BfModule.cpp 928 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250
  1. //#define USE_THUNKED_MddLLOC..
  2. #include "BeefySysLib/util/AllocDebug.h"
  3. #pragma warning(disable:4996)
  4. #pragma warning(push) // 6
  5. #include "BfCompiler.h"
  6. #include "BfSystem.h"
  7. #include "BfParser.h"
  8. #include "BfCodeGen.h"
  9. #include "BfExprEvaluator.h"
  10. #include "../Backend/BeLibManger.h"
  11. #include "BfConstResolver.h"
  12. #include "BfMangler.h"
  13. #include "BeefySysLib/util/PerfTimer.h"
  14. #include "BeefySysLib/util/BeefPerf.h"
  15. #include "BeefySysLib/util/StackHelper.h"
  16. #include "BfSourceClassifier.h"
  17. #include "BfAutoComplete.h"
  18. #include "BfDemangler.h"
  19. #include "BfResolvePass.h"
  20. #include "BfFixits.h"
  21. #include "BfIRCodeGen.h"
  22. #include "BfDefBuilder.h"
  23. #include "BfDeferEvalChecker.h"
  24. #include "CeMachine.h"
  25. #include "CeDebugger.h"
  26. #include <fcntl.h>
  27. #include <time.h>
  28. #pragma warning (disable:4267)
  29. //#include "llvm/Support/Compiler.h"
  30. //#include "llvm/IR/IRBuilder.h"
  31. //#include "llvm/IR/Type.h"
  32. #include "llvm/IR/DIBuilder.h"
  33. //#include "llvm/IR/DebugInfo.h"
  34. //#include "llvm/IR/Argument.h"
  35. //#include "llvm/IR/Constants.h"
  36. #pragma warning(pop)
  37. //////////////////////////////////////////////////////////////////////////
  38. static bool gDebugStuff = false;
  39. USING_NS_BF;
  40. //////////////////////////////////////////////////////////////////////////
  41. void BfLocalVariable::Init()
  42. {
  43. if (mResolvedType->IsValuelessType())
  44. {
  45. mAssignedKind = BfLocalVarAssignKind_Unconditional;
  46. return;
  47. }
  48. if (mAssignedKind != BfLocalVarAssignKind_None)
  49. return;
  50. bool isStruct = mResolvedType->IsStruct();
  51. if (mResolvedType->IsRef())
  52. isStruct = mResolvedType->GetUnderlyingType()->IsStruct();
  53. if ((isStruct) || ((mIsThis) && (mResolvedType->IsStructOrStructPtr())))
  54. {
  55. auto resolvedTypeRef = mResolvedType;
  56. if ((resolvedTypeRef->IsPointer()) || (resolvedTypeRef->IsRef()))
  57. resolvedTypeRef = resolvedTypeRef->GetUnderlyingType();
  58. auto typeInstance = resolvedTypeRef->ToTypeInstance();
  59. mUnassignedFieldFlags = (1 << typeInstance->mMergedFieldDataCount) - 1;
  60. if ((mIsThis) && (typeInstance->mBaseType != NULL))
  61. {
  62. // Base ctor is responsible for initializing its own fields
  63. mUnassignedFieldFlags &= ~(((int64)1 << typeInstance->mBaseType->mMergedFieldDataCount) - 1);
  64. }
  65. if (mUnassignedFieldFlags == 0)
  66. mAssignedKind = BfLocalVarAssignKind_Unconditional;
  67. }
  68. else
  69. {
  70. mUnassignedFieldFlags = 1;
  71. }
  72. }
  73. BfLocalMethod::~BfLocalMethod()
  74. {
  75. BfLogSys(mSystem, "~BfLocalMethod %p\n", this);
  76. if (mMethodDeclaration != NULL)
  77. {
  78. mSource->mRefCount--;
  79. BF_ASSERT(mSource->mRefCount >= 0);
  80. }
  81. delete mMethodInstanceGroup;
  82. delete mMethodDef;
  83. }
  84. void BfLocalMethod::Dispose()
  85. {
  86. if (mMethodInstanceGroup == NULL)
  87. return;
  88. if (mMethodInstanceGroup->mDefault != NULL)
  89. mMethodInstanceGroup->mDefault->Dispose();
  90. if (mMethodInstanceGroup->mMethodSpecializationMap != NULL)
  91. {
  92. for (auto& kv : *mMethodInstanceGroup->mMethodSpecializationMap)
  93. kv.mValue->Dispose();
  94. }
  95. }
  96. void BfDeferredLocalAssignData::ExtendFrom(BfDeferredLocalAssignData* outerLocalAssignData, bool doChain)
  97. {
  98. mIsChained = doChain;
  99. if (outerLocalAssignData == NULL)
  100. return;
  101. mChainedAssignData = outerLocalAssignData;
  102. if (!doChain)
  103. {
  104. outerLocalAssignData->BreakExtendChain();
  105. mAssignedLocals = outerLocalAssignData->mAssignedLocals;
  106. }
  107. mVarIdBarrier = outerLocalAssignData->mVarIdBarrier;
  108. }
  109. // The "extend chain" is broken when we have a conditional where the variable may not be defined after the block.
  110. // IE: "a" will be defined after the following, but "b" will not necessarily be defined.
  111. // if ((GetValue(out a)) && (GetValue(out b)) {}
  112. void BfDeferredLocalAssignData::BreakExtendChain()
  113. {
  114. if (!mIsChained)
  115. return;
  116. mIsChained = false;
  117. if (mChainedAssignData == NULL)
  118. return;
  119. mChainedAssignData->BreakExtendChain();
  120. mAssignedLocals = mChainedAssignData->mAssignedLocals;
  121. }
  122. void BfDeferredLocalAssignData::SetIntersection(const BfDeferredLocalAssignData& otherLocalAssignData)
  123. {
  124. BreakExtendChain();
  125. if (otherLocalAssignData.mLeftBlockUncond)
  126. {
  127. // Intersection of self and infinity is self
  128. }
  129. else if (mLeftBlockUncond)
  130. {
  131. // Intersection of infinity and other is other
  132. mAssignedLocals = otherLocalAssignData.mAssignedLocals;
  133. }
  134. else
  135. {
  136. for (int i = 0; i < (int)mAssignedLocals.size(); )
  137. {
  138. auto& local = mAssignedLocals[i];
  139. bool wantRemove = true;
  140. bool foundOtherFields = false;
  141. for (auto& otherLocalAssignData : otherLocalAssignData.mAssignedLocals)
  142. {
  143. if (otherLocalAssignData.mLocalVar == local.mLocalVar)
  144. {
  145. if ((otherLocalAssignData.mLocalVarField == local.mLocalVarField) || (otherLocalAssignData.mLocalVarField == -1))
  146. {
  147. if (otherLocalAssignData.mAssignKind == BfLocalVarAssignKind_Conditional)
  148. local.mAssignKind = BfLocalVarAssignKind_Conditional;
  149. wantRemove = false;
  150. }
  151. else
  152. foundOtherFields = true;
  153. }
  154. }
  155. if ((wantRemove) && (foundOtherFields))
  156. {
  157. for (auto& otherLocalAssignData : otherLocalAssignData.mAssignedLocals)
  158. {
  159. if (otherLocalAssignData.mLocalVar == local.mLocalVar)
  160. {
  161. mAssignedLocals.Add(otherLocalAssignData);
  162. }
  163. }
  164. }
  165. if (wantRemove)
  166. {
  167. mAssignedLocals.RemoveAt(i);
  168. }
  169. else
  170. i++;
  171. }
  172. }
  173. mHadFallthrough = mHadFallthrough && otherLocalAssignData.mHadFallthrough;
  174. mLeftBlockUncond = mLeftBlockUncond && otherLocalAssignData.mLeftBlockUncond;
  175. }
  176. void BfDeferredLocalAssignData::Validate() const
  177. {
  178. for (auto var : mAssignedLocals)
  179. {
  180. BF_ASSERT((uintptr)var.mLocalVar->mName.length() < 100000);
  181. }
  182. }
  183. void BfDeferredLocalAssignData::SetUnion(const BfDeferredLocalAssignData& otherLocalAssignData)
  184. {
  185. BreakExtendChain();
  186. Validate();
  187. otherLocalAssignData.Validate();
  188. auto otherItr = otherLocalAssignData.mAssignedLocals.begin();
  189. while (otherItr != otherLocalAssignData.mAssignedLocals.end())
  190. {
  191. if (!mAssignedLocals.Contains(*otherItr))
  192. mAssignedLocals.push_back(*otherItr);
  193. ++otherItr;
  194. }
  195. mHadFallthrough = mHadFallthrough || otherLocalAssignData.mHadFallthrough;
  196. mLeftBlockUncond = mLeftBlockUncond || otherLocalAssignData.mLeftBlockUncond;
  197. }
  198. BfMethodState::~BfMethodState()
  199. {
  200. BF_ASSERT(mPendingNullConditional == NULL);
  201. if (mPrevMethodState != NULL)
  202. {
  203. BF_ASSERT(mCurAccessId == 1);
  204. BF_ASSERT(mCurLocalVarId <= 0);
  205. }
  206. for (auto local : mLocals)
  207. {
  208. if (local->mIsBumpAlloc)
  209. local->~BfLocalVariable();
  210. else
  211. delete local;
  212. }
  213. for (auto& kv : mLambdaCache)
  214. delete kv.mValue;
  215. }
  216. BfMethodState* BfMethodState::GetMethodStateForLocal(BfLocalVariable* localVar)
  217. {
  218. auto checkMethodState = this;
  219. while (checkMethodState != NULL)
  220. {
  221. if ((localVar->mLocalVarIdx < checkMethodState->mLocals.size()) &&
  222. (checkMethodState->mLocals[localVar->mLocalVarIdx] == localVar))
  223. return checkMethodState;
  224. checkMethodState = checkMethodState->mPrevMethodState;
  225. }
  226. BF_FATAL("Failed to find method state for localvar");
  227. return NULL;
  228. }
  229. void BfMethodState::LocalDefined(BfLocalVariable* localVar, int fieldIdx, BfLocalVarAssignKind assignKind, bool isFromDeferredAssignData)
  230. {
  231. auto localVarMethodState = GetMethodStateForLocal(localVar);
  232. if (localVarMethodState != this)
  233. {
  234. return;
  235. }
  236. if (localVar->mAssignedKind == BfLocalVarAssignKind_None)
  237. {
  238. BfDeferredLocalAssignData* ifDeferredLocalAssignData = NULL;
  239. // 'a' is always defined, but 'b' isn't:
  240. // if (Check(out a) || Check(out b)) { } int z = a;
  241. auto deferredLocalAssignData = mDeferredLocalAssignData;
  242. if ((deferredLocalAssignData != NULL) &&
  243. (deferredLocalAssignData->mIsIfCondition) &&
  244. (!deferredLocalAssignData->mIfMayBeSkipped))
  245. {
  246. ifDeferredLocalAssignData = deferredLocalAssignData;
  247. deferredLocalAssignData = deferredLocalAssignData->mChainedAssignData;
  248. }
  249. while ((deferredLocalAssignData != NULL) &&
  250. ((deferredLocalAssignData->mIsChained) || (deferredLocalAssignData->mIsUnconditional)))
  251. deferredLocalAssignData = deferredLocalAssignData->mChainedAssignData;
  252. if (assignKind == BfLocalVarAssignKind_None)
  253. assignKind = ((deferredLocalAssignData != NULL) && (deferredLocalAssignData->mLeftBlock)) ? BfLocalVarAssignKind_Conditional : BfLocalVarAssignKind_Unconditional;
  254. if (localVar->mAssignedKind >= assignKind)
  255. {
  256. // Leave it alone
  257. }
  258. else if ((deferredLocalAssignData == NULL) || (localVar->mLocalVarId >= deferredLocalAssignData->mVarIdBarrier))
  259. {
  260. if (fieldIdx >= 0)
  261. {
  262. localVar->mUnassignedFieldFlags &= ~((int64)1 << fieldIdx);
  263. if (localVar->mResolvedType->IsUnion())
  264. {
  265. // We need more 'smarts' to determine assignment of unions
  266. localVar->mUnassignedFieldFlags = 0;
  267. }
  268. if (localVar->mUnassignedFieldFlags == 0)
  269. {
  270. if (localVar->mAssignedKind == BfLocalVarAssignKind_None)
  271. localVar->mAssignedKind = assignKind;
  272. }
  273. }
  274. else
  275. {
  276. localVar->mAssignedKind = assignKind;
  277. }
  278. }
  279. else
  280. {
  281. BF_ASSERT(deferredLocalAssignData->mVarIdBarrier != -1);
  282. BfAssignedLocal defineVal = {localVar, fieldIdx, assignKind};
  283. if (!deferredLocalAssignData->Contains(defineVal))
  284. deferredLocalAssignData->mAssignedLocals.push_back(defineVal);
  285. if (ifDeferredLocalAssignData != NULL)
  286. {
  287. if (!ifDeferredLocalAssignData->Contains(defineVal))
  288. ifDeferredLocalAssignData->mAssignedLocals.push_back(defineVal);
  289. }
  290. }
  291. }
  292. localVar->mWrittenToId = GetRootMethodState()->mCurAccessId++;
  293. }
  294. void BfMethodState::ApplyDeferredLocalAssignData(const BfDeferredLocalAssignData& deferredLocalAssignData)
  295. {
  296. BF_ASSERT(&deferredLocalAssignData != mDeferredLocalAssignData);
  297. if (deferredLocalAssignData.mLeftBlockUncond)
  298. {
  299. for (int localIdx = 0; localIdx < (int)mLocals.size(); localIdx++)
  300. {
  301. auto localDef = mLocals[localIdx];
  302. if (localDef->mAssignedKind == BfLocalVarAssignKind_None)
  303. {
  304. bool hadAssignment = false;
  305. if (mDeferredLocalAssignData != NULL)
  306. {
  307. for (auto& entry : mDeferredLocalAssignData->mAssignedLocals)
  308. if (entry.mLocalVar == localDef)
  309. hadAssignment = true;
  310. }
  311. if (!hadAssignment)
  312. {
  313. LocalDefined(localDef);
  314. }
  315. }
  316. }
  317. }
  318. else
  319. {
  320. for (auto& assignedLocal : deferredLocalAssignData.mAssignedLocals)
  321. {
  322. LocalDefined(assignedLocal.mLocalVar, assignedLocal.mLocalVarField, assignedLocal.mAssignKind, true);
  323. }
  324. }
  325. }
  326. void BfMethodState::Reset()
  327. {
  328. mHeadScope.mDeferredCallEntries.DeleteAll();
  329. }
  330. //////////////////////////////////////////////////////////////////////////
  331. void BfAmbiguityContext::Add(int id, BfTypeInterfaceEntry* interfaceEntry, int methodIdx, BfMethodInstance* candidateA, BfMethodInstance* candidateB)
  332. {
  333. Entry* entry = NULL;
  334. if (mEntries.TryAdd(id, NULL, &entry))
  335. {
  336. entry->mInterfaceEntry = interfaceEntry;
  337. entry->mMethodIdx = methodIdx;
  338. }
  339. if (!entry->mCandidates.Contains(candidateA))
  340. entry->mCandidates.push_back(candidateA);
  341. if (!entry->mCandidates.Contains(candidateB))
  342. entry->mCandidates.push_back(candidateB);
  343. }
  344. void BfAmbiguityContext::Remove(int id)
  345. {
  346. mEntries.Remove(id);
  347. }
  348. void BfAmbiguityContext::Finish()
  349. {
  350. for (auto& entryPair : mEntries)
  351. {
  352. int id = entryPair.mKey;
  353. auto entry = &entryPair.mValue;
  354. if (id >= 0)
  355. {
  356. auto declMethodInstance = mTypeInstance->mVirtualMethodTable[id].mDeclaringMethod;
  357. auto error = mModule->Fail(StrFormat("Method '%s' has ambiguous overrides", mModule->MethodToString(declMethodInstance).c_str()), declMethodInstance->mMethodDef->GetRefNode());
  358. if (error != NULL)
  359. {
  360. for (auto candidate : entry->mCandidates)
  361. {
  362. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' is a candidate",
  363. mModule->MethodToString(candidate, (BfMethodNameFlags)(BfMethodNameFlag_ResolveGenericParamNames | BfMethodNameFlag_IncludeReturnType)).c_str()), candidate->mMethodDef->GetRefNode());
  364. }
  365. }
  366. }
  367. else
  368. {
  369. auto iMethodInst = entry->mInterfaceEntry->mInterfaceType->mMethodInstanceGroups[entry->mMethodIdx].mDefault;
  370. auto error = mModule->Fail(StrFormat("Interface method '%s' has ambiguous implementations", mModule->MethodToString(iMethodInst).c_str()), entry->mInterfaceEntry->mDeclaringType->GetRefNode());
  371. if (error != NULL)
  372. {
  373. for (auto candidate : entry->mCandidates)
  374. {
  375. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' is a candidate",
  376. mModule->MethodToString(candidate, (BfMethodNameFlags)(BfMethodNameFlag_ResolveGenericParamNames | BfMethodNameFlag_IncludeReturnType)).c_str()), candidate->mMethodDef->GetRefNode());
  377. }
  378. }
  379. }
  380. }
  381. mEntries.Clear();
  382. }
  383. //////////////////////////////////////////////////////////////////////////
  384. class HasAppendAllocVisitor : BfElementVisitor
  385. {
  386. public:
  387. bool mHas;
  388. public:
  389. HasAppendAllocVisitor()
  390. {
  391. mHas = false;
  392. }
  393. void Visit(BfObjectCreateExpression* objCreateExpr)
  394. {
  395. if (auto newToken = BfNodeDynCast<BfTokenNode>(objCreateExpr->mNewNode))
  396. {
  397. if (newToken->GetToken() == BfToken_Append)
  398. {
  399. mHas = true;
  400. }
  401. }
  402. }
  403. bool HasAppendAlloc(BfAstNode* node)
  404. {
  405. mHas = false;
  406. VisitChild(node);
  407. return mHas;
  408. }
  409. };
  410. class AppendAllocVisitor : public BfStructuralVisitor
  411. {
  412. public:
  413. BfModule* mModule;
  414. HasAppendAllocVisitor mHasAppendAllocVisitor;
  415. BfTypedValue mConstAccum;
  416. bool mFailed;
  417. bool mIsFirstConstPass;
  418. bool mHasAppendWantMark;
  419. int mCurAppendAlign;
  420. public:
  421. AppendAllocVisitor()
  422. {
  423. mFailed = false;
  424. mIsFirstConstPass = false;
  425. mHasAppendWantMark = false;
  426. mCurAppendAlign = 1;
  427. }
  428. void EmitAppendAlign(int align, int sizeMultiple = 0)
  429. {
  430. if (align <= 1)
  431. return;
  432. if (mIsFirstConstPass)
  433. mModule->mCurMethodInstance->mAppendAllocAlign = BF_MAX((int)mModule->mCurMethodInstance->mAppendAllocAlign, align);
  434. if (sizeMultiple == 0)
  435. sizeMultiple = align;
  436. if (mCurAppendAlign == 0)
  437. mCurAppendAlign = sizeMultiple;
  438. else
  439. {
  440. if (sizeMultiple % align == 0)
  441. mCurAppendAlign = align;
  442. else
  443. mCurAppendAlign = sizeMultiple % align;
  444. }
  445. BF_ASSERT(mCurAppendAlign > 0);
  446. if (mConstAccum)
  447. {
  448. auto constant = mModule->mBfIRBuilder->GetConstant(mConstAccum.mValue);
  449. if (constant != NULL)
  450. mConstAccum.mValue = mModule->GetConstValue(BF_ALIGN(constant->mInt64, align));
  451. else
  452. BF_ASSERT(mIsFirstConstPass);
  453. return;
  454. }
  455. mModule->EmitAppendAlign(align, sizeMultiple);
  456. }
  457. void Visit(BfAstNode* astNode) override
  458. {
  459. mModule->VisitChild(astNode);
  460. }
  461. void DoObjectCreate(BfObjectCreateExpression* objCreateExpr, BfVariableDeclaration* variableDecl)
  462. {
  463. if (auto newToken = BfNodeDynCast<BfTokenNode>(objCreateExpr->mNewNode))
  464. {
  465. if (newToken->GetToken() == BfToken_Append)
  466. {
  467. //auto variableDecl = BfNodeDynCast<BfVariableDeclaration>(objCreateExpr->mParent);
  468. auto accumValuePtr = mModule->mCurMethodState->mRetVal.mValue;
  469. auto intPtrType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  470. BfArrayType* arrayType = NULL;
  471. bool isArrayAlloc = false;
  472. bool isRawArrayAlloc = objCreateExpr->mStarToken != NULL;
  473. SizedArray<BfIRValue, 2> dimLengthVals;
  474. BfType* origResolvedTypeRef = NULL;
  475. if (auto dotTypeRef = BfNodeDynCast<BfDotTypeReference>(objCreateExpr->mTypeRef))
  476. {
  477. if (variableDecl != NULL)
  478. {
  479. origResolvedTypeRef = mModule->ResolveTypeRef(variableDecl->mTypeRef, BfPopulateType_Data, BfResolveTypeRefFlag_NoResolveGenericParam);
  480. if (origResolvedTypeRef->IsObject())
  481. {
  482. if (origResolvedTypeRef->IsArray())
  483. {
  484. arrayType = (BfArrayType*)origResolvedTypeRef;
  485. origResolvedTypeRef = origResolvedTypeRef->GetUnderlyingType();
  486. isArrayAlloc = true;
  487. }
  488. }
  489. else if (origResolvedTypeRef->IsPointer())
  490. {
  491. origResolvedTypeRef = origResolvedTypeRef->GetUnderlyingType();
  492. }
  493. }
  494. }
  495. else if (auto arrayTypeRef = BfNodeDynCast<BfArrayTypeRef>(objCreateExpr->mTypeRef))
  496. {
  497. isArrayAlloc = true;
  498. bool handled = false;
  499. if (auto dotTypeRef = BfNodeDynCast<BfDotTypeReference>(arrayTypeRef->mElementType))
  500. {
  501. if (variableDecl->mTypeRef != NULL)
  502. {
  503. auto variableType = mModule->ResolveTypeRef(variableDecl->mTypeRef);
  504. if (variableType != NULL)
  505. {
  506. if (variableType->IsArray())
  507. origResolvedTypeRef = variableType->GetUnderlyingType();
  508. }
  509. handled = true;
  510. }
  511. }
  512. if (!handled)
  513. {
  514. origResolvedTypeRef = mModule->ResolveTypeRef(arrayTypeRef->mElementType, BfPopulateType_Declaration);
  515. }
  516. if (origResolvedTypeRef == NULL)
  517. {
  518. mModule->AssertErrorState();
  519. return;
  520. }
  521. int dimensions = 1;
  522. if (arrayTypeRef->mParams.size() != 0)
  523. {
  524. auto intType = mModule->ResolveTypeDef(mModule->mSystem->mTypeIntPtr);
  525. for (auto arg : arrayTypeRef->mParams)
  526. {
  527. if (auto tokenNode = BfNodeDynCastExact<BfTokenNode>(arg))
  528. {
  529. if (tokenNode->GetToken() == BfToken_Comma)
  530. {
  531. if (isRawArrayAlloc)
  532. {
  533. mModule->Fail("Sized arrays cannot be multidimensional", tokenNode);
  534. continue;
  535. }
  536. dimensions++;
  537. continue;
  538. }
  539. }
  540. auto expr = BfNodeDynCast<BfExpression>(arg);
  541. if ((isRawArrayAlloc) && (!dimLengthVals.IsEmpty()))
  542. {
  543. mModule->CreateValueFromExpression(expr, intType);
  544. continue;
  545. }
  546. BfTypedValue dimLength;
  547. if (expr == NULL)
  548. {
  549. // Not specified
  550. dimLengthVals.push_back(BfIRValue());
  551. continue;
  552. }
  553. if (arg != NULL)
  554. dimLength = mModule->CreateValueFromExpression(expr, intType);
  555. if (!dimLength)
  556. {
  557. dimLength = mModule->GetDefaultTypedValue(intType);
  558. }
  559. dimLengthVals.push_back(dimLength.mValue);
  560. }
  561. }
  562. if (!isRawArrayAlloc)
  563. arrayType = mModule->CreateArrayType(origResolvedTypeRef, dimensions);
  564. }
  565. if (origResolvedTypeRef == NULL)
  566. origResolvedTypeRef = mModule->ResolveTypeRef(objCreateExpr->mTypeRef, BfPopulateType_Data, BfResolveTypeRefFlag_NoResolveGenericParam);
  567. if (origResolvedTypeRef == NULL)
  568. {
  569. mModule->AssertErrorState();
  570. return;
  571. }
  572. if (origResolvedTypeRef->WantsGCMarking())
  573. mHasAppendWantMark = true;
  574. bool isGenericParam = origResolvedTypeRef->IsGenericParam();
  575. auto resolvedTypeRef = origResolvedTypeRef;
  576. auto resultType = resolvedTypeRef;
  577. BfIRValue sizeValue;
  578. int curAlign = 0;
  579. if (isArrayAlloc)
  580. {
  581. int dimensions = 1;
  582. if (arrayType != NULL)
  583. dimensions = arrayType->mDimensions;
  584. bool sizeFailed = false;
  585. //
  586. {
  587. BfAstNode* initNode = objCreateExpr;
  588. for (int dim = 0; dim < dimensions; dim++)
  589. {
  590. BfAstNode* nextInitNode = NULL;
  591. int dimSize = -1;
  592. if (initNode == objCreateExpr)
  593. {
  594. dimSize = objCreateExpr->mArguments.size();
  595. if (!objCreateExpr->mArguments.IsEmpty())
  596. nextInitNode = objCreateExpr->mArguments[0];
  597. }
  598. else if (auto tupleNode = BfNodeDynCast<BfTupleExpression>(initNode))
  599. {
  600. dimSize = (int)tupleNode->mCommas.size() + 1;
  601. }
  602. if (dimSize >= 0)
  603. {
  604. if (dim >= dimLengthVals.size())
  605. dimLengthVals.Add(mModule->GetConstValue(dimSize));
  606. }
  607. else
  608. {
  609. sizeFailed = true;
  610. }
  611. }
  612. }
  613. BfIRValue allocCount;
  614. if (!sizeFailed)
  615. {
  616. if (!dimLengthVals.IsEmpty())
  617. {
  618. allocCount = dimLengthVals[0];
  619. for (int dim = 1; dim < (int)dimLengthVals.size(); dim++)
  620. allocCount = mModule->mBfIRBuilder->CreateMul(allocCount, dimLengthVals[dim]);
  621. }
  622. }
  623. if (!allocCount)
  624. {
  625. mFailed = true;
  626. if (!mIsFirstConstPass)
  627. {
  628. if (!mConstAccum)
  629. mModule->Fail("Unable to determine append alloc size", objCreateExpr->mNewNode);
  630. return;
  631. }
  632. }
  633. mModule->PopulateType(resultType, resultType->IsValueType() ? BfPopulateType_Data : BfPopulateType_Declaration);
  634. if (isRawArrayAlloc)
  635. {
  636. curAlign = resultType->mAlign;
  637. EmitAppendAlign(resultType->mAlign);
  638. sizeValue = mModule->mBfIRBuilder->CreateMul(mModule->GetConstValue(resultType->GetStride()), allocCount);
  639. }
  640. else
  641. {
  642. if (arrayType == NULL)
  643. arrayType = mModule->CreateArrayType(resultType, 1);
  644. // Array is a special case where the total size isn't aligned with mAlign
  645. // since we add arbitrary elements to the end without padding the end to align
  646. EmitAppendAlign(arrayType->mAlign, resultType->mAlign);
  647. curAlign = arrayType->mAlign;
  648. auto firstElementField = &arrayType->mFieldInstances.back();
  649. int arrayClassSize = arrayType->mInstSize - firstElementField->mDataSize;
  650. sizeValue = mModule->GetConstValue(arrayClassSize);
  651. BfIRValue elementDataSize = mModule->mBfIRBuilder->CreateMul(mModule->GetConstValue(resultType->GetStride()), allocCount);
  652. sizeValue = mModule->mBfIRBuilder->CreateAdd(sizeValue, elementDataSize);
  653. }
  654. }
  655. else
  656. {
  657. auto typeInst = resultType->ToTypeInstance();
  658. if (typeInst != NULL)
  659. {
  660. curAlign = typeInst->mInstAlign;
  661. EmitAppendAlign(typeInst->mInstAlign, typeInst->mInstSize);
  662. sizeValue = mModule->GetConstValue(typeInst->mInstSize);
  663. }
  664. else
  665. {
  666. curAlign = resultType->mAlign;
  667. EmitAppendAlign(resultType->mAlign, resultType->mSize);
  668. sizeValue = mModule->GetConstValue(resultType->mSize);
  669. }
  670. BfTypedValue emtpyThis(mModule->mBfIRBuilder->GetFakeVal(), resultType, (typeInst == NULL) || (typeInst->IsComposite()));
  671. BfExprEvaluator exprEvaluator(mModule);
  672. SetAndRestoreValue<bool> prevNoBind(exprEvaluator.mNoBind, exprEvaluator.mNoBind || isGenericParam);
  673. BfFunctionBindResult bindResult;
  674. bindResult.mWantsArgs = true;
  675. exprEvaluator.mFunctionBindResult = &bindResult;
  676. SizedArray<BfExpression*, 8> copiedArgs;
  677. for (BfExpression* arg : objCreateExpr->mArguments)
  678. copiedArgs.push_back(arg);
  679. BfSizedArray<BfExpression*> sizedArgExprs(copiedArgs);
  680. BfResolvedArgs argValues(&sizedArgExprs);
  681. if (typeInst != NULL)
  682. {
  683. exprEvaluator.ResolveArgValues(argValues);
  684. exprEvaluator.MatchConstructor(objCreateExpr->mTypeRef, objCreateExpr, emtpyThis, typeInst, argValues, false, BfMethodGenericArguments(), BfAllowAppendKind_Infer);
  685. }
  686. exprEvaluator.mFunctionBindResult = NULL;
  687. if (bindResult.mMethodInstance != NULL)
  688. {
  689. if (bindResult.mMethodInstance->mMethodDef->HasAppend())
  690. {
  691. auto calcAppendArgs = bindResult.mIRArgs;
  692. BF_ASSERT(calcAppendArgs[0].IsFake());
  693. calcAppendArgs.RemoveRange(0, 2); // Remove 'this' and 'appendIdx'
  694. auto calcAppendMethodModule = mModule->GetMethodInstanceAtIdx(bindResult.mMethodInstance->GetOwner(), bindResult.mMethodInstance->mMethodDef->mIdx + 1, BF_METHODNAME_CALCAPPEND);
  695. auto subDependSize = mModule->TryConstCalcAppend(calcAppendMethodModule.mMethodInstance, calcAppendArgs);
  696. if (calcAppendMethodModule.mMethodInstance->mAppendAllocAlign > 0)
  697. {
  698. EmitAppendAlign(calcAppendMethodModule.mMethodInstance->mAppendAllocAlign);
  699. BF_ASSERT(calcAppendMethodModule.mMethodInstance->mEndingAppendAllocAlign > -1);
  700. mModule->mCurMethodState->mCurAppendAlign = BF_MAX(calcAppendMethodModule.mMethodInstance->mEndingAppendAllocAlign, 0);
  701. }
  702. curAlign = std::max(curAlign, (int)calcAppendMethodModule.mMethodInstance->mAppendAllocAlign);
  703. if ((!subDependSize) && (!mConstAccum))
  704. {
  705. BF_ASSERT(calcAppendMethodModule.mFunc);
  706. subDependSize = exprEvaluator.CreateCall(objCreateExpr, calcAppendMethodModule.mMethodInstance, calcAppendMethodModule.mFunc, false, calcAppendArgs);
  707. BF_ASSERT(subDependSize.mType == mModule->GetPrimitiveType(BfTypeCode_IntPtr));
  708. }
  709. if (subDependSize)
  710. sizeValue = mModule->mBfIRBuilder->CreateAdd(sizeValue, subDependSize.mValue);
  711. else
  712. mFailed = true;
  713. }
  714. }
  715. }
  716. if (sizeValue)
  717. {
  718. if (mConstAccum)
  719. {
  720. if (!sizeValue.IsConst())
  721. {
  722. mFailed = true;
  723. if (!mIsFirstConstPass)
  724. return;
  725. }
  726. mConstAccum.mValue = mModule->mBfIRBuilder->CreateAdd(sizeValue, mConstAccum.mValue);
  727. }
  728. else
  729. {
  730. auto prevVal = mModule->mBfIRBuilder->CreateAlignedLoad(accumValuePtr, intPtrType->mAlign);
  731. auto addedVal = mModule->mBfIRBuilder->CreateAdd(sizeValue, prevVal);
  732. mModule->mBfIRBuilder->CreateAlignedStore(addedVal, accumValuePtr, intPtrType->mAlign);
  733. }
  734. }
  735. }
  736. }
  737. }
  738. void Visit(BfObjectCreateExpression* objCreateExpr) override
  739. {
  740. DoObjectCreate(objCreateExpr, NULL);
  741. }
  742. void Visit(BfVariableDeclaration* varDecl) override
  743. {
  744. if (mHasAppendAllocVisitor.HasAppendAlloc(varDecl))
  745. {
  746. if (auto objectCreateExpr = BfNodeDynCast<BfObjectCreateExpression>(varDecl->mInitializer))
  747. DoObjectCreate(objectCreateExpr, varDecl);
  748. else
  749. VisitChild(varDecl->mInitializer);
  750. if (varDecl->mNameNode != NULL)
  751. {
  752. BfLocalVariable* localDef = new BfLocalVariable();
  753. localDef->mName = varDecl->mNameNode->ToString();
  754. localDef->mNameNode = BfNodeDynCast<BfIdentifierNode>(varDecl->mNameNode);
  755. localDef->mResolvedType = mModule->GetPrimitiveType(BfTypeCode_None);
  756. localDef->mIsReadOnly = true;
  757. localDef->mParamFailed = true;
  758. localDef->mReadFromId = 0;
  759. mModule->AddLocalVariableDef(localDef);
  760. }
  761. }
  762. else
  763. {
  764. mModule->Visit(varDecl);
  765. }
  766. }
  767. void Visit(BfExpressionStatement* exprStatement) override
  768. {
  769. VisitChild(exprStatement->mExpression);
  770. }
  771. // void Visit(BfIfStatement* ifStmt) override
  772. // {
  773. // mModule->DoIfStatement(ifStmt,
  774. // mHasAppendAllocVisitor.HasAppendAlloc(ifStmt->mTrueStatement),
  775. // mHasAppendAllocVisitor.HasAppendAlloc(ifStmt->mFalseStatement));
  776. // }
  777. void Visit(BfBlock* block) override
  778. {
  779. if (!mHasAppendAllocVisitor.HasAppendAlloc(block))
  780. return;
  781. int appendAllocIdx = -1;
  782. for (int childIdx = block->mChildArr.mSize - 1; childIdx >= 0; childIdx--)
  783. {
  784. auto child = block->mChildArr.mVals[childIdx];
  785. if (mHasAppendAllocVisitor.HasAppendAlloc(child))
  786. {
  787. for (int emitIdx = 0; emitIdx <= childIdx; emitIdx++)
  788. {
  789. auto emitChild = block->mChildArr.mVals[emitIdx];
  790. mModule->UpdateSrcPos(emitChild);
  791. VisitChild(emitChild);
  792. if ((mFailed) && (!mIsFirstConstPass))
  793. break;
  794. }
  795. break;
  796. }
  797. }
  798. }
  799. };
  800. //////////////////////////////////////////////////////////////////////////
  801. BfModule* gLastCreatedModule = NULL;
  802. BfModule::BfModule(BfContext* context, const StringImpl& moduleName)
  803. {
  804. BfLogSys(context->mSystem, "BfModule::BFModule %p %s\n", this, moduleName.c_str());
  805. gLastCreatedModule = this;
  806. mContext = context;
  807. mModuleName = moduleName;
  808. if (!moduleName.empty())
  809. {
  810. StringT<256> upperModuleName = moduleName;
  811. MakeUpper(upperModuleName);
  812. mContext->mUsedModuleNames.Add(upperModuleName);
  813. }
  814. mAddedToCount = false;
  815. mParentModule = NULL;
  816. mNextAltModule = NULL;
  817. mBfIRBuilder = NULL;
  818. mWantsIRIgnoreWrites = false;
  819. mModuleOptions = NULL;
  820. mLastUsedRevision = -1;
  821. mUsedSlotCount = -1;
  822. mIsReified = true;
  823. mGeneratesCode = true;
  824. mReifyQueued = false;
  825. mIsSpecialModule = false;
  826. mIsComptimeModule = false;
  827. mIsScratchModule = false;
  828. mIsSpecializedMethodModuleRoot = false; // There may be mNextAltModules extending from this
  829. mHadBuildError = false;
  830. mHadBuildWarning = false;
  831. mIgnoreErrors = false;
  832. mHadIgnoredError = false;
  833. mIgnoreWarnings = false;
  834. mReportErrors = true;
  835. mIsInsideAutoComplete = false;
  836. mIsDeleting = false;
  837. mSkipInnerLookup = false;
  838. mIsHotModule = false;
  839. mSetIllegalSrcPosition = false;
  840. mNoResolveGenericParams = false;
  841. mWroteToLib = false;
  842. mContext = context;
  843. mCompiler = context->mCompiler;
  844. mSystem = mCompiler->mSystem;
  845. mProject = NULL;
  846. mCurMethodState = NULL;
  847. mAttributeState = NULL;
  848. mCurLocalMethodId = 0;
  849. mParentNodeEntry = NULL;
  850. mRevision = -1;
  851. mRebuildIdx = 0;
  852. mLastModuleWrittenRevision = 0;
  853. mIsModuleMutable = false;
  854. mExtensionCount = 0;
  855. mIncompleteMethodCount = 0;
  856. mOnDemandMethodCount = 0;
  857. mHasGenericMethods = false;
  858. mCurMethodInstance = NULL;
  859. mCurTypeInstance = NULL;
  860. mAwaitingInitFinish = false;
  861. mAwaitingFinish = false;
  862. mHasFullDebugInfo = false;
  863. mHadHotObjectWrites = false;
  864. for (int i = 0; i < BfBuiltInFuncType_Count; i++)
  865. mBuiltInFuncs[i] = BfIRFunction();
  866. BfLogSysM("Creating module %p: %s Reified: %d ResolveOnly: %d\n", this, mModuleName.c_str(), mIsReified, mCompiler->mIsResolveOnly);
  867. }
  868. void BfReportMemory();
  869. BfModule::~BfModule()
  870. {
  871. mRevision = -2;
  872. BfLogSysM("Deleting module %p: %s \n", this, mModuleName.c_str());
  873. if (!mIsDeleting)
  874. RemoveModuleData();
  875. }
  876. void BfModule::RemoveModuleData()
  877. {
  878. BF_ASSERT(!mIsDeleting);
  879. if (!mModuleName.empty())
  880. {
  881. // Note: module names not necessarily unique
  882. mContext->mUsedModuleNames.Remove(ToUpper(mModuleName));
  883. }
  884. CleanupFileInstances();
  885. delete mBfIRBuilder;
  886. mBfIRBuilder = NULL;
  887. //delete mCpu;
  888. for (auto prevModule : mPrevIRBuilders)
  889. delete prevModule;
  890. mPrevIRBuilders.Clear();
  891. for (auto& pairVal : mDeferredMethodCallData)
  892. delete pairVal.mValue;
  893. mDeferredMethodCallData.Clear();
  894. mDeferredMethodIds.Clear();
  895. for (auto& specModulePair : mSpecializedMethodModules)
  896. delete specModulePair.mValue;
  897. mSpecializedMethodModules.Clear();
  898. if (mNextAltModule != NULL)
  899. delete mNextAltModule;
  900. mNextAltModule = NULL;
  901. if (mModuleOptions != NULL)
  902. delete mModuleOptions;
  903. mModuleOptions = NULL;
  904. BfReportMemory();
  905. }
  906. void BfModule::Init(bool isFullRebuild)
  907. {
  908. mContext->mFinishedModuleWorkList.Remove(this);
  909. if ((mCompiler->mIsResolveOnly) && (this != mContext->mUnreifiedModule))
  910. BF_ASSERT(mIsReified);
  911. if (!mIsScratchModule)
  912. {
  913. mCompiler->mStats.mModulesStarted++;
  914. if (mIsReified)
  915. mCompiler->mStats.mReifiedModuleCount++;
  916. mAddedToCount = true;
  917. }
  918. mIsHotModule = (mProject != NULL) && (mCompiler->mOptions.mHotProject != NULL) && (mCompiler->mOptions.mHotProject->ContainsReference(mProject));
  919. mFuncReferences.Clear();
  920. mClassVDataRefs.Clear();
  921. mClassVDataExtRefs.Clear();
  922. //mTypeDataRefs.Clear();
  923. mDbgRawAllocDataRefs.Clear();
  924. CleanupFileInstances();
  925. mStaticFieldRefs.Clear();
  926. //mInterfaceSlotRefs.Clear();
  927. // If we are just doing an extension then the ownede types aren't rebuilt.
  928. // If we set mRevision then QueueMethodSpecializations wouldn't actually queue up required specializations
  929. // and we'd end up with link errors if the original module uniquely referred to any generic methods
  930. if (isFullRebuild)
  931. mRevision = mCompiler->mRevision;
  932. BF_ASSERT(mCurTypeInstance == NULL);
  933. mIsModuleMutable = true;
  934. BF_ASSERT((mBfIRBuilder == NULL) || (mCompiler->mIsResolveOnly));
  935. if (!mIsComptimeModule)
  936. {
  937. #ifdef _DEBUG
  938. EnsureIRBuilder(mCompiler->mLastAutocompleteModule == this);
  939. #else
  940. EnsureIRBuilder(false);
  941. #endif
  942. }
  943. mCurMethodState = NULL;
  944. mAwaitingInitFinish = true;
  945. mOnDemandMethodCount = 0;
  946. mAwaitingFinish = false;
  947. mHasForceLinkMarker = false;
  948. mUsedSlotCount = -1;
  949. }
  950. bool BfModule::WantsFinishModule()
  951. {
  952. return (mIncompleteMethodCount == 0) && (mOnDemandMethodCount == 0) && (!mHasGenericMethods) && (!mIsScratchModule) && (mExtensionCount == 0) && (mParentModule == NULL);
  953. }
  954. bool BfModule::IsHotCompile()
  955. {
  956. return mCompiler->IsHotCompile() && !mIsComptimeModule;
  957. }
  958. void BfModule::FinishInit()
  959. {
  960. BF_ASSERT(mAwaitingInitFinish);
  961. auto moduleOptions = GetModuleOptions();
  962. mBfIRBuilder->Start(mModuleName, mCompiler->mSystem->mPtrSize, IsOptimized());
  963. mBfIRBuilder->Module_SetTargetTriple(mCompiler->mOptions.mTargetTriple, mCompiler->mOptions.mTargetCPU);
  964. mBfIRBuilder->SetBackend(IsTargetingBeefBackend());
  965. if (moduleOptions.mOptLevel == BfOptLevel_OgPlus)
  966. {
  967. // Og+ requires debug info
  968. moduleOptions.mEmitDebugInfo = 1;
  969. }
  970. mHasFullDebugInfo = moduleOptions.mEmitDebugInfo == 1;
  971. if (mIsComptimeModule)
  972. mHasFullDebugInfo = true;
  973. if (((!mCompiler->mIsResolveOnly) && (!mIsScratchModule) && (moduleOptions.mEmitDebugInfo != 0) && (mIsReified)) ||
  974. (mIsComptimeModule))
  975. {
  976. mBfIRBuilder->DbgInit();
  977. }
  978. else
  979. mHasFullDebugInfo = false;
  980. if ((mBfIRBuilder->DbgHasInfo()) && (mModuleName != "") &&
  981. ((moduleOptions.mEmitDebugInfo != 0)))
  982. {
  983. if (mCompiler->mOptions.IsCodeView())
  984. {
  985. mBfIRBuilder->Module_AddModuleFlag("CodeView", 1);
  986. }
  987. else
  988. {
  989. mBfIRBuilder->Module_AddModuleFlag("Dwarf Version", 4);
  990. }
  991. mBfIRBuilder->Module_AddModuleFlag("Debug Info Version", 3);
  992. mDICompileUnit = mBfIRBuilder->DbgCreateCompileUnit(llvm::dwarf::DW_LANG_C_plus_plus, mModuleName, ".", "Beef Compiler 0.42.3", /*moduleOptions.mOptLevel > 0*/false, "", 0, !mHasFullDebugInfo);
  993. }
  994. mAwaitingInitFinish = false;
  995. }
  996. void BfModule::CalcGeneratesCode()
  997. {
  998. if ((!mIsReified) || (mIsScratchModule))
  999. {
  1000. mGeneratesCode = false;
  1001. return;
  1002. }
  1003. mGeneratesCode = false;
  1004. for (auto typeInst : mOwnedTypeInstances)
  1005. if (!typeInst->IsInterface())
  1006. mGeneratesCode = true;
  1007. }
  1008. void BfModule::ReifyModule()
  1009. {
  1010. BF_ASSERT((mCompiler->mCompileState != BfCompiler::CompileState_Unreified) && (mCompiler->mCompileState != BfCompiler::CompileState_VData));
  1011. BfLogSysM("ReifyModule %@ %s\n", this, mModuleName.c_str());
  1012. BF_ASSERT((this != mContext->mScratchModule) && (this != mContext->mUnreifiedModule));
  1013. mIsReified = true;
  1014. CalcGeneratesCode();
  1015. mReifyQueued = false;
  1016. StartNewRevision(RebuildKind_SkipOnDemandTypes, true);
  1017. mCompiler->mStats.mModulesReified++;
  1018. }
  1019. void BfModule::UnreifyModule()
  1020. {
  1021. BfLogSysM("UnreifyModule %p %s\n", this, mModuleName.c_str());
  1022. BF_ASSERT((this != mContext->mScratchModule) && (this != mContext->mUnreifiedModule));
  1023. mIsReified = false;
  1024. CalcGeneratesCode();
  1025. mReifyQueued = false;
  1026. StartNewRevision(RebuildKind_None, true);
  1027. mCompiler->mStats.mModulesUnreified++;
  1028. }
  1029. void BfModule::CleanupFileInstances()
  1030. {
  1031. for (auto& itr : mNamedFileInstanceMap)
  1032. {
  1033. BfLogSysM("FileInstance deleted: %p\n", itr.mValue);
  1034. delete itr.mValue;
  1035. }
  1036. mCurFilePosition.mFileInstance = NULL;//
  1037. mFileInstanceMap.Clear();
  1038. mNamedFileInstanceMap.Clear();
  1039. }
  1040. void BfModule::Cleanup()
  1041. {
  1042. CleanupFileInstances();
  1043. }
  1044. void BfModule::PrepareForIRWriting(BfTypeInstance* typeInst)
  1045. {
  1046. if (HasCompiledOutput())
  1047. {
  1048. // It's possible that the target's code hasn't changed but we're requesting a new generic method specialization
  1049. if ((!mIsModuleMutable) && (!typeInst->IsUnspecializedType()) && (!typeInst->mResolvingVarField))
  1050. {
  1051. StartExtension();
  1052. }
  1053. }
  1054. else
  1055. {
  1056. EnsureIRBuilder();
  1057. }
  1058. }
  1059. void BfModule::SetupIRBuilder(bool dbgVerifyCodeGen)
  1060. {
  1061. if (mIsScratchModule)
  1062. {
  1063. mBfIRBuilder->mIgnoreWrites = true;
  1064. BF_ASSERT(!dbgVerifyCodeGen);
  1065. }
  1066. #ifdef _DEBUG
  1067. if (mCompiler->mIsResolveOnly)
  1068. {
  1069. // For "deep" verification testing
  1070. /*if (!mIsSpecialModule)
  1071. dbgVerifyCodeGen = true;*/
  1072. // We only want to turn this off on smaller builds for testing
  1073. mBfIRBuilder->mIgnoreWrites = true;
  1074. if (dbgVerifyCodeGen)
  1075. mBfIRBuilder->mIgnoreWrites = false;
  1076. if (!mBfIRBuilder->mIgnoreWrites)
  1077. {
  1078. // The only purpose of not ignoring writes is so we can verify the codegen one instruction at a time
  1079. mBfIRBuilder->mDbgVerifyCodeGen = true;
  1080. }
  1081. }
  1082. else if (!mGeneratesCode)
  1083. {
  1084. mBfIRBuilder->mIgnoreWrites = true;
  1085. }
  1086. else
  1087. {
  1088. // We almost always want this to be 'false' unless we need need to be able to inspect the generated LLVM
  1089. // code as we walk the AST
  1090. //mBfIRBuilder->mDbgVerifyCodeGen = true;
  1091. if (
  1092. (mModuleName == "-")
  1093. //|| (mModuleName == "")
  1094. //|| (mModuleName == "Tests_FuncRefs")
  1095. )
  1096. mBfIRBuilder->mDbgVerifyCodeGen = true;
  1097. // Just for testing!
  1098. //mBfIRBuilder->mIgnoreWrites = true;
  1099. }
  1100. #else
  1101. if (mCompiler->mIsResolveOnly)
  1102. {
  1103. // Always ignore writes in resolveOnly for release builds
  1104. mBfIRBuilder->mIgnoreWrites = true;
  1105. }
  1106. else
  1107. {
  1108. // Just for memory testing! This breaks everything.
  1109. //mBfIRBuilder->mIgnoreWrites = true;
  1110. // For "deep" verification testing
  1111. //mBfIRBuilder->mDbgVerifyCodeGen = true;
  1112. }
  1113. #endif
  1114. mWantsIRIgnoreWrites = mBfIRBuilder->mIgnoreWrites;
  1115. }
  1116. void BfModule::EnsureIRBuilder(bool dbgVerifyCodeGen)
  1117. {
  1118. BF_ASSERT(!mIsDeleting);
  1119. if (mBfIRBuilder == NULL)
  1120. {
  1121. if ((!mIsScratchModule) && (!mAddedToCount))
  1122. {
  1123. mCompiler->mStats.mModulesStarted++;
  1124. mAddedToCount = true;
  1125. }
  1126. BF_ASSERT(mStaticFieldRefs.GetCount() == 0);
  1127. /*if (mCompiler->mIsResolveOnly)
  1128. BF_ASSERT(mIsResolveOnly);*/
  1129. mBfIRBuilder = new BfIRBuilder(this);
  1130. BfLogSysM("Created mBfIRBuilder %p in %p %s Reified: %d\n", mBfIRBuilder, this, mModuleName.c_str(), mIsReified);
  1131. SetupIRBuilder(dbgVerifyCodeGen);
  1132. }
  1133. }
  1134. BfIRValue BfModule::CreateForceLinkMarker(BfModule* module, String* outName)
  1135. {
  1136. String name = "FORCELINKMOD_" + module->mModuleName;
  1137. if (outName != NULL)
  1138. *outName = name;
  1139. auto markerType = GetPrimitiveType(BfTypeCode_Int8);
  1140. return mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapType(markerType), true, BfIRLinkageType_External, (module == this) ? mBfIRBuilder->CreateConst(BfTypeCode_Int8, 0) : BfIRValue(), name);
  1141. }
  1142. void BfModule::StartNewRevision(RebuildKind rebuildKind, bool force)
  1143. {
  1144. BP_ZONE("BfModule::StartNewRevision");
  1145. // The project MAY be deleted because disabling a project can cause types to be deleted which
  1146. // causes other types rebuild BEFORE they get deleted, which is okay (though wasteful)
  1147. //BF_ASSERT((mProject == NULL) || (!mProject->mDisabled));
  1148. if (mCompiler->mCompileState == BfCompiler::CompileState_Cleanup)
  1149. {
  1150. // Cleaning up local methods may cause some necessary NewRevisions
  1151. force = true;
  1152. }
  1153. // Already on new revision?
  1154. if ((mRevision == mCompiler->mRevision) && (!force))
  1155. return;
  1156. mHadBuildError = false;
  1157. mHadBuildWarning = false;
  1158. mExtensionCount = 0;
  1159. mRevision = mCompiler->mRevision;
  1160. mRebuildIdx++;
  1161. ClearModuleData(!force);
  1162. // Clear this here, not in ClearModuleData, so we preserve those references even after writing out module
  1163. if (rebuildKind != BfModule::RebuildKind_None) // Leave string pool refs for when we need to use things like [LinkName("")] methods bofore re-reification
  1164. {
  1165. mStringPoolRefs.Clear();
  1166. mUnreifiedStringPoolRefs.Clear();
  1167. }
  1168. mDllImportEntries.Clear();
  1169. mImportFileNames.Clear();
  1170. for (auto& pairVal : mDeferredMethodCallData)
  1171. delete pairVal.mValue;
  1172. mDeferredMethodCallData.Clear();
  1173. mDeferredMethodIds.Clear();
  1174. mModuleRefs.Clear();
  1175. mOutFileNames.Clear();
  1176. mTypeDataRefs.Clear();
  1177. mInterfaceSlotRefs.Clear();
  1178. if (rebuildKind == BfModule::RebuildKind_None)
  1179. {
  1180. for (auto& specPair : mSpecializedMethodModules)
  1181. {
  1182. auto specModule = specPair.mValue;
  1183. if (specModule->mIsReified != mIsReified)
  1184. {
  1185. if (mIsReified)
  1186. specModule->ReifyModule();
  1187. else
  1188. specModule->UnreifyModule();
  1189. }
  1190. }
  1191. }
  1192. else
  1193. {
  1194. for (auto& specPair : mSpecializedMethodModules)
  1195. {
  1196. auto specModule = specPair.mValue;
  1197. BfLogSysM("Setting module mIsDeleting %p due to parent module starting a new revision\n", specModule);
  1198. // This module is no longer needed
  1199. specModule->RemoveModuleData();
  1200. specModule->mIsDeleting = true;
  1201. mContext->mDeletingModules.Add(specModule);
  1202. }
  1203. }
  1204. mSpecializedMethodModules.Clear();
  1205. delete mNextAltModule;
  1206. mNextAltModule = NULL;
  1207. BF_ASSERT(mModuleOptions == NULL);
  1208. BfLogSysM("Mod:%p StartNewRevision: %s Revision: %d\n", this, mModuleName.c_str(), mRevision);
  1209. bool needsTypePopulated = false;
  1210. int oldOnDemandCount = 0;
  1211. // We don't have to rebuild types in the unspecialized module because there is no
  1212. // data that's needed -- their method instances are all NULL and the module
  1213. // doesn't get included in the build
  1214. if (this != mContext->mScratchModule)
  1215. {
  1216. for (int typeIdx = 0; typeIdx < (int)mOwnedTypeInstances.size(); typeIdx++)
  1217. {
  1218. auto typeInst = mOwnedTypeInstances[typeIdx];
  1219. if (!typeInst->IsDeleting())
  1220. {
  1221. typeInst->mIsReified = mIsReified;
  1222. if (rebuildKind != BfModule::RebuildKind_None)
  1223. {
  1224. if (typeInst->IsOnDemand())
  1225. {
  1226. // Changing config should require on demand types to be recreated, but reifying a module shouldn't cause the type to be deleted
  1227. if (rebuildKind == BfModule::RebuildKind_All)
  1228. mContext->DeleteType(typeInst);
  1229. else
  1230. {
  1231. RebuildMethods(typeInst);
  1232. }
  1233. }
  1234. else
  1235. //TODO: Why weren't we placing specialzied in purgatory here originally? This caused failed types to stick around too long
  1236. mContext->RebuildType(typeInst, false, false, true);
  1237. //mContext->RebuildType(typeInst, false, false, false);
  1238. }
  1239. else
  1240. {
  1241. auto _HandleMethod = [&](BfMethodInstance* methodInstance)
  1242. {
  1243. if ((methodInstance != NULL) && (methodInstance->mDeclModule != NULL))
  1244. methodInstance->mDeclModule = this;
  1245. };
  1246. for (auto& methodGroup : typeInst->mMethodInstanceGroups)
  1247. {
  1248. if ((methodGroup.mOnDemandKind == BfMethodOnDemandKind_NoDecl_AwaitingReference) ||
  1249. (methodGroup.mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingDecl) ||
  1250. (methodGroup.mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingReference) ||
  1251. (methodGroup.mOnDemandKind == BfMethodOnDemandKind_InWorkList))
  1252. {
  1253. oldOnDemandCount++;
  1254. }
  1255. _HandleMethod(methodGroup.mDefault);
  1256. if (methodGroup.mMethodSpecializationMap != NULL)
  1257. for (auto& kv : *methodGroup.mMethodSpecializationMap)
  1258. _HandleMethod(kv.mValue);
  1259. }
  1260. }
  1261. if (typeInst->IsDeleting())
  1262. typeIdx--;
  1263. }
  1264. }
  1265. }
  1266. if (!mIsDeleting)
  1267. Init();
  1268. mOnDemandMethodCount += oldOnDemandCount;
  1269. VerifyOnDemandMethods();
  1270. }
  1271. void BfModule::StartExtension()
  1272. {
  1273. BF_ASSERT(!mIsModuleMutable);
  1274. BfLogSysM("Extension started of module %p\n", this);
  1275. mExtensionCount++;
  1276. if (mBfIRBuilder != NULL)
  1277. mPrevIRBuilders.push_back(mBfIRBuilder);
  1278. mBfIRBuilder = NULL;
  1279. mWantsIRIgnoreWrites = false;
  1280. mFuncReferences.Clear();
  1281. mClassVDataRefs.Clear();
  1282. mClassVDataExtRefs.Clear();
  1283. for (auto& kv : mTypeDataRefs)
  1284. kv.mValue = BfIRValue();
  1285. mDbgRawAllocDataRefs.Clear();
  1286. mStringCharPtrPool.Clear();
  1287. mStringObjectPool.Clear();
  1288. mStaticFieldRefs.Clear();
  1289. for (auto& kv : mInterfaceSlotRefs)
  1290. kv.mValue = BfIRValue();
  1291. for (auto& pairVal : mDeferredMethodCallData)
  1292. delete pairVal.mValue;
  1293. mDeferredMethodCallData.Clear();
  1294. mDeferredMethodIds.Clear();
  1295. DisownMethods();
  1296. BfLogSysM("Mod:%p StartExtension: %s\n", this, mModuleName.c_str());
  1297. bool wasAwaitingInitFinish = mAwaitingInitFinish;
  1298. int prevOnDemandMethodCount = mOnDemandMethodCount;
  1299. Init(false);
  1300. if (!wasAwaitingInitFinish)
  1301. FinishInit();
  1302. mOnDemandMethodCount = prevOnDemandMethodCount;
  1303. }
  1304. void BfModule::GetConstClassValueParam(BfIRValue classVData, SizedArrayImpl<BfIRValue>& typeValueParams)
  1305. {
  1306. auto hasObjectDebugFlags = mContext->mBfObjectType->mFieldInstances[0].mResolvedType->IsInteger();
  1307. BfIRValue vDataValue;
  1308. if (hasObjectDebugFlags)
  1309. vDataValue = mBfIRBuilder->CreatePtrToInt(classVData, BfTypeCode_IntPtr);
  1310. else
  1311. vDataValue = mBfIRBuilder->CreateBitCast(classVData, mBfIRBuilder->MapType(mContext->mBfClassVDataPtrType));
  1312. typeValueParams.push_back(vDataValue);
  1313. if (hasObjectDebugFlags)
  1314. {
  1315. auto primType = GetPrimitiveType(BfTypeCode_IntPtr);
  1316. typeValueParams.push_back(GetDefaultValue(primType));
  1317. }
  1318. }
  1319. BfIRValue BfModule::GetConstValue(int64 val)
  1320. {
  1321. return mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, (uint64)val);
  1322. }
  1323. BfIRValue BfModule::GetConstValue(int64 val, BfType* type)
  1324. {
  1325. BfType* checkType = type;
  1326. if (type->IsTypedPrimitive())
  1327. {
  1328. checkType = type->GetUnderlyingType();
  1329. }
  1330. if (checkType->IsPrimitiveType())
  1331. {
  1332. auto primType = (BfPrimitiveType*)checkType;
  1333. if (checkType->IsFloat())
  1334. return mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, (double)val);
  1335. else
  1336. return mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, (uint64)val);
  1337. }
  1338. return BfIRValue();
  1339. }
  1340. BfIRValue BfModule::GetConstValue8(int val)
  1341. {
  1342. return mBfIRBuilder->CreateConst(BfTypeCode_Int8, (uint64)val);
  1343. }
  1344. BfIRValue BfModule::GetConstValue32(int32 val)
  1345. {
  1346. return mBfIRBuilder->CreateConst(BfTypeCode_Int32, (uint64)val);
  1347. }
  1348. BfIRValue BfModule::GetConstValue64(int64 val)
  1349. {
  1350. return mBfIRBuilder->CreateConst(BfTypeCode_Int64, (uint64)val);
  1351. }
  1352. BfIRValue BfModule::GetDefaultValue(BfType* type)
  1353. {
  1354. PopulateType(type, BfPopulateType_Data);
  1355. mBfIRBuilder->PopulateType(type, BfIRPopulateType_Declaration);
  1356. if (type->IsTypedPrimitive())
  1357. {
  1358. auto underlyingType = type->GetUnderlyingType();
  1359. if (underlyingType == NULL)
  1360. return mBfIRBuilder->CreateConst(BfTypeCode_Int64, 0);
  1361. return GetDefaultValue(type->GetUnderlyingType());
  1362. }
  1363. if (type->IsPointer() || type->IsObjectOrInterface() || type->IsGenericParam() || type->IsVar() || type->IsRef() || type->IsNull() ||
  1364. type->IsModifiedTypeType() || type->IsConcreteInterfaceType())
  1365. return mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(type));
  1366. if ((type->IsIntegral()) || (type->IsBoolean()))
  1367. {
  1368. auto primType = (BfPrimitiveType*)type;
  1369. return mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, (uint64)0);
  1370. }
  1371. if (type->IsFloat())
  1372. {
  1373. auto primType = (BfPrimitiveType*)type;
  1374. return mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, 0.0);
  1375. }
  1376. return mBfIRBuilder->CreateConstAggZero(mBfIRBuilder->MapType(type));
  1377. }
  1378. BfTypedValue BfModule::GetFakeTypedValue(BfType* type)
  1379. {
  1380. // This is a conservative "IsValueless", since it's not an error to use a fakeVal even if we don't need one
  1381. if (type->mSize == 0)
  1382. return BfTypedValue(BfIRValue::sValueless, type);
  1383. else if (mBfIRBuilder != NULL)
  1384. return BfTypedValue(mBfIRBuilder->GetFakeVal(), type);
  1385. else
  1386. return BfTypedValue(BfIRValue(BfIRValueFlags_Value, -1), type);
  1387. }
  1388. BfTypedValue BfModule::GetDefaultTypedValue(BfType* type, bool allowRef, BfDefaultValueKind defaultValueKind)
  1389. {
  1390. if (type->IsVar())
  1391. return BfTypedValue(mBfIRBuilder->GetFakeVal(), type);
  1392. PopulateType(type, BfPopulateType_Data);
  1393. mBfIRBuilder->PopulateType(type, type->IsValueType() ? BfIRPopulateType_Full : BfIRPopulateType_Declaration);
  1394. if (defaultValueKind == BfDefaultValueKind_Undef)
  1395. {
  1396. return BfTypedValue(mBfIRBuilder->GetUndefConstValue(mBfIRBuilder->MapType(type)), type);
  1397. }
  1398. BfTypedValue typedValue;
  1399. if ((defaultValueKind != BfDefaultValueKind_Const) && (!type->IsValuelessType()))
  1400. {
  1401. if (type->IsRef())
  1402. {
  1403. BfRefType* refType = (BfRefType*)type;
  1404. BfType* underlyingType = refType->GetUnderlyingType();
  1405. typedValue = BfTypedValue(CreateAlloca(underlyingType), underlyingType, BfTypedValueKind_Addr);
  1406. }
  1407. else
  1408. {
  1409. typedValue = BfTypedValue(CreateAlloca(type), type, BfTypedValueKind_Addr);
  1410. }
  1411. if (!mBfIRBuilder->mIgnoreWrites)
  1412. {
  1413. mBfIRBuilder->CreateMemSet(typedValue.mValue, GetConstValue(0, GetPrimitiveType(BfTypeCode_Int8)),
  1414. GetConstValue(type->mSize), type->mAlign);
  1415. }
  1416. if ((defaultValueKind == BfDefaultValueKind_Value) && (!type->IsRef()))
  1417. typedValue = LoadValue(typedValue);
  1418. return typedValue;
  1419. }
  1420. if ((type->IsRef()) && (!allowRef))
  1421. {
  1422. BfRefType* refType = (BfRefType*)type;
  1423. BfType* underlyingType = refType->GetUnderlyingType();
  1424. if (underlyingType->IsValuelessType())
  1425. typedValue = BfTypedValue(mBfIRBuilder->GetFakeVal(), underlyingType, true);
  1426. else
  1427. typedValue = BfTypedValue(mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(type)), underlyingType, true);
  1428. }
  1429. else
  1430. {
  1431. typedValue = BfTypedValue(GetDefaultValue(type), type, (defaultValueKind == BfDefaultValueKind_Addr) ? BfTypedValueKind_Addr : BfTypedValueKind_Value);
  1432. }
  1433. return typedValue;
  1434. }
  1435. BfIRValue BfModule::CreateStringCharPtr(const StringImpl& str, int stringId, bool define)
  1436. {
  1437. String stringDataName = StrFormat("__bfStrData%d", stringId);
  1438. auto charType = GetPrimitiveType(BfTypeCode_Char8);
  1439. BfIRType irStrCharType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->MapType(charType), (int)str.length() + 1);
  1440. BfIRValue strConstant;
  1441. if (define)
  1442. {
  1443. strConstant = mBfIRBuilder->CreateConstString(str);
  1444. }
  1445. BfIRValue gv = mBfIRBuilder->CreateGlobalVariable(irStrCharType,
  1446. true, BfIRLinkageType_External,
  1447. strConstant, stringDataName);
  1448. if (define)
  1449. mBfIRBuilder->GlobalVar_SetUnnamedAddr(gv, true);
  1450. return mBfIRBuilder->CreateInBoundsGEP(gv, 0, 0);
  1451. }
  1452. void BfModule::FixConstValueParams(BfTypeInstance* typeInst, SizedArrayImpl<BfIRValue>& valueParams, bool fillInPadding)
  1453. {
  1454. if ((!typeInst->mTypeDef->mIsCombinedPartial) && (!fillInPadding))
  1455. return;
  1456. int prevDataIdx = -1;
  1457. int usedDataIdx = 0;
  1458. int valueParamIdx = 0;
  1459. if (typeInst->mBaseType != NULL)
  1460. {
  1461. usedDataIdx++;
  1462. valueParamIdx++;
  1463. prevDataIdx++;
  1464. }
  1465. int startingParamsSize = (int)valueParams.mSize;
  1466. for (int fieldIdx = 0; fieldIdx < (int)typeInst->mFieldInstances.size(); fieldIdx++)
  1467. {
  1468. auto fieldInstance = &typeInst->mFieldInstances[fieldIdx];
  1469. if (fieldInstance->mDataIdx < 0)
  1470. continue;
  1471. BF_ASSERT(fieldInstance->mDataIdx > prevDataIdx);
  1472. if (fillInPadding)
  1473. {
  1474. for (int i = prevDataIdx + 1; i < fieldInstance->mDataIdx; i++)
  1475. valueParams.Insert(valueParamIdx++, mBfIRBuilder->CreateConstArrayZero(0));
  1476. }
  1477. valueParamIdx++;
  1478. prevDataIdx = fieldInstance->mDataIdx;
  1479. usedDataIdx++;
  1480. if (usedDataIdx <= valueParams.mSize)
  1481. continue;
  1482. valueParams.Add(GetDefaultValue(fieldInstance->mResolvedType));
  1483. }
  1484. }
  1485. BfIRValue BfModule::CreateStringObjectValue(const StringImpl& str, int stringId, bool define)
  1486. {
  1487. auto stringTypeInst = ResolveTypeDef(mCompiler->mStringTypeDef, define ? BfPopulateType_Data : BfPopulateType_Declaration)->ToTypeInstance();
  1488. mBfIRBuilder->PopulateType(stringTypeInst);
  1489. auto classVDataGlobal = CreateClassVDataGlobal(stringTypeInst);
  1490. String stringObjName = StrFormat("__bfStrObj%d", stringId);
  1491. BfIRValue stringValData;
  1492. if (define)
  1493. {
  1494. BfIRValue stringCharsVal = CreateStringCharPtr(str, stringId, define);
  1495. mStringCharPtrPool[stringId] = stringCharsVal;
  1496. SizedArray<BfIRValue, 8> typeValueParams;
  1497. GetConstClassValueParam(classVDataGlobal, typeValueParams);
  1498. FixConstValueParams(stringTypeInst->mBaseType, typeValueParams);
  1499. auto objData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(stringTypeInst->mBaseType, BfIRPopulateType_Full), typeValueParams);
  1500. auto lenByteCount = stringTypeInst->mFieldInstances[0].mResolvedType->mSize;
  1501. typeValueParams.clear();
  1502. typeValueParams.push_back(objData);
  1503. if (lenByteCount == 4)
  1504. {
  1505. typeValueParams.push_back(GetConstValue32((int)str.length())); // mLength
  1506. typeValueParams.push_back(GetConstValue32((int32)(0x40000000 + str.length() + 1))); // mAllocSizeAndFlags
  1507. }
  1508. else
  1509. {
  1510. typeValueParams.push_back(GetConstValue64(str.length())); // mLength
  1511. typeValueParams.push_back(GetConstValue64(0x4000000000000000LL + str.length() + 1)); // mAllocSizeAndFlags
  1512. }
  1513. typeValueParams.push_back(stringCharsVal); // mPtr
  1514. FixConstValueParams(stringTypeInst, typeValueParams);
  1515. stringValData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(stringTypeInst, BfIRPopulateType_Full), typeValueParams);
  1516. }
  1517. mBfIRBuilder->PopulateType(stringTypeInst);
  1518. auto stringValLiteral = mBfIRBuilder->CreateGlobalVariable(
  1519. mBfIRBuilder->MapTypeInst(stringTypeInst, BfIRPopulateType_Full),
  1520. true,
  1521. BfIRLinkageType_External,
  1522. define ? stringValData : BfIRValue(),
  1523. stringObjName);
  1524. return stringValLiteral;
  1525. }
  1526. bool BfModule::HasStringId(BfIRValue constantStr, BfIRConstHolder* constHolder)
  1527. {
  1528. if (constHolder == NULL)
  1529. constHolder = mBfIRBuilder;
  1530. auto constant = constHolder->GetConstant(constantStr);
  1531. if (constant == NULL)
  1532. return false;
  1533. while (constant->mConstType == BfConstType_BitCast)
  1534. {
  1535. auto constBitCast = (BfConstantBitCast*)constant;
  1536. constant = constHolder->GetConstantById(constBitCast->mTarget);
  1537. }
  1538. if (constant->mTypeCode == BfTypeCode_StringId)
  1539. {
  1540. return true;
  1541. }
  1542. return false;
  1543. }
  1544. int BfModule::GetStringPoolIdx(BfIRValue constantStr, BfIRConstHolder* constHolder)
  1545. {
  1546. if (constHolder == NULL)
  1547. constHolder = mBfIRBuilder;
  1548. auto constant = constHolder->GetConstant(constantStr);
  1549. if (constant == NULL)
  1550. return -1;
  1551. if (constant->mTypeCode == BfTypeCode_StringId)
  1552. {
  1553. return constant->mInt32;
  1554. }
  1555. while (constant->mConstType == BfConstType_BitCast)
  1556. {
  1557. auto constBitCast = (BfConstantBitCast*)constant;
  1558. constant = constHolder->GetConstantById(constBitCast->mTarget);
  1559. }
  1560. if (constant->mConstType == BfConstType_GEP32_2)
  1561. {
  1562. auto constGEP = (BfConstantGEP32_2*)constant;
  1563. constant = constHolder->GetConstantById(constGEP->mTarget);
  1564. }
  1565. if (constant->mConstType == BfConstType_GlobalVar)
  1566. {
  1567. auto constGV = (BfGlobalVar*)constant;
  1568. const char* strDataPrefix = "__bfStrData";
  1569. if (strncmp(constGV->mName, strDataPrefix, strlen(strDataPrefix)) == 0)
  1570. return atoi(constGV->mName + strlen(strDataPrefix));
  1571. const char* strObjPrefix = "__bfStrObj";
  1572. if (strncmp(constGV->mName, strObjPrefix, strlen(strObjPrefix)) == 0)
  1573. return atoi(constGV->mName + strlen(strObjPrefix));
  1574. }
  1575. return -1;
  1576. }
  1577. String* BfModule::GetStringPoolString(BfIRValue constantStr, BfIRConstHolder * constHolder)
  1578. {
  1579. int strId = GetStringPoolIdx(constantStr, constHolder);
  1580. if (strId != -1)
  1581. {
  1582. auto& entry = mContext->mStringObjectIdMap[strId];
  1583. return &entry.mString;
  1584. }
  1585. return NULL;
  1586. }
  1587. CeDbgState* BfModule::GetCeDbgState()
  1588. {
  1589. if (!mIsComptimeModule)
  1590. return NULL;
  1591. if ((mCompiler->mCeMachine != NULL) && (mCompiler->mCeMachine->mDebugger != NULL))
  1592. return mCompiler->mCeMachine->mDebugger->mCurDbgState;
  1593. return NULL;
  1594. }
  1595. BfIRValue BfModule::GetStringCharPtr(int stringId, bool force)
  1596. {
  1597. if ((mBfIRBuilder->mIgnoreWrites) && (!force))
  1598. {
  1599. mUnreifiedStringPoolRefs.Add(stringId);
  1600. return mBfIRBuilder->CreateConst(BfTypeCode_StringId, stringId);
  1601. }
  1602. BfIRValue* irValue = NULL;
  1603. if (!mStringCharPtrPool.TryAdd(stringId, NULL, &irValue))
  1604. return *irValue;
  1605. // If this wasn't in neither dictionary yet, add to mStringPoolRefs
  1606. if (!mStringObjectPool.ContainsKey(stringId))
  1607. mStringPoolRefs.Add(stringId);
  1608. const StringImpl& str = mContext->mStringObjectIdMap[stringId].mString;
  1609. BfIRValue strCharPtrConst = CreateStringCharPtr(str, stringId, false);
  1610. *irValue = strCharPtrConst;
  1611. return strCharPtrConst;
  1612. }
  1613. BfIRValue BfModule::GetStringCharPtr(BfIRValue strValue, bool force)
  1614. {
  1615. if (strValue.IsConst())
  1616. {
  1617. int stringId = GetStringPoolIdx(strValue);
  1618. BF_ASSERT(stringId != -1);
  1619. return GetStringCharPtr(stringId, force);
  1620. }
  1621. BfIRValue charPtrPtr = mBfIRBuilder->CreateInBoundsGEP(strValue, 0, 1);
  1622. BfIRValue charPtr = mBfIRBuilder->CreateLoad(charPtrPtr);
  1623. return charPtr;
  1624. }
  1625. BfIRValue BfModule::GetStringCharPtr(const StringImpl& str, bool force)
  1626. {
  1627. return GetStringCharPtr(GetStringObjectValue(str, force), force);
  1628. }
  1629. BfIRValue BfModule::GetStringObjectValue(int strId, bool define, bool force)
  1630. {
  1631. BfIRValue* objValue;
  1632. if (mStringObjectPool.TryGetValue(strId, &objValue))
  1633. return *objValue;
  1634. auto stringPoolEntry = mContext->mStringObjectIdMap[strId];
  1635. return GetStringObjectValue(stringPoolEntry.mString, define, force);
  1636. }
  1637. BfIRValue BfModule::GetStringObjectValue(const StringImpl& str, bool define, bool force)
  1638. {
  1639. auto stringType = ResolveTypeDef(mCompiler->mStringTypeDef, define ? BfPopulateType_Data : BfPopulateType_Declaration);
  1640. mBfIRBuilder->PopulateType(stringType);
  1641. int strId = mContext->GetStringLiteralId(str);
  1642. if ((mBfIRBuilder->mIgnoreWrites) && (!force))
  1643. {
  1644. auto refModule = this;
  1645. if ((this == mContext->mUnreifiedModule) && (mCurTypeInstance != NULL))
  1646. refModule = mCurTypeInstance->mModule;
  1647. refModule->mUnreifiedStringPoolRefs.Add(strId);
  1648. return mBfIRBuilder->CreateConst(BfTypeCode_StringId, strId);
  1649. }
  1650. BfIRValue* irValuePtr = NULL;
  1651. if (mStringObjectPool.TryGetValue(strId, &irValuePtr))
  1652. return *irValuePtr;
  1653. // If this wasn't in neither dictionary yet, add to mStringPoolRefs
  1654. if (!mStringCharPtrPool.ContainsKey(strId))
  1655. mStringPoolRefs.Add(strId);
  1656. BfIRValue strObject = CreateStringObjectValue(str, strId, define);
  1657. mStringObjectPool[strId] = strObject;
  1658. mStringPoolRefs.Add(strId);
  1659. return strObject;
  1660. }
  1661. BfIRValue BfModule::CreateGlobalConstValue(const StringImpl& name, BfIRValue constant, BfIRType type, bool external)
  1662. {
  1663. auto newConst = mBfIRBuilder->CreateGlobalVariable(
  1664. type,
  1665. true,
  1666. external ? BfIRLinkageType_External : BfIRLinkageType_Internal,
  1667. constant,
  1668. name.c_str());
  1669. return newConst;
  1670. }
  1671. void BfModule::NewScopeState(bool createLexicalBlock, bool flushValueScope)
  1672. {
  1673. auto curScope = mCurMethodState->mCurScope;
  1674. if (curScope->mLabelNode != NULL)
  1675. {
  1676. curScope->mLabelNode->ToString(curScope->mLabel);
  1677. auto rootMethodState = mCurMethodState->GetRootMethodState();
  1678. curScope->mScopeLocalId = rootMethodState->mCurLocalVarId++;
  1679. auto autoComplete = mCompiler->GetAutoComplete();
  1680. if (autoComplete != NULL)
  1681. autoComplete->CheckLabel(curScope->mLabelNode, NULL, curScope);
  1682. }
  1683. if (!mCurMethodState->mCurScope->mLabel.IsEmpty())
  1684. {
  1685. auto checkScope = mCurMethodState->mCurScope->mPrevScope;
  1686. while (checkScope != NULL)
  1687. {
  1688. if (checkScope->mLabel == mCurMethodState->mCurScope->mLabel)
  1689. {
  1690. auto errorNode = Warn(0, StrFormat("Duplicate scope label '%s'", checkScope->mLabel.c_str()), curScope->mLabelNode);
  1691. if (errorNode != NULL)
  1692. mCompiler->mPassInstance->MoreInfo("See previous scope label", checkScope->mLabelNode);
  1693. break;
  1694. }
  1695. checkScope = checkScope->mPrevScope;
  1696. }
  1697. }
  1698. auto prevScope = mCurMethodState->mCurScope->mPrevScope;
  1699. if ((flushValueScope) && (prevScope != NULL) && (prevScope->mValueScopeStart))
  1700. {
  1701. if (prevScope->mHadScopeValueRetain)
  1702. mBfIRBuilder->CreateValueScopeSoftEnd(prevScope->mValueScopeStart);
  1703. else
  1704. mBfIRBuilder->CreateValueScopeHardEnd(prevScope->mValueScopeStart);
  1705. }
  1706. mCurMethodState->mBlockNestLevel++;
  1707. if ((createLexicalBlock) && (mBfIRBuilder->DbgHasInfo()) && (mHasFullDebugInfo))
  1708. {
  1709. // DIScope could be NULL if we're in an unspecialized method (for example)
  1710. if (mCurMethodState->mCurScope->mDIScope)
  1711. mCurMethodState->mCurScope->mDIScope = mBfIRBuilder->DbgCreateLexicalBlock(mCurMethodState->mCurScope->mDIScope, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, mCurFilePosition.mCurColumn);
  1712. }
  1713. mCurMethodState->mCurScope->mLocalVarStart = (int)mCurMethodState->mLocals.size();
  1714. mCurMethodState->mCurScope->mBlock = mBfIRBuilder->MaybeChainNewBlock((!mCurMethodState->mCurScope->mLabel.empty()) ? mCurMethodState->mCurScope->mLabel : "newScope");
  1715. mCurMethodState->mCurScope->mMixinState = mCurMethodState->mMixinState;
  1716. }
  1717. void BfModule::RestoreScoreState_LocalVariables(int localVarStart)
  1718. {
  1719. while (localVarStart < (int)mCurMethodState->mLocals.size())
  1720. {
  1721. auto localVar = mCurMethodState->mLocals.back();
  1722. LocalVariableDone(localVar, false);
  1723. mCurMethodState->mLocals.pop_back();
  1724. if (localVar->mShadowedLocal != NULL)
  1725. {
  1726. BfLocalVarEntry* localVarEntryPtr;
  1727. if (mCurMethodState->mLocalVarSet.TryGet(BfLocalVarEntry(localVar), &localVarEntryPtr))
  1728. {
  1729. localVarEntryPtr->mLocalVar = localVar->mShadowedLocal;
  1730. }
  1731. }
  1732. else
  1733. {
  1734. mCurMethodState->mLocalVarSet.Remove(BfLocalVarEntry(localVar));
  1735. }
  1736. if (localVar->mIsBumpAlloc)
  1737. localVar->~BfLocalVariable();
  1738. else
  1739. delete localVar;
  1740. }
  1741. }
  1742. void BfModule::RestoreScopeState()
  1743. {
  1744. BfScopeData* prevScopeData = mCurMethodState->mCurScope->mPrevScope;
  1745. mCurMethodState->mBlockNestLevel--;
  1746. if (!mCurMethodState->mCurScope->mAtEndBlocks.empty())
  1747. {
  1748. BfIRBlock afterEndBlock;
  1749. if (!mCurMethodState->mLeftBlockUncond)
  1750. {
  1751. afterEndBlock = mBfIRBuilder->CreateBlock("scopeAfterEnd");
  1752. mBfIRBuilder->CreateBr(afterEndBlock);
  1753. mBfIRBuilder->ClearDebugLocation_Last();
  1754. }
  1755. for (auto preExitBlock : mCurMethodState->mCurScope->mAtEndBlocks)
  1756. mBfIRBuilder->MoveBlockToEnd(preExitBlock);
  1757. if (afterEndBlock)
  1758. {
  1759. mBfIRBuilder->AddBlock(afterEndBlock);
  1760. mBfIRBuilder->SetInsertPoint(afterEndBlock);
  1761. }
  1762. }
  1763. mCurMethodState->mCurScope->mDone = true;
  1764. if (!mCurMethodState->mLeftBlockUncond)
  1765. EmitDeferredScopeCalls(true, mCurMethodState->mCurScope);
  1766. EmitDeferredCallProcessorInstances(mCurMethodState->mCurScope);
  1767. RestoreScoreState_LocalVariables(mCurMethodState->mCurScope->mLocalVarStart);
  1768. if (mCurMethodState->mCurScope->mValueScopeStart)
  1769. mBfIRBuilder->CreateValueScopeHardEnd(mCurMethodState->mCurScope->mValueScopeStart);
  1770. mCurMethodState->mCurScope = prevScopeData;
  1771. mCurMethodState->mTailScope = mCurMethodState->mCurScope;
  1772. }
  1773. BfIRValue BfModule::CreateAlloca(BfType* type, bool addLifetime, const char* name, BfIRValue arraySize)
  1774. {
  1775. if (mBfIRBuilder->mIgnoreWrites)
  1776. return mBfIRBuilder->GetFakeVal();
  1777. BF_ASSERT((*(int8*)&addLifetime == 1) || (*(int8*)&addLifetime == 0));
  1778. mBfIRBuilder->PopulateType(type);
  1779. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  1780. if (!mBfIRBuilder->mIgnoreWrites)
  1781. BF_ASSERT(!prevInsertBlock.IsFake());
  1782. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  1783. BfIRValue allocaInst;
  1784. if (arraySize)
  1785. allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(type), arraySize);
  1786. else
  1787. allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(type));
  1788. mBfIRBuilder->SetAllocaAlignment(allocaInst, type->mAlign);
  1789. mBfIRBuilder->ClearDebugLocation(allocaInst);
  1790. if (name != NULL)
  1791. mBfIRBuilder->SetName(allocaInst, name);
  1792. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  1793. if ((addLifetime) && (WantsLifetimes()))
  1794. {
  1795. auto lifetimeStart = mBfIRBuilder->CreateLifetimeStart(allocaInst);
  1796. mBfIRBuilder->ClearDebugLocation(lifetimeStart);
  1797. mCurMethodState->mCurScope->mDeferredLifetimeEnds.push_back(allocaInst);
  1798. }
  1799. return allocaInst;
  1800. }
  1801. BfIRValue BfModule::CreateAllocaInst(BfTypeInstance* typeInst, bool addLifetime, const char* name)
  1802. {
  1803. if (mBfIRBuilder->mIgnoreWrites)
  1804. return mBfIRBuilder->GetFakeVal();
  1805. BF_ASSERT((*(int8*)&addLifetime == 1) || (*(int8*)&addLifetime == 0));
  1806. mBfIRBuilder->PopulateType(typeInst);
  1807. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  1808. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  1809. auto allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapTypeInst(typeInst));
  1810. mBfIRBuilder->SetAllocaAlignment(allocaInst, typeInst->mInstAlign);
  1811. mBfIRBuilder->ClearDebugLocation(allocaInst);
  1812. if (name != NULL)
  1813. mBfIRBuilder->SetName(allocaInst, name);
  1814. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  1815. if ((addLifetime) && (WantsLifetimes()))
  1816. {
  1817. auto lifetimeStart = mBfIRBuilder->CreateLifetimeStart(allocaInst);
  1818. mBfIRBuilder->ClearDebugLocation(lifetimeStart);
  1819. mCurMethodState->mCurScope->mDeferredLifetimeEnds.push_back(allocaInst);
  1820. }
  1821. return allocaInst;
  1822. }
  1823. BfDeferredCallEntry* BfModule::AddStackAlloc(BfTypedValue val, BfIRValue arraySize, BfAstNode* refNode, BfScopeData* scopeData, bool condAlloca, bool mayEscape, BfIRBlock valBlock)
  1824. {
  1825. //This was removed because we want the alloc to be added to the __deferred list if it's actually a "stack"
  1826. // 'stack' in a head scopeData is really the same as 'scopeData', so use the simpler scopeData handling
  1827. /*if (mCurMethodState->mInHeadScope)
  1828. isScopeAlloc = true;*/
  1829. if (scopeData == NULL)
  1830. return NULL;
  1831. auto checkBaseType = val.mType->ToTypeInstance();
  1832. if ((checkBaseType != NULL) && (checkBaseType->IsObject()) && (!arraySize))
  1833. {
  1834. bool hadDtorCall = false;
  1835. while (checkBaseType != NULL)
  1836. {
  1837. BfMethodDef* dtorMethodDef = checkBaseType->mTypeDef->GetMethodByName("~this");
  1838. if (dtorMethodDef != NULL)
  1839. {
  1840. auto dtorMethodInstance = GetMethodInstance(checkBaseType, dtorMethodDef, BfTypeVector());
  1841. if (dtorMethodInstance)
  1842. {
  1843. bool isDynAlloc = (scopeData != NULL) && (mCurMethodState->mCurScope->IsDyn(scopeData));
  1844. BfIRValue useVal = val.mValue;
  1845. BfIRBlock prevBlock = mBfIRBuilder->GetInsertBlock();
  1846. if (valBlock)
  1847. mBfIRBuilder->SetInsertPoint(valBlock);
  1848. useVal = mBfIRBuilder->CreateBitCast(val.mValue, mBfIRBuilder->MapTypeInstPtr(checkBaseType));
  1849. if (!useVal.IsConst())
  1850. mBfIRBuilder->ClearDebugLocation(useVal);
  1851. if (valBlock)
  1852. mBfIRBuilder->SetInsertPoint(prevBlock);
  1853. if (isDynAlloc)
  1854. {
  1855. //
  1856. }
  1857. else if (condAlloca)
  1858. {
  1859. BF_ASSERT(!IsTargetingBeefBackend());
  1860. BF_ASSERT(!isDynAlloc);
  1861. auto valPtr = CreateAlloca(checkBaseType);
  1862. mBfIRBuilder->ClearDebugLocation_Last();
  1863. mBfIRBuilder->CreateAlignedStore(useVal, valPtr, checkBaseType->mAlign);
  1864. mBfIRBuilder->ClearDebugLocation_Last();
  1865. useVal = valPtr;
  1866. }
  1867. SizedArray<BfIRValue, 1> llvmArgs;
  1868. llvmArgs.push_back(useVal);
  1869. auto deferredCall = AddDeferredCall(dtorMethodInstance, llvmArgs, scopeData, refNode, true);
  1870. if (deferredCall != NULL)
  1871. {
  1872. deferredCall->mCastThis = (val.mType != checkBaseType) && (!isDynAlloc);
  1873. if (condAlloca)
  1874. deferredCall->mArgsNeedLoad = true;
  1875. }
  1876. hadDtorCall = true;
  1877. break;
  1878. }
  1879. }
  1880. checkBaseType = checkBaseType->mBaseType;
  1881. }
  1882. return NULL;
  1883. }
  1884. //TODO: In the future we could be smarter about statically determining that our value hasn't escaped and eliding this
  1885. if (mayEscape)
  1886. {
  1887. if ((!IsOptimized()) && (!mIsComptimeModule) && (!val.mType->IsValuelessType()) && (!mBfIRBuilder->mIgnoreWrites) && (!mCompiler->mIsResolveOnly))
  1888. {
  1889. auto nullPtrType = GetPrimitiveType(BfTypeCode_NullPtr);
  1890. bool isDyn = mCurMethodState->mCurScope->IsDyn(scopeData);
  1891. if (!isDyn)
  1892. {
  1893. const char* methodName = arraySize ? "SetDeletedArray" : "SetDeleted";
  1894. BfModuleMethodInstance dtorMethodInstance = GetInternalMethod(methodName);
  1895. BF_ASSERT(dtorMethodInstance.mMethodInstance != NULL);
  1896. if (!dtorMethodInstance.mMethodInstance)
  1897. {
  1898. Fail(StrFormat("Unable to find %s", methodName));
  1899. }
  1900. else
  1901. {
  1902. SizedArray<BfIRValue, 1> llvmArgs;
  1903. if (IsTargetingBeefBackend())
  1904. {
  1905. llvmArgs.push_back(mBfIRBuilder->CreateBitCast(val.mValue, mBfIRBuilder->MapType(nullPtrType)));
  1906. //mBfIRBuilder->ClearDebugLocation_Last();
  1907. }
  1908. else
  1909. llvmArgs.push_back(val.mValue);
  1910. llvmArgs.push_back(GetConstValue(val.mType->mSize));
  1911. llvmArgs.push_back(GetConstValue32(val.mType->mAlign));
  1912. if (arraySize)
  1913. llvmArgs.push_back(arraySize);
  1914. return AddDeferredCall(dtorMethodInstance, llvmArgs, scopeData, refNode, true);
  1915. }
  1916. }
  1917. else
  1918. {
  1919. if ((arraySize) && (!arraySize.IsConst()) && (val.mType->mSize < mSystem->mPtrSize))
  1920. {
  1921. BfIRValue clearSize = arraySize;
  1922. if (val.mType->GetStride() > 1)
  1923. clearSize = mBfIRBuilder->CreateMul(clearSize, GetConstValue(val.mType->GetStride()));
  1924. const char* methodName = "SetDeletedX";
  1925. BfModuleMethodInstance dtorMethodInstance = GetInternalMethod(methodName);
  1926. BF_ASSERT(dtorMethodInstance);
  1927. if (!dtorMethodInstance)
  1928. {
  1929. Fail(StrFormat("Unable to find %s", methodName));
  1930. }
  1931. else
  1932. {
  1933. SizedArray<BfIRValue, 1> llvmArgs;
  1934. llvmArgs.push_back(mBfIRBuilder->CreateBitCast(val.mValue, mBfIRBuilder->MapType(nullPtrType)));
  1935. //mBfIRBuilder->ClearDebugLocation_Last();
  1936. llvmArgs.push_back(clearSize);
  1937. return AddDeferredCall(dtorMethodInstance, llvmArgs, scopeData, refNode, true);
  1938. }
  1939. }
  1940. else
  1941. {
  1942. intptr clearSize = val.mType->mSize;
  1943. auto constant = mBfIRBuilder->GetConstant(arraySize);
  1944. if (constant != NULL)
  1945. clearSize = (intptr)(clearSize * constant->mInt64);
  1946. const char* funcName = "SetDeleted1";
  1947. if (clearSize >= 16)
  1948. funcName = "SetDeleted16";
  1949. else if (clearSize >= 8)
  1950. funcName = "SetDeleted8";
  1951. else if (clearSize >= 4)
  1952. funcName = "SetDeleted4";
  1953. BfModuleMethodInstance dtorMethodInstance = GetInternalMethod(funcName);
  1954. BF_ASSERT(dtorMethodInstance.mMethodInstance != NULL);
  1955. if (!dtorMethodInstance)
  1956. {
  1957. Fail(StrFormat("Unable to find %s", funcName));
  1958. }
  1959. else
  1960. {
  1961. SizedArray<BfIRValue, 1> llvmArgs;
  1962. llvmArgs.push_back(mBfIRBuilder->CreateBitCast(val.mValue, mBfIRBuilder->MapType(nullPtrType)));
  1963. //mBfIRBuilder->ClearDebugLocation_Last();
  1964. return AddDeferredCall(dtorMethodInstance, llvmArgs, scopeData, refNode, true);
  1965. }
  1966. }
  1967. }
  1968. }
  1969. }
  1970. return NULL;
  1971. }
  1972. bool BfModule::TryLocalVariableInit(BfLocalVariable* localVar)
  1973. {
  1974. auto startTypeInstance = localVar->mResolvedType->ToTypeInstance();
  1975. if ((startTypeInstance == NULL) || (!startTypeInstance->IsStruct()))
  1976. return false;
  1977. auto checkTypeInstance = startTypeInstance;
  1978. while (checkTypeInstance != NULL)
  1979. {
  1980. for (auto& fieldInstance : checkTypeInstance->mFieldInstances)
  1981. {
  1982. if (fieldInstance.mMergedDataIdx != -1)
  1983. {
  1984. int64 checkMask = (int64)1 << fieldInstance.mMergedDataIdx;
  1985. if ((localVar->mUnassignedFieldFlags & checkMask) != 0)
  1986. {
  1987. // For fields added in extensions, we automatically initialize those if necessary
  1988. auto fieldDef = fieldInstance.GetFieldDef();
  1989. if (!fieldDef->mDeclaringType->IsExtension())
  1990. return false;
  1991. if ((fieldInstance.mDataIdx != -1) && (!mBfIRBuilder->mIgnoreWrites) && (!mCompiler->mIsResolveOnly) && (!mIsComptimeModule))
  1992. {
  1993. auto curInsertBlock = mBfIRBuilder->GetInsertBlock();
  1994. mBfIRBuilder->SaveDebugLocation();
  1995. if (localVar->IsParam())
  1996. mBfIRBuilder->SetInsertPointAtStart(mCurMethodState->mIRInitBlock);
  1997. else
  1998. {
  1999. BF_ASSERT(localVar->mDeclBlock);
  2000. mBfIRBuilder->SetInsertPointAtStart(localVar->mDeclBlock);
  2001. }
  2002. mBfIRBuilder->ClearDebugLocation();
  2003. BfIRValue curVal;
  2004. if (localVar->mIsThis)
  2005. curVal = mBfIRBuilder->GetArgument(0);
  2006. else
  2007. curVal = localVar->mAddr;
  2008. auto subTypeInstance = startTypeInstance;
  2009. while (subTypeInstance != checkTypeInstance)
  2010. {
  2011. curVal = mBfIRBuilder->CreateInBoundsGEP(curVal, 0, 0);
  2012. subTypeInstance = subTypeInstance->mBaseType;
  2013. }
  2014. auto fieldPtr = mBfIRBuilder->CreateInBoundsGEP(curVal, 0, fieldInstance.mDataIdx);
  2015. auto defVal = GetDefaultValue(fieldInstance.mResolvedType);
  2016. auto storeInst = mBfIRBuilder->CreateStore(defVal, fieldPtr);
  2017. mBfIRBuilder->SetInsertPoint(curInsertBlock);
  2018. mBfIRBuilder->RestoreDebugLocation();
  2019. }
  2020. localVar->mUnassignedFieldFlags &= ~checkMask;
  2021. if (localVar->mUnassignedFieldFlags == 0)
  2022. localVar->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  2023. }
  2024. }
  2025. }
  2026. checkTypeInstance = checkTypeInstance->mBaseType;
  2027. }
  2028. return localVar->mAssignedKind != BfLocalVarAssignKind_None;
  2029. }
  2030. void BfModule::LocalVariableDone(BfLocalVariable* localVar, bool isMethodExit)
  2031. {
  2032. BfAstNode* localNameNode = localVar->mNameNode;
  2033. if ((localVar->mIsThis) && (mCurMethodInstance != NULL))
  2034. {
  2035. localNameNode = mCurMethodInstance->mMethodDef->GetRefNode();
  2036. }
  2037. if (localNameNode != NULL)
  2038. {
  2039. bool isOut = false;
  2040. if (localVar->mResolvedType->IsRef())
  2041. {
  2042. auto refType = (BfRefType*)localVar->mResolvedType;
  2043. isOut = refType->mRefKind == BfRefType::RefKind_Out;
  2044. }
  2045. if ((localVar->mReadFromId == -1) || (isOut) || ((localVar->mIsThis) && (mCurTypeInstance->IsStruct())))
  2046. {
  2047. if ((localVar->mAssignedKind != BfLocalVarAssignKind_Unconditional) & (localVar->IsParam()))
  2048. TryLocalVariableInit(localVar);
  2049. // We may skip processing of local methods, so we won't know if it bind to any of our local variables or not
  2050. bool deferFullAnalysis = mCurMethodState->GetRootMethodState()->mLocalMethodCache.size() != 0;
  2051. // We may have init blocks that we aren't processing here...
  2052. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mIsAutocompleteMethod) && (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_Ctor))
  2053. deferFullAnalysis = true;
  2054. //bool deferFullAnalysis = true;
  2055. bool deferUsageWarning = deferFullAnalysis && (mCompiler->IsAutocomplete()) &&
  2056. (mCompiler->mResolvePassData->mAutoComplete->mResolveType != BfResolveType_GetFixits);
  2057. if (((localVar->mAssignedKind != BfLocalVarAssignKind_Unconditional) || (localVar->mHadExitBeforeAssign)) &&
  2058. (!localVar->mIsImplicitParam))
  2059. {
  2060. if (deferUsageWarning)
  2061. {
  2062. // Ignore
  2063. }
  2064. else if (localVar->mIsThis)
  2065. {
  2066. bool foundFields = false;
  2067. auto checkTypeInstance = mCurTypeInstance;
  2068. while (checkTypeInstance != NULL)
  2069. {
  2070. for (auto& fieldInstance : checkTypeInstance->mFieldInstances)
  2071. {
  2072. if (fieldInstance.mMergedDataIdx == -1)
  2073. continue;
  2074. int checkMask = 1 << fieldInstance.mMergedDataIdx;
  2075. if ((localVar->mUnassignedFieldFlags & checkMask) != 0)
  2076. {
  2077. auto fieldDef = fieldInstance.GetFieldDef();
  2078. if (mCurMethodInstance->mMethodDef->mDeclaringType->mIsPartial)
  2079. {
  2080. if (mCurMethodInstance->mMethodDef->mDeclaringType != fieldInstance.GetFieldDef()->mDeclaringType)
  2081. {
  2082. // This extension is only responsible for its own fields
  2083. foundFields = true;
  2084. continue;
  2085. }
  2086. if (fieldDef->GetInitializer() != NULL)
  2087. {
  2088. // This initializer was handled in CtorNoBody
  2089. foundFields = true;
  2090. continue;
  2091. }
  2092. }
  2093. if (auto propertyDeclaration = BfNodeDynCast<BfPropertyDeclaration>(fieldDef->mFieldDeclaration))
  2094. {
  2095. String propName;
  2096. if (propertyDeclaration->mNameNode != NULL)
  2097. propertyDeclaration->mNameNode->ToString(propName);
  2098. if (checkTypeInstance == mCurTypeInstance)
  2099. {
  2100. Fail(StrFormat("Auto-implemented property '%s' must be fully assigned before control is returned to the caller",
  2101. propName.c_str()), localNameNode, deferFullAnalysis); // 0171
  2102. }
  2103. else
  2104. {
  2105. Fail(StrFormat("Auto-implemented property '%s.%s' must be fully assigned before control is returned to the caller",
  2106. TypeToString(checkTypeInstance).c_str(),
  2107. propName.c_str()), localNameNode, deferFullAnalysis); // 0171
  2108. }
  2109. }
  2110. else
  2111. {
  2112. if (checkTypeInstance == mCurTypeInstance)
  2113. {
  2114. Fail(StrFormat("Field '%s' must be fully assigned before control is returned to the caller",
  2115. fieldDef->mName.c_str()), localNameNode, deferFullAnalysis); // 0171
  2116. }
  2117. else
  2118. {
  2119. Fail(StrFormat("Field '%s.%s' must be fully assigned before control is returned to the caller",
  2120. TypeToString(checkTypeInstance).c_str(),
  2121. fieldDef->mName.c_str()), localNameNode, deferFullAnalysis); // 0171
  2122. }
  2123. }
  2124. foundFields = true;
  2125. }
  2126. }
  2127. checkTypeInstance = checkTypeInstance->mBaseType;
  2128. }
  2129. if (!foundFields)
  2130. {
  2131. if (mCurTypeInstance->mInstSize > 0)
  2132. Fail(StrFormat("The variable '%s' must be fully assigned to before control leaves the current method", localVar->mName.c_str()), localNameNode); // 0177
  2133. }
  2134. }
  2135. else if (localVar->IsParam())
  2136. Fail(StrFormat("The out parameter '%s' must be assigned to before control leaves the current method", localVar->mName.c_str()), localNameNode, deferFullAnalysis); // 0177
  2137. else if (!deferUsageWarning)
  2138. Warn(BfWarning_CS0168_VariableDeclaredButNeverUsed, StrFormat("The variable '%s' is declared but never used", localVar->mName.c_str()), localNameNode, deferFullAnalysis);
  2139. }
  2140. else if ((localVar->mReadFromId == -1) && (!localVar->IsParam()) && (!deferUsageWarning))
  2141. Warn(BfWarning_CS0168_VariableDeclaredButNeverUsed, StrFormat("The variable '%s' is assigned but its value is never used", localVar->mName.c_str()), localNameNode, deferFullAnalysis);
  2142. }
  2143. }
  2144. }
  2145. void BfModule::CreateRetValLocal()
  2146. {
  2147. if (mCurMethodState->mRetVal)
  2148. {
  2149. BfLocalVariable* localDef = new BfLocalVariable();
  2150. localDef->mName = "return";
  2151. localDef->mResolvedType = mCurMethodState->mRetVal.mType;
  2152. localDef->mAddr = mCurMethodState->mRetVal.mValue;
  2153. localDef->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  2154. AddLocalVariableDef(localDef);
  2155. }
  2156. else if (mCurMethodState->mRetValAddr)
  2157. {
  2158. BfLocalVariable* localDef = new BfLocalVariable();
  2159. localDef->mName = "return";
  2160. localDef->mResolvedType = CreateRefType(mCurMethodInstance->mReturnType);
  2161. localDef->mAddr = mCurMethodState->mRetValAddr;
  2162. localDef->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  2163. AddLocalVariableDef(localDef);
  2164. }
  2165. }
  2166. void BfModule::MarkDynStack(BfScopeData* scopeData)
  2167. {
  2168. auto checkScope = mCurMethodState->mCurScope;
  2169. while (true)
  2170. {
  2171. if (checkScope == scopeData)
  2172. break;
  2173. checkScope->mHadOuterDynStack = true;
  2174. checkScope = checkScope->mPrevScope;
  2175. }
  2176. }
  2177. void BfModule::SaveStackState(BfScopeData* scopeData)
  2178. {
  2179. // If we push a value on the stack that needs to survive until the end of scopeData, we need to make sure that no
  2180. // scopes within scopeData restore the stack
  2181. auto checkScope = mCurMethodState->mCurScope;
  2182. while (true)
  2183. {
  2184. if (checkScope == scopeData)
  2185. {
  2186. if ((!checkScope->mSavedStack) && (checkScope->mBlock) && (!checkScope->mIsScopeHead) && (!checkScope->mHadOuterDynStack))
  2187. {
  2188. if (mBfIRBuilder->mHasDebugInfo)
  2189. mBfIRBuilder->SaveDebugLocation();
  2190. auto prevPos = mBfIRBuilder->GetInsertBlock();
  2191. mBfIRBuilder->SetInsertPointAtStart(checkScope->mBlock);
  2192. checkScope->mSavedStack = mBfIRBuilder->CreateStackSave();
  2193. mBfIRBuilder->ClearDebugLocation(checkScope->mSavedStack);
  2194. mBfIRBuilder->SetInsertPoint(prevPos);
  2195. if (mBfIRBuilder->mHasDebugInfo)
  2196. mBfIRBuilder->RestoreDebugLocation();
  2197. }
  2198. break;
  2199. }
  2200. if (checkScope->mSavedStack)
  2201. {
  2202. for (auto usage : checkScope->mSavedStackUses)
  2203. mBfIRBuilder->EraseInstFromParent(usage);
  2204. checkScope->mSavedStackUses.Clear();
  2205. mBfIRBuilder->EraseInstFromParent(checkScope->mSavedStack);
  2206. checkScope->mSavedStack = BfIRValue();
  2207. }
  2208. checkScope = checkScope->mPrevScope;
  2209. }
  2210. }
  2211. BfIRValue BfModule::ValueScopeStart()
  2212. {
  2213. if (IsTargetingBeefBackend())
  2214. return mBfIRBuilder->CreateValueScopeStart();
  2215. return BfIRValue();
  2216. }
  2217. void BfModule::ValueScopeEnd(BfIRValue valueScopeStart)
  2218. {
  2219. if (valueScopeStart)
  2220. mBfIRBuilder->CreateValueScopeHardEnd(valueScopeStart);
  2221. }
  2222. BfProjectSet* BfModule::GetVisibleProjectSet()
  2223. {
  2224. if (mCurMethodState == NULL)
  2225. return NULL;
  2226. if (mCurMethodState->mVisibleProjectSet.IsEmpty())
  2227. {
  2228. HashSet<BfType*> seenTypes;
  2229. std::function<void(BfProject* project)> _AddProject = [&](BfProject* project)
  2230. {
  2231. if (mCurMethodState->mVisibleProjectSet.Add(project))
  2232. {
  2233. for (auto dep : project->mDependencies)
  2234. _AddProject(dep);
  2235. }
  2236. };
  2237. std::function<void(BfType* type)> _AddType = [&](BfType* type)
  2238. {
  2239. auto typeInstance = type->ToTypeInstance();
  2240. if (typeInstance == NULL)
  2241. {
  2242. if (type->IsSizedArray())
  2243. _AddType(type->GetUnderlyingType());
  2244. return;
  2245. }
  2246. if (typeInstance->IsTuple())
  2247. {
  2248. for (auto& fieldInst : typeInstance->mFieldInstances)
  2249. {
  2250. if (fieldInst.mDataIdx != -1)
  2251. _AddType(fieldInst.mResolvedType);
  2252. }
  2253. }
  2254. _AddProject(typeInstance->mTypeDef->mProject);
  2255. if (typeInstance->mGenericTypeInfo == NULL)
  2256. return;
  2257. for (auto type : typeInstance->mGenericTypeInfo->mTypeGenericArguments)
  2258. {
  2259. if (seenTypes.Add(type))
  2260. _AddType(type);
  2261. }
  2262. };
  2263. if (mCurTypeInstance != NULL)
  2264. {
  2265. _AddType(mCurTypeInstance);
  2266. if ((mContext->mCurTypeState != NULL) && (mContext->mCurTypeState->mType == mCurTypeInstance))
  2267. {
  2268. if (mContext->mCurTypeState->mCurTypeDef != NULL)
  2269. _AddProject(mContext->mCurTypeState->mCurTypeDef->mProject);
  2270. }
  2271. }
  2272. auto methodState = mCurMethodState;
  2273. while (methodState != NULL)
  2274. {
  2275. if (methodState->mMethodInstance != NULL)
  2276. {
  2277. _AddProject(methodState->mMethodInstance->mMethodDef->mDeclaringType->mProject);
  2278. if (methodState->mMethodInstance->mMethodInfoEx != NULL)
  2279. {
  2280. for (auto type : methodState->mMethodInstance->mMethodInfoEx->mMethodGenericArguments)
  2281. _AddType(type);
  2282. }
  2283. }
  2284. methodState = methodState->mPrevMethodState;
  2285. }
  2286. }
  2287. return &mCurMethodState->mVisibleProjectSet;
  2288. }
  2289. bool BfModule::IsProjectVisible(BfProject* project)
  2290. {
  2291. auto visibleProjectSet = GetVisibleProjectSet();
  2292. if (visibleProjectSet != NULL)
  2293. return visibleProjectSet->Contains(project);
  2294. auto activeTypeDef = GetActiveTypeDef();
  2295. if (activeTypeDef != NULL)
  2296. {
  2297. if (activeTypeDef->mProject == project)
  2298. return true;
  2299. return activeTypeDef->mProject->HasDependency(project);
  2300. }
  2301. return false;
  2302. }
  2303. BfFileInstance* BfModule::GetFileFromNode(BfAstNode* astNode)
  2304. {
  2305. auto bfParser = astNode->GetSourceData()->ToParserData();
  2306. if (bfParser == NULL)
  2307. return NULL;
  2308. BfFileInstance** fileInstancePtr = NULL;
  2309. if (!mFileInstanceMap.TryAdd(bfParser, NULL, &fileInstancePtr))
  2310. {
  2311. return *fileInstancePtr;
  2312. }
  2313. else
  2314. {
  2315. // It's possible two parsers have the same file name (ie: mNextRevision)
  2316. BfFileInstance** namedFileInstancePtr = NULL;
  2317. if (!mNamedFileInstanceMap.TryAdd(bfParser->mFileName, NULL, &namedFileInstancePtr))
  2318. {
  2319. auto bfFileInstance = *namedFileInstancePtr;
  2320. *fileInstancePtr = bfFileInstance;
  2321. return bfFileInstance;
  2322. }
  2323. int slashPos = (int)bfParser->mFileName.LastIndexOf(DIR_SEP_CHAR);
  2324. auto bfFileInstance = new BfFileInstance();
  2325. *fileInstancePtr = bfFileInstance;
  2326. *namedFileInstancePtr = bfFileInstance;
  2327. bfFileInstance->mPrevPosition.mFileInstance = bfFileInstance;
  2328. bfFileInstance->mParser = bfParser;
  2329. BfLogSysM("GetFileFromNode new file. Mod: %p FileInstance: %p Parser: %p\n", this, bfFileInstance, bfParser);
  2330. if ((mBfIRBuilder != NULL) && (mBfIRBuilder->DbgHasLineInfo()))
  2331. {
  2332. String fileName = bfParser->mFileName;
  2333. for (int i = 0; i < (int)fileName.length(); i++)
  2334. {
  2335. if (fileName[i] == DIR_SEP_CHAR_ALT)
  2336. fileName[i] = DIR_SEP_CHAR;
  2337. }
  2338. bfFileInstance->mDIFile = mBfIRBuilder->DbgCreateFile(fileName.Substring(slashPos + 1), fileName.Substring(0, BF_MAX(slashPos, 0)), bfParser->mMD5Hash);
  2339. }
  2340. return bfFileInstance;
  2341. }
  2342. }
  2343. void BfModule::UpdateSrcPos(BfAstNode* astNode, BfSrcPosFlags flags, int debugLocOffset)
  2344. {
  2345. // We set force to true when we MUST get the line position set (for navigation purposes, for example)
  2346. if (((mBfIRBuilder->mIgnoreWrites)) && ((flags & BfSrcPosFlag_Force) == 0))
  2347. return;
  2348. BF_ASSERT((!mAwaitingInitFinish) || (mBfIRBuilder->mIgnoreWrites));
  2349. if (astNode == NULL)
  2350. return;
  2351. auto bfParser = astNode->GetSourceData()->ToParserData();
  2352. if (bfParser == NULL)
  2353. return;
  2354. if ((mCurFilePosition.mFileInstance == NULL) || (mCurFilePosition.mFileInstance->mParser != bfParser))
  2355. {
  2356. if (mCurFilePosition.mFileInstance != NULL)
  2357. {
  2358. BF_ASSERT(mFileInstanceMap.GetCount() != 0);
  2359. mCurFilePosition.mFileInstance->mPrevPosition = mCurFilePosition;
  2360. }
  2361. auto bfFileInstance = GetFileFromNode(astNode);
  2362. if (bfFileInstance->mPrevPosition.mFileInstance != NULL)
  2363. {
  2364. mCurFilePosition = bfFileInstance->mPrevPosition;
  2365. }
  2366. else
  2367. {
  2368. mCurFilePosition.mFileInstance = bfFileInstance;
  2369. mCurFilePosition.mCurLine = 0;
  2370. mCurFilePosition.mCurColumn = 0;
  2371. mCurFilePosition.mCurSrcPos = 0;
  2372. }
  2373. }
  2374. int srcPos = astNode->GetSrcStart() + debugLocOffset;
  2375. BF_ASSERT(srcPos < bfParser->mSrcLength);
  2376. auto* jumpEntry = bfParser->mJumpTable + (srcPos / PARSER_JUMPTABLE_DIVIDE);
  2377. if (jumpEntry->mCharIdx > srcPos)
  2378. jumpEntry--;
  2379. mCurFilePosition.mCurLine = jumpEntry->mLineNum;
  2380. mCurFilePosition.mCurSrcPos = jumpEntry->mCharIdx;
  2381. mCurFilePosition.mCurColumn = 0;
  2382. while (mCurFilePosition.mCurSrcPos < srcPos)
  2383. {
  2384. if (bfParser->mSrc[mCurFilePosition.mCurSrcPos] == '\n')
  2385. {
  2386. mCurFilePosition.mCurLine++;
  2387. mCurFilePosition.mCurColumn = 0;
  2388. }
  2389. else
  2390. {
  2391. mCurFilePosition.mCurColumn++;
  2392. }
  2393. mCurFilePosition.mCurSrcPos++;
  2394. }
  2395. //TODO: if we bail on the "mCurMethodState == NULL" case then we don't get it set during type declarations
  2396. if (((flags & BfSrcPosFlag_NoSetDebugLoc) == 0) && (mBfIRBuilder->DbgHasLineInfo()) && (mCurMethodState != NULL))
  2397. {
  2398. int column = mCurFilePosition.mCurColumn + 1;
  2399. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend))
  2400. {
  2401. // Set to illegal position
  2402. column = 0;
  2403. }
  2404. if (mSetIllegalSrcPosition)
  2405. column = 0;
  2406. BfIRMDNode useDIScope = mCurMethodState->mCurScope->mDIScope;
  2407. auto wantDIFile = mCurFilePosition.mFileInstance->mDIFile;
  2408. if ((wantDIFile != mCurMethodState->mDIFile) && (mCurMethodState->mDIFile))
  2409. {
  2410. // This is from a different scope...
  2411. if (wantDIFile != mCurMethodState->mCurScope->mAltDIFile)
  2412. {
  2413. mCurMethodState->mCurScope->mAltDIFile = wantDIFile;
  2414. mCurMethodState->mCurScope->mAltDIScope = mBfIRBuilder->DbgCreateLexicalBlock(mCurMethodState->mCurScope->mDIScope, wantDIFile, mCurFilePosition.mCurLine + 1, column);
  2415. }
  2416. if (mCurMethodState->mCurScope->mAltDIScope) // This may not be set if mAltDIFile is set by a mixin
  2417. useDIScope = mCurMethodState->mCurScope->mAltDIScope;
  2418. }
  2419. else
  2420. {
  2421. if (mCurMethodState->mCurScope->mAltDIFile)
  2422. {
  2423. mCurMethodState->mCurScope->mAltDIFile = BfIRMDNode();
  2424. mCurMethodState->mCurScope->mAltDIScope = BfIRMDNode();
  2425. }
  2426. }
  2427. auto inlineAt = mCurMethodState->mCurScope->mDIInlinedAt;
  2428. if (mCurMethodState->mCrossingMixin)
  2429. inlineAt = BfIRMDNode();
  2430. if ((!useDIScope) && (mIsComptimeModule))
  2431. useDIScope = wantDIFile;
  2432. if (!useDIScope)
  2433. mBfIRBuilder->ClearDebugLocation();
  2434. else
  2435. mBfIRBuilder->SetCurrentDebugLocation(mCurFilePosition.mCurLine + 1, column, useDIScope, inlineAt);
  2436. if ((flags & BfSrcPosFlag_Expression) == 0)
  2437. mBfIRBuilder->CreateStatementStart();
  2438. }
  2439. }
  2440. void BfModule::UpdateExprSrcPos(BfAstNode* astNode, BfSrcPosFlags flags)
  2441. {
  2442. // We've turned off expr src pos (for now?)
  2443. //UpdateSrcPos(astNode, (BfSrcPosFlags)(flags | BfSrcPosFlag_Expression));
  2444. }
  2445. void BfModule::UseDefaultSrcPos(BfSrcPosFlags flags, int debugLocOffset)
  2446. {
  2447. if (mCompiler->mBfObjectTypeDef != NULL)
  2448. UpdateSrcPos(mCompiler->mBfObjectTypeDef->mTypeDeclaration, flags, debugLocOffset);
  2449. SetIllegalSrcPos();
  2450. }
  2451. void BfModule::SetIllegalSrcPos(BfSrcPosFlags flags)
  2452. {
  2453. if ((mBfIRBuilder->DbgHasInfo()) && (mCurMethodState != NULL))
  2454. {
  2455. auto curScope = mCurMethodState->mCurScope->mDIScope;
  2456. if (curScope)
  2457. {
  2458. if ((mCurMethodState->mCurScope->mDIInlinedAt) && (mCompiler->mOptions.IsCodeView()))
  2459. {
  2460. // Currently, CodeView does not record column positions so we can't use an illegal column position as an "invalid" marker
  2461. mBfIRBuilder->SetCurrentDebugLocation(0, 0, curScope, mCurMethodState->mCurScope->mDIInlinedAt);
  2462. }
  2463. else
  2464. {
  2465. // Set to whatever it previously was but at column zero, which we will know to be illegal
  2466. mBfIRBuilder->SetCurrentDebugLocation(mCurFilePosition.mCurLine + 1, 0, curScope, mCurMethodState->mCurScope->mDIInlinedAt);
  2467. }
  2468. }
  2469. if ((flags & BfSrcPosFlag_Expression) == 0)
  2470. mBfIRBuilder->CreateStatementStart();
  2471. }
  2472. }
  2473. void BfModule::SetIllegalExprSrcPos(BfSrcPosFlags flags)
  2474. {
  2475. // We've turned off expr src pos (for now?)
  2476. //SetIllegalSrcPos((BfSrcPosFlags)(flags | BfSrcPosFlag_Expression));
  2477. }
  2478. bool BfModule::CheckProtection(BfProtection protection, BfTypeDef* checkType, bool allowProtected, bool allowPrivate)
  2479. {
  2480. if ((protection == BfProtection_Public) ||
  2481. (((protection == BfProtection_Protected) || (protection == BfProtection_ProtectedInternal)) && (allowProtected)) ||
  2482. ((protection == BfProtection_Private) && (allowPrivate)))
  2483. return true;
  2484. if ((mAttributeState != NULL) && (mAttributeState->mCustomAttributes != NULL) && (mAttributeState->mCustomAttributes->Contains(mCompiler->mFriendAttributeTypeDef)))
  2485. {
  2486. mAttributeState->mUsed = true;
  2487. return true;
  2488. }
  2489. if (((protection == BfProtection_Internal) || (protection == BfProtection_ProtectedInternal)) && (checkType != NULL))
  2490. {
  2491. if (CheckInternalProtection(checkType))
  2492. return true;
  2493. }
  2494. return false;
  2495. }
  2496. void BfModule::GetAccessAllowed(BfTypeInstance* checkType, bool &allowProtected, bool &allowPrivate)
  2497. {
  2498. allowPrivate = (checkType == mCurTypeInstance) || (IsInnerType(mCurTypeInstance, checkType));
  2499. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL))
  2500. {
  2501. auto mixinOwner = mCurMethodState->mMixinState->mMixinMethodInstance->GetOwner();
  2502. allowPrivate |= (checkType == mixinOwner) || (IsInnerType(mixinOwner, checkType));
  2503. }
  2504. allowProtected = allowPrivate;
  2505. }
  2506. bool BfModule::CheckProtection(BfProtectionCheckFlags& flags, BfTypeInstance* memberOwner, BfProject* memberProject, BfProtection memberProtection, BfTypeInstance* lookupStartType)
  2507. {
  2508. if ((memberOwner != NULL) && (mCurMethodState != NULL) && (mCurMethodState->mPrivateTypeInstance == memberOwner))
  2509. return true;
  2510. if (memberProtection == BfProtection_Hidden)
  2511. return false;
  2512. if (memberProtection == BfProtection_Public)
  2513. return true;
  2514. if ((flags & BfProtectionCheckFlag_CheckedPrivate) == 0)
  2515. {
  2516. BfTypeInstance* curCheckType = mCurTypeInstance;
  2517. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL))
  2518. {
  2519. auto mixinOwner = mCurMethodState->mMixinState->mMixinMethodInstance->GetOwner();
  2520. curCheckType = mixinOwner;
  2521. }
  2522. bool allowPrivate = (curCheckType != NULL) && (memberOwner->IsInstanceOf(curCheckType->mTypeDef));
  2523. if (curCheckType != NULL)
  2524. {
  2525. allowPrivate |= IsInnerType(curCheckType->mTypeDef, memberOwner->mTypeDef);
  2526. if (memberOwner->mTypeDef->IsGlobalsContainer())
  2527. allowPrivate |= curCheckType->mTypeDef->mNamespace == memberOwner->mTypeDef->mNamespace;
  2528. }
  2529. if (allowPrivate)
  2530. flags = (BfProtectionCheckFlags)(flags | BfProtectionCheckFlag_AllowPrivate | BfProtectionCheckFlag_CheckedPrivate);
  2531. else
  2532. flags = (BfProtectionCheckFlags)(flags | BfProtectionCheckFlag_CheckedPrivate);
  2533. }
  2534. if ((flags & BfProtectionCheckFlag_AllowPrivate) != 0)
  2535. return true;
  2536. if ((memberProtection == BfProtection_Protected) || (memberProtection == BfProtection_ProtectedInternal))
  2537. {
  2538. if ((flags & BfProtectionCheckFlag_CheckedProtected) == 0)
  2539. {
  2540. bool allowProtected = false;
  2541. auto memberOwnerTypeDef = memberOwner->mTypeDef;
  2542. auto curCheckType = mCurTypeInstance;
  2543. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL))
  2544. {
  2545. auto mixinOwner = mCurMethodState->mMixinState->mMixinMethodInstance->GetOwner();
  2546. curCheckType = mixinOwner;
  2547. }
  2548. if ((flags & BfProtectionCheckFlag_InstanceLookup) != 0)
  2549. {
  2550. auto lookupCheckType = lookupStartType;
  2551. while (lookupCheckType->mInheritDepth >= curCheckType->mInheritDepth)
  2552. {
  2553. if (lookupCheckType == curCheckType)
  2554. {
  2555. allowProtected = true;
  2556. break;
  2557. }
  2558. if (lookupCheckType == memberOwner)
  2559. break;
  2560. lookupCheckType = lookupCheckType->mBaseType;
  2561. if (lookupCheckType == NULL)
  2562. break;
  2563. }
  2564. }
  2565. else
  2566. {
  2567. auto lookupCheckType = curCheckType;
  2568. while (lookupCheckType->mInheritDepth >= memberOwner->mInheritDepth)
  2569. {
  2570. if (lookupCheckType == memberOwner)
  2571. {
  2572. allowProtected = true;
  2573. break;
  2574. }
  2575. lookupCheckType = lookupCheckType->mBaseType;
  2576. if (lookupCheckType == NULL)
  2577. break;
  2578. }
  2579. }
  2580. if (!allowProtected)
  2581. {
  2582. // It's possible our outer type is derived from 'memberOwner'
  2583. while (curCheckType->mTypeDef->mNestDepth > 0)
  2584. {
  2585. curCheckType = GetOuterType(curCheckType);
  2586. if (curCheckType == NULL)
  2587. break;
  2588. auto lookupCheckType = lookupStartType;
  2589. while (lookupCheckType->mInheritDepth >= curCheckType->mInheritDepth)
  2590. {
  2591. if (lookupCheckType == curCheckType)
  2592. {
  2593. allowProtected = true;
  2594. break;
  2595. }
  2596. if (lookupCheckType == memberOwner)
  2597. break;
  2598. lookupCheckType = lookupCheckType->mBaseType;
  2599. if (lookupCheckType == NULL)
  2600. break;
  2601. }
  2602. }
  2603. }
  2604. if (allowProtected)
  2605. flags = (BfProtectionCheckFlags)(flags | BfProtectionCheckFlag_CheckedProtected | BfProtectionCheckFlag_AllowProtected);
  2606. else
  2607. flags = (BfProtectionCheckFlags)(flags | BfProtectionCheckFlag_CheckedProtected);
  2608. }
  2609. if ((flags & BfProtectionCheckFlag_AllowProtected) != 0)
  2610. return true;
  2611. }
  2612. if ((mAttributeState != NULL) && (mAttributeState->mCustomAttributes != NULL) && (mAttributeState->mCustomAttributes->Contains(mCompiler->mFriendAttributeTypeDef)))
  2613. {
  2614. mAttributeState->mUsed = true;
  2615. return true;
  2616. }
  2617. if (((memberProtection == BfProtection_Internal) || (memberProtection == BfProtection_ProtectedInternal)) && (memberOwner != NULL))
  2618. {
  2619. if (CheckInternalProtection(memberOwner->mTypeDef))
  2620. return true;
  2621. }
  2622. return false;
  2623. }
  2624. void BfModule::SetElementType(BfAstNode* astNode, BfSourceElementType elementType)
  2625. {
  2626. if (mCompiler->mResolvePassData != NULL)
  2627. {
  2628. if (auto sourceClassifier = mCompiler->mResolvePassData->GetSourceClassifier(astNode))
  2629. sourceClassifier->SetElementType(astNode, elementType);
  2630. }
  2631. }
  2632. void BfModule::SetHighestElementType(BfAstNode* astNode, BfSourceElementType elementType)
  2633. {
  2634. if (mCompiler->mResolvePassData != NULL)
  2635. {
  2636. if (auto sourceClassifier = mCompiler->mResolvePassData->GetSourceClassifier(astNode))
  2637. sourceClassifier->SetHighestElementType(astNode, elementType);
  2638. }
  2639. }
  2640. bool BfModule::PreFail()
  2641. {
  2642. if (!mIgnoreErrors)
  2643. return true;
  2644. SetFail();
  2645. return false;
  2646. }
  2647. void BfModule::SetFail()
  2648. {
  2649. if (mIgnoreErrors)
  2650. {
  2651. if (mAttributeState != NULL)
  2652. mAttributeState->mFlags = (BfAttributeState::Flags)(mAttributeState->mFlags | BfAttributeState::Flag_HadError);
  2653. }
  2654. }
  2655. void BfModule::VerifyOnDemandMethods()
  2656. {
  2657. #ifdef _DEBUG
  2658. // if (mParentModule != NULL)
  2659. // {
  2660. // BF_ASSERT(mOnDemandMethodCount == 0);
  2661. // mParentModule->VerifyOnDemandMethods();
  2662. // return;
  2663. // }
  2664. //
  2665. // int onDemandCount = 0;
  2666. // for (auto type : mOwnedTypeInstances)
  2667. // {
  2668. // auto typeInst = type->ToTypeInstance();
  2669. // for (auto& methodGroup : typeInst->mMethodInstanceGroups)
  2670. // {
  2671. // if ((methodGroup.mOnDemandKind == BfMethodOnDemandKind_NoDecl_AwaitingReference) ||
  2672. // (methodGroup.mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingReference) ||
  2673. // (methodGroup.mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingDecl) ||
  2674. // (methodGroup.mOnDemandKind == BfMethodOnDemandKind_InWorkList))
  2675. // onDemandCount++;
  2676. // }
  2677. // }
  2678. //
  2679. // BF_ASSERT(mOnDemandMethodCount == onDemandCount);
  2680. #endif
  2681. }
  2682. bool BfModule::IsSkippingExtraResolveChecks()
  2683. {
  2684. if (mIsComptimeModule)
  2685. return false;
  2686. return mCompiler->IsSkippingExtraResolveChecks();
  2687. }
  2688. bool BfModule::AddErrorContext(StringImpl& errorString, BfAstNode* refNode, BfWhileSpecializingFlags& isWhileSpecializing, bool isWarning)
  2689. {
  2690. bool isWhileSpecializingMethod = false;
  2691. if ((mIsSpecialModule) && (mModuleName == "vdata"))
  2692. errorString += StrFormat("\n while generating vdata for project '%s'", mProject->mName.c_str());
  2693. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend))
  2694. errorString += StrFormat("\n while generating append size calculating method");
  2695. else if (refNode == NULL)
  2696. {
  2697. if (mCurTypeInstance != NULL)
  2698. errorString += StrFormat("\n while compiling '%s'", TypeToString(mCurTypeInstance, BfTypeNameFlags_None).c_str());
  2699. else if (mProject != NULL)
  2700. errorString += StrFormat("\n while compiling project '%s'", mProject->mName.c_str());
  2701. }
  2702. if (mCurTypeInstance != NULL)
  2703. {
  2704. auto _CheckMethodInstance = [&](BfMethodInstance* methodInstance)
  2705. {
  2706. // Propogate the fail all the way to the main method (assuming we're in a local method or lambda)
  2707. if (isWarning)
  2708. methodInstance->mHasWarning = true;
  2709. else
  2710. methodInstance->mHasFailed = true;
  2711. if (!methodInstance->mHasStartedDeclaration)
  2712. StartMethodDeclaration(methodInstance, NULL);
  2713. bool isSpecializedMethod = ((methodInstance != NULL) && (!methodInstance->mIsUnspecialized) && (methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mMethodGenericArguments.size() != 0));
  2714. if (isSpecializedMethod)
  2715. {
  2716. //auto unspecializedMethod = &mCurMethodInstance->mMethodInstanceGroup->mMethodSpecializationMap.begin()->second;
  2717. auto unspecializedMethod = methodInstance->mMethodInstanceGroup->mDefault;
  2718. if (unspecializedMethod == methodInstance)
  2719. {
  2720. // This is a local method inside a generic method
  2721. BF_ASSERT(methodInstance->mMethodDef->mIsLocalMethod);
  2722. }
  2723. else
  2724. {
  2725. if (isWarning)
  2726. {
  2727. if (unspecializedMethod->mHasWarning)
  2728. return false; // At least SOME error has already been reported
  2729. }
  2730. else
  2731. {
  2732. if (unspecializedMethod->mHasFailed)
  2733. return false; // At least SOME error has already been reported
  2734. }
  2735. }
  2736. }
  2737. if (isSpecializedMethod)
  2738. {
  2739. errorString += StrFormat("\n while specializing method '%s'", MethodToString(methodInstance).c_str());
  2740. isWhileSpecializing = (BfWhileSpecializingFlags)(isWhileSpecializing | BfWhileSpecializingFlag_Method);
  2741. isWhileSpecializingMethod = true;
  2742. }
  2743. else if ((methodInstance != NULL) && (methodInstance->mIsForeignMethodDef))
  2744. {
  2745. errorString += StrFormat("\n while implementing default interface method '%s'", MethodToString(methodInstance).c_str());
  2746. isWhileSpecializing = (BfWhileSpecializingFlags)(isWhileSpecializing | BfWhileSpecializingFlag_Method);
  2747. isWhileSpecializingMethod = true;
  2748. }
  2749. if ((mCurTypeInstance->IsGenericTypeInstance()) && (!mCurTypeInstance->IsUnspecializedType()))
  2750. {
  2751. errorString += StrFormat("\n while specializing type '%s'", TypeToString(mCurTypeInstance).c_str());
  2752. isWhileSpecializing = (BfWhileSpecializingFlags)(isWhileSpecializing | BfWhileSpecializingFlag_Type);
  2753. }
  2754. return true;
  2755. };
  2756. bool hadMethodInstance = false;
  2757. if (mCurMethodState != NULL)
  2758. {
  2759. auto checkMethodState = mCurMethodState;
  2760. while (checkMethodState != NULL)
  2761. {
  2762. auto methodInstance = checkMethodState->mMethodInstance;
  2763. if (methodInstance == NULL)
  2764. {
  2765. checkMethodState = checkMethodState->mPrevMethodState;
  2766. continue;
  2767. }
  2768. hadMethodInstance = true;
  2769. if (!_CheckMethodInstance(methodInstance))
  2770. return false;
  2771. checkMethodState = checkMethodState->mPrevMethodState;
  2772. }
  2773. }
  2774. if ((!hadMethodInstance) && (mCurMethodInstance != NULL))
  2775. {
  2776. if (!_CheckMethodInstance(mCurMethodInstance))
  2777. return false;
  2778. }
  2779. }
  2780. if ((!isWhileSpecializing) && (mCurTypeInstance != NULL) && ((mCurTypeInstance->IsGenericTypeInstance()) && (!mCurTypeInstance->IsUnspecializedType())))
  2781. {
  2782. errorString += StrFormat("\n while specializing type '%s'", TypeToString(mCurTypeInstance).c_str());
  2783. isWhileSpecializing = (BfWhileSpecializingFlags)(isWhileSpecializing | BfWhileSpecializingFlag_Type);
  2784. }
  2785. return true;
  2786. }
  2787. BfError* BfModule::Fail(const StringImpl& error, BfAstNode* refNode, bool isPersistent, bool deferError)
  2788. {
  2789. BP_ZONE("BfModule::Fail");
  2790. if (mIgnoreErrors)
  2791. {
  2792. mHadIgnoredError = true;
  2793. if (mAttributeState != NULL)
  2794. mAttributeState->mFlags = (BfAttributeState::Flags)(mAttributeState->mFlags | BfAttributeState::Flag_HadError);
  2795. return NULL;
  2796. }
  2797. if (!mReportErrors)
  2798. {
  2799. mCompiler->mPassInstance->SilentFail();
  2800. return NULL;
  2801. }
  2802. if (refNode != NULL)
  2803. refNode = BfNodeToNonTemporary(refNode);
  2804. //BF_ASSERT(refNode != NULL);
  2805. if (mIsComptimeModule)
  2806. {
  2807. if (auto ceDbgState = GetCeDbgState())
  2808. {
  2809. // Follow normal fail path
  2810. }
  2811. else
  2812. {
  2813. mHadBuildError = true;
  2814. if ((mCompiler->mCeMachine->mCurContext != NULL) && (mCompiler->mCeMachine->mCurContext->mCurCallSource != NULL) &&
  2815. (mCompiler->mCeMachine->mCurContext->mCurCallSource->mRefNode != NULL))
  2816. {
  2817. BfError* bfError = mCompiler->mPassInstance->Fail("Comptime method generation had errors",
  2818. mCompiler->mCeMachine->mCurContext->mCurCallSource->mRefNode);
  2819. if (bfError != NULL)
  2820. mCompiler->mPassInstance->MoreInfo(error, refNode);
  2821. return bfError;
  2822. }
  2823. return NULL;
  2824. }
  2825. }
  2826. if ((mCurMethodState != NULL) && (mCurMethodState->mConstResolveState != NULL) && (mCurMethodState->mConstResolveState->mInCalcAppend))
  2827. {
  2828. mCurMethodState->mConstResolveState->mFailed = true;
  2829. return NULL;
  2830. }
  2831. if (mCurMethodInstance != NULL)
  2832. mCurMethodInstance->mHasFailed = true;
  2833. if ((mCurTypeInstance != NULL) && (mCurTypeInstance->IsUnspecializedTypeVariation()))
  2834. return NULL;
  2835. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->IsOrInUnspecializedVariation()))
  2836. return NULL; // Ignore errors on unspecialized variations, they are always dups
  2837. if (!mHadBuildError)
  2838. mHadBuildError = true;
  2839. if (mParentModule != NULL)
  2840. mParentModule->mHadBuildError = true;
  2841. if (mCurTypeInstance != NULL)
  2842. AddFailType(mCurTypeInstance);
  2843. BfLogSysM("BfModule::Fail module %p type %p %s @ %s\n", this, mCurTypeInstance, error.c_str(), (refNode != NULL) ? refNode->LocationToString().c_str() : "???");
  2844. String errorString = error;
  2845. BfWhileSpecializingFlags isWhileSpecializing = BfWhileSpecializingFlag_None;
  2846. if (!AddErrorContext(errorString, refNode, isWhileSpecializing, false))
  2847. return NULL;
  2848. BfError* bfError = NULL;
  2849. if (isWhileSpecializing)
  2850. deferError = true;
  2851. if (!mHadBuildError)
  2852. mHadBuildError = true;
  2853. // Check mixins
  2854. {
  2855. auto checkMethodState = mCurMethodState;
  2856. while (checkMethodState != NULL)
  2857. {
  2858. auto rootMixinState = checkMethodState->GetRootMixinState();
  2859. if (rootMixinState != NULL)
  2860. {
  2861. String mixinErr = StrFormat("Failed to inject mixin '%s'", MethodToString(rootMixinState->mMixinMethodInstance).c_str());
  2862. if (deferError)
  2863. bfError = mCompiler->mPassInstance->DeferFail(mixinErr, rootMixinState->mSource);
  2864. else
  2865. bfError = mCompiler->mPassInstance->Fail(mixinErr, rootMixinState->mSource);
  2866. if (bfError == NULL)
  2867. return NULL;
  2868. bfError->mIsWhileSpecializing = isWhileSpecializing;
  2869. mCompiler->mPassInstance->MoreInfo(errorString, refNode);
  2870. auto mixinState = checkMethodState->mMixinState;
  2871. while ((mixinState != NULL) && (mixinState->mPrevMixinState != NULL))
  2872. {
  2873. mCompiler->mPassInstance->MoreInfo(StrFormat("Injected from mixin '%s'", MethodToString(mixinState->mPrevMixinState->mMixinMethodInstance).c_str()), mixinState->mSource);
  2874. mixinState = mixinState->mPrevMixinState;
  2875. }
  2876. return bfError;
  2877. }
  2878. checkMethodState = checkMethodState->mPrevMethodState;
  2879. }
  2880. }
  2881. if (deferError)
  2882. bfError = mCompiler->mPassInstance->Fail(errorString, refNode);
  2883. else if (refNode == NULL)
  2884. bfError = mCompiler->mPassInstance->Fail(errorString);
  2885. else
  2886. bfError = mCompiler->mPassInstance->Fail(errorString, refNode);
  2887. if (bfError != NULL)
  2888. {
  2889. bfError->mIsWhileSpecializing = isWhileSpecializing;
  2890. bfError->mProject = mProject;
  2891. bfError->mIsPersistent = isPersistent;
  2892. if ((mCurMethodState != NULL) && (mCurMethodState->mDeferredCallEmitState != NULL) && (mCurMethodState->mDeferredCallEmitState->mCloseNode != NULL))
  2893. mCompiler->mPassInstance->MoreInfo("Error during deferred statement handling", mCurMethodState->mDeferredCallEmitState->mCloseNode);
  2894. else if ((mCurMethodState != NULL) && (mCurMethodState->mEmitRefNode != NULL))
  2895. mCompiler->mPassInstance->MoreInfo("Error in emitted code", mCurMethodState->mEmitRefNode);
  2896. }
  2897. return bfError;
  2898. }
  2899. BfError* BfModule::FailInternal(const StringImpl& error, BfAstNode* refNode)
  2900. {
  2901. if (mHadBuildError)
  2902. return NULL;
  2903. return Fail(error, refNode);
  2904. }
  2905. BfError* BfModule::FailAfter(const StringImpl& error, BfAstNode* refNode)
  2906. {
  2907. if (mIgnoreErrors)
  2908. return NULL;
  2909. if (refNode != NULL)
  2910. refNode = BfNodeToNonTemporary(refNode);
  2911. mHadBuildError = true;
  2912. BfError* bfError = mCompiler->mPassInstance->FailAfter(error, refNode);
  2913. if (bfError != NULL)
  2914. bfError->mProject = mProject;
  2915. return bfError;
  2916. }
  2917. BfError* BfModule::Warn(int warningNum, const StringImpl& warning, BfAstNode* refNode, bool isPersistent, bool showInSpecialized)
  2918. {
  2919. if (mIgnoreErrors || mIgnoreWarnings)
  2920. return NULL;
  2921. if (!mReportErrors)
  2922. {
  2923. mCompiler->mPassInstance->SilentFail();
  2924. return NULL;
  2925. }
  2926. BfAstNode* unwarnNode = refNode;
  2927. //
  2928. {
  2929. BfParentNodeEntry* parentNodeEntry = mParentNodeEntry;
  2930. while (parentNodeEntry != NULL)
  2931. {
  2932. if (auto block = BfNodeDynCast<BfBlock>(parentNodeEntry->mNode))
  2933. break;
  2934. unwarnNode = parentNodeEntry->mNode;
  2935. parentNodeEntry = parentNodeEntry->mPrev;
  2936. }
  2937. }
  2938. auto parser = unwarnNode->GetSourceData()->ToParserData();
  2939. if ((parser != NULL) && (parser->IsUnwarnedAt(unwarnNode)))
  2940. {
  2941. return NULL;
  2942. }
  2943. // Right now we're only warning on the unspecialized declarations, we may revisit this
  2944. if (mCurMethodInstance != NULL)
  2945. {
  2946. if (mCurMethodInstance->IsSpecializedGenericMethodOrType())
  2947. {
  2948. if (!showInSpecialized)
  2949. return NULL;
  2950. }
  2951. if (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend)
  2952. return NULL; // No ctorCalcAppend warnings
  2953. }
  2954. if ((mCurTypeInstance != NULL) && (mCurTypeInstance->IsSpecializedType()))
  2955. {
  2956. if (!showInSpecialized)
  2957. return NULL;
  2958. }
  2959. if (refNode != NULL)
  2960. refNode = BfNodeToNonTemporary(refNode);
  2961. String warningString = warning;
  2962. BfWhileSpecializingFlags isWhileSpecializing = BfWhileSpecializingFlag_None;
  2963. if (!AddErrorContext(warningString, refNode, isWhileSpecializing, true))
  2964. return NULL;
  2965. bool deferWarning = isWhileSpecializing != BfWhileSpecializingFlag_None;
  2966. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL))
  2967. {
  2968. // We used to bubble up warnings into the mixin injection site, BUT
  2969. // we are now assuming any relevant warnings will be given at the declaration site
  2970. return NULL;
  2971. }
  2972. if ((mCurMethodState != NULL) && (mCurMethodState->mEmitRefNode != NULL))
  2973. {
  2974. BfError* bfError = mCompiler->mPassInstance->Warn(warningNum, "Emitted code had errors", mCurMethodState->mEmitRefNode);
  2975. if (bfError != NULL)
  2976. mCompiler->mPassInstance->MoreInfo(warningString, refNode);
  2977. return bfError;
  2978. }
  2979. BfError* bfError;
  2980. if (refNode != NULL)
  2981. bfError = mCompiler->mPassInstance->WarnAt(warningNum, warningString, refNode->GetSourceData(), refNode->GetSrcStart(), refNode->GetSrcLength());
  2982. else
  2983. bfError = mCompiler->mPassInstance->Warn(warningNum, warningString);
  2984. if (bfError != NULL)
  2985. {
  2986. bfError->mIsWhileSpecializing = isWhileSpecializing;
  2987. bfError->mProject = mProject;
  2988. AddFailType(mCurTypeInstance);
  2989. mHadBuildWarning = true;
  2990. bfError->mIsPersistent = isPersistent;
  2991. if ((mCompiler->IsAutocomplete()) && (mCompiler->mResolvePassData->mAutoComplete->CheckFixit((refNode))))
  2992. {
  2993. BfParserData* parser = refNode->GetSourceData()->ToParserData();
  2994. if (parser != NULL)
  2995. {
  2996. int fileLoc = BfFixitFinder::FindLineStartBefore(refNode);
  2997. mCompiler->mResolvePassData->mAutoComplete->AddEntry(AutoCompleteEntry("fixit", StrFormat("#unwarn\tunwarn|%s|%d|#unwarn|", parser->mFileName.c_str(), fileLoc).c_str()));
  2998. if (warningNum != 0)
  2999. {
  3000. mCompiler->mResolvePassData->mAutoComplete->AddEntry(AutoCompleteEntry("fixit", StrFormat("#pragma warning disable %d\t.pragma|%s|%d||#pragma warning disable %d",
  3001. warningNum, parser->mFileName.c_str(), 0, warningNum).c_str()));
  3002. }
  3003. }
  3004. }
  3005. }
  3006. return bfError;
  3007. }
  3008. void BfModule::CheckErrorAttributes(BfTypeInstance* typeInstance, BfMethodInstance* methodInstance, BfFieldInstance* fieldInstance, BfCustomAttributes* customAttributes, BfAstNode* targetSrc)
  3009. {
  3010. if (customAttributes == NULL)
  3011. return;
  3012. auto _AddDeclarationMoreInfo = [&]()
  3013. {
  3014. if (methodInstance != NULL)
  3015. {
  3016. if (methodInstance->mMethodDef->mMethodDeclaration != NULL)
  3017. mCompiler->mPassInstance->MoreInfo(
  3018. StrFormat("See method declaration '%s'", MethodToString(methodInstance).c_str()),
  3019. methodInstance->mMethodDef->GetRefNode());
  3020. }
  3021. else
  3022. {
  3023. mCompiler->mPassInstance->MoreInfo(
  3024. StrFormat("See type declaration '%s'", TypeToString(typeInstance, BfTypeNameFlag_UseUnspecializedGenericParamNames).c_str()),
  3025. typeInstance->mTypeDef->GetRefNode());
  3026. }
  3027. };
  3028. BfIRConstHolder* constHolder = typeInstance->mConstHolder;
  3029. auto customAttribute = customAttributes->Get(mCompiler->mObsoleteAttributeTypeDef);
  3030. if ((customAttribute != NULL) && (targetSrc != NULL))
  3031. {
  3032. String err;
  3033. if (fieldInstance != NULL)
  3034. err = StrFormat("'%s' is obsolete", FieldToString(fieldInstance).c_str());
  3035. else if (methodInstance != NULL)
  3036. err = StrFormat("'%s' is obsolete", MethodToString(methodInstance).c_str());
  3037. else
  3038. err = StrFormat("'%s' is obsolete", TypeToString(typeInstance, BfTypeNameFlag_UseUnspecializedGenericParamNames).c_str());
  3039. bool isError = false;
  3040. if (customAttribute->mCtorArgs.size() >= 1)
  3041. {
  3042. auto constant = constHolder->GetConstant(customAttribute->mCtorArgs[0]);
  3043. if (constant->mTypeCode == BfTypeCode_Boolean)
  3044. {
  3045. isError = constant->mBool;
  3046. }
  3047. else if (constant->mTypeCode == BfTypeCode_StringId)
  3048. {
  3049. String* str = GetStringPoolString(customAttribute->mCtorArgs[0], constHolder);
  3050. if (str != NULL)
  3051. {
  3052. err += ":\n '";
  3053. err += *str;
  3054. err += "'";
  3055. }
  3056. if (customAttribute->mCtorArgs.size() >= 2)
  3057. {
  3058. constant = constHolder->GetConstant(customAttribute->mCtorArgs[1]);
  3059. isError = constant->mBool;
  3060. }
  3061. }
  3062. }
  3063. BfError* error = NULL;
  3064. if (isError)
  3065. error = Fail(err, targetSrc);
  3066. else
  3067. error = Warn(0, err, targetSrc, false, true);
  3068. if (error != NULL)
  3069. _AddDeclarationMoreInfo();
  3070. }
  3071. customAttribute = customAttributes->Get(mCompiler->mErrorAttributeTypeDef);
  3072. if ((customAttribute != NULL) && (!customAttribute->mCtorArgs.IsEmpty()))
  3073. {
  3074. String err;
  3075. if (fieldInstance != NULL)
  3076. err += StrFormat("Method error: '", FieldToString(fieldInstance).c_str());
  3077. else if (methodInstance != NULL)
  3078. err += StrFormat("Method error: '", MethodToString(methodInstance).c_str());
  3079. else
  3080. err += StrFormat("Type error: '", TypeToString(typeInstance, BfTypeNameFlag_UseUnspecializedGenericParamNames).c_str());
  3081. String* str = GetStringPoolString(customAttribute->mCtorArgs[0], constHolder);
  3082. if (str != NULL)
  3083. err += *str;
  3084. err += "'";
  3085. if (Fail(err, targetSrc) != NULL)
  3086. _AddDeclarationMoreInfo();
  3087. }
  3088. customAttribute = customAttributes->Get(mCompiler->mWarnAttributeTypeDef);
  3089. if ((customAttribute != NULL) && (!customAttribute->mCtorArgs.IsEmpty()) && (targetSrc != NULL))
  3090. {
  3091. String err;
  3092. if (fieldInstance != NULL)
  3093. err += StrFormat("Field warning: '", FieldToString(fieldInstance).c_str());
  3094. else if (methodInstance != NULL)
  3095. err += StrFormat("Method warning: '", MethodToString(methodInstance).c_str());
  3096. else
  3097. err += StrFormat("Type warning: '", TypeToString(typeInstance, BfTypeNameFlag_UseUnspecializedGenericParamNames).c_str());
  3098. String* str = GetStringPoolString(customAttribute->mCtorArgs[0], constHolder);
  3099. if (str != NULL)
  3100. err += *str;
  3101. err += "'";
  3102. if (Warn(0, err, targetSrc, false, true) != NULL)
  3103. _AddDeclarationMoreInfo();
  3104. }
  3105. }
  3106. void BfModule::CheckRangeError(BfType* type, BfAstNode* refNode)
  3107. {
  3108. if (mBfIRBuilder->mOpFailed)
  3109. Fail(StrFormat("Result out of range for type '%s'", TypeToString(type).c_str()), refNode);
  3110. }
  3111. void BfModule::FatalError(const StringImpl& error, const char* file, int line, int column)
  3112. {
  3113. static bool sHadFatalError = false;
  3114. static bool sHadReentrancy = false;
  3115. if (sHadFatalError)
  3116. {
  3117. return;
  3118. sHadReentrancy = true;
  3119. }
  3120. sHadFatalError = true;
  3121. String fullError = error;
  3122. if (file != NULL)
  3123. {
  3124. fullError += StrFormat(" at %s:%d", file, line);
  3125. if (column != -1)
  3126. fullError += StrFormat(":%d", column);
  3127. }
  3128. fullError += StrFormat("\nModule: %s", mModuleName.c_str());
  3129. if (mCurTypeInstance != NULL)
  3130. fullError += StrFormat("\nType: %s", TypeToString(mCurTypeInstance).c_str());
  3131. if (mCurMethodInstance != NULL)
  3132. fullError += StrFormat("\nMethod: %s", MethodToString(mCurMethodInstance).c_str());
  3133. if ((mCurFilePosition.mFileInstance != NULL) && (mCurFilePosition.mFileInstance->mParser != NULL))
  3134. fullError += StrFormat("\nSource Location: %s:%d", mCurFilePosition.mFileInstance->mParser->mFileName.c_str(), mCurFilePosition.mCurLine + 1);
  3135. if (sHadReentrancy)
  3136. fullError += "\nError had reentrancy";
  3137. BfpSystem_FatalError(fullError.c_str(), "FATAL MODULE ERROR");
  3138. }
  3139. void BfModule::FatalError(const StringImpl& error, BfFailHandleKind failHandleKind)
  3140. {
  3141. if (failHandleKind == BfFailHandleKind_Normal)
  3142. FatalError(error);
  3143. else if (failHandleKind == BfFailHandleKind_Soft)
  3144. InternalError(error);
  3145. }
  3146. void BfModule::InternalError(const StringImpl& error, BfAstNode* refNode, const char* file, int line)
  3147. {
  3148. static bool isInside = false;
  3149. if (isInside)
  3150. return;
  3151. isInside = true;
  3152. String fullError = error;
  3153. if (file != NULL)
  3154. fullError += StrFormat(" at %s:%d", file, line);
  3155. fullError += StrFormat("\nModule: %s", mModuleName.c_str());
  3156. if (mCurTypeInstance != NULL)
  3157. fullError += StrFormat("\nType: %s", TypeToString(mCurTypeInstance).c_str());
  3158. if (mCurMethodInstance != NULL)
  3159. fullError += StrFormat("\nMethod: %s", MethodToString(mCurMethodInstance).c_str());
  3160. if ((mCurFilePosition.mFileInstance != NULL) && (mCurFilePosition.mFileInstance->mParser != NULL))
  3161. fullError += StrFormat("\nSource Location: %s:%d", mCurFilePosition.mFileInstance->mParser->mFileName.c_str(), mCurFilePosition.mCurLine + 1);
  3162. Fail(String("INTERNAL ERROR: ") + fullError, refNode);
  3163. isInside = false;
  3164. }
  3165. void BfModule::NotImpl(BfAstNode* astNode)
  3166. {
  3167. Fail("INTERNAL ERROR: Not implemented", astNode);
  3168. }
  3169. bool BfModule::CheckAccessMemberProtection(BfProtection protection, BfTypeInstance* memberType)
  3170. {
  3171. bool allowPrivate = (memberType == mCurTypeInstance) || (IsInnerType(mCurTypeInstance, memberType));
  3172. if (!allowPrivate)
  3173. allowPrivate |= memberType->IsInterface();
  3174. bool allowProtected = allowPrivate;
  3175. //TODO: We had this commented out, but this makes accessing protected properties fail
  3176. if (mCurTypeInstance != NULL)
  3177. allowProtected |= TypeIsSubTypeOf(mCurTypeInstance, memberType->ToTypeInstance());
  3178. if (!CheckProtection(protection, memberType->mTypeDef, allowProtected, allowPrivate))
  3179. {
  3180. return false;
  3181. }
  3182. return true;
  3183. }
  3184. bool BfModule::CheckDefineMemberProtection(BfProtection protection, BfType* memberType)
  3185. {
  3186. // Use 'min' - exporting a 'public' from a 'private' class is really just 'private' still
  3187. protection = std::min(protection, mCurTypeInstance->mTypeDef->mProtection);
  3188. auto memberTypeInstance = memberType->ToTypeInstance();
  3189. if (memberTypeInstance == NULL)
  3190. {
  3191. auto underlyingType = memberType->GetUnderlyingType();
  3192. if (underlyingType != NULL)
  3193. return CheckDefineMemberProtection(protection, underlyingType);
  3194. return true;
  3195. }
  3196. if (memberTypeInstance->mTypeDef->mProtection < protection)
  3197. return false;
  3198. if (memberTypeInstance->IsGenericTypeInstance())
  3199. {
  3200. // When we're a generic struct, our data layout can depend on our generic parameters as well
  3201. auto genericTypeInstance = (BfTypeInstance*) memberTypeInstance;
  3202. for (auto typeGenericArg : genericTypeInstance->mGenericTypeInfo->mTypeGenericArguments)
  3203. {
  3204. if (!CheckDefineMemberProtection(protection, typeGenericArg))
  3205. return false;
  3206. }
  3207. }
  3208. return true;
  3209. }
  3210. void BfModule::AddDependency(BfType* usedType, BfType* userType, BfDependencyMap::DependencyFlags flags, BfDepContext* depContext)
  3211. {
  3212. if (usedType == userType)
  3213. return;
  3214. if (((flags & BfDependencyMap::DependencyFlag_ConstValue) != 0) && (mContext->mCurTypeState != NULL) && (mContext->mCurTypeState->mResolveKind == BfTypeState::ResolveKind_FieldType))
  3215. {
  3216. // This can be an `int32[UsedType.cVal]` type reference
  3217. flags = (BfDependencyMap::DependencyFlags)(flags | BfDependencyMap::DependencyFlag_ValueTypeSizeDep);
  3218. }
  3219. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mIsAutocompleteMethod))
  3220. {
  3221. if (userType->IsMethodRef())
  3222. {
  3223. // We cannot short-circuit dependencies because of method group ref counting
  3224. }
  3225. else
  3226. return;
  3227. }
  3228. if (usedType->IsSpecializedByAutoCompleteMethod())
  3229. {
  3230. if ((flags & (BfDependencyMap::DependencyFlag_TypeGenericArg | BfDependencyMap::DependencyFlag_MethodGenericArg |
  3231. BfDependencyMap::DependencyFlag_OuterType | BfDependencyMap::DependencyFlag_DerivedFrom)) == 0)
  3232. return;
  3233. }
  3234. // if (usedType->IsBoxed())
  3235. // {
  3236. // NOP;
  3237. // auto underlyingType = usedType->GetUnderlyingType()->ToTypeInstance();
  3238. // if ((underlyingType != NULL) && (underlyingType->IsInstanceOf(mCompiler->mSizedArrayTypeDef)))
  3239. // {
  3240. // BfLogSysM("AddDependency UsedType:%p UserType:%p Method:%p\n", usedType, userType, mCurMethodInstance);
  3241. // }
  3242. // }
  3243. // TODO: It seems this was bogus - it kept the root array from being marked as a dependency (for example)
  3244. // BfType* origUsedType = usedType;
  3245. bool isDataAccess = ((flags & (BfDependencyMap::DependencyFlag_ReadFields | BfDependencyMap::DependencyFlag_LocalUsage | BfDependencyMap::DependencyFlag_Allocates)) != 0);
  3246. // if (isDataAccess)
  3247. // {
  3248. // while (true)
  3249. // {
  3250. // if ((usedType->IsPointer()) || (usedType->IsRef()) || (usedType->IsSizedArray()))
  3251. // usedType = usedType->GetUnderlyingType();
  3252. // else if (usedType->IsArray())
  3253. // {
  3254. // usedType = ((BfTypeInstance*)usedType)->mGenericTypeInfo->mTypeGenericArguments[0];
  3255. // }
  3256. // else
  3257. // break;
  3258. // }
  3259. // }
  3260. if ((mCurMethodState != NULL) && (mCurMethodState->mHotDataReferenceBuilder != NULL) && (usedType != mCurTypeInstance) && (isDataAccess))
  3261. {
  3262. bool addType = true;
  3263. auto checkType = usedType;
  3264. PopulateType(checkType, BfPopulateType_Data);
  3265. if (checkType->IsValuelessType())
  3266. addType = false;
  3267. else if (checkType->IsPrimitiveType())
  3268. addType = false;
  3269. else
  3270. {
  3271. auto checkTypeInst = checkType->ToTypeInstance();
  3272. if (checkTypeInst == NULL)
  3273. {
  3274. addType = false;
  3275. }
  3276. else
  3277. {
  3278. if (TypeIsSubTypeOf(mCurTypeInstance, checkTypeInst))
  3279. addType = false;
  3280. }
  3281. }
  3282. if (addType)
  3283. {
  3284. auto checkTypeInst = checkType->ToTypeInstance();
  3285. if (checkTypeInst->mHotTypeData != NULL)
  3286. {
  3287. auto hotTypeVersion = checkTypeInst->mHotTypeData->GetLatestVersion();
  3288. BF_ASSERT(hotTypeVersion != NULL);
  3289. if (hotTypeVersion != NULL)
  3290. {
  3291. bool isAllocation = ((flags & BfDependencyMap::DependencyFlag_Allocates) != 0);
  3292. if (((flags & BfDependencyMap::DependencyFlag_LocalUsage) != 0) &&
  3293. (checkType->IsComposite()))
  3294. isAllocation = true;
  3295. if (isAllocation)
  3296. {
  3297. mCurMethodState->mHotDataReferenceBuilder->mAllocatedData.Add(hotTypeVersion);
  3298. }
  3299. else
  3300. mCurMethodState->mHotDataReferenceBuilder->mUsedData.Add(hotTypeVersion);
  3301. }
  3302. }
  3303. }
  3304. }
  3305. if ((!mCompiler->mIsResolveOnly) && (mIsReified))
  3306. {
  3307. auto usingModule = userType->GetModule();
  3308. BfModule* usedModule;
  3309. if (usedType->IsFunction())
  3310. {
  3311. if (mCompiler->mFunctionTypeDef != NULL)
  3312. {
  3313. auto functionType = ResolveTypeDef(mCompiler->mFunctionTypeDef)->ToTypeInstance();
  3314. usedModule = functionType->GetModule();
  3315. }
  3316. }
  3317. else
  3318. usedModule = usedType->GetModule();
  3319. if ((usingModule != NULL) && (!usingModule->mIsSpecialModule) &&
  3320. (usedModule != NULL) && (!usedModule->mIsSpecialModule))
  3321. {
  3322. if ((flags & ~(BfDependencyMap::DependencyFlag_OuterType)) == 0)
  3323. {
  3324. // Not a 'use' dependency
  3325. }
  3326. else
  3327. {
  3328. usingModule->mModuleRefs.Add(usedModule);
  3329. }
  3330. }
  3331. }
  3332. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mMethodInfoEx != NULL) && (flags != BfDependencyMap::DependencyFlag_MethodGenericArg))
  3333. {
  3334. // When we are specializing a method, usage of that specialized type is already handled with DependencyFlag_MethodGenericArg
  3335. for (auto genericArg : mCurMethodInstance->mMethodInfoEx->mMethodGenericArguments)
  3336. if (genericArg == usedType)
  3337. return;
  3338. }
  3339. auto depFlag = flags;
  3340. if ((flags & (BfDependencyMap::DependencyFlag_MethodGenericArg | BfDependencyMap::DependencyFlag_TypeGenericArg)) != 0)
  3341. {
  3342. if (usedType->IsDependendType())
  3343. {
  3344. // Cause a rebuild but not an outright deletion of the type
  3345. // We can only do this if the 'usedType' can actually hold the dependency which can actually trigger a deletion chain
  3346. depFlag = BfDependencyMap::DependencyFlag_GenericArgRef;
  3347. }
  3348. }
  3349. if (usedType->IsTypeAlias())
  3350. {
  3351. auto underlyingType = usedType->GetUnderlyingType();
  3352. if (underlyingType != NULL)
  3353. {
  3354. BfDepContext newDepContext;
  3355. if (depContext == NULL)
  3356. depContext = &newDepContext;
  3357. if (++depContext->mAliasDepth > 8)
  3358. {
  3359. if (!depContext->mDeepSeenAliases.Add(underlyingType))
  3360. return; // Circular!
  3361. }
  3362. AddDependency(underlyingType, userType, depFlag);
  3363. }
  3364. }
  3365. else if (!usedType->IsGenericTypeInstance())
  3366. {
  3367. auto underlyingType = usedType->GetUnderlyingType();
  3368. if (underlyingType != NULL)
  3369. AddDependency(underlyingType, userType, depFlag);
  3370. }
  3371. BfDependedType* checkDType = usedType->ToDependedType();
  3372. if (checkDType == NULL)
  3373. return;
  3374. if ((usedType->mRebuildFlags & BfTypeRebuildFlag_AwaitingReference) != 0)
  3375. mContext->MarkAsReferenced(checkDType);
  3376. #ifdef _DEBUG
  3377. // If a MethodRef depends ON US, that means it's a local method that we own
  3378. if (userType->IsMethodRef())
  3379. {
  3380. auto methodRefType = (BfMethodRefType*)userType;
  3381. BF_ASSERT(methodRefType->mOwner == checkDType);
  3382. }
  3383. #endif
  3384. if (!checkDType->mDependencyMap.AddUsedBy(userType, flags))
  3385. return;
  3386. if ((checkDType->IsGenericTypeInstance()) && (!userType->IsMethodRef()))
  3387. {
  3388. auto genericTypeInstance = (BfTypeInstance*) checkDType;
  3389. for (auto genericArg : genericTypeInstance->mGenericTypeInfo->mTypeGenericArguments)
  3390. {
  3391. AddDependency(genericArg, userType, depFlag);
  3392. }
  3393. }
  3394. if (checkDType->IsTuple())
  3395. {
  3396. for (auto& field : checkDType->ToTypeInstance()->mFieldInstances)
  3397. {
  3398. if (field.mDataIdx != -1)
  3399. AddDependency(field.mResolvedType, userType, depFlag);
  3400. }
  3401. }
  3402. }
  3403. void BfModule::AddDependency(BfGenericParamInstance* genericParam, BfTypeInstance* usingType)
  3404. {
  3405. if ((genericParam->mExternType != NULL) && (!genericParam->mExternType->IsGenericParam()))
  3406. AddDependency(genericParam->mExternType, mCurTypeInstance, BfDependencyMap::DependencyFlag_Constraint);
  3407. for (auto constraintTypeInst : genericParam->mInterfaceConstraints)
  3408. AddDependency(constraintTypeInst, mCurTypeInstance, BfDependencyMap::DependencyFlag_Constraint);
  3409. for (auto& operatorConstraint : genericParam->mOperatorConstraints)
  3410. {
  3411. if (operatorConstraint.mLeftType != NULL)
  3412. AddDependency(operatorConstraint.mLeftType, mCurTypeInstance, BfDependencyMap::DependencyFlag_Constraint);
  3413. if (operatorConstraint.mRightType != NULL)
  3414. AddDependency(operatorConstraint.mRightType, mCurTypeInstance, BfDependencyMap::DependencyFlag_Constraint);
  3415. }
  3416. if (genericParam->mTypeConstraint != NULL)
  3417. AddDependency(genericParam->mTypeConstraint, mCurTypeInstance, BfDependencyMap::DependencyFlag_Constraint);
  3418. }
  3419. void BfModule::AddCallDependency(BfMethodInstance* methodInstance, bool devirtualized)
  3420. {
  3421. if ((mCurMethodState != NULL) && (mCurMethodState->mHotDataReferenceBuilder != NULL))
  3422. {
  3423. if (methodInstance->mHotMethod == NULL)
  3424. CheckHotMethod(methodInstance, "");
  3425. BF_ASSERT(methodInstance->mHotMethod != NULL);
  3426. if (devirtualized)
  3427. mCurMethodState->mHotDataReferenceBuilder->mDevirtualizedCalledMethods.Add(methodInstance->mHotMethod);
  3428. else
  3429. mCurMethodState->mHotDataReferenceBuilder->mCalledMethods.Add(methodInstance->mHotMethod);
  3430. }
  3431. }
  3432. bool BfModule::IsAttribute(BfTypeInstance* typeInst)
  3433. {
  3434. auto checkTypeInst = typeInst;
  3435. while (checkTypeInst != NULL)
  3436. {
  3437. if (checkTypeInst->IsInstanceOf(mCompiler->mAttributeTypeDef))
  3438. return true;
  3439. checkTypeInst = checkTypeInst->mBaseType;
  3440. }
  3441. return false;
  3442. }
  3443. void BfModule::PopulateGlobalContainersList(const BfGlobalLookup& globalLookup)
  3444. {
  3445. if (mContext->mCurTypeState == NULL)
  3446. return;
  3447. BP_ZONE("PopulateGlobalContainersList");
  3448. BfTypeDef* userTypeDef = GetActiveTypeDef();
  3449. if (mContext->mCurTypeState->mGlobalContainerCurUserTypeDef != userTypeDef)
  3450. {
  3451. mContext->mCurTypeState->mGlobalContainers.Clear();
  3452. for (int namespaceIdx = -1; namespaceIdx < (int)userTypeDef->mNamespaceSearch.size(); namespaceIdx++)
  3453. {
  3454. BfAtomComposite findStr;
  3455. if (namespaceIdx != -1)
  3456. findStr.Reference(userTypeDef->mNamespaceSearch[namespaceIdx]);
  3457. auto typeDefItr = mSystem->mTypeDefs.TryGet(findStr);
  3458. while (typeDefItr)
  3459. {
  3460. auto typeDef = *typeDefItr;
  3461. if ((typeDef->mFullName == findStr) && (typeDef->mIsCombinedPartial) && (typeDef->IsGlobalsContainer()))
  3462. {
  3463. if (typeDef->mProject->ContainsReference(typeDef->mProject))
  3464. {
  3465. BfGlobalContainerEntry globalEntry;
  3466. globalEntry.mTypeDef = typeDef;
  3467. globalEntry.mTypeInst = NULL;
  3468. typeDef->PopulateMemberSets();
  3469. mContext->mCurTypeState->mGlobalContainers.Add(globalEntry);
  3470. }
  3471. }
  3472. else if (!typeDef->mIsPartial)
  3473. {
  3474. //break;
  3475. }
  3476. typeDefItr.MoveToNextHashMatch();
  3477. }
  3478. }
  3479. mContext->mCurTypeState->mGlobalContainerCurUserTypeDef = userTypeDef;
  3480. }
  3481. // Only create actual typeInst when we have an applicable member. This helps in keeping unused globals from
  3482. // reifing types
  3483. for (auto& globalEntry : mContext->mCurTypeState->mGlobalContainers)
  3484. {
  3485. if (globalEntry.mTypeInst == NULL)
  3486. {
  3487. bool include = false;
  3488. if (globalLookup.mKind == BfGlobalLookup::Kind_All)
  3489. include = true;
  3490. else if (globalLookup.mKind == BfGlobalLookup::Kind_Field)
  3491. {
  3492. if (globalEntry.mTypeDef->mFieldSet.ContainsWith(globalLookup.mName))
  3493. include = true;
  3494. if (globalEntry.mTypeDef->mPropertySet.ContainsWith(globalLookup.mName))
  3495. include = true;
  3496. }
  3497. else if (globalLookup.mKind == BfGlobalLookup::Kind_Method)
  3498. {
  3499. if (globalEntry.mTypeDef->mMethodSet.ContainsWith(globalLookup.mName))
  3500. include = true;
  3501. }
  3502. if (include)
  3503. {
  3504. auto type = ResolveTypeDef(globalEntry.mTypeDef);
  3505. if (type != NULL)
  3506. globalEntry.mTypeInst = type->ToTypeInstance();
  3507. }
  3508. }
  3509. }
  3510. }
  3511. BfStaticSearch* BfModule::GetStaticSearch()
  3512. {
  3513. auto activeTypeDef = GetActiveTypeDef();
  3514. BfStaticSearch* staticSearch = NULL;
  3515. if ((mCurTypeInstance != NULL) && (mCurTypeInstance->mStaticSearchMap.TryGetValue(activeTypeDef, &staticSearch)))
  3516. return staticSearch;
  3517. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mStaticSearchMap.TryGetValue(activeTypeDef, &staticSearch)))
  3518. return staticSearch;
  3519. return NULL;
  3520. }
  3521. BfInternalAccessSet* BfModule::GetInternalAccessSet()
  3522. {
  3523. auto activeTypeDef = GetActiveTypeDef();
  3524. BfInternalAccessSet* internalAccessSet = NULL;
  3525. if ((mCurTypeInstance != NULL) && (mCurTypeInstance->mInternalAccessMap.TryGetValue(activeTypeDef, &internalAccessSet)))
  3526. return internalAccessSet;
  3527. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mInternalAccessMap.TryGetValue(activeTypeDef, &internalAccessSet)))
  3528. return internalAccessSet;
  3529. return NULL;
  3530. }
  3531. bool BfModule::CheckInternalProtection(BfTypeDef* usingTypeDef)
  3532. {
  3533. if ((mCurTypeInstance != NULL) && (mCurTypeInstance->IsSpecializedType()))
  3534. return true;
  3535. if ((mCurMethodInstance != NULL) &&
  3536. ((mCurMethodInstance->mIsUnspecializedVariation) || (mCurMethodInstance->IsSpecializedGenericMethod())))
  3537. return true;
  3538. auto internalAccessSet = GetInternalAccessSet();
  3539. if (internalAccessSet == NULL)
  3540. return false;
  3541. for (auto& nameComposite : internalAccessSet->mNamespaces)
  3542. {
  3543. if (usingTypeDef->mNamespace.StartsWith(nameComposite))
  3544. return true;
  3545. }
  3546. for (auto internalType : internalAccessSet->mTypes)
  3547. {
  3548. auto checkTypeDef = usingTypeDef->GetDefinition();
  3549. while (checkTypeDef != NULL)
  3550. {
  3551. if (checkTypeDef == internalType->mTypeDef->GetDefinition())
  3552. return true;
  3553. checkTypeDef = checkTypeDef->mOuterType;
  3554. }
  3555. }
  3556. return false;
  3557. }
  3558. void PrintUsers(llvm::MDNode* md);
  3559. BfModuleOptions BfModule::GetModuleOptions()
  3560. {
  3561. if (mIsScratchModule)
  3562. return BfModuleOptions();
  3563. if (mModuleOptions != NULL)
  3564. return *mModuleOptions;
  3565. BfModuleOptions moduleOptions;
  3566. moduleOptions.mEmitDebugInfo = mCompiler->mOptions.mEmitDebugInfo ? 1 : mCompiler->mOptions.mEmitLineInfo ? 2 : 0;
  3567. if (mProject != NULL)
  3568. {
  3569. moduleOptions.mSIMDSetting = mProject->mCodeGenOptions.mSIMDSetting;
  3570. moduleOptions.mOptLevel = mProject->mCodeGenOptions.mOptLevel;
  3571. }
  3572. auto headModule = this;
  3573. while (headModule->mParentModule != NULL)
  3574. headModule = headModule->mParentModule;
  3575. BF_ASSERT((headModule->mOwnedTypeInstances.size() > 0) || (mModuleName == "vdata") || mIsSpecialModule);
  3576. if (headModule->mOwnedTypeInstances.size() > 0)
  3577. {
  3578. auto typeInst = headModule->mOwnedTypeInstances[0];
  3579. if (typeInst->mTypeOptionsIdx == -2)
  3580. PopulateType(typeInst);
  3581. if (typeInst->mTypeOptionsIdx != -1)
  3582. {
  3583. auto typeOptions = mSystem->GetTypeOptions(typeInst->mTypeOptionsIdx);
  3584. moduleOptions.mSIMDSetting = (BfSIMDSetting)BfTypeOptions::Apply((int)moduleOptions.mSIMDSetting, typeOptions->mSIMDSetting);
  3585. moduleOptions.mEmitDebugInfo = BfTypeOptions::Apply(moduleOptions.mEmitDebugInfo, typeOptions->mEmitDebugInfo);
  3586. moduleOptions.mOptLevel = (BfOptLevel)BfTypeOptions::Apply((int)moduleOptions.mOptLevel, (int)typeOptions->mOptimizationLevel);
  3587. }
  3588. }
  3589. return moduleOptions;
  3590. }
  3591. BfCheckedKind BfModule::GetDefaultCheckedKind()
  3592. {
  3593. if ((mCurMethodState != NULL) && (mCurMethodState->mDisableChecks))
  3594. return BfCheckedKind_Unchecked;
  3595. bool runtimeChecks = mCompiler->mOptions.mRuntimeChecks;
  3596. auto typeOptions = GetTypeOptions();
  3597. if (typeOptions != NULL)
  3598. runtimeChecks = typeOptions->Apply(runtimeChecks, BfOptionFlags_RuntimeChecks);
  3599. return runtimeChecks ? BfCheckedKind_Checked : BfCheckedKind_Unchecked;
  3600. }
  3601. void BfModule::AddFailType(BfTypeInstance* typeInstance)
  3602. {
  3603. BF_ASSERT(typeInstance != NULL);
  3604. if ((typeInstance->mRebuildFlags & BfTypeRebuildFlag_InFailTypes) != 0)
  3605. return;
  3606. typeInstance->mRebuildFlags = (BfTypeRebuildFlags)(typeInstance->mRebuildFlags | BfTypeRebuildFlag_InFailTypes);
  3607. mContext->mFailTypes.TryAdd(typeInstance, BfFailKind_Normal);
  3608. }
  3609. void BfModule::DeferRebuildType(BfTypeInstance* typeInstance)
  3610. {
  3611. if ((typeInstance->mRebuildFlags & BfTypeRebuildFlag_RebuildQueued) != 0)
  3612. return;
  3613. mCompiler->mHasQueuedTypeRebuilds = true;
  3614. typeInstance->mRebuildFlags = (BfTypeRebuildFlags)(typeInstance->mRebuildFlags | BfTypeRebuildFlag_RebuildQueued);
  3615. AddFailType(typeInstance);
  3616. }
  3617. void BfModule::CheckAddFailType()
  3618. {
  3619. //TODO: We removed this line, because failures in resolve-only generic method can occur in non-owning modules
  3620. // but we still need to add the owning type to the FailTypes list
  3621. //.. OLD:
  3622. // While we're inlining, it's possible that mCurTypeInstance belongs to another module, ignore it
  3623. /*if (mCurTypeInstance->mModule != this)
  3624. return;*/
  3625. // Using mHadBuildWarning to insert into mFailTypes is our core of our strategy for reasserting
  3626. // warnings on rebuilds where otherwise the warnings wouldn't be generated because no code was
  3627. // being recompiled. This forces types with warnings to be recompiled.
  3628. // We had this 'mIsResolveOnly' check for speed in resolveOnly, but we removed it so the IDE can be
  3629. // constantly warning-aware
  3630. if ((mHadBuildError) ||
  3631. (mHadBuildWarning /*&& !mCompiler->mIsResolveOnly*/))
  3632. {
  3633. //mContext->mFailTypes.Add(mCurTypeInstance);
  3634. }
  3635. }
  3636. void BfModule::MarkDerivedDirty(BfTypeInstance* typeInst)
  3637. {
  3638. if (!mCompiler->IsHotCompile())
  3639. return;
  3640. typeInst->mDirty = true;
  3641. for (auto& dep : typeInst->mDependencyMap)
  3642. {
  3643. auto depType = dep.mKey;
  3644. auto depFlags = dep.mValue.mFlags;
  3645. if ((depFlags & BfDependencyMap::DependencyFlag_DerivedFrom) != 0)
  3646. {
  3647. MarkDerivedDirty(depType->ToTypeInstance());
  3648. }
  3649. }
  3650. }
  3651. void BfModule::CreateStaticField(BfFieldInstance* fieldInstance, bool isThreadLocal)
  3652. {
  3653. auto fieldType = fieldInstance->GetResolvedType();
  3654. auto field = fieldInstance->GetFieldDef();
  3655. if (fieldType->IsVar())
  3656. return;
  3657. BfIRValue initValue;
  3658. if (field->mIsConst)
  3659. {
  3660. if (fieldType->IsPointer())
  3661. fieldType = fieldType->GetUnderlyingType();
  3662. }
  3663. BfIRStorageKind storageKind = BfIRStorageKind_Normal;
  3664. if ((fieldInstance->mCustomAttributes != NULL) && (fieldInstance->mCustomAttributes->Get(mCompiler->mExportAttributeTypeDef)))
  3665. storageKind = BfIRStorageKind_Export;
  3666. else if ((fieldInstance->mCustomAttributes != NULL) && (fieldInstance->mCustomAttributes->Get(mCompiler->mImportAttributeTypeDef)))
  3667. storageKind = BfIRStorageKind_Import;
  3668. if ((!field->mIsExtern) && (storageKind != BfIRStorageKind_Import))
  3669. initValue = GetDefaultValue(fieldType);
  3670. if (fieldInstance->mOwner->IsUnspecializedType())
  3671. {
  3672. // Placeholder
  3673. auto ptrVal = CreatePointerType(fieldType);
  3674. mStaticFieldRefs[fieldInstance] = GetDefaultValue(ptrVal);
  3675. }
  3676. else
  3677. {
  3678. BfLogSysM("Creating static field Module:%p Type:%p\n", this, fieldType);
  3679. StringT<4096> staticVarName;
  3680. BfMangler::Mangle(staticVarName, mCompiler->GetMangleKind(), fieldInstance);
  3681. if ((!fieldType->IsValuelessType()) && (!staticVarName.StartsWith("#")))
  3682. {
  3683. BfIRType irType;
  3684. if ((fieldInstance->IsAppendedObject()) && (!field->mIsStatic))
  3685. {
  3686. irType = mBfIRBuilder->MapTypeInst(fieldType->ToTypeInstance(), BfIRPopulateType_Eventually_Full);
  3687. initValue = mBfIRBuilder->CreateConstAggZero(irType);
  3688. }
  3689. else
  3690. irType = mBfIRBuilder->MapType(fieldType, BfIRPopulateType_Eventually_Full);
  3691. if (fieldType->mSize > 0)
  3692. {
  3693. BfIRValue globalVar = mBfIRBuilder->CreateGlobalVariable(
  3694. irType,
  3695. false,
  3696. BfIRLinkageType_External,
  3697. initValue,
  3698. staticVarName,
  3699. isThreadLocal);
  3700. mBfIRBuilder->GlobalVar_SetAlignment(globalVar, fieldType->mAlign);
  3701. if (storageKind != BfIRStorageKind_Normal)
  3702. mBfIRBuilder->GlobalVar_SetStorageKind(globalVar, storageKind);
  3703. BF_ASSERT(globalVar);
  3704. mStaticFieldRefs[fieldInstance] = globalVar;
  3705. }
  3706. }
  3707. }
  3708. }
  3709. void BfModule::ResolveConstField(BfTypeInstance* typeInstance, BfFieldInstance* fieldInstance, BfFieldDef* fieldDef, bool forceResolve)
  3710. {
  3711. bool autoCompleteOnly = mCompiler->IsAutocomplete();
  3712. BfType* fieldType = NULL;
  3713. if (fieldInstance != NULL)
  3714. {
  3715. fieldType = fieldInstance->GetResolvedType();
  3716. if (fieldType == NULL)
  3717. fieldType = ResolveTypeRef(fieldDef->mTypeRef);
  3718. }
  3719. else
  3720. {
  3721. BF_ASSERT(mCompiler->IsAutocomplete());
  3722. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  3723. if ((typeInstance->IsEnum()) && (fieldDef->mTypeRef == NULL))
  3724. {
  3725. fieldType = typeInstance;
  3726. }
  3727. else
  3728. {
  3729. auto isLet = (fieldDef->mTypeRef != NULL) && (fieldDef->mTypeRef->IsExact<BfLetTypeReference>());
  3730. auto isVar = (fieldDef->mTypeRef != NULL) && (fieldDef->mTypeRef->IsExact<BfVarTypeReference>());
  3731. if (isLet || isVar)
  3732. fieldType = GetPrimitiveType(BfTypeCode_Var);
  3733. else
  3734. fieldType = ResolveTypeRef(fieldDef->mTypeRef, BfPopulateType_Identity, BfResolveTypeRefFlag_AllowInferredSizedArray);
  3735. if (fieldType == NULL)
  3736. fieldType = mContext->mBfObjectType;
  3737. }
  3738. }
  3739. if ((fieldInstance != NULL) && (fieldInstance->mConstIdx != -1) && (!forceResolve))
  3740. return;
  3741. if (mContext->mFieldResolveReentrys.size() > 1)
  3742. {
  3743. if (mContext->mFieldResolveReentrys.IndexOf(fieldInstance, 1) != -1)
  3744. {
  3745. String failStr = "Circular data reference detected between the following fields:";
  3746. for (int i = 1; i < (int)mContext->mFieldResolveReentrys.size(); i++)
  3747. {
  3748. if (i > 1)
  3749. failStr += ",";
  3750. failStr += "\n '" + TypeToString(typeInstance) + "." + mContext->mFieldResolveReentrys[i]->GetFieldDef()->mName + "'";
  3751. }
  3752. BfError* err = Fail(failStr, fieldDef->mFieldDeclaration);
  3753. if (err)
  3754. err->mIsPersistent = true;
  3755. return;
  3756. }
  3757. }
  3758. mContext->mFieldResolveReentrys.push_back(fieldInstance);
  3759. AutoPopBack<decltype (mContext->mFieldResolveReentrys)> popTypeResolveReentry(&mContext->mFieldResolveReentrys);
  3760. if (fieldInstance == NULL)
  3761. popTypeResolveReentry.Pop();
  3762. auto typeDef = typeInstance->mTypeDef;
  3763. BfIRValue constValue;
  3764. if (fieldDef->mIsExtern)
  3765. {
  3766. if (!fieldDef->mTypeRef->IsA<BfPointerTypeRef>())
  3767. {
  3768. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  3769. Fail("Extern consts must be pointer types", fieldDef->mTypeRef);
  3770. }
  3771. if (fieldDef->GetInitializer() != NULL)
  3772. {
  3773. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  3774. Fail("Extern consts cannot have initializers", fieldDef->GetNameNode());
  3775. }
  3776. }
  3777. else if (fieldDef->GetInitializer() == NULL)
  3778. {
  3779. if (fieldDef->IsEnumCaseEntry())
  3780. {
  3781. if (typeInstance->IsTypedPrimitive())
  3782. {
  3783. BfFieldInstance* prevFieldInstance = NULL;
  3784. for (int i = fieldDef->mIdx - 1; i >= 0; i--)
  3785. {
  3786. BfFieldInstance* checkFieldInst = &typeInstance->mFieldInstances[i];
  3787. if (checkFieldInst->GetFieldDef()->IsEnumCaseEntry())
  3788. {
  3789. prevFieldInstance = checkFieldInst;
  3790. break;
  3791. }
  3792. }
  3793. if (prevFieldInstance == NULL)
  3794. constValue = GetConstValue(0, typeInstance);
  3795. else
  3796. {
  3797. ResolveConstField(typeInstance, prevFieldInstance, prevFieldInstance->GetFieldDef());
  3798. if (prevFieldInstance->mConstIdx == -1)
  3799. {
  3800. if (!mCompiler->IsAutocomplete())
  3801. AssertErrorState();
  3802. constValue = GetConstValue(0, typeInstance);
  3803. }
  3804. else
  3805. {
  3806. auto prevConstant = ConstantToCurrent(typeInstance->mConstHolder->GetConstantById(prevFieldInstance->mConstIdx), typeInstance->mConstHolder, typeInstance);
  3807. constValue = mBfIRBuilder->CreateAdd(prevConstant, GetConstValue(1, typeInstance));
  3808. }
  3809. }
  3810. }
  3811. }
  3812. else
  3813. {
  3814. Fail("Const requires initializer", fieldDef->GetNameNode());
  3815. }
  3816. }
  3817. else if (mBfIRBuilder != NULL)
  3818. {
  3819. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  3820. SetAndRestoreValue<bool> prevIgnoreWrite(mBfIRBuilder->mIgnoreWrites, true);
  3821. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, NULL);
  3822. BfMethodState methodState;
  3823. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  3824. methodState.mTempKind = BfMethodState::TempKind_Static;
  3825. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  3826. if ((fieldType->IsVar()) || (fieldType->IsUndefSizedArray()))
  3827. {
  3828. auto initValue = GetFieldInitializerValue(fieldInstance, fieldDef->GetInitializer(), fieldDef, fieldType);
  3829. if (!initValue)
  3830. {
  3831. AssertErrorState();
  3832. initValue = GetDefaultTypedValue(mContext->mBfObjectType);
  3833. }
  3834. if (fieldInstance != NULL)
  3835. {
  3836. if (fieldType->IsUndefSizedArray())
  3837. {
  3838. if ((initValue.mType->IsSizedArray()) && (initValue.mType->GetUnderlyingType() == fieldType->GetUnderlyingType()))
  3839. {
  3840. fieldInstance->mResolvedType = initValue.mType;
  3841. }
  3842. }
  3843. else
  3844. fieldInstance->mResolvedType = initValue.mType;
  3845. }
  3846. constValue = initValue.mValue;
  3847. }
  3848. else
  3849. {
  3850. auto uncastedInitValue = GetFieldInitializerValue(fieldInstance, fieldDef->GetInitializer(), fieldDef, fieldType);
  3851. constValue = uncastedInitValue.mValue;
  3852. }
  3853. if ((mCurTypeInstance->IsPayloadEnum()) && (fieldDef->IsEnumCaseEntry()))
  3854. {
  3855. // Illegal
  3856. constValue = BfIRValue();
  3857. }
  3858. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  3859. }
  3860. if (fieldInstance != NULL)
  3861. {
  3862. fieldType = fieldInstance->GetResolvedType();
  3863. if ((fieldType == NULL) || (fieldType->IsVar()))
  3864. {
  3865. SetAndRestoreValue<bool> prevIgnoreWrite(mBfIRBuilder->mIgnoreWrites, true);
  3866. AssertErrorState();
  3867. // Default const type is 'int'
  3868. BfTypedValue initValue = GetDefaultTypedValue(GetPrimitiveType(BfTypeCode_IntPtr));
  3869. if (fieldInstance != NULL)
  3870. {
  3871. fieldInstance->mResolvedType = initValue.mType;
  3872. }
  3873. constValue = initValue.mValue;
  3874. }
  3875. if ((constValue) && (fieldInstance->mConstIdx == -1))
  3876. {
  3877. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  3878. CurrentAddToConstHolder(constValue);
  3879. fieldInstance->mConstIdx = constValue.mId;
  3880. }
  3881. }
  3882. }
  3883. BfType* BfModule::ResolveVarFieldType(BfTypeInstance* typeInstance, BfFieldInstance* fieldInstance, BfFieldDef* field)
  3884. {
  3885. bool isDeclType = (field->mFieldDeclaration != NULL) && BfNodeDynCastExact<BfExprModTypeRef>(field->mTypeRef) != NULL;
  3886. auto fieldType = fieldInstance->GetResolvedType();
  3887. if ((field->mIsConst) && (!isDeclType))
  3888. {
  3889. ResolveConstField(typeInstance, fieldInstance, field);
  3890. return fieldInstance->GetResolvedType();
  3891. }
  3892. bool staticOnly = (field->mIsStatic) && (!isDeclType);
  3893. if (!fieldInstance->mIsInferredType)
  3894. return fieldType;
  3895. if ((!fieldType->IsVar()) && (!fieldType->IsUndefSizedArray()))
  3896. return fieldType;
  3897. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  3898. BfTypeState typeState(mCurTypeInstance, mContext->mCurTypeState);
  3899. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState, mContext->mCurTypeState->mType != typeInstance);
  3900. auto typeDef = typeInstance->mTypeDef;
  3901. if ((!field->mIsStatic) && (typeDef->mIsStatic))
  3902. {
  3903. AssertErrorState();
  3904. return fieldType;
  3905. }
  3906. bool hadInferenceCycle = false;
  3907. if (mContext->mFieldResolveReentrys.size() > 1)
  3908. {
  3909. if (mContext->mFieldResolveReentrys.IndexOf(fieldInstance, 1) != -1)
  3910. {
  3911. for (int i = 1; i < (int)mContext->mFieldResolveReentrys.size(); i++)
  3912. {
  3913. auto fieldInst = mContext->mFieldResolveReentrys[i];
  3914. auto fieldDef = fieldInst->GetFieldDef();
  3915. auto fieldOwner = fieldInst->mOwner;
  3916. auto fieldModule = fieldOwner->mModule;
  3917. SetAndRestoreValue<bool> prevIgnoreError(fieldModule->mIgnoreErrors, false);
  3918. fieldModule->Fail(StrFormat("Field '%s.%s' creates a type inference cycle", TypeToString(fieldOwner).c_str(), fieldDef->mName.c_str()), fieldDef->mTypeRef, true);
  3919. }
  3920. return fieldType;
  3921. }
  3922. }
  3923. mContext->mFieldResolveReentrys.push_back(fieldInstance);
  3924. AutoPopBack<decltype (mContext->mFieldResolveReentrys)> popTypeResolveReentry(&mContext->mFieldResolveReentrys);
  3925. SetAndRestoreValue<bool> prevResolvingVar(typeInstance->mResolvingVarField, true);
  3926. SetAndRestoreValue<bool> prevCtxResolvingVar(mContext->mResolvingVarField, true);
  3927. if ((field->GetInitializer() == NULL) && (!isDeclType))
  3928. {
  3929. if ((field->mTypeRef->IsA<BfVarTypeReference>()) || (field->mTypeRef->IsA<BfLetTypeReference>()))
  3930. Fail("Implicitly-typed fields must be initialized", field->GetRefNode());
  3931. return fieldType;
  3932. }
  3933. BfType* resolvedType = NULL;
  3934. if (!hadInferenceCycle)
  3935. {
  3936. BfTypeState typeState;
  3937. typeState.mPrevState = mContext->mCurTypeState;
  3938. typeState.mType = typeInstance;
  3939. typeState.mCurFieldDef = field;
  3940. typeState.mResolveKind = BfTypeState::ResolveKind_ResolvingVarType;
  3941. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  3942. SetAndRestoreValue<bool> prevIgnoreWrite(mBfIRBuilder->mIgnoreWrites, true);
  3943. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, NULL/*ctorMethod.mMethodInstance*/);
  3944. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  3945. BfMethodState methodState;
  3946. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  3947. methodState.mTempKind = staticOnly ? BfMethodState::TempKind_Static : BfMethodState::TempKind_NonStatic;
  3948. if (!staticOnly)
  3949. {
  3950. //BfLocalVariable localVar;
  3951. //methodState.mLocals.push_back(localVar);
  3952. }
  3953. if (isDeclType)
  3954. {
  3955. auto fieldDef = fieldInstance->GetFieldDef();
  3956. resolvedType = ResolveTypeRef(fieldDef->mTypeRef, BfPopulateType_Identity);
  3957. }
  3958. else
  3959. {
  3960. BfTypedValue valueFromExpr;
  3961. valueFromExpr = GetFieldInitializerValue(fieldInstance);
  3962. FixIntUnknown(valueFromExpr);
  3963. if (fieldType->IsUndefSizedArray())
  3964. {
  3965. if ((valueFromExpr.mType != NULL) && (valueFromExpr.mType->IsSizedArray()) && (valueFromExpr.mType->GetUnderlyingType() == fieldType->GetUnderlyingType()))
  3966. resolvedType = valueFromExpr.mType;
  3967. }
  3968. else
  3969. resolvedType = valueFromExpr.mType;
  3970. }
  3971. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  3972. }
  3973. if (resolvedType == NULL)
  3974. return fieldType;
  3975. fieldInstance->SetResolvedType(resolvedType);
  3976. if (field->mIsStatic)
  3977. {
  3978. }
  3979. else if (fieldInstance->mDataIdx >= 0)
  3980. {
  3981. }
  3982. else
  3983. {
  3984. BF_ASSERT(typeInstance->IsIncomplete());
  3985. }
  3986. return resolvedType;
  3987. }
  3988. void BfModule::MarkFieldInitialized(BfFieldInstance* fieldInstance)
  3989. {
  3990. BF_ASSERT(fieldInstance->mOwner == mCurTypeInstance);
  3991. auto fieldType = fieldInstance->GetResolvedType();
  3992. if ((fieldInstance->mMergedDataIdx != -1) && (mCurMethodState != NULL))
  3993. {
  3994. int fieldIdx = 0;
  3995. int fieldCount = 0;
  3996. fieldInstance->GetDataRange(fieldIdx, fieldCount);
  3997. fieldIdx--;
  3998. int count = fieldCount;
  3999. if (fieldIdx == -1)
  4000. count = 1;
  4001. //TODO: Under what circumstances could 'thisVariable' be NULL?
  4002. auto thisVariable = GetThisVariable();
  4003. if (thisVariable != NULL)
  4004. {
  4005. for (int i = 0; i < count; i++)
  4006. mCurMethodState->LocalDefined(thisVariable, fieldIdx + i);
  4007. }
  4008. }
  4009. }
  4010. bool BfModule::IsThreadLocal(BfFieldInstance * fieldInstance)
  4011. {
  4012. if (fieldInstance->mCustomAttributes == NULL)
  4013. return false;
  4014. auto fieldDef = fieldInstance->GetFieldDef();
  4015. if (!fieldDef->mIsStatic)
  4016. return false;
  4017. bool isThreadLocal = false;
  4018. if (fieldInstance->mCustomAttributes != NULL)
  4019. {
  4020. for (auto customAttr : fieldInstance->mCustomAttributes->mAttributes)
  4021. {
  4022. if (customAttr.mType->ToTypeInstance()->IsInstanceOf(mCompiler->mThreadStaticAttributeTypeDef))
  4023. return true;
  4024. }
  4025. }
  4026. return false;
  4027. }
  4028. BfTypedValue BfModule::GetFieldInitializerValue(BfFieldInstance* fieldInstance, BfExpression* initializer, BfFieldDef* fieldDef, BfType* fieldType, bool doStore)
  4029. {
  4030. if (fieldDef == NULL)
  4031. fieldDef = fieldInstance->GetFieldDef();
  4032. if (fieldType == NULL)
  4033. fieldType = fieldInstance->GetResolvedType();
  4034. if (initializer == NULL)
  4035. {
  4036. if (fieldDef == NULL)
  4037. return BfTypedValue();
  4038. initializer = fieldDef->GetInitializer();
  4039. }
  4040. BfTypedValue staticVarRef;
  4041. BfTypedValue result;
  4042. if (initializer == NULL)
  4043. {
  4044. result = GetDefaultTypedValue(fieldInstance->mResolvedType);
  4045. }
  4046. else
  4047. {
  4048. if (mCompiler->mIsResolveOnly)
  4049. {
  4050. if (auto sourceClassifier = mCompiler->mResolvePassData->GetSourceClassifier(initializer))
  4051. {
  4052. sourceClassifier->SetElementType(initializer, BfSourceElementType_Normal);
  4053. sourceClassifier->VisitChildNoRef(initializer);
  4054. }
  4055. }
  4056. if ((mCurTypeInstance->IsPayloadEnum()) && (fieldDef->IsEnumCaseEntry()))
  4057. {
  4058. Fail("Enums with payloads cannot have explicitly-defined discriminators", initializer);
  4059. BfConstResolver constResolver(this);
  4060. constResolver.Resolve(initializer);
  4061. return GetDefaultTypedValue(fieldType);
  4062. }
  4063. else if (mCurTypeInstance->IsUnspecializedTypeVariation())
  4064. {
  4065. return GetDefaultTypedValue(fieldType);
  4066. }
  4067. else if (fieldDef->mIsConst)
  4068. {
  4069. int ceExecuteId = -1;
  4070. if (mCompiler->mCeMachine != NULL)
  4071. ceExecuteId = mCompiler->mCeMachine->mExecuteId;
  4072. BfTypeState typeState;
  4073. typeState.mType = mCurTypeInstance;
  4074. typeState.mCurTypeDef = fieldDef->mDeclaringType;
  4075. typeState.mCurFieldDef = fieldDef;
  4076. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  4077. BfConstResolver constResolver(this);
  4078. if (fieldType->IsVar())
  4079. return constResolver.Resolve(initializer);
  4080. else
  4081. {
  4082. BfConstResolveFlags resolveFlags = BfConstResolveFlag_None;
  4083. if ((mCompiler->mResolvePassData != NULL) && (mCurTypeInstance->IsEnum()) && (fieldDef->IsEnumCaseEntry()) &&
  4084. (mCompiler->mResolvePassData->mAutoCompleteTempTypes.Contains(fieldDef->mDeclaringType)))
  4085. {
  4086. // We avoid doing the cast here because the value we're typing may not be in the range of the current
  4087. // auto-created underlying type and it will cause an 'error flash'. We defer errors until the full resolve for that purpose
  4088. resolveFlags = BfConstResolveFlag_NoCast;
  4089. }
  4090. if ((mCurTypeInstance->IsEnum()) && (fieldDef->IsEnumCaseEntry()))
  4091. resolveFlags = (BfConstResolveFlags)(resolveFlags | BfConstResolveFlag_NoConversionOperator | BfConstResolveFlag_ExplicitCast);
  4092. UpdateSrcPos(initializer);
  4093. auto result = constResolver.Resolve(initializer, fieldType, resolveFlags);
  4094. if ((mCompiler->mCeMachine != NULL) && (fieldInstance != NULL))
  4095. {
  4096. if (mCompiler->mCeMachine->mExecuteId != ceExecuteId)
  4097. fieldInstance->mHadConstEval = true;
  4098. }
  4099. if (auto autoComplete = mCompiler->GetAutoComplete())
  4100. autoComplete->CheckResult(initializer, result);
  4101. return result;
  4102. }
  4103. }
  4104. BfExprEvaluator exprEvaluator(this);
  4105. if (doStore)
  4106. {
  4107. staticVarRef = ReferenceStaticField(fieldInstance);
  4108. exprEvaluator.mReceivingValue = &staticVarRef;
  4109. }
  4110. if (fieldType->IsDeleting())
  4111. {
  4112. mCompiler->RequestExtraCompile();
  4113. InternalError("Field using deleted type", fieldDef->GetRefNode());
  4114. }
  4115. else if (fieldType->IsVar())
  4116. result = CreateValueFromExpression(exprEvaluator, initializer, NULL, (BfEvalExprFlags)(BfEvalExprFlags_NoValueAddr | BfEvalExprFlags_FieldInitializer));
  4117. else
  4118. result = CreateValueFromExpression(exprEvaluator, initializer, fieldType, (BfEvalExprFlags)(BfEvalExprFlags_NoValueAddr | BfEvalExprFlags_FieldInitializer));
  4119. if (doStore)
  4120. {
  4121. if (exprEvaluator.mReceivingValue == NULL)
  4122. doStore = false; // Already stored
  4123. }
  4124. }
  4125. if (fieldInstance != NULL)
  4126. MarkFieldInitialized(fieldInstance);
  4127. if ((doStore) && (result))
  4128. {
  4129. if (fieldInstance->mResolvedType->IsUndefSizedArray())
  4130. {
  4131. if ((!mBfIRBuilder->mIgnoreWrites) && (!mCompiler->mFastFinish))
  4132. AssertErrorState();
  4133. }
  4134. else
  4135. {
  4136. result = LoadValue(result);
  4137. if (!result.mType->IsValuelessType())
  4138. mBfIRBuilder->CreateAlignedStore(result.mValue, staticVarRef.mValue, result.mType->mAlign);
  4139. }
  4140. }
  4141. return result;
  4142. }
  4143. bool BfModule::TryGetAppendedObjectInfo(BfFieldInstance* fieldInstance, int& dataSize, int& alignSize)
  4144. {
  4145. auto resolvedFieldType = fieldInstance->GetResolvedType();
  4146. auto fieldDef = fieldInstance->GetFieldDef();
  4147. BfAstNode* nameRefNode = NULL;
  4148. if (auto fieldDecl = fieldDef->GetFieldDeclaration())
  4149. nameRefNode = fieldDecl->mNameNode;
  4150. else if (auto paramDecl = fieldDef->GetParamDeclaration())
  4151. nameRefNode = paramDecl->mNameNode;
  4152. if (nameRefNode == NULL)
  4153. nameRefNode = fieldDef->mTypeRef;
  4154. dataSize = resolvedFieldType->mSize;
  4155. alignSize = resolvedFieldType->mAlign;
  4156. SetAndRestoreValue<BfFieldDef*> prevTypeRef(mContext->mCurTypeState->mCurFieldDef, fieldDef);
  4157. SetAndRestoreValue<BfTypeState::ResolveKind> prevResolveKind(mContext->mCurTypeState->mResolveKind, BfTypeState::ResolveKind_FieldType);
  4158. PopulateType(resolvedFieldType, BfPopulateType_Data);
  4159. auto fieldTypeInst = resolvedFieldType->ToTypeInstance();
  4160. dataSize = BF_MAX(fieldTypeInst->mInstSize, 0);
  4161. alignSize = BF_MAX(fieldTypeInst->mInstAlign, 1);
  4162. if (fieldTypeInst->mTypeFailed)
  4163. {
  4164. TypeFailed(fieldTypeInst);
  4165. fieldInstance->mResolvedType = GetPrimitiveType(BfTypeCode_Var);
  4166. return false;
  4167. }
  4168. if ((fieldTypeInst != NULL) && (fieldTypeInst->mTypeDef->mIsAbstract))
  4169. {
  4170. Fail("Cannot create an instance of an abstract class", nameRefNode);
  4171. }
  4172. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, true);
  4173. BfMethodState methodState;
  4174. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  4175. methodState.mTempKind = BfMethodState::TempKind_NonStatic;
  4176. BfTypedValue appendIndexValue;
  4177. BfExprEvaluator exprEvaluator(this);
  4178. BfResolvedArgs resolvedArgs;
  4179. auto fieldDecl = fieldDef->GetFieldDeclaration();
  4180. if (auto invocationExpr = BfNodeDynCast<BfInvocationExpression>(fieldDecl->mInitializer))
  4181. {
  4182. resolvedArgs.Init(invocationExpr->mOpenParen, &invocationExpr->mArguments, &invocationExpr->mCommas, invocationExpr->mCloseParen);
  4183. exprEvaluator.ResolveArgValues(resolvedArgs, BfResolveArgsFlag_DeferParamEval);
  4184. }
  4185. BfFunctionBindResult bindResult;
  4186. bindResult.mSkipThis = true;
  4187. bindResult.mWantsArgs = true;
  4188. SetAndRestoreValue<BfFunctionBindResult*> prevBindResult(exprEvaluator.mFunctionBindResult, &bindResult);
  4189. BfTypedValue emptyThis(mBfIRBuilder->GetFakeVal(), mCurTypeInstance, mCurTypeInstance->IsStruct());
  4190. exprEvaluator.mBfEvalExprFlags = BfEvalExprFlags_Comptime;
  4191. auto ctorResult = exprEvaluator.MatchConstructor(nameRefNode, NULL, emptyThis, fieldTypeInst, resolvedArgs, false, BfMethodGenericArguments(), BfAllowAppendKind_Infer);
  4192. if ((bindResult.mMethodInstance != NULL) && (bindResult.mMethodInstance->mMethodDef->HasAppend()))
  4193. {
  4194. auto calcAppendMethodModule = GetMethodInstanceAtIdx(bindResult.mMethodInstance->GetOwner(), bindResult.mMethodInstance->mMethodDef->mIdx + 1, BF_METHODNAME_CALCAPPEND);
  4195. SizedArray<BfIRValue, 2> irArgs;
  4196. if (bindResult.mIRArgs.size() > 1)
  4197. irArgs.Insert(0, &bindResult.mIRArgs[1], bindResult.mIRArgs.size() - 1);
  4198. BfTypedValue appendSizeTypedValue = TryConstCalcAppend(calcAppendMethodModule.mMethodInstance, irArgs, true);
  4199. if (appendSizeTypedValue)
  4200. {
  4201. int appendAlign = calcAppendMethodModule.mMethodInstance->mAppendAllocAlign;
  4202. dataSize = BF_ALIGN(dataSize, appendAlign);
  4203. alignSize = BF_MAX(alignSize, appendAlign);
  4204. auto constant = mBfIRBuilder->GetConstant(appendSizeTypedValue.mValue);
  4205. if (constant != NULL)
  4206. {
  4207. dataSize += constant->mInt32;
  4208. }
  4209. }
  4210. else
  4211. {
  4212. Fail(StrFormat("Append constructor '%s' does not result in a constant size", MethodToString(bindResult.mMethodInstance).c_str()), nameRefNode);
  4213. }
  4214. }
  4215. return true;
  4216. }
  4217. void BfModule::AppendedObjectInit(BfFieldInstance* fieldInst)
  4218. {
  4219. BfExprEvaluator exprEvaluator(this);
  4220. bool failed = false;
  4221. auto fieldDef = fieldInst->GetFieldDef();
  4222. auto initializer = fieldDef->GetInitializer();
  4223. BfResolvedArgs resolvedArgs;
  4224. if (auto invocationExpr = BfNodeDynCast<BfInvocationExpression>(initializer))
  4225. {
  4226. bool isDot = false;
  4227. if (auto memberRefExpr = BfNodeDynCast<BfMemberReferenceExpression>(invocationExpr->mTarget))
  4228. isDot = (memberRefExpr->mTarget == NULL) && (memberRefExpr->mMemberName == NULL);
  4229. if (!isDot)
  4230. {
  4231. auto resolvedType = ResolveTypeRef(invocationExpr->mTarget, {});
  4232. if ((resolvedType == NULL) || (resolvedType != fieldInst->mResolvedType))
  4233. failed = true;
  4234. }
  4235. SetAndRestoreValue<BfType*> prevExpectingType(exprEvaluator.mExpectingType, fieldInst->mResolvedType);
  4236. resolvedArgs.Init(invocationExpr->mOpenParen, &invocationExpr->mArguments, &invocationExpr->mCommas, invocationExpr->mCloseParen);
  4237. exprEvaluator.ResolveArgValues(resolvedArgs, BfResolveArgsFlag_DeferParamEval);
  4238. }
  4239. else if (initializer != NULL)
  4240. {
  4241. GetFieldInitializerValue(fieldInst);
  4242. failed = true;
  4243. }
  4244. if (failed)
  4245. Fail("Append fields can only be initialized with a call to their constructor", initializer);
  4246. auto intType = GetPrimitiveType(BfTypeCode_IntPtr);
  4247. auto int8Type = mBfIRBuilder->GetPrimitiveType(BfTypeCode_Int8);
  4248. auto ptrType = mBfIRBuilder->GetPointerTo(int8Type);
  4249. auto ptrPtrType = mBfIRBuilder->GetPointerTo(ptrType);
  4250. auto fieldTypeInst = fieldInst->mResolvedType->ToTypeInstance();
  4251. BfIRValue fieldAddr;
  4252. if (fieldDef->mIsStatic)
  4253. {
  4254. auto fieldTypedValue = ReferenceStaticField(fieldInst);
  4255. int dataSize = 1;
  4256. int alignSize = 1;
  4257. TryGetAppendedObjectInfo(fieldInst, dataSize, alignSize);
  4258. String dataName;
  4259. BfMangler::MangleStaticFieldName(dataName, mCompiler->GetMangleKind(), mCurTypeInstance, fieldDef->mName, fieldInst->mResolvedType);
  4260. dataName += "__DATA";
  4261. auto arrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->GetPrimitiveType(BfTypeCode_Int8), dataSize);
  4262. auto globalVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->GetPrimitiveType(BfTypeCode_Int8), dataSize), false,
  4263. BfIRLinkageType_Internal, mBfIRBuilder->CreateConstArrayZero(dataSize), dataName);
  4264. mBfIRBuilder->GlobalVar_SetAlignment(globalVar, alignSize);
  4265. auto castedVal = mBfIRBuilder->CreateBitCast(globalVar, mBfIRBuilder->MapType(fieldInst->mResolvedType));
  4266. mBfIRBuilder->CreateStore(castedVal, fieldTypedValue.mValue);
  4267. fieldTypedValue = LoadValue(fieldTypedValue);
  4268. fieldAddr = fieldTypedValue.mValue;
  4269. }
  4270. else
  4271. fieldAddr = mBfIRBuilder->CreateInBoundsGEP(mCurMethodState->mLocals[0]->mValue, 0, fieldInst->mDataIdx);
  4272. auto thisValue = BfTypedValue(mBfIRBuilder->CreateBitCast(fieldAddr, mBfIRBuilder->MapType(fieldInst->mResolvedType)), fieldInst->mResolvedType);
  4273. auto indexVal = BfTypedValue(CreateAlloca(intType), CreateRefType(intType));
  4274. auto intThisVal = mBfIRBuilder->CreatePtrToInt(thisValue.mValue, (intType->mSize == 4) ? BfTypeCode_Int32 : BfTypeCode_Int64);
  4275. auto curValPtr = mBfIRBuilder->CreateAdd(intThisVal, GetConstValue(fieldTypeInst->mInstSize, intType));
  4276. mBfIRBuilder->CreateStore(curValPtr, indexVal.mValue);
  4277. auto vObjectAddr = mBfIRBuilder->CreateInBoundsGEP(thisValue.mValue, 0, 0);
  4278. auto vDataRef = CreateClassVDataGlobal(fieldInst->mResolvedType->ToTypeInstance());
  4279. auto destAddr = mBfIRBuilder->CreateBitCast(vObjectAddr, ptrPtrType);
  4280. auto srcVal = mBfIRBuilder->CreateBitCast(vDataRef, ptrType);
  4281. mBfIRBuilder->CreateStore(srcVal, destAddr);
  4282. if ((mCompiler->mOptions.mObjectHasDebugFlags) && (!mIsComptimeModule))
  4283. {
  4284. auto int8Type = mBfIRBuilder->GetPrimitiveType(BfTypeCode_Int8);
  4285. auto ptrType = mBfIRBuilder->GetPointerTo(int8Type);
  4286. auto thisFlagsPtr = mBfIRBuilder->CreateBitCast(thisValue.mValue, ptrType);
  4287. mBfIRBuilder->CreateStore(GetConstValue8(BfObjectFlag_AppendAlloc), thisFlagsPtr);
  4288. }
  4289. exprEvaluator.MatchConstructor(fieldDef->GetNameNode(), NULL, thisValue, fieldInst->mResolvedType->ToTypeInstance(), resolvedArgs, false, BfMethodGenericArguments(), BfAllowAppendKind_Infer, &indexVal);
  4290. }
  4291. void BfModule::CheckInterfaceMethod(BfMethodInstance* methodInstance)
  4292. {
  4293. }
  4294. void BfModule::FindSubTypes(BfTypeInstance* classType, SizedArrayImpl<int>* outVals, SizedArrayImpl<BfTypeInstance*>* exChecks, bool isInterfacePass)
  4295. {
  4296. PopulateType(classType);
  4297. if (isInterfacePass)
  4298. {
  4299. for (auto ifaceInst : classType->mInterfaces)
  4300. {
  4301. if (exChecks->Contains(ifaceInst.mInterfaceType))
  4302. continue;
  4303. if (outVals->Contains(ifaceInst.mInterfaceType->mTypeId))
  4304. continue;
  4305. if (ifaceInst.mDeclaringType->IsExtension())
  4306. {
  4307. bool needsExCheck = false;
  4308. if (ifaceInst.mDeclaringType->mProject != classType->mTypeDef->mProject)
  4309. {
  4310. PopulateType(ifaceInst.mInterfaceType, BfPopulateType_DataAndMethods);
  4311. if (ifaceInst.mInterfaceType->mVirtualMethodTableSize > 0)
  4312. {
  4313. exChecks->push_back(ifaceInst.mInterfaceType);
  4314. continue;
  4315. }
  4316. else
  4317. {
  4318. // We can only do an 'exCheck' if we're actually going to slot this interface
  4319. }
  4320. }
  4321. }
  4322. outVals->push_back(ifaceInst.mInterfaceType->mTypeId);
  4323. }
  4324. }
  4325. else
  4326. {
  4327. outVals->push_back(classType->mTypeId);
  4328. }
  4329. if (classType->mBaseType != NULL)
  4330. {
  4331. FindSubTypes(classType->mBaseType, outVals, exChecks, isInterfacePass);
  4332. }
  4333. }
  4334. void BfModule::CreateDynamicCastMethod()
  4335. {
  4336. auto objType = mContext->mBfObjectType;
  4337. if ((mCompiler->mIsResolveOnly) || (!mIsReified))
  4338. {
  4339. // The main reason to punt on this method for ResolveOnly is because types can be created
  4340. // and destroyed quickly during autocomplete and the typeId creep can generate lots of
  4341. // entries in the LLVM ConstantInt pool, primarily from the FindSubTypes call. We can
  4342. // remove this punt when we recycle typeId's
  4343. mBfIRBuilder->CreateRet(mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapTypeInstPtr(objType)));
  4344. mCurMethodState->mHadReturn = true;
  4345. return;
  4346. }
  4347. bool isInterfacePass = mCurMethodInstance->mMethodDef->mName == BF_METHODNAME_DYNAMICCAST_INTERFACE;
  4348. auto func = mCurMethodState->mIRFunction;
  4349. auto thisValue = mBfIRBuilder->GetArgument(0);
  4350. auto typeIdValue = mBfIRBuilder->GetArgument(1);
  4351. auto intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  4352. auto int32Type = GetPrimitiveType(BfTypeCode_Int32);
  4353. typeIdValue = CastToValue(NULL, BfTypedValue(typeIdValue, intPtrType), int32Type, (BfCastFlags)(BfCastFlags_Explicit | BfCastFlags_SilentFail));
  4354. auto thisObject = mBfIRBuilder->CreateBitCast(thisValue, mBfIRBuilder->MapType(objType));
  4355. auto trueBB = mBfIRBuilder->CreateBlock("check.true");
  4356. //auto falseBB = mBfIRBuilder->CreateBlock("check.false");
  4357. auto exitBB = mBfIRBuilder->CreateBlock("exit");
  4358. SizedArray<int, 8> typeMatches;
  4359. SizedArray<BfTypeInstance*, 8> exChecks;
  4360. FindSubTypes(mCurTypeInstance, &typeMatches, &exChecks, isInterfacePass);
  4361. if ((mCurTypeInstance->IsGenericTypeInstance()) && (!mCurTypeInstance->IsUnspecializedType()))
  4362. {
  4363. // Add 'unbound' type id to cast list so things like "List<int> is List<>" work
  4364. auto genericTypeInst = mCurTypeInstance->mTypeDef;
  4365. BfTypeVector genericArgs;
  4366. for (int i = 0; i < (int) genericTypeInst->mGenericParamDefs.size(); i++)
  4367. genericArgs.push_back(GetGenericParamType(BfGenericParamKind_Type, i));
  4368. auto unboundType = ResolveTypeDef(mCurTypeInstance->mTypeDef->GetDefinition(), genericArgs, BfPopulateType_Declaration);
  4369. typeMatches.push_back(unboundType->mTypeId);
  4370. }
  4371. if (mCurTypeInstance->IsBoxed())
  4372. {
  4373. BfBoxedType* boxedType = (BfBoxedType*)mCurTypeInstance;
  4374. BfTypeInstance* innerType = boxedType->mElementType->ToTypeInstance();
  4375. FindSubTypes(innerType, &typeMatches, &exChecks, isInterfacePass);
  4376. if (innerType->IsTypedPrimitive())
  4377. {
  4378. auto underlyingType = innerType->GetUnderlyingType();
  4379. typeMatches.push_back(underlyingType->mTypeId);
  4380. }
  4381. auto innerTypeInst = innerType->ToTypeInstance();
  4382. if ((innerTypeInst->IsInstanceOf(mCompiler->mSizedArrayTypeDef)) ||
  4383. (innerTypeInst->IsInstanceOf(mCompiler->mPointerTTypeDef)) ||
  4384. (innerTypeInst->IsInstanceOf(mCompiler->mMethodRefTypeDef)))
  4385. {
  4386. PopulateType(innerTypeInst);
  4387. //TODO: What case was this supposed to handle?
  4388. //typeMatches.push_back(innerTypeInst->mFieldInstances[0].mResolvedType->mTypeId);
  4389. }
  4390. }
  4391. auto curBlock = mBfIRBuilder->GetInsertBlock();
  4392. BfIRValue vDataPtr;
  4393. if (!exChecks.empty())
  4394. {
  4395. BfType* intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  4396. auto ptrPtrType = mBfIRBuilder->GetPointerTo(mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapType(intPtrType)));
  4397. auto vDataPtrPtr = mBfIRBuilder->CreateBitCast(thisValue, ptrPtrType);
  4398. vDataPtr = FixClassVData(mBfIRBuilder->CreateLoad(vDataPtrPtr/*, "vtable"*/));
  4399. }
  4400. auto switchStatement = mBfIRBuilder->CreateSwitch(typeIdValue, exitBB, (int)typeMatches.size() + (int)exChecks.size());
  4401. for (auto typeMatch : typeMatches)
  4402. mBfIRBuilder->AddSwitchCase(switchStatement, GetConstValue32(typeMatch), trueBB);
  4403. Array<BfIRValue> incomingFalses;
  4404. for (auto ifaceTypeInst : exChecks)
  4405. {
  4406. BfIRBlock nextBB = mBfIRBuilder->CreateBlock("exCheck", true);
  4407. mBfIRBuilder->AddSwitchCase(switchStatement, GetConstValue32(ifaceTypeInst->mTypeId), nextBB);
  4408. mBfIRBuilder->SetInsertPoint(nextBB);
  4409. BfIRValue slotOfs = GetInterfaceSlotNum(ifaceTypeInst);
  4410. auto ifacePtrPtr = mBfIRBuilder->CreateInBoundsGEP(vDataPtr, slotOfs/*, "iface"*/);
  4411. auto ifacePtr = mBfIRBuilder->CreateLoad(ifacePtrPtr);
  4412. auto cmpResult = mBfIRBuilder->CreateCmpNE(ifacePtr, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 0));
  4413. mBfIRBuilder->CreateCondBr(cmpResult, trueBB, exitBB);
  4414. incomingFalses.push_back(nextBB);
  4415. }
  4416. mBfIRBuilder->AddBlock(trueBB);
  4417. mBfIRBuilder->SetInsertPoint(trueBB);
  4418. mBfIRBuilder->CreateBr(exitBB);
  4419. mBfIRBuilder->AddBlock(exitBB);
  4420. mBfIRBuilder->SetInsertPoint(exitBB);
  4421. auto phi = mBfIRBuilder->CreatePhi(mBfIRBuilder->MapTypeInstPtr(objType), 2);
  4422. mBfIRBuilder->AddPhiIncoming(phi, thisObject, trueBB);
  4423. auto nullValue = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapTypeInstPtr(objType));
  4424. for (auto incomingFalseBlock : incomingFalses)
  4425. mBfIRBuilder->AddPhiIncoming(phi, nullValue, incomingFalseBlock);
  4426. mBfIRBuilder->AddPhiIncoming(phi, nullValue, curBlock);
  4427. mBfIRBuilder->CreateRet(phi);
  4428. mCurMethodState->mHadReturn = true;
  4429. }
  4430. void BfModule::EmitEquals(BfTypedValue leftValue, BfTypedValue rightValue, BfIRBlock exitBB, bool strictEquals)
  4431. {
  4432. BfExprEvaluator exprEvaluator(this);
  4433. exprEvaluator.mExpectingType = mCurMethodInstance->mReturnType;
  4434. auto typeInst = rightValue.mType->ToTypeInstance();
  4435. exprEvaluator.PerformBinaryOperation((BfAstNode*)NULL, (BfAstNode*)NULL, strictEquals ? BfBinaryOp_StrictEquality : BfBinaryOp_Equality, NULL, BfBinOpFlag_IgnoreOperatorWithWrongResult, leftValue, rightValue);
  4436. BfTypedValue result = exprEvaluator.GetResult();
  4437. if (result.mType != GetPrimitiveType(BfTypeCode_Boolean))
  4438. {
  4439. // Fail?
  4440. }
  4441. if ((result) && (!result.mType->IsVar()))
  4442. {
  4443. auto nextBB = mBfIRBuilder->CreateBlock("next");
  4444. mBfIRBuilder->CreateCondBr(result.mValue, nextBB, exitBB);
  4445. mBfIRBuilder->AddBlock(nextBB);
  4446. mBfIRBuilder->SetInsertPoint(nextBB);
  4447. }
  4448. }
  4449. void BfModule::CreateFakeCallerMethod(const String& funcName)
  4450. {
  4451. if (mCurMethodInstance->mHasFailed)
  4452. return;
  4453. if (mCurMethodInstance->mMethodDef->mIsSkipCall)
  4454. return;
  4455. BF_ASSERT(mCurMethodInstance->mIRFunction);
  4456. auto voidType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_None));
  4457. SizedArray<BfIRType, 4> paramTypes;
  4458. BfIRFunctionType funcType = mBfIRBuilder->CreateFunctionType(voidType, paramTypes);
  4459. BfIRFunction func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_Internal, "FORCELINK_" + funcName);
  4460. mBfIRBuilder->SetActiveFunction(func);
  4461. auto entryBlock = mBfIRBuilder->CreateBlock("main", true);
  4462. mBfIRBuilder->SetInsertPoint(entryBlock);
  4463. BfMethodState methodState;
  4464. methodState.mIRHeadBlock = entryBlock;
  4465. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  4466. SizedArray<BfIRValue, 8> args;
  4467. BfExprEvaluator exprEvaluator(this);
  4468. if (mCurMethodInstance->GetStructRetIdx() == 0)
  4469. {
  4470. auto retPtrType = CreatePointerType(mCurMethodInstance->mReturnType);
  4471. exprEvaluator.PushArg(GetDefaultTypedValue(retPtrType, true, BfDefaultValueKind_Const), args);
  4472. }
  4473. if (mCurMethodInstance->HasThis())
  4474. {
  4475. auto thisValue = GetDefaultTypedValue(mCurMethodInstance->GetOwner(), true, mCurTypeInstance->IsComposite() ? BfDefaultValueKind_Addr : BfDefaultValueKind_Const);
  4476. exprEvaluator.PushThis(NULL, thisValue, mCurMethodInstance, args);
  4477. }
  4478. if (mCurMethodInstance->GetStructRetIdx() == 1)
  4479. {
  4480. auto retPtrType = CreatePointerType(mCurMethodInstance->mReturnType);
  4481. exprEvaluator.PushArg(GetDefaultTypedValue(retPtrType, true, BfDefaultValueKind_Const), args);
  4482. }
  4483. for (int paramIdx = 0; paramIdx < mCurMethodInstance->GetParamCount(); paramIdx++)
  4484. {
  4485. auto paramType = mCurMethodInstance->GetParamType(paramIdx);
  4486. if (paramType->IsValuelessType())
  4487. continue;
  4488. exprEvaluator.PushArg(GetDefaultTypedValue(paramType, true, paramType->IsComposite() ? BfDefaultValueKind_Addr : BfDefaultValueKind_Const), args);
  4489. }
  4490. mBfIRBuilder->CreateCall(mCurMethodInstance->mIRFunction, args);
  4491. mBfIRBuilder->CreateRetVoid();
  4492. }
  4493. void BfModule::CreateDelegateEqualsMethod()
  4494. {
  4495. if (mBfIRBuilder->mIgnoreWrites)
  4496. return;
  4497. auto refNode = mCurTypeInstance->mTypeDef->GetRefNode();
  4498. if (refNode == NULL)
  4499. refNode = mCompiler->mValueTypeTypeDef->GetRefNode();
  4500. UpdateSrcPos(refNode);
  4501. SetIllegalSrcPos();
  4502. auto boolType = GetPrimitiveType(BfTypeCode_Boolean);
  4503. auto resultVal = CreateAlloca(boolType);
  4504. mBfIRBuilder->CreateStore(GetConstValue(0, boolType), resultVal);
  4505. auto exitBB = mBfIRBuilder->CreateBlock("exit");
  4506. auto delegateType = ResolveTypeDef(mCompiler->mDelegateTypeDef)->ToTypeInstance();
  4507. mBfIRBuilder->PopulateType(delegateType);
  4508. BfExprEvaluator exprEvaluator(this);
  4509. BfTypedValue leftTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[0]);
  4510. BfTypedValue lhsDelegate = BfTypedValue(mBfIRBuilder->CreateBitCast(leftTypedVal.mValue, mBfIRBuilder->MapType(delegateType)), delegateType);
  4511. BfTypedValue rhsDelegate = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  4512. rhsDelegate = LoadValue(rhsDelegate);
  4513. BfTypedValue rightTypedVal = BfTypedValue(mBfIRBuilder->CreateBitCast(rhsDelegate.mValue, mBfIRBuilder->MapType(mCurTypeInstance)), mCurTypeInstance);
  4514. auto& targetFieldInstance = delegateType->mFieldInstances[0];
  4515. BfTypedValue leftValue = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(lhsDelegate.mValue, 0, targetFieldInstance.mDataIdx), targetFieldInstance.mResolvedType, true);
  4516. BfTypedValue rightValue = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(rhsDelegate.mValue, 0, targetFieldInstance.mDataIdx), targetFieldInstance.mResolvedType, true);
  4517. leftValue = LoadValue(leftValue);
  4518. rightValue = LoadValue(rightValue);
  4519. EmitEquals(leftValue, rightValue, exitBB, false);
  4520. bool hadComparison = false;
  4521. for (auto& fieldRef : mCurTypeInstance->mFieldInstances)
  4522. {
  4523. BfFieldInstance* fieldInstance = &fieldRef;
  4524. if (fieldInstance->mDataOffset == -1)
  4525. continue;
  4526. auto fieldType = fieldInstance->mResolvedType;
  4527. if (fieldType->IsValuelessType())
  4528. continue;
  4529. if (fieldType->IsVar())
  4530. continue;
  4531. if (fieldType->IsMethodRef())
  4532. continue;
  4533. if (fieldType->IsRef())
  4534. fieldType = CreatePointerType(fieldType->GetUnderlyingType());
  4535. BfTypedValue leftValue = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(leftTypedVal.mValue, 0, fieldInstance->mDataIdx), fieldType, true);
  4536. BfTypedValue rightValue = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(rightTypedVal.mValue, 0, fieldInstance->mDataIdx), fieldType, true);
  4537. if (!fieldInstance->mResolvedType->IsComposite())
  4538. {
  4539. leftValue = LoadValue(leftValue);
  4540. rightValue = LoadValue(rightValue);
  4541. }
  4542. EmitEquals(leftValue, rightValue, exitBB, false);
  4543. }
  4544. mBfIRBuilder->CreateStore(GetConstValue(1, boolType), resultVal);
  4545. mBfIRBuilder->CreateBr(exitBB);
  4546. mBfIRBuilder->AddBlock(exitBB);
  4547. mBfIRBuilder->SetInsertPoint(exitBB);
  4548. auto loadedResult = mBfIRBuilder->CreateLoad(resultVal);
  4549. ClearLifetimeEnds();
  4550. mBfIRBuilder->CreateRet(loadedResult);
  4551. mCurMethodState->mHadReturn = true;
  4552. }
  4553. void BfModule::CreateValueTypeEqualsMethod(bool strictEquals)
  4554. {
  4555. if (mCurMethodInstance->mIsUnspecialized)
  4556. return;
  4557. if (mBfIRBuilder->mIgnoreWrites)
  4558. return;
  4559. BF_ASSERT(!mCurTypeInstance->IsBoxed());
  4560. auto compareType = mCurMethodInstance->mParams[0].mResolvedType;
  4561. bool isValid = true;
  4562. auto boolType = GetPrimitiveType(BfTypeCode_Boolean);
  4563. if (compareType->IsValuelessType())
  4564. {
  4565. mBfIRBuilder->CreateRet(GetDefaultValue(boolType));
  4566. return;
  4567. }
  4568. if (compareType->IsTypedPrimitive())
  4569. {
  4570. BfExprEvaluator exprEvaluator(this);
  4571. BfTypedValue leftTypedVal = LoadValue(exprEvaluator.LoadLocal(mCurMethodState->mLocals[0]));
  4572. BfTypedValue rightTypedVal = LoadValue(exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]));
  4573. auto cmpResult = mBfIRBuilder->CreateCmpEQ(leftTypedVal.mValue, rightTypedVal.mValue);
  4574. mBfIRBuilder->CreateRet(cmpResult);
  4575. return;
  4576. }
  4577. auto compareDType = compareType->ToDependedType();
  4578. BfTypeInstance* compareTypeInst = compareType->ToTypeInstance();
  4579. if (compareTypeInst != NULL)
  4580. {
  4581. if (compareType->IsPrimitiveType())
  4582. compareTypeInst = GetWrappedStructType(compareType);
  4583. if ((compareTypeInst == NULL) || (!compareTypeInst->IsValueType()))
  4584. {
  4585. isValid = false;
  4586. }
  4587. mBfIRBuilder->PopulateType(compareTypeInst);
  4588. }
  4589. if (!isValid)
  4590. {
  4591. ClearLifetimeEnds();
  4592. mBfIRBuilder->CreateRet(GetDefaultValue(boolType));
  4593. return;
  4594. }
  4595. AddDependency(compareDType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ReadFields);
  4596. auto refNode = mCurTypeInstance->mTypeDef->GetRefNode();
  4597. if (refNode == NULL)
  4598. refNode = mCompiler->mValueTypeTypeDef->GetRefNode();
  4599. UpdateSrcPos(refNode);
  4600. SetIllegalSrcPos();
  4601. auto resultVal = CreateAlloca(boolType);
  4602. mBfIRBuilder->CreateStore(GetConstValue(0, boolType), resultVal);
  4603. auto exitBB = mBfIRBuilder->CreateBlock("exit");
  4604. if (compareType->IsValuelessType())
  4605. {
  4606. // Always equal, nothing to do
  4607. }
  4608. else if (compareType->IsSizedArray())
  4609. {
  4610. auto sizedArrayType = (BfSizedArrayType*)compareType;
  4611. auto _SizedIndex = [&](BfIRValue target, BfIRValue index)
  4612. {
  4613. BfTypedValue result;
  4614. auto indexResult = CreateIndexedValue(sizedArrayType->mElementType, target, index, true);
  4615. result = BfTypedValue(indexResult, sizedArrayType->mElementType, BfTypedValueKind_Addr);
  4616. if (!result.mType->IsValueType())
  4617. result = LoadValue(result);
  4618. return result;
  4619. };
  4620. if (sizedArrayType->mElementCount > 6)
  4621. {
  4622. auto intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  4623. auto itr = CreateAlloca(intPtrType);
  4624. mBfIRBuilder->CreateStore(GetDefaultValue(intPtrType), itr);
  4625. auto loopBB = mBfIRBuilder->CreateBlock("loop", true);
  4626. auto bodyBB = mBfIRBuilder->CreateBlock("body", true);
  4627. auto doneBB = mBfIRBuilder->CreateBlock("done", true);
  4628. mBfIRBuilder->CreateBr(loopBB);
  4629. mBfIRBuilder->SetInsertPoint(loopBB);
  4630. auto loadedItr = mBfIRBuilder->CreateLoad(itr);
  4631. auto cmpRes = mBfIRBuilder->CreateCmpGTE(loadedItr, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, (uint64)sizedArrayType->mElementCount), true);
  4632. mBfIRBuilder->CreateCondBr(cmpRes, doneBB, bodyBB);
  4633. mBfIRBuilder->SetInsertPoint(bodyBB);
  4634. BfTypedValue leftValue = _SizedIndex(mCurMethodState->mLocals[0]->mValue, loadedItr);
  4635. BfTypedValue rightValue = _SizedIndex(mCurMethodState->mLocals[1]->mValue, loadedItr);
  4636. EmitEquals(leftValue, rightValue, exitBB, strictEquals);
  4637. auto incValue = mBfIRBuilder->CreateAdd(loadedItr, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 1));
  4638. mBfIRBuilder->CreateStore(incValue, itr);
  4639. mBfIRBuilder->CreateBr(loopBB);
  4640. mBfIRBuilder->SetInsertPoint(doneBB);
  4641. }
  4642. else
  4643. {
  4644. for (int dataIdx = 0; dataIdx < sizedArrayType->mElementCount; dataIdx++)
  4645. {
  4646. BfTypedValue leftValue = _SizedIndex(mCurMethodState->mLocals[0]->mValue, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, dataIdx));
  4647. BfTypedValue rightValue = _SizedIndex(mCurMethodState->mLocals[1]->mValue, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, dataIdx));
  4648. EmitEquals(leftValue, rightValue, exitBB, strictEquals);
  4649. }
  4650. }
  4651. }
  4652. else if (compareType->IsMethodRef())
  4653. {
  4654. auto methodRefType = (BfMethodRefType*)compareType;
  4655. BfMethodInstance* methodInstance = methodRefType->mMethodRef;
  4656. BfExprEvaluator exprEvaluator(this);
  4657. BfTypedValue leftTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[0]);
  4658. BfTypedValue rightTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  4659. // We only need to compare the 'this' capture. The rationale is that it's impossible to capture any other non-matching
  4660. // values for the same method reference -- they will always refer back to the same local variables.
  4661. int dataIdx = methodRefType->GetDataIdxFromParamIdx(-1);
  4662. if (dataIdx != -1)
  4663. {
  4664. bool failed = false;
  4665. BfTypedValue leftValue = exprEvaluator.DoImplicitArgCapture(NULL, methodInstance, methodRefType->GetParamIdxFromDataIdx(dataIdx), failed, BfImplicitParamKind_General, leftTypedVal);
  4666. BfTypedValue rightValue = exprEvaluator.DoImplicitArgCapture(NULL, methodInstance, methodRefType->GetParamIdxFromDataIdx(dataIdx), failed, BfImplicitParamKind_General, rightTypedVal);
  4667. BF_ASSERT(!failed);
  4668. EmitEquals(leftValue, rightValue, exitBB, strictEquals);
  4669. }
  4670. }
  4671. else if (compareTypeInst->IsEnum())
  4672. {
  4673. //auto intType = GetPrimitiveType(BfTypeCode_Int32);
  4674. BfExprEvaluator exprEvaluator(this);
  4675. BfTypedValue leftTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[0]);
  4676. BfTypedValue rightTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  4677. auto dscrType = compareTypeInst->GetDiscriminatorType();
  4678. BfTypedValue leftValue = ExtractValue(leftTypedVal, NULL, 2);
  4679. leftValue = LoadValue(leftValue);
  4680. BfTypedValue rightValue = ExtractValue(rightTypedVal, NULL, 2);
  4681. rightValue = LoadValue(rightValue);
  4682. BfTypedValue leftPayload = ExtractValue(leftTypedVal, NULL, 1);
  4683. BfTypedValue rightPayload = ExtractValue(rightTypedVal, NULL, 1);
  4684. EmitEquals(leftValue, rightValue, exitBB, strictEquals);
  4685. int enumCount = 0;
  4686. for (auto& fieldRef : compareTypeInst->mFieldInstances)
  4687. {
  4688. BfFieldInstance* fieldInstance = &fieldRef;
  4689. BfFieldDef* fieldDef = fieldInstance->GetFieldDef();
  4690. if ((fieldDef != NULL) && (fieldDef->IsEnumCaseEntry()))
  4691. {
  4692. enumCount = -fieldInstance->mDataIdx;
  4693. }
  4694. }
  4695. if (enumCount > 0)
  4696. {
  4697. BfIRBlock matchedBlock = mBfIRBuilder->CreateBlock("matched");
  4698. auto switchVal = mBfIRBuilder->CreateSwitch(leftValue.mValue, exitBB, enumCount);
  4699. for (auto& fieldRef : compareTypeInst->mFieldInstances)
  4700. {
  4701. BfFieldInstance* fieldInstance = &fieldRef;
  4702. BfFieldDef* fieldDef = fieldInstance->GetFieldDef();
  4703. if ((fieldDef != NULL) && (fieldDef->IsEnumCaseEntry()))
  4704. {
  4705. int enumIdx = -fieldInstance->mDataIdx - 1;
  4706. if (fieldInstance->mResolvedType->mSize == 0)
  4707. {
  4708. mBfIRBuilder->AddSwitchCase(switchVal, mBfIRBuilder->CreateConst(dscrType->mTypeDef->mTypeCode, enumIdx), matchedBlock);
  4709. }
  4710. else
  4711. {
  4712. auto caseBlock = mBfIRBuilder->CreateBlock("case", true);
  4713. mBfIRBuilder->SetInsertPoint(caseBlock);
  4714. auto tuplePtr = CreatePointerType(fieldInstance->mResolvedType);
  4715. BfTypedValue leftTuple;
  4716. BfTypedValue rightTuple;
  4717. if (leftPayload.IsAddr())
  4718. {
  4719. leftTuple = BfTypedValue(mBfIRBuilder->CreateBitCast(leftPayload.mValue, mBfIRBuilder->MapType(tuplePtr)), fieldInstance->mResolvedType, true);
  4720. rightTuple = BfTypedValue(mBfIRBuilder->CreateBitCast(rightPayload.mValue, mBfIRBuilder->MapType(tuplePtr)), fieldInstance->mResolvedType, true);
  4721. }
  4722. else
  4723. {
  4724. leftTuple = Cast(NULL, leftPayload, fieldInstance->mResolvedType, BfCastFlags_Force);
  4725. rightTuple = Cast(NULL, rightPayload, fieldInstance->mResolvedType, BfCastFlags_Force);
  4726. }
  4727. EmitEquals(leftTuple, rightTuple, exitBB, strictEquals);
  4728. mBfIRBuilder->CreateBr(matchedBlock);
  4729. mBfIRBuilder->AddSwitchCase(switchVal, mBfIRBuilder->CreateConst(dscrType->mTypeDef->mTypeCode, enumIdx), caseBlock);
  4730. }
  4731. }
  4732. }
  4733. mBfIRBuilder->AddBlock(matchedBlock);
  4734. mBfIRBuilder->SetInsertPoint(matchedBlock);
  4735. }
  4736. }
  4737. else if (compareTypeInst->IsUnion())
  4738. {
  4739. auto innerType = compareTypeInst->GetUnionInnerType();
  4740. if (!innerType->IsValuelessType())
  4741. {
  4742. BfExprEvaluator exprEvaluator(this);
  4743. BfTypedValue leftTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[0]);
  4744. leftTypedVal = AggregateSplat(leftTypedVal);
  4745. BfTypedValue leftUnionTypedVal = ExtractValue(leftTypedVal, NULL, 1);
  4746. BfTypedValue rightTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  4747. rightTypedVal = AggregateSplat(rightTypedVal);
  4748. BfTypedValue rightUnionTypedVal = ExtractValue(rightTypedVal, NULL, 1);
  4749. EmitEquals(leftUnionTypedVal, rightUnionTypedVal, exitBB, strictEquals);
  4750. }
  4751. }
  4752. else
  4753. {
  4754. BfExprEvaluator exprEvaluator(this);
  4755. BfTypedValue leftTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[0]);
  4756. BfTypedValue rightTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  4757. bool hadComparison = false;
  4758. for (auto& fieldRef : compareTypeInst->mFieldInstances)
  4759. {
  4760. BfFieldInstance* fieldInstance = &fieldRef;
  4761. if (fieldInstance->mDataOffset == -1)
  4762. continue;
  4763. if (fieldInstance->mResolvedType->IsValuelessType())
  4764. continue;
  4765. if (fieldInstance->mResolvedType->IsVar())
  4766. continue;
  4767. BfTypedValue leftValue = ExtractValue(leftTypedVal, fieldInstance, fieldInstance->mDataIdx);
  4768. BfTypedValue rightValue = ExtractValue(rightTypedVal, fieldInstance, fieldInstance->mDataIdx);
  4769. if (!fieldInstance->mResolvedType->IsComposite())
  4770. {
  4771. leftValue = LoadValue(leftValue);
  4772. rightValue = LoadValue(rightValue);
  4773. }
  4774. EmitEquals(leftValue, rightValue, exitBB, strictEquals);
  4775. }
  4776. auto baseTypeInst = compareTypeInst->mBaseType;
  4777. if ((baseTypeInst != NULL) && (baseTypeInst->mTypeDef != mCompiler->mValueTypeTypeDef))
  4778. {
  4779. BfTypedValue leftValue = Cast(NULL, leftTypedVal, baseTypeInst);
  4780. BfTypedValue rightValue = Cast(NULL, rightTypedVal, baseTypeInst);
  4781. EmitEquals(leftValue, rightValue, exitBB, strictEquals);
  4782. }
  4783. }
  4784. mBfIRBuilder->CreateStore(GetConstValue(1, boolType), resultVal);
  4785. mBfIRBuilder->CreateBr(exitBB);
  4786. mBfIRBuilder->AddBlock(exitBB);
  4787. mBfIRBuilder->SetInsertPoint(exitBB);
  4788. auto loadedResult = mBfIRBuilder->CreateLoad(resultVal);
  4789. ClearLifetimeEnds();
  4790. mBfIRBuilder->CreateRet(loadedResult);
  4791. mCurMethodState->mHadReturn = true;
  4792. }
  4793. BfIRValue BfModule::CreateClassVDataGlobal(BfTypeInstance* typeInstance, int* outNumElements, String* outMangledName)
  4794. {
  4795. if (mBfIRBuilder->mIgnoreWrites)
  4796. return mBfIRBuilder->GetFakeVal();
  4797. PopulateType(typeInstance, mIsComptimeModule ? BfPopulateType_Data : BfPopulateType_DataAndMethods);
  4798. BfType* classVDataType = ResolveTypeDef(mCompiler->mClassVDataTypeDef);
  4799. if (mIsComptimeModule)
  4800. {
  4801. auto idVal = mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, typeInstance->mTypeId);
  4802. return mBfIRBuilder->CreateIntToPtr(idVal, mBfIRBuilder->MapType(CreatePointerType(classVDataType)));
  4803. }
  4804. BfIRValue* globalVariablePtr = NULL;
  4805. mClassVDataRefs.TryGetValue(typeInstance, &globalVariablePtr);
  4806. int numElements = 1;
  4807. if (mSystem->mPtrSize == 4)
  4808. numElements++;
  4809. if ((outNumElements != NULL) || (globalVariablePtr == NULL))
  4810. {
  4811. numElements += mCompiler->mMaxInterfaceSlots;
  4812. auto maxIFaceVirtIdx = 0;
  4813. if (!typeInstance->IsInterface())
  4814. {
  4815. int dynCastDataElems = 1 + mCompiler->mMaxInterfaceSlots;
  4816. numElements += ((dynCastDataElems * 4) + mSystem->mPtrSize - 1) / mSystem->mPtrSize;
  4817. numElements += typeInstance->GetOrigVTableSize();
  4818. int ifaceMethodLen = typeInstance->GetIFaceVMethodSize();
  4819. if (typeInstance->mHotTypeData != NULL)
  4820. {
  4821. if (typeInstance->mHotTypeData->mOrigInterfaceMethodsLength != -1)
  4822. ifaceMethodLen = typeInstance->mHotTypeData->mOrigInterfaceMethodsLength;
  4823. }
  4824. numElements += ifaceMethodLen;
  4825. }
  4826. if (outNumElements != NULL)
  4827. *outNumElements = numElements;
  4828. }
  4829. StringT<128> classVDataName;
  4830. String memberName = "sBfClassVData";
  4831. if ((typeInstance->mHotTypeData != NULL) && ((typeInstance->mHotTypeData->mHadDataChange) || (typeInstance->mHotTypeData->mPendingDataChange)))
  4832. {
  4833. auto curVersion = typeInstance->mHotTypeData->GetLatestVersion();
  4834. memberName += "_";
  4835. memberName += BfTypeUtils::HashEncode64(curVersion->mDataHash.mLow);
  4836. memberName += BfTypeUtils::HashEncode64(curVersion->mDataHash.mHigh);
  4837. }
  4838. BfMangler::MangleStaticFieldName(classVDataName, mCompiler->GetMangleKind(), typeInstance, memberName, classVDataType);
  4839. if (outMangledName != NULL)
  4840. *outMangledName = classVDataName;
  4841. BfIRValue globalVariable;
  4842. if (globalVariablePtr != NULL)
  4843. {
  4844. globalVariable = *globalVariablePtr;
  4845. }
  4846. else
  4847. {
  4848. BfLogSysM("Creating VData %s\n", classVDataName.c_str());
  4849. auto arrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr), numElements);
  4850. globalVariable = mBfIRBuilder->CreateGlobalVariable(
  4851. arrayType,
  4852. true,
  4853. BfIRLinkageType_External,
  4854. BfIRValue(),
  4855. classVDataName);
  4856. mClassVDataRefs[typeInstance] = globalVariable;
  4857. }
  4858. return globalVariable;
  4859. }
  4860. BfIRValue BfModule::GetClassVDataPtr(BfTypeInstance* typeInstance)
  4861. {
  4862. auto classVDataType = ResolveTypeDef(mCompiler->mClassVDataTypeDef);
  4863. if (mIsComptimeModule)
  4864. return mBfIRBuilder->Comptime_GetBfType(typeInstance->mTypeId, mBfIRBuilder->MapType(CreatePointerType(classVDataType)));
  4865. return mBfIRBuilder->CreateBitCast(CreateClassVDataGlobal(typeInstance), mBfIRBuilder->MapType(CreatePointerType(classVDataType)));
  4866. }
  4867. BfIRValue BfModule::CreateClassVDataExtGlobal(BfTypeInstance* declTypeInst, BfTypeInstance* implTypeInst, int startVirtIdx)
  4868. {
  4869. if (mBfIRBuilder->mIgnoreWrites)
  4870. return mBfIRBuilder->GetFakeVal();
  4871. int numElements = declTypeInst->GetSelfVTableSize() - declTypeInst->GetOrigSelfVTableSize();
  4872. if (numElements < 0)
  4873. InternalError("CreateClassVDataExtGlobal numElements < 0");
  4874. if (numElements <= 0)
  4875. return BfIRValue();
  4876. BF_ASSERT(implTypeInst->mVirtualMethodTable[startVirtIdx].mDeclaringMethod.mMethodNum == -1);
  4877. BF_ASSERT(implTypeInst->mVirtualMethodTable[startVirtIdx].mDeclaringMethod.mTypeInstance == declTypeInst);
  4878. if (declTypeInst->mInheritDepth == implTypeInst->mInheritDepth)
  4879. BF_ASSERT(declTypeInst == implTypeInst);
  4880. else
  4881. BF_ASSERT(implTypeInst->mInheritDepth > declTypeInst->mInheritDepth);
  4882. if (declTypeInst != implTypeInst)
  4883. {
  4884. BfTypeInstance* highestImpl = declTypeInst;
  4885. for (int virtIdx = startVirtIdx + 1; virtIdx < (int)declTypeInst->mVirtualMethodTable.size(); virtIdx++)
  4886. {
  4887. if (implTypeInst->mVirtualMethodTable[virtIdx].mDeclaringMethod.mMethodNum == -1)
  4888. break; // Start of an ext entry for another type
  4889. auto checkImplTypeInst = implTypeInst->mVirtualMethodTable[virtIdx].mImplementingMethod.mTypeInstance;
  4890. if ((checkImplTypeInst != NULL) && (checkImplTypeInst->mInheritDepth > highestImpl->mInheritDepth))
  4891. highestImpl = checkImplTypeInst;
  4892. }
  4893. if (highestImpl != implTypeInst)
  4894. return CreateClassVDataExtGlobal(declTypeInst, highestImpl, startVirtIdx);
  4895. }
  4896. BfVDataExtEntry mapEntry;
  4897. mapEntry.mDeclTypeInst = declTypeInst;
  4898. mapEntry.mImplTypeInst = implTypeInst;
  4899. BfIRValue* irValuePtr = NULL;
  4900. if (mClassVDataExtRefs.TryGetValue(mapEntry, &irValuePtr))
  4901. return *irValuePtr;
  4902. PopulateType(declTypeInst, BfPopulateType_DataAndMethods);
  4903. PopulateType(implTypeInst, BfPopulateType_DataAndMethods);
  4904. StringT<512> classVDataName;
  4905. BfMangler::MangleStaticFieldName(classVDataName, mCompiler->GetMangleKind(), implTypeInst, "bf_hs_replace_VDataExt");
  4906. if (declTypeInst != implTypeInst)
  4907. {
  4908. classVDataName += StrFormat("_%d", implTypeInst->mInheritDepth - declTypeInst->mInheritDepth);
  4909. }
  4910. auto voidPtrType = GetPrimitiveType(BfTypeCode_NullPtr);
  4911. auto voidPtrIRType = mBfIRBuilder->MapType(voidPtrType);
  4912. SizedArray<BfIRValue, 32> vData;
  4913. auto voidPtrNull = GetDefaultValue(voidPtrType);
  4914. for (int virtIdx = startVirtIdx + declTypeInst->GetOrigSelfVTableSize(); virtIdx < (int)declTypeInst->mVirtualMethodTable.size(); virtIdx++)
  4915. {
  4916. if (implTypeInst->mVirtualMethodTable[virtIdx].mDeclaringMethod.mMethodNum == -1)
  4917. break; // Start of an ext entry for another type
  4918. BfIRValue vValue;
  4919. auto& entry = implTypeInst->mVirtualMethodTable[virtIdx];
  4920. BfMethodInstance* declaringMethodInstance = (BfMethodInstance*)entry.mDeclaringMethod;
  4921. if ((declaringMethodInstance != NULL) && (declaringMethodInstance->mMethodInstanceGroup->IsImplemented()) && (declaringMethodInstance->mIsReified))
  4922. {
  4923. BF_ASSERT(entry.mImplementingMethod.mTypeInstance->mMethodInstanceGroups[entry.mImplementingMethod.mMethodNum].IsImplemented());
  4924. BF_ASSERT(entry.mImplementingMethod.mTypeInstance->mMethodInstanceGroups[entry.mImplementingMethod.mMethodNum].mDefault->mIsReified);
  4925. BfMethodInstance* methodInstance = (BfMethodInstance*)entry.mImplementingMethod;
  4926. if ((methodInstance != NULL) && (!methodInstance->mMethodDef->mIsAbstract))
  4927. {
  4928. BF_ASSERT(implTypeInst->IsTypeMemberAccessible(methodInstance->mMethodDef->mDeclaringType, mProject));
  4929. auto moduleMethodInst = GetMethodInstanceAtIdx(methodInstance->mMethodInstanceGroup->mOwner, methodInstance->mMethodInstanceGroup->mMethodIdx, NULL, BfGetMethodInstanceFlag_NoInline);
  4930. auto funcPtr = mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, voidPtrIRType);
  4931. vValue = funcPtr;
  4932. }
  4933. }
  4934. if (!vValue)
  4935. vValue = voidPtrNull;
  4936. vData.Add(vValue);
  4937. }
  4938. BF_ASSERT((int)vData.size() == numElements);
  4939. BfLogSysM("Creating VDataExt %s\n", classVDataName.c_str());
  4940. auto arrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr), numElements);
  4941. auto globalVariable = mBfIRBuilder->CreateGlobalVariable(arrayType, true,
  4942. BfIRLinkageType_External, BfIRValue(), classVDataName);
  4943. BfIRType extVTableType = mBfIRBuilder->GetSizedArrayType(voidPtrIRType, (int)vData.size());
  4944. BfIRValue extVTableConst = mBfIRBuilder->CreateConstAgg_Value(extVTableType, vData);
  4945. mBfIRBuilder->GlobalVar_SetInitializer(globalVariable, extVTableConst);
  4946. mClassVDataExtRefs[mapEntry] = globalVariable;
  4947. return globalVariable;
  4948. }
  4949. BfIRValue BfModule::CreateTypeDataRef(BfType* type, bool forceConstant)
  4950. {
  4951. if (mBfIRBuilder->mIgnoreWrites)
  4952. {
  4953. return mBfIRBuilder->CreateTypeOf(type);
  4954. }
  4955. if (mIsComptimeModule)
  4956. {
  4957. if (forceConstant)
  4958. return mBfIRBuilder->CreateTypeOfComptime(type);
  4959. auto typeTypeDef = ResolveTypeDef(mCompiler->mTypeTypeDef);
  4960. auto typeTypeInst = typeTypeDef->ToTypeInstance();
  4961. return mBfIRBuilder->Comptime_GetReflectType(type->mTypeId, mBfIRBuilder->MapType(typeTypeInst));
  4962. }
  4963. PopulateType(type);
  4964. BfIRValue globalVariable;
  4965. BfIRValue* globalVariablePtr = NULL;
  4966. if (mTypeDataRefs.TryGetValue(type, &globalVariablePtr))
  4967. {
  4968. if (*globalVariablePtr)
  4969. return mBfIRBuilder->CreateTypeOf(type, *globalVariablePtr);
  4970. }
  4971. auto typeTypeDef = ResolveTypeDef(mCompiler->mTypeTypeDef);
  4972. auto typeTypeInst = typeTypeDef->ToTypeInstance();
  4973. auto typeInstance = type->ToTypeInstance();
  4974. StringT<4096> typeDataName;
  4975. if (typeInstance != NULL)
  4976. {
  4977. BfMangler::MangleStaticFieldName(typeDataName, mCompiler->GetMangleKind(), typeInstance, "sBfTypeData");
  4978. }
  4979. else
  4980. {
  4981. typeDataName += "sBfTypeData.";
  4982. BfMangler::Mangle(typeDataName, mCompiler->GetMangleKind(), type, this);
  4983. }
  4984. BfLogSysM("Creating TypeData %s\n", typeDataName.c_str());
  4985. globalVariable = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapTypeInst(typeTypeInst, BfIRPopulateType_Full), true, BfIRLinkageType_External, BfIRValue(), typeDataName);
  4986. mBfIRBuilder->SetReflectTypeData(mBfIRBuilder->MapType(type), globalVariable);
  4987. mTypeDataRefs[type] = globalVariable;
  4988. return mBfIRBuilder->CreateTypeOf(type, globalVariable);
  4989. }
  4990. void BfModule::EncodeAttributeData(BfTypeInstance* typeInstance, BfType* argType, BfIRValue arg, SizedArrayImpl<uint8>& data, Dictionary<int, int>& usedStringIdMap)
  4991. {
  4992. #define PUSH_INT8(val) data.push_back((uint8)val)
  4993. #define PUSH_INT16(val) { data.push_back(val & 0xFF); data.push_back((val >> 8) & 0xFF); }
  4994. #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); }
  4995. #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); \
  4996. data.push_back((val >> 32) & 0xFF); data.push_back((val >> 40) & 0xFF); data.push_back((val >> 48) & 0xFF); data.push_back((val >> 56) & 0xFF); }
  4997. auto constant = typeInstance->mConstHolder->GetConstant(arg);
  4998. bool handled = false;
  4999. if (constant == NULL)
  5000. {
  5001. Fail(StrFormat("Unhandled attribute constant data in '%s'", TypeToString(typeInstance).c_str()));
  5002. return;
  5003. }
  5004. if (argType->IsObject())
  5005. {
  5006. if ((argType->IsInstanceOf(mCompiler->mStringTypeDef)) || (argType == mContext->mBfObjectType))
  5007. {
  5008. if (constant->mTypeCode == BfTypeCode_StringId)
  5009. {
  5010. int stringId = constant->mInt32;
  5011. int* orderedIdPtr;
  5012. if (usedStringIdMap.TryAdd(stringId, NULL, &orderedIdPtr))
  5013. {
  5014. *orderedIdPtr = (int)usedStringIdMap.size() - 1;
  5015. }
  5016. GetStringObjectValue(stringId, true, true);
  5017. PUSH_INT8(0xFF); // String
  5018. PUSH_INT32(*orderedIdPtr);
  5019. return;
  5020. }
  5021. }
  5022. }
  5023. if (argType->IsPointer())
  5024. {
  5025. if (argType->GetUnderlyingType() == GetPrimitiveType(BfTypeCode_Char8))
  5026. {
  5027. if (constant->mTypeCode == BfTypeCode_StringId)
  5028. {
  5029. int stringId = constant->mInt32;
  5030. int* orderedIdPtr;
  5031. if (usedStringIdMap.TryAdd(stringId, NULL, &orderedIdPtr))
  5032. {
  5033. *orderedIdPtr = (int)usedStringIdMap.size() - 1;
  5034. }
  5035. GetStringObjectValue(stringId, true, true);
  5036. PUSH_INT8(0xFF); // String
  5037. PUSH_INT32(*orderedIdPtr);
  5038. return;
  5039. }
  5040. }
  5041. }
  5042. if (constant->mConstType == BfConstType_BitCastNull)
  5043. {
  5044. PUSH_INT8(BfTypeCode_NullPtr);
  5045. return;
  5046. }
  5047. if (constant->mConstType == BfConstType_BitCast)
  5048. {
  5049. auto bitcast = (BfConstantBitCast*)constant;
  5050. EncodeAttributeData(typeInstance, argType, BfIRValue(BfIRValueFlags_Const, bitcast->mTarget), data, usedStringIdMap);
  5051. return;
  5052. }
  5053. PUSH_INT8(constant->mTypeCode);
  5054. if ((constant->mTypeCode == BfTypeCode_Int64) ||
  5055. (constant->mTypeCode == BfTypeCode_UInt64) ||
  5056. (constant->mTypeCode == BfTypeCode_Double))
  5057. {
  5058. PUSH_INT64(constant->mInt64);
  5059. }
  5060. else if ((constant->mTypeCode == BfTypeCode_Int32) ||
  5061. (constant->mTypeCode == BfTypeCode_UInt32) ||
  5062. (constant->mTypeCode == BfTypeCode_Char32))
  5063. {
  5064. PUSH_INT32(constant->mInt32);
  5065. }
  5066. else if (constant->mTypeCode == BfTypeCode_Float)
  5067. {
  5068. float val = (float)constant->mDouble;
  5069. PUSH_INT32(*(int*)&val);
  5070. }
  5071. else if ((constant->mTypeCode == BfTypeCode_Int16) ||
  5072. (constant->mTypeCode == BfTypeCode_UInt16) ||
  5073. (constant->mTypeCode == BfTypeCode_Char16))
  5074. {
  5075. PUSH_INT16(constant->mInt16);
  5076. }
  5077. else if ((constant->mTypeCode == BfTypeCode_Int8) ||
  5078. (constant->mTypeCode == BfTypeCode_UInt8) ||
  5079. (constant->mTypeCode == BfTypeCode_Boolean) ||
  5080. (constant->mTypeCode == BfTypeCode_Char8))
  5081. {
  5082. PUSH_INT8(constant->mInt8);
  5083. }
  5084. else if (constant->mConstType == BfConstType_TypeOf)
  5085. {
  5086. auto typeOf = (BfTypeOf_Const*)constant;
  5087. PUSH_INT32(typeOf->mType->mTypeId);
  5088. }
  5089. else if (constant->mConstType == BfConstType_AggZero)
  5090. {
  5091. for (int i = 0; i < argType->mSize; i++)
  5092. data.Add(0);
  5093. }
  5094. else if (constant->mConstType == BfConstType_Box)
  5095. {
  5096. auto box = (BfConstantBox*)constant;
  5097. PUSH_INT32(box->mToType.mId);
  5098. BfType* resultType = NULL;
  5099. if (box->mToType.mKind == BfIRTypeData::TypeKind_TypeId)
  5100. resultType = mContext->FindTypeById(box->mToType.mId);
  5101. if ((resultType != NULL) && (resultType->IsBoxed()))
  5102. {
  5103. auto boxedType = (BfBoxedType*)resultType;
  5104. int dataOffset = 0;
  5105. if (!boxedType->mFieldInstances.IsEmpty())
  5106. dataOffset = BF_MAX(boxedType->mFieldInstances.back().mDataOffset, 0);
  5107. int dataSize = boxedType->mInstSize - dataOffset;
  5108. for (int i = 0; i < dataSize; i++)
  5109. data.Add(0);
  5110. typeInstance->mConstHolder->WriteConstant(BfIRValue(BfIRValueFlags_Const, box->mTarget), &data[data.mSize - dataSize], boxedType->GetUnderlyingType());
  5111. return;
  5112. }
  5113. //int dataOffset =
  5114. //mBfIRBuilder->WriteConstant()
  5115. // BfType* resultType = NULL;
  5116. // if (box->mToType.mKind == BfIRTypeData::TypeKind_TypeId)
  5117. // resultType = mContext->FindTypeById(box->mToType.mId);
  5118. //
  5119. // if ((resultType != NULL) && (resultType->IsBoxed()))
  5120. // {
  5121. // auto boxedType = (BfBoxedType*)resultType;
  5122. // EncodeAttributeData(typeInstance, boxedType->GetUnderlyingType(), BfIRValue(BfIRValueFlags_Const, box->mTarget), data, usedStringIdMap);
  5123. // return;
  5124. // }
  5125. Fail(StrFormat("Unhandled constant box in '%s'", TypeToString(typeInstance).c_str()));
  5126. }
  5127. // else if (constant->mConstType == BfConstType_Agg)
  5128. // {
  5129. // BF_ASSERT(argType->IsComposite());
  5130. // if (argType->IsSizedArray())
  5131. // {
  5132. // auto argSizedArrayType = (BfSizedArrayType*)argType;
  5133. // }
  5134. // else
  5135. // {
  5136. // auto argTypeInstance = argType->ToTypeInstance();
  5137. // }
  5138. // }
  5139. else
  5140. {
  5141. Fail(StrFormat("Unhandled attribute constant data in '%s'", TypeToString(typeInstance).c_str()));
  5142. }
  5143. }
  5144. BfIRValue BfModule::CreateFieldData(BfFieldInstance* fieldInstance, int customAttrIdx)
  5145. {
  5146. bool isComptimeArg = mBfIRBuilder->mIgnoreWrites;
  5147. BfFieldDef* fieldDef = fieldInstance->GetFieldDef();
  5148. auto typeInstance = fieldInstance->mOwner;
  5149. BfType* intType = GetPrimitiveType(BfTypeCode_Int32);
  5150. BfType* intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  5151. BfType* shortType = GetPrimitiveType(BfTypeCode_Int16);
  5152. BfType* typeIdType = intType;
  5153. BfTypeInstance* reflectFieldDataType = ResolveTypeDef(mCompiler->mReflectFieldDataDef)->ToTypeInstance();
  5154. BfIRValue emptyValueType = mBfIRBuilder->mIgnoreWrites ?
  5155. mBfIRBuilder->CreateConstAgg(mBfIRBuilder->MapTypeInst(reflectFieldDataType->mBaseType), SizedArray<BfIRValue, 1>()) :
  5156. mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectFieldDataType->mBaseType), SizedArray<BfIRValue, 1>());
  5157. BfIRValue fieldNameConst = GetStringObjectValue(fieldDef->mName, !mIsComptimeModule);
  5158. bool is32Bit = mCompiler->mSystem->mPtrSize == 4;
  5159. int typeId = 0;
  5160. auto fieldType = fieldInstance->GetResolvedType();
  5161. if (fieldType->IsGenericParam())
  5162. {
  5163. //TODO:
  5164. }
  5165. else
  5166. typeId = fieldType->mTypeId;
  5167. BfFieldFlags fieldFlags = (BfFieldFlags)0;
  5168. if (fieldDef->mProtection == BfProtection_Protected)
  5169. fieldFlags = (BfFieldFlags)(fieldFlags | BfFieldFlags_Protected);
  5170. if (fieldDef->mProtection == BfProtection_Public)
  5171. fieldFlags = (BfFieldFlags)(fieldFlags | BfFieldFlags_Public);
  5172. if (fieldDef->mIsStatic)
  5173. fieldFlags = (BfFieldFlags)(fieldFlags | BfFieldFlags_Static);
  5174. if (fieldDef->mIsConst)
  5175. fieldFlags = (BfFieldFlags)(fieldFlags | BfFieldFlags_Const);
  5176. if (fieldDef->IsEnumCaseEntry())
  5177. fieldFlags = (BfFieldFlags)(fieldFlags | BfFieldFlags_EnumCase);
  5178. if (fieldDef->mIsReadOnly)
  5179. fieldFlags = (BfFieldFlags)(fieldFlags | BfFieldFlags_ReadOnly);
  5180. if (fieldInstance->IsAppendedObject())
  5181. fieldFlags = (BfFieldFlags)(fieldFlags | BfFieldFlags_Appended);
  5182. BfIRValue constValue;
  5183. BfIRValue constValue2;
  5184. if (fieldInstance->mIsEnumPayloadCase)
  5185. {
  5186. int tagId = -fieldInstance->mDataIdx - 1;
  5187. constValue = mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, tagId);
  5188. }
  5189. else if (fieldInstance->GetFieldDef()->mIsConst)
  5190. {
  5191. if (fieldInstance->mConstIdx != -1)
  5192. {
  5193. auto constant = typeInstance->mConstHolder->GetConstantById(fieldInstance->mConstIdx);
  5194. uint64 val = constant->mUInt64;
  5195. if (constant->mTypeCode == BfTypeCode_Float)
  5196. {
  5197. float f = (float)*(double*)&val;
  5198. val = *(uint32*)&f;
  5199. }
  5200. constValue = mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, val);
  5201. if (is32Bit)
  5202. constValue2 = mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, val >> 32);
  5203. }
  5204. }
  5205. else if (fieldInstance->GetFieldDef()->mIsStatic)
  5206. {
  5207. BfTypedValue refVal;
  5208. if (mIsComptimeModule)
  5209. {
  5210. constValue = mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, fieldInstance->mFieldIdx);
  5211. }
  5212. else
  5213. {
  5214. refVal = ReferenceStaticField(fieldInstance);
  5215. }
  5216. if (refVal.mValue.IsConst())
  5217. {
  5218. auto constant = mBfIRBuilder->GetConstant(refVal.mValue);
  5219. if (constant->mConstType == BfConstType_GlobalVar)
  5220. {
  5221. auto globalVar = (BfGlobalVar*)constant;
  5222. if (globalVar->mName[0] == '#')
  5223. refVal = BfTypedValue();
  5224. }
  5225. }
  5226. if (!isComptimeArg)
  5227. {
  5228. if (refVal.IsAddr())
  5229. constValue = mBfIRBuilder->CreatePtrToInt(refVal.mValue, BfTypeCode_IntPtr);
  5230. else if ((fieldInstance->IsAppendedObject()) && (refVal))
  5231. constValue = mBfIRBuilder->CreatePtrToInt(refVal.mValue, BfTypeCode_IntPtr);
  5232. }
  5233. }
  5234. if (!constValue)
  5235. constValue = mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, fieldInstance->mDataOffset);
  5236. BfIRValue result;
  5237. if (is32Bit)
  5238. {
  5239. if (!constValue2)
  5240. constValue2 = mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 0);
  5241. SizedArray<BfIRValue, 8> fieldVals =
  5242. {
  5243. emptyValueType,
  5244. fieldNameConst, // mName
  5245. GetConstValue(typeId, typeIdType), // mFieldTypeId
  5246. constValue, // mData
  5247. constValue2, // mDataHi
  5248. GetConstValue(fieldFlags, shortType), // mFlags
  5249. GetConstValue((isComptimeArg || mIsComptimeModule) ? fieldInstance->mFieldIdx : customAttrIdx, intType), // mCustomAttributesIdx
  5250. };
  5251. FixConstValueParams(reflectFieldDataType, fieldVals, isComptimeArg);
  5252. result = isComptimeArg ?
  5253. mBfIRBuilder->CreateConstAgg(mBfIRBuilder->MapTypeInst(reflectFieldDataType, BfIRPopulateType_Full), fieldVals) :
  5254. mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectFieldDataType, BfIRPopulateType_Full), fieldVals);
  5255. }
  5256. else
  5257. {
  5258. SizedArray<BfIRValue, 8> fieldVals =
  5259. {
  5260. emptyValueType,
  5261. fieldNameConst, // mName
  5262. GetConstValue(typeId, typeIdType), // mFieldTypeId
  5263. constValue, // mData
  5264. GetConstValue(fieldFlags, shortType), // mFlags
  5265. GetConstValue((isComptimeArg || mIsComptimeModule) ? fieldInstance->mFieldIdx : customAttrIdx, intType), // mCustomAttributesIdx
  5266. };
  5267. FixConstValueParams(reflectFieldDataType, fieldVals, isComptimeArg);
  5268. result = isComptimeArg ?
  5269. mBfIRBuilder->CreateConstAgg(mBfIRBuilder->MapTypeInst(reflectFieldDataType, BfIRPopulateType_Full), fieldVals) :
  5270. mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectFieldDataType, BfIRPopulateType_Full), fieldVals);
  5271. }
  5272. return result;
  5273. }
  5274. void BfModule::CreateSlotOfs(BfTypeInstance* typeInstance)
  5275. {
  5276. int virtSlotIdx = -1;
  5277. if ((typeInstance != NULL) && (typeInstance->mSlotNum >= 0))
  5278. virtSlotIdx = typeInstance->mSlotNum + mCompiler->GetVDataPrefixDataCount() + mCompiler->GetDynCastVDataCount();
  5279. // For interfaces we ONLY emit the slot num
  5280. StringT<512> slotVarName;
  5281. BfMangler::MangleStaticFieldName(slotVarName, mCompiler->GetMangleKind(), typeInstance, "sBfSlotOfs");
  5282. auto intType = GetPrimitiveType(BfTypeCode_Int32);
  5283. auto slotNumVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapType(intType), true, BfIRLinkageType_External,
  5284. GetConstValue32(virtSlotIdx), slotVarName);
  5285. }
  5286. BfIRValue BfModule::GetTypeTypeData(BfType* type, BfCreateTypeDataContext& ctx, bool needsTypeData, bool wantsTypeDecl, bool needsTypeNames, int& typeFlags, int& typeCode)
  5287. {
  5288. BfTypeInstance* typeInstance = type->ToTypeInstance();
  5289. BfType* typeInstanceType = ResolveTypeDef(mCompiler->mReflectTypeInstanceTypeDef);
  5290. mBfIRBuilder->PopulateType(typeInstanceType, BfIRPopulateType_Full_ForceDefinition);
  5291. BfIRValue typeTypeData;
  5292. if (needsTypeData)
  5293. {
  5294. BfTypeInstance* typeInstanceTypeInstance = typeInstanceType->ToTypeInstance();
  5295. BfTypeInstance* typeDataSource = NULL;
  5296. if (typeInstance != NULL)
  5297. {
  5298. if (typeInstance->IsUnspecializedType())
  5299. {
  5300. typeDataSource = ResolveTypeDef(mCompiler->mReflectUnspecializedGenericType)->ToTypeInstance();
  5301. typeFlags |= BfTypeFlags_UnspecializedGeneric;
  5302. }
  5303. else if (typeInstance->IsArray())
  5304. {
  5305. typeDataSource = ResolveTypeDef(mCompiler->mReflectArrayType)->ToTypeInstance();
  5306. typeFlags |= BfTypeFlags_Array;
  5307. }
  5308. else if (typeInstance->IsGenericTypeInstance())
  5309. {
  5310. typeDataSource = ResolveTypeDef(mCompiler->mReflectSpecializedGenericType)->ToTypeInstance();
  5311. typeFlags |= BfTypeFlags_SpecializedGeneric;
  5312. }
  5313. else
  5314. typeDataSource = typeInstanceTypeInstance;
  5315. }
  5316. else if (type->IsPointer())
  5317. typeDataSource = ResolveTypeDef(mCompiler->mReflectPointerType)->ToTypeInstance();
  5318. else if (type->IsRef())
  5319. typeDataSource = ResolveTypeDef(mCompiler->mReflectRefType)->ToTypeInstance();
  5320. else if (type->IsSizedArray())
  5321. typeDataSource = ResolveTypeDef(mCompiler->mReflectSizedArrayType)->ToTypeInstance();
  5322. else if (type->IsConstExprValue())
  5323. typeDataSource = ResolveTypeDef(mCompiler->mReflectConstExprType)->ToTypeInstance();
  5324. else if (type->IsGenericParam())
  5325. {
  5326. typeFlags |= BfTypeFlags_GenericParam;
  5327. typeDataSource = ResolveTypeDef(mCompiler->mReflectGenericParamType)->ToTypeInstance();
  5328. }
  5329. else
  5330. typeDataSource = mContext->mBfTypeType;
  5331. if (wantsTypeDecl)
  5332. {
  5333. typeDataSource = ResolveTypeDef(mCompiler->mTypeTypeDeclDef)->ToTypeInstance();
  5334. }
  5335. if ((!mTypeDataRefs.ContainsKey(typeDataSource)) && (typeDataSource != type) && (!mIsComptimeModule))
  5336. {
  5337. CreateTypeData(typeDataSource, ctx, false, true, needsTypeNames, true);
  5338. }
  5339. typeTypeData = CreateClassVDataGlobal(typeDataSource);
  5340. ctx.mReflectTypeSet.Add(typeDataSource);
  5341. }
  5342. else
  5343. {
  5344. //typeTypeData = CreateClassVDataGlobal(typeInstanceType->ToTypeInstance());
  5345. typeTypeData = mBfIRBuilder->CreateConstNull();
  5346. }
  5347. if (typeInstance != NULL)
  5348. {
  5349. BF_ASSERT((type->mDefineState >= BfTypeDefineState_DefinedAndMethodsSlotted) || mIsComptimeModule);
  5350. typeCode = typeInstance->mTypeDef->mTypeCode;
  5351. if (typeInstance->IsBoxed())
  5352. typeCode = BfTypeCode_Object;
  5353. }
  5354. else if (type->IsPrimitiveType())
  5355. {
  5356. BfPrimitiveType* primType = (BfPrimitiveType*)type;
  5357. typeCode = primType->mTypeDef->mTypeCode;
  5358. }
  5359. else if (type->IsPointer())
  5360. {
  5361. typeCode = BfTypeCode_Pointer;
  5362. typeFlags |= BfTypeFlags_Pointer;
  5363. }
  5364. else if (type->IsRef())
  5365. {
  5366. typeCode = BfTypeCode_Pointer;
  5367. typeFlags |= BfTypeFlags_Pointer;
  5368. }
  5369. if (type->IsObject())
  5370. {
  5371. typeFlags |= BfTypeFlags_Object;
  5372. if ((!wantsTypeDecl) && (typeInstance->mDefineState >= BfTypeDefineState_DefinedAndMethodsSlotted))
  5373. {
  5374. BfMethodInstance* methodInstance = typeInstance->mVirtualMethodTable[mCompiler->GetVTableMethodOffset() + 0].mImplementingMethod;
  5375. if ((methodInstance != NULL) && (methodInstance->GetOwner() != mContext->mBfObjectType))
  5376. typeFlags |= BfTypeFlags_HasDestructor;
  5377. }
  5378. }
  5379. if (type->IsStruct())
  5380. typeFlags |= BfTypeFlags_Struct;
  5381. if (type->IsInterface())
  5382. typeFlags |= BfTypeFlags_Interface;
  5383. if (type->IsBoxed())
  5384. {
  5385. typeFlags |= BfTypeFlags_Boxed;
  5386. if (((BfBoxedType*)type)->IsBoxedStructPtr())
  5387. typeFlags |= BfTypeFlags_Pointer;
  5388. }
  5389. if (type->IsPrimitiveType())
  5390. typeFlags |= BfTypeFlags_Primitive;
  5391. if (type->IsTypedPrimitive())
  5392. typeFlags |= BfTypeFlags_TypedPrimitive;
  5393. if (type->IsTuple())
  5394. typeFlags |= BfTypeFlags_Tuple;
  5395. if (type->IsNullable())
  5396. typeFlags |= BfTypeFlags_Nullable;
  5397. if (type->IsSizedArray())
  5398. typeFlags |= BfTypeFlags_SizedArray;
  5399. if (type->IsConstExprValue())
  5400. typeFlags |= BfTypeFlags_ConstExpr;
  5401. if ((!wantsTypeDecl) && (type->IsSplattable()))
  5402. typeFlags |= BfTypeFlags_Splattable;
  5403. if (type->IsUnion())
  5404. typeFlags |= BfTypeFlags_Union;
  5405. if (type->IsDelegate())
  5406. typeFlags |= BfTypeFlags_Delegate;
  5407. if (type->IsFunction())
  5408. typeFlags |= BfTypeFlags_Function;
  5409. if ((!wantsTypeDecl) && (type->mDefineState != BfTypeDefineState_CETypeInit) && (type->WantsGCMarking()))
  5410. typeFlags |= BfTypeFlags_WantsMarking;
  5411. if ((typeInstance != NULL) && (typeInstance->mTypeDef->mIsStatic))
  5412. typeFlags |= BfTypeFlags_Static;
  5413. if ((typeInstance != NULL) && (typeInstance->mTypeDef->mIsAbstract))
  5414. typeFlags |= BfTypeFlags_Abstract;
  5415. if ((typeInstance != NULL) && (typeInstance->mHasAppendWantMark))
  5416. typeFlags |= BfTypeFlags_HasAppendWantMark;
  5417. return typeTypeData;
  5418. }
  5419. BfIRValue BfModule::CreateTypeDeclData(BfType* type, BfProject* curProject)
  5420. {
  5421. auto typeDeclType = ResolveTypeDef(mCompiler->mTypeTypeDeclDef)->ToTypeInstance();
  5422. int typeCode = 0;
  5423. int typeFlags = 0;
  5424. BfCreateTypeDataContext createTypeDataCtx;
  5425. BfIRValue typeTypeData = GetTypeTypeData(type, createTypeDataCtx, true, true, true, typeFlags, typeCode);
  5426. SizedArray<BfIRValue, 4> typeValueParams;
  5427. GetConstClassValueParam(typeTypeData, typeValueParams);
  5428. BfType* longType = GetPrimitiveType(BfTypeCode_Int64);
  5429. BfType* intType = GetPrimitiveType(BfTypeCode_Int32);
  5430. BfType* intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  5431. BfType* shortType = GetPrimitiveType(BfTypeCode_Int16);
  5432. BfType* byteType = GetPrimitiveType(BfTypeCode_Int8);
  5433. BfType* typeIdType = intType;
  5434. auto typeInst = type->ToTypeInstance();
  5435. auto outerType = GetOuterType(type);
  5436. BfType* baseType = NULL;
  5437. if (typeInst != NULL)
  5438. baseType = typeInst->mBaseType;
  5439. enum BfTypeDeclFlags
  5440. {
  5441. BfTypeDeclFlag_DeclaredInDependency = 1,
  5442. BfTypeDeclFlag_DeclaredInDependent = 2,
  5443. BfTypeDeclFlag_DeclaredInCurrent = 4,
  5444. BfTypeDeclFlag_AlwaysVisible = 8,
  5445. BfTypeDeclFlag_SometimesVisible = 0x10
  5446. };
  5447. int flags = 0;
  5448. if (typeInst != NULL)
  5449. {
  5450. auto declProject = typeInst->mTypeDef->mProject;
  5451. auto depKind = curProject->GetDependencyKind(declProject);
  5452. if (depKind == BfProject::DependencyKind_Identity)
  5453. {
  5454. flags |= BfTypeDeclFlag_DeclaredInCurrent | BfTypeDeclFlag_AlwaysVisible | BfTypeDeclFlag_SometimesVisible;
  5455. }
  5456. else if (depKind == BfProject::DependencyKind_Dependency)
  5457. {
  5458. flags |= BfTypeDeclFlag_DeclaredInDependency | BfTypeDeclFlag_AlwaysVisible | BfTypeDeclFlag_SometimesVisible;
  5459. }
  5460. else if (depKind == BfProject::DependencyKind_Dependent_Exclusive)
  5461. {
  5462. flags |= BfTypeDeclFlag_DeclaredInDependent | BfTypeDeclFlag_AlwaysVisible | BfTypeDeclFlag_SometimesVisible;
  5463. }
  5464. else if (depKind == BfProject::DependencyKind_Dependent_Shared)
  5465. {
  5466. flags |= BfTypeDeclFlag_DeclaredInDependent | BfTypeDeclFlag_SometimesVisible;
  5467. }
  5468. }
  5469. BfIRValue objectData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(mContext->mBfObjectType, BfIRPopulateType_Full), typeValueParams);
  5470. SizedArray<BfIRValue, 9> typeDataParams =
  5471. {
  5472. objectData,
  5473. GetConstValue(type->mTypeId, typeIdType), // mTypeId
  5474. GetConstValue((outerType != NULL) ? outerType->mTypeId : 0, typeIdType), // mOuterTypeId
  5475. GetConstValue(typeFlags, intType), // mTypeFlags
  5476. GetConstValue(flags, byteType), // mFlags
  5477. GetConstValue(typeCode, byteType), // mTypeCode
  5478. };
  5479. FixConstValueParams(typeDeclType, typeDataParams);
  5480. auto typeData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(typeDeclType, BfIRPopulateType_Full), typeDataParams);
  5481. String typeDataName = StrFormat("sBfTypeDeclData.%d", type->mTypeId);
  5482. BfIRValue typeDataVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapTypeInst(typeDeclType), true,
  5483. BfIRLinkageType_External, typeData, typeDataName);
  5484. mBfIRBuilder->GlobalVar_SetAlignment(typeDataVar, mSystem->mPtrSize);
  5485. return typeDataVar;
  5486. }
  5487. BfIRValue BfModule::CreateTypeData(BfType* type, BfCreateTypeDataContext& ctx, bool forceReflectFields, bool needsTypeData, bool needsTypeNames, bool needsVData)
  5488. {
  5489. if ((IsHotCompile()) && (!type->mDirty))
  5490. return BfIRValue();
  5491. BfIRValue* irValuePtr = NULL;
  5492. if (mTypeDataRefs.TryGetValue(type, &irValuePtr))
  5493. {
  5494. return *irValuePtr;
  5495. }
  5496. BfTypeInstance* typeInstance = type->ToTypeInstance();
  5497. BfType* typeInstanceType = ResolveTypeDef(mCompiler->mReflectTypeInstanceTypeDef);
  5498. mBfIRBuilder->PopulateType(typeInstanceType, BfIRPopulateType_Full_ForceDefinition);
  5499. if (typeInstanceType == NULL)
  5500. {
  5501. AssertErrorState();
  5502. return BfIRValue();
  5503. }
  5504. int typeCode = BfTypeCode_None;
  5505. int typeFlags = 0;
  5506. BfIRValue typeTypeData = GetTypeTypeData(type, ctx, needsTypeData, false, needsTypeNames, typeFlags, typeCode);
  5507. BfType* longType = GetPrimitiveType(BfTypeCode_Int64);
  5508. BfType* intType = GetPrimitiveType(BfTypeCode_Int32);
  5509. BfType* intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  5510. BfType* shortType = GetPrimitiveType(BfTypeCode_Int16);
  5511. BfType* byteType = GetPrimitiveType(BfTypeCode_Int8);
  5512. BfType* typeIdType = intType;
  5513. auto voidPtrType = GetPrimitiveType(BfTypeCode_NullPtr);
  5514. auto voidPtrIRType = mBfIRBuilder->MapType(voidPtrType);
  5515. auto voidPtrPtrIRType = mBfIRBuilder->GetPointerTo(voidPtrIRType);
  5516. auto voidPtrNull = GetDefaultValue(voidPtrType);
  5517. SizedArray<BfIRValue, 4> typeValueParams;
  5518. GetConstClassValueParam(typeTypeData, typeValueParams);
  5519. FixConstValueParams(mContext->mBfObjectType, typeValueParams);
  5520. BfIRValue objectData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(mContext->mBfObjectType, BfIRPopulateType_Full), typeValueParams);
  5521. StringT<512> typeDataName;
  5522. if ((typeInstance != NULL) && (!typeInstance->IsTypeAlias()))
  5523. {
  5524. BfMangler::MangleStaticFieldName(typeDataName, mCompiler->GetMangleKind(), typeInstance, "sBfTypeData");
  5525. if (typeInstance->mTypeDef->IsGlobalsContainer())
  5526. typeDataName += "`G`" + typeInstance->mTypeDef->mProject->mName;
  5527. }
  5528. else
  5529. {
  5530. typeDataName += "sBfTypeData.";
  5531. BfMangler::Mangle(typeDataName, mCompiler->GetMangleKind(), type, mContext->mScratchModule);
  5532. }
  5533. int virtSlotIdx = -1;
  5534. if ((typeInstance != NULL) && (typeInstance->mSlotNum >= 0))
  5535. virtSlotIdx = typeInstance->mSlotNum + mCompiler->GetVDataPrefixDataCount() + mCompiler->GetDynCastVDataCount();
  5536. int memberDataOffset = 0;
  5537. if (type->IsInterface())
  5538. memberDataOffset = virtSlotIdx * mSystem->mPtrSize;
  5539. else if (typeInstance != NULL)
  5540. {
  5541. for (auto& fieldInstance : typeInstance->mFieldInstances)
  5542. {
  5543. if (fieldInstance.mDataOffset != -1)
  5544. {
  5545. memberDataOffset = fieldInstance.mDataOffset;
  5546. break;
  5547. }
  5548. }
  5549. }
  5550. int boxedTypeId = 0;
  5551. if ((type->IsValueType()) || (type->IsWrappableType()))
  5552. {
  5553. auto boxedType = CreateBoxedType(type, false);
  5554. if ((boxedType != NULL) && (boxedType->mIsReified))
  5555. boxedTypeId = boxedType->mTypeId;
  5556. }
  5557. int stackCount = 0;
  5558. if ((typeInstance != NULL) && (typeInstance->mTypeOptionsIdx != -1))
  5559. {
  5560. auto typeOptions = mSystem->GetTypeOptions(typeInstance->mTypeOptionsIdx);
  5561. if (typeOptions->mAllocStackTraceDepth != -1)
  5562. stackCount = BF_MIN(0xFF, BF_MAX(0x01, typeOptions->mAllocStackTraceDepth));
  5563. }
  5564. SizedArray<BfIRValue, 9> typeDataParams =
  5565. {
  5566. objectData,
  5567. GetConstValue(type->mSize, intType), // mSize
  5568. GetConstValue(type->mTypeId, typeIdType), // mTypeId
  5569. GetConstValue(boxedTypeId, typeIdType), // mBoxedType
  5570. GetConstValue(typeFlags, intType), // mTypeFlags
  5571. GetConstValue(memberDataOffset, intType), // mMemberDataOffset
  5572. GetConstValue(typeCode, byteType), // mTypeCode
  5573. GetConstValue(type->mAlign, byteType), // mAlign
  5574. GetConstValue(stackCount, byteType), // mAllocStackCountOverride
  5575. };
  5576. FixConstValueParams(mContext->mBfTypeType, typeDataParams);
  5577. auto typeData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(mContext->mBfTypeType, BfIRPopulateType_Full), typeDataParams);
  5578. if (typeInstance == NULL)
  5579. {
  5580. BfIRValue typeDataVar;
  5581. if (needsTypeData)
  5582. {
  5583. if (type->IsPointer())
  5584. {
  5585. auto pointerType = (BfPointerType*)type;
  5586. SizedArray<BfIRValue, 3> pointerTypeDataParms =
  5587. {
  5588. typeData,
  5589. GetConstValue(pointerType->mElementType->mTypeId, typeIdType),
  5590. };
  5591. auto reflectPointerType = ResolveTypeDef(mCompiler->mReflectPointerType)->ToTypeInstance();
  5592. FixConstValueParams(reflectPointerType, pointerTypeDataParms);
  5593. auto pointerTypeData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectPointerType, BfIRPopulateType_Full), pointerTypeDataParms);
  5594. typeDataVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapTypeInst(reflectPointerType), true,
  5595. BfIRLinkageType_External, pointerTypeData, typeDataName);
  5596. mBfIRBuilder->GlobalVar_SetAlignment(typeDataVar, mSystem->mPtrSize);
  5597. typeDataVar = mBfIRBuilder->CreateBitCast(typeDataVar, mBfIRBuilder->MapType(mContext->mBfTypeType));
  5598. }
  5599. else if (type->IsRef())
  5600. {
  5601. auto refType = (BfRefType*)type;
  5602. SizedArray<BfIRValue, 3> refTypeDataParms =
  5603. {
  5604. typeData,
  5605. GetConstValue(refType->mElementType->mTypeId, typeIdType),
  5606. GetConstValue((int8)refType->mRefKind, byteType),
  5607. };
  5608. auto reflectRefType = ResolveTypeDef(mCompiler->mReflectRefType)->ToTypeInstance();
  5609. FixConstValueParams(reflectRefType, refTypeDataParms);
  5610. auto refTypeData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectRefType, BfIRPopulateType_Full), refTypeDataParms);
  5611. typeDataVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapTypeInst(reflectRefType), true,
  5612. BfIRLinkageType_External, refTypeData, typeDataName);
  5613. mBfIRBuilder->GlobalVar_SetAlignment(typeDataVar, mSystem->mPtrSize);
  5614. typeDataVar = mBfIRBuilder->CreateBitCast(typeDataVar, mBfIRBuilder->MapType(mContext->mBfTypeType));
  5615. }
  5616. else if (type->IsSizedArray())
  5617. {
  5618. auto sizedArrayType = (BfSizedArrayType*)type;
  5619. SizedArray<BfIRValue, 3> sizedArrayTypeDataParms =
  5620. {
  5621. typeData,
  5622. GetConstValue(sizedArrayType->mElementType->mTypeId, typeIdType),
  5623. GetConstValue(sizedArrayType->mElementCount, intType)
  5624. };
  5625. auto reflectSizedArrayType = ResolveTypeDef(mCompiler->mReflectSizedArrayType)->ToTypeInstance();
  5626. FixConstValueParams(reflectSizedArrayType, sizedArrayTypeDataParms);
  5627. auto sizedArrayTypeData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectSizedArrayType, BfIRPopulateType_Full), sizedArrayTypeDataParms);
  5628. typeDataVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapTypeInst(reflectSizedArrayType), true,
  5629. BfIRLinkageType_External, sizedArrayTypeData, typeDataName);
  5630. mBfIRBuilder->GlobalVar_SetAlignment(typeDataVar, mSystem->mPtrSize);
  5631. typeDataVar = mBfIRBuilder->CreateBitCast(typeDataVar, mBfIRBuilder->MapType(mContext->mBfTypeType));
  5632. }
  5633. else if (type->IsConstExprValue())
  5634. {
  5635. auto constExprType = (BfConstExprValueType*)type;
  5636. SizedArray<BfIRValue, 3> constExprTypeDataParms =
  5637. {
  5638. typeData,
  5639. GetConstValue(constExprType->mType->mTypeId, typeIdType),
  5640. GetConstValue(constExprType->mValue.mInt64, longType)
  5641. };
  5642. auto reflectConstExprType = ResolveTypeDef(mCompiler->mReflectConstExprType)->ToTypeInstance();
  5643. FixConstValueParams(reflectConstExprType, constExprTypeDataParms);
  5644. auto ConstExprTypeData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectConstExprType, BfIRPopulateType_Full), constExprTypeDataParms);
  5645. typeDataVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapTypeInst(reflectConstExprType), true,
  5646. BfIRLinkageType_External, ConstExprTypeData, typeDataName);
  5647. mBfIRBuilder->GlobalVar_SetAlignment(typeDataVar, mSystem->mPtrSize);
  5648. typeDataVar = mBfIRBuilder->CreateBitCast(typeDataVar, mBfIRBuilder->MapType(mContext->mBfTypeType));
  5649. }
  5650. else if (type->IsGenericParam())
  5651. {
  5652. auto genericParamType = (BfGenericParamType*)type;
  5653. SizedArray<BfIRValue, 3> genericParamTypeDataParms =
  5654. {
  5655. typeData
  5656. };
  5657. auto reflectGenericParamType = ResolveTypeDef(mCompiler->mReflectGenericParamType)->ToTypeInstance();
  5658. FixConstValueParams(reflectGenericParamType, genericParamTypeDataParms);
  5659. auto genericParamTypeData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectGenericParamType, BfIRPopulateType_Full), genericParamTypeDataParms);
  5660. typeDataVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapTypeInst(reflectGenericParamType), true,
  5661. BfIRLinkageType_External, genericParamTypeData, typeDataName);
  5662. mBfIRBuilder->GlobalVar_SetAlignment(typeDataVar, mSystem->mPtrSize);
  5663. typeDataVar = mBfIRBuilder->CreateBitCast(typeDataVar, mBfIRBuilder->MapType(mContext->mBfTypeType));
  5664. }
  5665. else
  5666. {
  5667. typeDataVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapTypeInst(mContext->mBfTypeType), true,
  5668. BfIRLinkageType_External, typeData, typeDataName);
  5669. mBfIRBuilder->GlobalVar_SetAlignment(typeDataVar, mSystem->mPtrSize);
  5670. }
  5671. }
  5672. else
  5673. typeDataVar = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(mContext->mBfTypeType));
  5674. mTypeDataRefs[type] = typeDataVar;
  5675. return typeDataVar;
  5676. }
  5677. // Reserve position
  5678. mTypeDataRefs[typeInstance] = BfIRValue();
  5679. if ((typeInstance->IsReified()) && (!mIsComptimeModule))
  5680. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  5681. BfTypeDef* typeDef = typeInstance->mTypeDef;
  5682. StringT<512> mangledName;
  5683. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), typeInstance, typeInstance->mModule);
  5684. if (!mIsComptimeModule)
  5685. {
  5686. for (int methodIdx = 0; methodIdx < (int)typeDef->mMethods.size(); methodIdx++)
  5687. {
  5688. auto methodDef = typeDef->mMethods[methodIdx];
  5689. auto methodInstance = typeInstance->mMethodInstanceGroups[methodIdx].mDefault;
  5690. if (methodInstance == NULL)
  5691. continue;
  5692. if (typeInstance->IsUnspecializedType())
  5693. continue;
  5694. if (!typeInstance->IsTypeMemberAccessible(methodDef->mDeclaringType, mProject))
  5695. {
  5696. if (methodInstance->mChainType == BfMethodChainType_ChainMember)
  5697. {
  5698. BF_ASSERT(!methodInstance->GetOwner()->IsUnspecializedType());
  5699. // We need to create an empty thunk for this chained method
  5700. BfIRFunction func = CreateFunctionFrom(methodInstance, false, methodInstance->mAlwaysInline);
  5701. mBfIRBuilder->SetActiveFunction(func);
  5702. auto block = mBfIRBuilder->CreateBlock("entry", true);
  5703. mBfIRBuilder->SetInsertPoint(block);
  5704. mBfIRBuilder->CreateRetVoid();
  5705. mBfIRBuilder->SetActiveFunction(BfIRFunction());
  5706. }
  5707. }
  5708. }
  5709. }
  5710. SizedArray<BfIRValue, 32> vData;
  5711. BfIRValue classVDataVar;
  5712. String classVDataName;
  5713. if (typeInstance->mSlotNum >= 0)
  5714. {
  5715. CreateSlotOfs(typeInstance);
  5716. }
  5717. else if ((typeInstance->IsObject()) && (!typeInstance->IsUnspecializedType()) && (needsVData))
  5718. {
  5719. int dynCastDataElems = 0;
  5720. int numElements = 1;
  5721. int vDataOfs = mCompiler->GetVDataPrefixDataCount(); // The number of intptrs before the iface slot map
  5722. numElements += mCompiler->mMaxInterfaceSlots;
  5723. if (!typeInstance->IsInterface())
  5724. {
  5725. dynCastDataElems = 1 + mCompiler->mMaxInterfaceSlots;
  5726. numElements += mCompiler->GetDynCastVDataCount();
  5727. numElements += typeInstance->mVirtualMethodTableSize;
  5728. }
  5729. int expectNumElements = 0;
  5730. if (!typeDef->mIsStatic)
  5731. {
  5732. classVDataVar = CreateClassVDataGlobal(typeInstance, &expectNumElements, &classVDataName);
  5733. }
  5734. for (int i = 0; i < mCompiler->GetVDataPrefixDataCount(); i++)
  5735. vData.push_back(BfIRValue()); // Type
  5736. SizedArray<BfIRValue, 1> extVTableData;
  5737. SizedArrayImpl<BfIRValue>* vFuncDataExt = &extVTableData;
  5738. if (!typeInstance->IsInterface())
  5739. {
  5740. Array<int32> dynCastData;
  5741. if (typeInstance->IsBoxed())
  5742. {
  5743. auto underlyingType = typeInstance->GetUnderlyingType()->ToTypeInstance();
  5744. dynCastData.Add(underlyingType->mInheritanceId);
  5745. }
  5746. else
  5747. dynCastData.Add(typeInstance->mInheritanceId);
  5748. for (int i = 0; i < mCompiler->mMaxInterfaceSlots; i++)
  5749. dynCastData.Add(0);
  5750. dynCastData.Add(0);
  5751. auto checkTypeInst = typeInstance;
  5752. while (checkTypeInst != NULL)
  5753. {
  5754. for (auto&& interfaceEntry : checkTypeInst->mInterfaces)
  5755. {
  5756. if (interfaceEntry.mInterfaceType->mSlotNum >= 0)
  5757. {
  5758. if (dynCastData[interfaceEntry.mInterfaceType->mSlotNum + 1] == 0)
  5759. dynCastData[interfaceEntry.mInterfaceType->mSlotNum + 1] = interfaceEntry.mInterfaceType->mTypeId;
  5760. }
  5761. }
  5762. checkTypeInst = checkTypeInst->GetImplBaseType();
  5763. }
  5764. if (mSystem->mPtrSize == 8)
  5765. {
  5766. int intPtrCount = (dynCastDataElems + 1) / 2;
  5767. vDataOfs += intPtrCount;
  5768. uint64* intPtrData = (uint64*)&dynCastData[0];
  5769. for (int i = 0; i < intPtrCount; i++)
  5770. {
  5771. uint64 val = intPtrData[i];
  5772. if (val == 0)
  5773. {
  5774. vData.push_back(voidPtrNull);
  5775. }
  5776. else
  5777. {
  5778. auto intPtrVal = mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, val);
  5779. vData.push_back(mBfIRBuilder->CreateBitCast(intPtrVal, voidPtrIRType));
  5780. }
  5781. }
  5782. }
  5783. else
  5784. {
  5785. int intPtrCount = dynCastDataElems;
  5786. vDataOfs += intPtrCount;
  5787. uint32* intPtrData = (uint32*)&dynCastData[0];
  5788. for (int i = 0; i < intPtrCount; i++)
  5789. {
  5790. uint32 val = intPtrData[i];
  5791. if (val == 0)
  5792. {
  5793. vData.push_back(voidPtrNull);
  5794. }
  5795. else
  5796. {
  5797. auto intPtrVal = mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, (int)val);
  5798. vData.push_back(mBfIRBuilder->CreateBitCast(intPtrVal, voidPtrIRType));
  5799. }
  5800. }
  5801. }
  5802. }
  5803. for (int iSlotIdx = 0; iSlotIdx < mCompiler->mMaxInterfaceSlots; iSlotIdx++)
  5804. vData.push_back(voidPtrNull);
  5805. struct _InterfaceMatchEntry
  5806. {
  5807. BfTypeInterfaceEntry* mEntry;
  5808. BfTypeInstance* mEntrySource;
  5809. Array<BfTypeInterfaceEntry*> mAmbiguousEntries;
  5810. };
  5811. int highestIFaceVirtIdx = 0;
  5812. Dictionary<BfTypeInstance*, _InterfaceMatchEntry> interfaceMap;
  5813. auto checkTypeInst = typeInstance;
  5814. bool forceInterfaceSet = false;
  5815. while (checkTypeInst != NULL)
  5816. {
  5817. for (auto&& interfaceEntry : checkTypeInst->mInterfaces)
  5818. {
  5819. highestIFaceVirtIdx = BF_MAX(highestIFaceVirtIdx, interfaceEntry.mStartVirtualIdx + interfaceEntry.mInterfaceType->mVirtualMethodTableSize);
  5820. if ((!mIsComptimeModule) && (!typeInstance->IsTypeMemberAccessible(interfaceEntry.mDeclaringType, mProject)))
  5821. continue;
  5822. _InterfaceMatchEntry* matchEntry = NULL;
  5823. if (interfaceMap.TryGetValue(interfaceEntry.mInterfaceType, &matchEntry))
  5824. {
  5825. BfTypeInstance* compareCheckTypeInst = checkTypeInst;
  5826. if (compareCheckTypeInst->IsBoxed())
  5827. compareCheckTypeInst = compareCheckTypeInst->GetUnderlyingType()->ToTypeInstance();
  5828. BfTypeInstance* compareEntrySource = matchEntry->mEntrySource;
  5829. if (compareEntrySource->IsBoxed())
  5830. compareEntrySource = compareEntrySource->GetUnderlyingType()->ToTypeInstance();
  5831. auto prevEntry = matchEntry->mEntry;
  5832. bool isBetter = TypeIsSubTypeOf(compareCheckTypeInst, compareEntrySource);
  5833. bool isWorse = TypeIsSubTypeOf(compareEntrySource, compareCheckTypeInst);
  5834. if ((!isBetter) && (!isWorse))
  5835. {
  5836. // Unboxed comparison to Object fix
  5837. if (compareCheckTypeInst == mContext->mBfObjectType)
  5838. isWorse = true;
  5839. else if (compareEntrySource == mContext->mBfObjectType)
  5840. isBetter = true;
  5841. }
  5842. if (forceInterfaceSet)
  5843. {
  5844. isBetter = true;
  5845. isWorse = false;
  5846. }
  5847. if (isBetter == isWorse)
  5848. CompareDeclTypes(checkTypeInst, interfaceEntry.mDeclaringType, prevEntry->mDeclaringType, isBetter, isWorse);
  5849. if (isBetter == isWorse)
  5850. {
  5851. if (matchEntry->mAmbiguousEntries.empty())
  5852. matchEntry->mAmbiguousEntries.push_back(prevEntry);
  5853. matchEntry->mAmbiguousEntries.push_back(&interfaceEntry);
  5854. continue;
  5855. }
  5856. else if (isBetter)
  5857. {
  5858. matchEntry->mEntry = &interfaceEntry;
  5859. matchEntry->mEntrySource = checkTypeInst;
  5860. matchEntry->mAmbiguousEntries.Clear();
  5861. }
  5862. else
  5863. continue;
  5864. }
  5865. else
  5866. {
  5867. _InterfaceMatchEntry matchEntry;
  5868. matchEntry.mEntry = &interfaceEntry;
  5869. matchEntry.mEntrySource = checkTypeInst;
  5870. interfaceMap[interfaceEntry.mInterfaceType] = matchEntry;
  5871. }
  5872. }
  5873. checkTypeInst = checkTypeInst->GetImplBaseType();
  5874. }
  5875. for (auto interfacePair : interfaceMap)
  5876. {
  5877. auto& interfaceMatchEntry = interfacePair.mValue;
  5878. if (!interfaceMatchEntry.mAmbiguousEntries.empty())
  5879. {
  5880. 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());
  5881. if (error != NULL)
  5882. {
  5883. for (auto ambiguiousEntry : interfaceMatchEntry.mAmbiguousEntries)
  5884. mCompiler->mPassInstance->MoreInfo("See other declaration", ambiguiousEntry->mDeclaringType->GetRefNode());
  5885. }
  5886. }
  5887. }
  5888. if ((!mIsComptimeModule) && (!typeInstance->IsInterface()) && (typeInstance->mVirtualMethodTableSize > 0) && (needsVData))
  5889. {
  5890. int startTabIdx = (int)vData.size();
  5891. SizedArray<BfTypeInstance*, 8> origVirtTypeStack;
  5892. BfTypeInstance* checkTypeInst = typeInstance;
  5893. while (checkTypeInst != NULL)
  5894. {
  5895. origVirtTypeStack.push_back(checkTypeInst);
  5896. checkTypeInst = checkTypeInst->GetImplBaseType();
  5897. }
  5898. Array<BfVirtualMethodEntry> origVTable;
  5899. int origVirtIdx = 0;
  5900. if (typeInstance->mTypeDef->mIsCombinedPartial)
  5901. {
  5902. HashSet<String> reslotNames;
  5903. for (int virtIdx = 0; virtIdx < (int)typeInstance->mVirtualMethodTable.size(); virtIdx++)
  5904. {
  5905. auto& entry = typeInstance->mVirtualMethodTable[virtIdx];
  5906. if (entry.mDeclaringMethod.mMethodNum == -1)
  5907. continue;
  5908. BfMethodInstance* methodInstance = (BfMethodInstance*)entry.mImplementingMethod;
  5909. if ((methodInstance == NULL) ||
  5910. ((!mIsComptimeModule) && (!typeInstance->IsTypeMemberAccessible(methodInstance->mMethodDef->mDeclaringType, mProject))))
  5911. {
  5912. if (origVTable.empty())
  5913. origVTable = typeInstance->mVirtualMethodTable;
  5914. BfMethodInstance* declMethodInstance = entry.mDeclaringMethod;
  5915. if (declMethodInstance != NULL)
  5916. {
  5917. if ((mIsComptimeModule) || (typeInstance->IsTypeMemberAccessible(declMethodInstance->mMethodDef->mDeclaringType, mProject)))
  5918. {
  5919. // Prepare to reslot...
  5920. entry.mImplementingMethod = entry.mDeclaringMethod;
  5921. reslotNames.Add(declMethodInstance->mMethodDef->mName);
  5922. }
  5923. else
  5924. {
  5925. // Decl isn't accessible, null out entry
  5926. entry.mImplementingMethod = BfMethodRef();
  5927. }
  5928. }
  5929. }
  5930. }
  5931. if (!reslotNames.IsEmpty())
  5932. {
  5933. BfAmbiguityContext ambiguityContext;
  5934. ambiguityContext.mTypeInstance = typeInstance;
  5935. ambiguityContext.mModule = this;
  5936. ambiguityContext.mIsProjectSpecific = true;
  5937. ambiguityContext.mIsReslotting = true;
  5938. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  5939. for (auto& methodGroup : typeInstance->mMethodInstanceGroups)
  5940. {
  5941. auto methodInstance = methodGroup.mDefault;
  5942. if ((methodInstance == NULL) || (!methodInstance->mMethodDef->mIsOverride))
  5943. continue;
  5944. if (!reslotNames.Contains(methodInstance->mMethodDef->mName))
  5945. continue;
  5946. if ((!mIsComptimeModule) && (!typeInstance->IsTypeMemberAccessible(methodInstance->mMethodDef->mDeclaringType, mProject)))
  5947. continue;
  5948. if ((methodInstance->mChainType != BfMethodChainType_None) && (methodInstance->mChainType != BfMethodChainType_ChainHead))
  5949. continue;
  5950. SlotVirtualMethod(methodInstance, &ambiguityContext);
  5951. }
  5952. ambiguityContext.Finish();
  5953. }
  5954. }
  5955. bool isInExts = false;
  5956. for (int virtIdx = 0; virtIdx < (int)typeInstance->mVirtualMethodTable.size(); virtIdx++)
  5957. {
  5958. BfIRValue vValue = voidPtrNull;
  5959. auto& entry = typeInstance->mVirtualMethodTable[virtIdx];
  5960. BfModuleMethodInstance moduleMethodInst;
  5961. if (entry.mDeclaringMethod.mMethodNum == -1)
  5962. {
  5963. // mMethodNum of -1 indicates a vExt slot rather than an actual method reference
  5964. isInExts = true;
  5965. BfIRValue vExt = CreateClassVDataExtGlobal(entry.mDeclaringMethod.mTypeInstance, typeInstance, virtIdx);
  5966. if (vExt)
  5967. vValue = mBfIRBuilder->CreateBitCast(vExt, voidPtrIRType);
  5968. }
  5969. else
  5970. {
  5971. BfMethodInstance* declaringMethodInstance = (BfMethodInstance*)entry.mDeclaringMethod;
  5972. if ((declaringMethodInstance != NULL) && (declaringMethodInstance->mMethodInstanceGroup->IsImplemented()) && (declaringMethodInstance->mIsReified))
  5973. {
  5974. if (entry.mImplementingMethod.mMethodNum >= 0)
  5975. {
  5976. BF_ASSERT(entry.mImplementingMethod.mTypeInstance->mMethodInstanceGroups[entry.mImplementingMethod.mMethodNum].IsImplemented());
  5977. BF_ASSERT(entry.mImplementingMethod.mTypeInstance->mMethodInstanceGroups[entry.mImplementingMethod.mMethodNum].mDefault->mIsReified);
  5978. }
  5979. BfMethodInstance* methodInstance = (BfMethodInstance*)entry.mImplementingMethod;
  5980. if ((methodInstance != NULL) && (!methodInstance->mMethodDef->mIsAbstract))
  5981. {
  5982. BF_ASSERT((mIsComptimeModule) || typeInstance->IsTypeMemberAccessible(methodInstance->mMethodDef->mDeclaringType, mProject));
  5983. moduleMethodInst = GetMethodInstanceAtIdx(methodInstance->mMethodInstanceGroup->mOwner, methodInstance->mMethodInstanceGroup->mMethodIdx, NULL, BfGetMethodInstanceFlag_NoInline);
  5984. auto funcPtr = mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, voidPtrIRType);
  5985. vValue = funcPtr;
  5986. }
  5987. }
  5988. }
  5989. while (origVirtTypeStack.size() != 0)
  5990. {
  5991. BfTypeInstance* useTypeInst = origVirtTypeStack[origVirtTypeStack.size() - 1];
  5992. if (virtIdx >= useTypeInst->mVirtualMethodTableSize)
  5993. {
  5994. // Moved past current base vtable size
  5995. origVirtTypeStack.pop_back();
  5996. continue;
  5997. }
  5998. if (origVirtIdx < useTypeInst->GetOrigVTableSize())
  5999. {
  6000. // We are within the original vtable size
  6001. int idx = startTabIdx + origVirtIdx;
  6002. origVirtIdx++;
  6003. vData.push_back(vValue);
  6004. }
  6005. else
  6006. {
  6007. // This is a new entry, it only gets added to the ext
  6008. BF_ASSERT(isInExts);
  6009. }
  6010. break;
  6011. }
  6012. }
  6013. if (!origVTable.empty())
  6014. typeInstance->mVirtualMethodTable = origVTable;
  6015. }
  6016. int ifaceMethodExtStart = (int)typeInstance->GetIFaceVMethodSize();
  6017. if (typeInstance->mHotTypeData != NULL)
  6018. {
  6019. if (typeInstance->mHotTypeData->mOrigInterfaceMethodsLength != -1)
  6020. ifaceMethodExtStart = typeInstance->mHotTypeData->mOrigInterfaceMethodsLength;
  6021. }
  6022. SizedArray<BfIRValue, 32> ifaceMethodExtData;
  6023. int iFaceMethodStartIdx = (int)vData.size();
  6024. vData.resize(iFaceMethodStartIdx + ifaceMethodExtStart);
  6025. for (int i = iFaceMethodStartIdx; i < iFaceMethodStartIdx + ifaceMethodExtStart; i++)
  6026. vData[i] = voidPtrNull;
  6027. if (expectNumElements != 0)
  6028. BF_ASSERT(expectNumElements == vData.size());
  6029. //BF_ASSERT(vData.size() == expectNumElements);
  6030. // for (int i = 0; i < (int)typeInstance->mInterfaceMethodTable.size() - ifaceMethodExtStart; i++)
  6031. // ifaceMethodExtData.Add(voidPtrNull);
  6032. int ifaceEntryIdx = iFaceMethodStartIdx;
  6033. for (auto& interfacePair : interfaceMap)
  6034. {
  6035. auto interfaceEntry = interfacePair.mValue.mEntry;
  6036. if (typeInstance->mDefineState < BfTypeDefineState_DefinedAndMethodsSlotted)
  6037. {
  6038. BF_ASSERT(mIsComptimeModule);
  6039. break;
  6040. }
  6041. bool makeEmpty = false;
  6042. if ((!mIsComptimeModule) && (!typeInstance->IsTypeMemberAccessible(interfaceEntry->mDeclaringType, mProject)))
  6043. makeEmpty = true;
  6044. int endVirtualIdx = interfaceEntry->mStartVirtualIdx + interfaceEntry->mInterfaceType->mVirtualMethodTableSize;
  6045. bool useExt = endVirtualIdx > ifaceMethodExtStart;
  6046. for (int methodIdx = 0; methodIdx < (int)interfaceEntry->mInterfaceType->mMethodInstanceGroups.size(); methodIdx++)
  6047. {
  6048. BfIRValue pushValue;
  6049. BfMethodInstance* ifaceMethodInstance = interfaceEntry->mInterfaceType->mMethodInstanceGroups[methodIdx].mDefault;
  6050. if ((ifaceMethodInstance == NULL) || (ifaceMethodInstance->mVirtualTableIdx == -1))
  6051. continue;
  6052. if ((!ifaceMethodInstance->mIsReified) || (!ifaceMethodInstance->mMethodInstanceGroup->IsImplemented()))
  6053. continue;
  6054. if (makeEmpty)
  6055. {
  6056. pushValue = voidPtrNull;
  6057. }
  6058. else
  6059. {
  6060. auto& methodRef = typeInstance->mInterfaceMethodTable[interfaceEntry->mStartInterfaceTableIdx + methodIdx].mMethodRef;
  6061. auto methodInstance = (BfMethodInstance*)methodRef;
  6062. if ((methodInstance != NULL) && (!methodInstance->mMethodDef->mIsAbstract))
  6063. {
  6064. BF_ASSERT(methodInstance->mIsReified);
  6065. // This doesn't work because we may have FOREIGN methods from implicit interface methods
  6066. //auto moduleMethodInst = GetMethodInstanceAtIdx(methodRef.mTypeInstance, methodRef.mMethodNum);
  6067. auto moduleMethodInst = ReferenceExternalMethodInstance(methodInstance, BfGetMethodInstanceFlag_NoInline);
  6068. auto funcPtr = mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, voidPtrIRType);
  6069. pushValue = funcPtr;
  6070. }
  6071. else
  6072. {
  6073. pushValue = voidPtrNull;
  6074. }
  6075. }
  6076. int idx = interfaceEntry->mStartVirtualIdx + ifaceMethodInstance->mVirtualTableIdx;
  6077. if (idx < ifaceMethodExtStart)
  6078. {
  6079. BF_ASSERT(iFaceMethodStartIdx + idx < (int)vData.size());
  6080. vData[iFaceMethodStartIdx + idx] = pushValue;
  6081. }
  6082. else
  6083. {
  6084. BF_ASSERT(useExt);
  6085. int extIdx = idx - ifaceMethodExtStart;
  6086. while (extIdx >= ifaceMethodExtData.size())
  6087. ifaceMethodExtData.Add(voidPtrNull);
  6088. ifaceMethodExtData[extIdx] = pushValue;
  6089. }
  6090. }
  6091. }
  6092. if (typeInstance->IsBoxed())
  6093. {
  6094. BfBoxedType* boxedType = (BfBoxedType*)typeInstance;
  6095. if (boxedType->IsBoxedStructPtr())
  6096. {
  6097. // Force override of GetHashCode so we use the pointer address as the hash code
  6098. checkTypeInst = CreateBoxedType(ResolveTypeDef(mCompiler->mPointerTypeDef));
  6099. // Force override of GetHashCode so we use the pointer address as the hash code
  6100. for (auto& checkIFace : checkTypeInst->mInterfaces)
  6101. {
  6102. if (checkIFace.mStartVirtualIdx < 0)
  6103. continue;
  6104. for (int methodIdx = 0; methodIdx < (int)checkIFace.mInterfaceType->mMethodInstanceGroups.size(); methodIdx++)
  6105. {
  6106. BfIRValue pushValue;
  6107. BfMethodInstance* ifaceMethodInstance = checkIFace.mInterfaceType->mMethodInstanceGroups[methodIdx].mDefault;
  6108. if ((ifaceMethodInstance == NULL) || (ifaceMethodInstance->mVirtualTableIdx == -1))
  6109. continue;
  6110. if ((!ifaceMethodInstance->mIsReified) || (!ifaceMethodInstance->mMethodInstanceGroup->IsImplemented()))
  6111. continue;
  6112. auto& methodRef = checkTypeInst->mInterfaceMethodTable[checkIFace.mStartInterfaceTableIdx + methodIdx].mMethodRef;
  6113. auto methodInstance = (BfMethodInstance*)methodRef;
  6114. BF_ASSERT(methodInstance->mIsReified);
  6115. // This doesn't work because we may have FOREIGN methods from implicit interface methods
  6116. //auto moduleMethodInst = GetMethodInstanceAtIdx(methodRef.mTypeInstance, methodRef.mMethodNum);
  6117. auto moduleMethodInst = ReferenceExternalMethodInstance(methodInstance, BfGetMethodInstanceFlag_NoInline);
  6118. auto funcPtr = mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, voidPtrIRType);
  6119. int idx = checkIFace.mStartVirtualIdx + ifaceMethodInstance->mVirtualTableIdx;
  6120. vData[iFaceMethodStartIdx + idx] = funcPtr;
  6121. }
  6122. }
  6123. }
  6124. }
  6125. if ((needsVData) && (!typeInstance->mTypeDef->mIsStatic) && (!mIsComptimeModule))
  6126. {
  6127. BfIRValue ifaceMethodExtVar;
  6128. if ((!ifaceMethodExtData.IsEmpty()) && (!mIsComptimeModule))
  6129. {
  6130. StringT<512> classVDataName;
  6131. BfMangler::MangleStaticFieldName(classVDataName, mCompiler->GetMangleKind(), typeInstance, "bf_hs_replace_IFaceExt");
  6132. auto arrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr), (int)ifaceMethodExtData.size());
  6133. ifaceMethodExtVar = mBfIRBuilder->CreateGlobalVariable(arrayType, true,
  6134. BfIRLinkageType_External, BfIRValue(), classVDataName);
  6135. BfIRType extVTableType = mBfIRBuilder->GetSizedArrayType(voidPtrIRType, (int)ifaceMethodExtData.size());
  6136. BfIRValue extVTableConst = mBfIRBuilder->CreateConstAgg_Value(extVTableType, ifaceMethodExtData);
  6137. mBfIRBuilder->GlobalVar_SetInitializer(ifaceMethodExtVar, extVTableConst);
  6138. }
  6139. for (auto& ifaceInstPair : interfaceMap)
  6140. {
  6141. auto interfaceEntry = ifaceInstPair.mValue.mEntry;
  6142. int slotNum = interfaceEntry->mInterfaceType->mSlotNum;
  6143. if (slotNum >= 0)
  6144. {
  6145. BfIRValue vtablePtr;
  6146. int idx = interfaceEntry->mStartVirtualIdx;
  6147. int endVirtualIdx = interfaceEntry->mStartVirtualIdx + interfaceEntry->mInterfaceType->mVirtualMethodTableSize;
  6148. if ((endVirtualIdx > ifaceMethodExtStart) && (ifaceMethodExtVar))
  6149. vtablePtr = mBfIRBuilder->CreateInBoundsGEP(ifaceMethodExtVar, 0, interfaceEntry->mStartVirtualIdx - ifaceMethodExtStart);
  6150. else
  6151. vtablePtr = mBfIRBuilder->CreateInBoundsGEP(classVDataVar, 0, iFaceMethodStartIdx + interfaceEntry->mStartVirtualIdx);
  6152. int slotVirtIdx = slotNum + vDataOfs;
  6153. if (vData[slotVirtIdx] == voidPtrNull)
  6154. {
  6155. vData[slotVirtIdx] = mBfIRBuilder->CreateBitCast(vtablePtr, voidPtrIRType);
  6156. }
  6157. else
  6158. {
  6159. if (mCompiler->IsHotCompile())
  6160. Fail("Interface slot collision error. Restart program or undo interface changes.", typeDef->GetRefNode());
  6161. else
  6162. Fail("Interface slot collision error", typeDef->GetRefNode());
  6163. }
  6164. }
  6165. }
  6166. }
  6167. }
  6168. BfIRValue typeNameConst;
  6169. BfIRValue namespaceConst;
  6170. if (needsTypeNames)
  6171. {
  6172. typeNameConst = GetStringObjectValue(typeDef->mName->mString, !mIsComptimeModule);
  6173. namespaceConst = GetStringObjectValue(typeDef->mNamespace.ToString(), !mIsComptimeModule);
  6174. }
  6175. else
  6176. {
  6177. auto stringType = ResolveTypeDef(mCompiler->mStringTypeDef);
  6178. typeNameConst = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(stringType));
  6179. namespaceConst = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(stringType));
  6180. }
  6181. int baseTypeId = 0;
  6182. if (typeInstance->mBaseType != NULL)
  6183. {
  6184. baseTypeId = typeInstance->mBaseType->mTypeId;
  6185. }
  6186. BfTypeOptions* typeOptions = NULL;
  6187. if (typeInstance->mTypeOptionsIdx >= 0)
  6188. typeOptions = mSystem->GetTypeOptions(typeInstance->mTypeOptionsIdx);
  6189. SizedArray<BfIRValue, 16> customAttrs;
  6190. BfTypeInstance* attributeType = mContext->mUnreifiedModule->ResolveTypeDef(mCompiler->mAttributeTypeDef)->ToTypeInstance();
  6191. BfIRValue castedClassVData;
  6192. if (classVDataVar)
  6193. castedClassVData = mBfIRBuilder->CreateBitCast(classVDataVar, mBfIRBuilder->MapType(mContext->mBfClassVDataPtrType));
  6194. else
  6195. castedClassVData = GetDefaultValue(mContext->mBfClassVDataPtrType);
  6196. bool freflectIncludeTypeData = false;
  6197. bool reflectIncludeAllFields = false;
  6198. bool reflectIncludeAllMethods = false;
  6199. if (TypeIsSubTypeOf(typeInstance, attributeType))
  6200. {
  6201. reflectIncludeAllFields = true;
  6202. reflectIncludeAllMethods = true;
  6203. }
  6204. if (typeInstance->IsTuple())
  6205. {
  6206. // Required to generate tuple name at runtime
  6207. reflectIncludeAllFields = true;
  6208. }
  6209. BfReflectKind reflectKind = BfReflectKind_Type;
  6210. auto _GetReflectUserFromDirective = [&](BfAttributeDirective* attributesDirective, BfAttributeTargets attrTarget)
  6211. {
  6212. BfReflectKind reflectKind = BfReflectKind_None;
  6213. auto customAttrs = GetCustomAttributes(attributesDirective, attrTarget);
  6214. if (customAttrs != NULL)
  6215. {
  6216. for (auto& attr : customAttrs->mAttributes)
  6217. {
  6218. reflectKind = (BfReflectKind)(reflectKind | GetUserReflectKind(attr.mType));
  6219. }
  6220. delete customAttrs;
  6221. }
  6222. return reflectKind;
  6223. };
  6224. reflectKind = GetReflectKind(reflectKind, typeInstance);
  6225. // Fields
  6226. BfType* reflectFieldDataType = ResolveTypeDef(mCompiler->mReflectFieldDataDef);
  6227. BfIRValue emptyValueType = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectFieldDataType->ToTypeInstance()->mBaseType), SizedArray<BfIRValue, 1>());
  6228. auto _HandleCustomAttrs = [&](BfCustomAttributes* customAttributes)
  6229. {
  6230. if (customAttributes == NULL)
  6231. return -1;
  6232. Array<BfCustomAttribute*> reflectAttributes;
  6233. for (auto& attr : customAttributes->mAttributes)
  6234. {
  6235. bool wantAttribute = false;
  6236. if (attr.mType->mCustomAttributes != NULL)
  6237. {
  6238. auto usageAttribute = attr.mType->mCustomAttributes->Get(mCompiler->mAttributeUsageAttributeTypeDef);
  6239. if (usageAttribute != NULL)
  6240. {
  6241. // Check for Flags arg
  6242. if (usageAttribute->mCtorArgs.size() < 2)
  6243. continue;
  6244. auto constant = attr.mType->mConstHolder->GetConstant(usageAttribute->mCtorArgs[1]);
  6245. if (constant == NULL)
  6246. continue;
  6247. if (constant->mTypeCode == BfTypeCode_Boolean)
  6248. continue;
  6249. if ((constant->mInt8 & BfCustomAttributeFlags_ReflectAttribute) != 0)
  6250. wantAttribute = true;
  6251. }
  6252. }
  6253. if ((wantAttribute) && (attr.mType->mIsReified))
  6254. {
  6255. reflectAttributes.Add(&attr);
  6256. }
  6257. }
  6258. if (reflectAttributes.size() == 0)
  6259. return -1;
  6260. #define PUSH_INT8(val) data.push_back((uint8)val)
  6261. #define PUSH_INT16(val) { data.push_back(val & 0xFF); data.push_back((val >> 8) & 0xFF); }
  6262. #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); }
  6263. SizedArray<uint8, 16> data;
  6264. int customAttrIdx = (int)customAttrs.size();
  6265. data.push_back((uint8)reflectAttributes.size());
  6266. for (auto attr : reflectAttributes)
  6267. {
  6268. // Size prefix
  6269. int sizeIdx = (int)data.size();
  6270. PUSH_INT16(0); // mSize
  6271. PUSH_INT32(attr->mType->mTypeId); // mType
  6272. int ctorIdx = -1;
  6273. int ctorCount = 0;
  6274. attr->mType->mTypeDef->PopulateMemberSets();
  6275. BfMemberSetEntry* entry;
  6276. if (attr->mType->mTypeDef->mMethodSet.TryGetWith(String("__BfCtor"), &entry))
  6277. {
  6278. BfMethodDef* nextMethodDef = (BfMethodDef*)entry->mMemberDef;
  6279. while (nextMethodDef != NULL)
  6280. {
  6281. if (nextMethodDef == attr->mCtor)
  6282. ctorIdx = ctorCount;
  6283. nextMethodDef = nextMethodDef->mNextWithSameName;
  6284. ctorCount++;
  6285. }
  6286. }
  6287. BF_ASSERT(ctorIdx != -1);
  6288. if (ctorIdx != -1)
  6289. ctorIdx = (ctorCount - 1) - ctorIdx;
  6290. PUSH_INT16(ctorIdx);
  6291. auto ctorMethodInstance = GetRawMethodInstanceAtIdx(attr->mType, attr->mCtor->mIdx);
  6292. int argIdx = 0;
  6293. for (auto arg : attr->mCtorArgs)
  6294. {
  6295. auto argType = ctorMethodInstance->GetParamType(argIdx);
  6296. EncodeAttributeData(typeInstance, argType, arg, data, ctx.mUsedStringIdMap);
  6297. argIdx++;
  6298. }
  6299. int size = (int)data.size() - sizeIdx;
  6300. *((uint16*)&data[sizeIdx]) = size;
  6301. }
  6302. #undef PUSH_INT8
  6303. #undef PUSH_INT16
  6304. #undef PUSH_INT32
  6305. SizedArray<BfIRValue, 16> dataValues;
  6306. for (uint8 val : data)
  6307. dataValues.push_back(GetConstValue8(val));
  6308. auto dataArrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->MapType(byteType), (int)data.size());
  6309. auto customAttrConst = mBfIRBuilder->CreateConstAgg_Value(dataArrayType, dataValues);
  6310. BfIRValue customAttrArray = mBfIRBuilder->CreateGlobalVariable(dataArrayType, true, BfIRLinkageType_Internal,
  6311. customAttrConst, typeDataName + StrFormat(".customAttr%d", customAttrIdx));
  6312. BfIRValue customAttrArrayPtr = mBfIRBuilder->CreateBitCast(customAttrArray, voidPtrIRType);
  6313. customAttrs.push_back(customAttrArrayPtr);
  6314. return customAttrIdx;
  6315. };
  6316. int typeCustomAttrIdx = _HandleCustomAttrs(typeInstance->mCustomAttributes);
  6317. SizedArray<int, 16> reflectFieldIndices;
  6318. for (int pass = 0; pass < 2; pass++)
  6319. {
  6320. bool skippedField = false;
  6321. reflectFieldIndices.clear();
  6322. for (int fieldIdx = 0; fieldIdx < (int)typeInstance->mFieldInstances.size(); fieldIdx++)
  6323. {
  6324. BfFieldInstance* fieldInstance = &typeInstance->mFieldInstances[fieldIdx];
  6325. BfFieldDef* fieldDef = fieldInstance->GetFieldDef();
  6326. if (fieldDef == NULL)
  6327. continue;
  6328. auto fieldReflectKind = (BfReflectKind)(reflectKind & ~BfReflectKind_User);
  6329. bool includeField = reflectIncludeAllFields;
  6330. if (fieldInstance->mCustomAttributes != NULL)
  6331. {
  6332. for (auto& customAttr : fieldInstance->mCustomAttributes->mAttributes)
  6333. {
  6334. if (customAttr.mType->mTypeDef->mName->ToString() == "ReflectAttribute")
  6335. {
  6336. includeField = true;
  6337. }
  6338. else
  6339. {
  6340. auto userReflectKind = GetUserReflectKind(customAttr.mType);
  6341. fieldReflectKind = (BfReflectKind)(fieldReflectKind | userReflectKind);
  6342. }
  6343. }
  6344. }
  6345. if ((fieldReflectKind & BfReflectKind_User) != 0)
  6346. includeField = true;
  6347. if ((!fieldDef->mIsStatic) && ((fieldReflectKind & BfReflectKind_NonStaticFields) != 0))
  6348. includeField = true;
  6349. if ((fieldDef->mIsStatic) && ((fieldReflectKind & BfReflectKind_StaticFields) != 0))
  6350. includeField = true;
  6351. if ((!fieldDef->mIsStatic) && (typeOptions != NULL))
  6352. includeField = typeOptions->Apply(includeField, BfOptionFlags_ReflectNonStaticFields);
  6353. if ((fieldDef->mIsStatic) && (typeOptions != NULL))
  6354. includeField = typeOptions->Apply(includeField, BfOptionFlags_ReflectStaticFields);
  6355. includeField |= forceReflectFields;
  6356. if (!includeField)
  6357. {
  6358. skippedField = true;
  6359. continue;
  6360. }
  6361. reflectFieldIndices.Add(fieldIdx);
  6362. }
  6363. // For a splattable type, we need to either include all fields or zero fields. This is to allow us to correctly splat
  6364. // params for reflected method calls even if we don't have reflection field info for the splatted type. This is
  6365. // possible because we write out a SplatData structure containing just TypeIds in that case
  6366. if (pass == 0)
  6367. {
  6368. if (!typeInstance->IsSplattable())
  6369. break;
  6370. if (!skippedField)
  6371. break;
  6372. if (reflectFieldIndices.size() == 0)
  6373. break;
  6374. }
  6375. }
  6376. SizedArray<BfIRValue, 16> fieldTypes;
  6377. bool is32Bit = mCompiler->mSystem->mPtrSize == 4;
  6378. if ((typeInstance->IsPayloadEnum()) && (!typeInstance->IsBoxed()))
  6379. {
  6380. BfType* payloadType = typeInstance->GetUnionInnerType();
  6381. if (!payloadType->IsValuelessType())
  6382. {
  6383. BfIRValue payloadNameConst = GetStringObjectValue("$payload", !mIsComptimeModule);
  6384. SizedArray<BfIRValue, 8> payloadFieldVals;
  6385. if (is32Bit)
  6386. {
  6387. payloadFieldVals =
  6388. {
  6389. emptyValueType,
  6390. payloadNameConst, // mName
  6391. GetConstValue(payloadType->mTypeId, typeIdType), // mFieldTypeId
  6392. GetConstValue(0, intPtrType), // mData
  6393. GetConstValue(0, intPtrType), // mDataHi
  6394. GetConstValue(BfFieldFlags_SpecialName | BfFieldFlags_EnumPayload, shortType), // mFlags
  6395. GetConstValue(-1, intType), // mCustomAttributesIdx
  6396. };
  6397. }
  6398. else
  6399. {
  6400. payloadFieldVals =
  6401. {
  6402. emptyValueType,
  6403. payloadNameConst, // mName
  6404. GetConstValue(payloadType->mTypeId, typeIdType), // mFieldTypeId
  6405. GetConstValue(0, intPtrType), // mData
  6406. GetConstValue(BfFieldFlags_SpecialName | BfFieldFlags_EnumPayload, shortType), // mFlags
  6407. GetConstValue(-1, intType), // mCustomAttributesIdx
  6408. };
  6409. }
  6410. FixConstValueParams(reflectFieldDataType->ToTypeInstance(), payloadFieldVals);
  6411. auto payloadFieldData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectFieldDataType->ToTypeInstance(), BfIRPopulateType_Full), payloadFieldVals);
  6412. fieldTypes.push_back(payloadFieldData);
  6413. }
  6414. BfType* dscrType = typeInstance->GetDiscriminatorType();
  6415. BfIRValue dscrNameConst = GetStringObjectValue("$discriminator", !mIsComptimeModule);
  6416. SizedArray<BfIRValue, 8> dscrFieldVals;
  6417. if (is32Bit)
  6418. {
  6419. dscrFieldVals =
  6420. {
  6421. emptyValueType,
  6422. dscrNameConst, // mName
  6423. GetConstValue(dscrType->mTypeId, typeIdType), // mFieldTypeId
  6424. GetConstValue(BF_ALIGN(payloadType->mSize, dscrType->mAlign), intPtrType), // mData
  6425. GetConstValue(0, intPtrType), // mDataHi
  6426. GetConstValue(BfFieldFlags_SpecialName | BfFieldFlags_EnumDiscriminator, shortType), // mFlags
  6427. GetConstValue(-1, intType), // mCustomAttributesIdx
  6428. };
  6429. }
  6430. else
  6431. {
  6432. dscrFieldVals =
  6433. {
  6434. emptyValueType,
  6435. dscrNameConst, // mName
  6436. GetConstValue(dscrType->mTypeId, typeIdType), // mFieldTypeId
  6437. GetConstValue(BF_ALIGN(payloadType->mSize, dscrType->mAlign), intPtrType), // mData
  6438. GetConstValue(BfFieldFlags_SpecialName | BfFieldFlags_EnumDiscriminator, shortType), // mFlags
  6439. GetConstValue(-1, intType), // mCustomAttributesIdx
  6440. };
  6441. }
  6442. auto dscrFieldData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectFieldDataType->ToTypeInstance(), BfIRPopulateType_Full), dscrFieldVals);
  6443. fieldTypes.push_back(dscrFieldData);
  6444. }
  6445. for (auto fieldIdx : reflectFieldIndices)
  6446. {
  6447. if (!needsTypeData)
  6448. break;
  6449. BfFieldInstance* fieldInstance = &typeInstance->mFieldInstances[fieldIdx];
  6450. fieldTypes.push_back(CreateFieldData(fieldInstance, _HandleCustomAttrs(fieldInstance->mCustomAttributes)));
  6451. }
  6452. auto reflectFieldDataIRType = mBfIRBuilder->MapType(reflectFieldDataType);
  6453. BfIRValue fieldDataPtr;
  6454. BfIRType fieldDataPtrType = mBfIRBuilder->GetPointerTo(reflectFieldDataIRType);
  6455. if (fieldTypes.size() == 0)
  6456. {
  6457. if ((type->IsSplattable()) && (type->IsStruct()) && (!type->IsValuelessType()) && (!typeInstance->mIsCRepr))
  6458. {
  6459. BfTypeInstance* reflectFieldSplatDataType = ResolveTypeDef(mCompiler->mReflectFieldSplatDataDef)->ToTypeInstance();
  6460. SizedArray<BfIRValue, 3> splatTypes;
  6461. SizedArray<BfIRValue, 3> splatOffsets;
  6462. std::function<void(BfType*, int)> _CheckSplat = [&](BfType* checkType, int offset)
  6463. {
  6464. auto checkTypeInstance = checkType->ToTypeInstance();
  6465. if ((checkTypeInstance != NULL) && (checkTypeInstance->IsValueType()) && (checkTypeInstance->IsDataIncomplete()))
  6466. PopulateType(checkTypeInstance);
  6467. if (checkType->IsStruct())
  6468. {
  6469. int dataEnd = offset;
  6470. if (checkTypeInstance->mBaseType != NULL)
  6471. _CheckSplat(checkTypeInstance->mBaseType, offset);
  6472. if (checkTypeInstance->mIsUnion)
  6473. {
  6474. BfType* unionInnerType = checkTypeInstance->GetUnionInnerType();
  6475. _CheckSplat(unionInnerType, offset);
  6476. }
  6477. else
  6478. {
  6479. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  6480. {
  6481. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  6482. if (fieldInstance->mDataIdx >= 0)
  6483. {
  6484. _CheckSplat(fieldInstance->GetResolvedType(), offset + fieldInstance->mDataOffset);
  6485. dataEnd = offset + fieldInstance->mDataOffset + fieldInstance->mResolvedType->mSize;
  6486. }
  6487. }
  6488. }
  6489. if (checkTypeInstance->IsEnum())
  6490. {
  6491. // Add discriminator
  6492. auto dscrType = checkTypeInstance->GetDiscriminatorType();
  6493. if (checkTypeInstance->mPacking > 0)
  6494. dataEnd = BF_ALIGN(dataEnd, dscrType->mAlign);
  6495. _CheckSplat(dscrType, dataEnd);
  6496. }
  6497. }
  6498. else if (checkType->IsMethodRef())
  6499. {
  6500. // auto methodRefType = (BfMethodRefType*)checkType;
  6501. // for (int dataIdx = 0; dataIdx < methodRefType->GetCaptureDataCount(); dataIdx++)
  6502. // {
  6503. // if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  6504. // _CheckSplat(methodRefType->GetCaptureType(dataIdx), offsetof);
  6505. // else
  6506. // dataLambda(methodRefType->GetCaptureType(dataIdx));
  6507. // }
  6508. }
  6509. else if (!checkType->IsValuelessType())
  6510. {
  6511. splatTypes.Add(GetConstValue(checkType->mTypeId, typeIdType));
  6512. splatOffsets.Add(GetConstValue(offset, intType));
  6513. }
  6514. };
  6515. _CheckSplat(type, 0);
  6516. while (splatTypes.size() < 3)
  6517. {
  6518. splatTypes.Add(GetConstValue(0, typeIdType));
  6519. splatOffsets.Add(GetConstValue(0, intType));
  6520. }
  6521. BfIRValue splatTypesConst = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapType(reflectFieldSplatDataType->mFieldInstances[0].mResolvedType), splatTypes);
  6522. BfIRValue splatOffsetsConst = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapType(reflectFieldSplatDataType->mFieldInstances[1].mResolvedType), splatOffsets);
  6523. SizedArray<BfIRValue, 8> splatVals =
  6524. {
  6525. emptyValueType,
  6526. splatTypesConst,
  6527. splatOffsetsConst
  6528. };
  6529. auto fieldSplatData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectFieldSplatDataType->ToTypeInstance(), BfIRPopulateType_Full), splatVals);
  6530. BfIRValue fieldDataArray = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapType(reflectFieldSplatDataType), true, BfIRLinkageType_Internal,
  6531. fieldSplatData, typeDataName + ".splats");
  6532. fieldDataPtr = mBfIRBuilder->CreateBitCast(fieldDataArray, fieldDataPtrType);
  6533. }
  6534. else
  6535. fieldDataPtr = mBfIRBuilder->CreateConstNull(fieldDataPtrType);
  6536. }
  6537. else
  6538. {
  6539. BfIRType fieldDataConstType = mBfIRBuilder->GetSizedArrayType(reflectFieldDataIRType, (int)fieldTypes.size());
  6540. BfIRValue fieldDataConst = mBfIRBuilder->CreateConstAgg_Value(fieldDataConstType, fieldTypes);
  6541. BfIRValue fieldDataArray = mBfIRBuilder->CreateGlobalVariable(fieldDataConstType, true, BfIRLinkageType_Internal,
  6542. fieldDataConst, "fields." + typeDataName);
  6543. fieldDataPtr = mBfIRBuilder->CreateBitCast(fieldDataArray, fieldDataPtrType);
  6544. }
  6545. /// Methods
  6546. BfType* reflectMethodDataType = ResolveTypeDef(mCompiler->mReflectMethodDataDef);
  6547. BfType* reflectParamDataType = ResolveTypeDef(mCompiler->mReflectParamDataDef);
  6548. BfType* reflectParamDataPtrType = CreatePointerType(reflectParamDataType);
  6549. struct _SortedMethodInfo
  6550. {
  6551. BfMethodDef* mMethodDef;
  6552. BfMethodCustomAttributes* mMethodCustomAttributes;
  6553. };
  6554. Array<_SortedMethodInfo> sortedMethodList;
  6555. SizedArray<BfIRValue, 16> methodTypes;
  6556. for (int methodIdx = 0; methodIdx < (int)typeDef->mMethods.size(); methodIdx++)
  6557. {
  6558. if (!needsTypeData)
  6559. break;
  6560. // Disable const method reflection info for now
  6561. if (mIsComptimeModule)
  6562. break;
  6563. auto methodInstanceGroup = &typeInstance->mMethodInstanceGroups[methodIdx];
  6564. if (!methodInstanceGroup->IsImplemented())
  6565. continue;
  6566. auto methodDef = typeDef->mMethods[methodIdx];
  6567. if (methodDef->mIsNoReflect)
  6568. continue;
  6569. if (methodDef->mHasComptime)
  6570. continue;
  6571. auto defaultMethod = methodInstanceGroup->mDefault;
  6572. if (defaultMethod == NULL)
  6573. continue;
  6574. if (defaultMethod->mIsUnspecialized)
  6575. continue;
  6576. if (!defaultMethod->mIsReified)
  6577. continue;
  6578. if ((defaultMethod->mChainType == BfMethodChainType_ChainMember) || (defaultMethod->mChainType == BfMethodChainType_ChainSkip))
  6579. continue;
  6580. if (defaultMethod->mMethodDef->mMethodType == BfMethodType_CtorNoBody)
  6581. continue;
  6582. if (!defaultMethod->mMethodDef->CanReflect())
  6583. continue;
  6584. auto methodReflectKind = (BfReflectKind)(reflectKind & ~BfReflectKind_User);
  6585. bool includeMethod = reflectIncludeAllMethods;
  6586. if (typeInstance->IsDelegateOrFunction())
  6587. includeMethod = true;
  6588. BfMethodCustomAttributes* methodCustomAttributes = NULL;
  6589. if ((defaultMethod->mMethodInfoEx != NULL) && (defaultMethod->mMethodInfoEx->mMethodCustomAttributes != NULL) && (defaultMethod->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes != NULL))
  6590. {
  6591. methodCustomAttributes = defaultMethod->mMethodInfoEx->mMethodCustomAttributes;
  6592. for (auto& customAttr : defaultMethod->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes->mAttributes)
  6593. {
  6594. if (customAttr.mType->mTypeDef->mName->ToString() == "ReflectAttribute")
  6595. {
  6596. includeMethod = true;
  6597. }
  6598. else
  6599. {
  6600. auto userReflectKind = GetUserReflectKind(customAttr.mType);
  6601. methodReflectKind = (BfReflectKind)(methodReflectKind | userReflectKind);
  6602. }
  6603. }
  6604. }
  6605. if ((!mIsComptimeModule) && (!typeInstance->IsTypeMemberAccessible(methodDef->mDeclaringType, mProject)))
  6606. continue;
  6607. //
  6608. {
  6609. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  6610. if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  6611. {
  6612. BfTypeState typeState;
  6613. typeState.mPrevState = mContext->mCurTypeState;
  6614. typeState.mForceActiveTypeDef = methodDef->mDeclaringType;
  6615. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  6616. for (BfParameterDeclaration* paramDecl : methodDeclaration->mParams)
  6617. {
  6618. if (paramDecl->mAttributes != NULL)
  6619. methodReflectKind = (BfReflectKind)(methodReflectKind | _GetReflectUserFromDirective(paramDecl->mAttributes, BfAttributeTargets_Parameter));
  6620. }
  6621. }
  6622. }
  6623. if ((methodReflectKind & (BfReflectKind_Methods | BfReflectKind_User)) != 0)
  6624. includeMethod = true;
  6625. if ((methodDef->mIsStatic) && ((methodReflectKind & BfReflectKind_StaticMethods) != 0))
  6626. includeMethod = true;
  6627. if ((methodDef->mMethodType == BfMethodType_Ctor) || (methodDef->mMethodType == BfMethodType_CtorCalcAppend))
  6628. {
  6629. if ((methodReflectKind & BfReflectKind_Constructors) != 0)
  6630. includeMethod = true;
  6631. if ((methodDef->IsDefaultCtor()) && ((methodReflectKind & BfReflectKind_DefaultConstructor) != 0))
  6632. includeMethod = true;
  6633. }
  6634. if ((!includeMethod) && (typeOptions != NULL))
  6635. includeMethod = ApplyTypeOptionMethodFilters(includeMethod, methodDef, typeOptions);
  6636. if (!includeMethod)
  6637. continue;
  6638. sortedMethodList.Add({ methodDef, methodCustomAttributes });
  6639. }
  6640. auto _GetMethodKind = [](BfMethodDef* methodDef)
  6641. {
  6642. if (methodDef->mMethodType == BfMethodType_Ctor)
  6643. return 0;
  6644. return 1;
  6645. };
  6646. std::sort(sortedMethodList.begin(), sortedMethodList.end(), [_GetMethodKind](const _SortedMethodInfo& lhs, const _SortedMethodInfo& rhs)
  6647. {
  6648. int lhsKind = _GetMethodKind(lhs.mMethodDef);
  6649. int rhsKind = _GetMethodKind(rhs.mMethodDef);
  6650. if (lhsKind != rhsKind)
  6651. return lhsKind < rhsKind;
  6652. if (lhs.mMethodDef->mName != rhs.mMethodDef->mName)
  6653. return lhs.mMethodDef->mName < rhs.mMethodDef->mName;
  6654. return lhs.mMethodDef->mIdx < rhs.mMethodDef->mIdx;
  6655. });
  6656. for (auto& methodInfo : sortedMethodList)
  6657. {
  6658. auto methodDef = methodInfo.mMethodDef;
  6659. int methodIdx = methodDef->mIdx;
  6660. auto methodInstanceGroup = &typeInstance->mMethodInstanceGroups[methodIdx];
  6661. auto defaultMethod = methodInstanceGroup->mDefault;
  6662. BfModuleMethodInstance moduleMethodInstance;
  6663. BfIRValue funcVal = voidPtrNull;
  6664. if (((!typeInstance->IsBoxed()) || (!methodDef->mIsStatic)) &&
  6665. (!typeInstance->IsUnspecializedType()) &&
  6666. (methodDef->mMethodType != BfMethodType_Ignore) &&
  6667. (methodDef->mMethodType != BfMethodType_Mixin) &&
  6668. (!methodDef->mIsAbstract) &&
  6669. (methodDef->mGenericParams.size() == 0))
  6670. {
  6671. moduleMethodInstance = GetMethodInstanceAtIdx(typeInstance, methodIdx, NULL, BfGetMethodInstanceFlag_NoInline);
  6672. if (moduleMethodInstance.mFunc)
  6673. funcVal = mBfIRBuilder->CreateBitCast(moduleMethodInstance.mFunc, voidPtrIRType);
  6674. }
  6675. BfIRValue methodNameConst = GetStringObjectValue(methodDef->GetReflectName(), !mIsComptimeModule);
  6676. BfMethodFlags methodFlags = defaultMethod->GetMethodFlags();
  6677. int customAttrIdx = -1;
  6678. int returnCustomAttrIdx = -1;
  6679. if (methodInfo.mMethodCustomAttributes != NULL)
  6680. {
  6681. customAttrIdx = _HandleCustomAttrs(methodInfo.mMethodCustomAttributes->mCustomAttributes);
  6682. returnCustomAttrIdx = _HandleCustomAttrs(methodInfo.mMethodCustomAttributes->mReturnCustomAttributes);
  6683. }
  6684. enum ParamFlags
  6685. {
  6686. ParamFlag_None = 0,
  6687. ParamFlag_Splat = 1,
  6688. ParamFlag_Implicit = 2,
  6689. ParamFlag_AppendIdx = 4,
  6690. ParamFlag_Params = 8
  6691. };
  6692. SizedArray<BfIRValue, 8> paramVals;
  6693. for (int paramIdx = 0; paramIdx < defaultMethod->GetParamCount(); paramIdx++)
  6694. {
  6695. String paramName = defaultMethod->GetParamName(paramIdx);
  6696. BfType* paramType = defaultMethod->GetParamType(paramIdx);
  6697. ParamFlags paramFlags = ParamFlag_None;
  6698. if (defaultMethod->GetParamIsSplat(paramIdx))
  6699. paramFlags = (ParamFlags)(paramFlags | ParamFlag_Splat);
  6700. if (defaultMethod->GetParamKind(paramIdx) == BfParamKind_AppendIdx)
  6701. paramFlags = (ParamFlags)(paramFlags | ParamFlag_Implicit | ParamFlag_AppendIdx);
  6702. if (defaultMethod->GetParamKind(paramIdx) == BfParamKind_Params)
  6703. paramFlags = (ParamFlags)(paramFlags | ParamFlag_Params);
  6704. BfIRValue paramNameConst = GetStringObjectValue(paramName, !mIsComptimeModule);
  6705. int paramCustomAttrIdx = -1;
  6706. if ((methodInfo.mMethodCustomAttributes != NULL) && (paramIdx < (int)methodInfo.mMethodCustomAttributes->mParamCustomAttributes.mSize))
  6707. paramCustomAttrIdx = _HandleCustomAttrs(methodInfo.mMethodCustomAttributes->mParamCustomAttributes[paramIdx]);
  6708. SizedArray<BfIRValue, 8> paramDataVals =
  6709. {
  6710. emptyValueType,
  6711. paramNameConst,
  6712. GetConstValue(paramType->mTypeId, typeIdType),
  6713. GetConstValue((int32)paramFlags, shortType),
  6714. GetConstValue(-1, intType), // defaultIdx
  6715. GetConstValue(paramCustomAttrIdx, intType) // customAttrIdx
  6716. };
  6717. auto paramData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapType(reflectParamDataType, BfIRPopulateType_Full), paramDataVals);
  6718. paramVals.Add(paramData);
  6719. }
  6720. BfIRValue paramsVal;
  6721. if (paramVals.size() > 0)
  6722. {
  6723. BfIRType paramDataArrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->MapType(reflectParamDataType, BfIRPopulateType_Full), (int)paramVals.size());
  6724. BfIRValue paramDataConst = mBfIRBuilder->CreateConstAgg_Value(paramDataArrayType, paramVals);
  6725. BfIRValue paramDataArray = mBfIRBuilder->CreateGlobalVariable(paramDataArrayType, true, BfIRLinkageType_Internal,
  6726. paramDataConst, typeDataName + StrFormat(".params%d", methodIdx));
  6727. paramsVal = mBfIRBuilder->CreateBitCast(paramDataArray, mBfIRBuilder->MapType(reflectParamDataPtrType));
  6728. }
  6729. else
  6730. paramsVal = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(reflectParamDataPtrType));
  6731. int vDataVal = -1;
  6732. if (defaultMethod->mVirtualTableIdx != -1)
  6733. {
  6734. int vDataIdx = -1;
  6735. if (type->IsInterface())
  6736. {
  6737. vDataIdx = defaultMethod->mVirtualTableIdx;
  6738. }
  6739. else
  6740. {
  6741. vDataIdx = mCompiler->GetVDataPrefixDataCount() + mCompiler->GetDynCastVDataCount() + mCompiler->mMaxInterfaceSlots;
  6742. if ((mCompiler->mOptions.mHasVDataExtender) && (mCompiler->IsHotCompile()))
  6743. {
  6744. auto typeInst = defaultMethod->mMethodInstanceGroup->mOwner;
  6745. int extMethodIdx = (defaultMethod->mVirtualTableIdx - typeInst->GetImplBaseVTableSize()) - typeInst->GetOrigSelfVTableSize();
  6746. if (extMethodIdx >= 0)
  6747. {
  6748. // Extension?
  6749. int vExtOfs = typeInst->GetOrigImplBaseVTableSize();
  6750. vDataVal = ((vDataIdx + vExtOfs + 1) << 20) | (extMethodIdx);
  6751. }
  6752. else
  6753. {
  6754. // Map this new virtual index back to the original index
  6755. vDataIdx += (defaultMethod->mVirtualTableIdx - typeInst->GetImplBaseVTableSize()) + typeInst->GetOrigImplBaseVTableSize();
  6756. }
  6757. }
  6758. else
  6759. {
  6760. vDataIdx += defaultMethod->mVirtualTableIdx;
  6761. }
  6762. }
  6763. if (vDataVal == -1)
  6764. vDataVal = vDataIdx * mSystem->mPtrSize;
  6765. }
  6766. SizedArray<BfIRValue, 8> methodDataVals =
  6767. {
  6768. emptyValueType,
  6769. methodNameConst, // mName
  6770. funcVal, // mFuncPtr
  6771. paramsVal,
  6772. GetConstValue(defaultMethod->mReturnType->mTypeId, typeIdType),
  6773. GetConstValue((int)paramVals.size(), shortType),
  6774. GetConstValue(methodFlags, intType),
  6775. GetConstValue(methodIdx, intType),
  6776. GetConstValue(vDataVal, intType),
  6777. GetConstValue(customAttrIdx, intType),
  6778. GetConstValue(returnCustomAttrIdx, intType),
  6779. };
  6780. auto methodData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectMethodDataType->ToTypeInstance(), BfIRPopulateType_Full), methodDataVals);
  6781. methodTypes.push_back(methodData);
  6782. }
  6783. BfIRValue methodDataPtr;
  6784. BfIRType methodDataPtrType = mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapType(reflectMethodDataType));
  6785. if (methodTypes.size() == 0)
  6786. methodDataPtr = mBfIRBuilder->CreateConstNull(methodDataPtrType);
  6787. else
  6788. {
  6789. BfIRType methodDataArrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->MapType(reflectMethodDataType, BfIRPopulateType_Full), (int)methodTypes.size());
  6790. BfIRValue methodDataConst = mBfIRBuilder->CreateConstAgg_Value(methodDataArrayType, methodTypes);
  6791. BfIRValue methodDataArray = mBfIRBuilder->CreateGlobalVariable(methodDataArrayType, true, BfIRLinkageType_Internal,
  6792. methodDataConst, "methods." + typeDataName);
  6793. methodDataPtr = mBfIRBuilder->CreateBitCast(methodDataArray, methodDataPtrType);
  6794. }
  6795. /////
  6796. int interfaceCount = 0;
  6797. BfIRValue interfaceDataPtr;
  6798. BfType* reflectInterfaceDataType = ResolveTypeDef(mCompiler->mReflectInterfaceDataDef);
  6799. BfIRType interfaceDataPtrType = mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapType(reflectInterfaceDataType));
  6800. Array<bool> wantsIfaceMethod;
  6801. bool wantsIfaceMethods = false;
  6802. if ((typeInstance->mInterfaces.IsEmpty()) || (!needsTypeData))
  6803. interfaceDataPtr = mBfIRBuilder->CreateConstNull(interfaceDataPtrType);
  6804. else
  6805. {
  6806. SizedArray<BfIRValue, 16> interfaces;
  6807. for (auto& interface : typeInstance->mInterfaces)
  6808. {
  6809. SizedArray<BfIRValue, 8> interfaceDataVals =
  6810. {
  6811. emptyValueType,
  6812. GetConstValue(interface.mInterfaceType->mTypeId, typeIdType),
  6813. GetConstValue(interface.mStartInterfaceTableIdx, intType),
  6814. GetConstValue(interface.mStartVirtualIdx, intType),
  6815. };
  6816. auto interfaceData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectInterfaceDataType->ToTypeInstance(), BfIRPopulateType_Full), interfaceDataVals);
  6817. interfaces.push_back(interfaceData);
  6818. if (!mIsComptimeModule)
  6819. {
  6820. for (int methodIdx = 0; methodIdx < (int)interface.mInterfaceType->mMethodInstanceGroups.size(); methodIdx++)
  6821. {
  6822. auto ifaceMethodGroup = &interface.mInterfaceType->mMethodInstanceGroups[methodIdx];
  6823. if (ifaceMethodGroup->mExplicitlyReflected)
  6824. {
  6825. wantsIfaceMethods = true;
  6826. int tableIdx = interface.mStartInterfaceTableIdx + methodIdx;
  6827. while (tableIdx >= wantsIfaceMethod.size())
  6828. wantsIfaceMethod.Add(false);
  6829. wantsIfaceMethod[tableIdx] = true;
  6830. }
  6831. }
  6832. }
  6833. }
  6834. BfIRType interfaceDataArrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->MapType(reflectInterfaceDataType, BfIRPopulateType_Full), (int)interfaces.size());
  6835. BfIRValue interfaceDataConst = mBfIRBuilder->CreateConstAgg_Value(interfaceDataArrayType, interfaces);
  6836. BfIRValue interfaceDataArray = mBfIRBuilder->CreateGlobalVariable(interfaceDataArrayType, true, BfIRLinkageType_Internal,
  6837. interfaceDataConst, "interfaces." + typeDataName);
  6838. interfaceDataPtr = mBfIRBuilder->CreateBitCast(interfaceDataArray, interfaceDataPtrType);
  6839. interfaceCount = (int)interfaces.size();
  6840. }
  6841. BfIRValue interfaceMethodTable;
  6842. int ifaceMethodTableSize = 0;
  6843. if ((wantsIfaceMethods) && (!typeInstance->IsInterface()) && (typeInstance->mIsReified) && (!typeInstance->IsUnspecializedType())
  6844. && (!typeInstance->mInterfaceMethodTable.IsEmpty()))
  6845. {
  6846. SizedArray<BfIRValue, 16> methods;
  6847. for (int tableIdx = 0; tableIdx < (int)typeInstance->mInterfaceMethodTable.size(); tableIdx++)
  6848. {
  6849. BfIRValue funcVal = voidPtrNull;
  6850. if ((tableIdx < (int)wantsIfaceMethod.size()) && (wantsIfaceMethod[tableIdx]))
  6851. {
  6852. auto methodEntry = typeInstance->mInterfaceMethodTable[tableIdx];
  6853. if (!methodEntry.mMethodRef.IsNull())
  6854. {
  6855. BfMethodInstance* methodInstance = methodEntry.mMethodRef;
  6856. if ((methodInstance->mIsReified) && (methodInstance->mMethodInstanceGroup->IsImplemented()) && (!methodInstance->mIsUnspecialized) &&
  6857. (!methodInstance->mMethodDef->mIsAbstract))
  6858. {
  6859. auto moduleMethodInstance = ReferenceExternalMethodInstance(methodInstance);
  6860. if (moduleMethodInstance.mFunc)
  6861. funcVal = mBfIRBuilder->CreateBitCast(moduleMethodInstance.mFunc, voidPtrIRType);
  6862. }
  6863. }
  6864. }
  6865. methods.Add(funcVal);
  6866. }
  6867. while ((!methods.IsEmpty()) && (methods.back() == voidPtrNull))
  6868. methods.pop_back();
  6869. if (!methods.IsEmpty())
  6870. {
  6871. BfIRType methodDataArrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->MapType(voidPtrType, BfIRPopulateType_Full), (int)methods.size());
  6872. BfIRValue methodDataConst = mBfIRBuilder->CreateConstAgg_Value(methodDataArrayType, methods);
  6873. BfIRValue methodDataArray = mBfIRBuilder->CreateGlobalVariable(methodDataArrayType, true, BfIRLinkageType_Internal,
  6874. methodDataConst, "imethods." + typeDataName);
  6875. interfaceMethodTable = mBfIRBuilder->CreateBitCast(methodDataArray, voidPtrPtrIRType);
  6876. ifaceMethodTableSize = (int)methods.size();
  6877. }
  6878. }
  6879. if (!interfaceMethodTable)
  6880. interfaceMethodTable = mBfIRBuilder->CreateConstNull(voidPtrPtrIRType);
  6881. /////
  6882. int underlyingType = 0;
  6883. if ((typeInstance->IsTypedPrimitive()) || (typeInstance->IsBoxed()))
  6884. {
  6885. underlyingType = typeInstance->GetUnderlyingType()->mTypeId;
  6886. }
  6887. int outerTypeId = 0;
  6888. auto outerType = mContext->mUnreifiedModule->GetOuterType(typeInstance);
  6889. if (outerType != NULL)
  6890. {
  6891. outerTypeId = outerType->mTypeId;
  6892. }
  6893. //
  6894. BfIRValue customAttrDataPtr;
  6895. if (customAttrs.size() > 0)
  6896. {
  6897. BfIRType customAttrsArrayType = mBfIRBuilder->GetSizedArrayType(voidPtrIRType, (int)customAttrs.size());
  6898. BfIRValue customAttrsConst = mBfIRBuilder->CreateConstAgg_Value(customAttrsArrayType, customAttrs);
  6899. BfIRValue customAttrsArray = mBfIRBuilder->CreateGlobalVariable(customAttrsArrayType, true, BfIRLinkageType_Internal,
  6900. customAttrsConst, "customAttrs." + typeDataName);
  6901. customAttrDataPtr = mBfIRBuilder->CreateBitCast(customAttrsArray, voidPtrPtrIRType);
  6902. }
  6903. else
  6904. {
  6905. customAttrDataPtr = mBfIRBuilder->CreateConstNull(voidPtrPtrIRType);
  6906. }
  6907. SizedArray<BfIRValue, 32> typeDataVals =
  6908. {
  6909. typeData,
  6910. castedClassVData, // mTypeClassVData
  6911. typeNameConst, // mName
  6912. namespaceConst, // mNamespace
  6913. GetConstValue(typeInstance->mInstSize, intType), // mInstSize
  6914. GetConstValue(typeInstance->mInstAlign, intType), // mInstAlign
  6915. GetConstValue(typeCustomAttrIdx, intType), // mCustomAttributes
  6916. GetConstValue(baseTypeId, typeIdType), // mBaseType
  6917. GetConstValue(underlyingType, typeIdType), // mUnderlyingType
  6918. GetConstValue(outerTypeId, typeIdType), // mOuterType
  6919. GetConstValue(typeInstance->mInheritanceId, intType), // mInheritanceId
  6920. GetConstValue(typeInstance->mInheritanceCount, intType), // mInheritanceCount
  6921. GetConstValue(typeInstance->mSlotNum, byteType), // mInterfaceSlot
  6922. GetConstValue(interfaceCount, byteType), // mInterfaceCount
  6923. GetConstValue(ifaceMethodTableSize, shortType), // mInterfaceMethodCount
  6924. GetConstValue((int)methodTypes.size(), shortType), // mMethodDataCount
  6925. GetConstValue(0, shortType), // mPropertyDataCount
  6926. GetConstValue((int)fieldTypes.size(), shortType), // mFieldDataCount
  6927. interfaceDataPtr, // mInterfaceDataPtr
  6928. interfaceMethodTable, // mInterfaceMethodTable
  6929. methodDataPtr, // mMethodDataPtr
  6930. voidPtrNull, // mPropertyDataPtr
  6931. fieldDataPtr, // mFieldDataPtr
  6932. customAttrDataPtr, // mCustomAttrDataPtr
  6933. };
  6934. BfIRType typeInstanceDataType = mBfIRBuilder->MapTypeInst(typeInstanceType->ToTypeInstance(), BfIRPopulateType_Full);
  6935. FixConstValueParams(typeInstanceType->ToTypeInstance(), typeDataVals);
  6936. auto typeInstanceData = mBfIRBuilder->CreateConstAgg_Value(typeInstanceDataType, typeDataVals);
  6937. if (!needsTypeData)
  6938. {
  6939. // No need for anything beyond typeInstanceData
  6940. }
  6941. else if ((typeInstance->IsGenericTypeInstance()) && (typeInstance->IsUnspecializedType()))
  6942. {
  6943. auto genericTypeInstance = typeInstance->ToGenericTypeInstance();
  6944. SizedArray<BfIRValue, 4> unspecializedData =
  6945. {
  6946. typeInstanceData,
  6947. GetConstValue((int)genericTypeInstance->mGenericTypeInfo->mTypeGenericArguments.size(), byteType), // mGenericParamCount
  6948. };
  6949. auto reflectUnspecializedGenericType = ResolveTypeDef(mCompiler->mReflectUnspecializedGenericType);
  6950. typeInstanceDataType = mBfIRBuilder->MapTypeInst(reflectUnspecializedGenericType->ToTypeInstance(), BfIRPopulateType_Full);
  6951. typeInstanceData = mBfIRBuilder->CreateConstAgg_Value(typeInstanceDataType, unspecializedData);
  6952. }
  6953. else if (typeInstance->IsGenericTypeInstance())
  6954. {
  6955. auto genericTypeInstance = typeInstance->ToGenericTypeInstance();
  6956. auto reflectSpecializedGenericType = ResolveTypeDef(mCompiler->mReflectSpecializedGenericType);
  6957. auto unspecializedType = ResolveTypeDef(typeInstance->mTypeDef->GetDefinition());
  6958. SizedArray<BfIRValue, 4> resolvedTypes;
  6959. for (auto typeGenericArg : genericTypeInstance->mGenericTypeInfo->mTypeGenericArguments)
  6960. resolvedTypes.push_back(GetConstValue(typeGenericArg->mTypeId, typeIdType));
  6961. auto typeIRType = mBfIRBuilder->MapType(typeIdType);
  6962. auto typePtrIRType = mBfIRBuilder->GetPointerTo(typeIRType);
  6963. auto genericArrayType = mBfIRBuilder->GetSizedArrayType(typeIRType, (int)resolvedTypes.size());
  6964. BfIRValue resolvedTypesConst = mBfIRBuilder->CreateConstAgg_Value(genericArrayType, resolvedTypes);
  6965. BfIRValue resolvedTypesArray = mBfIRBuilder->CreateGlobalVariable(genericArrayType, true, BfIRLinkageType_Internal,
  6966. resolvedTypesConst, "resolvedTypes." + typeDataName);
  6967. BfIRValue resovledTypesPtr = mBfIRBuilder->CreateBitCast(resolvedTypesArray, typePtrIRType);
  6968. SizedArray<BfIRValue, 3> specGenericData =
  6969. {
  6970. typeInstanceData,
  6971. GetConstValue(unspecializedType->mTypeId, typeIdType), // mUnspecialziedType
  6972. resovledTypesPtr, // mFieldDataPtr
  6973. };
  6974. typeInstanceDataType = mBfIRBuilder->MapTypeInst(reflectSpecializedGenericType->ToTypeInstance(), BfIRPopulateType_Full);
  6975. typeInstanceData = mBfIRBuilder->CreateConstAgg_Value(typeInstanceDataType, specGenericData);
  6976. if (typeInstance->IsArray())
  6977. {
  6978. auto arrayType = (BfArrayType*)typeInstance;
  6979. BfType* elementType = genericTypeInstance->mGenericTypeInfo->mTypeGenericArguments[0];
  6980. BfFieldInstance* elementFieldInstance = &genericTypeInstance->mFieldInstances[0];
  6981. SizedArray<BfIRValue, 4> arrayData =
  6982. {
  6983. typeInstanceData,
  6984. GetConstValue(elementType->mSize, intType), // mElementSize
  6985. GetConstValue(1, byteType), // mRank
  6986. GetConstValue(elementFieldInstance->mDataOffset, byteType), // mElementsDataOffset
  6987. };
  6988. auto reflectArrayType = ResolveTypeDef(mCompiler->mReflectArrayType);
  6989. typeInstanceDataType = mBfIRBuilder->MapTypeInst(reflectArrayType->ToTypeInstance(), BfIRPopulateType_Full);
  6990. typeInstanceData = mBfIRBuilder->CreateConstAgg_Value(typeInstanceDataType, arrayData);
  6991. }
  6992. }
  6993. BfIRValue typeDataVar;
  6994. if (needsTypeData)
  6995. {
  6996. typeDataVar = mBfIRBuilder->CreateGlobalVariable(typeInstanceDataType, true,
  6997. BfIRLinkageType_External, typeInstanceData, typeDataName);
  6998. mBfIRBuilder->GlobalVar_SetAlignment(typeDataVar, mSystem->mPtrSize);
  6999. if (mBfIRBuilder->DbgHasInfo())
  7000. {
  7001. mBfIRBuilder->DbgCreateGlobalVariable(mDICompileUnit, typeDataName, typeDataName, BfIRMDNode(), 0, mBfIRBuilder->DbgGetTypeInst(typeInstanceType->ToTypeInstance()), false, typeDataVar);
  7002. }
  7003. }
  7004. else
  7005. {
  7006. typeDataVar = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(mContext->mBfTypeType));
  7007. }
  7008. typeDataVar = mBfIRBuilder->CreateBitCast(typeDataVar, mBfIRBuilder->MapType(mContext->mBfTypeType));
  7009. mTypeDataRefs[typeInstance] = typeDataVar;
  7010. if ((!mIsComptimeModule) && (classVDataVar))
  7011. {
  7012. BF_ASSERT(!classVDataName.IsEmpty());
  7013. //vData[0] = mBfIRBuilder->CreateBitCast(typeDataVar, voidPtrIRType);
  7014. int unboxedTypeId = type->mTypeId;
  7015. if (type->IsBoxed())
  7016. unboxedTypeId = type->GetUnderlyingType()->mTypeId;
  7017. if (mSystem->mPtrSize == 4)
  7018. {
  7019. vData[0] = mBfIRBuilder->CreateIntToPtr(GetConstValue(type->mTypeId, intPtrType), voidPtrIRType);
  7020. vData[1] = mBfIRBuilder->CreateIntToPtr(GetConstValue(unboxedTypeId, intPtrType), voidPtrIRType);
  7021. }
  7022. else
  7023. {
  7024. vData[0] = mBfIRBuilder->CreateIntToPtr(GetConstValue(((int64)unboxedTypeId << 32) | type->mTypeId, intPtrType), voidPtrIRType);
  7025. }
  7026. auto classVDataConstDataType = mBfIRBuilder->GetSizedArrayType(voidPtrIRType, (int)vData.size());
  7027. auto classVDataConstData = mBfIRBuilder->CreateConstAgg_Value(classVDataConstDataType, vData);
  7028. mBfIRBuilder->GlobalVar_SetInitializer(classVDataVar, classVDataConstData);
  7029. if (mCompiler->mOptions.mObjectHasDebugFlags)
  7030. mBfIRBuilder->GlobalVar_SetAlignment(classVDataVar, 256);
  7031. else
  7032. mBfIRBuilder->GlobalVar_SetAlignment(classVDataVar, mContext->mBfClassVDataPtrType->mAlign);
  7033. if (mBfIRBuilder->DbgHasInfo())
  7034. {
  7035. BfType* voidType = GetPrimitiveType(BfTypeCode_None);
  7036. BfType* voidPtrType = CreatePointerType(voidType);
  7037. BfType* classVDataType = ResolveTypeDef(mCompiler->mClassVDataTypeDef);
  7038. BfIRMDNode arrayType = mBfIRBuilder->DbgCreateArrayType(vData.size() * mSystem->mPtrSize * 8, mSystem->mPtrSize * 8, mBfIRBuilder->DbgGetType(voidPtrType), vData.size());
  7039. mBfIRBuilder->DbgCreateGlobalVariable(mDICompileUnit, classVDataName, classVDataName, BfIRMDNode(), 0, arrayType, false, classVDataVar);
  7040. }
  7041. }
  7042. return typeDataVar;
  7043. }
  7044. BfIRValue BfModule::FixClassVData(BfIRValue value)
  7045. {
  7046. if ((!mCompiler->mOptions.mObjectHasDebugFlags) || (mIsComptimeModule))
  7047. return value;
  7048. auto intptrValue = mBfIRBuilder->CreatePtrToInt(value, BfTypeCode_IntPtr);
  7049. auto maskedValue = mBfIRBuilder->CreateAnd(intptrValue, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, (uint64)~0xFFULL));
  7050. return mBfIRBuilder->CreateIntToPtr(maskedValue, mBfIRBuilder->GetType(value));
  7051. }
  7052. void BfModule::CheckStaticAccess(BfTypeInstance* typeInstance)
  7053. {
  7054. // Note: this is not just for perf, it fixes a field var-type resolution issue
  7055. if (mBfIRBuilder->mIgnoreWrites)
  7056. return;
  7057. if (mIsComptimeModule)
  7058. return;
  7059. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  7060. //TODO: Create a hashset of these, we don't need to repeatedly call static ctors for a given type
  7061. // When we access classes with static constructors FROM a static constructor,
  7062. // we call that other class's static constructor first. Recursion cannot occur, since
  7063. // we simply ignore subsequent attempts to re-enter the constructor
  7064. if (!typeInstance->mHasStaticInitMethod)
  7065. return;
  7066. if ((mCurMethodInstance == NULL) || ((mCurMethodInstance->mMethodDef->mMethodType != BfMethodType_Ctor) || (!mCurMethodInstance->mMethodDef->mIsStatic)))
  7067. return;
  7068. if (mCurMethodInstance->mMethodInstanceGroup->mOwner == typeInstance)
  7069. return;
  7070. auto checkTypeDef = typeInstance->mTypeDef;
  7071. checkTypeDef->PopulateMemberSets();
  7072. BfMethodDef* nextMethodDef = NULL;
  7073. BfMemberSetEntry* entry;
  7074. if (checkTypeDef->mMethodSet.TryGetWith(String("__BfStaticCtor"), &entry))
  7075. nextMethodDef = (BfMethodDef*)entry->mMemberDef;
  7076. while (nextMethodDef != NULL)
  7077. {
  7078. auto checkMethod = nextMethodDef;
  7079. nextMethodDef = nextMethodDef->mNextWithSameName;
  7080. auto methodModule = GetMethodInstance(typeInstance, checkMethod, BfTypeVector());
  7081. if (methodModule)
  7082. {
  7083. auto methodInstance = methodModule.mMethodInstance;
  7084. if ((methodInstance != NULL) &&
  7085. (methodInstance->mMethodDef->mIsStatic) &&
  7086. (methodInstance->mMethodDef->mMethodType == BfMethodType_Ctor) &&
  7087. ((methodInstance->mChainType == BfMethodChainType_ChainHead) || (methodInstance->mChainType == BfMethodChainType_None)))
  7088. {
  7089. mBfIRBuilder->CreateCall(methodModule.mFunc, SizedArray<BfIRValue, 0>());
  7090. break;
  7091. }
  7092. }
  7093. }
  7094. }
  7095. BfIRFunction BfModule::GetIntrinsic(BfMethodInstance* methodInstance, bool reportFailure)
  7096. {
  7097. auto methodOwner = methodInstance->GetOwner();
  7098. auto methodDef = methodInstance->mMethodDef;
  7099. auto methodDeclaration = methodDef->GetMethodDeclaration();
  7100. if (!methodDef->mIsExtern)
  7101. return BfIRFunction();
  7102. if (methodInstance->GetCustomAttributes() == NULL)
  7103. return BfIRFunction();
  7104. for (auto& customAttribute : methodInstance->GetCustomAttributes()->mAttributes)
  7105. {
  7106. String typeName = TypeToString(customAttribute.mType);
  7107. if ((typeName == "System.IntrinsicAttribute") && (customAttribute.mCtorArgs.size() > 0))
  7108. {
  7109. methodInstance->mIsIntrinsic = true;
  7110. auto constant = methodOwner->mConstHolder->GetConstant(customAttribute.mCtorArgs[0]);
  7111. String error;
  7112. if ((constant != NULL) && (constant->mTypeCode == BfTypeCode_StringId))
  7113. {
  7114. int stringId = constant->mInt32;
  7115. auto entry = mContext->mStringObjectIdMap[stringId];
  7116. String intrinName = entry.mString;
  7117. // if (intrinName.StartsWith(":"))
  7118. // {
  7119. // SizedArray<BfIRType, 2> paramTypes;
  7120. // for (auto& param : methodInstance->mParams)
  7121. // paramTypes.push_back(mBfIRBuilder->MapType(param.mResolvedType));
  7122. // return mBfIRBuilder->GetIntrinsic(intrinName.Substring(1), mBfIRBuilder->MapType(methodInstance->mReturnType), paramTypes);
  7123. // }
  7124. // else
  7125. {
  7126. int intrinId = BfIRCodeGen::GetIntrinsicId(intrinName);
  7127. if (intrinId != -1)
  7128. {
  7129. if (intrinId == BfIRIntrinsic_Malloc)
  7130. {
  7131. return GetBuiltInFunc(BfBuiltInFuncType_Malloc);
  7132. }
  7133. else if (intrinId == BfIRIntrinsic_Free)
  7134. {
  7135. return GetBuiltInFunc(BfBuiltInFuncType_Free);
  7136. }
  7137. SizedArray<BfIRType, 2> paramTypes;
  7138. for (auto& param : methodInstance->mParams)
  7139. paramTypes.push_back(mBfIRBuilder->MapType(param.mResolvedType));
  7140. return mBfIRBuilder->GetIntrinsic(intrinName, intrinId, mBfIRBuilder->MapType(methodInstance->mReturnType), paramTypes);
  7141. }
  7142. else if (reportFailure)
  7143. error = StrFormat("Unable to find intrinsic '%s'", entry.mString.c_str());
  7144. }
  7145. }
  7146. else if (reportFailure)
  7147. error = "Intrinsic name must be a constant string";
  7148. if (reportFailure)
  7149. {
  7150. Fail(error, customAttribute.mRef);
  7151. }
  7152. }
  7153. }
  7154. return BfIRFunction();
  7155. }
  7156. BfIRFunction BfModule::GetBuiltInFunc(BfBuiltInFuncType funcTypeId)
  7157. {
  7158. if (mBfIRBuilder->mIgnoreWrites)
  7159. return mBfIRBuilder->GetFakeFunction();
  7160. if (!mBuiltInFuncs[(int)funcTypeId])
  7161. {
  7162. SizedArray<BfIRType, 4> paramTypes;
  7163. auto nullPtrType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr));
  7164. auto intType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_IntPtr));
  7165. auto int32Type = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_Int32));
  7166. auto intPtrType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_IntPtr));
  7167. auto byteType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_Int8));
  7168. auto voidType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_None));
  7169. auto objType = mBfIRBuilder->MapType(mContext->mBfObjectType);
  7170. BfIRFunctionType funcType;
  7171. BfIRFunction func;
  7172. switch (funcTypeId)
  7173. {
  7174. case BfBuiltInFuncType_PrintF:
  7175. paramTypes.Add(nullPtrType);
  7176. funcType = mBfIRBuilder->CreateFunctionType(int32Type, paramTypes, true);
  7177. func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, "PrintF");
  7178. break;
  7179. case BfBuiltInFuncType_Malloc:
  7180. {
  7181. if ((mCompiler->mOptions.mDebugAlloc) && (!mIsComptimeModule))
  7182. {
  7183. func = GetInternalMethod("Dbg_RawAlloc", 1).mFunc;
  7184. }
  7185. else
  7186. {
  7187. String funcName = mCompiler->mOptions.mMallocLinkName;
  7188. if ((funcName.IsEmpty()) || (mIsComptimeModule))
  7189. funcName = "malloc";
  7190. func = mBfIRBuilder->GetFunction(funcName);
  7191. if (!func)
  7192. {
  7193. paramTypes.clear();
  7194. paramTypes.push_back(intType);
  7195. funcType = mBfIRBuilder->CreateFunctionType(nullPtrType, paramTypes);
  7196. func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, funcName);
  7197. mBfIRBuilder->Func_SetParamName(func, 1, "size");
  7198. }
  7199. }
  7200. }
  7201. break;
  7202. case BfBuiltInFuncType_Free:
  7203. {
  7204. if ((mCompiler->mOptions.mDebugAlloc) && (!mIsComptimeModule))
  7205. {
  7206. func = GetInternalMethod("Dbg_RawFree").mFunc;
  7207. }
  7208. else
  7209. {
  7210. String funcName = mCompiler->mOptions.mFreeLinkName;
  7211. if ((funcName.IsEmpty()) || (mIsComptimeModule))
  7212. funcName = "free";
  7213. func = mBfIRBuilder->GetFunction(funcName);
  7214. if (!func)
  7215. {
  7216. paramTypes.clear();
  7217. paramTypes.push_back(nullPtrType);
  7218. funcType = mBfIRBuilder->CreateFunctionType(voidType, paramTypes);
  7219. func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, funcName);
  7220. mBfIRBuilder->Func_SetParamName(func, 1, "ptr");
  7221. }
  7222. }
  7223. }
  7224. break;
  7225. case BfBuiltInFuncType_LoadSharedLibraries:
  7226. paramTypes.clear();
  7227. funcType = mBfIRBuilder->CreateFunctionType(voidType, paramTypes);
  7228. func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, "BfLoadSharedLibraries");
  7229. break;
  7230. default: break;
  7231. }
  7232. mBuiltInFuncs[(int)funcTypeId] = func;
  7233. return func;
  7234. }
  7235. return mBuiltInFuncs[(int)funcTypeId];
  7236. }
  7237. void BfModule::ResolveGenericParamConstraints(BfGenericParamInstance* genericParamInstance, bool isUnspecialized, Array<BfTypeReference*>* deferredResolveTypes)
  7238. {
  7239. BfGenericParamDef* genericParamDef = genericParamInstance->GetGenericParamDef();
  7240. BfExternalConstraintDef* externConstraintDef = genericParamInstance->GetExternConstraintDef();
  7241. BfConstraintDef* constraintDef = genericParamInstance->GetConstraintDef();
  7242. BfType* startingTypeConstraint = genericParamInstance->mTypeConstraint;
  7243. BfAutoComplete* bfAutocomplete = NULL;
  7244. if ((mCompiler->mResolvePassData != NULL) && (isUnspecialized))
  7245. bfAutocomplete = mCompiler->mResolvePassData->mAutoComplete;
  7246. if ((bfAutocomplete != NULL) && (genericParamDef != NULL))
  7247. {
  7248. for (int nameIdx = 0; nameIdx < (int)genericParamDef->mNameNodes.size(); nameIdx++)
  7249. {
  7250. auto nameNode = genericParamDef->mNameNodes[nameIdx];
  7251. if (bfAutocomplete->IsAutocompleteNode(nameNode))
  7252. {
  7253. String filter = nameNode->ToString();
  7254. bfAutocomplete->mInsertStartIdx = nameNode->GetSrcStart();
  7255. bfAutocomplete->mInsertEndIdx = nameNode->GetSrcEnd();
  7256. if (nameIdx != 0)
  7257. {
  7258. bfAutocomplete->AddEntry(AutoCompleteEntry("generic", nameNode->ToString().c_str()), filter);
  7259. }
  7260. }
  7261. }
  7262. }
  7263. for (auto constraint : constraintDef->mConstraints)
  7264. {
  7265. if (auto opConstraint = BfNodeDynCast<BfGenericOperatorConstraint>(constraint))
  7266. {
  7267. BfGenericOperatorConstraintInstance opConstraintInstance;
  7268. if (opConstraint->mLeftType != NULL)
  7269. {
  7270. if (bfAutocomplete != NULL)
  7271. bfAutocomplete->CheckTypeRef(opConstraint->mLeftType, false);
  7272. opConstraintInstance.mLeftType = ResolveTypeRef(opConstraint->mLeftType, BfPopulateType_Interfaces_All);
  7273. if (opConstraintInstance.mLeftType == NULL)
  7274. continue;
  7275. }
  7276. if (opConstraint->mRightType == NULL)
  7277. {
  7278. // We had a failure in parsing
  7279. continue;
  7280. }
  7281. if (opConstraint->mRightType != NULL)
  7282. {
  7283. if (bfAutocomplete != NULL)
  7284. bfAutocomplete->CheckTypeRef(opConstraint->mRightType, false);
  7285. opConstraintInstance.mRightType = ResolveTypeRef(opConstraint->mRightType, BfPopulateType_Interfaces_All);
  7286. if (opConstraintInstance.mRightType == NULL)
  7287. continue;
  7288. }
  7289. if (opConstraint->mOpToken == NULL)
  7290. {
  7291. FailAfter("Missing operator", (opConstraint->mLeftType != NULL) ? (BfAstNode*)opConstraint->mLeftType : (BfAstNode*)opConstraint->mOperatorToken);
  7292. continue;
  7293. }
  7294. if (opConstraint->mLeftType != NULL)
  7295. {
  7296. if (opConstraint->mRightType == NULL)
  7297. {
  7298. // Parse should have failed
  7299. continue;
  7300. }
  7301. opConstraintInstance.mBinaryOp = BfTokenToBinaryOp(opConstraint->mOpToken->mToken);
  7302. if (opConstraintInstance.mBinaryOp == BfBinaryOp_None)
  7303. {
  7304. Fail("Invalid binary operator", opConstraint->mOpToken);
  7305. continue;
  7306. }
  7307. }
  7308. else if ((opConstraint->mOpToken->mToken == BfToken_Implicit) || (opConstraint->mOpToken->mToken == BfToken_Explicit))
  7309. {
  7310. opConstraintInstance.mCastToken = opConstraint->mOpToken->mToken;
  7311. }
  7312. else
  7313. {
  7314. opConstraintInstance.mUnaryOp = BfTokenToUnaryOp(opConstraint->mOpToken->mToken);
  7315. if (opConstraintInstance.mUnaryOp == BfUnaryOp_None)
  7316. {
  7317. Fail("Invalid unary operator", opConstraint->mOpToken);
  7318. continue;
  7319. }
  7320. }
  7321. genericParamInstance->mOperatorConstraints.Add(opConstraintInstance);
  7322. continue;
  7323. }
  7324. auto constraintTypeRef = BfNodeDynCast<BfTypeReference>(constraint);
  7325. if (bfAutocomplete != NULL)
  7326. bfAutocomplete->CheckTypeRef(constraintTypeRef, true);
  7327. //TODO: Constraints may refer to other generic params (of either type or method)
  7328. // TO allow resolution, perhaps move this generic param initialization into GetMethodInstance (passing a genericPass bool)
  7329. BfResolveTypeRefFlags resolveFlags = BfResolveTypeRefFlag_AllowGenericMethodParamConstValue;
  7330. if (isUnspecialized)
  7331. resolveFlags = (BfResolveTypeRefFlags)(resolveFlags | BfResolveTypeRefFlag_DisallowComptime);
  7332. // We we have a deferredResolveTypes then we defer the generic validation, because we may have a case like
  7333. // `where T : Dictionay<TElem, int> and TElem : IHashable` and we don't want to throw the error on `T` before we build `TElem`
  7334. BfType* constraintType;
  7335. if (constraintTypeRef->IsA<BfVarTypeReference>())
  7336. constraintType = GetPrimitiveType(BfTypeCode_Var);
  7337. else
  7338. constraintType = ResolveTypeRef(constraintTypeRef, (deferredResolveTypes != NULL) ? BfPopulateType_Identity : BfPopulateType_Declaration, resolveFlags);
  7339. if (constraintType != NULL)
  7340. {
  7341. if (deferredResolveTypes != NULL)
  7342. {
  7343. PopulateType(constraintType, BfPopulateType_Declaration);
  7344. if (constraintType->IsUnspecializedTypeVariation())
  7345. deferredResolveTypes->Add(constraintTypeRef);
  7346. }
  7347. if ((constraintDef->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  7348. {
  7349. bool isValidTypeCode = false;
  7350. BfTypeCode typeCode = BfTypeCode_None;
  7351. if (constraintType->IsTypedPrimitive())
  7352. {
  7353. auto underlyingType = constraintType->GetUnderlyingType();
  7354. if (underlyingType->IsPrimitiveType())
  7355. typeCode = ((BfPrimitiveType*)underlyingType)->mTypeDef->mTypeCode;
  7356. }
  7357. if (constraintType->IsPrimitiveType())
  7358. typeCode = ((BfPrimitiveType*)constraintType)->mTypeDef->mTypeCode;
  7359. if (constraintType->IsInstanceOf(mCompiler->mStringTypeDef))
  7360. isValidTypeCode = true;
  7361. if (constraintType->IsValueType())
  7362. isValidTypeCode = true;
  7363. if (constraintType->IsVar())
  7364. isValidTypeCode = true;
  7365. switch (typeCode)
  7366. {
  7367. case BfTypeCode_StringId:
  7368. case BfTypeCode_Boolean:
  7369. case BfTypeCode_Int8:
  7370. case BfTypeCode_UInt8:
  7371. case BfTypeCode_Int16:
  7372. case BfTypeCode_UInt16:
  7373. case BfTypeCode_Int32:
  7374. case BfTypeCode_UInt32:
  7375. case BfTypeCode_Int64:
  7376. case BfTypeCode_UInt64:
  7377. case BfTypeCode_IntPtr:
  7378. case BfTypeCode_UIntPtr:
  7379. case BfTypeCode_IntUnknown:
  7380. case BfTypeCode_UIntUnknown:
  7381. case BfTypeCode_Float:
  7382. case BfTypeCode_Double:
  7383. case BfTypeCode_Char8:
  7384. case BfTypeCode_Char16:
  7385. case BfTypeCode_Char32:
  7386. isValidTypeCode = true;
  7387. break;
  7388. default: break;
  7389. }
  7390. if (isValidTypeCode)
  7391. {
  7392. genericParamInstance->mTypeConstraint = constraintType;
  7393. }
  7394. else
  7395. {
  7396. Fail("Const constraint must be a valuetype or string", constraintTypeRef);
  7397. }
  7398. }
  7399. else
  7400. {
  7401. bool checkEquality = false;
  7402. if (constraintType->IsVar())
  7403. {
  7404. // From a `comptype` generic undef resolution. Ignore.
  7405. genericParamInstance->mGenericParamFlags = (BfGenericParamFlags)(genericParamInstance->mGenericParamFlags | BfGenericParamFlag_ComptypeExpr);
  7406. genericParamInstance->mComptypeConstraint.Add(constraintTypeRef);
  7407. continue;
  7408. }
  7409. else if (constraintType->IsPrimitiveType())
  7410. {
  7411. checkEquality = true;
  7412. }
  7413. if (constraintType->IsArray())
  7414. {
  7415. if (isUnspecialized)
  7416. {
  7417. 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);
  7418. continue;
  7419. }
  7420. checkEquality = true;
  7421. }
  7422. if (constraintType->IsGenericParam())
  7423. {
  7424. checkEquality = true;
  7425. }
  7426. else if ((!constraintType->IsTypeInstance()) && (!constraintType->IsSizedArray()))
  7427. {
  7428. checkEquality = true;
  7429. }
  7430. if (checkEquality)
  7431. {
  7432. genericParamInstance->mTypeConstraint = constraintType;
  7433. }
  7434. else if (constraintType->IsInterface())
  7435. {
  7436. genericParamInstance->mInterfaceConstraints.push_back(constraintType->ToTypeInstance());
  7437. }
  7438. else
  7439. {
  7440. auto constraintTypeInst = constraintType->ToTypeInstance();
  7441. if (genericParamInstance->mTypeConstraint != NULL)
  7442. {
  7443. if ((constraintTypeInst != NULL) && (TypeIsSubTypeOf(constraintTypeInst, genericParamInstance->mTypeConstraint->ToTypeInstance(), false)))
  7444. {
  7445. // Allow more specific type
  7446. genericParamInstance->mTypeConstraint = constraintTypeInst;
  7447. }
  7448. else if ((constraintTypeInst != NULL) && (TypeIsSubTypeOf(genericParamInstance->mTypeConstraint->ToTypeInstance(), constraintTypeInst, false)))
  7449. {
  7450. // Silently ignore less-specific type
  7451. if ((startingTypeConstraint != NULL) && (startingTypeConstraint->IsDelegate()))
  7452. {
  7453. // 'System.Delegate' means that we are expecting an actual delegate instance. Simulate this by wanting a class.
  7454. genericParamInstance->mGenericParamFlags = (BfGenericParamFlags)(genericParamInstance->mGenericParamFlags | BfGenericParamFlag_Class);
  7455. }
  7456. }
  7457. else
  7458. {
  7459. Fail("Only one concrete type constraint may be specified", constraintTypeRef);
  7460. return;
  7461. }
  7462. }
  7463. else
  7464. genericParamInstance->mTypeConstraint = constraintType;
  7465. }
  7466. }
  7467. }
  7468. }
  7469. if (((constraintDef->mGenericParamFlags & BfGenericParamFlag_Const) != 0) &&
  7470. (genericParamInstance->mTypeConstraint == NULL))
  7471. genericParamInstance->mTypeConstraint = GetPrimitiveType(BfTypeCode_IntPtr);
  7472. }
  7473. String BfModule::GenericParamSourceToString(const BfGenericParamSource & genericParamSource)
  7474. {
  7475. if (genericParamSource.mMethodInstance != NULL)
  7476. {
  7477. //auto methodInst = GetUnspecializedMethodInstance(genericParamSource.mMethodInstance, false);
  7478. //SetAndRestoreValue<BfMethodInstance*> prevMethodInst(mCurMethodInstance, methodInst);
  7479. return MethodToString(genericParamSource.mMethodInstance);
  7480. }
  7481. else
  7482. {
  7483. auto typeInst = GetUnspecializedTypeInstance(genericParamSource.mTypeInstance);
  7484. SetAndRestoreValue<BfMethodInstance*> prevMethodInst(mCurMethodInstance, NULL);
  7485. SetAndRestoreValue<BfTypeInstance*> prevTypeInst(mCurTypeInstance, typeInst);
  7486. return TypeToString(typeInst);
  7487. }
  7488. }
  7489. bool BfModule::CheckGenericConstraints(const BfGenericParamSource& genericParamSource, BfType* checkArgType, BfAstNode* checkArgTypeRef, BfGenericParamInstance* genericParamInst, BfTypeVector* methodGenericArgs, BfError** errorOut)
  7490. {
  7491. Array<String> methodParamNameOverrides;
  7492. auto _TypeToString = [&](BfType* type)
  7493. {
  7494. if (genericParamSource.mMethodInstance != NULL)
  7495. {
  7496. if (methodParamNameOverrides.IsEmpty())
  7497. {
  7498. for (auto genericParam : genericParamSource.mMethodInstance->mMethodDef->mGenericParams)
  7499. methodParamNameOverrides.Add(genericParam->mName);
  7500. }
  7501. return TypeToString(type, &methodParamNameOverrides);
  7502. }
  7503. return TypeToString(type);
  7504. };
  7505. bool ignoreErrors = (errorOut == NULL) ||
  7506. ((genericParamSource.mMethodInstance == NULL) && (genericParamSource.mTypeInstance == NULL));
  7507. if (checkArgType->IsVar())
  7508. return true;
  7509. BfType* origCheckArgType = checkArgType;
  7510. if (origCheckArgType->IsRef())
  7511. origCheckArgType = origCheckArgType->GetUnderlyingType();
  7512. bool argIsReferenceType = false;
  7513. int checkGenericParamFlags = 0;
  7514. if (checkArgType->IsGenericParam())
  7515. {
  7516. BfGenericParamInstance* checkGenericParamInst = GetGenericParamInstance((BfGenericParamType*)checkArgType);
  7517. checkGenericParamFlags = checkGenericParamInst->mGenericParamFlags;
  7518. if (checkGenericParamInst->mTypeConstraint != NULL)
  7519. checkArgType = checkGenericParamInst->mTypeConstraint;
  7520. if (checkGenericParamInst->mGenericParamFlags & BfGenericParamFlag_Var)
  7521. checkArgType = GetPrimitiveType(BfTypeCode_Var);
  7522. // if ((checkGenericParamFlags & (BfGenericParamFlag_Struct | BfGenericParamFlag_StructPtr)) != 0)
  7523. // {
  7524. // argMayBeReferenceType = false;
  7525. // }
  7526. // else
  7527. // {
  7528. // argMayBeReferenceType = true;
  7529. // }
  7530. }
  7531. if (checkArgType->IsObjectOrInterface())
  7532. argIsReferenceType = true;
  7533. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mIsUnspecialized) && (mCurMethodInstance->mMethodInfoEx != NULL))
  7534. {
  7535. for (int genericParamIdx = (int)mCurMethodInstance->mMethodInfoEx->mMethodGenericArguments.size();
  7536. genericParamIdx < mCurMethodInstance->mMethodInfoEx->mGenericParams.size(); genericParamIdx++)
  7537. {
  7538. auto genericParamInst = mCurMethodInstance->mMethodInfoEx->mGenericParams[genericParamIdx];
  7539. if ((genericParamInst->mExternType == checkArgType) && (checkArgType->IsUnspecializedType()))
  7540. {
  7541. checkGenericParamFlags |= genericParamInst->mGenericParamFlags;
  7542. }
  7543. }
  7544. }
  7545. BfTypeInstance* typeConstraintInst = NULL;
  7546. if (genericParamInst->mTypeConstraint != NULL)
  7547. typeConstraintInst = genericParamInst->mTypeConstraint->ToTypeInstance();
  7548. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Struct) &&
  7549. ((checkGenericParamFlags & (BfGenericParamFlag_Struct | BfGenericParamFlag_Enum | BfGenericParamFlag_Var)) == 0) && (!checkArgType->IsValueType()))
  7550. {
  7551. if ((!ignoreErrors) && (PreFail()))
  7552. *errorOut = Fail(StrFormat("The type '%s' must be a value type in order to use it as parameter '%s' for '%s'",
  7553. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7554. return false;
  7555. }
  7556. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_StructPtr) &&
  7557. ((checkGenericParamFlags & (BfGenericParamFlag_StructPtr | BfGenericParamFlag_Var)) == 0) && (!checkArgType->IsPointer()))
  7558. {
  7559. if ((!ignoreErrors) && (PreFail()))
  7560. *errorOut = Fail(StrFormat("The type '%s' must be a pointer type in order to use it as parameter '%s' for '%s'",
  7561. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7562. return false;
  7563. }
  7564. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Class) &&
  7565. ((checkGenericParamFlags & (BfGenericParamFlag_Class | BfGenericParamFlag_Var)) == 0) && (!argIsReferenceType))
  7566. {
  7567. if ((!ignoreErrors) && (PreFail()))
  7568. *errorOut = Fail(StrFormat("The type '%s' must be a reference type in order to use it as parameter '%s' for '%s'",
  7569. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7570. return false;
  7571. }
  7572. if (genericParamInst->mGenericParamFlags & BfGenericParamFlag_Enum)
  7573. {
  7574. bool isEnum = checkArgType->IsEnum();
  7575. if ((origCheckArgType->IsGenericParam()) && (checkArgType->IsInstanceOf(mCompiler->mEnumTypeDef)))
  7576. isEnum = true;
  7577. if (((checkGenericParamFlags & (BfGenericParamFlag_Enum | BfGenericParamFlag_Var)) == 0) && (!isEnum))
  7578. {
  7579. if ((!ignoreErrors) && (PreFail()))
  7580. *errorOut = Fail(StrFormat("The type '%s' must be an enum type in order to use it as parameter '%s' for '%s'",
  7581. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7582. return false;
  7583. }
  7584. }
  7585. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Concrete) &&
  7586. ((checkGenericParamFlags & (BfGenericParamFlag_Interface | BfGenericParamFlag_Var)) == 0) && (checkArgType->IsInterface()))
  7587. {
  7588. if ((!ignoreErrors) && (PreFail()))
  7589. *errorOut = Fail(StrFormat("The type '%s' must be an concrete type in order to use it as parameter '%s' for '%s'",
  7590. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7591. return false;
  7592. }
  7593. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Interface) &&
  7594. ((checkGenericParamFlags & (BfGenericParamFlag_Interface | BfGenericParamFlag_Var)) == 0) && (!checkArgType->IsInterface()))
  7595. {
  7596. if ((!ignoreErrors) && (PreFail()))
  7597. *errorOut = Fail(StrFormat("The type '%s' must be an interface type in order to use it as parameter '%s' for '%s'",
  7598. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7599. return false;
  7600. }
  7601. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  7602. {
  7603. if (((checkGenericParamFlags & BfGenericParamFlag_Const) == 0) && (!checkArgType->IsConstExprValue()))
  7604. {
  7605. if ((!ignoreErrors) && (PreFail()))
  7606. *errorOut = Fail(StrFormat("The type '%s' must be a const value in order to use it as parameter '%s' for '%s'",
  7607. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7608. return false;
  7609. }
  7610. }
  7611. else
  7612. {
  7613. if (checkArgType->IsConstExprValue())
  7614. {
  7615. if ((!ignoreErrors) && (PreFail()))
  7616. *errorOut = Fail(StrFormat("The value '%s' cannot be used for generic type parameter '%s' for '%s'",
  7617. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7618. return false;
  7619. }
  7620. }
  7621. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Delete) != 0)
  7622. {
  7623. bool canDelete = false;
  7624. if (checkArgType->IsPointer())
  7625. canDelete = true;
  7626. else if (checkArgType->IsObjectOrInterface())
  7627. canDelete = true;
  7628. else if ((checkGenericParamFlags & (BfGenericParamFlag_Delete | BfGenericParamFlag_Var)) != 0)
  7629. canDelete = true;
  7630. if (!canDelete)
  7631. {
  7632. if ((!ignoreErrors) && (PreFail()))
  7633. {
  7634. if (checkArgType->IsGenericParam())
  7635. *errorOut = Fail(StrFormat("Must add 'where %s : delete' constraint in order to use type as parameter '%s' for '%s'",
  7636. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7637. else
  7638. *errorOut = Fail(StrFormat("The type '%s' must be a deletable type in order to use it as parameter '%s' for '%s'",
  7639. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7640. }
  7641. return false;
  7642. }
  7643. }
  7644. if (checkArgType->IsPointer())
  7645. {
  7646. auto ptrType = (BfPointerType*)checkArgType;
  7647. checkArgType = ptrType->mElementType;
  7648. }
  7649. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_New) != 0)
  7650. {
  7651. bool canAlloc = false;
  7652. if (auto checkTypeInst = checkArgType->ToTypeInstance())
  7653. {
  7654. if (checkTypeInst->IsObjectOrStruct())
  7655. {
  7656. checkTypeInst->mTypeDef->PopulateMemberSets();
  7657. BfMemberSetEntry* entry = NULL;
  7658. BfMethodDef* checkMethodDef = NULL;
  7659. checkTypeInst->mTypeDef->mMethodSet.TryGetWith(String("__BfCtor"), &entry);
  7660. if (entry != NULL)
  7661. checkMethodDef = (BfMethodDef*)entry->mMemberDef;
  7662. bool hadProtected = false;
  7663. while (checkMethodDef != NULL)
  7664. {
  7665. if (!checkMethodDef->mParams.IsEmpty())
  7666. {
  7667. auto firstParam = checkMethodDef->mParams[0];
  7668. if (((firstParam->mParamKind == BfParamKind_Params) || (firstParam->mParamKind == BfParamKind_AppendIdx) || (firstParam->mParamKind == BfParamKind_VarArgs)) ||
  7669. ((firstParam->mParamDeclaration != NULL) && (firstParam->mParamDeclaration->mInitializer != NULL)))
  7670. {
  7671. // Allow all-default params
  7672. }
  7673. else
  7674. {
  7675. checkMethodDef = checkMethodDef->mNextWithSameName;
  7676. continue;
  7677. }
  7678. }
  7679. if (checkMethodDef->mProtection == BfProtection_Public)
  7680. {
  7681. canAlloc = true;
  7682. break;
  7683. }
  7684. if ((checkMethodDef->mProtection == BfProtection_Protected) || (checkMethodDef->mProtection == BfProtection_ProtectedInternal))
  7685. hadProtected = true;
  7686. checkMethodDef = checkMethodDef->mNextWithSameName;
  7687. }
  7688. if ((!canAlloc) && (hadProtected) && (mCurTypeInstance != NULL))
  7689. canAlloc = TypeIsSubTypeOf(mCurTypeInstance, checkTypeInst, false);
  7690. }
  7691. }
  7692. else if (checkArgType->IsGenericParam())
  7693. {
  7694. canAlloc = (checkGenericParamFlags & (BfGenericParamFlag_New | BfGenericParamFlag_Var)) != 0;
  7695. }
  7696. else if (checkArgType->IsPrimitiveType())
  7697. {
  7698. // Any primitive types and stuff can be allocated
  7699. canAlloc = true;
  7700. }
  7701. if (!canAlloc)
  7702. {
  7703. if ((!ignoreErrors) && (PreFail()))
  7704. {
  7705. if (checkArgType->IsGenericParam())
  7706. *errorOut = Fail(StrFormat("Must add 'where %s : new' constraint in order to use type as parameter '%s' for '%s'",
  7707. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7708. else
  7709. *errorOut = Fail(StrFormat("The type '%s' must have an accessible default constructor in order to use it as parameter '%s' for '%s'",
  7710. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7711. }
  7712. return false;
  7713. }
  7714. }
  7715. if ((genericParamInst->mInterfaceConstraints.IsEmpty()) && (genericParamInst->mOperatorConstraints.IsEmpty()) && (genericParamInst->mTypeConstraint == NULL))
  7716. return true;
  7717. if (genericParamInst->mTypeConstraint != NULL)
  7718. {
  7719. bool constraintMatched = false;
  7720. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  7721. {
  7722. if (checkArgType->IsConstExprValue())
  7723. {
  7724. auto constExprValueType = (BfConstExprValueType*)checkArgType;
  7725. if (genericParamInst->mTypeConstraint->IsPrimitiveType())
  7726. {
  7727. auto primType = (BfPrimitiveType*)genericParamInst->mTypeConstraint;
  7728. // Let either an exact typematch or an undef pass through. Eventually instead of undefs we may want to do
  7729. // actual expression comparisons, but we are overly permissive now and then we may fail on specialization
  7730. if ((constExprValueType->mValue.mTypeCode != primType->mTypeDef->mTypeCode) &&
  7731. (constExprValueType->mValue.mTypeCode != BfTypeCode_Let) &&
  7732. (primType->mTypeDef->mTypeCode != BfTypeCode_Let) &&
  7733. (primType->mTypeDef->mTypeCode != BfTypeCode_Var))
  7734. {
  7735. bool doError = true;
  7736. if (BfIRConstHolder::IsInt(constExprValueType->mValue.mTypeCode))
  7737. {
  7738. if (BfIRConstHolder::IsInt(primType->mTypeDef->mTypeCode))
  7739. {
  7740. if (mCompiler->mSystem->DoesLiteralFit(primType->mTypeDef->mTypeCode, constExprValueType->mValue))
  7741. doError = false;
  7742. }
  7743. }
  7744. else if ((primType->mTypeDef->mTypeCode == BfTypeCode_Float) && ((constExprValueType->mValue.mTypeCode == BfTypeCode_Double)))
  7745. {
  7746. doError = false;
  7747. }
  7748. if (doError)
  7749. {
  7750. if ((!ignoreErrors) && (PreFail()))
  7751. *errorOut = Fail(StrFormat("Const generic argument '%s', declared with '%s', is not compatible with const constraint '%s' for '%s'", genericParamInst->GetName().c_str(),
  7752. _TypeToString(constExprValueType).c_str(), _TypeToString(genericParamInst->mTypeConstraint).c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7753. return false;
  7754. }
  7755. }
  7756. }
  7757. else if (genericParamInst->mTypeConstraint != constExprValueType->mType)
  7758. {
  7759. if ((!ignoreErrors) && (PreFail()))
  7760. *errorOut = Fail(StrFormat("Const generic argument '%s', declared as '%s', is not compatible with const constraint '%s' for '%s'", genericParamInst->GetName().c_str(),
  7761. _TypeToString(constExprValueType).c_str(), _TypeToString(genericParamInst->mTypeConstraint).c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7762. return false;
  7763. }
  7764. }
  7765. }
  7766. else
  7767. {
  7768. BfType* convCheckConstraint = genericParamInst->mTypeConstraint;
  7769. if ((convCheckConstraint->IsUnspecializedType()) && (methodGenericArgs != NULL))
  7770. convCheckConstraint = ResolveGenericType(convCheckConstraint, NULL, methodGenericArgs, mCurTypeInstance);
  7771. if (convCheckConstraint == NULL)
  7772. return false;
  7773. if ((checkArgType->IsMethodRef()) || (checkArgType->IsFunction()))
  7774. {
  7775. if (convCheckConstraint->IsDelegate())
  7776. {
  7777. BfMethodInstance* checkMethodInstance;
  7778. if (checkArgType->IsMethodRef())
  7779. {
  7780. auto methodRefType = (BfMethodRefType*)checkArgType;
  7781. checkMethodInstance = methodRefType->mMethodRef;
  7782. }
  7783. else
  7784. {
  7785. checkMethodInstance = GetRawMethodInstanceAtIdx(checkArgType->ToTypeInstance(), 0, "Invoke");
  7786. }
  7787. auto invokeMethod = GetRawMethodInstanceAtIdx(convCheckConstraint->ToTypeInstance(), 0, "Invoke");
  7788. if (checkMethodInstance->HasExplicitThis() != 0)
  7789. {
  7790. // Don't allow functions with explicit 'this'
  7791. }
  7792. else
  7793. {
  7794. BfExprEvaluator exprEvaluator(this);
  7795. if (exprEvaluator.IsExactMethodMatch(checkMethodInstance, invokeMethod))
  7796. constraintMatched = true;
  7797. }
  7798. }
  7799. else if (convCheckConstraint->IsInstanceOf(mCompiler->mDelegateTypeDef))
  7800. constraintMatched = true;
  7801. else if ((checkArgType->IsFunction()) && (convCheckConstraint->IsInstanceOf(mCompiler->mFunctionTypeDef)))
  7802. constraintMatched = true;
  7803. }
  7804. else if ((checkArgType == convCheckConstraint) || (checkArgType->IsVar()) || (TypeIsSubTypeOf(checkArgType->ToTypeInstance(), convCheckConstraint->ToTypeInstance())))
  7805. {
  7806. constraintMatched = true;
  7807. }
  7808. else if (origCheckArgType->IsWrappableType())
  7809. {
  7810. if (origCheckArgType->IsSizedArray())
  7811. {
  7812. auto sizedArrayType = (BfSizedArrayType*)origCheckArgType;
  7813. if (convCheckConstraint->IsGenericTypeInstance())
  7814. {
  7815. auto convCheckConstraintInst = (BfTypeInstance*)convCheckConstraint;
  7816. if (convCheckConstraintInst->IsInstanceOf(mCompiler->mSizedArrayTypeDef))
  7817. {
  7818. if (convCheckConstraintInst->mGenericTypeInfo->mTypeGenericArguments[0] == sizedArrayType->mElementType)
  7819. {
  7820. auto constExprValueType = (BfConstExprValueType*)convCheckConstraintInst->mGenericTypeInfo->mTypeGenericArguments[1];
  7821. if (sizedArrayType->mElementCount == constExprValueType->mValue.mInt64)
  7822. constraintMatched = true;
  7823. }
  7824. }
  7825. }
  7826. }
  7827. if (!constraintMatched)
  7828. {
  7829. BfTypeInstance* wrappedStructType = GetWrappedStructType(origCheckArgType, false);
  7830. if ((wrappedStructType == convCheckConstraint) || (TypeIsSubTypeOf(wrappedStructType, convCheckConstraint->ToTypeInstance())))
  7831. constraintMatched = true;
  7832. }
  7833. }
  7834. if (!constraintMatched)
  7835. {
  7836. if ((!ignoreErrors) && (PreFail()))
  7837. *errorOut = Fail(StrFormat("Generic argument '%s', declared to be '%s' for '%s', must derive from '%s'", genericParamInst->GetName().c_str(),
  7838. TypeToString(origCheckArgType).c_str(), GenericParamSourceToString(genericParamSource).c_str(), TypeToString(convCheckConstraint).c_str(),
  7839. _TypeToString(genericParamInst->mTypeConstraint).c_str()), checkArgTypeRef);
  7840. return false;
  7841. }
  7842. }
  7843. }
  7844. for (auto checkConstraint : genericParamInst->mInterfaceConstraints)
  7845. {
  7846. BfType* convCheckConstraint = checkConstraint;
  7847. if (convCheckConstraint->IsUnspecializedType())
  7848. convCheckConstraint = ResolveGenericType(convCheckConstraint, NULL, methodGenericArgs, mCurTypeInstance);
  7849. if (convCheckConstraint == NULL)
  7850. return false;
  7851. BfTypeInstance* typeConstraintInst = convCheckConstraint->ToTypeInstance();
  7852. bool implementsInterface = false;
  7853. if (origCheckArgType != checkArgType)
  7854. {
  7855. implementsInterface = CanCast(BfTypedValue(BfIRValue::sValueless, origCheckArgType), convCheckConstraint);
  7856. }
  7857. if (!implementsInterface)
  7858. implementsInterface = CanCast(BfTypedValue(BfIRValue::sValueless, checkArgType), convCheckConstraint);
  7859. if ((!implementsInterface) && (origCheckArgType->IsWrappableType()))
  7860. {
  7861. BfTypeInstance* wrappedStructType = GetWrappedStructType(origCheckArgType, false);
  7862. if (TypeIsSubTypeOf(wrappedStructType, typeConstraintInst))
  7863. implementsInterface = true;
  7864. }
  7865. if ((!implementsInterface) && (origCheckArgType->IsTypedPrimitive()))
  7866. {
  7867. auto underlyingType = origCheckArgType->GetUnderlyingType();
  7868. BfTypeInstance* wrappedStructType = GetWrappedStructType(underlyingType, false);
  7869. if (TypeIsSubTypeOf(wrappedStructType, typeConstraintInst))
  7870. implementsInterface = true;
  7871. }
  7872. if (!implementsInterface)
  7873. {
  7874. if ((!ignoreErrors) && (PreFail()))
  7875. *errorOut = Fail(StrFormat("Generic argument '%s', declared to be '%s' for '%s', must implement '%s'", genericParamInst->GetName().c_str(),
  7876. TypeToString(origCheckArgType).c_str(), GenericParamSourceToString(genericParamSource).c_str(), TypeToString(checkConstraint).c_str()), checkArgTypeRef);
  7877. return false;
  7878. }
  7879. }
  7880. for (auto& checkOpConstraint : genericParamInst->mOperatorConstraints)
  7881. {
  7882. auto leftType = checkOpConstraint.mLeftType;
  7883. if ((leftType != NULL) && (leftType->IsUnspecializedType()))
  7884. leftType = ResolveGenericType(leftType, NULL, methodGenericArgs, mCurTypeInstance);
  7885. if (leftType != NULL)
  7886. leftType = FixIntUnknown(leftType);
  7887. auto rightType = checkOpConstraint.mRightType;
  7888. if ((rightType != NULL) && (rightType->IsUnspecializedType()))
  7889. rightType = ResolveGenericType(rightType, NULL, methodGenericArgs, mCurTypeInstance);
  7890. if (rightType != NULL)
  7891. rightType = FixIntUnknown(rightType);
  7892. BfConstraintState constraintSet;
  7893. constraintSet.mPrevState = mContext->mCurConstraintState;
  7894. constraintSet.mGenericParamInstance = genericParamInst;
  7895. constraintSet.mLeftType = leftType;
  7896. constraintSet.mRightType = rightType;
  7897. SetAndRestoreValue<BfConstraintState*> prevConstraintSet(mContext->mCurConstraintState, &constraintSet);
  7898. if (!CheckConstraintState(NULL))
  7899. return false;
  7900. if (checkOpConstraint.mBinaryOp != BfBinaryOp_None)
  7901. {
  7902. BfExprEvaluator exprEvaluator(this);
  7903. BfTypedValue leftValue(mBfIRBuilder->GetFakeVal(), leftType);
  7904. BfTypedValue rightValue(mBfIRBuilder->GetFakeVal(), rightType);
  7905. //
  7906. {
  7907. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, true);
  7908. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, true);
  7909. exprEvaluator.PerformBinaryOperation(NULL, NULL, checkOpConstraint.mBinaryOp, NULL, (BfBinOpFlags)(BfBinOpFlag_NoClassify | BfBinOpFlag_IsConstraintCheck), leftValue, rightValue);
  7910. }
  7911. if ((!exprEvaluator.mResult) ||
  7912. (!CanCast(exprEvaluator.mResult, origCheckArgType, BfCastFlags_NoConversionOperator)))
  7913. {
  7914. if ((!ignoreErrors) && (PreFail()))
  7915. {
  7916. if (genericParamInst->mExternType != NULL)
  7917. *errorOut = Fail(StrFormat("Binary operation for '%s' must result in '%s' from binary operation '%s %s %s'",
  7918. GenericParamSourceToString(genericParamSource).c_str(), TypeToString(origCheckArgType).c_str(),
  7919. TypeToString(leftType).c_str(), BfGetOpName(checkOpConstraint.mBinaryOp), TypeToString(rightType).c_str()
  7920. ), checkArgTypeRef);
  7921. else
  7922. *errorOut = Fail(StrFormat("Generic argument '%s', declared to be '%s' for '%s', must result from binary operation '%s %s %s'", genericParamInst->GetName().c_str(),
  7923. TypeToString(origCheckArgType).c_str(), GenericParamSourceToString(genericParamSource).c_str(),
  7924. TypeToString(leftType).c_str(), BfGetOpName(checkOpConstraint.mBinaryOp), TypeToString(rightType).c_str()
  7925. ), checkArgTypeRef);
  7926. }
  7927. return false;
  7928. }
  7929. }
  7930. else
  7931. {
  7932. BfTypedValue rightValue(mBfIRBuilder->GetFakeVal(), rightType);
  7933. StringT<128> failedOpName;
  7934. if (checkOpConstraint.mCastToken == BfToken_Implicit)
  7935. {
  7936. if (!CanCast(rightValue, origCheckArgType, (BfCastFlags)(BfCastFlags_SilentFail | BfCastFlags_IsConstraintCheck)))
  7937. failedOpName = "implicit conversion from '";
  7938. }
  7939. else
  7940. {
  7941. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, true);
  7942. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, true);
  7943. if (checkOpConstraint.mCastToken == BfToken_Explicit)
  7944. {
  7945. if (!CastToValue(NULL, rightValue, origCheckArgType, (BfCastFlags)(BfCastFlags_Explicit | BfCastFlags_SilentFail | BfCastFlags_IsConstraintCheck)))
  7946. failedOpName = "explicit conversion from '";
  7947. }
  7948. else
  7949. {
  7950. BfExprEvaluator exprEvaluator(this);
  7951. exprEvaluator.mResult = rightValue;
  7952. exprEvaluator.PerformUnaryOperation(NULL, checkOpConstraint.mUnaryOp, NULL, BfUnaryOpFlag_IsConstraintCheck);
  7953. if ((!exprEvaluator.mResult) ||
  7954. (!CanCast(exprEvaluator.mResult, origCheckArgType)))
  7955. {
  7956. failedOpName += "unary operation '";
  7957. failedOpName += BfGetOpName(checkOpConstraint.mUnaryOp);
  7958. }
  7959. }
  7960. }
  7961. if (!failedOpName.IsEmpty())
  7962. {
  7963. if ((!ignoreErrors) && (PreFail()))
  7964. *errorOut = Fail(StrFormat("Generic argument '%s', declared to be '%s' for '%s', must result from %s%s'", genericParamInst->GetName().c_str(),
  7965. TypeToString(origCheckArgType).c_str(), GenericParamSourceToString(genericParamSource).c_str(),
  7966. failedOpName.c_str(), TypeToString(rightType).c_str()
  7967. ), checkArgTypeRef);
  7968. return false;
  7969. }
  7970. }
  7971. }
  7972. return true;
  7973. }
  7974. BfGenericParamType* BfModule::GetGenericParamType(BfGenericParamKind paramKind, int paramIdx)
  7975. {
  7976. if (paramIdx < (int)mContext->mGenericParamTypes[paramKind].size())
  7977. {
  7978. auto genericParamType = mContext->mGenericParamTypes[paramKind][paramIdx];
  7979. return genericParamType;
  7980. }
  7981. auto genericParamType = new BfGenericParamType();
  7982. genericParamType->mContext = mContext;
  7983. genericParamType->mGenericParamKind = paramKind;
  7984. genericParamType->mGenericParamIdx = paramIdx;
  7985. PopulateType(genericParamType);
  7986. BF_ASSERT(paramIdx == (int)mContext->mGenericParamTypes[paramKind].size());
  7987. mContext->mGenericParamTypes[paramKind].push_back(genericParamType);
  7988. BfResolvedTypeSet::LookupContext lookupCtx;
  7989. lookupCtx.mModule = this;
  7990. BfResolvedTypeSet::EntryRef typeEntry;
  7991. auto inserted = mContext->mResolvedTypes.Insert(genericParamType, &lookupCtx, &typeEntry);
  7992. BF_ASSERT(inserted);
  7993. typeEntry->mValue = genericParamType;
  7994. return genericParamType;
  7995. }
  7996. static int sValueFromExprIdx = 0;
  7997. BfTypedValue BfModule::FlushNullConditional(BfTypedValue result, bool ignoreNullable)
  7998. {
  7999. auto pendingNullCond = mCurMethodState->mPendingNullConditional;
  8000. if ((result) && (!result.mType->IsVar()) && (!ignoreNullable))
  8001. {
  8002. auto notNullBB = mBfIRBuilder->GetInsertBlock();
  8003. //TODO: Make this work, needed for 'void' and such
  8004. BfType* nullableType = NULL;
  8005. if ((result.mType->IsValueType()) && (!result.mType->IsNullable()))
  8006. {
  8007. BfTypeVector typeVec;
  8008. typeVec.push_back(result.mType);
  8009. nullableType = ResolveTypeDef(mCompiler->mNullableTypeDef, typeVec);
  8010. BF_ASSERT(nullableType != NULL);
  8011. }
  8012. // Go back to start and do any setup we need
  8013. mBfIRBuilder->SetInsertPoint(pendingNullCond->mPrevBB);
  8014. BfTypedValue nullableTypedValue;
  8015. if (nullableType != NULL)
  8016. {
  8017. nullableTypedValue = BfTypedValue(CreateAlloca(nullableType, true, "nullCond.nullable"), nullableType, true);
  8018. mBfIRBuilder->CreateMemSet(nullableTypedValue.mValue, GetConstValue(0, GetPrimitiveType(BfTypeCode_Int8)),
  8019. GetConstValue(nullableType->mSize), nullableType->mAlign);
  8020. }
  8021. mBfIRBuilder->CreateBr(pendingNullCond->mCheckBB);
  8022. // Now that we have the nullableTypedValue we can set that, or just jump if we didn't need it
  8023. mBfIRBuilder->SetInsertPoint(notNullBB);
  8024. result = LoadValue(result);
  8025. if (nullableTypedValue)
  8026. {
  8027. auto elementType = nullableType->GetUnderlyingType();
  8028. if (elementType->IsVar())
  8029. {
  8030. // Do nothing
  8031. }
  8032. else if (elementType->IsValuelessType())
  8033. {
  8034. BfIRValue ptrValue = mBfIRBuilder->CreateInBoundsGEP(nullableTypedValue.mValue, 0, 1); // mHasValue
  8035. mBfIRBuilder->CreateStore(GetConstValue(1, GetPrimitiveType(BfTypeCode_Boolean)), ptrValue);
  8036. }
  8037. else
  8038. {
  8039. BfIRValue ptrValue = mBfIRBuilder->CreateInBoundsGEP(nullableTypedValue.mValue, 0, 1); // mValue
  8040. mBfIRBuilder->CreateAlignedStore(result.mValue, ptrValue, result.mType->mAlign);
  8041. ptrValue = mBfIRBuilder->CreateInBoundsGEP(nullableTypedValue.mValue, 0, 2); // mHasValue
  8042. mBfIRBuilder->CreateAlignedStore(GetConstValue(1, GetPrimitiveType(BfTypeCode_Boolean)), ptrValue, 1);
  8043. }
  8044. result = nullableTypedValue;
  8045. }
  8046. mBfIRBuilder->CreateBr(pendingNullCond->mDoneBB);
  8047. AddBasicBlock(pendingNullCond->mDoneBB);
  8048. if (nullableType == NULL)
  8049. {
  8050. auto phi = mBfIRBuilder->CreatePhi(mBfIRBuilder->MapType(result.mType), 1 + (int)pendingNullCond->mNotNullBBs.size());
  8051. mBfIRBuilder->AddPhiIncoming(phi, result.mValue, notNullBB);
  8052. mBfIRBuilder->AddPhiIncoming(phi, GetDefaultValue(result.mType), pendingNullCond->mCheckBB);
  8053. for (int notNullIdx = 0; notNullIdx < (int)pendingNullCond->mNotNullBBs.size() - 1; notNullIdx++)
  8054. {
  8055. auto prevNotNullBB = pendingNullCond->mNotNullBBs[notNullIdx];
  8056. mBfIRBuilder->AddPhiIncoming(phi, GetDefaultValue(result.mType), prevNotNullBB);
  8057. }
  8058. result.mValue = phi;
  8059. }
  8060. }
  8061. else
  8062. {
  8063. mBfIRBuilder->CreateBr(pendingNullCond->mDoneBB);
  8064. mBfIRBuilder->SetInsertPoint(pendingNullCond->mPrevBB);
  8065. mBfIRBuilder->CreateBr(pendingNullCond->mCheckBB);
  8066. AddBasicBlock(pendingNullCond->mDoneBB);
  8067. }
  8068. delete mCurMethodState->mPendingNullConditional;
  8069. mCurMethodState->mPendingNullConditional = NULL;
  8070. return result;
  8071. }
  8072. BF_NOINLINE void BfModule::EvaluateWithNewConditionalScope(BfExprEvaluator& exprEvaluator, BfExpression* expr, BfEvalExprFlags flags)
  8073. {
  8074. BfDeferredLocalAssignData deferredLocalAssignData(mCurMethodState->mCurScope);
  8075. SetAndRestoreValue<BfDeferredLocalAssignData*> prevDLA(mCurMethodState->mDeferredLocalAssignData);
  8076. if (mCurMethodState != NULL)
  8077. {
  8078. deferredLocalAssignData.mIsIfCondition = true;
  8079. deferredLocalAssignData.mIfMayBeSkipped = true;
  8080. deferredLocalAssignData.ExtendFrom(mCurMethodState->mDeferredLocalAssignData, false);
  8081. deferredLocalAssignData.mVarIdBarrier = mCurMethodState->GetRootMethodState()->mCurLocalVarId;
  8082. mCurMethodState->mDeferredLocalAssignData = &deferredLocalAssignData;
  8083. }
  8084. BfScopeData newScope;
  8085. newScope.mOuterIsConditional = true;
  8086. newScope.mAllowTargeting = false;
  8087. if (mCurMethodState != NULL)
  8088. {
  8089. mCurMethodState->AddScope(&newScope);
  8090. NewScopeState(true, false);
  8091. }
  8092. exprEvaluator.mBfEvalExprFlags = (BfEvalExprFlags)(exprEvaluator.mBfEvalExprFlags | flags);
  8093. exprEvaluator.Evaluate(expr, (flags & BfEvalExprFlags_PropogateNullConditional) != 0, (flags & BfEvalExprFlags_IgnoreNullConditional) != 0, (flags & BfEvalExprFlags_AllowSplat) != 0);
  8094. if (mCurMethodState != NULL)
  8095. RestoreScopeState();
  8096. }
  8097. BfTypedValue BfModule::CreateValueFromExpression(BfExprEvaluator& exprEvaluator, BfExpression* expr, BfType* wantTypeRef, BfEvalExprFlags flags, BfType** outOrigType)
  8098. {
  8099. //
  8100. {
  8101. BP_ZONE("CreateValueFromExpression:CheckStack");
  8102. StackHelper stackHelper;
  8103. if (!stackHelper.CanStackExpand(128 * 1024))
  8104. {
  8105. BfTypedValue result;
  8106. if (!stackHelper.Execute([&]()
  8107. {
  8108. result = CreateValueFromExpression(exprEvaluator, expr, wantTypeRef, flags, outOrigType);
  8109. }))
  8110. {
  8111. Fail("Expression too complex to compile", expr);
  8112. }
  8113. return result;
  8114. }
  8115. }
  8116. BP_ZONE("BfModule::CreateValueFromExpression");
  8117. if (outOrigType != NULL)
  8118. *outOrigType = NULL;
  8119. exprEvaluator.mExpectingType = wantTypeRef;
  8120. exprEvaluator.mBfEvalExprFlags = (BfEvalExprFlags)(exprEvaluator.mBfEvalExprFlags | flags);
  8121. exprEvaluator.mExplicitCast = (flags & BfEvalExprFlags_ExplicitCast) != 0;
  8122. if ((flags & BfEvalExprFlags_CreateConditionalScope) != 0)
  8123. {
  8124. if ((mCurMethodState == NULL) || (mCurMethodState->mCurScope->mScopeKind != BfScopeKind_StatementTarget_Conditional))
  8125. {
  8126. EvaluateWithNewConditionalScope(exprEvaluator, expr, flags);
  8127. }
  8128. else
  8129. {
  8130. SetAndRestoreValue<bool> prevIsConditional(mCurMethodState->mCurScope->mIsConditional, true);
  8131. exprEvaluator.Evaluate(expr, (flags & BfEvalExprFlags_PropogateNullConditional) != 0, (flags & BfEvalExprFlags_IgnoreNullConditional) != 0, true);
  8132. }
  8133. }
  8134. else
  8135. exprEvaluator.Evaluate(expr, (flags & BfEvalExprFlags_PropogateNullConditional) != 0, (flags & BfEvalExprFlags_IgnoreNullConditional) != 0, true);
  8136. if (!exprEvaluator.mResult)
  8137. {
  8138. if ((flags & BfEvalExprFlags_InferReturnType) != 0)
  8139. return exprEvaluator.mResult;
  8140. if (!mCompiler->mPassInstance->HasFailed())
  8141. {
  8142. if (PreFail())
  8143. Fail("INTERNAL ERROR: No expression result returned but no error caught in expression evaluator", expr);
  8144. }
  8145. return BfTypedValue();
  8146. }
  8147. auto typedVal = exprEvaluator.mResult;
  8148. if (typedVal.mKind == BfTypedValueKind_GenericConstValue)
  8149. {
  8150. BF_ASSERT(typedVal.mType->IsGenericParam());
  8151. auto genericParamDef = GetGenericParamInstance((BfGenericParamType*)typedVal.mType);
  8152. bool handled = false;
  8153. if ((genericParamDef->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  8154. {
  8155. auto genericTypeConstraint = genericParamDef->mTypeConstraint;
  8156. if (genericTypeConstraint != NULL)
  8157. {
  8158. auto underlyingConstraint = genericTypeConstraint;
  8159. if ((underlyingConstraint != NULL) && (underlyingConstraint->IsBoxed()))
  8160. underlyingConstraint = underlyingConstraint->GetUnderlyingType();
  8161. if (underlyingConstraint != NULL)
  8162. {
  8163. BfTypedValue result;
  8164. result.mKind = BfTypedValueKind_Value;
  8165. result.mType = genericTypeConstraint;
  8166. result.mValue = mBfIRBuilder->GetUndefConstValue(mBfIRBuilder->MapType(underlyingConstraint));
  8167. typedVal = result;
  8168. handled = true;
  8169. }
  8170. }
  8171. }
  8172. if (!handled)
  8173. {
  8174. //Fail("Only const generic parameters can be used as values", expr);
  8175. AssertErrorState();
  8176. return BfTypedValue();
  8177. }
  8178. }
  8179. if ((flags & BfEvalExprFlags_AllowIntUnknown) == 0)
  8180. FixIntUnknown(typedVal);
  8181. if (!mBfIRBuilder->mIgnoreWrites)
  8182. FixValueActualization(typedVal);
  8183. exprEvaluator.CheckResultForReading(typedVal);
  8184. if ((wantTypeRef == NULL) || (!wantTypeRef->IsRef()))
  8185. {
  8186. if ((flags & BfEvalExprFlags_NoCast) == 0)
  8187. {
  8188. // Only allow a 'ref' type if we have an explicit 'ref' operator
  8189. bool allowRef = false;
  8190. BfAstNode* checkExpr = expr;
  8191. while (checkExpr != NULL)
  8192. {
  8193. if (auto parenExpr = BfNodeDynCast<BfParenthesizedExpression>(checkExpr))
  8194. checkExpr = parenExpr->mExpression;
  8195. else if (auto unaryOp = BfNodeDynCast<BfUnaryOperatorExpression>(checkExpr))
  8196. {
  8197. if ((unaryOp->mOp == BfUnaryOp_Ref) || (unaryOp->mOp == BfUnaryOp_Mut))
  8198. allowRef = true;
  8199. break;
  8200. }
  8201. if (auto block = BfNodeDynCast<BfBlock>(checkExpr))
  8202. {
  8203. if (block->mChildArr.mSize == 0)
  8204. break;
  8205. checkExpr = block->mChildArr.back();
  8206. }
  8207. else
  8208. break;
  8209. }
  8210. if (!allowRef)
  8211. typedVal = RemoveRef(typedVal);
  8212. }
  8213. }
  8214. if ((!typedVal.mType->IsComposite()) && (!typedVal.mType->IsGenericParam())) // Load non-structs by default
  8215. {
  8216. if ((!mBfIRBuilder->mIgnoreWrites) && (!typedVal.mType->IsDataIncomplete()) && (!typedVal.mType->IsValuelessType()) && (!typedVal.mType->IsVar()))
  8217. {
  8218. if (typedVal.mValue.IsFake())
  8219. {
  8220. InternalError("Unexpected fakeval in CreateValueFromExpression");
  8221. typedVal = GetDefaultTypedValue(typedVal.mType);
  8222. }
  8223. }
  8224. typedVal = LoadValue(typedVal, 0, exprEvaluator.mIsVolatileReference);
  8225. }
  8226. if (wantTypeRef != NULL)
  8227. {
  8228. if (outOrigType != NULL)
  8229. *outOrigType = typedVal.mType;
  8230. if (((flags & BfEvalExprFlags_NoCast) == 0) && (!wantTypeRef->IsVar()))
  8231. {
  8232. BfCastFlags castFlags = ((flags & BfEvalExprFlags_ExplicitCast) != 0) ? BfCastFlags_Explicit : BfCastFlags_None;
  8233. if ((flags & BfEvalExprFlags_FieldInitializer) != 0)
  8234. castFlags = (BfCastFlags)(castFlags | BfCastFlags_WarnOnBox);
  8235. typedVal = Cast(expr, typedVal, wantTypeRef, castFlags);
  8236. if (!typedVal)
  8237. return typedVal;
  8238. }
  8239. if (exprEvaluator.mIsVolatileReference)
  8240. typedVal = LoadValue(typedVal, 0, exprEvaluator.mIsVolatileReference);
  8241. }
  8242. if ((typedVal.mType->IsValueType()) && ((flags & BfEvalExprFlags_NoValueAddr) != 0))
  8243. typedVal = LoadValue(typedVal, 0, exprEvaluator.mIsVolatileReference);
  8244. if (auto autoComplete = mCompiler->GetAutoComplete())
  8245. autoComplete->CheckResult(expr, typedVal);
  8246. return typedVal;
  8247. }
  8248. BfTypedValue BfModule::CreateValueFromExpression(BfExpression* expr, BfType* wantTypeRef, BfEvalExprFlags flags, BfType** outOrigType)
  8249. {
  8250. BfExprEvaluator exprEvaluator(this);
  8251. return CreateValueFromExpression(exprEvaluator, expr, wantTypeRef, flags, outOrigType);
  8252. }
  8253. BfTypedValue BfModule::GetOrCreateVarAddr(BfExpression* expr)
  8254. {
  8255. BfExprEvaluator exprEvaluator(this);
  8256. exprEvaluator.Evaluate(expr);
  8257. if (!exprEvaluator.mResult)
  8258. {
  8259. Fail("Invalid expression type", expr);
  8260. return BfTypedValue();
  8261. }
  8262. if (!exprEvaluator.mResult.IsAddr())
  8263. {
  8264. Fail("Cannot assign to value", expr);
  8265. return BfTypedValue();
  8266. }
  8267. return exprEvaluator.mResult;
  8268. }
  8269. // Clear memory, set classVData, call init. Actual ctor is called elsewhere.
  8270. void BfModule::InitTypeInst(BfTypedValue typedValue, BfScopeData* scopeData, bool zeroMemory, BfIRValue sizeValue, BfAllocFlags allocFlags)
  8271. {
  8272. auto typeInstance = typedValue.mType->ToTypeInstance();
  8273. if (zeroMemory)
  8274. {
  8275. int zeroAlign = typedValue.mType->mAlign;
  8276. if (typeInstance != NULL)
  8277. zeroAlign = typeInstance->mInstAlign;
  8278. mBfIRBuilder->CreateMemSet(typedValue.mValue, GetConstValue8(0), sizeValue, zeroAlign);
  8279. }
  8280. if (!typedValue.mType->IsObject())
  8281. {
  8282. return;
  8283. }
  8284. if ((scopeData == NULL) && (mCurMethodState != NULL))
  8285. return; // Handled in heap alloc funcs
  8286. auto typeDef = typeInstance->mTypeDef;
  8287. mBfIRBuilder->PopulateType(typedValue.mType);
  8288. auto vObjectAddr = mBfIRBuilder->CreateInBoundsGEP(typedValue.mValue, 0, 0);
  8289. bool isAutocomplete = mCompiler->IsAutocomplete();
  8290. BfIRValue vDataRef;
  8291. if (!isAutocomplete)
  8292. {
  8293. vDataRef = GetClassVDataPtr(typeInstance);
  8294. }
  8295. auto i8Type = GetPrimitiveType(BfTypeCode_Int8);
  8296. auto ptrType = CreatePointerType(i8Type);
  8297. auto ptrPtrType = CreatePointerType(ptrType);
  8298. PopulateType(ptrPtrType, BfPopulateType_Declaration);
  8299. PopulateType(ptrType, BfPopulateType_Declaration);
  8300. auto destAddr = mBfIRBuilder->CreateBitCast(vObjectAddr, mBfIRBuilder->MapType(ptrPtrType));
  8301. if (!isAutocomplete)
  8302. {
  8303. if ((mCompiler->mOptions.mObjectHasDebugFlags) && (!mIsComptimeModule))
  8304. {
  8305. auto objectPtr = mBfIRBuilder->CreateBitCast(destAddr, mBfIRBuilder->MapType(mContext->mBfObjectType));
  8306. SizedArray<BfIRValue, 4> llvmArgs;
  8307. llvmArgs.push_back(objectPtr);
  8308. llvmArgs.push_back(vDataRef);
  8309. llvmArgs.push_back(sizeValue);
  8310. llvmArgs.push_back(mBfIRBuilder->CreateConst(BfTypeCode_Int8, allocFlags));
  8311. auto objectStackInitMethod = GetInternalMethod("Dbg_ObjectStackInit");
  8312. if (objectStackInitMethod)
  8313. mBfIRBuilder->CreateCall(objectStackInitMethod.mFunc, llvmArgs);
  8314. }
  8315. else
  8316. {
  8317. auto srcVal = mBfIRBuilder->CreateBitCast(vDataRef, mBfIRBuilder->MapType(ptrType));
  8318. auto objectPtr = mBfIRBuilder->CreateBitCast(destAddr, mBfIRBuilder->MapType(ptrType));
  8319. mBfIRBuilder->CreateStore(srcVal, destAddr);
  8320. }
  8321. }
  8322. }
  8323. bool BfModule::IsAllocatorAligned()
  8324. {
  8325. if (mCompiler->mOptions.mMallocLinkName == "StompAlloc")
  8326. return false;
  8327. return true;
  8328. }
  8329. BfIRValue BfModule::AllocBytes(BfAstNode* refNode, const BfAllocTarget& allocTarget, BfType* type, BfIRValue sizeValue, BfIRValue alignValue, BfAllocFlags allocFlags/*, bool zeroMemory, bool defaultToMalloc*/)
  8330. {
  8331. BfIRValue result;
  8332. BfType* ptrType;
  8333. if ((type->IsObject()) && ((allocFlags & BfAllocFlags_RawArray) == 0))
  8334. ptrType = type;
  8335. else
  8336. ptrType = CreatePointerType(type);
  8337. if ((allocTarget.mScopedInvocationTarget != NULL) || (allocTarget.mCustomAllocator))
  8338. {
  8339. auto intType = GetPrimitiveType(BfTypeCode_IntPtr);
  8340. SizedArray<BfExpression*, 2> argExprs;
  8341. BfTypedValueExpression typedValueExpr;
  8342. typedValueExpr.Init(BfTypedValue(sizeValue, intType));
  8343. typedValueExpr.mRefNode = refNode;
  8344. argExprs.push_back(&typedValueExpr);
  8345. BfTypedValueExpression appendSizeValueExpr;
  8346. appendSizeValueExpr.Init(BfTypedValue(alignValue, intType));
  8347. appendSizeValueExpr.mRefNode = refNode;
  8348. argExprs.push_back(&appendSizeValueExpr);
  8349. BfExprEvaluator exprEvaluator(this);
  8350. BfTypedValue allocResult;
  8351. if (allocTarget.mScopedInvocationTarget != NULL)
  8352. {
  8353. SizedArray<BfTypeReference*, 2> genericArgs;
  8354. exprEvaluator.DoInvocation(allocTarget.mScopedInvocationTarget, NULL, argExprs, BfMethodGenericArguments());
  8355. allocResult = LoadValue(exprEvaluator.mResult);
  8356. }
  8357. else if (allocTarget.mCustomAllocator)
  8358. {
  8359. auto customTypeInst = allocTarget.mCustomAllocator.mType->ToTypeInstance();
  8360. if (customTypeInst == NULL)
  8361. {
  8362. if (allocTarget.mCustomAllocator.mType->IsStructPtr())
  8363. customTypeInst = allocTarget.mCustomAllocator.mType->GetUnderlyingType()->ToTypeInstance();
  8364. }
  8365. if (customTypeInst == NULL)
  8366. {
  8367. Fail(StrFormat("Type '%s' cannot be used as a custom allocator", TypeToString(allocTarget.mCustomAllocator.mType).c_str()), refNode);
  8368. }
  8369. else
  8370. {
  8371. BfTypedValueExpression typeValueExpr;
  8372. String allocMethodName = "Alloc";
  8373. if (GetRawMethodByName(customTypeInst, "AllocTyped", -1, true, true))
  8374. {
  8375. allocMethodName = "AllocTyped";
  8376. auto typeType = ResolveTypeDef(mCompiler->mTypeTypeDef);
  8377. auto typeRefVal = CreateTypeDataRef(type);
  8378. typeValueExpr.Init(BfTypedValue(typeRefVal, typeType));
  8379. typeValueExpr.mRefNode = refNode;
  8380. argExprs.Insert(0, &typeValueExpr);
  8381. }
  8382. if (HasMixin(customTypeInst, allocMethodName, 2))
  8383. {
  8384. BfSizedArray<BfExpression*> argExprArr;
  8385. argExprArr.mSize = (int)argExprs.size();
  8386. argExprArr.mVals = &argExprs[0];
  8387. exprEvaluator.InjectMixin(refNode, allocTarget.mCustomAllocator, false, allocMethodName, argExprs, {});
  8388. allocResult = exprEvaluator.GetResult();
  8389. }
  8390. else
  8391. {
  8392. BfSizedArray<BfExpression*> sizedArgExprs(argExprs);
  8393. BfResolvedArgs argValues(&sizedArgExprs);
  8394. exprEvaluator.ResolveArgValues(argValues);
  8395. SetAndRestoreValue<bool> prevNoBind(mCurMethodState->mNoBind, true);
  8396. allocResult = exprEvaluator.MatchMethod(refNode, NULL, allocTarget.mCustomAllocator, false, false, allocMethodName, argValues, BfMethodGenericArguments());
  8397. }
  8398. }
  8399. }
  8400. if (allocResult)
  8401. {
  8402. if (allocResult.mType->IsVoidPtr())
  8403. result = mBfIRBuilder->CreateBitCast(allocResult.mValue, mBfIRBuilder->MapType(ptrType));
  8404. else
  8405. result = CastToValue(refNode, allocResult, ptrType, BfCastFlags_Explicit);
  8406. return result;
  8407. }
  8408. }
  8409. if ((allocFlags & BfAllocFlags_NoDefaultToMalloc) != 0)
  8410. return result;
  8411. if ((mCompiler->mOptions.mDebugAlloc) && (!mIsComptimeModule))
  8412. {
  8413. BfIRValue allocData = GetDbgRawAllocData(type);
  8414. BfModuleMethodInstance allocMethod = GetInternalMethod("Dbg_RawAlloc", 2);
  8415. SizedArray<BfIRValue, 2> llvmArgs;
  8416. llvmArgs.push_back(sizeValue);
  8417. llvmArgs.push_back(allocData);
  8418. BfIRValue bitData = mBfIRBuilder->CreateCall(allocMethod.mFunc, llvmArgs);
  8419. return mBfIRBuilder->CreateBitCast(bitData, mBfIRBuilder->MapType(ptrType));
  8420. }
  8421. BfModuleMethodInstance moduleMethodInstance;
  8422. moduleMethodInstance = GetInternalMethod("Malloc");
  8423. SizedArray<BfIRValue, 1> llvmArgs;
  8424. llvmArgs.push_back(sizeValue);
  8425. auto func = moduleMethodInstance.mFunc;
  8426. if ((!func) || (func.IsFake()))
  8427. {
  8428. BF_ASSERT((mCompiler->mIsResolveOnly) || (mBfIRBuilder->mIgnoreWrites));
  8429. return mBfIRBuilder->CreateUndefValue(mBfIRBuilder->MapType(ptrType));
  8430. }
  8431. BfIRValue bitData = mBfIRBuilder->CreateCall(func, llvmArgs);
  8432. if ((allocFlags & BfAllocFlags_ZeroMemory) != 0)
  8433. mBfIRBuilder->CreateMemSet(bitData, GetConstValue8(0), sizeValue, alignValue);
  8434. result = mBfIRBuilder->CreateBitCast(bitData, mBfIRBuilder->MapType(ptrType));
  8435. return result;
  8436. }
  8437. BfIRValue BfModule::GetMarkFuncPtr(BfType* type)
  8438. {
  8439. if (type->IsStruct())
  8440. {
  8441. auto typeInstance = type->ToTypeInstance();
  8442. BfModuleMethodInstance moduleMethodInst = GetMethodByName(typeInstance, BF_METHODNAME_MARKMEMBERS, 0, true);
  8443. return mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr)));
  8444. }
  8445. else if (type->IsObjectOrInterface())
  8446. {
  8447. auto gcType = ResolveTypeDef(mCompiler->mGCTypeDef)->ToTypeInstance();
  8448. BfModuleMethodInstance moduleMethodInst = GetMethodByName(gcType, "MarkDerefedObject");
  8449. BF_ASSERT(moduleMethodInst.mFunc);
  8450. return mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr)));
  8451. }
  8452. else
  8453. {
  8454. auto gcType = ResolveTypeDef(mCompiler->mGCTypeDef)->ToTypeInstance();
  8455. BfExprEvaluator exprEvaluator(this);
  8456. SizedArray<BfResolvedArg, 1> resolvedArgs;
  8457. BfResolvedArg resolvedArg;
  8458. resolvedArg.mTypedValue = BfTypedValue(mBfIRBuilder->GetFakeVal(), type, type->IsComposite());
  8459. resolvedArgs.Add(resolvedArg);
  8460. BfMethodMatcher methodMatcher(NULL, this, "Mark", resolvedArgs, BfMethodGenericArguments());
  8461. methodMatcher.CheckType(gcType, BfTypedValue(), false);
  8462. BfModuleMethodInstance moduleMethodInst = exprEvaluator.GetSelectedMethod(NULL, methodMatcher.mBestMethodTypeInstance, methodMatcher.mBestMethodDef, methodMatcher);
  8463. BF_ASSERT(moduleMethodInst.mFunc);
  8464. return mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr)));
  8465. }
  8466. return BfIRValue();
  8467. }
  8468. BfIRValue BfModule::GetDbgRawAllocData(BfType* type)
  8469. {
  8470. BfIRValue allocDataValue;
  8471. if (mDbgRawAllocDataRefs.TryGetValue(type, &allocDataValue))
  8472. return allocDataValue;
  8473. BfIRValue markFuncPtr;
  8474. if (type->WantsGCMarking())
  8475. markFuncPtr = GetMarkFuncPtr(type);
  8476. else
  8477. markFuncPtr = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr)));
  8478. BfIRValue typeDataRef = CreateTypeDataRef(type);
  8479. auto dbgRawAllocDataType = ResolveTypeDef(mCompiler->mDbgRawAllocDataTypeDef)->ToTypeInstance();
  8480. BfTypeInstance* typeInstance = type->ToTypeInstance();
  8481. if (typeInstance == NULL)
  8482. {
  8483. typeInstance = GetWrappedStructType(type);
  8484. if (typeInstance != NULL)
  8485. AddDependency(typeInstance, mCurTypeInstance, BfDependencyMap::DependencyFlag_Allocates);
  8486. }
  8487. if (typeInstance != NULL)
  8488. PopulateType(typeInstance);
  8489. int stackCount = mCompiler->mOptions.mAllocStackCount;
  8490. if ((typeInstance != NULL) && (typeInstance->mTypeOptionsIdx != -1))
  8491. {
  8492. auto typeOptions = mSystem->GetTypeOptions(typeInstance->mTypeOptionsIdx);
  8493. stackCount = BfTypeOptions::Apply(stackCount, typeOptions->mAllocStackTraceDepth);
  8494. }
  8495. SizedArray<BfIRValue, 2> dataValues;
  8496. dataValues.Add(mBfIRBuilder->CreateConstAggZero(mBfIRBuilder->MapType(dbgRawAllocDataType->mBaseType, BfIRPopulateType_Full)));
  8497. dataValues.Add(typeDataRef);
  8498. dataValues.Add(markFuncPtr);
  8499. dataValues.Add(mBfIRBuilder->CreateConst(BfTypeCode_Int32, stackCount));
  8500. BfIRValue dataStruct = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapType(dbgRawAllocDataType, BfIRPopulateType_Full), dataValues);
  8501. allocDataValue = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapType(dbgRawAllocDataType), true, BfIRLinkageType_Internal, dataStruct, "__allocData_" + BfSafeMangler::Mangle(type));
  8502. mDbgRawAllocDataRefs.TryAdd(type, allocDataValue);
  8503. return allocDataValue;
  8504. }
  8505. BfIRValue BfModule::AllocFromType(BfType* type, const BfAllocTarget& allocTarget, BfIRValue appendSizeValue, BfIRValue arraySize, int arrayDim, BfAllocFlags allocFlags, int alignOverride)
  8506. {
  8507. BP_ZONE("AllocFromType");
  8508. BfScopeData* scopeData = allocTarget.mScopeData;
  8509. BF_ASSERT(!type->IsVar());
  8510. auto typeInstance = type->ToTypeInstance();
  8511. if ((typeInstance == NULL) && (type->IsGenericParam()))
  8512. typeInstance = mContext->mBfObjectType;
  8513. bool isHeapAlloc = scopeData == NULL;
  8514. bool isScopeAlloc = scopeData != NULL;
  8515. bool isLoopedAlloc = (scopeData != NULL) && (mCurMethodState->mCurScope->IsLooped(scopeData));
  8516. bool isDynAlloc = (scopeData != NULL) && (mCurMethodState->mCurScope->IsDyn(scopeData));
  8517. bool isRawArrayAlloc = (allocFlags & BfAllocFlags_RawArray) != 0;
  8518. bool zeroMemory = (allocFlags & BfAllocFlags_ZeroMemory) != 0;
  8519. bool noDtorCall = (allocFlags & BfAllocFlags_NoDtorCall) != 0;
  8520. if ((type->IsValuelessType()) && ((!arraySize) || (isRawArrayAlloc)))
  8521. {
  8522. BfPointerType* ptrType = CreatePointerType(type);
  8523. auto val = mBfIRBuilder->CreateIntToPtr(mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 1), mBfIRBuilder->MapType(ptrType));
  8524. return val;
  8525. }
  8526. if (typeInstance != NULL)
  8527. mBfIRBuilder->PopulateType(typeInstance);
  8528. bool hasCustomAllocator = (allocTarget.mCustomAllocator) || (allocTarget.mScopedInvocationTarget != NULL);
  8529. if ((!hasCustomAllocator) && (mBfIRBuilder->mIgnoreWrites))
  8530. {
  8531. return mBfIRBuilder->GetFakeVal();
  8532. }
  8533. AddDependency(type, mCurTypeInstance, BfDependencyMap::DependencyFlag_Allocates);
  8534. BfIRValue sizeValue;
  8535. BfIRType allocType = mBfIRBuilder->MapType(type);
  8536. int allocSize = type->mSize;
  8537. int allocAlign = type->mAlign;
  8538. if (typeInstance != NULL)
  8539. {
  8540. if ((!mBfIRBuilder->mIgnoreWrites) && (!mIsComptimeModule))
  8541. typeInstance->mHasBeenInstantiated = true;
  8542. allocSize = typeInstance->mInstSize;
  8543. allocAlign = typeInstance->mInstAlign;
  8544. //if (typeInstance->IsEnum())
  8545. //allocType = typeInstance->mIRType;
  8546. allocType = mBfIRBuilder->MapTypeInst(typeInstance);
  8547. }
  8548. if (alignOverride != -1)
  8549. allocAlign = alignOverride;
  8550. // The "dynSize" cases:
  8551. // If we are not dyn, but we are a variable size and could be looped over multiple times then we attempt to reuse
  8552. // the last stack space. We won't use StackSave and StackRestore because a scoped alloc that occurs after this but
  8553. // needs to be retained after the current scopeData (ie: scopeData::), then it would cause these allocs to accumulate even
  8554. // though we'd expect their stack space to be released
  8555. auto _CreateDynAlloc = [&](const BfIRValue& sizeValue, int align)
  8556. {
  8557. MarkDynStack(scopeData);
  8558. BfType* intType = GetPrimitiveType(BfTypeCode_IntPtr);
  8559. // For dynamically sized scoped allocs, we need to check the previous size to see if we need to realloc
  8560. BfType* voidType = GetPrimitiveType(BfTypeCode_None);
  8561. BfType* voidPtrType = CreatePointerType(voidType);
  8562. if (!mCurMethodState->mDynStackRevIdx)
  8563. {
  8564. mCurMethodState->mDynStackRevIdx = CreateAlloca(intType, false, "curDynStackRevIdx");
  8565. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  8566. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRInitBlock);
  8567. auto storeInst = mBfIRBuilder->CreateStore(GetConstValue(0), mCurMethodState->mDynStackRevIdx);
  8568. mBfIRBuilder->ClearDebugLocation(storeInst);
  8569. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  8570. }
  8571. auto byteType = GetPrimitiveType(BfTypeCode_Int8);
  8572. auto bytePtrType = CreatePointerType(byteType);
  8573. auto dynSizeAllocaInst = CreateAlloca(intType, false, "dynSize");
  8574. auto dynStackRevIdx = CreateAlloca(intType, false, "dynStackRevIdx");
  8575. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  8576. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRInitBlock);
  8577. auto storeInst = mBfIRBuilder->CreateStore(GetConstValue(0), dynSizeAllocaInst);
  8578. mBfIRBuilder->ClearDebugLocation(storeInst);
  8579. storeInst = mBfIRBuilder->CreateStore(GetConstValue(0), dynStackRevIdx);
  8580. mBfIRBuilder->ClearDebugLocation(storeInst);
  8581. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  8582. auto dynPtrAllocaInst = CreateAlloca(bytePtrType, false, "dynPtr");
  8583. if (IsTargetingBeefBackend())
  8584. {
  8585. // Since we don't allocate a debug variable for this, with LifetimeExtends, the easiest way
  8586. // to ensure there isn't any register collision during looping is just to not allow it to
  8587. // bind to a register at all
  8588. mBfIRBuilder->SetAllocaForceMem(dynSizeAllocaInst);
  8589. mBfIRBuilder->SetAllocaForceMem(dynPtrAllocaInst);
  8590. }
  8591. auto resizeBB = mBfIRBuilder->CreateBlock("dynAlloc.resize");
  8592. auto endBB = mBfIRBuilder->CreateBlock("dynAlloc.end");
  8593. auto verCheckBB = mBfIRBuilder->CreateBlock("dynAlloc.verCheck");
  8594. auto curDynStackRevIdx = mBfIRBuilder->CreateLoad(mCurMethodState->mDynStackRevIdx);
  8595. auto prevSize = mBfIRBuilder->CreateLoad(dynSizeAllocaInst);
  8596. auto isGreater = mBfIRBuilder->CreateCmpGT(sizeValue, prevSize, true);
  8597. mBfIRBuilder->CreateCondBr(isGreater, resizeBB, verCheckBB);
  8598. mBfIRBuilder->AddBlock(verCheckBB);
  8599. mBfIRBuilder->SetInsertPoint(verCheckBB);
  8600. auto prevDynStackRevIdx = mBfIRBuilder->CreateLoad(dynStackRevIdx);
  8601. auto dynStackChanged = mBfIRBuilder->CreateCmpNE(prevDynStackRevIdx, curDynStackRevIdx);
  8602. mBfIRBuilder->CreateCondBr(dynStackChanged, resizeBB, endBB);
  8603. mBfIRBuilder->AddBlock(resizeBB);
  8604. mBfIRBuilder->SetInsertPoint(resizeBB);
  8605. auto allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(byteType), sizeValue);
  8606. mBfIRBuilder->SetAllocaAlignment(allocaInst, align);
  8607. mBfIRBuilder->CreateStore(allocaInst, dynPtrAllocaInst);
  8608. mBfIRBuilder->CreateStore(sizeValue, dynSizeAllocaInst);
  8609. mBfIRBuilder->CreateStore(curDynStackRevIdx, dynStackRevIdx);
  8610. mBfIRBuilder->CreateBr(endBB);
  8611. mBfIRBuilder->AddBlock(endBB);
  8612. mBfIRBuilder->SetInsertPoint(endBB);
  8613. return mBfIRBuilder->CreateLoad(dynPtrAllocaInst);
  8614. };
  8615. if (isScopeAlloc)
  8616. {
  8617. if (arraySize)
  8618. {
  8619. bool isConstantArraySize = arraySize.IsConst();
  8620. if (isRawArrayAlloc)
  8621. {
  8622. BfPointerType* ptrType = CreatePointerType(type);
  8623. if ((!isDynAlloc) && (!isConstantArraySize) && (mCurMethodState->mCurScope->IsLooped(NULL)))
  8624. {
  8625. BfIRValue sizeValue = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySize);
  8626. auto loadedPtr = _CreateDynAlloc(sizeValue, type->mAlign);
  8627. InitTypeInst(BfTypedValue(loadedPtr, ptrType), scopeData, zeroMemory, sizeValue);
  8628. return mBfIRBuilder->CreateBitCast(loadedPtr, mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapType(type)));
  8629. }
  8630. else
  8631. {
  8632. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  8633. isDynAlloc = (isDynAlloc) || (!arraySize.IsConst());
  8634. if (!isDynAlloc)
  8635. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  8636. else
  8637. {
  8638. MarkDynStack(scopeData);
  8639. SaveStackState(scopeData);
  8640. }
  8641. int typeSize = type->GetStride();
  8642. BfIRValue allocaInst;
  8643. BfIRValue result;
  8644. if ((typeInstance == NULL) || (typeInstance->mIsCRepr))
  8645. {
  8646. allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(type), arraySize);
  8647. result = allocaInst;
  8648. }
  8649. else
  8650. {
  8651. if (typeInstance->IsStruct())
  8652. typeSize = typeInstance->GetInstStride();
  8653. auto byteType = GetPrimitiveStructType(BfTypeCode_Int8);
  8654. sizeValue = mBfIRBuilder->CreateMul(GetConstValue(typeSize), arraySize);
  8655. allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(byteType), sizeValue);
  8656. auto ptrType = CreatePointerType(typeInstance);
  8657. result = mBfIRBuilder->CreateBitCast(allocaInst, mBfIRBuilder->MapType(ptrType));
  8658. if (!isDynAlloc)
  8659. mBfIRBuilder->ClearDebugLocation(result);
  8660. }
  8661. if (!isDynAlloc)
  8662. mBfIRBuilder->ClearDebugLocation(allocaInst);
  8663. mBfIRBuilder->SetAllocaAlignment(allocaInst, allocAlign);
  8664. if (!isDynAlloc)
  8665. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  8666. auto typedVal = BfTypedValue(result, type, BfTypedValueKind_Addr);
  8667. if (arraySize.IsConst())
  8668. {
  8669. auto constant = mBfIRBuilder->GetConstant(arraySize);
  8670. if (constant->mInt64 == 0)
  8671. noDtorCall = true;
  8672. }
  8673. if (!noDtorCall)
  8674. {
  8675. bool isConstSize = arraySize.IsConst();
  8676. BfIRBlock clearBlock;
  8677. BfIRBlock contBlock;
  8678. bool wantsDeinit = ((!IsOptimized()) && (!mIsComptimeModule) && (!mBfIRBuilder->mIgnoreWrites) && (!mCompiler->mIsResolveOnly));
  8679. if (wantsDeinit)
  8680. {
  8681. BfIRBlock prevBlock;
  8682. if (!isConstSize)
  8683. {
  8684. clearBlock = mBfIRBuilder->CreateBlock("clear");
  8685. contBlock = mBfIRBuilder->CreateBlock("clearCont");
  8686. prevBlock = mBfIRBuilder->GetInsertBlock();
  8687. mBfIRBuilder->AddBlock(clearBlock);
  8688. mBfIRBuilder->SetInsertPoint(clearBlock);
  8689. }
  8690. auto deferredCall = AddStackAlloc(typedVal, arraySize, NULL, scopeData, false, true);
  8691. if (!isConstSize)
  8692. {
  8693. mBfIRBuilder->CreateBr(contBlock);
  8694. mBfIRBuilder->SetInsertPoint(prevBlock);
  8695. if (deferredCall != NULL)
  8696. {
  8697. // Zero out size args
  8698. for (int i = 1; i < deferredCall->mModuleMethodInstance.mMethodInstance->GetParamCount(); i++)
  8699. {
  8700. auto scopedArg = deferredCall->mScopeArgs[i];
  8701. if (scopedArg != deferredCall->mOrigScopeArgs[i])
  8702. mBfIRBuilder->CreateStore(GetDefaultValue(deferredCall->mModuleMethodInstance.mMethodInstance->GetParamType(i)), deferredCall->mScopeArgs[i]);
  8703. }
  8704. }
  8705. mBfIRBuilder->CreateCondBr(mBfIRBuilder->CreateCmpNE(arraySize, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 0)), clearBlock, contBlock);
  8706. mBfIRBuilder->AddBlock(contBlock);
  8707. mBfIRBuilder->SetInsertPoint(contBlock);
  8708. }
  8709. }
  8710. }
  8711. return result;
  8712. }
  8713. }
  8714. else
  8715. {
  8716. if ((!isDynAlloc) && (!arraySize.IsConst()) && (mCurMethodState->mCurScope->IsLooped(NULL)))
  8717. {
  8718. // Generate and check new size
  8719. BfArrayType* arrayType = CreateArrayType(type, arrayDim);
  8720. auto firstElementField = &arrayType->mFieldInstances.back();
  8721. int arrayClassSize = firstElementField->mDataOffset;
  8722. sizeValue = GetConstValue(arrayClassSize);
  8723. BfIRValue elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySize);
  8724. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, elementDataSize);
  8725. auto loadedPtr = _CreateDynAlloc(sizeValue, arrayType->mAlign);
  8726. auto typedVal = BfTypedValue(mBfIRBuilder->CreateBitCast(loadedPtr, mBfIRBuilder->MapType(arrayType)), arrayType);
  8727. if (!noDtorCall)
  8728. AddStackAlloc(typedVal, BfIRValue(), NULL, scopeData, false, true);
  8729. InitTypeInst(typedVal, scopeData, zeroMemory, sizeValue);
  8730. return typedVal.mValue;
  8731. }
  8732. else
  8733. {
  8734. BfArrayType* arrayType = CreateArrayType(type, arrayDim);
  8735. auto firstElementField = &arrayType->mFieldInstances.back();
  8736. if (!type->IsValuelessType())
  8737. {
  8738. int arrayClassSize = firstElementField->mDataOffset;
  8739. sizeValue = GetConstValue(arrayClassSize);
  8740. BfIRValue elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySize);
  8741. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, elementDataSize);
  8742. }
  8743. else
  8744. sizeValue = GetConstValue(arrayType->mInstSize);
  8745. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  8746. isDynAlloc = (isDynAlloc) || (!sizeValue.IsConst());
  8747. if (!isDynAlloc)
  8748. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  8749. else
  8750. {
  8751. MarkDynStack(scopeData);
  8752. SaveStackState(scopeData);
  8753. }
  8754. BfType* byteType = GetPrimitiveType(BfTypeCode_Int8);
  8755. auto allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(byteType), sizeValue);
  8756. if (!isDynAlloc)
  8757. mBfIRBuilder->ClearDebugLocation(allocaInst);
  8758. auto allocaBlock = mBfIRBuilder->GetInsertBlock();
  8759. mBfIRBuilder->SetAllocaAlignment(allocaInst, allocAlign);
  8760. BfTypedValue typedVal;
  8761. if (!isDynAlloc)
  8762. {
  8763. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRInitBlock);
  8764. typedVal = BfTypedValue(mBfIRBuilder->CreateBitCast(allocaInst, mBfIRBuilder->MapType(arrayType)), arrayType);
  8765. mBfIRBuilder->ClearDebugLocation(typedVal.mValue);
  8766. mBfIRBuilder->SetInsertPoint(prevBlock);
  8767. allocaBlock = mCurMethodState->mIRInitBlock;
  8768. }
  8769. else
  8770. typedVal = BfTypedValue(mBfIRBuilder->CreateBitCast(allocaInst, mBfIRBuilder->MapType(arrayType)), arrayType);
  8771. if (!noDtorCall)
  8772. AddStackAlloc(typedVal, BfIRValue(), NULL, scopeData, false, true, allocaBlock);
  8773. InitTypeInst(typedVal, scopeData, zeroMemory, sizeValue);
  8774. return typedVal.mValue;
  8775. }
  8776. }
  8777. }
  8778. else if (appendSizeValue)
  8779. {
  8780. // It may seem that we should check IsLooped against only the requested scope, BUT- if later on we perform
  8781. // a scoped alloc that crosses our boundary then we won't be able to reclaim the stack space, so we always
  8782. // use the "dynSize" version conservatively
  8783. if ((!isDynAlloc) && (!appendSizeValue.IsConst()) && (mCurMethodState->mCurScope->IsLooped(NULL)))
  8784. {
  8785. // Generate and check new size
  8786. sizeValue = GetConstValue(typeInstance->mInstSize);
  8787. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, appendSizeValue);
  8788. auto loadedPtr = _CreateDynAlloc(sizeValue, typeInstance->mAlign);
  8789. auto typedVal = BfTypedValue(mBfIRBuilder->CreateBitCast(loadedPtr, mBfIRBuilder->MapTypeInstPtr(typeInstance)), typeInstance);
  8790. if (!noDtorCall)
  8791. AddStackAlloc(typedVal, arraySize, NULL, scopeData, mCurMethodState->mInConditionalBlock, true);
  8792. InitTypeInst(typedVal, scopeData, zeroMemory, sizeValue);
  8793. return typedVal.mValue;
  8794. }
  8795. else // stack alloc, unlooped, with append
  8796. {
  8797. sizeValue = GetConstValue(typeInstance->mInstSize);
  8798. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, appendSizeValue);
  8799. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  8800. bool wasDynAlloc = isDynAlloc;
  8801. isDynAlloc = (isDynAlloc) || (!sizeValue.IsConst());
  8802. if (!isDynAlloc)
  8803. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  8804. else
  8805. {
  8806. MarkDynStack(scopeData);
  8807. SaveStackState(scopeData);
  8808. }
  8809. auto sbyteType = GetPrimitiveType(BfTypeCode_Int8);
  8810. auto allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(sbyteType), sizeValue);
  8811. if (!isDynAlloc)
  8812. {
  8813. mBfIRBuilder->ClearDebugLocation(allocaInst);
  8814. }
  8815. mBfIRBuilder->SetAllocaAlignment(allocaInst, allocAlign);
  8816. bool mayBeLarge = false;
  8817. if (sizeValue.IsConst())
  8818. {
  8819. auto constantInt = mBfIRBuilder->GetConstant(sizeValue);
  8820. if (constantInt->mInt64 >= 4096)
  8821. mayBeLarge = true;
  8822. }
  8823. else
  8824. mayBeLarge = true;
  8825. if (((type->IsObject() && (!mayBeLarge))) ||
  8826. // If we create a memset that can fill in backwards (or at least 4k chunked backward) then we can remove the '!mayBeLarge' cond
  8827. ((zeroMemory) && (!mayBeLarge)))
  8828. {
  8829. mBfIRBuilder->SetAllocaNoChkStkHint(allocaInst);
  8830. }
  8831. BfIRValue castedVal;
  8832. if (!isDynAlloc)
  8833. {
  8834. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRInitBlock);
  8835. castedVal = mBfIRBuilder->CreateBitCast(allocaInst, mBfIRBuilder->MapTypeInstPtr(typeInstance));
  8836. mBfIRBuilder->ClearDebugLocation(castedVal);
  8837. mBfIRBuilder->SetInsertPoint(prevBlock);
  8838. if (WantsLifetimes())
  8839. {
  8840. mBfIRBuilder->CreateLifetimeStart(allocaInst);
  8841. scopeData->mDeferredLifetimeEnds.push_back(allocaInst);
  8842. }
  8843. }
  8844. else
  8845. {
  8846. castedVal = mBfIRBuilder->CreateBitCast(allocaInst, mBfIRBuilder->MapTypeInstPtr(typeInstance));
  8847. }
  8848. auto typedVal = BfTypedValue(castedVal, typeInstance);
  8849. if (!noDtorCall)
  8850. {
  8851. bool doCondAlloca = false;
  8852. if (!IsTargetingBeefBackend())
  8853. doCondAlloca = !wasDynAlloc && isDynAlloc && mCurMethodState->mInConditionalBlock;
  8854. AddStackAlloc(typedVal, arraySize, NULL, scopeData, doCondAlloca, true);
  8855. }
  8856. InitTypeInst(typedVal, scopeData, zeroMemory, sizeValue, allocFlags);
  8857. return typedVal.mValue;
  8858. }
  8859. }
  8860. else // "Normal" stack alloc
  8861. {
  8862. BF_ASSERT(!sizeValue);
  8863. //TODO: If sizeValue is a constant then do this in the head IR builder
  8864. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  8865. if (!isLoopedAlloc)
  8866. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  8867. else
  8868. {
  8869. MarkDynStack(scopeData);
  8870. SaveStackState(scopeData);
  8871. }
  8872. auto allocaInst = mBfIRBuilder->CreateAlloca(allocType);
  8873. if (!isLoopedAlloc)
  8874. mBfIRBuilder->ClearDebugLocation(allocaInst);
  8875. mBfIRBuilder->SetAllocaAlignment(allocaInst, allocAlign);
  8876. bool mayBeLarge = allocSize >= 4096;
  8877. if (((typeInstance != NULL) && (typeInstance->IsObject()) && (!mayBeLarge)) ||
  8878. // If we create a memset that can fill in backwards (or at least 4k chunked backward) then we can remove the '!mayBeLarge' cond
  8879. ((zeroMemory) && (!mayBeLarge)))
  8880. {
  8881. // With an object, we know we will at least set the vdata pointer which will probe the start of the new address,
  8882. // and memset is always safe
  8883. mBfIRBuilder->SetAllocaNoChkStkHint(allocaInst);
  8884. }
  8885. auto typedVal = BfTypedValue(allocaInst, type);
  8886. if (!isLoopedAlloc)
  8887. {
  8888. mBfIRBuilder->ClearDebugLocation(allocaInst);
  8889. mBfIRBuilder->SetInsertPoint(prevBlock);
  8890. if (WantsLifetimes())
  8891. {
  8892. mBfIRBuilder->CreateLifetimeStart(allocaInst);
  8893. scopeData->mDeferredLifetimeEnds.push_back(allocaInst);
  8894. }
  8895. }
  8896. if (!noDtorCall)
  8897. AddStackAlloc(typedVal, BfIRValue(), NULL, scopeData, false, true);
  8898. if (typeInstance != NULL)
  8899. {
  8900. InitTypeInst(typedVal, scopeData, zeroMemory, GetConstValue(typeInstance->mInstSize));
  8901. }
  8902. else
  8903. {
  8904. mBfIRBuilder->CreateMemSet(allocaInst, GetConstValue8(0), GetConstValue(allocSize), allocAlign);
  8905. }
  8906. return allocaInst;
  8907. }
  8908. }
  8909. else if (arraySize)
  8910. {
  8911. if (isRawArrayAlloc)
  8912. {
  8913. sizeValue = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySize);
  8914. return AllocBytes(allocTarget.mRefNode, allocTarget, type, sizeValue, GetConstValue(allocAlign), allocFlags);
  8915. }
  8916. else
  8917. {
  8918. BfArrayType* arrayType = CreateArrayType(type, arrayDim);
  8919. typeInstance = arrayType;
  8920. BfIRValue arraySizeMinusOne = mBfIRBuilder->CreateSub(arraySize, GetConstValue(1));
  8921. BfIRValue elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySizeMinusOne);
  8922. appendSizeValue = elementDataSize;
  8923. if (!type->IsSizeAligned())
  8924. {
  8925. appendSizeValue = mBfIRBuilder->CreateAdd(appendSizeValue, GetConstValue(type->GetStride() - type->mSize));
  8926. }
  8927. }
  8928. }
  8929. if ((typeInstance != NULL) && (typeInstance->IsObject()))
  8930. {
  8931. auto vDataRef = GetClassVDataPtr(typeInstance);
  8932. BfIRValue result;
  8933. bool isResultInitialized = false;
  8934. int stackCount = mCompiler->mOptions.mAllocStackCount;
  8935. if (typeInstance->mTypeOptionsIdx != -1)
  8936. {
  8937. auto typeOptions = mSystem->GetTypeOptions(typeInstance->mTypeOptionsIdx);
  8938. stackCount = BfTypeOptions::Apply(stackCount, typeOptions->mAllocStackTraceDepth);
  8939. }
  8940. if (mIsComptimeModule)
  8941. stackCount = 0;
  8942. if (!sizeValue)
  8943. sizeValue = GetConstValue(typeInstance->mInstSize);
  8944. if (appendSizeValue)
  8945. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, appendSizeValue);
  8946. BfIRValue origSizeValue = sizeValue;
  8947. bool isAllocEx = hasCustomAllocator && (stackCount > 1);
  8948. if (isAllocEx)
  8949. {
  8950. auto prepareStackTraceMethod = GetInternalMethod("Dbg_PrepareStackTrace");
  8951. if (prepareStackTraceMethod)
  8952. {
  8953. SizedArray<BfIRValue, 2> irArgs;
  8954. irArgs.Add(sizeValue);
  8955. irArgs.Add(GetConstValue(stackCount));
  8956. auto addlBytes = mBfIRBuilder->CreateCall(prepareStackTraceMethod.mFunc, irArgs);
  8957. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, addlBytes);
  8958. }
  8959. }
  8960. if (allocTarget.mCustomAllocator)
  8961. {
  8962. auto customAlloc = allocTarget.mCustomAllocator.mType->ToTypeInstance();
  8963. // Use AllocObject if we have it, otherwise we just use AllocBytes further down
  8964. if ((customAlloc != NULL) && (GetRawMethodByName(customAlloc, "AllocObject", -1, true, true) != NULL))
  8965. {
  8966. auto classVDataType = ResolveTypeDef(mCompiler->mClassVDataTypeDef);
  8967. mBfIRBuilder->PopulateType(classVDataType);
  8968. auto typeInstType = ResolveTypeDef(mCompiler->mReflectTypeInstanceTypeDef)->ToTypeInstance();
  8969. mBfIRBuilder->PopulateType(typeInstType);
  8970. auto typePtrPtr = mBfIRBuilder->CreateInBoundsGEP(vDataRef, 0, 1); // mType
  8971. auto typePtr = mBfIRBuilder->CreateLoad(typePtrPtr);
  8972. auto typeInstPtr = mBfIRBuilder->CreateBitCast(typePtr, mBfIRBuilder->MapTypeInstPtr(typeInstType));
  8973. BfTypedValueExpression typedValueExpr;
  8974. typedValueExpr.Init(BfTypedValue(typeInstPtr, typeInstType));
  8975. typedValueExpr.mRefNode = allocTarget.mRefNode;
  8976. BfExprEvaluator exprEvaluator(this);
  8977. SizedArray<BfExpression*, 2> argExprs;
  8978. argExprs.push_back(&typedValueExpr);
  8979. BfTypedValueExpression sizeValueExpr;
  8980. sizeValueExpr.Init(BfTypedValue(sizeValue, GetPrimitiveType(BfTypeCode_IntPtr)));
  8981. sizeValueExpr.mRefNode = allocTarget.mRefNode;
  8982. argExprs.push_back(&sizeValueExpr);
  8983. BfSizedArray<BfExpression*> sizedArgExprs(argExprs);
  8984. BfResolvedArgs argValues(&sizedArgExprs);
  8985. exprEvaluator.ResolveArgValues(argValues);
  8986. exprEvaluator.mNoBind = true;
  8987. BfTypedValue allocResult = exprEvaluator.MatchMethod(allocTarget.mRefNode, NULL, allocTarget.mCustomAllocator, false, false, "AllocObject", argValues, BfMethodGenericArguments());
  8988. if (allocResult)
  8989. {
  8990. if ((allocResult.mType->IsVoidPtr()) || (allocResult.mType == mContext->mBfObjectType))
  8991. result = mBfIRBuilder->CreateBitCast(allocResult.mValue, mBfIRBuilder->MapType(typeInstance));
  8992. else
  8993. result = CastToValue(allocTarget.mRefNode, allocResult, typeInstance, BfCastFlags_Explicit);
  8994. isResultInitialized = true;
  8995. }
  8996. }
  8997. }
  8998. bool wasAllocated = false;
  8999. if (!result)
  9000. {
  9001. if (hasCustomAllocator)
  9002. result = AllocBytes(allocTarget.mRefNode, allocTarget, typeInstance, sizeValue, GetConstValue(typeInstance->mInstAlign), (BfAllocFlags)(BfAllocFlags_ZeroMemory | BfAllocFlags_NoDefaultToMalloc));
  9003. else if ((mCompiler->mOptions.mObjectHasDebugFlags) && (!mCompiler->mOptions.mDebugAlloc) && (!mIsComptimeModule))
  9004. {
  9005. SizedArray<BfIRValue, 4> llvmArgs;
  9006. llvmArgs.push_back(sizeValue);
  9007. auto irFunc = GetBuiltInFunc(BfBuiltInFuncType_Malloc);
  9008. result = mBfIRBuilder->CreateCall(irFunc, llvmArgs);
  9009. result = mBfIRBuilder->CreateBitCast(result, mBfIRBuilder->MapTypeInstPtr(typeInstance));
  9010. wasAllocated = true;
  9011. }
  9012. }
  9013. if (result)
  9014. {
  9015. if ((mCompiler->mOptions.mObjectHasDebugFlags) && (!mIsComptimeModule))
  9016. {
  9017. auto objectPtr = mBfIRBuilder->CreateBitCast(result, mBfIRBuilder->MapTypeInstPtr(mContext->mBfObjectType));
  9018. SizedArray<BfIRValue, 4> llvmArgs;
  9019. llvmArgs.push_back(objectPtr);
  9020. llvmArgs.push_back(origSizeValue);
  9021. llvmArgs.push_back(vDataRef);
  9022. auto objectCreatedMethod = GetInternalMethod(isAllocEx ?
  9023. (isResultInitialized ? "Dbg_ObjectCreatedEx" : "Dbg_ObjectAllocatedEx") :
  9024. (isResultInitialized ? "Dbg_ObjectCreated" : "Dbg_ObjectAllocated"));
  9025. mBfIRBuilder->CreateCall(objectCreatedMethod.mFunc, llvmArgs);
  9026. if (wasAllocated)
  9027. {
  9028. auto byteType = GetPrimitiveType(BfTypeCode_UInt8);
  9029. auto bytePtrType = CreatePointerType(byteType);
  9030. auto flagsPtr = mBfIRBuilder->CreateBitCast(result, mBfIRBuilder->MapType(bytePtrType));
  9031. auto flagsVal = mBfIRBuilder->CreateLoad(flagsPtr);
  9032. auto modifiedFlagsVal = mBfIRBuilder->CreateOr(flagsVal, mBfIRBuilder->CreateConst(BfTypeCode_UInt8, /*BF_OBJECTFLAG_ALLOCATED*/4));
  9033. mBfIRBuilder->CreateStore(modifiedFlagsVal, flagsPtr);
  9034. }
  9035. }
  9036. else
  9037. {
  9038. auto ptrType = mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr);
  9039. auto vDataPtr = mBfIRBuilder->CreateBitCast(vDataRef, ptrType);
  9040. auto vDataMemberPtr = mBfIRBuilder->CreateBitCast(result, mBfIRBuilder->GetPointerTo(ptrType));
  9041. mBfIRBuilder->CreateStore(vDataPtr, vDataMemberPtr);
  9042. }
  9043. }
  9044. else
  9045. {
  9046. if ((mBfIRBuilder->mIgnoreWrites) ||
  9047. ((mCompiler->mIsResolveOnly) && (!mIsComptimeModule)))
  9048. {
  9049. if (mBfIRBuilder->mIgnoreWrites)
  9050. {
  9051. return GetDefaultValue(typeInstance);
  9052. }
  9053. else
  9054. {
  9055. // Fake with alloca
  9056. mBfIRBuilder->PopulateType(typeInstance);
  9057. return mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapTypeInst(typeInstance));
  9058. }
  9059. }
  9060. auto classVDataType = ResolveTypeDef(mCompiler->mClassVDataTypeDef);
  9061. auto vData = mBfIRBuilder->CreateBitCast(vDataRef, mBfIRBuilder->MapTypeInstPtr(classVDataType->ToTypeInstance()));
  9062. if ((mCompiler->mOptions.mObjectHasDebugFlags) && (!mIsComptimeModule))
  9063. {
  9064. SizedArray<BfIRValue, 4> llvmArgs;
  9065. llvmArgs.push_back(vData);
  9066. llvmArgs.push_back(sizeValue);
  9067. llvmArgs.push_back(GetConstValue(typeInstance->mAlign));
  9068. llvmArgs.push_back(GetConstValue(stackCount));
  9069. llvmArgs.push_back(GetConstValue(allocFlags, GetPrimitiveType(BfTypeCode_Int8)));
  9070. auto moduleMethodInstance = GetInternalMethod("Dbg_ObjectAlloc", 5);
  9071. BfIRValue objectVal = mBfIRBuilder->CreateCall(moduleMethodInstance.mFunc, llvmArgs);
  9072. result = mBfIRBuilder->CreateBitCast(objectVal, mBfIRBuilder->MapType(typeInstance));
  9073. }
  9074. else
  9075. {
  9076. SizedArray<BfIRValue, 4> llvmArgs;
  9077. llvmArgs.push_back(sizeValue);
  9078. BfIRFunction irFunc;
  9079. if ((mCompiler->mOptions.mDebugAlloc) && (!mIsComptimeModule))
  9080. {
  9081. auto moduleMethodInstance = GetInternalMethod("Dbg_RawObjectAlloc", 1);
  9082. irFunc = moduleMethodInstance.mFunc;
  9083. }
  9084. if (!irFunc)
  9085. irFunc = GetBuiltInFunc(BfBuiltInFuncType_Malloc);
  9086. BfIRValue objectVal = mBfIRBuilder->CreateCall(irFunc, llvmArgs);
  9087. auto objResult = mBfIRBuilder->CreateBitCast(objectVal, mBfIRBuilder->MapType(mContext->mBfObjectType, BfIRPopulateType_Full));
  9088. auto vdataPtr = mBfIRBuilder->CreateInBoundsGEP(objResult, 0, 0);
  9089. if (mIsComptimeModule)
  9090. {
  9091. vdataPtr = mBfIRBuilder->CreateBitCast(vdataPtr, mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapTypeInstPtr(classVDataType->ToTypeInstance())));
  9092. }
  9093. mBfIRBuilder->CreateStore(vData, vdataPtr);
  9094. result = mBfIRBuilder->CreateBitCast(objectVal, mBfIRBuilder->MapType(typeInstance));
  9095. }
  9096. }
  9097. if ((zeroMemory) && (arraySize))
  9098. {
  9099. BfArrayType* arrayType = CreateArrayType(type, arrayDim);
  9100. typeInstance = arrayType;
  9101. auto firstElementField = &arrayType->mFieldInstances.back();
  9102. int arrayClassSize = firstElementField->mDataOffset;
  9103. BfIRValue elementDataSize;
  9104. bool skipZero = false;
  9105. if (arraySize.IsConst())
  9106. {
  9107. BfIRValue arraySizeMinusOne = mBfIRBuilder->CreateSub(arraySize, GetConstValue(1));
  9108. elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySizeMinusOne);
  9109. elementDataSize = mBfIRBuilder->CreateAdd(elementDataSize, GetConstValue(type->mSize));
  9110. auto constVal = mBfIRBuilder->GetConstant(elementDataSize);
  9111. if (constVal->mInt64 <= 0)
  9112. skipZero = true;
  9113. }
  9114. else
  9115. {
  9116. // For non const, don't use an unpadded last element - saves us checking against negative numbers going into memset for the zero-length case
  9117. elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySize);
  9118. }
  9119. if (!skipZero)
  9120. {
  9121. auto i8Type = GetPrimitiveType(BfTypeCode_Int8);
  9122. auto ptrType = CreatePointerType(i8Type);
  9123. auto ptrVal = mBfIRBuilder->CreateBitCast(result, mBfIRBuilder->MapType(ptrType));
  9124. ptrVal = mBfIRBuilder->CreateInBoundsGEP(ptrVal, arrayClassSize);
  9125. mBfIRBuilder->CreateMemSet(ptrVal, GetConstValue8(0), elementDataSize, type->mAlign);
  9126. appendSizeValue = elementDataSize;
  9127. }
  9128. }
  9129. return result;
  9130. }
  9131. else
  9132. {
  9133. if (!sizeValue)
  9134. sizeValue = GetConstValue(allocSize);
  9135. return AllocBytes(allocTarget.mRefNode, allocTarget, type, sizeValue, GetConstValue(allocAlign), zeroMemory ? BfAllocFlags_ZeroMemory : BfAllocFlags_None);
  9136. }
  9137. }
  9138. void BfModule::ValidateAllocation(BfType* type, BfAstNode* refNode)
  9139. {
  9140. if ((type == NULL) || (refNode == NULL))
  9141. return;
  9142. auto typeInstance = type->ToTypeInstance();
  9143. if ((typeInstance != NULL) && (typeInstance->mTypeDef->mIsOpaque))
  9144. Fail(StrFormat("Unable to allocate opaque type '%s'", TypeToString(type).c_str()), refNode);
  9145. }
  9146. void BfModule::EmitAppendAlign(int align, int sizeMultiple)
  9147. {
  9148. if (align <= 1)
  9149. return;
  9150. if (sizeMultiple == 0)
  9151. sizeMultiple = align;
  9152. if ((mCurMethodState->mCurAppendAlign != 0) && (mCurMethodState->mCurAppendAlign % align != 0))
  9153. {
  9154. if (!IsAllocatorAligned())
  9155. {
  9156. // Don't align
  9157. }
  9158. else if (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_Ctor)
  9159. {
  9160. auto localVar = mCurMethodState->GetRootMethodState()->mLocals[1];
  9161. BF_ASSERT(localVar->mName == "__appendIdx");
  9162. auto appendIdxVal = BfTypedValue(localVar->mValue, localVar->mResolvedType, true);
  9163. BfIRValue appendCurIdx = mBfIRBuilder->CreateLoad(appendIdxVal.mValue);
  9164. if (align > 1)
  9165. {
  9166. appendCurIdx = mBfIRBuilder->CreateAdd(appendCurIdx, GetConstValue(align - 1));
  9167. appendCurIdx = mBfIRBuilder->CreateAnd(appendCurIdx, GetConstValue(~(align - 1)));
  9168. }
  9169. mBfIRBuilder->CreateStore(appendCurIdx, appendIdxVal.mValue);
  9170. }
  9171. else
  9172. {
  9173. BF_ASSERT(mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend);
  9174. BfIRValue appendCurIdxPtr = mCurMethodState->mRetVal.mValue;
  9175. BfIRValue appendCurIdx = mBfIRBuilder->CreateLoad(appendCurIdxPtr);
  9176. appendCurIdx = mBfIRBuilder->CreateAdd(appendCurIdx, GetConstValue(align - 1));
  9177. appendCurIdx = mBfIRBuilder->CreateAnd(appendCurIdx, GetConstValue(~(align - 1)));
  9178. mBfIRBuilder->CreateStore(appendCurIdx, appendCurIdxPtr);
  9179. }
  9180. }
  9181. if (mCurMethodState->mCurAppendAlign == 0)
  9182. mCurMethodState->mCurAppendAlign = sizeMultiple;
  9183. else
  9184. {
  9185. if (sizeMultiple % align == 0)
  9186. mCurMethodState->mCurAppendAlign = align;
  9187. else
  9188. mCurMethodState->mCurAppendAlign = sizeMultiple % align;
  9189. }
  9190. }
  9191. BfIRValue BfModule::AppendAllocFromType(BfType* type, BfIRValue appendSizeValue, int appendAllocAlign, BfIRValue arraySize, int arrayDim, bool isRawArrayAlloc, bool zeroMemory)
  9192. {
  9193. auto localVar = mCurMethodState->GetRootMethodState()->mLocals[1];
  9194. BF_ASSERT(localVar->mName == "__appendIdx");
  9195. BfTypedValue appendIdxVal(localVar->mValue, localVar->mResolvedType, true);
  9196. BfIRValue retValue;
  9197. BfTypeInstance* retTypeInstance = NULL;
  9198. auto intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  9199. auto voidPtrType = GetPrimitiveType(BfTypeCode_NullPtr);
  9200. if (arraySize)
  9201. {
  9202. if (isRawArrayAlloc)
  9203. {
  9204. EmitAppendAlign(type->mAlign);
  9205. BfPointerType* ptrType = CreatePointerType(type);
  9206. BfIRValue sizeValue = mBfIRBuilder->CreateMul(GetConstValue(type->mSize), arraySize);
  9207. auto curIdxVal = mBfIRBuilder->CreateLoad(appendIdxVal.mValue);
  9208. if (mSystem->mPtrSize != 4)
  9209. sizeValue = mBfIRBuilder->CreateNumericCast(sizeValue, true, (intPtrType->mSize == 4) ? BfTypeCode_Int32 : BfTypeCode_Int64);
  9210. auto newIdxVal = mBfIRBuilder->CreateAdd(curIdxVal, sizeValue);
  9211. mBfIRBuilder->CreateStore(newIdxVal, appendIdxVal.mValue);
  9212. if (zeroMemory)
  9213. {
  9214. auto ptr = mBfIRBuilder->CreateIntToPtr(curIdxVal, mBfIRBuilder->MapType(voidPtrType));
  9215. mBfIRBuilder->CreateMemSet(ptr, GetConstValue8(0), sizeValue, type->mAlign);
  9216. }
  9217. return mBfIRBuilder->CreateIntToPtr(curIdxVal, mBfIRBuilder->MapType(ptrType));
  9218. }
  9219. else
  9220. {
  9221. BfArrayType* arrayType = CreateArrayType(type, arrayDim);
  9222. EmitAppendAlign(arrayType->mAlign, type->mSize);
  9223. auto firstElementField = &arrayType->mFieldInstances.back();
  9224. int arrayClassSize = arrayType->mInstSize - firstElementField->mDataSize;
  9225. BfIRValue sizeValue = GetConstValue(arrayClassSize);
  9226. BfIRValue elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->mSize), arraySize);
  9227. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, elementDataSize);
  9228. auto curIdxVal = mBfIRBuilder->CreateLoad(appendIdxVal.mValue);
  9229. if (mSystem->mPtrSize != 4)
  9230. sizeValue = mBfIRBuilder->CreateNumericCast(sizeValue, true, (intPtrType->mSize == 4) ? BfTypeCode_Int32 : BfTypeCode_Int64);
  9231. auto newIdxVal = mBfIRBuilder->CreateAdd(curIdxVal, sizeValue);
  9232. mBfIRBuilder->CreateStore(newIdxVal, appendIdxVal.mValue);
  9233. if (zeroMemory)
  9234. {
  9235. // Only zero out the actual elements
  9236. int dataOffset = arrayType->mFieldInstances.back().mDataOffset;
  9237. auto newOffset = mBfIRBuilder->CreateAdd(curIdxVal, GetConstValue(dataOffset));
  9238. auto newSize = mBfIRBuilder->CreateSub(sizeValue, GetConstValue(dataOffset));
  9239. auto ptr = mBfIRBuilder->CreateIntToPtr(newOffset, mBfIRBuilder->MapType(voidPtrType));
  9240. mBfIRBuilder->CreateMemSet(ptr, GetConstValue8(0), newSize, type->mAlign);
  9241. }
  9242. retTypeInstance = arrayType;
  9243. retValue = mBfIRBuilder->CreateIntToPtr(curIdxVal, mBfIRBuilder->MapType(arrayType));
  9244. }
  9245. }
  9246. else
  9247. {
  9248. auto typeInst = type->ToTypeInstance();
  9249. BfIRValue sizeValue;
  9250. BfIRType toType;
  9251. if (typeInst != NULL)
  9252. {
  9253. mBfIRBuilder->PopulateType(typeInst);
  9254. if (typeInst->WantsGCMarking())
  9255. mCurTypeInstance->mHasAppendWantMark = true;
  9256. EmitAppendAlign(typeInst->mInstAlign, typeInst->mInstSize);
  9257. sizeValue = GetConstValue(typeInst->mInstSize);
  9258. toType = mBfIRBuilder->MapTypeInstPtr(typeInst);
  9259. }
  9260. else
  9261. {
  9262. EmitAppendAlign(type->mAlign, type->mSize);
  9263. sizeValue = GetConstValue(type->mSize);
  9264. auto toPtrType = CreatePointerType(type);
  9265. toType = mBfIRBuilder->MapType(toPtrType);
  9266. }
  9267. auto curIdxVal = mBfIRBuilder->CreateLoad(appendIdxVal.mValue);
  9268. auto newIdxVal = mBfIRBuilder->CreateAdd(curIdxVal, sizeValue);
  9269. mBfIRBuilder->CreateStore(newIdxVal, appendIdxVal.mValue);
  9270. retTypeInstance = typeInst;
  9271. retValue = mBfIRBuilder->CreateIntToPtr(curIdxVal, toType);
  9272. if ((typeInst != NULL) && (typeInst->WantsGCMarking()) && (mCompiler->mOptions.mDebugAlloc))
  9273. {
  9274. auto curThis = GetThis();
  9275. auto thisObj = Cast(mCurMethodInstance->mMethodDef->GetRefNode(), curThis, mContext->mBfObjectType);
  9276. if (typeInst->IsObject())
  9277. {
  9278. auto appendedObj = Cast(mCurMethodInstance->mMethodDef->GetRefNode(), BfTypedValue(retValue, typeInst), mContext->mBfObjectType);
  9279. BfModuleMethodInstance allocMethod = GetInternalMethod("Dbg_ObjectAppended", 2);
  9280. SizedArray<BfIRValue, 2> llvmArgs;
  9281. llvmArgs.push_back(thisObj.mValue);
  9282. llvmArgs.push_back(appendedObj.mValue);
  9283. mBfIRBuilder->CreateCall(allocMethod.mFunc, llvmArgs);
  9284. }
  9285. else
  9286. {
  9287. // Raw
  9288. BfIRValue allocPtr = mBfIRBuilder->CreateBitCast(retValue, mBfIRBuilder->MapType(voidPtrType));
  9289. BfIRValue allocData = GetDbgRawAllocData(type);
  9290. BfModuleMethodInstance allocMethod = GetInternalMethod("Dbg_RawAppended", 3);
  9291. SizedArray<BfIRValue, 3> llvmArgs;
  9292. llvmArgs.push_back(thisObj.mValue);
  9293. llvmArgs.push_back(allocPtr);
  9294. llvmArgs.push_back(allocData);
  9295. mBfIRBuilder->CreateCall(allocMethod.mFunc, llvmArgs);
  9296. }
  9297. }
  9298. }
  9299. if ((retTypeInstance != NULL) && (retTypeInstance->IsObject()))
  9300. {
  9301. mBfIRBuilder->PopulateType(retTypeInstance);
  9302. auto int8Type = mBfIRBuilder->GetPrimitiveType(BfTypeCode_Int8);
  9303. auto ptrType = mBfIRBuilder->GetPointerTo(int8Type);
  9304. auto ptrPtrType = mBfIRBuilder->GetPointerTo(ptrType);
  9305. auto curThis = GetThis();
  9306. BfIRValue newFlags;
  9307. if ((mCompiler->mOptions.mObjectHasDebugFlags) && (!mIsComptimeModule))
  9308. {
  9309. auto thisFlagsPtr = mBfIRBuilder->CreateBitCast(curThis.mValue, ptrType);
  9310. auto thisFlags = mBfIRBuilder->CreateLoad(thisFlagsPtr);
  9311. auto maskedThisFlags = mBfIRBuilder->CreateAnd(thisFlags, GetConstValue8(BfObjectFlag_StackAlloc)); // Take 'stack' flag from 'this'
  9312. newFlags = mBfIRBuilder->CreateOr(maskedThisFlags, GetConstValue8(BfObjectFlag_AppendAlloc));
  9313. }
  9314. auto vObjectAddr = mBfIRBuilder->CreateInBoundsGEP(retValue, 0, 0);
  9315. auto vDataRef = CreateClassVDataGlobal(retTypeInstance);
  9316. auto destAddr = mBfIRBuilder->CreateBitCast(vObjectAddr, ptrPtrType);
  9317. auto srcVal = mBfIRBuilder->CreateBitCast(vDataRef, ptrType);
  9318. mBfIRBuilder->CreateStore(srcVal, destAddr);
  9319. if ((mCompiler->mOptions.mObjectHasDebugFlags) && (!mIsComptimeModule))
  9320. {
  9321. auto flagsPtr = mBfIRBuilder->CreateBitCast(destAddr, ptrType);
  9322. mBfIRBuilder->CreateStore(newFlags, flagsPtr);
  9323. }
  9324. }
  9325. if (appendSizeValue)
  9326. {
  9327. EmitAppendAlign(appendAllocAlign);
  9328. auto curIdxVal = mBfIRBuilder->CreateLoad(appendIdxVal.mValue);
  9329. auto newIdxVal = mBfIRBuilder->CreateAdd(curIdxVal, appendSizeValue);
  9330. mBfIRBuilder->CreateStore(newIdxVal, appendIdxVal.mValue);
  9331. }
  9332. return retValue;
  9333. }
  9334. bool BfModule::IsOptimized()
  9335. {
  9336. if (mProject == NULL)
  9337. return false;
  9338. if (mIsComptimeModule)
  9339. return false;
  9340. int optLevel = GetModuleOptions().mOptLevel;
  9341. return (optLevel >= BfOptLevel_O1) && (optLevel <= BfOptLevel_O3);
  9342. }
  9343. bool BfModule::IsTargetingBeefBackend()
  9344. {
  9345. if (mProject == NULL)
  9346. return true;
  9347. return GetModuleOptions().mOptLevel == BfOptLevel_OgPlus;
  9348. }
  9349. bool BfModule::WantsLifetimes()
  9350. {
  9351. if (mBfIRBuilder->mIgnoreWrites)
  9352. return false;
  9353. if ((mIsComptimeModule) && (mBfIRBuilder->HasDebugLocation()))
  9354. return true;
  9355. else if (mProject == NULL)
  9356. return false;
  9357. return GetModuleOptions().mOptLevel == BfOptLevel_OgPlus;
  9358. }
  9359. bool BfModule::HasCompiledOutput()
  9360. {
  9361. return (!mSystem->mIsResolveOnly) && (mGeneratesCode) && (!mIsComptimeModule);
  9362. }
  9363. bool BfModule::HasExecutedOutput()
  9364. {
  9365. return ((!mSystem->mIsResolveOnly) && (mGeneratesCode)) || (mIsComptimeModule);
  9366. }
  9367. // We will skip the object access check for any occurrences of this value
  9368. void BfModule::SkipObjectAccessCheck(BfTypedValue typedVal)
  9369. {
  9370. if ((mBfIRBuilder->mIgnoreWrites) || (!typedVal.mType->IsObjectOrInterface()) || (mCurMethodState == NULL) || (mCurMethodState->mIgnoreObjectAccessCheck))
  9371. return;
  9372. if ((!mCompiler->mOptions.mObjectHasDebugFlags) || (mIsComptimeModule))
  9373. return;
  9374. if ((typedVal.mValue.mFlags & BfIRValueFlags_Value) == 0)
  9375. return;
  9376. mCurMethodState->mSkipObjectAccessChecks.Add(typedVal.mValue.mId);
  9377. }
  9378. bool BfModule::WantsObjectAccessCheck(BfType* type)
  9379. {
  9380. if ((mBfIRBuilder->mIgnoreWrites) || (!type->IsObjectOrInterface()) || (mCurMethodState == NULL) || (mCurMethodState->mIgnoreObjectAccessCheck))
  9381. return false;
  9382. if ((!mCompiler->mOptions.mObjectHasDebugFlags) || (mIsComptimeModule))
  9383. return false;
  9384. bool emitObjectAccessCheck = mCompiler->mOptions.mEmitObjectAccessCheck;
  9385. auto typeOptions = GetTypeOptions();
  9386. if (typeOptions != NULL)
  9387. emitObjectAccessCheck = typeOptions->Apply(emitObjectAccessCheck, BfOptionFlags_EmitObjectAccessCheck);
  9388. if (!emitObjectAccessCheck)
  9389. return false;
  9390. return true;
  9391. }
  9392. void BfModule::EmitObjectAccessCheck(BfTypedValue typedVal)
  9393. {
  9394. if ((mBfIRBuilder->mIgnoreWrites) || (!typedVal.mType->IsObjectOrInterface()) || (mCurMethodState == NULL) || (mCurMethodState->mIgnoreObjectAccessCheck))
  9395. return;
  9396. if ((!mCompiler->mOptions.mObjectHasDebugFlags) || (mIsComptimeModule))
  9397. return;
  9398. if (typedVal.mValue.IsConst())
  9399. {
  9400. int stringIdx = GetStringPoolIdx(typedVal.mValue, mBfIRBuilder);
  9401. if (stringIdx != -1)
  9402. return;
  9403. auto constant = mBfIRBuilder->GetConstant(typedVal.mValue);
  9404. if (constant->mTypeCode == BfTypeCode_NullPtr)
  9405. return;
  9406. if (constant->mConstType == BfConstType_BitCastNull)
  9407. return;
  9408. }
  9409. bool emitObjectAccessCheck = mCompiler->mOptions.mEmitObjectAccessCheck;
  9410. auto typeOptions = GetTypeOptions();
  9411. if (typeOptions != NULL)
  9412. emitObjectAccessCheck = typeOptions->Apply(emitObjectAccessCheck, BfOptionFlags_EmitObjectAccessCheck);
  9413. if (!emitObjectAccessCheck)
  9414. return;
  9415. if ((typedVal.mValue.mFlags & BfIRValueFlags_Value) != 0)
  9416. {
  9417. if (mCurMethodState->mSkipObjectAccessChecks.Contains(typedVal.mValue.mId))
  9418. return;
  9419. }
  9420. if (typedVal.IsAddr())
  9421. typedVal = LoadValue(typedVal);
  9422. mBfIRBuilder->CreateObjectAccessCheck(typedVal.mValue, !IsOptimized());
  9423. }
  9424. bool BfModule::WantsDebugHelpers()
  9425. {
  9426. if (mBfIRBuilder->mIgnoreWrites)
  9427. return false;
  9428. if (mIsComptimeModule)
  9429. {
  9430. // Always add
  9431. }
  9432. else if ((mProject == NULL) || (!mHasFullDebugInfo) || (IsOptimized()) || (mCompiler->mOptions.mOmitDebugHelpers))
  9433. return false;
  9434. return true;
  9435. }
  9436. void BfModule::EmitEnsureInstructionAt()
  9437. {
  9438. if (!WantsDebugHelpers())
  9439. return;
  9440. mBfIRBuilder->CreateEnsureInstructionAt();
  9441. }
  9442. void BfModule::EmitDynamicCastCheck(const BfTypedValue& targetValue, BfType* targetType, BfIRBlock trueBlock, BfIRBlock falseBlock, bool nullSucceeds)
  9443. {
  9444. if (mBfIRBuilder->mIgnoreWrites)
  9445. return; // Nothing needed here
  9446. auto irb = mBfIRBuilder;
  9447. auto checkBB = irb->CreateBlock("as.check");
  9448. auto isNull = irb->CreateIsNull(targetValue.mValue);
  9449. mBfIRBuilder->CreateCondBr(isNull, nullSucceeds ? trueBlock : falseBlock, checkBB);
  9450. if (mIsComptimeModule)
  9451. {
  9452. AddBasicBlock(checkBB);
  9453. auto callResult = mBfIRBuilder->Comptime_DynamicCastCheck(targetValue.mValue, targetType->mTypeId, mBfIRBuilder->MapType(mContext->mBfObjectType));
  9454. auto cmpResult = mBfIRBuilder->CreateCmpNE(callResult, GetDefaultValue(mContext->mBfObjectType));
  9455. irb->CreateCondBr(cmpResult, trueBlock, falseBlock);
  9456. return;
  9457. }
  9458. auto intType = GetPrimitiveType(BfTypeCode_IntPtr);
  9459. auto intPtrType = CreatePointerType(intType);
  9460. auto intPtrPtrType = CreatePointerType(intPtrType);
  9461. auto int32Type = GetPrimitiveType(BfTypeCode_Int32);
  9462. auto int32PtrType = CreatePointerType(int32Type);
  9463. auto typeTypeInstance = ResolveTypeDef(mCompiler->mReflectTypeInstanceTypeDef)->ToTypeInstance();
  9464. if (mCompiler->mOptions.mAllowHotSwapping)
  9465. {
  9466. BfExprEvaluator exprEvaluator(this);
  9467. AddBasicBlock(checkBB);
  9468. auto objectParam = mBfIRBuilder->CreateBitCast(targetValue.mValue, mBfIRBuilder->MapType(mContext->mBfObjectType));
  9469. auto moduleMethodInstance = GetMethodByName(mContext->mBfObjectType, targetType->IsInterface() ? "DynamicCastToInterface" : "DynamicCastToTypeId");
  9470. SizedArray<BfIRValue, 4> irArgs;
  9471. irArgs.push_back(objectParam);
  9472. irArgs.push_back(GetConstValue32(targetType->mTypeId));
  9473. auto callResult = exprEvaluator.CreateCall(NULL, moduleMethodInstance.mMethodInstance, moduleMethodInstance.mFunc, false, irArgs);
  9474. auto cmpResult = mBfIRBuilder->CreateCmpNE(callResult.mValue, GetDefaultValue(callResult.mType));
  9475. irb->CreateCondBr(cmpResult, trueBlock, falseBlock);
  9476. }
  9477. else
  9478. {
  9479. AddBasicBlock(checkBB);
  9480. BfIRValue vDataPtr = irb->CreateBitCast(targetValue.mValue, irb->MapType(intPtrType));
  9481. vDataPtr = irb->CreateLoad(vDataPtr);
  9482. if ((mCompiler->mOptions.mObjectHasDebugFlags) && (!mIsComptimeModule))
  9483. vDataPtr = irb->CreateAnd(vDataPtr, irb->CreateConst(BfTypeCode_IntPtr, (uint64)~0xFFULL));
  9484. if (targetType->IsInterface())
  9485. {
  9486. auto targetTypeInst = targetType->ToTypeInstance();
  9487. AddDependency(targetType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ExprTypeReference);
  9488. // Skip past mType, but since a 'GetDynCastVDataCount()' data is included in the sSlotOfs, we need to remove that
  9489. //int inheritanceIdOfs = mSystem->mPtrSize - (mCompiler->GetDynCastVDataCount())*4;
  9490. //vDataPtr = irb->CreateAdd(vDataPtr, irb->CreateConst(BfTypeCode_IntPtr, inheritanceIdOfs));
  9491. vDataPtr = irb->CreateAdd(vDataPtr, irb->GetConfigConst(BfIRConfigConst_DynSlotOfs, BfTypeCode_IntPtr));
  9492. BfIRValue slotOfs = GetInterfaceSlotNum(targetType->ToTypeInstance());
  9493. BfIRValue slotByteOfs = irb->CreateMul(slotOfs, irb->CreateConst(BfTypeCode_Int32, 4));
  9494. slotByteOfs = irb->CreateNumericCast(slotByteOfs, false, BfTypeCode_IntPtr);
  9495. vDataPtr = irb->CreateAdd(vDataPtr, slotByteOfs);
  9496. vDataPtr = irb->CreateIntToPtr(vDataPtr, irb->MapType(int32PtrType));
  9497. BfIRValue typeId = irb->CreateLoad(vDataPtr);
  9498. BfIRValue cmpResult = irb->CreateCmpEQ(typeId, irb->CreateConst(BfTypeCode_Int32, targetType->mTypeId));
  9499. irb->CreateCondBr(cmpResult, trueBlock, falseBlock);
  9500. }
  9501. else
  9502. {
  9503. if (!targetType->IsTypeInstance())
  9504. targetType = GetWrappedStructType(targetType);
  9505. AddDependency(targetType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ExprTypeReference);
  9506. int inheritanceIdOfs = mSystem->mPtrSize * mCompiler->GetVDataPrefixDataCount();
  9507. vDataPtr = irb->CreateAdd(vDataPtr, irb->CreateConst(BfTypeCode_IntPtr, inheritanceIdOfs));
  9508. vDataPtr = irb->CreateIntToPtr(vDataPtr, irb->MapType(int32PtrType));
  9509. BfIRValue objInheritanceId = irb->CreateLoad(vDataPtr);
  9510. BfIRValue typeDataRef = CreateTypeDataRef(targetType);
  9511. BfIRValue typeInstDataRef = irb->CreateBitCast(typeDataRef, irb->MapType(typeTypeInstance, BfIRPopulateType_Full));
  9512. auto fieldInst = &typeTypeInstance->mFieldInstances[9];
  9513. BF_ASSERT(fieldInst->GetFieldDef()->mName == "mInheritanceId");
  9514. BfIRValue gepValue = irb->CreateInBoundsGEP(typeInstDataRef, 0, fieldInst->mDataIdx);
  9515. BfIRValue wantInheritanceId = irb->CreateLoad(gepValue);
  9516. fieldInst = &typeTypeInstance->mFieldInstances[10];
  9517. BF_ASSERT(fieldInst->GetFieldDef()->mName == "mInheritanceCount");
  9518. gepValue = irb->CreateInBoundsGEP(typeInstDataRef, 0, fieldInst->mDataIdx);
  9519. BfIRValue inheritanceCount = irb->CreateLoad(gepValue);
  9520. BfIRValue idDiff = irb->CreateSub(objInheritanceId, wantInheritanceId);
  9521. BfIRValue cmpResult = irb->CreateCmpLTE(idDiff, inheritanceCount, false);
  9522. irb->CreateCondBr(cmpResult, trueBlock, falseBlock);
  9523. }
  9524. }
  9525. }
  9526. void BfModule::EmitDynamicCastCheck(BfTypedValue typedVal, BfType* type, bool allowNull)
  9527. {
  9528. if (mBfIRBuilder->mIgnoreWrites)
  9529. return;
  9530. bool emitDynamicCastCheck = mCompiler->mOptions.mEmitDynamicCastCheck;
  9531. auto typeOptions = GetTypeOptions();
  9532. if (typeOptions != NULL)
  9533. emitDynamicCastCheck = typeOptions->Apply(emitDynamicCastCheck, BfOptionFlags_EmitDynamicCastCheck);
  9534. if (emitDynamicCastCheck)
  9535. {
  9536. int wantTypeId = 0;
  9537. if (!type->IsGenericParam())
  9538. wantTypeId = type->mTypeId;
  9539. BfIRBlock failBlock = mBfIRBuilder->CreateBlock("dynFail");
  9540. BfIRBlock endBlock = mBfIRBuilder->CreateBlock("dynEnd");
  9541. EmitDynamicCastCheck(typedVal, type, endBlock, failBlock, allowNull ? true : false);
  9542. AddBasicBlock(failBlock);
  9543. if (mIsComptimeModule)
  9544. {
  9545. mBfIRBuilder->Comptime_Error(CeErrorKind_ObjectDynCheckFailed);
  9546. }
  9547. else
  9548. {
  9549. SizedArray<BfIRValue, 8> llvmArgs;
  9550. auto bitAddr = mBfIRBuilder->CreateBitCast(typedVal.mValue, mBfIRBuilder->MapType(mContext->mBfObjectType));
  9551. llvmArgs.push_back(bitAddr);
  9552. llvmArgs.push_back(GetConstValue32(wantTypeId));
  9553. auto objDynCheck = GetInternalMethod("ObjectDynCheckFailed");
  9554. BF_ASSERT(objDynCheck);
  9555. if (objDynCheck)
  9556. {
  9557. auto callInst = mBfIRBuilder->CreateCall(objDynCheck.mFunc, llvmArgs);
  9558. }
  9559. }
  9560. mBfIRBuilder->CreateBr(endBlock);
  9561. AddBasicBlock(endBlock);
  9562. }
  9563. }
  9564. BfTypedValue BfModule::BoxValue(BfAstNode* srcNode, BfTypedValue typedVal, BfType* toType, const BfAllocTarget& allocTarget, BfCastFlags castFlags)
  9565. {
  9566. bool callDtor = (castFlags & BfCastFlags_NoBoxDtor) == 0;
  9567. bool wantConst = ((castFlags & BfCastFlags_WantsConst) != 0) && (typedVal.mValue.IsConst());
  9568. if ((mBfIRBuilder->mIgnoreWrites) && (!wantConst))
  9569. {
  9570. if (toType == mContext->mBfObjectType)
  9571. return BfTypedValue(mBfIRBuilder->GetFakeVal(), toType);
  9572. if (toType->IsBoxed())
  9573. {
  9574. BfBoxedType* boxedType = (BfBoxedType*)toType;
  9575. if (boxedType->mElementType->IsGenericParam())
  9576. {
  9577. if (typedVal.mType == boxedType->mElementType)
  9578. return BfTypedValue(mBfIRBuilder->GetFakeVal(), toType);
  9579. else
  9580. return BfTypedValue();
  9581. }
  9582. }
  9583. }
  9584. BP_ZONE("BoxValue");
  9585. BfTypeInstance* fromStructTypeInstance = typedVal.mType->ToTypeInstance();
  9586. if (typedVal.mType->IsNullable())
  9587. {
  9588. typedVal = MakeAddressable(typedVal);
  9589. auto innerType = typedVal.mType->GetUnderlyingType();
  9590. if (!innerType->IsValueType())
  9591. {
  9592. if (!mIgnoreErrors)
  9593. Fail("Only value types can be boxed", srcNode);
  9594. return BfTypedValue();
  9595. }
  9596. auto boxedType = CreateBoxedType(innerType);
  9597. auto resultType = toType;
  9598. if (resultType == NULL)
  9599. resultType = boxedType;
  9600. if (mBfIRBuilder->mIgnoreWrites)
  9601. return BfTypedValue(mBfIRBuilder->GetFakeVal(), resultType);
  9602. auto prevBB = mBfIRBuilder->GetInsertBlock();
  9603. auto boxBB = mBfIRBuilder->CreateBlock("boxedN.notNull");
  9604. auto endBB = mBfIRBuilder->CreateBlock("boxedN.end");
  9605. mBfIRBuilder->PopulateType(typedVal.mType);
  9606. auto hasValueAddr = mBfIRBuilder->CreateInBoundsGEP(typedVal.mValue, 0, innerType->IsValuelessType() ? 1 : 2); // has_value
  9607. auto hasValue = mBfIRBuilder->CreateLoad(hasValueAddr);
  9608. mBfIRBuilder->CreateCondBr(hasValue, boxBB, endBB);
  9609. AddDependency(boxedType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ReadFields);
  9610. mBfIRBuilder->AddBlock(boxBB);
  9611. mBfIRBuilder->SetInsertPoint(boxBB);
  9612. BfScopeData newScope;
  9613. newScope.mOuterIsConditional = true;
  9614. mCurMethodState->AddScope(&newScope);
  9615. NewScopeState();
  9616. BfIRValue nullableValueAddr;
  9617. BfIRValue loadedVal;
  9618. if (innerType->IsValuelessType())
  9619. {
  9620. loadedVal = mBfIRBuilder->GetFakeVal();
  9621. }
  9622. else
  9623. {
  9624. nullableValueAddr = mBfIRBuilder->CreateInBoundsGEP(typedVal.mValue, 0, 1); // value
  9625. loadedVal = mBfIRBuilder->CreateLoad(nullableValueAddr);
  9626. }
  9627. auto boxedVal = BoxValue(srcNode, BfTypedValue(loadedVal, fromStructTypeInstance->GetUnderlyingType()), resultType, allocTarget, callDtor ? BfCastFlags_None : BfCastFlags_NoBoxDtor);
  9628. RestoreScopeState();
  9629. if (!boxedVal)
  9630. return BfTypedValue();
  9631. mBfIRBuilder->CreateBr(endBB);
  9632. auto boxBBEnd = mBfIRBuilder->GetInsertBlock();
  9633. mBfIRBuilder->AddBlock(endBB);
  9634. mBfIRBuilder->SetInsertPoint(endBB);
  9635. auto phi = mBfIRBuilder->CreatePhi(mBfIRBuilder->MapType(resultType), 2);
  9636. mBfIRBuilder->AddPhiIncoming(phi, boxedVal.mValue, boxBBEnd);
  9637. mBfIRBuilder->AddPhiIncoming(phi, GetDefaultValue(resultType), prevBB);
  9638. return BfTypedValue(phi, resultType);
  9639. }
  9640. bool alreadyCheckedCast = false;
  9641. BfTypeInstance* toTypeInstance = NULL;
  9642. if (toType != NULL)
  9643. toTypeInstance = toType->ToTypeInstance();
  9644. bool isStructPtr = typedVal.mType->IsStructPtr();
  9645. if (fromStructTypeInstance == NULL)
  9646. {
  9647. auto primType = (BfPrimitiveType*)typedVal.mType;
  9648. if ((typedVal.mType->IsPointer()) && (toTypeInstance->IsInstanceOf(mCompiler->mIHashableTypeDef)))
  9649. {
  9650. // Can always do IHashable
  9651. alreadyCheckedCast = true;
  9652. }
  9653. if ((!typedVal.mType->IsPointer()) || (toTypeInstance == mContext->mBfObjectType))
  9654. fromStructTypeInstance = GetWrappedStructType(typedVal.mType);
  9655. else
  9656. {
  9657. auto checkStructTypeInstance = GetWrappedStructType(typedVal.mType);
  9658. if (checkStructTypeInstance == toType->GetUnderlyingType())
  9659. fromStructTypeInstance = checkStructTypeInstance;
  9660. }
  9661. if (isStructPtr)
  9662. {
  9663. if ((toTypeInstance != NULL) && (fromStructTypeInstance != NULL) && (TypeIsSubTypeOf(fromStructTypeInstance, toTypeInstance)))
  9664. alreadyCheckedCast = true;
  9665. fromStructTypeInstance = typedVal.mType->GetUnderlyingType()->ToTypeInstance();
  9666. }
  9667. if ((fromStructTypeInstance == NULL) && (alreadyCheckedCast))
  9668. fromStructTypeInstance = GetWrappedStructType(typedVal.mType);
  9669. }
  9670. if (fromStructTypeInstance == NULL)
  9671. return BfTypedValue();
  9672. // Need to box it
  9673. bool isBoxedType = (fromStructTypeInstance != NULL) && (toType->IsBoxed());
  9674. if ((toType == NULL) || (toType == mContext->mBfObjectType) || (isBoxedType) || (alreadyCheckedCast) || (TypeIsSubTypeOf(fromStructTypeInstance, toTypeInstance)))
  9675. {
  9676. if ((mBfIRBuilder->mIgnoreWrites) && (!wantConst))
  9677. return BfTypedValue(mBfIRBuilder->GetFakeVal(), (toType != NULL) ? toType : CreateBoxedType(typedVal.mType));
  9678. auto boxedType = CreateBoxedType(typedVal.mType);
  9679. mBfIRBuilder->PopulateType(boxedType);
  9680. if (wantConst)
  9681. return BfTypedValue(mBfIRBuilder->CreateConstBox(typedVal.mValue, mBfIRBuilder->MapType(boxedType)), boxedType);
  9682. AddDependency(boxedType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ReadFields);
  9683. auto allocaInst = AllocFromType(boxedType, allocTarget, BfIRValue(), BfIRValue(), 0, callDtor ? BfAllocFlags_None : BfAllocFlags_NoDtorCall);
  9684. BfTypedValue boxedTypedValue(allocaInst, boxedType);
  9685. mBfIRBuilder->SetName(allocaInst, "boxed." + fromStructTypeInstance->mTypeDef->mName->ToString());
  9686. if (boxedType->IsUnspecializedType())
  9687. {
  9688. BF_ASSERT((srcNode == NULL) || (mCurMethodInstance->mIsUnspecialized));
  9689. }
  9690. else
  9691. {
  9692. PopulateType(fromStructTypeInstance);
  9693. if (!fromStructTypeInstance->IsValuelessType())
  9694. {
  9695. typedVal = LoadValue(typedVal);
  9696. auto valPtr = mBfIRBuilder->CreateInBoundsGEP(allocaInst, 0, 1);
  9697. if ((typedVal.mType != fromStructTypeInstance) && (!isStructPtr))
  9698. {
  9699. auto ptrType = CreatePointerType(typedVal.mType);
  9700. valPtr = mBfIRBuilder->CreateBitCast(valPtr, mBfIRBuilder->MapType(ptrType));
  9701. }
  9702. if (typedVal.IsSplat())
  9703. {
  9704. AggregateSplatIntoAddr(typedVal, valPtr);
  9705. }
  9706. else
  9707. mBfIRBuilder->CreateStore(typedVal.mValue, valPtr, typedVal.mType->mAlign);
  9708. }
  9709. }
  9710. if (toType == NULL)
  9711. {
  9712. return BfTypedValue(allocaInst, boxedType);
  9713. }
  9714. else
  9715. {
  9716. auto castedValue = mBfIRBuilder->CreateBitCast(allocaInst, mBfIRBuilder->MapType(toType));
  9717. return BfTypedValue(castedValue, toType);
  9718. }
  9719. }
  9720. return BfTypedValue();
  9721. }
  9722. bool BfModule::GetBasePropertyDef(BfPropertyDef*& propDef, BfTypeInstance*& typeInst)
  9723. {
  9724. BfTypeInstance* checkTypeInst = typeInst;
  9725. while (checkTypeInst != NULL)
  9726. {
  9727. for (auto checkProp : checkTypeInst->mTypeDef->mProperties)
  9728. {
  9729. if (checkProp->mName == propDef->mName)
  9730. {
  9731. auto checkPropDeclaration = BfNodeDynCast<BfPropertyDeclaration>(checkProp->mFieldDeclaration);
  9732. if ((checkPropDeclaration == NULL) || (checkPropDeclaration->mVirtualSpecifier == NULL) || (checkPropDeclaration->mVirtualSpecifier->GetToken() == BfToken_Virtual))
  9733. {
  9734. propDef = checkProp;
  9735. typeInst = checkTypeInst;
  9736. return true;
  9737. }
  9738. }
  9739. }
  9740. checkTypeInst = checkTypeInst->mBaseType;
  9741. }
  9742. return false;
  9743. }
  9744. BfMethodInstance* BfModule::GetRawMethodInstanceAtIdx(BfTypeInstance* typeInstance, int methodIdx, const char* assertName)
  9745. {
  9746. if (typeInstance->IsDeleting())
  9747. {
  9748. mCompiler->RequestExtraCompile();
  9749. InternalError("GetRawMethodInstanceAtIdx for deleted type", typeInstance->mTypeDef->GetRefNode());
  9750. return NULL;
  9751. }
  9752. if (!typeInstance->mResolvingVarField)
  9753. {
  9754. if (!typeInstance->DefineStateAllowsStaticMethods())
  9755. PopulateType(typeInstance, BfPopulateType_AllowStaticMethods);
  9756. }
  9757. else
  9758. {
  9759. if (methodIdx >= (int)typeInstance->mMethodInstanceGroups.size())
  9760. {
  9761. AssertErrorState();
  9762. return NULL;
  9763. }
  9764. }
  9765. if (assertName != NULL)
  9766. {
  9767. BF_ASSERT(typeInstance->mTypeDef->mMethods[methodIdx]->mName == assertName);
  9768. }
  9769. if (methodIdx >= typeInstance->mMethodInstanceGroups.mSize)
  9770. {
  9771. if (mCompiler->EnsureCeUnpaused(typeInstance))
  9772. {
  9773. InternalError("OOB in GetRawMethodInstanceAtIdx");
  9774. }
  9775. return NULL;
  9776. }
  9777. auto& methodGroup = typeInstance->mMethodInstanceGroups[methodIdx];
  9778. if (methodGroup.mDefault == NULL)
  9779. {
  9780. if (!mCompiler->mIsResolveOnly)
  9781. {
  9782. // Get it from the owning module so we don't create a reference prematurely...
  9783. auto declModule = typeInstance->mModule;
  9784. if ((typeInstance->mGenericTypeInfo != NULL) && (typeInstance->mGenericTypeInfo->mFinishedGenericParams) && (methodGroup.mOnDemandKind == BfMethodOnDemandKind_NotSet))
  9785. {
  9786. methodGroup.mOnDemandKind = BfMethodOnDemandKind_NoDecl_AwaitingReference;
  9787. if (!declModule->mIsScratchModule)
  9788. declModule->mOnDemandMethodCount++;
  9789. }
  9790. BF_ASSERT((methodGroup.mOnDemandKind == BfMethodOnDemandKind_AlwaysInclude) || (methodGroup.mOnDemandKind == BfMethodOnDemandKind_NoDecl_AwaitingReference) || (methodGroup.mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingDecl) ||
  9791. (typeInstance->mTypeFailed) || (typeInstance->mDefineState < BfTypeDefineState_DefinedAndMethodsSlotted));
  9792. if ((methodGroup.mOnDemandKind == BfMethodOnDemandKind_NoDecl_AwaitingReference) || (methodGroup.mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingDecl))
  9793. methodGroup.mOnDemandKind = BfMethodOnDemandKind_Decl_AwaitingDecl;
  9794. BfGetMethodInstanceFlags useFlags = (BfGetMethodInstanceFlags)(BfGetMethodInstanceFlag_MethodInstanceOnly | BfGetMethodInstanceFlag_UnspecializedPass | BfGetMethodInstanceFlag_Unreified);
  9795. return declModule->GetMethodInstance(typeInstance, typeInstance->mTypeDef->mMethods[methodIdx], BfTypeVector(), useFlags).mMethodInstance;
  9796. }
  9797. else
  9798. {
  9799. auto declModule = typeInstance->mModule;
  9800. BfGetMethodInstanceFlags useFlags = (BfGetMethodInstanceFlags)(BfGetMethodInstanceFlag_MethodInstanceOnly | BfGetMethodInstanceFlag_UnspecializedPass);
  9801. return declModule->GetMethodInstance(typeInstance, typeInstance->mTypeDef->mMethods[methodIdx], BfTypeVector(), useFlags).mMethodInstance;
  9802. }
  9803. }
  9804. auto methodInstance = typeInstance->mMethodInstanceGroups[methodIdx].mDefault;
  9805. //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
  9806. // be from a call to the NON-raw version
  9807. // if (!methodInstance->mMethodInstanceGroup->IsImplemented())
  9808. // {
  9809. // methodInstance->mIsReified = mIsReified;
  9810. // if (methodInstance->mMethodProcessRequest == NULL)
  9811. // typeInstance->mModule->AddMethodToWorkList(methodInstance);
  9812. // }
  9813. return methodInstance;
  9814. }
  9815. BfMethodInstance* BfModule::GetRawMethodInstance(BfTypeInstance* typeInstance, BfMethodDef* methodDef)
  9816. {
  9817. if (methodDef->mIsLocalMethod)
  9818. {
  9819. return GetMethodInstance(typeInstance, methodDef, BfTypeVector()).mMethodInstance;
  9820. }
  9821. return GetRawMethodInstanceAtIdx(typeInstance, methodDef->mIdx, NULL);
  9822. }
  9823. BfMethodInstance* BfModule::GetRawMethodByName(BfTypeInstance* typeInstance, const StringImpl& methodName, int paramCount, bool checkBase, bool allowMixin)
  9824. {
  9825. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  9826. while (typeInstance != NULL)
  9827. {
  9828. typeInstance->mTypeDef->PopulateMemberSets();
  9829. BfMemberSetEntry* entry = NULL;
  9830. BfMethodDef* methodDef = NULL;
  9831. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(methodName, &entry))
  9832. methodDef = (BfMethodDef*)entry->mMemberDef;
  9833. while (methodDef != NULL)
  9834. {
  9835. if (((allowMixin) || (methodDef->mMethodType != BfMethodType_Mixin)) &&
  9836. (methodDef->mGenericParams.size() == 0) &&
  9837. ((paramCount == -1) || (paramCount == (int)methodDef->mParams.size())))
  9838. return GetRawMethodInstance(typeInstance, methodDef);
  9839. methodDef = methodDef->mNextWithSameName;
  9840. }
  9841. if (!checkBase)
  9842. break;
  9843. typeInstance = typeInstance->mBaseType;
  9844. }
  9845. return NULL;
  9846. }
  9847. BfMethodInstance* BfModule::GetUnspecializedMethodInstance(BfMethodInstance* methodInstance, bool useUnspecializedType)
  9848. {
  9849. if ((methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mMethodGenericArguments.size() != 0))
  9850. methodInstance = methodInstance->mMethodInstanceGroup->mDefault;
  9851. auto owner = methodInstance->mMethodInstanceGroup->mOwner;
  9852. if (!useUnspecializedType)
  9853. return methodInstance;
  9854. if (!owner->IsGenericTypeInstance())
  9855. return methodInstance;
  9856. if ((owner->IsDelegateFromTypeRef()) ||
  9857. (owner->IsFunctionFromTypeRef()) ||
  9858. (owner->IsTuple()))
  9859. {
  9860. return methodInstance;
  9861. }
  9862. auto genericType = (BfTypeInstance*)owner;
  9863. if ((genericType->IsUnspecializedType()) && (!genericType->IsUnspecializedTypeVariation()))
  9864. return methodInstance;
  9865. if (methodInstance->mMethodDef->mIsLocalMethod)
  9866. return methodInstance;
  9867. if (methodInstance->mMethodDef->mDeclaringType->IsEmitted())
  9868. return methodInstance;
  9869. auto unspecializedType = ResolveTypeDef(genericType->mTypeDef->GetDefinition());
  9870. if (unspecializedType == NULL)
  9871. {
  9872. AssertErrorState();
  9873. return methodInstance;
  9874. }
  9875. if (unspecializedType == NULL)
  9876. return methodInstance;
  9877. auto unspecializedTypeInst = unspecializedType->ToTypeInstance();
  9878. return GetRawMethodInstanceAtIdx(unspecializedTypeInst, methodInstance->mMethodDef->mIdx);
  9879. }
  9880. int BfModule::GetGenericParamAndReturnCount(BfMethodInstance* methodInstance)
  9881. {
  9882. int genericCount = 0;
  9883. auto unspecializedMethodInstance = GetUnspecializedMethodInstance(methodInstance);
  9884. for (int paramIdx = 0; paramIdx < unspecializedMethodInstance->GetParamCount(); paramIdx++)
  9885. {
  9886. auto param = unspecializedMethodInstance->GetParamType(paramIdx);
  9887. if (param->IsGenericParam())
  9888. genericCount++;
  9889. }
  9890. if (unspecializedMethodInstance->mReturnType->IsGenericParam())
  9891. genericCount++;
  9892. return genericCount;
  9893. }
  9894. BfModule* BfModule::GetSpecializedMethodModule(const SizedArrayImpl<BfProject*>& projectList)
  9895. {
  9896. BF_ASSERT(!mIsScratchModule);
  9897. BF_ASSERT(mIsReified);
  9898. BfModule* mainModule = this;
  9899. if (mParentModule != NULL)
  9900. mainModule = mParentModule;
  9901. BfModule* specModule = NULL;
  9902. BfModule** specModulePtr = NULL;
  9903. if (mainModule->mSpecializedMethodModules.TryGetValueWith(projectList, &specModulePtr))
  9904. {
  9905. return *specModulePtr;
  9906. }
  9907. else
  9908. {
  9909. String specModuleName = mModuleName;
  9910. for (auto bfProject : projectList)
  9911. {
  9912. specModuleName += StrFormat("@%s", bfProject->mSafeName.c_str());
  9913. }
  9914. specModule = new BfModule(mContext, specModuleName);
  9915. specModule->mProject = mainModule->mProject;
  9916. specModule->mParentModule = mainModule;
  9917. specModule->mIsSpecializedMethodModuleRoot = true;
  9918. specModule->Init();
  9919. Array<BfProject*> projList;
  9920. for (auto project : projectList)
  9921. projList.Add(project);
  9922. mainModule->mSpecializedMethodModules[projList] = specModule;
  9923. }
  9924. return specModule;
  9925. }
  9926. BfIRValue BfModule::CreateFunctionFrom(BfMethodInstance* methodInstance, bool tryExisting, bool isInlined)
  9927. {
  9928. if (IsSkippingExtraResolveChecks())
  9929. return BfIRValue();
  9930. if (methodInstance->mMethodInstanceGroup->mOwner->IsInterface())
  9931. {
  9932. //BF_ASSERT(!methodInstance->mIRFunction);
  9933. return BfIRValue();
  9934. }
  9935. auto methodDef = methodInstance->mMethodDef;
  9936. StringT<4096> methodName;
  9937. BfMangler::Mangle(methodName, mCompiler->GetMangleKind(), methodInstance);
  9938. if (isInlined != methodInstance->mAlwaysInline)
  9939. {
  9940. if (isInlined)
  9941. methodName += "__INLINE";
  9942. else
  9943. methodName += "__NOINLINE";
  9944. }
  9945. if (tryExisting)
  9946. {
  9947. auto func = mBfIRBuilder->GetFunction(methodName);
  9948. if (func)
  9949. return func;
  9950. }
  9951. auto intrinsic = GetIntrinsic(methodInstance);
  9952. if (intrinsic)
  9953. return intrinsic;
  9954. if (methodInstance->GetImportCallKind() != BfImportCallKind_None)
  9955. {
  9956. return CreateDllImportGlobalVar(methodInstance, false);
  9957. }
  9958. BfIRType returnType;
  9959. SizedArray<BfIRType, 8> paramTypes;
  9960. methodInstance->GetIRFunctionInfo(this, returnType, paramTypes);
  9961. auto funcType = mBfIRBuilder->CreateFunctionType(returnType, paramTypes, methodInstance->IsVarArgs());
  9962. auto func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, methodName);
  9963. auto callingConv = GetIRCallingConvention(methodInstance);
  9964. if (callingConv != BfIRCallingConv_CDecl)
  9965. mBfIRBuilder->SetFuncCallingConv(func, callingConv);
  9966. SetupIRMethod(methodInstance, func, isInlined);
  9967. // auto srcModule = methodInstance->GetOwner()->GetModule();
  9968. // if ((srcModule != NULL) && (srcModule->mProject != mProject))
  9969. // {
  9970. // if (srcModule->mProject->mTargetType == BfTargetType_BeefDynLib)
  9971. // {
  9972. // mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_DllImport);
  9973. // }
  9974. // }
  9975. return func;
  9976. }
  9977. BfModuleMethodInstance BfModule::GetMethodInstanceAtIdx(BfTypeInstance* typeInstance, int methodIdx, const char* assertName, BfGetMethodInstanceFlags flags)
  9978. {
  9979. if (assertName != NULL)
  9980. {
  9981. BF_ASSERT(typeInstance->mTypeDef->mMethods[methodIdx]->mName == assertName);
  9982. }
  9983. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  9984. if (methodIdx >= typeInstance->mMethodInstanceGroups.mSize)
  9985. return BfModuleMethodInstance();
  9986. auto methodInstance = typeInstance->mMethodInstanceGroups[methodIdx].mDefault;
  9987. BfMethodDef* methodDef = NULL;
  9988. BfTypeInstance* foreignType = NULL;
  9989. if (methodInstance != NULL)
  9990. {
  9991. methodDef = methodInstance->mMethodDef;
  9992. if (methodInstance->mMethodInfoEx != NULL)
  9993. foreignType = methodInstance->mMethodInfoEx->mForeignType;
  9994. }
  9995. if ((methodInstance != NULL) && (mIsReified) && (!methodInstance->mIsReified))
  9996. {
  9997. // Can't use it, not reified
  9998. methodInstance = NULL;
  9999. }
  10000. if ((methodInstance != NULL) && (mBfIRBuilder != NULL) && (mBfIRBuilder->mIgnoreWrites) &&
  10001. (methodInstance->mMethodInstanceGroup->IsImplemented()))
  10002. {
  10003. BfIRFunction func(mBfIRBuilder->GetFakeVal());
  10004. return BfModuleMethodInstance(methodInstance, func);
  10005. }
  10006. if (foreignType != NULL)
  10007. return GetMethodInstance(typeInstance, methodDef, BfTypeVector(), (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_ForeignMethodDef), foreignType);
  10008. return GetMethodInstance(typeInstance, typeInstance->mTypeDef->mMethods[methodIdx], BfTypeVector(), flags);
  10009. }
  10010. BfModuleMethodInstance BfModule::GetMethodByName(BfTypeInstance* typeInstance, const StringImpl& methodName, int paramCount, bool checkBase)
  10011. {
  10012. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  10013. while (typeInstance != NULL)
  10014. {
  10015. typeInstance->mTypeDef->PopulateMemberSets();
  10016. BfMemberSetEntry* entry = NULL;
  10017. BfMethodDef* methodDef = NULL;
  10018. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(methodName, &entry))
  10019. methodDef = (BfMethodDef*)entry->mMemberDef;
  10020. while (methodDef != NULL)
  10021. {
  10022. if ((methodDef->mMethodType != BfMethodType_Mixin) &&
  10023. (methodDef->mGenericParams.size() == 0) &&
  10024. ((paramCount == -1) || (paramCount == (int)methodDef->mParams.size())))
  10025. {
  10026. auto moduleMethodInstance = GetMethodInstanceAtIdx(typeInstance, methodDef->mIdx);
  10027. if (moduleMethodInstance)
  10028. return moduleMethodInstance;
  10029. }
  10030. methodDef = methodDef->mNextWithSameName;
  10031. }
  10032. if (!checkBase)
  10033. break;
  10034. typeInstance = typeInstance->mBaseType;
  10035. }
  10036. return BfModuleMethodInstance();
  10037. }
  10038. BfModuleMethodInstance BfModule::GetMethodByName(BfTypeInstance* typeInstance, const StringImpl& methodName, const Array<BfType*>& paramTypes, bool checkBase)
  10039. {
  10040. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  10041. while (typeInstance != NULL)
  10042. {
  10043. typeInstance->mTypeDef->PopulateMemberSets();
  10044. BfMemberSetEntry* entry = NULL;
  10045. BfMethodDef* methodDef = NULL;
  10046. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(methodName, &entry))
  10047. methodDef = (BfMethodDef*)entry->mMemberDef;
  10048. while (methodDef != NULL)
  10049. {
  10050. if ((methodDef->mMethodType != BfMethodType_Mixin) &&
  10051. (methodDef->mGenericParams.size() == 0) &&
  10052. (paramTypes.size() == methodDef->mParams.size()))
  10053. {
  10054. auto moduleMethodInstance = GetMethodInstanceAtIdx(typeInstance, methodDef->mIdx);
  10055. if (moduleMethodInstance.mMethodInstance != NULL)
  10056. {
  10057. bool matches = true;
  10058. for (int paramIdx = 0; paramIdx < (int)paramTypes.size(); paramIdx++)
  10059. {
  10060. if (moduleMethodInstance.mMethodInstance->GetParamType(paramIdx) != paramTypes[paramIdx])
  10061. matches = false;
  10062. }
  10063. if (matches)
  10064. return moduleMethodInstance;
  10065. }
  10066. }
  10067. methodDef = methodDef->mNextWithSameName;
  10068. }
  10069. if (!checkBase)
  10070. break;
  10071. typeInstance = typeInstance->mBaseType;
  10072. }
  10073. return BfModuleMethodInstance();
  10074. }
  10075. BfModuleMethodInstance BfModule::GetInternalMethod(const StringImpl& methodName, int paramCount)
  10076. {
  10077. auto internalType = ResolveTypeDef(mCompiler->mInternalTypeDef);
  10078. PopulateType(internalType);
  10079. auto moduleMethodInstance = GetMethodByName(internalType->ToTypeInstance(), methodName, paramCount);
  10080. if (!moduleMethodInstance)
  10081. {
  10082. Fail(StrFormat("Failed to find System.Internal method '%s'", methodName.c_str()));
  10083. }
  10084. return moduleMethodInstance;
  10085. }
  10086. BfOperatorInfo* BfModule::GetOperatorInfo(BfTypeInstance* typeInstance, BfOperatorDef* operatorDef)
  10087. {
  10088. while (operatorDef->mIdx >= typeInstance->mOperatorInfo.size())
  10089. typeInstance->mOperatorInfo.Add(NULL);
  10090. if (typeInstance->mOperatorInfo[operatorDef->mIdx] == NULL)
  10091. {
  10092. SetAndRestoreValue<bool> ignoreErrors(mIgnoreErrors, true);
  10093. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  10094. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, NULL);
  10095. BfTypeState typeState;
  10096. typeState.mType = typeInstance;
  10097. typeState.mCurTypeDef = operatorDef->mDeclaringType;
  10098. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  10099. BfOperatorInfo* operatorInfo = new BfOperatorInfo();
  10100. if (operatorDef->mReturnTypeRef != NULL)
  10101. operatorInfo->mReturnType = ResolveTypeRef(operatorDef->mReturnTypeRef, BfPopulateType_Identity);
  10102. if (operatorDef->mParams.size() >= 1)
  10103. operatorInfo->mLHSType = ResolveTypeRef(operatorDef->mParams[0]->mTypeRef, BfPopulateType_Identity);
  10104. if (operatorDef->mParams.size() >= 2)
  10105. operatorInfo->mRHSType = ResolveTypeRef(operatorDef->mParams[1]->mTypeRef, BfPopulateType_Identity);
  10106. typeInstance->mOperatorInfo[operatorDef->mIdx] = operatorInfo;
  10107. }
  10108. return typeInstance->mOperatorInfo[operatorDef->mIdx];
  10109. }
  10110. BfType* BfModule::CheckOperator(BfTypeInstance* typeInstance, BfOperatorDef* operatorDef, const BfTypedValue& lhs, const BfTypedValue& rhs)
  10111. {
  10112. auto operatorInfo = GetOperatorInfo(typeInstance, operatorDef);
  10113. if (operatorInfo == NULL)
  10114. return NULL;
  10115. if (operatorInfo->mReturnType == NULL)
  10116. return NULL;
  10117. auto castFlags = BfCastFlags_IsConstraintCheck;
  10118. if (operatorDef->mOperatorDeclaration->mIsConvOperator)
  10119. castFlags = (BfCastFlags)(castFlags | BfCastFlags_NoConversionOperator);
  10120. if (lhs)
  10121. {
  10122. if (operatorInfo->mLHSType == NULL)
  10123. return NULL;
  10124. if (!CanCast(lhs, operatorInfo->mLHSType, castFlags))
  10125. return NULL;
  10126. }
  10127. if (rhs)
  10128. {
  10129. if (operatorInfo->mRHSType == NULL)
  10130. return NULL;
  10131. if (!CanCast(rhs, operatorInfo->mRHSType, castFlags))
  10132. return NULL;
  10133. }
  10134. return operatorInfo->mReturnType;
  10135. }
  10136. bool BfModule::IsMethodImplementedAndReified(BfTypeInstance* typeInstance, const StringImpl& methodName, int paramCount, bool checkBase)
  10137. {
  10138. while (typeInstance != NULL)
  10139. {
  10140. typeInstance->mTypeDef->PopulateMemberSets();
  10141. BfMemberSetEntry* entry = NULL;
  10142. BfMethodDef* methodDef = NULL;
  10143. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(methodName, &entry))
  10144. methodDef = (BfMethodDef*)entry->mMemberDef;
  10145. while (methodDef != NULL)
  10146. {
  10147. if ((methodDef->mMethodType != BfMethodType_Mixin) &&
  10148. (methodDef->mGenericParams.size() == 0) &&
  10149. ((paramCount == -1) || (paramCount == (int)methodDef->mParams.size())))
  10150. {
  10151. auto& methodInstanceGroup = typeInstance->mMethodInstanceGroups[methodDef->mIdx];
  10152. if (!methodInstanceGroup.IsImplemented())
  10153. return false;
  10154. if (methodInstanceGroup.mDefault == NULL)
  10155. return false;
  10156. return methodInstanceGroup.mDefault->mIsReified;
  10157. }
  10158. methodDef = methodDef->mNextWithSameName;
  10159. }
  10160. if (!checkBase)
  10161. break;
  10162. typeInstance = typeInstance->mBaseType;
  10163. }
  10164. return false;
  10165. }
  10166. bool BfModule::HasMixin(BfTypeInstance* typeInstance, const StringImpl& methodName, int paramCount, bool checkBase)
  10167. {
  10168. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  10169. while (typeInstance != NULL)
  10170. {
  10171. typeInstance->mTypeDef->PopulateMemberSets();
  10172. BfMemberSetEntry* entry = NULL;
  10173. BfMethodDef* methodDef = NULL;
  10174. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(methodName, &entry))
  10175. methodDef = (BfMethodDef*)entry->mMemberDef;
  10176. while (methodDef != NULL)
  10177. {
  10178. if ((methodDef->mMethodType == BfMethodType_Mixin) &&
  10179. ((paramCount == -1) || (paramCount == (int)methodDef->mParams.size())))
  10180. return true;
  10181. methodDef = methodDef->mNextWithSameName;
  10182. }
  10183. if (!checkBase)
  10184. break;
  10185. typeInstance = typeInstance->mBaseType;
  10186. }
  10187. return BfModuleMethodInstance();
  10188. }
  10189. String BfModule::FieldToString(BfFieldInstance* fieldInstance)
  10190. {
  10191. auto result = TypeToString(fieldInstance->mOwner);
  10192. result += ".";
  10193. auto fieldDef = fieldInstance->GetFieldDef();
  10194. if (fieldDef != NULL)
  10195. result += fieldDef->mName;
  10196. else
  10197. result += "???";
  10198. return result;
  10199. }
  10200. StringT<128> BfModule::MethodToString(BfMethodInstance* methodInst, BfMethodNameFlags methodNameFlags, BfTypeVector* typeGenericArgs, BfTypeVector* methodGenericArgs)
  10201. {
  10202. auto methodDef = methodInst->mMethodDef;
  10203. bool allowResolveGenericParamNames = ((methodNameFlags & BfMethodNameFlag_ResolveGenericParamNames) != 0);
  10204. BfTypeNameFlags typeNameFlags = BfTypeNameFlags_None;
  10205. bool hasGenericArgs = (typeGenericArgs != NULL) || (methodGenericArgs != NULL);
  10206. BfType* type = methodInst->mMethodInstanceGroup->mOwner;
  10207. if ((hasGenericArgs) && (type->IsUnspecializedType()))
  10208. type = ResolveGenericType(type, typeGenericArgs, methodGenericArgs, mCurTypeInstance);
  10209. if ((type == NULL) || (!type->IsUnspecializedTypeVariation()))
  10210. typeNameFlags = BfTypeNameFlag_ResolveGenericParamNames;
  10211. if (allowResolveGenericParamNames)
  10212. typeNameFlags = BfTypeNameFlag_ResolveGenericParamNames;
  10213. StringT<128> methodName;
  10214. auto _AddTypeName = [&](BfType* type)
  10215. {
  10216. auto typeNameFlags = BfTypeNameFlags_None;
  10217. if (allowResolveGenericParamNames)
  10218. typeNameFlags = BfTypeNameFlag_ResolveGenericParamNames;
  10219. if ((hasGenericArgs) && (type->IsUnspecializedType()))
  10220. type = ResolveGenericType(type, typeGenericArgs, methodGenericArgs, mCurTypeInstance);
  10221. methodName += TypeToString(type, typeNameFlags);
  10222. };
  10223. if ((methodNameFlags & BfMethodNameFlag_IncludeReturnType) != 0)
  10224. {
  10225. _AddTypeName(methodInst->mReturnType);
  10226. methodName += " ";
  10227. }
  10228. if ((methodNameFlags & BfMethodNameFlag_OmitTypeName) == 0)
  10229. {
  10230. methodName += TypeToString(type, typeNameFlags);
  10231. if (methodName == "$")
  10232. methodName = "";
  10233. else if (!methodName.IsEmpty())
  10234. methodName += ".";
  10235. }
  10236. String accessorString;
  10237. StringT<64> methodDefName = methodInst->mMethodDef->mName;
  10238. if (methodInst->mMethodDef->mIsLocalMethod)
  10239. {
  10240. int atPos = (int)methodDefName.IndexOf('$');
  10241. methodDefName.RemoveToEnd(atPos);
  10242. methodDefName.Replace("@", ".");
  10243. }
  10244. else
  10245. {
  10246. int atPos = (int)methodDefName.IndexOf('$');
  10247. if (atPos != -1)
  10248. {
  10249. accessorString = methodDefName.Substring(0, atPos);
  10250. if ((accessorString == "get") || (accessorString == "set"))
  10251. {
  10252. methodDefName = methodDefName.Substring(atPos + 1);
  10253. }
  10254. else
  10255. accessorString = "";
  10256. }
  10257. }
  10258. if ((methodInst->mMethodInfoEx != NULL) && (methodInst->mMethodInfoEx->mForeignType != NULL))
  10259. {
  10260. BfTypeNameFlags typeNameFlags = BfTypeNameFlags_None;
  10261. if (!methodInst->mIsUnspecializedVariation && allowResolveGenericParamNames)
  10262. typeNameFlags = BfTypeNameFlag_ResolveGenericParamNames;
  10263. methodName += TypeToString(methodInst->mMethodInfoEx->mForeignType, typeNameFlags);
  10264. methodName += ".";
  10265. }
  10266. if ((methodInst->mMethodInfoEx != NULL) && (methodInst->mMethodInfoEx->mExplicitInterface != NULL))
  10267. {
  10268. BfTypeNameFlags typeNameFlags = BfTypeNameFlags_None;
  10269. if (!methodInst->mIsUnspecializedVariation && allowResolveGenericParamNames)
  10270. typeNameFlags = BfTypeNameFlag_ResolveGenericParamNames;
  10271. methodName += "[";
  10272. methodName += TypeToString(methodInst->mMethodInfoEx->mExplicitInterface, typeNameFlags);
  10273. methodName += "].";
  10274. }
  10275. if (methodDef->mMethodType == BfMethodType_Operator)
  10276. {
  10277. BfOperatorDef* operatorDef = (BfOperatorDef*)methodDef;
  10278. if (operatorDef->mOperatorDeclaration->mIsConvOperator)
  10279. {
  10280. // Don't add explicit/implicit part, since that's not available in GCC mangling
  10281. /*if (operatorDef->mOperatorDeclaration->mExplicitToken != NULL)
  10282. {
  10283. if (operatorDef->mOperatorDeclaration->mExplicitToken->GetToken() == BfToken_Explicit)
  10284. methodName += "explicit ";
  10285. else if (operatorDef->mOperatorDeclaration->mExplicitToken->GetToken() == BfToken_Explicit)
  10286. methodName += "explicit ";
  10287. }*/
  10288. methodName += "operator ";
  10289. if (methodInst->mReturnType != NULL)
  10290. methodName += TypeToString(methodInst->mReturnType);
  10291. }
  10292. else
  10293. {
  10294. methodName += "operator";
  10295. if (operatorDef->mOperatorDeclaration->mOpTypeToken != NULL)
  10296. methodName += BfTokenToString(operatorDef->mOperatorDeclaration->mOpTypeToken->GetToken());
  10297. }
  10298. }
  10299. else if (methodDef->mMethodType == BfMethodType_Ctor)
  10300. {
  10301. if (methodDef->mIsStatic)
  10302. methodName += "__BfStaticCtor";
  10303. else
  10304. methodName += "this";
  10305. accessorString = "";
  10306. }
  10307. else if (methodDef->mMethodType == BfMethodType_PropertyGetter)
  10308. {
  10309. auto propertyDecl = methodDef->GetPropertyDeclaration();
  10310. if (auto indexerProperty = BfNodeDynCast<BfIndexerDeclaration>(propertyDecl))
  10311. {
  10312. methodName += "get indexer";
  10313. }
  10314. else
  10315. {
  10316. if ((propertyDecl != NULL) && (propertyDecl->mNameNode != NULL))
  10317. propertyDecl->mNameNode->ToString(methodName);
  10318. methodName += " get accessor";
  10319. return methodName;
  10320. }
  10321. }
  10322. else if (methodDef->mMethodType == BfMethodType_PropertySetter)
  10323. {
  10324. auto propertyDecl = methodDef->GetPropertyDeclaration();
  10325. if (auto indexerProperty = BfNodeDynCast<BfIndexerDeclaration>(propertyDecl))
  10326. {
  10327. methodName += "set indexer";
  10328. }
  10329. else
  10330. {
  10331. if ((propertyDecl != NULL) && (propertyDecl->mNameNode != NULL))
  10332. propertyDecl->mNameNode->ToString(methodName);
  10333. methodName += " set accessor";
  10334. return methodName;
  10335. }
  10336. }
  10337. else
  10338. methodName += methodDefName;
  10339. if (methodDef->mMethodType == BfMethodType_Mixin)
  10340. methodName += "!";
  10341. BfTypeVector newMethodGenericArgs;
  10342. if ((methodInst->mMethodInfoEx != NULL) && (methodInst->mMethodInfoEx->mMethodGenericArguments.size() != 0))
  10343. {
  10344. methodName += "<";
  10345. for (int i = 0; i < (int)methodInst->mMethodInfoEx->mMethodGenericArguments.size(); i++)
  10346. {
  10347. if (i > 0)
  10348. methodName += ", ";
  10349. BfTypeNameFlags typeNameFlags = BfTypeNameFlag_ShortConst;
  10350. //Why did we have this methodInst->mIsUnspecializedVariation check? Sometimes we do need to show errors calling methods that refer back to our types
  10351. //if (!methodInst->mIsUnspecializedVariation && allowResolveGenericParamNames)
  10352. if (allowResolveGenericParamNames)
  10353. typeNameFlags = (BfTypeNameFlags)(typeNameFlags | BfTypeNameFlag_ResolveGenericParamNames);
  10354. BfType* type = methodInst->mMethodInfoEx->mMethodGenericArguments[i];
  10355. if ((methodGenericArgs != NULL) && (type->IsUnspecializedType()))
  10356. {
  10357. bool hasEmpty = false;
  10358. for (auto arg : *methodGenericArgs)
  10359. {
  10360. if (arg == NULL)
  10361. hasEmpty = true;
  10362. }
  10363. if (hasEmpty)
  10364. {
  10365. for (int genericIdx = 0; genericIdx < (int)methodGenericArgs->size(); genericIdx++)
  10366. {
  10367. auto arg = (*methodGenericArgs)[genericIdx];
  10368. if (arg != NULL)
  10369. newMethodGenericArgs.push_back(arg);
  10370. else
  10371. {
  10372. auto genericParamInst = methodInst->mMethodInfoEx->mGenericParams[genericIdx];
  10373. if (genericParamInst->mTypeConstraint != NULL)
  10374. newMethodGenericArgs.push_back(genericParamInst->mTypeConstraint);
  10375. else
  10376. newMethodGenericArgs.push_back(mContext->mBfObjectType); // Default
  10377. }
  10378. }
  10379. methodGenericArgs = &newMethodGenericArgs;
  10380. }
  10381. if (type->IsUnspecializedType())
  10382. type = ResolveGenericType(type, NULL, methodGenericArgs, mCurTypeInstance);
  10383. }
  10384. if ((methodGenericArgs == NULL) && (mCurMethodInstance == NULL) && (mCurTypeInstance == NULL))
  10385. {
  10386. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, methodInst->GetOwner());
  10387. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, methodInst);
  10388. methodName += TypeToString(type, typeNameFlags);
  10389. }
  10390. else
  10391. methodName += TypeToString(type, typeNameFlags);
  10392. }
  10393. methodName += ">";
  10394. }
  10395. if (accessorString.length() == 0)
  10396. {
  10397. int dispParamIdx = 0;
  10398. methodName += "(";
  10399. for (int paramIdx = 0; paramIdx < (int)methodInst->GetParamCount(); paramIdx++)
  10400. {
  10401. int paramKind = methodInst->GetParamKind(paramIdx);
  10402. if ((paramKind == BfParamKind_ImplicitCapture) || (paramKind == BfParamKind_AppendIdx))
  10403. continue;
  10404. if (dispParamIdx > 0)
  10405. methodName += ", ";
  10406. if (paramKind == BfParamKind_Params)
  10407. methodName += "params ";
  10408. BfType* type = methodInst->GetParamType(paramIdx);
  10409. _AddTypeName(type);
  10410. methodName += " ";
  10411. methodName += methodInst->GetParamName(paramIdx);
  10412. auto paramInitializer = methodInst->GetParamInitializer(paramIdx);
  10413. if ((paramInitializer != NULL) && ((methodNameFlags & BfMethodNameFlag_NoAst) == 0))
  10414. {
  10415. methodName += " = ";
  10416. methodName += paramInitializer->ToString();
  10417. }
  10418. dispParamIdx++;
  10419. }
  10420. methodName += ")";
  10421. }
  10422. if (accessorString.length() != 0)
  10423. {
  10424. methodName += " ";
  10425. methodName += accessorString;
  10426. }
  10427. if ((methodNameFlags & BfMethodNameFlag_IncludeMut) != 0)
  10428. {
  10429. if ((methodDef->mIsMutating) && (methodInst->GetOwner()->IsValueType()))
  10430. methodName += " mut";
  10431. }
  10432. return methodName;
  10433. }
  10434. void BfModule::pt(BfType* type)
  10435. {
  10436. OutputDebugStrF("%s\n", TypeToString(type).c_str());
  10437. }
  10438. void BfModule::pm(BfMethodInstance* type)
  10439. {
  10440. OutputDebugStrF("%s\n", MethodToString(type).c_str());
  10441. }
  10442. static void AddAttributeTargetName(BfAttributeTargets& flagsLeft, BfAttributeTargets checkFlag, String& str, String addString)
  10443. {
  10444. if ((flagsLeft & checkFlag) == 0)
  10445. return;
  10446. if (!str.empty())
  10447. {
  10448. if (flagsLeft == checkFlag)
  10449. {
  10450. if ((int)str.IndexOf(',') != -1)
  10451. str += ", and ";
  10452. else
  10453. str += " and ";
  10454. }
  10455. else
  10456. str += ", ";
  10457. }
  10458. str += addString;
  10459. flagsLeft = (BfAttributeTargets)(flagsLeft & ~checkFlag);
  10460. }
  10461. static String GetAttributesTargetListString(BfAttributeTargets attrTarget)
  10462. {
  10463. String resultStr;
  10464. auto flagsLeft = attrTarget;
  10465. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Assembly, resultStr, "assembly declarations");
  10466. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Module, resultStr, "module declarations");
  10467. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Class, resultStr, "class declarations");
  10468. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Struct, resultStr, "struct declarations");
  10469. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Enum, resultStr, "enum declarations");
  10470. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Constructor, resultStr, "constructor declarations");
  10471. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Method, resultStr, "method declarations");
  10472. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Property, resultStr, "property declarations");
  10473. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Field, resultStr, "field declarations");
  10474. AddAttributeTargetName(flagsLeft, BfAttributeTargets_StaticField, resultStr, "static field declarations");
  10475. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Interface, resultStr, "interface declarations");
  10476. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Parameter, resultStr, "parameter declarations");
  10477. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Delegate, resultStr, "delegate declarations");
  10478. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Function, resultStr, "function declarations");
  10479. AddAttributeTargetName(flagsLeft, BfAttributeTargets_ReturnValue, resultStr, "return value");
  10480. AddAttributeTargetName(flagsLeft, BfAttributeTargets_GenericParameter, resultStr, "generic parameters");
  10481. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Invocation, resultStr, "invocations");
  10482. AddAttributeTargetName(flagsLeft, BfAttributeTargets_MemberAccess, resultStr, "member access");
  10483. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Alloc, resultStr, "allocations");
  10484. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Alias, resultStr, "aliases");
  10485. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Block, resultStr, "blocks");
  10486. if (resultStr.IsEmpty())
  10487. return "<nothing>";
  10488. return resultStr;
  10489. }
  10490. BfIRType BfModule::CurrentAddToConstHolder(BfIRType irType)
  10491. {
  10492. if (irType.mKind == BfIRTypeData::TypeKind_SizedArray)
  10493. {
  10494. auto sizedArrayType = (BfConstantSizedArrayType*)mBfIRBuilder->GetConstantById(irType.mId);
  10495. return mCurTypeInstance->GetOrCreateConstHolder()->GetSizedArrayType(CurrentAddToConstHolder(sizedArrayType->mType), (int)sizedArrayType->mLength);
  10496. }
  10497. return irType;
  10498. }
  10499. void BfModule::CurrentAddToConstHolder(BfIRValue& irVal)
  10500. {
  10501. auto constant = mBfIRBuilder->GetConstant(irVal);
  10502. int stringPoolIdx = GetStringPoolIdx(irVal, mBfIRBuilder);
  10503. if (stringPoolIdx != -1)
  10504. {
  10505. irVal = mCurTypeInstance->GetOrCreateConstHolder()->CreateConst(BfTypeCode_StringId, stringPoolIdx);
  10506. return;
  10507. }
  10508. if (constant->mConstType == BfConstType_Agg)
  10509. {
  10510. auto constArray = (BfConstantAgg*)constant;
  10511. SizedArray<BfIRValue, 8> newVals;
  10512. for (auto val : constArray->mValues)
  10513. {
  10514. auto newVal = val;
  10515. CurrentAddToConstHolder(newVal);
  10516. newVals.push_back(newVal);
  10517. }
  10518. irVal = mCurTypeInstance->GetOrCreateConstHolder()->CreateConstAgg(CurrentAddToConstHolder(constArray->mType), newVals);
  10519. return;
  10520. }
  10521. auto origConst = irVal;
  10522. if ((constant->mConstType == BfConstType_BitCast) || (constant->mConstType == BfConstType_BitCastNull))
  10523. {
  10524. auto bitcast = (BfConstantBitCast*)constant;
  10525. BfIRValue newVal;
  10526. if (constant->mConstType == BfConstType_BitCast)
  10527. {
  10528. newVal = BfIRValue(BfIRValueFlags_Const, bitcast->mTarget);
  10529. CurrentAddToConstHolder(newVal);
  10530. }
  10531. else
  10532. newVal = mCurTypeInstance->GetOrCreateConstHolder()->CreateConstNull();
  10533. irVal = mCurTypeInstance->GetOrCreateConstHolder()->CreateConstBitCast(newVal, CurrentAddToConstHolder(bitcast->mToType));
  10534. return;
  10535. }
  10536. irVal = mCurTypeInstance->CreateConst(constant, mBfIRBuilder);
  10537. }
  10538. void BfModule::ClearConstData()
  10539. {
  10540. mBfIRBuilder->ClearConstData();
  10541. mStringObjectPool.Clear();
  10542. mStringCharPtrPool.Clear();
  10543. mStringPoolRefs.Clear();
  10544. mUnreifiedStringPoolRefs.Clear();
  10545. mStaticFieldRefs.Clear();
  10546. }
  10547. BfTypedValue BfModule::GetTypedValueFromConstant(BfConstant* constant, BfIRConstHolder* constHolder, BfType* wantType)
  10548. {
  10549. switch (constant->mTypeCode)
  10550. {
  10551. case BfTypeCode_StringId:
  10552. case BfTypeCode_Boolean:
  10553. case BfTypeCode_Int8:
  10554. case BfTypeCode_UInt8:
  10555. case BfTypeCode_Int16:
  10556. case BfTypeCode_UInt16:
  10557. case BfTypeCode_Int32:
  10558. case BfTypeCode_UInt32:
  10559. case BfTypeCode_Int64:
  10560. case BfTypeCode_UInt64:
  10561. case BfTypeCode_IntPtr:
  10562. case BfTypeCode_UIntPtr:
  10563. case BfTypeCode_IntUnknown:
  10564. case BfTypeCode_UIntUnknown:
  10565. case BfTypeCode_Char8:
  10566. case BfTypeCode_Char16:
  10567. case BfTypeCode_Char32:
  10568. case BfTypeCode_Float:
  10569. case BfTypeCode_Double:
  10570. {
  10571. auto constVal = mBfIRBuilder->CreateConst(constant, constHolder);
  10572. BfTypedValue typedValue;
  10573. bool allowUnactualized = mBfIRBuilder->mIgnoreWrites;
  10574. if (constant->mTypeCode == BfTypeCode_StringId)
  10575. {
  10576. if ((wantType->IsInstanceOf(mCompiler->mStringTypeDef)) ||
  10577. ((wantType->IsPointer()) && (wantType->GetUnderlyingType() == GetPrimitiveType(BfTypeCode_Char8))))
  10578. {
  10579. typedValue = BfTypedValue(ConstantToCurrent(constant, constHolder, wantType, allowUnactualized), wantType);
  10580. return typedValue;
  10581. }
  10582. auto stringType = ResolveTypeDef(mCompiler->mStringTypeDef);
  10583. typedValue = BfTypedValue(ConstantToCurrent(constant, constHolder, stringType, allowUnactualized), stringType);
  10584. }
  10585. if (!typedValue)
  10586. {
  10587. auto constVal = mBfIRBuilder->CreateConst(constant, constHolder);
  10588. typedValue = BfTypedValue(constVal, GetPrimitiveType(constant->mTypeCode));
  10589. }
  10590. if (typedValue.mType == wantType)
  10591. return typedValue;
  10592. if (wantType->IsTypedPrimitive())
  10593. {
  10594. if (typedValue.mType == wantType->GetUnderlyingType())
  10595. {
  10596. typedValue.mType = wantType;
  10597. return typedValue;
  10598. }
  10599. }
  10600. auto castedTypedValue = Cast(NULL, typedValue, wantType, (BfCastFlags)(BfCastFlags_SilentFail | BfCastFlags_Explicit));
  10601. if (!castedTypedValue)
  10602. return BfTypedValue();
  10603. return castedTypedValue;
  10604. }
  10605. break;
  10606. default: break;
  10607. }
  10608. BfIRValue irValue = ConstantToCurrent(constant, constHolder, wantType);
  10609. BF_ASSERT(irValue);
  10610. if (!irValue)
  10611. return BfTypedValue();
  10612. if (constant->mConstType == BfConstType_GlobalVar)
  10613. {
  10614. mBfIRBuilder->PopulateType(wantType);
  10615. auto result = BfTypedValue(irValue, wantType, true);
  10616. if (!wantType->IsComposite())
  10617. result = LoadValue(result);
  10618. return result;
  10619. }
  10620. return BfTypedValue(irValue, wantType, false);
  10621. }
  10622. bool BfModule::HasUnactializedConstant(BfConstant* constant, BfIRConstHolder* constHolder)
  10623. {
  10624. if ((constant->mConstType == BfConstType_TypeOf) || (constant->mConstType == BfConstType_TypeOf_WithData))
  10625. return true;
  10626. if (constant->mTypeCode == BfTypeCode_StringId)
  10627. return true;
  10628. if (constant->mConstType == BfConstType_Agg)
  10629. {
  10630. auto constArray = (BfConstantAgg*)constant;
  10631. for (auto val : constArray->mValues)
  10632. {
  10633. if (HasUnactializedConstant(constHolder->GetConstant(val), constHolder))
  10634. return true;
  10635. }
  10636. }
  10637. return false;
  10638. }
  10639. BfIRValue BfModule::ConstantToCurrent(BfConstant* constant, BfIRConstHolder* constHolder, BfType* wantType, bool allowUnactualized)
  10640. {
  10641. if (constant->mTypeCode == BfTypeCode_NullPtr)
  10642. {
  10643. if ((wantType == NULL) && (constant->mIRType.mKind == BfIRTypeData::TypeKind_TypeId))
  10644. wantType = mContext->mTypes[constant->mIRType.mId];
  10645. if (wantType == NULL)
  10646. return mBfIRBuilder->CreateConstNull();
  10647. return GetDefaultValue(wantType);
  10648. }
  10649. if (constant->mTypeCode == BfTypeCode_StringId)
  10650. {
  10651. if (!allowUnactualized)
  10652. {
  10653. if ((wantType == NULL) ||
  10654. (wantType->IsInstanceOf(mCompiler->mStringTypeDef)) ||
  10655. ((wantType->IsPointer()) && (wantType->GetUnderlyingType() == GetPrimitiveType(BfTypeCode_Char8))))
  10656. {
  10657. const StringImpl& str = mContext->mStringObjectIdMap[constant->mInt32].mString;
  10658. BfIRValue stringObjConst = GetStringObjectValue(str, false, true);
  10659. if ((wantType != NULL) && (wantType->IsPointer()))
  10660. return GetStringCharPtr(stringObjConst, true);
  10661. return stringObjConst;
  10662. }
  10663. }
  10664. }
  10665. if (constant->mConstType == Beefy::BfConstType_TypeOf)
  10666. {
  10667. auto constTypeOf = (BfTypeOf_Const*)constant;
  10668. if (mCurTypeInstance != NULL)
  10669. AddDependency(constTypeOf->mType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ExprTypeReference);
  10670. return CreateTypeDataRef(constTypeOf->mType, true);
  10671. }
  10672. if (constant->mConstType == BfConstType_PtrToInt)
  10673. {
  10674. auto fromPtrToInt = (BfConstantPtrToInt*)constant;
  10675. auto fromTarget = constHolder->GetConstantById(fromPtrToInt->mTarget);
  10676. return mBfIRBuilder->CreatePtrToInt(ConstantToCurrent(fromTarget, constHolder, NULL), fromPtrToInt->mToTypeCode);
  10677. }
  10678. if (constant->mConstType == BfConstType_IntToPtr)
  10679. {
  10680. auto fromPtrToInt = (BfConstantIntToPtr*)constant;
  10681. auto fromTarget = constHolder->GetConstantById(fromPtrToInt->mTarget);
  10682. BfIRType toIRType = fromPtrToInt->mToType;
  10683. if (toIRType.mKind == BfIRTypeData::TypeKind_TypeId)
  10684. {
  10685. auto toType = mContext->mTypes[toIRType.mId];
  10686. toIRType = mBfIRBuilder->MapType(toType);
  10687. }
  10688. return mBfIRBuilder->CreateIntToPtr(ConstantToCurrent(fromTarget, constHolder, NULL), toIRType);
  10689. }
  10690. if ((constant->mConstType == BfConstType_BitCast) || (constant->mConstType == BfConstType_BitCastNull))
  10691. {
  10692. auto bitcast = (BfConstantBitCast*)constant;
  10693. auto fromTarget = constHolder->GetConstantById(bitcast->mTarget);
  10694. BfIRType toIRType = bitcast->mToType;
  10695. if (toIRType.mKind == BfIRTypeData::TypeKind_TypeId)
  10696. {
  10697. auto toType = mContext->mTypes[toIRType.mId];
  10698. toIRType = mBfIRBuilder->MapType(toType);
  10699. }
  10700. return mBfIRBuilder->CreateBitCast(ConstantToCurrent(fromTarget, constHolder, NULL), toIRType);
  10701. }
  10702. if (constant->mConstType == BfConstType_Agg)
  10703. {
  10704. auto constArray = (BfConstantAgg*)constant;
  10705. if ((wantType == NULL) && (constArray->mType.mKind == BfIRTypeData::TypeKind_TypeId))
  10706. wantType = mContext->mTypes[constArray->mType.mId];
  10707. if (wantType->IsArray())
  10708. wantType = CreateSizedArrayType(wantType->GetUnderlyingType(), (int)constArray->mValues.mSize);
  10709. bool handleAsArray = false;
  10710. SizedArray<BfIRValue, 8> newVals;
  10711. if (wantType->IsSizedArray())
  10712. {
  10713. handleAsArray = true;
  10714. }
  10715. else if (wantType->IsInstanceOf(mCompiler->mSpanTypeDef))
  10716. {
  10717. auto valueType = ResolveTypeDef(mCompiler->mValueTypeTypeDef);
  10718. handleAsArray = true;
  10719. if (!constArray->mValues.IsEmpty())
  10720. {
  10721. auto firstConstant = constHolder->GetConstant(constArray->mValues[0]);
  10722. if ((firstConstant->mConstType == BfConstType_AggZero) && (firstConstant->mIRType.mKind == BfIRType::TypeKind_TypeId) &&
  10723. (firstConstant->mIRType.mId == valueType->mTypeId))
  10724. handleAsArray = false;
  10725. if (firstConstant->mConstType == BfConstType_Agg)
  10726. {
  10727. auto firstConstArray = (BfConstantAgg*)firstConstant;
  10728. if ((firstConstArray->mType.mKind == BfIRType::TypeKind_TypeId) &&
  10729. (firstConstArray->mType.mId == valueType->mTypeId))
  10730. handleAsArray = false;
  10731. }
  10732. }
  10733. }
  10734. if (handleAsArray)
  10735. {
  10736. auto elementType = wantType->GetUnderlyingType();
  10737. for (auto val : constArray->mValues)
  10738. {
  10739. newVals.Add(ConstantToCurrent(constHolder->GetConstant(val), constHolder, elementType));
  10740. }
  10741. }
  10742. else
  10743. {
  10744. auto wantTypeInst = wantType->ToTypeInstance();
  10745. if (wantTypeInst == NULL)
  10746. {
  10747. InternalError("BfModule::ConstantToCurrent typeInst error");
  10748. return BfIRValue();
  10749. }
  10750. if (wantTypeInst->mBaseType != NULL)
  10751. {
  10752. auto baseVal = ConstantToCurrent(constHolder->GetConstant(constArray->mValues[0]), constHolder, wantTypeInst->mBaseType);
  10753. newVals.Add(baseVal);
  10754. }
  10755. if (wantType->IsUnion())
  10756. {
  10757. auto innerType = wantType->ToTypeInstance()->GetUnionInnerType();
  10758. if (!innerType->IsValuelessType())
  10759. {
  10760. auto val = ConstantToCurrent(constHolder->GetConstant(constArray->mValues[1]), constHolder, innerType);
  10761. newVals.Add(val);
  10762. }
  10763. }
  10764. if ((!wantType->IsUnion()) || (wantType->IsPayloadEnum()))
  10765. {
  10766. for (auto& fieldInstance : wantTypeInst->mFieldInstances)
  10767. {
  10768. if (fieldInstance.mDataIdx < 0)
  10769. continue;
  10770. if (fieldInstance.mDataIdx >= constArray->mValues.mSize)
  10771. {
  10772. InternalError("BfModule::ConstantToCurrent union error");
  10773. return BfIRValue();
  10774. }
  10775. auto val = constArray->mValues[fieldInstance.mDataIdx];
  10776. BfIRValue memberVal = ConstantToCurrent(constHolder->GetConstant(val), constHolder, fieldInstance.mResolvedType);
  10777. if (fieldInstance.mDataIdx == newVals.mSize)
  10778. newVals.Add(memberVal);
  10779. else
  10780. {
  10781. while (fieldInstance.mDataIdx >= newVals.mSize)
  10782. newVals.Add(BfIRValue());
  10783. newVals[fieldInstance.mDataIdx] = memberVal;
  10784. }
  10785. }
  10786. }
  10787. for (auto& val : newVals)
  10788. {
  10789. if (!val)
  10790. val = mBfIRBuilder->CreateConstArrayZero(0);
  10791. }
  10792. }
  10793. return mBfIRBuilder->CreateConstAgg(mBfIRBuilder->MapType(wantType, BfIRPopulateType_Identity), newVals);
  10794. }
  10795. return mBfIRBuilder->CreateConst(constant, constHolder);
  10796. }
  10797. void BfModule::ValidateCustomAttributes(BfCustomAttributes* customAttributes, BfAttributeTargets attrTarget, bool force)
  10798. {
  10799. if (attrTarget == BfAttributeTargets_SkipValidate)
  10800. return;
  10801. for (auto& customAttribute : customAttributes->mAttributes)
  10802. {
  10803. if (!customAttribute.mAwaitingValidation)
  10804. continue;
  10805. if ((customAttribute.mType->mAttributeData->mAttributeTargets & attrTarget) == 0)
  10806. {
  10807. if ((customAttribute.mIsMultiUse) && (!force))
  10808. continue;
  10809. Fail(StrFormat("Attribute '%s' is not valid on this declaration type. It is only valid on %s.",
  10810. customAttribute.GetRefNode()->ToString().c_str(), GetAttributesTargetListString(customAttribute.mType->mAttributeData->mAttributeTargets).c_str()), customAttribute.mRef->mAttributeTypeRef); // CS0592
  10811. }
  10812. customAttribute.mAwaitingValidation = false;
  10813. }
  10814. }
  10815. void BfModule::GetCustomAttributes(BfCustomAttributes* customAttributes, BfAttributeDirective* attributesDirective, BfAttributeTargets attrTarget, BfGetCustomAttributesFlags flags, BfCaptureInfo* captureInfo)
  10816. {
  10817. bool allowNonConstArgs = (flags & BfGetCustomAttributesFlags_AllowNonConstArgs) != 0;
  10818. bool keepConstsInModule = (flags & BfGetCustomAttributesFlags_KeepConstsInModule) != 0;
  10819. if (!mCompiler->mHasRequiredTypes)
  10820. return;
  10821. if ((attributesDirective != NULL) && (mCompiler->mResolvePassData != NULL))
  10822. {
  10823. if (auto sourceClassifier = mCompiler->mResolvePassData->GetSourceClassifier(attributesDirective))
  10824. sourceClassifier->VisitChild(attributesDirective);
  10825. }
  10826. SetAndRestoreValue<bool> prevIsCapturingMethodMatchInfo;
  10827. if (mCompiler->IsAutocomplete())
  10828. prevIsCapturingMethodMatchInfo.Init(mCompiler->mResolvePassData->mAutoComplete->mIsCapturingMethodMatchInfo, false);
  10829. BfTypeInstance* baseAttrTypeInst = mContext->mUnreifiedModule->ResolveTypeDef(mCompiler->mAttributeTypeDef)->ToTypeInstance();
  10830. BfAttributeTargets targetOverride = (BfAttributeTargets)0;
  10831. BfTypeDef* activeTypeDef = GetActiveTypeDef();
  10832. BfAutoComplete* autoComplete = NULL;
  10833. if (mCompiler->mResolvePassData != NULL)
  10834. autoComplete = mCompiler->mResolvePassData->mAutoComplete;
  10835. for (; attributesDirective != NULL; attributesDirective = attributesDirective->mNextAttribute)
  10836. {
  10837. if (auto tokenNode = BfNodeDynCast<BfTokenNode>(attributesDirective->mAttributeTargetSpecifier))
  10838. {
  10839. if (captureInfo == NULL)
  10840. {
  10841. Fail("Capture specifiers can only be used in lambda allocations", tokenNode);
  10842. continue;
  10843. }
  10844. BfCaptureInfo::Entry captureEntry;
  10845. captureEntry.mRefNode = tokenNode;
  10846. captureEntry.mCaptureType = BfCaptureType_Copy;
  10847. if (tokenNode->mToken == BfToken_Ampersand)
  10848. captureEntry.mCaptureType = BfCaptureType_Reference;
  10849. if (tokenNode->mToken == BfToken_Question)
  10850. captureEntry.mCaptureType = BfCaptureType_Auto;
  10851. if (!attributesDirective->mArguments.IsEmpty())
  10852. {
  10853. if (auto identifierNode = BfNodeDynCast<BfIdentifierNode>(attributesDirective->mArguments[0]))
  10854. captureEntry.mNameNode = identifierNode;
  10855. else if (auto thisExpr = BfNodeDynCast<BfThisExpression>(attributesDirective->mArguments[0]))
  10856. {
  10857. captureEntry.mNameNode = thisExpr;
  10858. }
  10859. if ((captureEntry.mNameNode != NULL) && (autoComplete != NULL))
  10860. autoComplete->CheckIdentifier(captureEntry.mNameNode);
  10861. }
  10862. captureInfo->mCaptures.Add(captureEntry);
  10863. continue;
  10864. }
  10865. BfAutoParentNodeEntry autoParentNodeEntry(this, attributesDirective);
  10866. BfCustomAttribute customAttribute;
  10867. customAttribute.mAwaitingValidation = true;
  10868. customAttribute.mDeclaringType = activeTypeDef;
  10869. customAttribute.mRef = attributesDirective;
  10870. customAttribute.mIsMultiUse = attributesDirective->mIsMultiUse;
  10871. if (attributesDirective->mAttrOpenToken != NULL)
  10872. targetOverride = (BfAttributeTargets)0;
  10873. if (attributesDirective->mAttributeTypeRef == NULL)
  10874. {
  10875. AssertErrorState();
  10876. continue;
  10877. }
  10878. BfType* attrType;
  10879. if (mContext->mCurTypeState != NULL)
  10880. {
  10881. SetAndRestoreValue<BfTypeReference*> prevTypeRef(mContext->mCurTypeState->mCurAttributeTypeRef, attributesDirective->mAttributeTypeRef);
  10882. attrType = ResolveTypeRef(attributesDirective->mAttributeTypeRef, BfPopulateType_Identity, (BfResolveTypeRefFlags)(BfResolveTypeRefFlag_Attribute | BfResolveTypeRefFlag_NoReify));
  10883. }
  10884. else
  10885. {
  10886. attrType = ResolveTypeRef(attributesDirective->mAttributeTypeRef, BfPopulateType_Identity, (BfResolveTypeRefFlags)(BfResolveTypeRefFlag_Attribute | BfResolveTypeRefFlag_NoReify));
  10887. }
  10888. BfTypeDef* attrTypeDef = NULL;
  10889. if ((attrType != NULL) && (attrType->IsTypeInstance()))
  10890. attrTypeDef = attrType->ToTypeInstance()->mTypeDef;
  10891. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL))
  10892. {
  10893. mCompiler->mResolvePassData->mAutoComplete->CheckAttributeTypeRef(attributesDirective->mAttributeTypeRef);
  10894. if (attrTypeDef != NULL)
  10895. mCompiler->mResolvePassData->HandleTypeReference(attributesDirective->mAttributeTypeRef, attrTypeDef);
  10896. }
  10897. bool isBypassedAttr = false;
  10898. if (attrTypeDef != NULL)
  10899. {
  10900. // 'Object' has some dependencies on some attributes, but those attributes are classes so we have a circular dependency issue
  10901. // We solve it by having a 'bypass' for known attributes that Object depends on
  10902. if ((attributesDirective->mArguments.empty()) && (autoComplete == NULL) && (attrType != NULL) && (attrType->IsTypeInstance()))
  10903. {
  10904. if (attrType->IsInstanceOf(mCompiler->mCReprAttributeTypeDef))
  10905. {
  10906. for (auto methodDef : attrTypeDef->mMethods)
  10907. {
  10908. if ((methodDef->mMethodType == BfMethodType_Ctor) && (methodDef->mProtection == BfProtection_Public))
  10909. {
  10910. customAttribute.mType = attrType->ToTypeInstance();
  10911. customAttribute.mCtor = methodDef;
  10912. isBypassedAttr = true;
  10913. break;
  10914. }
  10915. }
  10916. }
  10917. }
  10918. if (isBypassedAttr)
  10919. {
  10920. customAttribute.mAwaitingValidation = false;
  10921. customAttributes->mAttributes.push_back(customAttribute);
  10922. continue;
  10923. }
  10924. SetAndRestoreValue<BfTypeInstance*> prevCurTypeInst(mContext->mUnreifiedModule->mCurTypeInstance, mCurTypeInstance);
  10925. SetAndRestoreValue<BfMethodInstance*> prevCurMethodInst(mContext->mUnreifiedModule->mCurMethodInstance, mCurMethodInstance);
  10926. if (mContext->mCurTypeState != NULL)
  10927. {
  10928. SetAndRestoreValue<BfTypeReference*> prevTypeRef(mContext->mCurTypeState->mCurAttributeTypeRef, attributesDirective->mAttributeTypeRef);
  10929. mContext->mUnreifiedModule->ResolveTypeResult(attributesDirective->mAttributeTypeRef, attrType, BfPopulateType_BaseType, (BfResolveTypeRefFlags)0);
  10930. }
  10931. else
  10932. {
  10933. mContext->mUnreifiedModule->ResolveTypeResult(attributesDirective->mAttributeTypeRef, attrType, BfPopulateType_BaseType, (BfResolveTypeRefFlags)0);
  10934. }
  10935. }
  10936. BfTypeInstance* attrTypeInst = NULL;
  10937. if (attrType == NULL)
  10938. continue;
  10939. attrTypeInst = attrType->ToTypeInstance();
  10940. if ((attrTypeInst != NULL) && (attrTypeInst->mDefineState != BfTypeDefineState_DefinedAndMethodsSlotting))
  10941. mContext->mUnreifiedModule->PopulateType(attrType, BfPopulateType_DataAndMethods);
  10942. if ((attrTypeInst == NULL) || (!TypeIsSubTypeOf(attrTypeInst, baseAttrTypeInst)) || (attrTypeInst->mAttributeData == NULL))
  10943. {
  10944. Fail(StrFormat("'%s' is not an attribute class", TypeToString(attrType).c_str()), attributesDirective->mAttributeTypeRef); //CS0616
  10945. continue;
  10946. }
  10947. if ((mIsReified) && (attrTypeInst->mAttributeData != NULL) && ((attrTypeInst->mAttributeData->mFlags & BfAttributeFlag_ReflectAttribute) != 0))
  10948. {
  10949. // Reify attribute
  10950. PopulateType(attrTypeInst);
  10951. }
  10952. if (mCurTypeInstance != NULL)
  10953. AddDependency(attrTypeInst, mCurTypeInstance, BfDependencyMap::DependencyFlag_CustomAttribute);
  10954. customAttribute.mType = attrTypeInst;
  10955. bool allocatedMethodState = NULL;
  10956. defer(
  10957. {
  10958. if (allocatedMethodState)
  10959. {
  10960. delete mCurMethodState;
  10961. mCurMethodState = NULL;
  10962. }
  10963. });
  10964. if (mCurMethodState == NULL)
  10965. {
  10966. allocatedMethodState = true;
  10967. mCurMethodState = new BfMethodState();
  10968. mCurMethodState->mTempKind = BfMethodState::TempKind_Static;
  10969. }
  10970. BfConstResolver constResolver(this);
  10971. if (allowNonConstArgs)
  10972. constResolver.mBfEvalExprFlags = (BfEvalExprFlags)(constResolver.mBfEvalExprFlags | BfEvalExprFlags_AllowNonConst);
  10973. bool inPropSet = false;
  10974. SizedArray<BfResolvedArg, 2> argValues;
  10975. for (BfExpression* arg : attributesDirective->mArguments)
  10976. {
  10977. if (arg == NULL)
  10978. {
  10979. continue;
  10980. }
  10981. if (autoComplete != NULL)
  10982. autoComplete->mShowAttributeProperties = attrTypeInst;
  10983. if (auto assignExpr = BfNodeDynCast<BfAssignmentExpression>(arg))
  10984. {
  10985. inPropSet = true;
  10986. if (autoComplete != NULL)
  10987. autoComplete->CheckNode(assignExpr->mLeft, true);
  10988. String findName = assignExpr->mLeft->ToString();
  10989. BfPropertyDef* bestProp = NULL;
  10990. BfTypeInstance* bestPropTypeInst = NULL;
  10991. BfFieldDef* bestField = NULL;
  10992. BfTypeInstance* bestFieldTypeInst = NULL;
  10993. auto checkTypeInst = attrTypeInst;
  10994. while (checkTypeInst != NULL)
  10995. {
  10996. mContext->mUnreifiedModule->PopulateType(checkTypeInst, BfPopulateType_Data);
  10997. for (auto prop : checkTypeInst->mTypeDef->mProperties)
  10998. {
  10999. if (prop->mName == findName)
  11000. {
  11001. if ((bestProp == NULL) || (bestProp->mProtection != BfProtection_Public))
  11002. {
  11003. bestProp = prop;
  11004. bestPropTypeInst = checkTypeInst;
  11005. }
  11006. }
  11007. }
  11008. for (auto field : checkTypeInst->mTypeDef->mFields)
  11009. {
  11010. if (field->mName == findName)
  11011. {
  11012. if ((bestField == NULL) || (bestField->mProtection != BfProtection_Public))
  11013. {
  11014. bestField = field;
  11015. bestFieldTypeInst = checkTypeInst;
  11016. }
  11017. }
  11018. }
  11019. if ((bestProp != NULL) || (bestField != NULL))
  11020. break;
  11021. checkTypeInst = checkTypeInst->mBaseType;
  11022. }
  11023. bool handledExpr = false;
  11024. if (bestField != NULL)
  11025. {
  11026. handledExpr = true;
  11027. if (mCompiler->mResolvePassData != NULL)
  11028. {
  11029. mCompiler->mResolvePassData->HandleFieldReference(assignExpr->mLeft, attrTypeDef, bestField);
  11030. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(assignExpr->mLeft)))
  11031. {
  11032. autoComplete->mDefField = bestField;
  11033. autoComplete->mDefType = attrTypeDef;
  11034. }
  11035. }
  11036. if (bestField->mProtection != BfProtection_Public)
  11037. Fail(StrFormat("'%s.%s' is inaccessible due to its protection level", TypeToString(bestFieldTypeInst).c_str(), findName.c_str()), assignExpr->mLeft); // CS0122
  11038. AddDependency(bestFieldTypeInst, mCurTypeInstance, BfDependencyMap::DependencyFlag_CustomAttribute);
  11039. BfCustomAttributeSetField setField;
  11040. setField.mFieldRef = BfFieldRef(bestFieldTypeInst, bestField);
  11041. auto& fieldTypeInst = checkTypeInst->mFieldInstances[bestField->mIdx];
  11042. if (assignExpr->mRight != NULL)
  11043. {
  11044. BfTypedValue result = constResolver.Resolve(assignExpr->mRight, fieldTypeInst.mResolvedType, BfConstResolveFlag_NoActualizeValues);
  11045. if (result)
  11046. {
  11047. if (!keepConstsInModule)
  11048. CurrentAddToConstHolder(result.mValue);
  11049. setField.mParam = result;
  11050. customAttribute.mSetField.push_back(setField);
  11051. }
  11052. }
  11053. }
  11054. else if (bestProp == NULL)
  11055. {
  11056. Fail(StrFormat("'%s' does not contain a field or property named '%s'", TypeToString(attrTypeInst).c_str(), findName.c_str()), assignExpr->mLeft);
  11057. }
  11058. else
  11059. {
  11060. BfMethodDef* setMethod = NULL;
  11061. for (auto methodDef : bestProp->mMethods)
  11062. {
  11063. if (methodDef->mMethodType == BfMethodType_PropertySetter)
  11064. {
  11065. setMethod = methodDef;
  11066. break;
  11067. }
  11068. }
  11069. if (setMethod == NULL)
  11070. {
  11071. Fail("Property has no setter", assignExpr->mLeft);
  11072. }
  11073. else
  11074. {
  11075. if (mCompiler->mResolvePassData != NULL)
  11076. {
  11077. mCompiler->mResolvePassData->HandlePropertyReference(assignExpr->mLeft, attrTypeDef, bestProp);
  11078. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(assignExpr->mLeft)))
  11079. {
  11080. autoComplete->mDefProp = bestProp;
  11081. autoComplete->mDefType = attrTypeDef;
  11082. }
  11083. }
  11084. handledExpr = true;
  11085. if (bestProp->mProtection != BfProtection_Public)
  11086. Fail(StrFormat("'%s.%s' is inaccessible due to its protection level", TypeToString(bestPropTypeInst).c_str(), findName.c_str()), assignExpr->mLeft); // CS0122
  11087. BfResolvedArg resolvedArg;
  11088. AddDependency(bestPropTypeInst, mCurTypeInstance, BfDependencyMap::DependencyFlag_CustomAttribute);
  11089. BfCustomAttributeSetProperty setProperty;
  11090. setProperty.mPropertyRef = BfPropertyRef(bestPropTypeInst, bestProp);
  11091. // We don't actually need the mFunc, so get the ModuleMethodInstance from the native module
  11092. auto methodInstance = bestPropTypeInst->mModule->GetMethodInstance(bestPropTypeInst, setMethod, BfTypeVector());
  11093. if (methodInstance.mMethodInstance != NULL)
  11094. {
  11095. auto propType = methodInstance.mMethodInstance->GetParamType(0);
  11096. if (assignExpr->mRight != NULL)
  11097. {
  11098. BfTypedValue result = constResolver.Resolve(assignExpr->mRight, propType, BfConstResolveFlag_NoActualizeValues);
  11099. if ((result) && (!result.mType->IsVar()))
  11100. {
  11101. if (!result.mValue.IsConst())
  11102. result = GetDefaultTypedValue(result.mType);
  11103. BF_ASSERT(result.mType == propType);
  11104. if (!keepConstsInModule)
  11105. CurrentAddToConstHolder(result.mValue);
  11106. setProperty.mParam = result;
  11107. customAttribute.mSetProperties.push_back(setProperty);
  11108. }
  11109. }
  11110. }
  11111. }
  11112. }
  11113. if ((!handledExpr) && (assignExpr->mRight != NULL))
  11114. constResolver.Resolve(assignExpr->mRight, NULL, BfConstResolveFlag_NoActualizeValues);
  11115. }
  11116. else
  11117. {
  11118. if (inPropSet)
  11119. {
  11120. Fail("Named attribute argument expected", arg); // CS1016
  11121. }
  11122. BfDeferEvalChecker deferEvalChecker;
  11123. arg->Accept(&deferEvalChecker);
  11124. bool deferParamEval = deferEvalChecker.mNeedsDeferEval;
  11125. BfResolvedArg resolvedArg;
  11126. resolvedArg.mExpression = arg;
  11127. if (deferParamEval)
  11128. {
  11129. resolvedArg.mArgFlags = BfArgFlag_DeferredEval;
  11130. }
  11131. else
  11132. resolvedArg.mTypedValue = constResolver.Resolve(arg, NULL, BfConstResolveFlag_NoActualizeValues);
  11133. if (!inPropSet)
  11134. {
  11135. argValues.push_back(resolvedArg);
  11136. }
  11137. }
  11138. if (autoComplete != NULL)
  11139. autoComplete->mShowAttributeProperties = NULL;
  11140. }
  11141. auto wasCapturingMethodInfo = false;
  11142. if (autoComplete != NULL)
  11143. {
  11144. wasCapturingMethodInfo = autoComplete->mIsCapturingMethodMatchInfo;
  11145. if (attributesDirective->mCtorOpenParen != NULL)
  11146. autoComplete->CheckInvocation(attributesDirective, attributesDirective->mCtorOpenParen, attributesDirective->mCtorCloseParen, attributesDirective->mCommas);
  11147. }
  11148. BfMethodMatcher methodMatcher(attributesDirective, this, "", argValues, BfMethodGenericArguments());
  11149. methodMatcher.mBfEvalExprFlags = constResolver.mBfEvalExprFlags;
  11150. attrTypeDef = attrTypeInst->mTypeDef;
  11151. bool success = true;
  11152. int methodCheckCount = 0;
  11153. bool isFailurePass = false;
  11154. for (int pass = 0; pass < 2; pass++)
  11155. {
  11156. bool isFailurePass = pass == 1;
  11157. for (auto checkMethod : attrTypeDef->mMethods)
  11158. {
  11159. if ((isFailurePass) && (checkMethod->mMethodDeclaration == NULL))
  11160. continue; // Don't match private default ctor if there's a user-defined one
  11161. if ((checkMethod->mIsStatic) || (checkMethod->mMethodType != BfMethodType_Ctor))
  11162. continue;
  11163. if ((!isFailurePass) && (!CheckProtection(checkMethod->mProtection, attrTypeInst->mTypeDef, false, false)))
  11164. continue;
  11165. methodCheckCount++;
  11166. methodMatcher.CheckMethod(NULL, attrTypeInst, checkMethod, isFailurePass);
  11167. }
  11168. if ((methodMatcher.mBestMethodDef != NULL) || (methodMatcher.mBackupMethodDef != NULL))
  11169. break;
  11170. }
  11171. if (autoComplete != NULL)
  11172. {
  11173. if ((wasCapturingMethodInfo) && (!autoComplete->mIsCapturingMethodMatchInfo))
  11174. {
  11175. autoComplete->mIsCapturingMethodMatchInfo = true;
  11176. BF_ASSERT(autoComplete->mMethodMatchInfo != NULL);
  11177. }
  11178. else
  11179. autoComplete->mIsCapturingMethodMatchInfo = false;
  11180. }
  11181. if (methodMatcher.mBestMethodDef == NULL)
  11182. methodMatcher.mBestMethodDef = methodMatcher.mBackupMethodDef;
  11183. if (methodMatcher.mBestMethodDef == NULL)
  11184. {
  11185. if (methodCheckCount == 0)
  11186. Fail(StrFormat("No attribute constructors found for type '%s'", TypeToString(attrTypeInst).c_str()), attributesDirective);
  11187. AssertErrorState();
  11188. continue;
  11189. }
  11190. BF_ASSERT(methodMatcher.mBestMethodDef != NULL);
  11191. customAttribute.mCtor = methodMatcher.mBestMethodDef;
  11192. if (methodMatcher.mBestMethodTypeInstance == mCurTypeInstance)
  11193. {
  11194. Fail("Custom attribute circular reference", attributesDirective);
  11195. }
  11196. if (mCurTypeInstance != NULL)
  11197. AddDependency(methodMatcher.mBestMethodTypeInstance, mCurTypeInstance, BfDependencyMap::DependencyFlag_CustomAttribute);
  11198. if (!constResolver.PrepareMethodArguments(attributesDirective->mAttributeTypeRef, &methodMatcher, customAttribute.mCtorArgs))
  11199. success = false;
  11200. for (auto& arg : argValues)
  11201. {
  11202. if ((arg.mArgFlags & BfArgFlag_DeferredEval) != 0)
  11203. {
  11204. if (auto expr = BfNodeDynCast<BfExpression>(arg.mExpression))
  11205. constResolver.Resolve(expr, NULL, BfConstResolveFlag_NoActualizeValues);
  11206. }
  11207. }
  11208. // Move all those to the constHolder
  11209. if (!keepConstsInModule)
  11210. {
  11211. for (auto& ctorArg : customAttribute.mCtorArgs)
  11212. {
  11213. if (ctorArg.IsConst())
  11214. CurrentAddToConstHolder(ctorArg);
  11215. }
  11216. }
  11217. if (attributesDirective->mAttributeTargetSpecifier != NULL)
  11218. {
  11219. targetOverride = BfAttributeTargets_ReturnValue;
  11220. if (attrTarget != BfAttributeTargets_Method)
  11221. {
  11222. 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.",
  11223. GetAttributesTargetListString(targetOverride).c_str(), GetAttributesTargetListString(attrTarget).c_str()), attributesDirective->mAttributeTargetSpecifier); // CS0657
  11224. success = false;
  11225. }
  11226. }
  11227. if ((success) && (targetOverride != (BfAttributeTargets)0))
  11228. {
  11229. if ((mCurMethodInstance != NULL) && (targetOverride == BfAttributeTargets_ReturnValue) && (attrTarget == BfAttributeTargets_Method))
  11230. {
  11231. auto methodInfoEx = mCurMethodInstance->GetMethodInfoEx();
  11232. if (methodInfoEx->mMethodCustomAttributes == NULL)
  11233. methodInfoEx->mMethodCustomAttributes = new BfMethodCustomAttributes();
  11234. if (success)
  11235. {
  11236. if (methodInfoEx->mMethodCustomAttributes->mReturnCustomAttributes == NULL)
  11237. methodInfoEx->mMethodCustomAttributes->mReturnCustomAttributes = new BfCustomAttributes();
  11238. methodInfoEx->mMethodCustomAttributes->mReturnCustomAttributes->mAttributes.push_back(customAttribute);
  11239. }
  11240. }
  11241. // Mark as failed since we don't actually want to add this to the custom attributes set
  11242. success = false;
  11243. }
  11244. if (success)
  11245. {
  11246. if ((attrTypeInst->mAttributeData->mFlags & BfAttributeFlag_DisallowAllowMultiple) != 0)
  11247. {
  11248. for (auto& prevCustomAttribute : customAttributes->mAttributes)
  11249. {
  11250. if (prevCustomAttribute.mType == attrTypeInst)
  11251. {
  11252. Fail(StrFormat("Duplicate '%s' attribute", attributesDirective->mAttributeTypeRef->ToCleanAttributeString().c_str()), attributesDirective->mAttributeTypeRef); // CS0579
  11253. }
  11254. }
  11255. }
  11256. }
  11257. if (success)
  11258. {
  11259. customAttributes->mAttributes.push_back(customAttribute);
  11260. }
  11261. }
  11262. ValidateCustomAttributes(customAttributes, attrTarget);
  11263. }
  11264. BfCustomAttributes* BfModule::GetCustomAttributes(BfAttributeDirective* attributesDirective, BfAttributeTargets attrType, BfGetCustomAttributesFlags flags, BfCaptureInfo* captureInfo)
  11265. {
  11266. BfCustomAttributes* customAttributes = new BfCustomAttributes();
  11267. GetCustomAttributes(customAttributes, attributesDirective, attrType, flags, captureInfo);
  11268. return customAttributes;
  11269. }
  11270. BfCustomAttributes* BfModule::GetCustomAttributes(BfTypeDef* typeDef)
  11271. {
  11272. BF_ASSERT(mCompiler->IsAutocomplete());
  11273. BfAttributeTargets attrTarget;
  11274. if (typeDef->mIsDelegate)
  11275. attrTarget = BfAttributeTargets_Delegate;
  11276. else if (typeDef->mIsFunction)
  11277. attrTarget = BfAttributeTargets_Function;
  11278. else if (typeDef->mTypeCode == BfTypeCode_Enum)
  11279. attrTarget = BfAttributeTargets_Enum;
  11280. else if (typeDef->mTypeCode == BfTypeCode_Interface)
  11281. attrTarget = BfAttributeTargets_Interface;
  11282. else if (typeDef->mTypeCode == BfTypeCode_Struct)
  11283. attrTarget = BfAttributeTargets_Struct;
  11284. else if (typeDef->mTypeCode == BfTypeCode_Extension)
  11285. attrTarget = (BfAttributeTargets)(BfAttributeTargets_Struct | BfAttributeTargets_Class | BfAttributeTargets_Interface | BfAttributeTargets_Enum);
  11286. else
  11287. attrTarget = BfAttributeTargets_Class;
  11288. return GetCustomAttributes(typeDef->mTypeDeclaration->mAttributes, attrTarget);
  11289. }
  11290. void BfModule::FinishAttributeState(BfAttributeState* attributeState)
  11291. {
  11292. if ((!attributeState->mUsed) && (attributeState->mSrc != NULL))
  11293. Warn(0, "Unused attributes", attributeState->mSrc);
  11294. }
  11295. void BfModule::ProcessTypeInstCustomAttributes(int& packing, bool& isUnion, bool& isCRepr, bool& isOrdered, int& alignOverride, BfType*& underlyingArrayType, int& underlyingArraySize)
  11296. {
  11297. if (mCurTypeInstance->mTypeDef->mIsAlwaysInclude)
  11298. mCurTypeInstance->mAlwaysIncludeFlags = (BfAlwaysIncludeFlags)(mCurTypeInstance->mAlwaysIncludeFlags | BfAlwaysIncludeFlag_Type);
  11299. if (mCurTypeInstance->mCustomAttributes != NULL)
  11300. {
  11301. for (auto& customAttribute : mCurTypeInstance->mCustomAttributes->mAttributes)
  11302. {
  11303. String typeName = TypeToString(customAttribute.mType);
  11304. if (typeName == "System.PackedAttribute")
  11305. {
  11306. packing = 1;
  11307. if (customAttribute.mCtorArgs.size() >= 1)
  11308. {
  11309. auto alignConstant = mCurTypeInstance->mConstHolder->GetConstant(customAttribute.mCtorArgs[0]);
  11310. int checkPacking = alignConstant->mInt32;
  11311. if (((checkPacking & (checkPacking - 1)) == 0) && (packing > 0) && (packing < 256))
  11312. packing = checkPacking;
  11313. else
  11314. Fail("Packing must be a power of 2", customAttribute.GetRefNode());
  11315. }
  11316. }
  11317. else if (typeName == "System.UnionAttribute")
  11318. {
  11319. isUnion = true;
  11320. }
  11321. else if (typeName == "System.CReprAttribute")
  11322. {
  11323. isCRepr = true;
  11324. isOrdered = true;
  11325. }
  11326. else if (typeName == "System.OrderedAttribute")
  11327. {
  11328. isOrdered = true;
  11329. }
  11330. else if (typeName == "System.AlwaysIncludeAttribute")
  11331. {
  11332. mCurTypeInstance->mAlwaysIncludeFlags = (BfAlwaysIncludeFlags)(mCurTypeInstance->mAlwaysIncludeFlags | BfAlwaysIncludeFlag_Type);
  11333. for (auto setProp : customAttribute.mSetProperties)
  11334. {
  11335. BfPropertyDef* propertyDef = setProp.mPropertyRef;
  11336. if (propertyDef->mName == "AssumeInstantiated")
  11337. {
  11338. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  11339. if ((constant != NULL) && (constant->mBool))
  11340. mCurTypeInstance->mAlwaysIncludeFlags = (BfAlwaysIncludeFlags)(mCurTypeInstance->mAlwaysIncludeFlags | BfAlwaysIncludeFlag_AssumeInstantiated);
  11341. }
  11342. else if (propertyDef->mName == "IncludeAllMethods")
  11343. {
  11344. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  11345. if ((constant != NULL) && (constant->mBool))
  11346. mCurTypeInstance->mAlwaysIncludeFlags = (BfAlwaysIncludeFlags)(mCurTypeInstance->mAlwaysIncludeFlags | BfAlwaysIncludeFlag_IncludeAllMethods);
  11347. }
  11348. }
  11349. }
  11350. else if (typeName == "System.AlignAttribute")
  11351. {
  11352. if (customAttribute.mCtorArgs.size() >= 1)
  11353. {
  11354. auto alignConstant = mCurTypeInstance->mConstHolder->GetConstant(customAttribute.mCtorArgs[0]);
  11355. int checkAlign = alignConstant->mInt32;
  11356. if ((checkAlign & (checkAlign - 1)) == 0)
  11357. alignOverride = checkAlign;
  11358. else
  11359. Fail("Alignment must be a power of 2", customAttribute.GetRefNode());
  11360. }
  11361. }
  11362. else if (typeName == "System.UnderlyingArrayAttribute")
  11363. {
  11364. if (customAttribute.mCtorArgs.size() >= 2)
  11365. {
  11366. auto typeConstant = mCurTypeInstance->mConstHolder->GetConstant(customAttribute.mCtorArgs[0]);
  11367. auto sizeConstant = mCurTypeInstance->mConstHolder->GetConstant(customAttribute.mCtorArgs[1]);
  11368. if ((typeConstant != NULL) && (sizeConstant != NULL) && (typeConstant->mConstType == BfConstType_TypeOf))
  11369. {
  11370. underlyingArrayType = (BfType*)(intptr)typeConstant->mInt64;
  11371. underlyingArraySize = sizeConstant->mInt32;
  11372. }
  11373. }
  11374. }
  11375. if (customAttribute.mType->mAttributeData == NULL)
  11376. PopulateType(customAttribute.mType);
  11377. BF_ASSERT(customAttribute.mType->mAttributeData != NULL);
  11378. if ((customAttribute.mType->mAttributeData != NULL) && ((customAttribute.mType->mAttributeData->mAlwaysIncludeUser & BfAlwaysIncludeFlag_AssumeInstantiated) != 0))
  11379. mCurTypeInstance->mAlwaysIncludeFlags = (BfAlwaysIncludeFlags)(mCurTypeInstance->mAlwaysIncludeFlags | customAttribute.mType->mAttributeData->mAlwaysIncludeUser);
  11380. }
  11381. }
  11382. }
  11383. // Checking to see if we're an attribute or not
  11384. void BfModule::ProcessCustomAttributeData()
  11385. {
  11386. if (mCurTypeInstance->mAttributeData != NULL)
  11387. return;
  11388. bool isAttribute = false;
  11389. auto checkTypeInst = mCurTypeInstance->mBaseType;
  11390. while (checkTypeInst != NULL)
  11391. {
  11392. if (checkTypeInst->IsInstanceOf(mCompiler->mAttributeTypeDef))
  11393. isAttribute = true;
  11394. checkTypeInst = checkTypeInst->mBaseType;
  11395. }
  11396. if (!isAttribute)
  11397. return;
  11398. auto attributeData = new BfAttributeData();
  11399. bool hasCustomAttribute = false;
  11400. if (mCurTypeInstance->mCustomAttributes != NULL)
  11401. {
  11402. for (auto& customAttribute : mCurTypeInstance->mCustomAttributes->mAttributes)
  11403. {
  11404. if (customAttribute.mType->IsInstanceOf(mCompiler->mAttributeUsageAttributeTypeDef))
  11405. {
  11406. if (customAttribute.mCtorArgs.size() > 0)
  11407. {
  11408. auto constant = mCurTypeInstance->mConstHolder->GetConstant(customAttribute.mCtorArgs[0]);
  11409. if ((constant != NULL) && (mBfIRBuilder->IsInt(constant->mTypeCode)))
  11410. attributeData->mAttributeTargets = (BfAttributeTargets)constant->mInt32;
  11411. }
  11412. if (customAttribute.mCtorArgs.size() == 2)
  11413. {
  11414. auto constant = mCurTypeInstance->mConstHolder->GetConstant(customAttribute.mCtorArgs[0]);
  11415. if ((constant != NULL) && (mBfIRBuilder->IsInt(constant->mTypeCode)))
  11416. {
  11417. attributeData->mFlags = (BfAttributeFlags)constant->mInt32;
  11418. }
  11419. }
  11420. for (auto& setProp : customAttribute.mSetProperties)
  11421. {
  11422. BfPropertyDef* propDef = setProp.mPropertyRef;
  11423. if (propDef->mName == "AllowMultiple")
  11424. {
  11425. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  11426. if ((constant != NULL) && (constant->mBool))
  11427. attributeData->mFlags = (BfAttributeFlags)(attributeData->mFlags & ~BfAttributeFlag_DisallowAllowMultiple);
  11428. else
  11429. attributeData->mFlags = (BfAttributeFlags)(attributeData->mFlags | BfAttributeFlag_DisallowAllowMultiple);
  11430. }
  11431. else if (propDef->mName == "Inherited")
  11432. {
  11433. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  11434. if ((constant != NULL) && (constant->mBool))
  11435. attributeData->mFlags = (BfAttributeFlags)(attributeData->mFlags & ~BfAttributeFlag_NotInherited);
  11436. else
  11437. attributeData->mFlags = (BfAttributeFlags)(attributeData->mFlags | BfAttributeFlag_NotInherited);
  11438. }
  11439. else if (propDef->mName == "ValidOn")
  11440. {
  11441. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  11442. if (constant != NULL)
  11443. attributeData->mAttributeTargets = (BfAttributeTargets)constant->mInt32;
  11444. }
  11445. else if (propDef->mName == "AlwaysIncludeUser")
  11446. {
  11447. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  11448. if (constant != NULL)
  11449. attributeData->mAlwaysIncludeUser = (BfAlwaysIncludeFlags)constant->mInt32;
  11450. }
  11451. }
  11452. hasCustomAttribute = true;
  11453. }
  11454. }
  11455. }
  11456. if ((!hasCustomAttribute) && (mCurTypeInstance->mBaseType->mAttributeData != NULL))
  11457. {
  11458. attributeData->mAttributeTargets = mCurTypeInstance->mBaseType->mAttributeData->mAttributeTargets;
  11459. attributeData->mFlags = mCurTypeInstance->mBaseType->mAttributeData->mFlags;
  11460. attributeData->mAlwaysIncludeUser = mCurTypeInstance->mBaseType->mAttributeData->mAlwaysIncludeUser;
  11461. }
  11462. mCurTypeInstance->mAttributeData = attributeData;
  11463. }
  11464. bool BfModule::TryGetConstString(BfIRConstHolder* constHolder, BfIRValue irValue, StringImpl& str)
  11465. {
  11466. auto constant = constHolder->GetConstant(irValue);
  11467. if (constant == NULL)
  11468. return false;
  11469. if (constant->mTypeCode != BfTypeCode_StringId)
  11470. return false;
  11471. int stringId = constant->mInt32;
  11472. BfStringPoolEntry* entry = NULL;
  11473. if (mContext->mStringObjectIdMap.TryGetValue(stringId, &entry))
  11474. {
  11475. str += entry->mString;
  11476. }
  11477. else
  11478. {
  11479. BF_DBG_FATAL("Failed to find string by id");
  11480. }
  11481. return true;
  11482. }
  11483. BfVariant BfModule::TypedValueToVariant(BfAstNode* refNode, const BfTypedValue& value, bool allowUndef)
  11484. {
  11485. BfVariant variant;
  11486. variant.mTypeCode = BfTypeCode_None;
  11487. BfType* primType = NULL;
  11488. if (value.mType->IsPrimitiveType())
  11489. primType = (BfPrimitiveType*)value.mType;
  11490. else if (value.mType->IsTypedPrimitive())
  11491. primType = value.mType->GetUnderlyingType();
  11492. else if (value.mType->IsInstanceOf(mCompiler->mStringTypeDef))
  11493. primType = value.mType;
  11494. if (primType)
  11495. {
  11496. auto constant = mBfIRBuilder->GetConstant(value.mValue);
  11497. if (constant != NULL)
  11498. {
  11499. if ((allowUndef) && (constant->mConstType == BfConstType_Undef))
  11500. {
  11501. variant.mUInt64 = 0;
  11502. variant.mTypeCode = BfTypeCode_Let;
  11503. return variant;
  11504. }
  11505. if (constant->mConstType == BfConstType_GlobalVar)
  11506. {
  11507. int stringIdx = GetStringPoolIdx(value.mValue, mBfIRBuilder);
  11508. if (stringIdx != -1)
  11509. {
  11510. variant.mTypeCode = BfTypeCode_StringId;
  11511. variant.mInt64 = stringIdx;
  11512. return variant;
  11513. }
  11514. }
  11515. switch (constant->mTypeCode)
  11516. {
  11517. case BfTypeCode_Boolean:
  11518. case BfTypeCode_Int8:
  11519. case BfTypeCode_UInt8:
  11520. case BfTypeCode_Int16:
  11521. case BfTypeCode_UInt16:
  11522. case BfTypeCode_Int32:
  11523. case BfTypeCode_UInt32:
  11524. case BfTypeCode_Int64:
  11525. case BfTypeCode_UInt64:
  11526. case BfTypeCode_IntPtr:
  11527. case BfTypeCode_UIntPtr:
  11528. case BfTypeCode_IntUnknown:
  11529. case BfTypeCode_UIntUnknown:
  11530. case BfTypeCode_Double:
  11531. case BfTypeCode_Char8:
  11532. case BfTypeCode_Char16:
  11533. case BfTypeCode_Char32:
  11534. case BfTypeCode_StringId:
  11535. variant.mTypeCode = constant->mTypeCode;
  11536. if (((variant.mTypeCode == BfTypeCode_Int64) || (variant.mTypeCode == BfTypeCode_UInt64)) &&
  11537. (primType->mSize > 0) && (primType->mSize < 8) &&
  11538. (mBfIRBuilder->IsIntable(primType->GetTypeCode())))
  11539. {
  11540. // We may have an 'int unknown' that we need to downsize
  11541. variant.mTypeCode = primType->GetTypeCode();
  11542. }
  11543. variant.mInt64 = constant->mInt64;
  11544. break;
  11545. case BfTypeCode_Float:
  11546. variant.mTypeCode = constant->mTypeCode;
  11547. variant.mSingle = (float)constant->mDouble;
  11548. break;
  11549. default:
  11550. if (refNode != NULL)
  11551. Fail("Invalid const expression type", refNode);
  11552. break;
  11553. }
  11554. }
  11555. }
  11556. else if (value.mType->IsConstExprValue())
  11557. {
  11558. auto constExprType = (BfConstExprValueType*)value.mType;
  11559. return constExprType->mValue;
  11560. }
  11561. else if (value.mType->IsValueType())
  11562. {
  11563. PopulateType(value.mType);
  11564. int allocSize = value.mType->mSize + 4;
  11565. BfVariant::StructData* structData = (BfVariant::StructData*)(new uint8[allocSize]);
  11566. memset(structData, 0, allocSize);
  11567. structData->mSize = value.mType->mSize;
  11568. mBfIRBuilder->WriteConstant(value.mValue, structData->mData, value.mType);
  11569. variant.mTypeCode = BfTypeCode_Struct;
  11570. variant.mPtr = structData;
  11571. }
  11572. return variant;
  11573. }
  11574. BfTypedValue BfModule::RemoveRef(BfTypedValue typedValue, bool makeInReadOnly)
  11575. {
  11576. if ((typedValue.mType != NULL) && (typedValue.mType->IsRef()))
  11577. {
  11578. auto refType = (BfRefType*)typedValue.mType;
  11579. auto elementType = typedValue.mType->GetUnderlyingType();
  11580. if (typedValue.IsAddr())
  11581. {
  11582. if (elementType->IsValuelessType())
  11583. {
  11584. BF_ASSERT(!typedValue.mValue);
  11585. typedValue = BfTypedValue(typedValue.mValue, elementType, true);
  11586. }
  11587. else
  11588. typedValue = BfTypedValue(mBfIRBuilder->CreateAlignedLoad(typedValue.mValue, elementType->mAlign), elementType, true);
  11589. }
  11590. else
  11591. typedValue = BfTypedValue(typedValue.mValue, elementType, true);
  11592. if (typedValue.mType->IsValuelessType())
  11593. {
  11594. BF_ASSERT(typedValue.mValue.IsFake());
  11595. }
  11596. if ((refType->mRefKind == BfRefType::RefKind_In) && (makeInReadOnly))
  11597. {
  11598. if (typedValue.mKind == BfTypedValueKind_Addr)
  11599. typedValue.mKind = BfTypedValueKind_ReadOnlyAddr;
  11600. }
  11601. }
  11602. return typedValue;
  11603. }
  11604. BfTypedValue BfModule::SanitizeAddr(BfTypedValue typedValue)
  11605. {
  11606. if (!typedValue)
  11607. return typedValue;
  11608. if (typedValue.mType->IsRef())
  11609. {
  11610. typedValue = LoadValue(typedValue);
  11611. auto copiedVal = BfTypedValue(CreateAlloca(typedValue.mType), typedValue.mType, true);
  11612. mBfIRBuilder->CreateStore(typedValue.mValue, copiedVal.mValue);
  11613. return copiedVal;
  11614. }
  11615. return typedValue;
  11616. }
  11617. BfTypedValue BfModule::ToRef(BfTypedValue typedValue, BfRefType* refType)
  11618. {
  11619. if (refType == NULL)
  11620. refType = CreateRefType(typedValue.mType);
  11621. if ((refType->mRefKind == BfRefType::RefKind_Mut) && (typedValue.mType->IsObjectOrInterface()))
  11622. {
  11623. return LoadValue(typedValue);
  11624. }
  11625. if (refType->mRefKind == BfRefType::RefKind_Mut)
  11626. refType = CreateRefType(typedValue.mType);
  11627. if (!typedValue.mType->IsValuelessNonOpaqueType())
  11628. typedValue = MakeAddressable(typedValue, false, true);
  11629. return BfTypedValue(typedValue.mValue, refType);
  11630. }
  11631. BfTypedValue BfModule::LoadValue(BfTypedValue typedValue, BfAstNode* refNode, bool isVolatile)
  11632. {
  11633. if (!typedValue.IsAddr())
  11634. return typedValue;
  11635. PopulateType(typedValue.mType);
  11636. if ((typedValue.mType->IsValuelessType()) || (typedValue.mType->IsVar()))
  11637. return BfTypedValue(mBfIRBuilder->GetFakeVal(), typedValue.mType, false);
  11638. if (typedValue.mValue.IsConst())
  11639. {
  11640. auto constantValue = mBfIRBuilder->GetConstant(typedValue.mValue);
  11641. if (constantValue != NULL)
  11642. {
  11643. if (constantValue->mConstType == BfConstType_GlobalVar)
  11644. {
  11645. auto globalVar = (BfGlobalVar*)constantValue;
  11646. if (globalVar->mName[0] == '#')
  11647. {
  11648. BfTypedValue result = GetCompilerFieldValue(globalVar->mName);
  11649. if (result)
  11650. {
  11651. // We want to avoid 'unreachable code' issues from values that
  11652. // are technically constant but change depending on compilation context
  11653. if (mCurMethodState != NULL)
  11654. {
  11655. auto checkScope = mCurMethodState->mCurScope;
  11656. while (checkScope != NULL)
  11657. {
  11658. checkScope->mSupressNextUnreachable = true;
  11659. checkScope = checkScope->mPrevScope;
  11660. }
  11661. }
  11662. return result;
  11663. }
  11664. if (!mIsComptimeModule)
  11665. return GetDefaultTypedValue(typedValue.mType);
  11666. }
  11667. }
  11668. if ((mIsComptimeModule) && (mCompiler->mCeMachine->mDebugger != NULL) && (mCompiler->mCeMachine->mDebugger->mCurDbgState != NULL))
  11669. {
  11670. auto ceDebugger = mCompiler->mCeMachine->mDebugger;
  11671. auto ceContext = ceDebugger->mCurDbgState->mCeContext;
  11672. auto activeFrame = ceDebugger->mCurDbgState->mActiveFrame;
  11673. auto ceTypedValue = ceDebugger->GetAddr(constantValue);
  11674. if (ceTypedValue)
  11675. {
  11676. if ((typedValue.mType->IsObjectOrInterface()) || (typedValue.mType->IsPointer()) || (typedValue.mType->IsRef()))
  11677. {
  11678. void* data = ceContext->GetMemoryPtr((addr_ce)ceTypedValue.mAddr, sizeof(addr_ce));
  11679. if (data == NULL)
  11680. {
  11681. Fail("Invalid address", refNode);
  11682. return GetDefaultTypedValue(typedValue.mType);
  11683. }
  11684. uint64 dataAddr;
  11685. if (mSystem->mPtrSize == 4)
  11686. dataAddr = *(uint32*)data;
  11687. else
  11688. dataAddr = *(uint64*)data;
  11689. return BfTypedValue(mBfIRBuilder->CreateIntToPtr(
  11690. mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, dataAddr), mBfIRBuilder->MapType(typedValue.mType)), typedValue.mType);
  11691. }
  11692. auto constVal = ceContext->CreateConstant(this, ceContext->mMemory.mVals + ceTypedValue.mAddr, typedValue.mType);
  11693. if (!constVal)
  11694. {
  11695. Fail("Failed to create const", refNode);
  11696. return GetDefaultTypedValue(typedValue.mType);
  11697. }
  11698. return BfTypedValue(constVal, typedValue.mType);
  11699. }
  11700. }
  11701. }
  11702. }
  11703. BfIRValue loadedVal = typedValue.mValue;
  11704. if (loadedVal)
  11705. {
  11706. if (typedValue.mType->IsVar())
  11707. {
  11708. return BfTypedValue(loadedVal, typedValue.mType, false);
  11709. }
  11710. PopulateType(typedValue.mType, BfPopulateType_Data);
  11711. loadedVal = mBfIRBuilder->CreateAlignedLoad(loadedVal, std::max(1, (int)typedValue.mType->mAlign), isVolatile || typedValue.IsVolatile());
  11712. }
  11713. return BfTypedValue(loadedVal, typedValue.mType, false);
  11714. }
  11715. BfTypedValue BfModule::PrepareConst(BfTypedValue& typedValue)
  11716. {
  11717. if (!typedValue.mValue.IsConst())
  11718. return typedValue;
  11719. auto constant = mBfIRBuilder->GetConstant(typedValue.mValue);
  11720. if (constant->mTypeCode == BfTypeCode_StringId)
  11721. return GetTypedValueFromConstant(constant, mBfIRBuilder, typedValue.mType);
  11722. return typedValue;
  11723. }
  11724. BfTypedValue BfModule::LoadOrAggregateValue(BfTypedValue typedValue)
  11725. {
  11726. if (typedValue.IsSplat())
  11727. return AggregateSplat(typedValue);
  11728. if (typedValue.IsAddr())
  11729. return LoadValue(typedValue);
  11730. if ((typedValue.mType != NULL) && (typedValue.mType->IsParamsType()) && (!typedValue.IsParams()))
  11731. {
  11732. return GetDefaultTypedValue(ResolveTypeDef(mCompiler->mTupleTypeDef));
  11733. }
  11734. else if ((typedValue.IsParams()) && (typedValue.mType->IsGenericParam()))
  11735. {
  11736. return BfTypedValue(mBfIRBuilder->GetFakeVal(), typedValue.mType);
  11737. }
  11738. return typedValue;
  11739. }
  11740. BfTypedValue BfModule::AggregateSplat(BfTypedValue typedValue, BfIRValue* valueArrPtr)
  11741. {
  11742. if (!typedValue.IsSplat())
  11743. return typedValue;
  11744. BF_ASSERT(!mIsComptimeModule);
  11745. if (typedValue.mType->IsValuelessType())
  11746. return typedValue;
  11747. int elementIdx = 0;
  11748. auto _ExtractValue = [&](BfType* checkType)
  11749. {
  11750. if (valueArrPtr != NULL)
  11751. return valueArrPtr[elementIdx++];
  11752. return ExtractSplatValue(typedValue, elementIdx++, checkType);
  11753. };
  11754. std::function<BfIRValue(BfType*)> checkTypeLambda = [&](BfType* checkType)
  11755. {
  11756. if (checkType->IsStruct())
  11757. {
  11758. BfIRValue curValue = mBfIRBuilder->CreateUndefValue(mBfIRBuilder->MapType(checkType, BfIRPopulateType_Full));
  11759. auto checkTypeInstance = checkType->ToTypeInstance();
  11760. if (checkTypeInstance->mBaseType != NULL)
  11761. {
  11762. mBfIRBuilder->PopulateType(checkTypeInstance->mBaseType, BfIRPopulateType_Full);
  11763. BfIRValue baseValue = checkTypeLambda(checkTypeInstance->mBaseType);
  11764. curValue = mBfIRBuilder->CreateInsertValue(curValue, baseValue, 0);
  11765. }
  11766. if (checkTypeInstance->mIsUnion)
  11767. {
  11768. auto unionInnerType = checkTypeInstance->GetUnionInnerType();
  11769. if (!unionInnerType->IsValuelessType())
  11770. {
  11771. BfIRValue fieldValue = checkTypeLambda(unionInnerType);
  11772. curValue = mBfIRBuilder->CreateInsertValue(curValue, fieldValue, 1);
  11773. }
  11774. if (checkTypeInstance->IsEnum())
  11775. {
  11776. auto dscrType = checkTypeInstance->GetDiscriminatorType();
  11777. BfIRValue fieldValue = checkTypeLambda(dscrType);
  11778. curValue = mBfIRBuilder->CreateInsertValue(curValue, fieldValue, 2);
  11779. }
  11780. }
  11781. else
  11782. {
  11783. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  11784. {
  11785. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  11786. if (fieldInstance->mDataIdx >= 0)
  11787. {
  11788. BfIRValue fieldValue = checkTypeLambda(fieldInstance->GetResolvedType());
  11789. curValue = mBfIRBuilder->CreateInsertValue(curValue, fieldValue, fieldInstance->mDataIdx);
  11790. }
  11791. }
  11792. }
  11793. return curValue;
  11794. }
  11795. else if (checkType->IsMethodRef())
  11796. {
  11797. BfMethodRefType* methodRefType = (BfMethodRefType*)checkType;
  11798. BfIRValue curValue = mBfIRBuilder->CreateUndefValue(mBfIRBuilder->MapType(checkType, BfIRPopulateType_Full));
  11799. for (int dataIdx = 0; dataIdx < methodRefType->GetCaptureDataCount(); dataIdx++)
  11800. {
  11801. BfIRValue fieldValue;
  11802. auto checkType = methodRefType->GetCaptureType(dataIdx);
  11803. if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  11804. {
  11805. fieldValue = checkTypeLambda(checkType);
  11806. }
  11807. else
  11808. {
  11809. fieldValue = _ExtractValue(checkType);
  11810. }
  11811. curValue = mBfIRBuilder->CreateInsertValue(curValue, fieldValue, dataIdx);
  11812. }
  11813. return curValue;
  11814. }
  11815. else if (!checkType->IsValuelessType())
  11816. {
  11817. return _ExtractValue(checkType);
  11818. }
  11819. return BfIRValue();
  11820. };
  11821. BfIRValue value = checkTypeLambda(typedValue.mType);
  11822. return BfTypedValue(value, typedValue.mType, typedValue.IsThis() ? BfTypedValueKind_ThisValue : BfTypedValueKind_Value);
  11823. }
  11824. void BfModule::AggregateSplatIntoAddr(BfTypedValue typedValue, BfIRValue addrVal)
  11825. {
  11826. if (!typedValue.IsSplat())
  11827. return;
  11828. if (typedValue.mType->IsValuelessType())
  11829. return;
  11830. BF_ASSERT(!mIsComptimeModule);
  11831. /*static int sCallIdx = 0;
  11832. if (!mCompiler->mIsResolveOnly)
  11833. sCallIdx++;
  11834. int callIdx = sCallIdx;*/
  11835. int elementIdx = 0;
  11836. std::function<void(BfType*, BfIRValue)> checkTypeLambda = [&](BfType* checkType, BfIRValue curAddrVal)
  11837. {
  11838. if (checkType->IsStruct())
  11839. {
  11840. auto checkTypeInstance = checkType->ToTypeInstance();
  11841. if (checkTypeInstance->mBaseType != NULL)
  11842. {
  11843. mBfIRBuilder->PopulateType(checkTypeInstance->mBaseType);
  11844. auto baseAddrVal = mBfIRBuilder->CreateInBoundsGEP(curAddrVal, 0, 0);
  11845. checkTypeLambda(checkTypeInstance->mBaseType, baseAddrVal);
  11846. }
  11847. if (checkTypeInstance->mIsUnion)
  11848. {
  11849. auto unionInnerType = checkTypeInstance->GetUnionInnerType();
  11850. if (!unionInnerType->IsValuelessType())
  11851. {
  11852. auto fieldAddrVal = mBfIRBuilder->CreateInBoundsGEP(curAddrVal, 0, 1);
  11853. checkTypeLambda(unionInnerType, fieldAddrVal);
  11854. }
  11855. if (checkTypeInstance->IsEnum())
  11856. {
  11857. auto dscrType = checkTypeInstance->GetDiscriminatorType();
  11858. auto fieldAddrVal = mBfIRBuilder->CreateInBoundsGEP(curAddrVal, 0, 2);
  11859. checkTypeLambda(dscrType, fieldAddrVal);
  11860. }
  11861. }
  11862. else
  11863. {
  11864. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  11865. {
  11866. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  11867. if (fieldInstance->mDataIdx >= 0)
  11868. {
  11869. auto fieldAddrVal = mBfIRBuilder->CreateInBoundsGEP(curAddrVal, 0, fieldInstance->mDataIdx);
  11870. checkTypeLambda(fieldInstance->mResolvedType, fieldAddrVal);
  11871. }
  11872. }
  11873. }
  11874. }
  11875. else if (checkType->IsMethodRef())
  11876. {
  11877. BfMethodRefType* methodRefType = (BfMethodRefType*)checkType;
  11878. for (int dataIdx = 0; dataIdx < methodRefType->GetCaptureDataCount(); dataIdx++)
  11879. {
  11880. auto dataType = methodRefType->GetCaptureType(dataIdx);
  11881. auto fieldAddrVal = mBfIRBuilder->CreateInBoundsGEP(curAddrVal, 0, dataIdx);
  11882. if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  11883. {
  11884. checkTypeLambda(methodRefType->GetCaptureType(dataIdx), fieldAddrVal);
  11885. }
  11886. else
  11887. {
  11888. // static int sItrCount = 0;
  11889. // sItrCount++;
  11890. // int curItr = sItrCount;
  11891. // if (curItr == 1)
  11892. // {
  11893. // NOP;
  11894. // }
  11895. auto val = ExtractSplatValue(typedValue, elementIdx++, dataType);
  11896. mBfIRBuilder->CreateStore(val, fieldAddrVal);
  11897. }
  11898. }
  11899. }
  11900. else if (!checkType->IsValuelessType())
  11901. {
  11902. auto val = ExtractSplatValue(typedValue, elementIdx++, checkType);
  11903. mBfIRBuilder->CreateStore(val, curAddrVal);
  11904. }
  11905. };
  11906. checkTypeLambda(typedValue.mType, addrVal);
  11907. }
  11908. BfTypedValue BfModule::MakeAddressable(BfTypedValue typedVal, bool forceMutable, bool forceAddressable)
  11909. {
  11910. bool wasReadOnly = typedVal.IsReadOnly();
  11911. if ((forceAddressable) ||
  11912. ((typedVal.mType->IsValueType()) &&
  11913. (!typedVal.mType->IsValuelessNonOpaqueType())))
  11914. {
  11915. wasReadOnly = true; // Any non-addr is implicitly read-only
  11916. //static int gCallIdx = 0;
  11917. FixValueActualization(typedVal);
  11918. if (typedVal.IsAddr())
  11919. return typedVal;
  11920. BfType* type = typedVal.mType;
  11921. PopulateType(type);
  11922. BfIRValue tempVar;
  11923. if (typedVal.mValue.IsFake())
  11924. tempVar = mBfIRBuilder->GetFakeVal();
  11925. else
  11926. {
  11927. tempVar = CreateAlloca(type);
  11928. if (typedVal.IsSplat())
  11929. AggregateSplatIntoAddr(typedVal, tempVar);
  11930. else
  11931. mBfIRBuilder->CreateAlignedStore(typedVal.mValue, tempVar, type->mAlign);
  11932. }
  11933. if (forceMutable)
  11934. wasReadOnly = false;
  11935. return BfTypedValue(tempVar, type,
  11936. typedVal.IsThis() ?
  11937. (wasReadOnly ? BfTypedValueKind_ReadOnlyThisAddr : BfTypedValueKind_ThisAddr) :
  11938. (wasReadOnly ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Addr));
  11939. }
  11940. return LoadValue(typedVal);
  11941. }
  11942. BfTypedValue BfModule::RemoveReadOnly(BfTypedValue typedValue)
  11943. {
  11944. if (typedValue.mKind == BfTypedValueKind_ReadOnlyAddr)
  11945. typedValue.mKind = BfTypedValueKind_Addr;
  11946. return typedValue;
  11947. }
  11948. BfTypedValue BfModule::CopyValue(const BfTypedValue& typedValue)
  11949. {
  11950. return MakeAddressable(LoadValue(typedValue), true);
  11951. }
  11952. BfIRValue BfModule::ExtractSplatValue(BfTypedValue typedValue, int componentIdx, BfType* wantType, bool* isAddr)
  11953. {
  11954. BF_ASSERT(!mIsComptimeModule);
  11955. BfIRValue val;
  11956. if (typedValue.mValue.IsArg())
  11957. {
  11958. val = mBfIRBuilder->GetArgument(typedValue.mValue.mId + componentIdx);
  11959. if (isAddr != NULL)
  11960. {
  11961. if (wantType != NULL)
  11962. *isAddr = wantType->IsComposite();
  11963. else
  11964. *isAddr = false;
  11965. }
  11966. else if (wantType->IsComposite())
  11967. val = mBfIRBuilder->CreateLoad(val);
  11968. }
  11969. if (!val)
  11970. {
  11971. auto checkMethodState = mCurMethodState;
  11972. while (checkMethodState != NULL)
  11973. {
  11974. for (int idx = 0; idx < (int)checkMethodState->mSplatDecompAddrs.size(); idx++)
  11975. {
  11976. auto decompAddr = checkMethodState->mSplatDecompAddrs[idx];
  11977. if (decompAddr == typedValue.mValue)
  11978. {
  11979. val = checkMethodState->mSplatDecompAddrs[idx + componentIdx];
  11980. if ((wantType->IsComposite()) && (typedValue.mType->IsMethodRef()))
  11981. {
  11982. // This is really backing for a POINTER to a composite inside a methodRef
  11983. val = mBfIRBuilder->CreateLoad(val);
  11984. }
  11985. if ((isAddr != NULL) && (typedValue.mKind != BfTypedValueKind_SplatHead_NeedsCasting))
  11986. {
  11987. *isAddr = true;
  11988. return val;
  11989. }
  11990. else
  11991. {
  11992. val = mBfIRBuilder->CreateAlignedLoad(val, wantType->mAlign);
  11993. break;
  11994. }
  11995. }
  11996. }
  11997. if (val)
  11998. break;
  11999. if ((checkMethodState->mClosureState != NULL) && (checkMethodState->mClosureState->mCapturing))
  12000. {
  12001. BF_ASSERT(mBfIRBuilder->mIgnoreWrites);
  12002. return mBfIRBuilder->GetFakeVal();
  12003. }
  12004. checkMethodState = checkMethodState->mPrevMethodState;
  12005. }
  12006. }
  12007. if (val)
  12008. {
  12009. if (typedValue.mKind == BfTypedValueKind_SplatHead_NeedsCasting)
  12010. {
  12011. BF_ASSERT(wantType != NULL);
  12012. if (wantType != NULL)
  12013. return mBfIRBuilder->CreateBitCast(val, mBfIRBuilder->MapType(wantType));
  12014. }
  12015. return val;
  12016. }
  12017. BFMODULE_FATAL(this, "Splat not found");
  12018. return BfIRValue();
  12019. }
  12020. BfTypedValue BfModule::ExtractValue(BfTypedValue typedValue, BfFieldInstance* fieldInstance, int fieldIdx)
  12021. {
  12022. int useFieldIdx = fieldIdx;
  12023. BfType* fieldType = NULL;
  12024. if (fieldInstance != NULL)
  12025. {
  12026. fieldType = fieldInstance->mResolvedType;
  12027. if (typedValue.mType->IsUnion())
  12028. {
  12029. if (fieldIdx == 1)
  12030. {
  12031. if (typedValue.IsSplat())
  12032. {
  12033. bool isAddr = false;
  12034. BfIRValue irVal = ExtractSplatValue(typedValue, 0, fieldType, &isAddr);
  12035. return BfTypedValue(irVal, fieldType, typedValue.mValue.IsArg() ? BfTypedValueKind_SplatHead : BfTypedValueKind_Addr);
  12036. }
  12037. }
  12038. }
  12039. }
  12040. else
  12041. {
  12042. if (typedValue.mType->IsPayloadEnum())
  12043. {
  12044. auto typeInst = typedValue.mType->ToTypeInstance();
  12045. if (fieldIdx == 1)
  12046. fieldType = typeInst->GetUnionInnerType();
  12047. else if (fieldIdx == 2)
  12048. {
  12049. fieldType = typeInst->GetDiscriminatorType(&useFieldIdx);
  12050. }
  12051. }
  12052. else if (typedValue.mType->IsUnion())
  12053. {
  12054. if (fieldIdx == 1)
  12055. {
  12056. fieldType = typedValue.mType->ToTypeInstance()->GetUnionInnerType();
  12057. if (typedValue.IsSplat())
  12058. {
  12059. bool isAddr = false;
  12060. BfIRValue irVal = ExtractSplatValue(typedValue, 0, fieldType, &isAddr);
  12061. return BfTypedValue(irVal, fieldType, typedValue.mValue.IsArg() ? BfTypedValueKind_SplatHead : BfTypedValueKind_Addr);
  12062. }
  12063. }
  12064. }
  12065. }
  12066. BF_ASSERT(typedValue.mType->IsStruct());
  12067. if (typedValue.IsSplat())
  12068. {
  12069. if (typedValue.mType->IsPayloadEnum())
  12070. {
  12071. if (fieldIdx == 1)
  12072. {
  12073. // Payload
  12074. auto typeInst = typedValue.mType->ToTypeInstance();
  12075. auto unionInnerType = typeInst->GetUnionInnerType();
  12076. bool isAddr = false;
  12077. BfIRValue irVal = ExtractSplatValue(typedValue, 0, unionInnerType, &isAddr);
  12078. return BfTypedValue(irVal, unionInnerType, BfTypedValueKind_SplatHead);
  12079. }
  12080. if (fieldIdx == 2)
  12081. {
  12082. // Discriminator
  12083. auto typeInst = typedValue.mType->ToTypeInstance();
  12084. auto unionInnerType = typeInst->GetUnionInnerType();
  12085. auto dscrType = typeInst->GetDiscriminatorType();
  12086. int argIdx = typedValue.mValue.mId;
  12087. int componentIdx = 0;
  12088. BfTypeUtils::SplatIterate([&](BfType* checkType) { componentIdx++; }, unionInnerType);
  12089. bool isAddr;
  12090. BfIRValue irVal = ExtractSplatValue(typedValue, componentIdx, dscrType, &isAddr);
  12091. return BfTypedValue(irVal, dscrType, isAddr);
  12092. }
  12093. }
  12094. int componentIdx = 0;
  12095. BfTypedValue retVal;
  12096. BfFieldInstance* wantFieldInstance = fieldInstance;
  12097. std::function<void(BfType*)> checkTypeLambda = [&](BfType* checkType)
  12098. {
  12099. if (checkType->IsStruct())
  12100. {
  12101. auto checkTypeInstance = checkType->ToTypeInstance();
  12102. if ((checkType->IsUnion()) || (checkType->IsEnum()))
  12103. {
  12104. //TODO: Why did we have this removed? It messed up an extraction from a nullable splattable
  12105. fieldType = checkTypeInstance->GetUnionInnerType();
  12106. checkTypeLambda(fieldType);
  12107. if (checkType->IsEnum())
  12108. {
  12109. // Past discriminator...
  12110. componentIdx++;
  12111. }
  12112. return;
  12113. }
  12114. if (checkTypeInstance->mBaseType != NULL)
  12115. checkTypeLambda(checkTypeInstance->mBaseType);
  12116. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  12117. {
  12118. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  12119. if (fieldInstance == wantFieldInstance)
  12120. {
  12121. if (fieldInstance->mResolvedType->IsValuelessType())
  12122. {
  12123. retVal = GetDefaultTypedValue(fieldInstance->mResolvedType);
  12124. break;
  12125. }
  12126. bool isAddr = false;
  12127. BfIRValue val = ExtractSplatValue(typedValue, componentIdx, fieldInstance->mResolvedType, &isAddr);
  12128. retVal = BfTypedValue(val, fieldInstance->mResolvedType,
  12129. fieldInstance->mResolvedType->IsComposite() ? BfTypedValueKind_SplatHead :
  12130. isAddr ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Value);
  12131. if ((retVal.IsAddr()) && (!fieldInstance->mResolvedType->IsValueType()))
  12132. {
  12133. retVal = LoadValue(retVal);
  12134. }
  12135. break;
  12136. }
  12137. if (fieldInstance->mDataIdx >= 0)
  12138. checkTypeLambda(fieldInstance->GetResolvedType());
  12139. }
  12140. }
  12141. else if (!checkType->IsValuelessType())
  12142. {
  12143. componentIdx++;
  12144. //argIdx++;
  12145. }
  12146. };
  12147. checkTypeLambda(typedValue.mType);
  12148. BF_ASSERT(retVal);
  12149. return retVal;
  12150. }
  12151. if (typedValue.IsAddr())
  12152. {
  12153. BF_ASSERT(fieldType != NULL);
  12154. auto valRef = mBfIRBuilder->CreateInBoundsGEP(typedValue.mValue, 0, useFieldIdx);
  12155. return BfTypedValue(valRef, fieldType, BfTypedValueKind_ReadOnlyAddr);
  12156. }
  12157. else
  12158. {
  12159. BF_ASSERT(fieldType != NULL);
  12160. return BfTypedValue(mBfIRBuilder->CreateExtractValue(typedValue.mValue, useFieldIdx), fieldType, BfTypedValueKind_Value);
  12161. }
  12162. }
  12163. BfIRValue BfModule::ExtractValue(BfTypedValue typedValue, int dataIdx)
  12164. {
  12165. if (typedValue.IsAddr())
  12166. {
  12167. auto addrVal = mBfIRBuilder->CreateInBoundsGEP(typedValue.mValue, 0, dataIdx);
  12168. return mBfIRBuilder->CreateAlignedLoad(addrVal, typedValue.mType->mAlign);
  12169. }
  12170. return mBfIRBuilder->CreateExtractValue(typedValue.mValue, dataIdx);
  12171. }
  12172. BfIRValue BfModule::CreateIndexedValue(BfType* elementType, BfIRValue value, BfIRValue indexValue, bool isElementIndex)
  12173. {
  12174. if (isElementIndex)
  12175. return mBfIRBuilder->CreateInBoundsGEP(value, GetConstValue(0), indexValue);
  12176. else
  12177. return mBfIRBuilder->CreateInBoundsGEP(value, indexValue);
  12178. // if (elementType->IsSizeAligned())
  12179. // {
  12180. // if (isElementIndex)
  12181. // return mBfIRBuilder->CreateInBoundsGEP(value, GetConstValue(0), indexValue);
  12182. // else
  12183. // return mBfIRBuilder->CreateInBoundsGEP(value, indexValue);
  12184. // }
  12185. //
  12186. // auto ptrType = CreatePointerType(elementType);
  12187. // auto ofsVal = mBfIRBuilder->CreateNumericCast(indexValue, true, BfTypeCode_IntPtr);
  12188. // auto ofsScaledVal = mBfIRBuilder->CreateMul(ofsVal, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, elementType->GetStride()));
  12189. // auto i8PtrType = mBfIRBuilder->GetPointerTo(mBfIRBuilder->GetPrimitiveType(BfTypeCode_Int8));
  12190. // BfIRValue origPtrValue = mBfIRBuilder->CreateBitCast(value, i8PtrType);
  12191. // BfIRValue newPtrValue = mBfIRBuilder->CreateInBoundsGEP(origPtrValue, ofsScaledVal);
  12192. // return mBfIRBuilder->CreateBitCast(newPtrValue, mBfIRBuilder->MapType(ptrType));
  12193. }
  12194. BfIRValue BfModule::CreateIndexedValue(BfType* elementType, BfIRValue value, int indexValue, bool isElementIndex)
  12195. {
  12196. if (elementType->IsSizeAligned())
  12197. {
  12198. if (isElementIndex)
  12199. return mBfIRBuilder->CreateInBoundsGEP(value, 0, indexValue);
  12200. else
  12201. return mBfIRBuilder->CreateInBoundsGEP(value, indexValue);
  12202. }
  12203. return CreateIndexedValue(elementType, value, GetConstValue(indexValue), isElementIndex);
  12204. }
  12205. bool BfModule::CheckModifyValue(BfTypedValue& typedValue, BfAstNode* refNode, const char* modifyType)
  12206. {
  12207. if (modifyType == NULL)
  12208. modifyType = "modify";
  12209. if (typedValue.mType->IsVar())
  12210. return true;
  12211. if (typedValue.IsReadOnly())
  12212. {
  12213. Fail(StrFormat("Cannot %s read-only variable", modifyType), refNode);
  12214. return false;
  12215. }
  12216. if ((!typedValue.IsAddr()) && (!typedValue.mType->IsValuelessType()))
  12217. {
  12218. Fail(StrFormat("Cannot %s value", modifyType), refNode);
  12219. return false;
  12220. }
  12221. if (typedValue.mKind == BfTypedValueKind_RestrictedTempAddr)
  12222. {
  12223. Fail(StrFormat("Cannot %s temporary value", modifyType), refNode);
  12224. return false;
  12225. }
  12226. return true;
  12227. }
  12228. bool BfModule::CompareMethodSignatures(BfMethodInstance* methodA, BfMethodInstance* methodB)
  12229. {
  12230. // If one is an interface and the other is an impl, B is the impl
  12231. auto implOwner = methodB->GetOwner();
  12232. if (methodA->mMethodDef->mIsLocalMethod)
  12233. {
  12234. int sepPosA = (int)BF_MIN(methodA->mMethodDef->mName.IndexOf('@'), methodA->mMethodDef->mName.length());
  12235. int sepPosB = (int)BF_MIN(methodB->mMethodDef->mName.IndexOf('@'), methodB->mMethodDef->mName.length());
  12236. if (sepPosA != sepPosB)
  12237. return false;
  12238. if (strncmp(methodA->mMethodDef->mName.c_str(), methodB->mMethodDef->mName.c_str(), sepPosA) != 0)
  12239. return false;
  12240. }
  12241. else if (methodA->mMethodDef->mName != methodB->mMethodDef->mName)
  12242. return false;
  12243. if (methodA->mMethodDef->mAppendKind != methodB->mMethodDef->mAppendKind)
  12244. return false;
  12245. if (methodA->mMethodDef->mCheckedKind != methodB->mMethodDef->mCheckedKind)
  12246. return false;
  12247. if (methodA->mMethodDef->mHasComptime != methodB->mMethodDef->mHasComptime)
  12248. return false;
  12249. if ((methodA->mMethodDef->mMethodType == BfMethodType_Mixin) != (methodB->mMethodDef->mMethodType == BfMethodType_Mixin))
  12250. return false;
  12251. if (methodA->mMethodDef->mMethodType == BfMethodType_Ctor)
  12252. {
  12253. if (methodA->mMethodDef->mIsStatic != methodB->mMethodDef->mIsStatic)
  12254. return false;
  12255. }
  12256. if (methodA->mMethodDef->mMethodType == BfMethodType_Operator)
  12257. {
  12258. if (methodB->mMethodDef->mMethodType != BfMethodType_Operator)
  12259. return false;
  12260. auto operatorA = (BfOperatorDef*)methodA->mMethodDef;
  12261. auto operatorB = (BfOperatorDef*)methodB->mMethodDef;
  12262. if (operatorA->mOperatorDeclaration->mUnaryOp != operatorB->mOperatorDeclaration->mUnaryOp)
  12263. return false;
  12264. if (operatorA->mOperatorDeclaration->mBinOp != operatorB->mOperatorDeclaration->mBinOp)
  12265. return false;
  12266. if (operatorA->mOperatorDeclaration->mAssignOp != operatorB->mOperatorDeclaration->mAssignOp)
  12267. return false;
  12268. if (operatorA->mOperatorDeclaration->mIsConvOperator)
  12269. {
  12270. if (!BfTypeUtils::TypeEquals(methodA->mReturnType, methodB->mReturnType, implOwner))
  12271. return false;
  12272. }
  12273. }
  12274. int implicitParamCountA = methodA->GetImplicitParamCount();
  12275. int implicitParamCountB = methodB->GetImplicitParamCount();
  12276. if (methodA->GetParamCount() - implicitParamCountA != methodB->GetParamCount() - implicitParamCountB)
  12277. return false;
  12278. if (methodA->mHadGenericDelegateParams != methodB->mHadGenericDelegateParams)
  12279. return false;
  12280. for (int paramIdx = 0; paramIdx < (int)methodA->GetParamCount() - implicitParamCountA; paramIdx++)
  12281. {
  12282. if ((!BfTypeUtils::TypeEquals(methodA->GetParamType(paramIdx + implicitParamCountA), methodB->GetParamType(paramIdx + implicitParamCountB), implOwner)) ||
  12283. (methodA->GetParamKind(paramIdx + implicitParamCountA) != methodB->GetParamKind(paramIdx + implicitParamCountB)))
  12284. return false;
  12285. }
  12286. // Compare generic params. Generic params are part of the method signature here
  12287. if (methodA->GetNumGenericParams() != methodB->GetNumGenericParams())
  12288. return false;
  12289. for (int genericParamIdx = 0; genericParamIdx < (int)methodA->GetNumGenericParams(); genericParamIdx++)
  12290. {
  12291. auto genericParamA = methodA->mMethodInfoEx->mGenericParams[genericParamIdx];
  12292. auto genericParamB = methodB->mMethodInfoEx->mGenericParams[genericParamIdx];
  12293. if (genericParamA->mGenericParamFlags != genericParamB->mGenericParamFlags)
  12294. return false;
  12295. if (genericParamA->mTypeConstraint != genericParamB->mTypeConstraint)
  12296. return false;
  12297. if (genericParamA->mInterfaceConstraints.size() != genericParamB->mInterfaceConstraints.size())
  12298. return false;
  12299. for (int interfaceIdx = 0; interfaceIdx < (int)genericParamA->mInterfaceConstraints.size(); interfaceIdx++)
  12300. if (genericParamA->mInterfaceConstraints[interfaceIdx] != genericParamB->mInterfaceConstraints[interfaceIdx])
  12301. return false;
  12302. }
  12303. return true;
  12304. }
  12305. bool BfModule::StrictCompareMethodSignatures(BfMethodInstance* methodA, BfMethodInstance* methodB)
  12306. {
  12307. if (!CompareMethodSignatures(methodA, methodB))
  12308. return false;
  12309. if (methodA->mReturnType != methodB->mReturnType)
  12310. return false;
  12311. if (methodA->mMethodDef->mIsStatic != methodB->mMethodDef->mIsStatic)
  12312. return false;
  12313. return true;
  12314. }
  12315. bool BfModule::IsCompatibleInterfaceMethod(BfMethodInstance* iMethodInst, BfMethodInstance* methodInstance)
  12316. {
  12317. if ((iMethodInst->GetNumGenericParams() != 0) || (methodInstance->GetNumGenericParams() != 0))
  12318. return false;
  12319. if (iMethodInst->mMethodDef->mName != methodInstance->mMethodDef->mName)
  12320. return false;
  12321. if (iMethodInst->mMethodDef->mIsOperator != methodInstance->mMethodDef->mIsOperator)
  12322. return false;
  12323. if (iMethodInst->mMethodDef->mIsOperator)
  12324. {
  12325. auto iOperatorDef = (BfOperatorDef*)iMethodInst->mMethodDef;
  12326. auto operatorDef = (BfOperatorDef*)methodInstance->mMethodDef;
  12327. if (iOperatorDef->mOperatorDeclaration->mUnaryOp != operatorDef->mOperatorDeclaration->mUnaryOp)
  12328. return false;
  12329. if (iOperatorDef->mOperatorDeclaration->mBinOp != operatorDef->mOperatorDeclaration->mBinOp)
  12330. return false;
  12331. }
  12332. if (iMethodInst->GetParamCount() != methodInstance->GetParamCount())
  12333. return false;
  12334. auto selfType = methodInstance->GetOwner();
  12335. for (int paramIdx = 0; paramIdx < (int)iMethodInst->GetParamCount(); paramIdx++)
  12336. {
  12337. if (iMethodInst->GetParamKind(paramIdx) != methodInstance->GetParamKind(paramIdx))
  12338. return false;
  12339. BfType* iParamType = iMethodInst->GetParamType(paramIdx);
  12340. BfType* methodParamType = methodInstance->GetParamType(paramIdx);
  12341. iParamType = ResolveSelfType(iParamType, selfType);
  12342. methodParamType = ResolveSelfType(methodParamType, selfType);
  12343. if (!iParamType->IsGenericParam())
  12344. {
  12345. if (methodParamType != iParamType)
  12346. return false;
  12347. }
  12348. else
  12349. {
  12350. if (!methodParamType->IsGenericParam())
  12351. return false;
  12352. auto genericParamType = (BfGenericParamType*)methodParamType;
  12353. if (genericParamType->mGenericParamKind == BfGenericParamKind_Type)
  12354. return false;
  12355. auto genericParam = methodInstance->mMethodInfoEx->mGenericParams[genericParamType->mGenericParamIdx];
  12356. bool hadInterface = false;
  12357. for (auto interfaceConstraint : genericParam->mInterfaceConstraints)
  12358. if (interfaceConstraint == iParamType)
  12359. hadInterface = true;
  12360. if (!hadInterface)
  12361. return false;
  12362. }
  12363. }
  12364. return true;
  12365. }
  12366. void BfModule::AddMethodReference(const BfMethodRef& methodRef, BfGetMethodInstanceFlags flags)
  12367. {
  12368. BfMethodInstance* methodInstance = methodRef;
  12369. if ((mCurTypeInstance != NULL) && (!mCompiler->IsAutocomplete()))
  12370. {
  12371. auto methodInstanceGroup = methodInstance->mMethodInstanceGroup;
  12372. if ((methodInstance->IsSpecializedGenericMethod()) || (methodInstanceGroup->mOnDemandKind != BfMethodOnDemandKind_AlwaysInclude))
  12373. {
  12374. BF_ASSERT(!methodRef.mTypeInstance->IsFunction());
  12375. // This ensures we rebuild - there are some cases where we get a method reference but never call it, so this is required here
  12376. AddDependency(methodInstance->GetOwner(), mCurTypeInstance, BfDependencyMap::DependencyFlag_Calls);
  12377. BfMethodRef methodRef = methodInstance;
  12378. BfSpecializedMethodRefInfo* specializedMethodRefInfo = NULL;
  12379. bool isNew = mCurTypeInstance->mSpecializedMethodReferences.TryAdd(methodRef, NULL, &specializedMethodRefInfo);
  12380. if (((flags & BfGetMethodInstanceFlag_Unreified) == 0) &&
  12381. ((flags & BfGetMethodInstanceFlag_NoForceReification) == 0) &&
  12382. (mIsReified))
  12383. {
  12384. specializedMethodRefInfo->mHasReifiedRef = true;
  12385. }
  12386. }
  12387. }
  12388. }
  12389. BfModuleMethodInstance BfModule::ReferenceExternalMethodInstance(BfMethodInstance* methodInstance, BfGetMethodInstanceFlags flags)
  12390. {
  12391. if ((flags & BfGetMethodInstanceFlag_ResultNotUsed) != 0)
  12392. return BfModuleMethodInstance(methodInstance, BfIRValue());
  12393. if (mBfIRBuilder == NULL)
  12394. return BfModuleMethodInstance(methodInstance, BfIRValue());
  12395. if (methodInstance->GetOwner()->IsFunction())
  12396. {
  12397. // No actual ref needed- not an actual generated function
  12398. return BfModuleMethodInstance(methodInstance, BfIRValue());
  12399. }
  12400. bool isGenFunction = methodInstance->mMethodInstanceGroup->mMethodIdx < 0;
  12401. if (!isGenFunction)
  12402. AddMethodReference(methodInstance, flags);
  12403. if ((mBfIRBuilder->mIgnoreWrites) || ((flags & BfGetMethodInstanceFlag_Unreified) != 0))
  12404. return BfModuleMethodInstance(methodInstance, mBfIRBuilder->GetFakeVal());
  12405. if (IsSkippingExtraResolveChecks())
  12406. return BfModuleMethodInstance(methodInstance, BfIRFunction());
  12407. if (methodInstance->mMethodDef->mMethodType == BfMethodType_Mixin)
  12408. {
  12409. return BfModuleMethodInstance(methodInstance, BfIRFunction());
  12410. }
  12411. bool isInlined = (methodInstance->mAlwaysInline) || ((flags & BfGetMethodInstanceFlag_ForceInline) != 0);
  12412. if ((methodInstance->mIsIntrinsic) || (methodInstance->mMethodDef->mIsExtern))
  12413. isInlined = false;
  12414. BfMethodRef methodRef = methodInstance;
  12415. if (isInlined)
  12416. methodRef.mMethodRefFlags = (BfMethodRefFlags)(methodRef.mMethodRefFlags | BfMethodRefFlag_AlwaysInclude);
  12417. else
  12418. methodRef.mMethodRefFlags = BfMethodRefFlag_None;
  12419. if (!isGenFunction)
  12420. {
  12421. BfIRValue* irFuncPtr = NULL;
  12422. if (mFuncReferences.TryGetValue(methodRef, &irFuncPtr))
  12423. return BfModuleMethodInstance(methodInstance, *irFuncPtr);
  12424. }
  12425. if (mAwaitingInitFinish)
  12426. FinishInit();
  12427. BfIRValue func = CreateFunctionFrom(methodInstance, isGenFunction, isInlined);
  12428. if (!isGenFunction)
  12429. {
  12430. BF_ASSERT(func || methodInstance->mMethodInstanceGroup->mOwner->IsInterface());
  12431. mFuncReferences[methodRef] = func;
  12432. }
  12433. BfLogSysM("Adding func reference. Module:%p MethodInst:%p NewLLVMFunc:%d OldLLVMFunc:%d\n", this, methodInstance, func.mId, methodInstance->mIRFunction.mId);
  12434. if ((isInlined) && (!mIsScratchModule) && ((flags & BfGetMethodInstanceFlag_NoInline) == 0))
  12435. {
  12436. // We can't just add a dependency to mCurTypeInstance because we may have nested inlined functions, and
  12437. // mCurTypeInstance will just reflect the owner of the method currently being inlined, not the top-level
  12438. // type instance
  12439. // Be smarter about this if we ever insert a lot of type instances into a single module - track in a field
  12440. BF_ASSERT(mOwnedTypeInstances.size() <= 1);
  12441. for (auto ownedTypeInst : mOwnedTypeInstances)
  12442. AddDependency(methodInstance->GetOwner(), ownedTypeInst, BfDependencyMap::DependencyFlag_InlinedCall);
  12443. if ((!mCompiler->mIsResolveOnly) && (mIsReified) && (!methodInstance->mIsUnspecialized))
  12444. {
  12445. mIncompleteMethodCount++;
  12446. BfInlineMethodRequest* inlineMethodRequest = mContext->mInlineMethodWorkList.Alloc();
  12447. inlineMethodRequest->mType = methodInstance->GetOwner();
  12448. inlineMethodRequest->mFromModule = this;
  12449. inlineMethodRequest->mFunc = func;
  12450. inlineMethodRequest->mFromModuleRevision = mRevision;
  12451. inlineMethodRequest->mFromModuleRebuildIdx = mRebuildIdx;
  12452. inlineMethodRequest->mMethodInstance = methodInstance;
  12453. BF_ASSERT(mIsModuleMutable);
  12454. BfLogSysM("mInlineMethodWorkList %p for method %p in module %p in ReferenceExternalMethodInstance\n", inlineMethodRequest, methodInstance, this);
  12455. }
  12456. }
  12457. return BfModuleMethodInstance(methodInstance, func);
  12458. }
  12459. BfModule* BfModule::GetOrCreateMethodModule(BfMethodInstance* methodInstance)
  12460. {
  12461. BfTypeInstance* typeInst = methodInstance->mMethodInstanceGroup->mOwner;
  12462. if (mBfIRBuilder == NULL)
  12463. {
  12464. // To allow for custom attribute data
  12465. PrepareForIRWriting(typeInst);
  12466. }
  12467. BfModule* declareModule = this;
  12468. // Get to the optionless branch head -- but this could still be a specialized method module, not the true root
  12469. while ((declareModule->mParentModule != NULL) && (!declareModule->mIsSpecializedMethodModuleRoot))
  12470. declareModule = declareModule->mParentModule;
  12471. // Check for attributes
  12472. if (typeInst == mContext->mBfObjectType)
  12473. {
  12474. auto methodDecl = methodInstance->mMethodDef->GetMethodDeclaration();
  12475. if (methodDecl != NULL)
  12476. {
  12477. auto attributesDirective = methodDecl->mAttributes;
  12478. if ((attributesDirective != NULL) && (mCompiler->mResolvePassData != NULL))
  12479. {
  12480. if (auto sourceClassifier = mCompiler->mResolvePassData->GetSourceClassifier(attributesDirective))
  12481. sourceClassifier->VisitChild(attributesDirective);
  12482. }
  12483. }
  12484. }
  12485. else
  12486. {
  12487. // Only allow attributes on System.Object methods that can be handled inside the DefBuilder
  12488. GetMethodCustomAttributes(methodInstance);
  12489. }
  12490. BF_ASSERT(mModuleOptions == NULL);
  12491. if (methodInstance->GetCustomAttributes() != NULL)
  12492. {
  12493. auto project = typeInst->mTypeDef->mProject;
  12494. BfModuleOptions moduleOptions = declareModule->GetModuleOptions();
  12495. BfModuleOptions wantOptions = moduleOptions;
  12496. auto typeOptions = mSystem->GetTypeOptions(typeInst->mTypeOptionsIdx);
  12497. if (typeOptions != NULL)
  12498. {
  12499. wantOptions.mOptLevel = (BfOptLevel)BfTypeOptions::Apply((int)wantOptions.mOptLevel, (int)typeOptions->mOptimizationLevel);
  12500. wantOptions.mSIMDSetting = (BfSIMDSetting)BfTypeOptions::Apply((int)wantOptions.mSIMDSetting, typeOptions->mSIMDSetting);
  12501. wantOptions.mEmitDebugInfo = (BfSIMDSetting)BfTypeOptions::Apply((int)wantOptions.mEmitDebugInfo, typeOptions->mEmitDebugInfo);
  12502. }
  12503. if (!mCompiler->mAttributeTypeOptionMap.IsEmpty())
  12504. {
  12505. StringT<128> attrName;
  12506. for (auto& customAttrs : methodInstance->GetCustomAttributes()->mAttributes)
  12507. {
  12508. attrName.Clear();
  12509. customAttrs.mType->mTypeDef->mFullName.ToString(attrName);
  12510. Array<int>* arrPtr;
  12511. if (mCompiler->mAttributeTypeOptionMap.TryGetValue(attrName, &arrPtr))
  12512. {
  12513. for (auto optionsIdx : *arrPtr)
  12514. {
  12515. auto& typeOptions = mCompiler->mSystem->mTypeOptions[optionsIdx];
  12516. wantOptions.mOptLevel = (BfOptLevel)BfTypeOptions::Apply((int)wantOptions.mOptLevel, (int)typeOptions.mOptimizationLevel);
  12517. wantOptions.mSIMDSetting = (BfSIMDSetting)BfTypeOptions::Apply((int)wantOptions.mSIMDSetting, typeOptions.mSIMDSetting);
  12518. wantOptions.mEmitDebugInfo = (BfSIMDSetting)BfTypeOptions::Apply((int)wantOptions.mEmitDebugInfo, typeOptions.mEmitDebugInfo);
  12519. }
  12520. }
  12521. }
  12522. }
  12523. if ((HasCompiledOutput()) && (wantOptions != moduleOptions) && (!mIsScratchModule))
  12524. {
  12525. auto lastCheckModule = this;
  12526. auto checkModule = this->mNextAltModule;
  12527. while (checkModule != NULL)
  12528. {
  12529. if (*checkModule->mModuleOptions == wantOptions)
  12530. {
  12531. declareModule = checkModule;
  12532. break;
  12533. }
  12534. lastCheckModule = checkModule;
  12535. checkModule = checkModule->mNextAltModule;
  12536. }
  12537. // Not found?
  12538. if (declareModule == this)
  12539. {
  12540. String specModuleName = mModuleName + "@@";
  12541. if (wantOptions.mOptLevel != moduleOptions.mOptLevel)
  12542. specModuleName += StrFormat("O%d", wantOptions.mOptLevel);
  12543. if (wantOptions.mSIMDSetting != moduleOptions.mSIMDSetting)
  12544. specModuleName += StrFormat("SIMD%d", wantOptions.mSIMDSetting);
  12545. declareModule = new BfModule(mContext, specModuleName);
  12546. declareModule->mProject = project;
  12547. declareModule->mModuleOptions = new BfModuleOptions();
  12548. *declareModule->mModuleOptions = wantOptions;
  12549. declareModule->mParentModule = lastCheckModule;
  12550. declareModule->Init();
  12551. lastCheckModule->mNextAltModule = declareModule;
  12552. }
  12553. }
  12554. }
  12555. declareModule->PrepareForIRWriting(typeInst);
  12556. return declareModule;
  12557. }
  12558. BfModuleMethodInstance BfModule::GetMethodInstance(BfTypeInstance* typeInst, BfMethodDef* methodDef, const BfTypeVector& methodGenericArguments, BfGetMethodInstanceFlags flags, BfTypeInstance* foreignType, BfModule* referencingModule)
  12559. {
  12560. if (methodDef->mMethodType == BfMethodType_Init)
  12561. return BfModuleMethodInstance();
  12562. if (((flags & BfGetMethodInstanceFlag_ForceInline) != 0) && (mCompiler->mIsResolveOnly))
  12563. {
  12564. // Don't bother inlining for resolve-only
  12565. flags = (BfGetMethodInstanceFlags)(flags & ~BfGetMethodInstanceFlag_ForceInline);
  12566. }
  12567. if (methodDef->mIsExtern)
  12568. flags = (BfGetMethodInstanceFlags)(flags & ~BfGetMethodInstanceFlag_ForceInline);
  12569. bool processNow = false;
  12570. bool keepInCurrentModule = false;
  12571. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mIsUnspecialized))
  12572. flags = (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_NoForceReification);
  12573. if (!typeInst->IsTypeMemberIncluded(methodDef->mDeclaringType))
  12574. {
  12575. return BfModuleMethodInstance();
  12576. }
  12577. if (methodDef->mIsLocalMethod)
  12578. {
  12579. auto rootMethodState = mCurMethodState->GetRootMethodState();
  12580. BfLocalMethod* localMethod;
  12581. if (rootMethodState->mLocalMethodCache.TryGetValue(methodDef->mName, &localMethod))
  12582. {
  12583. // Handle the def in the correct method state
  12584. return GetLocalMethodInstance(localMethod, methodGenericArguments);
  12585. }
  12586. BFMODULE_FATAL(this, "Cannot find local method");
  12587. return BfModuleMethodInstance();
  12588. }
  12589. #ifdef _DEBUG
  12590. for (auto arg : methodGenericArguments)
  12591. BF_ASSERT(!arg->IsVar());
  12592. #endif
  12593. BF_ASSERT(methodDef->mMethodType != BfMethodType_Ignore);
  12594. // We need to do the 'mNeedsMethodProcessing' check because we want to do a proper initial "awaiting reference" population
  12595. // on the methods before we handle an on-demand situation. This also ensures that our type options are set before doing
  12596. // a FinishInit
  12597. if ((typeInst->IsIncomplete()) &&
  12598. (!typeInst->mResolvingVarField) && (!typeInst->mTypeFailed))
  12599. {
  12600. // For autocomplete, we still may not actually generate methods. This shouldn't matter, and on-demand works differently
  12601. // for resolve-only because we don't differentiate between reified/unreified there
  12602. if ((methodDef->mIsStatic) /*&& (mIsComptimeModule)*/)
  12603. {
  12604. if (!typeInst->DefineStateAllowsStaticMethods())
  12605. PopulateType(typeInst, BfPopulateType_AllowStaticMethods);
  12606. }
  12607. else
  12608. PopulateType(typeInst, BfPopulateType_Full);
  12609. if (typeInst->mDefineState < BfTypeDefineState_Defined)
  12610. {
  12611. if (!mCompiler->EnsureCeUnpaused(typeInst))
  12612. {
  12613. BfLogSysM("GetMethodInstance (DefineState < BfTypeDefineState_Defined)) bailing due to IsCePaused\n");
  12614. return BfModuleMethodInstance();
  12615. }
  12616. }
  12617. }
  12618. bool tryModuleMethodLookup = false;
  12619. BfModuleMethodInstance moduleMethodInst;
  12620. BfModule* instModule = typeInst->mModule;
  12621. if (keepInCurrentModule)
  12622. {
  12623. // Stay here
  12624. instModule = this;
  12625. }
  12626. if (this == mContext->mUnreifiedModule)
  12627. {
  12628. // Stay in this 'resolve only' module here
  12629. }
  12630. else if (flags & BfGetMethodInstanceFlag_ExplicitResolveOnlyPass)
  12631. {
  12632. BF_ASSERT(this == mContext->mUnreifiedModule);
  12633. }
  12634. else if (flags & BfGetMethodInstanceFlag_ExplicitSpecializedModule)
  12635. {
  12636. BF_ASSERT(instModule == mParentModule);
  12637. }
  12638. else if (instModule != this)
  12639. {
  12640. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mMethodInfoEx != NULL) && (mCurMethodInstance->mMethodInfoEx->mMinDependDepth >= 32))
  12641. flags = (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_DepthExceeded);
  12642. if ((!mIsComptimeModule) && (!mIsReified) && (instModule->mIsReified))
  12643. {
  12644. BF_ASSERT(!mCompiler->mIsResolveOnly);
  12645. // A resolve-only module is specializing a method from a type in a reified module,
  12646. // we need to take care that this doesn't cause anything new to become reified
  12647. BfModuleMethodInstance moduleMethodInstance = mContext->mUnreifiedModule->GetMethodInstance(typeInst, methodDef, methodGenericArguments, (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_ExplicitResolveOnlyPass), foreignType);
  12648. if (!moduleMethodInstance)
  12649. return moduleMethodInstance;
  12650. SetMethodDependency(moduleMethodInstance.mMethodInstance);
  12651. return moduleMethodInstance;
  12652. }
  12653. else
  12654. {
  12655. if ((!mIsComptimeModule) && (mIsReified) && (!instModule->mIsReified))
  12656. {
  12657. if (!typeInst->IsUnspecializedType())
  12658. {
  12659. if (!instModule->mReifyQueued)
  12660. {
  12661. BF_ASSERT((instModule != mContext->mUnreifiedModule) && (instModule != mContext->mScratchModule));
  12662. BF_ASSERT((mCompiler->mCompileState != BfCompiler::CompileState_Unreified) && (mCompiler->mCompileState != BfCompiler::CompileState_VData));
  12663. BfLogSysM("Queueing ReifyModule: %p\n", instModule);
  12664. mContext->mReifyModuleWorkList.Add(instModule);
  12665. instModule->mReifyQueued = true;
  12666. }
  12667. BfLogSysM("REIFIED(GetMethodInstance QueueSpecializationRequest): %s %s MethodDef:%p RefModule:%s RefMethod:%p\n", TypeToString(typeInst).c_str(), methodDef->mName.c_str(), methodDef, mModuleName.c_str(), mCurMethodInstance);
  12668. // This ensures that the method will actually be created when it gets reified
  12669. BfMethodSpecializationRequest* specializationRequest = mContext->mMethodSpecializationWorkList.Alloc();
  12670. specializationRequest->mFromModule = typeInst->mModule;
  12671. specializationRequest->mFromModuleRevision = typeInst->mModule->mRevision;
  12672. specializationRequest->Init(typeInst, foreignType, methodDef);
  12673. //specializationRequest->mMethodDef = methodDef;
  12674. specializationRequest->mMethodGenericArguments = methodGenericArguments;
  12675. specializationRequest->mType = typeInst;
  12676. specializationRequest->mFlags = flags;
  12677. }
  12678. }
  12679. auto defFlags = (BfGetMethodInstanceFlags)(flags & ~BfGetMethodInstanceFlag_ForceInline);
  12680. defFlags = (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_NoReference);
  12681. if (mIsComptimeModule)
  12682. {
  12683. defFlags = (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_MethodInstanceOnly);
  12684. if (!mCompiler->mIsResolveOnly)
  12685. defFlags = (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_NoForceReification | BfGetMethodInstanceFlag_Unreified | BfGetMethodInstanceFlag_MethodInstanceOnly);
  12686. }
  12687. // Not extern
  12688. // Create the instance in the proper module and then create a reference in this one
  12689. moduleMethodInst = instModule->GetMethodInstance(typeInst, methodDef, methodGenericArguments, defFlags, foreignType, this);
  12690. if (!moduleMethodInst)
  12691. return moduleMethodInst;
  12692. tryModuleMethodLookup = true;
  12693. if ((mIsReified) && (!moduleMethodInst.mMethodInstance->mIsReified))
  12694. {
  12695. CheckHotMethod(moduleMethodInst.mMethodInstance, "");
  12696. }
  12697. }
  12698. }
  12699. if (tryModuleMethodLookup)
  12700. {
  12701. SetMethodDependency(moduleMethodInst.mMethodInstance);
  12702. return ReferenceExternalMethodInstance(moduleMethodInst.mMethodInstance, flags);
  12703. }
  12704. if (((flags & BfGetMethodInstanceFlag_ForceInline) != 0) && (!methodDef->mAlwaysInline))
  12705. {
  12706. auto moduleMethodInstance = GetMethodInstance(typeInst, methodDef, methodGenericArguments, (BfGetMethodInstanceFlags)(flags & ~BfGetMethodInstanceFlag_ForceInline), foreignType);
  12707. if (moduleMethodInstance)
  12708. return ReferenceExternalMethodInstance(moduleMethodInstance.mMethodInstance, flags);
  12709. return moduleMethodInst;
  12710. }
  12711. bool isReified = mIsReified /* || ((flags & BfGetMethodInstanceFlag_ExplicitResolveOnlyPass) != 0)*/;
  12712. bool hadConcreteInterfaceGenericArgument = false;
  12713. if ((flags & BfGetMethodInstanceFlag_Unreified) != 0)
  12714. isReified = false;
  12715. if ((flags & BfGetMethodInstanceFlag_ExplicitResolveOnlyPass) != 0)
  12716. {
  12717. isReified = false;
  12718. }
  12719. BfTypeVector sanitizedMethodGenericArguments;
  12720. SizedArray<BfProject*, 4> projectList;
  12721. bool isUnspecializedPass = (flags & BfGetMethodInstanceFlag_UnspecializedPass) != 0;
  12722. if ((isUnspecializedPass) && (methodDef->mGenericParams.size() == 0))
  12723. isUnspecializedPass = false;
  12724. // 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
  12725. bool isExternalExtensionMethod = false;
  12726. if ((!typeInst->IsUnspecializedType()) && (!isUnspecializedPass))
  12727. {
  12728. if (((flags & BfGetMethodInstanceFlag_ForeignMethodDef) == 0) &&
  12729. (methodDef->mDeclaringType != NULL) &&
  12730. (methodDef->mDeclaringType->mProject != typeInst->mTypeDef->mProject))
  12731. {
  12732. auto specProject = methodDef->mDeclaringType->mProject;
  12733. isExternalExtensionMethod = true;
  12734. if (typeInst->IsGenericTypeInstance())
  12735. {
  12736. auto genericTypeInst = (BfTypeInstance*)typeInst;
  12737. if (genericTypeInst->mGenericTypeInfo->mProjectsReferenced.empty())
  12738. genericTypeInst->GenerateProjectsReferenced();
  12739. if (genericTypeInst->mGenericTypeInfo->mProjectsReferenced.Contains(specProject))
  12740. {
  12741. // This is a generic type where a generic param is already confined to the project in question
  12742. isExternalExtensionMethod = false;
  12743. }
  12744. }
  12745. if (isExternalExtensionMethod)
  12746. {
  12747. BF_ASSERT(typeInst->mTypeDef->mIsCombinedPartial);
  12748. projectList.push_back(methodDef->mDeclaringType->mProject);
  12749. }
  12750. }
  12751. }
  12752. if ((!isUnspecializedPass) && (methodGenericArguments.size() != 0))
  12753. {
  12754. int typeProjectsCounts = 0;
  12755. if (typeInst->IsGenericTypeInstance())
  12756. {
  12757. auto genericTypeInst = (BfTypeInstance*)typeInst;
  12758. if (genericTypeInst->mGenericTypeInfo->mProjectsReferenced.empty())
  12759. genericTypeInst->GenerateProjectsReferenced();
  12760. typeProjectsCounts = (int)genericTypeInst->mGenericTypeInfo->mProjectsReferenced.size();
  12761. projectList.Insert(0, &genericTypeInst->mGenericTypeInfo->mProjectsReferenced[0], genericTypeInst->mGenericTypeInfo->mProjectsReferenced.size());
  12762. }
  12763. else
  12764. {
  12765. typeProjectsCounts = 1;
  12766. projectList.Insert(0, typeInst->mTypeDef->mProject);
  12767. }
  12768. isUnspecializedPass = true;
  12769. for (int genericArgIdx = 0; genericArgIdx < (int) methodGenericArguments.size(); genericArgIdx++)
  12770. {
  12771. auto genericArgType = methodGenericArguments[genericArgIdx];
  12772. //BF_ASSERT(!genericArgType->IsRef());
  12773. if (genericArgType->IsConcreteInterfaceType())
  12774. {
  12775. hadConcreteInterfaceGenericArgument = true;
  12776. auto concreteInterfaceType = (BfConcreteInterfaceType*)genericArgType;
  12777. genericArgType = concreteInterfaceType->mInterface;
  12778. }
  12779. if (genericArgType->IsGenericParam())
  12780. {
  12781. auto genericParam = (BfGenericParamType*) genericArgType;
  12782. if ((genericParam->mGenericParamKind != BfGenericParamKind_Method) || (genericParam->mGenericParamIdx != genericArgIdx))
  12783. isUnspecializedPass = false;
  12784. }
  12785. else
  12786. {
  12787. BfTypeUtils::GetProjectList(genericArgType, &projectList, typeProjectsCounts);
  12788. isUnspecializedPass = false;
  12789. }
  12790. sanitizedMethodGenericArguments.push_back(genericArgType);
  12791. }
  12792. if ((int)projectList.size() > typeProjectsCounts)
  12793. {
  12794. // Just leave the new items
  12795. projectList.RemoveRange(0, typeProjectsCounts);
  12796. std::sort(projectList.begin(), projectList.end(), [](BfProject* lhs, BfProject*rhs)
  12797. {
  12798. return lhs->mName < rhs->mName;
  12799. });
  12800. }
  12801. else
  12802. {
  12803. projectList.Clear();
  12804. }
  12805. }
  12806. const BfTypeVector& lookupMethodGenericArguments = isUnspecializedPass ? BfTypeVector() : sanitizedMethodGenericArguments;
  12807. BfMethodInstanceGroup* methodInstGroup = NULL;
  12808. if ((flags & BfGetMethodInstanceFlag_ForeignMethodDef) != 0)
  12809. {
  12810. BF_ASSERT(!typeInst->IsInterface());
  12811. //for (auto& checkGroup : typeInst->mMethodInstanceGroups)
  12812. for (int methodIdx = (int)typeInst->mTypeDef->mMethods.size(); methodIdx < (int)typeInst->mMethodInstanceGroups.size(); methodIdx++)
  12813. {
  12814. auto& checkGroup = typeInst->mMethodInstanceGroups[methodIdx];
  12815. // if (checkGroup.mDefault == NULL)
  12816. // {
  12817. // // This should only be for when we explicitly add a spot so we can set mOnDemandKind
  12818. // BF_ASSERT(methodIdx == typeInst->mMethodInstanceGroups.size() - 1);
  12819. // methodInstGroup = &checkGroup;
  12820. // break;
  12821. // }
  12822. if ((checkGroup.mDefault != NULL) && (checkGroup.mDefault->mMethodDef == methodDef))
  12823. {
  12824. methodInstGroup = &checkGroup;
  12825. break;
  12826. }
  12827. }
  12828. if (methodInstGroup == NULL)
  12829. {
  12830. if (lookupMethodGenericArguments.size() != 0)
  12831. {
  12832. BF_ASSERT((flags & BfGetMethodInstanceFlag_ForeignMethodDef) != 0);
  12833. auto defaultMethodInstance = GetMethodInstance(typeInst, methodDef, BfTypeVector(),
  12834. (BfGetMethodInstanceFlags)((flags & (BfGetMethodInstanceFlag_ForeignMethodDef)) | BfGetMethodInstanceFlag_UnspecializedPass | BfGetMethodInstanceFlag_MethodInstanceOnly), foreignType);
  12835. methodInstGroup = defaultMethodInstance.mMethodInstance->mMethodInstanceGroup;
  12836. }
  12837. else
  12838. {
  12839. // Allocate a new entry
  12840. typeInst->mMethodInstanceGroups.Resize(typeInst->mMethodInstanceGroups.size() + 1);
  12841. methodInstGroup = &typeInst->mMethodInstanceGroups.back();
  12842. methodInstGroup->mMethodIdx = (int)typeInst->mMethodInstanceGroups.size() - 1;
  12843. methodInstGroup->mOwner = typeInst;
  12844. // if (methodInstGroup->mOnDemandKind == BfMethodOnDemandKind_NotSet)
  12845. // methodInstGroup->mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  12846. if (mCompiler->mOptions.mCompileOnDemandKind == BfCompileOnDemandKind_AlwaysInclude)
  12847. methodInstGroup->mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  12848. else
  12849. {
  12850. methodInstGroup->mOnDemandKind = BfMethodOnDemandKind_Decl_AwaitingDecl;
  12851. if (!mIsScratchModule)
  12852. mOnDemandMethodCount++;
  12853. }
  12854. }
  12855. }
  12856. }
  12857. else
  12858. {
  12859. if (methodDef->mIdx >= typeInst->mMethodInstanceGroups.mSize)
  12860. PopulateType(typeInst, BfPopulateType_DataAndMethods);
  12861. if (methodDef->mIdx >= typeInst->mMethodInstanceGroups.mSize)
  12862. {
  12863. InternalError("GetMethodInstance OOB error", methodDef->GetRefNode());
  12864. return BfModuleMethodInstance();
  12865. }
  12866. methodInstGroup = &typeInst->mMethodInstanceGroups[methodDef->mIdx];
  12867. }
  12868. if (methodInstGroup->mOnDemandKind == BfMethodOnDemandKind_NotSet)
  12869. {
  12870. if (typeInst->mDefineState > BfTypeDefineState_DefinedAndMethodsSlotted)
  12871. {
  12872. BfLogSysM("Forcing BfMethodOnDemandKind_NotSet to BfMethodOnDemandKind_AlwaysInclude for Method:%s in Type:%p\n", methodDef->mName.c_str(), typeInst);
  12873. methodInstGroup->mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  12874. }
  12875. }
  12876. BfIRFunction prevIRFunc;
  12877. bool doingRedeclare = false;
  12878. BfMethodInstance* methodInstance = NULL;
  12879. auto _SetReified = [&]()
  12880. {
  12881. if (!mCompiler->mIsResolveOnly)
  12882. BF_ASSERT(mCompiler->mCompileState <= BfCompiler::CompileState_Normal);
  12883. methodInstance->mIsReified = true;
  12884. };
  12885. if (lookupMethodGenericArguments.size() == 0)
  12886. {
  12887. methodInstance = methodInstGroup->mDefault;
  12888. if ((methodInstance != NULL) && ((flags & BfGetMethodInstanceFlag_MethodInstanceOnly) != 0))
  12889. return methodInstance;
  12890. if ((methodInstance != NULL) && (isReified) && (!methodInstance->mIsReified))
  12891. {
  12892. MarkDerivedDirty(typeInst);
  12893. if (!HasCompiledOutput())
  12894. {
  12895. BfLogSysM("Marking non-compiled-output module method instance as reified: %p\n", methodInstance);
  12896. _SetReified();
  12897. CheckHotMethod(methodInstance, "");
  12898. }
  12899. else if ((flags & BfGetMethodInstanceFlag_NoForceReification) != 0)
  12900. {
  12901. // We don't need to force reification if we're in an unspecialized generic- we can wait for
  12902. // the specializations to handle that for us
  12903. return BfModuleMethodInstance(methodInstance);
  12904. }
  12905. else if (methodInstGroup->mOnDemandKind == BfMethodOnDemandKind_Referenced)
  12906. {
  12907. if (methodDef->mIsAbstract)
  12908. {
  12909. BfLogSysM("Reifying abstract unreified method instance: %p IRFunction:%d\n", methodInstance, methodInstance->mIRFunction.mId);
  12910. _SetReified();
  12911. }
  12912. else
  12913. {
  12914. BfLogSysM("Re-declaring processed but unreified method instance: %p IRFunction:%d\n", methodInstance, methodInstance->mIRFunction.mId);
  12915. methodInstGroup->mOnDemandKind = BfMethodOnDemandKind_NoDecl_AwaitingReference;
  12916. methodInstance->UndoDeclaration(!methodInstance->mIRFunction.IsFake());
  12917. doingRedeclare = true;
  12918. mOnDemandMethodCount++;
  12919. VerifyOnDemandMethods();
  12920. }
  12921. }
  12922. else
  12923. {
  12924. BfLogSysM("Marking unprocessed method instance as reified: %p\n", methodInstance);
  12925. // We haven't processed it yet
  12926. _SetReified();
  12927. CheckHotMethod(methodInstance, "");
  12928. if (methodInstance->mDeclModule == this)
  12929. {
  12930. if (methodInstance->mMethodProcessRequest != NULL)
  12931. {
  12932. // Disconnect method process request
  12933. BF_ASSERT(methodInstance->mMethodProcessRequest->mFromModule == this);
  12934. }
  12935. }
  12936. else
  12937. {
  12938. if (methodInstance->mMethodProcessRequest != NULL)
  12939. {
  12940. // Disconnect method process request
  12941. methodInstance->mMethodProcessRequest->mMethodInstance = NULL;
  12942. methodInstance->mMethodProcessRequest = NULL;
  12943. }
  12944. if (methodInstance->mDeclModule == mContext->mUnreifiedModule)
  12945. {
  12946. // Add new request in proper module
  12947. methodInstance->mDeclModule = this;
  12948. }
  12949. else
  12950. {
  12951. if (methodInstance->mDeclModule == NULL)
  12952. {
  12953. //
  12954. }
  12955. else if (methodInstance->mDeclModule != this)
  12956. {
  12957. // Is from specialized module?
  12958. BF_ASSERT(methodInstance->mDeclModule->mParentModule == this);
  12959. }
  12960. }
  12961. if ((!methodInstance->mIRFunction) || (methodInstance->mIRFunction.IsFake()))
  12962. {
  12963. methodInstance->mIRFunction = BfIRFunction();
  12964. if (!mIsModuleMutable)
  12965. StartExtension();
  12966. if ((!mBfIRBuilder->mIgnoreWrites) && (methodInstance->mDeclModule != NULL))
  12967. {
  12968. StringT<512> mangledName;
  12969. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), methodInstance);
  12970. bool isIntrinsic = false;
  12971. SetupIRFunction(methodInstance, mangledName, false, &isIntrinsic);
  12972. BfLogSysM("Creating new IRFunction %d\n", methodInstance->mIRFunction.mId);
  12973. }
  12974. }
  12975. AddMethodToWorkList(methodInstance);
  12976. }
  12977. }
  12978. }
  12979. }
  12980. else
  12981. {
  12982. if (methodInstGroup->mDefault == NULL)
  12983. {
  12984. auto defaultMethodInstance = GetMethodInstance(typeInst, methodDef, BfTypeVector(),
  12985. (BfGetMethodInstanceFlags)((flags & (BfGetMethodInstanceFlag_ForeignMethodDef)) | BfGetMethodInstanceFlag_UnspecializedPass | BfGetMethodInstanceFlag_MethodInstanceOnly), foreignType);
  12986. methodInstGroup = defaultMethodInstance.mMethodInstance->mMethodInstanceGroup;
  12987. }
  12988. BF_ASSERT(lookupMethodGenericArguments.size() != 0);
  12989. if (methodInstGroup->mMethodSpecializationMap == NULL)
  12990. methodInstGroup->mMethodSpecializationMap = new BfMethodInstanceGroup::MapType();
  12991. BfMethodInstance** methodInstancePtr = NULL;
  12992. if (methodInstGroup->mMethodSpecializationMap->TryGetValue(lookupMethodGenericArguments, &methodInstancePtr))
  12993. {
  12994. methodInstance = *methodInstancePtr;
  12995. if ((flags & BfGetMethodInstanceFlag_MethodInstanceOnly) != 0)
  12996. return methodInstance;
  12997. if ((methodInstance->mRequestedByAutocomplete) && (!mCompiler->IsAutocomplete()))
  12998. {
  12999. BfLogSysM("Setting mRequestedByAutocomplete=false for method instance %p\n", methodInstance);
  13000. // We didn't want to process this message yet if it was autocomplete-specific, but now we will
  13001. if (methodInstance->mMethodProcessRequest == NULL)
  13002. AddMethodToWorkList(methodInstance);
  13003. methodInstance->mRequestedByAutocomplete = false;
  13004. }
  13005. if ((isReified) && (!methodInstance->mIsReified))
  13006. {
  13007. MarkDerivedDirty(typeInst);
  13008. if (methodInstance->mHasBeenProcessed)
  13009. {
  13010. BfLogSysM("Deleting processed but unreified specialized method instance %p\n", methodInstance);
  13011. delete methodInstance;
  13012. methodInstGroup->mMethodSpecializationMap->Remove(lookupMethodGenericArguments);
  13013. methodInstance = NULL;
  13014. }
  13015. else if ((!methodInstance->mIRFunction) || (methodInstance->mIRFunction.IsFake()))
  13016. {
  13017. BfLogSysM("Deleting declared but uncreated specialized method instance %p\n", methodInstance);
  13018. delete methodInstance;
  13019. methodInstGroup->mMethodSpecializationMap->Remove(lookupMethodGenericArguments);
  13020. methodInstance = NULL;
  13021. }
  13022. else
  13023. {
  13024. BfLogSysM("Reifying declared but unreified method instance %p\n", methodInstance);
  13025. // We haven't processed it yet
  13026. _SetReified();
  13027. CheckHotMethod(methodInstance, "");
  13028. if (methodInstance->mMethodProcessRequest == NULL)
  13029. AddMethodToWorkList(methodInstance);
  13030. }
  13031. }
  13032. }
  13033. }
  13034. auto _CheckDllImport = [&]()
  13035. {
  13036. auto declModule = methodInstance->mDeclModule;
  13037. if ((!methodInstance->mIRFunction) && (declModule->mIsModuleMutable) && (!declModule->mBfIRBuilder->mIgnoreWrites))
  13038. {
  13039. auto importKind = methodInstance->GetImportCallKind();
  13040. if (importKind != BfImportCallKind_None)
  13041. {
  13042. BfLogSysM("DllImportGlobalVar creating %p in module %p from module %p\n", methodInstance, declModule, this);
  13043. methodInstance->mIRFunction = mBfIRBuilder->GetFakeVal();
  13044. auto func = declModule->CreateDllImportGlobalVar(methodInstance, true);
  13045. BF_ASSERT(func);
  13046. declModule->mFuncReferences[methodInstance] = func;
  13047. }
  13048. }
  13049. };
  13050. if ((methodInstance != NULL) && (!doingRedeclare))
  13051. {
  13052. SetMethodDependency(methodInstance);
  13053. if (methodInstance->mMethodInstanceGroup->mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingReference)
  13054. {
  13055. /*if ((!mCompiler->mIsResolveOnly) && (!isReified))
  13056. BF_ASSERT(!methodInstance->mIsReified);*/
  13057. if ((!mCompiler->mIsResolveOnly) && (isReified))
  13058. {
  13059. auto refModule = referencingModule;
  13060. if (refModule == NULL)
  13061. refModule = this;
  13062. BfLogSysM("REIFIED(GetMethodInstance Reference): %s MethodDef:%p MethodInst:%p RefModule:%s RefMethod:%p\n", methodInstance->mMethodDef->mName.c_str(), methodDef, methodInstance, refModule->mModuleName.c_str(), refModule->mCurMethodInstance);
  13063. }
  13064. if (methodInstance->mIsReified != isReified)
  13065. {
  13066. BfLogSysM("GetMethodInstance %p Decl_AwaitingReference setting reified to %d\n", methodInstance, isReified);
  13067. }
  13068. if ((!isReified) &&
  13069. ((methodInstance->mDeclModule == NULL) || (!methodInstance->mDeclModule->mIsModuleMutable)))
  13070. {
  13071. methodInstance->mDeclModule = mContext->mUnreifiedModule;
  13072. methodInstance->mIRFunction = BfIRFunction();
  13073. }
  13074. methodInstance->mIsReified = isReified;
  13075. if ((methodInstance->mHotMethod != NULL) && (!mCompiler->IsHotCompile()) && (isReified))
  13076. {
  13077. methodInstance->mHotMethod->mFlags = (BfHotDepDataFlags)(methodInstance->mHotMethod->mFlags | BfHotDepDataFlag_IsOriginalBuild);
  13078. }
  13079. if (!methodInstance->mMethodDef->mIsAbstract)
  13080. {
  13081. if ((methodInstance->mMethodDef->mMethodType == BfMethodType_Mixin) && (!methodInstance->mDeclModule->mIsModuleMutable))
  13082. {
  13083. // Wait until unreified
  13084. }
  13085. else
  13086. AddMethodToWorkList(methodInstance);
  13087. }
  13088. else
  13089. {
  13090. methodInstance->mMethodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_Referenced;
  13091. auto owningModule = methodInstance->GetOwner()->mModule;
  13092. if (!owningModule->mIsScratchModule)
  13093. {
  13094. owningModule->mOnDemandMethodCount--;
  13095. owningModule->VerifyOnDemandMethods();
  13096. }
  13097. }
  13098. }
  13099. if (mExtensionCount > 0)
  13100. {
  13101. if ((mIsModuleMutable) && (!methodInstance->mIRFunction) &&
  13102. ((projectList.IsEmpty() || ((flags & BfGetMethodInstanceFlag_ExplicitSpecializedModule) != 0))))
  13103. {
  13104. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, false);
  13105. if (mAwaitingInitFinish)
  13106. FinishInit();
  13107. // We need to refer to a function that was defined in a prior module
  13108. bool isInlined = (methodInstance->mAlwaysInline) || ((flags & BfGetMethodInstanceFlag_ForceInline) != 0);
  13109. if (methodInstance->mIsIntrinsic)
  13110. isInlined = false;
  13111. methodInstance->mIRFunction = CreateFunctionFrom(methodInstance, false, isInlined);
  13112. BF_ASSERT((methodInstance->mDeclModule == this) || (methodInstance->mDeclModule == mContext->mUnreifiedModule) || (methodInstance->mDeclModule == NULL));
  13113. methodInstance->mDeclModule = this;
  13114. // Add this inlined def to ourselves
  13115. if ((methodInstance->mAlwaysInline) && (HasCompiledOutput()) && (!methodInstance->mIsUnspecialized) && ((flags & BfGetMethodInstanceFlag_NoInline) == 0))
  13116. {
  13117. mIncompleteMethodCount++;
  13118. BfInlineMethodRequest* inlineMethodRequest = mContext->mInlineMethodWorkList.Alloc();
  13119. inlineMethodRequest->mType = typeInst;
  13120. inlineMethodRequest->mFromModule = this;
  13121. inlineMethodRequest->mFunc = methodInstance->mIRFunction;
  13122. inlineMethodRequest->mFromModuleRevision = mRevision;
  13123. inlineMethodRequest->mFromModuleRebuildIdx = mRebuildIdx;
  13124. inlineMethodRequest->mMethodInstance = methodInstance;
  13125. BfLogSysM("mInlineMethodWorkList %p for method %p in module %p in GetMethodInstance\n", inlineMethodRequest, methodInstance, this);
  13126. BF_ASSERT(mIsModuleMutable);
  13127. }
  13128. }
  13129. }
  13130. if (IsSkippingExtraResolveChecks())
  13131. return BfModuleMethodInstance(methodInstance, BfIRFunction());
  13132. else
  13133. {
  13134. if ((flags & (BfGetMethodInstanceFlag_MethodInstanceOnly | BfGetMethodInstanceFlag_NoReference)) != 0)
  13135. return methodInstance;
  13136. if (methodInstance->mDeclModule != this)
  13137. return ReferenceExternalMethodInstance(methodInstance, flags);
  13138. _CheckDllImport();
  13139. return BfModuleMethodInstance(methodInstance);
  13140. }
  13141. }
  13142. if (!doingRedeclare)
  13143. {
  13144. BfModule* specModule = NULL;
  13145. if ((!keepInCurrentModule) && (projectList.size() > 0) && (!isUnspecializedPass) && (HasCompiledOutput()) && (!mIsScratchModule))
  13146. {
  13147. specModule = GetSpecializedMethodModule(projectList);
  13148. }
  13149. if ((specModule != NULL) && (specModule != this))
  13150. {
  13151. auto specMethodInstance = specModule->GetMethodInstance(typeInst, methodDef, methodGenericArguments, (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_ExplicitSpecializedModule));
  13152. if (mAwaitingInitFinish)
  13153. return BfModuleMethodInstance(specMethodInstance.mMethodInstance, BfIRFunction());
  13154. if ((flags & (BfGetMethodInstanceFlag_MethodInstanceOnly | BfGetMethodInstanceFlag_NoReference)) != 0)
  13155. return specMethodInstance.mMethodInstance;
  13156. return ReferenceExternalMethodInstance(specMethodInstance.mMethodInstance, flags);
  13157. }
  13158. if ((!isUnspecializedPass) && (methodGenericArguments.size() != 0) && (methodInstGroup->mDefault == NULL))
  13159. {
  13160. // We are attempting to specialize but we don't have the unspecialized method yet. Generate that first.
  13161. GetMethodInstance(typeInst, methodDef, BfTypeVector(), BfGetMethodInstanceFlag_UnspecializedPass);
  13162. }
  13163. }
  13164. if (methodInstance == NULL)
  13165. {
  13166. if (!mCompiler->EnsureCeUnpaused(typeInst))
  13167. {
  13168. BfLogSysM("GetMethodInstance (methodInstance == NULL) bailing due to IsCePaused\n");
  13169. return BfModuleMethodInstance();
  13170. }
  13171. if (lookupMethodGenericArguments.size() == 0)
  13172. {
  13173. BF_ASSERT(methodInstGroup->mDefault == NULL);
  13174. methodInstance = new BfMethodInstance();
  13175. methodInstGroup->mDefault = methodInstance;
  13176. BF_ASSERT(typeInst->mDefineState > BfTypeDefineState_Declared);
  13177. BfLogSysM("Created Default MethodInst: %p TypeInst: %p Group: %p\n", methodInstance, typeInst, methodInstGroup);
  13178. }
  13179. else
  13180. {
  13181. bool depthExceeded = ((flags & BfGetMethodInstanceFlag_DepthExceeded) != 0);
  13182. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mMethodInfoEx != NULL) && (mCurMethodInstance->mMethodInfoEx->mMinDependDepth >= 32))
  13183. depthExceeded = true;
  13184. if (depthExceeded)
  13185. {
  13186. Fail("Generic method dependency depth exceeded", methodDef->GetRefNode());
  13187. return BfModuleMethodInstance();
  13188. }
  13189. BfMethodInstance** methodInstancePtr = NULL;
  13190. bool added = methodInstGroup->mMethodSpecializationMap->TryAdd(lookupMethodGenericArguments, NULL, &methodInstancePtr);
  13191. BF_ASSERT(added);
  13192. methodInstance = new BfMethodInstance();
  13193. *methodInstancePtr = methodInstance;
  13194. if (mCompiler->IsAutocomplete())
  13195. methodInstance->mRequestedByAutocomplete = true;
  13196. BfLogSysM("Created Specialized MethodInst: %p TypeInst: %p\n", methodInstance, typeInst);
  13197. }
  13198. if ((prevIRFunc) && (!prevIRFunc.IsFake()))
  13199. methodInstance->mIRFunction = prevIRFunc; // Take it over
  13200. }
  13201. methodInstance->mMethodDef = methodDef;
  13202. methodInstance->mAlwaysInline = methodDef->mAlwaysInline;
  13203. methodInstance->mMethodInstanceGroup = methodInstGroup;
  13204. methodInstance->mIsReified = isReified;
  13205. SetupMethodIdHash(methodInstance);
  13206. if (hadConcreteInterfaceGenericArgument)
  13207. methodInstance->mIgnoreBody = true;
  13208. if ((flags & BfGetMethodInstanceFlag_ForeignMethodDef) != 0)
  13209. {
  13210. methodInstance->mIsForeignMethodDef = true;
  13211. BF_ASSERT(foreignType != NULL);
  13212. methodInstance->GetMethodInfoEx()->mForeignType = foreignType;
  13213. }
  13214. if ((typeInst->IsInstanceOf(mCompiler->mValueTypeTypeDef)) && (methodDef->mName == BF_METHODNAME_EQUALS))
  13215. {
  13216. if (!lookupMethodGenericArguments.empty())
  13217. {
  13218. auto compareType = lookupMethodGenericArguments[0];
  13219. PopulateType(compareType, BfPopulateType_Data);
  13220. if (compareType->IsSplattable())
  13221. methodInstance->mAlwaysInline = true;
  13222. }
  13223. }
  13224. if (methodDef->mMethodType == BfMethodType_Init)
  13225. {
  13226. methodInstance->mMangleWithIdx = true;
  13227. }
  13228. if (methodDef->mAppendKind > BfAllowAppendKind_No)
  13229. {
  13230. methodInstance->mMangleWithIdx = true;
  13231. }
  13232. BF_ASSERT(typeInst == methodInstance->GetOwner());
  13233. auto methodDeclaration = methodDef->GetMethodDeclaration();
  13234. if (isUnspecializedPass)
  13235. {
  13236. for (int genericParamIdx = 0; genericParamIdx < (int) methodDef->mGenericParams.size(); genericParamIdx++)
  13237. {
  13238. auto genericParamType = GetGenericParamType(BfGenericParamKind_Method, genericParamIdx);
  13239. methodInstance->GetMethodInfoEx()->mMethodGenericArguments.Add(genericParamType);
  13240. }
  13241. }
  13242. else if ((methodDeclaration != NULL) && (methodDeclaration->mGenericParams != NULL))
  13243. {
  13244. if (!sanitizedMethodGenericArguments.IsEmpty())
  13245. methodInstance->GetMethodInfoEx()->mMethodGenericArguments = sanitizedMethodGenericArguments;
  13246. if (methodDef->mGenericParams.size() != sanitizedMethodGenericArguments.size())
  13247. {
  13248. Fail("Internal error");
  13249. BFMODULE_FATAL(this, "Generic method argument counts mismatch");
  13250. return NULL;
  13251. }
  13252. for (auto genericArg : sanitizedMethodGenericArguments)
  13253. {
  13254. if (genericArg->IsPrimitiveType())
  13255. genericArg = GetWrappedStructType(genericArg);
  13256. if (genericArg != NULL)
  13257. AddDependency(genericArg, typeInst, BfDependencyMap::DependencyFlag_MethodGenericArg);
  13258. }
  13259. }
  13260. // Generic constraints
  13261. if (!methodDef->mGenericParams.IsEmpty())
  13262. {
  13263. BF_ASSERT(methodInstance->GetMethodInfoEx()->mGenericParams.IsEmpty());
  13264. for (int genericParamIdx = 0; genericParamIdx < (int)methodDef->mGenericParams.size(); genericParamIdx++)
  13265. {
  13266. auto genericParamInstance = new BfGenericMethodParamInstance(methodDef, genericParamIdx);
  13267. methodInstance->GetMethodInfoEx()->mGenericParams.push_back(genericParamInstance);
  13268. }
  13269. }
  13270. for (int externConstraintIdx = 0; externConstraintIdx < (int)methodDef->mExternalConstraints.size(); externConstraintIdx++)
  13271. {
  13272. auto genericParamInstance = new BfGenericMethodParamInstance(methodDef, externConstraintIdx + (int)methodDef->mGenericParams.size());
  13273. methodInstance->GetMethodInfoEx()->mGenericParams.push_back(genericParamInstance);
  13274. }
  13275. bool addToWorkList = !processNow;
  13276. if (mCompiler->GetAutoComplete() != NULL)
  13277. {
  13278. if (typeInst->IsSpecializedByAutoCompleteMethod())
  13279. addToWorkList = false;
  13280. if (methodInstance->mRequestedByAutocomplete)
  13281. addToWorkList = false;
  13282. }
  13283. BfModule* declareModule;
  13284. //
  13285. {
  13286. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, methodInstance);
  13287. declareModule = GetOrCreateMethodModule(methodInstance);
  13288. }
  13289. if ((doingRedeclare) && (methodInstance->mDeclModule != mContext->mUnreifiedModule))
  13290. declareModule = methodInstance->mDeclModule;
  13291. BF_ASSERT(declareModule != NULL);
  13292. methodInstance->mDeclModule = declareModule;
  13293. if ((!methodInstance->mIsReified) && (mCompiler->mCompileState != BfCompiler::CompileState_Normal))
  13294. {
  13295. // We can be sure this method won't become reified later. Normally we can "go either way" with an unreified method
  13296. // of a reified module -
  13297. // If we declare it in the reified module then we can switch it to "reified" before actual processing without any extra work,
  13298. // BUT if we don't reify it then we have to remove the body after processing.
  13299. // 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
  13300. // the proper reified module.
  13301. declareModule = mContext->mUnreifiedModule;
  13302. }
  13303. else if ((!declareModule->mIsModuleMutable) && (!mCompiler->mIsResolveOnly))
  13304. {
  13305. if (!methodInstance->mIsReified)
  13306. {
  13307. declareModule = mContext->mUnreifiedModule;
  13308. }
  13309. else
  13310. {
  13311. declareModule->PrepareForIRWriting(methodInstance->GetOwner());
  13312. }
  13313. }
  13314. SetMethodDependency(methodInstance);
  13315. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(declareModule->mCurMethodInstance, methodInstance);
  13316. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(declareModule->mCurTypeInstance, typeInst);
  13317. SetAndRestoreValue<BfFilePosition> prevFilePos(declareModule->mCurFilePosition);
  13318. if ((methodDef->mMethodType == BfMethodType_Mixin) && (methodDef->mGenericParams.size() != 0) && (!isUnspecializedPass))
  13319. {
  13320. // For mixins we only process the unspecialized version
  13321. addToWorkList = false;
  13322. }
  13323. if (((flags & BfGetMethodInstanceFlag_MethodInstanceOnly) != 0) && (methodInstGroup->mOnDemandKind != BfMethodOnDemandKind_AlwaysInclude))
  13324. {
  13325. addToWorkList = false;
  13326. }
  13327. // if ((flags & BfGetMethodInstanceFlag_NoReference) != 0)
  13328. // addToWorkList = false;
  13329. declareModule->DoMethodDeclaration(methodDef->GetMethodDeclaration(), false, addToWorkList);
  13330. if (processNow)
  13331. {
  13332. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, NULL);
  13333. ProcessMethod(methodInstance);
  13334. }
  13335. if (IsSkippingExtraResolveChecks())
  13336. return BfModuleMethodInstance(methodInstance, BfIRFunction());
  13337. if (methodInstance->mDeclModule != this)
  13338. return ReferenceExternalMethodInstance(methodInstance, flags);
  13339. if (doingRedeclare)
  13340. {
  13341. _CheckDllImport();
  13342. }
  13343. return BfModuleMethodInstance(methodInstance);
  13344. }
  13345. BfModuleMethodInstance BfModule::GetMethodInstance(BfMethodInstance* methodInstance, BfGetMethodInstanceFlags flags)
  13346. {
  13347. BF_ASSERT((methodInstance->mMethodInfoEx == NULL) || (methodInstance->mMethodInfoEx->mGenericParams.IsEmpty()));
  13348. if (methodInstance->mIsForeignMethodDef)
  13349. flags = (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_ForeignMethodDef);
  13350. return GetMethodInstance(methodInstance->GetOwner(), methodInstance->mMethodDef, BfTypeVector(), flags);
  13351. }
  13352. BfMethodInstance* BfModule::GetOuterMethodInstance(BfMethodInstance* methodInstance)
  13353. {
  13354. if (!methodInstance->mMethodDef->mIsLocalMethod)
  13355. return NULL;
  13356. auto outerLocal = methodInstance->mMethodInfoEx->mClosureInstanceInfo->mLocalMethod->mOuterLocalMethod;
  13357. if (outerLocal == NULL)
  13358. return NULL;
  13359. BfTypeVector genericArgs;
  13360. for (int i = 0; i < (int)outerLocal->mMethodDef->mGenericParams.size(); i++)
  13361. genericArgs.Add(methodInstance->mMethodInfoEx->mMethodGenericArguments[i]);
  13362. return GetLocalMethodInstance(outerLocal, genericArgs).mMethodInstance;
  13363. }
  13364. void BfModule::SetupMethodIdHash(BfMethodInstance* methodInstance)
  13365. {
  13366. HashContext hashCtx;
  13367. std::function<void(BfMethodInstance*)> _MixinMethodInstance = [&](BfMethodInstance* methodInstance)
  13368. {
  13369. hashCtx.Mixin(methodInstance->GetOwner()->mTypeId);
  13370. hashCtx.Mixin(methodInstance->mMethodDef->mIdx);
  13371. if (methodInstance->GetNumGenericArguments() != 0)
  13372. {
  13373. hashCtx.Mixin((int32)methodInstance->mMethodInfoEx->mMethodGenericArguments.size());
  13374. for (auto methodGenericArg : methodInstance->mMethodInfoEx->mMethodGenericArguments)
  13375. hashCtx.Mixin(methodGenericArg->mTypeId);
  13376. }
  13377. };
  13378. _MixinMethodInstance(methodInstance);
  13379. if (methodInstance->mMethodDef->mIsLocalMethod)
  13380. {
  13381. auto outmostMethodInstance = mCurMethodState->GetRootMethodState()->mMethodInstance;
  13382. if (outmostMethodInstance != NULL)
  13383. {
  13384. BF_ASSERT((outmostMethodInstance->mIdHash != 0) || (outmostMethodInstance->mIsAutocompleteMethod));
  13385. hashCtx.Mixin(outmostMethodInstance->mIdHash);
  13386. }
  13387. }
  13388. methodInstance->mIdHash = (int64)hashCtx.Finish64();
  13389. }
  13390. bool BfModule::CheckUseMethodInstance(BfMethodInstance* methodInstance, BfAstNode* refNode)
  13391. {
  13392. if (methodInstance->mHasBeenDeclared)
  13393. return true;
  13394. Fail(StrFormat("Circular reference in method instance '%s'", MethodToString(methodInstance).c_str()), refNode);
  13395. return false;
  13396. }
  13397. BfIRValue BfModule::GetInterfaceSlotNum(BfTypeInstance* ifaceType)
  13398. {
  13399. BfIRValue globalValue;
  13400. BfIRValue* globalValuePtr = NULL;
  13401. if (mInterfaceSlotRefs.TryGetValue(ifaceType, &globalValuePtr))
  13402. {
  13403. globalValue = *globalValuePtr;
  13404. }
  13405. if (!globalValue)
  13406. {
  13407. // This is necessary to reify the interface type
  13408. PopulateType(ifaceType);
  13409. StringT<512> slotVarName;
  13410. BfMangler::MangleStaticFieldName(slotVarName, mCompiler->GetMangleKind(), ifaceType, "sBfSlotOfs");
  13411. BfType* intType = GetPrimitiveType(BfTypeCode_Int32);
  13412. BfIRValue value;
  13413. if ((mCompiler->mHotState != NULL) && (ifaceType->mSlotNum >= 0))
  13414. {
  13415. /*// If this interface already existed before this hot compile but we never indirectly called any of its methods
  13416. // then the sBfSlotOfs could have gotten its symbol stripped, so actually define it here.
  13417. int virtSlotIdx = ifaceType->mSlotNum + 1;
  13418. value = GetConstValue32(virtSlotIdx);*/
  13419. mCompiler->mHotState->mSlotDefineTypeIds.Add(ifaceType->mTypeId);
  13420. ifaceType->mDirty = true; // Makes sure we create interface in vdata
  13421. }
  13422. globalValue = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapType(intType), true, BfIRLinkageType_External, value, slotVarName);
  13423. mInterfaceSlotRefs[ifaceType] = globalValue;
  13424. // Make sure we reify
  13425. PopulateType(ifaceType, BfPopulateType_Declaration);
  13426. AddDependency(ifaceType, mCurTypeInstance, BfDependencyMap::DependencyFlag_StaticValue);
  13427. }
  13428. return mBfIRBuilder->CreateAlignedLoad(globalValue/*, "slotOfs"*/, 4);
  13429. }
  13430. void BfModule::HadSlotCountDependency()
  13431. {
  13432. if (mCompiler->mIsResolveOnly)
  13433. return;
  13434. BF_ASSERT(!mBfIRBuilder->mIgnoreWrites);
  13435. BF_ASSERT((mUsedSlotCount == BF_MAX(mCompiler->mMaxInterfaceSlots, 0)) || (mUsedSlotCount == -1));
  13436. mUsedSlotCount = BF_MAX(mCompiler->mMaxInterfaceSlots, 0);
  13437. }
  13438. BfTypedValue BfModule::GetCompilerFieldValue(const StringImpl& str)
  13439. {
  13440. if (str == "#IsComptime")
  13441. {
  13442. return BfTypedValue(mBfIRBuilder->CreateConst(BfTypeCode_Boolean, mIsComptimeModule ? 1 : 0), GetPrimitiveType(BfTypeCode_Boolean));
  13443. }
  13444. if (str == "#IsBuilding")
  13445. {
  13446. return BfTypedValue(mBfIRBuilder->CreateConst(BfTypeCode_Boolean, (!mCompiler->mIsResolveOnly) ? 1 : 0), GetPrimitiveType(BfTypeCode_Boolean));
  13447. }
  13448. if (str == "#IsReified")
  13449. {
  13450. return BfTypedValue(mBfIRBuilder->CreateConst(BfTypeCode_Boolean, mIsReified ? 1 : 0), GetPrimitiveType(BfTypeCode_Boolean));
  13451. }
  13452. if (str == "#CompileRev")
  13453. {
  13454. return BfTypedValue(mBfIRBuilder->CreateConst(BfTypeCode_Int32, mCompiler->mRevision), GetPrimitiveType(BfTypeCode_Int32));
  13455. }
  13456. if (str == "#NextId")
  13457. {
  13458. return BfTypedValue(mBfIRBuilder->CreateConst(BfTypeCode_Int64, (uint64)++mCompiler->mUniqueId), GetPrimitiveType(BfTypeCode_Int32));
  13459. }
  13460. if (str == "#ModuleName")
  13461. {
  13462. return BfTypedValue(GetStringObjectValue(mModuleName), ResolveTypeDef(mCompiler->mStringTypeDef));
  13463. }
  13464. if (str == "#ProjectName")
  13465. {
  13466. if (mProject != NULL)
  13467. return BfTypedValue(GetStringObjectValue(mProject->mName), ResolveTypeDef(mCompiler->mStringTypeDef));
  13468. }
  13469. if (str == "#AllocStackCount")
  13470. {
  13471. return BfTypedValue(mBfIRBuilder->CreateConst(BfTypeCode_Int32, mCompiler->mOptions.mAllocStackCount), GetPrimitiveType(BfTypeCode_Int32));
  13472. }
  13473. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL))
  13474. {
  13475. if (str == "#CallerLineNum")
  13476. {
  13477. return BfTypedValue(GetConstValue(mCurMethodState->mMixinState->mInjectFilePosition.mCurLine + 1), GetPrimitiveType(BfTypeCode_Int32));
  13478. }
  13479. else if (str == "#CallerFilePath")
  13480. {
  13481. String filePath = "";
  13482. if (mCurMethodState->mMixinState->mInjectFilePosition.mFileInstance != NULL)
  13483. filePath = mCurMethodState->mMixinState->mInjectFilePosition.mFileInstance->mParser->mFileName;
  13484. return BfTypedValue(GetStringObjectValue(filePath), ResolveTypeDef(mCompiler->mStringTypeDef));
  13485. }
  13486. else if (str == "#CallerFileName")
  13487. {
  13488. String filePath = "";
  13489. if (mCurMethodState->mMixinState->mInjectFilePosition.mFileInstance != NULL)
  13490. filePath = mCurMethodState->mMixinState->mInjectFilePosition.mFileInstance->mParser->mFileName;
  13491. return BfTypedValue(GetStringObjectValue(GetFileName(filePath)), ResolveTypeDef(mCompiler->mStringTypeDef));
  13492. }
  13493. else if (str == "#CallerFileDir")
  13494. {
  13495. String filePath = "";
  13496. if (mCurMethodState->mMixinState->mInjectFilePosition.mFileInstance != NULL)
  13497. filePath = mCurMethodState->mMixinState->mInjectFilePosition.mFileInstance->mParser->mFileName;
  13498. return BfTypedValue(GetStringObjectValue(GetFileDir(filePath)), ResolveTypeDef(mCompiler->mStringTypeDef));
  13499. }
  13500. else if (str == "#CallerTypeName")
  13501. {
  13502. String typeName = "";
  13503. if (mCurMethodState->mMixinState->mMixinMethodInstance)
  13504. typeName = TypeToString(mCurMethodState->mMixinState->mMixinMethodInstance->GetOwner());
  13505. return BfTypedValue(GetStringObjectValue(typeName), ResolveTypeDef(mCompiler->mStringTypeDef));
  13506. }
  13507. else if (str == "#CallerType")
  13508. {
  13509. auto typeType = ResolveTypeDef(mCompiler->mTypeTypeDef);
  13510. BfType* type = NULL;
  13511. if (mCurMethodState->mMixinState->mMixinMethodInstance)
  13512. type = mCurMethodState->mMixinState->mMixinMethodInstance->GetOwner();
  13513. if (type != NULL)
  13514. {
  13515. AddDependency(type, mCurTypeInstance, BfDependencyMap::DependencyFlag_ExprTypeReference);
  13516. return BfTypedValue(CreateTypeDataRef(type), typeType);
  13517. }
  13518. }
  13519. else if (str == "#CallerMemberName")
  13520. {
  13521. String memberName = "";
  13522. if (mCurMethodState->mMixinState->mMixinMethodInstance)
  13523. memberName = MethodToString(mCurMethodState->mMixinState->mMixinMethodInstance);
  13524. return BfTypedValue(GetStringObjectValue(memberName), ResolveTypeDef(mCompiler->mStringTypeDef));
  13525. }
  13526. else if (str == "#CallerProject")
  13527. {
  13528. BfProject* project = NULL;
  13529. project = mCurMethodState->mMixinState->mMixinMethodInstance->mMethodDef->mDeclaringType->mProject;
  13530. if (project != NULL)
  13531. return BfTypedValue(GetStringObjectValue(mProject->mName), ResolveTypeDef(mCompiler->mStringTypeDef));
  13532. }
  13533. }
  13534. if (str == "#TimeLocal")
  13535. {
  13536. time_t rawtime;
  13537. time(&rawtime);
  13538. tm* timeinfo = localtime(&rawtime);
  13539. char result[32];
  13540. sprintf(result, "%d/%.2d/%.2d %.2d:%.2d:%.2d",
  13541. 1900 + timeinfo->tm_year,
  13542. timeinfo->tm_mon + 1,
  13543. timeinfo->tm_mday,
  13544. timeinfo->tm_hour,
  13545. timeinfo->tm_min,
  13546. timeinfo->tm_sec);
  13547. return BfTypedValue(GetStringObjectValue(result), ResolveTypeDef(mCompiler->mStringTypeDef));
  13548. }
  13549. return BfTypedValue();
  13550. }
  13551. BfTypedValue BfModule::GetCompilerFieldValue(BfTypedValue typedValue)
  13552. {
  13553. if (!typedValue.IsAddr())
  13554. return BfTypedValue();
  13555. if (typedValue.mValue.IsConst())
  13556. {
  13557. auto constantValue = mBfIRBuilder->GetConstant(typedValue.mValue);
  13558. if (constantValue != NULL)
  13559. {
  13560. if (constantValue->mConstType == BfConstType_GlobalVar)
  13561. {
  13562. auto globalVar = (BfGlobalVar*)constantValue;
  13563. if (globalVar->mName[0] == '#')
  13564. {
  13565. BfTypedValue result = GetCompilerFieldValue(globalVar->mName);
  13566. return result;
  13567. }
  13568. }
  13569. }
  13570. }
  13571. return BfTypedValue();
  13572. }
  13573. BfTypedValue BfModule::ReferenceStaticField(BfFieldInstance* fieldInstance)
  13574. {
  13575. BfIRValue globalValue;
  13576. auto fieldDef = fieldInstance->GetFieldDef();
  13577. if ((fieldDef->mIsConst) && (!fieldDef->mIsExtern))
  13578. {
  13579. if (fieldInstance->mConstIdx != -1)
  13580. {
  13581. auto constant = fieldInstance->mOwner->mConstHolder->GetConstantById(fieldInstance->mConstIdx);
  13582. return BfTypedValue(ConstantToCurrent(constant, fieldInstance->mOwner->mConstHolder, fieldInstance->GetResolvedType()), fieldInstance->GetResolvedType());
  13583. }
  13584. else
  13585. {
  13586. return GetDefaultTypedValue(fieldInstance->GetResolvedType());
  13587. }
  13588. }
  13589. if ((mIsScratchModule) && (mCompiler->mIsResolveOnly) && (!fieldInstance->mOwner->IsInstanceOf(mCompiler->mCompilerTypeDef)))
  13590. {
  13591. // Just fake it for the extern and unspecialized modules
  13592. // We can't do this for compilation because unreified methods with default params need to get actual global variable refs
  13593. return BfTypedValue(mBfIRBuilder->CreateConstNull(), fieldInstance->GetResolvedType(), true);
  13594. }
  13595. BfIRValue* globalValuePtr = NULL;
  13596. if (mStaticFieldRefs.TryGetValue(fieldInstance, &globalValuePtr))
  13597. {
  13598. globalValue = *globalValuePtr;
  13599. BF_ASSERT(globalValue);
  13600. auto globalVar = (BfGlobalVar*)mBfIRBuilder->GetConstant(globalValue);
  13601. if ((globalVar->mStreamId == -1) && (!mBfIRBuilder->mIgnoreWrites))
  13602. {
  13603. mBfIRBuilder->MapType(fieldInstance->mResolvedType);
  13604. mBfIRBuilder->CreateGlobalVariable(globalValue);
  13605. }
  13606. }
  13607. else
  13608. {
  13609. StringT<512> staticVarName;
  13610. BfMangler::Mangle(staticVarName, mCompiler->GetMangleKind(), fieldInstance);
  13611. auto typeType = fieldInstance->GetResolvedType();
  13612. if ((fieldDef->mIsExtern) && (fieldDef->mIsConst) && (typeType->IsPointer()))
  13613. {
  13614. typeType = typeType->GetUnderlyingType();
  13615. }
  13616. if (mIsComptimeModule)
  13617. {
  13618. mCompiler->mCeMachine->QueueStaticField(fieldInstance, staticVarName);
  13619. }
  13620. PopulateType(typeType);
  13621. if ((typeType != NULL) && (!typeType->IsValuelessType()))
  13622. {
  13623. BfIRType irType = mBfIRBuilder->MapType(typeType);
  13624. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, mBfIRBuilder->mIgnoreWrites || staticVarName.StartsWith('#'));
  13625. globalValue = mBfIRBuilder->CreateGlobalVariable(
  13626. irType,
  13627. false,
  13628. BfIRLinkageType_External,
  13629. BfIRValue(),
  13630. staticVarName,
  13631. IsThreadLocal(fieldInstance));
  13632. BF_ASSERT(globalValue);
  13633. mStaticFieldRefs[fieldInstance] = globalValue;
  13634. BfLogSysM("Mod:%p Type:%p ReferenceStaticField %p -> %p\n", this, fieldInstance->mOwner, fieldInstance, globalValue);
  13635. }
  13636. }
  13637. auto type = fieldInstance->GetResolvedType();
  13638. if (type->IsValuelessType())
  13639. return BfTypedValue(globalValue, type);
  13640. if (fieldDef->mIsVolatile)
  13641. return BfTypedValue(globalValue, type, BfTypedValueKind_VolatileAddr);
  13642. return BfTypedValue(globalValue, type, !fieldDef->mIsConst);
  13643. }
  13644. BfFieldInstance* BfModule::GetFieldInstance(BfTypeInstance* typeInst, int fieldIdx, const char* fieldName)
  13645. {
  13646. if (typeInst->IsDataIncomplete())
  13647. PopulateType(typeInst);
  13648. if (fieldIdx >= typeInst->mFieldInstances.mSize)
  13649. {
  13650. Fail(StrFormat("Invalid field data in type '%s'", TypeToString(typeInst).c_str()));
  13651. return 0;
  13652. }
  13653. return &typeInst->mFieldInstances[fieldIdx];
  13654. }
  13655. void BfModule::MarkUsingThis()
  13656. {
  13657. auto useMethodState = mCurMethodState;
  13658. while ((useMethodState != NULL) && (useMethodState->mClosureState != NULL) && (useMethodState->mClosureState->mCapturing))
  13659. {
  13660. useMethodState = useMethodState->mPrevMethodState;
  13661. }
  13662. if ((useMethodState != NULL) && (!useMethodState->mLocals.IsEmpty()))
  13663. {
  13664. auto localVar = useMethodState->mLocals[0];
  13665. if (localVar->mIsThis)
  13666. localVar->mReadFromId = useMethodState->GetRootMethodState()->mCurAccessId++;
  13667. }
  13668. }
  13669. BfTypedValue BfModule::GetThis(bool markUsing)
  13670. {
  13671. if ((mIsComptimeModule) && (mCompiler->mCeMachine->mDebugger != NULL) && (mCompiler->mCeMachine->mDebugger->mCurDbgState != NULL))
  13672. {
  13673. if (mCompiler->mCeMachine->mDebugger->mCurDbgState->mExplicitThis)
  13674. return mCompiler->mCeMachine->mDebugger->mCurDbgState->mExplicitThis;
  13675. auto ceDebugger = mCompiler->mCeMachine->mDebugger;
  13676. auto activeFrame = ceDebugger->mCurDbgState->mActiveFrame;
  13677. if ((activeFrame != NULL) && (activeFrame->mFunction->mDbgInfo != NULL))
  13678. {
  13679. for (auto& dbgVar : activeFrame->mFunction->mDbgInfo->mVariables)
  13680. {
  13681. if (dbgVar.mName == "this")
  13682. return BfTypedValue(mBfIRBuilder->CreateConstAggCE(mBfIRBuilder->MapType(dbgVar.mType), activeFrame->mFrameAddr + dbgVar.mValue.mFrameOfs), dbgVar.mType,
  13683. dbgVar.mIsConst ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Addr);
  13684. }
  13685. }
  13686. return BfTypedValue();
  13687. }
  13688. auto useMethodState = mCurMethodState;
  13689. while ((useMethodState != NULL) && (useMethodState->mClosureState != NULL) && (useMethodState->mClosureState->mCapturing))
  13690. {
  13691. useMethodState = useMethodState->mPrevMethodState;
  13692. }
  13693. if (useMethodState != NULL)
  13694. {
  13695. // Fake a 'this' for var field resolution
  13696. if (useMethodState->mTempKind == BfMethodState::TempKind_NonStatic)
  13697. {
  13698. auto thisType = mCurTypeInstance;
  13699. if (thisType->IsValueType())
  13700. return BfTypedValue(mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapTypeInstPtr(thisType)), thisType, BfTypedValueKind_ThisAddr);
  13701. else
  13702. return BfTypedValue(mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapTypeInst(thisType)), thisType, BfTypedValueKind_ThisValue);
  13703. }
  13704. else if (useMethodState->mTempKind == BfMethodState::TempKind_Static)
  13705. {
  13706. return BfTypedValue();
  13707. }
  13708. }
  13709. else
  13710. {
  13711. //TODO: Do we allow useMethodState to be NULL anymore?
  13712. return BfTypedValue();
  13713. }
  13714. // Check mixin state for 'this'
  13715. {
  13716. auto checkMethodState = mCurMethodState;
  13717. while (checkMethodState != NULL)
  13718. {
  13719. if (checkMethodState->mMixinState != NULL)
  13720. {
  13721. BfTypedValue thisValue = checkMethodState->mMixinState->mTarget;
  13722. if (thisValue.HasType())
  13723. {
  13724. checkMethodState->mMixinState->mLastTargetAccessId = useMethodState->GetRootMethodState()->mCurAccessId++;
  13725. if (!thisValue.mType->IsValueType())
  13726. thisValue = LoadValue(thisValue);
  13727. return thisValue;
  13728. }
  13729. }
  13730. checkMethodState = checkMethodState->mPrevMethodState;
  13731. }
  13732. }
  13733. auto curMethodInstance = mCurMethodInstance;
  13734. if (useMethodState->mMethodInstance != NULL)
  13735. curMethodInstance = useMethodState->mMethodInstance;
  13736. if ((curMethodInstance == NULL) /*|| (!mCurMethodInstance->mIRFunction)*/ || (curMethodInstance->mMethodDef->mIsStatic))
  13737. {
  13738. if ((useMethodState->mClosureState != NULL) && (!useMethodState->mClosureState->mConstLocals.empty()))
  13739. {
  13740. auto& constLocal = useMethodState->mClosureState->mConstLocals[0];
  13741. if (constLocal.mIsThis)
  13742. {
  13743. BF_ASSERT(constLocal.mResolvedType->IsValuelessType());
  13744. return BfTypedValue(mBfIRBuilder->GetFakeVal(), constLocal.mResolvedType);
  13745. }
  13746. }
  13747. return BfTypedValue();
  13748. }
  13749. if (useMethodState->mLocals.IsEmpty())
  13750. {
  13751. // 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
  13752. BF_ASSERT(useMethodState->mPrevMethodState != NULL);
  13753. return BfTypedValue();
  13754. }
  13755. auto thisLocal = useMethodState->mLocals[0];
  13756. BF_ASSERT(thisLocal->mIsThis);
  13757. bool preferValue = !IsTargetingBeefBackend();
  13758. if (!thisLocal->mAddr)
  13759. preferValue = true;
  13760. bool usedVal = false;
  13761. BfIRValue thisValue;
  13762. if ((preferValue) && (!thisLocal->mIsLowered))
  13763. {
  13764. thisValue = thisLocal->mValue;
  13765. usedVal = true;
  13766. }
  13767. else if ((thisLocal->mIsSplat) || (thisLocal->mIsLowered))
  13768. thisValue = thisLocal->mAddr;
  13769. else
  13770. thisValue = mBfIRBuilder->CreateAlignedLoad(thisLocal->mAddr, thisLocal->mResolvedType->mAlign);
  13771. if (markUsing)
  13772. useMethodState->mLocals[0]->mReadFromId = useMethodState->GetRootMethodState()->mCurAccessId++;
  13773. if (useMethodState->mClosureState != NULL)
  13774. {
  13775. auto closureTypeInst = useMethodState->mClosureState->mClosureType;
  13776. if (closureTypeInst != NULL)
  13777. {
  13778. if (closureTypeInst->mFieldInstances.size() > 0)
  13779. {
  13780. auto& field = closureTypeInst->mFieldInstances[0];
  13781. auto fieldDef = field.GetFieldDef();
  13782. if (fieldDef->mName == "__this")
  13783. {
  13784. if (mCurMethodState->mClosureState->mCapturing)
  13785. mCurMethodState->mClosureState->mReferencedOuterClosureMembers.Add(&field);
  13786. // This is a captured 'this'
  13787. BfTypedValue result = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(thisValue, 0, field.mDataIdx), field.mResolvedType, true);
  13788. if (field.mResolvedType->IsRef())
  13789. {
  13790. auto refType = (BfRefType*)field.mResolvedType;
  13791. auto underlyingType = refType->GetUnderlyingType();
  13792. result = BfTypedValue(mBfIRBuilder->CreateLoad(result.mValue), underlyingType, true);
  13793. }
  13794. if (field.mResolvedType->IsObject())
  13795. {
  13796. result = LoadValue(result);
  13797. result.mKind = BfTypedValueKind_ThisValue;
  13798. }
  13799. else
  13800. {
  13801. if (fieldDef->mIsReadOnly)
  13802. result.mKind = BfTypedValueKind_ReadOnlyThisAddr;
  13803. else
  13804. result.mKind = BfTypedValueKind_ThisAddr;
  13805. }
  13806. return result;
  13807. }
  13808. }
  13809. return BfTypedValue();
  13810. }
  13811. if (useMethodState->mClosureState->mCapturing)
  13812. {
  13813. auto thisType = useMethodState->mLocals[0]->mResolvedType;
  13814. if (thisType->IsValueType())
  13815. return BfTypedValue(CreateAlloca(thisType), thisType, BfTypedValueKind_ThisAddr);
  13816. else
  13817. return BfTypedValue(GetDefaultValue(thisType), thisType, BfTypedValueKind_ThisValue);
  13818. }
  13819. }
  13820. if (mCurMethodInstance == NULL)
  13821. return BfTypedValue();
  13822. auto localDef = useMethodState->mLocals[0];
  13823. auto curMethodOwner = mCurMethodInstance->mMethodInstanceGroup->mOwner;
  13824. if ((curMethodOwner->IsStruct()) || (curMethodOwner->IsTypedPrimitive()))
  13825. {
  13826. if ((localDef->mResolvedType->IsTypedPrimitive()) && (!mCurMethodInstance->mMethodDef->mIsMutating) && (mCurMethodInstance->mCallingConvention != BfCallingConvention_Cdecl))
  13827. {
  13828. return BfTypedValue(thisValue, useMethodState->mLocals[0]->mResolvedType, BfTypedValueKind_ReadOnlyThisValue);
  13829. }
  13830. if (localDef->mIsSplat)
  13831. {
  13832. return BfTypedValue(thisValue, useMethodState->mLocals[0]->mResolvedType, BfTypedValueKind_ThisSplatHead);
  13833. }
  13834. return BfTypedValue(thisValue, useMethodState->mLocals[0]->mResolvedType, localDef->mIsReadOnly ? BfTypedValueKind_ReadOnlyThisAddr : BfTypedValueKind_ThisAddr);
  13835. }
  13836. return BfTypedValue(thisValue, mCurMethodInstance->mMethodInstanceGroup->mOwner, BfTypedValueKind_ThisValue);
  13837. }
  13838. BfLocalVariable* BfModule::GetThisVariable()
  13839. {
  13840. if (mCurMethodState == NULL)
  13841. return NULL;
  13842. auto methodState = mCurMethodState->GetNonCaptureState();
  13843. if ((methodState->mLocals.size() > 0) && (methodState->mLocals[0]->mIsThis))
  13844. return methodState->mLocals[0];
  13845. return NULL;
  13846. }
  13847. bool BfModule::IsInGeneric()
  13848. {
  13849. return ((mCurMethodInstance != NULL) && (mCurMethodInstance->GetNumGenericArguments() != 0)) || (mCurTypeInstance->IsGenericTypeInstance());
  13850. }
  13851. bool BfModule::InDefinitionSection()
  13852. {
  13853. if (mCurTypeInstance != NULL)
  13854. {
  13855. if (mCurTypeInstance->IsUnspecializedTypeVariation())
  13856. return false;
  13857. }
  13858. return !IsInSpecializedSection();
  13859. }
  13860. bool BfModule::IsInSpecializedGeneric()
  13861. {
  13862. if ((mCurTypeInstance != NULL) && (mCurTypeInstance->IsSpecializedType()))
  13863. return true;
  13864. if ((mCurMethodInstance == NULL) || (mCurMethodInstance->mIsUnspecialized))
  13865. return false;
  13866. return (mCurMethodInstance->GetNumGenericArguments() != 0);
  13867. }
  13868. bool BfModule::IsInSpecializedSection()
  13869. {
  13870. return IsInSpecializedGeneric() ||
  13871. ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL));
  13872. }
  13873. bool BfModule::IsInUnspecializedGeneric()
  13874. {
  13875. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mIsUnspecialized))
  13876. return true;
  13877. if ((mCurTypeInstance != NULL) && (mCurTypeInstance->IsUnspecializedType()))
  13878. return true;
  13879. return false;
  13880. }
  13881. //////////////////////////////////////////////////////////////////////////
  13882. BfIRValue BfModule::AllocLocalVariable(BfType* type, const StringImpl& name, bool doLifetimeEnd)
  13883. {
  13884. //if ((type->IsValuelessType()) || (type->IsMethodRef()))
  13885. if (type->IsValuelessType())
  13886. return mBfIRBuilder->GetFakeVal();
  13887. auto allocaInst = CreateAlloca(type, doLifetimeEnd, name.c_str());
  13888. if ((!doLifetimeEnd) && (WantsLifetimes()))
  13889. {
  13890. auto lifetimeStart = mBfIRBuilder->CreateLifetimeStart(allocaInst);
  13891. mBfIRBuilder->ClearDebugLocation(lifetimeStart);
  13892. }
  13893. bool initLocalVariables = mCompiler->mOptions.mInitLocalVariables;
  13894. auto typeOptions = GetTypeOptions();
  13895. if (typeOptions != NULL)
  13896. initLocalVariables = typeOptions->Apply(initLocalVariables, BfOptionFlags_InitLocalVariables);
  13897. // Local variable inits are implicitly handled in the Beef Backend
  13898. if ((initLocalVariables) && (!IsTargetingBeefBackend()))
  13899. {
  13900. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  13901. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRInitBlock);
  13902. auto storeInst = mBfIRBuilder->CreateAlignedStore(GetDefaultValue(type), allocaInst, type->mAlign);
  13903. mBfIRBuilder->ClearDebugLocation(storeInst);
  13904. mBfIRBuilder->SetInsertPoint(prevBlock);
  13905. }
  13906. return allocaInst;
  13907. }
  13908. void BfModule::DoAddLocalVariable(BfLocalVariable* localVar)
  13909. {
  13910. BF_ASSERT(localVar->mResolvedType != NULL);
  13911. while (localVar->mName.StartsWith('@'))
  13912. {
  13913. localVar->mNamePrefixCount++;
  13914. localVar->mName.Remove(0);
  13915. }
  13916. if (mCurMethodState->mLocals.mAllocSize == 0)
  13917. {
  13918. mCurMethodState->mLocals.Reserve(16);
  13919. mCurMethodState->mLocalVarSet.Reserve(16);
  13920. }
  13921. localVar->mLocalVarIdx = (int)mCurMethodState->mLocals.size();
  13922. mCurMethodState->mLocals.push_back(localVar);
  13923. BfLocalVarEntry* localVarEntryPtr;
  13924. if (!mCurMethodState->mLocalVarSet.TryAdd(BfLocalVarEntry(localVar), &localVarEntryPtr))
  13925. {
  13926. localVar->mShadowedLocal = localVarEntryPtr->mLocalVar;
  13927. localVarEntryPtr->mLocalVar = localVar;
  13928. }
  13929. }
  13930. void BfModule::DoLocalVariableDebugInfo(BfLocalVariable* localVarDef, bool doAliasValue, BfIRValue declareBefore, BfIRInitType initType)
  13931. {
  13932. if (localVarDef->mResolvedType->IsVar())
  13933. return;
  13934. if ((mBfIRBuilder->DbgHasInfo()) &&
  13935. ((mCurMethodInstance == NULL) || (!mCurMethodInstance->mIsUnspecialized)) &&
  13936. (mHasFullDebugInfo) &&
  13937. ((mCurMethodState->mClosureState == NULL) || (!mCurMethodState->mClosureState->mCapturing)))
  13938. {
  13939. auto varType = localVarDef->mResolvedType;
  13940. if (localVarDef->mResolvedType->IsValuelessType())
  13941. {
  13942. }
  13943. else
  13944. {
  13945. bool isByAddr = false;
  13946. auto diValue = localVarDef->mValue;
  13947. if (localVarDef->mConstValue)
  13948. diValue = localVarDef->mConstValue;
  13949. else if (localVarDef->mAddr)
  13950. {
  13951. diValue = localVarDef->mAddr;
  13952. isByAddr = true;
  13953. }
  13954. if (diValue.IsConst())
  13955. {
  13956. auto constant = mBfIRBuilder->GetConstant(diValue);
  13957. if ((constant->mConstType == BfConstType_TypeOf) || (constant->mConstType == BfConstType_TypeOf_WithData))
  13958. {
  13959. // Ignore for now
  13960. return;
  13961. }
  13962. }
  13963. auto diType = mBfIRBuilder->DbgGetType(localVarDef->mResolvedType);
  13964. bool didConstToMem = false;
  13965. bool isConstant = false;
  13966. if ((localVarDef->mIsReadOnly) && (localVarDef->mAddr))
  13967. diType = mBfIRBuilder->DbgCreateConstType(diType);
  13968. else if (localVarDef->mConstValue)
  13969. {
  13970. auto constant = mBfIRBuilder->GetConstant(localVarDef->mConstValue);
  13971. isConstant =
  13972. (constant->mConstType < BfConstType_GlobalVar) ||
  13973. (constant->mConstType == BfConstType_AggZero) ||
  13974. (constant->mConstType == BfConstType_Agg);
  13975. if (isConstant)
  13976. {
  13977. if (localVarDef->mResolvedType->IsComposite())
  13978. {
  13979. mBfIRBuilder->PopulateType(localVarDef->mResolvedType);
  13980. auto constMem = mBfIRBuilder->ConstToMemory(localVarDef->mConstValue);
  13981. // if (IsTargetingBeefBackend())
  13982. // {
  13983. // diValue = mBfIRBuilder->CreateAliasValue(constMem);
  13984. // didConstToMem = true;
  13985. //
  13986. // diType = mBfIRBuilder->DbgCreateReferenceType(diType);
  13987. // }
  13988. //else
  13989. {
  13990. isByAddr = true;
  13991. mBfIRBuilder->SaveDebugLocation();
  13992. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  13993. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRInitBlock);
  13994. mBfIRBuilder->ClearDebugLocation();
  13995. auto ptrType = CreatePointerType(localVarDef->mResolvedType);
  13996. auto addrVal = CreateAlloca(ptrType);
  13997. mBfIRBuilder->CreateStore(constMem, addrVal);
  13998. diType = mBfIRBuilder->DbgCreateReferenceType(diType);
  13999. diValue = addrVal;
  14000. didConstToMem = true;
  14001. mBfIRBuilder->SetInsertPoint(prevBlock);
  14002. mBfIRBuilder->RestoreDebugLocation();
  14003. }
  14004. }
  14005. if (mCompiler->mOptions.IsCodeView())
  14006. diType = mBfIRBuilder->DbgCreateConstType(diType);
  14007. }
  14008. }
  14009. if (!mBfIRBuilder->mIgnoreWrites)
  14010. {
  14011. if ((localVarDef->mIsStatic) && (localVarDef->mAddr) && (!localVarDef->mResolvedType->IsValuelessType()))
  14012. {
  14013. auto refType = CreateRefType(localVarDef->mResolvedType);
  14014. diType = mBfIRBuilder->DbgGetType(refType);
  14015. auto refAlloca = CreateAlloca(refType);
  14016. mBfIRBuilder->CreateStore(localVarDef->mAddr, refAlloca);
  14017. diValue = refAlloca;
  14018. }
  14019. auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(mCurMethodState->mCurScope->mDIScope,
  14020. localVarDef->mName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType, initType);
  14021. localVarDef->mDbgVarInst = diVariable;
  14022. if (mBfIRBuilder->HasDebugLocation())
  14023. {
  14024. if ((isConstant) && (!didConstToMem))
  14025. {
  14026. BfTypedValue result(localVarDef->mConstValue, localVarDef->mResolvedType);
  14027. FixValueActualization(result);
  14028. localVarDef->mDbgDeclareInst = mBfIRBuilder->DbgInsertValueIntrinsic(result.mValue, diVariable);
  14029. }
  14030. else
  14031. {
  14032. if ((IsTargetingBeefBackend()) && (doAliasValue) && (!mIsComptimeModule))
  14033. {
  14034. diValue = mBfIRBuilder->CreateAliasValue(diValue);
  14035. mCurMethodState->mCurScope->mDeferredLifetimeEnds.Add(diValue);
  14036. }
  14037. if (isByAddr)
  14038. localVarDef->mDbgDeclareInst = mBfIRBuilder->DbgInsertDeclare(diValue, diVariable, declareBefore);
  14039. else if (diValue)
  14040. {
  14041. localVarDef->mDbgDeclareInst = mBfIRBuilder->DbgInsertValueIntrinsic(diValue, diVariable);
  14042. }
  14043. else if (mCompiler->mOptions.mToolsetType != BfToolsetType_GNU) // DWARF chokes on this:
  14044. localVarDef->mDbgDeclareInst = mBfIRBuilder->DbgInsertValueIntrinsic(BfIRValue(), diVariable);
  14045. }
  14046. }
  14047. }
  14048. }
  14049. }
  14050. }
  14051. BfLocalVariable* BfModule::AddLocalVariableDef(BfLocalVariable* localVarDef, bool addDebugInfo, bool doAliasValue, BfIRValue declareBefore, BfIRInitType initType)
  14052. {
  14053. if ((localVarDef->mValue) && (!localVarDef->mAddr) && (IsTargetingBeefBackend()) && (!localVarDef->mResolvedType->IsValuelessType()))
  14054. {
  14055. if ((!localVarDef->mValue.IsConst()) &&
  14056. (!localVarDef->mValue.IsArg()) && (!localVarDef->mValue.IsFake()))
  14057. {
  14058. mBfIRBuilder->CreateValueScopeRetain(localVarDef->mValue);
  14059. mCurMethodState->mCurScope->mHadScopeValueRetain = true;
  14060. }
  14061. }
  14062. if (addDebugInfo)
  14063. DoLocalVariableDebugInfo(localVarDef, doAliasValue, declareBefore, initType);
  14064. localVarDef->mDeclBlock = mBfIRBuilder->GetInsertBlock();
  14065. DoAddLocalVariable(localVarDef);
  14066. auto rootMethodState = mCurMethodState->GetRootMethodState();
  14067. if (localVarDef->mLocalVarId == -1)
  14068. {
  14069. BF_ASSERT(rootMethodState->mCurLocalVarId >= 0);
  14070. localVarDef->mLocalVarId = rootMethodState->mCurLocalVarId++;
  14071. }
  14072. bool checkLocal = true;
  14073. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_Ctor))
  14074. {
  14075. if (auto autoCtorDecl = BfNodeDynCast<BfAutoConstructorDeclaration>(mCurMethodInstance->mMethodDef->mMethodDeclaration))
  14076. checkLocal = false;
  14077. }
  14078. if ((localVarDef->mNameNode != NULL) && (mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL) && (!mIsComptimeModule) && (checkLocal))
  14079. mCompiler->mResolvePassData->mAutoComplete->CheckLocalDef(localVarDef->mNameNode, localVarDef);
  14080. if (((localVarDef->mNameNode != NULL) && (mCurMethodInstance != NULL)) && (checkLocal))
  14081. {
  14082. bool isClosureProcessing = (mCurMethodState->mClosureState != NULL) && (!mCurMethodState->mClosureState->mCapturing);
  14083. if ((!isClosureProcessing) && (mCompiler->mResolvePassData != NULL) && (localVarDef->mNameNode != NULL) && (rootMethodState->mMethodInstance != NULL) && (!mIsComptimeModule))
  14084. mCompiler->mResolvePassData->HandleLocalReference(localVarDef->mNameNode, rootMethodState->mMethodInstance->GetOwner()->mTypeDef, rootMethodState->mMethodInstance->mMethodDef, localVarDef->mLocalVarId);
  14085. }
  14086. return localVarDef;
  14087. }
  14088. void BfModule::CreateDIRetVal()
  14089. {
  14090. if (!WantsDebugInfo())
  14091. return;
  14092. /*if (!mCurMethodState->mRetVal)
  14093. {
  14094. if (mCurMethodInstance->mMethodDef->mName != "Ziggle")
  14095. return;
  14096. }*/
  14097. if ((mCurMethodState->mRetVal) || (mCurMethodState->mRetValAddr))
  14098. {
  14099. BfType* dbgType = mCurMethodInstance->mReturnType;
  14100. BfIRValue dbgValue = mCurMethodState->mRetVal.mValue;
  14101. if ((!mIsComptimeModule) && (mCurMethodInstance->GetStructRetIdx() != -1))
  14102. {
  14103. BF_ASSERT(mCurMethodState->mRetValAddr);
  14104. dbgType = CreatePointerType(dbgType);
  14105. dbgValue = mCurMethodState->mRetValAddr;
  14106. }
  14107. else
  14108. {
  14109. BF_ASSERT(!mCurMethodState->mRetValAddr);
  14110. }
  14111. mCurMethodState->mDIRetVal = mBfIRBuilder->DbgCreateAutoVariable(mCurMethodState->mCurScope->mDIScope,
  14112. "@return", mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, mBfIRBuilder->DbgGetType(dbgType));
  14113. auto declareCall = mBfIRBuilder->DbgInsertDeclare(dbgValue, mCurMethodState->mDIRetVal);
  14114. }
  14115. }
  14116. BfTypedValue BfModule::CreateTuple(const Array<BfTypedValue>& values, const Array<String>& fieldNames)
  14117. {
  14118. BfTypeVector fieldTypes;
  14119. for (auto arg : values)
  14120. fieldTypes.Add(arg.mType);
  14121. auto tupleType = CreateTupleType(fieldTypes, fieldNames);
  14122. auto tupleTypedValue = BfTypedValue(CreateAlloca(tupleType), tupleType, true);
  14123. for (int fieldIdx = 0; fieldIdx < tupleType->mFieldInstances.size(); fieldIdx++)
  14124. {
  14125. auto& fieldInstance = tupleType->mFieldInstances[fieldIdx];
  14126. if (fieldInstance.mDataIdx <= 0)
  14127. continue;
  14128. auto typedVal = values[fieldIdx];
  14129. typedVal = LoadOrAggregateValue(typedVal);
  14130. mBfIRBuilder->CreateAlignedStore(typedVal.mValue, mBfIRBuilder->CreateInBoundsGEP(tupleTypedValue.mValue, 0, fieldInstance.mDataIdx), typedVal.mType->mAlign);
  14131. }
  14132. return tupleTypedValue;
  14133. }
  14134. void BfModule::CheckVariableDef(BfLocalVariable* variableDef)
  14135. {
  14136. if (variableDef->mName.IsEmpty())
  14137. return;
  14138. BfLocalVarEntry* localVarEntryPtr = NULL;
  14139. if ((mCurMethodState != NULL) && (mCurMethodState->mLocalVarSet.TryGet(BfLocalVarEntry(variableDef), &localVarEntryPtr)))
  14140. {
  14141. auto checkLocal = localVarEntryPtr->mLocalVar;
  14142. if ((checkLocal->mLocalVarIdx >= mCurMethodState->GetLocalStartIdx()) && (!checkLocal->mIsShadow))
  14143. {
  14144. auto _Fail = [&](int warningNum, String str, BfAstNode* refNode)
  14145. {
  14146. BfError* error = Warn(warningNum, str, refNode);
  14147. if ((checkLocal->mNameNode != NULL) && (error != NULL))
  14148. mCompiler->mPassInstance->MoreInfo("Previous declaration", checkLocal->mNameNode);
  14149. };
  14150. auto checkScope = mCurMethodState->mCurScope;
  14151. if (checkScope->mScopeKind == BfScopeKind_StatementTarget)
  14152. checkScope = checkScope->mPrevScope;
  14153. if (checkLocal->mIsImplicitParam)
  14154. return; // Ignore 'redefinition'
  14155. if (checkLocal->IsParam())
  14156. {
  14157. if (variableDef->IsParam())
  14158. _Fail(4200, StrFormat("A parameter named '%s' has already been declared", variableDef->mName.c_str()), variableDef->mNameNode);
  14159. else
  14160. _Fail(4200, StrFormat("The name '%s' is already used by a parameter. Consider declaring 'var %s;' if you wish to make a mutable copy of that parameter.", variableDef->mName.c_str(), variableDef->mName.c_str()), variableDef->mNameNode);
  14161. }
  14162. else if (checkLocal->mLocalVarIdx < checkScope->mLocalVarStart)
  14163. _Fail(4200, StrFormat("A variable named '%s' has already been declared in an outer scope", variableDef->mName.c_str()), variableDef->mNameNode);
  14164. else
  14165. _Fail(4200, StrFormat("A variable named '%s' has already been declared in this scope", variableDef->mName.c_str()), variableDef->mNameNode);
  14166. return;
  14167. }
  14168. }
  14169. }
  14170. BfScopeData* BfModule::FindScope(BfAstNode* scopeName, BfMixinState* fromMixinState, bool allowAcrossDeferredBlock)
  14171. {
  14172. bool inMixinDecl = (mCurMethodInstance != NULL) && (mCurMethodInstance->IsMixin());
  14173. if (auto tokenNode = BfNodeDynCast<BfTokenNode>(scopeName))
  14174. {
  14175. if (tokenNode->GetToken() == BfToken_Colon)
  14176. {
  14177. if ((!allowAcrossDeferredBlock) && (mCurMethodState->mInDeferredBlock))
  14178. {
  14179. Fail("Cannot access method scope across deferred block boundary", scopeName);
  14180. return NULL;
  14181. }
  14182. return &mCurMethodState->mHeadScope;
  14183. }
  14184. else if (tokenNode->GetToken() == BfToken_Mixin)
  14185. {
  14186. if (fromMixinState == NULL)
  14187. {
  14188. if (mCurMethodInstance->mMethodDef->mMethodType != BfMethodType_Mixin)
  14189. Fail("'mixin' scope specifier can only be used within a mixin declaration", scopeName);
  14190. return mCurMethodState->mCurScope;
  14191. }
  14192. fromMixinState->mUsedInvocationScope = true;
  14193. return fromMixinState->mTargetScope;
  14194. }
  14195. else if (tokenNode->GetToken() == BfToken_New)
  14196. return NULL;
  14197. }
  14198. if (auto identifier = BfNodeDynCast<BfIdentifierNode>(scopeName))
  14199. {
  14200. auto findLabel = scopeName->ToString();
  14201. bool crossedDeferredBlock = false;
  14202. auto checkScope = mCurMethodState->mCurScope;
  14203. while (checkScope != NULL)
  14204. {
  14205. if (checkScope->mIsDeferredBlock)
  14206. crossedDeferredBlock = true;
  14207. if (checkScope->mLabel == findLabel)
  14208. {
  14209. if ((crossedDeferredBlock) && (!allowAcrossDeferredBlock))
  14210. {
  14211. Fail(StrFormat("Cannot access scope '%s' across deferred block boundary", findLabel.c_str()), scopeName);
  14212. return NULL;
  14213. }
  14214. return checkScope;
  14215. }
  14216. checkScope = checkScope->mPrevScope;
  14217. }
  14218. if (!inMixinDecl)
  14219. Fail(StrFormat("Unable to locate label '%s'", findLabel.c_str()), scopeName);
  14220. return NULL;
  14221. }
  14222. if (auto scopeNode = BfNodeDynCast<BfScopeNode>(scopeName))
  14223. {
  14224. return FindScope(scopeNode->mTargetNode, allowAcrossDeferredBlock);
  14225. }
  14226. return mCurMethodState->mCurScope;
  14227. }
  14228. BfScopeData* BfModule::FindScope(BfAstNode* scopeName, bool allowAcrossDeferredBlock)
  14229. {
  14230. return FindScope(scopeName, mCurMethodState->mMixinState, allowAcrossDeferredBlock);
  14231. }
  14232. BfBreakData* BfModule::FindBreakData(BfAstNode* scopeName)
  14233. {
  14234. auto scopeData = FindScope(scopeName, false);
  14235. if (scopeData == NULL)
  14236. return NULL;
  14237. int scopeDepth = scopeData->GetDepth();
  14238. // Find the first break data that is at or below the depth of our requested scope
  14239. auto breakData = mCurMethodState->mBreakData;
  14240. while ((breakData != NULL) && (scopeDepth < breakData->mScope->GetDepth()))
  14241. {
  14242. if (breakData->mScope->mIsConditional)
  14243. return NULL;
  14244. breakData = breakData->mPrevBreakData;
  14245. }
  14246. return breakData;
  14247. }
  14248. void BfModule::EmitLifetimeEnds(BfScopeData* scopeData)
  14249. {
  14250. // LLVM is stricter about the placement of these (ie: they can't occur after a 'ret')
  14251. if (!IsTargetingBeefBackend())
  14252. return;
  14253. for (auto lifetimeEnd : scopeData->mDeferredLifetimeEnds)
  14254. {
  14255. mBfIRBuilder->CreateLifetimeEnd(lifetimeEnd);
  14256. }
  14257. }
  14258. void BfModule::ClearLifetimeEnds()
  14259. {
  14260. auto scopeData = mCurMethodState->mCurScope;
  14261. while (scopeData != NULL)
  14262. {
  14263. scopeData->mDeferredLifetimeEnds.Clear();
  14264. scopeData = scopeData->mPrevScope;
  14265. }
  14266. }
  14267. bool BfModule::WantsDebugInfo()
  14268. {
  14269. if ((mCurMethodInstance != NULL) &&
  14270. ((mCurMethodInstance->mIsUnspecialized) || (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_Mixin)))
  14271. return false;
  14272. return (mBfIRBuilder->DbgHasInfo()) && (mHasFullDebugInfo) &&
  14273. ((mCurMethodState == NULL) || (mCurMethodState->mClosureState == NULL) || (!mCurMethodState->mClosureState->mCapturing));
  14274. }
  14275. BfTypeOptions* BfModule::GetTypeOptions()
  14276. {
  14277. if ((mCurMethodState != NULL) && (mCurMethodState->mMethodTypeOptions != NULL))
  14278. return mCurMethodState->mMethodTypeOptions;
  14279. if (mCurMethodInstance == NULL)
  14280. return NULL;
  14281. return mSystem->GetTypeOptions(mCurTypeInstance->mTypeOptionsIdx);
  14282. }
  14283. BfReflectKind BfModule::GetUserReflectKind(BfTypeInstance* attrType)
  14284. {
  14285. BfReflectKind reflectKind = BfReflectKind_None;
  14286. if (attrType->mCustomAttributes != NULL)
  14287. {
  14288. for (auto& customAttr : attrType->mCustomAttributes->mAttributes)
  14289. {
  14290. if (customAttr.mType->mTypeDef->mName->ToString() == "AttributeUsageAttribute")
  14291. {
  14292. for (auto& prop : customAttr.mSetProperties)
  14293. {
  14294. auto propDef = prop.mPropertyRef.mTypeInstance->mTypeDef->mProperties[prop.mPropertyRef.mPropIdx];
  14295. if (propDef->mName == "ReflectUser")
  14296. {
  14297. if (prop.mParam.mValue.IsConst())
  14298. {
  14299. auto constant = attrType->mConstHolder->GetConstant(prop.mParam.mValue);
  14300. reflectKind = (BfReflectKind)(reflectKind | (BfReflectKind)constant->mInt32);
  14301. }
  14302. }
  14303. }
  14304. // Check for Flags arg
  14305. if (customAttr.mCtorArgs.size() < 2)
  14306. continue;
  14307. auto constant = attrType->mConstHolder->GetConstant(customAttr.mCtorArgs[1]);
  14308. if (constant == NULL)
  14309. continue;
  14310. if (constant->mTypeCode == BfTypeCode_Boolean)
  14311. continue;
  14312. if ((constant->mInt8 & BfCustomAttributeFlags_ReflectAttribute) != 0)
  14313. reflectKind = (BfReflectKind)(reflectKind | BfReflectKind_User);
  14314. }
  14315. }
  14316. }
  14317. return reflectKind;
  14318. }
  14319. BfReflectKind BfModule::GetReflectKind(BfReflectKind reflectKind, BfTypeInstance* typeInstance)
  14320. {
  14321. auto checkTypeInstance = typeInstance;
  14322. while (checkTypeInstance != NULL)
  14323. {
  14324. if (checkTypeInstance->mCustomAttributes != NULL)
  14325. {
  14326. auto checkReflectKind = BfReflectKind_None;
  14327. for (auto& customAttr : checkTypeInstance->mCustomAttributes->mAttributes)
  14328. {
  14329. if (customAttr.mType->mTypeDef->mName->ToString() == "ReflectAttribute")
  14330. {
  14331. if (customAttr.mCtorArgs.size() > 0)
  14332. {
  14333. auto constant = checkTypeInstance->mConstHolder->GetConstant(customAttr.mCtorArgs[0]);
  14334. checkReflectKind = (BfReflectKind)((int)checkReflectKind | constant->mInt32);
  14335. }
  14336. else
  14337. {
  14338. checkReflectKind = BfReflectKind_All;
  14339. }
  14340. }
  14341. else
  14342. {
  14343. auto userReflectKind = GetUserReflectKind(customAttr.mType);
  14344. checkReflectKind = (BfReflectKind)(checkReflectKind | userReflectKind);
  14345. }
  14346. }
  14347. if ((checkTypeInstance == typeInstance) ||
  14348. ((checkReflectKind & BfReflectKind_ApplyToInnerTypes) != 0))
  14349. {
  14350. reflectKind = (BfReflectKind)(reflectKind | checkReflectKind);
  14351. }
  14352. }
  14353. for (auto ifaceEntry : typeInstance->mInterfaces)
  14354. {
  14355. if (ifaceEntry.mInterfaceType->mCustomAttributes != NULL)
  14356. {
  14357. auto iface = ifaceEntry.mInterfaceType;
  14358. auto customAttr = iface->mCustomAttributes->Get(mCompiler->mReflectAttributeTypeDef);
  14359. if (customAttr != NULL)
  14360. {
  14361. for (auto& prop : customAttr->mSetProperties)
  14362. {
  14363. auto propDef = prop.mPropertyRef.mTypeInstance->mTypeDef->mProperties[prop.mPropertyRef.mPropIdx];
  14364. if (propDef->mName == "ReflectImplementer")
  14365. {
  14366. if (prop.mParam.mValue.IsConst())
  14367. {
  14368. auto constant = iface->mConstHolder->GetConstant(prop.mParam.mValue);
  14369. reflectKind = (BfReflectKind)(reflectKind | (BfReflectKind)constant->mInt32);
  14370. }
  14371. }
  14372. }
  14373. }
  14374. }
  14375. }
  14376. checkTypeInstance = mContext->mUnreifiedModule->GetOuterType(checkTypeInstance);
  14377. }
  14378. return reflectKind;
  14379. }
  14380. bool BfModule::HasDeferredScopeCalls(BfScopeData* scope)
  14381. {
  14382. BfScopeData* checkScope = mCurMethodState->mCurScope;
  14383. while (checkScope != NULL)
  14384. {
  14385. if ((!checkScope->mDeferredCallEntries.IsEmpty()) || (!checkScope->mDeferredLifetimeEnds.empty()))
  14386. return true;
  14387. if (checkScope == scope)
  14388. break;
  14389. checkScope = checkScope->mPrevScope;
  14390. }
  14391. return false;
  14392. }
  14393. void BfModule::EmitDeferredScopeCalls(bool useSrcPositions, BfScopeData* scopeData, BfIRBlock doneBlock)
  14394. {
  14395. // Is there anything we need to do here?
  14396. if (mBfIRBuilder->mIgnoreWrites)
  14397. {
  14398. // Just visit deferred blocks
  14399. BfScopeData* checkScope = mCurMethodState->mCurScope;
  14400. while (checkScope != NULL)
  14401. {
  14402. BfDeferredCallEntry* deferredCallEntry = checkScope->mDeferredCallEntries.mHead;
  14403. while (deferredCallEntry != NULL)
  14404. {
  14405. if (deferredCallEntry->mDeferredBlock != NULL)
  14406. {
  14407. SetAndRestoreValue<BfMixinState*> prevMixinState(mCurMethodState->mMixinState, checkScope->mMixinState);
  14408. if (checkScope == &mCurMethodState->mHeadScope)
  14409. CreateRetValLocal();
  14410. SetAndRestoreValue<BfAstNode*> prevCustomAttribute(mCurMethodState->mEmitRefNode, deferredCallEntry->mEmitRefNode);
  14411. VisitEmbeddedStatement(deferredCallEntry->mDeferredBlock, NULL, BfEmbeddedStatementFlags_IsDeferredBlock);
  14412. }
  14413. deferredCallEntry = deferredCallEntry->mNext;
  14414. }
  14415. if (checkScope == scopeData)
  14416. break;
  14417. checkScope = checkScope->mPrevScope;
  14418. }
  14419. return;
  14420. }
  14421. // Why did we want to do SetIllegalSrcPos here?
  14422. // Don't we always want to step onto these instances?
  14423. // Find a case where we don't and perhaps only do it there.
  14424. // The downside was that 'EmitEnsureInstructionAt' on the end of block statements causes
  14425. // a (seemingly) unneeded NOP when we do SetIllegalSrcPos
  14426. //SetIllegalSrcPos();
  14427. bool setSrcPos = false;
  14428. bool wantsNop = true;
  14429. BfAstNode* deferCloseNode = NULL;
  14430. if (mCurMethodState->mInPostReturn)
  14431. {
  14432. // These won't get used, they are post-return
  14433. return;
  14434. }
  14435. SizedArray<BfIRValue, 8> deferredLifetimeEnds;
  14436. BfScopeData* scopeJumpBlock = NULL;
  14437. bool hadExtraDeferredLifetimeEnds = false;
  14438. auto _FlushLifetimeEnds = [&]()
  14439. {
  14440. for (auto lifetimeEnd : deferredLifetimeEnds)
  14441. {
  14442. mBfIRBuilder->CreateLifetimeEnd(lifetimeEnd);
  14443. mBfIRBuilder->ClearDebugLocation_Last();
  14444. }
  14445. deferredLifetimeEnds.clear();
  14446. };
  14447. BfScopeData* checkScope = mCurMethodState->mCurScope;
  14448. while (checkScope != NULL)
  14449. {
  14450. if (checkScope->mCloseNode != NULL)
  14451. deferCloseNode = checkScope->mCloseNode;
  14452. if (doneBlock)
  14453. {
  14454. // Try to find a match where we've already emitted these calls and then jumped to the correct block
  14455. for (auto& checkHandler : checkScope->mDeferredHandlers)
  14456. {
  14457. if (checkHandler.mDoneBlock == doneBlock)
  14458. {
  14459. scopeJumpBlock = checkScope;
  14460. mBfIRBuilder->CreateBr(checkHandler.mHandlerBlock);
  14461. mBfIRBuilder->ClearDebugLocation_Last();
  14462. _FlushLifetimeEnds();
  14463. break;
  14464. }
  14465. }
  14466. if (scopeJumpBlock != NULL)
  14467. break;
  14468. }
  14469. bool hasWork = (checkScope->mSavedStack) || (checkScope->mDeferredCallEntries.mHead != NULL);
  14470. if (checkScope != scopeData) // Only emit a block for deferred lifetimes if we're going back beyond this entry
  14471. hasWork |= (!deferredLifetimeEnds.IsEmpty());
  14472. if (hasWork)
  14473. {
  14474. SetAndRestoreValue<BfScopeData*> prevScope(mCurMethodState->mCurScope, checkScope);
  14475. if (deferCloseNode != NULL)
  14476. {
  14477. UpdateSrcPos(deferCloseNode);
  14478. }
  14479. if (checkScope == &mCurMethodState->mHeadScope)
  14480. CreateRetValLocal();
  14481. if (doneBlock)
  14482. {
  14483. bool crossingMixin = mCurMethodState->mCurScope->mMixinDepth != checkScope->mMixinDepth;
  14484. String blockName = "deferredCalls";
  14485. //blockName += StrFormat("_%d", mBfIRBuilder->mBlockCount);
  14486. BfDeferredHandler deferredHandler;
  14487. if ((!crossingMixin) && (deferredLifetimeEnds.IsEmpty()))
  14488. {
  14489. mBfIRBuilder->SaveDebugLocation();
  14490. mBfIRBuilder->ClearDebugLocation();
  14491. deferredHandler.mHandlerBlock = mBfIRBuilder->MaybeChainNewBlock(blockName);
  14492. mBfIRBuilder->RestoreDebugLocation();
  14493. }
  14494. else
  14495. {
  14496. // Definitely chain
  14497. deferredHandler.mHandlerBlock = mBfIRBuilder->CreateBlock(blockName);
  14498. mBfIRBuilder->CreateBr(deferredHandler.mHandlerBlock);
  14499. mBfIRBuilder->ClearDebugLocation_Last();
  14500. _FlushLifetimeEnds();
  14501. mBfIRBuilder->AddBlock(deferredHandler.mHandlerBlock);
  14502. mBfIRBuilder->SetInsertPoint(deferredHandler.mHandlerBlock);
  14503. }
  14504. deferredHandler.mDoneBlock = doneBlock;
  14505. if (!mBfIRBuilder->mIgnoreWrites)
  14506. checkScope->mDeferredHandlers.push_back(deferredHandler);
  14507. if (checkScope == &mCurMethodState->mHeadScope)
  14508. {
  14509. if (!mCurMethodState->mDIRetVal)
  14510. {
  14511. // 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
  14512. // be scoped to the physical method
  14513. /*if (deferCloseNode != NULL)
  14514. {
  14515. UpdateSrcPos(deferCloseNode);
  14516. }*/
  14517. CreateDIRetVal();
  14518. }
  14519. }
  14520. if (checkScope != mCurMethodState->mTailScope)
  14521. {
  14522. if (deferredHandler.mHandlerBlock.IsFake())
  14523. {
  14524. BF_ASSERT(mBfIRBuilder->mIgnoreWrites);
  14525. }
  14526. if (!mBfIRBuilder->mIgnoreWrites)
  14527. checkScope->mAtEndBlocks.push_back(deferredHandler.mHandlerBlock);
  14528. }
  14529. }
  14530. HashSet<BfDeferredCallEntry*> handledSet;
  14531. BfDeferredCallEntry* deferredCallEntry = checkScope->mDeferredCallEntries.mHead;
  14532. while (deferredCallEntry != NULL)
  14533. {
  14534. BfDeferredCallEmitState deferredCallEmitState;
  14535. deferredCallEmitState.mCloseNode = deferCloseNode;
  14536. SetAndRestoreValue<BfDeferredCallEmitState*> prevDeferredCallEmitState(mCurMethodState->mDeferredCallEmitState, &deferredCallEmitState);
  14537. SetAndRestoreValue<bool> prevIgnoredWrites(mBfIRBuilder->mIgnoreWrites, deferredCallEntry->mIgnored);
  14538. SetAndRestoreValue<BfMixinState*> prevMixinState(mCurMethodState->mMixinState, checkScope->mMixinState);
  14539. if (deferCloseNode != NULL)
  14540. {
  14541. UpdateSrcPos(deferCloseNode);
  14542. }
  14543. if (wantsNop)
  14544. EmitEnsureInstructionAt();
  14545. wantsNop = false;
  14546. if (deferredCallEntry->mDeferredBlock != NULL)
  14547. {
  14548. BfDeferredCallEntry** entryPtr = NULL;
  14549. if (!handledSet.TryAdd(deferredCallEntry, &entryPtr))
  14550. {
  14551. // Already handled, can happen if we defer again within the block
  14552. deferredCallEntry = deferredCallEntry->mNext;
  14553. continue;
  14554. }
  14555. auto prevHead = checkScope->mDeferredCallEntries.mHead;
  14556. EmitDeferredCall(checkScope, *deferredCallEntry, true);
  14557. if (prevHead != checkScope->mDeferredCallEntries.mHead)
  14558. {
  14559. // The list changed, start over and ignore anything we've already handled
  14560. deferredCallEntry = checkScope->mDeferredCallEntries.mHead;
  14561. }
  14562. else
  14563. deferredCallEntry = deferredCallEntry->mNext;
  14564. }
  14565. else
  14566. {
  14567. EmitDeferredCall(checkScope, *deferredCallEntry, true);
  14568. deferredCallEntry = deferredCallEntry->mNext;
  14569. }
  14570. }
  14571. if (checkScope->mSavedStack)
  14572. {
  14573. checkScope->mSavedStackUses.Add(mBfIRBuilder->CreateStackRestore(checkScope->mSavedStack));
  14574. if (mCurMethodState->mDynStackRevIdx)
  14575. {
  14576. auto curValue = mBfIRBuilder->CreateLoad(mCurMethodState->mDynStackRevIdx);
  14577. auto newValue = mBfIRBuilder->CreateAdd(curValue, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 1));
  14578. mBfIRBuilder->CreateStore(newValue, mCurMethodState->mDynStackRevIdx);
  14579. }
  14580. }
  14581. }
  14582. if (!checkScope->mIsScopeHead)
  14583. {
  14584. // We manually emit function-level lifetime ends after the 'ret' in ProcessMethod
  14585. if (!IsTargetingBeefBackend())
  14586. {
  14587. for (auto lifetimeEnd : checkScope->mDeferredLifetimeEnds)
  14588. {
  14589. mBfIRBuilder->CreateLifetimeEnd(lifetimeEnd);
  14590. }
  14591. }
  14592. else
  14593. {
  14594. for (auto lifetimeEnd : checkScope->mDeferredLifetimeEnds)
  14595. {
  14596. deferredLifetimeEnds.Add(lifetimeEnd);
  14597. }
  14598. }
  14599. }
  14600. if (checkScope == scopeData)
  14601. break;
  14602. checkScope = checkScope->mPrevScope;
  14603. }
  14604. if ((doneBlock) && (scopeJumpBlock == NULL))
  14605. {
  14606. mBfIRBuilder->CreateBr(doneBlock);
  14607. mBfIRBuilder->ClearDebugLocation_Last();
  14608. }
  14609. // Keeping CreateLifetimeEnds until the end messes up when we chain to old mDeferredHandlers that
  14610. // may have been created when other scope lifetimes were available
  14611. _FlushLifetimeEnds();
  14612. // Emit lifetimeEnds after the branch for Beef
  14613. /*if (IsTargetingBeefBackend())
  14614. {
  14615. bool needsEnsureInst = (!doneBlock) && (scopeJumpBlock == NULL);
  14616. BfScopeData* checkScope = mCurMethodState->mCurScope;
  14617. while (checkScope != NULL)
  14618. {
  14619. if (checkScope == scopeJumpBlock)
  14620. break;
  14621. if (!checkScope->mIsScopeHead)
  14622. {
  14623. for (auto lifetimeEnd : checkScope->mDeferredLifetimeEnds)
  14624. {
  14625. if (needsEnsureInst)
  14626. {
  14627. needsEnsureInst = false;
  14628. }
  14629. mBfIRBuilder->CreateLifetimeEnd(lifetimeEnd);
  14630. }
  14631. }
  14632. if (checkScope == scopeData)
  14633. break;
  14634. checkScope = checkScope->mPrevScope;
  14635. }
  14636. }*/
  14637. }
  14638. void BfModule::MarkScopeLeft(BfScopeData* scopeData, bool isNoReturn)
  14639. {
  14640. if ((mCurMethodState->mDeferredLocalAssignData != NULL) && (!isNoReturn))
  14641. {
  14642. auto deferredLocalAssignData = mCurMethodState->mDeferredLocalAssignData;
  14643. while (deferredLocalAssignData != NULL)
  14644. {
  14645. if ((deferredLocalAssignData->mScopeData == NULL) || (deferredLocalAssignData->mScopeData->mScopeDepth < scopeData->mScopeDepth))
  14646. break;
  14647. if ((deferredLocalAssignData->mScopeData != NULL) && (deferredLocalAssignData->mScopeData->mScopeDepth == scopeData->mScopeDepth))
  14648. deferredLocalAssignData->mIsUnconditional = false;
  14649. deferredLocalAssignData = deferredLocalAssignData->mChainedAssignData;
  14650. }
  14651. }
  14652. // When we leave a scope, mark those as assigned for deferred assignment purposes
  14653. for (int localIdx = scopeData->mLocalVarStart; localIdx < (int)mCurMethodState->mLocals.size(); localIdx++)
  14654. {
  14655. auto localDef = mCurMethodState->mLocals[localIdx];
  14656. if (localDef->mAssignedKind == BfLocalVarAssignKind_None)
  14657. {
  14658. bool hadAssignment = false;
  14659. if (mCurMethodState->mDeferredLocalAssignData != NULL)
  14660. {
  14661. for (auto& entry : mCurMethodState->mDeferredLocalAssignData->mAssignedLocals)
  14662. if (entry.mLocalVar == localDef)
  14663. hadAssignment = true;
  14664. }
  14665. if (!hadAssignment)
  14666. {
  14667. if (!isNoReturn)
  14668. localDef->mHadExitBeforeAssign = true;
  14669. mCurMethodState->LocalDefined(localDef);
  14670. }
  14671. }
  14672. }
  14673. }
  14674. void BfModule::CreateReturn(BfIRValue val)
  14675. {
  14676. if ((!mIsComptimeModule) && (mCurMethodInstance->GetStructRetIdx() != -1))
  14677. {
  14678. // Store to sret
  14679. BF_ASSERT(val);
  14680. mBfIRBuilder->CreateStore(val, mBfIRBuilder->GetArgument(mCurMethodInstance->GetStructRetIdx()));
  14681. mBfIRBuilder->CreateRetVoid();
  14682. return;
  14683. }
  14684. if (mCurMethodInstance->mReturnType->IsVar())
  14685. return;
  14686. if (mCurMethodInstance->mReturnType->IsValuelessType())
  14687. {
  14688. mBfIRBuilder->CreateRetVoid();
  14689. return;
  14690. }
  14691. if (mCurMethodInstance->mReturnType->IsStruct())
  14692. {
  14693. BfTypeCode loweredReturnType = BfTypeCode_None;
  14694. BfTypeCode loweredReturnType2 = BfTypeCode_None;
  14695. if (!mIsComptimeModule)
  14696. mCurMethodInstance->GetLoweredReturnType(&loweredReturnType, &loweredReturnType2);
  14697. if (loweredReturnType != BfTypeCode_None)
  14698. {
  14699. auto retVal = CreateAlloca(mCurMethodInstance->mReturnType);
  14700. mBfIRBuilder->CreateStore(val, retVal);
  14701. auto irRetType = GetIRLoweredType(loweredReturnType, loweredReturnType2);
  14702. irRetType = mBfIRBuilder->GetPointerTo(irRetType);
  14703. auto ptrReturnValue = mBfIRBuilder->CreateBitCast(retVal, irRetType);
  14704. auto loadedReturnValue = mBfIRBuilder->CreateLoad(ptrReturnValue);
  14705. mBfIRBuilder->CreateRet(loadedReturnValue);
  14706. return;
  14707. }
  14708. }
  14709. BF_ASSERT(val);
  14710. mBfIRBuilder->CreateRet(val);
  14711. }
  14712. void BfModule::EmitReturn(const BfTypedValue& val)
  14713. {
  14714. if (mCurMethodState->mIRExitBlock)
  14715. {
  14716. if (!mCurMethodInstance->mReturnType->IsValuelessType())
  14717. {
  14718. if (val) // We allow for val to be empty if we know we've already written the value to mRetVal
  14719. {
  14720. if ((mCurMethodState->mRetValAddr) || (mCurMethodState->mRetVal))
  14721. {
  14722. BfIRValue retVal = mCurMethodState->mRetVal.mValue;
  14723. if (!mCurMethodState->mRetVal)
  14724. retVal = mBfIRBuilder->CreateAlignedLoad(mCurMethodState->mRetValAddr, mCurMethodInstance->mReturnType->mAlign);
  14725. mBfIRBuilder->CreateAlignedStore(val.mValue, retVal, mCurMethodInstance->mReturnType->mAlign);
  14726. }
  14727. else if (mIsComptimeModule)
  14728. {
  14729. if (!val.mType->IsValuelessType())
  14730. mBfIRBuilder->CreateSetRet(val.mValue, val.mType->mTypeId);
  14731. else
  14732. mBfIRBuilder->CreateSetRet(BfIRValue(), val.mType->mTypeId);
  14733. }
  14734. else
  14735. {
  14736. // Just ignore
  14737. BF_ASSERT(mCurMethodInstance->mReturnType->IsVar());
  14738. }
  14739. }
  14740. }
  14741. EmitDeferredScopeCalls(true, NULL, mCurMethodState->mIRExitBlock);
  14742. }
  14743. else
  14744. {
  14745. EmitDeferredScopeCalls(false, NULL);
  14746. if (val)
  14747. {
  14748. BF_ASSERT(mBfIRBuilder->mIgnoreWrites);
  14749. }
  14750. }
  14751. mCurMethodState->SetHadReturn(true);
  14752. mCurMethodState->mLeftBlockUncond = true;
  14753. }
  14754. void BfModule::EmitDefaultReturn()
  14755. {
  14756. if (mCurMethodState->mInDeferredBlock)
  14757. return;
  14758. if (mCurMethodState->mIRExitBlock)
  14759. {
  14760. EmitDeferredScopeCalls(true, NULL, mCurMethodState->mIRExitBlock);
  14761. }
  14762. else
  14763. {
  14764. if ((mCurMethodInstance == NULL) || (mCurMethodInstance->mReturnType->IsVar()))
  14765. {
  14766. // Ignore
  14767. }
  14768. else if (mCurMethodInstance->mReturnType->IsVoid())
  14769. mBfIRBuilder->CreateRetVoid();
  14770. else if ((!mIsComptimeModule) && (mCurMethodInstance->GetStructRetIdx() == -1))
  14771. mBfIRBuilder->CreateRet(GetDefaultValue(mCurMethodInstance->mReturnType));
  14772. }
  14773. mCurMethodState->SetHadReturn(true);
  14774. mCurMethodState->mLeftBlockUncond = true;
  14775. }
  14776. void BfModule::AssertErrorState()
  14777. {
  14778. if (mIgnoreErrors)
  14779. return;
  14780. if (mHadBuildError)
  14781. return;
  14782. if (mCurTypeInstance != NULL)
  14783. {
  14784. if (mCurTypeInstance->IsUnspecializedTypeVariation())
  14785. return;
  14786. }
  14787. if (mCurMethodInstance != NULL)
  14788. {
  14789. if (mCurMethodInstance->IsOrInUnspecializedVariation())
  14790. return;
  14791. if (mCurMethodInstance->mHasFailed)
  14792. return;
  14793. }
  14794. // We want the module to be marked as failed even if it's just an error in the parser
  14795. if (mCurMethodInstance != NULL)
  14796. mCurMethodInstance->mHasFailed = true;
  14797. mHadBuildError = true;
  14798. // We check for either the parsing to have failed (possibly on a previous run), or for the current instance to have failed
  14799. if (mCurTypeInstance != NULL)
  14800. {
  14801. if (mCurTypeInstance->mTypeFailed)
  14802. return;
  14803. if ((mCurTypeInstance->mTypeDef->GetDefinition()->mSource != NULL) && (mCurTypeInstance->mTypeDef->GetDefinition()->mSource->mParsingFailed))
  14804. return;
  14805. }
  14806. if (mCurMethodInstance != NULL)
  14807. {
  14808. if ((mCurMethodInstance->mMethodDef->mDeclaringType != NULL) &&
  14809. (mCurMethodInstance->mMethodDef->mDeclaringType->mSource != NULL) &&
  14810. (mCurMethodInstance->mMethodDef->mDeclaringType->mSource->mParsingFailed))
  14811. return;
  14812. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL) &&
  14813. (mCurMethodState->mMixinState->mMixinMethodInstance->mMethodDef->mDeclaringType->mSource != NULL) &&
  14814. (mCurMethodState->mMixinState->mMixinMethodInstance->mMethodDef->mDeclaringType->mSource->mParsingFailed))
  14815. return;
  14816. }
  14817. if (mCompiler->IsAutocomplete())
  14818. return;
  14819. if (mCompiler->mPassInstance->HasFailed())
  14820. return;
  14821. InternalError("Compiler in invalid state but AssertErrorState failed to detect prior error");
  14822. }
  14823. void BfModule::AssertParseErrorState()
  14824. {
  14825. if (mCompiler->mRevision == 1)
  14826. AssertErrorState();
  14827. }
  14828. BfType* BfModule::GetDelegateReturnType(BfType* delegateType)
  14829. {
  14830. BF_ASSERT(delegateType->IsDelegateOrFunction());
  14831. auto typeInst = delegateType->ToTypeInstance();
  14832. PopulateType(typeInst, BfPopulateType_DataAndMethods);
  14833. BfMethodInstance* invokeMethodInstance = GetRawMethodInstanceAtIdx(typeInst->ToTypeInstance(), 0, "Invoke");
  14834. if (invokeMethodInstance == NULL)
  14835. return GetPrimitiveType(BfTypeCode_Var);
  14836. return invokeMethodInstance->mReturnType;
  14837. }
  14838. BfMethodInstance* BfModule::GetDelegateInvokeMethod(BfTypeInstance* typeInstance)
  14839. {
  14840. return GetRawMethodInstanceAtIdx(typeInstance, 0, "Invoke");
  14841. }
  14842. void BfModule::CreateDelegateInvokeMethod()
  14843. {
  14844. // Clear out debug loc - otherwise we'll single step onto the delegate type declaration
  14845. //mBfIRBuilder->ClearDebugLocation();
  14846. SetIllegalSrcPos();
  14847. auto typeInstance = mCurTypeInstance;
  14848. auto memberFuncType = mBfIRBuilder->MapMethod(mCurMethodInstance);
  14849. SizedArray<BfIRType, 4> staticParamTypes;
  14850. SizedArray<BfIRValue, 4> staticFuncArgs;
  14851. SizedArray<BfIRValue, 4> memberFuncArgs;
  14852. auto multicastDelegateType = typeInstance->mBaseType;
  14853. if (multicastDelegateType->mFieldInstances.size() != 2)
  14854. {
  14855. AssertErrorState();
  14856. return;
  14857. }
  14858. auto multicastDelegate = mBfIRBuilder->CreateBitCast(mCurMethodState->mLocals[0]->mValue, mBfIRBuilder->MapType(multicastDelegateType));
  14859. auto fieldPtr = mBfIRBuilder->CreateInBoundsGEP(multicastDelegate, 0, 2); // Load 'delegate.mTarget'
  14860. auto fieldVal = mBfIRBuilder->CreateAlignedLoad(fieldPtr, mSystem->mPtrSize);
  14861. BfExprEvaluator exprEvaluator(this);
  14862. SizedArray<BfIRType, 8> origParamTypes;
  14863. BfIRType origReturnType;
  14864. BfIRType staticReturnType;
  14865. mCurMethodInstance->GetIRFunctionInfo(this, origReturnType, origParamTypes);
  14866. if (mCurMethodInstance->mReturnType->IsValueType())
  14867. mBfIRBuilder->PopulateType(mCurMethodInstance->mReturnType, BfIRPopulateType_Full);
  14868. if ((mIsComptimeModule) || (mCurMethodInstance->GetStructRetIdx() != 0))
  14869. memberFuncArgs.push_back(BfIRValue()); // Push 'target'
  14870. int thisIdx = 0;
  14871. if ((!mIsComptimeModule) && (mCurMethodInstance->GetStructRetIdx() != -1))
  14872. {
  14873. thisIdx = mCurMethodInstance->GetStructRetIdx() ^ 1;
  14874. memberFuncArgs.push_back(mBfIRBuilder->GetArgument(mCurMethodInstance->GetStructRetIdx()));
  14875. }
  14876. if ((!mIsComptimeModule) && (mCurMethodInstance->GetStructRetIdx(true) != -1))
  14877. staticFuncArgs.push_back(mBfIRBuilder->GetArgument(mCurMethodInstance->GetStructRetIdx()));
  14878. if ((!mIsComptimeModule) && (mCurMethodInstance->GetStructRetIdx() == 0))
  14879. memberFuncArgs.push_back(BfIRValue()); // Push 'target'
  14880. mCurMethodInstance->GetIRFunctionInfo(this, staticReturnType, staticParamTypes, true);
  14881. for (int i = 1; i < (int)mCurMethodState->mLocals.size(); i++)
  14882. {
  14883. if (mCurMethodState->mLocals[i]->mCompositeCount >= 0)
  14884. continue;
  14885. BfTypedValue localVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[i], true);
  14886. exprEvaluator.PushArg(localVal, staticFuncArgs);
  14887. exprEvaluator.PushArg(localVal, memberFuncArgs);
  14888. }
  14889. auto staticFunc = mBfIRBuilder->CreateFunctionType(staticReturnType, staticParamTypes, false);
  14890. auto staticFuncPtr = mBfIRBuilder->GetPointerTo(staticFunc);
  14891. auto staticFuncPtrPtr = mBfIRBuilder->GetPointerTo(staticFuncPtr);
  14892. auto trueBB = mBfIRBuilder->CreateBlock("if.then", true);
  14893. auto falseBB = mBfIRBuilder->CreateBlock("if.else");
  14894. auto doneBB = mBfIRBuilder->CreateBlock("done");
  14895. auto checkTargetNull = mBfIRBuilder->CreateIsNotNull(fieldVal);
  14896. mBfIRBuilder->CreateCondBr(checkTargetNull, trueBB, falseBB);
  14897. BfIRValue nonStaticResult;
  14898. BfIRValue staticResult;
  14899. auto callingConv = GetIRCallingConvention(mCurMethodInstance);
  14900. auto trueEndBB = trueBB;
  14901. /// Non-static invocation
  14902. {
  14903. auto memberFuncPtr = mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapMethod(mCurMethodInstance));
  14904. auto memberFuncPtrPtr = mBfIRBuilder->GetPointerTo(memberFuncPtr);
  14905. mBfIRBuilder->SetInsertPoint(trueBB);
  14906. BfIRValue numVal;
  14907. if ((mCompiler->mOptions.mObjectHasDebugFlags) && (!mIsComptimeModule) && (mCompiler->mSystem->mPtrSize == 8))
  14908. {
  14909. numVal = mBfIRBuilder->CreatePtrToInt(fieldVal, BfTypeCode_UInt64);
  14910. auto andVal = mBfIRBuilder->CreateAnd(numVal, mBfIRBuilder->CreateConst(BfTypeCode_UInt64, (uint64)~0x8000000000000000ULL));
  14911. fieldVal = mBfIRBuilder->CreateIntToPtr(andVal, mBfIRBuilder->MapType(mContext->mBfObjectType));
  14912. }
  14913. if ((WantsObjectAccessCheck(mContext->mBfObjectType) && (mCompiler->mSystem->mPtrSize == 8)))
  14914. {
  14915. auto oacDoBB = mBfIRBuilder->CreateBlock("oac.do", true);
  14916. auto oacDoneBB = mBfIRBuilder->CreateBlock("oac.done");
  14917. auto checkGTE = mBfIRBuilder->CreateCmpGTE(numVal, mBfIRBuilder->CreateConst(BfTypeCode_UInt64, (uint64)0x8000000000000000ULL), false);
  14918. mBfIRBuilder->CreateCondBr(checkGTE, oacDoBB, oacDoneBB);
  14919. mBfIRBuilder->SetInsertPoint(oacDoBB);
  14920. mBfIRBuilder->CreateObjectAccessCheck(fieldVal, !IsOptimized());
  14921. mBfIRBuilder->CreateBr(oacDoneBB);
  14922. mBfIRBuilder->AddBlock(oacDoneBB);
  14923. mBfIRBuilder->SetInsertPoint(oacDoneBB);
  14924. trueEndBB = oacDoneBB;
  14925. }
  14926. memberFuncArgs[thisIdx] = mBfIRBuilder->CreateBitCast(fieldVal, mBfIRBuilder->MapType(mCurTypeInstance));
  14927. auto fieldPtr = mBfIRBuilder->CreateInBoundsGEP(multicastDelegate, 0, 1); // Load 'delegate.mFuncPtr'
  14928. auto funcPtrPtr = mBfIRBuilder->CreateBitCast(fieldPtr, memberFuncPtrPtr);
  14929. auto funcPtr = mBfIRBuilder->CreateAlignedLoad(funcPtrPtr, mSystem->mPtrSize);
  14930. nonStaticResult = mBfIRBuilder->CreateCall(funcPtr, memberFuncArgs);
  14931. if ((!mIsComptimeModule) && (mCurMethodInstance->GetStructRetIdx() != -1))
  14932. mBfIRBuilder->Call_AddAttribute(nonStaticResult, mCurMethodInstance->GetStructRetIdx() + 1, BfIRAttribute_StructRet);
  14933. if (callingConv != BfIRCallingConv_CDecl)
  14934. mBfIRBuilder->SetCallCallingConv(nonStaticResult, callingConv);
  14935. mCurMethodState->SetHadReturn(false);
  14936. mCurMethodState->mLeftBlockUncond = false;
  14937. mCurMethodState->mLeftBlockCond = false;
  14938. mBfIRBuilder->CreateBr(doneBB);
  14939. }
  14940. // Static invocation
  14941. {
  14942. mBfIRBuilder->AddBlock(falseBB);
  14943. mBfIRBuilder->SetInsertPoint(falseBB);
  14944. auto fieldPtr = mBfIRBuilder->CreateInBoundsGEP(multicastDelegate, 0, 1); // Load 'delegate.mFuncPtr'
  14945. auto funcPtrPtr = mBfIRBuilder->CreateBitCast(fieldPtr, staticFuncPtrPtr);
  14946. auto funcPtr = mBfIRBuilder->CreateAlignedLoad(funcPtrPtr, mSystem->mPtrSize);
  14947. staticResult = mBfIRBuilder->CreateCall(funcPtr, staticFuncArgs);
  14948. if ((!mIsComptimeModule) && (mCurMethodInstance->GetStructRetIdx(true) != -1))
  14949. {
  14950. // Note: since this is a forced static invocation, we know the sret will be the first parameter
  14951. mBfIRBuilder->Call_AddAttribute(staticResult, 0 + 1, BfIRAttribute_StructRet);
  14952. }
  14953. // We had a sret for the non-static but no sret for the static (because we have a lowered return type there)
  14954. if ((!mIsComptimeModule) && (mCurMethodInstance->GetStructRetIdx() != -1) && (mCurMethodInstance->GetStructRetIdx(true) == -1))
  14955. {
  14956. auto sretToType = mBfIRBuilder->GetPointerTo(staticReturnType);
  14957. auto sretCastedPtr = mBfIRBuilder->CreateBitCast(mBfIRBuilder->GetArgument(mCurMethodInstance->GetStructRetIdx()), sretToType);
  14958. mBfIRBuilder->CreateStore(staticResult, sretCastedPtr);
  14959. }
  14960. if (callingConv == BfIRCallingConv_ThisCall)
  14961. callingConv = BfIRCallingConv_CDecl;
  14962. if (callingConv != BfIRCallingConv_CDecl)
  14963. mBfIRBuilder->SetCallCallingConv(staticResult, callingConv);
  14964. mCurMethodState->SetHadReturn(false);
  14965. mCurMethodState->mLeftBlockUncond = false;
  14966. mCurMethodState->mLeftBlockCond = false;
  14967. mBfIRBuilder->CreateBr(doneBB);
  14968. }
  14969. mBfIRBuilder->AddBlock(doneBB);
  14970. mBfIRBuilder->SetInsertPoint(doneBB);
  14971. if (mCurMethodInstance->mReturnType->IsVar())
  14972. {
  14973. // Do nothing
  14974. }
  14975. else if ((mCurMethodInstance->mReturnType->IsValuelessType()) ||
  14976. ((!mIsComptimeModule) && (mCurMethodInstance->GetStructRetIdx() != -1)))
  14977. {
  14978. mBfIRBuilder->CreateRetVoid();
  14979. }
  14980. else
  14981. {
  14982. BfIRType loweredIRReturnType;
  14983. BfTypeCode loweredTypeCode = BfTypeCode_None;
  14984. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  14985. if ((!mIsComptimeModule) && (mCurMethodInstance->GetLoweredReturnType(&loweredTypeCode, &loweredTypeCode2)))
  14986. loweredIRReturnType = GetIRLoweredType(loweredTypeCode, loweredTypeCode2);
  14987. else
  14988. loweredIRReturnType = mBfIRBuilder->MapType(mCurMethodInstance->mReturnType);
  14989. auto phi = mBfIRBuilder->CreatePhi(loweredIRReturnType, 2);
  14990. mBfIRBuilder->AddPhiIncoming(phi, nonStaticResult, trueEndBB);
  14991. mBfIRBuilder->AddPhiIncoming(phi, staticResult, falseBB);
  14992. mBfIRBuilder->CreateRet(phi);
  14993. }
  14994. }
  14995. // "Interested" here means every method for a normal compile, and just the method the cursor is on for autocompletion
  14996. bool BfModule::IsInterestedInMethod(BfTypeInstance* typeInstance, BfMethodDef* methodDef)
  14997. {
  14998. auto typeDef = typeInstance->mTypeDef;
  14999. auto methodDeclaration = methodDef->mMethodDeclaration;
  15000. if (!mCompiler->mIsResolveOnly)
  15001. return true;
  15002. if (typeInstance->IsGenericTypeInstance())
  15003. {
  15004. // We only really want to process the unspecialized type for autocompletion
  15005. if ((!typeInstance->IsUnspecializedType()) || (typeInstance->IsUnspecializedTypeVariation()))
  15006. return false;
  15007. }
  15008. BfAstNode* checkNode = methodDeclaration;
  15009. if (methodDeclaration == NULL)
  15010. checkNode = methodDef->mBody;
  15011. if ((!mCompiler->mResolvePassData->mParsers.IsEmpty()) && (typeDef->mTypeDeclaration->IsFromParser(mCompiler->mResolvePassData->mParsers[0])))
  15012. {
  15013. if (mCompiler->mResolvePassData->mAutoComplete == NULL)
  15014. return true;
  15015. }
  15016. return false;
  15017. }
  15018. void BfModule::CalcAppendAlign(BfMethodInstance* methodInst)
  15019. {
  15020. methodInst->mAppendAllocAlign = 1;
  15021. }
  15022. BfAllowAppendKind BfModule::GetBaseAllowAppend(BfMethodInstance* curMethodInstance)
  15023. {
  15024. auto typeInstance = curMethodInstance->GetOwner();
  15025. auto methodDef = curMethodInstance->mMethodDef;
  15026. if (methodDef->mAppendKind == BfAllowAppendKind_No)
  15027. return BfAllowAppendKind_No;
  15028. if ((typeInstance->mInstSize == typeInstance->mBaseType->mInstSize) &&
  15029. (typeInstance->IsZeroGap()) &&
  15030. (typeInstance->mBaseType->IsZeroGap()) &&
  15031. (methodDef->mAppendKind == BfAllowAppendKind_ZeroGap))
  15032. {
  15033. return BfAllowAppendKind_ZeroGap;
  15034. }
  15035. return BfAllowAppendKind_Yes;
  15036. }
  15037. BfTypedValue BfModule::TryConstCalcAppend(BfMethodInstance* methodInst, SizedArrayImpl<BfIRValue>& args, bool force)
  15038. {
  15039. BP_ZONE("BfModule::TryConstCalcAppend");
  15040. BF_ASSERT(methodInst->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend);
  15041. if ((mCompiler->mIsResolveOnly) && (!mIsComptimeModule) && (!force))
  15042. return BfTypedValue();
  15043. // We want to regenerate all ctor calls when the method internals change
  15044. {
  15045. auto checkTypeInst = methodInst->GetOwner();
  15046. while (checkTypeInst->mTypeDef->mHasAppendCtor)
  15047. {
  15048. AddDependency(checkTypeInst, mCurTypeInstance, BfDependencyMap::DependencyFlag_InlinedCall);
  15049. checkTypeInst = GetBaseType(checkTypeInst);
  15050. }
  15051. }
  15052. if (!methodInst->mMayBeConst)
  15053. return BfTypedValue();
  15054. // Do we need to iterate in order to resolve mAppendAllocAlign?
  15055. bool isFirstRun = methodInst->mEndingAppendAllocAlign < 0;
  15056. bool wasAllConst = true;
  15057. int argIdx = 0;
  15058. int paramIdx = 0;
  15059. while (true)
  15060. {
  15061. if (argIdx >= (int)args.size())
  15062. break;
  15063. auto paramType = methodInst->GetParamType(paramIdx);
  15064. PopulateType(paramType);
  15065. int argCount = 0;
  15066. if (!paramType->IsValuelessType())
  15067. {
  15068. if ((!mIsComptimeModule) && (methodInst->GetParamIsSplat(paramIdx)))
  15069. argCount = paramType->GetSplatCount();
  15070. else
  15071. argCount = 1;
  15072. for (int argOfs = 0; argOfs < argCount; argOfs++)
  15073. {
  15074. auto arg = args[argIdx + argOfs];
  15075. if (!arg.IsConst())
  15076. {
  15077. wasAllConst = false;
  15078. if (!isFirstRun)
  15079. {
  15080. auto& param = methodInst->mParams[argIdx];
  15081. if (param.mReferencedInConstPass)
  15082. {
  15083. // If this param is required as part of the const calculation then
  15084. // we require that it be const...
  15085. return BfTypedValue();
  15086. }
  15087. }
  15088. }
  15089. }
  15090. }
  15091. paramIdx++;
  15092. argIdx += argCount;
  15093. }
  15094. auto methodDef = methodInst->mMethodDef;
  15095. auto methodDecl = methodDef->GetMethodDeclaration();
  15096. auto methodDeclBlock = BfNodeDynCast<BfBlock>(methodDecl->mBody);
  15097. if (methodDeclBlock == NULL)
  15098. return GetDefaultTypedValue(GetPrimitiveType(BfTypeCode_IntPtr)); // Must not have an append alloc at all!
  15099. BfTypedValue constValue;
  15100. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  15101. auto checkState = mCurMethodState->mConstResolveState;
  15102. while (checkState != NULL)
  15103. {
  15104. if (checkState->mMethodInstance == methodInst)
  15105. {
  15106. return BfTypedValue();
  15107. }
  15108. checkState = checkState->mPrevConstResolveState;
  15109. }
  15110. //auto accumValue = GetConstValue(0);
  15111. bool failed = false;
  15112. //
  15113. {
  15114. BfConstResolveState constResolveState;
  15115. constResolveState.mMethodInstance = methodInst;
  15116. constResolveState.mPrevConstResolveState = mCurMethodState->mConstResolveState;
  15117. constResolveState.mInCalcAppend = true;
  15118. SetAndRestoreValue<bool> ignoreWrites(mBfIRBuilder->mIgnoreWrites, true);
  15119. BfMethodState methodState;
  15120. SetAndRestoreValue<BfTypeInstance*> prevTypeInst(mCurTypeInstance, methodInst->GetOwner());
  15121. SetAndRestoreValue<BfMethodInstance*> prevMethodInst(mCurMethodInstance, methodInst);
  15122. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  15123. methodState.mTempKind = BfMethodState::TempKind_NonStatic;
  15124. methodState.mConstResolveState = &constResolveState;
  15125. int argIdx = 0;
  15126. for (int paramIdx = 0; paramIdx < methodInst->GetParamCount(); paramIdx++)
  15127. {
  15128. if (methodInst->GetParamKind(paramIdx) == BfParamKind_AppendIdx)
  15129. continue;
  15130. auto paramType = methodInst->GetParamType(paramIdx);
  15131. // Fix this after we allow structs to be consts
  15132. //BF_ASSERT(!paramType->IsSplattable());
  15133. BfLocalVariable* localVar = new BfLocalVariable();
  15134. localVar->mName = methodInst->GetParamName(paramIdx);
  15135. localVar->mResolvedType = paramType;
  15136. localVar->mConstValue = args[argIdx];
  15137. localVar->mParamIdx = paramIdx;
  15138. AddLocalVariableDef(localVar);
  15139. argIdx++;
  15140. }
  15141. AppendAllocVisitor appendAllocVisitor;
  15142. appendAllocVisitor.mConstAccum = GetDefaultTypedValue(GetPrimitiveType(BfTypeCode_IntPtr));
  15143. appendAllocVisitor.mIsFirstConstPass = isFirstRun;
  15144. BfTypedValue baseCtorAppendValue = CallBaseCtorCalc(true);
  15145. if (baseCtorAppendValue)
  15146. {
  15147. if (baseCtorAppendValue.mValue.IsFake())
  15148. appendAllocVisitor.mFailed = true;
  15149. else
  15150. appendAllocVisitor.mConstAccum = baseCtorAppendValue;
  15151. }
  15152. appendAllocVisitor.mModule = this;
  15153. appendAllocVisitor.VisitChild(methodDecl->mBody);
  15154. if (constResolveState.mFailed)
  15155. appendAllocVisitor.mFailed = true;
  15156. if (!appendAllocVisitor.mFailed)
  15157. constValue = appendAllocVisitor.mConstAccum;
  15158. if (appendAllocVisitor.mHasAppendWantMark)
  15159. methodInst->mHasAppendWantMark = true;
  15160. if (isFirstRun)
  15161. {
  15162. mCurMethodInstance->mEndingAppendAllocAlign = appendAllocVisitor.mCurAppendAlign;
  15163. if (mCurMethodInstance->mAppendAllocAlign <= 0)
  15164. mCurMethodInstance->mAppendAllocAlign = 1;
  15165. }
  15166. if (isFirstRun)
  15167. {
  15168. for (int paramIdx = 0; paramIdx < methodInst->GetParamCount(); paramIdx++)
  15169. {
  15170. auto localVar = mCurMethodState->mLocals[paramIdx];
  15171. if (localVar->mReadFromId != -1)
  15172. {
  15173. auto& param = methodInst->mParams[paramIdx];
  15174. param.mReferencedInConstPass = true;
  15175. }
  15176. }
  15177. }
  15178. }
  15179. mBfIRBuilder->SetInsertPoint(prevBlock);
  15180. if (!constValue)
  15181. {
  15182. // If we did a 'force' then some params may not have been const -- only clear mMayBeConst if we had
  15183. // all-const args
  15184. if (wasAllConst)
  15185. {
  15186. methodInst->mMayBeConst = false;
  15187. }
  15188. }
  15189. return constValue;
  15190. }
  15191. BfTypedValue BfModule::CallBaseCtorCalc(bool constOnly)
  15192. {
  15193. // Any errors should only be shown in the actual CTOR call
  15194. SetAndRestoreValue<bool> prevIgnoreWrites(mIgnoreErrors, true);
  15195. auto methodDef = mCurMethodInstance->mMethodDef;
  15196. BF_ASSERT((methodDef->mMethodType == BfMethodType_Ctor) || (methodDef->mMethodType == BfMethodType_CtorCalcAppend));
  15197. auto ctorDeclaration = (BfConstructorDeclaration*)methodDef->mMethodDeclaration;
  15198. BfAllowAppendKind allowAppendKind = GetBaseAllowAppend(mCurMethodInstance);
  15199. BfCustomAttributes* customAttributes = NULL;
  15200. defer(delete customAttributes);
  15201. BfInvocationExpression* ctorInvocation = NULL;
  15202. if (ctorDeclaration != NULL)
  15203. {
  15204. ctorInvocation = BfNodeDynCast<BfInvocationExpression>(ctorDeclaration->mInitializer);
  15205. if (auto attributedExpr = BfNodeDynCast<BfAttributedExpression>(ctorDeclaration->mInitializer))
  15206. {
  15207. ctorInvocation = BfNodeDynCast<BfInvocationExpression>(attributedExpr->mExpression);
  15208. customAttributes = GetCustomAttributes(attributedExpr->mAttributes, BfAttributeTargets_MemberAccess);
  15209. }
  15210. }
  15211. BfTypeInstance* targetType = NULL;
  15212. if (ctorInvocation != NULL)
  15213. {
  15214. auto targetToken = BfNodeDynCast<BfTokenNode>(ctorInvocation->mTarget);
  15215. targetType = (targetToken->GetToken() == BfToken_This) ? mCurTypeInstance : mCurTypeInstance->mBaseType;
  15216. }
  15217. else
  15218. targetType = mCurTypeInstance->mBaseType;
  15219. if ((targetType == NULL) || (targetType == mContext->mBfObjectType))
  15220. return NULL;
  15221. auto targetRefNode = methodDef->GetRefNode();
  15222. BfType* targetThisType = targetType;
  15223. BfTypedValue target(mBfIRBuilder->GetFakeVal(), targetThisType);
  15224. BfExprEvaluator exprEvaluator(this);
  15225. BfResolvedArgs argValues;
  15226. if ((ctorDeclaration != NULL) && (ctorInvocation != NULL))
  15227. {
  15228. argValues.Init(&ctorInvocation->mArguments);
  15229. }
  15230. //
  15231. {
  15232. }
  15233. BfFunctionBindResult bindResult;
  15234. bindResult.mSkipThis = true;
  15235. bindResult.mWantsArgs = true;
  15236. {
  15237. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, true);
  15238. exprEvaluator.ResolveArgValues(argValues, BfResolveArgsFlag_DeferParamEval);
  15239. SetAndRestoreValue<BfFunctionBindResult*> prevBindResult(exprEvaluator.mFunctionBindResult, &bindResult);
  15240. exprEvaluator.MatchConstructor(targetRefNode, NULL, target, targetType, argValues, true, BfMethodGenericArguments(), allowAppendKind, NULL);
  15241. }
  15242. if (bindResult.mMethodInstance == NULL)
  15243. {
  15244. AssertErrorState();
  15245. return BfTypedValue();
  15246. }
  15247. if (!bindResult.mMethodInstance->mMethodDef->HasAppend())
  15248. {
  15249. return BfTypedValue();
  15250. }
  15251. BF_ASSERT(bindResult.mIRArgs[0].IsFake());
  15252. bindResult.mIRArgs.RemoveAt(0);
  15253. auto calcAppendMethodModule = GetMethodInstanceAtIdx(bindResult.mMethodInstance->GetOwner(), bindResult.mMethodInstance->mMethodDef->mIdx + 1, BF_METHODNAME_CALCAPPEND);
  15254. BfTypedValue appendSizeTypedValue = TryConstCalcAppend(calcAppendMethodModule.mMethodInstance, bindResult.mIRArgs, true);
  15255. BF_ASSERT(calcAppendMethodModule.mMethodInstance->mAppendAllocAlign >= 0);
  15256. mCurMethodInstance->mAppendAllocAlign = BF_MAX((int)mCurMethodInstance->mAppendAllocAlign, calcAppendMethodModule.mMethodInstance->mAppendAllocAlign);
  15257. BF_ASSERT(calcAppendMethodModule.mMethodInstance->mEndingAppendAllocAlign > -1);
  15258. mCurMethodState->mCurAppendAlign = BF_MAX(calcAppendMethodModule.mMethodInstance->mEndingAppendAllocAlign, 0);
  15259. if (appendSizeTypedValue)
  15260. return appendSizeTypedValue;
  15261. if (constOnly)
  15262. return BfTypedValue(mBfIRBuilder->GetFakeVal(), GetPrimitiveType(BfTypeCode_IntPtr));
  15263. bool needsRecalc = false;
  15264. for (auto irArg : bindResult.mIRArgs)
  15265. {
  15266. if (irArg.IsFake())
  15267. needsRecalc = true;
  15268. }
  15269. auto calcAppendArgs = bindResult.mIRArgs;
  15270. if (needsRecalc)
  15271. {
  15272. // Do it again, but without mIgnoreWrites set
  15273. BfResolvedArgs argValues;
  15274. argValues.Init(&ctorInvocation->mArguments);
  15275. exprEvaluator.ResolveArgValues(argValues, BfResolveArgsFlag_DeferParamEval);
  15276. BfFunctionBindResult bindResult;
  15277. bindResult.mSkipThis = true;
  15278. bindResult.mWantsArgs = true;
  15279. SetAndRestoreValue<BfFunctionBindResult*> prevBindResult(exprEvaluator.mFunctionBindResult, &bindResult);
  15280. exprEvaluator.MatchConstructor(targetRefNode, NULL, target, targetType, argValues, true, BfMethodGenericArguments(), allowAppendKind, NULL);
  15281. BF_ASSERT(bindResult.mIRArgs[0].IsFake());
  15282. bindResult.mIRArgs.RemoveAt(0);
  15283. calcAppendArgs = bindResult.mIRArgs;
  15284. }
  15285. if (mBfIRBuilder->mIgnoreWrites)
  15286. {
  15287. appendSizeTypedValue = GetFakeTypedValue(GetPrimitiveType(BfTypeCode_IntPtr));
  15288. }
  15289. else
  15290. {
  15291. BF_ASSERT(calcAppendMethodModule.mFunc);
  15292. appendSizeTypedValue = exprEvaluator.CreateCall(NULL, calcAppendMethodModule.mMethodInstance, calcAppendMethodModule.mFunc, false, calcAppendArgs);
  15293. }
  15294. BF_ASSERT(appendSizeTypedValue.mType == GetPrimitiveType(BfTypeCode_IntPtr));
  15295. return appendSizeTypedValue;
  15296. }
  15297. // This method never throws errors - it relies on the proper ctor actually throwing the errors
  15298. void BfModule::EmitCtorCalcAppend()
  15299. {
  15300. if ((mCompiler->mIsResolveOnly) && (!mIsComptimeModule))
  15301. return;
  15302. auto methodDef = mCurMethodInstance->mMethodDef;
  15303. auto methodDecl = methodDef->GetMethodDeclaration();
  15304. Array<BfAstNode*> deferredNodeList;
  15305. auto methodDeclBlock = BfNodeDynCast<BfBlock>(methodDecl->mBody);
  15306. if (methodDeclBlock == NULL)
  15307. return;
  15308. AppendAllocVisitor appendAllocVisitor;
  15309. auto baseCalcAppend = CallBaseCtorCalc(false);
  15310. if (baseCalcAppend)
  15311. {
  15312. mBfIRBuilder->CreateStore(baseCalcAppend.mValue, mCurMethodState->mRetVal.mValue);
  15313. }
  15314. appendAllocVisitor.mModule = this;
  15315. appendAllocVisitor.VisitChild(methodDecl->mBody);
  15316. }
  15317. void BfModule::CreateStaticCtor()
  15318. {
  15319. auto typeDef = mCurTypeInstance->mTypeDef;
  15320. auto methodDef = mCurMethodInstance->mMethodDef;
  15321. BfIRBlock exitBB;
  15322. if ((HasCompiledOutput()) && (!mCurMethodInstance->mIsUnspecialized) && (mCurMethodInstance->mChainType != BfMethodChainType_ChainMember))
  15323. {
  15324. auto boolType = GetPrimitiveType(BfTypeCode_Boolean);
  15325. auto didStaticInitVarAddr = mBfIRBuilder->CreateGlobalVariable(
  15326. mBfIRBuilder->MapType(boolType),
  15327. false,
  15328. BfIRLinkageType_Internal,
  15329. GetDefaultValue(boolType),
  15330. "didStaticInit");
  15331. auto initBB = mBfIRBuilder->CreateBlock("init", true);
  15332. mCurMethodState->mIRExitBlock = mBfIRBuilder->CreateBlock("exit", true);
  15333. auto didStaticInitVar = mBfIRBuilder->CreateLoad(didStaticInitVarAddr);
  15334. mBfIRBuilder->CreateCondBr(didStaticInitVar, mCurMethodState->mIRExitBlock, initBB);
  15335. mBfIRBuilder->SetInsertPoint(initBB);
  15336. mBfIRBuilder->CreateStore(GetConstValue(1, boolType), didStaticInitVarAddr);
  15337. }
  15338. // Do DLL imports
  15339. if (!mDllImportEntries.empty())
  15340. {
  15341. auto internalType = ResolveTypeDef(mCompiler->mInternalTypeDef);
  15342. PopulateType(internalType);
  15343. auto getSharedProcAddressInstance = GetMethodByName(internalType->ToTypeInstance(), "GetSharedProcAddress");
  15344. if (!getSharedProcAddressInstance)
  15345. {
  15346. if (!mCompiler->mPassInstance->HasFailed())
  15347. Fail("Internal error: System.Internal doesn't contain LoadSharedLibrary method");
  15348. }
  15349. }
  15350. // Fill in initializer values
  15351. if ((!mCompiler->mIsResolveOnly) || (mCompiler->mResolvePassData->mAutoComplete == NULL))
  15352. {
  15353. for (auto fieldDef : typeDef->mFields)
  15354. {
  15355. if ((!fieldDef->mIsConst) && (fieldDef->mIsStatic))
  15356. {
  15357. // For extensions, only handle these fields in the appropriate extension
  15358. if ((fieldDef->mDeclaringType->mTypeDeclaration != methodDef->mDeclaringType->mTypeDeclaration))
  15359. continue;
  15360. auto initializer = fieldDef->GetInitializer();
  15361. auto fieldInst = &mCurTypeInstance->mFieldInstances[fieldDef->mIdx];
  15362. if (!fieldInst->mFieldIncluded)
  15363. continue;
  15364. if (fieldInst->mResolvedType->IsVar())
  15365. {
  15366. continue;
  15367. }
  15368. if (fieldInst->IsAppendedObject())
  15369. {
  15370. AppendedObjectInit(fieldInst);
  15371. }
  15372. else if (initializer != NULL)
  15373. {
  15374. UpdateSrcPos(initializer);
  15375. GetFieldInitializerValue(fieldInst, NULL, NULL, NULL, true);
  15376. }
  15377. }
  15378. }
  15379. auto _CheckInitBlock = [&](BfAstNode* node)
  15380. {
  15381. };
  15382. EmitInitBlocks(_CheckInitBlock);
  15383. }
  15384. else
  15385. {
  15386. for (auto tempTypeDef : mCompiler->mResolvePassData->mAutoCompleteTempTypes)
  15387. {
  15388. if (tempTypeDef->mFullName == typeDef->mFullName)
  15389. {
  15390. for (auto fieldDef : tempTypeDef->mFields)
  15391. {
  15392. if ((fieldDef->mIsStatic) && (!fieldDef->mIsConst))
  15393. {
  15394. if (fieldDef->GetInitializer() != NULL)
  15395. {
  15396. if (auto sourceClassifier = mCompiler->mResolvePassData->GetSourceClassifier(fieldDef->GetInitializer()))
  15397. {
  15398. sourceClassifier->SetElementType(fieldDef->GetInitializer(), BfSourceElementType_Normal);
  15399. sourceClassifier->VisitChildNoRef(fieldDef->GetInitializer());
  15400. }
  15401. BfType* wantType = NULL;
  15402. if ((!BfNodeIsA<BfVarTypeReference>(fieldDef->mTypeRef)) && (!BfNodeIsA<BfLetTypeReference>(fieldDef->mTypeRef)))
  15403. {
  15404. wantType = ResolveTypeRef(fieldDef->mTypeRef, BfPopulateType_Identity, BfResolveTypeRefFlag_AllowInferredSizedArray);
  15405. }
  15406. BfEvalExprFlags exprFlags = BfEvalExprFlags_FieldInitializer;
  15407. if (fieldDef->mIsAppend)
  15408. exprFlags = (BfEvalExprFlags)(exprFlags | BfEvalExprFlags_AppendFieldInitializer);
  15409. CreateValueFromExpression(fieldDef->GetInitializer(), wantType, exprFlags);
  15410. }
  15411. }
  15412. }
  15413. }
  15414. }
  15415. }
  15416. if (mCurMethodInstance->mChainType == BfMethodChainType_ChainHead)
  15417. CallChainedMethods(mCurMethodInstance, false);
  15418. }
  15419. void BfModule::EmitDtorBody()
  15420. {
  15421. if (!mCurMethodState->mIRExitBlock)
  15422. mCurMethodState->mIRExitBlock = mBfIRBuilder->CreateBlock("exit", true);
  15423. if (mCurTypeInstance->IsClosure())
  15424. {
  15425. BfFieldInstance* fieldInstance = &mCurTypeInstance->mFieldInstances.back();
  15426. BF_ASSERT(fieldInstance->GetFieldDef()->mName == "__dtorThunk");
  15427. auto thisVal = GetThis();
  15428. auto dtorThunkPtr = mBfIRBuilder->CreateInBoundsGEP(thisVal.mValue, 0, fieldInstance->mDataIdx);
  15429. auto dtorThunk = mBfIRBuilder->CreateLoad(dtorThunkPtr);
  15430. auto funcPtrType = mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapMethod(mCurMethodInstance));
  15431. auto dtorPtr = mBfIRBuilder->CreateBitCast(dtorThunk, funcPtrType);
  15432. SizedArray<BfIRValue, 1> args;
  15433. args.push_back(thisVal.mValue);
  15434. auto result = mBfIRBuilder->CreateCall(dtorPtr, args);
  15435. mBfIRBuilder->SetCallCallingConv(result, BfIRCallingConv_CDecl);
  15436. // Fall through to Object::~this call
  15437. auto dtorFunc = GetMethodByName(mContext->mBfObjectType, "~this");
  15438. if (mIsComptimeModule)
  15439. mCompiler->mCeMachine->QueueMethod(dtorFunc.mMethodInstance, dtorFunc.mFunc);
  15440. auto basePtr = mBfIRBuilder->CreateBitCast(thisVal.mValue, mBfIRBuilder->MapTypeInstPtr(mContext->mBfObjectType));
  15441. SizedArray<BfIRValue, 1> vals = { basePtr };
  15442. result = mBfIRBuilder->CreateCall(dtorFunc.mFunc, vals);
  15443. mBfIRBuilder->SetCallCallingConv(result, GetIRCallingConvention(dtorFunc.mMethodInstance));
  15444. mBfIRBuilder->SetTailCall(result);
  15445. return;
  15446. }
  15447. auto typeDef = mCurTypeInstance->mTypeDef;
  15448. auto methodDef = mCurMethodInstance->mMethodDef;
  15449. auto methodDeclaration = methodDef->GetMethodDeclaration();
  15450. if (mCurMethodInstance->mChainType == BfMethodChainType_ChainHead)
  15451. CallChainedMethods(mCurMethodInstance, true);
  15452. if (auto bodyBlock = BfNodeDynCast<BfBlock>(methodDef->mBody))
  15453. {
  15454. VisitEmbeddedStatement(bodyBlock);
  15455. if (bodyBlock->mCloseBrace != NULL)
  15456. {
  15457. UpdateSrcPos(bodyBlock->mCloseBrace);
  15458. }
  15459. }
  15460. else
  15461. {
  15462. if (methodDeclaration != NULL)
  15463. UpdateSrcPos(methodDeclaration);
  15464. else if ((methodDef->mDeclaringType != NULL) && (methodDef->mDeclaringType->GetRefNode() != NULL))
  15465. UpdateSrcPos(methodDef->mDeclaringType->GetRefNode());
  15466. else if (typeDef->mTypeDeclaration != NULL)
  15467. UpdateSrcPos(typeDef->mTypeDeclaration);
  15468. if ((methodDeclaration != NULL) && (methodDeclaration->mFatArrowToken != NULL))
  15469. {
  15470. Fail("Destructors cannot have expression bodies", methodDeclaration->mFatArrowToken, true);
  15471. }
  15472. }
  15473. if ((!mCompiler->mIsResolveOnly) || (mCompiler->mResolvePassData->mAutoComplete == NULL))
  15474. {
  15475. for (int fieldIdx = (int)mCurTypeInstance->mFieldInstances.size() - 1; fieldIdx >= 0; fieldIdx--)
  15476. {
  15477. auto fieldInst = &mCurTypeInstance->mFieldInstances[fieldIdx];
  15478. auto fieldDef = fieldInst->GetFieldDef();
  15479. BfFieldDeclaration* fieldDecl = NULL;
  15480. if (fieldDef != NULL)
  15481. fieldDecl = fieldDef->GetFieldDeclaration();
  15482. if ((fieldDef != NULL) && (fieldDef->mIsStatic == methodDef->mIsStatic) && (fieldDecl != NULL) && (fieldDecl->mFieldDtor != NULL))
  15483. {
  15484. if (fieldDef->mDeclaringType != mCurMethodInstance->mMethodDef->mDeclaringType)
  15485. {
  15486. BF_ASSERT(mCurTypeInstance->mTypeDef->mIsCombinedPartial);
  15487. continue;
  15488. }
  15489. if ((!methodDef->mIsStatic) && (mCurTypeInstance->IsValueType()))
  15490. {
  15491. Fail("Structs cannot have field destructors", fieldDecl->mFieldDtor->mTildeToken, true);
  15492. }
  15493. SetAndRestoreValue<BfFilePosition> prevFilePos(mCurFilePosition);
  15494. auto fieldDtor = fieldDecl->mFieldDtor;
  15495. if ((fieldDef->mIsStatic) != (methodDef->mIsStatic))
  15496. continue;
  15497. UpdateSrcPos(fieldDtor);
  15498. BfScopeData scopeData;
  15499. mCurMethodState->AddScope(&scopeData);
  15500. NewScopeState();
  15501. UpdateSrcPos(fieldDtor);
  15502. bool hasDbgInfo = (!fieldDef->mIsConst);
  15503. if (hasDbgInfo)
  15504. {
  15505. mBfIRBuilder->SaveDebugLocation();
  15506. mBfIRBuilder->ClearDebugLocation();
  15507. }
  15508. BfIRValue value;
  15509. if (fieldDef->mIsStatic)
  15510. {
  15511. value = ReferenceStaticField(fieldInst).mValue;
  15512. }
  15513. else
  15514. {
  15515. PopulateType(fieldInst->mResolvedType);
  15516. if (fieldInst->mResolvedType->IsValuelessType())
  15517. {
  15518. value = mBfIRBuilder->GetFakeVal();
  15519. }
  15520. else if (!mCurTypeInstance->IsValueType())
  15521. {
  15522. auto thisValue = GetThis();
  15523. value = mBfIRBuilder->CreateInBoundsGEP(thisValue.mValue, 0, fieldInst->mDataIdx);
  15524. }
  15525. else
  15526. {
  15527. AssertErrorState();
  15528. value = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(fieldInst->mResolvedType));
  15529. }
  15530. }
  15531. BfIRValue staticVal;
  15532. if (hasDbgInfo)
  15533. {
  15534. BfIRValue dbgShowValue = value;
  15535. BfLocalVariable* localDef = new BfLocalVariable();
  15536. localDef->mName = "_";
  15537. localDef->mResolvedType = fieldInst->mResolvedType;
  15538. if ((fieldInst->IsAppendedObject()) && (!fieldDef->mIsStatic))
  15539. {
  15540. localDef->mValue = mBfIRBuilder->CreateBitCast(value, mBfIRBuilder->MapType(fieldInst->mResolvedType));
  15541. }
  15542. else
  15543. {
  15544. localDef->mAddr = value;
  15545. if ((mBfIRBuilder->DbgHasInfo()) && (!IsTargetingBeefBackend()))
  15546. {
  15547. // Create another pointer indirection, a ref to the gep
  15548. auto refFieldType = CreateRefType(fieldInst->mResolvedType);
  15549. auto allocaInst = CreateAlloca(refFieldType);
  15550. auto storeResult = mBfIRBuilder->CreateStore(value, allocaInst);
  15551. localDef->mResolvedType = refFieldType;
  15552. localDef->mAddr = allocaInst;
  15553. }
  15554. }
  15555. mBfIRBuilder->RestoreDebugLocation();
  15556. auto defLocalVar = AddLocalVariableDef(localDef, true);
  15557. if ((!fieldInst->IsAppendedObject()) && (!fieldDef->mIsStatic))
  15558. {
  15559. // Put back so we actually modify the correct value*/
  15560. defLocalVar->mResolvedType = fieldInst->mResolvedType;
  15561. defLocalVar->mAddr = value;
  15562. }
  15563. }
  15564. while (fieldDtor != NULL)
  15565. {
  15566. if (mCompiler->mResolvePassData != NULL)
  15567. {
  15568. if (auto sourceClassifier = mCompiler->mResolvePassData->GetSourceClassifier(fieldDtor))
  15569. {
  15570. sourceClassifier->SetElementType(fieldDtor, BfSourceElementType_Normal);
  15571. sourceClassifier->VisitChild(fieldDtor);
  15572. }
  15573. }
  15574. UpdateSrcPos(fieldDtor);
  15575. VisitEmbeddedStatement(fieldDtor->mBody);
  15576. fieldDtor = fieldDtor->mNextFieldDtor;
  15577. }
  15578. RestoreScopeState();
  15579. }
  15580. if ((fieldDef != NULL) && (fieldDef->mIsStatic == methodDef->mIsStatic) && (fieldInst->IsAppendedObject()))
  15581. {
  15582. if (fieldDef->mDeclaringType != mCurMethodInstance->mMethodDef->mDeclaringType)
  15583. {
  15584. BF_ASSERT(mCurTypeInstance->mTypeDef->mIsCombinedPartial);
  15585. continue;
  15586. }
  15587. auto refNode = fieldDef->GetRefNode();
  15588. UpdateSrcPos(refNode);
  15589. auto objectType = mContext->mBfObjectType;
  15590. BfTypeInstance* checkTypeInst = mCurTypeInstance->ToTypeInstance();
  15591. BfTypedValue val;
  15592. if (fieldDef->mIsStatic)
  15593. {
  15594. val = ReferenceStaticField(fieldInst);
  15595. val = LoadValue(val);
  15596. }
  15597. else
  15598. {
  15599. auto fieldAddr = mBfIRBuilder->CreateInBoundsGEP(mCurMethodState->mLocals[0]->mValue, 0, fieldInst->mDataIdx);
  15600. val = BfTypedValue(mBfIRBuilder->CreateBitCast(fieldAddr, mBfIRBuilder->MapType(fieldInst->mResolvedType)), fieldInst->mResolvedType);
  15601. }
  15602. bool allowPrivate = checkTypeInst == mCurTypeInstance;
  15603. bool allowProtected = allowPrivate || TypeIsSubTypeOf(mCurTypeInstance, checkTypeInst);
  15604. while (checkTypeInst != NULL)
  15605. {
  15606. auto dtorMethodDef = checkTypeInst->mTypeDef->GetMethodByName("~this");
  15607. if (dtorMethodDef)
  15608. {
  15609. if (!CheckProtection(dtorMethodDef->mProtection, checkTypeInst->mTypeDef, allowProtected, allowPrivate))
  15610. {
  15611. auto error = Fail(StrFormat("'%s.~this()' is inaccessible due to its protection level", TypeToString(checkTypeInst).c_str()), refNode); // CS0122
  15612. }
  15613. }
  15614. checkTypeInst = checkTypeInst->mBaseType;
  15615. allowPrivate = false;
  15616. }
  15617. // call dtor
  15618. BfExprEvaluator expressionEvaluator(this);
  15619. PopulateType(val.mType);
  15620. PopulateType(objectType, BfPopulateType_DataAndMethods);
  15621. EmitObjectAccessCheck(val);
  15622. if (objectType->mVirtualMethodTable.size() == 0)
  15623. {
  15624. if (!mCompiler->IsAutocomplete())
  15625. AssertErrorState();
  15626. }
  15627. else if (!IsSkippingExtraResolveChecks())
  15628. {
  15629. BfMethodInstance* methodInstance = objectType->mVirtualMethodTable[mCompiler->GetVTableMethodOffset() + 0].mImplementingMethod;
  15630. BF_ASSERT(methodInstance->mMethodDef->mName == "~this");
  15631. SizedArray<BfIRValue, 4> llvmArgs;
  15632. llvmArgs.push_back(mBfIRBuilder->CreateBitCast(val.mValue, mBfIRBuilder->MapType(objectType)));
  15633. expressionEvaluator.CreateCall(refNode, methodInstance, mBfIRBuilder->GetFakeVal(), false, llvmArgs);
  15634. }
  15635. if ((mCompiler->mOptions.mObjectHasDebugFlags) && (!mIsComptimeModule))
  15636. {
  15637. auto int8PtrType = CreatePointerType(GetPrimitiveType(BfTypeCode_Int8));
  15638. auto int8PtrVal = mBfIRBuilder->CreateBitCast(val.mValue, mBfIRBuilder->MapType(int8PtrType));
  15639. mBfIRBuilder->CreateStore(GetConstValue8(BfObjectFlag_Deleted), int8PtrVal);
  15640. }
  15641. }
  15642. }
  15643. if ((!methodDef->mIsStatic) && (mCurMethodInstance->mChainType != BfMethodChainType_ChainMember))
  15644. {
  15645. auto checkBaseType = mCurTypeInstance->mBaseType;
  15646. while (checkBaseType != NULL)
  15647. {
  15648. if (auto bodyBlock = BfNodeDynCast<BfBlock>(methodDef->mBody))
  15649. {
  15650. if (bodyBlock->mCloseBrace != NULL)
  15651. UpdateSrcPos(bodyBlock->mCloseBrace);
  15652. }
  15653. else
  15654. {
  15655. UpdateSrcPos(typeDef->mTypeDeclaration->mNameNode);
  15656. }
  15657. BfMethodDef* dtorMethodDef = checkBaseType->mTypeDef->GetMethodByName("~this");
  15658. if (dtorMethodDef != NULL)
  15659. {
  15660. auto dtorMethodInstance = GetMethodInstance(checkBaseType, dtorMethodDef, BfTypeVector());
  15661. if (IsSkippingExtraResolveChecks())
  15662. {
  15663. // Nothing
  15664. }
  15665. else if (dtorMethodInstance.mMethodInstance->GetParamCount() == 0)
  15666. {
  15667. if ((!IsSkippingExtraResolveChecks()) && (!checkBaseType->IsUnspecializedType()))
  15668. {
  15669. auto basePtr = mBfIRBuilder->CreateBitCast(mCurMethodState->mLocals[0]->mValue, mBfIRBuilder->MapTypeInstPtr(checkBaseType));
  15670. SizedArray<BfIRValue, 1> vals = { basePtr };
  15671. auto callInst = mBfIRBuilder->CreateCall(dtorMethodInstance.mFunc, vals);
  15672. if (mIsComptimeModule)
  15673. mCompiler->mCeMachine->QueueMethod(dtorMethodInstance.mMethodInstance, dtorMethodInstance.mFunc);
  15674. mBfIRBuilder->SetCallCallingConv(callInst, GetIRCallingConvention(dtorMethodInstance.mMethodInstance));
  15675. }
  15676. }
  15677. else
  15678. {
  15679. // Invalid base dtor declaration
  15680. AssertErrorState();
  15681. }
  15682. break;
  15683. }
  15684. checkBaseType = checkBaseType->mBaseType;
  15685. }
  15686. }
  15687. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  15688. }
  15689. else
  15690. {
  15691. // The reason we can't just do the 'normal' path for this is that the BfTypeInstance here is NOT the
  15692. // autocomplete type instance, so FieldInstance initializer values contain expressions from the full
  15693. // resolve pass, NOT the autocomplete expression
  15694. for (auto tempTypeDef : mCompiler->mResolvePassData->mAutoCompleteTempTypes)
  15695. {
  15696. if (tempTypeDef->mFullName == typeDef->mFullName)
  15697. {
  15698. for (auto fieldDef : tempTypeDef->mFields)
  15699. {
  15700. auto fieldDecl = fieldDef->GetFieldDeclaration();
  15701. if ((fieldDef->mIsStatic == methodDef->mIsStatic) && (fieldDef->mFieldDeclaration != NULL) &&
  15702. (fieldDecl->mFieldDtor != NULL) && (mCompiler->mResolvePassData->mIsClassifying))
  15703. {
  15704. BfType* fieldType = NULL;
  15705. for (int curFieldIdx = 0; curFieldIdx < (int)mCurTypeInstance->mFieldInstances.size(); curFieldIdx++)
  15706. {
  15707. auto curFieldInstance = &mCurTypeInstance->mFieldInstances[curFieldIdx];
  15708. auto curFieldDef = curFieldInstance->GetFieldDef();
  15709. if ((curFieldDef != NULL) && (fieldDef->mName == curFieldDef->mName))
  15710. fieldType = curFieldInstance->GetResolvedType();
  15711. }
  15712. if (fieldType == NULL)
  15713. fieldType = GetPrimitiveType(BfTypeCode_Var);
  15714. auto fieldDtor = fieldDecl->mFieldDtor;
  15715. BfScopeData scopeData;
  15716. mCurMethodState->AddScope(&scopeData);
  15717. NewScopeState();
  15718. // This is just for autocomplete, it doesn't matter that mAddr is incorrect
  15719. if (fieldType != NULL)
  15720. {
  15721. BfLocalVariable* localDef = new BfLocalVariable();
  15722. localDef->mName = "_";
  15723. localDef->mResolvedType = fieldType;
  15724. localDef->mAddr = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(fieldType));
  15725. localDef->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  15726. AddLocalVariableDef(localDef);
  15727. }
  15728. while (fieldDtor != NULL)
  15729. {
  15730. if (auto sourceClassifier = mCompiler->mResolvePassData->GetSourceClassifier(fieldDtor))
  15731. {
  15732. sourceClassifier->SetElementType(fieldDtor, BfSourceElementType_Normal);
  15733. sourceClassifier->VisitChild(fieldDtor);
  15734. }
  15735. UpdateSrcPos(fieldDtor);
  15736. VisitEmbeddedStatement(fieldDtor->mBody);
  15737. fieldDtor = fieldDtor->mNextFieldDtor;
  15738. }
  15739. RestoreScopeState();
  15740. }
  15741. }
  15742. }
  15743. }
  15744. }
  15745. // If there are appends then we just need the rootmost append type to do the Dbg_AppendDeleted
  15746. if ((!mIsComptimeModule) && (!methodDef->mIsStatic) && (mCompiler->mOptions.mDebugAlloc) &&
  15747. (mCurTypeInstance->HasAppendCtor()) && (!mCurTypeInstance->BaseHasAppendCtor()))
  15748. {
  15749. auto thisValue = GetThis();
  15750. auto appendedObj = mBfIRBuilder->CreateBitCast(thisValue.mValue, mBfIRBuilder->MapType(mContext->mBfObjectType));
  15751. BfModuleMethodInstance allocMethod = GetInternalMethod("Dbg_AppendDeleted", 2);
  15752. SizedArray<BfIRValue, 1> llvmArgs;
  15753. llvmArgs.Add(appendedObj);
  15754. llvmArgs.Add(mBfIRBuilder->CreateConst(BfTypeCode_Boolean, mCurMethodState->mDisableChecks ? 0 : 1));
  15755. if (allocMethod)
  15756. mBfIRBuilder->CreateCall(allocMethod.mFunc, llvmArgs);
  15757. }
  15758. }
  15759. BfIRValue BfModule::CreateDllImportGlobalVar(BfMethodInstance* methodInstance, bool define)
  15760. {
  15761. BF_ASSERT(methodInstance->mIsReified);
  15762. auto typeInstance = methodInstance->GetOwner();
  15763. bool foundDllImportAttr = false;
  15764. BfCallingConvention callingConvention = methodInstance->mCallingConvention;
  15765. for (auto customAttr : methodInstance->GetCustomAttributes()->mAttributes)
  15766. {
  15767. if (customAttr.mType->mTypeDef->mFullName.ToString() == "System.ImportAttribute")
  15768. {
  15769. foundDllImportAttr = true;
  15770. }
  15771. }
  15772. if (!foundDllImportAttr)
  15773. {
  15774. AssertErrorState();
  15775. return BfIRValue();
  15776. }
  15777. StringT<512> name = "bf_hs_preserve@";
  15778. BfMangler::Mangle(name, mCompiler->GetMangleKind(), methodInstance);
  15779. name += "__imp";
  15780. BfIRType returnType;
  15781. SizedArray<BfIRType, 8> paramTypes;
  15782. methodInstance->GetIRFunctionInfo(this, returnType, paramTypes);
  15783. BfIRFunctionType externFunctionType = mBfIRBuilder->CreateFunctionType(returnType, paramTypes, methodInstance->IsVarArgs());
  15784. auto ptrType = mBfIRBuilder->GetPointerTo(externFunctionType);
  15785. BfIRValue initVal;
  15786. if (define)
  15787. {
  15788. if (methodInstance->GetImportCallKind() != BfImportCallKind_None)
  15789. initVal = mBfIRBuilder->CreateConstNull(ptrType);
  15790. }
  15791. auto globalVar = mBfIRBuilder->CreateGlobalVariable(ptrType, false, BfIRLinkageType_External, initVal, name);
  15792. if ((define) && (mBfIRBuilder->DbgHasInfo()))
  15793. {
  15794. auto voidType = GetPrimitiveType(BfTypeCode_None);
  15795. auto ptrType = CreatePointerType(voidType);
  15796. mBfIRBuilder->DbgCreateGlobalVariable(mDICompileUnit, name, name, BfIRMDNode(), 0, mBfIRBuilder->DbgGetType(ptrType), false, globalVar);
  15797. }
  15798. return globalVar;
  15799. }
  15800. void BfModule::CreateDllImportMethod()
  15801. {
  15802. if (mBfIRBuilder->mIgnoreWrites)
  15803. return;
  15804. auto globalVar = mFuncReferences[mCurMethodInstance];
  15805. if (!globalVar)
  15806. return;
  15807. bool allowTailCall = true;
  15808. mBfIRBuilder->ClearDebugLocation();
  15809. bool isHotCompile = mCompiler->IsHotCompile();
  15810. // If we are hot swapping, we need to have this stub because we may need to call the LoadSharedLibraries on demand
  15811. if (isHotCompile)
  15812. {
  15813. auto loadSharedLibsFunc = GetBuiltInFunc(BfBuiltInFuncType_LoadSharedLibraries);
  15814. mBfIRBuilder->CreateCall(loadSharedLibsFunc, SizedArray<BfIRValue, 0>());
  15815. }
  15816. auto callingConvention = GetIRCallingConvention(mCurMethodInstance);
  15817. BfIRType returnType;
  15818. SizedArray<BfIRType, 8> paramTypes;
  15819. mCurMethodInstance->GetIRFunctionInfo(this, returnType, paramTypes, mCurMethodInstance->IsVarArgs());
  15820. SizedArray<BfIRValue, 8> args;
  15821. for (int i = 0; i < (int)paramTypes.size(); i++)
  15822. args.push_back(mBfIRBuilder->GetArgument(i));
  15823. BfIRFunctionType externFunctionType = mBfIRBuilder->CreateFunctionType(returnType, paramTypes, mCurMethodInstance->IsVarArgs());
  15824. if (isHotCompile)
  15825. {
  15826. BfIRValue funcVal = mBfIRBuilder->CreateLoad(globalVar);
  15827. auto result = mBfIRBuilder->CreateCall(funcVal, args);
  15828. if (callingConvention == BfIRCallingConv_StdCall)
  15829. mBfIRBuilder->SetCallCallingConv(result, BfIRCallingConv_StdCall);
  15830. else if (callingConvention == BfIRCallingConv_FastCall)
  15831. mBfIRBuilder->SetCallCallingConv(result, BfIRCallingConv_FastCall);
  15832. else
  15833. mBfIRBuilder->SetCallCallingConv(result, BfIRCallingConv_CDecl);
  15834. if (allowTailCall)
  15835. mBfIRBuilder->SetTailCall(result);
  15836. CreateReturn(result);
  15837. mCurMethodState->mHadReturn = true;
  15838. }
  15839. if (HasCompiledOutput())
  15840. {
  15841. BfDllImportEntry dllImportEntry;
  15842. dllImportEntry.mFuncVar = globalVar;
  15843. dllImportEntry.mMethodInstance = mCurMethodInstance;
  15844. mDllImportEntries.push_back(dllImportEntry);
  15845. }
  15846. }
  15847. BfIRCallingConv BfModule::GetIRCallingConvention(BfMethodInstance* methodInstance)
  15848. {
  15849. auto methodDef = methodInstance->mMethodDef;
  15850. BfTypeInstance* owner = NULL;
  15851. if (!methodDef->mIsStatic)
  15852. owner = methodInstance->GetThisType()->ToTypeInstance();
  15853. if (owner == NULL)
  15854. owner = methodInstance->GetOwner();
  15855. if ((mCompiler->mOptions.mMachineType != BfMachineType_x86) || (mCompiler->mOptions.mPlatformType != BfPlatformType_Windows))
  15856. return BfIRCallingConv_CDecl;
  15857. if (methodInstance->mCallingConvention == BfCallingConvention_Stdcall)
  15858. return BfIRCallingConv_StdCall;
  15859. if (methodInstance->mCallingConvention == BfCallingConvention_Fastcall)
  15860. return BfIRCallingConv_FastCall;
  15861. if (!methodDef->mIsStatic)
  15862. {
  15863. if (owner->mIsCRepr)
  15864. return BfIRCallingConv_ThisCall;
  15865. if ((!owner->IsValuelessType()) &&
  15866. ((!owner->IsSplattable()) || (methodDef->HasNoThisSplat())))
  15867. return BfIRCallingConv_ThisCall;
  15868. }
  15869. return BfIRCallingConv_CDecl;
  15870. //return GetIRCallingConvention(owner, methodInstance->mMethodDef);
  15871. }
  15872. void BfModule::SetupIRMethod(BfMethodInstance* methodInstance, BfIRFunction func, bool isInlined)
  15873. {
  15874. BfMethodDef* methodDef = NULL;
  15875. if (methodInstance != NULL)
  15876. methodDef = methodInstance->mMethodDef;
  15877. if (!func)
  15878. return;
  15879. if (mCompiler->mOptions.mNoFramePointerElim)
  15880. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_NoFramePointerElim);
  15881. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_NoUnwind);
  15882. if (mSystem->mPtrSize == 8) // We need unwind info for debugging
  15883. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_UWTable);
  15884. if (methodInstance == NULL)
  15885. return;
  15886. if (methodInstance->mReturnType->IsVar())
  15887. mBfIRBuilder->Func_AddAttribute(func, -1, BfIRAttribute_VarRet);
  15888. if (methodDef->mImportKind == BfImportKind_Export)
  15889. {
  15890. if (methodDef->mDeclaringType->mProject->mTargetType != BfTargetType_BeefLib_StaticLib)
  15891. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_DllExport);
  15892. }
  15893. if (methodDef->mIsNoReturn)
  15894. mBfIRBuilder->Func_AddAttribute(func, -1, BfIRAttribute_NoReturn);
  15895. auto callingConv = GetIRCallingConvention(methodInstance);
  15896. if (callingConv != BfIRCallingConv_CDecl)
  15897. mBfIRBuilder->SetFuncCallingConv(func, callingConv);
  15898. if (isInlined)
  15899. {
  15900. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_AlwaysInline);
  15901. }
  15902. int argIdx = 0;
  15903. int paramIdx = 0;
  15904. if ((methodInstance->HasThis()) && (!methodDef->mHasExplicitThis))
  15905. paramIdx = -1;
  15906. int argCount = methodInstance->GetIRFunctionParamCount(this);
  15907. while (argIdx < argCount)
  15908. {
  15909. if ((!mIsComptimeModule) && (argIdx == methodInstance->GetStructRetIdx()))
  15910. {
  15911. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_NoAlias);
  15912. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_StructRet);
  15913. argIdx++;
  15914. continue;
  15915. }
  15916. bool isThis = (paramIdx == -1) || ((methodDef->mHasExplicitThis) && (paramIdx == 0));
  15917. while ((!isThis) && (methodInstance->IsParamSkipped(paramIdx)))
  15918. paramIdx++;
  15919. BfType* resolvedTypeRef = NULL;
  15920. BfType* resolvedTypeRef2 = NULL;
  15921. String paramName;
  15922. bool isSplattable = false;
  15923. bool tryLowering = !mIsComptimeModule;
  15924. if (isThis)
  15925. {
  15926. paramName = "this";
  15927. if (methodInstance->mIsClosure)
  15928. resolvedTypeRef = mCurMethodState->mClosureState->mClosureType;
  15929. else
  15930. resolvedTypeRef = methodInstance->GetThisType();
  15931. isSplattable = (!mIsComptimeModule) && (resolvedTypeRef->IsSplattable()) && (methodInstance->AllowsSplatting(-1));
  15932. tryLowering = (!mIsComptimeModule) && (methodInstance->AllowsSplatting(-1));
  15933. }
  15934. else
  15935. {
  15936. paramName = methodInstance->GetParamName(paramIdx);
  15937. resolvedTypeRef = methodInstance->GetParamType(paramIdx);
  15938. if (resolvedTypeRef->IsMethodRef())
  15939. isSplattable = true;
  15940. else if ((!mIsComptimeModule) && (resolvedTypeRef->IsSplattable()) && (methodInstance->AllowsSplatting(paramIdx)))
  15941. {
  15942. auto resolvedTypeInst = resolvedTypeRef->ToTypeInstance();
  15943. if ((resolvedTypeInst != NULL) && (resolvedTypeInst->mIsCRepr))
  15944. {
  15945. // crepr splat is always splattable
  15946. isSplattable = true;
  15947. }
  15948. else
  15949. {
  15950. auto resolvedTypeInst = resolvedTypeRef->ToTypeInstance();
  15951. if ((resolvedTypeInst != NULL) && (resolvedTypeInst->mIsCRepr))
  15952. isSplattable = true;
  15953. else if (resolvedTypeRef->GetSplatCount() + argIdx <= mCompiler->mOptions.mMaxSplatRegs)
  15954. isSplattable = true;
  15955. }
  15956. }
  15957. }
  15958. if (tryLowering)
  15959. {
  15960. BfTypeCode loweredTypeCode = BfTypeCode_None;
  15961. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  15962. if (resolvedTypeRef->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2))
  15963. {
  15964. mBfIRBuilder->Func_SetParamName(func, argIdx + 1, paramName + "__1");
  15965. argIdx++;
  15966. if (loweredTypeCode2 != BfTypeCode_None)
  15967. {
  15968. mBfIRBuilder->Func_SetParamName(func, argIdx + 1, paramName + "__2");
  15969. argIdx++;
  15970. }
  15971. paramIdx++;
  15972. continue;
  15973. }
  15974. }
  15975. auto _SetupParam = [&](const StringImpl& paramName, BfType* resolvedTypeRef)
  15976. {
  15977. mBfIRBuilder->Func_SetParamName(func, argIdx + 1, paramName);
  15978. int addDeref = -1;
  15979. if (resolvedTypeRef->IsRef())
  15980. {
  15981. auto refType = (BfRefType*)resolvedTypeRef;
  15982. auto elementType = refType->mElementType;
  15983. PopulateType(elementType, BfPopulateType_Data);
  15984. addDeref = elementType->mSize;
  15985. if ((addDeref <= 0) && (!elementType->IsValuelessType()) && (!elementType->IsOpaque()))
  15986. AssertErrorState();
  15987. }
  15988. if ((resolvedTypeRef->IsComposite()) && (!resolvedTypeRef->IsTypedPrimitive()))
  15989. {
  15990. if (isThis)
  15991. {
  15992. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_NoCapture);
  15993. PopulateType(resolvedTypeRef, BfPopulateType_Data);
  15994. addDeref = resolvedTypeRef->mSize;
  15995. }
  15996. else if (methodInstance->WantsStructsAttribByVal(resolvedTypeRef))
  15997. {
  15998. mBfIRBuilder->PopulateType(resolvedTypeRef, BfIRPopulateType_Full);
  15999. BF_ASSERT(resolvedTypeRef->mAlign > 0);
  16000. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_ByVal, mSystem->mPtrSize);
  16001. }
  16002. }
  16003. else if (resolvedTypeRef->IsPrimitiveType())
  16004. {
  16005. auto primType = (BfPrimitiveType*)resolvedTypeRef;
  16006. if (primType->mTypeDef->mTypeCode == BfTypeCode_Boolean)
  16007. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_ZExt);
  16008. }
  16009. if (addDeref >= 0)
  16010. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_Dereferencable, addDeref);
  16011. argIdx++;
  16012. };
  16013. if (isSplattable)
  16014. {
  16015. std::function<void(BfType*, const StringImpl&)> checkTypeLambda = [&](BfType* checkType, const StringImpl& curName)
  16016. {
  16017. if (checkType->IsStruct())
  16018. {
  16019. auto checkTypeInstance = checkType->ToTypeInstance();
  16020. if (checkTypeInstance->mBaseType != NULL)
  16021. checkTypeLambda(checkTypeInstance->mBaseType, curName);
  16022. if (checkTypeInstance->mIsUnion)
  16023. {
  16024. BfType* unionInnerType = checkTypeInstance->GetUnionInnerType();
  16025. checkTypeLambda(unionInnerType, curName + "_data");
  16026. }
  16027. else
  16028. {
  16029. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  16030. {
  16031. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  16032. auto fieldDef = fieldInstance->GetFieldDef();
  16033. if (fieldInstance->mDataIdx >= 0)
  16034. {
  16035. checkTypeLambda(fieldInstance->GetResolvedType(), curName + "_" + fieldInstance->GetFieldDef()->mName);
  16036. }
  16037. }
  16038. }
  16039. if (checkTypeInstance->IsEnum())
  16040. {
  16041. mBfIRBuilder->Func_SetParamName(func, argIdx + 1, curName + "_dscr");
  16042. argIdx++;
  16043. }
  16044. }
  16045. else if (checkType->IsMethodRef())
  16046. {
  16047. auto methodRefType = (BfMethodRefType*)checkType;
  16048. BfMethodInstance* methodRefMethodInst = methodRefType->mMethodRef;
  16049. for (int dataIdx = 0; dataIdx < (int)methodRefType->GetCaptureDataCount(); dataIdx++)
  16050. {
  16051. int methodRefParamIdx = methodRefType->GetParamIdxFromDataIdx(dataIdx);
  16052. if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  16053. {
  16054. checkTypeLambda(methodRefType->GetCaptureType(dataIdx), curName + "_" + methodRefMethodInst->GetParamName(methodRefParamIdx));
  16055. }
  16056. else
  16057. {
  16058. _SetupParam(curName + "_" + methodRefMethodInst->GetParamName(methodRefParamIdx), methodRefType->GetCaptureType(dataIdx));
  16059. }
  16060. }
  16061. }
  16062. else if (!checkType->IsValuelessType())
  16063. {
  16064. _SetupParam(curName, checkType);
  16065. }
  16066. };
  16067. checkTypeLambda(resolvedTypeRef, paramName);
  16068. paramIdx++;
  16069. continue;
  16070. }
  16071. _SetupParam(paramName, resolvedTypeRef);
  16072. if (resolvedTypeRef2 != NULL)
  16073. _SetupParam(paramName, resolvedTypeRef2);
  16074. paramIdx++;
  16075. }
  16076. }
  16077. void BfModule::EmitInitBlocks(const std::function<void(BfAstNode*)>& initBlockCallback)
  16078. {
  16079. auto methodDef = mCurMethodInstance->mMethodDef;
  16080. mCurTypeInstance->mTypeDef->PopulateMemberSets();
  16081. BfMemberSetEntry* entry = NULL;
  16082. BfMethodDef* initMethodDef = NULL;
  16083. mCurTypeInstance->mTypeDef->mMethodSet.TryGetWith(String("__BfInit"), &entry);
  16084. if (entry != NULL)
  16085. initMethodDef = (BfMethodDef*)entry->mMemberDef;
  16086. SizedArray<BfAstNode*, 8> initBodies;
  16087. for (; initMethodDef != NULL; initMethodDef = initMethodDef->mNextWithSameName)
  16088. {
  16089. if (initMethodDef->mDeclaringType->GetDefinition() != methodDef->mDeclaringType->GetDefinition())
  16090. continue;
  16091. if (initMethodDef->mMethodType != BfMethodType_Init)
  16092. continue;
  16093. if (initMethodDef->mIsStatic != methodDef->mIsStatic)
  16094. continue;
  16095. initBodies.Insert(0, initMethodDef->mBody);
  16096. }
  16097. for (auto body : initBodies)
  16098. {
  16099. initBlockCallback(body);
  16100. VisitEmbeddedStatement(body);
  16101. }
  16102. }
  16103. void BfModule::EmitCtorBody(bool& skipBody)
  16104. {
  16105. auto methodInstance = mCurMethodInstance;
  16106. auto methodDef = methodInstance->mMethodDef;
  16107. auto methodDeclaration = methodDef->mMethodDeclaration;
  16108. auto ctorDeclaration = (BfConstructorDeclaration*)methodDef->mMethodDeclaration;
  16109. auto typeDef = mCurTypeInstance->mTypeDef;
  16110. BfCustomAttributes* customAttributes = NULL;
  16111. defer(delete customAttributes);
  16112. BfInvocationExpression* ctorInvocation = NULL;
  16113. BfAttributeState attributeState;
  16114. attributeState.mTarget = BfAttributeTargets_MemberAccess;
  16115. if (ctorDeclaration != NULL)
  16116. {
  16117. ctorInvocation = BfNodeDynCast<BfInvocationExpression>(ctorDeclaration->mInitializer);
  16118. if (auto attributedExpr = BfNodeDynCast<BfAttributedExpression>(ctorDeclaration->mInitializer))
  16119. {
  16120. ctorInvocation = BfNodeDynCast<BfInvocationExpression>(attributedExpr->mExpression);
  16121. attributeState.mCustomAttributes = GetCustomAttributes(attributedExpr->mAttributes, attributeState.mTarget);
  16122. }
  16123. }
  16124. SetAndRestoreValue<BfAttributeState*> prevAttributeState(mAttributeState, &attributeState);
  16125. // Prologue
  16126. mBfIRBuilder->ClearDebugLocation();
  16127. bool hadThisInitializer = false;
  16128. if ((ctorDeclaration != NULL) && (ctorInvocation != NULL))
  16129. {
  16130. auto targetToken = BfNodeDynCast<BfTokenNode>(ctorInvocation->mTarget);
  16131. auto targetType = (targetToken->GetToken() == BfToken_This) ? mCurTypeInstance : mCurTypeInstance->mBaseType;
  16132. if (targetToken->GetToken() == BfToken_This)
  16133. {
  16134. hadThisInitializer = true;
  16135. // Since we call a 'this', it's that other ctor's responsibility to fully assign the fields
  16136. mCurMethodState->LocalDefined(GetThisVariable());
  16137. }
  16138. }
  16139. // Zero out memory for default ctor
  16140. if ((methodDeclaration == NULL) && (mCurTypeInstance->IsStruct()) && (!mCurTypeInstance->IsAnonymousInitializerType()) && (methodInstance->mChainType != BfMethodChainType_ChainMember) &&
  16141. (!mCurMethodState->mLocals.IsEmpty()))
  16142. {
  16143. if (mCurTypeInstance->IsTypedPrimitive())
  16144. {
  16145. auto thisRef = mCurMethodState->mLocals[0]->mValue;
  16146. mBfIRBuilder->CreateStore(GetDefaultValue(mCurTypeInstance), thisRef);
  16147. }
  16148. else if (mCurTypeInstance->mInstSize > 0)
  16149. {
  16150. BfIRValue fillValue = GetConstValue8(0);
  16151. BfIRValue sizeValue = GetConstValue(mCurTypeInstance->mInstSize);
  16152. auto thisRef = mCurMethodState->mLocals[0]->mValue;
  16153. BfIRValue destBits = mBfIRBuilder->CreateBitCast(thisRef, mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr));
  16154. mBfIRBuilder->CreateMemSet(destBits, fillValue, sizeValue, mCurTypeInstance->mAlign);
  16155. }
  16156. }
  16157. BfAstNode* baseCtorNode = NULL;
  16158. if ((ctorDeclaration != NULL) && (ctorInvocation != NULL) && (ctorInvocation->mTarget != NULL))
  16159. baseCtorNode = ctorInvocation->mTarget;
  16160. else if (methodDef->mBody != NULL)
  16161. baseCtorNode = methodDef->mBody;
  16162. else if (ctorDeclaration != NULL)
  16163. baseCtorNode = ctorDeclaration;
  16164. else if ((methodDef->mDeclaringType != NULL) && (methodDef->mDeclaringType->GetRefNode() != NULL))
  16165. baseCtorNode = methodDef->mDeclaringType->GetRefNode();
  16166. else if (mCurTypeInstance->mTypeDef->mTypeDeclaration != NULL)
  16167. baseCtorNode = mCurTypeInstance->mTypeDef->mTypeDeclaration->mNameNode;
  16168. else if ((mCurTypeInstance->mBaseType != NULL) && (mCurTypeInstance->mBaseType->mTypeDef->mTypeDeclaration != NULL))
  16169. baseCtorNode = mCurTypeInstance->mBaseType->mTypeDef->mTypeDeclaration;
  16170. else
  16171. baseCtorNode = mContext->mBfObjectType->mTypeDef->mTypeDeclaration;
  16172. bool calledCtorNoBody = false;
  16173. if ((mCurTypeInstance->IsTypedPrimitive()) && (!mCurTypeInstance->IsValuelessType()))
  16174. {
  16175. // Zero out typed primitives in ctor
  16176. mBfIRBuilder->CreateAlignedStore(GetDefaultValue(mCurTypeInstance->GetUnderlyingType()), mBfIRBuilder->GetArgument(0), mCurTypeInstance->mAlign);
  16177. }
  16178. if ((!mCurTypeInstance->IsBoxed()) && (methodDef->mMethodType == BfMethodType_Ctor) && (!hadThisInitializer))
  16179. {
  16180. // Call the root type's default ctor (with no body) to initialize its fields and call the chained ctors
  16181. if (mCurTypeInstance->mTypeDef->mHasCtorNoBody)
  16182. {
  16183. BfMethodDef* defaultCtor = NULL;
  16184. for (auto methodDef : mCurTypeInstance->mTypeDef->mMethods)
  16185. {
  16186. if ((methodDef->mMethodType == BfMethodType_CtorNoBody) && (methodDef->mDeclaringType->mTypeCode != BfTypeCode_Extension))
  16187. {
  16188. defaultCtor = methodDef;
  16189. }
  16190. }
  16191. if (defaultCtor != NULL)
  16192. {
  16193. UpdateSrcPos(mCurTypeInstance->mTypeDef->GetRefNode());
  16194. SetIllegalSrcPos();
  16195. auto moduleMethodInstance = GetMethodInstance(mCurTypeInstance, defaultCtor, BfTypeVector());
  16196. BfExprEvaluator exprEvaluator(this);
  16197. SizedArray<BfIRValue, 1> irArgs;
  16198. exprEvaluator.PushThis(NULL, GetThis(), moduleMethodInstance.mMethodInstance, irArgs);
  16199. exprEvaluator.CreateCall(NULL, moduleMethodInstance.mMethodInstance, moduleMethodInstance.mFunc, false, irArgs);
  16200. if (mIsComptimeModule)
  16201. mCompiler->mCeMachine->QueueMethod(moduleMethodInstance);
  16202. calledCtorNoBody = true;
  16203. }
  16204. }
  16205. }
  16206. // Initialize fields (if applicable)
  16207. if (mCurTypeInstance->IsBoxed())
  16208. {
  16209. skipBody = true;
  16210. }
  16211. else if ((methodDef->mMethodType == BfMethodType_Ctor) && (methodDef->mDeclaringType->mTypeCode == BfTypeCode_Extension))
  16212. {
  16213. // Field initializers occur in CtorNoBody methods for extensions
  16214. }
  16215. else if (!hadThisInitializer)
  16216. {
  16217. // If we had a 'this' initializer, that other ctor will have initialized our fields
  16218. //auto
  16219. if ((!mCompiler->mIsResolveOnly) ||
  16220. (mCompiler->mResolvePassData->mAutoComplete == NULL) ||
  16221. (mCompiler->mResolvePassData->mAutoComplete->mResolveType == BfResolveType_ShowFileSymbolReferences))
  16222. {
  16223. // If we calledCtorNoBody then we did the field initializer code, but we still need to run though it here
  16224. // to properly set the assigned flags
  16225. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, mBfIRBuilder->mIgnoreWrites || calledCtorNoBody);
  16226. bool hadInlineInitBlock = false;
  16227. BfScopeData scopeData;
  16228. scopeData.mInInitBlock = true;
  16229. auto _CheckInitBlock = [&](BfAstNode* node)
  16230. {
  16231. if (!hadInlineInitBlock)
  16232. {
  16233. if ((mBfIRBuilder->DbgHasInfo()) && (!mCurTypeInstance->IsUnspecializedType()) && (mHasFullDebugInfo))
  16234. {
  16235. UpdateSrcPos(baseCtorNode);
  16236. if (methodDef->mBody == NULL)
  16237. SetIllegalSrcPos();
  16238. // 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
  16239. EmitEnsureInstructionAt();
  16240. BfType* thisType = mCurTypeInstance;
  16241. if (thisType->IsValueType())
  16242. thisType = CreateRefType(thisType);
  16243. SizedArray<BfIRMDNode, 1> diParamTypes;
  16244. BfIRMDNode diFuncType = mBfIRBuilder->DbgCreateSubroutineType(diParamTypes);
  16245. mCurMethodState->AddScope(&scopeData);
  16246. NewScopeState();
  16247. int flags = 0;
  16248. mCurMethodState->mCurScope->mDIInlinedAt = mBfIRBuilder->DbgGetCurrentLocation();
  16249. BF_ASSERT(mCurMethodState->mCurScope->mDIInlinedAt);
  16250. // mCurMethodState->mCurScope->mDIInlinedAt may still be null ifwe don't have an explicit ctor
  16251. String linkageName;
  16252. if ((mIsComptimeModule) && (mCompiler->mCeMachine->mCurBuilder != NULL))
  16253. linkageName = StrFormat("%d", mCompiler->mCeMachine->mCurBuilder->DbgCreateMethodRef(mCurMethodInstance, "$initFields"));
  16254. mCurMethodState->mCurScope->mDIScope = mBfIRBuilder->DbgCreateFunction(mBfIRBuilder->DbgGetTypeInst(mCurTypeInstance), "this$initFields", linkageName, mCurFilePosition.mFileInstance->mDIFile,
  16255. mCurFilePosition.mCurLine + 1, diFuncType, false, true, mCurFilePosition.mCurLine + 1, flags, false, BfIRValue());
  16256. UpdateSrcPos(node);
  16257. auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(mCurMethodState->mCurScope->mDIScope,
  16258. "this", mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, mBfIRBuilder->DbgGetType(thisType));
  16259. //
  16260. {
  16261. auto loadedThis = GetThis();
  16262. // LLVM can't handle two variables pointing to the same value
  16263. BfIRValue copiedThisPtr;
  16264. copiedThisPtr = CreateAlloca(thisType);
  16265. auto storeInst = mBfIRBuilder->CreateStore(loadedThis.mValue, copiedThisPtr);
  16266. mBfIRBuilder->ClearDebugLocation(storeInst);
  16267. mBfIRBuilder->DbgInsertDeclare(copiedThisPtr, diVariable);
  16268. }
  16269. hadInlineInitBlock = true;
  16270. }
  16271. else
  16272. {
  16273. // Just do a simple one
  16274. mCurMethodState->AddScope(&scopeData);
  16275. NewScopeState();
  16276. hadInlineInitBlock = true;
  16277. }
  16278. }
  16279. UpdateSrcPos(node);
  16280. };
  16281. for (auto fieldDef : typeDef->mFields)
  16282. {
  16283. // For extensions, only handle these fields in the appropriate extension
  16284. if ((fieldDef->mDeclaringType->mTypeDeclaration != methodDef->mDeclaringType->mTypeDeclaration))
  16285. continue;
  16286. if ((!fieldDef->mIsConst) && (!fieldDef->mIsStatic))
  16287. {
  16288. auto fieldInst = &mCurTypeInstance->mFieldInstances[fieldDef->mIdx];
  16289. if (!fieldInst->mFieldIncluded)
  16290. continue;
  16291. if (fieldInst->mDataIdx < 0)
  16292. continue;
  16293. auto initializer = fieldDef->GetInitializer();
  16294. if (fieldInst->IsAppendedObject())
  16295. {
  16296. UpdateSrcPos(fieldDef->GetNameNode());
  16297. AppendedObjectInit(fieldInst);
  16298. continue;
  16299. }
  16300. if (initializer == NULL)
  16301. {
  16302. continue;
  16303. // if (fieldDef->mProtection != BfProtection_Hidden)
  16304. // continue;
  16305. // if (mCurTypeInstance->IsObject()) // Already zeroed out
  16306. // continue;
  16307. }
  16308. if (fieldInst->mResolvedType == NULL)
  16309. {
  16310. BF_ASSERT(mHadBuildError);
  16311. continue;
  16312. }
  16313. if (initializer != NULL)
  16314. {
  16315. _CheckInitBlock(initializer);
  16316. }
  16317. BfIRValue fieldAddr;
  16318. if ((!mCurTypeInstance->IsTypedPrimitive()) && (!fieldInst->mResolvedType->IsVar()))
  16319. {
  16320. fieldAddr = mBfIRBuilder->CreateInBoundsGEP(mCurMethodState->mLocals[0]->mValue, 0, fieldInst->mDataIdx /*, fieldDef->mName*/);
  16321. }
  16322. else
  16323. {
  16324. // Failed
  16325. }
  16326. auto assignValue = GetFieldInitializerValue(fieldInst);
  16327. if (mCurTypeInstance->IsUnion())
  16328. {
  16329. auto fieldPtrType = CreatePointerType(fieldInst->mResolvedType);
  16330. fieldAddr = mBfIRBuilder->CreateBitCast(fieldAddr, mBfIRBuilder->MapType(fieldPtrType));
  16331. }
  16332. if ((fieldAddr) && (assignValue))
  16333. mBfIRBuilder->CreateAlignedStore(assignValue.mValue, fieldAddr, fieldInst->mResolvedType->mAlign);
  16334. }
  16335. }
  16336. EmitInitBlocks(_CheckInitBlock);
  16337. if (hadInlineInitBlock)
  16338. {
  16339. RestoreScopeState();
  16340. // This gets set to false because of AddScope but we actually are still in the head block
  16341. mCurMethodState->mInHeadScope = true;
  16342. // Make sure we emit a return even if we had a NoReturn call or return inside ourselves
  16343. mCurMethodState->mHadReturn = false;
  16344. mCurMethodState->mLeftBlockUncond = false;
  16345. }
  16346. }
  16347. else // Autocomplete case
  16348. {
  16349. BfScopeData scopeData;
  16350. scopeData.mInInitBlock = true;
  16351. mCurMethodState->AddScope(&scopeData);
  16352. NewScopeState();
  16353. // The reason we can't just do the 'normal' path for this is that the BfTypeInstance here is NOT the
  16354. // autocomplete type instance, so FieldInstance initializer values contain expressions from the full
  16355. // resolve pass, NOT the autocomplete expression
  16356. for (auto tempTypeDef : mCompiler->mResolvePassData->mAutoCompleteTempTypes)
  16357. {
  16358. if (tempTypeDef->mFullName == typeDef->mFullName)
  16359. {
  16360. for (auto fieldDef : tempTypeDef->mFields)
  16361. {
  16362. auto initializer = fieldDef->GetInitializer();
  16363. if ((!fieldDef->mIsStatic) && (initializer != NULL) && (mCompiler->mResolvePassData->mIsClassifying))
  16364. {
  16365. if (auto sourceClassifier = mCompiler->mResolvePassData->GetSourceClassifier(initializer))
  16366. {
  16367. sourceClassifier->SetElementType(initializer, BfSourceElementType_Normal);
  16368. sourceClassifier->VisitChild(initializer);
  16369. }
  16370. BfType* wantType = NULL;
  16371. if ((!BfNodeIsA<BfVarTypeReference>(fieldDef->mTypeRef)) &&
  16372. (!BfNodeIsA<BfLetTypeReference>(fieldDef->mTypeRef)))
  16373. wantType = ResolveTypeRef(fieldDef->mTypeRef, BfPopulateType_Declaration, BfResolveTypeRefFlag_AllowInferredSizedArray);
  16374. if ((wantType != NULL) &&
  16375. ((wantType->IsVar()) || (wantType->IsLet()) || (wantType->IsRef())))
  16376. wantType = NULL;
  16377. BfEvalExprFlags exprFlags = BfEvalExprFlags_FieldInitializer;
  16378. if (fieldDef->mIsAppend)
  16379. exprFlags = (BfEvalExprFlags)(exprFlags | BfEvalExprFlags_AppendFieldInitializer);
  16380. CreateValueFromExpression(initializer, wantType, exprFlags);
  16381. }
  16382. }
  16383. tempTypeDef->PopulateMemberSets();
  16384. BfMemberSetEntry* entry = NULL;
  16385. BfMethodDef* initMethodDef = NULL;
  16386. tempTypeDef->mMethodSet.TryGetWith(String("__BfInit"), &entry);
  16387. if (entry != NULL)
  16388. initMethodDef = (BfMethodDef*)entry->mMemberDef;
  16389. SizedArray<BfAstNode*, 8> initBodies;
  16390. for (; initMethodDef != NULL; initMethodDef = initMethodDef->mNextWithSameName)
  16391. {
  16392. if (initMethodDef->mMethodType != BfMethodType_Init)
  16393. continue;
  16394. initBodies.Insert(0, initMethodDef->mBody);
  16395. }
  16396. for (auto body : initBodies)
  16397. VisitEmbeddedStatement(body);
  16398. }
  16399. }
  16400. // Mark fields from full type with initializers as initialized, to give proper initialization errors within ctor
  16401. for (auto fieldDef : typeDef->mFields)
  16402. {
  16403. if ((!fieldDef->mIsConst) && (!fieldDef->mIsStatic) && (fieldDef->GetInitializer() != NULL))
  16404. {
  16405. auto fieldInst = &mCurTypeInstance->mFieldInstances[fieldDef->mIdx];
  16406. if (fieldDef->GetInitializer() != NULL)
  16407. MarkFieldInitialized(fieldInst);
  16408. }
  16409. }
  16410. RestoreScopeState();
  16411. }
  16412. }
  16413. if (!methodInstance->mIsAutocompleteMethod)
  16414. {
  16415. if (auto autoDecl = BfNodeDynCast<BfAutoConstructorDeclaration>(methodDeclaration))
  16416. {
  16417. BfExprEvaluator exprEvaluator(this);
  16418. for (int paramIdx = 0; paramIdx < methodDef->mParams.mSize; paramIdx++)
  16419. {
  16420. auto paramDef = methodDef->mParams[paramIdx];
  16421. auto& fieldInstance = mCurTypeInstance->mFieldInstances[paramIdx];
  16422. BF_ASSERT(paramDef->mName == fieldInstance.GetFieldDef()->mName);
  16423. if (fieldInstance.mDataIdx < 0)
  16424. continue;
  16425. if (paramDef->mParamKind != BfParamKind_Normal)
  16426. continue;
  16427. auto localVar = mCurMethodState->mLocals[paramIdx + 1];
  16428. BF_ASSERT(localVar->mName == paramDef->mName);
  16429. auto localVal = exprEvaluator.LoadLocal(localVar);
  16430. localVal = LoadOrAggregateValue(localVal);
  16431. if (!localVal.mType->IsVar())
  16432. {
  16433. auto thisVal = GetThis();
  16434. auto fieldPtr = mBfIRBuilder->CreateInBoundsGEP(thisVal.mValue, 0, fieldInstance.mDataIdx);
  16435. if (mCurTypeInstance->IsUnion())
  16436. fieldPtr = mBfIRBuilder->CreateBitCast(fieldPtr, mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapType(fieldInstance.mResolvedType)));
  16437. mBfIRBuilder->CreateAlignedStore(localVal.mValue, fieldPtr, localVar->mResolvedType->mAlign);
  16438. }
  16439. MarkFieldInitialized(&fieldInstance);
  16440. }
  16441. }
  16442. }
  16443. // Call base ctor (if applicable)
  16444. BfTypeInstance* targetType = NULL;
  16445. BfAstNode* targetRefNode = NULL;
  16446. if (ctorDeclaration != NULL)
  16447. targetRefNode = ctorDeclaration->mInitializer;
  16448. if (auto invocationExpr = BfNodeDynCast<BfInvocationExpression>(targetRefNode))
  16449. targetRefNode = invocationExpr->mTarget;
  16450. if (targetRefNode == NULL)
  16451. targetRefNode = mCurTypeInstance->mTypeDef->GetRefNode();
  16452. if (baseCtorNode != NULL)
  16453. {
  16454. UpdateSrcPos(baseCtorNode);
  16455. if (methodDef->mBody == NULL)
  16456. SetIllegalSrcPos();
  16457. }
  16458. if ((ctorDeclaration != NULL) && (ctorInvocation != NULL))
  16459. {
  16460. auto targetToken = BfNodeDynCast<BfTokenNode>(ctorInvocation->mTarget);
  16461. targetType = (targetToken->GetToken() == BfToken_This) ? mCurTypeInstance : mCurTypeInstance->mBaseType;
  16462. }
  16463. else if ((mCurTypeInstance->mBaseType != NULL) && (!mCurTypeInstance->IsUnspecializedType()) && (methodDef->mMethodType != BfMethodType_CtorNoBody))
  16464. {
  16465. auto baseType = mCurTypeInstance->mBaseType;
  16466. if ((!mCurTypeInstance->IsTypedPrimitive()) &&
  16467. ((baseType->mTypeDef != mCompiler->mValueTypeTypeDef) || (!mContext->mCanSkipValueTypeCtor)) &&
  16468. ((baseType->mTypeDef != mCompiler->mBfObjectTypeDef) || (!mContext->mCanSkipObjectCtor)))
  16469. {
  16470. // Try to find a ctor without any params first
  16471. BfMethodDef* matchedMethod = NULL;
  16472. bool hadCtorWithAllDefaults = false;
  16473. bool isHiddenGenerated = (methodDeclaration == NULL) && (methodDef->mProtection == BfProtection_Hidden);
  16474. for (int pass = 0; pass < 2; pass++)
  16475. {
  16476. baseType->mTypeDef->PopulateMemberSets();
  16477. BfMemberSetEntry* entry = NULL;
  16478. BfMethodDef* checkMethodDef = NULL;
  16479. baseType->mTypeDef->mMethodSet.TryGetWith(String("__BfCtor"), &entry);
  16480. if (entry != NULL)
  16481. checkMethodDef = (BfMethodDef*)entry->mMemberDef;
  16482. while (checkMethodDef != NULL)
  16483. {
  16484. bool allowMethod = checkMethodDef->mProtection > BfProtection_Private;
  16485. if (isHiddenGenerated)
  16486. {
  16487. // Allow calling of the default base ctor if it is implicitly defined
  16488. if ((checkMethodDef->mMethodDeclaration == NULL) && (pass == 1) && (!hadCtorWithAllDefaults))
  16489. allowMethod = true;
  16490. }
  16491. if ((checkMethodDef->mMethodType == BfMethodType_Ctor) && (!checkMethodDef->mIsStatic) && (allowMethod))
  16492. {
  16493. if (checkMethodDef->mParams.size() == 0)
  16494. {
  16495. if (matchedMethod != NULL)
  16496. {
  16497. // Has multiple matched methods - can happen from extensions
  16498. matchedMethod = NULL;
  16499. break;
  16500. }
  16501. matchedMethod = checkMethodDef;
  16502. }
  16503. else if (isHiddenGenerated)
  16504. {
  16505. if ((checkMethodDef->mParams[0]->mParamDeclaration != NULL) && (checkMethodDef->mParams[0]->mParamDeclaration->mInitializer != NULL))
  16506. hadCtorWithAllDefaults = true;
  16507. }
  16508. }
  16509. checkMethodDef = checkMethodDef->mNextWithSameName;
  16510. }
  16511. if (matchedMethod != NULL)
  16512. break;
  16513. }
  16514. if ((HasExecutedOutput()) && (matchedMethod != NULL))
  16515. {
  16516. SizedArray<BfIRValue, 1> args;
  16517. auto ctorBodyMethodInstance = GetMethodInstance(mCurTypeInstance->mBaseType, matchedMethod, BfTypeVector());
  16518. if (!mCurTypeInstance->mBaseType->IsValuelessType())
  16519. {
  16520. auto basePtr = mBfIRBuilder->CreateBitCast(mCurMethodState->mLocals[0]->mValue, mBfIRBuilder->MapTypeInstPtr(mCurTypeInstance->mBaseType));
  16521. args.push_back(basePtr);
  16522. }
  16523. AddCallDependency(ctorBodyMethodInstance.mMethodInstance, true);
  16524. auto callInst = mBfIRBuilder->CreateCall(ctorBodyMethodInstance.mFunc, args);
  16525. auto callingConv = GetIRCallingConvention(ctorBodyMethodInstance.mMethodInstance);
  16526. if (callingConv != BfIRCallingConv_CDecl)
  16527. mBfIRBuilder->SetCallCallingConv(callInst, callingConv);
  16528. if (mIsComptimeModule)
  16529. mCompiler->mCeMachine->QueueMethod(ctorBodyMethodInstance);
  16530. }
  16531. if (matchedMethod == NULL)
  16532. {
  16533. targetType = mCurTypeInstance->mBaseType;
  16534. if (ctorDeclaration != NULL)
  16535. targetRefNode = ctorDeclaration->mThisToken;
  16536. else if ((typeDef->mTypeDeclaration != NULL) && (typeDef->mTypeDeclaration->mNameNode != NULL))
  16537. targetRefNode = typeDef->mTypeDeclaration->mNameNode;
  16538. }
  16539. }
  16540. }
  16541. if (methodDef->HasAppend())
  16542. {
  16543. mCurMethodState->mCurAppendAlign = methodInstance->mAppendAllocAlign;
  16544. }
  16545. if ((ctorDeclaration != NULL) && (ctorInvocation != NULL) && (ctorInvocation->mArguments.size() == 1) && (targetType != NULL))
  16546. {
  16547. if (auto tokenNode = BfNodeDynCast<BfUninitializedExpression>(ctorInvocation->mArguments[0]))
  16548. {
  16549. if (targetType == mCurTypeInstance)
  16550. {
  16551. auto thisVariable = GetThisVariable();
  16552. if (thisVariable != NULL)
  16553. {
  16554. thisVariable->mUnassignedFieldFlags = 0;
  16555. thisVariable->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  16556. }
  16557. }
  16558. targetType = NULL;
  16559. }
  16560. }
  16561. auto autoComplete = mCompiler->GetAutoComplete();
  16562. if ((targetType != NULL) && (!mCurTypeInstance->IsAnonymousInitializerType()))
  16563. {
  16564. BfAstNode* refNode = methodDeclaration;
  16565. if (refNode == NULL)
  16566. refNode = typeDef->mTypeDeclaration;
  16567. BfAutoParentNodeEntry autoParentNodeEntry(this, refNode);
  16568. auto wasCapturingMethodInfo = (autoComplete != NULL) && (autoComplete->mIsCapturingMethodMatchInfo);
  16569. if ((autoComplete != NULL) && (ctorDeclaration != NULL) && (ctorInvocation != NULL))
  16570. {
  16571. auto invocationExpr = ctorInvocation;
  16572. autoComplete->CheckInvocation(invocationExpr, invocationExpr->mOpenParen, invocationExpr->mCloseParen, invocationExpr->mCommas);
  16573. }
  16574. BfType* targetThisType = targetType;
  16575. auto target = Cast(targetRefNode, GetThis(), targetThisType);
  16576. BfExprEvaluator exprEvaluator(this);
  16577. BfResolvedArgs argValues;
  16578. if ((ctorDeclaration != NULL) && (ctorInvocation != NULL))
  16579. {
  16580. argValues.Init(&ctorInvocation->mArguments);
  16581. if (gDebugStuff)
  16582. {
  16583. OutputDebugStrF("Expr: %@ %d\n", argValues.mArguments->mVals, argValues.mArguments->mSize);
  16584. }
  16585. }
  16586. exprEvaluator.ResolveArgValues(argValues, BfResolveArgsFlag_DeferParamEval);
  16587. BfAllowAppendKind allowAppendKind = GetBaseAllowAppend(mCurMethodInstance);
  16588. BfTypedValue appendIdxVal;
  16589. if (methodDef->HasAppend())
  16590. {
  16591. auto localVar = mCurMethodState->GetRootMethodState()->mLocals[1];
  16592. BF_ASSERT(localVar->mName == "__appendIdx");
  16593. auto intRefType = localVar->mResolvedType;
  16594. appendIdxVal = BfTypedValue(localVar->mValue, intRefType);
  16595. mCurMethodState->mCurAppendAlign = 1; // Don't make any assumptions about how the base leaves the alignment
  16596. }
  16597. exprEvaluator.MatchConstructor(targetRefNode, NULL, target, targetType, argValues, true, BfMethodGenericArguments(), allowAppendKind, &appendIdxVal);
  16598. if (autoComplete != NULL)
  16599. {
  16600. if ((wasCapturingMethodInfo) && (!autoComplete->mIsCapturingMethodMatchInfo))
  16601. {
  16602. if (autoComplete->mMethodMatchInfo != NULL)
  16603. autoComplete->mIsCapturingMethodMatchInfo = true;
  16604. else
  16605. autoComplete->mIsCapturingMethodMatchInfo = false;
  16606. }
  16607. else
  16608. autoComplete->mIsCapturingMethodMatchInfo = false;
  16609. }
  16610. }
  16611. auto autoCtorDecl = BfNodeDynCast<BfAutoConstructorDeclaration>(methodDeclaration);
  16612. if ((autoComplete != NULL) && (autoComplete->CheckFixit(methodDeclaration)) && (methodDeclaration != NULL) && (autoCtorDecl != NULL))
  16613. {
  16614. auto typeDecl = methodDef->mDeclaringType->mTypeDeclaration;
  16615. BfParserData* parser = typeDecl->GetSourceData()->ToParserData();
  16616. if (parser != NULL)
  16617. {
  16618. String fixitStr = "Expand auto constructor\t";
  16619. int insertPos = typeDecl->mSrcStart;
  16620. bool needsBlock = false;
  16621. if (auto defBlock = BfNodeDynCast<BfBlock>(typeDecl->mDefineNode))
  16622. {
  16623. insertPos = defBlock->mOpenBrace->mSrcStart + 1;
  16624. }
  16625. else if (auto tokenNode = BfNodeDynCast<BfTokenNode>(typeDecl->mDefineNode))
  16626. {
  16627. insertPos = tokenNode->mSrcStart;
  16628. fixitStr += StrFormat("delete|%s-%d|\x01",
  16629. autoComplete->FixitGetLocation(parser, tokenNode->mSrcStart).c_str(), tokenNode->mSrcEnd - tokenNode->mSrcStart);
  16630. needsBlock = true;
  16631. }
  16632. int srcStart = methodDeclaration->mSrcStart;
  16633. if ((autoCtorDecl->mPrefix == NULL) && (typeDecl->mColonToken != NULL))
  16634. srcStart = typeDecl->mColonToken->mSrcStart;
  16635. while ((srcStart > 0) && (::isspace((uint8)parser->mSrc[srcStart - 1])))
  16636. srcStart--;
  16637. fixitStr += StrFormat("expand|%s|%d|",
  16638. parser->mFileName.c_str(), insertPos);
  16639. if (needsBlock)
  16640. fixitStr += "\t";
  16641. else
  16642. fixitStr += "\f";
  16643. for (int paramIdx = 0; paramIdx < autoCtorDecl->mParams.mSize; paramIdx++)
  16644. {
  16645. String paramStr = autoCtorDecl->mParams[paramIdx]->ToString();
  16646. paramStr.Replace('\n', '\r');
  16647. fixitStr += "public ";
  16648. fixitStr += paramStr;
  16649. fixitStr += ";\r";
  16650. }
  16651. fixitStr += "\rpublic this(";
  16652. for (int paramIdx = 0; paramIdx < autoCtorDecl->mParams.mSize; paramIdx++)
  16653. {
  16654. if (paramIdx > 0)
  16655. fixitStr += ", ";
  16656. String paramStr = autoCtorDecl->mParams[paramIdx]->ToString();
  16657. paramStr.Replace('\n', '\r');
  16658. fixitStr += paramStr;
  16659. }
  16660. fixitStr += ")\t";
  16661. for (int paramIdx = 0; paramIdx < autoCtorDecl->mParams.mSize; paramIdx++)
  16662. {
  16663. if (paramIdx > 0)
  16664. fixitStr += "\r";
  16665. auto nameNode = autoCtorDecl->mParams[paramIdx]->mNameNode;
  16666. if (nameNode == NULL)
  16667. continue;
  16668. String nameStr = nameNode->ToString();
  16669. fixitStr += "this.";
  16670. fixitStr += nameStr;
  16671. fixitStr += " = ";
  16672. fixitStr += nameStr;
  16673. fixitStr += ";";
  16674. }
  16675. fixitStr += "\b";
  16676. if (needsBlock)
  16677. fixitStr += "\b";
  16678. fixitStr += StrFormat("\x01""delete|%s-%d|",
  16679. autoComplete->FixitGetLocation(parser, srcStart).c_str(), autoCtorDecl->mSrcEnd - srcStart);
  16680. mCompiler->mResolvePassData->mAutoComplete->AddEntry(AutoCompleteEntry("fixit", fixitStr.c_str()));
  16681. }
  16682. }
  16683. }
  16684. void BfModule::EmitEnumToStringBody()
  16685. {
  16686. auto stringType = ResolveTypeDef(mCompiler->mStringTypeDef);
  16687. auto strVal = CreateAlloca(stringType);
  16688. auto int64StructType = GetPrimitiveStructType(BfTypeCode_Int64);
  16689. BfExprEvaluator exprEvaluator(this);
  16690. auto stringDestAddr = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  16691. BfIRBlock appendBlock = mBfIRBuilder->CreateBlock("append");
  16692. BfIRBlock noMatchBlock = mBfIRBuilder->CreateBlock("noMatch");
  16693. BfIRBlock endBlock = mBfIRBuilder->CreateBlock("end");
  16694. BfType* discriminatorType = NULL;
  16695. BfTypedValue rawPayload;
  16696. BfIRValue enumVal;
  16697. if (mCurTypeInstance->IsPayloadEnum())
  16698. {
  16699. discriminatorType = mCurTypeInstance->GetDiscriminatorType();
  16700. auto enumTypedValue = ExtractValue(GetThis(), NULL, 2);
  16701. enumTypedValue = LoadValue(enumTypedValue);
  16702. enumVal = enumTypedValue.mValue;
  16703. rawPayload = ExtractValue(GetThis(), NULL, 1);
  16704. }
  16705. else
  16706. enumVal = mBfIRBuilder->GetArgument(0);
  16707. Array<BfType*> paramTypes;
  16708. paramTypes.Add(stringType);
  16709. auto appendModuleMethodInstance = GetMethodByName(stringType->ToTypeInstance(), "Append", paramTypes);
  16710. BfIRValue switchVal;
  16711. if (!mCurTypeInstance->IsValuelessType())
  16712. switchVal = mBfIRBuilder->CreateSwitch(enumVal, noMatchBlock, (int)mCurTypeInstance->mFieldInstances.size());
  16713. HashSet<int64> handledCases;
  16714. for (auto& fieldInstance : mCurTypeInstance->mFieldInstances)
  16715. {
  16716. if (fieldInstance.mIsEnumPayloadCase)
  16717. {
  16718. int tagId = -fieldInstance.mDataIdx - 1;
  16719. BfIRBlock caseBlock = mBfIRBuilder->CreateBlock("case");
  16720. mBfIRBuilder->AddBlock(caseBlock);
  16721. mBfIRBuilder->SetInsertPoint(caseBlock);
  16722. BF_ASSERT(discriminatorType->IsPrimitiveType());
  16723. auto constVal = mBfIRBuilder->CreateConst(((BfPrimitiveType*)discriminatorType)->mTypeDef->mTypeCode, tagId);
  16724. mBfIRBuilder->AddSwitchCase(switchVal, constVal, caseBlock);
  16725. auto caseStr = GetStringObjectValue(fieldInstance.GetFieldDef()->mName);
  16726. auto stringDestVal = LoadValue(stringDestAddr);
  16727. SizedArray<BfIRValue, 2> args;
  16728. args.Add(stringDestVal.mValue);
  16729. args.Add(caseStr);
  16730. exprEvaluator.CreateCall(NULL, appendModuleMethodInstance.mMethodInstance, appendModuleMethodInstance.mFunc, false, args);
  16731. auto payloadType = fieldInstance.mResolvedType->ToTypeInstance();
  16732. BF_ASSERT(payloadType->IsTuple());
  16733. if (payloadType->mFieldInstances.size() != 0)
  16734. {
  16735. auto payload = rawPayload;
  16736. if (payload.mType != payloadType)
  16737. {
  16738. payload = Cast(NULL, payload, payloadType, BfCastFlags_Force);
  16739. }
  16740. auto toStringMethod = GetMethodByName(payloadType->ToTypeInstance(), "ToString");
  16741. SizedArray<BfIRValue, 2> irArgs;
  16742. exprEvaluator.PushThis(NULL, payload, toStringMethod.mMethodInstance, irArgs);
  16743. stringDestVal = LoadValue(stringDestAddr);
  16744. irArgs.Add(stringDestVal.mValue);
  16745. exprEvaluator.CreateCall(NULL, toStringMethod.mMethodInstance, toStringMethod.mFunc, true, irArgs);
  16746. }
  16747. mBfIRBuilder->CreateBr(endBlock);
  16748. continue;
  16749. }
  16750. if (fieldInstance.mConstIdx == -1)
  16751. continue;
  16752. // Only allow compact 'ValA, ValB' enum declaration fields through
  16753. auto fieldDef = fieldInstance.GetFieldDef();
  16754. auto fieldDecl = fieldDef->mFieldDeclaration;
  16755. if ((fieldDecl == NULL) || (fieldDef->mTypeRef != NULL))
  16756. continue;
  16757. auto constant = mCurTypeInstance->mConstHolder->GetConstantById(fieldInstance.mConstIdx);
  16758. if (!handledCases.TryAdd(constant->mInt64, NULL))
  16759. {
  16760. // Duplicate
  16761. continue;
  16762. }
  16763. if (switchVal)
  16764. {
  16765. BfIRBlock caseBlock = mBfIRBuilder->CreateBlock("case");
  16766. mBfIRBuilder->AddBlock(caseBlock);
  16767. mBfIRBuilder->SetInsertPoint(caseBlock);
  16768. BfIRValue constVal = ConstantToCurrent(constant, mCurTypeInstance->mConstHolder, mCurTypeInstance);
  16769. mBfIRBuilder->AddSwitchCase(switchVal, constVal, caseBlock);
  16770. }
  16771. auto caseStr = GetStringObjectValue(fieldInstance.GetFieldDef()->mName);
  16772. mBfIRBuilder->CreateStore(caseStr, strVal);
  16773. mBfIRBuilder->CreateBr(appendBlock);
  16774. }
  16775. mBfIRBuilder->AddBlock(appendBlock);
  16776. mBfIRBuilder->SetInsertPoint(appendBlock);
  16777. SizedArray<BfIRValue, 2> args;
  16778. auto stringDestVal = LoadValue(stringDestAddr);
  16779. args.Add(stringDestVal.mValue);
  16780. args.Add(mBfIRBuilder->CreateLoad(strVal));
  16781. exprEvaluator.CreateCall(NULL, appendModuleMethodInstance.mMethodInstance, appendModuleMethodInstance.mFunc, false, args);
  16782. if (switchVal)
  16783. {
  16784. mBfIRBuilder->CreateBr(endBlock);
  16785. mBfIRBuilder->AddBlock(noMatchBlock);
  16786. mBfIRBuilder->SetInsertPoint(noMatchBlock);
  16787. auto int64Val = mBfIRBuilder->CreateNumericCast(enumVal, false, BfTypeCode_Int64);
  16788. auto toStringModuleMethodInstance = GetMethodByName(int64StructType, "ToString", 1);
  16789. args.clear();
  16790. args.Add(int64Val);
  16791. stringDestVal = LoadValue(stringDestAddr);
  16792. args.Add(stringDestVal.mValue);
  16793. exprEvaluator.CreateCall(NULL, toStringModuleMethodInstance.mMethodInstance, toStringModuleMethodInstance.mFunc, false, args);
  16794. mBfIRBuilder->CreateBr(endBlock);
  16795. mBfIRBuilder->AddBlock(endBlock);
  16796. mBfIRBuilder->SetInsertPoint(endBlock);
  16797. }
  16798. }
  16799. void BfModule::EmitTupleToStringBody()
  16800. {
  16801. auto stringType = ResolveTypeDef(mCompiler->mStringTypeDef);
  16802. BfExprEvaluator exprEvaluator(this);
  16803. auto stringDestRef = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  16804. Array<BfType*> paramTypes;
  16805. paramTypes.Add(GetPrimitiveType(BfTypeCode_Char8));
  16806. auto appendCharModuleMethodInstance = GetMethodByName(stringType->ToTypeInstance(), "Append", paramTypes);
  16807. paramTypes.Clear();
  16808. paramTypes.Add(stringType);
  16809. auto appendModuleMethodInstance = GetMethodByName(stringType->ToTypeInstance(), "Append", paramTypes);
  16810. auto _AppendChar = [&](char c)
  16811. {
  16812. SizedArray<BfIRValue, 2> args;
  16813. auto stringDestVal = LoadValue(stringDestRef);
  16814. args.Add(stringDestVal.mValue);
  16815. args.Add(mBfIRBuilder->CreateConst(BfTypeCode_Char8, (int)c));
  16816. exprEvaluator.CreateCall(NULL, appendCharModuleMethodInstance.mMethodInstance, appendCharModuleMethodInstance.mFunc, false, args);
  16817. };
  16818. int fieldIdx = 0;
  16819. auto thisValue = GetThis();
  16820. auto toStringModuleMethodInstance = GetMethodByName(mContext->mBfObjectType, "ToString", 1);
  16821. auto toStringSafeModuleMethodInstance = GetMethodByName(mContext->mBfObjectType, "ToString", 2);
  16822. BfIRValue commaStr;
  16823. auto iPrintableType = ResolveTypeDef(mCompiler->mIPrintableTypeDef)->ToTypeInstance();
  16824. auto printModuleMethodInstance = GetMethodByName(iPrintableType, "Print");
  16825. _AppendChar('(');
  16826. for (auto& fieldInstance : mCurTypeInstance->mFieldInstances)
  16827. {
  16828. if (fieldInstance.mDataIdx == -1)
  16829. continue;
  16830. if (fieldIdx > 0)
  16831. {
  16832. if (!commaStr)
  16833. commaStr = GetStringObjectValue(", ");
  16834. SizedArray<BfIRValue, 2> args;
  16835. auto stringDestVal = LoadValue(stringDestRef);
  16836. args.Add(stringDestVal.mValue);
  16837. args.Add(commaStr);
  16838. exprEvaluator.CreateCall(NULL, appendModuleMethodInstance.mMethodInstance, appendModuleMethodInstance.mFunc, false, args);
  16839. }
  16840. fieldIdx++;
  16841. if (fieldInstance.mResolvedType->IsValuelessType())
  16842. continue;
  16843. BfTypedValue fieldValue = ExtractValue(thisValue, &fieldInstance, fieldInstance.mDataIdx);
  16844. if (fieldValue.mType->IsWrappableType())
  16845. {
  16846. auto wrappedType = GetWrappedStructType(fieldValue.mType);
  16847. if ((wrappedType->IsTypedPrimitive()) || (wrappedType->IsValuelessType()))
  16848. {
  16849. fieldValue.mType = wrappedType;
  16850. }
  16851. else
  16852. {
  16853. fieldValue = MakeAddressable(fieldValue, false, true);
  16854. fieldValue.mType = wrappedType;
  16855. fieldValue.mValue = mBfIRBuilder->CreateBitCast(fieldValue.mValue, mBfIRBuilder->MapTypeInstPtr(fieldValue.mType->ToTypeInstance()));
  16856. if (!wrappedType->IsValuelessType())
  16857. fieldValue.mKind = BfTypedValueKind_Addr;
  16858. }
  16859. }
  16860. auto typeInstance = fieldValue.mType->ToTypeInstance();
  16861. if ((typeInstance != NULL) && (TypeIsSubTypeOf(typeInstance, iPrintableType, false)))
  16862. {
  16863. BfExprEvaluator exprEvaluator(this);
  16864. SizedArray<BfResolvedArg, 0> resolvedArgs;
  16865. BfMethodMatcher methodMatcher(NULL, this, printModuleMethodInstance.mMethodInstance, resolvedArgs, BfMethodGenericArguments());
  16866. methodMatcher.mBestMethodDef = printModuleMethodInstance.mMethodInstance->mMethodDef;
  16867. methodMatcher.mBestMethodTypeInstance = iPrintableType;
  16868. methodMatcher.TryDevirtualizeCall(fieldValue);
  16869. BfTypedValue callVal = Cast(NULL, fieldValue, methodMatcher.mBestMethodTypeInstance);
  16870. BfResolvedArg resolvedArg;
  16871. auto stringDestVal = LoadValue(stringDestRef);
  16872. resolvedArg.mTypedValue = stringDestVal;
  16873. resolvedArg.mResolvedType = stringDestVal.mType;
  16874. resolvedArgs.Add(resolvedArg);
  16875. exprEvaluator.CreateCall(&methodMatcher, callVal);
  16876. continue;
  16877. }
  16878. if (fieldValue.mType->IsObjectOrInterface())
  16879. {
  16880. fieldValue = LoadValue(fieldValue);
  16881. BF_ASSERT(!fieldValue.IsAddr());
  16882. SizedArray<BfIRValue, 2> args;
  16883. args.Add(mBfIRBuilder->CreateBitCast(fieldValue.mValue, mBfIRBuilder->MapType(mContext->mBfObjectType)));
  16884. auto stringDestVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  16885. stringDestVal = LoadValue(stringDestVal);
  16886. args.Add(stringDestVal.mValue);
  16887. exprEvaluator.CreateCall(NULL, toStringSafeModuleMethodInstance.mMethodInstance, toStringSafeModuleMethodInstance.mFunc, false, args);
  16888. continue;
  16889. }
  16890. BfExprEvaluator exprEvaluator(this);
  16891. SizedArray<BfResolvedArg, 0> resolvedArgs;
  16892. BfMethodMatcher methodMatcher(NULL, this, toStringModuleMethodInstance.mMethodInstance, resolvedArgs, BfMethodGenericArguments());
  16893. methodMatcher.mBestMethodDef = toStringModuleMethodInstance.mMethodInstance->mMethodDef;
  16894. methodMatcher.mBestMethodTypeInstance = mContext->mBfObjectType;
  16895. methodMatcher.TryDevirtualizeCall(fieldValue);
  16896. if (methodMatcher.mBestMethodTypeInstance == mContext->mBfObjectType)
  16897. {
  16898. AddCallDependency(appendModuleMethodInstance.mMethodInstance);
  16899. AddDependency(fieldValue.mType, mCurTypeInstance, BfDependencyMap::DependencyFlag_Calls);
  16900. // Just append the type name
  16901. String typeName = TypeToString(fieldInstance.mResolvedType);
  16902. auto strVal = GetStringObjectValue(typeName);
  16903. SizedArray<BfIRValue, 2> args;
  16904. auto stringDestVal = LoadValue(stringDestRef);
  16905. args.Add(stringDestVal.mValue);
  16906. args.Add(strVal);
  16907. exprEvaluator.CreateCall(NULL, appendModuleMethodInstance.mMethodInstance, appendModuleMethodInstance.mFunc, false, args);
  16908. continue;
  16909. }
  16910. BfTypedValue callVal = Cast(NULL, fieldValue, methodMatcher.mBestMethodTypeInstance);
  16911. BfResolvedArg resolvedArg;
  16912. auto stringDestVal = LoadValue(stringDestRef);
  16913. resolvedArg.mTypedValue = stringDestVal;
  16914. resolvedArg.mResolvedType = stringDestVal.mType;
  16915. resolvedArgs.Add(resolvedArg);
  16916. exprEvaluator.CreateCall(&methodMatcher, callVal);
  16917. }
  16918. _AppendChar(')');
  16919. }
  16920. void BfModule::EmitIteratorBlock(bool& skipBody)
  16921. {
  16922. auto methodInstance = mCurMethodInstance;
  16923. auto methodDef = methodInstance->mMethodDef;
  16924. auto methodDeclaration = methodDef->GetMethodDeclaration();
  16925. auto typeDef = mCurTypeInstance->mTypeDef;
  16926. BfType* innerRetType = NULL;
  16927. BfTypeInstance* usingInterface = NULL;
  16928. auto retTypeInst = mCurMethodInstance->mReturnType->ToGenericTypeInstance();
  16929. if (retTypeInst != NULL)
  16930. {
  16931. if ((retTypeInst->IsInstanceOf(mCompiler->mGenericIEnumerableTypeDef)) ||
  16932. (retTypeInst->IsInstanceOf(mCompiler->mGenericIEnumeratorTypeDef)))
  16933. {
  16934. innerRetType = retTypeInst->mGenericTypeInfo->mTypeGenericArguments[0];
  16935. }
  16936. }
  16937. if (innerRetType == NULL)
  16938. {
  16939. Fail("Methods with yields must return either System.IEnumerable<T> or System.IEnumerator<T>", methodDeclaration->mReturnType);
  16940. return;
  16941. }
  16942. auto blockBody = BfNodeDynCast<BfBlock>(methodDeclaration->mBody);
  16943. if (blockBody == NULL)
  16944. return;
  16945. }
  16946. void BfModule::EmitGCMarkAppended(BfTypedValue markVal)
  16947. {
  16948. auto gcType = ResolveTypeDef(mCompiler->mGCTypeDef, BfPopulateType_DataAndMethods);
  16949. if (gcType == NULL)
  16950. return;
  16951. BfModuleMethodInstance markFromGCThreadMethodInstance = GetMethodByName(gcType->ToTypeInstance(), "MarkAppendedObject", 1);
  16952. if (!markFromGCThreadMethodInstance)
  16953. return;
  16954. SizedArray<BfIRValue, 1> args;
  16955. args.push_back(mBfIRBuilder->CreateBitCast(markVal.mValue, mBfIRBuilder->MapType(mContext->mBfObjectType)));
  16956. BfExprEvaluator exprEvaluator(this);
  16957. exprEvaluator.CreateCall(NULL, markFromGCThreadMethodInstance.mMethodInstance, markFromGCThreadMethodInstance.mFunc, false, args);
  16958. }
  16959. void BfModule::EmitGCMarkValue(BfTypedValue markVal, BfModuleMethodInstance markFromGCThreadMethodInstance)
  16960. {
  16961. auto fieldType = markVal.mType;
  16962. auto fieldTypeInst = fieldType->ToTypeInstance();
  16963. if (fieldType == NULL)
  16964. return;
  16965. if (!markVal.mType->IsComposite())
  16966. markVal = LoadValue(markVal);
  16967. BfExprEvaluator exprEvaluator(this);
  16968. PopulateType(markVal.mType, BfPopulateType_Data);
  16969. if (markVal.mType->IsObjectOrInterface())
  16970. {
  16971. BfIRValue val = markVal.mValue;
  16972. val = mBfIRBuilder->CreateBitCast(val, mBfIRBuilder->MapType(mContext->mBfObjectType));
  16973. SizedArray<BfIRValue, 1> args;
  16974. args.push_back(val);
  16975. exprEvaluator.CreateCall(NULL, markFromGCThreadMethodInstance.mMethodInstance, markFromGCThreadMethodInstance.mFunc, false, args);
  16976. }
  16977. else if (fieldType->IsSizedArray())
  16978. {
  16979. BfSizedArrayType* sizedArrayType = (BfSizedArrayType*)fieldType;
  16980. if (sizedArrayType->mElementType->WantsGCMarking())
  16981. {
  16982. BfTypedValue arrayValue = markVal;
  16983. auto intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  16984. auto itr = CreateAlloca(intPtrType);
  16985. mBfIRBuilder->CreateStore(GetDefaultValue(intPtrType), itr);
  16986. auto loopBB = mBfIRBuilder->CreateBlock("loop", true);
  16987. auto bodyBB = mBfIRBuilder->CreateBlock("body", true);
  16988. auto doneBB = mBfIRBuilder->CreateBlock("done", true);
  16989. mBfIRBuilder->CreateBr(loopBB);
  16990. mBfIRBuilder->SetInsertPoint(loopBB);
  16991. auto loadedItr = mBfIRBuilder->CreateLoad(itr);
  16992. auto cmpRes = mBfIRBuilder->CreateCmpGTE(loadedItr, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, (uint64)sizedArrayType->mElementCount), true);
  16993. mBfIRBuilder->CreateCondBr(cmpRes, doneBB, bodyBB);
  16994. mBfIRBuilder->SetInsertPoint(bodyBB);
  16995. auto ptrType = CreatePointerType(sizedArrayType->mElementType);
  16996. auto ptrValue = mBfIRBuilder->CreateBitCast(arrayValue.mValue, mBfIRBuilder->MapType(ptrType));
  16997. auto gepResult = mBfIRBuilder->CreateInBoundsGEP(ptrValue, loadedItr);
  16998. auto value = BfTypedValue(gepResult, sizedArrayType->mElementType, BfTypedValueKind_Addr);
  16999. EmitGCMarkValue(value, markFromGCThreadMethodInstance);
  17000. auto incValue = mBfIRBuilder->CreateAdd(loadedItr, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 1));
  17001. mBfIRBuilder->CreateStore(incValue, itr);
  17002. mBfIRBuilder->CreateBr(loopBB);
  17003. mBfIRBuilder->SetInsertPoint(doneBB);
  17004. }
  17005. }
  17006. else if ((fieldType->IsComposite()) && (!fieldType->IsTypedPrimitive()) && (fieldTypeInst != NULL))
  17007. {
  17008. auto markMemberMethodInstance = GetMethodByName(fieldTypeInst, BF_METHODNAME_MARKMEMBERS, 0, true);
  17009. if (markMemberMethodInstance)
  17010. {
  17011. SizedArray<BfIRValue, 1> args;
  17012. auto methodOwner = markMemberMethodInstance.mMethodInstance->GetOwner();
  17013. if (markVal.mType != methodOwner)
  17014. markVal = Cast(NULL, markVal, methodOwner);
  17015. exprEvaluator.PushThis(NULL, markVal, markMemberMethodInstance.mMethodInstance, args);
  17016. exprEvaluator.CreateCall(NULL, markMemberMethodInstance.mMethodInstance, markMemberMethodInstance.mFunc, false, args);
  17017. }
  17018. }
  17019. }
  17020. void BfModule::CallChainedMethods(BfMethodInstance* methodInstance, bool reverse)
  17021. {
  17022. Array<BfMethodInstance*> methodInstances;
  17023. for (int methodIdx = 0; methodIdx < (int)mCurTypeInstance->mMethodInstanceGroups.size(); methodIdx++)
  17024. {
  17025. auto& methodInstGroup = mCurTypeInstance->mMethodInstanceGroups[methodIdx];
  17026. auto chainedMethodInst = methodInstGroup.mDefault;
  17027. if ((chainedMethodInst != NULL) && (chainedMethodInst->mChainType == BfMethodChainType_ChainMember))
  17028. {
  17029. if ((chainedMethodInst->mMethodDef->mIsStatic == methodInstance->mMethodDef->mIsStatic) &&
  17030. (CompareMethodSignatures(methodInstance, chainedMethodInst)))
  17031. {
  17032. methodInstances.push_back(chainedMethodInst);
  17033. }
  17034. }
  17035. }
  17036. std::stable_sort(methodInstances.begin(), methodInstances.end(),
  17037. [&](BfMethodInstance* lhs, BfMethodInstance* rhs)
  17038. {
  17039. bool isBetter;
  17040. bool isWorse;
  17041. CompareDeclTypes(mCurTypeInstance, lhs->mMethodDef->mDeclaringType, rhs->mMethodDef->mDeclaringType, isBetter, isWorse);
  17042. if (isBetter == isWorse)
  17043. {
  17044. return false;
  17045. }
  17046. return isWorse;
  17047. });
  17048. if (reverse)
  17049. std::reverse(methodInstances.begin(), methodInstances.end());
  17050. for (auto chainedMethodInst : methodInstances)
  17051. {
  17052. auto declModule = this;
  17053. BfGetMethodInstanceFlags flags = BfGetMethodInstanceFlag_None;
  17054. auto moduleMethodInst = declModule->GetMethodInstance(mCurTypeInstance, chainedMethodInst->mMethodDef, BfTypeVector(), flags);
  17055. BfExprEvaluator exprEvaluator(this);
  17056. SizedArray<BfIRValue, 1> args;
  17057. exprEvaluator.PushThis(chainedMethodInst->mMethodDef->GetRefNode(), GetThis(), chainedMethodInst, args);
  17058. exprEvaluator.CreateCall(NULL, moduleMethodInst.mMethodInstance, moduleMethodInst.mFunc, true, args);
  17059. }
  17060. }
  17061. void BfModule::AddHotDataReferences(BfHotDataReferenceBuilder* builder)
  17062. {
  17063. BF_ASSERT(mCurMethodInstance->mIsReified);
  17064. if (mCurTypeInstance->mHotTypeData == NULL)
  17065. {
  17066. mCurTypeInstance->mHotTypeData = new BfHotTypeData();
  17067. BfLogSysM("Created HotTypeData %p created for type %p in AddHotDataReferences\n", mCurTypeInstance->mHotTypeData, mCurTypeInstance);
  17068. }
  17069. auto hotMethod = mCurMethodInstance->mHotMethod;
  17070. for (auto depData : hotMethod->mReferences)
  17071. {
  17072. // Only virtual decls are allowed to already be there
  17073. BF_ASSERT((depData->mDataKind == BfHotDepDataKind_VirtualDecl) || (depData->mDataKind == BfHotDepDataKind_DupMethod));
  17074. }
  17075. BF_ASSERT(hotMethod->mSrcTypeVersion != NULL);
  17076. int prevSize = (int)hotMethod->mReferences.size();
  17077. int refCount = (int)(prevSize + builder->mUsedData.size() + builder->mCalledMethods.size() + builder->mDevirtualizedCalledMethods.size());
  17078. if (!mCurMethodInstance->mMethodDef->mIsStatic)
  17079. refCount++;
  17080. hotMethod->mReferences.Reserve(refCount);
  17081. if (!mCurMethodInstance->mMethodDef->mIsStatic)
  17082. {
  17083. auto hotThis = mCompiler->mHotData->GetThisType(mCurMethodInstance->GetOwner()->mHotTypeData->GetLatestVersion());
  17084. hotThis->mRefCount++;
  17085. hotMethod->mReferences.Insert(0, hotThis);
  17086. prevSize++;
  17087. }
  17088. for (auto val : builder->mAllocatedData)
  17089. {
  17090. auto hotAllocation = mCompiler->mHotData->GetAllocation(val);
  17091. hotMethod->mReferences.Add(hotAllocation);
  17092. }
  17093. for (auto val : builder->mUsedData)
  17094. hotMethod->mReferences.Add(val);
  17095. for (auto val : builder->mCalledMethods)
  17096. hotMethod->mReferences.Add(val);
  17097. for (auto val : builder->mDevirtualizedCalledMethods)
  17098. {
  17099. auto devirtualizedMethod = mCompiler->mHotData->GetDevirtualizedMethod(val);
  17100. hotMethod->mReferences.Add(devirtualizedMethod);
  17101. }
  17102. for (auto val : builder->mFunctionPtrs)
  17103. {
  17104. auto funcRef = mCompiler->mHotData->GetFunctionReference(val);
  17105. hotMethod->mReferences.Add(funcRef);
  17106. }
  17107. for (auto val : builder->mInnerMethods)
  17108. {
  17109. auto innerMethod = mCompiler->mHotData->GetInnerMethod(val);
  17110. hotMethod->mReferences.Add(innerMethod);
  17111. }
  17112. for (int refIdx = prevSize; refIdx < (int)hotMethod->mReferences.size(); refIdx++)
  17113. {
  17114. auto depData = hotMethod->mReferences[refIdx];
  17115. BF_ASSERT(depData != NULL);
  17116. depData->mRefCount++;
  17117. }
  17118. }
  17119. void BfModule::ProcessMethod_SetupParams(BfMethodInstance* methodInstance, BfType* thisType, bool wantsDIData, SizedArrayImpl<BfIRMDNode>* diParams)
  17120. {
  17121. auto methodDef = methodInstance->mMethodDef;
  17122. auto methodDeclaration = methodDef->mMethodDeclaration;
  17123. bool isThisStruct = false;
  17124. if (thisType != NULL)
  17125. isThisStruct = thisType->IsStruct() && !thisType->IsTypedPrimitive();
  17126. int argIdx = 0;
  17127. if ((!mIsComptimeModule) && (argIdx == methodInstance->GetStructRetIdx()))
  17128. argIdx++;
  17129. auto rootMethodState = mCurMethodState->GetRootMethodState();
  17130. if (!methodDef->mIsStatic)
  17131. {
  17132. BfTypeCode loweredTypeCode = BfTypeCode_None;
  17133. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  17134. BfLocalVariable* paramVar = rootMethodState->mBumpAlloc.Alloc<BfLocalVariable>();
  17135. paramVar->mIsBumpAlloc = true;
  17136. paramVar->mResolvedType = thisType;
  17137. paramVar->mName.Reference("this");
  17138. if (!thisType->IsValuelessType())
  17139. paramVar->mValue = mBfIRBuilder->GetArgument(argIdx);
  17140. else
  17141. paramVar->mValue = mBfIRBuilder->GetFakeVal();
  17142. if ((!mIsComptimeModule) && (thisType->IsSplattable()) && (methodInstance->AllowsSplatting(-1)))
  17143. {
  17144. if (!thisType->IsTypedPrimitive())
  17145. paramVar->mIsSplat = true;
  17146. }
  17147. else if ((!mIsComptimeModule) && (!methodDef->mIsMutating) && (methodInstance->mCallingConvention == BfCallingConvention_Unspecified))
  17148. paramVar->mIsLowered = thisType->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2) != BfTypeCode_None;
  17149. auto thisTypeInst = thisType->ToTypeInstance();
  17150. paramVar->mIsStruct = isThisStruct;
  17151. paramVar->mAddr = BfIRValue();
  17152. paramVar->mIsThis = true;
  17153. paramVar->mParamIdx = -1;
  17154. if ((methodDef->mMethodType == BfMethodType_Ctor) && (mCurTypeInstance->IsStruct()))
  17155. {
  17156. paramVar->mAssignedKind = BfLocalVarAssignKind_None;
  17157. }
  17158. else
  17159. {
  17160. paramVar->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  17161. }
  17162. paramVar->mReadFromId = -1;
  17163. paramVar->Init();
  17164. if (methodDeclaration == NULL)
  17165. UseDefaultSrcPos();
  17166. AddLocalVariableDef(paramVar);
  17167. if (!thisType->IsValuelessType())
  17168. {
  17169. if (wantsDIData)
  17170. {
  17171. BfType* thisPtrType = thisType;
  17172. auto diType = mBfIRBuilder->DbgGetType(thisPtrType);
  17173. if (!thisType->IsValueType())
  17174. diType = mBfIRBuilder->DbgCreateArtificialType(diType);
  17175. else if (!paramVar->mIsSplat)
  17176. diType = mBfIRBuilder->DbgCreatePointerType(diType);
  17177. diParams->push_back(diType);
  17178. }
  17179. if (paramVar->mIsSplat)
  17180. {
  17181. BfTypeUtils::SplatIterate([&](BfType* checkType) { argIdx++; }, paramVar->mResolvedType);
  17182. }
  17183. else
  17184. {
  17185. argIdx++;
  17186. if (loweredTypeCode2 != BfTypeCode_None)
  17187. argIdx++;
  17188. }
  17189. }
  17190. }
  17191. if ((!mIsComptimeModule) && (argIdx == methodInstance->GetStructRetIdx()))
  17192. argIdx++;
  17193. bool hadParams = false;
  17194. bool hasDefault = false;
  17195. int compositeVariableIdx = -1;
  17196. int paramIdx = 0;
  17197. for (paramIdx = 0; paramIdx < methodInstance->GetParamCount(); paramIdx++)
  17198. {
  17199. // We already issues a type error for this param if we had one in declaration processing
  17200. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, true);
  17201. BfLocalVariable* paramVar = rootMethodState->mBumpAlloc.Alloc<BfLocalVariable>();
  17202. paramVar->mIsBumpAlloc = true;
  17203. BfTypeCode loweredTypeCode = BfTypeCode_None;
  17204. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  17205. bool isParamSkipped = methodInstance->IsParamSkipped(paramIdx);
  17206. auto resolvedType = methodInstance->GetParamType(paramIdx);
  17207. if (resolvedType == NULL)
  17208. {
  17209. AssertErrorState();
  17210. paramVar->mParamFailed = true;
  17211. }
  17212. prevIgnoreErrors.Restore();
  17213. PopulateType(resolvedType, BfPopulateType_Declaration);
  17214. paramVar->mResolvedType = resolvedType;
  17215. int namePrefixCount = 0;
  17216. methodInstance->GetParamName(paramIdx, paramVar->mName, namePrefixCount);
  17217. paramVar->mNamePrefixCount = (uint8)namePrefixCount;
  17218. paramVar->mNameNode = methodInstance->GetParamNameNode(paramIdx);
  17219. if (!isParamSkipped)
  17220. {
  17221. paramVar->mValue = mBfIRBuilder->GetArgument(argIdx);
  17222. if (resolvedType->IsMethodRef())
  17223. {
  17224. paramVar->mIsSplat = true;
  17225. }
  17226. else if ((!mIsComptimeModule) && (resolvedType->IsComposite()) && (resolvedType->IsSplattable()))
  17227. {
  17228. if (methodInstance->AllowsSplatting(paramIdx))
  17229. {
  17230. auto resolveTypeInst = resolvedType->ToTypeInstance();
  17231. if ((resolveTypeInst != NULL) && (resolveTypeInst->mIsCRepr))
  17232. paramVar->mIsSplat = true;
  17233. else
  17234. {
  17235. int splatCount = resolvedType->GetSplatCount();
  17236. if (argIdx + splatCount <= mCompiler->mOptions.mMaxSplatRegs)
  17237. paramVar->mIsSplat = true;
  17238. }
  17239. }
  17240. }
  17241. }
  17242. else
  17243. {
  17244. paramVar->mIsSplat = true; // Treat skipped (valueless) as a splat
  17245. paramVar->mValue = mBfIRBuilder->GetFakeVal();
  17246. }
  17247. paramVar->mIsLowered = (!mIsComptimeModule) && resolvedType->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2) != BfTypeCode_None;
  17248. paramVar->mIsStruct = resolvedType->IsComposite() && !resolvedType->IsTypedPrimitive();
  17249. paramVar->mParamIdx = paramIdx;
  17250. paramVar->mIsImplicitParam = methodInstance->IsImplicitCapture(paramIdx);
  17251. paramVar->mReadFromId = 0;
  17252. if (resolvedType->IsRef())
  17253. {
  17254. auto refType = (BfRefType*)resolvedType;
  17255. paramVar->mAssignedKind = (refType->mRefKind != BfRefType::RefKind_Out) ? BfLocalVarAssignKind_Unconditional : BfLocalVarAssignKind_None;
  17256. if (refType->mRefKind == BfRefType::RefKind_In)
  17257. {
  17258. paramVar->mIsReadOnly = true;
  17259. }
  17260. }
  17261. else
  17262. {
  17263. paramVar->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  17264. if (methodDef->mMethodType != BfMethodType_Mixin)
  17265. paramVar->mIsReadOnly = true;
  17266. }
  17267. if (paramVar->mResolvedType->IsGenericParam())
  17268. {
  17269. auto genericParamInst = GetGenericParamInstance((BfGenericParamType*)paramVar->mResolvedType);
  17270. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  17271. {
  17272. auto typedVal = GetDefaultTypedValue(genericParamInst->mTypeConstraint, false, BfDefaultValueKind_Undef);
  17273. paramVar->mResolvedType = typedVal.mType;
  17274. paramVar->mConstValue = typedVal.mValue;
  17275. }
  17276. }
  17277. if (paramVar->mResolvedType->IsConstExprValue())
  17278. {
  17279. BfConstExprValueType* constExprValueType = (BfConstExprValueType*)paramVar->mResolvedType;
  17280. auto unspecializedMethodInstance = GetUnspecializedMethodInstance(methodInstance);
  17281. auto unspecParamType = unspecializedMethodInstance->GetParamType(paramIdx);
  17282. BF_ASSERT(unspecParamType->IsGenericParam());
  17283. if (unspecParamType->IsGenericParam())
  17284. {
  17285. BfGenericParamType* genericParamType = (BfGenericParamType*)unspecParamType;
  17286. if (genericParamType->mGenericParamKind == BfGenericParamKind_Method)
  17287. {
  17288. auto genericParamInst = unspecializedMethodInstance->mMethodInfoEx->mGenericParams[genericParamType->mGenericParamIdx];
  17289. if (genericParamInst->mTypeConstraint != NULL)
  17290. {
  17291. BfExprEvaluator exprEvaluator(this);
  17292. exprEvaluator.mExpectingType = genericParamInst->mTypeConstraint;
  17293. exprEvaluator.GetLiteral(NULL, constExprValueType->mValue);
  17294. auto checkType = genericParamInst->mTypeConstraint;
  17295. if (checkType->IsTypedPrimitive())
  17296. checkType = checkType->GetUnderlyingType();
  17297. auto typedVal = exprEvaluator.mResult;
  17298. if ((typedVal) && (typedVal.mType != checkType))
  17299. typedVal = Cast(NULL, typedVal, checkType, (BfCastFlags)(BfCastFlags_Explicit | BfCastFlags_SilentFail));
  17300. if ((typedVal.mType == checkType) && (typedVal.mValue.IsConst()))
  17301. {
  17302. paramVar->mResolvedType = genericParamInst->mTypeConstraint;
  17303. paramVar->mConstValue = typedVal.mValue;
  17304. BF_ASSERT(paramVar->mConstValue.IsConst());
  17305. paramVar->mIsConst = true;
  17306. }
  17307. else
  17308. {
  17309. AssertErrorState();
  17310. paramVar->mResolvedType = genericParamInst->mTypeConstraint;
  17311. paramVar->mConstValue = GetDefaultValue(genericParamInst->mTypeConstraint);
  17312. paramVar->mIsConst = true;
  17313. }
  17314. if (paramVar->mResolvedType->IsObject())
  17315. {
  17316. BfTypedValue typedVal(paramVar->mConstValue, paramVar->mResolvedType);
  17317. FixValueActualization(typedVal);
  17318. if (typedVal.mValue.IsConst())
  17319. paramVar->mConstValue = typedVal.mValue;
  17320. }
  17321. }
  17322. }
  17323. }
  17324. //BF_ASSERT(!paramVar->mResolvedType->IsConstExprValue());
  17325. if (paramVar->mResolvedType->IsConstExprValue())
  17326. {
  17327. Fail("Invalid use of constant expression", methodInstance->GetParamTypeRef(paramIdx));
  17328. //AssertErrorState();
  17329. paramVar->mResolvedType = GetPrimitiveType(BfTypeCode_IntPtr);
  17330. paramVar->mConstValue = GetDefaultValue(paramVar->mResolvedType);
  17331. paramVar->mIsConst = true;
  17332. }
  17333. }
  17334. if (methodInstance->GetParamKind(paramIdx) == BfParamKind_DelegateParam)
  17335. {
  17336. if (compositeVariableIdx == -1)
  17337. {
  17338. auto paramInst = &methodInstance->mParams[paramIdx];
  17339. auto paramDef = methodDef->mParams[paramInst->mParamDefIdx];
  17340. compositeVariableIdx = (int)mCurMethodState->mLocals.size();
  17341. BfLocalVariable* localVar = new BfLocalVariable();
  17342. localVar->mName = paramDef->mName;
  17343. localVar->mNamePrefixCount = paramDef->mNamePrefixCount;
  17344. if (paramDef->mTypeRef != NULL)
  17345. localVar->mResolvedType = ResolveTypeRef(paramDef->mTypeRef, BfPopulateType_Declaration, BfResolveTypeRefFlag_NoResolveGenericParam);
  17346. if (localVar->mResolvedType == NULL)
  17347. localVar->mResolvedType = GetPrimitiveType(BfTypeCode_None);
  17348. localVar->mCompositeCount = 0;
  17349. DoAddLocalVariable(localVar);
  17350. }
  17351. mCurMethodState->mLocals[compositeVariableIdx]->mCompositeCount++;
  17352. paramVar->mIsImplicitParam = true;
  17353. }
  17354. if (methodInstance->GetParamKind(paramIdx) == BfParamKind_Params)
  17355. {
  17356. if ((paramVar->mResolvedType->IsModifiedTypeType()) && (((BfModifiedTypeType*)paramVar->mResolvedType)->mModifiedKind == BfToken_Params))
  17357. {
  17358. paramVar->mValue = BfIRValue();
  17359. paramVar->mCompositeCount = 0;
  17360. paramVar->mIsSplat = false;
  17361. }
  17362. }
  17363. if (!mCurTypeInstance->IsDelegateOrFunction())
  17364. CheckVariableDef(paramVar);
  17365. paramVar->Init();
  17366. AddLocalVariableDef(paramVar);
  17367. if (!isParamSkipped)
  17368. {
  17369. if (wantsDIData)
  17370. diParams->push_back(mBfIRBuilder->DbgGetType(resolvedType));
  17371. if (paramVar->mIsSplat)
  17372. {
  17373. BfTypeUtils::SplatIterate([&](BfType* checkType) { argIdx++; }, paramVar->mResolvedType);
  17374. }
  17375. else
  17376. {
  17377. argIdx++;
  17378. }
  17379. if (loweredTypeCode2 != BfTypeCode_None)
  17380. argIdx++;
  17381. }
  17382. }
  17383. // Try to find an ending delegate params composite
  17384. if ((compositeVariableIdx == -1) && (methodDef->mParams.size() > 0))
  17385. {
  17386. auto paramDef = methodDef->mParams.back();
  17387. if (paramDef->mParamKind == BfParamKind_Params)
  17388. {
  17389. auto paramsType = ResolveTypeRef(paramDef->mTypeRef, BfPopulateType_Declaration, BfResolveTypeRefFlag_NoResolveGenericParam);
  17390. if (paramsType == NULL)
  17391. {
  17392. // Had error or 'var'
  17393. }
  17394. else if (paramsType->IsGenericParam())
  17395. {
  17396. auto genericParamInstance = GetGenericParamInstance((BfGenericParamType*)paramsType);
  17397. if (genericParamInstance->mTypeConstraint != NULL)
  17398. {
  17399. auto typeInstConstraint = genericParamInstance->mTypeConstraint->ToTypeInstance();
  17400. if ((genericParamInstance->mTypeConstraint->IsDelegate()) || (genericParamInstance->mTypeConstraint->IsFunction()) || (genericParamInstance->mTypeConstraint->IsTuple()) ||
  17401. ((typeInstConstraint != NULL) &&
  17402. ((typeInstConstraint->IsInstanceOf(mCompiler->mDelegateTypeDef)) || (typeInstConstraint->IsInstanceOf(mCompiler->mFunctionTypeDef)) || (typeInstConstraint->IsInstanceOf(mCompiler->mTupleTypeDef)))))
  17403. {
  17404. bool doAdd = true;
  17405. // TODO: Remove
  17406. if (!mCurMethodState->mLocals.IsEmpty())
  17407. {
  17408. auto checkVar = mCurMethodState->mLocals.back();
  17409. if (checkVar->mName == paramDef->mName)
  17410. doAdd = false;
  17411. }
  17412. if (doAdd)
  17413. {
  17414. BfLocalVariable* localVar = new BfLocalVariable();
  17415. localVar->mName = paramDef->mName;
  17416. localVar->mResolvedType = paramsType;
  17417. localVar->mCompositeCount = 0;
  17418. DoAddLocalVariable(localVar);
  17419. }
  17420. }
  17421. }
  17422. }
  17423. else if (paramsType->IsDelegate())
  17424. {
  17425. BfMethodInstance* invokeMethodInstance = GetRawMethodInstanceAtIdx(paramsType->ToTypeInstance(), 0, "Invoke");
  17426. if (invokeMethodInstance != NULL)
  17427. {
  17428. // This is only for the case where the delegate didn't actually have any params so the composite is zero-sized
  17429. // and wasn't cleared by the preceding loop
  17430. BF_ASSERT(invokeMethodInstance->GetParamCount() == 0);
  17431. BfLocalVariable* localVar = new BfLocalVariable();
  17432. localVar->mName = paramDef->mName;
  17433. localVar->mResolvedType = paramsType;
  17434. localVar->mCompositeCount = 0;
  17435. DoAddLocalVariable(localVar);
  17436. }
  17437. }
  17438. }
  17439. }
  17440. }
  17441. void BfModule::ProcessMethod_ProcessDeferredLocals(int startIdx)
  17442. {
  17443. // if (mCurMethodState->mPrevMethodState != NULL) // Re-entry
  17444. // return;
  17445. auto startMethodState = mCurMethodState;
  17446. auto _ClearState = [&]()
  17447. {
  17448. mCurMethodState->mLocalMethods.Clear();
  17449. for (auto& local : mCurMethodState->mLocals)
  17450. {
  17451. if (local->mIsBumpAlloc)
  17452. local->~BfLocalVariable();
  17453. else
  17454. delete local;
  17455. }
  17456. mCurMethodState->mLocals.Clear();
  17457. mCurMethodState->mLocalVarSet.Clear();
  17458. };
  17459. while (true)
  17460. {
  17461. bool didWork = false;
  17462. // 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
  17463. // we show errors in the capture phase. If we somehow pass the capture phase without error then this method WILL show any errors here,
  17464. // however (compiler bug), so this is the safest way
  17465. if (!mCurMethodState->mDeferredLocalMethods.IsEmpty())
  17466. {
  17467. for (int deferredLocalMethodIdx = 0; deferredLocalMethodIdx < (int)mCurMethodState->mDeferredLocalMethods.size(); deferredLocalMethodIdx++)
  17468. {
  17469. auto deferredLocalMethod = mCurMethodState->mDeferredLocalMethods[deferredLocalMethodIdx];
  17470. BfLogSysM("Processing deferred local method %p\n", deferredLocalMethod);
  17471. if (!mHadBuildError)
  17472. {
  17473. // Process as a closure - that allows us to look back and see the const locals and stuff
  17474. BfClosureState closureState;
  17475. mCurMethodState->mClosureState = &closureState;
  17476. closureState.mConstLocals = deferredLocalMethod->mConstLocals;
  17477. closureState.mReturnType = deferredLocalMethod->mMethodInstance->mReturnType;
  17478. closureState.mActiveDeferredLocalMethod = deferredLocalMethod;
  17479. closureState.mLocalMethod = deferredLocalMethod->mLocalMethod;
  17480. if (deferredLocalMethod->mMethodInstance->mMethodInfoEx != NULL)
  17481. closureState.mClosureInstanceInfo = deferredLocalMethod->mMethodInstance->mMethodInfoEx->mClosureInstanceInfo;
  17482. mCurMethodState->mMixinState = deferredLocalMethod->mLocalMethod->mDeclMixinState;
  17483. _ClearState();
  17484. for (auto& constLocal : deferredLocalMethod->mConstLocals)
  17485. {
  17486. auto localVar = new BfLocalVariable();
  17487. *localVar = constLocal;
  17488. DoAddLocalVariable(localVar);
  17489. }
  17490. mCurMethodState->mLocalMethods = deferredLocalMethod->mLocalMethods;
  17491. bool doProcess = !mCompiler->mCanceling;
  17492. if (doProcess)
  17493. {
  17494. BP_ZONE_F("ProcessMethod local %s", deferredLocalMethod->mMethodInstance->mMethodDef->mName.c_str());
  17495. ProcessMethod(deferredLocalMethod->mMethodInstance);
  17496. }
  17497. }
  17498. delete deferredLocalMethod;
  17499. mContext->CheckLockYield();
  17500. didWork = true;
  17501. }
  17502. mCurMethodState->mDeferredLocalMethods.Clear();
  17503. }
  17504. for (auto& kv : mCurMethodState->mLocalMethodCache)
  17505. {
  17506. BF_ASSERT((kv.mValue->mMethodDef == NULL) || (kv.mKey == kv.mValue->mMethodDef->mName));
  17507. }
  17508. if ((!mCurMethodState->mDeferredLambdaInstances.IsEmpty()) && (!mHadBuildError))
  17509. {
  17510. for (int deferredLambdaIdx = 0; deferredLambdaIdx < (int)mCurMethodState->mDeferredLambdaInstances.size(); deferredLambdaIdx++)
  17511. {
  17512. auto lambdaInstance = mCurMethodState->mDeferredLambdaInstances[deferredLambdaIdx];
  17513. BfLogSysM("Processing deferred lambdaInstance %p\n", lambdaInstance);
  17514. BfClosureState closureState;
  17515. mCurMethodState->mClosureState = &closureState;
  17516. //closureState.mConstLocals = deferredLocalMethod->mConstLocals;
  17517. closureState.mReturnType = lambdaInstance->mMethodInstance->mReturnType;
  17518. if (lambdaInstance->mClosureTypeInstance != NULL)
  17519. closureState.mClosureType = lambdaInstance->mClosureTypeInstance;
  17520. else
  17521. closureState.mClosureType = lambdaInstance->mDelegateTypeInstance;
  17522. closureState.mClosureInstanceInfo = lambdaInstance->mMethodInstance->mMethodInfoEx->mClosureInstanceInfo;
  17523. closureState.mDeclaringMethodIsMutating = lambdaInstance->mDeclaringMethodIsMutating;
  17524. mCurMethodState->mMixinState = lambdaInstance->mDeclMixinState;
  17525. _ClearState();
  17526. for (auto& constLocal : lambdaInstance->mConstLocals)
  17527. {
  17528. //if (constLocal.mIsThis)
  17529. {
  17530. // Valueless 'this'
  17531. closureState.mConstLocals.Add(constLocal);
  17532. }
  17533. /*else
  17534. {
  17535. auto localVar = new BfLocalVariable();
  17536. *localVar = constLocal;
  17537. DoAddLocalVariable(localVar);
  17538. }*/
  17539. }
  17540. BfMethodInstanceGroup methodInstanceGroup;
  17541. methodInstanceGroup.mOwner = mCurTypeInstance;
  17542. methodInstanceGroup.mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  17543. bool doProcess = !mCompiler->mCanceling;
  17544. if (doProcess)
  17545. {
  17546. BP_ZONE_F("ProcessMethod lambdaInstance %s", lambdaInstance->mMethodInstance->mMethodDef->mName.c_str());
  17547. lambdaInstance->mMethodInstance->mMethodInstanceGroup = &methodInstanceGroup;
  17548. ProcessMethod(lambdaInstance->mMethodInstance);
  17549. lambdaInstance->mMethodInstance->mMethodInstanceGroup = NULL;
  17550. if (lambdaInstance->mDtorMethodInstance != NULL)
  17551. {
  17552. lambdaInstance->mDtorMethodInstance->mMethodInstanceGroup = &methodInstanceGroup;
  17553. auto startMethodState2 = mCurMethodState;
  17554. ProcessMethod(lambdaInstance->mDtorMethodInstance);
  17555. lambdaInstance->mDtorMethodInstance->mMethodInstanceGroup = NULL;
  17556. }
  17557. }
  17558. didWork = true;
  17559. }
  17560. mContext->CheckLockYield();
  17561. mCurMethodState->mDeferredLambdaInstances.Clear();
  17562. }
  17563. if (!didWork)
  17564. break;
  17565. }
  17566. }
  17567. void BfModule::EmitGCMarkValue(BfTypedValue& thisValue, BfType* checkType, int memberDepth, int curOffset, HashSet<int>& objectOffsets, BfModuleMethodInstance markFromGCThreadMethodInstance, bool isAppendObject)
  17568. {
  17569. if (checkType->IsComposite())
  17570. PopulateType(checkType, BfPopulateType_Data);
  17571. if (!checkType->WantsGCMarking())
  17572. return;
  17573. if (checkType->IsDeleting())
  17574. {
  17575. mCompiler->RequestExtraCompile();
  17576. InternalError("EmitGCMarkValue deleted type");
  17577. return;
  17578. }
  17579. auto typeInstance = checkType->ToTypeInstance();
  17580. bool callMarkMethod = false;
  17581. // Call the actual marking method
  17582. if (memberDepth == 0)
  17583. {
  17584. // Don't call marking method on self
  17585. }
  17586. else if (checkType->IsObjectOrInterface())
  17587. {
  17588. if (!objectOffsets.Add(curOffset))
  17589. {
  17590. return;
  17591. }
  17592. callMarkMethod = true;
  17593. }
  17594. else if (checkType->IsSizedArray())
  17595. {
  17596. BfSizedArrayType* sizedArrayType = (BfSizedArrayType*)checkType;
  17597. if (sizedArrayType->mElementType->WantsGCMarking())
  17598. {
  17599. BfTypedValue arrayValue = thisValue;
  17600. if (thisValue.mType != checkType)
  17601. {
  17602. BfIRValue srcValue = thisValue.mValue;
  17603. if (curOffset != 0)
  17604. {
  17605. if (!thisValue.mType->IsPointer())
  17606. {
  17607. auto int8Type = GetPrimitiveType(BfTypeCode_UInt8);
  17608. auto int8PtrType = CreatePointerType(int8Type);
  17609. srcValue = mBfIRBuilder->CreateBitCast(thisValue.mValue, mBfIRBuilder->MapType(int8PtrType));
  17610. }
  17611. srcValue = mBfIRBuilder->CreateInBoundsGEP(srcValue, curOffset);
  17612. }
  17613. arrayValue = BfTypedValue(mBfIRBuilder->CreateBitCast(srcValue, mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapType(checkType))), checkType, BfTypedValueKind_Addr);
  17614. }
  17615. if (sizedArrayType->mElementCount > 6)
  17616. {
  17617. auto intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  17618. auto itr = CreateAlloca(intPtrType);
  17619. mBfIRBuilder->CreateStore(GetDefaultValue(intPtrType), itr);
  17620. auto loopBB = mBfIRBuilder->CreateBlock("loop", true);
  17621. auto bodyBB = mBfIRBuilder->CreateBlock("body", true);
  17622. auto doneBB = mBfIRBuilder->CreateBlock("done", true);
  17623. mBfIRBuilder->CreateBr(loopBB);
  17624. mBfIRBuilder->SetInsertPoint(loopBB);
  17625. auto loadedItr = mBfIRBuilder->CreateLoad(itr);
  17626. auto cmpRes = mBfIRBuilder->CreateCmpGTE(loadedItr, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, (uint64)sizedArrayType->mElementCount), true);
  17627. mBfIRBuilder->CreateCondBr(cmpRes, doneBB, bodyBB);
  17628. mBfIRBuilder->SetInsertPoint(bodyBB);
  17629. auto ptrType = CreatePointerType(sizedArrayType->mElementType);
  17630. auto ptrValue = mBfIRBuilder->CreateBitCast(arrayValue.mValue, mBfIRBuilder->MapType(ptrType));
  17631. auto gepResult = mBfIRBuilder->CreateInBoundsGEP(ptrValue, loadedItr);
  17632. auto value = BfTypedValue(gepResult, sizedArrayType->mElementType, BfTypedValueKind_Addr);
  17633. EmitGCMarkValue(value, markFromGCThreadMethodInstance);
  17634. auto incValue = mBfIRBuilder->CreateAdd(loadedItr, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 1));
  17635. mBfIRBuilder->CreateStore(incValue, itr);
  17636. mBfIRBuilder->CreateBr(loopBB);
  17637. mBfIRBuilder->SetInsertPoint(doneBB);
  17638. }
  17639. else
  17640. {
  17641. for (int dataIdx = 0; dataIdx < sizedArrayType->mElementCount; dataIdx++)
  17642. {
  17643. auto ptrType = CreatePointerType(sizedArrayType->mElementType);
  17644. auto ptrValue = mBfIRBuilder->CreateBitCast(arrayValue.mValue, mBfIRBuilder->MapType(ptrType));
  17645. auto gepResult = mBfIRBuilder->CreateInBoundsGEP(ptrValue, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, dataIdx));
  17646. auto value = BfTypedValue(gepResult, sizedArrayType->mElementType, BfTypedValueKind_Addr);
  17647. HashSet<int> objectOffsets;
  17648. EmitGCMarkValue(value, markFromGCThreadMethodInstance);
  17649. }
  17650. }
  17651. }
  17652. }
  17653. else if (typeInstance != NULL)
  17654. {
  17655. typeInstance->mTypeDef->PopulateMemberSets();
  17656. BfMemberSetEntry* entry = NULL;
  17657. BfMethodDef* methodDef = NULL;
  17658. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(String(BF_METHODNAME_MARKMEMBERS), &entry))
  17659. {
  17660. methodDef = (BfMethodDef*)entry->mMemberDef;
  17661. if (methodDef->HasBody())
  17662. {
  17663. callMarkMethod = true;
  17664. }
  17665. }
  17666. }
  17667. if (callMarkMethod)
  17668. {
  17669. BfTypedValue markValue;
  17670. auto memberType = checkType;
  17671. if (memberType->IsObjectOrInterface())
  17672. memberType = mContext->mBfObjectType; // Just to avoid that extra cast for the call itself
  17673. auto memberPtrType = CreatePointerType(memberType);
  17674. if (curOffset == 0)
  17675. {
  17676. markValue = BfTypedValue(mBfIRBuilder->CreateBitCast(thisValue.mValue, mBfIRBuilder->MapType(memberPtrType)), memberType, true);
  17677. }
  17678. else
  17679. {
  17680. if (!thisValue.mType->IsPointer())
  17681. {
  17682. auto int8Type = GetPrimitiveType(BfTypeCode_UInt8);
  17683. auto int8PtrType = CreatePointerType(int8Type);
  17684. thisValue = BfTypedValue(mBfIRBuilder->CreateBitCast(thisValue.mValue, mBfIRBuilder->MapType(int8PtrType)), int8PtrType);
  17685. }
  17686. auto offsetValue = mBfIRBuilder->CreateInBoundsGEP(thisValue.mValue, curOffset);
  17687. markValue = BfTypedValue(mBfIRBuilder->CreateBitCast(offsetValue, mBfIRBuilder->MapType(memberPtrType)), memberType, true);
  17688. }
  17689. if (isAppendObject)
  17690. EmitGCMarkAppended(markValue);
  17691. else
  17692. EmitGCMarkValue(markValue, markFromGCThreadMethodInstance);
  17693. return;
  17694. }
  17695. auto methodDef = mCurMethodInstance->mMethodDef;
  17696. if (checkType->IsPayloadEnum())
  17697. {
  17698. for (auto& fieldInst : typeInstance->mFieldInstances)
  17699. {
  17700. if (!fieldInst.mIsEnumPayloadCase)
  17701. continue;
  17702. auto fieldDef = fieldInst.GetFieldDef();
  17703. EmitGCMarkValue(thisValue, fieldInst.mResolvedType, memberDepth + 1, curOffset, objectOffsets, markFromGCThreadMethodInstance);
  17704. }
  17705. return;
  17706. }
  17707. if (typeInstance == NULL)
  17708. return;
  17709. for (auto& fieldInst : typeInstance->mFieldInstances)
  17710. {
  17711. auto fieldDef = fieldInst.GetFieldDef();
  17712. if (fieldDef == NULL)
  17713. continue;
  17714. if (fieldDef->mIsStatic)
  17715. continue;
  17716. if (typeInstance == mCurTypeInstance)
  17717. {
  17718. // Note: we don't do method chaining when we are marking members of members. Theoretically this means
  17719. // we may be marking member values that can never contain a value anyway, but this is benign
  17720. if ((fieldDef->mDeclaringType->mTypeDeclaration != methodDef->mDeclaringType->mTypeDeclaration))
  17721. continue;
  17722. }
  17723. EmitGCMarkValue(thisValue, fieldInst.mResolvedType, memberDepth + 1, curOffset + fieldInst.mDataOffset, objectOffsets, markFromGCThreadMethodInstance, fieldInst.IsAppendedObject());
  17724. }
  17725. if ((typeInstance->mBaseType != NULL) && (typeInstance->mBaseType != mContext->mBfObjectType))
  17726. {
  17727. EmitGCMarkValue(thisValue, typeInstance->mBaseType, memberDepth, curOffset, objectOffsets, markFromGCThreadMethodInstance);
  17728. }
  17729. }
  17730. void BfModule::EmitGCMarkMembers()
  17731. {
  17732. auto methodDef = mCurMethodInstance->mMethodDef;
  17733. auto gcType = ResolveTypeDef(mCompiler->mGCTypeDef, BfPopulateType_DataAndMethods);
  17734. BfModuleMethodInstance markFromGCThreadMethodInstance;
  17735. if (gcType != NULL)
  17736. markFromGCThreadMethodInstance = GetMethodByName(gcType->ToTypeInstance(), "Mark", 1);
  17737. if ((markFromGCThreadMethodInstance.mMethodInstance != NULL) && (!mCurMethodInstance->mIsUnspecialized))
  17738. {
  17739. if (mCurTypeInstance->IsBoxed())
  17740. {
  17741. // This already gets filled in by the normal boxed forwarding
  17742. }
  17743. else
  17744. {
  17745. auto thisValue = GetThis();
  17746. if (thisValue.IsSplat())
  17747. {
  17748. BfIRFunction func = mCurMethodInstance->mIRFunction;
  17749. int argIdx = 0;
  17750. std::function<void(BfType*)> checkTypeLambda = [&](BfType* checkType)
  17751. {
  17752. if (checkType->IsStruct())
  17753. {
  17754. auto checkTypeInstance = checkType->ToTypeInstance();
  17755. if (checkTypeInstance->mBaseType != NULL)
  17756. checkTypeLambda(checkTypeInstance->mBaseType);
  17757. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  17758. {
  17759. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  17760. if (fieldInstance->mDataIdx >= 0)
  17761. checkTypeLambda(fieldInstance->GetResolvedType());
  17762. }
  17763. }
  17764. else if (checkType->IsMethodRef())
  17765. {
  17766. BFMODULE_FATAL(this, "Not handled");
  17767. }
  17768. else if (checkType->WantsGCMarking())
  17769. {
  17770. BfTypedValue markValue(mBfIRBuilder->GetArgument(argIdx), checkType);
  17771. EmitGCMarkValue(markValue, markFromGCThreadMethodInstance);
  17772. argIdx++;
  17773. }
  17774. };
  17775. checkTypeLambda(thisValue.mType);
  17776. }
  17777. else if (!methodDef->mIsStatic)
  17778. {
  17779. if ((mCurTypeInstance->mBaseType != NULL) && (!mCurTypeInstance->IsTypedPrimitive()) && (mCurTypeInstance->mBaseType->WantsGCMarking()))
  17780. {
  17781. BfModuleMethodInstance moduleMethodInst = GetMethodByName(mCurTypeInstance->mBaseType, BF_METHODNAME_MARKMEMBERS, 0, true);
  17782. if (moduleMethodInst)
  17783. {
  17784. auto methodBaseType = moduleMethodInst.mMethodInstance->GetOwner();
  17785. bool wantsBaseMarking = true;
  17786. if (methodBaseType == mContext->mBfObjectType)
  17787. {
  17788. wantsBaseMarking = false;
  17789. PopulateType(methodBaseType);
  17790. for (auto& fieldInstance : mContext->mBfObjectType->mFieldInstances)
  17791. {
  17792. if ((fieldInstance.GetFieldDef()->mDeclaringType->IsExtension()) &&
  17793. (fieldInstance.mResolvedType->WantsGCMarking()))
  17794. wantsBaseMarking = true;
  17795. }
  17796. }
  17797. if (wantsBaseMarking)
  17798. {
  17799. auto thisValue = GetThis();
  17800. auto baseValue = Cast(NULL, thisValue, methodBaseType, BfCastFlags_Explicit);
  17801. SizedArray<BfIRValue, 1> args;
  17802. if ((!mIsComptimeModule) && (moduleMethodInst.mMethodInstance->GetParamIsSplat(-1)))
  17803. {
  17804. BfExprEvaluator exprEvaluator(this);
  17805. exprEvaluator.SplatArgs(baseValue, args);
  17806. }
  17807. else
  17808. {
  17809. args.push_back(baseValue.mValue);
  17810. }
  17811. mBfIRBuilder->CreateCall(moduleMethodInst.mFunc, args);
  17812. }
  17813. }
  17814. }
  17815. }
  17816. if (!methodDef->mIsStatic)
  17817. {
  17818. HashSet<int> objectOffsets;
  17819. EmitGCMarkValue(thisValue, mCurTypeInstance, 0, 0, objectOffsets, markFromGCThreadMethodInstance);
  17820. }
  17821. else
  17822. {
  17823. for (auto& fieldInst : mCurTypeInstance->mFieldInstances)
  17824. {
  17825. if (thisValue.IsSplat())
  17826. break;
  17827. auto fieldDef = fieldInst.GetFieldDef();
  17828. if (fieldDef == NULL)
  17829. continue;
  17830. if (IsThreadLocal(&fieldInst))
  17831. continue;
  17832. if (fieldDef->mIsStatic == methodDef->mIsStatic)
  17833. {
  17834. // For extensions, only handle these fields in the appropriate extension
  17835. if ((fieldDef->mDeclaringType->mTypeDeclaration != methodDef->mDeclaringType->mTypeDeclaration))
  17836. continue;
  17837. if (!fieldInst.mFieldIncluded)
  17838. continue;
  17839. auto fieldType = fieldInst.mResolvedType;
  17840. auto fieldDef = fieldInst.GetFieldDef();
  17841. BfTypedValue markVal;
  17842. if (fieldDef->mIsConst)
  17843. continue;
  17844. if ((!fieldType->IsObjectOrInterface()) && (!fieldType->IsComposite()))
  17845. continue;
  17846. mBfIRBuilder->PopulateType(fieldType);
  17847. if (fieldType->IsValuelessType())
  17848. continue;
  17849. if ((fieldDef->mIsStatic) && (!fieldDef->mIsConst))
  17850. {
  17851. StringT<512> staticVarName;
  17852. BfMangler::Mangle(staticVarName, mCompiler->GetMangleKind(), &fieldInst);
  17853. if (staticVarName.StartsWith('#'))
  17854. continue;
  17855. markVal = ReferenceStaticField(&fieldInst);
  17856. }
  17857. else if (!fieldDef->mIsStatic)
  17858. {
  17859. if (fieldInst.IsAppendedObject())
  17860. {
  17861. auto fieldAddr = mBfIRBuilder->CreateInBoundsGEP(mCurMethodState->mLocals[0]->mValue, 0, fieldInst.mDataIdx);
  17862. auto val = mBfIRBuilder->CreateBitCast(fieldAddr, mBfIRBuilder->MapType(mContext->mBfObjectType));
  17863. markVal = BfTypedValue(mBfIRBuilder->CreateBitCast(fieldAddr, mBfIRBuilder->MapType(fieldInst.mResolvedType)), fieldInst.mResolvedType);
  17864. }
  17865. else
  17866. {
  17867. markVal = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(thisValue.mValue, 0, fieldInst.mDataIdx/*, fieldDef->mName*/), fieldInst.mResolvedType, true);
  17868. }
  17869. }
  17870. if (markVal)
  17871. {
  17872. if ((fieldInst.IsAppendedObject()) && (!fieldDef->mIsStatic))
  17873. EmitGCMarkAppended(markVal);
  17874. else
  17875. EmitGCMarkValue(markVal, markFromGCThreadMethodInstance);
  17876. }
  17877. }
  17878. }
  17879. }
  17880. if (mCurMethodInstance->mChainType == BfMethodChainType_ChainHead)
  17881. CallChainedMethods(mCurMethodInstance, false);
  17882. }
  17883. }
  17884. // If there are appends then we just need the rootmost append type to do the Dbg_MarkAppended
  17885. if ((!mIsComptimeModule) && (!methodDef->mIsStatic) && (mCompiler->mOptions.mDebugAlloc) &&
  17886. (mCurTypeInstance->HasAppendCtor()) && (!mCurTypeInstance->BaseHasAppendCtor()))
  17887. {
  17888. auto thisValue = GetThis();
  17889. auto appendedObj = mBfIRBuilder->CreateBitCast(thisValue.mValue, mBfIRBuilder->MapType(mContext->mBfObjectType));
  17890. BfModuleMethodInstance allocMethod = GetInternalMethod("Dbg_MarkAppended", 1);
  17891. SizedArray<BfIRValue, 1> llvmArgs;
  17892. llvmArgs.push_back(appendedObj);
  17893. if (allocMethod)
  17894. mBfIRBuilder->CreateCall(allocMethod.mFunc, llvmArgs);
  17895. }
  17896. }
  17897. void BfModule::EmitGCFindTLSMembers()
  17898. {
  17899. auto methodDef = mCurMethodInstance->mMethodDef;
  17900. auto gcTypeInst = ResolveTypeDef(mCompiler->mGCTypeDef)->ToTypeInstance();
  17901. auto reportTLSMark = GetMethodByName(gcTypeInst, "ReportTLSMember", 2);
  17902. BF_ASSERT(reportTLSMark);
  17903. for (auto& fieldInst : mCurTypeInstance->mFieldInstances)
  17904. {
  17905. auto fieldDef = fieldInst.GetFieldDef();
  17906. if (fieldDef == NULL)
  17907. continue;
  17908. if (!IsThreadLocal(&fieldInst))
  17909. continue;
  17910. // For extensions, only handle these fields in the appropriate extension
  17911. if ((fieldDef->mDeclaringType->mTypeDeclaration != methodDef->mDeclaringType->mTypeDeclaration))
  17912. continue;
  17913. if (!fieldInst.mFieldIncluded)
  17914. continue;
  17915. if (fieldDef->mIsConst)
  17916. continue;
  17917. auto fieldType = fieldInst.mResolvedType;
  17918. if ((!fieldType->IsObjectOrInterface()) && (!fieldType->IsComposite()))
  17919. continue;
  17920. if (fieldType->IsValuelessType())
  17921. continue;
  17922. BfTypedValue markVal = ReferenceStaticField(&fieldInst);
  17923. if (markVal)
  17924. {
  17925. BfIRValue fieldRefPtr = mBfIRBuilder->CreateBitCast(markVal.mValue, mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr)));
  17926. BfIRValue markFuncPtr = GetMarkFuncPtr(fieldType);
  17927. SizedArray<BfIRValue, 2> llvmArgs;
  17928. llvmArgs.push_back(fieldRefPtr);
  17929. llvmArgs.push_back(markFuncPtr);
  17930. mBfIRBuilder->CreateCall(reportTLSMark.mFunc, llvmArgs);
  17931. }
  17932. }
  17933. if (mCurMethodInstance->mChainType == BfMethodChainType_ChainHead)
  17934. CallChainedMethods(mCurMethodInstance, false);
  17935. }
  17936. void BfModule::ProcessMethod(BfMethodInstance* methodInstance, bool isInlineDup, bool forceIRWrites)
  17937. {
  17938. BP_ZONE_F("BfModule::ProcessMethod %s", BP_DYN_STR(methodInstance->mMethodDef->mName.c_str()));
  17939. if (mIsComptimeModule)
  17940. {
  17941. BF_ASSERT(!mCompiler->IsAutocomplete());
  17942. }
  17943. if (mAwaitingInitFinish)
  17944. FinishInit();
  17945. if ((methodInstance->mIsReified) && (!mCompiler->mIsResolveOnly))
  17946. {
  17947. BfLogSysM("REIFIED(ProcessMethod): %s %p Module: %s\n", methodInstance->mMethodDef->mName.c_str(), methodInstance, mModuleName.c_str());
  17948. }
  17949. // Reify types that are actually used - they don't get reified during method declaration
  17950. if ((!mCompiler->mIsResolveOnly) && (mIsReified))
  17951. {
  17952. auto _CheckType = [&](BfType* type)
  17953. {
  17954. if (!type->IsReified())
  17955. PopulateType(type, BfPopulateType_Declaration);
  17956. };
  17957. _CheckType(methodInstance->mReturnType);
  17958. for (auto& param : methodInstance->mParams)
  17959. {
  17960. _CheckType(param.mResolvedType);
  17961. }
  17962. }
  17963. if (!methodInstance->mIsReified)
  17964. BF_ASSERT(!mIsReified);
  17965. BF_ASSERT((!methodInstance->GetOwner()->IsUnspecializedTypeVariation()) || (mIsComptimeModule));
  17966. if (methodInstance->mMethodInfoEx != NULL)
  17967. {
  17968. for (auto methodGenericArg : methodInstance->mMethodInfoEx->mMethodGenericArguments)
  17969. {
  17970. if (methodGenericArg->IsMethodRef())
  17971. {
  17972. auto methodRefType = (BfMethodRefType*)methodGenericArg;
  17973. BF_ASSERT(methodRefType->mOwnerRevision == methodRefType->mOwner->mRevision);
  17974. }
  17975. }
  17976. }
  17977. if (mBfIRBuilder == NULL)
  17978. {
  17979. BfLogSysM("ProcessMethod %p calling EnsureIRBuilder\n", methodInstance);
  17980. EnsureIRBuilder();
  17981. }
  17982. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, (mWantsIRIgnoreWrites || methodInstance->mIsUnspecialized) && (!forceIRWrites));
  17983. if ((HasCompiledOutput()) && (!mBfIRBuilder->mIgnoreWrites))
  17984. {
  17985. BF_ASSERT(!methodInstance->mIRFunction.IsFake() || (methodInstance->GetImportCallKind() != BfImportCallKind_None));
  17986. }
  17987. SetAndRestoreValue<bool> prevIsClassifying;
  17988. if (((methodInstance->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend) || (methodInstance->mIsForeignMethodDef) || (methodInstance->IsSpecializedGenericMethod())) &&
  17989. (mCompiler->mResolvePassData != NULL))
  17990. {
  17991. // Don't classify on the CtorCalcAppend, just on the actual Ctor
  17992. prevIsClassifying.Init(mCompiler->mResolvePassData->mIsClassifying, false);
  17993. }
  17994. if (methodInstance->mHasBeenProcessed)
  17995. {
  17996. BfLogSysM("ProcessMethod %p HasBeenProcessed\n", methodInstance);
  17997. return;
  17998. }
  17999. if (methodInstance->mFailedConstraints)
  18000. {
  18001. // The only way this should be able to happen is if we fail our generic param check
  18002. BF_ASSERT(methodInstance->IsSpecializedGenericMethod());
  18003. BfLogSysM("Method instance marked as 'failed' at start of ProcessMethod %p\n", methodInstance);
  18004. methodInstance->mHasBeenProcessed = true;
  18005. return;
  18006. }
  18007. if (HasExecutedOutput())
  18008. {
  18009. BF_ASSERT(mIsModuleMutable);
  18010. }
  18011. BfMethodInstance* defaultMethodInstance = methodInstance->mMethodInstanceGroup->mDefault;
  18012. if (!mIsComptimeModule)
  18013. {
  18014. BF_ASSERT(methodInstance->mMethodInstanceGroup->mOnDemandKind != BfMethodOnDemandKind_NotSet);
  18015. if ((methodInstance->mMethodInstanceGroup->mOnDemandKind != BfMethodOnDemandKind_AlwaysInclude) &&
  18016. (methodInstance->mMethodInstanceGroup->mOnDemandKind != BfMethodOnDemandKind_Referenced))
  18017. {
  18018. auto owningModule = methodInstance->GetOwner()->mModule;
  18019. if (owningModule->mIsScratchModule)
  18020. {
  18021. BF_ASSERT(owningModule->mOnDemandMethodCount == 0);
  18022. }
  18023. else
  18024. {
  18025. BF_ASSERT((owningModule->mOnDemandMethodCount > 0) || (!HasCompiledOutput()) || (owningModule->mExtensionCount > 0));
  18026. if (owningModule->mOnDemandMethodCount > 0)
  18027. owningModule->mOnDemandMethodCount--;
  18028. }
  18029. methodInstance->mMethodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_Referenced;
  18030. VerifyOnDemandMethods();
  18031. }
  18032. }
  18033. // We set mHasBeenProcessed to true immediately -- this helps avoid stack overflow during recursion for things like
  18034. // self-referencing append allocations in ctor@calcAppend
  18035. methodInstance->mHasBeenProcessed = true;
  18036. mIncompleteMethodCount--;
  18037. BF_ASSERT((mIsSpecialModule) || (mIncompleteMethodCount >= 0));
  18038. auto typeDef = methodInstance->mMethodInstanceGroup->mOwner->mTypeDef;
  18039. auto methodDef = methodInstance->mMethodDef;
  18040. auto methodDeclaration = methodDef->GetMethodDeclaration();
  18041. if ((methodDef->mHasComptime) && (!mIsComptimeModule))
  18042. mBfIRBuilder->mIgnoreWrites = true;
  18043. if ((methodInstance->mIsReified) && (methodInstance->mVirtualTableIdx != -1))
  18044. {
  18045. // If we reify a virtual method in a HotCompile then we need to make sure the type data gets written out
  18046. // so we get the new vdata for it
  18047. methodInstance->GetOwner()->mDirty = true;
  18048. }
  18049. int dependentGenericStartIdx = 0;
  18050. if ((methodDef->mIsLocalMethod) && (mCurMethodState != NULL)) // See DoMethodDeclaration for an explaination of dependentGenericStartIdx
  18051. dependentGenericStartIdx = (int)mCurMethodState->GetRootMethodState()->mMethodInstance->GetNumGenericArguments();
  18052. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, methodInstance);
  18053. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, methodInstance->mMethodInstanceGroup->mOwner);
  18054. SetAndRestoreValue<BfFilePosition> prevFilePos(mCurFilePosition);
  18055. SetAndRestoreValue<bool> prevHadBuildError(mHadBuildError, false);
  18056. SetAndRestoreValue<bool> prevHadWarning(mHadBuildWarning, false);
  18057. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors);
  18058. SetAndRestoreValue<bool> prevIgnoreWarnings(mIgnoreWarnings, mIsComptimeModule);
  18059. if ((!mIsComptimeModule) && (methodInstance->mIsReified) &&
  18060. ((methodDef->mMethodType == BfMethodType_Ctor) || (methodDef->mMethodType == BfMethodType_CtorNoBody)))
  18061. {
  18062. mCurTypeInstance->mHasBeenInstantiated = true;
  18063. }
  18064. // Warnings are shown in the capture phase
  18065. if ((methodDef->mIsLocalMethod) || (mCurTypeInstance->IsClosure()))
  18066. mIgnoreWarnings = true;
  18067. if ((methodDeclaration == NULL) && (mCurMethodState == NULL))
  18068. UseDefaultSrcPos();
  18069. if ((mIsComptimeModule) && (methodDef->mIsStatic))
  18070. {
  18071. PopulateType(mCurTypeInstance, BfPopulateType_AllowStaticMethods);
  18072. }
  18073. else
  18074. {
  18075. // We may not actually be populated in relatively rare autocompelte cases
  18076. PopulateType(mCurTypeInstance, BfPopulateType_DataAndMethods);
  18077. mBfIRBuilder->PopulateType(mCurTypeInstance, BfIRPopulateType_Full);
  18078. }
  18079. BfAstNode* nameNode = NULL;
  18080. if (methodDeclaration != NULL)
  18081. {
  18082. nameNode = methodDeclaration->mNameNode;
  18083. if (nameNode == NULL)
  18084. {
  18085. if (auto ctorDeclaration = BfNodeDynCast<BfConstructorDeclaration>(methodDeclaration))
  18086. nameNode = ctorDeclaration->mThisToken;
  18087. }
  18088. }
  18089. if ((mCompiler->mResolvePassData != NULL) && (methodDeclaration != NULL) && (nameNode != NULL) &&
  18090. (mCompiler->mResolvePassData->mGetSymbolReferenceKind == BfGetSymbolReferenceKind_Method) &&
  18091. (methodDef->mIdx >= 0) && (!methodInstance->mIsForeignMethodDef))
  18092. {
  18093. if (methodInstance->GetExplicitInterface() == NULL)
  18094. mCompiler->mResolvePassData->HandleMethodReference(nameNode, typeDef, methodDef);
  18095. else
  18096. {
  18097. for (auto& ifaceEntry : mCurTypeInstance->mInterfaces)
  18098. {
  18099. auto ifaceInst = ifaceEntry.mInterfaceType;
  18100. int startIdx = ifaceEntry.mStartInterfaceTableIdx;
  18101. int iMethodCount = (int)ifaceInst->mMethodInstanceGroups.size();
  18102. if (methodInstance->GetExplicitInterface() != ifaceInst)
  18103. continue;
  18104. ifaceInst->mTypeDef->PopulateMemberSets();
  18105. BfMethodDef* nextMethod = NULL;
  18106. BfMemberSetEntry* entry = NULL;
  18107. if (ifaceInst->mTypeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  18108. nextMethod = (BfMethodDef*)entry->mMemberDef;
  18109. while (nextMethod != NULL)
  18110. {
  18111. auto checkMethod = nextMethod;
  18112. nextMethod = nextMethod->mNextWithSameName;
  18113. BfMethodInstance* implMethodInst = mCurTypeInstance->mInterfaceMethodTable[startIdx + checkMethod->mIdx].mMethodRef;
  18114. if (implMethodInst == methodInstance)
  18115. {
  18116. auto ifaceMethodDef = ifaceInst->mTypeDef->mMethods[checkMethod->mIdx];
  18117. mCompiler->mResolvePassData->HandleMethodReference(nameNode, ifaceInst->mTypeDef, ifaceMethodDef);
  18118. }
  18119. }
  18120. }
  18121. }
  18122. if (methodDef->mIsOverride)
  18123. {
  18124. for (int virtIdx = 0; virtIdx < (int)mCurTypeInstance->mVirtualMethodTable.size(); virtIdx++)
  18125. {
  18126. auto& ventry = mCurTypeInstance->mVirtualMethodTable[virtIdx];
  18127. if (ventry.mDeclaringMethod.mMethodNum == -1)
  18128. continue;
  18129. BfMethodInstance* virtMethod = ventry.mImplementingMethod;
  18130. if (virtMethod != NULL)
  18131. {
  18132. if (virtMethod == methodInstance)
  18133. {
  18134. // Is matching method
  18135. if (virtIdx < (int)mCurTypeInstance->mBaseType->mVirtualMethodTable.size())
  18136. {
  18137. auto baseType = mCurTypeInstance->mBaseType;
  18138. if (baseType != NULL)
  18139. {
  18140. while ((baseType->mBaseType != NULL) && (virtIdx < baseType->mBaseType->mVirtualMethodTableSize))
  18141. baseType = baseType->mBaseType;
  18142. BfMethodInstance* baseVirtMethod = baseType->mVirtualMethodTable[virtIdx].mImplementingMethod;
  18143. mCompiler->mResolvePassData->HandleMethodReference(nameNode, baseType->mTypeDef, baseVirtMethod->mMethodDef);
  18144. }
  18145. }
  18146. break;
  18147. }
  18148. }
  18149. }
  18150. }
  18151. }
  18152. BfLogSysM("ProcessMethod %p Unspecialized: %d Module: %p IRFunction: %d Reified: %d Incomplete:%d\n", methodInstance, mCurTypeInstance->IsUnspecializedType(), this, methodInstance->mIRFunction.mId, methodInstance->mIsReified, mIncompleteMethodCount);
  18153. int importStrNum = -1;
  18154. auto importKind = methodInstance->GetImportKind();
  18155. if ((!mCompiler->mIsResolveOnly) &&
  18156. ((importKind == BfImportKind_Import_Static) || (importKind == BfImportKind_Import_Dynamic)))
  18157. {
  18158. if (auto customAttr = methodInstance->GetCustomAttributes()->Get(mCompiler->mImportAttributeTypeDef))
  18159. {
  18160. if (customAttr->mCtorArgs.size() == 1)
  18161. {
  18162. auto fileNameArg = customAttr->mCtorArgs[0];
  18163. auto constant = mCurTypeInstance->mConstHolder->GetConstant(fileNameArg);
  18164. if (constant != NULL)
  18165. {
  18166. if (!constant->IsNull())
  18167. importStrNum = constant->mInt32;
  18168. }
  18169. else
  18170. {
  18171. importStrNum = GetStringPoolIdx(fileNameArg, mCurTypeInstance->mConstHolder);
  18172. }
  18173. if (importStrNum != -1)
  18174. {
  18175. if (!mStringPoolRefs.Contains(importStrNum))
  18176. mStringPoolRefs.Add(importStrNum);
  18177. }
  18178. }
  18179. }
  18180. }
  18181. if (methodInstance->GetImportCallKind() != BfImportCallKind_None)
  18182. {
  18183. if (mBfIRBuilder->mIgnoreWrites)
  18184. return;
  18185. BfLogSysM("DllImportGlobalVar processing %p\n", methodInstance);
  18186. if (!methodInstance->mIRFunction)
  18187. {
  18188. BfIRValue dllImportGlobalVar = CreateDllImportGlobalVar(methodInstance, true);
  18189. methodInstance->mIRFunction = mBfIRBuilder->GetFakeVal();
  18190. BF_ASSERT(dllImportGlobalVar || methodInstance->mHasFailed);
  18191. mFuncReferences[mCurMethodInstance] = dllImportGlobalVar;
  18192. }
  18193. if (HasCompiledOutput())
  18194. {
  18195. BfDllImportEntry dllImportEntry;
  18196. dllImportEntry.mFuncVar = methodInstance->mIRFunction;
  18197. dllImportEntry.mMethodInstance = mCurMethodInstance;
  18198. mDllImportEntries.push_back(dllImportEntry);
  18199. }
  18200. return;
  18201. }
  18202. auto _SanityCheckType = [&](BfType* type)
  18203. {
  18204. if ((type != NULL) && (type->IsDeleting()))
  18205. {
  18206. InternalError("Method references deleted type", methodDef->GetRefNode());
  18207. return false;
  18208. }
  18209. return true;
  18210. };
  18211. if (!_SanityCheckType(methodInstance->mReturnType))
  18212. return;
  18213. for (int paramIdx = 0; paramIdx < methodInstance->GetParamCount(); paramIdx++)
  18214. if (!_SanityCheckType(methodInstance->GetParamType(paramIdx)))
  18215. return;
  18216. StringT<512> mangledName;
  18217. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), mCurMethodInstance);
  18218. if (!methodInstance->mIRFunction)
  18219. {
  18220. bool isIntrinsic = false;
  18221. SetupIRFunction(methodInstance, mangledName, false, &isIntrinsic);
  18222. }
  18223. if (methodInstance->mIsIntrinsic)
  18224. return;
  18225. if (mCurTypeInstance->IsFunction())
  18226. return;
  18227. auto prevActiveFunction = mBfIRBuilder->GetActiveFunction();
  18228. mBfIRBuilder->SetActiveFunction(mCurMethodInstance->mIRFunction);
  18229. if (methodDef->mBody != NULL)
  18230. UpdateSrcPos(methodDef->mBody, BfSrcPosFlag_NoSetDebugLoc);
  18231. else if (methodDeclaration != NULL)
  18232. UpdateSrcPos(methodDeclaration, BfSrcPosFlag_NoSetDebugLoc);
  18233. else if ((methodDef->mDeclaringType != NULL) && (methodDef->mDeclaringType->GetRefNode() != NULL))
  18234. UpdateSrcPos(methodDef->mDeclaringType->GetRefNode(), BfSrcPosFlag_NoSetDebugLoc);
  18235. else if (mCurTypeInstance->mTypeDef->mTypeDeclaration != NULL)
  18236. UpdateSrcPos(mCurTypeInstance->mTypeDef->mTypeDeclaration, BfSrcPosFlag_NoSetDebugLoc);
  18237. if ((mCurMethodState == NULL) && (!IsInSpecializedSection())) // Only do initial classify for the 'outer' method state, not any local methods or lambdas
  18238. {
  18239. if ((mCompiler->mIsResolveOnly) && (!mIsComptimeModule) && (methodDef->mBody != NULL) && (!mCurTypeInstance->IsBoxed()))
  18240. {
  18241. if (auto sourceClassifier = mCompiler->mResolvePassData->GetSourceClassifier(methodDef->mBody))
  18242. {
  18243. SetAndRestoreValue<bool> prevSkipAnonTypes(sourceClassifier->mSkipAnonymousTypes, true);
  18244. sourceClassifier->VisitChildNoRef(methodDef->mBody);
  18245. }
  18246. }
  18247. }
  18248. BfHotDataReferenceBuilder hotDataReferenceBuilder;
  18249. BfMethodState methodState;
  18250. if (mCurMethodState != NULL)
  18251. methodState.mClosureState = mCurMethodState->mClosureState;
  18252. if ((mCompiler->mOptions.mAllowHotSwapping) && (methodInstance->mIsReified) && (!methodInstance->mIsUnspecialized) && (!isInlineDup))
  18253. {
  18254. //BF_ASSERT(methodInstance->mHotMethod != NULL);
  18255. if (methodInstance->mHotMethod == NULL)
  18256. CheckHotMethod(methodInstance, mangledName);
  18257. methodState.mHotDataReferenceBuilder = &hotDataReferenceBuilder;
  18258. }
  18259. methodState.mPrevMethodState = mCurMethodState;
  18260. methodState.mMethodInstance = methodInstance;
  18261. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  18262. if (methodInstance->GetCustomAttributes() != NULL)
  18263. {
  18264. int typeOptionsIdx = GenerateTypeOptions(methodInstance->GetCustomAttributes(), mCurTypeInstance, false);
  18265. if (typeOptionsIdx != -1)
  18266. methodState.mMethodTypeOptions = mSystem->GetTypeOptions(typeOptionsIdx);
  18267. }
  18268. BfTypeState typeState(mCurTypeInstance);
  18269. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  18270. bool isGenericVariation = (methodInstance->mIsUnspecializedVariation) || (mCurTypeInstance->IsUnspecializedTypeVariation());
  18271. BfMethodInstance* unspecializedMethodInstance = NULL;
  18272. if ((prevMethodState.mPrevVal != NULL) &&
  18273. ((methodState.mClosureState == NULL) || (methodState.mClosureState->mActiveDeferredLocalMethod == NULL)))
  18274. {
  18275. // This is 'inner' (probably a closure) - use binding from outer function
  18276. methodState.mGenericTypeBindings = prevMethodState.mPrevVal->mGenericTypeBindings;
  18277. }
  18278. else if ((methodInstance->mIsUnspecialized) ||
  18279. ((mCurTypeInstance->IsUnspecializedType()) && (!isGenericVariation)))
  18280. {
  18281. methodState.mGenericTypeBindings = &methodInstance->GetMethodInfoEx()->mGenericTypeBindings;
  18282. }
  18283. else if ((((methodInstance->mMethodInfoEx != NULL) && ((int)methodInstance->mMethodInfoEx->mMethodGenericArguments.size() > dependentGenericStartIdx)) ||
  18284. ((mCurTypeInstance->IsGenericTypeInstance()) && (!isGenericVariation || mIsComptimeModule) && (!methodInstance->mMethodDef->mIsLocalMethod) && (!methodInstance->mMethodDef->mDeclaringType->IsEmitted()))))
  18285. {
  18286. unspecializedMethodInstance = GetUnspecializedMethodInstance(methodInstance, !methodInstance->mMethodDef->mIsLocalMethod);
  18287. if ((mIsComptimeModule) && (!unspecializedMethodInstance->mHasBeenProcessed))
  18288. {
  18289. // This will have already been populated by CeMachine
  18290. methodState.mGenericTypeBindings = &methodInstance->GetMethodInfoEx()->mGenericTypeBindings;
  18291. }
  18292. else
  18293. {
  18294. BF_ASSERT(unspecializedMethodInstance != methodInstance);
  18295. if (!unspecializedMethodInstance->mHasBeenProcessed)
  18296. {
  18297. // Make sure the unspecialized method is processed so we can take its bindings
  18298. // Clear mCurMethodState so we don't think we're in a local method
  18299. SetAndRestoreValue<BfMethodState*> prevMethodState_Unspec(mCurMethodState, prevMethodState.mPrevVal);
  18300. if (unspecializedMethodInstance->mMethodProcessRequest == NULL)
  18301. unspecializedMethodInstance->mDeclModule->mIncompleteMethodCount++;
  18302. mContext->ProcessMethod(unspecializedMethodInstance);
  18303. }
  18304. methodState.mGenericTypeBindings = &unspecializedMethodInstance->GetMethodInfoEx()->mGenericTypeBindings;
  18305. }
  18306. }
  18307. if (methodDef->mMethodType == BfMethodType_Operator)
  18308. {
  18309. auto operatorDef = (BfOperatorDef*) methodDef;
  18310. BfAstNode* refNode = operatorDef->mOperatorDeclaration->mOperatorToken;
  18311. auto paramErrorRefNode = refNode;
  18312. if (operatorDef->mOperatorDeclaration->mOpenParen != NULL)
  18313. paramErrorRefNode = operatorDef->mOperatorDeclaration->mOpenParen;
  18314. if ((mCurMethodInstance->GetParamCount() > 0) && (mCurMethodInstance->GetParamTypeRef(0) != NULL))
  18315. paramErrorRefNode = mCurMethodInstance->GetParamTypeRef(0);
  18316. if (operatorDef->mOperatorDeclaration->mBinOp != BfBinaryOp_None)
  18317. {
  18318. if (methodDef->mParams.size() != 2)
  18319. {
  18320. Fail("Binary operators must declare two parameters", paramErrorRefNode);
  18321. }
  18322. else
  18323. {
  18324. auto checkParam0 = mCurMethodInstance->GetParamType(0);
  18325. if ((checkParam0->IsRef()) && (!checkParam0->IsOut()))
  18326. checkParam0 = checkParam0->GetUnderlyingType();
  18327. auto checkParam1 = mCurMethodInstance->GetParamType(1);
  18328. if ((checkParam1->IsRef()) && (!checkParam1->IsOut()))
  18329. checkParam1 = checkParam1->GetUnderlyingType();
  18330. if ((checkParam0 != mCurTypeInstance) && (!checkParam0->IsSelf()) &&
  18331. (checkParam1 != mCurTypeInstance) && (!checkParam1->IsSelf()))
  18332. {
  18333. Fail("At least one of the parameters of a binary operator must be the containing type", paramErrorRefNode);
  18334. }
  18335. }
  18336. BfType* wantType = NULL;
  18337. if (operatorDef->mOperatorDeclaration->mBinOp == BfBinaryOp_Compare)
  18338. {
  18339. wantType = GetPrimitiveType(BfTypeCode_IntPtr);
  18340. }
  18341. if ((wantType != NULL) && (methodInstance->mReturnType != wantType))
  18342. Fail(StrFormat("The return type for the '%s' operator must be '%s'", BfGetOpName(operatorDef->mOperatorDeclaration->mBinOp),
  18343. TypeToString(wantType).c_str()), operatorDef->mOperatorDeclaration->mReturnType);
  18344. }
  18345. else if (operatorDef->mOperatorDeclaration->mUnaryOp != BfUnaryOp_None)
  18346. {
  18347. if (methodDef->mIsStatic)
  18348. {
  18349. if (methodDef->mParams.size() != 1)
  18350. {
  18351. Fail("Unary operators must declare one parameter", paramErrorRefNode);
  18352. }
  18353. else
  18354. {
  18355. auto checkParam0 = mCurMethodInstance->GetParamType(0);
  18356. if ((checkParam0->IsRef()) && (!checkParam0->IsOut()))
  18357. checkParam0 = checkParam0->GetUnderlyingType();
  18358. if ((checkParam0 != mCurTypeInstance) && (!checkParam0->IsSelf()))
  18359. {
  18360. Fail("The parameter of a unary operator must be the containing type", paramErrorRefNode);
  18361. }
  18362. }
  18363. if (((operatorDef->mOperatorDeclaration->mUnaryOp == BfUnaryOp_Increment) ||
  18364. (operatorDef->mOperatorDeclaration->mUnaryOp == BfUnaryOp_Decrement)) &&
  18365. (!TypeIsSubTypeOf(mCurMethodInstance->mReturnType->ToTypeInstance(), mCurTypeInstance)))
  18366. {
  18367. Fail("The return type for the '++' or '--' operator must match the parameter type or be derived from the parameter type", operatorDef->mOperatorDeclaration->mReturnType);
  18368. }
  18369. }
  18370. else
  18371. {
  18372. if (methodDef->mParams.size() != 0)
  18373. {
  18374. Fail("Non-static unary operators not declare any parameters", paramErrorRefNode);
  18375. }
  18376. if (!mCurMethodInstance->mReturnType->IsVoid())
  18377. {
  18378. Fail("The return type for non-static operator must be 'void'", operatorDef->mOperatorDeclaration->mReturnType);
  18379. }
  18380. }
  18381. }
  18382. else if (operatorDef->mOperatorDeclaration->mAssignOp != BfAssignmentOp_None)
  18383. {
  18384. if (methodDef->mParams.size() != 1)
  18385. {
  18386. Fail("Assignment operators must declare one parameter", paramErrorRefNode);
  18387. }
  18388. if (!mCurMethodInstance->mReturnType->IsVoid())
  18389. {
  18390. Fail("The return type for assignment operator must be 'void'", operatorDef->mOperatorDeclaration->mReturnType);
  18391. }
  18392. }
  18393. else // Conversion
  18394. {
  18395. if (!operatorDef->mOperatorDeclaration->mIsConvOperator)
  18396. {
  18397. if (operatorDef->mOperatorDeclaration->mReturnType != NULL)
  18398. Fail("Conversion operators must declare their target type after the 'operator' token, not before", operatorDef->mOperatorDeclaration->mReturnType);
  18399. }
  18400. if (methodDef->mParams.size() != 1)
  18401. {
  18402. auto refNode = paramErrorRefNode;
  18403. if (!operatorDef->mOperatorDeclaration->mCommas.empty())
  18404. refNode = operatorDef->mOperatorDeclaration->mCommas[0];
  18405. Fail("Conversion operators must declare one parameter", refNode);
  18406. }
  18407. else if ((methodInstance->mMethodInfoEx == NULL) ||
  18408. (methodInstance->mMethodInfoEx->mMethodGenericArguments.IsEmpty()) ||
  18409. ((methodInstance->mIsUnspecialized) && (!methodInstance->mIsUnspecializedVariation)))
  18410. {
  18411. auto checkParam0 = mCurMethodInstance->GetParamType(0);
  18412. if ((checkParam0->IsRef()) && (!checkParam0->IsOut()))
  18413. checkParam0 = checkParam0->GetUnderlyingType();
  18414. if ((checkParam0 != mCurTypeInstance) && (!checkParam0->IsSelf()) &&
  18415. (mCurMethodInstance->mReturnType != mCurTypeInstance) && (!mCurMethodInstance->mReturnType->IsSelf()))
  18416. Fail("User-defined conversion must convert to or from the enclosing type", paramErrorRefNode);
  18417. if (checkParam0 == mCurMethodInstance->mReturnType)
  18418. Fail("User-defined operator cannot take an object of the enclosing type and convert to an object of the enclosing type", operatorDef->mOperatorDeclaration->mReturnType);
  18419. // On type lookup error we default to 'object', so don't do the 'base class' error if that may have
  18420. // happened here
  18421. if ((!mHadBuildError) || ((mCurMethodInstance->mReturnType != mContext->mBfObjectType) && (checkParam0 != mContext->mBfObjectType)))
  18422. {
  18423. auto isToBase = TypeIsSubTypeOf(mCurTypeInstance->mBaseType, mCurMethodInstance->mReturnType->ToTypeInstance());
  18424. bool isFromBase = TypeIsSubTypeOf(mCurTypeInstance->mBaseType, checkParam0->ToTypeInstance());
  18425. if ((mCurTypeInstance->IsObject()) && (isToBase || isFromBase))
  18426. Fail("User-defined conversions to or from a base class are not allowed", paramErrorRefNode);
  18427. else if ((mCurTypeInstance->IsStruct()) && (isToBase))
  18428. Fail("User-defined conversions to a base struct are not allowed", paramErrorRefNode);
  18429. }
  18430. }
  18431. }
  18432. }
  18433. bool wantsDIData = (mBfIRBuilder->DbgHasInfo()) && (!methodDef->IsEmptyPartial()) && (!mBfIRBuilder->mIgnoreWrites) && (mHasFullDebugInfo);
  18434. if (methodDef->mMethodType == BfMethodType_Mixin)
  18435. wantsDIData = false;
  18436. if (mCurTypeInstance->IsUnspecializedType())
  18437. wantsDIData = false;
  18438. if ((mCurTypeInstance->IsBoxed()) && (methodDef->mMethodType != BfMethodType_Ctor))
  18439. wantsDIData = false;
  18440. bool wantsDIVariables = wantsDIData;
  18441. if (methodDef->mIsExtern)
  18442. wantsDIVariables = false;
  18443. SizedArray<BfIRMDNode, 8> diParams;
  18444. diParams.push_back(mBfIRBuilder->DbgGetType(methodInstance->mReturnType));
  18445. bool isThisStruct = mCurTypeInstance->IsStruct() && !mCurTypeInstance->IsTypedPrimitive();
  18446. BfType* thisType = NULL;
  18447. if (!methodDef->mIsStatic)
  18448. {
  18449. if ((methodState.mClosureState != NULL) && (methodState.mClosureState->mClosureType != NULL))
  18450. thisType = methodState.mClosureState->mClosureType;
  18451. else
  18452. thisType = mCurTypeInstance;
  18453. }
  18454. PopulateType(methodInstance->mReturnType, BfPopulateType_Data);
  18455. ProcessMethod_SetupParams(methodInstance, thisType, wantsDIData, &diParams);
  18456. //////////////////////////////////////////////////////////////////////////
  18457. //
  18458. {
  18459. if (methodDeclaration != NULL)
  18460. UpdateSrcPos(methodDeclaration, BfSrcPosFlag_NoSetDebugLoc);
  18461. else if (methodDef->mBody != NULL)
  18462. UpdateSrcPos(methodDef->mBody, BfSrcPosFlag_NoSetDebugLoc);
  18463. else if ((methodDef->mDeclaringType != NULL) && (methodDef->mDeclaringType->GetRefNode() != NULL))
  18464. UpdateSrcPos(methodDef->mDeclaringType->GetRefNode(), BfSrcPosFlag_NoSetDebugLoc);
  18465. else if (mCurTypeInstance->mTypeDef->mTypeDeclaration != NULL)
  18466. UpdateSrcPos(mCurTypeInstance->mTypeDef->mTypeDeclaration, BfSrcPosFlag_NoSetDebugLoc);
  18467. }
  18468. BfIRMDNode diFunction;
  18469. if (wantsDIData)
  18470. {
  18471. BP_ZONE("BfModule::DoMethodDeclaration.DISetup");
  18472. BfIRMDNode diFuncType = mBfIRBuilder->DbgCreateSubroutineType(diParams);
  18473. int defLine = mCurFilePosition.mCurLine;
  18474. if (mDICompileUnit)
  18475. {
  18476. // Note: for comptime we need to ensure we don't force type population with DbgGetTypeInst here, as that
  18477. // can generate a CeMachine InitType circular data reference
  18478. int flags = 0;
  18479. BfIRMDNode funcScope = mBfIRBuilder->DbgGetTypeInst(mCurTypeInstance, BfIRPopulateType_Identity);
  18480. if (methodDef->mProtection == BfProtection_Public)
  18481. flags = llvm::DINode::FlagPublic;
  18482. else if (methodDef->mProtection == BfProtection_Protected)
  18483. flags = llvm::DINode::FlagProtected;
  18484. else
  18485. flags = llvm::DINode::FlagPrivate;
  18486. if (methodDef->mIsOverride)
  18487. {
  18488. //flags |= llvm::DINode::FlagVirtual;
  18489. }
  18490. else if (methodDef->mIsVirtual)
  18491. flags |= llvm::DINode::FlagIntroducedVirtual;
  18492. if ((methodDef->mIsStatic) || (methodDef->mMethodType == BfMethodType_Mixin))
  18493. flags |= llvm::DINode::FlagStaticMember;
  18494. else
  18495. {
  18496. if ((mCurTypeInstance->IsValuelessType()) ||
  18497. ((!mIsComptimeModule) && (mCurTypeInstance->IsSplattable())))
  18498. flags |= llvm::DINode::FlagStaticMember;
  18499. }
  18500. flags |= llvm::DINode::FlagPrototyped;
  18501. if (methodDef->mMethodType == BfMethodType_Ctor)
  18502. {
  18503. flags |= llvm::DINode::FlagArtificial;
  18504. }
  18505. auto llvmFunction = methodInstance->mIRFunction;
  18506. SizedArray<BfIRMDNode, 1> genericArgs;
  18507. SizedArray<BfIRValue, 1> genericConstValueArgs;
  18508. String methodName;
  18509. if (methodInstance->GetForeignType() != NULL)
  18510. {
  18511. methodName += TypeToString(methodInstance->GetForeignType());
  18512. methodName += ".";
  18513. }
  18514. if (methodInstance->GetExplicitInterface() != NULL)
  18515. {
  18516. methodName += TypeToString(methodInstance->GetExplicitInterface());
  18517. methodName += ".";
  18518. }
  18519. methodName += methodDef->mName;
  18520. if (methodInstance->GetNumGenericArguments() != 0)
  18521. {
  18522. for (auto genericArg : methodInstance->mMethodInfoEx->mMethodGenericArguments)
  18523. {
  18524. if (genericArg->IsConstExprValue())
  18525. {
  18526. BfConstExprValueType* constExprValueType = (BfConstExprValueType*)genericArg;
  18527. while (genericConstValueArgs.size() < genericArgs.size())
  18528. genericConstValueArgs.push_back(BfIRValue());
  18529. genericConstValueArgs.push_back(mBfIRBuilder->CreateConst(BfTypeCode_UInt64, constExprValueType->mValue.mUInt64));
  18530. genericArgs.push_back(mBfIRBuilder->DbgGetType(GetPrimitiveType(BfTypeCode_Int64)));
  18531. }
  18532. else
  18533. genericArgs.push_back(mBfIRBuilder->DbgGetType(genericArg));
  18534. }
  18535. methodName += "<";
  18536. for (int i = 0; i < (int)methodInstance->mMethodInfoEx->mMethodGenericArguments.size(); i++)
  18537. {
  18538. if (i > 0)
  18539. methodName += ", ";
  18540. BfType* type = methodInstance->mMethodInfoEx->mMethodGenericArguments[i];
  18541. methodName += TypeToString(type);
  18542. }
  18543. methodName += ">";
  18544. }
  18545. if ((methodName.empty()) && (methodDeclaration != NULL))
  18546. {
  18547. if (auto operatorDecl = BfNodeDynCast<BfOperatorDeclaration>(methodDeclaration))
  18548. {
  18549. methodName += "operator";
  18550. if (operatorDecl->mIsConvOperator)
  18551. {
  18552. methodName += " ";
  18553. methodName += TypeToString(methodInstance->mReturnType);
  18554. }
  18555. else if (operatorDecl->mOpTypeToken != NULL)
  18556. methodName += operatorDecl->mOpTypeToken->ToString();
  18557. }
  18558. }
  18559. if (methodDef->mCheckedKind == BfCheckedKind_Checked)
  18560. methodName += "$CHK";
  18561. else if (methodDef->mCheckedKind == BfCheckedKind_Unchecked)
  18562. methodName += "$UCHK";
  18563. methodState.mDIFile = mCurFilePosition.mFileInstance->mDIFile;
  18564. // diFunction = mBfIRBuilder->DbgCreateMethod(funcScope, methodName, mangledName, methodState.mDIFile,
  18565. // defLine + 1, diFuncType, false, true,
  18566. // (methodInstance->mVirtualTableIdx != -1) ? llvm::dwarf::DW_VIRTUALITY_virtual : llvm::dwarf::DW_VIRTUALITY_none,
  18567. // (methodInstance->mVirtualTableIdx != -1) ? methodInstance->DbgGetVirtualMethodNum() : 0,
  18568. // nullptr, flags, IsOptimized(), llvmFunction, genericArgs, genericConstValueArgs);
  18569. diFunction = mBfIRBuilder->DbgCreateMethod(funcScope, methodName, mangledName, methodState.mDIFile,
  18570. defLine + 1, diFuncType, false, true,
  18571. llvm::dwarf::DW_VIRTUALITY_none,
  18572. 0,
  18573. BfIRMDNode(), flags, IsOptimized(), llvmFunction, genericArgs, genericConstValueArgs);
  18574. }
  18575. else
  18576. {
  18577. methodState.mDIFile = mCurFilePosition.mFileInstance->mDIFile;
  18578. }
  18579. }
  18580. //////////////////////////////////////////////////////////////////////////
  18581. // Head and Init get rolled into Entry afterwards.
  18582. methodState.mIRFunction = methodInstance->mIRFunction;
  18583. methodState.mIRHeadBlock = mBfIRBuilder->CreateBlock("head", true);
  18584. methodState.mIRInitBlock = mBfIRBuilder->CreateBlock("init", true);
  18585. methodState.mIREntryBlock = mBfIRBuilder->CreateBlock("entry", true);
  18586. methodState.mCurScope->mDIScope = diFunction;
  18587. auto llvmEntryBlock = methodState.mIREntryBlock;
  18588. mBfIRBuilder->SetInsertPoint(llvmEntryBlock);
  18589. if (methodDef->mName == "__MALFORMED")
  18590. {
  18591. auto newBlock = mBfIRBuilder->CreateBlock("malformed", true);
  18592. mBfIRBuilder->SetInsertPoint(newBlock);
  18593. }
  18594. if (methodDef->mBody != NULL)
  18595. {
  18596. UpdateSrcPos(methodDef->mBody, BfSrcPosFlag_NoSetDebugLoc);
  18597. }
  18598. else if ((mHasFullDebugInfo) && (diFunction) && (typeDef->mTypeDeclaration != NULL))
  18599. {
  18600. // We want to be able to step into delegate invokes -- we actually step over them
  18601. if (methodDef->mName != "Invoke")
  18602. {
  18603. UpdateSrcPos(methodDef->mDeclaringType->GetRefNode());
  18604. mBfIRBuilder->DbgCreateAnnotation(diFunction, "StepOver", GetConstValue32(1));
  18605. }
  18606. }
  18607. // Clear out DebugLoc - to mark the ".addr" code as part of prologue
  18608. mBfIRBuilder->ClearDebugLocation();
  18609. bool isTypedPrimitiveFunc = mCurTypeInstance->IsTypedPrimitive() && (methodDef->mMethodType != BfMethodType_Ctor);
  18610. int irParamCount = methodInstance->GetIRFunctionParamCount(this);
  18611. if (methodInstance->GetImportKind() != BfImportKind_Import_Dynamic)
  18612. {
  18613. int localIdx = 0;
  18614. int argIdx = 0;
  18615. Array<BfIRValue> splatAddrValues;
  18616. for ( ; argIdx < irParamCount; localIdx++)
  18617. {
  18618. bool isThis = ((localIdx == 0) && (!mCurMethodInstance->mMethodDef->mIsStatic));
  18619. if ((isThis) && (thisType->IsValuelessNonOpaqueType()))
  18620. isThis = false;
  18621. if ((!mIsComptimeModule) && (methodInstance->GetStructRetIdx() == argIdx))
  18622. {
  18623. argIdx++;
  18624. if (argIdx == irParamCount)
  18625. break;
  18626. }
  18627. BfLocalVariable* paramVar = NULL;
  18628. while (true)
  18629. {
  18630. BF_ASSERT(localIdx < methodState.mLocals.size());
  18631. paramVar = methodState.mLocals[localIdx];
  18632. if ((paramVar->mCompositeCount == -1) &&
  18633. (!paramVar->mIsConst) &&
  18634. ((!paramVar->mResolvedType->IsValuelessNonOpaqueType()) || (paramVar->mResolvedType->IsMethodRef())))
  18635. break;
  18636. localIdx++;
  18637. }
  18638. if ((isThis) && (mCurTypeInstance->IsValueType()) && (methodDef->mMethodType != BfMethodType_Ctor) && (!methodDef->HasNoThisSplat()))
  18639. {
  18640. paramVar->mIsReadOnly = true;
  18641. }
  18642. bool wantsAddr = (wantsDIVariables) || (!paramVar->mIsReadOnly) ||
  18643. ((!mIsComptimeModule) && (paramVar->mResolvedType->GetLoweredType(BfTypeUsage_Parameter)));
  18644. if (paramVar->mResolvedType->IsMethodRef())
  18645. wantsAddr = false;
  18646. // if ((methodDef->mHasAppend) && (argIdx == 1))
  18647. // {
  18648. // BF_ASSERT(paramVar->mName == "appendIdx");
  18649. // wantsAddr = true;
  18650. // }
  18651. if (paramVar->mIsSplat)
  18652. {
  18653. auto prevInsert = mBfIRBuilder->GetInsertBlock();
  18654. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  18655. BfTypeUtils::SplatIterate([&](BfType* checkType)
  18656. {
  18657. BfIRType splatIRType;
  18658. if (checkType->IsComposite())
  18659. splatIRType = mBfIRBuilder->MapType(CreatePointerType(checkType));
  18660. else
  18661. splatIRType = mBfIRBuilder->MapType(checkType);
  18662. auto allocaInst = mBfIRBuilder->CreateAlloca(splatIRType);
  18663. mBfIRBuilder->SetAllocaAlignment(allocaInst, checkType->mAlign);
  18664. if (!paramVar->mAddr)
  18665. paramVar->mAddr = allocaInst;
  18666. if (WantsLifetimes())
  18667. mCurMethodState->mCurScope->mDeferredLifetimeEnds.push_back(allocaInst);
  18668. splatAddrValues.push_back(allocaInst);
  18669. }, paramVar->mResolvedType);
  18670. mBfIRBuilder->SetInsertPoint(prevInsert);
  18671. }
  18672. else if (isThis)
  18673. {
  18674. if (wantsAddr)
  18675. {
  18676. auto prevInsert = mBfIRBuilder->GetInsertBlock();
  18677. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  18678. BfIRType thisAddrType = mBfIRBuilder->MapType(thisType);
  18679. if (paramVar->mIsSplat)
  18680. {
  18681. //
  18682. }
  18683. else
  18684. {
  18685. bool wantPtr = (thisType->IsComposite()) && (!paramVar->mIsLowered);
  18686. if ((thisType->IsTypedPrimitive()) &&
  18687. ((methodDef->HasNoThisSplat()) || (methodInstance->mCallingConvention == BfCallingConvention_Cdecl)))
  18688. wantPtr = true;
  18689. if (wantPtr)
  18690. {
  18691. thisAddrType = mBfIRBuilder->MapTypeInstPtr(thisType->ToTypeInstance());
  18692. }
  18693. auto allocaInst = mBfIRBuilder->CreateAlloca(thisAddrType);
  18694. mBfIRBuilder->SetName(allocaInst, paramVar->mName + ".addr");
  18695. mBfIRBuilder->SetAllocaAlignment(allocaInst, mSystem->mPtrSize);
  18696. paramVar->mAddr = allocaInst;
  18697. if (WantsLifetimes())
  18698. mCurMethodState->mCurScope->mDeferredLifetimeEnds.push_back(allocaInst);
  18699. }
  18700. mBfIRBuilder->SetInsertPoint(prevInsert);
  18701. }
  18702. }
  18703. else if ((!isThis) && ((paramVar->mIsStruct) || (paramVar->mResolvedType->IsRef())))
  18704. {
  18705. // Address doesn't change so we don't have to alloca it
  18706. BfIRType allocType;
  18707. int alignSize = mSystem->mPtrSize;
  18708. if (paramVar->mResolvedType->IsRef())
  18709. {
  18710. allocType = mBfIRBuilder->MapType(paramVar->mResolvedType);
  18711. }
  18712. else if ((paramVar->mIsSplat) || (paramVar->mIsLowered))
  18713. {
  18714. allocType = mBfIRBuilder->MapType(paramVar->mResolvedType);
  18715. alignSize = paramVar->mResolvedType->mAlign;
  18716. }
  18717. else
  18718. {
  18719. paramVar->mHasLocalStructBacking = true;
  18720. auto typeInst = paramVar->mResolvedType->ToTypeInstance();
  18721. if (typeInst != NULL)
  18722. allocType = mBfIRBuilder->MapTypeInstPtr(paramVar->mResolvedType->ToTypeInstance());
  18723. else
  18724. allocType = mBfIRBuilder->MapType(CreatePointerType(paramVar->mResolvedType));
  18725. }
  18726. if (wantsAddr)
  18727. {
  18728. auto prevInsert = mBfIRBuilder->GetInsertBlock();
  18729. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  18730. mBfIRBuilder->PopulateType(paramVar->mResolvedType);
  18731. auto allocaInst = mBfIRBuilder->CreateAlloca(allocType);
  18732. mBfIRBuilder->SetName(allocaInst, paramVar->mName + ".addr");
  18733. mBfIRBuilder->SetAllocaAlignment(allocaInst, alignSize);
  18734. paramVar->mAddr = allocaInst;
  18735. mBfIRBuilder->SetInsertPoint(prevInsert);
  18736. if (WantsLifetimes())
  18737. mCurMethodState->mCurScope->mDeferredLifetimeEnds.push_back(allocaInst);
  18738. }
  18739. }
  18740. else if (wantsAddr)
  18741. {
  18742. auto allocaInst = CreateAlloca(paramVar->mResolvedType);
  18743. mBfIRBuilder->SetName(allocaInst, paramVar->mName + ".addr");
  18744. paramVar->mAddr = allocaInst;
  18745. }
  18746. if (paramVar->mIsSplat)
  18747. {
  18748. BfTypeUtils::SplatIterate([&](BfType* checkType) { argIdx++; }, paramVar->mResolvedType);
  18749. }
  18750. else if (paramVar->mIsLowered)
  18751. {
  18752. BfTypeCode loweredTypeCode = BfTypeCode_None;
  18753. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  18754. paramVar->mResolvedType->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2);
  18755. argIdx++;
  18756. if (loweredTypeCode2 != BfTypeCode_None)
  18757. argIdx++;
  18758. }
  18759. else
  18760. {
  18761. argIdx++;
  18762. }
  18763. }
  18764. if (methodDef->mBody != NULL)
  18765. UpdateSrcPos(methodDef->mBody);
  18766. else if ((methodDef->mDeclaringType != NULL) && (methodDef->mDeclaringType->GetRefNode() != NULL))
  18767. UpdateSrcPos(methodDef->mDeclaringType->GetRefNode());
  18768. else if (mCurTypeInstance->mTypeDef->mTypeDeclaration != NULL)
  18769. UpdateSrcPos(mCurTypeInstance->mTypeDef->mTypeDeclaration);
  18770. localIdx = 0;
  18771. argIdx = 0;
  18772. int splatAddrIdx = 0;
  18773. while (localIdx < (int)methodState.mLocals.size())
  18774. {
  18775. if ((!mIsComptimeModule) && (argIdx == methodInstance->GetStructRetIdx()))
  18776. argIdx++;
  18777. int curLocalIdx = localIdx++;
  18778. BfLocalVariable* paramVar = methodState.mLocals[curLocalIdx];
  18779. if (paramVar->mIsConst)
  18780. continue;
  18781. if (!paramVar->IsParam())
  18782. continue;
  18783. if (paramVar->mCompositeCount != -1)
  18784. continue;
  18785. bool isThis = ((curLocalIdx == 0) && (!mCurMethodInstance->mMethodDef->mIsStatic));
  18786. if ((isThis) && (thisType->IsValuelessNonOpaqueType()))
  18787. isThis = false;
  18788. if (paramVar->mValue.IsArg())
  18789. BF_ASSERT(paramVar->mValue.mId == argIdx);
  18790. BfIRMDNode diVariable;
  18791. if (wantsDIData)
  18792. {
  18793. String paramName = paramVar->mName;
  18794. BfIRMDNode diType = mBfIRBuilder->DbgGetType(paramVar->mResolvedType);
  18795. if (isThis)
  18796. {
  18797. if ((mCurMethodState->mClosureState != NULL) && (mCurMethodState->mClosureState->mClosureType != NULL))
  18798. paramName = "__closure";
  18799. if ((paramVar->mResolvedType->IsValueType()) && (!paramVar->mIsSplat) && (!paramVar->mIsLowered))
  18800. {
  18801. diType = mBfIRBuilder->DbgGetType(paramVar->mResolvedType);
  18802. bool wantRef = paramVar->mResolvedType->IsComposite();
  18803. if ((paramVar->mResolvedType->IsTypedPrimitive()) &&
  18804. ((methodDef->HasNoThisSplat()) || (methodInstance->mCallingConvention == BfCallingConvention_Cdecl)))
  18805. wantRef = true;
  18806. if (wantRef)
  18807. diType = mBfIRBuilder->DbgCreateReferenceType(diType);
  18808. }
  18809. else if (!paramVar->mResolvedType->IsValueType())
  18810. {
  18811. diType = mBfIRBuilder->DbgCreateArtificialType(diType);
  18812. }
  18813. }
  18814. else
  18815. {
  18816. if ((paramVar->mResolvedType->IsComposite()) && (!paramVar->mIsSplat) && (!paramVar->mIsLowered))
  18817. {
  18818. diType = mBfIRBuilder->DbgGetType(paramVar->mResolvedType);
  18819. diType = mBfIRBuilder->DbgCreateReferenceType(diType);
  18820. diType = mBfIRBuilder->DbgCreateConstType(diType);
  18821. }
  18822. }
  18823. if (!paramVar->mIsSplat)
  18824. {
  18825. if ((paramVar->mParamIdx >= 0) && (paramVar->mParamIdx < methodInstance->mDefaultValues.mSize))
  18826. {
  18827. auto defaultValue = methodInstance->mDefaultValues[paramVar->mParamIdx];
  18828. auto constant = mCurTypeInstance->mConstHolder->GetConstant(defaultValue.mValue);
  18829. if ((constant != NULL) &&
  18830. ((BfIRConstHolder::IsIntable(constant->mTypeCode)) || (BfIRConstHolder::IsFloat(constant->mTypeCode))))
  18831. {
  18832. int64 writeVal = constant->mInt64;
  18833. if (constant->mTypeCode == BfTypeCode_Float)
  18834. {
  18835. // We need to do this because Singles are stored in mDouble, so we need to reduce here
  18836. float floatVal = (float)constant->mDouble;
  18837. writeVal = *(uint32*)&floatVal;
  18838. }
  18839. if (writeVal < 0)
  18840. paramName += StrFormat("$_%llu", -writeVal);
  18841. else
  18842. paramName += StrFormat("$%llu", writeVal);
  18843. }
  18844. }
  18845. if (paramVar->mResolvedType->IsValuelessNonOpaqueType())
  18846. {
  18847. diVariable = mBfIRBuilder->DbgCreateAutoVariable(diFunction,
  18848. paramName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType);
  18849. }
  18850. else if (paramVar->mIsImplicitParam)
  18851. {
  18852. // Annotate this specially?
  18853. diVariable = mBfIRBuilder->DbgCreateParameterVariable(diFunction,
  18854. paramName, argIdx + 1, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType, true, 0);
  18855. }
  18856. else
  18857. {
  18858. diVariable = mBfIRBuilder->DbgCreateParameterVariable(diFunction,
  18859. paramName, argIdx + 1, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType, true, 0);
  18860. }
  18861. paramVar->mDbgVarInst = diVariable;
  18862. }
  18863. else if ((paramVar->mIsSplat) && (paramVar->mResolvedType->GetSplatCount() == 0))
  18864. {
  18865. // if ((mBfIRBuilder->HasDebugLocation()) && (wantsDIVariables))
  18866. // {
  18867. // // Only add this placeholder if we don't have any values
  18868. // auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(mCurMethodState->mCurScope->mDIScope,
  18869. // paramName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType);
  18870. // mBfIRBuilder->DbgInsertValueIntrinsic(GetConstValue(0), diVariable);
  18871. // }
  18872. }
  18873. }
  18874. bool isTypedPrimCtor = mCurTypeInstance->IsTypedPrimitive() && (methodDef->mMethodType == BfMethodType_Ctor);
  18875. if ((!paramVar->mParamFailed) && (paramVar->mAddr))
  18876. {
  18877. // Write our argument value into the .addr
  18878. mBfIRBuilder->ClearDebugLocation();
  18879. if (paramVar->mIsSplat)
  18880. {
  18881. mBfIRBuilder->PopulateType(paramVar->mResolvedType);
  18882. //
  18883. }
  18884. else
  18885. {
  18886. bool handled = false;
  18887. if (paramVar->mIsLowered)
  18888. {
  18889. BfTypeCode loweredTypeCode = BfTypeCode_None;
  18890. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  18891. if (paramVar->mResolvedType->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2))
  18892. {
  18893. BfIRValue targetAddr = paramVar->mAddr;
  18894. bool isTempTarget = false;
  18895. int loweredSize = mBfIRBuilder->GetSize(loweredTypeCode) + mBfIRBuilder->GetSize(loweredTypeCode2);
  18896. if (paramVar->mResolvedType->mSize < loweredSize)
  18897. {
  18898. isTempTarget = true;
  18899. targetAddr = CreateAlloca(GetPrimitiveType(BfTypeCode_Int8), true, NULL, GetConstValue(loweredSize));
  18900. mBfIRBuilder->SetAllocaAlignment(targetAddr,
  18901. BF_MAX(paramVar->mResolvedType->mAlign,
  18902. BF_MAX(mBfIRBuilder->GetSize(loweredTypeCode), mBfIRBuilder->GetSize(loweredTypeCode2))));
  18903. }
  18904. // We have a lowered type coming in, so we have to cast the .addr before storing
  18905. auto primType = mBfIRBuilder->GetPrimitiveType(loweredTypeCode);
  18906. auto primPtrType = mBfIRBuilder->GetPointerTo(primType);
  18907. auto primPtrVal = mBfIRBuilder->CreateBitCast(targetAddr, primPtrType);
  18908. mBfIRBuilder->CreateAlignedStore(paramVar->mValue, primPtrVal, mCurTypeInstance->mAlign);
  18909. if (loweredTypeCode2 != BfTypeCode_None)
  18910. {
  18911. auto primType2 = mBfIRBuilder->GetPrimitiveType(loweredTypeCode2);
  18912. auto primPtrType2 = mBfIRBuilder->GetPointerTo(primType2);
  18913. BfIRValue primPtrVal2;
  18914. if (mBfIRBuilder->GetSize(loweredTypeCode) < mBfIRBuilder->GetSize(loweredTypeCode2))
  18915. primPtrVal2 = mBfIRBuilder->CreateInBoundsGEP(mBfIRBuilder->CreateBitCast(primPtrVal, primPtrType2), 1);
  18916. else
  18917. primPtrVal2 = mBfIRBuilder->CreateBitCast(mBfIRBuilder->CreateInBoundsGEP(primPtrVal, 1), primPtrType2);
  18918. mBfIRBuilder->CreateStore(mBfIRBuilder->GetArgument(argIdx + 1), primPtrVal2);
  18919. }
  18920. if (isTempTarget)
  18921. {
  18922. auto castedTempPtr = mBfIRBuilder->CreateBitCast(targetAddr, mBfIRBuilder->MapType(CreatePointerType(paramVar->mResolvedType)));
  18923. auto tempVal = mBfIRBuilder->CreateAlignedLoad(castedTempPtr, paramVar->mResolvedType->mAlign);
  18924. mBfIRBuilder->CreateAlignedStore(tempVal, paramVar->mAddr, paramVar->mResolvedType->mAlign);
  18925. }
  18926. // We don't want to allow directly using value
  18927. paramVar->mValue = BfIRValue();
  18928. handled = true;
  18929. }
  18930. else
  18931. {
  18932. BF_ASSERT("Expected lowered");
  18933. }
  18934. }
  18935. if (!handled)
  18936. mBfIRBuilder->CreateAlignedStore(paramVar->mValue, paramVar->mAddr, paramVar->mResolvedType->mAlign);
  18937. }
  18938. }
  18939. if (methodDef->mBody != NULL)
  18940. UpdateSrcPos(methodDef->mBody);
  18941. else if (methodDef->mDeclaringType->mTypeDeclaration != NULL)
  18942. UpdateSrcPos(methodDef->mDeclaringType->mTypeDeclaration);
  18943. else if (methodDeclaration == NULL)
  18944. UseDefaultSrcPos();
  18945. // Write our argument value into the .addr
  18946. if (paramVar->mIsSplat)
  18947. {
  18948. int splatComponentIdx = 0;
  18949. auto curArgIdx = argIdx;
  18950. auto _FinishSplats = [&] (BfType* checkType, const StringImpl& name)
  18951. {
  18952. BfIRValue splatAddrValue = splatAddrValues[splatAddrIdx++];
  18953. methodState.mSplatDecompAddrs.push_back(splatAddrValue);
  18954. auto storeInst = mBfIRBuilder->CreateAlignedStore(mBfIRBuilder->GetArgument(curArgIdx), splatAddrValue, checkType->mAlign);
  18955. mBfIRBuilder->ClearDebugLocation(storeInst);
  18956. if (wantsDIData)
  18957. {
  18958. BfIRMDNode diType;
  18959. if (checkType->IsComposite())
  18960. diType = mBfIRBuilder->DbgGetType(CreateRefType(checkType));
  18961. else
  18962. diType = mBfIRBuilder->DbgGetType(checkType);
  18963. auto diVariable = mBfIRBuilder->DbgCreateParameterVariable(diFunction,
  18964. name, curArgIdx + 1, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType);
  18965. if (wantsDIVariables)
  18966. {
  18967. mBfIRBuilder->DbgInsertDeclare(splatAddrValue, diVariable);
  18968. }
  18969. }
  18970. curArgIdx++;
  18971. splatComponentIdx++;
  18972. };
  18973. std::function<void(BfType*, const StringImpl&)> _FinishSplatsIterate = [&](BfType* checkType, const StringImpl& name)
  18974. {
  18975. if (checkType->IsStruct())
  18976. {
  18977. auto checkTypeInstance = checkType->ToTypeInstance();
  18978. if (checkTypeInstance->mBaseType != NULL)
  18979. {
  18980. _FinishSplatsIterate(checkTypeInstance->mBaseType, name + "$b");
  18981. }
  18982. if (checkTypeInstance->mIsUnion)
  18983. {
  18984. auto unionInnerType = checkTypeInstance->GetUnionInnerType();
  18985. if (!unionInnerType->IsValuelessType())
  18986. {
  18987. _FinishSplatsIterate(unionInnerType, name + "$u");
  18988. }
  18989. if (checkTypeInstance->IsEnum())
  18990. {
  18991. auto dscrType = checkTypeInstance->GetDiscriminatorType();
  18992. _FinishSplatsIterate(dscrType, name + "$d");
  18993. }
  18994. }
  18995. else
  18996. {
  18997. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  18998. {
  18999. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  19000. auto fieldDef = fieldInstance->GetFieldDef();
  19001. if (fieldInstance->mDataIdx >= 0)
  19002. {
  19003. _FinishSplatsIterate(fieldInstance->GetResolvedType(), name + "$m$" + fieldDef->mName);
  19004. }
  19005. }
  19006. }
  19007. }
  19008. else if (checkType->IsMethodRef())
  19009. {
  19010. auto methodRefType = (BfMethodRefType*)checkType;
  19011. BfMethodInstance* methodInstance = methodRefType->mMethodRef;
  19012. // int implicitParamCount = methodInstance->GetImplicitParamCount();
  19013. // for (int implicitParamIdx = methodInstance->HasThis() ? -1 : 0; implicitParamIdx < implicitParamCount; implicitParamIdx++)
  19014. // {
  19015. // auto paramType = methodInstance->GetParamType(implicitParamIdx);
  19016. // if (!paramType->IsValuelessType())
  19017. // _FinishSplats(paramType, name + "$m$" + methodInstance->GetParamName(implicitParamIdx));
  19018. // }
  19019. for (int dataIdx = 0; dataIdx < methodRefType->GetCaptureDataCount(); dataIdx++)
  19020. {
  19021. int paramIdx = methodRefType->GetParamIdxFromDataIdx(dataIdx);
  19022. String paramName = methodInstance->GetParamName(paramIdx);
  19023. if (paramName == "this")
  19024. paramName = "__this";
  19025. if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  19026. {
  19027. _FinishSplatsIterate(methodRefType->GetCaptureType(dataIdx), name + "$m$" + paramName);
  19028. }
  19029. else
  19030. {
  19031. _FinishSplats(methodRefType->GetCaptureType(dataIdx), name + "$m$" + paramName);
  19032. }
  19033. }
  19034. }
  19035. else if (!checkType->IsValuelessType())
  19036. {
  19037. _FinishSplats(checkType, name);
  19038. }
  19039. };
  19040. mBfIRBuilder->PopulateType(paramVar->mResolvedType);
  19041. if (!paramVar->mConstValue)
  19042. _FinishSplatsIterate(paramVar->mResolvedType, "$" + paramVar->mName);
  19043. }
  19044. BfIRValue declareCall;
  19045. if (diVariable)
  19046. {
  19047. if ((mBfIRBuilder->HasDebugLocation()) && (wantsDIVariables))
  19048. {
  19049. if (!paramVar->mAddr)
  19050. {
  19051. if ((!paramVar->mValue) || (paramVar->mValue.IsFake()))
  19052. {
  19053. if ((!paramVar->mIsThis) && (mCompiler->mOptions.mToolsetType != BfToolsetType_GNU)) // DWARF chokes on this:
  19054. {
  19055. // We don't need to set the location for this
  19056. mBfIRBuilder->DbgInsertValueIntrinsic(BfIRValue(), diVariable);
  19057. }
  19058. }
  19059. else
  19060. declareCall = mBfIRBuilder->DbgInsertDeclare(paramVar->mValue, diVariable);
  19061. }
  19062. else
  19063. {
  19064. declareCall = mBfIRBuilder->DbgInsertDeclare(paramVar->mAddr, diVariable);
  19065. }
  19066. }
  19067. }
  19068. if ((isThis) && (!paramVar->mIsSplat) && (paramVar->mAddr))
  19069. {
  19070. // We don't allow actually assignment to "this", so we just do a single load
  19071. // Keep in mind we don't use the ACTUAL mValue value because that's a register, but
  19072. // we need to store it in the stack frame for debugging purposes
  19073. auto loadedThis = mBfIRBuilder->CreateAlignedLoad(paramVar->mAddr/*, "this"*/, paramVar->mResolvedType->mAlign);
  19074. mBfIRBuilder->ClearDebugLocation(loadedThis);
  19075. paramVar->mValue = loadedThis;
  19076. }
  19077. if ((wantsDIData) && (declareCall))
  19078. mBfIRBuilder->UpdateDebugLocation(declareCall);
  19079. if (paramVar->mIsSplat)
  19080. {
  19081. BfTypeUtils::SplatIterate([&](BfType* checkType) { argIdx++; }, paramVar->mResolvedType);
  19082. }
  19083. else if (paramVar->mIsLowered)
  19084. {
  19085. argIdx++;
  19086. BfTypeCode loweredTypeCode = BfTypeCode_None;
  19087. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  19088. paramVar->mResolvedType->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2);
  19089. if (loweredTypeCode2 != BfTypeCode_None)
  19090. argIdx++;
  19091. }
  19092. else if ((isThis) && (paramVar->mResolvedType->IsOpaque()))
  19093. {
  19094. if ((methodDef->mIsMutating) || (methodInstance->mCallingConvention == BfCallingConvention_Cdecl))
  19095. argIdx++;
  19096. }
  19097. else if (!paramVar->mResolvedType->IsValuelessNonOpaqueType())
  19098. {
  19099. argIdx++;
  19100. }
  19101. }
  19102. if (wantsDIData)
  19103. {
  19104. BF_ASSERT(splatAddrIdx == (int)splatAddrValues.size());
  19105. }
  19106. }
  19107. for (int varIdx = 0; varIdx < (int)mCurMethodState->mLocals.size(); varIdx++)
  19108. {
  19109. auto paramVar = mCurMethodState->mLocals[varIdx];
  19110. // 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
  19111. // splat member. If the "splat" is valueless then we do create a placeholder, but further up in this method
  19112. // if (paramVar->mIsSplat)
  19113. // {
  19114. // if (wantsDIVariables)
  19115. // {
  19116. // auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(diFunction, paramVar->mName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, mBfIRBuilder->DbgGetType(paramVar->mResolvedType));
  19117. // mBfIRBuilder->DbgInsertValueIntrinsic(mBfIRBuilder->CreateConst(BfTypeCode_Int64, 0), diVariable);
  19118. // }
  19119. // }
  19120. if (paramVar->mResolvedType->IsValuelessType())
  19121. {
  19122. if ((mBfIRBuilder->HasDebugLocation()) && (wantsDIVariables) && (mCompiler->mOptions.mToolsetType != BfToolsetType_GNU)) // DWARF chokes on this:
  19123. {
  19124. // Only add this placeholder if we don't have any values
  19125. auto diType = mBfIRBuilder->DbgGetType(paramVar->mResolvedType);
  19126. auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(mCurMethodState->mCurScope->mDIScope,
  19127. paramVar->mName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType);
  19128. mBfIRBuilder->DbgInsertValueIntrinsic(BfIRValue(), diVariable);
  19129. }
  19130. }
  19131. }
  19132. if (IsTargetingBeefBackend())
  19133. mCurMethodState->mCurScope->mValueScopeStart = mBfIRBuilder->CreateValueScopeStart();
  19134. if (methodState.mClosureState != NULL)
  19135. {
  19136. for (auto& constLocal : methodState.mClosureState->mConstLocals)
  19137. {
  19138. BfLocalVariable* localVar = new BfLocalVariable();
  19139. *localVar = constLocal;
  19140. localVar->mIsBumpAlloc = false;
  19141. AddLocalVariableDef(localVar, true);
  19142. }
  19143. }
  19144. bool wantsRemoveBody = false;
  19145. bool skipBody = false;
  19146. bool skipUpdateSrcPos = false;
  19147. bool skipEndChecks = false;
  19148. bool hasExternSpecifier = (methodDeclaration != NULL) && (methodDeclaration->mExternSpecifier != NULL) && (methodInstance->GetImportKind() != BfImportKind_Import_Dynamic);
  19149. auto propertyDeclaration = methodDef->GetPropertyDeclaration();
  19150. if ((methodDef != NULL) && (propertyDeclaration != NULL) && (propertyDeclaration->mExternSpecifier != NULL))
  19151. hasExternSpecifier = true;
  19152. if (methodDef->mName == BF_METHODNAME_MARKMEMBERS)
  19153. {
  19154. // We need to be able to mark deleted objects
  19155. mCurMethodState->mIgnoreObjectAccessCheck = true;
  19156. }
  19157. auto customAttributes = methodInstance->GetCustomAttributes();
  19158. if (customAttributes != NULL)
  19159. {
  19160. if (customAttributes->Contains(mCompiler->mDisableObjectAccessChecksAttributeTypeDef))
  19161. mCurMethodState->mIgnoreObjectAccessCheck = true;
  19162. if (customAttributes->Contains(mCompiler->mDisableChecksAttributeTypeDef))
  19163. mCurMethodState->mDisableChecks = true;
  19164. }
  19165. // Allocate, clear, set classVData
  19166. if ((methodDef->mMethodType == BfMethodType_Ctor) && (methodDef->mIsStatic))
  19167. {
  19168. CreateStaticCtor();
  19169. }
  19170. else if ((mCurTypeInstance->IsBoxed()) && (methodDef->mMethodType != BfMethodType_Ctor) && (methodDef->mName != BF_METHODNAME_DYNAMICCAST) && (methodDef->mName != BF_METHODNAME_DYNAMICCAST_INTERFACE))
  19171. {
  19172. skipBody = true;
  19173. skipEndChecks = true;
  19174. if (HasExecutedOutput())
  19175. {
  19176. // Clear out DebugLoc - to mark the ".addr" code as part of prologue
  19177. mBfIRBuilder->ClearDebugLocation();
  19178. BfBoxedType* boxedType = (BfBoxedType*) mCurTypeInstance;
  19179. BfTypeInstance* innerType = boxedType->mElementType->ToTypeInstance();
  19180. PopulateType(innerType, BfPopulateType_DataAndMethods);
  19181. mBfIRBuilder->PopulateType(mCurTypeInstance);
  19182. BfGetMethodInstanceFlags flags = BfGetMethodInstanceFlag_None;
  19183. if (methodInstance->mIsForeignMethodDef)
  19184. {
  19185. flags = BfGetMethodInstanceFlag_ForeignMethodDef;
  19186. }
  19187. BfTypeVector methodGenericArguments;
  19188. if (methodInstance->mMethodInfoEx != NULL)
  19189. methodGenericArguments = methodInstance->mMethodInfoEx->mMethodGenericArguments;
  19190. auto innerMethodInstance = GetMethodInstance(innerType, methodDef, methodGenericArguments, flags, methodInstance->GetForeignType());
  19191. if (innerMethodInstance.mMethodInstance->IsSkipCall())
  19192. {
  19193. if (!methodInstance->mReturnType->IsValuelessType())
  19194. {
  19195. auto retVal = GetDefaultValue(methodInstance->mReturnType);
  19196. CreateReturn(retVal);
  19197. }
  19198. else
  19199. mBfIRBuilder->CreateRetVoid();
  19200. }
  19201. else
  19202. {
  19203. auto innerMethodDef = innerMethodInstance.mMethodInstance->mMethodDef;
  19204. if ((innerMethodDef == methodDef != NULL) && (!CompareMethodSignatures(methodInstance, innerMethodInstance.mMethodInstance)))
  19205. {
  19206. InternalError("Boxing method passthrough error");
  19207. }
  19208. else
  19209. {
  19210. SizedArray<BfIRValue, 8> innerParams;
  19211. BfExprEvaluator exprEvaluator(this);
  19212. if (!innerType->IsValuelessType())
  19213. {
  19214. BfIRValue thisValue = mBfIRBuilder->CreateInBoundsGEP(mCurMethodState->mLocals[0]->mValue, 0, 1);
  19215. BfTypedValue innerVal(thisValue, innerType, true);
  19216. if (boxedType->IsBoxedStructPtr())
  19217. {
  19218. innerVal = LoadValue(innerVal);
  19219. innerVal = BfTypedValue(innerVal.mValue, innerType, true);
  19220. }
  19221. exprEvaluator.PushThis(NULL, innerVal, innerMethodInstance.mMethodInstance, innerParams);
  19222. }
  19223. for (int i = 1; i < (int)mCurMethodState->mLocals.size(); i++)
  19224. {
  19225. BfLocalVariable* localVar = mCurMethodState->mLocals[i];
  19226. BfTypedValue localVal = exprEvaluator.LoadLocal(localVar, true);
  19227. exprEvaluator.PushArg(localVal, innerParams);
  19228. }
  19229. if (!innerMethodInstance.mFunc)
  19230. {
  19231. BF_ASSERT(innerType->IsUnspecializedType());
  19232. }
  19233. else if ((!mIsComptimeModule) && (methodInstance->GetStructRetIdx() != -1))
  19234. {
  19235. mBfIRBuilder->PopulateType(methodInstance->mReturnType);
  19236. auto returnType = BfTypedValue(mBfIRBuilder->GetArgument(methodInstance->GetStructRetIdx()), methodInstance->mReturnType, true);
  19237. exprEvaluator.mReceivingValue = &returnType;
  19238. auto retVal = exprEvaluator.CreateCall(NULL, innerMethodInstance.mMethodInstance, innerMethodInstance.mFunc, true, innerParams, NULL, BfCreateCallFlags_TailCall);
  19239. BF_ASSERT(exprEvaluator.mReceivingValue == NULL); // Ensure it was actually used
  19240. mBfIRBuilder->CreateRetVoid();
  19241. }
  19242. else
  19243. {
  19244. mBfIRBuilder->PopulateType(methodInstance->mReturnType);
  19245. auto retVal = exprEvaluator.CreateCall(NULL, innerMethodInstance.mMethodInstance, innerMethodInstance.mFunc, true, innerParams, NULL, BfCreateCallFlags_TailCall);
  19246. if (mCurMethodInstance->mReturnType->IsValueType())
  19247. retVal = LoadValue(retVal);
  19248. CreateReturn(retVal.mValue);
  19249. }
  19250. }
  19251. }
  19252. }
  19253. mCurMethodState->SetHadReturn(true);
  19254. mCurMethodState->mLeftBlockUncond = true;
  19255. }
  19256. else if (methodDef->mMethodType == BfMethodType_CtorClear)
  19257. {
  19258. SetIllegalSrcPos();
  19259. mBfIRBuilder->ClearDebugLocation();
  19260. PopulateType(mCurTypeInstance, BfPopulateType_Data);
  19261. auto thisVal = GetThis();
  19262. int prevSize = 0;
  19263. if ((mContext->mBfObjectType != NULL) && (mCurTypeInstance->IsObject()))
  19264. {
  19265. prevSize = mContext->mBfObjectType->mInstSize;
  19266. PopulateType(mContext->mBfObjectType);
  19267. // If we have object extensions, clear out starting at the extension
  19268. for (auto& fieldInstance : mContext->mBfObjectType->mFieldInstances)
  19269. {
  19270. if (fieldInstance.GetFieldDef()->mDeclaringType->IsExtension())
  19271. {
  19272. prevSize = fieldInstance.mDataOffset;
  19273. break;
  19274. }
  19275. }
  19276. }
  19277. auto int8PtrType = CreatePointerType(GetPrimitiveType(BfTypeCode_Int8));
  19278. int curSize = mCurTypeInstance->mInstSize;
  19279. if (curSize > prevSize)
  19280. {
  19281. auto int8PtrVal = mBfIRBuilder->CreateBitCast(thisVal.mValue, mBfIRBuilder->MapType(int8PtrType));
  19282. int8PtrVal = mBfIRBuilder->CreateInBoundsGEP(int8PtrVal, GetConstValue(prevSize));
  19283. mBfIRBuilder->CreateMemSet(int8PtrVal, GetConstValue8(0), GetConstValue(curSize - prevSize), GetConstValue(mCurTypeInstance->mInstAlign));
  19284. }
  19285. if ((mCompiler->mOptions.mObjectHasDebugFlags) && (!mIsComptimeModule))
  19286. {
  19287. auto useThis = mCurMethodState->mLocals[0]->mValue;
  19288. auto useThisType = mCurTypeInstance;
  19289. auto checkTypeInst = mCurTypeInstance;
  19290. while (checkTypeInst != NULL)
  19291. {
  19292. for (auto& fieldInstance : checkTypeInst->mFieldInstances)
  19293. {
  19294. auto fieldDef = fieldInstance.GetFieldDef();
  19295. if ((fieldDef == NULL) || (fieldDef->mIsStatic))
  19296. continue;
  19297. if (fieldInstance.IsAppendedObject())
  19298. {
  19299. if (checkTypeInst != useThisType)
  19300. {
  19301. useThis = mBfIRBuilder->CreateBitCast(useThis, mBfIRBuilder->MapType(checkTypeInst));
  19302. useThisType = checkTypeInst;
  19303. }
  19304. BfIRValue fieldAddr = mBfIRBuilder->CreateInBoundsGEP(useThis, 0, fieldInstance.mDataIdx);
  19305. auto int8PtrVal = mBfIRBuilder->CreateBitCast(fieldAddr, mBfIRBuilder->MapType(int8PtrType));
  19306. mBfIRBuilder->CreateStore(GetConstValue8(BfObjectFlag_Deleted), int8PtrVal);
  19307. }
  19308. }
  19309. checkTypeInst = checkTypeInst->mBaseType;
  19310. }
  19311. }
  19312. skipUpdateSrcPos = true;
  19313. }
  19314. else if (((methodDef->mMethodType == BfMethodType_Ctor) || (methodDef->mMethodType == BfMethodType_CtorNoBody)) && (!hasExternSpecifier))
  19315. {
  19316. EmitCtorBody(skipBody);
  19317. }
  19318. else if ((methodDef->mMethodType == BfMethodType_Dtor) && (!hasExternSpecifier))
  19319. {
  19320. EmitDtorBody();
  19321. skipBody = true;
  19322. }
  19323. if ((!mCurTypeInstance->IsBoxed()) && (methodDeclaration != NULL) && (methodDeclaration->mHadYield) && (methodDef->mBody != NULL))
  19324. {
  19325. EmitIteratorBlock(skipBody);
  19326. }
  19327. if ((methodDef->mMethodType == BfMethodType_CtorNoBody) && (!methodDef->mIsStatic) &&
  19328. ((methodInstance->mChainType == BfMethodChainType_ChainHead) || (methodInstance->mChainType == BfMethodChainType_None)))
  19329. {
  19330. // We chain even non-default ctors to the default ctors
  19331. auto defaultCtor = methodInstance;
  19332. if (defaultCtor->mChainType == BfMethodChainType_ChainHead)
  19333. CallChainedMethods(defaultCtor, false);
  19334. }
  19335. auto bodyBlock = BfNodeDynCast<BfBlock>(methodDef->mBody);
  19336. if (!mCompiler->mHasRequiredTypes)
  19337. {
  19338. // Skip processing to avoid errors
  19339. }
  19340. else if (methodDef->mBody == NULL)
  19341. {
  19342. if (methodDeclaration != NULL)
  19343. {
  19344. if (auto operatorDeclaration = BfNodeDynCast<BfOperatorDeclaration>(methodDeclaration))
  19345. {
  19346. if (operatorDeclaration->mIsConvOperator)
  19347. wantsRemoveBody = true;
  19348. }
  19349. }
  19350. bool isDllImport = false;
  19351. if ((importKind == BfImportKind_Import_Static) || (importKind == BfImportKind_Import_Dynamic))
  19352. {
  19353. if (importStrNum != -1)
  19354. {
  19355. if (importKind == BfImportKind_Import_Static)
  19356. {
  19357. if (!mImportFileNames.Contains(importStrNum))
  19358. {
  19359. mImportFileNames.Add(importStrNum);
  19360. }
  19361. }
  19362. }
  19363. }
  19364. else if (methodInstance->GetImportKind() == BfImportKind_Import_Dynamic)
  19365. {
  19366. CreateDllImportMethod();
  19367. }
  19368. else if (((mCurTypeInstance->mTypeDef->mIsDelegate) || (mCurTypeInstance->mTypeDef->mIsFunction)) &&
  19369. (methodDef->mName == "Invoke") && (methodDef->mMethodType == BfMethodType_Normal))
  19370. {
  19371. if (mCurTypeInstance->mTypeDef->mIsFunction)
  19372. {
  19373. // Emit nothing
  19374. }
  19375. else
  19376. {
  19377. CreateDelegateInvokeMethod();
  19378. mCurMethodState->SetHadReturn(true);
  19379. mCurMethodState->mLeftBlockUncond = true;
  19380. }
  19381. }
  19382. else if ((methodDef->mName == BF_METHODNAME_DYNAMICCAST) || (methodDef->mName == BF_METHODNAME_DYNAMICCAST_INTERFACE))
  19383. {
  19384. if (mCurTypeInstance->IsObject())
  19385. {
  19386. CreateDynamicCastMethod();
  19387. }
  19388. else
  19389. {
  19390. mBfIRBuilder->CreateRet(GetDefaultValue(methodInstance->mReturnType));
  19391. mCurMethodState->mHadReturn = true;
  19392. }
  19393. }
  19394. else if ((methodDef->mName == BF_METHODNAME_ENUM_HASFLAG) && (mCurTypeInstance->IsEnum()) && (!mCurTypeInstance->IsBoxed()))
  19395. {
  19396. BfIRValue ret;
  19397. if (mCurMethodState->mLocals[1]->mResolvedType != mCurTypeInstance)
  19398. {
  19399. // This can happen if we provide an invalid name
  19400. AssertErrorState();
  19401. ret = mBfIRBuilder->CreateRet(GetDefaultValue(GetPrimitiveType(BfTypeCode_Boolean)));
  19402. }
  19403. else
  19404. {
  19405. // Unfortunate DebugLoc shenanigans-
  19406. // 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,
  19407. // so we only set the loc on the CreateRet which gets inlined out
  19408. mBfIRBuilder->SaveDebugLocation();
  19409. mBfIRBuilder->ClearDebugLocation();
  19410. BfIRValue fromBool;
  19411. if ((!mCurTypeInstance->IsTypedPrimitive()) || (mCurTypeInstance->IsValuelessType()))
  19412. {
  19413. fromBool = GetDefaultValue(methodInstance->mReturnType);
  19414. }
  19415. else
  19416. {
  19417. auto andResult = mBfIRBuilder->CreateAnd(mCurMethodState->mLocals[0]->mValue, mCurMethodState->mLocals[1]->mValue);
  19418. auto toBool = mBfIRBuilder->CreateCmpNE(andResult, GetDefaultValue(mCurMethodState->mLocals[0]->mResolvedType));
  19419. fromBool = mBfIRBuilder->CreateNumericCast(toBool, false, BfTypeCode_Boolean);
  19420. }
  19421. mBfIRBuilder->RestoreDebugLocation();
  19422. ret = mBfIRBuilder->CreateRet(fromBool);
  19423. //ExtendLocalLifetimes(0);
  19424. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  19425. }
  19426. mCurMethodState->SetHadReturn(true);
  19427. mCurMethodState->mLeftBlockUncond = true;
  19428. }
  19429. else if (((methodDef->mName == BF_METHODNAME_ENUM_GETUNDERLYINGREF) || (methodDef->mName == BF_METHODNAME_ENUM_GETUNDERLYING)) &&
  19430. (mCurTypeInstance->IsEnum()) && (!mCurTypeInstance->IsBoxed()))
  19431. {
  19432. BfIRValue ret;
  19433. // Unfortunate DebugLoc shenanigans-
  19434. // 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,
  19435. // so we only set the loc on the CreateRet which gets inlined out
  19436. mBfIRBuilder->SaveDebugLocation();
  19437. mBfIRBuilder->ClearDebugLocation();
  19438. BfIRValue fromBool;
  19439. mBfIRBuilder->RestoreDebugLocation();
  19440. if ((!mCompiler->mIsResolveOnly) || (mIsComptimeModule))
  19441. {
  19442. if (!mCurTypeInstance->IsValuelessType())
  19443. ret = mBfIRBuilder->CreateRet(GetThis().mValue);
  19444. else
  19445. mBfIRBuilder->CreateRetVoid();
  19446. }
  19447. //ExtendLocalLifetimes(0);
  19448. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  19449. mCurMethodState->SetHadReturn(true);
  19450. mCurMethodState->mLeftBlockUncond = true;
  19451. }
  19452. else if ((mCurTypeInstance->IsEnum()) && (!mCurTypeInstance->IsBoxed()) && (methodDef->mName == BF_METHODNAME_TO_STRING))
  19453. {
  19454. auto enumType = ResolveTypeDef(mCompiler->mEnumTypeDef);
  19455. if (HasExecutedOutput())
  19456. {
  19457. EmitEnumToStringBody();
  19458. }
  19459. mBfIRBuilder->CreateRetVoid();
  19460. mCurMethodState->SetHadReturn(true);
  19461. mCurMethodState->mLeftBlockUncond = true;
  19462. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  19463. }
  19464. else if ((mCurTypeInstance->IsTuple()) && (!mCurTypeInstance->IsBoxed()) && (methodDef->mName == BF_METHODNAME_TO_STRING))
  19465. {
  19466. auto enumType = ResolveTypeDef(mCompiler->mEnumTypeDef);
  19467. if (HasExecutedOutput())
  19468. {
  19469. EmitTupleToStringBody();
  19470. }
  19471. mBfIRBuilder->CreateRetVoid();
  19472. mCurMethodState->SetHadReturn(true);
  19473. mCurMethodState->mLeftBlockUncond = true;
  19474. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  19475. }
  19476. else if (methodDef->mName == BF_METHODNAME_DEFAULT_EQUALS)
  19477. {
  19478. CreateValueTypeEqualsMethod(false);
  19479. skipBody = true;
  19480. skipEndChecks = true;
  19481. }
  19482. else if (methodDef->mName == BF_METHODNAME_DEFAULT_STRICT_EQUALS)
  19483. {
  19484. CreateValueTypeEqualsMethod(true);
  19485. skipBody = true;
  19486. skipEndChecks = true;
  19487. }
  19488. else if ((methodDef->mName == BF_METHODNAME_EQUALS) && (typeDef->GetDefinition() == mCompiler->mValueTypeTypeDef))
  19489. {
  19490. CreateValueTypeEqualsMethod(false);
  19491. skipBody = true;
  19492. skipEndChecks = true;
  19493. }
  19494. else if ((methodDef->mName == BF_METHODNAME_EQUALS) && (mCurTypeInstance->IsDelegate()))
  19495. {
  19496. CreateDelegateEqualsMethod();
  19497. skipBody = true;
  19498. skipEndChecks = true;
  19499. }
  19500. else
  19501. {
  19502. auto propertyDeclaration = methodDef->GetPropertyDeclaration();
  19503. if ((propertyDeclaration != NULL) && (!typeDef->HasAutoProperty(propertyDeclaration)))
  19504. {
  19505. if ((!mCurTypeInstance->IsInterface()) && (!hasExternSpecifier))
  19506. Fail("Body expected", methodDef->GetRefNode());
  19507. }
  19508. else if (methodDef->mMethodType == BfMethodType_PropertyGetter)
  19509. {
  19510. if ((methodInstance->mReturnType->IsRef()) && (!methodDef->mIsMutating) && (mCurTypeInstance->IsValueType()))
  19511. Fail("Auto-implemented ref property getters must declare 'mut'", methodInstance->mMethodDef->GetRefNode());
  19512. if (methodInstance->mReturnType->IsValuelessType())
  19513. {
  19514. mBfIRBuilder->CreateRetVoid();
  19515. }
  19516. else if (HasExecutedOutput())
  19517. {
  19518. String autoPropName = typeDef->GetAutoPropertyName(propertyDeclaration);
  19519. BfFieldInstance* fieldInstance = GetFieldByName(mCurTypeInstance, autoPropName);
  19520. BfFieldDef* fieldDef = NULL;
  19521. if (fieldInstance != NULL)
  19522. fieldDef = fieldInstance->GetFieldDef();
  19523. BfType* retType = methodInstance->mReturnType;
  19524. if (retType->IsRef())
  19525. retType = retType->GetUnderlyingType();
  19526. if ((fieldInstance != NULL) && (fieldInstance->GetResolvedType() == retType) &&
  19527. ((fieldInstance->mDataIdx >= 0) || (fieldDef->IsNonConstStatic())))
  19528. {
  19529. BfTypedValue lookupValue;
  19530. if (fieldDef->IsNonConstStatic())
  19531. lookupValue = ReferenceStaticField(fieldInstance);
  19532. else if (mCurTypeInstance->IsObject())
  19533. lookupValue = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(GetThis().mValue, 0, fieldInstance->mDataIdx), fieldInstance->mResolvedType, true);
  19534. else
  19535. lookupValue = ExtractValue(GetThis(), fieldInstance, fieldInstance->mDataIdx);
  19536. if (methodInstance->mReturnType->IsRef())
  19537. {
  19538. if ((!lookupValue.IsAddr()) && (!lookupValue.mType->IsValuelessType()))
  19539. lookupValue = MakeAddressable(lookupValue);
  19540. }
  19541. else
  19542. lookupValue = LoadOrAggregateValue(lookupValue);
  19543. CreateReturn(lookupValue.mValue);
  19544. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  19545. }
  19546. else
  19547. {
  19548. // This can happen if we have two properties with the same name but different types
  19549. CreateReturn(GetDefaultValue(mCurMethodInstance->mReturnType));
  19550. EmitDefaultReturn();
  19551. }
  19552. }
  19553. else
  19554. {
  19555. CreateReturn(GetDefaultValue(mCurMethodInstance->mReturnType));
  19556. EmitDefaultReturn();
  19557. }
  19558. mCurMethodState->SetHadReturn(true);
  19559. }
  19560. else if (methodDef->mMethodType == BfMethodType_PropertySetter)
  19561. {
  19562. if ((!methodDef->mIsMutating) && (!methodDef->mIsStatic) && (mCurTypeInstance->IsValueType()))
  19563. {
  19564. Fail("Auto-setter must be marked as 'mut'", methodDef->GetRefNode(), true);
  19565. }
  19566. else if (!mCompiler->IsAutocomplete())
  19567. {
  19568. String autoPropName = typeDef->GetAutoPropertyName(propertyDeclaration);
  19569. BfFieldInstance* fieldInstance = GetFieldByName(mCurTypeInstance, autoPropName);
  19570. auto fieldDef = fieldInstance->GetFieldDef();
  19571. auto& lastParam = mCurMethodState->mLocals.back();
  19572. if ((fieldInstance != NULL) && (fieldInstance->GetResolvedType() == lastParam->mResolvedType) &&
  19573. ((fieldInstance->mDataIdx >= 0) || (fieldDef->IsNonConstStatic())))
  19574. {
  19575. BfIRValue lookupAddr;
  19576. if (fieldDef->IsNonConstStatic())
  19577. lookupAddr = ReferenceStaticField(fieldInstance).mValue;
  19578. else
  19579. {
  19580. auto thisValue = GetThis();
  19581. if (thisValue.IsSplat())
  19582. {
  19583. BFMODULE_FATAL(this, "Should not happen");
  19584. }
  19585. if (mCurTypeInstance->IsObject())
  19586. thisValue = LoadValue(thisValue);
  19587. lookupAddr = mBfIRBuilder->CreateInBoundsGEP(thisValue.mValue, 0, fieldInstance->mDataIdx);
  19588. }
  19589. BfExprEvaluator exprEvaluator(this);
  19590. auto localVal = exprEvaluator.LoadLocal(lastParam);
  19591. localVal = LoadOrAggregateValue(localVal);
  19592. if (!localVal.mType->IsValuelessType())
  19593. mBfIRBuilder->CreateAlignedStore(localVal.mValue, lookupAddr, localVal.mType->mAlign);
  19594. }
  19595. else if (!fieldInstance->mResolvedType->IsValuelessType())
  19596. {
  19597. // This can happen if we have two properties with the same name but different types
  19598. AssertErrorState();
  19599. }
  19600. }
  19601. }
  19602. else if ((methodDef->mName == BF_METHODNAME_MARKMEMBERS) || (methodDef->mName == BF_METHODNAME_MARKMEMBERS_STATIC))
  19603. {
  19604. if (mCompiler->mOptions.mEnableRealtimeLeakCheck)
  19605. {
  19606. if (HasCompiledOutput())
  19607. EmitGCMarkMembers();
  19608. }
  19609. else if (!mCurTypeInstance->IsObject())
  19610. {
  19611. }
  19612. }
  19613. else if (methodDef->mName == BF_METHODNAME_FIND_TLS_MEMBERS)
  19614. {
  19615. if (mCompiler->mOptions.mEnableRealtimeLeakCheck)
  19616. {
  19617. if (HasCompiledOutput())
  19618. EmitGCFindTLSMembers();
  19619. }
  19620. }
  19621. }
  19622. }
  19623. else if (!skipBody)
  19624. {
  19625. bool isEmptyBodied = BfNodeDynCast<BfTokenNode>(methodDef->mBody) != NULL;
  19626. bool wantsRetVal = true;
  19627. if ((mIsComptimeModule) && (methodDef->mMethodType != BfMethodType_CtorCalcAppend))
  19628. wantsRetVal = false;
  19629. else if (mCurMethodInstance->mReturnType->IsVar())
  19630. wantsRetVal = false;
  19631. if ((!mCurMethodInstance->mReturnType->IsValuelessType()) && (!isEmptyBodied))
  19632. {
  19633. mBfIRBuilder->PopulateType(mCurMethodInstance->mReturnType);
  19634. if ((!mIsComptimeModule) && (mCurMethodInstance->GetStructRetIdx() != -1))
  19635. {
  19636. auto ptrType = CreatePointerType(mCurMethodInstance->mReturnType);
  19637. auto allocaInst = AllocLocalVariable(ptrType, "__return.addr", false);
  19638. auto storeInst = mBfIRBuilder->CreateAlignedStore(mBfIRBuilder->GetArgument(mCurMethodInstance->GetStructRetIdx()), allocaInst, mCurMethodInstance->mReturnType->mAlign);
  19639. mBfIRBuilder->ClearDebugLocation(storeInst);
  19640. mCurMethodState->mRetValAddr = allocaInst;
  19641. }
  19642. else if (wantsRetVal)
  19643. {
  19644. auto allocaInst = AllocLocalVariable(mCurMethodInstance->mReturnType, "__return", false);
  19645. mCurMethodState->mRetVal = BfTypedValue(allocaInst, mCurMethodInstance->mReturnType, true);
  19646. }
  19647. }
  19648. if (methodDef->mMethodType == BfMethodType_CtorCalcAppend)
  19649. {
  19650. mBfIRBuilder->CreateAlignedStore(GetConstValue(0), mCurMethodState->mRetVal.mValue, mCurMethodState->mRetVal.mType->mAlign);
  19651. BfGetSymbolReferenceKind prevSymbolKind;
  19652. BfAutoComplete* prevAutoComplete;
  19653. if (mCompiler->mResolvePassData != NULL)
  19654. {
  19655. prevSymbolKind = mCompiler->mResolvePassData->mGetSymbolReferenceKind;
  19656. prevAutoComplete = mCompiler->mResolvePassData->mAutoComplete;
  19657. mCompiler->mResolvePassData->mGetSymbolReferenceKind = BfGetSymbolReferenceKind_None;
  19658. }
  19659. EmitCtorCalcAppend();
  19660. if (mCompiler->mResolvePassData != NULL)
  19661. {
  19662. mCompiler->mResolvePassData->mGetSymbolReferenceKind = prevSymbolKind;
  19663. mCompiler->mResolvePassData->mAutoComplete = prevAutoComplete;
  19664. }
  19665. }
  19666. else if (!isEmptyBodied)
  19667. {
  19668. if (!mCurMethodState->mIRExitBlock)
  19669. mCurMethodState->mIRExitBlock = mBfIRBuilder->CreateBlock("exit", true);
  19670. bool isExpressionBody = false;
  19671. if (methodDeclaration != NULL)
  19672. {
  19673. if (methodDeclaration->mFatArrowToken != NULL)
  19674. isExpressionBody = true;
  19675. }
  19676. else if (auto propertyDeclaration = methodDef->GetPropertyDeclaration())
  19677. {
  19678. auto propertyMethodDeclaration = methodDef->GetPropertyMethodDeclaration();
  19679. if ((propertyMethodDeclaration != NULL) && (propertyMethodDeclaration->mFatArrowToken != NULL))
  19680. isExpressionBody = true;
  19681. if (auto propBodyExpr = BfNodeDynCast<BfPropertyBodyExpression>(propertyDeclaration->mDefinitionBlock))
  19682. {
  19683. isExpressionBody = true;
  19684. }
  19685. }
  19686. else
  19687. {
  19688. if (auto block = BfNodeDynCast<BfBlock>(methodDef->mBody))
  19689. {
  19690. if (!block->mChildArr.IsEmpty())
  19691. {
  19692. if (auto exprStmt = BfNodeDynCast<BfExpressionStatement>(block->mChildArr.GetLast()))
  19693. {
  19694. if (exprStmt->mTrailingSemicolon == NULL)
  19695. isExpressionBody = true;
  19696. }
  19697. }
  19698. }
  19699. else
  19700. isExpressionBody = true;
  19701. }
  19702. DoCEEmit(methodInstance);
  19703. if (methodInstance->mCeCancelled)
  19704. mIgnoreErrors = true;
  19705. if (auto fieldDtorBody = BfNodeDynCast<BfFieldDtorDeclaration>(methodDef->mBody))
  19706. {
  19707. while (fieldDtorBody != NULL)
  19708. {
  19709. VisitEmbeddedStatement(fieldDtorBody->mBody);
  19710. fieldDtorBody = fieldDtorBody->mNextFieldDtor;
  19711. }
  19712. }
  19713. else if (!isExpressionBody)
  19714. {
  19715. auto bodyBlock = BfNodeDynCast<BfBlock>(methodDef->mBody);
  19716. mCurMethodState->mHeadScope.mAstBlock = bodyBlock;
  19717. mCurMethodState->mHeadScope.mCloseNode = bodyBlock->mCloseBrace;
  19718. VisitCodeBlock(bodyBlock);
  19719. BF_ASSERT(mCurMethodState->mCurScope == &mCurMethodState->mHeadScope);
  19720. }
  19721. else if (auto expressionBody = BfNodeDynCast<BfExpression>(methodDef->mBody))
  19722. {
  19723. // if ((methodDef->mMethodType != BfMethodType_Normal) && (propertyDeclaration == NULL))
  19724. // {
  19725. // BF_ASSERT(methodDeclaration->mFatArrowToken != NULL);
  19726. // Fail("Only normal methods can have expression bodies", methodDeclaration->mFatArrowToken);
  19727. // }
  19728. auto expectingType = mCurMethodInstance->mReturnType;
  19729. // What was this error for?
  19730. // if ((expectingType->IsVoid()) && (IsInSpecializedSection()))
  19731. // {
  19732. // Warn(0, "Using a 'void' return with an expression-bodied method isn't needed. Consider removing '=>' token", methodDeclaration->mFatArrowToken);
  19733. // }
  19734. BfEvalExprFlags exprEvalFlags = (BfEvalExprFlags)(BfEvalExprFlags_AllowRefExpr | BfEvalExprFlags_IsExpressionBody);
  19735. if (expectingType->IsVoid())
  19736. {
  19737. exprEvalFlags = (BfEvalExprFlags)(exprEvalFlags | BfEvalExprFlags_NoCast);
  19738. bool wasReturnGenericParam = false;
  19739. if ((mCurMethodState->mClosureState != NULL) && (mCurMethodState->mClosureState->mReturnType != NULL))
  19740. {
  19741. wasReturnGenericParam = mCurMethodState->mClosureState->mReturnType->IsGenericParam();
  19742. }
  19743. else
  19744. {
  19745. auto unspecializedMethodInstance = GetUnspecializedMethodInstance(mCurMethodInstance);
  19746. if ((unspecializedMethodInstance != NULL) && (unspecializedMethodInstance->mReturnType->IsGenericParam()))
  19747. wasReturnGenericParam = true;
  19748. }
  19749. // If we the void return was from a generic specialization, allow us to return a void result,
  19750. // otherwise treat expression as though it must be a statement
  19751. bool isStatement = expressionBody->VerifyIsStatement(mCompiler->mPassInstance, wasReturnGenericParam);
  19752. if (isStatement)
  19753. expectingType = NULL;
  19754. }
  19755. BfExprEvaluator exprEvaluator(this);
  19756. if (mCurMethodInstance->mMethodDef->mIsReadOnly)
  19757. exprEvaluator.mAllowReadOnlyReference = true;
  19758. UpdateSrcPos(expressionBody);
  19759. auto retVal = CreateValueFromExpression(exprEvaluator, expressionBody, expectingType, exprEvalFlags);
  19760. if ((retVal) && (!retVal.mType->IsVar()) && (expectingType != NULL))
  19761. {
  19762. mCurMethodState->mHadReturn = true;
  19763. if (!mCurMethodState->mLeftBlockUncond)
  19764. {
  19765. retVal = LoadOrAggregateValue(retVal);
  19766. EmitReturn(retVal);
  19767. }
  19768. }
  19769. }
  19770. }
  19771. }
  19772. BF_ASSERT(mCurMethodState->mCurScope == &mCurMethodState->mHeadScope);
  19773. if (skipUpdateSrcPos)
  19774. {
  19775. // Skip
  19776. }
  19777. else if ((bodyBlock != NULL) && (bodyBlock->mCloseBrace != NULL))
  19778. UpdateSrcPos(bodyBlock->mCloseBrace);
  19779. else if (methodDef->mBody != NULL)
  19780. UpdateSrcPos(methodDef->mBody);
  19781. else if (methodDeclaration != NULL)
  19782. UpdateSrcPos(methodDeclaration);
  19783. else if (methodDef->mDeclaringType->mTypeDeclaration != NULL)
  19784. UpdateSrcPos(methodDef->mDeclaringType->mTypeDeclaration);
  19785. else
  19786. UseDefaultSrcPos();
  19787. if (methodDef->mMethodType == BfMethodType_CtorCalcAppend)
  19788. {
  19789. if (mCurMethodState->mRetVal)
  19790. {
  19791. mCurMethodState->SetHadReturn(true);
  19792. auto retVal = mBfIRBuilder->CreateLoad(mCurMethodState->mRetVal.mValue);
  19793. mBfIRBuilder->CreateRet(retVal);
  19794. }
  19795. else
  19796. AssertErrorState();
  19797. }
  19798. mCurMethodState->mHeadScope.mDone = true;
  19799. if (!mCurMethodState->mHadReturn)
  19800. {
  19801. // Clear off the stackallocs that have occurred after a scopeData break
  19802. EmitDeferredScopeCalls(false, &mCurMethodState->mHeadScope, mCurMethodState->mIRExitBlock);
  19803. }
  19804. EmitDeferredCallProcessorInstances(&mCurMethodState->mHeadScope);
  19805. if (mCurMethodState->mIRExitBlock)
  19806. {
  19807. for (auto preExitBlock : mCurMethodState->mHeadScope.mAtEndBlocks)
  19808. mBfIRBuilder->MoveBlockToEnd(preExitBlock);
  19809. mBfIRBuilder->MoveBlockToEnd(mCurMethodState->mIRExitBlock);
  19810. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRExitBlock);
  19811. if ((!mCurMethodState->mDIRetVal) && (wantsDIData))
  19812. CreateDIRetVal();
  19813. }
  19814. for (auto localVar : mCurMethodState->mLocals)
  19815. {
  19816. if (auto autoCtorDecl = BfNodeDynCast<BfAutoConstructorDeclaration>(methodDeclaration))
  19817. {
  19818. //
  19819. }
  19820. else if ((skipEndChecks) || (methodDef->mBody == NULL))
  19821. break;
  19822. LocalVariableDone(localVar, true);
  19823. }
  19824. if (mCurMethodState->mIRExitBlock)
  19825. {
  19826. if ((mCurMethodState->mRetVal) &&
  19827. ((mIsComptimeModule) || (mCurMethodInstance->GetStructRetIdx() == -1)))
  19828. {
  19829. auto loadedVal = mBfIRBuilder->CreateAlignedLoad(mCurMethodState->mRetVal.mValue, mCurMethodState->mRetVal.mType->mAlign);
  19830. CreateReturn(loadedVal);
  19831. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  19832. if (mCurMethodState->mDIRetVal)
  19833. mBfIRBuilder->DbgLifetimeEnd(mCurMethodState->mDIRetVal);
  19834. }
  19835. else
  19836. {
  19837. // Have something on the last line to step onto
  19838. if (mHasFullDebugInfo)
  19839. {
  19840. if ((bodyBlock != NULL) && (bodyBlock->mCloseBrace != NULL))
  19841. UpdateSrcPos(bodyBlock->mCloseBrace);
  19842. EmitEnsureInstructionAt();
  19843. if ((irParamCount == 0) && (!IsTargetingBeefBackend()) && (mCompiler->mOptions.mAllowHotSwapping))
  19844. {
  19845. // This may be a case where we only emit 4 bytes, whereas we need 5 for a hot replace jump
  19846. mBfIRBuilder->EnsureFunctionPatchable();
  19847. }
  19848. }
  19849. mBfIRBuilder->CreateRetVoid();
  19850. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  19851. if (mCurMethodState->mDIRetVal)
  19852. mBfIRBuilder->DbgLifetimeEnd(mCurMethodState->mDIRetVal);
  19853. }
  19854. }
  19855. if ((mCurMethodInstance->mReturnType == NULL) || (mCurMethodInstance->mReturnType->IsValuelessType()))
  19856. {
  19857. if ((!mCurMethodState->mHadReturn) && (!mCurMethodState->mIRExitBlock))
  19858. {
  19859. if ((!mIsComptimeModule) && (irParamCount == 0) && (!IsTargetingBeefBackend()) && (mCompiler->mOptions.mAllowHotSwapping))
  19860. {
  19861. // This may be a case where we only emit 4 bytes, whereas we need 5 for a hot replace jump
  19862. mBfIRBuilder->EnsureFunctionPatchable();
  19863. }
  19864. mBfIRBuilder->CreateRetVoid();
  19865. }
  19866. }
  19867. else
  19868. {
  19869. if (!mCurMethodState->mHadReturn)
  19870. {
  19871. auto refNode = mCurMethodInstance->mMethodDef->GetRefNode();
  19872. if (bodyBlock != NULL)
  19873. {
  19874. if (bodyBlock->mCloseBrace != NULL)
  19875. {
  19876. BfAstNode* target = bodyBlock->mCloseBrace;
  19877. if (!mCompiler->mHasRequiredTypes)
  19878. {
  19879. AddFailType(mCurTypeInstance);
  19880. mHadBuildError = true;
  19881. }
  19882. else
  19883. Fail("Method must return value", target);
  19884. }
  19885. else
  19886. {
  19887. // It's possible to not have a closing brace if the method ends in an EOF
  19888. AssertErrorState();
  19889. }
  19890. }
  19891. }
  19892. }
  19893. // Move 'init' into 'entry'
  19894. mBfIRBuilder->MergeBlockDown(mCurMethodState->mIRInitBlock, mCurMethodState->mIREntryBlock);
  19895. mBfIRBuilder->MergeBlockDown(mCurMethodState->mIRHeadBlock, mCurMethodState->mIREntryBlock);
  19896. if (((mCurMethodInstance->mIsUnspecialized) /*|| (typeDef->mIsFunction)*/ || (mCurTypeInstance->IsUnspecializedType())) &&
  19897. (!mIsComptimeModule))
  19898. {
  19899. // Don't keep instructions for unspecialized types
  19900. mBfIRBuilder->Func_DeleteBody(mCurMethodInstance->mIRFunction);
  19901. }
  19902. // Avoid linking any internal funcs that were just supposed to be comptime-accessible
  19903. /*if ((methodDef->mHasComptime) && (!mIsComptimeModule))
  19904. wantsRemoveBody = true;*/
  19905. if ((hasExternSpecifier) && (!skipBody))
  19906. {
  19907. // If we hot swap, we want to make sure at least one method refers to this extern method so it gets pulled in
  19908. // incase it gets called later by some hot-loaded coded
  19909. if ((mCompiler->mOptions.mAllowHotSwapping) && (mCurMethodInstance->mIRFunction) && (!mCurMethodInstance->mIRFunction.IsFake()) && (mCurTypeInstance != mContext->mBfObjectType))
  19910. {
  19911. if (!mCurMethodInstance->mMethodDef->mName.StartsWith("Comptime_"))
  19912. CreateFakeCallerMethod(mangledName);
  19913. }
  19914. mBfIRBuilder->Func_DeleteBody(mCurMethodInstance->mIRFunction);
  19915. }
  19916. else if ((methodInstance->GetImportKind() == BfImportKind_Import_Dynamic) && (!mCompiler->IsHotCompile()))
  19917. {
  19918. // We only need the DLL stub when we may be hot swapping
  19919. mBfIRBuilder->Func_DeleteBody(mCurMethodInstance->mIRFunction);
  19920. }
  19921. else if (wantsRemoveBody)
  19922. mBfIRBuilder->Func_DeleteBody(mCurMethodInstance->mIRFunction);
  19923. // We don't want to hold on to pointers to LLVMFunctions of unspecialized types.
  19924. // This allows us to delete the mScratchModule LLVM module without rebuilding all
  19925. // unspecialized types
  19926. if (((mCurTypeInstance->IsUnspecializedType()) && (!mIsComptimeModule)) ||
  19927. (mCurTypeInstance->IsInterface()))
  19928. {
  19929. BfLogSysM("ProcessMethod Clearing IRFunction: %p\n", methodInstance);
  19930. methodInstance->mIRFunction = BfIRFunction();
  19931. }
  19932. CheckAddFailType();
  19933. if (mHadBuildError)
  19934. prevHadBuildError.CancelRestore();
  19935. if (mHadBuildWarning)
  19936. prevHadWarning.CancelRestore();
  19937. if (!methodDef->mIsLocalMethod)
  19938. ProcessMethod_ProcessDeferredLocals();
  19939. prevIgnoreWrites.Restore();
  19940. mBfIRBuilder->SetActiveFunction(prevActiveFunction);
  19941. if (methodState.mHotDataReferenceBuilder != NULL)
  19942. {
  19943. AddHotDataReferences(&hotDataReferenceBuilder);
  19944. }
  19945. else
  19946. {
  19947. if ((methodInstance->mHotMethod != NULL) && (!methodInstance->mIsReified))
  19948. {
  19949. // Remove the hot method data
  19950. auto hotMethod = methodInstance->mHotMethod;
  19951. auto prevMethod = hotMethod->mPrevVersion;
  19952. if (prevMethod != NULL)
  19953. {
  19954. // If there's a prev method then pull its data into the main HotMethod.
  19955. // This, in effect, removes the 'hotMethod' data and rebases 'prevMethod'
  19956. // over to the main HotMethod definition to keep the HotMethod address
  19957. // invariant
  19958. for (auto ref : hotMethod->mReferences)
  19959. ref->Deref();
  19960. hotMethod->mReferences.Clear();
  19961. BF_ASSERT(prevMethod->mRefCount == 1);
  19962. hotMethod->mReferences = prevMethod->mReferences;
  19963. if (hotMethod->mSrcTypeVersion != NULL)
  19964. hotMethod->mSrcTypeVersion->Deref();
  19965. hotMethod->mSrcTypeVersion = prevMethod->mSrcTypeVersion;
  19966. prevMethod->mSrcTypeVersion = NULL;
  19967. prevMethod->mReferences.Clear();
  19968. hotMethod->mPrevVersion = prevMethod->mPrevVersion;
  19969. prevMethod->mPrevVersion = NULL;
  19970. prevMethod->Deref();
  19971. }
  19972. hotMethod->Deref();
  19973. methodInstance->mHotMethod = NULL;
  19974. }
  19975. }
  19976. }
  19977. String BfModule::GetLocalMethodName(const StringImpl& baseName, BfAstNode* anchorNode, BfMethodState* declMethodState, BfMixinState* declMixinState)
  19978. {
  19979. String name;
  19980. bool found = false;
  19981. auto checkMethodState = mCurMethodState;
  19982. while (checkMethodState != NULL)
  19983. {
  19984. if (checkMethodState->mClosureState == NULL)
  19985. break;
  19986. if (checkMethodState->mClosureState->mClosureMethodDef != NULL)
  19987. {
  19988. found = true;
  19989. name += checkMethodState->mClosureState->mClosureMethodDef->mName;
  19990. break;
  19991. }
  19992. checkMethodState = checkMethodState->mPrevMethodState;
  19993. }
  19994. if (!found)
  19995. name += mCurMethodInstance->mMethodDef->mName;
  19996. int prevSepPos = (int)name.LastIndexOf('$');
  19997. if (prevSepPos != -1)
  19998. {
  19999. name.RemoveToEnd(prevSepPos);
  20000. }
  20001. name += "@";
  20002. name += baseName;
  20003. HashContext hashCtx;
  20004. if (anchorNode != NULL)
  20005. {
  20006. hashCtx.Mixin(anchorNode->GetStartCharId());
  20007. }
  20008. //
  20009. {
  20010. auto checkMethodState = declMethodState;
  20011. auto checkMixinState = declMixinState;
  20012. while (checkMethodState != NULL)
  20013. {
  20014. if (checkMixinState != NULL)
  20015. {
  20016. hashCtx.Mixin(checkMixinState->mSource->GetStartCharId());
  20017. }
  20018. checkMethodState = checkMethodState->mPrevMethodState;
  20019. if (checkMethodState != NULL)
  20020. checkMixinState = checkMethodState->mMixinState;
  20021. }
  20022. }
  20023. auto rootMethodState = mCurMethodState->GetRootMethodState();
  20024. if ((rootMethodState != NULL) && (rootMethodState->mMethodInstance != NULL) && (rootMethodState->mMethodInstance->mMethodInfoEx != NULL))
  20025. {
  20026. for (auto methodGenericArg : rootMethodState->mMethodInstance->mMethodInfoEx->mMethodGenericArguments)
  20027. {
  20028. StringT<512> genericTypeName;
  20029. BfMangler::Mangle(genericTypeName, mCompiler->GetMangleKind(), methodGenericArg);
  20030. hashCtx.MixinStr(genericTypeName);
  20031. }
  20032. }
  20033. uint64 hashVal = hashCtx.Finish64();
  20034. name += "$";
  20035. name += BfTypeUtils::HashEncode64(hashVal);
  20036. return name;
  20037. }
  20038. BfMethodDef* BfModule::GetLocalMethodDef(BfLocalMethod* localMethod)
  20039. {
  20040. if (localMethod->mMethodDef != NULL)
  20041. return localMethod->mMethodDef;
  20042. auto rootMethodState = mCurMethodState->GetRootMethodState();
  20043. auto declMethodState = localMethod->mDeclMethodState;
  20044. auto declMixinState = localMethod->mDeclMixinState;
  20045. auto typeInst = mCurTypeInstance;
  20046. BfAstNode* body = NULL;
  20047. BfAstNode* anchorNode = NULL;
  20048. auto _AllocDirectTypeRef = [&](BfType* type)
  20049. {
  20050. BfDirectTypeReference* directTypeRef = localMethod->mDirectTypeRefs.Alloc();
  20051. directTypeRef->Init(type);
  20052. return directTypeRef;
  20053. };
  20054. auto methodDeclaration = localMethod->mMethodDeclaration;
  20055. if (methodDeclaration != NULL)
  20056. {
  20057. body = methodDeclaration->mBody;
  20058. anchorNode = methodDeclaration->mOpenParen;
  20059. }
  20060. else
  20061. {
  20062. body = localMethod->mLambdaBindExpr->mBody;
  20063. anchorNode = localMethod->mLambdaBindExpr->mFatArrowToken;
  20064. }
  20065. BF_ASSERT(rootMethodState->mCurLocalVarId >= 0);
  20066. int methodLocalIdx = rootMethodState->mCurLocalVarId++;
  20067. BfMethodDef* methodDef;
  20068. BfMethodDef* outerMethodDef = NULL;
  20069. if (localMethod->mOuterLocalMethod != NULL)
  20070. outerMethodDef = localMethod->mOuterLocalMethod->mMethodDef;
  20071. else if (rootMethodState->mMethodInstance != NULL)
  20072. outerMethodDef = rootMethodState->mMethodInstance->mMethodDef;
  20073. if (methodDeclaration != NULL)
  20074. {
  20075. BfDefBuilder defBuilder(mCompiler->mSystem);
  20076. defBuilder.mCurSource = localMethod->mMethodDeclaration->GetParser();
  20077. defBuilder.mPassInstance = mCompiler->mPassInstance;
  20078. defBuilder.mCurTypeDef = mCurMethodInstance->mMethodDef->mDeclaringType;
  20079. defBuilder.mCurDeclaringTypeDef = defBuilder.mCurTypeDef;
  20080. methodDef = defBuilder.CreateMethodDef(methodDeclaration, outerMethodDef);
  20081. }
  20082. else
  20083. {
  20084. auto invokeMethod = localMethod->mLambdaInvokeMethodInstance;
  20085. methodDef = new BfMethodDef();
  20086. methodDef->mName = localMethod->mMethodName;
  20087. methodDef->mDeclaringType = mCurMethodInstance->mMethodDef->mDeclaringType;
  20088. methodDef->mReturnTypeRef = _AllocDirectTypeRef(invokeMethod->mReturnType);
  20089. methodDef->mBody = body;
  20090. for (int paramIdx = 0; paramIdx < invokeMethod->GetParamCount(); paramIdx++)
  20091. {
  20092. auto paramType = invokeMethod->GetParamType(paramIdx);
  20093. String paramName;
  20094. if (paramIdx < (int)localMethod->mLambdaBindExpr->mParams.size())
  20095. paramName = localMethod->mLambdaBindExpr->mParams[paramIdx]->ToString();
  20096. else
  20097. paramName = invokeMethod->GetParamName(paramIdx);
  20098. auto paramDef = new BfParameterDef();
  20099. paramDef->mTypeRef = _AllocDirectTypeRef(paramType);
  20100. paramDef->mName = paramName;
  20101. methodDef->mParams.Add(paramDef);
  20102. }
  20103. if (outerMethodDef != NULL)
  20104. {
  20105. for (auto genericParam : outerMethodDef->mGenericParams)
  20106. {
  20107. auto* copiedGenericParamDef = new BfGenericParamDef();
  20108. *copiedGenericParamDef = *genericParam;
  20109. methodDef->mGenericParams.Add(copiedGenericParamDef);
  20110. }
  20111. }
  20112. }
  20113. methodDef->mIdx = ~methodLocalIdx;
  20114. BF_ASSERT(!localMethod->mExpectedFullName.IsEmpty());
  20115. methodDef->mName = localMethod->mExpectedFullName;
  20116. // methodDef->mName = GetLocalMethodName(methodDef->mName, anchorNode, declMethodState, declMixinState);
  20117. //
  20118. // if (!localMethod->mExpectedFullName.IsEmpty())
  20119. // BF_ASSERT(methodDef->mName == localMethod->mExpectedFullName);
  20120. methodDef->mIsStatic = true;
  20121. methodDef->mIsLocalMethod = true;
  20122. methodDef->mIsVirtual = false;
  20123. localMethod->mMethodDef = methodDef;
  20124. auto methodInstanceGroup = new BfMethodInstanceGroup();
  20125. localMethod->mMethodInstanceGroup = methodInstanceGroup;
  20126. methodInstanceGroup->mMethodIdx = -1;
  20127. methodInstanceGroup->mOwner = mCurTypeInstance;
  20128. methodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  20129. if ((declMethodState->mMixinState != NULL) && (declMethodState->mMixinState->mTarget))
  20130. {
  20131. methodInstanceGroup->mOwner = declMethodState->mMixinState->mTarget.mType->ToTypeInstance();
  20132. BF_ASSERT(methodInstanceGroup->mOwner != NULL);
  20133. }
  20134. if ((mCompiler->mResolvePassData != NULL) && (methodDeclaration != NULL))
  20135. {
  20136. mCompiler->mResolvePassData->HandleLocalReference(methodDeclaration->mNameNode, typeInst->mTypeDef, rootMethodState->mMethodInstance->mMethodDef, methodLocalIdx);
  20137. auto autoComplete = mCompiler->mResolvePassData->mAutoComplete;
  20138. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(methodDeclaration->mNameNode)))
  20139. {
  20140. autoComplete->SetDefinitionLocation(methodDeclaration->mNameNode);
  20141. autoComplete->mInsertStartIdx = methodDeclaration->mNameNode->GetSrcStart();
  20142. autoComplete->mInsertEndIdx = methodDeclaration->mNameNode->GetSrcEnd();
  20143. autoComplete->mDefType = typeInst->mTypeDef;
  20144. autoComplete->mDefMethod = rootMethodState->mMethodInstance->mMethodDef;
  20145. autoComplete->mReplaceLocalId = methodLocalIdx;
  20146. }
  20147. }
  20148. return localMethod->mMethodDef;
  20149. }
  20150. BfModuleMethodInstance BfModule::GetLocalMethodInstance(BfLocalMethod* localMethod, const BfTypeVector& methodGenericArguments, BfMethodInstance* methodInstance, bool force)
  20151. {
  20152. BP_ZONE_F("GetLocalMethodInstance %s", localMethod->mMethodName.c_str());
  20153. BfLogSysM("GetLocalMethodInstance %p\n", localMethod);
  20154. auto rootMethodState = mCurMethodState->GetRootMethodState();
  20155. auto declMethodState = localMethod->mDeclMethodState;
  20156. auto declMixinState = localMethod->mDeclMixinState;
  20157. auto callerMethodState = mCurMethodState;
  20158. auto typeInst = mCurTypeInstance;
  20159. if (mCurMethodState->mMixinState != NULL)
  20160. {
  20161. typeInst = mCurMethodState->mMixinState->mMixinMethodInstance->GetOwner();
  20162. }
  20163. auto methodDef = GetLocalMethodDef(localMethod);
  20164. BfAstNode* body = NULL;
  20165. auto methodDeclaration = localMethod->mMethodDeclaration;
  20166. if (methodDeclaration != NULL)
  20167. {
  20168. body = methodDeclaration->mBody;
  20169. }
  20170. else
  20171. {
  20172. body = localMethod->mLambdaBindExpr->mBody;
  20173. }
  20174. bool hadConcreteInterfaceGenericArgument = false;
  20175. BfTypeVector sanitizedMethodGenericArguments;
  20176. // Ignore the outermost method's generic method arguments for the purpose of determining if we are the 'default' (ie: unspecialized)
  20177. // version of this method for this pass through the outermost method
  20178. int dependentGenericStartIdx = 0;
  20179. if ((rootMethodState->mMethodInstance != NULL) && (rootMethodState->mMethodInstance->mMethodInfoEx != NULL))
  20180. dependentGenericStartIdx = (int)rootMethodState->mMethodInstance->mMethodInfoEx->mMethodGenericArguments.size();
  20181. BfMethodInstance* outerMethodInstance = mCurMethodInstance;
  20182. if (methodGenericArguments.size() == 0)
  20183. {
  20184. if ((rootMethodState->mMethodInstance != NULL) && (rootMethodState->mMethodInstance->mMethodInfoEx != NULL))
  20185. sanitizedMethodGenericArguments = rootMethodState->mMethodInstance->mMethodInfoEx->mMethodGenericArguments;
  20186. }
  20187. else
  20188. {
  20189. int genericArgIdx = 0;
  20190. // for (; genericArgIdx < (int)outerMethodInstance->mMethodGenericArguments.size(); genericArgIdx++)
  20191. // {
  20192. // BF_ASSERT(methodGenericArguments[genericArgIdx] == outerMethodInstance->mMethodGenericArguments[genericArgIdx]);
  20193. // sanitizedMethodGenericArguments.push_back(methodGenericArguments[genericArgIdx]);
  20194. // }
  20195. for (; genericArgIdx < (int)methodGenericArguments.size(); genericArgIdx++)
  20196. {
  20197. auto genericArgType = methodGenericArguments[genericArgIdx];
  20198. BF_ASSERT(!genericArgType->IsRef());
  20199. if (genericArgType->IsConcreteInterfaceType())
  20200. {
  20201. hadConcreteInterfaceGenericArgument = true;
  20202. auto concreteInterfaceType = (BfConcreteInterfaceType*)genericArgType;
  20203. genericArgType = concreteInterfaceType->mInterface;
  20204. }
  20205. sanitizedMethodGenericArguments.push_back(genericArgType);
  20206. }
  20207. }
  20208. bool wantPrematureMethodInstance = false;
  20209. if (!force)
  20210. {
  20211. wantPrematureMethodInstance = (callerMethodState->mClosureState != NULL) && (callerMethodState->mClosureState->mCaptureVisitingBody);
  20212. }
  20213. auto methodInstGroup = localMethod->mMethodInstanceGroup;
  20214. bool isDefaultPass = true;
  20215. BfTypeVector lookupMethodGenericArguments;
  20216. for (int genericArgIdx = dependentGenericStartIdx; genericArgIdx < (int)methodGenericArguments.size(); genericArgIdx++)
  20217. {
  20218. auto genericArgType = methodGenericArguments[genericArgIdx];
  20219. BF_ASSERT(!genericArgType->IsRef());
  20220. lookupMethodGenericArguments.Add(genericArgType);
  20221. if (genericArgType->IsGenericParam())
  20222. {
  20223. auto genericParam = (BfGenericParamType*)genericArgType;
  20224. if ((genericParam->mGenericParamKind != BfGenericParamKind_Method) || (genericParam->mGenericParamIdx != genericArgIdx))
  20225. isDefaultPass = false;
  20226. }
  20227. else
  20228. {
  20229. isDefaultPass = false;
  20230. }
  20231. }
  20232. bool hadExistingMethodInstance = false;
  20233. if (methodInstance != NULL)
  20234. {
  20235. hadExistingMethodInstance = true;
  20236. }
  20237. else
  20238. {
  20239. if (isDefaultPass)
  20240. {
  20241. methodInstance = methodInstGroup->mDefault;
  20242. if (methodInstance != NULL)
  20243. {
  20244. hadExistingMethodInstance = true;
  20245. }
  20246. else
  20247. {
  20248. methodInstance = new BfMethodInstance();
  20249. methodInstGroup->mDefault = methodInstance;
  20250. }
  20251. }
  20252. else
  20253. {
  20254. BF_ASSERT(sanitizedMethodGenericArguments.size() != 0);
  20255. if (methodInstGroup->mMethodSpecializationMap == NULL)
  20256. methodInstGroup->mMethodSpecializationMap = new BfMethodInstanceGroup::MapType();
  20257. BfMethodInstance** methodInstancePtr = NULL;
  20258. if (!methodInstGroup->mMethodSpecializationMap->TryAdd(lookupMethodGenericArguments, NULL, &methodInstancePtr))
  20259. {
  20260. methodInstance = *methodInstancePtr;
  20261. hadExistingMethodInstance = true;
  20262. }
  20263. else
  20264. {
  20265. methodInstance = new BfMethodInstance();
  20266. *methodInstancePtr = methodInstance;
  20267. }
  20268. }
  20269. }
  20270. if (hadExistingMethodInstance)
  20271. {
  20272. if ((!methodInstance->mDisallowCalling) ||
  20273. ((wantPrematureMethodInstance) && (methodInstance->mDisallowCalling)))
  20274. return BfModuleMethodInstance(methodInstance);
  20275. BF_ASSERT((methodInstance->mMethodInfoEx == NULL) || (methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureClosureState == NULL));
  20276. }
  20277. else
  20278. {
  20279. auto methodInfoEx = methodInstance->GetMethodInfoEx();
  20280. methodInfoEx->mClosureInstanceInfo = new BfClosureInstanceInfo();
  20281. methodInfoEx->mClosureInstanceInfo->mLocalMethod = localMethod;
  20282. methodInstance->mIsReified = mCurMethodInstance->mIsReified;
  20283. methodInstance->mIsAutocompleteMethod = mCurMethodInstance->mIsAutocompleteMethod;
  20284. methodInstance->mMethodDef = methodDef;
  20285. methodInstance->mMethodInstanceGroup = localMethod->mMethodInstanceGroup;
  20286. if (hadConcreteInterfaceGenericArgument)
  20287. methodInstance->mIgnoreBody = true;
  20288. methodInfoEx->mMethodGenericArguments = sanitizedMethodGenericArguments;
  20289. for (auto genericArg : sanitizedMethodGenericArguments)
  20290. {
  20291. if (genericArg->IsPrimitiveType())
  20292. genericArg = GetWrappedStructType(genericArg);
  20293. AddDependency(genericArg, typeInst, BfDependencyMap::DependencyFlag_MethodGenericArg);
  20294. }
  20295. for (int genericParamIdx = (int)sanitizedMethodGenericArguments.size(); genericParamIdx < (int)methodDef->mGenericParams.size(); genericParamIdx++)
  20296. {
  20297. auto genericParamType = GetGenericParamType(BfGenericParamKind_Method, genericParamIdx);
  20298. methodInfoEx->mMethodGenericArguments.push_back(genericParamType);
  20299. }
  20300. SetupMethodIdHash(methodInstance);
  20301. }
  20302. auto _SetupMethodInstance = [&]()
  20303. {
  20304. BF_ASSERT(methodInstance->GetNumGenericParams() == 0);
  20305. // Generic constraints
  20306. for (int genericParamIdx = 0; genericParamIdx < (int)methodDef->mGenericParams.size(); genericParamIdx++)
  20307. {
  20308. auto genericParamInstance = new BfGenericMethodParamInstance(methodDef, genericParamIdx);
  20309. methodInstance->GetMethodInfoEx()->mGenericParams.push_back(genericParamInstance);
  20310. }
  20311. for (int externConstraintIdx = 0; externConstraintIdx < (int)methodDef->mExternalConstraints.size(); externConstraintIdx++)
  20312. {
  20313. auto genericParamInstance = new BfGenericMethodParamInstance(methodDef, externConstraintIdx + (int)methodDef->mGenericParams.size());
  20314. methodInstance->GetMethodInfoEx()->mGenericParams.push_back(genericParamInstance);
  20315. }
  20316. };
  20317. //////////////////////////////////////////////////////////////////////////
  20318. auto _VisitLambdaBody = [&]()
  20319. {
  20320. if (localMethod->mDeclOnly)
  20321. return;
  20322. if (mCompiler->mCanceling)
  20323. return;
  20324. if (auto blockBody = BfNodeDynCast<BfBlock>(body))
  20325. {
  20326. VisitCodeBlock(blockBody);
  20327. }
  20328. else if (auto bodyExpr = BfNodeDynCast<BfExpression>(body))
  20329. {
  20330. BfType* expectType = NULL;
  20331. if (!methodInstance->mReturnType->IsVoid())
  20332. expectType = methodInstance->mReturnType;
  20333. CreateValueFromExpression(bodyExpr, expectType, BfEvalExprFlags_AllowRefExpr);
  20334. }
  20335. };
  20336. auto _SafeResolveTypeRef = [&](BfTypeReference* typeRef)
  20337. {
  20338. SetAndRestoreValue<bool> prevIgnoreError(mIgnoreErrors, true);
  20339. auto result = ResolveTypeRef(typeRef);
  20340. if (result == NULL)
  20341. result = mContext->mBfObjectType;
  20342. return result;
  20343. };
  20344. BfTypeInstance* outerClosure = NULL;
  20345. if ((declMethodState->mClosureState != NULL) && (!declMethodState->mClosureState->mCapturing))
  20346. outerClosure = declMethodState->mClosureState->mClosureType;
  20347. BfMethodState methodState;
  20348. methodState.mPrevMethodState = declMethodState;//mCurMethodState;
  20349. BfIRFunctionType funcType;
  20350. auto voidType = GetPrimitiveType(BfTypeCode_None);
  20351. SizedArray<BfIRType, 0> paramTypes;
  20352. funcType = mBfIRBuilder->CreateFunctionType(mBfIRBuilder->MapType(voidType), paramTypes, methodInstance->IsVarArgs());
  20353. mBfIRBuilder->SaveDebugLocation();
  20354. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  20355. auto prevActiveFunction = mBfIRBuilder->GetActiveFunction();
  20356. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, true);
  20357. BfDeferredLocalAssignData deferredLocalAssignData;
  20358. //TODO: Why did we do this? It can cause us to pull in local variables that don't belong to us...
  20359. /*if (declMethodState->mDeferredLocalAssignData != NULL)
  20360. deferredLocalAssignData.ExtendFrom(declMethodState->mDeferredLocalAssignData);*/
  20361. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  20362. methodState.mIRHeadBlock = mBfIRBuilder->CreateBlock("head", true);
  20363. methodState.mIRInitBlock = mBfIRBuilder->CreateBlock("init", true);
  20364. methodState.mIREntryBlock = mBfIRBuilder->CreateBlock("entry", true);
  20365. methodState.mCurScope->mDIScope = localMethod->mDeclDIScope; //declMethodState->mCurScope->mDIScope ;
  20366. //methodState.mCurLocalVarId = declMethodState->mCurLocalVarId;
  20367. methodState.mIRFunction = declMethodState->mIRFunction;
  20368. methodState.mDeferredLocalAssignData = &deferredLocalAssignData;
  20369. if (auto blockBody = BfNodeDynCast<BfBlock>(body))
  20370. {
  20371. methodState.mCurScope->mAstBlock = blockBody;
  20372. methodState.mCurScope->mCloseNode = blockBody->mCloseBrace;
  20373. }
  20374. mBfIRBuilder->SetInsertPoint(methodState.mIREntryBlock);
  20375. BfClosureState closureState;
  20376. if (methodDef->mMethodType == BfMethodType_Mixin)
  20377. {
  20378. if (declMethodState != NULL)
  20379. {
  20380. if ((declMethodState->mClosureState != NULL) && (declMethodState->mClosureState->mReturnType != NULL))
  20381. closureState.mReturnType = declMethodState->mClosureState->mReturnType;
  20382. else if (declMethodState->mMethodInstance != NULL)
  20383. closureState.mReturnType = declMethodState->mMethodInstance->mReturnType;
  20384. }
  20385. }
  20386. if (closureState.mReturnType == NULL)
  20387. closureState.mReturnType = _SafeResolveTypeRef(methodDef->mReturnTypeRef);
  20388. closureState.mCapturing = true;
  20389. closureState.mLocalMethod = localMethod;
  20390. closureState.mClosureInstanceInfo = methodInstance->mMethodInfoEx->mClosureInstanceInfo;
  20391. closureState.mDeclaringMethodIsMutating = mCurMethodInstance->mMethodDef->mIsMutating;
  20392. methodState.mClosureState = &closureState;
  20393. closureState.mClosureType = outerClosure;
  20394. int outerLocalsCount = (int)methodState.mLocals.size();
  20395. if (!hadExistingMethodInstance)
  20396. {
  20397. BfLogSysM("LocalMethod %p premature DoMethodDeclaration %p (Source:%p)\n", localMethod, methodInstance, (methodDeclaration != NULL) ? methodDeclaration->GetSourceData() : NULL);
  20398. SetAndRestoreValue<bool> prevIgnoreWrites(mWantsIRIgnoreWrites, true);
  20399. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, true);
  20400. // Prematurely do declaration. We will have to undo this later, so don't write this one and don't throw errors
  20401. auto declareModule = this;
  20402. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(declareModule->mCurMethodInstance, methodInstance);
  20403. SetAndRestoreValue<BfFilePosition> prevFilePos(declareModule->mCurFilePosition);
  20404. BF_ASSERT(declareModule != NULL);
  20405. methodInstance->mDeclModule = declareModule;
  20406. _SetupMethodInstance();
  20407. declareModule->DoMethodDeclaration(localMethod->mMethodDef->GetMethodDeclaration(), false, false);
  20408. methodInstance->mDisallowCalling = true; // Don't allow us to ACTUALLY call until we add the captures
  20409. }
  20410. if (wantPrematureMethodInstance)
  20411. {
  20412. // Return a premature methodInstance -- since we are partway through determining the capture of a local method, we can't rely on its
  20413. // capture information. This returned method instance can only be used for method matching, but we will visit it later to create
  20414. // its true method instance
  20415. //auto moduleMethodInstance = _CheckReturnedMethod(methodInstance);
  20416. //BF_ASSERT(moduleMethodInstance);
  20417. return BfModuleMethodInstance(methodInstance);
  20418. }
  20419. auto checkInsertBlock = mBfIRBuilder->GetInsertBlock();
  20420. BF_ASSERT(methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureClosureState == NULL);
  20421. closureState.mCaptureStartAccessId = mCurMethodState->GetRootMethodState()->mCurAccessId;
  20422. methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureClosureState = &closureState;
  20423. closureState.mClosureMethodDef = methodDef;
  20424. bool wantsVisitBody = true;
  20425. if ((methodDef->mMethodType == BfMethodType_Mixin) && (!methodGenericArguments.IsEmpty()))
  20426. wantsVisitBody = false;
  20427. if (methodInstance->IsOrInUnspecializedVariation())
  20428. wantsVisitBody = false;
  20429. bool allowCapture = (methodDeclaration == NULL) || (methodDeclaration->mStaticSpecifier == NULL);
  20430. if (wantsVisitBody)
  20431. {
  20432. BP_ZONE("VisitLambdaBody");
  20433. // For generic methods, we capture for each specialization, so make sure mIsStatic is set to 'true' for
  20434. // this capture stage for each of those times
  20435. SetAndRestoreValue<bool> prevWasStatis(methodDef->mIsStatic, true);
  20436. /*
  20437. // Only generate errors once. Also there are some errors that will occur during this scanning phase
  20438. // that will not occur during the actual lambda method generation, for example: returning a value
  20439. // when our current method is a 'void' method. This shouldn't affect capture scanning since all
  20440. // our AST nodes will still be visited
  20441. SetAndRestoreValue<bool> ignoreError(mIgnoreErrors, true);
  20442. */
  20443. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, methodInstance);
  20444. //SetAndRestoreValue<bool> wantsIgnoreWrites(mWantsISIgnoreWrites, true);
  20445. mBfIRBuilder->SaveDebugLocation();
  20446. closureState.mCaptureVisitingBody = true;
  20447. BF_ASSERT(methodInstance->mMethodInfoEx != NULL);
  20448. methodState.mGenericTypeBindings = &methodInstance->mMethodInfoEx->mGenericTypeBindings;
  20449. methodState.mMethodInstance = methodInstance;
  20450. NewScopeState();
  20451. ProcessMethod_SetupParams(methodInstance, NULL, false, NULL);
  20452. if (methodInstance->mMethodDef->mMethodType == BfMethodType_Mixin)
  20453. {
  20454. // Allow assigning to arguments when we're capturing - which may or may not be legal at the injection site (we throw error there)
  20455. for (auto localDef : methodState.mLocals)
  20456. {
  20457. if (localDef->mResolvedType->IsVar())
  20458. continue;
  20459. localDef->mAddr = CreateAlloca(localDef->mResolvedType);
  20460. }
  20461. }
  20462. // Keep outs from being marked as assigned
  20463. auto rootMethodState = mCurMethodState->GetRootMethodState();
  20464. BfDeferredLocalAssignData deferredLocalAssignData(rootMethodState->mCurScope);
  20465. deferredLocalAssignData.mVarIdBarrier = rootMethodState->mCurLocalVarId;
  20466. auto prevDLA = rootMethodState->mDeferredLocalAssignData;
  20467. while ((prevDLA != NULL) && (prevDLA->mIsChained))
  20468. prevDLA = prevDLA->mChainedAssignData;
  20469. if (prevDLA != NULL)
  20470. {
  20471. deferredLocalAssignData.mAssignedLocals = prevDLA->mAssignedLocals;
  20472. deferredLocalAssignData.mLeftBlockUncond = prevDLA->mLeftBlockUncond;
  20473. }
  20474. SetAndRestoreValue<BfDeferredLocalAssignData*> sarDLA(rootMethodState->mDeferredLocalAssignData, &deferredLocalAssignData);
  20475. if (!mIgnoreErrors)
  20476. localMethod->mDidBodyErrorPass = true;
  20477. _VisitLambdaBody();
  20478. RestoreScopeState();
  20479. closureState.mCaptureVisitingBody = false;
  20480. mBfIRBuilder->RestoreDebugLocation();
  20481. }
  20482. // If we ended up being called by a method with a lower captureStartAccessId, propagate that to whoever is calling us, too...
  20483. if ((methodState.mPrevMethodState->mClosureState != NULL) && (methodState.mPrevMethodState->mClosureState->mCapturing))
  20484. {
  20485. auto prevClosureState = methodState.mPrevMethodState->mClosureState;
  20486. if (closureState.mCaptureStartAccessId < prevClosureState->mCaptureStartAccessId)
  20487. prevClosureState->mCaptureStartAccessId = closureState.mCaptureStartAccessId;
  20488. }
  20489. // Actually get the referenced local methods. It's important we wait until after visiting the body, because then our own capture information
  20490. // can be used by these methods (which will be necessary if any of these methods call us directly or indirectly)
  20491. closureState.mClosureMethodDef = NULL;
  20492. for (auto methodInstance : closureState.mLocalMethodRefs)
  20493. {
  20494. GetLocalMethodInstance(methodInstance->mMethodInfoEx->mClosureInstanceInfo->mLocalMethod, BfTypeVector(), methodInstance);
  20495. }
  20496. methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureClosureState = NULL;
  20497. prevIgnoreWrites.Restore();
  20498. std::multiset<BfClosureCapturedEntry> capturedEntries;
  20499. //
  20500. {
  20501. auto varMethodState = declMethodState;
  20502. while (varMethodState != NULL)
  20503. {
  20504. if ((varMethodState->mMixinState != NULL) && (varMethodState->mMixinState->mLastTargetAccessId >= closureState.mCaptureStartAccessId))
  20505. {
  20506. BF_ASSERT(methodInstance->GetOwner() == varMethodState->mMixinState->mTarget.mType);
  20507. methodDef->mIsStatic = false;
  20508. if (rootMethodState->mMethodInstance->mMethodDef->mIsMutating)
  20509. methodDef->mIsMutating = true;
  20510. }
  20511. bool copyOuterCaptures = false;
  20512. for (int localIdx = 0; localIdx < varMethodState->mLocals.size(); localIdx++)
  20513. {
  20514. auto localVar = varMethodState->mLocals[localIdx];
  20515. if ((localVar->mReadFromId >= closureState.mCaptureStartAccessId) || (localVar->mWrittenToId >= closureState.mCaptureStartAccessId))
  20516. {
  20517. if (!allowCapture)
  20518. {
  20519. if ((!localVar->mIsStatic) && (!localVar->mConstValue))
  20520. continue;
  20521. }
  20522. if (localVar->mIsThis)
  20523. {
  20524. // We can only set mutating if our owning type is mutating
  20525. if (localVar->mWrittenToId >= closureState.mCaptureStartAccessId)
  20526. {
  20527. if (typeInst->IsValueType())
  20528. {
  20529. if (rootMethodState->mMethodInstance->mMethodDef->mIsMutating)
  20530. methodDef->mIsMutating = true;
  20531. }
  20532. }
  20533. methodDef->mIsStatic = false;
  20534. continue;
  20535. }
  20536. if ((localVar->mIsThis) && (outerClosure != NULL))
  20537. {
  20538. continue;
  20539. }
  20540. if ((localVar->mConstValue) || (localVar->mIsStatic) || (localVar->mResolvedType->IsValuelessType()))
  20541. {
  20542. closureState.mConstLocals.push_back(*localVar);
  20543. continue;
  20544. }
  20545. BfClosureCapturedEntry capturedEntry;
  20546. auto capturedType = localVar->mResolvedType;
  20547. bool captureByRef = false;
  20548. if (!capturedType->IsRef())
  20549. {
  20550. if (localVar->mIsThis)
  20551. {
  20552. if ((localVar->mResolvedType->IsValueType()) && (mCurMethodInstance->mMethodDef->HasNoThisSplat()))
  20553. captureByRef = true;
  20554. }
  20555. else if ((!localVar->mIsReadOnly) && (localVar->mWrittenToId >= closureState.mCaptureStartAccessId))
  20556. captureByRef = true;
  20557. }
  20558. else
  20559. {
  20560. if (localVar->mWrittenToId < closureState.mCaptureStartAccessId)
  20561. {
  20562. capturedType = ((BfRefType*)capturedType)->mElementType;
  20563. }
  20564. }
  20565. if (captureByRef)
  20566. {
  20567. //capturedEntry.mIsByReference = true;
  20568. capturedType = CreateRefType(capturedType);
  20569. }
  20570. else
  20571. {
  20572. //capturedEntry.mIsByReference = false;
  20573. }
  20574. capturedEntry.mNameNode = localVar->mNameNode;
  20575. capturedEntry.mType = capturedType;
  20576. capturedEntry.mName = localVar->mName;
  20577. //capturedEntry.mLocalVarDef = localVar;
  20578. capturedEntries.insert(capturedEntry);
  20579. }
  20580. }
  20581. varMethodState = varMethodState->mPrevMethodState;
  20582. if ((varMethodState == NULL) ||
  20583. (varMethodState->mMixinState != NULL) ||
  20584. ((varMethodState->mClosureState != NULL) && (!varMethodState->mClosureState->mCapturing)))
  20585. break;
  20586. }
  20587. }
  20588. for (auto& copyField : closureState.mReferencedOuterClosureMembers)
  20589. {
  20590. auto fieldDef = copyField->GetFieldDef();
  20591. BfClosureCapturedEntry capturedEntry;
  20592. capturedEntry.mName = copyField->GetFieldDef()->mName;
  20593. capturedEntry.mType = copyField->mResolvedType;
  20594. if (capturedEntry.mType->IsRef())
  20595. {
  20596. // Keep by ref
  20597. }
  20598. else if (!fieldDef->mIsReadOnly)
  20599. {
  20600. capturedEntry.mType = CreateRefType(capturedEntry.mType);
  20601. }
  20602. capturedEntries.insert(capturedEntry);
  20603. }
  20604. int captureIdx = 0;
  20605. for (auto& capturedEntry : capturedEntries)
  20606. {
  20607. methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureEntries.Add(capturedEntry);
  20608. }
  20609. /*if (isDefaultPass)
  20610. {
  20611. // Insert captured members a params at the start. If we added at the end then it would screw up varargs methods
  20612. int captureIdx = 0;
  20613. for (auto& capturedEntry : capturedEntries)
  20614. {
  20615. methodInstance->mClosureInstanceInfo->mCaptureNodes.Add(BfNodeDynCast<BfIdentifierNode>(capturedEntry.mNameNode));
  20616. BfParameterDef* paramDef = new BfParameterDef();
  20617. paramDef->mName = capturedEntry.mName;
  20618. BfDirectTypeReference* directTypeRef = new BfDirectTypeReference();
  20619. directTypeRef->mType = capturedEntry.mType;
  20620. typeInst->mTypeDef->mDirectAllocNodes.push_back(directTypeRef);
  20621. paramDef->mTypeRef = directTypeRef;
  20622. paramDef->mParamKind = BfParamKind_ImplicitCapture;
  20623. methodDef->mParams.Insert(captureIdx, paramDef);
  20624. captureIdx++;
  20625. }
  20626. }
  20627. else
  20628. {
  20629. auto defaultMethodInstance = methodInstGroup->mDefault;
  20630. methodInstance->mClosureInstanceInfo->mCaptureNodes = defaultMethodInstance->mClosureInstanceInfo->mCaptureNodes;
  20631. }*/
  20632. methodState.Reset();
  20633. closureState.mCapturing = false;
  20634. //////////////////////////////////////////////////////////////////////////
  20635. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, false);
  20636. if (methodInstance->mReturnType != NULL)
  20637. {
  20638. BF_ASSERT(methodInstance->mDisallowCalling);
  20639. // We did a premature declaration (without captures)
  20640. methodInstance->UndoDeclaration();
  20641. methodInstance->mDisallowCalling = false;
  20642. BfLogSysM("LocalMethod %p UndoingDeclaration %p\n", localMethod, methodInstance);
  20643. }
  20644. auto declareModule = this;
  20645. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(declareModule->mCurMethodInstance, methodInstance);
  20646. SetAndRestoreValue<BfFilePosition> prevFilePos(declareModule->mCurFilePosition);
  20647. BF_ASSERT(declareModule != NULL);
  20648. methodInstance->mDeclModule = declareModule;
  20649. _SetupMethodInstance();
  20650. BfLogSysM("LocalMethod %p DoMethodDeclaration %p\n", localMethod, methodInstance);
  20651. declareModule->DoMethodDeclaration(localMethod->mMethodDef->GetMethodDeclaration(), false, false);
  20652. closureState.mReturnType = methodInstance->mReturnType;
  20653. mCompiler->mStats.mMethodsQueued++;
  20654. mCompiler->UpdateCompletion();
  20655. declareModule->mIncompleteMethodCount++;
  20656. mCompiler->mStats.mMethodsProcessed++;
  20657. if (!methodInstance->mIsReified)
  20658. mCompiler->mStats.mUnreifiedMethodsProcessed++;
  20659. auto deferMethodState = rootMethodState;
  20660. // 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)
  20661. if ((!localMethod->mDeclOnly) && (!methodInstance->IsOrInUnspecializedVariation()) &&
  20662. (methodDef->mMethodType != BfMethodType_Mixin) &&
  20663. ((!mWantsIRIgnoreWrites) || (!localMethod->mDidBodyErrorPass)) &&
  20664. (!mCompiler->IsDataResolvePass()))
  20665. {
  20666. BP_ZONE("BfDeferredLocalMethod:create");
  20667. BfDeferredLocalMethod* deferredLocalMethod = new BfDeferredLocalMethod();
  20668. deferredLocalMethod->mLocalMethod = localMethod;
  20669. deferredLocalMethod->mConstLocals = closureState.mConstLocals;
  20670. deferredLocalMethod->mMethodInstance = methodInstance;
  20671. auto checkMethodState = declMethodState;
  20672. while (checkMethodState != NULL)
  20673. {
  20674. if ((checkMethodState->mClosureState != NULL) && (checkMethodState->mClosureState->mActiveDeferredLocalMethod != NULL))
  20675. {
  20676. for (auto& mixinRecord : checkMethodState->mClosureState->mActiveDeferredLocalMethod->mMixinStateRecords)
  20677. deferredLocalMethod->mMixinStateRecords.Add(mixinRecord);
  20678. }
  20679. if (checkMethodState->mMixinState != NULL)
  20680. {
  20681. BfMixinRecord mixinRecord;
  20682. mixinRecord.mSource = checkMethodState->mMixinState->mSource;
  20683. deferredLocalMethod->mMixinStateRecords.Add(mixinRecord);
  20684. }
  20685. checkMethodState = checkMethodState->mPrevMethodState;
  20686. }
  20687. rootMethodState->mDeferredLocalMethods.Add(deferredLocalMethod);
  20688. }
  20689. mBfIRBuilder->SetActiveFunction(prevActiveFunction);
  20690. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  20691. mBfIRBuilder->RestoreDebugLocation();
  20692. if (methodInstance == localMethod->mMethodInstanceGroup->mDefault)
  20693. {
  20694. auto checkMethodState = mCurMethodState;
  20695. while (checkMethodState != NULL)
  20696. {
  20697. BfLocalMethod* nextLocalMethod = NULL;
  20698. if (checkMethodState->mLocalMethodMap.TryGetValue(localMethod->mMethodName, &nextLocalMethod))
  20699. {
  20700. while (nextLocalMethod != NULL)
  20701. {
  20702. auto checkLocalMethod = nextLocalMethod;
  20703. nextLocalMethod = nextLocalMethod->mNextWithSameName;
  20704. if (checkLocalMethod == localMethod)
  20705. continue;
  20706. if (checkLocalMethod->mMethodInstanceGroup == NULL)
  20707. continue;
  20708. auto checkMethodInstance = checkLocalMethod->mMethodInstanceGroup->mDefault;
  20709. if (checkMethodInstance == NULL)
  20710. continue; // Not generated yet
  20711. if (CompareMethodSignatures(localMethod->mMethodInstanceGroup->mDefault, checkMethodInstance))
  20712. {
  20713. String error = "Method already declared with the same parameter types";
  20714. auto bfError = Fail(error, methodInstance->mMethodDef->GetRefNode(), true);
  20715. if ((bfError != NULL) && (methodInstance->mMethodDef->GetRefNode() != checkMethodInstance->mMethodDef->GetRefNode()))
  20716. mCompiler->mPassInstance->MoreInfo("First declaration", checkMethodInstance->mMethodDef->GetRefNode());
  20717. }
  20718. }
  20719. }
  20720. checkMethodState = checkMethodState->mPrevMethodState;
  20721. }
  20722. }
  20723. return BfModuleMethodInstance(methodInstance);
  20724. }
  20725. int BfModule::GetLocalInferrableGenericArgCount(BfMethodDef* methodDef)
  20726. {
  20727. if ((!methodDef->mIsLocalMethod) || (methodDef->mGenericParams.size() == 0))
  20728. return 0;
  20729. auto rootMethodState = mCurMethodState->GetRootMethodState();
  20730. int rootMethodGenericParamCount = 0;
  20731. if (rootMethodState->mMethodInstance->mMethodInfoEx != NULL)
  20732. rootMethodGenericParamCount = (int)rootMethodState->mMethodInstance->mMethodInfoEx->mGenericParams.size();
  20733. if (mCurMethodInstance == NULL)
  20734. return rootMethodGenericParamCount;
  20735. if ((mCurMethodInstance->mMethodInfoEx == NULL) || (mCurMethodInstance->mMethodInfoEx->mClosureInstanceInfo == NULL))
  20736. return rootMethodGenericParamCount;
  20737. BfLocalMethod* callerLocalMethod = mCurMethodInstance->mMethodInfoEx->mClosureInstanceInfo->mLocalMethod;
  20738. if (callerLocalMethod == NULL)
  20739. return rootMethodGenericParamCount;
  20740. BfLocalMethod* calledLocalMethod = NULL;
  20741. rootMethodState->mLocalMethodCache.TryGetValue(methodDef->mName, &calledLocalMethod);
  20742. while ((calledLocalMethod != NULL) && (callerLocalMethod != NULL))
  20743. {
  20744. if (calledLocalMethod->mOuterLocalMethod == callerLocalMethod)
  20745. return (int)callerLocalMethod->mMethodDef->mGenericParams.size();
  20746. callerLocalMethod = calledLocalMethod->mOuterLocalMethod;
  20747. }
  20748. return rootMethodGenericParamCount;
  20749. }
  20750. void BfModule::GetMethodCustomAttributes(BfMethodInstance* methodInstance)
  20751. {
  20752. auto methodDef = methodInstance->mMethodDef;
  20753. auto customAttributes = methodInstance->GetCustomAttributes();
  20754. if (customAttributes != NULL)
  20755. return;
  20756. auto methodDeclaration = methodDef->GetMethodDeclaration();
  20757. auto propertyMethodDeclaration = methodDef->GetPropertyMethodDeclaration();
  20758. auto typeInstance = methodInstance->GetOwner();
  20759. if (typeInstance->IsInstanceOf(mCompiler->mValueTypeTypeDef))
  20760. return;
  20761. BfTypeState typeState(typeInstance);
  20762. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  20763. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  20764. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, methodInstance);
  20765. BfAttributeTargets attrTarget = ((methodDef->mMethodType == BfMethodType_Ctor) || (methodDef->mMethodType == BfMethodType_CtorCalcAppend)) ? BfAttributeTargets_Constructor : BfAttributeTargets_Method;
  20766. BfAttributeDirective* attributeDirective = NULL;
  20767. if (methodDeclaration != NULL)
  20768. attributeDirective = methodDeclaration->mAttributes;
  20769. else if (propertyMethodDeclaration != NULL)
  20770. {
  20771. attributeDirective = propertyMethodDeclaration->mAttributes;
  20772. if (auto exprBody = BfNodeDynCast<BfPropertyBodyExpression>(propertyMethodDeclaration->mPropertyDeclaration->mDefinitionBlock))
  20773. {
  20774. attributeDirective = propertyMethodDeclaration->mPropertyDeclaration->mAttributes;
  20775. attrTarget = (BfAttributeTargets)(BfAttributeTargets_Property | BfAttributeTargets_Method);
  20776. }
  20777. }
  20778. if (attributeDirective != NULL)
  20779. {
  20780. if (methodInstance->GetMethodInfoEx()->mMethodCustomAttributes == NULL)
  20781. methodInstance->mMethodInfoEx->mMethodCustomAttributes = new BfMethodCustomAttributes();
  20782. if ((methodInstance == methodInstance->mMethodInstanceGroup->mDefault) && (methodInstance->mMethodInstanceGroup->mDefaultCustomAttributes != NULL))
  20783. {
  20784. // Take over previously-generated custom attributes
  20785. methodInstance->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes = methodInstance->mMethodInstanceGroup->mDefaultCustomAttributes;
  20786. methodInstance->mMethodInstanceGroup->mDefaultCustomAttributes = NULL;
  20787. }
  20788. else
  20789. methodInstance->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes = GetCustomAttributes(attributeDirective, attrTarget);
  20790. }
  20791. if ((propertyMethodDeclaration != NULL) && (propertyMethodDeclaration->mPropertyDeclaration->mAttributes != NULL) && ((attrTarget & BfAttributeTargets_Property) == 0))
  20792. {
  20793. if (methodInstance->GetMethodInfoEx()->mMethodCustomAttributes != NULL)
  20794. {
  20795. GetCustomAttributes(methodInstance->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes, propertyMethodDeclaration->mPropertyDeclaration->mAttributes, BfAttributeTargets_Property);
  20796. }
  20797. else
  20798. {
  20799. methodInstance->GetMethodInfoEx()->mMethodCustomAttributes = new BfMethodCustomAttributes();
  20800. methodInstance->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes = GetCustomAttributes(propertyMethodDeclaration->mPropertyDeclaration->mAttributes, BfAttributeTargets_Property);
  20801. }
  20802. }
  20803. if (methodDeclaration != NULL)
  20804. {
  20805. if (auto inlineTypeRef = BfNodeDynCast<BfInlineTypeReference>(methodDeclaration->mReturnType))
  20806. {
  20807. if (inlineTypeRef->mTypeDeclaration->mAttributes != NULL)
  20808. {
  20809. // Apply multiuse attributes from anonymous return type
  20810. auto returnType = ResolveTypeRef(inlineTypeRef);
  20811. if ((returnType != NULL) && (returnType->ToTypeInstance()))
  20812. {
  20813. auto returnTypeInst = returnType->ToTypeInstance();
  20814. if ((returnTypeInst->IsAnonymous()) && (returnTypeInst->mCustomAttributes != NULL))
  20815. {
  20816. bool hasPendingAttributes = false;
  20817. for (const auto& customAttribute : returnTypeInst->mCustomAttributes->mAttributes)
  20818. {
  20819. if (customAttribute.mAwaitingValidation)
  20820. {
  20821. hasPendingAttributes = true;
  20822. break;
  20823. }
  20824. }
  20825. if (hasPendingAttributes)
  20826. {
  20827. if (methodInstance->GetMethodInfoEx()->mMethodCustomAttributes == NULL)
  20828. methodInstance->mMethodInfoEx->mMethodCustomAttributes = new BfMethodCustomAttributes();
  20829. if (methodInstance->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes == NULL)
  20830. methodInstance->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes = new BfCustomAttributes();
  20831. for (const auto& customAttribute : returnTypeInst->mCustomAttributes->mAttributes)
  20832. {
  20833. if (!customAttribute.mAwaitingValidation)
  20834. continue;
  20835. BfCustomAttribute copiedCustomAttribute = customAttribute;
  20836. copiedCustomAttribute.mIsMultiUse = false;
  20837. methodInstance->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes->mAttributes.Add(copiedCustomAttribute);
  20838. }
  20839. ValidateCustomAttributes(methodInstance->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes, attrTarget);
  20840. }
  20841. }
  20842. }
  20843. }
  20844. }
  20845. }
  20846. customAttributes = methodInstance->GetCustomAttributes();
  20847. if (customAttributes == NULL)
  20848. {
  20849. auto owner = methodInstance->GetOwner();
  20850. if ((owner->IsDelegate()) || (owner->IsFunction()))
  20851. customAttributes = owner->mCustomAttributes;
  20852. }
  20853. methodInstance->mCallingConvention = methodDef->mCallingConvention;
  20854. if ((typeInstance->IsValueType()) && (methodDef->mIsOverride) && (methodDef->mName == BF_METHODNAME_MARKMEMBERS))
  20855. {
  20856. // Make sure we we pass 'this' as a pointer into GCMarkMembers so it's compatible with the mark function pointer
  20857. methodInstance->mCallingConvention = BfCallingConvention_Cdecl;
  20858. }
  20859. if (customAttributes != NULL)
  20860. {
  20861. auto linkNameAttr = customAttributes->Get(mCompiler->mCallingConventionAttributeTypeDef);
  20862. if (linkNameAttr != NULL)
  20863. {
  20864. if (linkNameAttr->mCtorArgs.size() == 1)
  20865. {
  20866. auto constant = typeInstance->mConstHolder->GetConstant(linkNameAttr->mCtorArgs[0]);
  20867. if (constant != NULL)
  20868. methodInstance->mCallingConvention = (BfCallingConvention)constant->mInt32;
  20869. }
  20870. }
  20871. if (methodDef->mHasComptime)
  20872. methodInstance->mComptimeFlags = BfComptimeFlag_Comptime;
  20873. auto comptimeAttr = customAttributes->Get(mCompiler->mComptimeAttributeTypeDef);
  20874. if (comptimeAttr != NULL)
  20875. {
  20876. for (auto setProp : comptimeAttr->mSetProperties)
  20877. {
  20878. BfPropertyDef* propertyDef = setProp.mPropertyRef;
  20879. if (propertyDef->mName == "OnlyFromComptime")
  20880. {
  20881. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  20882. if ((constant != NULL) && (constant->mBool))
  20883. methodInstance->mComptimeFlags = (BfComptimeFlags)(methodInstance->mComptimeFlags | BfComptimeFlag_OnlyFromComptime);
  20884. }
  20885. else if (propertyDef->mName == "ConstEval")
  20886. {
  20887. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  20888. if ((constant != NULL) && (constant->mBool))
  20889. methodInstance->mComptimeFlags = (BfComptimeFlags)(methodInstance->mComptimeFlags | BfComptimeFlag_ConstEval);
  20890. }
  20891. }
  20892. }
  20893. }
  20894. auto delegateInfo = typeInstance->GetDelegateInfo();
  20895. if ((delegateInfo != NULL) && (methodInstance->mMethodDef->mMethodType == BfMethodType_Normal) && (methodInstance->mMethodDef->mName == "Invoke"))
  20896. methodInstance->mCallingConvention = delegateInfo->mCallingConvention;
  20897. }
  20898. void BfModule::SetupIRFunction(BfMethodInstance* methodInstance, StringImpl& mangledName, bool isTemporaryFunc, bool* outIsIntrinsic)
  20899. {
  20900. if (methodInstance->GetImportCallKind() == BfImportCallKind_GlobalVar)
  20901. {
  20902. // Don't create a func
  20903. return;
  20904. }
  20905. auto typeInstance = methodInstance->GetOwner();
  20906. auto methodDef = methodInstance->mMethodDef;
  20907. BfIRFunctionType funcType = mBfIRBuilder->MapMethod(methodInstance);
  20908. if (isTemporaryFunc)
  20909. {
  20910. BF_ASSERT(((mCompiler->mIsResolveOnly) && (mCompiler->mResolvePassData->mAutoComplete != NULL)) ||
  20911. (methodInstance->GetOwner()->mDefineState < BfTypeDefineState_Defined));
  20912. mangledName = "autocomplete_tmp";
  20913. }
  20914. if (!mBfIRBuilder->mIgnoreWrites)
  20915. {
  20916. BfIRFunction prevFunc;
  20917. // Remove old version (if we have one)
  20918. prevFunc = mBfIRBuilder->GetFunction(mangledName);
  20919. if (prevFunc)
  20920. {
  20921. auto owner = methodInstance->GetOwner();
  20922. if ((methodDef->mIsOverride) && (owner->mTypeDef->mIsCombinedPartial))
  20923. {
  20924. bool takeover = false;
  20925. owner->mTypeDef->PopulateMemberSets();
  20926. BfMethodDef* nextMethod = NULL;
  20927. BfMemberSetEntry* entry = NULL;
  20928. if (owner->mTypeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  20929. nextMethod = (BfMethodDef*)entry->mMemberDef;
  20930. while (nextMethod != NULL)
  20931. {
  20932. auto checkMethod = nextMethod;
  20933. nextMethod = nextMethod->mNextWithSameName;
  20934. if (checkMethod == methodDef)
  20935. continue;
  20936. if (checkMethod->mIsOverride)
  20937. {
  20938. auto checkMethodInstance = owner->mMethodInstanceGroups[checkMethod->mIdx].mDefault;
  20939. if (checkMethodInstance == NULL)
  20940. continue;
  20941. if ((checkMethodInstance->mIRFunction == prevFunc) &&
  20942. (checkMethodInstance->mMethodDef->mMethodDeclaration != NULL) &&
  20943. (checkMethodInstance->mVirtualTableIdx < 0))
  20944. {
  20945. BfAstNode* refNode = methodDef->GetRefNode();
  20946. if (auto propertyMethodDeclaration = methodDef->GetPropertyMethodDeclaration())
  20947. refNode = propertyMethodDeclaration->mPropertyDeclaration->mVirtualSpecifier;
  20948. else if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  20949. refNode = methodDeclaration->mVirtualSpecifier;
  20950. auto error = Fail(StrFormat("Conflicting extension override method '%s'", MethodToString(methodInstance).c_str()), refNode);
  20951. if (error != NULL)
  20952. mCompiler->mPassInstance->MoreInfo("See previous override", checkMethod->GetRefNode());
  20953. takeover = false;
  20954. break;
  20955. }
  20956. }
  20957. if (!checkMethod->mIsExtern)
  20958. continue;
  20959. auto checkMethodInstance = owner->mMethodInstanceGroups[checkMethod->mIdx].mDefault;
  20960. if (checkMethodInstance == NULL)
  20961. continue;
  20962. if (!CompareMethodSignatures(checkMethodInstance, methodInstance))
  20963. continue;
  20964. // Take over function
  20965. takeover = true;
  20966. BfLogSysM("Method %p setting mHasBeenProcessed due to funcId takeover from method %p\n", checkMethodInstance, prevFunc.mId, methodInstance);
  20967. checkMethodInstance->mHasBeenProcessed = true;
  20968. }
  20969. if (takeover)
  20970. {
  20971. BfLogSysM("Method %p takover of previous funcId: %d\n", methodInstance, prevFunc.mId);
  20972. methodInstance->mIRFunction = prevFunc;
  20973. }
  20974. if (!methodInstance->mIRFunction)
  20975. {
  20976. BfLogSysM("Function collision from inner override erased prevFunc %p: %d\n", methodInstance, prevFunc.mId);
  20977. if (!mIsComptimeModule)
  20978. mBfIRBuilder->Func_SafeRenameFrom(prevFunc, mangledName);
  20979. }
  20980. }
  20981. else if (methodDef->mIsExtern)
  20982. {
  20983. // Allow this
  20984. BfLogSysM("Function collision allowed multiple extern functions for %p: %d\n", methodInstance, prevFunc.mId);
  20985. }
  20986. else if (typeInstance->IsIRFuncUsed(prevFunc))
  20987. {
  20988. // We can have a collision of names when we have generic methods that differ only in
  20989. // their constraints, but they should only collide in their unspecialized form
  20990. // since only one will be chosen for a given concrete type
  20991. if (!mIsComptimeModule)
  20992. methodInstance->mMangleWithIdx = true;
  20993. mangledName.Clear();
  20994. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), methodInstance);
  20995. BfLogSysM("Function collision forced mangleWithIdx for %p: %d GenericArgs: %d Unspecialized: %d\n", methodInstance, prevFunc.mId, methodInstance->GetNumGenericArguments(), methodInstance->mIsUnspecialized);
  20996. }
  20997. else
  20998. {
  20999. BfLogSysM("Function collision erased prevFunc %p: %d\n", methodInstance, prevFunc.mId);
  21000. if (!mIsComptimeModule)
  21001. mBfIRBuilder->Func_SafeRenameFrom(prevFunc, mangledName);
  21002. }
  21003. }
  21004. }
  21005. if (typeInstance != mContext->mBfObjectType)
  21006. {
  21007. // Only allow attributes on System.Object methods that can be handled inside the DefBuilder
  21008. GetMethodCustomAttributes(methodInstance);
  21009. }
  21010. bool isIntrinsic = false;
  21011. if (!methodInstance->mIRFunction)
  21012. {
  21013. BfIRFunction func;
  21014. bool wantsLLVMFunc = ((!typeInstance->IsUnspecializedType() || (mIsComptimeModule)) &&
  21015. (!methodDef->IsEmptyPartial())) && (funcType);
  21016. if (wantsLLVMFunc)
  21017. {
  21018. func = GetIntrinsic(methodInstance, true);
  21019. if (func)
  21020. {
  21021. isIntrinsic = true;
  21022. }
  21023. else
  21024. {
  21025. func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, mangledName);
  21026. BfLogSysM("Creating FuncId:%d %s in module %p\n", func.mId, mangledName.c_str(), this);
  21027. if (methodInstance->mAlwaysInline)
  21028. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_AlwaysInline);
  21029. }
  21030. methodInstance->mIRFunction = func;
  21031. }
  21032. }
  21033. if (outIsIntrinsic != NULL)
  21034. *outIsIntrinsic = isIntrinsic;
  21035. if (!isIntrinsic)
  21036. SetupIRMethod(methodInstance, methodInstance->mIRFunction, methodInstance->mAlwaysInline);
  21037. }
  21038. void BfModule::CheckHotMethod(BfMethodInstance* methodInstance, const StringImpl& inMangledName)
  21039. {
  21040. if (methodInstance->mHotMethod != NULL)
  21041. return;
  21042. if ((mCompiler->mOptions.mAllowHotSwapping) && (!methodInstance->mIsUnspecialized))
  21043. {
  21044. auto srcTypeInst = methodInstance->GetOwner();
  21045. if (srcTypeInst->mHotTypeData == NULL)
  21046. return;
  21047. StringT<128> mangledName = inMangledName;
  21048. if (mangledName.IsEmpty())
  21049. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), methodInstance);
  21050. // We always keep the current primary method at the same address
  21051. BfHotMethod* hotMethod;
  21052. BfHotMethod** hotMethodPtr;
  21053. if (mCompiler->mHotData->mMethodMap.TryAdd(mangledName, NULL, &hotMethodPtr))
  21054. {
  21055. hotMethod = new BfHotMethod();
  21056. *hotMethodPtr = hotMethod;
  21057. hotMethod->mRefCount = 1;
  21058. hotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_IsBound);
  21059. #ifdef BF_DBG_HOTMETHOD_IDX
  21060. static int sMethodIdx = 0;
  21061. hotMethod->mMethodIdx = sMethodIdx++;
  21062. #endif
  21063. BfLogSysM("HotMethodData %p created for method %p %s - %s\n", hotMethod, methodInstance, MethodToString(methodInstance).c_str(), mangledName.c_str());
  21064. }
  21065. else
  21066. {
  21067. hotMethod = *hotMethodPtr;
  21068. if ((hotMethod->mFlags & BfHotDepDataFlag_IsBound) != 0)
  21069. {
  21070. // This is a duplicate mangled name - we link to this new entry via a 'BfHotDupMethod'
  21071. auto prevHotMethod = *hotMethodPtr;
  21072. hotMethod = new BfHotMethod();
  21073. hotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_IsBound);
  21074. BfHotDupMethod* hotDupMethod = new BfHotDupMethod(hotMethod);
  21075. hotDupMethod->mRefCount++;
  21076. prevHotMethod->mReferences.Add(hotDupMethod);
  21077. prevHotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_HasDup);
  21078. BfLogSysM("HotMethodData %p (duplicate of %p) created for method %p %s - %s\n", hotMethod, prevHotMethod, methodInstance, MethodToString(methodInstance).c_str(), mangledName.c_str());
  21079. }
  21080. else if (mCompiler->IsHotCompile())
  21081. {
  21082. // Link the previous version into the mPrevVersion
  21083. BfHotMethod* prevMethod = new BfHotMethod();
  21084. prevMethod->mRefCount = 1;
  21085. prevMethod->mPrevVersion = hotMethod->mPrevVersion;
  21086. hotMethod->mPrevVersion = prevMethod;
  21087. prevMethod->mSrcTypeVersion = hotMethod->mSrcTypeVersion;
  21088. hotMethod->mSrcTypeVersion = NULL;
  21089. prevMethod->mFlags = hotMethod->mFlags;
  21090. hotMethod->mFlags = BfHotDepDataFlag_IsBound;
  21091. hotMethod->mReferences.MoveTo(prevMethod->mReferences);
  21092. #ifdef BF_DBG_HOTMETHOD_NAME
  21093. prevMethod->mMangledName = hotMethod->mMangledName;
  21094. #endif
  21095. BfLogSysM("HotMethodData %p created for prevmethod of %p for method %p %s\n", prevMethod, hotMethod, methodInstance, MethodToString(methodInstance).c_str());
  21096. }
  21097. else
  21098. {
  21099. BfLogSysM("HotMethodData %p used for method %p %s - %s\n", hotMethod, methodInstance, MethodToString(methodInstance).c_str(), mangledName.c_str());
  21100. hotMethod->Clear(true);
  21101. hotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_IsBound);
  21102. }
  21103. }
  21104. if (methodInstance->mIsClosure)
  21105. {
  21106. hotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_RetainMethodWithoutBinding);
  21107. }
  21108. hotMethod->mSrcTypeVersion = srcTypeInst->mHotTypeData->GetLatestVersion();
  21109. hotMethod->mSrcTypeVersion->mRefCount++;
  21110. hotMethod->mRefCount++;
  21111. #ifdef BF_DBG_HOTMETHOD_NAME
  21112. hotMethod->mMangledName = mangledName;
  21113. #endif
  21114. if ((methodInstance->mMethodInstanceGroup->IsImplemented()) && (!IsHotCompile()))
  21115. hotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_IsOriginalBuild);
  21116. methodInstance->mHotMethod = hotMethod;
  21117. }
  21118. }
  21119. static void StackOverflow()
  21120. {
  21121. int i = 0;
  21122. if (i == 0)
  21123. StackOverflow();
  21124. }
  21125. void BfModule::StartMethodDeclaration(BfMethodInstance* methodInstance, BfMethodState* prevMethodState)
  21126. {
  21127. methodInstance->mHasStartedDeclaration = true;
  21128. auto methodDef = methodInstance->mMethodDef;
  21129. auto typeInstance = methodInstance->GetOwner();
  21130. bool hasNonGenericParams = false;
  21131. bool hasGenericParams = false;
  21132. int dependentGenericStartIdx = 0;
  21133. if (methodDef->mIsLocalMethod)
  21134. {
  21135. // If we're a local generic method inside an outer generic method, we can still be considered unspecialized
  21136. // if our outer method's generic args are specialized but ours are unspecialized. This is because locals get
  21137. // instantiated uniquely for each specialized or unspecialized pass through the outer method, but the local
  21138. // method still 'inherits' the outer's generic arguments -- but we still need to make an unspecialized pass
  21139. // over the local method each time
  21140. auto rootMethodInstance = prevMethodState->GetRootMethodState()->mMethodInstance;
  21141. dependentGenericStartIdx = 0;
  21142. if (rootMethodInstance != NULL)
  21143. {
  21144. if (rootMethodInstance->mMethodInfoEx != NULL)
  21145. dependentGenericStartIdx = (int)rootMethodInstance->mMethodInfoEx->mMethodGenericArguments.size();
  21146. methodInstance->mIsUnspecialized = rootMethodInstance->mIsUnspecialized;
  21147. methodInstance->mIsUnspecializedVariation = rootMethodInstance->mIsUnspecializedVariation;
  21148. }
  21149. }
  21150. for (int genericArgIdx = dependentGenericStartIdx; genericArgIdx < (int)methodInstance->GetNumGenericArguments(); genericArgIdx++)
  21151. {
  21152. auto genericArgType = methodInstance->mMethodInfoEx->mMethodGenericArguments[genericArgIdx];
  21153. if (genericArgType->IsGenericParam())
  21154. {
  21155. hasGenericParams = true;
  21156. auto genericParam = (BfGenericParamType*)genericArgType;
  21157. methodInstance->mIsUnspecialized = true;
  21158. if ((genericParam->mGenericParamKind != BfGenericParamKind_Method) || (genericParam->mGenericParamIdx != genericArgIdx))
  21159. methodInstance->mIsUnspecializedVariation = true;
  21160. }
  21161. else
  21162. {
  21163. hasNonGenericParams = true;
  21164. if (genericArgType->IsUnspecializedType())
  21165. {
  21166. methodInstance->mIsUnspecialized = true;
  21167. methodInstance->mIsUnspecializedVariation = true;
  21168. }
  21169. }
  21170. }
  21171. if ((hasGenericParams) && (hasNonGenericParams))
  21172. {
  21173. methodInstance->mIsUnspecializedVariation = true;
  21174. }
  21175. if (typeInstance->IsUnspecializedType())
  21176. {
  21177. // A specialized method within an unspecialized type is considered an unspecialized variation -- in the sense that we don't
  21178. // actually want to do method processing on it
  21179. if ((!methodInstance->mIsUnspecialized) && (methodInstance->GetNumGenericArguments() != 0))
  21180. methodInstance->mIsUnspecializedVariation = true;
  21181. methodInstance->mIsUnspecialized = true;
  21182. }
  21183. if (methodInstance->mIsUnspecializedVariation)
  21184. BF_ASSERT(methodInstance->mIsUnspecialized);
  21185. //TODO: Why did we do this?
  21186. if (methodDef->mMethodType == BfMethodType_Mixin)
  21187. {
  21188. if (methodInstance->IsSpecializedGenericMethod())
  21189. methodInstance->mIsUnspecializedVariation = true;
  21190. methodInstance->mIsUnspecialized = true;
  21191. }
  21192. }
  21193. // methodDeclaration is NULL for default constructors
  21194. void BfModule::DoMethodDeclaration(BfMethodDeclaration* methodDeclaration, bool isTemporaryFunc, bool addToWorkList)
  21195. {
  21196. BF_ASSERT((mCompiler->mCeMachine == NULL) || (!mCompiler->mCeMachine->mDbgPaused));
  21197. BP_ZONE("BfModule::DoMethodDeclaration");
  21198. auto typeInstance = mCurTypeInstance;
  21199. auto typeDef = typeInstance->mTypeDef;
  21200. auto methodDef = mCurMethodInstance->mMethodDef;
  21201. // We could trigger a DoMethodDeclaration from a const resolver or other location, so we reset it here
  21202. // to effectively make mIgnoreWrites method-scoped
  21203. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, mWantsIRIgnoreWrites || mCurMethodInstance->mIsUnspecialized || mCurTypeInstance->mResolvingVarField);
  21204. SetAndRestoreValue<bool> prevIsCapturingMethodMatchInfo;
  21205. SetAndRestoreValue<bool> prevAllowLockYield(mContext->mAllowLockYield, false);
  21206. BfTypeState typeState(mCurTypeInstance);
  21207. typeState.mPrevState = mContext->mCurTypeState;
  21208. typeState.mCurMethodDef = methodDef;
  21209. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  21210. BfModule* resolveModule = mContext->mUnreifiedModule;
  21211. if (mCompiler->IsAutocomplete())
  21212. prevIsCapturingMethodMatchInfo.Init(mCompiler->mResolvePassData->mAutoComplete->mIsCapturingMethodMatchInfo, false);
  21213. if (mCurMethodInstance->mMethodInstanceGroup->mOnDemandKind == BfMethodOnDemandKind_NoDecl_AwaitingReference)
  21214. mCurMethodInstance->mMethodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_Decl_AwaitingReference;
  21215. BfMethodState methodState;
  21216. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  21217. methodState.mTempKind = BfMethodState::TempKind_Static;
  21218. defer({ mCurMethodInstance->mHasBeenDeclared = true; });
  21219. // If we are doing this then we may end up creating methods when var types are unknown still, failing on splat/zero-sized info
  21220. BF_ASSERT((!mCurTypeInstance->mResolvingVarField) || (mBfIRBuilder->mIgnoreWrites));
  21221. bool ignoreWrites = mBfIRBuilder->mIgnoreWrites;
  21222. // if ((!isTemporaryFunc) && (mCurTypeInstance->mDefineState < BfTypeDefineState_Defined))
  21223. // {
  21224. // BF_ASSERT(mContext->mResolvingVarField);
  21225. // isTemporaryFunc = true;
  21226. // }
  21227. if ((mAwaitingInitFinish) && (!mBfIRBuilder->mIgnoreWrites))
  21228. FinishInit();
  21229. if (methodDef->mName.StartsWith('_'))
  21230. {
  21231. BF_ASSERT(methodDef->mName != "__ASSERTNAME");
  21232. if (methodDef->mName == "__FATALERRORNAME")
  21233. BFMODULE_FATAL(this, "__FATALERRORNAME");
  21234. if (methodDef->mName == "__STACKOVERFLOW")
  21235. StackOverflow();
  21236. if (methodDef->mName == "__INTERNALERROR")
  21237. InternalError("Bad method name", methodDef->GetRefNode());
  21238. }
  21239. if (typeInstance->IsClosure())
  21240. {
  21241. if (methodDef->mName == "Invoke")
  21242. return;
  21243. }
  21244. auto methodInstance = mCurMethodInstance;
  21245. if ((methodInstance->IsSpecializedByAutoCompleteMethod()) || (mCurTypeInstance->IsFunction()))
  21246. addToWorkList = false;
  21247. if (!methodInstance->mHasStartedDeclaration)
  21248. StartMethodDeclaration(methodInstance, prevMethodState.mPrevVal);
  21249. BfAutoComplete* bfAutocomplete = NULL;
  21250. if (mCompiler->mResolvePassData != NULL)
  21251. bfAutocomplete = mCompiler->mResolvePassData->mAutoComplete;
  21252. if (methodInstance->mMethodInfoEx != NULL)
  21253. {
  21254. BfTypeInstance* unspecializedTypeInstance = NULL;
  21255. Array<BfTypeReference*> deferredResolveTypes;
  21256. for (int genericParamIdx = 0; genericParamIdx < (int)methodInstance->mMethodInfoEx->mGenericParams.size(); genericParamIdx++)
  21257. {
  21258. auto genericParam = methodInstance->mMethodInfoEx->mGenericParams[genericParamIdx];
  21259. if (genericParamIdx < (int)methodDef->mGenericParams.size())
  21260. {
  21261. genericParam->mExternType = GetGenericParamType(BfGenericParamKind_Method, genericParamIdx);
  21262. }
  21263. else
  21264. {
  21265. auto externConstraintDef = genericParam->GetExternConstraintDef();
  21266. genericParam->mExternType = ResolveTypeRef(externConstraintDef->mTypeRef);
  21267. auto autoComplete = mCompiler->GetAutoComplete();
  21268. if (autoComplete != NULL)
  21269. autoComplete->CheckTypeRef(externConstraintDef->mTypeRef, false);
  21270. if (genericParam->mExternType != NULL)
  21271. {
  21272. //
  21273. }
  21274. else
  21275. genericParam->mExternType = GetPrimitiveType(BfTypeCode_Var);
  21276. }
  21277. ResolveGenericParamConstraints(genericParam, methodInstance->mIsUnspecialized, &deferredResolveTypes);
  21278. if (genericParamIdx < (int)methodDef->mGenericParams.size())
  21279. {
  21280. auto genericParamDef = methodDef->mGenericParams[genericParamIdx];
  21281. if (bfAutocomplete != NULL)
  21282. {
  21283. for (auto nameNode : genericParamDef->mNameNodes)
  21284. {
  21285. HandleMethodGenericParamRef(nameNode, typeDef, methodDef, genericParamIdx);
  21286. }
  21287. }
  21288. }
  21289. }
  21290. for (auto typeRef : deferredResolveTypes)
  21291. auto constraintType = ResolveTypeRef(typeRef, BfPopulateType_Declaration, BfResolveTypeRefFlag_None);
  21292. if (methodInstance->mMethodInfoEx != NULL)
  21293. {
  21294. ValidateGenericParams(BfGenericParamKind_Method,
  21295. Span<BfGenericParamInstance*>((BfGenericParamInstance**)methodInstance->mMethodInfoEx->mGenericParams.mVals,
  21296. methodInstance->mMethodInfoEx->mGenericParams.mSize));
  21297. }
  21298. for (auto genericParam : methodInstance->mMethodInfoEx->mGenericParams)
  21299. AddDependency(genericParam, mCurTypeInstance);
  21300. }
  21301. if ((methodInstance->mIsAutocompleteMethod) && (methodDeclaration != NULL) && (!methodInstance->IsSpecializedGenericMethod()) && (methodDef->mIdx >= 0))
  21302. {
  21303. auto autoComplete = mCompiler->mResolvePassData->mAutoComplete;
  21304. BfAstNode* nameNode = methodDeclaration->mNameNode;
  21305. if (nameNode == NULL)
  21306. {
  21307. if (auto ctorDeclaration = BfNodeDynCast<BfConstructorDeclaration>(methodDeclaration))
  21308. nameNode = ctorDeclaration->mThisToken;
  21309. }
  21310. if ((autoComplete->IsAutocompleteNode(nameNode)) && (autoComplete->mResolveType != BfResolveType_Autocomplete))
  21311. {
  21312. autoComplete->mInsertStartIdx = nameNode->GetSrcStart();
  21313. autoComplete->mInsertEndIdx = nameNode->GetSrcEnd();
  21314. autoComplete->mDefType = typeDef;
  21315. autoComplete->mDefMethod = methodDef;
  21316. autoComplete->SetDefinitionLocation(nameNode);
  21317. if (methodDef->mIsOverride)
  21318. {
  21319. bool found = false;
  21320. for (int virtIdx = 0; virtIdx < (int)typeInstance->mVirtualMethodTable.size(); virtIdx++)
  21321. {
  21322. auto& ventry = typeInstance->mVirtualMethodTable[virtIdx];
  21323. if (ventry.mDeclaringMethod.mMethodNum == -1)
  21324. continue;
  21325. BfMethodInstance* virtMethod = ventry.mImplementingMethod;
  21326. if (virtMethod != NULL)
  21327. {
  21328. auto virtMethodDeclaration = virtMethod->mMethodDef->GetMethodDeclaration();
  21329. if ((virtMethod->GetOwner() == typeInstance) && (virtMethodDeclaration != NULL) &&
  21330. (virtMethodDeclaration->GetSrcStart() == methodDeclaration->GetSrcStart()))
  21331. {
  21332. // Is matching method
  21333. if (virtIdx < (int)typeInstance->mBaseType->mVirtualMethodTable.size())
  21334. {
  21335. auto baseType = typeInstance->mBaseType;
  21336. if (baseType != NULL)
  21337. {
  21338. found = true;
  21339. while ((baseType->mBaseType != NULL) && (virtIdx < baseType->mBaseType->mVirtualMethodTableSize))
  21340. baseType = baseType->mBaseType;
  21341. BfMethodInstance* baseVirtMethod = baseType->mVirtualMethodTable[virtIdx].mImplementingMethod;
  21342. autoComplete->SetDefinitionLocation(baseVirtMethod->mMethodDef->GetRefNode(), true);
  21343. autoComplete->mDefType = baseType->mTypeDef;
  21344. autoComplete->mDefMethod = baseVirtMethod->mMethodDef;
  21345. }
  21346. }
  21347. break;
  21348. }
  21349. }
  21350. }
  21351. if ((!found) && (autoComplete->mIsGetDefinition) && (methodDef->mDeclaringType->IsExtension()))
  21352. {
  21353. for (auto& methodGroup : typeInstance->mMethodInstanceGroups)
  21354. {
  21355. auto defaultMethod = methodGroup.mDefault;
  21356. if (defaultMethod == NULL)
  21357. continue;
  21358. if (!defaultMethod->mMethodDef->mIsExtern)
  21359. continue;
  21360. if (!CompareMethodSignatures(defaultMethod, methodInstance))
  21361. continue;
  21362. autoComplete->SetDefinitionLocation(defaultMethod->mMethodDef->GetRefNode(), true);
  21363. autoComplete->mDefType = typeInstance->mTypeDef;
  21364. autoComplete->mDefMethod = defaultMethod->mMethodDef;
  21365. }
  21366. }
  21367. }
  21368. }
  21369. }
  21370. bool reportErrors = true;
  21371. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL))
  21372. reportErrors = true;
  21373. // Only the defining contexts needs to report errors here
  21374. SetAndRestoreValue<bool> prevReporErrors(mReportErrors, reportErrors);
  21375. if (methodDef->mMethodType == BfMethodType_Dtor)
  21376. {
  21377. if (methodDef->mIsStatic)
  21378. {
  21379. }
  21380. else
  21381. {
  21382. if ((typeInstance->IsStruct()) || (typeInstance->IsTypedPrimitive()))
  21383. {
  21384. BfAstNode* refNode = methodDeclaration;
  21385. if (refNode == NULL)
  21386. {
  21387. // Whatever caused this ctor to be generated should have caused another failure
  21388. // But that failure might not be generated until the ctor is generated
  21389. }
  21390. else
  21391. {
  21392. auto dtorDecl = BfNodeDynCast<BfDestructorDeclaration>(methodDeclaration);
  21393. if (dtorDecl != NULL)
  21394. refNode = dtorDecl->mThisToken;
  21395. Fail("Structs cannot have destructors", refNode);
  21396. }
  21397. }
  21398. auto methodDeclaration = methodDef->GetMethodDeclaration();
  21399. if ((methodDeclaration != NULL) && (methodDeclaration->mVirtualSpecifier != NULL) &&
  21400. (mCurTypeInstance != mContext->mBfObjectType))
  21401. {
  21402. Fail("Virtual specifier is not required, all destructors are implicitly virtual.", methodDeclaration->mVirtualSpecifier);
  21403. }
  21404. }
  21405. }
  21406. BfType* resolvedReturnType = NULL;
  21407. if (((methodDef->mMethodType == BfMethodType_Normal) || (methodDef->mMethodType == BfMethodType_Extension) || (methodDef->mMethodType == BfMethodType_CtorCalcAppend) ||
  21408. (methodDef->mMethodType == BfMethodType_PropertyGetter) || (methodDef->mMethodType == BfMethodType_Operator)) &&
  21409. (methodDef->mReturnTypeRef != NULL))
  21410. {
  21411. SetAndRestoreValue<bool> prevIngoreErrors(mIgnoreErrors, mIgnoreErrors || (methodDef->GetPropertyDeclaration() != NULL));
  21412. if (methodDef->mReturnTypeRef->IsA<BfVarTypeReference>())
  21413. {
  21414. // An invalid 'var' error would not have been caught in the original property type pass
  21415. mIgnoreErrors = false;
  21416. }
  21417. BfResolveTypeRefFlags flags = (BfResolveTypeRefFlags)(BfResolveTypeRefFlag_NoResolveGenericParam | BfResolveTypeRefFlag_AllowRef | BfResolveTypeRefFlag_AllowRefGeneric | BfResolveTypeRefFlag_NoReify);
  21418. if ((((methodInstance->mComptimeFlags & BfComptimeFlag_ConstEval) != 0) || (methodInstance->mIsAutocompleteMethod))
  21419. && (methodDef->mReturnTypeRef->IsA<BfVarTypeReference>()))
  21420. resolvedReturnType = GetPrimitiveType(BfTypeCode_Var);
  21421. else
  21422. resolvedReturnType = ResolveTypeRef(methodDef->mReturnTypeRef, BfPopulateType_Declaration, flags);
  21423. if (resolvedReturnType == NULL)
  21424. resolvedReturnType = GetPrimitiveType(BfTypeCode_Var);
  21425. if ((methodDef->mIsReadOnly) && (!resolvedReturnType->IsRef()))
  21426. {
  21427. if (auto methodDeclaration = BfNodeDynCast<BfMethodDeclaration>(methodInstance->mMethodDef->mMethodDeclaration))
  21428. if (methodDeclaration->mReadOnlySpecifier != NULL)
  21429. Fail("Readonly specifier is only valid on 'ref' return types", methodDeclaration->mReadOnlySpecifier);
  21430. }
  21431. }
  21432. else
  21433. {
  21434. resolvedReturnType = ResolveTypeDef(mSystem->mTypeVoid);
  21435. }
  21436. BF_ASSERT(resolvedReturnType != NULL);
  21437. mCurMethodInstance->mReturnType = resolvedReturnType;
  21438. //TODO: We used to NOT add the return value dependency for specialized methods, but when we have types that are
  21439. // specialized based on the method's generic param then they can get deleted if no one else has referred to them (yet)
  21440. //if (!methodInstance->IsSpecializedGenericMethod())
  21441. AddDependency(resolvedReturnType, typeInstance, BfDependencyMap::DependencyFlag_ParamOrReturnValue);
  21442. if (methodDef->mExplicitInterface != NULL)
  21443. {
  21444. auto autoComplete = mCompiler->GetAutoComplete();
  21445. if (autoComplete != NULL)
  21446. autoComplete->CheckTypeRef(methodDef->mExplicitInterface, false);
  21447. auto explicitType = ResolveTypeRef(methodDef->mExplicitInterface, BfPopulateType_Declaration);
  21448. BfTypeInstance* explicitInterface = NULL;
  21449. if (explicitType != NULL)
  21450. explicitInterface = explicitType->ToTypeInstance();
  21451. if (explicitInterface != NULL)
  21452. {
  21453. mCurMethodInstance->GetMethodInfoEx()->mExplicitInterface = explicitInterface->ToTypeInstance();
  21454. if (autoComplete != NULL)
  21455. {
  21456. BfTokenNode* dotToken = NULL;
  21457. BfAstNode* nameNode = NULL;
  21458. if (auto methodDeclaration = BfNodeDynCast<BfMethodDeclaration>(methodDef->mMethodDeclaration))
  21459. {
  21460. dotToken = methodDeclaration->mExplicitInterfaceDotToken;
  21461. nameNode = methodDeclaration->mNameNode;
  21462. }
  21463. autoComplete->CheckExplicitInterface(explicitInterface, dotToken, nameNode);
  21464. }
  21465. }
  21466. if ((mCurMethodInstance->mMethodInfoEx != NULL) && (mCurMethodInstance->mMethodInfoEx->mExplicitInterface != NULL))
  21467. {
  21468. bool interfaceFound = false;
  21469. for (auto ifaceInst : typeInstance->mInterfaces)
  21470. interfaceFound |= ifaceInst.mInterfaceType == mCurMethodInstance->mMethodInfoEx->mExplicitInterface;
  21471. if ((!interfaceFound) && (!typeInstance->mTypeFailed))
  21472. {
  21473. if (methodDef->mMethodDeclaration != NULL)
  21474. Fail("Containing class has not declared to implement this interface", methodDef->mMethodDeclaration);
  21475. else
  21476. {
  21477. // For property decls, we should have already given the error during type population
  21478. if (mCompiler->mRevision == 1)
  21479. AssertErrorState();
  21480. }
  21481. }
  21482. }
  21483. }
  21484. bool isThisStruct = mCurTypeInstance->IsStruct();
  21485. BfType* thisType = NULL;
  21486. if ((!methodDef->mIsStatic) && (!mCurTypeInstance->IsValuelessType()))
  21487. {
  21488. if ((isThisStruct) || (mCurTypeInstance->IsTypedPrimitive()))
  21489. {
  21490. thisType = mCurTypeInstance;
  21491. if (thisType == NULL)
  21492. return;
  21493. if ((thisType->IsSplattable()) && (!methodDef->HasNoThisSplat()))
  21494. {
  21495. BfTypeUtils::SplatIterate([&](BfType* checkType)
  21496. {
  21497. resolveModule->PopulateType(checkType, BfPopulateType_Data);
  21498. }, thisType);
  21499. }
  21500. }
  21501. else
  21502. {
  21503. thisType = mCurTypeInstance;
  21504. resolveModule->PopulateType(thisType, BfPopulateType_Declaration);
  21505. }
  21506. }
  21507. int implicitParamCount = 0;
  21508. if ((mCurMethodInstance->mMethodInfoEx != NULL) && (mCurMethodInstance->mMethodInfoEx->mClosureInstanceInfo != NULL))
  21509. implicitParamCount = (int)methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureEntries.size();
  21510. methodInstance->mMethodDef->mParams.Reserve((int)methodDef->mParams.size());
  21511. bool hadDelegateParams = false;
  21512. bool hadParams = false;
  21513. for (int paramIdx = 0; paramIdx < (int)methodDef->mParams.size() + implicitParamCount; paramIdx++)
  21514. {
  21515. BfClosureCapturedEntry* closureCaptureEntry = NULL;
  21516. BfParameterDef* paramDef = NULL;
  21517. int paramDefIdx = -1;
  21518. if (paramIdx < implicitParamCount)
  21519. closureCaptureEntry = &methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureEntries[paramIdx];
  21520. else
  21521. {
  21522. paramDefIdx = paramIdx - implicitParamCount;
  21523. paramDef = methodDef->mParams[paramDefIdx];
  21524. }
  21525. if (hadParams)
  21526. break;
  21527. if ((paramDef != NULL) && (paramDef->mParamKind == BfParamKind_VarArgs))
  21528. continue;
  21529. if ((paramDef != NULL) && (mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL) &&
  21530. (paramDef->mParamKind != BfParamKind_AppendIdx))
  21531. {
  21532. mCompiler->mResolvePassData->mAutoComplete->CheckTypeRef(paramDef->mTypeRef, false);
  21533. if (mCompiler->mResolvePassData->mAutoComplete->IsAutocompleteNode(paramDef->mTypeRef))
  21534. mCompiler->mResolvePassData->mAutoComplete->AddEntry(AutoCompleteEntry("token", "in"), paramDef->mTypeRef->ToString());
  21535. }
  21536. if ((paramDef != NULL) && (paramDef->mParamDeclaration != NULL) && (paramDef->mParamDeclaration->mAttributes != NULL))
  21537. {
  21538. if (methodInstance->GetMethodInfoEx()->mMethodCustomAttributes == NULL)
  21539. methodInstance->mMethodInfoEx->mMethodCustomAttributes = new BfMethodCustomAttributes();
  21540. while ((int)methodInstance->mMethodInfoEx->mMethodCustomAttributes->mParamCustomAttributes.size() < paramIdx)
  21541. methodInstance->mMethodInfoEx->mMethodCustomAttributes->mParamCustomAttributes.push_back(NULL);
  21542. auto customAttributes = GetCustomAttributes(paramDef->mParamDeclaration->mAttributes, BfAttributeTargets_Parameter);
  21543. methodInstance->mMethodInfoEx->mMethodCustomAttributes->mParamCustomAttributes.push_back(customAttributes);
  21544. }
  21545. BfType* resolvedParamType = NULL;
  21546. if (closureCaptureEntry != NULL)
  21547. resolvedParamType = closureCaptureEntry->mType;
  21548. else if ((paramDef->mTypeRef != NULL) && (paramDef->mTypeRef->IsA<BfLetTypeReference>()))
  21549. {
  21550. Fail("Cannot declare 'let' parameters", paramDef->mTypeRef);
  21551. resolvedParamType = mContext->mBfObjectType;
  21552. }
  21553. else if ((paramDef->mTypeRef != NULL) && (paramDef->mTypeRef->IsA<BfVarTypeReference>()))
  21554. {
  21555. if (methodDef->mMethodType != BfMethodType_Mixin)
  21556. {
  21557. Fail("Cannot declare var parameters", paramDef->mTypeRef);
  21558. resolvedParamType = mContext->mBfObjectType;
  21559. }
  21560. else
  21561. resolvedParamType = GetPrimitiveType(BfTypeCode_Var);
  21562. }
  21563. BfType* unresolvedParamType = resolvedParamType;
  21564. bool wasGenericParam = false;
  21565. if (resolvedParamType == NULL)
  21566. {
  21567. BfResolveTypeRefFlags resolveFlags = (BfResolveTypeRefFlags)(BfResolveTypeRefFlag_NoResolveGenericParam | BfResolveTypeRefFlag_AllowRef | BfResolveTypeRefFlag_AllowRefGeneric | BfResolveTypeRefFlag_AllowGenericMethodParamConstValue | BfResolveTypeRefFlag_NoReify);
  21568. if (paramDef->mParamKind == BfParamKind_ExplicitThis)
  21569. resolveFlags = (BfResolveTypeRefFlags)(resolveFlags | BfResolveTypeRefFlag_NoWarnOnMut);
  21570. resolvedParamType = ResolveTypeRef(paramDef->mTypeRef, BfPopulateType_Declaration, resolveFlags);
  21571. if ((paramDef->mParamKind == BfParamKind_ExplicitThis) && (resolvedParamType != NULL) && (resolvedParamType->IsRef()))
  21572. resolvedParamType = resolvedParamType->GetUnderlyingType();
  21573. }
  21574. if (resolvedParamType == NULL)
  21575. {
  21576. resolvedParamType = GetPrimitiveType(BfTypeCode_Var);
  21577. unresolvedParamType = resolvedParamType;
  21578. if (mCurTypeInstance->IsBoxed())
  21579. {
  21580. auto boxedType = (BfBoxedType*)mCurTypeInstance;
  21581. // If we failed a lookup here then we better have also failed it in the original type
  21582. BF_ASSERT(boxedType->mElementType->ToTypeInstance()->mModule->mHadBuildError || mContext->mFailTypes.ContainsKey(boxedType->mElementType->ToTypeInstance()));
  21583. }
  21584. }
  21585. BF_ASSERT(!resolvedParamType->IsDeleting());
  21586. if (!methodInstance->IsSpecializedGenericMethod())
  21587. AddDependency(resolvedParamType, typeInstance, BfDependencyMap::DependencyFlag_ParamOrReturnValue);
  21588. PopulateType(resolvedParamType, BfPopulateType_Declaration);
  21589. AddDependency(resolvedParamType, mCurTypeInstance, BfDependencyMap::DependencyFlag_LocalUsage);
  21590. if ((paramDef != NULL) && (paramDef->mParamDeclaration != NULL) && (paramDef->mParamDeclaration->mInitializer != NULL) &&
  21591. (!paramDef->mParamDeclaration->mInitializer->IsA<BfBlock>()))
  21592. {
  21593. if (paramDef->mParamKind == BfParamKind_Params)
  21594. {
  21595. BfAstNode* refNode = paramDef->mParamDeclaration->mEqualsNode;
  21596. if (refNode != NULL)
  21597. refNode = paramDef->mParamDeclaration->mModToken;
  21598. Fail("Cannot specify a default value for a 'params' parameter", refNode);
  21599. }
  21600. BfTypedValue defaultValue;
  21601. if (resolvedParamType->IsConstExprValue())
  21602. {
  21603. auto constExprType = (BfConstExprValueType*)resolvedParamType;
  21604. BfExprEvaluator exprEvaluator(this);
  21605. exprEvaluator.mExpectingType = constExprType->mType;
  21606. exprEvaluator.GetLiteral(NULL, constExprType->mValue);
  21607. defaultValue = exprEvaluator.GetResult();
  21608. }
  21609. else
  21610. {
  21611. BfTypeState typeState;
  21612. typeState.mType = mCurTypeInstance;
  21613. typeState.mCurTypeDef = methodDef->mDeclaringType;
  21614. //typeState.mCurMethodDef = methodDef;
  21615. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  21616. BfConstResolver constResolver(this);
  21617. defaultValue = constResolver.Resolve(paramDef->mParamDeclaration->mInitializer, resolvedParamType, (BfConstResolveFlags)(BfConstResolveFlag_NoCast | BfConstResolveFlag_AllowGlobalVariable));
  21618. if ((defaultValue) && (defaultValue.mType != resolvedParamType))
  21619. {
  21620. SetAndRestoreValue<bool> prevIgnoreWrite(mBfIRBuilder->mIgnoreWrites, true);
  21621. auto castedDefaultValue = Cast(paramDef->mParamDeclaration->mInitializer, defaultValue, resolvedParamType, (BfCastFlags)(BfCastFlags_SilentFail | BfCastFlags_NoConversionOperator));
  21622. if ((castedDefaultValue) && (castedDefaultValue.mValue.IsConst()))
  21623. {
  21624. defaultValue = castedDefaultValue; // Good!
  21625. }
  21626. else if (!CanCast(defaultValue, resolvedParamType))
  21627. {
  21628. // We only care that we get a constant value that can be implicitly casted at the callsite- even if that requires
  21629. // a conversion operator.
  21630. // This should throw an error
  21631. defaultValue = Cast(paramDef->mParamDeclaration->mInitializer, defaultValue, resolvedParamType);
  21632. AssertErrorState();
  21633. if (!defaultValue.mValue.IsConst())
  21634. defaultValue = BfTypedValue();
  21635. }
  21636. }
  21637. }
  21638. if (!defaultValue)
  21639. {
  21640. defaultValue = GetDefaultTypedValue(resolvedParamType);
  21641. if (!defaultValue.mValue.IsConst())
  21642. defaultValue = BfTypedValue();
  21643. }
  21644. if (defaultValue)
  21645. {
  21646. if (defaultValue.mType->IsVar())
  21647. {
  21648. AssertErrorState();
  21649. }
  21650. else
  21651. {
  21652. BF_ASSERT(defaultValue.mValue.IsConst());
  21653. while ((int)mCurMethodInstance->mDefaultValues.size() < paramDefIdx)
  21654. mCurMethodInstance->mDefaultValues.Add(BfTypedValue());
  21655. CurrentAddToConstHolder(defaultValue.mValue);
  21656. mCurMethodInstance->mDefaultValues.Add(defaultValue);
  21657. }
  21658. }
  21659. }
  21660. if ((paramDef != NULL) && (paramDef->mParamKind == BfParamKind_Params))
  21661. {
  21662. bool addParams = true;
  21663. bool isValid = false;
  21664. auto resolvedParamTypeInst = resolvedParamType->ToTypeInstance();
  21665. if ((resolvedParamTypeInst != NULL) && (resolvedParamTypeInst->IsInstanceOf(mCompiler->mSpanTypeDef)))
  21666. {
  21667. // Span<T>
  21668. isValid = true;
  21669. }
  21670. else if (resolvedParamType->IsArray())
  21671. {
  21672. // Array is the 'normal' params type
  21673. isValid = true;
  21674. }
  21675. else if (resolvedParamType->IsSizedArray())
  21676. {
  21677. isValid = true;
  21678. }
  21679. else if (resolvedParamType->IsVar())
  21680. {
  21681. isValid = true;
  21682. }
  21683. else if ((resolvedParamType->IsDelegate()) || (resolvedParamType->IsFunction()) || (resolvedParamType->IsMethodRef()))
  21684. {
  21685. hadDelegateParams = true;
  21686. // This means we copy the params from a delegate
  21687. BfMethodParam methodParam;
  21688. methodParam.mResolvedType = resolvedParamType;
  21689. methodParam.mParamDefIdx = paramDefIdx;
  21690. methodParam.mDelegateParamIdx = 0;
  21691. auto invokeMethodInstance = methodParam.GetDelegateParamInvoke();
  21692. for (int delegateParamIdx = 0; delegateParamIdx < invokeMethodInstance->GetParamCount(); delegateParamIdx++)
  21693. {
  21694. methodParam.mDelegateParamIdx = delegateParamIdx;
  21695. mCurMethodInstance->mParams.Add(methodParam);
  21696. auto paramType = invokeMethodInstance->GetParamType(delegateParamIdx);
  21697. if (!methodInstance->IsSpecializedGenericMethod())
  21698. AddDependency(paramType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ParamOrReturnValue);
  21699. }
  21700. isValid = true;
  21701. addParams = false;
  21702. }
  21703. else if (resolvedParamType->IsTuple())
  21704. {
  21705. auto tupleType = (BfTupleType*)resolvedParamType;
  21706. PopulateType(tupleType);
  21707. hadDelegateParams = true;
  21708. // This means we copy the params from a delegate
  21709. BfMethodParam methodParam;
  21710. methodParam.mResolvedType = resolvedParamType;
  21711. methodParam.mParamDefIdx = paramDefIdx;
  21712. methodParam.mDelegateParamIdx = 0;
  21713. auto invokeMethodInstance = methodParam.GetDelegateParamInvoke();
  21714. for (int delegateParamIdx = 0; delegateParamIdx < tupleType->mFieldInstances.mSize; delegateParamIdx++)
  21715. {
  21716. auto& fieldInstance = tupleType->mFieldInstances[delegateParamIdx];
  21717. methodParam.mDelegateParamIdx = delegateParamIdx;
  21718. mCurMethodInstance->mParams.Add(methodParam);
  21719. if (!methodInstance->IsSpecializedGenericMethod())
  21720. AddDependency(fieldInstance.mResolvedType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ParamOrReturnValue);
  21721. }
  21722. isValid = true;
  21723. addParams = false;
  21724. }
  21725. else if (resolvedParamType->IsGenericParam())
  21726. {
  21727. bool isGenericDelegateParams = false;
  21728. bool addDelegateParamsType = false;
  21729. auto genericParamInstance = GetGenericParamInstance((BfGenericParamType*)resolvedParamType, false, BfFailHandleKind_Ignore);
  21730. if (genericParamInstance == NULL)
  21731. {
  21732. // Delegate case with a 'params T'?
  21733. isGenericDelegateParams = true;
  21734. addDelegateParamsType = true;
  21735. }
  21736. else if (genericParamInstance->mTypeConstraint != NULL)
  21737. {
  21738. auto typeInstConstraint = genericParamInstance->mTypeConstraint->ToTypeInstance();
  21739. if ((genericParamInstance->mTypeConstraint->IsArray()) || (genericParamInstance->mTypeConstraint->IsSizedArray()))
  21740. {
  21741. BfMethodParam methodParam;
  21742. methodParam.mResolvedType = resolvedParamType;
  21743. methodParam.mParamDefIdx = paramDefIdx;
  21744. mCurMethodInstance->mParams.Add(methodParam);
  21745. isValid = true;
  21746. }
  21747. else if ((genericParamInstance->mTypeConstraint->IsDelegate()) || (genericParamInstance->mTypeConstraint->IsFunction()) || (genericParamInstance->mTypeConstraint->IsTuple()) ||
  21748. ((genericParamInstance != NULL) && (typeInstConstraint != NULL) &&
  21749. ((typeInstConstraint->IsInstanceOf(mCompiler->mDelegateTypeDef)) || (typeInstConstraint->IsInstanceOf(mCompiler->mFunctionTypeDef)) || (typeInstConstraint->IsInstanceOf(mCompiler->mTupleTypeDef)))))
  21750. {
  21751. isGenericDelegateParams = true;
  21752. //addDelegateParamsType = typeInstConstraint->IsInstanceOf(mCompiler->mTupleTypeDef);
  21753. addDelegateParamsType = true;
  21754. }
  21755. }
  21756. if (isGenericDelegateParams)
  21757. {
  21758. mCurMethodInstance->mHadGenericDelegateParams = true;
  21759. isValid = true;
  21760. addParams = false;
  21761. if (addDelegateParamsType)
  21762. {
  21763. BfMethodParam methodParam;
  21764. methodParam.mResolvedType = CreateModifiedTypeType(resolvedParamType, BfToken_Params);
  21765. methodParam.mParamDefIdx = paramDefIdx;
  21766. mCurMethodInstance->mParams.Add(methodParam);
  21767. //TODO: Why do we have this 'if'
  21768. if (!methodInstance->IsSpecializedGenericMethod())
  21769. AddDependency(methodParam.mResolvedType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ParamOrReturnValue);
  21770. }
  21771. }
  21772. }
  21773. else
  21774. {
  21775. auto paramTypeInst = resolvedParamType->ToTypeInstance();
  21776. if ((paramTypeInst != NULL) &&
  21777. ((paramTypeInst->IsInstanceOf(mCompiler->mDelegateTypeDef)) || (paramTypeInst->IsInstanceOf(mCompiler->mFunctionTypeDef)) || (paramTypeInst->IsInstanceOf(mCompiler->mTupleTypeDef))))
  21778. {
  21779. // If we have a 'params T' and 'T' gets specialized with actually 'Tuple', 'Delegate' or 'Function' then just ignore it
  21780. isValid = true;
  21781. addParams = false;
  21782. }
  21783. }
  21784. if (!isValid)
  21785. {
  21786. Fail("Parameters with 'params' specifiers can only be used for array, span, tuple, delegate, or function types", paramDef->mParamDeclaration->mModToken);
  21787. // Failure case, make it an Object[]
  21788. resolvedParamType = CreateArrayType(mContext->mBfObjectType, 1);
  21789. }
  21790. if ((addParams) && (resolvedParamType != NULL))
  21791. {
  21792. BfMethodParam methodParam;
  21793. methodParam.mResolvedType = resolvedParamType;
  21794. methodParam.mParamDefIdx = paramDefIdx;
  21795. mCurMethodInstance->mParams.push_back(methodParam);
  21796. }
  21797. if (paramDefIdx < (int)methodDef->mParams.size() - 1)
  21798. {
  21799. Fail("Only the last parameter can specify 'params'", paramDef->mParamDeclaration->mModToken);
  21800. }
  21801. }
  21802. else
  21803. {
  21804. BfMethodParam methodParam;
  21805. methodParam.mResolvedType = resolvedParamType;
  21806. methodParam.mParamDefIdx = paramDefIdx;
  21807. mCurMethodInstance->mParams.Add(methodParam);
  21808. }
  21809. }
  21810. if (hadDelegateParams)
  21811. {
  21812. HashSet<String> usedNames;
  21813. Dictionary<int, int> usedParamDefIdx;
  21814. for (auto methodParam : methodDef->mParams)
  21815. {
  21816. usedNames.Add(methodParam->mName);
  21817. }
  21818. for (auto& methodParam : mCurMethodInstance->mParams)
  21819. {
  21820. if ((methodParam.mParamDefIdx != -1) && (methodParam.mDelegateParamIdx == 0))
  21821. {
  21822. int* refCount = NULL;
  21823. usedParamDefIdx.TryAdd(methodParam.mParamDefIdx, NULL, &refCount);
  21824. (*refCount)++;
  21825. }
  21826. }
  21827. for (auto& methodParam : mCurMethodInstance->mParams)
  21828. {
  21829. if (methodParam.mDelegateParamIdx != -1)
  21830. {
  21831. if (usedParamDefIdx[methodParam.mParamDefIdx] > 1)
  21832. methodParam.mDelegateParamNameCombine = true;
  21833. if (methodParam.mResolvedType->IsTuple())
  21834. {
  21835. auto tupleType = (BfTupleType*)methodParam.mResolvedType;
  21836. auto& fieldInstance = tupleType->mFieldInstances[methodParam.mDelegateParamIdx];
  21837. auto paramName = fieldInstance.GetFieldDef()->mName;
  21838. if ((!usedNames.Add(paramName)) || (::isdigit((uint8)paramName[0])))
  21839. methodParam.mDelegateParamNameCombine = true;
  21840. }
  21841. else
  21842. {
  21843. BfMethodInstance* invokeMethodInstance = methodParam.GetDelegateParamInvoke();
  21844. String paramName = invokeMethodInstance->GetParamName(methodParam.mDelegateParamIdx);
  21845. if (!usedNames.Add(paramName))
  21846. methodParam.mDelegateParamNameCombine = true;
  21847. }
  21848. }
  21849. }
  21850. }
  21851. int argIdx = 0;
  21852. resolveModule->PopulateType(methodInstance->mReturnType, BfPopulateType_Data);
  21853. if ((!methodDef->mIsStatic) && (!methodDef->mHasExplicitThis))
  21854. {
  21855. int thisIdx = methodDef->mHasExplicitThis ? 0 : -1;
  21856. auto thisType = methodInstance->GetOwner();
  21857. if (methodInstance->GetParamIsSplat(thisIdx))
  21858. argIdx += methodInstance->GetParamType(thisIdx)->GetSplatCount();
  21859. else if (!thisType->IsValuelessType())
  21860. {
  21861. BfTypeCode loweredTypeCode = BfTypeCode_None;
  21862. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  21863. if ((!mIsComptimeModule) && (!methodDef->mIsMutating))
  21864. thisType->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2);
  21865. argIdx++;
  21866. if (loweredTypeCode2 != BfTypeCode_None)
  21867. argIdx++;
  21868. }
  21869. }
  21870. if ((!mIsComptimeModule) && (methodInstance->GetStructRetIdx() != -1))
  21871. argIdx++;
  21872. for (int paramIdx = 0; paramIdx < mCurMethodInstance->mParams.size(); paramIdx++)
  21873. {
  21874. auto& methodParam = mCurMethodInstance->mParams[paramIdx];
  21875. BfType* checkType = methodParam.mResolvedType;
  21876. int checkArgIdx = argIdx;
  21877. if ((paramIdx == 0) && (methodDef->mHasExplicitThis))
  21878. {
  21879. checkArgIdx = 0;
  21880. checkType = methodInstance->GetThisType();
  21881. }
  21882. if (checkType->IsMethodRef())
  21883. {
  21884. methodParam.mIsSplat = true;
  21885. }
  21886. else if ((checkType->IsComposite()) && (methodInstance->AllowsSplatting(paramIdx)))
  21887. {
  21888. resolveModule->PopulateType(checkType, BfPopulateType_Data);
  21889. if (checkType->IsSplattable())
  21890. {
  21891. bool isSplat = false;
  21892. auto checkTypeInstance = checkType->ToTypeInstance();
  21893. if ((checkTypeInstance != NULL) && (checkTypeInstance->mIsCRepr))
  21894. isSplat = true;
  21895. int splatCount = checkType->GetSplatCount();
  21896. if (checkArgIdx + splatCount <= mCompiler->mOptions.mMaxSplatRegs)
  21897. isSplat = true;
  21898. if (isSplat)
  21899. {
  21900. methodParam.mIsSplat = true;
  21901. argIdx += splatCount;
  21902. continue;
  21903. }
  21904. }
  21905. else if (!checkType->IsValuelessType())
  21906. {
  21907. BfTypeCode loweredTypeCode = BfTypeCode_None;
  21908. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  21909. if (!mIsComptimeModule)
  21910. checkType->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2);
  21911. argIdx++;
  21912. if (loweredTypeCode2 != BfTypeCode_None)
  21913. argIdx++;
  21914. continue;
  21915. }
  21916. }
  21917. argIdx++;
  21918. }
  21919. bool hasExternSpecifier = (methodDeclaration != NULL) && (methodDeclaration->mExternSpecifier != NULL);
  21920. if ((hasExternSpecifier) && (methodDeclaration->mBody != NULL))
  21921. {
  21922. Fail("Cannot 'extern' and declare a body", methodDeclaration->mExternSpecifier);
  21923. }
  21924. else if ((methodDeclaration != NULL) && (methodDeclaration->mBody == NULL) && (!hasExternSpecifier) &&
  21925. (!typeInstance->IsInterface()) && (!mCurTypeInstance->IsDelegate()) && (!mCurTypeInstance->IsFunction()) &&
  21926. (!methodDef->mIsPartial) && (!methodDef->mIsAbstract) &&
  21927. (!methodDef->mIsSkipCall))
  21928. {
  21929. if (methodDeclaration->mEndSemicolon == NULL)
  21930. {
  21931. if (auto autoCtorDecl = BfNodeDynCast<BfAutoConstructorDeclaration>(methodDeclaration))
  21932. {
  21933. //
  21934. }
  21935. else
  21936. AssertParseErrorState();
  21937. }
  21938. else
  21939. {
  21940. bool isError = true;
  21941. if (typeInstance->IsTypedPrimitive())
  21942. {
  21943. if (auto operatorDeclaration = BfNodeDynCast<BfOperatorDeclaration>(methodDeclaration))
  21944. {
  21945. if ((operatorDeclaration->mIsConvOperator) && (methodInstance->mParams.size() == 1))
  21946. {
  21947. if (((methodInstance->mReturnType == typeInstance) && (methodInstance->GetParamType(0) == typeInstance->GetUnderlyingType())) ||
  21948. ((methodInstance->mReturnType == typeInstance->GetUnderlyingType()) && (methodInstance->GetParamType(0) == typeInstance)))
  21949. {
  21950. isError = false;
  21951. }
  21952. else if (mCurTypeInstance->IsEnum())
  21953. {
  21954. if (((methodInstance->mReturnType == typeInstance) && (methodInstance->GetParamType(0)->IsInteger())) ||
  21955. ((methodInstance->mReturnType->IsInteger()) && (methodInstance->GetParamType(0) == typeInstance)))
  21956. {
  21957. isError = false;
  21958. }
  21959. }
  21960. }
  21961. }
  21962. }
  21963. if (isError)
  21964. {
  21965. Fail(StrFormat("'%s' must declare a body because it is not marked abstract, extern, or partial",
  21966. MethodToString(methodInstance).c_str()),
  21967. methodDef->GetRefNode());
  21968. }
  21969. }
  21970. }
  21971. if (methodDef->IsEmptyPartial())
  21972. hasExternSpecifier = true;
  21973. if (!methodInstance->IsAutocompleteMethod())
  21974. {
  21975. auto defaultMethodInstance = methodInstance->mMethodInstanceGroup->mDefault;
  21976. int implicitParamCount = methodInstance->GetImplicitParamCount();
  21977. int defaultImplicitParamCount = defaultMethodInstance->GetImplicitParamCount();
  21978. int actualParamCount = (int)methodInstance->mParams.size() - implicitParamCount;
  21979. BF_ASSERT((actualParamCount == defaultMethodInstance->mParams.size() - defaultImplicitParamCount) || (defaultMethodInstance->mHadGenericDelegateParams));
  21980. mCurMethodInstance->mHadGenericDelegateParams = defaultMethodInstance->mHadGenericDelegateParams;
  21981. int paramIdx = 0;
  21982. int defaultParamIdx = 0;
  21983. while (true)
  21984. {
  21985. bool isDone = paramIdx + implicitParamCount >= (int)methodInstance->mParams.size();
  21986. bool isDefaultDone = defaultParamIdx + defaultImplicitParamCount >= (int)defaultMethodInstance->mParams.size();
  21987. if ((!isDone) && (methodInstance->mParams[paramIdx + implicitParamCount].mDelegateParamIdx >= 0))
  21988. {
  21989. paramIdx++;
  21990. continue;
  21991. }
  21992. if ((!isDefaultDone) && (defaultMethodInstance->mParams[defaultParamIdx + defaultImplicitParamCount].mDelegateParamIdx >= 0))
  21993. {
  21994. defaultParamIdx++;
  21995. continue;
  21996. }
  21997. if ((isDone) || (isDefaultDone))
  21998. {
  21999. // 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
  22000. // to cause us to throw an assertion in the declaration here
  22001. if ((!defaultMethodInstance->mHadGenericDelegateParams) && (!methodInstance->mHasFailed) && (!defaultMethodInstance->mHasFailed))
  22002. BF_ASSERT((isDone) && (isDefaultDone));
  22003. break;
  22004. }
  22005. BfType* paramType = defaultMethodInstance->mParams[defaultParamIdx + defaultImplicitParamCount].mResolvedType;
  22006. if (paramType->IsRef())
  22007. paramType = paramType->GetUnderlyingType();
  22008. methodInstance->mParams[paramIdx + implicitParamCount].mWasGenericParam = paramType->IsGenericParam();
  22009. paramIdx++;
  22010. defaultParamIdx++;
  22011. }
  22012. }
  22013. StringT<4096> mangledName;
  22014. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), mCurMethodInstance);
  22015. for (int paramIdx = 0; paramIdx < methodInstance->GetParamCount(); paramIdx++)
  22016. {
  22017. auto paramType = methodInstance->GetParamType(paramIdx);
  22018. if (paramType->IsComposite())
  22019. resolveModule->PopulateType(paramType, BfPopulateType_Data);
  22020. if (!methodInstance->IsParamSkipped(paramIdx))
  22021. {
  22022. if (paramType->IsStruct())
  22023. {
  22024. //
  22025. }
  22026. else
  22027. {
  22028. PopulateType(paramType, BfPopulateType_Declaration);
  22029. }
  22030. }
  22031. }
  22032. // Only process method in default unspecialized mode, not in variations
  22033. if (methodInstance->mIsUnspecializedVariation)
  22034. return;
  22035. resolveModule->PopulateType(resolvedReturnType, BfPopulateType_Data);
  22036. auto retLLVMType = mBfIRBuilder->MapType(resolvedReturnType);
  22037. if (resolvedReturnType->IsValuelessType())
  22038. retLLVMType = mBfIRBuilder->GetPrimitiveType(BfTypeCode_None);
  22039. if (!mBfIRBuilder->mIgnoreWrites)
  22040. {
  22041. bool isIntrinsic = false;
  22042. if (!methodInstance->mIRFunction)
  22043. SetupIRFunction(methodInstance, mangledName, isTemporaryFunc, &isIntrinsic);
  22044. if (isIntrinsic)
  22045. {
  22046. addToWorkList = false;
  22047. }
  22048. }
  22049. else
  22050. {
  22051. GetMethodCustomAttributes(methodInstance);
  22052. }
  22053. auto func = methodInstance->mIRFunction;
  22054. // if (methodInstance->mIsReified)
  22055. // CheckHotMethod(methodInstance, mangledName);
  22056. for (auto& param : methodInstance->mParams)
  22057. {
  22058. BF_ASSERT(!param.mResolvedType->IsDeleting());
  22059. }
  22060. 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);
  22061. SizedArray<BfIRMDNode, 8> diParams;
  22062. diParams.push_back(mBfIRBuilder->DbgGetType(resolvedReturnType));
  22063. if ((!methodDef->mIsStatic) && (typeDef->mIsStatic) && (methodDef->mMethodDeclaration != NULL))
  22064. {
  22065. //CS0708
  22066. Fail("Cannot declare instance members in a static class", methodDef->GetRefNode());
  22067. }
  22068. if ((methodDef->mIsVirtual) && (methodDef->mGenericParams.size() != 0))
  22069. {
  22070. Fail("Virtual generic methods not supported", methodDeclaration->mVirtualSpecifier);
  22071. methodDef->mIsVirtual = false;
  22072. }
  22073. BfAstNode* mutSpecifier = NULL;
  22074. if (methodDeclaration != NULL)
  22075. mutSpecifier = methodDeclaration->mMutSpecifier;
  22076. else if (methodDef->GetPropertyMethodDeclaration() != NULL)
  22077. {
  22078. mutSpecifier = methodDef->GetPropertyMethodDeclaration()->mMutSpecifier;
  22079. if (mutSpecifier == NULL)
  22080. {
  22081. auto propertyDeclaration = methodDef->GetPropertyDeclaration();
  22082. if (propertyDeclaration != NULL)
  22083. {
  22084. if (auto propExprBody = BfNodeDynCast<BfPropertyBodyExpression>(propertyDeclaration->mDefinitionBlock))
  22085. mutSpecifier = propExprBody->mMutSpecifier;
  22086. }
  22087. }
  22088. }
  22089. if ((mutSpecifier != NULL) && (!mCurTypeInstance->IsBoxed()) && (!methodInstance->mIsForeignMethodDef))
  22090. {
  22091. if (methodDef->mIsStatic)
  22092. Warn(0, "Unnecessary 'mut' specifier, static methods have no implicit 'this' target to mutate", mutSpecifier);
  22093. else if ((!mCurTypeInstance->IsValueType()) && (!mCurTypeInstance->IsInterface()))
  22094. Warn(0, "Unnecessary 'mut' specifier, methods of reference types are implicitly mutating", mutSpecifier);
  22095. else if (methodDef->mMethodType == BfMethodType_Ctor)
  22096. Warn(0, "Unnecessary 'mut' specifier, constructors are implicitly mutating", mutSpecifier);
  22097. else if (methodDef->mMethodType == BfMethodType_Dtor)
  22098. Warn(0, "Unnecessary 'mut' specifier, destructors are implicitly mutating", mutSpecifier);
  22099. }
  22100. if (isTemporaryFunc)
  22101. {
  22102. // This handles temporary methods for autocomplete types
  22103. //BF_ASSERT(mIsScratchModule);
  22104. //BF_ASSERT(mCompiler->IsAutocomplete());
  22105. BfLogSysM("DoMethodDeclaration isTemporaryFunc bailout\n");
  22106. return; // Bail out early for autocomplete pass
  22107. }
  22108. //TODO: We used to have this (this != mContext->mExternalFuncModule) check, but it caused us to keep around
  22109. // an invalid mFuncRefernce (which came from GetMethodInstanceAtIdx) which later got remapped by the
  22110. // autocompleter. Why did we have this check anyway?
  22111. /*if ((typeInstance->mContext != mContext) && (!methodDef->IsEmptyPartial()))
  22112. {
  22113. AddMethodReference(methodInstance);
  22114. mFuncReferences[methodInstance] = func;
  22115. BfLogSysM("Adding func reference (DoMethodDeclaration). Module:%p MethodInst:%p LLVMFunc:%p\n", this, methodInstance, func);
  22116. }*/
  22117. if (mParentModule != NULL)
  22118. {
  22119. // For extension modules we need to keep track of our own methods so we can know which methods
  22120. // we have defined ourselves and which are from the parent module or other extensions
  22121. if (!func.IsFake())
  22122. {
  22123. if (func)
  22124. mFuncReferences[methodInstance] = func;
  22125. }
  22126. }
  22127. if (methodInstance->mMethodInstanceGroup->mOnDemandKind == BfMethodOnDemandKind_NotSet)
  22128. {
  22129. methodInstance->mMethodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_Decl_AwaitingDecl;
  22130. auto owningModule = methodInstance->GetOwner()->mModule;
  22131. if (!owningModule->mIsScratchModule)
  22132. owningModule->mOnDemandMethodCount++;
  22133. VerifyOnDemandMethods();
  22134. }
  22135. bool wasAwaitingDecl = methodInstance->mMethodInstanceGroup->mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingDecl;
  22136. if (wasAwaitingDecl)
  22137. methodInstance->mMethodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_Decl_AwaitingReference;
  22138. if (addToWorkList)
  22139. {
  22140. if ((!methodDef->mIsAbstract) && (!methodInstance->mIgnoreBody))
  22141. {
  22142. AddMethodToWorkList(methodInstance);
  22143. }
  22144. else
  22145. {
  22146. BfLogSysM("DoMethodDeclaration ignoring method body %d %d %d\n", hasExternSpecifier, methodDef->mIsAbstract, methodInstance->mIgnoreBody);
  22147. methodInstance->mIgnoreBody = true;
  22148. if (typeInstance->IsUnspecializedType())
  22149. {
  22150. // Don't hold on to actual Function for unspecialized types
  22151. methodInstance->mIRFunction = BfIRFunction();
  22152. }
  22153. }
  22154. }
  22155. else
  22156. {
  22157. //BF_ASSERT(methodInstance->mMethodInstanceGroup->mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingReference);
  22158. }
  22159. if ((!methodInstance->IsSpecializedGenericMethodOrType()) && (!mCurTypeInstance->IsBoxed()) &&
  22160. (!methodDef->mIsLocalMethod) &&
  22161. (!CheckDefineMemberProtection(methodDef->mProtection, methodInstance->mReturnType)) &&
  22162. (!methodDef->mReturnTypeRef->IsTemporary()))
  22163. {
  22164. if (methodDef->mMethodType == BfMethodType_PropertyGetter)
  22165. {
  22166. //TODO:
  22167. //CS0053
  22168. Fail(StrFormat("Inconsistent accessibility: property type '%s' is less accessible than property '%s'",
  22169. TypeToString(methodInstance->mReturnType).c_str(), MethodToString(methodInstance).c_str()),
  22170. methodDef->mReturnTypeRef, true);
  22171. }
  22172. else
  22173. {
  22174. //CS0050
  22175. Fail(StrFormat("Inconsistent accessibility: return type '%s' is less accessible than method '%s'",
  22176. TypeToString(methodInstance->mReturnType).c_str(), MethodToString(methodInstance).c_str()),
  22177. methodDef->mReturnTypeRef, true);
  22178. }
  22179. }
  22180. if (typeInstance->IsInterface())
  22181. {
  22182. if (methodDef->mMethodType == BfMethodType_Ctor)
  22183. Fail("Interfaces cannot contain constructors", methodDeclaration);
  22184. if (methodDeclaration != NULL)
  22185. {
  22186. if (methodDef->mBody == NULL)
  22187. {
  22188. if (methodDef->mProtection != BfProtection_Public) //TODO: MAKE AN ERROR
  22189. Warn(0, "Protection specifiers can only be used with interface methods containing a default implementation body", methodDeclaration->mProtectionSpecifier);
  22190. if ((methodDeclaration->mVirtualSpecifier != NULL) &&
  22191. (methodDeclaration->mVirtualSpecifier->mToken != BfToken_Abstract) &&
  22192. (methodDeclaration->mVirtualSpecifier->mToken != BfToken_Concrete)) //TODO: MAKE AN ERROR
  22193. Warn(0, "Virtual specifiers can only be used with interface methods containing a default implementation body", methodDeclaration->mVirtualSpecifier);
  22194. }
  22195. }
  22196. }
  22197. bool foundHiddenMethod = false;
  22198. BfTokenNode* virtualToken = NULL;
  22199. auto propertyDeclaration = methodDef->GetPropertyDeclaration();
  22200. if (propertyDeclaration != NULL)
  22201. virtualToken = propertyDeclaration->mVirtualSpecifier;
  22202. else if (methodDeclaration != NULL)
  22203. virtualToken = methodDeclaration->mVirtualSpecifier;
  22204. // Don't compare specialized generic methods against normal methods
  22205. if ((((mCurMethodInstance->mIsUnspecialized) || (mCurMethodInstance->mMethodDef->mGenericParams.size() == 0))) &&
  22206. (!methodDef->mIsLocalMethod) && (!mCurTypeInstance->IsUnspecializedTypeVariation()))
  22207. {
  22208. if ((!methodInstance->mIsForeignMethodDef) && (methodDef->mMethodType != BfMethodType_Init))
  22209. {
  22210. typeDef->PopulateMemberSets();
  22211. BfMethodDef* nextMethod = NULL;
  22212. BfMemberSetEntry* entry = NULL;
  22213. if (typeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  22214. nextMethod = (BfMethodDef*)entry->mMemberDef;
  22215. while (nextMethod != NULL)
  22216. {
  22217. auto checkMethod = nextMethod;
  22218. nextMethod = nextMethod->mNextWithSameName;
  22219. if (checkMethod == methodDef)
  22220. continue;
  22221. auto checkMethodInstance = typeInstance->mMethodInstanceGroups[checkMethod->mIdx].mDefault;
  22222. if (checkMethodInstance == NULL)
  22223. {
  22224. if (methodDef->mDeclaringType->IsExtension())
  22225. checkMethodInstance = GetRawMethodInstanceAtIdx(typeInstance, checkMethod->mIdx);
  22226. if (checkMethodInstance == NULL)
  22227. continue;
  22228. }
  22229. if (((checkMethodInstance->mChainType == BfMethodChainType_None) || (checkMethodInstance->mChainType == BfMethodChainType_ChainHead)) &&
  22230. (checkMethodInstance->GetExplicitInterface() == methodInstance->GetExplicitInterface()) &&
  22231. (checkMethod->mIsMutating == methodDef->mIsMutating) &&
  22232. (CompareMethodSignatures(checkMethodInstance, mCurMethodInstance)))
  22233. {
  22234. bool canChain = false;
  22235. if ((methodDef->mParams.empty()) &&
  22236. (checkMethodInstance->mMethodDef->mIsStatic == methodInstance->mMethodDef->mIsStatic))
  22237. {
  22238. if ((methodDef->mMethodType == BfMethodType_CtorNoBody) || (methodDef->mMethodType == BfMethodType_Dtor))
  22239. canChain = true;
  22240. else if (methodDef->mMethodType == BfMethodType_Normal)
  22241. {
  22242. if ((methodDef->mName == BF_METHODNAME_MARKMEMBERS) ||
  22243. (methodDef->mName == BF_METHODNAME_MARKMEMBERS_STATIC) ||
  22244. (methodDef->mName == BF_METHODNAME_FIND_TLS_MEMBERS))
  22245. canChain = true;
  22246. }
  22247. }
  22248. if (canChain)
  22249. {
  22250. bool isBetter;
  22251. bool isWorse;
  22252. CompareDeclTypes(typeInstance, checkMethodInstance->mMethodDef->mDeclaringType, methodInstance->mMethodDef->mDeclaringType, isBetter, isWorse);
  22253. if (isBetter && !isWorse)
  22254. {
  22255. methodInstance->mChainType = BfMethodChainType_ChainHead;
  22256. checkMethodInstance->mChainType = BfMethodChainType_ChainMember;
  22257. }
  22258. else
  22259. {
  22260. checkMethodInstance->mChainType = BfMethodChainType_ChainHead;
  22261. methodInstance->mChainType = BfMethodChainType_ChainMember;
  22262. }
  22263. }
  22264. else
  22265. {
  22266. if (!typeInstance->IsTypeMemberAccessible(checkMethod->mDeclaringType, methodDef->mDeclaringType))
  22267. continue;
  22268. bool silentlyAllow = false;
  22269. bool extensionWarn = false;
  22270. if (checkMethod->mDeclaringType != methodDef->mDeclaringType)
  22271. {
  22272. if (typeInstance->IsInterface())
  22273. {
  22274. if (methodDef->mIsOverride)
  22275. silentlyAllow = true;
  22276. }
  22277. else
  22278. {
  22279. if ((methodDef->mIsOverride) && (checkMethod->mIsExtern))
  22280. {
  22281. silentlyAllow = true;
  22282. methodInstance->mIsInnerOverride = true;
  22283. CheckOverridenMethod(methodInstance, checkMethodInstance);
  22284. }
  22285. else if (!checkMethod->mDeclaringType->IsExtension())
  22286. {
  22287. foundHiddenMethod = true;
  22288. if ((methodDef->mMethodType == BfMethodType_Ctor) && (methodDef->mIsStatic))
  22289. silentlyAllow = true;
  22290. else if (methodDef->mIsNew)
  22291. {
  22292. silentlyAllow = true;
  22293. }
  22294. else if (checkMethod->GetMethodDeclaration() == NULL)
  22295. silentlyAllow = true;
  22296. else if (methodDef->mIsOverride)
  22297. silentlyAllow = true;
  22298. else
  22299. extensionWarn = true;
  22300. }
  22301. else
  22302. silentlyAllow = true;
  22303. }
  22304. }
  22305. if ((checkMethod->mCommutableKind == BfCommutableKind_Reverse) || (methodDef->mCommutableKind == BfCommutableKind_Reverse))
  22306. silentlyAllow = true;
  22307. if (checkMethod->mMethodDeclaration == NULL)
  22308. {
  22309. // This can allow emission of a default ctor if we've already auto-added a default ctor
  22310. silentlyAllow = true;
  22311. }
  22312. if (checkMethod->mMethodType == BfMethodType_CtorCalcAppend)
  22313. {
  22314. // Only use the main ctor as the error method
  22315. silentlyAllow = true;
  22316. }
  22317. if (!silentlyAllow)
  22318. {
  22319. if ((!methodDef->mName.IsEmpty()) || (checkMethodInstance->mMethodDef->mIsOperator))
  22320. {
  22321. auto refNode = methodDef->GetRefNode();
  22322. BfError* bfError;
  22323. if (extensionWarn)
  22324. {
  22325. if (methodDef->mDeclaringType->mProject != checkMethod->mDeclaringType->mProject)
  22326. bfError = Warn(BfWarning_CS0114_MethodHidesInherited,
  22327. StrFormat("This method hides a method in the root type definition. Use the 'new' keyword if the hiding was intentional. Note that this method is not callable from project '%s'.",
  22328. checkMethod->mDeclaringType->mProject->mName.c_str()), refNode);
  22329. else
  22330. bfError = Warn(BfWarning_CS0114_MethodHidesInherited,
  22331. "This method hides a method in the root type definition. Use the 'new' keyword if the hiding was intentional.", refNode);
  22332. }
  22333. else
  22334. {
  22335. bfError = Fail(StrFormat("Method '%s' already declared with the same parameter types", MethodToString(checkMethodInstance).c_str()), refNode, true);
  22336. }
  22337. if ((bfError != NULL) && (checkMethod->GetRefNode() != refNode))
  22338. mCompiler->mPassInstance->MoreInfo("First declaration", checkMethod->GetRefNode());
  22339. }
  22340. }
  22341. }
  22342. }
  22343. }
  22344. }
  22345. // Virtual methods give their error while slotting
  22346. if ((!typeInstance->IsBoxed()) && (!methodDef->mIsVirtual) && (methodDef->mProtection != BfProtection_Private) &&
  22347. (!methodDef->mIsLocalMethod) &&
  22348. (!methodInstance->mIsForeignMethodDef) && (typeInstance->mBaseType != NULL) &&
  22349. (methodDef->mMethodType == BfMethodType_Normal) && (methodDef->mMethodDeclaration != NULL))
  22350. {
  22351. auto baseType = typeInstance->mBaseType;
  22352. while (baseType != NULL)
  22353. {
  22354. auto baseTypeDef = baseType->mTypeDef;
  22355. baseTypeDef->PopulateMemberSets();
  22356. BfMethodDef* checkMethod = NULL;
  22357. BfMemberSetEntry* entry = NULL;
  22358. if (baseTypeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  22359. checkMethod = (BfMethodDef*)entry->mMemberDef;
  22360. while (checkMethod != NULL)
  22361. {
  22362. if (checkMethod->mMethodDeclaration == NULL)
  22363. {
  22364. checkMethod = checkMethod->mNextWithSameName;
  22365. continue;
  22366. }
  22367. if (baseType->mMethodInstanceGroups.size() == 0)
  22368. {
  22369. BF_ASSERT(baseType->IsIncomplete() && mCompiler->IsAutocomplete());
  22370. break;
  22371. }
  22372. if (checkMethod == methodDef)
  22373. {
  22374. checkMethod = checkMethod->mNextWithSameName;
  22375. continue;
  22376. }
  22377. if (checkMethod->mName != methodDef->mName)
  22378. {
  22379. checkMethod = checkMethod->mNextWithSameName;
  22380. continue;
  22381. }
  22382. auto checkMethodInstance = GetRawMethodInstanceAtIdx(baseType, checkMethod->mIdx);
  22383. if (checkMethodInstance != NULL)
  22384. {
  22385. if ((checkMethodInstance->GetExplicitInterface() == methodInstance->GetExplicitInterface()) &&
  22386. (checkMethod->mProtection != BfProtection_Private) &&
  22387. (CompareMethodSignatures(checkMethodInstance, mCurMethodInstance)))
  22388. {
  22389. if ((!methodDef->mIsNew) && (!checkMethod->mDeclaringType->IsExtension()))
  22390. {
  22391. BfAstNode* refNode = methodInstance->mMethodDef->GetRefNode();
  22392. if (refNode != NULL)
  22393. {
  22394. 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?
  22395. if (bfError != NULL)
  22396. {
  22397. bfError->mIsPersistent = true;
  22398. mCompiler->mPassInstance->MoreInfo("See inherited method", checkMethod->GetRefNode());
  22399. }
  22400. }
  22401. }
  22402. foundHiddenMethod = true;
  22403. break;
  22404. }
  22405. }
  22406. checkMethod = checkMethod->mNextWithSameName;
  22407. }
  22408. if (foundHiddenMethod)
  22409. break;
  22410. baseType = baseType->mBaseType;
  22411. }
  22412. if ((methodDef->mIsNew) && (!foundHiddenMethod) && (!mCurTypeInstance->IsSpecializedType()))
  22413. {
  22414. auto propertyDeclaration = methodDef->GetPropertyDeclaration();
  22415. auto tokenNode = (propertyDeclaration != NULL) ? propertyDeclaration->mNewSpecifier :
  22416. methodDeclaration->mNewSpecifier;
  22417. Fail("Method does not hide an inherited member. The 'new' keyword is not required", tokenNode, true);
  22418. }
  22419. }
  22420. }
  22421. if ((methodDef->mIsConcrete) && (!methodInstance->mIsForeignMethodDef) && (!mCurTypeInstance->IsInterface()))
  22422. {
  22423. Fail("Only interfaces methods can be declared as 'concrete'", methodDeclaration->mVirtualSpecifier);
  22424. }
  22425. if ((methodDef->mIsVirtual) && (methodDef->mIsStatic) && (!methodInstance->mIsInnerOverride))
  22426. {
  22427. if ((virtualToken != NULL) && (virtualToken->mToken == BfToken_Override) && (methodDef->mDeclaringType->mTypeCode == BfTypeCode_Extension))
  22428. Fail("No suitable method found to override", virtualToken, true);
  22429. else
  22430. Fail("Static members cannot be marked as override, virtual, or abstract", virtualToken, true);
  22431. }
  22432. else if (methodDef->mIsVirtual)
  22433. {
  22434. if ((methodDef->mProtection == BfProtection_Private) && (virtualToken != NULL))
  22435. Fail("Virtual or abstract members cannot be 'private'", virtualToken, true);
  22436. if ((methodDef->mProtection == BfProtection_Internal) && (virtualToken != NULL))
  22437. Fail("Virtual or abstract members cannot be 'internal'. Consider using the 'protected internal' access specifier.", virtualToken, true);
  22438. }
  22439. mCompiler->mStats.mMethodDeclarations++;
  22440. mCompiler->UpdateCompletion();
  22441. }
  22442. void BfModule::UniqueSlotVirtualMethod(BfMethodInstance* methodInstance)
  22443. {
  22444. BF_ASSERT(methodInstance->GetOwner() == mCurTypeInstance);
  22445. auto typeInstance = mCurTypeInstance;
  22446. auto methodDef = methodInstance->mMethodDef;
  22447. int virtualMethodMatchIdx = -1;
  22448. if (typeInstance->mHotTypeData != NULL)
  22449. {
  22450. if (typeInstance->mHotTypeData->mVTableOrigLength != -1)
  22451. {
  22452. BF_ASSERT(mCompiler->IsHotCompile());
  22453. // In the 'normal' case we'd assert that mIsOverride is false, but if we can't find the declaring method then we
  22454. // may slot this override anyway (?)
  22455. int vTableStart = 0;
  22456. auto implBaseType = typeInstance->GetImplBaseType();
  22457. if (implBaseType != NULL)
  22458. vTableStart = implBaseType->mVirtualMethodTableSize;
  22459. StringT<512> mangledName;
  22460. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), methodInstance);
  22461. for (int checkIdxOfs = 0; checkIdxOfs < (int)typeInstance->mHotTypeData->mVTableEntries.size(); checkIdxOfs++)
  22462. {
  22463. // O(1) checking when virtual methods haven't changed
  22464. int checkIdx = (typeInstance->mVirtualMethodTableSize - vTableStart + checkIdxOfs) % (int)typeInstance->mHotTypeData->mVTableEntries.size();
  22465. auto& entry = typeInstance->mHotTypeData->mVTableEntries[checkIdx];
  22466. if (mangledName == entry.mFuncName)
  22467. {
  22468. virtualMethodMatchIdx = vTableStart + checkIdx;
  22469. break;
  22470. }
  22471. }
  22472. if (virtualMethodMatchIdx != -1)
  22473. {
  22474. methodInstance->mVirtualTableIdx = virtualMethodMatchIdx;
  22475. typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mDeclaringMethod = methodInstance;
  22476. typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mImplementingMethod = methodInstance;
  22477. }
  22478. typeInstance->mVirtualMethodTableSize = (int)typeInstance->mVirtualMethodTable.size();
  22479. }
  22480. }
  22481. if (virtualMethodMatchIdx == -1)
  22482. {
  22483. methodInstance->mVirtualTableIdx = typeInstance->mVirtualMethodTableSize++;
  22484. BfVirtualMethodEntry entry = { methodInstance, methodInstance };
  22485. typeInstance->mVirtualMethodTable.push_back(entry);
  22486. }
  22487. }
  22488. void BfModule::CompareDeclTypes(BfTypeInstance* typeInst, BfTypeDef* newDeclType, BfTypeDef* prevDeclType, bool& isBetter, bool& isWorse)
  22489. {
  22490. if ((!prevDeclType->IsExtension()) && (newDeclType->IsExtension()))
  22491. {
  22492. // When we provide an extension override in the same project a root type override
  22493. isBetter = true;
  22494. isWorse = false;
  22495. }
  22496. else
  22497. {
  22498. isBetter = newDeclType->mProject->ContainsReference(prevDeclType->mProject);
  22499. isWorse = prevDeclType->mProject->ContainsReference(newDeclType->mProject);
  22500. }
  22501. if ((isBetter == isWorse) && (typeInst != NULL) && (newDeclType->IsExtension()) && (prevDeclType->IsExtension()))
  22502. {
  22503. if ((typeInst->mGenericTypeInfo != NULL) && (typeInst->mGenericTypeInfo->mGenericExtensionInfo != NULL))
  22504. {
  22505. isBetter = false;
  22506. isWorse = false;
  22507. auto newConstraints = typeInst->GetGenericParamsVector(newDeclType);
  22508. auto prevConstraints = typeInst->GetGenericParamsVector(prevDeclType);
  22509. for (int genericIdx = 0; genericIdx < (int)newConstraints->size(); genericIdx++)
  22510. {
  22511. auto newConstraint = (*newConstraints)[genericIdx];
  22512. auto prevConstraint = (*prevConstraints)[genericIdx];
  22513. bool newIsSubset = AreConstraintsSubset(newConstraint, prevConstraint);
  22514. bool prevIsSubset = AreConstraintsSubset(prevConstraint, newConstraint);
  22515. if ((prevIsSubset) && (!newIsSubset))
  22516. isBetter = true;
  22517. if ((!prevIsSubset) && (newIsSubset))
  22518. isWorse = true;
  22519. }
  22520. }
  22521. }
  22522. }
  22523. bool BfModule::SlotVirtualMethod(BfMethodInstance* methodInstance, BfAmbiguityContext* ambiguityContext)
  22524. {
  22525. BP_ZONE("BfModule::SlotVirtualMethod");
  22526. if (mCurTypeInstance->IsUnspecializedTypeVariation())
  22527. return false;
  22528. auto _AddVirtualDecl = [&](BfMethodInstance* declMethodInstance)
  22529. {
  22530. if (!mCompiler->mOptions.mAllowHotSwapping)
  22531. return;
  22532. if ((!methodInstance->mIsReified) || (!declMethodInstance->mIsReified))
  22533. return;
  22534. if (methodInstance->mHotMethod == NULL)
  22535. CheckHotMethod(methodInstance, "");
  22536. if (methodInstance->mHotMethod == NULL)
  22537. return;
  22538. //BF_ASSERT(declMethodInstance->mHotMethod != NULL);
  22539. if (declMethodInstance->mHotMethod == NULL)
  22540. CheckHotMethod(declMethodInstance, "");
  22541. auto virtualDecl = mCompiler->mHotData->GetVirtualDeclaration(declMethodInstance->mHotMethod);
  22542. virtualDecl->mRefCount++;
  22543. methodInstance->mHotMethod->mReferences.Add(virtualDecl);
  22544. };
  22545. auto typeInstance = mCurTypeInstance;
  22546. auto typeDef = typeInstance->mTypeDef;
  22547. auto methodDef = methodInstance->mMethodDef;
  22548. auto methodDeclaration = methodDef->GetMethodDeclaration();
  22549. auto propertyDeclaration = methodDef->GetPropertyDeclaration();
  22550. auto propertyMethodDeclaration = methodDef->GetPropertyMethodDeclaration();
  22551. if (methodInstance->mIsInnerOverride)
  22552. return false;
  22553. BfAstNode* declaringNode = methodDeclaration;
  22554. if (propertyMethodDeclaration != NULL)
  22555. declaringNode = propertyMethodDeclaration->mNameNode;
  22556. BfMethodInstance* methodOverriden = NULL;
  22557. bool usedMethod = false;
  22558. BfTokenNode* virtualToken = NULL;
  22559. if (propertyDeclaration != NULL)
  22560. virtualToken = propertyDeclaration->mVirtualSpecifier;
  22561. else if (methodDeclaration != NULL)
  22562. virtualToken = methodDeclaration->mVirtualSpecifier;
  22563. if ((methodDef->mIsVirtual) && (methodDef->mIsStatic))
  22564. {
  22565. //Fail: Static members cannot be marked as override, virtual, or abstract
  22566. }
  22567. else if (methodDef->mIsVirtual)
  22568. {
  22569. if (IsHotCompile())
  22570. mContext->EnsureHotMangledVirtualMethodName(methodInstance);
  22571. BfTypeInstance* checkBase = typeInstance;
  22572. // If we are in an extension, look in ourselves first
  22573. if (methodDef->mDeclaringType->mTypeDeclaration == typeInstance->mTypeDef->mTypeDeclaration)
  22574. checkBase = checkBase->mBaseType;
  22575. if (typeInstance->IsValueType())
  22576. {
  22577. if (typeInstance->mBaseType == NULL)
  22578. return false; // It's actually ValueType
  22579. // We allow structs to override object methods for when they get boxed, so just ignore 'override' keyword until it gets boxed
  22580. if (!methodDef->mIsOverride)
  22581. {
  22582. Fail("Structs cannot have virtual methods", virtualToken, true);
  22583. return false;
  22584. }
  22585. checkBase = mContext->mBfObjectType;
  22586. if (checkBase->mVirtualMethodTableSize == 0)
  22587. PopulateType(checkBase, BfPopulateType_Full);
  22588. if (checkBase->mDefineState < BfTypeDefineState_DefinedAndMethodsSlotted)
  22589. return false; // System circular ref, don't do struct checking on those
  22590. }
  22591. int virtualMethodMatchIdx = -1;
  22592. bool hadHidingError = false;
  22593. BfMethodInstance* bestOverrideMethodInstance = NULL;
  22594. BfMethodInstance* ambiguousOverrideMethodInstance = NULL;
  22595. int bestOverrideMethodIdx = -1;
  22596. int ambiguousOverrideMethodIdx = -1;
  22597. if (checkBase != NULL)
  22598. {
  22599. auto& baseVirtualMethodTable = checkBase->mVirtualMethodTable;
  22600. auto lookupType = checkBase;
  22601. while (lookupType != NULL)
  22602. {
  22603. lookupType->mTypeDef->PopulateMemberSets();
  22604. BfMethodDef* nextMethodDef = NULL;
  22605. BfMemberSetEntry* entry;
  22606. if (lookupType->mTypeDef->mMethodSet.TryGetWith((StringImpl&)methodInstance->mMethodDef->mName, &entry))
  22607. nextMethodDef = (BfMethodDef*)entry->mMemberDef;
  22608. while (nextMethodDef != NULL)
  22609. {
  22610. auto checkMethodDef = nextMethodDef;
  22611. nextMethodDef = nextMethodDef->mNextWithSameName;
  22612. if ((!checkMethodDef->mIsVirtual) || (checkMethodDef->mIsOverride))
  22613. continue;
  22614. BfMethodInstance* baseMethodInstance = NULL;
  22615. int checkMethodIdx = -1;
  22616. BfMethodInstance* lookupMethodInstance = lookupType->mMethodInstanceGroups[checkMethodDef->mIdx].mDefault;
  22617. if ((lookupMethodInstance == NULL) || (lookupMethodInstance->mVirtualTableIdx == -1))
  22618. {
  22619. if (lookupType->IsUnspecializedTypeVariation())
  22620. {
  22621. if (!lookupMethodInstance->mMethodDef->mIsOverride)
  22622. {
  22623. baseMethodInstance = lookupMethodInstance;
  22624. checkMethodIdx = -2;
  22625. }
  22626. }
  22627. if (baseMethodInstance == NULL)
  22628. continue;
  22629. }
  22630. if (baseMethodInstance == NULL)
  22631. {
  22632. checkMethodIdx = lookupMethodInstance->mVirtualTableIdx;
  22633. if (checkMethodIdx >= baseVirtualMethodTable.mSize)
  22634. {
  22635. Fail("SlotVirtualMethod out of bounds", checkMethodDef->GetRefNode());
  22636. continue;
  22637. }
  22638. auto& baseMethodRef = baseVirtualMethodTable[checkMethodIdx];
  22639. if (baseMethodRef.mDeclaringMethod.mMethodNum == -1)
  22640. {
  22641. BF_ASSERT(mCompiler->mOptions.mHasVDataExtender);
  22642. continue;
  22643. }
  22644. baseMethodInstance = baseVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  22645. if (baseMethodInstance == NULL)
  22646. {
  22647. AssertErrorState();
  22648. continue;
  22649. }
  22650. }
  22651. if ((baseMethodInstance != NULL) && (CompareMethodSignatures(baseMethodInstance, methodInstance)))
  22652. {
  22653. if (methodDef->mIsOverride)
  22654. {
  22655. BfMethodInstance* checkMethodInstance;
  22656. if (checkMethodIdx == -2)
  22657. checkMethodInstance = baseMethodInstance;
  22658. else if (typeInstance->IsValueType())
  22659. checkMethodInstance = checkBase->mVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  22660. else
  22661. checkMethodInstance = typeInstance->mVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  22662. auto newDeclType = checkMethodInstance->mMethodDef->mDeclaringType;
  22663. if (!typeInstance->IsTypeMemberAccessible(newDeclType, methodDef->mDeclaringType->mProject))
  22664. continue;
  22665. if (bestOverrideMethodInstance != NULL)
  22666. {
  22667. auto prevDeclType = bestOverrideMethodInstance->mMethodDef->mDeclaringType;
  22668. bool isBetter = newDeclType->mProject->ContainsReference(prevDeclType->mProject);
  22669. bool isWorse = prevDeclType->mProject->ContainsReference(newDeclType->mProject);
  22670. if (isBetter == isWorse)
  22671. {
  22672. ambiguousOverrideMethodInstance = bestOverrideMethodInstance;
  22673. }
  22674. else
  22675. {
  22676. if (isWorse)
  22677. continue;
  22678. ambiguousOverrideMethodInstance = NULL;
  22679. }
  22680. }
  22681. bestOverrideMethodInstance = checkMethodInstance;
  22682. bestOverrideMethodIdx = checkMethodIdx;
  22683. }
  22684. else
  22685. {
  22686. if ((baseMethodInstance->GetOwner() != methodInstance->GetOwner()) && (!methodDef->mIsNew))
  22687. {
  22688. if (!hadHidingError)
  22689. Warn(BfWarning_CS0114_MethodHidesInherited, StrFormat("Method hides inherited member from '%s'. Use either 'override' or 'new'.", TypeToString(checkBase).c_str()), declaringNode);
  22690. hadHidingError = true;
  22691. }
  22692. }
  22693. }
  22694. }
  22695. lookupType = lookupType->mBaseType;
  22696. }
  22697. }
  22698. //TODO:
  22699. if ((checkBase != NULL)
  22700. && (false)
  22701. )
  22702. {
  22703. auto& baseVirtualMethodTable = checkBase->mVirtualMethodTable;
  22704. for (int checkMethodIdx = (int) baseVirtualMethodTable.size() - 1; checkMethodIdx >= 0; checkMethodIdx--)
  22705. {
  22706. auto& baseMethodRef = baseVirtualMethodTable[checkMethodIdx];
  22707. if (baseMethodRef.mDeclaringMethod.mMethodNum == -1)
  22708. {
  22709. BF_ASSERT(mCompiler->mOptions.mHasVDataExtender);
  22710. continue;
  22711. }
  22712. BfMethodInstance* baseMethodInstance = baseVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  22713. if (baseMethodInstance == NULL)
  22714. {
  22715. AssertErrorState();
  22716. continue;
  22717. }
  22718. if ((baseMethodInstance != NULL) && (CompareMethodSignatures(baseMethodInstance, methodInstance)))
  22719. {
  22720. if (methodDef->mIsOverride)
  22721. {
  22722. BfMethodInstance* checkMethodInstance;
  22723. if (typeInstance->IsValueType())
  22724. checkMethodInstance = checkBase->mVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  22725. else
  22726. checkMethodInstance = typeInstance->mVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  22727. auto newDeclType = checkMethodInstance->mMethodDef->mDeclaringType;
  22728. if (!typeInstance->IsTypeMemberAccessible(newDeclType, methodDef->mDeclaringType->mProject))
  22729. continue;
  22730. if (bestOverrideMethodInstance != NULL)
  22731. {
  22732. auto prevDeclType = bestOverrideMethodInstance->mMethodDef->mDeclaringType;
  22733. bool isBetter = newDeclType->mProject->ContainsReference(prevDeclType->mProject);
  22734. bool isWorse = prevDeclType->mProject->ContainsReference(newDeclType->mProject);
  22735. if (isBetter == isWorse)
  22736. {
  22737. ambiguousOverrideMethodInstance = bestOverrideMethodInstance;
  22738. }
  22739. else
  22740. {
  22741. if (isWorse)
  22742. continue;
  22743. ambiguousOverrideMethodInstance = NULL;
  22744. }
  22745. }
  22746. bestOverrideMethodInstance = checkMethodInstance;
  22747. bestOverrideMethodIdx = checkMethodIdx;
  22748. }
  22749. else
  22750. {
  22751. if ((baseMethodInstance->GetOwner() != methodInstance->GetOwner()) && (!methodDef->mIsNew))
  22752. {
  22753. if (!hadHidingError)
  22754. Warn(BfWarning_CS0114_MethodHidesInherited, StrFormat("Method hides inherited member from '%s'. Use either 'override' or 'new'.", TypeToString(checkBase).c_str()), declaringNode);
  22755. hadHidingError = true;
  22756. }
  22757. }
  22758. }
  22759. }
  22760. }
  22761. if (bestOverrideMethodInstance != NULL)
  22762. {
  22763. if (ambiguousOverrideMethodInstance != NULL)
  22764. {
  22765. bool allow = false;
  22766. // 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.
  22767. // When when specialize, the specialized type will determine wither it has illegally pulled in both declarations or not
  22768. bool canSeeEachOther = false;
  22769. //
  22770. {
  22771. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, ambiguousOverrideMethodInstance);
  22772. if (bestOverrideMethodInstance->GetOwner()->IsTypeMemberIncluded(bestOverrideMethodInstance->mMethodDef->mDeclaringType, ambiguousOverrideMethodInstance->mMethodDef->mDeclaringType, this))
  22773. canSeeEachOther = true;
  22774. }
  22775. //
  22776. {
  22777. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, bestOverrideMethodInstance);
  22778. if (ambiguousOverrideMethodInstance->GetOwner()->IsTypeMemberIncluded(ambiguousOverrideMethodInstance->mMethodDef->mDeclaringType, bestOverrideMethodInstance->mMethodDef->mDeclaringType, this))
  22779. canSeeEachOther = true;
  22780. }
  22781. if (!canSeeEachOther)
  22782. {
  22783. BF_ASSERT(bestOverrideMethodInstance->GetOwner()->IsUnspecializedType() && ambiguousOverrideMethodInstance->GetOwner()->IsUnspecializedType());
  22784. }
  22785. else
  22786. {
  22787. auto error = Fail(StrFormat("Method '%s' is an ambiguous override", MethodToString(methodInstance).c_str()), methodDef->GetRefNode());
  22788. if (error != NULL)
  22789. {
  22790. mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' is a candidate", MethodToString(bestOverrideMethodInstance).c_str()), bestOverrideMethodInstance->mMethodDef->GetRefNode());
  22791. mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' is a candidate", MethodToString(ambiguousOverrideMethodInstance).c_str()), ambiguousOverrideMethodInstance->mMethodDef->GetRefNode());
  22792. }
  22793. }
  22794. }
  22795. }
  22796. if (bestOverrideMethodIdx == -2)
  22797. {
  22798. // Comes from an unspecialized variation
  22799. virtualMethodMatchIdx = bestOverrideMethodIdx;
  22800. }
  22801. else if ((bestOverrideMethodInstance != NULL) && (bestOverrideMethodIdx != -1))
  22802. {
  22803. auto& baseVirtualMethodTable = checkBase->mVirtualMethodTable;
  22804. BfMethodInstance* baseVirtualMethodInstance = baseVirtualMethodTable[bestOverrideMethodIdx].mDeclaringMethod;
  22805. if ((baseVirtualMethodInstance != methodInstance) && (methodDef->mIsOverride))
  22806. {
  22807. if (baseVirtualMethodInstance->mReturnType != methodInstance->mReturnType)
  22808. {
  22809. BfTypeReference* returnTypeRef;
  22810. if (auto propertyDeclaration = methodDef->GetPropertyDeclaration())
  22811. {
  22812. returnTypeRef = propertyDeclaration->mTypeRef;
  22813. Fail("Property differs from overridden property by type", returnTypeRef, true);
  22814. }
  22815. else if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  22816. {
  22817. returnTypeRef = methodDeclaration->mReturnType;
  22818. Fail("Method differs from overridden method by return value", returnTypeRef, true);
  22819. }
  22820. else
  22821. {
  22822. Fail(StrFormat("Internal error with method '%s'", MethodToString(methodInstance).c_str()));
  22823. }
  22824. return usedMethod;
  22825. }
  22826. }
  22827. if (methodDef->mIsOverride)
  22828. {
  22829. // We can have multiple matches when a virtual method is used to implement interface methods
  22830. // It doesn't matter what we set mVirtualTableIdx, as all base classes will override all matching
  22831. // vtable entries for this method signature
  22832. virtualMethodMatchIdx = bestOverrideMethodIdx;
  22833. if (!typeInstance->IsValueType())
  22834. methodInstance->mVirtualTableIdx = virtualMethodMatchIdx;
  22835. if (typeInstance->IsValueType())
  22836. {
  22837. methodOverriden = checkBase->mVirtualMethodTable[virtualMethodMatchIdx].mImplementingMethod;
  22838. }
  22839. else
  22840. {
  22841. methodInstance->mVirtualTableIdx = virtualMethodMatchIdx;
  22842. bool preferRootDefinition = (methodDef->mName == BF_METHODNAME_MARKMEMBERS) || (methodDef->mMethodType == BfMethodType_Dtor);
  22843. BfMethodInstance* setMethodInstance = methodInstance;
  22844. bool doOverride = false;
  22845. auto& overridenRef = typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mImplementingMethod;
  22846. if (overridenRef.mKind != BfMethodRefKind_AmbiguousRef)
  22847. {
  22848. methodOverriden = overridenRef;
  22849. doOverride = true;
  22850. if (methodOverriden->GetOwner() == methodInstance->GetOwner())
  22851. {
  22852. bool isBetter = false;
  22853. bool isWorse = false;
  22854. CompareDeclTypes(typeInstance, methodInstance->mMethodDef->mDeclaringType, methodOverriden->mMethodDef->mDeclaringType, isBetter, isWorse);
  22855. if (isBetter == isWorse)
  22856. {
  22857. // We have to resolve later per-project
  22858. if ((ambiguityContext != NULL) && (ambiguityContext->mIsProjectSpecific))
  22859. {
  22860. auto declMethodInstance = checkBase->mVirtualMethodTable[virtualMethodMatchIdx].mDeclaringMethod;
  22861. ambiguityContext->Add(virtualMethodMatchIdx, NULL, -1, methodOverriden, methodInstance);
  22862. }
  22863. if ((ambiguityContext == NULL) || (!ambiguityContext->mIsProjectSpecific))
  22864. typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mImplementingMethod.mKind = BfMethodRefKind_AmbiguousRef;
  22865. doOverride = false;
  22866. }
  22867. else
  22868. {
  22869. if ((isBetter) && (ambiguityContext != NULL))
  22870. {
  22871. ambiguityContext->Remove(virtualMethodMatchIdx);
  22872. }
  22873. if ((isBetter) && (methodInstance->GetOwner() == methodOverriden->GetOwner()))
  22874. {
  22875. if (preferRootDefinition)
  22876. {
  22877. // Leave the master GCMarkMember
  22878. isBetter = false;
  22879. isWorse = true;
  22880. }
  22881. }
  22882. doOverride = isBetter;
  22883. }
  22884. }
  22885. }
  22886. else if ((preferRootDefinition) && (!methodDef->mDeclaringType->IsExtension()))
  22887. {
  22888. methodOverriden = overridenRef;
  22889. doOverride = true;
  22890. }
  22891. if (doOverride)
  22892. {
  22893. auto declMethodInstance = (BfMethodInstance*)typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mDeclaringMethod;
  22894. _AddVirtualDecl(declMethodInstance);
  22895. setMethodInstance->mVirtualTableIdx = virtualMethodMatchIdx;
  22896. auto& implMethodRef = typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mImplementingMethod;
  22897. if ((!mCompiler->mIsResolveOnly) && (implMethodRef.mMethodNum >= 0) &&
  22898. (implMethodRef.mTypeInstance == typeInstance) && (methodInstance->GetOwner() == typeInstance))
  22899. {
  22900. auto prevImplMethodInstance = (BfMethodInstance*)implMethodRef;
  22901. if (prevImplMethodInstance->mMethodDef->mDeclaringType->mProject != methodInstance->mMethodDef->mDeclaringType->mProject)
  22902. {
  22903. // We may need to have to previous method reified when we must re-slot in another project during vdata creation
  22904. BfReifyMethodDependency dep;
  22905. dep.mDepMethod = typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mDeclaringMethod;
  22906. dep.mMethodIdx = implMethodRef.mMethodNum;
  22907. typeInstance->mReifyMethodDependencies.Add(dep);
  22908. }
  22909. if (!methodInstance->mMangleWithIdx)
  22910. {
  22911. // Keep mangled names from conflicting
  22912. methodInstance->mMangleWithIdx = true;
  22913. if ((methodInstance->mIRFunction) && (methodInstance->mDeclModule->mIsModuleMutable))
  22914. {
  22915. StringT<4096> mangledName;
  22916. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), methodInstance);
  22917. methodInstance->mDeclModule->mBfIRBuilder->SetFunctionName(methodInstance->mIRFunction, mangledName);
  22918. }
  22919. }
  22920. }
  22921. typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mImplementingMethod = setMethodInstance;
  22922. }
  22923. }
  22924. if (methodOverriden != NULL)
  22925. {
  22926. CheckOverridenMethod(methodInstance, methodOverriden);
  22927. }
  22928. }
  22929. }
  22930. if ((virtualMethodMatchIdx == -1) && ((ambiguityContext == NULL) || (!ambiguityContext->mIsReslotting)))
  22931. {
  22932. if (methodDef->mIsOverride)
  22933. {
  22934. BfTokenNode* overrideToken = NULL;
  22935. if (auto propertyMethodDeclaration = methodDef->GetPropertyMethodDeclaration())
  22936. overrideToken = propertyMethodDeclaration->mPropertyDeclaration->mVirtualSpecifier;
  22937. else if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  22938. overrideToken = methodDeclaration->mVirtualSpecifier;
  22939. if (overrideToken != NULL)
  22940. {
  22941. if ((propertyDeclaration != NULL) && (propertyDeclaration->mNameNode != NULL) &&
  22942. ((methodDef->mMethodType == BfMethodType_PropertyGetter) || (methodDef->mMethodType == BfMethodType_PropertySetter)))
  22943. Fail(StrFormat("No suitable method found to override for '%s.%s'",
  22944. propertyDeclaration->mNameNode->ToString().c_str(), (methodDef->mMethodType == BfMethodType_PropertyGetter) ? "get" : "set"), overrideToken, true);
  22945. else
  22946. Fail("No suitable method found to override", overrideToken, true);
  22947. }
  22948. return usedMethod;
  22949. }
  22950. UniqueSlotVirtualMethod(methodInstance);
  22951. }
  22952. else
  22953. usedMethod = true;
  22954. if (typeInstance->IsValueType())
  22955. return usedMethod;
  22956. }
  22957. bool foundInterface = false;
  22958. bool hadAnyMatch = false;
  22959. // See if this method matches interfaces
  22960. for (auto& ifaceTypeInst : typeInstance->mInterfaces)
  22961. {
  22962. auto ifaceInst = ifaceTypeInst.mInterfaceType;
  22963. if (ifaceInst->IsIncomplete())
  22964. PopulateType(ifaceInst, BfPopulateType_DataAndMethods);
  22965. int startIdx = ifaceTypeInst.mStartInterfaceTableIdx;
  22966. int iMethodCount = (int)ifaceInst->mMethodInstanceGroups.size();
  22967. // See "bidirectional" rules mentioned in DoTypeInstanceMethodProcessing
  22968. if ((!typeInstance->IsTypeMemberAccessible(methodDef->mDeclaringType, ifaceTypeInst.mDeclaringType)) &&
  22969. (!typeInstance->IsTypeMemberAccessible(ifaceTypeInst.mDeclaringType, methodDef->mDeclaringType)))
  22970. continue;
  22971. if (!typeInstance->IsTypeMemberIncluded(methodDef->mDeclaringType, ifaceTypeInst.mDeclaringType, this))
  22972. continue;
  22973. bool hadMatch = false;
  22974. BfMethodInstance* hadNameMatch = NULL;
  22975. BfType* expectedReturnType = NULL;
  22976. bool showedError = false;
  22977. // We go through our VTable looking for NULL entries within the interface sections
  22978. // The only instance of finding a "better" method is when we have explicitly interface-dotted method
  22979. // because a normal method declared in this type could have matched earlier
  22980. //for (int iMethodIdx = 0; iMethodIdx < iMethodCount; iMethodIdx++)
  22981. ifaceInst->mTypeDef->PopulateMemberSets();
  22982. BfMethodDef* checkMethodDef = NULL;
  22983. BfMemberSetEntry* entry;
  22984. if (ifaceInst->mTypeDef->mMethodSet.TryGetWith((StringImpl&)methodInstance->mMethodDef->mName, &entry))
  22985. checkMethodDef = (BfMethodDef*)entry->mMemberDef;
  22986. while (checkMethodDef != NULL)
  22987. {
  22988. int iMethodIdx = checkMethodDef->mIdx;
  22989. int iTableIdx = iMethodIdx + startIdx;
  22990. BfTypeInterfaceMethodEntry* interfaceMethodEntry = &typeInstance->mInterfaceMethodTable[iTableIdx];
  22991. auto iMethodPtr = &interfaceMethodEntry->mMethodRef;
  22992. bool storeIFaceMethod = false;
  22993. if ((mCompiler->mPassInstance->HasFailed()) && (iMethodIdx >= (int)ifaceInst->mMethodInstanceGroups.size()))
  22994. {
  22995. checkMethodDef = checkMethodDef->mNextWithSameName;
  22996. continue;
  22997. }
  22998. if (iMethodIdx >= ifaceInst->mMethodInstanceGroups.mSize)
  22999. PopulateType(ifaceInst, BfPopulateType_DataAndMethods);
  23000. if (iMethodIdx >= ifaceInst->mMethodInstanceGroups.mSize)
  23001. {
  23002. InternalError("Interface slotting error", methodInstance->mMethodDef->GetMutNode());
  23003. break;
  23004. }
  23005. auto& iMethodGroup = ifaceInst->mMethodInstanceGroups[iMethodIdx];
  23006. auto iMethodInst = iMethodGroup.mDefault;
  23007. if (iMethodInst == NULL)
  23008. {
  23009. if ((!ifaceInst->IsGenericTypeInstance()) || (!ifaceInst->mTypeDef->mIsCombinedPartial))
  23010. AssertErrorState();
  23011. checkMethodDef = checkMethodDef->mNextWithSameName;
  23012. continue;
  23013. }
  23014. if (iMethodInst->mMethodDef->mName == methodInstance->mMethodDef->mName)
  23015. hadNameMatch = iMethodInst;
  23016. bool doesMethodSignatureMatch = CompareMethodSignatures(iMethodInst, methodInstance);
  23017. if ((!doesMethodSignatureMatch) && (interfaceMethodEntry->mMethodRef.IsNull()))
  23018. {
  23019. doesMethodSignatureMatch = IsCompatibleInterfaceMethod(iMethodInst, methodInstance);
  23020. }
  23021. if ((doesMethodSignatureMatch) && (methodInstance->GetOwner()->IsValueType()))
  23022. {
  23023. if ((!iMethodInst->mMethodDef->mIsMutating) && (methodInstance->mMethodDef->mIsMutating))
  23024. {
  23025. if ((methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface == ifaceInst))
  23026. {
  23027. auto error = mCompiler->mPassInstance->Fail(StrFormat("Implementation method '%s' cannot specify 'mut' because the interface method does not allow it",
  23028. MethodToString(methodInstance).c_str()), methodInstance->mMethodDef->GetMutNode());
  23029. if (error != NULL)
  23030. mCompiler->mPassInstance->MoreInfo(StrFormat("Declare the interface method as 'mut' to allow matching 'mut' implementations"), iMethodInst->mMethodDef->mMethodDeclaration);
  23031. showedError = true;
  23032. }
  23033. }
  23034. }
  23035. if (doesMethodSignatureMatch)
  23036. {
  23037. usedMethod = true;
  23038. hadMatch = true;
  23039. hadAnyMatch = true;
  23040. storeIFaceMethod = true;
  23041. if ((iMethodPtr->mKind != BfMethodRefKind_AmbiguousRef) && (iMethodPtr->mTypeInstance != NULL))
  23042. {
  23043. auto prevMethod = (BfMethodInstance*)*iMethodPtr;
  23044. if ((mCompiler->mIsResolveOnly) && (prevMethod == methodInstance) && (!mIsComptimeModule))
  23045. {
  23046. // When autocompletion regenerates a single method body but not the whole type then
  23047. // we will see ourselves in the vtable already
  23048. return usedMethod;
  23049. }
  23050. bool isBetter = false;
  23051. bool isWorse = false;
  23052. isBetter = (methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface != NULL);
  23053. isWorse = (prevMethod->mMethodInfoEx != NULL) && (prevMethod->mMethodInfoEx->mExplicitInterface != NULL);
  23054. if (isBetter == isWorse)
  23055. {
  23056. isBetter = methodInstance->mReturnType == iMethodInst->mReturnType;
  23057. isWorse = prevMethod->mReturnType == iMethodInst->mReturnType;
  23058. }
  23059. if (isBetter == isWorse)
  23060. CompareDeclTypes(typeInstance, methodInstance->mMethodDef->mDeclaringType, prevMethod->mMethodDef->mDeclaringType, isBetter, isWorse);
  23061. if (isBetter == isWorse)
  23062. {
  23063. if (ambiguityContext != NULL)
  23064. {
  23065. ambiguityContext->Add(~iTableIdx, &ifaceTypeInst, iMethodIdx, prevMethod, methodInstance);
  23066. }
  23067. iMethodPtr->mKind = BfMethodRefKind_AmbiguousRef;
  23068. storeIFaceMethod = true;
  23069. }
  23070. else
  23071. {
  23072. if ((isBetter) && (ambiguityContext != NULL))
  23073. ambiguityContext->Remove(~iTableIdx);
  23074. storeIFaceMethod = isBetter;
  23075. }
  23076. }
  23077. }
  23078. if (storeIFaceMethod)
  23079. {
  23080. if (methodInstance->GetNumGenericParams() != 0)
  23081. _AddVirtualDecl(iMethodInst);
  23082. *iMethodPtr = methodInstance;
  23083. }
  23084. checkMethodDef = checkMethodDef->mNextWithSameName;
  23085. }
  23086. if ((methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface == ifaceInst) && (!hadMatch) && (!showedError))
  23087. {
  23088. if (expectedReturnType != NULL)
  23089. Fail(StrFormat("Wrong return type, expected '%s'", TypeToString(expectedReturnType).c_str()), declaringNode, true);
  23090. else if (hadNameMatch != NULL)
  23091. {
  23092. auto error = Fail("Method parameters don't match interface method", declaringNode, true);
  23093. if (error != NULL)
  23094. mCompiler->mPassInstance->MoreInfo("See interface method declaration", hadNameMatch->mMethodDef->GetRefNode());
  23095. }
  23096. else
  23097. {
  23098. auto propertyDecl = methodDef->GetPropertyDeclaration();
  23099. if (propertyDecl != NULL)
  23100. {
  23101. auto propertyMethodDecl = methodDef->GetPropertyMethodDeclaration();
  23102. String name;
  23103. if (auto indexerDeclaration = BfNodeDynCast<BfIndexerDeclaration>(propertyDecl))
  23104. name = "this[]";
  23105. else if (propertyDecl->mNameNode != NULL)
  23106. propertyDecl->mNameNode->ToString(name);
  23107. Fail(StrFormat("Property '%s' %s accessor not defined in interface '%s'", name.c_str(),
  23108. (methodDef->mMethodType == BfMethodType_PropertyGetter) ? "get" : "set", TypeToString(ifaceInst).c_str()), methodDef->GetRefNode(), true);
  23109. }
  23110. else
  23111. Fail(StrFormat("Method '%s' not found in interface '%s'", methodDef->mName.c_str(), TypeToString(ifaceInst).c_str()), methodDef->GetRefNode(), true);
  23112. }
  23113. }
  23114. }
  23115. // Any overriden virtual methods that were used in interfaces also need to be replaced
  23116. if (methodOverriden != NULL)
  23117. {
  23118. for (auto& methodEntry : typeInstance->mInterfaceMethodTable)
  23119. {
  23120. if (methodEntry.mMethodRef == methodOverriden)
  23121. methodEntry.mMethodRef = methodInstance;
  23122. }
  23123. }
  23124. return usedMethod;
  23125. }
  23126. void BfModule::CheckOverridenMethod(BfMethodInstance* methodInstance, BfMethodInstance* methodOverriden)
  23127. {
  23128. auto methodDef = methodInstance->mMethodDef;
  23129. auto prevProtection = methodOverriden->mMethodDef->mProtection;
  23130. if ((methodDef->mProtection != prevProtection) && (methodDef->mMethodType != BfMethodType_Dtor))
  23131. {
  23132. const char* protectionNames[] = { "disabled", "hidden", "private", "internal", "protected", "protected internal", "public" };
  23133. BF_STATIC_ASSERT(BF_ARRAY_COUNT(protectionNames) == BfProtection_COUNT);
  23134. BfAstNode* protectionRefNode = NULL;
  23135. if (auto propertyMethodDeclaration = methodDef->GetPropertyMethodDeclaration())
  23136. {
  23137. protectionRefNode = propertyMethodDeclaration->mProtectionSpecifier;
  23138. if (protectionRefNode == NULL)
  23139. protectionRefNode = propertyMethodDeclaration->mPropertyDeclaration->mProtectionSpecifier;
  23140. if (protectionRefNode == NULL)
  23141. protectionRefNode = propertyMethodDeclaration->mPropertyDeclaration->mNameNode;
  23142. }
  23143. else if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  23144. {
  23145. protectionRefNode = methodDeclaration->mProtectionSpecifier;
  23146. if (protectionRefNode == NULL)
  23147. protectionRefNode = methodDeclaration->mNameNode;
  23148. }
  23149. if (protectionRefNode != NULL)
  23150. Fail(StrFormat("Cannot change access modifiers when overriding '%s' inherited member", protectionNames[(int)prevProtection]), protectionRefNode, true);
  23151. }
  23152. }
  23153. bool BfModule::SlotInterfaceMethod(BfMethodInstance* methodInstance)
  23154. {
  23155. auto typeInstance = mCurTypeInstance;
  23156. auto methodDef = methodInstance->mMethodDef;
  23157. if (methodDef->mMethodType == BfMethodType_Ctor)
  23158. return true;
  23159. bool foundOverride = false;
  23160. if ((methodDef->mBody == NULL) && (methodDef->mProtection == BfProtection_Private))
  23161. {
  23162. auto methodDeclaration = methodDef->GetMethodDeclaration();
  23163. BfAstNode* refNode = NULL;
  23164. if (auto propertyDeclaration = methodDef->GetPropertyDeclaration())
  23165. refNode = propertyDeclaration->mProtectionSpecifier;
  23166. else if (methodDeclaration != NULL)
  23167. refNode = methodDeclaration->mProtectionSpecifier;
  23168. Fail("Private interface methods must provide a body", refNode);
  23169. }
  23170. if ((methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface != NULL) && (!methodDef->mIsOverride))
  23171. {
  23172. Fail("Explicit interfaces can only be specified for overrides in interface declarations", methodDef->GetMethodDeclaration()->mExplicitInterface);
  23173. }
  23174. BfAstNode* declaringNode = methodDef->GetRefNode();
  23175. for (auto& ifaceTypeInst : typeInstance->mInterfaces)
  23176. {
  23177. auto ifaceInst = ifaceTypeInst.mInterfaceType;
  23178. int startIdx = ifaceTypeInst.mStartInterfaceTableIdx;
  23179. int iMethodCount = (int)ifaceInst->mMethodInstanceGroups.size();
  23180. if ((methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface != ifaceInst))
  23181. continue;
  23182. ifaceInst->mTypeDef->PopulateMemberSets();
  23183. BfMethodDef* nextMethod = NULL;
  23184. BfMemberSetEntry* entry = NULL;
  23185. if (ifaceInst->mTypeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  23186. nextMethod = (BfMethodDef*)entry->mMemberDef;
  23187. while (nextMethod != NULL)
  23188. {
  23189. auto checkMethod = nextMethod;
  23190. nextMethod = nextMethod->mNextWithSameName;
  23191. auto ifaceMethod = ifaceInst->mMethodInstanceGroups[checkMethod->mIdx].mDefault;
  23192. if (ifaceMethod == NULL)
  23193. continue;
  23194. if (CompareMethodSignatures(ifaceMethod, methodInstance))
  23195. {
  23196. if (methodDef->mIsOverride)
  23197. {
  23198. if (ifaceMethod->mMethodDef->mProtection == BfProtection_Private)
  23199. {
  23200. auto error = Fail(StrFormat("Interface method '%s' cannot override private interface method '%s'", MethodToString(methodInstance).c_str(), MethodToString(ifaceMethod).c_str()), declaringNode);
  23201. if (error != NULL)
  23202. {
  23203. mCompiler->mPassInstance->MoreInfo("See base interface method", ifaceMethod->mMethodDef->GetRefNode());
  23204. }
  23205. }
  23206. foundOverride = true;
  23207. }
  23208. else if (!methodDef->mIsNew)
  23209. {
  23210. auto error = Warn(BfWarning_CS0114_MethodHidesInherited, StrFormat("Method hides inherited member from '%s'. Use the 'new' keyword if hiding was intentional.", TypeToString(ifaceInst).c_str()), declaringNode);
  23211. if (error != NULL)
  23212. {
  23213. mCompiler->mPassInstance->MoreInfo("See inherited method", ifaceMethod->mMethodDef->GetRefNode());
  23214. }
  23215. }
  23216. }
  23217. }
  23218. }
  23219. if ((methodDef->mIsOverride) && (!foundOverride))
  23220. {
  23221. // This allows us to declare a method in the base definition or in an extension and then provide
  23222. // an implementation in a more-specific extension
  23223. typeInstance->mTypeDef->PopulateMemberSets();
  23224. BfMethodDef* nextMethod = NULL;
  23225. BfMemberSetEntry* entry = NULL;
  23226. if (typeInstance->mTypeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  23227. nextMethod = (BfMethodDef*)entry->mMemberDef;
  23228. while (nextMethod != NULL)
  23229. {
  23230. auto checkMethod = nextMethod;
  23231. nextMethod = nextMethod->mNextWithSameName;
  23232. auto ifaceMethod = typeInstance->mMethodInstanceGroups[checkMethod->mIdx].mDefault;
  23233. if (ifaceMethod == NULL)
  23234. continue;
  23235. if (ifaceMethod->mMethodDef->mDeclaringType == methodInstance->mMethodDef->mDeclaringType)
  23236. continue;
  23237. if (CompareMethodSignatures(ifaceMethod, methodInstance))
  23238. {
  23239. foundOverride = true;
  23240. }
  23241. }
  23242. // for (int methodIdx = 0; methodIdx < typeInstance->mMethodInstanceGroups.size(); methodIdx++)
  23243. // {
  23244. // auto ifaceMethod = typeInstance->mMethodInstanceGroups[methodIdx].mDefault;
  23245. // if (ifaceMethod == NULL)
  23246. // continue;
  23247. // if (ifaceMethod->mMethodDef->mDeclaringType == methodInstance->mMethodDef->mDeclaringType)
  23248. // continue;
  23249. //
  23250. // if (CompareMethodSignatures(ifaceMethod, methodInstance))
  23251. // {
  23252. // foundOverride = true;
  23253. // }
  23254. // }
  23255. }
  23256. if (methodDef->mIsOverride)
  23257. {
  23258. if (!foundOverride)
  23259. {
  23260. BfTokenNode* overrideToken = NULL;
  23261. if (auto propertyDeclaration = methodDef->GetPropertyDeclaration())
  23262. overrideToken = propertyDeclaration->mVirtualSpecifier;
  23263. else if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  23264. overrideToken = methodDeclaration->mVirtualSpecifier;
  23265. if (overrideToken != NULL)
  23266. {
  23267. Fail("No suitable method found to override", overrideToken, true);
  23268. }
  23269. else
  23270. {
  23271. // Possible cause - DTOR with params
  23272. AssertErrorState();
  23273. }
  23274. }
  23275. return true;
  23276. }
  23277. // Generic methods can't be called virtually
  23278. if (methodInstance->GetNumGenericParams() != 0)
  23279. return true;
  23280. // Only public methods can be called virtually
  23281. if (methodDef->mProtection != BfProtection_Public)
  23282. return true;
  23283. UniqueSlotVirtualMethod(methodInstance);
  23284. return true;
  23285. }
  23286. void BfModule::SetMethodDependency(BfMethodInstance* methodInstance)
  23287. {
  23288. if (methodInstance->mMethodInfoEx == NULL)
  23289. return;
  23290. int wantMinDepth = -1;
  23291. if (mCurTypeInstance != NULL)
  23292. wantMinDepth = mCurTypeInstance->mDependencyMap.mMinDependDepth + 1;
  23293. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mMethodInfoEx != NULL) && (mCurMethodInstance->mMethodInfoEx->mMinDependDepth != -1))
  23294. {
  23295. int wantTypeMinDepth = mCurMethodInstance->mMethodInfoEx->mMinDependDepth + 1;
  23296. if ((wantMinDepth == -1) || (wantTypeMinDepth < wantMinDepth))
  23297. wantMinDepth = wantTypeMinDepth;
  23298. }
  23299. if ((methodInstance->mMethodInfoEx->mMinDependDepth == -1) || (wantMinDepth < methodInstance->mMethodInfoEx->mMinDependDepth))
  23300. methodInstance->mMethodInfoEx->mMinDependDepth = wantMinDepth;
  23301. }
  23302. void BfModule::DbgFinish()
  23303. {
  23304. if ((mBfIRBuilder == NULL) || (mExtensionCount != 0))
  23305. return;
  23306. if (mAwaitingInitFinish)
  23307. FinishInit();
  23308. if (mHasForceLinkMarker)
  23309. return;
  23310. String markerName;
  23311. BfIRValue linkMarker;
  23312. if (mBfIRBuilder->DbgHasInfo())
  23313. {
  23314. bool needForceLinking = false;
  23315. if (WantsDebugHelpers())
  23316. {
  23317. for (auto& ownedType : mOwnedTypeInstances)
  23318. {
  23319. bool hasConfirmedReference = false;
  23320. for (auto& methodInstGroup : ownedType->mMethodInstanceGroups)
  23321. {
  23322. if ((methodInstGroup.IsImplemented()) && (methodInstGroup.mDefault != NULL) &&
  23323. (!methodInstGroup.mDefault->mMethodDef->mIsStatic) && (methodInstGroup.mDefault->mIsReified) && (!methodInstGroup.mDefault->mAlwaysInline) &&
  23324. ((methodInstGroup.mOnDemandKind == BfMethodOnDemandKind_AlwaysInclude) || (methodInstGroup.mOnDemandKind == BfMethodOnDemandKind_Referenced)) &&
  23325. (methodInstGroup.mHasEmittedReference))
  23326. {
  23327. hasConfirmedReference = true;
  23328. }
  23329. }
  23330. if ((!hasConfirmedReference) || (ownedType->IsBoxed()))
  23331. needForceLinking = true;
  23332. }
  23333. }
  23334. if ((needForceLinking) && (mProject->mCodeGenOptions.mAsmKind == BfAsmKind_None))
  23335. {
  23336. BfMethodState methodState;
  23337. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  23338. methodState.mTempKind = BfMethodState::TempKind_Static;
  23339. mHasForceLinkMarker = true;
  23340. auto voidType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_None));
  23341. SizedArray<BfIRType, 0> paramTypes;
  23342. BfIRFunctionType funcType = mBfIRBuilder->CreateFunctionType(voidType, paramTypes);
  23343. String linkName = "FORCELINKMOD_" + mModuleName;
  23344. BfIRFunction func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, linkName);
  23345. mBfIRBuilder->SetActiveFunction(func);
  23346. auto entryBlock = mBfIRBuilder->CreateBlock("main", true);
  23347. mBfIRBuilder->SetInsertPoint(entryBlock);
  23348. auto firstType = mOwnedTypeInstances[0];
  23349. UpdateSrcPos(mContext->mBfObjectType->mTypeDef->GetRefNode());
  23350. SizedArray<BfIRMDNode, 1> diParamTypes;
  23351. diParamTypes.Add(mBfIRBuilder->DbgGetType(GetPrimitiveType(BfTypeCode_None)));
  23352. BfIRMDNode diFuncType = mBfIRBuilder->DbgCreateSubroutineType(diParamTypes);
  23353. auto diScope = mBfIRBuilder->DbgCreateFunction(mDICompileUnit, "FORCELINKMOD", linkName, mCurFilePosition.mFileInstance->mDIFile,
  23354. mCurFilePosition.mCurLine + 1, diFuncType, false, true, mCurFilePosition.mCurLine + 1, 0, false, func);
  23355. methodState.mCurScope->mDIScope = diScope;
  23356. UpdateSrcPos(mContext->mBfObjectType->mTypeDef->GetRefNode(), BfSrcPosFlag_Force);
  23357. SizedArray<BfIRValue, 8> args;
  23358. BfExprEvaluator exprEvaluator(this);
  23359. for (auto& ownedType : mOwnedTypeInstances)
  23360. {
  23361. auto alloca = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_Int8)));
  23362. auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(diScope, "variable", mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, mBfIRBuilder->DbgGetType(ownedType));
  23363. mBfIRBuilder->DbgInsertDeclare(alloca, diVariable);
  23364. }
  23365. mBfIRBuilder->CreateRetVoid();
  23366. mBfIRBuilder->SetActiveFunction(BfIRFunction());
  23367. }
  23368. }
  23369. }
  23370. bool BfModule::Finish()
  23371. {
  23372. BP_ZONE("BfModule::Finish");
  23373. BfLogSysM("BfModule finish: %p\n", this);
  23374. if (mHadBuildError)
  23375. {
  23376. // Don't AssertErrorState here, this current pass may not have failed but
  23377. // the module was still queued in mFinishedModuleWorkList
  23378. ClearModule();
  23379. return true;
  23380. }
  23381. if (mUsedSlotCount != -1)
  23382. {
  23383. BF_ASSERT(mCompiler->mMaxInterfaceSlots != -1);
  23384. mUsedSlotCount = mCompiler->mMaxInterfaceSlots;
  23385. }
  23386. if ((!mGeneratesCode) && (!mAddedToCount))
  23387. return true;
  23388. BF_ASSERT(mAddedToCount);
  23389. mAddedToCount = false;
  23390. mAwaitingFinish = false;
  23391. mCompiler->mStats.mModulesFinished++;
  23392. if (HasCompiledOutput())
  23393. {
  23394. BF_ASSERT(!mBfIRBuilder->mIgnoreWrites);
  23395. DbgFinish();
  23396. if (mAwaitingInitFinish)
  23397. FinishInit();
  23398. for (auto ownedTypeInst : mOwnedTypeInstances)
  23399. {
  23400. // Generate dbg info and add global variables if we haven't already
  23401. mBfIRBuilder->PopulateType(ownedTypeInst);
  23402. }
  23403. if (mBfIRBuilder->DbgHasInfo())
  23404. {
  23405. mBfIRBuilder->DbgFinalize();
  23406. }
  23407. String objOutputPath;
  23408. String irOutputPath;
  23409. mIsModuleMutable = false;
  23410. //mOutFileNames.Clear();
  23411. BF_ASSERT(((int)mOutFileNames.size() >= mExtensionCount) || (mParentModule != NULL));
  23412. bool writeModule = mBfIRBuilder->HasExports();
  23413. String outputPath;
  23414. BfCodeGenOptions codeGenOptions = mProject->mCodeGenOptions;
  23415. auto& compilerOpts = mCompiler->mOptions;
  23416. codeGenOptions.mSIMDSetting = compilerOpts.mSIMDSetting;
  23417. auto moduleOptions = GetModuleOptions();
  23418. codeGenOptions.mOptLevel = moduleOptions.mOptLevel;
  23419. codeGenOptions.mSIMDSetting = moduleOptions.mSIMDSetting;
  23420. codeGenOptions.mWriteLLVMIR = mCompiler->mOptions.mWriteIR;
  23421. codeGenOptions.mWriteObj = mCompiler->mOptions.mGenerateObj;
  23422. codeGenOptions.mWriteBitcode = mCompiler->mOptions.mGenerateBitcode;
  23423. codeGenOptions.mVirtualMethodOfs = mCompiler->GetVDataPrefixDataCount() + mCompiler->GetDynCastVDataCount() + mCompiler->mMaxInterfaceSlots;
  23424. codeGenOptions.mDynSlotOfs = mSystem->mPtrSize - mCompiler->GetDynCastVDataCount() * 4;
  23425. mCompiler->mStats.mIRBytes += mBfIRBuilder->mStream.GetSize();
  23426. mCompiler->mStats.mConstBytes += mBfIRBuilder->mTempAlloc.GetAllocSize();
  23427. bool allowWriteToLib = true;
  23428. if ((allowWriteToLib) && (codeGenOptions.mOptLevel == BfOptLevel_OgPlus) &&
  23429. (!mCompiler->IsHotCompile()) && (mModuleName != "vdata"))
  23430. {
  23431. codeGenOptions.mWriteToLib = true;
  23432. mWroteToLib = true;
  23433. }
  23434. else
  23435. {
  23436. mWroteToLib = false;
  23437. }
  23438. for (int fileIdx = 0; fileIdx <= mExtensionCount; fileIdx++)
  23439. {
  23440. outputPath = mModuleName;
  23441. outputPath = mCompiler->mOutputDirectory + "/" + mProject->mName + "/" + outputPath;
  23442. BfModuleFileName moduleFileName;
  23443. if (mParentModule != NULL)
  23444. {
  23445. for (auto&& checkPair : mParentModule->mSpecializedMethodModules)
  23446. {
  23447. if (checkPair.mValue == this)
  23448. moduleFileName.mProjects = checkPair.mKey;
  23449. }
  23450. }
  23451. moduleFileName.mProjects.Add(mProject);
  23452. if (fileIdx > 0)
  23453. outputPath += StrFormat("@%d", fileIdx + 1);
  23454. if (mCompiler->mOptions.mWriteIR)
  23455. irOutputPath = outputPath + ".ll";
  23456. if (mCompiler->mOptions.mGenerateObj)
  23457. {
  23458. objOutputPath = outputPath + BF_OBJ_EXT;
  23459. moduleFileName.mFileName = objOutputPath;
  23460. }
  23461. else if (mCompiler->mOptions.mWriteIR)
  23462. {
  23463. moduleFileName.mFileName = irOutputPath;
  23464. }
  23465. else if ((!mCompiler->mOptions.mGenerateObj) && (!mCompiler->mOptions.mGenerateBitcode) && (!mCompiler->mOptions.mWriteIR))
  23466. {
  23467. BFMODULE_FATAL(this, "Neither obj nor IR specified");
  23468. }
  23469. moduleFileName.mModuleWritten = writeModule;
  23470. moduleFileName.mWroteToLib = mWroteToLib;
  23471. if (!mOutFileNames.Contains(moduleFileName))
  23472. mOutFileNames.Add(moduleFileName);
  23473. }
  23474. if (mCompiler->IsHotCompile())
  23475. {
  23476. codeGenOptions.mIsHotCompile = true;
  23477. if (mParentModule != NULL)
  23478. mParentModule->mHadHotObjectWrites = true;
  23479. mHadHotObjectWrites = true;
  23480. }
  23481. //TODO: Testing VDATA
  23482. /*if (mModuleName == "vdata")
  23483. {
  23484. codeGenOptions.mOptLevel = 4;
  23485. }*/
  23486. codeGenOptions.GenerateHash();
  23487. BP_ZONE("BfModule::Finish.WriteObjectFile");
  23488. if ((writeModule) && (!mBfIRBuilder->mIgnoreWrites))
  23489. mCompiler->mCodeGen.WriteObjectFile(this, outputPath, codeGenOptions);
  23490. mLastModuleWrittenRevision = mCompiler->mRevision;
  23491. }
  23492. else
  23493. {
  23494. for (auto type : mOwnedTypeInstances)
  23495. {
  23496. BF_ASSERT((!type->IsIncomplete()) || (type->IsSpecializedByAutoCompleteMethod()));
  23497. }
  23498. }
  23499. for (auto& specModulePair : mSpecializedMethodModules)
  23500. {
  23501. auto specModule = specModulePair.mValue;
  23502. if ((specModule->mIsModuleMutable) && (!specModule->mAwaitingFinish))
  23503. {
  23504. BfLogSysM(" Mutable spec module remaining: %p\n", specModule);
  23505. }
  23506. }
  23507. CleanupFileInstances();
  23508. // We can't ClearModuleData here because we need the mSpecializedMethodModules to remain valid until we Finish them too
  23509. return true;
  23510. }
  23511. void BfModule::ReportMemory(MemReporter* memReporter)
  23512. {
  23513. memReporter->Add(sizeof(BfModule));
  23514. if (mBfIRBuilder != NULL)
  23515. {
  23516. memReporter->BeginSection("IRBuilder_ConstData");
  23517. memReporter->Add("Used", mBfIRBuilder->mTempAlloc.GetAllocSize());
  23518. memReporter->Add("Unused", mBfIRBuilder->mTempAlloc.GetTotalAllocSize() - mBfIRBuilder->mTempAlloc.GetAllocSize());
  23519. memReporter->EndSection();
  23520. memReporter->BeginSection("IRBuilder_BFIR");
  23521. memReporter->Add("Used", (int)(mBfIRBuilder->mStream.GetSize()));
  23522. memReporter->Add("Unused", (int)(mBfIRBuilder->mStream.mPools.size() * ChunkedDataBuffer::ALLOC_SIZE) - mBfIRBuilder->mStream.GetSize());
  23523. memReporter->EndSection();
  23524. memReporter->Add(sizeof(BfIRBuilder));
  23525. }
  23526. memReporter->BeginSection("FileInstanceMap");
  23527. memReporter->AddMap(mFileInstanceMap);
  23528. memReporter->AddMap(mNamedFileInstanceMap);
  23529. memReporter->Add((int)mNamedFileInstanceMap.size() * sizeof(BfFileInstance));
  23530. memReporter->EndSection();
  23531. memReporter->AddVec(mOwnedTypeInstances, false);
  23532. memReporter->AddVec(mSpecializedMethodModules, false);
  23533. memReporter->AddVec(mOutFileNames, false);
  23534. memReporter->AddMap("FuncReferences", mFuncReferences, false);
  23535. memReporter->AddMap(mInterfaceSlotRefs, false);
  23536. memReporter->AddMap(mStaticFieldRefs, false);
  23537. memReporter->AddMap(mClassVDataRefs, false);
  23538. memReporter->AddMap("VDataExtMap", mClassVDataExtRefs, false);
  23539. memReporter->AddMap(mTypeDataRefs, false);
  23540. memReporter->AddMap(mDbgRawAllocDataRefs, false);
  23541. memReporter->AddMap(mDeferredMethodCallData, false);
  23542. memReporter->AddHashSet(mDeferredMethodIds, false);
  23543. memReporter->AddHashSet("ModuleRefs", mModuleRefs, false);
  23544. }
  23545. // ClearModuleData is called immediately after the module is compiled, so don't clear out any data that needs to
  23546. // be transient through the next compile
  23547. void BfModule::ClearModuleData(bool clearTransientData)
  23548. {
  23549. BfLogSysM("ClearModuleData %p\n", this);
  23550. if (mAddedToCount)
  23551. {
  23552. mCompiler->mStats.mModulesFinished++;
  23553. mAddedToCount = false;
  23554. }
  23555. mDICompileUnit = BfIRMDNode();
  23556. if (clearTransientData)
  23557. mIncompleteMethodCount = 0;
  23558. mHasGenericMethods = false;
  23559. // We don't want to clear these because we want it to persist through module extensions-
  23560. // otherwise we may think an extension succeeds even though the base module failed
  23561. //mHadBuildError = false;
  23562. //mHadBuildWarning = false;
  23563. mClassVDataRefs.Clear();
  23564. mClassVDataExtRefs.Clear();
  23565. for (auto& kv : mTypeDataRefs)
  23566. kv.mValue = BfIRValue();
  23567. mStringCharPtrPool.Clear();
  23568. mStringObjectPool.Clear();
  23569. mStaticFieldRefs.Clear();
  23570. BF_ASSERT(!mIgnoreErrors);
  23571. for (auto prevIRBuilder : mPrevIRBuilders)
  23572. delete prevIRBuilder;
  23573. mPrevIRBuilders.Clear();
  23574. for (auto& specPair : mSpecializedMethodModules)
  23575. {
  23576. auto specModule = specPair.mValue;
  23577. specModule->ClearModuleData();
  23578. }
  23579. for (int i = 0; i < BfBuiltInFuncType_Count; i++)
  23580. mBuiltInFuncs[i] = BfIRFunction();
  23581. if (mNextAltModule != NULL)
  23582. mNextAltModule->ClearModuleData();
  23583. BfLogSysM("ClearModuleData. Deleting IRBuilder: %p\n", mBfIRBuilder);
  23584. mIsModuleMutable = false;
  23585. delete mBfIRBuilder;
  23586. mBfIRBuilder = NULL;
  23587. mWantsIRIgnoreWrites = false;
  23588. }
  23589. void BfModule::DisownMethods()
  23590. {
  23591. for (int i = 0; i < BfBuiltInFuncType_Count; i++)
  23592. mBuiltInFuncs[i] = BfIRFunction();
  23593. BfModule* methodModule = this;
  23594. if (mParentModule != NULL)
  23595. methodModule = mParentModule;
  23596. for (auto typeInst : methodModule->mOwnedTypeInstances)
  23597. {
  23598. for (auto& methodGroup : typeInst->mMethodInstanceGroups)
  23599. {
  23600. if (methodGroup.mDefault != NULL)
  23601. {
  23602. if (methodGroup.mDefault->mIRFunction)
  23603. {
  23604. BF_ASSERT(methodGroup.mDefault->mDeclModule != NULL);
  23605. if (methodGroup.mDefault->mDeclModule == this)
  23606. {
  23607. methodGroup.mDefault->mIRFunction = BfIRFunction();
  23608. }
  23609. }
  23610. }
  23611. if (methodGroup.mMethodSpecializationMap != NULL)
  23612. {
  23613. for (auto& mapPair : *methodGroup.mMethodSpecializationMap)
  23614. {
  23615. auto methodInstance = mapPair.mValue;
  23616. if (methodInstance->mDeclModule == this)
  23617. {
  23618. methodInstance->mIRFunction = BfIRFunction();
  23619. }
  23620. }
  23621. }
  23622. }
  23623. }
  23624. }
  23625. void BfModule::ClearModule()
  23626. {
  23627. ClearModuleData();
  23628. DisownMethods();
  23629. for (auto& specPair : mSpecializedMethodModules)
  23630. {
  23631. auto specModule = specPair.mValue;
  23632. specModule->ClearModule();
  23633. }
  23634. if (mNextAltModule != NULL)
  23635. mNextAltModule->ClearModule();
  23636. }