BfModule.cpp 857 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110
  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 <fcntl.h>
  26. #include <time.h>
  27. #pragma warning(pop)
  28. //////////////////////////////////////////////////////////////////////////
  29. static bool gDebugStuff = false;
  30. USING_NS_BF;
  31. //////////////////////////////////////////////////////////////////////////
  32. void BfLocalVariable::Init()
  33. {
  34. if (mResolvedType->IsValuelessType())
  35. {
  36. mAssignedKind = BfLocalVarAssignKind_Unconditional;
  37. return;
  38. }
  39. if (mAssignedKind != BfLocalVarAssignKind_None)
  40. return;
  41. bool isStruct = mResolvedType->IsStruct();
  42. if (mResolvedType->IsRef())
  43. isStruct = mResolvedType->GetUnderlyingType()->IsStruct();
  44. if ((isStruct) || ((mIsThis) && (mResolvedType->IsStructOrStructPtr())))
  45. {
  46. auto resolvedTypeRef = mResolvedType;
  47. if ((resolvedTypeRef->IsPointer()) || (resolvedTypeRef->IsRef()))
  48. resolvedTypeRef = resolvedTypeRef->GetUnderlyingType();
  49. auto typeInstance = resolvedTypeRef->ToTypeInstance();
  50. mUnassignedFieldFlags = (1 << typeInstance->mMergedFieldDataCount) - 1;
  51. if ((mIsThis) && (typeInstance->mBaseType != NULL))
  52. {
  53. // Base ctor is responsible for initializing its own fields
  54. mUnassignedFieldFlags &= ~(((int64)1 << typeInstance->mBaseType->mMergedFieldDataCount) - 1);
  55. }
  56. if (mUnassignedFieldFlags == 0)
  57. mAssignedKind = BfLocalVarAssignKind_Unconditional;
  58. }
  59. else
  60. {
  61. mUnassignedFieldFlags = 1;
  62. }
  63. }
  64. BfLocalMethod::~BfLocalMethod()
  65. {
  66. BfLogSys(mSystem, "~BfLocalMethod %p\n", this);
  67. if (mMethodDeclaration != NULL)
  68. {
  69. mSource->mRefCount--;
  70. BF_ASSERT(mSource->mRefCount >= 0);
  71. }
  72. delete mMethodInstanceGroup;
  73. delete mMethodDef;
  74. }
  75. void BfLocalMethod::Dispose()
  76. {
  77. if (mMethodInstanceGroup == NULL)
  78. return;
  79. if (mMethodInstanceGroup->mDefault != NULL)
  80. mMethodInstanceGroup->mDefault->Dispose();
  81. if (mMethodInstanceGroup->mMethodSpecializationMap != NULL)
  82. {
  83. for (auto& kv : *mMethodInstanceGroup->mMethodSpecializationMap)
  84. kv.mValue->Dispose();
  85. }
  86. }
  87. void BfDeferredLocalAssignData::ExtendFrom(BfDeferredLocalAssignData* outerLocalAssignData, bool doChain)
  88. {
  89. mIsChained = doChain;
  90. if (outerLocalAssignData == NULL)
  91. return;
  92. mChainedAssignData = outerLocalAssignData;
  93. if (!doChain)
  94. {
  95. outerLocalAssignData->BreakExtendChain();
  96. mAssignedLocals = outerLocalAssignData->mAssignedLocals;
  97. }
  98. mVarIdBarrier = outerLocalAssignData->mVarIdBarrier;
  99. }
  100. // The "extend chain" is broken when we have a conditional where the variable may not be defined after the block.
  101. // IE: "a" will be defined after the following, but "b" will not necessarily be defined.
  102. // if ((GetValue(out a)) && (GetValue(out b)) {}
  103. void BfDeferredLocalAssignData::BreakExtendChain()
  104. {
  105. if (!mIsChained)
  106. return;
  107. mIsChained = false;
  108. if (mChainedAssignData == NULL)
  109. return;
  110. mChainedAssignData->BreakExtendChain();
  111. mAssignedLocals = mChainedAssignData->mAssignedLocals;
  112. }
  113. void BfDeferredLocalAssignData::SetIntersection(const BfDeferredLocalAssignData& otherLocalAssignData)
  114. {
  115. BreakExtendChain();
  116. for (int i = 0; i < (int)mAssignedLocals.size(); )
  117. {
  118. auto& local = mAssignedLocals[i];
  119. bool wantRemove = true;
  120. bool foundOtherFields = false;
  121. for (auto& otherLocalAssignData : otherLocalAssignData.mAssignedLocals)
  122. {
  123. if (otherLocalAssignData.mLocalVar == local.mLocalVar)
  124. {
  125. if ((otherLocalAssignData.mLocalVarField == local.mLocalVarField) || (otherLocalAssignData.mLocalVarField == -1))
  126. {
  127. if (otherLocalAssignData.mAssignKind == BfLocalVarAssignKind_Conditional)
  128. local.mAssignKind = BfLocalVarAssignKind_Conditional;
  129. wantRemove = false;
  130. }
  131. else
  132. foundOtherFields = true;
  133. }
  134. }
  135. if ((wantRemove) && (foundOtherFields))
  136. {
  137. for (auto& otherLocalAssignData : otherLocalAssignData.mAssignedLocals)
  138. {
  139. if (otherLocalAssignData.mLocalVar == local.mLocalVar)
  140. {
  141. mAssignedLocals.Add(otherLocalAssignData);
  142. }
  143. }
  144. }
  145. if (wantRemove)
  146. {
  147. mAssignedLocals.RemoveAt(i);
  148. }
  149. else
  150. i++;
  151. }
  152. mHadFallthrough = mHadFallthrough && otherLocalAssignData.mHadFallthrough;
  153. }
  154. void BfDeferredLocalAssignData::Validate() const
  155. {
  156. for (auto var : mAssignedLocals)
  157. {
  158. BF_ASSERT((uintptr)var.mLocalVar->mName.length() < 100000);
  159. }
  160. }
  161. void BfDeferredLocalAssignData::SetUnion(const BfDeferredLocalAssignData& otherLocalAssignData)
  162. {
  163. BreakExtendChain();
  164. Validate();
  165. otherLocalAssignData.Validate();
  166. auto otherItr = otherLocalAssignData.mAssignedLocals.begin();
  167. while (otherItr != otherLocalAssignData.mAssignedLocals.end())
  168. {
  169. if (!mAssignedLocals.Contains(*otherItr))
  170. mAssignedLocals.push_back(*otherItr);
  171. ++otherItr;
  172. }
  173. mHadFallthrough = mHadFallthrough || otherLocalAssignData.mHadFallthrough;
  174. }
  175. BfMethodState::~BfMethodState()
  176. {
  177. BF_ASSERT(mPendingNullConditional == NULL);
  178. if (mPrevMethodState != NULL)
  179. {
  180. BF_ASSERT(mCurAccessId == 1);
  181. BF_ASSERT(mCurLocalVarId <= 0);
  182. }
  183. for (auto local : mLocals)
  184. delete local;
  185. for (auto& kv : mLambdaCache)
  186. delete kv.mValue;
  187. }
  188. BfMethodState* BfMethodState::GetMethodStateForLocal(BfLocalVariable* localVar)
  189. {
  190. auto checkMethodState = this;
  191. while (checkMethodState != NULL)
  192. {
  193. if ((localVar->mLocalVarIdx < checkMethodState->mLocals.size()) &&
  194. (checkMethodState->mLocals[localVar->mLocalVarIdx] == localVar))
  195. return checkMethodState;
  196. checkMethodState = checkMethodState->mPrevMethodState;
  197. }
  198. BF_FATAL("Failed to find method state for localvar");
  199. return NULL;
  200. }
  201. void BfMethodState::LocalDefined(BfLocalVariable* localVar, int fieldIdx, BfLocalVarAssignKind assignKind, bool isFromDeferredAssignData)
  202. {
  203. auto localVarMethodState = GetMethodStateForLocal(localVar);
  204. if (localVarMethodState != this)
  205. {
  206. return;
  207. }
  208. if (localVar->mAssignedKind == BfLocalVarAssignKind_None)
  209. {
  210. BfDeferredLocalAssignData* ifDeferredLocalAssignData = NULL;
  211. // 'a' is always defined, but 'b' isn't:
  212. // if (Check(out a) || Check(out b)) { } int z = a;
  213. auto deferredLocalAssignData = mDeferredLocalAssignData;
  214. if ((deferredLocalAssignData != NULL) &&
  215. (deferredLocalAssignData->mIsIfCondition) &&
  216. (!deferredLocalAssignData->mIfMayBeSkipped))
  217. {
  218. ifDeferredLocalAssignData = deferredLocalAssignData;
  219. deferredLocalAssignData = deferredLocalAssignData->mChainedAssignData;
  220. }
  221. while ((deferredLocalAssignData != NULL) &&
  222. ((deferredLocalAssignData->mIsChained) || (deferredLocalAssignData->mIsUnconditional)))
  223. deferredLocalAssignData = deferredLocalAssignData->mChainedAssignData;
  224. if (assignKind == BfLocalVarAssignKind_None)
  225. assignKind = ((deferredLocalAssignData != NULL) && (deferredLocalAssignData->mLeftBlock)) ? BfLocalVarAssignKind_Conditional : BfLocalVarAssignKind_Unconditional;
  226. if (localVar->mAssignedKind >= assignKind)
  227. {
  228. // Leave it alone
  229. }
  230. else if ((deferredLocalAssignData == NULL) || (localVar->mLocalVarId >= deferredLocalAssignData->mVarIdBarrier))
  231. {
  232. if (fieldIdx >= 0)
  233. {
  234. localVar->mUnassignedFieldFlags &= ~((int64)1 << fieldIdx);
  235. if (localVar->mUnassignedFieldFlags == 0)
  236. {
  237. if (localVar->mAssignedKind == BfLocalVarAssignKind_None)
  238. localVar->mAssignedKind = assignKind;
  239. }
  240. }
  241. else
  242. {
  243. localVar->mAssignedKind = assignKind;
  244. }
  245. }
  246. else
  247. {
  248. BF_ASSERT(deferredLocalAssignData->mVarIdBarrier != -1);
  249. BfAssignedLocal defineVal = {localVar, fieldIdx, assignKind};
  250. if (!deferredLocalAssignData->Contains(defineVal))
  251. deferredLocalAssignData->mAssignedLocals.push_back(defineVal);
  252. if (ifDeferredLocalAssignData != NULL)
  253. {
  254. if (!ifDeferredLocalAssignData->Contains(defineVal))
  255. ifDeferredLocalAssignData->mAssignedLocals.push_back(defineVal);
  256. }
  257. }
  258. }
  259. localVar->mWrittenToId = GetRootMethodState()->mCurAccessId++;
  260. }
  261. void BfMethodState::ApplyDeferredLocalAssignData(const BfDeferredLocalAssignData& deferredLocalAssignData)
  262. {
  263. BF_ASSERT(&deferredLocalAssignData != mDeferredLocalAssignData);
  264. for (auto& assignedLocal : deferredLocalAssignData.mAssignedLocals)
  265. {
  266. LocalDefined(assignedLocal.mLocalVar, assignedLocal.mLocalVarField, assignedLocal.mAssignKind, true);
  267. }
  268. }
  269. void BfMethodState::Reset()
  270. {
  271. mHeadScope.mDeferredCallEntries.DeleteAll();
  272. }
  273. //////////////////////////////////////////////////////////////////////////
  274. void BfAmbiguityContext::Add(int id, BfTypeInterfaceEntry* interfaceEntry, int methodIdx, BfMethodInstance* candidateA, BfMethodInstance* candidateB)
  275. {
  276. Entry* entry = NULL;
  277. if (mEntries.TryAdd(id, NULL, &entry))
  278. {
  279. entry->mInterfaceEntry = interfaceEntry;
  280. entry->mMethodIdx = methodIdx;
  281. }
  282. if (!entry->mCandidates.Contains(candidateA))
  283. entry->mCandidates.push_back(candidateA);
  284. if (!entry->mCandidates.Contains(candidateB))
  285. entry->mCandidates.push_back(candidateB);
  286. }
  287. void BfAmbiguityContext::Remove(int id)
  288. {
  289. mEntries.Remove(id);
  290. }
  291. void BfAmbiguityContext::Finish()
  292. {
  293. for (auto& entryPair : mEntries)
  294. {
  295. int id = entryPair.mKey;
  296. auto entry = &entryPair.mValue;
  297. if (id >= 0)
  298. {
  299. auto declMethodInstance = mTypeInstance->mVirtualMethodTable[id].mDeclaringMethod;
  300. auto error = mModule->Fail(StrFormat("Method '%s' has ambiguous overrides", mModule->MethodToString(declMethodInstance).c_str()), declMethodInstance->mMethodDef->GetRefNode());
  301. for (auto candidate : entry->mCandidates)
  302. {
  303. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' is a candidate", mModule->MethodToString(candidate).c_str()), candidate->mMethodDef->GetRefNode());
  304. }
  305. }
  306. else
  307. {
  308. auto iMethodInst = entry->mInterfaceEntry->mInterfaceType->mMethodInstanceGroups[entry->mMethodIdx].mDefault;
  309. auto error = mModule->Fail(StrFormat("Interface method '%s' has ambiguous implementations", mModule->MethodToString(iMethodInst).c_str()), entry->mInterfaceEntry->mDeclaringType->GetRefNode());
  310. for (auto candidate : entry->mCandidates)
  311. {
  312. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' is a candidate", mModule->MethodToString(candidate).c_str()), candidate->mMethodDef->GetRefNode());
  313. }
  314. }
  315. }
  316. }
  317. //////////////////////////////////////////////////////////////////////////
  318. class HasAppendAllocVisitor : BfElementVisitor
  319. {
  320. public:
  321. bool mHas;
  322. public:
  323. HasAppendAllocVisitor()
  324. {
  325. mHas = false;
  326. }
  327. void Visit(BfObjectCreateExpression* objCreateExpr)
  328. {
  329. if (auto newToken = BfNodeDynCast<BfTokenNode>(objCreateExpr->mNewNode))
  330. {
  331. if (newToken->GetToken() == BfToken_Append)
  332. {
  333. mHas = true;
  334. }
  335. }
  336. }
  337. bool HasAppendAlloc(BfAstNode* node)
  338. {
  339. mHas = false;
  340. VisitChild(node);
  341. return mHas;
  342. }
  343. };
  344. class AppendAllocVisitor : public BfStructuralVisitor
  345. {
  346. public:
  347. BfModule* mModule;
  348. HasAppendAllocVisitor mHasAppendAllocVisitor;
  349. BfTypedValue mConstAccum;
  350. bool mFailed;
  351. bool mIsFirstConstPass;
  352. int mCurAppendAlign;
  353. public:
  354. AppendAllocVisitor()
  355. {
  356. mFailed = false;
  357. mIsFirstConstPass = false;
  358. mCurAppendAlign = 1;
  359. }
  360. void EmitAppendAlign(int align, int sizeMultiple = 0)
  361. {
  362. BF_ASSERT(align > 0);
  363. if (mIsFirstConstPass)
  364. mModule->mCurMethodInstance->mAppendAllocAlign = BF_MAX((int)mModule->mCurMethodInstance->mAppendAllocAlign, align);
  365. if (sizeMultiple == 0)
  366. sizeMultiple = align;
  367. if (mCurAppendAlign == 0)
  368. mCurAppendAlign = sizeMultiple;
  369. else
  370. {
  371. if (sizeMultiple % align == 0)
  372. mCurAppendAlign = align;
  373. else
  374. mCurAppendAlign = sizeMultiple % align;
  375. }
  376. BF_ASSERT(mCurAppendAlign > 0);
  377. if (mConstAccum)
  378. {
  379. auto constant = mModule->mBfIRBuilder->GetConstant(mConstAccum.mValue);
  380. if (constant != NULL)
  381. mConstAccum.mValue = mModule->GetConstValue(BF_ALIGN(constant->mInt64, align));
  382. else
  383. BF_ASSERT(mIsFirstConstPass);
  384. return;
  385. }
  386. mModule->EmitAppendAlign(align, sizeMultiple);
  387. }
  388. void Visit(BfAstNode* astNode) override
  389. {
  390. mModule->VisitChild(astNode);
  391. }
  392. void DoObjectCreate(BfObjectCreateExpression* objCreateExpr, BfVariableDeclaration* variableDecl)
  393. {
  394. if (auto newToken = BfNodeDynCast<BfTokenNode>(objCreateExpr->mNewNode))
  395. {
  396. if (newToken->GetToken() == BfToken_Append)
  397. {
  398. //auto variableDecl = BfNodeDynCast<BfVariableDeclaration>(objCreateExpr->mParent);
  399. auto accumValuePtr = mModule->mCurMethodState->mRetVal.mValue;
  400. auto intPtrType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  401. BfArrayType* arrayType = NULL;
  402. bool isArrayAlloc = false;
  403. bool isRawArrayAlloc = objCreateExpr->mStarToken != NULL;
  404. SizedArray<BfIRValue, 2> dimLengthVals;
  405. BfType* origResolvedTypeRef = NULL;
  406. if (auto dotTypeRef = BfNodeDynCast<BfDotTypeReference>(objCreateExpr->mTypeRef))
  407. {
  408. if (variableDecl != NULL)
  409. {
  410. origResolvedTypeRef = mModule->ResolveTypeRef(variableDecl->mTypeRef, BfPopulateType_Data, BfResolveTypeRefFlag_NoResolveGenericParam);
  411. if (origResolvedTypeRef->IsObject())
  412. {
  413. if (origResolvedTypeRef->IsArray())
  414. {
  415. arrayType = (BfArrayType*)origResolvedTypeRef;
  416. origResolvedTypeRef = origResolvedTypeRef->GetUnderlyingType();
  417. isArrayAlloc = true;
  418. }
  419. }
  420. else if (origResolvedTypeRef->IsPointer())
  421. {
  422. origResolvedTypeRef = origResolvedTypeRef->GetUnderlyingType();
  423. }
  424. }
  425. }
  426. else if (auto arrayTypeRef = BfNodeDynCast<BfArrayTypeRef>(objCreateExpr->mTypeRef))
  427. {
  428. isArrayAlloc = true;
  429. bool handled = false;
  430. if (auto dotTypeRef = BfNodeDynCast<BfDotTypeReference>(arrayTypeRef->mElementType))
  431. {
  432. if (variableDecl->mTypeRef != NULL)
  433. {
  434. auto variableType = mModule->ResolveTypeRef(variableDecl->mTypeRef);
  435. if (variableType != NULL)
  436. {
  437. if (variableType->IsArray())
  438. origResolvedTypeRef = variableType->GetUnderlyingType();
  439. }
  440. handled = true;
  441. }
  442. }
  443. if (!handled)
  444. {
  445. origResolvedTypeRef = mModule->ResolveTypeRef(arrayTypeRef->mElementType);
  446. }
  447. if (origResolvedTypeRef == NULL)
  448. {
  449. mModule->AssertErrorState();
  450. return;
  451. }
  452. int dimensions = 1;
  453. if (arrayTypeRef->mParams.size() != 0)
  454. {
  455. auto intType = mModule->ResolveTypeDef(mModule->mSystem->mTypeIntPtr);
  456. for (auto arg : arrayTypeRef->mParams)
  457. {
  458. if (auto tokenNode = BfNodeDynCastExact<BfTokenNode>(arg))
  459. {
  460. if (tokenNode->GetToken() == BfToken_Comma)
  461. {
  462. if (isRawArrayAlloc)
  463. {
  464. mModule->Fail("Sized arrays cannot be multidimensional", tokenNode);
  465. continue;
  466. }
  467. dimensions++;
  468. continue;
  469. }
  470. }
  471. auto expr = BfNodeDynCast<BfExpression>(arg);
  472. if ((isRawArrayAlloc) && (!dimLengthVals.IsEmpty()))
  473. {
  474. mModule->CreateValueFromExpression(expr, intType);
  475. continue;
  476. }
  477. BfTypedValue dimLength;
  478. if (expr == NULL)
  479. {
  480. // Not specified
  481. dimLengthVals.push_back(BfIRValue());
  482. continue;
  483. }
  484. if (arg != NULL)
  485. dimLength = mModule->CreateValueFromExpression(expr, intType);
  486. if (!dimLength)
  487. {
  488. dimLength = mModule->GetDefaultTypedValue(intType);
  489. }
  490. dimLengthVals.push_back(dimLength.mValue);
  491. }
  492. }
  493. if (!isRawArrayAlloc)
  494. arrayType = mModule->CreateArrayType(origResolvedTypeRef, dimensions);
  495. }
  496. if (origResolvedTypeRef == NULL)
  497. origResolvedTypeRef = mModule->ResolveTypeRef(objCreateExpr->mTypeRef, BfPopulateType_Data, BfResolveTypeRefFlag_NoResolveGenericParam);
  498. if (origResolvedTypeRef == NULL)
  499. {
  500. mModule->AssertErrorState();
  501. return;
  502. }
  503. bool isGenericParam = origResolvedTypeRef->IsGenericParam();
  504. auto resolvedTypeRef = origResolvedTypeRef;
  505. auto resultType = resolvedTypeRef;
  506. BfIRValue sizeValue;
  507. int curAlign = 0;
  508. if (isArrayAlloc)
  509. {
  510. int dimensions = 1;
  511. if (arrayType != NULL)
  512. dimensions = arrayType->mDimensions;
  513. bool sizeFailed = false;
  514. //
  515. {
  516. BfAstNode* initNode = objCreateExpr;
  517. for (int dim = 0; dim < dimensions; dim++)
  518. {
  519. BfAstNode* nextInitNode = NULL;
  520. int dimSize = -1;
  521. if (initNode == objCreateExpr)
  522. {
  523. dimSize = objCreateExpr->mArguments.size();
  524. if (!objCreateExpr->mArguments.IsEmpty())
  525. nextInitNode = objCreateExpr->mArguments[0];
  526. }
  527. else if (auto tupleNode = BfNodeDynCast<BfTupleExpression>(initNode))
  528. {
  529. dimSize = (int)tupleNode->mCommas.size() + 1;
  530. }
  531. if (dimSize >= 0)
  532. {
  533. if (dim >= dimLengthVals.size())
  534. dimLengthVals.Add(mModule->GetConstValue(dimSize));
  535. }
  536. else
  537. {
  538. sizeFailed = true;
  539. }
  540. }
  541. }
  542. BfIRValue allocCount;
  543. if (!sizeFailed)
  544. {
  545. if (!dimLengthVals.IsEmpty())
  546. {
  547. allocCount = dimLengthVals[0];
  548. for (int dim = 1; dim < (int)dimLengthVals.size(); dim++)
  549. allocCount = mModule->mBfIRBuilder->CreateMul(allocCount, dimLengthVals[dim]);
  550. }
  551. }
  552. if (!allocCount)
  553. {
  554. mFailed = true;
  555. if (!mIsFirstConstPass)
  556. {
  557. if (!mConstAccum)
  558. mModule->Fail("Unable to determine append alloc size", objCreateExpr->mNewNode);
  559. return;
  560. }
  561. }
  562. mModule->PopulateType(resultType);
  563. if (isRawArrayAlloc)
  564. {
  565. curAlign = resultType->mAlign;
  566. EmitAppendAlign(resultType->mAlign);
  567. sizeValue = mModule->mBfIRBuilder->CreateMul(mModule->GetConstValue(resultType->GetStride()), allocCount);
  568. }
  569. else
  570. {
  571. if (arrayType == NULL)
  572. arrayType = mModule->CreateArrayType(resultType, 1);
  573. // Array is a special case where the total size isn't aligned with mAlign
  574. // since we add arbitrary elements to the end without padding the end to align
  575. EmitAppendAlign(arrayType->mAlign, resultType->mAlign);
  576. curAlign = arrayType->mAlign;
  577. auto firstElementField = &arrayType->mFieldInstances.back();
  578. int arrayClassSize = arrayType->mInstSize - firstElementField->mDataSize;
  579. sizeValue = mModule->GetConstValue(arrayClassSize);
  580. BfIRValue elementDataSize = mModule->mBfIRBuilder->CreateMul(mModule->GetConstValue(resultType->GetStride()), allocCount);
  581. sizeValue = mModule->mBfIRBuilder->CreateAdd(sizeValue, elementDataSize);
  582. }
  583. }
  584. else
  585. {
  586. auto typeInst = resultType->ToTypeInstance();
  587. if (typeInst != NULL)
  588. {
  589. curAlign = typeInst->mInstAlign;
  590. EmitAppendAlign(typeInst->mInstAlign, typeInst->mInstSize);
  591. sizeValue = mModule->GetConstValue(typeInst->mInstSize);
  592. }
  593. else
  594. {
  595. curAlign = resultType->mAlign;
  596. EmitAppendAlign(resultType->mAlign, resultType->mSize);
  597. sizeValue = mModule->GetConstValue(resultType->mSize);
  598. }
  599. BfTypedValue emtpyThis(mModule->mBfIRBuilder->GetFakeVal(), resultType, (typeInst == NULL) || (typeInst->IsComposite()));
  600. BfExprEvaluator exprEvaluator(mModule);
  601. SetAndRestoreValue<bool> prevNoBind(exprEvaluator.mNoBind, exprEvaluator.mNoBind || isGenericParam);
  602. BfFunctionBindResult bindResult;
  603. bindResult.mWantsArgs = true;
  604. exprEvaluator.mFunctionBindResult = &bindResult;
  605. SizedArray<BfExpression*, 8> copiedArgs;
  606. for (BfExpression* arg : objCreateExpr->mArguments)
  607. copiedArgs.push_back(arg);
  608. BfSizedArray<BfExpression*> sizedArgExprs(copiedArgs);
  609. BfResolvedArgs argValues(&sizedArgExprs);
  610. if (typeInst != NULL)
  611. {
  612. exprEvaluator.ResolveArgValues(argValues);
  613. exprEvaluator.MatchConstructor(objCreateExpr->mTypeRef, objCreateExpr, emtpyThis, typeInst, argValues, false, true);
  614. }
  615. exprEvaluator.mFunctionBindResult = NULL;
  616. if (bindResult.mMethodInstance != NULL)
  617. {
  618. if (bindResult.mMethodInstance->mMethodDef->mHasAppend)
  619. {
  620. auto calcAppendArgs = bindResult.mIRArgs;
  621. BF_ASSERT(calcAppendArgs[0].IsFake());
  622. calcAppendArgs.RemoveRange(0, 2); // Remove 'this' and 'appendIdx'
  623. auto calcAppendMethodModule = mModule->GetMethodInstanceAtIdx(bindResult.mMethodInstance->GetOwner(), bindResult.mMethodInstance->mMethodDef->mIdx + 1, BF_METHODNAME_CALCAPPEND);
  624. auto subDependSize = mModule->TryConstCalcAppend(calcAppendMethodModule.mMethodInstance, calcAppendArgs);
  625. if (calcAppendMethodModule.mMethodInstance->mAppendAllocAlign > 0)
  626. {
  627. EmitAppendAlign(calcAppendMethodModule.mMethodInstance->mAppendAllocAlign);
  628. BF_ASSERT(calcAppendMethodModule.mMethodInstance->mEndingAppendAllocAlign > -1);
  629. mModule->mCurMethodState->mCurAppendAlign = BF_MAX(calcAppendMethodModule.mMethodInstance->mEndingAppendAllocAlign, 0);
  630. }
  631. curAlign = std::max(curAlign, (int)calcAppendMethodModule.mMethodInstance->mAppendAllocAlign);
  632. if ((!subDependSize) && (!mConstAccum))
  633. {
  634. BF_ASSERT(calcAppendMethodModule.mFunc);
  635. subDependSize = exprEvaluator.CreateCall(objCreateExpr, calcAppendMethodModule.mMethodInstance, calcAppendMethodModule.mFunc, false, calcAppendArgs);
  636. BF_ASSERT(subDependSize.mType == mModule->GetPrimitiveType(BfTypeCode_IntPtr));
  637. }
  638. if (subDependSize)
  639. sizeValue = mModule->mBfIRBuilder->CreateAdd(sizeValue, subDependSize.mValue);
  640. else
  641. mFailed = true;
  642. }
  643. }
  644. }
  645. if (sizeValue)
  646. {
  647. if (mConstAccum)
  648. {
  649. if (!sizeValue.IsConst())
  650. {
  651. mFailed = true;
  652. if (!mIsFirstConstPass)
  653. return;
  654. }
  655. mConstAccum.mValue = mModule->mBfIRBuilder->CreateAdd(sizeValue, mConstAccum.mValue);
  656. }
  657. else
  658. {
  659. auto prevVal = mModule->mBfIRBuilder->CreateLoad(accumValuePtr);
  660. auto addedVal = mModule->mBfIRBuilder->CreateAdd(sizeValue, prevVal);
  661. mModule->mBfIRBuilder->CreateStore(addedVal, accumValuePtr);
  662. }
  663. }
  664. }
  665. }
  666. }
  667. void Visit(BfObjectCreateExpression* objCreateExpr) override
  668. {
  669. DoObjectCreate(objCreateExpr, NULL);
  670. }
  671. void Visit(BfVariableDeclaration* varDecl) override
  672. {
  673. if (mHasAppendAllocVisitor.HasAppendAlloc(varDecl))
  674. {
  675. if (auto objectCreateExpr = BfNodeDynCast<BfObjectCreateExpression>(varDecl->mInitializer))
  676. DoObjectCreate(objectCreateExpr, varDecl);
  677. else
  678. VisitChild(varDecl->mInitializer);
  679. if (varDecl->mNameNode != NULL)
  680. {
  681. BfLocalVariable* localDef = new BfLocalVariable();
  682. localDef->mName = varDecl->mNameNode->ToString();
  683. localDef->mNameNode = BfNodeDynCast<BfIdentifierNode>(varDecl->mNameNode);
  684. localDef->mResolvedType = mModule->GetPrimitiveType(BfTypeCode_None);
  685. localDef->mIsReadOnly = true;
  686. localDef->mParamFailed = true;
  687. localDef->mReadFromId = 0;
  688. mModule->AddLocalVariableDef(localDef);
  689. }
  690. }
  691. else
  692. {
  693. mModule->Visit(varDecl);
  694. }
  695. }
  696. void Visit(BfExpressionStatement* exprStatement) override
  697. {
  698. VisitChild(exprStatement->mExpression);
  699. }
  700. // void Visit(BfIfStatement* ifStmt) override
  701. // {
  702. // mModule->DoIfStatement(ifStmt,
  703. // mHasAppendAllocVisitor.HasAppendAlloc(ifStmt->mTrueStatement),
  704. // mHasAppendAllocVisitor.HasAppendAlloc(ifStmt->mFalseStatement));
  705. // }
  706. void Visit(BfBlock* block) override
  707. {
  708. if (!mHasAppendAllocVisitor.HasAppendAlloc(block))
  709. return;
  710. int appendAllocIdx = -1;
  711. for (int childIdx = block->mChildArr.mSize - 1; childIdx >= 0; childIdx--)
  712. {
  713. auto child = block->mChildArr.mVals[childIdx];
  714. if (mHasAppendAllocVisitor.HasAppendAlloc(child))
  715. {
  716. for (int emitIdx = 0; emitIdx <= childIdx; emitIdx++)
  717. {
  718. auto emitChild = block->mChildArr.mVals[emitIdx];
  719. mModule->UpdateSrcPos(emitChild);
  720. VisitChild(emitChild);
  721. if ((mFailed) && (!mIsFirstConstPass))
  722. break;
  723. }
  724. break;
  725. }
  726. }
  727. }
  728. };
  729. //////////////////////////////////////////////////////////////////////////
  730. BfModule* gLastCreatedModule = NULL;
  731. BfModule::BfModule(BfContext* context, const StringImpl& moduleName)
  732. {
  733. BfLogSys(context->mSystem, "BfModule::BFModule %p %s\n", this, moduleName.c_str());
  734. gLastCreatedModule = this;
  735. mContext = context;
  736. mModuleName = moduleName;
  737. if (!moduleName.empty())
  738. mContext->mUsedModuleNames.Add(ToUpper(moduleName));
  739. mAddedToCount = false;
  740. mParentModule = NULL;
  741. mNextAltModule = NULL;
  742. mBfIRBuilder = NULL;
  743. mWantsIRIgnoreWrites = false;
  744. mModuleOptions = NULL;
  745. mLastUsedRevision = -1;
  746. mUsedSlotCount = -1;
  747. mIsReified = true;
  748. mGeneratesCode = true;
  749. mReifyQueued = false;
  750. mIsSpecialModule = false;
  751. mIsComptimeModule = false;
  752. mIsScratchModule = false;
  753. mIsSpecializedMethodModuleRoot = false; // There may be mNextAltModules extending from this
  754. mHadBuildError = false;
  755. mHadBuildWarning = false;
  756. mIgnoreErrors = false;
  757. mHadIgnoredError = false;
  758. mIgnoreWarnings = false;
  759. mReportErrors = true;
  760. mIsInsideAutoComplete = false;
  761. mIsDeleting = false;
  762. mSkipInnerLookup = false;
  763. mIsHotModule = false;
  764. mSetIllegalSrcPosition = false;
  765. mNoResolveGenericParams = false;
  766. mWroteToLib = false;
  767. mContext = context;
  768. mCompiler = context->mCompiler;
  769. mSystem = mCompiler->mSystem;
  770. mProject = NULL;
  771. mCurMethodState = NULL;
  772. mAttributeState = NULL;
  773. mCurLocalMethodId = 0;
  774. mParentNodeEntry = NULL;
  775. mRevision = -1;
  776. mRebuildIdx = 0;
  777. mLastModuleWrittenRevision = 0;
  778. mIsModuleMutable = false;
  779. mExtensionCount = 0;
  780. mIncompleteMethodCount = 0;
  781. mOnDemandMethodCount = 0;
  782. mHasGenericMethods = false;
  783. mCurMethodInstance = NULL;
  784. mCurTypeInstance = NULL;
  785. mAwaitingInitFinish = false;
  786. mAwaitingFinish = false;
  787. mHasFullDebugInfo = false;
  788. mHadHotObjectWrites = false;
  789. for (int i = 0; i < BfBuiltInFuncType_Count; i++)
  790. mBuiltInFuncs[i] = BfIRFunction();
  791. BfLogSysM("Creating module %p: %s Reified: %d ResolveOnly: %d\n", this, mModuleName.c_str(), mIsReified, mCompiler->mIsResolveOnly);
  792. }
  793. void BfReportMemory();
  794. BfModule::~BfModule()
  795. {
  796. BfLogSysM("Deleting module %p: %s \n", this, mModuleName.c_str());
  797. if (!mIsDeleting)
  798. RemoveModuleData();
  799. }
  800. void BfModule::RemoveModuleData()
  801. {
  802. BF_ASSERT(!mIsDeleting);
  803. if (!mModuleName.empty())
  804. {
  805. // Note: module names not necessarily unique
  806. mContext->mUsedModuleNames.Remove(ToUpper(mModuleName));
  807. }
  808. CleanupFileInstances();
  809. delete mBfIRBuilder;
  810. mBfIRBuilder = NULL;
  811. //delete mCpu;
  812. for (auto prevModule : mPrevIRBuilders)
  813. delete prevModule;
  814. mPrevIRBuilders.Clear();
  815. for (auto& pairVal : mDeferredMethodCallData)
  816. delete pairVal.mValue;
  817. mDeferredMethodCallData.Clear();
  818. mDeferredMethodIds.Clear();
  819. for (auto& specModulePair : mSpecializedMethodModules)
  820. delete specModulePair.mValue;
  821. mSpecializedMethodModules.Clear();
  822. if (mNextAltModule != NULL)
  823. delete mNextAltModule;
  824. mNextAltModule = NULL;
  825. if (mModuleOptions != NULL)
  826. delete mModuleOptions;
  827. mModuleOptions = NULL;
  828. BfReportMemory();
  829. }
  830. void BfModule::Init(bool isFullRebuild)
  831. {
  832. mContext->mFinishedModuleWorkList.Remove(this);
  833. if ((mCompiler->mIsResolveOnly) && (this != mContext->mUnreifiedModule))
  834. BF_ASSERT(mIsReified);
  835. if (!mIsScratchModule)
  836. {
  837. mCompiler->mStats.mModulesStarted++;
  838. if (mIsReified)
  839. mCompiler->mStats.mReifiedModuleCount++;
  840. mAddedToCount = true;
  841. }
  842. mIsHotModule = (mProject != NULL) && (mCompiler->mOptions.mHotProject != NULL) && (mCompiler->mOptions.mHotProject->ContainsReference(mProject));
  843. mFuncReferences.Clear();
  844. mClassVDataRefs.Clear();
  845. mClassVDataExtRefs.Clear();
  846. //mTypeDataRefs.Clear();
  847. mDbgRawAllocDataRefs.Clear();
  848. CleanupFileInstances();
  849. mStaticFieldRefs.Clear();
  850. //mInterfaceSlotRefs.Clear();
  851. // If we are just doing an extension then the ownede types aren't rebuilt.
  852. // If we set mRevision then QueueMethodSpecializations wouldn't actually queue up required specializations
  853. // and we'd end up with link errors if the original module uniquely referred to any generic methods
  854. if (isFullRebuild)
  855. mRevision = mCompiler->mRevision;
  856. BF_ASSERT(mCurTypeInstance == NULL);
  857. mIsModuleMutable = true;
  858. BF_ASSERT((mBfIRBuilder == NULL) || (mCompiler->mIsResolveOnly));
  859. #ifdef _DEBUG
  860. EnsureIRBuilder(mCompiler->mLastAutocompleteModule == this);
  861. #else
  862. EnsureIRBuilder(false);
  863. #endif
  864. mCurMethodState = NULL;
  865. mAwaitingInitFinish = true;
  866. mOnDemandMethodCount = 0;
  867. mAwaitingFinish = false;
  868. mHasForceLinkMarker = false;
  869. mUsedSlotCount = -1;
  870. }
  871. bool BfModule::WantsFinishModule()
  872. {
  873. return (mIncompleteMethodCount == 0) && (mOnDemandMethodCount == 0) && (!mHasGenericMethods) && (!mIsScratchModule) && (mExtensionCount == 0) && (mParentModule == NULL);
  874. }
  875. bool BfModule::IsHotCompile()
  876. {
  877. return mCompiler->IsHotCompile() && !mIsComptimeModule;
  878. }
  879. void BfModule::FinishInit()
  880. {
  881. BF_ASSERT(mAwaitingInitFinish);
  882. auto moduleOptions = GetModuleOptions();
  883. mBfIRBuilder->Start(mModuleName, mCompiler->mSystem->mPtrSize, IsOptimized());
  884. mBfIRBuilder->Module_SetTargetTriple(mCompiler->mOptions.mTargetTriple, mCompiler->mOptions.mTargetCPU);
  885. mBfIRBuilder->SetBackend(IsTargetingBeefBackend());
  886. if (moduleOptions.mOptLevel == BfOptLevel_OgPlus)
  887. {
  888. // Og+ requires debug info
  889. moduleOptions.mEmitDebugInfo = 1;
  890. }
  891. mHasFullDebugInfo = moduleOptions.mEmitDebugInfo == 1;
  892. if (mIsComptimeModule)
  893. mHasFullDebugInfo = false;
  894. if (((!mCompiler->mIsResolveOnly) && (!mIsScratchModule) && (moduleOptions.mEmitDebugInfo != 0) && (mIsReified)) ||
  895. (mIsComptimeModule))
  896. {
  897. mBfIRBuilder->DbgInit();
  898. }
  899. else
  900. mHasFullDebugInfo = false;
  901. if ((mBfIRBuilder->DbgHasInfo()) && (mModuleName != "") &&
  902. ((moduleOptions.mEmitDebugInfo != 0)))
  903. {
  904. if (mCompiler->mOptions.IsCodeView())
  905. {
  906. mBfIRBuilder->Module_AddModuleFlag("CodeView", 1);
  907. }
  908. else
  909. {
  910. mBfIRBuilder->Module_AddModuleFlag("Dwarf Version", 4);
  911. }
  912. mBfIRBuilder->Module_AddModuleFlag("Debug Info Version", 3);
  913. mDICompileUnit = mBfIRBuilder->DbgCreateCompileUnit(llvm::dwarf::DW_LANG_C_plus_plus, mModuleName, ".", "Beef Compiler 0.42.3", /*moduleOptions.mOptLevel > 0*/false, "", 0, !mHasFullDebugInfo);
  914. }
  915. mAwaitingInitFinish = false;
  916. }
  917. void BfModule::CalcGeneratesCode()
  918. {
  919. if ((!mIsReified) || (mIsScratchModule))
  920. {
  921. mGeneratesCode = false;
  922. return;
  923. }
  924. mGeneratesCode = false;
  925. for (auto typeInst : mOwnedTypeInstances)
  926. if (!typeInst->IsInterface())
  927. mGeneratesCode = true;
  928. }
  929. void BfModule::ReifyModule()
  930. {
  931. BF_ASSERT((mCompiler->mCompileState != BfCompiler::CompileState_Unreified) && (mCompiler->mCompileState != BfCompiler::CompileState_VData));
  932. BfLogSysM("ReifyModule %@ %s\n", this, mModuleName.c_str());
  933. BF_ASSERT((this != mContext->mScratchModule) && (this != mContext->mUnreifiedModule));
  934. mIsReified = true;
  935. CalcGeneratesCode();
  936. mReifyQueued = false;
  937. StartNewRevision(RebuildKind_SkipOnDemandTypes, true);
  938. mCompiler->mStats.mModulesReified++;
  939. }
  940. void BfModule::UnreifyModule()
  941. {
  942. BfLogSysM("UnreifyModule %p %s\n", this, mModuleName.c_str());
  943. BF_ASSERT((this != mContext->mScratchModule) && (this != mContext->mUnreifiedModule));
  944. mIsReified = false;
  945. CalcGeneratesCode();
  946. mReifyQueued = false;
  947. StartNewRevision(RebuildKind_None, true);
  948. mCompiler->mStats.mModulesUnreified++;
  949. }
  950. void BfModule::CleanupFileInstances()
  951. {
  952. for (auto& itr : mNamedFileInstanceMap)
  953. {
  954. BfLogSysM("FileInstance deleted: %p\n", itr.mValue);
  955. delete itr.mValue;
  956. }
  957. mCurFilePosition.mFileInstance = NULL;//
  958. mFileInstanceMap.Clear();
  959. mNamedFileInstanceMap.Clear();
  960. }
  961. void BfModule::Cleanup()
  962. {
  963. CleanupFileInstances();
  964. }
  965. void BfModule::PrepareForIRWriting(BfTypeInstance* typeInst)
  966. {
  967. if (HasCompiledOutput())
  968. {
  969. // It's possible that the target's code hasn't changed but we're requesting a new generic method specialization
  970. if ((!mIsModuleMutable) && (!typeInst->IsUnspecializedType()) && (!typeInst->mResolvingVarField))
  971. {
  972. StartExtension();
  973. }
  974. }
  975. else
  976. {
  977. EnsureIRBuilder();
  978. }
  979. }
  980. void BfModule::SetupIRBuilder(bool dbgVerifyCodeGen)
  981. {
  982. if (mIsScratchModule)
  983. {
  984. mBfIRBuilder->mIgnoreWrites = true;
  985. BF_ASSERT(!dbgVerifyCodeGen);
  986. }
  987. #ifdef _DEBUG
  988. if (mCompiler->mIsResolveOnly)
  989. {
  990. // For "deep" verification testing
  991. /*if (!mIsSpecialModule)
  992. dbgVerifyCodeGen = true;*/
  993. // We only want to turn this off on smaller builds for testing
  994. mBfIRBuilder->mIgnoreWrites = true;
  995. if (dbgVerifyCodeGen)
  996. mBfIRBuilder->mIgnoreWrites = false;
  997. if (!mBfIRBuilder->mIgnoreWrites)
  998. {
  999. // The only purpose of not ignoring writes is so we can verify the codegen one instruction at a time
  1000. mBfIRBuilder->mDbgVerifyCodeGen = true;
  1001. }
  1002. }
  1003. else if (!mGeneratesCode)
  1004. {
  1005. mBfIRBuilder->mIgnoreWrites = true;
  1006. }
  1007. else
  1008. {
  1009. // We almost always want this to be 'false' unless we need need to be able to inspect the generated LLVM
  1010. // code as we walk the AST
  1011. //mBfIRBuilder->mDbgVerifyCodeGen = true;
  1012. if (
  1013. (mModuleName == "-")
  1014. //|| (mModuleName == "BeefTest2_ClearColorValue")
  1015. //|| (mModuleName == "Tests_FuncRefs")
  1016. )
  1017. mBfIRBuilder->mDbgVerifyCodeGen = true;
  1018. // Just for testing!
  1019. //mBfIRBuilder->mIgnoreWrites = true;
  1020. }
  1021. #else
  1022. if (mCompiler->mIsResolveOnly)
  1023. {
  1024. // Always ignore writes in resolveOnly for release builds
  1025. mBfIRBuilder->mIgnoreWrites = true;
  1026. }
  1027. else
  1028. {
  1029. // Just for memory testing! This breaks everything.
  1030. //mBfIRBuilder->mIgnoreWrites = true;
  1031. // For "deep" verification testing
  1032. //mBfIRBuilder->mDbgVerifyCodeGen = true;
  1033. }
  1034. #endif
  1035. mWantsIRIgnoreWrites = mBfIRBuilder->mIgnoreWrites;
  1036. }
  1037. void BfModule::EnsureIRBuilder(bool dbgVerifyCodeGen)
  1038. {
  1039. BF_ASSERT(!mIsDeleting);
  1040. if (mBfIRBuilder == NULL)
  1041. {
  1042. if ((!mIsScratchModule) && (!mAddedToCount))
  1043. {
  1044. mCompiler->mStats.mModulesStarted++;
  1045. mAddedToCount = true;
  1046. }
  1047. BF_ASSERT(mStaticFieldRefs.GetCount() == 0);
  1048. /*if (mCompiler->mIsResolveOnly)
  1049. BF_ASSERT(mIsResolveOnly);*/
  1050. mBfIRBuilder = new BfIRBuilder(this);
  1051. BfLogSysM("Created mBfIRBuilder %p in %p %s Reified: %d\n", mBfIRBuilder, this, mModuleName.c_str(), mIsReified);
  1052. SetupIRBuilder(dbgVerifyCodeGen);
  1053. }
  1054. }
  1055. BfIRValue BfModule::CreateForceLinkMarker(BfModule* module, String* outName)
  1056. {
  1057. String name = "FORCELINKMOD_" + module->mModuleName;
  1058. if (outName != NULL)
  1059. *outName = name;
  1060. auto markerType = GetPrimitiveType(BfTypeCode_Int8);
  1061. return mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapType(markerType), true, BfIRLinkageType_External, (module == this) ? mBfIRBuilder->CreateConst(BfTypeCode_Int8, 0) : BfIRValue(), name);
  1062. }
  1063. void BfModule::StartNewRevision(RebuildKind rebuildKind, bool force)
  1064. {
  1065. BP_ZONE("BfModule::StartNewRevision");
  1066. // The project MAY be deleted because disabling a project can cause types to be deleted which
  1067. // causes other types rebuild BEFORE they get deleted, which is okay (though wasteful)
  1068. //BF_ASSERT((mProject == NULL) || (!mProject->mDisabled));
  1069. if (mCompiler->mCompileState == BfCompiler::CompileState_Cleanup)
  1070. {
  1071. // Cleaning up local methods may cause some necessary NewRevisions
  1072. force = true;
  1073. }
  1074. // Already on new revision?
  1075. if ((mRevision == mCompiler->mRevision) && (!force))
  1076. return;
  1077. mHadBuildError = false;
  1078. mHadBuildWarning = false;
  1079. mExtensionCount = 0;
  1080. mRevision = mCompiler->mRevision;
  1081. mRebuildIdx++;
  1082. ClearModuleData(!force);
  1083. // Clear this here, not in ClearModuleData, so we preserve those references even after writing out module
  1084. if (rebuildKind != BfModule::RebuildKind_None) // Leave string pool refs for when we need to use things like [LinkName("")] methods bofore re-reification
  1085. {
  1086. mStringPoolRefs.Clear();
  1087. mUnreifiedStringPoolRefs.Clear();
  1088. }
  1089. mDllImportEntries.Clear();
  1090. mImportFileNames.Clear();
  1091. for (auto& pairVal : mDeferredMethodCallData)
  1092. delete pairVal.mValue;
  1093. mDeferredMethodCallData.Clear();
  1094. mDeferredMethodIds.Clear();
  1095. mModuleRefs.Clear();
  1096. mOutFileNames.Clear();
  1097. mTypeDataRefs.Clear();
  1098. mInterfaceSlotRefs.Clear();
  1099. if (rebuildKind == BfModule::RebuildKind_None)
  1100. {
  1101. for (auto& specPair : mSpecializedMethodModules)
  1102. {
  1103. auto specModule = specPair.mValue;
  1104. if (specModule->mIsReified != mIsReified)
  1105. {
  1106. if (mIsReified)
  1107. specModule->ReifyModule();
  1108. else
  1109. specModule->UnreifyModule();
  1110. }
  1111. }
  1112. }
  1113. else
  1114. {
  1115. for (auto& specPair : mSpecializedMethodModules)
  1116. {
  1117. auto specModule = specPair.mValue;
  1118. delete specModule;
  1119. }
  1120. }
  1121. mSpecializedMethodModules.Clear();
  1122. delete mNextAltModule;
  1123. mNextAltModule = NULL;
  1124. BF_ASSERT(mModuleOptions == NULL);
  1125. BfLogSysM("Mod:%p StartNewRevision: %s Revision: %d\n", this, mModuleName.c_str(), mRevision);
  1126. bool needsTypePopulated = false;
  1127. int oldOnDemandCount = 0;
  1128. // We don't have to rebuild types in the unspecialized module because there is no
  1129. // data that's needed -- their method instances are all NULL and the module
  1130. // doesn't get included in the build
  1131. if (this != mContext->mScratchModule)
  1132. {
  1133. for (int typeIdx = 0; typeIdx < (int)mOwnedTypeInstances.size(); typeIdx++)
  1134. {
  1135. auto typeInst = mOwnedTypeInstances[typeIdx];
  1136. if (!typeInst->IsDeleting())
  1137. {
  1138. typeInst->mIsReified = mIsReified;
  1139. if (rebuildKind != BfModule::RebuildKind_None)
  1140. {
  1141. if (typeInst->IsOnDemand())
  1142. {
  1143. // Changing config should require on demand types to be recreated, but reifying a module shouldn't cause the type to be deleted
  1144. if (rebuildKind == BfModule::RebuildKind_All)
  1145. mContext->DeleteType(typeInst);
  1146. else
  1147. {
  1148. RebuildMethods(typeInst);
  1149. }
  1150. }
  1151. else
  1152. //TODO: Why weren't we placing specialzied in purgatory here originally? This caused failed types to stick around too long
  1153. mContext->RebuildType(typeInst, false, false, true);
  1154. //mContext->RebuildType(typeInst, false, false, false);
  1155. }
  1156. else
  1157. {
  1158. auto _HandleMethod = [&](BfMethodInstance* methodInstance)
  1159. {
  1160. if ((methodInstance != NULL) && (methodInstance->mDeclModule != NULL))
  1161. methodInstance->mDeclModule = this;
  1162. };
  1163. for (auto& methodGroup : typeInst->mMethodInstanceGroups)
  1164. {
  1165. if ((methodGroup.mOnDemandKind == BfMethodOnDemandKind_NoDecl_AwaitingReference) ||
  1166. (methodGroup.mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingDecl) ||
  1167. (methodGroup.mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingReference) ||
  1168. (methodGroup.mOnDemandKind == BfMethodOnDemandKind_InWorkList))
  1169. {
  1170. oldOnDemandCount++;
  1171. }
  1172. _HandleMethod(methodGroup.mDefault);
  1173. if (methodGroup.mMethodSpecializationMap != NULL)
  1174. for (auto& kv : *methodGroup.mMethodSpecializationMap)
  1175. _HandleMethod(kv.mValue);
  1176. }
  1177. }
  1178. if (typeInst->IsDeleting())
  1179. typeIdx--;
  1180. }
  1181. }
  1182. }
  1183. if (!mIsDeleting)
  1184. Init();
  1185. mOnDemandMethodCount += oldOnDemandCount;
  1186. VerifyOnDemandMethods();
  1187. }
  1188. void BfModule::StartExtension()
  1189. {
  1190. BF_ASSERT(!mIsModuleMutable);
  1191. BfLogSysM("Extension started of module %p\n", this);
  1192. mExtensionCount++;
  1193. if (mBfIRBuilder != NULL)
  1194. mPrevIRBuilders.push_back(mBfIRBuilder);
  1195. mBfIRBuilder = NULL;
  1196. mWantsIRIgnoreWrites = false;
  1197. mFuncReferences.Clear();
  1198. mClassVDataRefs.Clear();
  1199. mClassVDataExtRefs.Clear();
  1200. for (auto& kv : mTypeDataRefs)
  1201. kv.mValue = BfIRValue();
  1202. mDbgRawAllocDataRefs.Clear();
  1203. mStringCharPtrPool.Clear();
  1204. mStringObjectPool.Clear();
  1205. mStaticFieldRefs.Clear();
  1206. for (auto& kv : mInterfaceSlotRefs)
  1207. kv.mValue = BfIRValue();
  1208. for (auto& pairVal : mDeferredMethodCallData)
  1209. delete pairVal.mValue;
  1210. mDeferredMethodCallData.Clear();
  1211. mDeferredMethodIds.Clear();
  1212. DisownMethods();
  1213. BfLogSysM("Mod:%p StartExtension: %s\n", this, mModuleName.c_str());
  1214. bool wasAwaitingInitFinish = mAwaitingInitFinish;
  1215. int prevOnDemandMethodCount = mOnDemandMethodCount;
  1216. Init(false);
  1217. if (!wasAwaitingInitFinish)
  1218. FinishInit();
  1219. mOnDemandMethodCount = prevOnDemandMethodCount;
  1220. }
  1221. void BfModule::GetConstClassValueParam(BfIRValue classVData, SizedArrayImpl<BfIRValue>& typeValueParams)
  1222. {
  1223. auto hasObjectDebugFlags = mContext->mBfObjectType->mFieldInstances[0].mResolvedType->IsInteger();
  1224. BfIRValue vDataValue;
  1225. if (hasObjectDebugFlags)
  1226. vDataValue = mBfIRBuilder->CreatePtrToInt(classVData, BfTypeCode_IntPtr);
  1227. else
  1228. vDataValue = mBfIRBuilder->CreateBitCast(classVData, mBfIRBuilder->MapType(mContext->mBfClassVDataPtrType));
  1229. typeValueParams.push_back(vDataValue);
  1230. if (hasObjectDebugFlags)
  1231. {
  1232. auto primType = GetPrimitiveType(BfTypeCode_IntPtr);
  1233. typeValueParams.push_back(GetDefaultValue(primType));
  1234. }
  1235. }
  1236. BfIRValue BfModule::GetConstValue(int64 val)
  1237. {
  1238. return mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, (uint64)val);
  1239. }
  1240. BfIRValue BfModule::GetConstValue(int64 val, BfType* type)
  1241. {
  1242. BfType* checkType = type;
  1243. if (type->IsTypedPrimitive())
  1244. {
  1245. checkType = type->GetUnderlyingType();
  1246. }
  1247. if (checkType->IsPrimitiveType())
  1248. {
  1249. auto primType = (BfPrimitiveType*)checkType;
  1250. if (checkType->IsFloat())
  1251. return mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, (double)val);
  1252. else
  1253. return mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, (uint64)val);
  1254. }
  1255. return BfIRValue();
  1256. }
  1257. BfIRValue BfModule::GetConstValue8(int val)
  1258. {
  1259. return mBfIRBuilder->CreateConst(BfTypeCode_Int8, (uint64)val);
  1260. }
  1261. BfIRValue BfModule::GetConstValue32(int32 val)
  1262. {
  1263. return mBfIRBuilder->CreateConst(BfTypeCode_Int32, (uint64)val);
  1264. }
  1265. BfIRValue BfModule::GetConstValue64(int64 val)
  1266. {
  1267. return mBfIRBuilder->CreateConst(BfTypeCode_Int64, (uint64)val);
  1268. }
  1269. BfIRValue BfModule::GetDefaultValue(BfType* type)
  1270. {
  1271. PopulateType(type, BfPopulateType_Data);
  1272. mBfIRBuilder->PopulateType(type, BfIRPopulateType_Declaration);
  1273. if (type->IsTypedPrimitive())
  1274. {
  1275. auto underlyingType = type->GetUnderlyingType();
  1276. if (underlyingType == NULL)
  1277. return mBfIRBuilder->CreateConst(BfTypeCode_Int64, 0);
  1278. return GetDefaultValue(type->GetUnderlyingType());
  1279. }
  1280. if (type->IsPointer() || type->IsObjectOrInterface() || type->IsGenericParam() || type->IsVar() || type->IsRef() || type->IsNull() ||
  1281. type->IsModifiedTypeType() || type->IsConcreteInterfaceType())
  1282. return mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(type));
  1283. if ((type->IsIntegral()) || (type->IsBoolean()))
  1284. {
  1285. auto primType = (BfPrimitiveType*)type;
  1286. return mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, (uint64)0);
  1287. }
  1288. if (type->IsFloat())
  1289. {
  1290. auto primType = (BfPrimitiveType*)type;
  1291. return mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, 0.0);
  1292. }
  1293. if (type->IsVoid())
  1294. return mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(type));
  1295. return mBfIRBuilder->CreateConstAggZero(mBfIRBuilder->MapType(type));
  1296. }
  1297. BfTypedValue BfModule::GetFakeTypedValue(BfType* type)
  1298. {
  1299. // This is a conservative "IsValueless", since it's not an error to use a fakeVal even if we don't need one
  1300. if (type->mSize == 0)
  1301. return BfTypedValue(BfIRValue::sValueless, type);
  1302. else
  1303. return BfTypedValue(mBfIRBuilder->GetFakeVal(), type);
  1304. }
  1305. BfTypedValue BfModule::GetDefaultTypedValue(BfType* type, bool allowRef, BfDefaultValueKind defaultValueKind)
  1306. {
  1307. if (type->IsVar())
  1308. return BfTypedValue(mBfIRBuilder->GetFakeVal(), type);
  1309. PopulateType(type, BfPopulateType_Data);
  1310. mBfIRBuilder->PopulateType(type, type->IsValueType() ? BfIRPopulateType_Full : BfIRPopulateType_Declaration);
  1311. if (defaultValueKind == BfDefaultValueKind_Undef)
  1312. {
  1313. return BfTypedValue(mBfIRBuilder->GetUndefConstValue(mBfIRBuilder->MapType(type)), type);
  1314. }
  1315. BfTypedValue typedValue;
  1316. if ((defaultValueKind != BfDefaultValueKind_Const) && (!type->IsValuelessType()))
  1317. {
  1318. if (type->IsRef())
  1319. {
  1320. BfRefType* refType = (BfRefType*)type;
  1321. BfType* underlyingType = refType->GetUnderlyingType();
  1322. typedValue = BfTypedValue(CreateAlloca(underlyingType), underlyingType, BfTypedValueKind_Addr);
  1323. }
  1324. else
  1325. {
  1326. typedValue = BfTypedValue(CreateAlloca(type), type, BfTypedValueKind_Addr);
  1327. }
  1328. if (!mBfIRBuilder->mIgnoreWrites)
  1329. {
  1330. mBfIRBuilder->CreateMemSet(typedValue.mValue, GetConstValue(0, GetPrimitiveType(BfTypeCode_Int8)),
  1331. GetConstValue(type->mSize), type->mAlign);
  1332. }
  1333. if ((defaultValueKind == BfDefaultValueKind_Value) && (!type->IsRef()))
  1334. typedValue = LoadValue(typedValue);
  1335. return typedValue;
  1336. }
  1337. if ((type->IsRef()) && (!allowRef))
  1338. {
  1339. BfRefType* refType = (BfRefType*)type;
  1340. BfType* underlyingType = refType->GetUnderlyingType();
  1341. if (underlyingType->IsValuelessType())
  1342. typedValue = BfTypedValue(mBfIRBuilder->GetFakeVal(), underlyingType, true);
  1343. else
  1344. typedValue = BfTypedValue(mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(type)), underlyingType, true);
  1345. }
  1346. else
  1347. {
  1348. typedValue = BfTypedValue(GetDefaultValue(type), type, (defaultValueKind == BfDefaultValueKind_Addr) ? BfTypedValueKind_Addr : BfTypedValueKind_Value);
  1349. }
  1350. return typedValue;
  1351. }
  1352. BfIRValue BfModule::CreateStringCharPtr(const StringImpl& str, int stringId, bool define)
  1353. {
  1354. String stringDataName = StrFormat("__bfStrData%d", stringId);
  1355. auto charType = GetPrimitiveType(BfTypeCode_Char8);
  1356. BfIRType irStrCharType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->MapType(charType), (int)str.length() + 1);
  1357. BfIRValue strConstant;
  1358. if (define)
  1359. {
  1360. strConstant = mBfIRBuilder->CreateConstString(str);
  1361. }
  1362. BfIRValue gv = mBfIRBuilder->CreateGlobalVariable(irStrCharType,
  1363. true, BfIRLinkageType_External,
  1364. strConstant, stringDataName);
  1365. if (define)
  1366. mBfIRBuilder->GlobalVar_SetUnnamedAddr(gv, true);
  1367. return mBfIRBuilder->CreateInBoundsGEP(gv, 0, 0);
  1368. }
  1369. void BfModule::FixConstValueParams(BfTypeInstance* typeInst, SizedArrayImpl<BfIRValue>& valueParams, bool fillInPadding)
  1370. {
  1371. if ((!typeInst->mTypeDef->mIsCombinedPartial) && (!fillInPadding))
  1372. return;
  1373. int prevDataIdx = -1;
  1374. int usedDataIdx = 0;
  1375. int valueParamIdx = 0;
  1376. if (typeInst->mBaseType != NULL)
  1377. {
  1378. usedDataIdx++;
  1379. valueParamIdx++;
  1380. prevDataIdx++;
  1381. }
  1382. int startingParamsSize = (int)valueParams.mSize;
  1383. for (int fieldIdx = 0; fieldIdx < (int)typeInst->mFieldInstances.size(); fieldIdx++)
  1384. {
  1385. auto fieldInstance = &typeInst->mFieldInstances[fieldIdx];
  1386. if (fieldInstance->mDataIdx < 0)
  1387. continue;
  1388. BF_ASSERT(fieldInstance->mDataIdx > prevDataIdx);
  1389. if (fillInPadding)
  1390. {
  1391. for (int i = prevDataIdx + 1; i < fieldInstance->mDataIdx; i++)
  1392. valueParams.Insert(valueParamIdx++, mBfIRBuilder->CreateConstArrayZero(0));
  1393. }
  1394. valueParamIdx++;
  1395. prevDataIdx = fieldInstance->mDataIdx;
  1396. usedDataIdx++;
  1397. if (usedDataIdx <= valueParams.mSize)
  1398. continue;
  1399. valueParams.Add(GetDefaultValue(fieldInstance->mResolvedType));
  1400. }
  1401. }
  1402. BfIRValue BfModule::CreateStringObjectValue(const StringImpl& str, int stringId, bool define)
  1403. {
  1404. auto stringTypeInst = ResolveTypeDef(mCompiler->mStringTypeDef, define ? BfPopulateType_Data : BfPopulateType_Declaration)->ToTypeInstance();
  1405. mBfIRBuilder->PopulateType(stringTypeInst);
  1406. auto classVDataGlobal = CreateClassVDataGlobal(stringTypeInst);
  1407. String stringObjName = StrFormat("__bfStrObj%d", stringId);
  1408. BfIRValue stringValData;
  1409. if (define)
  1410. {
  1411. BfIRValue stringCharsVal = CreateStringCharPtr(str, stringId, define);
  1412. mStringCharPtrPool[stringId] = stringCharsVal;
  1413. SizedArray<BfIRValue, 8> typeValueParams;
  1414. GetConstClassValueParam(classVDataGlobal, typeValueParams);
  1415. FixConstValueParams(stringTypeInst->mBaseType, typeValueParams);
  1416. auto objData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(stringTypeInst->mBaseType, BfIRPopulateType_Full), typeValueParams);
  1417. auto lenByteCount = stringTypeInst->mFieldInstances[0].mResolvedType->mSize;
  1418. typeValueParams.clear();
  1419. typeValueParams.push_back(objData);
  1420. if (lenByteCount == 4)
  1421. {
  1422. typeValueParams.push_back(GetConstValue32((int)str.length())); // mLength
  1423. typeValueParams.push_back(GetConstValue32((int32)(0x40000000 + str.length() + 1))); // mAllocSizeAndFlags
  1424. }
  1425. else
  1426. {
  1427. typeValueParams.push_back(GetConstValue64(str.length())); // mLength
  1428. typeValueParams.push_back(GetConstValue64(0x4000000000000000LL + str.length() + 1)); // mAllocSizeAndFlags
  1429. }
  1430. typeValueParams.push_back(stringCharsVal); // mPtr
  1431. FixConstValueParams(stringTypeInst, typeValueParams);
  1432. stringValData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(stringTypeInst, BfIRPopulateType_Full), typeValueParams);
  1433. }
  1434. mBfIRBuilder->PopulateType(stringTypeInst);
  1435. auto stringValLiteral = mBfIRBuilder->CreateGlobalVariable(
  1436. mBfIRBuilder->MapTypeInst(stringTypeInst, BfIRPopulateType_Full),
  1437. true,
  1438. BfIRLinkageType_External,
  1439. define ? stringValData : BfIRValue(),
  1440. stringObjName);
  1441. return stringValLiteral;
  1442. }
  1443. int BfModule::GetStringPoolIdx(BfIRValue constantStr, BfIRConstHolder* constHolder)
  1444. {
  1445. BF_ASSERT(constantStr.IsConst());
  1446. if (constHolder == NULL)
  1447. constHolder = mBfIRBuilder;
  1448. auto constant = constHolder->GetConstant(constantStr);
  1449. if (constant->mTypeCode == BfTypeCode_StringId)
  1450. {
  1451. return constant->mInt32;
  1452. }
  1453. while (constant->mConstType == BfConstType_BitCast)
  1454. {
  1455. auto constBitCast = (BfConstantBitCast*)constant;
  1456. constant = constHolder->GetConstantById(constBitCast->mTarget);
  1457. }
  1458. if (constant->mConstType == BfConstType_GEP32_2)
  1459. {
  1460. auto constGEP = (BfConstantGEP32_2*)constant;
  1461. constant = constHolder->GetConstantById(constGEP->mTarget);
  1462. }
  1463. if (constant->mConstType == BfConstType_GlobalVar)
  1464. {
  1465. auto constGV = (BfGlobalVar*)constant;
  1466. const char* strDataPrefix = "__bfStrData";
  1467. if (strncmp(constGV->mName, strDataPrefix, strlen(strDataPrefix)) == 0)
  1468. return atoi(constGV->mName + strlen(strDataPrefix));
  1469. const char* strObjPrefix = "__bfStrObj";
  1470. if (strncmp(constGV->mName, strObjPrefix, strlen(strObjPrefix)) == 0)
  1471. return atoi(constGV->mName + strlen(strObjPrefix));
  1472. }
  1473. return -1;
  1474. }
  1475. String* BfModule::GetStringPoolString(BfIRValue constantStr, BfIRConstHolder * constHolder)
  1476. {
  1477. int strId = GetStringPoolIdx(constantStr, constHolder);
  1478. if (strId != -1)
  1479. {
  1480. auto& entry = mContext->mStringObjectIdMap[strId];
  1481. return &entry.mString;
  1482. }
  1483. return NULL;
  1484. }
  1485. BfIRValue BfModule::GetStringCharPtr(int stringId, bool force)
  1486. {
  1487. if ((mBfIRBuilder->mIgnoreWrites) && (!force))
  1488. {
  1489. mUnreifiedStringPoolRefs.Add(stringId);
  1490. return mBfIRBuilder->CreateConst(BfTypeCode_StringId, stringId);
  1491. }
  1492. BfIRValue* irValue = NULL;
  1493. if (!mStringCharPtrPool.TryAdd(stringId, NULL, &irValue))
  1494. return *irValue;
  1495. // If this wasn't in neither dictionary yet, add to mStringPoolRefs
  1496. if (!mStringObjectPool.ContainsKey(stringId))
  1497. mStringPoolRefs.Add(stringId);
  1498. const StringImpl& str = mContext->mStringObjectIdMap[stringId].mString;
  1499. BfIRValue strCharPtrConst = CreateStringCharPtr(str, stringId, false);
  1500. *irValue = strCharPtrConst;
  1501. return strCharPtrConst;
  1502. }
  1503. BfIRValue BfModule::GetStringCharPtr(BfIRValue strValue, bool force)
  1504. {
  1505. if (strValue.IsConst())
  1506. {
  1507. int stringId = GetStringPoolIdx(strValue);
  1508. BF_ASSERT(stringId != -1);
  1509. return GetStringCharPtr(stringId, force);
  1510. }
  1511. BfIRValue charPtrPtr = mBfIRBuilder->CreateInBoundsGEP(strValue, 0, 1);
  1512. BfIRValue charPtr = mBfIRBuilder->CreateLoad(charPtrPtr);
  1513. return charPtr;
  1514. }
  1515. BfIRValue BfModule::GetStringCharPtr(const StringImpl& str, bool force)
  1516. {
  1517. return GetStringCharPtr(GetStringObjectValue(str, force), force);
  1518. }
  1519. BfIRValue BfModule::GetStringObjectValue(int strId, bool define, bool force)
  1520. {
  1521. BfIRValue* objValue;
  1522. if (mStringObjectPool.TryGetValue(strId, &objValue))
  1523. return *objValue;
  1524. auto stringPoolEntry = mContext->mStringObjectIdMap[strId];
  1525. return GetStringObjectValue(stringPoolEntry.mString, define, force);
  1526. }
  1527. BfIRValue BfModule::GetStringObjectValue(const StringImpl& str, bool define, bool force)
  1528. {
  1529. auto stringType = ResolveTypeDef(mCompiler->mStringTypeDef, define ? BfPopulateType_Data : BfPopulateType_Declaration);
  1530. mBfIRBuilder->PopulateType(stringType);
  1531. int strId = mContext->GetStringLiteralId(str);
  1532. if ((mBfIRBuilder->mIgnoreWrites) && (!force))
  1533. {
  1534. auto refModule = this;
  1535. if ((this == mContext->mUnreifiedModule) && (mCurTypeInstance != NULL))
  1536. refModule = mCurTypeInstance->mModule;
  1537. refModule->mUnreifiedStringPoolRefs.Add(strId);
  1538. return mBfIRBuilder->CreateConst(BfTypeCode_StringId, strId);
  1539. }
  1540. BfIRValue* irValuePtr = NULL;
  1541. if (!mStringObjectPool.TryAdd(strId, NULL, &irValuePtr))
  1542. return *irValuePtr;
  1543. // If this wasn't in neither dictionary yet, add to mStringPoolRefs
  1544. if (!mStringCharPtrPool.ContainsKey(strId))
  1545. mStringPoolRefs.Add(strId);
  1546. BfIRValue strObject = CreateStringObjectValue(str, strId, define);
  1547. *irValuePtr = strObject;
  1548. mStringPoolRefs.Add(strId);
  1549. return strObject;
  1550. }
  1551. BfIRValue BfModule::CreateGlobalConstValue(const StringImpl& name, BfIRValue constant, BfIRType type, bool external)
  1552. {
  1553. auto newConst = mBfIRBuilder->CreateGlobalVariable(
  1554. type,
  1555. true,
  1556. external ? BfIRLinkageType_External : BfIRLinkageType_Internal,
  1557. constant,
  1558. name.c_str());
  1559. return newConst;
  1560. }
  1561. void BfModule::NewScopeState(bool createLexicalBlock, bool flushValueScope)
  1562. {
  1563. auto curScope = mCurMethodState->mCurScope;
  1564. if (curScope->mLabelNode != NULL)
  1565. {
  1566. curScope->mLabelNode->ToString(curScope->mLabel);
  1567. auto rootMethodState = mCurMethodState->GetRootMethodState();
  1568. curScope->mScopeLocalId = rootMethodState->mCurLocalVarId++;
  1569. auto autoComplete = mCompiler->GetAutoComplete();
  1570. if (autoComplete != NULL)
  1571. autoComplete->CheckLabel(curScope->mLabelNode, NULL, curScope);
  1572. }
  1573. if (!mCurMethodState->mCurScope->mLabel.IsEmpty())
  1574. {
  1575. auto checkScope = mCurMethodState->mCurScope->mPrevScope;
  1576. while (checkScope != NULL)
  1577. {
  1578. if (checkScope->mLabel == mCurMethodState->mCurScope->mLabel)
  1579. {
  1580. auto errorNode = Fail("Duplicate scope label", curScope->mLabelNode);
  1581. if (errorNode != NULL)
  1582. mCompiler->mPassInstance->MoreInfo("See previous scope label", checkScope->mLabelNode);
  1583. break;
  1584. }
  1585. checkScope = checkScope->mPrevScope;
  1586. }
  1587. }
  1588. auto prevScope = mCurMethodState->mCurScope->mPrevScope;
  1589. if ((flushValueScope) && (prevScope != NULL) && (prevScope->mValueScopeStart))
  1590. {
  1591. if (prevScope->mHadScopeValueRetain)
  1592. mBfIRBuilder->CreateValueScopeSoftEnd(prevScope->mValueScopeStart);
  1593. else
  1594. mBfIRBuilder->CreateValueScopeHardEnd(prevScope->mValueScopeStart);
  1595. }
  1596. mCurMethodState->mBlockNestLevel++;
  1597. if ((createLexicalBlock) && (mBfIRBuilder->DbgHasInfo()) && (mHasFullDebugInfo))
  1598. {
  1599. // DIScope could be NULL if we're in an unspecialized method (for example)
  1600. if (mCurMethodState->mCurScope->mDIScope)
  1601. mCurMethodState->mCurScope->mDIScope = mBfIRBuilder->DbgCreateLexicalBlock(mCurMethodState->mCurScope->mDIScope, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, mCurFilePosition.mCurColumn);
  1602. }
  1603. mCurMethodState->mCurScope->mLocalVarStart = (int)mCurMethodState->mLocals.size();
  1604. mCurMethodState->mCurScope->mBlock = mBfIRBuilder->MaybeChainNewBlock((!mCurMethodState->mCurScope->mLabel.empty()) ? mCurMethodState->mCurScope->mLabel : "newScope");
  1605. mCurMethodState->mCurScope->mMixinState = mCurMethodState->mMixinState;
  1606. }
  1607. void BfModule::RestoreScoreState_LocalVariables()
  1608. {
  1609. while (mCurMethodState->mCurScope->mLocalVarStart < (int)mCurMethodState->mLocals.size())
  1610. {
  1611. auto localVar = mCurMethodState->mLocals.back();
  1612. LocalVariableDone(localVar, false);
  1613. mCurMethodState->mLocals.pop_back();
  1614. if (localVar->mShadowedLocal != NULL)
  1615. {
  1616. BfLocalVarEntry* localVarEntryPtr;
  1617. if (mCurMethodState->mLocalVarSet.TryGet(BfLocalVarEntry(localVar), &localVarEntryPtr))
  1618. {
  1619. localVarEntryPtr->mLocalVar = localVar->mShadowedLocal;
  1620. }
  1621. }
  1622. else
  1623. {
  1624. mCurMethodState->mLocalVarSet.Remove(BfLocalVarEntry(localVar));
  1625. }
  1626. delete localVar;
  1627. }
  1628. }
  1629. void BfModule::RestoreScopeState()
  1630. {
  1631. BfScopeData* prevScopeData = mCurMethodState->mCurScope->mPrevScope;
  1632. mCurMethodState->mBlockNestLevel--;
  1633. if (!mCurMethodState->mCurScope->mAtEndBlocks.empty())
  1634. {
  1635. BfIRBlock afterEndBlock;
  1636. if (!mCurMethodState->mLeftBlockUncond)
  1637. {
  1638. afterEndBlock = mBfIRBuilder->CreateBlock("scopeAfterEnd");
  1639. mBfIRBuilder->CreateBr(afterEndBlock);
  1640. mBfIRBuilder->ClearDebugLocation_Last();
  1641. }
  1642. for (auto preExitBlock : mCurMethodState->mCurScope->mAtEndBlocks)
  1643. mBfIRBuilder->MoveBlockToEnd(preExitBlock);
  1644. if (afterEndBlock)
  1645. {
  1646. mBfIRBuilder->AddBlock(afterEndBlock);
  1647. mBfIRBuilder->SetInsertPoint(afterEndBlock);
  1648. }
  1649. }
  1650. if (!mCurMethodState->mLeftBlockUncond)
  1651. EmitDeferredScopeCalls(true, mCurMethodState->mCurScope);
  1652. RestoreScoreState_LocalVariables();
  1653. if (mCurMethodState->mCurScope->mValueScopeStart)
  1654. mBfIRBuilder->CreateValueScopeHardEnd(mCurMethodState->mCurScope->mValueScopeStart);
  1655. mCurMethodState->mCurScope = prevScopeData;
  1656. mCurMethodState->mTailScope = mCurMethodState->mCurScope;
  1657. }
  1658. BfIRValue BfModule::CreateAlloca(BfType* type, bool addLifetime, const char* name, BfIRValue arraySize)
  1659. {
  1660. if (mBfIRBuilder->mIgnoreWrites)
  1661. return mBfIRBuilder->GetFakeVal();
  1662. BF_ASSERT((*(int8*)&addLifetime == 1) || (*(int8*)&addLifetime == 0));
  1663. mBfIRBuilder->PopulateType(type);
  1664. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  1665. if (!mBfIRBuilder->mIgnoreWrites)
  1666. BF_ASSERT(!prevInsertBlock.IsFake());
  1667. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  1668. BfIRValue allocaInst;
  1669. if (arraySize)
  1670. allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(type), arraySize);
  1671. else
  1672. allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(type));
  1673. mBfIRBuilder->SetAllocaAlignment(allocaInst, type->mAlign);
  1674. mBfIRBuilder->ClearDebugLocation(allocaInst);
  1675. if (name != NULL)
  1676. mBfIRBuilder->SetName(allocaInst, name);
  1677. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  1678. if ((addLifetime) && (WantsLifetimes()))
  1679. {
  1680. auto lifetimeStart = mBfIRBuilder->CreateLifetimeStart(allocaInst);
  1681. mBfIRBuilder->ClearDebugLocation(lifetimeStart);
  1682. mCurMethodState->mCurScope->mDeferredLifetimeEnds.push_back(allocaInst);
  1683. }
  1684. return allocaInst;
  1685. }
  1686. BfIRValue BfModule::CreateAllocaInst(BfTypeInstance* typeInst, bool addLifetime, const char* name)
  1687. {
  1688. if (mBfIRBuilder->mIgnoreWrites)
  1689. return mBfIRBuilder->GetFakeVal();
  1690. BF_ASSERT((*(int8*)&addLifetime == 1) || (*(int8*)&addLifetime == 0));
  1691. mBfIRBuilder->PopulateType(typeInst);
  1692. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  1693. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  1694. auto allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapTypeInst(typeInst));
  1695. mBfIRBuilder->SetAllocaAlignment(allocaInst, typeInst->mInstAlign);
  1696. mBfIRBuilder->ClearDebugLocation(allocaInst);
  1697. if (name != NULL)
  1698. mBfIRBuilder->SetName(allocaInst, name);
  1699. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  1700. if ((addLifetime) && (WantsLifetimes()))
  1701. {
  1702. auto lifetimeStart = mBfIRBuilder->CreateLifetimeStart(allocaInst);
  1703. mBfIRBuilder->ClearDebugLocation(lifetimeStart);
  1704. mCurMethodState->mCurScope->mDeferredLifetimeEnds.push_back(allocaInst);
  1705. }
  1706. return allocaInst;
  1707. }
  1708. BfDeferredCallEntry* BfModule::AddStackAlloc(BfTypedValue val, BfIRValue arraySize, BfAstNode* refNode, BfScopeData* scopeData, bool condAlloca, bool mayEscape, BfIRBlock valBlock)
  1709. {
  1710. //This was removed because we want the alloc to be added to the __deferred list if it's actually a "stack"
  1711. // 'stack' in a head scopeData is really the same as 'scopeData', so use the simpler scopeData handling
  1712. /*if (mCurMethodState->mInHeadScope)
  1713. isScopeAlloc = true;*/
  1714. if (scopeData == NULL)
  1715. return NULL;
  1716. auto checkBaseType = val.mType->ToTypeInstance();
  1717. if ((checkBaseType != NULL) && (checkBaseType->IsObject()) && (!arraySize))
  1718. {
  1719. bool hadDtorCall = false;
  1720. while (checkBaseType != NULL)
  1721. {
  1722. BfMethodDef* dtorMethodDef = checkBaseType->mTypeDef->GetMethodByName("~this");
  1723. if (dtorMethodDef != NULL)
  1724. {
  1725. auto dtorMethodInstance = GetMethodInstance(checkBaseType, dtorMethodDef, BfTypeVector());
  1726. if (dtorMethodInstance)
  1727. {
  1728. bool isDynAlloc = (scopeData != NULL) && (mCurMethodState->mCurScope->IsDyn(scopeData));
  1729. BfIRValue useVal = val.mValue;
  1730. BfIRBlock prevBlock = mBfIRBuilder->GetInsertBlock();
  1731. if (valBlock)
  1732. mBfIRBuilder->SetInsertPoint(valBlock);
  1733. useVal = mBfIRBuilder->CreateBitCast(val.mValue, mBfIRBuilder->MapTypeInstPtr(checkBaseType));
  1734. if (!useVal.IsConst())
  1735. mBfIRBuilder->ClearDebugLocation(useVal);
  1736. if (valBlock)
  1737. mBfIRBuilder->SetInsertPoint(prevBlock);
  1738. if (isDynAlloc)
  1739. {
  1740. //
  1741. }
  1742. else if (condAlloca)
  1743. {
  1744. BF_ASSERT(!IsTargetingBeefBackend());
  1745. BF_ASSERT(!isDynAlloc);
  1746. auto valPtr = CreateAlloca(checkBaseType);
  1747. mBfIRBuilder->ClearDebugLocation_Last();
  1748. mBfIRBuilder->CreateStore(useVal, valPtr);
  1749. mBfIRBuilder->ClearDebugLocation_Last();
  1750. useVal = valPtr;
  1751. }
  1752. SizedArray<BfIRValue, 1> llvmArgs;
  1753. llvmArgs.push_back(useVal);
  1754. auto deferredCall = AddDeferredCall(dtorMethodInstance, llvmArgs, scopeData, refNode, true);
  1755. if (deferredCall != NULL)
  1756. {
  1757. deferredCall->mCastThis = (val.mType != checkBaseType) && (!isDynAlloc);
  1758. if (condAlloca)
  1759. deferredCall->mArgsNeedLoad = true;
  1760. }
  1761. hadDtorCall = true;
  1762. break;
  1763. }
  1764. }
  1765. checkBaseType = checkBaseType->mBaseType;
  1766. }
  1767. return NULL;
  1768. }
  1769. //TODO: In the future we could be smarter about statically determining that our value hasn't escaped and eliding this
  1770. if (mayEscape)
  1771. {
  1772. if ((!IsOptimized()) && (!mIsComptimeModule) && (!val.mType->IsValuelessType()) && (!mBfIRBuilder->mIgnoreWrites) && (!mCompiler->mIsResolveOnly))
  1773. {
  1774. auto nullPtrType = GetPrimitiveType(BfTypeCode_NullPtr);
  1775. bool isDyn = mCurMethodState->mCurScope->IsDyn(scopeData);
  1776. if (!isDyn)
  1777. {
  1778. const char* methodName = arraySize ? "SetDeletedArray" : "SetDeleted";
  1779. BfModuleMethodInstance dtorMethodInstance = GetInternalMethod(methodName);
  1780. BF_ASSERT(dtorMethodInstance.mMethodInstance != NULL);
  1781. if (!dtorMethodInstance.mMethodInstance)
  1782. {
  1783. Fail(StrFormat("Unable to find %s", methodName));
  1784. }
  1785. else
  1786. {
  1787. SizedArray<BfIRValue, 1> llvmArgs;
  1788. if (IsTargetingBeefBackend())
  1789. {
  1790. llvmArgs.push_back(mBfIRBuilder->CreateBitCast(val.mValue, mBfIRBuilder->MapType(nullPtrType)));
  1791. //mBfIRBuilder->ClearDebugLocation_Last();
  1792. }
  1793. else
  1794. llvmArgs.push_back(val.mValue);
  1795. llvmArgs.push_back(GetConstValue(val.mType->mSize));
  1796. llvmArgs.push_back(GetConstValue32(val.mType->mAlign));
  1797. if (arraySize)
  1798. llvmArgs.push_back(arraySize);
  1799. return AddDeferredCall(dtorMethodInstance, llvmArgs, scopeData, refNode, true);
  1800. }
  1801. }
  1802. else
  1803. {
  1804. if ((arraySize) && (!arraySize.IsConst()) && (val.mType->mSize < mSystem->mPtrSize))
  1805. {
  1806. BfIRValue clearSize = arraySize;
  1807. if (val.mType->GetStride() > 1)
  1808. clearSize = mBfIRBuilder->CreateMul(clearSize, GetConstValue(val.mType->GetStride()));
  1809. const char* methodName = "SetDeletedX";
  1810. BfModuleMethodInstance dtorMethodInstance = GetInternalMethod(methodName);
  1811. BF_ASSERT(dtorMethodInstance);
  1812. if (!dtorMethodInstance)
  1813. {
  1814. Fail(StrFormat("Unable to find %s", methodName));
  1815. }
  1816. else
  1817. {
  1818. SizedArray<BfIRValue, 1> llvmArgs;
  1819. llvmArgs.push_back(mBfIRBuilder->CreateBitCast(val.mValue, mBfIRBuilder->MapType(nullPtrType)));
  1820. //mBfIRBuilder->ClearDebugLocation_Last();
  1821. llvmArgs.push_back(clearSize);
  1822. return AddDeferredCall(dtorMethodInstance, llvmArgs, scopeData, refNode, true);
  1823. }
  1824. }
  1825. else
  1826. {
  1827. intptr clearSize = val.mType->mSize;
  1828. auto constant = mBfIRBuilder->GetConstant(arraySize);
  1829. if (constant != NULL)
  1830. clearSize = (intptr)(clearSize * constant->mInt64);
  1831. const char* funcName = "SetDeleted1";
  1832. if (clearSize >= 16)
  1833. funcName = "SetDeleted16";
  1834. else if (clearSize >= 8)
  1835. funcName = "SetDeleted8";
  1836. else if (clearSize >= 4)
  1837. funcName = "SetDeleted4";
  1838. BfModuleMethodInstance dtorMethodInstance = GetInternalMethod(funcName);
  1839. BF_ASSERT(dtorMethodInstance.mMethodInstance != NULL);
  1840. if (!dtorMethodInstance)
  1841. {
  1842. Fail(StrFormat("Unable to find %s", funcName));
  1843. }
  1844. else
  1845. {
  1846. SizedArray<BfIRValue, 1> llvmArgs;
  1847. llvmArgs.push_back(mBfIRBuilder->CreateBitCast(val.mValue, mBfIRBuilder->MapType(nullPtrType)));
  1848. //mBfIRBuilder->ClearDebugLocation_Last();
  1849. return AddDeferredCall(dtorMethodInstance, llvmArgs, scopeData, refNode, true);
  1850. }
  1851. }
  1852. }
  1853. }
  1854. }
  1855. return NULL;
  1856. }
  1857. bool BfModule::TryLocalVariableInit(BfLocalVariable* localVar)
  1858. {
  1859. auto startTypeInstance = localVar->mResolvedType->ToTypeInstance();
  1860. if ((startTypeInstance == NULL) || (!startTypeInstance->IsStruct()))
  1861. return false;
  1862. auto checkTypeInstance = startTypeInstance;
  1863. while (checkTypeInstance != NULL)
  1864. {
  1865. for (auto& fieldInstance : checkTypeInstance->mFieldInstances)
  1866. {
  1867. if (fieldInstance.mMergedDataIdx != -1)
  1868. {
  1869. int64 checkMask = (int64)1 << fieldInstance.mMergedDataIdx;
  1870. if ((localVar->mUnassignedFieldFlags & checkMask) != 0)
  1871. {
  1872. // For fields added in extensions, we automatically initialize those if necessary
  1873. auto fieldDef = fieldInstance.GetFieldDef();
  1874. if (!fieldDef->mDeclaringType->IsExtension())
  1875. return false;
  1876. if ((fieldInstance.mDataIdx != -1) && (!mBfIRBuilder->mIgnoreWrites) && (!mCompiler->mIsResolveOnly) && (!mIsComptimeModule))
  1877. {
  1878. auto curInsertBlock = mBfIRBuilder->GetInsertBlock();
  1879. mBfIRBuilder->SaveDebugLocation();
  1880. if (localVar->IsParam())
  1881. mBfIRBuilder->SetInsertPointAtStart(mCurMethodState->mIRInitBlock);
  1882. else
  1883. {
  1884. BF_ASSERT(localVar->mDeclBlock);
  1885. mBfIRBuilder->SetInsertPointAtStart(localVar->mDeclBlock);
  1886. }
  1887. mBfIRBuilder->ClearDebugLocation();
  1888. BfIRValue curVal;
  1889. if (localVar->mIsThis)
  1890. curVal = mBfIRBuilder->GetArgument(0);
  1891. else
  1892. curVal = localVar->mAddr;
  1893. auto subTypeInstance = startTypeInstance;
  1894. while (subTypeInstance != checkTypeInstance)
  1895. {
  1896. curVal = mBfIRBuilder->CreateInBoundsGEP(curVal, 0, 0);
  1897. subTypeInstance = subTypeInstance->mBaseType;
  1898. }
  1899. auto fieldPtr = mBfIRBuilder->CreateInBoundsGEP(curVal, 0, fieldInstance.mDataIdx);
  1900. auto defVal = GetDefaultValue(fieldInstance.mResolvedType);
  1901. auto storeInst = mBfIRBuilder->CreateStore(defVal, fieldPtr);
  1902. mBfIRBuilder->SetInsertPoint(curInsertBlock);
  1903. mBfIRBuilder->RestoreDebugLocation();
  1904. }
  1905. localVar->mUnassignedFieldFlags &= ~checkMask;
  1906. if (localVar->mUnassignedFieldFlags == 0)
  1907. localVar->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  1908. }
  1909. }
  1910. }
  1911. checkTypeInstance = checkTypeInstance->mBaseType;
  1912. }
  1913. return localVar->mAssignedKind != BfLocalVarAssignKind_None;
  1914. }
  1915. void BfModule::LocalVariableDone(BfLocalVariable* localVar, bool isMethodExit)
  1916. {
  1917. //if (localVar->mAddr == NULL)
  1918. /*if ((localVar->mValue) && (!localVar->mAddr) && (IsTargetingBeefBackend()))
  1919. {
  1920. if ((!localVar->mValue.IsConst()) && (!localVar->mValue.IsArg()) && (!localVar->mValue.IsFake()))
  1921. {
  1922. if (mCurMethodInstance->mMethodDef->mName == "FuncA")
  1923. mBfIRBuilder->CreateLifetimeEnd(localVar->mValue);
  1924. }
  1925. }*/
  1926. BfAstNode* localNameNode = localVar->mNameNode;
  1927. if (localVar->mIsThis)
  1928. {
  1929. localNameNode = mCurMethodInstance->mMethodDef->GetRefNode();
  1930. }
  1931. if (localNameNode != NULL)
  1932. {
  1933. bool isOut = false;
  1934. if (localVar->mResolvedType->IsRef())
  1935. {
  1936. auto refType = (BfRefType*)localVar->mResolvedType;
  1937. isOut = refType->mRefKind == BfRefType::RefKind_Out;
  1938. }
  1939. if ((localVar->mReadFromId == -1) || (isOut) || ((localVar->mIsThis) && (mCurTypeInstance->IsStruct())))
  1940. {
  1941. if ((localVar->mAssignedKind != BfLocalVarAssignKind_Unconditional) & (localVar->IsParam()))
  1942. TryLocalVariableInit(localVar);
  1943. // We may skip processing of local methods, so we won't know if it bind to any of our local variables or not
  1944. bool deferFullAnalysis = mCurMethodState->GetRootMethodState()->mLocalMethodCache.size() != 0;
  1945. // We may have init blocks that we aren't processing here...
  1946. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mIsAutocompleteMethod) && (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_Ctor))
  1947. deferFullAnalysis = true;
  1948. //bool deferFullAnalysis = true;
  1949. bool deferUsageWarning = deferFullAnalysis && mCompiler->IsAutocomplete();
  1950. if (((localVar->mAssignedKind != BfLocalVarAssignKind_Unconditional) || (localVar->mHadExitBeforeAssign)) &&
  1951. (!localVar->mIsImplicitParam))
  1952. {
  1953. if (deferUsageWarning)
  1954. {
  1955. // Ignore
  1956. }
  1957. else if (localVar->mIsThis)
  1958. {
  1959. bool foundFields = false;
  1960. auto checkTypeInstance = mCurTypeInstance;
  1961. while (checkTypeInstance != NULL)
  1962. {
  1963. for (auto& fieldInstance : checkTypeInstance->mFieldInstances)
  1964. {
  1965. if (fieldInstance.mMergedDataIdx == -1)
  1966. continue;
  1967. int checkMask = 1 << fieldInstance.mMergedDataIdx;
  1968. if ((localVar->mUnassignedFieldFlags & checkMask) != 0)
  1969. {
  1970. auto fieldDef = fieldInstance.GetFieldDef();
  1971. if (mCurMethodInstance->mMethodDef->mDeclaringType->mIsPartial)
  1972. {
  1973. if (mCurMethodInstance->mMethodDef->mDeclaringType != fieldInstance.GetFieldDef()->mDeclaringType)
  1974. {
  1975. // This extension is only responsible for its own fields
  1976. foundFields = true;
  1977. continue;
  1978. }
  1979. if ((fieldDef->mFieldDeclaration != NULL) && (fieldDef->mFieldDeclaration->mInitializer != NULL))
  1980. {
  1981. // This initializer was handled in CtorNoBody
  1982. foundFields = true;
  1983. continue;
  1984. }
  1985. }
  1986. if (auto propertyDeclaration = BfNodeDynCast<BfPropertyDeclaration>(fieldDef->mFieldDeclaration))
  1987. {
  1988. String propName;
  1989. if (propertyDeclaration->mNameNode != NULL)
  1990. propertyDeclaration->mNameNode->ToString(propName);
  1991. if (checkTypeInstance == mCurTypeInstance)
  1992. {
  1993. Fail(StrFormat("Auto-implemented property '%s' must be fully assigned before control is returned to the caller",
  1994. propName.c_str()), localNameNode, deferFullAnalysis); // 0171
  1995. }
  1996. else
  1997. {
  1998. Fail(StrFormat("Auto-implemented property '%s.%s' must be fully assigned before control is returned to the caller",
  1999. TypeToString(checkTypeInstance).c_str(),
  2000. propName.c_str()), localNameNode, deferFullAnalysis); // 0171
  2001. }
  2002. }
  2003. else
  2004. {
  2005. if (checkTypeInstance == mCurTypeInstance)
  2006. {
  2007. Fail(StrFormat("Field '%s' must be fully assigned before control is returned to the caller",
  2008. fieldDef->mName.c_str()), localNameNode, deferFullAnalysis); // 0171
  2009. }
  2010. else
  2011. {
  2012. Fail(StrFormat("Field '%s.%s' must be fully assigned before control is returned to the caller",
  2013. TypeToString(checkTypeInstance).c_str(),
  2014. fieldDef->mName.c_str()), localNameNode, deferFullAnalysis); // 0171
  2015. }
  2016. }
  2017. foundFields = true;
  2018. }
  2019. }
  2020. checkTypeInstance = checkTypeInstance->mBaseType;
  2021. }
  2022. if (!foundFields)
  2023. {
  2024. if (mCurTypeInstance->mInstSize > 0)
  2025. Fail(StrFormat("The variable '%s' must be fully assigned to before control leaves the current method", localVar->mName.c_str()), localNameNode); // 0177
  2026. }
  2027. }
  2028. else if (localVar->IsParam())
  2029. Fail(StrFormat("The out parameter '%s' must be assigned to before control leaves the current method", localVar->mName.c_str()), localNameNode, deferFullAnalysis); // 0177
  2030. else if (!deferUsageWarning)
  2031. Warn(BfWarning_CS0168_VariableDeclaredButNeverUsed, StrFormat("The variable '%s' is declared but never used", localVar->mName.c_str()), localNameNode, deferFullAnalysis);
  2032. }
  2033. else if ((localVar->mReadFromId == -1) && (!localVar->IsParam()) && (!deferUsageWarning))
  2034. Warn(BfWarning_CS0168_VariableDeclaredButNeverUsed, StrFormat("The variable '%s' is assigned but its value is never used", localVar->mName.c_str()), localNameNode, deferFullAnalysis);
  2035. }
  2036. }
  2037. }
  2038. void BfModule::CreateRetValLocal()
  2039. {
  2040. if (mCurMethodState->mRetVal)
  2041. {
  2042. BfLocalVariable* localDef = new BfLocalVariable();
  2043. localDef->mName = "return";
  2044. localDef->mResolvedType = mCurMethodState->mRetVal.mType;
  2045. localDef->mAddr = mCurMethodState->mRetVal.mValue;
  2046. localDef->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  2047. AddLocalVariableDef(localDef);
  2048. }
  2049. else if (mCurMethodState->mRetValAddr)
  2050. {
  2051. BfLocalVariable* localDef = new BfLocalVariable();
  2052. localDef->mName = "return";
  2053. localDef->mResolvedType = CreateRefType(mCurMethodInstance->mReturnType);
  2054. localDef->mAddr = mCurMethodState->mRetValAddr;
  2055. localDef->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  2056. AddLocalVariableDef(localDef);
  2057. }
  2058. }
  2059. void BfModule::MarkDynStack(BfScopeData* scopeData)
  2060. {
  2061. auto checkScope = mCurMethodState->mCurScope;
  2062. while (true)
  2063. {
  2064. if (checkScope == scopeData)
  2065. break;
  2066. checkScope->mHadOuterDynStack = true;
  2067. checkScope = checkScope->mPrevScope;
  2068. }
  2069. }
  2070. void BfModule::SaveStackState(BfScopeData* scopeData)
  2071. {
  2072. // If we push a value on the stack that needs to survive until the end of scopeData, we need to make sure that no
  2073. // scopes within scopeData restore the stack
  2074. auto checkScope = mCurMethodState->mCurScope;
  2075. while (true)
  2076. {
  2077. if (checkScope == scopeData)
  2078. {
  2079. if ((!checkScope->mSavedStack) && (checkScope->mBlock) && (!checkScope->mIsScopeHead) && (!checkScope->mHadOuterDynStack))
  2080. {
  2081. if (mBfIRBuilder->mHasDebugInfo)
  2082. mBfIRBuilder->SaveDebugLocation();
  2083. auto prevPos = mBfIRBuilder->GetInsertBlock();
  2084. mBfIRBuilder->SetInsertPointAtStart(checkScope->mBlock);
  2085. checkScope->mSavedStack = mBfIRBuilder->CreateStackSave();
  2086. mBfIRBuilder->ClearDebugLocation(checkScope->mSavedStack);
  2087. mBfIRBuilder->SetInsertPoint(prevPos);
  2088. if (mBfIRBuilder->mHasDebugInfo)
  2089. mBfIRBuilder->RestoreDebugLocation();
  2090. }
  2091. break;
  2092. }
  2093. if (checkScope->mSavedStack)
  2094. {
  2095. for (auto usage : checkScope->mSavedStackUses)
  2096. mBfIRBuilder->EraseInstFromParent(usage);
  2097. checkScope->mSavedStackUses.Clear();
  2098. mBfIRBuilder->EraseInstFromParent(checkScope->mSavedStack);
  2099. checkScope->mSavedStack = BfIRValue();
  2100. }
  2101. checkScope = checkScope->mPrevScope;
  2102. }
  2103. }
  2104. BfIRValue BfModule::ValueScopeStart()
  2105. {
  2106. if (IsTargetingBeefBackend())
  2107. return mBfIRBuilder->CreateValueScopeStart();
  2108. return BfIRValue();
  2109. }
  2110. void BfModule::ValueScopeEnd(BfIRValue valueScopeStart)
  2111. {
  2112. if (valueScopeStart)
  2113. mBfIRBuilder->CreateValueScopeHardEnd(valueScopeStart);
  2114. }
  2115. BfProjectSet* BfModule::GetVisibleProjectSet()
  2116. {
  2117. if (mCurMethodState == NULL)
  2118. return NULL;
  2119. if (mCurMethodState->mVisibleProjectSet.IsEmpty())
  2120. {
  2121. HashSet<BfType*> seenTypes;
  2122. std::function<void(BfProject* project)> _AddProject = [&](BfProject* project)
  2123. {
  2124. if (mCurMethodState->mVisibleProjectSet.Add(project))
  2125. {
  2126. for (auto dep : project->mDependencies)
  2127. _AddProject(dep);
  2128. }
  2129. };
  2130. std::function<void(BfType* type)> _AddType = [&](BfType* type)
  2131. {
  2132. auto typeInstance = type->ToTypeInstance();
  2133. if (typeInstance == NULL)
  2134. {
  2135. if (type->IsSizedArray())
  2136. _AddType(type->GetUnderlyingType());
  2137. return;
  2138. }
  2139. if (typeInstance->IsTuple())
  2140. {
  2141. for (auto& fieldInst : typeInstance->mFieldInstances)
  2142. {
  2143. if (fieldInst.mDataIdx != -1)
  2144. _AddType(fieldInst.mResolvedType);
  2145. }
  2146. }
  2147. _AddProject(typeInstance->mTypeDef->mProject);
  2148. if (typeInstance->mGenericTypeInfo == NULL)
  2149. return;
  2150. for (auto type : typeInstance->mGenericTypeInfo->mTypeGenericArguments)
  2151. {
  2152. if (seenTypes.Add(type))
  2153. _AddType(type);
  2154. }
  2155. };
  2156. if (mCurTypeInstance != NULL)
  2157. _AddType(mCurTypeInstance);
  2158. auto methodState = mCurMethodState;
  2159. while (methodState != NULL)
  2160. {
  2161. if (methodState->mMethodInstance != NULL)
  2162. {
  2163. _AddProject(methodState->mMethodInstance->mMethodDef->mDeclaringType->mProject);
  2164. if (methodState->mMethodInstance->mMethodInfoEx != NULL)
  2165. {
  2166. for (auto type : methodState->mMethodInstance->mMethodInfoEx->mMethodGenericArguments)
  2167. _AddType(type);
  2168. }
  2169. }
  2170. methodState = methodState->mPrevMethodState;
  2171. }
  2172. }
  2173. return &mCurMethodState->mVisibleProjectSet;
  2174. }
  2175. BfFileInstance* BfModule::GetFileFromNode(BfAstNode* astNode)
  2176. {
  2177. auto bfParser = astNode->GetSourceData()->ToParserData();
  2178. if (bfParser == NULL)
  2179. return NULL;
  2180. BfFileInstance** fileInstancePtr = NULL;
  2181. if (!mFileInstanceMap.TryAdd(bfParser, NULL, &fileInstancePtr))
  2182. {
  2183. return *fileInstancePtr;
  2184. }
  2185. else
  2186. {
  2187. // It's possible two parsers have the same file name (ie: mNextRevision)
  2188. BfFileInstance** namedFileInstancePtr = NULL;
  2189. if (!mNamedFileInstanceMap.TryAdd(bfParser->mFileName, NULL, &namedFileInstancePtr))
  2190. {
  2191. auto bfFileInstance = *namedFileInstancePtr;
  2192. *fileInstancePtr = bfFileInstance;
  2193. return bfFileInstance;
  2194. }
  2195. int slashPos = (int)bfParser->mFileName.LastIndexOf(DIR_SEP_CHAR);
  2196. auto bfFileInstance = new BfFileInstance();
  2197. *fileInstancePtr = bfFileInstance;
  2198. *namedFileInstancePtr = bfFileInstance;
  2199. bfFileInstance->mPrevPosition.mFileInstance = bfFileInstance;
  2200. bfFileInstance->mParser = bfParser;
  2201. BfLogSysM("GetFileFromNode new file. Mod: %p FileInstance: %p Parser: %p\n", this, bfFileInstance, bfParser);
  2202. if ((mBfIRBuilder != NULL) && (mBfIRBuilder->DbgHasLineInfo()))
  2203. {
  2204. String fileName = bfParser->mFileName;
  2205. for (int i = 0; i < (int)fileName.length(); i++)
  2206. {
  2207. if (fileName[i] == DIR_SEP_CHAR_ALT)
  2208. fileName[i] = DIR_SEP_CHAR;
  2209. }
  2210. bfFileInstance->mDIFile = mBfIRBuilder->DbgCreateFile(fileName.Substring(slashPos + 1), fileName.Substring(0, BF_MAX(slashPos, 0)), bfParser->mMD5Hash);
  2211. }
  2212. return bfFileInstance;
  2213. }
  2214. }
  2215. void BfModule::UpdateSrcPos(BfAstNode* astNode, BfSrcPosFlags flags, int debugLocOffset)
  2216. {
  2217. // We set force to true when we MUST get the line position set (for navigation purposes, for example)
  2218. if (((mBfIRBuilder->mIgnoreWrites)) && ((flags & BfSrcPosFlag_Force) == 0))
  2219. return;
  2220. BF_ASSERT((!mAwaitingInitFinish) || (mBfIRBuilder->mIgnoreWrites));
  2221. if (astNode == NULL)
  2222. return;
  2223. auto bfParser = astNode->GetSourceData()->ToParserData();
  2224. if (bfParser == NULL)
  2225. return;
  2226. if ((mCurFilePosition.mFileInstance == NULL) || (mCurFilePosition.mFileInstance->mParser != bfParser))
  2227. {
  2228. if (mCurFilePosition.mFileInstance != NULL)
  2229. {
  2230. BF_ASSERT(mFileInstanceMap.GetCount() != 0);
  2231. mCurFilePosition.mFileInstance->mPrevPosition = mCurFilePosition;
  2232. }
  2233. auto bfFileInstance = GetFileFromNode(astNode);
  2234. if (bfFileInstance->mPrevPosition.mFileInstance != NULL)
  2235. {
  2236. mCurFilePosition = bfFileInstance->mPrevPosition;
  2237. }
  2238. else
  2239. {
  2240. mCurFilePosition.mFileInstance = bfFileInstance;
  2241. mCurFilePosition.mCurLine = 0;
  2242. mCurFilePosition.mCurSrcPos = 0;
  2243. }
  2244. }
  2245. int srcPos = astNode->GetSrcStart() + debugLocOffset;
  2246. BF_ASSERT(srcPos < bfParser->mSrcLength);
  2247. auto* jumpEntry = bfParser->mJumpTable + (srcPos / PARSER_JUMPTABLE_DIVIDE);
  2248. if (jumpEntry->mCharIdx > srcPos)
  2249. jumpEntry--;
  2250. mCurFilePosition.mCurLine = jumpEntry->mLineNum;
  2251. mCurFilePosition.mCurSrcPos = jumpEntry->mCharIdx;
  2252. mCurFilePosition.mCurColumn = 0;
  2253. while (mCurFilePosition.mCurSrcPos < srcPos)
  2254. {
  2255. if (bfParser->mSrc[mCurFilePosition.mCurSrcPos] == '\n')
  2256. {
  2257. mCurFilePosition.mCurLine++;
  2258. mCurFilePosition.mCurColumn = 0;
  2259. }
  2260. else
  2261. {
  2262. mCurFilePosition.mCurColumn++;
  2263. }
  2264. mCurFilePosition.mCurSrcPos++;
  2265. }
  2266. //TODO: if we bail on the "mCurMethodState == NULL" case then we don't get it set during type declarations
  2267. if (((flags & BfSrcPosFlag_NoSetDebugLoc) == 0) && (mBfIRBuilder->DbgHasLineInfo()) && (mCurMethodState != NULL))
  2268. {
  2269. int column = mCurFilePosition.mCurColumn + 1;
  2270. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend))
  2271. {
  2272. // Set to illegal position
  2273. column = 0;
  2274. }
  2275. if (mSetIllegalSrcPosition)
  2276. column = 0;
  2277. BfIRMDNode useDIScope = mCurMethodState->mCurScope->mDIScope;
  2278. auto wantDIFile = mCurFilePosition.mFileInstance->mDIFile;
  2279. if ((wantDIFile != mCurMethodState->mDIFile) && (mCurMethodState->mDIFile))
  2280. {
  2281. // This is from a different scope...
  2282. if (wantDIFile != mCurMethodState->mCurScope->mAltDIFile)
  2283. {
  2284. mCurMethodState->mCurScope->mAltDIFile = wantDIFile;
  2285. mCurMethodState->mCurScope->mAltDIScope = mBfIRBuilder->DbgCreateLexicalBlock(mCurMethodState->mCurScope->mDIScope, wantDIFile, mCurFilePosition.mCurLine + 1, column);
  2286. }
  2287. if (mCurMethodState->mCurScope->mAltDIScope) // This may not be set if mAltDIFile is set by a mixin
  2288. useDIScope = mCurMethodState->mCurScope->mAltDIScope;
  2289. }
  2290. else
  2291. {
  2292. if (mCurMethodState->mCurScope->mAltDIFile)
  2293. {
  2294. mCurMethodState->mCurScope->mAltDIFile = BfIRMDNode();
  2295. mCurMethodState->mCurScope->mAltDIScope = BfIRMDNode();
  2296. }
  2297. }
  2298. auto inlineAt = mCurMethodState->mCurScope->mDIInlinedAt;
  2299. if (mCurMethodState->mCrossingMixin)
  2300. inlineAt = BfIRMDNode();
  2301. if ((!useDIScope) && (mIsComptimeModule))
  2302. useDIScope = wantDIFile;
  2303. if (!useDIScope)
  2304. mBfIRBuilder->ClearDebugLocation();
  2305. else
  2306. mBfIRBuilder->SetCurrentDebugLocation(mCurFilePosition.mCurLine + 1, column, useDIScope, inlineAt);
  2307. if ((flags & BfSrcPosFlag_Expression) == 0)
  2308. mBfIRBuilder->CreateStatementStart();
  2309. }
  2310. }
  2311. void BfModule::UpdateExprSrcPos(BfAstNode* astNode, BfSrcPosFlags flags)
  2312. {
  2313. // We've turned off expr src pos (for now?)
  2314. //UpdateSrcPos(astNode, (BfSrcPosFlags)(flags | BfSrcPosFlag_Expression));
  2315. }
  2316. void BfModule::UseDefaultSrcPos(BfSrcPosFlags flags, int debugLocOffset)
  2317. {
  2318. if (mCompiler->mBfObjectTypeDef != NULL)
  2319. UpdateSrcPos(mCompiler->mBfObjectTypeDef->mTypeDeclaration, flags, debugLocOffset);
  2320. SetIllegalSrcPos();
  2321. }
  2322. void BfModule::SetIllegalSrcPos(BfSrcPosFlags flags)
  2323. {
  2324. if ((mBfIRBuilder->DbgHasInfo()) && (mCurMethodState != NULL))
  2325. {
  2326. auto curScope = mCurMethodState->mCurScope->mDIScope;
  2327. if (curScope)
  2328. {
  2329. if ((mCurMethodState->mCurScope->mDIInlinedAt) && (mCompiler->mOptions.IsCodeView()))
  2330. {
  2331. // Currently, CodeView does not record column positions so we can't use an illegal column position as an "invalid" marker
  2332. mBfIRBuilder->SetCurrentDebugLocation(0, 0, curScope, mCurMethodState->mCurScope->mDIInlinedAt);
  2333. }
  2334. else
  2335. {
  2336. // Set to whatever it previously was but at column zero, which we will know to be illegal
  2337. mBfIRBuilder->SetCurrentDebugLocation(mCurFilePosition.mCurLine + 1, 0, curScope, mCurMethodState->mCurScope->mDIInlinedAt);
  2338. }
  2339. }
  2340. if ((flags & BfSrcPosFlag_Expression) == 0)
  2341. mBfIRBuilder->CreateStatementStart();
  2342. }
  2343. }
  2344. void BfModule::SetIllegalExprSrcPos(BfSrcPosFlags flags)
  2345. {
  2346. // We've turned off expr src pos (for now?)
  2347. //SetIllegalSrcPos((BfSrcPosFlags)(flags | BfSrcPosFlag_Expression));
  2348. }
  2349. bool BfModule::CheckProtection(BfProtection protection, BfTypeDef* checkType, bool allowProtected, bool allowPrivate)
  2350. {
  2351. if ((protection == BfProtection_Public) ||
  2352. (((protection == BfProtection_Protected) || (protection == BfProtection_ProtectedInternal)) && (allowProtected)) ||
  2353. ((protection == BfProtection_Private) && (allowPrivate)))
  2354. return true;
  2355. if ((mAttributeState != NULL) && (mAttributeState->mCustomAttributes != NULL) && (mAttributeState->mCustomAttributes->Contains(mCompiler->mFriendAttributeTypeDef)))
  2356. {
  2357. mAttributeState->mUsed = true;
  2358. return true;
  2359. }
  2360. if (((protection == BfProtection_Internal) || (protection == BfProtection_ProtectedInternal)) && (checkType != NULL))
  2361. {
  2362. if (CheckInternalProtection(checkType))
  2363. return true;
  2364. }
  2365. return false;
  2366. }
  2367. void BfModule::GetAccessAllowed(BfTypeInstance* checkType, bool &allowProtected, bool &allowPrivate)
  2368. {
  2369. allowPrivate = (checkType == mCurTypeInstance) || (IsInnerType(mCurTypeInstance, checkType));
  2370. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL))
  2371. {
  2372. auto mixinOwner = mCurMethodState->mMixinState->mMixinMethodInstance->GetOwner();
  2373. allowPrivate |= (checkType == mixinOwner) || (IsInnerType(mixinOwner, checkType));
  2374. }
  2375. allowProtected = allowPrivate;
  2376. }
  2377. bool BfModule::CheckProtection(BfProtectionCheckFlags& flags, BfTypeInstance* memberOwner, BfProject* memberProject, BfProtection memberProtection, BfTypeInstance* lookupStartType)
  2378. {
  2379. if (memberProtection == BfProtection_Hidden)
  2380. return false;
  2381. if (memberProtection == BfProtection_Public)
  2382. return true;
  2383. if ((flags & BfProtectionCheckFlag_CheckedPrivate) == 0)
  2384. {
  2385. BfTypeInstance* curCheckType = mCurTypeInstance;
  2386. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL))
  2387. {
  2388. auto mixinOwner = mCurMethodState->mMixinState->mMixinMethodInstance->GetOwner();
  2389. curCheckType = mixinOwner;
  2390. }
  2391. bool allowPrivate = (curCheckType != NULL) && (memberOwner->IsInstanceOf(curCheckType->mTypeDef));
  2392. if (curCheckType != NULL)
  2393. allowPrivate |= IsInnerType(curCheckType->mTypeDef, memberOwner->mTypeDef);
  2394. if (allowPrivate)
  2395. flags = (BfProtectionCheckFlags)(flags | BfProtectionCheckFlag_AllowPrivate | BfProtectionCheckFlag_CheckedPrivate);
  2396. else
  2397. flags = (BfProtectionCheckFlags)(flags | BfProtectionCheckFlag_CheckedPrivate);
  2398. }
  2399. if ((flags & BfProtectionCheckFlag_AllowPrivate) != 0)
  2400. return true;
  2401. if ((memberProtection == BfProtection_Protected) || (memberProtection == BfProtection_ProtectedInternal))
  2402. {
  2403. if ((flags & BfProtectionCheckFlag_CheckedProtected) == 0)
  2404. {
  2405. bool allowProtected = false;
  2406. auto memberOwnerTypeDef = memberOwner->mTypeDef;
  2407. auto curCheckType = mCurTypeInstance;
  2408. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL))
  2409. {
  2410. auto mixinOwner = mCurMethodState->mMixinState->mMixinMethodInstance->GetOwner();
  2411. curCheckType = mixinOwner;
  2412. }
  2413. if ((flags & BfProtectionCheckFlag_InstanceLookup) != 0)
  2414. {
  2415. auto lookupCheckType = lookupStartType;
  2416. while (lookupCheckType->mInheritDepth >= curCheckType->mInheritDepth)
  2417. {
  2418. if (lookupCheckType == curCheckType)
  2419. {
  2420. allowProtected = true;
  2421. break;
  2422. }
  2423. if (lookupCheckType == memberOwner)
  2424. break;
  2425. lookupCheckType = lookupCheckType->mBaseType;
  2426. if (lookupCheckType == NULL)
  2427. break;
  2428. }
  2429. }
  2430. else
  2431. {
  2432. auto lookupCheckType = curCheckType;
  2433. while (lookupCheckType->mInheritDepth >= memberOwner->mInheritDepth)
  2434. {
  2435. if (lookupCheckType == memberOwner)
  2436. {
  2437. allowProtected = true;
  2438. break;
  2439. }
  2440. lookupCheckType = lookupCheckType->mBaseType;
  2441. if (lookupCheckType == NULL)
  2442. break;
  2443. }
  2444. }
  2445. if (!allowProtected)
  2446. {
  2447. // It's possible our outer type is derived from 'memberOwner'
  2448. while (curCheckType->mTypeDef->mNestDepth > 0)
  2449. {
  2450. curCheckType = GetOuterType(curCheckType);
  2451. if (curCheckType == NULL)
  2452. break;
  2453. auto lookupCheckType = lookupStartType;
  2454. while (lookupCheckType->mInheritDepth >= curCheckType->mInheritDepth)
  2455. {
  2456. if (lookupCheckType == curCheckType)
  2457. {
  2458. allowProtected = true;
  2459. break;
  2460. }
  2461. if (lookupCheckType == memberOwner)
  2462. break;
  2463. lookupCheckType = lookupCheckType->mBaseType;
  2464. if (lookupCheckType == NULL)
  2465. break;
  2466. }
  2467. }
  2468. }
  2469. if (allowProtected)
  2470. flags = (BfProtectionCheckFlags)(flags | BfProtectionCheckFlag_CheckedProtected | BfProtectionCheckFlag_AllowProtected);
  2471. else
  2472. flags = (BfProtectionCheckFlags)(flags | BfProtectionCheckFlag_CheckedProtected);
  2473. }
  2474. if ((flags & BfProtectionCheckFlag_AllowProtected) != 0)
  2475. return true;
  2476. }
  2477. if ((mAttributeState != NULL) && (mAttributeState->mCustomAttributes != NULL) && (mAttributeState->mCustomAttributes->Contains(mCompiler->mFriendAttributeTypeDef)))
  2478. {
  2479. mAttributeState->mUsed = true;
  2480. return true;
  2481. }
  2482. if (((memberProtection == BfProtection_Internal) || (memberProtection == BfProtection_ProtectedInternal)) && (memberOwner != NULL))
  2483. {
  2484. if (CheckInternalProtection(memberOwner->mTypeDef))
  2485. return true;
  2486. }
  2487. return false;
  2488. }
  2489. void BfModule::SetElementType(BfAstNode* astNode, BfSourceElementType elementType)
  2490. {
  2491. if ((mCompiler->mResolvePassData != NULL) &&
  2492. (mCompiler->mResolvePassData->mSourceClassifier != NULL) &&
  2493. (astNode->IsFromParser(mCompiler->mResolvePassData->mParser)))
  2494. {
  2495. mCompiler->mResolvePassData->mSourceClassifier->SetElementType(astNode, elementType);
  2496. }
  2497. }
  2498. bool BfModule::PreFail()
  2499. {
  2500. if (!mIgnoreErrors)
  2501. return true;
  2502. SetFail();
  2503. return false;
  2504. }
  2505. void BfModule::SetFail()
  2506. {
  2507. if (mIgnoreErrors)
  2508. {
  2509. if (mAttributeState != NULL)
  2510. mAttributeState->mFlags = (BfAttributeState::Flags)(mAttributeState->mFlags | BfAttributeState::Flag_HadError);
  2511. }
  2512. }
  2513. void BfModule::VerifyOnDemandMethods()
  2514. {
  2515. #ifdef _DEBUG
  2516. // if (mParentModule != NULL)
  2517. // {
  2518. // BF_ASSERT(mOnDemandMethodCount == 0);
  2519. // mParentModule->VerifyOnDemandMethods();
  2520. // return;
  2521. // }
  2522. //
  2523. // int onDemandCount = 0;
  2524. // for (auto type : mOwnedTypeInstances)
  2525. // {
  2526. // auto typeInst = type->ToTypeInstance();
  2527. // for (auto& methodGroup : typeInst->mMethodInstanceGroups)
  2528. // {
  2529. // if ((methodGroup.mOnDemandKind == BfMethodOnDemandKind_NoDecl_AwaitingReference) ||
  2530. // (methodGroup.mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingReference) ||
  2531. // (methodGroup.mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingDecl) ||
  2532. // (methodGroup.mOnDemandKind == BfMethodOnDemandKind_InWorkList))
  2533. // onDemandCount++;
  2534. // }
  2535. // }
  2536. //
  2537. // BF_ASSERT(mOnDemandMethodCount == onDemandCount);
  2538. #endif
  2539. }
  2540. bool BfModule::IsSkippingExtraResolveChecks()
  2541. {
  2542. if (mIsComptimeModule)
  2543. return false;
  2544. return mCompiler->IsSkippingExtraResolveChecks();
  2545. }
  2546. bool BfModule::AddErrorContext(StringImpl& errorString, BfAstNode* refNode, bool& isWhileSpecializing, bool isWarning)
  2547. {
  2548. bool isWhileSpecializingMethod = false;
  2549. if ((mIsSpecialModule) && (mModuleName == "vdata"))
  2550. errorString += StrFormat("\n while generating vdata for project '%s'", mProject->mName.c_str());
  2551. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend))
  2552. errorString += StrFormat("\n while generating append size calculating method");
  2553. else if (refNode == NULL)
  2554. {
  2555. if (mCurTypeInstance != NULL)
  2556. errorString += StrFormat("\n while compiling '%s'", TypeToString(mCurTypeInstance, BfTypeNameFlags_None).c_str());
  2557. else if (mProject != NULL)
  2558. errorString += StrFormat("\n while compiling project '%s'", mProject->mName.c_str());
  2559. }
  2560. if (mCurTypeInstance != NULL)
  2561. {
  2562. auto _CheckMethodInstance = [&](BfMethodInstance* methodInstance)
  2563. {
  2564. // Propogate the fail all the way to the main method (assuming we're in a local method or lambda)
  2565. if (isWarning)
  2566. methodInstance->mHasWarning = true;
  2567. else
  2568. methodInstance->mHasFailed = true;
  2569. if (!methodInstance->mHasStartedDeclaration)
  2570. StartMethodDeclaration(methodInstance, NULL);
  2571. bool isSpecializedMethod = ((methodInstance != NULL) && (!methodInstance->mIsUnspecialized) && (methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mMethodGenericArguments.size() != 0));
  2572. if (isSpecializedMethod)
  2573. {
  2574. //auto unspecializedMethod = &mCurMethodInstance->mMethodInstanceGroup->mMethodSpecializationMap.begin()->second;
  2575. auto unspecializedMethod = methodInstance->mMethodInstanceGroup->mDefault;
  2576. if (unspecializedMethod == methodInstance)
  2577. {
  2578. // This is a local method inside a generic method
  2579. BF_ASSERT(methodInstance->mMethodDef->mIsLocalMethod);
  2580. }
  2581. else
  2582. {
  2583. if (isWarning)
  2584. {
  2585. if (unspecializedMethod->mHasWarning)
  2586. return false; // At least SOME error has already been reported
  2587. }
  2588. else
  2589. {
  2590. if (unspecializedMethod->mHasFailed)
  2591. return false; // At least SOME error has already been reported
  2592. }
  2593. }
  2594. }
  2595. if (isSpecializedMethod)
  2596. {
  2597. errorString += StrFormat("\n while specializing method '%s'", MethodToString(methodInstance).c_str());
  2598. isWhileSpecializing = true;
  2599. isWhileSpecializingMethod = true;
  2600. }
  2601. else if ((methodInstance != NULL) && (methodInstance->mIsForeignMethodDef))
  2602. {
  2603. errorString += StrFormat("\n while implementing default interface method '%s'", MethodToString(methodInstance).c_str());
  2604. isWhileSpecializing = true;
  2605. isWhileSpecializingMethod = true;
  2606. }
  2607. else if ((mCurTypeInstance->IsGenericTypeInstance()) && (!mCurTypeInstance->IsUnspecializedType()))
  2608. {
  2609. errorString += StrFormat("\n while specializing type '%s'", TypeToString(mCurTypeInstance).c_str());
  2610. isWhileSpecializing = true;
  2611. }
  2612. return true;
  2613. };
  2614. bool hadMethodInstance = false;
  2615. if (mCurMethodState != NULL)
  2616. {
  2617. auto checkMethodState = mCurMethodState;
  2618. while (checkMethodState != NULL)
  2619. {
  2620. auto methodInstance = checkMethodState->mMethodInstance;
  2621. if (methodInstance == NULL)
  2622. {
  2623. checkMethodState = checkMethodState->mPrevMethodState;
  2624. continue;
  2625. }
  2626. hadMethodInstance = true;
  2627. if (!_CheckMethodInstance(methodInstance))
  2628. return false;
  2629. checkMethodState = checkMethodState->mPrevMethodState;
  2630. }
  2631. }
  2632. if ((!hadMethodInstance) && (mCurMethodInstance != NULL))
  2633. {
  2634. if (!_CheckMethodInstance(mCurMethodInstance))
  2635. return false;
  2636. }
  2637. }
  2638. if ((!isWhileSpecializing) && (mCurTypeInstance != NULL) && ((mCurTypeInstance->IsGenericTypeInstance()) && (!mCurTypeInstance->IsUnspecializedType())))
  2639. {
  2640. errorString += StrFormat("\n while specializing type '%s'", TypeToString(mCurTypeInstance).c_str());
  2641. isWhileSpecializing = true;
  2642. }
  2643. return true;
  2644. }
  2645. BfError* BfModule::Fail(const StringImpl& error, BfAstNode* refNode, bool isPersistent, bool deferError)
  2646. {
  2647. BP_ZONE("BfModule::Fail");
  2648. if (mIgnoreErrors)
  2649. {
  2650. mHadIgnoredError = true;
  2651. if (mAttributeState != NULL)
  2652. mAttributeState->mFlags = (BfAttributeState::Flags)(mAttributeState->mFlags | BfAttributeState::Flag_HadError);
  2653. return NULL;
  2654. }
  2655. if (!mReportErrors)
  2656. {
  2657. mCompiler->mPassInstance->SilentFail();
  2658. return NULL;
  2659. }
  2660. if (refNode != NULL)
  2661. refNode = BfNodeToNonTemporary(refNode);
  2662. //BF_ASSERT(refNode != NULL);
  2663. if (mIsComptimeModule)
  2664. {
  2665. if ((mCompiler->mCEMachine->mCurContext != NULL) && (mCompiler->mCEMachine->mCurContext->mCurTargetSrc != NULL))
  2666. {
  2667. BfError* bfError = mCompiler->mPassInstance->Fail("Comptime method generation had errors", mCompiler->mCEMachine->mCurContext->mCurTargetSrc);
  2668. if (bfError != NULL)
  2669. mCompiler->mPassInstance->MoreInfo(error, refNode);
  2670. return bfError;
  2671. }
  2672. mHadBuildError = true;
  2673. return NULL;
  2674. }
  2675. if (mCurMethodInstance != NULL)
  2676. mCurMethodInstance->mHasFailed = true;
  2677. if ((mCurTypeInstance != NULL) && (mCurTypeInstance->IsUnspecializedTypeVariation()))
  2678. return NULL;
  2679. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->IsOrInUnspecializedVariation()))
  2680. return NULL; // Ignore errors on unspecialized variations, they are always dups
  2681. if (!mHadBuildError)
  2682. mHadBuildError = true;
  2683. if (mParentModule != NULL)
  2684. mParentModule->mHadBuildError = true;
  2685. if (mCurTypeInstance != NULL)
  2686. AddFailType(mCurTypeInstance);
  2687. BfLogSysM("BfModule::Fail module %p type %p %s\n", this, mCurTypeInstance, error.c_str());
  2688. String errorString = error;
  2689. bool isWhileSpecializing = false;
  2690. if (!AddErrorContext(errorString, refNode, isWhileSpecializing, false))
  2691. return NULL;
  2692. BfError* bfError = NULL;
  2693. if (isWhileSpecializing)
  2694. deferError = true;
  2695. if (!mHadBuildError)
  2696. mHadBuildError = true;
  2697. if ((mCurMethodState != NULL) && (mCurMethodState->mEmitRefNode != NULL))
  2698. {
  2699. bfError = mCompiler->mPassInstance->Fail("Emitted code had errors", mCurMethodState->mEmitRefNode);
  2700. if (bfError != NULL)
  2701. mCompiler->mPassInstance->MoreInfo(errorString, refNode);
  2702. return bfError;
  2703. }
  2704. // Check mixins
  2705. {
  2706. auto checkMethodState = mCurMethodState;
  2707. while (checkMethodState != NULL)
  2708. {
  2709. auto rootMixinState = checkMethodState->GetRootMixinState();
  2710. if (rootMixinState != NULL)
  2711. {
  2712. String mixinErr = StrFormat("Failed to inject mixin '%s'", MethodToString(rootMixinState->mMixinMethodInstance).c_str());
  2713. if (deferError)
  2714. bfError = mCompiler->mPassInstance->DeferFail(mixinErr, rootMixinState->mSource);
  2715. else
  2716. bfError = mCompiler->mPassInstance->Fail(mixinErr, rootMixinState->mSource);
  2717. if (bfError == NULL)
  2718. return NULL;
  2719. bfError->mIsWhileSpecializing = isWhileSpecializing;
  2720. mCompiler->mPassInstance->MoreInfo(errorString, refNode);
  2721. auto mixinState = checkMethodState->mMixinState;
  2722. while ((mixinState != NULL) && (mixinState->mPrevMixinState != NULL))
  2723. {
  2724. mCompiler->mPassInstance->MoreInfo(StrFormat("Injected from mixin '%s'", MethodToString(mixinState->mPrevMixinState->mMixinMethodInstance).c_str()), mixinState->mSource);
  2725. mixinState = mixinState->mPrevMixinState;
  2726. }
  2727. return bfError;
  2728. }
  2729. checkMethodState = checkMethodState->mPrevMethodState;
  2730. }
  2731. }
  2732. if (deferError)
  2733. bfError = mCompiler->mPassInstance->Fail(errorString, refNode);
  2734. else if (refNode == NULL)
  2735. bfError = mCompiler->mPassInstance->Fail(errorString);
  2736. else
  2737. bfError = mCompiler->mPassInstance->Fail(errorString, refNode);
  2738. if (bfError != NULL)
  2739. {
  2740. bfError->mIsWhileSpecializing = isWhileSpecializing;
  2741. bfError->mProject = mProject;
  2742. bfError->mIsPersistent = isPersistent;
  2743. if ((mCurMethodState != NULL) && (mCurMethodState->mDeferredCallEmitState != NULL) && (mCurMethodState->mDeferredCallEmitState->mCloseNode != NULL))
  2744. mCompiler->mPassInstance->MoreInfo("Error during deferred statement handling", mCurMethodState->mDeferredCallEmitState->mCloseNode);
  2745. }
  2746. return bfError;
  2747. }
  2748. BfError* BfModule::FailInternal(const StringImpl& error, BfAstNode* refNode)
  2749. {
  2750. if (mHadBuildError)
  2751. return NULL;
  2752. return Fail(error, refNode);
  2753. }
  2754. BfError* BfModule::FailAfter(const StringImpl& error, BfAstNode* refNode)
  2755. {
  2756. if (mIgnoreErrors)
  2757. return NULL;
  2758. if (refNode != NULL)
  2759. refNode = BfNodeToNonTemporary(refNode);
  2760. mHadBuildError = true;
  2761. BfError* bfError = mCompiler->mPassInstance->FailAfter(error, refNode);
  2762. if (bfError != NULL)
  2763. bfError->mProject = mProject;
  2764. return bfError;
  2765. }
  2766. BfError* BfModule::Warn(int warningNum, const StringImpl& warning, BfAstNode* refNode, bool isPersistent, bool showInSpecialized)
  2767. {
  2768. if (mIgnoreErrors || mIgnoreWarnings)
  2769. return NULL;
  2770. if (!mReportErrors)
  2771. {
  2772. mCompiler->mPassInstance->SilentFail();
  2773. return NULL;
  2774. }
  2775. BfAstNode* unwarnNode = refNode;
  2776. //
  2777. {
  2778. BfParentNodeEntry* parentNodeEntry = mParentNodeEntry;
  2779. while (parentNodeEntry != NULL)
  2780. {
  2781. if (auto block = BfNodeDynCast<BfBlock>(parentNodeEntry->mNode))
  2782. break;
  2783. unwarnNode = parentNodeEntry->mNode;
  2784. parentNodeEntry = parentNodeEntry->mPrev;
  2785. }
  2786. }
  2787. auto parser = unwarnNode->GetSourceData()->ToParserData();
  2788. if ((parser != NULL) && (parser->IsUnwarnedAt(unwarnNode)))
  2789. {
  2790. return NULL;
  2791. }
  2792. // Right now we're only warning on the unspecialized declarations, we may revisit this
  2793. if (mCurMethodInstance != NULL)
  2794. {
  2795. if (mCurMethodInstance->IsSpecializedGenericMethodOrType())
  2796. {
  2797. if (!showInSpecialized)
  2798. return NULL;
  2799. }
  2800. if (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend)
  2801. return NULL; // No ctorCalcAppend warnings
  2802. }
  2803. if ((mCurTypeInstance != NULL) && (mCurTypeInstance->IsSpecializedType()))
  2804. {
  2805. if (!showInSpecialized)
  2806. return NULL;
  2807. }
  2808. if (refNode != NULL)
  2809. refNode = BfNodeToNonTemporary(refNode);
  2810. String warningString = warning;
  2811. bool isWhileSpecializing = false;
  2812. if (!AddErrorContext(warningString, refNode, isWhileSpecializing, true))
  2813. return NULL;
  2814. bool deferWarning = isWhileSpecializing;
  2815. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL))
  2816. {
  2817. // We used to bubble up warnings into the mixin injection site, BUT
  2818. // we are now assuming any relevant warnings will be given at the declaration site
  2819. return NULL;
  2820. }
  2821. if ((mCurMethodState != NULL) && (mCurMethodState->mEmitRefNode != NULL))
  2822. {
  2823. BfError* bfError = mCompiler->mPassInstance->Warn(warningNum, "Emitted code had errors", mCurMethodState->mEmitRefNode);
  2824. if (bfError != NULL)
  2825. mCompiler->mPassInstance->MoreInfo(warningString, refNode);
  2826. return bfError;
  2827. }
  2828. BfError* bfError;
  2829. if (refNode != NULL)
  2830. bfError = mCompiler->mPassInstance->WarnAt(warningNum, warningString, refNode->GetSourceData(), refNode->GetSrcStart(), refNode->GetSrcLength());
  2831. else
  2832. bfError = mCompiler->mPassInstance->Warn(warningNum, warningString);
  2833. if (bfError != NULL)
  2834. {
  2835. bfError->mIsWhileSpecializing = isWhileSpecializing;
  2836. bfError->mProject = mProject;
  2837. AddFailType(mCurTypeInstance);
  2838. mHadBuildWarning = true;
  2839. bfError->mIsPersistent = isPersistent;
  2840. if ((mCompiler->IsAutocomplete()) && (mCompiler->mResolvePassData->mAutoComplete->CheckFixit((refNode))))
  2841. {
  2842. BfParserData* parser = refNode->GetSourceData()->ToParserData();
  2843. if (parser != NULL)
  2844. {
  2845. int fileLoc = BfFixitFinder::FindLineStartBefore(refNode);
  2846. mCompiler->mResolvePassData->mAutoComplete->AddEntry(AutoCompleteEntry("fixit", StrFormat("#unwarn\tunwarn|%s|%d|#unwarn|", parser->mFileName.c_str(), fileLoc).c_str()));
  2847. if (warningNum != 0)
  2848. {
  2849. mCompiler->mResolvePassData->mAutoComplete->AddEntry(AutoCompleteEntry("fixit", StrFormat("#pragma warning disable %d\t.pragma|%s|%d||#pragma warning disable %d",
  2850. warningNum, parser->mFileName.c_str(), 0, warningNum).c_str()));
  2851. }
  2852. }
  2853. }
  2854. }
  2855. return bfError;
  2856. }
  2857. void BfModule::CheckErrorAttributes(BfTypeInstance* typeInstance, BfMethodInstance* methodInstance, BfCustomAttributes* customAttributes, BfAstNode* targetSrc)
  2858. {
  2859. if (customAttributes == NULL)
  2860. return;
  2861. auto _AddDeclarationMoreInfo = [&]()
  2862. {
  2863. if (methodInstance != NULL)
  2864. {
  2865. if (methodInstance->mMethodDef->mMethodDeclaration != NULL)
  2866. mCompiler->mPassInstance->MoreInfo(
  2867. StrFormat("See method declaration '%s'", MethodToString(methodInstance).c_str()),
  2868. methodInstance->mMethodDef->GetRefNode());
  2869. }
  2870. else
  2871. {
  2872. mCompiler->mPassInstance->MoreInfo(
  2873. StrFormat("See type declaration '%s'", TypeToString(typeInstance, BfTypeNameFlag_UseUnspecializedGenericParamNames).c_str()),
  2874. typeInstance->mTypeDef->GetRefNode());
  2875. }
  2876. };
  2877. BfIRConstHolder* constHolder = typeInstance->mConstHolder;
  2878. auto customAttribute = customAttributes->Get(mCompiler->mObsoleteAttributeTypeDef);
  2879. if ((customAttribute != NULL) && (!customAttribute->mCtorArgs.IsEmpty()) && (targetSrc != NULL))
  2880. {
  2881. String err;
  2882. if (methodInstance != NULL)
  2883. err = StrFormat("'%s' is obsolete", MethodToString(methodInstance).c_str());
  2884. else
  2885. err = StrFormat("'%s' is obsolete", TypeToString(typeInstance, BfTypeNameFlag_UseUnspecializedGenericParamNames).c_str());
  2886. bool isError = false;
  2887. auto constant = constHolder->GetConstant(customAttribute->mCtorArgs[0]);
  2888. if (constant->mTypeCode == BfTypeCode_Boolean)
  2889. {
  2890. isError = constant->mBool;
  2891. }
  2892. else if (customAttribute->mCtorArgs.size() >= 2)
  2893. {
  2894. String* str = GetStringPoolString(customAttribute->mCtorArgs[0], constHolder);
  2895. if (str != NULL)
  2896. {
  2897. err += ":\n '";
  2898. err += *str;
  2899. err += "'";
  2900. }
  2901. constant = constHolder->GetConstant(customAttribute->mCtorArgs[1]);
  2902. isError = constant->mBool;
  2903. }
  2904. BfError* error = NULL;
  2905. if (isError)
  2906. error = Fail(err, targetSrc);
  2907. else
  2908. error = Warn(0, err, targetSrc, false, true);
  2909. if (error != NULL)
  2910. _AddDeclarationMoreInfo();
  2911. }
  2912. customAttribute = customAttributes->Get(mCompiler->mErrorAttributeTypeDef);
  2913. if ((customAttribute != NULL) && (!customAttribute->mCtorArgs.IsEmpty()))
  2914. {
  2915. String err;
  2916. if (methodInstance != NULL)
  2917. err += StrFormat("Method error: '", MethodToString(methodInstance).c_str());
  2918. else
  2919. err += StrFormat("Type error: '", TypeToString(typeInstance, BfTypeNameFlag_UseUnspecializedGenericParamNames).c_str());
  2920. String* str = GetStringPoolString(customAttribute->mCtorArgs[0], constHolder);
  2921. if (str != NULL)
  2922. err += *str;
  2923. err += "'";
  2924. if (Fail(err, targetSrc) != NULL)
  2925. _AddDeclarationMoreInfo();
  2926. }
  2927. customAttribute = customAttributes->Get(mCompiler->mWarnAttributeTypeDef);
  2928. if ((customAttribute != NULL) && (!customAttribute->mCtorArgs.IsEmpty()) && (targetSrc != NULL))
  2929. {
  2930. String err;
  2931. if (methodInstance != NULL)
  2932. err += StrFormat("Method warning: '", MethodToString(methodInstance).c_str());
  2933. else
  2934. err += StrFormat("Type warning: '", TypeToString(typeInstance, BfTypeNameFlag_UseUnspecializedGenericParamNames).c_str());
  2935. String* str = GetStringPoolString(customAttribute->mCtorArgs[0], constHolder);
  2936. if (str != NULL)
  2937. err += *str;
  2938. err += "'";
  2939. if (Warn(0, err, targetSrc, false, true) != NULL)
  2940. _AddDeclarationMoreInfo();
  2941. }
  2942. }
  2943. void BfModule::CheckRangeError(BfType* type, BfAstNode* refNode)
  2944. {
  2945. if (mBfIRBuilder->mOpFailed)
  2946. Fail(StrFormat("Result out of range for type '%s'", TypeToString(type).c_str()), refNode);
  2947. }
  2948. void BfModule::FatalError(const StringImpl& error, const char* file, int line)
  2949. {
  2950. static bool sHadFatalError = false;
  2951. static bool sHadReentrancy = false;
  2952. if (sHadFatalError)
  2953. {
  2954. return;
  2955. sHadReentrancy = true;
  2956. }
  2957. sHadFatalError = true;
  2958. String fullError = error;
  2959. if (file != NULL)
  2960. fullError += StrFormat(" at %s:%d", file, line);
  2961. fullError += StrFormat("\nModule: %s", mModuleName.c_str());
  2962. if (mCurTypeInstance != NULL)
  2963. fullError += StrFormat("\nType: %s", TypeToString(mCurTypeInstance).c_str());
  2964. if (mCurMethodInstance != NULL)
  2965. fullError += StrFormat("\nMethod: %s", MethodToString(mCurMethodInstance).c_str());
  2966. if ((mCurFilePosition.mFileInstance != NULL) && (mCurFilePosition.mFileInstance->mParser != NULL))
  2967. fullError += StrFormat("\nSource Location: %s:%d", mCurFilePosition.mFileInstance->mParser->mFileName.c_str(), mCurFilePosition.mCurLine + 1);
  2968. if (sHadReentrancy)
  2969. fullError += "\nError had reentrancy";
  2970. BfpSystem_FatalError(fullError.c_str(), "FATAL MODULE ERROR");
  2971. }
  2972. void BfModule::NotImpl(BfAstNode* astNode)
  2973. {
  2974. Fail("INTERNAL ERROR: Not implemented", astNode);
  2975. }
  2976. bool BfModule::CheckAccessMemberProtection(BfProtection protection, BfTypeInstance* memberType)
  2977. {
  2978. bool allowPrivate = (memberType == mCurTypeInstance) || (IsInnerType(mCurTypeInstance, memberType));
  2979. if (!allowPrivate)
  2980. allowPrivate |= memberType->IsInterface();
  2981. bool allowProtected = allowPrivate;
  2982. //TODO: We had this commented out, but this makes accessing protected properties fail
  2983. if (mCurTypeInstance != NULL)
  2984. allowProtected |= TypeIsSubTypeOf(mCurTypeInstance, memberType->ToTypeInstance());
  2985. if (!CheckProtection(protection, memberType->mTypeDef, allowProtected, allowPrivate))
  2986. {
  2987. return false;
  2988. }
  2989. return true;
  2990. }
  2991. bool BfModule::CheckDefineMemberProtection(BfProtection protection, BfType* memberType)
  2992. {
  2993. // Use 'min' - exporting a 'public' from a 'private' class is really just 'private' still
  2994. protection = std::min(protection, mCurTypeInstance->mTypeDef->mProtection);
  2995. auto memberTypeInstance = memberType->ToTypeInstance();
  2996. if (memberTypeInstance == NULL)
  2997. {
  2998. auto underlyingType = memberType->GetUnderlyingType();
  2999. if (underlyingType != NULL)
  3000. return CheckDefineMemberProtection(protection, underlyingType);
  3001. return true;
  3002. }
  3003. if (memberTypeInstance->mTypeDef->mProtection < protection)
  3004. return false;
  3005. if (memberTypeInstance->IsGenericTypeInstance())
  3006. {
  3007. // When we're a generic struct, our data layout can depend on our generic parameters as well
  3008. auto genericTypeInstance = (BfTypeInstance*) memberTypeInstance;
  3009. for (auto typeGenericArg : genericTypeInstance->mGenericTypeInfo->mTypeGenericArguments)
  3010. {
  3011. if (!CheckDefineMemberProtection(protection, typeGenericArg))
  3012. return false;
  3013. }
  3014. }
  3015. return true;
  3016. }
  3017. void BfModule::AddDependency(BfType* usedType, BfType* userType, BfDependencyMap::DependencyFlags flags)
  3018. {
  3019. if (usedType == userType)
  3020. return;
  3021. if (((flags & BfDependencyMap::DependencyFlag_ConstValue) != 0) && (mContext->mCurTypeState != NULL) && (mContext->mCurTypeState->mResolveKind == BfTypeState::ResolveKind_FieldType))
  3022. {
  3023. // This can be an `int32[UsedType.cVal]` type reference
  3024. flags = (BfDependencyMap::DependencyFlags)(flags | BfDependencyMap::DependencyFlag_ValueTypeSizeDep);
  3025. }
  3026. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mIsAutocompleteMethod))
  3027. {
  3028. if (userType->IsMethodRef())
  3029. {
  3030. // We cannot short-circuit dependencies because of method group ref counting
  3031. }
  3032. else
  3033. return;
  3034. }
  3035. if (usedType->IsSpecializedByAutoCompleteMethod())
  3036. {
  3037. if ((flags & (BfDependencyMap::DependencyFlag_TypeGenericArg | BfDependencyMap::DependencyFlag_OuterType | BfDependencyMap::DependencyFlag_DerivedFrom)) == 0)
  3038. return;
  3039. }
  3040. // if (usedType->IsBoxed())
  3041. // {
  3042. // NOP;
  3043. // auto underlyingType = usedType->GetUnderlyingType()->ToTypeInstance();
  3044. // if ((underlyingType != NULL) && (underlyingType->IsInstanceOf(mCompiler->mSizedArrayTypeDef)))
  3045. // {
  3046. // BfLogSysM("AddDependency UsedType:%p UserType:%p Method:%p\n", usedType, userType, mCurMethodInstance);
  3047. // }
  3048. // }
  3049. // TODO: It seems this was bogus - it kept the root array from being marked as a dependency (for example)
  3050. // BfType* origUsedType = usedType;
  3051. bool isDataAccess = ((flags & (BfDependencyMap::DependencyFlag_ReadFields | BfDependencyMap::DependencyFlag_LocalUsage | BfDependencyMap::DependencyFlag_Allocates)) != 0);
  3052. // if (isDataAccess)
  3053. // {
  3054. // while (true)
  3055. // {
  3056. // if ((usedType->IsPointer()) || (usedType->IsRef()) || (usedType->IsSizedArray()))
  3057. // usedType = usedType->GetUnderlyingType();
  3058. // else if (usedType->IsArray())
  3059. // {
  3060. // usedType = ((BfTypeInstance*)usedType)->mGenericTypeInfo->mTypeGenericArguments[0];
  3061. // }
  3062. // else
  3063. // break;
  3064. // }
  3065. // }
  3066. if ((mCurMethodState != NULL) && (mCurMethodState->mHotDataReferenceBuilder != NULL) && (usedType != mCurTypeInstance) && (isDataAccess))
  3067. {
  3068. bool addType = true;
  3069. auto checkType = usedType;
  3070. PopulateType(checkType, BfPopulateType_Data);
  3071. if (checkType->IsValuelessType())
  3072. addType = false;
  3073. else if (checkType->IsPrimitiveType())
  3074. addType = false;
  3075. else
  3076. {
  3077. auto checkTypeInst = checkType->ToTypeInstance();
  3078. if (checkTypeInst == NULL)
  3079. {
  3080. addType = false;
  3081. }
  3082. else
  3083. {
  3084. if (TypeIsSubTypeOf(mCurTypeInstance, checkTypeInst))
  3085. addType = false;
  3086. }
  3087. }
  3088. if (addType)
  3089. {
  3090. auto checkTypeInst = checkType->ToTypeInstance();
  3091. if (checkTypeInst->mHotTypeData != NULL)
  3092. {
  3093. auto hotTypeVersion = checkTypeInst->mHotTypeData->GetLatestVersion();
  3094. BF_ASSERT(hotTypeVersion != NULL);
  3095. if (hotTypeVersion != NULL)
  3096. {
  3097. bool isAllocation = ((flags & BfDependencyMap::DependencyFlag_Allocates) != 0);
  3098. if (((flags & BfDependencyMap::DependencyFlag_LocalUsage) != 0) &&
  3099. (checkType->IsComposite()))
  3100. isAllocation = true;
  3101. if (isAllocation)
  3102. {
  3103. mCurMethodState->mHotDataReferenceBuilder->mAllocatedData.Add(hotTypeVersion);
  3104. }
  3105. else
  3106. mCurMethodState->mHotDataReferenceBuilder->mUsedData.Add(hotTypeVersion);
  3107. }
  3108. }
  3109. }
  3110. }
  3111. if ((!mCompiler->mIsResolveOnly) && (mIsReified))
  3112. {
  3113. auto usingModule = userType->GetModule();
  3114. BfModule* usedModule;
  3115. if (usedType->IsFunction())
  3116. {
  3117. if (mCompiler->mFunctionTypeDef != NULL)
  3118. {
  3119. auto functionType = ResolveTypeDef(mCompiler->mFunctionTypeDef)->ToTypeInstance();
  3120. usedModule = functionType->GetModule();
  3121. }
  3122. }
  3123. else
  3124. usedModule = usedType->GetModule();
  3125. if ((usingModule != NULL) && (!usingModule->mIsSpecialModule) &&
  3126. (usedModule != NULL) && (!usedModule->mIsSpecialModule))
  3127. {
  3128. if ((flags & ~(BfDependencyMap::DependencyFlag_OuterType)) == 0)
  3129. {
  3130. // Not a 'use' dependency
  3131. }
  3132. else
  3133. {
  3134. usingModule->mModuleRefs.Add(usedModule);
  3135. }
  3136. }
  3137. }
  3138. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mMethodInfoEx != NULL) && (flags != BfDependencyMap::DependencyFlag_MethodGenericArg))
  3139. {
  3140. // When we are specializing a method, usage of that specialized type is already handled with DependencyFlag_MethodGenericArg
  3141. for (auto genericArg : mCurMethodInstance->mMethodInfoEx->mMethodGenericArguments)
  3142. if (genericArg == usedType)
  3143. return;
  3144. }
  3145. auto depFlag = flags;
  3146. if ((flags & (BfDependencyMap::DependencyFlag_MethodGenericArg | BfDependencyMap::DependencyFlag_TypeGenericArg)) != 0)
  3147. {
  3148. if (usedType->IsDependendType())
  3149. {
  3150. // Cause a rebuild but not an outright deletion of the type
  3151. // We can only do this if the 'usedType' can actually hold the dependency which can actually trigger a deletion chain
  3152. depFlag = BfDependencyMap::DependencyFlag_GenericArgRef;
  3153. }
  3154. }
  3155. if (!usedType->IsGenericTypeInstance())
  3156. {
  3157. auto underlyingType = usedType->GetUnderlyingType();
  3158. if (underlyingType != NULL)
  3159. AddDependency(underlyingType, userType, depFlag);
  3160. }
  3161. BfDependedType* checkDType = usedType->ToDependedType();
  3162. if (checkDType == NULL)
  3163. return;
  3164. if ((usedType->mRebuildFlags & BfTypeRebuildFlag_AwaitingReference) != 0)
  3165. mContext->MarkAsReferenced(checkDType);
  3166. #ifdef _DEBUG
  3167. // If a MethodRef depends ON US, that means it's a local method that we own
  3168. if (userType->IsMethodRef())
  3169. {
  3170. auto methodRefType = (BfMethodRefType*)userType;
  3171. BF_ASSERT(methodRefType->mOwner == checkDType);
  3172. }
  3173. #endif
  3174. if (!checkDType->mDependencyMap.AddUsedBy(userType, flags))
  3175. return;
  3176. if ((checkDType->IsGenericTypeInstance()) && (!userType->IsMethodRef()))
  3177. {
  3178. auto genericTypeInstance = (BfTypeInstance*) checkDType;
  3179. for (auto genericArg : genericTypeInstance->mGenericTypeInfo->mTypeGenericArguments)
  3180. {
  3181. AddDependency(genericArg, userType, depFlag);
  3182. }
  3183. }
  3184. if (checkDType->IsTuple())
  3185. {
  3186. for (auto& field : checkDType->ToTypeInstance()->mFieldInstances)
  3187. {
  3188. if (field.mDataIdx != -1)
  3189. AddDependency(field.mResolvedType, userType, depFlag);
  3190. }
  3191. }
  3192. }
  3193. void BfModule::AddDependency(BfGenericParamInstance* genericParam, BfTypeInstance* usingType)
  3194. {
  3195. if ((genericParam->mExternType != NULL) && (!genericParam->mExternType->IsGenericParam()))
  3196. AddDependency(genericParam->mExternType, mCurTypeInstance, BfDependencyMap::DependencyFlag_Constraint);
  3197. for (auto constraintTypeInst : genericParam->mInterfaceConstraints)
  3198. AddDependency(constraintTypeInst, mCurTypeInstance, BfDependencyMap::DependencyFlag_Constraint);
  3199. for (auto& operatorConstraint : genericParam->mOperatorConstraints)
  3200. {
  3201. if (operatorConstraint.mLeftType != NULL)
  3202. AddDependency(operatorConstraint.mLeftType, mCurTypeInstance, BfDependencyMap::DependencyFlag_Constraint);
  3203. if (operatorConstraint.mRightType != NULL)
  3204. AddDependency(operatorConstraint.mRightType, mCurTypeInstance, BfDependencyMap::DependencyFlag_Constraint);
  3205. }
  3206. if (genericParam->mTypeConstraint != NULL)
  3207. AddDependency(genericParam->mTypeConstraint, mCurTypeInstance, BfDependencyMap::DependencyFlag_Constraint);
  3208. }
  3209. void BfModule::AddCallDependency(BfMethodInstance* methodInstance, bool devirtualized)
  3210. {
  3211. if ((mCurMethodState != NULL) && (mCurMethodState->mHotDataReferenceBuilder != NULL))
  3212. {
  3213. if (methodInstance->mHotMethod == NULL)
  3214. CheckHotMethod(methodInstance, "");
  3215. BF_ASSERT(methodInstance->mHotMethod != NULL);
  3216. if (devirtualized)
  3217. mCurMethodState->mHotDataReferenceBuilder->mDevirtualizedCalledMethods.Add(methodInstance->mHotMethod);
  3218. else
  3219. mCurMethodState->mHotDataReferenceBuilder->mCalledMethods.Add(methodInstance->mHotMethod);
  3220. }
  3221. }
  3222. bool BfModule::IsAttribute(BfTypeInstance* typeInst)
  3223. {
  3224. auto checkTypeInst = typeInst;
  3225. while (checkTypeInst != NULL)
  3226. {
  3227. if (checkTypeInst->IsInstanceOf(mCompiler->mAttributeTypeDef))
  3228. return true;
  3229. checkTypeInst = checkTypeInst->mBaseType;
  3230. }
  3231. return false;
  3232. }
  3233. void BfModule::PopulateGlobalContainersList(const BfGlobalLookup& globalLookup)
  3234. {
  3235. if (mContext->mCurTypeState == NULL)
  3236. return;
  3237. BP_ZONE("PopulateGlobalContainersList");
  3238. BfTypeDef* userTypeDef = mContext->mCurTypeState->mCurTypeDef;
  3239. if ((userTypeDef == NULL) && (mCurMethodInstance != NULL))
  3240. userTypeDef = mCurMethodInstance->mMethodDef->mDeclaringType;
  3241. if (userTypeDef == NULL)
  3242. userTypeDef = mCurTypeInstance->mTypeDef;
  3243. if (mContext->mCurTypeState->mGlobalContainerCurUserTypeDef != userTypeDef)
  3244. {
  3245. mContext->mCurTypeState->mGlobalContainers.Clear();
  3246. for (int namespaceIdx = -1; namespaceIdx < (int)userTypeDef->mNamespaceSearch.size(); namespaceIdx++)
  3247. {
  3248. BfAtomComposite findStr;
  3249. if (namespaceIdx != -1)
  3250. findStr.Reference(userTypeDef->mNamespaceSearch[namespaceIdx]);
  3251. auto typeDefItr = mSystem->mTypeDefs.TryGet(findStr);
  3252. while (typeDefItr)
  3253. {
  3254. auto typeDef = *typeDefItr;
  3255. if ((typeDef->mFullName == findStr) && (typeDef->mIsCombinedPartial) && (typeDef->IsGlobalsContainer()))
  3256. {
  3257. if (typeDef->mProject->ContainsReference(typeDef->mProject))
  3258. {
  3259. BfGlobalContainerEntry globalEntry;
  3260. globalEntry.mTypeDef = typeDef;
  3261. globalEntry.mTypeInst = NULL;
  3262. typeDef->PopulateMemberSets();
  3263. mContext->mCurTypeState->mGlobalContainers.Add(globalEntry);
  3264. }
  3265. }
  3266. else if (!typeDef->mIsPartial)
  3267. {
  3268. //break;
  3269. }
  3270. typeDefItr.MoveToNextHashMatch();
  3271. }
  3272. }
  3273. mContext->mCurTypeState->mGlobalContainerCurUserTypeDef = userTypeDef;
  3274. }
  3275. // Only create actual typeInst when we have an applicable member. This helps in keeping unused globals from
  3276. // reifing types
  3277. for (auto& globalEntry : mContext->mCurTypeState->mGlobalContainers)
  3278. {
  3279. if (globalEntry.mTypeInst == NULL)
  3280. {
  3281. bool include = false;
  3282. if (globalLookup.mKind == BfGlobalLookup::Kind_All)
  3283. include = true;
  3284. else if (globalLookup.mKind == BfGlobalLookup::Kind_Field)
  3285. {
  3286. if (globalEntry.mTypeDef->mFieldSet.ContainsWith(globalLookup.mName))
  3287. include = true;
  3288. if (globalEntry.mTypeDef->mPropertySet.ContainsWith(globalLookup.mName))
  3289. include = true;
  3290. }
  3291. else if (globalLookup.mKind == BfGlobalLookup::Kind_Method)
  3292. {
  3293. if (globalEntry.mTypeDef->mMethodSet.ContainsWith(globalLookup.mName))
  3294. include = true;
  3295. }
  3296. if (include)
  3297. {
  3298. auto type = ResolveTypeDef(globalEntry.mTypeDef);
  3299. if (type != NULL)
  3300. globalEntry.mTypeInst = type->ToTypeInstance();
  3301. }
  3302. }
  3303. }
  3304. }
  3305. BfStaticSearch* BfModule::GetStaticSearch()
  3306. {
  3307. auto activeTypeDef = GetActiveTypeDef();
  3308. BfStaticSearch* staticSearch = NULL;
  3309. if ((mCurTypeInstance != NULL) && (mCurTypeInstance->mStaticSearchMap.TryGetValue(activeTypeDef, &staticSearch)))
  3310. return staticSearch;
  3311. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mStaticSearchMap.TryGetValue(activeTypeDef, &staticSearch)))
  3312. return staticSearch;
  3313. return NULL;
  3314. }
  3315. BfInternalAccessSet* BfModule::GetInternalAccessSet()
  3316. {
  3317. auto activeTypeDef = GetActiveTypeDef();
  3318. BfInternalAccessSet* internalAccessSet = NULL;
  3319. if ((mCurTypeInstance != NULL) && (mCurTypeInstance->mInternalAccessMap.TryGetValue(activeTypeDef, &internalAccessSet)))
  3320. return internalAccessSet;
  3321. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mInternalAccessMap.TryGetValue(activeTypeDef, &internalAccessSet)))
  3322. return internalAccessSet;
  3323. return NULL;
  3324. }
  3325. bool BfModule::CheckInternalProtection(BfTypeDef* usingTypeDef)
  3326. {
  3327. if ((mCurTypeInstance != NULL) && (mCurTypeInstance->IsSpecializedType()))
  3328. return true;
  3329. if ((mCurMethodInstance != NULL) &&
  3330. ((mCurMethodInstance->mIsUnspecializedVariation) || (mCurMethodInstance->IsSpecializedGenericMethod())))
  3331. return true;
  3332. auto internalAccessSet = GetInternalAccessSet();
  3333. if (internalAccessSet == NULL)
  3334. return false;
  3335. for (auto& nameComposite : internalAccessSet->mNamespaces)
  3336. {
  3337. if (usingTypeDef->mNamespace.StartsWith(nameComposite))
  3338. return true;
  3339. }
  3340. for (auto internalType : internalAccessSet->mTypes)
  3341. {
  3342. auto checkTypeDef = usingTypeDef->GetDefinition();
  3343. while (checkTypeDef != NULL)
  3344. {
  3345. if (checkTypeDef == internalType->mTypeDef->GetDefinition())
  3346. return true;
  3347. checkTypeDef = checkTypeDef->mOuterType;
  3348. }
  3349. }
  3350. return false;
  3351. }
  3352. void PrintUsers(llvm::MDNode* md);
  3353. BfModuleOptions BfModule::GetModuleOptions()
  3354. {
  3355. if (mIsScratchModule)
  3356. return BfModuleOptions();
  3357. if (mModuleOptions != NULL)
  3358. return *mModuleOptions;
  3359. BfModuleOptions moduleOptions;
  3360. moduleOptions.mEmitDebugInfo = mCompiler->mOptions.mEmitDebugInfo ? 1 : mCompiler->mOptions.mEmitLineInfo ? 2 : 0;
  3361. if (mProject != NULL)
  3362. {
  3363. moduleOptions.mSIMDSetting = mProject->mCodeGenOptions.mSIMDSetting;
  3364. moduleOptions.mOptLevel = mProject->mCodeGenOptions.mOptLevel;
  3365. }
  3366. auto headModule = this;
  3367. while (headModule->mParentModule != NULL)
  3368. headModule = headModule->mParentModule;
  3369. BF_ASSERT((headModule->mOwnedTypeInstances.size() > 0) || (mModuleName == "vdata") || mIsSpecialModule);
  3370. if (headModule->mOwnedTypeInstances.size() > 0)
  3371. {
  3372. auto typeInst = headModule->mOwnedTypeInstances[0];
  3373. if (typeInst->mTypeOptionsIdx == -2)
  3374. PopulateType(typeInst);
  3375. if (typeInst->mTypeOptionsIdx != -1)
  3376. {
  3377. auto typeOptions = mSystem->GetTypeOptions(typeInst->mTypeOptionsIdx);
  3378. moduleOptions.mSIMDSetting = (BfSIMDSetting)BfTypeOptions::Apply((int)moduleOptions.mSIMDSetting, typeOptions->mSIMDSetting);
  3379. moduleOptions.mEmitDebugInfo = BfTypeOptions::Apply(moduleOptions.mEmitDebugInfo, typeOptions->mEmitDebugInfo);
  3380. moduleOptions.mOptLevel = (BfOptLevel)BfTypeOptions::Apply((int)moduleOptions.mOptLevel, (int)typeOptions->mOptimizationLevel);
  3381. }
  3382. }
  3383. return moduleOptions;
  3384. }
  3385. BfCheckedKind BfModule::GetDefaultCheckedKind()
  3386. {
  3387. if ((mCurMethodState != NULL) && (mCurMethodState->mDisableChecks))
  3388. return BfCheckedKind_Unchecked;
  3389. bool runtimeChecks = mCompiler->mOptions.mRuntimeChecks;
  3390. auto typeOptions = GetTypeOptions();
  3391. if (typeOptions != NULL)
  3392. runtimeChecks = typeOptions->Apply(runtimeChecks, BfOptionFlags_RuntimeChecks);
  3393. return runtimeChecks ? BfCheckedKind_Checked : BfCheckedKind_Unchecked;
  3394. }
  3395. void BfModule::AddFailType(BfTypeInstance* typeInstance)
  3396. {
  3397. BF_ASSERT(typeInstance != NULL);
  3398. if ((typeInstance->mRebuildFlags & BfTypeRebuildFlag_InFailTypes) != 0)
  3399. return;
  3400. typeInstance->mRebuildFlags = (BfTypeRebuildFlags)(typeInstance->mRebuildFlags | BfTypeRebuildFlag_InFailTypes);
  3401. mContext->mFailTypes.Add(typeInstance);
  3402. }
  3403. void BfModule::DeferRebuildType(BfTypeInstance* typeInstance)
  3404. {
  3405. if ((typeInstance->mRebuildFlags & BfTypeRebuildFlag_RebuildQueued) != 0)
  3406. return;
  3407. mCompiler->mHasQueuedTypeRebuilds = true;
  3408. typeInstance->mRebuildFlags = (BfTypeRebuildFlags)(typeInstance->mRebuildFlags | BfTypeRebuildFlag_RebuildQueued);
  3409. AddFailType(typeInstance);
  3410. }
  3411. void BfModule::CheckAddFailType()
  3412. {
  3413. //TODO: We removed this line, because failures in resolve-only generic method can occur in non-owning modules
  3414. // but we still need to add the owning type to the FailTypes list
  3415. //.. OLD:
  3416. // While we're inlining, it's possible that mCurTypeInstance belongs to another module, ignore it
  3417. /*if (mCurTypeInstance->mModule != this)
  3418. return;*/
  3419. // Using mHadBuildWarning to insert into mFailTypes is our core of our strategy for reasserting
  3420. // warnings on rebuilds where otherwise the warnings wouldn't be generated because no code was
  3421. // being recompiled. This forces types with warnings to be recompiled.
  3422. // We had this 'mIsResolveOnly' check for speed in resolveOnly, but we removed it so the IDE can be
  3423. // constantly warning-aware
  3424. if ((mHadBuildError) ||
  3425. (mHadBuildWarning /*&& !mCompiler->mIsResolveOnly*/))
  3426. {
  3427. //mContext->mFailTypes.Add(mCurTypeInstance);
  3428. }
  3429. }
  3430. void BfModule::MarkDerivedDirty(BfTypeInstance* typeInst)
  3431. {
  3432. if (!mCompiler->IsHotCompile())
  3433. return;
  3434. typeInst->mDirty = true;
  3435. for (auto& dep : typeInst->mDependencyMap)
  3436. {
  3437. auto depType = dep.mKey;
  3438. auto depFlags = dep.mValue.mFlags;
  3439. if ((depFlags & BfDependencyMap::DependencyFlag_DerivedFrom) != 0)
  3440. {
  3441. MarkDerivedDirty(depType->ToTypeInstance());
  3442. }
  3443. }
  3444. }
  3445. void BfModule::CreateStaticField(BfFieldInstance* fieldInstance, bool isThreadLocal)
  3446. {
  3447. auto fieldType = fieldInstance->GetResolvedType();
  3448. auto field = fieldInstance->GetFieldDef();
  3449. if (fieldType->IsVar())
  3450. return;
  3451. BfIRValue initValue;
  3452. if (field->mIsConst)
  3453. {
  3454. if (fieldType->IsPointer())
  3455. fieldType = fieldType->GetUnderlyingType();
  3456. }
  3457. BfIRStorageKind storageKind = BfIRStorageKind_Normal;
  3458. if ((fieldInstance->mCustomAttributes != NULL) && (fieldInstance->mCustomAttributes->Get(mCompiler->mExportAttributeTypeDef)))
  3459. storageKind = BfIRStorageKind_Export;
  3460. else if ((fieldInstance->mCustomAttributes != NULL) && (fieldInstance->mCustomAttributes->Get(mCompiler->mImportAttributeTypeDef)))
  3461. storageKind = BfIRStorageKind_Import;
  3462. if ((!field->mIsExtern) && (storageKind != BfIRStorageKind_Import))
  3463. initValue = GetDefaultValue(fieldType);
  3464. if (fieldInstance->mOwner->IsUnspecializedType())
  3465. {
  3466. // Placeholder
  3467. auto ptrVal = CreatePointerType(fieldType);
  3468. mStaticFieldRefs[fieldInstance] = GetDefaultValue(ptrVal);
  3469. }
  3470. else
  3471. {
  3472. BfLogSysM("Creating static field Module:%p Type:%p\n", this, fieldType);
  3473. StringT<128> staticVarName;
  3474. BfMangler::Mangle(staticVarName, mCompiler->GetMangleKind(), fieldInstance);
  3475. if ((!fieldType->IsValuelessType()) && (!staticVarName.StartsWith("#")))
  3476. {
  3477. BfIRValue globalVar = mBfIRBuilder->CreateGlobalVariable(
  3478. mBfIRBuilder->MapType(fieldType, BfIRPopulateType_Eventually_Full),
  3479. false,
  3480. BfIRLinkageType_External,
  3481. initValue,
  3482. staticVarName,
  3483. isThreadLocal);
  3484. mBfIRBuilder->GlobalVar_SetAlignment(globalVar, fieldType->mAlign);
  3485. if (storageKind != BfIRStorageKind_Normal)
  3486. mBfIRBuilder->GlobalVar_SetStorageKind(globalVar, storageKind);
  3487. BF_ASSERT(globalVar);
  3488. mStaticFieldRefs[fieldInstance] = globalVar;
  3489. }
  3490. }
  3491. }
  3492. void BfModule::ResolveConstField(BfTypeInstance* typeInstance, BfFieldInstance* fieldInstance, BfFieldDef* fieldDef, bool forceResolve)
  3493. {
  3494. bool autoCompleteOnly = mCompiler->IsAutocomplete();
  3495. BfType* fieldType = NULL;
  3496. if (fieldInstance != NULL)
  3497. {
  3498. fieldType = fieldInstance->GetResolvedType();
  3499. if (fieldType == NULL)
  3500. fieldType = ResolveTypeRef(fieldDef->mTypeRef);
  3501. }
  3502. else
  3503. {
  3504. BF_ASSERT(mCompiler->IsAutocomplete());
  3505. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  3506. if ((typeInstance->IsEnum()) && (fieldDef->mTypeRef == NULL))
  3507. {
  3508. fieldType = typeInstance;
  3509. }
  3510. else
  3511. {
  3512. auto isLet = (fieldDef->mTypeRef != NULL) && (fieldDef->mTypeRef->IsExact<BfLetTypeReference>());
  3513. auto isVar = (fieldDef->mTypeRef != NULL) && (fieldDef->mTypeRef->IsExact<BfVarTypeReference>());
  3514. if (isLet || isVar)
  3515. fieldType = GetPrimitiveType(BfTypeCode_Var);
  3516. else
  3517. fieldType = ResolveTypeRef(fieldDef->mTypeRef,BfPopulateType_Identity, BfResolveTypeRefFlag_AllowInferredSizedArray);
  3518. if (fieldType == NULL)
  3519. fieldType = mContext->mBfObjectType;
  3520. }
  3521. }
  3522. if ((fieldInstance != NULL) && (fieldInstance->mConstIdx != -1) && (!forceResolve))
  3523. return;
  3524. if (mContext->mFieldResolveReentrys.size() > 1)
  3525. {
  3526. if (mContext->mFieldResolveReentrys.IndexOf(fieldInstance, 1) != -1)
  3527. {
  3528. String failStr = "Circular data reference detected between the following fields:";
  3529. for (int i = 1; i < (int)mContext->mFieldResolveReentrys.size(); i++)
  3530. {
  3531. if (i > 1)
  3532. failStr += ",";
  3533. failStr += "\n '" + TypeToString(typeInstance) + "." + mContext->mFieldResolveReentrys[i]->GetFieldDef()->mName + "'";
  3534. }
  3535. BfError* err = Fail(failStr, fieldDef->mFieldDeclaration);
  3536. if (err)
  3537. err->mIsPersistent = true;
  3538. return;
  3539. }
  3540. }
  3541. mContext->mFieldResolveReentrys.push_back(fieldInstance);
  3542. AutoPopBack<decltype (mContext->mFieldResolveReentrys)> popTypeResolveReentry(&mContext->mFieldResolveReentrys);
  3543. if (fieldInstance == NULL)
  3544. popTypeResolveReentry.Pop();
  3545. auto typeDef = typeInstance->mTypeDef;
  3546. BfIRValue constValue;
  3547. if (fieldDef->mIsExtern)
  3548. {
  3549. if (!fieldDef->mTypeRef->IsA<BfPointerTypeRef>())
  3550. {
  3551. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  3552. Fail("Extern consts must be pointer types", fieldDef->mFieldDeclaration->mTypeRef);
  3553. }
  3554. if (fieldDef->mInitializer != NULL)
  3555. {
  3556. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  3557. Fail("Extern consts cannot have initializers", fieldDef->mFieldDeclaration->mNameNode);
  3558. }
  3559. }
  3560. else if (fieldDef->mInitializer == NULL)
  3561. {
  3562. if (fieldDef->IsEnumCaseEntry())
  3563. {
  3564. if (typeInstance->IsTypedPrimitive())
  3565. {
  3566. BfFieldInstance* prevFieldInstance = NULL;
  3567. for (int i = fieldDef->mIdx - 1; i >= 0; i--)
  3568. {
  3569. BfFieldInstance* checkFieldInst = &typeInstance->mFieldInstances[i];
  3570. if (checkFieldInst->GetFieldDef()->IsEnumCaseEntry())
  3571. {
  3572. prevFieldInstance = checkFieldInst;
  3573. break;
  3574. }
  3575. }
  3576. if (prevFieldInstance == NULL)
  3577. constValue = GetConstValue(0, typeInstance);
  3578. else
  3579. {
  3580. ResolveConstField(typeInstance, prevFieldInstance, prevFieldInstance->GetFieldDef());
  3581. if (prevFieldInstance->mConstIdx == -1)
  3582. {
  3583. if (!mCompiler->IsAutocomplete())
  3584. AssertErrorState();
  3585. constValue = GetConstValue(0, typeInstance);
  3586. }
  3587. else
  3588. {
  3589. auto prevConstant = ConstantToCurrent(typeInstance->mConstHolder->GetConstantById(prevFieldInstance->mConstIdx), typeInstance->mConstHolder, typeInstance);
  3590. constValue = mBfIRBuilder->CreateAdd(prevConstant, GetConstValue(1, typeInstance));
  3591. }
  3592. }
  3593. }
  3594. }
  3595. else
  3596. {
  3597. Fail("Const requires initializer", fieldDef->mFieldDeclaration->mNameNode);
  3598. }
  3599. }
  3600. else if (mBfIRBuilder != NULL)
  3601. {
  3602. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  3603. SetAndRestoreValue<bool> prevIgnoreWrite(mBfIRBuilder->mIgnoreWrites, true);
  3604. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, NULL);
  3605. BfMethodState methodState;
  3606. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  3607. methodState.mTempKind = BfMethodState::TempKind_Static;
  3608. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  3609. if ((fieldType->IsVar()) || (fieldType->IsUndefSizedArray()))
  3610. {
  3611. auto initValue = GetFieldInitializerValue(fieldInstance, fieldDef->mInitializer, fieldDef, fieldType);
  3612. if (!initValue)
  3613. {
  3614. AssertErrorState();
  3615. initValue = GetDefaultTypedValue(mContext->mBfObjectType);
  3616. }
  3617. if (fieldInstance != NULL)
  3618. {
  3619. if (fieldType->IsUndefSizedArray())
  3620. {
  3621. if ((initValue.mType->IsSizedArray()) && (initValue.mType->GetUnderlyingType() == fieldType->GetUnderlyingType()))
  3622. {
  3623. fieldInstance->mResolvedType = initValue.mType;
  3624. }
  3625. }
  3626. else
  3627. fieldInstance->mResolvedType = initValue.mType;
  3628. }
  3629. constValue = initValue.mValue;
  3630. }
  3631. else
  3632. {
  3633. auto uncastedInitValue = GetFieldInitializerValue(fieldInstance, fieldDef->mInitializer, fieldDef, fieldType);
  3634. constValue = uncastedInitValue.mValue;
  3635. }
  3636. if ((mCurTypeInstance->IsPayloadEnum()) && (fieldDef->IsEnumCaseEntry()))
  3637. {
  3638. // Illegal
  3639. constValue = BfIRValue();
  3640. }
  3641. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  3642. }
  3643. if (fieldInstance != NULL)
  3644. {
  3645. fieldType = fieldInstance->GetResolvedType();
  3646. if ((fieldType == NULL) || (fieldType->IsVar()))
  3647. {
  3648. SetAndRestoreValue<bool> prevIgnoreWrite(mBfIRBuilder->mIgnoreWrites, true);
  3649. AssertErrorState();
  3650. // Default const type is 'int'
  3651. BfTypedValue initValue = GetDefaultTypedValue(GetPrimitiveType(BfTypeCode_IntPtr));
  3652. if (fieldInstance != NULL)
  3653. {
  3654. fieldInstance->mResolvedType = initValue.mType;
  3655. }
  3656. constValue = initValue.mValue;
  3657. }
  3658. if ((constValue) && (fieldInstance->mConstIdx == -1))
  3659. {
  3660. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  3661. CurrentAddToConstHolder(constValue);
  3662. fieldInstance->mConstIdx = constValue.mId;
  3663. }
  3664. }
  3665. }
  3666. BfType* BfModule::ResolveVarFieldType(BfTypeInstance* typeInstance, BfFieldInstance* fieldInstance, BfFieldDef* field)
  3667. {
  3668. bool isDeclType = (field->mFieldDeclaration != NULL) && BfNodeDynCastExact<BfExprModTypeRef>(field->mFieldDeclaration->mTypeRef) != NULL;
  3669. auto fieldType = fieldInstance->GetResolvedType();
  3670. if ((field->mIsConst) && (!isDeclType))
  3671. {
  3672. ResolveConstField(typeInstance, fieldInstance, field);
  3673. return fieldInstance->GetResolvedType();
  3674. }
  3675. bool staticOnly = (field->mIsStatic) && (!isDeclType);
  3676. if (!fieldInstance->mIsInferredType)
  3677. return fieldType;
  3678. if ((!fieldType->IsVar()) && (!fieldType->IsUndefSizedArray()))
  3679. return fieldType;
  3680. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  3681. BfTypeState typeState(mCurTypeInstance, mContext->mCurTypeState);
  3682. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState, mContext->mCurTypeState->mType != typeInstance);
  3683. auto typeDef = typeInstance->mTypeDef;
  3684. if ((!field->mIsStatic) && (typeDef->mIsStatic))
  3685. {
  3686. AssertErrorState();
  3687. return fieldType;
  3688. }
  3689. bool hadInferenceCycle = false;
  3690. if (mContext->mFieldResolveReentrys.size() > 1)
  3691. {
  3692. if (mContext->mFieldResolveReentrys.IndexOf(fieldInstance, 1) != -1)
  3693. {
  3694. for (int i = 1; i < (int)mContext->mFieldResolveReentrys.size(); i++)
  3695. {
  3696. auto fieldInst = mContext->mFieldResolveReentrys[i];
  3697. auto fieldDef = fieldInst->GetFieldDef();
  3698. auto fieldOwner = fieldInst->mOwner;
  3699. auto fieldModule = fieldOwner->mModule;
  3700. SetAndRestoreValue<bool> prevIgnoreError(fieldModule->mIgnoreErrors, false);
  3701. fieldModule->Fail(StrFormat("Field '%s.%s' creates a type inference cycle", TypeToString(fieldOwner).c_str(), fieldDef->mName.c_str()), fieldDef->mTypeRef, true);
  3702. }
  3703. return fieldType;
  3704. }
  3705. }
  3706. mContext->mFieldResolveReentrys.push_back(fieldInstance);
  3707. AutoPopBack<decltype (mContext->mFieldResolveReentrys)> popTypeResolveReentry(&mContext->mFieldResolveReentrys);
  3708. SetAndRestoreValue<bool> prevResolvingVar(typeInstance->mResolvingVarField, true);
  3709. SetAndRestoreValue<bool> prevCtxResolvingVar(mContext->mResolvingVarField, true);
  3710. if ((field->mInitializer == NULL) && (!isDeclType))
  3711. {
  3712. if ((field->mTypeRef->IsA<BfVarTypeReference>()) || (field->mTypeRef->IsA<BfLetTypeReference>()))
  3713. Fail("Implicitly-typed fields must be initialized", field->GetRefNode());
  3714. return fieldType;
  3715. }
  3716. BfType* resolvedType = NULL;
  3717. if (!hadInferenceCycle)
  3718. {
  3719. BfTypeState typeState;
  3720. typeState.mPrevState = mContext->mCurTypeState;
  3721. typeState.mType = typeInstance;
  3722. typeState.mCurFieldDef = field;
  3723. typeState.mResolveKind = BfTypeState::ResolveKind_ResolvingVarType;
  3724. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  3725. SetAndRestoreValue<bool> prevIgnoreWrite(mBfIRBuilder->mIgnoreWrites, true);
  3726. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, NULL/*ctorMethod.mMethodInstance*/);
  3727. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  3728. BfMethodState methodState;
  3729. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  3730. methodState.mTempKind = staticOnly ? BfMethodState::TempKind_Static : BfMethodState::TempKind_NonStatic;
  3731. if (!staticOnly)
  3732. {
  3733. //BfLocalVariable localVar;
  3734. //methodState.mLocals.push_back(localVar);
  3735. }
  3736. if (isDeclType)
  3737. {
  3738. auto fieldDef = fieldInstance->GetFieldDef();
  3739. resolvedType = ResolveTypeRef(fieldDef->mTypeRef, BfPopulateType_Identity);
  3740. }
  3741. else
  3742. {
  3743. BfTypedValue valueFromExpr;
  3744. valueFromExpr = GetFieldInitializerValue(fieldInstance);
  3745. FixIntUnknown(valueFromExpr);
  3746. if (fieldType->IsUndefSizedArray())
  3747. {
  3748. if ((valueFromExpr.mType != NULL) && (valueFromExpr.mType->IsSizedArray()) && (valueFromExpr.mType->GetUnderlyingType() == fieldType->GetUnderlyingType()))
  3749. resolvedType = valueFromExpr.mType;
  3750. }
  3751. else
  3752. resolvedType = valueFromExpr.mType;
  3753. }
  3754. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  3755. }
  3756. if (resolvedType == NULL)
  3757. return fieldType;
  3758. fieldInstance->SetResolvedType(resolvedType);
  3759. if (field->mIsStatic)
  3760. {
  3761. }
  3762. else if (fieldInstance->mDataIdx >= 0)
  3763. {
  3764. }
  3765. else
  3766. {
  3767. BF_ASSERT(typeInstance->IsIncomplete());
  3768. }
  3769. return resolvedType;
  3770. }
  3771. void BfModule::MarkFieldInitialized(BfFieldInstance* fieldInstance)
  3772. {
  3773. BF_ASSERT(fieldInstance->mOwner == mCurTypeInstance);
  3774. auto fieldType = fieldInstance->GetResolvedType();
  3775. if ((fieldInstance->mMergedDataIdx != -1) && (mCurMethodState != NULL))
  3776. {
  3777. int fieldIdx = 0;
  3778. int fieldCount = 0;
  3779. fieldInstance->GetDataRange(fieldIdx, fieldCount);
  3780. fieldIdx--;
  3781. int count = fieldCount;
  3782. if (fieldIdx == -1)
  3783. count = 1;
  3784. //TODO: Under what circumstances could 'thisVariable' be NULL?
  3785. auto thisVariable = GetThisVariable();
  3786. if (thisVariable != NULL)
  3787. {
  3788. for (int i = 0; i < count; i++)
  3789. mCurMethodState->LocalDefined(thisVariable, fieldIdx + i);
  3790. }
  3791. }
  3792. }
  3793. bool BfModule::IsThreadLocal(BfFieldInstance * fieldInstance)
  3794. {
  3795. if (fieldInstance->mCustomAttributes == NULL)
  3796. return false;
  3797. auto fieldDef = fieldInstance->GetFieldDef();
  3798. if (!fieldDef->mIsStatic)
  3799. return false;
  3800. bool isThreadLocal = false;
  3801. if (fieldInstance->mCustomAttributes != NULL)
  3802. {
  3803. for (auto customAttr : fieldInstance->mCustomAttributes->mAttributes)
  3804. {
  3805. if (customAttr.mType->ToTypeInstance()->IsInstanceOf(mCompiler->mThreadStaticAttributeTypeDef))
  3806. return true;
  3807. }
  3808. }
  3809. return false;
  3810. }
  3811. BfTypedValue BfModule::GetFieldInitializerValue(BfFieldInstance* fieldInstance, BfExpression* initializer, BfFieldDef* fieldDef, BfType* fieldType, bool doStore)
  3812. {
  3813. if (fieldDef == NULL)
  3814. fieldDef = fieldInstance->GetFieldDef();
  3815. if (fieldType == NULL)
  3816. fieldType = fieldInstance->GetResolvedType();
  3817. if (initializer == NULL)
  3818. {
  3819. if (fieldDef == NULL)
  3820. return BfTypedValue();
  3821. initializer = fieldDef->mInitializer;
  3822. }
  3823. BfTypedValue staticVarRef;
  3824. BfTypedValue result;
  3825. if (initializer == NULL)
  3826. {
  3827. result = GetDefaultTypedValue(fieldInstance->mResolvedType);
  3828. }
  3829. else
  3830. {
  3831. if ((mCompiler->mIsResolveOnly) && (mCompiler->mResolvePassData->mSourceClassifier != NULL) && (initializer->IsFromParser(mCompiler->mResolvePassData->mParser)))
  3832. {
  3833. mCompiler->mResolvePassData->mSourceClassifier->SetElementType(initializer, BfSourceElementType_Normal);
  3834. mCompiler->mResolvePassData->mSourceClassifier->VisitChildNoRef(initializer);
  3835. }
  3836. if ((mCurTypeInstance->IsPayloadEnum()) && (fieldDef->IsEnumCaseEntry()))
  3837. {
  3838. Fail("Enums with payloads cannot have explicitly-defined discriminators", initializer);
  3839. BfConstResolver constResolver(this);
  3840. constResolver.Resolve(initializer);
  3841. return GetDefaultTypedValue(fieldType);
  3842. }
  3843. else if (fieldDef->mIsConst)
  3844. {
  3845. int ceExecuteId = -1;
  3846. if (mCompiler->mCEMachine != NULL)
  3847. ceExecuteId = mCompiler->mCEMachine->mExecuteId;
  3848. BfTypeState typeState;
  3849. typeState.mType = mCurTypeInstance;
  3850. typeState.mCurTypeDef = fieldDef->mDeclaringType;
  3851. typeState.mCurFieldDef = fieldDef;
  3852. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  3853. BfConstResolver constResolver(this);
  3854. if (fieldType->IsVar())
  3855. return constResolver.Resolve(initializer);
  3856. else
  3857. {
  3858. BfConstResolveFlags resolveFlags = BfConstResolveFlag_None;
  3859. if ((mCompiler->mResolvePassData != NULL) && (mCurTypeInstance->IsEnum()) && (fieldDef->IsEnumCaseEntry()) &&
  3860. (mCompiler->mResolvePassData->mAutoCompleteTempTypes.Contains(fieldDef->mDeclaringType)))
  3861. {
  3862. // We avoid doing the cast here because the value we're typing may not be in the range of the current
  3863. // auto-created underlying type and it will cause an 'error flash'. We defer errors until the full resolve for that purpose
  3864. resolveFlags = BfConstResolveFlag_NoCast;
  3865. }
  3866. UpdateSrcPos(initializer);
  3867. auto result = constResolver.Resolve(initializer, fieldType, resolveFlags);
  3868. if ((mCompiler->mCEMachine != NULL) && (fieldInstance != NULL))
  3869. {
  3870. if (mCompiler->mCEMachine->mExecuteId != ceExecuteId)
  3871. fieldInstance->mHadConstEval = true;
  3872. }
  3873. return result;
  3874. }
  3875. }
  3876. BfExprEvaluator exprEvaluator(this);
  3877. if (doStore)
  3878. {
  3879. staticVarRef = ReferenceStaticField(fieldInstance);
  3880. exprEvaluator.mReceivingValue = &staticVarRef;
  3881. }
  3882. if (fieldType->IsVar())
  3883. result = CreateValueFromExpression(exprEvaluator, initializer, NULL, (BfEvalExprFlags)(BfEvalExprFlags_NoValueAddr | BfEvalExprFlags_FieldInitializer));
  3884. else
  3885. result = CreateValueFromExpression(exprEvaluator, initializer, fieldType, (BfEvalExprFlags)(BfEvalExprFlags_NoValueAddr | BfEvalExprFlags_FieldInitializer));
  3886. if (doStore)
  3887. {
  3888. if (exprEvaluator.mReceivingValue == NULL)
  3889. doStore = false; // Already stored
  3890. }
  3891. }
  3892. if (fieldInstance != NULL)
  3893. MarkFieldInitialized(fieldInstance);
  3894. if ((doStore) && (result))
  3895. {
  3896. if (fieldInstance->mResolvedType->IsUndefSizedArray())
  3897. {
  3898. if ((!mBfIRBuilder->mIgnoreWrites) && (!mCompiler->mFastFinish))
  3899. AssertErrorState();
  3900. }
  3901. else
  3902. {
  3903. result = LoadValue(result);
  3904. if (!result.mType->IsValuelessType())
  3905. mBfIRBuilder->CreateStore(result.mValue, staticVarRef.mValue);
  3906. }
  3907. }
  3908. return result;
  3909. }
  3910. void BfModule::CheckInterfaceMethod(BfMethodInstance* methodInstance)
  3911. {
  3912. }
  3913. void BfModule::FindSubTypes(BfTypeInstance* classType, SizedArrayImpl<int>* outVals, SizedArrayImpl<BfTypeInstance*>* exChecks, bool isInterfacePass)
  3914. {
  3915. PopulateType(classType);
  3916. if (isInterfacePass)
  3917. {
  3918. for (auto ifaceInst : classType->mInterfaces)
  3919. {
  3920. if (exChecks->Contains(ifaceInst.mInterfaceType))
  3921. continue;
  3922. if (outVals->Contains(ifaceInst.mInterfaceType->mTypeId))
  3923. continue;
  3924. if (ifaceInst.mDeclaringType->IsExtension())
  3925. {
  3926. bool needsExCheck = false;
  3927. if (ifaceInst.mDeclaringType->mProject != classType->mTypeDef->mProject)
  3928. {
  3929. PopulateType(ifaceInst.mInterfaceType, BfPopulateType_DataAndMethods);
  3930. if (ifaceInst.mInterfaceType->mVirtualMethodTableSize > 0)
  3931. {
  3932. exChecks->push_back(ifaceInst.mInterfaceType);
  3933. continue;
  3934. }
  3935. else
  3936. {
  3937. // We can only do an 'exCheck' if we're actually going to slot this interface
  3938. }
  3939. }
  3940. }
  3941. outVals->push_back(ifaceInst.mInterfaceType->mTypeId);
  3942. }
  3943. }
  3944. else
  3945. {
  3946. outVals->push_back(classType->mTypeId);
  3947. }
  3948. if (classType->mBaseType != NULL)
  3949. {
  3950. FindSubTypes(classType->mBaseType, outVals, exChecks, isInterfacePass);
  3951. }
  3952. }
  3953. void BfModule::CreateDynamicCastMethod()
  3954. {
  3955. auto objType = mContext->mBfObjectType;
  3956. if ((mCompiler->mIsResolveOnly) || (!mIsReified))
  3957. {
  3958. // The main reason to punt on this method for ResolveOnly is because types can be created
  3959. // and destroyed quickly during autocomplete and the typeId creep can generate lots of
  3960. // entries in the LLVM ConstantInt pool, primarily from the FindSubTypes call. We can
  3961. // remove this punt when we recycle typeId's
  3962. mBfIRBuilder->CreateRet(mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapTypeInstPtr(objType)));
  3963. mCurMethodState->mHadReturn = true;
  3964. return;
  3965. }
  3966. bool isInterfacePass = mCurMethodInstance->mMethodDef->mName == BF_METHODNAME_DYNAMICCAST_INTERFACE;
  3967. auto func = mCurMethodState->mIRFunction;
  3968. auto thisValue = mBfIRBuilder->GetArgument(0);
  3969. auto typeIdValue = mBfIRBuilder->GetArgument(1);
  3970. auto intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  3971. auto int32Type = GetPrimitiveType(BfTypeCode_Int32);
  3972. typeIdValue = CastToValue(NULL, BfTypedValue(typeIdValue, intPtrType), int32Type, (BfCastFlags)(BfCastFlags_Explicit | BfCastFlags_SilentFail));
  3973. auto thisObject = mBfIRBuilder->CreateBitCast(thisValue, mBfIRBuilder->MapType(objType));
  3974. auto trueBB = mBfIRBuilder->CreateBlock("check.true");
  3975. //auto falseBB = mBfIRBuilder->CreateBlock("check.false");
  3976. auto exitBB = mBfIRBuilder->CreateBlock("exit");
  3977. SizedArray<int, 8> typeMatches;
  3978. SizedArray<BfTypeInstance*, 8> exChecks;
  3979. FindSubTypes(mCurTypeInstance, &typeMatches, &exChecks, isInterfacePass);
  3980. if ((mCurTypeInstance->IsGenericTypeInstance()) && (!mCurTypeInstance->IsUnspecializedType()))
  3981. {
  3982. // Add 'unbound' type id to cast list so things like "List<int> is List<>" work
  3983. auto genericTypeInst = mCurTypeInstance->mTypeDef;
  3984. BfTypeVector genericArgs;
  3985. for (int i = 0; i < (int) genericTypeInst->mGenericParamDefs.size(); i++)
  3986. genericArgs.push_back(GetGenericParamType(BfGenericParamKind_Type, i));
  3987. auto unboundType = ResolveTypeDef(mCurTypeInstance->mTypeDef->GetDefinition(), genericArgs, BfPopulateType_Declaration);
  3988. typeMatches.push_back(unboundType->mTypeId);
  3989. }
  3990. if (mCurTypeInstance->IsBoxed())
  3991. {
  3992. BfBoxedType* boxedType = (BfBoxedType*)mCurTypeInstance;
  3993. BfTypeInstance* innerType = boxedType->mElementType->ToTypeInstance();
  3994. FindSubTypes(innerType, &typeMatches, &exChecks, isInterfacePass);
  3995. if (innerType->IsTypedPrimitive())
  3996. {
  3997. auto underlyingType = innerType->GetUnderlyingType();
  3998. typeMatches.push_back(underlyingType->mTypeId);
  3999. }
  4000. auto innerTypeInst = innerType->ToTypeInstance();
  4001. if ((innerTypeInst->IsInstanceOf(mCompiler->mSizedArrayTypeDef)) ||
  4002. (innerTypeInst->IsInstanceOf(mCompiler->mPointerTTypeDef)) ||
  4003. (innerTypeInst->IsInstanceOf(mCompiler->mMethodRefTypeDef)))
  4004. {
  4005. PopulateType(innerTypeInst);
  4006. //TODO: What case was this supposed to handle?
  4007. //typeMatches.push_back(innerTypeInst->mFieldInstances[0].mResolvedType->mTypeId);
  4008. }
  4009. }
  4010. auto curBlock = mBfIRBuilder->GetInsertBlock();
  4011. BfIRValue vDataPtr;
  4012. if (!exChecks.empty())
  4013. {
  4014. BfType* intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  4015. auto ptrPtrType = mBfIRBuilder->GetPointerTo(mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapType(intPtrType)));
  4016. auto vDataPtrPtr = mBfIRBuilder->CreateBitCast(thisValue, ptrPtrType);
  4017. vDataPtr = FixClassVData(mBfIRBuilder->CreateLoad(vDataPtrPtr/*, "vtable"*/));
  4018. }
  4019. auto switchStatement = mBfIRBuilder->CreateSwitch(typeIdValue, exitBB, (int)typeMatches.size() + (int)exChecks.size());
  4020. for (auto typeMatch : typeMatches)
  4021. mBfIRBuilder->AddSwitchCase(switchStatement, GetConstValue32(typeMatch), trueBB);
  4022. Array<BfIRValue> incomingFalses;
  4023. for (auto ifaceTypeInst : exChecks)
  4024. {
  4025. BfIRBlock nextBB = mBfIRBuilder->CreateBlock("exCheck", true);
  4026. mBfIRBuilder->AddSwitchCase(switchStatement, GetConstValue32(ifaceTypeInst->mTypeId), nextBB);
  4027. mBfIRBuilder->SetInsertPoint(nextBB);
  4028. BfIRValue slotOfs = GetInterfaceSlotNum(ifaceTypeInst);
  4029. auto ifacePtrPtr = mBfIRBuilder->CreateInBoundsGEP(vDataPtr, slotOfs/*, "iface"*/);
  4030. auto ifacePtr = mBfIRBuilder->CreateLoad(ifacePtrPtr);
  4031. auto cmpResult = mBfIRBuilder->CreateCmpNE(ifacePtr, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 0));
  4032. mBfIRBuilder->CreateCondBr(cmpResult, trueBB, exitBB);
  4033. incomingFalses.push_back(nextBB);
  4034. }
  4035. mBfIRBuilder->AddBlock(trueBB);
  4036. mBfIRBuilder->SetInsertPoint(trueBB);
  4037. mBfIRBuilder->CreateBr(exitBB);
  4038. mBfIRBuilder->AddBlock(exitBB);
  4039. mBfIRBuilder->SetInsertPoint(exitBB);
  4040. auto phi = mBfIRBuilder->CreatePhi(mBfIRBuilder->MapTypeInstPtr(objType), 2);
  4041. mBfIRBuilder->AddPhiIncoming(phi, thisObject, trueBB);
  4042. auto nullValue = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapTypeInstPtr(objType));
  4043. for (auto incomingFalseBlock : incomingFalses)
  4044. mBfIRBuilder->AddPhiIncoming(phi, nullValue, incomingFalseBlock);
  4045. mBfIRBuilder->AddPhiIncoming(phi, nullValue, curBlock);
  4046. mBfIRBuilder->CreateRet(phi);
  4047. mCurMethodState->mHadReturn = true;
  4048. }
  4049. void BfModule::EmitEquals(BfTypedValue leftValue, BfTypedValue rightValue, BfIRBlock exitBB, bool strictEquals)
  4050. {
  4051. BfExprEvaluator exprEvaluator(this);
  4052. exprEvaluator.mExpectingType = mCurMethodInstance->mReturnType;
  4053. auto typeInst = rightValue.mType->ToTypeInstance();
  4054. exprEvaluator.PerformBinaryOperation((BfAstNode*)NULL, (BfAstNode*)NULL, strictEquals ? BfBinaryOp_StrictEquality : BfBinaryOp_Equality, NULL, BfBinOpFlag_IgnoreOperatorWithWrongResult, leftValue, rightValue);
  4055. BfTypedValue result = exprEvaluator.GetResult();
  4056. if (result.mType != GetPrimitiveType(BfTypeCode_Boolean))
  4057. {
  4058. // Fail?
  4059. }
  4060. if ((result) && (!result.mType->IsVar()))
  4061. {
  4062. auto nextBB = mBfIRBuilder->CreateBlock("next");
  4063. mBfIRBuilder->CreateCondBr(result.mValue, nextBB, exitBB);
  4064. mBfIRBuilder->AddBlock(nextBB);
  4065. mBfIRBuilder->SetInsertPoint(nextBB);
  4066. }
  4067. }
  4068. void BfModule::CreateFakeCallerMethod(const String& funcName)
  4069. {
  4070. if (mCurMethodInstance->mHasFailed)
  4071. return;
  4072. if (mCurMethodInstance->mMethodDef->mIsSkipCall)
  4073. return;
  4074. BF_ASSERT(mCurMethodInstance->mIRFunction);
  4075. auto voidType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_None));
  4076. SizedArray<BfIRType, 4> paramTypes;
  4077. BfIRFunctionType funcType = mBfIRBuilder->CreateFunctionType(voidType, paramTypes);
  4078. BfIRFunction func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_Internal, "FORCELINK_" + funcName);
  4079. mBfIRBuilder->SetActiveFunction(func);
  4080. auto entryBlock = mBfIRBuilder->CreateBlock("main", true);
  4081. mBfIRBuilder->SetInsertPoint(entryBlock);
  4082. BfMethodState methodState;
  4083. methodState.mIRHeadBlock = entryBlock;
  4084. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  4085. SizedArray<BfIRValue, 8> args;
  4086. BfExprEvaluator exprEvaluator(this);
  4087. if (mCurMethodInstance->GetStructRetIdx() == 0)
  4088. {
  4089. auto retPtrType = CreatePointerType(mCurMethodInstance->mReturnType);
  4090. exprEvaluator.PushArg(GetDefaultTypedValue(retPtrType, true, BfDefaultValueKind_Const), args);
  4091. }
  4092. if (mCurMethodInstance->HasThis())
  4093. {
  4094. auto thisValue = GetDefaultTypedValue(mCurMethodInstance->GetOwner(), true, mCurTypeInstance->IsComposite() ? BfDefaultValueKind_Addr : BfDefaultValueKind_Const);
  4095. exprEvaluator.PushThis(NULL, thisValue, mCurMethodInstance, args);
  4096. }
  4097. if (mCurMethodInstance->GetStructRetIdx() == 1)
  4098. {
  4099. auto retPtrType = CreatePointerType(mCurMethodInstance->mReturnType);
  4100. exprEvaluator.PushArg(GetDefaultTypedValue(retPtrType, true, BfDefaultValueKind_Const), args);
  4101. }
  4102. for (int paramIdx = 0; paramIdx < mCurMethodInstance->GetParamCount(); paramIdx++)
  4103. {
  4104. auto paramType = mCurMethodInstance->GetParamType(paramIdx);
  4105. if (paramType->IsValuelessType())
  4106. continue;
  4107. exprEvaluator.PushArg(GetDefaultTypedValue(paramType, true, paramType->IsComposite() ? BfDefaultValueKind_Addr : BfDefaultValueKind_Const), args);
  4108. }
  4109. mBfIRBuilder->CreateCall(mCurMethodInstance->mIRFunction, args);
  4110. mBfIRBuilder->CreateRetVoid();
  4111. }
  4112. void BfModule::CreateDelegateEqualsMethod()
  4113. {
  4114. if (mBfIRBuilder->mIgnoreWrites)
  4115. return;
  4116. auto refNode = mCurTypeInstance->mTypeDef->GetRefNode();
  4117. if (refNode == NULL)
  4118. refNode = mCompiler->mValueTypeTypeDef->GetRefNode();
  4119. UpdateSrcPos(refNode);
  4120. SetIllegalSrcPos();
  4121. auto boolType = GetPrimitiveType(BfTypeCode_Boolean);
  4122. auto resultVal = CreateAlloca(boolType);
  4123. mBfIRBuilder->CreateStore(GetConstValue(0, boolType), resultVal);
  4124. auto exitBB = mBfIRBuilder->CreateBlock("exit");
  4125. auto delegateType = ResolveTypeDef(mCompiler->mDelegateTypeDef)->ToTypeInstance();
  4126. mBfIRBuilder->PopulateType(delegateType);
  4127. BfExprEvaluator exprEvaluator(this);
  4128. BfTypedValue leftTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[0]);
  4129. BfTypedValue lhsDelegate = BfTypedValue(mBfIRBuilder->CreateBitCast(leftTypedVal.mValue, mBfIRBuilder->MapType(delegateType)), delegateType);
  4130. BfTypedValue rhsDelegate = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  4131. rhsDelegate = LoadValue(rhsDelegate);
  4132. BfTypedValue rightTypedVal = BfTypedValue(mBfIRBuilder->CreateBitCast(rhsDelegate.mValue, mBfIRBuilder->MapType(mCurTypeInstance)), mCurTypeInstance);
  4133. auto& targetFieldInstance = delegateType->mFieldInstances[0];
  4134. BfTypedValue leftValue = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(lhsDelegate.mValue, 0, targetFieldInstance.mDataIdx), targetFieldInstance.mResolvedType, true);
  4135. BfTypedValue rightValue = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(rhsDelegate.mValue, 0, targetFieldInstance.mDataIdx), targetFieldInstance.mResolvedType, true);
  4136. leftValue = LoadValue(leftValue);
  4137. rightValue = LoadValue(rightValue);
  4138. EmitEquals(leftValue, rightValue, exitBB, false);
  4139. bool hadComparison = false;
  4140. for (auto& fieldRef : mCurTypeInstance->mFieldInstances)
  4141. {
  4142. BfFieldInstance* fieldInstance = &fieldRef;
  4143. if (fieldInstance->mDataOffset == -1)
  4144. continue;
  4145. auto fieldType = fieldInstance->mResolvedType;
  4146. if (fieldType->IsValuelessType())
  4147. continue;
  4148. if (fieldType->IsVar())
  4149. continue;
  4150. if (fieldType->IsMethodRef())
  4151. continue;
  4152. if (fieldType->IsRef())
  4153. fieldType = CreatePointerType(fieldType->GetUnderlyingType());
  4154. BfTypedValue leftValue = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(leftTypedVal.mValue, 0, fieldInstance->mDataIdx), fieldType, true);
  4155. BfTypedValue rightValue = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(rightTypedVal.mValue, 0, fieldInstance->mDataIdx), fieldType, true);
  4156. if (!fieldInstance->mResolvedType->IsComposite())
  4157. {
  4158. leftValue = LoadValue(leftValue);
  4159. rightValue = LoadValue(rightValue);
  4160. }
  4161. EmitEquals(leftValue, rightValue, exitBB, false);
  4162. }
  4163. mBfIRBuilder->CreateStore(GetConstValue(1, boolType), resultVal);
  4164. mBfIRBuilder->CreateBr(exitBB);
  4165. mBfIRBuilder->AddBlock(exitBB);
  4166. mBfIRBuilder->SetInsertPoint(exitBB);
  4167. auto loadedResult = mBfIRBuilder->CreateLoad(resultVal);
  4168. ClearLifetimeEnds();
  4169. mBfIRBuilder->CreateRet(loadedResult);
  4170. mCurMethodState->mHadReturn = true;
  4171. }
  4172. void BfModule::CreateValueTypeEqualsMethod(bool strictEquals)
  4173. {
  4174. if (mCurMethodInstance->mIsUnspecialized)
  4175. return;
  4176. if (mBfIRBuilder->mIgnoreWrites)
  4177. return;
  4178. BF_ASSERT(!mCurTypeInstance->IsBoxed());
  4179. auto compareType = mCurMethodInstance->mParams[0].mResolvedType;
  4180. bool isValid = true;
  4181. auto boolType = GetPrimitiveType(BfTypeCode_Boolean);
  4182. if (compareType->IsValuelessType())
  4183. {
  4184. mBfIRBuilder->CreateRet(GetDefaultValue(boolType));
  4185. return;
  4186. }
  4187. if (compareType->IsTypedPrimitive())
  4188. {
  4189. BfExprEvaluator exprEvaluator(this);
  4190. BfTypedValue leftTypedVal = LoadValue(exprEvaluator.LoadLocal(mCurMethodState->mLocals[0]));
  4191. BfTypedValue rightTypedVal = LoadValue(exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]));
  4192. auto cmpResult = mBfIRBuilder->CreateCmpEQ(leftTypedVal.mValue, rightTypedVal.mValue);
  4193. mBfIRBuilder->CreateRet(cmpResult);
  4194. return;
  4195. }
  4196. auto compareDType = compareType->ToDependedType();
  4197. BfTypeInstance* compareTypeInst = compareType->ToTypeInstance();
  4198. if (compareTypeInst != NULL)
  4199. {
  4200. if (compareType->IsPrimitiveType())
  4201. compareTypeInst = GetWrappedStructType(compareType);
  4202. if ((compareTypeInst == NULL) || (!compareTypeInst->IsValueType()))
  4203. {
  4204. isValid = false;
  4205. }
  4206. mBfIRBuilder->PopulateType(compareTypeInst);
  4207. }
  4208. if (!isValid)
  4209. {
  4210. ClearLifetimeEnds();
  4211. mBfIRBuilder->CreateRet(GetDefaultValue(boolType));
  4212. return;
  4213. }
  4214. AddDependency(compareDType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ReadFields);
  4215. auto refNode = mCurTypeInstance->mTypeDef->GetRefNode();
  4216. if (refNode == NULL)
  4217. refNode = mCompiler->mValueTypeTypeDef->GetRefNode();
  4218. UpdateSrcPos(refNode);
  4219. SetIllegalSrcPos();
  4220. auto resultVal = CreateAlloca(boolType);
  4221. mBfIRBuilder->CreateStore(GetConstValue(0, boolType), resultVal);
  4222. auto exitBB = mBfIRBuilder->CreateBlock("exit");
  4223. if (compareType->IsValuelessType())
  4224. {
  4225. // Always equal, nothing to do
  4226. }
  4227. else if (compareType->IsSizedArray())
  4228. {
  4229. auto sizedArrayType = (BfSizedArrayType*)compareType;
  4230. auto _SizedIndex = [&](BfIRValue target, BfIRValue index)
  4231. {
  4232. BfTypedValue result;
  4233. // if (sizedArrayType->mElementType->IsSizeAligned())
  4234. // {
  4235. // auto ptrType = CreatePointerType(sizedArrayType->mElementType);
  4236. // auto ptrValue = mBfIRBuilder->CreateBitCast(target, mBfIRBuilder->MapType(ptrType));
  4237. // auto gepResult = mBfIRBuilder->CreateInBoundsGEP(ptrValue, index);
  4238. // result = BfTypedValue(gepResult, sizedArrayType->mElementType, BfTypedValueKind_Addr);
  4239. // }
  4240. // else
  4241. // {
  4242. // auto indexResult = CreateIndexedValue(sizedArrayType->mElementType, target, index);
  4243. // result = BfTypedValue(indexResult, sizedArrayType->mElementType, BfTypedValueKind_Addr);
  4244. // }
  4245. auto indexResult = CreateIndexedValue(sizedArrayType->mElementType, target, index, true);
  4246. result = BfTypedValue(indexResult, sizedArrayType->mElementType, BfTypedValueKind_Addr);
  4247. if (!result.mType->IsValueType())
  4248. result = LoadValue(result);
  4249. return result;
  4250. };
  4251. if (sizedArrayType->mElementCount > 6)
  4252. {
  4253. auto intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  4254. auto itr = CreateAlloca(intPtrType);
  4255. mBfIRBuilder->CreateStore(GetDefaultValue(intPtrType), itr);
  4256. auto loopBB = mBfIRBuilder->CreateBlock("loop", true);
  4257. auto bodyBB = mBfIRBuilder->CreateBlock("body", true);
  4258. auto doneBB = mBfIRBuilder->CreateBlock("done", true);
  4259. mBfIRBuilder->CreateBr(loopBB);
  4260. mBfIRBuilder->SetInsertPoint(loopBB);
  4261. auto loadedItr = mBfIRBuilder->CreateLoad(itr);
  4262. auto cmpRes = mBfIRBuilder->CreateCmpGTE(loadedItr, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, (uint64)sizedArrayType->mElementCount), true);
  4263. mBfIRBuilder->CreateCondBr(cmpRes, doneBB, bodyBB);
  4264. mBfIRBuilder->SetInsertPoint(bodyBB);
  4265. BfTypedValue leftValue = _SizedIndex(mCurMethodState->mLocals[0]->mValue, loadedItr);
  4266. BfTypedValue rightValue = _SizedIndex(mCurMethodState->mLocals[1]->mValue, loadedItr);
  4267. EmitEquals(leftValue, rightValue, exitBB, strictEquals);
  4268. auto incValue = mBfIRBuilder->CreateAdd(loadedItr, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 1));
  4269. mBfIRBuilder->CreateStore(incValue, itr);
  4270. mBfIRBuilder->CreateBr(loopBB);
  4271. mBfIRBuilder->SetInsertPoint(doneBB);
  4272. }
  4273. else
  4274. {
  4275. for (int dataIdx = 0; dataIdx < sizedArrayType->mElementCount; dataIdx++)
  4276. {
  4277. BfTypedValue leftValue = _SizedIndex(mCurMethodState->mLocals[0]->mValue, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, dataIdx));
  4278. BfTypedValue rightValue = _SizedIndex(mCurMethodState->mLocals[1]->mValue, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, dataIdx));
  4279. EmitEquals(leftValue, rightValue, exitBB, strictEquals);
  4280. }
  4281. }
  4282. }
  4283. else if (compareType->IsMethodRef())
  4284. {
  4285. auto methodRefType = (BfMethodRefType*)compareType;
  4286. BfMethodInstance* methodInstance = methodRefType->mMethodRef;
  4287. BfExprEvaluator exprEvaluator(this);
  4288. BfTypedValue leftTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[0]);
  4289. BfTypedValue rightTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  4290. // We only need to compare the 'this' capture. The rationale is that it's impossible to capture any other non-matching
  4291. // values for the same method reference -- they will always refer back to the same local variables.
  4292. int dataIdx = methodRefType->GetDataIdxFromParamIdx(-1);
  4293. if (dataIdx != -1)
  4294. {
  4295. bool failed = false;
  4296. BfTypedValue leftValue = exprEvaluator.DoImplicitArgCapture(NULL, methodInstance, methodRefType->GetParamIdxFromDataIdx(dataIdx), failed, BfImplicitParamKind_General, leftTypedVal);
  4297. BfTypedValue rightValue = exprEvaluator.DoImplicitArgCapture(NULL, methodInstance, methodRefType->GetParamIdxFromDataIdx(dataIdx), failed, BfImplicitParamKind_General, rightTypedVal);
  4298. BF_ASSERT(!failed);
  4299. EmitEquals(leftValue, rightValue, exitBB, strictEquals);
  4300. }
  4301. }
  4302. else if (compareTypeInst->IsEnum())
  4303. {
  4304. //auto intType = GetPrimitiveType(BfTypeCode_Int32);
  4305. BfExprEvaluator exprEvaluator(this);
  4306. BfTypedValue leftTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[0]);
  4307. BfTypedValue rightTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  4308. auto dscrType = compareTypeInst->GetDiscriminatorType();
  4309. BfTypedValue leftValue = ExtractValue(leftTypedVal, NULL, 2);
  4310. leftValue = LoadValue(leftValue);
  4311. BfTypedValue rightValue = ExtractValue(rightTypedVal, NULL, 2);
  4312. rightValue = LoadValue(rightValue);
  4313. BfTypedValue leftPayload = ExtractValue(leftTypedVal, NULL, 1);
  4314. BfTypedValue rightPayload = ExtractValue(rightTypedVal, NULL, 1);
  4315. EmitEquals(leftValue, rightValue, exitBB, strictEquals);
  4316. int enumCount = 0;
  4317. for (auto& fieldRef : compareTypeInst->mFieldInstances)
  4318. {
  4319. BfFieldInstance* fieldInstance = &fieldRef;
  4320. BfFieldDef* fieldDef = fieldInstance->GetFieldDef();
  4321. if ((fieldDef != NULL) && (fieldDef->IsEnumCaseEntry()))
  4322. {
  4323. enumCount = -fieldInstance->mDataIdx;
  4324. }
  4325. }
  4326. if (enumCount > 0)
  4327. {
  4328. BfIRBlock matchedBlock = mBfIRBuilder->CreateBlock("matched");
  4329. auto switchVal = mBfIRBuilder->CreateSwitch(leftValue.mValue, exitBB, enumCount);
  4330. for (auto& fieldRef : compareTypeInst->mFieldInstances)
  4331. {
  4332. BfFieldInstance* fieldInstance = &fieldRef;
  4333. BfFieldDef* fieldDef = fieldInstance->GetFieldDef();
  4334. if ((fieldDef != NULL) && (fieldDef->IsEnumCaseEntry()))
  4335. {
  4336. int enumIdx = -fieldInstance->mDataIdx - 1;
  4337. if (fieldInstance->mResolvedType->mSize == 0)
  4338. {
  4339. mBfIRBuilder->AddSwitchCase(switchVal, mBfIRBuilder->CreateConst(dscrType->mTypeDef->mTypeCode, enumIdx), matchedBlock);
  4340. }
  4341. else
  4342. {
  4343. auto caseBlock = mBfIRBuilder->CreateBlock("case", true);
  4344. mBfIRBuilder->SetInsertPoint(caseBlock);
  4345. auto tuplePtr = CreatePointerType(fieldInstance->mResolvedType);
  4346. BfTypedValue leftTuple;
  4347. BfTypedValue rightTuple;
  4348. if (leftPayload.IsAddr())
  4349. {
  4350. leftTuple = BfTypedValue(mBfIRBuilder->CreateBitCast(leftPayload.mValue, mBfIRBuilder->MapType(tuplePtr)), fieldInstance->mResolvedType, true);
  4351. rightTuple = BfTypedValue(mBfIRBuilder->CreateBitCast(rightPayload.mValue, mBfIRBuilder->MapType(tuplePtr)), fieldInstance->mResolvedType, true);
  4352. }
  4353. else
  4354. {
  4355. leftTuple = Cast(NULL, leftPayload, fieldInstance->mResolvedType, BfCastFlags_Force);
  4356. rightTuple = Cast(NULL, rightPayload, fieldInstance->mResolvedType, BfCastFlags_Force);
  4357. }
  4358. EmitEquals(leftTuple, rightTuple, exitBB, strictEquals);
  4359. mBfIRBuilder->CreateBr(matchedBlock);
  4360. mBfIRBuilder->AddSwitchCase(switchVal, mBfIRBuilder->CreateConst(dscrType->mTypeDef->mTypeCode, enumIdx), caseBlock);
  4361. }
  4362. }
  4363. }
  4364. mBfIRBuilder->AddBlock(matchedBlock);
  4365. mBfIRBuilder->SetInsertPoint(matchedBlock);
  4366. }
  4367. }
  4368. else if (compareTypeInst->IsUnion())
  4369. {
  4370. auto innerType = compareTypeInst->GetUnionInnerType();
  4371. if (!innerType->IsValuelessType())
  4372. {
  4373. BfExprEvaluator exprEvaluator(this);
  4374. BfTypedValue leftTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[0]);
  4375. BfTypedValue leftUnionTypedVal = ExtractValue(leftTypedVal, NULL, 1);
  4376. BfTypedValue rightTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  4377. BfTypedValue rightUnionTypedVal = ExtractValue(rightTypedVal, NULL, 1);
  4378. EmitEquals(leftUnionTypedVal, rightUnionTypedVal, exitBB, strictEquals);
  4379. }
  4380. }
  4381. else
  4382. {
  4383. BfExprEvaluator exprEvaluator(this);
  4384. BfTypedValue leftTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[0]);
  4385. BfTypedValue rightTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  4386. bool hadComparison = false;
  4387. for (auto& fieldRef : compareTypeInst->mFieldInstances)
  4388. {
  4389. BfFieldInstance* fieldInstance = &fieldRef;
  4390. if (fieldInstance->mDataOffset == -1)
  4391. continue;
  4392. if (fieldInstance->mResolvedType->IsValuelessType())
  4393. continue;
  4394. if (fieldInstance->mResolvedType->IsVar())
  4395. continue;
  4396. BfTypedValue leftValue = ExtractValue(leftTypedVal, fieldInstance, fieldInstance->mDataIdx);
  4397. BfTypedValue rightValue = ExtractValue(rightTypedVal, fieldInstance, fieldInstance->mDataIdx);
  4398. if (!fieldInstance->mResolvedType->IsComposite())
  4399. {
  4400. leftValue = LoadValue(leftValue);
  4401. rightValue = LoadValue(rightValue);
  4402. }
  4403. EmitEquals(leftValue, rightValue, exitBB, strictEquals);
  4404. }
  4405. auto baseTypeInst = compareTypeInst->mBaseType;
  4406. if ((baseTypeInst != NULL) && (baseTypeInst->mTypeDef != mCompiler->mValueTypeTypeDef))
  4407. {
  4408. BfTypedValue leftValue = Cast(NULL, leftTypedVal, baseTypeInst);
  4409. BfTypedValue rightValue = Cast(NULL, rightTypedVal, baseTypeInst);
  4410. EmitEquals(leftValue, rightValue, exitBB, strictEquals);
  4411. }
  4412. }
  4413. mBfIRBuilder->CreateStore(GetConstValue(1, boolType), resultVal);
  4414. mBfIRBuilder->CreateBr(exitBB);
  4415. mBfIRBuilder->AddBlock(exitBB);
  4416. mBfIRBuilder->SetInsertPoint(exitBB);
  4417. auto loadedResult = mBfIRBuilder->CreateLoad(resultVal);
  4418. ClearLifetimeEnds();
  4419. mBfIRBuilder->CreateRet(loadedResult);
  4420. mCurMethodState->mHadReturn = true;
  4421. }
  4422. BfIRValue BfModule::CreateClassVDataGlobal(BfTypeInstance* typeInstance, int* outNumElements, String* outMangledName)
  4423. {
  4424. if (mBfIRBuilder->mIgnoreWrites)
  4425. return mBfIRBuilder->GetFakeVal();
  4426. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  4427. BfType* classVDataType = ResolveTypeDef(mCompiler->mClassVDataTypeDef);
  4428. if (mIsComptimeModule)
  4429. {
  4430. auto idVal = mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, typeInstance->mTypeId);
  4431. return mBfIRBuilder->CreateIntToPtr(idVal, mBfIRBuilder->MapType(CreatePointerType(classVDataType)));
  4432. }
  4433. BfIRValue* globalVariablePtr = NULL;
  4434. mClassVDataRefs.TryGetValue(typeInstance, &globalVariablePtr);
  4435. int numElements = 1;
  4436. if ((outNumElements != NULL) || (globalVariablePtr == NULL))
  4437. {
  4438. numElements += mCompiler->mMaxInterfaceSlots;
  4439. auto maxIFaceVirtIdx = 0;
  4440. if (!typeInstance->IsInterface())
  4441. {
  4442. int dynCastDataElems = 1 + mCompiler->mMaxInterfaceSlots;
  4443. numElements += ((dynCastDataElems * 4) + mSystem->mPtrSize - 1) / mSystem->mPtrSize;
  4444. numElements += typeInstance->GetOrigVTableSize();
  4445. int ifaceMethodLen = typeInstance->GetIFaceVMethodSize();
  4446. if (typeInstance->mHotTypeData != NULL)
  4447. {
  4448. if (typeInstance->mHotTypeData->mOrigInterfaceMethodsLength != -1)
  4449. ifaceMethodLen = typeInstance->mHotTypeData->mOrigInterfaceMethodsLength;
  4450. }
  4451. numElements += ifaceMethodLen;
  4452. }
  4453. if (outNumElements != NULL)
  4454. *outNumElements = numElements;
  4455. }
  4456. StringT<128> classVDataName;
  4457. String memberName = "sBfClassVData";
  4458. if ((typeInstance->mHotTypeData != NULL) && ((typeInstance->mHotTypeData->mHadDataChange) || (typeInstance->mHotTypeData->mPendingDataChange)))
  4459. {
  4460. auto curVersion = typeInstance->mHotTypeData->GetLatestVersion();
  4461. memberName += "_";
  4462. memberName += BfTypeUtils::HashEncode64(curVersion->mDataHash.mLow);
  4463. memberName += BfTypeUtils::HashEncode64(curVersion->mDataHash.mHigh);
  4464. }
  4465. BfMangler::MangleStaticFieldName(classVDataName, mCompiler->GetMangleKind(), typeInstance, memberName, classVDataType);
  4466. if (outMangledName != NULL)
  4467. *outMangledName = classVDataName;
  4468. /*if (itr != mClassVDataRefs.end())
  4469. {
  4470. globalVariable = itr->second;
  4471. }*/
  4472. BfIRValue globalVariable;
  4473. if (globalVariablePtr != NULL)
  4474. {
  4475. globalVariable = *globalVariablePtr;
  4476. }
  4477. else
  4478. {
  4479. BfLogSysM("Creating VData %s\n", classVDataName.c_str());
  4480. auto arrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr), numElements);
  4481. globalVariable = mBfIRBuilder->CreateGlobalVariable(
  4482. arrayType,
  4483. true,
  4484. BfIRLinkageType_External,
  4485. BfIRValue(),
  4486. classVDataName);
  4487. mClassVDataRefs[typeInstance] = globalVariable;
  4488. }
  4489. return globalVariable;
  4490. }
  4491. BfIRValue BfModule::GetClassVDataPtr(BfTypeInstance* typeInstance)
  4492. {
  4493. auto classVDataType = ResolveTypeDef(mCompiler->mClassVDataTypeDef);
  4494. if (mIsComptimeModule)
  4495. return mBfIRBuilder->Comptime_GetBfType(typeInstance->mTypeId, mBfIRBuilder->MapType(CreatePointerType(classVDataType)));
  4496. return mBfIRBuilder->CreateBitCast(CreateClassVDataGlobal(typeInstance), mBfIRBuilder->MapType(CreatePointerType(classVDataType)));
  4497. }
  4498. BfIRValue BfModule::CreateClassVDataExtGlobal(BfTypeInstance* declTypeInst, BfTypeInstance* implTypeInst, int startVirtIdx)
  4499. {
  4500. if (mBfIRBuilder->mIgnoreWrites)
  4501. return mBfIRBuilder->GetFakeVal();
  4502. int numElements = declTypeInst->GetSelfVTableSize() - declTypeInst->GetOrigSelfVTableSize();
  4503. BF_ASSERT(numElements >= 0);
  4504. if (numElements <= 0)
  4505. return BfIRValue();
  4506. BF_ASSERT(implTypeInst->mVirtualMethodTable[startVirtIdx].mDeclaringMethod.mMethodNum == -1);
  4507. BF_ASSERT(implTypeInst->mVirtualMethodTable[startVirtIdx].mDeclaringMethod.mTypeInstance == declTypeInst);
  4508. if (declTypeInst->mInheritDepth == implTypeInst->mInheritDepth)
  4509. BF_ASSERT(declTypeInst == implTypeInst);
  4510. else
  4511. BF_ASSERT(implTypeInst->mInheritDepth > declTypeInst->mInheritDepth);
  4512. if (declTypeInst != implTypeInst)
  4513. {
  4514. BfTypeInstance* highestImpl = declTypeInst;
  4515. for (int virtIdx = startVirtIdx + 1; virtIdx < (int)declTypeInst->mVirtualMethodTable.size(); virtIdx++)
  4516. {
  4517. if (implTypeInst->mVirtualMethodTable[virtIdx].mDeclaringMethod.mMethodNum == -1)
  4518. break; // Start of an ext entry for another type
  4519. auto checkImplTypeInst = implTypeInst->mVirtualMethodTable[virtIdx].mImplementingMethod.mTypeInstance;
  4520. if ((checkImplTypeInst != NULL) && (checkImplTypeInst->mInheritDepth > highestImpl->mInheritDepth))
  4521. highestImpl = checkImplTypeInst;
  4522. }
  4523. if (highestImpl != implTypeInst)
  4524. return CreateClassVDataExtGlobal(declTypeInst, highestImpl, startVirtIdx);
  4525. }
  4526. BfVDataExtEntry mapEntry;
  4527. mapEntry.mDeclTypeInst = declTypeInst;
  4528. mapEntry.mImplTypeInst = implTypeInst;
  4529. BfIRValue* irValuePtr = NULL;
  4530. if (mClassVDataExtRefs.TryGetValue(mapEntry, &irValuePtr))
  4531. return *irValuePtr;
  4532. PopulateType(declTypeInst, BfPopulateType_DataAndMethods);
  4533. PopulateType(implTypeInst, BfPopulateType_DataAndMethods);
  4534. StringT<128> classVDataName;
  4535. BfMangler::MangleStaticFieldName(classVDataName, mCompiler->GetMangleKind(), implTypeInst, "bf_hs_replace_VDataExt");
  4536. if (declTypeInst != implTypeInst)
  4537. {
  4538. classVDataName += StrFormat("_%d", implTypeInst->mInheritDepth - declTypeInst->mInheritDepth);
  4539. }
  4540. auto voidPtrType = GetPrimitiveType(BfTypeCode_NullPtr);
  4541. auto voidPtrIRType = mBfIRBuilder->MapType(voidPtrType);
  4542. SizedArray<BfIRValue, 32> vData;
  4543. auto voidPtrNull = GetDefaultValue(voidPtrType);
  4544. for (int virtIdx = startVirtIdx + declTypeInst->GetOrigSelfVTableSize(); virtIdx < (int)declTypeInst->mVirtualMethodTable.size(); virtIdx++)
  4545. {
  4546. if (implTypeInst->mVirtualMethodTable[virtIdx].mDeclaringMethod.mMethodNum == -1)
  4547. break; // Start of an ext entry for another type
  4548. BfIRValue vValue;
  4549. auto& entry = implTypeInst->mVirtualMethodTable[virtIdx];
  4550. BfMethodInstance* declaringMethodInstance = (BfMethodInstance*)entry.mDeclaringMethod;
  4551. if ((declaringMethodInstance != NULL) && (declaringMethodInstance->mMethodInstanceGroup->IsImplemented()) && (declaringMethodInstance->mIsReified))
  4552. {
  4553. BF_ASSERT(entry.mImplementingMethod.mTypeInstance->mMethodInstanceGroups[entry.mImplementingMethod.mMethodNum].IsImplemented());
  4554. BF_ASSERT(entry.mImplementingMethod.mTypeInstance->mMethodInstanceGroups[entry.mImplementingMethod.mMethodNum].mDefault->mIsReified);
  4555. BfMethodInstance* methodInstance = (BfMethodInstance*)entry.mImplementingMethod;
  4556. if ((methodInstance != NULL) && (!methodInstance->mMethodDef->mIsAbstract))
  4557. {
  4558. BF_ASSERT(implTypeInst->IsTypeMemberAccessible(methodInstance->mMethodDef->mDeclaringType, mProject));
  4559. auto moduleMethodInst = GetMethodInstanceAtIdx(methodInstance->mMethodInstanceGroup->mOwner, methodInstance->mMethodInstanceGroup->mMethodIdx, NULL, BfGetMethodInstanceFlag_NoInline);
  4560. auto funcPtr = mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, voidPtrIRType);
  4561. vValue = funcPtr;
  4562. }
  4563. }
  4564. if (!vValue)
  4565. vValue = voidPtrNull;
  4566. vData.Add(vValue);
  4567. }
  4568. BF_ASSERT((int)vData.size() == numElements);
  4569. BfLogSysM("Creating VDataExt %s\n", classVDataName.c_str());
  4570. auto arrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr), numElements);
  4571. auto globalVariable = mBfIRBuilder->CreateGlobalVariable(arrayType, true,
  4572. BfIRLinkageType_External, BfIRValue(), classVDataName);
  4573. BfIRType extVTableType = mBfIRBuilder->GetSizedArrayType(voidPtrIRType, (int)vData.size());
  4574. BfIRValue extVTableConst = mBfIRBuilder->CreateConstAgg_Value(extVTableType, vData);
  4575. mBfIRBuilder->GlobalVar_SetInitializer(globalVariable, extVTableConst);
  4576. mClassVDataExtRefs[mapEntry] = globalVariable;
  4577. return globalVariable;
  4578. }
  4579. BfIRValue BfModule::CreateTypeDataRef(BfType* type)
  4580. {
  4581. if (mBfIRBuilder->mIgnoreWrites)
  4582. {
  4583. return mBfIRBuilder->CreateTypeOf(type);
  4584. }
  4585. if (mIsComptimeModule)
  4586. {
  4587. auto typeTypeDef = ResolveTypeDef(mCompiler->mTypeTypeDef);
  4588. auto typeTypeInst = typeTypeDef->ToTypeInstance();
  4589. return mBfIRBuilder->Comptime_GetReflectType(type->mTypeId, mBfIRBuilder->MapType(typeTypeInst));
  4590. }
  4591. PopulateType(type);
  4592. BfIRValue globalVariable;
  4593. BfIRValue* globalVariablePtr = NULL;
  4594. if (mTypeDataRefs.TryGetValue(type, &globalVariablePtr))
  4595. {
  4596. if (*globalVariablePtr)
  4597. return mBfIRBuilder->CreateTypeOf(type, *globalVariablePtr);
  4598. }
  4599. auto typeTypeDef = ResolveTypeDef(mCompiler->mTypeTypeDef);
  4600. auto typeTypeInst = typeTypeDef->ToTypeInstance();
  4601. auto typeInstance = type->ToTypeInstance();
  4602. StringT<128> typeDataName;
  4603. if (typeInstance != NULL)
  4604. {
  4605. BfMangler::MangleStaticFieldName(typeDataName, mCompiler->GetMangleKind(), typeInstance, "sBfTypeData");
  4606. }
  4607. else
  4608. {
  4609. typeDataName += "sBfTypeData.";
  4610. BfMangler::Mangle(typeDataName, mCompiler->GetMangleKind(), type, this);
  4611. }
  4612. BfLogSysM("Creating TypeData %s\n", typeDataName.c_str());
  4613. globalVariable = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapTypeInst(typeTypeInst, BfIRPopulateType_Full), true, BfIRLinkageType_External, BfIRValue(), typeDataName);
  4614. mBfIRBuilder->SetReflectTypeData(mBfIRBuilder->MapType(type), globalVariable);
  4615. mTypeDataRefs[type] = globalVariable;
  4616. return mBfIRBuilder->CreateTypeOf(type, globalVariable);
  4617. }
  4618. void BfModule::EncodeAttributeData(BfTypeInstance* typeInstance, BfType* argType, BfIRValue arg, SizedArrayImpl<uint8>& data, Dictionary<int, int>& usedStringIdMap)
  4619. {
  4620. #define PUSH_INT8(val) data.push_back((uint8)val)
  4621. #define PUSH_INT16(val) { data.push_back(val & 0xFF); data.push_back((val >> 8) & 0xFF); }
  4622. #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); }
  4623. #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); \
  4624. data.push_back((val >> 32) & 0xFF); data.push_back((val >> 40) & 0xFF); data.push_back((val >> 48) & 0xFF); data.push_back((val >> 56) & 0xFF); }
  4625. auto constant = typeInstance->mConstHolder->GetConstant(arg);
  4626. bool handled = false;
  4627. if (constant == NULL)
  4628. {
  4629. Fail(StrFormat("Unhandled attribute constant data in '%s'", TypeToString(typeInstance).c_str()));
  4630. return;
  4631. }
  4632. if (argType->IsObject())
  4633. {
  4634. if (argType->IsInstanceOf(mCompiler->mStringTypeDef))
  4635. {
  4636. int stringId = constant->mInt32;
  4637. int* orderedIdPtr;
  4638. if (usedStringIdMap.TryAdd(stringId, NULL, &orderedIdPtr))
  4639. {
  4640. *orderedIdPtr = (int)usedStringIdMap.size() - 1;
  4641. }
  4642. GetStringObjectValue(stringId, true, true);
  4643. PUSH_INT8(0xFF); // String
  4644. PUSH_INT32(*orderedIdPtr);
  4645. return;
  4646. }
  4647. }
  4648. if (argType->IsPointer())
  4649. {
  4650. if (argType->GetUnderlyingType() == GetPrimitiveType(BfTypeCode_Char8))
  4651. {
  4652. if (constant->mTypeCode == BfTypeCode_StringId)
  4653. {
  4654. int stringId = constant->mInt32;
  4655. int* orderedIdPtr;
  4656. if (usedStringIdMap.TryAdd(stringId, NULL, &orderedIdPtr))
  4657. {
  4658. *orderedIdPtr = (int)usedStringIdMap.size() - 1;
  4659. }
  4660. GetStringObjectValue(stringId, true, true);
  4661. PUSH_INT8(0xFF); // String
  4662. PUSH_INT32(*orderedIdPtr);
  4663. return;
  4664. }
  4665. }
  4666. }
  4667. PUSH_INT8(constant->mTypeCode);
  4668. if ((constant->mTypeCode == BfTypeCode_Int64) ||
  4669. (constant->mTypeCode == BfTypeCode_UInt64) ||
  4670. (constant->mTypeCode == BfTypeCode_Double))
  4671. {
  4672. PUSH_INT64(constant->mInt64);
  4673. }
  4674. else if ((constant->mTypeCode == BfTypeCode_Int32) ||
  4675. (constant->mTypeCode == BfTypeCode_UInt32) ||
  4676. (constant->mTypeCode == BfTypeCode_Char32))
  4677. {
  4678. PUSH_INT32(constant->mInt32);
  4679. }
  4680. else if (constant->mTypeCode == BfTypeCode_Float)
  4681. {
  4682. float val = (float)constant->mDouble;
  4683. PUSH_INT32(*(int*)&val);
  4684. }
  4685. else if ((constant->mTypeCode == BfTypeCode_Int16) ||
  4686. (constant->mTypeCode == BfTypeCode_UInt16) ||
  4687. (constant->mTypeCode == BfTypeCode_Char16))
  4688. {
  4689. PUSH_INT16(constant->mInt16);
  4690. }
  4691. else if ((constant->mTypeCode == BfTypeCode_Int8) ||
  4692. (constant->mTypeCode == BfTypeCode_UInt8) ||
  4693. (constant->mTypeCode == BfTypeCode_Boolean) ||
  4694. (constant->mTypeCode == BfTypeCode_Char8))
  4695. {
  4696. PUSH_INT8(constant->mInt8);
  4697. }
  4698. else if (constant->mConstType == BfConstType_TypeOf)
  4699. {
  4700. auto typeOf = (BfTypeOf_Const*)constant;
  4701. PUSH_INT32(typeOf->mType->mTypeId);
  4702. }
  4703. else if (constant->mConstType == BfConstType_AggZero)
  4704. {
  4705. for (int i = 0; i < argType->mSize; i++)
  4706. data.Add(0);
  4707. }
  4708. // else if (constant->mConstType == BfConstType_Agg)
  4709. // {
  4710. // BF_ASSERT(argType->IsComposite());
  4711. // if (argType->IsSizedArray())
  4712. // {
  4713. // auto argSizedArrayType = (BfSizedArrayType*)argType;
  4714. // }
  4715. // else
  4716. // {
  4717. // auto argTypeInstance = argType->ToTypeInstance();
  4718. // }
  4719. // }
  4720. else
  4721. {
  4722. Fail(StrFormat("Unhandled attribute constant data in '%s'", TypeToString(typeInstance).c_str()));
  4723. }
  4724. }
  4725. BfIRValue BfModule::CreateFieldData(BfFieldInstance* fieldInstance, int customAttrIdx)
  4726. {
  4727. bool isComptime = mBfIRBuilder->mIgnoreWrites;
  4728. BfFieldDef* fieldDef = fieldInstance->GetFieldDef();
  4729. auto typeInstance = fieldInstance->mOwner;
  4730. BfType* intType = GetPrimitiveType(BfTypeCode_Int32);
  4731. BfType* intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  4732. BfType* shortType = GetPrimitiveType(BfTypeCode_Int16);
  4733. BfType* typeIdType = intType;
  4734. BfTypeInstance* reflectFieldDataType = ResolveTypeDef(mCompiler->mReflectFieldDataDef)->ToTypeInstance();
  4735. BfIRValue emptyValueType = mBfIRBuilder->mIgnoreWrites ?
  4736. mBfIRBuilder->CreateConstAgg(mBfIRBuilder->MapTypeInst(reflectFieldDataType->mBaseType), SizedArray<BfIRValue, 1>()) :
  4737. mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectFieldDataType->mBaseType), SizedArray<BfIRValue, 1>());
  4738. BfIRValue fieldNameConst = GetStringObjectValue(fieldDef->mName, !mIsComptimeModule);
  4739. bool is32Bit = mCompiler->mSystem->mPtrSize == 4;
  4740. int typeId = 0;
  4741. auto fieldType = fieldInstance->GetResolvedType();
  4742. if (fieldType->IsGenericParam())
  4743. {
  4744. //TODO:
  4745. }
  4746. else
  4747. typeId = fieldType->mTypeId;
  4748. BfFieldFlags fieldFlags = (BfFieldFlags)0;
  4749. if (fieldDef->mProtection == BfProtection_Protected)
  4750. fieldFlags = (BfFieldFlags)(fieldFlags | BfFieldFlags_Protected);
  4751. if (fieldDef->mProtection == BfProtection_Public)
  4752. fieldFlags = (BfFieldFlags)(fieldFlags | BfFieldFlags_Public);
  4753. if (fieldDef->mIsStatic)
  4754. fieldFlags = (BfFieldFlags)(fieldFlags | BfFieldFlags_Static);
  4755. if (fieldDef->mIsConst)
  4756. fieldFlags = (BfFieldFlags)(fieldFlags | BfFieldFlags_Const);
  4757. if (fieldDef->IsEnumCaseEntry())
  4758. fieldFlags = (BfFieldFlags)(fieldFlags | BfFieldFlags_EnumCase);
  4759. BfIRValue constValue;
  4760. BfIRValue constValue2;
  4761. if (fieldInstance->GetFieldDef()->mIsConst)
  4762. {
  4763. if (fieldInstance->mConstIdx != -1)
  4764. {
  4765. auto constant = typeInstance->mConstHolder->GetConstantById(fieldInstance->mConstIdx);
  4766. uint64 val = constant->mUInt64;
  4767. if (constant->mTypeCode == BfTypeCode_Float)
  4768. {
  4769. float f = (float)*(double*)&val;
  4770. val = *(uint32*)&f;
  4771. }
  4772. constValue = mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, val);
  4773. if (is32Bit)
  4774. constValue2 = mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, val >> 32);
  4775. }
  4776. }
  4777. else if (fieldInstance->GetFieldDef()->mIsStatic)
  4778. {
  4779. BfTypedValue refVal;
  4780. if (!mIsComptimeModule) // This can create circular reference issues for a `Self` static
  4781. refVal = ReferenceStaticField(fieldInstance);
  4782. if (refVal.mValue.IsConst())
  4783. {
  4784. auto constant = mBfIRBuilder->GetConstant(refVal.mValue);
  4785. if (constant->mConstType == BfConstType_GlobalVar)
  4786. {
  4787. auto globalVar = (BfGlobalVar*)constant;
  4788. if (globalVar->mName[0] == '#')
  4789. refVal = BfTypedValue();
  4790. }
  4791. }
  4792. if ((refVal.IsAddr()) && (!isComptime))
  4793. constValue = mBfIRBuilder->CreatePtrToInt(refVal.mValue, BfTypeCode_IntPtr);
  4794. }
  4795. if (!constValue)
  4796. constValue = mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, fieldInstance->mDataOffset);
  4797. BfIRValue result;
  4798. if (is32Bit)
  4799. {
  4800. if (!constValue2)
  4801. constValue2 = mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 0);
  4802. SizedArray<BfIRValue, 8> fieldVals =
  4803. {
  4804. emptyValueType,
  4805. fieldNameConst, // mName
  4806. GetConstValue(typeId, typeIdType), // mFieldTypeId
  4807. constValue, // mData
  4808. constValue2, // mDataHi
  4809. GetConstValue(fieldFlags, shortType), // mFlags
  4810. GetConstValue(customAttrIdx, intType), // mCustomAttributesIdx
  4811. };
  4812. FixConstValueParams(reflectFieldDataType, fieldVals, isComptime);
  4813. result = isComptime ?
  4814. mBfIRBuilder->CreateConstAgg(mBfIRBuilder->MapTypeInst(reflectFieldDataType, BfIRPopulateType_Full), fieldVals) :
  4815. mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectFieldDataType, BfIRPopulateType_Full), fieldVals);
  4816. }
  4817. else
  4818. {
  4819. SizedArray<BfIRValue, 8> fieldVals =
  4820. {
  4821. emptyValueType,
  4822. fieldNameConst, // mName
  4823. GetConstValue(typeId, typeIdType), // mFieldTypeId
  4824. constValue, // mData
  4825. GetConstValue(fieldFlags, shortType), // mFlags
  4826. GetConstValue(customAttrIdx, intType), // mCustomAttributesIdx
  4827. };
  4828. FixConstValueParams(reflectFieldDataType, fieldVals, isComptime);
  4829. result = isComptime ?
  4830. mBfIRBuilder->CreateConstAgg(mBfIRBuilder->MapTypeInst(reflectFieldDataType, BfIRPopulateType_Full), fieldVals) :
  4831. mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectFieldDataType, BfIRPopulateType_Full), fieldVals);
  4832. }
  4833. return result;
  4834. }
  4835. BfIRValue BfModule::CreateTypeData(BfType* type, Dictionary<int, int>& usedStringIdMap, bool forceReflectFields, bool needsTypeData, bool needsTypeNames, bool needsVData)
  4836. {
  4837. if ((IsHotCompile()) && (!type->mDirty))
  4838. return BfIRValue();
  4839. BfIRValue* irValuePtr = NULL;
  4840. if (mTypeDataRefs.TryGetValue(type, &irValuePtr))
  4841. {
  4842. return *irValuePtr;
  4843. }
  4844. BfTypeInstance* typeInstance = type->ToTypeInstance();
  4845. BfType* typeInstanceType = ResolveTypeDef(mCompiler->mReflectTypeInstanceTypeDef);
  4846. mBfIRBuilder->PopulateType(typeInstanceType, BfIRPopulateType_Full_ForceDefinition);
  4847. if (typeInstanceType == NULL)
  4848. {
  4849. AssertErrorState();
  4850. return BfIRValue();
  4851. }
  4852. BfIRValue typeTypeData;
  4853. int typeFlags = 0;
  4854. if (needsTypeData)
  4855. {
  4856. BfTypeInstance* typeInstanceTypeInstance = typeInstanceType->ToTypeInstance();
  4857. BfTypeInstance* typeDataSource = NULL;
  4858. if (typeInstance != NULL)
  4859. {
  4860. if (typeInstance->IsUnspecializedType())
  4861. {
  4862. typeDataSource = ResolveTypeDef(mCompiler->mReflectUnspecializedGenericType)->ToTypeInstance();
  4863. typeFlags |= BfTypeFlags_UnspecializedGeneric;
  4864. }
  4865. else if (typeInstance->IsArray())
  4866. {
  4867. typeDataSource = ResolveTypeDef(mCompiler->mReflectArrayType)->ToTypeInstance();
  4868. typeFlags |= BfTypeFlags_Array;
  4869. }
  4870. else if (typeInstance->IsGenericTypeInstance())
  4871. {
  4872. typeDataSource = ResolveTypeDef(mCompiler->mReflectSpecializedGenericType)->ToTypeInstance();
  4873. typeFlags |= BfTypeFlags_SpecializedGeneric;
  4874. }
  4875. else
  4876. typeDataSource = typeInstanceTypeInstance;
  4877. }
  4878. else if (type->IsPointer())
  4879. typeDataSource = ResolveTypeDef(mCompiler->mReflectPointerType)->ToTypeInstance();
  4880. else if (type->IsRef())
  4881. typeDataSource = ResolveTypeDef(mCompiler->mReflectRefType)->ToTypeInstance();
  4882. else if (type->IsSizedArray())
  4883. typeDataSource = ResolveTypeDef(mCompiler->mReflectSizedArrayType)->ToTypeInstance();
  4884. else if (type->IsConstExprValue())
  4885. typeDataSource = ResolveTypeDef(mCompiler->mReflectConstExprType)->ToTypeInstance();
  4886. else if (type->IsGenericParam())
  4887. {
  4888. typeFlags |= BfTypeFlags_GenericParam;
  4889. typeDataSource = ResolveTypeDef(mCompiler->mReflectGenericParamType)->ToTypeInstance();
  4890. }
  4891. else
  4892. typeDataSource = mContext->mBfTypeType;
  4893. if ((!mTypeDataRefs.ContainsKey(typeDataSource)) && (typeDataSource != type))
  4894. {
  4895. CreateTypeData(typeDataSource, usedStringIdMap, false, true, needsTypeNames, true);
  4896. }
  4897. typeTypeData = CreateClassVDataGlobal(typeDataSource);
  4898. }
  4899. else
  4900. typeTypeData = CreateClassVDataGlobal(typeInstanceType->ToTypeInstance());
  4901. BfType* longType = GetPrimitiveType(BfTypeCode_Int64);
  4902. BfType* intType = GetPrimitiveType(BfTypeCode_Int32);
  4903. BfType* intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  4904. BfType* shortType = GetPrimitiveType(BfTypeCode_Int16);
  4905. BfType* byteType = GetPrimitiveType(BfTypeCode_Int8);
  4906. BfType* typeIdType = intType;
  4907. auto voidPtrType = GetPrimitiveType(BfTypeCode_NullPtr);
  4908. auto voidPtrIRType = mBfIRBuilder->MapType(voidPtrType);
  4909. auto voidPtrPtrIRType = mBfIRBuilder->GetPointerTo(voidPtrIRType);
  4910. auto voidPtrNull = GetDefaultValue(voidPtrType);
  4911. SizedArray<BfIRValue, 4> typeValueParams;
  4912. GetConstClassValueParam(typeTypeData, typeValueParams);
  4913. FixConstValueParams(mContext->mBfObjectType, typeValueParams);
  4914. BfIRValue objectData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(mContext->mBfObjectType, BfIRPopulateType_Full), typeValueParams);
  4915. StringT<128> typeDataName;
  4916. if ((typeInstance != NULL) && (!typeInstance->IsTypeAlias()))
  4917. {
  4918. BfMangler::MangleStaticFieldName(typeDataName, mCompiler->GetMangleKind(), typeInstance, "sBfTypeData");
  4919. if (typeInstance->mTypeDef->IsGlobalsContainer())
  4920. typeDataName += "`G`" + typeInstance->mTypeDef->mProject->mName;
  4921. }
  4922. else
  4923. {
  4924. typeDataName += "sBfTypeData.";
  4925. BfMangler::Mangle(typeDataName, mCompiler->GetMangleKind(), type, mContext->mScratchModule);
  4926. }
  4927. int typeCode = BfTypeCode_None;
  4928. if (typeInstance != NULL)
  4929. {
  4930. BF_ASSERT((type->mDefineState >= BfTypeDefineState_DefinedAndMethodsSlotted) || mIsComptimeModule);
  4931. typeCode = typeInstance->mTypeDef->mTypeCode;
  4932. }
  4933. else if (type->IsPrimitiveType())
  4934. {
  4935. BfPrimitiveType* primType = (BfPrimitiveType*)type;
  4936. typeCode = primType->mTypeDef->mTypeCode;
  4937. }
  4938. else if (type->IsPointer())
  4939. {
  4940. typeCode = BfTypeCode_Pointer;
  4941. typeFlags |= BfTypeFlags_Pointer;
  4942. }
  4943. else if (type->IsRef())
  4944. {
  4945. typeCode = BfTypeCode_Pointer;
  4946. typeFlags |= BfTypeFlags_Pointer;
  4947. }
  4948. if (type->IsObject())
  4949. {
  4950. typeFlags |= BfTypeFlags_Object;
  4951. if (typeInstance->mDefineState >= BfTypeDefineState_DefinedAndMethodsSlotted)
  4952. {
  4953. BfMethodInstance* methodInstance = typeInstance->mVirtualMethodTable[mCompiler->GetVTableMethodOffset() + 0].mImplementingMethod;
  4954. if (methodInstance->GetOwner() != mContext->mBfObjectType)
  4955. typeFlags |= BfTypeFlags_HasDestructor;
  4956. }
  4957. }
  4958. if (type->IsStruct())
  4959. typeFlags |= BfTypeFlags_Struct;
  4960. if (type->IsInterface())
  4961. typeFlags |= BfTypeFlags_Interface;
  4962. if (type->IsBoxed())
  4963. {
  4964. typeFlags |= BfTypeFlags_Boxed;
  4965. if (((BfBoxedType*)type)->IsBoxedStructPtr())
  4966. typeFlags |= BfTypeFlags_Pointer;
  4967. }
  4968. if (type->IsPrimitiveType())
  4969. typeFlags |= BfTypeFlags_Primitive;
  4970. if (type->IsTypedPrimitive())
  4971. typeFlags |= BfTypeFlags_TypedPrimitive;
  4972. if (type->IsTuple())
  4973. typeFlags |= BfTypeFlags_Tuple;
  4974. if (type->IsNullable())
  4975. typeFlags |= BfTypeFlags_Nullable;
  4976. if (type->IsSizedArray())
  4977. typeFlags |= BfTypeFlags_SizedArray;
  4978. if (type->IsConstExprValue())
  4979. typeFlags |= BfTypeFlags_ConstExpr;
  4980. if (type->IsSplattable())
  4981. typeFlags |= BfTypeFlags_Splattable;
  4982. if (type->IsUnion())
  4983. typeFlags |= BfTypeFlags_Union;
  4984. if (type->IsDelegate())
  4985. typeFlags |= BfTypeFlags_Delegate;
  4986. if (type->IsFunction())
  4987. typeFlags |= BfTypeFlags_Function;
  4988. if ((type->mDefineState != BfTypeDefineState_CETypeInit) && (type->WantsGCMarking()))
  4989. typeFlags |= BfTypeFlags_WantsMarking;
  4990. int virtSlotIdx = -1;
  4991. if ((typeInstance != NULL) && (typeInstance->mSlotNum >= 0))
  4992. virtSlotIdx = typeInstance->mSlotNum + 1 + mCompiler->GetDynCastVDataCount();
  4993. int memberDataOffset = 0;
  4994. if (type->IsInterface())
  4995. memberDataOffset = virtSlotIdx * mSystem->mPtrSize;
  4996. else if (typeInstance != NULL)
  4997. {
  4998. for (auto& fieldInstance : typeInstance->mFieldInstances)
  4999. {
  5000. if (fieldInstance.mDataOffset != -1)
  5001. {
  5002. memberDataOffset = fieldInstance.mDataOffset;
  5003. break;
  5004. }
  5005. }
  5006. }
  5007. int boxedTypeId = 0;
  5008. if ((type->IsValueType()) || (type->IsWrappableType()))
  5009. {
  5010. auto boxedType = CreateBoxedType(type, false);
  5011. if ((boxedType != NULL) && (boxedType->mIsReified))
  5012. boxedTypeId = boxedType->mTypeId;
  5013. }
  5014. int stackCount = 0;
  5015. if ((typeInstance != NULL) && (typeInstance->mTypeOptionsIdx != -1))
  5016. {
  5017. auto typeOptions = mSystem->GetTypeOptions(typeInstance->mTypeOptionsIdx);
  5018. if (typeOptions->mAllocStackTraceDepth != -1)
  5019. stackCount = BF_MIN(0xFF, BF_MAX(0x01, typeOptions->mAllocStackTraceDepth));
  5020. }
  5021. SizedArray<BfIRValue, 9> typeDataParams =
  5022. {
  5023. objectData,
  5024. GetConstValue(type->mSize, intType), // mSize
  5025. GetConstValue(type->mTypeId, typeIdType), // mTypeId
  5026. GetConstValue(boxedTypeId, typeIdType), // mBoxedType
  5027. GetConstValue(typeFlags, intType), // mTypeFlags
  5028. GetConstValue(memberDataOffset, intType), // mMemberDataOffset
  5029. GetConstValue(typeCode, byteType), // mTypeCode
  5030. GetConstValue(type->mAlign, byteType), // mAlign
  5031. GetConstValue(stackCount, byteType), // mAllocStackCountOverride
  5032. };
  5033. FixConstValueParams(mContext->mBfTypeType, typeDataParams);
  5034. auto typeData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(mContext->mBfTypeType, BfIRPopulateType_Full), typeDataParams);
  5035. if (typeInstance == NULL)
  5036. {
  5037. BfIRValue typeDataVar;
  5038. if (needsTypeData)
  5039. {
  5040. if (type->IsPointer())
  5041. {
  5042. auto pointerType = (BfPointerType*)type;
  5043. SizedArray<BfIRValue, 3> pointerTypeDataParms =
  5044. {
  5045. typeData,
  5046. GetConstValue(pointerType->mElementType->mTypeId, typeIdType),
  5047. };
  5048. auto reflectPointerType = ResolveTypeDef(mCompiler->mReflectPointerType)->ToTypeInstance();
  5049. FixConstValueParams(reflectPointerType, pointerTypeDataParms);
  5050. auto pointerTypeData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectPointerType, BfIRPopulateType_Full), pointerTypeDataParms);
  5051. typeDataVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapTypeInst(reflectPointerType), true,
  5052. BfIRLinkageType_External, pointerTypeData, typeDataName);
  5053. mBfIRBuilder->GlobalVar_SetAlignment(typeDataVar, mSystem->mPtrSize);
  5054. typeDataVar = mBfIRBuilder->CreateBitCast(typeDataVar, mBfIRBuilder->MapType(mContext->mBfTypeType));
  5055. }
  5056. else if (type->IsRef())
  5057. {
  5058. auto refType = (BfRefType*)type;
  5059. SizedArray<BfIRValue, 3> refTypeDataParms =
  5060. {
  5061. typeData,
  5062. GetConstValue(refType->mElementType->mTypeId, typeIdType),
  5063. GetConstValue((int8)refType->mRefKind, byteType),
  5064. };
  5065. auto reflectRefType = ResolveTypeDef(mCompiler->mReflectRefType)->ToTypeInstance();
  5066. FixConstValueParams(reflectRefType, refTypeDataParms);
  5067. auto refTypeData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectRefType, BfIRPopulateType_Full), refTypeDataParms);
  5068. typeDataVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapTypeInst(reflectRefType), true,
  5069. BfIRLinkageType_External, refTypeData, typeDataName);
  5070. mBfIRBuilder->GlobalVar_SetAlignment(typeDataVar, mSystem->mPtrSize);
  5071. typeDataVar = mBfIRBuilder->CreateBitCast(typeDataVar, mBfIRBuilder->MapType(mContext->mBfTypeType));
  5072. }
  5073. else if (type->IsSizedArray())
  5074. {
  5075. auto sizedArrayType = (BfSizedArrayType*)type;
  5076. SizedArray<BfIRValue, 3> sizedArrayTypeDataParms =
  5077. {
  5078. typeData,
  5079. GetConstValue(sizedArrayType->mElementType->mTypeId, typeIdType),
  5080. GetConstValue(sizedArrayType->mElementCount, intType)
  5081. };
  5082. auto reflectSizedArrayType = ResolveTypeDef(mCompiler->mReflectSizedArrayType)->ToTypeInstance();
  5083. FixConstValueParams(reflectSizedArrayType, sizedArrayTypeDataParms);
  5084. auto sizedArrayTypeData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectSizedArrayType, BfIRPopulateType_Full), sizedArrayTypeDataParms);
  5085. typeDataVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapTypeInst(reflectSizedArrayType), true,
  5086. BfIRLinkageType_External, sizedArrayTypeData, typeDataName);
  5087. mBfIRBuilder->GlobalVar_SetAlignment(typeDataVar, mSystem->mPtrSize);
  5088. typeDataVar = mBfIRBuilder->CreateBitCast(typeDataVar, mBfIRBuilder->MapType(mContext->mBfTypeType));
  5089. }
  5090. else if (type->IsConstExprValue())
  5091. {
  5092. auto constExprType = (BfConstExprValueType*)type;
  5093. SizedArray<BfIRValue, 3> constExprTypeDataParms =
  5094. {
  5095. typeData,
  5096. GetConstValue(constExprType->mType->mTypeId, typeIdType),
  5097. GetConstValue(constExprType->mValue.mInt64, longType)
  5098. };
  5099. auto reflectConstExprType = ResolveTypeDef(mCompiler->mReflectConstExprType)->ToTypeInstance();
  5100. FixConstValueParams(reflectConstExprType, constExprTypeDataParms);
  5101. auto ConstExprTypeData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectConstExprType, BfIRPopulateType_Full), constExprTypeDataParms);
  5102. typeDataVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapTypeInst(reflectConstExprType), true,
  5103. BfIRLinkageType_External, ConstExprTypeData, typeDataName);
  5104. mBfIRBuilder->GlobalVar_SetAlignment(typeDataVar, mSystem->mPtrSize);
  5105. typeDataVar = mBfIRBuilder->CreateBitCast(typeDataVar, mBfIRBuilder->MapType(mContext->mBfTypeType));
  5106. }
  5107. else if (type->IsGenericParam())
  5108. {
  5109. auto genericParamType = (BfGenericParamType*)type;
  5110. SizedArray<BfIRValue, 3> genericParamTypeDataParms =
  5111. {
  5112. typeData
  5113. };
  5114. auto reflectGenericParamType = ResolveTypeDef(mCompiler->mReflectGenericParamType)->ToTypeInstance();
  5115. FixConstValueParams(reflectGenericParamType, genericParamTypeDataParms);
  5116. auto genericParamTypeData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectGenericParamType, BfIRPopulateType_Full), genericParamTypeDataParms);
  5117. typeDataVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapTypeInst(reflectGenericParamType), true,
  5118. BfIRLinkageType_External, genericParamTypeData, typeDataName);
  5119. mBfIRBuilder->GlobalVar_SetAlignment(typeDataVar, mSystem->mPtrSize);
  5120. typeDataVar = mBfIRBuilder->CreateBitCast(typeDataVar, mBfIRBuilder->MapType(mContext->mBfTypeType));
  5121. }
  5122. else
  5123. {
  5124. typeDataVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapTypeInst(mContext->mBfTypeType), true,
  5125. BfIRLinkageType_External, typeData, typeDataName);
  5126. mBfIRBuilder->GlobalVar_SetAlignment(typeDataVar, mSystem->mPtrSize);
  5127. }
  5128. }
  5129. else
  5130. typeDataVar = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(mContext->mBfTypeType));
  5131. mTypeDataRefs[type] = typeDataVar;
  5132. return typeDataVar;
  5133. }
  5134. // Reserve position
  5135. mTypeDataRefs[typeInstance] = BfIRValue();
  5136. if ((typeInstance->IsReified()) && (!mIsComptimeModule))
  5137. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  5138. BfTypeDef* typeDef = typeInstance->mTypeDef;
  5139. StringT<128> mangledName;
  5140. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), typeInstance, typeInstance->mModule);
  5141. if (!mIsComptimeModule)
  5142. {
  5143. for (int methodIdx = 0; methodIdx < (int)typeDef->mMethods.size(); methodIdx++)
  5144. {
  5145. auto methodDef = typeDef->mMethods[methodIdx];
  5146. auto methodInstance = typeInstance->mMethodInstanceGroups[methodIdx].mDefault;
  5147. if (methodInstance == NULL)
  5148. continue;
  5149. if (typeInstance->IsUnspecializedType())
  5150. continue;
  5151. if (!typeInstance->IsTypeMemberAccessible(methodDef->mDeclaringType, mProject))
  5152. {
  5153. if (methodInstance->mChainType == BfMethodChainType_ChainMember)
  5154. {
  5155. BF_ASSERT(!methodInstance->GetOwner()->IsUnspecializedType());
  5156. // We need to create an empty thunk for this chained method
  5157. BfIRFunction func = CreateFunctionFrom(methodInstance, false, methodInstance->mAlwaysInline);
  5158. mBfIRBuilder->SetActiveFunction(func);
  5159. auto block = mBfIRBuilder->CreateBlock("entry", true);
  5160. mBfIRBuilder->SetInsertPoint(block);
  5161. mBfIRBuilder->CreateRetVoid();
  5162. mBfIRBuilder->SetActiveFunction(BfIRFunction());
  5163. }
  5164. }
  5165. }
  5166. }
  5167. SizedArray<BfIRValue, 32> vData;
  5168. BfIRValue classVDataVar;
  5169. String classVDataName;
  5170. if (typeInstance->mSlotNum >= 0)
  5171. {
  5172. // For interfaces we ONLY emit the slot num
  5173. StringT<128> slotVarName;
  5174. BfMangler::MangleStaticFieldName(slotVarName, mCompiler->GetMangleKind(), typeInstance, "sBfSlotOfs");
  5175. auto intType = GetPrimitiveType(BfTypeCode_Int32);
  5176. auto slotNumVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapType(intType), true, BfIRLinkageType_External,
  5177. GetConstValue32(virtSlotIdx), slotVarName);
  5178. }
  5179. else if ((typeInstance->IsObject()) && (!typeInstance->IsUnspecializedType()) && (needsVData))
  5180. {
  5181. int dynCastDataElems = 0;
  5182. int numElements = 1;
  5183. int vDataOfs = 1; // The number of intptrs before the iface slot map
  5184. numElements += mCompiler->mMaxInterfaceSlots;
  5185. if (!typeInstance->IsInterface())
  5186. {
  5187. dynCastDataElems = 1 + mCompiler->mMaxInterfaceSlots;
  5188. numElements += mCompiler->GetDynCastVDataCount();
  5189. numElements += typeInstance->mVirtualMethodTableSize;
  5190. }
  5191. int expectNumElements = 0;
  5192. if (!typeDef->mIsStatic)
  5193. {
  5194. classVDataVar = CreateClassVDataGlobal(typeInstance, &expectNumElements, &classVDataName);
  5195. }
  5196. vData.push_back(BfIRValue()); // Type*
  5197. SizedArray<BfIRValue, 1> extVTableData;
  5198. SizedArrayImpl<BfIRValue>* vFuncDataExt = &extVTableData;
  5199. if (!typeInstance->IsInterface())
  5200. {
  5201. Array<int32> dynCastData;
  5202. if (typeInstance->IsBoxed())
  5203. {
  5204. auto underlyingType = typeInstance->GetUnderlyingType()->ToTypeInstance();
  5205. dynCastData.Add(underlyingType->mInheritanceId);
  5206. }
  5207. else
  5208. dynCastData.Add(typeInstance->mInheritanceId);
  5209. for (int i = 0; i < mCompiler->mMaxInterfaceSlots; i++)
  5210. dynCastData.Add(0);
  5211. dynCastData.Add(0);
  5212. auto checkTypeInst = typeInstance;
  5213. while (checkTypeInst != NULL)
  5214. {
  5215. for (auto&& interfaceEntry : checkTypeInst->mInterfaces)
  5216. {
  5217. if (interfaceEntry.mInterfaceType->mSlotNum >= 0)
  5218. {
  5219. if (dynCastData[interfaceEntry.mInterfaceType->mSlotNum + 1] == 0)
  5220. dynCastData[interfaceEntry.mInterfaceType->mSlotNum + 1] = interfaceEntry.mInterfaceType->mTypeId;
  5221. }
  5222. }
  5223. checkTypeInst = checkTypeInst->GetImplBaseType();
  5224. }
  5225. if (mSystem->mPtrSize == 8)
  5226. {
  5227. int intPtrCount = (dynCastDataElems + 1) / 2;
  5228. vDataOfs += intPtrCount;
  5229. uint64* intPtrData = (uint64*)&dynCastData[0];
  5230. for (int i = 0; i < intPtrCount; i++)
  5231. {
  5232. uint64 val = intPtrData[i];
  5233. if (val == 0)
  5234. {
  5235. vData.push_back(voidPtrNull);
  5236. }
  5237. else
  5238. {
  5239. auto intPtrVal = mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, val);
  5240. vData.push_back(mBfIRBuilder->CreateBitCast(intPtrVal, voidPtrIRType));
  5241. }
  5242. }
  5243. }
  5244. else
  5245. {
  5246. int intPtrCount = dynCastDataElems;
  5247. vDataOfs += intPtrCount;
  5248. uint32* intPtrData = (uint32*)&dynCastData[0];
  5249. for (int i = 0; i < intPtrCount; i++)
  5250. {
  5251. uint32 val = intPtrData[i];
  5252. if (val == 0)
  5253. {
  5254. vData.push_back(voidPtrNull);
  5255. }
  5256. else
  5257. {
  5258. auto intPtrVal = mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, (int)val);
  5259. vData.push_back(mBfIRBuilder->CreateBitCast(intPtrVal, voidPtrIRType));
  5260. }
  5261. }
  5262. }
  5263. }
  5264. for (int iSlotIdx = 0; iSlotIdx < mCompiler->mMaxInterfaceSlots; iSlotIdx++)
  5265. vData.push_back(voidPtrNull);
  5266. struct _InterfaceMatchEntry
  5267. {
  5268. BfTypeInterfaceEntry* mEntry;
  5269. BfTypeInstance* mEntrySource;
  5270. Array<BfTypeInterfaceEntry*> mAmbiguousEntries;
  5271. };
  5272. int highestIFaceVirtIdx = 0;
  5273. Dictionary<BfTypeInstance*, _InterfaceMatchEntry> interfaceMap;
  5274. auto checkTypeInst = typeInstance;
  5275. bool forceInterfaceSet = false;
  5276. while (checkTypeInst != NULL)
  5277. {
  5278. for (auto&& interfaceEntry : checkTypeInst->mInterfaces)
  5279. {
  5280. highestIFaceVirtIdx = BF_MAX(highestIFaceVirtIdx, interfaceEntry.mStartVirtualIdx + interfaceEntry.mInterfaceType->mVirtualMethodTableSize);
  5281. if ((!mIsComptimeModule) && (!typeInstance->IsTypeMemberAccessible(interfaceEntry.mDeclaringType, mProject)))
  5282. continue;
  5283. _InterfaceMatchEntry* matchEntry = NULL;
  5284. if (interfaceMap.TryGetValue(interfaceEntry.mInterfaceType, &matchEntry))
  5285. {
  5286. BfTypeInstance* compareCheckTypeInst = checkTypeInst;
  5287. if (compareCheckTypeInst->IsBoxed())
  5288. compareCheckTypeInst = compareCheckTypeInst->GetUnderlyingType()->ToTypeInstance();
  5289. BfTypeInstance* compareEntrySource = matchEntry->mEntrySource;
  5290. if (compareEntrySource->IsBoxed())
  5291. compareEntrySource = compareEntrySource->GetUnderlyingType()->ToTypeInstance();
  5292. auto prevEntry = matchEntry->mEntry;
  5293. bool isBetter = TypeIsSubTypeOf(compareCheckTypeInst, compareEntrySource);
  5294. bool isWorse = TypeIsSubTypeOf(compareEntrySource, compareCheckTypeInst);
  5295. if ((!isBetter) && (!isWorse))
  5296. {
  5297. // Unboxed comparison to Object fix
  5298. if (compareCheckTypeInst == mContext->mBfObjectType)
  5299. isWorse = true;
  5300. else if (compareEntrySource == mContext->mBfObjectType)
  5301. isBetter = true;
  5302. }
  5303. if (forceInterfaceSet)
  5304. {
  5305. isBetter = true;
  5306. isWorse = false;
  5307. }
  5308. if (isBetter == isWorse)
  5309. CompareDeclTypes(interfaceEntry.mDeclaringType, prevEntry->mDeclaringType, isBetter, isWorse);
  5310. if (isBetter == isWorse)
  5311. {
  5312. if (matchEntry->mAmbiguousEntries.empty())
  5313. matchEntry->mAmbiguousEntries.push_back(prevEntry);
  5314. matchEntry->mAmbiguousEntries.push_back(&interfaceEntry);
  5315. continue;
  5316. }
  5317. else if (isBetter)
  5318. {
  5319. matchEntry->mEntry = &interfaceEntry;
  5320. matchEntry->mEntrySource = checkTypeInst;
  5321. matchEntry->mAmbiguousEntries.Clear();
  5322. }
  5323. else
  5324. continue;
  5325. }
  5326. else
  5327. {
  5328. _InterfaceMatchEntry matchEntry;
  5329. matchEntry.mEntry = &interfaceEntry;
  5330. matchEntry.mEntrySource = checkTypeInst;
  5331. interfaceMap[interfaceEntry.mInterfaceType] = matchEntry;
  5332. }
  5333. }
  5334. checkTypeInst = checkTypeInst->GetImplBaseType();
  5335. }
  5336. for (auto interfacePair : interfaceMap)
  5337. {
  5338. auto& interfaceMatchEntry = interfacePair.mValue;
  5339. if (!interfaceMatchEntry.mAmbiguousEntries.empty())
  5340. {
  5341. 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());
  5342. if (error != NULL)
  5343. {
  5344. for (auto ambiguiousEntry : interfaceMatchEntry.mAmbiguousEntries)
  5345. mCompiler->mPassInstance->MoreInfo("See other declaration", ambiguiousEntry->mDeclaringType->GetRefNode());
  5346. }
  5347. }
  5348. }
  5349. if ((!mIsComptimeModule) && (!typeInstance->IsInterface()) && (typeInstance->mVirtualMethodTableSize > 0) && (needsVData))
  5350. {
  5351. int startTabIdx = (int)vData.size();
  5352. SizedArray<BfTypeInstance*, 8> origVirtTypeStack;
  5353. BfTypeInstance* checkTypeInst = typeInstance;
  5354. while (checkTypeInst != NULL)
  5355. {
  5356. origVirtTypeStack.push_back(checkTypeInst);
  5357. checkTypeInst = checkTypeInst->GetImplBaseType();
  5358. }
  5359. Array<BfVirtualMethodEntry> origVTable;
  5360. int origVirtIdx = 0;
  5361. if (typeInstance->mTypeDef->mIsCombinedPartial)
  5362. {
  5363. HashSet<String> reslotNames;
  5364. for (int virtIdx = 0; virtIdx < (int)typeInstance->mVirtualMethodTable.size(); virtIdx++)
  5365. {
  5366. auto& entry = typeInstance->mVirtualMethodTable[virtIdx];
  5367. if (entry.mDeclaringMethod.mMethodNum == -1)
  5368. continue;
  5369. BfMethodInstance* methodInstance = (BfMethodInstance*)entry.mImplementingMethod;
  5370. if ((methodInstance == NULL) ||
  5371. ((!mIsComptimeModule) && (!typeInstance->IsTypeMemberAccessible(methodInstance->mMethodDef->mDeclaringType, mProject))))
  5372. {
  5373. if (origVTable.empty())
  5374. origVTable = typeInstance->mVirtualMethodTable;
  5375. BfMethodInstance* declMethodInstance = entry.mDeclaringMethod;
  5376. if ((mIsComptimeModule) || (typeInstance->IsTypeMemberAccessible(declMethodInstance->mMethodDef->mDeclaringType, mProject)))
  5377. {
  5378. // Prepare to reslot...
  5379. entry.mImplementingMethod = entry.mDeclaringMethod;
  5380. reslotNames.Add(declMethodInstance->mMethodDef->mName);
  5381. }
  5382. else
  5383. {
  5384. // Decl isn't accessible, null out entry
  5385. entry.mImplementingMethod = BfMethodRef();
  5386. }
  5387. }
  5388. }
  5389. if (!reslotNames.IsEmpty())
  5390. {
  5391. BfAmbiguityContext ambiguityContext;
  5392. ambiguityContext.mTypeInstance = typeInstance;
  5393. ambiguityContext.mModule = this;
  5394. ambiguityContext.mIsProjectSpecific = true;
  5395. ambiguityContext.mIsReslotting = true;
  5396. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  5397. for (auto& methodGroup : typeInstance->mMethodInstanceGroups)
  5398. {
  5399. auto methodInstance = methodGroup.mDefault;
  5400. if ((methodInstance == NULL) || (!methodInstance->mMethodDef->mIsOverride))
  5401. continue;
  5402. if (!reslotNames.Contains(methodInstance->mMethodDef->mName))
  5403. continue;
  5404. if ((!mIsComptimeModule) && (!typeInstance->IsTypeMemberAccessible(methodInstance->mMethodDef->mDeclaringType, mProject)))
  5405. continue;
  5406. if ((methodInstance->mChainType != BfMethodChainType_None) && (methodInstance->mChainType != BfMethodChainType_ChainHead))
  5407. continue;
  5408. SlotVirtualMethod(methodInstance, &ambiguityContext);
  5409. }
  5410. ambiguityContext.Finish();
  5411. }
  5412. }
  5413. bool isInExts = false;
  5414. for (int virtIdx = 0; virtIdx < (int)typeInstance->mVirtualMethodTable.size(); virtIdx++)
  5415. {
  5416. BfIRValue vValue = voidPtrNull;
  5417. auto& entry = typeInstance->mVirtualMethodTable[virtIdx];
  5418. BfModuleMethodInstance moduleMethodInst;
  5419. if (entry.mDeclaringMethod.mMethodNum == -1)
  5420. {
  5421. // mMethodNum of -1 indicates a vExt slot rather than an actual method reference
  5422. isInExts = true;
  5423. BfIRValue vExt = CreateClassVDataExtGlobal(entry.mDeclaringMethod.mTypeInstance, typeInstance, virtIdx);
  5424. if (vExt)
  5425. vValue = mBfIRBuilder->CreateBitCast(vExt, voidPtrIRType);
  5426. }
  5427. else
  5428. {
  5429. BfMethodInstance* declaringMethodInstance = (BfMethodInstance*)entry.mDeclaringMethod;
  5430. if ((declaringMethodInstance != NULL) && (declaringMethodInstance->mMethodInstanceGroup->IsImplemented()) && (declaringMethodInstance->mIsReified))
  5431. {
  5432. BF_ASSERT(entry.mImplementingMethod.mTypeInstance->mMethodInstanceGroups[entry.mImplementingMethod.mMethodNum].IsImplemented());
  5433. BF_ASSERT(entry.mImplementingMethod.mTypeInstance->mMethodInstanceGroups[entry.mImplementingMethod.mMethodNum].mDefault->mIsReified);
  5434. BfMethodInstance* methodInstance = (BfMethodInstance*)entry.mImplementingMethod;
  5435. if ((methodInstance != NULL) && (!methodInstance->mMethodDef->mIsAbstract))
  5436. {
  5437. BF_ASSERT((mIsComptimeModule) || typeInstance->IsTypeMemberAccessible(methodInstance->mMethodDef->mDeclaringType, mProject));
  5438. moduleMethodInst = GetMethodInstanceAtIdx(methodInstance->mMethodInstanceGroup->mOwner, methodInstance->mMethodInstanceGroup->mMethodIdx, NULL, BfGetMethodInstanceFlag_NoInline);
  5439. auto funcPtr = mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, voidPtrIRType);
  5440. vValue = funcPtr;
  5441. }
  5442. }
  5443. }
  5444. while (origVirtTypeStack.size() != 0)
  5445. {
  5446. BfTypeInstance* useTypeInst = origVirtTypeStack[origVirtTypeStack.size() - 1];
  5447. if (virtIdx >= useTypeInst->mVirtualMethodTableSize)
  5448. {
  5449. // Moved past current base vtable size
  5450. origVirtTypeStack.pop_back();
  5451. continue;
  5452. }
  5453. if (origVirtIdx < useTypeInst->GetOrigVTableSize())
  5454. {
  5455. // We are within the original vtable size
  5456. int idx = startTabIdx + origVirtIdx;
  5457. origVirtIdx++;
  5458. vData.push_back(vValue);
  5459. }
  5460. else
  5461. {
  5462. // This is a new entry, it only gets added to the ext
  5463. BF_ASSERT(isInExts);
  5464. }
  5465. break;
  5466. }
  5467. }
  5468. if (!origVTable.empty())
  5469. typeInstance->mVirtualMethodTable = origVTable;
  5470. }
  5471. int ifaceMethodExtStart = (int)typeInstance->GetIFaceVMethodSize();
  5472. if (typeInstance->mHotTypeData != NULL)
  5473. {
  5474. if (typeInstance->mHotTypeData->mOrigInterfaceMethodsLength != -1)
  5475. ifaceMethodExtStart = typeInstance->mHotTypeData->mOrigInterfaceMethodsLength;
  5476. }
  5477. SizedArray<BfIRValue, 32> ifaceMethodExtData;
  5478. int iFaceMethodStartIdx = (int)vData.size();
  5479. vData.resize(iFaceMethodStartIdx + ifaceMethodExtStart);
  5480. for (int i = iFaceMethodStartIdx; i < iFaceMethodStartIdx + ifaceMethodExtStart; i++)
  5481. vData[i] = voidPtrNull;
  5482. if (expectNumElements != 0)
  5483. BF_ASSERT(expectNumElements == vData.size());
  5484. //BF_ASSERT(vData.size() == expectNumElements);
  5485. // for (int i = 0; i < (int)typeInstance->mInterfaceMethodTable.size() - ifaceMethodExtStart; i++)
  5486. // ifaceMethodExtData.Add(voidPtrNull);
  5487. int ifaceEntryIdx = iFaceMethodStartIdx;
  5488. for (auto& interfacePair : interfaceMap)
  5489. {
  5490. auto interfaceEntry = interfacePair.mValue.mEntry;
  5491. if (typeInstance->mDefineState < BfTypeDefineState_DefinedAndMethodsSlotted)
  5492. {
  5493. BF_ASSERT(mIsComptimeModule);
  5494. break;
  5495. }
  5496. bool makeEmpty = false;
  5497. if ((!mIsComptimeModule) && (!typeInstance->IsTypeMemberAccessible(interfaceEntry->mDeclaringType, mProject)))
  5498. makeEmpty = true;
  5499. int endVirtualIdx = interfaceEntry->mStartVirtualIdx + interfaceEntry->mInterfaceType->mVirtualMethodTableSize;
  5500. bool useExt = endVirtualIdx > ifaceMethodExtStart;
  5501. for (int methodIdx = 0; methodIdx < (int)interfaceEntry->mInterfaceType->mMethodInstanceGroups.size(); methodIdx++)
  5502. {
  5503. BfIRValue pushValue;
  5504. BfMethodInstance* ifaceMethodInstance = interfaceEntry->mInterfaceType->mMethodInstanceGroups[methodIdx].mDefault;
  5505. if ((ifaceMethodInstance == NULL) || (ifaceMethodInstance->mVirtualTableIdx == -1))
  5506. continue;
  5507. if ((!ifaceMethodInstance->mIsReified) || (!ifaceMethodInstance->mMethodInstanceGroup->IsImplemented()))
  5508. continue;
  5509. if (makeEmpty)
  5510. {
  5511. pushValue = voidPtrNull;
  5512. }
  5513. else
  5514. {
  5515. auto& methodRef = typeInstance->mInterfaceMethodTable[interfaceEntry->mStartInterfaceTableIdx + methodIdx].mMethodRef;
  5516. auto methodInstance = (BfMethodInstance*)methodRef;
  5517. if ((methodInstance != NULL) && (!methodInstance->mMethodDef->mIsAbstract))
  5518. {
  5519. BF_ASSERT(methodInstance->mIsReified);
  5520. // This doesn't work because we may have FOREIGN methods from implicit interface methods
  5521. //auto moduleMethodInst = GetMethodInstanceAtIdx(methodRef.mTypeInstance, methodRef.mMethodNum);
  5522. auto moduleMethodInst = ReferenceExternalMethodInstance(methodInstance, BfGetMethodInstanceFlag_NoInline);
  5523. auto funcPtr = mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, voidPtrIRType);
  5524. pushValue = funcPtr;
  5525. }
  5526. else
  5527. {
  5528. pushValue = voidPtrNull;
  5529. }
  5530. }
  5531. int idx = interfaceEntry->mStartVirtualIdx + ifaceMethodInstance->mVirtualTableIdx;
  5532. if (idx < ifaceMethodExtStart)
  5533. {
  5534. BF_ASSERT(iFaceMethodStartIdx + idx < (int)vData.size());
  5535. vData[iFaceMethodStartIdx + idx] = pushValue;
  5536. }
  5537. else
  5538. {
  5539. BF_ASSERT(useExt);
  5540. int extIdx = idx - ifaceMethodExtStart;
  5541. while (extIdx >= ifaceMethodExtData.size())
  5542. ifaceMethodExtData.Add(voidPtrNull);
  5543. ifaceMethodExtData[extIdx] = pushValue;
  5544. }
  5545. }
  5546. }
  5547. if (typeInstance->IsBoxed())
  5548. {
  5549. BfBoxedType* boxedType = (BfBoxedType*)typeInstance;
  5550. if (boxedType->IsBoxedStructPtr())
  5551. {
  5552. // Force override of GetHashCode so we use the pointer address as the hash code
  5553. checkTypeInst = CreateBoxedType(ResolveTypeDef(mCompiler->mPointerTypeDef));
  5554. // Force override of GetHashCode so we use the pointer address as the hash code
  5555. for (auto& checkIFace : checkTypeInst->mInterfaces)
  5556. {
  5557. for (int methodIdx = 0; methodIdx < (int)checkIFace.mInterfaceType->mMethodInstanceGroups.size(); methodIdx++)
  5558. {
  5559. BfIRValue pushValue;
  5560. BfMethodInstance* ifaceMethodInstance = checkIFace.mInterfaceType->mMethodInstanceGroups[methodIdx].mDefault;
  5561. if ((ifaceMethodInstance == NULL) || (ifaceMethodInstance->mVirtualTableIdx == -1))
  5562. continue;
  5563. if ((!ifaceMethodInstance->mIsReified) || (!ifaceMethodInstance->mMethodInstanceGroup->IsImplemented()))
  5564. continue;
  5565. auto& methodRef = checkTypeInst->mInterfaceMethodTable[checkIFace.mStartInterfaceTableIdx + methodIdx].mMethodRef;
  5566. auto methodInstance = (BfMethodInstance*)methodRef;
  5567. BF_ASSERT(methodInstance->mIsReified);
  5568. // This doesn't work because we may have FOREIGN methods from implicit interface methods
  5569. //auto moduleMethodInst = GetMethodInstanceAtIdx(methodRef.mTypeInstance, methodRef.mMethodNum);
  5570. auto moduleMethodInst = ReferenceExternalMethodInstance(methodInstance, BfGetMethodInstanceFlag_NoInline);
  5571. auto funcPtr = mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, voidPtrIRType);
  5572. int idx = checkIFace.mStartVirtualIdx + ifaceMethodInstance->mVirtualTableIdx;
  5573. vData[iFaceMethodStartIdx + idx] = funcPtr;
  5574. }
  5575. }
  5576. }
  5577. }
  5578. if ((needsVData) && (!typeInstance->mTypeDef->mIsStatic) && (!mIsComptimeModule))
  5579. {
  5580. BfIRValue ifaceMethodExtVar;
  5581. if ((!ifaceMethodExtData.IsEmpty()) && (!mIsComptimeModule))
  5582. {
  5583. StringT<128> classVDataName;
  5584. BfMangler::MangleStaticFieldName(classVDataName, mCompiler->GetMangleKind(), typeInstance, "bf_hs_replace_IFaceExt");
  5585. auto arrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr), (int)ifaceMethodExtData.size());
  5586. ifaceMethodExtVar = mBfIRBuilder->CreateGlobalVariable(arrayType, true,
  5587. BfIRLinkageType_External, BfIRValue(), classVDataName);
  5588. BfIRType extVTableType = mBfIRBuilder->GetSizedArrayType(voidPtrIRType, (int)ifaceMethodExtData.size());
  5589. BfIRValue extVTableConst = mBfIRBuilder->CreateConstAgg_Value(extVTableType, ifaceMethodExtData);
  5590. mBfIRBuilder->GlobalVar_SetInitializer(ifaceMethodExtVar, extVTableConst);
  5591. }
  5592. for (auto& ifaceInstPair : interfaceMap)
  5593. {
  5594. auto interfaceEntry = ifaceInstPair.mValue.mEntry;
  5595. int slotNum = interfaceEntry->mInterfaceType->mSlotNum;
  5596. if (slotNum >= 0)
  5597. {
  5598. BfIRValue vtablePtr;
  5599. int idx = interfaceEntry->mStartVirtualIdx;
  5600. int endVirtualIdx = interfaceEntry->mStartVirtualIdx + interfaceEntry->mInterfaceType->mVirtualMethodTableSize;
  5601. if ((endVirtualIdx > ifaceMethodExtStart) && (ifaceMethodExtVar))
  5602. vtablePtr = mBfIRBuilder->CreateInBoundsGEP(ifaceMethodExtVar, 0, interfaceEntry->mStartVirtualIdx - ifaceMethodExtStart);
  5603. else
  5604. vtablePtr = mBfIRBuilder->CreateInBoundsGEP(classVDataVar, 0, iFaceMethodStartIdx + interfaceEntry->mStartVirtualIdx);
  5605. int slotVirtIdx = slotNum + vDataOfs;
  5606. if (vData[slotVirtIdx] == voidPtrNull)
  5607. {
  5608. vData[slotVirtIdx] = mBfIRBuilder->CreateBitCast(vtablePtr, voidPtrIRType);
  5609. }
  5610. else
  5611. {
  5612. if (mCompiler->IsHotCompile())
  5613. Fail("Interface slot collision error. Restart program or undo interface changes.", typeDef->GetRefNode());
  5614. else
  5615. Fail("Interface slot collision error", typeDef->GetRefNode());
  5616. }
  5617. }
  5618. }
  5619. }
  5620. }
  5621. BfIRValue typeNameConst;
  5622. BfIRValue namespaceConst;
  5623. if (needsTypeNames)
  5624. {
  5625. typeNameConst = GetStringObjectValue(typeDef->mName->mString, !mIsComptimeModule);
  5626. namespaceConst = GetStringObjectValue(typeDef->mNamespace.ToString(), !mIsComptimeModule);
  5627. }
  5628. else
  5629. {
  5630. auto stringType = ResolveTypeDef(mCompiler->mStringTypeDef);
  5631. typeNameConst = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(stringType));
  5632. namespaceConst = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(stringType));
  5633. }
  5634. int baseTypeId = 0;
  5635. if (typeInstance->mBaseType != NULL)
  5636. {
  5637. baseTypeId = typeInstance->mBaseType->mTypeId;
  5638. }
  5639. BfTypeOptions* typeOptions = NULL;
  5640. if (typeInstance->mTypeOptionsIdx >= 0)
  5641. typeOptions = mSystem->GetTypeOptions(typeInstance->mTypeOptionsIdx);
  5642. SizedArray<BfIRValue, 16> customAttrs;
  5643. BfTypeInstance* attributeType = mContext->mUnreifiedModule->ResolveTypeDef(mCompiler->mAttributeTypeDef)->ToTypeInstance();
  5644. BfIRValue castedClassVData;
  5645. if (classVDataVar)
  5646. castedClassVData = mBfIRBuilder->CreateBitCast(classVDataVar, mBfIRBuilder->MapType(mContext->mBfClassVDataPtrType));
  5647. else
  5648. castedClassVData = GetDefaultValue(mContext->mBfClassVDataPtrType);
  5649. bool freflectIncludeTypeData = false;
  5650. bool reflectIncludeAllFields = false;
  5651. bool reflectIncludeAllMethods = false;
  5652. if (TypeIsSubTypeOf(typeInstance, attributeType))
  5653. {
  5654. reflectIncludeAllFields = true;
  5655. reflectIncludeAllMethods = true;
  5656. }
  5657. BfReflectKind reflectKind = BfReflectKind_Type;
  5658. auto _GetReflectUserFromDirective = [&](BfAttributeDirective* attributesDirective, BfAttributeTargets attrTarget)
  5659. {
  5660. BfReflectKind reflectKind = BfReflectKind_None;
  5661. auto customAttrs = GetCustomAttributes(attributesDirective, attrTarget);
  5662. if (customAttrs != NULL)
  5663. {
  5664. for (auto& attr : customAttrs->mAttributes)
  5665. {
  5666. reflectKind = (BfReflectKind)(reflectKind | GetUserReflectKind(attr.mType));
  5667. }
  5668. }
  5669. return reflectKind;
  5670. };
  5671. reflectKind = GetReflectKind(reflectKind, typeInstance);
  5672. // Fields
  5673. BfType* reflectFieldDataType = ResolveTypeDef(mCompiler->mReflectFieldDataDef);
  5674. BfIRValue emptyValueType = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectFieldDataType->ToTypeInstance()->mBaseType), SizedArray<BfIRValue, 1>());
  5675. auto _HandleCustomAttrs = [&](BfCustomAttributes* customAttributes)
  5676. {
  5677. if (customAttributes == NULL)
  5678. return -1;
  5679. Array<BfCustomAttribute*> reflectAttributes;
  5680. for (auto& attr : customAttributes->mAttributes)
  5681. {
  5682. bool wantAttribute = false;
  5683. if (attr.mType->mCustomAttributes != NULL)
  5684. {
  5685. auto usageAttribute = attr.mType->mCustomAttributes->Get(mCompiler->mAttributeUsageAttributeTypeDef);
  5686. if (usageAttribute != NULL)
  5687. {
  5688. // Check for Flags arg
  5689. if (usageAttribute->mCtorArgs.size() < 2)
  5690. continue;
  5691. auto constant = attr.mType->mConstHolder->GetConstant(usageAttribute->mCtorArgs[1]);
  5692. if (constant == NULL)
  5693. continue;
  5694. if (constant->mTypeCode == BfTypeCode_Boolean)
  5695. continue;
  5696. if ((constant->mInt8 & BfCustomAttributeFlags_ReflectAttribute) != 0)
  5697. wantAttribute = true;
  5698. }
  5699. }
  5700. if ((wantAttribute) && (attr.mType->mIsReified))
  5701. {
  5702. reflectAttributes.Add(&attr);
  5703. }
  5704. }
  5705. if (reflectAttributes.size() == 0)
  5706. return -1;
  5707. #define PUSH_INT8(val) data.push_back((uint8)val)
  5708. #define PUSH_INT16(val) { data.push_back(val & 0xFF); data.push_back((val >> 8) & 0xFF); }
  5709. #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); }
  5710. SizedArray<uint8, 16> data;
  5711. int customAttrIdx = (int)customAttrs.size();
  5712. data.push_back((uint8)reflectAttributes.size());
  5713. for (auto attr : reflectAttributes)
  5714. {
  5715. // Size prefix
  5716. int sizeIdx = (int)data.size();
  5717. PUSH_INT16(0); // mSize
  5718. PUSH_INT32(attr->mType->mTypeId); // mType
  5719. int ctorIdx = -1;
  5720. int ctorCount = 0;
  5721. attr->mType->mTypeDef->PopulateMemberSets();
  5722. BfMemberSetEntry* entry;
  5723. if (attr->mType->mTypeDef->mMethodSet.TryGetWith(String("__BfCtor"), &entry))
  5724. {
  5725. BfMethodDef* nextMethodDef = (BfMethodDef*)entry->mMemberDef;
  5726. while (nextMethodDef != NULL)
  5727. {
  5728. if (nextMethodDef == attr->mCtor)
  5729. ctorIdx = ctorCount;
  5730. nextMethodDef = nextMethodDef->mNextWithSameName;
  5731. ctorCount++;
  5732. }
  5733. }
  5734. BF_ASSERT(ctorIdx != -1);
  5735. if (ctorIdx != -1)
  5736. ctorIdx = (ctorCount - 1) - ctorIdx;
  5737. PUSH_INT16(ctorIdx);
  5738. auto ctorMethodInstance = GetRawMethodInstanceAtIdx(attr->mType, attr->mCtor->mIdx);
  5739. int argIdx = 0;
  5740. for (auto arg : attr->mCtorArgs)
  5741. {
  5742. auto argType = ctorMethodInstance->GetParamType(argIdx);
  5743. EncodeAttributeData(typeInstance, argType, arg, data, usedStringIdMap);
  5744. argIdx++;
  5745. }
  5746. int size = (int)data.size() - sizeIdx;
  5747. *((uint16*)&data[sizeIdx]) = size;
  5748. }
  5749. #undef PUSH_INT8
  5750. #undef PUSH_INT16
  5751. #undef PUSH_INT32
  5752. SizedArray<BfIRValue, 16> dataValues;
  5753. for (uint8 val : data)
  5754. dataValues.push_back(GetConstValue8(val));
  5755. auto dataArrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->MapType(byteType), (int)data.size());
  5756. auto customAttrConst = mBfIRBuilder->CreateConstAgg_Value(dataArrayType, dataValues);
  5757. BfIRValue customAttrArray = mBfIRBuilder->CreateGlobalVariable(dataArrayType, true, BfIRLinkageType_Internal,
  5758. customAttrConst, typeDataName + StrFormat(".customAttr%d", customAttrIdx));
  5759. BfIRValue customAttrArrayPtr = mBfIRBuilder->CreateBitCast(customAttrArray, voidPtrIRType);
  5760. customAttrs.push_back(customAttrArrayPtr);
  5761. return customAttrIdx;
  5762. };
  5763. int typeCustomAttrIdx = _HandleCustomAttrs(typeInstance->mCustomAttributes);
  5764. SizedArray<int, 16> reflectFieldIndices;
  5765. for (int pass = 0; pass < 2; pass++)
  5766. {
  5767. bool skippedField = false;
  5768. reflectFieldIndices.clear();
  5769. for (int fieldIdx = 0; fieldIdx < (int)typeInstance->mFieldInstances.size(); fieldIdx++)
  5770. {
  5771. BfFieldInstance* fieldInstance = &typeInstance->mFieldInstances[fieldIdx];
  5772. BfFieldDef* fieldDef = fieldInstance->GetFieldDef();
  5773. if (fieldDef == NULL)
  5774. continue;
  5775. auto fieldReflectKind = (BfReflectKind)(reflectKind & ~BfReflectKind_User);
  5776. bool includeField = reflectIncludeAllFields;
  5777. if (fieldInstance->mCustomAttributes != NULL)
  5778. {
  5779. for (auto& customAttr : fieldInstance->mCustomAttributes->mAttributes)
  5780. {
  5781. if (customAttr.mType->mTypeDef->mName->ToString() == "ReflectAttribute")
  5782. {
  5783. includeField = true;
  5784. }
  5785. else
  5786. {
  5787. auto userReflectKind = GetUserReflectKind(customAttr.mType);
  5788. fieldReflectKind = (BfReflectKind)(fieldReflectKind | userReflectKind);
  5789. }
  5790. }
  5791. }
  5792. if ((fieldReflectKind & BfReflectKind_User) != 0)
  5793. includeField = true;
  5794. if ((!fieldDef->mIsStatic) && ((fieldReflectKind & BfReflectKind_NonStaticFields) != 0))
  5795. includeField = true;
  5796. if ((fieldDef->mIsStatic) && ((fieldReflectKind & BfReflectKind_StaticFields) != 0))
  5797. includeField = true;
  5798. if ((!fieldDef->mIsStatic) && (typeOptions != NULL))
  5799. includeField = typeOptions->Apply(includeField, BfOptionFlags_ReflectNonStaticFields);
  5800. if ((fieldDef->mIsStatic) && (typeOptions != NULL))
  5801. includeField = typeOptions->Apply(includeField, BfOptionFlags_ReflectStaticFields);
  5802. includeField |= forceReflectFields;
  5803. if (!includeField)
  5804. {
  5805. skippedField = true;
  5806. continue;
  5807. }
  5808. reflectFieldIndices.Add(fieldIdx);
  5809. }
  5810. // For a splattable type, we need to either include all fields or zero fields. This is to allow us to correctly splat
  5811. // params for reflected method calls even if we don't have reflection field info for the splatted type. This is
  5812. // possible because we write out a SplatData structure containing just TypeIds in that case
  5813. if (pass == 0)
  5814. {
  5815. if (!typeInstance->IsSplattable())
  5816. break;
  5817. if (!skippedField)
  5818. break;
  5819. if (reflectFieldIndices.size() == 0)
  5820. break;
  5821. }
  5822. }
  5823. SizedArray<BfIRValue, 16> fieldTypes;
  5824. bool is32Bit = mCompiler->mSystem->mPtrSize == 4;
  5825. if ((typeInstance->IsPayloadEnum()) && (!typeInstance->IsBoxed()))
  5826. {
  5827. BfType* payloadType = typeInstance->GetUnionInnerType();
  5828. if (!payloadType->IsValuelessType())
  5829. {
  5830. BfIRValue payloadNameConst = GetStringObjectValue("$payload", !mIsComptimeModule);
  5831. SizedArray<BfIRValue, 8> payloadFieldVals;
  5832. if (is32Bit)
  5833. {
  5834. payloadFieldVals =
  5835. {
  5836. emptyValueType,
  5837. payloadNameConst, // mName
  5838. GetConstValue(payloadType->mTypeId, typeIdType), // mFieldTypeId
  5839. GetConstValue(0, intPtrType), // mData
  5840. GetConstValue(0, intPtrType), // mDataHi
  5841. GetConstValue(BfFieldFlags_SpecialName | BfFieldFlags_EnumPayload, shortType), // mFlags
  5842. GetConstValue(-1, intType), // mCustomAttributesIdx
  5843. };
  5844. }
  5845. else
  5846. {
  5847. payloadFieldVals =
  5848. {
  5849. emptyValueType,
  5850. payloadNameConst, // mName
  5851. GetConstValue(payloadType->mTypeId, typeIdType), // mFieldTypeId
  5852. GetConstValue(0, intPtrType), // mData
  5853. GetConstValue(BfFieldFlags_SpecialName | BfFieldFlags_EnumPayload, shortType), // mFlags
  5854. GetConstValue(-1, intType), // mCustomAttributesIdx
  5855. };
  5856. }
  5857. FixConstValueParams(reflectFieldDataType->ToTypeInstance(), payloadFieldVals);
  5858. auto payloadFieldData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectFieldDataType->ToTypeInstance(), BfIRPopulateType_Full), payloadFieldVals);
  5859. fieldTypes.push_back(payloadFieldData);
  5860. }
  5861. BfType* dscrType = typeInstance->GetDiscriminatorType();
  5862. BfIRValue dscrNameConst = GetStringObjectValue("$discriminator", !mIsComptimeModule);
  5863. SizedArray<BfIRValue, 8> dscrFieldVals;
  5864. if (is32Bit)
  5865. {
  5866. dscrFieldVals =
  5867. {
  5868. emptyValueType,
  5869. dscrNameConst, // mName
  5870. GetConstValue(dscrType->mTypeId, typeIdType), // mFieldTypeId
  5871. GetConstValue(BF_ALIGN(payloadType->mSize, dscrType->mAlign), intPtrType), // mData
  5872. GetConstValue(0, intPtrType), // mDataHi
  5873. GetConstValue(BfFieldFlags_SpecialName | BfFieldFlags_EnumDiscriminator, shortType), // mFlags
  5874. GetConstValue(-1, intType), // mCustomAttributesIdx
  5875. };
  5876. }
  5877. else
  5878. {
  5879. dscrFieldVals =
  5880. {
  5881. emptyValueType,
  5882. dscrNameConst, // mName
  5883. GetConstValue(dscrType->mTypeId, typeIdType), // mFieldTypeId
  5884. GetConstValue(BF_ALIGN(payloadType->mSize, dscrType->mAlign), intPtrType), // mData
  5885. GetConstValue(BfFieldFlags_SpecialName | BfFieldFlags_EnumDiscriminator, shortType), // mFlags
  5886. GetConstValue(-1, intType), // mCustomAttributesIdx
  5887. };
  5888. }
  5889. auto dscrFieldData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectFieldDataType->ToTypeInstance(), BfIRPopulateType_Full), dscrFieldVals);
  5890. fieldTypes.push_back(dscrFieldData);
  5891. }
  5892. for (auto fieldIdx : reflectFieldIndices)
  5893. {
  5894. if (!needsTypeData)
  5895. break;
  5896. BfFieldInstance* fieldInstance = &typeInstance->mFieldInstances[fieldIdx];
  5897. fieldTypes.push_back(CreateFieldData(fieldInstance, _HandleCustomAttrs(fieldInstance->mCustomAttributes)));
  5898. }
  5899. auto reflectFieldDataIRType = mBfIRBuilder->MapType(reflectFieldDataType);
  5900. BfIRValue fieldDataPtr;
  5901. BfIRType fieldDataPtrType = mBfIRBuilder->GetPointerTo(reflectFieldDataIRType);
  5902. if (fieldTypes.size() == 0)
  5903. {
  5904. if ((type->IsSplattable()) && (type->IsStruct()) && (!type->IsValuelessType()) && (!typeInstance->mIsCRepr))
  5905. {
  5906. BfTypeInstance* reflectFieldSplatDataType = ResolveTypeDef(mCompiler->mReflectFieldSplatDataDef)->ToTypeInstance();
  5907. SizedArray<BfIRValue, 3> splatTypes;
  5908. SizedArray<BfIRValue, 3> splatOffsets;
  5909. std::function<void(BfType*, int)> _CheckSplat = [&](BfType* checkType, int offset)
  5910. {
  5911. auto checkTypeInstance = checkType->ToTypeInstance();
  5912. if ((checkTypeInstance != NULL) && (checkTypeInstance->IsValueType()) && (checkTypeInstance->IsDataIncomplete()))
  5913. PopulateType(checkTypeInstance);
  5914. if (checkType->IsStruct())
  5915. {
  5916. int dataEnd = offset;
  5917. if (checkTypeInstance->mBaseType != NULL)
  5918. _CheckSplat(checkTypeInstance->mBaseType, offset);
  5919. if (checkTypeInstance->mIsUnion)
  5920. {
  5921. BfType* unionInnerType = checkTypeInstance->GetUnionInnerType();
  5922. _CheckSplat(unionInnerType, offset);
  5923. }
  5924. else
  5925. {
  5926. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  5927. {
  5928. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  5929. if (fieldInstance->mDataIdx >= 0)
  5930. {
  5931. _CheckSplat(fieldInstance->GetResolvedType(), offset + fieldInstance->mDataOffset);
  5932. dataEnd = offset + fieldInstance->mDataOffset + fieldInstance->mResolvedType->mSize;
  5933. }
  5934. }
  5935. }
  5936. if (checkTypeInstance->IsEnum())
  5937. {
  5938. // Add discriminator
  5939. auto dscrType = checkTypeInstance->GetDiscriminatorType();
  5940. if (checkTypeInstance->mPacking > 0)
  5941. dataEnd = BF_ALIGN(dataEnd, dscrType->mAlign);
  5942. _CheckSplat(dscrType, dataEnd);
  5943. }
  5944. }
  5945. else if (checkType->IsMethodRef())
  5946. {
  5947. // auto methodRefType = (BfMethodRefType*)checkType;
  5948. // for (int dataIdx = 0; dataIdx < methodRefType->GetCaptureDataCount(); dataIdx++)
  5949. // {
  5950. // if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  5951. // _CheckSplat(methodRefType->GetCaptureType(dataIdx), offsetof);
  5952. // else
  5953. // dataLambda(methodRefType->GetCaptureType(dataIdx));
  5954. // }
  5955. }
  5956. else if (!checkType->IsValuelessType())
  5957. {
  5958. splatTypes.Add(GetConstValue(checkType->mTypeId, typeIdType));
  5959. splatOffsets.Add(GetConstValue(offset, intType));
  5960. }
  5961. };
  5962. _CheckSplat(type, 0);
  5963. while (splatTypes.size() < 3)
  5964. {
  5965. splatTypes.Add(GetConstValue(0, typeIdType));
  5966. splatOffsets.Add(GetConstValue(0, intType));
  5967. }
  5968. BfIRValue splatTypesConst = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapType(reflectFieldSplatDataType->mFieldInstances[0].mResolvedType), splatTypes);
  5969. BfIRValue splatOffsetsConst = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapType(reflectFieldSplatDataType->mFieldInstances[1].mResolvedType), splatOffsets);
  5970. SizedArray<BfIRValue, 8> splatVals =
  5971. {
  5972. emptyValueType,
  5973. splatTypesConst,
  5974. splatOffsetsConst
  5975. };
  5976. auto fieldSplatData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectFieldSplatDataType->ToTypeInstance(), BfIRPopulateType_Full), splatVals);
  5977. BfIRValue fieldDataArray = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapType(reflectFieldSplatDataType), true, BfIRLinkageType_Internal,
  5978. fieldSplatData, typeDataName + ".splats");
  5979. fieldDataPtr = mBfIRBuilder->CreateBitCast(fieldDataArray, fieldDataPtrType);
  5980. }
  5981. else
  5982. fieldDataPtr = mBfIRBuilder->CreateConstNull(fieldDataPtrType);
  5983. }
  5984. else
  5985. {
  5986. BfIRType fieldDataConstType = mBfIRBuilder->GetSizedArrayType(reflectFieldDataIRType, (int)fieldTypes.size());
  5987. BfIRValue fieldDataConst = mBfIRBuilder->CreateConstAgg_Value(fieldDataConstType, fieldTypes);
  5988. BfIRValue fieldDataArray = mBfIRBuilder->CreateGlobalVariable(fieldDataConstType, true, BfIRLinkageType_Internal,
  5989. fieldDataConst, "fields." + typeDataName);
  5990. fieldDataPtr = mBfIRBuilder->CreateBitCast(fieldDataArray, fieldDataPtrType);
  5991. }
  5992. /// Methods
  5993. BfType* reflectMethodDataType = ResolveTypeDef(mCompiler->mReflectMethodDataDef);
  5994. BfType* reflectParamDataType = ResolveTypeDef(mCompiler->mReflectParamDataDef);
  5995. BfType* reflectParamDataPtrType = CreatePointerType(reflectParamDataType);
  5996. struct _SortedMethodInfo
  5997. {
  5998. BfMethodDef* mMethodDef;
  5999. BfMethodCustomAttributes* mMethodCustomAttributes;
  6000. };
  6001. Array<_SortedMethodInfo> sortedMethodList;
  6002. SizedArray<BfIRValue, 16> methodTypes;
  6003. for (int methodIdx = 0; methodIdx < (int)typeDef->mMethods.size(); methodIdx++)
  6004. {
  6005. if (!needsTypeData)
  6006. break;
  6007. // Disable const method reflection info for now
  6008. if (mIsComptimeModule)
  6009. break;
  6010. auto methodInstanceGroup = &typeInstance->mMethodInstanceGroups[methodIdx];
  6011. if (!methodInstanceGroup->IsImplemented())
  6012. continue;
  6013. auto methodDef = typeDef->mMethods[methodIdx];
  6014. if (methodDef->mIsNoReflect)
  6015. continue;
  6016. if (methodDef->mHasComptime)
  6017. continue;
  6018. auto defaultMethod = methodInstanceGroup->mDefault;
  6019. if (defaultMethod == NULL)
  6020. continue;
  6021. if (defaultMethod->mIsUnspecialized)
  6022. continue;
  6023. if (!defaultMethod->mIsReified)
  6024. continue;
  6025. if ((defaultMethod->mChainType == BfMethodChainType_ChainMember) || (defaultMethod->mChainType == BfMethodChainType_ChainSkip))
  6026. continue;
  6027. if (defaultMethod->mMethodDef->mMethodType == BfMethodType_CtorNoBody)
  6028. continue;
  6029. auto methodReflectKind = (BfReflectKind)(reflectKind & ~BfReflectKind_User);
  6030. bool includeMethod = reflectIncludeAllMethods;
  6031. BfMethodCustomAttributes* methodCustomAttributes = NULL;
  6032. if ((defaultMethod->mMethodInfoEx != NULL) && (defaultMethod->mMethodInfoEx->mMethodCustomAttributes != NULL) && (defaultMethod->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes != NULL))
  6033. {
  6034. methodCustomAttributes = defaultMethod->mMethodInfoEx->mMethodCustomAttributes;
  6035. for (auto& customAttr : defaultMethod->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes->mAttributes)
  6036. {
  6037. if (customAttr.mType->mTypeDef->mName->ToString() == "ReflectAttribute")
  6038. {
  6039. includeMethod = true;
  6040. }
  6041. else
  6042. {
  6043. auto userReflectKind = GetUserReflectKind(customAttr.mType);
  6044. methodReflectKind = (BfReflectKind)(methodReflectKind | userReflectKind);
  6045. }
  6046. }
  6047. }
  6048. if ((!mIsComptimeModule) && (!typeInstance->IsTypeMemberAccessible(methodDef->mDeclaringType, mProject)))
  6049. continue;
  6050. //
  6051. {
  6052. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  6053. if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  6054. {
  6055. for (BfParameterDeclaration* paramDecl : methodDeclaration->mParams)
  6056. {
  6057. if (paramDecl->mAttributes != NULL)
  6058. methodReflectKind = (BfReflectKind)(methodReflectKind | _GetReflectUserFromDirective(paramDecl->mAttributes, BfAttributeTargets_Parameter));
  6059. }
  6060. }
  6061. }
  6062. if ((methodReflectKind & (BfReflectKind_Methods | BfReflectKind_User)) != 0)
  6063. includeMethod = true;
  6064. if ((methodDef->mIsStatic) && ((methodReflectKind & BfReflectKind_StaticMethods) != 0))
  6065. includeMethod = true;
  6066. if ((methodDef->mMethodType == BfMethodType_Ctor) || (methodDef->mMethodType == BfMethodType_CtorCalcAppend))
  6067. {
  6068. if ((methodReflectKind & BfReflectKind_Constructors) != 0)
  6069. includeMethod = true;
  6070. if ((methodDef->IsDefaultCtor()) && ((methodReflectKind & BfReflectKind_DefaultConstructor) != 0))
  6071. includeMethod = true;
  6072. }
  6073. if ((!includeMethod) && (typeOptions != NULL))
  6074. includeMethod = ApplyTypeOptionMethodFilters(includeMethod, methodDef, typeOptions);
  6075. if (!includeMethod)
  6076. continue;
  6077. sortedMethodList.Add({ methodDef, methodCustomAttributes });
  6078. }
  6079. auto _GetMethodKind = [](BfMethodDef* methodDef)
  6080. {
  6081. if (methodDef->mMethodType == BfMethodType_Ctor)
  6082. return 0;
  6083. return 1;
  6084. };
  6085. std::sort(sortedMethodList.begin(), sortedMethodList.end(), [_GetMethodKind](const _SortedMethodInfo& lhs, const _SortedMethodInfo& rhs)
  6086. {
  6087. int lhsKind = _GetMethodKind(lhs.mMethodDef);
  6088. int rhsKind = _GetMethodKind(rhs.mMethodDef);
  6089. if (lhsKind != rhsKind)
  6090. return lhsKind < rhsKind;
  6091. if (lhs.mMethodDef->mName != rhs.mMethodDef->mName)
  6092. return lhs.mMethodDef->mName < rhs.mMethodDef->mName;
  6093. return lhs.mMethodDef->mIdx < rhs.mMethodDef->mIdx;
  6094. });
  6095. for (auto& methodInfo : sortedMethodList)
  6096. {
  6097. auto methodDef = methodInfo.mMethodDef;
  6098. int methodIdx = methodDef->mIdx;
  6099. auto methodInstanceGroup = &typeInstance->mMethodInstanceGroups[methodIdx];
  6100. auto defaultMethod = methodInstanceGroup->mDefault;
  6101. BfModuleMethodInstance moduleMethodInstance;
  6102. BfIRValue funcVal = voidPtrNull;
  6103. if (((!typeInstance->IsBoxed()) || (!methodDef->mIsStatic)) &&
  6104. (!typeInstance->IsUnspecializedType()) &&
  6105. (methodDef->mMethodType != BfMethodType_Ignore) &&
  6106. (methodDef->mMethodType != BfMethodType_Mixin) &&
  6107. (!methodDef->mIsAbstract) &&
  6108. (methodDef->mGenericParams.size() == 0))
  6109. {
  6110. moduleMethodInstance = GetMethodInstanceAtIdx(typeInstance, methodIdx, NULL, BfGetMethodInstanceFlag_NoInline);
  6111. if (moduleMethodInstance.mFunc)
  6112. funcVal = mBfIRBuilder->CreateBitCast(moduleMethodInstance.mFunc, voidPtrIRType);
  6113. }
  6114. BfIRValue methodNameConst = GetStringObjectValue(methodDef->mName, !mIsComptimeModule);
  6115. BfMethodFlags methodFlags = defaultMethod->GetMethodFlags();
  6116. int customAttrIdx = -1;
  6117. int returnCustomAttrIdx = -1;
  6118. if (methodInfo.mMethodCustomAttributes != NULL)
  6119. {
  6120. customAttrIdx = _HandleCustomAttrs(methodInfo.mMethodCustomAttributes->mCustomAttributes);
  6121. returnCustomAttrIdx = _HandleCustomAttrs(methodInfo.mMethodCustomAttributes->mReturnCustomAttributes);
  6122. }
  6123. enum ParamFlags
  6124. {
  6125. ParamFlag_None = 0,
  6126. ParamFlag_Splat = 1,
  6127. ParamFlag_Implicit = 2,
  6128. ParamFlag_AppendIdx = 4
  6129. };
  6130. SizedArray<BfIRValue, 8> paramVals;
  6131. for (int paramIdx = 0; paramIdx < defaultMethod->GetParamCount(); paramIdx++)
  6132. {
  6133. String paramName = defaultMethod->GetParamName(paramIdx);
  6134. BfType* paramType = defaultMethod->GetParamType(paramIdx);
  6135. ParamFlags paramFlags = ParamFlag_None;
  6136. if (defaultMethod->GetParamIsSplat(paramIdx))
  6137. paramFlags = (ParamFlags)(paramFlags | ParamFlag_Splat);
  6138. if (defaultMethod->GetParamKind(paramIdx) == BfParamKind_AppendIdx)
  6139. paramFlags = (ParamFlags)(paramFlags | ParamFlag_Implicit | ParamFlag_AppendIdx);
  6140. BfIRValue paramNameConst = GetStringObjectValue(paramName, !mIsComptimeModule);
  6141. int paramCustomAttrIdx = -1;
  6142. if ((methodInfo.mMethodCustomAttributes != NULL) && (paramIdx < (int)methodInfo.mMethodCustomAttributes->mParamCustomAttributes.mSize))
  6143. paramCustomAttrIdx = _HandleCustomAttrs(methodInfo.mMethodCustomAttributes->mParamCustomAttributes[paramIdx]);
  6144. SizedArray<BfIRValue, 8> paramDataVals =
  6145. {
  6146. emptyValueType,
  6147. paramNameConst,
  6148. GetConstValue(paramType->mTypeId, typeIdType),
  6149. GetConstValue((int32)paramFlags, shortType),
  6150. GetConstValue(-1, intType), // defaultIdx
  6151. GetConstValue(paramCustomAttrIdx, intType) // customAttrIdx
  6152. };
  6153. auto paramData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapType(reflectParamDataType, BfIRPopulateType_Full), paramDataVals);
  6154. paramVals.Add(paramData);
  6155. }
  6156. BfIRValue paramsVal;
  6157. if (paramVals.size() > 0)
  6158. {
  6159. BfIRType paramDataArrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->MapType(reflectParamDataType, BfIRPopulateType_Full), (int)paramVals.size());
  6160. BfIRValue paramDataConst = mBfIRBuilder->CreateConstAgg_Value(paramDataArrayType, paramVals);
  6161. BfIRValue paramDataArray = mBfIRBuilder->CreateGlobalVariable(paramDataArrayType, true, BfIRLinkageType_Internal,
  6162. paramDataConst, typeDataName + StrFormat(".params%d", methodIdx));
  6163. paramsVal = mBfIRBuilder->CreateBitCast(paramDataArray, mBfIRBuilder->MapType(reflectParamDataPtrType));
  6164. }
  6165. else
  6166. paramsVal = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(reflectParamDataPtrType));
  6167. int vDataVal = -1;
  6168. if (defaultMethod->mVirtualTableIdx != -1)
  6169. {
  6170. int vDataIdx = -1;
  6171. if (type->IsInterface())
  6172. {
  6173. vDataIdx = defaultMethod->mVirtualTableIdx;
  6174. }
  6175. else
  6176. {
  6177. vDataIdx = 1 + mCompiler->GetDynCastVDataCount() + mCompiler->mMaxInterfaceSlots;
  6178. if ((mCompiler->mOptions.mHasVDataExtender) && (mCompiler->IsHotCompile()))
  6179. {
  6180. auto typeInst = defaultMethod->mMethodInstanceGroup->mOwner;
  6181. int extMethodIdx = (defaultMethod->mVirtualTableIdx - typeInst->GetImplBaseVTableSize()) - typeInst->GetOrigSelfVTableSize();
  6182. if (extMethodIdx >= 0)
  6183. {
  6184. // Extension?
  6185. int vExtOfs = typeInst->GetOrigImplBaseVTableSize();
  6186. vDataVal = ((vDataIdx + vExtOfs + 1) << 20) | (extMethodIdx);
  6187. }
  6188. else
  6189. {
  6190. // Map this new virtual index back to the original index
  6191. vDataIdx += (defaultMethod->mVirtualTableIdx - typeInst->GetImplBaseVTableSize()) + typeInst->GetOrigImplBaseVTableSize();
  6192. }
  6193. }
  6194. else
  6195. {
  6196. vDataIdx += defaultMethod->mVirtualTableIdx;
  6197. }
  6198. }
  6199. if (vDataVal == -1)
  6200. vDataVal = vDataIdx * mSystem->mPtrSize;
  6201. }
  6202. SizedArray<BfIRValue, 8> methodDataVals =
  6203. {
  6204. emptyValueType,
  6205. methodNameConst, // mName
  6206. funcVal, // mFuncPtr
  6207. paramsVal,
  6208. GetConstValue(defaultMethod->mReturnType->mTypeId, typeIdType),
  6209. GetConstValue((int)paramVals.size(), shortType),
  6210. GetConstValue(methodFlags, shortType),
  6211. GetConstValue(methodIdx, intType),
  6212. GetConstValue(vDataVal, intType),
  6213. GetConstValue(customAttrIdx, intType),
  6214. GetConstValue(returnCustomAttrIdx, intType),
  6215. };
  6216. auto methodData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectMethodDataType->ToTypeInstance(), BfIRPopulateType_Full), methodDataVals);
  6217. methodTypes.push_back(methodData);
  6218. }
  6219. BfIRValue methodDataPtr;
  6220. BfIRType methodDataPtrType = mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapType(reflectMethodDataType));
  6221. if (methodTypes.size() == 0)
  6222. methodDataPtr = mBfIRBuilder->CreateConstNull(methodDataPtrType);
  6223. else
  6224. {
  6225. BfIRType methodDataArrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->MapType(reflectMethodDataType, BfIRPopulateType_Full), (int)methodTypes.size());
  6226. BfIRValue methodDataConst = mBfIRBuilder->CreateConstAgg_Value(methodDataArrayType, methodTypes);
  6227. BfIRValue methodDataArray = mBfIRBuilder->CreateGlobalVariable(methodDataArrayType, true, BfIRLinkageType_Internal,
  6228. methodDataConst, "methods." + typeDataName);
  6229. methodDataPtr = mBfIRBuilder->CreateBitCast(methodDataArray, methodDataPtrType);
  6230. }
  6231. /////
  6232. int interfaceCount = 0;
  6233. BfIRValue interfaceDataPtr;
  6234. BfType* reflectInterfaceDataType = ResolveTypeDef(mCompiler->mReflectInterfaceDataDef);
  6235. BfIRType interfaceDataPtrType = mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapType(reflectInterfaceDataType));
  6236. Array<bool> wantsIfaceMethod;
  6237. bool wantsIfaceMethods = false;
  6238. if (typeInstance->mInterfaces.IsEmpty())
  6239. interfaceDataPtr = mBfIRBuilder->CreateConstNull(interfaceDataPtrType);
  6240. else
  6241. {
  6242. SizedArray<BfIRValue, 16> interfaces;
  6243. for (auto& interface : typeInstance->mInterfaces)
  6244. {
  6245. SizedArray<BfIRValue, 8> interfaceDataVals =
  6246. {
  6247. emptyValueType,
  6248. GetConstValue(interface.mInterfaceType->mTypeId, typeIdType),
  6249. GetConstValue(interface.mStartInterfaceTableIdx, intType),
  6250. GetConstValue(interface.mStartVirtualIdx, intType),
  6251. };
  6252. auto interfaceData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectInterfaceDataType->ToTypeInstance(), BfIRPopulateType_Full), interfaceDataVals);
  6253. interfaces.push_back(interfaceData);
  6254. if (!mIsComptimeModule)
  6255. {
  6256. for (int methodIdx = 0; methodIdx < (int)interface.mInterfaceType->mMethodInstanceGroups.size(); methodIdx++)
  6257. {
  6258. auto ifaceMethodGroup = &interface.mInterfaceType->mMethodInstanceGroups[methodIdx];
  6259. if (ifaceMethodGroup->mExplicitlyReflected)
  6260. {
  6261. wantsIfaceMethods = true;
  6262. int tableIdx = interface.mStartInterfaceTableIdx + methodIdx;
  6263. while (tableIdx >= wantsIfaceMethod.size())
  6264. wantsIfaceMethod.Add(false);
  6265. wantsIfaceMethod[tableIdx] = true;
  6266. }
  6267. }
  6268. }
  6269. }
  6270. BfIRType interfaceDataArrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->MapType(reflectInterfaceDataType, BfIRPopulateType_Full), (int)interfaces.size());
  6271. BfIRValue interfaceDataConst = mBfIRBuilder->CreateConstAgg_Value(interfaceDataArrayType, interfaces);
  6272. BfIRValue interfaceDataArray = mBfIRBuilder->CreateGlobalVariable(interfaceDataArrayType, true, BfIRLinkageType_Internal,
  6273. interfaceDataConst, "interfaces." + typeDataName);
  6274. interfaceDataPtr = mBfIRBuilder->CreateBitCast(interfaceDataArray, interfaceDataPtrType);
  6275. interfaceCount = (int)interfaces.size();
  6276. }
  6277. BfIRValue interfaceMethodTable;
  6278. int ifaceMethodTableSize = 0;
  6279. if ((wantsIfaceMethods) && (!typeInstance->IsInterface()) && (typeInstance->mIsReified) && (!typeInstance->IsUnspecializedType())
  6280. && (!typeInstance->mInterfaceMethodTable.IsEmpty()))
  6281. {
  6282. SizedArray<BfIRValue, 16> methods;
  6283. for (int tableIdx = 0; tableIdx < (int)typeInstance->mInterfaceMethodTable.size(); tableIdx++)
  6284. {
  6285. BfIRValue funcVal = voidPtrNull;
  6286. if ((tableIdx < (int)wantsIfaceMethod.size()) && (wantsIfaceMethod[tableIdx]))
  6287. {
  6288. auto methodEntry = typeInstance->mInterfaceMethodTable[tableIdx];
  6289. if (!methodEntry.mMethodRef.IsNull())
  6290. {
  6291. BfMethodInstance* methodInstance = methodEntry.mMethodRef;
  6292. if ((methodInstance->mIsReified) && (methodInstance->mMethodInstanceGroup->IsImplemented()) && (!methodInstance->mIsUnspecialized) &&
  6293. (!methodInstance->mMethodDef->mIsAbstract))
  6294. {
  6295. auto moduleMethodInstance = ReferenceExternalMethodInstance(methodInstance);
  6296. if (moduleMethodInstance.mFunc)
  6297. funcVal = mBfIRBuilder->CreateBitCast(moduleMethodInstance.mFunc, voidPtrIRType);
  6298. }
  6299. }
  6300. }
  6301. methods.Add(funcVal);
  6302. }
  6303. while ((!methods.IsEmpty()) && (methods.back() == voidPtrNull))
  6304. methods.pop_back();
  6305. if (!methods.IsEmpty())
  6306. {
  6307. BfIRType methodDataArrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->MapType(voidPtrType, BfIRPopulateType_Full), (int)methods.size());
  6308. BfIRValue methodDataConst = mBfIRBuilder->CreateConstAgg_Value(methodDataArrayType, methods);
  6309. BfIRValue methodDataArray = mBfIRBuilder->CreateGlobalVariable(methodDataArrayType, true, BfIRLinkageType_Internal,
  6310. methodDataConst, "imethods." + typeDataName);
  6311. interfaceMethodTable = mBfIRBuilder->CreateBitCast(methodDataArray, voidPtrPtrIRType);
  6312. ifaceMethodTableSize = (int)methods.size();
  6313. }
  6314. }
  6315. if (!interfaceMethodTable)
  6316. interfaceMethodTable = mBfIRBuilder->CreateConstNull(voidPtrPtrIRType);
  6317. /////
  6318. int underlyingType = 0;
  6319. if ((typeInstance->IsTypedPrimitive()) || (typeInstance->IsBoxed()))
  6320. {
  6321. underlyingType = typeInstance->GetUnderlyingType()->mTypeId;
  6322. }
  6323. int outerTypeId = 0;
  6324. auto outerType = mContext->mUnreifiedModule->GetOuterType(typeInstance);
  6325. if (outerType != NULL)
  6326. {
  6327. outerTypeId = outerType->mTypeId;
  6328. }
  6329. //
  6330. BfIRValue customAttrDataPtr;
  6331. if (customAttrs.size() > 0)
  6332. {
  6333. BfIRType customAttrsArrayType = mBfIRBuilder->GetSizedArrayType(voidPtrIRType, (int)customAttrs.size());
  6334. BfIRValue customAttrsConst = mBfIRBuilder->CreateConstAgg_Value(customAttrsArrayType, customAttrs);
  6335. BfIRValue customAttrsArray = mBfIRBuilder->CreateGlobalVariable(customAttrsArrayType, true, BfIRLinkageType_Internal,
  6336. customAttrsConst, "customAttrs." + typeDataName);
  6337. customAttrDataPtr = mBfIRBuilder->CreateBitCast(customAttrsArray, voidPtrPtrIRType);
  6338. }
  6339. else
  6340. {
  6341. customAttrDataPtr = mBfIRBuilder->CreateConstNull(voidPtrPtrIRType);
  6342. }
  6343. SizedArray<BfIRValue, 32> typeDataVals =
  6344. {
  6345. typeData,
  6346. castedClassVData, // mTypeClassVData
  6347. typeNameConst, // mName
  6348. namespaceConst, // mNamespace
  6349. GetConstValue(typeInstance->mInstSize, intType), // mInstSize
  6350. GetConstValue(typeInstance->mInstAlign, intType), // mInstAlign
  6351. GetConstValue(typeCustomAttrIdx, intType), // mCustomAttributes
  6352. GetConstValue(baseTypeId, typeIdType), // mBaseType
  6353. GetConstValue(underlyingType, typeIdType), // mUnderlyingType
  6354. GetConstValue(outerTypeId, typeIdType), // mOuterType
  6355. GetConstValue(typeInstance->mInheritanceId, intType), // mInheritanceId
  6356. GetConstValue(typeInstance->mInheritanceCount, intType), // mInheritanceCount
  6357. GetConstValue(typeInstance->mSlotNum, byteType), // mInterfaceSlot
  6358. GetConstValue(interfaceCount, byteType), // mInterfaceCount
  6359. GetConstValue(ifaceMethodTableSize, shortType), // mInterfaceMethodCount
  6360. GetConstValue((int)methodTypes.size(), shortType), // mMethodDataCount
  6361. GetConstValue(0, shortType), // mPropertyDataCount
  6362. GetConstValue((int)fieldTypes.size(), shortType), // mFieldDataCount
  6363. interfaceDataPtr, // mInterfaceDataPtr
  6364. interfaceMethodTable, // mInterfaceMethodTable
  6365. methodDataPtr, // mMethodDataPtr
  6366. voidPtrNull, // mPropertyDataPtr
  6367. fieldDataPtr, // mFieldDataPtr
  6368. customAttrDataPtr, // mCustomAttrDataPtr
  6369. };
  6370. BfIRType typeInstanceDataType = mBfIRBuilder->MapTypeInst(typeInstanceType->ToTypeInstance(), BfIRPopulateType_Full);
  6371. FixConstValueParams(typeInstanceType->ToTypeInstance(), typeDataVals);
  6372. auto typeInstanceData = mBfIRBuilder->CreateConstAgg_Value(typeInstanceDataType, typeDataVals);
  6373. if (!needsTypeData)
  6374. {
  6375. // No need for anything beyond typeInstanceData
  6376. }
  6377. else if ((typeInstance->IsGenericTypeInstance()) && (typeInstance->IsUnspecializedType()))
  6378. {
  6379. auto genericTypeInstance = typeInstance->ToGenericTypeInstance();
  6380. SizedArray<BfIRValue, 4> unspecializedData =
  6381. {
  6382. typeInstanceData,
  6383. GetConstValue((int)genericTypeInstance->mGenericTypeInfo->mTypeGenericArguments.size(), byteType), // mGenericParamCount
  6384. };
  6385. auto reflectUnspecializedGenericType = ResolveTypeDef(mCompiler->mReflectUnspecializedGenericType);
  6386. typeInstanceDataType = mBfIRBuilder->MapTypeInst(reflectUnspecializedGenericType->ToTypeInstance(), BfIRPopulateType_Full);
  6387. typeInstanceData = mBfIRBuilder->CreateConstAgg_Value(typeInstanceDataType, unspecializedData);
  6388. }
  6389. else if (typeInstance->IsGenericTypeInstance())
  6390. {
  6391. auto genericTypeInstance = typeInstance->ToGenericTypeInstance();
  6392. auto reflectSpecializedGenericType = ResolveTypeDef(mCompiler->mReflectSpecializedGenericType);
  6393. auto unspecializedType = ResolveTypeDef(typeInstance->mTypeDef->GetDefinition());
  6394. SizedArray<BfIRValue, 4> resolvedTypes;
  6395. for (auto typeGenericArg : genericTypeInstance->mGenericTypeInfo->mTypeGenericArguments)
  6396. resolvedTypes.push_back(GetConstValue(typeGenericArg->mTypeId, typeIdType));
  6397. auto typeIRType = mBfIRBuilder->MapType(typeIdType);
  6398. auto typePtrIRType = mBfIRBuilder->GetPointerTo(typeIRType);
  6399. auto genericArrayType = mBfIRBuilder->GetSizedArrayType(typeIRType, (int)resolvedTypes.size());
  6400. BfIRValue resolvedTypesConst = mBfIRBuilder->CreateConstAgg_Value(genericArrayType, resolvedTypes);
  6401. BfIRValue resolvedTypesArray = mBfIRBuilder->CreateGlobalVariable(genericArrayType, true, BfIRLinkageType_Internal,
  6402. resolvedTypesConst, "resolvedTypes." + typeDataName);
  6403. BfIRValue resovledTypesPtr = mBfIRBuilder->CreateBitCast(resolvedTypesArray, typePtrIRType);
  6404. SizedArray<BfIRValue, 3> specGenericData =
  6405. {
  6406. typeInstanceData,
  6407. GetConstValue(unspecializedType->mTypeId, typeIdType), // mUnspecialziedType
  6408. resovledTypesPtr, // mFieldDataPtr
  6409. };
  6410. typeInstanceDataType = mBfIRBuilder->MapTypeInst(reflectSpecializedGenericType->ToTypeInstance(), BfIRPopulateType_Full);
  6411. typeInstanceData = mBfIRBuilder->CreateConstAgg_Value(typeInstanceDataType, specGenericData);
  6412. if (typeInstance->IsArray())
  6413. {
  6414. auto arrayType = (BfArrayType*)typeInstance;
  6415. BfType* elementType = genericTypeInstance->mGenericTypeInfo->mTypeGenericArguments[0];
  6416. BfFieldInstance* elementFieldInstance = &genericTypeInstance->mFieldInstances[0];
  6417. SizedArray<BfIRValue, 4> arrayData =
  6418. {
  6419. typeInstanceData,
  6420. GetConstValue(elementType->mSize, intType), // mElementSize
  6421. GetConstValue(1, byteType), // mRank
  6422. GetConstValue(elementFieldInstance->mDataOffset, byteType), // mElementsDataOffset
  6423. };
  6424. auto reflectArrayType = ResolveTypeDef(mCompiler->mReflectArrayType);
  6425. typeInstanceDataType = mBfIRBuilder->MapTypeInst(reflectArrayType->ToTypeInstance(), BfIRPopulateType_Full);
  6426. typeInstanceData = mBfIRBuilder->CreateConstAgg_Value(typeInstanceDataType, arrayData);
  6427. }
  6428. }
  6429. BfIRValue typeDataVar;
  6430. if (needsTypeData)
  6431. {
  6432. typeDataVar = mBfIRBuilder->CreateGlobalVariable(typeInstanceDataType, true,
  6433. BfIRLinkageType_External, typeInstanceData, typeDataName);
  6434. mBfIRBuilder->GlobalVar_SetAlignment(typeDataVar, mSystem->mPtrSize);
  6435. if (mBfIRBuilder->DbgHasInfo())
  6436. {
  6437. mBfIRBuilder->DbgCreateGlobalVariable(mDICompileUnit, typeDataName, typeDataName, BfIRMDNode(), 0, mBfIRBuilder->DbgGetTypeInst(typeInstanceType->ToTypeInstance()), false, typeDataVar);
  6438. }
  6439. }
  6440. else
  6441. {
  6442. typeDataVar = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(mContext->mBfTypeType));
  6443. }
  6444. typeDataVar = mBfIRBuilder->CreateBitCast(typeDataVar, mBfIRBuilder->MapType(mContext->mBfTypeType));
  6445. mTypeDataRefs[typeInstance] = typeDataVar;
  6446. if ((!mIsComptimeModule) && (classVDataVar))
  6447. {
  6448. BF_ASSERT(!classVDataName.IsEmpty());
  6449. vData[0] = mBfIRBuilder->CreateBitCast(typeDataVar, voidPtrIRType);
  6450. auto classVDataConstDataType = mBfIRBuilder->GetSizedArrayType(voidPtrIRType, (int)vData.size());
  6451. auto classVDataConstData = mBfIRBuilder->CreateConstAgg_Value(classVDataConstDataType, vData);
  6452. mBfIRBuilder->GlobalVar_SetInitializer(classVDataVar, classVDataConstData);
  6453. if (mCompiler->mOptions.mObjectHasDebugFlags)
  6454. mBfIRBuilder->GlobalVar_SetAlignment(classVDataVar, 256);
  6455. else
  6456. mBfIRBuilder->GlobalVar_SetAlignment(classVDataVar, mContext->mBfClassVDataPtrType->mAlign);
  6457. if (mBfIRBuilder->DbgHasInfo())
  6458. {
  6459. BfType* voidType = GetPrimitiveType(BfTypeCode_None);
  6460. BfType* voidPtrType = CreatePointerType(voidType);
  6461. BfType* classVDataType = ResolveTypeDef(mCompiler->mClassVDataTypeDef);
  6462. BfIRMDNode arrayType = mBfIRBuilder->DbgCreateArrayType(vData.size() * mSystem->mPtrSize * 8, mSystem->mPtrSize * 8, mBfIRBuilder->DbgGetType(voidPtrType), vData.size());
  6463. mBfIRBuilder->DbgCreateGlobalVariable(mDICompileUnit, classVDataName, classVDataName, BfIRMDNode(), 0, arrayType, false, classVDataVar);
  6464. }
  6465. }
  6466. return typeDataVar;
  6467. }
  6468. BfIRValue BfModule::FixClassVData(BfIRValue value)
  6469. {
  6470. if ((!mCompiler->mOptions.mObjectHasDebugFlags) || (mIsComptimeModule))
  6471. return value;
  6472. auto intptrValue = mBfIRBuilder->CreatePtrToInt(value, BfTypeCode_IntPtr);
  6473. auto maskedValue = mBfIRBuilder->CreateAnd(intptrValue, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, (uint64)~0xFFULL));
  6474. return mBfIRBuilder->CreateIntToPtr(maskedValue, mBfIRBuilder->GetType(value));
  6475. }
  6476. void BfModule::CheckStaticAccess(BfTypeInstance* typeInstance)
  6477. {
  6478. // Note: this is not just for perf, it fixes a field var-type resolution issue
  6479. if (mBfIRBuilder->mIgnoreWrites)
  6480. return;
  6481. if (mIsComptimeModule)
  6482. return;
  6483. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  6484. //TODO: Create a hashset of these, we don't need to repeatedly call static ctors for a given type
  6485. // When we access classes with static constructors FROM a static constructor,
  6486. // we call that other class's static constructor first. Recursion cannot occur, since
  6487. // we simply ignore subsequent attempts to re-enter the constructor
  6488. if (!typeInstance->mHasStaticInitMethod)
  6489. return;
  6490. if ((mCurMethodInstance == NULL) || ((mCurMethodInstance->mMethodDef->mMethodType != BfMethodType_Ctor) || (!mCurMethodInstance->mMethodDef->mIsStatic)))
  6491. return;
  6492. if (mCurMethodInstance->mMethodInstanceGroup->mOwner == typeInstance)
  6493. return;
  6494. auto checkTypeDef = typeInstance->mTypeDef;
  6495. checkTypeDef->PopulateMemberSets();
  6496. BfMethodDef* nextMethodDef = NULL;
  6497. BfMemberSetEntry* entry;
  6498. if (checkTypeDef->mMethodSet.TryGetWith(String("__BfStaticCtor"), &entry))
  6499. nextMethodDef = (BfMethodDef*)entry->mMemberDef;
  6500. while (nextMethodDef != NULL)
  6501. {
  6502. auto checkMethod = nextMethodDef;
  6503. nextMethodDef = nextMethodDef->mNextWithSameName;
  6504. auto methodModule = GetMethodInstance(typeInstance, checkMethod, BfTypeVector());
  6505. if (methodModule)
  6506. {
  6507. auto methodInstance = methodModule.mMethodInstance;
  6508. if ((methodInstance != NULL) &&
  6509. (methodInstance->mMethodDef->mIsStatic) &&
  6510. (methodInstance->mMethodDef->mMethodType == BfMethodType_Ctor) &&
  6511. ((methodInstance->mChainType == BfMethodChainType_ChainHead) || (methodInstance->mChainType == BfMethodChainType_None)))
  6512. {
  6513. mBfIRBuilder->CreateCall(methodModule.mFunc, SizedArray<BfIRValue, 0>());
  6514. break;
  6515. }
  6516. }
  6517. }
  6518. }
  6519. BfIRFunction BfModule::GetIntrinsic(BfMethodInstance* methodInstance, bool reportFailure)
  6520. {
  6521. auto methodOwner = methodInstance->GetOwner();
  6522. auto methodDef = methodInstance->mMethodDef;
  6523. auto methodDeclaration = methodDef->GetMethodDeclaration();
  6524. if (!methodDef->mIsExtern)
  6525. return BfIRFunction();
  6526. if (methodInstance->GetCustomAttributes() == NULL)
  6527. return BfIRFunction();
  6528. for (auto& customAttribute : methodInstance->GetCustomAttributes()->mAttributes)
  6529. {
  6530. String typeName = TypeToString(customAttribute.mType);
  6531. if ((typeName == "System.IntrinsicAttribute") && (customAttribute.mCtorArgs.size() > 0))
  6532. {
  6533. methodInstance->mIsIntrinsic = true;
  6534. auto constant = methodOwner->mConstHolder->GetConstant(customAttribute.mCtorArgs[0]);
  6535. String error;
  6536. if ((constant != NULL) && (constant->mTypeCode == BfTypeCode_StringId))
  6537. {
  6538. int stringId = constant->mInt32;
  6539. auto entry = mContext->mStringObjectIdMap[stringId];
  6540. String intrinName = entry.mString;
  6541. // if (intrinName.StartsWith(":"))
  6542. // {
  6543. // SizedArray<BfIRType, 2> paramTypes;
  6544. // for (auto& param : methodInstance->mParams)
  6545. // paramTypes.push_back(mBfIRBuilder->MapType(param.mResolvedType));
  6546. // return mBfIRBuilder->GetIntrinsic(intrinName.Substring(1), mBfIRBuilder->MapType(methodInstance->mReturnType), paramTypes);
  6547. // }
  6548. // else
  6549. {
  6550. int intrinId = BfIRCodeGen::GetIntrinsicId(intrinName);
  6551. if (intrinId != -1)
  6552. {
  6553. if (intrinId == BfIRIntrinsic_Malloc)
  6554. {
  6555. return GetBuiltInFunc(BfBuiltInFuncType_Malloc);
  6556. }
  6557. else if (intrinId == BfIRIntrinsic_Free)
  6558. {
  6559. return GetBuiltInFunc(BfBuiltInFuncType_Free);
  6560. }
  6561. SizedArray<BfIRType, 2> paramTypes;
  6562. for (auto& param : methodInstance->mParams)
  6563. paramTypes.push_back(mBfIRBuilder->MapType(param.mResolvedType));
  6564. return mBfIRBuilder->GetIntrinsic(intrinName, intrinId, mBfIRBuilder->MapType(methodInstance->mReturnType), paramTypes);
  6565. }
  6566. else if (reportFailure)
  6567. error = StrFormat("Unable to find intrinsic '%s'", entry.mString.c_str());
  6568. }
  6569. }
  6570. else if (reportFailure)
  6571. error = "Intrinsic name must be a constant string";
  6572. if (reportFailure)
  6573. {
  6574. Fail(error, customAttribute.mRef);
  6575. }
  6576. }
  6577. }
  6578. return BfIRFunction();
  6579. }
  6580. BfIRFunction BfModule::GetBuiltInFunc(BfBuiltInFuncType funcTypeId)
  6581. {
  6582. if (mBfIRBuilder->mIgnoreWrites)
  6583. return mBfIRBuilder->GetFakeFunction();
  6584. if (!mBuiltInFuncs[(int)funcTypeId])
  6585. {
  6586. SizedArray<BfIRType, 4> paramTypes;
  6587. auto nullPtrType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr));
  6588. auto intType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_IntPtr));
  6589. auto int32Type = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_Int32));
  6590. auto intPtrType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_IntPtr));
  6591. auto byteType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_Int8));
  6592. auto voidType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_None));
  6593. auto objType = mBfIRBuilder->MapType(mContext->mBfObjectType);
  6594. BfIRFunctionType funcType;
  6595. BfIRFunction func;
  6596. switch (funcTypeId)
  6597. {
  6598. case BfBuiltInFuncType_PrintF:
  6599. paramTypes.Add(nullPtrType);
  6600. funcType = mBfIRBuilder->CreateFunctionType(int32Type, paramTypes, true);
  6601. func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, "PrintF");
  6602. break;
  6603. case BfBuiltInFuncType_Malloc:
  6604. {
  6605. if ((mCompiler->mOptions.mDebugAlloc) && (!mIsComptimeModule))
  6606. {
  6607. func = GetInternalMethod("Dbg_RawAlloc", 1).mFunc;
  6608. }
  6609. else
  6610. {
  6611. String funcName = mCompiler->mOptions.mMallocLinkName;
  6612. if (funcName.IsEmpty())
  6613. funcName = "malloc";
  6614. func = mBfIRBuilder->GetFunction(funcName);
  6615. if (!func)
  6616. {
  6617. paramTypes.clear();
  6618. paramTypes.push_back(intType);
  6619. funcType = mBfIRBuilder->CreateFunctionType(nullPtrType, paramTypes);
  6620. func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, funcName);
  6621. mBfIRBuilder->Func_SetParamName(func, 1, "size");
  6622. }
  6623. }
  6624. }
  6625. break;
  6626. case BfBuiltInFuncType_Free:
  6627. {
  6628. if ((mCompiler->mOptions.mDebugAlloc) && (!mIsComptimeModule))
  6629. {
  6630. func = GetInternalMethod("Dbg_RawFree").mFunc;
  6631. }
  6632. else
  6633. {
  6634. String funcName = mCompiler->mOptions.mFreeLinkName;
  6635. if (funcName.IsEmpty())
  6636. funcName = "free";
  6637. func = mBfIRBuilder->GetFunction(funcName);
  6638. if (!func)
  6639. {
  6640. paramTypes.clear();
  6641. paramTypes.push_back(nullPtrType);
  6642. funcType = mBfIRBuilder->CreateFunctionType(voidType, paramTypes);
  6643. func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, funcName);
  6644. mBfIRBuilder->Func_SetParamName(func, 1, "ptr");
  6645. }
  6646. }
  6647. }
  6648. break;
  6649. case BfBuiltInFuncType_LoadSharedLibraries:
  6650. paramTypes.clear();
  6651. funcType = mBfIRBuilder->CreateFunctionType(voidType, paramTypes);
  6652. func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, "BfLoadSharedLibraries");
  6653. break;
  6654. default: break;
  6655. }
  6656. mBuiltInFuncs[(int)funcTypeId] = func;
  6657. return func;
  6658. }
  6659. return mBuiltInFuncs[(int)funcTypeId];
  6660. }
  6661. void BfModule::ResolveGenericParamConstraints(BfGenericParamInstance* genericParamInstance, bool isUnspecialized, Array<BfTypeReference*>* deferredResolveTypes)
  6662. {
  6663. BfGenericParamDef* genericParamDef = genericParamInstance->GetGenericParamDef();
  6664. BfExternalConstraintDef* externConstraintDef = genericParamInstance->GetExternConstraintDef();
  6665. BfConstraintDef* constraintDef = genericParamInstance->GetConstraintDef();
  6666. BfType* startingTypeConstraint = genericParamInstance->mTypeConstraint;
  6667. BfAutoComplete* bfAutocomplete = NULL;
  6668. if ((mCompiler->mResolvePassData != NULL) && (isUnspecialized))
  6669. bfAutocomplete = mCompiler->mResolvePassData->mAutoComplete;
  6670. if ((bfAutocomplete != NULL) && (genericParamDef != NULL))
  6671. {
  6672. for (int nameIdx = 0; nameIdx < (int)genericParamDef->mNameNodes.size(); nameIdx++)
  6673. {
  6674. auto nameNode = genericParamDef->mNameNodes[nameIdx];
  6675. if (bfAutocomplete->IsAutocompleteNode(nameNode))
  6676. {
  6677. String filter = nameNode->ToString();
  6678. bfAutocomplete->mInsertStartIdx = nameNode->GetSrcStart();
  6679. bfAutocomplete->mInsertEndIdx = nameNode->GetSrcEnd();
  6680. if (nameIdx != 0)
  6681. {
  6682. bfAutocomplete->AddEntry(AutoCompleteEntry("generic", nameNode->ToString().c_str()), filter);
  6683. }
  6684. }
  6685. }
  6686. }
  6687. for (auto constraint : constraintDef->mConstraints)
  6688. {
  6689. if (auto opConstraint = BfNodeDynCast<BfGenericOperatorConstraint>(constraint))
  6690. {
  6691. BfGenericOperatorConstraintInstance opConstraintInstance;
  6692. if (opConstraint->mLeftType != NULL)
  6693. {
  6694. if (bfAutocomplete != NULL)
  6695. bfAutocomplete->CheckTypeRef(opConstraint->mLeftType, false);
  6696. opConstraintInstance.mLeftType = ResolveTypeRef(opConstraint->mLeftType, BfPopulateType_Interfaces);
  6697. if (opConstraintInstance.mLeftType == NULL)
  6698. continue;
  6699. }
  6700. if (opConstraint->mRightType == NULL)
  6701. {
  6702. // We had a failure in parsing
  6703. continue;
  6704. }
  6705. if (opConstraint->mRightType != NULL)
  6706. {
  6707. if (bfAutocomplete != NULL)
  6708. bfAutocomplete->CheckTypeRef(opConstraint->mRightType, false);
  6709. opConstraintInstance.mRightType = ResolveTypeRef(opConstraint->mRightType, BfPopulateType_Interfaces);
  6710. if (opConstraintInstance.mRightType == NULL)
  6711. continue;
  6712. }
  6713. if (opConstraint->mOpToken == NULL)
  6714. {
  6715. FailAfter("Missing operator", (opConstraint->mLeftType != NULL) ? (BfAstNode*)opConstraint->mLeftType : (BfAstNode*)opConstraint->mOperatorToken);
  6716. continue;
  6717. }
  6718. if (opConstraint->mLeftType != NULL)
  6719. {
  6720. if (opConstraint->mRightType == NULL)
  6721. {
  6722. // Parse should have failed
  6723. continue;
  6724. }
  6725. opConstraintInstance.mBinaryOp = BfTokenToBinaryOp(opConstraint->mOpToken->mToken);
  6726. if (opConstraintInstance.mBinaryOp == BfBinaryOp_None)
  6727. {
  6728. Fail("Invalid binary operator", opConstraint->mOpToken);
  6729. continue;
  6730. }
  6731. }
  6732. else if ((opConstraint->mOpToken->mToken == BfToken_Implicit) || (opConstraint->mOpToken->mToken == BfToken_Explicit))
  6733. {
  6734. opConstraintInstance.mCastToken = opConstraint->mOpToken->mToken;
  6735. }
  6736. else
  6737. {
  6738. opConstraintInstance.mUnaryOp = BfTokenToUnaryOp(opConstraint->mOpToken->mToken);
  6739. if (opConstraintInstance.mUnaryOp == BfUnaryOp_None)
  6740. {
  6741. Fail("Invalid unary operator", opConstraint->mOpToken);
  6742. continue;
  6743. }
  6744. }
  6745. genericParamInstance->mOperatorConstraints.Add(opConstraintInstance);
  6746. continue;
  6747. }
  6748. auto constraintTypeRef = BfNodeDynCast<BfTypeReference>(constraint);
  6749. if (bfAutocomplete != NULL)
  6750. bfAutocomplete->CheckTypeRef(constraintTypeRef, true);
  6751. //TODO: Constraints may refer to other generic params (of either type or method)
  6752. // TO allow resolution, perhaps move this generic param initialization into GetMethodInstance (passing a genericPass bool)
  6753. BfResolveTypeRefFlags resolveFlags = BfResolveTypeRefFlag_AllowGenericMethodParamConstValue;
  6754. if (isUnspecialized)
  6755. resolveFlags = (BfResolveTypeRefFlags)(resolveFlags | BfResolveTypeRefFlag_DisallowComptime);
  6756. // We we have a deferredResolveTypes then we defer the generic validation, because we may have a case like
  6757. // `where T : Dictionay<TElem, int> and TElem : IHashable` and we don't want to throw the error on `T` before we build `TElem`
  6758. auto constraintType = ResolveTypeRef(constraintTypeRef, (deferredResolveTypes != NULL) ? BfPopulateType_Identity : BfPopulateType_Declaration, resolveFlags);
  6759. if (constraintType != NULL)
  6760. {
  6761. if (deferredResolveTypes != NULL)
  6762. {
  6763. PopulateType(constraintType, BfPopulateType_Declaration);
  6764. if (constraintType->IsUnspecializedTypeVariation())
  6765. deferredResolveTypes->Add(constraintTypeRef);
  6766. }
  6767. if ((constraintDef->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  6768. {
  6769. bool isValidTypeCode = false;
  6770. BfTypeCode typeCode = BfTypeCode_None;
  6771. if (constraintType->IsTypedPrimitive())
  6772. {
  6773. auto underlyingType = constraintType->GetUnderlyingType();
  6774. if (underlyingType->IsPrimitiveType())
  6775. typeCode = ((BfPrimitiveType*)underlyingType)->mTypeDef->mTypeCode;
  6776. }
  6777. if (constraintType->IsPrimitiveType())
  6778. typeCode = ((BfPrimitiveType*)constraintType)->mTypeDef->mTypeCode;
  6779. if (constraintType->IsInstanceOf(mCompiler->mStringTypeDef))
  6780. isValidTypeCode = true;
  6781. switch (typeCode)
  6782. {
  6783. case BfTypeCode_StringId:
  6784. case BfTypeCode_Boolean:
  6785. case BfTypeCode_Int8:
  6786. case BfTypeCode_UInt8:
  6787. case BfTypeCode_Int16:
  6788. case BfTypeCode_UInt16:
  6789. case BfTypeCode_Int32:
  6790. case BfTypeCode_UInt32:
  6791. case BfTypeCode_Int64:
  6792. case BfTypeCode_UInt64:
  6793. case BfTypeCode_IntPtr:
  6794. case BfTypeCode_UIntPtr:
  6795. case BfTypeCode_IntUnknown:
  6796. case BfTypeCode_UIntUnknown:
  6797. case BfTypeCode_Float:
  6798. case BfTypeCode_Double:
  6799. case BfTypeCode_Char8:
  6800. case BfTypeCode_Char16:
  6801. case BfTypeCode_Char32:
  6802. isValidTypeCode = true;
  6803. break;
  6804. default: break;
  6805. }
  6806. if (isValidTypeCode)
  6807. {
  6808. genericParamInstance->mTypeConstraint = constraintType;
  6809. }
  6810. else
  6811. {
  6812. Fail("Const constraint must be a primitive type", constraintTypeRef);
  6813. }
  6814. }
  6815. else
  6816. {
  6817. bool checkEquality = false;
  6818. if (constraintType->IsVar())
  6819. {
  6820. // From a `comptype` generic undef resolution. Ignore.
  6821. genericParamInstance->mGenericParamFlags = (BfGenericParamFlags)(genericParamInstance->mGenericParamFlags | BfGenericParamFlag_ComptypeExpr);
  6822. genericParamInstance->mComptypeConstraint.Add(constraintTypeRef);
  6823. continue;
  6824. }
  6825. else if (constraintType->IsPrimitiveType())
  6826. {
  6827. if (isUnspecialized)
  6828. {
  6829. Fail("Primitive constraints are not allowed unless preceded with 'const'", constraintTypeRef);
  6830. continue;
  6831. }
  6832. checkEquality = true;
  6833. }
  6834. if (constraintType->IsArray())
  6835. {
  6836. if (isUnspecialized)
  6837. {
  6838. 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);
  6839. continue;
  6840. }
  6841. checkEquality = true;
  6842. }
  6843. if (constraintType->IsGenericParam())
  6844. {
  6845. checkEquality = true;
  6846. }
  6847. else if ((!constraintType->IsTypeInstance()) && (!constraintType->IsSizedArray()))
  6848. {
  6849. if (isUnspecialized)
  6850. {
  6851. Fail(StrFormat("Type '%s' is not allowed as a generic constraint", TypeToString(constraintType).c_str()), constraintTypeRef);
  6852. continue;
  6853. }
  6854. checkEquality = true;
  6855. }
  6856. if (checkEquality)
  6857. {
  6858. genericParamInstance->mTypeConstraint = constraintType;
  6859. }
  6860. else if (constraintType->IsInterface())
  6861. {
  6862. genericParamInstance->mInterfaceConstraints.push_back(constraintType->ToTypeInstance());
  6863. }
  6864. else
  6865. {
  6866. auto constraintTypeInst = constraintType->ToTypeInstance();
  6867. if (genericParamInstance->mTypeConstraint != NULL)
  6868. {
  6869. if ((constraintTypeInst != NULL) && (TypeIsSubTypeOf(constraintTypeInst, genericParamInstance->mTypeConstraint->ToTypeInstance(), false)))
  6870. {
  6871. // Allow more specific type
  6872. genericParamInstance->mTypeConstraint = constraintTypeInst;
  6873. }
  6874. else if ((constraintTypeInst != NULL) && (TypeIsSubTypeOf(genericParamInstance->mTypeConstraint->ToTypeInstance(), constraintTypeInst, false)))
  6875. {
  6876. // Silently ignore less-specific type
  6877. if ((startingTypeConstraint != NULL) && (startingTypeConstraint->IsDelegate()))
  6878. {
  6879. // 'System.Delegate' means that we are expecting an actual delegate instance. Simulate this by wanting a class.
  6880. genericParamInstance->mGenericParamFlags = (BfGenericParamFlags)(genericParamInstance->mGenericParamFlags | BfGenericParamFlag_Class);
  6881. }
  6882. }
  6883. else
  6884. {
  6885. Fail("Only one concrete type constraint may be specified", constraintTypeRef);
  6886. return;
  6887. }
  6888. }
  6889. else
  6890. genericParamInstance->mTypeConstraint = constraintType;
  6891. }
  6892. }
  6893. }
  6894. }
  6895. if (((constraintDef->mGenericParamFlags & BfGenericParamFlag_Const) != 0) &&
  6896. (genericParamInstance->mTypeConstraint == NULL))
  6897. genericParamInstance->mTypeConstraint = GetPrimitiveType(BfTypeCode_IntPtr);
  6898. }
  6899. String BfModule::GenericParamSourceToString(const BfGenericParamSource & genericParamSource)
  6900. {
  6901. if (genericParamSource.mMethodInstance != NULL)
  6902. {
  6903. //auto methodInst = GetUnspecializedMethodInstance(genericParamSource.mMethodInstance, false);
  6904. //SetAndRestoreValue<BfMethodInstance*> prevMethodInst(mCurMethodInstance, methodInst);
  6905. return MethodToString(genericParamSource.mMethodInstance);
  6906. }
  6907. else
  6908. {
  6909. auto typeInst = GetUnspecializedTypeInstance(genericParamSource.mTypeInstance);
  6910. SetAndRestoreValue<BfMethodInstance*> prevMethodInst(mCurMethodInstance, NULL);
  6911. SetAndRestoreValue<BfTypeInstance*> prevTypeInst(mCurTypeInstance, typeInst);
  6912. return TypeToString(typeInst);
  6913. }
  6914. }
  6915. bool BfModule::CheckGenericConstraints(const BfGenericParamSource& genericParamSource, BfType* checkArgType, BfAstNode* checkArgTypeRef, BfGenericParamInstance* genericParamInst, BfTypeVector* methodGenericArgs, BfError** errorOut)
  6916. {
  6917. Array<String> methodParamNameOverrides;
  6918. auto _TypeToString = [&](BfType* type)
  6919. {
  6920. if (genericParamSource.mMethodInstance != NULL)
  6921. {
  6922. if (methodParamNameOverrides.IsEmpty())
  6923. {
  6924. for (auto genericParam : genericParamSource.mMethodInstance->mMethodDef->mGenericParams)
  6925. methodParamNameOverrides.Add(genericParam->mName);
  6926. }
  6927. return TypeToString(type, &methodParamNameOverrides);
  6928. }
  6929. return TypeToString(type);
  6930. };
  6931. bool ignoreErrors = (errorOut == NULL) ||
  6932. ((genericParamSource.mMethodInstance == NULL) && (genericParamSource.mTypeInstance == NULL));
  6933. BfType* origCheckArgType = checkArgType;
  6934. if (origCheckArgType->IsRef())
  6935. origCheckArgType = origCheckArgType->GetUnderlyingType();
  6936. bool argIsReferenceType = false;
  6937. int checkGenericParamFlags = 0;
  6938. if (checkArgType->IsGenericParam())
  6939. {
  6940. BfGenericParamInstance* checkGenericParamInst = GetGenericParamInstance((BfGenericParamType*)checkArgType);
  6941. checkGenericParamFlags = checkGenericParamInst->mGenericParamFlags;
  6942. if (checkGenericParamInst->mTypeConstraint != NULL)
  6943. checkArgType = checkGenericParamInst->mTypeConstraint;
  6944. // if ((checkGenericParamFlags & (BfGenericParamFlag_Struct | BfGenericParamFlag_StructPtr)) != 0)
  6945. // {
  6946. // argMayBeReferenceType = false;
  6947. // }
  6948. // else
  6949. // {
  6950. // argMayBeReferenceType = true;
  6951. // }
  6952. }
  6953. if (checkArgType->IsObjectOrInterface())
  6954. argIsReferenceType = true;
  6955. BfTypeInstance* typeConstraintInst = NULL;
  6956. if (genericParamInst->mTypeConstraint != NULL)
  6957. typeConstraintInst = genericParamInst->mTypeConstraint->ToTypeInstance();
  6958. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Struct) &&
  6959. ((checkGenericParamFlags & (BfGenericParamFlag_Struct | BfGenericParamFlag_Enum | BfGenericParamFlag_Var)) == 0) && (!checkArgType->IsValueType()))
  6960. {
  6961. if ((!ignoreErrors) && (PreFail()))
  6962. *errorOut = Fail(StrFormat("The type '%s' must be a value type in order to use it as parameter '%s' for '%s'",
  6963. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  6964. return false;
  6965. }
  6966. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_StructPtr) &&
  6967. ((checkGenericParamFlags & (BfGenericParamFlag_StructPtr | BfGenericParamFlag_Var)) == 0) && (!checkArgType->IsPointer()))
  6968. {
  6969. if ((!ignoreErrors) && (PreFail()))
  6970. *errorOut = Fail(StrFormat("The type '%s' must be a pointer type in order to use it as parameter '%s' for '%s'",
  6971. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  6972. return false;
  6973. }
  6974. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Class) &&
  6975. ((checkGenericParamFlags & (BfGenericParamFlag_Class | BfGenericParamFlag_Var)) == 0) && (!argIsReferenceType))
  6976. {
  6977. if ((!ignoreErrors) && (PreFail()))
  6978. *errorOut = Fail(StrFormat("The type '%s' must be a reference type in order to use it as parameter '%s' for '%s'",
  6979. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  6980. return false;
  6981. }
  6982. if (genericParamInst->mGenericParamFlags & BfGenericParamFlag_Enum)
  6983. {
  6984. bool isEnum = checkArgType->IsEnum();
  6985. if ((origCheckArgType->IsGenericParam()) && (checkArgType->IsInstanceOf(mCompiler->mEnumTypeDef)))
  6986. isEnum = true;
  6987. if (((checkGenericParamFlags & (BfGenericParamFlag_Enum | BfGenericParamFlag_Var)) == 0) && (!isEnum))
  6988. {
  6989. if ((!ignoreErrors) && (PreFail()))
  6990. *errorOut = Fail(StrFormat("The type '%s' must be an enum type in order to use it as parameter '%s' for '%s'",
  6991. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  6992. return false;
  6993. }
  6994. }
  6995. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Concrete) &&
  6996. ((checkGenericParamFlags & (BfGenericParamFlag_Interface | BfGenericParamFlag_Var)) == 0) && (checkArgType->IsInterface()))
  6997. {
  6998. if ((!ignoreErrors) && (PreFail()))
  6999. *errorOut = Fail(StrFormat("The type '%s' must be an concrete type in order to use it as parameter '%s' for '%s'",
  7000. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7001. return false;
  7002. }
  7003. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Interface) &&
  7004. ((checkGenericParamFlags & (BfGenericParamFlag_Interface | BfGenericParamFlag_Var)) == 0) && (!checkArgType->IsInterface()))
  7005. {
  7006. if ((!ignoreErrors) && (PreFail()))
  7007. *errorOut = Fail(StrFormat("The type '%s' must be an interface type in order to use it as parameter '%s' for '%s'",
  7008. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7009. return false;
  7010. }
  7011. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  7012. {
  7013. if (((checkGenericParamFlags & BfGenericParamFlag_Const) == 0) && (!checkArgType->IsConstExprValue()))
  7014. {
  7015. if ((!ignoreErrors) && (PreFail()))
  7016. *errorOut = Fail(StrFormat("The type '%s' must be a const value in order to use it as parameter '%s' for '%s'",
  7017. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7018. return false;
  7019. }
  7020. }
  7021. else
  7022. {
  7023. if (checkArgType->IsConstExprValue())
  7024. {
  7025. if ((!ignoreErrors) && (PreFail()))
  7026. *errorOut = Fail(StrFormat("The value '%s' cannot be used for generic type parameter '%s' for '%s'",
  7027. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7028. return false;
  7029. }
  7030. }
  7031. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Delete) != 0)
  7032. {
  7033. bool canDelete = false;
  7034. if (checkArgType->IsPointer())
  7035. canDelete = true;
  7036. else if (checkArgType->IsObjectOrInterface())
  7037. canDelete = true;
  7038. else if ((checkGenericParamFlags & (BfGenericParamFlag_Delete | BfGenericParamFlag_Var)) != 0)
  7039. canDelete = true;
  7040. if (!canDelete)
  7041. {
  7042. if ((!ignoreErrors) && (PreFail()))
  7043. {
  7044. if (checkArgType->IsGenericParam())
  7045. *errorOut = Fail(StrFormat("Must add 'where %s : delete' constraint in order to use type as parameter '%s' for '%s'",
  7046. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7047. else
  7048. *errorOut = Fail(StrFormat("The type '%s' must be a deletable type in order to use it as parameter '%s' for '%s'",
  7049. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7050. }
  7051. return false;
  7052. }
  7053. }
  7054. if (checkArgType->IsPointer())
  7055. {
  7056. auto ptrType = (BfPointerType*)checkArgType;
  7057. checkArgType = ptrType->mElementType;
  7058. }
  7059. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_New) != 0)
  7060. {
  7061. bool canAlloc = false;
  7062. if (auto checkTypeInst = checkArgType->ToTypeInstance())
  7063. {
  7064. if (checkTypeInst->IsObjectOrStruct())
  7065. {
  7066. checkTypeInst->mTypeDef->PopulateMemberSets();
  7067. BfMemberSetEntry* entry = NULL;
  7068. BfMethodDef* checkMethodDef = NULL;
  7069. checkTypeInst->mTypeDef->mMethodSet.TryGetWith(String("__BfCtor"), &entry);
  7070. if (entry != NULL)
  7071. checkMethodDef = (BfMethodDef*)entry->mMemberDef;
  7072. bool hadProtected = false;
  7073. while (checkMethodDef != NULL)
  7074. {
  7075. if (!checkMethodDef->mParams.IsEmpty())
  7076. {
  7077. auto firstParam = checkMethodDef->mParams[0];
  7078. if (((firstParam->mParamKind == BfParamKind_Params) || (firstParam->mParamKind == BfParamKind_AppendIdx) || (firstParam->mParamKind == BfParamKind_VarArgs)) ||
  7079. ((firstParam->mParamDeclaration != NULL) && (firstParam->mParamDeclaration->mInitializer != NULL)))
  7080. {
  7081. // Allow all-default params
  7082. }
  7083. else
  7084. {
  7085. checkMethodDef = checkMethodDef->mNextWithSameName;
  7086. continue;
  7087. }
  7088. }
  7089. if (checkMethodDef->mProtection == BfProtection_Public)
  7090. {
  7091. canAlloc = true;
  7092. break;
  7093. }
  7094. if ((checkMethodDef->mProtection == BfProtection_Protected) || (checkMethodDef->mProtection == BfProtection_ProtectedInternal))
  7095. hadProtected = true;
  7096. checkMethodDef = checkMethodDef->mNextWithSameName;
  7097. }
  7098. if ((!canAlloc) && (hadProtected) && (mCurTypeInstance != NULL))
  7099. canAlloc = TypeIsSubTypeOf(mCurTypeInstance, checkTypeInst, false);
  7100. }
  7101. }
  7102. else if (checkArgType->IsGenericParam())
  7103. {
  7104. canAlloc = (checkGenericParamFlags & (BfGenericParamFlag_New | BfGenericParamFlag_Var)) != 0;
  7105. }
  7106. else if (checkArgType->IsPrimitiveType())
  7107. {
  7108. // Any primitive types and stuff can be allocated
  7109. canAlloc = true;
  7110. }
  7111. if (!canAlloc)
  7112. {
  7113. if ((!ignoreErrors) && (PreFail()))
  7114. {
  7115. if (checkArgType->IsGenericParam())
  7116. *errorOut = Fail(StrFormat("Must add 'where %s : new' constraint in order to use type as parameter '%s' for '%s'",
  7117. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7118. else
  7119. *errorOut = Fail(StrFormat("The type '%s' must have an accessible default constructor in order to use it as parameter '%s' for '%s'",
  7120. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7121. }
  7122. return false;
  7123. }
  7124. }
  7125. if ((genericParamInst->mInterfaceConstraints.IsEmpty()) && (genericParamInst->mOperatorConstraints.IsEmpty()) && (genericParamInst->mTypeConstraint == NULL))
  7126. return true;
  7127. if (genericParamInst->mTypeConstraint != NULL)
  7128. {
  7129. bool constraintMatched = false;
  7130. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  7131. {
  7132. if (checkArgType->IsConstExprValue())
  7133. {
  7134. auto constExprValueType = (BfConstExprValueType*)checkArgType;
  7135. if (genericParamInst->mTypeConstraint->IsPrimitiveType())
  7136. {
  7137. auto primType = (BfPrimitiveType*)genericParamInst->mTypeConstraint;
  7138. // Let either an exact typematch or an undef pass through. Eventually instead of undefs we may want to do
  7139. // actual expression comparisons, but we are overly permissive now and then we may fail on specialization
  7140. if ((constExprValueType->mValue.mTypeCode != primType->mTypeDef->mTypeCode) &&
  7141. (constExprValueType->mValue.mTypeCode != BfTypeCode_Let) &&
  7142. (primType->mTypeDef->mTypeCode != BfTypeCode_Let))
  7143. {
  7144. if (BfIRConstHolder::IsInt(constExprValueType->mValue.mTypeCode))
  7145. {
  7146. if (BfIRConstHolder::IsInt(primType->mTypeDef->mTypeCode))
  7147. {
  7148. if (!mCompiler->mSystem->DoesLiteralFit(primType->mTypeDef->mTypeCode, constExprValueType->mValue))
  7149. {
  7150. if ((!ignoreErrors) && (PreFail()))
  7151. *errorOut = Fail(StrFormat("Const generic argument '%s', declared with const '%lld', does not fit into const constraint '%s' for '%s'", genericParamInst->GetName().c_str(),
  7152. constExprValueType->mValue.mInt64, _TypeToString(genericParamInst->mTypeConstraint).c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7153. return false;
  7154. }
  7155. }
  7156. else
  7157. {
  7158. if ((!ignoreErrors) && (PreFail()))
  7159. *errorOut = Fail(StrFormat("Const generic argument '%s', declared with integer const '%lld', is not compatible with const constraint '%s' for '%s'", genericParamInst->GetName().c_str(),
  7160. constExprValueType->mValue.mInt64, _TypeToString(genericParamInst->mTypeConstraint).c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7161. return false;
  7162. }
  7163. }
  7164. else
  7165. {
  7166. if (BfIRConstHolder::IsInt(primType->mTypeDef->mTypeCode))
  7167. {
  7168. char valStr[64];
  7169. if (constExprValueType->mValue.mTypeCode == BfTypeCode_Double)
  7170. ExactMinimalDoubleToStr(constExprValueType->mValue.mDouble, valStr);
  7171. else
  7172. ExactMinimalFloatToStr(constExprValueType->mValue.mSingle, valStr);
  7173. if ((!ignoreErrors) && (PreFail()))
  7174. *errorOut = Fail(StrFormat("Const generic argument '%s', declared with floating point const '%s', is not compatible with const constraint '%s' for '%s'", genericParamInst->GetName().c_str(),
  7175. valStr, _TypeToString(genericParamInst->mTypeConstraint).c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7176. return false;
  7177. }
  7178. }
  7179. }
  7180. }
  7181. else if (genericParamInst->mTypeConstraint != constExprValueType->mType)
  7182. {
  7183. if ((!ignoreErrors) && (PreFail()))
  7184. *errorOut = Fail(StrFormat("Const generic argument '%s', declared as '%s', is not compatible with const constraint '%s' for '%s'", genericParamInst->GetName().c_str(),
  7185. _TypeToString(constExprValueType).c_str(), _TypeToString(genericParamInst->mTypeConstraint).c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7186. return false;
  7187. }
  7188. }
  7189. }
  7190. else
  7191. {
  7192. BfType* convCheckConstraint = genericParamInst->mTypeConstraint;
  7193. if ((convCheckConstraint->IsUnspecializedType()) && (methodGenericArgs != NULL))
  7194. convCheckConstraint = ResolveGenericType(convCheckConstraint, NULL, methodGenericArgs);
  7195. if (convCheckConstraint == NULL)
  7196. return false;
  7197. if (((checkArgType->IsMethodRef()) || (checkArgType->IsFunction())) && (convCheckConstraint->IsDelegate()))
  7198. {
  7199. BfMethodInstance* checkMethodInstance;
  7200. if (checkArgType->IsMethodRef())
  7201. {
  7202. auto methodRefType = (BfMethodRefType*)checkArgType;
  7203. checkMethodInstance = methodRefType->mMethodRef;
  7204. }
  7205. else
  7206. {
  7207. checkMethodInstance = GetRawMethodInstanceAtIdx(checkArgType->ToTypeInstance(), 0, "Invoke");
  7208. }
  7209. auto invokeMethod = GetRawMethodInstanceAtIdx(convCheckConstraint->ToTypeInstance(), 0, "Invoke");
  7210. BfExprEvaluator exprEvaluator(this);
  7211. if (exprEvaluator.IsExactMethodMatch(checkMethodInstance, invokeMethod))
  7212. constraintMatched = true;
  7213. }
  7214. else if (CanCast(GetFakeTypedValue(checkArgType), convCheckConstraint))
  7215. {
  7216. constraintMatched = true;
  7217. }
  7218. else if (origCheckArgType->IsWrappableType())
  7219. {
  7220. if (origCheckArgType->IsSizedArray())
  7221. {
  7222. auto sizedArrayType = (BfSizedArrayType*)origCheckArgType;
  7223. if (convCheckConstraint->IsGenericTypeInstance())
  7224. {
  7225. auto convCheckConstraintInst = (BfTypeInstance*)convCheckConstraint;
  7226. if (convCheckConstraintInst->IsInstanceOf(mCompiler->mSizedArrayTypeDef))
  7227. {
  7228. if (convCheckConstraintInst->mGenericTypeInfo->mTypeGenericArguments[0] == sizedArrayType->mElementType)
  7229. {
  7230. auto constExprValueType = (BfConstExprValueType*)convCheckConstraintInst->mGenericTypeInfo->mTypeGenericArguments[1];
  7231. if (sizedArrayType->mElementCount == constExprValueType->mValue.mInt64)
  7232. constraintMatched = true;
  7233. }
  7234. }
  7235. }
  7236. }
  7237. if (!constraintMatched)
  7238. {
  7239. BfType* wrappedStructType = GetWrappedStructType(origCheckArgType, false);
  7240. if (CanCast(GetFakeTypedValue(wrappedStructType), convCheckConstraint))
  7241. constraintMatched = true;
  7242. }
  7243. }
  7244. if (!constraintMatched)
  7245. {
  7246. if ((!ignoreErrors) && (PreFail()))
  7247. *errorOut = Fail(StrFormat("Generic argument '%s', declared to be '%s' for '%s', must derive from '%s'", genericParamInst->GetName().c_str(),
  7248. TypeToString(origCheckArgType).c_str(), GenericParamSourceToString(genericParamSource).c_str(), TypeToString(convCheckConstraint).c_str(),
  7249. _TypeToString(genericParamInst->mTypeConstraint).c_str()), checkArgTypeRef);
  7250. return false;
  7251. }
  7252. }
  7253. }
  7254. for (auto checkConstraint : genericParamInst->mInterfaceConstraints)
  7255. {
  7256. BfType* convCheckConstraint = checkConstraint;
  7257. if (convCheckConstraint->IsUnspecializedType())
  7258. convCheckConstraint = ResolveGenericType(convCheckConstraint, NULL, methodGenericArgs);
  7259. if (convCheckConstraint == NULL)
  7260. return false;
  7261. BfTypeInstance* typeConstraintInst = convCheckConstraint->ToTypeInstance();
  7262. bool implementsInterface = false;
  7263. if (origCheckArgType != checkArgType)
  7264. {
  7265. implementsInterface = CanCast(BfTypedValue(BfIRValue::sValueless, origCheckArgType), convCheckConstraint);
  7266. }
  7267. if (!implementsInterface)
  7268. implementsInterface = CanCast(BfTypedValue(BfIRValue::sValueless, checkArgType), convCheckConstraint);
  7269. if ((!implementsInterface) && (origCheckArgType->IsWrappableType()))
  7270. {
  7271. BfTypeInstance* wrappedStructType = GetWrappedStructType(origCheckArgType, false);
  7272. if (TypeIsSubTypeOf(wrappedStructType, typeConstraintInst))
  7273. implementsInterface = true;
  7274. }
  7275. if ((!implementsInterface) && (origCheckArgType->IsTypedPrimitive()))
  7276. {
  7277. auto underlyingType = origCheckArgType->GetUnderlyingType();
  7278. BfTypeInstance* wrappedStructType = GetWrappedStructType(underlyingType, false);
  7279. if (TypeIsSubTypeOf(wrappedStructType, typeConstraintInst))
  7280. implementsInterface = true;
  7281. }
  7282. if (!implementsInterface)
  7283. {
  7284. if ((!ignoreErrors) && (PreFail()))
  7285. *errorOut = Fail(StrFormat("Generic argument '%s', declared to be '%s' for '%s', must implement '%s'", genericParamInst->GetName().c_str(),
  7286. TypeToString(origCheckArgType).c_str(), GenericParamSourceToString(genericParamSource).c_str(), TypeToString(checkConstraint).c_str()), checkArgTypeRef);
  7287. return false;
  7288. }
  7289. }
  7290. for (auto& checkOpConstraint : genericParamInst->mOperatorConstraints)
  7291. {
  7292. auto leftType = checkOpConstraint.mLeftType;
  7293. if ((leftType != NULL) && (leftType->IsUnspecializedType()))
  7294. leftType = ResolveGenericType(leftType, NULL, methodGenericArgs);
  7295. if (leftType != NULL)
  7296. leftType = FixIntUnknown(leftType);
  7297. auto rightType = checkOpConstraint.mRightType;
  7298. if ((rightType != NULL) && (rightType->IsUnspecializedType()))
  7299. rightType = ResolveGenericType(rightType, NULL, methodGenericArgs);
  7300. if (rightType != NULL)
  7301. rightType = FixIntUnknown(rightType);
  7302. BfConstraintState constraintSet;
  7303. constraintSet.mPrevState = mContext->mCurConstraintState;
  7304. constraintSet.mGenericParamInstance = genericParamInst;
  7305. constraintSet.mLeftType = leftType;
  7306. constraintSet.mRightType = rightType;
  7307. SetAndRestoreValue<BfConstraintState*> prevConstraintSet(mContext->mCurConstraintState, &constraintSet);
  7308. if (!CheckConstraintState(NULL))
  7309. return false;
  7310. if (checkOpConstraint.mBinaryOp != BfBinaryOp_None)
  7311. {
  7312. BfExprEvaluator exprEvaluator(this);
  7313. BfTypedValue leftValue(mBfIRBuilder->GetFakeVal(), leftType);
  7314. BfTypedValue rightValue(mBfIRBuilder->GetFakeVal(), rightType);
  7315. //
  7316. {
  7317. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, true);
  7318. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, true);
  7319. exprEvaluator.PerformBinaryOperation(NULL, NULL, checkOpConstraint.mBinaryOp, NULL, (BfBinOpFlags)(BfBinOpFlag_NoClassify | BfBinOpFlag_IsConstraintCheck), leftValue, rightValue);
  7320. }
  7321. if ((!exprEvaluator.mResult) ||
  7322. (!CanCast(exprEvaluator.mResult, origCheckArgType, BfCastFlags_NoConversionOperator)))
  7323. {
  7324. if ((!ignoreErrors) && (PreFail()))
  7325. {
  7326. if (genericParamInst->mExternType != NULL)
  7327. *errorOut = Fail(StrFormat("Binary operation for '%s' must result in '%s' from binary operation '%s %s %s'",
  7328. GenericParamSourceToString(genericParamSource).c_str(), TypeToString(origCheckArgType).c_str(),
  7329. TypeToString(leftType).c_str(), BfGetOpName(checkOpConstraint.mBinaryOp), TypeToString(rightType).c_str()
  7330. ), checkArgTypeRef);
  7331. else
  7332. *errorOut = Fail(StrFormat("Generic argument '%s', declared to be '%s' for '%s', must result from binary operation '%s %s %s'", genericParamInst->GetName().c_str(),
  7333. TypeToString(origCheckArgType).c_str(), GenericParamSourceToString(genericParamSource).c_str(),
  7334. TypeToString(leftType).c_str(), BfGetOpName(checkOpConstraint.mBinaryOp), TypeToString(rightType).c_str()
  7335. ), checkArgTypeRef);
  7336. }
  7337. return false;
  7338. }
  7339. }
  7340. else
  7341. {
  7342. BfTypedValue rightValue(mBfIRBuilder->GetFakeVal(), rightType);
  7343. StringT<128> failedOpName;
  7344. if (checkOpConstraint.mCastToken == BfToken_Implicit)
  7345. {
  7346. if (!CanCast(rightValue, origCheckArgType, (BfCastFlags)(BfCastFlags_SilentFail | BfCastFlags_IsConstraintCheck)))
  7347. failedOpName = "implicit conversion from '";
  7348. }
  7349. else
  7350. {
  7351. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, true);
  7352. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, true);
  7353. if (checkOpConstraint.mCastToken == BfToken_Explicit)
  7354. {
  7355. if (!CastToValue(NULL, rightValue, origCheckArgType, (BfCastFlags)(BfCastFlags_Explicit | BfCastFlags_SilentFail | BfCastFlags_IsConstraintCheck)))
  7356. failedOpName = "explicit conversion from '";
  7357. }
  7358. else
  7359. {
  7360. BfExprEvaluator exprEvaluator(this);
  7361. exprEvaluator.mResult = rightValue;
  7362. exprEvaluator.PerformUnaryOperation(NULL, checkOpConstraint.mUnaryOp, NULL, BfUnaryOpFlag_IsConstraintCheck);
  7363. if ((!exprEvaluator.mResult) ||
  7364. (!CanCast(exprEvaluator.mResult, origCheckArgType)))
  7365. {
  7366. failedOpName += "unary operation '";
  7367. failedOpName += BfGetOpName(checkOpConstraint.mUnaryOp);
  7368. }
  7369. }
  7370. }
  7371. if (!failedOpName.IsEmpty())
  7372. {
  7373. if ((!ignoreErrors) && (PreFail()))
  7374. *errorOut = Fail(StrFormat("Generic argument '%s', declared to be '%s' for '%s', must result from %s%s'", genericParamInst->GetName().c_str(),
  7375. TypeToString(origCheckArgType).c_str(), GenericParamSourceToString(genericParamSource).c_str(),
  7376. failedOpName.c_str(), TypeToString(rightType).c_str()
  7377. ), checkArgTypeRef);
  7378. return false;
  7379. }
  7380. }
  7381. }
  7382. return true;
  7383. }
  7384. BfGenericParamType* BfModule::GetGenericParamType(BfGenericParamKind paramKind, int paramIdx)
  7385. {
  7386. if (paramIdx < (int)mContext->mGenericParamTypes[paramKind].size())
  7387. {
  7388. auto genericParamType = mContext->mGenericParamTypes[paramKind][paramIdx];
  7389. return genericParamType;
  7390. }
  7391. auto genericParamType = new BfGenericParamType();
  7392. genericParamType->mContext = mContext;
  7393. genericParamType->mGenericParamKind = paramKind;
  7394. genericParamType->mGenericParamIdx = paramIdx;
  7395. PopulateType(genericParamType);
  7396. BF_ASSERT(paramIdx == (int)mContext->mGenericParamTypes[paramKind].size());
  7397. mContext->mGenericParamTypes[paramKind].push_back(genericParamType);
  7398. BfResolvedTypeSet::LookupContext lookupCtx;
  7399. lookupCtx.mModule = this;
  7400. BfResolvedTypeSet::Entry* typeEntry = NULL;
  7401. auto inserted = mContext->mResolvedTypes.Insert(genericParamType, &lookupCtx, &typeEntry);
  7402. BF_ASSERT(inserted);
  7403. typeEntry->mValue = genericParamType;
  7404. return genericParamType;
  7405. }
  7406. static int sValueFromExprIdx = 0;
  7407. BfTypedValue BfModule::FlushNullConditional(BfTypedValue result, bool ignoreNullable)
  7408. {
  7409. auto pendingNullCond = mCurMethodState->mPendingNullConditional;
  7410. if ((result) && (!ignoreNullable))
  7411. {
  7412. if (result.mType->IsVar())
  7413. return result;
  7414. auto notNullBB = mBfIRBuilder->GetInsertBlock();
  7415. //TODO: Make this work, needed for 'void' and such
  7416. BfType* nullableType = NULL;
  7417. if ((result.mType->IsValueType()) && (!result.mType->IsNullable()))
  7418. {
  7419. BfTypeVector typeVec;
  7420. typeVec.push_back(result.mType);
  7421. nullableType = ResolveTypeDef(mCompiler->mNullableTypeDef, typeVec);
  7422. BF_ASSERT(nullableType != NULL);
  7423. }
  7424. // Go back to start and do any setup we need
  7425. mBfIRBuilder->SetInsertPoint(pendingNullCond->mPrevBB);
  7426. BfTypedValue nullableTypedValue;
  7427. if (nullableType != NULL)
  7428. {
  7429. nullableTypedValue = BfTypedValue(CreateAlloca(nullableType, true, "nullCond.nullable"), nullableType, true);
  7430. mBfIRBuilder->CreateMemSet(nullableTypedValue.mValue, GetConstValue(0, GetPrimitiveType(BfTypeCode_Int8)),
  7431. GetConstValue(nullableType->mSize), nullableType->mAlign);
  7432. }
  7433. mBfIRBuilder->CreateBr(pendingNullCond->mCheckBB);
  7434. // Now that we have the nullableTypedValue we can set that, or just jump if we didn't need it
  7435. mBfIRBuilder->SetInsertPoint(notNullBB);
  7436. result = LoadValue(result);
  7437. if (nullableTypedValue)
  7438. {
  7439. auto elementType = nullableType->GetUnderlyingType();
  7440. if (elementType->IsVar())
  7441. {
  7442. // Do nothing
  7443. }
  7444. else if (elementType->IsValuelessType())
  7445. {
  7446. BfIRValue ptrValue = mBfIRBuilder->CreateInBoundsGEP(nullableTypedValue.mValue, 0, 1); // mHasValue
  7447. mBfIRBuilder->CreateStore(GetConstValue(1, GetPrimitiveType(BfTypeCode_Boolean)), ptrValue);
  7448. }
  7449. else
  7450. {
  7451. BfIRValue ptrValue = mBfIRBuilder->CreateInBoundsGEP(nullableTypedValue.mValue, 0, 1); // mValue
  7452. mBfIRBuilder->CreateStore(result.mValue, ptrValue);
  7453. ptrValue = mBfIRBuilder->CreateInBoundsGEP(nullableTypedValue.mValue, 0, 2); // mHasValue
  7454. mBfIRBuilder->CreateStore(GetConstValue(1, GetPrimitiveType(BfTypeCode_Boolean)), ptrValue);
  7455. }
  7456. result = nullableTypedValue;
  7457. }
  7458. mBfIRBuilder->CreateBr(pendingNullCond->mDoneBB);
  7459. AddBasicBlock(pendingNullCond->mDoneBB);
  7460. if (nullableType == NULL)
  7461. {
  7462. auto phi = mBfIRBuilder->CreatePhi(mBfIRBuilder->MapType(result.mType), 1 + (int)pendingNullCond->mNotNullBBs.size());
  7463. mBfIRBuilder->AddPhiIncoming(phi, result.mValue, notNullBB);
  7464. mBfIRBuilder->AddPhiIncoming(phi, GetDefaultValue(result.mType), pendingNullCond->mCheckBB);
  7465. for (int notNullIdx = 0; notNullIdx < (int)pendingNullCond->mNotNullBBs.size() - 1; notNullIdx++)
  7466. {
  7467. auto prevNotNullBB = pendingNullCond->mNotNullBBs[notNullIdx];
  7468. mBfIRBuilder->AddPhiIncoming(phi, GetDefaultValue(result.mType), prevNotNullBB);
  7469. }
  7470. result.mValue = phi;
  7471. }
  7472. }
  7473. else
  7474. {
  7475. mBfIRBuilder->CreateBr(pendingNullCond->mDoneBB);
  7476. mBfIRBuilder->SetInsertPoint(pendingNullCond->mPrevBB);
  7477. mBfIRBuilder->CreateBr(pendingNullCond->mCheckBB);
  7478. AddBasicBlock(pendingNullCond->mDoneBB);
  7479. }
  7480. delete mCurMethodState->mPendingNullConditional;
  7481. mCurMethodState->mPendingNullConditional = NULL;
  7482. return result;
  7483. }
  7484. BF_NOINLINE void BfModule::EvaluateWithNewConditionalScope(BfExprEvaluator& exprEvaluator, BfExpression* expr, BfEvalExprFlags flags)
  7485. {
  7486. BfDeferredLocalAssignData deferredLocalAssignData(mCurMethodState->mCurScope);
  7487. SetAndRestoreValue<BfDeferredLocalAssignData*> prevDLA(mCurMethodState->mDeferredLocalAssignData);
  7488. if (mCurMethodState != NULL)
  7489. {
  7490. deferredLocalAssignData.mIsIfCondition = true;
  7491. deferredLocalAssignData.mIfMayBeSkipped = true;
  7492. deferredLocalAssignData.ExtendFrom(mCurMethodState->mDeferredLocalAssignData, false);
  7493. deferredLocalAssignData.mVarIdBarrier = mCurMethodState->GetRootMethodState()->mCurLocalVarId;
  7494. mCurMethodState->mDeferredLocalAssignData = &deferredLocalAssignData;
  7495. }
  7496. BfScopeData newScope;
  7497. newScope.mOuterIsConditional = true;
  7498. newScope.mAllowTargeting = false;
  7499. if (mCurMethodState != NULL)
  7500. {
  7501. mCurMethodState->AddScope(&newScope);
  7502. NewScopeState(true, false);
  7503. }
  7504. exprEvaluator.mBfEvalExprFlags = (BfEvalExprFlags)(exprEvaluator.mBfEvalExprFlags | flags);
  7505. exprEvaluator.Evaluate(expr, (flags & BfEvalExprFlags_PropogateNullConditional) != 0, (flags & BfEvalExprFlags_IgnoreNullConditional) != 0, (flags & BfEvalExprFlags_AllowSplat) != 0);
  7506. if (mCurMethodState != NULL)
  7507. RestoreScopeState();
  7508. }
  7509. BfTypedValue BfModule::CreateValueFromExpression(BfExprEvaluator& exprEvaluator, BfExpression* expr, BfType* wantTypeRef, BfEvalExprFlags flags, BfType** outOrigType)
  7510. {
  7511. //
  7512. {
  7513. BP_ZONE("CreateValueFromExpression:CheckStack");
  7514. StackHelper stackHelper;
  7515. if (!stackHelper.CanStackExpand(64 * 1024))
  7516. {
  7517. BfTypedValue result;
  7518. if (!stackHelper.Execute([&]()
  7519. {
  7520. result = CreateValueFromExpression(exprEvaluator, expr, wantTypeRef, flags, outOrigType);
  7521. }))
  7522. {
  7523. Fail("Expression too complex to compile", expr);
  7524. }
  7525. return result;
  7526. }
  7527. }
  7528. BP_ZONE("BfModule::CreateValueFromExpression");
  7529. if (outOrigType != NULL)
  7530. *outOrigType = NULL;
  7531. exprEvaluator.mExpectingType = wantTypeRef;
  7532. exprEvaluator.mBfEvalExprFlags = (BfEvalExprFlags)(exprEvaluator.mBfEvalExprFlags | flags);
  7533. exprEvaluator.mExplicitCast = (flags & BfEvalExprFlags_ExplicitCast) != 0;
  7534. if ((flags & BfEvalExprFlags_CreateConditionalScope) != 0)
  7535. {
  7536. if ((mCurMethodState == NULL) || (mCurMethodState->mCurScope->mScopeKind != BfScopeKind_StatementTarget_Conditional))
  7537. {
  7538. EvaluateWithNewConditionalScope(exprEvaluator, expr, flags);
  7539. }
  7540. else
  7541. {
  7542. SetAndRestoreValue<bool> prevIsConditional(mCurMethodState->mCurScope->mIsConditional, true);
  7543. exprEvaluator.Evaluate(expr, (flags & BfEvalExprFlags_PropogateNullConditional) != 0, (flags & BfEvalExprFlags_IgnoreNullConditional) != 0, true);
  7544. }
  7545. }
  7546. else
  7547. exprEvaluator.Evaluate(expr, (flags & BfEvalExprFlags_PropogateNullConditional) != 0, (flags & BfEvalExprFlags_IgnoreNullConditional) != 0, true);
  7548. if (!exprEvaluator.mResult)
  7549. {
  7550. if ((flags & BfEvalExprFlags_InferReturnType) != 0)
  7551. return exprEvaluator.mResult;
  7552. if (!mCompiler->mPassInstance->HasFailed())
  7553. {
  7554. if (PreFail())
  7555. Fail("INTERNAL ERROR: No expression result returned but no error caught in expression evaluator", expr);
  7556. }
  7557. return BfTypedValue();
  7558. }
  7559. auto typedVal = exprEvaluator.mResult;
  7560. if (typedVal.mKind == BfTypedValueKind_GenericConstValue)
  7561. {
  7562. BF_ASSERT(typedVal.mType->IsGenericParam());
  7563. auto genericParamDef = GetGenericParamInstance((BfGenericParamType*)typedVal.mType);
  7564. bool handled = false;
  7565. if ((genericParamDef->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  7566. {
  7567. auto genericTypeConstraint = genericParamDef->mTypeConstraint;
  7568. if (genericTypeConstraint != NULL)
  7569. {
  7570. auto underlyingConstraint = genericTypeConstraint;
  7571. if ((underlyingConstraint != NULL) && (underlyingConstraint->IsBoxed()))
  7572. underlyingConstraint = underlyingConstraint->GetUnderlyingType();
  7573. if (underlyingConstraint != NULL)
  7574. {
  7575. BfTypedValue result;
  7576. result.mKind = BfTypedValueKind_Value;
  7577. result.mType = genericTypeConstraint;
  7578. result.mValue = mBfIRBuilder->GetUndefConstValue(mBfIRBuilder->MapType(underlyingConstraint));
  7579. typedVal = result;
  7580. handled = true;
  7581. }
  7582. }
  7583. }
  7584. if (!handled)
  7585. {
  7586. //Fail("Only const generic parameters can be used as values", expr);
  7587. AssertErrorState();
  7588. return BfTypedValue();
  7589. }
  7590. }
  7591. if ((flags & BfEvalExprFlags_AllowIntUnknown) == 0)
  7592. FixIntUnknown(typedVal);
  7593. if (!mBfIRBuilder->mIgnoreWrites)
  7594. FixValueActualization(typedVal);
  7595. exprEvaluator.CheckResultForReading(typedVal);
  7596. if ((wantTypeRef == NULL) || (!wantTypeRef->IsRef()))
  7597. {
  7598. if ((flags & BfEvalExprFlags_NoCast) == 0)
  7599. {
  7600. // Only allow a 'ref' type if we have an explicit 'ref' operator
  7601. bool allowRef = false;
  7602. BfExpression* checkExpr = expr;
  7603. while (auto parenExpr = BfNodeDynCast<BfParenthesizedExpression>(checkExpr))
  7604. checkExpr = parenExpr->mExpression;
  7605. if (auto unaryOp = BfNodeDynCast<BfUnaryOperatorExpression>(checkExpr))
  7606. {
  7607. if ((unaryOp->mOp == BfUnaryOp_Ref) || (unaryOp->mOp == BfUnaryOp_Mut))
  7608. allowRef = true;
  7609. }
  7610. if (!allowRef)
  7611. typedVal = RemoveRef(typedVal);
  7612. }
  7613. }
  7614. if ((!typedVal.mType->IsComposite()) && (!typedVal.mType->IsGenericParam())) // Load non-structs by default
  7615. {
  7616. if ((!mBfIRBuilder->mIgnoreWrites) && (!typedVal.mType->IsValuelessType()) && (!typedVal.mType->IsVar()))
  7617. {
  7618. BF_ASSERT(!typedVal.mValue.IsFake());
  7619. }
  7620. typedVal = LoadValue(typedVal, 0, exprEvaluator.mIsVolatileReference);
  7621. }
  7622. if (wantTypeRef != NULL)
  7623. {
  7624. if (outOrigType != NULL)
  7625. *outOrigType = typedVal.mType;
  7626. if (((flags & BfEvalExprFlags_NoCast) == 0) && (!wantTypeRef->IsVar()))
  7627. {
  7628. BfCastFlags castFlags = ((flags & BfEvalExprFlags_ExplicitCast) != 0) ? BfCastFlags_Explicit : BfCastFlags_None;
  7629. if ((flags & BfEvalExprFlags_FieldInitializer) != 0)
  7630. castFlags = (BfCastFlags)(castFlags | BfCastFlags_WarnOnBox);
  7631. typedVal = Cast(expr, typedVal, wantTypeRef, castFlags);
  7632. if (!typedVal)
  7633. return typedVal;
  7634. }
  7635. if (exprEvaluator.mIsVolatileReference)
  7636. typedVal = LoadValue(typedVal, 0, exprEvaluator.mIsVolatileReference);
  7637. }
  7638. if ((typedVal.mType->IsValueType()) && ((flags & BfEvalExprFlags_NoValueAddr) != 0))
  7639. typedVal = LoadValue(typedVal, 0, exprEvaluator.mIsVolatileReference);
  7640. return typedVal;
  7641. }
  7642. BfTypedValue BfModule::CreateValueFromExpression(BfExpression* expr, BfType* wantTypeRef, BfEvalExprFlags flags, BfType** outOrigType)
  7643. {
  7644. BfExprEvaluator exprEvaluator(this);
  7645. return CreateValueFromExpression(exprEvaluator, expr, wantTypeRef, flags, outOrigType);
  7646. }
  7647. BfTypedValue BfModule::GetOrCreateVarAddr(BfExpression* expr)
  7648. {
  7649. BfExprEvaluator exprEvaluator(this);
  7650. exprEvaluator.Evaluate(expr);
  7651. if (!exprEvaluator.mResult)
  7652. {
  7653. Fail("Invalid expression type", expr);
  7654. return BfTypedValue();
  7655. }
  7656. if (!exprEvaluator.mResult.IsAddr())
  7657. {
  7658. Fail("Cannot assign to value", expr);
  7659. return BfTypedValue();
  7660. }
  7661. return exprEvaluator.mResult;
  7662. }
  7663. // Clear memory, set classVData, call init. Actual ctor is called elsewhere.
  7664. void BfModule::InitTypeInst(BfTypedValue typedValue, BfScopeData* scopeData, bool zeroMemory, BfIRValue sizeValue)
  7665. {
  7666. auto typeInstance = typedValue.mType->ToTypeInstance();
  7667. if (zeroMemory)
  7668. {
  7669. int zeroAlign = typedValue.mType->mAlign;
  7670. if (typeInstance != NULL)
  7671. zeroAlign = typeInstance->mInstAlign;
  7672. mBfIRBuilder->CreateMemSet(typedValue.mValue, GetConstValue8(0), sizeValue, zeroAlign);
  7673. }
  7674. if (!typedValue.mType->IsObject())
  7675. {
  7676. return;
  7677. }
  7678. if ((scopeData == NULL) && (mCurMethodState != NULL))
  7679. return; // Handled in heap alloc funcs
  7680. auto typeDef = typeInstance->mTypeDef;
  7681. mBfIRBuilder->PopulateType(typedValue.mType);
  7682. auto vObjectAddr = mBfIRBuilder->CreateInBoundsGEP(typedValue.mValue, 0, 0);
  7683. bool isAutocomplete = mCompiler->IsAutocomplete();
  7684. BfIRValue vDataRef;
  7685. if (!isAutocomplete)
  7686. {
  7687. vDataRef = GetClassVDataPtr(typeInstance);
  7688. }
  7689. auto i8Type = GetPrimitiveType(BfTypeCode_Int8);
  7690. auto ptrType = CreatePointerType(i8Type);
  7691. auto ptrPtrType = CreatePointerType(ptrType);
  7692. PopulateType(ptrPtrType, BfPopulateType_Declaration);
  7693. PopulateType(ptrType, BfPopulateType_Declaration);
  7694. auto destAddr = mBfIRBuilder->CreateBitCast(vObjectAddr, mBfIRBuilder->MapType(ptrPtrType));
  7695. if (!isAutocomplete)
  7696. {
  7697. if ((mCompiler->mOptions.mObjectHasDebugFlags) && (!mIsComptimeModule))
  7698. {
  7699. auto objectPtr = mBfIRBuilder->CreateBitCast(destAddr, mBfIRBuilder->MapType(mContext->mBfObjectType));
  7700. SizedArray<BfIRValue, 4> llvmArgs;
  7701. llvmArgs.push_back(objectPtr);
  7702. llvmArgs.push_back(vDataRef);
  7703. auto objectStackInitMethod = GetInternalMethod("Dbg_ObjectStackInit");
  7704. if (objectStackInitMethod)
  7705. mBfIRBuilder->CreateCall(objectStackInitMethod.mFunc, llvmArgs);
  7706. }
  7707. else
  7708. {
  7709. auto srcVal = mBfIRBuilder->CreateBitCast(vDataRef, mBfIRBuilder->MapType(ptrType));
  7710. auto objectPtr = mBfIRBuilder->CreateBitCast(destAddr, mBfIRBuilder->MapType(ptrType));
  7711. mBfIRBuilder->CreateStore(srcVal, destAddr);
  7712. }
  7713. }
  7714. }
  7715. BfIRValue BfModule::AllocBytes(BfAstNode* refNode, const BfAllocTarget& allocTarget, BfType* type, BfIRValue sizeValue, BfIRValue alignValue, BfAllocFlags allocFlags/*, bool zeroMemory, bool defaultToMalloc*/)
  7716. {
  7717. BfIRValue result;
  7718. BfType* ptrType;
  7719. if ((type->IsObject()) && ((allocFlags & BfAllocFlags_RawArray) == 0))
  7720. ptrType = type;
  7721. else
  7722. ptrType = CreatePointerType(type);
  7723. if ((allocTarget.mScopedInvocationTarget != NULL) || (allocTarget.mCustomAllocator))
  7724. {
  7725. auto intType = GetPrimitiveType(BfTypeCode_IntPtr);
  7726. SizedArray<BfExpression*, 2> argExprs;
  7727. BfTypedValueExpression typedValueExpr;
  7728. typedValueExpr.Init(BfTypedValue(sizeValue, intType));
  7729. typedValueExpr.mRefNode = refNode;
  7730. argExprs.push_back(&typedValueExpr);
  7731. BfTypedValueExpression appendSizeValueExpr;
  7732. appendSizeValueExpr.Init(BfTypedValue(alignValue, intType));
  7733. appendSizeValueExpr.mRefNode = refNode;
  7734. argExprs.push_back(&appendSizeValueExpr);
  7735. BfExprEvaluator exprEvaluator(this);
  7736. BfTypedValue allocResult;
  7737. if (allocTarget.mScopedInvocationTarget != NULL)
  7738. {
  7739. SizedArray<BfTypeReference*, 2> genericArgs;
  7740. exprEvaluator.DoInvocation(allocTarget.mScopedInvocationTarget, NULL, argExprs, BfMethodGenericArguments());
  7741. allocResult = LoadValue(exprEvaluator.mResult);
  7742. }
  7743. else if (allocTarget.mCustomAllocator)
  7744. {
  7745. auto customTypeInst = allocTarget.mCustomAllocator.mType->ToTypeInstance();
  7746. if (customTypeInst == NULL)
  7747. {
  7748. if (allocTarget.mCustomAllocator.mType->IsStructPtr())
  7749. customTypeInst = allocTarget.mCustomAllocator.mType->GetUnderlyingType()->ToTypeInstance();
  7750. }
  7751. if (customTypeInst == NULL)
  7752. {
  7753. Fail(StrFormat("Type '%s' cannot be used as a custom allocator", TypeToString(allocTarget.mCustomAllocator.mType).c_str()), refNode);
  7754. }
  7755. else
  7756. {
  7757. BfTypedValueExpression typeValueExpr;
  7758. String allocMethodName = "Alloc";
  7759. if (GetRawMethodByName(customTypeInst, "AllocTyped", -1, true, true))
  7760. {
  7761. allocMethodName = "AllocTyped";
  7762. auto typeType = ResolveTypeDef(mCompiler->mTypeTypeDef);
  7763. auto typeRefVal = CreateTypeDataRef(type);
  7764. typeValueExpr.Init(BfTypedValue(typeRefVal, typeType));
  7765. typeValueExpr.mRefNode = refNode;
  7766. argExprs.Insert(0, &typeValueExpr);
  7767. }
  7768. if (HasMixin(customTypeInst, allocMethodName, 2))
  7769. {
  7770. BfSizedArray<BfExpression*> argExprArr;
  7771. argExprArr.mSize = (int)argExprs.size();
  7772. argExprArr.mVals = &argExprs[0];
  7773. exprEvaluator.InjectMixin(refNode, allocTarget.mCustomAllocator, false, allocMethodName, argExprs, {});
  7774. allocResult = exprEvaluator.GetResult();
  7775. }
  7776. else
  7777. {
  7778. BfSizedArray<BfExpression*> sizedArgExprs(argExprs);
  7779. BfResolvedArgs argValues(&sizedArgExprs);
  7780. exprEvaluator.ResolveArgValues(argValues);
  7781. SetAndRestoreValue<bool> prevNoBind(mCurMethodState->mNoBind, true);
  7782. allocResult = exprEvaluator.MatchMethod(refNode, NULL, allocTarget.mCustomAllocator, false, false, allocMethodName, argValues, BfMethodGenericArguments());
  7783. }
  7784. }
  7785. }
  7786. if (allocResult)
  7787. {
  7788. if (allocResult.mType->IsVoidPtr())
  7789. result = mBfIRBuilder->CreateBitCast(allocResult.mValue, mBfIRBuilder->MapType(ptrType));
  7790. else
  7791. result = CastToValue(refNode, allocResult, ptrType, BfCastFlags_Explicit);
  7792. return result;
  7793. }
  7794. }
  7795. if ((allocFlags & BfAllocFlags_NoDefaultToMalloc) != 0)
  7796. return result;
  7797. if ((mCompiler->mOptions.mDebugAlloc) && (!mIsComptimeModule))
  7798. {
  7799. BfIRValue allocData = GetDbgRawAllocData(type);
  7800. BfModuleMethodInstance allocMethod = GetInternalMethod("Dbg_RawAlloc", 2);
  7801. SizedArray<BfIRValue, 2> llvmArgs;
  7802. llvmArgs.push_back(sizeValue);
  7803. llvmArgs.push_back(allocData);
  7804. BfIRValue bitData = mBfIRBuilder->CreateCall(allocMethod.mFunc, llvmArgs);
  7805. return mBfIRBuilder->CreateBitCast(bitData, mBfIRBuilder->MapType(ptrType));
  7806. }
  7807. BfModuleMethodInstance moduleMethodInstance;
  7808. moduleMethodInstance = GetInternalMethod("Malloc");
  7809. SizedArray<BfIRValue, 1> llvmArgs;
  7810. llvmArgs.push_back(sizeValue);
  7811. auto func = moduleMethodInstance.mFunc;
  7812. if ((!func) || (func.IsFake()))
  7813. {
  7814. BF_ASSERT((mCompiler->mIsResolveOnly) || (mBfIRBuilder->mIgnoreWrites));
  7815. return mBfIRBuilder->CreateUndefValue(mBfIRBuilder->MapType(ptrType));
  7816. }
  7817. BfIRValue bitData = mBfIRBuilder->CreateCall(func, llvmArgs);
  7818. if ((allocFlags & BfAllocFlags_ZeroMemory) != 0)
  7819. mBfIRBuilder->CreateMemSet(bitData, GetConstValue8(0), sizeValue, alignValue);
  7820. result = mBfIRBuilder->CreateBitCast(bitData, mBfIRBuilder->MapType(ptrType));
  7821. return result;
  7822. }
  7823. BfIRValue BfModule::GetMarkFuncPtr(BfType* type)
  7824. {
  7825. if (type->IsStruct())
  7826. {
  7827. auto typeInstance = type->ToTypeInstance();
  7828. BfModuleMethodInstance moduleMethodInst = GetMethodByName(typeInstance, BF_METHODNAME_MARKMEMBERS, 0, true);
  7829. return mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr)));
  7830. }
  7831. else if (type->IsObjectOrInterface())
  7832. {
  7833. auto gcType = ResolveTypeDef(mCompiler->mGCTypeDef)->ToTypeInstance();
  7834. BfModuleMethodInstance moduleMethodInst = GetMethodByName(gcType, "MarkDerefedObject");
  7835. BF_ASSERT(moduleMethodInst.mFunc);
  7836. return mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr)));
  7837. }
  7838. else
  7839. {
  7840. auto gcType = ResolveTypeDef(mCompiler->mGCTypeDef)->ToTypeInstance();
  7841. BfExprEvaluator exprEvaluator(this);
  7842. SizedArray<BfResolvedArg, 1> resolvedArgs;
  7843. BfResolvedArg resolvedArg;
  7844. resolvedArg.mTypedValue = BfTypedValue(mBfIRBuilder->GetFakeVal(), type, type->IsComposite());
  7845. resolvedArgs.Add(resolvedArg);
  7846. BfMethodMatcher methodMatcher(NULL, this, "Mark", resolvedArgs, BfMethodGenericArguments());
  7847. methodMatcher.CheckType(gcType, BfTypedValue(), false);
  7848. BfModuleMethodInstance moduleMethodInst = exprEvaluator.GetSelectedMethod(NULL, methodMatcher.mBestMethodTypeInstance, methodMatcher.mBestMethodDef, methodMatcher);
  7849. BF_ASSERT(moduleMethodInst.mFunc);
  7850. return mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr)));
  7851. }
  7852. return BfIRValue();
  7853. }
  7854. BfIRValue BfModule::GetDbgRawAllocData(BfType* type)
  7855. {
  7856. BfIRValue allocDataValue;
  7857. if (mDbgRawAllocDataRefs.TryGetValue(type, &allocDataValue))
  7858. return allocDataValue;
  7859. BfIRValue markFuncPtr;
  7860. if (type->WantsGCMarking())
  7861. markFuncPtr = GetMarkFuncPtr(type);
  7862. else
  7863. markFuncPtr = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr)));
  7864. BfIRValue typeDataRef = CreateTypeDataRef(type);
  7865. auto dbgRawAllocDataType = ResolveTypeDef(mCompiler->mDbgRawAllocDataTypeDef)->ToTypeInstance();
  7866. BfTypeInstance* typeInstance = type->ToTypeInstance();
  7867. if (typeInstance == NULL)
  7868. {
  7869. typeInstance = GetWrappedStructType(type);
  7870. if (typeInstance != NULL)
  7871. AddDependency(typeInstance, mCurTypeInstance, BfDependencyMap::DependencyFlag_Allocates);
  7872. }
  7873. if (typeInstance != NULL)
  7874. PopulateType(typeInstance);
  7875. int stackCount = mCompiler->mOptions.mAllocStackCount;
  7876. if ((typeInstance != NULL) && (typeInstance->mTypeOptionsIdx != -1))
  7877. {
  7878. auto typeOptions = mSystem->GetTypeOptions(typeInstance->mTypeOptionsIdx);
  7879. stackCount = BfTypeOptions::Apply(stackCount, typeOptions->mAllocStackTraceDepth);
  7880. }
  7881. SizedArray<BfIRValue, 2> dataValues;
  7882. dataValues.Add(mBfIRBuilder->CreateConstAggZero(mBfIRBuilder->MapType(dbgRawAllocDataType->mBaseType, BfIRPopulateType_Full)));
  7883. dataValues.Add(typeDataRef);
  7884. dataValues.Add(markFuncPtr);
  7885. dataValues.Add(mBfIRBuilder->CreateConst(BfTypeCode_Int32, stackCount));
  7886. BfIRValue dataStruct = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapType(dbgRawAllocDataType, BfIRPopulateType_Full), dataValues);
  7887. allocDataValue = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapType(dbgRawAllocDataType), true, BfIRLinkageType_Internal, dataStruct, "__allocData_" + BfSafeMangler::Mangle(type));
  7888. mDbgRawAllocDataRefs.TryAdd(type, allocDataValue);
  7889. return allocDataValue;
  7890. }
  7891. BfIRValue BfModule::AllocFromType(BfType* type, const BfAllocTarget& allocTarget, BfIRValue appendSizeValue, BfIRValue arraySize, int arrayDim, BfAllocFlags allocFlags, int alignOverride)
  7892. {
  7893. BP_ZONE("AllocFromType");
  7894. BfScopeData* scopeData = allocTarget.mScopeData;
  7895. BF_ASSERT(!type->IsVar());
  7896. auto typeInstance = type->ToTypeInstance();
  7897. if ((typeInstance == NULL) && (type->IsGenericParam()))
  7898. typeInstance = mContext->mBfObjectType;
  7899. bool isHeapAlloc = scopeData == NULL;
  7900. bool isScopeAlloc = scopeData != NULL;
  7901. bool isLoopedAlloc = (scopeData != NULL) && (mCurMethodState->mCurScope->IsLooped(scopeData));
  7902. bool isDynAlloc = (scopeData != NULL) && (mCurMethodState->mCurScope->IsDyn(scopeData));
  7903. bool isRawArrayAlloc = (allocFlags & BfAllocFlags_RawArray) != 0;
  7904. bool zeroMemory = (allocFlags & BfAllocFlags_ZeroMemory) != 0;
  7905. bool noDtorCall = (allocFlags & BfAllocFlags_NoDtorCall) != 0;
  7906. if ((type->IsValuelessType()) && ((!arraySize) || (isRawArrayAlloc)))
  7907. {
  7908. BfPointerType* ptrType = CreatePointerType(type);
  7909. auto val = mBfIRBuilder->CreateIntToPtr(mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 1), mBfIRBuilder->MapType(ptrType));
  7910. return val;
  7911. }
  7912. if (typeInstance != NULL)
  7913. mBfIRBuilder->PopulateType(typeInstance);
  7914. bool hasCustomAllocator = (allocTarget.mCustomAllocator) || (allocTarget.mScopedInvocationTarget != NULL);
  7915. if ((!hasCustomAllocator) && (mBfIRBuilder->mIgnoreWrites))
  7916. {
  7917. return mBfIRBuilder->GetFakeVal();
  7918. }
  7919. AddDependency(type, mCurTypeInstance, BfDependencyMap::DependencyFlag_Allocates);
  7920. BfIRValue sizeValue;
  7921. BfIRType allocType = mBfIRBuilder->MapType(type);
  7922. int allocSize = type->mSize;
  7923. int allocAlign = type->mAlign;
  7924. if (typeInstance != NULL)
  7925. {
  7926. if (!mBfIRBuilder->mIgnoreWrites)
  7927. typeInstance->mHasBeenInstantiated = true;
  7928. allocSize = typeInstance->mInstSize;
  7929. allocAlign = typeInstance->mInstAlign;
  7930. //if (typeInstance->IsEnum())
  7931. //allocType = typeInstance->mIRType;
  7932. allocType = mBfIRBuilder->MapTypeInst(typeInstance);
  7933. }
  7934. if (alignOverride != -1)
  7935. allocAlign = alignOverride;
  7936. // The "dynSize" cases:
  7937. // If we are not dyn, but we are a variable size and could be looped over multiple times then we attempt to reuse
  7938. // the last stack space. We won't use StackSave and StackRestore because a scoped alloc that occurs after this but
  7939. // needs to be retained after the current scopeData (ie: scopeData::), then it would cause these allocs to accumulate even
  7940. // though we'd expect their stack space to be released
  7941. auto _CreateDynAlloc = [&](const BfIRValue& sizeValue, int align)
  7942. {
  7943. MarkDynStack(scopeData);
  7944. BfType* intType = GetPrimitiveType(BfTypeCode_IntPtr);
  7945. // For dynamically sized scoped allocs, we need to check the previous size to see if we need to realloc
  7946. BfType* voidType = GetPrimitiveType(BfTypeCode_None);
  7947. BfType* voidPtrType = CreatePointerType(voidType);
  7948. if (!mCurMethodState->mDynStackRevIdx)
  7949. {
  7950. mCurMethodState->mDynStackRevIdx = CreateAlloca(intType, false, "curDynStackRevIdx");
  7951. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  7952. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRInitBlock);
  7953. auto storeInst = mBfIRBuilder->CreateStore(GetConstValue(0), mCurMethodState->mDynStackRevIdx);
  7954. mBfIRBuilder->ClearDebugLocation(storeInst);
  7955. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  7956. }
  7957. auto byteType = GetPrimitiveType(BfTypeCode_Int8);
  7958. auto bytePtrType = CreatePointerType(byteType);
  7959. auto dynSizeAllocaInst = CreateAlloca(intType, false, "dynSize");
  7960. auto dynStackRevIdx = CreateAlloca(intType, false, "dynStackRevIdx");
  7961. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  7962. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRInitBlock);
  7963. auto storeInst = mBfIRBuilder->CreateStore(GetConstValue(0), dynSizeAllocaInst);
  7964. mBfIRBuilder->ClearDebugLocation(storeInst);
  7965. storeInst = mBfIRBuilder->CreateStore(GetConstValue(0), dynStackRevIdx);
  7966. mBfIRBuilder->ClearDebugLocation(storeInst);
  7967. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  7968. auto dynPtrAllocaInst = CreateAlloca(bytePtrType, false, "dynPtr");
  7969. if (IsTargetingBeefBackend())
  7970. {
  7971. // Since we don't allocate a debug variable for this, with LifetimeExtends, the easiest way
  7972. // to ensure there isn't any register collision during looping is just to not allow it to
  7973. // bind to a register at all
  7974. mBfIRBuilder->SetAllocaForceMem(dynSizeAllocaInst);
  7975. mBfIRBuilder->SetAllocaForceMem(dynPtrAllocaInst);
  7976. }
  7977. auto resizeBB = mBfIRBuilder->CreateBlock("dynAlloc.resize");
  7978. auto endBB = mBfIRBuilder->CreateBlock("dynAlloc.end");
  7979. auto verCheckBB = mBfIRBuilder->CreateBlock("dynAlloc.verCheck");
  7980. auto curDynStackRevIdx = mBfIRBuilder->CreateLoad(mCurMethodState->mDynStackRevIdx);
  7981. auto prevSize = mBfIRBuilder->CreateLoad(dynSizeAllocaInst);
  7982. auto isGreater = mBfIRBuilder->CreateCmpGT(sizeValue, prevSize, true);
  7983. mBfIRBuilder->CreateCondBr(isGreater, resizeBB, verCheckBB);
  7984. mBfIRBuilder->AddBlock(verCheckBB);
  7985. mBfIRBuilder->SetInsertPoint(verCheckBB);
  7986. auto prevDynStackRevIdx = mBfIRBuilder->CreateLoad(dynStackRevIdx);
  7987. auto dynStackChanged = mBfIRBuilder->CreateCmpNE(prevDynStackRevIdx, curDynStackRevIdx);
  7988. mBfIRBuilder->CreateCondBr(dynStackChanged, resizeBB, endBB);
  7989. mBfIRBuilder->AddBlock(resizeBB);
  7990. mBfIRBuilder->SetInsertPoint(resizeBB);
  7991. auto allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(byteType), sizeValue);
  7992. mBfIRBuilder->SetAllocaAlignment(allocaInst, align);
  7993. mBfIRBuilder->CreateStore(allocaInst, dynPtrAllocaInst);
  7994. mBfIRBuilder->CreateStore(sizeValue, dynSizeAllocaInst);
  7995. mBfIRBuilder->CreateStore(curDynStackRevIdx, dynStackRevIdx);
  7996. mBfIRBuilder->CreateBr(endBB);
  7997. mBfIRBuilder->AddBlock(endBB);
  7998. mBfIRBuilder->SetInsertPoint(endBB);
  7999. return mBfIRBuilder->CreateLoad(dynPtrAllocaInst);
  8000. };
  8001. if (isScopeAlloc)
  8002. {
  8003. if (arraySize)
  8004. {
  8005. bool isConstantArraySize = arraySize.IsConst();
  8006. if (isRawArrayAlloc)
  8007. {
  8008. BfPointerType* ptrType = CreatePointerType(type);
  8009. if ((!isDynAlloc) && (!isConstantArraySize) && (mCurMethodState->mCurScope->IsLooped(NULL)))
  8010. {
  8011. BfIRValue sizeValue = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySize);
  8012. auto loadedPtr = _CreateDynAlloc(sizeValue, type->mAlign);
  8013. InitTypeInst(BfTypedValue(loadedPtr, ptrType), scopeData, zeroMemory, sizeValue);
  8014. return mBfIRBuilder->CreateBitCast(loadedPtr, mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapType(type)));
  8015. }
  8016. else
  8017. {
  8018. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  8019. isDynAlloc = (isDynAlloc) || (!arraySize.IsConst());
  8020. if (!isDynAlloc)
  8021. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  8022. else
  8023. {
  8024. MarkDynStack(scopeData);
  8025. SaveStackState(scopeData);
  8026. }
  8027. int typeSize = type->GetStride();
  8028. BfIRValue allocaInst;
  8029. BfIRValue result;
  8030. if ((typeInstance == NULL) || (typeInstance->mIsCRepr))
  8031. {
  8032. allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(type), arraySize);
  8033. result = allocaInst;
  8034. }
  8035. else
  8036. {
  8037. if (typeInstance->IsStruct())
  8038. typeSize = typeInstance->GetInstStride();
  8039. auto byteType = GetPrimitiveStructType(BfTypeCode_Int8);
  8040. sizeValue = mBfIRBuilder->CreateMul(GetConstValue(typeSize), arraySize);
  8041. allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(byteType), sizeValue);
  8042. auto ptrType = CreatePointerType(typeInstance);
  8043. result = mBfIRBuilder->CreateBitCast(allocaInst, mBfIRBuilder->MapType(ptrType));
  8044. if (!isDynAlloc)
  8045. mBfIRBuilder->ClearDebugLocation(result);
  8046. }
  8047. if (!isDynAlloc)
  8048. mBfIRBuilder->ClearDebugLocation(allocaInst);
  8049. mBfIRBuilder->SetAllocaAlignment(allocaInst, allocAlign);
  8050. if (!isDynAlloc)
  8051. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  8052. auto typedVal = BfTypedValue(result, type, BfTypedValueKind_Addr);
  8053. if (arraySize.IsConst())
  8054. {
  8055. auto constant = mBfIRBuilder->GetConstant(arraySize);
  8056. if (constant->mInt64 == 0)
  8057. noDtorCall = true;
  8058. }
  8059. if (!noDtorCall)
  8060. {
  8061. bool isConstSize = arraySize.IsConst();
  8062. BfIRBlock clearBlock;
  8063. BfIRBlock contBlock;
  8064. bool wantsDeinit = ((!IsOptimized()) && (!mIsComptimeModule) && (!mBfIRBuilder->mIgnoreWrites) && (!mCompiler->mIsResolveOnly));
  8065. if (wantsDeinit)
  8066. {
  8067. BfIRBlock prevBlock;
  8068. if (!isConstSize)
  8069. {
  8070. clearBlock = mBfIRBuilder->CreateBlock("clear");
  8071. contBlock = mBfIRBuilder->CreateBlock("clearCont");
  8072. prevBlock = mBfIRBuilder->GetInsertBlock();
  8073. mBfIRBuilder->AddBlock(clearBlock);
  8074. mBfIRBuilder->SetInsertPoint(clearBlock);
  8075. }
  8076. auto deferredCall = AddStackAlloc(typedVal, arraySize, NULL, scopeData, false, true);
  8077. if (!isConstSize)
  8078. {
  8079. mBfIRBuilder->CreateBr(contBlock);
  8080. mBfIRBuilder->SetInsertPoint(prevBlock);
  8081. if (deferredCall != NULL)
  8082. {
  8083. // Zero out size args
  8084. for (int i = 1; i < deferredCall->mModuleMethodInstance.mMethodInstance->GetParamCount(); i++)
  8085. {
  8086. auto scopedArg = deferredCall->mScopeArgs[i];
  8087. if (scopedArg != deferredCall->mOrigScopeArgs[i])
  8088. mBfIRBuilder->CreateStore(GetDefaultValue(deferredCall->mModuleMethodInstance.mMethodInstance->GetParamType(i)), deferredCall->mScopeArgs[i]);
  8089. }
  8090. }
  8091. mBfIRBuilder->CreateCondBr(mBfIRBuilder->CreateCmpNE(arraySize, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 0)), clearBlock, contBlock);
  8092. mBfIRBuilder->AddBlock(contBlock);
  8093. mBfIRBuilder->SetInsertPoint(contBlock);
  8094. }
  8095. }
  8096. }
  8097. return result;
  8098. }
  8099. }
  8100. else
  8101. {
  8102. if ((!isDynAlloc) && (!arraySize.IsConst()) && (mCurMethodState->mCurScope->IsLooped(NULL)))
  8103. {
  8104. // Generate and check new size
  8105. BfArrayType* arrayType = CreateArrayType(type, arrayDim);
  8106. auto firstElementField = &arrayType->mFieldInstances.back();
  8107. int arrayClassSize = firstElementField->mDataOffset;
  8108. sizeValue = GetConstValue(arrayClassSize);
  8109. BfIRValue elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySize);
  8110. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, elementDataSize);
  8111. auto loadedPtr = _CreateDynAlloc(sizeValue, arrayType->mAlign);
  8112. auto typedVal = BfTypedValue(mBfIRBuilder->CreateBitCast(loadedPtr, mBfIRBuilder->MapType(arrayType)), arrayType);
  8113. if (!noDtorCall)
  8114. AddStackAlloc(typedVal, BfIRValue(), NULL, scopeData, false, true);
  8115. InitTypeInst(typedVal, scopeData, zeroMemory, sizeValue);
  8116. return typedVal.mValue;
  8117. }
  8118. else
  8119. {
  8120. BfArrayType* arrayType = CreateArrayType(type, arrayDim);
  8121. auto firstElementField = &arrayType->mFieldInstances.back();
  8122. if (!type->IsValuelessType())
  8123. {
  8124. int arrayClassSize = firstElementField->mDataOffset;
  8125. sizeValue = GetConstValue(arrayClassSize);
  8126. BfIRValue elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySize);
  8127. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, elementDataSize);
  8128. }
  8129. else
  8130. sizeValue = GetConstValue(arrayType->mInstSize);
  8131. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  8132. isDynAlloc = (isDynAlloc) || (!sizeValue.IsConst());
  8133. if (!isDynAlloc)
  8134. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  8135. else
  8136. {
  8137. MarkDynStack(scopeData);
  8138. SaveStackState(scopeData);
  8139. }
  8140. BfType* byteType = GetPrimitiveType(BfTypeCode_Int8);
  8141. auto allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(byteType), sizeValue);
  8142. if (!isDynAlloc)
  8143. mBfIRBuilder->ClearDebugLocation(allocaInst);
  8144. auto allocaBlock = mBfIRBuilder->GetInsertBlock();
  8145. mBfIRBuilder->SetAllocaAlignment(allocaInst, allocAlign);
  8146. BfTypedValue typedVal;
  8147. if (!isDynAlloc)
  8148. {
  8149. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRInitBlock);
  8150. typedVal = BfTypedValue(mBfIRBuilder->CreateBitCast(allocaInst, mBfIRBuilder->MapType(arrayType)), arrayType);
  8151. mBfIRBuilder->ClearDebugLocation_Last();
  8152. mBfIRBuilder->SetInsertPoint(prevBlock);
  8153. allocaBlock = mCurMethodState->mIRInitBlock;
  8154. }
  8155. else
  8156. typedVal = BfTypedValue(mBfIRBuilder->CreateBitCast(allocaInst, mBfIRBuilder->MapType(arrayType)), arrayType);
  8157. if (!noDtorCall)
  8158. AddStackAlloc(typedVal, BfIRValue(), NULL, scopeData, false, true, allocaBlock);
  8159. InitTypeInst(typedVal, scopeData, zeroMemory, sizeValue);
  8160. return typedVal.mValue;
  8161. }
  8162. }
  8163. }
  8164. else if (appendSizeValue)
  8165. {
  8166. // It may seem that we should check IsLooped against only the requested scope, BUT- if later on we perform
  8167. // a scoped alloc that crosses our boundary then we won't be able to reclaim the stack space, so we always
  8168. // use the "dynSize" version conservatively
  8169. if ((!isDynAlloc) && (!appendSizeValue.IsConst()) && (mCurMethodState->mCurScope->IsLooped(NULL)))
  8170. {
  8171. // Generate and check new size
  8172. sizeValue = GetConstValue(typeInstance->mInstSize);
  8173. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, appendSizeValue);
  8174. auto loadedPtr = _CreateDynAlloc(sizeValue, typeInstance->mAlign);
  8175. auto typedVal = BfTypedValue(mBfIRBuilder->CreateBitCast(loadedPtr, mBfIRBuilder->MapTypeInstPtr(typeInstance)), typeInstance);
  8176. if (!noDtorCall)
  8177. AddStackAlloc(typedVal, arraySize, NULL, scopeData, mCurMethodState->mInConditionalBlock, true);
  8178. InitTypeInst(typedVal, scopeData, zeroMemory, sizeValue);
  8179. return typedVal.mValue;
  8180. }
  8181. else // stack alloc, unlooped, with append
  8182. {
  8183. sizeValue = GetConstValue(typeInstance->mInstSize);
  8184. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, appendSizeValue);
  8185. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  8186. bool wasDynAlloc = isDynAlloc;
  8187. isDynAlloc = (isDynAlloc) || (!sizeValue.IsConst());
  8188. if (!isDynAlloc)
  8189. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  8190. else
  8191. {
  8192. MarkDynStack(scopeData);
  8193. SaveStackState(scopeData);
  8194. }
  8195. auto sbyteType = GetPrimitiveType(BfTypeCode_Int8);
  8196. auto allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(sbyteType), sizeValue);
  8197. if (!isDynAlloc)
  8198. {
  8199. mBfIRBuilder->ClearDebugLocation(allocaInst);
  8200. }
  8201. mBfIRBuilder->SetAllocaAlignment(allocaInst, allocAlign);
  8202. bool mayBeLarge = false;
  8203. if (sizeValue.IsConst())
  8204. {
  8205. auto constantInt = mBfIRBuilder->GetConstant(sizeValue);
  8206. if (constantInt->mInt64 >= 4096)
  8207. mayBeLarge = true;
  8208. }
  8209. else
  8210. mayBeLarge = true;
  8211. if (((type->IsObject() && (!mayBeLarge))) ||
  8212. // If we create a memset that can fill in backwards (or at least 4k chunked backward) then we can remove the '!mayBeLarge' cond
  8213. ((zeroMemory) && (!mayBeLarge)))
  8214. {
  8215. mBfIRBuilder->SetAllocaNoChkStkHint(allocaInst);
  8216. }
  8217. BfIRValue castedVal;
  8218. if (!isDynAlloc)
  8219. {
  8220. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRInitBlock);
  8221. castedVal = mBfIRBuilder->CreateBitCast(allocaInst, mBfIRBuilder->MapTypeInstPtr(typeInstance));
  8222. mBfIRBuilder->ClearDebugLocation(castedVal);
  8223. mBfIRBuilder->SetInsertPoint(prevBlock);
  8224. if (WantsLifetimes())
  8225. {
  8226. mBfIRBuilder->CreateLifetimeStart(allocaInst);
  8227. scopeData->mDeferredLifetimeEnds.push_back(allocaInst);
  8228. }
  8229. }
  8230. else
  8231. {
  8232. castedVal = mBfIRBuilder->CreateBitCast(allocaInst, mBfIRBuilder->MapTypeInstPtr(typeInstance));
  8233. }
  8234. auto typedVal = BfTypedValue(castedVal, typeInstance);
  8235. if (!noDtorCall)
  8236. {
  8237. bool doCondAlloca = false;
  8238. if (!IsTargetingBeefBackend())
  8239. doCondAlloca = !wasDynAlloc && isDynAlloc && mCurMethodState->mInConditionalBlock;
  8240. AddStackAlloc(typedVal, arraySize, NULL, scopeData, doCondAlloca, true);
  8241. }
  8242. InitTypeInst(typedVal, scopeData, zeroMemory, sizeValue);
  8243. return typedVal.mValue;
  8244. }
  8245. }
  8246. else // "Normal" stack alloc
  8247. {
  8248. BF_ASSERT(!sizeValue);
  8249. //TODO: If sizeValue is a constant then do this in the head IR builder
  8250. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  8251. if (!isLoopedAlloc)
  8252. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  8253. else
  8254. {
  8255. MarkDynStack(scopeData);
  8256. SaveStackState(scopeData);
  8257. }
  8258. auto allocaInst = mBfIRBuilder->CreateAlloca(allocType);
  8259. if (!isLoopedAlloc)
  8260. mBfIRBuilder->ClearDebugLocation(allocaInst);
  8261. mBfIRBuilder->SetAllocaAlignment(allocaInst, allocAlign);
  8262. bool mayBeLarge = allocSize >= 4096;
  8263. if (((typeInstance != NULL) && (typeInstance->IsObject()) && (!mayBeLarge)) ||
  8264. // If we create a memset that can fill in backwards (or at least 4k chunked backward) then we can remove the '!mayBeLarge' cond
  8265. ((zeroMemory) && (!mayBeLarge)))
  8266. {
  8267. // With an object, we know we will at least set the vdata pointer which will probe the start of the new address,
  8268. // and memset is always safe
  8269. mBfIRBuilder->SetAllocaNoChkStkHint(allocaInst);
  8270. }
  8271. auto typedVal = BfTypedValue(allocaInst, type);
  8272. if (!isLoopedAlloc)
  8273. {
  8274. mBfIRBuilder->ClearDebugLocation(allocaInst);
  8275. mBfIRBuilder->SetInsertPoint(prevBlock);
  8276. if (WantsLifetimes())
  8277. {
  8278. mBfIRBuilder->CreateLifetimeStart(allocaInst);
  8279. scopeData->mDeferredLifetimeEnds.push_back(allocaInst);
  8280. }
  8281. }
  8282. if (!noDtorCall)
  8283. AddStackAlloc(typedVal, BfIRValue(), NULL, scopeData, false, true);
  8284. if (typeInstance != NULL)
  8285. {
  8286. InitTypeInst(typedVal, scopeData, zeroMemory, GetConstValue(typeInstance->mInstSize));
  8287. }
  8288. else
  8289. {
  8290. mBfIRBuilder->CreateMemSet(allocaInst, GetConstValue8(0), GetConstValue(allocSize), allocAlign);
  8291. }
  8292. return allocaInst;
  8293. }
  8294. }
  8295. else if (arraySize)
  8296. {
  8297. if (isRawArrayAlloc)
  8298. {
  8299. sizeValue = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySize);
  8300. return AllocBytes(allocTarget.mRefNode, allocTarget, type, sizeValue, GetConstValue(allocAlign), allocFlags);
  8301. }
  8302. else
  8303. {
  8304. BfArrayType* arrayType = CreateArrayType(type, arrayDim);
  8305. typeInstance = arrayType;
  8306. BfIRValue arraySizeMinusOne = mBfIRBuilder->CreateSub(arraySize, GetConstValue(1));
  8307. BfIRValue elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySizeMinusOne);
  8308. appendSizeValue = elementDataSize;
  8309. if (!type->IsSizeAligned())
  8310. {
  8311. appendSizeValue = mBfIRBuilder->CreateAdd(appendSizeValue, GetConstValue(type->GetStride() - type->mSize));
  8312. }
  8313. }
  8314. }
  8315. if ((typeInstance != NULL) && (typeInstance->IsObject()))
  8316. {
  8317. auto vDataRef = GetClassVDataPtr(typeInstance);
  8318. BfIRValue result;
  8319. bool isResultInitialized = false;
  8320. int stackCount = mCompiler->mOptions.mAllocStackCount;
  8321. if (typeInstance->mTypeOptionsIdx != -1)
  8322. {
  8323. auto typeOptions = mSystem->GetTypeOptions(typeInstance->mTypeOptionsIdx);
  8324. stackCount = BfTypeOptions::Apply(stackCount, typeOptions->mAllocStackTraceDepth);
  8325. }
  8326. if (mIsComptimeModule)
  8327. stackCount = 0;
  8328. if (!sizeValue)
  8329. sizeValue = GetConstValue(typeInstance->mInstSize);
  8330. if (appendSizeValue)
  8331. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, appendSizeValue);
  8332. BfIRValue origSizeValue = sizeValue;
  8333. bool isAllocEx = hasCustomAllocator && (stackCount > 1);
  8334. if (isAllocEx)
  8335. {
  8336. auto prepareStackTraceMethod = GetInternalMethod("Dbg_PrepareStackTrace");
  8337. if (prepareStackTraceMethod)
  8338. {
  8339. SizedArray<BfIRValue, 2> irArgs;
  8340. irArgs.Add(sizeValue);
  8341. irArgs.Add(GetConstValue(stackCount));
  8342. auto addlBytes = mBfIRBuilder->CreateCall(prepareStackTraceMethod.mFunc, irArgs);
  8343. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, addlBytes);
  8344. }
  8345. }
  8346. if (allocTarget.mCustomAllocator)
  8347. {
  8348. auto customAlloc = allocTarget.mCustomAllocator.mType->ToTypeInstance();
  8349. // Use AllocObject if we have it, otherwise we just use AllocBytes further down
  8350. if ((customAlloc != NULL) && (GetRawMethodByName(customAlloc, "AllocObject", -1, true, true) != NULL))
  8351. {
  8352. auto classVDataType = ResolveTypeDef(mCompiler->mClassVDataTypeDef);
  8353. mBfIRBuilder->PopulateType(classVDataType);
  8354. auto typeInstType = ResolveTypeDef(mCompiler->mReflectTypeInstanceTypeDef)->ToTypeInstance();
  8355. mBfIRBuilder->PopulateType(typeInstType);
  8356. auto typePtrPtr = mBfIRBuilder->CreateInBoundsGEP(vDataRef, 0, 1); // mType
  8357. auto typePtr = mBfIRBuilder->CreateLoad(typePtrPtr);
  8358. auto typeInstPtr = mBfIRBuilder->CreateBitCast(typePtr, mBfIRBuilder->MapTypeInstPtr(typeInstType));
  8359. BfTypedValueExpression typedValueExpr;
  8360. typedValueExpr.Init(BfTypedValue(typeInstPtr, typeInstType));
  8361. typedValueExpr.mRefNode = allocTarget.mRefNode;
  8362. BfExprEvaluator exprEvaluator(this);
  8363. SizedArray<BfExpression*, 2> argExprs;
  8364. argExprs.push_back(&typedValueExpr);
  8365. BfTypedValueExpression sizeValueExpr;
  8366. sizeValueExpr.Init(BfTypedValue(sizeValue, GetPrimitiveType(BfTypeCode_IntPtr)));
  8367. sizeValueExpr.mRefNode = allocTarget.mRefNode;
  8368. argExprs.push_back(&sizeValueExpr);
  8369. BfSizedArray<BfExpression*> sizedArgExprs(argExprs);
  8370. BfResolvedArgs argValues(&sizedArgExprs);
  8371. exprEvaluator.ResolveArgValues(argValues);
  8372. exprEvaluator.mNoBind = true;
  8373. BfTypedValue allocResult = exprEvaluator.MatchMethod(allocTarget.mRefNode, NULL, allocTarget.mCustomAllocator, false, false, "AllocObject", argValues, BfMethodGenericArguments());
  8374. if (allocResult)
  8375. {
  8376. if ((allocResult.mType->IsVoidPtr()) || (allocResult.mType == mContext->mBfObjectType))
  8377. result = mBfIRBuilder->CreateBitCast(allocResult.mValue, mBfIRBuilder->MapType(typeInstance));
  8378. else
  8379. result = CastToValue(allocTarget.mRefNode, allocResult, typeInstance, BfCastFlags_Explicit);
  8380. isResultInitialized = true;
  8381. }
  8382. }
  8383. }
  8384. bool wasAllocated = false;
  8385. if (!result)
  8386. {
  8387. if (hasCustomAllocator)
  8388. result = AllocBytes(allocTarget.mRefNode, allocTarget, typeInstance, sizeValue, GetConstValue(typeInstance->mInstAlign), (BfAllocFlags)(BfAllocFlags_ZeroMemory | BfAllocFlags_NoDefaultToMalloc));
  8389. else if ((mCompiler->mOptions.mObjectHasDebugFlags) && (!mCompiler->mOptions.mDebugAlloc) && (!mIsComptimeModule))
  8390. {
  8391. SizedArray<BfIRValue, 4> llvmArgs;
  8392. llvmArgs.push_back(sizeValue);
  8393. auto irFunc = GetBuiltInFunc(BfBuiltInFuncType_Malloc);
  8394. result = mBfIRBuilder->CreateCall(irFunc, llvmArgs);
  8395. result = mBfIRBuilder->CreateBitCast(result, mBfIRBuilder->MapTypeInstPtr(typeInstance));
  8396. wasAllocated = true;
  8397. }
  8398. }
  8399. if (result)
  8400. {
  8401. if ((mCompiler->mOptions.mObjectHasDebugFlags) && (!mIsComptimeModule))
  8402. {
  8403. auto objectPtr = mBfIRBuilder->CreateBitCast(result, mBfIRBuilder->MapTypeInstPtr(mContext->mBfObjectType));
  8404. SizedArray<BfIRValue, 4> llvmArgs;
  8405. llvmArgs.push_back(objectPtr);
  8406. llvmArgs.push_back(origSizeValue);
  8407. llvmArgs.push_back(vDataRef);
  8408. auto objectCreatedMethod = GetInternalMethod(isAllocEx ?
  8409. (isResultInitialized ? "Dbg_ObjectCreatedEx" : "Dbg_ObjectAllocatedEx") :
  8410. (isResultInitialized ? "Dbg_ObjectCreated" : "Dbg_ObjectAllocated"));
  8411. mBfIRBuilder->CreateCall(objectCreatedMethod.mFunc, llvmArgs);
  8412. if (wasAllocated)
  8413. {
  8414. auto byteType = GetPrimitiveType(BfTypeCode_UInt8);
  8415. auto bytePtrType = CreatePointerType(byteType);
  8416. auto flagsPtr = mBfIRBuilder->CreateBitCast(result, mBfIRBuilder->MapType(bytePtrType));
  8417. auto flagsVal = mBfIRBuilder->CreateLoad(flagsPtr);
  8418. auto modifiedFlagsVal = mBfIRBuilder->CreateOr(flagsVal, mBfIRBuilder->CreateConst(BfTypeCode_UInt8, /*BF_OBJECTFLAG_ALLOCATED*/4));
  8419. mBfIRBuilder->CreateStore(modifiedFlagsVal, flagsPtr);
  8420. }
  8421. }
  8422. else
  8423. {
  8424. auto ptrType = mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr);
  8425. auto vDataPtr = mBfIRBuilder->CreateBitCast(vDataRef, ptrType);
  8426. auto vDataMemberPtr = mBfIRBuilder->CreateBitCast(result, mBfIRBuilder->GetPointerTo(ptrType));
  8427. mBfIRBuilder->CreateStore(vDataPtr, vDataMemberPtr);
  8428. }
  8429. }
  8430. else
  8431. {
  8432. if ((mBfIRBuilder->mIgnoreWrites) ||
  8433. ((mCompiler->mIsResolveOnly) && (!mIsComptimeModule)))
  8434. return GetDefaultValue(typeInstance);
  8435. auto classVDataType = ResolveTypeDef(mCompiler->mClassVDataTypeDef);
  8436. auto vData = mBfIRBuilder->CreateBitCast(vDataRef, mBfIRBuilder->MapTypeInstPtr(classVDataType->ToTypeInstance()));
  8437. if ((mCompiler->mOptions.mObjectHasDebugFlags) && (!mIsComptimeModule))
  8438. {
  8439. SizedArray<BfIRValue, 4> llvmArgs;
  8440. llvmArgs.push_back(vData);
  8441. llvmArgs.push_back(sizeValue);
  8442. llvmArgs.push_back(GetConstValue(typeInstance->mAlign));
  8443. llvmArgs.push_back(GetConstValue(stackCount));
  8444. auto moduleMethodInstance = GetInternalMethod("Dbg_ObjectAlloc", 4);
  8445. BfIRValue objectVal = mBfIRBuilder->CreateCall(moduleMethodInstance.mFunc, llvmArgs);
  8446. result = mBfIRBuilder->CreateBitCast(objectVal, mBfIRBuilder->MapType(typeInstance));
  8447. }
  8448. else
  8449. {
  8450. SizedArray<BfIRValue, 4> llvmArgs;
  8451. llvmArgs.push_back(sizeValue);
  8452. BfIRFunction irFunc;
  8453. if ((mCompiler->mOptions.mDebugAlloc) && (!mIsComptimeModule))
  8454. {
  8455. auto moduleMethodInstance = GetInternalMethod("Dbg_RawObjectAlloc", 1);
  8456. irFunc = moduleMethodInstance.mFunc;
  8457. }
  8458. if (!irFunc)
  8459. irFunc = GetBuiltInFunc(BfBuiltInFuncType_Malloc);
  8460. BfIRValue objectVal = mBfIRBuilder->CreateCall(irFunc, llvmArgs);
  8461. auto objResult = mBfIRBuilder->CreateBitCast(objectVal, mBfIRBuilder->MapType(mContext->mBfObjectType, BfIRPopulateType_Full));
  8462. auto vdataPtr = mBfIRBuilder->CreateInBoundsGEP(objResult, 0, 0);
  8463. if (mIsComptimeModule)
  8464. {
  8465. vdataPtr = mBfIRBuilder->CreateBitCast(vdataPtr, mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapTypeInstPtr(classVDataType->ToTypeInstance())));
  8466. }
  8467. mBfIRBuilder->CreateStore(vData, vdataPtr);
  8468. result = mBfIRBuilder->CreateBitCast(objectVal, mBfIRBuilder->MapType(typeInstance));
  8469. }
  8470. }
  8471. if ((zeroMemory) && (arraySize))
  8472. {
  8473. BfArrayType* arrayType = CreateArrayType(type, arrayDim);
  8474. typeInstance = arrayType;
  8475. auto firstElementField = &arrayType->mFieldInstances.back();
  8476. int arrayClassSize = firstElementField->mDataOffset;
  8477. BfIRValue elementDataSize;
  8478. bool skipZero = false;
  8479. if (arraySize.IsConst())
  8480. {
  8481. BfIRValue arraySizeMinusOne = mBfIRBuilder->CreateSub(arraySize, GetConstValue(1));
  8482. elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySizeMinusOne);
  8483. elementDataSize = mBfIRBuilder->CreateAdd(elementDataSize, GetConstValue(type->mSize));
  8484. auto constVal = mBfIRBuilder->GetConstant(elementDataSize);
  8485. if (constVal->mInt64 <= 0)
  8486. skipZero = true;
  8487. }
  8488. else
  8489. {
  8490. // For non const, don't use an unpadded last element - saves us checking against negative numbers going into memset for the zero-length case
  8491. elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySize);
  8492. }
  8493. if (!skipZero)
  8494. {
  8495. auto i8Type = GetPrimitiveType(BfTypeCode_Int8);
  8496. auto ptrType = CreatePointerType(i8Type);
  8497. auto ptrVal = mBfIRBuilder->CreateBitCast(result, mBfIRBuilder->MapType(ptrType));
  8498. ptrVal = mBfIRBuilder->CreateInBoundsGEP(ptrVal, arrayClassSize);
  8499. mBfIRBuilder->CreateMemSet(ptrVal, GetConstValue8(0), elementDataSize, type->mAlign);
  8500. appendSizeValue = elementDataSize;
  8501. }
  8502. }
  8503. return result;
  8504. }
  8505. else
  8506. {
  8507. if (!sizeValue)
  8508. sizeValue = GetConstValue(allocSize);
  8509. return AllocBytes(allocTarget.mRefNode, allocTarget, type, sizeValue, GetConstValue(allocAlign), zeroMemory ? BfAllocFlags_ZeroMemory : BfAllocFlags_None);
  8510. }
  8511. }
  8512. void BfModule::ValidateAllocation(BfType* type, BfAstNode* refNode)
  8513. {
  8514. if ((type == NULL) || (refNode == NULL))
  8515. return;
  8516. auto typeInstance = type->ToTypeInstance();
  8517. if ((typeInstance != NULL) && (typeInstance->mTypeDef->mIsOpaque))
  8518. Fail(StrFormat("Unable to allocate opaque type '%s'", TypeToString(type).c_str()), refNode);
  8519. }
  8520. void BfModule::EmitAlign(BfIRValue& appendCurIdx, int align)
  8521. {
  8522. appendCurIdx = mBfIRBuilder->CreateAdd(appendCurIdx, GetConstValue(align - 1));
  8523. appendCurIdx = mBfIRBuilder->CreateAnd(appendCurIdx, GetConstValue(~(align - 1)));
  8524. }
  8525. void BfModule::EmitAppendAlign(int align, int sizeMultiple)
  8526. {
  8527. if (sizeMultiple == 0)
  8528. sizeMultiple = align;
  8529. if ((mCurMethodState->mCurAppendAlign != 0) && (mCurMethodState->mCurAppendAlign % align != 0))
  8530. {
  8531. if (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_Ctor)
  8532. {
  8533. auto localVar = mCurMethodState->GetRootMethodState()->mLocals[1];
  8534. BF_ASSERT(localVar->mName == "appendIdx");
  8535. auto appendIdxVal = BfTypedValue(localVar->mValue, localVar->mResolvedType, true);
  8536. BfIRValue appendCurIdx = mBfIRBuilder->CreateLoad(appendIdxVal.mValue);
  8537. if (align > 1)
  8538. {
  8539. appendCurIdx = mBfIRBuilder->CreateAdd(appendCurIdx, GetConstValue(align - 1));
  8540. appendCurIdx = mBfIRBuilder->CreateAnd(appendCurIdx, GetConstValue(~(align - 1)));
  8541. }
  8542. mBfIRBuilder->CreateStore(appendCurIdx, appendIdxVal.mValue);
  8543. }
  8544. else
  8545. {
  8546. BF_ASSERT(mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend);
  8547. BfIRValue appendCurIdxPtr = mCurMethodState->mRetVal.mValue;
  8548. BfIRValue appendCurIdx = mBfIRBuilder->CreateLoad(appendCurIdxPtr);
  8549. appendCurIdx = mBfIRBuilder->CreateAdd(appendCurIdx, GetConstValue(align - 1));
  8550. appendCurIdx = mBfIRBuilder->CreateAnd(appendCurIdx, GetConstValue(~(align - 1)));
  8551. mBfIRBuilder->CreateStore(appendCurIdx, appendCurIdxPtr);
  8552. }
  8553. }
  8554. if (mCurMethodState->mCurAppendAlign == 0)
  8555. mCurMethodState->mCurAppendAlign = sizeMultiple;
  8556. else
  8557. {
  8558. if (sizeMultiple % align == 0)
  8559. mCurMethodState->mCurAppendAlign = align;
  8560. else
  8561. mCurMethodState->mCurAppendAlign = sizeMultiple % align;
  8562. }
  8563. }
  8564. BfIRValue BfModule::AppendAllocFromType(BfType* type, BfIRValue appendSizeValue, int appendAllocAlign, BfIRValue arraySize, int arrayDim, bool isRawArrayAlloc, bool zeroMemory)
  8565. {
  8566. auto localVar = mCurMethodState->GetRootMethodState()->mLocals[1];
  8567. BF_ASSERT(localVar->mName == "appendIdx");
  8568. BfTypedValue appendIdxVal(localVar->mValue, localVar->mResolvedType, true);
  8569. BfIRValue retValue;
  8570. BfTypeInstance* retTypeInstance = NULL;
  8571. auto intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  8572. auto voidPtrType = GetPrimitiveType(BfTypeCode_NullPtr);
  8573. if (arraySize)
  8574. {
  8575. if (isRawArrayAlloc)
  8576. {
  8577. EmitAppendAlign(type->mAlign);
  8578. BfPointerType* ptrType = CreatePointerType(type);
  8579. BfIRValue sizeValue = mBfIRBuilder->CreateMul(GetConstValue(type->mSize), arraySize);
  8580. auto curIdxVal = mBfIRBuilder->CreateLoad(appendIdxVal.mValue);
  8581. if (mSystem->mPtrSize != 4)
  8582. sizeValue = mBfIRBuilder->CreateNumericCast(sizeValue, true, (intPtrType->mSize == 4) ? BfTypeCode_Int32 : BfTypeCode_Int64);
  8583. auto newIdxVal = mBfIRBuilder->CreateAdd(curIdxVal, sizeValue);
  8584. mBfIRBuilder->CreateStore(newIdxVal, appendIdxVal.mValue);
  8585. if (zeroMemory)
  8586. {
  8587. auto ptr = mBfIRBuilder->CreateIntToPtr(curIdxVal, mBfIRBuilder->MapType(voidPtrType));
  8588. mBfIRBuilder->CreateMemSet(ptr, GetConstValue8(0), sizeValue, type->mAlign);
  8589. }
  8590. return mBfIRBuilder->CreateIntToPtr(curIdxVal, mBfIRBuilder->MapType(ptrType));
  8591. }
  8592. else
  8593. {
  8594. BfArrayType* arrayType = CreateArrayType(type, arrayDim);
  8595. EmitAppendAlign(arrayType->mAlign, type->mSize);
  8596. auto firstElementField = &arrayType->mFieldInstances.back();
  8597. int arrayClassSize = arrayType->mInstSize - firstElementField->mDataSize;
  8598. BfIRValue sizeValue = GetConstValue(arrayClassSize);
  8599. BfIRValue elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->mSize), arraySize);
  8600. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, elementDataSize);
  8601. auto curIdxVal = mBfIRBuilder->CreateLoad(appendIdxVal.mValue);
  8602. if (mSystem->mPtrSize != 4)
  8603. sizeValue = mBfIRBuilder->CreateNumericCast(sizeValue, true, (intPtrType->mSize == 4) ? BfTypeCode_Int32 : BfTypeCode_Int64);
  8604. auto newIdxVal = mBfIRBuilder->CreateAdd(curIdxVal, sizeValue);
  8605. mBfIRBuilder->CreateStore(newIdxVal, appendIdxVal.mValue);
  8606. if (zeroMemory)
  8607. {
  8608. // Only zero out the actual elements
  8609. int dataOffset = arrayType->mFieldInstances.back().mDataOffset;
  8610. auto newOffset = mBfIRBuilder->CreateAdd(curIdxVal, GetConstValue(dataOffset));
  8611. auto newSize = mBfIRBuilder->CreateSub(sizeValue, GetConstValue(dataOffset));
  8612. auto ptr = mBfIRBuilder->CreateIntToPtr(newOffset, mBfIRBuilder->MapType(voidPtrType));
  8613. mBfIRBuilder->CreateMemSet(ptr, GetConstValue8(0), newSize, type->mAlign);
  8614. }
  8615. retTypeInstance = arrayType;
  8616. retValue = mBfIRBuilder->CreateIntToPtr(curIdxVal, mBfIRBuilder->MapType(arrayType));
  8617. }
  8618. }
  8619. else
  8620. {
  8621. auto typeInst = type->ToTypeInstance();
  8622. BfIRValue sizeValue;
  8623. BfIRType toType;
  8624. if (typeInst != NULL)
  8625. {
  8626. EmitAppendAlign(typeInst->mInstAlign, typeInst->mInstSize);
  8627. sizeValue = GetConstValue(typeInst->mInstSize);
  8628. toType = mBfIRBuilder->MapTypeInstPtr(typeInst);
  8629. }
  8630. else
  8631. {
  8632. EmitAppendAlign(type->mAlign, type->mSize);
  8633. sizeValue = GetConstValue(type->mSize);
  8634. auto toPtrType = CreatePointerType(type);
  8635. toType = mBfIRBuilder->MapType(toPtrType);
  8636. }
  8637. auto curIdxVal = mBfIRBuilder->CreateLoad(appendIdxVal.mValue);
  8638. auto newIdxVal = mBfIRBuilder->CreateAdd(curIdxVal, sizeValue);
  8639. mBfIRBuilder->CreateStore(newIdxVal, appendIdxVal.mValue);
  8640. retTypeInstance = typeInst;
  8641. retValue = mBfIRBuilder->CreateIntToPtr(curIdxVal, toType);
  8642. }
  8643. if ((retTypeInstance != NULL) && (retTypeInstance->IsObject()))
  8644. {
  8645. mBfIRBuilder->PopulateType(retTypeInstance);
  8646. auto int8Type = mBfIRBuilder->GetPrimitiveType(BfTypeCode_Int8);
  8647. auto ptrType = mBfIRBuilder->GetPointerTo(int8Type);
  8648. auto ptrPtrType = mBfIRBuilder->GetPointerTo(ptrType);
  8649. auto curThis = GetThis();
  8650. BfIRValue newFlags;
  8651. if ((mCompiler->mOptions.mObjectHasDebugFlags) && (!mIsComptimeModule))
  8652. {
  8653. auto thisFlagsPtr = mBfIRBuilder->CreateBitCast(curThis.mValue, ptrType);
  8654. auto thisFlags = mBfIRBuilder->CreateLoad(thisFlagsPtr);
  8655. auto maskedThisFlags = mBfIRBuilder->CreateAnd(thisFlags, GetConstValue8(BfObjectFlag_StackAlloc)); // Take 'stack' flag from 'this'
  8656. newFlags = mBfIRBuilder->CreateOr(maskedThisFlags, GetConstValue8(BfObjectFlag_AppendAlloc));
  8657. }
  8658. auto vObjectAddr = mBfIRBuilder->CreateInBoundsGEP(retValue, 0, 0);
  8659. auto vDataRef = CreateClassVDataGlobal(retTypeInstance);
  8660. auto destAddr = mBfIRBuilder->CreateBitCast(vObjectAddr, ptrPtrType);
  8661. auto srcVal = mBfIRBuilder->CreateBitCast(vDataRef, ptrType);
  8662. mBfIRBuilder->CreateStore(srcVal, destAddr);
  8663. if ((mCompiler->mOptions.mObjectHasDebugFlags) && (!mIsComptimeModule))
  8664. {
  8665. auto flagsPtr = mBfIRBuilder->CreateBitCast(destAddr, ptrType);
  8666. mBfIRBuilder->CreateStore(newFlags, flagsPtr);
  8667. }
  8668. }
  8669. if (appendSizeValue)
  8670. {
  8671. EmitAppendAlign(appendAllocAlign);
  8672. auto curIdxVal = mBfIRBuilder->CreateLoad(appendIdxVal.mValue);
  8673. auto newIdxVal = mBfIRBuilder->CreateAdd(curIdxVal, appendSizeValue);
  8674. mBfIRBuilder->CreateStore(newIdxVal, appendIdxVal.mValue);
  8675. }
  8676. return retValue;
  8677. }
  8678. bool BfModule::IsOptimized()
  8679. {
  8680. if (mProject == NULL)
  8681. return false;
  8682. int optLevel = GetModuleOptions().mOptLevel;
  8683. return (optLevel >= BfOptLevel_O1) && (optLevel <= BfOptLevel_O3);
  8684. }
  8685. bool BfModule::IsTargetingBeefBackend()
  8686. {
  8687. if (mProject == NULL)
  8688. return true;
  8689. return GetModuleOptions().mOptLevel == BfOptLevel_OgPlus;
  8690. }
  8691. bool BfModule::WantsLifetimes()
  8692. {
  8693. if (mProject == NULL)
  8694. return false;
  8695. if (mBfIRBuilder->mIgnoreWrites)
  8696. return false;
  8697. return GetModuleOptions().mOptLevel == BfOptLevel_OgPlus;
  8698. }
  8699. bool BfModule::HasCompiledOutput()
  8700. {
  8701. return (!mSystem->mIsResolveOnly) && (mGeneratesCode) && (!mIsComptimeModule);
  8702. }
  8703. bool BfModule::HasExecutedOutput()
  8704. {
  8705. return ((!mSystem->mIsResolveOnly) && (mGeneratesCode)) || (mIsComptimeModule);
  8706. }
  8707. // We will skip the object access check for any occurrences of this value
  8708. void BfModule::SkipObjectAccessCheck(BfTypedValue typedVal)
  8709. {
  8710. if ((mBfIRBuilder->mIgnoreWrites) || (!typedVal.mType->IsObjectOrInterface()) || (mCurMethodState == NULL) || (mCurMethodState->mIgnoreObjectAccessCheck))
  8711. return;
  8712. if ((!mCompiler->mOptions.mObjectHasDebugFlags) || (mIsComptimeModule))
  8713. return;
  8714. if ((typedVal.mValue.mFlags & BfIRValueFlags_Value) == 0)
  8715. return;
  8716. mCurMethodState->mSkipObjectAccessChecks.Add(typedVal.mValue.mId);
  8717. }
  8718. void BfModule::EmitObjectAccessCheck(BfTypedValue typedVal)
  8719. {
  8720. if ((mBfIRBuilder->mIgnoreWrites) || (!typedVal.mType->IsObjectOrInterface()) || (mCurMethodState == NULL) || (mCurMethodState->mIgnoreObjectAccessCheck))
  8721. return;
  8722. if ((!mCompiler->mOptions.mObjectHasDebugFlags) || (mIsComptimeModule))
  8723. return;
  8724. if (typedVal.mValue.IsConst())
  8725. {
  8726. int stringIdx = GetStringPoolIdx(typedVal.mValue, mBfIRBuilder);
  8727. if (stringIdx != -1)
  8728. return;
  8729. auto constant = mBfIRBuilder->GetConstant(typedVal.mValue);
  8730. if (constant->mTypeCode == BfTypeCode_NullPtr)
  8731. return;
  8732. if (constant->mConstType == BfConstType_BitCastNull)
  8733. return;
  8734. }
  8735. bool emitObjectAccessCheck = mCompiler->mOptions.mEmitObjectAccessCheck;
  8736. auto typeOptions = GetTypeOptions();
  8737. if (typeOptions != NULL)
  8738. emitObjectAccessCheck = typeOptions->Apply(emitObjectAccessCheck, BfOptionFlags_EmitObjectAccessCheck);
  8739. if (!emitObjectAccessCheck)
  8740. return;
  8741. if ((typedVal.mValue.mFlags & BfIRValueFlags_Value) != 0)
  8742. {
  8743. if (mCurMethodState->mSkipObjectAccessChecks.Contains(typedVal.mValue.mId))
  8744. return;
  8745. }
  8746. if (typedVal.IsAddr())
  8747. typedVal = LoadValue(typedVal);
  8748. mBfIRBuilder->CreateObjectAccessCheck(typedVal.mValue, !IsOptimized());
  8749. }
  8750. void BfModule::EmitEnsureInstructionAt()
  8751. {
  8752. if (mProject == NULL)
  8753. return;
  8754. if ((mBfIRBuilder->mIgnoreWrites) || (!mHasFullDebugInfo) || (IsOptimized()) || (mCompiler->mOptions.mOmitDebugHelpers))
  8755. return;
  8756. mBfIRBuilder->CreateEnsureInstructionAt();
  8757. }
  8758. void BfModule::EmitDynamicCastCheck(const BfTypedValue& targetValue, BfType* targetType, BfIRBlock trueBlock, BfIRBlock falseBlock, bool nullSucceeds)
  8759. {
  8760. if (mBfIRBuilder->mIgnoreWrites)
  8761. return; // Nothing needed here
  8762. auto irb = mBfIRBuilder;
  8763. auto checkBB = irb->CreateBlock("as.check");
  8764. auto isNull = irb->CreateIsNull(targetValue.mValue);
  8765. mBfIRBuilder->CreateCondBr(isNull, nullSucceeds ? trueBlock : falseBlock, checkBB);
  8766. if (mIsComptimeModule)
  8767. {
  8768. AddBasicBlock(checkBB);
  8769. auto callResult = mBfIRBuilder->Comptime_DynamicCastCheck(targetValue.mValue, targetType->mTypeId, mBfIRBuilder->MapType(mContext->mBfObjectType));
  8770. auto cmpResult = mBfIRBuilder->CreateCmpNE(callResult, GetDefaultValue(mContext->mBfObjectType));
  8771. irb->CreateCondBr(cmpResult, trueBlock, falseBlock);
  8772. return;
  8773. }
  8774. auto intType = GetPrimitiveType(BfTypeCode_IntPtr);
  8775. auto intPtrType = CreatePointerType(intType);
  8776. auto intPtrPtrType = CreatePointerType(intPtrType);
  8777. auto int32Type = GetPrimitiveType(BfTypeCode_Int32);
  8778. auto int32PtrType = CreatePointerType(int32Type);
  8779. auto typeTypeInstance = ResolveTypeDef(mCompiler->mReflectTypeInstanceTypeDef)->ToTypeInstance();
  8780. if (mCompiler->mOptions.mAllowHotSwapping)
  8781. {
  8782. BfExprEvaluator exprEvaluator(this);
  8783. AddBasicBlock(checkBB);
  8784. auto objectParam = mBfIRBuilder->CreateBitCast(targetValue.mValue, mBfIRBuilder->MapType(mContext->mBfObjectType));
  8785. auto moduleMethodInstance = GetMethodByName(mContext->mBfObjectType, targetType->IsInterface() ? "DynamicCastToInterface" : "DynamicCastToTypeId");
  8786. SizedArray<BfIRValue, 4> irArgs;
  8787. irArgs.push_back(objectParam);
  8788. irArgs.push_back(GetConstValue32(targetType->mTypeId));
  8789. auto callResult = exprEvaluator.CreateCall(NULL, moduleMethodInstance.mMethodInstance, moduleMethodInstance.mFunc, false, irArgs);
  8790. auto cmpResult = mBfIRBuilder->CreateCmpNE(callResult.mValue, GetDefaultValue(callResult.mType));
  8791. irb->CreateCondBr(cmpResult, trueBlock, falseBlock);
  8792. }
  8793. else
  8794. {
  8795. AddBasicBlock(checkBB);
  8796. BfIRValue vDataPtr = irb->CreateBitCast(targetValue.mValue, irb->MapType(intPtrType));
  8797. vDataPtr = irb->CreateLoad(vDataPtr);
  8798. if ((mCompiler->mOptions.mObjectHasDebugFlags) && (!mIsComptimeModule))
  8799. vDataPtr = irb->CreateAnd(vDataPtr, irb->CreateConst(BfTypeCode_IntPtr, (uint64)~0xFFULL));
  8800. if (targetType->IsInterface())
  8801. {
  8802. auto targetTypeInst = targetType->ToTypeInstance();
  8803. AddDependency(targetType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ExprTypeReference);
  8804. // Skip past mType, but since a 'GetDynCastVDataCount()' data is included in the sSlotOfs, we need to remove that
  8805. //int inheritanceIdOfs = mSystem->mPtrSize - (mCompiler->GetDynCastVDataCount())*4;
  8806. //vDataPtr = irb->CreateAdd(vDataPtr, irb->CreateConst(BfTypeCode_IntPtr, inheritanceIdOfs));
  8807. vDataPtr = irb->CreateAdd(vDataPtr, irb->GetConfigConst(BfIRConfigConst_DynSlotOfs, BfTypeCode_IntPtr));
  8808. BfIRValue slotOfs = GetInterfaceSlotNum(targetType->ToTypeInstance());
  8809. BfIRValue slotByteOfs = irb->CreateMul(slotOfs, irb->CreateConst(BfTypeCode_Int32, 4));
  8810. slotByteOfs = irb->CreateNumericCast(slotByteOfs, false, BfTypeCode_IntPtr);
  8811. vDataPtr = irb->CreateAdd(vDataPtr, slotByteOfs);
  8812. vDataPtr = irb->CreateIntToPtr(vDataPtr, irb->MapType(int32PtrType));
  8813. BfIRValue typeId = irb->CreateLoad(vDataPtr);
  8814. BfIRValue cmpResult = irb->CreateCmpEQ(typeId, irb->CreateConst(BfTypeCode_Int32, targetType->mTypeId));
  8815. irb->CreateCondBr(cmpResult, trueBlock, falseBlock);
  8816. }
  8817. else
  8818. {
  8819. if (!targetType->IsTypeInstance())
  8820. targetType = GetWrappedStructType(targetType);
  8821. AddDependency(targetType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ExprTypeReference);
  8822. int inheritanceIdOfs = mSystem->mPtrSize;
  8823. vDataPtr = irb->CreateAdd(vDataPtr, irb->CreateConst(BfTypeCode_IntPtr, inheritanceIdOfs));
  8824. vDataPtr = irb->CreateIntToPtr(vDataPtr, irb->MapType(int32PtrType));
  8825. BfIRValue objInheritanceId = irb->CreateLoad(vDataPtr);
  8826. BfIRValue typeDataRef = CreateTypeDataRef(targetType);
  8827. BfIRValue typeInstDataRef = irb->CreateBitCast(typeDataRef, irb->MapType(typeTypeInstance, BfIRPopulateType_Full));
  8828. auto fieldInst = &typeTypeInstance->mFieldInstances[9];
  8829. BF_ASSERT(fieldInst->GetFieldDef()->mName == "mInheritanceId");
  8830. BfIRValue gepValue = irb->CreateInBoundsGEP(typeInstDataRef, 0, fieldInst->mDataIdx);
  8831. BfIRValue wantInheritanceId = irb->CreateLoad(gepValue);
  8832. fieldInst = &typeTypeInstance->mFieldInstances[10];
  8833. BF_ASSERT(fieldInst->GetFieldDef()->mName == "mInheritanceCount");
  8834. gepValue = irb->CreateInBoundsGEP(typeInstDataRef, 0, fieldInst->mDataIdx);
  8835. BfIRValue inheritanceCount = irb->CreateLoad(gepValue);
  8836. BfIRValue idDiff = irb->CreateSub(objInheritanceId, wantInheritanceId);
  8837. BfIRValue cmpResult = irb->CreateCmpLTE(idDiff, inheritanceCount, false);
  8838. irb->CreateCondBr(cmpResult, trueBlock, falseBlock);
  8839. }
  8840. }
  8841. }
  8842. void BfModule::EmitDynamicCastCheck(BfTypedValue typedVal, BfType* type, bool allowNull)
  8843. {
  8844. if (mBfIRBuilder->mIgnoreWrites)
  8845. return;
  8846. bool emitDynamicCastCheck = mCompiler->mOptions.mEmitDynamicCastCheck;
  8847. auto typeOptions = GetTypeOptions();
  8848. if (typeOptions != NULL)
  8849. emitDynamicCastCheck = typeOptions->Apply(emitDynamicCastCheck, BfOptionFlags_EmitDynamicCastCheck);
  8850. if (emitDynamicCastCheck)
  8851. {
  8852. int wantTypeId = 0;
  8853. if (!type->IsGenericParam())
  8854. wantTypeId = type->mTypeId;
  8855. BfIRBlock failBlock = mBfIRBuilder->CreateBlock("dynFail");
  8856. BfIRBlock endBlock = mBfIRBuilder->CreateBlock("dynEnd");
  8857. EmitDynamicCastCheck(typedVal, type, endBlock, failBlock, allowNull ? true : false);
  8858. AddBasicBlock(failBlock);
  8859. if (mIsComptimeModule)
  8860. {
  8861. mBfIRBuilder->Comptime_Error(CeErrorKind_ObjectDynCheckFailed);
  8862. }
  8863. else
  8864. {
  8865. SizedArray<BfIRValue, 8> llvmArgs;
  8866. auto bitAddr = mBfIRBuilder->CreateBitCast(typedVal.mValue, mBfIRBuilder->MapType(mContext->mBfObjectType));
  8867. llvmArgs.push_back(bitAddr);
  8868. llvmArgs.push_back(GetConstValue32(wantTypeId));
  8869. auto objDynCheck = GetInternalMethod("ObjectDynCheckFailed");
  8870. BF_ASSERT(objDynCheck);
  8871. if (objDynCheck)
  8872. {
  8873. auto callInst = mBfIRBuilder->CreateCall(objDynCheck.mFunc, llvmArgs);
  8874. }
  8875. }
  8876. mBfIRBuilder->CreateBr(endBlock);
  8877. AddBasicBlock(endBlock);
  8878. }
  8879. }
  8880. BfTypedValue BfModule::BoxValue(BfAstNode* srcNode, BfTypedValue typedVal, BfType* toType, const BfAllocTarget& allocTarget, BfCastFlags castFlags)
  8881. {
  8882. bool callDtor = (castFlags & BfCastFlags_NoBoxDtor) == 0;
  8883. bool wantConst = ((castFlags & BfCastFlags_WantsConst) != 0) && (typedVal.mValue.IsConst());
  8884. if ((mBfIRBuilder->mIgnoreWrites) && (!wantConst))
  8885. {
  8886. if (toType == mContext->mBfObjectType)
  8887. return BfTypedValue(mBfIRBuilder->GetFakeVal(), toType);
  8888. if (toType->IsBoxed())
  8889. {
  8890. BfBoxedType* boxedType = (BfBoxedType*)toType;
  8891. if (boxedType->mElementType->IsGenericParam())
  8892. {
  8893. if (typedVal.mType == boxedType->mElementType)
  8894. return BfTypedValue(mBfIRBuilder->GetFakeVal(), toType);
  8895. else
  8896. return BfTypedValue();
  8897. }
  8898. }
  8899. }
  8900. BP_ZONE("BoxValue");
  8901. BfTypeInstance* fromStructTypeInstance = typedVal.mType->ToTypeInstance();
  8902. if (typedVal.mType->IsNullable())
  8903. {
  8904. typedVal = MakeAddressable(typedVal);
  8905. auto innerType = typedVal.mType->GetUnderlyingType();
  8906. if (!innerType->IsValueType())
  8907. {
  8908. if (!mIgnoreErrors)
  8909. Fail("Only value types can be boxed", srcNode);
  8910. return BfTypedValue();
  8911. }
  8912. auto boxedType = CreateBoxedType(innerType);
  8913. auto resultType = toType;
  8914. if (resultType == NULL)
  8915. resultType = boxedType;
  8916. if (mBfIRBuilder->mIgnoreWrites)
  8917. return BfTypedValue(mBfIRBuilder->GetFakeVal(), resultType);
  8918. auto prevBB = mBfIRBuilder->GetInsertBlock();
  8919. auto boxBB = mBfIRBuilder->CreateBlock("boxedN.notNull");
  8920. auto endBB = mBfIRBuilder->CreateBlock("boxedN.end");
  8921. mBfIRBuilder->PopulateType(typedVal.mType);
  8922. auto hasValueAddr = mBfIRBuilder->CreateInBoundsGEP(typedVal.mValue, 0, innerType->IsValuelessType() ? 1 : 2); // has_value
  8923. auto hasValue = mBfIRBuilder->CreateLoad(hasValueAddr);
  8924. mBfIRBuilder->CreateCondBr(hasValue, boxBB, endBB);
  8925. AddDependency(boxedType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ReadFields);
  8926. mBfIRBuilder->AddBlock(boxBB);
  8927. mBfIRBuilder->SetInsertPoint(boxBB);
  8928. BfScopeData newScope;
  8929. newScope.mOuterIsConditional = true;
  8930. mCurMethodState->AddScope(&newScope);
  8931. NewScopeState();
  8932. BfIRValue nullableValueAddr;
  8933. BfIRValue loadedVal;
  8934. if (innerType->IsValuelessType())
  8935. {
  8936. loadedVal = mBfIRBuilder->GetFakeVal();
  8937. }
  8938. else
  8939. {
  8940. nullableValueAddr = mBfIRBuilder->CreateInBoundsGEP(typedVal.mValue, 0, 1); // value
  8941. loadedVal = mBfIRBuilder->CreateLoad(nullableValueAddr);
  8942. }
  8943. auto boxedVal = BoxValue(srcNode, BfTypedValue(loadedVal, fromStructTypeInstance->GetUnderlyingType()), resultType, allocTarget, callDtor ? BfCastFlags_None : BfCastFlags_NoBoxDtor);
  8944. RestoreScopeState();
  8945. if (!boxedVal)
  8946. return BfTypedValue();
  8947. mBfIRBuilder->CreateBr(endBB);
  8948. auto boxBBEnd = mBfIRBuilder->GetInsertBlock();
  8949. mBfIRBuilder->AddBlock(endBB);
  8950. mBfIRBuilder->SetInsertPoint(endBB);
  8951. auto phi = mBfIRBuilder->CreatePhi(mBfIRBuilder->MapType(resultType), 2);
  8952. mBfIRBuilder->AddPhiIncoming(phi, boxedVal.mValue, boxBBEnd);
  8953. mBfIRBuilder->AddPhiIncoming(phi, GetDefaultValue(resultType), prevBB);
  8954. return BfTypedValue(phi, resultType);
  8955. }
  8956. bool alreadyCheckedCast = false;
  8957. BfTypeInstance* toTypeInstance = NULL;
  8958. if (toType != NULL)
  8959. toTypeInstance = toType->ToTypeInstance();
  8960. bool isStructPtr = typedVal.mType->IsStructPtr();
  8961. if (fromStructTypeInstance == NULL)
  8962. {
  8963. auto primType = (BfPrimitiveType*)typedVal.mType;
  8964. if ((typedVal.mType->IsPointer()) && (toTypeInstance->IsInstanceOf(mCompiler->mIHashableTypeDef)))
  8965. {
  8966. // Can always do IHashable
  8967. alreadyCheckedCast = true;
  8968. }
  8969. if ((!typedVal.mType->IsPointer()) || (toTypeInstance == mContext->mBfObjectType))
  8970. fromStructTypeInstance = GetWrappedStructType(typedVal.mType);
  8971. else
  8972. {
  8973. auto checkStructTypeInstance = GetWrappedStructType(typedVal.mType);
  8974. if (checkStructTypeInstance == toType->GetUnderlyingType())
  8975. fromStructTypeInstance = checkStructTypeInstance;
  8976. }
  8977. if (isStructPtr)
  8978. {
  8979. if ((toTypeInstance != NULL) && (fromStructTypeInstance != NULL) && (TypeIsSubTypeOf(fromStructTypeInstance, toTypeInstance)))
  8980. alreadyCheckedCast = true;
  8981. fromStructTypeInstance = typedVal.mType->GetUnderlyingType()->ToTypeInstance();
  8982. }
  8983. if ((fromStructTypeInstance == NULL) && (alreadyCheckedCast))
  8984. fromStructTypeInstance = GetWrappedStructType(typedVal.mType);
  8985. }
  8986. if (fromStructTypeInstance == NULL)
  8987. return BfTypedValue();
  8988. // Need to box it
  8989. bool isBoxedType = (fromStructTypeInstance != NULL) && (toType->IsBoxed());
  8990. if ((toType == NULL) || (toType == mContext->mBfObjectType) || (isBoxedType) || (alreadyCheckedCast) || (TypeIsSubTypeOf(fromStructTypeInstance, toTypeInstance)))
  8991. {
  8992. if ((mBfIRBuilder->mIgnoreWrites) && (!wantConst))
  8993. return BfTypedValue(mBfIRBuilder->GetFakeVal(), (toType != NULL) ? toType : CreateBoxedType(typedVal.mType));
  8994. auto boxedType = CreateBoxedType(typedVal.mType);
  8995. mBfIRBuilder->PopulateType(boxedType);
  8996. if (wantConst)
  8997. return BfTypedValue(mBfIRBuilder->CreateConstBox(typedVal.mValue, mBfIRBuilder->MapType(boxedType)), boxedType);
  8998. AddDependency(boxedType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ReadFields);
  8999. auto allocaInst = AllocFromType(boxedType, allocTarget, BfIRValue(), BfIRValue(), 0, callDtor ? BfAllocFlags_None : BfAllocFlags_NoDtorCall);
  9000. BfTypedValue boxedTypedValue(allocaInst, boxedType);
  9001. mBfIRBuilder->SetName(allocaInst, "boxed." + fromStructTypeInstance->mTypeDef->mName->ToString());
  9002. if (boxedType->IsUnspecializedType())
  9003. {
  9004. BF_ASSERT((srcNode == NULL) || (mCurMethodInstance->mIsUnspecialized));
  9005. }
  9006. else
  9007. {
  9008. PopulateType(fromStructTypeInstance);
  9009. if (!fromStructTypeInstance->IsValuelessType())
  9010. {
  9011. typedVal = LoadValue(typedVal);
  9012. auto valPtr = mBfIRBuilder->CreateInBoundsGEP(allocaInst, 0, 1);
  9013. if ((typedVal.mType != fromStructTypeInstance) && (!isStructPtr))
  9014. {
  9015. auto ptrType = CreatePointerType(typedVal.mType);
  9016. valPtr = mBfIRBuilder->CreateBitCast(valPtr, mBfIRBuilder->MapType(ptrType));
  9017. }
  9018. if (typedVal.IsSplat())
  9019. {
  9020. AggregateSplatIntoAddr(typedVal, valPtr);
  9021. }
  9022. else
  9023. mBfIRBuilder->CreateStore(typedVal.mValue, valPtr);
  9024. }
  9025. }
  9026. if (toType == NULL)
  9027. {
  9028. return BfTypedValue(allocaInst, boxedType);
  9029. }
  9030. else
  9031. {
  9032. auto castedValue = mBfIRBuilder->CreateBitCast(allocaInst, mBfIRBuilder->MapType(toType));
  9033. return BfTypedValue(castedValue, toType);
  9034. }
  9035. }
  9036. return BfTypedValue();
  9037. }
  9038. bool BfModule::GetBasePropertyDef(BfPropertyDef*& propDef, BfTypeInstance*& typeInst)
  9039. {
  9040. BfTypeInstance* checkTypeInst = typeInst;
  9041. while (checkTypeInst != NULL)
  9042. {
  9043. for (auto checkProp : checkTypeInst->mTypeDef->mProperties)
  9044. {
  9045. if (checkProp->mName == propDef->mName)
  9046. {
  9047. auto checkPropDeclaration = BfNodeDynCast<BfPropertyDeclaration>(checkProp->mFieldDeclaration);
  9048. if ((checkPropDeclaration == NULL) || (checkPropDeclaration->mVirtualSpecifier == NULL) || (checkPropDeclaration->mVirtualSpecifier->GetToken() == BfToken_Virtual))
  9049. {
  9050. propDef = checkProp;
  9051. typeInst = checkTypeInst;
  9052. return true;
  9053. }
  9054. }
  9055. }
  9056. checkTypeInst = checkTypeInst->mBaseType;
  9057. }
  9058. return false;
  9059. }
  9060. BfMethodInstance* BfModule::GetRawMethodInstanceAtIdx(BfTypeInstance* typeInstance, int methodIdx, const char* assertName)
  9061. {
  9062. if (!typeInstance->mResolvingVarField)
  9063. {
  9064. if (!typeInstance->DefineStateAllowsStaticMethods())
  9065. PopulateType(typeInstance, BfPopulateType_AllowStaticMethods);
  9066. }
  9067. else
  9068. {
  9069. if (methodIdx >= (int)typeInstance->mMethodInstanceGroups.size())
  9070. {
  9071. AssertErrorState();
  9072. return NULL;
  9073. }
  9074. }
  9075. if (assertName != NULL)
  9076. {
  9077. BF_ASSERT(typeInstance->mTypeDef->mMethods[methodIdx]->mName == assertName);
  9078. }
  9079. auto& methodGroup = typeInstance->mMethodInstanceGroups[methodIdx];
  9080. if (methodGroup.mDefault == NULL)
  9081. {
  9082. if (!mCompiler->mIsResolveOnly)
  9083. {
  9084. // Get it from the owning module so we don't create a reference prematurely...
  9085. auto declModule = typeInstance->mModule;
  9086. if ((typeInstance->mGenericTypeInfo != NULL) && (typeInstance->mGenericTypeInfo->mFinishedGenericParams) && (methodGroup.mOnDemandKind == BfMethodOnDemandKind_NotSet))
  9087. {
  9088. methodGroup.mOnDemandKind = BfMethodOnDemandKind_NoDecl_AwaitingReference;
  9089. if (!declModule->mIsScratchModule)
  9090. declModule->mOnDemandMethodCount++;
  9091. }
  9092. BF_ASSERT((methodGroup.mOnDemandKind == BfMethodOnDemandKind_AlwaysInclude) || (methodGroup.mOnDemandKind == BfMethodOnDemandKind_NoDecl_AwaitingReference) || (methodGroup.mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingDecl) ||
  9093. (typeInstance->mTypeFailed) || (typeInstance->mDefineState < BfTypeDefineState_DefinedAndMethodsSlotted));
  9094. if ((methodGroup.mOnDemandKind == BfMethodOnDemandKind_NoDecl_AwaitingReference) || (methodGroup.mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingDecl))
  9095. methodGroup.mOnDemandKind = BfMethodOnDemandKind_Decl_AwaitingDecl;
  9096. BfGetMethodInstanceFlags useFlags = (BfGetMethodInstanceFlags)(BfGetMethodInstanceFlag_MethodInstanceOnly | BfGetMethodInstanceFlag_UnspecializedPass | BfGetMethodInstanceFlag_Unreified);
  9097. return declModule->GetMethodInstance(typeInstance, typeInstance->mTypeDef->mMethods[methodIdx], BfTypeVector(), useFlags).mMethodInstance;
  9098. }
  9099. else
  9100. {
  9101. auto declModule = typeInstance->mModule;
  9102. BfGetMethodInstanceFlags useFlags = (BfGetMethodInstanceFlags)(BfGetMethodInstanceFlag_MethodInstanceOnly | BfGetMethodInstanceFlag_UnspecializedPass);
  9103. return declModule->GetMethodInstance(typeInstance, typeInstance->mTypeDef->mMethods[methodIdx], BfTypeVector(), useFlags).mMethodInstance;
  9104. }
  9105. }
  9106. auto methodInstance = typeInstance->mMethodInstanceGroups[methodIdx].mDefault;
  9107. //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
  9108. // be from a call to the NON-raw version
  9109. // if (!methodInstance->mMethodInstanceGroup->IsImplemented())
  9110. // {
  9111. // methodInstance->mIsReified = mIsReified;
  9112. // if (methodInstance->mMethodProcessRequest == NULL)
  9113. // typeInstance->mModule->AddMethodToWorkList(methodInstance);
  9114. // }
  9115. return methodInstance;
  9116. }
  9117. BfMethodInstance* BfModule::GetRawMethodInstance(BfTypeInstance* typeInstance, BfMethodDef* methodDef)
  9118. {
  9119. if (methodDef->mIsLocalMethod)
  9120. {
  9121. return GetMethodInstance(typeInstance, methodDef, BfTypeVector()).mMethodInstance;
  9122. }
  9123. return GetRawMethodInstanceAtIdx(typeInstance, methodDef->mIdx, NULL);
  9124. }
  9125. BfMethodInstance* BfModule::GetRawMethodByName(BfTypeInstance* typeInstance, const StringImpl& methodName, int paramCount, bool checkBase, bool allowMixin)
  9126. {
  9127. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  9128. while (typeInstance != NULL)
  9129. {
  9130. typeInstance->mTypeDef->PopulateMemberSets();
  9131. BfMemberSetEntry* entry = NULL;
  9132. BfMethodDef* methodDef = NULL;
  9133. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(methodName, &entry))
  9134. methodDef = (BfMethodDef*)entry->mMemberDef;
  9135. while (methodDef != NULL)
  9136. {
  9137. if (((allowMixin) || (methodDef->mMethodType != BfMethodType_Mixin)) &&
  9138. (methodDef->mGenericParams.size() == 0) &&
  9139. ((paramCount == -1) || (paramCount == (int)methodDef->mParams.size())))
  9140. return GetRawMethodInstance(typeInstance, methodDef);
  9141. methodDef = methodDef->mNextWithSameName;
  9142. }
  9143. if (!checkBase)
  9144. break;
  9145. typeInstance = typeInstance->mBaseType;
  9146. }
  9147. return NULL;
  9148. }
  9149. BfMethodInstance* BfModule::GetUnspecializedMethodInstance(BfMethodInstance* methodInstance, bool useUnspecializedType)
  9150. {
  9151. if ((methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mMethodGenericArguments.size() != 0))
  9152. methodInstance = methodInstance->mMethodInstanceGroup->mDefault;
  9153. auto owner = methodInstance->mMethodInstanceGroup->mOwner;
  9154. if (!useUnspecializedType)
  9155. return methodInstance;
  9156. if (!owner->IsGenericTypeInstance())
  9157. return methodInstance;
  9158. if ((owner->IsDelegateFromTypeRef()) ||
  9159. (owner->IsFunctionFromTypeRef()) ||
  9160. (owner->IsTuple()))
  9161. {
  9162. return methodInstance;
  9163. }
  9164. auto genericType = (BfTypeInstance*)owner;
  9165. if ((genericType->IsUnspecializedType()) && (!genericType->IsUnspecializedTypeVariation()))
  9166. return methodInstance;
  9167. if (methodInstance->mMethodDef->mIsLocalMethod)
  9168. return methodInstance;
  9169. if (methodInstance->mMethodDef->mDeclaringType->IsEmitted())
  9170. return methodInstance;
  9171. auto unspecializedType = ResolveTypeDef(genericType->mTypeDef->GetDefinition());
  9172. if (unspecializedType == NULL)
  9173. {
  9174. AssertErrorState();
  9175. return methodInstance;
  9176. }
  9177. if (unspecializedType == NULL)
  9178. return methodInstance;
  9179. auto unspecializedTypeInst = unspecializedType->ToTypeInstance();
  9180. return GetRawMethodInstanceAtIdx(unspecializedTypeInst, methodInstance->mMethodDef->mIdx);
  9181. }
  9182. int BfModule::GetGenericParamAndReturnCount(BfMethodInstance* methodInstance)
  9183. {
  9184. int genericCount = 0;
  9185. auto unspecializedMethodInstance = GetUnspecializedMethodInstance(methodInstance);
  9186. for (int paramIdx = 0; paramIdx < unspecializedMethodInstance->GetParamCount(); paramIdx++)
  9187. {
  9188. auto param = unspecializedMethodInstance->GetParamType(paramIdx);
  9189. if (param->IsGenericParam())
  9190. genericCount++;
  9191. }
  9192. if (unspecializedMethodInstance->mReturnType->IsGenericParam())
  9193. genericCount++;
  9194. return genericCount;
  9195. }
  9196. BfModule* BfModule::GetSpecializedMethodModule(const SizedArrayImpl<BfProject*>& projectList)
  9197. {
  9198. BF_ASSERT(!mIsScratchModule);
  9199. BF_ASSERT(mIsReified);
  9200. BfModule* mainModule = this;
  9201. if (mParentModule != NULL)
  9202. mainModule = mParentModule;
  9203. BfModule* specModule = NULL;
  9204. BfModule** specModulePtr = NULL;
  9205. if (mainModule->mSpecializedMethodModules.TryGetValueWith(projectList, &specModulePtr))
  9206. {
  9207. return *specModulePtr;
  9208. }
  9209. else
  9210. {
  9211. String specModuleName = mModuleName;
  9212. for (auto bfProject : projectList)
  9213. {
  9214. specModuleName += StrFormat("@%s", bfProject->mSafeName.c_str());
  9215. }
  9216. specModule = new BfModule(mContext, specModuleName);
  9217. specModule->mProject = mainModule->mProject;
  9218. specModule->mParentModule = mainModule;
  9219. specModule->mIsSpecializedMethodModuleRoot = true;
  9220. specModule->Init();
  9221. Array<BfProject*> projList;
  9222. for (auto project : projectList)
  9223. projList.Add(project);
  9224. mainModule->mSpecializedMethodModules[projList] = specModule;
  9225. }
  9226. return specModule;
  9227. }
  9228. BfIRValue BfModule::CreateFunctionFrom(BfMethodInstance* methodInstance, bool tryExisting, bool isInlined)
  9229. {
  9230. if (IsSkippingExtraResolveChecks())
  9231. return BfIRValue();
  9232. if (methodInstance->mMethodInstanceGroup->mOwner->IsInterface())
  9233. {
  9234. //BF_ASSERT(!methodInstance->mIRFunction);
  9235. return BfIRValue();
  9236. }
  9237. auto methodDef = methodInstance->mMethodDef;
  9238. StringT<128> methodName;
  9239. BfMangler::Mangle(methodName, mCompiler->GetMangleKind(), methodInstance);
  9240. if (isInlined != methodInstance->mAlwaysInline)
  9241. {
  9242. if (isInlined)
  9243. methodName += "__INLINE";
  9244. else
  9245. methodName += "__NOINLINE";
  9246. }
  9247. if (tryExisting)
  9248. {
  9249. auto func = mBfIRBuilder->GetFunction(methodName);
  9250. if (func)
  9251. return func;
  9252. }
  9253. auto intrinsic = GetIntrinsic(methodInstance);
  9254. if (intrinsic)
  9255. return intrinsic;
  9256. if (methodInstance->GetImportCallKind() != BfImportCallKind_None)
  9257. {
  9258. return CreateDllImportGlobalVar(methodInstance, false);
  9259. }
  9260. BfIRType returnType;
  9261. SizedArray<BfIRType, 8> paramTypes;
  9262. methodInstance->GetIRFunctionInfo(this, returnType, paramTypes);
  9263. auto funcType = mBfIRBuilder->CreateFunctionType(returnType, paramTypes, methodInstance->IsVarArgs());
  9264. auto func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, methodName);
  9265. auto callingConv = GetIRCallingConvention(methodInstance);
  9266. if (callingConv != BfIRCallingConv_CDecl)
  9267. mBfIRBuilder->SetFuncCallingConv(func, callingConv);
  9268. SetupIRMethod(methodInstance, func, isInlined);
  9269. // auto srcModule = methodInstance->GetOwner()->GetModule();
  9270. // if ((srcModule != NULL) && (srcModule->mProject != mProject))
  9271. // {
  9272. // if (srcModule->mProject->mTargetType == BfTargetType_BeefDynLib)
  9273. // {
  9274. // mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_DllImport);
  9275. // }
  9276. // }
  9277. return func;
  9278. }
  9279. BfModuleMethodInstance BfModule::GetMethodInstanceAtIdx(BfTypeInstance* typeInstance, int methodIdx, const char* assertName, BfGetMethodInstanceFlags flags)
  9280. {
  9281. if (assertName != NULL)
  9282. {
  9283. BF_ASSERT(typeInstance->mTypeDef->mMethods[methodIdx]->mName == assertName);
  9284. }
  9285. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  9286. auto methodInstance = typeInstance->mMethodInstanceGroups[methodIdx].mDefault;
  9287. BfMethodDef* methodDef = NULL;
  9288. BfTypeInstance* foreignType = NULL;
  9289. if (methodInstance != NULL)
  9290. {
  9291. methodDef = methodInstance->mMethodDef;
  9292. if (methodInstance->mMethodInfoEx != NULL)
  9293. foreignType = methodInstance->mMethodInfoEx->mForeignType;
  9294. }
  9295. if ((methodInstance != NULL) && (mIsReified) && (!methodInstance->mIsReified))
  9296. {
  9297. // Can't use it, not reified
  9298. methodInstance = NULL;
  9299. }
  9300. if ((methodInstance != NULL) && (mBfIRBuilder != NULL) && (mBfIRBuilder->mIgnoreWrites) &&
  9301. (methodInstance->mMethodInstanceGroup->IsImplemented()))
  9302. {
  9303. BfIRFunction func(mBfIRBuilder->GetFakeVal());
  9304. return BfModuleMethodInstance(methodInstance, func);
  9305. }
  9306. if (foreignType != NULL)
  9307. return GetMethodInstance(typeInstance, methodDef, BfTypeVector(), (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_ForeignMethodDef), foreignType);
  9308. return GetMethodInstance(typeInstance, typeInstance->mTypeDef->mMethods[methodIdx], BfTypeVector(), flags);
  9309. }
  9310. BfModuleMethodInstance BfModule::GetMethodByName(BfTypeInstance* typeInstance, const StringImpl& methodName, int paramCount, bool checkBase)
  9311. {
  9312. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  9313. while (typeInstance != NULL)
  9314. {
  9315. typeInstance->mTypeDef->PopulateMemberSets();
  9316. BfMemberSetEntry* entry = NULL;
  9317. BfMethodDef* methodDef = NULL;
  9318. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(methodName, &entry))
  9319. methodDef = (BfMethodDef*)entry->mMemberDef;
  9320. while (methodDef != NULL)
  9321. {
  9322. if ((methodDef->mMethodType != BfMethodType_Mixin) &&
  9323. (methodDef->mGenericParams.size() == 0) &&
  9324. ((paramCount == -1) || (paramCount == (int)methodDef->mParams.size())))
  9325. return GetMethodInstanceAtIdx(typeInstance, methodDef->mIdx);
  9326. methodDef = methodDef->mNextWithSameName;
  9327. }
  9328. if (!checkBase)
  9329. break;
  9330. typeInstance = typeInstance->mBaseType;
  9331. }
  9332. return BfModuleMethodInstance();
  9333. }
  9334. BfModuleMethodInstance BfModule::GetMethodByName(BfTypeInstance* typeInstance, const StringImpl& methodName, const Array<BfType*>& paramTypes, bool checkBase)
  9335. {
  9336. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  9337. while (typeInstance != NULL)
  9338. {
  9339. typeInstance->mTypeDef->PopulateMemberSets();
  9340. BfMemberSetEntry* entry = NULL;
  9341. BfMethodDef* methodDef = NULL;
  9342. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(methodName, &entry))
  9343. methodDef = (BfMethodDef*)entry->mMemberDef;
  9344. while (methodDef != NULL)
  9345. {
  9346. if ((methodDef->mMethodType != BfMethodType_Mixin) &&
  9347. (methodDef->mGenericParams.size() == 0) &&
  9348. (paramTypes.size() == methodDef->mParams.size()))
  9349. {
  9350. auto moduleMethodInstance = GetMethodInstanceAtIdx(typeInstance, methodDef->mIdx);
  9351. if (moduleMethodInstance.mMethodInstance != NULL)
  9352. {
  9353. bool matches = true;
  9354. for (int paramIdx = 0; paramIdx < (int)paramTypes.size(); paramIdx++)
  9355. {
  9356. if (moduleMethodInstance.mMethodInstance->GetParamType(paramIdx) != paramTypes[paramIdx])
  9357. matches = false;
  9358. }
  9359. if (matches)
  9360. return moduleMethodInstance;
  9361. }
  9362. }
  9363. methodDef = methodDef->mNextWithSameName;
  9364. }
  9365. if (!checkBase)
  9366. break;
  9367. typeInstance = typeInstance->mBaseType;
  9368. }
  9369. return BfModuleMethodInstance();
  9370. }
  9371. BfModuleMethodInstance BfModule::GetInternalMethod(const StringImpl& methodName, int paramCount)
  9372. {
  9373. auto internalType = ResolveTypeDef(mCompiler->mInternalTypeDef);
  9374. PopulateType(internalType);
  9375. auto moduleMethodInstance = GetMethodByName(internalType->ToTypeInstance(), methodName, paramCount);
  9376. if (!moduleMethodInstance)
  9377. {
  9378. Fail(StrFormat("Failed to find System.Internal method '%s'", methodName.c_str()));
  9379. }
  9380. return moduleMethodInstance;
  9381. }
  9382. BfOperatorInfo* BfModule::GetOperatorInfo(BfTypeInstance* typeInstance, BfOperatorDef* operatorDef)
  9383. {
  9384. while (operatorDef->mIdx >= typeInstance->mOperatorInfo.size())
  9385. typeInstance->mOperatorInfo.Add(NULL);
  9386. if (typeInstance->mOperatorInfo[operatorDef->mIdx] == NULL)
  9387. {
  9388. SetAndRestoreValue<bool> ignoreErrors(mIgnoreErrors, true);
  9389. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  9390. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, NULL);
  9391. BfTypeState typeState;
  9392. typeState.mType = typeInstance;
  9393. typeState.mCurTypeDef = operatorDef->mDeclaringType;
  9394. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  9395. BfOperatorInfo* operatorInfo = new BfOperatorInfo();
  9396. if (operatorDef->mReturnTypeRef != NULL)
  9397. operatorInfo->mReturnType = ResolveTypeRef(operatorDef->mReturnTypeRef, BfPopulateType_Identity);
  9398. if (operatorDef->mParams.size() >= 1)
  9399. operatorInfo->mLHSType = ResolveTypeRef(operatorDef->mParams[0]->mTypeRef, BfPopulateType_Identity);
  9400. if (operatorDef->mParams.size() >= 2)
  9401. operatorInfo->mRHSType = ResolveTypeRef(operatorDef->mParams[1]->mTypeRef, BfPopulateType_Identity);
  9402. typeInstance->mOperatorInfo[operatorDef->mIdx] = operatorInfo;
  9403. }
  9404. return typeInstance->mOperatorInfo[operatorDef->mIdx];
  9405. }
  9406. BfType* BfModule::CheckOperator(BfTypeInstance* typeInstance, BfOperatorDef* operatorDef, const BfTypedValue& lhs, const BfTypedValue& rhs)
  9407. {
  9408. auto operatorInfo = GetOperatorInfo(typeInstance, operatorDef);
  9409. if (operatorInfo == NULL)
  9410. return NULL;
  9411. if (operatorInfo->mReturnType == NULL)
  9412. return NULL;
  9413. auto castFlags = BfCastFlags_IsConstraintCheck;
  9414. if (operatorDef->mOperatorDeclaration->mIsConvOperator)
  9415. castFlags = (BfCastFlags)(castFlags | BfCastFlags_NoConversionOperator);
  9416. if (lhs)
  9417. {
  9418. if (operatorInfo->mLHSType == NULL)
  9419. return NULL;
  9420. if (!CanCast(lhs, operatorInfo->mLHSType, castFlags))
  9421. return NULL;
  9422. }
  9423. if (rhs)
  9424. {
  9425. if (operatorInfo->mRHSType == NULL)
  9426. return NULL;
  9427. if (!CanCast(rhs, operatorInfo->mRHSType, castFlags))
  9428. return NULL;
  9429. }
  9430. return operatorInfo->mReturnType;
  9431. }
  9432. bool BfModule::IsMethodImplementedAndReified(BfTypeInstance* typeInstance, const StringImpl& methodName, int paramCount, bool checkBase)
  9433. {
  9434. while (typeInstance != NULL)
  9435. {
  9436. typeInstance->mTypeDef->PopulateMemberSets();
  9437. BfMemberSetEntry* entry = NULL;
  9438. BfMethodDef* methodDef = NULL;
  9439. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(methodName, &entry))
  9440. methodDef = (BfMethodDef*)entry->mMemberDef;
  9441. while (methodDef != NULL)
  9442. {
  9443. if ((methodDef->mMethodType != BfMethodType_Mixin) &&
  9444. (methodDef->mGenericParams.size() == 0) &&
  9445. ((paramCount == -1) || (paramCount == (int)methodDef->mParams.size())))
  9446. {
  9447. auto& methodInstanceGroup = typeInstance->mMethodInstanceGroups[methodDef->mIdx];
  9448. if (!methodInstanceGroup.IsImplemented())
  9449. return false;
  9450. if (methodInstanceGroup.mDefault == NULL)
  9451. return false;
  9452. return methodInstanceGroup.mDefault->mIsReified;
  9453. }
  9454. methodDef = methodDef->mNextWithSameName;
  9455. }
  9456. if (!checkBase)
  9457. break;
  9458. typeInstance = typeInstance->mBaseType;
  9459. }
  9460. return false;
  9461. }
  9462. bool BfModule::HasMixin(BfTypeInstance* typeInstance, const StringImpl& methodName, int paramCount, bool checkBase)
  9463. {
  9464. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  9465. while (typeInstance != NULL)
  9466. {
  9467. typeInstance->mTypeDef->PopulateMemberSets();
  9468. BfMemberSetEntry* entry = NULL;
  9469. BfMethodDef* methodDef = NULL;
  9470. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(methodName, &entry))
  9471. methodDef = (BfMethodDef*)entry->mMemberDef;
  9472. while (methodDef != NULL)
  9473. {
  9474. if ((methodDef->mMethodType == BfMethodType_Mixin) &&
  9475. ((paramCount == -1) || (paramCount == (int)methodDef->mParams.size())))
  9476. return true;
  9477. methodDef = methodDef->mNextWithSameName;
  9478. }
  9479. if (!checkBase)
  9480. break;
  9481. typeInstance = typeInstance->mBaseType;
  9482. }
  9483. return BfModuleMethodInstance();
  9484. }
  9485. StringT<128> BfModule::MethodToString(BfMethodInstance* methodInst, BfMethodNameFlags methodNameFlags, BfTypeVector* typeGenericArgs, BfTypeVector* methodGenericArgs)
  9486. {
  9487. auto methodDef = methodInst->mMethodDef;
  9488. bool allowResolveGenericParamNames = ((methodNameFlags & BfMethodNameFlag_ResolveGenericParamNames) != 0);
  9489. BfTypeNameFlags typeNameFlags = BfTypeNameFlags_None;
  9490. bool hasGenericArgs = (typeGenericArgs != NULL) || (methodGenericArgs != NULL);
  9491. BfType* type = methodInst->mMethodInstanceGroup->mOwner;
  9492. if ((hasGenericArgs) && (type->IsUnspecializedType()))
  9493. type = ResolveGenericType(type, typeGenericArgs, methodGenericArgs);
  9494. if ((type == NULL) || (!type->IsUnspecializedTypeVariation()))
  9495. typeNameFlags = BfTypeNameFlag_ResolveGenericParamNames;
  9496. if (allowResolveGenericParamNames)
  9497. typeNameFlags = BfTypeNameFlag_ResolveGenericParamNames;
  9498. StringT<128> methodName;
  9499. auto _AddTypeName = [&](BfType* type)
  9500. {
  9501. auto typeNameFlags = BfTypeNameFlags_None;
  9502. if (allowResolveGenericParamNames)
  9503. typeNameFlags = BfTypeNameFlag_ResolveGenericParamNames;
  9504. if ((hasGenericArgs) && (type->IsUnspecializedType()))
  9505. type = ResolveGenericType(type, typeGenericArgs, methodGenericArgs);
  9506. methodName += TypeToString(type, typeNameFlags);
  9507. };
  9508. if ((methodNameFlags & BfMethodNameFlag_IncludeReturnType) != 0)
  9509. {
  9510. _AddTypeName(methodInst->mReturnType);
  9511. methodName += " ";
  9512. }
  9513. if ((methodNameFlags & BfMethodNameFlag_OmitTypeName) == 0)
  9514. {
  9515. methodName += TypeToString(type, typeNameFlags);
  9516. if (methodName == "$")
  9517. methodName = "";
  9518. else if (!methodName.IsEmpty())
  9519. methodName += ".";
  9520. }
  9521. String accessorString;
  9522. StringT<64> methodDefName = methodInst->mMethodDef->mName;
  9523. if (methodInst->mMethodDef->mIsLocalMethod)
  9524. {
  9525. int atPos = (int)methodDefName.IndexOf('$');
  9526. methodDefName.RemoveToEnd(atPos);
  9527. methodDefName.Replace("@", ".");
  9528. }
  9529. else
  9530. {
  9531. int atPos = (int)methodDefName.IndexOf('$');
  9532. if (atPos != -1)
  9533. {
  9534. accessorString = methodDefName.Substring(0, atPos);
  9535. if ((accessorString == "get") || (accessorString == "set"))
  9536. {
  9537. methodDefName = methodDefName.Substring(atPos + 1);
  9538. }
  9539. else
  9540. accessorString = "";
  9541. }
  9542. }
  9543. if ((methodInst->mMethodInfoEx != NULL) && (methodInst->mMethodInfoEx->mForeignType != NULL))
  9544. {
  9545. BfTypeNameFlags typeNameFlags = BfTypeNameFlags_None;
  9546. if (!methodInst->mIsUnspecializedVariation && allowResolveGenericParamNames)
  9547. typeNameFlags = BfTypeNameFlag_ResolveGenericParamNames;
  9548. methodName += TypeToString(methodInst->mMethodInfoEx->mForeignType, typeNameFlags);
  9549. methodName += ".";
  9550. }
  9551. if ((methodInst->mMethodInfoEx != NULL) && (methodInst->mMethodInfoEx->mExplicitInterface != NULL))
  9552. {
  9553. BfTypeNameFlags typeNameFlags = BfTypeNameFlags_None;
  9554. if (!methodInst->mIsUnspecializedVariation && allowResolveGenericParamNames)
  9555. typeNameFlags = BfTypeNameFlag_ResolveGenericParamNames;
  9556. methodName += "[";
  9557. methodName += TypeToString(methodInst->mMethodInfoEx->mExplicitInterface, typeNameFlags);
  9558. methodName += "].";
  9559. }
  9560. if (methodDef->mMethodType == BfMethodType_Operator)
  9561. {
  9562. BfOperatorDef* operatorDef = (BfOperatorDef*)methodDef;
  9563. if (operatorDef->mOperatorDeclaration->mIsConvOperator)
  9564. {
  9565. // Don't add explicit/implicit part, since that's not available in GCC mangling
  9566. /*if (operatorDef->mOperatorDeclaration->mExplicitToken != NULL)
  9567. {
  9568. if (operatorDef->mOperatorDeclaration->mExplicitToken->GetToken() == BfToken_Explicit)
  9569. methodName += "explicit ";
  9570. else if (operatorDef->mOperatorDeclaration->mExplicitToken->GetToken() == BfToken_Explicit)
  9571. methodName += "explicit ";
  9572. }*/
  9573. methodName += "operator ";
  9574. if (methodInst->mReturnType != NULL)
  9575. methodName += TypeToString(methodInst->mReturnType);
  9576. }
  9577. else
  9578. {
  9579. methodName += "operator";
  9580. if (operatorDef->mOperatorDeclaration->mOpTypeToken != NULL)
  9581. methodName += BfTokenToString(operatorDef->mOperatorDeclaration->mOpTypeToken->GetToken());
  9582. }
  9583. }
  9584. else if (methodDef->mMethodType == BfMethodType_Ctor)
  9585. {
  9586. if (methodDef->mIsStatic)
  9587. methodName += "__BfStaticCtor";
  9588. else
  9589. methodName += "this";
  9590. accessorString = "";
  9591. }
  9592. else if (methodDef->mMethodType == BfMethodType_PropertyGetter)
  9593. {
  9594. auto propertyDecl = methodDef->GetPropertyDeclaration();
  9595. if (auto indexerProperty = BfNodeDynCast<BfIndexerDeclaration>(propertyDecl))
  9596. {
  9597. methodName += "get indexer";
  9598. }
  9599. else
  9600. {
  9601. if ((propertyDecl != NULL) && (propertyDecl->mNameNode != NULL))
  9602. propertyDecl->mNameNode->ToString(methodName);
  9603. methodName += " get accessor";
  9604. return methodName;
  9605. }
  9606. }
  9607. else if (methodDef->mMethodType == BfMethodType_PropertySetter)
  9608. {
  9609. auto propertyDecl = methodDef->GetPropertyDeclaration();
  9610. if (auto indexerProperty = BfNodeDynCast<BfIndexerDeclaration>(propertyDecl))
  9611. {
  9612. methodName += "set indexer";
  9613. }
  9614. else
  9615. {
  9616. if ((propertyDecl != NULL) && (propertyDecl->mNameNode != NULL))
  9617. propertyDecl->mNameNode->ToString(methodName);
  9618. methodName += " set accessor";
  9619. return methodName;
  9620. }
  9621. }
  9622. else
  9623. methodName += methodDefName;
  9624. if (methodDef->mMethodType == BfMethodType_Mixin)
  9625. methodName += "!";
  9626. BfTypeVector newMethodGenericArgs;
  9627. if ((methodInst->mMethodInfoEx != NULL) && (methodInst->mMethodInfoEx->mMethodGenericArguments.size() != 0))
  9628. {
  9629. methodName += "<";
  9630. for (int i = 0; i < (int)methodInst->mMethodInfoEx->mMethodGenericArguments.size(); i++)
  9631. {
  9632. if (i > 0)
  9633. methodName += ", ";
  9634. BfTypeNameFlags typeNameFlags = BfTypeNameFlag_ShortConst;
  9635. //Why did we have this methodInst->mIsUnspecializedVariation check? Sometimes we do need to show errors calling methods that refer back to our types
  9636. //if (!methodInst->mIsUnspecializedVariation && allowResolveGenericParamNames)
  9637. if (allowResolveGenericParamNames)
  9638. typeNameFlags = (BfTypeNameFlags)(typeNameFlags | BfTypeNameFlag_ResolveGenericParamNames);
  9639. BfType* type = methodInst->mMethodInfoEx->mMethodGenericArguments[i];
  9640. if ((methodGenericArgs != NULL) && (type->IsUnspecializedType()))
  9641. {
  9642. bool hasEmpty = false;
  9643. for (auto arg : *methodGenericArgs)
  9644. {
  9645. if (arg == NULL)
  9646. hasEmpty = true;
  9647. }
  9648. if (hasEmpty)
  9649. {
  9650. for (int genericIdx = 0; genericIdx < (int)methodGenericArgs->size(); genericIdx++)
  9651. {
  9652. auto arg = (*methodGenericArgs)[genericIdx];
  9653. if (arg != NULL)
  9654. newMethodGenericArgs.push_back(arg);
  9655. else
  9656. {
  9657. auto genericParamInst = methodInst->mMethodInfoEx->mGenericParams[genericIdx];
  9658. if (genericParamInst->mTypeConstraint != NULL)
  9659. newMethodGenericArgs.push_back(genericParamInst->mTypeConstraint);
  9660. else
  9661. newMethodGenericArgs.push_back(mContext->mBfObjectType); // Default
  9662. }
  9663. }
  9664. methodGenericArgs = &newMethodGenericArgs;
  9665. }
  9666. if (type->IsUnspecializedType())
  9667. type = ResolveGenericType(type, NULL, methodGenericArgs);
  9668. }
  9669. if ((methodGenericArgs == NULL) && (mCurMethodInstance == NULL) && (mCurTypeInstance == NULL))
  9670. {
  9671. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, methodInst->GetOwner());
  9672. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, methodInst);
  9673. methodName += TypeToString(type, typeNameFlags);
  9674. }
  9675. else
  9676. methodName += TypeToString(type, typeNameFlags);
  9677. }
  9678. methodName += ">";
  9679. }
  9680. if (accessorString.length() == 0)
  9681. {
  9682. int dispParamIdx = 0;
  9683. methodName += "(";
  9684. for (int paramIdx = 0; paramIdx < (int)methodInst->GetParamCount(); paramIdx++)
  9685. {
  9686. int paramKind = methodInst->GetParamKind(paramIdx);
  9687. if (paramKind == BfParamKind_ImplicitCapture)
  9688. continue;
  9689. if (dispParamIdx > 0)
  9690. methodName += ", ";
  9691. if (paramKind == BfParamKind_Params)
  9692. methodName += "params ";
  9693. BfType* type = methodInst->GetParamType(paramIdx);
  9694. _AddTypeName(type);
  9695. methodName += " ";
  9696. methodName += methodInst->GetParamName(paramIdx);
  9697. auto paramInitializer = methodInst->GetParamInitializer(paramIdx);
  9698. if ((paramInitializer != NULL) && ((methodNameFlags & BfMethodNameFlag_NoAst) == 0))
  9699. {
  9700. methodName += " = ";
  9701. methodName += paramInitializer->ToString();
  9702. }
  9703. dispParamIdx++;
  9704. }
  9705. methodName += ")";
  9706. }
  9707. if (accessorString.length() != 0)
  9708. {
  9709. methodName += " ";
  9710. methodName += accessorString;
  9711. }
  9712. if ((methodNameFlags & BfMethodNameFlag_IncludeMut) != 0)
  9713. {
  9714. if ((methodDef->mIsMutating) && (methodInst->GetOwner()->IsValueType()))
  9715. methodName += " mut";
  9716. }
  9717. return methodName;
  9718. }
  9719. void BfModule::pt(BfType* type)
  9720. {
  9721. OutputDebugStrF("%s\n", TypeToString(type).c_str());
  9722. }
  9723. void BfModule::pm(BfMethodInstance* type)
  9724. {
  9725. OutputDebugStrF("%s\n", MethodToString(type).c_str());
  9726. }
  9727. static void AddAttributeTargetName(BfAttributeTargets& flagsLeft, BfAttributeTargets checkFlag, String& str, String addString)
  9728. {
  9729. if ((flagsLeft & checkFlag) == 0)
  9730. return;
  9731. if (!str.empty())
  9732. {
  9733. if (flagsLeft == checkFlag)
  9734. {
  9735. if ((int)str.IndexOf(',') != -1)
  9736. str += ", and ";
  9737. else
  9738. str += " and ";
  9739. }
  9740. else
  9741. str += ", ";
  9742. }
  9743. str += addString;
  9744. flagsLeft = (BfAttributeTargets)(flagsLeft & ~checkFlag);
  9745. }
  9746. static String GetAttributesTargetListString(BfAttributeTargets attrTarget)
  9747. {
  9748. String resultStr;
  9749. auto flagsLeft = attrTarget;
  9750. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Assembly, resultStr, "assembly declarations");
  9751. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Module, resultStr, "module declarations");
  9752. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Class, resultStr, "class declarations");
  9753. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Struct, resultStr, "struct declarations");
  9754. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Enum, resultStr, "enum declarations");
  9755. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Constructor, resultStr, "constructor declarations");
  9756. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Method, resultStr, "method declarations");
  9757. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Property, resultStr, "property declarations");
  9758. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Field, resultStr, "field declarations");
  9759. AddAttributeTargetName(flagsLeft, BfAttributeTargets_StaticField, resultStr, "static field declarations");
  9760. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Interface, resultStr, "interface declarations");
  9761. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Parameter, resultStr, "parameter declarations");
  9762. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Delegate, resultStr, "delegate declarations");
  9763. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Function, resultStr, "function declarations");
  9764. AddAttributeTargetName(flagsLeft, BfAttributeTargets_ReturnValue, resultStr, "return value");
  9765. AddAttributeTargetName(flagsLeft, BfAttributeTargets_GenericParameter, resultStr, "generic parameters");
  9766. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Invocation, resultStr, "invocations");
  9767. AddAttributeTargetName(flagsLeft, BfAttributeTargets_MemberAccess, resultStr, "member access");
  9768. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Alloc, resultStr, "allocations");
  9769. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Alias, resultStr, "aliases");
  9770. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Block, resultStr, "blocks");
  9771. if (resultStr.IsEmpty())
  9772. return "<nothing>";
  9773. return resultStr;
  9774. }
  9775. void BfModule::CurrentAddToConstHolder(BfIRValue& irVal)
  9776. {
  9777. auto constant = mBfIRBuilder->GetConstant(irVal);
  9778. int stringPoolIdx = GetStringPoolIdx(irVal, mBfIRBuilder);
  9779. if (stringPoolIdx != -1)
  9780. {
  9781. irVal = mCurTypeInstance->GetOrCreateConstHolder()->CreateConst(BfTypeCode_StringId, stringPoolIdx);
  9782. return;
  9783. }
  9784. if (constant->mConstType == BfConstType_Agg)
  9785. {
  9786. auto constArray = (BfConstantAgg*)constant;
  9787. SizedArray<BfIRValue, 8> newVals;
  9788. for (auto val : constArray->mValues)
  9789. {
  9790. auto newVal = val;
  9791. CurrentAddToConstHolder(newVal);
  9792. newVals.push_back(newVal);
  9793. }
  9794. irVal = mCurTypeInstance->GetOrCreateConstHolder()->CreateConstAgg(constArray->mType, newVals);
  9795. return;
  9796. }
  9797. auto origConst = irVal;
  9798. if ((constant->mConstType == BfConstType_BitCast) || (constant->mConstType == BfConstType_BitCastNull))
  9799. {
  9800. auto bitcast = (BfConstantBitCast*)constant;
  9801. BfIRValue newVal;
  9802. if (bitcast->mTarget)
  9803. {
  9804. newVal = BfIRValue(BfIRValueFlags_Const, bitcast->mTarget);
  9805. CurrentAddToConstHolder(newVal);
  9806. }
  9807. else
  9808. newVal = mCurTypeInstance->GetOrCreateConstHolder()->CreateConstNull();
  9809. irVal = mCurTypeInstance->GetOrCreateConstHolder()->CreateConstBitCast(newVal, bitcast->mToType);
  9810. return;
  9811. }
  9812. irVal = mCurTypeInstance->CreateConst(constant, mBfIRBuilder);
  9813. }
  9814. void BfModule::ClearConstData()
  9815. {
  9816. mBfIRBuilder->ClearConstData();
  9817. mStringObjectPool.Clear();
  9818. mStringCharPtrPool.Clear();
  9819. mStringPoolRefs.Clear();
  9820. mUnreifiedStringPoolRefs.Clear();
  9821. }
  9822. BfTypedValue BfModule::GetTypedValueFromConstant(BfConstant* constant, BfIRConstHolder* constHolder, BfType* wantType)
  9823. {
  9824. switch (constant->mTypeCode)
  9825. {
  9826. case BfTypeCode_StringId:
  9827. case BfTypeCode_Boolean:
  9828. case BfTypeCode_Int8:
  9829. case BfTypeCode_UInt8:
  9830. case BfTypeCode_Int16:
  9831. case BfTypeCode_UInt16:
  9832. case BfTypeCode_Int32:
  9833. case BfTypeCode_UInt32:
  9834. case BfTypeCode_Int64:
  9835. case BfTypeCode_UInt64:
  9836. case BfTypeCode_IntPtr:
  9837. case BfTypeCode_UIntPtr:
  9838. case BfTypeCode_IntUnknown:
  9839. case BfTypeCode_UIntUnknown:
  9840. case BfTypeCode_Char8:
  9841. case BfTypeCode_Char16:
  9842. case BfTypeCode_Char32:
  9843. case BfTypeCode_Float:
  9844. case BfTypeCode_Double:
  9845. {
  9846. auto constVal = mBfIRBuilder->CreateConst(constant, constHolder);
  9847. BfTypedValue typedValue;
  9848. bool allowUnactualized = mBfIRBuilder->mIgnoreWrites;
  9849. if (constant->mTypeCode == BfTypeCode_StringId)
  9850. {
  9851. if ((wantType->IsInstanceOf(mCompiler->mStringTypeDef)) ||
  9852. ((wantType->IsPointer()) && (wantType->GetUnderlyingType() == GetPrimitiveType(BfTypeCode_Char8))))
  9853. {
  9854. typedValue = BfTypedValue(ConstantToCurrent(constant, constHolder, wantType, allowUnactualized), wantType);
  9855. return typedValue;
  9856. }
  9857. auto stringType = ResolveTypeDef(mCompiler->mStringTypeDef);
  9858. typedValue = BfTypedValue(ConstantToCurrent(constant, constHolder, stringType, allowUnactualized), stringType);
  9859. }
  9860. if (!typedValue)
  9861. {
  9862. auto constVal = mBfIRBuilder->CreateConst(constant, constHolder);
  9863. typedValue = BfTypedValue(constVal, GetPrimitiveType(constant->mTypeCode));
  9864. }
  9865. if (typedValue.mType == wantType)
  9866. return typedValue;
  9867. if (wantType->IsTypedPrimitive())
  9868. {
  9869. if (typedValue.mType == wantType->GetUnderlyingType())
  9870. {
  9871. typedValue.mType = wantType;
  9872. return typedValue;
  9873. }
  9874. }
  9875. auto castedTypedValue = Cast(NULL, typedValue, wantType, (BfCastFlags)(BfCastFlags_SilentFail | BfCastFlags_Explicit));
  9876. if (!castedTypedValue)
  9877. return BfTypedValue();
  9878. return castedTypedValue;
  9879. }
  9880. break;
  9881. default: break;
  9882. }
  9883. BfIRValue irValue = ConstantToCurrent(constant, constHolder, wantType);
  9884. BF_ASSERT(irValue);
  9885. if (!irValue)
  9886. return BfTypedValue();
  9887. if (constant->mConstType == BfConstType_GlobalVar)
  9888. {
  9889. mBfIRBuilder->PopulateType(wantType);
  9890. auto result = BfTypedValue(irValue, wantType, true);
  9891. if (!wantType->IsComposite())
  9892. result = LoadValue(result);
  9893. return result;
  9894. }
  9895. return BfTypedValue(irValue, wantType, false);
  9896. }
  9897. bool BfModule::HasUnactializedConstant(BfConstant* constant, BfIRConstHolder* constHolder)
  9898. {
  9899. if ((constant->mConstType == BfConstType_TypeOf) || (constant->mConstType == BfConstType_TypeOf_WithData))
  9900. return true;
  9901. if (constant->mTypeCode == BfTypeCode_StringId)
  9902. return true;
  9903. if (constant->mConstType == BfConstType_Agg)
  9904. {
  9905. auto constArray = (BfConstantAgg*)constant;
  9906. for (auto val : constArray->mValues)
  9907. {
  9908. if (HasUnactializedConstant(constHolder->GetConstant(val), constHolder))
  9909. return true;
  9910. }
  9911. }
  9912. return false;
  9913. }
  9914. BfIRValue BfModule::ConstantToCurrent(BfConstant* constant, BfIRConstHolder* constHolder, BfType* wantType, bool allowUnactualized)
  9915. {
  9916. if (constant->mTypeCode == BfTypeCode_NullPtr)
  9917. {
  9918. if ((wantType == NULL) && (constant->mIRType.mKind == BfIRTypeData::TypeKind_TypeId))
  9919. wantType = mContext->mTypes[constant->mIRType.mId];
  9920. if (wantType == NULL)
  9921. return mBfIRBuilder->CreateConstNull();
  9922. return GetDefaultValue(wantType);
  9923. }
  9924. if (constant->mTypeCode == BfTypeCode_StringId)
  9925. {
  9926. if (!allowUnactualized)
  9927. {
  9928. if ((wantType->IsInstanceOf(mCompiler->mStringTypeDef)) ||
  9929. ((wantType->IsPointer()) && (wantType->GetUnderlyingType() == GetPrimitiveType(BfTypeCode_Char8))))
  9930. {
  9931. const StringImpl& str = mContext->mStringObjectIdMap[constant->mInt32].mString;
  9932. BfIRValue stringObjConst = GetStringObjectValue(str, false, true);
  9933. if (wantType->IsPointer())
  9934. return GetStringCharPtr(stringObjConst, true);
  9935. return stringObjConst;
  9936. }
  9937. }
  9938. }
  9939. if (constant->mConstType == Beefy::BfConstType_TypeOf)
  9940. {
  9941. auto constTypeOf = (BfTypeOf_Const*)constant;
  9942. if (mCurTypeInstance != NULL)
  9943. AddDependency(constTypeOf->mType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ExprTypeReference);
  9944. return CreateTypeDataRef(constTypeOf->mType);
  9945. }
  9946. if (constant->mConstType == BfConstType_PtrToInt)
  9947. {
  9948. auto fromPtrToInt = (BfConstantPtrToInt*)constant;
  9949. auto fromTarget = constHolder->GetConstantById(fromPtrToInt->mTarget);
  9950. return mBfIRBuilder->CreatePtrToInt(ConstantToCurrent(fromTarget, constHolder, NULL), fromPtrToInt->mToTypeCode);
  9951. }
  9952. if (constant->mConstType == BfConstType_IntToPtr)
  9953. {
  9954. auto fromPtrToInt = (BfConstantIntToPtr*)constant;
  9955. auto fromTarget = constHolder->GetConstantById(fromPtrToInt->mTarget);
  9956. BfIRType toIRType = fromPtrToInt->mToType;
  9957. if (toIRType.mKind == BfIRTypeData::TypeKind_TypeId)
  9958. {
  9959. auto toType = mContext->mTypes[toIRType.mId];
  9960. toIRType = mBfIRBuilder->MapType(toType);
  9961. }
  9962. return mBfIRBuilder->CreateIntToPtr(ConstantToCurrent(fromTarget, constHolder, NULL), toIRType);
  9963. }
  9964. if ((constant->mConstType == BfConstType_BitCast) || (constant->mConstType == BfConstType_BitCastNull))
  9965. {
  9966. auto bitcast = (BfConstantBitCast*)constant;
  9967. auto fromTarget = constHolder->GetConstantById(bitcast->mTarget);
  9968. BfIRType toIRType = bitcast->mToType;
  9969. if (toIRType.mKind == BfIRTypeData::TypeKind_TypeId)
  9970. {
  9971. auto toType = mContext->mTypes[toIRType.mId];
  9972. toIRType = mBfIRBuilder->MapType(toType);
  9973. }
  9974. return mBfIRBuilder->CreateBitCast(ConstantToCurrent(fromTarget, constHolder, NULL), toIRType);
  9975. }
  9976. if (constant->mConstType == BfConstType_Agg)
  9977. {
  9978. auto constArray = (BfConstantAgg*)constant;
  9979. if ((wantType == NULL) && (constArray->mType.mKind == BfIRTypeData::TypeKind_TypeId))
  9980. wantType = mContext->mTypes[constArray->mType.mId];
  9981. SizedArray<BfIRValue, 8> newVals;
  9982. if (wantType->IsSizedArray())
  9983. {
  9984. auto elementType = wantType->GetUnderlyingType();
  9985. for (auto val : constArray->mValues)
  9986. {
  9987. newVals.Add(ConstantToCurrent(constHolder->GetConstant(val), constHolder, elementType));
  9988. }
  9989. }
  9990. else
  9991. {
  9992. auto wantTypeInst = wantType->ToTypeInstance();
  9993. if (wantTypeInst->mBaseType != NULL)
  9994. {
  9995. auto baseVal = ConstantToCurrent(constHolder->GetConstant(constArray->mValues[0]), constHolder, wantTypeInst->mBaseType);
  9996. newVals.Add(baseVal);
  9997. }
  9998. if (wantType->IsUnion())
  9999. {
  10000. auto innerType = wantType->ToTypeInstance()->GetUnionInnerType();
  10001. if (!innerType->IsValuelessType())
  10002. {
  10003. auto val = ConstantToCurrent(constHolder->GetConstant(constArray->mValues[1]), constHolder, innerType);
  10004. newVals.Add(val);
  10005. }
  10006. }
  10007. if ((!wantType->IsUnion()) || (wantType->IsPayloadEnum()))
  10008. {
  10009. for (auto& fieldInstance : wantTypeInst->mFieldInstances)
  10010. {
  10011. if (fieldInstance.mDataIdx < 0)
  10012. continue;
  10013. auto val = constArray->mValues[fieldInstance.mDataIdx];
  10014. BfIRValue memberVal = ConstantToCurrent(constHolder->GetConstant(val), constHolder, fieldInstance.mResolvedType);
  10015. if (fieldInstance.mDataIdx == newVals.mSize)
  10016. newVals.Add(memberVal);
  10017. else
  10018. {
  10019. while (fieldInstance.mDataIdx >= newVals.mSize)
  10020. newVals.Add(BfIRValue());
  10021. newVals[fieldInstance.mDataIdx] = memberVal;
  10022. }
  10023. }
  10024. }
  10025. for (auto& val : newVals)
  10026. {
  10027. if (!val)
  10028. val = mBfIRBuilder->CreateConstArrayZero(0);
  10029. }
  10030. }
  10031. return mBfIRBuilder->CreateConstAgg(mBfIRBuilder->MapType(wantType, BfIRPopulateType_Identity), newVals);
  10032. }
  10033. return mBfIRBuilder->CreateConst(constant, constHolder);
  10034. }
  10035. void BfModule::ValidateCustomAttributes(BfCustomAttributes* customAttributes, BfAttributeTargets attrTarget)
  10036. {
  10037. if (attrTarget == BfAttributeTargets_SkipValidate)
  10038. return;
  10039. for (auto& customAttribute : customAttributes->mAttributes)
  10040. {
  10041. if (!customAttribute.mAwaitingValidation)
  10042. continue;
  10043. if ((customAttribute.mType->mAttributeData->mAttributeTargets & attrTarget) == 0)
  10044. {
  10045. Fail(StrFormat("Attribute '%s' is not valid on this declaration type. It is only valid on %s.",
  10046. customAttribute.GetRefNode()->ToString().c_str(), GetAttributesTargetListString(customAttribute.mType->mAttributeData->mAttributeTargets).c_str()), customAttribute.mRef->mAttributeTypeRef); // CS0592
  10047. }
  10048. customAttribute.mAwaitingValidation = false;
  10049. }
  10050. }
  10051. void BfModule::GetCustomAttributes(BfCustomAttributes* customAttributes, BfAttributeDirective* attributesDirective, BfAttributeTargets attrTarget, BfGetCustomAttributesFlags flags, BfCaptureInfo* captureInfo)
  10052. {
  10053. bool allowNonConstArgs = (flags & BfGetCustomAttributesFlags_AllowNonConstArgs) != 0;
  10054. bool keepConstsInModule = (flags & BfGetCustomAttributesFlags_KeepConstsInModule) != 0;
  10055. if (!mCompiler->mHasRequiredTypes)
  10056. return;
  10057. if ((attributesDirective != NULL) && (mCompiler->mResolvePassData != NULL) &&
  10058. (attributesDirective->IsFromParser(mCompiler->mResolvePassData->mParser)) && (mCompiler->mResolvePassData->mSourceClassifier != NULL))
  10059. {
  10060. mCompiler->mResolvePassData->mSourceClassifier->VisitChild(attributesDirective);
  10061. }
  10062. SetAndRestoreValue<bool> prevIsCapturingMethodMatchInfo;
  10063. if (mCompiler->IsAutocomplete())
  10064. prevIsCapturingMethodMatchInfo.Init(mCompiler->mResolvePassData->mAutoComplete->mIsCapturingMethodMatchInfo, false);
  10065. BfTypeInstance* baseAttrTypeInst = mContext->mUnreifiedModule->ResolveTypeDef(mCompiler->mAttributeTypeDef)->ToTypeInstance();
  10066. BfAttributeTargets targetOverride = (BfAttributeTargets)0;
  10067. BfAutoComplete* autoComplete = NULL;
  10068. if (mCompiler->mResolvePassData != NULL)
  10069. autoComplete = mCompiler->mResolvePassData->mAutoComplete;
  10070. for (; attributesDirective != NULL; attributesDirective = attributesDirective->mNextAttribute)
  10071. {
  10072. if (auto tokenNode = BfNodeDynCast<BfTokenNode>(attributesDirective->mAttributeTargetSpecifier))
  10073. {
  10074. if (captureInfo == NULL)
  10075. {
  10076. Fail("Capture specifiers can only be used in lambda allocations", tokenNode);
  10077. continue;
  10078. }
  10079. BfCaptureInfo::Entry captureEntry;
  10080. captureEntry.mCaptureType = (tokenNode->mToken == BfToken_Ampersand) ? BfCaptureType_Reference : BfCaptureType_Copy;
  10081. if (!attributesDirective->mArguments.IsEmpty())
  10082. {
  10083. captureEntry.mNameNode = BfNodeDynCast<BfIdentifierNode>(attributesDirective->mArguments[0]);
  10084. if ((captureEntry.mNameNode != NULL) && (autoComplete != NULL))
  10085. autoComplete->CheckIdentifier(captureEntry.mNameNode);
  10086. }
  10087. captureInfo->mCaptures.Add(captureEntry);
  10088. continue;
  10089. }
  10090. BfAutoParentNodeEntry autoParentNodeEntry(this, attributesDirective);
  10091. BfCustomAttribute customAttribute;
  10092. customAttribute.mAwaitingValidation = true;
  10093. customAttribute.mRef = attributesDirective;
  10094. if (attributesDirective->mAttrOpenToken != NULL)
  10095. targetOverride = (BfAttributeTargets)0;
  10096. if (attributesDirective->mAttributeTypeRef == NULL)
  10097. {
  10098. AssertErrorState();
  10099. continue;
  10100. }
  10101. BfType* attrType = ResolveTypeRef(attributesDirective->mAttributeTypeRef, BfPopulateType_Identity, (BfResolveTypeRefFlags)(BfResolveTypeRefFlag_Attribute | BfResolveTypeRefFlag_NoReify));
  10102. BfTypeDef* attrTypeDef = NULL;
  10103. if ((attrType != NULL) && (attrType->IsTypeInstance()))
  10104. attrTypeDef = attrType->ToTypeInstance()->mTypeDef;
  10105. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL))
  10106. {
  10107. mCompiler->mResolvePassData->mAutoComplete->CheckAttributeTypeRef(attributesDirective->mAttributeTypeRef);
  10108. if (attrTypeDef != NULL)
  10109. mCompiler->mResolvePassData->HandleTypeReference(attributesDirective->mAttributeTypeRef, attrTypeDef);
  10110. }
  10111. bool isBypassedAttr = false;
  10112. if (attrTypeDef != NULL)
  10113. {
  10114. // 'Object' has some dependencies on some attributes, but those attributes are classes so we have a circular dependency issue
  10115. // We solve it by having a 'bypass' for known attributes that Object depends on
  10116. if ((attributesDirective->mArguments.empty()) && (autoComplete == NULL) && (attrType != NULL) && (attrType->IsTypeInstance()))
  10117. {
  10118. if (attrType->IsInstanceOf(mCompiler->mCReprAttributeTypeDef))
  10119. {
  10120. for (auto methodDef : attrTypeDef->mMethods)
  10121. {
  10122. if ((methodDef->mMethodType == BfMethodType_Ctor) && (methodDef->mProtection == BfProtection_Public))
  10123. {
  10124. customAttribute.mType = attrType->ToTypeInstance();
  10125. customAttribute.mCtor = methodDef;
  10126. isBypassedAttr = true;
  10127. break;
  10128. }
  10129. }
  10130. }
  10131. }
  10132. if (isBypassedAttr)
  10133. {
  10134. customAttribute.mAwaitingValidation = false;
  10135. customAttributes->mAttributes.push_back(customAttribute);
  10136. continue;
  10137. }
  10138. SetAndRestoreValue<BfTypeInstance*> prevCurTypeInst(mContext->mUnreifiedModule->mCurTypeInstance, mCurTypeInstance);
  10139. SetAndRestoreValue<BfMethodInstance*> prevCurMethodInst(mContext->mUnreifiedModule->mCurMethodInstance, mCurMethodInstance);
  10140. if (mContext->mCurTypeState != NULL)
  10141. {
  10142. SetAndRestoreValue<BfTypeReference*> prevTypeRef(mContext->mCurTypeState->mCurAttributeTypeRef, attributesDirective->mAttributeTypeRef);
  10143. mContext->mUnreifiedModule->ResolveTypeResult(attributesDirective->mAttributeTypeRef, attrType, BfPopulateType_BaseType, (BfResolveTypeRefFlags)0);
  10144. }
  10145. else
  10146. {
  10147. mContext->mUnreifiedModule->ResolveTypeResult(attributesDirective->mAttributeTypeRef, attrType, BfPopulateType_BaseType, (BfResolveTypeRefFlags)0);
  10148. }
  10149. }
  10150. BfTypeInstance* attrTypeInst = NULL;
  10151. if (attrType == NULL)
  10152. continue;
  10153. attrTypeInst = attrType->ToTypeInstance();
  10154. if ((attrTypeInst != NULL) && (attrTypeInst->mDefineState != BfTypeDefineState_DefinedAndMethodsSlotting))
  10155. mContext->mUnreifiedModule->PopulateType(attrType, BfPopulateType_DataAndMethods);
  10156. if ((attrTypeInst == NULL) || (!TypeIsSubTypeOf(attrTypeInst, baseAttrTypeInst)) || (attrTypeInst->mAttributeData == NULL))
  10157. {
  10158. Fail(StrFormat("'%s' is not an attribute class", TypeToString(attrType).c_str()), attributesDirective->mAttributeTypeRef); //CS0616
  10159. continue;
  10160. }
  10161. if ((mIsReified) && (attrTypeInst->mAttributeData != NULL) && ((attrTypeInst->mAttributeData->mFlags & BfAttributeFlag_ReflectAttribute) != 0))
  10162. {
  10163. // Reify attribute
  10164. PopulateType(attrTypeInst);
  10165. }
  10166. if (mCurTypeInstance != NULL)
  10167. AddDependency(attrTypeInst, mCurTypeInstance, BfDependencyMap::DependencyFlag_CustomAttribute);
  10168. customAttribute.mType = attrTypeInst;
  10169. bool allocatedMethodState = NULL;
  10170. defer(
  10171. {
  10172. if (allocatedMethodState)
  10173. {
  10174. delete mCurMethodState;
  10175. mCurMethodState = NULL;
  10176. }
  10177. });
  10178. if (mCurMethodState == NULL)
  10179. {
  10180. allocatedMethodState = true;
  10181. mCurMethodState = new BfMethodState();
  10182. mCurMethodState->mTempKind = BfMethodState::TempKind_Static;
  10183. }
  10184. BfConstResolver constResolver(this);
  10185. if (allowNonConstArgs)
  10186. constResolver.mBfEvalExprFlags = (BfEvalExprFlags)(constResolver.mBfEvalExprFlags | BfEvalExprFlags_AllowNonConst);
  10187. bool inPropSet = false;
  10188. SizedArray<BfResolvedArg, 2> argValues;
  10189. for (BfExpression* arg : attributesDirective->mArguments)
  10190. {
  10191. if (arg == NULL)
  10192. {
  10193. continue;
  10194. }
  10195. if (autoComplete != NULL)
  10196. autoComplete->mShowAttributeProperties = attrTypeInst;
  10197. if (auto assignExpr = BfNodeDynCast<BfAssignmentExpression>(arg))
  10198. {
  10199. inPropSet = true;
  10200. if (autoComplete != NULL)
  10201. autoComplete->CheckNode(assignExpr->mLeft, true);
  10202. String findName = assignExpr->mLeft->ToString();
  10203. BfPropertyDef* bestProp = NULL;
  10204. BfTypeInstance* bestPropTypeInst = NULL;
  10205. BfFieldDef* bestField = NULL;
  10206. BfTypeInstance* bestFieldTypeInst = NULL;
  10207. auto checkTypeInst = attrTypeInst;
  10208. while (checkTypeInst != NULL)
  10209. {
  10210. mContext->mUnreifiedModule->PopulateType(checkTypeInst, BfPopulateType_Data);
  10211. for (auto prop : checkTypeInst->mTypeDef->mProperties)
  10212. {
  10213. if (prop->mName == findName)
  10214. {
  10215. if ((bestProp == NULL) || (bestProp->mProtection != BfProtection_Public))
  10216. {
  10217. bestProp = prop;
  10218. bestPropTypeInst = checkTypeInst;
  10219. }
  10220. }
  10221. }
  10222. for (auto field : checkTypeInst->mTypeDef->mFields)
  10223. {
  10224. if (field->mName == findName)
  10225. {
  10226. if ((bestField == NULL) || (bestField->mProtection != BfProtection_Public))
  10227. {
  10228. bestField = field;
  10229. bestFieldTypeInst = checkTypeInst;
  10230. }
  10231. }
  10232. }
  10233. if ((bestProp != NULL) || (bestField != NULL))
  10234. break;
  10235. checkTypeInst = checkTypeInst->mBaseType;
  10236. }
  10237. bool handledExpr = false;
  10238. if (bestField != NULL)
  10239. {
  10240. handledExpr = true;
  10241. if (mCompiler->mResolvePassData != NULL)
  10242. {
  10243. mCompiler->mResolvePassData->HandleFieldReference(assignExpr->mLeft, attrTypeDef, bestField);
  10244. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(assignExpr->mLeft)))
  10245. {
  10246. autoComplete->mDefField = bestField;
  10247. autoComplete->mDefType = attrTypeDef;
  10248. }
  10249. }
  10250. if (bestField->mProtection != BfProtection_Public)
  10251. Fail(StrFormat("'%s.%s' is inaccessible due to its protection level", TypeToString(bestFieldTypeInst).c_str(), findName.c_str()), assignExpr->mLeft); // CS0122
  10252. AddDependency(bestFieldTypeInst, mCurTypeInstance, BfDependencyMap::DependencyFlag_CustomAttribute);
  10253. BfCustomAttributeSetField setField;
  10254. setField.mFieldRef = BfFieldRef(bestFieldTypeInst, bestField);
  10255. auto& fieldTypeInst = checkTypeInst->mFieldInstances[bestField->mIdx];
  10256. if (assignExpr->mRight != NULL)
  10257. {
  10258. BfTypedValue result = constResolver.Resolve(assignExpr->mRight, fieldTypeInst.mResolvedType, BfConstResolveFlag_NoActualizeValues);
  10259. if (result)
  10260. {
  10261. if (!keepConstsInModule)
  10262. CurrentAddToConstHolder(result.mValue);
  10263. setField.mParam = result;
  10264. customAttribute.mSetField.push_back(setField);
  10265. }
  10266. }
  10267. }
  10268. else if (bestProp == NULL)
  10269. {
  10270. Fail(StrFormat("'%s' does not contain a field or property named '%s'", TypeToString(attrTypeInst).c_str(), findName.c_str()), assignExpr->mLeft);
  10271. }
  10272. else
  10273. {
  10274. BfMethodDef* setMethod = NULL;
  10275. for (auto methodDef : bestProp->mMethods)
  10276. {
  10277. if (methodDef->mMethodType == BfMethodType_PropertySetter)
  10278. {
  10279. setMethod = methodDef;
  10280. break;
  10281. }
  10282. }
  10283. if (setMethod == NULL)
  10284. {
  10285. Fail("Property has no setter", assignExpr->mLeft);
  10286. }
  10287. else
  10288. {
  10289. if (mCompiler->mResolvePassData != NULL)
  10290. {
  10291. mCompiler->mResolvePassData->HandlePropertyReference(assignExpr->mLeft, attrTypeDef, bestProp);
  10292. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(assignExpr->mLeft)))
  10293. {
  10294. autoComplete->mDefProp = bestProp;
  10295. autoComplete->mDefType = attrTypeDef;
  10296. }
  10297. }
  10298. handledExpr = true;
  10299. if (bestProp->mProtection != BfProtection_Public)
  10300. Fail(StrFormat("'%s.%s' is inaccessible due to its protection level", TypeToString(bestPropTypeInst).c_str(), findName.c_str()), assignExpr->mLeft); // CS0122
  10301. BfResolvedArg resolvedArg;
  10302. AddDependency(bestPropTypeInst, mCurTypeInstance, BfDependencyMap::DependencyFlag_CustomAttribute);
  10303. BfCustomAttributeSetProperty setProperty;
  10304. setProperty.mPropertyRef = BfPropertyRef(bestPropTypeInst, bestProp);
  10305. // We don't actually need the mFunc, so get the ModuleMethodInstance from the native module
  10306. auto methodInstance = bestPropTypeInst->mModule->GetMethodInstance(bestPropTypeInst, setMethod, BfTypeVector());
  10307. if (methodInstance.mMethodInstance != NULL)
  10308. {
  10309. auto propType = methodInstance.mMethodInstance->GetParamType(0);
  10310. if (assignExpr->mRight != NULL)
  10311. {
  10312. BfTypedValue result = constResolver.Resolve(assignExpr->mRight, propType, BfConstResolveFlag_NoActualizeValues);
  10313. if ((result) && (!result.mType->IsVar()))
  10314. {
  10315. if (!result.mValue.IsConst())
  10316. result = GetDefaultTypedValue(result.mType);
  10317. BF_ASSERT(result.mType == propType);
  10318. if (!keepConstsInModule)
  10319. CurrentAddToConstHolder(result.mValue);
  10320. setProperty.mParam = result;
  10321. customAttribute.mSetProperties.push_back(setProperty);
  10322. }
  10323. }
  10324. }
  10325. }
  10326. }
  10327. if ((!handledExpr) && (assignExpr->mRight != NULL))
  10328. constResolver.Resolve(assignExpr->mRight, NULL, BfConstResolveFlag_NoActualizeValues);
  10329. }
  10330. else
  10331. {
  10332. if (inPropSet)
  10333. {
  10334. Fail("Named attribute argument expected", arg); // CS1016
  10335. }
  10336. BfDeferEvalChecker deferEvalChecker;
  10337. arg->Accept(&deferEvalChecker);
  10338. bool deferParamEval = deferEvalChecker.mNeedsDeferEval;
  10339. BfResolvedArg resolvedArg;
  10340. resolvedArg.mExpression = arg;
  10341. if (deferParamEval)
  10342. {
  10343. resolvedArg.mArgFlags = BfArgFlag_DeferredEval;
  10344. }
  10345. else
  10346. resolvedArg.mTypedValue = constResolver.Resolve(arg, NULL, BfConstResolveFlag_NoActualizeValues);
  10347. if (!inPropSet)
  10348. {
  10349. argValues.push_back(resolvedArg);
  10350. }
  10351. }
  10352. if (autoComplete != NULL)
  10353. autoComplete->mShowAttributeProperties = NULL;
  10354. }
  10355. auto wasCapturingMethodInfo = false;
  10356. if (autoComplete != NULL)
  10357. {
  10358. wasCapturingMethodInfo = autoComplete->mIsCapturingMethodMatchInfo;
  10359. if (attributesDirective->mCtorOpenParen != NULL)
  10360. autoComplete->CheckInvocation(attributesDirective, attributesDirective->mCtorOpenParen, attributesDirective->mCtorCloseParen, attributesDirective->mCommas);
  10361. }
  10362. BfMethodMatcher methodMatcher(attributesDirective, this, "", argValues, BfMethodGenericArguments());
  10363. methodMatcher.mBfEvalExprFlags = constResolver.mBfEvalExprFlags;
  10364. attrTypeDef = attrTypeInst->mTypeDef;
  10365. bool success = true;
  10366. bool isFailurePass = false;
  10367. for (int pass = 0; pass < 2; pass++)
  10368. {
  10369. bool isFailurePass = pass == 1;
  10370. for (auto checkMethod : attrTypeDef->mMethods)
  10371. {
  10372. if ((isFailurePass) && (checkMethod->mMethodDeclaration == NULL))
  10373. continue; // Don't match private default ctor if there's a user-defined one
  10374. if ((checkMethod->mIsStatic) || (checkMethod->mMethodType != BfMethodType_Ctor))
  10375. continue;
  10376. if ((!isFailurePass) && (!CheckProtection(checkMethod->mProtection, attrTypeInst->mTypeDef, false, false)))
  10377. continue;
  10378. methodMatcher.CheckMethod(NULL, attrTypeInst, checkMethod, isFailurePass);
  10379. }
  10380. if ((methodMatcher.mBestMethodDef != NULL) || (methodMatcher.mBackupMethodDef != NULL))
  10381. break;
  10382. }
  10383. if (autoComplete != NULL)
  10384. {
  10385. if ((wasCapturingMethodInfo) && (!autoComplete->mIsCapturingMethodMatchInfo))
  10386. {
  10387. autoComplete->mIsCapturingMethodMatchInfo = true;
  10388. BF_ASSERT(autoComplete->mMethodMatchInfo != NULL);
  10389. }
  10390. else
  10391. autoComplete->mIsCapturingMethodMatchInfo = false;
  10392. }
  10393. if (methodMatcher.mBestMethodDef == NULL)
  10394. methodMatcher.mBestMethodDef = methodMatcher.mBackupMethodDef;
  10395. BF_ASSERT(methodMatcher.mBestMethodDef != NULL);
  10396. customAttribute.mCtor = methodMatcher.mBestMethodDef;
  10397. if (methodMatcher.mBestMethodTypeInstance == mCurTypeInstance)
  10398. {
  10399. Fail("Custom attribute circular reference", attributesDirective);
  10400. }
  10401. if (mCurTypeInstance != NULL)
  10402. AddDependency(methodMatcher.mBestMethodTypeInstance, mCurTypeInstance, BfDependencyMap::DependencyFlag_CustomAttribute);
  10403. if (!constResolver.PrepareMethodArguments(attributesDirective->mAttributeTypeRef, &methodMatcher, customAttribute.mCtorArgs))
  10404. success = false;
  10405. for (auto& arg : argValues)
  10406. {
  10407. if ((arg.mArgFlags & BfArgFlag_DeferredEval) != 0)
  10408. {
  10409. if (auto expr = BfNodeDynCast<BfExpression>(arg.mExpression))
  10410. constResolver.Resolve(expr, NULL, BfConstResolveFlag_NoActualizeValues);
  10411. }
  10412. }
  10413. // Move all those to the constHolder
  10414. if (!keepConstsInModule)
  10415. {
  10416. for (auto& ctorArg : customAttribute.mCtorArgs)
  10417. {
  10418. if (ctorArg.IsConst())
  10419. CurrentAddToConstHolder(ctorArg);
  10420. }
  10421. }
  10422. if (attributesDirective->mAttributeTargetSpecifier != NULL)
  10423. {
  10424. targetOverride = BfAttributeTargets_ReturnValue;
  10425. if (attrTarget != BfAttributeTargets_Method)
  10426. {
  10427. 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.",
  10428. GetAttributesTargetListString(targetOverride).c_str(), GetAttributesTargetListString(attrTarget).c_str()), attributesDirective->mAttributeTargetSpecifier); // CS0657
  10429. success = false;
  10430. }
  10431. }
  10432. if ((success) && (targetOverride != (BfAttributeTargets)0))
  10433. {
  10434. if ((mCurMethodInstance != NULL) && (targetOverride == BfAttributeTargets_ReturnValue) && (attrTarget == BfAttributeTargets_Method))
  10435. {
  10436. auto methodInfoEx = mCurMethodInstance->GetMethodInfoEx();
  10437. if (methodInfoEx->mMethodCustomAttributes == NULL)
  10438. methodInfoEx->mMethodCustomAttributes = new BfMethodCustomAttributes();
  10439. if (success)
  10440. {
  10441. if (methodInfoEx->mMethodCustomAttributes->mReturnCustomAttributes == NULL)
  10442. methodInfoEx->mMethodCustomAttributes->mReturnCustomAttributes = new BfCustomAttributes();
  10443. methodInfoEx->mMethodCustomAttributes->mReturnCustomAttributes->mAttributes.push_back(customAttribute);
  10444. }
  10445. }
  10446. // Mark as failed since we don't actually want to add this to the custom attributes set
  10447. success = false;
  10448. }
  10449. if (success)
  10450. {
  10451. if ((attrTypeInst->mAttributeData->mFlags & BfAttributeFlag_DisallowAllowMultiple) != 0)
  10452. {
  10453. for (auto& prevCustomAttribute : customAttributes->mAttributes)
  10454. {
  10455. if (prevCustomAttribute.mType == attrTypeInst)
  10456. {
  10457. Fail(StrFormat("Duplicate '%s' attribute", attributesDirective->mAttributeTypeRef->ToCleanAttributeString().c_str()), attributesDirective->mAttributeTypeRef); // CS0579
  10458. }
  10459. }
  10460. }
  10461. }
  10462. if (success)
  10463. {
  10464. customAttributes->mAttributes.push_back(customAttribute);
  10465. }
  10466. }
  10467. ValidateCustomAttributes(customAttributes, attrTarget);
  10468. }
  10469. BfCustomAttributes* BfModule::GetCustomAttributes(BfAttributeDirective* attributesDirective, BfAttributeTargets attrType, BfGetCustomAttributesFlags flags, BfCaptureInfo* captureInfo)
  10470. {
  10471. BfCustomAttributes* customAttributes = new BfCustomAttributes();
  10472. GetCustomAttributes(customAttributes, attributesDirective, attrType, flags, captureInfo);
  10473. return customAttributes;
  10474. }
  10475. BfCustomAttributes* BfModule::GetCustomAttributes(BfTypeDef* typeDef)
  10476. {
  10477. BF_ASSERT(mCompiler->IsAutocomplete());
  10478. BfAttributeTargets attrTarget;
  10479. if (typeDef->mIsDelegate)
  10480. attrTarget = BfAttributeTargets_Delegate;
  10481. else if (typeDef->mIsFunction)
  10482. attrTarget = BfAttributeTargets_Function;
  10483. else if (typeDef->mTypeCode == BfTypeCode_Enum)
  10484. attrTarget = BfAttributeTargets_Enum;
  10485. else if (typeDef->mTypeCode == BfTypeCode_Interface)
  10486. attrTarget = BfAttributeTargets_Interface;
  10487. else if (typeDef->mTypeCode == BfTypeCode_Struct)
  10488. attrTarget = BfAttributeTargets_Struct;
  10489. else
  10490. attrTarget = BfAttributeTargets_Class;
  10491. return GetCustomAttributes(typeDef->mTypeDeclaration->mAttributes, attrTarget);
  10492. }
  10493. void BfModule::FinishAttributeState(BfAttributeState* attributeState)
  10494. {
  10495. if ((!attributeState->mUsed) && (attributeState->mSrc != NULL))
  10496. Warn(0, "Unused attributes", attributeState->mSrc);
  10497. }
  10498. void BfModule::ProcessTypeInstCustomAttributes(int& packing, bool& isUnion, bool& isCRepr, bool& isOrdered, int& alignOverride, BfType*& underlyingArrayType, int& underlyingArraySize)
  10499. {
  10500. if (mCurTypeInstance->mTypeDef->mIsAlwaysInclude)
  10501. mCurTypeInstance->mAlwaysIncludeFlags = (BfAlwaysIncludeFlags)(mCurTypeInstance->mAlwaysIncludeFlags | BfAlwaysIncludeFlag_Type);
  10502. if (mCurTypeInstance->mCustomAttributes != NULL)
  10503. {
  10504. for (auto& customAttribute : mCurTypeInstance->mCustomAttributes->mAttributes)
  10505. {
  10506. String typeName = TypeToString(customAttribute.mType);
  10507. if (typeName == "System.PackedAttribute")
  10508. {
  10509. packing = 1;
  10510. if (customAttribute.mCtorArgs.size() >= 1)
  10511. {
  10512. auto alignConstant = mCurTypeInstance->mConstHolder->GetConstant(customAttribute.mCtorArgs[0]);
  10513. int checkPacking = alignConstant->mInt32;
  10514. if (((checkPacking & (checkPacking - 1)) == 0) && (packing > 0) && (packing < 256))
  10515. packing = checkPacking;
  10516. else
  10517. Fail("Packing must be a power of 2", customAttribute.GetRefNode());
  10518. }
  10519. }
  10520. else if (typeName == "System.UnionAttribute")
  10521. {
  10522. isUnion = true;
  10523. }
  10524. else if (typeName == "System.CReprAttribute")
  10525. {
  10526. isCRepr = true;
  10527. isOrdered = true;
  10528. }
  10529. else if (typeName == "System.OrderedAttribute")
  10530. {
  10531. isOrdered = true;
  10532. }
  10533. else if (typeName == "System.AlwaysIncludeAttribute")
  10534. {
  10535. mCurTypeInstance->mAlwaysIncludeFlags = (BfAlwaysIncludeFlags)(mCurTypeInstance->mAlwaysIncludeFlags | BfAlwaysIncludeFlag_Type);
  10536. for (auto setProp : customAttribute.mSetProperties)
  10537. {
  10538. BfPropertyDef* propertyDef = setProp.mPropertyRef;
  10539. if (propertyDef->mName == "AssumeInstantiated")
  10540. {
  10541. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  10542. if ((constant != NULL) && (constant->mBool))
  10543. mCurTypeInstance->mAlwaysIncludeFlags = (BfAlwaysIncludeFlags)(mCurTypeInstance->mAlwaysIncludeFlags | BfAlwaysIncludeFlag_AssumeInstantiated);
  10544. }
  10545. else if (propertyDef->mName == "IncludeAllMethods")
  10546. {
  10547. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  10548. if ((constant != NULL) && (constant->mBool))
  10549. mCurTypeInstance->mAlwaysIncludeFlags = (BfAlwaysIncludeFlags)(mCurTypeInstance->mAlwaysIncludeFlags | BfAlwaysIncludeFlag_IncludeAllMethods);
  10550. }
  10551. }
  10552. }
  10553. else if (typeName == "System.AlignAttribute")
  10554. {
  10555. if (customAttribute.mCtorArgs.size() >= 1)
  10556. {
  10557. auto alignConstant = mCurTypeInstance->mConstHolder->GetConstant(customAttribute.mCtorArgs[0]);
  10558. int checkAlign = alignConstant->mInt32;
  10559. if ((checkAlign & (checkAlign - 1)) == 0)
  10560. alignOverride = checkAlign;
  10561. else
  10562. Fail("Alignment must be a power of 2", customAttribute.GetRefNode());
  10563. }
  10564. }
  10565. else if (typeName == "System.UnderlyingArrayAttribute")
  10566. {
  10567. if (customAttribute.mCtorArgs.size() >= 2)
  10568. {
  10569. auto typeConstant = mCurTypeInstance->mConstHolder->GetConstant(customAttribute.mCtorArgs[0]);
  10570. auto sizeConstant = mCurTypeInstance->mConstHolder->GetConstant(customAttribute.mCtorArgs[1]);
  10571. if ((typeConstant != NULL) && (sizeConstant != NULL) && (typeConstant->mConstType == BfConstType_TypeOf))
  10572. {
  10573. underlyingArrayType = (BfType*)(intptr)typeConstant->mInt64;
  10574. underlyingArraySize = sizeConstant->mInt32;
  10575. }
  10576. }
  10577. }
  10578. if (customAttribute.mType->mAttributeData == NULL)
  10579. PopulateType(customAttribute.mType);
  10580. BF_ASSERT(customAttribute.mType->mAttributeData != NULL);
  10581. if ((customAttribute.mType->mAttributeData != NULL) && ((customAttribute.mType->mAttributeData->mAlwaysIncludeUser & BfAlwaysIncludeFlag_AssumeInstantiated) != 0))
  10582. mCurTypeInstance->mAlwaysIncludeFlags = (BfAlwaysIncludeFlags)(mCurTypeInstance->mAlwaysIncludeFlags | customAttribute.mType->mAttributeData->mAlwaysIncludeUser);
  10583. }
  10584. }
  10585. }
  10586. // Checking to see if we're an attribute or not
  10587. void BfModule::ProcessCustomAttributeData()
  10588. {
  10589. bool isAttribute = false;
  10590. auto checkTypeInst = mCurTypeInstance->mBaseType;
  10591. while (checkTypeInst != NULL)
  10592. {
  10593. if (checkTypeInst->IsInstanceOf(mCompiler->mAttributeTypeDef))
  10594. isAttribute = true;
  10595. checkTypeInst = checkTypeInst->mBaseType;
  10596. }
  10597. if (!isAttribute)
  10598. return;
  10599. auto attributeData = new BfAttributeData();
  10600. bool hasCustomAttribute = false;
  10601. if (mCurTypeInstance->mCustomAttributes != NULL)
  10602. {
  10603. for (auto& customAttribute : mCurTypeInstance->mCustomAttributes->mAttributes)
  10604. {
  10605. if (customAttribute.mType->IsInstanceOf(mCompiler->mAttributeUsageAttributeTypeDef))
  10606. {
  10607. if (customAttribute.mCtorArgs.size() > 0)
  10608. {
  10609. auto constant = mCurTypeInstance->mConstHolder->GetConstant(customAttribute.mCtorArgs[0]);
  10610. if ((constant != NULL) && (mBfIRBuilder->IsInt(constant->mTypeCode)))
  10611. attributeData->mAttributeTargets = (BfAttributeTargets)constant->mInt32;
  10612. }
  10613. if (customAttribute.mCtorArgs.size() == 2)
  10614. {
  10615. auto constant = mCurTypeInstance->mConstHolder->GetConstant(customAttribute.mCtorArgs[0]);
  10616. if ((constant != NULL) && (mBfIRBuilder->IsInt(constant->mTypeCode)))
  10617. {
  10618. attributeData->mFlags = (BfAttributeFlags)constant->mInt32;
  10619. }
  10620. }
  10621. for (auto& setProp : customAttribute.mSetProperties)
  10622. {
  10623. BfPropertyDef* propDef = setProp.mPropertyRef;
  10624. if (propDef->mName == "AllowMultiple")
  10625. {
  10626. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  10627. if ((constant != NULL) && (constant->mBool))
  10628. attributeData->mFlags = (BfAttributeFlags)(attributeData->mFlags & ~BfAttributeFlag_DisallowAllowMultiple);
  10629. else
  10630. attributeData->mFlags = (BfAttributeFlags)(attributeData->mFlags | BfAttributeFlag_DisallowAllowMultiple);
  10631. }
  10632. else if (propDef->mName == "Inherited")
  10633. {
  10634. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  10635. if ((constant != NULL) && (constant->mBool))
  10636. attributeData->mFlags = (BfAttributeFlags)(attributeData->mFlags & ~BfAttributeFlag_NotInherited);
  10637. else
  10638. attributeData->mFlags = (BfAttributeFlags)(attributeData->mFlags | BfAttributeFlag_NotInherited);
  10639. }
  10640. else if (propDef->mName == "ValidOn")
  10641. {
  10642. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  10643. if (constant != NULL)
  10644. attributeData->mAttributeTargets = (BfAttributeTargets)constant->mInt32;
  10645. }
  10646. else if (propDef->mName == "AlwaysIncludeUser")
  10647. {
  10648. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  10649. if (constant != NULL)
  10650. attributeData->mAlwaysIncludeUser = (BfAlwaysIncludeFlags)constant->mInt32;
  10651. }
  10652. }
  10653. hasCustomAttribute = true;
  10654. }
  10655. }
  10656. }
  10657. if ((!hasCustomAttribute) && (mCurTypeInstance->mBaseType->mAttributeData != NULL))
  10658. {
  10659. attributeData->mAttributeTargets = mCurTypeInstance->mBaseType->mAttributeData->mAttributeTargets;
  10660. attributeData->mFlags = mCurTypeInstance->mBaseType->mAttributeData->mFlags;
  10661. attributeData->mAlwaysIncludeUser = mCurTypeInstance->mBaseType->mAttributeData->mAlwaysIncludeUser;
  10662. }
  10663. mCurTypeInstance->mAttributeData = attributeData;
  10664. }
  10665. bool BfModule::TryGetConstString(BfIRConstHolder* constHolder, BfIRValue irValue, StringImpl& str)
  10666. {
  10667. auto constant = constHolder->GetConstant(irValue);
  10668. if (constant == NULL)
  10669. return false;
  10670. if (constant->mTypeCode != BfTypeCode_StringId)
  10671. return false;
  10672. int stringId = constant->mInt32;
  10673. BfStringPoolEntry* entry = NULL;
  10674. if (mContext->mStringObjectIdMap.TryGetValue(stringId, &entry))
  10675. {
  10676. str += entry->mString;
  10677. }
  10678. else
  10679. {
  10680. BF_DBG_FATAL("Failed to find string by id");
  10681. }
  10682. return true;
  10683. }
  10684. BfVariant BfModule::TypedValueToVariant(BfAstNode* refNode, const BfTypedValue& value, bool allowUndef)
  10685. {
  10686. BfVariant variant;
  10687. variant.mTypeCode = BfTypeCode_None;
  10688. BfType* primType = NULL;
  10689. if (value.mType->IsPrimitiveType())
  10690. primType = (BfPrimitiveType*)value.mType;
  10691. else if (value.mType->IsTypedPrimitive())
  10692. primType = value.mType->GetUnderlyingType();
  10693. else if (value.mType->IsInstanceOf(mCompiler->mStringTypeDef))
  10694. primType = value.mType;
  10695. if (primType)
  10696. {
  10697. auto constant = mBfIRBuilder->GetConstant(value.mValue);
  10698. if (constant != NULL)
  10699. {
  10700. if ((allowUndef) && (constant->mConstType == BfConstType_Undef))
  10701. {
  10702. variant.mUInt64 = 0;
  10703. variant.mTypeCode = BfTypeCode_Let;
  10704. return variant;
  10705. }
  10706. if (constant->mConstType == BfConstType_GlobalVar)
  10707. {
  10708. int stringIdx = GetStringPoolIdx(value.mValue, mBfIRBuilder);
  10709. if (stringIdx != -1)
  10710. {
  10711. variant.mTypeCode = BfTypeCode_StringId;
  10712. variant.mInt64 = stringIdx;
  10713. return variant;
  10714. }
  10715. }
  10716. switch (constant->mTypeCode)
  10717. {
  10718. case BfTypeCode_Boolean:
  10719. case BfTypeCode_Int8:
  10720. case BfTypeCode_UInt8:
  10721. case BfTypeCode_Int16:
  10722. case BfTypeCode_UInt16:
  10723. case BfTypeCode_Int32:
  10724. case BfTypeCode_UInt32:
  10725. case BfTypeCode_Int64:
  10726. case BfTypeCode_UInt64:
  10727. case BfTypeCode_IntPtr:
  10728. case BfTypeCode_UIntPtr:
  10729. case BfTypeCode_IntUnknown:
  10730. case BfTypeCode_UIntUnknown:
  10731. case BfTypeCode_Double:
  10732. case BfTypeCode_Char8:
  10733. case BfTypeCode_Char16:
  10734. case BfTypeCode_Char32:
  10735. case BfTypeCode_StringId:
  10736. variant.mTypeCode = constant->mTypeCode;
  10737. variant.mInt64 = constant->mInt64;
  10738. break;
  10739. case BfTypeCode_Float:
  10740. variant.mTypeCode = constant->mTypeCode;
  10741. variant.mSingle = (float)constant->mDouble;
  10742. break;
  10743. default:
  10744. if (refNode != NULL)
  10745. Fail("Invalid const expression type", refNode);
  10746. break;
  10747. }
  10748. }
  10749. }
  10750. return variant;
  10751. }
  10752. BfTypedValue BfModule::RemoveRef(BfTypedValue typedValue)
  10753. {
  10754. if ((typedValue.mType != NULL) && (typedValue.mType->IsRef()))
  10755. {
  10756. auto refType = (BfRefType*)typedValue.mType;
  10757. auto elementType = typedValue.mType->GetUnderlyingType();
  10758. if (typedValue.IsAddr())
  10759. {
  10760. if (elementType->IsValuelessType())
  10761. {
  10762. BF_ASSERT(!typedValue.mValue);
  10763. typedValue = BfTypedValue(typedValue.mValue, elementType, true);
  10764. }
  10765. else
  10766. typedValue = BfTypedValue(mBfIRBuilder->CreateLoad(typedValue.mValue), elementType, true);
  10767. }
  10768. else
  10769. typedValue = BfTypedValue(typedValue.mValue, elementType, true);
  10770. if (typedValue.mType->IsValuelessType())
  10771. {
  10772. BF_ASSERT(typedValue.mValue.IsFake());
  10773. }
  10774. if (refType->mRefKind == BfRefType::RefKind_In)
  10775. {
  10776. if (typedValue.mKind == BfTypedValueKind_Addr)
  10777. typedValue.mKind = BfTypedValueKind_ReadOnlyAddr;
  10778. }
  10779. }
  10780. return typedValue;
  10781. }
  10782. BfTypedValue BfModule::ToRef(BfTypedValue typedValue, BfRefType* refType)
  10783. {
  10784. if (refType == NULL)
  10785. refType = CreateRefType(typedValue.mType);
  10786. if ((refType->mRefKind == BfRefType::RefKind_Mut) && (typedValue.mType->IsObjectOrInterface()))
  10787. {
  10788. return LoadValue(typedValue);
  10789. }
  10790. if (refType->mRefKind == BfRefType::RefKind_Mut)
  10791. refType = CreateRefType(typedValue.mType);
  10792. if (!typedValue.mType->IsValuelessType())
  10793. typedValue = MakeAddressable(typedValue, false, true);
  10794. return BfTypedValue(typedValue.mValue, refType);
  10795. }
  10796. BfTypedValue BfModule::LoadValue(BfTypedValue typedValue, BfAstNode* refNode, bool isVolatile)
  10797. {
  10798. if (!typedValue.IsAddr())
  10799. return typedValue;
  10800. PopulateType(typedValue.mType);
  10801. if ((typedValue.mType->IsValuelessType()) || (typedValue.mType->IsVar()))
  10802. return BfTypedValue(mBfIRBuilder->GetFakeVal(), typedValue.mType, false);
  10803. if (typedValue.mValue.IsConst())
  10804. {
  10805. auto constantValue = mBfIRBuilder->GetConstant(typedValue.mValue);
  10806. if (constantValue != NULL)
  10807. {
  10808. if (constantValue->mConstType == BfConstType_GlobalVar)
  10809. {
  10810. auto globalVar = (BfGlobalVar*)constantValue;
  10811. if (globalVar->mName[0] == '#')
  10812. {
  10813. BfTypedValue result = GetCompilerFieldValue(globalVar->mName);
  10814. if (result)
  10815. return result;
  10816. return GetDefaultTypedValue(typedValue.mType);
  10817. }
  10818. }
  10819. }
  10820. }
  10821. BfIRValue loadedVal = typedValue.mValue;
  10822. if (loadedVal)
  10823. {
  10824. if (typedValue.mType->IsVar())
  10825. {
  10826. return BfTypedValue(loadedVal, typedValue.mType, false);
  10827. }
  10828. /*if (isVolatile)
  10829. mBfIRBuilder->CreateFence(BfIRFenceType_AcquireRelease);*/
  10830. PopulateType(typedValue.mType, BfPopulateType_Data);
  10831. loadedVal = mBfIRBuilder->CreateAlignedLoad(loadedVal, std::max(1, (int)typedValue.mType->mAlign), isVolatile);
  10832. }
  10833. return BfTypedValue(loadedVal, typedValue.mType, false);
  10834. }
  10835. BfTypedValue BfModule::PrepareConst(BfTypedValue& typedValue)
  10836. {
  10837. if (!typedValue.mValue.IsConst())
  10838. return typedValue;
  10839. auto constant = mBfIRBuilder->GetConstant(typedValue.mValue);
  10840. if (constant->mTypeCode == BfTypeCode_StringId)
  10841. return GetTypedValueFromConstant(constant, mBfIRBuilder, typedValue.mType);
  10842. return typedValue;
  10843. }
  10844. BfTypedValue BfModule::LoadOrAggregateValue(BfTypedValue typedValue)
  10845. {
  10846. if (typedValue.IsSplat())
  10847. return AggregateSplat(typedValue);
  10848. if (typedValue.IsAddr())
  10849. return LoadValue(typedValue);
  10850. return typedValue;
  10851. }
  10852. BfTypedValue BfModule::AggregateSplat(BfTypedValue typedValue, BfIRValue* valueArrPtr)
  10853. {
  10854. if (!typedValue.IsSplat())
  10855. return typedValue;
  10856. BF_ASSERT(!mIsComptimeModule);
  10857. if (typedValue.mType->IsValuelessType())
  10858. return typedValue;
  10859. int elementIdx = 0;
  10860. auto _ExtractValue = [&](BfType* checkType)
  10861. {
  10862. if (valueArrPtr != NULL)
  10863. return valueArrPtr[elementIdx++];
  10864. return ExtractSplatValue(typedValue, elementIdx++, checkType);
  10865. };
  10866. std::function<BfIRValue(BfType*)> checkTypeLambda = [&](BfType* checkType)
  10867. {
  10868. if (checkType->IsStruct())
  10869. {
  10870. BfIRValue curValue = mBfIRBuilder->CreateUndefValue(mBfIRBuilder->MapType(checkType, BfIRPopulateType_Full));
  10871. auto checkTypeInstance = checkType->ToTypeInstance();
  10872. if (checkTypeInstance->mBaseType != NULL)
  10873. {
  10874. mBfIRBuilder->PopulateType(checkTypeInstance->mBaseType, BfIRPopulateType_Full);
  10875. BfIRValue baseValue = checkTypeLambda(checkTypeInstance->mBaseType);
  10876. curValue = mBfIRBuilder->CreateInsertValue(curValue, baseValue, 0);
  10877. }
  10878. if (checkTypeInstance->mIsUnion)
  10879. {
  10880. auto unionInnerType = checkTypeInstance->GetUnionInnerType();
  10881. if (!unionInnerType->IsValuelessType())
  10882. {
  10883. BfIRValue fieldValue = checkTypeLambda(unionInnerType);
  10884. curValue = mBfIRBuilder->CreateInsertValue(curValue, fieldValue, 1);
  10885. }
  10886. if (checkTypeInstance->IsEnum())
  10887. {
  10888. auto dscrType = checkTypeInstance->GetDiscriminatorType();
  10889. BfIRValue fieldValue = checkTypeLambda(dscrType);
  10890. curValue = mBfIRBuilder->CreateInsertValue(curValue, fieldValue, 2);
  10891. }
  10892. }
  10893. else
  10894. {
  10895. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  10896. {
  10897. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  10898. if (fieldInstance->mDataIdx >= 0)
  10899. {
  10900. BfIRValue fieldValue = checkTypeLambda(fieldInstance->GetResolvedType());
  10901. curValue = mBfIRBuilder->CreateInsertValue(curValue, fieldValue, fieldInstance->mDataIdx);
  10902. }
  10903. }
  10904. }
  10905. return curValue;
  10906. }
  10907. else if (checkType->IsMethodRef())
  10908. {
  10909. BfMethodRefType* methodRefType = (BfMethodRefType*)checkType;
  10910. BfIRValue curValue = mBfIRBuilder->CreateUndefValue(mBfIRBuilder->MapType(checkType, BfIRPopulateType_Full));
  10911. for (int dataIdx = 0; dataIdx < methodRefType->GetCaptureDataCount(); dataIdx++)
  10912. {
  10913. BfIRValue fieldValue;
  10914. auto checkType = methodRefType->GetCaptureType(dataIdx);
  10915. if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  10916. {
  10917. fieldValue = checkTypeLambda(checkType);
  10918. }
  10919. else
  10920. {
  10921. fieldValue = _ExtractValue(checkType);
  10922. }
  10923. curValue = mBfIRBuilder->CreateInsertValue(curValue, fieldValue, dataIdx);
  10924. }
  10925. return curValue;
  10926. }
  10927. else if (!checkType->IsValuelessType())
  10928. {
  10929. return _ExtractValue(checkType);
  10930. }
  10931. return BfIRValue();
  10932. };
  10933. BfIRValue value = checkTypeLambda(typedValue.mType);
  10934. return BfTypedValue(value, typedValue.mType, typedValue.IsThis() ? BfTypedValueKind_ThisValue : BfTypedValueKind_Value);
  10935. }
  10936. void BfModule::AggregateSplatIntoAddr(BfTypedValue typedValue, BfIRValue addrVal)
  10937. {
  10938. if (!typedValue.IsSplat())
  10939. return;
  10940. if (typedValue.mType->IsValuelessType())
  10941. return;
  10942. BF_ASSERT(!mIsComptimeModule);
  10943. /*static int sCallIdx = 0;
  10944. if (!mCompiler->mIsResolveOnly)
  10945. sCallIdx++;
  10946. int callIdx = sCallIdx;*/
  10947. int elementIdx = 0;
  10948. std::function<void(BfType*, BfIRValue)> checkTypeLambda = [&](BfType* checkType, BfIRValue curAddrVal)
  10949. {
  10950. if (checkType->IsStruct())
  10951. {
  10952. auto checkTypeInstance = checkType->ToTypeInstance();
  10953. if (checkTypeInstance->mBaseType != NULL)
  10954. {
  10955. mBfIRBuilder->PopulateType(checkTypeInstance->mBaseType);
  10956. auto baseAddrVal = mBfIRBuilder->CreateInBoundsGEP(curAddrVal, 0, 0);
  10957. checkTypeLambda(checkTypeInstance->mBaseType, baseAddrVal);
  10958. }
  10959. if (checkTypeInstance->mIsUnion)
  10960. {
  10961. auto unionInnerType = checkTypeInstance->GetUnionInnerType();
  10962. if (!unionInnerType->IsValuelessType())
  10963. {
  10964. auto fieldAddrVal = mBfIRBuilder->CreateInBoundsGEP(curAddrVal, 0, 1);
  10965. checkTypeLambda(unionInnerType, fieldAddrVal);
  10966. }
  10967. if (checkTypeInstance->IsEnum())
  10968. {
  10969. auto dscrType = checkTypeInstance->GetDiscriminatorType();
  10970. auto fieldAddrVal = mBfIRBuilder->CreateInBoundsGEP(curAddrVal, 0, 2);
  10971. checkTypeLambda(dscrType, fieldAddrVal);
  10972. }
  10973. }
  10974. else
  10975. {
  10976. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  10977. {
  10978. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  10979. if (fieldInstance->mDataIdx >= 0)
  10980. {
  10981. auto fieldAddrVal = mBfIRBuilder->CreateInBoundsGEP(curAddrVal, 0, fieldInstance->mDataIdx);
  10982. checkTypeLambda(fieldInstance->mResolvedType, fieldAddrVal);
  10983. }
  10984. }
  10985. }
  10986. }
  10987. else if (checkType->IsMethodRef())
  10988. {
  10989. BfMethodRefType* methodRefType = (BfMethodRefType*)checkType;
  10990. for (int dataIdx = 0; dataIdx < methodRefType->GetCaptureDataCount(); dataIdx++)
  10991. {
  10992. auto dataType = methodRefType->GetCaptureType(dataIdx);
  10993. auto fieldAddrVal = mBfIRBuilder->CreateInBoundsGEP(curAddrVal, 0, dataIdx);
  10994. if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  10995. {
  10996. checkTypeLambda(methodRefType->GetCaptureType(dataIdx), fieldAddrVal);
  10997. }
  10998. else
  10999. {
  11000. // static int sItrCount = 0;
  11001. // sItrCount++;
  11002. // int curItr = sItrCount;
  11003. // if (curItr == 1)
  11004. // {
  11005. // NOP;
  11006. // }
  11007. auto val = ExtractSplatValue(typedValue, elementIdx++, dataType);
  11008. mBfIRBuilder->CreateStore(val, fieldAddrVal);
  11009. }
  11010. }
  11011. }
  11012. else if (!checkType->IsValuelessType())
  11013. {
  11014. auto val = ExtractSplatValue(typedValue, elementIdx++, checkType);
  11015. mBfIRBuilder->CreateStore(val, curAddrVal);
  11016. }
  11017. };
  11018. checkTypeLambda(typedValue.mType, addrVal);
  11019. }
  11020. BfTypedValue BfModule::MakeAddressable(BfTypedValue typedVal, bool forceMutable, bool forceAddressable)
  11021. {
  11022. bool wasReadOnly = typedVal.IsReadOnly();
  11023. if ((forceAddressable) ||
  11024. ((typedVal.mType->IsValueType()) &&
  11025. (!typedVal.mType->IsValuelessType())))
  11026. {
  11027. wasReadOnly = true; // Any non-addr is implicitly read-only
  11028. //static int gCallIdx = 0;
  11029. FixValueActualization(typedVal);
  11030. if (typedVal.IsAddr())
  11031. return typedVal;
  11032. BfType* type = typedVal.mType;
  11033. PopulateType(type);
  11034. BfIRValue tempVar;
  11035. if (typedVal.mValue.IsFake())
  11036. tempVar = mBfIRBuilder->GetFakeVal();
  11037. else
  11038. {
  11039. tempVar = CreateAlloca(type);
  11040. if (typedVal.IsSplat())
  11041. AggregateSplatIntoAddr(typedVal, tempVar);
  11042. else
  11043. mBfIRBuilder->CreateAlignedStore(typedVal.mValue, tempVar, type->mAlign);
  11044. }
  11045. if (forceMutable)
  11046. wasReadOnly = false;
  11047. return BfTypedValue(tempVar, type,
  11048. typedVal.IsThis() ?
  11049. (wasReadOnly ? BfTypedValueKind_ReadOnlyThisAddr : BfTypedValueKind_ThisAddr) :
  11050. (wasReadOnly ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Addr));
  11051. }
  11052. return LoadValue(typedVal);
  11053. }
  11054. BfTypedValue BfModule::RemoveReadOnly(BfTypedValue typedValue)
  11055. {
  11056. if (typedValue.mKind == BfTypedValueKind_ReadOnlyAddr)
  11057. typedValue.mKind = BfTypedValueKind_Addr;
  11058. return typedValue;
  11059. }
  11060. BfTypedValue BfModule::CopyValue(const BfTypedValue& typedValue)
  11061. {
  11062. return MakeAddressable(LoadValue(typedValue), true);
  11063. }
  11064. BfIRValue BfModule::ExtractSplatValue(BfTypedValue typedValue, int componentIdx, BfType* wantType, bool* isAddr)
  11065. {
  11066. BF_ASSERT(!mIsComptimeModule);
  11067. BfIRValue val;
  11068. if (typedValue.mValue.IsArg())
  11069. {
  11070. val = mBfIRBuilder->GetArgument(typedValue.mValue.mId + componentIdx);
  11071. if (isAddr != NULL)
  11072. {
  11073. if (wantType != NULL)
  11074. *isAddr = wantType->IsComposite();
  11075. else
  11076. *isAddr = false;
  11077. }
  11078. else if (wantType->IsComposite())
  11079. val = mBfIRBuilder->CreateLoad(val);
  11080. }
  11081. if (!val)
  11082. {
  11083. auto checkMethodState = mCurMethodState;
  11084. while (checkMethodState != NULL)
  11085. {
  11086. for (int idx = 0; idx < (int)checkMethodState->mSplatDecompAddrs.size(); idx++)
  11087. {
  11088. auto decompAddr = checkMethodState->mSplatDecompAddrs[idx];
  11089. if (decompAddr == typedValue.mValue)
  11090. {
  11091. val = checkMethodState->mSplatDecompAddrs[idx + componentIdx];
  11092. if ((wantType->IsComposite()) && (typedValue.mType->IsMethodRef()))
  11093. {
  11094. // This is really backing for a POINTER to a composite inside a methodRef
  11095. val = mBfIRBuilder->CreateLoad(val);
  11096. }
  11097. if ((isAddr != NULL) && (typedValue.mKind != BfTypedValueKind_SplatHead_NeedsCasting))
  11098. {
  11099. *isAddr = true;
  11100. return val;
  11101. }
  11102. else
  11103. {
  11104. val = mBfIRBuilder->CreateLoad(val);
  11105. break;
  11106. }
  11107. }
  11108. }
  11109. if (val)
  11110. break;
  11111. if ((checkMethodState->mClosureState != NULL) && (checkMethodState->mClosureState->mCapturing))
  11112. {
  11113. BF_ASSERT(mBfIRBuilder->mIgnoreWrites);
  11114. return mBfIRBuilder->GetFakeVal();
  11115. }
  11116. checkMethodState = checkMethodState->mPrevMethodState;
  11117. }
  11118. }
  11119. if (val)
  11120. {
  11121. if (typedValue.mKind == BfTypedValueKind_SplatHead_NeedsCasting)
  11122. {
  11123. BF_ASSERT(wantType != NULL);
  11124. if (wantType != NULL)
  11125. return mBfIRBuilder->CreateBitCast(val, mBfIRBuilder->MapType(wantType));
  11126. }
  11127. return val;
  11128. }
  11129. BFMODULE_FATAL(this, "Splat not found");
  11130. return BfIRValue();
  11131. }
  11132. BfTypedValue BfModule::ExtractValue(BfTypedValue typedValue, BfFieldInstance* fieldInstance, int fieldIdx)
  11133. {
  11134. int useFieldIdx = fieldIdx;
  11135. BfType* fieldType = NULL;
  11136. if (fieldInstance != NULL)
  11137. {
  11138. fieldType = fieldInstance->mResolvedType;
  11139. if (typedValue.mType->IsUnion())
  11140. {
  11141. if (fieldIdx == 1)
  11142. {
  11143. if (typedValue.IsSplat())
  11144. {
  11145. BfTypedValue innerVal = typedValue;
  11146. innerVal.mType = fieldType;
  11147. return innerVal;
  11148. }
  11149. }
  11150. }
  11151. }
  11152. else
  11153. {
  11154. if (typedValue.mType->IsPayloadEnum())
  11155. {
  11156. auto typeInst = typedValue.mType->ToTypeInstance();
  11157. if (fieldIdx == 1)
  11158. fieldType = typeInst->GetUnionInnerType();
  11159. else if (fieldIdx == 2)
  11160. {
  11161. fieldType = typeInst->GetDiscriminatorType(&useFieldIdx);
  11162. }
  11163. }
  11164. else if (typedValue.mType->IsUnion())
  11165. {
  11166. if (fieldIdx == 1)
  11167. {
  11168. fieldType = typedValue.mType->ToTypeInstance()->GetUnionInnerType();
  11169. if (typedValue.IsSplat())
  11170. {
  11171. BfTypedValue innerVal = typedValue;
  11172. innerVal.mType = fieldType;
  11173. return innerVal;
  11174. }
  11175. }
  11176. }
  11177. }
  11178. BF_ASSERT(typedValue.mType->IsStruct());
  11179. if (typedValue.IsSplat())
  11180. {
  11181. if (typedValue.mType->IsPayloadEnum())
  11182. {
  11183. if (fieldIdx == 1)
  11184. {
  11185. // Payload
  11186. auto typeInst = typedValue.mType->ToTypeInstance();
  11187. auto unionInnerType = typeInst->GetUnionInnerType();
  11188. bool isAddr = false;
  11189. BfIRValue irVal = ExtractSplatValue(typedValue, 0, unionInnerType, &isAddr);
  11190. return BfTypedValue(irVal, unionInnerType, BfTypedValueKind_SplatHead);
  11191. }
  11192. if (fieldIdx == 2)
  11193. {
  11194. // Discriminator
  11195. auto typeInst = typedValue.mType->ToTypeInstance();
  11196. auto unionInnerType = typeInst->GetUnionInnerType();
  11197. auto dscrType = typeInst->GetDiscriminatorType();
  11198. int argIdx = typedValue.mValue.mId;
  11199. int componentIdx = 0;
  11200. BfTypeUtils::SplatIterate([&](BfType* checkType) { componentIdx++; }, unionInnerType);
  11201. bool isAddr;
  11202. BfIRValue irVal = ExtractSplatValue(typedValue, componentIdx, dscrType, &isAddr);
  11203. return BfTypedValue(irVal, dscrType, isAddr);
  11204. }
  11205. }
  11206. int componentIdx = 0;
  11207. BfTypedValue retVal;
  11208. BfFieldInstance* wantFieldInstance = fieldInstance;
  11209. std::function<void(BfType*)> checkTypeLambda = [&](BfType* checkType)
  11210. {
  11211. if (checkType->IsStruct())
  11212. {
  11213. auto checkTypeInstance = checkType->ToTypeInstance();
  11214. if ((checkType->IsUnion()) || (checkType->IsEnum()))
  11215. {
  11216. //TODO: Why did we have this removed? It messed up an extraction from a nullable splattable
  11217. fieldType = checkTypeInstance->GetUnionInnerType();
  11218. checkTypeLambda(fieldType);
  11219. if (checkType->IsEnum())
  11220. {
  11221. // Past discriminator...
  11222. componentIdx++;
  11223. }
  11224. return;
  11225. }
  11226. if (checkTypeInstance->mBaseType != NULL)
  11227. checkTypeLambda(checkTypeInstance->mBaseType);
  11228. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  11229. {
  11230. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  11231. if (fieldInstance == wantFieldInstance)
  11232. {
  11233. if (fieldInstance->mResolvedType->IsValuelessType())
  11234. {
  11235. retVal = GetDefaultTypedValue(fieldInstance->mResolvedType);
  11236. break;
  11237. }
  11238. bool isAddr = false;
  11239. BfIRValue val = ExtractSplatValue(typedValue, componentIdx, fieldInstance->mResolvedType, &isAddr);
  11240. retVal = BfTypedValue(val, fieldInstance->mResolvedType,
  11241. fieldInstance->mResolvedType->IsComposite() ? BfTypedValueKind_SplatHead :
  11242. isAddr ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Value);
  11243. if ((retVal.IsAddr()) && (!fieldInstance->mResolvedType->IsValueType()))
  11244. {
  11245. retVal = LoadValue(retVal);
  11246. }
  11247. break;
  11248. }
  11249. if (fieldInstance->mDataIdx >= 0)
  11250. checkTypeLambda(fieldInstance->GetResolvedType());
  11251. }
  11252. }
  11253. else if (!checkType->IsValuelessType())
  11254. {
  11255. componentIdx++;
  11256. //argIdx++;
  11257. }
  11258. };
  11259. checkTypeLambda(typedValue.mType);
  11260. BF_ASSERT(retVal);
  11261. return retVal;
  11262. }
  11263. if (typedValue.IsAddr())
  11264. {
  11265. BF_ASSERT(fieldType != NULL);
  11266. auto valRef = mBfIRBuilder->CreateInBoundsGEP(typedValue.mValue, 0, useFieldIdx);
  11267. return BfTypedValue(valRef, fieldType, BfTypedValueKind_ReadOnlyAddr);
  11268. }
  11269. else
  11270. {
  11271. BF_ASSERT(fieldType != NULL);
  11272. return BfTypedValue(mBfIRBuilder->CreateExtractValue(typedValue.mValue, useFieldIdx), fieldType, BfTypedValueKind_Value);
  11273. }
  11274. }
  11275. BfIRValue BfModule::ExtractValue(BfTypedValue typedValue, int dataIdx)
  11276. {
  11277. if (typedValue.IsAddr())
  11278. {
  11279. auto addrVal = mBfIRBuilder->CreateInBoundsGEP(typedValue.mValue, 0, dataIdx);
  11280. return mBfIRBuilder->CreateLoad(addrVal);
  11281. }
  11282. return mBfIRBuilder->CreateExtractValue(typedValue.mValue, dataIdx);
  11283. }
  11284. BfIRValue BfModule::CreateIndexedValue(BfType* elementType, BfIRValue value, BfIRValue indexValue, bool isElementIndex)
  11285. {
  11286. if (isElementIndex)
  11287. return mBfIRBuilder->CreateInBoundsGEP(value, GetConstValue(0), indexValue);
  11288. else
  11289. return mBfIRBuilder->CreateInBoundsGEP(value, indexValue);
  11290. // if (elementType->IsSizeAligned())
  11291. // {
  11292. // if (isElementIndex)
  11293. // return mBfIRBuilder->CreateInBoundsGEP(value, GetConstValue(0), indexValue);
  11294. // else
  11295. // return mBfIRBuilder->CreateInBoundsGEP(value, indexValue);
  11296. // }
  11297. //
  11298. // auto ptrType = CreatePointerType(elementType);
  11299. // auto ofsVal = mBfIRBuilder->CreateNumericCast(indexValue, true, BfTypeCode_IntPtr);
  11300. // auto ofsScaledVal = mBfIRBuilder->CreateMul(ofsVal, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, elementType->GetStride()));
  11301. // auto i8PtrType = mBfIRBuilder->GetPointerTo(mBfIRBuilder->GetPrimitiveType(BfTypeCode_Int8));
  11302. // BfIRValue origPtrValue = mBfIRBuilder->CreateBitCast(value, i8PtrType);
  11303. // BfIRValue newPtrValue = mBfIRBuilder->CreateInBoundsGEP(origPtrValue, ofsScaledVal);
  11304. // return mBfIRBuilder->CreateBitCast(newPtrValue, mBfIRBuilder->MapType(ptrType));
  11305. }
  11306. BfIRValue BfModule::CreateIndexedValue(BfType* elementType, BfIRValue value, int indexValue, bool isElementIndex)
  11307. {
  11308. if (elementType->IsSizeAligned())
  11309. {
  11310. if (isElementIndex)
  11311. return mBfIRBuilder->CreateInBoundsGEP(value, 0, indexValue);
  11312. else
  11313. return mBfIRBuilder->CreateInBoundsGEP(value, indexValue);
  11314. }
  11315. return CreateIndexedValue(elementType, value, GetConstValue(indexValue), isElementIndex);
  11316. }
  11317. bool BfModule::CheckModifyValue(BfTypedValue& typedValue, BfAstNode* refNode, const char* modifyType)
  11318. {
  11319. if (modifyType == NULL)
  11320. modifyType = "modify";
  11321. if (typedValue.mType->IsVar())
  11322. return true;
  11323. if (typedValue.IsReadOnly())
  11324. {
  11325. Fail(StrFormat("Cannot %s read-only variable", modifyType), refNode);
  11326. return false;
  11327. }
  11328. if ((!typedValue.IsAddr()) && (!typedValue.mType->IsValuelessType()))
  11329. {
  11330. Fail(StrFormat("Cannot %s value", modifyType), refNode);
  11331. return false;
  11332. }
  11333. if (typedValue.mKind == BfTypedValueKind_RestrictedTempAddr)
  11334. {
  11335. Fail(StrFormat("Cannot %s temporary value", modifyType), refNode);
  11336. return false;
  11337. }
  11338. return true;
  11339. }
  11340. bool BfModule::CompareMethodSignatures(BfMethodInstance* methodA, BfMethodInstance* methodB)
  11341. {
  11342. // If one is an interface and the other is an impl, B is the impl
  11343. auto implOwner = methodB->GetOwner();
  11344. if (methodA->mMethodDef->mIsLocalMethod)
  11345. {
  11346. int sepPosA = (int)BF_MIN(methodA->mMethodDef->mName.IndexOf('@'), methodA->mMethodDef->mName.length());
  11347. int sepPosB = (int)BF_MIN(methodB->mMethodDef->mName.IndexOf('@'), methodB->mMethodDef->mName.length());
  11348. if (sepPosA != sepPosB)
  11349. return false;
  11350. if (strncmp(methodA->mMethodDef->mName.c_str(), methodB->mMethodDef->mName.c_str(), sepPosA) != 0)
  11351. return false;
  11352. }
  11353. else if (methodA->mMethodDef->mName != methodB->mMethodDef->mName)
  11354. return false;
  11355. if (methodA->mMethodDef->mCheckedKind != methodB->mMethodDef->mCheckedKind)
  11356. return false;
  11357. if (methodA->mMethodDef->mHasComptime != methodB->mMethodDef->mHasComptime)
  11358. return false;
  11359. if ((methodA->mMethodDef->mMethodType == BfMethodType_Mixin) != (methodB->mMethodDef->mMethodType == BfMethodType_Mixin))
  11360. return false;
  11361. if (methodA->mMethodDef->mMethodType == BfMethodType_Ctor)
  11362. {
  11363. if (methodA->mMethodDef->mIsStatic != methodB->mMethodDef->mIsStatic)
  11364. return false;
  11365. }
  11366. if (methodA->mMethodDef->mMethodType == BfMethodType_Operator)
  11367. {
  11368. if (methodB->mMethodDef->mMethodType != BfMethodType_Operator)
  11369. return false;
  11370. auto operatorA = (BfOperatorDef*)methodA->mMethodDef;
  11371. auto operatorB = (BfOperatorDef*)methodB->mMethodDef;
  11372. if (operatorA->mOperatorDeclaration->mUnaryOp != operatorB->mOperatorDeclaration->mUnaryOp)
  11373. return false;
  11374. if (operatorA->mOperatorDeclaration->mBinOp != operatorB->mOperatorDeclaration->mBinOp)
  11375. return false;
  11376. if (operatorA->mOperatorDeclaration->mAssignOp != operatorB->mOperatorDeclaration->mAssignOp)
  11377. return false;
  11378. if (operatorA->mOperatorDeclaration->mIsConvOperator)
  11379. {
  11380. if (!BfTypeUtils::TypeEquals(methodA->mReturnType, methodB->mReturnType, implOwner))
  11381. return false;
  11382. }
  11383. }
  11384. int implicitParamCountA = methodA->GetImplicitParamCount();
  11385. int implicitParamCountB = methodB->GetImplicitParamCount();
  11386. if (methodA->GetParamCount() - implicitParamCountA != methodB->GetParamCount() - implicitParamCountB)
  11387. return false;
  11388. if (methodA->mHadGenericDelegateParams != methodB->mHadGenericDelegateParams)
  11389. return false;
  11390. for (int paramIdx = 0; paramIdx < (int)methodA->GetParamCount() - implicitParamCountA; paramIdx++)
  11391. {
  11392. if ((!BfTypeUtils::TypeEquals(methodA->GetParamType(paramIdx + implicitParamCountA), methodB->GetParamType(paramIdx + implicitParamCountB), implOwner)) ||
  11393. (methodA->GetParamKind(paramIdx + implicitParamCountA) != methodB->GetParamKind(paramIdx + implicitParamCountB)))
  11394. return false;
  11395. }
  11396. // Compare generic params. Generic params are part of the method signature here
  11397. if (methodA->GetNumGenericParams() != methodB->GetNumGenericParams())
  11398. return false;
  11399. for (int genericParamIdx = 0; genericParamIdx < (int)methodA->GetNumGenericParams(); genericParamIdx++)
  11400. {
  11401. auto genericParamA = methodA->mMethodInfoEx->mGenericParams[genericParamIdx];
  11402. auto genericParamB = methodB->mMethodInfoEx->mGenericParams[genericParamIdx];
  11403. if (genericParamA->mGenericParamFlags != genericParamB->mGenericParamFlags)
  11404. return false;
  11405. if (genericParamA->mTypeConstraint != genericParamB->mTypeConstraint)
  11406. return false;
  11407. if (genericParamA->mInterfaceConstraints.size() != genericParamB->mInterfaceConstraints.size())
  11408. return false;
  11409. for (int interfaceIdx = 0; interfaceIdx < (int)genericParamA->mInterfaceConstraints.size(); interfaceIdx++)
  11410. if (genericParamA->mInterfaceConstraints[interfaceIdx] != genericParamB->mInterfaceConstraints[interfaceIdx])
  11411. return false;
  11412. }
  11413. return true;
  11414. }
  11415. bool BfModule::StrictCompareMethodSignatures(BfMethodInstance* methodA, BfMethodInstance* methodB)
  11416. {
  11417. if (!CompareMethodSignatures(methodA, methodB))
  11418. return false;
  11419. if (methodA->mReturnType != methodB->mReturnType)
  11420. return false;
  11421. if (methodA->mMethodDef->mIsStatic != methodB->mMethodDef->mIsStatic)
  11422. return false;
  11423. return true;
  11424. }
  11425. bool BfModule::IsCompatibleInterfaceMethod(BfMethodInstance* iMethodInst, BfMethodInstance* methodInstance)
  11426. {
  11427. if (iMethodInst->mMethodDef->mName != methodInstance->mMethodDef->mName)
  11428. return false;
  11429. if (iMethodInst->mMethodDef->mIsOperator != methodInstance->mMethodDef->mIsOperator)
  11430. return false;
  11431. if (iMethodInst->mMethodDef->mIsOperator)
  11432. {
  11433. auto iOperatorDef = (BfOperatorDef*)iMethodInst->mMethodDef;
  11434. auto operatorDef = (BfOperatorDef*)methodInstance->mMethodDef;
  11435. if (iOperatorDef->mOperatorDeclaration->mUnaryOp != operatorDef->mOperatorDeclaration->mUnaryOp)
  11436. return false;
  11437. if (iOperatorDef->mOperatorDeclaration->mBinOp != operatorDef->mOperatorDeclaration->mBinOp)
  11438. return false;
  11439. }
  11440. if (iMethodInst->GetParamCount() != methodInstance->GetParamCount())
  11441. return false;
  11442. auto selfType = methodInstance->GetOwner();
  11443. for (int paramIdx = 0; paramIdx < (int)iMethodInst->GetParamCount(); paramIdx++)
  11444. {
  11445. if (iMethodInst->GetParamKind(paramIdx) != methodInstance->GetParamKind(paramIdx))
  11446. return false;
  11447. BfType* iParamType = iMethodInst->GetParamType(paramIdx);
  11448. BfType* methodParamType = methodInstance->GetParamType(paramIdx);
  11449. iParamType = ResolveSelfType(iParamType, selfType);
  11450. methodParamType = ResolveSelfType(methodParamType, selfType);
  11451. if (!iParamType->IsGenericParam())
  11452. {
  11453. if (methodParamType != iParamType)
  11454. return false;
  11455. }
  11456. else
  11457. {
  11458. if (!methodParamType->IsGenericParam())
  11459. return false;
  11460. auto genericParamType = (BfGenericParamType*)methodParamType;
  11461. if (genericParamType->mGenericParamKind == BfGenericParamKind_Type)
  11462. return false;
  11463. auto genericParam = methodInstance->mMethodInfoEx->mGenericParams[genericParamType->mGenericParamIdx];
  11464. bool hadInterface = false;
  11465. for (auto interfaceConstraint : genericParam->mInterfaceConstraints)
  11466. if (interfaceConstraint == iParamType)
  11467. hadInterface = true;
  11468. if (!hadInterface)
  11469. return false;
  11470. }
  11471. }
  11472. return true;
  11473. }
  11474. void BfModule::AddMethodReference(const BfMethodRef& methodRef, BfGetMethodInstanceFlags flags)
  11475. {
  11476. BfMethodInstance* methodInstance = methodRef;
  11477. if ((mCurTypeInstance != NULL) && (!mCompiler->IsAutocomplete()))
  11478. {
  11479. auto methodInstanceGroup = methodInstance->mMethodInstanceGroup;
  11480. if ((methodInstance->IsSpecializedGenericMethod()) || (methodInstanceGroup->mOnDemandKind != BfMethodOnDemandKind_AlwaysInclude))
  11481. {
  11482. BF_ASSERT(!methodRef.mTypeInstance->IsFunction());
  11483. // This ensures we rebuild - there are some cases where we get a method reference but never call it, so this is required here
  11484. AddDependency(methodInstance->GetOwner(), mCurTypeInstance, BfDependencyMap::DependencyFlag_Calls);
  11485. BfMethodRef methodRef = methodInstance;
  11486. BfSpecializedMethodRefInfo* specializedMethodRefInfo = NULL;
  11487. bool isNew = mCurTypeInstance->mSpecializedMethodReferences.TryAdd(methodRef, NULL, &specializedMethodRefInfo);
  11488. if (((flags & BfGetMethodInstanceFlag_Unreified) == 0) &&
  11489. ((flags & BfGetMethodInstanceFlag_NoForceReification) == 0) &&
  11490. (mIsReified))
  11491. {
  11492. specializedMethodRefInfo->mHasReifiedRef = true;
  11493. }
  11494. }
  11495. }
  11496. }
  11497. BfModuleMethodInstance BfModule::ReferenceExternalMethodInstance(BfMethodInstance* methodInstance, BfGetMethodInstanceFlags flags)
  11498. {
  11499. if ((flags & BfGetMethodInstanceFlag_ResultNotUsed) != 0)
  11500. return BfModuleMethodInstance(methodInstance, BfIRValue());
  11501. if (mBfIRBuilder == NULL)
  11502. return BfModuleMethodInstance(methodInstance, BfIRValue());
  11503. if (methodInstance->GetOwner()->IsFunction())
  11504. {
  11505. // No actual ref needed- not an actual generated function
  11506. return BfModuleMethodInstance(methodInstance, BfIRValue());
  11507. }
  11508. bool isGenFunction = methodInstance->mMethodInstanceGroup->mMethodIdx < 0;
  11509. if (!isGenFunction)
  11510. AddMethodReference(methodInstance, flags);
  11511. if ((mBfIRBuilder->mIgnoreWrites) || ((flags & BfGetMethodInstanceFlag_Unreified) != 0))
  11512. return BfModuleMethodInstance(methodInstance, mBfIRBuilder->GetFakeVal());
  11513. if (IsSkippingExtraResolveChecks())
  11514. return BfModuleMethodInstance(methodInstance, BfIRFunction());
  11515. if (methodInstance->mMethodDef->mMethodType == BfMethodType_Mixin)
  11516. {
  11517. return BfModuleMethodInstance(methodInstance, BfIRFunction());
  11518. }
  11519. bool isInlined = (methodInstance->mAlwaysInline) || ((flags & BfGetMethodInstanceFlag_ForceInline) != 0);
  11520. if ((methodInstance->mIsIntrinsic) || (methodInstance->mMethodDef->mIsExtern))
  11521. isInlined = false;
  11522. BfMethodRef methodRef = methodInstance;
  11523. if (isInlined)
  11524. methodRef.mMethodRefFlags = (BfMethodRefFlags)(methodRef.mMethodRefFlags | BfMethodRefFlag_AlwaysInclude);
  11525. else
  11526. methodRef.mMethodRefFlags = BfMethodRefFlag_None;
  11527. if (!isGenFunction)
  11528. {
  11529. BfIRValue* irFuncPtr = NULL;
  11530. if (mFuncReferences.TryGetValue(methodRef, &irFuncPtr))
  11531. return BfModuleMethodInstance(methodInstance, *irFuncPtr);
  11532. }
  11533. if (mAwaitingInitFinish)
  11534. FinishInit();
  11535. BfIRValue func = CreateFunctionFrom(methodInstance, isGenFunction, isInlined);
  11536. if (!isGenFunction)
  11537. {
  11538. BF_ASSERT(func || methodInstance->mMethodInstanceGroup->mOwner->IsInterface());
  11539. mFuncReferences[methodRef] = func;
  11540. }
  11541. BfLogSysM("Adding func reference. Module:%p MethodInst:%p NewLLVMFunc:%d OldLLVMFunc:%d\n", this, methodInstance, func.mId, methodInstance->mIRFunction.mId);
  11542. if ((isInlined) && (!mIsScratchModule) && ((flags & BfGetMethodInstanceFlag_NoInline) == 0))
  11543. {
  11544. // We can't just add a dependency to mCurTypeInstance because we may have nested inlined functions, and
  11545. // mCurTypeInstance will just reflect the owner of the method currently being inlined, not the top-level
  11546. // type instance
  11547. // Be smarter about this if we ever insert a lot of type instances into a single module - track in a field
  11548. BF_ASSERT(mOwnedTypeInstances.size() <= 1);
  11549. for (auto ownedTypeInst : mOwnedTypeInstances)
  11550. AddDependency(methodInstance->GetOwner(), ownedTypeInst, BfDependencyMap::DependencyFlag_InlinedCall);
  11551. if ((!mCompiler->mIsResolveOnly) && (mIsReified) && (!methodInstance->mIsUnspecialized))
  11552. {
  11553. mIncompleteMethodCount++;
  11554. BfInlineMethodRequest* inlineMethodRequest = mContext->mInlineMethodWorkList.Alloc();
  11555. inlineMethodRequest->mType = methodInstance->GetOwner();
  11556. inlineMethodRequest->mFromModule = this;
  11557. inlineMethodRequest->mFunc = func;
  11558. inlineMethodRequest->mFromModuleRevision = mRevision;
  11559. inlineMethodRequest->mMethodInstance = methodInstance;
  11560. BF_ASSERT(mIsModuleMutable);
  11561. BfLogSysM("mInlineMethodWorkList %p for method %p in module %p in ReferenceExternalMethodInstance\n", inlineMethodRequest, methodInstance, this);
  11562. }
  11563. }
  11564. return BfModuleMethodInstance(methodInstance, func);
  11565. }
  11566. BfModule* BfModule::GetOrCreateMethodModule(BfMethodInstance* methodInstance)
  11567. {
  11568. BfTypeInstance* typeInst = methodInstance->mMethodInstanceGroup->mOwner;
  11569. if (mBfIRBuilder == NULL)
  11570. {
  11571. // To allow for custom attribute data
  11572. PrepareForIRWriting(typeInst);
  11573. }
  11574. BfModule* declareModule = this;
  11575. // Get to the optionless branch head -- but this could still be a specialized method module, not the true root
  11576. while ((declareModule->mParentModule != NULL) && (!declareModule->mIsSpecializedMethodModuleRoot))
  11577. declareModule = declareModule->mParentModule;
  11578. // Check for attributes
  11579. if (typeInst == mContext->mBfObjectType)
  11580. {
  11581. auto methodDecl = methodInstance->mMethodDef->GetMethodDeclaration();
  11582. if (methodDecl != NULL)
  11583. {
  11584. auto attributesDirective = methodDecl->mAttributes;
  11585. if ((attributesDirective != NULL) && (mCompiler->mResolvePassData != NULL) &&
  11586. (attributesDirective->IsFromParser(mCompiler->mResolvePassData->mParser)) && (mCompiler->mResolvePassData->mSourceClassifier != NULL))
  11587. {
  11588. mCompiler->mResolvePassData->mSourceClassifier->VisitChild(attributesDirective);
  11589. }
  11590. }
  11591. }
  11592. else
  11593. {
  11594. // Only allow attributes on System.Object methods that can be handled inside the DefBuilder
  11595. GetMethodCustomAttributes(methodInstance);
  11596. }
  11597. BF_ASSERT(mModuleOptions == NULL);
  11598. if (methodInstance->GetCustomAttributes() != NULL)
  11599. {
  11600. auto project = typeInst->mTypeDef->mProject;
  11601. BfModuleOptions moduleOptions = declareModule->GetModuleOptions();
  11602. BfModuleOptions wantOptions = moduleOptions;
  11603. auto typeOptions = mSystem->GetTypeOptions(typeInst->mTypeOptionsIdx);
  11604. if (typeOptions != NULL)
  11605. {
  11606. wantOptions.mOptLevel = (BfOptLevel)BfTypeOptions::Apply((int)wantOptions.mOptLevel, (int)typeOptions->mOptimizationLevel);
  11607. wantOptions.mSIMDSetting = (BfSIMDSetting)BfTypeOptions::Apply((int)wantOptions.mSIMDSetting, typeOptions->mSIMDSetting);
  11608. wantOptions.mEmitDebugInfo = (BfSIMDSetting)BfTypeOptions::Apply((int)wantOptions.mEmitDebugInfo, typeOptions->mEmitDebugInfo);
  11609. }
  11610. if (!mCompiler->mAttributeTypeOptionMap.IsEmpty())
  11611. {
  11612. StringT<128> attrName;
  11613. for (auto& customAttrs : methodInstance->GetCustomAttributes()->mAttributes)
  11614. {
  11615. attrName.Clear();
  11616. customAttrs.mType->mTypeDef->mFullName.ToString(attrName);
  11617. Array<int>* arrPtr;
  11618. if (mCompiler->mAttributeTypeOptionMap.TryGetValue(attrName, &arrPtr))
  11619. {
  11620. for (auto optionsIdx : *arrPtr)
  11621. {
  11622. auto& typeOptions = mCompiler->mSystem->mTypeOptions[optionsIdx];
  11623. wantOptions.mOptLevel = (BfOptLevel)BfTypeOptions::Apply((int)wantOptions.mOptLevel, (int)typeOptions.mOptimizationLevel);
  11624. wantOptions.mSIMDSetting = (BfSIMDSetting)BfTypeOptions::Apply((int)wantOptions.mSIMDSetting, typeOptions.mSIMDSetting);
  11625. wantOptions.mEmitDebugInfo = (BfSIMDSetting)BfTypeOptions::Apply((int)wantOptions.mEmitDebugInfo, typeOptions.mEmitDebugInfo);
  11626. }
  11627. }
  11628. }
  11629. }
  11630. if ((HasCompiledOutput()) && (wantOptions != moduleOptions) && (!mIsScratchModule))
  11631. {
  11632. auto lastCheckModule = this;
  11633. auto checkModule = this->mNextAltModule;
  11634. while (checkModule != NULL)
  11635. {
  11636. if (*checkModule->mModuleOptions == wantOptions)
  11637. {
  11638. declareModule = checkModule;
  11639. break;
  11640. }
  11641. lastCheckModule = checkModule;
  11642. checkModule = checkModule->mNextAltModule;
  11643. }
  11644. // Not found?
  11645. if (declareModule == this)
  11646. {
  11647. String specModuleName = mModuleName + "@@";
  11648. if (wantOptions.mOptLevel != moduleOptions.mOptLevel)
  11649. specModuleName += StrFormat("O%d", wantOptions.mOptLevel);
  11650. if (wantOptions.mSIMDSetting != moduleOptions.mSIMDSetting)
  11651. specModuleName += StrFormat("SIMD%d", wantOptions.mSIMDSetting);
  11652. declareModule = new BfModule(mContext, specModuleName);
  11653. declareModule->mProject = project;
  11654. declareModule->mModuleOptions = new BfModuleOptions();
  11655. *declareModule->mModuleOptions = wantOptions;
  11656. declareModule->mParentModule = lastCheckModule;
  11657. declareModule->Init();
  11658. lastCheckModule->mNextAltModule = declareModule;
  11659. }
  11660. }
  11661. }
  11662. declareModule->PrepareForIRWriting(typeInst);
  11663. return declareModule;
  11664. }
  11665. BfModuleMethodInstance BfModule::GetMethodInstance(BfTypeInstance* typeInst, BfMethodDef* methodDef, const BfTypeVector& methodGenericArguments, BfGetMethodInstanceFlags flags, BfTypeInstance* foreignType)
  11666. {
  11667. if (methodDef->mMethodType == BfMethodType_Init)
  11668. return BfModuleMethodInstance();
  11669. if (((flags & BfGetMethodInstanceFlag_ForceInline) != 0) && (mCompiler->mIsResolveOnly))
  11670. {
  11671. // Don't bother inlining for resolve-only
  11672. flags = (BfGetMethodInstanceFlags)(flags & ~BfGetMethodInstanceFlag_ForceInline);
  11673. }
  11674. if (methodDef->mIsExtern)
  11675. flags = (BfGetMethodInstanceFlags)(flags & ~BfGetMethodInstanceFlag_ForceInline);
  11676. bool processNow = false;
  11677. bool keepInCurrentModule = false;
  11678. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mIsUnspecialized))
  11679. flags = (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_NoForceReification);
  11680. if (!typeInst->IsTypeMemberIncluded(methodDef->mDeclaringType))
  11681. {
  11682. return BfModuleMethodInstance();
  11683. }
  11684. if (methodDef->mIsLocalMethod)
  11685. {
  11686. auto rootMethodState = mCurMethodState->GetRootMethodState();
  11687. BfLocalMethod* localMethod;
  11688. if (rootMethodState->mLocalMethodCache.TryGetValue(methodDef->mName, &localMethod))
  11689. {
  11690. // Handle the def in the correct method state
  11691. return GetLocalMethodInstance(localMethod, methodGenericArguments);
  11692. }
  11693. BFMODULE_FATAL(this, "Cannot find local method");
  11694. return BfModuleMethodInstance();
  11695. }
  11696. #ifdef _DEBUG
  11697. for (auto arg : methodGenericArguments)
  11698. BF_ASSERT(!arg->IsVar());
  11699. #endif
  11700. BF_ASSERT(methodDef->mMethodType != BfMethodType_Ignore);
  11701. // We need to do the 'mNeedsMethodProcessing' check because we want to do a proper initial "awaiting reference" population
  11702. // on the methods before we handle an on-demand situation. This also ensures that our type options are set before doing
  11703. // a FinishInit
  11704. if ((typeInst->IsIncomplete()) &&
  11705. (!typeInst->mResolvingVarField) && (!typeInst->mTypeFailed))
  11706. {
  11707. // For autocomplete, we still may not actually generate methods. This shouldn't matter, and on-demand works differently
  11708. // for resolve-only because we don't differentiate between reified/unreified there
  11709. if ((methodDef->mIsStatic) /*&& (mIsComptimeModule)*/)
  11710. {
  11711. if (!typeInst->DefineStateAllowsStaticMethods())
  11712. PopulateType(typeInst, BfPopulateType_AllowStaticMethods);
  11713. }
  11714. else
  11715. PopulateType(typeInst, BfPopulateType_Full);
  11716. }
  11717. bool tryModuleMethodLookup = false;
  11718. BfModuleMethodInstance moduleMethodInst;
  11719. BfModule* instModule = typeInst->mModule;
  11720. if (keepInCurrentModule)
  11721. {
  11722. // Stay here
  11723. instModule = this;
  11724. }
  11725. if (this == mContext->mUnreifiedModule)
  11726. {
  11727. // Stay in this 'resolve only' module here
  11728. }
  11729. else if (flags & BfGetMethodInstanceFlag_ExplicitResolveOnlyPass)
  11730. {
  11731. BF_ASSERT(this == mContext->mUnreifiedModule);
  11732. }
  11733. else if (flags & BfGetMethodInstanceFlag_ExplicitSpecializedModule)
  11734. {
  11735. BF_ASSERT(instModule == mParentModule);
  11736. }
  11737. else if (instModule != this)
  11738. {
  11739. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mMethodInfoEx != NULL) && (mCurMethodInstance->mMethodInfoEx->mMinDependDepth >= 32))
  11740. flags = (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_DepthExceeded);
  11741. if ((!mIsComptimeModule) && (!mIsReified) && (instModule->mIsReified))
  11742. {
  11743. BF_ASSERT(!mCompiler->mIsResolveOnly);
  11744. // A resolve-only module is specializing a method from a type in a reified module,
  11745. // we need to take care that this doesn't cause anything new to become reified
  11746. BfModuleMethodInstance moduleMethodInstance = mContext->mUnreifiedModule->GetMethodInstance(typeInst, methodDef, methodGenericArguments, (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_ExplicitResolveOnlyPass), foreignType);
  11747. if (!moduleMethodInstance)
  11748. return moduleMethodInstance;
  11749. SetMethodDependency(moduleMethodInstance.mMethodInstance);
  11750. return moduleMethodInstance;
  11751. }
  11752. else
  11753. {
  11754. if ((!mIsComptimeModule) && (mIsReified) && (!instModule->mIsReified))
  11755. {
  11756. if (!typeInst->IsUnspecializedType())
  11757. {
  11758. if (!instModule->mReifyQueued)
  11759. {
  11760. BF_ASSERT((instModule != mContext->mUnreifiedModule) && (instModule != mContext->mScratchModule));
  11761. BF_ASSERT((mCompiler->mCompileState != BfCompiler::CompileState_Unreified) && (mCompiler->mCompileState != BfCompiler::CompileState_VData));
  11762. BfLogSysM("Queueing ReifyModule: %p\n", instModule);
  11763. mContext->mReifyModuleWorkList.Add(instModule);
  11764. instModule->mReifyQueued = true;
  11765. }
  11766. // This ensures that the method will actually be created when it gets reified
  11767. BfMethodSpecializationRequest* specializationRequest = mContext->mMethodSpecializationWorkList.Alloc();
  11768. specializationRequest->mFromModule = typeInst->mModule;
  11769. specializationRequest->mFromModuleRevision = typeInst->mModule->mRevision;
  11770. specializationRequest->Init(typeInst, foreignType, methodDef);
  11771. //specializationRequest->mMethodDef = methodDef;
  11772. specializationRequest->mMethodGenericArguments = methodGenericArguments;
  11773. specializationRequest->mType = typeInst;
  11774. specializationRequest->mFlags = flags;
  11775. }
  11776. }
  11777. auto defFlags = (BfGetMethodInstanceFlags)(flags & ~BfGetMethodInstanceFlag_ForceInline);
  11778. defFlags = (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_NoReference);
  11779. if (mIsComptimeModule)
  11780. {
  11781. defFlags = (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_MethodInstanceOnly);
  11782. if (!mCompiler->mIsResolveOnly)
  11783. defFlags = (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_NoForceReification | BfGetMethodInstanceFlag_Unreified | BfGetMethodInstanceFlag_MethodInstanceOnly);
  11784. }
  11785. // Not extern
  11786. // Create the instance in the proper module and then create a reference in this one
  11787. moduleMethodInst = instModule->GetMethodInstance(typeInst, methodDef, methodGenericArguments, defFlags, foreignType);
  11788. if (!moduleMethodInst)
  11789. return moduleMethodInst;
  11790. tryModuleMethodLookup = true;
  11791. if ((mIsReified) && (!moduleMethodInst.mMethodInstance->mIsReified))
  11792. {
  11793. CheckHotMethod(moduleMethodInst.mMethodInstance, "");
  11794. }
  11795. }
  11796. }
  11797. if (tryModuleMethodLookup)
  11798. {
  11799. SetMethodDependency(moduleMethodInst.mMethodInstance);
  11800. return ReferenceExternalMethodInstance(moduleMethodInst.mMethodInstance, flags);
  11801. }
  11802. if (((flags & BfGetMethodInstanceFlag_ForceInline) != 0) && (!methodDef->mAlwaysInline))
  11803. {
  11804. auto moduleMethodInstance = GetMethodInstance(typeInst, methodDef, methodGenericArguments, (BfGetMethodInstanceFlags)(flags & ~BfGetMethodInstanceFlag_ForceInline), foreignType);
  11805. if (moduleMethodInstance)
  11806. return ReferenceExternalMethodInstance(moduleMethodInstance.mMethodInstance, flags);
  11807. return moduleMethodInst;
  11808. }
  11809. bool isReified = mIsReified /* || ((flags & BfGetMethodInstanceFlag_ExplicitResolveOnlyPass) != 0)*/;
  11810. bool hadConcreteInterfaceGenericArgument = false;
  11811. if ((flags & BfGetMethodInstanceFlag_Unreified) != 0)
  11812. isReified = false;
  11813. if ((flags & BfGetMethodInstanceFlag_ExplicitResolveOnlyPass) != 0)
  11814. {
  11815. isReified = false;
  11816. }
  11817. BfTypeVector sanitizedMethodGenericArguments;
  11818. SizedArray<BfProject*, 4> projectList;
  11819. bool isUnspecializedPass = (flags & BfGetMethodInstanceFlag_UnspecializedPass) != 0;
  11820. if ((isUnspecializedPass) && (methodDef->mGenericParams.size() == 0))
  11821. isUnspecializedPass = false;
  11822. // 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
  11823. bool isExternalExtensionMethod = false;
  11824. if ((!typeInst->IsUnspecializedType()) && (!isUnspecializedPass))
  11825. {
  11826. if (((flags & BfGetMethodInstanceFlag_ForeignMethodDef) == 0) &&
  11827. (methodDef->mDeclaringType != NULL) &&
  11828. (methodDef->mDeclaringType->mProject != typeInst->mTypeDef->mProject))
  11829. {
  11830. auto specProject = methodDef->mDeclaringType->mProject;
  11831. isExternalExtensionMethod = true;
  11832. if (typeInst->IsGenericTypeInstance())
  11833. {
  11834. auto genericTypeInst = (BfTypeInstance*)typeInst;
  11835. if (genericTypeInst->mGenericTypeInfo->mProjectsReferenced.empty())
  11836. genericTypeInst->GenerateProjectsReferenced();
  11837. if (genericTypeInst->mGenericTypeInfo->mProjectsReferenced.Contains(specProject))
  11838. {
  11839. // This is a generic type where a generic param is already confined to the project in question
  11840. isExternalExtensionMethod = false;
  11841. }
  11842. }
  11843. if (isExternalExtensionMethod)
  11844. {
  11845. BF_ASSERT(typeInst->mTypeDef->mIsCombinedPartial);
  11846. projectList.push_back(methodDef->mDeclaringType->mProject);
  11847. }
  11848. }
  11849. }
  11850. if ((!isUnspecializedPass) && (methodGenericArguments.size() != 0))
  11851. {
  11852. int typeProjectsCounts = 0;
  11853. if (typeInst->IsGenericTypeInstance())
  11854. {
  11855. auto genericTypeInst = (BfTypeInstance*)typeInst;
  11856. if (genericTypeInst->mGenericTypeInfo->mProjectsReferenced.empty())
  11857. genericTypeInst->GenerateProjectsReferenced();
  11858. typeProjectsCounts = (int)genericTypeInst->mGenericTypeInfo->mProjectsReferenced.size();
  11859. projectList.Insert(0, &genericTypeInst->mGenericTypeInfo->mProjectsReferenced[0], genericTypeInst->mGenericTypeInfo->mProjectsReferenced.size());
  11860. }
  11861. else
  11862. {
  11863. typeProjectsCounts = 1;
  11864. projectList.Insert(0, typeInst->mTypeDef->mProject);
  11865. }
  11866. isUnspecializedPass = true;
  11867. for (int genericArgIdx = 0; genericArgIdx < (int) methodGenericArguments.size(); genericArgIdx++)
  11868. {
  11869. auto genericArgType = methodGenericArguments[genericArgIdx];
  11870. //BF_ASSERT(!genericArgType->IsRef());
  11871. if (genericArgType->IsConcreteInterfaceType())
  11872. {
  11873. hadConcreteInterfaceGenericArgument = true;
  11874. auto concreteInterfaceType = (BfConcreteInterfaceType*)genericArgType;
  11875. genericArgType = concreteInterfaceType->mInterface;
  11876. }
  11877. if (genericArgType->IsGenericParam())
  11878. {
  11879. auto genericParam = (BfGenericParamType*) genericArgType;
  11880. if ((genericParam->mGenericParamKind != BfGenericParamKind_Method) || (genericParam->mGenericParamIdx != genericArgIdx))
  11881. isUnspecializedPass = false;
  11882. }
  11883. else
  11884. {
  11885. BfTypeUtils::GetProjectList(genericArgType, &projectList, typeProjectsCounts);
  11886. isUnspecializedPass = false;
  11887. }
  11888. sanitizedMethodGenericArguments.push_back(genericArgType);
  11889. }
  11890. if ((int)projectList.size() > typeProjectsCounts)
  11891. {
  11892. // Just leave the new items
  11893. projectList.RemoveRange(0, typeProjectsCounts);
  11894. std::sort(projectList.begin(), projectList.end(), [](BfProject* lhs, BfProject*rhs)
  11895. {
  11896. return lhs->mName < rhs->mName;
  11897. });
  11898. }
  11899. else
  11900. {
  11901. projectList.Clear();
  11902. }
  11903. }
  11904. const BfTypeVector& lookupMethodGenericArguments = isUnspecializedPass ? BfTypeVector() : sanitizedMethodGenericArguments;
  11905. BfMethodInstanceGroup* methodInstGroup = NULL;
  11906. if ((flags & BfGetMethodInstanceFlag_ForeignMethodDef) != 0)
  11907. {
  11908. BF_ASSERT(!typeInst->IsInterface());
  11909. //for (auto& checkGroup : typeInst->mMethodInstanceGroups)
  11910. for (int methodIdx = (int)typeInst->mTypeDef->mMethods.size(); methodIdx < (int)typeInst->mMethodInstanceGroups.size(); methodIdx++)
  11911. {
  11912. auto& checkGroup = typeInst->mMethodInstanceGroups[methodIdx];
  11913. // if (checkGroup.mDefault == NULL)
  11914. // {
  11915. // // This should only be for when we explicitly add a spot so we can set mOnDemandKind
  11916. // BF_ASSERT(methodIdx == typeInst->mMethodInstanceGroups.size() - 1);
  11917. // methodInstGroup = &checkGroup;
  11918. // break;
  11919. // }
  11920. if ((checkGroup.mDefault != NULL) && (checkGroup.mDefault->mMethodDef == methodDef))
  11921. {
  11922. methodInstGroup = &checkGroup;
  11923. break;
  11924. }
  11925. }
  11926. if (methodInstGroup == NULL)
  11927. {
  11928. // Allocate a new entry
  11929. typeInst->mMethodInstanceGroups.Resize(typeInst->mMethodInstanceGroups.size() + 1);
  11930. methodInstGroup = &typeInst->mMethodInstanceGroups.back();
  11931. methodInstGroup->mMethodIdx = (int)typeInst->mMethodInstanceGroups.size() - 1;
  11932. methodInstGroup->mOwner = typeInst;
  11933. // if (methodInstGroup->mOnDemandKind == BfMethodOnDemandKind_NotSet)
  11934. // methodInstGroup->mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  11935. if (mCompiler->mOptions.mCompileOnDemandKind == BfCompileOnDemandKind_AlwaysInclude)
  11936. methodInstGroup->mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  11937. else
  11938. methodInstGroup->mOnDemandKind = BfMethodOnDemandKind_Decl_AwaitingDecl;
  11939. }
  11940. }
  11941. else
  11942. {
  11943. methodInstGroup = &typeInst->mMethodInstanceGroups[methodDef->mIdx];
  11944. }
  11945. if (methodInstGroup->mOnDemandKind == BfMethodOnDemandKind_NotSet)
  11946. {
  11947. if (typeInst->mDefineState > BfTypeDefineState_DefinedAndMethodsSlotted)
  11948. {
  11949. BfLogSysM("Forcing BfMethodOnDemandKind_NotSet to BfMethodOnDemandKind_AlwaysInclude for Method:%s in Type:%p\n", methodDef->mName.c_str(), typeInst);
  11950. methodInstGroup->mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  11951. }
  11952. }
  11953. BfIRFunction prevIRFunc;
  11954. bool doingRedeclare = false;
  11955. BfMethodInstance* methodInstance = NULL;
  11956. auto _SetReified = [&]()
  11957. {
  11958. methodInstance->mIsReified = true;
  11959. };
  11960. if (lookupMethodGenericArguments.size() == 0)
  11961. {
  11962. methodInstance = methodInstGroup->mDefault;
  11963. if ((methodInstance != NULL) && ((flags & BfGetMethodInstanceFlag_MethodInstanceOnly) != 0))
  11964. return methodInstance;
  11965. if ((methodInstance != NULL) && (isReified) && (!methodInstance->mIsReified))
  11966. {
  11967. MarkDerivedDirty(typeInst);
  11968. if (!HasCompiledOutput())
  11969. {
  11970. BfLogSysM("Marking non-compiled-output module method instance as reified: %p\n", methodInstance);
  11971. _SetReified();
  11972. CheckHotMethod(methodInstance, "");
  11973. }
  11974. else if ((flags & BfGetMethodInstanceFlag_NoForceReification) != 0)
  11975. {
  11976. // We don't need to force reification if we're in an unspecialized generic- we can wait for
  11977. // the specializations to handle that for us
  11978. return BfModuleMethodInstance(methodInstance);
  11979. }
  11980. else if (methodInstGroup->mOnDemandKind == BfMethodOnDemandKind_Referenced)
  11981. {
  11982. if (methodDef->mIsAbstract)
  11983. {
  11984. BfLogSysM("Reifying abstract unreified method instance: %p IRFunction:%d\n", methodInstance, methodInstance->mIRFunction.mId);
  11985. _SetReified();
  11986. }
  11987. else
  11988. {
  11989. BfLogSysM("Re-declaring processed but unreified method instance: %p IRFunction:%d\n", methodInstance, methodInstance->mIRFunction.mId);
  11990. methodInstGroup->mOnDemandKind = BfMethodOnDemandKind_NoDecl_AwaitingReference;
  11991. methodInstance->UndoDeclaration(!methodInstance->mIRFunction.IsFake());
  11992. doingRedeclare = true;
  11993. mOnDemandMethodCount++;
  11994. VerifyOnDemandMethods();
  11995. }
  11996. }
  11997. else
  11998. {
  11999. BfLogSysM("Marking unprocessed method instance as reified: %p\n", methodInstance);
  12000. // We haven't processed it yet
  12001. _SetReified();
  12002. CheckHotMethod(methodInstance, "");
  12003. if (methodInstance->mDeclModule == this)
  12004. {
  12005. if (methodInstance->mMethodProcessRequest != NULL)
  12006. {
  12007. // Disconnect method process request
  12008. BF_ASSERT(methodInstance->mMethodProcessRequest->mFromModule == this);
  12009. }
  12010. }
  12011. else
  12012. {
  12013. if (methodInstance->mMethodProcessRequest != NULL)
  12014. {
  12015. // Disconnect method process request
  12016. methodInstance->mMethodProcessRequest->mMethodInstance = NULL;
  12017. methodInstance->mMethodProcessRequest = NULL;
  12018. }
  12019. if (methodInstance->mDeclModule == mContext->mUnreifiedModule)
  12020. {
  12021. // Add new request in proper module
  12022. methodInstance->mDeclModule = this;
  12023. }
  12024. else
  12025. {
  12026. if (methodInstance->mDeclModule == NULL)
  12027. {
  12028. //
  12029. }
  12030. else if (methodInstance->mDeclModule != this)
  12031. {
  12032. // Is from specialized module?
  12033. BF_ASSERT(methodInstance->mDeclModule->mParentModule == this);
  12034. }
  12035. }
  12036. if ((!methodInstance->mIRFunction) || (methodInstance->mIRFunction.IsFake()))
  12037. {
  12038. methodInstance->mIRFunction = BfIRFunction();
  12039. if (!mIsModuleMutable)
  12040. StartExtension();
  12041. if ((!mBfIRBuilder->mIgnoreWrites) && (methodInstance->mDeclModule != NULL))
  12042. {
  12043. StringT<128> mangledName;
  12044. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), methodInstance);
  12045. bool isIntrinsic = false;
  12046. SetupIRFunction(methodInstance, mangledName, false, &isIntrinsic);
  12047. BfLogSysM("Creating new IRFunction %d\n", methodInstance->mIRFunction.mId);
  12048. }
  12049. }
  12050. AddMethodToWorkList(methodInstance);
  12051. }
  12052. }
  12053. }
  12054. }
  12055. else
  12056. {
  12057. BF_ASSERT(lookupMethodGenericArguments.size() != 0);
  12058. if (methodInstGroup->mMethodSpecializationMap == NULL)
  12059. methodInstGroup->mMethodSpecializationMap = new BfMethodInstanceGroup::MapType();
  12060. BfMethodInstance** methodInstancePtr = NULL;
  12061. if (methodInstGroup->mMethodSpecializationMap->TryGetValue(lookupMethodGenericArguments, &methodInstancePtr))
  12062. {
  12063. methodInstance = *methodInstancePtr;
  12064. if ((flags & BfGetMethodInstanceFlag_MethodInstanceOnly) != 0)
  12065. return methodInstance;
  12066. if ((methodInstance->mRequestedByAutocomplete) && (!mCompiler->IsAutocomplete()))
  12067. {
  12068. BfLogSysM("Setting mRequestedByAutocomplete=false for method instance %p\n", methodInstance);
  12069. // We didn't want to process this message yet if it was autocomplete-specific, but now we will
  12070. if (methodInstance->mMethodProcessRequest == NULL)
  12071. AddMethodToWorkList(methodInstance);
  12072. methodInstance->mRequestedByAutocomplete = false;
  12073. }
  12074. if ((isReified) && (!methodInstance->mIsReified))
  12075. {
  12076. MarkDerivedDirty(typeInst);
  12077. if (methodInstance->mHasBeenProcessed)
  12078. {
  12079. BfLogSysM("Deleting processed but unreified specialized method instance %p\n", methodInstance);
  12080. delete methodInstance;
  12081. methodInstGroup->mMethodSpecializationMap->Remove(lookupMethodGenericArguments);
  12082. methodInstance = NULL;
  12083. }
  12084. else if ((!methodInstance->mIRFunction) || (methodInstance->mIRFunction.IsFake()))
  12085. {
  12086. BfLogSysM("Deleting declared but uncreated specialized method instance %p\n", methodInstance);
  12087. delete methodInstance;
  12088. methodInstGroup->mMethodSpecializationMap->Remove(lookupMethodGenericArguments);
  12089. methodInstance = NULL;
  12090. }
  12091. else
  12092. {
  12093. BfLogSysM("Reifying declared but unreified method instance %p\n", methodInstance);
  12094. // We haven't processed it yet
  12095. _SetReified();
  12096. CheckHotMethod(methodInstance, "");
  12097. if (methodInstance->mMethodProcessRequest == NULL)
  12098. AddMethodToWorkList(methodInstance);
  12099. }
  12100. }
  12101. }
  12102. }
  12103. if ((methodInstance != NULL) && (!doingRedeclare))
  12104. {
  12105. SetMethodDependency(methodInstance);
  12106. if (methodInstance->mMethodInstanceGroup->mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingReference)
  12107. {
  12108. /*if ((!mCompiler->mIsResolveOnly) && (!isReified))
  12109. BF_ASSERT(!methodInstance->mIsReified);*/
  12110. if (methodInstance->mIsReified != isReified)
  12111. BfLogSysM("GetMethodInstance %p Decl_AwaitingReference setting reified to %d\n", methodInstance, isReified);
  12112. if ((!isReified) &&
  12113. ((methodInstance->mDeclModule == NULL) || (!methodInstance->mDeclModule->mIsModuleMutable)))
  12114. {
  12115. methodInstance->mDeclModule = mContext->mUnreifiedModule;
  12116. methodInstance->mIRFunction = BfIRFunction();
  12117. }
  12118. methodInstance->mIsReified = isReified;
  12119. if ((methodInstance->mHotMethod != NULL) && (!mCompiler->IsHotCompile()) && (isReified))
  12120. {
  12121. methodInstance->mHotMethod->mFlags = (BfHotDepDataFlags)(methodInstance->mHotMethod->mFlags | BfHotDepDataFlag_IsOriginalBuild);
  12122. }
  12123. if (!methodInstance->mMethodDef->mIsAbstract)
  12124. {
  12125. if ((methodInstance->mMethodDef->mMethodType == BfMethodType_Mixin) && (!methodInstance->mDeclModule->mIsModuleMutable))
  12126. {
  12127. // Wait until unreified
  12128. }
  12129. else
  12130. AddMethodToWorkList(methodInstance);
  12131. }
  12132. else
  12133. {
  12134. methodInstance->mMethodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_Referenced;
  12135. auto owningModule = methodInstance->GetOwner()->mModule;
  12136. if (!owningModule->mIsScratchModule)
  12137. {
  12138. owningModule->mOnDemandMethodCount--;
  12139. owningModule->VerifyOnDemandMethods();
  12140. }
  12141. }
  12142. }
  12143. if (mExtensionCount > 0)
  12144. {
  12145. if ((mIsModuleMutable) && (!methodInstance->mIRFunction) &&
  12146. ((projectList.IsEmpty() || ((flags & BfGetMethodInstanceFlag_ExplicitSpecializedModule) != 0))))
  12147. {
  12148. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, false);
  12149. if (mAwaitingInitFinish)
  12150. FinishInit();
  12151. // We need to refer to a function that was defined in a prior module
  12152. bool isInlined = (methodInstance->mAlwaysInline) || ((flags & BfGetMethodInstanceFlag_ForceInline) != 0);
  12153. if (methodInstance->mIsIntrinsic)
  12154. isInlined = false;
  12155. methodInstance->mIRFunction = CreateFunctionFrom(methodInstance, false, isInlined);
  12156. BF_ASSERT((methodInstance->mDeclModule == this) || (methodInstance->mDeclModule == mContext->mUnreifiedModule) || (methodInstance->mDeclModule == NULL));
  12157. methodInstance->mDeclModule = this;
  12158. // Add this inlined def to ourselves
  12159. if ((methodInstance->mAlwaysInline) && (HasCompiledOutput()) && (!methodInstance->mIsUnspecialized) && ((flags & BfGetMethodInstanceFlag_NoInline) == 0))
  12160. {
  12161. mIncompleteMethodCount++;
  12162. BfInlineMethodRequest* inlineMethodRequest = mContext->mInlineMethodWorkList.Alloc();
  12163. inlineMethodRequest->mType = typeInst;
  12164. inlineMethodRequest->mFromModule = this;
  12165. inlineMethodRequest->mFunc = methodInstance->mIRFunction;
  12166. inlineMethodRequest->mFromModuleRevision = mRevision;
  12167. inlineMethodRequest->mMethodInstance = methodInstance;
  12168. BfLogSysM("mInlineMethodWorkList %p for method %p in module %p in GetMethodInstance\n", inlineMethodRequest, methodInstance, this);
  12169. BF_ASSERT(mIsModuleMutable);
  12170. }
  12171. }
  12172. }
  12173. if (IsSkippingExtraResolveChecks())
  12174. return BfModuleMethodInstance(methodInstance, BfIRFunction());
  12175. else
  12176. {
  12177. if ((flags & (BfGetMethodInstanceFlag_MethodInstanceOnly | BfGetMethodInstanceFlag_NoReference)) != 0)
  12178. return methodInstance;
  12179. if (methodInstance->mDeclModule != this)
  12180. return ReferenceExternalMethodInstance(methodInstance, flags);
  12181. if ((!methodInstance->mIRFunction) && (mIsModuleMutable) && (!mBfIRBuilder->mIgnoreWrites))
  12182. {
  12183. auto importKind = methodInstance->GetImportCallKind();
  12184. if (importKind != BfImportCallKind_None)
  12185. {
  12186. BfLogSysM("DllImportGlobalVar creating %p\n", methodInstance);
  12187. methodInstance->mIRFunction = mBfIRBuilder->GetFakeVal();
  12188. auto func = CreateDllImportGlobalVar(methodInstance, true);
  12189. BF_ASSERT(func);
  12190. mFuncReferences[methodInstance] = func;
  12191. }
  12192. }
  12193. return BfModuleMethodInstance(methodInstance);
  12194. }
  12195. }
  12196. if (!doingRedeclare)
  12197. {
  12198. BfModule* specModule = NULL;
  12199. if ((!keepInCurrentModule) && (projectList.size() > 0) && (!isUnspecializedPass) && (HasCompiledOutput()) && (!mIsScratchModule))
  12200. {
  12201. specModule = GetSpecializedMethodModule(projectList);
  12202. }
  12203. if ((specModule != NULL) && (specModule != this))
  12204. {
  12205. auto specMethodInstance = specModule->GetMethodInstance(typeInst, methodDef, methodGenericArguments, (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_ExplicitSpecializedModule));
  12206. if (mAwaitingInitFinish)
  12207. return BfModuleMethodInstance(specMethodInstance.mMethodInstance, BfIRFunction());
  12208. if ((flags & (BfGetMethodInstanceFlag_MethodInstanceOnly | BfGetMethodInstanceFlag_NoReference)) != 0)
  12209. return specMethodInstance.mMethodInstance;
  12210. return ReferenceExternalMethodInstance(specMethodInstance.mMethodInstance, flags);
  12211. }
  12212. if ((!isUnspecializedPass) && (methodGenericArguments.size() != 0) && (methodInstGroup->mDefault == NULL))
  12213. {
  12214. // We are attempting to specialize but we don't have the unspecialized method yet. Generate that first.
  12215. GetMethodInstance(typeInst, methodDef, BfTypeVector(), BfGetMethodInstanceFlag_UnspecializedPass);
  12216. }
  12217. }
  12218. if (methodInstance == NULL)
  12219. {
  12220. if (lookupMethodGenericArguments.size() == 0)
  12221. {
  12222. BF_ASSERT(methodInstGroup->mDefault == NULL);
  12223. methodInstance = new BfMethodInstance();
  12224. methodInstGroup->mDefault = methodInstance;
  12225. BF_ASSERT(typeInst->mDefineState > BfTypeDefineState_Declared);
  12226. BfLogSysM("Created Default MethodInst: %p TypeInst: %p Group: %p\n", methodInstance, typeInst, methodInstGroup);
  12227. }
  12228. else
  12229. {
  12230. bool depthExceeded = ((flags & BfGetMethodInstanceFlag_DepthExceeded) != 0);
  12231. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mMethodInfoEx != NULL) && (mCurMethodInstance->mMethodInfoEx->mMinDependDepth >= 32))
  12232. depthExceeded = true;
  12233. if (depthExceeded)
  12234. {
  12235. Fail("Generic method dependency depth exceeded", methodDef->GetRefNode());
  12236. return BfModuleMethodInstance();
  12237. }
  12238. BfMethodInstance** methodInstancePtr = NULL;
  12239. bool added = methodInstGroup->mMethodSpecializationMap->TryAdd(lookupMethodGenericArguments, NULL, &methodInstancePtr);
  12240. BF_ASSERT(added);
  12241. methodInstance = new BfMethodInstance();
  12242. *methodInstancePtr = methodInstance;
  12243. if (mCompiler->IsAutocomplete())
  12244. methodInstance->mRequestedByAutocomplete = true;
  12245. BfLogSysM("Created Specialized MethodInst: %p TypeInst: %p\n", methodInstance, typeInst);
  12246. }
  12247. if ((prevIRFunc) && (!prevIRFunc.IsFake()))
  12248. methodInstance->mIRFunction = prevIRFunc; // Take it over
  12249. }
  12250. methodInstance->mMethodDef = methodDef;
  12251. methodInstance->mAlwaysInline = methodDef->mAlwaysInline;
  12252. methodInstance->mMethodInstanceGroup = methodInstGroup;
  12253. methodInstance->mIsReified = isReified;
  12254. SetupMethodIdHash(methodInstance);
  12255. if (hadConcreteInterfaceGenericArgument)
  12256. methodInstance->mIgnoreBody = true;
  12257. if ((flags & BfGetMethodInstanceFlag_ForeignMethodDef) != 0)
  12258. {
  12259. methodInstance->mIsForeignMethodDef = true;
  12260. BF_ASSERT(foreignType != NULL);
  12261. methodInstance->GetMethodInfoEx()->mForeignType = foreignType;
  12262. }
  12263. if ((typeInst->IsInstanceOf(mCompiler->mValueTypeTypeDef)) && (methodDef->mName == BF_METHODNAME_EQUALS))
  12264. {
  12265. if (!lookupMethodGenericArguments.empty())
  12266. {
  12267. auto compareType = lookupMethodGenericArguments[0];
  12268. PopulateType(compareType, BfPopulateType_Data);
  12269. if (compareType->IsSplattable())
  12270. methodInstance->mAlwaysInline = true;
  12271. }
  12272. }
  12273. if (methodDef->mMethodType == BfMethodType_Init)
  12274. {
  12275. methodInstance->mMangleWithIdx = true;
  12276. }
  12277. BF_ASSERT(typeInst == methodInstance->GetOwner());
  12278. auto methodDeclaration = methodDef->GetMethodDeclaration();
  12279. if (isUnspecializedPass)
  12280. {
  12281. for (int genericParamIdx = 0; genericParamIdx < (int) methodDef->mGenericParams.size(); genericParamIdx++)
  12282. {
  12283. auto genericParamType = GetGenericParamType(BfGenericParamKind_Method, genericParamIdx);
  12284. methodInstance->GetMethodInfoEx()->mMethodGenericArguments.Add(genericParamType);
  12285. }
  12286. }
  12287. else if ((methodDeclaration != NULL) && (methodDeclaration->mGenericParams != NULL))
  12288. {
  12289. if (!sanitizedMethodGenericArguments.IsEmpty())
  12290. methodInstance->GetMethodInfoEx()->mMethodGenericArguments = sanitizedMethodGenericArguments;
  12291. if (methodDef->mGenericParams.size() != sanitizedMethodGenericArguments.size())
  12292. {
  12293. Fail("Internal error");
  12294. BFMODULE_FATAL(this, "Generic method argument counts mismatch");
  12295. return NULL;
  12296. }
  12297. for (auto genericArg : sanitizedMethodGenericArguments)
  12298. {
  12299. if (genericArg->IsPrimitiveType())
  12300. genericArg = GetWrappedStructType(genericArg);
  12301. if (genericArg != NULL)
  12302. AddDependency(genericArg, typeInst, BfDependencyMap::DependencyFlag_MethodGenericArg);
  12303. }
  12304. }
  12305. // Generic constraints
  12306. if (!methodDef->mGenericParams.IsEmpty())
  12307. {
  12308. BF_ASSERT(methodInstance->GetMethodInfoEx()->mGenericParams.IsEmpty());
  12309. for (int genericParamIdx = 0; genericParamIdx < (int)methodDef->mGenericParams.size(); genericParamIdx++)
  12310. {
  12311. auto genericParamInstance = new BfGenericMethodParamInstance(methodDef, genericParamIdx);
  12312. methodInstance->GetMethodInfoEx()->mGenericParams.push_back(genericParamInstance);
  12313. }
  12314. }
  12315. for (int externConstraintIdx = 0; externConstraintIdx < (int)methodDef->mExternalConstraints.size(); externConstraintIdx++)
  12316. {
  12317. auto genericParamInstance = new BfGenericMethodParamInstance(methodDef, externConstraintIdx + (int)methodDef->mGenericParams.size());
  12318. methodInstance->GetMethodInfoEx()->mGenericParams.push_back(genericParamInstance);
  12319. }
  12320. bool addToWorkList = !processNow;
  12321. if (mCompiler->GetAutoComplete() != NULL)
  12322. {
  12323. if (typeInst->IsSpecializedByAutoCompleteMethod())
  12324. addToWorkList = false;
  12325. if (methodInstance->mRequestedByAutocomplete)
  12326. addToWorkList = false;
  12327. }
  12328. BfModule* declareModule;
  12329. //
  12330. {
  12331. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, methodInstance);
  12332. declareModule = GetOrCreateMethodModule(methodInstance);
  12333. }
  12334. if ((doingRedeclare) && (methodInstance->mDeclModule != mContext->mUnreifiedModule))
  12335. declareModule = methodInstance->mDeclModule;
  12336. BF_ASSERT(declareModule != NULL);
  12337. methodInstance->mDeclModule = declareModule;
  12338. if ((!methodInstance->mIsReified) && (mCompiler->mCompileState != BfCompiler::CompileState_Normal))
  12339. {
  12340. // We can be sure this method won't become reified later. Normally we can "go either way" with an unreified method
  12341. // of a reified module -
  12342. // If we declare it in the reified module then we can switch it to "reified" before actual processing without any extra work,
  12343. // BUT if we don't reify it then we have to remove the body after processing.
  12344. // 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
  12345. // the proper reified module.
  12346. declareModule = mContext->mUnreifiedModule;
  12347. }
  12348. else if ((!declareModule->mIsModuleMutable) && (!mCompiler->mIsResolveOnly))
  12349. {
  12350. if (!methodInstance->mIsReified)
  12351. {
  12352. declareModule = mContext->mUnreifiedModule;
  12353. }
  12354. else
  12355. {
  12356. declareModule->PrepareForIRWriting(methodInstance->GetOwner());
  12357. }
  12358. }
  12359. SetMethodDependency(methodInstance);
  12360. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(declareModule->mCurMethodInstance, methodInstance);
  12361. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(declareModule->mCurTypeInstance, typeInst);
  12362. SetAndRestoreValue<BfFilePosition> prevFilePos(declareModule->mCurFilePosition);
  12363. if ((methodDef->mMethodType == BfMethodType_Mixin) && (methodDef->mGenericParams.size() != 0) && (!isUnspecializedPass))
  12364. {
  12365. // For mixins we only process the unspecialized version
  12366. addToWorkList = false;
  12367. }
  12368. if ((flags & BfGetMethodInstanceFlag_MethodInstanceOnly) != 0)
  12369. {
  12370. addToWorkList = false;
  12371. }
  12372. // if ((flags & BfGetMethodInstanceFlag_NoReference) != 0)
  12373. // addToWorkList = false;
  12374. declareModule->DoMethodDeclaration(methodDef->GetMethodDeclaration(), false, addToWorkList);
  12375. if (processNow)
  12376. {
  12377. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, NULL);
  12378. ProcessMethod(methodInstance);
  12379. }
  12380. if (IsSkippingExtraResolveChecks())
  12381. return BfModuleMethodInstance(methodInstance, BfIRFunction());
  12382. if (methodInstance->mDeclModule != this)
  12383. return ReferenceExternalMethodInstance(methodInstance, flags);
  12384. return BfModuleMethodInstance(methodInstance);
  12385. }
  12386. BfModuleMethodInstance BfModule::GetMethodInstance(BfMethodInstance* methodInstance, BfGetMethodInstanceFlags flags)
  12387. {
  12388. BF_ASSERT((methodInstance->mMethodInfoEx == NULL) || (methodInstance->mMethodInfoEx->mGenericParams.IsEmpty()));
  12389. if (methodInstance->mIsForeignMethodDef)
  12390. flags = (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_ForeignMethodDef);
  12391. return GetMethodInstance(methodInstance->GetOwner(), methodInstance->mMethodDef, BfTypeVector(), flags);
  12392. }
  12393. BfMethodInstance* BfModule::GetOuterMethodInstance(BfMethodInstance* methodInstance)
  12394. {
  12395. if (!methodInstance->mMethodDef->mIsLocalMethod)
  12396. return NULL;
  12397. auto outerLocal = methodInstance->mMethodInfoEx->mClosureInstanceInfo->mLocalMethod->mOuterLocalMethod;
  12398. if (outerLocal == NULL)
  12399. return NULL;
  12400. BfTypeVector genericArgs;
  12401. for (int i = 0; i < (int)outerLocal->mMethodDef->mGenericParams.size(); i++)
  12402. genericArgs.Add(methodInstance->mMethodInfoEx->mMethodGenericArguments[i]);
  12403. return GetLocalMethodInstance(outerLocal, genericArgs).mMethodInstance;
  12404. }
  12405. void BfModule::SetupMethodIdHash(BfMethodInstance* methodInstance)
  12406. {
  12407. HashContext hashCtx;
  12408. std::function<void(BfMethodInstance*)> _MixinMethodInstance = [&](BfMethodInstance* methodInstance)
  12409. {
  12410. hashCtx.Mixin(methodInstance->GetOwner()->mTypeId);
  12411. hashCtx.Mixin(methodInstance->mMethodDef->mIdx);
  12412. if (methodInstance->GetNumGenericArguments() != 0)
  12413. {
  12414. hashCtx.Mixin((int32)methodInstance->mMethodInfoEx->mMethodGenericArguments.size());
  12415. for (auto methodGenericArg : methodInstance->mMethodInfoEx->mMethodGenericArguments)
  12416. hashCtx.Mixin(methodGenericArg->mTypeId);
  12417. }
  12418. };
  12419. _MixinMethodInstance(methodInstance);
  12420. if (methodInstance->mMethodDef->mIsLocalMethod)
  12421. {
  12422. auto outmostMethodInstance = mCurMethodState->GetRootMethodState()->mMethodInstance;
  12423. if (outmostMethodInstance != NULL)
  12424. {
  12425. BF_ASSERT((outmostMethodInstance->mIdHash != 0) || (outmostMethodInstance->mIsAutocompleteMethod));
  12426. hashCtx.Mixin(outmostMethodInstance->mIdHash);
  12427. }
  12428. }
  12429. methodInstance->mIdHash = (int64)hashCtx.Finish64();
  12430. }
  12431. bool BfModule::CheckUseMethodInstance(BfMethodInstance* methodInstance, BfAstNode* refNode)
  12432. {
  12433. if (methodInstance->mHasBeenDeclared)
  12434. return true;
  12435. Fail(StrFormat("Circular reference in method instance '%s'", MethodToString(methodInstance).c_str()), refNode);
  12436. return false;
  12437. }
  12438. BfIRValue BfModule::GetInterfaceSlotNum(BfTypeInstance* ifaceType)
  12439. {
  12440. BfIRValue globalValue;
  12441. BfIRValue* globalValuePtr = NULL;
  12442. if (mInterfaceSlotRefs.TryGetValue(ifaceType, &globalValuePtr))
  12443. {
  12444. globalValue = *globalValuePtr;
  12445. }
  12446. if (!globalValue)
  12447. {
  12448. // This is necessary to reify the interface type
  12449. PopulateType(ifaceType);
  12450. StringT<128> slotVarName;
  12451. BfMangler::MangleStaticFieldName(slotVarName, mCompiler->GetMangleKind(), ifaceType, "sBfSlotOfs");
  12452. BfType* intType = GetPrimitiveType(BfTypeCode_Int32);
  12453. BfIRValue value;
  12454. if ((mCompiler->mHotState != NULL) && (ifaceType->mSlotNum >= 0))
  12455. {
  12456. /*// If this interface already existed before this hot compile but we never indirectly called any of its methods
  12457. // then the sBfSlotOfs could have gotten its symbol stripped, so actually define it here.
  12458. int virtSlotIdx = ifaceType->mSlotNum + 1;
  12459. value = GetConstValue32(virtSlotIdx);*/
  12460. mCompiler->mHotState->mSlotDefineTypeIds.Add(ifaceType->mTypeId);
  12461. ifaceType->mDirty = true; // Makes sure we create interface in vdata
  12462. }
  12463. globalValue = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapType(intType), true, BfIRLinkageType_External, value, slotVarName);
  12464. mInterfaceSlotRefs[ifaceType] = globalValue;
  12465. }
  12466. return mBfIRBuilder->CreateLoad(globalValue/*, "slotOfs"*/);
  12467. }
  12468. void BfModule::HadSlotCountDependency()
  12469. {
  12470. if (mCompiler->mIsResolveOnly)
  12471. return;
  12472. BF_ASSERT(!mBfIRBuilder->mIgnoreWrites);
  12473. BF_ASSERT((mUsedSlotCount == BF_MAX(mCompiler->mMaxInterfaceSlots, 0)) || (mUsedSlotCount == -1));
  12474. mUsedSlotCount = BF_MAX(mCompiler->mMaxInterfaceSlots, 0);
  12475. }
  12476. BfTypedValue BfModule::GetCompilerFieldValue(const StringImpl& str)
  12477. {
  12478. if (str == "#IsComptime")
  12479. {
  12480. return BfTypedValue(mBfIRBuilder->CreateConst(BfTypeCode_Boolean, mIsComptimeModule ? 1 : 0), GetPrimitiveType(BfTypeCode_Boolean));
  12481. }
  12482. if (str == "#IsBuilding")
  12483. {
  12484. return BfTypedValue(mBfIRBuilder->CreateConst(BfTypeCode_Boolean, (!mCompiler->mIsResolveOnly) ? 1 : 0), GetPrimitiveType(BfTypeCode_Boolean));
  12485. }
  12486. if (str == "#IsReified")
  12487. {
  12488. return BfTypedValue(mBfIRBuilder->CreateConst(BfTypeCode_Boolean, mIsReified ? 1 : 0), GetPrimitiveType(BfTypeCode_Boolean));
  12489. }
  12490. if (str == "#CompileRev")
  12491. {
  12492. return BfTypedValue(mBfIRBuilder->CreateConst(BfTypeCode_Int32, mCompiler->mRevision), GetPrimitiveType(BfTypeCode_Int32));
  12493. }
  12494. if (str == "#ModuleName")
  12495. {
  12496. return BfTypedValue(GetStringObjectValue(mModuleName), ResolveTypeDef(mCompiler->mStringTypeDef));
  12497. }
  12498. if (str == "#ProjectName")
  12499. {
  12500. if (mProject != NULL)
  12501. return BfTypedValue(GetStringObjectValue(mProject->mName), ResolveTypeDef(mCompiler->mStringTypeDef));
  12502. }
  12503. if (str == "#AllocStackCount")
  12504. {
  12505. return BfTypedValue(mBfIRBuilder->CreateConst(BfTypeCode_Int32, mCompiler->mOptions.mAllocStackCount), GetPrimitiveType(BfTypeCode_Int32));
  12506. }
  12507. if (mCurMethodState->mMixinState != NULL)
  12508. {
  12509. if (str == "#CallerLineNum")
  12510. {
  12511. return BfTypedValue(GetConstValue(mCurMethodState->mMixinState->mInjectFilePosition.mCurLine + 1), GetPrimitiveType(BfTypeCode_Int32));
  12512. }
  12513. else if (str == "#CallerFilePath")
  12514. {
  12515. String filePath = "";
  12516. if (mCurMethodState->mMixinState->mInjectFilePosition.mFileInstance != NULL)
  12517. filePath = mCurMethodState->mMixinState->mInjectFilePosition.mFileInstance->mParser->mFileName;
  12518. return BfTypedValue(GetStringObjectValue(filePath), ResolveTypeDef(mCompiler->mStringTypeDef));
  12519. }
  12520. else if (str == "#CallerFileName")
  12521. {
  12522. String filePath = "";
  12523. if (mCurMethodState->mMixinState->mInjectFilePosition.mFileInstance != NULL)
  12524. filePath = mCurMethodState->mMixinState->mInjectFilePosition.mFileInstance->mParser->mFileName;
  12525. return BfTypedValue(GetStringObjectValue(GetFileName(filePath)), ResolveTypeDef(mCompiler->mStringTypeDef));
  12526. }
  12527. else if (str == "#CallerFileDir")
  12528. {
  12529. String filePath = "";
  12530. if (mCurMethodState->mMixinState->mInjectFilePosition.mFileInstance != NULL)
  12531. filePath = mCurMethodState->mMixinState->mInjectFilePosition.mFileInstance->mParser->mFileName;
  12532. return BfTypedValue(GetStringObjectValue(GetFileDir(filePath)), ResolveTypeDef(mCompiler->mStringTypeDef));
  12533. }
  12534. else if (str == "#CallerMemberName")
  12535. {
  12536. String memberName = "";
  12537. if (mCurMethodState->mMixinState->mMixinMethodInstance)
  12538. memberName = MethodToString(mCurMethodState->mMixinState->mMixinMethodInstance);
  12539. return BfTypedValue(GetStringObjectValue(memberName), ResolveTypeDef(mCompiler->mStringTypeDef));
  12540. }
  12541. else if (str == "#CallerProject")
  12542. {
  12543. BfProject* project = NULL;
  12544. project = mCurMethodState->mMixinState->mMixinMethodInstance->mMethodDef->mDeclaringType->mProject;
  12545. if (project != NULL)
  12546. return BfTypedValue(GetStringObjectValue(mProject->mName), ResolveTypeDef(mCompiler->mStringTypeDef));
  12547. }
  12548. }
  12549. if (str == "#TimeLocal")
  12550. {
  12551. time_t rawtime;
  12552. time(&rawtime);
  12553. tm* timeinfo = localtime(&rawtime);
  12554. char result[32];
  12555. sprintf(result, "%d/%.2d/%.2d %.2d:%.2d:%.2d",
  12556. 1900 + timeinfo->tm_year,
  12557. timeinfo->tm_mon,
  12558. timeinfo->tm_mday,
  12559. timeinfo->tm_hour,
  12560. timeinfo->tm_min,
  12561. timeinfo->tm_sec);
  12562. return BfTypedValue(GetStringObjectValue(result), ResolveTypeDef(mCompiler->mStringTypeDef));
  12563. }
  12564. return BfTypedValue();
  12565. }
  12566. BfTypedValue BfModule::ReferenceStaticField(BfFieldInstance* fieldInstance)
  12567. {
  12568. BfIRValue globalValue;
  12569. auto fieldDef = fieldInstance->GetFieldDef();
  12570. if ((fieldDef->mIsConst) && (!fieldDef->mIsExtern))
  12571. {
  12572. if (fieldInstance->mConstIdx != -1)
  12573. {
  12574. auto constant = fieldInstance->mOwner->mConstHolder->GetConstantById(fieldInstance->mConstIdx);
  12575. return BfTypedValue(ConstantToCurrent(constant, fieldInstance->mOwner->mConstHolder, fieldInstance->GetResolvedType()), fieldInstance->GetResolvedType());
  12576. }
  12577. else
  12578. {
  12579. return GetDefaultTypedValue(fieldInstance->GetResolvedType());
  12580. }
  12581. }
  12582. if ((mIsScratchModule) && (mCompiler->mIsResolveOnly))
  12583. {
  12584. // Just fake it for the extern and unspecialized modules
  12585. // We can't do this for compilation because unreified methods with default params need to get acutal global variable refs
  12586. return BfTypedValue(mBfIRBuilder->CreateConstNull(), fieldInstance->GetResolvedType(), true);
  12587. }
  12588. BfIRValue* globalValuePtr = NULL;
  12589. if (mStaticFieldRefs.TryGetValue(fieldInstance, &globalValuePtr))
  12590. {
  12591. globalValue = *globalValuePtr;
  12592. BF_ASSERT(globalValue);
  12593. auto globalVar = (BfGlobalVar*)mBfIRBuilder->GetConstant(globalValue);
  12594. if ((globalVar->mStreamId == -1) && (!mBfIRBuilder->mIgnoreWrites))
  12595. {
  12596. mBfIRBuilder->MapType(fieldInstance->mResolvedType);
  12597. mBfIRBuilder->CreateGlobalVariable(globalValue);
  12598. }
  12599. }
  12600. else
  12601. {
  12602. StringT<128> staticVarName;
  12603. BfMangler::Mangle(staticVarName, mCompiler->GetMangleKind(), fieldInstance);
  12604. auto typeType = fieldInstance->GetResolvedType();
  12605. if ((fieldDef->mIsExtern) && (fieldDef->mIsConst) && (typeType->IsPointer()))
  12606. {
  12607. typeType = typeType->GetUnderlyingType();
  12608. }
  12609. if (mIsComptimeModule)
  12610. {
  12611. mCompiler->mCEMachine->QueueStaticField(fieldInstance, staticVarName);
  12612. }
  12613. PopulateType(typeType);
  12614. if ((typeType != NULL) && (!typeType->IsValuelessType()))
  12615. {
  12616. BfIRType irType = mBfIRBuilder->MapType(typeType);
  12617. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, mBfIRBuilder->mIgnoreWrites || staticVarName.StartsWith('#'));
  12618. globalValue = mBfIRBuilder->CreateGlobalVariable(
  12619. irType,
  12620. false,
  12621. BfIRLinkageType_External,
  12622. BfIRValue(),
  12623. staticVarName,
  12624. IsThreadLocal(fieldInstance));
  12625. BF_ASSERT(globalValue);
  12626. mStaticFieldRefs[fieldInstance] = globalValue;
  12627. BfLogSysM("Mod:%p Type:%p ReferenceStaticField %p -> %p\n", this, fieldInstance->mOwner, fieldInstance, globalValue);
  12628. }
  12629. }
  12630. auto type = fieldInstance->GetResolvedType();
  12631. if (type->IsValuelessType())
  12632. return BfTypedValue(globalValue, type);
  12633. return BfTypedValue(globalValue, type, !fieldDef->mIsConst);
  12634. }
  12635. int BfModule::GetFieldDataIdx(BfTypeInstance* typeInst, int fieldIdx, const char* fieldName)
  12636. {
  12637. if (typeInst->IsDataIncomplete())
  12638. PopulateType(typeInst);
  12639. if (fieldIdx >= typeInst->mFieldInstances.mSize)
  12640. {
  12641. Fail(StrFormat("Invalid field data in type '%s'", TypeToString(typeInst).c_str()));
  12642. return 0;
  12643. }
  12644. auto& fieldInstance = typeInst->mFieldInstances[fieldIdx];
  12645. return fieldInstance.mDataIdx;
  12646. }
  12647. void BfModule::MarkUsingThis()
  12648. {
  12649. auto useMethodState = mCurMethodState;
  12650. while ((useMethodState != NULL) && (useMethodState->mClosureState != NULL) && (useMethodState->mClosureState->mCapturing))
  12651. {
  12652. useMethodState = useMethodState->mPrevMethodState;
  12653. }
  12654. if ((useMethodState != NULL) && (!useMethodState->mLocals.IsEmpty()))
  12655. {
  12656. auto localVar = useMethodState->mLocals[0];
  12657. if (localVar->mIsThis)
  12658. localVar->mReadFromId = useMethodState->GetRootMethodState()->mCurAccessId++;
  12659. }
  12660. }
  12661. BfTypedValue BfModule::GetThis(bool markUsing)
  12662. {
  12663. auto useMethodState = mCurMethodState;
  12664. while ((useMethodState != NULL) && (useMethodState->mClosureState != NULL) && (useMethodState->mClosureState->mCapturing))
  12665. {
  12666. useMethodState = useMethodState->mPrevMethodState;
  12667. }
  12668. if (useMethodState != NULL)
  12669. {
  12670. // Fake a 'this' for var field resolution
  12671. if (useMethodState->mTempKind == BfMethodState::TempKind_NonStatic)
  12672. {
  12673. auto thisType = mCurTypeInstance;
  12674. if (thisType->IsValueType())
  12675. return BfTypedValue(mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapTypeInstPtr(thisType)), thisType, BfTypedValueKind_ThisAddr);
  12676. else
  12677. return BfTypedValue(mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapTypeInst(thisType)), thisType, BfTypedValueKind_ThisValue);
  12678. }
  12679. else if (useMethodState->mTempKind == BfMethodState::TempKind_Static)
  12680. {
  12681. return BfTypedValue();
  12682. }
  12683. }
  12684. else
  12685. {
  12686. //TODO: Do we allow useMethodState to be NULL anymore?
  12687. return BfTypedValue();
  12688. }
  12689. // Check mixin state for 'this'
  12690. {
  12691. auto checkMethodState = mCurMethodState;
  12692. while (checkMethodState != NULL)
  12693. {
  12694. if (checkMethodState->mMixinState != NULL)
  12695. {
  12696. BfTypedValue thisValue = checkMethodState->mMixinState->mTarget;
  12697. if (thisValue.HasType())
  12698. {
  12699. checkMethodState->mMixinState->mLastTargetAccessId = useMethodState->GetRootMethodState()->mCurAccessId++;
  12700. if (!thisValue.mType->IsValueType())
  12701. thisValue = LoadValue(thisValue);
  12702. return thisValue;
  12703. }
  12704. }
  12705. checkMethodState = checkMethodState->mPrevMethodState;
  12706. }
  12707. }
  12708. auto curMethodInstance = mCurMethodInstance;
  12709. if (useMethodState->mMethodInstance != NULL)
  12710. curMethodInstance = useMethodState->mMethodInstance;
  12711. if ((curMethodInstance == NULL) /*|| (!mCurMethodInstance->mIRFunction)*/ || (curMethodInstance->mMethodDef->mIsStatic))
  12712. {
  12713. if ((useMethodState->mClosureState != NULL) && (!useMethodState->mClosureState->mConstLocals.empty()))
  12714. {
  12715. auto& constLocal = useMethodState->mClosureState->mConstLocals[0];
  12716. if (constLocal.mIsThis)
  12717. {
  12718. BF_ASSERT(constLocal.mResolvedType->IsValuelessType());
  12719. return BfTypedValue(mBfIRBuilder->GetFakeVal(), constLocal.mResolvedType);
  12720. }
  12721. }
  12722. return BfTypedValue();
  12723. }
  12724. if (useMethodState->mLocals.IsEmpty())
  12725. {
  12726. // 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
  12727. BF_ASSERT(useMethodState->mPrevMethodState != NULL);
  12728. return BfTypedValue();
  12729. }
  12730. auto thisLocal = useMethodState->mLocals[0];
  12731. BF_ASSERT(thisLocal->mIsThis);
  12732. bool preferValue = !IsTargetingBeefBackend();
  12733. if (!thisLocal->mAddr)
  12734. preferValue = true;
  12735. bool usedVal = false;
  12736. BfIRValue thisValue;
  12737. if ((preferValue) && (!thisLocal->mIsLowered))
  12738. {
  12739. thisValue = thisLocal->mValue;
  12740. usedVal = true;
  12741. }
  12742. else if ((thisLocal->mIsSplat) || (thisLocal->mIsLowered))
  12743. thisValue = thisLocal->mAddr;
  12744. else
  12745. thisValue = mBfIRBuilder->CreateLoad(thisLocal->mAddr);
  12746. if (markUsing)
  12747. useMethodState->mLocals[0]->mReadFromId = useMethodState->GetRootMethodState()->mCurAccessId++;
  12748. if (useMethodState->mClosureState != NULL)
  12749. {
  12750. auto closureTypeInst = useMethodState->mClosureState->mClosureType;
  12751. if (closureTypeInst != NULL)
  12752. {
  12753. if (closureTypeInst->mFieldInstances.size() > 0)
  12754. {
  12755. auto& field = closureTypeInst->mFieldInstances[0];
  12756. auto fieldDef = field.GetFieldDef();
  12757. if (fieldDef->mName == "__this")
  12758. {
  12759. if (mCurMethodState->mClosureState->mCapturing)
  12760. mCurMethodState->mClosureState->mReferencedOuterClosureMembers.Add(&field);
  12761. // This is a captured 'this'
  12762. BfTypedValue result = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(thisValue, 0, field.mDataIdx), field.mResolvedType, true);
  12763. if (field.mResolvedType->IsRef())
  12764. {
  12765. auto refType = (BfRefType*)field.mResolvedType;
  12766. auto underlyingType = refType->GetUnderlyingType();
  12767. result = BfTypedValue(mBfIRBuilder->CreateLoad(result.mValue), underlyingType, true);
  12768. }
  12769. if (field.mResolvedType->IsObject())
  12770. {
  12771. result = LoadValue(result);
  12772. result.mKind = BfTypedValueKind_ThisValue;
  12773. }
  12774. else
  12775. {
  12776. if (fieldDef->mIsReadOnly)
  12777. result.mKind = BfTypedValueKind_ReadOnlyThisAddr;
  12778. else
  12779. result.mKind = BfTypedValueKind_ThisAddr;
  12780. }
  12781. return result;
  12782. }
  12783. }
  12784. return BfTypedValue();
  12785. }
  12786. if (useMethodState->mClosureState->mCapturing)
  12787. {
  12788. auto thisType = useMethodState->mLocals[0]->mResolvedType;
  12789. if (thisType->IsValueType())
  12790. return BfTypedValue(CreateAlloca(thisType), thisType, BfTypedValueKind_ThisAddr);
  12791. else
  12792. return BfTypedValue(GetDefaultValue(thisType), thisType, BfTypedValueKind_ThisValue);
  12793. }
  12794. }
  12795. if (mCurMethodInstance == NULL)
  12796. return BfTypedValue();
  12797. auto localDef = useMethodState->mLocals[0];
  12798. auto curMethodOwner = mCurMethodInstance->mMethodInstanceGroup->mOwner;
  12799. if ((curMethodOwner->IsStruct()) || (curMethodOwner->IsTypedPrimitive()))
  12800. {
  12801. if ((localDef->mResolvedType->IsTypedPrimitive()) && (!mCurMethodInstance->mMethodDef->mIsMutating))
  12802. {
  12803. return BfTypedValue(thisValue, useMethodState->mLocals[0]->mResolvedType, BfTypedValueKind_ReadOnlyThisValue);
  12804. }
  12805. if (localDef->mIsSplat)
  12806. {
  12807. return BfTypedValue(thisValue, useMethodState->mLocals[0]->mResolvedType, BfTypedValueKind_ThisSplatHead);
  12808. }
  12809. return BfTypedValue(thisValue, useMethodState->mLocals[0]->mResolvedType, localDef->mIsReadOnly ? BfTypedValueKind_ReadOnlyThisAddr : BfTypedValueKind_ThisAddr);
  12810. }
  12811. return BfTypedValue(thisValue, mCurMethodInstance->mMethodInstanceGroup->mOwner, BfTypedValueKind_ThisValue);
  12812. }
  12813. BfLocalVariable* BfModule::GetThisVariable()
  12814. {
  12815. if (mCurMethodState == NULL)
  12816. return NULL;
  12817. auto methodState = mCurMethodState->GetNonCaptureState();
  12818. if ((methodState->mLocals.size() > 0) && (methodState->mLocals[0]->mIsThis))
  12819. return methodState->mLocals[0];
  12820. return NULL;
  12821. }
  12822. bool BfModule::IsInGeneric()
  12823. {
  12824. return ((mCurMethodInstance != NULL) && (mCurMethodInstance->GetNumGenericArguments() != 0)) || (mCurTypeInstance->IsGenericTypeInstance());
  12825. }
  12826. bool BfModule::InDefinitionSection()
  12827. {
  12828. if (mCurTypeInstance != NULL)
  12829. {
  12830. if (mCurTypeInstance->IsUnspecializedTypeVariation())
  12831. return false;
  12832. }
  12833. return !IsInSpecializedSection();
  12834. }
  12835. bool BfModule::IsInSpecializedGeneric()
  12836. {
  12837. if ((mCurTypeInstance != NULL) && (mCurTypeInstance->IsSpecializedType()))
  12838. return true;
  12839. if ((mCurMethodInstance == NULL) || (mCurMethodInstance->mIsUnspecialized))
  12840. return false;
  12841. return (mCurMethodInstance->GetNumGenericArguments() != 0);
  12842. }
  12843. bool BfModule::IsInSpecializedSection()
  12844. {
  12845. return IsInSpecializedGeneric() ||
  12846. ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL));
  12847. }
  12848. bool BfModule::IsInUnspecializedGeneric()
  12849. {
  12850. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mIsUnspecialized))
  12851. return true;
  12852. if ((mCurTypeInstance != NULL) && (mCurTypeInstance->IsUnspecializedType()))
  12853. return true;
  12854. return false;
  12855. }
  12856. //////////////////////////////////////////////////////////////////////////
  12857. BfIRValue BfModule::AllocLocalVariable(BfType* type, const StringImpl& name, bool doLifetimeEnd)
  12858. {
  12859. //if ((type->IsValuelessType()) || (type->IsMethodRef()))
  12860. if (type->IsValuelessType())
  12861. return mBfIRBuilder->GetFakeVal();
  12862. auto allocaInst = CreateAlloca(type, doLifetimeEnd, name.c_str());
  12863. if ((!doLifetimeEnd) && (WantsLifetimes()))
  12864. {
  12865. auto lifetimeStart = mBfIRBuilder->CreateLifetimeStart(allocaInst);
  12866. mBfIRBuilder->ClearDebugLocation(lifetimeStart);
  12867. }
  12868. bool initLocalVariables = mCompiler->mOptions.mInitLocalVariables;
  12869. auto typeOptions = GetTypeOptions();
  12870. if (typeOptions != NULL)
  12871. initLocalVariables = typeOptions->Apply(initLocalVariables, BfOptionFlags_InitLocalVariables);
  12872. // Local variable inits are implicitly handled in the Beef Backend
  12873. if ((initLocalVariables) && (!IsTargetingBeefBackend()))
  12874. {
  12875. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  12876. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRInitBlock);
  12877. auto storeInst = mBfIRBuilder->CreateAlignedStore(GetDefaultValue(type), allocaInst, type->mAlign);
  12878. mBfIRBuilder->ClearDebugLocation(storeInst);
  12879. mBfIRBuilder->SetInsertPoint(prevBlock);
  12880. }
  12881. return allocaInst;
  12882. }
  12883. void BfModule::DoAddLocalVariable(BfLocalVariable* localVar)
  12884. {
  12885. while (localVar->mName.StartsWith('@'))
  12886. {
  12887. localVar->mNamePrefixCount++;
  12888. localVar->mName.Remove(0);
  12889. }
  12890. localVar->mLocalVarIdx = (int)mCurMethodState->mLocals.size();
  12891. mCurMethodState->mLocals.push_back(localVar);
  12892. BfLocalVarEntry* localVarEntryPtr;
  12893. if (!mCurMethodState->mLocalVarSet.TryAdd(BfLocalVarEntry(localVar), &localVarEntryPtr))
  12894. {
  12895. localVar->mShadowedLocal = localVarEntryPtr->mLocalVar;
  12896. localVarEntryPtr->mLocalVar = localVar;
  12897. }
  12898. }
  12899. void BfModule::DoLocalVariableDebugInfo(BfLocalVariable* localVarDef, bool doAliasValue, BfIRValue declareBefore, BfIRInitType initType)
  12900. {
  12901. if (localVarDef->mResolvedType->IsVar())
  12902. return;
  12903. if ((mBfIRBuilder->DbgHasInfo()) &&
  12904. ((mCurMethodInstance == NULL) || (!mCurMethodInstance->mIsUnspecialized)) &&
  12905. (mHasFullDebugInfo) &&
  12906. ((mCurMethodState->mClosureState == NULL) || (!mCurMethodState->mClosureState->mCapturing)))
  12907. {
  12908. auto varType = localVarDef->mResolvedType;
  12909. if (localVarDef->mResolvedType->IsValuelessType())
  12910. {
  12911. }
  12912. else
  12913. {
  12914. bool isByAddr = false;
  12915. auto diValue = localVarDef->mValue;
  12916. if (localVarDef->mConstValue)
  12917. diValue = localVarDef->mConstValue;
  12918. else if (localVarDef->mAddr)
  12919. {
  12920. diValue = localVarDef->mAddr;
  12921. isByAddr = true;
  12922. }
  12923. if (diValue.IsConst())
  12924. {
  12925. auto constant = mBfIRBuilder->GetConstant(diValue);
  12926. if ((constant->mConstType == BfConstType_TypeOf) || (constant->mConstType == BfConstType_TypeOf_WithData))
  12927. {
  12928. // Ignore for now
  12929. return;
  12930. }
  12931. }
  12932. auto diType = mBfIRBuilder->DbgGetType(localVarDef->mResolvedType);
  12933. bool didConstToMem = false;
  12934. bool isConstant = false;
  12935. if ((localVarDef->mIsReadOnly) && (localVarDef->mAddr))
  12936. diType = mBfIRBuilder->DbgCreateConstType(diType);
  12937. else if (localVarDef->mConstValue)
  12938. {
  12939. auto constant = mBfIRBuilder->GetConstant(localVarDef->mConstValue);
  12940. isConstant =
  12941. (constant->mConstType < BfConstType_GlobalVar) ||
  12942. (constant->mConstType == BfConstType_AggZero) ||
  12943. (constant->mConstType == BfConstType_Agg);
  12944. if (isConstant)
  12945. {
  12946. if (localVarDef->mResolvedType->IsComposite())
  12947. {
  12948. mBfIRBuilder->PopulateType(localVarDef->mResolvedType);
  12949. auto constMem = mBfIRBuilder->ConstToMemory(localVarDef->mConstValue);
  12950. // if (IsTargetingBeefBackend())
  12951. // {
  12952. // diValue = mBfIRBuilder->CreateAliasValue(constMem);
  12953. // didConstToMem = true;
  12954. //
  12955. // diType = mBfIRBuilder->DbgCreateReferenceType(diType);
  12956. // }
  12957. //else
  12958. {
  12959. isByAddr = true;
  12960. mBfIRBuilder->SaveDebugLocation();
  12961. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  12962. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRInitBlock);
  12963. mBfIRBuilder->ClearDebugLocation();
  12964. auto ptrType = CreatePointerType(localVarDef->mResolvedType);
  12965. auto addrVal = CreateAlloca(ptrType);
  12966. mBfIRBuilder->CreateStore(constMem, addrVal);
  12967. diType = mBfIRBuilder->DbgCreateReferenceType(diType);
  12968. diValue = addrVal;
  12969. didConstToMem = true;
  12970. mBfIRBuilder->SetInsertPoint(prevBlock);
  12971. mBfIRBuilder->RestoreDebugLocation();
  12972. }
  12973. }
  12974. if (mCompiler->mOptions.IsCodeView())
  12975. diType = mBfIRBuilder->DbgCreateConstType(diType);
  12976. }
  12977. }
  12978. if (!mBfIRBuilder->mIgnoreWrites)
  12979. {
  12980. auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(mCurMethodState->mCurScope->mDIScope,
  12981. localVarDef->mName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType, initType);
  12982. localVarDef->mDbgVarInst = diVariable;
  12983. if (mBfIRBuilder->HasDebugLocation())
  12984. {
  12985. if ((isConstant) && (!didConstToMem))
  12986. {
  12987. BfTypedValue result(localVarDef->mConstValue, localVarDef->mResolvedType);
  12988. FixValueActualization(result);
  12989. localVarDef->mDbgDeclareInst = mBfIRBuilder->DbgInsertValueIntrinsic(result.mValue, diVariable);
  12990. }
  12991. else
  12992. {
  12993. if ((IsTargetingBeefBackend()) && (doAliasValue))
  12994. {
  12995. diValue = mBfIRBuilder->CreateAliasValue(diValue);
  12996. mCurMethodState->mCurScope->mDeferredLifetimeEnds.Add(diValue);
  12997. }
  12998. if (isByAddr)
  12999. localVarDef->mDbgDeclareInst = mBfIRBuilder->DbgInsertDeclare(diValue, diVariable, declareBefore);
  13000. else if (diValue)
  13001. {
  13002. localVarDef->mDbgDeclareInst = mBfIRBuilder->DbgInsertValueIntrinsic(diValue, diVariable);
  13003. }
  13004. else if (mCompiler->mOptions.mToolsetType != BfToolsetType_GNU) // DWARF chokes on this:
  13005. localVarDef->mDbgDeclareInst = mBfIRBuilder->DbgInsertValueIntrinsic(BfIRValue(), diVariable);
  13006. }
  13007. }
  13008. }
  13009. }
  13010. }
  13011. }
  13012. BfLocalVariable* BfModule::AddLocalVariableDef(BfLocalVariable* localVarDef, bool addDebugInfo, bool doAliasValue, BfIRValue declareBefore, BfIRInitType initType)
  13013. {
  13014. if ((localVarDef->mValue) && (!localVarDef->mAddr) && (IsTargetingBeefBackend()) && (!localVarDef->mResolvedType->IsValuelessType()))
  13015. {
  13016. if ((!localVarDef->mValue.IsConst()) &&
  13017. (!localVarDef->mValue.IsArg()) && (!localVarDef->mValue.IsFake()))
  13018. {
  13019. mBfIRBuilder->CreateValueScopeRetain(localVarDef->mValue);
  13020. mCurMethodState->mCurScope->mHadScopeValueRetain = true;
  13021. }
  13022. }
  13023. if (addDebugInfo)
  13024. DoLocalVariableDebugInfo(localVarDef, doAliasValue, declareBefore, initType);
  13025. localVarDef->mDeclBlock = mBfIRBuilder->GetInsertBlock();
  13026. DoAddLocalVariable(localVarDef);
  13027. auto rootMethodState = mCurMethodState->GetRootMethodState();
  13028. if (localVarDef->mLocalVarId == -1)
  13029. {
  13030. BF_ASSERT(rootMethodState->mCurLocalVarId >= 0);
  13031. localVarDef->mLocalVarId = rootMethodState->mCurLocalVarId++;
  13032. }
  13033. if ((localVarDef->mNameNode != NULL) && (mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL) && (!mIsComptimeModule))
  13034. mCompiler->mResolvePassData->mAutoComplete->CheckLocalDef(localVarDef->mNameNode, localVarDef);
  13035. if ((localVarDef->mNameNode != NULL) && (mCurMethodInstance != NULL))
  13036. {
  13037. bool isClosureProcessing = (mCurMethodState->mClosureState != NULL) && (!mCurMethodState->mClosureState->mCapturing);
  13038. if ((!isClosureProcessing) && (mCompiler->mResolvePassData != NULL) && (localVarDef->mNameNode != NULL) && (rootMethodState->mMethodInstance != NULL) && (!mIsComptimeModule))
  13039. mCompiler->mResolvePassData->HandleLocalReference(localVarDef->mNameNode, rootMethodState->mMethodInstance->GetOwner()->mTypeDef, rootMethodState->mMethodInstance->mMethodDef, localVarDef->mLocalVarId);
  13040. }
  13041. return localVarDef;
  13042. }
  13043. void BfModule::CreateDIRetVal()
  13044. {
  13045. if (!WantsDebugInfo())
  13046. return;
  13047. /*if (!mCurMethodState->mRetVal)
  13048. {
  13049. if (mCurMethodInstance->mMethodDef->mName != "Ziggle")
  13050. return;
  13051. }*/
  13052. if ((mCurMethodState->mRetVal) || (mCurMethodState->mRetValAddr))
  13053. {
  13054. BfType* dbgType = mCurMethodInstance->mReturnType;
  13055. BfIRValue dbgValue = mCurMethodState->mRetVal.mValue;
  13056. if ((!mIsComptimeModule) && (mCurMethodInstance->GetStructRetIdx() != -1))
  13057. {
  13058. BF_ASSERT(mCurMethodState->mRetValAddr);
  13059. dbgType = CreatePointerType(dbgType);
  13060. dbgValue = mCurMethodState->mRetValAddr;
  13061. }
  13062. else
  13063. {
  13064. BF_ASSERT(!mCurMethodState->mRetValAddr);
  13065. }
  13066. mCurMethodState->mDIRetVal = mBfIRBuilder->DbgCreateAutoVariable(mCurMethodState->mCurScope->mDIScope,
  13067. "@return", mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, mBfIRBuilder->DbgGetType(dbgType));
  13068. auto declareCall = mBfIRBuilder->DbgInsertDeclare(dbgValue, mCurMethodState->mDIRetVal);
  13069. }
  13070. }
  13071. BfTypedValue BfModule::CreateTuple(const Array<BfTypedValue>& values, const Array<String>& fieldNames)
  13072. {
  13073. BfTypeVector fieldTypes;
  13074. for (auto arg : values)
  13075. fieldTypes.Add(arg.mType);
  13076. auto tupleType = CreateTupleType(fieldTypes, fieldNames);
  13077. auto tupleTypedValue = BfTypedValue(CreateAlloca(tupleType), tupleType, true);
  13078. for (int fieldIdx = 0; fieldIdx < tupleType->mFieldInstances.size(); fieldIdx++)
  13079. {
  13080. auto& fieldInstance = tupleType->mFieldInstances[fieldIdx];
  13081. if (fieldInstance.mDataIdx <= 0)
  13082. continue;
  13083. auto typedVal = values[fieldIdx];
  13084. typedVal = LoadOrAggregateValue(typedVal);
  13085. mBfIRBuilder->CreateAlignedStore(typedVal.mValue, mBfIRBuilder->CreateInBoundsGEP(tupleTypedValue.mValue, 0, fieldInstance.mDataIdx), typedVal.mType->mAlign);
  13086. }
  13087. return tupleTypedValue;
  13088. }
  13089. void BfModule::CheckVariableDef(BfLocalVariable* variableDef)
  13090. {
  13091. if (variableDef->mName.IsEmpty())
  13092. return;
  13093. BfLocalVarEntry* localVarEntryPtr = NULL;
  13094. if ((mCurMethodState != NULL) && (mCurMethodState->mLocalVarSet.TryGet(BfLocalVarEntry(variableDef), &localVarEntryPtr)))
  13095. {
  13096. auto checkLocal = localVarEntryPtr->mLocalVar;
  13097. if ((checkLocal->mLocalVarIdx >= mCurMethodState->GetLocalStartIdx()) && (!checkLocal->mIsShadow))
  13098. {
  13099. BfError* error;
  13100. if (checkLocal->mIsImplicitParam)
  13101. return; // Ignore 'redefinition'
  13102. if (checkLocal->IsParam())
  13103. {
  13104. if (variableDef->IsParam())
  13105. error = Fail(StrFormat("A parameter named '%s' has already been declared", variableDef->mName.c_str()), variableDef->mNameNode);
  13106. else
  13107. error = Fail(StrFormat("The name '%s' is already used by a parameter. Consider declaring 'var %s;' if you wish to make a mutable copy of that parameter.", variableDef->mName.c_str(), variableDef->mName.c_str()), variableDef->mNameNode);
  13108. }
  13109. else if (checkLocal->mLocalVarIdx < mCurMethodState->mCurScope->mLocalVarStart)
  13110. error = Fail(StrFormat("A variable named '%s' has already been declared in this parent's scope", variableDef->mName.c_str()), variableDef->mNameNode);
  13111. else
  13112. error = Fail(StrFormat("A variable named '%s' has already been declared in this scope", variableDef->mName.c_str()), variableDef->mNameNode);
  13113. if ((checkLocal->mNameNode != NULL) && (error != NULL))
  13114. mCompiler->mPassInstance->MoreInfo("Previous declaration", checkLocal->mNameNode);
  13115. return;
  13116. }
  13117. }
  13118. }
  13119. BfScopeData* BfModule::FindScope(BfAstNode* scopeName, BfMixinState* fromMixinState, bool allowAcrossDeferredBlock)
  13120. {
  13121. bool inMixinDecl = (mCurMethodInstance != NULL) && (mCurMethodInstance->IsMixin());
  13122. if (auto tokenNode = BfNodeDynCast<BfTokenNode>(scopeName))
  13123. {
  13124. if (tokenNode->GetToken() == BfToken_Colon)
  13125. {
  13126. if ((!allowAcrossDeferredBlock) && (mCurMethodState->mInDeferredBlock))
  13127. {
  13128. Fail("Cannot access method scope across deferred block boundary", scopeName);
  13129. return NULL;
  13130. }
  13131. return &mCurMethodState->mHeadScope;
  13132. }
  13133. else if (tokenNode->GetToken() == BfToken_Mixin)
  13134. {
  13135. if (fromMixinState == NULL)
  13136. {
  13137. if (mCurMethodInstance->mMethodDef->mMethodType != BfMethodType_Mixin)
  13138. Fail("'mixin' scope specifier can only be used within a mixin declaration", scopeName);
  13139. return mCurMethodState->mCurScope;
  13140. }
  13141. fromMixinState->mUsedInvocationScope = true;
  13142. return fromMixinState->mTargetScope;
  13143. }
  13144. else if (tokenNode->GetToken() == BfToken_New)
  13145. return NULL;
  13146. }
  13147. if (auto identifier = BfNodeDynCast<BfIdentifierNode>(scopeName))
  13148. {
  13149. auto findLabel = scopeName->ToString();
  13150. bool crossedDeferredBlock = false;
  13151. auto checkScope = mCurMethodState->mCurScope;
  13152. while (checkScope != NULL)
  13153. {
  13154. if (checkScope->mIsDeferredBlock)
  13155. crossedDeferredBlock = true;
  13156. if (checkScope->mLabel == findLabel)
  13157. {
  13158. if ((crossedDeferredBlock) && (!allowAcrossDeferredBlock))
  13159. {
  13160. Fail(StrFormat("Cannot access scope '%s' across deferred block boundary", findLabel.c_str()), scopeName);
  13161. return NULL;
  13162. }
  13163. return checkScope;
  13164. }
  13165. checkScope = checkScope->mPrevScope;
  13166. }
  13167. if (!inMixinDecl)
  13168. Fail(StrFormat("Unable to locate label '%s'", findLabel.c_str()), scopeName);
  13169. }
  13170. if (auto scopeNode = BfNodeDynCast<BfScopeNode>(scopeName))
  13171. {
  13172. return FindScope(scopeNode->mTargetNode, allowAcrossDeferredBlock);
  13173. }
  13174. return mCurMethodState->mCurScope;
  13175. }
  13176. BfScopeData* BfModule::FindScope(BfAstNode* scopeName, bool allowAcrossDeferredBlock)
  13177. {
  13178. return FindScope(scopeName, mCurMethodState->mMixinState, allowAcrossDeferredBlock);
  13179. }
  13180. BfBreakData* BfModule::FindBreakData(BfAstNode* scopeName)
  13181. {
  13182. auto scopeData = FindScope(scopeName, false);
  13183. if (scopeData == NULL)
  13184. return NULL;
  13185. int scopeDepth = scopeData->GetDepth();
  13186. // Find the first break data that is at or below the depth of our requested scope
  13187. auto breakData = mCurMethodState->mBreakData;
  13188. while ((breakData != NULL) && (scopeDepth < breakData->mScope->GetDepth()))
  13189. {
  13190. if (breakData->mScope->mIsConditional)
  13191. return NULL;
  13192. breakData = breakData->mPrevBreakData;
  13193. }
  13194. return breakData;
  13195. }
  13196. void BfModule::EmitLifetimeEnds(BfScopeData* scopeData)
  13197. {
  13198. // LLVM is stricter about the placement of these (ie: they can't occur after a 'ret')
  13199. if (!IsTargetingBeefBackend())
  13200. return;
  13201. for (auto lifetimeEnd : scopeData->mDeferredLifetimeEnds)
  13202. {
  13203. mBfIRBuilder->CreateLifetimeEnd(lifetimeEnd);
  13204. }
  13205. }
  13206. void BfModule::ClearLifetimeEnds()
  13207. {
  13208. auto scopeData = mCurMethodState->mCurScope;
  13209. while (scopeData != NULL)
  13210. {
  13211. scopeData->mDeferredLifetimeEnds.Clear();
  13212. scopeData = scopeData->mPrevScope;
  13213. }
  13214. }
  13215. bool BfModule::WantsDebugInfo()
  13216. {
  13217. if ((mCurMethodInstance != NULL) &&
  13218. ((mCurMethodInstance->mIsUnspecialized) || (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_Mixin)))
  13219. return false;
  13220. return (mBfIRBuilder->DbgHasInfo()) && (mHasFullDebugInfo) &&
  13221. ((mCurMethodState == NULL) || (mCurMethodState->mClosureState == NULL) || (!mCurMethodState->mClosureState->mCapturing));
  13222. }
  13223. BfTypeOptions* BfModule::GetTypeOptions()
  13224. {
  13225. if ((mCurMethodState != NULL) && (mCurMethodState->mMethodTypeOptions != NULL))
  13226. return mCurMethodState->mMethodTypeOptions;
  13227. if (mCurMethodInstance == NULL)
  13228. return NULL;
  13229. return mSystem->GetTypeOptions(mCurTypeInstance->mTypeOptionsIdx);
  13230. }
  13231. BfReflectKind BfModule::GetUserReflectKind(BfTypeInstance* attrType)
  13232. {
  13233. BfReflectKind reflectKind = BfReflectKind_None;
  13234. if (attrType->mCustomAttributes != NULL)
  13235. {
  13236. for (auto& customAttr : attrType->mCustomAttributes->mAttributes)
  13237. {
  13238. if (customAttr.mType->mTypeDef->mName->ToString() == "AttributeUsageAttribute")
  13239. {
  13240. for (auto& prop : customAttr.mSetProperties)
  13241. {
  13242. auto propDef = prop.mPropertyRef.mTypeInstance->mTypeDef->mProperties[prop.mPropertyRef.mPropIdx];
  13243. if (propDef->mName == "ReflectUser")
  13244. {
  13245. if (prop.mParam.mValue.IsConst())
  13246. {
  13247. auto constant = attrType->mConstHolder->GetConstant(prop.mParam.mValue);
  13248. reflectKind = (BfReflectKind)(reflectKind | (BfReflectKind)constant->mInt32);
  13249. }
  13250. }
  13251. }
  13252. // Check for Flags arg
  13253. if (customAttr.mCtorArgs.size() < 2)
  13254. continue;
  13255. auto constant = attrType->mConstHolder->GetConstant(customAttr.mCtorArgs[1]);
  13256. if (constant == NULL)
  13257. continue;
  13258. if (constant->mTypeCode == BfTypeCode_Boolean)
  13259. continue;
  13260. if ((constant->mInt8 & BfCustomAttributeFlags_ReflectAttribute) != 0)
  13261. reflectKind = (BfReflectKind)(reflectKind | BfReflectKind_User);
  13262. }
  13263. }
  13264. }
  13265. return reflectKind;
  13266. }
  13267. BfReflectKind BfModule::GetReflectKind(BfReflectKind reflectKind, BfTypeInstance* typeInstance)
  13268. {
  13269. auto checkTypeInstance = typeInstance;
  13270. while (checkTypeInstance != NULL)
  13271. {
  13272. if (checkTypeInstance->mCustomAttributes != NULL)
  13273. {
  13274. auto checkReflectKind = BfReflectKind_None;
  13275. for (auto& customAttr : checkTypeInstance->mCustomAttributes->mAttributes)
  13276. {
  13277. if (customAttr.mType->mTypeDef->mName->ToString() == "ReflectAttribute")
  13278. {
  13279. if (customAttr.mCtorArgs.size() > 0)
  13280. {
  13281. auto constant = checkTypeInstance->mConstHolder->GetConstant(customAttr.mCtorArgs[0]);
  13282. checkReflectKind = (BfReflectKind)((int)checkReflectKind | constant->mInt32);
  13283. }
  13284. else
  13285. {
  13286. checkReflectKind = BfReflectKind_All;
  13287. }
  13288. }
  13289. else
  13290. {
  13291. auto userReflectKind = GetUserReflectKind(customAttr.mType);
  13292. checkReflectKind = (BfReflectKind)(checkReflectKind | userReflectKind);
  13293. }
  13294. }
  13295. if ((checkTypeInstance == typeInstance) ||
  13296. ((checkReflectKind & BfReflectKind_ApplyToInnerTypes) != 0))
  13297. {
  13298. reflectKind = (BfReflectKind)(reflectKind | checkReflectKind);
  13299. }
  13300. }
  13301. for (auto ifaceEntry : typeInstance->mInterfaces)
  13302. {
  13303. if (ifaceEntry.mInterfaceType->mCustomAttributes != NULL)
  13304. {
  13305. auto iface = ifaceEntry.mInterfaceType;
  13306. auto customAttr = iface->mCustomAttributes->Get(mCompiler->mReflectAttributeTypeDef);
  13307. if (customAttr != NULL)
  13308. {
  13309. for (auto& prop : customAttr->mSetProperties)
  13310. {
  13311. auto propDef = prop.mPropertyRef.mTypeInstance->mTypeDef->mProperties[prop.mPropertyRef.mPropIdx];
  13312. if (propDef->mName == "ReflectImplementer")
  13313. {
  13314. if (prop.mParam.mValue.IsConst())
  13315. {
  13316. auto constant = iface->mConstHolder->GetConstant(prop.mParam.mValue);
  13317. reflectKind = (BfReflectKind)(reflectKind | (BfReflectKind)constant->mInt32);
  13318. }
  13319. }
  13320. }
  13321. }
  13322. }
  13323. }
  13324. checkTypeInstance = mContext->mUnreifiedModule->GetOuterType(checkTypeInstance);
  13325. }
  13326. return reflectKind;
  13327. }
  13328. bool BfModule::HasDeferredScopeCalls(BfScopeData* scope)
  13329. {
  13330. BfScopeData* checkScope = mCurMethodState->mCurScope;
  13331. while (checkScope != NULL)
  13332. {
  13333. if ((!checkScope->mDeferredCallEntries.IsEmpty()) || (!checkScope->mDeferredLifetimeEnds.empty()))
  13334. return true;
  13335. if (checkScope == scope)
  13336. break;
  13337. checkScope = checkScope->mPrevScope;
  13338. }
  13339. return false;
  13340. }
  13341. void BfModule::EmitDeferredScopeCalls(bool useSrcPositions, BfScopeData* scopeData, BfIRBlock doneBlock)
  13342. {
  13343. // Is there anything we need to do here?
  13344. if (mBfIRBuilder->mIgnoreWrites)
  13345. {
  13346. // Just visit deferred blocks
  13347. BfScopeData* checkScope = mCurMethodState->mCurScope;
  13348. while (checkScope != NULL)
  13349. {
  13350. BfDeferredCallEntry* deferredCallEntry = checkScope->mDeferredCallEntries.mHead;
  13351. while (deferredCallEntry != NULL)
  13352. {
  13353. if (deferredCallEntry->mDeferredBlock != NULL)
  13354. {
  13355. SetAndRestoreValue<BfMixinState*> prevMixinState(mCurMethodState->mMixinState, checkScope->mMixinState);
  13356. if (checkScope == &mCurMethodState->mHeadScope)
  13357. CreateRetValLocal();
  13358. SetAndRestoreValue<BfAstNode*> prevCustomAttribute(mCurMethodState->mEmitRefNode, deferredCallEntry->mEmitRefNode);
  13359. VisitEmbeddedStatement(deferredCallEntry->mDeferredBlock, NULL, BfEmbeddedStatementFlags_IsDeferredBlock);
  13360. }
  13361. deferredCallEntry = deferredCallEntry->mNext;
  13362. }
  13363. if (checkScope == scopeData)
  13364. break;
  13365. checkScope = checkScope->mPrevScope;
  13366. }
  13367. return;
  13368. }
  13369. // Why did we want to do SetIllegalSrcPos here?
  13370. // Don't we always want to step onto these instances?
  13371. // Find a case where we don't and perhaps only do it there.
  13372. // The downside was that 'EmitEnsureInstructionAt' on the end of block statements causes
  13373. // a (seemingly) unneeded NOP when we do SetIllegalSrcPos
  13374. //SetIllegalSrcPos();
  13375. bool setSrcPos = false;
  13376. bool wantsNop = true;
  13377. BfAstNode* deferCloseNode = NULL;
  13378. if (mCurMethodState->mInPostReturn)
  13379. {
  13380. // These won't get used, they are post-return
  13381. return;
  13382. }
  13383. SizedArray<BfIRValue, 8> deferredLifetimeEnds;
  13384. BfScopeData* scopeJumpBlock = NULL;
  13385. bool hadExtraDeferredLifetimeEnds = false;
  13386. auto _FlushLifetimeEnds = [&]()
  13387. {
  13388. for (auto lifetimeEnd : deferredLifetimeEnds)
  13389. {
  13390. mBfIRBuilder->CreateLifetimeEnd(lifetimeEnd);
  13391. mBfIRBuilder->ClearDebugLocation_Last();
  13392. }
  13393. deferredLifetimeEnds.clear();
  13394. };
  13395. BfScopeData* checkScope = mCurMethodState->mCurScope;
  13396. while (checkScope != NULL)
  13397. {
  13398. if (checkScope->mCloseNode != NULL)
  13399. deferCloseNode = checkScope->mCloseNode;
  13400. if (doneBlock)
  13401. {
  13402. // Try to find a match where we've already emitted these calls and then jumped to the correct block
  13403. for (auto& checkHandler : checkScope->mDeferredHandlers)
  13404. {
  13405. if (checkHandler.mDoneBlock == doneBlock)
  13406. {
  13407. scopeJumpBlock = checkScope;
  13408. mBfIRBuilder->CreateBr(checkHandler.mHandlerBlock);
  13409. mBfIRBuilder->ClearDebugLocation_Last();
  13410. _FlushLifetimeEnds();
  13411. break;
  13412. }
  13413. }
  13414. if (scopeJumpBlock != NULL)
  13415. break;
  13416. }
  13417. bool hasWork = (checkScope->mSavedStack) || (checkScope->mDeferredCallEntries.mHead != NULL);
  13418. if (checkScope != scopeData) // Only emit a block for deferred lifetimes if we're going back beyond this entry
  13419. hasWork |= (!deferredLifetimeEnds.IsEmpty());
  13420. if (hasWork)
  13421. {
  13422. SetAndRestoreValue<BfScopeData*> prevScope(mCurMethodState->mCurScope, checkScope);
  13423. if (deferCloseNode != NULL)
  13424. {
  13425. UpdateSrcPos(deferCloseNode);
  13426. }
  13427. if (checkScope == &mCurMethodState->mHeadScope)
  13428. CreateRetValLocal();
  13429. if (doneBlock)
  13430. {
  13431. bool crossingMixin = mCurMethodState->mCurScope->mMixinDepth != checkScope->mMixinDepth;
  13432. String blockName = "deferredCalls";
  13433. //blockName += StrFormat("_%d", mBfIRBuilder->mBlockCount);
  13434. BfDeferredHandler deferredHandler;
  13435. if ((!crossingMixin) && (deferredLifetimeEnds.IsEmpty()))
  13436. {
  13437. mBfIRBuilder->SaveDebugLocation();
  13438. mBfIRBuilder->ClearDebugLocation();
  13439. deferredHandler.mHandlerBlock = mBfIRBuilder->MaybeChainNewBlock(blockName);
  13440. mBfIRBuilder->RestoreDebugLocation();
  13441. }
  13442. else
  13443. {
  13444. // Definitely chain
  13445. deferredHandler.mHandlerBlock = mBfIRBuilder->CreateBlock(blockName);
  13446. mBfIRBuilder->CreateBr(deferredHandler.mHandlerBlock);
  13447. mBfIRBuilder->ClearDebugLocation_Last();
  13448. _FlushLifetimeEnds();
  13449. mBfIRBuilder->AddBlock(deferredHandler.mHandlerBlock);
  13450. mBfIRBuilder->SetInsertPoint(deferredHandler.mHandlerBlock);
  13451. }
  13452. deferredHandler.mDoneBlock = doneBlock;
  13453. if (!mBfIRBuilder->mIgnoreWrites)
  13454. checkScope->mDeferredHandlers.push_back(deferredHandler);
  13455. if (checkScope == &mCurMethodState->mHeadScope)
  13456. {
  13457. if (!mCurMethodState->mDIRetVal)
  13458. {
  13459. // 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
  13460. // be scoped to the physical method
  13461. /*if (deferCloseNode != NULL)
  13462. {
  13463. UpdateSrcPos(deferCloseNode);
  13464. }*/
  13465. CreateDIRetVal();
  13466. }
  13467. }
  13468. if (checkScope != mCurMethodState->mTailScope)
  13469. {
  13470. if (deferredHandler.mHandlerBlock.IsFake())
  13471. {
  13472. BF_ASSERT(mBfIRBuilder->mIgnoreWrites);
  13473. }
  13474. if (!mBfIRBuilder->mIgnoreWrites)
  13475. checkScope->mAtEndBlocks.push_back(deferredHandler.mHandlerBlock);
  13476. }
  13477. }
  13478. std::unordered_set<BfDeferredCallEntry*> handledSet;
  13479. BfDeferredCallEntry* deferredCallEntry = checkScope->mDeferredCallEntries.mHead;
  13480. while (deferredCallEntry != NULL)
  13481. {
  13482. BfDeferredCallEmitState deferredCallEmitState;
  13483. deferredCallEmitState.mCloseNode = deferCloseNode;
  13484. SetAndRestoreValue<BfDeferredCallEmitState*> prevDeferredCallEmitState(mCurMethodState->mDeferredCallEmitState, &deferredCallEmitState);
  13485. SetAndRestoreValue<bool> prevIgnoredWrites(mBfIRBuilder->mIgnoreWrites, deferredCallEntry->mIgnored);
  13486. SetAndRestoreValue<BfMixinState*> prevMixinState(mCurMethodState->mMixinState, checkScope->mMixinState);
  13487. if (deferCloseNode != NULL)
  13488. {
  13489. UpdateSrcPos(deferCloseNode);
  13490. }
  13491. if (wantsNop)
  13492. EmitEnsureInstructionAt();
  13493. wantsNop = false;
  13494. if (deferredCallEntry->mDeferredBlock != NULL)
  13495. {
  13496. auto itr = handledSet.insert(deferredCallEntry);
  13497. if (!itr.second)
  13498. {
  13499. // Already handled, can happen if we defer again within the block
  13500. deferredCallEntry = deferredCallEntry->mNext;
  13501. continue;
  13502. }
  13503. auto prevHead = checkScope->mDeferredCallEntries.mHead;
  13504. EmitDeferredCall(*deferredCallEntry, true);
  13505. if (prevHead != checkScope->mDeferredCallEntries.mHead)
  13506. {
  13507. // The list changed, start over and ignore anything we've already handled
  13508. deferredCallEntry = checkScope->mDeferredCallEntries.mHead;
  13509. }
  13510. else
  13511. deferredCallEntry = deferredCallEntry->mNext;
  13512. }
  13513. else
  13514. {
  13515. EmitDeferredCall(*deferredCallEntry, true);
  13516. deferredCallEntry = deferredCallEntry->mNext;
  13517. }
  13518. }
  13519. if (checkScope->mSavedStack)
  13520. {
  13521. checkScope->mSavedStackUses.Add(mBfIRBuilder->CreateStackRestore(checkScope->mSavedStack));
  13522. if (mCurMethodState->mDynStackRevIdx)
  13523. {
  13524. auto curValue = mBfIRBuilder->CreateLoad(mCurMethodState->mDynStackRevIdx);
  13525. auto newValue = mBfIRBuilder->CreateAdd(curValue, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 1));
  13526. mBfIRBuilder->CreateStore(newValue, mCurMethodState->mDynStackRevIdx);
  13527. }
  13528. }
  13529. }
  13530. if (!checkScope->mIsScopeHead)
  13531. {
  13532. // We manually emit function-level lifetime ends after the 'ret' in ProcessMethod
  13533. if (!IsTargetingBeefBackend())
  13534. {
  13535. for (auto lifetimeEnd : checkScope->mDeferredLifetimeEnds)
  13536. {
  13537. mBfIRBuilder->CreateLifetimeEnd(lifetimeEnd);
  13538. }
  13539. }
  13540. else
  13541. {
  13542. for (auto lifetimeEnd : checkScope->mDeferredLifetimeEnds)
  13543. {
  13544. deferredLifetimeEnds.Add(lifetimeEnd);
  13545. }
  13546. }
  13547. }
  13548. if (checkScope == scopeData)
  13549. break;
  13550. checkScope = checkScope->mPrevScope;
  13551. }
  13552. if ((doneBlock) && (scopeJumpBlock == NULL))
  13553. {
  13554. mBfIRBuilder->CreateBr(doneBlock);
  13555. mBfIRBuilder->ClearDebugLocation_Last();
  13556. }
  13557. // Keeping CreateLifetimeEnds until the end messes up when we chain to old mDeferredHandlers that
  13558. // may have been created when other scope lifetimes were available
  13559. _FlushLifetimeEnds();
  13560. // Emit lifetimeEnds after the branch for Beef
  13561. /*if (IsTargetingBeefBackend())
  13562. {
  13563. bool needsEnsureInst = (!doneBlock) && (scopeJumpBlock == NULL);
  13564. BfScopeData* checkScope = mCurMethodState->mCurScope;
  13565. while (checkScope != NULL)
  13566. {
  13567. if (checkScope == scopeJumpBlock)
  13568. break;
  13569. if (!checkScope->mIsScopeHead)
  13570. {
  13571. for (auto lifetimeEnd : checkScope->mDeferredLifetimeEnds)
  13572. {
  13573. if (needsEnsureInst)
  13574. {
  13575. needsEnsureInst = false;
  13576. }
  13577. mBfIRBuilder->CreateLifetimeEnd(lifetimeEnd);
  13578. }
  13579. }
  13580. if (checkScope == scopeData)
  13581. break;
  13582. checkScope = checkScope->mPrevScope;
  13583. }
  13584. }*/
  13585. }
  13586. void BfModule::MarkScopeLeft(BfScopeData* scopeData, bool isNoReturn)
  13587. {
  13588. if ((mCurMethodState->mDeferredLocalAssignData != NULL) && (!isNoReturn))
  13589. {
  13590. auto deferredLocalAssignData = mCurMethodState->mDeferredLocalAssignData;
  13591. while (deferredLocalAssignData != NULL)
  13592. {
  13593. if ((deferredLocalAssignData->mScopeData == NULL) || (deferredLocalAssignData->mScopeData->mScopeDepth < scopeData->mScopeDepth))
  13594. break;
  13595. if ((deferredLocalAssignData->mScopeData != NULL) && (deferredLocalAssignData->mScopeData->mScopeDepth == scopeData->mScopeDepth))
  13596. deferredLocalAssignData->mIsUnconditional = false;
  13597. deferredLocalAssignData = deferredLocalAssignData->mChainedAssignData;
  13598. }
  13599. }
  13600. // When we leave a scope, mark those as assigned for deferred assignment purposes
  13601. for (int localIdx = scopeData->mLocalVarStart; localIdx < (int)mCurMethodState->mLocals.size(); localIdx++)
  13602. {
  13603. auto localDef = mCurMethodState->mLocals[localIdx];
  13604. if (localDef->mAssignedKind == BfLocalVarAssignKind_None)
  13605. {
  13606. bool hadAssignment = false;
  13607. if (mCurMethodState->mDeferredLocalAssignData != NULL)
  13608. {
  13609. for (auto& entry : mCurMethodState->mDeferredLocalAssignData->mAssignedLocals)
  13610. if (entry.mLocalVar == localDef)
  13611. hadAssignment = true;
  13612. }
  13613. if (!hadAssignment)
  13614. {
  13615. if (!isNoReturn)
  13616. localDef->mHadExitBeforeAssign = true;
  13617. mCurMethodState->LocalDefined(localDef);
  13618. }
  13619. }
  13620. }
  13621. }
  13622. void BfModule::CreateReturn(BfIRValue val)
  13623. {
  13624. if ((!mIsComptimeModule) && (mCurMethodInstance->GetStructRetIdx() != -1))
  13625. {
  13626. // Store to sret
  13627. BF_ASSERT(val);
  13628. mBfIRBuilder->CreateStore(val, mBfIRBuilder->GetArgument(mCurMethodInstance->GetStructRetIdx()));
  13629. mBfIRBuilder->CreateRetVoid();
  13630. return;
  13631. }
  13632. if (mCurMethodInstance->mReturnType->IsVar())
  13633. return;
  13634. if (mCurMethodInstance->mReturnType->IsValuelessType())
  13635. {
  13636. mBfIRBuilder->CreateRetVoid();
  13637. return;
  13638. }
  13639. if (mCurMethodInstance->mReturnType->IsStruct())
  13640. {
  13641. BfTypeCode loweredReturnType = BfTypeCode_None;
  13642. BfTypeCode loweredReturnType2 = BfTypeCode_None;
  13643. if (!mIsComptimeModule)
  13644. mCurMethodInstance->GetLoweredReturnType(&loweredReturnType, &loweredReturnType2);
  13645. if (loweredReturnType != BfTypeCode_None)
  13646. {
  13647. auto retVal = CreateAlloca(mCurMethodInstance->mReturnType);
  13648. mBfIRBuilder->CreateStore(val, retVal);
  13649. auto irRetType = GetIRLoweredType(loweredReturnType, loweredReturnType2);
  13650. irRetType = mBfIRBuilder->GetPointerTo(irRetType);
  13651. auto ptrReturnValue = mBfIRBuilder->CreateBitCast(retVal, irRetType);
  13652. auto loadedReturnValue = mBfIRBuilder->CreateLoad(ptrReturnValue);
  13653. mBfIRBuilder->CreateRet(loadedReturnValue);
  13654. return;
  13655. }
  13656. }
  13657. BF_ASSERT(val);
  13658. mBfIRBuilder->CreateRet(val);
  13659. }
  13660. void BfModule::EmitReturn(const BfTypedValue& val)
  13661. {
  13662. if (mCurMethodState->mIRExitBlock)
  13663. {
  13664. if (!mCurMethodInstance->mReturnType->IsValuelessType())
  13665. {
  13666. if (val) // We allow for val to be empty if we know we've already written the value to mRetVal
  13667. {
  13668. if ((mCurMethodState->mRetValAddr) || (mCurMethodState->mRetVal))
  13669. {
  13670. BfIRValue retVal = mCurMethodState->mRetVal.mValue;
  13671. if (!mCurMethodState->mRetVal)
  13672. retVal = mBfIRBuilder->CreateLoad(mCurMethodState->mRetValAddr);
  13673. mBfIRBuilder->CreateStore(val.mValue, retVal);
  13674. }
  13675. else if (mIsComptimeModule)
  13676. {
  13677. if (!val.mType->IsValuelessType())
  13678. mBfIRBuilder->CreateSetRet(val.mValue, val.mType->mTypeId);
  13679. else
  13680. mBfIRBuilder->CreateSetRet(BfIRValue(), val.mType->mTypeId);
  13681. }
  13682. else
  13683. {
  13684. // Just ignore
  13685. BF_ASSERT(mCurMethodInstance->mReturnType->IsVar());
  13686. }
  13687. }
  13688. }
  13689. EmitDeferredScopeCalls(true, NULL, mCurMethodState->mIRExitBlock);
  13690. }
  13691. else
  13692. {
  13693. EmitDeferredScopeCalls(false, NULL);
  13694. if (val)
  13695. {
  13696. BF_ASSERT(mBfIRBuilder->mIgnoreWrites);
  13697. }
  13698. }
  13699. mCurMethodState->SetHadReturn(true);
  13700. mCurMethodState->mLeftBlockUncond = true;
  13701. }
  13702. void BfModule::EmitDefaultReturn()
  13703. {
  13704. if (mCurMethodState->mInDeferredBlock)
  13705. return;
  13706. if (mCurMethodState->mIRExitBlock)
  13707. {
  13708. EmitDeferredScopeCalls(true, NULL, mCurMethodState->mIRExitBlock);
  13709. }
  13710. else
  13711. {
  13712. if ((mCurMethodInstance == NULL) || (mCurMethodInstance->mReturnType->IsVar()))
  13713. {
  13714. // Ignore
  13715. }
  13716. else if (mCurMethodInstance->mReturnType->IsVoid())
  13717. mBfIRBuilder->CreateRetVoid();
  13718. else if ((!mIsComptimeModule) && (mCurMethodInstance->GetStructRetIdx() == -1))
  13719. mBfIRBuilder->CreateRet(GetDefaultValue(mCurMethodInstance->mReturnType));
  13720. }
  13721. mCurMethodState->SetHadReturn(true);
  13722. mCurMethodState->mLeftBlockUncond = true;
  13723. }
  13724. void BfModule::AssertErrorState()
  13725. {
  13726. if (mIgnoreErrors)
  13727. return;
  13728. if (mHadBuildError)
  13729. return;
  13730. if (mCurTypeInstance != NULL)
  13731. {
  13732. if (mCurTypeInstance->IsUnspecializedTypeVariation())
  13733. return;
  13734. }
  13735. if (mCurMethodInstance != NULL)
  13736. {
  13737. if (mCurMethodInstance->IsOrInUnspecializedVariation())
  13738. return;
  13739. if (mCurMethodInstance->mHasFailed)
  13740. return;
  13741. }
  13742. // We want the module to be marked as failed even if it's just an error in the parser
  13743. if (mCurMethodInstance != NULL)
  13744. mCurMethodInstance->mHasFailed = true;
  13745. mHadBuildError = true;
  13746. // We check for either the parsing to have failed (possibly on a previous run), or for the current instance to have failed
  13747. if (mCurTypeInstance != NULL)
  13748. {
  13749. if (mCurTypeInstance->mTypeFailed)
  13750. return;
  13751. if ((mCurTypeInstance->mTypeDef->GetDefinition()->mSource != NULL) && (mCurTypeInstance->mTypeDef->GetDefinition()->mSource->mParsingFailed))
  13752. return;
  13753. }
  13754. if (mCurMethodInstance != NULL)
  13755. {
  13756. if ((mCurMethodInstance->mMethodDef->mDeclaringType != NULL) &&
  13757. (mCurMethodInstance->mMethodDef->mDeclaringType->mSource != NULL) &&
  13758. (mCurMethodInstance->mMethodDef->mDeclaringType->mSource->mParsingFailed))
  13759. return;
  13760. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL) &&
  13761. (mCurMethodState->mMixinState->mMixinMethodInstance->mMethodDef->mDeclaringType->mSource != NULL) &&
  13762. (mCurMethodState->mMixinState->mMixinMethodInstance->mMethodDef->mDeclaringType->mSource->mParsingFailed))
  13763. return;
  13764. }
  13765. if (mCompiler->IsAutocomplete())
  13766. return;
  13767. BF_ASSERT(mCompiler->mPassInstance->HasFailed());
  13768. }
  13769. void BfModule::AssertParseErrorState()
  13770. {
  13771. if (mCompiler->mRevision == 1)
  13772. AssertErrorState();
  13773. }
  13774. BfType* BfModule::GetDelegateReturnType(BfType* delegateType)
  13775. {
  13776. BF_ASSERT(delegateType->IsDelegate());
  13777. auto typeInst = delegateType->ToTypeInstance();
  13778. PopulateType(typeInst, BfPopulateType_DataAndMethods);
  13779. BfMethodInstance* invokeMethodInstance = GetRawMethodInstanceAtIdx(typeInst->ToTypeInstance(), 0, "Invoke");
  13780. return invokeMethodInstance->mReturnType;
  13781. }
  13782. BfMethodInstance* BfModule::GetDelegateInvokeMethod(BfTypeInstance* typeInstance)
  13783. {
  13784. return GetRawMethodInstanceAtIdx(typeInstance, 0, "Invoke");
  13785. }
  13786. void BfModule::CreateDelegateInvokeMethod()
  13787. {
  13788. // Clear out debug loc - otherwise we'll single step onto the delegate type declaration
  13789. //mBfIRBuilder->ClearDebugLocation();
  13790. SetIllegalSrcPos();
  13791. auto typeInstance = mCurTypeInstance;
  13792. auto memberFuncType = mBfIRBuilder->MapMethod(mCurMethodInstance);
  13793. SizedArray<BfIRType, 4> staticParamTypes;
  13794. SizedArray<BfIRValue, 4> staticFuncArgs;
  13795. SizedArray<BfIRValue, 4> memberFuncArgs;
  13796. auto multicastDelegateType = typeInstance->mBaseType;
  13797. if (multicastDelegateType->mFieldInstances.size() != 2)
  13798. {
  13799. AssertErrorState();
  13800. return;
  13801. }
  13802. auto multicastDelegate = mBfIRBuilder->CreateBitCast(mCurMethodState->mLocals[0]->mValue, mBfIRBuilder->MapType(multicastDelegateType));
  13803. auto fieldPtr = mBfIRBuilder->CreateInBoundsGEP(multicastDelegate, 0, 2); // Load 'delegate.mTarget'
  13804. auto fieldVal = mBfIRBuilder->CreateLoad(fieldPtr);
  13805. BfExprEvaluator exprEvaluator(this);
  13806. SizedArray<BfIRType, 8> origParamTypes;
  13807. BfIRType origReturnType;
  13808. BfIRType staticReturnType;
  13809. mCurMethodInstance->GetIRFunctionInfo(this, origReturnType, origParamTypes);
  13810. if (mCurMethodInstance->mReturnType->IsValueType())
  13811. mBfIRBuilder->PopulateType(mCurMethodInstance->mReturnType, BfIRPopulateType_Full);
  13812. if ((mIsComptimeModule) || (mCurMethodInstance->GetStructRetIdx() != 0))
  13813. memberFuncArgs.push_back(BfIRValue()); // Push 'target'
  13814. int thisIdx = 0;
  13815. if ((!mIsComptimeModule) && (mCurMethodInstance->GetStructRetIdx() != -1))
  13816. {
  13817. thisIdx = mCurMethodInstance->GetStructRetIdx() ^ 1;
  13818. memberFuncArgs.push_back(mBfIRBuilder->GetArgument(mCurMethodInstance->GetStructRetIdx()));
  13819. }
  13820. if ((!mIsComptimeModule) && (mCurMethodInstance->GetStructRetIdx(true) != -1))
  13821. staticFuncArgs.push_back(mBfIRBuilder->GetArgument(mCurMethodInstance->GetStructRetIdx()));
  13822. if ((!mIsComptimeModule) && (mCurMethodInstance->GetStructRetIdx() == 0))
  13823. memberFuncArgs.push_back(BfIRValue()); // Push 'target'
  13824. mCurMethodInstance->GetIRFunctionInfo(this, staticReturnType, staticParamTypes, true);
  13825. for (int i = 1; i < (int)mCurMethodState->mLocals.size(); i++)
  13826. {
  13827. BfTypedValue localVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[i], true);
  13828. exprEvaluator.PushArg(localVal, staticFuncArgs);
  13829. exprEvaluator.PushArg(localVal, memberFuncArgs);
  13830. }
  13831. auto staticFunc = mBfIRBuilder->CreateFunctionType(staticReturnType, staticParamTypes, false);
  13832. auto staticFuncPtr = mBfIRBuilder->GetPointerTo(staticFunc);
  13833. auto staticFuncPtrPtr = mBfIRBuilder->GetPointerTo(staticFuncPtr);
  13834. auto trueBB = mBfIRBuilder->CreateBlock("if.then", true);
  13835. auto falseBB = mBfIRBuilder->CreateBlock("if.else");
  13836. auto doneBB = mBfIRBuilder->CreateBlock("done");
  13837. auto checkTargetNull = mBfIRBuilder->CreateIsNotNull(fieldVal);
  13838. mBfIRBuilder->CreateCondBr(checkTargetNull, trueBB, falseBB);
  13839. BfIRValue nonStaticResult;
  13840. BfIRValue staticResult;
  13841. auto callingConv = GetIRCallingConvention(mCurMethodInstance);
  13842. /// Non-static invocation
  13843. {
  13844. auto memberFuncPtr = mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapMethod(mCurMethodInstance));
  13845. auto memberFuncPtrPtr = mBfIRBuilder->GetPointerTo(memberFuncPtr);
  13846. mBfIRBuilder->SetInsertPoint(trueBB);
  13847. memberFuncArgs[thisIdx] = mBfIRBuilder->CreateBitCast(fieldVal, mBfIRBuilder->MapType(mCurTypeInstance));
  13848. auto fieldPtr = mBfIRBuilder->CreateInBoundsGEP(multicastDelegate, 0, 1); // Load 'delegate.mFuncPtr'
  13849. auto funcPtrPtr = mBfIRBuilder->CreateBitCast(fieldPtr, memberFuncPtrPtr);
  13850. auto funcPtr = mBfIRBuilder->CreateLoad(funcPtrPtr);
  13851. nonStaticResult = mBfIRBuilder->CreateCall(funcPtr, memberFuncArgs);
  13852. if ((!mIsComptimeModule) && (mCurMethodInstance->GetStructRetIdx() != -1))
  13853. mBfIRBuilder->Call_AddAttribute(nonStaticResult, mCurMethodInstance->GetStructRetIdx() + 1, BfIRAttribute_StructRet);
  13854. if (callingConv != BfIRCallingConv_CDecl)
  13855. mBfIRBuilder->SetCallCallingConv(nonStaticResult, callingConv);
  13856. mCurMethodState->SetHadReturn(false);
  13857. mCurMethodState->mLeftBlockUncond = false;
  13858. mCurMethodState->mLeftBlockCond = false;
  13859. mBfIRBuilder->CreateBr(doneBB);
  13860. }
  13861. // Static invocation
  13862. {
  13863. mBfIRBuilder->AddBlock(falseBB);
  13864. mBfIRBuilder->SetInsertPoint(falseBB);
  13865. auto fieldPtr = mBfIRBuilder->CreateInBoundsGEP(multicastDelegate, 0, 1); // Load 'delegate.mFuncPtr'
  13866. auto funcPtrPtr = mBfIRBuilder->CreateBitCast(fieldPtr, staticFuncPtrPtr);
  13867. auto funcPtr = mBfIRBuilder->CreateLoad(funcPtrPtr);
  13868. staticResult = mBfIRBuilder->CreateCall(funcPtr, staticFuncArgs);
  13869. if ((!mIsComptimeModule) && (mCurMethodInstance->GetStructRetIdx(true) != -1))
  13870. {
  13871. // Note: since this is a forced static invocation, we know the sret will be the first parameter
  13872. mBfIRBuilder->Call_AddAttribute(staticResult, 0 + 1, BfIRAttribute_StructRet);
  13873. }
  13874. // We had a sret for the non-static but no sret for the static (because we have a lowered return type there)
  13875. if ((!mIsComptimeModule) && (mCurMethodInstance->GetStructRetIdx() != -1) && (mCurMethodInstance->GetStructRetIdx(true) == -1))
  13876. {
  13877. auto sretToType = mBfIRBuilder->GetPointerTo(staticReturnType);
  13878. auto sretCastedPtr = mBfIRBuilder->CreateBitCast(mBfIRBuilder->GetArgument(mCurMethodInstance->GetStructRetIdx()), sretToType);
  13879. mBfIRBuilder->CreateStore(staticResult, sretCastedPtr);
  13880. }
  13881. if (callingConv == BfIRCallingConv_ThisCall)
  13882. callingConv = BfIRCallingConv_CDecl;
  13883. if (callingConv != BfIRCallingConv_CDecl)
  13884. mBfIRBuilder->SetCallCallingConv(staticResult, callingConv);
  13885. mCurMethodState->SetHadReturn(false);
  13886. mCurMethodState->mLeftBlockUncond = false;
  13887. mCurMethodState->mLeftBlockCond = false;
  13888. mBfIRBuilder->CreateBr(doneBB);
  13889. }
  13890. mBfIRBuilder->AddBlock(doneBB);
  13891. mBfIRBuilder->SetInsertPoint(doneBB);
  13892. if (mCurMethodInstance->mReturnType->IsVar())
  13893. {
  13894. // Do nothing
  13895. }
  13896. else if ((mCurMethodInstance->mReturnType->IsValuelessType()) ||
  13897. ((!mIsComptimeModule) && (mCurMethodInstance->GetStructRetIdx() != -1)))
  13898. {
  13899. mBfIRBuilder->CreateRetVoid();
  13900. }
  13901. else
  13902. {
  13903. BfIRType loweredIRReturnType;
  13904. BfTypeCode loweredTypeCode = BfTypeCode_None;
  13905. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  13906. if ((!mIsComptimeModule) && (mCurMethodInstance->GetLoweredReturnType(&loweredTypeCode, &loweredTypeCode2)))
  13907. loweredIRReturnType = GetIRLoweredType(loweredTypeCode, loweredTypeCode2);
  13908. else
  13909. loweredIRReturnType = mBfIRBuilder->MapType(mCurMethodInstance->mReturnType);
  13910. auto phi = mBfIRBuilder->CreatePhi(loweredIRReturnType, 2);
  13911. mBfIRBuilder->AddPhiIncoming(phi, nonStaticResult, trueBB);
  13912. mBfIRBuilder->AddPhiIncoming(phi, staticResult, falseBB);
  13913. mBfIRBuilder->CreateRet(phi);
  13914. }
  13915. }
  13916. // "Interested" here means every method for a normal compile, and just the method the cursor is on for autocompletion
  13917. bool BfModule::IsInterestedInMethod(BfTypeInstance* typeInstance, BfMethodDef* methodDef)
  13918. {
  13919. auto typeDef = typeInstance->mTypeDef;
  13920. auto methodDeclaration = methodDef->mMethodDeclaration;
  13921. if (!mCompiler->mIsResolveOnly)
  13922. return true;
  13923. if (typeInstance->IsGenericTypeInstance())
  13924. {
  13925. // We only really want to process the unspecialized type for autocompletion
  13926. if ((!typeInstance->IsUnspecializedType()) || (typeInstance->IsUnspecializedTypeVariation()))
  13927. return false;
  13928. }
  13929. BfAstNode* checkNode = methodDeclaration;
  13930. if (methodDeclaration == NULL)
  13931. checkNode = methodDef->mBody;
  13932. if ((mCompiler->mResolvePassData->mParser != NULL) && (typeDef->mTypeDeclaration->IsFromParser(mCompiler->mResolvePassData->mParser)))
  13933. {
  13934. if (mCompiler->mResolvePassData->mAutoComplete == NULL)
  13935. return true;
  13936. }
  13937. return false;
  13938. }
  13939. void BfModule::CalcAppendAlign(BfMethodInstance* methodInst)
  13940. {
  13941. methodInst->mAppendAllocAlign = 1;
  13942. }
  13943. BfTypedValue BfModule::TryConstCalcAppend(BfMethodInstance* methodInst, SizedArrayImpl<BfIRValue>& args)
  13944. {
  13945. BP_ZONE("BfModule::TryConstCalcAppend");
  13946. BF_ASSERT(methodInst->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend);
  13947. if ((mCompiler->mIsResolveOnly) && (!mIsComptimeModule))
  13948. return BfTypedValue();
  13949. // We want to regenerate all ctor calls when the method internals change
  13950. {
  13951. auto checkTypeInst = methodInst->GetOwner();
  13952. while (checkTypeInst->mTypeDef->mHasAppendCtor)
  13953. {
  13954. AddDependency(checkTypeInst, mCurTypeInstance, BfDependencyMap::DependencyFlag_InlinedCall);
  13955. checkTypeInst = GetBaseType(checkTypeInst);
  13956. }
  13957. }
  13958. if (!methodInst->mMayBeConst)
  13959. return BfTypedValue();
  13960. // Do we need to iterate in order to resolve mAppendAllocAlign?
  13961. bool isFirstRun = methodInst->mEndingAppendAllocAlign < 0;
  13962. bool wasAllConst = true;
  13963. int argIdx = 0;
  13964. int paramIdx = 0;
  13965. while (true)
  13966. {
  13967. if (argIdx >= (int)args.size())
  13968. break;
  13969. auto paramType = methodInst->GetParamType(paramIdx);
  13970. PopulateType(paramType);
  13971. int argCount = 0;
  13972. if (!paramType->IsValuelessType())
  13973. {
  13974. if ((!mIsComptimeModule) && (methodInst->GetParamIsSplat(paramIdx)))
  13975. argCount = paramType->GetSplatCount();
  13976. else
  13977. argCount = 1;
  13978. for (int argOfs = 0; argOfs < argCount; argOfs++)
  13979. {
  13980. auto arg = args[argIdx + argOfs];
  13981. if (!arg.IsConst())
  13982. {
  13983. wasAllConst = false;
  13984. if (!isFirstRun)
  13985. {
  13986. auto& param = methodInst->mParams[argIdx];
  13987. if (param.mReferencedInConstPass)
  13988. {
  13989. // If this param is required as part of the const calculation then
  13990. // we require that it be const...
  13991. return BfTypedValue();
  13992. }
  13993. }
  13994. }
  13995. }
  13996. }
  13997. paramIdx++;
  13998. argIdx += argCount;
  13999. }
  14000. auto methodDef = methodInst->mMethodDef;
  14001. auto methodDecl = methodDef->GetMethodDeclaration();
  14002. auto methodDeclBlock = BfNodeDynCast<BfBlock>(methodDecl->mBody);
  14003. if (methodDeclBlock == NULL)
  14004. return GetDefaultTypedValue(GetPrimitiveType(BfTypeCode_IntPtr)); // Must not have an append alloc at all!
  14005. BfTypedValue constValue;
  14006. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  14007. auto checkState = mCurMethodState->mConstResolveState;
  14008. while (checkState != NULL)
  14009. {
  14010. if (checkState->mMethodInstance == methodInst)
  14011. {
  14012. return BfTypedValue();
  14013. }
  14014. checkState = checkState->mPrevConstResolveState;
  14015. }
  14016. //auto accumValue = GetConstValue(0);
  14017. bool failed = false;
  14018. //
  14019. {
  14020. BfConstResolveState constResolveState;
  14021. constResolveState.mMethodInstance = methodInst;
  14022. constResolveState.mPrevConstResolveState = mCurMethodState->mConstResolveState;
  14023. SetAndRestoreValue<bool> ignoreWrites(mBfIRBuilder->mIgnoreWrites, true);
  14024. BfMethodState methodState;
  14025. SetAndRestoreValue<BfTypeInstance*> prevTypeInst(mCurTypeInstance, methodInst->GetOwner());
  14026. SetAndRestoreValue<BfMethodInstance*> prevMethodInst(mCurMethodInstance, methodInst);
  14027. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  14028. methodState.mTempKind = BfMethodState::TempKind_NonStatic;
  14029. methodState.mConstResolveState = &constResolveState;
  14030. int argIdx = 0;
  14031. for (int paramIdx = 0; paramIdx < methodInst->GetParamCount(); paramIdx++)
  14032. {
  14033. if (methodInst->GetParamKind(paramIdx) == BfParamKind_AppendIdx)
  14034. continue;
  14035. auto paramType = methodInst->GetParamType(paramIdx);
  14036. // Fix this after we allow structs to be consts
  14037. //BF_ASSERT(!paramType->IsSplattable());
  14038. BfLocalVariable* localVar = new BfLocalVariable();
  14039. localVar->mName = methodInst->GetParamName(paramIdx);
  14040. localVar->mResolvedType = paramType;
  14041. localVar->mConstValue = args[argIdx];
  14042. localVar->mParamIdx = paramIdx;
  14043. AddLocalVariableDef(localVar);
  14044. argIdx++;
  14045. }
  14046. AppendAllocVisitor appendAllocVisitor;
  14047. appendAllocVisitor.mConstAccum = GetDefaultTypedValue(GetPrimitiveType(BfTypeCode_IntPtr));
  14048. appendAllocVisitor.mIsFirstConstPass = isFirstRun;
  14049. BfTypedValue baseCtorAppendValue = CallBaseCtorCalc(true);
  14050. if (baseCtorAppendValue)
  14051. {
  14052. if (baseCtorAppendValue.mValue.IsFake())
  14053. appendAllocVisitor.mFailed = true;
  14054. else
  14055. appendAllocVisitor.mConstAccum = baseCtorAppendValue;
  14056. }
  14057. appendAllocVisitor.mModule = this;
  14058. appendAllocVisitor.VisitChild(methodDecl->mBody);
  14059. if (!appendAllocVisitor.mFailed)
  14060. constValue = appendAllocVisitor.mConstAccum;
  14061. if (isFirstRun)
  14062. {
  14063. mCurMethodInstance->mEndingAppendAllocAlign = appendAllocVisitor.mCurAppendAlign;
  14064. if (mCurMethodInstance->mAppendAllocAlign <= 0)
  14065. mCurMethodInstance->mAppendAllocAlign = 1;
  14066. }
  14067. if (isFirstRun)
  14068. {
  14069. for (int paramIdx = 0; paramIdx < methodInst->GetParamCount(); paramIdx++)
  14070. {
  14071. auto localVar = mCurMethodState->mLocals[paramIdx];
  14072. if (localVar->mReadFromId != -1)
  14073. {
  14074. auto& param = methodInst->mParams[paramIdx];
  14075. param.mReferencedInConstPass = true;
  14076. }
  14077. }
  14078. }
  14079. }
  14080. mBfIRBuilder->SetInsertPoint(prevBlock);
  14081. if (!constValue)
  14082. {
  14083. // If we did a 'force' then some params may not have been const -- only clear mMayBeConst if we had
  14084. // all-const args
  14085. if (wasAllConst)
  14086. {
  14087. methodInst->mMayBeConst = false;
  14088. }
  14089. }
  14090. return constValue;
  14091. }
  14092. BfTypedValue BfModule::CallBaseCtorCalc(bool constOnly)
  14093. {
  14094. // Any errors should only be shown in the actual CTOR call
  14095. SetAndRestoreValue<bool> prevIgnoreWrites(mIgnoreErrors, true);
  14096. auto methodDef = mCurMethodInstance->mMethodDef;
  14097. BF_ASSERT((methodDef->mMethodType == BfMethodType_Ctor) || (methodDef->mMethodType == BfMethodType_CtorCalcAppend));
  14098. auto ctorDeclaration = (BfConstructorDeclaration*)methodDef->mMethodDeclaration;
  14099. BfCustomAttributes* customAttributes = NULL;
  14100. defer(delete customAttributes);
  14101. BfInvocationExpression* ctorInvocation = NULL;
  14102. if (ctorDeclaration != NULL)
  14103. {
  14104. ctorInvocation = BfNodeDynCast<BfInvocationExpression>(ctorDeclaration->mInitializer);
  14105. if (auto attributedExpr = BfNodeDynCast<BfAttributedExpression>(ctorDeclaration->mInitializer))
  14106. {
  14107. ctorInvocation = BfNodeDynCast<BfInvocationExpression>(attributedExpr->mExpression);
  14108. customAttributes = GetCustomAttributes(attributedExpr->mAttributes, BfAttributeTargets_MemberAccess);
  14109. }
  14110. }
  14111. BfTypeInstance* targetType = NULL;
  14112. if (ctorInvocation != NULL)
  14113. {
  14114. auto targetToken = BfNodeDynCast<BfTokenNode>(ctorInvocation->mTarget);
  14115. targetType = (targetToken->GetToken() == BfToken_This) ? mCurTypeInstance : mCurTypeInstance->mBaseType;
  14116. }
  14117. else
  14118. targetType = mCurTypeInstance->mBaseType;
  14119. if ((targetType == NULL) || (targetType == mContext->mBfObjectType))
  14120. return NULL;
  14121. auto targetRefNode = methodDef->GetRefNode();
  14122. BfType* targetThisType = targetType;
  14123. BfTypedValue target(mBfIRBuilder->GetFakeVal(), targetThisType);
  14124. BfExprEvaluator exprEvaluator(this);
  14125. BfResolvedArgs argValues;
  14126. if ((ctorDeclaration != NULL) && (ctorInvocation != NULL))
  14127. {
  14128. argValues.Init(&ctorInvocation->mArguments);
  14129. }
  14130. //
  14131. {
  14132. }
  14133. BfFunctionBindResult bindResult;
  14134. bindResult.mSkipThis = true;
  14135. bindResult.mWantsArgs = true;
  14136. {
  14137. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, true);
  14138. exprEvaluator.ResolveArgValues(argValues, BfResolveArgsFlag_DeferParamEval);
  14139. SetAndRestoreValue<BfFunctionBindResult*> prevBindResult(exprEvaluator.mFunctionBindResult, &bindResult);
  14140. exprEvaluator.MatchConstructor(targetRefNode, NULL, target, targetType, argValues, true, true);
  14141. }
  14142. if (bindResult.mMethodInstance == NULL)
  14143. {
  14144. AssertErrorState();
  14145. return BfTypedValue();
  14146. }
  14147. if (!bindResult.mMethodInstance->mMethodDef->mHasAppend)
  14148. {
  14149. return BfTypedValue();
  14150. }
  14151. BF_ASSERT(bindResult.mIRArgs[0].IsFake());
  14152. bindResult.mIRArgs.RemoveAt(0);
  14153. auto calcAppendMethodModule = GetMethodInstanceAtIdx(bindResult.mMethodInstance->GetOwner(), bindResult.mMethodInstance->mMethodDef->mIdx + 1, BF_METHODNAME_CALCAPPEND);
  14154. BfTypedValue appendSizeTypedValue = TryConstCalcAppend(calcAppendMethodModule.mMethodInstance, bindResult.mIRArgs);
  14155. BF_ASSERT(calcAppendMethodModule.mMethodInstance->mAppendAllocAlign >= 0);
  14156. mCurMethodInstance->mAppendAllocAlign = BF_MAX((int)mCurMethodInstance->mAppendAllocAlign, calcAppendMethodModule.mMethodInstance->mAppendAllocAlign);
  14157. BF_ASSERT(calcAppendMethodModule.mMethodInstance->mEndingAppendAllocAlign > -1);
  14158. mCurMethodState->mCurAppendAlign = BF_MAX(calcAppendMethodModule.mMethodInstance->mEndingAppendAllocAlign, 0);
  14159. if (appendSizeTypedValue)
  14160. return appendSizeTypedValue;
  14161. if (constOnly)
  14162. return BfTypedValue(mBfIRBuilder->GetFakeVal(), GetPrimitiveType(BfTypeCode_IntPtr));
  14163. bool needsRecalc = false;
  14164. for (auto irArg : bindResult.mIRArgs)
  14165. {
  14166. if (irArg.IsFake())
  14167. needsRecalc = true;
  14168. }
  14169. auto calcAppendArgs = bindResult.mIRArgs;
  14170. if (needsRecalc)
  14171. {
  14172. // Do it again, but without mIgnoreWrites set
  14173. BfResolvedArgs argValues;
  14174. argValues.Init(&ctorInvocation->mArguments);
  14175. exprEvaluator.ResolveArgValues(argValues, BfResolveArgsFlag_DeferParamEval);
  14176. BfFunctionBindResult bindResult;
  14177. bindResult.mSkipThis = true;
  14178. bindResult.mWantsArgs = true;
  14179. SetAndRestoreValue<BfFunctionBindResult*> prevBindResult(exprEvaluator.mFunctionBindResult, &bindResult);
  14180. exprEvaluator.MatchConstructor(targetRefNode, NULL, target, targetType, argValues, true, true);
  14181. BF_ASSERT(bindResult.mIRArgs[0].IsFake());
  14182. bindResult.mIRArgs.RemoveAt(0);
  14183. calcAppendArgs = bindResult.mIRArgs;
  14184. }
  14185. BF_ASSERT(calcAppendMethodModule.mFunc);
  14186. appendSizeTypedValue = exprEvaluator.CreateCall(NULL, calcAppendMethodModule.mMethodInstance, calcAppendMethodModule.mFunc, false, calcAppendArgs);
  14187. BF_ASSERT(appendSizeTypedValue.mType == GetPrimitiveType(BfTypeCode_IntPtr));
  14188. return appendSizeTypedValue;
  14189. }
  14190. // This method never throws errors - it relies on the proper ctor actually throwing the errors
  14191. void BfModule::EmitCtorCalcAppend()
  14192. {
  14193. if ((mCompiler->mIsResolveOnly) && (!mIsComptimeModule))
  14194. return;
  14195. auto methodDef = mCurMethodInstance->mMethodDef;
  14196. auto methodDecl = methodDef->GetMethodDeclaration();
  14197. Array<BfAstNode*> deferredNodeList;
  14198. auto methodDeclBlock = BfNodeDynCast<BfBlock>(methodDecl->mBody);
  14199. if (methodDeclBlock == NULL)
  14200. return;
  14201. AppendAllocVisitor appendAllocVisitor;
  14202. auto baseCalcAppend = CallBaseCtorCalc(false);
  14203. if (baseCalcAppend)
  14204. {
  14205. mBfIRBuilder->CreateStore(baseCalcAppend.mValue, mCurMethodState->mRetVal.mValue);
  14206. }
  14207. appendAllocVisitor.mModule = this;
  14208. appendAllocVisitor.VisitChild(methodDecl->mBody);
  14209. }
  14210. void BfModule::CreateStaticCtor()
  14211. {
  14212. auto typeDef = mCurTypeInstance->mTypeDef;
  14213. auto methodDef = mCurMethodInstance->mMethodDef;
  14214. BfIRBlock exitBB;
  14215. if ((HasCompiledOutput()) && (!mCurMethodInstance->mIsUnspecialized) && (mCurMethodInstance->mChainType != BfMethodChainType_ChainMember))
  14216. {
  14217. auto boolType = GetPrimitiveType(BfTypeCode_Boolean);
  14218. auto didStaticInitVarAddr = mBfIRBuilder->CreateGlobalVariable(
  14219. mBfIRBuilder->MapType(boolType),
  14220. false,
  14221. BfIRLinkageType_Internal,
  14222. GetDefaultValue(boolType),
  14223. "didStaticInit");
  14224. auto initBB = mBfIRBuilder->CreateBlock("init", true);
  14225. mCurMethodState->mIRExitBlock = mBfIRBuilder->CreateBlock("exit", true);
  14226. auto didStaticInitVar = mBfIRBuilder->CreateLoad(didStaticInitVarAddr);
  14227. mBfIRBuilder->CreateCondBr(didStaticInitVar, mCurMethodState->mIRExitBlock, initBB);
  14228. mBfIRBuilder->SetInsertPoint(initBB);
  14229. mBfIRBuilder->CreateStore(GetConstValue(1, boolType), didStaticInitVarAddr);
  14230. }
  14231. // Do DLL imports
  14232. if (!mDllImportEntries.empty())
  14233. {
  14234. auto internalType = ResolveTypeDef(mCompiler->mInternalTypeDef);
  14235. PopulateType(internalType);
  14236. auto getSharedProcAddressInstance = GetMethodByName(internalType->ToTypeInstance(), "GetSharedProcAddress");
  14237. if (!getSharedProcAddressInstance)
  14238. {
  14239. if (!mCompiler->mPassInstance->HasFailed())
  14240. Fail("Internal error: System.Internal doesn't contain LoadSharedLibrary method");
  14241. }
  14242. }
  14243. // Fill in initializer values
  14244. if ((!mCompiler->mIsResolveOnly) || (mCompiler->mResolvePassData->mAutoComplete == NULL))
  14245. {
  14246. for (auto fieldDef : typeDef->mFields)
  14247. {
  14248. if ((!fieldDef->mIsConst) && (fieldDef->mIsStatic) && (fieldDef->mInitializer != NULL))
  14249. {
  14250. // For extensions, only handle these fields in the appropriate extension
  14251. if ((fieldDef->mDeclaringType->mTypeDeclaration != methodDef->mDeclaringType->mTypeDeclaration))
  14252. continue;
  14253. UpdateSrcPos(fieldDef->mInitializer);
  14254. auto fieldInst = &mCurTypeInstance->mFieldInstances[fieldDef->mIdx];
  14255. if (!fieldInst->mFieldIncluded)
  14256. continue;
  14257. if (fieldInst->mResolvedType->IsVar())
  14258. {
  14259. continue;
  14260. }
  14261. GetFieldInitializerValue(fieldInst, NULL, NULL, NULL, true);
  14262. }
  14263. }
  14264. auto _CheckInitBlock = [&](BfAstNode* node)
  14265. {
  14266. };
  14267. EmitInitBlocks(_CheckInitBlock);
  14268. }
  14269. else
  14270. {
  14271. for (auto tempTypeDef : mCompiler->mResolvePassData->mAutoCompleteTempTypes)
  14272. {
  14273. if (tempTypeDef->mFullName == typeDef->mFullName)
  14274. {
  14275. for (auto fieldDef : tempTypeDef->mFields)
  14276. {
  14277. if ((fieldDef->mIsStatic) && (!fieldDef->mIsConst))
  14278. {
  14279. if (fieldDef->mInitializer != NULL)
  14280. {
  14281. if (mCompiler->mResolvePassData->mSourceClassifier != NULL)
  14282. {
  14283. mCompiler->mResolvePassData->mSourceClassifier->SetElementType(fieldDef->mInitializer, BfSourceElementType_Normal);
  14284. mCompiler->mResolvePassData->mSourceClassifier->VisitChild(fieldDef->mInitializer);
  14285. }
  14286. BfType* wantType = NULL;
  14287. if ((!BfNodeIsA<BfVarTypeReference>(fieldDef->mTypeRef)) && (!BfNodeIsA<BfLetTypeReference>(fieldDef->mTypeRef)))
  14288. {
  14289. wantType = ResolveTypeRef(fieldDef->mTypeRef, BfPopulateType_Identity, BfResolveTypeRefFlag_AllowInferredSizedArray);
  14290. }
  14291. CreateValueFromExpression(fieldDef->mInitializer, wantType, BfEvalExprFlags_FieldInitializer);
  14292. }
  14293. }
  14294. }
  14295. }
  14296. }
  14297. }
  14298. if (mCurMethodInstance->mChainType == BfMethodChainType_ChainHead)
  14299. CallChainedMethods(mCurMethodInstance, false);
  14300. }
  14301. void BfModule::EmitDtorBody()
  14302. {
  14303. if (!mCurMethodState->mIRExitBlock)
  14304. mCurMethodState->mIRExitBlock = mBfIRBuilder->CreateBlock("exit", true);
  14305. if (mCurTypeInstance->IsClosure())
  14306. {
  14307. BfFieldInstance* fieldInstance = &mCurTypeInstance->mFieldInstances.back();
  14308. BF_ASSERT(fieldInstance->GetFieldDef()->mName == "__dtorThunk");
  14309. auto thisVal = GetThis();
  14310. auto dtorThunkPtr = mBfIRBuilder->CreateInBoundsGEP(thisVal.mValue, 0, fieldInstance->mDataIdx);
  14311. auto dtorThunk = mBfIRBuilder->CreateLoad(dtorThunkPtr);
  14312. auto funcPtrType = mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapMethod(mCurMethodInstance));
  14313. auto dtorPtr = mBfIRBuilder->CreateBitCast(dtorThunk, funcPtrType);
  14314. SizedArray<BfIRValue, 1> args;
  14315. args.push_back(thisVal.mValue);
  14316. auto result = mBfIRBuilder->CreateCall(dtorPtr, args);
  14317. mBfIRBuilder->SetCallCallingConv(result, BfIRCallingConv_CDecl);
  14318. // Fall through to Object::~this call
  14319. auto dtorFunc = GetMethodByName(mContext->mBfObjectType, "~this");
  14320. if (mIsComptimeModule)
  14321. mCompiler->mCEMachine->QueueMethod(dtorFunc.mMethodInstance, dtorFunc.mFunc);
  14322. auto basePtr = mBfIRBuilder->CreateBitCast(thisVal.mValue, mBfIRBuilder->MapTypeInstPtr(mContext->mBfObjectType));
  14323. SizedArray<BfIRValue, 1> vals = { basePtr };
  14324. result = mBfIRBuilder->CreateCall(dtorFunc.mFunc, vals);
  14325. mBfIRBuilder->SetCallCallingConv(result, GetIRCallingConvention(dtorFunc.mMethodInstance));
  14326. mBfIRBuilder->SetTailCall(result);
  14327. return;
  14328. }
  14329. auto typeDef = mCurTypeInstance->mTypeDef;
  14330. auto methodDef = mCurMethodInstance->mMethodDef;
  14331. auto methodDeclaration = methodDef->GetMethodDeclaration();
  14332. if (mCurMethodInstance->mChainType == BfMethodChainType_ChainHead)
  14333. CallChainedMethods(mCurMethodInstance, true);
  14334. if (auto bodyBlock = BfNodeDynCast<BfBlock>(methodDef->mBody))
  14335. {
  14336. VisitEmbeddedStatement(bodyBlock);
  14337. if (bodyBlock->mCloseBrace != NULL)
  14338. {
  14339. UpdateSrcPos(bodyBlock->mCloseBrace);
  14340. }
  14341. }
  14342. else
  14343. {
  14344. if (methodDeclaration != NULL)
  14345. UpdateSrcPos(methodDeclaration);
  14346. else if ((methodDef->mDeclaringType != NULL) && (methodDef->mDeclaringType->GetRefNode() != NULL))
  14347. UpdateSrcPos(methodDef->mDeclaringType->GetRefNode());
  14348. else if (typeDef->mTypeDeclaration != NULL)
  14349. UpdateSrcPos(typeDef->mTypeDeclaration);
  14350. if ((methodDeclaration != NULL) && (methodDeclaration->mFatArrowToken != NULL))
  14351. {
  14352. Fail("Destructors cannot have expression bodies", methodDeclaration->mFatArrowToken, true);
  14353. }
  14354. }
  14355. if ((!mCompiler->mIsResolveOnly) || (mCompiler->mResolvePassData->mAutoComplete == NULL))
  14356. {
  14357. for (int fieldIdx = (int)mCurTypeInstance->mFieldInstances.size() - 1; fieldIdx >= 0; fieldIdx--)
  14358. {
  14359. auto fieldInst = &mCurTypeInstance->mFieldInstances[fieldIdx];
  14360. auto fieldDef = fieldInst->GetFieldDef();
  14361. if ((fieldDef != NULL) && (fieldDef->mIsStatic == methodDef->mIsStatic) && (fieldDef->mFieldDeclaration != NULL) && (fieldDef->mFieldDeclaration->mFieldDtor != NULL))
  14362. {
  14363. if (fieldDef->mDeclaringType != mCurMethodInstance->mMethodDef->mDeclaringType)
  14364. {
  14365. BF_ASSERT(mCurTypeInstance->mTypeDef->mIsCombinedPartial);
  14366. continue;
  14367. }
  14368. if ((!methodDef->mIsStatic) && (mCurTypeInstance->IsValueType()))
  14369. {
  14370. Fail("Structs cannot have field destructors", fieldDef->mFieldDeclaration->mFieldDtor->mTildeToken, true);
  14371. }
  14372. SetAndRestoreValue<BfFilePosition> prevFilePos(mCurFilePosition);
  14373. auto fieldDtor = fieldDef->mFieldDeclaration->mFieldDtor;
  14374. if ((fieldDef->mIsStatic) != (methodDef->mIsStatic))
  14375. continue;
  14376. UpdateSrcPos(fieldDtor);
  14377. BfScopeData scopeData;
  14378. mCurMethodState->AddScope(&scopeData);
  14379. NewScopeState();
  14380. UpdateSrcPos(fieldDtor);
  14381. bool hasDbgInfo = (!fieldDef->mIsConst);
  14382. if (hasDbgInfo)
  14383. {
  14384. mBfIRBuilder->SaveDebugLocation();
  14385. mBfIRBuilder->ClearDebugLocation();
  14386. }
  14387. BfIRValue value;
  14388. if (fieldDef->mIsStatic)
  14389. {
  14390. value = ReferenceStaticField(fieldInst).mValue;
  14391. }
  14392. else
  14393. {
  14394. if (fieldInst->mResolvedType->IsValuelessType())
  14395. {
  14396. value = mBfIRBuilder->GetFakeVal();
  14397. }
  14398. else if (!mCurTypeInstance->IsValueType())
  14399. {
  14400. auto thisValue = GetThis();
  14401. value = mBfIRBuilder->CreateInBoundsGEP(thisValue.mValue, 0, fieldInst->mDataIdx);
  14402. }
  14403. else
  14404. {
  14405. AssertErrorState();
  14406. value = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(fieldInst->mResolvedType));
  14407. }
  14408. }
  14409. BfIRValue staticVal;
  14410. if (hasDbgInfo)
  14411. {
  14412. BfIRValue dbgShowValue = value;
  14413. BfLocalVariable* localDef = new BfLocalVariable();
  14414. localDef->mName = "_";
  14415. localDef->mResolvedType = fieldInst->mResolvedType;
  14416. localDef->mAddr = value;
  14417. if ((mBfIRBuilder->DbgHasInfo()) && (!IsTargetingBeefBackend()))
  14418. {
  14419. // Create another pointer indirection, a ref to the gep
  14420. auto refFieldType = CreateRefType(fieldInst->mResolvedType);
  14421. auto allocaInst = CreateAlloca(refFieldType);
  14422. auto storeResult = mBfIRBuilder->CreateStore(value, allocaInst);
  14423. localDef->mResolvedType = refFieldType;
  14424. localDef->mAddr = allocaInst;
  14425. }
  14426. mBfIRBuilder->RestoreDebugLocation();
  14427. auto defLocalVar = AddLocalVariableDef(localDef, true);
  14428. // Put back so we actually modify the correct value*/
  14429. defLocalVar->mResolvedType = fieldInst->mResolvedType;
  14430. defLocalVar->mAddr = value;
  14431. }
  14432. while (fieldDtor != NULL)
  14433. {
  14434. if (mCompiler->WantsClassifyNode(fieldDtor))
  14435. {
  14436. mCompiler->mResolvePassData->mSourceClassifier->SetElementType(fieldDtor, BfSourceElementType_Normal);
  14437. mCompiler->mResolvePassData->mSourceClassifier->VisitChild(fieldDtor);
  14438. }
  14439. UpdateSrcPos(fieldDtor);
  14440. VisitEmbeddedStatement(fieldDtor->mBody);
  14441. fieldDtor = fieldDtor->mNextFieldDtor;
  14442. }
  14443. RestoreScopeState();
  14444. }
  14445. }
  14446. if ((!methodDef->mIsStatic) && (mCurMethodInstance->mChainType != BfMethodChainType_ChainMember))
  14447. {
  14448. auto checkBaseType = mCurTypeInstance->mBaseType;
  14449. while (checkBaseType != NULL)
  14450. {
  14451. if (auto bodyBlock = BfNodeDynCast<BfBlock>(methodDef->mBody))
  14452. {
  14453. if (bodyBlock->mCloseBrace != NULL)
  14454. UpdateSrcPos(bodyBlock->mCloseBrace);
  14455. }
  14456. else
  14457. {
  14458. UpdateSrcPos(typeDef->mTypeDeclaration->mNameNode);
  14459. }
  14460. BfMethodDef* dtorMethodDef = checkBaseType->mTypeDef->GetMethodByName("~this");
  14461. if (dtorMethodDef != NULL)
  14462. {
  14463. auto dtorMethodInstance = GetMethodInstance(checkBaseType, dtorMethodDef, BfTypeVector());
  14464. if (IsSkippingExtraResolveChecks())
  14465. {
  14466. // Nothing
  14467. }
  14468. else if (dtorMethodInstance.mMethodInstance->GetParamCount() == 0)
  14469. {
  14470. if ((!IsSkippingExtraResolveChecks()) && (!checkBaseType->IsUnspecializedType()))
  14471. {
  14472. auto basePtr = mBfIRBuilder->CreateBitCast(mCurMethodState->mLocals[0]->mValue, mBfIRBuilder->MapTypeInstPtr(checkBaseType));
  14473. SizedArray<BfIRValue, 1> vals = { basePtr };
  14474. auto callInst = mBfIRBuilder->CreateCall(dtorMethodInstance.mFunc, vals);
  14475. if (mIsComptimeModule)
  14476. mCompiler->mCEMachine->QueueMethod(dtorMethodInstance.mMethodInstance, dtorMethodInstance.mFunc);
  14477. mBfIRBuilder->SetCallCallingConv(callInst, GetIRCallingConvention(dtorMethodInstance.mMethodInstance));
  14478. }
  14479. }
  14480. else
  14481. {
  14482. // Invalid base dtor declaration
  14483. AssertErrorState();
  14484. }
  14485. break;
  14486. }
  14487. checkBaseType = checkBaseType->mBaseType;
  14488. }
  14489. }
  14490. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  14491. }
  14492. else
  14493. {
  14494. // The reason we can't just do the 'normal' path for this is that the BfTypeInstance here is NOT the
  14495. // autocomplete type instance, so FieldInstance initializer values contain expressions from the full
  14496. // resolve pass, NOT the autocomplete expression
  14497. for (auto tempTypeDef : mCompiler->mResolvePassData->mAutoCompleteTempTypes)
  14498. {
  14499. if (tempTypeDef->mFullName == typeDef->mFullName)
  14500. {
  14501. for (auto fieldDef : tempTypeDef->mFields)
  14502. {
  14503. if ((fieldDef->mIsStatic == methodDef->mIsStatic) && (fieldDef->mFieldDeclaration != NULL) &&
  14504. (fieldDef->mFieldDeclaration->mFieldDtor != NULL) && (mCompiler->mResolvePassData->mSourceClassifier != NULL))
  14505. {
  14506. BfType* fieldType = NULL;
  14507. for (int curFieldIdx = 0; curFieldIdx < (int)mCurTypeInstance->mFieldInstances.size(); curFieldIdx++)
  14508. {
  14509. auto curFieldInstance = &mCurTypeInstance->mFieldInstances[curFieldIdx];
  14510. auto curFieldDef = curFieldInstance->GetFieldDef();
  14511. if ((curFieldDef != NULL) && (fieldDef->mName == curFieldDef->mName))
  14512. fieldType = curFieldInstance->GetResolvedType();
  14513. }
  14514. if (fieldType == NULL)
  14515. fieldType = GetPrimitiveType(BfTypeCode_Var);
  14516. auto fieldDtor = fieldDef->mFieldDeclaration->mFieldDtor;
  14517. BfScopeData scopeData;
  14518. mCurMethodState->AddScope(&scopeData);
  14519. NewScopeState();
  14520. // This is just for autocomplete, it doesn't matter that mAddr is incorrect
  14521. if (fieldType != NULL)
  14522. {
  14523. BfLocalVariable* localDef = new BfLocalVariable();
  14524. localDef->mName = "_";
  14525. localDef->mResolvedType = fieldType;
  14526. localDef->mAddr = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(fieldType));
  14527. localDef->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  14528. AddLocalVariableDef(localDef);
  14529. }
  14530. while (fieldDtor != NULL)
  14531. {
  14532. mCompiler->mResolvePassData->mSourceClassifier->SetElementType(fieldDtor, BfSourceElementType_Normal);
  14533. mCompiler->mResolvePassData->mSourceClassifier->VisitChild(fieldDtor);
  14534. UpdateSrcPos(fieldDtor);
  14535. VisitEmbeddedStatement(fieldDtor->mBody);
  14536. fieldDtor = fieldDtor->mNextFieldDtor;
  14537. }
  14538. RestoreScopeState();
  14539. }
  14540. }
  14541. }
  14542. }
  14543. }
  14544. }
  14545. BfIRValue BfModule::CreateDllImportGlobalVar(BfMethodInstance* methodInstance, bool define)
  14546. {
  14547. BF_ASSERT(methodInstance->mIsReified);
  14548. auto typeInstance = methodInstance->GetOwner();
  14549. bool foundDllImportAttr = false;
  14550. BfCallingConvention callingConvention = methodInstance->mCallingConvention;
  14551. for (auto customAttr : methodInstance->GetCustomAttributes()->mAttributes)
  14552. {
  14553. if (customAttr.mType->mTypeDef->mFullName.ToString() == "System.ImportAttribute")
  14554. {
  14555. foundDllImportAttr = true;
  14556. }
  14557. }
  14558. if (!foundDllImportAttr)
  14559. {
  14560. AssertErrorState();
  14561. return BfIRValue();
  14562. }
  14563. String name = "bf_hs_preserve@";
  14564. BfMangler::Mangle(name, mCompiler->GetMangleKind(), methodInstance);
  14565. name += "__imp";
  14566. BfIRType returnType;
  14567. SizedArray<BfIRType, 8> paramTypes;
  14568. methodInstance->GetIRFunctionInfo(this, returnType, paramTypes);
  14569. BfIRFunctionType externFunctionType = mBfIRBuilder->CreateFunctionType(returnType, paramTypes, methodInstance->IsVarArgs());
  14570. auto ptrType = mBfIRBuilder->GetPointerTo(externFunctionType);
  14571. BfIRValue initVal;
  14572. if (define)
  14573. {
  14574. if (methodInstance->GetImportCallKind() != BfImportCallKind_None)
  14575. initVal = mBfIRBuilder->CreateConstNull(ptrType);
  14576. }
  14577. auto globalVar = mBfIRBuilder->CreateGlobalVariable(ptrType, false, BfIRLinkageType_External, initVal, name);
  14578. if ((define) && (mBfIRBuilder->DbgHasInfo()))
  14579. {
  14580. auto voidType = GetPrimitiveType(BfTypeCode_None);
  14581. auto ptrType = CreatePointerType(voidType);
  14582. mBfIRBuilder->DbgCreateGlobalVariable(mDICompileUnit, name, name, BfIRMDNode(), 0, mBfIRBuilder->DbgGetType(ptrType), false, globalVar);
  14583. }
  14584. return globalVar;
  14585. }
  14586. void BfModule::CreateDllImportMethod()
  14587. {
  14588. if (mBfIRBuilder->mIgnoreWrites)
  14589. return;
  14590. auto globalVar = mFuncReferences[mCurMethodInstance];
  14591. if (!globalVar)
  14592. return;
  14593. bool allowTailCall = true;
  14594. mBfIRBuilder->ClearDebugLocation();
  14595. bool isHotCompile = mCompiler->IsHotCompile();
  14596. // If we are hot swapping, we need to have this stub because we may need to call the LoadSharedLibraries on demand
  14597. if (isHotCompile)
  14598. {
  14599. auto loadSharedLibsFunc = GetBuiltInFunc(BfBuiltInFuncType_LoadSharedLibraries);
  14600. mBfIRBuilder->CreateCall(loadSharedLibsFunc, SizedArray<BfIRValue, 0>());
  14601. }
  14602. auto callingConvention = GetIRCallingConvention(mCurMethodInstance);
  14603. BfIRType returnType;
  14604. SizedArray<BfIRType, 8> paramTypes;
  14605. mCurMethodInstance->GetIRFunctionInfo(this, returnType, paramTypes, mCurMethodInstance->IsVarArgs());
  14606. SizedArray<BfIRValue, 8> args;
  14607. for (int i = 0; i < (int)paramTypes.size(); i++)
  14608. args.push_back(mBfIRBuilder->GetArgument(i));
  14609. BfIRFunctionType externFunctionType = mBfIRBuilder->CreateFunctionType(returnType, paramTypes, mCurMethodInstance->IsVarArgs());
  14610. if (isHotCompile)
  14611. {
  14612. BfIRValue funcVal = mBfIRBuilder->CreateLoad(globalVar);
  14613. auto result = mBfIRBuilder->CreateCall(funcVal, args);
  14614. if (callingConvention == BfIRCallingConv_StdCall)
  14615. mBfIRBuilder->SetCallCallingConv(result, BfIRCallingConv_StdCall);
  14616. else if (callingConvention == BfIRCallingConv_FastCall)
  14617. mBfIRBuilder->SetCallCallingConv(result, BfIRCallingConv_FastCall);
  14618. else
  14619. mBfIRBuilder->SetCallCallingConv(result, BfIRCallingConv_CDecl);
  14620. if (allowTailCall)
  14621. mBfIRBuilder->SetTailCall(result);
  14622. CreateReturn(result);
  14623. mCurMethodState->mHadReturn = true;
  14624. }
  14625. if (HasCompiledOutput())
  14626. {
  14627. BfDllImportEntry dllImportEntry;
  14628. dllImportEntry.mFuncVar = globalVar;
  14629. dllImportEntry.mMethodInstance = mCurMethodInstance;
  14630. mDllImportEntries.push_back(dllImportEntry);
  14631. }
  14632. }
  14633. BfIRCallingConv BfModule::GetIRCallingConvention(BfMethodInstance* methodInstance)
  14634. {
  14635. auto methodDef = methodInstance->mMethodDef;
  14636. BfTypeInstance* owner = NULL;
  14637. if (!methodDef->mIsStatic)
  14638. owner = methodInstance->GetThisType()->ToTypeInstance();
  14639. if (owner == NULL)
  14640. owner = methodInstance->GetOwner();
  14641. if ((mCompiler->mOptions.mMachineType != BfMachineType_x86) || (mCompiler->mOptions.mPlatformType != BfPlatformType_Windows))
  14642. return BfIRCallingConv_CDecl;
  14643. if (methodInstance->mCallingConvention == BfCallingConvention_Stdcall)
  14644. return BfIRCallingConv_StdCall;
  14645. if (methodInstance->mCallingConvention == BfCallingConvention_Fastcall)
  14646. return BfIRCallingConv_FastCall;
  14647. if (!methodDef->mIsStatic)
  14648. {
  14649. if (owner->mIsCRepr)
  14650. return BfIRCallingConv_ThisCall;
  14651. if ((!owner->IsValuelessType()) &&
  14652. ((!owner->IsSplattable()) || (methodDef->HasNoThisSplat())))
  14653. return BfIRCallingConv_ThisCall;
  14654. }
  14655. return BfIRCallingConv_CDecl;
  14656. //return GetIRCallingConvention(owner, methodInstance->mMethodDef);
  14657. }
  14658. void BfModule::SetupIRMethod(BfMethodInstance* methodInstance, BfIRFunction func, bool isInlined)
  14659. {
  14660. BfMethodDef* methodDef = NULL;
  14661. if (methodInstance != NULL)
  14662. methodDef = methodInstance->mMethodDef;
  14663. if (!func)
  14664. return;
  14665. if (mCompiler->mOptions.mNoFramePointerElim)
  14666. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_NoFramePointerElim);
  14667. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_NoUnwind);
  14668. if (mSystem->mPtrSize == 8) // We need unwind info for debugging
  14669. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_UWTable);
  14670. if (methodInstance == NULL)
  14671. return;
  14672. if (methodInstance->mReturnType->IsVar())
  14673. mBfIRBuilder->Func_AddAttribute(func, -1, BfIRAttribute_VarRet);
  14674. if (methodDef->mImportKind == BfImportKind_Export)
  14675. {
  14676. if (methodDef->mDeclaringType->mProject->mTargetType != BfTargetType_BeefLib_StaticLib)
  14677. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_DllExport);
  14678. }
  14679. if (methodDef->mIsNoReturn)
  14680. mBfIRBuilder->Func_AddAttribute(func, -1, BfIRAttribute_NoReturn);
  14681. auto callingConv = GetIRCallingConvention(methodInstance);
  14682. if (callingConv != BfIRCallingConv_CDecl)
  14683. mBfIRBuilder->SetFuncCallingConv(func, callingConv);
  14684. if (isInlined)
  14685. {
  14686. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_AlwaysInline);
  14687. }
  14688. int argIdx = 0;
  14689. int paramIdx = 0;
  14690. if ((methodInstance->HasThis()) && (!methodDef->mHasExplicitThis))
  14691. paramIdx = -1;
  14692. int argCount = methodInstance->GetIRFunctionParamCount(this);
  14693. while (argIdx < argCount)
  14694. {
  14695. if ((!mIsComptimeModule) && (argIdx == methodInstance->GetStructRetIdx()))
  14696. {
  14697. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_NoAlias);
  14698. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_StructRet);
  14699. argIdx++;
  14700. continue;
  14701. }
  14702. bool isThis = (paramIdx == -1) || ((methodDef->mHasExplicitThis) && (paramIdx == 0));
  14703. while ((!isThis) && (methodInstance->IsParamSkipped(paramIdx)))
  14704. paramIdx++;
  14705. BfType* resolvedTypeRef = NULL;
  14706. BfType* resolvedTypeRef2 = NULL;
  14707. String paramName;
  14708. bool isSplattable = false;
  14709. bool tryLowering = !mIsComptimeModule;
  14710. if (isThis)
  14711. {
  14712. paramName = "this";
  14713. if (methodInstance->mIsClosure)
  14714. resolvedTypeRef = mCurMethodState->mClosureState->mClosureType;
  14715. else
  14716. resolvedTypeRef = methodInstance->GetThisType();
  14717. isSplattable = (!mIsComptimeModule) && (resolvedTypeRef->IsSplattable()) && (methodInstance->AllowsSplatting(-1));
  14718. tryLowering = (!mIsComptimeModule) && (methodInstance->AllowsSplatting(-1));
  14719. }
  14720. else
  14721. {
  14722. paramName = methodInstance->GetParamName(paramIdx);
  14723. resolvedTypeRef = methodInstance->GetParamType(paramIdx);
  14724. if (resolvedTypeRef->IsMethodRef())
  14725. isSplattable = true;
  14726. else if ((!mIsComptimeModule) && (resolvedTypeRef->IsSplattable()) && (methodInstance->AllowsSplatting(paramIdx)))
  14727. {
  14728. auto resolvedTypeInst = resolvedTypeRef->ToTypeInstance();
  14729. if ((resolvedTypeInst != NULL) && (resolvedTypeInst->mIsCRepr))
  14730. {
  14731. // crepr splat is always splattable
  14732. isSplattable = true;
  14733. }
  14734. else
  14735. {
  14736. auto resolvedTypeInst = resolvedTypeRef->ToTypeInstance();
  14737. if ((resolvedTypeInst != NULL) && (resolvedTypeInst->mIsCRepr))
  14738. isSplattable = true;
  14739. else if (resolvedTypeRef->GetSplatCount() + argIdx <= mCompiler->mOptions.mMaxSplatRegs)
  14740. isSplattable = true;
  14741. }
  14742. }
  14743. }
  14744. if (tryLowering)
  14745. {
  14746. BfTypeCode loweredTypeCode = BfTypeCode_None;
  14747. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  14748. if (resolvedTypeRef->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2))
  14749. {
  14750. mBfIRBuilder->Func_SetParamName(func, argIdx + 1, paramName + "__1");
  14751. argIdx++;
  14752. if (loweredTypeCode2 != BfTypeCode_None)
  14753. {
  14754. mBfIRBuilder->Func_SetParamName(func, argIdx + 1, paramName + "__2");
  14755. argIdx++;
  14756. }
  14757. paramIdx++;
  14758. continue;
  14759. }
  14760. }
  14761. auto _SetupParam = [&](const StringImpl& paramName, BfType* resolvedTypeRef)
  14762. {
  14763. mBfIRBuilder->Func_SetParamName(func, argIdx + 1, paramName);
  14764. int addDeref = -1;
  14765. if (resolvedTypeRef->IsRef())
  14766. {
  14767. auto refType = (BfRefType*)resolvedTypeRef;
  14768. auto elementType = refType->mElementType;
  14769. PopulateType(elementType, BfPopulateType_Data);
  14770. addDeref = elementType->mSize;
  14771. if ((addDeref <= 0) && (!elementType->IsValuelessType()) && (!elementType->IsOpaque()))
  14772. AssertErrorState();
  14773. }
  14774. if ((resolvedTypeRef->IsComposite()) && (!resolvedTypeRef->IsTypedPrimitive()))
  14775. {
  14776. if (isThis)
  14777. {
  14778. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_NoCapture);
  14779. PopulateType(resolvedTypeRef, BfPopulateType_Data);
  14780. addDeref = resolvedTypeRef->mSize;
  14781. }
  14782. else if (methodInstance->WantsStructsAttribByVal(resolvedTypeRef))
  14783. {
  14784. mBfIRBuilder->PopulateType(resolvedTypeRef, BfIRPopulateType_Full);
  14785. BF_ASSERT(resolvedTypeRef->mAlign > 0);
  14786. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_ByVal, mSystem->mPtrSize);
  14787. }
  14788. }
  14789. else if (resolvedTypeRef->IsPrimitiveType())
  14790. {
  14791. auto primType = (BfPrimitiveType*)resolvedTypeRef;
  14792. if (primType->mTypeDef->mTypeCode == BfTypeCode_Boolean)
  14793. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_ZExt);
  14794. }
  14795. if (addDeref >= 0)
  14796. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_Dereferencable, addDeref);
  14797. argIdx++;
  14798. };
  14799. if (isSplattable)
  14800. {
  14801. std::function<void(BfType*, const StringImpl&)> checkTypeLambda = [&](BfType* checkType, const StringImpl& curName)
  14802. {
  14803. if (checkType->IsStruct())
  14804. {
  14805. auto checkTypeInstance = checkType->ToTypeInstance();
  14806. if (checkTypeInstance->mBaseType != NULL)
  14807. checkTypeLambda(checkTypeInstance->mBaseType, curName);
  14808. if (checkTypeInstance->mIsUnion)
  14809. {
  14810. BfType* unionInnerType = checkTypeInstance->GetUnionInnerType();
  14811. checkTypeLambda(unionInnerType, curName + "_data");
  14812. }
  14813. else
  14814. {
  14815. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  14816. {
  14817. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  14818. auto fieldDef = fieldInstance->GetFieldDef();
  14819. if (fieldInstance->mDataIdx >= 0)
  14820. {
  14821. checkTypeLambda(fieldInstance->GetResolvedType(), curName + "_" + fieldInstance->GetFieldDef()->mName);
  14822. }
  14823. }
  14824. }
  14825. if (checkTypeInstance->IsEnum())
  14826. {
  14827. mBfIRBuilder->Func_SetParamName(func, argIdx + 1, curName + "_dscr");
  14828. argIdx++;
  14829. }
  14830. }
  14831. else if (checkType->IsMethodRef())
  14832. {
  14833. auto methodRefType = (BfMethodRefType*)checkType;
  14834. BfMethodInstance* methodRefMethodInst = methodRefType->mMethodRef;
  14835. for (int dataIdx = 0; dataIdx < (int)methodRefType->GetCaptureDataCount(); dataIdx++)
  14836. {
  14837. int methodRefParamIdx = methodRefType->GetParamIdxFromDataIdx(dataIdx);
  14838. if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  14839. {
  14840. checkTypeLambda(methodRefType->GetCaptureType(dataIdx), curName + "_" + methodRefMethodInst->GetParamName(methodRefParamIdx));
  14841. }
  14842. else
  14843. {
  14844. _SetupParam(curName + "_" + methodRefMethodInst->GetParamName(methodRefParamIdx), methodRefType->GetCaptureType(dataIdx));
  14845. }
  14846. }
  14847. }
  14848. else if (!checkType->IsValuelessType())
  14849. {
  14850. _SetupParam(curName, checkType);
  14851. }
  14852. };
  14853. checkTypeLambda(resolvedTypeRef, paramName);
  14854. paramIdx++;
  14855. continue;
  14856. }
  14857. _SetupParam(paramName, resolvedTypeRef);
  14858. if (resolvedTypeRef2 != NULL)
  14859. _SetupParam(paramName, resolvedTypeRef2);
  14860. paramIdx++;
  14861. }
  14862. }
  14863. void BfModule::EmitInitBlocks(const std::function<void(BfAstNode*)>& initBlockCallback)
  14864. {
  14865. auto methodDef = mCurMethodInstance->mMethodDef;
  14866. mCurTypeInstance->mTypeDef->PopulateMemberSets();
  14867. BfMemberSetEntry* entry = NULL;
  14868. BfMethodDef* initMethodDef = NULL;
  14869. mCurTypeInstance->mTypeDef->mMethodSet.TryGetWith(String("__BfInit"), &entry);
  14870. if (entry != NULL)
  14871. initMethodDef = (BfMethodDef*)entry->mMemberDef;
  14872. SizedArray<BfAstNode*, 8> initBodies;
  14873. for (; initMethodDef != NULL; initMethodDef = initMethodDef->mNextWithSameName)
  14874. {
  14875. if (initMethodDef->mDeclaringType->GetDefinition() != methodDef->mDeclaringType->GetDefinition())
  14876. continue;
  14877. if (initMethodDef->mMethodType != BfMethodType_Init)
  14878. continue;
  14879. if (initMethodDef->mIsStatic != methodDef->mIsStatic)
  14880. continue;
  14881. initBodies.Insert(0, initMethodDef->mBody);
  14882. }
  14883. for (auto body : initBodies)
  14884. {
  14885. initBlockCallback(body);
  14886. VisitEmbeddedStatement(body);
  14887. }
  14888. }
  14889. void BfModule::EmitCtorBody(bool& skipBody)
  14890. {
  14891. auto methodInstance = mCurMethodInstance;
  14892. auto methodDef = methodInstance->mMethodDef;
  14893. auto methodDeclaration = methodDef->mMethodDeclaration;
  14894. auto ctorDeclaration = (BfConstructorDeclaration*)methodDef->mMethodDeclaration;
  14895. auto typeDef = mCurTypeInstance->mTypeDef;
  14896. BfCustomAttributes* customAttributes = NULL;
  14897. defer(delete customAttributes);
  14898. BfInvocationExpression* ctorInvocation = NULL;
  14899. BfAttributeState attributeState;
  14900. attributeState.mTarget = BfAttributeTargets_MemberAccess;
  14901. if (ctorDeclaration != NULL)
  14902. {
  14903. ctorInvocation = BfNodeDynCast<BfInvocationExpression>(ctorDeclaration->mInitializer);
  14904. if (auto attributedExpr = BfNodeDynCast<BfAttributedExpression>(ctorDeclaration->mInitializer))
  14905. {
  14906. ctorInvocation = BfNodeDynCast<BfInvocationExpression>(attributedExpr->mExpression);
  14907. attributeState.mCustomAttributes = GetCustomAttributes(attributedExpr->mAttributes, attributeState.mTarget);
  14908. }
  14909. }
  14910. SetAndRestoreValue<BfAttributeState*> prevAttributeState(mAttributeState, &attributeState);
  14911. // Prologue
  14912. mBfIRBuilder->ClearDebugLocation();
  14913. bool hadThisInitializer = false;
  14914. if ((ctorDeclaration != NULL) && (ctorInvocation != NULL))
  14915. {
  14916. auto targetToken = BfNodeDynCast<BfTokenNode>(ctorInvocation->mTarget);
  14917. auto targetType = (targetToken->GetToken() == BfToken_This) ? mCurTypeInstance : mCurTypeInstance->mBaseType;
  14918. if (targetToken->GetToken() == BfToken_This)
  14919. {
  14920. hadThisInitializer = true;
  14921. // Since we call a 'this', it's that other ctor's responsibility to fully assign the fields
  14922. mCurMethodState->LocalDefined(GetThisVariable());
  14923. }
  14924. }
  14925. // Zero out memory for default ctor
  14926. if ((methodDeclaration == NULL) && (mCurTypeInstance->IsStruct()) && (methodInstance->mChainType != BfMethodChainType_ChainMember))
  14927. {
  14928. if (mCurTypeInstance->IsTypedPrimitive())
  14929. {
  14930. auto thisRef = mCurMethodState->mLocals[0]->mValue;
  14931. mBfIRBuilder->CreateStore(GetDefaultValue(mCurTypeInstance), thisRef);
  14932. }
  14933. else if (mCurTypeInstance->mInstSize > 0)
  14934. {
  14935. BfIRValue fillValue = GetConstValue8(0);
  14936. BfIRValue sizeValue = GetConstValue(mCurTypeInstance->mInstSize);
  14937. auto thisRef = mCurMethodState->mLocals[0]->mValue;
  14938. BfIRValue destBits = mBfIRBuilder->CreateBitCast(thisRef, mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr));
  14939. mBfIRBuilder->CreateMemSet(destBits, fillValue, sizeValue, mCurTypeInstance->mAlign);
  14940. }
  14941. }
  14942. BfAstNode* baseCtorNode = NULL;
  14943. if ((ctorDeclaration != NULL) && (ctorInvocation != NULL) && (ctorInvocation->mTarget != NULL))
  14944. baseCtorNode = ctorInvocation->mTarget;
  14945. else if (methodDef->mBody != NULL)
  14946. baseCtorNode = methodDef->mBody;
  14947. else if (ctorDeclaration != NULL)
  14948. baseCtorNode = ctorDeclaration;
  14949. else if ((methodDef->mDeclaringType != NULL) && (methodDef->mDeclaringType->GetRefNode() != NULL))
  14950. baseCtorNode = methodDef->mDeclaringType->GetRefNode();
  14951. else if (mCurTypeInstance->mTypeDef->mTypeDeclaration != NULL)
  14952. baseCtorNode = mCurTypeInstance->mTypeDef->mTypeDeclaration->mNameNode;
  14953. else if ((mCurTypeInstance->mBaseType != NULL) && (mCurTypeInstance->mBaseType->mTypeDef->mTypeDeclaration != NULL))
  14954. baseCtorNode = mCurTypeInstance->mBaseType->mTypeDef->mTypeDeclaration;
  14955. else
  14956. baseCtorNode = mContext->mBfObjectType->mTypeDef->mTypeDeclaration;
  14957. bool calledCtorNoBody = false;
  14958. if ((mCurTypeInstance->IsTypedPrimitive()) && (!mCurTypeInstance->IsValuelessType()))
  14959. {
  14960. // Zero out typed primitives in ctor
  14961. mBfIRBuilder->CreateStore(GetDefaultValue(mCurTypeInstance->GetUnderlyingType()), mBfIRBuilder->GetArgument(0));
  14962. }
  14963. if ((!mCurTypeInstance->IsBoxed()) && (methodDef->mMethodType == BfMethodType_Ctor) && (!hadThisInitializer))
  14964. {
  14965. // Call the root type's default ctor (with no body) to initialize its fields and call the chained ctors
  14966. if (mCurTypeInstance->mTypeDef->mHasCtorNoBody)
  14967. {
  14968. BfMethodDef* defaultCtor = NULL;
  14969. for (auto methodDef : mCurTypeInstance->mTypeDef->mMethods)
  14970. {
  14971. if ((methodDef->mMethodType == BfMethodType_CtorNoBody) && (methodDef->mDeclaringType->mTypeCode != BfTypeCode_Extension))
  14972. {
  14973. defaultCtor = methodDef;
  14974. }
  14975. }
  14976. if (defaultCtor != NULL)
  14977. {
  14978. UpdateSrcPos(mCurTypeInstance->mTypeDef->GetRefNode());
  14979. SetIllegalSrcPos();
  14980. auto moduleMethodInstance = GetMethodInstance(mCurTypeInstance, defaultCtor, BfTypeVector());
  14981. BfExprEvaluator exprEvaluator(this);
  14982. SizedArray<BfIRValue, 1> irArgs;
  14983. exprEvaluator.PushThis(NULL, GetThis(), moduleMethodInstance.mMethodInstance, irArgs);
  14984. exprEvaluator.CreateCall(NULL, moduleMethodInstance.mMethodInstance, moduleMethodInstance.mFunc, false, irArgs);
  14985. if (mIsComptimeModule)
  14986. mCompiler->mCEMachine->QueueMethod(moduleMethodInstance);
  14987. calledCtorNoBody = true;
  14988. }
  14989. }
  14990. }
  14991. // Initialize fields (if applicable)
  14992. if (mCurTypeInstance->IsBoxed())
  14993. {
  14994. skipBody = true;
  14995. }
  14996. else if ((methodDef->mMethodType == BfMethodType_Ctor) && (methodDef->mDeclaringType->mTypeCode == BfTypeCode_Extension))
  14997. {
  14998. // Field initializers occur in CtorNoBody methods for extensions
  14999. }
  15000. else if (!hadThisInitializer)
  15001. {
  15002. // If we had a 'this' initializer, that other ctor will have initialized our fields
  15003. //auto
  15004. if ((!mCompiler->mIsResolveOnly) ||
  15005. (mCompiler->mResolvePassData->mAutoComplete == NULL) ||
  15006. (mCompiler->mResolvePassData->mAutoComplete->mResolveType == BfResolveType_ShowFileSymbolReferences))
  15007. {
  15008. // If we calledCtorNoBody then we did the field initializer code, but we still need to run though it here
  15009. // to properly set the assigned flags
  15010. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, mBfIRBuilder->mIgnoreWrites || calledCtorNoBody);
  15011. bool hadInlineInitBlock = false;
  15012. BfScopeData scopeData;
  15013. scopeData.mInInitBlock = true;
  15014. auto _CheckInitBlock = [&](BfAstNode* node)
  15015. {
  15016. if (!hadInlineInitBlock)
  15017. {
  15018. if ((mBfIRBuilder->DbgHasInfo()) && (!mCurTypeInstance->IsUnspecializedType()) && (mHasFullDebugInfo))
  15019. {
  15020. UpdateSrcPos(baseCtorNode);
  15021. if (methodDef->mBody == NULL)
  15022. SetIllegalSrcPos();
  15023. // 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
  15024. EmitEnsureInstructionAt();
  15025. BfType* thisType = mCurTypeInstance;
  15026. if (thisType->IsValueType())
  15027. thisType = CreateRefType(thisType);
  15028. SizedArray<BfIRMDNode, 1> diParamTypes;
  15029. BfIRMDNode diFuncType = mBfIRBuilder->DbgCreateSubroutineType(diParamTypes);
  15030. mCurMethodState->AddScope(&scopeData);
  15031. NewScopeState();
  15032. int flags = 0;
  15033. mCurMethodState->mCurScope->mDIInlinedAt = mBfIRBuilder->DbgGetCurrentLocation();
  15034. BF_ASSERT(mCurMethodState->mCurScope->mDIInlinedAt);
  15035. // mCurMethodState->mCurScope->mDIInlinedAt may still be null ifwe don't have an explicit ctor
  15036. mCurMethodState->mCurScope->mDIScope = mBfIRBuilder->DbgCreateFunction(mBfIRBuilder->DbgGetTypeInst(mCurTypeInstance), "this$initFields", "", mCurFilePosition.mFileInstance->mDIFile,
  15037. mCurFilePosition.mCurLine + 1, diFuncType, false, true, mCurFilePosition.mCurLine + 1, flags, false, BfIRValue());
  15038. UpdateSrcPos(node);
  15039. auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(mCurMethodState->mCurScope->mDIScope,
  15040. "this", mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, mBfIRBuilder->DbgGetType(thisType));
  15041. //
  15042. {
  15043. auto loadedThis = GetThis();
  15044. // LLVM can't handle two variables pointing to the same value
  15045. BfIRValue copiedThisPtr;
  15046. copiedThisPtr = CreateAlloca(thisType);
  15047. auto storeInst = mBfIRBuilder->CreateStore(loadedThis.mValue, copiedThisPtr);
  15048. mBfIRBuilder->ClearDebugLocation(storeInst);
  15049. mBfIRBuilder->DbgInsertDeclare(copiedThisPtr, diVariable);
  15050. }
  15051. hadInlineInitBlock = true;
  15052. }
  15053. else
  15054. {
  15055. // Just do a simple one
  15056. mCurMethodState->AddScope(&scopeData);
  15057. NewScopeState();
  15058. hadInlineInitBlock = true;
  15059. }
  15060. }
  15061. UpdateSrcPos(node);
  15062. };
  15063. for (auto fieldDef : typeDef->mFields)
  15064. {
  15065. // For extensions, only handle these fields in the appropriate extension
  15066. if ((fieldDef->mDeclaringType->mTypeDeclaration != methodDef->mDeclaringType->mTypeDeclaration))
  15067. continue;
  15068. if ((!fieldDef->mIsConst) && (!fieldDef->mIsStatic))
  15069. {
  15070. auto fieldInst = &mCurTypeInstance->mFieldInstances[fieldDef->mIdx];
  15071. if (!fieldInst->mFieldIncluded)
  15072. continue;
  15073. if (fieldInst->mDataIdx < 0)
  15074. continue;
  15075. if (fieldDef->mInitializer == NULL)
  15076. {
  15077. continue;
  15078. // if (fieldDef->mProtection != BfProtection_Hidden)
  15079. // continue;
  15080. // if (mCurTypeInstance->IsObject()) // Already zeroed out
  15081. // continue;
  15082. }
  15083. if (fieldInst->mResolvedType == NULL)
  15084. {
  15085. BF_ASSERT(mHadBuildError);
  15086. continue;
  15087. }
  15088. if (fieldDef->mInitializer != NULL)
  15089. {
  15090. _CheckInitBlock(fieldDef->mInitializer);
  15091. }
  15092. BfIRValue fieldAddr;
  15093. if ((!mCurTypeInstance->IsTypedPrimitive()) && (!fieldInst->mResolvedType->IsVar()))
  15094. {
  15095. fieldAddr = mBfIRBuilder->CreateInBoundsGEP(mCurMethodState->mLocals[0]->mValue, 0, fieldInst->mDataIdx /*, fieldDef->mName*/);
  15096. }
  15097. else
  15098. {
  15099. // Failed
  15100. }
  15101. auto assignValue = GetFieldInitializerValue(fieldInst);
  15102. if (mCurTypeInstance->IsUnion())
  15103. {
  15104. auto fieldPtrType = CreatePointerType(fieldInst->mResolvedType);
  15105. fieldAddr = mBfIRBuilder->CreateBitCast(fieldAddr, mBfIRBuilder->MapType(fieldPtrType));
  15106. }
  15107. if ((fieldAddr) && (assignValue))
  15108. mBfIRBuilder->CreateStore(assignValue.mValue, fieldAddr);
  15109. }
  15110. }
  15111. EmitInitBlocks(_CheckInitBlock);
  15112. if (hadInlineInitBlock)
  15113. {
  15114. RestoreScopeState();
  15115. // This gets set to false because of AddScope but we actually are still in the head block
  15116. mCurMethodState->mInHeadScope = true;
  15117. // Make sure we emit a return even if we had a NoReturn call or return inside ourselves
  15118. mCurMethodState->mHadReturn = false;
  15119. mCurMethodState->mLeftBlockUncond = false;
  15120. }
  15121. }
  15122. else // Autocomplete case
  15123. {
  15124. BfScopeData scopeData;
  15125. scopeData.mInInitBlock = true;
  15126. mCurMethodState->AddScope(&scopeData);
  15127. NewScopeState();
  15128. // The reason we can't just do the 'normal' path for this is that the BfTypeInstance here is NOT the
  15129. // autocomplete type instance, so FieldInstance initializer values contain expressions from the full
  15130. // resolve pass, NOT the autocomplete expression
  15131. for (auto tempTypeDef : mCompiler->mResolvePassData->mAutoCompleteTempTypes)
  15132. {
  15133. if (tempTypeDef->mFullName == typeDef->mFullName)
  15134. {
  15135. for (auto fieldDef : tempTypeDef->mFields)
  15136. {
  15137. if ((!fieldDef->mIsStatic) && (fieldDef->mInitializer != NULL) && (mCompiler->mResolvePassData->mSourceClassifier != NULL))
  15138. {
  15139. mCompiler->mResolvePassData->mSourceClassifier->SetElementType(fieldDef->mInitializer, BfSourceElementType_Normal);
  15140. mCompiler->mResolvePassData->mSourceClassifier->VisitChild(fieldDef->mInitializer);
  15141. BfType* wantType = NULL;
  15142. if ((!BfNodeIsA<BfVarTypeReference>(fieldDef->mTypeRef)) &&
  15143. (!BfNodeIsA<BfLetTypeReference>(fieldDef->mTypeRef)))
  15144. wantType = ResolveTypeRef(fieldDef->mTypeRef, BfPopulateType_Declaration, BfResolveTypeRefFlag_AllowInferredSizedArray);
  15145. if ((wantType != NULL) &&
  15146. ((wantType->IsVar()) || (wantType->IsLet()) || (wantType->IsRef())))
  15147. wantType = NULL;
  15148. CreateValueFromExpression(fieldDef->mInitializer, wantType, BfEvalExprFlags_FieldInitializer);
  15149. }
  15150. }
  15151. tempTypeDef->PopulateMemberSets();
  15152. BfMemberSetEntry* entry = NULL;
  15153. BfMethodDef* initMethodDef = NULL;
  15154. tempTypeDef->mMethodSet.TryGetWith(String("__BfInit"), &entry);
  15155. if (entry != NULL)
  15156. initMethodDef = (BfMethodDef*)entry->mMemberDef;
  15157. SizedArray<BfAstNode*, 8> initBodies;
  15158. for (; initMethodDef != NULL; initMethodDef = initMethodDef->mNextWithSameName)
  15159. {
  15160. if (initMethodDef->mMethodType != BfMethodType_Init)
  15161. continue;
  15162. initBodies.Insert(0, initMethodDef->mBody);
  15163. }
  15164. for (auto body : initBodies)
  15165. VisitEmbeddedStatement(body);
  15166. }
  15167. }
  15168. // Mark fields from full type with initializers as initialized, to give proper initialization errors within ctor
  15169. for (auto fieldDef : typeDef->mFields)
  15170. {
  15171. if ((!fieldDef->mIsConst) && (!fieldDef->mIsStatic) && (fieldDef->mInitializer != NULL))
  15172. {
  15173. auto fieldInst = &mCurTypeInstance->mFieldInstances[fieldDef->mIdx];
  15174. if (fieldDef->mInitializer != NULL)
  15175. MarkFieldInitialized(fieldInst);
  15176. }
  15177. }
  15178. RestoreScopeState();
  15179. }
  15180. }
  15181. if (!methodInstance->mIsAutocompleteMethod)
  15182. {
  15183. if (auto autoDecl = BfNodeDynCast<BfAutoConstructorDeclaration>(methodDeclaration))
  15184. {
  15185. BfExprEvaluator exprEvaluator(this);
  15186. for (int paramIdx = 0; paramIdx < methodDef->mParams.mSize; paramIdx++)
  15187. {
  15188. auto paramDef = methodDef->mParams[paramIdx];
  15189. auto& fieldInstance = mCurTypeInstance->mFieldInstances[paramIdx];
  15190. BF_ASSERT(paramDef->mName == fieldInstance.GetFieldDef()->mName);
  15191. if (fieldInstance.mDataIdx < 0)
  15192. continue;
  15193. if (paramDef->mParamKind != BfParamKind_Normal)
  15194. continue;
  15195. auto localVar = mCurMethodState->mLocals[paramIdx + 1];
  15196. BF_ASSERT(localVar->mName == paramDef->mName);
  15197. auto localVal = exprEvaluator.LoadLocal(localVar);
  15198. localVal = LoadOrAggregateValue(localVal);
  15199. if (!localVal.mType->IsVar())
  15200. {
  15201. auto thisVal = GetThis();
  15202. auto fieldPtr = mBfIRBuilder->CreateInBoundsGEP(thisVal.mValue, 0, fieldInstance.mDataIdx);
  15203. mBfIRBuilder->CreateAlignedStore(localVal.mValue, fieldPtr, localVar->mResolvedType->mAlign);
  15204. }
  15205. MarkFieldInitialized(&fieldInstance);
  15206. }
  15207. }
  15208. }
  15209. // Call base ctor (if applicable)
  15210. BfTypeInstance* targetType = NULL;
  15211. BfAstNode* targetRefNode = NULL;
  15212. if (ctorDeclaration != NULL)
  15213. targetRefNode = ctorDeclaration->mInitializer;
  15214. if (auto invocationExpr = BfNodeDynCast<BfInvocationExpression>(targetRefNode))
  15215. targetRefNode = invocationExpr->mTarget;
  15216. if (baseCtorNode != NULL)
  15217. {
  15218. UpdateSrcPos(baseCtorNode);
  15219. if (methodDef->mBody == NULL)
  15220. SetIllegalSrcPos();
  15221. }
  15222. if ((ctorDeclaration != NULL) && (ctorInvocation != NULL))
  15223. {
  15224. auto targetToken = BfNodeDynCast<BfTokenNode>(ctorInvocation->mTarget);
  15225. targetType = (targetToken->GetToken() == BfToken_This) ? mCurTypeInstance : mCurTypeInstance->mBaseType;
  15226. }
  15227. else if ((mCurTypeInstance->mBaseType != NULL) && (!mCurTypeInstance->IsUnspecializedType()) && (methodDef->mMethodType != BfMethodType_CtorNoBody))
  15228. {
  15229. auto baseType = mCurTypeInstance->mBaseType;
  15230. if ((!mCurTypeInstance->IsTypedPrimitive()) &&
  15231. ((baseType->mTypeDef != mCompiler->mValueTypeTypeDef) || (!mContext->mCanSkipValueTypeCtor)) &&
  15232. ((baseType->mTypeDef != mCompiler->mBfObjectTypeDef) || (!mContext->mCanSkipObjectCtor)))
  15233. {
  15234. // Try to find a ctor without any params first
  15235. BfMethodDef* matchedMethod = NULL;
  15236. bool hadCtorWithAllDefaults = false;
  15237. bool isHiddenGenerated = (methodDeclaration == NULL) && (methodDef->mProtection == BfProtection_Hidden);
  15238. for (int pass = 0; pass < 2; pass++)
  15239. {
  15240. baseType->mTypeDef->PopulateMemberSets();
  15241. BfMemberSetEntry* entry = NULL;
  15242. BfMethodDef* checkMethodDef = NULL;
  15243. baseType->mTypeDef->mMethodSet.TryGetWith(String("__BfCtor"), &entry);
  15244. if (entry != NULL)
  15245. checkMethodDef = (BfMethodDef*)entry->mMemberDef;
  15246. while (checkMethodDef != NULL)
  15247. {
  15248. bool allowMethod = checkMethodDef->mProtection > BfProtection_Private;
  15249. if (isHiddenGenerated)
  15250. {
  15251. // Allow calling of the default base ctor if it is implicitly defined
  15252. if ((checkMethodDef->mMethodDeclaration == NULL) && (pass == 1) && (!hadCtorWithAllDefaults))
  15253. allowMethod = true;
  15254. }
  15255. if ((checkMethodDef->mMethodType == BfMethodType_Ctor) && (!checkMethodDef->mIsStatic) && (allowMethod))
  15256. {
  15257. if (checkMethodDef->mParams.size() == 0)
  15258. {
  15259. matchedMethod = checkMethodDef;
  15260. }
  15261. else if (isHiddenGenerated)
  15262. {
  15263. if ((checkMethodDef->mParams[0]->mParamDeclaration != NULL) && (checkMethodDef->mParams[0]->mParamDeclaration->mInitializer != NULL))
  15264. hadCtorWithAllDefaults = true;
  15265. }
  15266. }
  15267. checkMethodDef = checkMethodDef->mNextWithSameName;
  15268. }
  15269. if (matchedMethod != NULL)
  15270. break;
  15271. }
  15272. if ((HasExecutedOutput()) && (matchedMethod != NULL))
  15273. {
  15274. SizedArray<BfIRValue, 1> args;
  15275. auto ctorBodyMethodInstance = GetMethodInstance(mCurTypeInstance->mBaseType, matchedMethod, BfTypeVector());
  15276. if (!mCurTypeInstance->mBaseType->IsValuelessType())
  15277. {
  15278. auto basePtr = mBfIRBuilder->CreateBitCast(mCurMethodState->mLocals[0]->mValue, mBfIRBuilder->MapTypeInstPtr(mCurTypeInstance->mBaseType));
  15279. args.push_back(basePtr);
  15280. }
  15281. AddCallDependency(ctorBodyMethodInstance.mMethodInstance, true);
  15282. auto callInst = mBfIRBuilder->CreateCall(ctorBodyMethodInstance.mFunc, args);
  15283. auto callingConv = GetIRCallingConvention(ctorBodyMethodInstance.mMethodInstance);
  15284. if (callingConv != BfIRCallingConv_CDecl)
  15285. mBfIRBuilder->SetCallCallingConv(callInst, callingConv);
  15286. if (mIsComptimeModule)
  15287. mCompiler->mCEMachine->QueueMethod(ctorBodyMethodInstance);
  15288. }
  15289. if (matchedMethod == NULL)
  15290. {
  15291. targetType = mCurTypeInstance->mBaseType;
  15292. if (ctorDeclaration != NULL)
  15293. targetRefNode = ctorDeclaration->mThisToken;
  15294. else if (typeDef->mTypeDeclaration != NULL)
  15295. targetRefNode = typeDef->mTypeDeclaration->mNameNode;
  15296. }
  15297. }
  15298. }
  15299. if (methodDef->mHasAppend)
  15300. {
  15301. mCurMethodState->mCurAppendAlign = methodInstance->mAppendAllocAlign;
  15302. }
  15303. if ((ctorDeclaration != NULL) && (ctorInvocation != NULL) && (ctorInvocation->mArguments.size() == 1) && (targetType != NULL))
  15304. {
  15305. if (auto tokenNode = BfNodeDynCast<BfUninitializedExpression>(ctorInvocation->mArguments[0]))
  15306. {
  15307. if (targetType == mCurTypeInstance)
  15308. {
  15309. auto thisVariable = GetThisVariable();
  15310. if (thisVariable != NULL)
  15311. {
  15312. thisVariable->mUnassignedFieldFlags = 0;
  15313. thisVariable->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  15314. }
  15315. }
  15316. targetType = NULL;
  15317. }
  15318. }
  15319. if (targetType != NULL)
  15320. {
  15321. BfAstNode* refNode = methodDeclaration;
  15322. if (refNode == NULL)
  15323. refNode = typeDef->mTypeDeclaration;
  15324. BfAutoParentNodeEntry autoParentNodeEntry(this, refNode);
  15325. auto autoComplete = mCompiler->GetAutoComplete();
  15326. auto wasCapturingMethodInfo = (autoComplete != NULL) && (autoComplete->mIsCapturingMethodMatchInfo);
  15327. if ((autoComplete != NULL) && (ctorDeclaration != NULL) && (ctorInvocation != NULL))
  15328. {
  15329. auto invocationExpr = ctorInvocation;
  15330. autoComplete->CheckInvocation(invocationExpr, invocationExpr->mOpenParen, invocationExpr->mCloseParen, invocationExpr->mCommas);
  15331. }
  15332. BfType* targetThisType = targetType;
  15333. auto target = Cast(targetRefNode, GetThis(), targetThisType);
  15334. BfExprEvaluator exprEvaluator(this);
  15335. BfResolvedArgs argValues;
  15336. if ((ctorDeclaration != NULL) && (ctorInvocation != NULL))
  15337. {
  15338. argValues.Init(&ctorInvocation->mArguments);
  15339. if (gDebugStuff)
  15340. {
  15341. OutputDebugStrF("Expr: %@ %d\n", argValues.mArguments->mVals, argValues.mArguments->mSize);
  15342. }
  15343. }
  15344. exprEvaluator.ResolveArgValues(argValues, BfResolveArgsFlag_DeferParamEval);
  15345. BfTypedValue appendIdxVal;
  15346. if (methodDef->mHasAppend)
  15347. {
  15348. auto localVar = mCurMethodState->GetRootMethodState()->mLocals[1];
  15349. BF_ASSERT(localVar->mName == "appendIdx");
  15350. auto intRefType = localVar->mResolvedType;
  15351. appendIdxVal = BfTypedValue(localVar->mValue, intRefType);
  15352. mCurMethodState->mCurAppendAlign = 1; // Don't make any assumptions about how the base leaves the alignment
  15353. }
  15354. exprEvaluator.MatchConstructor(targetRefNode, NULL, target, targetType, argValues, true, methodDef->mHasAppend, &appendIdxVal);
  15355. if (autoComplete != NULL)
  15356. {
  15357. if ((wasCapturingMethodInfo) && (!autoComplete->mIsCapturingMethodMatchInfo))
  15358. {
  15359. if (autoComplete->mMethodMatchInfo != NULL)
  15360. autoComplete->mIsCapturingMethodMatchInfo = true;
  15361. else
  15362. autoComplete->mIsCapturingMethodMatchInfo = false;
  15363. }
  15364. else
  15365. autoComplete->mIsCapturingMethodMatchInfo = false;
  15366. }
  15367. }
  15368. }
  15369. void BfModule::EmitEnumToStringBody()
  15370. {
  15371. auto stringType = ResolveTypeDef(mCompiler->mStringTypeDef);
  15372. auto strVal = CreateAlloca(stringType);
  15373. auto int64StructType = GetPrimitiveStructType(BfTypeCode_Int64);
  15374. BfExprEvaluator exprEvaluator(this);
  15375. auto stringDestAddr = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  15376. BfIRBlock appendBlock = mBfIRBuilder->CreateBlock("append");
  15377. BfIRBlock noMatchBlock = mBfIRBuilder->CreateBlock("noMatch");
  15378. BfIRBlock endBlock = mBfIRBuilder->CreateBlock("end");
  15379. BfType* discriminatorType = NULL;
  15380. BfTypedValue rawPayload;
  15381. BfIRValue enumVal;
  15382. if (mCurTypeInstance->IsPayloadEnum())
  15383. {
  15384. discriminatorType = mCurTypeInstance->GetDiscriminatorType();
  15385. auto enumTypedValue = ExtractValue(GetThis(), NULL, 2);
  15386. enumTypedValue = LoadValue(enumTypedValue);
  15387. enumVal = enumTypedValue.mValue;
  15388. rawPayload = ExtractValue(GetThis(), NULL, 1);
  15389. }
  15390. else
  15391. enumVal = mBfIRBuilder->GetArgument(0);
  15392. Array<BfType*> paramTypes;
  15393. paramTypes.Add(stringType);
  15394. auto appendModuleMethodInstance = GetMethodByName(stringType->ToTypeInstance(), "Append", paramTypes);
  15395. auto switchVal = mBfIRBuilder->CreateSwitch(enumVal, noMatchBlock, (int)mCurTypeInstance->mFieldInstances.size());
  15396. HashSet<int64> handledCases;
  15397. for (auto& fieldInstance : mCurTypeInstance->mFieldInstances)
  15398. {
  15399. if (fieldInstance.mIsEnumPayloadCase)
  15400. {
  15401. int tagId = -fieldInstance.mDataIdx - 1;
  15402. BfIRBlock caseBlock = mBfIRBuilder->CreateBlock("case");
  15403. mBfIRBuilder->AddBlock(caseBlock);
  15404. mBfIRBuilder->SetInsertPoint(caseBlock);
  15405. BF_ASSERT(discriminatorType->IsPrimitiveType());
  15406. auto constVal = mBfIRBuilder->CreateConst(((BfPrimitiveType*)discriminatorType)->mTypeDef->mTypeCode, tagId);
  15407. mBfIRBuilder->AddSwitchCase(switchVal, constVal, caseBlock);
  15408. auto caseStr = GetStringObjectValue(fieldInstance.GetFieldDef()->mName);
  15409. auto stringDestVal = LoadValue(stringDestAddr);
  15410. SizedArray<BfIRValue, 2> args;
  15411. args.Add(stringDestVal.mValue);
  15412. args.Add(caseStr);
  15413. exprEvaluator.CreateCall(NULL, appendModuleMethodInstance.mMethodInstance, appendModuleMethodInstance.mFunc, false, args);
  15414. auto payloadType = fieldInstance.mResolvedType->ToTypeInstance();
  15415. BF_ASSERT(payloadType->IsTuple());
  15416. if (payloadType->mFieldInstances.size() != 0)
  15417. {
  15418. auto payload = rawPayload;
  15419. if (payload.mType != payloadType)
  15420. {
  15421. payload = Cast(NULL, payload, payloadType, BfCastFlags_Force);
  15422. }
  15423. auto toStringMethod = GetMethodByName(payloadType->ToTypeInstance(), "ToString");
  15424. SizedArray<BfIRValue, 2> irArgs;
  15425. exprEvaluator.PushThis(NULL, payload, toStringMethod.mMethodInstance, irArgs);
  15426. stringDestVal = LoadValue(stringDestAddr);
  15427. irArgs.Add(stringDestVal.mValue);
  15428. exprEvaluator.CreateCall(NULL, toStringMethod.mMethodInstance, toStringMethod.mFunc, true, irArgs);
  15429. }
  15430. mBfIRBuilder->CreateBr(endBlock);
  15431. continue;
  15432. }
  15433. if (fieldInstance.mConstIdx == -1)
  15434. continue;
  15435. // Only allow compact 'ValA, ValB' enum declaration fields through
  15436. auto fieldDecl = fieldInstance.GetFieldDef()->mFieldDeclaration;
  15437. if ((fieldDecl == NULL) || (fieldDecl->mTypeRef != NULL))
  15438. continue;
  15439. auto constant = mCurTypeInstance->mConstHolder->GetConstantById(fieldInstance.mConstIdx);
  15440. if (!handledCases.TryAdd(constant->mInt64, NULL))
  15441. {
  15442. // Duplicate
  15443. continue;
  15444. }
  15445. BfIRBlock caseBlock = mBfIRBuilder->CreateBlock("case");
  15446. mBfIRBuilder->AddBlock(caseBlock);
  15447. mBfIRBuilder->SetInsertPoint(caseBlock);
  15448. BfIRValue constVal = ConstantToCurrent(constant, mCurTypeInstance->mConstHolder, mCurTypeInstance);
  15449. mBfIRBuilder->AddSwitchCase(switchVal, constVal, caseBlock);
  15450. auto caseStr = GetStringObjectValue(fieldInstance.GetFieldDef()->mName);
  15451. mBfIRBuilder->CreateStore(caseStr, strVal);
  15452. mBfIRBuilder->CreateBr(appendBlock);
  15453. }
  15454. mBfIRBuilder->AddBlock(appendBlock);
  15455. mBfIRBuilder->SetInsertPoint(appendBlock);
  15456. SizedArray<BfIRValue, 2> args;
  15457. auto stringDestVal = LoadValue(stringDestAddr);
  15458. args.Add(stringDestVal.mValue);
  15459. args.Add(mBfIRBuilder->CreateLoad(strVal));
  15460. exprEvaluator.CreateCall(NULL, appendModuleMethodInstance.mMethodInstance, appendModuleMethodInstance.mFunc, false, args);
  15461. mBfIRBuilder->CreateBr(endBlock);
  15462. mBfIRBuilder->AddBlock(noMatchBlock);
  15463. mBfIRBuilder->SetInsertPoint(noMatchBlock);
  15464. auto int64Val = mBfIRBuilder->CreateNumericCast(enumVal, false, BfTypeCode_Int64);
  15465. auto toStringModuleMethodInstance = GetMethodByName(int64StructType, "ToString", 1);
  15466. args.clear();
  15467. args.Add(int64Val);
  15468. stringDestVal = LoadValue(stringDestAddr);
  15469. args.Add(stringDestVal.mValue);
  15470. exprEvaluator.CreateCall(NULL, toStringModuleMethodInstance.mMethodInstance, toStringModuleMethodInstance.mFunc, false, args);
  15471. mBfIRBuilder->CreateBr(endBlock);
  15472. mBfIRBuilder->AddBlock(endBlock);
  15473. mBfIRBuilder->SetInsertPoint(endBlock);
  15474. }
  15475. void BfModule::EmitTupleToStringBody()
  15476. {
  15477. auto stringType = ResolveTypeDef(mCompiler->mStringTypeDef);
  15478. BfExprEvaluator exprEvaluator(this);
  15479. auto stringDestRef = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  15480. Array<BfType*> paramTypes;
  15481. paramTypes.Add(GetPrimitiveType(BfTypeCode_Char8));
  15482. auto appendCharModuleMethodInstance = GetMethodByName(stringType->ToTypeInstance(), "Append", paramTypes);
  15483. paramTypes.Clear();
  15484. paramTypes.Add(stringType);
  15485. auto appendModuleMethodInstance = GetMethodByName(stringType->ToTypeInstance(), "Append", paramTypes);
  15486. auto _AppendChar = [&](char c)
  15487. {
  15488. SizedArray<BfIRValue, 2> args;
  15489. auto stringDestVal = LoadValue(stringDestRef);
  15490. args.Add(stringDestVal.mValue);
  15491. args.Add(mBfIRBuilder->CreateConst(BfTypeCode_Char8, (int)c));
  15492. exprEvaluator.CreateCall(NULL, appendCharModuleMethodInstance.mMethodInstance, appendCharModuleMethodInstance.mFunc, false, args);
  15493. };
  15494. int fieldIdx = 0;
  15495. auto thisValue = GetThis();
  15496. auto toStringModuleMethodInstance = GetMethodByName(mContext->mBfObjectType, "ToString", 1);
  15497. auto toStringSafeModuleMethodInstance = GetMethodByName(mContext->mBfObjectType, "ToString", 2);
  15498. BfIRValue commaStr;
  15499. auto iPrintableType = ResolveTypeDef(mCompiler->mIPrintableTypeDef)->ToTypeInstance();
  15500. auto printModuleMethodInstance = GetMethodByName(iPrintableType, "Print");
  15501. _AppendChar('(');
  15502. for (auto& fieldInstance : mCurTypeInstance->mFieldInstances)
  15503. {
  15504. if (fieldInstance.mDataIdx == -1)
  15505. continue;
  15506. if (fieldIdx > 0)
  15507. {
  15508. if (!commaStr)
  15509. commaStr = GetStringObjectValue(", ");
  15510. SizedArray<BfIRValue, 2> args;
  15511. auto stringDestVal = LoadValue(stringDestRef);
  15512. args.Add(stringDestVal.mValue);
  15513. args.Add(commaStr);
  15514. exprEvaluator.CreateCall(NULL, appendModuleMethodInstance.mMethodInstance, appendModuleMethodInstance.mFunc, false, args);
  15515. }
  15516. fieldIdx++;
  15517. if (fieldInstance.mResolvedType->IsValuelessType())
  15518. continue;
  15519. BfTypedValue fieldValue = ExtractValue(thisValue, &fieldInstance, fieldInstance.mDataIdx);
  15520. if (fieldValue.mType->IsPrimitiveType())
  15521. {
  15522. fieldValue.mType = GetPrimitiveStructType(((BfPrimitiveType*)fieldValue.mType)->mTypeDef->mTypeCode);
  15523. }
  15524. auto typeInstance = fieldValue.mType->ToTypeInstance();
  15525. if ((typeInstance != NULL) && (TypeIsSubTypeOf(typeInstance, iPrintableType, false)))
  15526. {
  15527. BfExprEvaluator exprEvaluator(this);
  15528. SizedArray<BfResolvedArg, 0> resolvedArgs;
  15529. BfMethodMatcher methodMatcher(NULL, this, printModuleMethodInstance.mMethodInstance, resolvedArgs, BfMethodGenericArguments());
  15530. methodMatcher.mBestMethodDef = printModuleMethodInstance.mMethodInstance->mMethodDef;
  15531. methodMatcher.mBestMethodTypeInstance = iPrintableType;
  15532. methodMatcher.TryDevirtualizeCall(fieldValue);
  15533. BfTypedValue callVal = Cast(NULL, fieldValue, methodMatcher.mBestMethodTypeInstance);
  15534. BfResolvedArg resolvedArg;
  15535. auto stringDestVal = LoadValue(stringDestRef);
  15536. resolvedArg.mTypedValue = stringDestVal;
  15537. resolvedArg.mResolvedType = stringDestVal.mType;
  15538. resolvedArgs.Add(resolvedArg);
  15539. exprEvaluator.CreateCall(&methodMatcher, callVal);
  15540. continue;
  15541. }
  15542. if (fieldValue.mType->IsObjectOrInterface())
  15543. {
  15544. fieldValue = LoadValue(fieldValue);
  15545. BF_ASSERT(!fieldValue.IsAddr());
  15546. SizedArray<BfIRValue, 2> args;
  15547. args.Add(mBfIRBuilder->CreateBitCast(fieldValue.mValue, mBfIRBuilder->MapType(mContext->mBfObjectType)));
  15548. auto stringDestVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  15549. stringDestVal = LoadValue(stringDestVal);
  15550. args.Add(stringDestVal.mValue);
  15551. exprEvaluator.CreateCall(NULL, toStringSafeModuleMethodInstance.mMethodInstance, toStringSafeModuleMethodInstance.mFunc, false, args);
  15552. continue;
  15553. }
  15554. BfExprEvaluator exprEvaluator(this);
  15555. SizedArray<BfResolvedArg, 0> resolvedArgs;
  15556. BfMethodMatcher methodMatcher(NULL, this, toStringModuleMethodInstance.mMethodInstance, resolvedArgs, BfMethodGenericArguments());
  15557. methodMatcher.mBestMethodDef = toStringModuleMethodInstance.mMethodInstance->mMethodDef;
  15558. methodMatcher.mBestMethodTypeInstance = mContext->mBfObjectType;
  15559. methodMatcher.TryDevirtualizeCall(fieldValue);
  15560. if (methodMatcher.mBestMethodTypeInstance == mContext->mBfObjectType)
  15561. {
  15562. AddCallDependency(appendModuleMethodInstance.mMethodInstance);
  15563. AddDependency(fieldValue.mType, mCurTypeInstance, BfDependencyMap::DependencyFlag_Calls);
  15564. // Just append the type name
  15565. String typeName = TypeToString(fieldInstance.mResolvedType);
  15566. auto strVal = GetStringObjectValue(typeName);
  15567. SizedArray<BfIRValue, 2> args;
  15568. auto stringDestVal = LoadValue(stringDestRef);
  15569. args.Add(stringDestVal.mValue);
  15570. args.Add(strVal);
  15571. exprEvaluator.CreateCall(NULL, appendModuleMethodInstance.mMethodInstance, appendModuleMethodInstance.mFunc, false, args);
  15572. continue;
  15573. }
  15574. BfTypedValue callVal = Cast(NULL, fieldValue, methodMatcher.mBestMethodTypeInstance);
  15575. BfResolvedArg resolvedArg;
  15576. auto stringDestVal = LoadValue(stringDestRef);
  15577. resolvedArg.mTypedValue = stringDestVal;
  15578. resolvedArg.mResolvedType = stringDestVal.mType;
  15579. resolvedArgs.Add(resolvedArg);
  15580. exprEvaluator.CreateCall(&methodMatcher, callVal);
  15581. }
  15582. _AppendChar(')');
  15583. }
  15584. void BfModule::EmitIteratorBlock(bool& skipBody)
  15585. {
  15586. auto methodInstance = mCurMethodInstance;
  15587. auto methodDef = methodInstance->mMethodDef;
  15588. auto methodDeclaration = methodDef->GetMethodDeclaration();
  15589. auto typeDef = mCurTypeInstance->mTypeDef;
  15590. BfType* innerRetType = NULL;
  15591. BfTypeInstance* usingInterface = NULL;
  15592. auto retTypeInst = mCurMethodInstance->mReturnType->ToGenericTypeInstance();
  15593. if (retTypeInst != NULL)
  15594. {
  15595. if ((retTypeInst->IsInstanceOf(mCompiler->mGenericIEnumerableTypeDef)) ||
  15596. (retTypeInst->IsInstanceOf(mCompiler->mGenericIEnumeratorTypeDef)))
  15597. {
  15598. innerRetType = retTypeInst->mGenericTypeInfo->mTypeGenericArguments[0];
  15599. }
  15600. }
  15601. if (innerRetType == NULL)
  15602. {
  15603. Fail("Methods with yields must return either System.IEnumerable<T> or System.IEnumerator<T>", methodDeclaration->mReturnType);
  15604. return;
  15605. }
  15606. auto blockBody = BfNodeDynCast<BfBlock>(methodDeclaration->mBody);
  15607. if (blockBody == NULL)
  15608. return;
  15609. }
  15610. void BfModule::EmitGCMarkValue(BfTypedValue markVal, BfModuleMethodInstance markFromGCThreadMethodInstance)
  15611. {
  15612. auto fieldType = markVal.mType;
  15613. auto fieldTypeInst = fieldType->ToTypeInstance();
  15614. if (fieldType == NULL)
  15615. return;
  15616. if (!markVal.mType->IsComposite())
  15617. markVal = LoadValue(markVal);
  15618. BfExprEvaluator exprEvaluator(this);
  15619. PopulateType(markVal.mType, BfPopulateType_Data);
  15620. if (markVal.mType->IsObjectOrInterface())
  15621. {
  15622. BfIRValue val = markVal.mValue;
  15623. val = mBfIRBuilder->CreateBitCast(val, mBfIRBuilder->MapType(mContext->mBfObjectType));
  15624. SizedArray<BfIRValue, 1> args;
  15625. args.push_back(val);
  15626. exprEvaluator.CreateCall(NULL, markFromGCThreadMethodInstance.mMethodInstance, markFromGCThreadMethodInstance.mFunc, false, args);
  15627. }
  15628. else if (fieldType->IsSizedArray())
  15629. {
  15630. BfSizedArrayType* sizedArrayType = (BfSizedArrayType*)fieldType;
  15631. if (sizedArrayType->mElementType->WantsGCMarking())
  15632. {
  15633. BfTypedValue arrayValue = markVal;
  15634. auto intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  15635. auto itr = CreateAlloca(intPtrType);
  15636. mBfIRBuilder->CreateStore(GetDefaultValue(intPtrType), itr);
  15637. auto loopBB = mBfIRBuilder->CreateBlock("loop", true);
  15638. auto bodyBB = mBfIRBuilder->CreateBlock("body", true);
  15639. auto doneBB = mBfIRBuilder->CreateBlock("done", true);
  15640. mBfIRBuilder->CreateBr(loopBB);
  15641. mBfIRBuilder->SetInsertPoint(loopBB);
  15642. auto loadedItr = mBfIRBuilder->CreateLoad(itr);
  15643. auto cmpRes = mBfIRBuilder->CreateCmpGTE(loadedItr, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, (uint64)sizedArrayType->mElementCount), true);
  15644. mBfIRBuilder->CreateCondBr(cmpRes, doneBB, bodyBB);
  15645. mBfIRBuilder->SetInsertPoint(bodyBB);
  15646. auto ptrType = CreatePointerType(sizedArrayType->mElementType);
  15647. auto ptrValue = mBfIRBuilder->CreateBitCast(arrayValue.mValue, mBfIRBuilder->MapType(ptrType));
  15648. auto gepResult = mBfIRBuilder->CreateInBoundsGEP(ptrValue, loadedItr);
  15649. auto value = BfTypedValue(gepResult, sizedArrayType->mElementType, BfTypedValueKind_Addr);
  15650. EmitGCMarkValue(value, markFromGCThreadMethodInstance);
  15651. auto incValue = mBfIRBuilder->CreateAdd(loadedItr, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 1));
  15652. mBfIRBuilder->CreateStore(incValue, itr);
  15653. mBfIRBuilder->CreateBr(loopBB);
  15654. mBfIRBuilder->SetInsertPoint(doneBB);
  15655. }
  15656. }
  15657. else if ((fieldType->IsComposite()) && (!fieldType->IsTypedPrimitive()) && (fieldTypeInst != NULL))
  15658. {
  15659. auto markMemberMethodInstance = GetMethodByName(fieldTypeInst, BF_METHODNAME_MARKMEMBERS, 0, true);
  15660. if (markMemberMethodInstance)
  15661. {
  15662. SizedArray<BfIRValue, 1> args;
  15663. auto methodOwner = markMemberMethodInstance.mMethodInstance->GetOwner();
  15664. if (markVal.mType != methodOwner)
  15665. markVal = Cast(NULL, markVal, methodOwner);
  15666. exprEvaluator.PushThis(NULL, markVal, markMemberMethodInstance.mMethodInstance, args);
  15667. exprEvaluator.CreateCall(NULL, markMemberMethodInstance.mMethodInstance, markMemberMethodInstance.mFunc, false, args);
  15668. }
  15669. }
  15670. }
  15671. void BfModule::CallChainedMethods(BfMethodInstance* methodInstance, bool reverse)
  15672. {
  15673. Array<BfMethodInstance*> methodInstances;
  15674. for (int methodIdx = 0; methodIdx < (int)mCurTypeInstance->mMethodInstanceGroups.size(); methodIdx++)
  15675. {
  15676. auto& methodInstGroup = mCurTypeInstance->mMethodInstanceGroups[methodIdx];
  15677. auto chainedMethodInst = methodInstGroup.mDefault;
  15678. if ((chainedMethodInst != NULL) && (chainedMethodInst->mChainType == BfMethodChainType_ChainMember))
  15679. {
  15680. if ((chainedMethodInst->mMethodDef->mIsStatic == methodInstance->mMethodDef->mIsStatic) &&
  15681. (CompareMethodSignatures(methodInstance, chainedMethodInst)))
  15682. {
  15683. methodInstances.push_back(chainedMethodInst);
  15684. }
  15685. }
  15686. }
  15687. std::stable_sort(methodInstances.begin(), methodInstances.end(),
  15688. [&](BfMethodInstance* lhs, BfMethodInstance* rhs)
  15689. {
  15690. bool isBetter;
  15691. bool isWorse;
  15692. CompareDeclTypes(lhs->mMethodDef->mDeclaringType, rhs->mMethodDef->mDeclaringType, isBetter, isWorse);
  15693. if (isBetter == isWorse)
  15694. {
  15695. return false;
  15696. }
  15697. return isWorse;
  15698. });
  15699. if (reverse)
  15700. std::reverse(methodInstances.begin(), methodInstances.end());
  15701. for (auto chainedMethodInst : methodInstances)
  15702. {
  15703. auto declModule = this;
  15704. BfGetMethodInstanceFlags flags = BfGetMethodInstanceFlag_None;
  15705. auto moduleMethodInst = declModule->GetMethodInstance(mCurTypeInstance, chainedMethodInst->mMethodDef, BfTypeVector(), flags);
  15706. BfExprEvaluator exprEvaluator(this);
  15707. SizedArray<BfIRValue, 1> args;
  15708. exprEvaluator.PushThis(chainedMethodInst->mMethodDef->GetRefNode(), GetThis(), chainedMethodInst, args);
  15709. exprEvaluator.CreateCall(NULL, moduleMethodInst.mMethodInstance, moduleMethodInst.mFunc, true, args);
  15710. }
  15711. }
  15712. void BfModule::AddHotDataReferences(BfHotDataReferenceBuilder* builder)
  15713. {
  15714. BF_ASSERT(mCurMethodInstance->mIsReified);
  15715. if (mCurTypeInstance->mHotTypeData == NULL)
  15716. {
  15717. mCurTypeInstance->mHotTypeData = new BfHotTypeData();
  15718. BfLogSysM("Created HotTypeData %p created for type %p in AddHotDataReferences\n", mCurTypeInstance->mHotTypeData, mCurTypeInstance);
  15719. }
  15720. auto hotMethod = mCurMethodInstance->mHotMethod;
  15721. for (auto depData : hotMethod->mReferences)
  15722. {
  15723. // Only virtual decls are allowed to already be there
  15724. BF_ASSERT((depData->mDataKind == BfHotDepDataKind_VirtualDecl) || (depData->mDataKind == BfHotDepDataKind_DupMethod));
  15725. }
  15726. BF_ASSERT(hotMethod->mSrcTypeVersion != NULL);
  15727. int prevSize = (int)hotMethod->mReferences.size();
  15728. int refCount = (int)(prevSize + builder->mUsedData.size() + builder->mCalledMethods.size() + builder->mDevirtualizedCalledMethods.size());
  15729. if (!mCurMethodInstance->mMethodDef->mIsStatic)
  15730. refCount++;
  15731. hotMethod->mReferences.Reserve(refCount);
  15732. if (!mCurMethodInstance->mMethodDef->mIsStatic)
  15733. {
  15734. auto hotThis = mCompiler->mHotData->GetThisType(mCurMethodInstance->GetOwner()->mHotTypeData->GetLatestVersion());
  15735. hotThis->mRefCount++;
  15736. hotMethod->mReferences.Insert(0, hotThis);
  15737. prevSize++;
  15738. }
  15739. for (auto val : builder->mAllocatedData)
  15740. {
  15741. auto hotAllocation = mCompiler->mHotData->GetAllocation(val);
  15742. hotMethod->mReferences.Add(hotAllocation);
  15743. }
  15744. for (auto val : builder->mUsedData)
  15745. hotMethod->mReferences.Add(val);
  15746. for (auto val : builder->mCalledMethods)
  15747. hotMethod->mReferences.Add(val);
  15748. for (auto val : builder->mDevirtualizedCalledMethods)
  15749. {
  15750. auto devirtualizedMethod = mCompiler->mHotData->GetDevirtualizedMethod(val);
  15751. hotMethod->mReferences.Add(devirtualizedMethod);
  15752. }
  15753. for (auto val : builder->mFunctionPtrs)
  15754. {
  15755. auto funcRef = mCompiler->mHotData->GetFunctionReference(val);
  15756. hotMethod->mReferences.Add(funcRef);
  15757. }
  15758. for (auto val : builder->mInnerMethods)
  15759. {
  15760. auto innerMethod = mCompiler->mHotData->GetInnerMethod(val);
  15761. hotMethod->mReferences.Add(innerMethod);
  15762. }
  15763. for (int refIdx = prevSize; refIdx < (int)hotMethod->mReferences.size(); refIdx++)
  15764. {
  15765. auto depData = hotMethod->mReferences[refIdx];
  15766. BF_ASSERT(depData != NULL);
  15767. depData->mRefCount++;
  15768. }
  15769. }
  15770. void BfModule::ProcessMethod_SetupParams(BfMethodInstance* methodInstance, BfType* thisType, bool wantsDIData, SizedArrayImpl<BfIRMDNode>* diParams)
  15771. {
  15772. auto methodDef = methodInstance->mMethodDef;
  15773. auto methodDeclaration = methodDef->mMethodDeclaration;
  15774. bool isThisStruct = false;
  15775. if (thisType != NULL)
  15776. isThisStruct = thisType->IsStruct() && !thisType->IsTypedPrimitive();
  15777. int argIdx = 0;
  15778. if ((!mIsComptimeModule) && (argIdx == methodInstance->GetStructRetIdx()))
  15779. argIdx++;
  15780. if (!methodDef->mIsStatic)
  15781. {
  15782. BfTypeCode loweredTypeCode = BfTypeCode_None;
  15783. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  15784. BfLocalVariable* paramVar = new BfLocalVariable();
  15785. paramVar->mResolvedType = thisType;
  15786. paramVar->mName = "this";
  15787. if (!thisType->IsValuelessType())
  15788. paramVar->mValue = mBfIRBuilder->GetArgument(argIdx);
  15789. else
  15790. paramVar->mValue = mBfIRBuilder->GetFakeVal();
  15791. if ((!mIsComptimeModule) && (thisType->IsSplattable()) && (methodInstance->AllowsSplatting(-1)))
  15792. {
  15793. if (!thisType->IsTypedPrimitive())
  15794. paramVar->mIsSplat = true;
  15795. }
  15796. else if ((!mIsComptimeModule) && (!methodDef->mIsMutating) && (methodInstance->mCallingConvention == BfCallingConvention_Unspecified))
  15797. paramVar->mIsLowered = thisType->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2) != BfTypeCode_None;
  15798. auto thisTypeInst = thisType->ToTypeInstance();
  15799. paramVar->mIsStruct = isThisStruct;
  15800. paramVar->mAddr = BfIRValue();
  15801. paramVar->mIsThis = true;
  15802. paramVar->mParamIdx = -1;
  15803. if ((methodDef->mMethodType == BfMethodType_Ctor) && (mCurTypeInstance->IsStruct()))
  15804. {
  15805. paramVar->mAssignedKind = BfLocalVarAssignKind_None;
  15806. }
  15807. else
  15808. {
  15809. paramVar->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  15810. }
  15811. paramVar->mReadFromId = -1;
  15812. paramVar->Init();
  15813. if (methodDeclaration == NULL)
  15814. UseDefaultSrcPos();
  15815. AddLocalVariableDef(paramVar);
  15816. if (!thisType->IsValuelessType())
  15817. {
  15818. if (wantsDIData)
  15819. {
  15820. BfType* thisPtrType = thisType;
  15821. auto diType = mBfIRBuilder->DbgGetType(thisPtrType);
  15822. if (!thisType->IsValueType())
  15823. diType = mBfIRBuilder->DbgCreateArtificialType(diType);
  15824. else if (!paramVar->mIsSplat)
  15825. diType = mBfIRBuilder->DbgCreatePointerType(diType);
  15826. diParams->push_back(diType);
  15827. }
  15828. if (paramVar->mIsSplat)
  15829. {
  15830. BfTypeUtils::SplatIterate([&](BfType* checkType) { argIdx++; }, paramVar->mResolvedType);
  15831. }
  15832. else
  15833. {
  15834. argIdx++;
  15835. if (loweredTypeCode2 != BfTypeCode_None)
  15836. argIdx++;
  15837. }
  15838. }
  15839. }
  15840. if ((!mIsComptimeModule) && (argIdx == methodInstance->GetStructRetIdx()))
  15841. argIdx++;
  15842. bool hadParams = false;
  15843. bool hasDefault = false;
  15844. int compositeVariableIdx = -1;
  15845. int paramIdx = 0;
  15846. for (paramIdx = 0; paramIdx < methodInstance->GetParamCount(); paramIdx++)
  15847. {
  15848. // We already issues a type error for this param if we had one in declaration processing
  15849. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, true);
  15850. BfLocalVariable* paramVar = new BfLocalVariable();
  15851. BfTypeCode loweredTypeCode = BfTypeCode_None;
  15852. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  15853. bool isParamSkipped = methodInstance->IsParamSkipped(paramIdx);
  15854. auto resolvedType = methodInstance->GetParamType(paramIdx);
  15855. if (resolvedType == NULL)
  15856. {
  15857. AssertErrorState();
  15858. paramVar->mParamFailed = true;
  15859. }
  15860. prevIgnoreErrors.Restore();
  15861. PopulateType(resolvedType, BfPopulateType_Declaration);
  15862. paramVar->mResolvedType = resolvedType;
  15863. int namePrefixCount = 0;
  15864. paramVar->mName = methodInstance->GetParamName(paramIdx, namePrefixCount);
  15865. paramVar->mNamePrefixCount = (uint8)namePrefixCount;
  15866. paramVar->mNameNode = methodInstance->GetParamNameNode(paramIdx);
  15867. if (!isParamSkipped)
  15868. {
  15869. paramVar->mValue = mBfIRBuilder->GetArgument(argIdx);
  15870. if (resolvedType->IsMethodRef())
  15871. {
  15872. paramVar->mIsSplat = true;
  15873. }
  15874. else if ((!mIsComptimeModule) && (resolvedType->IsComposite()) && (resolvedType->IsSplattable()))
  15875. {
  15876. if (methodInstance->AllowsSplatting(paramIdx))
  15877. {
  15878. auto resolveTypeInst = resolvedType->ToTypeInstance();
  15879. if ((resolveTypeInst != NULL) && (resolveTypeInst->mIsCRepr))
  15880. paramVar->mIsSplat = true;
  15881. else
  15882. {
  15883. int splatCount = resolvedType->GetSplatCount();
  15884. if (argIdx + splatCount <= mCompiler->mOptions.mMaxSplatRegs)
  15885. paramVar->mIsSplat = true;
  15886. }
  15887. }
  15888. }
  15889. }
  15890. else
  15891. {
  15892. paramVar->mIsSplat = true; // Treat skipped (valueless) as a splat
  15893. paramVar->mValue = mBfIRBuilder->GetFakeVal();
  15894. }
  15895. paramVar->mIsLowered = (!mIsComptimeModule) && resolvedType->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2) != BfTypeCode_None;
  15896. paramVar->mIsStruct = resolvedType->IsComposite() && !resolvedType->IsTypedPrimitive();
  15897. paramVar->mParamIdx = paramIdx;
  15898. paramVar->mIsImplicitParam = methodInstance->IsImplicitCapture(paramIdx);
  15899. paramVar->mReadFromId = 0;
  15900. if (resolvedType->IsRef())
  15901. {
  15902. auto refType = (BfRefType*)resolvedType;
  15903. paramVar->mAssignedKind = (refType->mRefKind != BfRefType::RefKind_Out) ? BfLocalVarAssignKind_Unconditional : BfLocalVarAssignKind_None;
  15904. if (refType->mRefKind == BfRefType::RefKind_In)
  15905. {
  15906. paramVar->mIsReadOnly = true;
  15907. }
  15908. }
  15909. else
  15910. {
  15911. paramVar->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  15912. if (methodDef->mMethodType != BfMethodType_Mixin)
  15913. paramVar->mIsReadOnly = true;
  15914. }
  15915. if (paramVar->mResolvedType->IsGenericParam())
  15916. {
  15917. auto genericParamInst = GetGenericParamInstance((BfGenericParamType*)paramVar->mResolvedType);
  15918. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  15919. {
  15920. auto typedVal = GetDefaultTypedValue(genericParamInst->mTypeConstraint, false, BfDefaultValueKind_Undef);
  15921. paramVar->mResolvedType = typedVal.mType;
  15922. paramVar->mConstValue = typedVal.mValue;
  15923. }
  15924. }
  15925. if (paramVar->mResolvedType->IsConstExprValue())
  15926. {
  15927. BfConstExprValueType* constExprValueType = (BfConstExprValueType*)paramVar->mResolvedType;
  15928. auto unspecializedMethodInstance = GetUnspecializedMethodInstance(methodInstance);
  15929. auto unspecParamType = unspecializedMethodInstance->GetParamType(paramIdx);
  15930. BF_ASSERT(unspecParamType->IsGenericParam());
  15931. if (unspecParamType->IsGenericParam())
  15932. {
  15933. BfGenericParamType* genericParamType = (BfGenericParamType*)unspecParamType;
  15934. if (genericParamType->mGenericParamKind == BfGenericParamKind_Method)
  15935. {
  15936. auto genericParamInst = unspecializedMethodInstance->mMethodInfoEx->mGenericParams[genericParamType->mGenericParamIdx];
  15937. if (genericParamInst->mTypeConstraint != NULL)
  15938. {
  15939. BfExprEvaluator exprEvaluator(this);
  15940. exprEvaluator.mExpectingType = genericParamInst->mTypeConstraint;
  15941. exprEvaluator.GetLiteral(NULL, constExprValueType->mValue);
  15942. auto checkType = genericParamInst->mTypeConstraint;
  15943. if (checkType->IsTypedPrimitive())
  15944. checkType = checkType->GetUnderlyingType();
  15945. if (exprEvaluator.mResult.mType == checkType)
  15946. {
  15947. paramVar->mResolvedType = genericParamInst->mTypeConstraint;
  15948. paramVar->mConstValue = exprEvaluator.mResult.mValue;
  15949. BF_ASSERT(paramVar->mConstValue.IsConst());
  15950. }
  15951. else
  15952. {
  15953. AssertErrorState();
  15954. paramVar->mResolvedType = genericParamInst->mTypeConstraint;
  15955. paramVar->mConstValue = GetDefaultValue(genericParamInst->mTypeConstraint);
  15956. }
  15957. }
  15958. }
  15959. }
  15960. //BF_ASSERT(!paramVar->mResolvedType->IsConstExprValue());
  15961. if (paramVar->mResolvedType->IsConstExprValue())
  15962. {
  15963. Fail("Invalid use of constant expression", methodInstance->GetParamTypeRef(paramIdx));
  15964. //AssertErrorState();
  15965. paramVar->mResolvedType = GetPrimitiveType(BfTypeCode_IntPtr);
  15966. paramVar->mConstValue = GetDefaultValue(paramVar->mResolvedType);
  15967. }
  15968. }
  15969. if (methodInstance->GetParamKind(paramIdx) == BfParamKind_DelegateParam)
  15970. {
  15971. if (compositeVariableIdx == -1)
  15972. {
  15973. compositeVariableIdx = (int)mCurMethodState->mLocals.size();
  15974. BfLocalVariable* localVar = new BfLocalVariable();
  15975. auto paramInst = &methodInstance->mParams[paramIdx];
  15976. auto paramDef = methodDef->mParams[paramInst->mParamDefIdx];
  15977. localVar->mName = paramDef->mName;
  15978. localVar->mNamePrefixCount = paramDef->mNamePrefixCount;
  15979. localVar->mResolvedType = ResolveTypeRef(paramDef->mTypeRef, BfPopulateType_Declaration, BfResolveTypeRefFlag_NoResolveGenericParam);
  15980. localVar->mCompositeCount = 0;
  15981. DoAddLocalVariable(localVar);
  15982. }
  15983. mCurMethodState->mLocals[compositeVariableIdx]->mCompositeCount++;
  15984. }
  15985. if (!mCurTypeInstance->IsDelegateOrFunction())
  15986. CheckVariableDef(paramVar);
  15987. paramVar->Init();
  15988. AddLocalVariableDef(paramVar);
  15989. if (!isParamSkipped)
  15990. {
  15991. if (wantsDIData)
  15992. diParams->push_back(mBfIRBuilder->DbgGetType(resolvedType));
  15993. if (paramVar->mIsSplat)
  15994. {
  15995. BfTypeUtils::SplatIterate([&](BfType* checkType) { argIdx++; }, paramVar->mResolvedType);
  15996. }
  15997. else
  15998. {
  15999. argIdx++;
  16000. }
  16001. if (loweredTypeCode2 != BfTypeCode_None)
  16002. argIdx++;
  16003. }
  16004. }
  16005. // Try to find an ending delegate params composite
  16006. if ((compositeVariableIdx == -1) && (methodDef->mParams.size() > 0))
  16007. {
  16008. auto paramDef = methodDef->mParams.back();
  16009. if (paramDef->mParamKind == BfParamKind_Params)
  16010. {
  16011. auto paramsType = ResolveTypeRef(paramDef->mTypeRef, BfPopulateType_Declaration, BfResolveTypeRefFlag_NoResolveGenericParam);
  16012. if (paramsType == NULL)
  16013. {
  16014. AssertErrorState();
  16015. }
  16016. else if (paramsType->IsGenericParam())
  16017. {
  16018. auto genericParamInstance = GetGenericParamInstance((BfGenericParamType*)paramsType);
  16019. if (genericParamInstance->mTypeConstraint != NULL)
  16020. {
  16021. auto typeInstConstraint = genericParamInstance->mTypeConstraint->ToTypeInstance();
  16022. if ((genericParamInstance->mTypeConstraint->IsDelegate()) || (genericParamInstance->mTypeConstraint->IsFunction()) ||
  16023. ((typeInstConstraint != NULL) &&
  16024. ((typeInstConstraint->IsInstanceOf(mCompiler->mDelegateTypeDef)) || (typeInstConstraint->IsInstanceOf(mCompiler->mFunctionTypeDef)))))
  16025. {
  16026. BfLocalVariable* localVar = new BfLocalVariable();
  16027. localVar->mName = paramDef->mName;
  16028. localVar->mResolvedType = paramsType;
  16029. localVar->mCompositeCount = 0;
  16030. DoAddLocalVariable(localVar);
  16031. }
  16032. }
  16033. }
  16034. else if (paramsType->IsDelegate())
  16035. {
  16036. BfMethodInstance* invokeMethodInstance = GetRawMethodInstanceAtIdx(paramsType->ToTypeInstance(), 0, "Invoke");
  16037. if (invokeMethodInstance != NULL)
  16038. {
  16039. // This is only for the case where the delegate didn't actually have any params so the composite is zero-sized
  16040. // and wasn't cleared by the preceding loop
  16041. BF_ASSERT(invokeMethodInstance->GetParamCount() == 0);
  16042. BfLocalVariable* localVar = new BfLocalVariable();
  16043. localVar->mName = paramDef->mName;
  16044. localVar->mResolvedType = paramsType;
  16045. localVar->mCompositeCount = 0;
  16046. DoAddLocalVariable(localVar);
  16047. }
  16048. }
  16049. }
  16050. }
  16051. }
  16052. void BfModule::ProcessMethod_ProcessDeferredLocals(int startIdx)
  16053. {
  16054. // if (mCurMethodState->mPrevMethodState != NULL) // Re-entry
  16055. // return;
  16056. auto startMethodState = mCurMethodState;
  16057. auto _ClearState = [&]()
  16058. {
  16059. mCurMethodState->mLocalMethods.Clear();
  16060. for (auto& local : mCurMethodState->mLocals)
  16061. delete local;
  16062. mCurMethodState->mLocals.Clear();
  16063. mCurMethodState->mLocalVarSet.Clear();
  16064. };
  16065. while (true)
  16066. {
  16067. bool didWork = false;
  16068. // 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
  16069. // we show errors in the capture phase. If we somehow pass the capture phase without error then this method WILL show any errors here,
  16070. // however (compiler bug), so this is the safest way
  16071. if (!mCurMethodState->mDeferredLocalMethods.IsEmpty())
  16072. {
  16073. for (int deferredLocalMethodIdx = 0; deferredLocalMethodIdx < (int)mCurMethodState->mDeferredLocalMethods.size(); deferredLocalMethodIdx++)
  16074. {
  16075. auto deferredLocalMethod = mCurMethodState->mDeferredLocalMethods[deferredLocalMethodIdx];
  16076. BfLogSysM("Processing deferred local method %p\n", deferredLocalMethod);
  16077. if (!mHadBuildError)
  16078. {
  16079. // Process as a closure - that allows us to look back and see the const locals and stuff
  16080. BfClosureState closureState;
  16081. mCurMethodState->mClosureState = &closureState;
  16082. closureState.mConstLocals = deferredLocalMethod->mConstLocals;
  16083. closureState.mReturnType = deferredLocalMethod->mMethodInstance->mReturnType;
  16084. closureState.mActiveDeferredLocalMethod = deferredLocalMethod;
  16085. closureState.mLocalMethod = deferredLocalMethod->mLocalMethod;
  16086. if (deferredLocalMethod->mMethodInstance->mMethodInfoEx != NULL)
  16087. closureState.mClosureInstanceInfo = deferredLocalMethod->mMethodInstance->mMethodInfoEx->mClosureInstanceInfo;
  16088. mCurMethodState->mMixinState = deferredLocalMethod->mLocalMethod->mDeclMixinState;
  16089. _ClearState();
  16090. for (auto& constLocal : deferredLocalMethod->mConstLocals)
  16091. {
  16092. auto localVar = new BfLocalVariable();
  16093. *localVar = constLocal;
  16094. DoAddLocalVariable(localVar);
  16095. }
  16096. mCurMethodState->mLocalMethods = deferredLocalMethod->mLocalMethods;
  16097. bool doProcess = !mCompiler->mCanceling;
  16098. if (doProcess)
  16099. {
  16100. BP_ZONE_F("ProcessMethod local %s", deferredLocalMethod->mMethodInstance->mMethodDef->mName.c_str());
  16101. ProcessMethod(deferredLocalMethod->mMethodInstance);
  16102. }
  16103. }
  16104. delete deferredLocalMethod;
  16105. mContext->CheckLockYield();
  16106. didWork = true;
  16107. }
  16108. mCurMethodState->mDeferredLocalMethods.Clear();
  16109. }
  16110. for (auto& kv : mCurMethodState->mLocalMethodCache)
  16111. {
  16112. BF_ASSERT((kv.mValue->mMethodDef == NULL) || (kv.mKey == kv.mValue->mMethodDef->mName));
  16113. }
  16114. if ((!mCurMethodState->mDeferredLambdaInstances.IsEmpty()) && (!mHadBuildError))
  16115. {
  16116. for (int deferredLambdaIdx = 0; deferredLambdaIdx < (int)mCurMethodState->mDeferredLambdaInstances.size(); deferredLambdaIdx++)
  16117. {
  16118. auto lambdaInstance = mCurMethodState->mDeferredLambdaInstances[deferredLambdaIdx];
  16119. BfLogSysM("Processing deferred lambdaInstance %p\n", lambdaInstance);
  16120. BfClosureState closureState;
  16121. mCurMethodState->mClosureState = &closureState;
  16122. //closureState.mConstLocals = deferredLocalMethod->mConstLocals;
  16123. closureState.mReturnType = lambdaInstance->mMethodInstance->mReturnType;
  16124. if (lambdaInstance->mClosureTypeInstance != NULL)
  16125. closureState.mClosureType = lambdaInstance->mClosureTypeInstance;
  16126. else
  16127. closureState.mClosureType = lambdaInstance->mDelegateTypeInstance;
  16128. closureState.mClosureInstanceInfo = lambdaInstance->mMethodInstance->mMethodInfoEx->mClosureInstanceInfo;
  16129. closureState.mDeclaringMethodIsMutating = lambdaInstance->mDeclaringMethodIsMutating;
  16130. mCurMethodState->mMixinState = lambdaInstance->mDeclMixinState;
  16131. _ClearState();
  16132. for (auto& constLocal : lambdaInstance->mConstLocals)
  16133. {
  16134. //if (constLocal.mIsThis)
  16135. {
  16136. // Valueless 'this'
  16137. closureState.mConstLocals.Add(constLocal);
  16138. }
  16139. /*else
  16140. {
  16141. auto localVar = new BfLocalVariable();
  16142. *localVar = constLocal;
  16143. DoAddLocalVariable(localVar);
  16144. }*/
  16145. }
  16146. BfMethodInstanceGroup methodInstanceGroup;
  16147. methodInstanceGroup.mOwner = mCurTypeInstance;
  16148. methodInstanceGroup.mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  16149. bool doProcess = !mCompiler->mCanceling;
  16150. if (doProcess)
  16151. {
  16152. BP_ZONE_F("ProcessMethod lambdaInstance %s", lambdaInstance->mMethodInstance->mMethodDef->mName.c_str());
  16153. lambdaInstance->mMethodInstance->mMethodInstanceGroup = &methodInstanceGroup;
  16154. ProcessMethod(lambdaInstance->mMethodInstance);
  16155. lambdaInstance->mMethodInstance->mMethodInstanceGroup = NULL;
  16156. if (lambdaInstance->mDtorMethodInstance != NULL)
  16157. {
  16158. lambdaInstance->mDtorMethodInstance->mMethodInstanceGroup = &methodInstanceGroup;
  16159. auto startMethodState2 = mCurMethodState;
  16160. ProcessMethod(lambdaInstance->mDtorMethodInstance);
  16161. lambdaInstance->mDtorMethodInstance->mMethodInstanceGroup = NULL;
  16162. }
  16163. }
  16164. didWork = true;
  16165. }
  16166. mContext->CheckLockYield();
  16167. mCurMethodState->mDeferredLambdaInstances.Clear();
  16168. }
  16169. if (!didWork)
  16170. break;
  16171. }
  16172. }
  16173. void BfModule::EmitGCMarkValue(BfTypedValue& thisValue, BfType* checkType, int memberDepth, int curOffset, HashSet<int>& objectOffsets, BfModuleMethodInstance markFromGCThreadMethodInstance)
  16174. {
  16175. if (checkType->IsComposite())
  16176. PopulateType(checkType, BfPopulateType_Data);
  16177. if (!checkType->WantsGCMarking())
  16178. return;
  16179. auto typeInstance = checkType->ToTypeInstance();
  16180. bool callMarkMethod = false;
  16181. // Call the actual marking method
  16182. if (memberDepth == 0)
  16183. {
  16184. // Don't call marking method on self
  16185. }
  16186. else if (checkType->IsObjectOrInterface())
  16187. {
  16188. if (!objectOffsets.Add(curOffset))
  16189. {
  16190. return;
  16191. }
  16192. callMarkMethod = true;
  16193. }
  16194. else if (checkType->IsSizedArray())
  16195. {
  16196. BfSizedArrayType* sizedArrayType = (BfSizedArrayType*)checkType;
  16197. if (sizedArrayType->mElementType->WantsGCMarking())
  16198. {
  16199. BfTypedValue arrayValue = thisValue;
  16200. if (thisValue.mType != checkType)
  16201. {
  16202. BfIRValue srcValue = thisValue.mValue;
  16203. if (curOffset != 0)
  16204. {
  16205. if (!thisValue.mType->IsPointer())
  16206. {
  16207. auto int8Type = GetPrimitiveType(BfTypeCode_UInt8);
  16208. auto int8PtrType = CreatePointerType(int8Type);
  16209. srcValue = mBfIRBuilder->CreateBitCast(thisValue.mValue, mBfIRBuilder->MapType(int8PtrType));
  16210. }
  16211. srcValue = mBfIRBuilder->CreateInBoundsGEP(srcValue, curOffset);
  16212. }
  16213. arrayValue = BfTypedValue(mBfIRBuilder->CreateBitCast(srcValue, mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapType(checkType))), checkType, BfTypedValueKind_Addr);
  16214. }
  16215. if (sizedArrayType->mElementCount > 6)
  16216. {
  16217. auto intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  16218. auto itr = CreateAlloca(intPtrType);
  16219. mBfIRBuilder->CreateStore(GetDefaultValue(intPtrType), itr);
  16220. auto loopBB = mBfIRBuilder->CreateBlock("loop", true);
  16221. auto bodyBB = mBfIRBuilder->CreateBlock("body", true);
  16222. auto doneBB = mBfIRBuilder->CreateBlock("done", true);
  16223. mBfIRBuilder->CreateBr(loopBB);
  16224. mBfIRBuilder->SetInsertPoint(loopBB);
  16225. auto loadedItr = mBfIRBuilder->CreateLoad(itr);
  16226. auto cmpRes = mBfIRBuilder->CreateCmpGTE(loadedItr, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, (uint64)sizedArrayType->mElementCount), true);
  16227. mBfIRBuilder->CreateCondBr(cmpRes, doneBB, bodyBB);
  16228. mBfIRBuilder->SetInsertPoint(bodyBB);
  16229. auto ptrType = CreatePointerType(sizedArrayType->mElementType);
  16230. auto ptrValue = mBfIRBuilder->CreateBitCast(arrayValue.mValue, mBfIRBuilder->MapType(ptrType));
  16231. auto gepResult = mBfIRBuilder->CreateInBoundsGEP(ptrValue, loadedItr);
  16232. auto value = BfTypedValue(gepResult, sizedArrayType->mElementType, BfTypedValueKind_Addr);
  16233. EmitGCMarkValue(value, markFromGCThreadMethodInstance);
  16234. auto incValue = mBfIRBuilder->CreateAdd(loadedItr, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 1));
  16235. mBfIRBuilder->CreateStore(incValue, itr);
  16236. mBfIRBuilder->CreateBr(loopBB);
  16237. mBfIRBuilder->SetInsertPoint(doneBB);
  16238. }
  16239. else
  16240. {
  16241. for (int dataIdx = 0; dataIdx < sizedArrayType->mElementCount; dataIdx++)
  16242. {
  16243. auto ptrType = CreatePointerType(sizedArrayType->mElementType);
  16244. auto ptrValue = mBfIRBuilder->CreateBitCast(arrayValue.mValue, mBfIRBuilder->MapType(ptrType));
  16245. auto gepResult = mBfIRBuilder->CreateInBoundsGEP(ptrValue, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, dataIdx));
  16246. auto value = BfTypedValue(gepResult, sizedArrayType->mElementType, BfTypedValueKind_Addr);
  16247. HashSet<int> objectOffsets;
  16248. EmitGCMarkValue(value, markFromGCThreadMethodInstance);
  16249. }
  16250. }
  16251. }
  16252. }
  16253. else if (typeInstance != NULL)
  16254. {
  16255. typeInstance->mTypeDef->PopulateMemberSets();
  16256. BfMemberSetEntry* entry = NULL;
  16257. BfMethodDef* methodDef = NULL;
  16258. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(String(BF_METHODNAME_MARKMEMBERS), &entry))
  16259. {
  16260. methodDef = (BfMethodDef*)entry->mMemberDef;
  16261. if (methodDef->HasBody())
  16262. {
  16263. callMarkMethod = true;
  16264. }
  16265. }
  16266. }
  16267. if (callMarkMethod)
  16268. {
  16269. BfTypedValue markValue;
  16270. auto memberType = checkType;
  16271. if (memberType->IsObjectOrInterface())
  16272. memberType = mContext->mBfObjectType; // Just to avoid that extra cast for the call itself
  16273. auto memberPtrType = CreatePointerType(memberType);
  16274. if (curOffset == 0)
  16275. {
  16276. markValue = BfTypedValue(mBfIRBuilder->CreateBitCast(thisValue.mValue, mBfIRBuilder->MapType(memberPtrType)), memberType, true);
  16277. }
  16278. else
  16279. {
  16280. if (!thisValue.mType->IsPointer())
  16281. {
  16282. auto int8Type = GetPrimitiveType(BfTypeCode_UInt8);
  16283. auto int8PtrType = CreatePointerType(int8Type);
  16284. thisValue = BfTypedValue(mBfIRBuilder->CreateBitCast(thisValue.mValue, mBfIRBuilder->MapType(int8PtrType)), int8PtrType);
  16285. }
  16286. auto offsetValue = mBfIRBuilder->CreateInBoundsGEP(thisValue.mValue, curOffset);
  16287. markValue = BfTypedValue(mBfIRBuilder->CreateBitCast(offsetValue, mBfIRBuilder->MapType(memberPtrType)), memberType, true);
  16288. }
  16289. EmitGCMarkValue(markValue, markFromGCThreadMethodInstance);
  16290. return;
  16291. }
  16292. auto methodDef = mCurMethodInstance->mMethodDef;
  16293. if (checkType->IsPayloadEnum())
  16294. {
  16295. for (auto& fieldInst : typeInstance->mFieldInstances)
  16296. {
  16297. if (!fieldInst.mIsEnumPayloadCase)
  16298. continue;
  16299. auto fieldDef = fieldInst.GetFieldDef();
  16300. EmitGCMarkValue(thisValue, fieldInst.mResolvedType, memberDepth + 1, curOffset, objectOffsets, markFromGCThreadMethodInstance);
  16301. }
  16302. return;
  16303. }
  16304. if (typeInstance == NULL)
  16305. return;
  16306. for (auto& fieldInst : typeInstance->mFieldInstances)
  16307. {
  16308. auto fieldDef = fieldInst.GetFieldDef();
  16309. if (fieldDef == NULL)
  16310. continue;
  16311. if (fieldDef->mIsStatic)
  16312. continue;
  16313. if (typeInstance == mCurTypeInstance)
  16314. {
  16315. // Note: we don't do method chaining when we are marking members of members. Theoretically this means
  16316. // we may be marking member values that can never contain a value anyway, but this is benign
  16317. if ((fieldDef->mDeclaringType->mTypeDeclaration != methodDef->mDeclaringType->mTypeDeclaration))
  16318. continue;
  16319. }
  16320. EmitGCMarkValue(thisValue, fieldInst.mResolvedType, memberDepth + 1, curOffset + fieldInst.mDataOffset, objectOffsets, markFromGCThreadMethodInstance);
  16321. }
  16322. if ((typeInstance->mBaseType != NULL) && (typeInstance->mBaseType != mContext->mBfObjectType))
  16323. {
  16324. EmitGCMarkValue(thisValue, typeInstance->mBaseType, memberDepth, curOffset, objectOffsets, markFromGCThreadMethodInstance);
  16325. }
  16326. }
  16327. void BfModule::EmitGCMarkMembers()
  16328. {
  16329. auto methodDef = mCurMethodInstance->mMethodDef;
  16330. auto gcType = ResolveTypeDef(mCompiler->mGCTypeDef, BfPopulateType_DataAndMethods);
  16331. BfModuleMethodInstance markFromGCThreadMethodInstance;
  16332. if (gcType != NULL)
  16333. markFromGCThreadMethodInstance = GetMethodByName(gcType->ToTypeInstance(), "Mark", 1);
  16334. if ((markFromGCThreadMethodInstance.mMethodInstance != NULL) && (!mCurMethodInstance->mIsUnspecialized))
  16335. {
  16336. if (mCurTypeInstance->IsBoxed())
  16337. {
  16338. // This already gets filled in by the normal boxed forwarding
  16339. }
  16340. else
  16341. {
  16342. auto thisValue = GetThis();
  16343. if (thisValue.IsSplat())
  16344. {
  16345. BfIRFunction func = mCurMethodInstance->mIRFunction;
  16346. int argIdx = 0;
  16347. std::function<void(BfType*)> checkTypeLambda = [&](BfType* checkType)
  16348. {
  16349. if (checkType->IsStruct())
  16350. {
  16351. auto checkTypeInstance = checkType->ToTypeInstance();
  16352. if (checkTypeInstance->mBaseType != NULL)
  16353. checkTypeLambda(checkTypeInstance->mBaseType);
  16354. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  16355. {
  16356. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  16357. if (fieldInstance->mDataIdx >= 0)
  16358. checkTypeLambda(fieldInstance->GetResolvedType());
  16359. }
  16360. }
  16361. else if (checkType->IsMethodRef())
  16362. {
  16363. BFMODULE_FATAL(this, "Not handled");
  16364. }
  16365. else if (checkType->WantsGCMarking())
  16366. {
  16367. BfTypedValue markValue(mBfIRBuilder->GetArgument(argIdx), checkType);
  16368. EmitGCMarkValue(markValue, markFromGCThreadMethodInstance);
  16369. argIdx++;
  16370. }
  16371. };
  16372. checkTypeLambda(thisValue.mType);
  16373. }
  16374. else if (!methodDef->mIsStatic)
  16375. {
  16376. if ((mCurTypeInstance->mBaseType != NULL) && (!mCurTypeInstance->IsTypedPrimitive()) && (mCurTypeInstance->mBaseType->WantsGCMarking()))
  16377. {
  16378. BfModuleMethodInstance moduleMethodInst = GetMethodByName(mCurTypeInstance->mBaseType, BF_METHODNAME_MARKMEMBERS, 0, true);
  16379. if (moduleMethodInst)
  16380. {
  16381. auto methodBaseType = moduleMethodInst.mMethodInstance->GetOwner();
  16382. bool wantsBaseMarking = true;
  16383. if (methodBaseType == mContext->mBfObjectType)
  16384. {
  16385. wantsBaseMarking = false;
  16386. PopulateType(methodBaseType);
  16387. for (auto& fieldInstance : mContext->mBfObjectType->mFieldInstances)
  16388. {
  16389. if ((fieldInstance.GetFieldDef()->mDeclaringType->IsExtension()) &&
  16390. (fieldInstance.mResolvedType->WantsGCMarking()))
  16391. wantsBaseMarking = true;
  16392. }
  16393. }
  16394. if (wantsBaseMarking)
  16395. {
  16396. auto thisValue = GetThis();
  16397. auto baseValue = Cast(NULL, thisValue, methodBaseType, BfCastFlags_Explicit);
  16398. SizedArray<BfIRValue, 1> args;
  16399. if ((!mIsComptimeModule) && (moduleMethodInst.mMethodInstance->GetParamIsSplat(-1)))
  16400. {
  16401. BfExprEvaluator exprEvaluator(this);
  16402. exprEvaluator.SplatArgs(baseValue, args);
  16403. }
  16404. else
  16405. {
  16406. args.push_back(baseValue.mValue);
  16407. }
  16408. mBfIRBuilder->CreateCall(moduleMethodInst.mFunc, args);
  16409. }
  16410. }
  16411. }
  16412. }
  16413. if (!methodDef->mIsStatic)
  16414. {
  16415. HashSet<int> objectOffsets;
  16416. EmitGCMarkValue(thisValue, mCurTypeInstance, 0, 0, objectOffsets, markFromGCThreadMethodInstance);
  16417. }
  16418. else
  16419. {
  16420. for (auto& fieldInst : mCurTypeInstance->mFieldInstances)
  16421. {
  16422. if (thisValue.IsSplat())
  16423. break;
  16424. auto fieldDef = fieldInst.GetFieldDef();
  16425. if (fieldDef == NULL)
  16426. continue;
  16427. if (fieldInst.mIsThreadLocal)
  16428. continue;
  16429. if (fieldDef->mIsStatic == methodDef->mIsStatic)
  16430. {
  16431. // For extensions, only handle these fields in the appropriate extension
  16432. if ((fieldDef->mDeclaringType->mTypeDeclaration != methodDef->mDeclaringType->mTypeDeclaration))
  16433. continue;
  16434. if (!fieldInst.mFieldIncluded)
  16435. continue;
  16436. auto fieldType = fieldInst.mResolvedType;
  16437. auto fieldDef = fieldInst.GetFieldDef();
  16438. BfTypedValue markVal;
  16439. if (fieldDef->mIsConst)
  16440. continue;
  16441. if ((!fieldType->IsObjectOrInterface()) && (!fieldType->IsComposite()))
  16442. continue;
  16443. mBfIRBuilder->PopulateType(fieldType);
  16444. if (fieldType->IsValuelessType())
  16445. continue;
  16446. if ((fieldDef->mIsStatic) && (!fieldDef->mIsConst))
  16447. {
  16448. StringT<128> staticVarName;
  16449. BfMangler::Mangle(staticVarName, mCompiler->GetMangleKind(), &fieldInst);
  16450. if (staticVarName.StartsWith('#'))
  16451. continue;
  16452. markVal = ReferenceStaticField(&fieldInst);
  16453. }
  16454. else if (!fieldDef->mIsStatic)
  16455. {
  16456. markVal = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(thisValue.mValue, 0, fieldInst.mDataIdx/*, fieldDef->mName*/), fieldInst.mResolvedType, true);
  16457. }
  16458. if (markVal)
  16459. EmitGCMarkValue(markVal, markFromGCThreadMethodInstance);
  16460. }
  16461. }
  16462. }
  16463. if (mCurMethodInstance->mChainType == BfMethodChainType_ChainHead)
  16464. CallChainedMethods(mCurMethodInstance, false);
  16465. }
  16466. }
  16467. }
  16468. void BfModule::EmitGCFindTLSMembers()
  16469. {
  16470. auto methodDef = mCurMethodInstance->mMethodDef;
  16471. auto gcTypeInst = ResolveTypeDef(mCompiler->mGCTypeDef)->ToTypeInstance();
  16472. auto reportTLSMark = GetMethodByName(gcTypeInst, "ReportTLSMember", 2);
  16473. BF_ASSERT(reportTLSMark);
  16474. for (auto& fieldInst : mCurTypeInstance->mFieldInstances)
  16475. {
  16476. auto fieldDef = fieldInst.GetFieldDef();
  16477. if (fieldDef == NULL)
  16478. continue;
  16479. if (!fieldInst.mIsThreadLocal)
  16480. continue;
  16481. // For extensions, only handle these fields in the appropriate extension
  16482. if ((fieldDef->mDeclaringType->mTypeDeclaration != methodDef->mDeclaringType->mTypeDeclaration))
  16483. continue;
  16484. if (!fieldInst.mFieldIncluded)
  16485. continue;
  16486. if (fieldDef->mIsConst)
  16487. continue;
  16488. auto fieldType = fieldInst.mResolvedType;
  16489. if ((!fieldType->IsObjectOrInterface()) && (!fieldType->IsComposite()))
  16490. continue;
  16491. if (fieldType->IsValuelessType())
  16492. continue;
  16493. BfTypedValue markVal = ReferenceStaticField(&fieldInst);
  16494. if (markVal)
  16495. {
  16496. BfIRValue fieldRefPtr = mBfIRBuilder->CreateBitCast(markVal.mValue, mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr)));
  16497. BfIRValue markFuncPtr = GetMarkFuncPtr(fieldType);
  16498. SizedArray<BfIRValue, 2> llvmArgs;
  16499. llvmArgs.push_back(fieldRefPtr);
  16500. llvmArgs.push_back(markFuncPtr);
  16501. mBfIRBuilder->CreateCall(reportTLSMark.mFunc, llvmArgs);
  16502. }
  16503. }
  16504. if (mCurMethodInstance->mChainType == BfMethodChainType_ChainHead)
  16505. CallChainedMethods(mCurMethodInstance, false);
  16506. }
  16507. void BfModule::ProcessMethod(BfMethodInstance* methodInstance, bool isInlineDup, bool forceIRWrites)
  16508. {
  16509. BP_ZONE_F("BfModule::ProcessMethod %s", BP_DYN_STR(methodInstance->mMethodDef->mName.c_str()));
  16510. if (mIsComptimeModule)
  16511. {
  16512. BF_ASSERT(!mCompiler->IsAutocomplete());
  16513. }
  16514. if (mAwaitingInitFinish)
  16515. FinishInit();
  16516. if (!methodInstance->mIsReified)
  16517. BF_ASSERT(!mIsReified);
  16518. BF_ASSERT((!methodInstance->GetOwner()->IsUnspecializedTypeVariation()) || (mIsComptimeModule));
  16519. if (methodInstance->mMethodInfoEx != NULL)
  16520. {
  16521. for (auto methodGenericArg : methodInstance->mMethodInfoEx->mMethodGenericArguments)
  16522. {
  16523. if (methodGenericArg->IsMethodRef())
  16524. {
  16525. auto methodRefType = (BfMethodRefType*)methodGenericArg;
  16526. BF_ASSERT(methodRefType->mOwnerRevision == methodRefType->mOwner->mRevision);
  16527. }
  16528. }
  16529. }
  16530. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, (mWantsIRIgnoreWrites || methodInstance->mIsUnspecialized) && (!forceIRWrites));
  16531. if ((HasCompiledOutput()) && (!mBfIRBuilder->mIgnoreWrites))
  16532. {
  16533. BF_ASSERT(!methodInstance->mIRFunction.IsFake() || (methodInstance->GetImportCallKind() != BfImportCallKind_None));
  16534. }
  16535. SetAndRestoreValue<BfSourceClassifier*> prevSourceClassifier;
  16536. if (((methodInstance->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend) || (methodInstance->mIsForeignMethodDef) || (methodInstance->IsSpecializedGenericMethod())) &&
  16537. (mCompiler->mResolvePassData != NULL))
  16538. {
  16539. // Don't classify on the CtorCalcAppend, just on the actual Ctor
  16540. prevSourceClassifier.Init(mCompiler->mResolvePassData->mSourceClassifier, NULL);
  16541. }
  16542. if (methodInstance->mHasBeenProcessed)
  16543. {
  16544. BfLogSysM("ProcessMethod %p HasBeenProcessed\n", methodInstance);
  16545. return;
  16546. }
  16547. if (methodInstance->mFailedConstraints)
  16548. {
  16549. // The only way this should be able to happen is if we fail our generic param check
  16550. BF_ASSERT(methodInstance->IsSpecializedGenericMethod());
  16551. BfLogSysM("Method instance marked as 'failed' at start of ProcessMethod %p\n", methodInstance);
  16552. methodInstance->mHasBeenProcessed = true;
  16553. return;
  16554. }
  16555. if (HasExecutedOutput())
  16556. {
  16557. BF_ASSERT(mIsModuleMutable);
  16558. }
  16559. BfMethodInstance* defaultMethodInstance = methodInstance->mMethodInstanceGroup->mDefault;
  16560. if (!mIsComptimeModule)
  16561. {
  16562. BF_ASSERT(methodInstance->mMethodInstanceGroup->mOnDemandKind != BfMethodOnDemandKind_NotSet);
  16563. if ((methodInstance->mMethodInstanceGroup->mOnDemandKind != BfMethodOnDemandKind_AlwaysInclude) &&
  16564. (methodInstance->mMethodInstanceGroup->mOnDemandKind != BfMethodOnDemandKind_Referenced))
  16565. {
  16566. auto owningModule = methodInstance->GetOwner()->mModule;
  16567. if (owningModule->mIsScratchModule)
  16568. {
  16569. BF_ASSERT(owningModule->mOnDemandMethodCount == 0);
  16570. }
  16571. else
  16572. {
  16573. BF_ASSERT((owningModule->mOnDemandMethodCount > 0) || (!HasCompiledOutput()) || (owningModule->mExtensionCount > 0));
  16574. if (owningModule->mOnDemandMethodCount > 0)
  16575. owningModule->mOnDemandMethodCount--;
  16576. }
  16577. methodInstance->mMethodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_Referenced;
  16578. VerifyOnDemandMethods();
  16579. }
  16580. }
  16581. // We set mHasBeenProcessed to true immediately -- this helps avoid stack overflow during recursion for things like
  16582. // self-referencing append allocations in ctor@calcAppend
  16583. methodInstance->mHasBeenProcessed = true;
  16584. mIncompleteMethodCount--;
  16585. BF_ASSERT((mIsSpecialModule) || (mIncompleteMethodCount >= 0));
  16586. auto typeDef = methodInstance->mMethodInstanceGroup->mOwner->mTypeDef;
  16587. auto methodDef = methodInstance->mMethodDef;
  16588. auto methodDeclaration = methodDef->GetMethodDeclaration();
  16589. if ((methodDef->mHasComptime) && (!mIsComptimeModule))
  16590. mBfIRBuilder->mIgnoreWrites = true;
  16591. if ((methodInstance->mIsReified) && (methodInstance->mVirtualTableIdx != -1))
  16592. {
  16593. // If we reify a virtual method in a HotCompile then we need to make sure the type data gets written out
  16594. // so we get the new vdata for it
  16595. methodInstance->GetOwner()->mDirty = true;
  16596. }
  16597. int dependentGenericStartIdx = 0;
  16598. if ((methodDef->mIsLocalMethod) && (mCurMethodState != NULL)) // See DoMethodDeclaration for an explaination of dependentGenericStartIdx
  16599. dependentGenericStartIdx = (int)mCurMethodState->GetRootMethodState()->mMethodInstance->GetNumGenericArguments();
  16600. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, methodInstance);
  16601. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, methodInstance->mMethodInstanceGroup->mOwner);
  16602. SetAndRestoreValue<BfFilePosition> prevFilePos(mCurFilePosition);
  16603. SetAndRestoreValue<bool> prevHadBuildError(mHadBuildError, false);
  16604. SetAndRestoreValue<bool> prevHadWarning(mHadBuildWarning, false);
  16605. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors);
  16606. SetAndRestoreValue<bool> prevIgnoreWarnings(mIgnoreWarnings, mIsComptimeModule);
  16607. if ((methodInstance->mIsReified) &&
  16608. ((methodDef->mMethodType == BfMethodType_Ctor) || (methodDef->mMethodType == BfMethodType_CtorNoBody)))
  16609. {
  16610. mCurTypeInstance->mHasBeenInstantiated = true;
  16611. }
  16612. // Warnings are shown in the capture phase
  16613. if ((methodDef->mIsLocalMethod) || (mCurTypeInstance->IsClosure()))
  16614. mIgnoreWarnings = true;
  16615. if ((methodDeclaration == NULL) && (mCurMethodState == NULL))
  16616. UseDefaultSrcPos();
  16617. if ((mIsComptimeModule) && (methodDef->mIsStatic))
  16618. {
  16619. PopulateType(mCurTypeInstance, BfPopulateType_AllowStaticMethods);
  16620. }
  16621. else
  16622. {
  16623. // We may not actually be populated in relatively rare autocompelte cases
  16624. PopulateType(mCurTypeInstance, BfPopulateType_DataAndMethods);
  16625. mBfIRBuilder->PopulateType(mCurTypeInstance, BfIRPopulateType_Full);
  16626. }
  16627. BfAstNode* nameNode = NULL;
  16628. if (methodDeclaration != NULL)
  16629. {
  16630. nameNode = methodDeclaration->mNameNode;
  16631. if (nameNode == NULL)
  16632. {
  16633. if (auto ctorDeclaration = BfNodeDynCast<BfConstructorDeclaration>(methodDeclaration))
  16634. nameNode = ctorDeclaration->mThisToken;
  16635. }
  16636. }
  16637. if ((mCompiler->mResolvePassData != NULL) && (methodDeclaration != NULL) && (nameNode != NULL) &&
  16638. (mCompiler->mResolvePassData->mGetSymbolReferenceKind == BfGetSymbolReferenceKind_Method) &&
  16639. (methodDef->mIdx >= 0) && (!methodInstance->mIsForeignMethodDef))
  16640. {
  16641. if (methodInstance->GetExplicitInterface() == NULL)
  16642. mCompiler->mResolvePassData->HandleMethodReference(nameNode, typeDef, methodDef);
  16643. else
  16644. {
  16645. for (auto& ifaceEntry : mCurTypeInstance->mInterfaces)
  16646. {
  16647. auto ifaceInst = ifaceEntry.mInterfaceType;
  16648. int startIdx = ifaceEntry.mStartInterfaceTableIdx;
  16649. int iMethodCount = (int)ifaceInst->mMethodInstanceGroups.size();
  16650. if (methodInstance->GetExplicitInterface() != ifaceInst)
  16651. continue;
  16652. ifaceInst->mTypeDef->PopulateMemberSets();
  16653. BfMethodDef* nextMethod = NULL;
  16654. BfMemberSetEntry* entry = NULL;
  16655. if (ifaceInst->mTypeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  16656. nextMethod = (BfMethodDef*)entry->mMemberDef;
  16657. while (nextMethod != NULL)
  16658. {
  16659. auto checkMethod = nextMethod;
  16660. nextMethod = nextMethod->mNextWithSameName;
  16661. BfMethodInstance* implMethodInst = mCurTypeInstance->mInterfaceMethodTable[startIdx + checkMethod->mIdx].mMethodRef;
  16662. if (implMethodInst == methodInstance)
  16663. {
  16664. auto ifaceMethodDef = ifaceInst->mTypeDef->mMethods[checkMethod->mIdx];
  16665. mCompiler->mResolvePassData->HandleMethodReference(nameNode, ifaceInst->mTypeDef, ifaceMethodDef);
  16666. }
  16667. }
  16668. }
  16669. }
  16670. if (methodDef->mIsOverride)
  16671. {
  16672. for (int virtIdx = 0; virtIdx < (int)mCurTypeInstance->mVirtualMethodTable.size(); virtIdx++)
  16673. {
  16674. auto& ventry = mCurTypeInstance->mVirtualMethodTable[virtIdx];
  16675. if (ventry.mDeclaringMethod.mMethodNum == -1)
  16676. continue;
  16677. BfMethodInstance* virtMethod = ventry.mImplementingMethod;
  16678. if (virtMethod != NULL)
  16679. {
  16680. if (virtMethod == methodInstance)
  16681. {
  16682. // Is matching method
  16683. if (virtIdx < (int)mCurTypeInstance->mBaseType->mVirtualMethodTable.size())
  16684. {
  16685. auto baseType = mCurTypeInstance->mBaseType;
  16686. if (baseType != NULL)
  16687. {
  16688. while ((baseType->mBaseType != NULL) && (virtIdx < baseType->mBaseType->mVirtualMethodTableSize))
  16689. baseType = baseType->mBaseType;
  16690. BfMethodInstance* baseVirtMethod = baseType->mVirtualMethodTable[virtIdx].mImplementingMethod;
  16691. mCompiler->mResolvePassData->HandleMethodReference(nameNode, baseType->mTypeDef, baseVirtMethod->mMethodDef);
  16692. }
  16693. }
  16694. break;
  16695. }
  16696. }
  16697. }
  16698. }
  16699. }
  16700. BfLogSysM("ProcessMethod %p Unspecialized: %d Module: %p IRFunction: %d Reified: %d Incomplete:%d\n", methodInstance, mCurTypeInstance->IsUnspecializedType(), this, methodInstance->mIRFunction.mId, methodInstance->mIsReified, mIncompleteMethodCount);
  16701. int importStrNum = -1;
  16702. auto importKind = methodInstance->GetImportKind();
  16703. if ((!mCompiler->mIsResolveOnly) &&
  16704. ((importKind == BfImportKind_Import_Static) || (importKind == BfImportKind_Import_Dynamic)))
  16705. {
  16706. if (auto customAttr = methodInstance->GetCustomAttributes()->Get(mCompiler->mImportAttributeTypeDef))
  16707. {
  16708. if (customAttr->mCtorArgs.size() == 1)
  16709. {
  16710. auto fileNameArg = customAttr->mCtorArgs[0];
  16711. auto constant = mCurTypeInstance->mConstHolder->GetConstant(fileNameArg);
  16712. if (constant != NULL)
  16713. {
  16714. if (!constant->IsNull())
  16715. importStrNum = constant->mInt32;
  16716. }
  16717. else
  16718. {
  16719. importStrNum = GetStringPoolIdx(fileNameArg, mCurTypeInstance->mConstHolder);
  16720. }
  16721. if (importStrNum != -1)
  16722. {
  16723. if (!mStringPoolRefs.Contains(importStrNum))
  16724. mStringPoolRefs.Add(importStrNum);
  16725. }
  16726. }
  16727. }
  16728. }
  16729. if (methodInstance->GetImportCallKind() != BfImportCallKind_None)
  16730. {
  16731. if (mBfIRBuilder->mIgnoreWrites)
  16732. return;
  16733. BfLogSysM("DllImportGlobalVar processing %p\n", methodInstance);
  16734. if (!methodInstance->mIRFunction)
  16735. {
  16736. BfIRValue dllImportGlobalVar = CreateDllImportGlobalVar(methodInstance, true);
  16737. methodInstance->mIRFunction = mBfIRBuilder->GetFakeVal();
  16738. BF_ASSERT(dllImportGlobalVar || methodInstance->mHasFailed);
  16739. mFuncReferences[mCurMethodInstance] = dllImportGlobalVar;
  16740. }
  16741. if (HasCompiledOutput())
  16742. {
  16743. BfDllImportEntry dllImportEntry;
  16744. dllImportEntry.mFuncVar = methodInstance->mIRFunction;
  16745. dllImportEntry.mMethodInstance = mCurMethodInstance;
  16746. mDllImportEntries.push_back(dllImportEntry);
  16747. }
  16748. return;
  16749. }
  16750. StringT<128> mangledName;
  16751. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), mCurMethodInstance);
  16752. if (!methodInstance->mIRFunction)
  16753. {
  16754. bool isIntrinsic = false;
  16755. SetupIRFunction(methodInstance, mangledName, false, &isIntrinsic);
  16756. }
  16757. if (methodInstance->mIsIntrinsic)
  16758. return;
  16759. if (mCurTypeInstance->IsFunction())
  16760. return;
  16761. auto prevActiveFunction = mBfIRBuilder->GetActiveFunction();
  16762. mBfIRBuilder->SetActiveFunction(mCurMethodInstance->mIRFunction);
  16763. if (methodDef->mBody != NULL)
  16764. UpdateSrcPos(methodDef->mBody, BfSrcPosFlag_NoSetDebugLoc);
  16765. else if (methodDeclaration != NULL)
  16766. UpdateSrcPos(methodDeclaration, BfSrcPosFlag_NoSetDebugLoc);
  16767. else if ((methodDef->mDeclaringType != NULL) && (methodDef->mDeclaringType->GetRefNode() != NULL))
  16768. UpdateSrcPos(methodDef->mDeclaringType->GetRefNode(), BfSrcPosFlag_NoSetDebugLoc);
  16769. else if (mCurTypeInstance->mTypeDef->mTypeDeclaration != NULL)
  16770. UpdateSrcPos(mCurTypeInstance->mTypeDef->mTypeDeclaration, BfSrcPosFlag_NoSetDebugLoc);
  16771. if ((mCurMethodState == NULL) && (!IsInSpecializedSection())) // Only do initial classify for the 'outer' method state, not any local methods or lambdas
  16772. {
  16773. if ((mCompiler->mIsResolveOnly) && (!mIsComptimeModule) && (methodDef->mBody != NULL) && (!mCurTypeInstance->IsBoxed()) &&
  16774. (methodDef->mBody->IsFromParser(mCompiler->mResolvePassData->mParser)) && (mCompiler->mResolvePassData->mSourceClassifier != NULL))
  16775. {
  16776. mCompiler->mResolvePassData->mSourceClassifier->VisitChildNoRef(methodDef->mBody);
  16777. }
  16778. }
  16779. BfHotDataReferenceBuilder hotDataReferenceBuilder;
  16780. BfMethodState methodState;
  16781. if (mCurMethodState != NULL)
  16782. methodState.mClosureState = mCurMethodState->mClosureState;
  16783. if ((mCompiler->mOptions.mAllowHotSwapping) && (methodInstance->mIsReified) && (!methodInstance->mIsUnspecialized) && (!isInlineDup))
  16784. {
  16785. //BF_ASSERT(methodInstance->mHotMethod != NULL);
  16786. if (methodInstance->mHotMethod == NULL)
  16787. CheckHotMethod(methodInstance, mangledName);
  16788. methodState.mHotDataReferenceBuilder = &hotDataReferenceBuilder;
  16789. }
  16790. methodState.mPrevMethodState = mCurMethodState;
  16791. methodState.mMethodInstance = methodInstance;
  16792. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  16793. if (methodInstance->GetCustomAttributes() != NULL)
  16794. {
  16795. int typeOptionsIdx = GenerateTypeOptions(methodInstance->GetCustomAttributes(), mCurTypeInstance, false);
  16796. if (typeOptionsIdx != -1)
  16797. methodState.mMethodTypeOptions = mSystem->GetTypeOptions(typeOptionsIdx);
  16798. }
  16799. BfTypeState typeState(mCurTypeInstance);
  16800. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  16801. bool isGenericVariation = (methodInstance->mIsUnspecializedVariation) || (mCurTypeInstance->IsUnspecializedTypeVariation());
  16802. BfMethodInstance* unspecializedMethodInstance = NULL;
  16803. if ((prevMethodState.mPrevVal != NULL) &&
  16804. ((methodState.mClosureState == NULL) || (methodState.mClosureState->mActiveDeferredLocalMethod == NULL)))
  16805. {
  16806. // This is 'inner' (probably a closure) - use binding from outer function
  16807. methodState.mGenericTypeBindings = prevMethodState.mPrevVal->mGenericTypeBindings;
  16808. }
  16809. else if ((methodInstance->mIsUnspecialized) ||
  16810. ((mCurTypeInstance->IsUnspecializedType()) && (!isGenericVariation)))
  16811. {
  16812. methodState.mGenericTypeBindings = &methodInstance->GetMethodInfoEx()->mGenericTypeBindings;
  16813. }
  16814. else if ((((methodInstance->mMethodInfoEx != NULL) && ((int)methodInstance->mMethodInfoEx->mMethodGenericArguments.size() > dependentGenericStartIdx)) ||
  16815. ((mCurTypeInstance->IsGenericTypeInstance()) && (!isGenericVariation || mIsComptimeModule) && (!methodInstance->mMethodDef->mIsLocalMethod) && (!methodInstance->mMethodDef->mDeclaringType->IsEmitted()))))
  16816. {
  16817. unspecializedMethodInstance = GetUnspecializedMethodInstance(methodInstance, !methodInstance->mMethodDef->mIsLocalMethod);
  16818. if ((mIsComptimeModule) && (!unspecializedMethodInstance->mHasBeenProcessed))
  16819. {
  16820. // This will have already been populated by CeMachine
  16821. methodState.mGenericTypeBindings = &methodInstance->GetMethodInfoEx()->mGenericTypeBindings;
  16822. }
  16823. else
  16824. {
  16825. BF_ASSERT(unspecializedMethodInstance != methodInstance);
  16826. if (!unspecializedMethodInstance->mHasBeenProcessed)
  16827. {
  16828. // Make sure the unspecialized method is processed so we can take its bindings
  16829. // Clear mCurMethodState so we don't think we're in a local method
  16830. SetAndRestoreValue<BfMethodState*> prevMethodState_Unspec(mCurMethodState, prevMethodState.mPrevVal);
  16831. if (unspecializedMethodInstance->mMethodProcessRequest == NULL)
  16832. unspecializedMethodInstance->mDeclModule->mIncompleteMethodCount++;
  16833. mContext->ProcessMethod(unspecializedMethodInstance);
  16834. }
  16835. methodState.mGenericTypeBindings = &unspecializedMethodInstance->GetMethodInfoEx()->mGenericTypeBindings;
  16836. }
  16837. }
  16838. if (methodDef->mMethodType == BfMethodType_Operator)
  16839. {
  16840. auto operatorDef = (BfOperatorDef*) methodDef;
  16841. BfAstNode* refNode = operatorDef->mOperatorDeclaration->mOperatorToken;
  16842. auto paramErrorRefNode = refNode;
  16843. if (operatorDef->mOperatorDeclaration->mOpenParen != NULL)
  16844. paramErrorRefNode = operatorDef->mOperatorDeclaration->mOpenParen;
  16845. if ((mCurMethodInstance->GetParamCount() > 0) && (mCurMethodInstance->GetParamTypeRef(0) != NULL))
  16846. paramErrorRefNode = mCurMethodInstance->GetParamTypeRef(0);
  16847. if (operatorDef->mOperatorDeclaration->mBinOp != BfBinaryOp_None)
  16848. {
  16849. if (methodDef->mParams.size() != 2)
  16850. {
  16851. Fail("Binary operators must declare two parameters", paramErrorRefNode);
  16852. }
  16853. else
  16854. {
  16855. auto checkParam0 = mCurMethodInstance->GetParamType(0);
  16856. if ((checkParam0->IsRef()) && (!checkParam0->IsOut()))
  16857. checkParam0 = checkParam0->GetUnderlyingType();
  16858. auto checkParam1 = mCurMethodInstance->GetParamType(1);
  16859. if ((checkParam1->IsRef()) && (!checkParam1->IsOut()))
  16860. checkParam1 = checkParam1->GetUnderlyingType();
  16861. if ((checkParam0 != mCurTypeInstance) && (!checkParam0->IsSelf()) &&
  16862. (checkParam1 != mCurTypeInstance) && (!checkParam1->IsSelf()))
  16863. {
  16864. Fail("At least one of the parameters of a binary operator must be the containing type", paramErrorRefNode);
  16865. }
  16866. }
  16867. BfType* wantType = NULL;
  16868. if (operatorDef->mOperatorDeclaration->mBinOp == BfBinaryOp_Compare)
  16869. {
  16870. wantType = GetPrimitiveType(BfTypeCode_IntPtr);
  16871. }
  16872. if ((wantType != NULL) && (methodInstance->mReturnType != wantType))
  16873. Fail(StrFormat("The return type for the '%s' operator must be '%s'", BfGetOpName(operatorDef->mOperatorDeclaration->mBinOp),
  16874. TypeToString(wantType).c_str()), operatorDef->mOperatorDeclaration->mReturnType);
  16875. }
  16876. else if (operatorDef->mOperatorDeclaration->mUnaryOp != BfUnaryOp_None)
  16877. {
  16878. if (methodDef->mIsStatic)
  16879. {
  16880. if (methodDef->mParams.size() != 1)
  16881. {
  16882. Fail("Unary operators must declare one parameter", paramErrorRefNode);
  16883. }
  16884. else
  16885. {
  16886. auto checkParam0 = mCurMethodInstance->GetParamType(0);
  16887. if ((checkParam0->IsRef()) && (!checkParam0->IsOut()))
  16888. checkParam0 = checkParam0->GetUnderlyingType();
  16889. if ((checkParam0 != mCurTypeInstance) && (!checkParam0->IsSelf()))
  16890. {
  16891. Fail("The parameter of a unary operator must be the containing type", paramErrorRefNode);
  16892. }
  16893. }
  16894. if (((operatorDef->mOperatorDeclaration->mUnaryOp == BfUnaryOp_Increment) ||
  16895. (operatorDef->mOperatorDeclaration->mUnaryOp == BfUnaryOp_Decrement)) &&
  16896. (!TypeIsSubTypeOf(mCurMethodInstance->mReturnType->ToTypeInstance(), mCurTypeInstance)))
  16897. {
  16898. Fail("The return type for the '++' or '--' operator must match the parameter type or be derived from the parameter type", operatorDef->mOperatorDeclaration->mReturnType);
  16899. }
  16900. }
  16901. else
  16902. {
  16903. if (methodDef->mParams.size() != 0)
  16904. {
  16905. Fail("Non-static unary operators not declare any parameters", paramErrorRefNode);
  16906. }
  16907. if (!mCurMethodInstance->mReturnType->IsVoid())
  16908. {
  16909. Fail("The return type for non-static operator must be 'void'", operatorDef->mOperatorDeclaration->mReturnType);
  16910. }
  16911. }
  16912. }
  16913. else if (operatorDef->mOperatorDeclaration->mAssignOp != BfAssignmentOp_None)
  16914. {
  16915. if (methodDef->mParams.size() != 1)
  16916. {
  16917. Fail("Assignment operators must declare one parameter", paramErrorRefNode);
  16918. }
  16919. if (!mCurMethodInstance->mReturnType->IsVoid())
  16920. {
  16921. Fail("The return type for assignment operator must be 'void'", operatorDef->mOperatorDeclaration->mReturnType);
  16922. }
  16923. }
  16924. else // Conversion
  16925. {
  16926. if (!operatorDef->mOperatorDeclaration->mIsConvOperator)
  16927. {
  16928. if (operatorDef->mOperatorDeclaration->mReturnType != NULL)
  16929. Fail("Conversion operators must declare their target type after the 'operator' token, not before", operatorDef->mOperatorDeclaration->mReturnType);
  16930. }
  16931. if (methodDef->mParams.size() != 1)
  16932. {
  16933. auto refNode = paramErrorRefNode;
  16934. if (!operatorDef->mOperatorDeclaration->mCommas.empty())
  16935. refNode = operatorDef->mOperatorDeclaration->mCommas[0];
  16936. Fail("Conversion operators must declare one parameter", refNode);
  16937. }
  16938. else if ((methodInstance->mMethodInfoEx == NULL) ||
  16939. (methodInstance->mMethodInfoEx->mMethodGenericArguments.IsEmpty()) ||
  16940. ((methodInstance->mIsUnspecialized) && (!methodInstance->mIsUnspecializedVariation)))
  16941. {
  16942. auto checkParam0 = mCurMethodInstance->GetParamType(0);
  16943. if ((checkParam0->IsRef()) && (!checkParam0->IsOut()))
  16944. checkParam0 = checkParam0->GetUnderlyingType();
  16945. if ((checkParam0 != mCurTypeInstance) && (!checkParam0->IsSelf()) &&
  16946. (mCurMethodInstance->mReturnType != mCurTypeInstance) && (!mCurMethodInstance->mReturnType->IsSelf()))
  16947. Fail("User-defined conversion must convert to or from the enclosing type", paramErrorRefNode);
  16948. if (checkParam0 == mCurMethodInstance->mReturnType)
  16949. Fail("User-defined operator cannot take an object of the enclosing type and convert to an object of the enclosing type", operatorDef->mOperatorDeclaration->mReturnType);
  16950. // On type lookup error we default to 'object', so don't do the 'base class' error if that may have
  16951. // happened here
  16952. if ((!mHadBuildError) || ((mCurMethodInstance->mReturnType != mContext->mBfObjectType) && (checkParam0 != mContext->mBfObjectType)))
  16953. {
  16954. auto isToBase = TypeIsSubTypeOf(mCurTypeInstance->mBaseType, mCurMethodInstance->mReturnType->ToTypeInstance());
  16955. bool isFromBase = TypeIsSubTypeOf(mCurTypeInstance->mBaseType, checkParam0->ToTypeInstance());
  16956. if ((mCurTypeInstance->IsObject()) && (isToBase || isFromBase))
  16957. Fail("User-defined conversions to or from a base class are not allowed", paramErrorRefNode);
  16958. else if ((mCurTypeInstance->IsStruct()) && (isToBase))
  16959. Fail("User-defined conversions to a base struct are not allowed", paramErrorRefNode);
  16960. }
  16961. }
  16962. }
  16963. }
  16964. bool wantsDIData = (mBfIRBuilder->DbgHasInfo()) && (!methodDef->IsEmptyPartial()) && (!mBfIRBuilder->mIgnoreWrites) && (mHasFullDebugInfo);
  16965. if (methodDef->mMethodType == BfMethodType_Mixin)
  16966. wantsDIData = false;
  16967. if ((mCurTypeInstance->IsBoxed()) && (methodDef->mMethodType != BfMethodType_Ctor))
  16968. wantsDIData = false;
  16969. bool wantsDIVariables = wantsDIData;
  16970. if (methodDef->mIsExtern)
  16971. wantsDIVariables = false;
  16972. SizedArray<BfIRMDNode, 8> diParams;
  16973. diParams.push_back(mBfIRBuilder->DbgGetType(methodInstance->mReturnType));
  16974. bool isThisStruct = mCurTypeInstance->IsStruct() && !mCurTypeInstance->IsTypedPrimitive();
  16975. BfType* thisType = NULL;
  16976. if (!methodDef->mIsStatic)
  16977. {
  16978. if ((methodState.mClosureState != NULL) && (methodState.mClosureState->mClosureType != NULL))
  16979. thisType = methodState.mClosureState->mClosureType;
  16980. else
  16981. thisType = mCurTypeInstance;
  16982. }
  16983. PopulateType(methodInstance->mReturnType, BfPopulateType_Data);
  16984. ProcessMethod_SetupParams(methodInstance, thisType, wantsDIData, &diParams);
  16985. //////////////////////////////////////////////////////////////////////////
  16986. //
  16987. {
  16988. if (methodDeclaration != NULL)
  16989. UpdateSrcPos(methodDeclaration, BfSrcPosFlag_NoSetDebugLoc);
  16990. else if (methodDef->mBody != NULL)
  16991. UpdateSrcPos(methodDef->mBody, BfSrcPosFlag_NoSetDebugLoc);
  16992. else if ((methodDef->mDeclaringType != NULL) && (methodDef->mDeclaringType->GetRefNode() != NULL))
  16993. UpdateSrcPos(methodDef->mDeclaringType->GetRefNode(), BfSrcPosFlag_NoSetDebugLoc);
  16994. else if (mCurTypeInstance->mTypeDef->mTypeDeclaration != NULL)
  16995. UpdateSrcPos(mCurTypeInstance->mTypeDef->mTypeDeclaration, BfSrcPosFlag_NoSetDebugLoc);
  16996. }
  16997. BfIRMDNode diFunction;
  16998. if (wantsDIData)
  16999. {
  17000. BP_ZONE("BfModule::DoMethodDeclaration.DISetup");
  17001. BfIRMDNode diFuncType = mBfIRBuilder->DbgCreateSubroutineType(diParams);
  17002. int defLine = mCurFilePosition.mCurLine;
  17003. if (mDICompileUnit)
  17004. {
  17005. int flags = 0;
  17006. BfIRMDNode funcScope = mBfIRBuilder->DbgGetTypeInst(mCurTypeInstance);
  17007. if (methodDef->mProtection == BfProtection_Public)
  17008. flags = llvm::DINode::FlagPublic;
  17009. else if (methodDef->mProtection == BfProtection_Protected)
  17010. flags = llvm::DINode::FlagProtected;
  17011. else
  17012. flags = llvm::DINode::FlagPrivate;
  17013. if (methodDef->mIsOverride)
  17014. {
  17015. //flags |= llvm::DINode::FlagVirtual;
  17016. }
  17017. else if (methodDef->mIsVirtual)
  17018. flags |= llvm::DINode::FlagIntroducedVirtual;
  17019. if ((methodDef->mIsStatic) || (methodDef->mMethodType == BfMethodType_Mixin))
  17020. flags |= llvm::DINode::FlagStaticMember;
  17021. else
  17022. {
  17023. if ((mCurTypeInstance->IsValuelessType()) ||
  17024. ((!mIsComptimeModule) && (mCurTypeInstance->IsSplattable())))
  17025. flags |= llvm::DINode::FlagStaticMember;
  17026. }
  17027. flags |= llvm::DINode::FlagPrototyped;
  17028. if (methodDef->mMethodType == BfMethodType_Ctor)
  17029. {
  17030. flags |= llvm::DINode::FlagArtificial;
  17031. }
  17032. auto llvmFunction = methodInstance->mIRFunction;
  17033. SizedArray<BfIRMDNode, 1> genericArgs;
  17034. SizedArray<BfIRValue, 1> genericConstValueArgs;
  17035. String methodName;
  17036. if (methodInstance->GetForeignType() != NULL)
  17037. {
  17038. methodName += TypeToString(methodInstance->GetForeignType());
  17039. methodName += ".";
  17040. }
  17041. if (methodInstance->GetExplicitInterface() != NULL)
  17042. {
  17043. methodName += TypeToString(methodInstance->GetExplicitInterface());
  17044. methodName += ".";
  17045. }
  17046. methodName += methodDef->mName;
  17047. if (methodInstance->GetNumGenericArguments() != 0)
  17048. {
  17049. for (auto genericArg : methodInstance->mMethodInfoEx->mMethodGenericArguments)
  17050. {
  17051. if (genericArg->IsConstExprValue())
  17052. {
  17053. BfConstExprValueType* constExprValueType = (BfConstExprValueType*)genericArg;
  17054. while (genericConstValueArgs.size() < genericArgs.size())
  17055. genericConstValueArgs.push_back(BfIRValue());
  17056. genericConstValueArgs.push_back(mBfIRBuilder->CreateConst(BfTypeCode_UInt64, constExprValueType->mValue.mUInt64));
  17057. genericArgs.push_back(mBfIRBuilder->DbgGetType(GetPrimitiveType(BfTypeCode_Int64)));
  17058. }
  17059. else
  17060. genericArgs.push_back(mBfIRBuilder->DbgGetType(genericArg));
  17061. }
  17062. methodName += "<";
  17063. for (int i = 0; i < (int)methodInstance->mMethodInfoEx->mMethodGenericArguments.size(); i++)
  17064. {
  17065. if (i > 0)
  17066. methodName += ", ";
  17067. BfType* type = methodInstance->mMethodInfoEx->mMethodGenericArguments[i];
  17068. methodName += TypeToString(type);
  17069. }
  17070. methodName += ">";
  17071. }
  17072. if ((methodName.empty()) && (methodDeclaration != NULL))
  17073. {
  17074. if (auto operatorDecl = BfNodeDynCast<BfOperatorDeclaration>(methodDeclaration))
  17075. {
  17076. methodName += "operator";
  17077. if (operatorDecl->mIsConvOperator)
  17078. {
  17079. methodName += " ";
  17080. methodName += TypeToString(methodInstance->mReturnType);
  17081. }
  17082. else if (operatorDecl->mOpTypeToken != NULL)
  17083. methodName += operatorDecl->mOpTypeToken->ToString();
  17084. }
  17085. }
  17086. if (methodDef->mCheckedKind == BfCheckedKind_Checked)
  17087. methodName += "$CHK";
  17088. else if (methodDef->mCheckedKind == BfCheckedKind_Unchecked)
  17089. methodName += "$UCHK";
  17090. methodState.mDIFile = mCurFilePosition.mFileInstance->mDIFile;
  17091. // diFunction = mBfIRBuilder->DbgCreateMethod(funcScope, methodName, mangledName, methodState.mDIFile,
  17092. // defLine + 1, diFuncType, false, true,
  17093. // (methodInstance->mVirtualTableIdx != -1) ? llvm::dwarf::DW_VIRTUALITY_virtual : llvm::dwarf::DW_VIRTUALITY_none,
  17094. // (methodInstance->mVirtualTableIdx != -1) ? methodInstance->DbgGetVirtualMethodNum() : 0,
  17095. // nullptr, flags, IsOptimized(), llvmFunction, genericArgs, genericConstValueArgs);
  17096. diFunction = mBfIRBuilder->DbgCreateMethod(funcScope, methodName, mangledName, methodState.mDIFile,
  17097. defLine + 1, diFuncType, false, true,
  17098. llvm::dwarf::DW_VIRTUALITY_none,
  17099. 0,
  17100. BfIRMDNode(), flags, IsOptimized(), llvmFunction, genericArgs, genericConstValueArgs);
  17101. }
  17102. else
  17103. {
  17104. methodState.mDIFile = mCurFilePosition.mFileInstance->mDIFile;
  17105. }
  17106. }
  17107. //////////////////////////////////////////////////////////////////////////
  17108. // Head and Init get rolled into Entry afterwards.
  17109. methodState.mIRFunction = methodInstance->mIRFunction;
  17110. methodState.mIRHeadBlock = mBfIRBuilder->CreateBlock("head", true);
  17111. methodState.mIRInitBlock = mBfIRBuilder->CreateBlock("init", true);
  17112. methodState.mIREntryBlock = mBfIRBuilder->CreateBlock("entry", true);
  17113. methodState.mCurScope->mDIScope = diFunction;
  17114. auto llvmEntryBlock = methodState.mIREntryBlock;
  17115. mBfIRBuilder->SetInsertPoint(llvmEntryBlock);
  17116. if (methodDef->mName == "__MALFORMED")
  17117. {
  17118. auto newBlock = mBfIRBuilder->CreateBlock("malformed", true);
  17119. mBfIRBuilder->SetInsertPoint(newBlock);
  17120. }
  17121. if (methodDef->mBody != NULL)
  17122. {
  17123. UpdateSrcPos(methodDef->mBody, BfSrcPosFlag_NoSetDebugLoc);
  17124. }
  17125. else if ((mHasFullDebugInfo) && (diFunction) && (typeDef->mTypeDeclaration != NULL))
  17126. {
  17127. // We want to be able to step into delegate invokes -- we actually step over them
  17128. if (methodDef->mName != "Invoke")
  17129. {
  17130. UpdateSrcPos(methodDef->mDeclaringType->GetRefNode());
  17131. mBfIRBuilder->DbgCreateAnnotation(diFunction, "StepOver", GetConstValue32(1));
  17132. }
  17133. }
  17134. // Clear out DebugLoc - to mark the ".addr" code as part of prologue
  17135. mBfIRBuilder->ClearDebugLocation();
  17136. bool isTypedPrimitiveFunc = mCurTypeInstance->IsTypedPrimitive() && (methodDef->mMethodType != BfMethodType_Ctor);
  17137. int irParamCount = methodInstance->GetIRFunctionParamCount(this);
  17138. if (methodInstance->GetImportKind() != BfImportKind_Import_Dynamic)
  17139. {
  17140. int localIdx = 0;
  17141. int argIdx = 0;
  17142. Array<BfIRValue> splatAddrValues;
  17143. for ( ; argIdx < irParamCount; localIdx++)
  17144. {
  17145. bool isThis = ((localIdx == 0) && (!mCurMethodInstance->mMethodDef->mIsStatic));
  17146. if ((isThis) && (thisType->IsValuelessType()))
  17147. isThis = false;
  17148. if ((!mIsComptimeModule) && (methodInstance->GetStructRetIdx() == argIdx))
  17149. {
  17150. argIdx++;
  17151. if (argIdx == irParamCount)
  17152. break;
  17153. }
  17154. BfLocalVariable* paramVar = NULL;
  17155. while (true)
  17156. {
  17157. BF_ASSERT(localIdx < methodState.mLocals.size());
  17158. paramVar = methodState.mLocals[localIdx];
  17159. if ((paramVar->mCompositeCount == -1) &&
  17160. ((!paramVar->mResolvedType->IsValuelessType()) || (paramVar->mResolvedType->IsMethodRef())))
  17161. break;
  17162. localIdx++;
  17163. }
  17164. if ((isThis) && (mCurTypeInstance->IsValueType()) && (methodDef->mMethodType != BfMethodType_Ctor) && (!methodDef->HasNoThisSplat()))
  17165. {
  17166. paramVar->mIsReadOnly = true;
  17167. }
  17168. bool wantsAddr = (wantsDIVariables) || (!paramVar->mIsReadOnly) ||
  17169. ((!mIsComptimeModule) && (paramVar->mResolvedType->GetLoweredType(BfTypeUsage_Parameter)));
  17170. if (paramVar->mResolvedType->IsMethodRef())
  17171. wantsAddr = false;
  17172. // if ((methodDef->mHasAppend) && (argIdx == 1))
  17173. // {
  17174. // BF_ASSERT(paramVar->mName == "appendIdx");
  17175. // wantsAddr = true;
  17176. // }
  17177. if (paramVar->mIsSplat)
  17178. {
  17179. auto prevInsert = mBfIRBuilder->GetInsertBlock();
  17180. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  17181. BfTypeUtils::SplatIterate([&](BfType* checkType)
  17182. {
  17183. BfIRType splatIRType;
  17184. if (checkType->IsComposite())
  17185. splatIRType = mBfIRBuilder->MapType(CreatePointerType(checkType));
  17186. else
  17187. splatIRType = mBfIRBuilder->MapType(checkType);
  17188. auto allocaInst = mBfIRBuilder->CreateAlloca(splatIRType);
  17189. mBfIRBuilder->SetAllocaAlignment(allocaInst, checkType->mAlign);
  17190. if (!paramVar->mAddr)
  17191. paramVar->mAddr = allocaInst;
  17192. if (WantsLifetimes())
  17193. mCurMethodState->mCurScope->mDeferredLifetimeEnds.push_back(allocaInst);
  17194. splatAddrValues.push_back(allocaInst);
  17195. }, paramVar->mResolvedType);
  17196. mBfIRBuilder->SetInsertPoint(prevInsert);
  17197. }
  17198. else if (isThis)
  17199. {
  17200. if (wantsAddr)
  17201. {
  17202. auto prevInsert = mBfIRBuilder->GetInsertBlock();
  17203. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  17204. BfIRType thisAddrType = mBfIRBuilder->MapType(thisType);
  17205. if (paramVar->mIsSplat)
  17206. {
  17207. //
  17208. }
  17209. else
  17210. {
  17211. bool wantPtr = (thisType->IsComposite()) && (!paramVar->mIsLowered);
  17212. if ((thisType->IsTypedPrimitive()) && (methodDef->HasNoThisSplat()))
  17213. wantPtr = true;
  17214. if (wantPtr)
  17215. {
  17216. thisAddrType = mBfIRBuilder->MapTypeInstPtr(thisType->ToTypeInstance());
  17217. }
  17218. auto allocaInst = mBfIRBuilder->CreateAlloca(thisAddrType);
  17219. mBfIRBuilder->SetName(allocaInst, paramVar->mName + ".addr");
  17220. mBfIRBuilder->SetAllocaAlignment(allocaInst, mSystem->mPtrSize);
  17221. paramVar->mAddr = allocaInst;
  17222. if (WantsLifetimes())
  17223. mCurMethodState->mCurScope->mDeferredLifetimeEnds.push_back(allocaInst);
  17224. }
  17225. mBfIRBuilder->SetInsertPoint(prevInsert);
  17226. }
  17227. }
  17228. else if ((!isThis) && ((paramVar->mIsStruct) || (paramVar->mResolvedType->IsRef())))
  17229. {
  17230. // Address doesn't change so we don't have to alloca it
  17231. BfIRType allocType;
  17232. int alignSize = mSystem->mPtrSize;
  17233. if (paramVar->mResolvedType->IsRef())
  17234. {
  17235. allocType = mBfIRBuilder->MapType(paramVar->mResolvedType);
  17236. }
  17237. else if ((paramVar->mIsSplat) || (paramVar->mIsLowered))
  17238. {
  17239. allocType = mBfIRBuilder->MapType(paramVar->mResolvedType);
  17240. alignSize = paramVar->mResolvedType->mAlign;
  17241. }
  17242. else
  17243. {
  17244. paramVar->mHasLocalStructBacking = true;
  17245. auto typeInst = paramVar->mResolvedType->ToTypeInstance();
  17246. if (typeInst != NULL)
  17247. allocType = mBfIRBuilder->MapTypeInstPtr(paramVar->mResolvedType->ToTypeInstance());
  17248. else
  17249. allocType = mBfIRBuilder->MapType(CreatePointerType(paramVar->mResolvedType));
  17250. }
  17251. if (wantsAddr)
  17252. {
  17253. auto prevInsert = mBfIRBuilder->GetInsertBlock();
  17254. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  17255. mBfIRBuilder->PopulateType(paramVar->mResolvedType);
  17256. auto allocaInst = mBfIRBuilder->CreateAlloca(allocType);
  17257. mBfIRBuilder->SetName(allocaInst, paramVar->mName + ".addr");
  17258. mBfIRBuilder->SetAllocaAlignment(allocaInst, alignSize);
  17259. paramVar->mAddr = allocaInst;
  17260. mBfIRBuilder->SetInsertPoint(prevInsert);
  17261. if (WantsLifetimes())
  17262. mCurMethodState->mCurScope->mDeferredLifetimeEnds.push_back(allocaInst);
  17263. }
  17264. }
  17265. else if (wantsAddr)
  17266. {
  17267. auto allocaInst = CreateAlloca(paramVar->mResolvedType);
  17268. mBfIRBuilder->SetName(allocaInst, paramVar->mName + ".addr");
  17269. paramVar->mAddr = allocaInst;
  17270. }
  17271. if (paramVar->mIsSplat)
  17272. {
  17273. BfTypeUtils::SplatIterate([&](BfType* checkType) { argIdx++; }, paramVar->mResolvedType);
  17274. }
  17275. else if (paramVar->mIsLowered)
  17276. {
  17277. BfTypeCode loweredTypeCode = BfTypeCode_None;
  17278. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  17279. paramVar->mResolvedType->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2);
  17280. argIdx++;
  17281. if (loweredTypeCode2 != BfTypeCode_None)
  17282. argIdx++;
  17283. }
  17284. else
  17285. {
  17286. argIdx++;
  17287. }
  17288. }
  17289. if (methodDef->mBody != NULL)
  17290. UpdateSrcPos(methodDef->mBody);
  17291. else if ((methodDef->mDeclaringType != NULL) && (methodDef->mDeclaringType->GetRefNode() != NULL))
  17292. UpdateSrcPos(methodDef->mDeclaringType->GetRefNode());
  17293. else if (mCurTypeInstance->mTypeDef->mTypeDeclaration != NULL)
  17294. UpdateSrcPos(mCurTypeInstance->mTypeDef->mTypeDeclaration);
  17295. localIdx = 0;
  17296. argIdx = 0;
  17297. int splatAddrIdx = 0;
  17298. while (localIdx < (int)methodState.mLocals.size())
  17299. {
  17300. if ((!mIsComptimeModule) && (argIdx == methodInstance->GetStructRetIdx()))
  17301. argIdx++;
  17302. int curLocalIdx = localIdx++;
  17303. BfLocalVariable* paramVar = methodState.mLocals[curLocalIdx];
  17304. if (!paramVar->IsParam())
  17305. continue;
  17306. if (paramVar->mCompositeCount != -1)
  17307. continue;
  17308. bool isThis = ((curLocalIdx == 0) && (!mCurMethodInstance->mMethodDef->mIsStatic));
  17309. if ((isThis) && (thisType->IsValuelessType()))
  17310. isThis = false;
  17311. if (paramVar->mValue.IsArg())
  17312. BF_ASSERT(paramVar->mValue.mId == argIdx);
  17313. BfIRMDNode diVariable;
  17314. if (wantsDIData)
  17315. {
  17316. String paramName = paramVar->mName;
  17317. BfIRMDNode diType = mBfIRBuilder->DbgGetType(paramVar->mResolvedType);
  17318. if (isThis)
  17319. {
  17320. if ((mCurMethodState->mClosureState != NULL) && (mCurMethodState->mClosureState->mClosureType != NULL))
  17321. paramName = "__closure";
  17322. if ((paramVar->mResolvedType->IsValueType()) && (!paramVar->mIsSplat) && (!paramVar->mIsLowered))
  17323. {
  17324. diType = mBfIRBuilder->DbgGetType(paramVar->mResolvedType);
  17325. bool wantRef = paramVar->mResolvedType->IsComposite();
  17326. if ((paramVar->mResolvedType->IsTypedPrimitive()) && (methodDef->HasNoThisSplat()))
  17327. wantRef = true;
  17328. if (wantRef)
  17329. diType = mBfIRBuilder->DbgCreateReferenceType(diType);
  17330. }
  17331. else if (!paramVar->mResolvedType->IsValueType())
  17332. {
  17333. diType = mBfIRBuilder->DbgCreateArtificialType(diType);
  17334. }
  17335. }
  17336. else
  17337. {
  17338. if ((paramVar->mResolvedType->IsComposite()) && (!paramVar->mIsSplat) && (!paramVar->mIsLowered))
  17339. {
  17340. diType = mBfIRBuilder->DbgGetType(paramVar->mResolvedType);
  17341. diType = mBfIRBuilder->DbgCreateReferenceType(diType);
  17342. diType = mBfIRBuilder->DbgCreateConstType(diType);
  17343. }
  17344. }
  17345. if (!paramVar->mIsSplat)
  17346. {
  17347. if (paramVar->mResolvedType->IsValuelessType())
  17348. {
  17349. diVariable = mBfIRBuilder->DbgCreateAutoVariable(diFunction,
  17350. paramName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType);
  17351. }
  17352. else if (paramVar->mIsImplicitParam)
  17353. {
  17354. // Annotate this specially?
  17355. diVariable = mBfIRBuilder->DbgCreateParameterVariable(diFunction,
  17356. paramName, argIdx + 1, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType, true, 0);
  17357. }
  17358. else
  17359. {
  17360. diVariable = mBfIRBuilder->DbgCreateParameterVariable(diFunction,
  17361. paramName, argIdx + 1, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType, true, 0);
  17362. }
  17363. paramVar->mDbgVarInst = diVariable;
  17364. }
  17365. else if ((paramVar->mIsSplat) && (paramVar->mResolvedType->GetSplatCount() == 0))
  17366. {
  17367. // if ((mBfIRBuilder->HasDebugLocation()) && (wantsDIVariables))
  17368. // {
  17369. // // Only add this placeholder if we don't have any values
  17370. // auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(mCurMethodState->mCurScope->mDIScope,
  17371. // paramName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType);
  17372. // mBfIRBuilder->DbgInsertValueIntrinsic(GetConstValue(0), diVariable);
  17373. // }
  17374. }
  17375. }
  17376. bool isTypedPrimCtor = mCurTypeInstance->IsTypedPrimitive() && (methodDef->mMethodType == BfMethodType_Ctor);
  17377. if ((!paramVar->mParamFailed) && (paramVar->mAddr))
  17378. {
  17379. // Write our argument value into the .addr
  17380. mBfIRBuilder->ClearDebugLocation();
  17381. if (paramVar->mIsSplat)
  17382. {
  17383. mBfIRBuilder->PopulateType(paramVar->mResolvedType);
  17384. //
  17385. }
  17386. else
  17387. {
  17388. bool handled = false;
  17389. if (paramVar->mIsLowered)
  17390. {
  17391. BfTypeCode loweredTypeCode = BfTypeCode_None;
  17392. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  17393. if (paramVar->mResolvedType->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2))
  17394. {
  17395. // We have a lowered type coming in, so we have to cast the .addr before storing
  17396. auto primType = mBfIRBuilder->GetPrimitiveType(loweredTypeCode);
  17397. auto primPtrType = mBfIRBuilder->GetPointerTo(primType);
  17398. auto primPtrVal = mBfIRBuilder->CreateBitCast(paramVar->mAddr, primPtrType);
  17399. mBfIRBuilder->CreateStore(paramVar->mValue, primPtrVal);
  17400. if (loweredTypeCode2 != BfTypeCode_None)
  17401. {
  17402. auto primType2 = mBfIRBuilder->GetPrimitiveType(loweredTypeCode2);
  17403. auto primPtrType2 = mBfIRBuilder->GetPointerTo(primType2);
  17404. BfIRValue primPtrVal2;
  17405. if (mBfIRBuilder->GetSize(loweredTypeCode) < mBfIRBuilder->GetSize(loweredTypeCode2))
  17406. primPtrVal2 = mBfIRBuilder->CreateInBoundsGEP(mBfIRBuilder->CreateBitCast(primPtrVal, primPtrType2), 1);
  17407. else
  17408. primPtrVal2 = mBfIRBuilder->CreateBitCast(mBfIRBuilder->CreateInBoundsGEP(primPtrVal, 1), primPtrType2);
  17409. mBfIRBuilder->CreateStore(mBfIRBuilder->GetArgument(argIdx + 1), primPtrVal2);
  17410. }
  17411. // We don't want to allow directly using value
  17412. paramVar->mValue = BfIRValue();
  17413. handled = true;
  17414. }
  17415. else
  17416. {
  17417. BF_ASSERT("Expected lowered");
  17418. }
  17419. }
  17420. if (!handled)
  17421. mBfIRBuilder->CreateAlignedStore(paramVar->mValue, paramVar->mAddr, paramVar->mResolvedType->mAlign);
  17422. }
  17423. }
  17424. if (methodDef->mBody != NULL)
  17425. UpdateSrcPos(methodDef->mBody);
  17426. else if (methodDef->mDeclaringType->mTypeDeclaration != NULL)
  17427. UpdateSrcPos(methodDef->mDeclaringType->mTypeDeclaration);
  17428. else if (methodDeclaration == NULL)
  17429. UseDefaultSrcPos();
  17430. // Write our argument value into the .addr
  17431. if (paramVar->mIsSplat)
  17432. {
  17433. int splatComponentIdx = 0;
  17434. auto curArgIdx = argIdx;
  17435. auto _FinishSplats = [&] (BfType* checkType, const StringImpl& name)
  17436. {
  17437. BfIRValue splatAddrValue = splatAddrValues[splatAddrIdx++];
  17438. methodState.mSplatDecompAddrs.push_back(splatAddrValue);
  17439. auto storeInst = mBfIRBuilder->CreateAlignedStore(mBfIRBuilder->GetArgument(curArgIdx), splatAddrValue, checkType->mAlign);
  17440. mBfIRBuilder->ClearDebugLocation(storeInst);
  17441. if (wantsDIData)
  17442. {
  17443. BfIRMDNode diType;
  17444. if (checkType->IsComposite())
  17445. diType = mBfIRBuilder->DbgGetType(CreateRefType(checkType));
  17446. else
  17447. diType = mBfIRBuilder->DbgGetType(checkType);
  17448. auto diVariable = mBfIRBuilder->DbgCreateParameterVariable(diFunction,
  17449. name, curArgIdx + 1, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType);
  17450. if (wantsDIVariables)
  17451. {
  17452. mBfIRBuilder->DbgInsertDeclare(splatAddrValue, diVariable);
  17453. }
  17454. }
  17455. curArgIdx++;
  17456. splatComponentIdx++;
  17457. };
  17458. std::function<void(BfType*, const StringImpl&)> _FinishSplatsIterate = [&](BfType* checkType, const StringImpl& name)
  17459. {
  17460. if (checkType->IsStruct())
  17461. {
  17462. auto checkTypeInstance = checkType->ToTypeInstance();
  17463. if (checkTypeInstance->mBaseType != NULL)
  17464. {
  17465. _FinishSplatsIterate(checkTypeInstance->mBaseType, name + "$b");
  17466. }
  17467. if (checkTypeInstance->mIsUnion)
  17468. {
  17469. auto unionInnerType = checkTypeInstance->GetUnionInnerType();
  17470. if (!unionInnerType->IsValuelessType())
  17471. {
  17472. _FinishSplatsIterate(unionInnerType, name + "$u");
  17473. }
  17474. if (checkTypeInstance->IsEnum())
  17475. {
  17476. auto dscrType = checkTypeInstance->GetDiscriminatorType();
  17477. _FinishSplatsIterate(dscrType, name + "$d");
  17478. }
  17479. }
  17480. else
  17481. {
  17482. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  17483. {
  17484. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  17485. auto fieldDef = fieldInstance->GetFieldDef();
  17486. if (fieldInstance->mDataIdx >= 0)
  17487. {
  17488. _FinishSplatsIterate(fieldInstance->GetResolvedType(), name + "$m$" + fieldDef->mName);
  17489. }
  17490. }
  17491. }
  17492. }
  17493. else if (checkType->IsMethodRef())
  17494. {
  17495. auto methodRefType = (BfMethodRefType*)checkType;
  17496. BfMethodInstance* methodInstance = methodRefType->mMethodRef;
  17497. // int implicitParamCount = methodInstance->GetImplicitParamCount();
  17498. // for (int implicitParamIdx = methodInstance->HasThis() ? -1 : 0; implicitParamIdx < implicitParamCount; implicitParamIdx++)
  17499. // {
  17500. // auto paramType = methodInstance->GetParamType(implicitParamIdx);
  17501. // if (!paramType->IsValuelessType())
  17502. // _FinishSplats(paramType, name + "$m$" + methodInstance->GetParamName(implicitParamIdx));
  17503. // }
  17504. for (int dataIdx = 0; dataIdx < methodRefType->GetCaptureDataCount(); dataIdx++)
  17505. {
  17506. int paramIdx = methodRefType->GetParamIdxFromDataIdx(dataIdx);
  17507. String paramName = methodInstance->GetParamName(paramIdx);
  17508. if (paramName == "this")
  17509. paramName = "__this";
  17510. if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  17511. {
  17512. _FinishSplatsIterate(methodRefType->GetCaptureType(dataIdx), name + "$m$" + paramName);
  17513. }
  17514. else
  17515. {
  17516. _FinishSplats(methodRefType->GetCaptureType(dataIdx), name + "$m$" + paramName);
  17517. }
  17518. }
  17519. }
  17520. else if (!checkType->IsValuelessType())
  17521. {
  17522. _FinishSplats(checkType, name);
  17523. }
  17524. };
  17525. mBfIRBuilder->PopulateType(paramVar->mResolvedType);
  17526. if (!paramVar->mConstValue)
  17527. _FinishSplatsIterate(paramVar->mResolvedType, "$" + paramVar->mName);
  17528. }
  17529. BfIRValue declareCall;
  17530. if (diVariable)
  17531. {
  17532. if ((mBfIRBuilder->HasDebugLocation()) && (wantsDIVariables))
  17533. {
  17534. if (!paramVar->mAddr)
  17535. {
  17536. if ((!paramVar->mValue) || (paramVar->mValue.IsFake()))
  17537. {
  17538. if ((!paramVar->mIsThis) && (mCompiler->mOptions.mToolsetType != BfToolsetType_GNU)) // DWARF chokes on this:
  17539. {
  17540. // We don't need to set the location for this
  17541. mBfIRBuilder->DbgInsertValueIntrinsic(BfIRValue(), diVariable);
  17542. }
  17543. }
  17544. else
  17545. declareCall = mBfIRBuilder->DbgInsertDeclare(paramVar->mValue, diVariable);
  17546. }
  17547. else
  17548. {
  17549. declareCall = mBfIRBuilder->DbgInsertDeclare(paramVar->mAddr, diVariable);
  17550. }
  17551. }
  17552. }
  17553. if ((isThis) && (!paramVar->mIsSplat) && (paramVar->mAddr))
  17554. {
  17555. // We don't allow actually assignment to "this", so we just do a single load
  17556. // Keep in mind we don't use the ACTUAL mValue value because that's a register, but
  17557. // we need to store it in the stack frame for debugging purposes
  17558. auto loadedThis = mBfIRBuilder->CreateLoad(paramVar->mAddr/*, "this"*/);
  17559. mBfIRBuilder->ClearDebugLocation(loadedThis);
  17560. paramVar->mValue = loadedThis;
  17561. }
  17562. if ((wantsDIData) && (declareCall))
  17563. mBfIRBuilder->UpdateDebugLocation(declareCall);
  17564. if (paramVar->mIsSplat)
  17565. {
  17566. BfTypeUtils::SplatIterate([&](BfType* checkType) { argIdx++; }, paramVar->mResolvedType);
  17567. }
  17568. else if (paramVar->mIsLowered)
  17569. {
  17570. argIdx++;
  17571. BfTypeCode loweredTypeCode = BfTypeCode_None;
  17572. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  17573. paramVar->mResolvedType->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2);
  17574. if (loweredTypeCode2 != BfTypeCode_None)
  17575. argIdx++;
  17576. }
  17577. else if (!paramVar->mResolvedType->IsValuelessType())
  17578. {
  17579. argIdx++;
  17580. }
  17581. }
  17582. if (wantsDIData)
  17583. {
  17584. BF_ASSERT(splatAddrIdx == (int)splatAddrValues.size());
  17585. }
  17586. }
  17587. for (int varIdx = 0; varIdx < (int)mCurMethodState->mLocals.size(); varIdx++)
  17588. {
  17589. auto paramVar = mCurMethodState->mLocals[varIdx];
  17590. // 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
  17591. // splat member. If the "splat" is valueless then we do create a placeholder, but further up in this method
  17592. // if (paramVar->mIsSplat)
  17593. // {
  17594. // if (wantsDIVariables)
  17595. // {
  17596. // auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(diFunction, paramVar->mName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, mBfIRBuilder->DbgGetType(paramVar->mResolvedType));
  17597. // mBfIRBuilder->DbgInsertValueIntrinsic(mBfIRBuilder->CreateConst(BfTypeCode_Int64, 0), diVariable);
  17598. // }
  17599. // }
  17600. if (paramVar->mResolvedType->IsValuelessType())
  17601. {
  17602. if ((mBfIRBuilder->HasDebugLocation()) && (wantsDIVariables) && (mCompiler->mOptions.mToolsetType != BfToolsetType_GNU)) // DWARF chokes on this:
  17603. {
  17604. // Only add this placeholder if we don't have any values
  17605. auto diType = mBfIRBuilder->DbgGetType(paramVar->mResolvedType);
  17606. auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(mCurMethodState->mCurScope->mDIScope,
  17607. paramVar->mName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType);
  17608. mBfIRBuilder->DbgInsertValueIntrinsic(BfIRValue(), diVariable);
  17609. }
  17610. }
  17611. }
  17612. if (IsTargetingBeefBackend())
  17613. mCurMethodState->mCurScope->mValueScopeStart = mBfIRBuilder->CreateValueScopeStart();
  17614. if (methodState.mClosureState != NULL)
  17615. {
  17616. for (auto& constLocal : methodState.mClosureState->mConstLocals)
  17617. {
  17618. BfLocalVariable* localVar = new BfLocalVariable();
  17619. *localVar = constLocal;
  17620. AddLocalVariableDef(localVar, true);
  17621. }
  17622. }
  17623. bool wantsRemoveBody = false;
  17624. bool skipBody = false;
  17625. bool skipUpdateSrcPos = false;
  17626. bool skipEndChecks = false;
  17627. bool hasExternSpecifier = (methodDeclaration != NULL) && (methodDeclaration->mExternSpecifier != NULL) && (methodInstance->GetImportKind() != BfImportKind_Import_Dynamic);
  17628. auto propertyDeclaration = methodDef->GetPropertyDeclaration();
  17629. if ((methodDef != NULL) && (propertyDeclaration != NULL) && (propertyDeclaration->mExternSpecifier != NULL))
  17630. hasExternSpecifier = true;
  17631. // Allocate, clear, set classVData
  17632. if ((methodDef->mMethodType == BfMethodType_Ctor) && (methodDef->mIsStatic))
  17633. {
  17634. CreateStaticCtor();
  17635. }
  17636. else if ((mCurTypeInstance->IsBoxed()) && (methodDef->mMethodType != BfMethodType_Ctor) && (methodDef->mName != BF_METHODNAME_DYNAMICCAST) && (methodDef->mName != BF_METHODNAME_DYNAMICCAST_INTERFACE))
  17637. {
  17638. skipBody = true;
  17639. skipEndChecks = true;
  17640. if (HasExecutedOutput())
  17641. {
  17642. // Clear out DebugLoc - to mark the ".addr" code as part of prologue
  17643. mBfIRBuilder->ClearDebugLocation();
  17644. BfBoxedType* boxedType = (BfBoxedType*) mCurTypeInstance;
  17645. BfTypeInstance* innerType = boxedType->mElementType->ToTypeInstance();
  17646. PopulateType(innerType, BfPopulateType_DataAndMethods);
  17647. mBfIRBuilder->PopulateType(mCurTypeInstance);
  17648. BfGetMethodInstanceFlags flags = BfGetMethodInstanceFlag_None;
  17649. if (methodInstance->mIsForeignMethodDef)
  17650. {
  17651. flags = BfGetMethodInstanceFlag_ForeignMethodDef;
  17652. }
  17653. BfTypeVector methodGenericArguments;
  17654. if (methodInstance->mMethodInfoEx != NULL)
  17655. methodGenericArguments = methodInstance->mMethodInfoEx->mMethodGenericArguments;
  17656. auto innerMethodInstance = GetMethodInstance(innerType, methodDef, methodGenericArguments, flags, methodInstance->GetForeignType());
  17657. if (innerMethodInstance.mMethodInstance->IsSkipCall())
  17658. {
  17659. if (!methodInstance->mReturnType->IsValuelessType())
  17660. {
  17661. auto retVal = GetDefaultValue(methodInstance->mReturnType);
  17662. CreateReturn(retVal);
  17663. }
  17664. else
  17665. mBfIRBuilder->CreateRetVoid();
  17666. }
  17667. else
  17668. {
  17669. auto innerMethodDef = innerMethodInstance.mMethodInstance->mMethodDef;
  17670. BF_ASSERT(innerMethodDef == methodDef);
  17671. SizedArray<BfIRValue, 8> innerParams;
  17672. BfExprEvaluator exprEvaluator(this);
  17673. if (!innerType->IsValuelessType())
  17674. {
  17675. BfIRValue thisValue = mBfIRBuilder->CreateInBoundsGEP(mCurMethodState->mLocals[0]->mValue, 0, 1);
  17676. BfTypedValue innerVal(thisValue, innerType, true);
  17677. if (boxedType->IsBoxedStructPtr())
  17678. {
  17679. innerVal = LoadValue(innerVal);
  17680. innerVal = BfTypedValue(innerVal.mValue, innerType, true);
  17681. }
  17682. exprEvaluator.PushThis(NULL, innerVal, innerMethodInstance.mMethodInstance, innerParams);
  17683. }
  17684. for (int i = 1; i < (int)mCurMethodState->mLocals.size(); i++)
  17685. {
  17686. BfLocalVariable* localVar = mCurMethodState->mLocals[i];
  17687. BfTypedValue localVal = exprEvaluator.LoadLocal(localVar, true);
  17688. exprEvaluator.PushArg(localVal, innerParams);
  17689. }
  17690. if (!innerMethodInstance.mFunc)
  17691. {
  17692. BF_ASSERT(innerType->IsUnspecializedType());
  17693. }
  17694. else if ((!mIsComptimeModule) && (methodInstance->GetStructRetIdx() != -1))
  17695. {
  17696. mBfIRBuilder->PopulateType(methodInstance->mReturnType);
  17697. auto returnType = BfTypedValue(mBfIRBuilder->GetArgument(methodInstance->GetStructRetIdx()), methodInstance->mReturnType, true);
  17698. exprEvaluator.mReceivingValue = &returnType;
  17699. auto retVal = exprEvaluator.CreateCall(NULL, innerMethodInstance.mMethodInstance, innerMethodInstance.mFunc, true, innerParams, NULL, BfCreateCallFlags_TailCall);
  17700. BF_ASSERT(exprEvaluator.mReceivingValue == NULL); // Ensure it was actually used
  17701. mBfIRBuilder->CreateRetVoid();
  17702. }
  17703. else
  17704. {
  17705. mBfIRBuilder->PopulateType(methodInstance->mReturnType);
  17706. auto retVal = exprEvaluator.CreateCall(NULL, innerMethodInstance.mMethodInstance, innerMethodInstance.mFunc, true, innerParams, NULL, BfCreateCallFlags_TailCall);
  17707. if (mCurMethodInstance->mReturnType->IsValueType())
  17708. retVal = LoadValue(retVal);
  17709. CreateReturn(retVal.mValue);
  17710. }
  17711. }
  17712. }
  17713. mCurMethodState->SetHadReturn(true);
  17714. mCurMethodState->mLeftBlockUncond = true;
  17715. }
  17716. else if (methodDef->mMethodType == BfMethodType_CtorClear)
  17717. {
  17718. SetIllegalSrcPos();
  17719. mBfIRBuilder->ClearDebugLocation();
  17720. PopulateType(mCurTypeInstance, BfPopulateType_Data);
  17721. auto thisVal = GetThis();
  17722. int prevSize = 0;
  17723. if (mContext->mBfObjectType != NULL)
  17724. {
  17725. prevSize = mContext->mBfObjectType->mInstSize;
  17726. PopulateType(mContext->mBfObjectType);
  17727. // If we have object extensions, clear out starting at the extension
  17728. for (auto& fieldInstance : mContext->mBfObjectType->mFieldInstances)
  17729. {
  17730. if (fieldInstance.GetFieldDef()->mDeclaringType->IsExtension())
  17731. {
  17732. prevSize = fieldInstance.mDataOffset;
  17733. break;
  17734. }
  17735. }
  17736. }
  17737. int curSize = mCurTypeInstance->mInstSize;
  17738. if (curSize > prevSize)
  17739. {
  17740. auto int8PtrType = CreatePointerType(GetPrimitiveType(BfTypeCode_Int8));
  17741. auto int8PtrVal = mBfIRBuilder->CreateBitCast(thisVal.mValue, mBfIRBuilder->MapType(int8PtrType));
  17742. int8PtrVal = mBfIRBuilder->CreateInBoundsGEP(int8PtrVal, GetConstValue(prevSize));
  17743. mBfIRBuilder->CreateMemSet(int8PtrVal, GetConstValue8(0), GetConstValue(curSize - prevSize), GetConstValue(mCurTypeInstance->mInstAlign));
  17744. }
  17745. skipUpdateSrcPos = true;
  17746. }
  17747. else if (((methodDef->mMethodType == BfMethodType_Ctor) || (methodDef->mMethodType == BfMethodType_CtorNoBody)) && (!hasExternSpecifier))
  17748. {
  17749. EmitCtorBody(skipBody);
  17750. }
  17751. else if ((methodDef->mMethodType == BfMethodType_Dtor) && (!hasExternSpecifier))
  17752. {
  17753. EmitDtorBody();
  17754. skipBody = true;
  17755. }
  17756. if ((!mCurTypeInstance->IsBoxed()) && (methodDeclaration != NULL) && (methodDeclaration->mHadYield) && (methodDef->mBody != NULL))
  17757. {
  17758. EmitIteratorBlock(skipBody);
  17759. }
  17760. if (methodDef->mName == BF_METHODNAME_MARKMEMBERS)
  17761. {
  17762. // We need to be able to mark deleted objects
  17763. mCurMethodState->mIgnoreObjectAccessCheck = true;
  17764. }
  17765. auto customAttributes = methodInstance->GetCustomAttributes();
  17766. if (customAttributes != NULL)
  17767. {
  17768. if (customAttributes->Contains(mCompiler->mDisableObjectAccessChecksAttributeTypeDef))
  17769. mCurMethodState->mIgnoreObjectAccessCheck = true;
  17770. if (customAttributes->Contains(mCompiler->mDisableChecksAttributeTypeDef))
  17771. mCurMethodState->mDisableChecks = true;
  17772. }
  17773. if ((methodDef->mMethodType == BfMethodType_CtorNoBody) && (!methodDef->mIsStatic) &&
  17774. ((methodInstance->mChainType == BfMethodChainType_ChainHead) || (methodInstance->mChainType == BfMethodChainType_None)))
  17775. {
  17776. // We chain even non-default ctors to the default ctors
  17777. auto defaultCtor = methodInstance;
  17778. if (defaultCtor->mChainType == BfMethodChainType_ChainHead)
  17779. CallChainedMethods(defaultCtor, false);
  17780. }
  17781. auto bodyBlock = BfNodeDynCast<BfBlock>(methodDef->mBody);
  17782. if (!mCompiler->mHasRequiredTypes)
  17783. {
  17784. // Skip processing to avoid errors
  17785. }
  17786. else if (methodDef->mBody == NULL)
  17787. {
  17788. if (methodDeclaration != NULL)
  17789. {
  17790. if (auto operatorDeclaration = BfNodeDynCast<BfOperatorDeclaration>(methodDeclaration))
  17791. {
  17792. if (operatorDeclaration->mIsConvOperator)
  17793. wantsRemoveBody = true;
  17794. }
  17795. }
  17796. bool isDllImport = false;
  17797. if ((importKind == BfImportKind_Import_Static) || (importKind == BfImportKind_Import_Dynamic))
  17798. {
  17799. if (importStrNum != -1)
  17800. {
  17801. if (importKind == BfImportKind_Import_Static)
  17802. {
  17803. if (!mImportFileNames.Contains(importStrNum))
  17804. {
  17805. mImportFileNames.Add(importStrNum);
  17806. }
  17807. }
  17808. }
  17809. }
  17810. else if (methodInstance->GetImportKind() == BfImportKind_Import_Dynamic)
  17811. {
  17812. CreateDllImportMethod();
  17813. }
  17814. else if (((mCurTypeInstance->mTypeDef->mIsDelegate) || (mCurTypeInstance->mTypeDef->mIsFunction)) &&
  17815. (methodDef->mName == "Invoke") && (methodDef->mMethodType == BfMethodType_Normal))
  17816. {
  17817. if (mCurTypeInstance->mTypeDef->mIsFunction)
  17818. {
  17819. // Emit nothing
  17820. }
  17821. else
  17822. {
  17823. CreateDelegateInvokeMethod();
  17824. mCurMethodState->SetHadReturn(true);
  17825. mCurMethodState->mLeftBlockUncond = true;
  17826. }
  17827. }
  17828. else if ((methodDef->mName == BF_METHODNAME_DYNAMICCAST) || (methodDef->mName == BF_METHODNAME_DYNAMICCAST_INTERFACE))
  17829. {
  17830. if (mCurTypeInstance->IsObject())
  17831. {
  17832. CreateDynamicCastMethod();
  17833. }
  17834. else
  17835. {
  17836. mBfIRBuilder->CreateRet(GetDefaultValue(methodInstance->mReturnType));
  17837. mCurMethodState->mHadReturn = true;
  17838. }
  17839. }
  17840. else if ((methodDef->mName == BF_METHODNAME_ENUM_HASFLAG) && (mCurTypeInstance->IsEnum()) && (!mCurTypeInstance->IsBoxed()))
  17841. {
  17842. BfIRValue ret;
  17843. if (mCurMethodState->mLocals[1]->mResolvedType != mCurTypeInstance)
  17844. {
  17845. // This can happen if we provide an invalid name
  17846. AssertErrorState();
  17847. ret = mBfIRBuilder->CreateRet(GetDefaultValue(GetPrimitiveType(BfTypeCode_Boolean)));
  17848. }
  17849. else
  17850. {
  17851. // Unfortunate DebugLoc shenanigans-
  17852. // 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,
  17853. // so we only set the loc on the CreateRet which gets inlined out
  17854. mBfIRBuilder->SaveDebugLocation();
  17855. mBfIRBuilder->ClearDebugLocation();
  17856. BfIRValue fromBool;
  17857. if (!mCurTypeInstance->IsTypedPrimitive())
  17858. {
  17859. fromBool = GetDefaultValue(methodInstance->mReturnType);
  17860. }
  17861. else
  17862. {
  17863. auto andResult = mBfIRBuilder->CreateAnd(mCurMethodState->mLocals[0]->mValue, mCurMethodState->mLocals[1]->mValue);
  17864. auto toBool = mBfIRBuilder->CreateCmpNE(andResult, GetDefaultValue(mCurMethodState->mLocals[0]->mResolvedType));
  17865. fromBool = mBfIRBuilder->CreateNumericCast(toBool, false, BfTypeCode_Boolean);
  17866. }
  17867. mBfIRBuilder->RestoreDebugLocation();
  17868. ret = mBfIRBuilder->CreateRet(fromBool);
  17869. //ExtendLocalLifetimes(0);
  17870. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  17871. }
  17872. mCurMethodState->SetHadReturn(true);
  17873. mCurMethodState->mLeftBlockUncond = true;
  17874. }
  17875. else if (((methodDef->mName == BF_METHODNAME_ENUM_GETUNDERLYINGREF) || (methodDef->mName == BF_METHODNAME_ENUM_GETUNDERLYING)) &&
  17876. (mCurTypeInstance->IsEnum()) && (!mCurTypeInstance->IsBoxed()))
  17877. {
  17878. BfIRValue ret;
  17879. // Unfortunate DebugLoc shenanigans-
  17880. // 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,
  17881. // so we only set the loc on the CreateRet which gets inlined out
  17882. mBfIRBuilder->SaveDebugLocation();
  17883. mBfIRBuilder->ClearDebugLocation();
  17884. BfIRValue fromBool;
  17885. mBfIRBuilder->RestoreDebugLocation();
  17886. ret = mBfIRBuilder->CreateRet(GetThis().mValue);
  17887. //ExtendLocalLifetimes(0);
  17888. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  17889. mCurMethodState->SetHadReturn(true);
  17890. mCurMethodState->mLeftBlockUncond = true;
  17891. }
  17892. else if ((mCurTypeInstance->IsEnum()) && (!mCurTypeInstance->IsBoxed()) && (methodDef->mName == BF_METHODNAME_TO_STRING))
  17893. {
  17894. auto enumType = ResolveTypeDef(mCompiler->mEnumTypeDef);
  17895. if (HasExecutedOutput())
  17896. {
  17897. EmitEnumToStringBody();
  17898. }
  17899. mBfIRBuilder->CreateRetVoid();
  17900. mCurMethodState->SetHadReturn(true);
  17901. mCurMethodState->mLeftBlockUncond = true;
  17902. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  17903. }
  17904. else if ((mCurTypeInstance->IsTuple()) && (!mCurTypeInstance->IsBoxed()) && (methodDef->mName == BF_METHODNAME_TO_STRING))
  17905. {
  17906. auto enumType = ResolveTypeDef(mCompiler->mEnumTypeDef);
  17907. if (HasExecutedOutput())
  17908. {
  17909. EmitTupleToStringBody();
  17910. }
  17911. mBfIRBuilder->CreateRetVoid();
  17912. mCurMethodState->SetHadReturn(true);
  17913. mCurMethodState->mLeftBlockUncond = true;
  17914. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  17915. }
  17916. else if (methodDef->mName == BF_METHODNAME_DEFAULT_EQUALS)
  17917. {
  17918. CreateValueTypeEqualsMethod(false);
  17919. skipBody = true;
  17920. skipEndChecks = true;
  17921. }
  17922. else if (methodDef->mName == BF_METHODNAME_DEFAULT_STRICT_EQUALS)
  17923. {
  17924. CreateValueTypeEqualsMethod(true);
  17925. skipBody = true;
  17926. skipEndChecks = true;
  17927. }
  17928. else if ((methodDef->mName == BF_METHODNAME_EQUALS) && (typeDef->GetDefinition() == mCompiler->mValueTypeTypeDef))
  17929. {
  17930. CreateValueTypeEqualsMethod(false);
  17931. skipBody = true;
  17932. skipEndChecks = true;
  17933. }
  17934. else if ((methodDef->mName == BF_METHODNAME_EQUALS) && (mCurTypeInstance->IsDelegate()))
  17935. {
  17936. CreateDelegateEqualsMethod();
  17937. skipBody = true;
  17938. skipEndChecks = true;
  17939. }
  17940. else
  17941. {
  17942. auto propertyDeclaration = methodDef->GetPropertyDeclaration();
  17943. if ((propertyDeclaration != NULL) && (!typeDef->HasAutoProperty(propertyDeclaration)))
  17944. {
  17945. if ((!mCurTypeInstance->IsInterface()) && (!hasExternSpecifier))
  17946. Fail("Body expected", methodDef->mBody);
  17947. }
  17948. else if (methodDef->mMethodType == BfMethodType_PropertyGetter)
  17949. {
  17950. if (methodInstance->mReturnType->IsValuelessType())
  17951. {
  17952. mBfIRBuilder->CreateRetVoid();
  17953. }
  17954. else if (HasExecutedOutput())
  17955. {
  17956. String autoPropName = typeDef->GetAutoPropertyName(propertyDeclaration);
  17957. BfFieldInstance* fieldInstance = GetFieldByName(mCurTypeInstance, autoPropName);
  17958. BfFieldDef* fieldDef = NULL;
  17959. if (fieldInstance != NULL)
  17960. fieldDef = fieldInstance->GetFieldDef();
  17961. BfType* retType = methodInstance->mReturnType;
  17962. if (retType->IsRef())
  17963. retType = retType->GetUnderlyingType();
  17964. if ((fieldInstance != NULL) && (fieldInstance->GetResolvedType() == retType) &&
  17965. ((fieldInstance->mDataIdx >= 0) || (fieldDef->IsNonConstStatic())))
  17966. {
  17967. BfTypedValue lookupValue;
  17968. if (fieldDef->IsNonConstStatic())
  17969. lookupValue = ReferenceStaticField(fieldInstance);
  17970. else if (mCurTypeInstance->IsObject())
  17971. lookupValue = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(GetThis().mValue, 0, fieldInstance->mDataIdx), fieldInstance->mResolvedType, true);
  17972. else
  17973. lookupValue = ExtractValue(GetThis(), fieldInstance, fieldInstance->mDataIdx);
  17974. if (!methodInstance->mReturnType->IsRef())
  17975. lookupValue = LoadOrAggregateValue(lookupValue);
  17976. CreateReturn(lookupValue.mValue);
  17977. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  17978. }
  17979. else
  17980. {
  17981. // This can happen if we have two properties with the same name but different types
  17982. CreateReturn(GetDefaultValue(mCurMethodInstance->mReturnType));
  17983. EmitDefaultReturn();
  17984. }
  17985. }
  17986. else
  17987. {
  17988. CreateReturn(GetDefaultValue(mCurMethodInstance->mReturnType));
  17989. EmitDefaultReturn();
  17990. }
  17991. mCurMethodState->SetHadReturn(true);
  17992. }
  17993. else if (methodDef->mMethodType == BfMethodType_PropertySetter)
  17994. {
  17995. if ((!methodDef->mIsMutating) && (!methodDef->mIsStatic) && (mCurTypeInstance->IsValueType()))
  17996. {
  17997. Fail("Auto-setter must be marked as 'mut'", methodDef->GetRefNode(), true);
  17998. }
  17999. else if (!mCompiler->IsAutocomplete())
  18000. {
  18001. String autoPropName = typeDef->GetAutoPropertyName(propertyDeclaration);
  18002. BfFieldInstance* fieldInstance = GetFieldByName(mCurTypeInstance, autoPropName);
  18003. auto fieldDef = fieldInstance->GetFieldDef();
  18004. auto& lastParam = mCurMethodState->mLocals.back();
  18005. if ((fieldInstance != NULL) && (fieldInstance->GetResolvedType() == lastParam->mResolvedType) &&
  18006. ((fieldInstance->mDataIdx >= 0) || (fieldDef->IsNonConstStatic())))
  18007. {
  18008. BfIRValue lookupAddr;
  18009. if (fieldDef->IsNonConstStatic())
  18010. lookupAddr = ReferenceStaticField(fieldInstance).mValue;
  18011. else
  18012. {
  18013. auto thisValue = GetThis();
  18014. if (thisValue.IsSplat())
  18015. {
  18016. BFMODULE_FATAL(this, "Should not happen");
  18017. }
  18018. if (mCurTypeInstance->IsObject())
  18019. thisValue = LoadValue(thisValue);
  18020. lookupAddr = mBfIRBuilder->CreateInBoundsGEP(thisValue.mValue, 0, fieldInstance->mDataIdx);
  18021. }
  18022. BfExprEvaluator exprEvaluator(this);
  18023. auto localVal = exprEvaluator.LoadLocal(lastParam);
  18024. localVal = LoadOrAggregateValue(localVal);
  18025. mBfIRBuilder->CreateStore(localVal.mValue, lookupAddr);
  18026. }
  18027. else if (!fieldInstance->mResolvedType->IsValuelessType())
  18028. {
  18029. // This can happen if we have two properties with the same name but different types
  18030. AssertErrorState();
  18031. }
  18032. }
  18033. }
  18034. else if ((methodDef->mName == BF_METHODNAME_MARKMEMBERS) || (methodDef->mName == BF_METHODNAME_MARKMEMBERS_STATIC))
  18035. {
  18036. if (mCompiler->mOptions.mEnableRealtimeLeakCheck)
  18037. {
  18038. if (HasCompiledOutput())
  18039. EmitGCMarkMembers();
  18040. }
  18041. else if (!mCurTypeInstance->IsObject())
  18042. {
  18043. }
  18044. }
  18045. else if (methodDef->mName == BF_METHODNAME_FIND_TLS_MEMBERS)
  18046. {
  18047. if (mCompiler->mOptions.mEnableRealtimeLeakCheck)
  18048. {
  18049. if (HasCompiledOutput())
  18050. EmitGCFindTLSMembers();
  18051. }
  18052. }
  18053. }
  18054. }
  18055. else if (!skipBody)
  18056. {
  18057. bool isEmptyBodied = BfNodeDynCast<BfTokenNode>(methodDef->mBody) != NULL;
  18058. bool wantsRetVal = true;
  18059. if ((mIsComptimeModule) && (methodDef->mMethodType != BfMethodType_CtorCalcAppend))
  18060. wantsRetVal = false;
  18061. else if (mCurMethodInstance->mReturnType->IsVar())
  18062. wantsRetVal = false;
  18063. if ((!mCurMethodInstance->mReturnType->IsValuelessType()) && (!isEmptyBodied))
  18064. {
  18065. mBfIRBuilder->PopulateType(mCurMethodInstance->mReturnType);
  18066. if ((!mIsComptimeModule) && (mCurMethodInstance->GetStructRetIdx() != -1))
  18067. {
  18068. auto ptrType = CreatePointerType(mCurMethodInstance->mReturnType);
  18069. auto allocaInst = AllocLocalVariable(ptrType, "__return.addr", false);
  18070. auto storeInst = mBfIRBuilder->CreateStore(mBfIRBuilder->GetArgument(mCurMethodInstance->GetStructRetIdx()), allocaInst);
  18071. mBfIRBuilder->ClearDebugLocation(storeInst);
  18072. mCurMethodState->mRetValAddr = allocaInst;
  18073. }
  18074. else if (wantsRetVal)
  18075. {
  18076. auto allocaInst = AllocLocalVariable(mCurMethodInstance->mReturnType, "__return", false);
  18077. mCurMethodState->mRetVal = BfTypedValue(allocaInst, mCurMethodInstance->mReturnType, true);
  18078. }
  18079. }
  18080. if (methodDef->mMethodType == BfMethodType_CtorCalcAppend)
  18081. {
  18082. mBfIRBuilder->CreateStore(GetConstValue(0), mCurMethodState->mRetVal.mValue);
  18083. BfGetSymbolReferenceKind prevSymbolKind;
  18084. BfAutoComplete* prevAutoComplete;
  18085. if (mCompiler->mResolvePassData != NULL)
  18086. {
  18087. prevSymbolKind = mCompiler->mResolvePassData->mGetSymbolReferenceKind;
  18088. prevAutoComplete = mCompiler->mResolvePassData->mAutoComplete;
  18089. mCompiler->mResolvePassData->mGetSymbolReferenceKind = BfGetSymbolReferenceKind_None;
  18090. }
  18091. EmitCtorCalcAppend();
  18092. if (mCompiler->mResolvePassData != NULL)
  18093. {
  18094. mCompiler->mResolvePassData->mGetSymbolReferenceKind = prevSymbolKind;
  18095. mCompiler->mResolvePassData->mAutoComplete = prevAutoComplete;
  18096. }
  18097. }
  18098. else if (!isEmptyBodied)
  18099. {
  18100. if (!mCurMethodState->mIRExitBlock)
  18101. mCurMethodState->mIRExitBlock = mBfIRBuilder->CreateBlock("exit", true);
  18102. bool isExpressionBody = false;
  18103. if (methodDeclaration != NULL)
  18104. {
  18105. if (methodDeclaration->mFatArrowToken != NULL)
  18106. isExpressionBody = true;
  18107. }
  18108. else if (auto propertyDeclaration = methodDef->GetPropertyDeclaration())
  18109. {
  18110. auto propertyMethodDeclaration = methodDef->GetPropertyMethodDeclaration();
  18111. if ((propertyMethodDeclaration != NULL) && (propertyMethodDeclaration->mFatArrowToken != NULL))
  18112. isExpressionBody = true;
  18113. if (auto propBodyExpr = BfNodeDynCast<BfPropertyBodyExpression>(propertyDeclaration->mDefinitionBlock))
  18114. {
  18115. isExpressionBody = true;
  18116. }
  18117. }
  18118. else
  18119. {
  18120. if (auto block = BfNodeDynCast<BfBlock>(methodDef->mBody))
  18121. {
  18122. if (!block->mChildArr.IsEmpty())
  18123. {
  18124. if (auto exprStmt = BfNodeDynCast<BfExpressionStatement>(block->mChildArr.GetLast()))
  18125. {
  18126. if (exprStmt->mTrailingSemicolon == NULL)
  18127. isExpressionBody = true;
  18128. }
  18129. }
  18130. }
  18131. else
  18132. isExpressionBody = true;
  18133. }
  18134. DoCEEmit(methodInstance);
  18135. if (methodInstance->mCeCancelled)
  18136. mIgnoreErrors = true;
  18137. if (auto fieldDtorBody = BfNodeDynCast<BfFieldDtorDeclaration>(methodDef->mBody))
  18138. {
  18139. while (fieldDtorBody != NULL)
  18140. {
  18141. VisitEmbeddedStatement(fieldDtorBody->mBody);
  18142. fieldDtorBody = fieldDtorBody->mNextFieldDtor;
  18143. }
  18144. }
  18145. else if (!isExpressionBody)
  18146. {
  18147. auto bodyBlock = BfNodeDynCast<BfBlock>(methodDef->mBody);
  18148. mCurMethodState->mHeadScope.mAstBlock = bodyBlock;
  18149. mCurMethodState->mHeadScope.mCloseNode = bodyBlock->mCloseBrace;
  18150. VisitCodeBlock(bodyBlock);
  18151. }
  18152. else if (auto expressionBody = BfNodeDynCast<BfExpression>(methodDef->mBody))
  18153. {
  18154. // if ((methodDef->mMethodType != BfMethodType_Normal) && (propertyDeclaration == NULL))
  18155. // {
  18156. // BF_ASSERT(methodDeclaration->mFatArrowToken != NULL);
  18157. // Fail("Only normal methods can have expression bodies", methodDeclaration->mFatArrowToken);
  18158. // }
  18159. auto expectingType = mCurMethodInstance->mReturnType;
  18160. // What was this error for?
  18161. // if ((expectingType->IsVoid()) && (IsInSpecializedSection()))
  18162. // {
  18163. // Warn(0, "Using a 'void' return with an expression-bodied method isn't needed. Consider removing '=>' token", methodDeclaration->mFatArrowToken);
  18164. // }
  18165. BfEvalExprFlags exprEvalFlags = BfEvalExprFlags_AllowRefExpr;
  18166. if (expectingType->IsVoid())
  18167. {
  18168. exprEvalFlags = (BfEvalExprFlags)(exprEvalFlags | BfEvalExprFlags_NoCast);
  18169. bool wasReturnGenericParam = false;
  18170. if ((mCurMethodState->mClosureState != NULL) && (mCurMethodState->mClosureState->mReturnType != NULL))
  18171. {
  18172. wasReturnGenericParam = mCurMethodState->mClosureState->mReturnType->IsGenericParam();
  18173. }
  18174. else
  18175. {
  18176. auto unspecializedMethodInstance = GetUnspecializedMethodInstance(mCurMethodInstance);
  18177. if ((unspecializedMethodInstance != NULL) && (unspecializedMethodInstance->mReturnType->IsGenericParam()))
  18178. wasReturnGenericParam = true;
  18179. }
  18180. // If we the void return was from a generic specialization, allow us to return a void result,
  18181. // otherwise treat expression as though it must be a statement
  18182. bool isStatement = expressionBody->VerifyIsStatement(mCompiler->mPassInstance, wasReturnGenericParam);
  18183. if (isStatement)
  18184. expectingType = NULL;
  18185. }
  18186. UpdateSrcPos(expressionBody);
  18187. auto retVal = CreateValueFromExpression(expressionBody, expectingType, exprEvalFlags);
  18188. if ((retVal) && (!retVal.mType->IsVar()) && (expectingType != NULL))
  18189. {
  18190. mCurMethodState->mHadReturn = true;
  18191. retVal = LoadOrAggregateValue(retVal);
  18192. EmitReturn(retVal);
  18193. }
  18194. }
  18195. }
  18196. }
  18197. BF_ASSERT(mCurMethodState->mCurScope == &mCurMethodState->mHeadScope);
  18198. if (skipUpdateSrcPos)
  18199. {
  18200. // Skip
  18201. }
  18202. else if ((bodyBlock != NULL) && (bodyBlock->mCloseBrace != NULL))
  18203. UpdateSrcPos(bodyBlock->mCloseBrace);
  18204. else if (methodDef->mBody != NULL)
  18205. UpdateSrcPos(methodDef->mBody);
  18206. else if (methodDeclaration != NULL)
  18207. UpdateSrcPos(methodDeclaration);
  18208. else if (methodDef->mDeclaringType->mTypeDeclaration != NULL)
  18209. UpdateSrcPos(methodDef->mDeclaringType->mTypeDeclaration);
  18210. else
  18211. UseDefaultSrcPos();
  18212. if (methodDef->mMethodType == BfMethodType_CtorCalcAppend)
  18213. {
  18214. if (mCurMethodState->mRetVal)
  18215. {
  18216. mCurMethodState->SetHadReturn(true);
  18217. auto retVal = mBfIRBuilder->CreateLoad(mCurMethodState->mRetVal.mValue);
  18218. mBfIRBuilder->CreateRet(retVal);
  18219. }
  18220. else
  18221. AssertErrorState();
  18222. }
  18223. if (!mCurMethodState->mHadReturn)
  18224. {
  18225. // Clear off the stackallocs that have occurred after a scopeData break
  18226. EmitDeferredScopeCalls(false, &mCurMethodState->mHeadScope, mCurMethodState->mIRExitBlock);
  18227. }
  18228. if (mCurMethodState->mIRExitBlock)
  18229. {
  18230. for (auto preExitBlock : mCurMethodState->mHeadScope.mAtEndBlocks)
  18231. mBfIRBuilder->MoveBlockToEnd(preExitBlock);
  18232. mBfIRBuilder->MoveBlockToEnd(mCurMethodState->mIRExitBlock);
  18233. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRExitBlock);
  18234. if ((!mCurMethodState->mDIRetVal) && (wantsDIData))
  18235. CreateDIRetVal();
  18236. }
  18237. for (auto localVar : mCurMethodState->mLocals)
  18238. {
  18239. if (auto autoCtorDecl = BfNodeDynCast<BfAutoConstructorDeclaration>(methodDeclaration))
  18240. {
  18241. //
  18242. }
  18243. else if ((skipEndChecks) || (methodDef->mBody == NULL))
  18244. break;
  18245. LocalVariableDone(localVar, true);
  18246. }
  18247. if (mCurMethodState->mIRExitBlock)
  18248. {
  18249. if ((mCurMethodState->mRetVal) &&
  18250. ((mIsComptimeModule) || (mCurMethodInstance->GetStructRetIdx() == -1)))
  18251. {
  18252. auto loadedVal = mBfIRBuilder->CreateLoad(mCurMethodState->mRetVal.mValue);
  18253. CreateReturn(loadedVal);
  18254. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  18255. if (mCurMethodState->mDIRetVal)
  18256. mBfIRBuilder->DbgLifetimeEnd(mCurMethodState->mDIRetVal);
  18257. }
  18258. else
  18259. {
  18260. // Have something on the last line to step onto
  18261. if (mHasFullDebugInfo)
  18262. {
  18263. if ((bodyBlock != NULL) && (bodyBlock->mCloseBrace != NULL))
  18264. UpdateSrcPos(bodyBlock->mCloseBrace);
  18265. EmitEnsureInstructionAt();
  18266. if ((irParamCount == 0) && (!IsTargetingBeefBackend()) && (mCompiler->mOptions.mAllowHotSwapping))
  18267. {
  18268. // This may be a case where we only emit 4 bytes, whereas we need 5 for a hot replace jump
  18269. mBfIRBuilder->EnsureFunctionPatchable();
  18270. }
  18271. }
  18272. mBfIRBuilder->CreateRetVoid();
  18273. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  18274. if (mCurMethodState->mDIRetVal)
  18275. mBfIRBuilder->DbgLifetimeEnd(mCurMethodState->mDIRetVal);
  18276. }
  18277. }
  18278. if ((mCurMethodInstance->mReturnType == NULL) || (mCurMethodInstance->mReturnType->IsValuelessType()))
  18279. {
  18280. if ((!mCurMethodState->mHadReturn) && (!mCurMethodState->mIRExitBlock))
  18281. {
  18282. if ((!mIsComptimeModule) && (irParamCount == 0) && (!IsTargetingBeefBackend()) && (mCompiler->mOptions.mAllowHotSwapping))
  18283. {
  18284. // This may be a case where we only emit 4 bytes, whereas we need 5 for a hot replace jump
  18285. mBfIRBuilder->EnsureFunctionPatchable();
  18286. }
  18287. mBfIRBuilder->CreateRetVoid();
  18288. }
  18289. }
  18290. else
  18291. {
  18292. if (!mCurMethodState->mHadReturn)
  18293. {
  18294. auto refNode = mCurMethodInstance->mMethodDef->GetRefNode();
  18295. if (bodyBlock != NULL)
  18296. {
  18297. if (bodyBlock->mCloseBrace != NULL)
  18298. {
  18299. BfAstNode* target = bodyBlock->mCloseBrace;
  18300. if (!mCompiler->mHasRequiredTypes)
  18301. {
  18302. AddFailType(mCurTypeInstance);
  18303. mHadBuildError = true;
  18304. }
  18305. else
  18306. Fail("Method must return value", target);
  18307. }
  18308. else
  18309. {
  18310. // It's possible to not have a closing brace if the method ends in an EOF
  18311. AssertErrorState();
  18312. }
  18313. }
  18314. }
  18315. }
  18316. // Move 'init' into 'entry'
  18317. mBfIRBuilder->MergeBlockDown(mCurMethodState->mIRInitBlock, mCurMethodState->mIREntryBlock);
  18318. mBfIRBuilder->MergeBlockDown(mCurMethodState->mIRHeadBlock, mCurMethodState->mIREntryBlock);
  18319. if (((mCurMethodInstance->mIsUnspecialized) /*|| (typeDef->mIsFunction)*/ || (mCurTypeInstance->IsUnspecializedType())) &&
  18320. (!mIsComptimeModule))
  18321. {
  18322. // Don't keep instructions for unspecialized types
  18323. mBfIRBuilder->Func_DeleteBody(mCurMethodInstance->mIRFunction);
  18324. }
  18325. // Avoid linking any internal funcs that were just supposed to be comptime-accessible
  18326. /*if ((methodDef->mHasComptime) && (!mIsComptimeModule))
  18327. wantsRemoveBody = true;*/
  18328. if ((hasExternSpecifier) && (!skipBody))
  18329. {
  18330. // If we hot swap, we want to make sure at least one method refers to this extern method so it gets pulled in
  18331. // incase it gets called later by some hot-loaded coded
  18332. if ((mCompiler->mOptions.mAllowHotSwapping) && (mCurMethodInstance->mIRFunction) && (!mCurMethodInstance->mIRFunction.IsFake()) && (mCurTypeInstance != mContext->mBfObjectType))
  18333. {
  18334. if (!mCurMethodInstance->mMethodDef->mName.StartsWith("Comptime_"))
  18335. CreateFakeCallerMethod(mangledName);
  18336. }
  18337. mBfIRBuilder->Func_DeleteBody(mCurMethodInstance->mIRFunction);
  18338. }
  18339. else if ((methodInstance->GetImportKind() == BfImportKind_Import_Dynamic) && (!mCompiler->IsHotCompile()))
  18340. {
  18341. // We only need the DLL stub when we may be hot swapping
  18342. mBfIRBuilder->Func_DeleteBody(mCurMethodInstance->mIRFunction);
  18343. }
  18344. else if (wantsRemoveBody)
  18345. mBfIRBuilder->Func_DeleteBody(mCurMethodInstance->mIRFunction);
  18346. // We don't want to hold on to pointers to LLVMFunctions of unspecialized types.
  18347. // This allows us to delete the mScratchModule LLVM module without rebuilding all
  18348. // unspecialized types
  18349. if (((mCurTypeInstance->IsUnspecializedType()) && (!mIsComptimeModule)) ||
  18350. (mCurTypeInstance->IsInterface()))
  18351. {
  18352. BfLogSysM("ProcessMethod Clearing IRFunction: %p\n", methodInstance);
  18353. methodInstance->mIRFunction = BfIRFunction();
  18354. }
  18355. CheckAddFailType();
  18356. if (mHadBuildError)
  18357. prevHadBuildError.CancelRestore();
  18358. if (mHadBuildWarning)
  18359. prevHadWarning.CancelRestore();
  18360. if (!methodDef->mIsLocalMethod)
  18361. ProcessMethod_ProcessDeferredLocals();
  18362. mBfIRBuilder->SetActiveFunction(prevActiveFunction);
  18363. if (methodState.mHotDataReferenceBuilder != NULL)
  18364. {
  18365. AddHotDataReferences(&hotDataReferenceBuilder);
  18366. }
  18367. else
  18368. {
  18369. if ((methodInstance->mHotMethod != NULL) && (!methodInstance->mIsReified))
  18370. {
  18371. // Remove the hot method data
  18372. auto hotMethod = methodInstance->mHotMethod;
  18373. auto prevMethod = hotMethod->mPrevVersion;
  18374. if (prevMethod != NULL)
  18375. {
  18376. // If there's a prev method then pull its data into the main HotMethod.
  18377. // This, in effect, removes the 'hotMethod' data and rebases 'prevMethod'
  18378. // over to the main HotMethod definition to keep the HotMethod address
  18379. // invariant
  18380. for (auto ref : hotMethod->mReferences)
  18381. ref->Deref();
  18382. hotMethod->mReferences.Clear();
  18383. BF_ASSERT(prevMethod->mRefCount == 1);
  18384. hotMethod->mReferences = prevMethod->mReferences;
  18385. if (hotMethod->mSrcTypeVersion != NULL)
  18386. hotMethod->mSrcTypeVersion->Deref();
  18387. hotMethod->mSrcTypeVersion = prevMethod->mSrcTypeVersion;
  18388. prevMethod->mSrcTypeVersion = NULL;
  18389. prevMethod->mReferences.Clear();
  18390. hotMethod->mPrevVersion = prevMethod->mPrevVersion;
  18391. prevMethod->mPrevVersion = NULL;
  18392. prevMethod->Deref();
  18393. }
  18394. hotMethod->Deref();
  18395. methodInstance->mHotMethod = NULL;
  18396. }
  18397. }
  18398. }
  18399. String BfModule::GetLocalMethodName(const StringImpl& baseName, BfAstNode* anchorNode, BfMethodState* declMethodState, BfMixinState* declMixinState)
  18400. {
  18401. String name;
  18402. bool found = false;
  18403. auto checkMethodState = mCurMethodState;
  18404. while (checkMethodState != NULL)
  18405. {
  18406. if (checkMethodState->mClosureState == NULL)
  18407. break;
  18408. if (checkMethodState->mClosureState->mClosureMethodDef != NULL)
  18409. {
  18410. found = true;
  18411. name += checkMethodState->mClosureState->mClosureMethodDef->mName;
  18412. break;
  18413. }
  18414. checkMethodState = checkMethodState->mPrevMethodState;
  18415. }
  18416. if (!found)
  18417. name += mCurMethodInstance->mMethodDef->mName;
  18418. int prevSepPos = (int)name.LastIndexOf('$');
  18419. if (prevSepPos != -1)
  18420. {
  18421. name.RemoveToEnd(prevSepPos);
  18422. }
  18423. name += "@";
  18424. name += baseName;
  18425. HashContext hashCtx;
  18426. if (anchorNode != NULL)
  18427. {
  18428. hashCtx.Mixin(anchorNode->GetStartCharId());
  18429. }
  18430. //
  18431. {
  18432. auto checkMethodState = declMethodState;
  18433. auto checkMixinState = declMixinState;
  18434. while (checkMethodState != NULL)
  18435. {
  18436. if (checkMixinState != NULL)
  18437. {
  18438. hashCtx.Mixin(checkMixinState->mSource->GetStartCharId());
  18439. }
  18440. checkMethodState = checkMethodState->mPrevMethodState;
  18441. if (checkMethodState != NULL)
  18442. checkMixinState = checkMethodState->mMixinState;
  18443. }
  18444. }
  18445. auto rootMethodState = mCurMethodState->GetRootMethodState();
  18446. if ((rootMethodState != NULL) && (rootMethodState->mMethodInstance != NULL) && (rootMethodState->mMethodInstance->mMethodInfoEx != NULL))
  18447. {
  18448. for (auto methodGenericArg : rootMethodState->mMethodInstance->mMethodInfoEx->mMethodGenericArguments)
  18449. {
  18450. StringT<128> genericTypeName;
  18451. BfMangler::Mangle(genericTypeName, mCompiler->GetMangleKind(), methodGenericArg);
  18452. hashCtx.MixinStr(genericTypeName);
  18453. }
  18454. }
  18455. uint64 hashVal = hashCtx.Finish64();
  18456. name += "$";
  18457. name += BfTypeUtils::HashEncode64(hashVal);
  18458. return name;
  18459. }
  18460. BfMethodDef* BfModule::GetLocalMethodDef(BfLocalMethod* localMethod)
  18461. {
  18462. if (localMethod->mMethodDef != NULL)
  18463. return localMethod->mMethodDef;
  18464. auto rootMethodState = mCurMethodState->GetRootMethodState();
  18465. auto declMethodState = localMethod->mDeclMethodState;
  18466. auto declMixinState = localMethod->mDeclMixinState;
  18467. auto typeInst = mCurTypeInstance;
  18468. BfAstNode* body = NULL;
  18469. BfAstNode* anchorNode = NULL;
  18470. auto _AllocDirectTypeRef = [&](BfType* type)
  18471. {
  18472. BfDirectTypeReference* directTypeRef = localMethod->mDirectTypeRefs.Alloc();
  18473. directTypeRef->Init(type);
  18474. return directTypeRef;
  18475. };
  18476. auto methodDeclaration = localMethod->mMethodDeclaration;
  18477. if (methodDeclaration != NULL)
  18478. {
  18479. body = methodDeclaration->mBody;
  18480. anchorNode = methodDeclaration->mOpenParen;
  18481. }
  18482. else
  18483. {
  18484. body = localMethod->mLambdaBindExpr->mBody;
  18485. anchorNode = localMethod->mLambdaBindExpr->mFatArrowToken;
  18486. }
  18487. BF_ASSERT(rootMethodState->mCurLocalVarId >= 0);
  18488. int methodLocalIdx = rootMethodState->mCurLocalVarId++;
  18489. BfMethodDef* methodDef;
  18490. BfMethodDef* outerMethodDef = NULL;
  18491. if (localMethod->mOuterLocalMethod != NULL)
  18492. outerMethodDef = localMethod->mOuterLocalMethod->mMethodDef;
  18493. else if (rootMethodState->mMethodInstance != NULL)
  18494. outerMethodDef = rootMethodState->mMethodInstance->mMethodDef;
  18495. if (methodDeclaration != NULL)
  18496. {
  18497. BfDefBuilder defBuilder(mCompiler->mSystem);
  18498. defBuilder.mCurSource = localMethod->mMethodDeclaration->GetParser();
  18499. defBuilder.mPassInstance = mCompiler->mPassInstance;
  18500. defBuilder.mCurTypeDef = mCurMethodInstance->mMethodDef->mDeclaringType;
  18501. defBuilder.mCurDeclaringTypeDef = defBuilder.mCurTypeDef;
  18502. methodDef = defBuilder.CreateMethodDef(methodDeclaration, outerMethodDef);
  18503. }
  18504. else
  18505. {
  18506. auto invokeMethod = localMethod->mLambdaInvokeMethodInstance;
  18507. methodDef = new BfMethodDef();
  18508. methodDef->mName = localMethod->mMethodName;
  18509. methodDef->mDeclaringType = mCurMethodInstance->mMethodDef->mDeclaringType;
  18510. methodDef->mReturnTypeRef = _AllocDirectTypeRef(invokeMethod->mReturnType);
  18511. methodDef->mBody = body;
  18512. for (int paramIdx = 0; paramIdx < invokeMethod->GetParamCount(); paramIdx++)
  18513. {
  18514. auto paramType = invokeMethod->GetParamType(paramIdx);
  18515. String paramName;
  18516. if (paramIdx < (int)localMethod->mLambdaBindExpr->mParams.size())
  18517. paramName = localMethod->mLambdaBindExpr->mParams[paramIdx]->ToString();
  18518. else
  18519. paramName = invokeMethod->GetParamName(paramIdx);
  18520. auto paramDef = new BfParameterDef();
  18521. paramDef->mTypeRef = _AllocDirectTypeRef(paramType);
  18522. paramDef->mName = paramName;
  18523. methodDef->mParams.Add(paramDef);
  18524. }
  18525. if (outerMethodDef != NULL)
  18526. {
  18527. for (auto genericParam : outerMethodDef->mGenericParams)
  18528. {
  18529. auto* copiedGenericParamDef = new BfGenericParamDef();
  18530. *copiedGenericParamDef = *genericParam;
  18531. methodDef->mGenericParams.Add(copiedGenericParamDef);
  18532. }
  18533. }
  18534. }
  18535. methodDef->mIdx = ~methodLocalIdx;
  18536. BF_ASSERT(!localMethod->mExpectedFullName.IsEmpty());
  18537. methodDef->mName = localMethod->mExpectedFullName;
  18538. // methodDef->mName = GetLocalMethodName(methodDef->mName, anchorNode, declMethodState, declMixinState);
  18539. //
  18540. // if (!localMethod->mExpectedFullName.IsEmpty())
  18541. // BF_ASSERT(methodDef->mName == localMethod->mExpectedFullName);
  18542. methodDef->mIsStatic = true;
  18543. methodDef->mIsLocalMethod = true;
  18544. methodDef->mIsVirtual = false;
  18545. localMethod->mMethodDef = methodDef;
  18546. auto methodInstanceGroup = new BfMethodInstanceGroup();
  18547. localMethod->mMethodInstanceGroup = methodInstanceGroup;
  18548. methodInstanceGroup->mMethodIdx = -1;
  18549. methodInstanceGroup->mOwner = mCurTypeInstance;
  18550. methodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  18551. if ((declMethodState->mMixinState != NULL) && (declMethodState->mMixinState->mTarget))
  18552. {
  18553. methodInstanceGroup->mOwner = declMethodState->mMixinState->mTarget.mType->ToTypeInstance();
  18554. BF_ASSERT(methodInstanceGroup->mOwner != NULL);
  18555. }
  18556. if ((mCompiler->mResolvePassData != NULL) && (methodDeclaration != NULL))
  18557. {
  18558. mCompiler->mResolvePassData->HandleLocalReference(methodDeclaration->mNameNode, typeInst->mTypeDef, rootMethodState->mMethodInstance->mMethodDef, methodLocalIdx);
  18559. auto autoComplete = mCompiler->mResolvePassData->mAutoComplete;
  18560. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(methodDeclaration->mNameNode)))
  18561. {
  18562. autoComplete->SetDefinitionLocation(methodDeclaration->mNameNode);
  18563. autoComplete->mInsertStartIdx = methodDeclaration->mNameNode->GetSrcStart();
  18564. autoComplete->mInsertEndIdx = methodDeclaration->mNameNode->GetSrcEnd();
  18565. autoComplete->mDefType = typeInst->mTypeDef;
  18566. autoComplete->mDefMethod = rootMethodState->mMethodInstance->mMethodDef;
  18567. autoComplete->mReplaceLocalId = methodLocalIdx;
  18568. }
  18569. }
  18570. return localMethod->mMethodDef;
  18571. }
  18572. BfModuleMethodInstance BfModule::GetLocalMethodInstance(BfLocalMethod* localMethod, const BfTypeVector& methodGenericArguments, BfMethodInstance* methodInstance, bool force)
  18573. {
  18574. BP_ZONE_F("GetLocalMethodInstance %s", localMethod->mMethodName.c_str());
  18575. BfLogSysM("GetLocalMethodInstance %p\n", localMethod);
  18576. auto rootMethodState = mCurMethodState->GetRootMethodState();
  18577. auto declMethodState = localMethod->mDeclMethodState;
  18578. auto declMixinState = localMethod->mDeclMixinState;
  18579. auto callerMethodState = mCurMethodState;
  18580. auto typeInst = mCurTypeInstance;
  18581. if (mCurMethodState->mMixinState != NULL)
  18582. {
  18583. typeInst = mCurMethodState->mMixinState->mMixinMethodInstance->GetOwner();
  18584. }
  18585. auto methodDef = GetLocalMethodDef(localMethod);
  18586. BfAstNode* body = NULL;
  18587. auto methodDeclaration = localMethod->mMethodDeclaration;
  18588. if (methodDeclaration != NULL)
  18589. {
  18590. body = methodDeclaration->mBody;
  18591. }
  18592. else
  18593. {
  18594. body = localMethod->mLambdaBindExpr->mBody;
  18595. }
  18596. bool hadConcreteInterfaceGenericArgument = false;
  18597. BfTypeVector sanitizedMethodGenericArguments;
  18598. // Ignore the outermost method's generic method arguments for the purpose of determining if we are the 'default' (ie: unspecialized)
  18599. // version of this method for this pass through the outermost method
  18600. int dependentGenericStartIdx = 0;
  18601. if ((rootMethodState->mMethodInstance != NULL) && (rootMethodState->mMethodInstance->mMethodInfoEx != NULL))
  18602. dependentGenericStartIdx = (int)rootMethodState->mMethodInstance->mMethodInfoEx->mMethodGenericArguments.size();
  18603. BfMethodInstance* outerMethodInstance = mCurMethodInstance;
  18604. if (methodGenericArguments.size() == 0)
  18605. {
  18606. if ((rootMethodState->mMethodInstance != NULL) && (rootMethodState->mMethodInstance->mMethodInfoEx != NULL))
  18607. sanitizedMethodGenericArguments = rootMethodState->mMethodInstance->mMethodInfoEx->mMethodGenericArguments;
  18608. }
  18609. else
  18610. {
  18611. int genericArgIdx = 0;
  18612. // for (; genericArgIdx < (int)outerMethodInstance->mMethodGenericArguments.size(); genericArgIdx++)
  18613. // {
  18614. // BF_ASSERT(methodGenericArguments[genericArgIdx] == outerMethodInstance->mMethodGenericArguments[genericArgIdx]);
  18615. // sanitizedMethodGenericArguments.push_back(methodGenericArguments[genericArgIdx]);
  18616. // }
  18617. for (; genericArgIdx < (int)methodGenericArguments.size(); genericArgIdx++)
  18618. {
  18619. auto genericArgType = methodGenericArguments[genericArgIdx];
  18620. BF_ASSERT(!genericArgType->IsRef());
  18621. if (genericArgType->IsConcreteInterfaceType())
  18622. {
  18623. hadConcreteInterfaceGenericArgument = true;
  18624. auto concreteInterfaceType = (BfConcreteInterfaceType*)genericArgType;
  18625. genericArgType = concreteInterfaceType->mInterface;
  18626. }
  18627. sanitizedMethodGenericArguments.push_back(genericArgType);
  18628. }
  18629. }
  18630. bool wantPrematureMethodInstance = false;
  18631. if (!force)
  18632. {
  18633. wantPrematureMethodInstance = (callerMethodState->mClosureState != NULL) && (callerMethodState->mClosureState->mCaptureVisitingBody);
  18634. }
  18635. auto methodInstGroup = localMethod->mMethodInstanceGroup;
  18636. bool isDefaultPass = true;
  18637. BfTypeVector lookupMethodGenericArguments;
  18638. for (int genericArgIdx = dependentGenericStartIdx; genericArgIdx < (int)methodGenericArguments.size(); genericArgIdx++)
  18639. {
  18640. auto genericArgType = methodGenericArguments[genericArgIdx];
  18641. BF_ASSERT(!genericArgType->IsRef());
  18642. lookupMethodGenericArguments.Add(genericArgType);
  18643. if (genericArgType->IsGenericParam())
  18644. {
  18645. auto genericParam = (BfGenericParamType*)genericArgType;
  18646. if ((genericParam->mGenericParamKind != BfGenericParamKind_Method) || (genericParam->mGenericParamIdx != genericArgIdx))
  18647. isDefaultPass = false;
  18648. }
  18649. else
  18650. {
  18651. isDefaultPass = false;
  18652. }
  18653. }
  18654. bool hadExistingMethodInstance = false;
  18655. if (methodInstance != NULL)
  18656. {
  18657. hadExistingMethodInstance = true;
  18658. }
  18659. else
  18660. {
  18661. if (isDefaultPass)
  18662. {
  18663. methodInstance = methodInstGroup->mDefault;
  18664. if (methodInstance != NULL)
  18665. {
  18666. hadExistingMethodInstance = true;
  18667. }
  18668. else
  18669. {
  18670. methodInstance = new BfMethodInstance();
  18671. methodInstGroup->mDefault = methodInstance;
  18672. }
  18673. }
  18674. else
  18675. {
  18676. BF_ASSERT(sanitizedMethodGenericArguments.size() != 0);
  18677. if (methodInstGroup->mMethodSpecializationMap == NULL)
  18678. methodInstGroup->mMethodSpecializationMap = new BfMethodInstanceGroup::MapType();
  18679. BfMethodInstance** methodInstancePtr = NULL;
  18680. if (!methodInstGroup->mMethodSpecializationMap->TryAdd(lookupMethodGenericArguments, NULL, &methodInstancePtr))
  18681. {
  18682. methodInstance = *methodInstancePtr;
  18683. hadExistingMethodInstance = true;
  18684. }
  18685. else
  18686. {
  18687. methodInstance = new BfMethodInstance();
  18688. *methodInstancePtr = methodInstance;
  18689. }
  18690. }
  18691. }
  18692. if (hadExistingMethodInstance)
  18693. {
  18694. if ((!methodInstance->mDisallowCalling) ||
  18695. ((wantPrematureMethodInstance) && (methodInstance->mDisallowCalling)))
  18696. return BfModuleMethodInstance(methodInstance);
  18697. BF_ASSERT((methodInstance->mMethodInfoEx == NULL) || (methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureClosureState == NULL));
  18698. }
  18699. else
  18700. {
  18701. auto methodInfoEx = methodInstance->GetMethodInfoEx();
  18702. methodInfoEx->mClosureInstanceInfo = new BfClosureInstanceInfo();
  18703. methodInfoEx->mClosureInstanceInfo->mLocalMethod = localMethod;
  18704. methodInstance->mIsReified = mCurMethodInstance->mIsReified;
  18705. methodInstance->mIsAutocompleteMethod = mCurMethodInstance->mIsAutocompleteMethod;
  18706. methodInstance->mMethodDef = methodDef;
  18707. methodInstance->mMethodInstanceGroup = localMethod->mMethodInstanceGroup;
  18708. if (hadConcreteInterfaceGenericArgument)
  18709. methodInstance->mIgnoreBody = true;
  18710. methodInfoEx->mMethodGenericArguments = sanitizedMethodGenericArguments;
  18711. for (auto genericArg : sanitizedMethodGenericArguments)
  18712. {
  18713. if (genericArg->IsPrimitiveType())
  18714. genericArg = GetWrappedStructType(genericArg);
  18715. AddDependency(genericArg, typeInst, BfDependencyMap::DependencyFlag_MethodGenericArg);
  18716. }
  18717. for (int genericParamIdx = (int)sanitizedMethodGenericArguments.size(); genericParamIdx < (int)methodDef->mGenericParams.size(); genericParamIdx++)
  18718. {
  18719. auto genericParamType = GetGenericParamType(BfGenericParamKind_Method, genericParamIdx);
  18720. methodInfoEx->mMethodGenericArguments.push_back(genericParamType);
  18721. }
  18722. SetupMethodIdHash(methodInstance);
  18723. }
  18724. auto _SetupMethodInstance = [&]()
  18725. {
  18726. BF_ASSERT(methodInstance->GetNumGenericParams() == 0);
  18727. // Generic constraints
  18728. for (int genericParamIdx = 0; genericParamIdx < (int)methodDef->mGenericParams.size(); genericParamIdx++)
  18729. {
  18730. auto genericParamInstance = new BfGenericMethodParamInstance(methodDef, genericParamIdx);
  18731. methodInstance->GetMethodInfoEx()->mGenericParams.push_back(genericParamInstance);
  18732. }
  18733. };
  18734. //////////////////////////////////////////////////////////////////////////
  18735. auto _VisitLambdaBody = [&]()
  18736. {
  18737. if (localMethod->mDeclOnly)
  18738. return;
  18739. if (mCompiler->mCanceling)
  18740. return;
  18741. if (auto blockBody = BfNodeDynCast<BfBlock>(body))
  18742. {
  18743. VisitCodeBlock(blockBody);
  18744. }
  18745. else if (auto bodyExpr = BfNodeDynCast<BfExpression>(body))
  18746. {
  18747. BfType* expectType = NULL;
  18748. if (!methodInstance->mReturnType->IsVoid())
  18749. expectType = methodInstance->mReturnType;
  18750. CreateValueFromExpression(bodyExpr, expectType, BfEvalExprFlags_AllowRefExpr);
  18751. }
  18752. };
  18753. auto _SafeResolveTypeRef = [&](BfTypeReference* typeRef)
  18754. {
  18755. SetAndRestoreValue<bool> prevIgnoreError(mIgnoreErrors, true);
  18756. auto result = ResolveTypeRef(typeRef);
  18757. if (result == NULL)
  18758. result = mContext->mBfObjectType;
  18759. return result;
  18760. };
  18761. BfTypeInstance* outerClosure = NULL;
  18762. if ((declMethodState->mClosureState != NULL) && (!declMethodState->mClosureState->mCapturing))
  18763. outerClosure = declMethodState->mClosureState->mClosureType;
  18764. BfMethodState methodState;
  18765. methodState.mPrevMethodState = declMethodState;//mCurMethodState;
  18766. BfIRFunctionType funcType;
  18767. auto voidType = GetPrimitiveType(BfTypeCode_None);
  18768. SizedArray<BfIRType, 0> paramTypes;
  18769. funcType = mBfIRBuilder->CreateFunctionType(mBfIRBuilder->MapType(voidType), paramTypes, methodInstance->IsVarArgs());
  18770. mBfIRBuilder->SaveDebugLocation();
  18771. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  18772. auto prevActiveFunction = mBfIRBuilder->GetActiveFunction();
  18773. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, true);
  18774. BfDeferredLocalAssignData deferredLocalAssignData;
  18775. //TODO: Why did we do this? It can cause us to pull in local variables that don't belong to us...
  18776. /*if (declMethodState->mDeferredLocalAssignData != NULL)
  18777. deferredLocalAssignData.ExtendFrom(declMethodState->mDeferredLocalAssignData);*/
  18778. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  18779. methodState.mIRHeadBlock = mBfIRBuilder->CreateBlock("head", true);
  18780. methodState.mIRInitBlock = mBfIRBuilder->CreateBlock("init", true);
  18781. methodState.mIREntryBlock = mBfIRBuilder->CreateBlock("entry", true);
  18782. methodState.mCurScope->mDIScope = localMethod->mDeclDIScope; //declMethodState->mCurScope->mDIScope ;
  18783. //methodState.mCurLocalVarId = declMethodState->mCurLocalVarId;
  18784. methodState.mIRFunction = declMethodState->mIRFunction;
  18785. methodState.mDeferredLocalAssignData = &deferredLocalAssignData;
  18786. if (auto blockBody = BfNodeDynCast<BfBlock>(body))
  18787. {
  18788. methodState.mCurScope->mAstBlock = blockBody;
  18789. methodState.mCurScope->mCloseNode = blockBody->mCloseBrace;
  18790. }
  18791. mBfIRBuilder->SetInsertPoint(methodState.mIREntryBlock);
  18792. BfClosureState closureState;
  18793. if (methodDef->mMethodType == BfMethodType_Mixin)
  18794. {
  18795. if (declMethodState != NULL)
  18796. {
  18797. if ((declMethodState->mClosureState != NULL) && (declMethodState->mClosureState->mReturnType != NULL))
  18798. closureState.mReturnType = declMethodState->mClosureState->mReturnType;
  18799. else if (declMethodState->mMethodInstance != NULL)
  18800. closureState.mReturnType = declMethodState->mMethodInstance->mReturnType;
  18801. }
  18802. }
  18803. if (closureState.mReturnType == NULL)
  18804. closureState.mReturnType = _SafeResolveTypeRef(methodDef->mReturnTypeRef);
  18805. closureState.mCapturing = true;
  18806. closureState.mLocalMethod = localMethod;
  18807. closureState.mClosureInstanceInfo = methodInstance->mMethodInfoEx->mClosureInstanceInfo;
  18808. closureState.mDeclaringMethodIsMutating = mCurMethodInstance->mMethodDef->mIsMutating;
  18809. methodState.mClosureState = &closureState;
  18810. closureState.mClosureType = outerClosure;
  18811. int outerLocalsCount = (int)methodState.mLocals.size();
  18812. if (!hadExistingMethodInstance)
  18813. {
  18814. BfLogSysM("LocalMethod %p premature DoMethodDeclaration %p (Source:%p)\n", localMethod, methodInstance, (methodDeclaration != NULL) ? methodDeclaration->GetSourceData() : NULL);
  18815. SetAndRestoreValue<bool> prevIgnoreWrites(mWantsIRIgnoreWrites, true);
  18816. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, true);
  18817. // Prematurely do declaration. We will have to undo this later, so don't write this one and don't throw errors
  18818. auto declareModule = this;
  18819. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(declareModule->mCurMethodInstance, methodInstance);
  18820. SetAndRestoreValue<BfFilePosition> prevFilePos(declareModule->mCurFilePosition);
  18821. BF_ASSERT(declareModule != NULL);
  18822. methodInstance->mDeclModule = declareModule;
  18823. _SetupMethodInstance();
  18824. declareModule->DoMethodDeclaration(localMethod->mMethodDef->GetMethodDeclaration(), false, false);
  18825. methodInstance->mDisallowCalling = true; // Don't allow us to ACTUALLY call until we add the captures
  18826. }
  18827. if (wantPrematureMethodInstance)
  18828. {
  18829. // Return a premature methodInstance -- since we are partway through determining the capture of a local method, we can't rely on its
  18830. // capture information. This returned method instance can only be used for method matching, but we will visit it later to create
  18831. // its true method instance
  18832. //auto moduleMethodInstance = _CheckReturnedMethod(methodInstance);
  18833. //BF_ASSERT(moduleMethodInstance);
  18834. return BfModuleMethodInstance(methodInstance);
  18835. }
  18836. auto checkInsertBlock = mBfIRBuilder->GetInsertBlock();
  18837. BF_ASSERT(methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureClosureState == NULL);
  18838. closureState.mCaptureStartAccessId = mCurMethodState->GetRootMethodState()->mCurAccessId;
  18839. methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureClosureState = &closureState;
  18840. closureState.mClosureMethodDef = methodDef;
  18841. bool wantsVisitBody = true;
  18842. if ((methodDef->mMethodType == BfMethodType_Mixin) && (!methodGenericArguments.IsEmpty()))
  18843. wantsVisitBody = false;
  18844. if (methodInstance->IsOrInUnspecializedVariation())
  18845. wantsVisitBody = false;
  18846. bool allowCapture = (methodDeclaration == NULL) || (methodDeclaration->mStaticSpecifier == NULL);
  18847. if (wantsVisitBody)
  18848. {
  18849. BP_ZONE("VisitLambdaBody");
  18850. // For generic methods, we capture for each specialization, so make sure mIsStatic is set to 'true' for
  18851. // this capture stage for each of those times
  18852. SetAndRestoreValue<bool> prevWasStatis(methodDef->mIsStatic, true);
  18853. /*
  18854. // Only generate errors once. Also there are some errors that will occur during this scanning phase
  18855. // that will not occur during the actual lambda method generation, for example: returning a value
  18856. // when our current method is a 'void' method. This shouldn't affect capture scanning since all
  18857. // our AST nodes will still be visited
  18858. SetAndRestoreValue<bool> ignoreError(mIgnoreErrors, true);
  18859. */
  18860. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, methodInstance);
  18861. //SetAndRestoreValue<bool> wantsIgnoreWrites(mWantsISIgnoreWrites, true);
  18862. mBfIRBuilder->SaveDebugLocation();
  18863. closureState.mCaptureVisitingBody = true;
  18864. BF_ASSERT(methodInstance->mMethodInfoEx != NULL);
  18865. methodState.mGenericTypeBindings = &methodInstance->mMethodInfoEx->mGenericTypeBindings;
  18866. methodState.mMethodInstance = methodInstance;
  18867. NewScopeState();
  18868. ProcessMethod_SetupParams(methodInstance, NULL, false, NULL);
  18869. if (methodInstance->mMethodDef->mMethodType == BfMethodType_Mixin)
  18870. {
  18871. // Allow assigning to arguments when we're capturing - which may or may not be legal at the injection site (we throw error there)
  18872. for (auto localDef : methodState.mLocals)
  18873. {
  18874. if (localDef->mResolvedType->IsVar())
  18875. continue;
  18876. localDef->mAddr = CreateAlloca(localDef->mResolvedType);
  18877. }
  18878. }
  18879. // Keep outs for being marked as assigned
  18880. auto rootMethodState = mCurMethodState->GetRootMethodState();
  18881. BfDeferredLocalAssignData deferredLocalAssignData(rootMethodState->mCurScope);
  18882. deferredLocalAssignData.mVarIdBarrier = rootMethodState->mCurLocalVarId;
  18883. SetAndRestoreValue<BfDeferredLocalAssignData*> prevDLA(rootMethodState->mDeferredLocalAssignData, &deferredLocalAssignData);
  18884. if (!mIgnoreErrors)
  18885. localMethod->mDidBodyErrorPass = true;
  18886. _VisitLambdaBody();
  18887. RestoreScopeState();
  18888. closureState.mCaptureVisitingBody = false;
  18889. mBfIRBuilder->RestoreDebugLocation();
  18890. }
  18891. // If we ended up being called by a method with a lower captureStartAccessId, propagate that to whoever is calling us, too...
  18892. if ((methodState.mPrevMethodState->mClosureState != NULL) && (methodState.mPrevMethodState->mClosureState->mCapturing))
  18893. {
  18894. auto prevClosureState = methodState.mPrevMethodState->mClosureState;
  18895. if (closureState.mCaptureStartAccessId < prevClosureState->mCaptureStartAccessId)
  18896. prevClosureState->mCaptureStartAccessId = closureState.mCaptureStartAccessId;
  18897. }
  18898. // Actually get the referenced local methods. It's important we wait until after visiting the body, because then our own capture information
  18899. // can be used by these methods (which will be necessary if any of these methods call us directly or indirectly)
  18900. closureState.mClosureMethodDef = NULL;
  18901. for (auto methodInstance : closureState.mLocalMethodRefs)
  18902. {
  18903. GetLocalMethodInstance(methodInstance->mMethodInfoEx->mClosureInstanceInfo->mLocalMethod, BfTypeVector(), methodInstance);
  18904. }
  18905. methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureClosureState = NULL;
  18906. prevIgnoreWrites.Restore();
  18907. std::multiset<BfClosureCapturedEntry> capturedEntries;
  18908. //
  18909. {
  18910. auto varMethodState = declMethodState;
  18911. while (varMethodState != NULL)
  18912. {
  18913. if ((varMethodState->mMixinState != NULL) && (varMethodState->mMixinState->mLastTargetAccessId >= closureState.mCaptureStartAccessId))
  18914. {
  18915. BF_ASSERT(methodInstance->GetOwner() == varMethodState->mMixinState->mTarget.mType);
  18916. methodDef->mIsStatic = false;
  18917. if (rootMethodState->mMethodInstance->mMethodDef->mIsMutating)
  18918. methodDef->mIsMutating = true;
  18919. }
  18920. bool copyOuterCaptures = false;
  18921. for (int localIdx = 0; localIdx < varMethodState->mLocals.size(); localIdx++)
  18922. {
  18923. auto localVar = varMethodState->mLocals[localIdx];
  18924. if ((localVar->mReadFromId >= closureState.mCaptureStartAccessId) || (localVar->mWrittenToId >= closureState.mCaptureStartAccessId))
  18925. {
  18926. if (!allowCapture)
  18927. {
  18928. if ((!localVar->mIsStatic) && (!localVar->mConstValue))
  18929. continue;
  18930. }
  18931. if (localVar->mIsThis)
  18932. {
  18933. // We can only set mutating if our owning type is mutating
  18934. if (localVar->mWrittenToId >= closureState.mCaptureStartAccessId)
  18935. {
  18936. if (typeInst->IsValueType())
  18937. {
  18938. if (rootMethodState->mMethodInstance->mMethodDef->mIsMutating)
  18939. methodDef->mIsMutating = true;
  18940. }
  18941. }
  18942. methodDef->mIsStatic = false;
  18943. continue;
  18944. }
  18945. if ((localVar->mIsThis) && (outerClosure != NULL))
  18946. {
  18947. continue;
  18948. }
  18949. if ((localVar->mConstValue) || (localVar->mIsStatic) || (localVar->mResolvedType->IsValuelessType()))
  18950. {
  18951. closureState.mConstLocals.push_back(*localVar);
  18952. continue;
  18953. }
  18954. BfClosureCapturedEntry capturedEntry;
  18955. auto capturedType = localVar->mResolvedType;
  18956. bool captureByRef = false;
  18957. if (!capturedType->IsRef())
  18958. {
  18959. if (localVar->mIsThis)
  18960. {
  18961. if ((localVar->mResolvedType->IsValueType()) && (mCurMethodInstance->mMethodDef->HasNoThisSplat()))
  18962. captureByRef = true;
  18963. }
  18964. else if ((!localVar->mIsReadOnly) && (localVar->mWrittenToId >= closureState.mCaptureStartAccessId))
  18965. captureByRef = true;
  18966. }
  18967. else
  18968. {
  18969. if (localVar->mWrittenToId < closureState.mCaptureStartAccessId)
  18970. {
  18971. capturedType = ((BfRefType*)capturedType)->mElementType;
  18972. }
  18973. }
  18974. if (captureByRef)
  18975. {
  18976. //capturedEntry.mIsByReference = true;
  18977. capturedType = CreateRefType(capturedType);
  18978. }
  18979. else
  18980. {
  18981. //capturedEntry.mIsByReference = false;
  18982. }
  18983. capturedEntry.mNameNode = localVar->mNameNode;
  18984. capturedEntry.mType = capturedType;
  18985. capturedEntry.mName = localVar->mName;
  18986. //capturedEntry.mLocalVarDef = localVar;
  18987. capturedEntries.insert(capturedEntry);
  18988. }
  18989. }
  18990. varMethodState = varMethodState->mPrevMethodState;
  18991. if ((varMethodState == NULL) ||
  18992. (varMethodState->mMixinState != NULL) ||
  18993. ((varMethodState->mClosureState != NULL) && (!varMethodState->mClosureState->mCapturing)))
  18994. break;
  18995. }
  18996. }
  18997. for (auto& copyField : closureState.mReferencedOuterClosureMembers)
  18998. {
  18999. auto fieldDef = copyField->GetFieldDef();
  19000. BfClosureCapturedEntry capturedEntry;
  19001. capturedEntry.mName = copyField->GetFieldDef()->mName;
  19002. capturedEntry.mType = copyField->mResolvedType;
  19003. if (capturedEntry.mType->IsRef())
  19004. {
  19005. // Keep by ref
  19006. }
  19007. else if (!fieldDef->mIsReadOnly)
  19008. {
  19009. capturedEntry.mType = CreateRefType(capturedEntry.mType);
  19010. }
  19011. capturedEntries.insert(capturedEntry);
  19012. }
  19013. int captureIdx = 0;
  19014. for (auto& capturedEntry : capturedEntries)
  19015. {
  19016. methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureEntries.Add(capturedEntry);
  19017. }
  19018. /*if (isDefaultPass)
  19019. {
  19020. // Insert captured members a params at the start. If we added at the end then it would screw up varargs methods
  19021. int captureIdx = 0;
  19022. for (auto& capturedEntry : capturedEntries)
  19023. {
  19024. methodInstance->mClosureInstanceInfo->mCaptureNodes.Add(BfNodeDynCast<BfIdentifierNode>(capturedEntry.mNameNode));
  19025. BfParameterDef* paramDef = new BfParameterDef();
  19026. paramDef->mName = capturedEntry.mName;
  19027. BfDirectTypeReference* directTypeRef = new BfDirectTypeReference();
  19028. directTypeRef->mType = capturedEntry.mType;
  19029. typeInst->mTypeDef->mDirectAllocNodes.push_back(directTypeRef);
  19030. paramDef->mTypeRef = directTypeRef;
  19031. paramDef->mParamKind = BfParamKind_ImplicitCapture;
  19032. methodDef->mParams.Insert(captureIdx, paramDef);
  19033. captureIdx++;
  19034. }
  19035. }
  19036. else
  19037. {
  19038. auto defaultMethodInstance = methodInstGroup->mDefault;
  19039. methodInstance->mClosureInstanceInfo->mCaptureNodes = defaultMethodInstance->mClosureInstanceInfo->mCaptureNodes;
  19040. }*/
  19041. methodState.Reset();
  19042. closureState.mCapturing = false;
  19043. //////////////////////////////////////////////////////////////////////////
  19044. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, false);
  19045. if (methodInstance->mReturnType != NULL)
  19046. {
  19047. BF_ASSERT(methodInstance->mDisallowCalling);
  19048. // We did a premature declaration (without captures)
  19049. methodInstance->UndoDeclaration();
  19050. methodInstance->mDisallowCalling = false;
  19051. BfLogSysM("LocalMethod %p UndoingDeclaration %p\n", localMethod, methodInstance);
  19052. }
  19053. auto declareModule = this;
  19054. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(declareModule->mCurMethodInstance, methodInstance);
  19055. SetAndRestoreValue<BfFilePosition> prevFilePos(declareModule->mCurFilePosition);
  19056. BF_ASSERT(declareModule != NULL);
  19057. methodInstance->mDeclModule = declareModule;
  19058. _SetupMethodInstance();
  19059. BfLogSysM("LocalMethod %p DoMethodDeclaration %p\n", localMethod, methodInstance);
  19060. declareModule->DoMethodDeclaration(localMethod->mMethodDef->GetMethodDeclaration(), false, false);
  19061. closureState.mReturnType = methodInstance->mReturnType;
  19062. mCompiler->mStats.mMethodsQueued++;
  19063. mCompiler->UpdateCompletion();
  19064. declareModule->mIncompleteMethodCount++;
  19065. mCompiler->mStats.mMethodsProcessed++;
  19066. if (!methodInstance->mIsReified)
  19067. mCompiler->mStats.mUnreifiedMethodsProcessed++;
  19068. auto deferMethodState = rootMethodState;
  19069. // 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)
  19070. if ((!localMethod->mDeclOnly) && (!methodInstance->IsOrInUnspecializedVariation()) &&
  19071. (methodDef->mMethodType != BfMethodType_Mixin) &&
  19072. ((!mWantsIRIgnoreWrites) || (!localMethod->mDidBodyErrorPass)) &&
  19073. (!mCompiler->IsDataResolvePass()))
  19074. {
  19075. BP_ZONE("BfDeferredLocalMethod:create");
  19076. BfDeferredLocalMethod* deferredLocalMethod = new BfDeferredLocalMethod();
  19077. deferredLocalMethod->mLocalMethod = localMethod;
  19078. deferredLocalMethod->mConstLocals = closureState.mConstLocals;
  19079. deferredLocalMethod->mMethodInstance = methodInstance;
  19080. auto checkMethodState = declMethodState;
  19081. while (checkMethodState != NULL)
  19082. {
  19083. if ((checkMethodState->mClosureState != NULL) && (checkMethodState->mClosureState->mActiveDeferredLocalMethod != NULL))
  19084. {
  19085. for (auto& mixinRecord : checkMethodState->mClosureState->mActiveDeferredLocalMethod->mMixinStateRecords)
  19086. deferredLocalMethod->mMixinStateRecords.Add(mixinRecord);
  19087. }
  19088. if (checkMethodState->mMixinState != NULL)
  19089. {
  19090. BfMixinRecord mixinRecord;
  19091. mixinRecord.mSource = checkMethodState->mMixinState->mSource;
  19092. deferredLocalMethod->mMixinStateRecords.Add(mixinRecord);
  19093. }
  19094. checkMethodState = checkMethodState->mPrevMethodState;
  19095. }
  19096. rootMethodState->mDeferredLocalMethods.Add(deferredLocalMethod);
  19097. }
  19098. mBfIRBuilder->SetActiveFunction(prevActiveFunction);
  19099. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  19100. mBfIRBuilder->RestoreDebugLocation();
  19101. if (methodInstance == localMethod->mMethodInstanceGroup->mDefault)
  19102. {
  19103. auto checkMethodState = mCurMethodState;
  19104. while (checkMethodState != NULL)
  19105. {
  19106. BfLocalMethod* nextLocalMethod = NULL;
  19107. if (checkMethodState->mLocalMethodMap.TryGetValue(localMethod->mMethodName, &nextLocalMethod))
  19108. {
  19109. while (nextLocalMethod != NULL)
  19110. {
  19111. auto checkLocalMethod = nextLocalMethod;
  19112. nextLocalMethod = nextLocalMethod->mNextWithSameName;
  19113. if (checkLocalMethod == localMethod)
  19114. continue;
  19115. if (checkLocalMethod->mMethodInstanceGroup == NULL)
  19116. continue;
  19117. auto checkMethodInstance = checkLocalMethod->mMethodInstanceGroup->mDefault;
  19118. if (checkMethodInstance == NULL)
  19119. continue; // Not generated yet
  19120. if (CompareMethodSignatures(localMethod->mMethodInstanceGroup->mDefault, checkMethodInstance))
  19121. {
  19122. String error = "Method already declared with the same parameter types";
  19123. auto bfError = Fail(error, methodInstance->mMethodDef->GetRefNode(), true);
  19124. if ((bfError != NULL) && (methodInstance->mMethodDef->GetRefNode() != checkMethodInstance->mMethodDef->GetRefNode()))
  19125. mCompiler->mPassInstance->MoreInfo("First declaration", checkMethodInstance->mMethodDef->GetRefNode());
  19126. }
  19127. }
  19128. }
  19129. checkMethodState = checkMethodState->mPrevMethodState;
  19130. }
  19131. }
  19132. return BfModuleMethodInstance(methodInstance);
  19133. }
  19134. int BfModule::GetLocalInferrableGenericArgCount(BfMethodDef* methodDef)
  19135. {
  19136. if ((!methodDef->mIsLocalMethod) || (methodDef->mGenericParams.size() == 0))
  19137. return 0;
  19138. auto rootMethodState = mCurMethodState->GetRootMethodState();
  19139. int rootMethodGenericParamCount = 0;
  19140. if (rootMethodState->mMethodInstance->mMethodInfoEx != NULL)
  19141. rootMethodGenericParamCount = (int)rootMethodState->mMethodInstance->mMethodInfoEx->mGenericParams.size();
  19142. if (mCurMethodInstance == NULL)
  19143. return rootMethodGenericParamCount;
  19144. if ((mCurMethodInstance->mMethodInfoEx == NULL) || (mCurMethodInstance->mMethodInfoEx->mClosureInstanceInfo == NULL))
  19145. return rootMethodGenericParamCount;
  19146. BfLocalMethod* callerLocalMethod = mCurMethodInstance->mMethodInfoEx->mClosureInstanceInfo->mLocalMethod;
  19147. if (callerLocalMethod == NULL)
  19148. return rootMethodGenericParamCount;
  19149. BfLocalMethod* calledLocalMethod = NULL;
  19150. rootMethodState->mLocalMethodCache.TryGetValue(methodDef->mName, &calledLocalMethod);
  19151. while ((calledLocalMethod != NULL) && (callerLocalMethod != NULL))
  19152. {
  19153. if (calledLocalMethod->mOuterLocalMethod == callerLocalMethod)
  19154. return (int)callerLocalMethod->mMethodDef->mGenericParams.size();
  19155. callerLocalMethod = calledLocalMethod->mOuterLocalMethod;
  19156. }
  19157. return rootMethodGenericParamCount;
  19158. }
  19159. void BfModule::GetMethodCustomAttributes(BfMethodInstance* methodInstance)
  19160. {
  19161. auto methodDef = methodInstance->mMethodDef;
  19162. auto customAttributes = methodInstance->GetCustomAttributes();
  19163. if (customAttributes != NULL)
  19164. return;
  19165. auto methodDeclaration = methodDef->GetMethodDeclaration();
  19166. auto propertyMethodDeclaration = methodDef->GetPropertyMethodDeclaration();
  19167. auto typeInstance = methodInstance->GetOwner();
  19168. BfTypeState typeState(typeInstance);
  19169. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  19170. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  19171. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, methodInstance);
  19172. BfAttributeTargets attrTarget = ((methodDef->mMethodType == BfMethodType_Ctor) || (methodDef->mMethodType == BfMethodType_CtorCalcAppend)) ? BfAttributeTargets_Constructor : BfAttributeTargets_Method;
  19173. BfAttributeDirective* attributeDirective = NULL;
  19174. if (methodDeclaration != NULL)
  19175. attributeDirective = methodDeclaration->mAttributes;
  19176. else if (propertyMethodDeclaration != NULL)
  19177. {
  19178. attributeDirective = propertyMethodDeclaration->mAttributes;
  19179. if (auto exprBody = BfNodeDynCast<BfPropertyBodyExpression>(propertyMethodDeclaration->mPropertyDeclaration->mDefinitionBlock))
  19180. {
  19181. attributeDirective = propertyMethodDeclaration->mPropertyDeclaration->mAttributes;
  19182. attrTarget = (BfAttributeTargets)(BfAttributeTargets_Property | BfAttributeTargets_Method);
  19183. }
  19184. }
  19185. if (attributeDirective != NULL)
  19186. {
  19187. if (methodInstance->GetMethodInfoEx()->mMethodCustomAttributes == NULL)
  19188. methodInstance->mMethodInfoEx->mMethodCustomAttributes = new BfMethodCustomAttributes();
  19189. methodInstance->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes = GetCustomAttributes(attributeDirective, attrTarget);
  19190. }
  19191. if ((propertyMethodDeclaration != NULL) && (propertyMethodDeclaration->mPropertyDeclaration->mAttributes != NULL) && ((attrTarget & BfAttributeTargets_Property) == 0))
  19192. {
  19193. if (methodInstance->GetMethodInfoEx()->mMethodCustomAttributes != NULL)
  19194. {
  19195. GetCustomAttributes(methodInstance->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes, propertyMethodDeclaration->mPropertyDeclaration->mAttributes, BfAttributeTargets_Property);
  19196. }
  19197. else
  19198. {
  19199. methodInstance->GetMethodInfoEx()->mMethodCustomAttributes = new BfMethodCustomAttributes();
  19200. methodInstance->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes = GetCustomAttributes(propertyMethodDeclaration->mPropertyDeclaration->mAttributes, BfAttributeTargets_Property);
  19201. }
  19202. }
  19203. customAttributes = methodInstance->GetCustomAttributes();
  19204. if (customAttributes == NULL)
  19205. {
  19206. auto owner = methodInstance->GetOwner();
  19207. if ((owner->IsDelegate()) || (owner->IsFunction()))
  19208. customAttributes = owner->mCustomAttributes;
  19209. }
  19210. methodInstance->mCallingConvention = methodDef->mCallingConvention;
  19211. if (customAttributes != NULL)
  19212. {
  19213. auto linkNameAttr = customAttributes->Get(mCompiler->mCallingConventionAttributeTypeDef);
  19214. if (linkNameAttr != NULL)
  19215. {
  19216. if (linkNameAttr->mCtorArgs.size() == 1)
  19217. {
  19218. auto constant = typeInstance->mConstHolder->GetConstant(linkNameAttr->mCtorArgs[0]);
  19219. if (constant != NULL)
  19220. methodInstance->mCallingConvention = (BfCallingConvention)constant->mInt32;
  19221. }
  19222. }
  19223. if (methodDef->mHasComptime)
  19224. methodInstance->mComptimeFlags = BfComptimeFlag_Comptime;
  19225. auto comptimeAttr = customAttributes->Get(mCompiler->mComptimeAttributeTypeDef);
  19226. if (comptimeAttr != NULL)
  19227. {
  19228. for (auto setProp : comptimeAttr->mSetProperties)
  19229. {
  19230. BfPropertyDef* propertyDef = setProp.mPropertyRef;
  19231. if (propertyDef->mName == "OnlyFromComptime")
  19232. {
  19233. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  19234. if ((constant != NULL) && (constant->mBool))
  19235. methodInstance->mComptimeFlags = (BfComptimeFlags)(methodInstance->mComptimeFlags | BfComptimeFlag_OnlyFromComptime);
  19236. }
  19237. else if (propertyDef->mName == "ConstEval")
  19238. {
  19239. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  19240. if ((constant != NULL) && (constant->mBool))
  19241. methodInstance->mComptimeFlags = (BfComptimeFlags)(methodInstance->mComptimeFlags | BfComptimeFlag_ConstEval);
  19242. }
  19243. }
  19244. }
  19245. }
  19246. auto delegateInfo = typeInstance->GetDelegateInfo();
  19247. if ((delegateInfo != NULL) && (methodInstance->mMethodDef->mMethodType == BfMethodType_Normal) && (methodInstance->mMethodDef->mName == "Invoke"))
  19248. methodInstance->mCallingConvention = delegateInfo->mCallingConvention;
  19249. }
  19250. void BfModule::SetupIRFunction(BfMethodInstance* methodInstance, StringImpl& mangledName, bool isTemporaryFunc, bool* outIsIntrinsic)
  19251. {
  19252. if (methodInstance->GetImportCallKind() == BfImportCallKind_GlobalVar)
  19253. {
  19254. // Don't create a func
  19255. return;
  19256. }
  19257. auto typeInstance = methodInstance->GetOwner();
  19258. auto methodDef = methodInstance->mMethodDef;
  19259. BfIRFunctionType funcType = mBfIRBuilder->MapMethod(methodInstance);
  19260. if (isTemporaryFunc)
  19261. {
  19262. BF_ASSERT(((mCompiler->mIsResolveOnly) && (mCompiler->mResolvePassData->mAutoComplete != NULL)) ||
  19263. (methodInstance->GetOwner()->mDefineState < BfTypeDefineState_Defined));
  19264. mangledName = "autocomplete_tmp";
  19265. }
  19266. if (!mBfIRBuilder->mIgnoreWrites)
  19267. {
  19268. BfIRFunction prevFunc;
  19269. // Remove old version (if we have one)
  19270. prevFunc = mBfIRBuilder->GetFunction(mangledName);
  19271. if (prevFunc)
  19272. {
  19273. if ((methodDef->mIsOverride) && (mCurTypeInstance->mTypeDef->mIsCombinedPartial))
  19274. {
  19275. mCurTypeInstance->mTypeDef->PopulateMemberSets();
  19276. BfMethodDef* nextMethod = NULL;
  19277. BfMemberSetEntry* entry = NULL;
  19278. if (mCurTypeInstance->mTypeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  19279. nextMethod = (BfMethodDef*)entry->mMemberDef;
  19280. while (nextMethod != NULL)
  19281. {
  19282. auto checkMethod = nextMethod;
  19283. nextMethod = nextMethod->mNextWithSameName;
  19284. if (checkMethod == methodDef)
  19285. continue;
  19286. if (!checkMethod->mIsExtern)
  19287. continue;
  19288. auto checkMethodInstance = mCurTypeInstance->mMethodInstanceGroups[checkMethod->mIdx].mDefault;
  19289. if (checkMethodInstance == NULL)
  19290. continue;
  19291. if (!CompareMethodSignatures(checkMethodInstance, mCurMethodInstance))
  19292. continue;
  19293. // Take over function
  19294. mCurMethodInstance->mIRFunction = prevFunc;
  19295. }
  19296. if (!mCurMethodInstance->mIRFunction)
  19297. {
  19298. BfLogSysM("Function collision from inner override erased prevFunc %p: %d\n", methodInstance, prevFunc.mId);
  19299. if (!mIsComptimeModule)
  19300. mBfIRBuilder->Func_SafeRename(prevFunc);
  19301. }
  19302. }
  19303. else if (methodDef->mIsExtern)
  19304. {
  19305. // Allow this
  19306. BfLogSysM("Function collision allowed multiple extern functions for %p: %d\n", methodInstance, prevFunc.mId);
  19307. }
  19308. else if (typeInstance->IsIRFuncUsed(prevFunc))
  19309. {
  19310. // We can have a collision of names when we have generic methods that differ only in
  19311. // their constraints, but they should only collide in their unspecialized form
  19312. // since only one will be chosen for a given concrete type
  19313. if (!mIsComptimeModule)
  19314. mCurMethodInstance->mMangleWithIdx = true;
  19315. mangledName.Clear();
  19316. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), mCurMethodInstance);
  19317. prevFunc = mBfIRBuilder->GetFunction(mangledName);
  19318. BfLogSysM("Function collision forced mangleWithIdx for %p: %d\n", methodInstance, prevFunc.mId);
  19319. }
  19320. else
  19321. {
  19322. BfLogSysM("Function collision erased prevFunc %p: %d\n", methodInstance, prevFunc.mId);
  19323. if (!mIsComptimeModule)
  19324. mBfIRBuilder->Func_SafeRename(prevFunc);
  19325. }
  19326. }
  19327. }
  19328. if (typeInstance != mContext->mBfObjectType)
  19329. {
  19330. // Only allow attributes on System.Object methods that can be handled inside the DefBuilder
  19331. GetMethodCustomAttributes(methodInstance);
  19332. }
  19333. // if (prevFunc)
  19334. // {
  19335. // if (methodDef->mIsExtern)
  19336. // {
  19337. // BfLogSysM("Reusing function for %p: %d\n", methodInstance, prevFunc.mId);
  19338. // methodInstance->mIRFunction = prevFunc;
  19339. // }
  19340. // else
  19341. // {
  19342. // if ((methodInstance->IsSpecializedByAutoCompleteMethod()) ||
  19343. // ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mResolveType >= BfResolveType_GoToDefinition)))
  19344. // {
  19345. // // If we're doing re-pass over the methods for something like BfResolveType_ShowFileSymbolReferences, then allow this collision
  19346. // BfLogSysM("Ignoring function name collision\n");
  19347. // }
  19348. // else
  19349. // {
  19350. // if (methodDef->mMethodDeclaration == NULL)
  19351. // {
  19352. // AssertErrorState();
  19353. // }
  19354. // else
  19355. // {
  19356. // BF_ASSERT(mIsSpecialModule);
  19357. // if ((mCompiler->mRevision == 1) && (HasCompiledOutput()))
  19358. // {
  19359. // // We shouldn't have name collisions on the first run!
  19360. // AssertErrorState();
  19361. // }
  19362. // }
  19363. // }
  19364. // BfLogSysM("Before erase\n");
  19365. // mBfIRBuilder->Func_EraseFromParent(prevFunc);
  19366. // }
  19367. // }
  19368. bool isIntrinsic = false;
  19369. if (!methodInstance->mIRFunction)
  19370. {
  19371. BfIRFunction func;
  19372. bool wantsLLVMFunc = ((!typeInstance->IsUnspecializedType() || (mIsComptimeModule)) &&
  19373. (!methodDef->IsEmptyPartial())) && (funcType);
  19374. /*if (mCurTypeInstance->mTypeDef->mName->ToString() == "ClassA")
  19375. {
  19376. if (!mIsReified)
  19377. wantsLLVMFunc = false;
  19378. }*/
  19379. if (wantsLLVMFunc)
  19380. {
  19381. func = GetIntrinsic(methodInstance, true);
  19382. if (func)
  19383. {
  19384. isIntrinsic = true;
  19385. }
  19386. else
  19387. {
  19388. func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, mangledName);
  19389. BfLogSysM("Creating FuncId:%d %s in module %p\n", func.mId, mangledName.c_str(), this);
  19390. if (methodInstance->mAlwaysInline)
  19391. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_AlwaysInline);
  19392. // if (prevFunc)
  19393. // BfLogSysM("Removing Func %d, replacing with %d\n", prevFunc.mId, func.mId);
  19394. }
  19395. methodInstance->mIRFunction = func;
  19396. //if (!ignoreWrites)
  19397. //BF_ASSERT(!func.IsFake());
  19398. }
  19399. }
  19400. if (outIsIntrinsic != NULL)
  19401. *outIsIntrinsic = isIntrinsic;
  19402. if (!isIntrinsic)
  19403. SetupIRMethod(methodInstance, methodInstance->mIRFunction, methodInstance->mAlwaysInline);
  19404. }
  19405. void BfModule::CheckHotMethod(BfMethodInstance* methodInstance, const StringImpl& inMangledName)
  19406. {
  19407. if (methodInstance->mHotMethod != NULL)
  19408. return;
  19409. if ((mCompiler->mOptions.mAllowHotSwapping) && (!methodInstance->mIsUnspecialized))
  19410. {
  19411. auto srcTypeInst = methodInstance->GetOwner();
  19412. StringT<128> mangledName = inMangledName;
  19413. if (mangledName.IsEmpty())
  19414. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), methodInstance);
  19415. // We always keep the current primary method at the same address
  19416. BfHotMethod* hotMethod;
  19417. BfHotMethod** hotMethodPtr;
  19418. if (mCompiler->mHotData->mMethodMap.TryAdd(mangledName, NULL, &hotMethodPtr))
  19419. {
  19420. hotMethod = new BfHotMethod();
  19421. *hotMethodPtr = hotMethod;
  19422. hotMethod->mRefCount = 1;
  19423. hotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_IsBound);
  19424. #ifdef BF_DBG_HOTMETHOD_IDX
  19425. static int sMethodIdx = 0;
  19426. hotMethod->mMethodIdx = sMethodIdx++;
  19427. #endif
  19428. BfLogSysM("HotMethodData %p created for method %p %s - %s\n", hotMethod, methodInstance, MethodToString(methodInstance).c_str(), mangledName.c_str());
  19429. }
  19430. else
  19431. {
  19432. hotMethod = *hotMethodPtr;
  19433. if ((hotMethod->mFlags & BfHotDepDataFlag_IsBound) != 0)
  19434. {
  19435. // This is a duplicate mangled name - we link to this new entry via a 'BfHotDupMethod'
  19436. auto prevHotMethod = *hotMethodPtr;
  19437. hotMethod = new BfHotMethod();
  19438. hotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_IsBound);
  19439. BfHotDupMethod* hotDupMethod = new BfHotDupMethod(hotMethod);
  19440. hotDupMethod->mRefCount++;
  19441. prevHotMethod->mReferences.Add(hotDupMethod);
  19442. prevHotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_HasDup);
  19443. BfLogSysM("HotMethodData %p (duplicate of %p) created for method %p %s - %s\n", hotMethod, prevHotMethod, methodInstance, MethodToString(methodInstance).c_str(), mangledName.c_str());
  19444. }
  19445. else if (mCompiler->IsHotCompile())
  19446. {
  19447. // Link the previous version into the mPrevVersion
  19448. BfHotMethod* prevMethod = new BfHotMethod();
  19449. prevMethod->mRefCount = 1;
  19450. prevMethod->mPrevVersion = hotMethod->mPrevVersion;
  19451. hotMethod->mPrevVersion = prevMethod;
  19452. prevMethod->mSrcTypeVersion = hotMethod->mSrcTypeVersion;
  19453. hotMethod->mSrcTypeVersion = NULL;
  19454. prevMethod->mFlags = hotMethod->mFlags;
  19455. hotMethod->mFlags = BfHotDepDataFlag_IsBound;
  19456. hotMethod->mReferences.MoveTo(prevMethod->mReferences);
  19457. #ifdef BF_DBG_HOTMETHOD_NAME
  19458. prevMethod->mMangledName = hotMethod->mMangledName;
  19459. #endif
  19460. BfLogSysM("HotMethodData %p created for prevmethod of %p for method %p %s\n", prevMethod, hotMethod, methodInstance, MethodToString(methodInstance).c_str());
  19461. }
  19462. else
  19463. {
  19464. BfLogSysM("HotMethodData %p used for method %p %s - %s\n", hotMethod, methodInstance, MethodToString(methodInstance).c_str(), mangledName.c_str());
  19465. hotMethod->Clear(true);
  19466. hotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_IsBound);
  19467. }
  19468. }
  19469. if (methodInstance->mIsClosure)
  19470. {
  19471. hotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_RetainMethodWithoutBinding);
  19472. }
  19473. hotMethod->mSrcTypeVersion = srcTypeInst->mHotTypeData->GetLatestVersion();
  19474. hotMethod->mSrcTypeVersion->mRefCount++;
  19475. hotMethod->mRefCount++;
  19476. #ifdef BF_DBG_HOTMETHOD_NAME
  19477. hotMethod->mMangledName = mangledName;
  19478. #endif
  19479. if ((methodInstance->mMethodInstanceGroup->IsImplemented()) && (!IsHotCompile()))
  19480. hotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_IsOriginalBuild);
  19481. methodInstance->mHotMethod = hotMethod;
  19482. }
  19483. }
  19484. static void StackOverflow()
  19485. {
  19486. int i = 0;
  19487. if (i == 0)
  19488. StackOverflow();
  19489. }
  19490. void BfModule::StartMethodDeclaration(BfMethodInstance* methodInstance, BfMethodState* prevMethodState)
  19491. {
  19492. methodInstance->mHasStartedDeclaration = true;
  19493. auto methodDef = methodInstance->mMethodDef;
  19494. auto typeInstance = methodInstance->GetOwner();
  19495. bool hasNonGenericParams = false;
  19496. bool hasGenericParams = false;
  19497. int dependentGenericStartIdx = 0;
  19498. if (methodDef->mIsLocalMethod)
  19499. {
  19500. // If we're a local generic method inside an outer generic method, we can still be considered unspecialized
  19501. // if our outer method's generic args are specialized but ours are unspecialized. This is because locals get
  19502. // instantiated uniquely for each specialized or unspecialized pass through the outer method, but the local
  19503. // method still 'inherits' the outer's generic arguments -- but we still need to make an unspecialized pass
  19504. // over the local method each time
  19505. auto rootMethodInstance = prevMethodState->GetRootMethodState()->mMethodInstance;
  19506. dependentGenericStartIdx = 0;
  19507. if (rootMethodInstance != NULL)
  19508. {
  19509. if (rootMethodInstance->mMethodInfoEx != NULL)
  19510. dependentGenericStartIdx = (int)rootMethodInstance->mMethodInfoEx->mMethodGenericArguments.size();
  19511. methodInstance->mIsUnspecialized = rootMethodInstance->mIsUnspecialized;
  19512. methodInstance->mIsUnspecializedVariation = rootMethodInstance->mIsUnspecializedVariation;
  19513. }
  19514. }
  19515. for (int genericArgIdx = dependentGenericStartIdx; genericArgIdx < (int)methodInstance->GetNumGenericArguments(); genericArgIdx++)
  19516. {
  19517. auto genericArgType = methodInstance->mMethodInfoEx->mMethodGenericArguments[genericArgIdx];
  19518. if (genericArgType->IsGenericParam())
  19519. {
  19520. hasGenericParams = true;
  19521. auto genericParam = (BfGenericParamType*)genericArgType;
  19522. methodInstance->mIsUnspecialized = true;
  19523. if ((genericParam->mGenericParamKind != BfGenericParamKind_Method) || (genericParam->mGenericParamIdx != genericArgIdx))
  19524. methodInstance->mIsUnspecializedVariation = true;
  19525. }
  19526. else
  19527. {
  19528. hasNonGenericParams = true;
  19529. if (genericArgType->IsUnspecializedType())
  19530. {
  19531. methodInstance->mIsUnspecialized = true;
  19532. methodInstance->mIsUnspecializedVariation = true;
  19533. }
  19534. }
  19535. }
  19536. if ((hasGenericParams) && (hasNonGenericParams))
  19537. {
  19538. methodInstance->mIsUnspecializedVariation = true;
  19539. }
  19540. if (typeInstance->IsUnspecializedType())
  19541. {
  19542. // A specialized method within an unspecialized type is considered an unspecialized variation -- in the sense that we don't
  19543. // actually want to do method processing on it
  19544. if ((!methodInstance->mIsUnspecialized) && (methodInstance->GetNumGenericArguments() != 0))
  19545. methodInstance->mIsUnspecializedVariation = true;
  19546. methodInstance->mIsUnspecialized = true;
  19547. }
  19548. if (methodInstance->mIsUnspecializedVariation)
  19549. BF_ASSERT(methodInstance->mIsUnspecialized);
  19550. //TODO: Why did we do this?
  19551. if (methodDef->mMethodType == BfMethodType_Mixin)
  19552. {
  19553. if (methodInstance->IsSpecializedGenericMethod())
  19554. methodInstance->mIsUnspecializedVariation = true;
  19555. methodInstance->mIsUnspecialized = true;
  19556. }
  19557. }
  19558. // methodDeclaration is NULL for default constructors
  19559. void BfModule::DoMethodDeclaration(BfMethodDeclaration* methodDeclaration, bool isTemporaryFunc, bool addToWorkList)
  19560. {
  19561. BP_ZONE("BfModule::DoMethodDeclaration");
  19562. // We could trigger a DoMethodDeclaration from a const resolver or other location, so we reset it here
  19563. // to effectively make mIgnoreWrites method-scoped
  19564. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, mWantsIRIgnoreWrites || mCurMethodInstance->mIsUnspecialized || mCurTypeInstance->mResolvingVarField);
  19565. SetAndRestoreValue<bool> prevIsCapturingMethodMatchInfo;
  19566. SetAndRestoreValue<bool> prevAllowLockYield(mContext->mAllowLockYield, false);
  19567. BfTypeState typeState(mCurTypeInstance);
  19568. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  19569. if (mCompiler->IsAutocomplete())
  19570. prevIsCapturingMethodMatchInfo.Init(mCompiler->mResolvePassData->mAutoComplete->mIsCapturingMethodMatchInfo, false);
  19571. if (mCurMethodInstance->mMethodInstanceGroup->mOnDemandKind == BfMethodOnDemandKind_NoDecl_AwaitingReference)
  19572. mCurMethodInstance->mMethodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_Decl_AwaitingReference;
  19573. BfMethodState methodState;
  19574. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  19575. methodState.mTempKind = BfMethodState::TempKind_Static;
  19576. defer({ mCurMethodInstance->mHasBeenDeclared = true; });
  19577. // If we are doing this then we may end up creating methods when var types are unknown still, failing on splat/zero-sized info
  19578. BF_ASSERT((!mCurTypeInstance->mResolvingVarField) || (mBfIRBuilder->mIgnoreWrites));
  19579. bool ignoreWrites = mBfIRBuilder->mIgnoreWrites;
  19580. // if ((!isTemporaryFunc) && (mCurTypeInstance->mDefineState < BfTypeDefineState_Defined))
  19581. // {
  19582. // BF_ASSERT(mContext->mResolvingVarField);
  19583. // isTemporaryFunc = true;
  19584. // }
  19585. if ((mAwaitingInitFinish) && (!mBfIRBuilder->mIgnoreWrites))
  19586. FinishInit();
  19587. auto typeInstance = mCurTypeInstance;
  19588. auto typeDef = typeInstance->mTypeDef;
  19589. auto methodDef = mCurMethodInstance->mMethodDef;
  19590. BF_ASSERT(methodDef->mName != "__ASSERTNAME");
  19591. if (methodDef->mName == "__FATALERRORNAME")
  19592. BFMODULE_FATAL(this, "__FATALERRORNAME");
  19593. if (methodDef->mName == "__STACKOVERFLOW")
  19594. StackOverflow();
  19595. if (typeInstance->IsClosure())
  19596. {
  19597. if (methodDef->mName == "Invoke")
  19598. return;
  19599. }
  19600. auto methodInstance = mCurMethodInstance;
  19601. if ((methodInstance->IsSpecializedByAutoCompleteMethod()) || (mCurTypeInstance->IsFunction()))
  19602. addToWorkList = false;
  19603. if (!methodInstance->mHasStartedDeclaration)
  19604. StartMethodDeclaration(methodInstance, prevMethodState.mPrevVal);
  19605. BfAutoComplete* bfAutocomplete = NULL;
  19606. if (mCompiler->mResolvePassData != NULL)
  19607. bfAutocomplete = mCompiler->mResolvePassData->mAutoComplete;
  19608. if (methodInstance->mMethodInfoEx != NULL)
  19609. {
  19610. BfTypeInstance* unspecializedTypeInstance = NULL;
  19611. Array<BfTypeReference*> deferredResolveTypes;
  19612. for (int genericParamIdx = 0; genericParamIdx < (int)methodInstance->mMethodInfoEx->mGenericParams.size(); genericParamIdx++)
  19613. {
  19614. auto genericParam = methodInstance->mMethodInfoEx->mGenericParams[genericParamIdx];
  19615. if (genericParamIdx < (int)methodDef->mGenericParams.size())
  19616. {
  19617. genericParam->mExternType = GetGenericParamType(BfGenericParamKind_Method, genericParamIdx);
  19618. }
  19619. else
  19620. {
  19621. auto externConstraintDef = genericParam->GetExternConstraintDef();
  19622. genericParam->mExternType = ResolveTypeRef(externConstraintDef->mTypeRef);
  19623. auto autoComplete = mCompiler->GetAutoComplete();
  19624. if (autoComplete != NULL)
  19625. autoComplete->CheckTypeRef(externConstraintDef->mTypeRef, false);
  19626. if (genericParam->mExternType != NULL)
  19627. {
  19628. //
  19629. }
  19630. else
  19631. genericParam->mExternType = GetPrimitiveType(BfTypeCode_Var);
  19632. }
  19633. ResolveGenericParamConstraints(genericParam, methodInstance->mIsUnspecialized, &deferredResolveTypes);
  19634. if (genericParamIdx < (int)methodDef->mGenericParams.size())
  19635. {
  19636. auto genericParamDef = methodDef->mGenericParams[genericParamIdx];
  19637. if (bfAutocomplete != NULL)
  19638. {
  19639. for (auto nameNode : genericParamDef->mNameNodes)
  19640. {
  19641. HandleMethodGenericParamRef(nameNode, typeDef, methodDef, genericParamIdx);
  19642. }
  19643. }
  19644. }
  19645. }
  19646. for (auto typeRef : deferredResolveTypes)
  19647. auto constraintType = ResolveTypeRef(typeRef, BfPopulateType_Declaration, BfResolveTypeRefFlag_None);
  19648. for (auto genericParam : methodInstance->mMethodInfoEx->mGenericParams)
  19649. AddDependency(genericParam, mCurTypeInstance);
  19650. }
  19651. if ((methodInstance->mIsAutocompleteMethod) && (methodDeclaration != NULL) && (!methodInstance->IsSpecializedGenericMethod()) && (methodDef->mIdx >= 0))
  19652. {
  19653. auto autoComplete = mCompiler->mResolvePassData->mAutoComplete;
  19654. BfAstNode* nameNode = methodDeclaration->mNameNode;
  19655. if (nameNode == NULL)
  19656. {
  19657. if (auto ctorDeclaration = BfNodeDynCast<BfConstructorDeclaration>(methodDeclaration))
  19658. nameNode = ctorDeclaration->mThisToken;
  19659. }
  19660. if ((autoComplete->IsAutocompleteNode(nameNode)) && (autoComplete->mResolveType != BfResolveType_Autocomplete))
  19661. {
  19662. autoComplete->mInsertStartIdx = nameNode->GetSrcStart();
  19663. autoComplete->mInsertEndIdx = nameNode->GetSrcEnd();
  19664. autoComplete->mDefType = typeDef;
  19665. autoComplete->mDefMethod = methodDef;
  19666. autoComplete->SetDefinitionLocation(nameNode);
  19667. if (methodDef->mIsOverride)
  19668. {
  19669. bool found = false;
  19670. for (int virtIdx = 0; virtIdx < (int)typeInstance->mVirtualMethodTable.size(); virtIdx++)
  19671. {
  19672. auto& ventry = typeInstance->mVirtualMethodTable[virtIdx];
  19673. if (ventry.mDeclaringMethod.mMethodNum == -1)
  19674. continue;
  19675. BfMethodInstance* virtMethod = ventry.mImplementingMethod;
  19676. if (virtMethod != NULL)
  19677. {
  19678. auto virtMethodDeclaration = virtMethod->mMethodDef->GetMethodDeclaration();
  19679. if ((virtMethod->GetOwner() == typeInstance) && (virtMethodDeclaration != NULL) &&
  19680. (virtMethodDeclaration->GetSrcStart() == methodDeclaration->GetSrcStart()))
  19681. {
  19682. // Is matching method
  19683. if (virtIdx < (int)typeInstance->mBaseType->mVirtualMethodTable.size())
  19684. {
  19685. auto baseType = typeInstance->mBaseType;
  19686. if (baseType != NULL)
  19687. {
  19688. found = true;
  19689. while ((baseType->mBaseType != NULL) && (virtIdx < baseType->mBaseType->mVirtualMethodTableSize))
  19690. baseType = baseType->mBaseType;
  19691. BfMethodInstance* baseVirtMethod = baseType->mVirtualMethodTable[virtIdx].mImplementingMethod;
  19692. autoComplete->SetDefinitionLocation(baseVirtMethod->mMethodDef->GetRefNode(), true);
  19693. autoComplete->mDefType = baseType->mTypeDef;
  19694. autoComplete->mDefMethod = baseVirtMethod->mMethodDef;
  19695. }
  19696. }
  19697. break;
  19698. }
  19699. }
  19700. }
  19701. if ((!found) && (autoComplete->mIsGetDefinition) && (methodDef->mDeclaringType->IsExtension()))
  19702. {
  19703. for (auto& methodGroup : typeInstance->mMethodInstanceGroups)
  19704. {
  19705. auto defaultMethod = methodGroup.mDefault;
  19706. if (defaultMethod == NULL)
  19707. continue;
  19708. if (!defaultMethod->mMethodDef->mIsExtern)
  19709. continue;
  19710. if (!CompareMethodSignatures(defaultMethod, methodInstance))
  19711. continue;
  19712. autoComplete->SetDefinitionLocation(defaultMethod->mMethodDef->GetRefNode(), true);
  19713. autoComplete->mDefType = typeInstance->mTypeDef;
  19714. autoComplete->mDefMethod = defaultMethod->mMethodDef;
  19715. }
  19716. }
  19717. }
  19718. }
  19719. }
  19720. bool reportErrors = true;
  19721. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL))
  19722. reportErrors = true;
  19723. // Only the defining contexts needs to report errors here
  19724. SetAndRestoreValue<bool> prevReporErrors(mReportErrors, reportErrors);
  19725. if (methodDef->mMethodType == BfMethodType_Dtor)
  19726. {
  19727. if (methodDef->mIsStatic)
  19728. {
  19729. }
  19730. else
  19731. {
  19732. if ((typeInstance->IsStruct()) || (typeInstance->IsTypedPrimitive()))
  19733. {
  19734. BfAstNode* refNode = methodDeclaration;
  19735. if (refNode == NULL)
  19736. {
  19737. // Whatever caused this ctor to be generated should have caused another failure
  19738. // But that failure might not be generated until the ctor is generated
  19739. }
  19740. else
  19741. {
  19742. auto dtorDecl = BfNodeDynCast<BfDestructorDeclaration>(methodDeclaration);
  19743. if (dtorDecl != NULL)
  19744. refNode = dtorDecl->mThisToken;
  19745. Fail("Structs cannot have destructors", refNode);
  19746. }
  19747. }
  19748. auto methodDeclaration = methodDef->GetMethodDeclaration();
  19749. if ((methodDeclaration != NULL) && (methodDeclaration->mVirtualSpecifier != NULL) &&
  19750. (mCurTypeInstance != mContext->mBfObjectType))
  19751. {
  19752. Fail("Virtual specifier is not required, all destructors are implicitly virtual.", methodDeclaration->mVirtualSpecifier);
  19753. }
  19754. }
  19755. }
  19756. BfType* resolvedReturnType = NULL;
  19757. if (((methodDef->mMethodType == BfMethodType_Normal) || (methodDef->mMethodType == BfMethodType_Extension) || (methodDef->mMethodType == BfMethodType_CtorCalcAppend) ||
  19758. (methodDef->mMethodType == BfMethodType_PropertyGetter) || (methodDef->mMethodType == BfMethodType_Operator)) &&
  19759. (methodDef->mReturnTypeRef != NULL))
  19760. {
  19761. SetAndRestoreValue<bool> prevIngoreErrors(mIgnoreErrors, mIgnoreErrors || (methodDef->GetPropertyDeclaration() != NULL));
  19762. BfResolveTypeRefFlags flags = (BfResolveTypeRefFlags)(BfResolveTypeRefFlag_NoResolveGenericParam | BfResolveTypeRefFlag_AllowRef | BfResolveTypeRefFlag_AllowRefGeneric);
  19763. if ((((methodInstance->mComptimeFlags & BfComptimeFlag_ConstEval) != 0) || (methodInstance->mIsAutocompleteMethod))
  19764. && (methodDef->mReturnTypeRef->IsA<BfVarTypeReference>()))
  19765. resolvedReturnType = GetPrimitiveType(BfTypeCode_Var);
  19766. else
  19767. resolvedReturnType = ResolveTypeRef(methodDef->mReturnTypeRef, BfPopulateType_Declaration, flags);
  19768. if (resolvedReturnType == NULL)
  19769. resolvedReturnType = GetPrimitiveType(BfTypeCode_Var);
  19770. if ((methodDef->mIsReadOnly) && (!resolvedReturnType->IsRef()))
  19771. {
  19772. if (auto methodDeclaration = BfNodeDynCast<BfMethodDeclaration>(methodInstance->mMethodDef->mMethodDeclaration))
  19773. if (methodDeclaration->mReadOnlySpecifier != NULL)
  19774. Fail("Readonly specifier is only valid on 'ref' return types", methodDeclaration->mReadOnlySpecifier);
  19775. }
  19776. }
  19777. else
  19778. {
  19779. resolvedReturnType = ResolveTypeDef(mSystem->mTypeVoid);
  19780. }
  19781. BF_ASSERT(resolvedReturnType != NULL);
  19782. mCurMethodInstance->mReturnType = resolvedReturnType;
  19783. //TODO: We used to NOT add the return value dependency for specialized methods, but when we have types that are
  19784. // specialized based on the method's generic param then they can get deleted if no one else has referred to them (yet)
  19785. //if (!methodInstance->IsSpecializedGenericMethod())
  19786. AddDependency(resolvedReturnType, typeInstance, BfDependencyMap::DependencyFlag_ParamOrReturnValue);
  19787. if (methodDef->mExplicitInterface != NULL)
  19788. {
  19789. auto autoComplete = mCompiler->GetAutoComplete();
  19790. if (autoComplete != NULL)
  19791. autoComplete->CheckTypeRef(methodDef->mExplicitInterface, false);
  19792. auto explicitType = ResolveTypeRef(methodDef->mExplicitInterface, BfPopulateType_Declaration);
  19793. BfTypeInstance* explicitInterface = NULL;
  19794. if (explicitType != NULL)
  19795. explicitInterface = explicitType->ToTypeInstance();
  19796. if (explicitInterface != NULL)
  19797. {
  19798. mCurMethodInstance->GetMethodInfoEx()->mExplicitInterface = explicitInterface->ToTypeInstance();
  19799. if (autoComplete != NULL)
  19800. {
  19801. BfTokenNode* dotToken = NULL;
  19802. BfAstNode* nameNode = NULL;
  19803. if (auto methodDeclaration = BfNodeDynCast<BfMethodDeclaration>(methodDef->mMethodDeclaration))
  19804. {
  19805. dotToken = methodDeclaration->mExplicitInterfaceDotToken;
  19806. nameNode = methodDeclaration->mNameNode;
  19807. }
  19808. autoComplete->CheckExplicitInterface(explicitInterface, dotToken, nameNode);
  19809. }
  19810. }
  19811. if ((mCurMethodInstance->mMethodInfoEx != NULL) && (mCurMethodInstance->mMethodInfoEx->mExplicitInterface != NULL))
  19812. {
  19813. bool interfaceFound = false;
  19814. for (auto ifaceInst : typeInstance->mInterfaces)
  19815. interfaceFound |= ifaceInst.mInterfaceType == mCurMethodInstance->mMethodInfoEx->mExplicitInterface;
  19816. if (!interfaceFound)
  19817. {
  19818. if (methodDef->mMethodDeclaration != NULL)
  19819. Fail("Containing class has not declared to implement this interface", methodDef->mMethodDeclaration);
  19820. else
  19821. {
  19822. // For property decls, we should have already given the error during type population
  19823. if (mCompiler->mRevision == 1)
  19824. AssertErrorState();
  19825. }
  19826. }
  19827. }
  19828. }
  19829. bool isThisStruct = mCurTypeInstance->IsStruct();
  19830. BfType* thisType = NULL;
  19831. if ((!methodDef->mIsStatic) && (!mCurTypeInstance->IsValuelessType()))
  19832. {
  19833. if ((isThisStruct) || (mCurTypeInstance->IsTypedPrimitive()))
  19834. {
  19835. thisType = mCurTypeInstance;
  19836. if (thisType == NULL)
  19837. return;
  19838. if ((thisType->IsSplattable()) && (!methodDef->HasNoThisSplat()))
  19839. {
  19840. BfTypeUtils::SplatIterate([&](BfType* checkType)
  19841. {
  19842. PopulateType(checkType, BfPopulateType_Data);
  19843. }, thisType);
  19844. }
  19845. }
  19846. else
  19847. {
  19848. thisType = mCurTypeInstance;
  19849. PopulateType(thisType, BfPopulateType_Declaration);
  19850. }
  19851. }
  19852. int implicitParamCount = 0;
  19853. if ((mCurMethodInstance->mMethodInfoEx != NULL) && (mCurMethodInstance->mMethodInfoEx->mClosureInstanceInfo != NULL))
  19854. implicitParamCount = (int)methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureEntries.size();
  19855. methodInstance->mMethodDef->mParams.Reserve((int)methodDef->mParams.size());
  19856. bool hadDelegateParams = false;
  19857. bool hadParams = false;
  19858. for (int paramIdx = 0; paramIdx < (int)methodDef->mParams.size() + implicitParamCount; paramIdx++)
  19859. {
  19860. BfClosureCapturedEntry* closureCaptureEntry = NULL;
  19861. BfParameterDef* paramDef = NULL;
  19862. int paramDefIdx = -1;
  19863. if (paramIdx < implicitParamCount)
  19864. closureCaptureEntry = &methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureEntries[paramIdx];
  19865. else
  19866. {
  19867. paramDefIdx = paramIdx - implicitParamCount;
  19868. paramDef = methodDef->mParams[paramDefIdx];
  19869. }
  19870. if (hadParams)
  19871. break;
  19872. if ((paramDef != NULL) && (paramDef->mParamKind == BfParamKind_VarArgs))
  19873. continue;
  19874. if ((paramDef != NULL) && (mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL) &&
  19875. (paramDef->mParamKind != BfParamKind_AppendIdx))
  19876. {
  19877. mCompiler->mResolvePassData->mAutoComplete->CheckTypeRef(paramDef->mTypeRef, false);
  19878. if (mCompiler->mResolvePassData->mAutoComplete->IsAutocompleteNode(paramDef->mTypeRef))
  19879. mCompiler->mResolvePassData->mAutoComplete->AddEntry(AutoCompleteEntry("token", "in"), paramDef->mTypeRef->ToString());
  19880. }
  19881. if ((paramDef != NULL) && (paramDef->mParamDeclaration != NULL) && (paramDef->mParamDeclaration->mAttributes != NULL))
  19882. {
  19883. if (methodInstance->GetMethodInfoEx()->mMethodCustomAttributes == NULL)
  19884. methodInstance->mMethodInfoEx->mMethodCustomAttributes = new BfMethodCustomAttributes();
  19885. while ((int)methodInstance->mMethodInfoEx->mMethodCustomAttributes->mParamCustomAttributes.size() < paramIdx)
  19886. methodInstance->mMethodInfoEx->mMethodCustomAttributes->mParamCustomAttributes.push_back(NULL);
  19887. auto customAttributes = GetCustomAttributes(paramDef->mParamDeclaration->mAttributes, BfAttributeTargets_Parameter);
  19888. methodInstance->mMethodInfoEx->mMethodCustomAttributes->mParamCustomAttributes.push_back(customAttributes);
  19889. }
  19890. BfType* resolvedParamType = NULL;
  19891. if (closureCaptureEntry != NULL)
  19892. resolvedParamType = closureCaptureEntry->mType;
  19893. else if (paramDef->mTypeRef->IsA<BfLetTypeReference>())
  19894. {
  19895. Fail("Cannot declare 'let' parameters", paramDef->mTypeRef);
  19896. resolvedParamType = mContext->mBfObjectType;
  19897. }
  19898. else if (paramDef->mTypeRef->IsA<BfVarTypeReference>())
  19899. {
  19900. if (methodDef->mMethodType != BfMethodType_Mixin)
  19901. {
  19902. Fail("Cannot declare var parameters", paramDef->mTypeRef);
  19903. resolvedParamType = mContext->mBfObjectType;
  19904. }
  19905. else
  19906. resolvedParamType = GetPrimitiveType(BfTypeCode_Var);
  19907. }
  19908. BfType* unresolvedParamType = resolvedParamType;
  19909. bool wasGenericParam = false;
  19910. if (resolvedParamType == NULL)
  19911. {
  19912. BfResolveTypeRefFlags resolveFlags = (BfResolveTypeRefFlags)(BfResolveTypeRefFlag_NoResolveGenericParam | BfResolveTypeRefFlag_AllowRef | BfResolveTypeRefFlag_AllowRefGeneric | BfResolveTypeRefFlag_AllowGenericMethodParamConstValue);
  19913. if (paramDef->mParamKind == BfParamKind_ExplicitThis)
  19914. resolveFlags = (BfResolveTypeRefFlags)(resolveFlags | BfResolveTypeRefFlag_NoWarnOnMut);
  19915. resolvedParamType = ResolveTypeRef(paramDef->mTypeRef, BfPopulateType_Declaration, resolveFlags);
  19916. if ((paramDef->mParamKind == BfParamKind_ExplicitThis) && (resolvedParamType != NULL) && (resolvedParamType->IsRef()))
  19917. resolvedParamType = resolvedParamType->GetUnderlyingType();
  19918. }
  19919. if (resolvedParamType == NULL)
  19920. {
  19921. resolvedParamType = GetPrimitiveType(BfTypeCode_Var);
  19922. unresolvedParamType = resolvedParamType;
  19923. if (mCurTypeInstance->IsBoxed())
  19924. {
  19925. auto boxedType = (BfBoxedType*)mCurTypeInstance;
  19926. // If we failed a lookup here then we better have also failed it in the original type
  19927. BF_ASSERT(boxedType->mElementType->ToTypeInstance()->mModule->mHadBuildError || mContext->mFailTypes.Contains(boxedType->mElementType->ToTypeInstance()));
  19928. }
  19929. }
  19930. if (!methodInstance->IsSpecializedGenericMethod())
  19931. AddDependency(resolvedParamType, typeInstance, BfDependencyMap::DependencyFlag_ParamOrReturnValue);
  19932. PopulateType(resolvedParamType, BfPopulateType_Declaration);
  19933. AddDependency(resolvedParamType, mCurTypeInstance, BfDependencyMap::DependencyFlag_LocalUsage);
  19934. if ((paramDef != NULL) && (paramDef->mParamDeclaration != NULL) && (paramDef->mParamDeclaration->mInitializer != NULL) &&
  19935. (!paramDef->mParamDeclaration->mInitializer->IsA<BfBlock>()))
  19936. {
  19937. if (paramDef->mParamKind == BfParamKind_Params)
  19938. {
  19939. BfAstNode* refNode = paramDef->mParamDeclaration->mEqualsNode;
  19940. if (refNode != NULL)
  19941. refNode = paramDef->mParamDeclaration->mModToken;
  19942. Fail("Cannot specify a default value for a 'params' parameter", refNode);
  19943. }
  19944. BfTypedValue defaultValue;
  19945. if (resolvedParamType->IsConstExprValue())
  19946. {
  19947. auto constExprType = (BfConstExprValueType*)resolvedParamType;
  19948. BfExprEvaluator exprEvaluator(this);
  19949. exprEvaluator.mExpectingType = constExprType->mType;
  19950. exprEvaluator.GetLiteral(NULL, constExprType->mValue);
  19951. defaultValue = exprEvaluator.GetResult();
  19952. }
  19953. else
  19954. {
  19955. BfTypeState typeState;
  19956. typeState.mType = mCurTypeInstance;
  19957. typeState.mCurTypeDef = methodDef->mDeclaringType;
  19958. //typeState.mCurMethodDef = methodDef;
  19959. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  19960. BfConstResolver constResolver(this);
  19961. defaultValue = constResolver.Resolve(paramDef->mParamDeclaration->mInitializer, resolvedParamType, (BfConstResolveFlags)(BfConstResolveFlag_NoCast | BfConstResolveFlag_AllowGlobalVariable));
  19962. if ((defaultValue) && (defaultValue.mType != resolvedParamType))
  19963. {
  19964. SetAndRestoreValue<bool> prevIgnoreWrite(mBfIRBuilder->mIgnoreWrites, true);
  19965. auto castedDefaultValue = Cast(paramDef->mParamDeclaration->mInitializer, defaultValue, resolvedParamType, (BfCastFlags)(BfCastFlags_SilentFail | BfCastFlags_NoConversionOperator));
  19966. if ((castedDefaultValue) && (castedDefaultValue.mValue.IsConst()))
  19967. {
  19968. defaultValue = castedDefaultValue; // Good!
  19969. }
  19970. else if (!CanCast(defaultValue, resolvedParamType))
  19971. {
  19972. // We only care that we get a constant value that can be implicitly casted at the callsite- even if that requires
  19973. // a conversion operator.
  19974. // This should throw an error
  19975. defaultValue = Cast(paramDef->mParamDeclaration->mInitializer, defaultValue, resolvedParamType);
  19976. AssertErrorState();
  19977. if (!defaultValue.mValue.IsConst())
  19978. defaultValue = BfTypedValue();
  19979. }
  19980. }
  19981. }
  19982. if (!defaultValue)
  19983. {
  19984. defaultValue = GetDefaultTypedValue(resolvedParamType);
  19985. if (!defaultValue.mValue.IsConst())
  19986. defaultValue = BfTypedValue();
  19987. }
  19988. if (defaultValue)
  19989. {
  19990. if (defaultValue.mType->IsVar())
  19991. {
  19992. AssertErrorState();
  19993. }
  19994. else
  19995. {
  19996. BF_ASSERT(defaultValue.mValue.IsConst());
  19997. while ((int)mCurMethodInstance->mDefaultValues.size() < paramDefIdx)
  19998. mCurMethodInstance->mDefaultValues.Add(BfTypedValue());
  19999. CurrentAddToConstHolder(defaultValue.mValue);
  20000. mCurMethodInstance->mDefaultValues.Add(defaultValue);
  20001. }
  20002. }
  20003. }
  20004. if ((paramDef != NULL) && (paramDef->mParamKind == BfParamKind_Params))
  20005. {
  20006. bool addParams = true;
  20007. bool isValid = false;
  20008. auto resolvedParamTypeInst = resolvedParamType->ToTypeInstance();
  20009. if ((resolvedParamTypeInst != NULL) && (resolvedParamTypeInst->IsInstanceOf(mCompiler->mSpanTypeDef)))
  20010. {
  20011. // Span<T>
  20012. isValid = true;
  20013. }
  20014. else if (resolvedParamType->IsArray())
  20015. {
  20016. // Array is the 'normal' params type
  20017. isValid = true;
  20018. }
  20019. else if (resolvedParamType->IsSizedArray())
  20020. {
  20021. isValid = true;
  20022. }
  20023. else if ((resolvedParamType->IsDelegate()) || (resolvedParamType->IsFunction()))
  20024. {
  20025. hadDelegateParams = true;
  20026. // This means we copy the params from a delegate
  20027. BfMethodParam methodParam;
  20028. methodParam.mResolvedType = resolvedParamType;
  20029. methodParam.mParamDefIdx = paramDefIdx;
  20030. methodParam.mDelegateParamIdx = 0;
  20031. auto invokeMethodInstance = methodParam.GetDelegateParamInvoke();
  20032. for (int delegateParamIdx = 0; delegateParamIdx < invokeMethodInstance->GetParamCount(); delegateParamIdx++)
  20033. {
  20034. methodParam.mDelegateParamIdx = delegateParamIdx;
  20035. mCurMethodInstance->mParams.Add(methodParam);
  20036. auto paramType = invokeMethodInstance->GetParamType(delegateParamIdx);
  20037. if (!methodInstance->IsSpecializedGenericMethod())
  20038. AddDependency(paramType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ParamOrReturnValue);
  20039. }
  20040. isValid = true;
  20041. addParams = false;
  20042. }
  20043. else if (resolvedParamType->IsGenericParam())
  20044. {
  20045. auto genericParamInstance = GetGenericParamInstance((BfGenericParamType*)resolvedParamType);
  20046. if (genericParamInstance->mTypeConstraint != NULL)
  20047. {
  20048. auto typeInstConstraint = genericParamInstance->mTypeConstraint->ToTypeInstance();
  20049. if ((genericParamInstance->mTypeConstraint->IsArray()) || (genericParamInstance->mTypeConstraint->IsSizedArray()))
  20050. {
  20051. BfMethodParam methodParam;
  20052. methodParam.mResolvedType = resolvedParamType;
  20053. methodParam.mParamDefIdx = paramDefIdx;
  20054. mCurMethodInstance->mParams.Add(methodParam);
  20055. isValid = true;
  20056. }
  20057. else if ((genericParamInstance->mTypeConstraint->IsDelegate()) || (genericParamInstance->mTypeConstraint->IsFunction()) ||
  20058. ((genericParamInstance != NULL) && (typeInstConstraint != NULL) &&
  20059. ((typeInstConstraint->IsInstanceOf(mCompiler->mDelegateTypeDef)) || (typeInstConstraint->IsInstanceOf(mCompiler->mFunctionTypeDef)))))
  20060. {
  20061. mCurMethodInstance->mHadGenericDelegateParams = true;
  20062. isValid = true;
  20063. addParams = false;
  20064. }
  20065. }
  20066. }
  20067. else
  20068. {
  20069. auto paramTypeInst = resolvedParamType->ToTypeInstance();
  20070. if ((paramTypeInst != NULL) &&
  20071. ((paramTypeInst->IsInstanceOf(mCompiler->mDelegateTypeDef)) || (paramTypeInst->IsInstanceOf(mCompiler->mFunctionTypeDef))))
  20072. {
  20073. // If we have a 'params T' and 'T' gets specialized with actually 'Delegate' or 'Function' then just ignore it
  20074. isValid = true;
  20075. addParams = false;
  20076. }
  20077. }
  20078. if (!isValid)
  20079. {
  20080. Fail("Parameters with 'params' specifiers can only be used for array, span, delegate, or function types", paramDef->mParamDeclaration->mModToken);
  20081. // Failure case, make it an Object[]
  20082. resolvedParamType = CreateArrayType(mContext->mBfObjectType, 1);
  20083. }
  20084. if ((addParams) && (resolvedParamType != NULL))
  20085. {
  20086. BfMethodParam methodParam;
  20087. methodParam.mResolvedType = resolvedParamType;
  20088. methodParam.mParamDefIdx = paramDefIdx;
  20089. mCurMethodInstance->mParams.push_back(methodParam);
  20090. }
  20091. if (paramDefIdx < (int)methodDef->mParams.size() - 1)
  20092. {
  20093. Fail("Only the last parameter can specify 'params'", paramDef->mParamDeclaration->mModToken);
  20094. }
  20095. }
  20096. else
  20097. {
  20098. BfMethodParam methodParam;
  20099. methodParam.mResolvedType = resolvedParamType;
  20100. methodParam.mParamDefIdx = paramDefIdx;
  20101. mCurMethodInstance->mParams.Add(methodParam);
  20102. }
  20103. }
  20104. if (hadDelegateParams)
  20105. {
  20106. HashSet<String> usedNames;
  20107. Dictionary<int, int> usedParamDefIdx;
  20108. for (auto methodParam : methodDef->mParams)
  20109. {
  20110. usedNames.Add(methodParam->mName);
  20111. }
  20112. for (auto& methodParam : mCurMethodInstance->mParams)
  20113. {
  20114. if ((methodParam.mParamDefIdx != -1) && (methodParam.mDelegateParamIdx == 0))
  20115. {
  20116. int* refCount = NULL;
  20117. usedParamDefIdx.TryAdd(methodParam.mParamDefIdx, NULL, &refCount);
  20118. (*refCount)++;
  20119. }
  20120. }
  20121. for (auto& methodParam : mCurMethodInstance->mParams)
  20122. {
  20123. if (methodParam.mDelegateParamIdx != -1)
  20124. {
  20125. if (usedParamDefIdx[methodParam.mParamDefIdx] > 1)
  20126. methodParam.mDelegateParamNameCombine = true;
  20127. BfMethodInstance* invokeMethodInstance = methodParam.GetDelegateParamInvoke();
  20128. String paramName = invokeMethodInstance->GetParamName(methodParam.mDelegateParamIdx);
  20129. if (usedNames.Contains(paramName))
  20130. methodParam.mDelegateParamNameCombine = true;
  20131. }
  20132. }
  20133. }
  20134. int argIdx = 0;
  20135. PopulateType(methodInstance->mReturnType, BfPopulateType_Data);
  20136. if ((!methodDef->mIsStatic) && (!methodDef->mHasExplicitThis))
  20137. {
  20138. int thisIdx = methodDef->mHasExplicitThis ? 0 : -1;
  20139. auto thisType = methodInstance->GetOwner();
  20140. if (methodInstance->GetParamIsSplat(thisIdx))
  20141. argIdx += methodInstance->GetParamType(thisIdx)->GetSplatCount();
  20142. else if (!thisType->IsValuelessType())
  20143. {
  20144. BfTypeCode loweredTypeCode = BfTypeCode_None;
  20145. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  20146. if ((!mIsComptimeModule) && (!methodDef->mIsMutating))
  20147. thisType->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2);
  20148. argIdx++;
  20149. if (loweredTypeCode2 != BfTypeCode_None)
  20150. argIdx++;
  20151. }
  20152. }
  20153. if ((!mIsComptimeModule) && (methodInstance->GetStructRetIdx() != -1))
  20154. argIdx++;
  20155. for (int paramIdx = 0; paramIdx < mCurMethodInstance->mParams.size(); paramIdx++)
  20156. {
  20157. auto& methodParam = mCurMethodInstance->mParams[paramIdx];
  20158. BfType* checkType = methodParam.mResolvedType;
  20159. int checkArgIdx = argIdx;
  20160. if ((paramIdx == 0) && (methodDef->mHasExplicitThis))
  20161. {
  20162. checkArgIdx = 0;
  20163. checkType = methodInstance->GetThisType();
  20164. }
  20165. if (checkType->IsMethodRef())
  20166. {
  20167. methodParam.mIsSplat = true;
  20168. }
  20169. else if ((checkType->IsComposite()) && (methodInstance->AllowsSplatting(paramIdx)))
  20170. {
  20171. PopulateType(checkType, BfPopulateType_Data);
  20172. if (checkType->IsSplattable())
  20173. {
  20174. bool isSplat = false;
  20175. auto checkTypeInstance = checkType->ToTypeInstance();
  20176. if ((checkTypeInstance != NULL) && (checkTypeInstance->mIsCRepr))
  20177. isSplat = true;
  20178. int splatCount = checkType->GetSplatCount();
  20179. if (checkArgIdx + splatCount <= mCompiler->mOptions.mMaxSplatRegs)
  20180. isSplat = true;
  20181. if (isSplat)
  20182. {
  20183. methodParam.mIsSplat = true;
  20184. argIdx += splatCount;
  20185. continue;
  20186. }
  20187. }
  20188. else if (!checkType->IsValuelessType())
  20189. {
  20190. BfTypeCode loweredTypeCode = BfTypeCode_None;
  20191. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  20192. if (!mIsComptimeModule)
  20193. checkType->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2);
  20194. argIdx++;
  20195. if (loweredTypeCode2 != BfTypeCode_None)
  20196. argIdx++;
  20197. continue;
  20198. }
  20199. }
  20200. argIdx++;
  20201. }
  20202. bool hasExternSpecifier = (methodDeclaration != NULL) && (methodDeclaration->mExternSpecifier != NULL);
  20203. if ((hasExternSpecifier) && (methodDeclaration->mBody != NULL))
  20204. {
  20205. Fail("Cannot 'extern' and declare a body", methodDeclaration->mExternSpecifier);
  20206. }
  20207. else if ((methodDeclaration != NULL) && (methodDeclaration->mBody == NULL) && (!hasExternSpecifier) &&
  20208. (!typeInstance->IsInterface()) && (!mCurTypeInstance->IsDelegate()) && (!mCurTypeInstance->IsFunction()) &&
  20209. (!methodDef->mIsPartial) && (!methodDef->mIsAbstract) &&
  20210. (!methodDef->mIsSkipCall))
  20211. {
  20212. if (methodDeclaration->mEndSemicolon == NULL)
  20213. {
  20214. if (auto autoCtorDecl = BfNodeDynCast<BfAutoConstructorDeclaration>(methodDeclaration))
  20215. {
  20216. //
  20217. }
  20218. else
  20219. AssertParseErrorState();
  20220. }
  20221. else
  20222. {
  20223. bool isError = true;
  20224. if (typeInstance->IsTypedPrimitive())
  20225. {
  20226. if (auto operatorDeclaration = BfNodeDynCast<BfOperatorDeclaration>(methodDeclaration))
  20227. {
  20228. if ((operatorDeclaration->mIsConvOperator) && (methodInstance->mParams.size() == 1))
  20229. {
  20230. if (((methodInstance->mReturnType == typeInstance) && (methodInstance->GetParamType(0) == typeInstance->GetUnderlyingType())) ||
  20231. ((methodInstance->mReturnType == typeInstance->GetUnderlyingType()) && (methodInstance->GetParamType(0) == typeInstance)))
  20232. {
  20233. isError = false;
  20234. }
  20235. }
  20236. }
  20237. }
  20238. if (isError)
  20239. {
  20240. Fail(StrFormat("'%s' must declare a body because it is not marked abstract, extern, or partial",
  20241. MethodToString(methodInstance).c_str()),
  20242. methodDef->GetRefNode());
  20243. }
  20244. }
  20245. }
  20246. if (methodDef->IsEmptyPartial())
  20247. hasExternSpecifier = true;
  20248. if (!methodInstance->IsAutocompleteMethod())
  20249. {
  20250. auto defaultMethodInstance = methodInstance->mMethodInstanceGroup->mDefault;
  20251. int implicitParamCount = methodInstance->GetImplicitParamCount();
  20252. int defaultImplicitParamCount = defaultMethodInstance->GetImplicitParamCount();
  20253. int actualParamCount = (int)methodInstance->mParams.size() - implicitParamCount;
  20254. BF_ASSERT((actualParamCount == defaultMethodInstance->mParams.size() - defaultImplicitParamCount) || (defaultMethodInstance->mHadGenericDelegateParams));
  20255. mCurMethodInstance->mHadGenericDelegateParams = defaultMethodInstance->mHadGenericDelegateParams;
  20256. int paramIdx = 0;
  20257. int defaultParamIdx = 0;
  20258. while (true)
  20259. {
  20260. bool isDone = paramIdx + implicitParamCount >= (int)methodInstance->mParams.size();
  20261. bool isDefaultDone = defaultParamIdx + defaultImplicitParamCount >= (int)defaultMethodInstance->mParams.size();
  20262. if ((!isDone) && (methodInstance->mParams[paramIdx + implicitParamCount].mDelegateParamIdx >= 0))
  20263. {
  20264. paramIdx++;
  20265. continue;
  20266. }
  20267. if ((!isDefaultDone) && (defaultMethodInstance->mParams[defaultParamIdx + defaultImplicitParamCount].mDelegateParamIdx >= 0))
  20268. {
  20269. defaultParamIdx++;
  20270. continue;
  20271. }
  20272. if ((isDone) || (isDefaultDone))
  20273. {
  20274. // 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
  20275. // to cause us to throw an assertion in the declaration here
  20276. if (!defaultMethodInstance->mHadGenericDelegateParams)
  20277. BF_ASSERT((isDone) && (isDefaultDone));
  20278. break;
  20279. }
  20280. BfType* paramType = defaultMethodInstance->mParams[defaultParamIdx + defaultImplicitParamCount].mResolvedType;
  20281. if (paramType->IsRef())
  20282. paramType = paramType->GetUnderlyingType();
  20283. methodInstance->mParams[paramIdx + implicitParamCount].mWasGenericParam = paramType->IsGenericParam();
  20284. paramIdx++;
  20285. defaultParamIdx++;
  20286. }
  20287. }
  20288. StringT<128> mangledName;
  20289. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), mCurMethodInstance);
  20290. for (int paramIdx = 0; paramIdx < methodInstance->GetParamCount(); paramIdx++)
  20291. {
  20292. auto paramType = methodInstance->GetParamType(paramIdx);
  20293. if (paramType->IsComposite())
  20294. PopulateType(paramType, BfPopulateType_Data);
  20295. if (!methodInstance->IsParamSkipped(paramIdx))
  20296. {
  20297. if (paramType->IsStruct())
  20298. {
  20299. //
  20300. }
  20301. else
  20302. {
  20303. PopulateType(paramType, BfPopulateType_Declaration);
  20304. }
  20305. }
  20306. }
  20307. // Only process method in default unspecialized mode, not in variations
  20308. if (methodInstance->mIsUnspecializedVariation)
  20309. return;
  20310. PopulateType(resolvedReturnType, BfPopulateType_Data);
  20311. auto retLLVMType = mBfIRBuilder->MapType(resolvedReturnType);
  20312. if (resolvedReturnType->IsValuelessType())
  20313. retLLVMType = mBfIRBuilder->GetPrimitiveType(BfTypeCode_None);
  20314. if (!mBfIRBuilder->mIgnoreWrites)
  20315. {
  20316. bool isIntrinsic = false;
  20317. if (!methodInstance->mIRFunction)
  20318. SetupIRFunction(methodInstance, mangledName, isTemporaryFunc, &isIntrinsic);
  20319. if (isIntrinsic)
  20320. {
  20321. addToWorkList = false;
  20322. }
  20323. }
  20324. auto func = methodInstance->mIRFunction;
  20325. // if (methodInstance->mIsReified)
  20326. // CheckHotMethod(methodInstance, mangledName);
  20327. 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);
  20328. SizedArray<BfIRMDNode, 8> diParams;
  20329. diParams.push_back(mBfIRBuilder->DbgGetType(resolvedReturnType));
  20330. if ((!methodDef->mIsStatic) && (typeDef->mIsStatic) && (methodDef->mMethodDeclaration != NULL))
  20331. {
  20332. //CS0708
  20333. Fail("Cannot declare instance members in a static class", methodDef->GetRefNode());
  20334. }
  20335. if ((methodDef->mIsVirtual) && (methodDef->mGenericParams.size() != 0))
  20336. {
  20337. Fail("Virtual generic methods not supported", methodDeclaration->mVirtualSpecifier);
  20338. methodDef->mIsVirtual = false;
  20339. }
  20340. BfAstNode* mutSpecifier = NULL;
  20341. if (methodDeclaration != NULL)
  20342. mutSpecifier = methodDeclaration->mMutSpecifier;
  20343. else if (methodDef->GetPropertyMethodDeclaration() != NULL)
  20344. {
  20345. mutSpecifier = methodDef->GetPropertyMethodDeclaration()->mMutSpecifier;
  20346. if (mutSpecifier == NULL)
  20347. {
  20348. auto propertyDeclaration = methodDef->GetPropertyDeclaration();
  20349. if (propertyDeclaration != NULL)
  20350. {
  20351. if (auto propExprBody = BfNodeDynCast<BfPropertyBodyExpression>(propertyDeclaration->mDefinitionBlock))
  20352. mutSpecifier = propExprBody->mMutSpecifier;
  20353. }
  20354. }
  20355. }
  20356. if ((mutSpecifier != NULL) && (!mCurTypeInstance->IsBoxed()) && (!methodInstance->mIsForeignMethodDef))
  20357. {
  20358. if (methodDef->mIsStatic)
  20359. Warn(0, "Unnecessary 'mut' specifier, static methods have no implicit 'this' target to mutate", mutSpecifier);
  20360. else if ((!mCurTypeInstance->IsValueType()) && (!mCurTypeInstance->IsInterface()))
  20361. Warn(0, "Unnecessary 'mut' specifier, methods of reference types are implicitly mutating", mutSpecifier);
  20362. else if (methodDef->mMethodType == BfMethodType_Ctor)
  20363. Warn(0, "Unnecessary 'mut' specifier, constructors are implicitly mutating", mutSpecifier);
  20364. else if (methodDef->mMethodType == BfMethodType_Dtor)
  20365. Warn(0, "Unnecessary 'mut' specifier, destructors are implicitly mutating", mutSpecifier);
  20366. }
  20367. if (isTemporaryFunc)
  20368. {
  20369. // This handles temporary methods for autocomplete types
  20370. //BF_ASSERT(mIsScratchModule);
  20371. //BF_ASSERT(mCompiler->IsAutocomplete());
  20372. BfLogSysM("DoMethodDeclaration isTemporaryFunc bailout\n");
  20373. return; // Bail out early for autocomplete pass
  20374. }
  20375. //TODO: We used to have this (this != mContext->mExternalFuncModule) check, but it caused us to keep around
  20376. // an invalid mFuncRefernce (which came from GetMethodInstanceAtIdx) which later got remapped by the
  20377. // autocompleter. Why did we have this check anyway?
  20378. /*if ((typeInstance->mContext != mContext) && (!methodDef->IsEmptyPartial()))
  20379. {
  20380. AddMethodReference(methodInstance);
  20381. mFuncReferences[methodInstance] = func;
  20382. BfLogSysM("Adding func reference (DoMethodDeclaration). Module:%p MethodInst:%p LLVMFunc:%p\n", this, methodInstance, func);
  20383. }*/
  20384. if (mParentModule != NULL)
  20385. {
  20386. // For extension modules we need to keep track of our own methods so we can know which methods
  20387. // we have defined ourselves and which are from the parent module or other extensions
  20388. if (!func.IsFake())
  20389. {
  20390. if (func)
  20391. mFuncReferences[methodInstance] = func;
  20392. }
  20393. }
  20394. if (methodInstance->mMethodInstanceGroup->mOnDemandKind == BfMethodOnDemandKind_NotSet)
  20395. {
  20396. methodInstance->mMethodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_Decl_AwaitingDecl;
  20397. auto owningModule = methodInstance->GetOwner()->mModule;
  20398. if (!owningModule->mIsScratchModule)
  20399. owningModule->mOnDemandMethodCount++;
  20400. VerifyOnDemandMethods();
  20401. }
  20402. bool wasAwaitingDecl = methodInstance->mMethodInstanceGroup->mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingDecl;
  20403. if (wasAwaitingDecl)
  20404. methodInstance->mMethodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_Decl_AwaitingReference;
  20405. if (addToWorkList)
  20406. {
  20407. if ((!methodDef->mIsAbstract) && (!methodInstance->mIgnoreBody))
  20408. {
  20409. AddMethodToWorkList(methodInstance);
  20410. }
  20411. else
  20412. {
  20413. BfLogSysM("DoMethodDeclaration ignoring method body %d %d %d\n", hasExternSpecifier, methodDef->mIsAbstract, methodInstance->mIgnoreBody);
  20414. methodInstance->mIgnoreBody = true;
  20415. if (typeInstance->IsUnspecializedType())
  20416. {
  20417. // Don't hold on to actual Function for unspecialized types
  20418. methodInstance->mIRFunction = BfIRFunction();
  20419. }
  20420. }
  20421. }
  20422. else
  20423. {
  20424. //BF_ASSERT(methodInstance->mMethodInstanceGroup->mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingReference);
  20425. }
  20426. if ((!methodInstance->IsSpecializedGenericMethodOrType()) && (!mCurTypeInstance->IsBoxed()) &&
  20427. (!methodDef->mIsLocalMethod) &&
  20428. (!CheckDefineMemberProtection(methodDef->mProtection, methodInstance->mReturnType)) &&
  20429. (!methodDef->mReturnTypeRef->IsTemporary()))
  20430. {
  20431. if (methodDef->mMethodType == BfMethodType_PropertyGetter)
  20432. {
  20433. //TODO:
  20434. //CS0053
  20435. Fail(StrFormat("Inconsistent accessibility: property type '%s' is less accessible than property '%s'",
  20436. TypeToString(methodInstance->mReturnType).c_str(), MethodToString(methodInstance).c_str()),
  20437. methodDef->mReturnTypeRef, true);
  20438. }
  20439. else
  20440. {
  20441. //CS0050
  20442. Fail(StrFormat("Inconsistent accessibility: return type '%s' is less accessible than method '%s'",
  20443. TypeToString(methodInstance->mReturnType).c_str(), MethodToString(methodInstance).c_str()),
  20444. methodDef->mReturnTypeRef, true);
  20445. }
  20446. }
  20447. if (typeInstance->IsInterface())
  20448. {
  20449. if (methodDef->mMethodType == BfMethodType_Ctor)
  20450. Fail("Interfaces cannot contain constructors", methodDeclaration);
  20451. if (methodDeclaration != NULL)
  20452. {
  20453. if (methodDef->mBody == NULL)
  20454. {
  20455. if (methodDef->mProtection != BfProtection_Public) //TODO: MAKE AN ERROR
  20456. Warn(0, "Protection specifiers can only be used with interface methods containing a default implementation body", methodDeclaration->mProtectionSpecifier);
  20457. if ((methodDeclaration->mVirtualSpecifier != NULL) &&
  20458. (methodDeclaration->mVirtualSpecifier->mToken != BfToken_Abstract) &&
  20459. (methodDeclaration->mVirtualSpecifier->mToken != BfToken_Concrete)) //TODO: MAKE AN ERROR
  20460. Warn(0, "Virtual specifiers can only be used with interface methods containing a default implementation body", methodDeclaration->mVirtualSpecifier);
  20461. }
  20462. }
  20463. }
  20464. bool foundHiddenMethod = false;
  20465. BfTokenNode* virtualToken = NULL;
  20466. auto propertyDeclaration = methodDef->GetPropertyDeclaration();
  20467. if (propertyDeclaration != NULL)
  20468. virtualToken = propertyDeclaration->mVirtualSpecifier;
  20469. else if (methodDeclaration != NULL)
  20470. virtualToken = methodDeclaration->mVirtualSpecifier;
  20471. // Don't compare specialized generic methods against normal methods
  20472. if ((((mCurMethodInstance->mIsUnspecialized) || (mCurMethodInstance->mMethodDef->mGenericParams.size() == 0))) &&
  20473. (!methodDef->mIsLocalMethod) && (!mCurTypeInstance->IsUnspecializedTypeVariation()))
  20474. {
  20475. if ((!methodInstance->mIsForeignMethodDef) && (methodDef->mMethodType != BfMethodType_Init))
  20476. {
  20477. typeDef->PopulateMemberSets();
  20478. BfMethodDef* nextMethod = NULL;
  20479. BfMemberSetEntry* entry = NULL;
  20480. if (typeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  20481. nextMethod = (BfMethodDef*)entry->mMemberDef;
  20482. while (nextMethod != NULL)
  20483. {
  20484. auto checkMethod = nextMethod;
  20485. nextMethod = nextMethod->mNextWithSameName;
  20486. if (checkMethod == methodDef)
  20487. continue;
  20488. auto checkMethodInstance = typeInstance->mMethodInstanceGroups[checkMethod->mIdx].mDefault;
  20489. if (checkMethodInstance == NULL)
  20490. {
  20491. if ((methodDef->mIsNew) && (methodDef->mDeclaringType->IsExtension()) && (!checkMethod->mDeclaringType->IsExtension()))
  20492. checkMethodInstance = GetRawMethodInstanceAtIdx(typeInstance, checkMethod->mIdx);
  20493. if (checkMethodInstance == NULL)
  20494. continue;
  20495. }
  20496. if (((checkMethodInstance->mChainType == BfMethodChainType_None) || (checkMethodInstance->mChainType == BfMethodChainType_ChainHead)) &&
  20497. (checkMethodInstance->GetExplicitInterface() == methodInstance->GetExplicitInterface()) &&
  20498. (checkMethod->mIsMutating == methodDef->mIsMutating) &&
  20499. (CompareMethodSignatures(checkMethodInstance, mCurMethodInstance)))
  20500. {
  20501. bool canChain = false;
  20502. if ((methodDef->mParams.empty()) &&
  20503. (checkMethodInstance->mMethodDef->mIsStatic == methodInstance->mMethodDef->mIsStatic))
  20504. {
  20505. if ((methodDef->mMethodType == BfMethodType_CtorNoBody) || (methodDef->mMethodType == BfMethodType_Dtor))
  20506. canChain = true;
  20507. else if (methodDef->mMethodType == BfMethodType_Normal)
  20508. {
  20509. if ((methodDef->mName == BF_METHODNAME_MARKMEMBERS) ||
  20510. (methodDef->mName == BF_METHODNAME_MARKMEMBERS_STATIC) ||
  20511. (methodDef->mName == BF_METHODNAME_FIND_TLS_MEMBERS))
  20512. canChain = true;
  20513. }
  20514. }
  20515. if (canChain)
  20516. {
  20517. bool isBetter;
  20518. bool isWorse;
  20519. CompareDeclTypes(checkMethodInstance->mMethodDef->mDeclaringType, methodInstance->mMethodDef->mDeclaringType, isBetter, isWorse);
  20520. if (isBetter && !isWorse)
  20521. {
  20522. methodInstance->mChainType = BfMethodChainType_ChainHead;
  20523. checkMethodInstance->mChainType = BfMethodChainType_ChainMember;
  20524. }
  20525. else
  20526. {
  20527. checkMethodInstance->mChainType = BfMethodChainType_ChainHead;
  20528. methodInstance->mChainType = BfMethodChainType_ChainMember;
  20529. }
  20530. }
  20531. else
  20532. {
  20533. if (!typeInstance->IsTypeMemberAccessible(checkMethod->mDeclaringType, methodDef->mDeclaringType))
  20534. continue;
  20535. bool silentlyAllow = false;
  20536. bool extensionWarn = false;
  20537. if (checkMethod->mDeclaringType != methodDef->mDeclaringType)
  20538. {
  20539. if (typeInstance->IsInterface())
  20540. {
  20541. if (methodDef->mIsOverride)
  20542. silentlyAllow = true;
  20543. }
  20544. else
  20545. {
  20546. if ((methodDef->mIsOverride) && (checkMethod->mIsExtern))
  20547. {
  20548. silentlyAllow = true;
  20549. methodInstance->mIsInnerOverride = true;
  20550. CheckOverridenMethod(methodInstance, checkMethodInstance);
  20551. }
  20552. else if ((methodDef->mDeclaringType->mProject != checkMethod->mDeclaringType->mProject) &&
  20553. (!checkMethod->mDeclaringType->IsExtension()))
  20554. {
  20555. foundHiddenMethod = true;
  20556. if ((methodDef->mMethodType == BfMethodType_Ctor) && (methodDef->mIsStatic))
  20557. silentlyAllow = true;
  20558. else if (methodDef->mIsNew)
  20559. {
  20560. silentlyAllow = true;
  20561. }
  20562. else
  20563. extensionWarn = true;
  20564. }
  20565. else
  20566. silentlyAllow = true;
  20567. }
  20568. }
  20569. if ((checkMethod->mCommutableKind == BfCommutableKind_Reverse) || (methodDef->mCommutableKind == BfCommutableKind_Reverse))
  20570. silentlyAllow = true;
  20571. if (!silentlyAllow)
  20572. {
  20573. if ((!methodDef->mName.IsEmpty()) || (checkMethodInstance->mMethodDef->mIsOperator))
  20574. {
  20575. auto refNode = methodDef->GetRefNode();
  20576. BfError* bfError;
  20577. if (extensionWarn)
  20578. bfError = Warn(BfWarning_CS0114_MethodHidesInherited,
  20579. 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'.",
  20580. checkMethod->mDeclaringType->mProject->mName.c_str()), refNode);
  20581. else
  20582. {
  20583. bfError = Fail(StrFormat("Method '%s' already declared with the same parameter types", MethodToString(checkMethodInstance).c_str()), refNode, true);
  20584. }
  20585. if ((bfError != NULL) && (checkMethod->GetRefNode() != refNode))
  20586. mCompiler->mPassInstance->MoreInfo("First declaration", checkMethod->GetRefNode());
  20587. }
  20588. }
  20589. }
  20590. }
  20591. }
  20592. }
  20593. // Virtual methods give their error while slotting
  20594. if ((!typeInstance->IsBoxed()) && (!methodDef->mIsVirtual) && (methodDef->mProtection != BfProtection_Private) &&
  20595. (!methodDef->mIsLocalMethod) &&
  20596. (!methodInstance->mIsForeignMethodDef) && (typeInstance->mBaseType != NULL) &&
  20597. (methodDef->mMethodType == BfMethodType_Normal) && (methodDef->mMethodDeclaration != NULL))
  20598. {
  20599. auto baseType = typeInstance->mBaseType;
  20600. while (baseType != NULL)
  20601. {
  20602. auto baseTypeDef = baseType->mTypeDef;
  20603. baseTypeDef->PopulateMemberSets();
  20604. BfMethodDef* checkMethod = NULL;
  20605. BfMemberSetEntry* entry = NULL;
  20606. if (baseTypeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  20607. checkMethod = (BfMethodDef*)entry->mMemberDef;
  20608. while (checkMethod != NULL)
  20609. {
  20610. if (checkMethod->mMethodDeclaration == NULL)
  20611. {
  20612. checkMethod = checkMethod->mNextWithSameName;
  20613. continue;
  20614. }
  20615. if (baseType->mMethodInstanceGroups.size() == 0)
  20616. {
  20617. BF_ASSERT(baseType->IsIncomplete() && mCompiler->IsAutocomplete());
  20618. break;
  20619. }
  20620. if (checkMethod == methodDef)
  20621. {
  20622. checkMethod = checkMethod->mNextWithSameName;
  20623. continue;
  20624. }
  20625. if (checkMethod->mName != methodDef->mName)
  20626. {
  20627. checkMethod = checkMethod->mNextWithSameName;
  20628. continue;
  20629. }
  20630. auto checkMethodInstance = GetRawMethodInstanceAtIdx(baseType, checkMethod->mIdx);
  20631. if (checkMethodInstance != NULL)
  20632. {
  20633. if ((checkMethodInstance->GetExplicitInterface() == methodInstance->GetExplicitInterface()) &&
  20634. (checkMethod->mProtection != BfProtection_Private) &&
  20635. (CompareMethodSignatures(checkMethodInstance, mCurMethodInstance)))
  20636. {
  20637. if (!methodDef->mIsNew)
  20638. {
  20639. BfAstNode* refNode = methodInstance->mMethodDef->GetRefNode();
  20640. if (refNode != NULL)
  20641. {
  20642. 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?
  20643. if (bfError != NULL)
  20644. bfError->mIsPersistent = true;
  20645. }
  20646. }
  20647. foundHiddenMethod = true;
  20648. break;
  20649. }
  20650. }
  20651. checkMethod = checkMethod->mNextWithSameName;
  20652. }
  20653. if (foundHiddenMethod)
  20654. break;
  20655. baseType = baseType->mBaseType;
  20656. }
  20657. if ((methodDef->mIsNew) && (!foundHiddenMethod) && (!mCurTypeInstance->IsSpecializedType()))
  20658. {
  20659. auto propertyDeclaration = methodDef->GetPropertyDeclaration();
  20660. auto tokenNode = (propertyDeclaration != NULL) ? propertyDeclaration->mNewSpecifier :
  20661. methodDeclaration->mNewSpecifier;
  20662. Fail("Method does not hide an inherited member. The 'new' keyword is not required", tokenNode, true);
  20663. }
  20664. }
  20665. }
  20666. if ((methodDef->mIsConcrete) && (!methodInstance->mIsForeignMethodDef) && (!mCurTypeInstance->IsInterface()))
  20667. {
  20668. Fail("Only interfaces methods can be declared as 'concrete'", methodDeclaration->mVirtualSpecifier);
  20669. }
  20670. if ((methodDef->mIsVirtual) && (methodDef->mIsStatic) && (!methodInstance->mIsInnerOverride))
  20671. {
  20672. if ((virtualToken != NULL) && (virtualToken->mToken == BfToken_Override) && (methodDef->mDeclaringType->mTypeCode == BfTypeCode_Extension))
  20673. Fail("No suitable method found to override", virtualToken, true);
  20674. else
  20675. Fail("Static members cannot be marked as override, virtual, or abstract", virtualToken, true);
  20676. }
  20677. else if (methodDef->mIsVirtual)
  20678. {
  20679. if ((methodDef->mProtection == BfProtection_Private) && (virtualToken != NULL))
  20680. Fail("Virtual or abstract members cannot be 'private'", virtualToken, true);
  20681. if ((methodDef->mProtection == BfProtection_Internal) && (virtualToken != NULL))
  20682. Fail("Virtual or abstract members cannot be 'internal'. Consider using the 'protected internal' access specifier.", virtualToken, true);
  20683. }
  20684. mCompiler->mStats.mMethodDeclarations++;
  20685. mCompiler->UpdateCompletion();
  20686. }
  20687. void BfModule::UniqueSlotVirtualMethod(BfMethodInstance* methodInstance)
  20688. {
  20689. BF_ASSERT(methodInstance->GetOwner() == mCurTypeInstance);
  20690. auto typeInstance = mCurTypeInstance;
  20691. auto methodDef = methodInstance->mMethodDef;
  20692. int virtualMethodMatchIdx = -1;
  20693. if (typeInstance->mHotTypeData != NULL)
  20694. {
  20695. if (typeInstance->mHotTypeData->mVTableOrigLength != -1)
  20696. {
  20697. BF_ASSERT(mCompiler->IsHotCompile());
  20698. // In the 'normal' case we'd assert that mIsOverride is false, but if we can't find the declaring method then we
  20699. // may slot this override anyway (?)
  20700. int vTableStart = 0;
  20701. auto implBaseType = typeInstance->GetImplBaseType();
  20702. if (implBaseType != NULL)
  20703. vTableStart = implBaseType->mVirtualMethodTableSize;
  20704. StringT<128> mangledName;
  20705. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), methodInstance);
  20706. for (int checkIdxOfs = 0; checkIdxOfs < (int)typeInstance->mHotTypeData->mVTableEntries.size(); checkIdxOfs++)
  20707. {
  20708. // O(1) checking when virtual methods haven't changed
  20709. int checkIdx = (typeInstance->mVirtualMethodTableSize - vTableStart + checkIdxOfs) % (int)typeInstance->mHotTypeData->mVTableEntries.size();
  20710. auto& entry = typeInstance->mHotTypeData->mVTableEntries[checkIdx];
  20711. if (mangledName == entry.mFuncName)
  20712. {
  20713. virtualMethodMatchIdx = vTableStart + checkIdx;
  20714. break;
  20715. }
  20716. }
  20717. if (virtualMethodMatchIdx != -1)
  20718. {
  20719. methodInstance->mVirtualTableIdx = virtualMethodMatchIdx;
  20720. typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mDeclaringMethod = methodInstance;
  20721. typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mImplementingMethod = methodInstance;
  20722. }
  20723. typeInstance->mVirtualMethodTableSize = (int)typeInstance->mVirtualMethodTable.size();
  20724. }
  20725. }
  20726. if (virtualMethodMatchIdx == -1)
  20727. {
  20728. methodInstance->mVirtualTableIdx = typeInstance->mVirtualMethodTableSize++;
  20729. BfVirtualMethodEntry entry = { methodInstance, methodInstance };
  20730. typeInstance->mVirtualMethodTable.push_back(entry);
  20731. }
  20732. }
  20733. void BfModule::CompareDeclTypes(BfTypeDef* newDeclType, BfTypeDef* prevDeclType, bool& isBetter, bool& isWorse)
  20734. {
  20735. if ((!prevDeclType->IsExtension()) && (newDeclType->IsExtension()))
  20736. {
  20737. // When we provide an extension override in the same project a root type override
  20738. isBetter = true;
  20739. isWorse = false;
  20740. }
  20741. else
  20742. {
  20743. isBetter = newDeclType->mProject->ContainsReference(prevDeclType->mProject);
  20744. isWorse = prevDeclType->mProject->ContainsReference(newDeclType->mProject);
  20745. }
  20746. }
  20747. bool BfModule::SlotVirtualMethod(BfMethodInstance* methodInstance, BfAmbiguityContext* ambiguityContext)
  20748. {
  20749. BP_ZONE("BfModule::SlotVirtualMethod");
  20750. if (mCurTypeInstance->IsUnspecializedTypeVariation())
  20751. return false;
  20752. auto _AddVirtualDecl = [&](BfMethodInstance* declMethodInstance)
  20753. {
  20754. if (!mCompiler->mOptions.mAllowHotSwapping)
  20755. return;
  20756. if ((!methodInstance->mIsReified) || (!declMethodInstance->mIsReified))
  20757. return;
  20758. if (methodInstance->mHotMethod == NULL)
  20759. CheckHotMethod(methodInstance, "");
  20760. if (methodInstance->mHotMethod == NULL)
  20761. return;
  20762. //BF_ASSERT(declMethodInstance->mHotMethod != NULL);
  20763. if (declMethodInstance->mHotMethod == NULL)
  20764. CheckHotMethod(declMethodInstance, "");
  20765. auto virtualDecl = mCompiler->mHotData->GetVirtualDeclaration(declMethodInstance->mHotMethod);
  20766. virtualDecl->mRefCount++;
  20767. methodInstance->mHotMethod->mReferences.Add(virtualDecl);
  20768. };
  20769. auto typeInstance = mCurTypeInstance;
  20770. auto typeDef = typeInstance->mTypeDef;
  20771. auto methodDef = methodInstance->mMethodDef;
  20772. auto methodDeclaration = methodDef->GetMethodDeclaration();
  20773. auto propertyDeclaration = methodDef->GetPropertyDeclaration();
  20774. auto propertyMethodDeclaration = methodDef->GetPropertyMethodDeclaration();
  20775. if (methodInstance->mIsInnerOverride)
  20776. return false;
  20777. BfAstNode* declaringNode = methodDeclaration;
  20778. if (propertyMethodDeclaration != NULL)
  20779. declaringNode = propertyMethodDeclaration->mNameNode;
  20780. BfMethodInstance* methodOverriden = NULL;
  20781. bool usedMethod = false;
  20782. BfTokenNode* virtualToken = NULL;
  20783. if (propertyDeclaration != NULL)
  20784. virtualToken = propertyDeclaration->mVirtualSpecifier;
  20785. else if (methodDeclaration != NULL)
  20786. virtualToken = methodDeclaration->mVirtualSpecifier;
  20787. if ((methodDef->mIsVirtual) && (methodDef->mIsStatic))
  20788. {
  20789. //Fail: Static members cannot be marked as override, virtual, or abstract
  20790. }
  20791. else if (methodDef->mIsVirtual)
  20792. {
  20793. if (IsHotCompile())
  20794. mContext->EnsureHotMangledVirtualMethodName(methodInstance);
  20795. BfTypeInstance* checkBase = typeInstance;
  20796. // If we are in an extension, look in ourselves first
  20797. if (methodDef->mDeclaringType->mTypeDeclaration == typeInstance->mTypeDef->mTypeDeclaration)
  20798. checkBase = checkBase->mBaseType;
  20799. if (typeInstance->IsValueType())
  20800. {
  20801. if (typeInstance->mBaseType == NULL)
  20802. return false; // It's actually ValueType
  20803. // We allow structs to override object methods for when they get boxed, so just ignore 'override' keyword until it gets boxed
  20804. if (!methodDef->mIsOverride)
  20805. {
  20806. Fail("Structs cannot have virtual methods", virtualToken, true);
  20807. return false;
  20808. }
  20809. checkBase = mContext->mBfObjectType;
  20810. if (checkBase->mVirtualMethodTableSize == 0)
  20811. PopulateType(checkBase, BfPopulateType_Full);
  20812. if (checkBase->mDefineState < BfTypeDefineState_DefinedAndMethodsSlotted)
  20813. return false; // System circular ref, don't do struct checking on those
  20814. }
  20815. int virtualMethodMatchIdx = -1;
  20816. bool hadHidingError = false;
  20817. BfMethodInstance* bestOverrideMethodInstance = NULL;
  20818. BfMethodInstance* ambiguousOverrideMethodInstance = NULL;
  20819. int bestOverrideMethodIdx = -1;
  20820. int ambiguousOverrideMethodIdx = -1;
  20821. if (checkBase != NULL)
  20822. {
  20823. auto& baseVirtualMethodTable = checkBase->mVirtualMethodTable;
  20824. auto lookupType = checkBase;
  20825. while (lookupType != NULL)
  20826. {
  20827. lookupType->mTypeDef->PopulateMemberSets();
  20828. BfMethodDef* nextMethodDef = NULL;
  20829. BfMemberSetEntry* entry;
  20830. if (lookupType->mTypeDef->mMethodSet.TryGetWith((StringImpl&)methodInstance->mMethodDef->mName, &entry))
  20831. nextMethodDef = (BfMethodDef*)entry->mMemberDef;
  20832. while (nextMethodDef != NULL)
  20833. {
  20834. auto checkMethodDef = nextMethodDef;
  20835. nextMethodDef = nextMethodDef->mNextWithSameName;
  20836. if ((!checkMethodDef->mIsVirtual) || (checkMethodDef->mIsOverride))
  20837. continue;
  20838. BfMethodInstance* lookupMethodInstance = lookupType->mMethodInstanceGroups[checkMethodDef->mIdx].mDefault;
  20839. if ((lookupMethodInstance == NULL) || (lookupMethodInstance->mVirtualTableIdx == -1))
  20840. continue;
  20841. int checkMethodIdx = lookupMethodInstance->mVirtualTableIdx;
  20842. if (checkMethodIdx >= baseVirtualMethodTable.mSize)
  20843. FatalError("SlotVirtualMethod OOB in baseVirtualMethodTable[checkMethodIdx]");
  20844. auto& baseMethodRef = baseVirtualMethodTable[checkMethodIdx];
  20845. if (baseMethodRef.mDeclaringMethod.mMethodNum == -1)
  20846. {
  20847. BF_ASSERT(mCompiler->mOptions.mHasVDataExtender);
  20848. continue;
  20849. }
  20850. BfMethodInstance* baseMethodInstance = baseVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  20851. if (baseMethodInstance == NULL)
  20852. {
  20853. AssertErrorState();
  20854. continue;
  20855. }
  20856. if ((baseMethodInstance != NULL) && (CompareMethodSignatures(baseMethodInstance, methodInstance)))
  20857. {
  20858. if (methodDef->mIsOverride)
  20859. {
  20860. BfMethodInstance* checkMethodInstance;
  20861. if (typeInstance->IsValueType())
  20862. checkMethodInstance = checkBase->mVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  20863. else
  20864. checkMethodInstance = typeInstance->mVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  20865. auto newDeclType = checkMethodInstance->mMethodDef->mDeclaringType;
  20866. if (!typeInstance->IsTypeMemberAccessible(newDeclType, methodDef->mDeclaringType->mProject))
  20867. continue;
  20868. if (bestOverrideMethodInstance != NULL)
  20869. {
  20870. auto prevDeclType = bestOverrideMethodInstance->mMethodDef->mDeclaringType;
  20871. bool isBetter = newDeclType->mProject->ContainsReference(prevDeclType->mProject);
  20872. bool isWorse = prevDeclType->mProject->ContainsReference(newDeclType->mProject);
  20873. if (isBetter == isWorse)
  20874. {
  20875. ambiguousOverrideMethodInstance = bestOverrideMethodInstance;
  20876. }
  20877. else
  20878. {
  20879. if (isWorse)
  20880. continue;
  20881. ambiguousOverrideMethodInstance = NULL;
  20882. }
  20883. }
  20884. bestOverrideMethodInstance = checkMethodInstance;
  20885. bestOverrideMethodIdx = checkMethodIdx;
  20886. }
  20887. else
  20888. {
  20889. if ((baseMethodInstance->GetOwner() != methodInstance->GetOwner()) && (!methodDef->mIsNew))
  20890. {
  20891. if (!hadHidingError)
  20892. Warn(BfWarning_CS0114_MethodHidesInherited, StrFormat("Method hides inherited member from '%s'. Use either 'override' or 'new'.", TypeToString(checkBase).c_str()), declaringNode);
  20893. hadHidingError = true;
  20894. }
  20895. }
  20896. }
  20897. }
  20898. lookupType = lookupType->mBaseType;
  20899. }
  20900. }
  20901. //TODO:
  20902. if ((checkBase != NULL)
  20903. && (false)
  20904. )
  20905. {
  20906. auto& baseVirtualMethodTable = checkBase->mVirtualMethodTable;
  20907. for (int checkMethodIdx = (int) baseVirtualMethodTable.size() - 1; checkMethodIdx >= 0; checkMethodIdx--)
  20908. {
  20909. auto& baseMethodRef = baseVirtualMethodTable[checkMethodIdx];
  20910. if (baseMethodRef.mDeclaringMethod.mMethodNum == -1)
  20911. {
  20912. BF_ASSERT(mCompiler->mOptions.mHasVDataExtender);
  20913. continue;
  20914. }
  20915. BfMethodInstance* baseMethodInstance = baseVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  20916. if (baseMethodInstance == NULL)
  20917. {
  20918. AssertErrorState();
  20919. continue;
  20920. }
  20921. if ((baseMethodInstance != NULL) && (CompareMethodSignatures(baseMethodInstance, methodInstance)))
  20922. {
  20923. if (methodDef->mIsOverride)
  20924. {
  20925. BfMethodInstance* checkMethodInstance;
  20926. if (typeInstance->IsValueType())
  20927. checkMethodInstance = checkBase->mVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  20928. else
  20929. checkMethodInstance = typeInstance->mVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  20930. auto newDeclType = checkMethodInstance->mMethodDef->mDeclaringType;
  20931. if (!typeInstance->IsTypeMemberAccessible(newDeclType, methodDef->mDeclaringType->mProject))
  20932. continue;
  20933. if (bestOverrideMethodInstance != NULL)
  20934. {
  20935. auto prevDeclType = bestOverrideMethodInstance->mMethodDef->mDeclaringType;
  20936. bool isBetter = newDeclType->mProject->ContainsReference(prevDeclType->mProject);
  20937. bool isWorse = prevDeclType->mProject->ContainsReference(newDeclType->mProject);
  20938. if (isBetter == isWorse)
  20939. {
  20940. ambiguousOverrideMethodInstance = bestOverrideMethodInstance;
  20941. }
  20942. else
  20943. {
  20944. if (isWorse)
  20945. continue;
  20946. ambiguousOverrideMethodInstance = NULL;
  20947. }
  20948. }
  20949. bestOverrideMethodInstance = checkMethodInstance;
  20950. bestOverrideMethodIdx = checkMethodIdx;
  20951. }
  20952. else
  20953. {
  20954. if ((baseMethodInstance->GetOwner() != methodInstance->GetOwner()) && (!methodDef->mIsNew))
  20955. {
  20956. if (!hadHidingError)
  20957. Warn(BfWarning_CS0114_MethodHidesInherited, StrFormat("Method hides inherited member from '%s'. Use either 'override' or 'new'.", TypeToString(checkBase).c_str()), declaringNode);
  20958. hadHidingError = true;
  20959. }
  20960. }
  20961. }
  20962. }
  20963. }
  20964. if (bestOverrideMethodInstance != NULL)
  20965. {
  20966. if (ambiguousOverrideMethodInstance != NULL)
  20967. {
  20968. bool allow = false;
  20969. // 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.
  20970. // When when specialize, the specialized type will determine wither it has illegally pulled in both declarations or not
  20971. bool canSeeEachOther = false;
  20972. //
  20973. {
  20974. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, ambiguousOverrideMethodInstance);
  20975. if (bestOverrideMethodInstance->GetOwner()->IsTypeMemberIncluded(bestOverrideMethodInstance->mMethodDef->mDeclaringType, ambiguousOverrideMethodInstance->mMethodDef->mDeclaringType, this))
  20976. canSeeEachOther = true;
  20977. }
  20978. //
  20979. {
  20980. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, bestOverrideMethodInstance);
  20981. if (ambiguousOverrideMethodInstance->GetOwner()->IsTypeMemberIncluded(ambiguousOverrideMethodInstance->mMethodDef->mDeclaringType, bestOverrideMethodInstance->mMethodDef->mDeclaringType, this))
  20982. canSeeEachOther = true;
  20983. }
  20984. if (!canSeeEachOther)
  20985. {
  20986. BF_ASSERT(bestOverrideMethodInstance->GetOwner()->IsUnspecializedType() && ambiguousOverrideMethodInstance->GetOwner()->IsUnspecializedType());
  20987. }
  20988. else
  20989. {
  20990. auto error = Fail(StrFormat("Method '%s' is an ambiguous override", MethodToString(methodInstance).c_str()), methodDef->GetRefNode());
  20991. if (error != NULL)
  20992. {
  20993. mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' is a candidate", MethodToString(bestOverrideMethodInstance).c_str()), bestOverrideMethodInstance->mMethodDef->GetRefNode());
  20994. mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' is a candidate", MethodToString(ambiguousOverrideMethodInstance).c_str()), ambiguousOverrideMethodInstance->mMethodDef->GetRefNode());
  20995. }
  20996. }
  20997. }
  20998. auto& baseVirtualMethodTable = checkBase->mVirtualMethodTable;
  20999. BfMethodInstance* baseVirtualMethodInstance = baseVirtualMethodTable[bestOverrideMethodIdx].mDeclaringMethod;
  21000. if ((baseVirtualMethodInstance != methodInstance) && (methodDef->mIsOverride))
  21001. {
  21002. if (baseVirtualMethodInstance->mReturnType != methodInstance->mReturnType)
  21003. {
  21004. BfTypeReference* returnTypeRef;
  21005. if (auto propertyDeclaration = methodDef->GetPropertyDeclaration())
  21006. {
  21007. returnTypeRef = propertyDeclaration->mTypeRef;
  21008. Fail("Property differs from overridden property by type", returnTypeRef, true);
  21009. }
  21010. else if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  21011. {
  21012. returnTypeRef = methodDeclaration->mReturnType;
  21013. Fail("Method differs from overridden method by return value", returnTypeRef, true);
  21014. }
  21015. else
  21016. {
  21017. Fail(StrFormat("Internal error with method '%s'", MethodToString(methodInstance).c_str()));
  21018. }
  21019. return usedMethod;
  21020. }
  21021. }
  21022. if (methodDef->mIsOverride)
  21023. {
  21024. // We can have multiple matches when a virtual method is used to implement interface methods
  21025. // It doesn't matter what we set mVirtualTableIdx, as all base classes will override all matching
  21026. // vtable entries for this method signature
  21027. virtualMethodMatchIdx = bestOverrideMethodIdx;
  21028. if (!typeInstance->IsValueType())
  21029. methodInstance->mVirtualTableIdx = virtualMethodMatchIdx;
  21030. if (typeInstance->IsValueType())
  21031. {
  21032. methodOverriden = checkBase->mVirtualMethodTable[virtualMethodMatchIdx].mImplementingMethod;
  21033. }
  21034. else
  21035. {
  21036. methodInstance->mVirtualTableIdx = virtualMethodMatchIdx;
  21037. bool preferRootDefinition = (methodDef->mName == BF_METHODNAME_MARKMEMBERS) || (methodDef->mMethodType == BfMethodType_Dtor);
  21038. BfMethodInstance* setMethodInstance = methodInstance;
  21039. bool doOverride = false;
  21040. auto& overridenRef = typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mImplementingMethod;
  21041. if (overridenRef.mKind != BfMethodRefKind_AmbiguousRef)
  21042. {
  21043. methodOverriden = overridenRef;
  21044. doOverride = true;
  21045. if (methodOverriden->GetOwner() == methodInstance->GetOwner())
  21046. {
  21047. bool isBetter = false;
  21048. bool isWorse = false;
  21049. CompareDeclTypes(methodInstance->mMethodDef->mDeclaringType, methodOverriden->mMethodDef->mDeclaringType, isBetter, isWorse);
  21050. if (isBetter == isWorse)
  21051. {
  21052. // We have to resolve later per-project
  21053. if ((ambiguityContext != NULL) && (ambiguityContext->mIsProjectSpecific))
  21054. {
  21055. auto declMethodInstance = checkBase->mVirtualMethodTable[virtualMethodMatchIdx].mDeclaringMethod;
  21056. ambiguityContext->Add(virtualMethodMatchIdx, NULL, -1, methodOverriden, methodInstance);
  21057. }
  21058. if ((ambiguityContext == NULL) || (!ambiguityContext->mIsProjectSpecific))
  21059. typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mImplementingMethod.mKind = BfMethodRefKind_AmbiguousRef;
  21060. doOverride = false;
  21061. }
  21062. else
  21063. {
  21064. if ((isBetter) && (ambiguityContext != NULL))
  21065. {
  21066. ambiguityContext->Remove(virtualMethodMatchIdx);
  21067. }
  21068. if ((isBetter) && (methodInstance->GetOwner() == methodOverriden->GetOwner()))
  21069. {
  21070. if (preferRootDefinition)
  21071. {
  21072. // Leave the master GCMarkMember
  21073. isBetter = false;
  21074. isWorse = true;
  21075. }
  21076. }
  21077. doOverride = isBetter;
  21078. }
  21079. }
  21080. }
  21081. else if ((preferRootDefinition) && (!methodDef->mDeclaringType->IsExtension()))
  21082. {
  21083. methodOverriden = overridenRef;
  21084. doOverride = true;
  21085. }
  21086. if (doOverride)
  21087. {
  21088. auto declMethodInstance = (BfMethodInstance*)typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mDeclaringMethod;
  21089. _AddVirtualDecl(declMethodInstance);
  21090. setMethodInstance->mVirtualTableIdx = virtualMethodMatchIdx;
  21091. typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mImplementingMethod = setMethodInstance;
  21092. }
  21093. }
  21094. if (methodOverriden != NULL)
  21095. {
  21096. CheckOverridenMethod(methodInstance, methodOverriden);
  21097. }
  21098. }
  21099. }
  21100. if ((virtualMethodMatchIdx == -1) && ((ambiguityContext == NULL) || (!ambiguityContext->mIsReslotting)))
  21101. {
  21102. if (methodDef->mIsOverride)
  21103. {
  21104. BfTokenNode* overrideToken = NULL;
  21105. if (auto propertyMethodDeclaration = methodDef->GetPropertyMethodDeclaration())
  21106. overrideToken = propertyMethodDeclaration->mPropertyDeclaration->mVirtualSpecifier;
  21107. else if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  21108. overrideToken = methodDeclaration->mVirtualSpecifier;
  21109. if (overrideToken != NULL)
  21110. {
  21111. if ((propertyDeclaration != NULL) && (propertyDeclaration->mNameNode != NULL) &&
  21112. ((methodDef->mMethodType == BfMethodType_PropertyGetter) || (methodDef->mMethodType == BfMethodType_PropertySetter)))
  21113. Fail(StrFormat("No suitable method found to override for '%s.%s'",
  21114. propertyDeclaration->mNameNode->ToString().c_str(), (methodDef->mMethodType == BfMethodType_PropertyGetter) ? "get" : "set"), overrideToken, true);
  21115. else
  21116. Fail("No suitable method found to override", overrideToken, true);
  21117. }
  21118. return usedMethod;
  21119. }
  21120. UniqueSlotVirtualMethod(methodInstance);
  21121. }
  21122. else
  21123. usedMethod = true;
  21124. if (typeInstance->IsValueType())
  21125. return usedMethod;
  21126. }
  21127. bool foundInterface = false;
  21128. bool hadAnyMatch = false;
  21129. // See if this method matches interfaces
  21130. for (auto& ifaceTypeInst : typeInstance->mInterfaces)
  21131. {
  21132. auto ifaceInst = ifaceTypeInst.mInterfaceType;
  21133. if (ifaceInst->IsIncomplete())
  21134. PopulateType(ifaceInst, BfPopulateType_DataAndMethods);
  21135. int startIdx = ifaceTypeInst.mStartInterfaceTableIdx;
  21136. int iMethodCount = (int)ifaceInst->mMethodInstanceGroups.size();
  21137. // See "bidirectional" rules mentioned in DoTypeInstanceMethodProcessing
  21138. if ((!typeInstance->IsTypeMemberAccessible(methodDef->mDeclaringType, ifaceTypeInst.mDeclaringType)) &&
  21139. (!typeInstance->IsTypeMemberAccessible(ifaceTypeInst.mDeclaringType, methodDef->mDeclaringType)))
  21140. continue;
  21141. if (!typeInstance->IsTypeMemberIncluded(methodDef->mDeclaringType, ifaceTypeInst.mDeclaringType, this))
  21142. continue;
  21143. bool hadMatch = false;
  21144. BfMethodInstance* hadNameMatch = NULL;
  21145. BfType* expectedReturnType = NULL;
  21146. bool showedError = false;
  21147. // We go through our VTable looking for NULL entries within the interface sections
  21148. // The only instance of finding a "better" method is when we have explicitly interface-dotted method
  21149. // because a normal method declared in this type could have matched earlier
  21150. //for (int iMethodIdx = 0; iMethodIdx < iMethodCount; iMethodIdx++)
  21151. ifaceInst->mTypeDef->PopulateMemberSets();
  21152. BfMethodDef* checkMethodDef = NULL;
  21153. BfMemberSetEntry* entry;
  21154. if (ifaceInst->mTypeDef->mMethodSet.TryGetWith((StringImpl&)methodInstance->mMethodDef->mName, &entry))
  21155. checkMethodDef = (BfMethodDef*)entry->mMemberDef;
  21156. while (checkMethodDef != NULL)
  21157. {
  21158. int iMethodIdx = checkMethodDef->mIdx;
  21159. int iTableIdx = iMethodIdx + startIdx;
  21160. BfTypeInterfaceMethodEntry* interfaceMethodEntry = &typeInstance->mInterfaceMethodTable[iTableIdx];
  21161. auto iMethodPtr = &interfaceMethodEntry->mMethodRef;
  21162. bool storeIFaceMethod = false;
  21163. if ((mCompiler->mPassInstance->HasFailed()) && (iMethodIdx >= (int)ifaceInst->mMethodInstanceGroups.size()))
  21164. {
  21165. checkMethodDef = checkMethodDef->mNextWithSameName;
  21166. continue;
  21167. }
  21168. auto& iMethodGroup = ifaceInst->mMethodInstanceGroups[iMethodIdx];
  21169. auto iMethodInst = iMethodGroup.mDefault;
  21170. if (iMethodInst == NULL)
  21171. {
  21172. if ((!ifaceInst->IsGenericTypeInstance()) || (!ifaceInst->mTypeDef->mIsCombinedPartial))
  21173. AssertErrorState();
  21174. checkMethodDef = checkMethodDef->mNextWithSameName;
  21175. continue;
  21176. }
  21177. if (iMethodInst->mMethodDef->mName == methodInstance->mMethodDef->mName)
  21178. hadNameMatch = iMethodInst;
  21179. bool doesMethodSignatureMatch = CompareMethodSignatures(iMethodInst, methodInstance);
  21180. if ((!doesMethodSignatureMatch) && (iMethodInst->GetNumGenericParams() == 0) && (interfaceMethodEntry->mMethodRef.IsNull()))
  21181. {
  21182. doesMethodSignatureMatch = IsCompatibleInterfaceMethod(iMethodInst, methodInstance);
  21183. }
  21184. if ((doesMethodSignatureMatch) && (methodInstance->GetOwner()->IsValueType()))
  21185. {
  21186. if ((!iMethodInst->mMethodDef->mIsMutating) && (methodInstance->mMethodDef->mIsMutating))
  21187. {
  21188. if ((methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface == ifaceInst))
  21189. {
  21190. auto error = mCompiler->mPassInstance->Fail(StrFormat("Implementation method '%s' cannot specify 'mut' because the interface method does not allow it",
  21191. MethodToString(methodInstance).c_str()), methodInstance->mMethodDef->GetMutNode());
  21192. if (error != NULL)
  21193. mCompiler->mPassInstance->MoreInfo(StrFormat("Declare the interface method as 'mut' to allow matching 'mut' implementations"), iMethodInst->mMethodDef->mMethodDeclaration);
  21194. showedError = true;
  21195. }
  21196. }
  21197. }
  21198. if (doesMethodSignatureMatch)
  21199. {
  21200. usedMethod = true;
  21201. hadMatch = true;
  21202. hadAnyMatch = true;
  21203. storeIFaceMethod = true;
  21204. if ((iMethodPtr->mKind != BfMethodRefKind_AmbiguousRef) && (iMethodPtr->mTypeInstance != NULL))
  21205. {
  21206. auto prevMethod = (BfMethodInstance*)*iMethodPtr;
  21207. if ((mCompiler->mIsResolveOnly) && (prevMethod == methodInstance) && (!mIsComptimeModule))
  21208. {
  21209. // When autocompletion regenerates a single method body but not the whole type then
  21210. // we will see ourselves in the vtable already
  21211. return usedMethod;
  21212. }
  21213. bool isBetter = false;
  21214. bool isWorse = false;
  21215. isBetter = (methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface != NULL);
  21216. isWorse = (prevMethod->mMethodInfoEx != NULL) && (prevMethod->mMethodInfoEx->mExplicitInterface != NULL);
  21217. if (isBetter == isWorse)
  21218. CompareDeclTypes(methodInstance->mMethodDef->mDeclaringType, prevMethod->mMethodDef->mDeclaringType, isBetter, isWorse);
  21219. if (isBetter == isWorse)
  21220. {
  21221. if (ambiguityContext != NULL)
  21222. {
  21223. ambiguityContext->Add(~iTableIdx, &ifaceTypeInst, iMethodIdx, prevMethod, methodInstance);
  21224. }
  21225. iMethodPtr->mKind = BfMethodRefKind_AmbiguousRef;
  21226. storeIFaceMethod = true;
  21227. }
  21228. else
  21229. {
  21230. if ((isBetter) && (ambiguityContext != NULL))
  21231. ambiguityContext->Remove(~iTableIdx);
  21232. storeIFaceMethod = isBetter;
  21233. }
  21234. }
  21235. }
  21236. if (storeIFaceMethod)
  21237. {
  21238. if (methodInstance->GetNumGenericParams() != 0)
  21239. _AddVirtualDecl(iMethodInst);
  21240. *iMethodPtr = methodInstance;
  21241. }
  21242. checkMethodDef = checkMethodDef->mNextWithSameName;
  21243. }
  21244. if ((methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface == ifaceInst) && (!hadMatch) && (!showedError))
  21245. {
  21246. if (expectedReturnType != NULL)
  21247. Fail(StrFormat("Wrong return type, expected '%s'", TypeToString(expectedReturnType).c_str()), declaringNode, true);
  21248. else if (hadNameMatch != NULL)
  21249. {
  21250. auto error = Fail("Method parameters don't match interface method", declaringNode, true);
  21251. if (error != NULL)
  21252. mCompiler->mPassInstance->MoreInfo("See interface method declaration", hadNameMatch->mMethodDef->GetRefNode());
  21253. }
  21254. else
  21255. {
  21256. auto propertyDecl = methodDef->GetPropertyDeclaration();
  21257. if (propertyDecl != NULL)
  21258. {
  21259. auto propertyMethodDecl = methodDef->GetPropertyMethodDeclaration();
  21260. String name;
  21261. if (auto indexerDeclaration = BfNodeDynCast<BfIndexerDeclaration>(propertyDecl))
  21262. name = "this[]";
  21263. else if (propertyDecl->mNameNode != NULL)
  21264. propertyDecl->mNameNode->ToString(name);
  21265. Fail(StrFormat("Property '%s' %s accessor not defined in interface '%s'", name.c_str(),
  21266. (methodDef->mMethodType == BfMethodType_PropertyGetter) ? "get" : "set", TypeToString(ifaceInst).c_str()), methodDef->GetRefNode(), true);
  21267. }
  21268. else
  21269. Fail(StrFormat("Method '%s' not found in interface '%s'", methodDef->mName.c_str(), TypeToString(ifaceInst).c_str()), methodDef->GetRefNode(), true);
  21270. }
  21271. }
  21272. }
  21273. // Any overriden virtual methods that were used in interfaces also need to be replaced
  21274. if (methodOverriden != NULL)
  21275. {
  21276. for (auto& methodEntry : typeInstance->mInterfaceMethodTable)
  21277. {
  21278. if (methodEntry.mMethodRef == methodOverriden)
  21279. methodEntry.mMethodRef = methodInstance;
  21280. }
  21281. }
  21282. return usedMethod;
  21283. }
  21284. void BfModule::CheckOverridenMethod(BfMethodInstance* methodInstance, BfMethodInstance* methodOverriden)
  21285. {
  21286. auto methodDef = methodInstance->mMethodDef;
  21287. auto prevProtection = methodOverriden->mMethodDef->mProtection;
  21288. if ((methodDef->mProtection != prevProtection) && (methodDef->mMethodType != BfMethodType_Dtor))
  21289. {
  21290. const char* protectionNames[] = { "hidden", "private", "internal", "protected", "protected internal", "public" };
  21291. BF_STATIC_ASSERT(BF_ARRAY_COUNT(protectionNames) == BfProtection_COUNT);
  21292. BfAstNode* protectionRefNode = NULL;
  21293. if (auto propertyMethodDeclaration = methodDef->GetPropertyMethodDeclaration())
  21294. {
  21295. protectionRefNode = propertyMethodDeclaration->mProtectionSpecifier;
  21296. if (protectionRefNode == NULL)
  21297. protectionRefNode = propertyMethodDeclaration->mPropertyDeclaration->mProtectionSpecifier;
  21298. if (protectionRefNode == NULL)
  21299. protectionRefNode = propertyMethodDeclaration->mPropertyDeclaration->mNameNode;
  21300. }
  21301. else if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  21302. {
  21303. protectionRefNode = methodDeclaration->mProtectionSpecifier;
  21304. if (protectionRefNode == NULL)
  21305. protectionRefNode = methodDeclaration->mNameNode;
  21306. }
  21307. if (protectionRefNode != NULL)
  21308. Fail(StrFormat("Cannot change access modifiers when overriding '%s' inherited member", protectionNames[(int)prevProtection]), protectionRefNode, true);
  21309. }
  21310. }
  21311. bool BfModule::SlotInterfaceMethod(BfMethodInstance* methodInstance)
  21312. {
  21313. auto typeInstance = mCurTypeInstance;
  21314. auto methodDef = methodInstance->mMethodDef;
  21315. if (methodDef->mMethodType == BfMethodType_Ctor)
  21316. return true;
  21317. bool foundOverride = false;
  21318. if ((methodDef->mBody == NULL) && (methodDef->mProtection == BfProtection_Private))
  21319. {
  21320. auto methodDeclaration = methodDef->GetMethodDeclaration();
  21321. BfAstNode* refNode = NULL;
  21322. if (auto propertyDeclaration = methodDef->GetPropertyDeclaration())
  21323. refNode = propertyDeclaration->mProtectionSpecifier;
  21324. else if (methodDeclaration != NULL)
  21325. refNode = methodDeclaration->mProtectionSpecifier;
  21326. Fail("Private interface methods must provide a body", refNode);
  21327. }
  21328. if ((methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface != NULL) && (!methodDef->mIsOverride))
  21329. {
  21330. Fail("Explicit interfaces can only be specified for overrides in interface declarations", methodDef->GetMethodDeclaration()->mExplicitInterface);
  21331. }
  21332. BfAstNode* declaringNode = methodDef->GetRefNode();
  21333. for (auto& ifaceTypeInst : typeInstance->mInterfaces)
  21334. {
  21335. auto ifaceInst = ifaceTypeInst.mInterfaceType;
  21336. int startIdx = ifaceTypeInst.mStartInterfaceTableIdx;
  21337. int iMethodCount = (int)ifaceInst->mMethodInstanceGroups.size();
  21338. if ((methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface != ifaceInst))
  21339. continue;
  21340. ifaceInst->mTypeDef->PopulateMemberSets();
  21341. BfMethodDef* nextMethod = NULL;
  21342. BfMemberSetEntry* entry = NULL;
  21343. if (ifaceInst->mTypeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  21344. nextMethod = (BfMethodDef*)entry->mMemberDef;
  21345. while (nextMethod != NULL)
  21346. {
  21347. auto checkMethod = nextMethod;
  21348. nextMethod = nextMethod->mNextWithSameName;
  21349. auto ifaceMethod = ifaceInst->mMethodInstanceGroups[checkMethod->mIdx].mDefault;
  21350. if (ifaceMethod == NULL)
  21351. continue;
  21352. if (CompareMethodSignatures(ifaceMethod, methodInstance))
  21353. {
  21354. if (methodDef->mIsOverride)
  21355. {
  21356. if (ifaceMethod->mMethodDef->mProtection == BfProtection_Private)
  21357. {
  21358. auto error = Fail(StrFormat("Interface method '%s' cannot override private interface method '%s'", MethodToString(methodInstance).c_str(), MethodToString(ifaceMethod).c_str()), declaringNode);
  21359. if (error != NULL)
  21360. {
  21361. mCompiler->mPassInstance->MoreInfo("See base interface method", ifaceMethod->mMethodDef->GetRefNode());
  21362. }
  21363. }
  21364. foundOverride = true;
  21365. }
  21366. else if (!methodDef->mIsNew)
  21367. {
  21368. Warn(BfWarning_CS0114_MethodHidesInherited, StrFormat("Method hides inherited member from '%s'. Use the 'new' keyword if hiding was intentional.", TypeToString(ifaceInst).c_str()), declaringNode);
  21369. }
  21370. }
  21371. }
  21372. }
  21373. if ((methodDef->mIsOverride) && (!foundOverride))
  21374. {
  21375. // This allows us to declare a method in the base definition or in an extension and then provide
  21376. // an implementation in a more-specific extension
  21377. typeInstance->mTypeDef->PopulateMemberSets();
  21378. BfMethodDef* nextMethod = NULL;
  21379. BfMemberSetEntry* entry = NULL;
  21380. if (typeInstance->mTypeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  21381. nextMethod = (BfMethodDef*)entry->mMemberDef;
  21382. while (nextMethod != NULL)
  21383. {
  21384. auto checkMethod = nextMethod;
  21385. nextMethod = nextMethod->mNextWithSameName;
  21386. auto ifaceMethod = typeInstance->mMethodInstanceGroups[checkMethod->mIdx].mDefault;
  21387. if (ifaceMethod == NULL)
  21388. continue;
  21389. if (ifaceMethod->mMethodDef->mDeclaringType == methodInstance->mMethodDef->mDeclaringType)
  21390. continue;
  21391. if (CompareMethodSignatures(ifaceMethod, methodInstance))
  21392. {
  21393. foundOverride = true;
  21394. }
  21395. }
  21396. // for (int methodIdx = 0; methodIdx < typeInstance->mMethodInstanceGroups.size(); methodIdx++)
  21397. // {
  21398. // auto ifaceMethod = typeInstance->mMethodInstanceGroups[methodIdx].mDefault;
  21399. // if (ifaceMethod == NULL)
  21400. // continue;
  21401. // if (ifaceMethod->mMethodDef->mDeclaringType == methodInstance->mMethodDef->mDeclaringType)
  21402. // continue;
  21403. //
  21404. // if (CompareMethodSignatures(ifaceMethod, methodInstance))
  21405. // {
  21406. // foundOverride = true;
  21407. // }
  21408. // }
  21409. }
  21410. if (methodDef->mIsOverride)
  21411. {
  21412. if (!foundOverride)
  21413. {
  21414. BfTokenNode* overrideToken = NULL;
  21415. if (auto propertyDeclaration = methodDef->GetPropertyDeclaration())
  21416. overrideToken = propertyDeclaration->mVirtualSpecifier;
  21417. else if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  21418. overrideToken = methodDeclaration->mVirtualSpecifier;
  21419. if (overrideToken != NULL)
  21420. {
  21421. Fail("No suitable method found to override", overrideToken, true);
  21422. }
  21423. else
  21424. {
  21425. // Possible cause - DTOR with params
  21426. AssertErrorState();
  21427. }
  21428. }
  21429. return true;
  21430. }
  21431. // Generic methods can't be called virtually
  21432. if (methodInstance->GetNumGenericParams() != 0)
  21433. return true;
  21434. // Only public methods can be called virtually
  21435. if (methodDef->mProtection != BfProtection_Public)
  21436. return true;
  21437. UniqueSlotVirtualMethod(methodInstance);
  21438. return true;
  21439. }
  21440. void BfModule::SetMethodDependency(BfMethodInstance* methodInstance)
  21441. {
  21442. if (methodInstance->mMethodInfoEx == NULL)
  21443. return;
  21444. int wantMinDepth = -1;
  21445. if (mCurTypeInstance != NULL)
  21446. wantMinDepth = mCurTypeInstance->mDependencyMap.mMinDependDepth + 1;
  21447. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mMethodInfoEx != NULL) && (mCurMethodInstance->mMethodInfoEx->mMinDependDepth != -1))
  21448. {
  21449. int wantTypeMinDepth = mCurMethodInstance->mMethodInfoEx->mMinDependDepth + 1;
  21450. if ((wantMinDepth == -1) || (wantTypeMinDepth < wantMinDepth))
  21451. wantMinDepth = wantTypeMinDepth;
  21452. }
  21453. if ((methodInstance->mMethodInfoEx->mMinDependDepth == -1) || (wantMinDepth < methodInstance->mMethodInfoEx->mMinDependDepth))
  21454. methodInstance->mMethodInfoEx->mMinDependDepth = wantMinDepth;
  21455. }
  21456. void BfModule::DbgFinish()
  21457. {
  21458. if ((mBfIRBuilder == NULL) || (mExtensionCount != 0))
  21459. return;
  21460. if (mAwaitingInitFinish)
  21461. FinishInit();
  21462. if (mHasForceLinkMarker)
  21463. return;
  21464. String markerName;
  21465. BfIRValue linkMarker;
  21466. if (mBfIRBuilder->DbgHasInfo())
  21467. {
  21468. bool needForceLinking = false;
  21469. for (auto& ownedType : mOwnedTypeInstances)
  21470. {
  21471. bool hasConfirmedReference = false;
  21472. for (auto& methodInstGroup : ownedType->mMethodInstanceGroups)
  21473. {
  21474. if ((methodInstGroup.IsImplemented()) && (methodInstGroup.mDefault != NULL) &&
  21475. (!methodInstGroup.mDefault->mMethodDef->mIsStatic) && (methodInstGroup.mDefault->mIsReified) && (!methodInstGroup.mDefault->mAlwaysInline) &&
  21476. ((methodInstGroup.mOnDemandKind == BfMethodOnDemandKind_AlwaysInclude) || (methodInstGroup.mOnDemandKind == BfMethodOnDemandKind_Referenced)) &&
  21477. (methodInstGroup.mHasEmittedReference))
  21478. {
  21479. hasConfirmedReference = true;
  21480. }
  21481. }
  21482. if ((!hasConfirmedReference) || (ownedType->IsBoxed()))
  21483. needForceLinking = true;
  21484. }
  21485. if ((needForceLinking) && (mProject->mCodeGenOptions.mAsmKind == BfAsmKind_None))
  21486. {
  21487. BfMethodState methodState;
  21488. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  21489. methodState.mTempKind = BfMethodState::TempKind_Static;
  21490. mHasForceLinkMarker = true;
  21491. auto voidType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_None));
  21492. SizedArray<BfIRType, 0> paramTypes;
  21493. BfIRFunctionType funcType = mBfIRBuilder->CreateFunctionType(voidType, paramTypes);
  21494. String linkName = "FORCELINKMOD_" + mModuleName;
  21495. BfIRFunction func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, linkName);
  21496. mBfIRBuilder->SetActiveFunction(func);
  21497. auto entryBlock = mBfIRBuilder->CreateBlock("main", true);
  21498. mBfIRBuilder->SetInsertPoint(entryBlock);
  21499. auto firstType = mOwnedTypeInstances[0];
  21500. UpdateSrcPos(mContext->mBfObjectType->mTypeDef->GetRefNode());
  21501. SizedArray<BfIRMDNode, 1> diParamTypes;
  21502. diParamTypes.Add(mBfIRBuilder->DbgGetType(GetPrimitiveType(BfTypeCode_None)));
  21503. BfIRMDNode diFuncType = mBfIRBuilder->DbgCreateSubroutineType(diParamTypes);
  21504. auto diScope = mBfIRBuilder->DbgCreateFunction(mDICompileUnit, "FORCELINKMOD", linkName, mCurFilePosition.mFileInstance->mDIFile,
  21505. mCurFilePosition.mCurLine + 1, diFuncType, false, true, mCurFilePosition.mCurLine + 1, 0, false, func);
  21506. methodState.mCurScope->mDIScope = diScope;
  21507. UpdateSrcPos(mContext->mBfObjectType->mTypeDef->GetRefNode(), BfSrcPosFlag_Force);
  21508. SizedArray<BfIRValue, 8> args;
  21509. BfExprEvaluator exprEvaluator(this);
  21510. for (auto& ownedType : mOwnedTypeInstances)
  21511. {
  21512. auto alloca = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_Int8)));
  21513. auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(diScope, "variable", mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, mBfIRBuilder->DbgGetType(ownedType));
  21514. mBfIRBuilder->DbgInsertDeclare(alloca, diVariable);
  21515. }
  21516. mBfIRBuilder->CreateRetVoid();
  21517. mBfIRBuilder->SetActiveFunction(BfIRFunction());
  21518. }
  21519. }
  21520. }
  21521. bool BfModule::Finish()
  21522. {
  21523. BP_ZONE("BfModule::Finish");
  21524. BfLogSysM("BfModule finish: %p\n", this);
  21525. if (mHadBuildError)
  21526. {
  21527. // Don't AssertErrorState here, this current pass may not have failed but
  21528. // the module was still queued in mFinishedModuleWorkList
  21529. ClearModule();
  21530. return true;
  21531. }
  21532. if (mUsedSlotCount != -1)
  21533. {
  21534. BF_ASSERT(mCompiler->mMaxInterfaceSlots != -1);
  21535. mUsedSlotCount = mCompiler->mMaxInterfaceSlots;
  21536. }
  21537. if ((!mGeneratesCode) && (!mAddedToCount))
  21538. return true;
  21539. BF_ASSERT(mAddedToCount);
  21540. mAddedToCount = false;
  21541. mAwaitingFinish = false;
  21542. mCompiler->mStats.mModulesFinished++;
  21543. if (HasCompiledOutput())
  21544. {
  21545. BF_ASSERT(!mBfIRBuilder->mIgnoreWrites);
  21546. DbgFinish();
  21547. if (mAwaitingInitFinish)
  21548. FinishInit();
  21549. for (auto ownedTypeInst : mOwnedTypeInstances)
  21550. {
  21551. // Generate dbg info and add global variables if we haven't already
  21552. mBfIRBuilder->PopulateType(ownedTypeInst);
  21553. }
  21554. if (mBfIRBuilder->DbgHasInfo())
  21555. {
  21556. mBfIRBuilder->DbgFinalize();
  21557. }
  21558. String objOutputPath;
  21559. String irOutputPath;
  21560. mIsModuleMutable = false;
  21561. //mOutFileNames.Clear();
  21562. BF_ASSERT(((int)mOutFileNames.size() >= mExtensionCount) || (mParentModule != NULL));
  21563. bool writeModule = mBfIRBuilder->HasExports();
  21564. String outputPath;
  21565. BfCodeGenOptions codeGenOptions = mProject->mCodeGenOptions;
  21566. auto& compilerOpts = mCompiler->mOptions;
  21567. codeGenOptions.mSIMDSetting = compilerOpts.mSIMDSetting;
  21568. auto moduleOptions = GetModuleOptions();
  21569. codeGenOptions.mOptLevel = moduleOptions.mOptLevel;
  21570. codeGenOptions.mSIMDSetting = moduleOptions.mSIMDSetting;
  21571. codeGenOptions.mWriteLLVMIR = mCompiler->mOptions.mWriteIR;
  21572. codeGenOptions.mWriteObj = mCompiler->mOptions.mGenerateObj;
  21573. codeGenOptions.mWriteBitcode = mCompiler->mOptions.mGenerateBitcode;
  21574. codeGenOptions.mVirtualMethodOfs = 1 + mCompiler->GetDynCastVDataCount() + mCompiler->mMaxInterfaceSlots;
  21575. codeGenOptions.mDynSlotOfs = mSystem->mPtrSize - mCompiler->GetDynCastVDataCount() * 4;
  21576. mCompiler->mStats.mIRBytes += mBfIRBuilder->mStream.GetSize();
  21577. mCompiler->mStats.mConstBytes += mBfIRBuilder->mTempAlloc.GetAllocSize();
  21578. bool allowWriteToLib = true;
  21579. if ((allowWriteToLib) && (codeGenOptions.mOptLevel == BfOptLevel_OgPlus) &&
  21580. (!mCompiler->IsHotCompile()) && (mModuleName != "vdata"))
  21581. {
  21582. codeGenOptions.mWriteToLib = true;
  21583. mWroteToLib = true;
  21584. }
  21585. else
  21586. {
  21587. mWroteToLib = false;
  21588. }
  21589. for (int fileIdx = 0; fileIdx <= mExtensionCount; fileIdx++)
  21590. {
  21591. outputPath = mModuleName;
  21592. outputPath = mCompiler->mOutputDirectory + "/" + mProject->mName + "/" + outputPath;
  21593. BfModuleFileName moduleFileName;
  21594. if (mParentModule != NULL)
  21595. {
  21596. for (auto&& checkPair : mParentModule->mSpecializedMethodModules)
  21597. {
  21598. if (checkPair.mValue == this)
  21599. moduleFileName.mProjects = checkPair.mKey;
  21600. }
  21601. }
  21602. moduleFileName.mProjects.Add(mProject);
  21603. if (fileIdx > 0)
  21604. outputPath += StrFormat("@%d", fileIdx + 1);
  21605. if (mCompiler->mOptions.mWriteIR)
  21606. irOutputPath = outputPath + ".ll";
  21607. if (mCompiler->mOptions.mGenerateObj)
  21608. {
  21609. objOutputPath = outputPath + BF_OBJ_EXT;
  21610. moduleFileName.mFileName = objOutputPath;
  21611. }
  21612. else if (mCompiler->mOptions.mWriteIR)
  21613. {
  21614. moduleFileName.mFileName = irOutputPath;
  21615. }
  21616. else if ((!mCompiler->mOptions.mGenerateObj) && (!mCompiler->mOptions.mGenerateBitcode) && (!mCompiler->mOptions.mWriteIR))
  21617. {
  21618. BFMODULE_FATAL(this, "Neither obj nor IR specified");
  21619. }
  21620. moduleFileName.mModuleWritten = writeModule;
  21621. moduleFileName.mWroteToLib = mWroteToLib;
  21622. if (!mOutFileNames.Contains(moduleFileName))
  21623. mOutFileNames.Add(moduleFileName);
  21624. }
  21625. if (mCompiler->IsHotCompile())
  21626. {
  21627. codeGenOptions.mIsHotCompile = true;
  21628. if (mParentModule != NULL)
  21629. mParentModule->mHadHotObjectWrites = true;
  21630. mHadHotObjectWrites = true;
  21631. }
  21632. //TODO: Testing VDATA
  21633. /*if (mModuleName == "vdata")
  21634. {
  21635. codeGenOptions.mOptLevel = 4;
  21636. }*/
  21637. codeGenOptions.GenerateHash();
  21638. BP_ZONE("BfModule::Finish.WriteObjectFile");
  21639. if ((writeModule) && (!mBfIRBuilder->mIgnoreWrites))
  21640. mCompiler->mCodeGen.WriteObjectFile(this, outputPath, codeGenOptions);
  21641. mLastModuleWrittenRevision = mCompiler->mRevision;
  21642. }
  21643. else
  21644. {
  21645. for (auto type : mOwnedTypeInstances)
  21646. {
  21647. BF_ASSERT((!type->IsIncomplete()) || (type->IsSpecializedByAutoCompleteMethod()));
  21648. }
  21649. }
  21650. for (auto& specModulePair : mSpecializedMethodModules)
  21651. {
  21652. auto specModule = specModulePair.mValue;
  21653. if ((specModule->mIsModuleMutable) && (!specModule->mAwaitingFinish))
  21654. {
  21655. BfLogSysM(" Mutable spec module remaining: %p\n", specModule);
  21656. }
  21657. }
  21658. CleanupFileInstances();
  21659. // We can't ClearModuleData here because we need the mSpecializedMethodModules to remain valid until we Finish them too
  21660. return true;
  21661. }
  21662. void BfModule::ReportMemory(MemReporter* memReporter)
  21663. {
  21664. memReporter->Add(sizeof(BfModule));
  21665. if (mBfIRBuilder != NULL)
  21666. {
  21667. memReporter->BeginSection("IRBuilder_ConstData");
  21668. memReporter->Add("Used", mBfIRBuilder->mTempAlloc.GetAllocSize());
  21669. memReporter->Add("Unused", mBfIRBuilder->mTempAlloc.GetTotalAllocSize() - mBfIRBuilder->mTempAlloc.GetAllocSize());
  21670. memReporter->EndSection();
  21671. memReporter->BeginSection("IRBuilder_BFIR");
  21672. memReporter->Add("Used", (int)(mBfIRBuilder->mStream.GetSize()));
  21673. memReporter->Add("Unused", (int)(mBfIRBuilder->mStream.mPools.size() * ChunkedDataBuffer::ALLOC_SIZE) - mBfIRBuilder->mStream.GetSize());
  21674. memReporter->EndSection();
  21675. memReporter->Add(sizeof(BfIRBuilder));
  21676. }
  21677. memReporter->BeginSection("FileInstanceMap");
  21678. memReporter->AddMap(mFileInstanceMap);
  21679. memReporter->AddMap(mNamedFileInstanceMap);
  21680. memReporter->Add((int)mNamedFileInstanceMap.size() * sizeof(BfFileInstance));
  21681. memReporter->EndSection();
  21682. memReporter->AddVec(mOwnedTypeInstances, false);
  21683. memReporter->AddVec(mSpecializedMethodModules, false);
  21684. memReporter->AddVec(mOutFileNames, false);
  21685. memReporter->AddMap("FuncReferences", mFuncReferences, false);
  21686. memReporter->AddMap(mInterfaceSlotRefs, false);
  21687. memReporter->AddMap(mStaticFieldRefs, false);
  21688. memReporter->AddMap(mClassVDataRefs, false);
  21689. memReporter->AddMap("VDataExtMap", mClassVDataExtRefs, false);
  21690. memReporter->AddMap(mTypeDataRefs, false);
  21691. memReporter->AddMap(mDbgRawAllocDataRefs, false);
  21692. memReporter->AddMap(mDeferredMethodCallData, false);
  21693. memReporter->AddHashSet(mDeferredMethodIds, false);
  21694. memReporter->AddHashSet("ModuleRefs", mModuleRefs, false);
  21695. }
  21696. // ClearModuleData is called immediately after the module is compiled, so don't clear out any data that needs to
  21697. // be transient through the next compile
  21698. void BfModule::ClearModuleData(bool clearTransientData)
  21699. {
  21700. BfLogSysM("ClearModuleData %p\n", this);
  21701. if (mAddedToCount)
  21702. {
  21703. mCompiler->mStats.mModulesFinished++;
  21704. mAddedToCount = false;
  21705. }
  21706. mDICompileUnit = BfIRMDNode();
  21707. if (clearTransientData)
  21708. mIncompleteMethodCount = 0;
  21709. mHasGenericMethods = false;
  21710. // We don't want to clear these because we want it to persist through module extensions-
  21711. // otherwise we may think an extension succeeds even though the base module failed
  21712. //mHadBuildError = false;
  21713. //mHadBuildWarning = false;
  21714. mClassVDataRefs.Clear();
  21715. mClassVDataExtRefs.Clear();
  21716. for (auto& kv : mTypeDataRefs)
  21717. kv.mValue = BfIRValue();
  21718. mStringCharPtrPool.Clear();
  21719. mStringObjectPool.Clear();
  21720. mStaticFieldRefs.Clear();
  21721. BF_ASSERT(!mIgnoreErrors);
  21722. for (auto prevIRBuilder : mPrevIRBuilders)
  21723. delete prevIRBuilder;
  21724. mPrevIRBuilders.Clear();
  21725. for (auto& specPair : mSpecializedMethodModules)
  21726. {
  21727. auto specModule = specPair.mValue;
  21728. specModule->ClearModuleData();
  21729. }
  21730. for (int i = 0; i < BfBuiltInFuncType_Count; i++)
  21731. mBuiltInFuncs[i] = BfIRFunction();
  21732. if (mNextAltModule != NULL)
  21733. mNextAltModule->ClearModuleData();
  21734. BfLogSysM("ClearModuleData. Deleting IRBuilder: %p\n", mBfIRBuilder);
  21735. mIsModuleMutable = false;
  21736. delete mBfIRBuilder;
  21737. mBfIRBuilder = NULL;
  21738. mWantsIRIgnoreWrites = false;
  21739. }
  21740. void BfModule::DisownMethods()
  21741. {
  21742. for (int i = 0; i < BfBuiltInFuncType_Count; i++)
  21743. mBuiltInFuncs[i] = BfIRFunction();
  21744. BfModule* methodModule = this;
  21745. if (mParentModule != NULL)
  21746. methodModule = mParentModule;
  21747. for (auto typeInst : methodModule->mOwnedTypeInstances)
  21748. {
  21749. for (auto& methodGroup : typeInst->mMethodInstanceGroups)
  21750. {
  21751. if (methodGroup.mDefault != NULL)
  21752. {
  21753. if (methodGroup.mDefault->mIRFunction)
  21754. {
  21755. BF_ASSERT(methodGroup.mDefault->mDeclModule != NULL);
  21756. if (methodGroup.mDefault->mDeclModule == this)
  21757. {
  21758. methodGroup.mDefault->mIRFunction = BfIRFunction();
  21759. }
  21760. }
  21761. }
  21762. if (methodGroup.mMethodSpecializationMap != NULL)
  21763. {
  21764. for (auto& mapPair : *methodGroup.mMethodSpecializationMap)
  21765. {
  21766. auto methodInstance = mapPair.mValue;
  21767. if (methodInstance->mDeclModule == this)
  21768. {
  21769. methodInstance->mIRFunction = BfIRFunction();
  21770. }
  21771. }
  21772. }
  21773. }
  21774. }
  21775. }
  21776. void BfModule::ClearModule()
  21777. {
  21778. ClearModuleData();
  21779. DisownMethods();
  21780. for (auto& specPair : mSpecializedMethodModules)
  21781. {
  21782. auto specModule = specPair.mValue;
  21783. specModule->ClearModule();
  21784. }
  21785. if (mNextAltModule != NULL)
  21786. mNextAltModule->ClearModule();
  21787. }