BfModule.cpp 712 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093
  1. //#define USE_THUNKED_MddLLOC..
  2. #include "BeefySysLib/util/AllocDebug.h"
  3. #pragma warning(push) // 6
  4. #pragma warning(disable:4996)
  5. #include "BfCompiler.h"
  6. #include "BfSystem.h"
  7. #include "BfParser.h"
  8. #include "BfCodeGen.h"
  9. #include "BfExprEvaluator.h"
  10. #include "../Backend/BeLibManger.h"
  11. #include <fcntl.h>
  12. #include "BfConstResolver.h"
  13. #include "BfMangler.h"
  14. #include "BeefySysLib/util/PerfTimer.h"
  15. #include "BeefySysLib/util/BeefPerf.h"
  16. #include "BeefySysLib/util/StackHelper.h"
  17. #include "BfSourceClassifier.h"
  18. #include "BfAutoComplete.h"
  19. #include "BfDemangler.h"
  20. #include "BfResolvePass.h"
  21. #include "BfFixits.h"
  22. #include "BfIRCodeGen.h"
  23. #include "BfDefBuilder.h"
  24. #include "BfDeferEvalChecker.h"
  25. #pragma warning(pop)
  26. //////////////////////////////////////////////////////////////////////////
  27. static bool gDebugStuff = false;
  28. USING_NS_BF;
  29. //////////////////////////////////////////////////////////////////////////
  30. void BfLocalVariable::Init()
  31. {
  32. if (mResolvedType->IsValuelessType())
  33. {
  34. mIsAssigned = true;
  35. return;
  36. }
  37. if (mIsAssigned)
  38. return;
  39. bool isStruct = mResolvedType->IsStruct();
  40. if (mResolvedType->IsRef())
  41. isStruct = mResolvedType->GetUnderlyingType()->IsStruct();
  42. if ((isStruct) || ((mIsThis) && (mResolvedType->IsStructOrStructPtr())))
  43. {
  44. auto resolvedTypeRef = mResolvedType;
  45. if ((resolvedTypeRef->IsPointer()) || (resolvedTypeRef->IsRef()))
  46. resolvedTypeRef = resolvedTypeRef->GetUnderlyingType();
  47. auto typeInstance = resolvedTypeRef->ToTypeInstance();
  48. mUnassignedFieldFlags = (1 << typeInstance->mMergedFieldDataCount) - 1;
  49. if ((mIsThis) && (typeInstance->mBaseType != NULL))
  50. {
  51. // Base ctor is responsible for initializing its own fields
  52. mUnassignedFieldFlags &= ~(((int64)1 << typeInstance->mBaseType->mMergedFieldDataCount) - 1);
  53. }
  54. if (mUnassignedFieldFlags == 0)
  55. mIsAssigned = true;
  56. }
  57. else
  58. {
  59. mUnassignedFieldFlags = 1;
  60. }
  61. }
  62. BfLocalMethod::~BfLocalMethod()
  63. {
  64. BfLogSys(mSystem, "~BfLocalMethod %p\n", this);
  65. if (mMethodDeclaration != NULL)
  66. {
  67. mSource->mRefCount--;
  68. BF_ASSERT(mSource->mRefCount >= 0);
  69. }
  70. delete mMethodDef;
  71. delete mMethodInstanceGroup;
  72. }
  73. void BfDeferredLocalAssignData::ExtendFrom(BfDeferredLocalAssignData* outerLocalAssignData, bool doChain)
  74. {
  75. mIsChained = doChain;
  76. if (outerLocalAssignData == NULL)
  77. return;
  78. mChainedAssignData = outerLocalAssignData;
  79. if (!doChain)
  80. {
  81. outerLocalAssignData->BreakExtendChain();
  82. mAssignedLocals = outerLocalAssignData->mAssignedLocals;
  83. }
  84. mVarIdBarrier = outerLocalAssignData->mVarIdBarrier;
  85. }
  86. // The "extend chain" is broken when we have a conditional where the variable may not be defined after the block.
  87. // IE: "a" will be defined after the following, but "b" will not necessarily be defined.
  88. // if ((GetValue(out a)) && (GetValue(out b)) {}
  89. void BfDeferredLocalAssignData::BreakExtendChain()
  90. {
  91. if (!mIsChained)
  92. return;
  93. mIsChained = false;
  94. if (mChainedAssignData == NULL)
  95. return;
  96. mChainedAssignData->BreakExtendChain();
  97. mAssignedLocals = mChainedAssignData->mAssignedLocals;
  98. }
  99. void BfDeferredLocalAssignData::SetIntersection(const BfDeferredLocalAssignData& otherLocalAssignData)
  100. {
  101. BreakExtendChain();
  102. //TODO: We got rid of this case because we now set the proper assigned data when we do a return
  103. // If one of these had a return then treat that case as if it did have an assign -- because it doesn't
  104. // cause an UNASSIGNED value to be used
  105. // if (mHadReturn || otherLocalAssignData.mHadReturn)
  106. // {
  107. // SetUnion(otherLocalAssignData);
  108. // mHadFallthrough = mHadFallthrough && otherLocalAssignData.mHadFallthrough;
  109. // return;
  110. // }
  111. for (int i = 0; i < (int)mAssignedLocals.size(); )
  112. {
  113. auto& local = mAssignedLocals[i];
  114. if (!otherLocalAssignData.mAssignedLocals.Contains(local))
  115. {
  116. mAssignedLocals.RemoveAt(i);
  117. }
  118. else
  119. i++;
  120. }
  121. mHadFallthrough = mHadFallthrough && otherLocalAssignData.mHadFallthrough;
  122. }
  123. void BfDeferredLocalAssignData::Validate() const
  124. {
  125. for (auto var : mAssignedLocals)
  126. {
  127. BF_ASSERT((uintptr)var.mLocalVar->mName.length() < 100000);
  128. }
  129. }
  130. void BfDeferredLocalAssignData::SetUnion(const BfDeferredLocalAssignData& otherLocalAssignData)
  131. {
  132. BreakExtendChain();
  133. Validate();
  134. otherLocalAssignData.Validate();
  135. auto otherItr = otherLocalAssignData.mAssignedLocals.begin();
  136. while (otherItr != otherLocalAssignData.mAssignedLocals.end())
  137. {
  138. if (!mAssignedLocals.Contains(*otherItr))
  139. mAssignedLocals.push_back(*otherItr);
  140. ++otherItr;
  141. }
  142. mHadFallthrough = mHadFallthrough || otherLocalAssignData.mHadFallthrough;
  143. }
  144. BfMethodState::~BfMethodState()
  145. {
  146. BF_ASSERT(mPendingNullConditional == NULL);
  147. if (mPrevMethodState != NULL)
  148. {
  149. BF_ASSERT(mCurAccessId == 1);
  150. BF_ASSERT(mCurLocalVarId <= 0);
  151. }
  152. for (auto local : mLocals)
  153. delete local;
  154. for (auto& kv : mLambdaCache)
  155. delete kv.mValue;
  156. }
  157. BfMethodState* BfMethodState::GetMethodStateForLocal(BfLocalVariable* localVar)
  158. {
  159. auto checkMethodState = this;
  160. while (checkMethodState != NULL)
  161. {
  162. if ((localVar->mLocalVarIdx < checkMethodState->mLocals.size()) &&
  163. (checkMethodState->mLocals[localVar->mLocalVarIdx] == localVar))
  164. return checkMethodState;
  165. checkMethodState = checkMethodState->mPrevMethodState;
  166. }
  167. BF_FATAL("Failed to find method state for localvar");
  168. return NULL;
  169. }
  170. void BfMethodState::LocalDefined(BfLocalVariable* localVar, int fieldIdx)
  171. {
  172. auto localVarMethodState = GetMethodStateForLocal(localVar);
  173. if (localVarMethodState != this)
  174. {
  175. return;
  176. }
  177. //BF_ASSERT(localVarMethodState == this);
  178. if (!localVar->mIsAssigned)
  179. {
  180. BfDeferredLocalAssignData* ifDeferredLocalAssignData = NULL;
  181. // 'a' is always defined, but 'b' isn't:
  182. // if (Check(out a) || Check(out b)) { } int z = a;
  183. auto deferredLocalAssignData = mDeferredLocalAssignData;
  184. if ((deferredLocalAssignData != NULL) &&
  185. (deferredLocalAssignData->mIsIfCondition) &&
  186. (!deferredLocalAssignData->mIfMayBeSkipped))
  187. {
  188. ifDeferredLocalAssignData = deferredLocalAssignData;
  189. deferredLocalAssignData = deferredLocalAssignData->mChainedAssignData;
  190. }
  191. while ((deferredLocalAssignData != NULL) &&
  192. ((deferredLocalAssignData->mIsChained) || (deferredLocalAssignData->mIsUnconditional)))
  193. deferredLocalAssignData = deferredLocalAssignData->mChainedAssignData;
  194. if ((deferredLocalAssignData == NULL) || (localVar->mLocalVarId >= deferredLocalAssignData->mVarIdBarrier))
  195. {
  196. if (fieldIdx >= 0)
  197. {
  198. localVar->mUnassignedFieldFlags &= ~((int64)1 << fieldIdx);
  199. /*if ((localVar->mResolvedTypeRef != NULL) && (localVar->mResolvedTypeRef->IsUnion()))
  200. {
  201. }*/
  202. if (localVar->mUnassignedFieldFlags == 0)
  203. localVar->mIsAssigned = true;
  204. }
  205. else
  206. {
  207. localVar->mIsAssigned = true;
  208. }
  209. }
  210. else
  211. {
  212. BF_ASSERT(deferredLocalAssignData->mVarIdBarrier != -1);
  213. BfAssignedLocal defineVal = {localVar, fieldIdx + 1};
  214. auto& assignedLocals = deferredLocalAssignData->mAssignedLocals;
  215. if (!assignedLocals.Contains(defineVal))
  216. assignedLocals.push_back(defineVal);
  217. if (ifDeferredLocalAssignData != NULL)
  218. {
  219. auto& assignedLocals = ifDeferredLocalAssignData->mAssignedLocals;
  220. if (!assignedLocals.Contains(defineVal))
  221. assignedLocals.push_back(defineVal);
  222. }
  223. }
  224. }
  225. localVar->mWrittenToId = GetRootMethodState()->mCurAccessId++;
  226. }
  227. void BfMethodState::ApplyDeferredLocalAssignData(const BfDeferredLocalAssignData& deferredLocalAssignData)
  228. {
  229. BF_ASSERT(&deferredLocalAssignData != mDeferredLocalAssignData);
  230. for (auto& assignedLocal : deferredLocalAssignData.mAssignedLocals)
  231. {
  232. LocalDefined(assignedLocal.mLocalVar);
  233. }
  234. }
  235. void BfMethodState::Reset()
  236. {
  237. mHeadScope.mDeferredCallEntries.DeleteAll();
  238. }
  239. //////////////////////////////////////////////////////////////////////////
  240. void BfAmbiguityContext::Add(int id, BfTypeInterfaceEntry* interfaceEntry, int methodIdx, BfMethodInstance* candidateA, BfMethodInstance* candidateB)
  241. {
  242. Entry* entry = NULL;
  243. if (mEntries.TryAdd(id, NULL, &entry))
  244. {
  245. entry->mInterfaceEntry = interfaceEntry;
  246. entry->mMethodIdx = methodIdx;
  247. }
  248. if (!entry->mCandidates.Contains(candidateA))
  249. entry->mCandidates.push_back(candidateA);
  250. if (!entry->mCandidates.Contains(candidateB))
  251. entry->mCandidates.push_back(candidateB);
  252. }
  253. void BfAmbiguityContext::Remove(int id)
  254. {
  255. mEntries.Remove(id);
  256. }
  257. void BfAmbiguityContext::Finish()
  258. {
  259. for (auto& entryPair : mEntries)
  260. {
  261. int id = entryPair.mKey;
  262. auto entry = &entryPair.mValue;
  263. if (id >= 0)
  264. {
  265. auto declMethodInstance = mTypeInstance->mVirtualMethodTable[id].mDeclaringMethod;
  266. auto error = mModule->Fail(StrFormat("Method '%s' has ambiguous overrides", mModule->MethodToString(declMethodInstance).c_str()), declMethodInstance->mMethodDef->GetRefNode());
  267. for (auto candidate : entry->mCandidates)
  268. {
  269. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' is a candidate", mModule->MethodToString(candidate).c_str()), candidate->mMethodDef->GetRefNode());
  270. }
  271. }
  272. else
  273. {
  274. auto iMethodInst = entry->mInterfaceEntry->mInterfaceType->mMethodInstanceGroups[entry->mMethodIdx].mDefault;
  275. auto error = mModule->Fail(StrFormat("Interface method '%s' has ambiguous implementations", mModule->MethodToString(iMethodInst).c_str()), entry->mInterfaceEntry->mDeclaringType->GetRefNode());
  276. for (auto candidate : entry->mCandidates)
  277. {
  278. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' is a candidate", mModule->MethodToString(candidate).c_str()), candidate->mMethodDef->GetRefNode());
  279. }
  280. }
  281. }
  282. }
  283. //////////////////////////////////////////////////////////////////////////
  284. class HasAppendAllocVisitor : BfElementVisitor
  285. {
  286. public:
  287. bool mHas;
  288. public:
  289. HasAppendAllocVisitor()
  290. {
  291. mHas = false;
  292. }
  293. void Visit(BfObjectCreateExpression* objCreateExpr)
  294. {
  295. if (auto newToken = BfNodeDynCast<BfTokenNode>(objCreateExpr->mNewNode))
  296. {
  297. if (newToken->GetToken() == BfToken_Append)
  298. {
  299. mHas = true;
  300. }
  301. }
  302. }
  303. bool HasAppendAlloc(BfAstNode* node)
  304. {
  305. mHas = false;
  306. VisitChild(node);
  307. return mHas;
  308. }
  309. };
  310. class AppendAllocVisitor : public BfStructuralVisitor
  311. {
  312. public:
  313. BfModule* mModule;
  314. HasAppendAllocVisitor mHasAppendAllocVisitor;
  315. BfTypedValue mConstAccum;
  316. bool mFailed;
  317. bool mIsFirstConstPass;
  318. int mCurAppendAlign;
  319. public:
  320. AppendAllocVisitor()
  321. {
  322. mFailed = false;
  323. mIsFirstConstPass = false;
  324. mCurAppendAlign = 0;
  325. }
  326. void EmitAppendAlign(int align, int sizeMultiple = 0)
  327. {
  328. if (mIsFirstConstPass)
  329. mModule->mCurMethodInstance->mAppendAllocAlign = BF_MAX((int)mModule->mCurMethodInstance->mAppendAllocAlign, align);
  330. if (sizeMultiple == 0)
  331. sizeMultiple = align;
  332. if (mCurAppendAlign == 0)
  333. mCurAppendAlign = sizeMultiple;
  334. else
  335. {
  336. if (sizeMultiple % align == 0)
  337. mCurAppendAlign = align;
  338. else
  339. mCurAppendAlign = sizeMultiple % align;
  340. }
  341. if (mConstAccum)
  342. {
  343. auto constant = mModule->mBfIRBuilder->GetConstant(mConstAccum.mValue);
  344. if (constant != NULL)
  345. mConstAccum.mValue = mModule->GetConstValue(BF_ALIGN(constant->mInt64, align));
  346. else
  347. BF_ASSERT(mIsFirstConstPass);
  348. return;
  349. }
  350. mModule->EmitAppendAlign(align, sizeMultiple);
  351. }
  352. void Visit(BfAstNode* astNode) override
  353. {
  354. mModule->VisitChild(astNode);
  355. }
  356. void DoObjectCreate(BfObjectCreateExpression* objCreateExpr, BfVariableDeclaration* variableDecl)
  357. {
  358. if (auto newToken = BfNodeDynCast<BfTokenNode>(objCreateExpr->mNewNode))
  359. {
  360. if (newToken->GetToken() == BfToken_Append)
  361. {
  362. //auto variableDecl = BfNodeDynCast<BfVariableDeclaration>(objCreateExpr->mParent);
  363. auto accumValuePtr = mModule->mCurMethodState->mRetVal.mValue;
  364. auto intPtrType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  365. BfArrayType* arrayType = NULL;
  366. bool isArrayAlloc = false;
  367. bool isRawArrayAlloc = objCreateExpr->mStarToken != NULL;
  368. SizedArray<BfIRValue, 2> dimLengthVals;
  369. BfType* origResolvedTypeRef = NULL;
  370. if (auto dotTypeRef = BfNodeDynCast<BfDotTypeReference>(objCreateExpr->mTypeRef))
  371. {
  372. if (variableDecl != NULL)
  373. {
  374. origResolvedTypeRef = mModule->ResolveTypeRef(variableDecl->mTypeRef, BfPopulateType_Data, BfResolveTypeRefFlag_NoResolveGenericParam);
  375. if (origResolvedTypeRef->IsObject())
  376. {
  377. if (origResolvedTypeRef->IsArray())
  378. {
  379. arrayType = (BfArrayType*)origResolvedTypeRef;
  380. origResolvedTypeRef = origResolvedTypeRef->GetUnderlyingType();
  381. isArrayAlloc = true;
  382. }
  383. }
  384. else if (origResolvedTypeRef->IsPointer())
  385. {
  386. origResolvedTypeRef = origResolvedTypeRef->GetUnderlyingType();
  387. }
  388. }
  389. }
  390. else if (auto arrayTypeRef = BfNodeDynCast<BfArrayTypeRef>(objCreateExpr->mTypeRef))
  391. {
  392. isArrayAlloc = true;
  393. origResolvedTypeRef = mModule->ResolveTypeRef(arrayTypeRef->mElementType);
  394. int dimensions = 1;
  395. if (arrayTypeRef->mParams.size() != 0)
  396. {
  397. auto intType = mModule->ResolveTypeDef(mModule->mSystem->mTypeIntPtr);
  398. for (auto arg : arrayTypeRef->mParams)
  399. {
  400. if (auto tokenNode = BfNodeDynCastExact<BfTokenNode>(arg))
  401. {
  402. if (tokenNode->GetToken() == BfToken_Comma)
  403. {
  404. if (isRawArrayAlloc)
  405. {
  406. mModule->Fail("Sized arrays cannot be multidimensional", tokenNode);
  407. continue;
  408. }
  409. dimensions++;
  410. continue;
  411. }
  412. }
  413. auto expr = BfNodeDynCast<BfExpression>(arg);
  414. if ((isRawArrayAlloc) && (!dimLengthVals.IsEmpty()))
  415. {
  416. mModule->CreateValueFromExpression(expr, intType);
  417. continue;
  418. }
  419. BfTypedValue dimLength;
  420. if (expr == NULL)
  421. {
  422. // Not specified
  423. dimLengthVals.push_back(BfIRValue());
  424. continue;
  425. }
  426. if (arg != NULL)
  427. dimLength = mModule->CreateValueFromExpression(expr, intType);
  428. if (!dimLength)
  429. {
  430. dimLength = mModule->GetDefaultTypedValue(intType);
  431. }
  432. dimLengthVals.push_back(dimLength.mValue);
  433. }
  434. }
  435. if (!isRawArrayAlloc)
  436. arrayType = mModule->CreateArrayType(origResolvedTypeRef, dimensions);
  437. }
  438. if (origResolvedTypeRef == NULL)
  439. origResolvedTypeRef = mModule->ResolveTypeRef(objCreateExpr->mTypeRef, BfPopulateType_Data, BfResolveTypeRefFlag_NoResolveGenericParam);
  440. if (origResolvedTypeRef == NULL)
  441. {
  442. mModule->AssertErrorState();
  443. return;
  444. }
  445. bool isGenericParam = origResolvedTypeRef->IsGenericParam();
  446. auto resolvedTypeRef = origResolvedTypeRef;
  447. auto resultType = resolvedTypeRef;
  448. BfIRValue sizeValue;
  449. int curAlign = 0;
  450. if (isArrayAlloc)
  451. {
  452. int dimensions = 1;
  453. if (arrayType != NULL)
  454. dimensions = arrayType->mDimensions;
  455. bool sizeFailed = false;
  456. //
  457. {
  458. BfAstNode* initNode = objCreateExpr;
  459. for (int dim = 0; dim < dimensions; dim++)
  460. {
  461. BfAstNode* nextInitNode = NULL;
  462. int dimSize = -1;
  463. if (initNode == objCreateExpr)
  464. {
  465. dimSize = objCreateExpr->mArguments.size();
  466. if (!objCreateExpr->mArguments.IsEmpty())
  467. nextInitNode = objCreateExpr->mArguments[0];
  468. }
  469. else if (auto tupleNode = BfNodeDynCast<BfTupleExpression>(initNode))
  470. {
  471. dimSize = (int)tupleNode->mCommas.size() + 1;
  472. }
  473. if (dimSize >= 0)
  474. {
  475. if (dim >= dimLengthVals.size())
  476. dimLengthVals.Add(mModule->GetConstValue(dimSize));
  477. }
  478. else
  479. {
  480. sizeFailed = true;
  481. }
  482. }
  483. }
  484. BfIRValue allocCount;
  485. if (!sizeFailed)
  486. {
  487. if (!dimLengthVals.IsEmpty())
  488. {
  489. allocCount = dimLengthVals[0];
  490. for (int dim = 1; dim < (int)dimLengthVals.size(); dim++)
  491. allocCount = mModule->mBfIRBuilder->CreateMul(allocCount, dimLengthVals[dim]);
  492. }
  493. }
  494. if (!allocCount)
  495. {
  496. mFailed = true;
  497. if (!mIsFirstConstPass)
  498. {
  499. if (!mConstAccum)
  500. mModule->Fail("Unable to determine append alloc size", objCreateExpr->mNewNode);
  501. return;
  502. }
  503. }
  504. if (isRawArrayAlloc)
  505. {
  506. curAlign = resultType->mAlign;
  507. EmitAppendAlign(resultType->mAlign);
  508. sizeValue = mModule->mBfIRBuilder->CreateMul(mModule->GetConstValue(resultType->mSize), allocCount);
  509. }
  510. else
  511. {
  512. if (arrayType == NULL)
  513. arrayType = mModule->CreateArrayType(resultType, 1);
  514. // Array is a special case where the total size isn't aligned with mAlign
  515. // since we add arbitrary elements to the end without padding the end to align
  516. EmitAppendAlign(arrayType->mAlign, resultType->mAlign);
  517. curAlign = arrayType->mAlign;
  518. auto firstElementField = &arrayType->mFieldInstances.back();
  519. int arrayClassSize = arrayType->mInstSize - firstElementField->mDataSize;
  520. sizeValue = mModule->GetConstValue(arrayClassSize);
  521. BfIRValue elementDataSize = mModule->mBfIRBuilder->CreateMul(mModule->GetConstValue(resultType->mSize), allocCount);
  522. sizeValue = mModule->mBfIRBuilder->CreateAdd(sizeValue, elementDataSize);
  523. }
  524. }
  525. else
  526. {
  527. auto typeInst = resultType->ToTypeInstance();
  528. if (typeInst != NULL)
  529. {
  530. curAlign = typeInst->mInstAlign;
  531. EmitAppendAlign(typeInst->mInstAlign, typeInst->mInstSize);
  532. sizeValue = mModule->GetConstValue(typeInst->mInstSize);
  533. }
  534. else
  535. {
  536. curAlign = resultType->mAlign;
  537. EmitAppendAlign(resultType->mAlign, resultType->mSize);
  538. sizeValue = mModule->GetConstValue(resultType->mSize);
  539. }
  540. BfTypedValue emtpyThis(mModule->mBfIRBuilder->GetFakeVal(), resultType, (typeInst == NULL) || (typeInst->IsComposite()));
  541. BfExprEvaluator exprEvaluator(mModule);
  542. SetAndRestoreValue<bool> prevNoBind(exprEvaluator.mNoBind, exprEvaluator.mNoBind || isGenericParam);
  543. BfFunctionBindResult bindResult;
  544. bindResult.mWantsArgs = true;
  545. exprEvaluator.mFunctionBindResult = &bindResult;
  546. SizedArray<BfExpression*, 8> copiedArgs;
  547. for (BfExpression* arg : objCreateExpr->mArguments)
  548. copiedArgs.push_back(arg);
  549. BfSizedArray<BfExpression*> sizedArgExprs(copiedArgs);
  550. BfResolvedArgs argValues(&sizedArgExprs);
  551. if (typeInst != NULL)
  552. {
  553. exprEvaluator.ResolveArgValues(argValues);
  554. exprEvaluator.MatchConstructor(objCreateExpr->mTypeRef, objCreateExpr, emtpyThis, typeInst, argValues, false, true);
  555. }
  556. exprEvaluator.mFunctionBindResult = NULL;
  557. if (bindResult.mMethodInstance != NULL)
  558. {
  559. if (bindResult.mMethodInstance->mMethodDef->mHasAppend)
  560. {
  561. auto calcAppendArgs = bindResult.mIRArgs;
  562. BF_ASSERT(calcAppendArgs[0].IsFake());
  563. calcAppendArgs.RemoveRange(0, 2); // Remove 'this' and 'appendIdx'
  564. auto calcAppendMethodModule = mModule->GetMethodInstanceAtIdx(bindResult.mMethodInstance->GetOwner(), bindResult.mMethodInstance->mMethodDef->mIdx + 1, BF_METHODNAME_CALCAPPEND);
  565. auto subDependSize = mModule->TryConstCalcAppend(bindResult.mMethodInstance, calcAppendArgs);
  566. if (calcAppendMethodModule.mMethodInstance->mAppendAllocAlign > 0)
  567. {
  568. EmitAppendAlign(calcAppendMethodModule.mMethodInstance->mAppendAllocAlign);
  569. BF_ASSERT(calcAppendMethodModule.mMethodInstance->mEndingAppendAllocAlign > -1);
  570. mModule->mCurMethodState->mCurAppendAlign = BF_MAX(calcAppendMethodModule.mMethodInstance->mEndingAppendAllocAlign, 0);
  571. }
  572. curAlign = std::max(curAlign, (int)calcAppendMethodModule.mMethodInstance->mAppendAllocAlign);
  573. if ((!subDependSize) && (!mConstAccum))
  574. {
  575. BF_ASSERT(calcAppendMethodModule.mFunc);
  576. subDependSize = exprEvaluator.CreateCall(calcAppendMethodModule.mMethodInstance, calcAppendMethodModule.mFunc, false, calcAppendArgs);
  577. BF_ASSERT(subDependSize.mType == mModule->GetPrimitiveType(BfTypeCode_IntPtr));
  578. }
  579. if (subDependSize)
  580. sizeValue = mModule->mBfIRBuilder->CreateAdd(sizeValue, subDependSize.mValue);
  581. else
  582. mFailed = true;
  583. }
  584. }
  585. }
  586. if (sizeValue)
  587. {
  588. if (mConstAccum)
  589. {
  590. if (!sizeValue.IsConst())
  591. {
  592. mFailed = true;
  593. if (!mIsFirstConstPass)
  594. return;
  595. }
  596. mConstAccum.mValue = mModule->mBfIRBuilder->CreateAdd(sizeValue, mConstAccum.mValue);
  597. }
  598. else
  599. {
  600. auto prevVal = mModule->mBfIRBuilder->CreateLoad(accumValuePtr);
  601. auto addedVal = mModule->mBfIRBuilder->CreateAdd(sizeValue, prevVal);
  602. mModule->mBfIRBuilder->CreateStore(addedVal, accumValuePtr);
  603. }
  604. }
  605. }
  606. }
  607. }
  608. void Visit(BfObjectCreateExpression* objCreateExpr) override
  609. {
  610. DoObjectCreate(objCreateExpr, NULL);
  611. }
  612. void Visit(BfVariableDeclaration* varDecl) override
  613. {
  614. if (mHasAppendAllocVisitor.HasAppendAlloc(varDecl))
  615. {
  616. if (auto objectCreateExpr = BfNodeDynCast<BfObjectCreateExpression>(varDecl->mInitializer))
  617. DoObjectCreate(objectCreateExpr, varDecl);
  618. else
  619. VisitChild(varDecl->mInitializer);
  620. if (varDecl->mNameNode != NULL)
  621. {
  622. BfLocalVariable* localDef = new BfLocalVariable();
  623. localDef->mName = varDecl->mNameNode->ToString();
  624. localDef->mNameNode = BfNodeDynCast<BfIdentifierNode>(varDecl->mNameNode);
  625. localDef->mResolvedType = mModule->GetPrimitiveType(BfTypeCode_None);
  626. localDef->mIsReadOnly = true;
  627. localDef->mParamFailed = true;
  628. localDef->mReadFromId = 0;
  629. mModule->AddLocalVariableDef(localDef);
  630. }
  631. }
  632. else
  633. {
  634. mModule->Visit(varDecl);
  635. }
  636. }
  637. void Visit(BfExpressionStatement* exprStatement) override
  638. {
  639. VisitChild(exprStatement->mExpression);
  640. }
  641. // void Visit(BfIfStatement* ifStmt) override
  642. // {
  643. // mModule->DoIfStatement(ifStmt,
  644. // mHasAppendAllocVisitor.HasAppendAlloc(ifStmt->mTrueStatement),
  645. // mHasAppendAllocVisitor.HasAppendAlloc(ifStmt->mFalseStatement));
  646. // }
  647. void Visit(BfBlock* block) override
  648. {
  649. if (!mHasAppendAllocVisitor.HasAppendAlloc(block))
  650. return;
  651. int appendAllocIdx = -1;
  652. for (int childIdx = block->mChildArr.mSize - 1; childIdx >= 0; childIdx--)
  653. {
  654. auto child = block->mChildArr.mVals[childIdx];
  655. if (mHasAppendAllocVisitor.HasAppendAlloc(child))
  656. {
  657. for (int emitIdx = 0; emitIdx <= childIdx; emitIdx++)
  658. {
  659. auto emitChild = block->mChildArr.mVals[emitIdx];
  660. mModule->UpdateSrcPos(emitChild);
  661. VisitChild(emitChild);
  662. if ((mFailed) && (!mIsFirstConstPass))
  663. break;
  664. }
  665. break;
  666. }
  667. }
  668. }
  669. };
  670. //////////////////////////////////////////////////////////////////////////
  671. BfModule* gLastCreatedModule = NULL;
  672. BfModule::BfModule(BfContext* context, const StringImpl& moduleName)
  673. {
  674. BfLogSys(context->mSystem, "BfModule::BFModule %p %s\n", this, moduleName.c_str());
  675. gLastCreatedModule = this;
  676. mContext = context;
  677. mModuleName = moduleName;
  678. if (!moduleName.empty())
  679. mContext->mUsedModuleNames.Add(ToUpper(moduleName));
  680. mAddedToCount = false;
  681. mParentModule = NULL;
  682. mNextAltModule = NULL;
  683. mBfIRBuilder = NULL;
  684. mWantsIRIgnoreWrites = false;
  685. mModuleOptions = NULL;
  686. mLastUsedRevision = -1;
  687. mUsedSlotCount = -1;
  688. mIsReified = true;
  689. mReifyQueued = false;
  690. mIsSpecialModule = false;
  691. mIsScratchModule = false;
  692. mIsSpecializedMethodModuleRoot = false; // There may be mNextAltModules extending from this
  693. mHadBuildError = false;
  694. mHadBuildWarning = false;
  695. mIgnoreErrors = false;
  696. mIgnoreWarnings = false;
  697. mReportErrors = true;
  698. mIsInsideAutoComplete = false;
  699. mIsDeleting = false;
  700. mSkipInnerLookup = false;
  701. mIsHotModule = false;
  702. mSetIllegalSrcPosition = false;
  703. mNoResolveGenericParams = false;
  704. mWroteToLib = false;
  705. mContext = context;
  706. mCompiler = context->mCompiler;
  707. mSystem = mCompiler->mSystem;
  708. mProject = NULL;
  709. mCurMethodState = NULL;
  710. mAttributeState = NULL;
  711. mCurLocalMethodId = 0;
  712. mParentNodeEntry = NULL;
  713. mRevision = -1;
  714. mRebuildIdx = 0;
  715. mLastModuleWrittenRevision = 0;
  716. mIsModuleMutable = false;
  717. mExtensionCount = 0;
  718. mIncompleteMethodCount = 0;
  719. mOnDemandMethodCount = 0;
  720. mHasGenericMethods = false;
  721. mCurMethodInstance = NULL;
  722. mCurTypeInstance = NULL;
  723. mAwaitingInitFinish = false;
  724. mAwaitingFinish = false;
  725. mHasFullDebugInfo = false;
  726. mHadHotObjectWrites = false;
  727. for (int i = 0; i < BfBuiltInFuncType_Count; i++)
  728. mBuiltInFuncs[i] = BfIRFunction();
  729. BfLogSysM("Creating module %p: %s Reified: %d ResolveOnly: %d\n", this, mModuleName.c_str(), mIsReified, mCompiler->mIsResolveOnly);
  730. }
  731. void BfReportMemory();
  732. BfModule::~BfModule()
  733. {
  734. BfLogSysM("Deleting module %p: %s \n", this, mModuleName.c_str());
  735. if (!mIsDeleting)
  736. RemoveModuleData();
  737. }
  738. void BfModule::RemoveModuleData()
  739. {
  740. BF_ASSERT(!mIsDeleting);
  741. if (!mModuleName.empty())
  742. {
  743. // Note: module names not necessarily unique
  744. mContext->mUsedModuleNames.Remove(ToUpper(mModuleName));
  745. }
  746. CleanupFileInstances();
  747. delete mBfIRBuilder;
  748. mBfIRBuilder = NULL;
  749. //delete mCpu;
  750. for (auto prevModule : mPrevIRBuilders)
  751. delete prevModule;
  752. mPrevIRBuilders.Clear();
  753. for (auto& pairVal : mDeferredMethodCallData)
  754. delete pairVal.mValue;
  755. mDeferredMethodCallData.Clear();
  756. mDeferredMethodIds.Clear();
  757. for (auto& specModulePair : mSpecializedMethodModules)
  758. delete specModulePair.mValue;
  759. mSpecializedMethodModules.Clear();
  760. if (mNextAltModule != NULL)
  761. delete mNextAltModule;
  762. mNextAltModule = NULL;
  763. if (mModuleOptions != NULL)
  764. delete mModuleOptions;
  765. mModuleOptions = NULL;
  766. BfReportMemory();
  767. }
  768. void BfModule::Init(bool isFullRebuild)
  769. {
  770. mContext->mFinishedModuleWorkList.Remove(this);
  771. if ((mCompiler->mIsResolveOnly) && (this != mContext->mUnreifiedModule))
  772. BF_ASSERT(mIsReified);
  773. if (!mIsScratchModule)
  774. {
  775. mCompiler->mStats.mModulesStarted++;
  776. if (mIsReified)
  777. mCompiler->mStats.mReifiedModuleCount++;
  778. mAddedToCount = true;
  779. }
  780. mIsHotModule = (mProject != NULL) && (mCompiler->mOptions.mHotProject != NULL) && (mCompiler->mOptions.mHotProject->ContainsReference(mProject));
  781. mFuncReferences.Clear();
  782. mClassVDataRefs.Clear();
  783. mClassVDataExtRefs.Clear();
  784. //mTypeDataRefs.Clear();
  785. mDbgRawAllocDataRefs.Clear();
  786. CleanupFileInstances();
  787. mStaticFieldRefs.Clear();
  788. //mInterfaceSlotRefs.Clear();
  789. // If we are just doing an extension then the ownede types aren't rebuilt.
  790. // If we set mRevision then QueueMethodSpecializations wouldn't actually queue up required specializations
  791. // and we'd end up with link errors if the original module uniquely referred to any generic methods
  792. if (isFullRebuild)
  793. mRevision = mCompiler->mRevision;
  794. BF_ASSERT(mCurTypeInstance == NULL);
  795. mIsModuleMutable = true;
  796. BF_ASSERT((mBfIRBuilder == NULL) || (mCompiler->mIsResolveOnly));
  797. #ifdef _DEBUG
  798. EnsureIRBuilder(mCompiler->mLastAutocompleteModule == this);
  799. #else
  800. EnsureIRBuilder(false);
  801. #endif
  802. mCurMethodState = NULL;
  803. mAwaitingInitFinish = true;
  804. mOnDemandMethodCount = 0;
  805. mAwaitingFinish = false;
  806. mHasForceLinkMarker = false;
  807. mUsedSlotCount = -1;
  808. }
  809. bool BfModule::WantsFinishModule()
  810. {
  811. return (mIncompleteMethodCount == 0) && (mOnDemandMethodCount == 0) && (!mHasGenericMethods) && (!mIsScratchModule) && (mExtensionCount == 0) && (mParentModule == NULL);
  812. }
  813. void BfModule::FinishInit()
  814. {
  815. BF_ASSERT(mAwaitingInitFinish);
  816. auto moduleOptions = GetModuleOptions();
  817. mBfIRBuilder->Start(mModuleName, mCompiler->mSystem->mPtrSize, IsOptimized());
  818. mBfIRBuilder->Module_SetTargetTriple(mCompiler->mOptions.mTargetTriple);
  819. mBfIRBuilder->SetBackend(IsTargetingBeefBackend());
  820. if (moduleOptions.mOptLevel == BfOptLevel_OgPlus)
  821. {
  822. // Og+ requires debug info
  823. moduleOptions.mEmitDebugInfo = 1;
  824. }
  825. mHasFullDebugInfo = moduleOptions.mEmitDebugInfo == 1;
  826. if ((!mCompiler->mIsResolveOnly) && (!mIsScratchModule) && (moduleOptions.mEmitDebugInfo != 0) && (mIsReified))
  827. {
  828. mBfIRBuilder->DbgInit();
  829. }
  830. else
  831. mHasFullDebugInfo = false;
  832. if ((mBfIRBuilder->DbgHasInfo()) && (mModuleName != "") &&
  833. ((moduleOptions.mEmitDebugInfo != 0)))
  834. {
  835. if (mCompiler->mOptions.IsCodeView())
  836. {
  837. mBfIRBuilder->Module_AddModuleFlag("CodeView", 1);
  838. }
  839. else
  840. {
  841. mBfIRBuilder->Module_AddModuleFlag("Dwarf Version", 4);
  842. }
  843. mBfIRBuilder->Module_AddModuleFlag("Debug Info Version", 3);
  844. mDICompileUnit = mBfIRBuilder->DbgCreateCompileUnit(llvm::dwarf::DW_LANG_C_plus_plus, mModuleName, ".", "Beef Compiler 0.42", /*moduleOptions.mOptLevel > 0*/false, "", 0, !mHasFullDebugInfo);
  845. }
  846. mAwaitingInitFinish = false;
  847. }
  848. void BfModule::ReifyModule()
  849. {
  850. BF_ASSERT((mCompiler->mCompileState != BfCompiler::CompileState_Unreified) && (mCompiler->mCompileState != BfCompiler::CompileState_VData));
  851. BfLogSysM("ReifyModule %@ %s\n", this, mModuleName.c_str());
  852. BF_ASSERT((this != mContext->mScratchModule) && (this != mContext->mUnreifiedModule));
  853. mIsReified = true;
  854. mReifyQueued = false;
  855. StartNewRevision(RebuildKind_SkipOnDemandTypes, true);
  856. mCompiler->mStats.mModulesReified++;
  857. }
  858. void BfModule::UnreifyModule()
  859. {
  860. BfLogSysM("UnreifyModule %p %s\n", this, mModuleName.c_str());
  861. BF_ASSERT((this != mContext->mScratchModule) && (this != mContext->mUnreifiedModule));
  862. mIsReified = false;
  863. mReifyQueued = false;
  864. StartNewRevision(RebuildKind_None, true);
  865. mCompiler->mStats.mModulesUnreified++;
  866. }
  867. void BfModule::CleanupFileInstances()
  868. {
  869. for (auto& itr : mNamedFileInstanceMap)
  870. {
  871. BfLogSysM("FileInstance deleted: %p\n", itr.mValue);
  872. delete itr.mValue;
  873. }
  874. mCurFilePosition.mFileInstance = NULL;//
  875. mFileInstanceMap.Clear();
  876. mNamedFileInstanceMap.Clear();
  877. }
  878. void BfModule::Cleanup()
  879. {
  880. CleanupFileInstances();
  881. }
  882. void BfModule::PrepareForIRWriting(BfTypeInstance* typeInst)
  883. {
  884. if (HasCompiledOutput())
  885. {
  886. // It's possible that the target's code hasn't changed but we're requesting a new generic method specialization
  887. if ((!mIsModuleMutable) && (!typeInst->IsUnspecializedType()) && (!typeInst->mResolvingVarField))
  888. {
  889. StartExtension();
  890. }
  891. }
  892. else
  893. {
  894. EnsureIRBuilder();
  895. }
  896. }
  897. void BfModule::EnsureIRBuilder(bool dbgVerifyCodeGen)
  898. {
  899. BF_ASSERT(!mIsDeleting);
  900. if (mBfIRBuilder == NULL)
  901. {
  902. if ((!mIsScratchModule) && (!mAddedToCount))
  903. {
  904. mCompiler->mStats.mModulesStarted++;
  905. mAddedToCount = true;
  906. }
  907. BF_ASSERT(mStaticFieldRefs.GetCount() == 0);
  908. /*if (mCompiler->mIsResolveOnly)
  909. BF_ASSERT(mIsResolveOnly);*/
  910. mBfIRBuilder = new BfIRBuilder(this);
  911. BfLogSysM("Created mBfIRBuilder %p in %p %s Reified: %d\n", mBfIRBuilder, this, mModuleName.c_str(), mIsReified);
  912. if (mIsScratchModule)
  913. {
  914. mBfIRBuilder->mIgnoreWrites = true;
  915. BF_ASSERT(!dbgVerifyCodeGen);
  916. }
  917. #ifdef _DEBUG
  918. if (mCompiler->mIsResolveOnly)
  919. {
  920. // For "deep" verification testing
  921. /*if (!mIsSpecialModule)
  922. dbgVerifyCodeGen = true;*/
  923. // We only want to turn this off on smaller builds for testing
  924. mBfIRBuilder->mIgnoreWrites = true;
  925. if (dbgVerifyCodeGen)
  926. mBfIRBuilder->mIgnoreWrites = false;
  927. if (!mBfIRBuilder->mIgnoreWrites)
  928. {
  929. // The only purpose of not ignoring writes is so we can verify the codegen one instruction at a time
  930. mBfIRBuilder->mDbgVerifyCodeGen = true;
  931. }
  932. }
  933. else if (!mIsReified)
  934. {
  935. mBfIRBuilder->mIgnoreWrites = true;
  936. }
  937. else
  938. {
  939. // We almost always want this to be 'false' unless we need need to be able to inspect the generated LLVM
  940. // code as we walk the AST
  941. //mBfIRBuilder->mDbgVerifyCodeGen = true;
  942. if (
  943. (mModuleName == "-")
  944. //|| (mModuleName == "System_Internal")
  945. //|| (mModuleName == "vdata")
  946. //|| (mModuleName == "Hey_Dude_Bro_TestClass")
  947. )
  948. mBfIRBuilder->mDbgVerifyCodeGen = true;
  949. // Just for testing!
  950. //mBfIRBuilder->mIgnoreWrites = true;
  951. }
  952. #else
  953. if (mCompiler->mIsResolveOnly)
  954. {
  955. // Always ignore writes in resolveOnly for release builds
  956. mBfIRBuilder->mIgnoreWrites = true;
  957. }
  958. else
  959. {
  960. // Just for memory testing! This breaks everything.
  961. //mBfIRBuilder->mIgnoreWrites = true;
  962. // For "deep" verification testing
  963. //mBfIRBuilder->mDbgVerifyCodeGen = true;
  964. }
  965. #endif
  966. mWantsIRIgnoreWrites = mBfIRBuilder->mIgnoreWrites;
  967. }
  968. }
  969. BfIRValue BfModule::CreateForceLinkMarker(BfModule* module, String* outName)
  970. {
  971. String name = "FORCELINKMOD_" + module->mModuleName;
  972. if (outName != NULL)
  973. *outName = name;
  974. auto markerType = GetPrimitiveType(BfTypeCode_Int8);
  975. return mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapType(markerType), true, BfIRLinkageType_External, (module == this) ? mBfIRBuilder->CreateConst(BfTypeCode_Int8, 0) : BfIRValue(), name);
  976. }
  977. void BfModule::StartNewRevision(RebuildKind rebuildKind, bool force)
  978. {
  979. BP_ZONE("BfModule::StartNewRevision");
  980. // The project MAY be deleted because disabling a project can cause types to be deleted which
  981. // causes other types rebuild BEFORE they get deleted, which is okay (though wasteful)
  982. //BF_ASSERT((mProject == NULL) || (!mProject->mDisabled));
  983. // Already on new revision?
  984. if ((mRevision == mCompiler->mRevision) && (!force))
  985. return;
  986. mHadBuildError = false;
  987. mHadBuildWarning = false;
  988. mExtensionCount = 0;
  989. mRevision = mCompiler->mRevision;
  990. mRebuildIdx++;
  991. ClearModuleData();
  992. // Clear this here, not in ClearModuleData, so we preserve those references even after writing out module
  993. if (rebuildKind != BfModule::RebuildKind_None) // Leave string pool refs for when we need to use things like [LinkName("")] methods bofore re-reification
  994. mStringPoolRefs.Clear();
  995. mDllImportEntries.Clear();
  996. mImportFileNames.Clear();
  997. for (auto& pairVal : mDeferredMethodCallData)
  998. delete pairVal.mValue;
  999. mDeferredMethodCallData.Clear();
  1000. mDeferredMethodIds.Clear();
  1001. mModuleRefs.Clear();
  1002. mOutFileNames.Clear();
  1003. mTypeDataRefs.Clear();
  1004. mInterfaceSlotRefs.Clear();
  1005. if (rebuildKind == BfModule::RebuildKind_None)
  1006. {
  1007. for (auto& specPair : mSpecializedMethodModules)
  1008. {
  1009. auto specModule = specPair.mValue;
  1010. if (specModule->mIsReified != mIsReified)
  1011. {
  1012. if (mIsReified)
  1013. specModule->ReifyModule();
  1014. else
  1015. specModule->UnreifyModule();
  1016. }
  1017. }
  1018. }
  1019. else
  1020. {
  1021. for (auto& specPair : mSpecializedMethodModules)
  1022. {
  1023. auto specModule = specPair.mValue;
  1024. delete specModule;
  1025. }
  1026. }
  1027. mSpecializedMethodModules.Clear();
  1028. delete mNextAltModule;
  1029. mNextAltModule = NULL;
  1030. BF_ASSERT(mModuleOptions == NULL);
  1031. BfLogSysM("Mod:%p StartNewRevision: %s Revision: %d\n", this, mModuleName.c_str(), mRevision);
  1032. bool needsTypePopulated = false;
  1033. int oldOnDemandCount = 0;
  1034. // We don't have to rebuild types in the unspecialized module because there is no
  1035. // data that's needed -- their method instances are all NULL and the module
  1036. // doesn't get included in the build
  1037. if (this != mContext->mScratchModule)
  1038. {
  1039. for (int typeIdx = 0; typeIdx < (int)mOwnedTypeInstances.size(); typeIdx++)
  1040. {
  1041. auto typeInst = mOwnedTypeInstances[typeIdx];
  1042. if (!typeInst->IsDeleting())
  1043. {
  1044. typeInst->mIsReified = mIsReified;
  1045. if (rebuildKind != BfModule::RebuildKind_None)
  1046. {
  1047. if (typeInst->IsOnDemand())
  1048. {
  1049. // Changing config should require on demand types to be recreated, but reifying a module shouldn't cause the type to be deleted
  1050. if (rebuildKind == BfModule::RebuildKind_All)
  1051. mContext->DeleteType(typeInst);
  1052. else
  1053. {
  1054. RebuildMethods(typeInst);
  1055. }
  1056. }
  1057. else
  1058. mContext->RebuildType(typeInst, false, false, false);
  1059. }
  1060. else
  1061. {
  1062. for (auto& methodGroup : typeInst->mMethodInstanceGroups)
  1063. if ((methodGroup.mOnDemandKind == BfMethodOnDemandKind_NoDecl_AwaitingReference) ||
  1064. (methodGroup.mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingReference))
  1065. {
  1066. oldOnDemandCount++;
  1067. }
  1068. }
  1069. if (typeInst->IsDeleting())
  1070. typeIdx--;
  1071. }
  1072. }
  1073. }
  1074. if (!mIsDeleting)
  1075. Init();
  1076. mOnDemandMethodCount += oldOnDemandCount;
  1077. }
  1078. void BfModule::StartExtension()
  1079. {
  1080. BF_ASSERT(!mIsModuleMutable);
  1081. BfLogSysM("Extension started of module %p\n", this);
  1082. mExtensionCount++;
  1083. if (mBfIRBuilder != NULL)
  1084. mPrevIRBuilders.push_back(mBfIRBuilder);
  1085. mBfIRBuilder = NULL;
  1086. mWantsIRIgnoreWrites = false;
  1087. mFuncReferences.Clear();
  1088. mClassVDataRefs.Clear();
  1089. mClassVDataExtRefs.Clear();
  1090. for (auto& kv : mTypeDataRefs)
  1091. kv.mValue = BfIRValue();
  1092. mDbgRawAllocDataRefs.Clear();
  1093. mStringCharPtrPool.Clear();
  1094. mStringObjectPool.Clear();
  1095. mStaticFieldRefs.Clear();
  1096. for (auto& kv : mInterfaceSlotRefs)
  1097. kv.mValue = BfIRValue();
  1098. mDeferredMethodCallData.Clear();
  1099. mDeferredMethodIds.Clear();
  1100. DisownMethods();
  1101. BfLogSysM("Mod:%p StartExtension: %s\n", this, mModuleName.c_str());
  1102. bool wasAwaitingInitFinish = mAwaitingInitFinish;
  1103. int prevOnDemandMethodCount = mOnDemandMethodCount;
  1104. Init(false);
  1105. if (!wasAwaitingInitFinish)
  1106. FinishInit();
  1107. mOnDemandMethodCount = prevOnDemandMethodCount;
  1108. }
  1109. void BfModule::GetConstClassValueParam(BfIRValue classVData, SizedArrayImpl<BfIRValue>& typeValueParams)
  1110. {
  1111. BfIRValue vDataValue;
  1112. if (mCompiler->mOptions.mObjectHasDebugFlags)
  1113. vDataValue = mBfIRBuilder->CreatePtrToInt(classVData, BfTypeCode_IntPtr);
  1114. else
  1115. vDataValue = mBfIRBuilder->CreateBitCast(classVData, mBfIRBuilder->MapType(mContext->mBfClassVDataPtrType));
  1116. typeValueParams.push_back(vDataValue);
  1117. if (mCompiler->mOptions.mObjectHasDebugFlags)
  1118. {
  1119. auto primType = GetPrimitiveType(BfTypeCode_IntPtr);
  1120. typeValueParams.push_back(GetDefaultValue(primType));
  1121. }
  1122. }
  1123. BfIRValue BfModule::GetConstValue(int64 val)
  1124. {
  1125. return mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, (uint64)val);
  1126. }
  1127. BfIRValue BfModule::GetConstValue(int64 val, BfType* type)
  1128. {
  1129. BfType* checkType = type;
  1130. if (type->IsTypedPrimitive())
  1131. {
  1132. checkType = type->GetUnderlyingType();
  1133. }
  1134. if (checkType->IsPrimitiveType())
  1135. {
  1136. auto primType = (BfPrimitiveType*)checkType;
  1137. if (checkType->IsFloat())
  1138. return mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, (double)val);
  1139. else
  1140. return mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, (uint64)val);
  1141. }
  1142. return BfIRValue();
  1143. }
  1144. BfIRValue BfModule::GetConstValue8(int val)
  1145. {
  1146. return mBfIRBuilder->CreateConst(BfTypeCode_Int8, (uint64)val);
  1147. }
  1148. BfIRValue BfModule::GetConstValue32(int32 val)
  1149. {
  1150. return mBfIRBuilder->CreateConst(BfTypeCode_Int32, (uint64)val);
  1151. }
  1152. BfIRValue BfModule::GetConstValue64(int64 val)
  1153. {
  1154. return mBfIRBuilder->CreateConst(BfTypeCode_Int64, (uint64)val);
  1155. }
  1156. BfIRValue BfModule::GetDefaultValue(BfType* type)
  1157. {
  1158. PopulateType(type, BfPopulateType_Data);
  1159. mBfIRBuilder->PopulateType(type, BfIRPopulateType_Declaration);
  1160. if (type->IsTypedPrimitive())
  1161. {
  1162. auto underlyingType = type->GetUnderlyingType();
  1163. if (underlyingType == NULL)
  1164. return mBfIRBuilder->CreateConst(BfTypeCode_Int64, 0);
  1165. return GetDefaultValue(type->GetUnderlyingType());
  1166. }
  1167. if (type->IsPointer() || type->IsObjectOrInterface() || type->IsGenericParam() || type->IsVar() || type->IsRef() || type->IsNull() ||
  1168. type->IsRetTypeType() || type->IsConcreteInterfaceType())
  1169. return mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(type));
  1170. if ((type->IsIntegral()) || (type->IsBoolean()))
  1171. {
  1172. auto primType = (BfPrimitiveType*)type;
  1173. return mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, (uint64)0);
  1174. }
  1175. if (type->IsFloat())
  1176. {
  1177. auto primType = (BfPrimitiveType*)type;
  1178. return mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, 0.0);
  1179. }
  1180. if (type->IsVoid())
  1181. return mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(type));
  1182. return mBfIRBuilder->CreateConstStructZero(mBfIRBuilder->MapType(type));
  1183. }
  1184. BfTypedValue BfModule::GetFakeTypedValue(BfType* type)
  1185. {
  1186. // This is a conservative "IsValueless", since it's not an error to use a fakeVal even if we don't need one
  1187. if (type->mSize == 0)
  1188. return BfTypedValue(BfIRValue::sValueless, type);
  1189. else
  1190. return BfTypedValue(mBfIRBuilder->GetFakeVal(), type);
  1191. }
  1192. BfTypedValue BfModule::GetDefaultTypedValue(BfType* type, bool allowRef, BfDefaultValueKind defaultValueKind)
  1193. {
  1194. PopulateType(type, BfPopulateType_Data);
  1195. mBfIRBuilder->PopulateType(type, type->IsValueType() ? BfIRPopulateType_Full : BfIRPopulateType_Declaration);
  1196. if (defaultValueKind == BfDefaultValueKind_Undef)
  1197. {
  1198. auto primType = type->ToPrimitiveType();
  1199. if (primType != NULL)
  1200. {
  1201. return BfTypedValue(mBfIRBuilder->GetUndefConstValue(primType->mTypeDef->mTypeCode), type);
  1202. }
  1203. return BfTypedValue(mBfIRBuilder->CreateUndefValue(mBfIRBuilder->MapType(type)), type);
  1204. }
  1205. BfTypedValue typedValue;
  1206. if ((defaultValueKind != BfDefaultValueKind_Const) && (!type->IsValuelessType()))
  1207. {
  1208. if (type->IsRef())
  1209. {
  1210. BfRefType* refType = (BfRefType*)type;
  1211. BfType* underlyingType = refType->GetUnderlyingType();
  1212. typedValue = BfTypedValue(CreateAlloca(underlyingType), underlyingType, BfTypedValueKind_Addr);
  1213. }
  1214. else
  1215. {
  1216. typedValue = BfTypedValue(CreateAlloca(type), type, BfTypedValueKind_Addr);
  1217. }
  1218. if (!mBfIRBuilder->mIgnoreWrites)
  1219. {
  1220. mBfIRBuilder->CreateMemSet(typedValue.mValue, GetConstValue(0, GetPrimitiveType(BfTypeCode_Int8)),
  1221. GetConstValue(type->mSize), type->mAlign);
  1222. }
  1223. if ((defaultValueKind == BfDefaultValueKind_Value) && (!type->IsRef()))
  1224. typedValue = LoadValue(typedValue);
  1225. return typedValue;
  1226. }
  1227. if ((type->IsRef()) && (!allowRef))
  1228. {
  1229. BfRefType* refType = (BfRefType*)type;
  1230. BfType* underlyingType = refType->GetUnderlyingType();
  1231. if (underlyingType->IsValuelessType())
  1232. typedValue = BfTypedValue(mBfIRBuilder->GetFakeVal(), underlyingType, true);
  1233. else
  1234. typedValue = BfTypedValue(mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(type)), underlyingType, true);
  1235. }
  1236. else
  1237. {
  1238. typedValue = BfTypedValue(GetDefaultValue(type), type, (defaultValueKind == BfDefaultValueKind_Addr) ? BfTypedValueKind_Addr : BfTypedValueKind_Value);
  1239. }
  1240. return typedValue;
  1241. }
  1242. BfIRValue BfModule::CreateStringCharPtr(const StringImpl& str, int stringId, bool define)
  1243. {
  1244. String stringDataName = StrFormat("__bfStrData%d", stringId);
  1245. BfIRType strCharType;
  1246. //
  1247. {
  1248. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, mWantsIRIgnoreWrites);
  1249. strCharType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->GetPrimitiveType(BfTypeCode_Char8), (int)str.length() + 1);
  1250. }
  1251. BfIRValue strConstant;
  1252. if (define)
  1253. {
  1254. strConstant = mBfIRBuilder->CreateConstString(str);
  1255. }
  1256. BfIRValue gv = mBfIRBuilder->CreateGlobalVariable(strCharType,
  1257. true, BfIRLinkageType_External,
  1258. strConstant, stringDataName);
  1259. if (define)
  1260. mBfIRBuilder->GlobalVar_SetUnnamedAddr(gv, true);
  1261. return mBfIRBuilder->CreateInBoundsGEP(gv, 0, 0);
  1262. }
  1263. BfIRValue BfModule::CreateStringObjectValue(const StringImpl& str, int stringId, bool define)
  1264. {
  1265. auto stringTypeInst = ResolveTypeDef(mCompiler->mStringTypeDef, define ? BfPopulateType_Data : BfPopulateType_Declaration)->ToTypeInstance();
  1266. mBfIRBuilder->PopulateType(stringTypeInst);
  1267. auto classVDataGlobal = CreateClassVDataGlobal(stringTypeInst);
  1268. String stringObjName = StrFormat("__bfStrObj%d", stringId);
  1269. BfIRValue stringValData;
  1270. if (define)
  1271. {
  1272. BfIRValue stringCharsVal = CreateStringCharPtr(str, stringId, define);
  1273. mStringCharPtrPool[stringId] = stringCharsVal;
  1274. SizedArray<BfIRValue, 8> typeValueParams;
  1275. GetConstClassValueParam(classVDataGlobal, typeValueParams);
  1276. auto objData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(stringTypeInst->mBaseType, BfIRPopulateType_Full), typeValueParams);
  1277. auto lenByteCount = stringTypeInst->mFieldInstances[0].mResolvedType->mSize;
  1278. typeValueParams.clear();
  1279. typeValueParams.push_back(objData);
  1280. if (lenByteCount == 4)
  1281. {
  1282. typeValueParams.push_back(GetConstValue32((int)str.length())); // mLength
  1283. typeValueParams.push_back(GetConstValue32((int32)(0x40000000 + str.length() + 1))); // mAllocSizeAndFlags
  1284. }
  1285. else
  1286. {
  1287. typeValueParams.push_back(GetConstValue64(str.length())); // mLength
  1288. typeValueParams.push_back(GetConstValue64(0x4000000000000000LL + str.length() + 1)); // mAllocSizeAndFlags
  1289. }
  1290. typeValueParams.push_back(stringCharsVal); // mPtr
  1291. stringValData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(stringTypeInst, BfIRPopulateType_Full), typeValueParams);
  1292. }
  1293. auto stringValLiteral = mBfIRBuilder->CreateGlobalVariable(
  1294. mBfIRBuilder->MapTypeInst(stringTypeInst),
  1295. true,
  1296. BfIRLinkageType_External,
  1297. define ? stringValData : BfIRValue(),
  1298. stringObjName);
  1299. auto stringVal = mBfIRBuilder->CreateBitCast(stringValLiteral, mBfIRBuilder->MapType(stringTypeInst, BfIRPopulateType_Full));
  1300. return stringVal;
  1301. }
  1302. int BfModule::GetStringPoolIdx(BfIRValue constantStr, BfIRConstHolder* constHolder)
  1303. {
  1304. BF_ASSERT(constantStr.IsConst());
  1305. if (constHolder == NULL)
  1306. constHolder = mBfIRBuilder;
  1307. auto constant = constHolder->GetConstant(constantStr);
  1308. if (constant->mTypeCode == BfTypeCode_Int32)
  1309. {
  1310. return constant->mInt32;
  1311. }
  1312. while (constant->mConstType == BfConstType_BitCast)
  1313. {
  1314. auto constBitCast = (BfConstantBitCast*)constant;
  1315. constant = constHolder->GetConstantById(constBitCast->mTarget);
  1316. }
  1317. if (constant->mConstType == BfConstType_GEP32_2)
  1318. {
  1319. auto constGEP = (BfConstantGEP32_2*)constant;
  1320. constant = constHolder->GetConstantById(constGEP->mTarget);
  1321. }
  1322. if (constant->mConstType == BfConstType_GlobalVar)
  1323. {
  1324. auto constGV = (BfGlobalVar*)constant;
  1325. const char* strDataPrefix = "__bfStrData";
  1326. if (strncmp(constGV->mName, strDataPrefix, strlen(strDataPrefix)) == 0)
  1327. return atoi(constGV->mName + strlen(strDataPrefix));
  1328. const char* strObjPrefix = "__bfStrObj";
  1329. if (strncmp(constGV->mName, strObjPrefix, strlen(strObjPrefix)) == 0)
  1330. return atoi(constGV->mName + strlen(strObjPrefix));
  1331. }
  1332. return -1;
  1333. }
  1334. String* BfModule::GetStringPoolString(BfIRValue constantStr, BfIRConstHolder * constHolder)
  1335. {
  1336. int strId = GetStringPoolIdx(constantStr, constHolder);
  1337. if (strId != -1)
  1338. {
  1339. auto& entry = mContext->mStringObjectIdMap[strId];
  1340. return &entry.mString;
  1341. }
  1342. return NULL;
  1343. }
  1344. BfIRValue BfModule::GetStringCharPtr(int stringId)
  1345. {
  1346. BfIRValue* irValue = NULL;
  1347. if (!mStringCharPtrPool.TryAdd(stringId, NULL, &irValue))
  1348. return *irValue;
  1349. // If this wasn't in neither dictionary yet, add to mStringPoolRefs
  1350. if (!mStringObjectPool.ContainsKey(stringId))
  1351. mStringPoolRefs.Add(stringId);
  1352. const StringImpl& str = mContext->mStringObjectIdMap[stringId].mString;
  1353. BfIRValue strCharPtrConst = CreateStringCharPtr(str, stringId, false);
  1354. *irValue = strCharPtrConst;
  1355. return strCharPtrConst;
  1356. }
  1357. BfIRValue BfModule::GetStringCharPtr(BfIRValue strValue)
  1358. {
  1359. if (strValue.IsConst())
  1360. {
  1361. int stringId = GetStringPoolIdx(strValue);
  1362. BF_ASSERT(stringId != -1);
  1363. return GetStringCharPtr(stringId);
  1364. }
  1365. BfIRValue charPtrPtr = mBfIRBuilder->CreateInBoundsGEP(strValue, 0, 1);
  1366. BfIRValue charPtr = mBfIRBuilder->CreateLoad(charPtrPtr);
  1367. return charPtr;
  1368. }
  1369. BfIRValue BfModule::GetStringCharPtr(const StringImpl& str)
  1370. {
  1371. return GetStringCharPtr(GetStringObjectValue(str));
  1372. }
  1373. BfIRValue BfModule::GetStringObjectValue(int strId)
  1374. {
  1375. BfIRValue* objValue;
  1376. if (mStringObjectPool.TryGetValue(strId, &objValue))
  1377. return *objValue;
  1378. auto stringPoolEntry = mContext->mStringObjectIdMap[strId];
  1379. return GetStringObjectValue(stringPoolEntry.mString, true);
  1380. }
  1381. BfIRValue BfModule::GetStringObjectValue(const StringImpl& str, bool define)
  1382. {
  1383. auto stringType = ResolveTypeDef(mCompiler->mStringTypeDef, define ? BfPopulateType_Data : BfPopulateType_Declaration);
  1384. mBfIRBuilder->PopulateType(stringType);
  1385. int strId = mContext->GetStringLiteralId(str);
  1386. BfIRValue* irValuePtr = NULL;
  1387. if (!mStringObjectPool.TryAdd(strId, NULL, &irValuePtr))
  1388. return *irValuePtr;
  1389. // If this wasn't in neither dictionary yet, add to mStringPoolRefs
  1390. if (!mStringCharPtrPool.ContainsKey(strId))
  1391. mStringPoolRefs.Add(strId);
  1392. BfIRValue strObject = CreateStringObjectValue(str, strId, define);
  1393. *irValuePtr = strObject;
  1394. mStringPoolRefs.Add(strId);
  1395. return strObject;
  1396. }
  1397. BfIRValue BfModule::CreateGlobalConstValue(const StringImpl& name, BfIRValue constant, BfIRType type, bool external)
  1398. {
  1399. auto newConst = mBfIRBuilder->CreateGlobalVariable(
  1400. type,
  1401. true,
  1402. external ? BfIRLinkageType_External : BfIRLinkageType_Internal,
  1403. constant,
  1404. name.c_str());
  1405. return newConst;
  1406. }
  1407. void BfModule::NewScopeState(bool createLexicalBlock, bool flushValueScope)
  1408. {
  1409. auto curScope = mCurMethodState->mCurScope;
  1410. if (curScope->mLabelNode != NULL)
  1411. curScope->mLabelNode->ToString(curScope->mLabel);
  1412. if (!mCurMethodState->mCurScope->mLabel.IsEmpty())
  1413. {
  1414. auto checkScope = mCurMethodState->mCurScope->mPrevScope;
  1415. while (checkScope != NULL)
  1416. {
  1417. if (checkScope->mLabel == mCurMethodState->mCurScope->mLabel)
  1418. {
  1419. auto errorNode = Fail("Duplicate scope label", curScope->mLabelNode);
  1420. if (errorNode != NULL)
  1421. mCompiler->mPassInstance->MoreInfo("See previous scope label", checkScope->mLabelNode);
  1422. break;
  1423. }
  1424. checkScope = checkScope->mPrevScope;
  1425. }
  1426. }
  1427. auto prevScope = mCurMethodState->mCurScope->mPrevScope;
  1428. if ((flushValueScope) && (prevScope != NULL) && (prevScope->mValueScopeStart))
  1429. {
  1430. if (prevScope->mHadScopeValueRetain)
  1431. mBfIRBuilder->CreateValueScopeSoftEnd(prevScope->mValueScopeStart);
  1432. else
  1433. mBfIRBuilder->CreateValueScopeHardEnd(prevScope->mValueScopeStart);
  1434. }
  1435. mCurMethodState->mBlockNestLevel++;
  1436. if ((createLexicalBlock) && (mBfIRBuilder->DbgHasInfo()) && (mHasFullDebugInfo))
  1437. {
  1438. // DIScope could be NULL if we're in an unspecialized method (for example)
  1439. if (mCurMethodState->mCurScope->mDIScope)
  1440. mCurMethodState->mCurScope->mDIScope = mBfIRBuilder->DbgCreateLexicalBlock(mCurMethodState->mCurScope->mDIScope, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, mCurFilePosition.mCurColumn);
  1441. }
  1442. mCurMethodState->mCurScope->mLocalVarStart = (int)mCurMethodState->mLocals.size();
  1443. mCurMethodState->mCurScope->mBlock = mBfIRBuilder->MaybeChainNewBlock((!mCurMethodState->mCurScope->mLabel.empty()) ? mCurMethodState->mCurScope->mLabel : "newScope");
  1444. }
  1445. void BfModule::RestoreScoreState_LocalVariables()
  1446. {
  1447. while (mCurMethodState->mCurScope->mLocalVarStart < (int)mCurMethodState->mLocals.size())
  1448. {
  1449. auto localVar = mCurMethodState->mLocals.back();
  1450. LocalVariableDone(localVar, false);
  1451. mCurMethodState->mLocals.pop_back();
  1452. if (localVar->mShadowedLocal != NULL)
  1453. {
  1454. BfLocalVarEntry* localVarEntryPtr;
  1455. if (mCurMethodState->mLocalVarSet.TryGet(BfLocalVarEntry(localVar), &localVarEntryPtr))
  1456. {
  1457. localVarEntryPtr->mLocalVar = localVar->mShadowedLocal;
  1458. }
  1459. }
  1460. else
  1461. {
  1462. mCurMethodState->mLocalVarSet.Remove(BfLocalVarEntry(localVar));
  1463. }
  1464. delete localVar;
  1465. }
  1466. }
  1467. void BfModule::RestoreScopeState()
  1468. {
  1469. BfScopeData* prevScopeData = mCurMethodState->mCurScope->mPrevScope;
  1470. mCurMethodState->mBlockNestLevel--;
  1471. if (!mCurMethodState->mCurScope->mAtEndBlocks.empty())
  1472. {
  1473. BfIRBlock afterEndBlock;
  1474. if (!mCurMethodState->mLeftBlockUncond)
  1475. {
  1476. afterEndBlock = mBfIRBuilder->CreateBlock("scopeAfterEnd");
  1477. mBfIRBuilder->CreateBr(afterEndBlock);
  1478. mBfIRBuilder->ClearDebugLocation_Last();
  1479. }
  1480. for (auto preExitBlock : mCurMethodState->mCurScope->mAtEndBlocks)
  1481. mBfIRBuilder->MoveBlockToEnd(preExitBlock);
  1482. if (afterEndBlock)
  1483. {
  1484. mBfIRBuilder->AddBlock(afterEndBlock);
  1485. mBfIRBuilder->SetInsertPoint(afterEndBlock);
  1486. }
  1487. }
  1488. if (!mCurMethodState->mLeftBlockUncond)
  1489. EmitDeferredScopeCalls(true, mCurMethodState->mCurScope);
  1490. RestoreScoreState_LocalVariables();
  1491. if (mCurMethodState->mCurScope->mValueScopeStart)
  1492. mBfIRBuilder->CreateValueScopeHardEnd(mCurMethodState->mCurScope->mValueScopeStart);
  1493. mCurMethodState->mCurScope = prevScopeData;
  1494. mCurMethodState->mTailScope = mCurMethodState->mCurScope;
  1495. }
  1496. BfIRValue BfModule::CreateAlloca(BfType* type, bool addLifetime, const char* name, BfIRValue arraySize)
  1497. {
  1498. if (mBfIRBuilder->mIgnoreWrites)
  1499. return mBfIRBuilder->GetFakeVal();
  1500. BF_ASSERT((*(int8*)&addLifetime == 1) || (*(int8*)&addLifetime == 0));
  1501. mBfIRBuilder->PopulateType(type);
  1502. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  1503. if (!mBfIRBuilder->mIgnoreWrites)
  1504. BF_ASSERT(!prevInsertBlock.IsFake());
  1505. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  1506. BfIRValue allocaInst;
  1507. if (arraySize)
  1508. allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(type), arraySize);
  1509. else
  1510. allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(type));
  1511. mBfIRBuilder->SetAllocaAlignment(allocaInst, type->mAlign);
  1512. mBfIRBuilder->ClearDebugLocation(allocaInst);
  1513. if (name != NULL)
  1514. mBfIRBuilder->SetName(allocaInst, name);
  1515. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  1516. if ((addLifetime) && (WantsLifetimes()))
  1517. {
  1518. auto lifetimeStart = mBfIRBuilder->CreateLifetimeStart(allocaInst);
  1519. mBfIRBuilder->ClearDebugLocation(lifetimeStart);
  1520. mCurMethodState->mCurScope->mDeferredLifetimeEnds.push_back(allocaInst);
  1521. }
  1522. return allocaInst;
  1523. }
  1524. BfIRValue BfModule::CreateAllocaInst(BfTypeInstance* typeInst, bool addLifetime, const char* name)
  1525. {
  1526. if (mBfIRBuilder->mIgnoreWrites)
  1527. return mBfIRBuilder->GetFakeVal();
  1528. BF_ASSERT((*(int8*)&addLifetime == 1) || (*(int8*)&addLifetime == 0));
  1529. mBfIRBuilder->PopulateType(typeInst);
  1530. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  1531. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  1532. auto allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapTypeInst(typeInst));
  1533. mBfIRBuilder->SetAllocaAlignment(allocaInst, typeInst->mInstAlign);
  1534. mBfIRBuilder->ClearDebugLocation(allocaInst);
  1535. if (name != NULL)
  1536. mBfIRBuilder->SetName(allocaInst, name);
  1537. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  1538. if ((addLifetime) && (WantsLifetimes()))
  1539. {
  1540. auto lifetimeStart = mBfIRBuilder->CreateLifetimeStart(allocaInst);
  1541. mBfIRBuilder->ClearDebugLocation(lifetimeStart);
  1542. mCurMethodState->mCurScope->mDeferredLifetimeEnds.push_back(allocaInst);
  1543. }
  1544. return allocaInst;
  1545. }
  1546. void BfModule::AddStackAlloc(BfTypedValue val, BfAstNode* refNode, BfScopeData* scopeData, bool condAlloca, bool mayEscape)
  1547. {
  1548. //This was removed because we want the alloc to be added to the __deferred list if it's actually a "stack"
  1549. // 'stack' in a head scopeData is really the same as 'scopeData', so use the simpler scopeData handling
  1550. /*if (mCurMethodState->mInHeadScope)
  1551. isScopeAlloc = true;*/
  1552. if (scopeData == NULL)
  1553. return;
  1554. auto checkBaseType = val.mType->ToTypeInstance();
  1555. if ((checkBaseType != NULL) && (checkBaseType->IsObject()))
  1556. {
  1557. bool hadDtorCall = false;
  1558. while (checkBaseType != NULL)
  1559. {
  1560. if ((checkBaseType->mTypeDef->mDtorDef != NULL) /*&& (checkBaseType != mContext->mBfObjectType)*/)
  1561. {
  1562. bool isDynAlloc = (scopeData != NULL) && (mCurMethodState->mCurScope->IsDyn(scopeData));
  1563. auto dtorMethodInstance = GetMethodInstance(checkBaseType, checkBaseType->mTypeDef->mDtorDef, BfTypeVector());
  1564. BfIRValue useVal = val.mValue;
  1565. useVal = mBfIRBuilder->CreateBitCast(val.mValue, mBfIRBuilder->MapTypeInstPtr(checkBaseType));
  1566. if (isDynAlloc)
  1567. {
  1568. //
  1569. }
  1570. else if (condAlloca)
  1571. {
  1572. BF_ASSERT(!IsTargetingBeefBackend());
  1573. BF_ASSERT(!isDynAlloc);
  1574. auto valPtr = CreateAlloca(checkBaseType);
  1575. mBfIRBuilder->CreateStore(useVal, valPtr);
  1576. useVal = valPtr;
  1577. }
  1578. SizedArray<BfIRValue, 1> llvmArgs;
  1579. llvmArgs.push_back(useVal);
  1580. auto deferredCall = AddDeferredCall(dtorMethodInstance, llvmArgs, scopeData, refNode, true);
  1581. if (deferredCall != NULL)
  1582. {
  1583. deferredCall->mCastThis = (val.mType != checkBaseType) && (!isDynAlloc);
  1584. if (condAlloca)
  1585. deferredCall->mArgsNeedLoad = true;
  1586. }
  1587. hadDtorCall = true;
  1588. break;
  1589. }
  1590. checkBaseType = checkBaseType->mBaseType;
  1591. }
  1592. return;
  1593. }
  1594. //TODO: In the future we could be smarter about statically determining that our value hasn't escaped and eliding this
  1595. if (mayEscape)
  1596. {
  1597. // Is this worth it?
  1598. // if ((!IsOptimized()) && (val.mType->IsComposite()) && (!val.mType->IsValuelessType()) && (!mBfIRBuilder->mIgnoreWrites) && (!mCompiler->mIsResolveOnly))
  1599. // {
  1600. // auto nullPtrType = GetPrimitiveType(BfTypeCode_NullPtr);
  1601. // bool isDyn = mCurMethodState->mCurScope->IsDyn(scopeData);
  1602. // if (!isDyn)
  1603. // {
  1604. // int clearSize = val.mType->mSize;
  1605. // BfModuleMethodInstance dtorMethodInstance = GetInternalMethod("MemSet");
  1606. // BF_ASSERT(dtorMethodInstance.mMethodInstance != NULL);
  1607. // SizedArray<BfIRValue, 1> llvmArgs;
  1608. // llvmArgs.push_back(mBfIRBuilder->CreateBitCast(val.mValue, mBfIRBuilder->MapType(nullPtrType)));
  1609. // llvmArgs.push_back(GetConstValue8(0xDD));
  1610. // llvmArgs.push_back(GetConstValue(clearSize));
  1611. // llvmArgs.push_back(GetConstValue32(val.mType->mAlign));
  1612. // llvmArgs.push_back(mBfIRBuilder->CreateConst(BfTypeCode_Boolean, 0));
  1613. // AddDeferredCall(dtorMethodInstance, llvmArgs, scopeData, refNode, true);
  1614. // }
  1615. // else
  1616. // {
  1617. // const char* funcName = "SetDeleted1";
  1618. // if (val.mType->mSize >= 16)
  1619. // funcName = "SetDeleted16";
  1620. // else if (val.mType->mSize >= 8)
  1621. // funcName = "SetDeleted8";
  1622. // else if (val.mType->mSize >= 4)
  1623. // funcName = "SetDeleted4";
  1624. //
  1625. // BfModuleMethodInstance dtorMethodInstance = GetInternalMethod(funcName);
  1626. // BF_ASSERT(dtorMethodInstance.mMethodInstance != NULL);
  1627. // SizedArray<BfIRValue, 1> llvmArgs;
  1628. // llvmArgs.push_back(mBfIRBuilder->CreateBitCast(val.mValue, mBfIRBuilder->MapType(nullPtrType)));
  1629. // AddDeferredCall(dtorMethodInstance, llvmArgs, scopeData, refNode, true);
  1630. // }
  1631. // }
  1632. }
  1633. }
  1634. bool BfModule::TryLocalVariableInit(BfLocalVariable* localVar)
  1635. {
  1636. auto startTypeInstance = localVar->mResolvedType->ToTypeInstance();
  1637. if ((startTypeInstance == NULL) || (!startTypeInstance->IsStruct()))
  1638. return false;
  1639. auto checkTypeInstance = startTypeInstance;
  1640. while (checkTypeInstance != NULL)
  1641. {
  1642. for (auto& fieldInstance : checkTypeInstance->mFieldInstances)
  1643. {
  1644. if (fieldInstance.mMergedDataIdx != -1)
  1645. {
  1646. int64 checkMask = (int64)1 << fieldInstance.mMergedDataIdx;
  1647. if ((localVar->mUnassignedFieldFlags & checkMask) != 0)
  1648. {
  1649. // For fields added in extensions, we automatically initialize those if necessary
  1650. auto fieldDef = fieldInstance.GetFieldDef();
  1651. if (!fieldDef->mDeclaringType->IsExtension())
  1652. return false;
  1653. if ((fieldInstance.mDataIdx != -1) && (!mBfIRBuilder->mIgnoreWrites) && (!mCompiler->mIsResolveOnly))
  1654. {
  1655. auto curInsertBlock = mBfIRBuilder->GetInsertBlock();
  1656. mBfIRBuilder->SaveDebugLocation();
  1657. if (localVar->IsParam())
  1658. mBfIRBuilder->SetInsertPointAtStart(mCurMethodState->mIRInitBlock);
  1659. else
  1660. {
  1661. BF_ASSERT(localVar->mDeclBlock);
  1662. mBfIRBuilder->SetInsertPointAtStart(localVar->mDeclBlock);
  1663. }
  1664. mBfIRBuilder->ClearDebugLocation();
  1665. BfIRValue curVal;
  1666. if (localVar->mIsThis)
  1667. curVal = mBfIRBuilder->GetArgument(0);
  1668. else
  1669. curVal = localVar->mAddr;
  1670. auto subTypeInstance = startTypeInstance;
  1671. while (subTypeInstance != checkTypeInstance)
  1672. {
  1673. curVal = mBfIRBuilder->CreateInBoundsGEP(curVal, 0, 0);
  1674. subTypeInstance = subTypeInstance->mBaseType;
  1675. }
  1676. auto fieldPtr = mBfIRBuilder->CreateInBoundsGEP(curVal, 0, fieldInstance.mDataIdx);
  1677. auto defVal = GetDefaultValue(fieldInstance.mResolvedType);
  1678. auto storeInst = mBfIRBuilder->CreateStore(defVal, fieldPtr);
  1679. mBfIRBuilder->SetInsertPoint(curInsertBlock);
  1680. mBfIRBuilder->RestoreDebugLocation();
  1681. }
  1682. localVar->mUnassignedFieldFlags &= ~checkMask;
  1683. if (localVar->mUnassignedFieldFlags == 0)
  1684. localVar->mIsAssigned = true;
  1685. }
  1686. }
  1687. }
  1688. checkTypeInstance = checkTypeInstance->mBaseType;
  1689. }
  1690. return localVar->mIsAssigned;
  1691. }
  1692. void BfModule::LocalVariableDone(BfLocalVariable* localVar, bool isMethodExit)
  1693. {
  1694. //if (localVar->mAddr == NULL)
  1695. /*if ((localVar->mValue) && (!localVar->mAddr) && (IsTargetingBeefBackend()))
  1696. {
  1697. if ((!localVar->mValue.IsConst()) && (!localVar->mValue.IsArg()) && (!localVar->mValue.IsFake()))
  1698. {
  1699. if (mCurMethodInstance->mMethodDef->mName == "FuncA")
  1700. mBfIRBuilder->CreateLifetimeEnd(localVar->mValue);
  1701. }
  1702. }*/
  1703. BfAstNode* localNameNode = localVar->mNameNode;
  1704. if (localVar->mIsThis)
  1705. {
  1706. localNameNode = mCurMethodInstance->mMethodDef->GetRefNode();
  1707. }
  1708. if (localNameNode != NULL)
  1709. {
  1710. bool isOut = false;
  1711. if (localVar->mResolvedType->IsRef())
  1712. {
  1713. auto refType = (BfRefType*)localVar->mResolvedType;
  1714. isOut = refType->mRefKind == BfRefType::RefKind_Out;
  1715. }
  1716. if ((localVar->mReadFromId == -1) || (isOut) || ((localVar->mIsThis) && (mCurTypeInstance->IsStruct())))
  1717. {
  1718. if ((!localVar->mIsAssigned) & (localVar->IsParam()))
  1719. TryLocalVariableInit(localVar);
  1720. // We may skip processing of local methods, so we won't know if it bind to any of our local variables or not
  1721. bool deferFullAnalysis = mCurMethodState->GetRootMethodState()->mLocalMethodCache.size() != 0;
  1722. //bool deferFullAnalysis = true;
  1723. bool deferUsageWarning = deferFullAnalysis && mCompiler->IsAutocomplete();
  1724. if (!localVar->mIsAssigned)
  1725. {
  1726. if (deferUsageWarning)
  1727. {
  1728. // Ignore
  1729. }
  1730. else if (localVar->mIsThis)
  1731. {
  1732. bool foundFields = false;
  1733. auto checkTypeInstance = mCurTypeInstance;
  1734. while (checkTypeInstance != NULL)
  1735. {
  1736. for (auto& fieldInstance : checkTypeInstance->mFieldInstances)
  1737. {
  1738. if (fieldInstance.mMergedDataIdx != -1)
  1739. {
  1740. int checkMask = 1 << fieldInstance.mMergedDataIdx;
  1741. if ((localVar->mUnassignedFieldFlags & checkMask) != 0)
  1742. {
  1743. auto fieldDef = fieldInstance.GetFieldDef();
  1744. if (fieldDef->mProtection != BfProtection_Hidden)
  1745. {
  1746. if (checkTypeInstance == mCurTypeInstance)
  1747. {
  1748. Fail(StrFormat("Field '%s' must be fully assigned before control is returned to the caller",
  1749. fieldDef->mName.c_str()), localNameNode, deferFullAnalysis); // 0171
  1750. }
  1751. else
  1752. {
  1753. Fail(StrFormat("Field '%s.%s' must be fully assigned before control is returned to the caller",
  1754. TypeToString(checkTypeInstance).c_str(),
  1755. fieldDef->mName.c_str()), localNameNode, deferFullAnalysis); // 0171
  1756. }
  1757. }
  1758. foundFields = true;
  1759. }
  1760. }
  1761. }
  1762. checkTypeInstance = checkTypeInstance->mBaseType;
  1763. }
  1764. if (!foundFields)
  1765. {
  1766. if (mCurTypeInstance->mInstSize > 0)
  1767. Fail(StrFormat("The variable '%s' must be fully assigned to before control leaves the current method", localVar->mName.c_str()), localNameNode); // 0177
  1768. }
  1769. }
  1770. else if (localVar->IsParam())
  1771. Fail(StrFormat("The out parameter '%s' must be assigned to before control leaves the current method", localVar->mName.c_str()), localNameNode, deferFullAnalysis); // 0177
  1772. else if (!deferUsageWarning)
  1773. Warn(BfWarning_CS0168_VariableDeclaredButNeverUsed, StrFormat("The variable '%s' is declared but never used", localVar->mName.c_str()), localNameNode, deferFullAnalysis);
  1774. }
  1775. else if ((localVar->mReadFromId == -1) && (!localVar->IsParam()) && (!deferUsageWarning))
  1776. Warn(BfWarning_CS0168_VariableDeclaredButNeverUsed, StrFormat("The variable '%s' is assigned but its value is never used", localVar->mName.c_str()), localNameNode, deferFullAnalysis);
  1777. }
  1778. }
  1779. }
  1780. void BfModule::MarkDynStack(BfScopeData* scopeData)
  1781. {
  1782. auto checkScope = mCurMethodState->mCurScope;
  1783. while (true)
  1784. {
  1785. if (checkScope == scopeData)
  1786. break;
  1787. checkScope->mHadOuterDynStack = true;
  1788. checkScope = checkScope->mPrevScope;
  1789. }
  1790. }
  1791. void BfModule::SaveStackState(BfScopeData* scopeData)
  1792. {
  1793. // If we push a value on the stack that needs to survive until the end of scopeData, we need to make sure that no
  1794. // scopes within scopeData restore the stack
  1795. auto checkScope = mCurMethodState->mCurScope;
  1796. while (true)
  1797. {
  1798. if (checkScope == scopeData)
  1799. {
  1800. if ((!checkScope->mSavedStack) && (checkScope->mBlock) && (!checkScope->mIsScopeHead) && (!checkScope->mHadOuterDynStack))
  1801. {
  1802. if (mBfIRBuilder->mHasDebugInfo)
  1803. mBfIRBuilder->SaveDebugLocation();
  1804. auto prevPos = mBfIRBuilder->GetInsertBlock();
  1805. mBfIRBuilder->SetInsertPointAtStart(checkScope->mBlock);
  1806. checkScope->mSavedStack = mBfIRBuilder->CreateStackSave();
  1807. mBfIRBuilder->ClearDebugLocation(checkScope->mSavedStack);
  1808. mBfIRBuilder->SetInsertPoint(prevPos);
  1809. if (mBfIRBuilder->mHasDebugInfo)
  1810. mBfIRBuilder->RestoreDebugLocation();
  1811. }
  1812. break;
  1813. }
  1814. if (checkScope->mSavedStack)
  1815. {
  1816. for (auto usage : checkScope->mSavedStackUses)
  1817. mBfIRBuilder->EraseInstFromParent(usage);
  1818. checkScope->mSavedStackUses.Clear();
  1819. mBfIRBuilder->EraseInstFromParent(checkScope->mSavedStack);
  1820. checkScope->mSavedStack = BfIRValue();
  1821. }
  1822. checkScope = checkScope->mPrevScope;
  1823. }
  1824. }
  1825. BfIRValue BfModule::ValueScopeStart()
  1826. {
  1827. if (IsTargetingBeefBackend())
  1828. return mBfIRBuilder->CreateValueScopeStart();
  1829. return BfIRValue();
  1830. }
  1831. void BfModule::ValueScopeEnd(BfIRValue valueScopeStart)
  1832. {
  1833. if (valueScopeStart)
  1834. mBfIRBuilder->CreateValueScopeHardEnd(valueScopeStart);
  1835. }
  1836. BfFileInstance* BfModule::GetFileFromNode(BfAstNode* astNode)
  1837. {
  1838. auto bfParser = astNode->GetSourceData()->ToParserData();
  1839. if (bfParser == NULL)
  1840. return NULL;
  1841. BfFileInstance** fileInstancePtr = NULL;
  1842. if (!mFileInstanceMap.TryAdd(bfParser, NULL, &fileInstancePtr))
  1843. {
  1844. return *fileInstancePtr;
  1845. }
  1846. else
  1847. {
  1848. // It's possible two parsers have the same file name (ie: mNextRevision)
  1849. BfFileInstance** namedFileInstancePtr = NULL;
  1850. if (!mNamedFileInstanceMap.TryAdd(bfParser->mFileName, NULL, &namedFileInstancePtr))
  1851. {
  1852. auto bfFileInstance = *namedFileInstancePtr;
  1853. *fileInstancePtr = bfFileInstance;
  1854. return bfFileInstance;
  1855. }
  1856. int slashPos = (int)bfParser->mFileName.LastIndexOf(DIR_SEP_CHAR);
  1857. auto bfFileInstance = new BfFileInstance();
  1858. *fileInstancePtr = bfFileInstance;
  1859. *namedFileInstancePtr = bfFileInstance;
  1860. bfFileInstance->mPrevPosition.mFileInstance = bfFileInstance;
  1861. bfFileInstance->mParser = bfParser;
  1862. BfLogSysM("GetFileFromNode new file. Mod: %p FileInstance: %p Parser: %p\n", this, bfFileInstance, bfParser);
  1863. if ((mBfIRBuilder != NULL) && (mBfIRBuilder->DbgHasInfo()))
  1864. {
  1865. String fileName = bfParser->mFileName;
  1866. for (int i = 0; i < (int)fileName.length(); i++)
  1867. {
  1868. if (fileName[i] == DIR_SEP_CHAR_ALT)
  1869. fileName[i] = DIR_SEP_CHAR;
  1870. }
  1871. bfFileInstance->mDIFile = mBfIRBuilder->DbgCreateFile(fileName.Substring(slashPos + 1), fileName.Substring(0, slashPos));
  1872. }
  1873. return bfFileInstance;
  1874. }
  1875. }
  1876. void BfModule::UpdateSrcPos(BfAstNode* astNode, BfSrcPosFlags flags, int debugLocOffset)
  1877. {
  1878. // We set force to true when we MUST get the line position set (for navigation purposes, for example)
  1879. if (((mBfIRBuilder->mIgnoreWrites)) && ((flags & BfSrcPosFlag_Force) == 0))
  1880. return;
  1881. BF_ASSERT((!mAwaitingInitFinish) || (mBfIRBuilder->mIgnoreWrites));
  1882. if (astNode == NULL)
  1883. return;
  1884. auto bfParser = astNode->GetSourceData()->ToParserData();
  1885. if (bfParser == NULL)
  1886. return;
  1887. if ((mCurFilePosition.mFileInstance == NULL) || (mCurFilePosition.mFileInstance->mParser != bfParser))
  1888. {
  1889. if (mCurFilePosition.mFileInstance != NULL)
  1890. {
  1891. BF_ASSERT(mFileInstanceMap.GetCount() != 0);
  1892. mCurFilePosition.mFileInstance->mPrevPosition = mCurFilePosition;
  1893. }
  1894. auto bfFileInstance = GetFileFromNode(astNode);
  1895. if (bfFileInstance->mPrevPosition.mFileInstance != NULL)
  1896. {
  1897. mCurFilePosition = bfFileInstance->mPrevPosition;
  1898. }
  1899. else
  1900. {
  1901. mCurFilePosition.mFileInstance = bfFileInstance;
  1902. mCurFilePosition.mCurLine = 0;
  1903. mCurFilePosition.mCurSrcPos = 0;
  1904. }
  1905. }
  1906. int srcPos = astNode->GetSrcStart() + debugLocOffset;
  1907. BF_ASSERT(srcPos < bfParser->mSrcLength);
  1908. auto* jumpEntry = bfParser->mJumpTable + (srcPos / PARSER_JUMPTABLE_DIVIDE);
  1909. if (jumpEntry->mCharIdx > srcPos)
  1910. jumpEntry--;
  1911. mCurFilePosition.mCurLine = jumpEntry->mLineNum;
  1912. mCurFilePosition.mCurSrcPos = jumpEntry->mCharIdx;
  1913. mCurFilePosition.mCurColumn = 0;
  1914. while (mCurFilePosition.mCurSrcPos < srcPos)
  1915. {
  1916. if (bfParser->mSrc[mCurFilePosition.mCurSrcPos] == '\n')
  1917. {
  1918. mCurFilePosition.mCurLine++;
  1919. mCurFilePosition.mCurColumn = 0;
  1920. }
  1921. else
  1922. {
  1923. mCurFilePosition.mCurColumn++;
  1924. }
  1925. mCurFilePosition.mCurSrcPos++;
  1926. }
  1927. //TODO: if we bail on the "mCurMethodState == NULL" case then we don't get it set during type declarations
  1928. if (((flags & BfSrcPosFlag_NoSetDebugLoc) == 0) && (mBfIRBuilder->DbgHasInfo()) && (mCurMethodState != NULL))
  1929. {
  1930. int column = mCurFilePosition.mCurColumn + 1;
  1931. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend))
  1932. {
  1933. // Set to illegal position
  1934. column = 0;
  1935. }
  1936. if (mSetIllegalSrcPosition)
  1937. column = 0;
  1938. BfIRMDNode useDIScope = mCurMethodState->mCurScope->mDIScope;
  1939. auto wantDIFile = mCurFilePosition.mFileInstance->mDIFile;
  1940. if ((wantDIFile != mCurMethodState->mDIFile) && (mCurMethodState->mDIFile))
  1941. {
  1942. // This is from a different scope...
  1943. if (wantDIFile != mCurMethodState->mCurScope->mAltDIFile)
  1944. {
  1945. mCurMethodState->mCurScope->mAltDIFile = wantDIFile;
  1946. mCurMethodState->mCurScope->mAltDIScope = mBfIRBuilder->DbgCreateLexicalBlock(mCurMethodState->mCurScope->mDIScope, wantDIFile, mCurFilePosition.mCurLine + 1, column);
  1947. }
  1948. if (mCurMethodState->mCurScope->mAltDIScope) // This may not be set if mAltDIFile is set by a mixin
  1949. useDIScope = mCurMethodState->mCurScope->mAltDIScope;
  1950. }
  1951. else
  1952. {
  1953. if (mCurMethodState->mCurScope->mAltDIFile)
  1954. {
  1955. mCurMethodState->mCurScope->mAltDIFile = BfIRMDNode();
  1956. mCurMethodState->mCurScope->mAltDIScope = BfIRMDNode();
  1957. }
  1958. }
  1959. auto inlineAt = mCurMethodState->mCurScope->mDIInlinedAt;
  1960. if (mCurMethodState->mCrossingMixin)
  1961. inlineAt = BfIRMDNode();
  1962. mBfIRBuilder->SetCurrentDebugLocation(mCurFilePosition.mCurLine + 1, column, useDIScope, inlineAt);
  1963. if ((flags & BfSrcPosFlag_Expression) == 0)
  1964. mBfIRBuilder->CreateStatementStart();
  1965. }
  1966. }
  1967. void BfModule::UpdateExprSrcPos(BfAstNode* astNode, BfSrcPosFlags flags)
  1968. {
  1969. // We've turned off expr src pos (for now?)
  1970. //UpdateSrcPos(astNode, (BfSrcPosFlags)(flags | BfSrcPosFlag_Expression));
  1971. }
  1972. void BfModule::UseDefaultSrcPos(BfSrcPosFlags flags, int debugLocOffset)
  1973. {
  1974. UpdateSrcPos(mCompiler->mBfObjectTypeDef->mTypeDeclaration, flags, debugLocOffset);
  1975. }
  1976. void BfModule::SetIllegalSrcPos(BfSrcPosFlags flags)
  1977. {
  1978. if ((mBfIRBuilder->DbgHasInfo()) && (mCurMethodState != NULL))
  1979. {
  1980. if ((mCurMethodState->mCurScope->mDIInlinedAt) && (mCompiler->mOptions.IsCodeView()))
  1981. {
  1982. // Currently, CodeView does not record column positions so we can't use an illegal column position as an "invalid" marker
  1983. mBfIRBuilder->SetCurrentDebugLocation(0, 0, mCurMethodState->mCurScope->mDIScope, mCurMethodState->mCurScope->mDIInlinedAt);
  1984. }
  1985. else
  1986. {
  1987. // Set to whatever it previously was but at column zero, which we will know to be illegal
  1988. mBfIRBuilder->SetCurrentDebugLocation(mCurFilePosition.mCurLine + 1, 0, mCurMethodState->mCurScope->mDIScope, mCurMethodState->mCurScope->mDIInlinedAt);
  1989. }
  1990. if ((flags & BfSrcPosFlag_Expression) == 0)
  1991. mBfIRBuilder->CreateStatementStart();
  1992. }
  1993. }
  1994. void BfModule::SetIllegalExprSrcPos(BfSrcPosFlags flags)
  1995. {
  1996. // We've turned off expr src pos (for now?)
  1997. //SetIllegalSrcPos((BfSrcPosFlags)(flags | BfSrcPosFlag_Expression));
  1998. }
  1999. bool BfModule::CheckProtection(BfProtection protection, bool allowProtected, bool allowPrivate)
  2000. {
  2001. if ((protection == BfProtection_Public) ||
  2002. ((protection == BfProtection_Protected) && (allowProtected)) ||
  2003. ((protection == BfProtection_Private) && (allowPrivate)))
  2004. return true;
  2005. if ((mAttributeState != NULL) && (mAttributeState->mCustomAttributes != NULL) && (mAttributeState->mCustomAttributes->Contains(mCompiler->mFriendAttributeTypeDef)))
  2006. return true;
  2007. return false;
  2008. }
  2009. void BfModule::GetAccessAllowed(BfTypeInstance* checkType, bool &allowProtected, bool &allowPrivate)
  2010. {
  2011. allowPrivate = (checkType == mCurTypeInstance) || (IsInnerType(mCurTypeInstance, checkType));
  2012. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL))
  2013. {
  2014. auto mixinOwner = mCurMethodState->mMixinState->mMixinMethodInstance->GetOwner();
  2015. allowPrivate |= (checkType == mixinOwner) || (IsInnerType(mixinOwner, checkType));
  2016. }
  2017. allowProtected = allowPrivate;
  2018. }
  2019. bool BfModule::CheckProtection(BfProtectionCheckFlags& flags, BfTypeInstance* memberOwner, BfProtection memberProtection, BfTypeInstance* lookupStartType)
  2020. {
  2021. if (memberProtection == BfProtection_Hidden)
  2022. return false;
  2023. if (memberProtection == BfProtection_Public)
  2024. return true;
  2025. if ((flags & BfProtectionCheckFlag_CheckedPrivate) == 0)
  2026. {
  2027. BfTypeInstance* curCheckType = mCurTypeInstance;
  2028. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL))
  2029. {
  2030. auto mixinOwner = mCurMethodState->mMixinState->mMixinMethodInstance->GetOwner();
  2031. curCheckType = mixinOwner;
  2032. }
  2033. bool allowPrivate = (memberOwner->mTypeDef == curCheckType->mTypeDef) || (IsInnerType(curCheckType->mTypeDef, memberOwner->mTypeDef));
  2034. if (allowPrivate)
  2035. flags = (BfProtectionCheckFlags)(flags | BfProtectionCheckFlag_AllowPrivate | BfProtectionCheckFlag_CheckedPrivate);
  2036. else
  2037. flags = (BfProtectionCheckFlags)(flags | BfProtectionCheckFlag_CheckedPrivate);
  2038. }
  2039. if ((flags & BfProtectionCheckFlag_AllowPrivate) != 0)
  2040. return true;
  2041. if (memberProtection == BfProtection_Protected)
  2042. {
  2043. if ((flags & BfProtectionCheckFlag_CheckedProtected) == 0)
  2044. {
  2045. bool allowProtected = false;
  2046. auto memberOwnerTypeDef = memberOwner->mTypeDef;
  2047. auto curCheckType = mCurTypeInstance;
  2048. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL))
  2049. {
  2050. auto mixinOwner = mCurMethodState->mMixinState->mMixinMethodInstance->GetOwner();
  2051. curCheckType = mixinOwner;
  2052. }
  2053. auto lookupCheckType = lookupStartType;
  2054. while (lookupCheckType->mInheritDepth >= curCheckType->mInheritDepth)
  2055. {
  2056. if (lookupCheckType == curCheckType)
  2057. {
  2058. allowProtected = true;
  2059. break;
  2060. }
  2061. if (lookupCheckType == memberOwner)
  2062. break;
  2063. lookupCheckType = lookupCheckType->mBaseType;
  2064. if (lookupCheckType == NULL)
  2065. break;
  2066. }
  2067. if (!allowProtected)
  2068. {
  2069. // It's possible our outer type is derived from 'memberOwner'
  2070. while (curCheckType->mTypeDef->mNestDepth > 0)
  2071. {
  2072. curCheckType = GetOuterType(curCheckType);
  2073. if (curCheckType == NULL)
  2074. break;
  2075. auto lookupCheckType = lookupStartType;
  2076. while (lookupCheckType->mInheritDepth >= curCheckType->mInheritDepth)
  2077. {
  2078. if (lookupCheckType == curCheckType)
  2079. {
  2080. allowProtected = true;
  2081. break;
  2082. }
  2083. if (lookupCheckType == memberOwner)
  2084. break;
  2085. lookupCheckType = lookupCheckType->mBaseType;
  2086. if (lookupCheckType == NULL)
  2087. break;
  2088. }
  2089. }
  2090. }
  2091. if (allowProtected)
  2092. flags = (BfProtectionCheckFlags)(flags | BfProtectionCheckFlag_CheckedProtected | BfProtectionCheckFlag_AllowProtected);
  2093. else
  2094. flags = (BfProtectionCheckFlags)(flags | BfProtectionCheckFlag_CheckedProtected);
  2095. }
  2096. if ((flags & BfProtectionCheckFlag_AllowProtected) != 0)
  2097. return true;
  2098. }
  2099. if ((mAttributeState != NULL) && (mAttributeState->mCustomAttributes != NULL) && (mAttributeState->mCustomAttributes->Contains(mCompiler->mFriendAttributeTypeDef)))
  2100. return true;
  2101. return false;
  2102. }
  2103. void BfModule::SetElementType(BfAstNode* astNode, BfSourceElementType elementType)
  2104. {
  2105. if ((mCompiler->mResolvePassData != NULL) &&
  2106. (mCompiler->mResolvePassData->mSourceClassifier != NULL) &&
  2107. (astNode->IsFromParser( mCompiler->mResolvePassData->mParser)))
  2108. {
  2109. mCompiler->mResolvePassData->mSourceClassifier->SetElementType(astNode, elementType);
  2110. }
  2111. }
  2112. BfError* BfModule::Fail(const StringImpl& error, BfAstNode* refNode, bool isPersistent)
  2113. {
  2114. BP_ZONE("BfModule::Fail");
  2115. if (mIgnoreErrors)
  2116. {
  2117. return NULL;
  2118. }
  2119. if (!mReportErrors)
  2120. {
  2121. mCompiler->mPassInstance->SilentFail();
  2122. return NULL;
  2123. }
  2124. if (refNode != NULL)
  2125. refNode = BfNodeToNonTemporary(refNode);
  2126. //BF_ASSERT(refNode != NULL);
  2127. if (mCurMethodInstance != NULL)
  2128. mCurMethodInstance->mHasFailed = true;
  2129. if ((mCurTypeInstance != NULL) && (mCurTypeInstance->IsUnspecializedTypeVariation()))
  2130. return NULL;
  2131. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mIsUnspecializedVariation))
  2132. return NULL; // Ignore errors on unspecialized variations, they are always dups
  2133. if (!mHadBuildError)
  2134. mHadBuildError = true;
  2135. if (mParentModule != NULL)
  2136. mParentModule->mHadBuildError = true;
  2137. if (mCurTypeInstance != NULL)
  2138. AddFailType(mCurTypeInstance);
  2139. BfLogSysM("BfModule::Fail module %p type %p %s\n", this, mCurTypeInstance, error.c_str());
  2140. String errorString = error;
  2141. bool isWhileSpecializing = false;
  2142. bool isWhileSpecializingMethod = false;
  2143. if ((mIsSpecialModule) && (mModuleName == "vdata"))
  2144. errorString += StrFormat("\n while generating vdata for project '%s'", mProject->mName.c_str());
  2145. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend))
  2146. errorString += StrFormat("\n while generating append size calculating method");
  2147. else if (refNode == NULL)
  2148. {
  2149. if (mCurTypeInstance != NULL)
  2150. errorString += StrFormat("\n while compiling '%s'", TypeToString(mCurTypeInstance, BfTypeNameFlags_None).c_str());
  2151. else if (mProject != NULL)
  2152. errorString += StrFormat("\n while compiling project '%s'", mProject->mName.c_str());
  2153. }
  2154. if (mCurTypeInstance != NULL)
  2155. {
  2156. auto _CheckMethodInstance = [&](BfMethodInstance* methodInstance)
  2157. {
  2158. // Propogatea the fail all the way to the main method (assuming we're in a local method or lambda)
  2159. methodInstance->mHasFailed = true;
  2160. bool isSpecializedMethod = ((methodInstance != NULL) && (!methodInstance->mIsUnspecialized) && (methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mMethodGenericArguments.size() != 0));
  2161. if (isSpecializedMethod)
  2162. {
  2163. //auto unspecializedMethod = &mCurMethodInstance->mMethodInstanceGroup->mMethodSpecializationMap.begin()->second;
  2164. auto unspecializedMethod = methodInstance->mMethodInstanceGroup->mDefault;
  2165. if (unspecializedMethod->mHasFailed)
  2166. return false; // At least SOME error has already been reported
  2167. }
  2168. if (isSpecializedMethod)
  2169. {
  2170. errorString += StrFormat("\n while specializing method '%s'", MethodToString(methodInstance).c_str());
  2171. isWhileSpecializing = true;
  2172. isWhileSpecializingMethod = true;
  2173. }
  2174. else if ((methodInstance != NULL) && (methodInstance->mIsForeignMethodDef))
  2175. {
  2176. errorString += StrFormat("\n while implementing default interface method '%s'", MethodToString(methodInstance).c_str());
  2177. isWhileSpecializing = true;
  2178. isWhileSpecializingMethod = true;
  2179. }
  2180. else if ((mCurTypeInstance->IsGenericTypeInstance()) && (!mCurTypeInstance->IsUnspecializedType()))
  2181. {
  2182. errorString += StrFormat("\n while specializing type '%s'", TypeToString(mCurTypeInstance).c_str());
  2183. isWhileSpecializing = true;
  2184. }
  2185. return true;
  2186. };
  2187. if (mCurMethodState != NULL)
  2188. {
  2189. auto checkMethodState = mCurMethodState;
  2190. while (checkMethodState != NULL)
  2191. {
  2192. auto methodInstance = checkMethodState->mMethodInstance;
  2193. if (methodInstance == NULL)
  2194. {
  2195. checkMethodState = checkMethodState->mPrevMethodState;
  2196. continue;
  2197. }
  2198. if (!_CheckMethodInstance(methodInstance))
  2199. return NULL;
  2200. checkMethodState = checkMethodState->mPrevMethodState;
  2201. }
  2202. }
  2203. else if (mCurMethodInstance != NULL)
  2204. {
  2205. if (!_CheckMethodInstance(mCurMethodInstance))
  2206. return NULL;
  2207. }
  2208. // Keep in mind that all method specializations with generic type instances as its method generic params
  2209. // need to be deferred because the specified generic type instance might get deleted at the end of the
  2210. // compilation due to no longer having indirect references removed, and we have to ignore errors from
  2211. // those method specializations if that occurs
  2212. if (isWhileSpecializing)
  2213. {
  2214. BfError* bfError = mCompiler->mPassInstance->DeferFail(errorString, refNode);
  2215. if (bfError != NULL)
  2216. bfError->mIsWhileSpecializing = isWhileSpecializing;
  2217. return bfError;
  2218. }
  2219. }
  2220. if ((!isWhileSpecializing) && (mCurTypeInstance != NULL) && ((mCurTypeInstance->IsGenericTypeInstance()) && (!mCurTypeInstance->IsUnspecializedType())))
  2221. {
  2222. errorString += StrFormat("\n while specializing type '%s'", TypeToString(mCurTypeInstance).c_str());
  2223. isWhileSpecializing = true;
  2224. }
  2225. if (!mHadBuildError)
  2226. mHadBuildError = true;
  2227. // Check mixins
  2228. {
  2229. auto checkMethodInstance = mCurMethodState;
  2230. while (checkMethodInstance != NULL)
  2231. {
  2232. auto rootMixinState = checkMethodInstance->GetRootMixinState();
  2233. if (rootMixinState != NULL)
  2234. {
  2235. BfError* bfError = mCompiler->mPassInstance->Fail(StrFormat("Failed to inject mixin '%s'", MethodToString(rootMixinState->mMixinMethodInstance).c_str()), rootMixinState->mSource);
  2236. mCompiler->mPassInstance->MoreInfo(errorString, refNode);
  2237. auto mixinState = checkMethodInstance->mMixinState;
  2238. while ((mixinState != NULL) && (mixinState->mPrevMixinState != NULL))
  2239. {
  2240. mCompiler->mPassInstance->MoreInfo(StrFormat("Injected from mixin '%s'", MethodToString(mixinState->mPrevMixinState->mMixinMethodInstance).c_str()), mixinState->mSource);
  2241. mixinState = mixinState->mPrevMixinState;
  2242. }
  2243. return bfError;
  2244. }
  2245. checkMethodInstance = checkMethodInstance->mPrevMethodState;
  2246. }
  2247. }
  2248. BfError* bfError = NULL;
  2249. if (refNode == NULL)
  2250. bfError = mCompiler->mPassInstance->Fail(errorString);
  2251. else
  2252. {
  2253. bfError = mCompiler->mPassInstance->Fail(errorString, refNode);
  2254. }
  2255. if (bfError != NULL)
  2256. {
  2257. bfError->mIsPersistent = isPersistent;
  2258. bfError->mIsWhileSpecializing = isWhileSpecializing;
  2259. if ((mCurMethodState != NULL) && (mCurMethodState->mDeferredCallEmitState != NULL) && (mCurMethodState->mDeferredCallEmitState->mCloseNode != NULL))
  2260. mCompiler->mPassInstance->MoreInfo("Error during deferred statement handling", mCurMethodState->mDeferredCallEmitState->mCloseNode);
  2261. }
  2262. return bfError;
  2263. }
  2264. BfError* BfModule::FailAfter(const StringImpl& error, BfAstNode* refNode)
  2265. {
  2266. if (mIgnoreErrors)
  2267. return NULL;
  2268. if (refNode != NULL)
  2269. refNode = BfNodeToNonTemporary(refNode);
  2270. mHadBuildError = true;
  2271. return mCompiler->mPassInstance->FailAfter(error, refNode);
  2272. }
  2273. BfError* BfModule::Warn(int warningNum, const StringImpl& warning, BfAstNode* refNode, bool isPersistent)
  2274. {
  2275. if (mIgnoreErrors || mIgnoreWarnings)
  2276. return NULL;
  2277. if (!mReportErrors)
  2278. {
  2279. mCompiler->mPassInstance->SilentFail();
  2280. return NULL;
  2281. }
  2282. BfAstNode* unwarnNode = refNode;
  2283. //
  2284. {
  2285. BfParentNodeEntry* parentNodeEntry = mParentNodeEntry;
  2286. while (parentNodeEntry != NULL)
  2287. {
  2288. if (auto block = BfNodeDynCast<BfBlock>(parentNodeEntry->mNode))
  2289. break;
  2290. unwarnNode = parentNodeEntry->mNode;
  2291. parentNodeEntry = parentNodeEntry->mPrev;
  2292. }
  2293. }
  2294. auto parser = unwarnNode->GetSourceData()->ToParserData();
  2295. if ((parser != NULL) && (parser->IsUnwarnedAt(unwarnNode)))
  2296. {
  2297. return NULL;
  2298. }
  2299. // Right now we're only warning on the unspecialized declarations, we may revisit this
  2300. if (mCurMethodInstance != NULL)
  2301. {
  2302. if (mCurMethodInstance->IsSpecializedGenericMethodOrType())
  2303. return NULL;
  2304. if (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend)
  2305. return NULL; // No ctorCalcAppend warnings
  2306. }
  2307. if ((mCurTypeInstance != NULL) && (mCurTypeInstance->IsSpecializedType()))
  2308. return NULL;
  2309. if (refNode != NULL)
  2310. refNode = BfNodeToNonTemporary(refNode);
  2311. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL))
  2312. {
  2313. // We used to bubble up warnings into the mixin injection site, BUT
  2314. // we are now assuming any relevant warnings will be given at the declaration site
  2315. return NULL;
  2316. // AddFailType(mCurTypeInstance);
  2317. //
  2318. // BfError* bfError = mCompiler->mPassInstance->Warn(warningNum, "Warning while injecting mixin", mCurMethodState->mMixinState->GetRoot()->mSource);
  2319. // if (bfError == NULL)
  2320. // return NULL;
  2321. // mHadBuildWarning = true;
  2322. // return mCompiler->mPassInstance->MoreInfo(warning, refNode);
  2323. }
  2324. BfError* bfError = mCompiler->mPassInstance->WarnAt(warningNum, warning, refNode->GetSourceData(), refNode->GetSrcStart(), refNode->GetSrcLength());
  2325. if (bfError != NULL)
  2326. {
  2327. AddFailType(mCurTypeInstance);
  2328. mHadBuildWarning = true;
  2329. bfError->mIsPersistent = isPersistent;
  2330. if ((mCompiler->IsAutocomplete()) && (mCompiler->mResolvePassData->mAutoComplete->CheckFixit((refNode))))
  2331. {
  2332. BfParserData* parser = refNode->GetSourceData()->ToParserData();
  2333. if (parser != NULL)
  2334. {
  2335. int fileLoc = BfFixitFinder::FindLineStartBefore(refNode);
  2336. mCompiler->mResolvePassData->mAutoComplete->AddEntry(AutoCompleteEntry("fixit", StrFormat("#unwarn\tunwarn|%s|%d|#unwarn|", parser->mFileName.c_str(), fileLoc).c_str()));
  2337. }
  2338. }
  2339. }
  2340. return bfError;
  2341. }
  2342. void BfModule::CheckRangeError(BfType* type, BfAstNode* refNode)
  2343. {
  2344. if (mBfIRBuilder->mOpFailed)
  2345. Fail(StrFormat("Result out of range for type '%s'", TypeToString(type).c_str()), refNode);
  2346. }
  2347. void BfModule::NotImpl(BfAstNode* astNode)
  2348. {
  2349. Fail("INTERNAL ERROR: Not implemented", astNode);
  2350. }
  2351. bool BfModule::CheckAccessMemberProtection(BfProtection protection, BfType* memberType)
  2352. {
  2353. bool allowPrivate = (memberType == mCurTypeInstance) || (IsInnerType(mCurTypeInstance, memberType));
  2354. if (!allowPrivate)
  2355. allowPrivate |= memberType->IsInterface();
  2356. bool allowProtected = allowPrivate;// allowPrivate || TypeIsSubTypeOf(mCurTypeInstance, memberType->ToTypeInstance());
  2357. if (!CheckProtection(protection, allowProtected, allowPrivate))
  2358. {
  2359. return false;
  2360. }
  2361. return true;
  2362. }
  2363. bool BfModule::CheckDefineMemberProtection(BfProtection protection, BfType* memberType)
  2364. {
  2365. // Use 'min' - exporting a 'public' from a 'private' class is really just 'private' still
  2366. protection = std::min(protection, mCurTypeInstance->mTypeDef->mProtection);
  2367. auto memberTypeInstance = memberType->ToTypeInstance();
  2368. if (memberTypeInstance == NULL)
  2369. {
  2370. auto underlyingType = memberType->GetUnderlyingType();
  2371. if (underlyingType != NULL)
  2372. return CheckDefineMemberProtection(protection, underlyingType);
  2373. return true;
  2374. }
  2375. if (memberTypeInstance->mTypeDef->mProtection < protection)
  2376. return false;
  2377. if (memberTypeInstance->IsGenericTypeInstance())
  2378. {
  2379. // When we're a generic struct, our data layout can depend on our generic parameters as well
  2380. auto genericTypeInstance = (BfGenericTypeInstance*) memberTypeInstance;
  2381. for (auto typeGenericArg : genericTypeInstance->mTypeGenericArguments)
  2382. {
  2383. if (!CheckDefineMemberProtection(protection, typeGenericArg))
  2384. return false;
  2385. }
  2386. }
  2387. return true;
  2388. }
  2389. void BfModule::AddDependency(BfType* usedType, BfType* usingType, BfDependencyMap::DependencyDependencyFlag flags)
  2390. {
  2391. if (usedType == usingType)
  2392. return;
  2393. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mIsAutocompleteMethod))
  2394. return;
  2395. if (usedType->IsSpecializedByAutoCompleteMethod())
  2396. return;
  2397. if ((mCurMethodState != NULL) && (mCurMethodState->mHotDataReferenceBuilder != NULL) && (usedType != mCurTypeInstance) &&
  2398. ((flags & (BfDependencyMap::DependencyFlag_ReadFields | BfDependencyMap::DependencyFlag_LocalUsage | BfDependencyMap::DependencyFlag_Allocates)) != 0))
  2399. {
  2400. bool addType = true;
  2401. auto checkType = usedType;
  2402. while (true)
  2403. {
  2404. if ((checkType->IsPointer()) || (checkType->IsRef()) || (checkType->IsSizedArray()))
  2405. checkType = checkType->GetUnderlyingType();
  2406. else if (checkType->IsArray())
  2407. {
  2408. checkType = ((BfGenericTypeInstance*)checkType)->mTypeGenericArguments[0];
  2409. }
  2410. else
  2411. break;
  2412. }
  2413. PopulateType(checkType, BfPopulateType_Data);
  2414. if (checkType->IsValuelessType())
  2415. addType = false;
  2416. else if (checkType->IsPrimitiveType())
  2417. addType = false;
  2418. else
  2419. {
  2420. auto checkTypeInst = checkType->ToTypeInstance();
  2421. if (checkTypeInst == NULL)
  2422. {
  2423. addType = false;
  2424. }
  2425. else
  2426. {
  2427. if (TypeIsSubTypeOf(mCurTypeInstance, checkTypeInst))
  2428. addType = false;
  2429. }
  2430. }
  2431. if (addType)
  2432. {
  2433. auto checkTypeInst = checkType->ToTypeInstance();
  2434. auto hotTypeVersion = checkTypeInst->mHotTypeData->GetLatestVersion();
  2435. BF_ASSERT(hotTypeVersion != NULL);
  2436. bool isAllocation = ((flags & BfDependencyMap::DependencyFlag_Allocates) != 0);
  2437. if (((flags & BfDependencyMap::DependencyFlag_LocalUsage) != 0) &&
  2438. (checkType->IsComposite()))
  2439. isAllocation = true;
  2440. if (isAllocation)
  2441. {
  2442. mCurMethodState->mHotDataReferenceBuilder->mAllocatedData.Add(hotTypeVersion);
  2443. }
  2444. else
  2445. mCurMethodState->mHotDataReferenceBuilder->mUsedData.Add(hotTypeVersion);
  2446. }
  2447. }
  2448. //BP_ZONE("BfModule::AddDependency");
  2449. /*if (usedType->IsMethodRef())
  2450. {
  2451. auto methodRefType = (BfMethodRefType*)usedType;
  2452. AddDependency(methodRefType->mMethodRef->GetOwner(), usingType, flags);
  2453. return;
  2454. }*/
  2455. // Why in the world were we doing this?
  2456. // This caused functions to get immediately deleted since they appear to have no references ever....
  2457. // if (usedType->IsFunction())
  2458. // {
  2459. // usedType = ResolveTypeDef(mCompiler->mFunctionTypeDef);
  2460. // }
  2461. if ((!mCompiler->mIsResolveOnly) && (mIsReified))
  2462. {
  2463. auto usingModule = usingType->GetModule();
  2464. BfModule* usedModule;
  2465. if (usedType->IsFunction())
  2466. {
  2467. auto typeInst = usedType->ToTypeInstance();
  2468. if (typeInst->mBaseType == NULL)
  2469. PopulateType(typeInst);
  2470. usedModule = typeInst->mBaseType->GetModule();
  2471. }
  2472. else
  2473. usedModule = usedType->GetModule();
  2474. if ((usingModule != NULL) && (!usingModule->mIsSpecialModule) &&
  2475. (usedModule != NULL) && (!usedModule->mIsSpecialModule))
  2476. {
  2477. usingModule->mModuleRefs.Add(usedModule);
  2478. }
  2479. }
  2480. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mMethodInfoEx != NULL) && (flags != BfDependencyMap::DependencyFlag_MethodGenericArg))
  2481. {
  2482. // When we are specializing a method, usage of that specialized type is already handled with DependencyFlag_MethodGenericArg
  2483. for (auto genericArg : mCurMethodInstance->mMethodInfoEx->mMethodGenericArguments)
  2484. if (genericArg == usedType)
  2485. return;
  2486. }
  2487. auto underlyingType = usedType->GetUnderlyingType();
  2488. if (underlyingType != NULL) // Not really a "GenericArg", but... same purpose.
  2489. AddDependency(underlyingType, usingType, BfDependencyMap::DependencyFlag_GenericArgRef);
  2490. BfDependedType* checkDType = usedType->ToDependedType();
  2491. if (checkDType == NULL)
  2492. return;
  2493. if ((usedType->mRebuildFlags & BfTypeRebuildFlag_AwaitingReference) != 0)
  2494. mContext->MarkAsReferenced(checkDType);
  2495. checkDType->mDependencyMap.AddUsedBy(usingType, flags);
  2496. if (checkDType->IsGenericTypeInstance())
  2497. {
  2498. auto genericTypeInstance = (BfGenericTypeInstance*) checkDType;
  2499. for (auto genericArg : genericTypeInstance->mTypeGenericArguments)
  2500. {
  2501. AddDependency(genericArg, usingType, BfDependencyMap::DependencyFlag_GenericArgRef);
  2502. }
  2503. }
  2504. }
  2505. void BfModule::AddCallDependency(BfMethodInstance* methodInstance, bool devirtualized)
  2506. {
  2507. if ((mCurMethodState != NULL) && (mCurMethodState->mHotDataReferenceBuilder != NULL))
  2508. {
  2509. if (methodInstance->mHotMethod == NULL)
  2510. CheckHotMethod(methodInstance, "");
  2511. BF_ASSERT(methodInstance->mHotMethod != NULL);
  2512. if (devirtualized)
  2513. mCurMethodState->mHotDataReferenceBuilder->mDevirtualizedCalledMethods.Add(methodInstance->mHotMethod);
  2514. else
  2515. mCurMethodState->mHotDataReferenceBuilder->mCalledMethods.Add(methodInstance->mHotMethod);
  2516. }
  2517. }
  2518. bool BfModule::IsAttribute(BfTypeInstance* typeInst)
  2519. {
  2520. auto checkTypeInst = typeInst;
  2521. while (checkTypeInst != NULL)
  2522. {
  2523. if (checkTypeInst->mTypeDef == mCompiler->mAttributeTypeDef)
  2524. return true;
  2525. checkTypeInst = checkTypeInst->mBaseType;
  2526. }
  2527. return false;
  2528. }
  2529. void BfModule::PopulateGlobalContainersList(const BfGlobalLookup& globalLookup)
  2530. {
  2531. if (mContext->mCurTypeState == NULL)
  2532. return;
  2533. BP_ZONE("PopulateGlobalContainersList");
  2534. BfTypeDef* userTypeDef = mContext->mCurTypeState->mCurTypeDef;
  2535. if (userTypeDef == NULL)
  2536. userTypeDef = mCurTypeInstance->mTypeDef;
  2537. if (mContext->mCurTypeState->mGlobalContainerCurUserTypeDef != userTypeDef)
  2538. {
  2539. mContext->mCurTypeState->mGlobalContainers.Clear();
  2540. for (int namespaceIdx = -1; namespaceIdx < (int)userTypeDef->mNamespaceSearch.size(); namespaceIdx++)
  2541. {
  2542. BfAtomComposite findStr;
  2543. if (namespaceIdx != -1)
  2544. findStr.Reference(userTypeDef->mNamespaceSearch[namespaceIdx]);
  2545. auto typeDefItr = mSystem->mTypeDefs.TryGet(findStr);
  2546. while (typeDefItr)
  2547. {
  2548. auto typeDef = *typeDefItr;
  2549. if ((typeDef->mFullName == findStr) && (typeDef->mIsCombinedPartial) && (typeDef->IsGlobalsContainer()))
  2550. {
  2551. if (typeDef->mProject->ContainsReference(typeDef->mProject))
  2552. {
  2553. BfGlobalContainerEntry globalEntry;
  2554. globalEntry.mTypeDef = typeDef;
  2555. globalEntry.mTypeInst = NULL;
  2556. typeDef->PopulateMemberSets();
  2557. mContext->mCurTypeState->mGlobalContainers.Add(globalEntry);
  2558. }
  2559. }
  2560. else if (!typeDef->mIsPartial)
  2561. {
  2562. //break;
  2563. }
  2564. typeDefItr.MoveToNextHashMatch();
  2565. }
  2566. }
  2567. mContext->mCurTypeState->mGlobalContainerCurUserTypeDef = userTypeDef;
  2568. }
  2569. // Only create actual typeInst when we have an applicable member. This helps in keeping unused globals from
  2570. // reifing types
  2571. for (auto& globalEntry : mContext->mCurTypeState->mGlobalContainers)
  2572. {
  2573. if (globalEntry.mTypeInst == NULL)
  2574. {
  2575. bool include = false;
  2576. if (globalLookup.mKind == BfGlobalLookup::Kind_All)
  2577. include = true;
  2578. else if (globalLookup.mKind == BfGlobalLookup::Kind_Field)
  2579. {
  2580. if (globalEntry.mTypeDef->mFieldSet.ContainsWith(globalLookup.mName))
  2581. include = true;
  2582. if (globalEntry.mTypeDef->mPropertySet.ContainsWith(globalLookup.mName))
  2583. include = true;
  2584. }
  2585. else if (globalLookup.mKind == BfGlobalLookup::Kind_Method)
  2586. {
  2587. if (globalEntry.mTypeDef->mMethodSet.ContainsWith(globalLookup.mName))
  2588. include = true;
  2589. }
  2590. if (include)
  2591. {
  2592. auto type = ResolveTypeDef(globalEntry.mTypeDef);
  2593. if (type != NULL)
  2594. globalEntry.mTypeInst = type->ToTypeInstance();
  2595. }
  2596. }
  2597. }
  2598. }
  2599. void PrintUsers(llvm::MDNode* md);
  2600. BfModuleOptions BfModule::GetModuleOptions()
  2601. {
  2602. if (mIsScratchModule)
  2603. return BfModuleOptions();
  2604. if (mModuleOptions != NULL)
  2605. return *mModuleOptions;
  2606. BfModuleOptions moduleOptions;
  2607. moduleOptions.mEmitDebugInfo = mCompiler->mOptions.mEmitDebugInfo ? 1 : mCompiler->mOptions.mEmitLineInfo ? 2 : 0;
  2608. if (mProject != NULL)
  2609. {
  2610. moduleOptions.mSIMDSetting = mProject->mCodeGenOptions.mSIMDSetting;
  2611. moduleOptions.mOptLevel = mProject->mCodeGenOptions.mOptLevel;
  2612. }
  2613. auto headModule = this;
  2614. while (headModule->mParentModule != NULL)
  2615. headModule = headModule->mParentModule;
  2616. BF_ASSERT((headModule->mOwnedTypeInstances.size() > 0) || (mModuleName == "vdata"));
  2617. if (headModule->mOwnedTypeInstances.size() > 0)
  2618. {
  2619. auto typeInst = headModule->mOwnedTypeInstances[0];
  2620. PopulateType(typeInst);
  2621. if (typeInst->mTypeOptionsIdx != -1)
  2622. {
  2623. auto typeOptions = mSystem->GetTypeOptions(typeInst->mTypeOptionsIdx);
  2624. moduleOptions.mSIMDSetting = (BfSIMDSetting)BfTypeOptions::Apply((int)moduleOptions.mSIMDSetting, typeOptions->mSIMDSetting);
  2625. moduleOptions.mEmitDebugInfo = BfTypeOptions::Apply(moduleOptions.mEmitDebugInfo, typeOptions->mEmitDebugInfo);
  2626. moduleOptions.mOptLevel = (BfOptLevel)BfTypeOptions::Apply((int)moduleOptions.mOptLevel, (int)typeOptions->mOptimizationLevel);
  2627. }
  2628. }
  2629. return moduleOptions;
  2630. }
  2631. BfCheckedKind BfModule::GetDefaultCheckedKind()
  2632. {
  2633. if ((mCurMethodState != NULL) && (mCurMethodState->mDisableChecks))
  2634. return BfCheckedKind_Unchecked;
  2635. bool runtimeChecks = mCompiler->mOptions.mRuntimeChecks;
  2636. auto typeOptions = GetTypeOptions();
  2637. if (typeOptions != NULL)
  2638. runtimeChecks = BfTypeOptions::Apply(runtimeChecks, typeOptions->mRuntimeChecks);
  2639. return runtimeChecks ? BfCheckedKind_Checked : BfCheckedKind_Unchecked;
  2640. }
  2641. void BfModule::AddFailType(BfTypeInstance* typeInstance)
  2642. {
  2643. mContext->mFailTypes.Add(typeInstance);
  2644. }
  2645. void BfModule::CheckAddFailType()
  2646. {
  2647. //TODO: We removed this line, because failures in resolve-only generic method can occur in non-owning modules
  2648. // but we still need to add the owning type to the FailTypes list
  2649. //.. OLD:
  2650. // While we're inlining, it's possible that mCurTypeInstance belongs to another module, ignore it
  2651. /*if (mCurTypeInstance->mModule != this)
  2652. return;*/
  2653. // Using mHadBuildWarning to insert into mFailTypes is our core of our strategy for reasserting
  2654. // warnings on rebuilds where otherwise the warnings wouldn't be generated because no code was
  2655. // being recompiled. This forces types with warnings to be recompiled.
  2656. // We had this 'mIsResolveOnly' check for speed in resolveOnly, but we removed it so the IDE can be
  2657. // constantly warning-aware
  2658. if ((mHadBuildError) ||
  2659. (mHadBuildWarning /*&& !mCompiler->mIsResolveOnly*/))
  2660. {
  2661. //mContext->mFailTypes.Add(mCurTypeInstance);
  2662. }
  2663. }
  2664. void BfModule::MarkDerivedDirty(BfTypeInstance* typeInst)
  2665. {
  2666. if (!mCompiler->IsHotCompile())
  2667. return;
  2668. typeInst->mDirty = true;
  2669. for (auto& dep : typeInst->mDependencyMap)
  2670. {
  2671. auto depType = dep.mKey;
  2672. auto depFlags = dep.mValue.mFlags;
  2673. if ((depFlags & BfDependencyMap::DependencyFlag_DerivedFrom) != 0)
  2674. {
  2675. MarkDerivedDirty(depType->ToTypeInstance());
  2676. }
  2677. }
  2678. }
  2679. void BfModule::CreateStaticField(BfFieldInstance* fieldInstance, bool isThreadLocal)
  2680. {
  2681. auto fieldType = fieldInstance->GetResolvedType();
  2682. auto field = fieldInstance->GetFieldDef();
  2683. if (fieldType->IsVar())
  2684. return;
  2685. BfIRValue initValue;
  2686. if (field->mIsConst)
  2687. {
  2688. if (fieldType->IsPointer())
  2689. fieldType = fieldType->GetUnderlyingType();
  2690. }
  2691. if (!field->mIsExtern)
  2692. initValue = GetDefaultValue(fieldType);
  2693. if (fieldInstance->mOwner->IsUnspecializedType())
  2694. {
  2695. // Placeholder
  2696. auto ptrVal = CreatePointerType(fieldType);
  2697. mStaticFieldRefs[fieldInstance] = GetDefaultValue(ptrVal);
  2698. }
  2699. else
  2700. {
  2701. BfLogSysM("Creating static field Module:%p Type:%p\n", this, fieldType);
  2702. StringT<128> staticVarName;
  2703. BfMangler::Mangle(staticVarName, mCompiler->GetMangleKind(), fieldInstance);
  2704. if (!fieldType->IsValuelessType())
  2705. {
  2706. BfIRValue globalVar = mBfIRBuilder->CreateGlobalVariable(
  2707. mBfIRBuilder->MapType(fieldType, BfIRPopulateType_Eventually_Full),
  2708. false,
  2709. BfIRLinkageType_External,
  2710. initValue,
  2711. staticVarName,
  2712. isThreadLocal);
  2713. BF_ASSERT(globalVar);
  2714. mStaticFieldRefs[fieldInstance] = globalVar;
  2715. }
  2716. }
  2717. }
  2718. void BfModule::ResolveConstField(BfTypeInstance* typeInstance, BfFieldInstance* fieldInstance, BfFieldDef* fieldDef, bool forceResolve)
  2719. {
  2720. bool autoCompleteOnly = mCompiler->IsAutocomplete();
  2721. BfType* fieldType = NULL;
  2722. if (fieldInstance != NULL)
  2723. {
  2724. fieldType = fieldInstance->GetResolvedType();
  2725. if (fieldType == NULL)
  2726. fieldType = ResolveTypeRef(fieldDef->mTypeRef);
  2727. }
  2728. else
  2729. {
  2730. BF_ASSERT(mCompiler->IsAutocomplete());
  2731. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  2732. if ((typeInstance->IsEnum()) && (fieldDef->mTypeRef == NULL))
  2733. {
  2734. fieldType = typeInstance;
  2735. }
  2736. else
  2737. {
  2738. auto isLet = (fieldDef->mTypeRef != NULL) && (fieldDef->mTypeRef->IsExact<BfLetTypeReference>());
  2739. auto isVar = (fieldDef->mTypeRef != NULL) && (fieldDef->mTypeRef->IsExact<BfVarTypeReference>());
  2740. if (isLet || isVar)
  2741. fieldType = GetPrimitiveType(BfTypeCode_Var);
  2742. else
  2743. fieldType = ResolveTypeRef(fieldDef->mTypeRef);
  2744. if (fieldType == NULL)
  2745. fieldType = mContext->mBfObjectType;
  2746. }
  2747. }
  2748. if ((fieldInstance != NULL) && (fieldInstance->mConstIdx != -1) && (!forceResolve))
  2749. return;
  2750. if (mContext->mFieldResolveReentrys.size() > 1)
  2751. {
  2752. if (mContext->mFieldResolveReentrys.IndexOf(fieldInstance, 1) != -1)
  2753. {
  2754. String failStr = "Circular data reference detected between the following fields:";
  2755. for (int i = 1; i < (int)mContext->mFieldResolveReentrys.size(); i++)
  2756. {
  2757. if (i > 1)
  2758. failStr += ",";
  2759. failStr += "\n '" + TypeToString(typeInstance) + "." + mContext->mFieldResolveReentrys[i]->GetFieldDef()->mName + "'";
  2760. }
  2761. BfError* err = Fail(failStr, fieldDef->mFieldDeclaration);
  2762. if (err)
  2763. err->mIsPersistent = true;
  2764. return;
  2765. }
  2766. }
  2767. mContext->mFieldResolveReentrys.push_back(fieldInstance);
  2768. AutoPopBack<decltype (mContext->mFieldResolveReentrys)> popTypeResolveReentry(&mContext->mFieldResolveReentrys);
  2769. if (fieldInstance == NULL)
  2770. popTypeResolveReentry.Pop();
  2771. auto typeDef = typeInstance->mTypeDef;
  2772. BfIRValue constValue;
  2773. if (fieldDef->mIsExtern)
  2774. {
  2775. if (!fieldDef->mTypeRef->IsA<BfPointerTypeRef>())
  2776. {
  2777. Fail("Extern consts must be pointer types", fieldDef->mFieldDeclaration->mTypeRef);
  2778. }
  2779. if (fieldDef->mInitializer != NULL)
  2780. {
  2781. Fail("Extern consts cannot have initializers", fieldDef->mFieldDeclaration->mNameNode);
  2782. }
  2783. }
  2784. else if (fieldDef->mInitializer == NULL)
  2785. {
  2786. if (fieldDef->IsEnumCaseEntry())
  2787. {
  2788. if (typeInstance->IsTypedPrimitive())
  2789. {
  2790. BfFieldInstance* prevFieldInstance = NULL;
  2791. for (int i = fieldDef->mIdx - 1; i >= 0; i--)
  2792. {
  2793. BfFieldInstance* checkFieldInst = &typeInstance->mFieldInstances[i];
  2794. if (checkFieldInst->GetFieldDef()->IsEnumCaseEntry())
  2795. {
  2796. prevFieldInstance = checkFieldInst;
  2797. break;
  2798. }
  2799. }
  2800. if (prevFieldInstance == NULL)
  2801. constValue = GetConstValue(0, typeInstance);
  2802. else
  2803. {
  2804. ResolveConstField(typeInstance, prevFieldInstance, prevFieldInstance->GetFieldDef());
  2805. if (prevFieldInstance->mConstIdx == -1)
  2806. {
  2807. if (!mCompiler->IsAutocomplete())
  2808. AssertErrorState();
  2809. constValue = GetConstValue(0, typeInstance);
  2810. }
  2811. else
  2812. {
  2813. auto prevConstant = ConstantToCurrent(typeInstance->mConstHolder->GetConstantById(prevFieldInstance->mConstIdx), typeInstance->mConstHolder, typeInstance);
  2814. constValue = mBfIRBuilder->CreateAdd(prevConstant, GetConstValue(1, typeInstance));
  2815. }
  2816. }
  2817. }
  2818. }
  2819. else
  2820. {
  2821. Fail("Const requires initializer", fieldDef->mFieldDeclaration->mNameNode);
  2822. }
  2823. }
  2824. else
  2825. {
  2826. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  2827. SetAndRestoreValue<bool> prevIgnoreWrite(mBfIRBuilder->mIgnoreWrites, true);
  2828. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, NULL);
  2829. BfConstResolver constResolver(this);
  2830. BfMethodState methodState;
  2831. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  2832. methodState.mTempKind = BfMethodState::TempKind_Static;
  2833. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  2834. if (fieldType->IsVar())
  2835. {
  2836. auto initValue = GetFieldInitializerValue(fieldInstance, fieldDef->mInitializer, fieldDef, fieldType);
  2837. if (!initValue)
  2838. {
  2839. AssertErrorState();
  2840. initValue = GetDefaultTypedValue(mContext->mBfObjectType);
  2841. }
  2842. if (fieldInstance != NULL)
  2843. {
  2844. fieldInstance->mResolvedType = initValue.mType;
  2845. }
  2846. constValue = initValue.mValue;
  2847. }
  2848. else
  2849. {
  2850. auto uncastedInitValue = GetFieldInitializerValue(fieldInstance, fieldDef->mInitializer, fieldDef, fieldType);
  2851. constValue = uncastedInitValue.mValue;
  2852. }
  2853. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  2854. }
  2855. if (fieldInstance != NULL)
  2856. {
  2857. fieldType = fieldInstance->GetResolvedType();
  2858. if ((fieldType == NULL) || (fieldType->IsVar()))
  2859. {
  2860. AssertErrorState();
  2861. // Default const type is 'int'
  2862. BfTypedValue initValue = GetDefaultTypedValue(GetPrimitiveType(BfTypeCode_IntPtr));
  2863. if (fieldInstance != NULL)
  2864. {
  2865. fieldInstance->mResolvedType = initValue.mType;
  2866. }
  2867. constValue = initValue.mValue;
  2868. }
  2869. if ((constValue) && (fieldInstance->mConstIdx == -1))
  2870. {
  2871. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  2872. CurrentAddToConstHolder(constValue);
  2873. fieldInstance->mConstIdx = constValue.mId;
  2874. }
  2875. }
  2876. }
  2877. BfType* BfModule::ResolveVarFieldType(BfTypeInstance* typeInstance, BfFieldInstance* fieldInstance, BfFieldDef* field)
  2878. {
  2879. bool isDeclType = BfNodeDynCastExact<BfDeclTypeRef>(field->mFieldDeclaration->mTypeRef) != NULL;
  2880. auto fieldType = fieldInstance->GetResolvedType();
  2881. if ((field->mIsConst) && (!isDeclType))
  2882. {
  2883. ResolveConstField(typeInstance, fieldInstance, field);
  2884. return fieldInstance->GetResolvedType();
  2885. }
  2886. bool staticOnly = (field->mIsStatic) && (!isDeclType);
  2887. if (!fieldInstance->mIsInferredType)
  2888. return fieldType;
  2889. if (!fieldType->IsVar())
  2890. return fieldType;
  2891. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  2892. BfTypeState typeState(mCurTypeInstance, mContext->mCurTypeState);
  2893. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState, mContext->mCurTypeState->mTypeInstance != typeInstance);
  2894. auto typeDef = typeInstance->mTypeDef;
  2895. if ((!field->mIsStatic) && (typeDef->mIsStatic))
  2896. {
  2897. AssertErrorState();
  2898. return GetPrimitiveType(BfTypeCode_Var);
  2899. }
  2900. bool hadInferenceCycle = false;
  2901. if (mContext->mFieldResolveReentrys.size() > 1)
  2902. {
  2903. if (mContext->mFieldResolveReentrys.IndexOf(fieldInstance, 1) != -1)
  2904. {
  2905. for (int i = 1; i < (int)mContext->mFieldResolveReentrys.size(); i++)
  2906. {
  2907. auto fieldInst = mContext->mFieldResolveReentrys[i];
  2908. auto fieldDef = fieldInst->GetFieldDef();
  2909. auto fieldOwner = fieldInst->mOwner;
  2910. auto fieldModule = fieldOwner->mModule;
  2911. SetAndRestoreValue<bool> prevIgnoreError(fieldModule->mIgnoreErrors, false);
  2912. fieldModule->Fail(StrFormat("Field '%s.%s' creates a type inference cycle", TypeToString(fieldOwner).c_str(), fieldDef->mName.c_str()), fieldDef->mTypeRef, true);
  2913. }
  2914. return GetPrimitiveType(BfTypeCode_Var);
  2915. }
  2916. }
  2917. mContext->mFieldResolveReentrys.push_back(fieldInstance);
  2918. AutoPopBack<decltype (mContext->mFieldResolveReentrys)> popTypeResolveReentry(&mContext->mFieldResolveReentrys);
  2919. SetAndRestoreValue<bool> prevResolvingVar(typeInstance->mResolvingVarField, true);
  2920. SetAndRestoreValue<bool> prevCtxResolvingVar(mContext->mResolvingVarField, true);
  2921. if ((field->mInitializer == NULL) && (!isDeclType))
  2922. {
  2923. if ((field->mTypeRef->IsA<BfVarTypeReference>()) || (field->mTypeRef->IsA<BfLetTypeReference>()))
  2924. Fail("Implicitly-typed fields must be initialized", field->GetRefNode());
  2925. return GetPrimitiveType(BfTypeCode_Var);
  2926. }
  2927. BfType* resolvedType = NULL;
  2928. if (!hadInferenceCycle)
  2929. {
  2930. SetAndRestoreValue<bool> prevIgnoreWrite(mBfIRBuilder->mIgnoreWrites, true);
  2931. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, NULL/*ctorMethod.mMethodInstance*/);
  2932. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  2933. BfMethodState methodState;
  2934. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  2935. methodState.mTempKind = staticOnly ? BfMethodState::TempKind_Static : BfMethodState::TempKind_NonStatic;
  2936. if (!staticOnly)
  2937. {
  2938. //BfLocalVariable localVar;
  2939. //methodState.mLocals.push_back(localVar);
  2940. }
  2941. if (isDeclType)
  2942. {
  2943. auto fieldDef = fieldInstance->GetFieldDef();
  2944. resolvedType = ResolveTypeRef(fieldDef->mTypeRef, BfPopulateType_Identity);
  2945. }
  2946. else
  2947. {
  2948. BfTypedValue valueFromExpr;
  2949. valueFromExpr = GetFieldInitializerValue(fieldInstance);
  2950. FixIntUnknown(valueFromExpr);
  2951. resolvedType = valueFromExpr.mType;
  2952. }
  2953. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  2954. }
  2955. if (resolvedType == NULL)
  2956. return GetPrimitiveType(BfTypeCode_Var);
  2957. fieldInstance->SetResolvedType(resolvedType);
  2958. if (field->mIsStatic)
  2959. {
  2960. }
  2961. else if (fieldInstance->mDataIdx <= 0)
  2962. {
  2963. }
  2964. else
  2965. {
  2966. BF_ASSERT(typeInstance->IsIncomplete());
  2967. }
  2968. return resolvedType;
  2969. }
  2970. void BfModule::MarkFieldInitialized(BfFieldInstance* fieldInstance)
  2971. {
  2972. BF_ASSERT(fieldInstance->mOwner == mCurTypeInstance);
  2973. auto fieldType = fieldInstance->GetResolvedType();
  2974. if ((fieldInstance->mMergedDataIdx != -1) && (mCurMethodState != NULL))
  2975. {
  2976. int fieldDataCount = 1;
  2977. if (fieldType->IsStruct())
  2978. {
  2979. auto structTypeInst = fieldType->ToTypeInstance();
  2980. fieldDataCount = structTypeInst->mMergedFieldDataCount;
  2981. }
  2982. //TODO: Under what circumstances could 'thisVariable' be NULL?
  2983. auto thisVariable = GetThisVariable();
  2984. if (thisVariable != NULL)
  2985. {
  2986. for (int i = 0; i < fieldDataCount; i++)
  2987. mCurMethodState->LocalDefined(thisVariable, fieldInstance->mMergedDataIdx + i);
  2988. }
  2989. }
  2990. }
  2991. bool BfModule::IsThreadLocal(BfFieldInstance * fieldInstance)
  2992. {
  2993. if (fieldInstance->mCustomAttributes == NULL)
  2994. return false;
  2995. auto fieldDef = fieldInstance->GetFieldDef();
  2996. if (!fieldDef->mIsStatic)
  2997. return false;
  2998. bool isThreadLocal = false;
  2999. if (fieldInstance->mCustomAttributes != NULL)
  3000. {
  3001. for (auto customAttr : fieldInstance->mCustomAttributes->mAttributes)
  3002. {
  3003. if (customAttr.mType->ToTypeInstance()->mTypeDef == mCompiler->mThreadStaticAttributeTypeDef)
  3004. return true;
  3005. }
  3006. }
  3007. return false;
  3008. }
  3009. BfTypedValue BfModule::GetFieldInitializerValue(BfFieldInstance* fieldInstance, BfExpression* initializer, BfFieldDef* fieldDef, BfType* fieldType)
  3010. {
  3011. if (fieldDef == NULL)
  3012. fieldDef = fieldInstance->GetFieldDef();
  3013. if (fieldType == NULL)
  3014. fieldType = fieldInstance->GetResolvedType();
  3015. if (initializer == NULL)
  3016. {
  3017. if (fieldDef == NULL)
  3018. return BfTypedValue();
  3019. initializer = fieldDef->mInitializer;
  3020. }
  3021. BfTypedValue result;
  3022. if (initializer == NULL)
  3023. {
  3024. result = GetDefaultTypedValue(fieldInstance->mResolvedType);
  3025. }
  3026. else
  3027. {
  3028. if ((mCompiler->mIsResolveOnly) && (mCompiler->mResolvePassData->mSourceClassifier != NULL) && (initializer->IsFromParser(mCompiler->mResolvePassData->mParser)))
  3029. {
  3030. mCompiler->mResolvePassData->mSourceClassifier->SetElementType(initializer, BfSourceElementType_Normal);
  3031. mCompiler->mResolvePassData->mSourceClassifier->VisitChildNoRef(initializer);
  3032. }
  3033. if ((mCurTypeInstance->IsPayloadEnum()) && (fieldDef->IsEnumCaseEntry()))
  3034. {
  3035. Fail("Enums with payloads cannot have explicitly-defined discriminators", initializer);
  3036. BfConstResolver constResolver(this);
  3037. constResolver.Resolve(initializer);
  3038. return GetDefaultTypedValue(fieldType);
  3039. }
  3040. else if (fieldDef->mIsConst)
  3041. {
  3042. BfTypeState typeState;
  3043. typeState.mCurTypeDef = fieldDef->mDeclaringType;
  3044. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  3045. BfConstResolver constResolver(this);
  3046. if (fieldType->IsVar())
  3047. return constResolver.Resolve(initializer);
  3048. else
  3049. return constResolver.Resolve(initializer, fieldType);
  3050. }
  3051. if (fieldType->IsVar())
  3052. result = CreateValueFromExpression(initializer, NULL, (BfEvalExprFlags)(BfEvalExprFlags_NoValueAddr | BfEvalExprFlags_FieldInitializer));
  3053. else
  3054. result = CreateValueFromExpression(initializer, fieldType, (BfEvalExprFlags)(BfEvalExprFlags_NoValueAddr | BfEvalExprFlags_FieldInitializer));
  3055. }
  3056. if (fieldInstance != NULL)
  3057. MarkFieldInitialized(fieldInstance);
  3058. return result;
  3059. }
  3060. void BfModule::CheckInterfaceMethod(BfMethodInstance* methodInstance)
  3061. {
  3062. }
  3063. void BfModule::FindSubTypes(BfTypeInstance* classType, SizedArrayImpl<int>* outVals, SizedArrayImpl<BfTypeInstance*>* exChecks, bool isInterfacePass)
  3064. {
  3065. PopulateType(classType);
  3066. if (isInterfacePass)
  3067. {
  3068. for (auto ifaceInst : classType->mInterfaces)
  3069. {
  3070. if (exChecks->Contains(ifaceInst.mInterfaceType))
  3071. continue;
  3072. if (outVals->Contains(ifaceInst.mInterfaceType->mTypeId))
  3073. continue;
  3074. if (ifaceInst.mDeclaringType->IsExtension())
  3075. {
  3076. bool needsExCheck = false;
  3077. if (ifaceInst.mDeclaringType->mProject != classType->mTypeDef->mProject)
  3078. {
  3079. exChecks->push_back(ifaceInst.mInterfaceType);
  3080. continue;
  3081. }
  3082. }
  3083. outVals->push_back(ifaceInst.mInterfaceType->mTypeId);
  3084. }
  3085. }
  3086. else
  3087. {
  3088. outVals->push_back(classType->mTypeId);
  3089. }
  3090. if (classType->mBaseType != NULL)
  3091. {
  3092. FindSubTypes(classType->mBaseType, outVals, exChecks, isInterfacePass);
  3093. }
  3094. }
  3095. void BfModule::CreateDynamicCastMethod()
  3096. {
  3097. auto objType = mContext->mBfObjectType;
  3098. if ((mCompiler->mIsResolveOnly) || (!mIsReified))
  3099. {
  3100. // The main reason to punt on this method for ResolveOnly is because types can be created
  3101. // and destroyed quickly during autocomplete and the typeId creep can generate lots of
  3102. // entries in the LLVM ConstantInt pool, primarily from the FindSubTypes call. We can
  3103. // remove this punt when we recycle typeId's
  3104. mBfIRBuilder->CreateRet(mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapTypeInstPtr(objType)));
  3105. mCurMethodState->mHadReturn = true;
  3106. return;
  3107. }
  3108. bool isInterfacePass = mCurMethodInstance->mMethodDef->mName == BF_METHODNAME_DYNAMICCAST_INTERFACE;
  3109. auto func = mCurMethodState->mIRFunction;
  3110. auto thisValue = mBfIRBuilder->GetArgument(0);
  3111. auto typeIdValue = mBfIRBuilder->GetArgument(1);
  3112. auto intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  3113. auto int32Type = GetPrimitiveType(BfTypeCode_Int32);
  3114. typeIdValue = CastToValue(NULL, BfTypedValue(typeIdValue, intPtrType), int32Type, (BfCastFlags)(BfCastFlags_Explicit | BfCastFlags_SilentFail));
  3115. auto thisObject = mBfIRBuilder->CreateBitCast(thisValue, mBfIRBuilder->MapType(objType));
  3116. auto trueBB = mBfIRBuilder->CreateBlock("check.true");
  3117. //auto falseBB = mBfIRBuilder->CreateBlock("check.false");
  3118. auto exitBB = mBfIRBuilder->CreateBlock("exit");
  3119. SizedArray<int, 8> typeMatches;
  3120. SizedArray<BfTypeInstance*, 8> exChecks;
  3121. FindSubTypes(mCurTypeInstance, &typeMatches, &exChecks, isInterfacePass);
  3122. if ((mCurTypeInstance->IsGenericTypeInstance()) && (!mCurTypeInstance->IsUnspecializedType()))
  3123. {
  3124. // Add 'unbound' type id to cast list so things like "List<int> is List<>" work
  3125. auto genericTypeInst = mCurTypeInstance->mTypeDef;
  3126. BfTypeVector genericArgs;
  3127. for (int i = 0; i < (int) genericTypeInst->mGenericParamDefs.size(); i++)
  3128. genericArgs.push_back(GetGenericParamType(BfGenericParamKind_Type, i));
  3129. auto unboundType = ResolveTypeDef(mCurTypeInstance->mTypeDef, genericArgs, BfPopulateType_Declaration);
  3130. typeMatches.push_back(unboundType->mTypeId);
  3131. }
  3132. if (mCurTypeInstance->IsBoxed())
  3133. {
  3134. BfBoxedType* boxedType = (BfBoxedType*)mCurTypeInstance;
  3135. BfTypeInstance* innerType = boxedType->mElementType;
  3136. FindSubTypes(innerType, &typeMatches, &exChecks, isInterfacePass);
  3137. if (innerType->IsTypedPrimitive())
  3138. {
  3139. auto underlyingType = innerType->GetUnderlyingType();
  3140. typeMatches.push_back(underlyingType->mTypeId);
  3141. }
  3142. auto innerTypeInst = innerType->ToTypeInstance();
  3143. if ((innerTypeInst->mTypeDef == mCompiler->mSizedArrayTypeDef) ||
  3144. (innerTypeInst->mTypeDef == mCompiler->mPointerTTypeDef) ||
  3145. (innerTypeInst->mTypeDef == mCompiler->mMethodRefTypeDef))
  3146. {
  3147. PopulateType(innerTypeInst);
  3148. //TODO: What case was this supposed to handle?
  3149. //typeMatches.push_back(innerTypeInst->mFieldInstances[0].mResolvedType->mTypeId);
  3150. }
  3151. }
  3152. auto curBlock = mBfIRBuilder->GetInsertBlock();
  3153. BfIRValue vDataPtr;
  3154. if (!exChecks.empty())
  3155. {
  3156. BfType* intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  3157. auto ptrPtrType = mBfIRBuilder->GetPointerTo(mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapType(intPtrType)));
  3158. auto vDataPtrPtr = mBfIRBuilder->CreateBitCast(thisValue, ptrPtrType);
  3159. vDataPtr = FixClassVData(mBfIRBuilder->CreateLoad(vDataPtrPtr/*, "vtable"*/));
  3160. }
  3161. auto switchStatement = mBfIRBuilder->CreateSwitch(typeIdValue, exitBB, (int)typeMatches.size() + (int)exChecks.size());
  3162. for (auto typeMatch : typeMatches)
  3163. mBfIRBuilder->AddSwitchCase(switchStatement, GetConstValue32(typeMatch), trueBB);
  3164. Array<BfIRValue> incomingFalses;
  3165. for (auto ifaceTypeInst : exChecks)
  3166. {
  3167. BfIRBlock nextBB = mBfIRBuilder->CreateBlock("exCheck", true);
  3168. mBfIRBuilder->AddSwitchCase(switchStatement, GetConstValue32(ifaceTypeInst->mTypeId), nextBB);
  3169. mBfIRBuilder->SetInsertPoint(nextBB);
  3170. BfIRValue slotOfs = GetInterfaceSlotNum(ifaceTypeInst);
  3171. auto ifacePtrPtr = mBfIRBuilder->CreateInBoundsGEP(vDataPtr, slotOfs/*, "iface"*/);
  3172. auto ifacePtr = mBfIRBuilder->CreateLoad(ifacePtrPtr);
  3173. auto cmpResult = mBfIRBuilder->CreateCmpNE(ifacePtr, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 0));
  3174. mBfIRBuilder->CreateCondBr(cmpResult, trueBB, exitBB);
  3175. incomingFalses.push_back(nextBB);
  3176. }
  3177. mBfIRBuilder->AddBlock(trueBB);
  3178. mBfIRBuilder->SetInsertPoint(trueBB);
  3179. mBfIRBuilder->CreateBr(exitBB);
  3180. mBfIRBuilder->AddBlock(exitBB);
  3181. mBfIRBuilder->SetInsertPoint(exitBB);
  3182. auto phi = mBfIRBuilder->CreatePhi(mBfIRBuilder->MapTypeInstPtr(objType), 2);
  3183. mBfIRBuilder->AddPhiIncoming(phi, thisObject, trueBB);
  3184. auto nullValue = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapTypeInstPtr(objType));
  3185. for (auto incomingFalseBlock : incomingFalses)
  3186. mBfIRBuilder->AddPhiIncoming(phi, nullValue, incomingFalseBlock);
  3187. mBfIRBuilder->AddPhiIncoming(phi, nullValue, curBlock);
  3188. mBfIRBuilder->CreateRet(phi);
  3189. mCurMethodState->mHadReturn = true;
  3190. }
  3191. void BfModule::EmitEquals(BfTypedValue leftValue, BfTypedValue rightValue, BfIRBlock exitBB)
  3192. {
  3193. BfExprEvaluator exprEvaluator(this);
  3194. exprEvaluator.mExpectingType = mCurMethodInstance->mReturnType;
  3195. exprEvaluator.PerformBinaryOperation((BfAstNode*)NULL, (BfAstNode*)NULL, BfBinaryOp_Equality, NULL, BfBinOpFlag_None, leftValue, rightValue);
  3196. BfTypedValue result = exprEvaluator.GetResult();
  3197. if ((result) && (!result.mType->IsVar()))
  3198. {
  3199. auto nextBB = mBfIRBuilder->CreateBlock("next");
  3200. mBfIRBuilder->CreateCondBr(result.mValue, nextBB, exitBB);
  3201. mBfIRBuilder->AddBlock(nextBB);
  3202. mBfIRBuilder->SetInsertPoint(nextBB);
  3203. }
  3204. }
  3205. void BfModule::CreateFakeCallerMethod(const String& funcName)
  3206. {
  3207. BF_ASSERT(mCurMethodInstance->mIRFunction);
  3208. auto voidType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_None));
  3209. SizedArray<BfIRType, 4> paramTypes;
  3210. BfIRFunctionType funcType = mBfIRBuilder->CreateFunctionType(voidType, paramTypes);
  3211. BfIRFunction func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_Internal, "FORCELINK_" + funcName);
  3212. mBfIRBuilder->SetActiveFunction(func);
  3213. auto entryBlock = mBfIRBuilder->CreateBlock("main", true);
  3214. mBfIRBuilder->SetInsertPoint(entryBlock);
  3215. SizedArray<BfIRValue, 8> args;
  3216. BfExprEvaluator exprEvaluator(this);
  3217. if (mCurMethodInstance->HasThis())
  3218. {
  3219. auto thisValue = GetDefaultTypedValue(mCurMethodInstance->GetOwner(), true);
  3220. exprEvaluator.PushThis(NULL, thisValue, mCurMethodInstance, args);
  3221. }
  3222. for (int paramIdx = 0; paramIdx < mCurMethodInstance->GetParamCount(); paramIdx++)
  3223. {
  3224. auto paramType = mCurMethodInstance->GetParamType(paramIdx);
  3225. if (paramType->IsValuelessType())
  3226. continue;
  3227. exprEvaluator.PushArg(GetDefaultTypedValue(paramType, true, paramType->IsComposite() ? BfDefaultValueKind_Addr : BfDefaultValueKind_Const), args);
  3228. }
  3229. mBfIRBuilder->CreateCall(mCurMethodInstance->mIRFunction, args);
  3230. mBfIRBuilder->CreateRetVoid();
  3231. }
  3232. void BfModule::CreateValueTypeEqualsMethod()
  3233. {
  3234. if (mCurMethodInstance->mIsUnspecialized)
  3235. return;
  3236. if (mCurTypeInstance->IsTypedPrimitive())
  3237. return;
  3238. if (mBfIRBuilder->mIgnoreWrites)
  3239. return;
  3240. BF_ASSERT(!mCurTypeInstance->IsBoxed());
  3241. auto compareType = mCurMethodInstance->mParams[0].mResolvedType;
  3242. bool isValid = true;
  3243. auto compareDType = compareType->ToDependedType();
  3244. BfTypeInstance* compareTypeInst = compareType->ToTypeInstance();
  3245. if (compareTypeInst != NULL)
  3246. {
  3247. if (compareType->IsPrimitiveType())
  3248. compareTypeInst = GetWrappedStructType(compareType);
  3249. if ((compareTypeInst == NULL) || (!compareTypeInst->IsValueType()))
  3250. {
  3251. isValid = false;
  3252. }
  3253. mBfIRBuilder->PopulateType(compareTypeInst);
  3254. }
  3255. auto boolType = GetPrimitiveType(BfTypeCode_Boolean);
  3256. if (!isValid)
  3257. {
  3258. ClearLifetimeEnds();
  3259. mBfIRBuilder->CreateRet(GetDefaultValue(boolType));
  3260. return;
  3261. }
  3262. AddDependency(compareDType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ReadFields);
  3263. auto refNode = mCurTypeInstance->mTypeDef->GetRefNode();
  3264. if (refNode == NULL)
  3265. refNode = mCompiler->mValueTypeTypeDef->GetRefNode();
  3266. UpdateSrcPos(refNode);
  3267. SetIllegalSrcPos();
  3268. auto resultVal = CreateAlloca(boolType);
  3269. mBfIRBuilder->CreateStore(GetConstValue(0, boolType), resultVal);
  3270. auto exitBB = mBfIRBuilder->CreateBlock("exit");
  3271. if (compareType->IsSizedArray())
  3272. {
  3273. auto sizedArrayType = (BfSizedArrayType*)compareType;
  3274. if (sizedArrayType->mElementCount > 6)
  3275. {
  3276. auto intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  3277. auto itr = CreateAlloca(intPtrType);
  3278. mBfIRBuilder->CreateStore(GetDefaultValue(intPtrType), itr);
  3279. auto loopBB = mBfIRBuilder->CreateBlock("loop", true);
  3280. auto bodyBB = mBfIRBuilder->CreateBlock("body", true);
  3281. auto doneBB = mBfIRBuilder->CreateBlock("done", true);
  3282. mBfIRBuilder->CreateBr(loopBB);
  3283. mBfIRBuilder->SetInsertPoint(loopBB);
  3284. auto loadedItr = mBfIRBuilder->CreateLoad(itr);
  3285. auto cmpRes = mBfIRBuilder->CreateCmpGTE(loadedItr, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, (uint64)sizedArrayType->mElementCount), true);
  3286. mBfIRBuilder->CreateCondBr(cmpRes, doneBB, bodyBB);
  3287. mBfIRBuilder->SetInsertPoint(bodyBB);
  3288. BfTypedValue leftValue = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(mCurMethodState->mLocals[0]->mValue, GetDefaultValue(intPtrType), loadedItr), sizedArrayType->mElementType, BfTypedValueKind_Addr);
  3289. BfTypedValue rightValue = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(mCurMethodState->mLocals[1]->mValue, GetDefaultValue(intPtrType), loadedItr), sizedArrayType->mElementType, BfTypedValueKind_Addr);
  3290. EmitEquals(leftValue, rightValue, exitBB);
  3291. auto incValue = mBfIRBuilder->CreateAdd(loadedItr, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 1));
  3292. mBfIRBuilder->CreateStore(incValue, itr);
  3293. mBfIRBuilder->CreateBr(loopBB);
  3294. mBfIRBuilder->SetInsertPoint(doneBB);
  3295. }
  3296. else
  3297. {
  3298. for (int dataIdx = 0; dataIdx < sizedArrayType->mElementCount; dataIdx++)
  3299. {
  3300. BfTypedValue leftValue = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(mCurMethodState->mLocals[0]->mValue, 0, dataIdx), sizedArrayType->mElementType, BfTypedValueKind_Addr);
  3301. BfTypedValue rightValue = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(mCurMethodState->mLocals[1]->mValue, 0, dataIdx), sizedArrayType->mElementType, BfTypedValueKind_Addr);
  3302. EmitEquals(leftValue, rightValue, exitBB);
  3303. }
  3304. }
  3305. }
  3306. else if (compareType->IsMethodRef())
  3307. {
  3308. auto methodRefType = (BfMethodRefType*)compareType;
  3309. BfMethodInstance* methodInstance = methodRefType->mMethodRef;
  3310. BfExprEvaluator exprEvaluator(this);
  3311. BfTypedValue leftTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[0]);
  3312. BfTypedValue rightTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  3313. // We only need to compare the 'this' capture. The rationale is that it's impossible to capture any other non-matching
  3314. // values for the same method reference -- they will always refer back to the same local variables.
  3315. int dataIdx = methodRefType->GetDataIdxFromParamIdx(-1);
  3316. if (dataIdx != -1)
  3317. {
  3318. bool failed = false;
  3319. BfTypedValue leftValue = exprEvaluator.DoImplicitArgCapture(NULL, methodInstance, methodRefType->GetParamIdxFromDataIdx(dataIdx), failed, BfImplicitParamKind_General, leftTypedVal);
  3320. BfTypedValue rightValue = exprEvaluator.DoImplicitArgCapture(NULL, methodInstance, methodRefType->GetParamIdxFromDataIdx(dataIdx), failed, BfImplicitParamKind_General, rightTypedVal);
  3321. BF_ASSERT(!failed);
  3322. EmitEquals(leftValue, rightValue, exitBB);
  3323. }
  3324. }
  3325. else if (compareTypeInst->IsEnum())
  3326. {
  3327. //auto intType = GetPrimitiveType(BfTypeCode_Int32);
  3328. BfExprEvaluator exprEvaluator(this);
  3329. BfTypedValue leftTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[0]);
  3330. BfTypedValue rightTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  3331. auto dscrType = compareTypeInst->GetDiscriminatorType();
  3332. BfTypedValue leftValue = ExtractValue(leftTypedVal, NULL, 2);
  3333. leftValue = LoadValue(leftValue);
  3334. BfTypedValue rightValue = ExtractValue(rightTypedVal, NULL, 2);
  3335. rightValue = LoadValue(rightValue);
  3336. BfTypedValue leftPayload = ExtractValue(leftTypedVal, NULL, 1);
  3337. BfTypedValue rightPayload = ExtractValue(rightTypedVal, NULL, 1);
  3338. EmitEquals(leftValue, rightValue, exitBB);
  3339. int enumCount = 0;
  3340. for (auto& fieldRef : compareTypeInst->mFieldInstances)
  3341. {
  3342. BfFieldInstance* fieldInstance = &fieldRef;
  3343. BfFieldDef* fieldDef = fieldInstance->GetFieldDef();
  3344. if ((fieldDef != NULL) && (fieldDef->IsEnumCaseEntry()))
  3345. {
  3346. enumCount = -fieldInstance->mDataIdx;
  3347. }
  3348. }
  3349. if (enumCount > 0)
  3350. {
  3351. BfIRBlock matchedBlock = mBfIRBuilder->CreateBlock("matched");
  3352. auto switchVal = mBfIRBuilder->CreateSwitch(leftValue.mValue, exitBB, enumCount);
  3353. for (auto& fieldRef : compareTypeInst->mFieldInstances)
  3354. {
  3355. BfFieldInstance* fieldInstance = &fieldRef;
  3356. BfFieldDef* fieldDef = fieldInstance->GetFieldDef();
  3357. if ((fieldDef != NULL) && (fieldDef->IsEnumCaseEntry()))
  3358. {
  3359. int enumIdx = -fieldInstance->mDataIdx - 1;
  3360. if (fieldInstance->mResolvedType->mSize == 0)
  3361. {
  3362. mBfIRBuilder->AddSwitchCase(switchVal, mBfIRBuilder->CreateConst(dscrType->mTypeDef->mTypeCode, enumIdx), matchedBlock);
  3363. }
  3364. else
  3365. {
  3366. auto caseBlock = mBfIRBuilder->CreateBlock("case", true);
  3367. mBfIRBuilder->SetInsertPoint(caseBlock);
  3368. auto tuplePtr = CreatePointerType(fieldInstance->mResolvedType);
  3369. BfTypedValue leftTuple;
  3370. BfTypedValue rightTuple;
  3371. if (leftPayload.IsAddr())
  3372. {
  3373. leftTuple = BfTypedValue(mBfIRBuilder->CreateBitCast(leftPayload.mValue, mBfIRBuilder->MapType(tuplePtr)), fieldInstance->mResolvedType, true);
  3374. rightTuple = BfTypedValue(mBfIRBuilder->CreateBitCast(rightPayload.mValue, mBfIRBuilder->MapType(tuplePtr)), fieldInstance->mResolvedType, true);
  3375. }
  3376. else
  3377. {
  3378. leftTuple = Cast(NULL, leftPayload, fieldInstance->mResolvedType, BfCastFlags_Force);
  3379. rightTuple = Cast(NULL, rightPayload, fieldInstance->mResolvedType, BfCastFlags_Force);
  3380. }
  3381. EmitEquals(leftTuple, rightTuple, exitBB);
  3382. mBfIRBuilder->CreateBr(matchedBlock);
  3383. mBfIRBuilder->AddSwitchCase(switchVal, mBfIRBuilder->CreateConst(dscrType->mTypeDef->mTypeCode, enumIdx), caseBlock);
  3384. }
  3385. }
  3386. }
  3387. mBfIRBuilder->AddBlock(matchedBlock);
  3388. mBfIRBuilder->SetInsertPoint(matchedBlock);
  3389. }
  3390. }
  3391. else if (compareTypeInst->IsUnion())
  3392. {
  3393. auto innerType = compareTypeInst->GetUnionInnerType();
  3394. if (!innerType->IsValuelessType())
  3395. {
  3396. BfExprEvaluator exprEvaluator(this);
  3397. BfTypedValue leftTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[0]);
  3398. BfTypedValue leftUnionTypedVal = ExtractValue(leftTypedVal, NULL, 1);
  3399. BfTypedValue rightTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  3400. BfTypedValue rightUnionTypedVal = ExtractValue(rightTypedVal, NULL, 1);
  3401. EmitEquals(leftUnionTypedVal, rightUnionTypedVal, exitBB);
  3402. }
  3403. }
  3404. else
  3405. {
  3406. BfExprEvaluator exprEvaluator(this);
  3407. BfTypedValue leftTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[0]);
  3408. BfTypedValue rightTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  3409. bool hadComparison = false;
  3410. for (auto& fieldRef : compareTypeInst->mFieldInstances)
  3411. {
  3412. BfFieldInstance* fieldInstance = &fieldRef;
  3413. if (fieldInstance->mDataOffset == -1)
  3414. continue;
  3415. if (fieldInstance->mResolvedType->IsValuelessType())
  3416. continue;
  3417. BfTypedValue leftValue = ExtractValue(leftTypedVal, fieldInstance, fieldInstance->mDataIdx);
  3418. BfTypedValue rightValue = ExtractValue(rightTypedVal, fieldInstance, fieldInstance->mDataIdx);
  3419. if (!fieldInstance->mResolvedType->IsComposite())
  3420. {
  3421. leftValue = LoadValue(leftValue);
  3422. rightValue = LoadValue(rightValue);
  3423. }
  3424. EmitEquals(leftValue, rightValue, exitBB);
  3425. }
  3426. auto baseTypeInst = compareTypeInst->mBaseType;
  3427. if ((baseTypeInst != NULL) && (baseTypeInst->mTypeDef != mCompiler->mValueTypeTypeDef))
  3428. {
  3429. BfTypedValue leftOrigValue(mCurMethodState->mLocals[0]->mValue, compareTypeInst, true);
  3430. BfTypedValue rightOrigValue(mCurMethodState->mLocals[1]->mValue, compareTypeInst, true);
  3431. BfTypedValue leftValue = Cast(NULL, leftOrigValue, baseTypeInst);
  3432. BfTypedValue rightValue = Cast(NULL, rightOrigValue, baseTypeInst);
  3433. EmitEquals(leftValue, rightValue, exitBB);
  3434. }
  3435. }
  3436. mBfIRBuilder->CreateStore(GetConstValue(1, boolType), resultVal);
  3437. mBfIRBuilder->CreateBr(exitBB);
  3438. mBfIRBuilder->AddBlock(exitBB);
  3439. mBfIRBuilder->SetInsertPoint(exitBB);
  3440. auto loadedResult = mBfIRBuilder->CreateLoad(resultVal);
  3441. ClearLifetimeEnds();
  3442. mBfIRBuilder->CreateRet(loadedResult);
  3443. mCurMethodState->mHadReturn = true;
  3444. }
  3445. BfIRValue BfModule::CreateClassVDataGlobal(BfTypeInstance* typeInstance, int* outNumElements, String* outMangledName)
  3446. {
  3447. if (mBfIRBuilder->mIgnoreWrites)
  3448. return mBfIRBuilder->GetFakeVal();
  3449. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  3450. BfType* classVDataType = ResolveTypeDef(mCompiler->mClassVDataTypeDef);
  3451. BfIRValue* globalVariablePtr = NULL;
  3452. mClassVDataRefs.TryGetValue(typeInstance, &globalVariablePtr);
  3453. int numElements = 1;
  3454. if ((outNumElements != NULL) || (globalVariablePtr == NULL))
  3455. {
  3456. numElements += mCompiler->mMaxInterfaceSlots;
  3457. auto maxIFaceVirtIdx = 0;
  3458. if (!typeInstance->IsInterface())
  3459. {
  3460. int dynCastDataElems = 1 + mCompiler->mMaxInterfaceSlots;
  3461. numElements += ((dynCastDataElems * 4) + mSystem->mPtrSize - 1) / mSystem->mPtrSize;
  3462. numElements += typeInstance->GetOrigVTableSize();
  3463. int ifaceMethodLen = typeInstance->GetIFaceVMethodSize();
  3464. if (typeInstance->mHotTypeData != NULL)
  3465. {
  3466. if (typeInstance->mHotTypeData->mOrigInterfaceMethodsLength != -1)
  3467. ifaceMethodLen = typeInstance->mHotTypeData->mOrigInterfaceMethodsLength;
  3468. }
  3469. numElements += ifaceMethodLen;
  3470. }
  3471. if (outNumElements != NULL)
  3472. *outNumElements = numElements;
  3473. }
  3474. StringT<128> classVDataName;
  3475. String memberName = "sBfClassVData";
  3476. if ((typeInstance->mHotTypeData != NULL) && ((typeInstance->mHotTypeData->mHadDataChange) || (typeInstance->mHotTypeData->mPendingDataChange)))
  3477. {
  3478. auto curVersion = typeInstance->mHotTypeData->GetLatestVersion();
  3479. memberName += "_";
  3480. memberName += BfTypeUtils::HashEncode64(curVersion->mDataHash.mLow);
  3481. memberName += BfTypeUtils::HashEncode64(curVersion->mDataHash.mHigh);
  3482. }
  3483. BfMangler::MangleStaticFieldName(classVDataName, mCompiler->GetMangleKind(), typeInstance, memberName, classVDataType);
  3484. if (outMangledName != NULL)
  3485. *outMangledName = classVDataName;
  3486. /*if (itr != mClassVDataRefs.end())
  3487. {
  3488. globalVariable = itr->second;
  3489. }*/
  3490. BfIRValue globalVariable;
  3491. if (globalVariablePtr != NULL)
  3492. {
  3493. globalVariable = *globalVariablePtr;
  3494. }
  3495. else
  3496. {
  3497. BfLogSysM("Creating VData %s\n", classVDataName.c_str());
  3498. auto arrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr), numElements);
  3499. globalVariable = mBfIRBuilder->CreateGlobalVariable(
  3500. arrayType,
  3501. true,
  3502. BfIRLinkageType_External,
  3503. BfIRValue(),
  3504. classVDataName);
  3505. mClassVDataRefs[typeInstance] = globalVariable;
  3506. }
  3507. return globalVariable;
  3508. }
  3509. BfIRValue BfModule::GetClassVDataPtr(BfTypeInstance* typeInstance)
  3510. {
  3511. auto classVDataType = ResolveTypeDef(mCompiler->mClassVDataTypeDef);
  3512. return mBfIRBuilder->CreateBitCast(CreateClassVDataGlobal(typeInstance), mBfIRBuilder->MapType(CreatePointerType(classVDataType)));
  3513. }
  3514. BfIRValue BfModule::CreateClassVDataExtGlobal(BfTypeInstance* declTypeInst, BfTypeInstance* implTypeInst, int startVirtIdx)
  3515. {
  3516. if (mBfIRBuilder->mIgnoreWrites)
  3517. return mBfIRBuilder->GetFakeVal();
  3518. int numElements = declTypeInst->GetSelfVTableSize() - declTypeInst->GetOrigSelfVTableSize();
  3519. BF_ASSERT(numElements >= 0);
  3520. if (numElements <= 0)
  3521. return BfIRValue();
  3522. BF_ASSERT(implTypeInst->mVirtualMethodTable[startVirtIdx].mDeclaringMethod.mMethodNum == -1);
  3523. BF_ASSERT(implTypeInst->mVirtualMethodTable[startVirtIdx].mDeclaringMethod.mTypeInstance == declTypeInst);
  3524. if (declTypeInst->mInheritDepth == implTypeInst->mInheritDepth)
  3525. BF_ASSERT(declTypeInst == implTypeInst);
  3526. else
  3527. BF_ASSERT(implTypeInst->mInheritDepth > declTypeInst->mInheritDepth);
  3528. if (declTypeInst != implTypeInst)
  3529. {
  3530. BfTypeInstance* highestImpl = declTypeInst;
  3531. for (int virtIdx = startVirtIdx + 1; virtIdx < (int)declTypeInst->mVirtualMethodTable.size(); virtIdx++)
  3532. {
  3533. if (implTypeInst->mVirtualMethodTable[virtIdx].mDeclaringMethod.mMethodNum == -1)
  3534. break; // Start of an ext entry for another type
  3535. auto checkImplTypeInst = implTypeInst->mVirtualMethodTable[virtIdx].mImplementingMethod.mTypeInstance;
  3536. if ((checkImplTypeInst != NULL) && (checkImplTypeInst->mInheritDepth > highestImpl->mInheritDepth))
  3537. highestImpl = checkImplTypeInst;
  3538. }
  3539. if (highestImpl != implTypeInst)
  3540. return CreateClassVDataExtGlobal(declTypeInst, highestImpl, startVirtIdx);
  3541. }
  3542. BfVDataExtEntry mapEntry;
  3543. mapEntry.mDeclTypeInst = declTypeInst;
  3544. mapEntry.mImplTypeInst = implTypeInst;
  3545. BfIRValue* irValuePtr = NULL;
  3546. if (mClassVDataExtRefs.TryGetValue(mapEntry, &irValuePtr))
  3547. return *irValuePtr;
  3548. PopulateType(declTypeInst, BfPopulateType_DataAndMethods);
  3549. PopulateType(implTypeInst, BfPopulateType_DataAndMethods);
  3550. StringT<128> classVDataName;
  3551. BfMangler::MangleStaticFieldName(classVDataName, mCompiler->GetMangleKind(), implTypeInst, "bf_hs_replace_VDataExt");
  3552. if (declTypeInst != implTypeInst)
  3553. {
  3554. classVDataName += StrFormat("_%d", implTypeInst->mInheritDepth - declTypeInst->mInheritDepth);
  3555. }
  3556. auto voidPtrType = GetPrimitiveType(BfTypeCode_NullPtr);
  3557. auto voidPtrIRType = mBfIRBuilder->MapType(voidPtrType);
  3558. SizedArray<BfIRValue, 32> vData;
  3559. auto voidPtrNull = GetDefaultValue(voidPtrType);
  3560. for (int virtIdx = startVirtIdx + declTypeInst->GetOrigSelfVTableSize(); virtIdx < (int)declTypeInst->mVirtualMethodTable.size(); virtIdx++)
  3561. {
  3562. if (implTypeInst->mVirtualMethodTable[virtIdx].mDeclaringMethod.mMethodNum == -1)
  3563. break; // Start of an ext entry for another type
  3564. BfIRValue vValue;
  3565. auto& entry = implTypeInst->mVirtualMethodTable[virtIdx];
  3566. BfMethodInstance* declaringMethodInstance = (BfMethodInstance*)entry.mDeclaringMethod;
  3567. if ((declaringMethodInstance != NULL) && (declaringMethodInstance->mMethodInstanceGroup->IsImplemented()) && (declaringMethodInstance->mIsReified))
  3568. {
  3569. BF_ASSERT(entry.mImplementingMethod.mTypeInstance->mMethodInstanceGroups[entry.mImplementingMethod.mMethodNum].IsImplemented());
  3570. BF_ASSERT(entry.mImplementingMethod.mTypeInstance->mMethodInstanceGroups[entry.mImplementingMethod.mMethodNum].mDefault->mIsReified);
  3571. BfMethodInstance* methodInstance = (BfMethodInstance*)entry.mImplementingMethod;
  3572. if ((methodInstance != NULL) && (!methodInstance->mMethodDef->mIsAbstract))
  3573. {
  3574. BF_ASSERT(implTypeInst->IsTypeMemberAccessible(methodInstance->mMethodDef->mDeclaringType, mProject));
  3575. auto moduleMethodInst = GetMethodInstanceAtIdx(methodInstance->mMethodInstanceGroup->mOwner, methodInstance->mMethodInstanceGroup->mMethodIdx);
  3576. auto funcPtr = mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, voidPtrIRType);
  3577. vValue = funcPtr;
  3578. }
  3579. }
  3580. if (!vValue)
  3581. vValue = voidPtrNull;
  3582. vData.Add(vValue);
  3583. }
  3584. BF_ASSERT((int)vData.size() == numElements);
  3585. BfLogSysM("Creating VDataExt %s\n", classVDataName.c_str());
  3586. auto arrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr), numElements);
  3587. auto globalVariable = mBfIRBuilder->CreateGlobalVariable(arrayType, true,
  3588. BfIRLinkageType_External, BfIRValue(), classVDataName);
  3589. BfIRType extVTableType = mBfIRBuilder->GetSizedArrayType(voidPtrIRType, (int)vData.size());
  3590. BfIRValue extVTableConst = mBfIRBuilder->CreateConstArray(extVTableType, vData);
  3591. mBfIRBuilder->GlobalVar_SetInitializer(globalVariable, extVTableConst);
  3592. mClassVDataExtRefs[mapEntry] = globalVariable;
  3593. return globalVariable;
  3594. }
  3595. BfIRValue BfModule::CreateTypeDataRef(BfType* type)
  3596. {
  3597. if (mBfIRBuilder->mIgnoreWrites)
  3598. {
  3599. return mBfIRBuilder->CreateTypeOf(type);
  3600. }
  3601. BfIRValue globalVariable;
  3602. BfIRValue* globalVariablePtr = NULL;
  3603. if (mTypeDataRefs.TryGetValue(type, &globalVariablePtr))
  3604. {
  3605. globalVariable = *globalVariablePtr;
  3606. if (globalVariable)
  3607. return globalVariable;
  3608. }
  3609. auto typeTypeDef = ResolveTypeDef(mCompiler->mTypeTypeDef);
  3610. auto typeTypeInst = typeTypeDef->ToTypeInstance();
  3611. auto typeInstance = type->ToTypeInstance();
  3612. StringT<128> typeDataName;
  3613. if (typeInstance != NULL)
  3614. {
  3615. BfMangler::MangleStaticFieldName(typeDataName, mCompiler->GetMangleKind(), typeInstance, "sBfTypeData");
  3616. }
  3617. else
  3618. {
  3619. typeDataName += "sBfTypeData.";
  3620. BfMangler::Mangle(typeDataName, mCompiler->GetMangleKind(), type);
  3621. }
  3622. BfLogSysM("Creating TypeData %s\n", typeDataName.c_str());
  3623. globalVariable = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapTypeInst(typeTypeInst, BfIRPopulateType_Full), true, BfIRLinkageType_External, BfIRValue(), typeDataName);
  3624. mTypeDataRefs[type] = globalVariable;
  3625. return globalVariable;
  3626. }
  3627. BfIRValue BfModule::CreateTypeData(BfType* type, Dictionary<int, int>& usedStringIdMap, bool forceReflectFields, bool needsTypeData, bool needsTypeNames, bool needsVData)
  3628. {
  3629. if ((mCompiler->IsHotCompile()) && (!type->mDirty))
  3630. return BfIRValue();
  3631. BfIRValue* irValuePtr = NULL;
  3632. if (mTypeDataRefs.TryGetValue(type, &irValuePtr))
  3633. {
  3634. return *irValuePtr;
  3635. }
  3636. BfTypeInstance* typeInstance = type->ToTypeInstance();
  3637. BfType* typeInstanceType = ResolveTypeDef(mCompiler->mReflectTypeInstanceTypeDef);
  3638. mBfIRBuilder->PopulateType(typeInstanceType, BfIRPopulateType_Full_ForceDefinition);
  3639. if (typeInstanceType == NULL)
  3640. {
  3641. AssertErrorState();
  3642. return BfIRValue();
  3643. }
  3644. BfIRValue typeTypeData;
  3645. int typeFlags = 0;
  3646. if (needsTypeData)
  3647. {
  3648. BfTypeInstance* typeInstanceTypeInstance = typeInstanceType->ToTypeInstance();
  3649. BfTypeInstance* typeDataSource = NULL;
  3650. if (typeInstance != NULL)
  3651. {
  3652. if (typeInstance->IsUnspecializedType())
  3653. {
  3654. typeDataSource = ResolveTypeDef(mCompiler->mReflectUnspecializedGenericType)->ToTypeInstance();
  3655. typeFlags |= BfTypeFlags_UnspecializedGeneric;
  3656. }
  3657. else if (typeInstance->IsArray())
  3658. {
  3659. typeDataSource = ResolveTypeDef(mCompiler->mReflectArrayType)->ToTypeInstance();
  3660. typeFlags |= BfTypeFlags_Array;
  3661. }
  3662. else if (typeInstance->IsGenericTypeInstance())
  3663. {
  3664. typeDataSource = ResolveTypeDef(mCompiler->mReflectSpecializedGenericType)->ToTypeInstance();
  3665. typeFlags |= BfTypeFlags_SpecializedGeneric;
  3666. }
  3667. else
  3668. typeDataSource = typeInstanceTypeInstance;
  3669. }
  3670. else if (type->IsPointer())
  3671. typeDataSource = ResolveTypeDef(mCompiler->mReflectPointerType)->ToTypeInstance();
  3672. else if (type->IsSizedArray())
  3673. typeDataSource = ResolveTypeDef(mCompiler->mReflectSizedArrayType)->ToTypeInstance();
  3674. else
  3675. typeDataSource = mContext->mBfTypeType;
  3676. if ((!mTypeDataRefs.ContainsKey(typeDataSource)) && (typeDataSource != type))
  3677. {
  3678. CreateTypeData(typeDataSource, usedStringIdMap, false, true, needsTypeNames, true);
  3679. }
  3680. typeTypeData = CreateClassVDataGlobal(typeDataSource);
  3681. }
  3682. else
  3683. typeTypeData = CreateClassVDataGlobal(typeInstanceType->ToTypeInstance());
  3684. BfType* longType = GetPrimitiveType(BfTypeCode_Int64);
  3685. BfType* intType = GetPrimitiveType(BfTypeCode_Int32);
  3686. BfType* shortType = GetPrimitiveType(BfTypeCode_Int16);
  3687. BfType* byteType = GetPrimitiveType(BfTypeCode_Int8);
  3688. BfType* typeIdType = intType;
  3689. auto voidPtrType = GetPrimitiveType(BfTypeCode_NullPtr);
  3690. auto voidPtrIRType = mBfIRBuilder->MapType(voidPtrType);
  3691. auto voidPtrPtrIRType = mBfIRBuilder->GetPointerTo(voidPtrIRType);
  3692. auto voidPtrNull = GetDefaultValue(voidPtrType);
  3693. SizedArray<BfIRValue, 4> typeValueParams;
  3694. GetConstClassValueParam(typeTypeData, typeValueParams);
  3695. BfIRValue objectData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(mContext->mBfObjectType, BfIRPopulateType_Full), typeValueParams);
  3696. StringT<128> typeDataName;
  3697. if ((typeInstance != NULL) && (!typeInstance->IsTypeAlias()))
  3698. {
  3699. BfMangler::MangleStaticFieldName(typeDataName, mCompiler->GetMangleKind(), typeInstance, "sBfTypeData");
  3700. if (typeInstance->mTypeDef->IsGlobalsContainer())
  3701. typeDataName += "`G`" + typeInstance->mTypeDef->mProject->mName;
  3702. }
  3703. else
  3704. {
  3705. typeDataName += "sBfTypeData.";
  3706. BfMangler::Mangle(typeDataName, mCompiler->GetMangleKind(), type, mContext->mScratchModule);
  3707. }
  3708. int typeCode = BfTypeCode_None;
  3709. if (typeInstance != NULL)
  3710. {
  3711. typeCode = typeInstance->mTypeDef->mTypeCode;
  3712. }
  3713. else if (type->IsPrimitiveType())
  3714. {
  3715. BfPrimitiveType* primType = (BfPrimitiveType*)type;
  3716. typeCode = primType->mTypeDef->mTypeCode;
  3717. }
  3718. else if (type->IsPointer())
  3719. {
  3720. typeCode = BfTypeCode_Pointer;
  3721. typeFlags |= BfTypeFlags_Pointer;
  3722. }
  3723. if (type->IsObject())
  3724. {
  3725. typeFlags |= BfTypeFlags_Object;
  3726. BfMethodInstance* methodInstance = typeInstance->mVirtualMethodTable[mCompiler->GetVTableMethodOffset() + 0].mImplementingMethod;
  3727. if (methodInstance->GetOwner() != mContext->mBfObjectType)
  3728. typeFlags |= BfTypeFlags_HasDestructor;
  3729. }
  3730. if (type->IsStruct())
  3731. typeFlags |= BfTypeFlags_Struct;
  3732. if (type->IsBoxed())
  3733. {
  3734. typeFlags |= BfTypeFlags_Boxed;
  3735. if (((BfBoxedType*)type)->IsBoxedStructPtr())
  3736. typeFlags |= BfTypeFlags_Pointer;
  3737. }
  3738. if (type->IsPrimitiveType())
  3739. typeFlags |= BfTypeFlags_Primitive;
  3740. if (type->IsTypedPrimitive())
  3741. typeFlags |= BfTypeFlags_TypedPrimitive;
  3742. if (type->IsTuple())
  3743. typeFlags |= BfTypeFlags_Tuple;
  3744. if (type->IsNullable())
  3745. typeFlags |= BfTypeFlags_Nullable;
  3746. if (type->IsSizedArray())
  3747. typeFlags |= BfTypeFlags_SizedArray;
  3748. if (type->IsSplattable())
  3749. typeFlags |= BfTypeFlags_Splattable;
  3750. if (type->IsUnion())
  3751. typeFlags |= BfTypeFlags_Union;
  3752. if (type->IsDelegate())
  3753. typeFlags |= BfTypeFlags_Delegate;
  3754. if (type->WantsGCMarking())
  3755. typeFlags |= BfTypeFlags_WantsMarking;
  3756. int memberDataOffset = 0;
  3757. if (typeInstance != NULL)
  3758. {
  3759. for (auto& fieldInstance : typeInstance->mFieldInstances)
  3760. {
  3761. if (fieldInstance.mDataOffset != -1)
  3762. {
  3763. memberDataOffset = fieldInstance.mDataOffset;
  3764. break;
  3765. }
  3766. }
  3767. }
  3768. SizedArray<BfIRValue, 8> typeDataParams =
  3769. {
  3770. objectData,
  3771. GetConstValue(type->mSize, intType), // mSize
  3772. GetConstValue(type->mTypeId, typeIdType), // mTypeId
  3773. GetConstValue(typeFlags, intType), // mTypeFlags
  3774. GetConstValue(memberDataOffset, intType), // mMemberDataOffset
  3775. GetConstValue(typeCode, byteType), // mTypeCode
  3776. GetConstValue(type->mAlign, byteType),
  3777. };
  3778. auto typeData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(mContext->mBfTypeType, BfIRPopulateType_Full), typeDataParams);
  3779. if (typeInstance == NULL)
  3780. {
  3781. BfIRValue typeDataVar;
  3782. if (needsTypeData)
  3783. {
  3784. if (type->IsPointer())
  3785. {
  3786. auto pointerType = (BfPointerType*)type;
  3787. SizedArray<BfIRValue, 3> pointerTypeDataParms =
  3788. {
  3789. typeData,
  3790. GetConstValue(pointerType->mElementType->mTypeId, typeIdType),
  3791. };
  3792. auto reflectPointerType = ResolveTypeDef(mCompiler->mReflectPointerType)->ToTypeInstance();
  3793. auto pointerTypeData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(reflectPointerType, BfIRPopulateType_Full), pointerTypeDataParms);
  3794. typeDataVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapTypeInst(reflectPointerType), true,
  3795. BfIRLinkageType_External, pointerTypeData, typeDataName);
  3796. typeDataVar = mBfIRBuilder->CreateBitCast(typeDataVar, mBfIRBuilder->MapType(mContext->mBfTypeType));
  3797. }
  3798. else if (type->IsSizedArray())
  3799. {
  3800. auto sizedArrayType = (BfSizedArrayType*)type;
  3801. SizedArray<BfIRValue, 3> sizedArrayTypeDataParms =
  3802. {
  3803. typeData,
  3804. GetConstValue(sizedArrayType->mElementType->mTypeId, typeIdType),
  3805. GetConstValue(sizedArrayType->mElementCount, intType)
  3806. };
  3807. auto reflectSizedArrayType = ResolveTypeDef(mCompiler->mReflectSizedArrayType)->ToTypeInstance();
  3808. auto sizedArrayTypeData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(reflectSizedArrayType, BfIRPopulateType_Full), sizedArrayTypeDataParms);
  3809. typeDataVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapTypeInst(reflectSizedArrayType), true,
  3810. BfIRLinkageType_External, sizedArrayTypeData, typeDataName);
  3811. typeDataVar = mBfIRBuilder->CreateBitCast(typeDataVar, mBfIRBuilder->MapType(mContext->mBfTypeType));
  3812. }
  3813. else
  3814. {
  3815. typeDataVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapTypeInst(mContext->mBfTypeType), true,
  3816. BfIRLinkageType_External, typeData, typeDataName);
  3817. }
  3818. }
  3819. else
  3820. typeDataVar = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(mContext->mBfTypeType));
  3821. mTypeDataRefs[typeInstance] = typeDataVar;
  3822. return typeDataVar;
  3823. }
  3824. // Reserve position
  3825. mTypeDataRefs[typeInstance] = BfIRValue();
  3826. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  3827. BfTypeDef* typeDef = typeInstance->mTypeDef;
  3828. StringT<128> mangledName;
  3829. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), typeInstance, typeInstance->mModule);
  3830. for (int methodIdx = 0; methodIdx < (int)typeDef->mMethods.size(); methodIdx++)
  3831. {
  3832. auto methodDef = typeDef->mMethods[methodIdx];
  3833. auto methodInstance = typeInstance->mMethodInstanceGroups[methodIdx].mDefault;
  3834. if (methodInstance == NULL)
  3835. continue;
  3836. if (typeInstance->IsUnspecializedType())
  3837. continue;
  3838. if (!typeInstance->IsTypeMemberAccessible(methodDef->mDeclaringType, mProject))
  3839. {
  3840. if (methodInstance->mChainType == BfMethodChainType_ChainMember)
  3841. {
  3842. BF_ASSERT(!methodInstance->GetOwner()->IsUnspecializedType());
  3843. // We need to create an empty thunk for this chained method
  3844. BfIRFunction func = CreateFunctionFrom(methodInstance, false, methodInstance->mAlwaysInline);
  3845. mBfIRBuilder->SetActiveFunction(func);
  3846. auto block = mBfIRBuilder->CreateBlock("entry", true);
  3847. mBfIRBuilder->SetInsertPoint(block);
  3848. mBfIRBuilder->CreateRetVoid();
  3849. mBfIRBuilder->SetActiveFunction(BfIRFunction());
  3850. }
  3851. }
  3852. }
  3853. SizedArray<BfIRValue, 32> vData;
  3854. BfIRValue classVDataVar;
  3855. String classVDataName;
  3856. if (typeInstance->mSlotNum >= 0)
  3857. {
  3858. // For interfaces we ONLY emit the slot num
  3859. int virtSlotIdx = typeInstance->mSlotNum + 1 + mCompiler->GetDynCastVDataCount();
  3860. StringT<128> slotVarName;
  3861. BfMangler::MangleStaticFieldName(slotVarName, mCompiler->GetMangleKind(), typeInstance, "sBfSlotOfs");
  3862. auto intType = GetPrimitiveType(BfTypeCode_Int32);
  3863. auto slotNumVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapType(intType), true, BfIRLinkageType_External,
  3864. GetConstValue32(virtSlotIdx), slotVarName);
  3865. }
  3866. else if ((typeInstance->IsObject()) && (!typeInstance->IsUnspecializedType()) && (needsVData))
  3867. {
  3868. int dynCastDataElems = 0;
  3869. int numElements = 1;
  3870. int vDataOfs = 1; // The number of intptrs before the iface slot map
  3871. numElements += mCompiler->mMaxInterfaceSlots;
  3872. if (!typeInstance->IsInterface())
  3873. {
  3874. dynCastDataElems = 1 + mCompiler->mMaxInterfaceSlots;
  3875. numElements += mCompiler->GetDynCastVDataCount();
  3876. numElements += typeInstance->mVirtualMethodTableSize;
  3877. }
  3878. int expectNumElements = 0;
  3879. if (!typeDef->mIsStatic)
  3880. {
  3881. classVDataVar = CreateClassVDataGlobal(typeInstance, &expectNumElements, &classVDataName);
  3882. }
  3883. vData.push_back(BfIRValue()); // Type*
  3884. SizedArray<BfIRValue, 1> extVTableData;
  3885. SizedArrayImpl<BfIRValue>* vFuncDataExt = &extVTableData;
  3886. if (!typeInstance->IsInterface())
  3887. {
  3888. Array<int32> dynCastData;
  3889. if (typeInstance->IsBoxed())
  3890. {
  3891. auto underlyingType = typeInstance->GetUnderlyingType()->ToTypeInstance();
  3892. dynCastData.Add(underlyingType->mInheritanceId);
  3893. }
  3894. else
  3895. dynCastData.Add(typeInstance->mInheritanceId);
  3896. for (int i = 0; i < mCompiler->mMaxInterfaceSlots; i++)
  3897. dynCastData.Add(0);
  3898. dynCastData.Add(0);
  3899. auto checkTypeInst = typeInstance;
  3900. while (checkTypeInst != NULL)
  3901. {
  3902. for (auto&& interfaceEntry : checkTypeInst->mInterfaces)
  3903. {
  3904. if (interfaceEntry.mInterfaceType->mSlotNum >= 0)
  3905. {
  3906. if (dynCastData[interfaceEntry.mInterfaceType->mSlotNum + 1] == 0)
  3907. dynCastData[interfaceEntry.mInterfaceType->mSlotNum + 1] = interfaceEntry.mInterfaceType->mTypeId;
  3908. }
  3909. }
  3910. checkTypeInst = checkTypeInst->GetImplBaseType();
  3911. }
  3912. if (mSystem->mPtrSize == 8)
  3913. {
  3914. int intPtrCount = (dynCastDataElems + 1) / 2;
  3915. vDataOfs += intPtrCount;
  3916. uint64* intPtrData = (uint64*)&dynCastData[0];
  3917. for (int i = 0; i < intPtrCount; i++)
  3918. {
  3919. uint64 val = intPtrData[i];
  3920. if (val == 0)
  3921. {
  3922. vData.push_back(voidPtrNull);
  3923. }
  3924. else
  3925. {
  3926. auto intPtrVal = mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, val);
  3927. vData.push_back(mBfIRBuilder->CreateBitCast(intPtrVal, voidPtrIRType));
  3928. }
  3929. }
  3930. }
  3931. else
  3932. {
  3933. int intPtrCount = dynCastDataElems;
  3934. vDataOfs += intPtrCount;
  3935. uint32* intPtrData = (uint32*)&dynCastData[0];
  3936. for (int i = 0; i < intPtrCount; i++)
  3937. {
  3938. uint32 val = intPtrData[i];
  3939. if (val == 0)
  3940. {
  3941. vData.push_back(voidPtrNull);
  3942. }
  3943. else
  3944. {
  3945. auto intPtrVal = mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, (int)val);
  3946. vData.push_back(mBfIRBuilder->CreateBitCast(intPtrVal, voidPtrIRType));
  3947. }
  3948. }
  3949. }
  3950. }
  3951. for (int iSlotIdx = 0; iSlotIdx < mCompiler->mMaxInterfaceSlots; iSlotIdx++)
  3952. vData.push_back(voidPtrNull);
  3953. struct _InterfaceMatchEntry
  3954. {
  3955. BfTypeInterfaceEntry* mEntry;
  3956. BfTypeInstance* mEntrySource;
  3957. Array<BfTypeInterfaceEntry*> mAmbiguousEntries;
  3958. };
  3959. int highestIFaceVirtIdx = 0;
  3960. Dictionary<BfTypeInstance*, _InterfaceMatchEntry> interfaceMap;
  3961. auto checkTypeInst = typeInstance;
  3962. bool forceInterfaceSet = false;
  3963. while (checkTypeInst != NULL)
  3964. {
  3965. for (auto&& interfaceEntry : checkTypeInst->mInterfaces)
  3966. {
  3967. highestIFaceVirtIdx = BF_MAX(highestIFaceVirtIdx, interfaceEntry.mStartVirtualIdx + interfaceEntry.mInterfaceType->mVirtualMethodTableSize);
  3968. if (!typeInstance->IsTypeMemberAccessible(interfaceEntry.mDeclaringType, mProject))
  3969. continue;
  3970. _InterfaceMatchEntry* matchEntry = NULL;
  3971. if (interfaceMap.TryGetValue(interfaceEntry.mInterfaceType, &matchEntry))
  3972. {
  3973. auto prevEntry = matchEntry->mEntry;
  3974. bool isBetter = TypeIsSubTypeOf(checkTypeInst, matchEntry->mEntrySource);
  3975. bool isWorse = TypeIsSubTypeOf(matchEntry->mEntrySource, checkTypeInst);
  3976. if (forceInterfaceSet)
  3977. {
  3978. isBetter = true;
  3979. isWorse = false;
  3980. }
  3981. if (isBetter == isWorse)
  3982. CompareDeclTypes(interfaceEntry.mDeclaringType, prevEntry->mDeclaringType, isBetter, isWorse);
  3983. if (isBetter == isWorse)
  3984. {
  3985. if (matchEntry->mAmbiguousEntries.empty())
  3986. matchEntry->mAmbiguousEntries.push_back(prevEntry);
  3987. matchEntry->mAmbiguousEntries.push_back(&interfaceEntry);
  3988. continue;
  3989. }
  3990. else if (isBetter)
  3991. {
  3992. matchEntry->mEntry = &interfaceEntry;
  3993. matchEntry->mEntrySource = checkTypeInst;
  3994. matchEntry->mAmbiguousEntries.Clear();
  3995. }
  3996. else
  3997. continue;
  3998. }
  3999. else
  4000. {
  4001. _InterfaceMatchEntry matchEntry;
  4002. matchEntry.mEntry = &interfaceEntry;
  4003. matchEntry.mEntrySource = checkTypeInst;
  4004. interfaceMap[interfaceEntry.mInterfaceType] = matchEntry;
  4005. }
  4006. }
  4007. checkTypeInst = checkTypeInst->GetImplBaseType();
  4008. }
  4009. for (auto interfacePair : interfaceMap)
  4010. {
  4011. auto& interfaceMatchEntry = interfacePair.mValue;
  4012. if (!interfaceMatchEntry.mAmbiguousEntries.empty())
  4013. {
  4014. 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());
  4015. if (error != NULL)
  4016. {
  4017. for (auto ambiguiousEntry : interfaceMatchEntry.mAmbiguousEntries)
  4018. mCompiler->mPassInstance->MoreInfo("See other declaration", ambiguiousEntry->mDeclaringType->GetRefNode());
  4019. }
  4020. }
  4021. }
  4022. if ((!typeInstance->IsInterface()) && (typeInstance->mVirtualMethodTableSize > 0) && (needsVData))
  4023. {
  4024. int startTabIdx = (int)vData.size();
  4025. SizedArray<BfTypeInstance*, 8> origVirtTypeStack;
  4026. BfTypeInstance* checkTypeInst = typeInstance;
  4027. while (checkTypeInst != NULL)
  4028. {
  4029. origVirtTypeStack.push_back(checkTypeInst);
  4030. checkTypeInst = checkTypeInst->GetImplBaseType();
  4031. }
  4032. Array<BfVirtualMethodEntry> origVTable;
  4033. int origVirtIdx = 0;
  4034. if (typeInstance->mTypeDef->mIsCombinedPartial)
  4035. {
  4036. HashSet<String> reslotNames;
  4037. for (int virtIdx = 0; virtIdx < (int)typeInstance->mVirtualMethodTable.size(); virtIdx++)
  4038. {
  4039. auto& entry = typeInstance->mVirtualMethodTable[virtIdx];
  4040. if (entry.mDeclaringMethod.mMethodNum == -1)
  4041. continue;
  4042. BfMethodInstance* methodInstance = (BfMethodInstance*)entry.mImplementingMethod;
  4043. if ((methodInstance == NULL) || (!typeInstance->IsTypeMemberAccessible(methodInstance->mMethodDef->mDeclaringType, mProject)))
  4044. {
  4045. if (origVTable.empty())
  4046. origVTable = typeInstance->mVirtualMethodTable;
  4047. BfMethodInstance* declMethodInstance = entry.mDeclaringMethod;
  4048. if (typeInstance->IsTypeMemberAccessible(declMethodInstance->mMethodDef->mDeclaringType, mProject))
  4049. {
  4050. // Prepare to reslot...
  4051. entry.mImplementingMethod = entry.mDeclaringMethod;
  4052. reslotNames.Add(declMethodInstance->mMethodDef->mName);
  4053. }
  4054. else
  4055. {
  4056. // Decl isn't accessible, null out entry
  4057. entry.mImplementingMethod = BfMethodRef();
  4058. }
  4059. }
  4060. }
  4061. if (!reslotNames.IsEmpty())
  4062. {
  4063. BfAmbiguityContext ambiguityContext;
  4064. ambiguityContext.mTypeInstance = typeInstance;
  4065. ambiguityContext.mModule = this;
  4066. ambiguityContext.mIsProjectSpecific = true;
  4067. ambiguityContext.mIsReslotting = true;
  4068. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  4069. for (auto& methodGroup : typeInstance->mMethodInstanceGroups)
  4070. {
  4071. auto methodInstance = methodGroup.mDefault;
  4072. if ((methodInstance == NULL) || (!methodInstance->mMethodDef->mIsOverride))
  4073. continue;
  4074. if (!reslotNames.Contains(methodInstance->mMethodDef->mName))
  4075. continue;
  4076. if (!typeInstance->IsTypeMemberAccessible(methodInstance->mMethodDef->mDeclaringType, mProject))
  4077. continue;
  4078. if ((methodInstance->mChainType != BfMethodChainType_None) && (methodInstance->mChainType != BfMethodChainType_ChainHead))
  4079. continue;
  4080. SlotVirtualMethod(methodInstance, &ambiguityContext);
  4081. }
  4082. ambiguityContext.Finish();
  4083. }
  4084. }
  4085. bool isInExts = false;
  4086. for (int virtIdx = 0; virtIdx < (int)typeInstance->mVirtualMethodTable.size(); virtIdx++)
  4087. {
  4088. BfIRValue vValue = voidPtrNull;
  4089. auto& entry = typeInstance->mVirtualMethodTable[virtIdx];
  4090. BfModuleMethodInstance moduleMethodInst;
  4091. if (entry.mDeclaringMethod.mMethodNum == -1)
  4092. {
  4093. // mMethodNum of -1 indicates a vExt slot rather than an actual method reference
  4094. isInExts = true;
  4095. BfIRValue vExt = CreateClassVDataExtGlobal(entry.mDeclaringMethod.mTypeInstance, typeInstance, virtIdx);
  4096. if (vExt)
  4097. vValue = mBfIRBuilder->CreateBitCast(vExt, voidPtrIRType);
  4098. }
  4099. else
  4100. {
  4101. BfMethodInstance* declaringMethodInstance = (BfMethodInstance*)entry.mDeclaringMethod;
  4102. if ((declaringMethodInstance != NULL) && (declaringMethodInstance->mMethodInstanceGroup->IsImplemented()) && (declaringMethodInstance->mIsReified))
  4103. {
  4104. BF_ASSERT(entry.mImplementingMethod.mTypeInstance->mMethodInstanceGroups[entry.mImplementingMethod.mMethodNum].IsImplemented());
  4105. BF_ASSERT(entry.mImplementingMethod.mTypeInstance->mMethodInstanceGroups[entry.mImplementingMethod.mMethodNum].mDefault->mIsReified);
  4106. BfMethodInstance* methodInstance = (BfMethodInstance*)entry.mImplementingMethod;
  4107. if ((methodInstance != NULL) && (!methodInstance->mMethodDef->mIsAbstract))
  4108. {
  4109. BF_ASSERT(typeInstance->IsTypeMemberAccessible(methodInstance->mMethodDef->mDeclaringType, mProject));
  4110. moduleMethodInst = GetMethodInstanceAtIdx(methodInstance->mMethodInstanceGroup->mOwner, methodInstance->mMethodInstanceGroup->mMethodIdx);
  4111. auto funcPtr = mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, voidPtrIRType);
  4112. vValue = funcPtr;
  4113. }
  4114. }
  4115. }
  4116. while (origVirtTypeStack.size() != 0)
  4117. {
  4118. BfTypeInstance* useTypeInst = origVirtTypeStack[origVirtTypeStack.size() - 1];
  4119. if (virtIdx >= useTypeInst->mVirtualMethodTableSize)
  4120. {
  4121. // Moved past current base vtable size
  4122. origVirtTypeStack.pop_back();
  4123. continue;
  4124. }
  4125. if (origVirtIdx < useTypeInst->GetOrigVTableSize())
  4126. {
  4127. // We are within the original vtable size
  4128. int idx = startTabIdx + origVirtIdx;
  4129. origVirtIdx++;
  4130. vData.push_back(vValue);
  4131. }
  4132. else
  4133. {
  4134. // This is a new entry, it only gets added to the ext
  4135. BF_ASSERT(isInExts);
  4136. }
  4137. break;
  4138. }
  4139. }
  4140. if (!origVTable.empty())
  4141. typeInstance->mVirtualMethodTable = origVTable;
  4142. }
  4143. int ifaceMethodExtStart = (int)typeInstance->GetIFaceVMethodSize();
  4144. if (typeInstance->mHotTypeData != NULL)
  4145. {
  4146. if (typeInstance->mHotTypeData->mOrigInterfaceMethodsLength != -1)
  4147. ifaceMethodExtStart = typeInstance->mHotTypeData->mOrigInterfaceMethodsLength;
  4148. }
  4149. SizedArray<BfIRValue, 32> ifaceMethodExtData;
  4150. int iFaceMethodStartIdx = (int)vData.size();
  4151. vData.resize(iFaceMethodStartIdx + ifaceMethodExtStart);
  4152. for (int i = iFaceMethodStartIdx; i < iFaceMethodStartIdx + ifaceMethodExtStart; i++)
  4153. vData[i] = voidPtrNull;
  4154. if (expectNumElements != 0)
  4155. BF_ASSERT(expectNumElements == vData.size());
  4156. //BF_ASSERT(vData.size() == expectNumElements);
  4157. // for (int i = 0; i < (int)typeInstance->mInterfaceMethodTable.size() - ifaceMethodExtStart; i++)
  4158. // ifaceMethodExtData.Add(voidPtrNull);
  4159. int ifaceEntryIdx = iFaceMethodStartIdx;
  4160. for (auto& interfacePair : interfaceMap)
  4161. {
  4162. auto interfaceEntry = interfacePair.mValue.mEntry;
  4163. bool makeEmpty = false;
  4164. if (!typeInstance->IsTypeMemberAccessible(interfaceEntry->mDeclaringType, mProject))
  4165. makeEmpty = true;
  4166. int endVirtualIdx = interfaceEntry->mStartVirtualIdx + interfaceEntry->mInterfaceType->mVirtualMethodTableSize;
  4167. bool useExt = endVirtualIdx > ifaceMethodExtStart;
  4168. for (int methodIdx = 0; methodIdx < (int)interfaceEntry->mInterfaceType->mMethodInstanceGroups.size(); methodIdx++)
  4169. {
  4170. BfIRValue pushValue;
  4171. BfMethodInstance* ifaceMethodInstance = interfaceEntry->mInterfaceType->mMethodInstanceGroups[methodIdx].mDefault;
  4172. if ((ifaceMethodInstance == NULL) || (ifaceMethodInstance->mVirtualTableIdx == -1))
  4173. continue;
  4174. if ((!ifaceMethodInstance->mIsReified) || (!ifaceMethodInstance->mMethodInstanceGroup->IsImplemented()))
  4175. continue;
  4176. if (makeEmpty)
  4177. {
  4178. pushValue = voidPtrNull;
  4179. }
  4180. else
  4181. {
  4182. auto& methodRef = typeInstance->mInterfaceMethodTable[interfaceEntry->mStartInterfaceTableIdx + methodIdx].mMethodRef;
  4183. auto methodInstance = (BfMethodInstance*)methodRef;
  4184. if ((methodInstance != NULL) && (!methodInstance->mMethodDef->mIsAbstract))
  4185. {
  4186. BF_ASSERT(methodInstance->mIsReified);
  4187. // This doesn't work because we may have FOREIGN methods from implicit interface methods
  4188. //auto moduleMethodInst = GetMethodInstanceAtIdx(methodRef.mTypeInstance, methodRef.mMethodNum);
  4189. auto moduleMethodInst = ReferenceExternalMethodInstance(methodInstance);
  4190. auto funcPtr = mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, voidPtrIRType);
  4191. pushValue = funcPtr;
  4192. }
  4193. else
  4194. {
  4195. pushValue = voidPtrNull;
  4196. }
  4197. }
  4198. int idx = interfaceEntry->mStartVirtualIdx + ifaceMethodInstance->mVirtualTableIdx;
  4199. if (idx < ifaceMethodExtStart)
  4200. {
  4201. BF_ASSERT(iFaceMethodStartIdx + idx < (int)vData.size());
  4202. vData[iFaceMethodStartIdx + idx] = pushValue;
  4203. }
  4204. else
  4205. {
  4206. BF_ASSERT(useExt);
  4207. int extIdx = idx - ifaceMethodExtStart;
  4208. while (extIdx >= ifaceMethodExtData.size())
  4209. ifaceMethodExtData.Add(voidPtrNull);
  4210. ifaceMethodExtData[extIdx] = pushValue;
  4211. }
  4212. }
  4213. }
  4214. if (typeInstance->IsBoxed())
  4215. {
  4216. BfBoxedType* boxedType = (BfBoxedType*)typeInstance;
  4217. if (boxedType->IsBoxedStructPtr())
  4218. {
  4219. // Force override of GetHashCode so we use the pointer address as the hash code
  4220. checkTypeInst = CreateBoxedType(ResolveTypeDef(mCompiler->mPointerTypeDef));
  4221. // Force override of GetHashCode so we use the pointer address as the hash code
  4222. for (auto& checkIFace : checkTypeInst->mInterfaces)
  4223. {
  4224. for (int methodIdx = 0; methodIdx < (int)checkIFace.mInterfaceType->mMethodInstanceGroups.size(); methodIdx++)
  4225. {
  4226. BfIRValue pushValue;
  4227. BfMethodInstance* ifaceMethodInstance = checkIFace.mInterfaceType->mMethodInstanceGroups[methodIdx].mDefault;
  4228. if ((ifaceMethodInstance == NULL) || (ifaceMethodInstance->mVirtualTableIdx == -1))
  4229. continue;
  4230. if ((!ifaceMethodInstance->mIsReified) || (!ifaceMethodInstance->mMethodInstanceGroup->IsImplemented()))
  4231. continue;
  4232. auto& methodRef = checkTypeInst->mInterfaceMethodTable[checkIFace.mStartInterfaceTableIdx + methodIdx].mMethodRef;
  4233. auto methodInstance = (BfMethodInstance*)methodRef;
  4234. BF_ASSERT(methodInstance->mIsReified);
  4235. // This doesn't work because we may have FOREIGN methods from implicit interface methods
  4236. //auto moduleMethodInst = GetMethodInstanceAtIdx(methodRef.mTypeInstance, methodRef.mMethodNum);
  4237. auto moduleMethodInst = ReferenceExternalMethodInstance(methodInstance);
  4238. auto funcPtr = mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, voidPtrIRType);
  4239. int idx = checkIFace.mStartVirtualIdx + ifaceMethodInstance->mVirtualTableIdx;
  4240. vData[iFaceMethodStartIdx + idx] = funcPtr;
  4241. }
  4242. }
  4243. }
  4244. }
  4245. if ((needsVData) && (!typeInstance->mTypeDef->mIsStatic))
  4246. {
  4247. BfIRValue ifaceMethodExtVar;
  4248. if (!ifaceMethodExtData.IsEmpty())
  4249. {
  4250. StringT<128> classVDataName;
  4251. BfMangler::MangleStaticFieldName(classVDataName, mCompiler->GetMangleKind(), typeInstance, "bf_hs_replace_IFaceExt");
  4252. auto arrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr), (int)ifaceMethodExtData.size());
  4253. ifaceMethodExtVar = mBfIRBuilder->CreateGlobalVariable(arrayType, true,
  4254. BfIRLinkageType_External, BfIRValue(), classVDataName);
  4255. BfIRType extVTableType = mBfIRBuilder->GetSizedArrayType(voidPtrIRType, (int)ifaceMethodExtData.size());
  4256. BfIRValue extVTableConst = mBfIRBuilder->CreateConstArray(extVTableType, ifaceMethodExtData);
  4257. mBfIRBuilder->GlobalVar_SetInitializer(ifaceMethodExtVar, extVTableConst);
  4258. }
  4259. for (auto& ifaceInstPair : interfaceMap)
  4260. {
  4261. auto interfaceEntry = ifaceInstPair.mValue.mEntry;
  4262. int slotNum = interfaceEntry->mInterfaceType->mSlotNum;
  4263. if (slotNum >= 0)
  4264. {
  4265. BfIRValue vtablePtr;
  4266. int idx = interfaceEntry->mStartVirtualIdx;
  4267. int endVirtualIdx = interfaceEntry->mStartVirtualIdx + interfaceEntry->mInterfaceType->mVirtualMethodTableSize;
  4268. if (endVirtualIdx > ifaceMethodExtStart)
  4269. vtablePtr = mBfIRBuilder->CreateInBoundsGEP(ifaceMethodExtVar, 0, interfaceEntry->mStartVirtualIdx - ifaceMethodExtStart);
  4270. else
  4271. vtablePtr = mBfIRBuilder->CreateInBoundsGEP(classVDataVar, 0, iFaceMethodStartIdx + interfaceEntry->mStartVirtualIdx);
  4272. int slotVirtIdx = slotNum + vDataOfs;
  4273. if (vData[slotVirtIdx] == voidPtrNull)
  4274. {
  4275. vData[slotVirtIdx] = mBfIRBuilder->CreateBitCast(vtablePtr, voidPtrIRType);
  4276. }
  4277. else
  4278. {
  4279. if (mCompiler->IsHotCompile())
  4280. Fail("Interface slot collision error. Restart program or undo interface changes.", typeDef->GetRefNode());
  4281. else
  4282. Fail("Interface slot collision error", typeDef->GetRefNode());
  4283. }
  4284. }
  4285. }
  4286. }
  4287. }
  4288. BfIRValue typeNameConst;
  4289. BfIRValue namespaceConst;
  4290. if (needsTypeNames)
  4291. {
  4292. typeNameConst = GetStringObjectValue(typeDef->mName->mString, true);
  4293. namespaceConst = GetStringObjectValue(typeDef->mNamespace.ToString(), true);
  4294. }
  4295. else
  4296. {
  4297. auto stringType = ResolveTypeDef(mCompiler->mStringTypeDef);
  4298. typeNameConst = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(stringType));
  4299. namespaceConst = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(stringType));
  4300. }
  4301. int baseTypeId = 0;
  4302. if (typeInstance->mBaseType != NULL)
  4303. {
  4304. baseTypeId = typeInstance->mBaseType->mTypeId;
  4305. }
  4306. SizedArray<BfIRValue, 16> customAttrs;
  4307. BfTypeInstance* attributeType = mContext->mUnreifiedModule->ResolveTypeDef(mCompiler->mAttributeTypeDef)->ToTypeInstance();
  4308. BfIRValue castedClassVData;
  4309. if (classVDataVar)
  4310. castedClassVData = mBfIRBuilder->CreateBitCast(classVDataVar, mBfIRBuilder->MapType(mContext->mBfClassVDataPtrType));
  4311. else
  4312. castedClassVData = GetDefaultValue(mContext->mBfClassVDataPtrType);
  4313. bool freflectIncludeTypeData = false;
  4314. bool reflectIncludeAllFields = false;
  4315. bool reflectIncludeAllMethods = false;
  4316. if (TypeIsSubTypeOf(typeInstance, attributeType))
  4317. {
  4318. reflectIncludeAllFields = true;
  4319. reflectIncludeAllMethods = true;
  4320. }
  4321. enum ReflectKind
  4322. {
  4323. ReflectKind_None = 0,
  4324. ReflectKind_Type = 1,
  4325. ReflectKind_NonStaticFields = 2,
  4326. ReflectKind_StaticFields = 4,
  4327. ReflectKind_DefaultConstructor = 8,
  4328. ReflectKind_Constructors = 0x10,
  4329. ReflectKind_StaticMethods = 0x20,
  4330. ReflectKind_Methods = 0x40,
  4331. ReflectKind_User = 0x80,
  4332. ReflectKind_All = 0x7F,
  4333. ReflectKind_ApplyToInnerTypes = 0x80
  4334. };
  4335. ReflectKind reflectKind = ReflectKind_Type;
  4336. auto _GetReflectUser = [&](BfTypeInstance* attrType)
  4337. {
  4338. ReflectKind reflectKind = ReflectKind_None;
  4339. if (attrType->mCustomAttributes != NULL)
  4340. {
  4341. for (auto& customAttr : attrType->mCustomAttributes->mAttributes)
  4342. {
  4343. if (customAttr.mType->mTypeDef->mName->ToString() == "AttributeUsageAttribute")
  4344. {
  4345. for (auto& prop : customAttr.mSetProperties)
  4346. {
  4347. auto propDef = prop.mPropertyRef.mTypeInstance->mTypeDef->mProperties[prop.mPropertyRef.mPropIdx];
  4348. if (propDef->mName == "ReflectUser")
  4349. {
  4350. if (prop.mParam.mValue.IsConst())
  4351. {
  4352. auto constant = attrType->mConstHolder->GetConstant(prop.mParam.mValue);
  4353. reflectKind = (ReflectKind)(reflectKind | (ReflectKind)constant->mInt32);
  4354. }
  4355. }
  4356. }
  4357. // Check for Flags arg
  4358. if (customAttr.mCtorArgs.size() < 2)
  4359. continue;
  4360. auto constant = attrType->mConstHolder->GetConstant(customAttr.mCtorArgs[1]);
  4361. if (constant == NULL)
  4362. continue;
  4363. if (constant->mTypeCode == BfTypeCode_Boolean)
  4364. continue;
  4365. if ((constant->mInt8 & BfCustomAttributeFlags_ReflectAttribute) != 0)
  4366. reflectKind = (ReflectKind)(reflectKind | ReflectKind_User);
  4367. }
  4368. }
  4369. }
  4370. return reflectKind;
  4371. };
  4372. auto _GetReflectUserFromDirective = [&](BfAttributeDirective* attributesDirective, BfAttributeTargets attrTarget)
  4373. {
  4374. ReflectKind reflectKind = ReflectKind_None;
  4375. auto customAttrs = GetCustomAttributes(attributesDirective, attrTarget);
  4376. if (customAttrs != NULL)
  4377. {
  4378. for (auto& attr : customAttrs->mAttributes)
  4379. {
  4380. reflectKind = (ReflectKind)(reflectKind | _GetReflectUser(attr.mType));
  4381. }
  4382. }
  4383. return reflectKind;
  4384. };
  4385. //
  4386. {
  4387. auto checkTypeInstance = typeInstance;
  4388. while (checkTypeInstance != NULL)
  4389. {
  4390. if (checkTypeInstance->mCustomAttributes != NULL)
  4391. {
  4392. auto checkReflectKind = ReflectKind_None;
  4393. for (auto& customAttr : checkTypeInstance->mCustomAttributes->mAttributes)
  4394. {
  4395. if (customAttr.mType->mTypeDef->mName->ToString() == "ReflectAttribute")
  4396. {
  4397. if (customAttr.mCtorArgs.size() > 0)
  4398. {
  4399. auto constant = checkTypeInstance->mConstHolder->GetConstant(customAttr.mCtorArgs[0]);
  4400. checkReflectKind = (ReflectKind)((int)checkReflectKind | constant->mInt32);
  4401. }
  4402. else
  4403. {
  4404. checkReflectKind = ReflectKind_All;
  4405. }
  4406. }
  4407. else
  4408. {
  4409. auto userReflectKind = _GetReflectUser(customAttr.mType);
  4410. checkReflectKind = (ReflectKind)(checkReflectKind | userReflectKind);
  4411. }
  4412. }
  4413. if ((checkTypeInstance == typeInstance) ||
  4414. ((checkReflectKind & ReflectKind_ApplyToInnerTypes) != 0))
  4415. {
  4416. reflectKind = (ReflectKind)(reflectKind | checkReflectKind);
  4417. }
  4418. }
  4419. checkTypeInstance = GetOuterType(checkTypeInstance);
  4420. }
  4421. }
  4422. // Fields
  4423. BfType* reflectFieldDataType = ResolveTypeDef(mCompiler->mReflectFieldDataDef);
  4424. BfIRValue emptyValueType = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(reflectFieldDataType->ToTypeInstance()->mBaseType), SizedArray<BfIRValue, 1>());
  4425. auto _HandleCustomAttrs = [&](BfCustomAttributes* customAttributes)
  4426. {
  4427. if (customAttributes == NULL)
  4428. return -1;
  4429. Array<BfCustomAttribute*> reflectAttributes;
  4430. for (auto& attr : customAttributes->mAttributes)
  4431. {
  4432. bool wantAttribute = false;
  4433. if (attr.mType->mCustomAttributes != NULL)
  4434. {
  4435. auto usageAttribute = attr.mType->mCustomAttributes->Get(mCompiler->mAttributeUsageAttributeTypeDef);
  4436. if (usageAttribute != NULL)
  4437. {
  4438. // Check for Flags arg
  4439. if (usageAttribute->mCtorArgs.size() < 2)
  4440. continue;
  4441. auto constant = attr.mType->mConstHolder->GetConstant(usageAttribute->mCtorArgs[1]);
  4442. if (constant == NULL)
  4443. continue;
  4444. if (constant->mTypeCode == BfTypeCode_Boolean)
  4445. continue;
  4446. if ((constant->mInt8 & BfCustomAttributeFlags_ReflectAttribute) != 0)
  4447. wantAttribute = true;
  4448. }
  4449. }
  4450. if ((wantAttribute) && (attr.mType->mIsReified))
  4451. {
  4452. reflectAttributes.Add(&attr);
  4453. }
  4454. }
  4455. if (reflectAttributes.size() == 0)
  4456. return -1;
  4457. #define PUSH_INT8(val) data.push_back((uint8)val)
  4458. #define PUSH_INT16(val) { data.push_back(val & 0xFF); data.push_back((val >> 8) & 0xFF); }
  4459. #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); }
  4460. #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); \
  4461. data.push_back((val >> 32) & 0xFF); data.push_back((val >> 40) & 0xFF); data.push_back((val >> 48) & 0xFF); data.push_back((val >> 56) & 0xFF); }
  4462. SizedArray<uint8, 16> data;
  4463. int customAttrIdx = (int)customAttrs.size();
  4464. data.push_back((uint8)reflectAttributes.size());
  4465. for (auto attr : reflectAttributes)
  4466. {
  4467. // Size prefix
  4468. int sizeIdx = (int)data.size();
  4469. PUSH_INT16(0); // mSize
  4470. PUSH_INT32(attr->mType->mTypeId); // mType
  4471. PUSH_INT16(attr->mCtor->mIdx);
  4472. auto ctorMethodInstance = GetRawMethodInstanceAtIdx(attr->mType, attr->mCtor->mIdx);
  4473. int argIdx = 0;
  4474. for (auto arg : attr->mCtorArgs)
  4475. {
  4476. auto constant = typeInstance->mConstHolder->GetConstant(arg);
  4477. bool handled = false;
  4478. if (constant != NULL)
  4479. {
  4480. auto argType = ctorMethodInstance->GetParamType(argIdx);
  4481. if (argType->IsObject())
  4482. {
  4483. BF_ASSERT(argType->ToTypeInstance()->mTypeDef == mCompiler->mStringTypeDef);
  4484. int stringId = constant->mInt32;
  4485. int* orderedIdPtr;
  4486. if (usedStringIdMap.TryAdd(stringId, NULL, &orderedIdPtr))
  4487. {
  4488. *orderedIdPtr = (int)usedStringIdMap.size() - 1;
  4489. }
  4490. GetStringObjectValue(stringId);
  4491. PUSH_INT8(0xFF); // String
  4492. PUSH_INT32(*orderedIdPtr);
  4493. continue;
  4494. }
  4495. PUSH_INT8(constant->mTypeCode);
  4496. if ((constant->mTypeCode == BfTypeCode_Int64) ||
  4497. (constant->mTypeCode == BfTypeCode_UInt64) ||
  4498. (constant->mTypeCode == BfTypeCode_Double))
  4499. {
  4500. PUSH_INT64(constant->mInt64);
  4501. }
  4502. else if ((constant->mTypeCode == BfTypeCode_Int32) ||
  4503. (constant->mTypeCode == BfTypeCode_UInt32))
  4504. {
  4505. PUSH_INT32(constant->mInt32);
  4506. }
  4507. else if (constant->mTypeCode == BfTypeCode_Single)
  4508. {
  4509. float val = (float)constant->mDouble;
  4510. PUSH_INT32(*(int*)&val);
  4511. }
  4512. else if ((constant->mTypeCode == BfTypeCode_Int16) ||
  4513. (constant->mTypeCode == BfTypeCode_UInt16))
  4514. {
  4515. PUSH_INT16(constant->mInt16);
  4516. }
  4517. else if ((constant->mTypeCode == BfTypeCode_Int8) ||
  4518. (constant->mTypeCode == BfTypeCode_UInt8))
  4519. {
  4520. PUSH_INT8(constant->mInt8);
  4521. }
  4522. else if (constant->mTypeCode == BfTypeCode_Object)
  4523. {
  4524. BF_FATAL("Unhandled");
  4525. }
  4526. else
  4527. {
  4528. BF_FATAL("Unhandled");
  4529. }
  4530. }
  4531. else if (!handled)
  4532. {
  4533. BF_FATAL("Unhandled");
  4534. }
  4535. argIdx++;
  4536. }
  4537. int size = (int)data.size() - sizeIdx;
  4538. *((uint16*)&data[sizeIdx]) = size;
  4539. }
  4540. #undef PUSH_INT8
  4541. #undef PUSH_INT16
  4542. #undef PUSH_INT32
  4543. SizedArray<BfIRValue, 16> dataValues;
  4544. for (uint8 val : data)
  4545. dataValues.push_back(GetConstValue8(val));
  4546. auto dataArrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->MapType(byteType), (int)data.size());
  4547. auto customAttrConst = mBfIRBuilder->CreateConstArray(dataArrayType, dataValues);
  4548. BfIRValue customAttrArray = mBfIRBuilder->CreateGlobalVariable(dataArrayType, true, BfIRLinkageType_Internal,
  4549. customAttrConst, typeDataName + StrFormat(".customAttr%d", customAttrIdx));
  4550. BfIRValue customAttrArrayPtr = mBfIRBuilder->CreateBitCast(customAttrArray, voidPtrIRType);
  4551. customAttrs.push_back(customAttrArrayPtr);
  4552. return customAttrIdx;
  4553. };
  4554. int typeCustomAttrIdx = _HandleCustomAttrs(typeInstance->mCustomAttributes);
  4555. SizedArray<int, 16> reflectFieldIndices;
  4556. for (int pass = 0; pass < 2; pass++)
  4557. {
  4558. bool skippedField = false;
  4559. reflectFieldIndices.clear();
  4560. for (int fieldIdx = 0; fieldIdx < (int)typeInstance->mFieldInstances.size(); fieldIdx++)
  4561. {
  4562. BfFieldInstance* fieldInstance = &typeInstance->mFieldInstances[fieldIdx];
  4563. BfFieldDef* fieldDef = fieldInstance->GetFieldDef();
  4564. if (fieldDef == NULL)
  4565. continue;
  4566. auto fieldReflectKind = (ReflectKind)(reflectKind & ~ReflectKind_User);
  4567. bool includeField = reflectIncludeAllFields;
  4568. if (fieldInstance->mCustomAttributes != NULL)
  4569. {
  4570. for (auto& customAttr : fieldInstance->mCustomAttributes->mAttributes)
  4571. {
  4572. if (customAttr.mType->mTypeDef->mName->ToString() == "ReflectAttribute")
  4573. {
  4574. includeField = true;
  4575. }
  4576. else
  4577. {
  4578. auto userReflectKind = _GetReflectUser(customAttr.mType);
  4579. fieldReflectKind = (ReflectKind)(fieldReflectKind | userReflectKind);
  4580. }
  4581. }
  4582. }
  4583. if ((fieldReflectKind & ReflectKind_User) != 0)
  4584. includeField = true;
  4585. if ((!fieldDef->mIsStatic) && ((fieldReflectKind & ReflectKind_NonStaticFields) != 0))
  4586. includeField = true;
  4587. if ((fieldDef->mIsStatic) && ((fieldReflectKind & ReflectKind_StaticFields) != 0))
  4588. includeField = true;
  4589. includeField |= forceReflectFields;
  4590. if (!includeField)
  4591. {
  4592. skippedField = true;
  4593. continue;
  4594. }
  4595. reflectFieldIndices.Add(fieldIdx);
  4596. }
  4597. // For a splattable type, we need to either include all fields or zero fields. This is to allow us to correctly splat
  4598. // params for reflected method calls even if we don't have reflection field info for the splatted type. This is
  4599. // possible because we write out a SplatData structure containing just TypeIds in that case
  4600. if (pass == 0)
  4601. {
  4602. if (!typeInstance->IsSplattable())
  4603. break;
  4604. if (!skippedField)
  4605. break;
  4606. if (reflectFieldIndices.size() == 0)
  4607. break;
  4608. }
  4609. }
  4610. SizedArray<BfIRValue, 16> fieldTypes;
  4611. enum FieldFlags
  4612. {
  4613. FieldFlags_Protected = 3,
  4614. FieldFlags_Public = 6,
  4615. FieldFlags_Static = 0x10,
  4616. FieldFlags_Const = 0x40,
  4617. FieldFlags_SpecialName = 0x80,
  4618. FieldFlags_EnumPayload = 0x100,
  4619. FieldFlags_EnumDiscriminator = 0x200
  4620. };
  4621. if ((typeInstance->IsPayloadEnum()) && (!typeInstance->IsBoxed()))
  4622. {
  4623. BfType* payloadType = typeInstance->GetUnionInnerType();
  4624. if (!payloadType->IsValuelessType())
  4625. {
  4626. BfIRValue payloadNameConst = GetStringObjectValue("$payload", true);
  4627. SizedArray<BfIRValue, 8> payloadFieldVals =
  4628. {
  4629. emptyValueType,
  4630. payloadNameConst, // mName
  4631. GetConstValue(0, longType), // mConstValue
  4632. GetConstValue(0, intType), // mDataOffset
  4633. GetConstValue(payloadType->mTypeId, typeIdType), // mFieldTypeId
  4634. GetConstValue(FieldFlags_SpecialName | FieldFlags_EnumPayload, shortType), // mFlags
  4635. GetConstValue(-1, intType), // mCustomAttributesIdx
  4636. };
  4637. auto payloadFieldData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(reflectFieldDataType->ToTypeInstance(), BfIRPopulateType_Full), payloadFieldVals);
  4638. fieldTypes.push_back(payloadFieldData);
  4639. }
  4640. BfType* dscrType = typeInstance->GetDiscriminatorType();
  4641. BfIRValue dscrNameConst = GetStringObjectValue("$discriminator", true);
  4642. SizedArray<BfIRValue, 8> dscrFieldVals =
  4643. {
  4644. emptyValueType,
  4645. dscrNameConst, // mName
  4646. GetConstValue(0, longType), // mConstValue
  4647. GetConstValue(BF_ALIGN(payloadType->mSize, dscrType->mAlign), intType), // mDataOffset
  4648. GetConstValue(dscrType->mTypeId, typeIdType), // mFieldTypeId
  4649. GetConstValue(FieldFlags_SpecialName | FieldFlags_EnumDiscriminator, shortType), // mFlags
  4650. GetConstValue(-1, intType), // mCustomAttributesIdx
  4651. };
  4652. auto dscrFieldData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(reflectFieldDataType->ToTypeInstance(), BfIRPopulateType_Full), dscrFieldVals);
  4653. fieldTypes.push_back(dscrFieldData);
  4654. }
  4655. for (auto fieldIdx : reflectFieldIndices)
  4656. {
  4657. if (!needsTypeData)
  4658. break;
  4659. BfFieldInstance* fieldInstance = &typeInstance->mFieldInstances[fieldIdx];
  4660. BfFieldDef* fieldDef = fieldInstance->GetFieldDef();
  4661. BfIRValue fieldNameConst = GetStringObjectValue(fieldDef->mName, true);
  4662. int typeId = 0;
  4663. auto fieldType = fieldInstance->GetResolvedType();
  4664. if (fieldType->IsGenericParam())
  4665. {
  4666. //TODO:
  4667. }
  4668. else
  4669. typeId = fieldType->mTypeId;
  4670. FieldFlags fieldFlags = (FieldFlags)0;
  4671. if (fieldDef->mProtection == BfProtection_Protected)
  4672. fieldFlags = (FieldFlags)(fieldFlags | FieldFlags_Protected);
  4673. if (fieldDef->mProtection == BfProtection_Public)
  4674. fieldFlags = (FieldFlags)(fieldFlags | FieldFlags_Public);
  4675. if (fieldDef->mIsStatic)
  4676. fieldFlags = (FieldFlags)(fieldFlags | FieldFlags_Static);
  4677. if (fieldDef->mIsConst)
  4678. fieldFlags = (FieldFlags)(fieldFlags | FieldFlags_Const);
  4679. int customAttrIdx = _HandleCustomAttrs(fieldInstance->mCustomAttributes);
  4680. BfIRValue constValue = GetConstValue(0, longType);
  4681. if (fieldInstance->GetFieldDef()->mIsConst)
  4682. {
  4683. if (fieldInstance->mConstIdx != -1)
  4684. {
  4685. auto constant = typeInstance->mConstHolder->GetConstantById(fieldInstance->mConstIdx);
  4686. constValue = mBfIRBuilder->CreateConst(BfTypeCode_UInt64, constant->mUInt64);
  4687. }
  4688. }
  4689. SizedArray<BfIRValue, 8> fieldVals =
  4690. {
  4691. emptyValueType,
  4692. fieldNameConst, // mName
  4693. constValue, // mConstValue
  4694. GetConstValue(fieldInstance->mDataOffset, intType), // mDataOffset
  4695. GetConstValue(typeId, typeIdType), // mFieldTypeId
  4696. GetConstValue(fieldFlags, shortType), // mFlags
  4697. GetConstValue(customAttrIdx, intType), // mCustomAttributesIdx
  4698. };
  4699. auto fieldData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(reflectFieldDataType->ToTypeInstance(), BfIRPopulateType_Full), fieldVals);
  4700. fieldTypes.push_back(fieldData);
  4701. }
  4702. auto reflectFieldDataIRType = mBfIRBuilder->MapType(reflectFieldDataType);
  4703. BfIRValue fieldDataPtr;
  4704. BfIRType fieldDataPtrType = mBfIRBuilder->GetPointerTo(reflectFieldDataIRType);
  4705. if (fieldTypes.size() == 0)
  4706. {
  4707. if ((type->IsSplattable()) && (type->IsStruct()) && (!type->IsValuelessType()))
  4708. {
  4709. BfTypeInstance* reflectFieldSplatDataType = ResolveTypeDef(mCompiler->mReflectFieldSplatDataDef)->ToTypeInstance();
  4710. SizedArray<BfIRValue, 3> splatTypes;
  4711. SizedArray<BfIRValue, 3> splatOffsets;
  4712. std::function<void(BfType*, int)> _CheckSplat = [&](BfType* checkType, int offset)
  4713. {
  4714. auto checkTypeInstance = checkType->ToTypeInstance();
  4715. if ((checkTypeInstance != NULL) && (checkTypeInstance->IsValueType()) && (checkTypeInstance->IsDataIncomplete()))
  4716. PopulateType(checkTypeInstance);
  4717. if (checkType->IsStruct())
  4718. {
  4719. int dataEnd = offset;
  4720. if (checkTypeInstance->mBaseType != NULL)
  4721. _CheckSplat(checkTypeInstance->mBaseType, offset);
  4722. if (checkTypeInstance->mIsUnion)
  4723. {
  4724. BfType* unionInnerType = checkTypeInstance->GetUnionInnerType();
  4725. _CheckSplat(unionInnerType, offset);
  4726. }
  4727. else
  4728. {
  4729. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  4730. {
  4731. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  4732. if (fieldInstance->mDataIdx >= 0)
  4733. {
  4734. _CheckSplat(fieldInstance->GetResolvedType(), offset + fieldInstance->mDataOffset);
  4735. dataEnd = offset + fieldInstance->mDataOffset + fieldInstance->mResolvedType->mSize;
  4736. }
  4737. }
  4738. }
  4739. if (checkTypeInstance->IsEnum())
  4740. {
  4741. // Add discriminator
  4742. auto dscrType = checkTypeInstance->GetDiscriminatorType();
  4743. if (!checkTypeInstance->mIsPacked)
  4744. dataEnd = BF_ALIGN(dataEnd, dscrType->mAlign);
  4745. _CheckSplat(dscrType, dataEnd);
  4746. }
  4747. }
  4748. else if (checkType->IsMethodRef())
  4749. {
  4750. // auto methodRefType = (BfMethodRefType*)checkType;
  4751. // for (int dataIdx = 0; dataIdx < methodRefType->GetCaptureDataCount(); dataIdx++)
  4752. // {
  4753. // if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  4754. // _CheckSplat(methodRefType->GetCaptureType(dataIdx), offsetof);
  4755. // else
  4756. // dataLambda(methodRefType->GetCaptureType(dataIdx));
  4757. // }
  4758. }
  4759. else if (!checkType->IsValuelessType())
  4760. {
  4761. splatTypes.Add(GetConstValue(checkType->mTypeId, typeIdType));
  4762. splatOffsets.Add(GetConstValue(offset, intType));
  4763. }
  4764. };
  4765. _CheckSplat(type, 0);
  4766. while (splatTypes.size() < 3)
  4767. {
  4768. splatTypes.Add(GetConstValue(0, typeIdType));
  4769. splatOffsets.Add(GetConstValue(0, intType));
  4770. }
  4771. BfIRValue splatTypesConst = mBfIRBuilder->CreateConstArray(mBfIRBuilder->MapType(reflectFieldSplatDataType->mFieldInstances[0].mResolvedType), splatTypes);
  4772. BfIRValue splatOffsetsConst = mBfIRBuilder->CreateConstArray(mBfIRBuilder->MapType(reflectFieldSplatDataType->mFieldInstances[1].mResolvedType), splatOffsets);
  4773. SizedArray<BfIRValue, 8> splatVals =
  4774. {
  4775. emptyValueType,
  4776. splatTypesConst,
  4777. splatOffsetsConst
  4778. };
  4779. auto fieldSplatData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(reflectFieldSplatDataType->ToTypeInstance(), BfIRPopulateType_Full), splatVals);
  4780. BfIRValue fieldDataArray = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapType(reflectFieldSplatDataType), true, BfIRLinkageType_Internal,
  4781. fieldSplatData, typeDataName + ".splats");
  4782. fieldDataPtr = mBfIRBuilder->CreateBitCast(fieldDataArray, fieldDataPtrType);
  4783. }
  4784. else
  4785. fieldDataPtr = mBfIRBuilder->CreateConstNull(fieldDataPtrType);
  4786. }
  4787. else
  4788. {
  4789. BfIRType fieldDataConstType = mBfIRBuilder->GetSizedArrayType(reflectFieldDataIRType, (int)fieldTypes.size());
  4790. BfIRValue fieldDataConst = mBfIRBuilder->CreateConstArray(fieldDataConstType, fieldTypes);
  4791. BfIRValue fieldDataArray = mBfIRBuilder->CreateGlobalVariable(fieldDataConstType, true, BfIRLinkageType_Internal,
  4792. fieldDataConst, "fields." + typeDataName);
  4793. fieldDataPtr = mBfIRBuilder->CreateBitCast(fieldDataArray, fieldDataPtrType);
  4794. }
  4795. /// Methods
  4796. BfType* reflectMethodDataType = ResolveTypeDef(mCompiler->mReflectMethodDataDef);
  4797. BfType* reflectParamDataType = ResolveTypeDef(mCompiler->mReflectParamDataDef);
  4798. BfType* reflectParamDataPtrType = CreatePointerType(reflectParamDataType);
  4799. SizedArray<BfIRValue, 16> methodTypes;
  4800. for (int methodIdx = 0; methodIdx < (int)typeDef->mMethods.size(); methodIdx++)
  4801. {
  4802. if (!needsTypeData)
  4803. break;
  4804. auto methodInstanceGroup = &typeInstance->mMethodInstanceGroups[methodIdx];
  4805. if (!methodInstanceGroup->IsImplemented())
  4806. continue;
  4807. auto methodDef = typeDef->mMethods[methodIdx];
  4808. if (methodDef->mNoReflect)
  4809. continue;
  4810. auto defaultMethod = methodInstanceGroup->mDefault;
  4811. if (defaultMethod == NULL)
  4812. continue;
  4813. if (defaultMethod->mIsUnspecialized)
  4814. continue;
  4815. if (!defaultMethod->mIsReified)
  4816. continue;
  4817. if ((defaultMethod->mChainType == BfMethodChainType_ChainMember) || (defaultMethod->mChainType == BfMethodChainType_ChainSkip))
  4818. continue;
  4819. if (defaultMethod->mMethodDef->mMethodType == BfMethodType_CtorNoBody)
  4820. continue;
  4821. auto methodReflectKind = (ReflectKind)(reflectKind & ~ReflectKind_User);
  4822. bool includeMethod = reflectIncludeAllMethods;
  4823. BfCustomAttributes* methodCustomAttributes = NULL;
  4824. if ((defaultMethod->mMethodInfoEx != NULL) && (defaultMethod->mMethodInfoEx->mMethodCustomAttributes != NULL) && (defaultMethod->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes != NULL))
  4825. {
  4826. methodCustomAttributes = defaultMethod->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes;
  4827. for (auto& customAttr : defaultMethod->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes->mAttributes)
  4828. {
  4829. if (customAttr.mType->mTypeDef->mName->ToString() == "ReflectAttribute")
  4830. {
  4831. includeMethod = true;
  4832. }
  4833. else
  4834. {
  4835. auto userReflectKind = _GetReflectUser(customAttr.mType);
  4836. methodReflectKind = (ReflectKind)(methodReflectKind | userReflectKind);
  4837. }
  4838. }
  4839. }
  4840. if (!typeInstance->IsTypeMemberAccessible(methodDef->mDeclaringType, mProject))
  4841. continue;
  4842. if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  4843. {
  4844. for (BfParameterDeclaration* paramDecl : methodDeclaration->mParams)
  4845. {
  4846. if (paramDecl->mAttributes != NULL)
  4847. methodReflectKind = (ReflectKind)(methodReflectKind | _GetReflectUserFromDirective(paramDecl->mAttributes, BfAttributeTargets_Parameter));
  4848. }
  4849. if (methodDeclaration->mReturnAttributes != NULL)
  4850. methodReflectKind = (ReflectKind)(methodReflectKind | _GetReflectUserFromDirective(methodDeclaration->mReturnAttributes, BfAttributeTargets_ReturnValue));
  4851. }
  4852. if ((methodReflectKind & (ReflectKind_Methods | ReflectKind_User)) != 0)
  4853. includeMethod = true;
  4854. if ((methodDef->mIsStatic) && ((methodReflectKind & ReflectKind_StaticMethods) != 0))
  4855. includeMethod = true;
  4856. if (!includeMethod)
  4857. continue;
  4858. BfModuleMethodInstance moduleMethodInstance;
  4859. BfIRValue funcVal = voidPtrNull;
  4860. if (((!typeInstance->IsBoxed()) || (!methodDef->mIsStatic)) &&
  4861. (!typeInstance->IsUnspecializedType()) &&
  4862. (methodDef->mMethodType != BfMethodType_Ignore) &&
  4863. (methodDef->mMethodType != BfMethodType_Mixin) &&
  4864. (!methodDef->mIsAbstract) &&
  4865. (methodDef->mGenericParams.size() == 0))
  4866. {
  4867. moduleMethodInstance = GetMethodInstanceAtIdx(typeInstance, methodIdx);
  4868. if (moduleMethodInstance.mFunc)
  4869. funcVal = mBfIRBuilder->CreateBitCast(moduleMethodInstance.mFunc, voidPtrIRType);
  4870. }
  4871. BfIRValue methodNameConst = GetStringObjectValue(methodDef->mName, true);
  4872. enum MethodFlags
  4873. {
  4874. MethodFlags_Protected = 3,
  4875. MethodFlags_Public = 6,
  4876. MethodFlags_Static = 0x10,
  4877. MethodFlags_Virtual = 0x40,
  4878. MethodFlags_StdCall = 0x1000,
  4879. MethodFlags_FastCall = 0x2000,
  4880. MethodFlags_ThisCall = 0x3000,
  4881. MethodFlags_Mutating = 0x4000,
  4882. };
  4883. MethodFlags methodFlags = (MethodFlags)0;
  4884. if (methodDef->mProtection == BfProtection_Protected)
  4885. methodFlags = (MethodFlags)(methodFlags | MethodFlags_Protected);
  4886. if (methodDef->mProtection == BfProtection_Public)
  4887. methodFlags = (MethodFlags)(methodFlags | MethodFlags_Public);
  4888. if (methodDef->mIsStatic)
  4889. methodFlags = (MethodFlags)(methodFlags | MethodFlags_Static);
  4890. if (methodDef->mIsVirtual)
  4891. methodFlags = (MethodFlags)(methodFlags | MethodFlags_Virtual);
  4892. if (methodDef->mCallingConvention == BfCallingConvention_Fastcall)
  4893. methodFlags = (MethodFlags)(methodFlags | MethodFlags_FastCall);
  4894. if (methodDef->mIsMutating)
  4895. methodFlags = (MethodFlags)(methodFlags | MethodFlags_Mutating);
  4896. auto callingConvention = GetIRCallingConvention(defaultMethod);
  4897. if (callingConvention == BfIRCallingConv_ThisCall)
  4898. methodFlags = (MethodFlags)(methodFlags | MethodFlags_ThisCall);
  4899. else if (callingConvention == BfIRCallingConv_StdCall)
  4900. methodFlags = (MethodFlags)(methodFlags | MethodFlags_StdCall);
  4901. int customAttrIdx = _HandleCustomAttrs(methodCustomAttributes);
  4902. enum ParamFlags
  4903. {
  4904. ParamFlag_None = 0,
  4905. ParamFlag_Splat = 1,
  4906. ParamFlag_Implicit = 2,
  4907. };
  4908. SizedArray<BfIRValue, 8> paramVals;
  4909. for (int paramIdx = 0; paramIdx < defaultMethod->GetParamCount(); paramIdx++)
  4910. {
  4911. String paramName = defaultMethod->GetParamName(paramIdx);
  4912. BfType* paramType = defaultMethod->GetParamType(paramIdx);
  4913. ParamFlags paramFlags = ParamFlag_None;
  4914. if (defaultMethod->GetParamIsSplat(paramIdx))
  4915. paramFlags = (ParamFlags)(paramFlags | ParamFlag_Splat);
  4916. BfIRValue paramNameConst = GetStringObjectValue(paramName, true);
  4917. SizedArray<BfIRValue, 8> paramDataVals =
  4918. {
  4919. emptyValueType,
  4920. paramNameConst,
  4921. GetConstValue(paramType->mTypeId, typeIdType),
  4922. GetConstValue((int32)paramFlags, shortType),
  4923. GetConstValue(customAttrIdx, intType) // defaultIdx
  4924. };
  4925. auto paramData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapType(reflectParamDataType, BfIRPopulateType_Full), paramDataVals);
  4926. paramVals.Add(paramData);
  4927. }
  4928. BfIRValue paramsVal;
  4929. if (paramVals.size() > 0)
  4930. {
  4931. BfIRType paramDataArrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->MapType(reflectParamDataType, BfIRPopulateType_Full), (int)paramVals.size());
  4932. BfIRValue paramDataConst = mBfIRBuilder->CreateConstArray(paramDataArrayType, paramVals);
  4933. BfIRValue paramDataArray = mBfIRBuilder->CreateGlobalVariable(paramDataArrayType, true, BfIRLinkageType_Internal,
  4934. paramDataConst, typeDataName + StrFormat(".params%d", methodIdx));
  4935. paramsVal = mBfIRBuilder->CreateBitCast(paramDataArray, mBfIRBuilder->MapType(reflectParamDataPtrType));
  4936. }
  4937. else
  4938. paramsVal = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(reflectParamDataPtrType));
  4939. int vDataVal = -1;
  4940. if (defaultMethod->mVirtualTableIdx != -1)
  4941. {
  4942. int vDataIdx = -1;
  4943. vDataIdx = 1 + mCompiler->GetDynCastVDataCount() + mCompiler->mMaxInterfaceSlots;
  4944. if ((mCompiler->mOptions.mHasVDataExtender) && (mCompiler->IsHotCompile()))
  4945. {
  4946. auto typeInst = defaultMethod->mMethodInstanceGroup->mOwner;
  4947. int extMethodIdx = (defaultMethod->mVirtualTableIdx - typeInst->GetBaseVTableSize()) - typeInst->GetOrigSelfVTableSize();
  4948. if (extMethodIdx >= 0)
  4949. {
  4950. // Extension?
  4951. int vExtOfs = typeInst->GetOrigBaseVTableSize();
  4952. vDataVal = ((vDataIdx + vExtOfs + 1) << 20) | (extMethodIdx);
  4953. }
  4954. else
  4955. {
  4956. // Map this new virtual index back to the original index
  4957. vDataIdx += (defaultMethod->mVirtualTableIdx - typeInst->GetBaseVTableSize()) + typeInst->GetOrigBaseVTableSize();
  4958. }
  4959. }
  4960. else
  4961. {
  4962. vDataIdx += defaultMethod->mVirtualTableIdx;
  4963. }
  4964. if (vDataVal == -1)
  4965. vDataVal = vDataIdx * mSystem->mPtrSize;
  4966. }
  4967. SizedArray<BfIRValue, 8> methodDataVals =
  4968. {
  4969. emptyValueType,
  4970. methodNameConst, // mName
  4971. funcVal, // mFuncPtr
  4972. paramsVal,
  4973. GetConstValue(defaultMethod->mReturnType->mTypeId, typeIdType),
  4974. GetConstValue((int)paramVals.size(), shortType),
  4975. GetConstValue(methodFlags, shortType),
  4976. GetConstValue(vDataVal, intType),
  4977. GetConstValue(-1, intType),
  4978. };
  4979. auto methodData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(reflectMethodDataType->ToTypeInstance(), BfIRPopulateType_Full), methodDataVals);
  4980. methodTypes.push_back(methodData);
  4981. }
  4982. BfIRValue methodDataPtr;
  4983. BfIRType methodDataPtrType = mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapType(reflectMethodDataType));
  4984. if (methodTypes.size() == 0)
  4985. methodDataPtr = mBfIRBuilder->CreateConstNull(methodDataPtrType);
  4986. else
  4987. {
  4988. BfIRType methodDataArrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->MapType(reflectMethodDataType, BfIRPopulateType_Full), (int)methodTypes.size());
  4989. BfIRValue methodDataConst = mBfIRBuilder->CreateConstArray(methodDataArrayType, methodTypes);
  4990. BfIRValue methodDataArray = mBfIRBuilder->CreateGlobalVariable(methodDataArrayType, true, BfIRLinkageType_Internal,
  4991. methodDataConst, "methods." + typeDataName);
  4992. methodDataPtr = mBfIRBuilder->CreateBitCast(methodDataArray, methodDataPtrType);
  4993. }
  4994. /////
  4995. int underlyingType = 0;
  4996. if ((typeInstance->IsTypedPrimitive()) || (typeInstance->IsBoxed()))
  4997. {
  4998. underlyingType = typeInstance->GetUnderlyingType()->mTypeId;
  4999. }
  5000. int outerTypeId = 0;
  5001. auto outerType = GetOuterType(typeInstance);
  5002. if (outerType != NULL)
  5003. outerTypeId = outerType->mTypeId;
  5004. BfIRValue customAttrDataPtr;
  5005. if (customAttrs.size() > 0)
  5006. {
  5007. BfIRType customAttrsArrayType = mBfIRBuilder->GetSizedArrayType(voidPtrIRType, (int)customAttrs.size());
  5008. BfIRValue customAttrsConst = mBfIRBuilder->CreateConstArray(customAttrsArrayType, customAttrs);
  5009. BfIRValue customAttrsArray = mBfIRBuilder->CreateGlobalVariable(customAttrsArrayType, true, BfIRLinkageType_Internal,
  5010. customAttrsConst, "customAttrs." + typeDataName);
  5011. customAttrDataPtr = mBfIRBuilder->CreateBitCast(customAttrsArray, voidPtrPtrIRType);
  5012. }
  5013. else
  5014. {
  5015. customAttrDataPtr = mBfIRBuilder->CreateConstNull(voidPtrPtrIRType);
  5016. }
  5017. SizedArray<BfIRValue, 32> typeDataVals =
  5018. {
  5019. typeData,
  5020. castedClassVData, // mTypeClassVData
  5021. typeNameConst, // mName
  5022. namespaceConst, // mNamespace
  5023. GetConstValue(typeInstance->mInstSize, intType), // mInstSize
  5024. GetConstValue(typeInstance->mInstAlign, intType), // mInstAlign
  5025. GetConstValue(typeCustomAttrIdx, intType), // mCustomAttributes
  5026. GetConstValue(baseTypeId, typeIdType), // mBaseType
  5027. GetConstValue(underlyingType, typeIdType), // mUnderlyingType
  5028. GetConstValue(outerTypeId, typeIdType), // mOuterType
  5029. GetConstValue(typeInstance->mInheritanceId, intType), // mInheritanceId
  5030. GetConstValue(typeInstance->mInheritanceCount, intType), // mInheritanceCount
  5031. GetConstValue(typeInstance->mSlotNum, byteType), // mInterfaceSlot
  5032. GetConstValue(0, byteType), // mInterfaceCount
  5033. GetConstValue((int)methodTypes.size(), shortType), // mMethodDataCount
  5034. GetConstValue(0, shortType), // mPropertyDataCount
  5035. GetConstValue((int)fieldTypes.size(), shortType), // mFieldDataCount
  5036. GetConstValue(0, shortType), // mConstructorDataCount
  5037. voidPtrNull, // mInterfaceDataPtr
  5038. methodDataPtr, // mMethodDataPtr
  5039. voidPtrNull, // mPropertyDataPtr
  5040. fieldDataPtr, // mFieldDataPtr
  5041. voidPtrNull, // mConstructorDataPtr
  5042. customAttrDataPtr, // mCustomAttrDataPtr
  5043. };
  5044. BfIRType typeInstanceDataType = mBfIRBuilder->MapTypeInst(typeInstanceType->ToTypeInstance(), BfIRPopulateType_Full);
  5045. auto typeInstanceData = mBfIRBuilder->CreateConstStruct(typeInstanceDataType, typeDataVals);
  5046. if (!needsTypeData)
  5047. {
  5048. // No need for anything beyond typeInstanceData
  5049. }
  5050. else if ((typeInstance->IsGenericTypeInstance()) && (typeInstance->IsUnspecializedType()))
  5051. {
  5052. auto genericTypeInstance = typeInstance->ToGenericTypeInstance();
  5053. SizedArray<BfIRValue, 4> unspecializedData =
  5054. {
  5055. typeInstanceData,
  5056. GetConstValue((int)genericTypeInstance->mTypeGenericArguments.size(), byteType), // mGenericParamCount
  5057. };
  5058. auto reflectUnspecializedGenericType = ResolveTypeDef(mCompiler->mReflectUnspecializedGenericType);
  5059. typeInstanceDataType = mBfIRBuilder->MapTypeInst(reflectUnspecializedGenericType->ToTypeInstance(), BfIRPopulateType_Full);
  5060. typeInstanceData = mBfIRBuilder->CreateConstStruct(typeInstanceDataType, unspecializedData);
  5061. }
  5062. else if (typeInstance->IsGenericTypeInstance())
  5063. {
  5064. auto genericTypeInstance = typeInstance->ToGenericTypeInstance();
  5065. auto reflectSpecializedGenericType = ResolveTypeDef(mCompiler->mReflectSpecializedGenericType);
  5066. auto unspecializedType = ResolveTypeDef(typeInstance->mTypeDef);
  5067. SizedArray<BfIRValue, 4> resolvedTypes;
  5068. for (auto typeGenericArg : genericTypeInstance->mTypeGenericArguments)
  5069. resolvedTypes.push_back(GetConstValue(typeGenericArg->mTypeId, typeIdType));
  5070. auto typeIRType = mBfIRBuilder->MapType(typeIdType);
  5071. auto typePtrIRType = mBfIRBuilder->GetPointerTo(typeIRType);
  5072. auto genericArrayType = mBfIRBuilder->GetSizedArrayType(typeIRType, (int)resolvedTypes.size());
  5073. BfIRValue resolvedTypesConst = mBfIRBuilder->CreateConstArray(genericArrayType, resolvedTypes);
  5074. BfIRValue resolvedTypesArray = mBfIRBuilder->CreateGlobalVariable(genericArrayType, true, BfIRLinkageType_Internal,
  5075. resolvedTypesConst, "resolvedTypes." + typeDataName);
  5076. BfIRValue resovledTypesPtr = mBfIRBuilder->CreateBitCast(resolvedTypesArray, typePtrIRType);
  5077. SizedArray<BfIRValue, 3> specGenericData =
  5078. {
  5079. typeInstanceData,
  5080. GetConstValue(unspecializedType->mTypeId, typeIdType), // mUnspecialziedType
  5081. resovledTypesPtr, // mFieldDataPtr
  5082. };
  5083. typeInstanceDataType = mBfIRBuilder->MapTypeInst(reflectSpecializedGenericType->ToTypeInstance(), BfIRPopulateType_Full);
  5084. typeInstanceData = mBfIRBuilder->CreateConstStruct(typeInstanceDataType, specGenericData);
  5085. if (typeInstance->IsArray())
  5086. {
  5087. auto arrayType = (BfArrayType*)typeInstance;
  5088. BfType* elementType = genericTypeInstance->mTypeGenericArguments[0];
  5089. BfFieldInstance* elementFieldInstance = &genericTypeInstance->mFieldInstances[0];
  5090. SizedArray<BfIRValue, 4> arrayData =
  5091. {
  5092. typeInstanceData,
  5093. GetConstValue(elementType->mSize, intType), // mElementSize
  5094. GetConstValue(1, byteType), // mRank
  5095. GetConstValue(elementFieldInstance->mDataOffset, byteType), // mElementsDataOffset
  5096. };
  5097. auto reflectArrayType = ResolveTypeDef(mCompiler->mReflectArrayType);
  5098. typeInstanceDataType = mBfIRBuilder->MapTypeInst(reflectArrayType->ToTypeInstance(), BfIRPopulateType_Full);
  5099. typeInstanceData = mBfIRBuilder->CreateConstStruct(typeInstanceDataType, arrayData);
  5100. }
  5101. }
  5102. BfIRValue typeDataVar;
  5103. if (needsTypeData)
  5104. {
  5105. typeDataVar = mBfIRBuilder->CreateGlobalVariable(typeInstanceDataType, true,
  5106. BfIRLinkageType_External, typeInstanceData, typeDataName);
  5107. if (mBfIRBuilder->DbgHasInfo())
  5108. {
  5109. mBfIRBuilder->DbgCreateGlobalVariable(mDICompileUnit, typeDataName, typeDataName, NULL, 0, mBfIRBuilder->DbgGetTypeInst(typeInstanceType->ToTypeInstance()), false, typeDataVar);
  5110. }
  5111. }
  5112. else
  5113. {
  5114. typeDataVar = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(mContext->mBfTypeType));
  5115. }
  5116. typeDataVar = mBfIRBuilder->CreateBitCast(typeDataVar, mBfIRBuilder->MapType(mContext->mBfTypeType));
  5117. mTypeDataRefs[typeInstance] = typeDataVar;
  5118. if (classVDataVar)
  5119. {
  5120. BF_ASSERT(!classVDataName.IsEmpty());
  5121. vData[0] = mBfIRBuilder->CreateBitCast(typeDataVar, voidPtrIRType);
  5122. auto classVDataConstDataType = mBfIRBuilder->GetSizedArrayType(voidPtrIRType, (int)vData.size());
  5123. auto classVDataConstData = mBfIRBuilder->CreateConstArray(classVDataConstDataType, vData);
  5124. mBfIRBuilder->GlobalVar_SetInitializer(classVDataVar, classVDataConstData);
  5125. if (mCompiler->mOptions.mObjectHasDebugFlags)
  5126. mBfIRBuilder->GlobalVar_SetAlignment(classVDataVar, 256);
  5127. else
  5128. mBfIRBuilder->GlobalVar_SetAlignment(classVDataVar, mContext->mBfClassVDataPtrType->mAlign);
  5129. if (mBfIRBuilder->DbgHasInfo())
  5130. {
  5131. BfType* voidType = GetPrimitiveType(BfTypeCode_None);
  5132. BfType* voidPtrType = CreatePointerType(voidType);
  5133. BfType* classVDataType = ResolveTypeDef(mCompiler->mClassVDataTypeDef);
  5134. BfIRMDNode arrayType = mBfIRBuilder->DbgCreateArrayType(vData.size() * mSystem->mPtrSize * 8, mSystem->mPtrSize * 8, mBfIRBuilder->DbgGetType(voidPtrType), vData.size());
  5135. mBfIRBuilder->DbgCreateGlobalVariable(mDICompileUnit, classVDataName, classVDataName, NULL, 0, arrayType, false, classVDataVar);
  5136. }
  5137. }
  5138. return typeDataVar;
  5139. }
  5140. BfIRValue BfModule::FixClassVData(BfIRValue value)
  5141. {
  5142. if (!mCompiler->mOptions.mObjectHasDebugFlags)
  5143. return value;
  5144. auto intptrValue = mBfIRBuilder->CreatePtrToInt(value, BfTypeCode_IntPtr);
  5145. auto maskedValue = mBfIRBuilder->CreateAnd(intptrValue, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, (uint64)~0xFFULL));
  5146. return mBfIRBuilder->CreateIntToPtr(maskedValue, mBfIRBuilder->GetType(value));
  5147. }
  5148. void BfModule::CheckStaticAccess(BfTypeInstance* typeInstance)
  5149. {
  5150. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  5151. //TODO: Create a hashset of these, we don't need to repeatedly call static ctors for a given type
  5152. // When we access classes with static constructors FROM a static constructor,
  5153. // we call that other class's static constructor first. Recursion cannot occur, since
  5154. // we simply ignore subsequent attempts to re-enter the constructor
  5155. if (!typeInstance->mHasStaticInitMethod)
  5156. return;
  5157. if ((mCurMethodInstance == NULL) || ((mCurMethodInstance->mMethodDef->mMethodType != BfMethodType_Ctor) || (!mCurMethodInstance->mMethodDef->mIsStatic)))
  5158. return;
  5159. if (mCurMethodInstance->mMethodInstanceGroup->mOwner == typeInstance)
  5160. return;
  5161. auto checkTypeDef = typeInstance->mTypeDef;
  5162. checkTypeDef->PopulateMemberSets();
  5163. BfMethodDef* nextMethodDef = NULL;
  5164. BfMemberSetEntry* entry;
  5165. if (checkTypeDef->mMethodSet.TryGetWith(String("__BfStaticCtor"), &entry))
  5166. nextMethodDef = (BfMethodDef*)entry->mMemberDef;
  5167. while (nextMethodDef != NULL)
  5168. {
  5169. auto checkMethod = nextMethodDef;
  5170. nextMethodDef = nextMethodDef->mNextWithSameName;
  5171. auto methodModule = GetMethodInstance(typeInstance, checkMethod, BfTypeVector());
  5172. if (methodModule)
  5173. {
  5174. auto methodInstance = methodModule.mMethodInstance;
  5175. if ((methodInstance != NULL) &&
  5176. (methodInstance->mMethodDef->mIsStatic) &&
  5177. (methodInstance->mMethodDef->mMethodType == BfMethodType_Ctor) &&
  5178. ((methodInstance->mChainType == BfMethodChainType_ChainHead) || (methodInstance->mChainType == BfMethodChainType_None)))
  5179. {
  5180. mBfIRBuilder->CreateCall(methodModule.mFunc, SizedArray<BfIRValue, 0>());
  5181. break;
  5182. }
  5183. }
  5184. }
  5185. }
  5186. BfIRFunction BfModule::GetIntrinsic(BfMethodInstance* methodInstance, bool reportFailure)
  5187. {
  5188. auto methodOwner = methodInstance->GetOwner();
  5189. auto methodDef = methodInstance->mMethodDef;
  5190. auto methodDeclaration = methodDef->GetMethodDeclaration();
  5191. bool hasExternSpecifier = (methodDeclaration != NULL) && (methodDeclaration->mExternSpecifier != NULL);
  5192. if (!hasExternSpecifier)
  5193. return BfIRFunction();
  5194. if (methodInstance->GetCustomAttributes() == NULL)
  5195. return BfIRFunction();
  5196. for (auto& customAttribute : methodInstance->GetCustomAttributes()->mAttributes)
  5197. {
  5198. String typeName = TypeToString(customAttribute.mType);
  5199. if ((typeName == "System.IntrinsicAttribute") && (customAttribute.mCtorArgs.size() > 0))
  5200. {
  5201. methodInstance->mIsIntrinsic = true;
  5202. auto constant = methodOwner->mConstHolder->GetConstant(customAttribute.mCtorArgs[0]);
  5203. String error;
  5204. if ((constant != NULL) && (BfIRConstHolder::IsInt(constant->mTypeCode)))
  5205. {
  5206. int stringId = constant->mInt32;
  5207. auto entry = mContext->mStringObjectIdMap[stringId];
  5208. int intrinId = BfIRCodeGen::GetIntrinsicId(entry.mString);
  5209. if (intrinId != -1)
  5210. {
  5211. if (intrinId == BfIRIntrinsic_Malloc)
  5212. {
  5213. return GetBuiltInFunc(BfBuiltInFuncType_Malloc);
  5214. }
  5215. else if (intrinId == BfIRIntrinsic_Free)
  5216. {
  5217. return GetBuiltInFunc(BfBuiltInFuncType_Free);
  5218. }
  5219. SizedArray<BfIRType, 2> paramTypes;
  5220. for (auto& param : methodInstance->mParams)
  5221. paramTypes.push_back(mBfIRBuilder->MapType(param.mResolvedType));
  5222. return mBfIRBuilder->GetIntrinsic(intrinId, paramTypes);
  5223. }
  5224. else if (reportFailure)
  5225. error = StrFormat("Unable to find intrinsic '%s'", entry.mString.c_str());
  5226. }
  5227. else if (reportFailure)
  5228. error = "Intrinsic name must be a constant string";
  5229. if (reportFailure)
  5230. {
  5231. BfAstNode* ref = methodDeclaration->mAttributes;
  5232. Fail(error, ref);
  5233. }
  5234. }
  5235. }
  5236. return BfIRFunction();
  5237. }
  5238. BfIRFunction BfModule::GetBuiltInFunc(BfBuiltInFuncType funcTypeId)
  5239. {
  5240. if (mBfIRBuilder->mIgnoreWrites)
  5241. return mBfIRBuilder->GetFakeFunction();
  5242. if (!mBuiltInFuncs[(int)funcTypeId])
  5243. {
  5244. SizedArray<BfIRType, 4> paramTypes;
  5245. auto nullPtrType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr));
  5246. auto intType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_IntPtr));
  5247. auto int32Type = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_Int32));
  5248. auto intPtrType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_IntPtr));
  5249. auto byteType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_Int8));
  5250. auto voidType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_None));
  5251. auto objType = mBfIRBuilder->MapType(mContext->mBfObjectType);
  5252. BfIRFunctionType funcType;
  5253. BfIRFunction func;
  5254. switch (funcTypeId)
  5255. {
  5256. case BfBuiltInFuncType_PrintF:
  5257. funcType = mBfIRBuilder->CreateFunctionType(int32Type, paramTypes, true);
  5258. func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, "PrintF");
  5259. break;
  5260. case BfBuiltInFuncType_Malloc:
  5261. {
  5262. if (mCompiler->mOptions.mDebugAlloc)
  5263. {
  5264. func = GetInternalMethod("Dbg_RawAlloc", 1).mFunc;
  5265. }
  5266. else
  5267. {
  5268. String funcName = mCompiler->mOptions.mMallocLinkName;
  5269. if (funcName.IsEmpty())
  5270. funcName = "malloc";
  5271. func = mBfIRBuilder->GetFunction(funcName);
  5272. if (!func)
  5273. {
  5274. paramTypes.clear();
  5275. paramTypes.push_back(intType);
  5276. funcType = mBfIRBuilder->CreateFunctionType(nullPtrType, paramTypes);
  5277. func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, funcName);
  5278. mBfIRBuilder->Func_SetParamName(func, 1, "size");
  5279. }
  5280. }
  5281. }
  5282. break;
  5283. case BfBuiltInFuncType_Free:
  5284. {
  5285. if (mCompiler->mOptions.mDebugAlloc)
  5286. {
  5287. func = GetInternalMethod("Dbg_RawFree").mFunc;
  5288. }
  5289. else
  5290. {
  5291. String funcName = mCompiler->mOptions.mFreeLinkName;
  5292. if (funcName.IsEmpty())
  5293. funcName = "free";
  5294. func = mBfIRBuilder->GetFunction(funcName);
  5295. if (!func)
  5296. {
  5297. paramTypes.clear();
  5298. paramTypes.push_back(nullPtrType);
  5299. funcType = mBfIRBuilder->CreateFunctionType(voidType, paramTypes);
  5300. func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, funcName);
  5301. mBfIRBuilder->Func_SetParamName(func, 1, "ptr");
  5302. }
  5303. }
  5304. }
  5305. break;
  5306. case BfBuiltInFuncType_LoadSharedLibraries:
  5307. paramTypes.clear();
  5308. funcType = mBfIRBuilder->CreateFunctionType(voidType, paramTypes);
  5309. func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, "BfLoadSharedLibraries");
  5310. break;
  5311. default: break;
  5312. }
  5313. mBuiltInFuncs[(int)funcTypeId] = func;
  5314. return func;
  5315. }
  5316. return mBuiltInFuncs[(int)funcTypeId];
  5317. }
  5318. void BfModule::ResolveGenericParamConstraints(BfGenericParamInstance* genericParamInstance, bool isUnspecialized)
  5319. {
  5320. BfGenericParamDef* genericParamDef = genericParamInstance->GetGenericParamDef();
  5321. BfExternalConstraintDef* externConstraintDef = genericParamInstance->GetExternConstraintDef();
  5322. BfConstraintDef* constraintDef = genericParamInstance->GetConstraintDef();
  5323. BfType* startingTypeConstraint = genericParamInstance->mTypeConstraint;
  5324. BfAutoComplete* bfAutocomplete = NULL;
  5325. if ((mCompiler->mResolvePassData != NULL) && (isUnspecialized))
  5326. bfAutocomplete = mCompiler->mResolvePassData->mAutoComplete;
  5327. if ((bfAutocomplete != NULL) && (genericParamDef != NULL))
  5328. {
  5329. for (int nameIdx = 0; nameIdx < (int)genericParamDef->mNameNodes.size(); nameIdx++)
  5330. {
  5331. auto nameNode = genericParamDef->mNameNodes[nameIdx];
  5332. if (bfAutocomplete->IsAutocompleteNode(nameNode))
  5333. {
  5334. String filter = nameNode->ToString();
  5335. bfAutocomplete->mInsertStartIdx = nameNode->GetSrcStart();
  5336. bfAutocomplete->mInsertEndIdx = nameNode->GetSrcEnd();
  5337. if (nameIdx != 0)
  5338. {
  5339. bfAutocomplete->AddEntry(AutoCompleteEntry("generic", nameNode->ToString().c_str()), filter);
  5340. }
  5341. }
  5342. }
  5343. }
  5344. for (auto constraint : constraintDef->mConstraints)
  5345. {
  5346. if (auto opConstraint = BfNodeDynCast<BfGenericOperatorConstraint>(constraint))
  5347. {
  5348. BfGenericOperatorConstraintInstance opConstraintInstance;
  5349. if (opConstraint->mLeftType != NULL)
  5350. {
  5351. if (bfAutocomplete != NULL)
  5352. bfAutocomplete->CheckTypeRef(opConstraint->mLeftType, false);
  5353. opConstraintInstance.mLeftType = ResolveTypeRef(opConstraint->mLeftType);
  5354. if (opConstraintInstance.mLeftType == NULL)
  5355. continue;
  5356. }
  5357. if (opConstraint->mRightType == NULL)
  5358. {
  5359. // We had a failure in parsing
  5360. continue;
  5361. }
  5362. if (opConstraint->mRightType != NULL)
  5363. {
  5364. if (bfAutocomplete != NULL)
  5365. bfAutocomplete->CheckTypeRef(opConstraint->mRightType, false);
  5366. opConstraintInstance.mRightType = ResolveTypeRef(opConstraint->mRightType);
  5367. if (opConstraintInstance.mRightType == NULL)
  5368. continue;
  5369. }
  5370. if (opConstraint->mOpToken == NULL)
  5371. {
  5372. FailAfter("Missing operator", (opConstraint->mLeftType != NULL) ? (BfAstNode*)opConstraint->mLeftType : (BfAstNode*)opConstraint->mOperatorToken);
  5373. continue;
  5374. }
  5375. if (opConstraint->mLeftType != NULL)
  5376. {
  5377. if (opConstraint->mRightType == NULL)
  5378. {
  5379. // Parse should have failed
  5380. continue;
  5381. }
  5382. opConstraintInstance.mBinaryOp = BfTokenToBinaryOp(opConstraint->mOpToken->mToken);
  5383. if (opConstraintInstance.mBinaryOp == BfBinaryOp_None)
  5384. {
  5385. Fail("Invalid binary operator", opConstraint->mOpToken);
  5386. continue;
  5387. }
  5388. }
  5389. else if ((opConstraint->mOpToken->mToken == BfToken_Implicit) || (opConstraint->mOpToken->mToken == BfToken_Explicit))
  5390. {
  5391. opConstraintInstance.mCastToken = opConstraint->mOpToken->mToken;
  5392. }
  5393. else
  5394. {
  5395. opConstraintInstance.mUnaryOp = BfTokenToUnaryOp(opConstraint->mOpToken->mToken);
  5396. if (opConstraintInstance.mUnaryOp == BfUnaryOp_None)
  5397. {
  5398. Fail("Invalid unary operator", opConstraint->mOpToken);
  5399. continue;
  5400. }
  5401. }
  5402. if ((constraintDef->mGenericParamFlags & BfGenericParamFlag_Equals) != 0)
  5403. genericParamInstance->mGenericParamFlags = (BfGenericParamFlags)(genericParamInstance->mGenericParamFlags | BfGenericParamFlag_Equals_Op);
  5404. genericParamInstance->mOperatorConstraints.Add(opConstraintInstance);
  5405. continue;
  5406. }
  5407. auto constraintTypeRef = BfNodeDynCast<BfTypeReference>(constraint);
  5408. if (bfAutocomplete != NULL)
  5409. bfAutocomplete->CheckTypeRef(constraintTypeRef, true);
  5410. //TODO: Constraints may refer to other generic params (of either type or method)
  5411. // TO allow resolution, perhaps move this generic param initalization into GetMethodInstance (passing a genericPass bool)
  5412. auto constraintType = ResolveTypeRef(constraintTypeRef, BfPopulateType_Declaration, BfResolveTypeRefFlag_AllowGenericMethodParamConstValue);
  5413. if (constraintType != NULL)
  5414. {
  5415. if ((constraintDef->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  5416. {
  5417. bool isValidTypeCode = false;
  5418. BfTypeCode typeCode = BfTypeCode_None;
  5419. if (constraintType->IsTypedPrimitive())
  5420. {
  5421. auto underlyingType = constraintType->GetUnderlyingType();
  5422. if (underlyingType->IsPrimitiveType())
  5423. typeCode = ((BfPrimitiveType*)underlyingType)->mTypeDef->mTypeCode;
  5424. }
  5425. if (constraintType->IsPrimitiveType())
  5426. typeCode = ((BfPrimitiveType*)constraintType)->mTypeDef->mTypeCode;
  5427. switch (typeCode)
  5428. {
  5429. case BfTypeCode_Int8:
  5430. case BfTypeCode_UInt8:
  5431. case BfTypeCode_Int16:
  5432. case BfTypeCode_UInt16:
  5433. case BfTypeCode_Int32:
  5434. case BfTypeCode_UInt32:
  5435. case BfTypeCode_Int64:
  5436. case BfTypeCode_UInt64:
  5437. case BfTypeCode_IntPtr:
  5438. case BfTypeCode_UIntPtr:
  5439. case BfTypeCode_IntUnknown:
  5440. case BfTypeCode_UIntUnknown:
  5441. case BfTypeCode_Single:
  5442. case BfTypeCode_Double:
  5443. case BfTypeCode_Char8:
  5444. case BfTypeCode_Char16:
  5445. case BfTypeCode_Char32:
  5446. isValidTypeCode = true;
  5447. break;
  5448. default: break;
  5449. }
  5450. if (isValidTypeCode)
  5451. {
  5452. genericParamInstance->mTypeConstraint = constraintType;
  5453. }
  5454. else
  5455. {
  5456. Fail("Const constraint must be a primitive type", constraintTypeRef);
  5457. }
  5458. }
  5459. else
  5460. {
  5461. bool checkEquality = false;
  5462. if (constraintType->IsPrimitiveType())
  5463. {
  5464. if (isUnspecialized)
  5465. {
  5466. Fail("Primitive constraints are not allowed unless preceded with 'const'", constraintTypeRef);
  5467. continue;
  5468. }
  5469. checkEquality = true;
  5470. }
  5471. if (constraintType->IsArray())
  5472. {
  5473. if (isUnspecialized)
  5474. {
  5475. 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);
  5476. continue;
  5477. }
  5478. checkEquality = true;
  5479. }
  5480. if (constraintType->IsGenericParam())
  5481. {
  5482. continue;
  5483. }
  5484. if ((!constraintType->IsTypeInstance()) && (!constraintType->IsSizedArray()))
  5485. {
  5486. if (isUnspecialized)
  5487. {
  5488. Fail(StrFormat("Type '%s' is not allowed as a generic constraint", TypeToString(constraintType).c_str()), constraintTypeRef);
  5489. continue;
  5490. }
  5491. checkEquality = true;
  5492. }
  5493. if ((constraintDef->mGenericParamFlags & BfGenericParamFlag_Equals) != 0)
  5494. {
  5495. genericParamInstance->mGenericParamFlags = (BfGenericParamFlags)(genericParamInstance->mGenericParamFlags | BfGenericParamFlag_Equals_Type);
  5496. checkEquality = true;
  5497. }
  5498. if (checkEquality)
  5499. {
  5500. genericParamInstance->mTypeConstraint = constraintType;
  5501. }
  5502. else if (constraintType->IsInterface())
  5503. {
  5504. if ((constraintDef->mGenericParamFlags & BfGenericParamFlag_Equals) != 0)
  5505. genericParamInstance->mGenericParamFlags = (BfGenericParamFlags)(genericParamInstance->mGenericParamFlags | BfGenericParamFlag_Equals_IFace);
  5506. genericParamInstance->mInterfaceConstraints.push_back(constraintType->ToTypeInstance());
  5507. }
  5508. else
  5509. {
  5510. auto constraintTypeInst = constraintType->ToTypeInstance();
  5511. if (genericParamInstance->mTypeConstraint != NULL)
  5512. {
  5513. if ((constraintTypeInst != NULL) && (TypeIsSubTypeOf(constraintTypeInst, genericParamInstance->mTypeConstraint->ToTypeInstance(), false)))
  5514. {
  5515. // Allow more specific type
  5516. genericParamInstance->mTypeConstraint = constraintTypeInst;
  5517. }
  5518. else if ((constraintTypeInst != NULL) && (TypeIsSubTypeOf(genericParamInstance->mTypeConstraint->ToTypeInstance(), constraintTypeInst, false)))
  5519. {
  5520. // Silently ignore less-specific type
  5521. if ((startingTypeConstraint != NULL) && (startingTypeConstraint->IsDelegate()))
  5522. {
  5523. // 'System.Delegate' means that we are expecting an actual delegate instance. Simulate this by wanting a class.
  5524. genericParamInstance->mGenericParamFlags |= BfGenericParamFlag_Class;
  5525. }
  5526. }
  5527. else
  5528. {
  5529. Fail("Only one concrete type constraint may be specified", constraintTypeRef);
  5530. return;
  5531. }
  5532. }
  5533. else
  5534. genericParamInstance->mTypeConstraint = constraintType;
  5535. }
  5536. }
  5537. }
  5538. }
  5539. if (((constraintDef->mGenericParamFlags & BfGenericParamFlag_Const) != 0) &&
  5540. (genericParamInstance->mTypeConstraint == NULL))
  5541. genericParamInstance->mTypeConstraint = GetPrimitiveType(BfTypeCode_IntPtr);
  5542. }
  5543. String BfModule::GenericParamSourceToString(const BfGenericParamSource & genericParamSource)
  5544. {
  5545. if (genericParamSource.mMethodInstance != NULL)
  5546. {
  5547. auto methodInst = GetUnspecializedMethodInstance(genericParamSource.mMethodInstance);
  5548. SetAndRestoreValue<BfMethodInstance*> prevMethodInst(mCurMethodInstance, methodInst);
  5549. return MethodToString(methodInst);
  5550. }
  5551. else
  5552. {
  5553. auto typeInst = GetUnspecializedTypeInstance(genericParamSource.mTypeInstance);
  5554. SetAndRestoreValue<BfMethodInstance*> prevMethodInst(mCurMethodInstance, NULL);
  5555. SetAndRestoreValue<BfTypeInstance*> prevTypeInst(mCurTypeInstance, typeInst);
  5556. return TypeToString(typeInst);
  5557. }
  5558. }
  5559. bool BfModule::CheckGenericConstraints(const BfGenericParamSource& genericParamSource, BfType* checkArgType, BfAstNode* checkArgTypeRef, BfGenericParamInstance* genericParamInst, BfTypeVector* methodGenericArgs, BfError** errorOut)
  5560. {
  5561. bool ignoreErrors = mIgnoreErrors || (errorOut == NULL) ||
  5562. ((genericParamSource.mMethodInstance == NULL) && (genericParamSource.mTypeInstance == NULL));
  5563. BfType* origCheckArgType = checkArgType;
  5564. if (origCheckArgType->IsRef())
  5565. origCheckArgType = origCheckArgType->GetUnderlyingType();
  5566. bool argMayBeReferenceType = false;
  5567. int checkGenericParamFlags = 0;
  5568. if (checkArgType->IsGenericParam())
  5569. {
  5570. auto checkGenericParamInst = GetGenericParamInstance((BfGenericParamType*)checkArgType);
  5571. checkGenericParamFlags = checkGenericParamInst->mGenericParamFlags;
  5572. if (checkGenericParamInst->mTypeConstraint != NULL)
  5573. checkArgType = checkGenericParamInst->mTypeConstraint;
  5574. if ((checkGenericParamFlags & (BfGenericParamFlag_Struct | BfGenericParamFlag_StructPtr)) != 0)
  5575. {
  5576. argMayBeReferenceType = false;
  5577. }
  5578. else
  5579. {
  5580. argMayBeReferenceType = true;
  5581. }
  5582. }
  5583. if (checkArgType->IsObjectOrInterface())
  5584. argMayBeReferenceType = true;
  5585. BfTypeInstance* typeConstraintInst = NULL;
  5586. if (genericParamInst->mTypeConstraint != NULL)
  5587. typeConstraintInst = genericParamInst->mTypeConstraint->ToTypeInstance();
  5588. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Struct) &&
  5589. ((checkGenericParamFlags & (BfGenericParamFlag_Struct | BfGenericParamFlag_Var)) == 0) && (!checkArgType->IsValueType()))
  5590. {
  5591. if (!ignoreErrors)
  5592. *errorOut = Fail(StrFormat("The type '%s' must be a value type in order to use it as parameter '%s' for '%s'",
  5593. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  5594. return false;
  5595. }
  5596. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_StructPtr) &&
  5597. ((checkGenericParamFlags & (BfGenericParamFlag_StructPtr | BfGenericParamFlag_Var)) == 0) && (!checkArgType->IsPointer()))
  5598. {
  5599. if (!ignoreErrors)
  5600. *errorOut = Fail(StrFormat("The type '%s' must be a pointer type in order to use it as parameter '%s' for '%s'",
  5601. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  5602. return false;
  5603. }
  5604. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Class) &&
  5605. ((checkGenericParamFlags & (BfGenericParamFlag_Class | BfGenericParamFlag_Var)) == 0) && (!argMayBeReferenceType))
  5606. {
  5607. if (!ignoreErrors)
  5608. *errorOut = Fail(StrFormat("The type '%s' must be a reference type in order to use it as parameter '%s' for '%s'",
  5609. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  5610. return false;
  5611. }
  5612. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  5613. {
  5614. if (((checkGenericParamFlags & BfGenericParamFlag_Const) == 0) && (!checkArgType->IsConstExprValue()))
  5615. {
  5616. if (!ignoreErrors)
  5617. *errorOut = Fail(StrFormat("The type '%s' must be a const value in order to use it as parameter '%s' for '%s'",
  5618. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  5619. return false;
  5620. }
  5621. }
  5622. else
  5623. {
  5624. if (checkArgType->IsConstExprValue())
  5625. {
  5626. if (!ignoreErrors)
  5627. *errorOut = Fail(StrFormat("The value '%s' cannot be used for generic type parameter '%s' for '%s'",
  5628. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  5629. return false;
  5630. }
  5631. }
  5632. if ((genericParamInst->mInterfaceConstraints.IsEmpty()) && (genericParamInst->mOperatorConstraints.IsEmpty()) && (genericParamInst->mTypeConstraint == NULL))
  5633. return true;
  5634. if (checkArgType->IsPointer())
  5635. {
  5636. auto ptrType = (BfPointerType*)checkArgType;
  5637. checkArgType = ptrType->mElementType;
  5638. }
  5639. if (genericParamInst->mTypeConstraint != NULL)
  5640. {
  5641. bool constraintMatched = false;
  5642. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  5643. {
  5644. if (checkArgType->IsConstExprValue())
  5645. {
  5646. auto constExprValueType = (BfConstExprValueType*)checkArgType;
  5647. if (genericParamInst->mTypeConstraint->IsPrimitiveType())
  5648. {
  5649. auto primType = (BfPrimitiveType*)genericParamInst->mTypeConstraint;
  5650. // Let either an exact typematch or an undef pass through. Eventually instead of undefs we may want to do
  5651. // actual expression comparisons, but we are overly permissive now and then we may fail on specialization
  5652. if ((constExprValueType->mValue.mTypeCode != primType->mTypeDef->mTypeCode) &&
  5653. (constExprValueType->mValue.mTypeCode != BfTypeCode_Let) &&
  5654. (primType->mTypeDef->mTypeCode != BfTypeCode_Let))
  5655. {
  5656. if (BfIRConstHolder::IsInt(constExprValueType->mValue.mTypeCode))
  5657. {
  5658. if (BfIRConstHolder::IsInt(primType->mTypeDef->mTypeCode))
  5659. {
  5660. if (!mCompiler->mSystem->DoesLiteralFit(primType->mTypeDef->mTypeCode, constExprValueType->mValue.mInt64))
  5661. {
  5662. if (!ignoreErrors)
  5663. *errorOut = Fail(StrFormat("Const generic argument '%s', declared with const '%lld', does not fit into const constraint '%s' for '%s'", genericParamInst->GetName().c_str(),
  5664. constExprValueType->mValue.mInt64, TypeToString(genericParamInst->mTypeConstraint).c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  5665. return false;
  5666. }
  5667. }
  5668. else
  5669. {
  5670. if (!ignoreErrors)
  5671. *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(),
  5672. constExprValueType->mValue.mInt64, TypeToString(genericParamInst->mTypeConstraint).c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  5673. return false;
  5674. }
  5675. }
  5676. else
  5677. {
  5678. if (BfIRConstHolder::IsInt(primType->mTypeDef->mTypeCode))
  5679. {
  5680. char valStr[64];
  5681. ExactMinimalDoubleToStr(constExprValueType->mValue.mDouble, valStr);
  5682. if (!ignoreErrors)
  5683. *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(),
  5684. valStr, TypeToString(genericParamInst->mTypeConstraint).c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  5685. return false;
  5686. }
  5687. }
  5688. }
  5689. }
  5690. }
  5691. }
  5692. else
  5693. {
  5694. BfType* convCheckConstraint = genericParamInst->mTypeConstraint;
  5695. if ((convCheckConstraint->IsUnspecializedType()) && (methodGenericArgs != NULL))
  5696. convCheckConstraint = ResolveGenericType(convCheckConstraint, *methodGenericArgs);
  5697. if ((checkArgType->IsMethodRef()) && (convCheckConstraint->IsDelegate()))
  5698. {
  5699. auto methodRefType = (BfMethodRefType*)checkArgType;
  5700. auto invokeMethod = GetRawMethodInstanceAtIdx(convCheckConstraint->ToTypeInstance(), 0, "Invoke");
  5701. BfExprEvaluator exprEvaluator(this);
  5702. if (exprEvaluator.IsExactMethodMatch(methodRefType->mMethodRef, invokeMethod))
  5703. constraintMatched = true;
  5704. }
  5705. else if (CanImplicitlyCast(GetFakeTypedValue(checkArgType), convCheckConstraint))
  5706. {
  5707. constraintMatched = true;
  5708. }
  5709. else if (origCheckArgType->IsWrappableType())
  5710. {
  5711. if (origCheckArgType->IsSizedArray())
  5712. {
  5713. auto sizedArrayType = (BfSizedArrayType*)origCheckArgType;
  5714. if (convCheckConstraint->IsGenericTypeInstance())
  5715. {
  5716. auto convCheckConstraintInst = (BfGenericTypeInstance*)convCheckConstraint;
  5717. if (convCheckConstraintInst->mTypeDef == mCompiler->mSizedArrayTypeDef)
  5718. {
  5719. if (convCheckConstraintInst->mTypeGenericArguments[0] == sizedArrayType->mElementType)
  5720. {
  5721. auto constExprValueType = (BfConstExprValueType*)convCheckConstraintInst->mTypeGenericArguments[1];
  5722. if (sizedArrayType->mElementCount == constExprValueType->mValue.mInt64)
  5723. constraintMatched = true;
  5724. }
  5725. }
  5726. }
  5727. }
  5728. if (!constraintMatched)
  5729. {
  5730. BfType* wrappedStructType = GetWrappedStructType(origCheckArgType, false);
  5731. if (CanImplicitlyCast(GetFakeTypedValue(wrappedStructType), convCheckConstraint))
  5732. constraintMatched = true;
  5733. }
  5734. }
  5735. if (!constraintMatched)
  5736. {
  5737. if (!ignoreErrors)
  5738. *errorOut = Fail(StrFormat("Generic argument '%s', declared to be '%s' for '%s', must derive from '%s'", genericParamInst->GetName().c_str(),
  5739. TypeToString(origCheckArgType).c_str(), GenericParamSourceToString(genericParamSource).c_str(), TypeToString(convCheckConstraint).c_str(),
  5740. TypeToString(genericParamInst->mTypeConstraint).c_str()), checkArgTypeRef);
  5741. return false;
  5742. }
  5743. }
  5744. }
  5745. if ((genericParamInst->mInterfaceConstraints.size() > 0) && (origCheckArgType->IsInterface()))
  5746. {
  5747. PopulateType(origCheckArgType);
  5748. auto checkTypeInst = origCheckArgType->ToTypeInstance();
  5749. if (checkTypeInst->mTypeDef->mIsConcrete)
  5750. {
  5751. if (!ignoreErrors)
  5752. *errorOut = Fail(StrFormat("Generic argument '%s', declared to be concrete interface '%s' for '%s', must be a concrete type", genericParamInst->GetName().c_str(),
  5753. TypeToString(origCheckArgType).c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  5754. return false;
  5755. }
  5756. }
  5757. for (auto checkConstraint : genericParamInst->mInterfaceConstraints)
  5758. {
  5759. BfType* convCheckConstraint = checkConstraint;
  5760. if (convCheckConstraint->IsUnspecializedType())
  5761. convCheckConstraint = ResolveGenericType(convCheckConstraint, *methodGenericArgs);
  5762. BfTypeInstance* typeConstraintInst = convCheckConstraint->ToTypeInstance();
  5763. bool implementsInterface = false;
  5764. if (origCheckArgType != checkArgType)
  5765. {
  5766. implementsInterface = CanImplicitlyCast(BfTypedValue(BfIRValue::sValueless, origCheckArgType), convCheckConstraint);
  5767. }
  5768. if (!implementsInterface)
  5769. implementsInterface = CanImplicitlyCast(BfTypedValue(BfIRValue::sValueless, checkArgType), convCheckConstraint);
  5770. if ((!implementsInterface) && (origCheckArgType->IsWrappableType()))
  5771. {
  5772. BfTypeInstance* wrappedStructType = GetWrappedStructType(origCheckArgType, false);
  5773. if (TypeIsSubTypeOf(wrappedStructType, typeConstraintInst))
  5774. implementsInterface = true;
  5775. }
  5776. if ((!implementsInterface) && (origCheckArgType->IsTypedPrimitive()))
  5777. {
  5778. auto underlyingType = origCheckArgType->GetUnderlyingType();
  5779. BfTypeInstance* wrappedStructType = GetWrappedStructType(underlyingType, false);
  5780. if (TypeIsSubTypeOf(wrappedStructType, typeConstraintInst))
  5781. implementsInterface = true;
  5782. }
  5783. if (!implementsInterface)
  5784. {
  5785. if (!ignoreErrors)
  5786. *errorOut = Fail(StrFormat("Generic argument '%s', declared to be '%s' for '%s', must implement '%s'", genericParamInst->GetName().c_str(),
  5787. TypeToString(origCheckArgType).c_str(), GenericParamSourceToString(genericParamSource).c_str(), TypeToString(checkConstraint).c_str()), checkArgTypeRef);
  5788. return false;
  5789. }
  5790. }
  5791. for (auto& checkOpConstraint : genericParamInst->mOperatorConstraints)
  5792. {
  5793. auto leftType = checkOpConstraint.mLeftType;
  5794. if ((leftType != NULL) && (leftType->IsUnspecializedType()))
  5795. leftType = ResolveGenericType(leftType, *methodGenericArgs);
  5796. if (leftType != NULL)
  5797. leftType = FixIntUnknown(leftType);
  5798. auto rightType = checkOpConstraint.mRightType;
  5799. if ((rightType != NULL) && (rightType->IsUnspecializedType()))
  5800. rightType = ResolveGenericType(rightType, *methodGenericArgs);
  5801. if (rightType != NULL)
  5802. rightType = FixIntUnknown(rightType);
  5803. BfConstraintState constraintSet;
  5804. constraintSet.mPrevState = mContext->mCurConstraintState;
  5805. constraintSet.mGenericParamInstance = genericParamInst;
  5806. constraintSet.mLeftType = leftType;
  5807. constraintSet.mRightType = rightType;
  5808. SetAndRestoreValue<BfConstraintState*> prevConstraintSet(mContext->mCurConstraintState, &constraintSet);
  5809. if (!CheckConstraintState(NULL))
  5810. return false;
  5811. if (checkOpConstraint.mBinaryOp != BfBinaryOp_None)
  5812. {
  5813. BfExprEvaluator exprEvaluator(this);
  5814. BfTypedValue leftValue(mBfIRBuilder->GetFakeVal(), leftType);
  5815. BfTypedValue rightValue(mBfIRBuilder->GetFakeVal(), rightType);
  5816. //
  5817. {
  5818. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, true);
  5819. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, true);
  5820. exprEvaluator.PerformBinaryOperation(NULL, NULL, checkOpConstraint.mBinaryOp, NULL, BfBinOpFlag_NoClassify, leftValue, rightValue);
  5821. }
  5822. if ((!exprEvaluator.mResult) ||
  5823. (!CanImplicitlyCast(exprEvaluator.mResult, origCheckArgType)))
  5824. {
  5825. if (!ignoreErrors)
  5826. *errorOut = Fail(StrFormat("Generic argument '%s', declared to be '%s' for '%s', must result from binary operation '%s %s %s'", genericParamInst->GetName().c_str(),
  5827. TypeToString(origCheckArgType).c_str(), GenericParamSourceToString(genericParamSource).c_str(),
  5828. TypeToString(leftType).c_str(), BfGetOpName(checkOpConstraint.mBinaryOp), TypeToString(rightType).c_str()
  5829. ), checkArgTypeRef);
  5830. return false;
  5831. }
  5832. }
  5833. else
  5834. {
  5835. BfTypedValue rightValue(mBfIRBuilder->GetFakeVal(), rightType);
  5836. StringT<128> failedOpName;
  5837. if (checkOpConstraint.mCastToken == BfToken_Implicit)
  5838. {
  5839. if (!CanImplicitlyCast(rightValue, origCheckArgType, BfCastFlags_SilentFail))
  5840. failedOpName = "implicit conversion from '";
  5841. }
  5842. else
  5843. {
  5844. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, true);
  5845. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, true);
  5846. if (checkOpConstraint.mCastToken == BfToken_Explicit)
  5847. {
  5848. if (!CastToValue(NULL, rightValue, origCheckArgType, (BfCastFlags)(BfCastFlags_Explicit | BfCastFlags_SilentFail)))
  5849. failedOpName = "explicit conversion from '";
  5850. }
  5851. else
  5852. {
  5853. BfExprEvaluator exprEvaluator(this);
  5854. exprEvaluator.mResult = rightValue;
  5855. exprEvaluator.PerformUnaryOperation(NULL, checkOpConstraint.mUnaryOp, NULL);
  5856. if ((!exprEvaluator.mResult) ||
  5857. (!CanImplicitlyCast(exprEvaluator.mResult, origCheckArgType)))
  5858. {
  5859. failedOpName += "unary operation '";
  5860. failedOpName += BfGetOpName(checkOpConstraint.mUnaryOp);
  5861. }
  5862. }
  5863. }
  5864. if (!failedOpName.IsEmpty())
  5865. {
  5866. if (!ignoreErrors)
  5867. *errorOut = Fail(StrFormat("Generic argument '%s', declared to be '%s' for '%s', must result from %s%s'", genericParamInst->GetName().c_str(),
  5868. TypeToString(origCheckArgType).c_str(), GenericParamSourceToString(genericParamSource).c_str(),
  5869. failedOpName.c_str(), TypeToString(rightType).c_str()
  5870. ), checkArgTypeRef);
  5871. return false;
  5872. }
  5873. }
  5874. }
  5875. return true;
  5876. }
  5877. BfGenericParamType* BfModule::GetGenericParamType(BfGenericParamKind paramKind, int paramIdx)
  5878. {
  5879. if (paramIdx < (int)mContext->mGenericParamTypes[paramKind].size())
  5880. {
  5881. auto genericParamType = mContext->mGenericParamTypes[paramKind][paramIdx];
  5882. return genericParamType;
  5883. }
  5884. auto genericParamType = new BfGenericParamType();
  5885. genericParamType->mContext = mContext;
  5886. genericParamType->mGenericParamKind = paramKind;
  5887. genericParamType->mGenericParamIdx = paramIdx;
  5888. PopulateType(genericParamType);
  5889. BF_ASSERT(paramIdx == (int)mContext->mGenericParamTypes[paramKind].size());
  5890. mContext->mGenericParamTypes[paramKind].push_back(genericParamType);
  5891. BfResolvedTypeSet::LookupContext lookupCtx;
  5892. lookupCtx.mModule = this;
  5893. BfResolvedTypeSet::Entry* typeEntry = NULL;
  5894. auto inserted = mContext->mResolvedTypes.Insert(genericParamType, &lookupCtx, &typeEntry);
  5895. BF_ASSERT(inserted);
  5896. typeEntry->mValue = genericParamType;
  5897. return genericParamType;
  5898. }
  5899. static int sValueFromExprIdx = 0;
  5900. BfTypedValue BfModule::FlushNullConditional(BfTypedValue result, bool ignoreNullable)
  5901. {
  5902. auto pendingNullCond = mCurMethodState->mPendingNullConditional;
  5903. if ((result) && (!ignoreNullable))
  5904. {
  5905. auto notNullBB = mBfIRBuilder->GetInsertBlock();
  5906. //TODO: Make this work, needed for 'void' and such
  5907. BfType* nullableType = NULL;
  5908. if ((result.mType->IsValueType()) && (!result.mType->IsNullable()))
  5909. {
  5910. BfTypeVector typeVec;
  5911. typeVec.push_back(result.mType);
  5912. nullableType = ResolveTypeDef(mCompiler->mNullableTypeDef, typeVec);
  5913. BF_ASSERT(nullableType != NULL);
  5914. }
  5915. // Go back to start and do any setup we need
  5916. mBfIRBuilder->SetInsertPoint(pendingNullCond->mPrevBB);
  5917. BfTypedValue nullableTypedValue;
  5918. if (nullableType != NULL)
  5919. {
  5920. nullableTypedValue = BfTypedValue(CreateAlloca(nullableType, true, "nullCond.nullable"), nullableType, true);
  5921. mBfIRBuilder->CreateMemSet(nullableTypedValue.mValue, GetConstValue(0, GetPrimitiveType(BfTypeCode_Int8)),
  5922. GetConstValue(nullableType->mSize), nullableType->mAlign);
  5923. }
  5924. mBfIRBuilder->CreateBr(pendingNullCond->mCheckBB);
  5925. // Now that we have the nullableTypedValue we can set that, or just jump if we didn't need it
  5926. mBfIRBuilder->SetInsertPoint(notNullBB);
  5927. result = LoadValue(result);
  5928. if (nullableTypedValue)
  5929. {
  5930. auto elementType = nullableType->GetUnderlyingType();
  5931. if (elementType->IsValuelessType())
  5932. {
  5933. BfIRValue ptrValue = mBfIRBuilder->CreateInBoundsGEP(nullableTypedValue.mValue, 0, 1); // mHasValue
  5934. mBfIRBuilder->CreateStore(GetConstValue(1, GetPrimitiveType(BfTypeCode_Boolean)), ptrValue);
  5935. result = nullableTypedValue;
  5936. }
  5937. else
  5938. {
  5939. BfIRValue ptrValue = mBfIRBuilder->CreateInBoundsGEP(nullableTypedValue.mValue, 0, 1); // mValue
  5940. mBfIRBuilder->CreateStore(result.mValue, ptrValue);
  5941. ptrValue = mBfIRBuilder->CreateInBoundsGEP(nullableTypedValue.mValue, 0, 2); // mHasValue
  5942. mBfIRBuilder->CreateStore(GetConstValue(1, GetPrimitiveType(BfTypeCode_Boolean)), ptrValue);
  5943. result = nullableTypedValue;
  5944. }
  5945. }
  5946. mBfIRBuilder->CreateBr(pendingNullCond->mDoneBB);
  5947. AddBasicBlock(pendingNullCond->mDoneBB);
  5948. if (nullableType == NULL)
  5949. {
  5950. auto phi = mBfIRBuilder->CreatePhi(mBfIRBuilder->MapType(result.mType), 1 + (int)pendingNullCond->mNotNullBBs.size());
  5951. mBfIRBuilder->AddPhiIncoming(phi, result.mValue, notNullBB);
  5952. mBfIRBuilder->AddPhiIncoming(phi, GetDefaultValue(result.mType), pendingNullCond->mCheckBB);
  5953. for (int notNullIdx = 0; notNullIdx < (int)pendingNullCond->mNotNullBBs.size() - 1; notNullIdx++)
  5954. {
  5955. auto prevNotNullBB = pendingNullCond->mNotNullBBs[notNullIdx];
  5956. mBfIRBuilder->AddPhiIncoming(phi, GetDefaultValue(result.mType), prevNotNullBB);
  5957. }
  5958. result.mValue = phi;
  5959. }
  5960. }
  5961. else
  5962. {
  5963. mBfIRBuilder->CreateBr(pendingNullCond->mDoneBB);
  5964. mBfIRBuilder->SetInsertPoint(pendingNullCond->mPrevBB);
  5965. mBfIRBuilder->CreateBr(pendingNullCond->mCheckBB);
  5966. AddBasicBlock(pendingNullCond->mDoneBB);
  5967. }
  5968. delete mCurMethodState->mPendingNullConditional;
  5969. mCurMethodState->mPendingNullConditional = NULL;
  5970. return result;
  5971. }
  5972. BF_NOINLINE void BfModule::EvaluateWithNewScope(BfExprEvaluator& exprEvaluator, BfExpression* expr, BfEvalExprFlags flags)
  5973. {
  5974. BfScopeData newScope;
  5975. newScope.mOuterIsConditional = true;
  5976. newScope.mAllowTargeting = false;
  5977. mCurMethodState->AddScope(&newScope);
  5978. NewScopeState();
  5979. exprEvaluator.mBfEvalExprFlags = flags;
  5980. exprEvaluator.Evaluate(expr, (flags & BfEvalExprFlags_PropogateNullConditional) != 0, (flags & BfEvalExprFlags_IgnoreNullConditional) != 0, true);
  5981. RestoreScopeState();
  5982. }
  5983. BfTypedValue BfModule::CreateValueFromExpression(BfExprEvaluator& exprEvaluator, BfExpression* expr, BfType* wantTypeRef, BfEvalExprFlags flags, BfType** outOrigType)
  5984. {
  5985. //
  5986. {
  5987. BP_ZONE("CreateValueFromExpression:CheckStack");
  5988. StackHelper stackHelper;
  5989. if (!stackHelper.CanStackExpand(64 * 1024))
  5990. {
  5991. BfTypedValue result;
  5992. if (!stackHelper.Execute([&]()
  5993. {
  5994. result = CreateValueFromExpression(exprEvaluator, expr, wantTypeRef, flags, outOrigType);
  5995. }))
  5996. {
  5997. Fail("Expression too complex to compile", expr);
  5998. }
  5999. return result;
  6000. }
  6001. }
  6002. BP_ZONE("BfModule::CreateValueFromExpression");
  6003. if (outOrigType != NULL)
  6004. *outOrigType = NULL;
  6005. exprEvaluator.mExpectingType = wantTypeRef;
  6006. exprEvaluator.mBfEvalExprFlags = flags;
  6007. exprEvaluator.mExplicitCast = (flags & BfEvalExprFlags_ExplicitCast) != 0;
  6008. if ((flags & BfEvalExprFlags_CreateConditionalScope) != 0)
  6009. {
  6010. EvaluateWithNewScope(exprEvaluator, expr, flags);
  6011. }
  6012. else
  6013. exprEvaluator.Evaluate(expr, (flags & BfEvalExprFlags_PropogateNullConditional) != 0, (flags & BfEvalExprFlags_IgnoreNullConditional) != 0, true);
  6014. if (!exprEvaluator.mResult)
  6015. {
  6016. if (!mCompiler->mPassInstance->HasFailed())
  6017. Fail("INTERNAL ERROR: No expression result returned but no error caught in expression evaluator", expr);
  6018. return BfTypedValue();
  6019. }
  6020. auto typedVal = exprEvaluator.mResult;
  6021. if (typedVal.mKind == BfTypedValueKind_GenericConstValue)
  6022. {
  6023. BF_ASSERT(typedVal.mType->IsGenericParam());
  6024. auto genericParamDef = GetGenericParamInstance((BfGenericParamType*)typedVal.mType);
  6025. bool handled = false;
  6026. if ((genericParamDef->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  6027. {
  6028. auto genericTypeConstraint = genericParamDef->mTypeConstraint;
  6029. if (genericTypeConstraint != NULL)
  6030. {
  6031. auto primType = genericTypeConstraint->ToPrimitiveType();
  6032. if (primType != NULL)
  6033. {
  6034. BfTypedValue result;
  6035. result.mKind = BfTypedValueKind_Value;
  6036. result.mType = genericTypeConstraint;
  6037. result.mValue = mBfIRBuilder->GetUndefConstValue(primType->mTypeDef->mTypeCode);
  6038. typedVal = result;
  6039. handled = true;
  6040. }
  6041. }
  6042. }
  6043. if (!handled)
  6044. {
  6045. //Fail("Only const generic parameters can be used as values", expr);
  6046. AssertErrorState();
  6047. return BfTypedValue();
  6048. }
  6049. }
  6050. if ((flags & BfEvalExprFlags_AllowIntUnknown) == 0)
  6051. FixIntUnknown(typedVal);
  6052. exprEvaluator.CheckResultForReading(typedVal);
  6053. if ((wantTypeRef == NULL) || (!wantTypeRef->IsRef()))
  6054. {
  6055. if ((flags & BfEvalExprFlags_NoCast) == 0)
  6056. {
  6057. // Only allow a 'ref' type if we have an explicit 'ref' operator
  6058. bool allowRef = false;
  6059. BfExpression* checkExpr = expr;
  6060. while (auto parenExpr = BfNodeDynCast<BfParenthesizedExpression>(checkExpr))
  6061. checkExpr = parenExpr->mExpression;
  6062. if (auto unaryOp = BfNodeDynCast<BfUnaryOperatorExpression>(checkExpr))
  6063. {
  6064. if ((unaryOp->mOp == BfUnaryOp_Ref) || (unaryOp->mOp == BfUnaryOp_Mut))
  6065. allowRef = true;
  6066. }
  6067. if (!allowRef)
  6068. typedVal = RemoveRef(typedVal);
  6069. }
  6070. }
  6071. if (!typedVal.mType->IsComposite()) // Load non-structs by default
  6072. typedVal = LoadValue(typedVal, 0, exprEvaluator.mIsVolatileReference);
  6073. if (wantTypeRef != NULL)
  6074. {
  6075. if (outOrigType != NULL)
  6076. *outOrigType = typedVal.mType;
  6077. if ((flags & BfEvalExprFlags_NoCast) == 0)
  6078. {
  6079. BfCastFlags castFlags = ((flags & BfEvalExprFlags_ExplicitCast) != 0) ? BfCastFlags_Explicit : BfCastFlags_None;
  6080. if ((flags & BfEvalExprFlags_FieldInitializer) != 0)
  6081. castFlags = (BfCastFlags)(castFlags | BfCastFlags_WarnOnBox);
  6082. typedVal = Cast(expr, typedVal, wantTypeRef, castFlags);
  6083. if (!typedVal)
  6084. return typedVal;
  6085. }
  6086. //WTF- why did we have this?
  6087. /*if ((flags & BfEvalExprFlags_ExplicitCast) == 0)
  6088. typedVal = LoadValue(typedVal, 0, exprEvaluator.mIsVolatileReference);*/
  6089. if (exprEvaluator.mIsVolatileReference)
  6090. typedVal = LoadValue(typedVal, 0, exprEvaluator.mIsVolatileReference);
  6091. }
  6092. // if ((typedVal.IsSplat()) && ((flags & BfEvalExprFlags_AllowSplat) == 0))
  6093. // typedVal = MakeAddressable(typedVal);
  6094. //typedVal = AggregateSplat(typedVal);
  6095. if ((typedVal.mType->IsValueType()) && ((flags & BfEvalExprFlags_NoValueAddr) != 0))
  6096. typedVal = LoadValue(typedVal, 0, exprEvaluator.mIsVolatileReference);
  6097. return typedVal;
  6098. }
  6099. BfTypedValue BfModule::CreateValueFromExpression(BfExpression* expr, BfType* wantTypeRef, BfEvalExprFlags flags, BfType** outOrigType)
  6100. {
  6101. BfExprEvaluator exprEvaluator(this);
  6102. return CreateValueFromExpression(exprEvaluator, expr, wantTypeRef, flags, outOrigType);
  6103. }
  6104. BfTypedValue BfModule::GetOrCreateVarAddr(BfExpression* expr)
  6105. {
  6106. BfExprEvaluator exprEvaluator(this);
  6107. exprEvaluator.Evaluate(expr);
  6108. if (!exprEvaluator.mResult)
  6109. {
  6110. Fail("Invalid expression type", expr);
  6111. return BfTypedValue();
  6112. }
  6113. if (!exprEvaluator.mResult.IsAddr())
  6114. {
  6115. Fail("Cannot assign to value", expr);
  6116. return BfTypedValue();
  6117. }
  6118. return exprEvaluator.mResult;
  6119. }
  6120. // Clear memory, set classVData, call init. Actual ctor is called elsewhere.
  6121. void BfModule::InitTypeInst(BfTypedValue typedValue, BfScopeData* scopeData, bool zeroMemory, BfIRValue sizeValue)
  6122. {
  6123. auto typeInstance = typedValue.mType->ToTypeInstance();
  6124. if (zeroMemory)
  6125. {
  6126. int zeroAlign = typedValue.mType->mAlign;
  6127. if (typeInstance != NULL)
  6128. zeroAlign = typeInstance->mInstAlign;
  6129. mBfIRBuilder->CreateMemSet(typedValue.mValue, GetConstValue8(0), sizeValue, zeroAlign);
  6130. }
  6131. if (!typedValue.mType->IsObject())
  6132. {
  6133. return;
  6134. }
  6135. if ((scopeData == NULL) && (mCurMethodState != NULL))
  6136. return; // Handled in heap alloc funcs
  6137. auto typeDef = typeInstance->mTypeDef;
  6138. mBfIRBuilder->PopulateType(typedValue.mType);
  6139. auto vObjectAddr = mBfIRBuilder->CreateInBoundsGEP(typedValue.mValue, 0, 0);
  6140. bool isAutocomplete = mCompiler->IsAutocomplete();
  6141. BfIRValue vDataRef;
  6142. if (!isAutocomplete)
  6143. {
  6144. vDataRef = GetClassVDataPtr(typeInstance);
  6145. }
  6146. auto i8Type = GetPrimitiveType(BfTypeCode_Int8);
  6147. auto ptrType = CreatePointerType(i8Type);
  6148. auto ptrPtrType = CreatePointerType(ptrType);
  6149. PopulateType(ptrPtrType, BfPopulateType_Declaration);
  6150. PopulateType(ptrType, BfPopulateType_Declaration);
  6151. auto destAddr = mBfIRBuilder->CreateBitCast(vObjectAddr, mBfIRBuilder->MapType(ptrPtrType));
  6152. if (!isAutocomplete)
  6153. {
  6154. if (mCompiler->mOptions.mObjectHasDebugFlags)
  6155. {
  6156. auto objectPtr = mBfIRBuilder->CreateBitCast(destAddr, mBfIRBuilder->MapType(mContext->mBfObjectType));
  6157. SizedArray<BfIRValue, 4> llvmArgs;
  6158. llvmArgs.push_back(objectPtr);
  6159. llvmArgs.push_back(vDataRef);
  6160. auto objectStackInitMethod = GetInternalMethod("Dbg_ObjectStackInit");
  6161. if (objectStackInitMethod)
  6162. mBfIRBuilder->CreateCall(objectStackInitMethod.mFunc, llvmArgs);
  6163. }
  6164. else
  6165. {
  6166. auto srcVal = mBfIRBuilder->CreateBitCast(vDataRef, mBfIRBuilder->MapType(ptrType));
  6167. auto objectPtr = mBfIRBuilder->CreateBitCast(destAddr, mBfIRBuilder->MapType(ptrType));
  6168. mBfIRBuilder->CreateStore(srcVal, destAddr);
  6169. }
  6170. }
  6171. }
  6172. BfIRValue BfModule::AllocBytes(BfAstNode* refNode, const BfAllocTarget& allocTarget, BfType* type, BfIRValue sizeValue, BfIRValue alignValue, BfAllocFlags allocFlags/*, bool zeroMemory, bool defaultToMalloc*/)
  6173. {
  6174. BfIRValue result;
  6175. BfType* ptrType;
  6176. if ((type->IsObject()) && ((allocFlags & BfAllocFlags_RawArray) == 0))
  6177. ptrType = type;
  6178. else
  6179. ptrType = CreatePointerType(type);
  6180. if ((allocTarget.mScopedInvocationTarget != NULL) || (allocTarget.mCustomAllocator))
  6181. {
  6182. auto intType = GetPrimitiveType(BfTypeCode_IntPtr);
  6183. SizedArray<BfExpression*, 2> argExprs;
  6184. BfTypedValueExpression typedValueExpr;
  6185. typedValueExpr.Init(BfTypedValue(sizeValue, intType));
  6186. typedValueExpr.mRefNode = refNode;
  6187. argExprs.push_back(&typedValueExpr);
  6188. BfTypedValueExpression appendSizeValueExpr;
  6189. appendSizeValueExpr.Init(BfTypedValue(alignValue, intType));
  6190. appendSizeValueExpr.mRefNode = refNode;
  6191. argExprs.push_back(&appendSizeValueExpr);
  6192. BfExprEvaluator exprEvaluator(this);
  6193. BfTypedValue allocResult;
  6194. if (allocTarget.mScopedInvocationTarget != NULL)
  6195. {
  6196. SizedArray<BfTypeReference*, 2> genericArgs;
  6197. exprEvaluator.DoInvocation(allocTarget.mScopedInvocationTarget, NULL, argExprs, NULL);
  6198. allocResult = LoadValue(exprEvaluator.mResult);
  6199. }
  6200. else if (allocTarget.mCustomAllocator)
  6201. {
  6202. auto customTypeInst = allocTarget.mCustomAllocator.mType->ToTypeInstance();
  6203. if (customTypeInst != NULL)
  6204. {
  6205. BfTypedValueExpression typeValueExpr;
  6206. String allocMethodName = "Alloc";
  6207. if (GetRawMethodByName(customTypeInst, "AllocTyped", -1, true, true))
  6208. {
  6209. allocMethodName = "AllocTyped";
  6210. auto typeType = ResolveTypeDef(mCompiler->mTypeTypeDef);
  6211. auto typeRefVal = CreateTypeDataRef(type);
  6212. typeValueExpr.Init(BfTypedValue(typeRefVal, typeType));
  6213. typeValueExpr.mRefNode = refNode;
  6214. argExprs.Insert(0, &typeValueExpr);
  6215. }
  6216. if (HasMixin(customTypeInst, allocMethodName, 2))
  6217. {
  6218. BfSizedArray<BfExpression*> argExprArr;
  6219. argExprArr.mSize = (int)argExprs.size();
  6220. argExprArr.mVals = &argExprs[0];
  6221. exprEvaluator.InjectMixin(refNode, allocTarget.mCustomAllocator, false, allocMethodName, argExprs, {});
  6222. allocResult = exprEvaluator.GetResult();
  6223. }
  6224. else
  6225. {
  6226. BfSizedArray<BfExpression*> sizedArgExprs(argExprs);
  6227. BfResolvedArgs argValues(&sizedArgExprs);
  6228. exprEvaluator.ResolveArgValues(argValues);
  6229. SetAndRestoreValue<bool> prevNoBind(mCurMethodState->mNoBind, true);
  6230. allocResult = exprEvaluator.MatchMethod(refNode, NULL, allocTarget.mCustomAllocator, false, false, allocMethodName, argValues, NULL);
  6231. }
  6232. }
  6233. }
  6234. if (allocResult)
  6235. {
  6236. if (allocResult.mType->IsVoidPtr())
  6237. result = mBfIRBuilder->CreateBitCast(allocResult.mValue, mBfIRBuilder->MapType(ptrType));
  6238. else
  6239. result = CastToValue(refNode, allocResult, ptrType, BfCastFlags_Explicit);
  6240. return result;
  6241. }
  6242. }
  6243. if ((allocFlags & BfAllocFlags_NoDefaultToMalloc) != 0)
  6244. return result;
  6245. if (mCompiler->mOptions.mDebugAlloc)
  6246. {
  6247. BfIRValue allocData = GetDbgRawAllocData(type);
  6248. BfModuleMethodInstance allocMethod = GetInternalMethod("Dbg_RawAlloc", 2);
  6249. SizedArray<BfIRValue, 2> llvmArgs;
  6250. llvmArgs.push_back(sizeValue);
  6251. llvmArgs.push_back(allocData);
  6252. BfIRValue bitData = mBfIRBuilder->CreateCall(allocMethod.mFunc, llvmArgs);
  6253. return mBfIRBuilder->CreateBitCast(bitData, mBfIRBuilder->MapType(ptrType));
  6254. }
  6255. BfModuleMethodInstance moduleMethodInstance;
  6256. moduleMethodInstance = GetInternalMethod("Malloc");
  6257. SizedArray<BfIRValue, 1> llvmArgs;
  6258. llvmArgs.push_back(sizeValue);
  6259. auto func = moduleMethodInstance.mFunc;
  6260. if ((!func) || (func.IsFake()))
  6261. {
  6262. BF_ASSERT((mCompiler->mIsResolveOnly) || (mBfIRBuilder->mIgnoreWrites));
  6263. return mBfIRBuilder->CreateUndefValue(mBfIRBuilder->MapType(ptrType));
  6264. }
  6265. BfIRValue bitData = mBfIRBuilder->CreateCall(func, llvmArgs);
  6266. if ((allocFlags & BfAllocFlags_ZeroMemory) != 0)
  6267. mBfIRBuilder->CreateMemSet(bitData, GetConstValue8(0), sizeValue, alignValue);
  6268. result = mBfIRBuilder->CreateBitCast(bitData, mBfIRBuilder->MapType(ptrType));
  6269. return result;
  6270. }
  6271. BfIRValue BfModule::GetMarkFuncPtr(BfType* type)
  6272. {
  6273. if (type->IsStruct())
  6274. {
  6275. auto typeInstance = type->ToTypeInstance();
  6276. BfModuleMethodInstance moduleMethodInst = GetMethodByName(typeInstance, BF_METHODNAME_MARKMEMBERS, 0, true);
  6277. return mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr)));
  6278. }
  6279. else if (type->IsObjectOrInterface())
  6280. {
  6281. auto gcType = ResolveTypeDef(mCompiler->mGCTypeDef)->ToTypeInstance();
  6282. BfModuleMethodInstance moduleMethodInst = GetMethodByName(gcType, "MarkDerefedObject");
  6283. BF_ASSERT(moduleMethodInst.mFunc);
  6284. return mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr)));
  6285. }
  6286. else
  6287. {
  6288. auto gcType = ResolveTypeDef(mCompiler->mGCTypeDef)->ToTypeInstance();
  6289. BfExprEvaluator exprEvaluator(this);
  6290. SizedArray<BfResolvedArg, 1> resolvedArgs;
  6291. BfResolvedArg resolvedArg;
  6292. resolvedArg.mTypedValue = BfTypedValue(mBfIRBuilder->GetFakeVal(), type, type->IsComposite());
  6293. resolvedArgs.Add(resolvedArg);
  6294. BfMethodMatcher methodMatcher(NULL, this, "Mark", resolvedArgs, NULL);
  6295. methodMatcher.CheckType(gcType, BfTypedValue(), false);
  6296. BfModuleMethodInstance moduleMethodInst = exprEvaluator.GetSelectedMethod(NULL, methodMatcher.mBestMethodTypeInstance, methodMatcher.mBestMethodDef, methodMatcher);
  6297. BF_ASSERT(moduleMethodInst.mFunc);
  6298. return mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr)));
  6299. }
  6300. return BfIRValue();
  6301. }
  6302. BfIRValue BfModule::GetDbgRawAllocData(BfType* type)
  6303. {
  6304. BfIRValue allocDataValue;
  6305. if (mDbgRawAllocDataRefs.TryGetValue(type, &allocDataValue))
  6306. return allocDataValue;
  6307. BfIRValue markFuncPtr;
  6308. if (type->WantsGCMarking())
  6309. markFuncPtr = GetMarkFuncPtr(type);
  6310. else
  6311. markFuncPtr = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr)));
  6312. BfIRValue typeDataRef = CreateTypeDataRef(type);
  6313. auto dbgRawAllocDataType = ResolveTypeDef(mCompiler->mDbgRawAllocDataTypeDef)->ToTypeInstance();
  6314. BfTypeInstance* typeInstance = type->ToTypeInstance();
  6315. if (typeInstance == NULL)
  6316. {
  6317. typeInstance = GetWrappedStructType(type);
  6318. if (typeInstance != NULL)
  6319. AddDependency(typeInstance, mCurTypeInstance, BfDependencyMap::DependencyFlag_Allocates);
  6320. }
  6321. if (typeInstance != NULL)
  6322. PopulateType(typeInstance);
  6323. int stackCount = mCompiler->mOptions.mAllocStackCount;
  6324. if ((typeInstance != NULL) && (typeInstance->mTypeOptionsIdx != -1))
  6325. {
  6326. auto typeOptions = mSystem->GetTypeOptions(typeInstance->mTypeOptionsIdx);
  6327. stackCount = BfTypeOptions::Apply(stackCount, typeOptions->mAllocStackTraceDepth);
  6328. }
  6329. SizedArray<BfIRValue, 2> dataValues;
  6330. dataValues.Add(mBfIRBuilder->CreateConstStructZero(mBfIRBuilder->MapType(dbgRawAllocDataType->mBaseType, BfIRPopulateType_Full)));
  6331. dataValues.Add(typeDataRef);
  6332. dataValues.Add(markFuncPtr);
  6333. dataValues.Add(mBfIRBuilder->CreateConst(BfTypeCode_Int32, stackCount));
  6334. BfIRValue dataStruct = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapType(dbgRawAllocDataType, BfIRPopulateType_Full), dataValues);
  6335. allocDataValue = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapType(dbgRawAllocDataType), true, BfIRLinkageType_Internal, dataStruct, "__allocData_" + BfSafeMangler::Mangle(type));
  6336. mDbgRawAllocDataRefs.TryAdd(type, allocDataValue);
  6337. return allocDataValue;
  6338. }
  6339. BfIRValue BfModule::AllocFromType(BfType* type, const BfAllocTarget& allocTarget, BfIRValue appendSizeValue, BfIRValue arraySize, int arrayDim, BfAllocFlags allocFlags, int alignOverride)
  6340. {
  6341. BP_ZONE("AllocFromType");
  6342. BfScopeData* scopeData = allocTarget.mScopeData;
  6343. auto typeInstance = type->ToTypeInstance();
  6344. if ((typeInstance == NULL) && (type->IsGenericParam()))
  6345. typeInstance = mContext->mBfObjectType;
  6346. bool isHeapAlloc = scopeData == NULL;
  6347. bool isScopeAlloc = scopeData != NULL;
  6348. bool isLoopedAlloc = (scopeData != NULL) && (mCurMethodState->mCurScope->IsLooped(scopeData));
  6349. bool isDynAlloc = (scopeData != NULL) && (mCurMethodState->mCurScope->IsDyn(scopeData));
  6350. bool isRawArrayAlloc = (allocFlags & BfAllocFlags_RawArray) != 0;
  6351. bool zeroMemory = (allocFlags & BfAllocFlags_ZeroMemory) != 0;
  6352. bool noDtorCall = (allocFlags & BfAllocFlags_NoDtorCall) != 0;
  6353. if ((type->IsValuelessType()) && ((!arraySize) || (isRawArrayAlloc)))
  6354. {
  6355. BfPointerType* ptrType = CreatePointerType(type);
  6356. auto val = mBfIRBuilder->CreateIntToPtr(mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 1), mBfIRBuilder->MapType(ptrType));
  6357. return val;
  6358. }
  6359. if (typeInstance != NULL)
  6360. mBfIRBuilder->PopulateType(typeInstance);
  6361. bool hasCustomAllocator = (allocTarget.mCustomAllocator) || (allocTarget.mScopedInvocationTarget != NULL);
  6362. if ((!hasCustomAllocator) && (mBfIRBuilder->mIgnoreWrites))
  6363. {
  6364. if (arraySize)
  6365. {
  6366. if (isRawArrayAlloc)
  6367. {
  6368. BfPointerType* ptrType = CreatePointerType(type);
  6369. return GetDefaultValue(ptrType);
  6370. }
  6371. BfArrayType* arrayType = CreateArrayType(type, arrayDim);
  6372. return GetDefaultValue(arrayType);
  6373. }
  6374. if (type->IsValueType())
  6375. {
  6376. BfPointerType* ptrType = CreatePointerType(type);
  6377. return GetDefaultValue(ptrType);
  6378. }
  6379. return mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(type));
  6380. }
  6381. AddDependency(type, mCurTypeInstance, BfDependencyMap::DependencyFlag_Allocates);
  6382. BfIRValue sizeValue;
  6383. BfIRType allocType = mBfIRBuilder->MapType(type);
  6384. int allocSize = type->mSize;
  6385. int allocAlign = type->mAlign;
  6386. if (typeInstance != NULL)
  6387. {
  6388. if (!mBfIRBuilder->mIgnoreWrites)
  6389. typeInstance->mHasBeenInstantiated = true;
  6390. allocSize = typeInstance->mInstSize;
  6391. allocAlign = typeInstance->mInstAlign;
  6392. //if (typeInstance->IsEnum())
  6393. //allocType = typeInstance->mIRType;
  6394. allocType = mBfIRBuilder->MapTypeInst(typeInstance);
  6395. }
  6396. if (alignOverride != -1)
  6397. allocAlign = alignOverride;
  6398. // The "dynSize" cases:
  6399. // If we are not dyn, but we are a variable size and could be looped over multiple times then we attempt to reuse
  6400. // the last stack space. We won't use StackSave and StackRestore because a scoped alloc that occurs after this but
  6401. // needs to be retained after the current scopeData (ie: scopeData::), then it would cause these allocs to accumulate even
  6402. // though we'd expect their stack space to be released
  6403. auto _CreateDynAlloc = [&](const BfIRValue& sizeValue, int align)
  6404. {
  6405. MarkDynStack(scopeData);
  6406. BfType* intType = GetPrimitiveType(BfTypeCode_IntPtr);
  6407. // For dynamically sized scoped allocs, we need to check the previous size to see if we need to realloc
  6408. BfType* voidType = GetPrimitiveType(BfTypeCode_None);
  6409. BfType* voidPtrType = CreatePointerType(voidType);
  6410. if (!mCurMethodState->mDynStackRevIdx)
  6411. {
  6412. mCurMethodState->mDynStackRevIdx = CreateAlloca(intType, false, "curDynStackRevIdx");
  6413. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  6414. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRInitBlock);
  6415. auto storeInst = mBfIRBuilder->CreateStore(GetConstValue(0), mCurMethodState->mDynStackRevIdx);
  6416. mBfIRBuilder->ClearDebugLocation(storeInst);
  6417. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  6418. }
  6419. auto byteType = GetPrimitiveType(BfTypeCode_Int8);
  6420. auto bytePtrType = CreatePointerType(byteType);
  6421. auto dynSizeAllocaInst = CreateAlloca(intType, false, "dynSize");
  6422. auto dynStackRevIdx = CreateAlloca(intType, false, "dynStackRevIdx");
  6423. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  6424. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRInitBlock);
  6425. auto storeInst = mBfIRBuilder->CreateStore(GetConstValue(0), dynSizeAllocaInst);
  6426. mBfIRBuilder->ClearDebugLocation(storeInst);
  6427. storeInst = mBfIRBuilder->CreateStore(GetConstValue(0), dynStackRevIdx);
  6428. mBfIRBuilder->ClearDebugLocation(storeInst);
  6429. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  6430. auto dynPtrAllocaInst = CreateAlloca(bytePtrType, false, "dynPtr");
  6431. if (IsTargetingBeefBackend())
  6432. {
  6433. // Since we don't allocate a debug variable for this, with LifetimeExtends, the easiest way
  6434. // to ensure there isn't any register collision during looping is just to not allow it to
  6435. // bind to a register at all
  6436. mBfIRBuilder->SetAllocaForceMem(dynSizeAllocaInst);
  6437. mBfIRBuilder->SetAllocaForceMem(dynPtrAllocaInst);
  6438. }
  6439. auto resizeBB = mBfIRBuilder->CreateBlock("dynAlloc.resize");
  6440. auto endBB = mBfIRBuilder->CreateBlock("dynAlloc.end");
  6441. auto verCheckBB = mBfIRBuilder->CreateBlock("dynAlloc.verCheck");
  6442. auto curDynStackRevIdx = mBfIRBuilder->CreateLoad(mCurMethodState->mDynStackRevIdx);
  6443. auto prevSize = mBfIRBuilder->CreateLoad(dynSizeAllocaInst);
  6444. auto isGreater = mBfIRBuilder->CreateCmpGT(sizeValue, prevSize, true);
  6445. mBfIRBuilder->CreateCondBr(isGreater, resizeBB, verCheckBB);
  6446. mBfIRBuilder->AddBlock(verCheckBB);
  6447. mBfIRBuilder->SetInsertPoint(verCheckBB);
  6448. auto prevDynStackRevIdx = mBfIRBuilder->CreateLoad(dynStackRevIdx);
  6449. auto dynStackChanged = mBfIRBuilder->CreateCmpNE(prevDynStackRevIdx, curDynStackRevIdx);
  6450. mBfIRBuilder->CreateCondBr(dynStackChanged, resizeBB, endBB);
  6451. mBfIRBuilder->AddBlock(resizeBB);
  6452. mBfIRBuilder->SetInsertPoint(resizeBB);
  6453. auto allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(byteType), sizeValue);
  6454. mBfIRBuilder->SetAllocaAlignment(allocaInst, align);
  6455. mBfIRBuilder->CreateStore(allocaInst, dynPtrAllocaInst);
  6456. mBfIRBuilder->CreateStore(sizeValue, dynSizeAllocaInst);
  6457. mBfIRBuilder->CreateStore(curDynStackRevIdx, dynStackRevIdx);
  6458. mBfIRBuilder->CreateBr(endBB);
  6459. mBfIRBuilder->AddBlock(endBB);
  6460. mBfIRBuilder->SetInsertPoint(endBB);
  6461. return mBfIRBuilder->CreateLoad(dynPtrAllocaInst);
  6462. };
  6463. if (isScopeAlloc)
  6464. {
  6465. if (arraySize)
  6466. {
  6467. bool isConstantArraySize = arraySize.IsConst();
  6468. if (isRawArrayAlloc)
  6469. {
  6470. BfPointerType* ptrType = CreatePointerType(type);
  6471. if ((!isDynAlloc) && (!isConstantArraySize) && (mCurMethodState->mCurScope->IsLooped(NULL)))
  6472. {
  6473. BfIRValue sizeValue = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySize);
  6474. auto loadedPtr = _CreateDynAlloc(sizeValue, type->mAlign);
  6475. InitTypeInst(BfTypedValue(loadedPtr, ptrType), scopeData, zeroMemory, sizeValue);
  6476. return mBfIRBuilder->CreateBitCast(loadedPtr, mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapType(type)));
  6477. }
  6478. else
  6479. {
  6480. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  6481. isDynAlloc = (isDynAlloc) || (!arraySize.IsConst());
  6482. if (!isDynAlloc)
  6483. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  6484. else
  6485. {
  6486. MarkDynStack(scopeData);
  6487. SaveStackState(scopeData);
  6488. }
  6489. int typeSize = type->GetStride();
  6490. BfIRValue allocaInst;
  6491. BfIRValue result;
  6492. if ((typeInstance == NULL) || (typeInstance->mIsCRepr))
  6493. {
  6494. sizeValue = mBfIRBuilder->CreateMul(GetConstValue(typeSize), arraySize);
  6495. allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(type), arraySize);
  6496. result = allocaInst;
  6497. }
  6498. else
  6499. {
  6500. if (typeInstance->IsStruct())
  6501. typeSize = typeInstance->GetInstStride();
  6502. auto byteType = GetPrimitiveStructType(BfTypeCode_Int8);
  6503. sizeValue = mBfIRBuilder->CreateMul(GetConstValue(typeSize), arraySize);
  6504. allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(byteType), sizeValue);
  6505. auto ptrType = CreatePointerType(typeInstance);
  6506. result = mBfIRBuilder->CreateBitCast(allocaInst, mBfIRBuilder->MapType(ptrType));
  6507. if (!isDynAlloc)
  6508. mBfIRBuilder->ClearDebugLocation(result);
  6509. }
  6510. if (!isDynAlloc)
  6511. mBfIRBuilder->ClearDebugLocation(allocaInst);
  6512. mBfIRBuilder->SetAllocaAlignment(allocaInst, allocAlign);
  6513. if (!isDynAlloc)
  6514. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  6515. auto typedVal = BfTypedValue(result, type, BfTypedValueKind_Addr);
  6516. if (arraySize.IsConst())
  6517. {
  6518. auto constant = mBfIRBuilder->GetConstant(arraySize);
  6519. if (constant->mInt64 == 0)
  6520. noDtorCall = true;
  6521. }
  6522. if (!noDtorCall)
  6523. {
  6524. bool isConstSize = arraySize.IsConst();
  6525. BfIRBlock clearBlock;
  6526. BfIRBlock contBlock;
  6527. if (!isConstSize)
  6528. {
  6529. clearBlock = mBfIRBuilder->CreateBlock("clear");
  6530. contBlock = mBfIRBuilder->CreateBlock("clearCont");
  6531. mBfIRBuilder->CreateCondBr(mBfIRBuilder->CreateCmpNE(arraySize, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 0)), clearBlock, contBlock);
  6532. mBfIRBuilder->AddBlock(clearBlock);
  6533. mBfIRBuilder->SetInsertPoint(clearBlock);
  6534. }
  6535. AddStackAlloc(typedVal, NULL, scopeData, false, true);
  6536. if (!isConstSize)
  6537. {
  6538. mBfIRBuilder->CreateBr(contBlock);
  6539. mBfIRBuilder->AddBlock(contBlock);
  6540. mBfIRBuilder->SetInsertPoint(contBlock);
  6541. }
  6542. }
  6543. //InitTypeInst(typedVal, scopeData, zeroMemory, sizeValue);
  6544. return result;
  6545. }
  6546. }
  6547. else
  6548. {
  6549. if ((!isDynAlloc) && (!arraySize.IsConst()) && (mCurMethodState->mCurScope->IsLooped(NULL)))
  6550. {
  6551. // Generate and check new size
  6552. BfArrayType* arrayType = CreateArrayType(type, arrayDim);
  6553. auto firstElementField = &arrayType->mFieldInstances.back();
  6554. int arrayClassSize = firstElementField->mDataOffset;
  6555. sizeValue = GetConstValue(arrayClassSize);
  6556. BfIRValue elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySize);
  6557. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, elementDataSize);
  6558. auto loadedPtr = _CreateDynAlloc(sizeValue, arrayType->mAlign);
  6559. auto typedVal = BfTypedValue(mBfIRBuilder->CreateBitCast(loadedPtr, mBfIRBuilder->MapType(arrayType)), arrayType);
  6560. if (!noDtorCall)
  6561. AddStackAlloc(typedVal, NULL, scopeData, false, true);
  6562. InitTypeInst(typedVal, scopeData, zeroMemory, sizeValue);
  6563. return typedVal.mValue;
  6564. }
  6565. else
  6566. {
  6567. BfArrayType* arrayType = CreateArrayType(type, arrayDim);
  6568. auto firstElementField = &arrayType->mFieldInstances.back();
  6569. int arrayClassSize = firstElementField->mDataOffset;
  6570. sizeValue = GetConstValue(arrayClassSize);
  6571. BfIRValue elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySize);
  6572. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, elementDataSize);
  6573. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  6574. isDynAlloc = (isDynAlloc) || (!sizeValue.IsConst());
  6575. if (!isDynAlloc)
  6576. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  6577. else
  6578. {
  6579. MarkDynStack(scopeData);
  6580. SaveStackState(scopeData);
  6581. }
  6582. BfType* byteType = GetPrimitiveType(BfTypeCode_Int8);
  6583. auto allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(byteType), sizeValue);
  6584. if (!isDynAlloc)
  6585. mBfIRBuilder->ClearDebugLocation(allocaInst);
  6586. mBfIRBuilder->SetAllocaAlignment(allocaInst, allocAlign);
  6587. auto typedVal = BfTypedValue(mBfIRBuilder->CreateBitCast(allocaInst, mBfIRBuilder->MapType(arrayType)), arrayType);
  6588. mBfIRBuilder->ClearDebugLocation_Last();
  6589. if (!isDynAlloc)
  6590. mBfIRBuilder->SetInsertPoint(prevBlock);
  6591. if (!noDtorCall)
  6592. AddStackAlloc(typedVal, NULL, scopeData, false, true);
  6593. InitTypeInst(typedVal, scopeData, zeroMemory, sizeValue);
  6594. return typedVal.mValue;
  6595. }
  6596. }
  6597. }
  6598. else if (appendSizeValue)
  6599. {
  6600. // It may seem that we should check IsLooped against only the requested scope, BUT- if later on we perform
  6601. // a scoped alloc that crosses our boundary then we won't be able to reclaim the stack space, so we always
  6602. // use the "dynSize" version conservatively
  6603. if ((!isDynAlloc) && (!appendSizeValue.IsConst()) && (mCurMethodState->mCurScope->IsLooped(NULL)))
  6604. {
  6605. // Generate and check new size
  6606. sizeValue = GetConstValue(typeInstance->mInstSize);
  6607. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, appendSizeValue);
  6608. auto loadedPtr = _CreateDynAlloc(sizeValue, typeInstance->mAlign);
  6609. auto typedVal = BfTypedValue(mBfIRBuilder->CreateBitCast(loadedPtr, mBfIRBuilder->MapTypeInstPtr(typeInstance)), typeInstance);
  6610. if (!noDtorCall)
  6611. AddStackAlloc(typedVal, NULL, scopeData, mCurMethodState->mInConditionalBlock, true);
  6612. InitTypeInst(typedVal, scopeData, zeroMemory, sizeValue);
  6613. return typedVal.mValue;
  6614. }
  6615. else // stack alloc, unlooped, with append
  6616. {
  6617. sizeValue = GetConstValue(typeInstance->mInstSize);
  6618. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, appendSizeValue);
  6619. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  6620. bool wasDynAlloc = isDynAlloc;
  6621. isDynAlloc = (isDynAlloc) || (!sizeValue.IsConst());
  6622. if (!isDynAlloc)
  6623. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  6624. else
  6625. {
  6626. MarkDynStack(scopeData);
  6627. SaveStackState(scopeData);
  6628. }
  6629. auto sbyteType = GetPrimitiveType(BfTypeCode_Int8);
  6630. auto allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(sbyteType), sizeValue);
  6631. if (!isDynAlloc)
  6632. {
  6633. mBfIRBuilder->ClearDebugLocation(allocaInst);
  6634. }
  6635. mBfIRBuilder->SetAllocaAlignment(allocaInst, allocAlign);
  6636. bool mayBeLarge = false;
  6637. if (sizeValue.IsConst())
  6638. {
  6639. auto constantInt = mBfIRBuilder->GetConstant(sizeValue);
  6640. if (constantInt->mInt64 >= 4096)
  6641. mayBeLarge = true;
  6642. }
  6643. else
  6644. mayBeLarge = true;
  6645. if (((type->IsObject() && (!mayBeLarge))) ||
  6646. // If we create a memset that can fill in backwards (or at least 4k chunked backward) then we can remove the '!mayBeLarge' cond
  6647. ((zeroMemory) && (!mayBeLarge)))
  6648. {
  6649. mBfIRBuilder->SetAllocaNoChkStkHint(allocaInst);
  6650. }
  6651. BfIRValue castedVal;
  6652. if (!isDynAlloc)
  6653. {
  6654. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRInitBlock);
  6655. castedVal = mBfIRBuilder->CreateBitCast(allocaInst, mBfIRBuilder->MapTypeInstPtr(typeInstance));
  6656. mBfIRBuilder->ClearDebugLocation(castedVal);
  6657. mBfIRBuilder->SetInsertPoint(prevBlock);
  6658. if (WantsLifetimes())
  6659. {
  6660. mBfIRBuilder->CreateLifetimeStart(allocaInst);
  6661. scopeData->mDeferredLifetimeEnds.push_back(allocaInst);
  6662. }
  6663. }
  6664. else
  6665. {
  6666. castedVal = mBfIRBuilder->CreateBitCast(allocaInst, mBfIRBuilder->MapTypeInstPtr(typeInstance));
  6667. }
  6668. auto typedVal = BfTypedValue(castedVal, typeInstance);
  6669. if (!noDtorCall)
  6670. {
  6671. bool doCondAlloca = false;
  6672. if (!IsTargetingBeefBackend())
  6673. doCondAlloca = !wasDynAlloc && isDynAlloc && mCurMethodState->mInConditionalBlock;
  6674. AddStackAlloc(typedVal, NULL, scopeData, doCondAlloca, true);
  6675. }
  6676. InitTypeInst(typedVal, scopeData, zeroMemory, sizeValue);
  6677. return typedVal.mValue;
  6678. }
  6679. }
  6680. else // "Normal" stack alloc
  6681. {
  6682. BF_ASSERT(!sizeValue);
  6683. //TODO: If sizeValue is a constant then do this in the head IR builder
  6684. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  6685. if (!isLoopedAlloc)
  6686. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  6687. else
  6688. {
  6689. MarkDynStack(scopeData);
  6690. SaveStackState(scopeData);
  6691. }
  6692. auto allocaInst = mBfIRBuilder->CreateAlloca(allocType);
  6693. if (!isLoopedAlloc)
  6694. mBfIRBuilder->ClearDebugLocation(allocaInst);
  6695. mBfIRBuilder->SetAllocaAlignment(allocaInst, allocAlign);
  6696. bool mayBeLarge = allocSize >= 4096;
  6697. if (((typeInstance != NULL) && (typeInstance->IsObject()) && (!mayBeLarge)) ||
  6698. // If we create a memset that can fill in backwards (or at least 4k chunked backward) then we can remove the '!mayBeLarge' cond
  6699. ((zeroMemory) && (!mayBeLarge)))
  6700. {
  6701. // With an object, we know we will at least set the vdata pointer which will probe the start of the new address,
  6702. // and memset is always safe
  6703. mBfIRBuilder->SetAllocaNoChkStkHint(allocaInst);
  6704. }
  6705. auto typedVal = BfTypedValue(allocaInst, type);
  6706. if (!isLoopedAlloc)
  6707. {
  6708. mBfIRBuilder->ClearDebugLocation(allocaInst);
  6709. mBfIRBuilder->SetInsertPoint(prevBlock);
  6710. if (WantsLifetimes())
  6711. {
  6712. mBfIRBuilder->CreateLifetimeStart(allocaInst);
  6713. scopeData->mDeferredLifetimeEnds.push_back(allocaInst);
  6714. }
  6715. }
  6716. if (!noDtorCall)
  6717. AddStackAlloc(typedVal, NULL, scopeData, false, true);
  6718. if (typeInstance != NULL)
  6719. {
  6720. InitTypeInst(typedVal, scopeData, zeroMemory, GetConstValue(typeInstance->mInstSize));
  6721. }
  6722. else
  6723. {
  6724. mBfIRBuilder->CreateMemSet(allocaInst, GetConstValue8(0), GetConstValue(allocSize), allocAlign);
  6725. }
  6726. return allocaInst;
  6727. }
  6728. }
  6729. else if (arraySize)
  6730. {
  6731. if (isRawArrayAlloc)
  6732. {
  6733. sizeValue = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySize);
  6734. return AllocBytes(allocTarget.mRefNode, allocTarget, type, sizeValue, GetConstValue(allocAlign), allocFlags);
  6735. }
  6736. else
  6737. {
  6738. BfArrayType* arrayType = CreateArrayType(type, arrayDim);
  6739. typeInstance = arrayType;
  6740. BfIRValue arraySizeMinusOne = mBfIRBuilder->CreateSub(arraySize, GetConstValue(1));
  6741. BfIRValue elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySizeMinusOne);
  6742. appendSizeValue = elementDataSize;
  6743. if (!type->IsSizeAligned())
  6744. {
  6745. appendSizeValue = mBfIRBuilder->CreateAdd(appendSizeValue, GetConstValue(type->GetStride() - type->mSize));
  6746. }
  6747. }
  6748. }
  6749. if ((typeInstance != NULL) && (typeInstance->IsObject()))
  6750. {
  6751. auto vDataRef = GetClassVDataPtr(typeInstance);
  6752. BfIRValue result;
  6753. bool isResultInitialized = false;
  6754. int stackCount = mCompiler->mOptions.mAllocStackCount;
  6755. if (typeInstance->mTypeOptionsIdx != -1)
  6756. {
  6757. auto typeOptions = mSystem->GetTypeOptions(typeInstance->mTypeOptionsIdx);
  6758. stackCount = BfTypeOptions::Apply(stackCount, typeOptions->mAllocStackTraceDepth);
  6759. }
  6760. if (!sizeValue)
  6761. sizeValue = GetConstValue(typeInstance->mInstSize);
  6762. if (appendSizeValue)
  6763. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, appendSizeValue);
  6764. BfIRValue origSizeValue = sizeValue;
  6765. bool isAllocEx = hasCustomAllocator && (stackCount > 1);
  6766. if (isAllocEx)
  6767. {
  6768. auto prepareStackTraceMethod = GetInternalMethod("Dbg_PrepareStackTrace");
  6769. if (prepareStackTraceMethod)
  6770. {
  6771. SizedArray<BfIRValue, 2> irArgs;
  6772. irArgs.Add(sizeValue);
  6773. irArgs.Add(GetConstValue(stackCount));
  6774. auto addlBytes = mBfIRBuilder->CreateCall(prepareStackTraceMethod.mFunc, irArgs);
  6775. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, addlBytes);
  6776. }
  6777. }
  6778. if (allocTarget.mCustomAllocator)
  6779. {
  6780. auto customAlloc = allocTarget.mCustomAllocator.mType->ToTypeInstance();
  6781. // Use AllocObject if we have it, otherwise we just use AllocBytes further down
  6782. if ((customAlloc != NULL) && (GetRawMethodByName(customAlloc, "AllocObject", -1, true, true) != NULL))
  6783. {
  6784. auto classVDataType = ResolveTypeDef(mCompiler->mClassVDataTypeDef);
  6785. mBfIRBuilder->PopulateType(classVDataType);
  6786. auto typeInstType = ResolveTypeDef(mCompiler->mReflectTypeInstanceTypeDef)->ToTypeInstance();
  6787. mBfIRBuilder->PopulateType(typeInstType);
  6788. auto typePtrPtr = mBfIRBuilder->CreateInBoundsGEP(vDataRef, 0, 1); // mType
  6789. auto typePtr = mBfIRBuilder->CreateLoad(typePtrPtr);
  6790. auto typeInstPtr = mBfIRBuilder->CreateBitCast(typePtr, mBfIRBuilder->MapTypeInstPtr(typeInstType));
  6791. BfTypedValueExpression typedValueExpr;
  6792. typedValueExpr.Init(BfTypedValue(typeInstPtr, typeInstType));
  6793. typedValueExpr.mRefNode = allocTarget.mRefNode;
  6794. BfExprEvaluator exprEvaluator(this);
  6795. SizedArray<BfExpression*, 2> argExprs;
  6796. argExprs.push_back(&typedValueExpr);
  6797. BfTypedValueExpression sizeValueExpr;
  6798. sizeValueExpr.Init(BfTypedValue(sizeValue, GetPrimitiveType(BfTypeCode_IntPtr)));
  6799. sizeValueExpr.mRefNode = allocTarget.mRefNode;
  6800. argExprs.push_back(&sizeValueExpr);
  6801. BfSizedArray<BfExpression*> sizedArgExprs(argExprs);
  6802. BfResolvedArgs argValues(&sizedArgExprs);
  6803. exprEvaluator.ResolveArgValues(argValues);
  6804. exprEvaluator.mNoBind = true;
  6805. BfTypedValue allocResult = exprEvaluator.MatchMethod(allocTarget.mRefNode, NULL, allocTarget.mCustomAllocator, false, false, "AllocObject", argValues, NULL);
  6806. if (allocResult)
  6807. {
  6808. if ((allocResult.mType->IsVoidPtr()) || (allocResult.mType == mContext->mBfObjectType))
  6809. result = mBfIRBuilder->CreateBitCast(allocResult.mValue, mBfIRBuilder->MapType(typeInstance));
  6810. else
  6811. result = CastToValue(allocTarget.mRefNode, allocResult, typeInstance, BfCastFlags_Explicit);
  6812. isResultInitialized = true;
  6813. }
  6814. }
  6815. }
  6816. if (!result)
  6817. {
  6818. if (hasCustomAllocator)
  6819. result = AllocBytes(allocTarget.mRefNode, allocTarget, typeInstance, sizeValue, GetConstValue(typeInstance->mInstAlign), (BfAllocFlags)(BfAllocFlags_ZeroMemory | BfAllocFlags_NoDefaultToMalloc));
  6820. }
  6821. if (result)
  6822. {
  6823. if (mCompiler->mOptions.mObjectHasDebugFlags)
  6824. {
  6825. auto objectPtr = mBfIRBuilder->CreateBitCast(result, mBfIRBuilder->MapTypeInstPtr(mContext->mBfObjectType));
  6826. SizedArray<BfIRValue, 4> llvmArgs;
  6827. llvmArgs.push_back(objectPtr);
  6828. llvmArgs.push_back(origSizeValue);
  6829. llvmArgs.push_back(vDataRef);
  6830. auto objectCreatedMethod = GetInternalMethod(isAllocEx ?
  6831. (isResultInitialized ? "Dbg_ObjectCreatedEx" : "Dbg_ObjectAllocatedEx") :
  6832. (isResultInitialized ? "Dbg_ObjectCreated" : "Dbg_ObjectAllocated"));
  6833. mBfIRBuilder->CreateCall(objectCreatedMethod.mFunc, llvmArgs);
  6834. }
  6835. else
  6836. {
  6837. auto ptrType = mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr);
  6838. auto vDataPtr = mBfIRBuilder->CreateBitCast(vDataRef, ptrType);
  6839. auto vDataMemberPtr = mBfIRBuilder->CreateBitCast(result, mBfIRBuilder->GetPointerTo(ptrType));
  6840. mBfIRBuilder->CreateStore(vDataPtr, vDataMemberPtr);
  6841. }
  6842. }
  6843. else
  6844. {
  6845. if ((mBfIRBuilder->mIgnoreWrites) || (mCompiler->mIsResolveOnly))
  6846. return GetDefaultValue(typeInstance);
  6847. auto classVDataType = ResolveTypeDef(mCompiler->mClassVDataTypeDef);
  6848. auto vData = mBfIRBuilder->CreateBitCast(vDataRef, mBfIRBuilder->MapTypeInstPtr(classVDataType->ToTypeInstance()));
  6849. if (mCompiler->mOptions.mObjectHasDebugFlags)
  6850. {
  6851. SizedArray<BfIRValue, 4> llvmArgs;
  6852. llvmArgs.push_back(vData);
  6853. llvmArgs.push_back(sizeValue);
  6854. llvmArgs.push_back(GetConstValue(typeInstance->mAlign));
  6855. llvmArgs.push_back(GetConstValue(stackCount));
  6856. auto moduleMethodInstance = GetInternalMethod("Dbg_ObjectAlloc", 4);
  6857. BfIRValue objectVal = mBfIRBuilder->CreateCall(moduleMethodInstance.mFunc, llvmArgs);
  6858. result = mBfIRBuilder->CreateBitCast(objectVal, mBfIRBuilder->MapType(typeInstance));
  6859. }
  6860. else
  6861. {
  6862. SizedArray<BfIRValue, 4> llvmArgs;
  6863. llvmArgs.push_back(sizeValue);
  6864. BfIRFunction irFunc;
  6865. if (mCompiler->mOptions.mDebugAlloc)
  6866. {
  6867. auto moduleMethodInstance = GetInternalMethod("Dbg_RawObjectAlloc", 1);
  6868. irFunc = moduleMethodInstance.mFunc;
  6869. }
  6870. if (!irFunc)
  6871. irFunc = GetBuiltInFunc(BfBuiltInFuncType_Malloc);
  6872. BfIRValue objectVal = mBfIRBuilder->CreateCall(irFunc, llvmArgs);
  6873. auto objResult = mBfIRBuilder->CreateBitCast(objectVal, mBfIRBuilder->MapType(mContext->mBfObjectType, BfIRPopulateType_Full));
  6874. auto vdataPtr = mBfIRBuilder->CreateInBoundsGEP(objResult, 0, 0);
  6875. mBfIRBuilder->CreateStore(vData, vdataPtr);
  6876. result = mBfIRBuilder->CreateBitCast(objectVal, mBfIRBuilder->MapType(typeInstance));
  6877. }
  6878. }
  6879. if ((zeroMemory) && (arraySize))
  6880. {
  6881. BfArrayType* arrayType = CreateArrayType(type, arrayDim);
  6882. typeInstance = arrayType;
  6883. auto firstElementField = &arrayType->mFieldInstances.back();
  6884. int arrayClassSize = firstElementField->mDataOffset;
  6885. BfIRValue elementDataSize;
  6886. bool skipZero = false;
  6887. if (arraySize.IsConst())
  6888. {
  6889. BfIRValue arraySizeMinusOne = mBfIRBuilder->CreateSub(arraySize, GetConstValue(1));
  6890. elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySizeMinusOne);
  6891. elementDataSize = mBfIRBuilder->CreateAdd(elementDataSize, GetConstValue(type->mSize));
  6892. auto constVal = mBfIRBuilder->GetConstant(elementDataSize);
  6893. if (constVal->mInt64 <= 0)
  6894. skipZero = true;
  6895. }
  6896. else
  6897. {
  6898. // For non const, don't use an unpadded last element - saves us checking against negative numbers going into memset for the zero-length case
  6899. elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySize);
  6900. }
  6901. if (!skipZero)
  6902. {
  6903. auto i8Type = GetPrimitiveType(BfTypeCode_Int8);
  6904. auto ptrType = CreatePointerType(i8Type);
  6905. auto ptrVal = mBfIRBuilder->CreateBitCast(result, mBfIRBuilder->MapType(ptrType));
  6906. ptrVal = mBfIRBuilder->CreateInBoundsGEP(ptrVal, arrayClassSize);
  6907. mBfIRBuilder->CreateMemSet(ptrVal, GetConstValue8(0), elementDataSize, type->mAlign);
  6908. appendSizeValue = elementDataSize;
  6909. }
  6910. }
  6911. return result;
  6912. }
  6913. else
  6914. {
  6915. if (!sizeValue)
  6916. sizeValue = GetConstValue(allocSize);
  6917. return AllocBytes(allocTarget.mRefNode, allocTarget, type, sizeValue, GetConstValue(allocAlign), zeroMemory ? BfAllocFlags_ZeroMemory : BfAllocFlags_None);
  6918. }
  6919. }
  6920. void BfModule::ValidateAllocation(BfType* type, BfAstNode* refNode)
  6921. {
  6922. if ((type == NULL) || (refNode == NULL))
  6923. return;
  6924. auto typeInstance = type->ToTypeInstance();
  6925. if ((typeInstance != NULL) && (typeInstance->mTypeDef->mIsOpaque))
  6926. Fail(StrFormat("Unable to allocate opaque type '%s'", TypeToString(type).c_str()), refNode);
  6927. }
  6928. void BfModule::EmitAlign(BfIRValue& appendCurIdx, int align)
  6929. {
  6930. appendCurIdx = mBfIRBuilder->CreateAdd(appendCurIdx, GetConstValue(align - 1));
  6931. appendCurIdx = mBfIRBuilder->CreateAnd(appendCurIdx, GetConstValue(~(align - 1)));
  6932. }
  6933. void BfModule::EmitAppendAlign(int align, int sizeMultiple)
  6934. {
  6935. if (sizeMultiple == 0)
  6936. sizeMultiple = align;
  6937. if ((mCurMethodState->mCurAppendAlign != 0) && (mCurMethodState->mCurAppendAlign % align != 0))
  6938. {
  6939. if (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_Ctor)
  6940. {
  6941. auto localVar = mCurMethodState->GetRootMethodState()->mLocals[1];
  6942. BF_ASSERT(localVar->mName == "appendIdx");
  6943. auto appendIdxVal = BfTypedValue(localVar->mValue, localVar->mResolvedType, true);
  6944. BfIRValue appendCurIdx = mBfIRBuilder->CreateLoad(appendIdxVal.mValue);
  6945. if (align > 1)
  6946. {
  6947. appendCurIdx = mBfIRBuilder->CreateAdd(appendCurIdx, GetConstValue(align - 1));
  6948. appendCurIdx = mBfIRBuilder->CreateAnd(appendCurIdx, GetConstValue(~(align - 1)));
  6949. }
  6950. mBfIRBuilder->CreateStore(appendCurIdx, appendIdxVal.mValue);
  6951. }
  6952. else
  6953. {
  6954. BF_ASSERT(mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend);
  6955. BfIRValue appendCurIdxPtr = mCurMethodState->mRetVal.mValue;
  6956. BfIRValue appendCurIdx = mBfIRBuilder->CreateLoad(appendCurIdxPtr);
  6957. appendCurIdx = mBfIRBuilder->CreateAdd(appendCurIdx, GetConstValue(align - 1));
  6958. appendCurIdx = mBfIRBuilder->CreateAnd(appendCurIdx, GetConstValue(~(align - 1)));
  6959. mBfIRBuilder->CreateStore(appendCurIdx, appendCurIdxPtr);
  6960. }
  6961. }
  6962. if (mCurMethodState->mCurAppendAlign == 0)
  6963. mCurMethodState->mCurAppendAlign = sizeMultiple;
  6964. else
  6965. {
  6966. if (sizeMultiple % align == 0)
  6967. mCurMethodState->mCurAppendAlign = align;
  6968. else
  6969. mCurMethodState->mCurAppendAlign = sizeMultiple % align;
  6970. }
  6971. }
  6972. BfIRValue BfModule::AppendAllocFromType(BfType* type, BfIRValue appendSizeValue, int appendAllocAlign, BfIRValue arraySize, int arrayDim, bool isRawArrayAlloc, bool zeroMemory)
  6973. {
  6974. auto localVar = mCurMethodState->GetRootMethodState()->mLocals[1];
  6975. BF_ASSERT(localVar->mName == "appendIdx");
  6976. BfTypedValue appendIdxVal(localVar->mValue, localVar->mResolvedType, true);
  6977. BfIRValue retValue;
  6978. BfTypeInstance* retTypeInstance = NULL;
  6979. auto intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  6980. auto voidPtrType = GetPrimitiveType(BfTypeCode_NullPtr);
  6981. if (arraySize)
  6982. {
  6983. if (isRawArrayAlloc)
  6984. {
  6985. EmitAppendAlign(type->mAlign);
  6986. BfPointerType* ptrType = CreatePointerType(type);
  6987. BfIRValue sizeValue = mBfIRBuilder->CreateMul(GetConstValue(type->mSize), arraySize);
  6988. auto curIdxVal = mBfIRBuilder->CreateLoad(appendIdxVal.mValue);
  6989. if (mSystem->mPtrSize != 4)
  6990. sizeValue = mBfIRBuilder->CreateNumericCast(sizeValue, true, (intPtrType->mSize == 4) ? BfTypeCode_Int32 : BfTypeCode_Int64);
  6991. auto newIdxVal = mBfIRBuilder->CreateAdd(curIdxVal, sizeValue);
  6992. mBfIRBuilder->CreateStore(newIdxVal, appendIdxVal.mValue);
  6993. if (zeroMemory)
  6994. {
  6995. auto ptr = mBfIRBuilder->CreateIntToPtr(curIdxVal, mBfIRBuilder->MapType(voidPtrType));
  6996. mBfIRBuilder->CreateMemSet(ptr, GetConstValue8(0), sizeValue, type->mAlign);
  6997. }
  6998. return mBfIRBuilder->CreateIntToPtr(curIdxVal, mBfIRBuilder->MapType(ptrType));
  6999. }
  7000. else
  7001. {
  7002. BfArrayType* arrayType = CreateArrayType(type, arrayDim);
  7003. EmitAppendAlign(arrayType->mAlign, type->mSize);
  7004. auto firstElementField = &arrayType->mFieldInstances.back();
  7005. int arrayClassSize = arrayType->mInstSize - firstElementField->mDataSize;
  7006. BfIRValue sizeValue = GetConstValue(arrayClassSize);
  7007. BfIRValue elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->mSize), arraySize);
  7008. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, elementDataSize);
  7009. auto curIdxVal = mBfIRBuilder->CreateLoad(appendIdxVal.mValue);
  7010. if (mSystem->mPtrSize != 4)
  7011. sizeValue = mBfIRBuilder->CreateNumericCast(sizeValue, true, (intPtrType->mSize == 4) ? BfTypeCode_Int32 : BfTypeCode_Int64);
  7012. auto newIdxVal = mBfIRBuilder->CreateAdd(curIdxVal, sizeValue);
  7013. mBfIRBuilder->CreateStore(newIdxVal, appendIdxVal.mValue);
  7014. if (zeroMemory)
  7015. {
  7016. // Only zero out the actual elements
  7017. int dataOffset = arrayType->mFieldInstances.back().mDataOffset;
  7018. auto newOffset = mBfIRBuilder->CreateAdd(curIdxVal, GetConstValue(dataOffset));
  7019. auto newSize = mBfIRBuilder->CreateSub(sizeValue, GetConstValue(dataOffset));
  7020. auto ptr = mBfIRBuilder->CreateIntToPtr(newOffset, mBfIRBuilder->MapType(voidPtrType));
  7021. mBfIRBuilder->CreateMemSet(ptr, GetConstValue8(0), newSize, type->mAlign);
  7022. }
  7023. retTypeInstance = arrayType;
  7024. retValue = mBfIRBuilder->CreateIntToPtr(curIdxVal, mBfIRBuilder->MapType(arrayType));
  7025. }
  7026. }
  7027. else
  7028. {
  7029. auto typeInst = type->ToTypeInstance();
  7030. BfIRValue sizeValue;
  7031. BfIRType toType;
  7032. if (typeInst != NULL)
  7033. {
  7034. EmitAppendAlign(typeInst->mInstAlign, typeInst->mInstSize);
  7035. sizeValue = GetConstValue(typeInst->mInstSize);
  7036. toType = mBfIRBuilder->MapTypeInstPtr(typeInst);
  7037. }
  7038. else
  7039. {
  7040. EmitAppendAlign(type->mAlign, type->mSize);
  7041. sizeValue = GetConstValue(type->mSize);
  7042. auto toPtrType = CreatePointerType(type);
  7043. toType = mBfIRBuilder->MapType(toPtrType);
  7044. }
  7045. auto curIdxVal = mBfIRBuilder->CreateLoad(appendIdxVal.mValue);
  7046. auto newIdxVal = mBfIRBuilder->CreateAdd(curIdxVal, sizeValue);
  7047. mBfIRBuilder->CreateStore(newIdxVal, appendIdxVal.mValue);
  7048. retTypeInstance = typeInst;
  7049. retValue = mBfIRBuilder->CreateIntToPtr(curIdxVal, toType);
  7050. }
  7051. if ((retTypeInstance != NULL) && (retTypeInstance->IsObject()))
  7052. {
  7053. mBfIRBuilder->PopulateType(retTypeInstance);
  7054. auto int8Type = mBfIRBuilder->GetPrimitiveType(BfTypeCode_Int8);
  7055. auto ptrType = mBfIRBuilder->GetPointerTo(int8Type);
  7056. auto ptrPtrType = mBfIRBuilder->GetPointerTo(ptrType);
  7057. auto curThis = GetThis();
  7058. BfIRValue newFlags;
  7059. if (mCompiler->mOptions.mObjectHasDebugFlags)
  7060. {
  7061. auto thisFlagsPtr = mBfIRBuilder->CreateBitCast(curThis.mValue, ptrType);
  7062. auto thisFlags = mBfIRBuilder->CreateLoad(thisFlagsPtr);
  7063. auto maskedThisFlags = mBfIRBuilder->CreateAnd(thisFlags, GetConstValue8(BfObjectFlag_StackAlloc)); // Take 'stack' flag from 'this'
  7064. newFlags = mBfIRBuilder->CreateOr(maskedThisFlags, GetConstValue8(BfObjectFlag_AppendAlloc));
  7065. }
  7066. auto vObjectAddr = mBfIRBuilder->CreateInBoundsGEP(retValue, 0, 0);
  7067. auto vDataRef = CreateClassVDataGlobal(retTypeInstance);
  7068. auto destAddr = mBfIRBuilder->CreateBitCast(vObjectAddr, ptrPtrType);
  7069. auto srcVal = mBfIRBuilder->CreateBitCast(vDataRef, ptrType);
  7070. mBfIRBuilder->CreateStore(srcVal, destAddr);
  7071. if (mCompiler->mOptions.mObjectHasDebugFlags)
  7072. {
  7073. auto flagsPtr = mBfIRBuilder->CreateBitCast(destAddr, ptrType);
  7074. mBfIRBuilder->CreateStore(newFlags, flagsPtr);
  7075. }
  7076. }
  7077. if (appendSizeValue)
  7078. {
  7079. EmitAppendAlign(appendAllocAlign);
  7080. auto curIdxVal = mBfIRBuilder->CreateLoad(appendIdxVal.mValue);
  7081. auto newIdxVal = mBfIRBuilder->CreateAdd(curIdxVal, appendSizeValue);
  7082. mBfIRBuilder->CreateStore(newIdxVal, appendIdxVal.mValue);
  7083. }
  7084. return retValue;
  7085. }
  7086. bool BfModule::IsOptimized()
  7087. {
  7088. if (mProject == NULL)
  7089. return false;
  7090. int optLevel = GetModuleOptions().mOptLevel;
  7091. return (optLevel >= BfOptLevel_O1) && (optLevel <= BfOptLevel_O3);
  7092. }
  7093. bool BfModule::IsTargetingBeefBackend()
  7094. {
  7095. if (mProject == NULL)
  7096. return false;
  7097. return GetModuleOptions().mOptLevel == BfOptLevel_OgPlus;
  7098. }
  7099. bool BfModule::WantsLifetimes()
  7100. {
  7101. if (mProject == NULL)
  7102. return false;
  7103. return GetModuleOptions().mOptLevel == BfOptLevel_OgPlus;
  7104. }
  7105. bool BfModule::HasCompiledOutput()
  7106. {
  7107. return (!mSystem->mIsResolveOnly) && (mIsReified);
  7108. }
  7109. // We will skip the object access check for any occurances of this value
  7110. void BfModule::SkipObjectAccessCheck(BfTypedValue typedVal)
  7111. {
  7112. if ((mBfIRBuilder->mIgnoreWrites) || (!typedVal.mType->IsObjectOrInterface()) || (mCurMethodState == NULL) || (mCurMethodState->mIgnoreObjectAccessCheck))
  7113. return;
  7114. if (!mCompiler->mOptions.mObjectHasDebugFlags)
  7115. return;
  7116. if ((typedVal.mValue.mFlags & BfIRValueFlags_Value) == 0)
  7117. return;
  7118. mCurMethodState->mSkipObjectAccessChecks.Add(typedVal.mValue.mId);
  7119. }
  7120. void BfModule::EmitObjectAccessCheck(BfTypedValue typedVal)
  7121. {
  7122. if ((mBfIRBuilder->mIgnoreWrites) || (!typedVal.mType->IsObjectOrInterface()) || (mCurMethodState == NULL) || (mCurMethodState->mIgnoreObjectAccessCheck))
  7123. return;
  7124. if (!mCompiler->mOptions.mObjectHasDebugFlags)
  7125. return;
  7126. bool emitObjectAccessCheck = mCompiler->mOptions.mEmitObjectAccessCheck;
  7127. auto typeOptions = GetTypeOptions();
  7128. if (typeOptions != NULL)
  7129. emitObjectAccessCheck = BfTypeOptions::Apply(emitObjectAccessCheck, typeOptions->mEmitObjectAccessCheck);
  7130. if (!emitObjectAccessCheck)
  7131. return;
  7132. if ((typedVal.mValue.mFlags & BfIRValueFlags_Value) != 0)
  7133. {
  7134. if (mCurMethodState->mSkipObjectAccessChecks.Contains(typedVal.mValue.mId))
  7135. return;
  7136. }
  7137. if (typedVal.IsAddr())
  7138. typedVal = LoadValue(typedVal);
  7139. mBfIRBuilder->CreateObjectAccessCheck(typedVal.mValue, !IsOptimized());
  7140. }
  7141. void BfModule::EmitEnsureInstructionAt()
  7142. {
  7143. if (mProject == NULL)
  7144. return;
  7145. if ((mBfIRBuilder->mIgnoreWrites) || (!mHasFullDebugInfo) || (IsOptimized()) || (mCompiler->mOptions.mOmitDebugHelpers))
  7146. return;
  7147. mBfIRBuilder->CreateEnsureInstructionAt();
  7148. }
  7149. void BfModule::EmitDynamicCastCheck(const BfTypedValue& targetValue, BfType* targetType, BfIRBlock trueBlock, BfIRBlock falseBlock, bool nullSucceeds)
  7150. {
  7151. if (mBfIRBuilder->mIgnoreWrites)
  7152. return; // Nothing needed here
  7153. auto irb = mBfIRBuilder;
  7154. auto checkBB = irb->CreateBlock("as.check");
  7155. auto isNull = irb->CreateIsNull(targetValue.mValue);
  7156. mBfIRBuilder->CreateCondBr(isNull, nullSucceeds ? trueBlock : falseBlock, checkBB);
  7157. auto intType = GetPrimitiveType(BfTypeCode_IntPtr);
  7158. auto intPtrType = CreatePointerType(intType);
  7159. auto intPtrPtrType = CreatePointerType(intPtrType);
  7160. auto int32Type = GetPrimitiveType(BfTypeCode_Int32);
  7161. auto int32PtrType = CreatePointerType(int32Type);
  7162. auto typeTypeInstance = ResolveTypeDef(mCompiler->mReflectTypeInstanceTypeDef)->ToTypeInstance();
  7163. if (mCompiler->mOptions.mAllowHotSwapping)
  7164. {
  7165. BfExprEvaluator exprEvaluator(this);
  7166. AddBasicBlock(checkBB);
  7167. auto objectParam = mBfIRBuilder->CreateBitCast(targetValue.mValue, mBfIRBuilder->MapType(mContext->mBfObjectType));
  7168. auto moduleMethodInstance = GetMethodByName(mContext->mBfObjectType, targetType->IsInterface() ? "DynamicCastToInterface" : "DynamicCastToTypeId");
  7169. SizedArray<BfIRValue, 4> irArgs;
  7170. irArgs.push_back(objectParam);
  7171. irArgs.push_back(GetConstValue32(targetType->mTypeId));
  7172. auto callResult = exprEvaluator.CreateCall(moduleMethodInstance.mMethodInstance, moduleMethodInstance.mFunc, false, irArgs);
  7173. auto resultType = ResolveTypeDef(mSystem->mTypeBool);
  7174. auto cmpResult = mBfIRBuilder->CreateCmpNE(callResult.mValue, GetDefaultValue(callResult.mType));
  7175. irb->CreateCondBr(cmpResult, trueBlock, falseBlock);
  7176. }
  7177. else
  7178. {
  7179. AddBasicBlock(checkBB);
  7180. BfIRValue vDataPtr = irb->CreateBitCast(targetValue.mValue, irb->MapType(intPtrType));
  7181. vDataPtr = irb->CreateLoad(vDataPtr);
  7182. if (mCompiler->mOptions.mObjectHasDebugFlags)
  7183. vDataPtr = irb->CreateAnd(vDataPtr, irb->CreateConst(BfTypeCode_IntPtr, (uint64)~0xFFULL));
  7184. if (targetType->IsInterface())
  7185. {
  7186. auto targetTypeInst = targetType->ToTypeInstance();
  7187. AddDependency(targetType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ExprTypeReference);
  7188. // Skip past mType, but since a 'GetDynCastVDataCount()' data is included in the sSlotOfs, we need to remove that
  7189. //int inheritanceIdOfs = mSystem->mPtrSize - (mCompiler->GetDynCastVDataCount())*4;
  7190. //vDataPtr = irb->CreateAdd(vDataPtr, irb->CreateConst(BfTypeCode_IntPtr, inheritanceIdOfs));
  7191. vDataPtr = irb->CreateAdd(vDataPtr, irb->GetConfigConst(BfIRConfigConst_DynSlotOfs, BfTypeCode_IntPtr));
  7192. BfIRValue slotOfs = GetInterfaceSlotNum(targetType->ToTypeInstance());
  7193. BfIRValue slotByteOfs = irb->CreateMul(slotOfs, irb->CreateConst(BfTypeCode_Int32, 4));
  7194. slotByteOfs = irb->CreateNumericCast(slotByteOfs, false, BfTypeCode_IntPtr);
  7195. vDataPtr = irb->CreateAdd(vDataPtr, slotByteOfs);
  7196. vDataPtr = irb->CreateIntToPtr(vDataPtr, irb->MapType(int32PtrType));
  7197. BfIRValue typeId = irb->CreateLoad(vDataPtr);
  7198. BfIRValue cmpResult = irb->CreateCmpEQ(typeId, irb->CreateConst(BfTypeCode_Int32, targetType->mTypeId));
  7199. irb->CreateCondBr(cmpResult, trueBlock, falseBlock);
  7200. }
  7201. else
  7202. {
  7203. if (!targetType->IsTypeInstance())
  7204. targetType = GetWrappedStructType(targetType);
  7205. AddDependency(targetType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ExprTypeReference);
  7206. int inheritanceIdOfs = mSystem->mPtrSize;
  7207. vDataPtr = irb->CreateAdd(vDataPtr, irb->CreateConst(BfTypeCode_IntPtr, inheritanceIdOfs));
  7208. vDataPtr = irb->CreateIntToPtr(vDataPtr, irb->MapType(int32PtrType));
  7209. BfIRValue objInheritanceId = irb->CreateLoad(vDataPtr);
  7210. BfIRValue typeDataRef = CreateTypeDataRef(targetType);
  7211. BfIRValue typeInstDataRef = irb->CreateBitCast(typeDataRef, irb->MapType(typeTypeInstance, BfIRPopulateType_Full));
  7212. auto fieldInst = &typeTypeInstance->mFieldInstances[9];
  7213. BF_ASSERT(fieldInst->GetFieldDef()->mName == "mInheritanceId");
  7214. BfIRValue gepValue = irb->CreateInBoundsGEP(typeInstDataRef, 0, fieldInst->mDataIdx);
  7215. BfIRValue wantInheritanceId = irb->CreateLoad(gepValue);
  7216. fieldInst = &typeTypeInstance->mFieldInstances[10];
  7217. BF_ASSERT(fieldInst->GetFieldDef()->mName == "mInheritanceCount");
  7218. gepValue = irb->CreateInBoundsGEP(typeInstDataRef, 0, fieldInst->mDataIdx);
  7219. BfIRValue inheritanceCount = irb->CreateLoad(gepValue);
  7220. BfIRValue idDiff = irb->CreateSub(objInheritanceId, wantInheritanceId);
  7221. BfIRValue cmpResult = irb->CreateCmpLTE(idDiff, inheritanceCount, false);
  7222. irb->CreateCondBr(cmpResult, trueBlock, falseBlock);
  7223. }
  7224. }
  7225. }
  7226. void BfModule::EmitDynamicCastCheck(BfTypedValue typedVal, BfType* type, bool allowNull)
  7227. {
  7228. if (mBfIRBuilder->mIgnoreWrites)
  7229. return;
  7230. bool emitDynamicCastCheck = mCompiler->mOptions.mEmitDynamicCastCheck;
  7231. auto typeOptions = GetTypeOptions();
  7232. if (typeOptions != NULL)
  7233. emitDynamicCastCheck = BfTypeOptions::Apply(emitDynamicCastCheck, typeOptions->mEmitDynamicCastCheck);
  7234. if (emitDynamicCastCheck)
  7235. {
  7236. int wantTypeId = 0;
  7237. if (!type->IsGenericParam())
  7238. wantTypeId = type->mTypeId;
  7239. BfIRBlock failBlock = mBfIRBuilder->CreateBlock("dynFail");
  7240. BfIRBlock endBlock = mBfIRBuilder->CreateBlock("dynEnd");
  7241. EmitDynamicCastCheck(typedVal, type, endBlock, failBlock, allowNull ? true : false);
  7242. AddBasicBlock(failBlock);
  7243. SizedArray<BfIRValue, 8> llvmArgs;
  7244. auto bitAddr = mBfIRBuilder->CreateBitCast(typedVal.mValue, mBfIRBuilder->MapType(mContext->mBfObjectType));
  7245. llvmArgs.push_back(bitAddr);
  7246. llvmArgs.push_back(GetConstValue32(wantTypeId));
  7247. auto objDynCheck = GetInternalMethod("ObjectDynCheckFailed");
  7248. BF_ASSERT(objDynCheck);
  7249. if (objDynCheck)
  7250. {
  7251. auto callInst = mBfIRBuilder->CreateCall(objDynCheck.mFunc, llvmArgs);
  7252. }
  7253. mBfIRBuilder->CreateBr(endBlock);
  7254. AddBasicBlock(endBlock);
  7255. }
  7256. }
  7257. BfTypedValue BfModule::BoxValue(BfAstNode* srcNode, BfTypedValue typedVal, BfType* toType, const BfAllocTarget& allocTarget, bool callDtor)
  7258. {
  7259. if (mBfIRBuilder->mIgnoreWrites)
  7260. {
  7261. if (toType == mContext->mBfObjectType)
  7262. return BfTypedValue(mBfIRBuilder->GetFakeVal(), toType);
  7263. }
  7264. BP_ZONE("BoxValue");
  7265. BfTypeInstance* fromStructTypeInstance = typedVal.mType->ToTypeInstance();
  7266. if (typedVal.mType->IsNullable())
  7267. {
  7268. typedVal = MakeAddressable(typedVal);
  7269. auto innerType = typedVal.mType->GetUnderlyingType();
  7270. if (!innerType->IsValueType())
  7271. {
  7272. if (!mIgnoreErrors)
  7273. Fail("Only value types can be boxed", srcNode);
  7274. return BfTypedValue();
  7275. }
  7276. auto boxedType = CreateBoxedType(innerType);
  7277. auto resultType = toType;
  7278. if (resultType == NULL)
  7279. resultType = boxedType;
  7280. if (mBfIRBuilder->mIgnoreWrites)
  7281. return BfTypedValue(mBfIRBuilder->GetFakeVal(), resultType);
  7282. auto prevBB = mBfIRBuilder->GetInsertBlock();
  7283. auto boxBB = mBfIRBuilder->CreateBlock("boxedN.notNull");
  7284. auto endBB = mBfIRBuilder->CreateBlock("boxedN.end");
  7285. mBfIRBuilder->PopulateType(typedVal.mType);
  7286. auto hasValueAddr = mBfIRBuilder->CreateInBoundsGEP(typedVal.mValue, 0, innerType->IsValuelessType() ? 1 : 2); // has_value
  7287. auto hasValue = mBfIRBuilder->CreateLoad(hasValueAddr);
  7288. mBfIRBuilder->CreateCondBr(hasValue, boxBB, endBB);
  7289. AddDependency(boxedType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ReadFields);
  7290. mBfIRBuilder->AddBlock(boxBB);
  7291. mBfIRBuilder->SetInsertPoint(boxBB);
  7292. BfScopeData newScope;
  7293. newScope.mOuterIsConditional = true;
  7294. mCurMethodState->AddScope(&newScope);
  7295. NewScopeState();
  7296. BfIRValue nullableValueAddr;
  7297. BfIRValue loadedVal;
  7298. if (innerType->IsValuelessType())
  7299. {
  7300. loadedVal = mBfIRBuilder->GetFakeVal();
  7301. }
  7302. else
  7303. {
  7304. nullableValueAddr = mBfIRBuilder->CreateInBoundsGEP(typedVal.mValue, 0, 1); // value
  7305. loadedVal = mBfIRBuilder->CreateLoad(nullableValueAddr);
  7306. }
  7307. auto boxedVal = BoxValue(srcNode, BfTypedValue(loadedVal, fromStructTypeInstance->GetUnderlyingType()), resultType, allocTarget, callDtor);
  7308. RestoreScopeState();
  7309. if (!boxedVal)
  7310. return BfTypedValue();
  7311. mBfIRBuilder->CreateBr(endBB);
  7312. auto boxBBEnd = mBfIRBuilder->GetInsertBlock();
  7313. mBfIRBuilder->AddBlock(endBB);
  7314. mBfIRBuilder->SetInsertPoint(endBB);
  7315. auto phi = mBfIRBuilder->CreatePhi(mBfIRBuilder->MapType(resultType), 2);
  7316. mBfIRBuilder->AddPhiIncoming(phi, boxedVal.mValue, boxBBEnd);
  7317. mBfIRBuilder->AddPhiIncoming(phi, GetDefaultValue(resultType), prevBB);
  7318. return BfTypedValue(phi, resultType);
  7319. }
  7320. bool alreadyCheckedCast = false;
  7321. BfTypeInstance* toTypeInstance = NULL;
  7322. if (toType != NULL)
  7323. toTypeInstance = toType->ToTypeInstance();
  7324. bool isStructPtr = typedVal.mType->IsStructPtr();
  7325. if (fromStructTypeInstance == NULL)
  7326. {
  7327. auto primType = (BfPrimitiveType*)typedVal.mType;
  7328. fromStructTypeInstance = GetWrappedStructType(typedVal.mType);
  7329. if (isStructPtr)
  7330. {
  7331. if ((toTypeInstance != NULL) && (TypeIsSubTypeOf(fromStructTypeInstance, toTypeInstance)))
  7332. alreadyCheckedCast = true;
  7333. fromStructTypeInstance = typedVal.mType->GetUnderlyingType()->ToTypeInstance();
  7334. }
  7335. }
  7336. if (fromStructTypeInstance == NULL)
  7337. return BfTypedValue();
  7338. // Need to box it
  7339. bool isBoxedType = (fromStructTypeInstance != NULL) && (toType->IsBoxed());
  7340. if ((toType == NULL) || (toType == mContext->mBfObjectType) || (isBoxedType) || (alreadyCheckedCast) || (TypeIsSubTypeOf(fromStructTypeInstance, toTypeInstance)))
  7341. {
  7342. if (mBfIRBuilder->mIgnoreWrites)
  7343. return BfTypedValue(mBfIRBuilder->GetFakeVal(), (toType != NULL) ? toType : CreateBoxedType(typedVal.mType));
  7344. auto boxedType = CreateBoxedType(typedVal.mType);
  7345. mBfIRBuilder->PopulateType(boxedType);
  7346. AddDependency(boxedType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ReadFields);
  7347. auto allocaInst = AllocFromType(boxedType, allocTarget, BfIRValue(), BfIRValue(), 0, callDtor ? BfAllocFlags_None : BfAllocFlags_NoDtorCall);
  7348. BfTypedValue boxedTypedValue(allocaInst, boxedType);
  7349. mBfIRBuilder->SetName(allocaInst, "boxed." + fromStructTypeInstance->mTypeDef->mName->ToString());
  7350. if (boxedType->IsUnspecializedType())
  7351. {
  7352. BF_ASSERT((srcNode == NULL) || (mCurMethodInstance->mIsUnspecialized));
  7353. }
  7354. else
  7355. {
  7356. PopulateType(fromStructTypeInstance);
  7357. if (!fromStructTypeInstance->IsValuelessType())
  7358. {
  7359. typedVal = LoadValue(typedVal);
  7360. auto valPtr = mBfIRBuilder->CreateInBoundsGEP(allocaInst, 0, 1);
  7361. if ((typedVal.mType != fromStructTypeInstance) && (!isStructPtr))
  7362. {
  7363. auto ptrType = CreatePointerType(typedVal.mType);
  7364. valPtr = mBfIRBuilder->CreateBitCast(valPtr, mBfIRBuilder->MapType(ptrType));
  7365. }
  7366. if (typedVal.IsSplat())
  7367. {
  7368. AggregateSplatIntoAddr(typedVal, valPtr);
  7369. }
  7370. else
  7371. mBfIRBuilder->CreateStore(typedVal.mValue, valPtr);
  7372. }
  7373. }
  7374. if (toType == NULL)
  7375. {
  7376. return BfTypedValue(allocaInst, boxedType);
  7377. }
  7378. else
  7379. {
  7380. auto castedValue = mBfIRBuilder->CreateBitCast(allocaInst, mBfIRBuilder->MapType(toType));
  7381. return BfTypedValue(castedValue, toType);
  7382. }
  7383. }
  7384. return BfTypedValue();
  7385. }
  7386. bool BfModule::GetBasePropertyDef(BfPropertyDef*& propDef, BfTypeInstance*& typeInst)
  7387. {
  7388. BfTypeInstance* checkTypeInst = typeInst;
  7389. while (checkTypeInst != NULL)
  7390. {
  7391. for (auto checkProp : checkTypeInst->mTypeDef->mProperties)
  7392. {
  7393. if (checkProp->mName == propDef->mName)
  7394. {
  7395. auto checkPropDeclaration = BfNodeDynCast<BfPropertyDeclaration>(checkProp->mFieldDeclaration);
  7396. if ((checkPropDeclaration == NULL) || (checkPropDeclaration->mVirtualSpecifier == NULL) || (checkPropDeclaration->mVirtualSpecifier->GetToken() == BfToken_Virtual))
  7397. {
  7398. propDef = checkProp;
  7399. typeInst = checkTypeInst;
  7400. return true;
  7401. }
  7402. }
  7403. }
  7404. checkTypeInst = checkTypeInst->mBaseType;
  7405. }
  7406. return false;
  7407. }
  7408. BfMethodInstance* BfModule::GetRawMethodInstanceAtIdx(BfTypeInstance* typeInstance, int methodIdx, const char* assertName)
  7409. {
  7410. if (!typeInstance->mResolvingVarField)
  7411. {
  7412. if (typeInstance->IsIncomplete())
  7413. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  7414. }
  7415. else
  7416. {
  7417. if (methodIdx >= (int)typeInstance->mMethodInstanceGroups.size())
  7418. {
  7419. AssertErrorState();
  7420. return NULL;
  7421. }
  7422. }
  7423. if (assertName != NULL)
  7424. {
  7425. BF_ASSERT(typeInstance->mTypeDef->mMethods[methodIdx]->mName == assertName);
  7426. }
  7427. auto& methodGroup = typeInstance->mMethodInstanceGroups[methodIdx];
  7428. if (methodGroup.mDefault == NULL)
  7429. {
  7430. if (!mCompiler->mIsResolveOnly)
  7431. {
  7432. BF_ASSERT((methodGroup.mOnDemandKind == BfMethodOnDemandKind_NoDecl_AwaitingReference) || (methodGroup.mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingDecl));
  7433. methodGroup.mOnDemandKind = BfMethodOnDemandKind_Decl_AwaitingDecl;
  7434. // Get it from the owning module so we don't create a reference prematurely...
  7435. auto declModule = typeInstance->mModule;
  7436. return declModule->GetMethodInstance(typeInstance, typeInstance->mTypeDef->mMethods[methodIdx], BfTypeVector(), (BfGetMethodInstanceFlags)(BfGetMethodInstanceFlag_UnspecializedPass | BfGetMethodInstanceFlag_Unreified)).mMethodInstance;
  7437. }
  7438. else
  7439. {
  7440. auto declModule = typeInstance->mModule;
  7441. return declModule->GetMethodInstance(typeInstance, typeInstance->mTypeDef->mMethods[methodIdx], BfTypeVector(), (BfGetMethodInstanceFlags)(BfGetMethodInstanceFlag_UnspecializedPass)).mMethodInstance;
  7442. }
  7443. }
  7444. auto methodInstance = typeInstance->mMethodInstanceGroups[methodIdx].mDefault;
  7445. //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
  7446. // be from a call to the NON-raw version
  7447. // if (!methodInstance->mMethodInstanceGroup->IsImplemented())
  7448. // {
  7449. // methodInstance->mIsReified = mIsReified;
  7450. // if (methodInstance->mMethodProcessRequest == NULL)
  7451. // typeInstance->mModule->AddMethodToWorkList(methodInstance);
  7452. // }
  7453. return methodInstance;
  7454. }
  7455. BfMethodInstance* BfModule::GetRawMethodInstance(BfTypeInstance* typeInstance, BfMethodDef* methodDef)
  7456. {
  7457. if (methodDef->mIsLocalMethod)
  7458. {
  7459. return GetMethodInstance(typeInstance, methodDef, BfTypeVector()).mMethodInstance;
  7460. }
  7461. return GetRawMethodInstanceAtIdx(typeInstance, methodDef->mIdx);
  7462. }
  7463. BfMethodInstance* BfModule::GetRawMethodByName(BfTypeInstance* typeInstance, const StringImpl& methodName, int paramCount, bool checkBase, bool allowMixin)
  7464. {
  7465. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  7466. while (typeInstance != NULL)
  7467. {
  7468. typeInstance->mTypeDef->PopulateMemberSets();
  7469. BfMemberSetEntry* entry = NULL;
  7470. BfMethodDef* methodDef = NULL;
  7471. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(methodName, &entry))
  7472. methodDef = (BfMethodDef*)entry->mMemberDef;
  7473. while (methodDef != NULL)
  7474. {
  7475. if (((allowMixin) || (methodDef->mMethodType != BfMethodType_Mixin)) &&
  7476. (methodDef->mGenericParams.size() == 0) &&
  7477. ((paramCount == -1) || (paramCount == (int)methodDef->mParams.size())))
  7478. return GetRawMethodInstance(typeInstance, methodDef);
  7479. methodDef = methodDef->mNextWithSameName;
  7480. }
  7481. if (!checkBase)
  7482. break;
  7483. typeInstance = typeInstance->mBaseType;
  7484. }
  7485. return NULL;
  7486. }
  7487. BfMethodInstance* BfModule::GetUnspecializedMethodInstance(BfMethodInstance* methodInstance)
  7488. {
  7489. if ((methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mMethodGenericArguments.size() != 0))
  7490. methodInstance = methodInstance->mMethodInstanceGroup->mDefault;
  7491. auto owner = methodInstance->mMethodInstanceGroup->mOwner;
  7492. if (!owner->IsGenericTypeInstance())
  7493. return methodInstance;
  7494. auto genericType = (BfGenericTypeInstance*)owner;
  7495. if (genericType->IsUnspecializedType())
  7496. return methodInstance;
  7497. auto unspecializedType = ResolveTypeDef(genericType->mTypeDef);
  7498. if (unspecializedType == NULL)
  7499. {
  7500. AssertErrorState();
  7501. return methodInstance;
  7502. }
  7503. if (unspecializedType == NULL)
  7504. return methodInstance;
  7505. auto unspecializedTypeInst = unspecializedType->ToTypeInstance();
  7506. return GetRawMethodInstanceAtIdx(unspecializedTypeInst, methodInstance->mMethodDef->mIdx);
  7507. }
  7508. int BfModule::GetGenericParamAndReturnCount(BfMethodInstance* methodInstance)
  7509. {
  7510. int genericCount = 0;
  7511. auto unspecializedMethodInstance = GetUnspecializedMethodInstance(methodInstance);
  7512. for (int paramIdx = 0; paramIdx < unspecializedMethodInstance->GetParamCount(); paramIdx++)
  7513. {
  7514. auto param = unspecializedMethodInstance->GetParamType(paramIdx);
  7515. if (param->IsGenericParam())
  7516. genericCount++;
  7517. }
  7518. if (unspecializedMethodInstance->mReturnType->IsGenericParam())
  7519. genericCount++;
  7520. return genericCount;
  7521. }
  7522. BfModule* BfModule::GetSpecializedMethodModule(const SizedArrayImpl<BfProject*>& projectList)
  7523. {
  7524. BF_ASSERT(!mIsScratchModule);
  7525. BF_ASSERT(mIsReified);
  7526. BfModule* mainModule = this;
  7527. if (mParentModule != NULL)
  7528. mainModule = mParentModule;
  7529. BfModule* specModule = NULL;
  7530. BfModule** specModulePtr = NULL;
  7531. if (mainModule->mSpecializedMethodModules.TryGetValueWith(projectList, &specModulePtr))
  7532. {
  7533. return *specModulePtr;
  7534. }
  7535. else
  7536. {
  7537. String specModuleName = mModuleName;
  7538. for (auto bfProject : projectList)
  7539. specModuleName += StrFormat("@%s", bfProject->mName.c_str());
  7540. specModule = new BfModule(mContext, specModuleName);
  7541. specModule->mProject = mainModule->mProject;
  7542. specModule->mParentModule = mainModule;
  7543. specModule->mIsSpecializedMethodModuleRoot = true;
  7544. specModule->Init();
  7545. Array<BfProject*> projList;
  7546. for (auto project : projectList)
  7547. projList.Add(project);
  7548. mainModule->mSpecializedMethodModules[projList] = specModule;
  7549. }
  7550. return specModule;
  7551. }
  7552. BfIRValue BfModule::CreateFunctionFrom(BfMethodInstance* methodInstance, bool tryExisting, bool isInlined)
  7553. {
  7554. if (mCompiler->IsSkippingExtraResolveChecks())
  7555. return BfIRValue();
  7556. if (methodInstance->mMethodInstanceGroup->mOwner->IsInterface())
  7557. {
  7558. //BF_ASSERT(!methodInstance->mIRFunction);
  7559. return BfIRValue();
  7560. }
  7561. auto methodDef = methodInstance->mMethodDef;
  7562. StringT<128> methodName;
  7563. BfMangler::Mangle(methodName, mCompiler->GetMangleKind(), methodInstance);
  7564. if (isInlined != methodInstance->mAlwaysInline)
  7565. {
  7566. if (isInlined)
  7567. methodName += "__INLINE";
  7568. else
  7569. methodName += "__NOINLINE";
  7570. }
  7571. if (tryExisting)
  7572. {
  7573. auto func = mBfIRBuilder->GetFunction(methodName);
  7574. if (func)
  7575. return func;
  7576. }
  7577. if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  7578. {
  7579. if (methodDeclaration->mExternSpecifier != NULL)
  7580. {
  7581. auto intrinsic = GetIntrinsic(methodInstance);
  7582. if (intrinsic)
  7583. return intrinsic;
  7584. // If we have multiple entries with the same name, they could have different arguments and will generate other errors...
  7585. /*auto func = mBfIRBuilder->GetFunction(methodName);
  7586. if (func)
  7587. return func;*/
  7588. }
  7589. }
  7590. if (methodInstance->GetImportCallKind() != BfImportCallKind_None)
  7591. {
  7592. return CreateDllImportGlobalVar(methodInstance, false);
  7593. }
  7594. BfIRType returnType;
  7595. SizedArray<BfIRType, 8> paramTypes;
  7596. methodInstance->GetIRFunctionInfo(this, returnType, paramTypes);
  7597. auto funcType = mBfIRBuilder->CreateFunctionType(returnType, paramTypes);
  7598. auto func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, methodName);
  7599. auto callingConv = GetIRCallingConvention(methodInstance);
  7600. if (callingConv != BfIRCallingConv_CDecl)
  7601. mBfIRBuilder->SetFuncCallingConv(func, callingConv);
  7602. SetupIRMethod(methodInstance, func, isInlined);
  7603. // auto srcModule = methodInstance->GetOwner()->GetModule();
  7604. // if ((srcModule != NULL) && (srcModule->mProject != mProject))
  7605. // {
  7606. // if (srcModule->mProject->mTargetType == BfTargetType_BeefDynLib)
  7607. // {
  7608. // mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_DllImport);
  7609. // }
  7610. // }
  7611. return func;
  7612. }
  7613. BfModuleMethodInstance BfModule::GetMethodInstanceAtIdx(BfTypeInstance* typeInstance, int methodIdx, const char* assertName)
  7614. {
  7615. if (assertName != NULL)
  7616. {
  7617. BF_ASSERT(typeInstance->mTypeDef->mMethods[methodIdx]->mName == assertName);
  7618. }
  7619. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  7620. auto methodInstance = typeInstance->mMethodInstanceGroups[methodIdx].mDefault;
  7621. if ((methodInstance != NULL) && (mIsReified) && (!methodInstance->mIsReified))
  7622. {
  7623. // Can't use it, not reified
  7624. methodInstance = NULL;
  7625. }
  7626. if ((methodInstance != NULL) && (mBfIRBuilder != NULL) && (mBfIRBuilder->mIgnoreWrites) &&
  7627. (methodInstance->mMethodInstanceGroup->IsImplemented()))
  7628. {
  7629. BfIRFunction func(mBfIRBuilder->GetFakeVal());
  7630. return BfModuleMethodInstance(methodInstance, func);
  7631. }
  7632. return GetMethodInstance(typeInstance, typeInstance->mTypeDef->mMethods[methodIdx], BfTypeVector());
  7633. }
  7634. BfModuleMethodInstance BfModule::GetMethodByName(BfTypeInstance* typeInstance, const StringImpl& methodName, int paramCount, bool checkBase)
  7635. {
  7636. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  7637. while (typeInstance != NULL)
  7638. {
  7639. typeInstance->mTypeDef->PopulateMemberSets();
  7640. BfMemberSetEntry* entry = NULL;
  7641. BfMethodDef* methodDef = NULL;
  7642. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(methodName, &entry))
  7643. methodDef = (BfMethodDef*)entry->mMemberDef;
  7644. while (methodDef != NULL)
  7645. {
  7646. if ((methodDef->mMethodType != BfMethodType_Mixin) &&
  7647. (methodDef->mGenericParams.size() == 0) &&
  7648. ((paramCount == -1) || (paramCount == (int)methodDef->mParams.size())))
  7649. return GetMethodInstanceAtIdx(typeInstance, methodDef->mIdx);
  7650. methodDef = methodDef->mNextWithSameName;
  7651. }
  7652. if (!checkBase)
  7653. break;
  7654. typeInstance = typeInstance->mBaseType;
  7655. }
  7656. return BfModuleMethodInstance();
  7657. }
  7658. BfModuleMethodInstance BfModule::GetMethodByName(BfTypeInstance* typeInstance, const StringImpl& methodName, const Array<BfType*>& paramTypes, bool checkBase)
  7659. {
  7660. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  7661. while (typeInstance != NULL)
  7662. {
  7663. typeInstance->mTypeDef->PopulateMemberSets();
  7664. BfMemberSetEntry* entry = NULL;
  7665. BfMethodDef* methodDef = NULL;
  7666. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(methodName, &entry))
  7667. methodDef = (BfMethodDef*)entry->mMemberDef;
  7668. while (methodDef != NULL)
  7669. {
  7670. if ((methodDef->mMethodType != BfMethodType_Mixin) &&
  7671. (methodDef->mGenericParams.size() == 0) &&
  7672. (paramTypes.size() == methodDef->mParams.size()))
  7673. {
  7674. auto moduleMethodInstance = GetMethodInstanceAtIdx(typeInstance, methodDef->mIdx);
  7675. if (moduleMethodInstance.mMethodInstance != NULL)
  7676. {
  7677. bool matches = true;
  7678. for (int paramIdx = 0; paramIdx < (int)paramTypes.size(); paramIdx++)
  7679. {
  7680. if (moduleMethodInstance.mMethodInstance->GetParamType(paramIdx) != paramTypes[paramIdx])
  7681. matches = false;
  7682. }
  7683. if (matches)
  7684. return moduleMethodInstance;
  7685. }
  7686. }
  7687. methodDef = methodDef->mNextWithSameName;
  7688. }
  7689. if (!checkBase)
  7690. break;
  7691. typeInstance = typeInstance->mBaseType;
  7692. }
  7693. return BfModuleMethodInstance();
  7694. }
  7695. BfModuleMethodInstance BfModule::GetInternalMethod(const StringImpl& methodName, int paramCount)
  7696. {
  7697. auto internalType = ResolveTypeDef(mCompiler->mInternalTypeDef);
  7698. PopulateType(internalType);
  7699. auto moduleMethodInstance = GetMethodByName(internalType->ToTypeInstance(), methodName, paramCount);
  7700. if (!moduleMethodInstance)
  7701. {
  7702. Fail(StrFormat("Failed to find System.Internal method '%s'", methodName.c_str()));
  7703. }
  7704. return moduleMethodInstance;
  7705. }
  7706. bool BfModule::IsMethodImplementedAndReified(BfTypeInstance* typeInstance, const StringImpl& methodName, int paramCount, bool checkBase)
  7707. {
  7708. while (typeInstance != NULL)
  7709. {
  7710. typeInstance->mTypeDef->PopulateMemberSets();
  7711. BfMemberSetEntry* entry = NULL;
  7712. BfMethodDef* methodDef = NULL;
  7713. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(methodName, &entry))
  7714. methodDef = (BfMethodDef*)entry->mMemberDef;
  7715. while (methodDef != NULL)
  7716. {
  7717. if ((methodDef->mMethodType != BfMethodType_Mixin) &&
  7718. (methodDef->mGenericParams.size() == 0) &&
  7719. ((paramCount == -1) || (paramCount == (int)methodDef->mParams.size())))
  7720. {
  7721. auto& methodInstanceGroup = typeInstance->mMethodInstanceGroups[methodDef->mIdx];
  7722. if (!methodInstanceGroup.IsImplemented())
  7723. return false;
  7724. if (methodInstanceGroup.mDefault == NULL)
  7725. return false;
  7726. return methodInstanceGroup.mDefault->mIsReified;
  7727. }
  7728. methodDef = methodDef->mNextWithSameName;
  7729. }
  7730. if (!checkBase)
  7731. break;
  7732. typeInstance = typeInstance->mBaseType;
  7733. }
  7734. return false;
  7735. }
  7736. bool BfModule::HasMixin(BfTypeInstance* typeInstance, const StringImpl& methodName, int paramCount, bool checkBase)
  7737. {
  7738. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  7739. while (typeInstance != NULL)
  7740. {
  7741. typeInstance->mTypeDef->PopulateMemberSets();
  7742. BfMemberSetEntry* entry = NULL;
  7743. BfMethodDef* methodDef = NULL;
  7744. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(methodName, &entry))
  7745. methodDef = (BfMethodDef*)entry->mMemberDef;
  7746. while (methodDef != NULL)
  7747. {
  7748. if ((methodDef->mMethodType == BfMethodType_Mixin) &&
  7749. ((paramCount == -1) || (paramCount == (int)methodDef->mParams.size())))
  7750. return true;
  7751. methodDef = methodDef->mNextWithSameName;
  7752. }
  7753. if (!checkBase)
  7754. break;
  7755. typeInstance = typeInstance->mBaseType;
  7756. }
  7757. return BfModuleMethodInstance();
  7758. }
  7759. BfFieldInstance* BfModule::GetFieldByName(BfTypeInstance* typeInstance, const StringImpl& fieldName)
  7760. {
  7761. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  7762. typeInstance->mTypeDef->PopulateMemberSets();
  7763. BfMemberSetEntry* entry = NULL;
  7764. BfFieldDef* fieldDef = NULL;
  7765. if (typeInstance->mTypeDef->mFieldSet.TryGetWith(fieldName, &entry))
  7766. {
  7767. fieldDef = (BfFieldDef*)entry->mMemberDef;
  7768. return &typeInstance->mFieldInstances[fieldDef->mIdx];
  7769. }
  7770. // for (auto& fieldInst : typeInstance->mFieldInstances)
  7771. // {
  7772. // auto fieldDef = fieldInst.GetFieldDef();
  7773. // if ((fieldDef != NULL) && (fieldDef->mName == fieldName))
  7774. // return &fieldInst;
  7775. // }
  7776. return NULL;
  7777. }
  7778. String BfModule::MethodToString(BfMethodInstance* methodInst, BfMethodNameFlags methodNameFlags, BfTypeVector* methodGenericArgs)
  7779. {
  7780. auto methodDef = methodInst->mMethodDef;
  7781. bool allowResolveGenericParamNames = ((methodNameFlags & BfMethodNameFlag_ResolveGenericParamNames) != 0);
  7782. BfTypeNameFlags typeNameFlags = BfTypeNameFlags_None;
  7783. if ((mCurTypeInstance == NULL) || (!mCurTypeInstance->IsUnspecializedTypeVariation()))
  7784. typeNameFlags = BfTypeNameFlag_ResolveGenericParamNames;
  7785. BfType* type = methodInst->mMethodInstanceGroup->mOwner;
  7786. if ((methodGenericArgs != NULL) && (type->IsUnspecializedType()))
  7787. type = ResolveGenericType(type, *methodGenericArgs);
  7788. String methodName;
  7789. if ((methodNameFlags & BfMethodNameFlag_OmitTypeName) == 0)
  7790. {
  7791. methodName = TypeToString(type, typeNameFlags);
  7792. if (methodName == "$")
  7793. methodName = "";
  7794. else
  7795. methodName += ".";
  7796. }
  7797. String accessorString;
  7798. StringT<64> methodDefName = methodInst->mMethodDef->mName;
  7799. if (methodInst->mMethodDef->mIsLocalMethod)
  7800. {
  7801. int atPos = (int)methodDefName.IndexOf('$');
  7802. methodDefName.RemoveToEnd(atPos);
  7803. methodDefName.Replace("@", ".");
  7804. }
  7805. else
  7806. {
  7807. int atPos = (int)methodDefName.IndexOf('$');
  7808. if (atPos != -1)
  7809. {
  7810. accessorString = methodDefName.Substring(0, atPos);
  7811. if ((accessorString == "get") || (accessorString == "set"))
  7812. {
  7813. methodDefName = methodDefName.Substring(atPos + 1);
  7814. }
  7815. else
  7816. accessorString = "";
  7817. }
  7818. }
  7819. if ((methodInst->mMethodInfoEx != NULL) && (methodInst->mMethodInfoEx->mForeignType != NULL))
  7820. {
  7821. BfTypeNameFlags typeNameFlags = BfTypeNameFlags_None;
  7822. if (!methodInst->mIsUnspecializedVariation && allowResolveGenericParamNames)
  7823. typeNameFlags = BfTypeNameFlag_ResolveGenericParamNames;
  7824. methodName += TypeToString(methodInst->mMethodInfoEx->mForeignType, typeNameFlags);
  7825. methodName += ".";
  7826. }
  7827. if ((methodInst->mMethodInfoEx != NULL) && (methodInst->mMethodInfoEx->mExplicitInterface != NULL))
  7828. {
  7829. BfTypeNameFlags typeNameFlags = BfTypeNameFlags_None;
  7830. if (!methodInst->mIsUnspecializedVariation && allowResolveGenericParamNames)
  7831. typeNameFlags = BfTypeNameFlag_ResolveGenericParamNames;
  7832. methodName += "[";
  7833. methodName += TypeToString(methodInst->mMethodInfoEx->mExplicitInterface, typeNameFlags);
  7834. methodName += "].";
  7835. }
  7836. if (methodDef->mMethodType == BfMethodType_Operator)
  7837. {
  7838. BfOperatorDef* operatorDef = (BfOperatorDef*)methodDef;
  7839. if (operatorDef->mOperatorDeclaration->mIsConvOperator)
  7840. {
  7841. // Don't add explicit/implicit part, since that's not available in GCC mangling
  7842. /*if (operatorDef->mOperatorDeclaration->mExplicitToken != NULL)
  7843. {
  7844. if (operatorDef->mOperatorDeclaration->mExplicitToken->GetToken() == BfToken_Explicit)
  7845. methodName += "explicit ";
  7846. else if (operatorDef->mOperatorDeclaration->mExplicitToken->GetToken() == BfToken_Explicit)
  7847. methodName += "explicit ";
  7848. }*/
  7849. methodName += "operator ";
  7850. if (methodInst->mReturnType != NULL)
  7851. methodName += TypeToString(methodInst->mReturnType);
  7852. }
  7853. else
  7854. {
  7855. methodName += "operator";
  7856. if (operatorDef->mOperatorDeclaration->mOpTypeToken != NULL)
  7857. methodName += BfTokenToString(operatorDef->mOperatorDeclaration->mOpTypeToken->GetToken());
  7858. }
  7859. }
  7860. else if (methodDef->mMethodType == BfMethodType_Ctor)
  7861. {
  7862. if (methodDef->mIsStatic)
  7863. methodName += "__BfStaticCtor";
  7864. else
  7865. methodName += "this";
  7866. accessorString = "";
  7867. }
  7868. else if (methodDef->mMethodType == BfMethodType_PropertyGetter)
  7869. {
  7870. auto propertyDecl = methodDef->GetPropertyDeclaration();
  7871. if ((propertyDecl != NULL) && (propertyDecl->mNameNode != NULL))
  7872. propertyDecl->mNameNode->ToString(methodName);
  7873. methodName += " get accessor";
  7874. return methodName;
  7875. }
  7876. else if (methodDef->mMethodType == BfMethodType_PropertySetter)
  7877. {
  7878. auto propertyDecl = methodDef->GetPropertyDeclaration();
  7879. if ((propertyDecl != NULL) && (propertyDecl->mNameNode != NULL))
  7880. propertyDecl->mNameNode->ToString(methodName);
  7881. methodName += " set accessor";
  7882. return methodName;
  7883. }
  7884. else
  7885. methodName += methodDefName;
  7886. BfTypeVector newMethodGenericArgs;
  7887. if ((methodInst->mMethodInfoEx != NULL) && (methodInst->mMethodInfoEx->mMethodGenericArguments.size() != 0))
  7888. {
  7889. methodName += "<";
  7890. for (int i = 0; i < (int) methodInst->mMethodInfoEx->mMethodGenericArguments.size(); i++)
  7891. {
  7892. if (i > 0)
  7893. methodName += ", ";
  7894. BfTypeNameFlags typeNameFlags = BfTypeNameFlags_None;
  7895. //Why did we have this methodInst->mIsUnspecializedVariation check? Sometimes we do need to show errors calling methods that refer back to our types
  7896. //if (!methodInst->mIsUnspecializedVariation && allowResolveGenericParamNames)
  7897. if (allowResolveGenericParamNames)
  7898. typeNameFlags = BfTypeNameFlag_ResolveGenericParamNames;
  7899. BfType* type = methodInst->mMethodInfoEx->mMethodGenericArguments[i];
  7900. if ((methodGenericArgs != NULL) && (type->IsUnspecializedType()))
  7901. {
  7902. bool hasEmpty = false;
  7903. for (auto arg : *methodGenericArgs)
  7904. {
  7905. if (arg == NULL)
  7906. hasEmpty = true;
  7907. }
  7908. if (hasEmpty)
  7909. {
  7910. for (int genericIdx = 0; genericIdx < (int)methodGenericArgs->size(); genericIdx++)
  7911. {
  7912. auto arg = (*methodGenericArgs)[genericIdx];
  7913. if (arg != NULL)
  7914. newMethodGenericArgs.push_back(arg);
  7915. else
  7916. {
  7917. auto genericParamInst = methodInst->mMethodInfoEx->mGenericParams[genericIdx];
  7918. if (genericParamInst->mTypeConstraint != NULL)
  7919. newMethodGenericArgs.push_back(genericParamInst->mTypeConstraint);
  7920. else
  7921. newMethodGenericArgs.push_back(mContext->mBfObjectType); // Default
  7922. }
  7923. }
  7924. methodGenericArgs = &newMethodGenericArgs;
  7925. }
  7926. if (type->IsUnspecializedType())
  7927. type = ResolveGenericType(type, *methodGenericArgs);
  7928. }
  7929. methodName += TypeToString(type, typeNameFlags);
  7930. }
  7931. methodName += ">";
  7932. }
  7933. if (accessorString.length() == 0)
  7934. {
  7935. int dispParamIdx = 0;
  7936. methodName += "(";
  7937. for (int paramIdx = 0; paramIdx < (int) methodInst->GetParamCount(); paramIdx++)
  7938. {
  7939. int paramKind = methodInst->GetParamKind(paramIdx);
  7940. if (paramKind == BfParamKind_ImplicitCapture)
  7941. continue;
  7942. if (dispParamIdx > 0)
  7943. methodName += ", ";
  7944. if (paramKind == BfParamKind_Params)
  7945. methodName += "params ";
  7946. typeNameFlags = BfTypeNameFlag_ResolveGenericParamNames;
  7947. BfType* type = methodInst->GetParamType(paramIdx);
  7948. if ((methodGenericArgs != NULL) && (type->IsUnspecializedType()))
  7949. type = ResolveGenericType(type, *methodGenericArgs);
  7950. methodName += TypeToString(type, typeNameFlags);
  7951. methodName += " ";
  7952. methodName += methodInst->GetParamName(paramIdx);
  7953. dispParamIdx++;
  7954. }
  7955. methodName += ")";
  7956. }
  7957. if (accessorString.length() != 0)
  7958. {
  7959. methodName += " " + accessorString;
  7960. }
  7961. return methodName;
  7962. }
  7963. static void AddAttributeTargetName(BfAttributeTargets& flagsLeft, BfAttributeTargets checkFlag, String& str, String addString)
  7964. {
  7965. if ((flagsLeft & checkFlag) == 0)
  7966. return;
  7967. if (!str.empty())
  7968. {
  7969. if (flagsLeft == checkFlag)
  7970. {
  7971. if ((int)str.IndexOf(',') != -1)
  7972. str += ", and ";
  7973. else
  7974. str += " and ";
  7975. }
  7976. else
  7977. str += ", ";
  7978. }
  7979. str += addString;
  7980. flagsLeft = (BfAttributeTargets)(flagsLeft & ~checkFlag);
  7981. }
  7982. static String GetAttributesTargetListString(BfAttributeTargets attrTarget)
  7983. {
  7984. String resultStr;
  7985. auto flagsLeft = attrTarget;
  7986. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Assembly, resultStr, "assembly declarations");
  7987. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Module, resultStr, "module declarations");
  7988. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Class, resultStr, "class declarations");
  7989. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Struct, resultStr, "struct declarations");
  7990. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Enum, resultStr, "enum declarations");
  7991. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Constructor, resultStr, "constructor declarations");
  7992. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Method, resultStr, "method declarations");
  7993. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Property, resultStr, "property declarations");
  7994. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Field, resultStr, "field declarations");
  7995. AddAttributeTargetName(flagsLeft, BfAttributeTargets_StaticField, resultStr, "static field declarations");
  7996. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Interface, resultStr, "interface declarations");
  7997. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Parameter, resultStr, "parameter declarations");
  7998. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Delegate, resultStr, "delegate declarations");
  7999. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Function, resultStr, "function declarations");
  8000. AddAttributeTargetName(flagsLeft, BfAttributeTargets_ReturnValue, resultStr, "return value");
  8001. AddAttributeTargetName(flagsLeft, BfAttributeTargets_GenericParameter, resultStr, "generic parameters");
  8002. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Invocation, resultStr, "invocations");
  8003. AddAttributeTargetName(flagsLeft, BfAttributeTargets_MemberAccess, resultStr, "member access");
  8004. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Alloc, resultStr, "allocations");
  8005. if (resultStr.IsEmpty())
  8006. return "<nothing>";
  8007. return resultStr;
  8008. }
  8009. void BfModule::CurrentAddToConstHolder(BfIRValue& irVal)
  8010. {
  8011. auto constant = mBfIRBuilder->GetConstant(irVal);
  8012. int stringPoolIdx = GetStringPoolIdx(irVal, mBfIRBuilder);
  8013. if (stringPoolIdx != -1)
  8014. {
  8015. irVal = mCurTypeInstance->GetOrCreateConstHolder()->CreateConst(BfTypeCode_Int32, stringPoolIdx);
  8016. return;
  8017. }
  8018. if (constant->mConstType == BfConstType_Array)
  8019. {
  8020. auto constArray = (BfConstantArray*)constant;
  8021. SizedArray<BfIRValue, 8> newVals;
  8022. for (auto val : constArray->mValues)
  8023. {
  8024. auto newVal = val;
  8025. CurrentAddToConstHolder(newVal);
  8026. newVals.push_back(newVal);
  8027. }
  8028. irVal = mCurTypeInstance->mConstHolder->CreateConstArray(constArray->mType, newVals);
  8029. return;
  8030. }
  8031. auto origConst = irVal;
  8032. if ((constant->mConstType == BfConstType_BitCast) || (constant->mConstType == BfConstType_BitCastNull))
  8033. {
  8034. auto bitcast = (BfConstantBitCast*)constant;
  8035. constant = mBfIRBuilder->GetConstantById(bitcast->mTarget);
  8036. }
  8037. irVal = mCurTypeInstance->CreateConst(constant, mBfIRBuilder);
  8038. }
  8039. void BfModule::ClearConstData()
  8040. {
  8041. mBfIRBuilder->ClearConstData();
  8042. mStringObjectPool.Clear();
  8043. mStringCharPtrPool.Clear();
  8044. mStringPoolRefs.Clear();
  8045. }
  8046. BfTypedValue BfModule::GetTypedValueFromConstant(BfConstant* constant, BfIRConstHolder* constHolder, BfType* wantType)
  8047. {
  8048. bool isString = false;
  8049. isString = (wantType->IsObject()) && (wantType->ToTypeInstance()->mTypeDef == mCompiler->mStringTypeDef);
  8050. if (wantType->IsPointer())
  8051. isString = true;
  8052. if (!isString)
  8053. {
  8054. switch (constant->mTypeCode)
  8055. {
  8056. case BfTypeCode_Boolean:
  8057. case BfTypeCode_Int8:
  8058. case BfTypeCode_UInt8:
  8059. case BfTypeCode_Int16:
  8060. case BfTypeCode_UInt16:
  8061. case BfTypeCode_Int32:
  8062. case BfTypeCode_UInt32:
  8063. case BfTypeCode_Int64:
  8064. case BfTypeCode_UInt64:
  8065. case BfTypeCode_IntPtr:
  8066. case BfTypeCode_UIntPtr:
  8067. case BfTypeCode_IntUnknown:
  8068. case BfTypeCode_UIntUnknown:
  8069. case BfTypeCode_Char8:
  8070. case BfTypeCode_Char16:
  8071. case BfTypeCode_Char32:
  8072. case BfTypeCode_Single:
  8073. case BfTypeCode_Double:
  8074. {
  8075. auto constVal = mBfIRBuilder->CreateConst(constant, constHolder);
  8076. auto typedValue = BfTypedValue(constVal, GetPrimitiveType(constant->mTypeCode));
  8077. if (typedValue.mType == wantType)
  8078. return typedValue;
  8079. if (wantType->IsTypedPrimitive())
  8080. {
  8081. if (typedValue.mType == wantType->GetUnderlyingType())
  8082. {
  8083. typedValue.mType = wantType;
  8084. return typedValue;
  8085. }
  8086. }
  8087. auto castedTypedValue = Cast(NULL, typedValue, wantType, (BfCastFlags)(BfCastFlags_SilentFail | BfCastFlags_Explicit));
  8088. BF_ASSERT(castedTypedValue);
  8089. return castedTypedValue;
  8090. }
  8091. break;
  8092. default: break;
  8093. }
  8094. }
  8095. BfIRValue irValue = ConstantToCurrent(constant, constHolder, wantType);
  8096. BF_ASSERT(irValue);
  8097. if (!irValue)
  8098. return BfTypedValue();
  8099. return BfTypedValue(irValue, wantType, false);
  8100. }
  8101. BfIRValue BfModule::ConstantToCurrent(BfConstant* constant, BfIRConstHolder* constHolder, BfType* wantType)
  8102. {
  8103. if (constant->mTypeCode == BfTypeCode_NullPtr)
  8104. {
  8105. return GetDefaultValue(wantType);
  8106. }
  8107. bool isString = false;
  8108. isString = (wantType->IsObject()) && (wantType->ToTypeInstance()->mTypeDef == mCompiler->mStringTypeDef);
  8109. if (((wantType->IsPointer()) || (isString)) && (mBfIRBuilder->IsInt(constant->mTypeCode)))
  8110. {
  8111. const StringImpl& str = mContext->mStringObjectIdMap[constant->mInt32].mString;
  8112. BfIRValue stringObjConst = GetStringObjectValue(str);
  8113. if (wantType->IsObject())
  8114. return stringObjConst;
  8115. return GetStringCharPtr(stringObjConst);
  8116. }
  8117. if (constant->mConstType == BfConstType_Array)
  8118. {
  8119. auto elementType = wantType->GetUnderlyingType();
  8120. auto constArray = (BfConstantArray*)constant;
  8121. SizedArray<BfIRValue, 8> newVals;
  8122. for (auto val : constArray->mValues)
  8123. {
  8124. newVals.push_back(ConstantToCurrent(constHolder->GetConstant(val), constHolder, elementType));
  8125. }
  8126. return mBfIRBuilder->CreateConstArray(mBfIRBuilder->MapType(wantType), newVals);
  8127. }
  8128. return mBfIRBuilder->CreateConst(constant, constHolder);
  8129. }
  8130. void BfModule::ValidateCustomAttributes(BfCustomAttributes* customAttributes, BfAttributeTargets attrTarget)
  8131. {
  8132. if (attrTarget == BfAttributeTargets_SkipValidate)
  8133. return;
  8134. for (auto& customAttribute : customAttributes->mAttributes)
  8135. {
  8136. if (!customAttribute.mAwaitingValidation)
  8137. continue;
  8138. if ((customAttribute.mType->mAttributeData->mAttributeTargets & attrTarget) == 0)
  8139. {
  8140. Fail(StrFormat("Attribute '%s' is not valid on this declaration type. It is only valid on %s.",
  8141. customAttribute.GetRefNode()->ToString().c_str(), GetAttributesTargetListString(customAttribute.mType->mAttributeData->mAttributeTargets).c_str()), customAttribute.mRef->mAttributeTypeRef); // CS0592
  8142. }
  8143. customAttribute.mAwaitingValidation = false;
  8144. }
  8145. }
  8146. void BfModule::GetCustomAttributes(BfCustomAttributes* customAttributes, BfAttributeDirective* attributesDirective, BfAttributeTargets attrTarget, bool allowNonConstArgs, BfCaptureInfo* captureInfo)
  8147. {
  8148. if ((attributesDirective != NULL) && (mCompiler->mResolvePassData != NULL) &&
  8149. (attributesDirective->IsFromParser(mCompiler->mResolvePassData->mParser)) && (mCompiler->mResolvePassData->mSourceClassifier != NULL))
  8150. {
  8151. mCompiler->mResolvePassData->mSourceClassifier->VisitChild(attributesDirective);
  8152. }
  8153. SetAndRestoreValue<bool> prevIsCapturingMethodMatchInfo;
  8154. if (mCompiler->IsAutocomplete())
  8155. prevIsCapturingMethodMatchInfo.Init(mCompiler->mResolvePassData->mAutoComplete->mIsCapturingMethodMatchInfo, false);
  8156. BfTypeInstance* baseAttrTypeInst = mContext->mUnreifiedModule->ResolveTypeDef(mCompiler->mAttributeTypeDef)->ToTypeInstance();
  8157. BfAttributeTargets targetOverride = (BfAttributeTargets)0;
  8158. BfAutoComplete* autoComplete = NULL;
  8159. if (mCompiler->mResolvePassData != NULL)
  8160. autoComplete = mCompiler->mResolvePassData->mAutoComplete;
  8161. for (; attributesDirective != NULL; attributesDirective = attributesDirective->mNextAttribute)
  8162. {
  8163. if (auto tokenNode = BfNodeDynCast<BfTokenNode>(attributesDirective->mAttributeTargetSpecifier))
  8164. {
  8165. if (captureInfo == NULL)
  8166. {
  8167. Fail("Capture specifiers can only be used in lambda allocations", attributesDirective);
  8168. continue;
  8169. }
  8170. BfCaptureInfo::Entry captureEntry;
  8171. captureEntry.mCaptureType = (tokenNode->mToken == BfToken_Ampersand) ? BfCaptureType_Reference : BfCaptureType_Copy;
  8172. if (!attributesDirective->mArguments.IsEmpty())
  8173. {
  8174. captureEntry.mNameNode = BfNodeDynCast<BfIdentifierNode>(attributesDirective->mArguments[0]);
  8175. if ((captureEntry.mNameNode != NULL) && (autoComplete != NULL))
  8176. autoComplete->CheckIdentifier(captureEntry.mNameNode);
  8177. }
  8178. captureInfo->mCaptures.Add(captureEntry);
  8179. continue;
  8180. }
  8181. BfAutoParentNodeEntry autoParentNodeEntry(this, attributesDirective);
  8182. BfCustomAttribute customAttribute;
  8183. customAttribute.mAwaitingValidation = true;
  8184. customAttribute.mRef = attributesDirective;
  8185. if (attributesDirective->mAttrOpenToken != NULL)
  8186. targetOverride = (BfAttributeTargets)0;
  8187. if (attributesDirective->mAttributeTypeRef == NULL)
  8188. {
  8189. AssertErrorState();
  8190. continue;
  8191. }
  8192. String attrName = attributesDirective->mAttributeTypeRef->ToString();
  8193. BfType* attrType = NULL;
  8194. BfAtomComposite nameComposite;
  8195. BfTypeDef* attrTypeDef = NULL;
  8196. if (mSystem->ParseAtomComposite(attrName + "Attribute", nameComposite))
  8197. {
  8198. BfTypeLookupError error;
  8199. error.mRefNode = attributesDirective->mAttributeTypeRef;
  8200. attrTypeDef = FindTypeDefRaw(nameComposite, 0, mCurTypeInstance, GetActiveTypeDef(NULL, true), &error);
  8201. }
  8202. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL))
  8203. {
  8204. mCompiler->mResolvePassData->mAutoComplete->CheckAttributeTypeRef(attributesDirective->mAttributeTypeRef);
  8205. if (attrTypeDef != NULL)
  8206. mCompiler->mResolvePassData->HandleTypeReference(attributesDirective->mAttributeTypeRef, attrTypeDef);
  8207. }
  8208. if (attrTypeDef == NULL)
  8209. {
  8210. TypeRefNotFound(attributesDirective->mAttributeTypeRef, "Attribute");
  8211. continue;
  8212. }
  8213. bool isBypassedAttr = false;
  8214. if (attrTypeDef != NULL)
  8215. {
  8216. attrType = mContext->mUnreifiedModule->ResolveTypeDef(attrTypeDef, BfPopulateType_Identity);
  8217. // 'Object' has some dependencies on some attributes, but those attributes are classes so we have a circular dependency issue
  8218. // We solve it by having a 'bypass' for known attributes that Object depends on
  8219. if ((attributesDirective->mArguments.empty()) && (autoComplete == NULL) && (attrType != NULL) && (attrType->IsTypeInstance()))
  8220. {
  8221. if (attrTypeDef == mCompiler->mCReprAttributeTypeDef)
  8222. {
  8223. BfTypeInstance* attrTypeInst = attrType->ToTypeInstance();
  8224. for (auto methodDef : attrTypeDef->mMethods)
  8225. {
  8226. if ((methodDef->mMethodType == BfMethodType_Ctor) && (methodDef->mProtection == BfProtection_Public))
  8227. {
  8228. customAttribute.mType = attrType->ToTypeInstance();
  8229. customAttribute.mCtor = methodDef;
  8230. isBypassedAttr = true;
  8231. break;
  8232. }
  8233. }
  8234. }
  8235. }
  8236. if (isBypassedAttr)
  8237. {
  8238. customAttribute.mAwaitingValidation = false;
  8239. customAttributes->mAttributes.push_back(customAttribute);
  8240. continue;
  8241. }
  8242. if (mContext->mCurTypeState != NULL)
  8243. {
  8244. SetAndRestoreValue<BfTypeReference*> prevTypeRef(mContext->mCurTypeState->mCurAttributeTypeRef, attributesDirective->mAttributeTypeRef);
  8245. mContext->mUnreifiedModule->ResolveTypeResult(attributesDirective->mAttributeTypeRef, attrType, BfPopulateType_BaseType, (BfResolveTypeRefFlags)0);
  8246. }
  8247. else
  8248. {
  8249. mContext->mUnreifiedModule->ResolveTypeResult(attributesDirective->mAttributeTypeRef, attrType, BfPopulateType_BaseType, (BfResolveTypeRefFlags)0);
  8250. }
  8251. }
  8252. // Don't allow this
  8253. /*else if (mContext->mCurTypeState != NULL)
  8254. {
  8255. SetAndRestoreValue<BfTypeReference*> prevTypeRef(mContext->mCurTypeState->mCurAttributeTypeRef, attributesDirective->mAttributeTypeRef);
  8256. attrType = mContext->mUnreifiedModule->ResolveTypeRef(attributesDirective->mAttributeTypeRef, BfPopulateType_DataAndMethods);
  8257. }
  8258. else
  8259. {
  8260. attrType = mContext->mUnreifiedModule->ResolveTypeRef(attributesDirective->mAttributeTypeRef);
  8261. }*/
  8262. BfTypeInstance* attrTypeInst = NULL;
  8263. if (attrType == NULL)
  8264. continue;
  8265. mContext->mUnreifiedModule->PopulateType(attrType, BfPopulateType_DataAndMethods);
  8266. attrTypeInst = attrType->ToTypeInstance();
  8267. if ((attrTypeInst == NULL) || (!TypeIsSubTypeOf(attrTypeInst, baseAttrTypeInst)) || (attrTypeInst->mAttributeData == NULL))
  8268. {
  8269. Fail(StrFormat("'%s' is not an attribute class", TypeToString(attrType).c_str()), attributesDirective->mAttributeTypeRef); //CS0616
  8270. continue;
  8271. }
  8272. if (mCurTypeInstance != NULL)
  8273. AddDependency(attrTypeInst, mCurTypeInstance, BfDependencyMap::DependencyFlag_CustomAttribute);
  8274. customAttribute.mType = attrTypeInst;
  8275. BfConstResolver constResolver(this);
  8276. if (allowNonConstArgs)
  8277. constResolver.mBfEvalExprFlags = (BfEvalExprFlags)(constResolver.mBfEvalExprFlags | BfEvalExprFlags_AllowNonConst);
  8278. bool inPropSet = false;
  8279. SizedArray<BfResolvedArg, 2> argValues;
  8280. for (BfExpression* arg : attributesDirective->mArguments)
  8281. {
  8282. if (arg == NULL)
  8283. {
  8284. continue;
  8285. }
  8286. if (autoComplete != NULL)
  8287. autoComplete->mShowAttributeProperties = attrTypeInst;
  8288. if (auto assignExpr = BfNodeDynCast<BfAssignmentExpression>(arg))
  8289. {
  8290. inPropSet = true;
  8291. if (autoComplete != NULL)
  8292. autoComplete->CheckNode(assignExpr->mLeft);
  8293. String findName = assignExpr->mLeft->ToString();
  8294. BfPropertyDef* bestProp = NULL;
  8295. BfTypeInstance* bestPropTypeInst = NULL;
  8296. BfFieldDef* bestField = NULL;
  8297. BfTypeInstance* bestFieldTypeInst = NULL;
  8298. auto checkTypeInst = attrTypeInst;
  8299. while (checkTypeInst != NULL)
  8300. {
  8301. mContext->mUnreifiedModule->PopulateType(checkTypeInst, BfPopulateType_Data);
  8302. for (auto prop : checkTypeInst->mTypeDef->mProperties)
  8303. {
  8304. if (prop->mName == findName)
  8305. {
  8306. if ((bestProp == NULL) || (bestProp->mProtection != BfProtection_Public))
  8307. {
  8308. bestProp = prop;
  8309. bestPropTypeInst = checkTypeInst;
  8310. }
  8311. }
  8312. }
  8313. for (auto field : checkTypeInst->mTypeDef->mFields)
  8314. {
  8315. if (field->mName == findName)
  8316. {
  8317. if ((bestField == NULL) || (bestField->mProtection != BfProtection_Public))
  8318. {
  8319. bestField = field;
  8320. bestFieldTypeInst = checkTypeInst;
  8321. }
  8322. }
  8323. }
  8324. if ((bestProp != NULL) || (bestField != NULL))
  8325. break;
  8326. checkTypeInst = checkTypeInst->mBaseType;
  8327. }
  8328. bool handledExpr = false;
  8329. if (bestField != NULL)
  8330. {
  8331. handledExpr = true;
  8332. if (mCompiler->mResolvePassData != NULL)
  8333. {
  8334. mCompiler->mResolvePassData->HandleFieldReference(assignExpr->mLeft, attrTypeDef, bestField);
  8335. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(assignExpr->mLeft)))
  8336. {
  8337. autoComplete->mDefField = bestField;
  8338. autoComplete->mDefType = attrTypeDef;
  8339. }
  8340. }
  8341. if (bestField->mProtection != BfProtection_Public)
  8342. Fail(StrFormat("'%s.%s' is inaccessible due to its protection level", TypeToString(bestFieldTypeInst).c_str(), findName.c_str()), assignExpr->mLeft); // CS0122
  8343. AddDependency(bestFieldTypeInst, mCurTypeInstance, BfDependencyMap::DependencyFlag_CustomAttribute);
  8344. BfCustomAttributeSetField setField;
  8345. setField.mFieldRef = BfFieldRef(bestFieldTypeInst, bestField);
  8346. auto& fieldTypeInst = checkTypeInst->mFieldInstances[bestField->mIdx];
  8347. if (assignExpr->mRight != NULL)
  8348. {
  8349. BfTypedValue result = constResolver.Resolve(assignExpr->mRight, fieldTypeInst.mResolvedType);
  8350. if (result)
  8351. {
  8352. CurrentAddToConstHolder(result.mValue);
  8353. setField.mParam = result;
  8354. customAttribute.mSetField.push_back(setField);
  8355. }
  8356. }
  8357. }
  8358. else if (bestProp == NULL)
  8359. {
  8360. Fail(StrFormat("'%s' does not contain a field or property named '%s'", TypeToString(attrTypeInst).c_str(), findName.c_str()), assignExpr->mLeft);
  8361. }
  8362. else
  8363. {
  8364. BfMethodDef* setMethod = NULL;
  8365. for (auto methodDef : bestProp->mMethods)
  8366. {
  8367. if (methodDef->mMethodType == BfMethodType_PropertySetter)
  8368. {
  8369. setMethod = methodDef;
  8370. break;
  8371. }
  8372. }
  8373. if (setMethod == NULL)
  8374. {
  8375. Fail("Property has no setter", assignExpr->mLeft);
  8376. }
  8377. else
  8378. {
  8379. if (mCompiler->mResolvePassData != NULL)
  8380. {
  8381. mCompiler->mResolvePassData->HandlePropertyReference(assignExpr->mLeft, attrTypeDef, bestProp);
  8382. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(assignExpr->mLeft)))
  8383. {
  8384. autoComplete->mDefProp = bestProp;
  8385. autoComplete->mDefType = attrTypeDef;
  8386. }
  8387. }
  8388. handledExpr = true;
  8389. if (bestProp->mProtection != BfProtection_Public)
  8390. Fail(StrFormat("'%s.%s' is inaccessible due to its protection level", TypeToString(bestPropTypeInst).c_str(), findName.c_str()), assignExpr->mLeft); // CS0122
  8391. BfResolvedArg resolvedArg;
  8392. AddDependency(bestPropTypeInst, mCurTypeInstance, BfDependencyMap::DependencyFlag_CustomAttribute);
  8393. BfCustomAttributeSetProperty setProperty;
  8394. setProperty.mPropertyRef = BfPropertyRef(bestPropTypeInst, bestProp);
  8395. // We don't actually need the mFunc, so get the ModuleMethodInstance from the native module
  8396. auto methodInstance = bestPropTypeInst->mModule->GetMethodInstance(bestPropTypeInst, setMethod, BfTypeVector());
  8397. if (methodInstance.mMethodInstance != NULL)
  8398. {
  8399. auto propType = methodInstance.mMethodInstance->GetParamType(0);
  8400. if (assignExpr->mRight != NULL)
  8401. {
  8402. BfTypedValue result = constResolver.Resolve(assignExpr->mRight, propType);
  8403. if (result)
  8404. {
  8405. BF_ASSERT(result.mType == propType);
  8406. CurrentAddToConstHolder(result.mValue);
  8407. setProperty.mParam = result;
  8408. customAttribute.mSetProperties.push_back(setProperty);
  8409. }
  8410. }
  8411. }
  8412. }
  8413. }
  8414. if ((!handledExpr) && (assignExpr->mRight != NULL))
  8415. constResolver.Resolve(assignExpr->mRight);
  8416. }
  8417. else
  8418. {
  8419. if (inPropSet)
  8420. {
  8421. Fail("Named attribute argument expected", arg); // CS1016
  8422. }
  8423. BfDeferEvalChecker deferEvalChecker;
  8424. arg->Accept(&deferEvalChecker);
  8425. bool deferParamEval = deferEvalChecker.mNeedsDeferEval;
  8426. BfResolvedArg resolvedArg;
  8427. resolvedArg.mExpression = arg;
  8428. if (deferParamEval)
  8429. {
  8430. resolvedArg.mArgFlags = BfArgFlag_DeferredEval;
  8431. }
  8432. else
  8433. resolvedArg.mTypedValue = constResolver.Resolve(arg);
  8434. if (!inPropSet)
  8435. argValues.push_back(resolvedArg);
  8436. }
  8437. if (autoComplete != NULL)
  8438. autoComplete->mShowAttributeProperties = NULL;
  8439. }
  8440. auto wasCapturingMethodInfo = false;
  8441. if (autoComplete != NULL)
  8442. {
  8443. wasCapturingMethodInfo = autoComplete->mIsCapturingMethodMatchInfo;
  8444. if (attributesDirective->mCtorOpenParen != NULL)
  8445. autoComplete->CheckInvocation(attributesDirective, attributesDirective->mCtorOpenParen, attributesDirective->mCtorCloseParen, attributesDirective->mCommas);
  8446. }
  8447. BfMethodMatcher methodMatcher(attributesDirective, this, "", argValues, NULL);
  8448. attrTypeDef = attrTypeInst->mTypeDef;
  8449. bool success = true;
  8450. bool isFailurePass = false;
  8451. for (int pass = 0; pass < 2; pass++)
  8452. {
  8453. bool isFailurePass = pass == 1;
  8454. for (auto checkMethod : attrTypeDef->mMethods)
  8455. {
  8456. if ((isFailurePass) && (checkMethod->mMethodDeclaration == NULL))
  8457. continue; // Don't match private default ctor if there's a user-defined one
  8458. if ((checkMethod->mIsStatic) || (checkMethod->mMethodType != BfMethodType_Ctor))
  8459. continue;
  8460. if ((!isFailurePass) && (!CheckProtection(checkMethod->mProtection, false, false)))
  8461. continue;
  8462. methodMatcher.CheckMethod(attrTypeInst, checkMethod, isFailurePass);
  8463. }
  8464. if ((methodMatcher.mBestMethodDef != NULL) || (methodMatcher.mBackupMethodDef != NULL))
  8465. break;
  8466. }
  8467. if (autoComplete != NULL)
  8468. {
  8469. if ((wasCapturingMethodInfo) && (!autoComplete->mIsCapturingMethodMatchInfo))
  8470. {
  8471. autoComplete->mIsCapturingMethodMatchInfo = true;
  8472. BF_ASSERT(autoComplete->mMethodMatchInfo != NULL);
  8473. }
  8474. else
  8475. autoComplete->mIsCapturingMethodMatchInfo = false;
  8476. }
  8477. if (methodMatcher.mBestMethodDef == NULL)
  8478. methodMatcher.mBestMethodDef = methodMatcher.mBackupMethodDef;
  8479. BF_ASSERT(methodMatcher.mBestMethodDef != NULL);
  8480. customAttribute.mCtor = methodMatcher.mBestMethodDef;
  8481. if (methodMatcher.mBestMethodTypeInstance == mCurTypeInstance)
  8482. {
  8483. Fail("Custom attribute circular reference", attributesDirective);
  8484. }
  8485. if (mCurTypeInstance != NULL)
  8486. AddDependency(methodMatcher.mBestMethodTypeInstance, mCurTypeInstance, BfDependencyMap::DependencyFlag_CustomAttribute);
  8487. if (!constResolver.PrepareMethodArguments(attributesDirective->mAttributeTypeRef, &methodMatcher, customAttribute.mCtorArgs))
  8488. success = false;
  8489. for (auto& arg : argValues)
  8490. {
  8491. if ((arg.mArgFlags & BfArgFlag_DeferredEval) != 0)
  8492. {
  8493. if (auto expr = BfNodeDynCast<BfExpression>(arg.mExpression))
  8494. constResolver.Resolve(expr);
  8495. }
  8496. }
  8497. // Move all those to the constHolder
  8498. for (auto& ctorArg : customAttribute.mCtorArgs)
  8499. {
  8500. if (ctorArg.IsConst())
  8501. CurrentAddToConstHolder(ctorArg);
  8502. }
  8503. if (attributesDirective->mAttributeTargetSpecifier != NULL)
  8504. {
  8505. targetOverride = BfAttributeTargets_ReturnValue;
  8506. if (attrTarget != BfAttributeTargets_Method)
  8507. {
  8508. 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.",
  8509. GetAttributesTargetListString(targetOverride).c_str(), GetAttributesTargetListString(attrTarget).c_str()), attributesDirective->mAttributeTargetSpecifier); // CS0657
  8510. }
  8511. success = false;
  8512. }
  8513. if ((success) && (targetOverride != (BfAttributeTargets)0))
  8514. {
  8515. if ((targetOverride == BfAttributeTargets_ReturnValue) && (attrTarget == BfAttributeTargets_Method))
  8516. {
  8517. auto methodInfoEx = mCurMethodInstance->GetMethodInfoEx();
  8518. if (methodInfoEx->mMethodCustomAttributes == NULL)
  8519. methodInfoEx->mMethodCustomAttributes = new BfMethodCustomAttributes();
  8520. if (success)
  8521. {
  8522. if (methodInfoEx->mMethodCustomAttributes->mReturnCustomAttributes == NULL)
  8523. methodInfoEx->mMethodCustomAttributes->mReturnCustomAttributes = new BfCustomAttributes();
  8524. methodInfoEx->mMethodCustomAttributes->mReturnCustomAttributes->mAttributes.push_back(customAttribute);
  8525. }
  8526. }
  8527. else
  8528. {
  8529. // Failed - ignore
  8530. success = false;
  8531. }
  8532. }
  8533. if (success)
  8534. {
  8535. if (!attrTypeInst->mAttributeData->mAllowMultiple)
  8536. {
  8537. for (auto& prevCustomAttribute : customAttributes->mAttributes)
  8538. {
  8539. if (prevCustomAttribute.mType == attrTypeInst)
  8540. {
  8541. Fail(StrFormat("Duplicate '%s' attribute", attributesDirective->mAttributeTypeRef->ToString().c_str()), attributesDirective->mAttributeTypeRef); // CS0579
  8542. }
  8543. }
  8544. }
  8545. }
  8546. if (success)
  8547. {
  8548. customAttributes->mAttributes.push_back(customAttribute);
  8549. }
  8550. }
  8551. ValidateCustomAttributes(customAttributes, attrTarget);
  8552. }
  8553. BfCustomAttributes* BfModule::GetCustomAttributes(BfAttributeDirective* attributesDirective, BfAttributeTargets attrType, bool allowNonConstArgs, BfCaptureInfo* captureInfo)
  8554. {
  8555. BfCustomAttributes* customAttributes = new BfCustomAttributes();
  8556. GetCustomAttributes(customAttributes, attributesDirective, attrType, allowNonConstArgs, captureInfo);
  8557. return customAttributes;
  8558. }
  8559. void BfModule::ProcessTypeInstCustomAttributes(bool& isPacked, bool& isUnion, bool& isCRepr, bool& isOrdered)
  8560. {
  8561. if (mCurTypeInstance->mCustomAttributes != NULL)
  8562. {
  8563. for (auto& customAttribute : mCurTypeInstance->mCustomAttributes->mAttributes)
  8564. {
  8565. String typeName = TypeToString(customAttribute.mType);
  8566. if (typeName == "System.PackedAttribute")
  8567. {
  8568. isPacked = true;
  8569. }
  8570. else if (typeName == "System.UnionAttribute")
  8571. {
  8572. isUnion = true;
  8573. }
  8574. else if (typeName == "System.CReprAttribute")
  8575. {
  8576. isCRepr = true;
  8577. isOrdered = true;
  8578. }
  8579. else if (typeName == "System.OrderedAttribute")
  8580. {
  8581. isOrdered = true;
  8582. }
  8583. else if (typeName == "System.AlwaysIncludeAttribute")
  8584. {
  8585. for (auto setProp : customAttribute.mSetProperties)
  8586. {
  8587. BfPropertyDef* propertyDef = setProp.mPropertyRef;
  8588. if (propertyDef->mName == "AssumeInstantiated")
  8589. {
  8590. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  8591. if ((constant != NULL) && (constant->mBool))
  8592. mCurTypeInstance->mHasBeenInstantiated = true;
  8593. }
  8594. }
  8595. }
  8596. }
  8597. }
  8598. }
  8599. // Checking to see if we're an attribute or not
  8600. void BfModule::ProcessCustomAttributeData()
  8601. {
  8602. bool isAttribute = false;
  8603. auto checkTypeInst = mCurTypeInstance->mBaseType;
  8604. while (checkTypeInst != NULL)
  8605. {
  8606. if (checkTypeInst->mTypeDef == mCompiler->mAttributeTypeDef)
  8607. isAttribute = true;
  8608. checkTypeInst = checkTypeInst->mBaseType;
  8609. }
  8610. if (!isAttribute)
  8611. return;
  8612. auto attributeData = new BfAttributeData();
  8613. bool hasCustomAttribute = false;
  8614. if (mCurTypeInstance->mCustomAttributes != NULL)
  8615. {
  8616. for (auto& customAttribute : mCurTypeInstance->mCustomAttributes->mAttributes)
  8617. {
  8618. if (customAttribute.mType->mTypeDef == mCompiler->mAttributeUsageAttributeTypeDef)
  8619. {
  8620. if (customAttribute.mCtorArgs.size() > 0)
  8621. {
  8622. auto constant = mCurTypeInstance->mConstHolder->GetConstant(customAttribute.mCtorArgs[0]);
  8623. if ((constant != NULL) && (mBfIRBuilder->IsInt(constant->mTypeCode)))
  8624. attributeData->mAttributeTargets = (BfAttributeTargets)constant->mInt32;
  8625. }
  8626. for (auto& setProp : customAttribute.mSetProperties)
  8627. {
  8628. BfPropertyDef* propDef = setProp.mPropertyRef;
  8629. if (propDef->mName == "AllowMultiple")
  8630. {
  8631. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  8632. if (constant != NULL)
  8633. attributeData->mAllowMultiple = constant->mBool;
  8634. }
  8635. else if (propDef->mName == "Inherited")
  8636. {
  8637. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  8638. if (constant != NULL)
  8639. attributeData->mInherited = constant->mBool;
  8640. }
  8641. else if (propDef->mName == "ValidOn")
  8642. {
  8643. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  8644. if (constant != NULL)
  8645. attributeData->mAttributeTargets = (BfAttributeTargets)constant->mInt32;
  8646. }
  8647. }
  8648. hasCustomAttribute = true;
  8649. }
  8650. }
  8651. }
  8652. if ((!hasCustomAttribute) && (mCurTypeInstance->mBaseType->mAttributeData != NULL))
  8653. {
  8654. attributeData->mAttributeTargets = mCurTypeInstance->mBaseType->mAttributeData->mAttributeTargets;
  8655. attributeData->mInherited = mCurTypeInstance->mBaseType->mAttributeData->mInherited;
  8656. attributeData->mAllowMultiple = mCurTypeInstance->mBaseType->mAttributeData->mAllowMultiple;
  8657. }
  8658. mCurTypeInstance->mAttributeData = attributeData;
  8659. }
  8660. bool BfModule::TryGetConstString(BfIRConstHolder* constHolder, BfIRValue irValue, StringImpl& str)
  8661. {
  8662. auto constant = constHolder->GetConstant(irValue);
  8663. if (constant == NULL)
  8664. return false;
  8665. if (!BfIRConstHolder::IsInt(constant->mTypeCode))
  8666. return false;
  8667. int stringId = constant->mInt32;
  8668. BfStringPoolEntry* entry = NULL;
  8669. if (mContext->mStringObjectIdMap.TryGetValue(stringId, &entry))
  8670. {
  8671. str = entry->mString;
  8672. }
  8673. else
  8674. {
  8675. BF_DBG_FATAL("Failed to find string by id");
  8676. }
  8677. return true;
  8678. }
  8679. BfVariant BfModule::TypedValueToVariant(BfAstNode* refNode, const BfTypedValue& value, bool allowUndef)
  8680. {
  8681. BfVariant variant;
  8682. variant.mTypeCode = BfTypeCode_None;
  8683. BfType* primType = NULL;
  8684. if (value.mType->IsPrimitiveType())
  8685. primType = (BfPrimitiveType*)value.mType;
  8686. else if (value.mType->IsTypedPrimitive())
  8687. primType = value.mType->GetUnderlyingType();
  8688. if (primType)
  8689. {
  8690. auto constant = mBfIRBuilder->GetConstant(value.mValue);
  8691. if (constant != NULL)
  8692. {
  8693. if ((allowUndef) && (constant->mConstType == BfConstType_Undef))
  8694. {
  8695. variant.mTypeCode = BfTypeCode_Let;
  8696. return variant;
  8697. }
  8698. switch (constant->mTypeCode)
  8699. {
  8700. case BfTypeCode_Int8:
  8701. case BfTypeCode_UInt8:
  8702. case BfTypeCode_Int16:
  8703. case BfTypeCode_UInt16:
  8704. case BfTypeCode_Int32:
  8705. case BfTypeCode_UInt32:
  8706. case BfTypeCode_Int64:
  8707. case BfTypeCode_UInt64:
  8708. case BfTypeCode_IntPtr:
  8709. case BfTypeCode_UIntPtr:
  8710. case BfTypeCode_IntUnknown:
  8711. case BfTypeCode_UIntUnknown:
  8712. case BfTypeCode_Single:
  8713. case BfTypeCode_Double:
  8714. case BfTypeCode_Char8:
  8715. case BfTypeCode_Char16:
  8716. case BfTypeCode_Char32:
  8717. variant.mTypeCode = constant->mTypeCode;
  8718. variant.mInt64 = constant->mInt64;
  8719. break;
  8720. default:
  8721. if (refNode != NULL)
  8722. Fail("Invalid const expression type", refNode);
  8723. break;
  8724. }
  8725. }
  8726. }
  8727. return variant;
  8728. }
  8729. BfTypedValue BfModule::RemoveRef(BfTypedValue typedValue)
  8730. {
  8731. if ((typedValue.mType != NULL) && (typedValue.mType->IsRef()))
  8732. {
  8733. auto elementType = typedValue.mType->GetUnderlyingType();
  8734. if (typedValue.IsAddr())
  8735. {
  8736. if (elementType->IsValuelessType())
  8737. {
  8738. BF_ASSERT(!typedValue.mValue);
  8739. typedValue = BfTypedValue(typedValue.mValue, elementType, true);
  8740. }
  8741. else
  8742. typedValue = BfTypedValue(mBfIRBuilder->CreateLoad(typedValue.mValue), elementType, true);
  8743. }
  8744. else
  8745. typedValue = BfTypedValue(typedValue.mValue, elementType, true);
  8746. if (typedValue.mType->IsValuelessType())
  8747. {
  8748. BF_ASSERT(typedValue.mValue.IsFake());
  8749. }
  8750. }
  8751. return typedValue;
  8752. }
  8753. BfTypedValue BfModule::LoadValue(BfTypedValue typedValue, BfAstNode* refNode, bool isVolatile)
  8754. {
  8755. if (!typedValue.IsAddr())
  8756. return typedValue;
  8757. if (typedValue.mType->IsValuelessType())
  8758. return BfTypedValue(mBfIRBuilder->GetFakeVal(), typedValue.mType, false);
  8759. BfIRValue loadedVal = typedValue.mValue;
  8760. if (loadedVal)
  8761. {
  8762. if (typedValue.mType->IsVar())
  8763. {
  8764. return BfTypedValue(loadedVal, typedValue.mType, false);
  8765. }
  8766. /*if (isVolatile)
  8767. mBfIRBuilder->CreateFence(BfIRFenceType_AcquireRelease);*/
  8768. PopulateType(typedValue.mType, BfPopulateType_Data);
  8769. loadedVal = mBfIRBuilder->CreateAlignedLoad(loadedVal, std::max(1, (int)typedValue.mType->mAlign), isVolatile);
  8770. }
  8771. return BfTypedValue(loadedVal, typedValue.mType, false);
  8772. }
  8773. BfTypedValue BfModule::LoadOrAggregateValue(BfTypedValue typedValue)
  8774. {
  8775. if (typedValue.IsSplat())
  8776. return AggregateSplat(typedValue);
  8777. if (typedValue.IsAddr())
  8778. return LoadValue(typedValue);
  8779. return typedValue;
  8780. }
  8781. BfTypedValue BfModule::AggregateSplat(BfTypedValue typedValue, BfIRValue* valueArrPtr)
  8782. {
  8783. if (!typedValue.IsSplat())
  8784. return typedValue;
  8785. if (typedValue.mType->IsValuelessType())
  8786. return typedValue;
  8787. int elementIdx = 0;
  8788. auto _ExtractValue = [&](BfType* checkType)
  8789. {
  8790. if (valueArrPtr != NULL)
  8791. return valueArrPtr[elementIdx++];
  8792. return ExtractSplatValue(typedValue, elementIdx++, checkType);
  8793. };
  8794. std::function<BfIRValue(BfType*)> checkTypeLambda = [&](BfType* checkType)
  8795. {
  8796. if (checkType->IsStruct())
  8797. {
  8798. BfIRValue curValue = mBfIRBuilder->CreateUndefValue(mBfIRBuilder->MapType(checkType, BfIRPopulateType_Full));
  8799. auto checkTypeInstance = checkType->ToTypeInstance();
  8800. if (checkTypeInstance->mBaseType != NULL)
  8801. {
  8802. mBfIRBuilder->PopulateType(checkTypeInstance->mBaseType, BfIRPopulateType_Full);
  8803. BfIRValue baseValue = checkTypeLambda(checkTypeInstance->mBaseType);
  8804. curValue = mBfIRBuilder->CreateInsertValue(curValue, baseValue, 0);
  8805. }
  8806. if (checkTypeInstance->mIsUnion)
  8807. {
  8808. auto unionInnerType = checkTypeInstance->GetUnionInnerType();
  8809. if (!unionInnerType->IsValuelessType())
  8810. {
  8811. BfIRValue fieldValue = checkTypeLambda(unionInnerType);
  8812. curValue = mBfIRBuilder->CreateInsertValue(curValue, fieldValue, 1);
  8813. }
  8814. if (checkTypeInstance->IsEnum())
  8815. {
  8816. auto dscrType = checkTypeInstance->GetDiscriminatorType();
  8817. BfIRValue fieldValue = checkTypeLambda(dscrType);
  8818. curValue = mBfIRBuilder->CreateInsertValue(curValue, fieldValue, 2);
  8819. }
  8820. }
  8821. else
  8822. {
  8823. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  8824. {
  8825. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  8826. if (fieldInstance->mDataIdx >= 0)
  8827. {
  8828. BfIRValue fieldValue = checkTypeLambda(fieldInstance->GetResolvedType());
  8829. curValue = mBfIRBuilder->CreateInsertValue(curValue, fieldValue, fieldInstance->mDataIdx);
  8830. }
  8831. }
  8832. }
  8833. return curValue;
  8834. }
  8835. else if (checkType->IsMethodRef())
  8836. {
  8837. BfMethodRefType* methodRefType = (BfMethodRefType*)checkType;
  8838. BfIRValue curValue = mBfIRBuilder->CreateUndefValue(mBfIRBuilder->MapType(checkType, BfIRPopulateType_Full));
  8839. for (int dataIdx = 0; dataIdx < methodRefType->GetCaptureDataCount(); dataIdx++)
  8840. {
  8841. BfIRValue fieldValue;
  8842. auto checkType = methodRefType->GetCaptureType(dataIdx);
  8843. if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  8844. {
  8845. fieldValue = checkTypeLambda(checkType);
  8846. }
  8847. else
  8848. {
  8849. fieldValue = _ExtractValue(checkType);
  8850. }
  8851. curValue = mBfIRBuilder->CreateInsertValue(curValue, fieldValue, dataIdx);
  8852. }
  8853. return curValue;
  8854. }
  8855. else if (!checkType->IsValuelessType())
  8856. {
  8857. return _ExtractValue(checkType);
  8858. }
  8859. return BfIRValue();
  8860. };
  8861. BfIRValue value = checkTypeLambda(typedValue.mType);
  8862. return BfTypedValue(value, typedValue.mType, typedValue.IsThis() ? BfTypedValueKind_ThisValue : BfTypedValueKind_Value);
  8863. }
  8864. void BfModule::AggregateSplatIntoAddr(BfTypedValue typedValue, BfIRValue addrVal)
  8865. {
  8866. if (!typedValue.IsSplat())
  8867. return;
  8868. if (typedValue.mType->IsValuelessType())
  8869. return;
  8870. /*static int sCallIdx = 0;
  8871. if (!mCompiler->mIsResolveOnly)
  8872. sCallIdx++;
  8873. int callIdx = sCallIdx;*/
  8874. int elementIdx = 0;
  8875. std::function<void(BfType*, BfIRValue)> checkTypeLambda = [&](BfType* checkType, BfIRValue curAddrVal)
  8876. {
  8877. if (checkType->IsStruct())
  8878. {
  8879. auto checkTypeInstance = checkType->ToTypeInstance();
  8880. if (checkTypeInstance->mBaseType != NULL)
  8881. {
  8882. mBfIRBuilder->PopulateType(checkTypeInstance->mBaseType);
  8883. auto baseAddrVal = mBfIRBuilder->CreateInBoundsGEP(curAddrVal, 0, 0);
  8884. checkTypeLambda(checkTypeInstance->mBaseType, baseAddrVal);
  8885. }
  8886. if (checkTypeInstance->mIsUnion)
  8887. {
  8888. auto unionInnerType = checkTypeInstance->GetUnionInnerType();
  8889. if (!unionInnerType->IsValuelessType())
  8890. {
  8891. auto fieldAddrVal = mBfIRBuilder->CreateInBoundsGEP(curAddrVal, 0, 1);
  8892. checkTypeLambda(unionInnerType, fieldAddrVal);
  8893. }
  8894. if (checkTypeInstance->IsEnum())
  8895. {
  8896. auto dscrType = checkTypeInstance->GetDiscriminatorType();
  8897. auto fieldAddrVal = mBfIRBuilder->CreateInBoundsGEP(curAddrVal, 0, 2);
  8898. checkTypeLambda(dscrType, fieldAddrVal);
  8899. }
  8900. }
  8901. else
  8902. {
  8903. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  8904. {
  8905. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  8906. if (fieldInstance->mDataIdx >= 0)
  8907. {
  8908. auto fieldAddrVal = mBfIRBuilder->CreateInBoundsGEP(curAddrVal, 0, fieldInstance->mDataIdx);
  8909. checkTypeLambda(fieldInstance->mResolvedType, fieldAddrVal);
  8910. }
  8911. }
  8912. }
  8913. }
  8914. else if (checkType->IsMethodRef())
  8915. {
  8916. BfMethodRefType* methodRefType = (BfMethodRefType*)checkType;
  8917. for (int dataIdx = 0; dataIdx < methodRefType->GetCaptureDataCount(); dataIdx++)
  8918. {
  8919. auto dataType = methodRefType->GetCaptureType(dataIdx);
  8920. auto fieldAddrVal = mBfIRBuilder->CreateInBoundsGEP(curAddrVal, 0, dataIdx);
  8921. if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  8922. {
  8923. checkTypeLambda(methodRefType->GetCaptureType(dataIdx), fieldAddrVal);
  8924. }
  8925. else
  8926. {
  8927. // static int sItrCount = 0;
  8928. // sItrCount++;
  8929. // int curItr = sItrCount;
  8930. // if (curItr == 1)
  8931. // {
  8932. // NOP;
  8933. // }
  8934. auto val = ExtractSplatValue(typedValue, elementIdx++, dataType);
  8935. mBfIRBuilder->CreateStore(val, fieldAddrVal);
  8936. }
  8937. }
  8938. }
  8939. else if (!checkType->IsValuelessType())
  8940. {
  8941. auto val = ExtractSplatValue(typedValue, elementIdx++, checkType);
  8942. mBfIRBuilder->CreateStore(val, curAddrVal);
  8943. }
  8944. };
  8945. checkTypeLambda(typedValue.mType, addrVal);
  8946. }
  8947. BfTypedValue BfModule::MakeAddressable(BfTypedValue typedVal)
  8948. {
  8949. bool wasReadOnly = typedVal.IsReadOnly();
  8950. if ((typedVal.mType->IsValueType()) &&
  8951. (!typedVal.mType->IsValuelessType()))
  8952. {
  8953. wasReadOnly = true; // Any non-addr is implicitly read-only
  8954. //static int gCallIdx = 0;
  8955. if (typedVal.IsAddr())
  8956. return typedVal;
  8957. BfType* type = typedVal.mType;
  8958. PopulateType(type);
  8959. auto tempVar = CreateAlloca(type);
  8960. if (typedVal.IsSplat())
  8961. AggregateSplatIntoAddr(typedVal, tempVar);
  8962. else
  8963. mBfIRBuilder->CreateAlignedStore(typedVal.mValue, tempVar, type->mAlign);
  8964. return BfTypedValue(tempVar, type,
  8965. typedVal.IsThis() ?
  8966. (wasReadOnly ? BfTypedValueKind_ReadOnlyThisAddr : BfTypedValueKind_ThisAddr) :
  8967. (wasReadOnly ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Addr));
  8968. }
  8969. return LoadValue(typedVal);
  8970. }
  8971. BfTypedValue BfModule::RemoveReadOnly(BfTypedValue typedValue)
  8972. {
  8973. if (typedValue.mKind == BfTypedValueKind_ReadOnlyAddr)
  8974. typedValue.mKind = BfTypedValueKind_Addr;
  8975. return typedValue;
  8976. }
  8977. BfIRValue BfModule::ExtractSplatValue(BfTypedValue typedValue, int componentIdx, BfType* wantType, bool* isAddr)
  8978. {
  8979. BfIRValue val;
  8980. if (typedValue.mValue.IsArg())
  8981. {
  8982. val = mBfIRBuilder->GetArgument(typedValue.mValue.mId + componentIdx);
  8983. if (isAddr != NULL)
  8984. {
  8985. if (wantType != NULL)
  8986. *isAddr = wantType->IsComposite();
  8987. else
  8988. *isAddr = false;
  8989. }
  8990. else if (wantType->IsComposite())
  8991. val = mBfIRBuilder->CreateLoad(val);
  8992. }
  8993. if (!val)
  8994. {
  8995. auto checkMethodState = mCurMethodState;
  8996. while (checkMethodState != NULL)
  8997. {
  8998. for (int idx = 0; idx < (int)checkMethodState->mSplatDecompAddrs.size(); idx++)
  8999. {
  9000. auto decompAddr = checkMethodState->mSplatDecompAddrs[idx];
  9001. if (decompAddr == typedValue.mValue)
  9002. {
  9003. val = checkMethodState->mSplatDecompAddrs[idx + componentIdx];
  9004. if ((wantType->IsComposite()) && (typedValue.mType->IsMethodRef()))
  9005. {
  9006. // This is really backing for a POINTER to a composite inside a methodRef
  9007. val = mBfIRBuilder->CreateLoad(val);
  9008. }
  9009. if ((isAddr != NULL) && (typedValue.mKind != BfTypedValueKind_SplatHead_NeedsCasting))
  9010. {
  9011. *isAddr = true;
  9012. return val;
  9013. }
  9014. else
  9015. {
  9016. val = mBfIRBuilder->CreateLoad(val);
  9017. break;
  9018. }
  9019. }
  9020. }
  9021. if (val)
  9022. break;
  9023. checkMethodState = checkMethodState->mPrevMethodState;
  9024. }
  9025. }
  9026. if (val)
  9027. {
  9028. if (typedValue.mKind == BfTypedValueKind_SplatHead_NeedsCasting)
  9029. {
  9030. BF_ASSERT(wantType != NULL);
  9031. if (wantType != NULL)
  9032. return mBfIRBuilder->CreateBitCast(val, mBfIRBuilder->MapType(wantType));
  9033. }
  9034. return val;
  9035. }
  9036. BF_FATAL("Splat not found");
  9037. return BfIRValue();
  9038. }
  9039. BfTypedValue BfModule::ExtractValue(BfTypedValue typedValue, BfFieldInstance* fieldInstance, int fieldIdx)
  9040. {
  9041. int useFieldIdx = fieldIdx;
  9042. BfType* fieldType = NULL;
  9043. if (fieldInstance != NULL)
  9044. {
  9045. fieldType = fieldInstance->mResolvedType;
  9046. if (typedValue.mType->IsUnion())
  9047. {
  9048. if (fieldIdx == 1)
  9049. {
  9050. if (typedValue.IsSplat())
  9051. {
  9052. BfTypedValue innerVal = typedValue;
  9053. innerVal.mType = fieldType;
  9054. return innerVal;
  9055. }
  9056. }
  9057. }
  9058. }
  9059. else
  9060. {
  9061. if (typedValue.mType->IsPayloadEnum())
  9062. {
  9063. auto typeInst = typedValue.mType->ToTypeInstance();
  9064. if (fieldIdx == 1)
  9065. fieldType = typeInst->GetUnionInnerType();
  9066. else if (fieldIdx == 2)
  9067. {
  9068. fieldType = typeInst->GetDiscriminatorType(&useFieldIdx);
  9069. }
  9070. }
  9071. else if (typedValue.mType->IsUnion())
  9072. {
  9073. if (fieldIdx == 1)
  9074. {
  9075. fieldType = typedValue.mType->ToTypeInstance()->GetUnionInnerType();
  9076. if (typedValue.IsSplat())
  9077. {
  9078. BfTypedValue innerVal = typedValue;
  9079. innerVal.mType = fieldType;
  9080. return innerVal;
  9081. }
  9082. }
  9083. }
  9084. }
  9085. BF_ASSERT(typedValue.mType->IsStruct());
  9086. if (typedValue.IsSplat())
  9087. {
  9088. if (typedValue.mType->IsPayloadEnum())
  9089. {
  9090. if (fieldIdx == 1)
  9091. {
  9092. // Payload
  9093. auto typeInst = typedValue.mType->ToTypeInstance();
  9094. auto unionInnerType = typeInst->GetUnionInnerType();
  9095. bool isAddr = false;
  9096. BfIRValue irVal = ExtractSplatValue(typedValue, 0, unionInnerType, &isAddr);
  9097. return BfTypedValue(irVal, unionInnerType, BfTypedValueKind_SplatHead);
  9098. }
  9099. if (fieldIdx == 2)
  9100. {
  9101. // Discriminator
  9102. auto typeInst = typedValue.mType->ToTypeInstance();
  9103. auto unionInnerType = typeInst->GetUnionInnerType();
  9104. auto dscrType = typeInst->GetDiscriminatorType();
  9105. int argIdx = typedValue.mValue.mId;
  9106. int componentIdx = 0;
  9107. BfTypeUtils::SplatIterate([&](BfType* checkType) { componentIdx++; }, unionInnerType);
  9108. bool isAddr;
  9109. BfIRValue irVal = ExtractSplatValue(typedValue, componentIdx, dscrType, &isAddr);
  9110. return BfTypedValue(irVal, dscrType, isAddr);
  9111. }
  9112. }
  9113. int componentIdx = 0;
  9114. BfTypedValue retVal;
  9115. BfFieldInstance* wantFieldInstance = fieldInstance;
  9116. std::function<void(BfType*)> checkTypeLambda = [&](BfType* checkType)
  9117. {
  9118. if (checkType->IsStruct())
  9119. {
  9120. auto checkTypeInstance = checkType->ToTypeInstance();
  9121. if ((checkType->IsUnion()) || (checkType->IsEnum()))
  9122. {
  9123. //TODO: Why did we have this removed? It messed up an extraction from a nullable splattable
  9124. fieldType = checkTypeInstance->GetUnionInnerType();
  9125. checkTypeLambda(fieldType);
  9126. if (checkType->IsEnum())
  9127. {
  9128. // Past discriminator...
  9129. componentIdx++;
  9130. }
  9131. return;
  9132. }
  9133. if (checkTypeInstance->mBaseType != NULL)
  9134. checkTypeLambda(checkTypeInstance->mBaseType);
  9135. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  9136. {
  9137. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  9138. if (fieldInstance == wantFieldInstance)
  9139. {
  9140. bool isAddr = false;
  9141. BfIRValue val = ExtractSplatValue(typedValue, componentIdx, fieldInstance->mResolvedType, &isAddr);
  9142. retVal = BfTypedValue(val, fieldInstance->mResolvedType,
  9143. fieldInstance->mResolvedType->IsComposite() ? BfTypedValueKind_SplatHead :
  9144. isAddr ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Value);
  9145. if ((retVal.IsAddr()) && (!fieldInstance->mResolvedType->IsValueType()))
  9146. {
  9147. retVal = LoadValue(retVal);
  9148. }
  9149. break;
  9150. }
  9151. if (fieldInstance->mDataIdx >= 0)
  9152. checkTypeLambda(fieldInstance->GetResolvedType());
  9153. }
  9154. }
  9155. else if (!checkType->IsValuelessType())
  9156. {
  9157. componentIdx++;
  9158. //argIdx++;
  9159. }
  9160. };
  9161. checkTypeLambda(typedValue.mType);
  9162. BF_ASSERT(retVal);
  9163. return retVal;
  9164. }
  9165. if (typedValue.IsAddr())
  9166. {
  9167. BF_ASSERT(fieldType != NULL);
  9168. auto valRef = mBfIRBuilder->CreateInBoundsGEP(typedValue.mValue, 0, useFieldIdx);
  9169. return BfTypedValue(valRef, fieldType, BfTypedValueKind_ReadOnlyAddr);
  9170. }
  9171. else
  9172. {
  9173. BF_ASSERT(fieldType != NULL);
  9174. return BfTypedValue(mBfIRBuilder->CreateExtractValue(typedValue.mValue, useFieldIdx), fieldType, BfTypedValueKind_Value);
  9175. }
  9176. }
  9177. BfIRValue BfModule::ExtractValue(BfTypedValue typedValue, int dataIdx)
  9178. {
  9179. if (typedValue.IsAddr())
  9180. {
  9181. auto addrVal = mBfIRBuilder->CreateInBoundsGEP(typedValue.mValue, 0, dataIdx);
  9182. return mBfIRBuilder->CreateLoad(addrVal);
  9183. }
  9184. return mBfIRBuilder->CreateExtractValue(typedValue.mValue, dataIdx);
  9185. }
  9186. BfIRValue BfModule::CreateIndexedValue(BfType* elementType, BfIRValue value, BfIRValue indexValue, bool isElementIndex)
  9187. {
  9188. if (elementType->IsSizeAligned())
  9189. {
  9190. if (isElementIndex)
  9191. return mBfIRBuilder->CreateInBoundsGEP(value, GetConstValue(0), indexValue);
  9192. else
  9193. return mBfIRBuilder->CreateInBoundsGEP(value, indexValue);
  9194. }
  9195. auto ptrType = CreatePointerType(elementType);
  9196. auto ofsVal = mBfIRBuilder->CreateNumericCast(indexValue, true, BfTypeCode_IntPtr);
  9197. auto ofsScaledVal = mBfIRBuilder->CreateMul(ofsVal, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, elementType->GetStride()));
  9198. auto intVal = mBfIRBuilder->CreatePtrToInt(value, BfTypeCode_IntPtr);
  9199. auto newIntVal = mBfIRBuilder->CreateAdd(intVal, ofsScaledVal);
  9200. return mBfIRBuilder->CreateIntToPtr(newIntVal, mBfIRBuilder->MapType(ptrType));
  9201. }
  9202. BfIRValue BfModule::CreateIndexedValue(BfType* elementType, BfIRValue value, int indexValue, bool isElementIndex)
  9203. {
  9204. if (elementType->IsSizeAligned())
  9205. {
  9206. if (isElementIndex)
  9207. return mBfIRBuilder->CreateInBoundsGEP(value, 0, indexValue);
  9208. else
  9209. return mBfIRBuilder->CreateInBoundsGEP(value, indexValue);
  9210. }
  9211. return CreateIndexedValue(elementType, value, GetConstValue(indexValue), isElementIndex);
  9212. }
  9213. bool BfModule::CheckModifyValue(BfTypedValue& typedValue, BfAstNode* refNode, const char* modifyType)
  9214. {
  9215. if (modifyType == NULL)
  9216. modifyType = "modify";
  9217. if (typedValue.mType->IsVar())
  9218. return true;
  9219. if (typedValue.IsReadOnly())
  9220. {
  9221. Fail(StrFormat("Cannot %s read-only variable", modifyType), refNode);
  9222. return false;
  9223. }
  9224. if ((!typedValue.IsAddr()) && (!typedValue.mType->IsValuelessType()))
  9225. {
  9226. Fail(StrFormat("Cannot %s value", modifyType), refNode);
  9227. return false;
  9228. }
  9229. if (typedValue.mKind == BfTypedValueKind_TempAddr)
  9230. {
  9231. Fail(StrFormat("Cannot %s temporary value", modifyType), refNode);
  9232. return false;
  9233. }
  9234. return true;
  9235. }
  9236. bool BfModule::CompareMethodSignatures(BfMethodInstance* methodA, BfMethodInstance* methodB)
  9237. {
  9238. // If one is an interface and the other is an impl, B is the impl
  9239. auto implOwner = methodB->GetOwner();
  9240. if (methodA->mMethodDef->mIsLocalMethod)
  9241. {
  9242. int sepPosA = (int)BF_MIN(methodA->mMethodDef->mName.IndexOf('@'), methodA->mMethodDef->mName.length());
  9243. int sepPosB = (int)BF_MIN(methodB->mMethodDef->mName.IndexOf('@'), methodB->mMethodDef->mName.length());
  9244. if (sepPosA != sepPosB)
  9245. return false;
  9246. if (strncmp(methodA->mMethodDef->mName.c_str(), methodB->mMethodDef->mName.c_str(), sepPosA) != 0)
  9247. return false;
  9248. }
  9249. else if (methodA->mMethodDef->mName != methodB->mMethodDef->mName)
  9250. return false;
  9251. if (methodA->mMethodDef->mCheckedKind != methodB->mMethodDef->mCheckedKind)
  9252. return false;
  9253. if (methodA->mMethodDef->mMethodType == BfMethodType_Ctor)
  9254. {
  9255. if (methodA->mMethodDef->mIsStatic != methodB->mMethodDef->mIsStatic)
  9256. return false;
  9257. }
  9258. if (methodA->mMethodDef->mMethodType == BfMethodType_Operator)
  9259. {
  9260. if (methodB->mMethodDef->mMethodType != BfMethodType_Operator)
  9261. return false;
  9262. auto operatorA = (BfOperatorDef*)methodA->mMethodDef;
  9263. auto operatorB = (BfOperatorDef*)methodB->mMethodDef;
  9264. if (operatorA->mOperatorDeclaration->mBinOp != operatorB->mOperatorDeclaration->mBinOp)
  9265. return false;
  9266. if (operatorA->mOperatorDeclaration->mUnaryOp != operatorB->mOperatorDeclaration->mUnaryOp)
  9267. return false;
  9268. if (operatorA->mOperatorDeclaration->mIsConvOperator)
  9269. {
  9270. if (!BfTypeUtils::TypeEquals(methodA->mReturnType, methodB->mReturnType, implOwner))
  9271. return false;
  9272. }
  9273. }
  9274. int implicitParamCountA = methodA->GetImplicitParamCount();
  9275. int implicitParamCountB = methodB->GetImplicitParamCount();
  9276. if (methodA->GetParamCount() - implicitParamCountA != methodB->GetParamCount() - implicitParamCountB)
  9277. return false;
  9278. if (methodA->mHadGenericDelegateParams != methodB->mHadGenericDelegateParams)
  9279. return false;
  9280. for (int paramIdx = 0; paramIdx < (int)methodA->GetParamCount() - implicitParamCountA; paramIdx++)
  9281. {
  9282. if ((!BfTypeUtils::TypeEquals(methodA->GetParamType(paramIdx + implicitParamCountA), methodB->GetParamType(paramIdx + implicitParamCountB), implOwner)) ||
  9283. (methodA->GetParamKind(paramIdx + implicitParamCountA) != methodB->GetParamKind(paramIdx + implicitParamCountB)))
  9284. return false;
  9285. }
  9286. // Compare generic params. Generic params are part of the method signature here
  9287. if (methodA->GetNumGenericParams() != methodB->GetNumGenericParams())
  9288. return false;
  9289. for (int genericParamIdx = 0; genericParamIdx < (int)methodA->GetNumGenericParams(); genericParamIdx++)
  9290. {
  9291. auto genericParamA = methodA->mMethodInfoEx->mGenericParams[genericParamIdx];
  9292. auto genericParamB = methodB->mMethodInfoEx->mGenericParams[genericParamIdx];
  9293. if (genericParamA->mGenericParamFlags != genericParamB->mGenericParamFlags)
  9294. return false;
  9295. if (genericParamA->mTypeConstraint != genericParamB->mTypeConstraint)
  9296. return false;
  9297. if (genericParamA->mInterfaceConstraints.size() != genericParamB->mInterfaceConstraints.size())
  9298. return false;
  9299. for (int interfaceIdx = 0; interfaceIdx < (int)genericParamA->mInterfaceConstraints.size(); interfaceIdx++)
  9300. if (genericParamA->mInterfaceConstraints[interfaceIdx] != genericParamB->mInterfaceConstraints[interfaceIdx])
  9301. return false;
  9302. }
  9303. return true;
  9304. }
  9305. bool BfModule::IsCompatibleInterfaceMethod(BfMethodInstance* iMethodInst, BfMethodInstance* methodInstance)
  9306. {
  9307. if (iMethodInst->mMethodDef->mName != methodInstance->mMethodDef->mName)
  9308. return false;
  9309. if (iMethodInst->mMethodDef->mIsOperator != methodInstance->mMethodDef->mIsOperator)
  9310. return false;
  9311. if (iMethodInst->mMethodDef->mIsOperator)
  9312. {
  9313. auto iOperatorDef = (BfOperatorDef*)iMethodInst->mMethodDef;
  9314. auto operatorDef = (BfOperatorDef*)methodInstance->mMethodDef;
  9315. if (iOperatorDef->mOperatorDeclaration->mUnaryOp != operatorDef->mOperatorDeclaration->mUnaryOp)
  9316. return false;
  9317. if (iOperatorDef->mOperatorDeclaration->mBinOp != operatorDef->mOperatorDeclaration->mBinOp)
  9318. return false;
  9319. }
  9320. if (iMethodInst->GetParamCount() != methodInstance->GetParamCount())
  9321. return false;
  9322. for (int paramIdx = 0; paramIdx < (int)iMethodInst->GetParamCount(); paramIdx++)
  9323. {
  9324. if (iMethodInst->GetParamKind(paramIdx) != methodInstance->GetParamKind(paramIdx))
  9325. return false;
  9326. BfType* iParamType = iMethodInst->GetParamType(paramIdx);
  9327. BfType* methodParamType = methodInstance->GetParamType(paramIdx);
  9328. if (iParamType->IsSelf())
  9329. {
  9330. if (methodParamType != methodInstance->GetOwner())
  9331. return false;
  9332. }
  9333. else if (!iParamType->IsGenericParam())
  9334. {
  9335. if (methodParamType != iParamType)
  9336. return false;
  9337. }
  9338. else
  9339. {
  9340. if (!methodParamType->IsGenericParam())
  9341. return false;
  9342. auto genericParamType = (BfGenericParamType*)methodParamType;
  9343. if (genericParamType->mGenericParamKind == BfGenericParamKind_Type)
  9344. return false;
  9345. auto genericParam = methodInstance->mMethodInfoEx->mGenericParams[genericParamType->mGenericParamIdx];
  9346. bool hadInterface = false;
  9347. for (auto interfaceConstraint : genericParam->mInterfaceConstraints)
  9348. if (interfaceConstraint == iParamType)
  9349. hadInterface = true;
  9350. if (!hadInterface)
  9351. return false;
  9352. }
  9353. }
  9354. return true;
  9355. }
  9356. void BfModule::AddMethodReference(const BfMethodRef& methodRef, BfGetMethodInstanceFlags flags)
  9357. {
  9358. BfMethodInstance* methodInstance = methodRef;
  9359. if ((mCurTypeInstance != NULL) && (!mCompiler->IsAutocomplete()))
  9360. {
  9361. auto methodInstanceGroup = methodInstance->mMethodInstanceGroup;
  9362. if ((methodInstance->IsSpecializedGenericMethod()) || (methodInstanceGroup->mOnDemandKind != BfMethodOnDemandKind_AlwaysInclude))
  9363. {
  9364. BF_ASSERT(!methodRef.mTypeInstance->IsFunction());
  9365. BfMethodRef methodRef = methodInstance;
  9366. BfSpecializedMethodRefInfo* specializedMethodRefInfo = NULL;
  9367. bool isNew = mCurTypeInstance->mSpecializedMethodReferences.TryAdd(methodRef, NULL, &specializedMethodRefInfo);
  9368. if (((flags & BfGetMethodInstanceFlag_Unreified) == 0) &&
  9369. ((flags & BfGetMethodInstanceFlag_NoForceReification) == 0) &&
  9370. (mIsReified))
  9371. {
  9372. specializedMethodRefInfo->mHasReifiedRef = true;
  9373. }
  9374. }
  9375. }
  9376. }
  9377. BfModuleMethodInstance BfModule::ReferenceExternalMethodInstance(BfMethodInstance* methodInstance, BfGetMethodInstanceFlags flags)
  9378. {
  9379. if ((flags & BfGetMethodInstanceFlag_ResultNotUsed) != 0)
  9380. return BfModuleMethodInstance(methodInstance, BfIRValue());
  9381. if (mBfIRBuilder == NULL)
  9382. return BfModuleMethodInstance(methodInstance, BfIRValue());
  9383. if (methodInstance->GetOwner()->IsFunction())
  9384. {
  9385. // No actual ref needed- not an actual generated function
  9386. return BfModuleMethodInstance(methodInstance, BfIRValue());
  9387. }
  9388. bool isGenFunction = methodInstance->mMethodInstanceGroup->mMethodIdx < 0;
  9389. if (!isGenFunction)
  9390. AddMethodReference(methodInstance, flags);
  9391. if (mBfIRBuilder->mIgnoreWrites)
  9392. return BfModuleMethodInstance(methodInstance, mBfIRBuilder->GetFakeVal());
  9393. if (mCompiler->IsSkippingExtraResolveChecks())
  9394. return BfModuleMethodInstance(methodInstance, BfIRFunction());
  9395. if (methodInstance->mMethodDef->mMethodType == BfMethodType_Mixin)
  9396. {
  9397. return BfModuleMethodInstance(methodInstance, BfIRFunction());
  9398. }
  9399. bool isInlined = (methodInstance->mAlwaysInline) || ((flags & BfGetMethodInstanceFlag_ForceInline) != 0);
  9400. BfMethodRef methodRef = methodInstance;
  9401. if (isInlined)
  9402. methodRef.mMethodRefFlags = (BfMethodRefFlags)(methodRef.mMethodRefFlags | BfMethodRefFlag_AlwaysInclude);
  9403. else
  9404. methodRef.mMethodRefFlags = BfMethodRefFlag_None;
  9405. if (!isGenFunction)
  9406. {
  9407. BfIRValue* irFuncPtr = NULL;
  9408. if (mFuncReferences.TryGetValue(methodRef, &irFuncPtr))
  9409. return BfModuleMethodInstance(methodInstance, *irFuncPtr);
  9410. }
  9411. if (mAwaitingInitFinish)
  9412. FinishInit();
  9413. BfIRValue func = CreateFunctionFrom(methodInstance, isGenFunction, isInlined);
  9414. if (!isGenFunction)
  9415. mFuncReferences[methodRef] = func;
  9416. BfLogSysM("Adding func reference. Module:%p MethodInst:%p NewLLVMFunc:%d OldLLVMFunc:%d\n", this, methodInstance, func.mId, methodInstance->mIRFunction.mId);
  9417. if ((isInlined) && (!mIsScratchModule))
  9418. {
  9419. // We can't just add a dependency to mCurTypeInstance because we may have nested inlined functions, and
  9420. // mCurTypeInstance will just reflect the owner of the method currently being inlined, not the top-level
  9421. // type instance
  9422. // Be smarter about this if we ever insert a lot of type instances into a single module - track in a field
  9423. BF_ASSERT(mOwnedTypeInstances.size() <= 1);
  9424. for (auto ownedTypeInst : mOwnedTypeInstances)
  9425. AddDependency(methodInstance->GetOwner(), ownedTypeInst, BfDependencyMap::DependencyFlag_InlinedCall);
  9426. if ((!mCompiler->mIsResolveOnly) && (mIsReified) && (!methodInstance->mIsUnspecialized))
  9427. {
  9428. mIncompleteMethodCount++;
  9429. BfInlineMethodRequest* inlineMethodRequest = mContext->mInlineMethodWorkList.Alloc();
  9430. inlineMethodRequest->mType = methodInstance->GetOwner();
  9431. inlineMethodRequest->mFromModule = this;
  9432. inlineMethodRequest->mFunc = func;
  9433. inlineMethodRequest->mFromModuleRevision = mRevision;
  9434. inlineMethodRequest->mMethodInstance = methodInstance;
  9435. BF_ASSERT(mIsModuleMutable);
  9436. BfLogSysM("mInlineMethodWorkList %p for method %p in module %p in ReferenceExternalMethodInstance\n", inlineMethodRequest, methodInstance, this);
  9437. }
  9438. }
  9439. return BfModuleMethodInstance(methodInstance, func);
  9440. }
  9441. BfModule* BfModule::GetOrCreateMethodModule(BfMethodInstance* methodInstance)
  9442. {
  9443. BfTypeInstance* typeInst = methodInstance->mMethodInstanceGroup->mOwner;
  9444. if (mBfIRBuilder == NULL)
  9445. {
  9446. // To allow for custom attribute data
  9447. PrepareForIRWriting(typeInst);
  9448. }
  9449. BfModule* declareModule = this;
  9450. // Get to the optionless branch head -- but this could still be a specialized method module, not the true root
  9451. while ((declareModule->mParentModule != NULL) && (!declareModule->mIsSpecializedMethodModuleRoot))
  9452. declareModule = declareModule->mParentModule;
  9453. // Check for attributes
  9454. if (typeInst == mContext->mBfObjectType)
  9455. {
  9456. auto methodDecl = methodInstance->mMethodDef->GetMethodDeclaration();
  9457. if (methodDecl != NULL)
  9458. {
  9459. auto attributesDirective = methodDecl->mAttributes;
  9460. if ((attributesDirective != NULL) && (mCompiler->mResolvePassData != NULL) &&
  9461. (attributesDirective->IsFromParser(mCompiler->mResolvePassData->mParser)) && (mCompiler->mResolvePassData->mSourceClassifier != NULL))
  9462. {
  9463. mCompiler->mResolvePassData->mSourceClassifier->VisitChild(attributesDirective);
  9464. }
  9465. }
  9466. }
  9467. else
  9468. {
  9469. // Only allow attributes on System.Object methods that can be handled inside the DefBuilder
  9470. GetMethodCustomAttributes(methodInstance);
  9471. }
  9472. BF_ASSERT(mModuleOptions == NULL);
  9473. if (methodInstance->GetCustomAttributes() != NULL)
  9474. {
  9475. auto project = typeInst->mTypeDef->mProject;
  9476. BfModuleOptions moduleOptions = declareModule->GetModuleOptions();
  9477. BfModuleOptions wantOptions = moduleOptions;
  9478. auto typeOptions = mSystem->GetTypeOptions(typeInst->mTypeOptionsIdx);
  9479. if (typeOptions != NULL)
  9480. {
  9481. wantOptions.mOptLevel = (BfOptLevel)BfTypeOptions::Apply((int)wantOptions.mOptLevel, (int)typeOptions->mOptimizationLevel);
  9482. wantOptions.mSIMDSetting = (BfSIMDSetting)BfTypeOptions::Apply((int)wantOptions.mSIMDSetting, typeOptions->mSIMDSetting);
  9483. wantOptions.mEmitDebugInfo = (BfSIMDSetting)BfTypeOptions::Apply((int)wantOptions.mEmitDebugInfo, typeOptions->mEmitDebugInfo);
  9484. }
  9485. if (!mCompiler->mAttributeTypeOptionMap.IsEmpty())
  9486. {
  9487. StringT<128> attrName;
  9488. for (auto& customAttrs : methodInstance->GetCustomAttributes()->mAttributes)
  9489. {
  9490. attrName.Clear();
  9491. customAttrs.mType->mTypeDef->mFullName.ToString(attrName);
  9492. Array<int>* arrPtr;
  9493. if (mCompiler->mAttributeTypeOptionMap.TryGetValue(attrName, &arrPtr))
  9494. {
  9495. for (auto optionsIdx : *arrPtr)
  9496. {
  9497. auto& typeOptions = mCompiler->mSystem->mTypeOptions[optionsIdx];
  9498. wantOptions.mOptLevel = (BfOptLevel)BfTypeOptions::Apply((int)wantOptions.mOptLevel, (int)typeOptions.mOptimizationLevel);
  9499. wantOptions.mSIMDSetting = (BfSIMDSetting)BfTypeOptions::Apply((int)wantOptions.mSIMDSetting, typeOptions.mSIMDSetting);
  9500. wantOptions.mEmitDebugInfo = (BfSIMDSetting)BfTypeOptions::Apply((int)wantOptions.mEmitDebugInfo, typeOptions.mEmitDebugInfo);
  9501. }
  9502. }
  9503. }
  9504. }
  9505. if ((HasCompiledOutput()) && (wantOptions != moduleOptions) && (!mIsScratchModule))
  9506. {
  9507. auto lastCheckModule = this;
  9508. auto checkModule = this->mNextAltModule;
  9509. while (checkModule != NULL)
  9510. {
  9511. if (*checkModule->mModuleOptions == wantOptions)
  9512. {
  9513. declareModule = checkModule;
  9514. break;
  9515. }
  9516. lastCheckModule = checkModule;
  9517. checkModule = checkModule->mNextAltModule;
  9518. }
  9519. // Not found?
  9520. if (declareModule == this)
  9521. {
  9522. String specModuleName = mModuleName + "@@";
  9523. if (wantOptions.mOptLevel != moduleOptions.mOptLevel)
  9524. specModuleName += StrFormat("O%d", wantOptions.mOptLevel);
  9525. if (wantOptions.mSIMDSetting != moduleOptions.mSIMDSetting)
  9526. specModuleName += StrFormat("SIMD%d", wantOptions.mSIMDSetting);
  9527. declareModule = new BfModule(mContext, specModuleName);
  9528. declareModule->mProject = project;
  9529. declareModule->mModuleOptions = new BfModuleOptions();
  9530. *declareModule->mModuleOptions = wantOptions;
  9531. declareModule->mParentModule = lastCheckModule;
  9532. declareModule->Init();
  9533. lastCheckModule->mNextAltModule = declareModule;
  9534. }
  9535. }
  9536. }
  9537. declareModule->PrepareForIRWriting(typeInst);
  9538. return declareModule;
  9539. }
  9540. BfModuleMethodInstance BfModule::GetMethodInstance(BfTypeInstance* typeInst, BfMethodDef* methodDef, const BfTypeVector& methodGenericArguments, BfGetMethodInstanceFlags flags, BfTypeInstance* foreignType)
  9541. {
  9542. if (((flags & BfGetMethodInstanceFlag_ForceInline) != 0) && (mCompiler->mIsResolveOnly))
  9543. {
  9544. // Don't bother inlining for resolve-only
  9545. flags = (BfGetMethodInstanceFlags)(flags & ~BfGetMethodInstanceFlag_ForceInline);
  9546. }
  9547. bool processNow = false;
  9548. bool keepInCurrentModule = false;
  9549. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mIsUnspecialized))
  9550. flags = (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_NoForceReification);
  9551. if (!typeInst->IsTypeMemberIncluded(methodDef->mDeclaringType))
  9552. {
  9553. return BfModuleMethodInstance();
  9554. }
  9555. if (methodDef->mIsLocalMethod)
  9556. {
  9557. auto rootMethodState = mCurMethodState->GetRootMethodState();
  9558. BfLocalMethod* localMethod;
  9559. if (rootMethodState->mLocalMethodCache.TryGetValue(methodDef->mName, &localMethod))
  9560. {
  9561. // Handle the def in the correct method state
  9562. return GetLocalMethodInstance(localMethod, methodGenericArguments);
  9563. }
  9564. BF_FATAL("Cannot find local method");
  9565. return BfModuleMethodInstance();
  9566. }
  9567. #ifdef _DEBUG
  9568. for (auto arg : methodGenericArguments)
  9569. BF_ASSERT(!arg->IsVar());
  9570. #endif
  9571. BF_ASSERT(methodDef->mMethodType != BfMethodType_Ignore);
  9572. // We need to do the 'mNeedsMethodProcessing' check because we want to do a proper initial "awaiting reference" population
  9573. // on the methods before we handle an on-demand situation. This also ensures that our type options are set before doing
  9574. // a FinishInit
  9575. if ((typeInst->IsIncomplete()) &&
  9576. (!typeInst->mResolvingVarField) && (!typeInst->mTypeFailed))
  9577. {
  9578. // For autocomplete, we still may not actually generate methods. This shouldn't matter, and on-demand works differently
  9579. // for resolve-only because we don't differentiate between reified/unreified there
  9580. PopulateType(typeInst, BfPopulateType_Full);
  9581. }
  9582. bool tryModuleMethodLookup = false;
  9583. BfModuleMethodInstance moduleMethodInst;
  9584. BfModule* instModule = typeInst->mModule;
  9585. if (keepInCurrentModule)
  9586. {
  9587. // Stay here
  9588. instModule = this;
  9589. }
  9590. if (this == mContext->mUnreifiedModule)
  9591. {
  9592. // Stay in this 'resolve only' module here
  9593. }
  9594. else if (flags & BfGetMethodInstanceFlag_ExplicitResolveOnlyPass)
  9595. {
  9596. BF_ASSERT(this == mContext->mUnreifiedModule);
  9597. }
  9598. else if (flags & BfGetMethodInstanceFlag_ExplicitSpecializedModule)
  9599. {
  9600. BF_ASSERT(instModule == mParentModule);
  9601. }
  9602. else if (instModule != this)
  9603. {
  9604. if ((!mIsReified) && (instModule->mIsReified))
  9605. {
  9606. BF_ASSERT(!mCompiler->mIsResolveOnly);
  9607. // A resolve-only module is specializing a method from a type in a reified module,
  9608. // we need to take care that this doesn't cause anything new to become reified
  9609. return mContext->mUnreifiedModule->GetMethodInstance(typeInst, methodDef, methodGenericArguments, (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_ExplicitResolveOnlyPass), foreignType);
  9610. }
  9611. else
  9612. {
  9613. if ((mIsReified) && (!instModule->mIsReified))
  9614. {
  9615. if (!instModule->mReifyQueued)
  9616. {
  9617. BF_ASSERT((mCompiler->mCompileState != BfCompiler::CompileState_Unreified) && (mCompiler->mCompileState != BfCompiler::CompileState_VData));
  9618. BfLogSysM("Queueing ReifyModule: %p\n", instModule);
  9619. mContext->mReifyModuleWorkList.Add(instModule);
  9620. instModule->mReifyQueued = true;
  9621. }
  9622. // This ensures that the method will actually be created when it gets reified
  9623. BfMethodSpecializationRequest* specializationRequest = mContext->mMethodSpecializationWorkList.Alloc();
  9624. specializationRequest->mFromModule = typeInst->mModule;
  9625. specializationRequest->mFromModuleRevision = typeInst->mModule->mRevision;
  9626. specializationRequest->mMethodDef = methodDef;
  9627. specializationRequest->mMethodGenericArguments = methodGenericArguments;
  9628. specializationRequest->mType = typeInst;
  9629. specializationRequest->mFlags = flags;
  9630. }
  9631. auto defFlags = (BfGetMethodInstanceFlags)(flags & ~BfGetMethodInstanceFlag_ForceInline);
  9632. // Not extern
  9633. // Create the instance in the proper module and then create a reference in this one
  9634. moduleMethodInst = instModule->GetMethodInstance(typeInst, methodDef, methodGenericArguments, defFlags, foreignType);
  9635. tryModuleMethodLookup = true;
  9636. if ((mIsReified) && (!moduleMethodInst.mMethodInstance->mIsReified))
  9637. {
  9638. CheckHotMethod(moduleMethodInst.mMethodInstance, "");
  9639. }
  9640. }
  9641. }
  9642. if (tryModuleMethodLookup)
  9643. return ReferenceExternalMethodInstance(moduleMethodInst.mMethodInstance, flags);
  9644. if (((flags & BfGetMethodInstanceFlag_ForceInline) != 0) && (!methodDef->mAlwaysInline))
  9645. {
  9646. auto moduleMethodInstance = GetMethodInstance(typeInst, methodDef, methodGenericArguments, (BfGetMethodInstanceFlags)(flags & ~BfGetMethodInstanceFlag_ForceInline), foreignType);
  9647. if (moduleMethodInstance)
  9648. return ReferenceExternalMethodInstance(moduleMethodInstance.mMethodInstance, flags);
  9649. return moduleMethodInst;
  9650. }
  9651. bool isReified = mIsReified /* || ((flags & BfGetMethodInstanceFlag_ExplicitResolveOnlyPass) != 0)*/;
  9652. bool hadConcreteInterfaceGenericArgument = false;
  9653. if ((flags & BfGetMethodInstanceFlag_Unreified) != 0)
  9654. isReified = false;
  9655. if ((flags & BfGetMethodInstanceFlag_ExplicitResolveOnlyPass) != 0)
  9656. {
  9657. isReified = false;
  9658. }
  9659. BfTypeVector sanitizedMethodGenericArguments;
  9660. SizedArray<BfProject*, 4> projectList;
  9661. bool isUnspecializedPass = (flags & BfGetMethodInstanceFlag_UnspecializedPass) != 0;
  9662. if ((isUnspecializedPass) && (methodDef->mGenericParams.size() == 0))
  9663. isUnspecializedPass = false;
  9664. // 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
  9665. bool isExternalExtensionMethod = false;
  9666. if ((!typeInst->IsUnspecializedType()) && (!isUnspecializedPass))
  9667. {
  9668. if (((flags & BfGetMethodInstanceFlag_ForeignMethodDef) == 0) && (methodDef->mDeclaringType->mProject != typeInst->mTypeDef->mProject))
  9669. {
  9670. auto specProject = methodDef->mDeclaringType->mProject;
  9671. isExternalExtensionMethod = true;
  9672. if (typeInst->IsGenericTypeInstance())
  9673. {
  9674. auto genericTypeInst = (BfGenericTypeInstance*)typeInst;
  9675. if (genericTypeInst->mProjectsReferenced.empty())
  9676. genericTypeInst->GenerateProjectsReferenced();
  9677. if (genericTypeInst->mProjectsReferenced.Contains(specProject))
  9678. {
  9679. // This is a generic type where a generic param is already confined to the project in question
  9680. isExternalExtensionMethod = false;
  9681. }
  9682. }
  9683. if (isExternalExtensionMethod)
  9684. {
  9685. BF_ASSERT(typeInst->mTypeDef->mIsCombinedPartial);
  9686. projectList.push_back(methodDef->mDeclaringType->mProject);
  9687. }
  9688. }
  9689. }
  9690. if ((!isUnspecializedPass) && (methodGenericArguments.size() != 0))
  9691. {
  9692. int typeProjectsCounts = 0;
  9693. if (typeInst->IsGenericTypeInstance())
  9694. {
  9695. auto genericTypeInst = (BfGenericTypeInstance*)typeInst;
  9696. if (genericTypeInst->mProjectsReferenced.empty())
  9697. genericTypeInst->GenerateProjectsReferenced();
  9698. typeProjectsCounts = (int)genericTypeInst->mProjectsReferenced.size();
  9699. projectList.Insert(0, &genericTypeInst->mProjectsReferenced[0], genericTypeInst->mProjectsReferenced.size());
  9700. }
  9701. else
  9702. {
  9703. typeProjectsCounts = 1;
  9704. projectList.Insert(0, typeInst->mTypeDef->mProject);
  9705. }
  9706. isUnspecializedPass = true;
  9707. for (int genericArgIdx = 0; genericArgIdx < (int) methodGenericArguments.size(); genericArgIdx++)
  9708. {
  9709. auto genericArgType = methodGenericArguments[genericArgIdx];
  9710. //BF_ASSERT(!genericArgType->IsRef());
  9711. if (genericArgType->IsConcreteInterfaceType())
  9712. {
  9713. hadConcreteInterfaceGenericArgument = true;
  9714. auto concreteInterfaceType = (BfConcreteInterfaceType*)genericArgType;
  9715. genericArgType = concreteInterfaceType->mInterface;
  9716. }
  9717. if (genericArgType->IsGenericParam())
  9718. {
  9719. auto genericParam = (BfGenericParamType*) genericArgType;
  9720. if ((genericParam->mGenericParamKind != BfGenericParamKind_Method) || (genericParam->mGenericParamIdx != genericArgIdx))
  9721. isUnspecializedPass = false;
  9722. }
  9723. else
  9724. {
  9725. BfTypeUtils::GetProjectList(genericArgType, &projectList, typeProjectsCounts);
  9726. isUnspecializedPass = false;
  9727. }
  9728. sanitizedMethodGenericArguments.push_back(genericArgType);
  9729. }
  9730. if ((int)projectList.size() > typeProjectsCounts)
  9731. {
  9732. // Just leave the new items
  9733. projectList.RemoveRange(0, typeProjectsCounts);
  9734. std::sort(projectList.begin(), projectList.end(), [](BfProject* lhs, BfProject*rhs)
  9735. {
  9736. return lhs->mName < rhs->mName;
  9737. });
  9738. }
  9739. else
  9740. {
  9741. projectList.Clear();
  9742. }
  9743. }
  9744. const BfTypeVector& lookupMethodGenericArguments = isUnspecializedPass ? BfTypeVector() : sanitizedMethodGenericArguments;
  9745. BfMethodInstanceGroup* methodInstGroup = NULL;
  9746. if ((flags & BfGetMethodInstanceFlag_ForeignMethodDef) != 0)
  9747. {
  9748. BF_ASSERT(!typeInst->IsInterface());
  9749. //for (auto& checkGroup : typeInst->mMethodInstanceGroups)
  9750. for (int methodIdx = (int)typeInst->mTypeDef->mMethods.size(); methodIdx < (int)typeInst->mMethodInstanceGroups.size(); methodIdx++)
  9751. {
  9752. auto& checkGroup = typeInst->mMethodInstanceGroups[methodIdx];
  9753. // if (checkGroup.mDefault == NULL)
  9754. // {
  9755. // // This should only be for when we explicitly add a spot so we can set mOnDemandKind
  9756. // BF_ASSERT(methodIdx == typeInst->mMethodInstanceGroups.size() - 1);
  9757. // methodInstGroup = &checkGroup;
  9758. // break;
  9759. // }
  9760. if ((checkGroup.mDefault != NULL) && (checkGroup.mDefault->mMethodDef == methodDef))
  9761. {
  9762. methodInstGroup = &checkGroup;
  9763. break;
  9764. }
  9765. }
  9766. if (methodInstGroup == NULL)
  9767. {
  9768. // Allocate a new entry
  9769. typeInst->mMethodInstanceGroups.Resize(typeInst->mMethodInstanceGroups.size() + 1);
  9770. methodInstGroup = &typeInst->mMethodInstanceGroups.back();
  9771. methodInstGroup->mMethodIdx = (int)typeInst->mMethodInstanceGroups.size() - 1;
  9772. methodInstGroup->mOwner = typeInst;
  9773. // if (methodInstGroup->mOnDemandKind == BfMethodOnDemandKind_NotSet)
  9774. // methodInstGroup->mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  9775. if (mCompiler->mOptions.mCompileOnDemandKind == BfCompileOnDemandKind_AlwaysInclude)
  9776. methodInstGroup->mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  9777. else
  9778. methodInstGroup->mOnDemandKind = BfMethodOnDemandKind_Decl_AwaitingDecl;
  9779. }
  9780. }
  9781. else
  9782. {
  9783. methodInstGroup = &typeInst->mMethodInstanceGroups[methodDef->mIdx];
  9784. }
  9785. if (methodInstGroup->mOnDemandKind == BfMethodOnDemandKind_NotSet)
  9786. {
  9787. BfLogSysM("Forcing BfMethodOnDemandKind_NotSet to BfMethodOnDemandKind_AlwaysInclude for Method:%s in Type:%p\n", methodDef->mName.c_str(), typeInst);
  9788. methodInstGroup->mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  9789. }
  9790. BfIRFunction prevIRFunc;
  9791. bool doingRedeclare = false;
  9792. BfMethodInstance* methodInstance = NULL;
  9793. auto _SetReified = [&]()
  9794. {
  9795. methodInstance->mIsReified = true;
  9796. };
  9797. if (lookupMethodGenericArguments.size() == 0)
  9798. {
  9799. methodInstance = methodInstGroup->mDefault;
  9800. if ((methodInstance != NULL) && (isReified) && (!methodInstance->mIsReified))
  9801. {
  9802. MarkDerivedDirty(typeInst);
  9803. if (mIsScratchModule)
  9804. {
  9805. BfLogSysM("Marking scratch module method instance as reified: %p\n", methodInstance);
  9806. _SetReified();
  9807. CheckHotMethod(methodInstance, "");
  9808. }
  9809. else if ((flags & BfGetMethodInstanceFlag_NoForceReification) != 0)
  9810. {
  9811. // We don't need to force reification if we're in an unspecialized generic- we can wait for
  9812. // the specializations to handle that for us
  9813. return BfModuleMethodInstance(methodInstance);
  9814. }
  9815. else if (methodInstGroup->mOnDemandKind == BfMethodOnDemandKind_Referenced)
  9816. {
  9817. if (methodDef->mIsAbstract)
  9818. {
  9819. BfLogSysM("Reifying abstract unreified method instance: %p IRFunction:%d\n", methodInstance, methodInstance->mIRFunction.mId);
  9820. _SetReified();
  9821. }
  9822. else
  9823. {
  9824. BfLogSysM("Re-declaring processed but unreified method instance: %p IRFunction:%d\n", methodInstance, methodInstance->mIRFunction.mId);
  9825. methodInstGroup->mOnDemandKind = BfMethodOnDemandKind_NoDecl_AwaitingReference;
  9826. methodInstance->UndoDeclaration(!methodInstance->mIRFunction.IsFake());
  9827. doingRedeclare = true;
  9828. mOnDemandMethodCount++;
  9829. }
  9830. }
  9831. else
  9832. {
  9833. BfLogSysM("Marking unprocessed method instance as reified: %p\n", methodInstance);
  9834. // We haven't processed it yet
  9835. _SetReified();
  9836. CheckHotMethod(methodInstance, "");
  9837. if (methodInstance->mDeclModule == this)
  9838. {
  9839. if (methodInstance->mMethodProcessRequest != NULL)
  9840. {
  9841. // Disconnect method process request
  9842. BF_ASSERT(methodInstance->mMethodProcessRequest->mFromModule == this);
  9843. }
  9844. }
  9845. else
  9846. {
  9847. if (methodInstance->mMethodProcessRequest != NULL)
  9848. {
  9849. // Disconnect method process request
  9850. BF_ASSERT(methodInstance->mMethodProcessRequest->mFromModule == mContext->mUnreifiedModule);
  9851. methodInstance->mMethodProcessRequest->mMethodInstance = NULL;
  9852. methodInstance->mMethodProcessRequest = NULL;
  9853. }
  9854. if (methodInstance->mDeclModule == mContext->mUnreifiedModule)
  9855. {
  9856. // Add new request in proper module
  9857. methodInstance->mDeclModule = this;
  9858. }
  9859. else
  9860. {
  9861. if (methodInstance->mDeclModule == NULL)
  9862. {
  9863. //
  9864. }
  9865. else if (methodInstance->mDeclModule != this)
  9866. {
  9867. // Is from specialized module?
  9868. BF_ASSERT(methodInstance->mDeclModule->mParentModule == this);
  9869. }
  9870. }
  9871. if ((!methodInstance->mIRFunction) || (methodInstance->mIRFunction.IsFake()))
  9872. {
  9873. methodInstance->mIRFunction = BfIRFunction();
  9874. if (!mIsModuleMutable)
  9875. StartExtension();
  9876. if ((!mBfIRBuilder->mIgnoreWrites) && (methodInstance->mDeclModule != NULL))
  9877. {
  9878. StringT<128> mangledName;
  9879. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), methodInstance);
  9880. bool isIntrinsic = false;
  9881. SetupIRFunction(methodInstance, mangledName, false, &isIntrinsic);
  9882. BfLogSysM("Creating new IRFunction %d\n", methodInstance->mIRFunction.mId);
  9883. }
  9884. }
  9885. AddMethodToWorkList(methodInstance);
  9886. }
  9887. }
  9888. }
  9889. }
  9890. else
  9891. {
  9892. BF_ASSERT(lookupMethodGenericArguments.size() != 0);
  9893. if (methodInstGroup->mMethodSpecializationMap == NULL)
  9894. methodInstGroup->mMethodSpecializationMap = new BfMethodInstanceGroup::MapType();
  9895. BfMethodInstance** methodInstancePtr = NULL;
  9896. if (methodInstGroup->mMethodSpecializationMap->TryGetValue(lookupMethodGenericArguments, &methodInstancePtr))
  9897. {
  9898. methodInstance = *methodInstancePtr;
  9899. if ((isReified) && (!methodInstance->mIsReified))
  9900. {
  9901. MarkDerivedDirty(typeInst);
  9902. if (methodInstance->mHasBeenProcessed)
  9903. {
  9904. BfLogSysM("Deleting processed but unreified specialized method instance %p\n", methodInstance);
  9905. delete methodInstance;
  9906. methodInstGroup->mMethodSpecializationMap->Remove(lookupMethodGenericArguments);
  9907. methodInstance = NULL;
  9908. }
  9909. else if ((!methodInstance->mIRFunction) || (methodInstance->mIRFunction.IsFake()))
  9910. {
  9911. BfLogSysM("Deleting declared but uncreated specialized method instance %p\n", methodInstance);
  9912. delete methodInstance;
  9913. methodInstGroup->mMethodSpecializationMap->Remove(lookupMethodGenericArguments);
  9914. methodInstance = NULL;
  9915. }
  9916. else
  9917. {
  9918. BfLogSysM("Reifying declared but unreified method instance %p\n", methodInstance);
  9919. // We haven't processed it yet
  9920. _SetReified();
  9921. CheckHotMethod(methodInstance, "");
  9922. }
  9923. }
  9924. }
  9925. }
  9926. if ((methodInstance != NULL) && (!doingRedeclare))
  9927. {
  9928. if (methodInstance->mMethodInstanceGroup->mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingReference)
  9929. {
  9930. /*if ((!mCompiler->mIsResolveOnly) && (!isReified))
  9931. BF_ASSERT(!methodInstance->mIsReified);*/
  9932. if (methodInstance->mIsReified != isReified)
  9933. BfLogSysM("GetMethodInstance %p Decl_AwaitingReference setting reified to %d\n", methodInstance, isReified);
  9934. if ((!isReified) &&
  9935. ((methodInstance->mDeclModule == NULL) || (!methodInstance->mDeclModule->mIsModuleMutable)))
  9936. {
  9937. methodInstance->mDeclModule = mContext->mUnreifiedModule;
  9938. methodInstance->mIRFunction = BfIRFunction();
  9939. }
  9940. methodInstance->mIsReified = isReified;
  9941. if ((methodInstance->mHotMethod != NULL) && (!mCompiler->IsHotCompile()) && (isReified))
  9942. {
  9943. methodInstance->mHotMethod->mFlags = (BfHotDepDataFlags)(methodInstance->mHotMethod->mFlags | BfHotDepDataFlag_IsOriginalBuild);
  9944. }
  9945. if (!methodInstance->mMethodDef->mIsAbstract)
  9946. {
  9947. AddMethodToWorkList(methodInstance);
  9948. }
  9949. else
  9950. {
  9951. methodInstance->mMethodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_Referenced;
  9952. }
  9953. }
  9954. if (mExtensionCount > 0)
  9955. {
  9956. if ((mIsModuleMutable) && (!methodInstance->mIRFunction) &&
  9957. ((projectList.IsEmpty() || ((flags & BfGetMethodInstanceFlag_ExplicitSpecializedModule) != 0))))
  9958. {
  9959. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, false);
  9960. if (mAwaitingInitFinish)
  9961. FinishInit();
  9962. // We need to refer to a function that was defined in a prior module
  9963. bool isInlined = (methodInstance->mAlwaysInline) || ((flags & BfGetMethodInstanceFlag_ForceInline) != 0);
  9964. methodInstance->mIRFunction = CreateFunctionFrom(methodInstance, false, isInlined);
  9965. BF_ASSERT((methodInstance->mDeclModule == this) || (methodInstance->mDeclModule == mContext->mUnreifiedModule) || (methodInstance->mDeclModule == NULL));
  9966. methodInstance->mDeclModule = this;
  9967. // Add this inlined def to ourselves
  9968. if ((methodInstance->mAlwaysInline) && (HasCompiledOutput()) && (!methodInstance->mIsUnspecialized))
  9969. {
  9970. mIncompleteMethodCount++;
  9971. BfInlineMethodRequest* inlineMethodRequest = mContext->mInlineMethodWorkList.Alloc();
  9972. inlineMethodRequest->mType = typeInst;
  9973. inlineMethodRequest->mFromModule = this;
  9974. inlineMethodRequest->mFunc = methodInstance->mIRFunction;
  9975. inlineMethodRequest->mFromModuleRevision = mRevision;
  9976. inlineMethodRequest->mMethodInstance = methodInstance;
  9977. BfLogSysM("mInlineMethodWorkList %p for method %p in module %p in GetMethodInstance\n", inlineMethodRequest, methodInstance, this);
  9978. BF_ASSERT(mIsModuleMutable);
  9979. }
  9980. }
  9981. }
  9982. if (mCompiler->IsSkippingExtraResolveChecks())
  9983. return BfModuleMethodInstance(methodInstance, BfIRFunction());
  9984. else
  9985. {
  9986. if (methodInstance->mDeclModule != this)
  9987. return ReferenceExternalMethodInstance(methodInstance, flags);
  9988. if ((!methodInstance->mIRFunction) && (mIsModuleMutable) && (!mBfIRBuilder->mIgnoreWrites))
  9989. {
  9990. auto importKind = methodInstance->GetImportCallKind();
  9991. if (importKind != BfImportCallKind_None)
  9992. {
  9993. BfLogSysM("DllImportGlobalVar creating %p\n", methodInstance);
  9994. methodInstance->mIRFunction = mBfIRBuilder->GetFakeVal();
  9995. mFuncReferences[methodInstance] = CreateDllImportGlobalVar(methodInstance, true);;
  9996. }
  9997. }
  9998. return BfModuleMethodInstance(methodInstance);
  9999. }
  10000. }
  10001. if (!doingRedeclare)
  10002. {
  10003. BfModule* specModule = NULL;
  10004. if ((!keepInCurrentModule) && (projectList.size() > 0) && (!isUnspecializedPass) && (HasCompiledOutput()) && (!mIsScratchModule))
  10005. {
  10006. specModule = GetSpecializedMethodModule(projectList);
  10007. }
  10008. if ((specModule != NULL) && (specModule != this))
  10009. {
  10010. auto specMethodInstance = specModule->GetMethodInstance(typeInst, methodDef, methodGenericArguments, (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_ExplicitSpecializedModule));
  10011. if (mAwaitingInitFinish)
  10012. return BfModuleMethodInstance(specMethodInstance.mMethodInstance, BfIRFunction());
  10013. return ReferenceExternalMethodInstance(specMethodInstance.mMethodInstance, flags);
  10014. }
  10015. if ((!isUnspecializedPass) && (methodGenericArguments.size() != 0) && (methodInstGroup->mDefault == NULL))
  10016. {
  10017. // We are attempting to specialize but we don't have the unspecialized method yet. Generate that first.
  10018. GetMethodInstance(typeInst, methodDef, BfTypeVector(), BfGetMethodInstanceFlag_UnspecializedPass);
  10019. }
  10020. }
  10021. if (methodInstance == NULL)
  10022. {
  10023. if (lookupMethodGenericArguments.size() == 0)
  10024. {
  10025. BF_ASSERT(methodInstGroup->mDefault == NULL);
  10026. methodInstance = new BfMethodInstance();
  10027. methodInstGroup->mDefault = methodInstance;
  10028. BfLogSysM("Created Default MethodInst: %p TypeInst: %p Group: %p\n", methodInstance, typeInst, methodInstGroup);
  10029. }
  10030. else
  10031. {
  10032. BfMethodInstance** methodInstancePtr = NULL;
  10033. bool added = methodInstGroup->mMethodSpecializationMap->TryAdd(lookupMethodGenericArguments, NULL, &methodInstancePtr);
  10034. BF_ASSERT(added);
  10035. methodInstance = new BfMethodInstance();
  10036. *methodInstancePtr = methodInstance;
  10037. BfLogSysM("Created Specialized MethodInst: %p TypeInst: %p\n", methodInstance, typeInst);
  10038. }
  10039. if ((prevIRFunc) && (!prevIRFunc.IsFake()))
  10040. methodInstance->mIRFunction = prevIRFunc; // Take it over
  10041. }
  10042. /*// 24 bits for typeid, 20 for method id, 20 for specialization index
  10043. methodInstance->mMethodId = ((int64)typeInst->mTypeId) + ((int64)methodInstGroup->mMethodIdx << 24);
  10044. if (methodInstGroup->mMethodSpecializationMap != NULL)
  10045. methodInstance->mMethodId += ((int64)methodInstGroup->mMethodSpecializationMap->size() << 44);*/
  10046. methodInstance->mMethodDef = methodDef;
  10047. methodInstance->mAlwaysInline = methodDef->mAlwaysInline;
  10048. methodInstance->mMethodInstanceGroup = methodInstGroup;
  10049. methodInstance->mIsReified = isReified;
  10050. SetupMethodIdHash(methodInstance);
  10051. if (hadConcreteInterfaceGenericArgument)
  10052. methodInstance->mIgnoreBody = true;
  10053. if ((flags & BfGetMethodInstanceFlag_ForeignMethodDef) != 0)
  10054. {
  10055. methodInstance->mIsForeignMethodDef = true;
  10056. BF_ASSERT(foreignType != NULL);
  10057. methodInstance->GetMethodInfoEx()->mForeignType = foreignType;
  10058. }
  10059. if ((typeInst->mTypeDef == mCompiler->mValueTypeTypeDef) && (methodDef->mName == BF_METHODNAME_EQUALS))
  10060. {
  10061. if (!lookupMethodGenericArguments.empty())
  10062. {
  10063. auto compareType = lookupMethodGenericArguments[0];
  10064. PopulateType(compareType, BfPopulateType_Data);
  10065. if (compareType->IsSplattable())
  10066. methodInstance->mAlwaysInline = true;
  10067. }
  10068. }
  10069. if (methodDef->mDeclaringType->mTypeDeclaration != typeInst->mTypeDef->mTypeDeclaration)
  10070. {
  10071. // With extensions we can have multiple definitions of the same method
  10072. //methodInstance->mMangleWithIdx = true;
  10073. }
  10074. BfModule* declareModule = GetOrCreateMethodModule(methodInstance);
  10075. BF_ASSERT(typeInst == methodInstance->GetOwner());
  10076. auto methodDeclaration = methodDef->GetMethodDeclaration();
  10077. if (isUnspecializedPass)
  10078. {
  10079. for (int genericParamIdx = 0; genericParamIdx < (int) methodDef->mGenericParams.size(); genericParamIdx++)
  10080. {
  10081. auto genericParamType = GetGenericParamType(BfGenericParamKind_Method, genericParamIdx);
  10082. methodInstance->GetMethodInfoEx()->mMethodGenericArguments.Add(genericParamType);
  10083. }
  10084. }
  10085. else if ((methodDeclaration != NULL) && (methodDeclaration->mGenericParams != NULL))
  10086. {
  10087. if (!sanitizedMethodGenericArguments.IsEmpty())
  10088. methodInstance->GetMethodInfoEx()->mMethodGenericArguments = sanitizedMethodGenericArguments;
  10089. if (methodDef->mGenericParams.size() != sanitizedMethodGenericArguments.size())
  10090. {
  10091. Fail("Internal error");
  10092. BF_FATAL("Generic method argument counts mismatch");
  10093. return NULL;
  10094. }
  10095. for (auto genericArg : sanitizedMethodGenericArguments)
  10096. {
  10097. if (genericArg->IsPrimitiveType())
  10098. genericArg = GetWrappedStructType(genericArg);
  10099. AddDependency(genericArg, typeInst, BfDependencyMap::DependencyFlag_MethodGenericArg);
  10100. if (genericArg->IsMethodRef())
  10101. {
  10102. auto methodRefType = (BfMethodRefType*)genericArg;
  10103. //AddDependency(genericArg, typeInst, BfDependencyMap::DependencyFlag_);
  10104. }
  10105. }
  10106. }
  10107. // Generic constraints
  10108. for (int genericParamIdx = 0; genericParamIdx < (int)methodDef->mGenericParams.size(); genericParamIdx++)
  10109. {
  10110. auto genericParamInstance = new BfGenericMethodParamInstance(methodDef, genericParamIdx);
  10111. methodInstance->GetMethodInfoEx()->mGenericParams.push_back(genericParamInstance);
  10112. }
  10113. for (int externConstraintIdx = 0; externConstraintIdx < (int)methodDef->mExternalConstraints.size(); externConstraintIdx++)
  10114. {
  10115. auto genericParamInstance = new BfGenericMethodParamInstance(methodDef, externConstraintIdx + (int)methodDef->mGenericParams.size());
  10116. methodInstance->GetMethodInfoEx()->mGenericParams.push_back(genericParamInstance);
  10117. }
  10118. bool addToWorkList = !processNow;
  10119. if (mCompiler->GetAutoComplete() != NULL)
  10120. {
  10121. if (typeInst->IsSpecializedByAutoCompleteMethod())
  10122. addToWorkList = false;
  10123. }
  10124. BF_ASSERT(declareModule != NULL);
  10125. methodInstance->mDeclModule = declareModule;
  10126. if ((!methodInstance->mIsReified) && (mCompiler->mCompileState != BfCompiler::CompileState_Normal))
  10127. {
  10128. // We can be sure this method won't become reified later. Normally we can "go either way" with an unreified method
  10129. // of a reified module -
  10130. // If we declare it in the reified module then we can switch it to "reified" before actual processing without any extra work,
  10131. // BUT if we don't reify it then we have to remove the body after processing.
  10132. // 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
  10133. // the proper reified module.
  10134. declareModule = mContext->mUnreifiedModule;
  10135. }
  10136. else if ((!declareModule->mIsModuleMutable) && (!mCompiler->mIsResolveOnly))
  10137. {
  10138. BF_ASSERT(!methodInstance->mIsReified);
  10139. declareModule = mContext->mUnreifiedModule;
  10140. }
  10141. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(declareModule->mCurMethodInstance, methodInstance);
  10142. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(declareModule->mCurTypeInstance, typeInst);
  10143. SetAndRestoreValue<BfFilePosition> prevFilePos(declareModule->mCurFilePosition);
  10144. declareModule->DoMethodDeclaration(methodDef->GetMethodDeclaration(), false, addToWorkList);
  10145. if (processNow)
  10146. {
  10147. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, NULL);
  10148. ProcessMethod(methodInstance);
  10149. }
  10150. if (mCompiler->IsSkippingExtraResolveChecks())
  10151. return BfModuleMethodInstance(methodInstance, BfIRFunction());
  10152. return BfModuleMethodInstance(methodInstance);
  10153. }
  10154. BfModuleMethodInstance BfModule::GetMethodInstance(BfMethodInstance* methodInstance, BfGetMethodInstanceFlags flags)
  10155. {
  10156. BF_ASSERT((methodInstance->mMethodInfoEx == NULL) || (methodInstance->mMethodInfoEx->mGenericParams.IsEmpty()));
  10157. if (methodInstance->mIsForeignMethodDef)
  10158. flags = (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_ForeignMethodDef);
  10159. return GetMethodInstance(methodInstance->GetOwner(), methodInstance->mMethodDef, BfTypeVector(), flags);
  10160. }
  10161. BfMethodInstance* BfModule::GetOuterMethodInstance(BfMethodInstance* methodInstance)
  10162. {
  10163. if (!methodInstance->mMethodDef->mIsLocalMethod)
  10164. return NULL;
  10165. auto outerLocal = methodInstance->mMethodInfoEx->mClosureInstanceInfo->mLocalMethod->mOuterLocalMethod;
  10166. if (outerLocal == NULL)
  10167. return NULL;
  10168. BfTypeVector genericArgs;
  10169. for (int i = 0; i < (int)outerLocal->mMethodDef->mGenericParams.size(); i++)
  10170. genericArgs.Add(methodInstance->mMethodInfoEx->mMethodGenericArguments[i]);
  10171. return GetLocalMethodInstance(outerLocal, genericArgs).mMethodInstance;
  10172. }
  10173. void BfModule::SetupMethodIdHash(BfMethodInstance* methodInstance)
  10174. {
  10175. HashContext hashCtx;
  10176. std::function<void(BfMethodInstance*)> _MixinMethodInstance = [&](BfMethodInstance* methodInstance)
  10177. {
  10178. hashCtx.Mixin(methodInstance->GetOwner()->mTypeId);
  10179. hashCtx.Mixin(methodInstance->mMethodDef->mIdx);
  10180. if (methodInstance->GetNumGenericArguments() != 0)
  10181. {
  10182. hashCtx.Mixin((int32)methodInstance->mMethodInfoEx->mMethodGenericArguments.size());
  10183. for (auto methodGenericArg : methodInstance->mMethodInfoEx->mMethodGenericArguments)
  10184. hashCtx.Mixin(methodGenericArg->mTypeId);
  10185. }
  10186. };
  10187. _MixinMethodInstance(methodInstance);
  10188. if (methodInstance->mMethodDef->mIsLocalMethod)
  10189. {
  10190. auto outmostMethodInstance = mCurMethodState->GetRootMethodState()->mMethodInstance;
  10191. BF_ASSERT((outmostMethodInstance->mIdHash != 0) || (outmostMethodInstance->mIsAutocompleteMethod));
  10192. hashCtx.Mixin(outmostMethodInstance->mIdHash);
  10193. }
  10194. methodInstance->mIdHash = (int64)hashCtx.Finish64();
  10195. }
  10196. BfIRValue BfModule::GetInterfaceSlotNum(BfTypeInstance* ifaceType)
  10197. {
  10198. BfIRValue globalValue;
  10199. BfIRValue* globalValuePtr = NULL;
  10200. if (mInterfaceSlotRefs.TryGetValue(ifaceType, &globalValuePtr))
  10201. {
  10202. globalValue = *globalValuePtr;
  10203. }
  10204. if (!globalValue)
  10205. {
  10206. // This is necessary to reify the interface type
  10207. PopulateType(ifaceType);
  10208. StringT<128> slotVarName;
  10209. BfMangler::MangleStaticFieldName(slotVarName, mCompiler->GetMangleKind(), ifaceType, "sBfSlotOfs");
  10210. BfType* intType = GetPrimitiveType(BfTypeCode_Int32);
  10211. BfIRValue value;
  10212. if ((mCompiler->mHotState != NULL) && (ifaceType->mSlotNum >= 0))
  10213. {
  10214. /*// If this interface already existed before this hot compile but we never indirectly called any of its methods
  10215. // then the sBfSlotOfs could have gotten its symbol stripped, so actually define it here.
  10216. int virtSlotIdx = ifaceType->mSlotNum + 1;
  10217. value = GetConstValue32(virtSlotIdx);*/
  10218. mCompiler->mHotState->mSlotDefineTypeIds.Add(ifaceType->mTypeId);
  10219. ifaceType->mDirty = true; // Makes sure we create interface in vdata
  10220. }
  10221. globalValue = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapType(intType), true, BfIRLinkageType_External, value, slotVarName);
  10222. mInterfaceSlotRefs[ifaceType] = globalValue;
  10223. }
  10224. return mBfIRBuilder->CreateLoad(globalValue/*, "slotOfs"*/);
  10225. }
  10226. void BfModule::HadSlotCountDependency()
  10227. {
  10228. if (mCompiler->mIsResolveOnly)
  10229. return;
  10230. BF_ASSERT(!mBfIRBuilder->mIgnoreWrites);
  10231. BF_ASSERT((mUsedSlotCount == BF_MAX(mCompiler->mMaxInterfaceSlots, 0)) || (mUsedSlotCount == -1));
  10232. mUsedSlotCount = BF_MAX(mCompiler->mMaxInterfaceSlots, 0);
  10233. }
  10234. BfTypedValue BfModule::ReferenceStaticField(BfFieldInstance* fieldInstance)
  10235. {
  10236. if (mIsScratchModule)
  10237. {
  10238. // Just fake it for the extern and unspecialized modules
  10239. auto ptrType = CreatePointerType(fieldInstance->GetResolvedType());
  10240. return BfTypedValue(GetDefaultValue(ptrType), fieldInstance->GetResolvedType(), true);
  10241. }
  10242. BfIRValue globalValue;
  10243. auto fieldDef = fieldInstance->GetFieldDef();
  10244. if ((fieldDef->mIsConst) && (!fieldDef->mIsExtern))
  10245. {
  10246. if (fieldInstance->mConstIdx != -1)
  10247. {
  10248. auto constant = fieldInstance->mOwner->mConstHolder->GetConstantById(fieldInstance->mConstIdx);
  10249. return BfTypedValue(ConstantToCurrent(constant, fieldInstance->mOwner->mConstHolder, fieldInstance->GetResolvedType()), fieldInstance->GetResolvedType());
  10250. }
  10251. else
  10252. {
  10253. return GetDefaultTypedValue(fieldInstance->GetResolvedType());
  10254. }
  10255. }
  10256. BfIRValue* globalValuePtr = NULL;
  10257. if (mStaticFieldRefs.TryGetValue(fieldInstance, &globalValuePtr))
  10258. {
  10259. globalValue = *globalValuePtr;
  10260. BF_ASSERT(globalValue);
  10261. }
  10262. else
  10263. {
  10264. StringT<128> staticVarName;
  10265. BfMangler::Mangle(staticVarName, mCompiler->GetMangleKind(), fieldInstance);
  10266. auto typeType = fieldInstance->GetResolvedType();
  10267. if ((fieldDef->mIsExtern) && (fieldDef->mIsConst) && (typeType->IsPointer()))
  10268. {
  10269. typeType = typeType->GetUnderlyingType();
  10270. }
  10271. PopulateType(typeType);
  10272. if ((typeType != NULL) && (!typeType->IsValuelessType()))
  10273. {
  10274. globalValue = mBfIRBuilder->CreateGlobalVariable(
  10275. mBfIRBuilder->MapType(typeType),
  10276. false,
  10277. BfIRLinkageType_External,
  10278. BfIRValue(),
  10279. staticVarName,
  10280. IsThreadLocal(fieldInstance));
  10281. if (!mBfIRBuilder->mIgnoreWrites)
  10282. {
  10283. // Only store this if we actually did the creation
  10284. BF_ASSERT(globalValue);
  10285. mStaticFieldRefs[fieldInstance] = globalValue;
  10286. }
  10287. BfLogSysM("Mod:%p Type:%p ReferenceStaticField %p -> %p\n", this, fieldInstance->mOwner, fieldInstance, globalValue);
  10288. }
  10289. }
  10290. auto type = fieldInstance->GetResolvedType();
  10291. if (type->IsValuelessType())
  10292. return BfTypedValue(globalValue, type);
  10293. return BfTypedValue(globalValue, type, !fieldDef->mIsConst);
  10294. }
  10295. BfTypedValue BfModule::GetThis()
  10296. {
  10297. auto useMethodState = mCurMethodState;
  10298. while ((useMethodState != NULL) && (useMethodState->mClosureState != NULL) && (useMethodState->mClosureState->mCapturing))
  10299. {
  10300. useMethodState = useMethodState->mPrevMethodState;
  10301. }
  10302. if (useMethodState != NULL)
  10303. {
  10304. // Fake a 'this' for var field resolution
  10305. if (useMethodState->mTempKind == BfMethodState::TempKind_NonStatic)
  10306. {
  10307. auto thisType = mCurTypeInstance;
  10308. if (thisType->IsValueType())
  10309. return BfTypedValue(mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapTypeInstPtr(thisType)), thisType, BfTypedValueKind_ThisAddr);
  10310. else
  10311. return BfTypedValue(mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapTypeInst(thisType)), thisType, BfTypedValueKind_ThisValue);
  10312. }
  10313. else if (useMethodState->mTempKind == BfMethodState::TempKind_Static)
  10314. {
  10315. return BfTypedValue();
  10316. }
  10317. }
  10318. else
  10319. {
  10320. //TODO: Do we allow useMethodState to be NULL anymore?
  10321. return BfTypedValue();
  10322. }
  10323. // if (useMethodState->HasNonStaticMixin())
  10324. // {
  10325. // auto checkMethodState = useMethodState;
  10326. // while (checkMethodState != NULL)
  10327. // {
  10328. // for (int localIdx = (int)checkMethodState->mLocals.size() - 1; localIdx >= 0; localIdx--)
  10329. // {
  10330. // auto varDecl = checkMethodState->mLocals[localIdx];
  10331. // if (varDecl->mName == "this")
  10332. // {
  10333. // varDecl->mReadFromId = useMethodState->GetRootMethodState()->mCurAccessId++;
  10334. // if (varDecl->mIsSplat)
  10335. // {
  10336. // return BfTypedValue(varDecl->mValue, varDecl->mResolvedType, BfTypedValueKind_ThisSplatHead);
  10337. // }
  10338. // else if ((varDecl->mResolvedType->IsValueType()) && (varDecl->mAddr))
  10339. // {
  10340. // return BfTypedValue(varDecl->mAddr, varDecl->mResolvedType, BfTypedValueKind_ThisAddr);
  10341. // }
  10342. // return BfTypedValue(varDecl->mValue, varDecl->mResolvedType, varDecl->mResolvedType->IsValueType() ? BfTypedValueKind_ThisAddr : BfTypedValueKind_ThisValue);
  10343. // }
  10344. // }
  10345. //
  10346. // checkMethodState = checkMethodState->mPrevMethodState;
  10347. // }
  10348. // }
  10349. // Check mixin state for 'this'
  10350. {
  10351. auto checkMethodState = useMethodState;
  10352. while (checkMethodState != NULL)
  10353. {
  10354. if (checkMethodState->mMixinState != NULL)
  10355. {
  10356. BfTypedValue thisValue = checkMethodState->mMixinState->mTarget;
  10357. if (thisValue)
  10358. {
  10359. checkMethodState->mMixinState->mLastTargetAccessId = useMethodState->GetRootMethodState()->mCurAccessId++;
  10360. if (!thisValue.mType->IsValueType())
  10361. thisValue = LoadValue(thisValue);
  10362. return thisValue;
  10363. }
  10364. }
  10365. checkMethodState = checkMethodState->mPrevMethodState;
  10366. }
  10367. }
  10368. auto curMethodInstance = mCurMethodInstance;
  10369. if (useMethodState->mMethodInstance != NULL)
  10370. curMethodInstance = useMethodState->mMethodInstance;
  10371. if ((curMethodInstance == NULL) /*|| (!mCurMethodInstance->mIRFunction)*/ || (curMethodInstance->mMethodDef->mIsStatic))
  10372. {
  10373. if ((useMethodState->mClosureState != NULL) && (!useMethodState->mClosureState->mConstLocals.empty()))
  10374. {
  10375. auto& constLocal = useMethodState->mClosureState->mConstLocals[0];
  10376. if (constLocal.mIsThis)
  10377. {
  10378. BF_ASSERT(constLocal.mResolvedType->IsValuelessType());
  10379. return BfTypedValue(mBfIRBuilder->GetFakeVal(), constLocal.mResolvedType);
  10380. }
  10381. }
  10382. return BfTypedValue();
  10383. }
  10384. bool preferValue = !IsTargetingBeefBackend();
  10385. if (useMethodState->mLocals.IsEmpty())
  10386. {
  10387. // 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
  10388. BF_ASSERT(useMethodState->mPrevMethodState != NULL);
  10389. return BfTypedValue();
  10390. }
  10391. auto thisLocal = useMethodState->mLocals[0];
  10392. BF_ASSERT(thisLocal->mIsThis);
  10393. BfIRValue thisValue;
  10394. if ((preferValue) || (!thisLocal->mAddr) /*|| (thisLocal->mIsSplat)*/)
  10395. thisValue = thisLocal->mValue;
  10396. else if ((thisLocal->mIsSplat) || (thisLocal->mIsLowered))
  10397. thisValue = thisLocal->mAddr;
  10398. else
  10399. thisValue = mBfIRBuilder->CreateLoad(thisLocal->mAddr);
  10400. useMethodState->mLocals[0]->mReadFromId = useMethodState->GetRootMethodState()->mCurAccessId++;
  10401. if (useMethodState->mClosureState != NULL)
  10402. {
  10403. auto closureTypeInst = useMethodState->mClosureState->mClosureType;
  10404. if (closureTypeInst != NULL)
  10405. {
  10406. if (closureTypeInst->mFieldInstances.size() > 0)
  10407. {
  10408. auto& field = closureTypeInst->mFieldInstances[0];
  10409. auto fieldDef = field.GetFieldDef();
  10410. if (fieldDef->mName == "__this")
  10411. {
  10412. if (mCurMethodState->mClosureState->mCapturing)
  10413. mCurMethodState->mClosureState->mReferencedOuterClosureMembers.Add(&field);
  10414. // This is a captured 'this'
  10415. BfTypedValue result = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(thisValue, 0, field.mDataIdx), field.mResolvedType, true);
  10416. if (field.mResolvedType->IsRef())
  10417. {
  10418. auto refType = (BfRefType*)field.mResolvedType;
  10419. auto underlyingType = refType->GetUnderlyingType();
  10420. result = BfTypedValue(mBfIRBuilder->CreateLoad(result.mValue), underlyingType, true);
  10421. }
  10422. if (field.mResolvedType->IsObject())
  10423. {
  10424. result = LoadValue(result);
  10425. result.mKind = BfTypedValueKind_ThisValue;
  10426. }
  10427. else
  10428. {
  10429. if (fieldDef->mIsReadOnly)
  10430. result.mKind = BfTypedValueKind_ReadOnlyThisAddr;
  10431. else
  10432. result.mKind = BfTypedValueKind_ThisAddr;
  10433. }
  10434. return result;
  10435. }
  10436. }
  10437. return BfTypedValue();
  10438. }
  10439. if (useMethodState->mClosureState->mCapturing)
  10440. {
  10441. auto thisType = useMethodState->mLocals[0]->mResolvedType;
  10442. if (thisType->IsValueType())
  10443. return BfTypedValue(CreateAlloca(thisType), thisType, BfTypedValueKind_ThisAddr);
  10444. else
  10445. return BfTypedValue(GetDefaultValue(thisType), thisType, BfTypedValueKind_ThisValue);
  10446. }
  10447. }
  10448. auto localDef = useMethodState->mLocals[0];
  10449. auto curMethodOwner = mCurMethodInstance->mMethodInstanceGroup->mOwner;
  10450. if ((curMethodOwner->IsStruct()) || (curMethodOwner->IsTypedPrimitive()))
  10451. {
  10452. if ((localDef->mResolvedType->IsTypedPrimitive()) && (!mCurMethodInstance->mMethodDef->mIsMutating))
  10453. {
  10454. return BfTypedValue(thisValue, useMethodState->mLocals[0]->mResolvedType, BfTypedValueKind_ReadOnlyThisValue);
  10455. }
  10456. if (localDef->mIsSplat)
  10457. {
  10458. return BfTypedValue(thisValue, useMethodState->mLocals[0]->mResolvedType, BfTypedValueKind_ThisSplatHead);
  10459. }
  10460. return BfTypedValue(thisValue, useMethodState->mLocals[0]->mResolvedType, localDef->mIsReadOnly ? BfTypedValueKind_ReadOnlyThisAddr : BfTypedValueKind_ThisAddr);
  10461. }
  10462. return BfTypedValue(thisValue, mCurMethodInstance->mMethodInstanceGroup->mOwner, BfTypedValueKind_ThisValue);
  10463. }
  10464. BfLocalVariable* BfModule::GetThisVariable()
  10465. {
  10466. if (mCurMethodState == NULL)
  10467. return NULL;
  10468. auto methodState = mCurMethodState->GetNonCaptureState();
  10469. if ((methodState->mLocals.size() > 0) && (methodState->mLocals[0]->mIsThis))
  10470. return methodState->mLocals[0];
  10471. return NULL;
  10472. }
  10473. bool BfModule::IsInGeneric()
  10474. {
  10475. return (mCurMethodInstance->GetNumGenericArguments() != 0) || (mCurTypeInstance->IsGenericTypeInstance());
  10476. }
  10477. bool BfModule::IsInSpecializedGeneric()
  10478. {
  10479. if ((mCurMethodInstance == NULL) || (mCurMethodInstance->mIsUnspecialized))
  10480. return false;
  10481. return (mCurMethodInstance->GetNumGenericArguments() != 0) || (mCurTypeInstance->IsGenericTypeInstance());
  10482. }
  10483. bool BfModule::IsInSpecializedSection()
  10484. {
  10485. return IsInSpecializedGeneric() ||
  10486. ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL));
  10487. }
  10488. bool BfModule::IsInUnspecializedGeneric()
  10489. {
  10490. if (mCurMethodInstance != NULL)
  10491. return mCurMethodInstance->mIsUnspecialized;
  10492. return false;
  10493. }
  10494. //////////////////////////////////////////////////////////////////////////
  10495. BfIRValue BfModule::AllocLocalVariable(BfType* type, const StringImpl& name, bool doLifetimeEnd)
  10496. {
  10497. //if ((type->IsValuelessType()) || (type->IsMethodRef()))
  10498. if (type->IsValuelessType())
  10499. return mBfIRBuilder->GetFakeVal();
  10500. auto allocaInst = CreateAlloca(type, doLifetimeEnd, name.c_str());
  10501. if ((!doLifetimeEnd) && (WantsLifetimes()))
  10502. {
  10503. auto lifetimeStart = mBfIRBuilder->CreateLifetimeStart(allocaInst);
  10504. mBfIRBuilder->ClearDebugLocation(lifetimeStart);
  10505. }
  10506. bool initLocalVariables = mCompiler->mOptions.mInitLocalVariables;
  10507. auto typeOptions = GetTypeOptions();
  10508. if (typeOptions != NULL)
  10509. initLocalVariables = BfTypeOptions::Apply(initLocalVariables, typeOptions->mInitLocalVariables);
  10510. // Local variable inits are implicitly handled in the Beef Backend
  10511. if ((initLocalVariables) && (!IsTargetingBeefBackend()))
  10512. {
  10513. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  10514. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRInitBlock);
  10515. auto storeInst = mBfIRBuilder->CreateAlignedStore(GetDefaultValue(type), allocaInst, type->mAlign);
  10516. mBfIRBuilder->ClearDebugLocation(storeInst);
  10517. mBfIRBuilder->SetInsertPoint(prevBlock);
  10518. }
  10519. return allocaInst;
  10520. }
  10521. void BfModule::DoAddLocalVariable(BfLocalVariable* localVar)
  10522. {
  10523. localVar->mLocalVarIdx = (int)mCurMethodState->mLocals.size();
  10524. mCurMethodState->mLocals.push_back(localVar);
  10525. BfLocalVarEntry* localVarEntryPtr;
  10526. if (!mCurMethodState->mLocalVarSet.TryAdd(BfLocalVarEntry(localVar), &localVarEntryPtr))
  10527. {
  10528. localVar->mShadowedLocal = localVarEntryPtr->mLocalVar;
  10529. localVarEntryPtr->mLocalVar = localVar;
  10530. }
  10531. }
  10532. BfLocalVariable* BfModule::AddLocalVariableDef(BfLocalVariable* localVarDef, bool addDebugInfo, bool doAliasValue, BfIRValue declareBefore, BfIRInitType initType)
  10533. {
  10534. if ((localVarDef->mValue) && (!localVarDef->mAddr) && (IsTargetingBeefBackend()))
  10535. {
  10536. if ((!localVarDef->mValue.IsConst()) && (!localVarDef->mValue.IsArg()) && (!localVarDef->mValue.IsFake()))
  10537. {
  10538. mBfIRBuilder->CreateValueScopeRetain(localVarDef->mValue);
  10539. mCurMethodState->mCurScope->mHadScopeValueRetain = true;
  10540. }
  10541. }
  10542. if ((addDebugInfo) && (mBfIRBuilder->DbgHasInfo()) &&
  10543. ((mCurMethodInstance == NULL) || (!mCurMethodInstance->mIsUnspecialized)) &&
  10544. (mHasFullDebugInfo) &&
  10545. ((mCurMethodState->mClosureState == NULL) || (!mCurMethodState->mClosureState->mCapturing)))
  10546. {
  10547. auto varType = localVarDef->mResolvedType;
  10548. if (localVarDef->mResolvedType->IsValuelessType())
  10549. {
  10550. }
  10551. else
  10552. {
  10553. bool isByAddr = false;
  10554. auto diValue = localVarDef->mValue;
  10555. if (localVarDef->mConstValue)
  10556. diValue = localVarDef->mConstValue;
  10557. else if (localVarDef->mAddr)
  10558. {
  10559. diValue = localVarDef->mAddr;
  10560. isByAddr = true;
  10561. }
  10562. auto diType = mBfIRBuilder->DbgGetType(localVarDef->mResolvedType);
  10563. bool didConstToMem = false;
  10564. bool isConstant = false;
  10565. if ((localVarDef->mIsReadOnly) && (localVarDef->mAddr))
  10566. diType = mBfIRBuilder->DbgCreateConstType(diType);
  10567. else if (localVarDef->mConstValue)
  10568. {
  10569. auto constant = mBfIRBuilder->GetConstant(localVarDef->mConstValue);
  10570. isConstant =
  10571. (constant->mConstType < BfConstType_GlobalVar) ||
  10572. (constant->mConstType == BfConstType_AggZero) ||
  10573. (constant->mConstType == BfConstType_Array);
  10574. if (isConstant)
  10575. {
  10576. if (localVarDef->mResolvedType->IsComposite())
  10577. {
  10578. mBfIRBuilder->PopulateType(localVarDef->mResolvedType);
  10579. auto constMem = mBfIRBuilder->ConstToMemory(localVarDef->mConstValue);
  10580. if (IsTargetingBeefBackend())
  10581. {
  10582. diValue = mBfIRBuilder->CreateAliasValue(constMem);
  10583. didConstToMem = true;
  10584. diType = mBfIRBuilder->DbgCreateReferenceType(diType);
  10585. }
  10586. else
  10587. {
  10588. isByAddr = true;
  10589. mBfIRBuilder->SaveDebugLocation();
  10590. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  10591. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRInitBlock);
  10592. mBfIRBuilder->ClearDebugLocation();
  10593. auto ptrType = CreatePointerType(localVarDef->mResolvedType);
  10594. auto addrVal = CreateAlloca(ptrType);
  10595. mBfIRBuilder->CreateStore(constMem, addrVal);
  10596. diType = mBfIRBuilder->DbgCreateReferenceType(diType);
  10597. diValue = addrVal;
  10598. didConstToMem = true;
  10599. mBfIRBuilder->SetInsertPoint(prevBlock);
  10600. mBfIRBuilder->RestoreDebugLocation();
  10601. }
  10602. }
  10603. if (mCompiler->mOptions.IsCodeView())
  10604. diType = mBfIRBuilder->DbgCreateConstType(diType);
  10605. }
  10606. }
  10607. auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(mCurMethodState->mCurScope->mDIScope,
  10608. localVarDef->mName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType, initType);
  10609. localVarDef->mDbgVarInst = diVariable;
  10610. if (mBfIRBuilder->HasDebugLocation())
  10611. {
  10612. if ((isConstant) && (!didConstToMem))
  10613. {
  10614. localVarDef->mDbgDeclareInst = mBfIRBuilder->DbgInsertValueIntrinsic(localVarDef->mConstValue, diVariable);
  10615. }
  10616. else
  10617. {
  10618. if ((IsTargetingBeefBackend()) && (doAliasValue))
  10619. {
  10620. diValue = mBfIRBuilder->CreateAliasValue(diValue);
  10621. mCurMethodState->mCurScope->mDeferredLifetimeEnds.Add(diValue);
  10622. }
  10623. if (isByAddr)
  10624. localVarDef->mDbgDeclareInst = mBfIRBuilder->DbgInsertDeclare(diValue, diVariable, declareBefore);
  10625. else if (diValue)
  10626. {
  10627. localVarDef->mDbgDeclareInst = mBfIRBuilder->DbgInsertValueIntrinsic(diValue, diVariable);
  10628. }
  10629. else if (mCompiler->mOptions.mToolsetType != BfToolsetType_GNU) // DWARF chokes on this:
  10630. localVarDef->mDbgDeclareInst = mBfIRBuilder->DbgInsertValueIntrinsic(BfIRValue(), diVariable);
  10631. }
  10632. }
  10633. }
  10634. }
  10635. localVarDef->mDeclBlock = mBfIRBuilder->GetInsertBlock();
  10636. DoAddLocalVariable(localVarDef);
  10637. auto rootMethodState = mCurMethodState->GetRootMethodState();
  10638. if (localVarDef->mLocalVarId == -1)
  10639. {
  10640. BF_ASSERT(rootMethodState->mCurLocalVarId >= 0);
  10641. localVarDef->mLocalVarId = rootMethodState->mCurLocalVarId++;
  10642. }
  10643. if ((localVarDef->mNameNode != NULL) && (mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL))
  10644. mCompiler->mResolvePassData->mAutoComplete->CheckLocalDef(localVarDef->mNameNode, localVarDef);
  10645. if ((localVarDef->mNameNode != NULL) && (mCurMethodInstance != NULL))
  10646. {
  10647. bool isClosureProcessing = (mCurMethodState->mClosureState != NULL) && (!mCurMethodState->mClosureState->mCapturing);
  10648. if ((!isClosureProcessing) && (mCompiler->mResolvePassData != NULL) && (localVarDef->mNameNode != NULL))
  10649. mCompiler->mResolvePassData->HandleLocalReference(localVarDef->mNameNode, rootMethodState->mMethodInstance->GetOwner()->mTypeDef, rootMethodState->mMethodInstance->mMethodDef, localVarDef->mLocalVarId);
  10650. }
  10651. return localVarDef;
  10652. }
  10653. void BfModule::CreateDIRetVal()
  10654. {
  10655. if (!WantsDebugInfo())
  10656. return;
  10657. /*if (!mCurMethodState->mRetVal)
  10658. {
  10659. if (mCurMethodInstance->mMethodDef->mName != "Ziggle")
  10660. return;
  10661. }*/
  10662. if ((mCurMethodState->mRetVal) || (mCurMethodState->mRetValAddr))
  10663. {
  10664. BfType* dbgType = mCurMethodInstance->mReturnType;
  10665. BfIRValue dbgValue = mCurMethodState->mRetVal.mValue;
  10666. if (mCurMethodInstance->HasStructRet())
  10667. {
  10668. BF_ASSERT(mCurMethodState->mRetValAddr);
  10669. dbgType = CreatePointerType(dbgType);
  10670. dbgValue = mCurMethodState->mRetValAddr;
  10671. }
  10672. else
  10673. {
  10674. BF_ASSERT(!mCurMethodState->mRetValAddr);
  10675. }
  10676. mCurMethodState->mDIRetVal = mBfIRBuilder->DbgCreateAutoVariable(mCurMethodState->mCurScope->mDIScope,
  10677. "__return", mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, mBfIRBuilder->DbgGetType(dbgType));
  10678. auto declareCall = mBfIRBuilder->DbgInsertDeclare(dbgValue, mCurMethodState->mDIRetVal);
  10679. }
  10680. }
  10681. void BfModule::CheckVariableDef(BfLocalVariable* variableDef)
  10682. {
  10683. BfLocalVarEntry* localVarEntryPtr = NULL;
  10684. if ((mCurMethodState != NULL) && (mCurMethodState->mLocalVarSet.TryGet(BfLocalVarEntry(variableDef), &localVarEntryPtr)))
  10685. {
  10686. auto checkLocal = localVarEntryPtr->mLocalVar;
  10687. if ((checkLocal->mLocalVarIdx >= mCurMethodState->GetLocalStartIdx()) && (!checkLocal->mIsShadow))
  10688. {
  10689. BfError* error;
  10690. if (checkLocal->mIsImplicitParam)
  10691. return; // Ignore 'redefinition'
  10692. if (checkLocal->IsParam())
  10693. error = Fail(StrFormat("A parameter named '%s' has already been declared.", variableDef->mName.c_str()), variableDef->mNameNode);
  10694. else if (checkLocal->mLocalVarIdx < mCurMethodState->mCurScope->mLocalVarStart)
  10695. error = Fail(StrFormat("A variable named '%s' has already been declared in this parent's scope.", variableDef->mName.c_str()), variableDef->mNameNode);
  10696. else
  10697. error = Fail(StrFormat("A variable named '%s' has already been declared in this scope.", variableDef->mName.c_str()), variableDef->mNameNode);
  10698. if ((checkLocal->mNameNode != NULL) && (error != NULL))
  10699. mCompiler->mPassInstance->MoreInfo("Previous declaration", checkLocal->mNameNode);
  10700. return;
  10701. }
  10702. }
  10703. }
  10704. BfScopeData* BfModule::FindScope(BfAstNode* scopeName, BfMixinState* fromMixinState, bool allowAcrossDeferredBlock)
  10705. {
  10706. bool inMixinDecl = (mCurMethodInstance != NULL) && (mCurMethodInstance->IsMixin());
  10707. if (auto tokenNode = BfNodeDynCast<BfTokenNode>(scopeName))
  10708. {
  10709. if (tokenNode->GetToken() == BfToken_Colon)
  10710. {
  10711. if ((!allowAcrossDeferredBlock) && (mCurMethodState->mInDeferredBlock))
  10712. {
  10713. Fail("Cannot access method scope across deferred block boundary", scopeName);
  10714. return NULL;
  10715. }
  10716. return &mCurMethodState->mHeadScope;
  10717. }
  10718. else if (tokenNode->GetToken() == BfToken_Mixin)
  10719. {
  10720. if (fromMixinState == NULL)
  10721. {
  10722. if (mCurMethodInstance->mMethodDef->mMethodType != BfMethodType_Mixin)
  10723. Fail("'mixin' scope specifier can only be used within a mixin declaration", scopeName);
  10724. return mCurMethodState->mCurScope;
  10725. }
  10726. fromMixinState->mUsedInvocationScope = true;
  10727. return fromMixinState->mTargetScope;
  10728. }
  10729. else if (tokenNode->GetToken() == BfToken_New)
  10730. return NULL;
  10731. }
  10732. if (auto identifier = BfNodeDynCast<BfIdentifierNode>(scopeName))
  10733. {
  10734. auto findLabel = scopeName->ToString();
  10735. bool crossedDeferredBlock = false;
  10736. auto checkScope = mCurMethodState->mCurScope;
  10737. while (checkScope != NULL)
  10738. {
  10739. if (checkScope->mIsDeferredBlock)
  10740. crossedDeferredBlock = true;
  10741. if (checkScope->mLabel == findLabel)
  10742. {
  10743. if ((crossedDeferredBlock) && (!allowAcrossDeferredBlock))
  10744. {
  10745. Fail(StrFormat("Cannot access scope '%s' across deferred block boundary", findLabel.c_str()), scopeName);
  10746. return NULL;
  10747. }
  10748. return checkScope;
  10749. }
  10750. checkScope = checkScope->mPrevScope;
  10751. }
  10752. if (!inMixinDecl)
  10753. Fail(StrFormat("Unable to locate label '%s'", findLabel.c_str()), scopeName);
  10754. }
  10755. if (auto scopeNode = BfNodeDynCast<BfScopeNode>(scopeName))
  10756. {
  10757. return FindScope(scopeNode->mTargetNode, allowAcrossDeferredBlock);
  10758. }
  10759. return mCurMethodState->mCurScope;
  10760. }
  10761. BfScopeData* BfModule::FindScope(BfAstNode* scopeName, bool allowAcrossDeferredBlock)
  10762. {
  10763. return FindScope(scopeName, mCurMethodState->mMixinState, allowAcrossDeferredBlock);
  10764. }
  10765. BfBreakData* BfModule::FindBreakData(BfAstNode* scopeName)
  10766. {
  10767. auto scopeData = FindScope(scopeName, false);
  10768. if (scopeData == NULL)
  10769. return NULL;
  10770. int scopeDepth = scopeData->GetDepth();
  10771. // Find the first break data that is at or below the depth of our requested scope
  10772. auto breakData = mCurMethodState->mBreakData;
  10773. while ((breakData != NULL) && (scopeDepth < breakData->mScope->GetDepth()))
  10774. {
  10775. if (breakData->mScope->mIsConditional)
  10776. return NULL;
  10777. breakData = breakData->mPrevBreakData;
  10778. }
  10779. return breakData;
  10780. }
  10781. void BfModule::EmitLifetimeEnds(BfScopeData* scopeData)
  10782. {
  10783. // LLVM is stricter about the placement of these (ie: they can't occur after a 'ret')
  10784. if (!IsTargetingBeefBackend())
  10785. return;
  10786. for (auto lifetimeEnd : scopeData->mDeferredLifetimeEnds)
  10787. {
  10788. mBfIRBuilder->CreateLifetimeEnd(lifetimeEnd);
  10789. }
  10790. }
  10791. void BfModule::ClearLifetimeEnds()
  10792. {
  10793. auto scopeData = mCurMethodState->mCurScope;
  10794. while (scopeData != NULL)
  10795. {
  10796. scopeData->mDeferredLifetimeEnds.Clear();
  10797. scopeData = scopeData->mPrevScope;
  10798. }
  10799. }
  10800. bool BfModule::WantsDebugInfo()
  10801. {
  10802. if ((mCurMethodInstance != NULL) &&
  10803. ((mCurMethodInstance->mIsUnspecialized) || (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_Mixin)))
  10804. return false;
  10805. return (mBfIRBuilder->DbgHasInfo()) && (mHasFullDebugInfo) &&
  10806. ((mCurMethodState == NULL) || (mCurMethodState->mClosureState == NULL) || (!mCurMethodState->mClosureState->mCapturing));
  10807. }
  10808. BfTypeOptions* BfModule::GetTypeOptions()
  10809. {
  10810. if ((mCurMethodState != NULL) && (mCurMethodState->mMethodTypeOptions != NULL))
  10811. return mCurMethodState->mMethodTypeOptions;
  10812. return mSystem->GetTypeOptions(mCurTypeInstance->mTypeOptionsIdx);
  10813. }
  10814. bool BfModule::HasDeferredScopeCalls(BfScopeData* scope)
  10815. {
  10816. BfScopeData* checkScope = mCurMethodState->mCurScope;
  10817. while (checkScope != NULL)
  10818. {
  10819. if ((!checkScope->mDeferredCallEntries.IsEmpty()) || (!checkScope->mDeferredLifetimeEnds.empty()))
  10820. return true;
  10821. if (checkScope == scope)
  10822. break;
  10823. checkScope = checkScope->mPrevScope;
  10824. }
  10825. return false;
  10826. }
  10827. void BfModule::EmitDeferredScopeCalls(bool useSrcPositions, BfScopeData* scopeData, BfIRBlock doneBlock)
  10828. {
  10829. // Is there anything we need to do here?
  10830. if (mBfIRBuilder->mIgnoreWrites)
  10831. {
  10832. // Just visit deferred blocks
  10833. BfScopeData* checkScope = mCurMethodState->mCurScope;
  10834. while (checkScope != NULL)
  10835. {
  10836. BfDeferredCallEntry* deferredCallEntry = checkScope->mDeferredCallEntries.mHead;
  10837. while (deferredCallEntry != NULL)
  10838. {
  10839. if (deferredCallEntry->mDeferredBlock != NULL)
  10840. {
  10841. VisitEmbeddedStatement(deferredCallEntry->mDeferredBlock, NULL, BfEmbeddedStatementFlags_IsDeferredBlock);
  10842. }
  10843. deferredCallEntry = deferredCallEntry->mNext;
  10844. }
  10845. if (checkScope == scopeData)
  10846. break;
  10847. checkScope = checkScope->mPrevScope;
  10848. }
  10849. return;
  10850. }
  10851. // Why did we want to do SetIllegalSrcPos here?
  10852. // Don't we always want to step onto these instances?
  10853. // Find a case where we don't and perhaps only do it there.
  10854. // The downside was that 'EmitEnsureInstructionAt' on the end of block statements causes
  10855. // a (seemingly) unneeded NOP when we do SetIllegalSrcPos
  10856. //SetIllegalSrcPos();
  10857. bool setSrcPos = false;
  10858. bool wantsNop = true;
  10859. BfAstNode* deferCloseNode = NULL;
  10860. if (mCurMethodState->mInPostReturn)
  10861. {
  10862. // These won't get used, they are post-return
  10863. return;
  10864. }
  10865. SizedArray<BfIRValue, 8> deferredLifetimeEnds;
  10866. BfScopeData* scopeJumpBlock = NULL;
  10867. bool hadExtraDeferredLifetimeEnds = false;
  10868. auto _FlushLifetimeEnds = [&]()
  10869. {
  10870. for (auto lifetimeEnd : deferredLifetimeEnds)
  10871. {
  10872. mBfIRBuilder->CreateLifetimeEnd(lifetimeEnd);
  10873. mBfIRBuilder->ClearDebugLocation_Last();
  10874. }
  10875. deferredLifetimeEnds.clear();
  10876. };
  10877. BfScopeData* checkScope = mCurMethodState->mCurScope;
  10878. while (checkScope != NULL)
  10879. {
  10880. if (checkScope->mCloseNode != NULL)
  10881. deferCloseNode = checkScope->mCloseNode;
  10882. if (doneBlock)
  10883. {
  10884. // Try to find a match where we've already emitted these calls and then jumped to the correct block
  10885. for (auto& checkHandler : checkScope->mDeferredHandlers)
  10886. {
  10887. if (checkHandler.mDoneBlock == doneBlock)
  10888. {
  10889. scopeJumpBlock = checkScope;
  10890. mBfIRBuilder->CreateBr(checkHandler.mHandlerBlock);
  10891. mBfIRBuilder->ClearDebugLocation_Last();
  10892. _FlushLifetimeEnds();
  10893. break;
  10894. }
  10895. }
  10896. if (scopeJumpBlock != NULL)
  10897. break;
  10898. }
  10899. bool hasWork = (checkScope->mSavedStack) || (checkScope->mDeferredCallEntries.mHead != NULL);
  10900. if (checkScope != scopeData) // Only emit a block for deferred lifetimes if we're going back beyond this entry
  10901. hasWork |= (!deferredLifetimeEnds.IsEmpty());
  10902. if (hasWork)
  10903. {
  10904. SetAndRestoreValue<BfScopeData*> prevScope(mCurMethodState->mCurScope, checkScope);
  10905. if (deferCloseNode != NULL)
  10906. {
  10907. UpdateSrcPos(deferCloseNode);
  10908. }
  10909. if (doneBlock)
  10910. {
  10911. bool crossingMixin = mCurMethodState->mCurScope->mMixinDepth != checkScope->mMixinDepth;
  10912. String blockName = "deferredCalls";
  10913. //blockName += StrFormat("_%d", mBfIRBuilder->mBlockCount);
  10914. BfDeferredHandler deferredHandler;
  10915. if ((!crossingMixin) && (deferredLifetimeEnds.IsEmpty()))
  10916. {
  10917. mBfIRBuilder->SaveDebugLocation();
  10918. mBfIRBuilder->ClearDebugLocation();
  10919. deferredHandler.mHandlerBlock = mBfIRBuilder->MaybeChainNewBlock(blockName);
  10920. mBfIRBuilder->RestoreDebugLocation();
  10921. }
  10922. else
  10923. {
  10924. // Definitely chain
  10925. deferredHandler.mHandlerBlock = mBfIRBuilder->CreateBlock(blockName);
  10926. mBfIRBuilder->CreateBr(deferredHandler.mHandlerBlock);
  10927. mBfIRBuilder->ClearDebugLocation_Last();
  10928. _FlushLifetimeEnds();
  10929. mBfIRBuilder->AddBlock(deferredHandler.mHandlerBlock);
  10930. mBfIRBuilder->SetInsertPoint(deferredHandler.mHandlerBlock);
  10931. }
  10932. deferredHandler.mDoneBlock = doneBlock;
  10933. if (!mBfIRBuilder->mIgnoreWrites)
  10934. checkScope->mDeferredHandlers.push_back(deferredHandler);
  10935. if (checkScope == &mCurMethodState->mHeadScope)
  10936. {
  10937. if (!mCurMethodState->mDIRetVal)
  10938. {
  10939. // 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
  10940. // be scoped to the physical method
  10941. /*if (deferCloseNode != NULL)
  10942. {
  10943. UpdateSrcPos(deferCloseNode);
  10944. }*/
  10945. CreateDIRetVal();
  10946. }
  10947. }
  10948. if (checkScope != mCurMethodState->mTailScope)
  10949. {
  10950. if (deferredHandler.mHandlerBlock.IsFake())
  10951. {
  10952. BF_ASSERT(mBfIRBuilder->mIgnoreWrites);
  10953. }
  10954. if (!mBfIRBuilder->mIgnoreWrites)
  10955. checkScope->mAtEndBlocks.push_back(deferredHandler.mHandlerBlock);
  10956. }
  10957. }
  10958. std::unordered_set<BfDeferredCallEntry*> handledSet;
  10959. BfDeferredCallEntry* deferredCallEntry = checkScope->mDeferredCallEntries.mHead;
  10960. while (deferredCallEntry != NULL)
  10961. {
  10962. BfDeferredCallEmitState deferredCallEmitState;
  10963. deferredCallEmitState.mCloseNode = deferCloseNode;
  10964. SetAndRestoreValue<BfDeferredCallEmitState*> prevDeferredCallEmitState(mCurMethodState->mDeferredCallEmitState, &deferredCallEmitState);
  10965. SetAndRestoreValue<bool> prevIgnoredWrites(mBfIRBuilder->mIgnoreWrites, deferredCallEntry->mIgnored);
  10966. if (deferCloseNode != NULL)
  10967. {
  10968. UpdateSrcPos(deferCloseNode);
  10969. }
  10970. if (wantsNop)
  10971. EmitEnsureInstructionAt();
  10972. wantsNop = false;
  10973. if (deferredCallEntry->mDeferredBlock != NULL)
  10974. {
  10975. auto itr = handledSet.insert(deferredCallEntry);
  10976. if (!itr.second)
  10977. {
  10978. // Already handled, can happen if we defer again within the block
  10979. deferredCallEntry = deferredCallEntry->mNext;
  10980. continue;
  10981. }
  10982. auto prevHead = checkScope->mDeferredCallEntries.mHead;
  10983. EmitDeferredCall(*deferredCallEntry);
  10984. if (prevHead != checkScope->mDeferredCallEntries.mHead)
  10985. {
  10986. // The list changed, start over and ignore anything we've already handled
  10987. deferredCallEntry = checkScope->mDeferredCallEntries.mHead;
  10988. }
  10989. else
  10990. deferredCallEntry = deferredCallEntry->mNext;
  10991. }
  10992. else
  10993. {
  10994. EmitDeferredCall(*deferredCallEntry);
  10995. deferredCallEntry = deferredCallEntry->mNext;
  10996. }
  10997. }
  10998. if (checkScope->mSavedStack)
  10999. {
  11000. checkScope->mSavedStackUses.Add(mBfIRBuilder->CreateStackRestore(checkScope->mSavedStack));
  11001. if (mCurMethodState->mDynStackRevIdx)
  11002. {
  11003. auto curValue = mBfIRBuilder->CreateLoad(mCurMethodState->mDynStackRevIdx);
  11004. auto newValue = mBfIRBuilder->CreateAdd(curValue, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 1));
  11005. mBfIRBuilder->CreateStore(newValue, mCurMethodState->mDynStackRevIdx);
  11006. }
  11007. }
  11008. }
  11009. if (!checkScope->mIsScopeHead)
  11010. {
  11011. // We manually emit function-level lifetime ends after the 'ret' in ProcessMethod
  11012. if (!IsTargetingBeefBackend())
  11013. {
  11014. for (auto lifetimeEnd : checkScope->mDeferredLifetimeEnds)
  11015. {
  11016. mBfIRBuilder->CreateLifetimeEnd(lifetimeEnd);
  11017. }
  11018. }
  11019. else
  11020. {
  11021. for (auto lifetimeEnd : checkScope->mDeferredLifetimeEnds)
  11022. {
  11023. deferredLifetimeEnds.Add(lifetimeEnd);
  11024. }
  11025. }
  11026. }
  11027. if (checkScope == scopeData)
  11028. break;
  11029. checkScope = checkScope->mPrevScope;
  11030. }
  11031. if ((doneBlock) && (scopeJumpBlock == NULL))
  11032. {
  11033. mBfIRBuilder->CreateBr(doneBlock);
  11034. mBfIRBuilder->ClearDebugLocation_Last();
  11035. }
  11036. // Keeping CreateLifetimeEnds until the end messes up when we chain to old mDeferredHandlers that
  11037. // may have been created when other scope lifetimes were available
  11038. _FlushLifetimeEnds();
  11039. // Emit lifetimeEnds after the branch for Beef
  11040. /*if (IsTargetingBeefBackend())
  11041. {
  11042. bool needsEnsureInst = (!doneBlock) && (scopeJumpBlock == NULL);
  11043. BfScopeData* checkScope = mCurMethodState->mCurScope;
  11044. while (checkScope != NULL)
  11045. {
  11046. if (checkScope == scopeJumpBlock)
  11047. break;
  11048. if (!checkScope->mIsScopeHead)
  11049. {
  11050. for (auto lifetimeEnd : checkScope->mDeferredLifetimeEnds)
  11051. {
  11052. if (needsEnsureInst)
  11053. {
  11054. needsEnsureInst = false;
  11055. }
  11056. mBfIRBuilder->CreateLifetimeEnd(lifetimeEnd);
  11057. }
  11058. }
  11059. if (checkScope == scopeData)
  11060. break;
  11061. checkScope = checkScope->mPrevScope;
  11062. }
  11063. }*/
  11064. }
  11065. void BfModule::MarkScopeLeft(BfScopeData* scopeData)
  11066. {
  11067. if (mCurMethodState->mDeferredLocalAssignData != NULL)
  11068. {
  11069. auto deferredLocalAssignData = mCurMethodState->mDeferredLocalAssignData;
  11070. while (deferredLocalAssignData != NULL)
  11071. {
  11072. if ((deferredLocalAssignData->mScopeData == NULL) || (deferredLocalAssignData->mScopeData->mScopeDepth < scopeData->mScopeDepth))
  11073. break;
  11074. if ((deferredLocalAssignData->mScopeData != NULL) && (deferredLocalAssignData->mScopeData->mScopeDepth == scopeData->mScopeDepth))
  11075. deferredLocalAssignData->mIsUnconditional = false;
  11076. deferredLocalAssignData = deferredLocalAssignData->mChainedAssignData;
  11077. }
  11078. }
  11079. //for (int localIdx = scopeData->mLocalVarStart; localIdx < (int)mCurMethodState->mLocals.size(); localIdx++)
  11080. // We mark all unassigned variables as assigned now, for avoiding "may be unassigned" usage cases like:
  11081. // int b;
  11082. // if (cond) return;
  11083. // else b = 1;
  11084. // Use(b);
  11085. for (int localIdx = 0; localIdx < (int)mCurMethodState->mLocals.size(); localIdx++)
  11086. {
  11087. auto localDef = mCurMethodState->mLocals[localIdx];
  11088. if ((!localDef->mIsAssigned) && (!localDef->IsParam()))
  11089. mCurMethodState->LocalDefined(localDef);
  11090. }
  11091. }
  11092. void BfModule::CreateReturn(BfIRValue val)
  11093. {
  11094. if (mCurMethodInstance->mReturnType->IsComposite())
  11095. {
  11096. // Store to sret
  11097. BF_ASSERT(val);
  11098. mBfIRBuilder->CreateStore(val, mBfIRBuilder->GetArgument(0));
  11099. mBfIRBuilder->CreateRetVoid();
  11100. }
  11101. else
  11102. {
  11103. if (mCurMethodInstance->mReturnType->IsValuelessType())
  11104. {
  11105. mBfIRBuilder->CreateRetVoid();
  11106. }
  11107. else
  11108. {
  11109. BF_ASSERT(val);
  11110. mBfIRBuilder->CreateRet(val);
  11111. }
  11112. }
  11113. }
  11114. void BfModule::EmitReturn(BfIRValue val)
  11115. {
  11116. if (mCurMethodState->mIRExitBlock)
  11117. {
  11118. if (!mCurMethodInstance->mReturnType->IsValuelessType())
  11119. {
  11120. if (val) // We allow for val to be empty if we know we've already written the value to mRetVal
  11121. {
  11122. BfIRValue retVal = mCurMethodState->mRetVal.mValue;
  11123. if (!mCurMethodState->mRetVal)
  11124. retVal = mBfIRBuilder->CreateLoad(mCurMethodState->mRetValAddr);
  11125. mBfIRBuilder->CreateStore(val, retVal);
  11126. }
  11127. }
  11128. EmitDeferredScopeCalls(true, NULL, mCurMethodState->mIRExitBlock);
  11129. }
  11130. else
  11131. {
  11132. EmitDeferredScopeCalls(false, NULL);
  11133. if (mCurMethodInstance->mReturnType->IsValuelessType())
  11134. mBfIRBuilder->CreateRetVoid();
  11135. else
  11136. mBfIRBuilder->CreateRet(val);
  11137. }
  11138. mCurMethodState->SetHadReturn(true);
  11139. mCurMethodState->mLeftBlockUncond = true;
  11140. }
  11141. void BfModule::EmitDefaultReturn()
  11142. {
  11143. if (mCurMethodState->mInDeferredBlock)
  11144. return;
  11145. if (mCurMethodState->mIRExitBlock)
  11146. {
  11147. EmitDeferredScopeCalls(true, NULL, mCurMethodState->mIRExitBlock);
  11148. }
  11149. else
  11150. {
  11151. if (mCurMethodInstance->mReturnType->IsVoid())
  11152. mBfIRBuilder->CreateRetVoid();
  11153. else
  11154. mBfIRBuilder->CreateRet(GetDefaultValue(mCurMethodInstance->mReturnType));
  11155. }
  11156. mCurMethodState->SetHadReturn(true);
  11157. mCurMethodState->mLeftBlockUncond = true;
  11158. }
  11159. void BfModule::AssertErrorState()
  11160. {
  11161. if (mIgnoreErrors)
  11162. return;
  11163. if (mHadBuildError)
  11164. return;
  11165. if (mCurTypeInstance != NULL)
  11166. {
  11167. if (mCurTypeInstance->IsUnspecializedTypeVariation())
  11168. return;
  11169. }
  11170. if (mCurMethodInstance != NULL)
  11171. {
  11172. if (mCurMethodInstance->mIsUnspecializedVariation)
  11173. return;
  11174. }
  11175. // We want the module to be marked as failed even if it's just an error in the parser
  11176. if (mCurMethodInstance != NULL)
  11177. mCurMethodInstance->mHasFailed = true;
  11178. mHadBuildError = true;
  11179. // We check for either the parsing to have failed (possibly on a previous run), or for the current instance to have failed
  11180. if (mCurTypeInstance != NULL)
  11181. {
  11182. if (mCurTypeInstance->mTypeFailed)
  11183. return;
  11184. if (mCurTypeInstance->mTypeDef->mSource->mParsingFailed)
  11185. return;
  11186. }
  11187. if (mCurMethodInstance != NULL)
  11188. {
  11189. if ((mCurMethodInstance->mMethodDef->mDeclaringType != NULL) && (mCurMethodInstance->mMethodDef->mDeclaringType->mSource->mParsingFailed))
  11190. return;
  11191. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL) && (mCurMethodState->mMixinState->mMixinMethodInstance->mMethodDef->mDeclaringType->mSource->mParsingFailed))
  11192. return;
  11193. }
  11194. BF_ASSERT(mCompiler->mPassInstance->HasFailed());
  11195. }
  11196. void BfModule::AssertParseErrorState()
  11197. {
  11198. if (mCompiler->mRevision == 1)
  11199. AssertErrorState();
  11200. }
  11201. BfType* BfModule::GetDelegateReturnType(BfType* delegateType)
  11202. {
  11203. BF_ASSERT(delegateType->IsDelegate());
  11204. auto typeInst = delegateType->ToTypeInstance();
  11205. PopulateType(typeInst, BfPopulateType_DataAndMethods);
  11206. BfMethodInstance* invokeMethodInstance = GetRawMethodInstanceAtIdx(typeInst->ToTypeInstance(), 0, "Invoke");
  11207. return invokeMethodInstance->mReturnType;
  11208. }
  11209. BfMethodInstance* BfModule::GetDelegateInvokeMethod(BfTypeInstance* typeInstance)
  11210. {
  11211. return GetRawMethodInstanceAtIdx(typeInstance, 0, "Invoke");
  11212. }
  11213. void BfModule::CreateDelegateInvokeMethod()
  11214. {
  11215. // Clear out debug loc - otherwise we'll single step onto the delegate type declaration
  11216. //mBfIRBuilder->ClearDebugLocation();
  11217. SetIllegalSrcPos();
  11218. auto typeInstance = mCurTypeInstance;
  11219. auto memberFuncType = mBfIRBuilder->MapMethod(mCurMethodInstance);
  11220. SizedArray<BfIRType, 4> staticParamTypes;
  11221. SizedArray<BfIRValue, 4> staticFuncArgs;
  11222. SizedArray<BfIRValue, 4> memberFuncArgs;
  11223. auto multicastDelegateType = typeInstance->mBaseType;
  11224. if (multicastDelegateType->mFieldInstances.size() != 2)
  11225. {
  11226. AssertErrorState();
  11227. return;
  11228. }
  11229. auto multicastDelegate = mBfIRBuilder->CreateBitCast(mCurMethodState->mLocals[0]->mValue, mBfIRBuilder->MapType(multicastDelegateType));
  11230. auto fieldPtr = mBfIRBuilder->CreateInBoundsGEP(multicastDelegate, 0, 2); // Load 'delegate.mTarget'
  11231. auto fieldVal = mBfIRBuilder->CreateLoad(fieldPtr);
  11232. BfExprEvaluator exprEvaluator(this);
  11233. SizedArray<BfIRType, 8> origParamTypes;
  11234. BfIRType origReturnType;
  11235. mCurMethodInstance->GetIRFunctionInfo(this, origReturnType, origParamTypes);
  11236. if (mCurMethodInstance->mReturnType->IsValueType())
  11237. mBfIRBuilder->PopulateType(mCurMethodInstance->mReturnType, BfIRPopulateType_Full);
  11238. int thisIdx = 0;
  11239. if (mCurMethodInstance->HasStructRet())
  11240. {
  11241. thisIdx = 1;
  11242. staticFuncArgs.push_back(mBfIRBuilder->GetArgument(0));
  11243. memberFuncArgs.push_back(mBfIRBuilder->GetArgument(0));
  11244. }
  11245. memberFuncArgs.push_back(BfIRValue()); // Push 'target'
  11246. mCurMethodInstance->GetIRFunctionInfo(this, origReturnType, staticParamTypes, true);
  11247. for (int i = 1; i < (int)mCurMethodState->mLocals.size(); i++)
  11248. {
  11249. BfTypedValue localVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[i], true);
  11250. exprEvaluator.PushArg(localVal, staticFuncArgs);
  11251. exprEvaluator.PushArg(localVal, memberFuncArgs);
  11252. }
  11253. auto staticFunc = mBfIRBuilder->CreateFunctionType(origReturnType, staticParamTypes, false);
  11254. auto staticFuncPtr = mBfIRBuilder->GetPointerTo(staticFunc);
  11255. auto staticFuncPtrPtr = mBfIRBuilder->GetPointerTo(staticFuncPtr);
  11256. auto trueBB = mBfIRBuilder->CreateBlock("if.then", true);
  11257. auto falseBB = mBfIRBuilder->CreateBlock("if.else");
  11258. auto doneBB = mBfIRBuilder->CreateBlock("done");
  11259. auto checkTargetNull = mBfIRBuilder->CreateIsNotNull(fieldVal);
  11260. mBfIRBuilder->CreateCondBr(checkTargetNull, trueBB, falseBB);
  11261. BfIRValue nonStaticResult;
  11262. BfIRValue staticResult;
  11263. auto callingConv = GetIRCallingConvention(mCurTypeInstance, mCurMethodInstance->mMethodDef);
  11264. /// Non-static invocation
  11265. {
  11266. auto memberFuncPtr = mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapMethod(mCurMethodInstance));
  11267. auto memberFuncPtrPtr = mBfIRBuilder->GetPointerTo(memberFuncPtr);
  11268. mBfIRBuilder->SetInsertPoint(trueBB);
  11269. memberFuncArgs[thisIdx] = mBfIRBuilder->CreateBitCast(fieldVal, mBfIRBuilder->MapType(mCurTypeInstance));
  11270. auto fieldPtr = mBfIRBuilder->CreateInBoundsGEP(multicastDelegate, 0, 1); // Load 'delegate.mFuncPtr'
  11271. auto funcPtrPtr = mBfIRBuilder->CreateBitCast(fieldPtr, memberFuncPtrPtr);
  11272. auto funcPtr = mBfIRBuilder->CreateLoad(funcPtrPtr);
  11273. nonStaticResult = mBfIRBuilder->CreateCall(funcPtr, memberFuncArgs);
  11274. if (callingConv != BfIRCallingConv_CDecl)
  11275. mBfIRBuilder->SetCallCallingConv(nonStaticResult, callingConv);
  11276. mCurMethodState->SetHadReturn(false);
  11277. mCurMethodState->mLeftBlockUncond = false;
  11278. mCurMethodState->mLeftBlockCond = false;
  11279. mBfIRBuilder->CreateBr(doneBB);
  11280. }
  11281. // Static invocation
  11282. {
  11283. mBfIRBuilder->AddBlock(falseBB);
  11284. mBfIRBuilder->SetInsertPoint(falseBB);
  11285. auto fieldPtr = mBfIRBuilder->CreateInBoundsGEP(multicastDelegate, 0, 1); // Load 'delegate.mFuncPtr'
  11286. auto funcPtrPtr = mBfIRBuilder->CreateBitCast(fieldPtr, staticFuncPtrPtr);
  11287. auto funcPtr = mBfIRBuilder->CreateLoad(funcPtrPtr);
  11288. staticResult = mBfIRBuilder->CreateCall(funcPtr, staticFuncArgs);
  11289. if (callingConv == BfIRCallingConv_ThisCall)
  11290. callingConv = BfIRCallingConv_CDecl;
  11291. if (callingConv != BfIRCallingConv_CDecl)
  11292. mBfIRBuilder->SetCallCallingConv(staticResult, callingConv);
  11293. // if (!mSystem->IsCompatibleCallingConvention(BfCallingConvention_Unspecified, mCurMethodInstance->mMethodDef->mCallingConvention))
  11294. // {
  11295. // if (mCurMethodInstance->mMethodDef->mCallingConvention == BfCallingConvention_Stdcall)
  11296. //
  11297. // }
  11298. mCurMethodState->SetHadReturn(false);
  11299. mCurMethodState->mLeftBlockUncond = false;
  11300. mCurMethodState->mLeftBlockCond = false;
  11301. mBfIRBuilder->CreateBr(doneBB);
  11302. }
  11303. mBfIRBuilder->AddBlock(doneBB);
  11304. mBfIRBuilder->SetInsertPoint(doneBB);
  11305. if ((mCurMethodInstance->mReturnType->IsValuelessType()) || (mCurMethodInstance->HasStructRet()))
  11306. {
  11307. mBfIRBuilder->CreateRetVoid();
  11308. }
  11309. else
  11310. {
  11311. auto phi = mBfIRBuilder->CreatePhi(mBfIRBuilder->MapType(mCurMethodInstance->mReturnType), 2);
  11312. mBfIRBuilder->AddPhiIncoming(phi, nonStaticResult, trueBB);
  11313. mBfIRBuilder->AddPhiIncoming(phi, staticResult, falseBB);
  11314. mBfIRBuilder->CreateRet(phi);
  11315. }
  11316. }
  11317. // "Interested" here means every method for a normal compile, and just the method the cursor is on for autocompletion
  11318. bool BfModule::IsInterestedInMethod(BfTypeInstance* typeInstance, BfMethodDef* methodDef)
  11319. {
  11320. auto typeDef = typeInstance->mTypeDef;
  11321. auto methodDeclaration = methodDef->mMethodDeclaration;
  11322. if (!mCompiler->mIsResolveOnly)
  11323. return true;
  11324. if (typeInstance->IsGenericTypeInstance())
  11325. {
  11326. // We only really want to process the unspecialized type for autocompletion
  11327. if ((!typeInstance->IsUnspecializedType()) || (typeInstance->IsUnspecializedTypeVariation()))
  11328. return false;
  11329. }
  11330. BfAstNode* checkNode = methodDeclaration;
  11331. if (methodDeclaration == NULL)
  11332. checkNode = methodDef->mBody;
  11333. if ((mCompiler->mResolvePassData->mParser != NULL) && (typeDef->mTypeDeclaration->IsFromParser(mCompiler->mResolvePassData->mParser)))
  11334. {
  11335. if (mCompiler->mResolvePassData->mAutoComplete == NULL)
  11336. return true;
  11337. }
  11338. return false;
  11339. }
  11340. void BfModule::CalcAppendAlign(BfMethodInstance* methodInst)
  11341. {
  11342. methodInst->mAppendAllocAlign = 1;
  11343. }
  11344. BfTypedValue BfModule::TryConstCalcAppend(BfMethodInstance* methodInst, SizedArrayImpl<BfIRValue>& args)
  11345. {
  11346. BP_ZONE("BfModule::TryConstCalcAppend");
  11347. if (mCompiler->mIsResolveOnly)
  11348. return BfTypedValue();
  11349. // We want to regenerate all ctor calls when the method internals change
  11350. {
  11351. auto checkTypeInst = methodInst->GetOwner();
  11352. while (checkTypeInst->mTypeDef->mHasAppendCtor)
  11353. {
  11354. AddDependency(checkTypeInst, mCurTypeInstance, BfDependencyMap::DependencyFlag_InlinedCall);
  11355. checkTypeInst = GetBaseType(checkTypeInst);
  11356. }
  11357. }
  11358. if (!methodInst->mMayBeConst)
  11359. return BfTypedValue();
  11360. // Do we need to iterate in order to resolve mAppendAllocAlign?
  11361. bool isFirstRun = methodInst->mAppendAllocAlign < 0;
  11362. bool wasAllConst = true;
  11363. int argIdx = 0;
  11364. int paramIdx = 0;
  11365. while (true)
  11366. {
  11367. if (argIdx >= (int)args.size())
  11368. break;
  11369. auto paramType = methodInst->GetParamType(paramIdx);
  11370. PopulateType(paramType);
  11371. int argCount = 0;
  11372. if (!paramType->IsValuelessType())
  11373. {
  11374. if (methodInst->GetParamIsSplat(paramIdx))
  11375. argCount = paramType->GetSplatCount();
  11376. else
  11377. argCount = 1;
  11378. for (int argOfs = 0; argOfs < argCount; argOfs++)
  11379. {
  11380. auto arg = args[argIdx + argOfs];
  11381. if (!arg.IsConst())
  11382. {
  11383. wasAllConst = false;
  11384. if (!isFirstRun)
  11385. {
  11386. auto& param = methodInst->mParams[argIdx];
  11387. if (param.mReferencedInConstPass)
  11388. {
  11389. // If this param is required as part of the const calculation then
  11390. // we require that it be const...
  11391. return BfTypedValue();
  11392. }
  11393. }
  11394. }
  11395. }
  11396. }
  11397. paramIdx++;
  11398. argIdx += argCount;
  11399. }
  11400. auto methodDef = methodInst->mMethodDef;
  11401. auto methodDecl = methodDef->GetMethodDeclaration();
  11402. auto methodDeclBlock = BfNodeDynCast<BfBlock>(methodDecl->mBody);
  11403. if (methodDeclBlock == NULL)
  11404. return BfTypedValue();
  11405. BfTypedValue constValue;
  11406. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  11407. auto checkState = mCurMethodState->mConstResolveState;
  11408. while (checkState != NULL)
  11409. {
  11410. if (checkState->mMethodInstance == methodInst)
  11411. {
  11412. return BfTypedValue();
  11413. }
  11414. checkState = checkState->mPrevConstResolveState;
  11415. }
  11416. //auto accumValue = GetConstValue(0);
  11417. bool failed = false;
  11418. //
  11419. {
  11420. BfConstResolveState constResolveState;
  11421. constResolveState.mMethodInstance = methodInst;
  11422. constResolveState.mPrevConstResolveState = mCurMethodState->mConstResolveState;
  11423. SetAndRestoreValue<bool> ignoreWrites(mBfIRBuilder->mIgnoreWrites, true);
  11424. BfMethodState methodState;
  11425. SetAndRestoreValue<BfTypeInstance*> prevTypeInst(mCurTypeInstance, methodInst->GetOwner());
  11426. SetAndRestoreValue<BfMethodInstance*> prevMethodInst(mCurMethodInstance, methodInst);
  11427. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  11428. methodState.mTempKind = BfMethodState::TempKind_NonStatic;
  11429. methodState.mConstResolveState = &constResolveState;
  11430. int argIdx = 0;
  11431. for (int paramIdx = 0; paramIdx < methodInst->GetParamCount(); paramIdx++)
  11432. {
  11433. if (methodInst->GetParamKind(paramIdx) == BfParamKind_AppendIdx)
  11434. continue;
  11435. auto paramType = methodInst->GetParamType(paramIdx);
  11436. // Fix this after we allow structs to be consts
  11437. //BF_ASSERT(!paramType->IsSplattable());
  11438. BfLocalVariable* localVar = new BfLocalVariable();
  11439. localVar->mName = methodInst->GetParamName(paramIdx);
  11440. localVar->mResolvedType = paramType;
  11441. localVar->mConstValue = args[argIdx];
  11442. localVar->mParamIdx = paramIdx;
  11443. AddLocalVariableDef(localVar);
  11444. argIdx++;
  11445. }
  11446. AppendAllocVisitor appendAllocVisitor;
  11447. appendAllocVisitor.mConstAccum = GetDefaultTypedValue(GetPrimitiveType(BfTypeCode_IntPtr));
  11448. appendAllocVisitor.mIsFirstConstPass = isFirstRun;
  11449. BfTypedValue baseCtorAppendValue = CallBaseCtorCalc(true);
  11450. if (baseCtorAppendValue)
  11451. {
  11452. if (baseCtorAppendValue.mValue.IsFake())
  11453. appendAllocVisitor.mFailed = true;
  11454. else
  11455. appendAllocVisitor.mConstAccum = baseCtorAppendValue;
  11456. }
  11457. appendAllocVisitor.mModule = this;
  11458. appendAllocVisitor.VisitChild(methodDecl->mBody);
  11459. if (!appendAllocVisitor.mFailed)
  11460. constValue = appendAllocVisitor.mConstAccum;
  11461. if (isFirstRun)
  11462. mCurMethodInstance->mEndingAppendAllocAlign = appendAllocVisitor.mCurAppendAlign;
  11463. if (isFirstRun)
  11464. {
  11465. for (int paramIdx = 0; paramIdx < methodInst->GetParamCount(); paramIdx++)
  11466. {
  11467. auto localVar = mCurMethodState->mLocals[paramIdx];
  11468. if (localVar->mReadFromId != -1)
  11469. {
  11470. auto& param = methodInst->mParams[paramIdx];
  11471. param.mReferencedInConstPass = true;
  11472. }
  11473. }
  11474. }
  11475. }
  11476. mBfIRBuilder->SetInsertPoint(prevBlock);
  11477. if (!constValue)
  11478. {
  11479. // If we did a 'force' then some params may not have been const -- only clear mMayBeConst if we had
  11480. // all-const args
  11481. if (wasAllConst)
  11482. {
  11483. methodInst->mMayBeConst = false;
  11484. }
  11485. }
  11486. return constValue;
  11487. }
  11488. BfTypedValue BfModule::CallBaseCtorCalc(bool constOnly)
  11489. {
  11490. // Any errors should only be shown in the actual CTOR call
  11491. SetAndRestoreValue<bool> prevIgnoreWrites(mIgnoreErrors, true);
  11492. auto methodDef = mCurMethodInstance->mMethodDef;
  11493. BF_ASSERT((methodDef->mMethodType == BfMethodType_Ctor) || (methodDef->mMethodType == BfMethodType_CtorCalcAppend));
  11494. auto ctorDeclaration = (BfConstructorDeclaration*)methodDef->mMethodDeclaration;
  11495. BfTypeInstance* targetType = NULL;
  11496. if (ctorDeclaration->mInitializer != NULL)
  11497. {
  11498. auto targetToken = BfNodeDynCast<BfTokenNode>(ctorDeclaration->mInitializer->mTarget);
  11499. targetType = (targetToken->GetToken() == BfToken_This) ? mCurTypeInstance : mCurTypeInstance->mBaseType;
  11500. }
  11501. else
  11502. targetType = mCurTypeInstance->mBaseType;
  11503. if ((targetType == NULL) || (targetType == mContext->mBfObjectType))
  11504. return NULL;
  11505. auto targetRefNode = methodDef->GetRefNode();
  11506. BfType* targetThisType = targetType;
  11507. BfTypedValue target(mBfIRBuilder->GetFakeVal(), targetThisType);
  11508. BfExprEvaluator exprEvaluator(this);
  11509. BfResolvedArgs argValues;
  11510. if ((ctorDeclaration != NULL) && (ctorDeclaration->mInitializer != NULL))
  11511. {
  11512. argValues.Init(&ctorDeclaration->mInitializer->mArguments);
  11513. }
  11514. //
  11515. {
  11516. }
  11517. BfFunctionBindResult bindResult;
  11518. bindResult.mSkipThis = true;
  11519. bindResult.mWantsArgs = true;
  11520. {
  11521. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, true);
  11522. exprEvaluator.ResolveArgValues(argValues, BfResolveArgFlag_DeferParamEval);
  11523. SetAndRestoreValue<BfFunctionBindResult*> prevBindResult(exprEvaluator.mFunctionBindResult, &bindResult);
  11524. exprEvaluator.MatchConstructor(targetRefNode, NULL, target, targetType, argValues, true, true);
  11525. }
  11526. if (bindResult.mMethodInstance == NULL)
  11527. {
  11528. AssertErrorState();
  11529. return BfTypedValue();
  11530. }
  11531. if (!bindResult.mMethodInstance->mMethodDef->mHasAppend)
  11532. {
  11533. return BfTypedValue();
  11534. }
  11535. BF_ASSERT(bindResult.mIRArgs[0].IsFake());
  11536. bindResult.mIRArgs.RemoveAt(0);
  11537. auto calcAppendMethodModule = GetMethodInstanceAtIdx(bindResult.mMethodInstance->GetOwner(), bindResult.mMethodInstance->mMethodDef->mIdx + 1, BF_METHODNAME_CALCAPPEND);
  11538. BfTypedValue appendSizeTypedValue = TryConstCalcAppend(calcAppendMethodModule.mMethodInstance, bindResult.mIRArgs);
  11539. BF_ASSERT(calcAppendMethodModule.mMethodInstance->mAppendAllocAlign >= 0);
  11540. mCurMethodInstance->mAppendAllocAlign = BF_MAX((int)mCurMethodInstance->mAppendAllocAlign, calcAppendMethodModule.mMethodInstance->mAppendAllocAlign);
  11541. BF_ASSERT(calcAppendMethodModule.mMethodInstance->mEndingAppendAllocAlign > -1);
  11542. mCurMethodState->mCurAppendAlign = BF_MAX(calcAppendMethodModule.mMethodInstance->mEndingAppendAllocAlign, 0);
  11543. if (appendSizeTypedValue)
  11544. return appendSizeTypedValue;
  11545. if (constOnly)
  11546. return BfTypedValue(mBfIRBuilder->GetFakeVal(), GetPrimitiveType(BfTypeCode_IntPtr));
  11547. bool needsRecalc = false;
  11548. for (auto irArg : bindResult.mIRArgs)
  11549. {
  11550. if (irArg.IsFake())
  11551. needsRecalc = true;
  11552. }
  11553. auto calcAppendArgs = bindResult.mIRArgs;
  11554. if (needsRecalc)
  11555. {
  11556. // Do it again, but without mIgnoreWrites set
  11557. BfResolvedArgs argValues;
  11558. argValues.Init(&ctorDeclaration->mInitializer->mArguments);
  11559. exprEvaluator.ResolveArgValues(argValues, BfResolveArgFlag_DeferParamEval);
  11560. BfFunctionBindResult bindResult;
  11561. bindResult.mSkipThis = true;
  11562. bindResult.mWantsArgs = true;
  11563. SetAndRestoreValue<BfFunctionBindResult*> prevBindResult(exprEvaluator.mFunctionBindResult, &bindResult);
  11564. exprEvaluator.MatchConstructor(targetRefNode, NULL, target, targetType, argValues, true, true);
  11565. BF_ASSERT(bindResult.mIRArgs[0].IsFake());
  11566. bindResult.mIRArgs.RemoveAt(0);
  11567. calcAppendArgs = bindResult.mIRArgs;
  11568. }
  11569. BF_ASSERT(calcAppendMethodModule.mFunc);
  11570. appendSizeTypedValue = exprEvaluator.CreateCall(calcAppendMethodModule.mMethodInstance, calcAppendMethodModule.mFunc, false, calcAppendArgs);
  11571. BF_ASSERT(appendSizeTypedValue.mType == GetPrimitiveType(BfTypeCode_IntPtr));
  11572. return appendSizeTypedValue;
  11573. }
  11574. // This method never throws errors - it relies on the proper ctor actually throwing the errors
  11575. void BfModule::EmitCtorCalcAppend()
  11576. {
  11577. if (mCompiler->mIsResolveOnly)
  11578. return;
  11579. auto methodDef = mCurMethodInstance->mMethodDef;
  11580. auto methodDecl = methodDef->GetMethodDeclaration();
  11581. Array<BfAstNode*> deferredNodeList;
  11582. auto methodDeclBlock = BfNodeDynCast<BfBlock>(methodDecl->mBody);
  11583. if (methodDeclBlock == NULL)
  11584. return;
  11585. AppendAllocVisitor appendAllocVisitor;
  11586. auto baseCalcAppend = CallBaseCtorCalc(false);
  11587. if (baseCalcAppend)
  11588. {
  11589. mBfIRBuilder->CreateStore(baseCalcAppend.mValue, mCurMethodState->mRetVal.mValue);
  11590. }
  11591. appendAllocVisitor.mModule = this;
  11592. appendAllocVisitor.VisitChild(methodDecl->mBody);
  11593. }
  11594. void BfModule::CreateStaticCtor()
  11595. {
  11596. auto typeDef = mCurTypeInstance->mTypeDef;
  11597. auto methodDef = mCurMethodInstance->mMethodDef;
  11598. BfIRBlock exitBB;
  11599. if ((HasCompiledOutput()) && (!mCurMethodInstance->mIsUnspecialized) && (mCurMethodInstance->mChainType != BfMethodChainType_ChainMember))
  11600. {
  11601. auto boolType = GetPrimitiveType(BfTypeCode_Boolean);
  11602. auto didStaticInitVarAddr = mBfIRBuilder->CreateGlobalVariable(
  11603. mBfIRBuilder->MapType(boolType),
  11604. false,
  11605. BfIRLinkageType_Internal,
  11606. GetDefaultValue(boolType),
  11607. "didStaticInit");
  11608. auto initBB = mBfIRBuilder->CreateBlock("init", true);
  11609. mCurMethodState->mIRExitBlock = mBfIRBuilder->CreateBlock("exit", true);
  11610. auto didStaticInitVar = mBfIRBuilder->CreateLoad(didStaticInitVarAddr);
  11611. mBfIRBuilder->CreateCondBr(didStaticInitVar, mCurMethodState->mIRExitBlock, initBB);
  11612. mBfIRBuilder->SetInsertPoint(initBB);
  11613. mBfIRBuilder->CreateStore(GetConstValue(1, boolType), didStaticInitVarAddr);
  11614. }
  11615. // Do DLL imports
  11616. if (!mDllImportEntries.empty())
  11617. {
  11618. auto internalType = ResolveTypeDef(mCompiler->mInternalTypeDef);
  11619. PopulateType(internalType);
  11620. auto getSharedProcAddressInstance = GetMethodByName(internalType->ToTypeInstance(), "GetSharedProcAddress");
  11621. if (!getSharedProcAddressInstance)
  11622. {
  11623. if (!mCompiler->mPassInstance->HasFailed())
  11624. Fail("Internal error: System.Internal doesn't contain LoadSharedLibrary method");
  11625. }
  11626. }
  11627. // Fill in initializer values
  11628. if ((!mCompiler->mIsResolveOnly) || (mCompiler->mResolvePassData->mAutoComplete == NULL))
  11629. {
  11630. for (auto fieldDef : typeDef->mFields)
  11631. {
  11632. if ((!fieldDef->mIsConst) && (fieldDef->mIsStatic) && (fieldDef->mInitializer != NULL))
  11633. {
  11634. // For extensions, only handle these fields in the appropriate extension
  11635. if ((fieldDef->mDeclaringType->mTypeDeclaration != methodDef->mDeclaringType->mTypeDeclaration))
  11636. continue;
  11637. UpdateSrcPos(fieldDef->mInitializer);
  11638. auto fieldInst = &mCurTypeInstance->mFieldInstances[fieldDef->mIdx];
  11639. if (!fieldInst->mFieldIncluded)
  11640. continue;
  11641. if (fieldInst->mResolvedType->IsVar())
  11642. {
  11643. continue;
  11644. }
  11645. auto assignValue = GetFieldInitializerValue(fieldInst);
  11646. if (assignValue)
  11647. {
  11648. assignValue = LoadValue(assignValue);
  11649. if (!assignValue.mType->IsValuelessType())
  11650. {
  11651. auto staticVarRef = ReferenceStaticField(fieldInst).mValue;
  11652. mBfIRBuilder->CreateStore(assignValue.mValue, staticVarRef);
  11653. }
  11654. }
  11655. }
  11656. }
  11657. }
  11658. else
  11659. {
  11660. for (auto tempTypeDef : mCompiler->mResolvePassData->mAutoCompleteTempTypes)
  11661. {
  11662. if (tempTypeDef->mFullName == typeDef->mFullName)
  11663. {
  11664. for (auto fieldDef : tempTypeDef->mFields)
  11665. {
  11666. if ((fieldDef->mIsStatic) && (!fieldDef->mIsConst))
  11667. {
  11668. if (fieldDef->mInitializer != NULL)
  11669. {
  11670. if (mCompiler->mResolvePassData->mSourceClassifier != NULL)
  11671. {
  11672. mCompiler->mResolvePassData->mSourceClassifier->SetElementType(fieldDef->mInitializer, BfSourceElementType_Normal);
  11673. mCompiler->mResolvePassData->mSourceClassifier->VisitChild(fieldDef->mInitializer);
  11674. }
  11675. BfType* wantType = NULL;
  11676. if ((!BfNodeIsA<BfVarTypeReference>(fieldDef->mTypeRef)) && (!BfNodeIsA<BfLetTypeReference>(fieldDef->mTypeRef)))
  11677. {
  11678. wantType = ResolveTypeRef(fieldDef->mTypeRef);
  11679. }
  11680. CreateValueFromExpression(fieldDef->mInitializer, wantType, BfEvalExprFlags_FieldInitializer);
  11681. }
  11682. }
  11683. }
  11684. }
  11685. }
  11686. }
  11687. if (mCurMethodInstance->mChainType == BfMethodChainType_ChainHead)
  11688. CallChainedMethods(mCurMethodInstance, false);
  11689. }
  11690. void BfModule::EmitDtorBody()
  11691. {
  11692. if (mCurTypeInstance->IsClosure())
  11693. {
  11694. BfFieldInstance* fieldInstance = &mCurTypeInstance->mFieldInstances.back();
  11695. BF_ASSERT(fieldInstance->GetFieldDef()->mName == "__dtorThunk");
  11696. auto thisVal = GetThis();
  11697. auto dtorThunkPtr = mBfIRBuilder->CreateInBoundsGEP(thisVal.mValue, 0, fieldInstance->mDataIdx);
  11698. auto dtorThunk = mBfIRBuilder->CreateLoad(dtorThunkPtr);
  11699. auto funcPtrType = mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapMethod(mCurMethodInstance));
  11700. auto dtorPtr = mBfIRBuilder->CreateBitCast(dtorThunk, funcPtrType);
  11701. SizedArray<BfIRValue, 1> args;
  11702. args.push_back(thisVal.mValue);
  11703. auto result = mBfIRBuilder->CreateCall(dtorPtr, args);
  11704. mBfIRBuilder->SetCallCallingConv(result, BfIRCallingConv_CDecl);
  11705. // Fall through to Object::~this call
  11706. auto dtorFunc = GetMethodByName(mContext->mBfObjectType, "~this");
  11707. auto basePtr = mBfIRBuilder->CreateBitCast(thisVal.mValue, mBfIRBuilder->MapTypeInstPtr(mContext->mBfObjectType));
  11708. SizedArray<BfIRValue, 1> vals = { basePtr };
  11709. result = mBfIRBuilder->CreateCall(dtorFunc.mFunc, vals);
  11710. mBfIRBuilder->SetCallCallingConv(result, GetIRCallingConvention(dtorFunc.mMethodInstance));
  11711. mBfIRBuilder->SetTailCall(result);
  11712. return;
  11713. }
  11714. auto typeDef = mCurTypeInstance->mTypeDef;
  11715. auto methodDef = mCurMethodInstance->mMethodDef;
  11716. auto methodDeclaration = methodDef->GetMethodDeclaration();
  11717. if (mCurMethodInstance->mChainType == BfMethodChainType_ChainHead)
  11718. CallChainedMethods(mCurMethodInstance, true);
  11719. if (auto bodyBlock = BfNodeDynCast<BfBlock>(methodDef->mBody))
  11720. {
  11721. VisitCodeBlock(bodyBlock);
  11722. if (bodyBlock->mCloseBrace != NULL)
  11723. {
  11724. UpdateSrcPos(bodyBlock->mCloseBrace);
  11725. }
  11726. }
  11727. else
  11728. {
  11729. if (methodDeclaration != NULL)
  11730. UpdateSrcPos(methodDeclaration);
  11731. else if (typeDef->mTypeDeclaration != NULL)
  11732. UpdateSrcPos(typeDef->mTypeDeclaration);
  11733. if ((methodDeclaration != NULL) && (methodDeclaration->mFatArrowToken != NULL))
  11734. {
  11735. Fail("Destructors cannot have expression bodies", methodDeclaration->mFatArrowToken);
  11736. }
  11737. }
  11738. if ((!mCompiler->mIsResolveOnly) || (mCompiler->mResolvePassData->mAutoComplete == NULL))
  11739. {
  11740. for (int fieldIdx = (int)mCurTypeInstance->mFieldInstances.size() - 1; fieldIdx >= 0; fieldIdx--)
  11741. {
  11742. auto fieldInst = &mCurTypeInstance->mFieldInstances[fieldIdx];
  11743. auto fieldDef = fieldInst->GetFieldDef();
  11744. if ((fieldDef != NULL) && (fieldDef->mIsStatic == methodDef->mIsStatic) && (fieldDef->mFieldDeclaration != NULL) && (fieldDef->mFieldDeclaration->mFieldDtor != NULL))
  11745. {
  11746. if ((!methodDef->mIsStatic) && (mCurTypeInstance->IsValueType()))
  11747. {
  11748. Fail("Structs cannot have field destructors", fieldDef->mFieldDeclaration->mFieldDtor->mTildeToken);
  11749. }
  11750. SetAndRestoreValue<BfFilePosition> prevFilePos(mCurFilePosition);
  11751. auto fieldDtor = fieldDef->mFieldDeclaration->mFieldDtor;
  11752. if ((fieldDef->mIsStatic) != (methodDef->mIsStatic))
  11753. continue;
  11754. UpdateSrcPos(fieldDtor);
  11755. BfScopeData scopeData;
  11756. mCurMethodState->AddScope(&scopeData);
  11757. NewScopeState();
  11758. UpdateSrcPos(fieldDtor);
  11759. bool hasDbgInfo = (!fieldDef->mIsConst);
  11760. if (hasDbgInfo)
  11761. {
  11762. mBfIRBuilder->SaveDebugLocation();
  11763. mBfIRBuilder->ClearDebugLocation();
  11764. }
  11765. BfIRValue value;
  11766. if (fieldDef->mIsStatic)
  11767. {
  11768. value = ReferenceStaticField(fieldInst).mValue;
  11769. }
  11770. else
  11771. {
  11772. if (!mCurTypeInstance->IsValueType())
  11773. {
  11774. auto thisValue = GetThis();
  11775. value = mBfIRBuilder->CreateInBoundsGEP(thisValue.mValue, 0, fieldInst->mDataIdx);
  11776. }
  11777. else
  11778. {
  11779. AssertErrorState();
  11780. value = mBfIRBuilder->CreateConstNull(mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapType(fieldInst->mResolvedType)));
  11781. }
  11782. }
  11783. BfIRValue staticVal;
  11784. if (hasDbgInfo)
  11785. {
  11786. BfIRValue dbgShowValue = value;
  11787. BfLocalVariable* localDef = new BfLocalVariable();
  11788. localDef->mName = "_";
  11789. localDef->mResolvedType = fieldInst->mResolvedType;
  11790. localDef->mAddr = value;
  11791. if ((mBfIRBuilder->DbgHasInfo()) && (!IsTargetingBeefBackend()))
  11792. {
  11793. // Create another pointer indirection, a ref to the gep
  11794. auto refFieldType = CreateRefType(fieldInst->mResolvedType);
  11795. auto allocaInst = CreateAlloca(refFieldType);
  11796. auto storeResult = mBfIRBuilder->CreateStore(value, allocaInst);
  11797. localDef->mResolvedType = refFieldType;
  11798. localDef->mAddr = allocaInst;
  11799. }
  11800. mBfIRBuilder->RestoreDebugLocation();
  11801. auto defLocalVar = AddLocalVariableDef(localDef, true);
  11802. // Put back so we actually modify the correct value*/
  11803. defLocalVar->mResolvedType = fieldInst->mResolvedType;
  11804. defLocalVar->mAddr = value;
  11805. }
  11806. while (fieldDtor != NULL)
  11807. {
  11808. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mSourceClassifier != NULL))
  11809. {
  11810. mCompiler->mResolvePassData->mSourceClassifier->SetElementType(fieldDtor, BfSourceElementType_Normal);
  11811. mCompiler->mResolvePassData->mSourceClassifier->VisitChild(fieldDtor);
  11812. }
  11813. UpdateSrcPos(fieldDtor);
  11814. VisitEmbeddedStatement(fieldDtor->mBody);
  11815. fieldDtor = fieldDtor->mNextFieldDtor;
  11816. }
  11817. RestoreScopeState();
  11818. }
  11819. }
  11820. if (!methodDef->mIsStatic)
  11821. {
  11822. auto checkBaseType = mCurTypeInstance->mBaseType;
  11823. while (checkBaseType != NULL)
  11824. {
  11825. if (auto bodyBlock = BfNodeDynCast<BfBlock>(methodDef->mBody))
  11826. {
  11827. if (bodyBlock->mCloseBrace != NULL)
  11828. UpdateSrcPos(bodyBlock->mCloseBrace);
  11829. }
  11830. else
  11831. {
  11832. UpdateSrcPos(typeDef->mTypeDeclaration->mNameNode);
  11833. }
  11834. if (checkBaseType->mTypeDef->mDtorDef != NULL)
  11835. {
  11836. auto dtorMethodInstance = GetMethodInstance(checkBaseType, checkBaseType->mTypeDef->mDtorDef, BfTypeVector());
  11837. if (mCompiler->IsSkippingExtraResolveChecks())
  11838. {
  11839. // Nothing
  11840. }
  11841. else if (dtorMethodInstance.mMethodInstance->GetParamCount() == 0)
  11842. {
  11843. if ((!mCompiler->IsSkippingExtraResolveChecks()) && (!checkBaseType->IsUnspecializedType()))
  11844. {
  11845. auto basePtr = mBfIRBuilder->CreateBitCast(mCurMethodState->mLocals[0]->mValue, mBfIRBuilder->MapTypeInstPtr(checkBaseType));
  11846. SizedArray<BfIRValue, 1> vals = { basePtr };
  11847. auto callInst = mBfIRBuilder->CreateCall(dtorMethodInstance.mFunc, vals);
  11848. mBfIRBuilder->SetCallCallingConv(callInst, GetIRCallingConvention(dtorMethodInstance.mMethodInstance));
  11849. }
  11850. }
  11851. else
  11852. {
  11853. // Invalid base dtor declaration
  11854. AssertErrorState();
  11855. }
  11856. break;
  11857. }
  11858. checkBaseType = checkBaseType->mBaseType;
  11859. }
  11860. }
  11861. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  11862. }
  11863. else
  11864. {
  11865. // The reason we can't just do the 'normal' path for this is that the BfTypeInstance here is NOT the
  11866. // autocomplete type instance, so FieldInstance initializer values contain expressions from the full
  11867. // resolve pass, NOT the autocomplete expression
  11868. for (auto tempTypeDef : mCompiler->mResolvePassData->mAutoCompleteTempTypes)
  11869. {
  11870. if (tempTypeDef->mFullName == typeDef->mFullName)
  11871. {
  11872. for (auto fieldDef : tempTypeDef->mFields)
  11873. {
  11874. if ((fieldDef->mIsStatic == methodDef->mIsStatic) && (fieldDef->mFieldDeclaration != NULL) &&
  11875. (fieldDef->mFieldDeclaration->mFieldDtor != NULL) && (mCompiler->mResolvePassData->mSourceClassifier != NULL))
  11876. {
  11877. BfType* fieldType = NULL;
  11878. for (int curFieldIdx = 0; curFieldIdx < (int)mCurTypeInstance->mFieldInstances.size(); curFieldIdx++)
  11879. {
  11880. auto curFieldInstance = &mCurTypeInstance->mFieldInstances[curFieldIdx];
  11881. auto curFieldDef = curFieldInstance->GetFieldDef();
  11882. if ((curFieldDef != NULL) && (fieldDef->mName == curFieldDef->mName))
  11883. fieldType = curFieldInstance->GetResolvedType();
  11884. }
  11885. auto fieldDtor = fieldDef->mFieldDeclaration->mFieldDtor;
  11886. BfScopeData scopeData;
  11887. mCurMethodState->AddScope(&scopeData);
  11888. NewScopeState();
  11889. // This is just for autocomplete, it doesn't matter that mAddr is incorrect
  11890. if (fieldType != NULL)
  11891. {
  11892. BfLocalVariable* localDef = new BfLocalVariable();
  11893. localDef->mName = "_";
  11894. localDef->mResolvedType = fieldType;
  11895. localDef->mAddr = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(fieldType));
  11896. localDef->mIsAssigned = true;
  11897. AddLocalVariableDef(localDef);
  11898. }
  11899. while (fieldDtor != NULL)
  11900. {
  11901. mCompiler->mResolvePassData->mSourceClassifier->SetElementType(fieldDtor, BfSourceElementType_Normal);
  11902. mCompiler->mResolvePassData->mSourceClassifier->VisitChild(fieldDtor);
  11903. UpdateSrcPos(fieldDtor);
  11904. VisitEmbeddedStatement(fieldDtor->mBody);
  11905. fieldDtor = fieldDtor->mNextFieldDtor;
  11906. }
  11907. RestoreScopeState();
  11908. }
  11909. }
  11910. }
  11911. }
  11912. }
  11913. }
  11914. BfIRValue BfModule::CreateDllImportGlobalVar(BfMethodInstance* methodInstance, bool define)
  11915. {
  11916. auto typeInstance = methodInstance->GetOwner();
  11917. bool foundDllImportAttr = false;
  11918. BfCallingConvention callingConvention = methodInstance->mMethodDef->mCallingConvention;
  11919. for (auto customAttr : methodInstance->GetCustomAttributes()->mAttributes)
  11920. {
  11921. if (customAttr.mType->mTypeDef->mFullName.ToString() == "System.ImportAttribute")
  11922. {
  11923. foundDllImportAttr = true;
  11924. }
  11925. }
  11926. if (!foundDllImportAttr)
  11927. {
  11928. AssertErrorState();
  11929. return BfIRValue();
  11930. }
  11931. String name = "bf_hs_preserve@";
  11932. BfMangler::Mangle(name, mCompiler->GetMangleKind(), methodInstance);
  11933. name += "__imp";
  11934. BfIRType returnType;
  11935. SizedArray<BfIRType, 8> paramTypes;
  11936. methodInstance->GetIRFunctionInfo(this, returnType, paramTypes);
  11937. BfIRFunctionType externFunctionType = mBfIRBuilder->CreateFunctionType(returnType, paramTypes, false);
  11938. auto ptrType = mBfIRBuilder->GetPointerTo(externFunctionType);
  11939. BfIRValue initVal;
  11940. if (define)
  11941. {
  11942. if (methodInstance->GetImportCallKind() != BfImportCallKind_None)
  11943. initVal = mBfIRBuilder->CreateConstNull(ptrType);
  11944. }
  11945. auto globalVar = mBfIRBuilder->CreateGlobalVariable(ptrType, false, BfIRLinkageType_External, initVal, name);
  11946. if ((define) && (mBfIRBuilder->DbgHasInfo()))
  11947. {
  11948. auto voidType = GetPrimitiveType(BfTypeCode_None);
  11949. auto ptrType = CreatePointerType(voidType);
  11950. mBfIRBuilder->DbgCreateGlobalVariable(mDICompileUnit, name, name, BfIRMDNode(), 0, mBfIRBuilder->DbgGetType(ptrType), false, globalVar);
  11951. }
  11952. return globalVar;
  11953. }
  11954. void BfModule::CreateDllImportMethod()
  11955. {
  11956. if (mBfIRBuilder->mIgnoreWrites)
  11957. return;
  11958. auto globalVar = mFuncReferences[mCurMethodInstance];
  11959. if (!globalVar)
  11960. return;
  11961. bool allowTailCall = true;
  11962. mBfIRBuilder->ClearDebugLocation();
  11963. bool isHotCompile = mCompiler->IsHotCompile();
  11964. // If we are hot swapping, we need to have this stub because we may need to call the LoadSharedLibraries on demand
  11965. if (isHotCompile)
  11966. {
  11967. auto loadSharedLibsFunc = GetBuiltInFunc(BfBuiltInFuncType_LoadSharedLibraries);
  11968. mBfIRBuilder->CreateCall(loadSharedLibsFunc, SizedArray<BfIRValue, 0>());
  11969. }
  11970. auto callingConvention = GetIRCallingConvention(mCurTypeInstance, mCurMethodInstance->mMethodDef);
  11971. BfIRType returnType;
  11972. SizedArray<BfIRType, 8> paramTypes;
  11973. mCurMethodInstance->GetIRFunctionInfo(this, returnType, paramTypes);
  11974. SizedArray<BfIRValue, 8> args;
  11975. for (int i = 0; i < (int)paramTypes.size(); i++)
  11976. args.push_back(mBfIRBuilder->GetArgument(i));
  11977. BfIRFunctionType externFunctionType = mBfIRBuilder->CreateFunctionType(returnType, paramTypes, false);
  11978. if (isHotCompile)
  11979. {
  11980. BfIRValue funcVal = mBfIRBuilder->CreateLoad(globalVar);
  11981. auto result = mBfIRBuilder->CreateCall(funcVal, args);
  11982. if (callingConvention == BfIRCallingConv_StdCall)
  11983. mBfIRBuilder->SetCallCallingConv(result, BfIRCallingConv_StdCall);
  11984. else
  11985. mBfIRBuilder->SetCallCallingConv(result, BfIRCallingConv_CDecl);
  11986. if (allowTailCall)
  11987. mBfIRBuilder->SetTailCall(result);
  11988. CreateReturn(result);
  11989. mCurMethodState->mHadReturn = true;
  11990. }
  11991. if (HasCompiledOutput())
  11992. {
  11993. BfDllImportEntry dllImportEntry;
  11994. dllImportEntry.mFuncVar = globalVar;
  11995. dllImportEntry.mMethodInstance = mCurMethodInstance;
  11996. mDllImportEntries.push_back(dllImportEntry);
  11997. }
  11998. }
  11999. BfIRCallingConv BfModule::GetIRCallingConvention(BfTypeInstance* typeInst, BfMethodDef* methodDef)
  12000. {
  12001. if ((mCompiler->mOptions.mMachineType != BfMachineType_x86) || (mCompiler->mOptions.mPlatformType != BfPlatformType_Windows))
  12002. return BfIRCallingConv_CDecl;
  12003. if (methodDef->mCallingConvention == BfCallingConvention_Stdcall)
  12004. return BfIRCallingConv_StdCall;
  12005. if ((!methodDef->mIsStatic) && (!typeInst->IsValuelessType()) &&
  12006. ((!typeInst->IsSplattable()) || (methodDef->HasNoThisSplat())))
  12007. return BfIRCallingConv_ThisCall;
  12008. return BfIRCallingConv_CDecl;
  12009. }
  12010. BfIRCallingConv BfModule::GetIRCallingConvention(BfMethodInstance* methodInstance)
  12011. {
  12012. auto methodDef = methodInstance->mMethodDef;
  12013. BfTypeInstance* owner = NULL;
  12014. if (!methodDef->mIsStatic)
  12015. owner = methodInstance->GetParamType(-1)->ToTypeInstance();
  12016. if (owner == NULL)
  12017. owner = methodInstance->GetOwner();
  12018. return GetIRCallingConvention(owner, methodInstance->mMethodDef);
  12019. }
  12020. void BfModule::SetupIRMethod(BfMethodInstance* methodInstance, BfIRFunction func, bool isInlined)
  12021. {
  12022. BfMethodDef* methodDef = NULL;
  12023. if (methodInstance != NULL)
  12024. methodDef = methodInstance->mMethodDef;
  12025. if (!func)
  12026. return;
  12027. if (mCompiler->mOptions.mNoFramePointerElim)
  12028. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_NoFramePointerElim);
  12029. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_NoUnwind);
  12030. if (mSystem->mPtrSize == 8) // We need unwind info for debugging
  12031. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_UWTable);
  12032. if (methodInstance == NULL)
  12033. return;
  12034. if (methodDef->mImportKind == BfImportKind_Export)
  12035. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_DllExport);
  12036. if (methodDef->mNoReturn)
  12037. mBfIRBuilder->Func_AddAttribute(func, -1, BfIRAttribute_NoReturn);
  12038. auto callingConv = GetIRCallingConvention(methodInstance);
  12039. if (callingConv != BfIRCallingConv_CDecl)
  12040. mBfIRBuilder->SetFuncCallingConv(func, callingConv);
  12041. if (isInlined)
  12042. {
  12043. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_AlwaysInline);
  12044. }
  12045. int argIdx = 0;
  12046. int paramIdx = 0;
  12047. if (methodInstance->HasThis())
  12048. {
  12049. paramIdx = -1;
  12050. }
  12051. int argCount = methodInstance->GetIRFunctionParamCount(this);
  12052. if (methodInstance->HasStructRet())
  12053. {
  12054. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_NoAlias);
  12055. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_StructRet);
  12056. argIdx++;
  12057. }
  12058. while (argIdx < argCount)
  12059. {
  12060. while ((paramIdx != -1) && (methodInstance->IsParamSkipped(paramIdx)))
  12061. paramIdx++;
  12062. BfType* resolvedTypeRef = NULL;
  12063. String paramName;
  12064. bool isSplattable = false;
  12065. bool isThis = paramIdx == -1;
  12066. if (isThis)
  12067. {
  12068. paramName = "this";
  12069. if (methodInstance->mIsClosure)
  12070. resolvedTypeRef = mCurMethodState->mClosureState->mClosureType;
  12071. else
  12072. resolvedTypeRef = methodInstance->GetOwner();
  12073. isSplattable = (resolvedTypeRef->IsSplattable()) && (!methodDef->HasNoThisSplat());
  12074. }
  12075. else if (!methodDef->mNoSplat)
  12076. {
  12077. paramName = methodInstance->GetParamName(paramIdx);
  12078. resolvedTypeRef = methodInstance->GetParamType(paramIdx);
  12079. if (resolvedTypeRef->IsMethodRef())
  12080. isSplattable = true;
  12081. else if (resolvedTypeRef->IsSplattable())
  12082. {
  12083. if (resolvedTypeRef->GetSplatCount() + argIdx <= mCompiler->mOptions.mMaxSplatRegs)
  12084. isSplattable = true;
  12085. }
  12086. }
  12087. //
  12088. {
  12089. auto loweredTypeCode = resolvedTypeRef->GetLoweredType();
  12090. if (loweredTypeCode != BfTypeCode_None)
  12091. resolvedTypeRef = GetPrimitiveType(loweredTypeCode);
  12092. }
  12093. auto _SetupParam = [&](const StringImpl& paramName, BfType* resolvedTypeRef)
  12094. {
  12095. mBfIRBuilder->Func_SetParamName(func, argIdx + 1, paramName);
  12096. int addDeref = -1;
  12097. if (resolvedTypeRef->IsRef())
  12098. {
  12099. auto refType = (BfRefType*)resolvedTypeRef;
  12100. auto elementType = refType->mElementType;
  12101. PopulateType(elementType, BfPopulateType_Data);
  12102. addDeref = elementType->mSize;
  12103. if ((addDeref <= 0) && (!elementType->IsValuelessType()))
  12104. AssertErrorState();
  12105. }
  12106. if ((resolvedTypeRef->IsComposite()) && (!resolvedTypeRef->IsTypedPrimitive()))
  12107. {
  12108. if (mCompiler->mOptions.mAllowStructByVal)
  12109. {
  12110. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_ByVal);
  12111. }
  12112. else
  12113. {
  12114. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_NoCapture);
  12115. PopulateType(resolvedTypeRef, BfPopulateType_Data);
  12116. addDeref = resolvedTypeRef->mSize;
  12117. }
  12118. }
  12119. else if (resolvedTypeRef->IsPrimitiveType())
  12120. {
  12121. auto primType = (BfPrimitiveType*)resolvedTypeRef;
  12122. if (primType->mTypeDef->mTypeCode == BfTypeCode_Boolean)
  12123. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_ZExt);
  12124. }
  12125. if (addDeref >= 0)
  12126. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_Dereferencable, addDeref);
  12127. argIdx++;
  12128. };
  12129. if (isSplattable)
  12130. {
  12131. std::function<void(BfType*, const StringImpl&)> checkTypeLambda = [&](BfType* checkType, const StringImpl& curName)
  12132. {
  12133. if (checkType->IsStruct())
  12134. {
  12135. auto checkTypeInstance = checkType->ToTypeInstance();
  12136. if (checkTypeInstance->mBaseType != NULL)
  12137. checkTypeLambda(checkTypeInstance->mBaseType, curName);
  12138. if (checkTypeInstance->mIsUnion)
  12139. {
  12140. BfType* unionInnerType = checkTypeInstance->GetUnionInnerType();
  12141. checkTypeLambda(unionInnerType, curName + "_data");
  12142. }
  12143. else
  12144. {
  12145. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  12146. {
  12147. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  12148. auto fieldDef = fieldInstance->GetFieldDef();
  12149. if (fieldInstance->mDataIdx >= 0)
  12150. {
  12151. checkTypeLambda(fieldInstance->GetResolvedType(), curName + "_" + fieldInstance->GetFieldDef()->mName);
  12152. }
  12153. }
  12154. }
  12155. if (checkTypeInstance->IsEnum())
  12156. {
  12157. mBfIRBuilder->Func_SetParamName(func, argIdx + 1, curName + "_dscr");
  12158. argIdx++;
  12159. }
  12160. }
  12161. else if (checkType->IsMethodRef())
  12162. {
  12163. auto methodRefType = (BfMethodRefType*)checkType;
  12164. BfMethodInstance* methodRefMethodInst = methodRefType->mMethodRef;
  12165. for (int dataIdx = 0; dataIdx < (int)methodRefType->GetCaptureDataCount(); dataIdx++)
  12166. {
  12167. int methodRefParamIdx = methodRefType->GetParamIdxFromDataIdx(dataIdx);
  12168. if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  12169. {
  12170. checkTypeLambda(methodRefType->GetCaptureType(dataIdx), curName + "_" + methodRefMethodInst->GetParamName(methodRefParamIdx));
  12171. }
  12172. else
  12173. {
  12174. _SetupParam(curName + "_" + methodRefMethodInst->GetParamName(methodRefParamIdx), methodRefType->GetCaptureType(dataIdx));
  12175. }
  12176. }
  12177. }
  12178. else if (!checkType->IsValuelessType())
  12179. {
  12180. _SetupParam(curName, checkType);
  12181. }
  12182. };
  12183. checkTypeLambda(resolvedTypeRef, paramName);
  12184. paramIdx++;
  12185. continue;
  12186. }
  12187. _SetupParam(paramName, resolvedTypeRef);
  12188. //argIdx++;
  12189. paramIdx++;
  12190. }
  12191. }
  12192. void BfModule::EmitCtorBody(bool& skipBody)
  12193. {
  12194. auto methodInstance = mCurMethodInstance;
  12195. auto methodDef = methodInstance->mMethodDef;
  12196. auto methodDeclaration = methodDef->mMethodDeclaration;
  12197. auto ctorDeclaration = (BfConstructorDeclaration*)methodDef->mMethodDeclaration;
  12198. auto typeDef = mCurTypeInstance->mTypeDef;
  12199. // Prologue
  12200. mBfIRBuilder->ClearDebugLocation();
  12201. bool hadThisInitializer = false;
  12202. if ((ctorDeclaration != NULL) && (ctorDeclaration->mInitializer != NULL))
  12203. {
  12204. auto targetToken = BfNodeDynCast<BfTokenNode>(ctorDeclaration->mInitializer->mTarget);
  12205. auto targetType = (targetToken->GetToken() == BfToken_This) ? mCurTypeInstance : mCurTypeInstance->mBaseType;
  12206. if (targetToken->GetToken() == BfToken_This)
  12207. {
  12208. hadThisInitializer = true;
  12209. // Since we call a 'this', it's that other ctor's responsibility to fully assign the fields
  12210. mCurMethodState->LocalDefined(GetThisVariable());
  12211. }
  12212. }
  12213. // Zero out memory for default ctor
  12214. if ((methodDeclaration == NULL) && (mCurTypeInstance->IsStruct()))
  12215. {
  12216. if (mCurTypeInstance->IsTypedPrimitive())
  12217. {
  12218. auto thisRef = mCurMethodState->mLocals[0]->mValue;
  12219. mBfIRBuilder->CreateStore(GetDefaultValue(mCurTypeInstance), thisRef);
  12220. }
  12221. else if (mCurTypeInstance->mInstSize > 0)
  12222. {
  12223. BfIRValue fillValue = GetConstValue8(0);
  12224. BfIRValue sizeValue = GetConstValue(mCurTypeInstance->mInstSize);
  12225. auto thisRef = mCurMethodState->mLocals[0]->mValue;
  12226. BfIRValue destBits = mBfIRBuilder->CreateBitCast(thisRef, mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr));
  12227. mBfIRBuilder->CreateMemSet(destBits, fillValue, sizeValue, mCurTypeInstance->mAlign);
  12228. }
  12229. }
  12230. BfAstNode* baseCtorNode = NULL;
  12231. if ((ctorDeclaration != NULL) && (ctorDeclaration->mInitializer != NULL) && (ctorDeclaration->mInitializer->mTarget != NULL))
  12232. baseCtorNode = ctorDeclaration->mInitializer->mTarget;
  12233. else if (methodDef->mBody != NULL)
  12234. baseCtorNode = methodDef->mBody;
  12235. else if (ctorDeclaration != NULL)
  12236. baseCtorNode = ctorDeclaration;
  12237. else if (mCurTypeInstance->mTypeDef->mTypeDeclaration != NULL)
  12238. baseCtorNode = mCurTypeInstance->mTypeDef->mTypeDeclaration->mNameNode;
  12239. else if ((mCurTypeInstance->mBaseType != NULL) && (mCurTypeInstance->mBaseType->mTypeDef->mTypeDeclaration != NULL))
  12240. baseCtorNode = mCurTypeInstance->mBaseType->mTypeDef->mTypeDeclaration;
  12241. else
  12242. baseCtorNode = mContext->mBfObjectType->mTypeDef->mTypeDeclaration;
  12243. if ((!mCurTypeInstance->IsBoxed()) && (methodDef->mMethodType == BfMethodType_Ctor))
  12244. {
  12245. // Call the root type's default ctor (with no body) to initialize its fields and call the chained ctors
  12246. if (methodDef->mDeclaringType->mTypeCode == BfTypeCode_Extension)
  12247. {
  12248. BfMethodDef* defaultCtor = NULL;
  12249. for (auto methodDef : mCurTypeInstance->mTypeDef->mMethods)
  12250. {
  12251. if ((methodDef->mMethodType == BfMethodType_CtorNoBody) && (methodDef->mDeclaringType->mTypeCode != BfTypeCode_Extension))
  12252. {
  12253. defaultCtor = methodDef;
  12254. }
  12255. }
  12256. if (defaultCtor != NULL)
  12257. {
  12258. UpdateSrcPos(mCurTypeInstance->mTypeDef->GetRefNode());
  12259. SetIllegalSrcPos();
  12260. auto moduleMethodInstance = GetMethodInstance(mCurTypeInstance, defaultCtor, BfTypeVector());
  12261. BfExprEvaluator exprEvaluator(this);
  12262. SizedArray<BfIRValue, 1> irArgs;
  12263. exprEvaluator.PushThis(NULL, GetThis(), moduleMethodInstance.mMethodInstance, irArgs);
  12264. exprEvaluator.CreateCall(moduleMethodInstance.mMethodInstance, moduleMethodInstance.mFunc, false, irArgs);
  12265. }
  12266. }
  12267. }
  12268. // Initialize fields (if applicable)
  12269. if (mCurTypeInstance->IsBoxed())
  12270. {
  12271. skipBody = true;
  12272. }
  12273. else if ((methodDef->mMethodType == BfMethodType_Ctor) && (methodDef->mDeclaringType->mTypeCode == BfTypeCode_Extension))
  12274. {
  12275. // Field initializers occur in CtorNoBody methods for extensions
  12276. }
  12277. else if (!hadThisInitializer)
  12278. {
  12279. // If we had a 'this' initializer, that other ctor will have initialized our fields
  12280. if ((!mCompiler->mIsResolveOnly) ||
  12281. (mCompiler->mResolvePassData->mAutoComplete == NULL) ||
  12282. (mCompiler->mResolvePassData->mAutoComplete->mResolveType == BfResolveType_ShowFileSymbolReferences))
  12283. {
  12284. bool hadInlineInitBlock = false;
  12285. BfScopeData scopeData;
  12286. for (auto fieldDef : typeDef->mFields)
  12287. {
  12288. // For extensions, only handle these fields in the appropriate extension
  12289. if ((fieldDef->mDeclaringType->mTypeDeclaration != methodDef->mDeclaringType->mTypeDeclaration))
  12290. continue;
  12291. if ((!fieldDef->mIsConst) && (!fieldDef->mIsStatic))
  12292. {
  12293. auto fieldInst = &mCurTypeInstance->mFieldInstances[fieldDef->mIdx];
  12294. if (!fieldInst->mFieldIncluded)
  12295. continue;
  12296. if (fieldInst->mDataIdx < 0)
  12297. continue;
  12298. if (fieldDef->mInitializer == NULL)
  12299. {
  12300. if (fieldDef->mProtection != BfProtection_Hidden)
  12301. continue;
  12302. if (mCurTypeInstance->IsObject()) // Already zeroed out
  12303. continue;
  12304. }
  12305. if (fieldInst->mResolvedType == NULL)
  12306. {
  12307. BF_ASSERT(mHadBuildError);
  12308. continue;
  12309. }
  12310. if (fieldDef->mInitializer != NULL)
  12311. {
  12312. if (!hadInlineInitBlock)
  12313. {
  12314. if ((mBfIRBuilder->DbgHasInfo()) && (!mCurTypeInstance->IsUnspecializedType()) && (mHasFullDebugInfo))
  12315. {
  12316. UpdateSrcPos(baseCtorNode);
  12317. // 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
  12318. EmitEnsureInstructionAt();
  12319. BfType* thisType = mCurTypeInstance;
  12320. if (thisType->IsValueType())
  12321. thisType = CreateRefType(thisType);
  12322. SizedArray<BfIRMDNode, 1> diParamTypes;
  12323. BfIRMDNode diFuncType = mBfIRBuilder->DbgCreateSubroutineType(diParamTypes);
  12324. mCurMethodState->AddScope(&scopeData);
  12325. NewScopeState();
  12326. int flags = 0;
  12327. mCurMethodState->mCurScope->mDIInlinedAt = mBfIRBuilder->DbgGetCurrentLocation();
  12328. BF_ASSERT(mCurMethodState->mCurScope->mDIInlinedAt);
  12329. // mCurMethodState->mCurScope->mDIInlinedAt may still be null ifwe don't have an explicit ctor
  12330. mCurMethodState->mCurScope->mDIScope = mBfIRBuilder->DbgCreateFunction(mBfIRBuilder->DbgGetTypeInst(mCurTypeInstance), "this$initFields", "", mCurFilePosition.mFileInstance->mDIFile,
  12331. mCurFilePosition.mCurLine + 1, diFuncType, false, true, mCurFilePosition.mCurLine + 1, flags, false, BfIRValue());
  12332. UpdateSrcPos(fieldDef->mInitializer);
  12333. auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(mCurMethodState->mCurScope->mDIScope,
  12334. "this", mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, mBfIRBuilder->DbgGetType(thisType));
  12335. //
  12336. {
  12337. auto loadedThis = GetThis();
  12338. // LLVM can't handle two variables pointing to the same value
  12339. BfIRValue copiedThisPtr;
  12340. copiedThisPtr = CreateAlloca(thisType);
  12341. auto storeInst = mBfIRBuilder->CreateStore(loadedThis.mValue, copiedThisPtr);
  12342. mBfIRBuilder->ClearDebugLocation(storeInst);
  12343. mBfIRBuilder->DbgInsertDeclare(copiedThisPtr, diVariable);
  12344. }
  12345. hadInlineInitBlock = true;
  12346. }
  12347. }
  12348. UpdateSrcPos(fieldDef->mInitializer);
  12349. }
  12350. BfIRValue fieldAddr;
  12351. if ((!mCurTypeInstance->IsTypedPrimitive()) && (!fieldInst->mResolvedType->IsVar()))
  12352. {
  12353. fieldAddr = mBfIRBuilder->CreateInBoundsGEP(mCurMethodState->mLocals[0]->mValue, 0, fieldInst->mDataIdx /*, fieldDef->mName*/);
  12354. }
  12355. else
  12356. {
  12357. AssertErrorState();
  12358. }
  12359. auto assignValue = GetFieldInitializerValue(fieldInst);
  12360. if ((fieldAddr) && (assignValue))
  12361. mBfIRBuilder->CreateStore(assignValue.mValue, fieldAddr);
  12362. }
  12363. }
  12364. if (hadInlineInitBlock)
  12365. {
  12366. RestoreScopeState();
  12367. // This gets set to false because of AddScope but we actually are still in the head block
  12368. mCurMethodState->mInHeadScope = true;
  12369. }
  12370. }
  12371. else // Autocomplete case
  12372. {
  12373. // The reason we can't just do the 'normal' path for this is that the BfTypeInstance here is NOT the
  12374. // autocomplete type instance, so FieldInstance initializer values contain expressions from the full
  12375. // resolve pass, NOT the autocomplete expression
  12376. for (auto tempTypeDef : mCompiler->mResolvePassData->mAutoCompleteTempTypes)
  12377. {
  12378. if (tempTypeDef->mFullName == typeDef->mFullName)
  12379. {
  12380. for (auto fieldDef : tempTypeDef->mFields)
  12381. {
  12382. if ((!fieldDef->mIsStatic) && (fieldDef->mInitializer != NULL) && (mCompiler->mResolvePassData->mSourceClassifier != NULL))
  12383. {
  12384. mCompiler->mResolvePassData->mSourceClassifier->SetElementType(fieldDef->mInitializer, BfSourceElementType_Normal);
  12385. mCompiler->mResolvePassData->mSourceClassifier->VisitChild(fieldDef->mInitializer);
  12386. auto wantType = ResolveTypeRef(fieldDef->mTypeRef);
  12387. if ((wantType != NULL) &&
  12388. ((wantType->IsVar()) || (wantType->IsLet()) || (wantType->IsRef())))
  12389. wantType = NULL;
  12390. CreateValueFromExpression(fieldDef->mInitializer, wantType, BfEvalExprFlags_FieldInitializer);
  12391. }
  12392. }
  12393. }
  12394. }
  12395. // Mark fields from full type with initializers as initialized, to give proper initialization errors within ctor
  12396. for (auto fieldDef : typeDef->mFields)
  12397. {
  12398. if ((!fieldDef->mIsConst) && (!fieldDef->mIsStatic) && (fieldDef->mInitializer != NULL))
  12399. {
  12400. auto fieldInst = &mCurTypeInstance->mFieldInstances[fieldDef->mIdx];
  12401. if (fieldDef->mInitializer != NULL)
  12402. MarkFieldInitialized(fieldInst);
  12403. }
  12404. }
  12405. }
  12406. }
  12407. // Call base ctor (if applicable)
  12408. BfTypeInstance* targetType = NULL;
  12409. BfAstNode* targetRefNode = NULL;
  12410. if (ctorDeclaration != NULL)
  12411. targetRefNode = ctorDeclaration->mInitializer;
  12412. if (auto invocationExpr = BfNodeDynCast<BfInvocationExpression>(targetRefNode))
  12413. targetRefNode = invocationExpr->mTarget;
  12414. if (baseCtorNode != NULL)
  12415. {
  12416. UpdateSrcPos(baseCtorNode);
  12417. }
  12418. if ((ctorDeclaration != NULL) && (ctorDeclaration->mInitializer != NULL))
  12419. {
  12420. auto targetToken = BfNodeDynCast<BfTokenNode>(ctorDeclaration->mInitializer->mTarget);
  12421. targetType = (targetToken->GetToken() == BfToken_This) ? mCurTypeInstance : mCurTypeInstance->mBaseType;
  12422. }
  12423. else if ((mCurTypeInstance->mBaseType != NULL) && (!mCurTypeInstance->IsUnspecializedType()))
  12424. {
  12425. auto baseType = mCurTypeInstance->mBaseType;
  12426. if ((!mCurTypeInstance->IsTypedPrimitive()) &&
  12427. (baseType->mTypeDef != mCompiler->mValueTypeTypeDef) &&
  12428. (baseType->mTypeDef != mCompiler->mBfObjectTypeDef))
  12429. {
  12430. // Try to find a ctor without any params first
  12431. bool foundBaseCtor = false;
  12432. bool hadCtorWithAllDefaults = false;
  12433. for (int pass = 0; pass < 2; pass++)
  12434. {
  12435. for (auto checkMethodDef : baseType->mTypeDef->mMethods)
  12436. {
  12437. bool allowPriv = checkMethodDef->mProtection != BfProtection_Private;
  12438. // Allow calling of the default base ctor if it is implicitly defined
  12439. if ((checkMethodDef->mMethodDeclaration == NULL) && (pass == 1) && (!hadCtorWithAllDefaults))
  12440. allowPriv = true;
  12441. if ((checkMethodDef->mMethodType == BfMethodType_Ctor) && (!checkMethodDef->mIsStatic) && (allowPriv))
  12442. {
  12443. if (checkMethodDef->mParams.size() == 0)
  12444. {
  12445. foundBaseCtor = true;
  12446. if (HasCompiledOutput())
  12447. {
  12448. SizedArray<BfIRValue, 1> args;
  12449. auto ctorBodyMethodInstance = GetMethodInstance(mCurTypeInstance->mBaseType, checkMethodDef, BfTypeVector());
  12450. if (!mCurTypeInstance->mBaseType->IsValuelessType())
  12451. {
  12452. auto basePtr = mBfIRBuilder->CreateBitCast(mCurMethodState->mLocals[0]->mValue, mBfIRBuilder->MapTypeInstPtr(mCurTypeInstance->mBaseType));
  12453. args.push_back(basePtr);
  12454. }
  12455. AddCallDependency(ctorBodyMethodInstance.mMethodInstance, true);
  12456. auto callInst = mBfIRBuilder->CreateCall(ctorBodyMethodInstance.mFunc, args);
  12457. auto callingConv = GetIRCallingConvention(ctorBodyMethodInstance.mMethodInstance);
  12458. if (callingConv != BfIRCallingConv_CDecl)
  12459. mBfIRBuilder->SetCallCallingConv(callInst, callingConv);
  12460. // if (!mCurTypeInstance->mBaseType->IsValuelessType())
  12461. // mBfIRBuilder->SetCallCallingConv(callInst, BfIRCallingConv_ThisCall);
  12462. break;
  12463. }
  12464. }
  12465. else if ((checkMethodDef->mParams[0]->mParamDeclaration != NULL) && (checkMethodDef->mParams[0]->mParamDeclaration->mInitializer != NULL))
  12466. hadCtorWithAllDefaults = true;
  12467. }
  12468. }
  12469. if (foundBaseCtor)
  12470. break;
  12471. }
  12472. if (!foundBaseCtor)
  12473. {
  12474. targetType = mCurTypeInstance->mBaseType;
  12475. if (ctorDeclaration != NULL)
  12476. targetRefNode = ctorDeclaration->mThisToken;
  12477. else if (typeDef->mTypeDeclaration != NULL)
  12478. targetRefNode = typeDef->mTypeDeclaration->mNameNode;
  12479. }
  12480. }
  12481. }
  12482. if (methodDef->mHasAppend)
  12483. {
  12484. mCurMethodState->mCurAppendAlign = methodInstance->mAppendAllocAlign;
  12485. }
  12486. if (targetType != NULL)
  12487. {
  12488. auto autoComplete = mCompiler->GetAutoComplete();
  12489. auto wasCapturingMethodInfo = (autoComplete != NULL) && (autoComplete->mIsCapturingMethodMatchInfo);
  12490. if ((autoComplete != NULL) && (ctorDeclaration != NULL) && (ctorDeclaration->mInitializer != NULL))
  12491. {
  12492. auto invocationExpr = ctorDeclaration->mInitializer;
  12493. autoComplete->CheckInvocation(invocationExpr, invocationExpr->mOpenParen, invocationExpr->mCloseParen, invocationExpr->mCommas);
  12494. }
  12495. BfType* targetThisType = targetType;
  12496. auto target = Cast(targetRefNode, GetThis(), targetThisType);
  12497. BfExprEvaluator exprEvaluator(this);
  12498. BfResolvedArgs argValues;
  12499. if ((ctorDeclaration != NULL) && (ctorDeclaration->mInitializer != NULL))
  12500. {
  12501. argValues.Init(&ctorDeclaration->mInitializer->mArguments);
  12502. if (gDebugStuff)
  12503. {
  12504. OutputDebugStrF("Expr: %@ %d\n", argValues.mArguments->mVals, argValues.mArguments->mSize);
  12505. }
  12506. }
  12507. exprEvaluator.ResolveArgValues(argValues, BfResolveArgFlag_DeferParamEval);
  12508. BfTypedValue appendIdxVal;
  12509. if (methodDef->mHasAppend)
  12510. {
  12511. auto localVar = mCurMethodState->GetRootMethodState()->mLocals[1];
  12512. BF_ASSERT(localVar->mName == "appendIdx");
  12513. auto intRefType = CreateRefType(localVar->mResolvedType);
  12514. appendIdxVal = BfTypedValue(localVar->mValue, intRefType);
  12515. mCurMethodState->mCurAppendAlign = 1; // Don't make any assumptions about how the base leaves the alignment
  12516. }
  12517. exprEvaluator.MatchConstructor(targetRefNode, NULL, target, targetType, argValues, true, methodDef->mHasAppend, &appendIdxVal);
  12518. if (autoComplete != NULL)
  12519. {
  12520. if ((wasCapturingMethodInfo) && (!autoComplete->mIsCapturingMethodMatchInfo))
  12521. {
  12522. if (autoComplete->mMethodMatchInfo != NULL)
  12523. autoComplete->mIsCapturingMethodMatchInfo = true;
  12524. else
  12525. autoComplete->mIsCapturingMethodMatchInfo = false;
  12526. }
  12527. else
  12528. autoComplete->mIsCapturingMethodMatchInfo = false;
  12529. }
  12530. }
  12531. }
  12532. void BfModule::EmitEnumToStringBody()
  12533. {
  12534. auto stringType = ResolveTypeDef(mCompiler->mStringTypeDef);
  12535. auto strVal = CreateAlloca(stringType);
  12536. auto int64StructType = GetPrimitiveStructType(BfTypeCode_Int64);
  12537. BfExprEvaluator exprEvaluator(this);
  12538. auto stringDestAddr = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  12539. BfIRBlock appendBlock = mBfIRBuilder->CreateBlock("append");
  12540. BfIRBlock noMatchBlock = mBfIRBuilder->CreateBlock("noMatch");
  12541. BfIRBlock endBlock = mBfIRBuilder->CreateBlock("end");
  12542. BfType* discriminatorType = NULL;
  12543. BfTypedValue rawPayload;
  12544. BfIRValue enumVal;
  12545. if (mCurTypeInstance->IsPayloadEnum())
  12546. {
  12547. discriminatorType = mCurTypeInstance->GetDiscriminatorType();
  12548. auto enumTypedValue = ExtractValue(GetThis(), NULL, 2);
  12549. enumTypedValue = LoadValue(enumTypedValue);
  12550. enumVal = enumTypedValue.mValue;
  12551. rawPayload = ExtractValue(GetThis(), NULL, 1);
  12552. }
  12553. else
  12554. enumVal = mBfIRBuilder->GetArgument(0);
  12555. Array<BfType*> paramTypes;
  12556. paramTypes.Add(stringType);
  12557. auto appendModuleMethodInstance = GetMethodByName(stringType->ToTypeInstance(), "Append", paramTypes);
  12558. auto switchVal = mBfIRBuilder->CreateSwitch(enumVal, noMatchBlock, (int)mCurTypeInstance->mFieldInstances.size());
  12559. HashSet<int64> handledCases;
  12560. for (auto& fieldInstance : mCurTypeInstance->mFieldInstances)
  12561. {
  12562. if (fieldInstance.mIsEnumPayloadCase)
  12563. {
  12564. int tagId = -fieldInstance.mDataIdx - 1;
  12565. BfIRBlock caseBlock = mBfIRBuilder->CreateBlock("case");
  12566. mBfIRBuilder->AddBlock(caseBlock);
  12567. mBfIRBuilder->SetInsertPoint(caseBlock);
  12568. BF_ASSERT(discriminatorType->IsPrimitiveType());
  12569. auto constVal = mBfIRBuilder->CreateConst(((BfPrimitiveType*)discriminatorType)->mTypeDef->mTypeCode, tagId);
  12570. mBfIRBuilder->AddSwitchCase(switchVal, constVal, caseBlock);
  12571. auto caseStr = GetStringObjectValue(fieldInstance.GetFieldDef()->mName);
  12572. auto stringDestVal = LoadValue(stringDestAddr);
  12573. SizedArray<BfIRValue, 2> args;
  12574. args.Add(stringDestVal.mValue);
  12575. args.Add(caseStr);
  12576. exprEvaluator.CreateCall(appendModuleMethodInstance.mMethodInstance, appendModuleMethodInstance.mFunc, false, args);
  12577. auto payloadType = fieldInstance.mResolvedType->ToTypeInstance();
  12578. BF_ASSERT(payloadType->IsTuple());
  12579. if (payloadType->mFieldInstances.size() != 0)
  12580. {
  12581. auto payload = rawPayload;
  12582. if (payload.mType != payloadType)
  12583. {
  12584. payload = Cast(NULL, payload, payloadType, BfCastFlags_Force);
  12585. }
  12586. auto toStringMethod = GetMethodByName(payloadType->ToTypeInstance(), "ToString");
  12587. SizedArray<BfIRValue, 2> irArgs;
  12588. exprEvaluator.PushThis(NULL, payload, toStringMethod.mMethodInstance, irArgs);
  12589. stringDestVal = LoadValue(stringDestAddr);
  12590. irArgs.Add(stringDestVal.mValue);
  12591. exprEvaluator.CreateCall(toStringMethod.mMethodInstance, toStringMethod.mFunc, true, irArgs);
  12592. }
  12593. mBfIRBuilder->CreateBr(endBlock);
  12594. continue;
  12595. }
  12596. if (fieldInstance.mConstIdx == -1)
  12597. continue;
  12598. auto constant = mCurTypeInstance->mConstHolder->GetConstantById(fieldInstance.mConstIdx);
  12599. if (!handledCases.TryAdd(constant->mInt64, NULL))
  12600. {
  12601. // Duplicate
  12602. continue;
  12603. }
  12604. BfIRBlock caseBlock = mBfIRBuilder->CreateBlock("case");
  12605. mBfIRBuilder->AddBlock(caseBlock);
  12606. mBfIRBuilder->SetInsertPoint(caseBlock);
  12607. BfIRValue constVal = ConstantToCurrent(constant, mCurTypeInstance->mConstHolder, mCurTypeInstance);
  12608. mBfIRBuilder->AddSwitchCase(switchVal, constVal, caseBlock);
  12609. auto caseStr = GetStringObjectValue(fieldInstance.GetFieldDef()->mName);
  12610. mBfIRBuilder->CreateStore(caseStr, strVal);
  12611. mBfIRBuilder->CreateBr(appendBlock);
  12612. }
  12613. mBfIRBuilder->AddBlock(appendBlock);
  12614. mBfIRBuilder->SetInsertPoint(appendBlock);
  12615. SizedArray<BfIRValue, 2> args;
  12616. auto stringDestVal = LoadValue(stringDestAddr);
  12617. args.Add(stringDestVal.mValue);
  12618. args.Add(mBfIRBuilder->CreateLoad(strVal));
  12619. exprEvaluator.CreateCall(appendModuleMethodInstance.mMethodInstance, appendModuleMethodInstance.mFunc, false, args);
  12620. mBfIRBuilder->CreateBr(endBlock);
  12621. mBfIRBuilder->AddBlock(noMatchBlock);
  12622. mBfIRBuilder->SetInsertPoint(noMatchBlock);
  12623. auto int64Val = mBfIRBuilder->CreateNumericCast(enumVal, false, BfTypeCode_Int64);
  12624. auto toStringModuleMethodInstance = GetMethodByName(int64StructType, "ToString", 1);
  12625. args.clear();
  12626. args.Add(int64Val);
  12627. stringDestVal = LoadValue(stringDestAddr);
  12628. args.Add(stringDestVal.mValue);
  12629. exprEvaluator.CreateCall(toStringModuleMethodInstance.mMethodInstance, toStringModuleMethodInstance.mFunc, false, args);
  12630. mBfIRBuilder->CreateBr(endBlock);
  12631. mBfIRBuilder->AddBlock(endBlock);
  12632. mBfIRBuilder->SetInsertPoint(endBlock);
  12633. }
  12634. void BfModule::EmitTupleToStringBody()
  12635. {
  12636. auto stringType = ResolveTypeDef(mCompiler->mStringTypeDef);
  12637. BfExprEvaluator exprEvaluator(this);
  12638. auto stringDestRef = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  12639. Array<BfType*> paramTypes;
  12640. paramTypes.Add(GetPrimitiveType(BfTypeCode_Char8));
  12641. auto appendCharModuleMethodInstance = GetMethodByName(stringType->ToTypeInstance(), "Append", paramTypes);
  12642. paramTypes.Clear();
  12643. paramTypes.Add(stringType);
  12644. auto appendModuleMethodInstance = GetMethodByName(stringType->ToTypeInstance(), "Append", paramTypes);
  12645. auto _AppendChar = [&](char c)
  12646. {
  12647. SizedArray<BfIRValue, 2> args;
  12648. auto stringDestVal = LoadValue(stringDestRef);
  12649. args.Add(stringDestVal.mValue);
  12650. args.Add(mBfIRBuilder->CreateConst(BfTypeCode_Char8, (int)c));
  12651. exprEvaluator.CreateCall(appendCharModuleMethodInstance.mMethodInstance, appendCharModuleMethodInstance.mFunc, false, args);
  12652. };
  12653. int fieldIdx = 0;
  12654. auto thisValue = GetThis();
  12655. auto toStringModuleMethodInstance = GetMethodByName(mContext->mBfObjectType, "ToString", 1);
  12656. auto toStringSafeModuleMethodInstance = GetMethodByName(mContext->mBfObjectType, "ToString", 2);
  12657. BfIRValue commaStr;
  12658. auto iPrintableType = ResolveTypeDef(mCompiler->mIPrintableTypeDef)->ToTypeInstance();
  12659. auto printModuleMethodInstance = GetMethodByName(iPrintableType, "Print");
  12660. _AppendChar('(');
  12661. for (auto& fieldInstance : mCurTypeInstance->mFieldInstances)
  12662. {
  12663. if (fieldInstance.mDataIdx == -1)
  12664. continue;
  12665. if (fieldIdx > 0)
  12666. {
  12667. if (!commaStr)
  12668. commaStr = GetStringObjectValue(", ");
  12669. SizedArray<BfIRValue, 2> args;
  12670. auto stringDestVal = LoadValue(stringDestRef);
  12671. args.Add(stringDestVal.mValue);
  12672. args.Add(commaStr);
  12673. exprEvaluator.CreateCall(appendModuleMethodInstance.mMethodInstance, appendModuleMethodInstance.mFunc, false, args);
  12674. }
  12675. fieldIdx++;
  12676. if (fieldInstance.mResolvedType->IsValuelessType())
  12677. continue;
  12678. BfTypedValue fieldValue = ExtractValue(thisValue, &fieldInstance, fieldInstance.mDataIdx);
  12679. if (fieldValue.mType->IsPrimitiveType())
  12680. {
  12681. fieldValue.mType = GetPrimitiveStructType(((BfPrimitiveType*)fieldValue.mType)->mTypeDef->mTypeCode);
  12682. }
  12683. auto typeInstance = fieldValue.mType->ToTypeInstance();
  12684. if ((typeInstance != NULL) && (TypeIsSubTypeOf(typeInstance, iPrintableType, false)))
  12685. {
  12686. BfExprEvaluator exprEvaluator(this);
  12687. SizedArray<BfResolvedArg, 0> resolvedArgs;
  12688. BfMethodMatcher methodMatcher(NULL, this, printModuleMethodInstance.mMethodInstance, resolvedArgs);
  12689. methodMatcher.mBestMethodDef = printModuleMethodInstance.mMethodInstance->mMethodDef;
  12690. methodMatcher.mBestMethodTypeInstance = iPrintableType;
  12691. methodMatcher.TryDevirtualizeCall(fieldValue);
  12692. BfTypedValue callVal = Cast(NULL, fieldValue, methodMatcher.mBestMethodTypeInstance);
  12693. BfResolvedArg resolvedArg;
  12694. auto stringDestVal = LoadValue(stringDestRef);
  12695. resolvedArg.mTypedValue = stringDestVal;
  12696. resolvedArg.mResolvedType = stringDestVal.mType;
  12697. resolvedArgs.Add(resolvedArg);
  12698. exprEvaluator.CreateCall(&methodMatcher, callVal);
  12699. continue;
  12700. }
  12701. if (fieldValue.mType->IsObjectOrInterface())
  12702. {
  12703. BF_ASSERT(!fieldValue.IsAddr());
  12704. SizedArray<BfIRValue, 2> args;
  12705. args.Add(mBfIRBuilder->CreateBitCast(fieldValue.mValue, mBfIRBuilder->MapType(mContext->mBfObjectType)));
  12706. auto stringDestVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  12707. stringDestVal = LoadValue(stringDestVal);
  12708. args.Add(stringDestVal.mValue);
  12709. exprEvaluator.CreateCall(toStringSafeModuleMethodInstance.mMethodInstance, toStringSafeModuleMethodInstance.mFunc, false, args);
  12710. continue;
  12711. }
  12712. BfExprEvaluator exprEvaluator(this);
  12713. SizedArray<BfResolvedArg, 0> resolvedArgs;
  12714. BfMethodMatcher methodMatcher(NULL, this, toStringModuleMethodInstance.mMethodInstance, resolvedArgs);
  12715. methodMatcher.mBestMethodDef = toStringModuleMethodInstance.mMethodInstance->mMethodDef;
  12716. methodMatcher.mBestMethodTypeInstance = mContext->mBfObjectType;
  12717. methodMatcher.TryDevirtualizeCall(fieldValue);
  12718. if (methodMatcher.mBestMethodTypeInstance == mContext->mBfObjectType)
  12719. {
  12720. AddCallDependency(appendModuleMethodInstance.mMethodInstance);
  12721. AddDependency(fieldValue.mType, mCurTypeInstance, BfDependencyMap::DependencyFlag_Calls);
  12722. // Just append the type name
  12723. String typeName = TypeToString(fieldInstance.mResolvedType);
  12724. auto strVal = GetStringObjectValue(typeName);
  12725. SizedArray<BfIRValue, 2> args;
  12726. auto stringDestVal = LoadValue(stringDestRef);
  12727. args.Add(stringDestVal.mValue);
  12728. args.Add(strVal);
  12729. exprEvaluator.CreateCall(appendModuleMethodInstance.mMethodInstance, appendModuleMethodInstance.mFunc, false, args);
  12730. continue;
  12731. }
  12732. BfTypedValue callVal = Cast(NULL, fieldValue, methodMatcher.mBestMethodTypeInstance);
  12733. BfResolvedArg resolvedArg;
  12734. auto stringDestVal = LoadValue(stringDestRef);
  12735. resolvedArg.mTypedValue = stringDestVal;
  12736. resolvedArg.mResolvedType = stringDestVal.mType;
  12737. resolvedArgs.Add(resolvedArg);
  12738. exprEvaluator.CreateCall(&methodMatcher, callVal);
  12739. }
  12740. _AppendChar(')');
  12741. }
  12742. void BfModule::EmitIteratorBlock(bool& skipBody)
  12743. {
  12744. auto methodInstance = mCurMethodInstance;
  12745. auto methodDef = methodInstance->mMethodDef;
  12746. auto methodDeclaration = methodDef->GetMethodDeclaration();
  12747. auto typeDef = mCurTypeInstance->mTypeDef;
  12748. BfType* innerRetType = NULL;
  12749. BfTypeInstance* usingInterface = NULL;
  12750. auto retTypeInst = mCurMethodInstance->mReturnType->ToGenericTypeInstance();
  12751. if (retTypeInst != NULL)
  12752. {
  12753. if ((retTypeInst->mTypeDef == mCompiler->mGenericIEnumerableTypeDef) ||
  12754. (retTypeInst->mTypeDef == mCompiler->mGenericIEnumeratorTypeDef))
  12755. {
  12756. innerRetType = retTypeInst->mTypeGenericArguments[0];
  12757. }
  12758. }
  12759. if (innerRetType == NULL)
  12760. {
  12761. Fail("Methods with yields must return either System.IEnumerable<T> or System.IEnumerator<T>", methodDeclaration->mReturnType);
  12762. return;
  12763. }
  12764. auto blockBody = BfNodeDynCast<BfBlock>(methodDeclaration->mBody);
  12765. if (blockBody == NULL)
  12766. return;
  12767. }
  12768. void BfModule::EmitGCMarkValue(BfTypedValue markVal, BfModuleMethodInstance markFromGCThreadMethodInstance)
  12769. {
  12770. auto fieldTypeInst = markVal.mType->ToTypeInstance();
  12771. if (fieldTypeInst == NULL)
  12772. return;
  12773. if (!markVal.mType->IsComposite())
  12774. markVal = LoadValue(markVal);
  12775. BfExprEvaluator exprEvaluator(this);
  12776. PopulateType(markVal.mType, BfPopulateType_Data);
  12777. if (markVal.mType->IsObjectOrInterface())
  12778. {
  12779. BfIRValue val = markVal.mValue;
  12780. val = mBfIRBuilder->CreateBitCast(val, mBfIRBuilder->MapType(mContext->mBfObjectType));
  12781. SizedArray<BfIRValue, 1> args;
  12782. args.push_back(val);
  12783. exprEvaluator.CreateCall(markFromGCThreadMethodInstance.mMethodInstance, markFromGCThreadMethodInstance.mFunc, false, args);
  12784. }
  12785. else if ((fieldTypeInst->IsComposite()) && (!fieldTypeInst->IsTypedPrimitive()))
  12786. {
  12787. auto markMemberMethodInstance = GetMethodByName(fieldTypeInst, BF_METHODNAME_MARKMEMBERS, 0, true);
  12788. if (markMemberMethodInstance)
  12789. {
  12790. SizedArray<BfIRValue, 1> args;
  12791. //(1, markVal.mValue);
  12792. //exprEvaluator.PushArg(markVal, args);
  12793. exprEvaluator.PushThis(NULL, markVal, markMemberMethodInstance.mMethodInstance, args);
  12794. exprEvaluator.CreateCall(markMemberMethodInstance.mMethodInstance, markMemberMethodInstance.mFunc, false, args);
  12795. }
  12796. }
  12797. }
  12798. void BfModule::CallChainedMethods(BfMethodInstance* methodInstance, bool reverse)
  12799. {
  12800. Array<BfMethodInstance*> methodInstances;
  12801. for (int methodIdx = 0; methodIdx < (int)mCurTypeInstance->mMethodInstanceGroups.size(); methodIdx++)
  12802. {
  12803. auto& methodInstGroup = mCurTypeInstance->mMethodInstanceGroups[methodIdx];
  12804. auto chainedMethodInst = methodInstGroup.mDefault;
  12805. if ((chainedMethodInst != NULL) && (chainedMethodInst->mChainType == BfMethodChainType_ChainMember))
  12806. {
  12807. if ((chainedMethodInst->mMethodDef->mIsStatic == methodInstance->mMethodDef->mIsStatic) &&
  12808. (CompareMethodSignatures(methodInstance, chainedMethodInst)))
  12809. {
  12810. methodInstances.push_back(chainedMethodInst);
  12811. }
  12812. }
  12813. }
  12814. std::stable_sort(methodInstances.begin(), methodInstances.end(),
  12815. [&](BfMethodInstance* lhs, BfMethodInstance* rhs)
  12816. {
  12817. bool isBetter;
  12818. bool isWorse;
  12819. CompareDeclTypes(lhs->mMethodDef->mDeclaringType, rhs->mMethodDef->mDeclaringType, isBetter, isWorse);
  12820. if (isBetter == isWorse)
  12821. {
  12822. return false;
  12823. }
  12824. return isWorse;
  12825. });
  12826. if (reverse)
  12827. std::reverse(methodInstances.begin(), methodInstances.end());
  12828. for (auto chainedMethodInst : methodInstances)
  12829. {
  12830. auto declModule = this;
  12831. BfGetMethodInstanceFlags flags = BfGetMethodInstanceFlag_None;
  12832. auto moduleMethodInst = declModule->GetMethodInstance(mCurTypeInstance, chainedMethodInst->mMethodDef, BfTypeVector(), flags);
  12833. BfExprEvaluator exprEvaluator(this);
  12834. SizedArray<BfIRValue, 1> args;
  12835. exprEvaluator.PushThis(chainedMethodInst->mMethodDef->GetRefNode(), GetThis(), chainedMethodInst, args);
  12836. exprEvaluator.CreateCall(moduleMethodInst.mMethodInstance, moduleMethodInst.mFunc, true, args);
  12837. }
  12838. }
  12839. void BfModule::AddHotDataReferences(BfHotDataReferenceBuilder* builder)
  12840. {
  12841. BF_ASSERT(mCurMethodInstance->mIsReified);
  12842. if (mCurTypeInstance->mHotTypeData == NULL)
  12843. mCurTypeInstance->mHotTypeData = new BfHotTypeData();
  12844. auto hotMethod = mCurMethodInstance->mHotMethod;
  12845. for (auto depData : hotMethod->mReferences)
  12846. {
  12847. // Only virtual decls are allowed to already be there
  12848. BF_ASSERT((depData->mDataKind == BfHotDepDataKind_VirtualDecl) || (depData->mDataKind == BfHotDepDataKind_DupMethod));
  12849. }
  12850. BF_ASSERT(hotMethod->mSrcTypeVersion != NULL);
  12851. int prevSize = (int)hotMethod->mReferences.size();
  12852. int refCount = (int)(prevSize + builder->mUsedData.size() + builder->mCalledMethods.size() + builder->mDevirtualizedCalledMethods.size());
  12853. if (!mCurMethodInstance->mMethodDef->mIsStatic)
  12854. refCount++;
  12855. hotMethod->mReferences.Reserve(refCount);
  12856. if (!mCurMethodInstance->mMethodDef->mIsStatic)
  12857. {
  12858. auto hotThis = mCompiler->mHotData->GetThisType(mCurMethodInstance->GetOwner()->mHotTypeData->GetLatestVersion());
  12859. hotThis->mRefCount++;
  12860. hotMethod->mReferences.Insert(0, hotThis);
  12861. prevSize++;
  12862. }
  12863. for (auto val : builder->mAllocatedData)
  12864. {
  12865. auto hotAllocation = mCompiler->mHotData->GetAllocation(val);
  12866. hotMethod->mReferences.Add(hotAllocation);
  12867. }
  12868. for (auto val : builder->mUsedData)
  12869. hotMethod->mReferences.Add(val);
  12870. for (auto val : builder->mCalledMethods)
  12871. hotMethod->mReferences.Add(val);
  12872. for (auto val : builder->mDevirtualizedCalledMethods)
  12873. {
  12874. auto devirtualizedMethod = mCompiler->mHotData->GetDevirtualizedMethod(val);
  12875. hotMethod->mReferences.Add(devirtualizedMethod);
  12876. }
  12877. for (auto val : builder->mFunctionPtrs)
  12878. {
  12879. auto funcRef = mCompiler->mHotData->GetFunctionReference(val);
  12880. hotMethod->mReferences.Add(funcRef);
  12881. }
  12882. for (auto val : builder->mInnerMethods)
  12883. {
  12884. auto innerMethod = mCompiler->mHotData->GetInnerMethod(val);
  12885. hotMethod->mReferences.Add(innerMethod);
  12886. }
  12887. for (int refIdx = prevSize; refIdx < (int)hotMethod->mReferences.size(); refIdx++)
  12888. {
  12889. auto depData = hotMethod->mReferences[refIdx];
  12890. BF_ASSERT(depData != NULL);
  12891. depData->mRefCount++;
  12892. }
  12893. //hotMethod->mReferences.Sort([](BfHotDepData* lhs, BfHotDepData* rhs) { return lhs < rhs; });
  12894. }
  12895. void BfModule::ProcessMethod_SetupParams(BfMethodInstance* methodInstance, BfType* thisType, bool wantsDIData, SizedArrayImpl<BfIRMDNode>* diParams)
  12896. {
  12897. auto methodDef = methodInstance->mMethodDef;
  12898. auto methodDeclaration = methodDef->mMethodDeclaration;
  12899. bool isThisStruct = false;
  12900. if (thisType != NULL)
  12901. isThisStruct = thisType->IsStruct() && !thisType->IsTypedPrimitive();
  12902. int argIdx = 0;
  12903. if (methodInstance->HasStructRet())
  12904. argIdx++;
  12905. if (!methodDef->mIsStatic)
  12906. {
  12907. BfLocalVariable* paramVar = new BfLocalVariable();
  12908. paramVar->mResolvedType = thisType;
  12909. paramVar->mName = "this";
  12910. if (!thisType->IsValuelessType())
  12911. paramVar->mValue = mBfIRBuilder->GetArgument(argIdx);
  12912. else
  12913. paramVar->mValue = mBfIRBuilder->GetFakeVal();
  12914. if ((thisType->IsComposite()) && (!methodDef->HasNoThisSplat()))
  12915. {
  12916. if (thisType->IsSplattable())
  12917. paramVar->mIsSplat = true;
  12918. else
  12919. paramVar->mIsLowered = thisType->GetLoweredType() != BfTypeCode_None;
  12920. }
  12921. auto thisTypeInst = thisType->ToTypeInstance();
  12922. paramVar->mIsStruct = isThisStruct;
  12923. paramVar->mAddr = BfIRValue();
  12924. paramVar->mIsThis = true;
  12925. paramVar->mParamIdx = -1;
  12926. if ((methodDef->mMethodType == BfMethodType_Ctor) && (mCurTypeInstance->IsStruct()))
  12927. {
  12928. paramVar->mIsAssigned = false;
  12929. }
  12930. else
  12931. {
  12932. paramVar->mIsAssigned = true;
  12933. }
  12934. paramVar->mReadFromId = -1;
  12935. paramVar->Init();
  12936. if (methodDeclaration == NULL)
  12937. UseDefaultSrcPos();
  12938. AddLocalVariableDef(paramVar);
  12939. if (!thisType->IsValuelessType())
  12940. {
  12941. if (wantsDIData)
  12942. {
  12943. BfType* thisPtrType = thisType;
  12944. auto diType = mBfIRBuilder->DbgGetType(thisPtrType);
  12945. if (!thisType->IsValueType())
  12946. diType = mBfIRBuilder->DbgCreateArtificialType(diType);
  12947. diParams->push_back(diType);
  12948. }
  12949. if (paramVar->mIsSplat)
  12950. {
  12951. BfTypeUtils::SplatIterate([&](BfType* checkType) { argIdx++; }, paramVar->mResolvedType);
  12952. }
  12953. else
  12954. {
  12955. argIdx++;
  12956. }
  12957. }
  12958. }
  12959. bool hadParams = false;
  12960. bool hasDefault = false;
  12961. int compositeVariableIdx = -1;
  12962. int paramIdx = 0;
  12963. for (paramIdx = 0; paramIdx < methodInstance->GetParamCount(); paramIdx++)
  12964. {
  12965. // We already issues a type error for this param if we had one in declaration processing
  12966. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, true);
  12967. BfLocalVariable* paramVar = new BfLocalVariable();
  12968. bool isParamSkipped = methodInstance->IsParamSkipped(paramIdx);
  12969. BfType* unresolvedType = methodInstance->GetParamType(paramIdx, false);
  12970. if (unresolvedType == NULL)
  12971. {
  12972. AssertErrorState();
  12973. unresolvedType = mContext->mBfObjectType;
  12974. paramVar->mParamFailed = true;
  12975. }
  12976. auto resolvedType = methodInstance->GetParamType(paramIdx, true);
  12977. prevIgnoreErrors.Restore();
  12978. PopulateType(resolvedType, BfPopulateType_Declaration);
  12979. paramVar->mResolvedType = resolvedType;
  12980. paramVar->mName = methodInstance->GetParamName(paramIdx);
  12981. paramVar->mNameNode = methodInstance->GetParamNameNode(paramIdx);
  12982. if (!isParamSkipped)
  12983. {
  12984. paramVar->mValue = mBfIRBuilder->GetArgument(argIdx);
  12985. if (resolvedType->IsMethodRef())
  12986. {
  12987. paramVar->mIsSplat = true;
  12988. }
  12989. else if (resolvedType->IsComposite() && resolvedType->IsSplattable())
  12990. {
  12991. int splatCount = resolvedType->GetSplatCount();
  12992. if (argIdx + splatCount <= mCompiler->mOptions.mMaxSplatRegs)
  12993. paramVar->mIsSplat = true;
  12994. }
  12995. }
  12996. else
  12997. {
  12998. paramVar->mIsSplat = true; // Treat skipped (valueless) as a splat
  12999. paramVar->mValue = mBfIRBuilder->GetFakeVal();
  13000. }
  13001. paramVar->mIsLowered = resolvedType->GetLoweredType() != BfTypeCode_None;
  13002. paramVar->mIsStruct = resolvedType->IsComposite() && !resolvedType->IsTypedPrimitive();
  13003. paramVar->mParamIdx = paramIdx;
  13004. paramVar->mIsImplicitParam = methodInstance->IsImplicitCapture(paramIdx);
  13005. paramVar->mReadFromId = 0;
  13006. if (resolvedType->IsRef())
  13007. {
  13008. auto refType = (BfRefType*)resolvedType;
  13009. paramVar->mIsAssigned = refType->mRefKind != BfRefType::RefKind_Out;
  13010. }
  13011. else
  13012. {
  13013. paramVar->mIsAssigned = true;
  13014. if (methodDef->mMethodType != BfMethodType_Mixin)
  13015. paramVar->mIsReadOnly = true;
  13016. }
  13017. if (paramVar->mResolvedType->IsGenericParam())
  13018. {
  13019. auto genericParamInst = GetGenericParamInstance((BfGenericParamType*)paramVar->mResolvedType);
  13020. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  13021. {
  13022. auto typedVal = GetDefaultTypedValue(genericParamInst->mTypeConstraint, false, BfDefaultValueKind_Undef);
  13023. paramVar->mResolvedType = typedVal.mType;
  13024. paramVar->mConstValue = typedVal.mValue;
  13025. }
  13026. }
  13027. if (paramVar->mResolvedType->IsConstExprValue())
  13028. {
  13029. BfConstExprValueType* constExprValueType = (BfConstExprValueType*)paramVar->mResolvedType;
  13030. auto unspecializedMethodInstance = GetUnspecializedMethodInstance(methodInstance);
  13031. auto unspecParamType = unspecializedMethodInstance->GetParamType(paramIdx);
  13032. BF_ASSERT(unspecParamType->IsGenericParam());
  13033. if (unspecParamType->IsGenericParam())
  13034. {
  13035. BfGenericParamType* genericParamType = (BfGenericParamType*)unspecParamType;
  13036. if (genericParamType->mGenericParamKind == BfGenericParamKind_Method)
  13037. {
  13038. auto genericParamInst = unspecializedMethodInstance->mMethodInfoEx->mGenericParams[genericParamType->mGenericParamIdx];
  13039. if (genericParamInst->mTypeConstraint != NULL)
  13040. {
  13041. BfExprEvaluator exprEvaluator(this);
  13042. exprEvaluator.mExpectingType = genericParamInst->mTypeConstraint;
  13043. exprEvaluator.GetLiteral(NULL, constExprValueType->mValue);
  13044. auto checkType = genericParamInst->mTypeConstraint;
  13045. if (checkType->IsTypedPrimitive())
  13046. checkType = checkType->GetUnderlyingType();
  13047. if (exprEvaluator.mResult.mType == checkType)
  13048. {
  13049. paramVar->mResolvedType = genericParamInst->mTypeConstraint;
  13050. paramVar->mConstValue = exprEvaluator.mResult.mValue;
  13051. BF_ASSERT(paramVar->mConstValue.IsConst());
  13052. }
  13053. else
  13054. {
  13055. AssertErrorState();
  13056. paramVar->mResolvedType = genericParamInst->mTypeConstraint;
  13057. paramVar->mConstValue = GetDefaultValue(genericParamInst->mTypeConstraint);
  13058. }
  13059. }
  13060. }
  13061. }
  13062. //BF_ASSERT(!paramVar->mResolvedType->IsConstExprValue());
  13063. if (paramVar->mResolvedType->IsConstExprValue())
  13064. {
  13065. Fail("Invalid use of constant expression", methodInstance->GetParamTypeRef(paramIdx));
  13066. //AssertErrorState();
  13067. paramVar->mResolvedType = GetPrimitiveType(BfTypeCode_IntPtr);
  13068. paramVar->mConstValue = GetDefaultValue(paramVar->mResolvedType);
  13069. }
  13070. }
  13071. if (methodInstance->GetParamKind(paramIdx) == BfParamKind_DelegateParam)
  13072. {
  13073. if (compositeVariableIdx == -1)
  13074. {
  13075. compositeVariableIdx = (int)mCurMethodState->mLocals.size();
  13076. BfLocalVariable* localVar = new BfLocalVariable();
  13077. auto paramInst = &methodInstance->mParams[paramIdx];
  13078. auto paramDef = methodDef->mParams[paramInst->mParamDefIdx];
  13079. localVar->mName = paramDef->mName;
  13080. localVar->mResolvedType = ResolveTypeRef(paramDef->mTypeRef, BfPopulateType_Declaration, BfResolveTypeRefFlag_NoResolveGenericParam);
  13081. localVar->mCompositeCount = 0;
  13082. DoAddLocalVariable(localVar);
  13083. }
  13084. mCurMethodState->mLocals[compositeVariableIdx]->mCompositeCount++;
  13085. }
  13086. CheckVariableDef(paramVar);
  13087. paramVar->Init();
  13088. AddLocalVariableDef(paramVar);
  13089. if (!isParamSkipped)
  13090. {
  13091. if (wantsDIData)
  13092. diParams->push_back(mBfIRBuilder->DbgGetType(resolvedType));
  13093. if (paramVar->mIsSplat)
  13094. {
  13095. BfTypeUtils::SplatIterate([&](BfType* checkType) { argIdx++; }, paramVar->mResolvedType);
  13096. }
  13097. else
  13098. {
  13099. argIdx++;
  13100. }
  13101. }
  13102. }
  13103. // Try to find an ending delegate params composite
  13104. if ((compositeVariableIdx == -1) && (methodDef->mParams.size() > 0))
  13105. {
  13106. auto paramDef = methodDef->mParams.back();
  13107. if (paramDef->mParamKind == BfParamKind_Params)
  13108. {
  13109. auto paramsType = ResolveTypeRef(paramDef->mTypeRef, BfPopulateType_Declaration, BfResolveTypeRefFlag_NoResolveGenericParam);
  13110. if (paramsType == NULL)
  13111. {
  13112. AssertErrorState();
  13113. }
  13114. else if (paramsType->IsGenericParam())
  13115. {
  13116. auto genericParamInstance = GetGenericParamInstance((BfGenericParamType*)paramsType);
  13117. if (genericParamInstance->mTypeConstraint != NULL)
  13118. {
  13119. auto typeInstConstraint = genericParamInstance->mTypeConstraint->ToTypeInstance();
  13120. if ((genericParamInstance->mTypeConstraint->IsDelegate()) || (genericParamInstance->mTypeConstraint->IsFunction()) ||
  13121. ((typeInstConstraint != NULL) &&
  13122. ((typeInstConstraint->mTypeDef == mCompiler->mDelegateTypeDef) || (typeInstConstraint->mTypeDef == mCompiler->mFunctionTypeDef))))
  13123. {
  13124. BfLocalVariable* localVar = new BfLocalVariable();
  13125. localVar->mName = paramDef->mName;
  13126. localVar->mResolvedType = paramsType;
  13127. localVar->mCompositeCount = 0;
  13128. DoAddLocalVariable(localVar);
  13129. }
  13130. }
  13131. }
  13132. else if (paramsType->IsDelegate())
  13133. {
  13134. BfMethodInstance* invokeMethodInstance = GetRawMethodInstanceAtIdx(paramsType->ToTypeInstance(), 0, "Invoke");
  13135. if (invokeMethodInstance != NULL)
  13136. {
  13137. // This is only for the case where the delegate didn't actually have any params so the composite is zero-sized
  13138. // and wasn't cleared by the preceding loop
  13139. BF_ASSERT(invokeMethodInstance->GetParamCount() == 0);
  13140. BfLocalVariable* localVar = new BfLocalVariable();
  13141. localVar->mName = paramDef->mName;
  13142. localVar->mResolvedType = paramsType;
  13143. localVar->mCompositeCount = 0;
  13144. DoAddLocalVariable(localVar);
  13145. }
  13146. }
  13147. }
  13148. }
  13149. }
  13150. void BfModule::ProcessMethod_ProcessDeferredLocals(int startIdx)
  13151. {
  13152. // if (mCurMethodState->mPrevMethodState != NULL) // Re-entry
  13153. // return;
  13154. auto _ClearState = [&]()
  13155. {
  13156. mCurMethodState->mLocalMethods.Clear();
  13157. for (auto& local : mCurMethodState->mLocals)
  13158. delete local;
  13159. mCurMethodState->mLocals.Clear();
  13160. mCurMethodState->mLocalVarSet.Clear();
  13161. };
  13162. // 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
  13163. // we show errors in the capture phase. If we somehow pass the capture phase without error then this method WILL show any errors here,
  13164. // however (compiler bug), so this is the safest way
  13165. if (!mCurMethodState->mDeferredLocalMethods.IsEmpty())
  13166. {
  13167. for (int deferredLocalMethodIdx = 0; deferredLocalMethodIdx < (int)mCurMethodState->mDeferredLocalMethods.size(); deferredLocalMethodIdx++)
  13168. {
  13169. auto deferredLocalMethod = mCurMethodState->mDeferredLocalMethods[deferredLocalMethodIdx];
  13170. BfLogSysM("Processing deferred local method %p\n", deferredLocalMethod);
  13171. if (!mHadBuildError)
  13172. {
  13173. // Process as a closure - that allows us to look back and see the const locals and stuff
  13174. BfClosureState closureState;
  13175. mCurMethodState->mClosureState = &closureState;
  13176. closureState.mConstLocals = deferredLocalMethod->mConstLocals;
  13177. closureState.mReturnType = deferredLocalMethod->mMethodInstance->mReturnType;
  13178. closureState.mActiveDeferredLocalMethod = deferredLocalMethod;
  13179. closureState.mLocalMethod = deferredLocalMethod->mLocalMethod;
  13180. if (deferredLocalMethod->mMethodInstance->mMethodInfoEx != NULL)
  13181. closureState.mClosureInstanceInfo = deferredLocalMethod->mMethodInstance->mMethodInfoEx->mClosureInstanceInfo;
  13182. mCurMethodState->mMixinState = deferredLocalMethod->mLocalMethod->mDeclMixinState;
  13183. _ClearState();
  13184. for (auto& constLocal : deferredLocalMethod->mConstLocals)
  13185. {
  13186. auto localVar = new BfLocalVariable();
  13187. *localVar = constLocal;
  13188. DoAddLocalVariable(localVar);
  13189. }
  13190. mCurMethodState->mLocalMethods = deferredLocalMethod->mLocalMethods;
  13191. bool doProcess = !mCompiler->mCanceling;
  13192. if (doProcess)
  13193. {
  13194. BP_ZONE_F("ProcessMethod local %s", deferredLocalMethod->mMethodInstance->mMethodDef->mName.c_str());
  13195. ProcessMethod(deferredLocalMethod->mMethodInstance);
  13196. }
  13197. }
  13198. delete deferredLocalMethod;
  13199. mSystem->CheckLockYield();
  13200. }
  13201. }
  13202. for (auto& kv : mCurMethodState->mLocalMethodCache)
  13203. {
  13204. BF_ASSERT((kv.mValue->mMethodDef == NULL) || (kv.mKey == kv.mValue->mMethodDef->mName));
  13205. }
  13206. if ((!mCurMethodState->mDeferredLambdaInstances.IsEmpty()) && (!mHadBuildError))
  13207. {
  13208. for (int deferredLambdaIdx = 0; deferredLambdaIdx < (int)mCurMethodState->mDeferredLambdaInstances.size(); deferredLambdaIdx++)
  13209. {
  13210. auto lambdaInstance = mCurMethodState->mDeferredLambdaInstances[deferredLambdaIdx];
  13211. BfLogSysM("Processing deferred lambdaInstance %p\n", lambdaInstance);
  13212. BfClosureState closureState;
  13213. mCurMethodState->mClosureState = &closureState;
  13214. //closureState.mConstLocals = deferredLocalMethod->mConstLocals;
  13215. closureState.mReturnType = lambdaInstance->mMethodInstance->mReturnType;
  13216. if (lambdaInstance->mClosureTypeInstance != NULL)
  13217. closureState.mClosureType = lambdaInstance->mClosureTypeInstance;
  13218. else
  13219. closureState.mClosureType = lambdaInstance->mDelegateTypeInstance;
  13220. closureState.mClosureInstanceInfo = lambdaInstance->mMethodInstance->mMethodInfoEx->mClosureInstanceInfo;
  13221. closureState.mDeclaringMethodIsMutating = lambdaInstance->mDeclaringMethodIsMutating;
  13222. mCurMethodState->mMixinState = lambdaInstance->mDeclMixinState;
  13223. _ClearState();
  13224. for (auto& constLocal : lambdaInstance->mConstLocals)
  13225. {
  13226. //if (constLocal.mIsThis)
  13227. {
  13228. // Valueless 'this'
  13229. closureState.mConstLocals.Add(constLocal);
  13230. }
  13231. /*else
  13232. {
  13233. auto localVar = new BfLocalVariable();
  13234. *localVar = constLocal;
  13235. DoAddLocalVariable(localVar);
  13236. }*/
  13237. }
  13238. BfMethodInstanceGroup methodInstanceGroup;
  13239. methodInstanceGroup.mOwner = mCurTypeInstance;
  13240. methodInstanceGroup.mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  13241. bool doProcess = !mCompiler->mCanceling;
  13242. if (doProcess)
  13243. {
  13244. BP_ZONE_F("ProcessMethod lambdaInstance %s", lambdaInstance->mMethodInstance->mMethodDef->mName.c_str());
  13245. lambdaInstance->mMethodInstance->mMethodInstanceGroup = &methodInstanceGroup;
  13246. ProcessMethod(lambdaInstance->mMethodInstance);
  13247. if (lambdaInstance->mDtorMethodInstance != NULL)
  13248. {
  13249. lambdaInstance->mDtorMethodInstance->mMethodInstanceGroup = &methodInstanceGroup;
  13250. ProcessMethod(lambdaInstance->mDtorMethodInstance);
  13251. }
  13252. }
  13253. }
  13254. mSystem->CheckLockYield();
  13255. }
  13256. }
  13257. void BfModule::EmitGCMarkValue(BfTypedValue& thisValue, BfType* checkType, int memberDepth, int curOffset, HashSet<int>& objectOffsets, BfModuleMethodInstance markFromGCThreadMethodInstance)
  13258. {
  13259. if (checkType->IsComposite())
  13260. PopulateType(checkType, BfPopulateType_Data);
  13261. if (!checkType->WantsGCMarking())
  13262. return;
  13263. auto typeInstance = checkType->ToTypeInstance();
  13264. bool callMarkMethod = false;
  13265. // Call the actual marking method
  13266. if (memberDepth == 0)
  13267. {
  13268. // Don't call marking method on self
  13269. }
  13270. else if (checkType->IsObjectOrInterface())
  13271. {
  13272. if (!objectOffsets.Add(curOffset))
  13273. {
  13274. return;
  13275. }
  13276. callMarkMethod = true;
  13277. }
  13278. else if (checkType->IsSizedArray())
  13279. {
  13280. callMarkMethod = true;
  13281. }
  13282. else if (typeInstance != NULL)
  13283. {
  13284. typeInstance->mTypeDef->PopulateMemberSets();
  13285. BfMemberSetEntry* entry = NULL;
  13286. BfMethodDef* methodDef = NULL;
  13287. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(String(BF_METHODNAME_MARKMEMBERS), &entry))
  13288. {
  13289. methodDef = (BfMethodDef*)entry->mMemberDef;
  13290. if (methodDef->HasBody())
  13291. {
  13292. callMarkMethod = true;
  13293. }
  13294. }
  13295. }
  13296. if (callMarkMethod)
  13297. {
  13298. BfTypedValue markValue;
  13299. auto memberType = checkType;
  13300. if (memberType->IsObjectOrInterface())
  13301. memberType = mContext->mBfObjectType; // Just to avoid that extra cast for the call itself
  13302. auto memberPtrType = CreatePointerType(memberType);
  13303. if (curOffset == 0)
  13304. {
  13305. markValue = BfTypedValue(mBfIRBuilder->CreateBitCast(thisValue.mValue, mBfIRBuilder->MapType(memberPtrType)), memberType, true);
  13306. }
  13307. else
  13308. {
  13309. if (!thisValue.mType->IsPointer())
  13310. {
  13311. auto int8Type = GetPrimitiveType(BfTypeCode_UInt8);
  13312. auto int8PtrType = CreatePointerType(int8Type);
  13313. thisValue = BfTypedValue(mBfIRBuilder->CreateBitCast(thisValue.mValue, mBfIRBuilder->MapType(int8PtrType)), int8PtrType);
  13314. }
  13315. auto offsetValue = mBfIRBuilder->CreateInBoundsGEP(thisValue.mValue, curOffset);
  13316. markValue = BfTypedValue(mBfIRBuilder->CreateBitCast(offsetValue, mBfIRBuilder->MapType(memberPtrType)), memberType, true);
  13317. }
  13318. EmitGCMarkValue(markValue, markFromGCThreadMethodInstance);
  13319. return;
  13320. }
  13321. auto methodDef = mCurMethodInstance->mMethodDef;
  13322. if (checkType->IsPayloadEnum())
  13323. {
  13324. for (auto& fieldInst : typeInstance->mFieldInstances)
  13325. {
  13326. if (!fieldInst.mIsEnumPayloadCase)
  13327. continue;
  13328. auto fieldDef = fieldInst.GetFieldDef();
  13329. EmitGCMarkValue(thisValue, fieldInst.mResolvedType, memberDepth + 1, curOffset, objectOffsets, markFromGCThreadMethodInstance);
  13330. }
  13331. return;
  13332. }
  13333. if (typeInstance == NULL)
  13334. return;
  13335. for (auto& fieldInst : typeInstance->mFieldInstances)
  13336. {
  13337. auto fieldDef = fieldInst.GetFieldDef();
  13338. if (fieldDef == NULL)
  13339. continue;
  13340. if (fieldDef->mIsStatic)
  13341. continue;
  13342. if (typeInstance == mCurTypeInstance)
  13343. {
  13344. // Note: we don't do method chaining when we are marking members of members. Theoretically this means
  13345. // we may be marking member values that can never contain a value anyway, but this is benign
  13346. if ((fieldDef->mDeclaringType->mTypeDeclaration != methodDef->mDeclaringType->mTypeDeclaration))
  13347. continue;
  13348. }
  13349. EmitGCMarkValue(thisValue, fieldInst.mResolvedType, memberDepth + 1, curOffset + fieldInst.mDataOffset, objectOffsets, markFromGCThreadMethodInstance);
  13350. }
  13351. if ((typeInstance->mBaseType != NULL) && (typeInstance->mBaseType != mContext->mBfObjectType))
  13352. {
  13353. EmitGCMarkValue(thisValue, typeInstance->mBaseType, memberDepth, curOffset, objectOffsets, markFromGCThreadMethodInstance);
  13354. }
  13355. }
  13356. void BfModule::EmitGCMarkMembers()
  13357. {
  13358. auto methodDef = mCurMethodInstance->mMethodDef;
  13359. auto gcType = ResolveTypeDef(mCompiler->mGCTypeDef, BfPopulateType_DataAndMethods);
  13360. BfModuleMethodInstance markFromGCThreadMethodInstance;
  13361. if (gcType != NULL)
  13362. markFromGCThreadMethodInstance = GetMethodByName(gcType->ToTypeInstance(), "Mark", 1);
  13363. if ((markFromGCThreadMethodInstance.mMethodInstance != NULL) && (!mCurMethodInstance->mIsUnspecialized))
  13364. {
  13365. if (mCurTypeInstance->IsBoxed())
  13366. {
  13367. // This already gets filled in by the normal boxed forwarding
  13368. }
  13369. else
  13370. {
  13371. auto thisValue = GetThis();
  13372. if (thisValue.IsSplat())
  13373. {
  13374. BfIRFunction func = mCurMethodInstance->mIRFunction;
  13375. int argIdx = 0;
  13376. std::function<void(BfType*)> checkTypeLambda = [&](BfType* checkType)
  13377. {
  13378. if (checkType->IsStruct())
  13379. {
  13380. auto checkTypeInstance = checkType->ToTypeInstance();
  13381. if (checkTypeInstance->mBaseType != NULL)
  13382. checkTypeLambda(checkTypeInstance->mBaseType);
  13383. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  13384. {
  13385. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  13386. if (fieldInstance->mDataIdx >= 0)
  13387. checkTypeLambda(fieldInstance->GetResolvedType());
  13388. }
  13389. }
  13390. else if (checkType->IsMethodRef())
  13391. {
  13392. BF_FATAL("Not handled");
  13393. }
  13394. else if (checkType->WantsGCMarking())
  13395. {
  13396. BfTypedValue markValue(mBfIRBuilder->GetArgument(argIdx), checkType);
  13397. EmitGCMarkValue(markValue, markFromGCThreadMethodInstance);
  13398. argIdx++;
  13399. }
  13400. };
  13401. checkTypeLambda(thisValue.mType);
  13402. }
  13403. else if (!methodDef->mIsStatic)
  13404. {
  13405. if ((mCurTypeInstance->mBaseType != NULL) && (!mCurTypeInstance->IsTypedPrimitive()) && (mCurTypeInstance->mBaseType->WantsGCMarking()))
  13406. {
  13407. BfModuleMethodInstance moduleMethodInst = GetMethodByName(mCurTypeInstance->mBaseType, BF_METHODNAME_MARKMEMBERS, 0, true);
  13408. if (moduleMethodInst)
  13409. {
  13410. auto methodBaseType = moduleMethodInst.mMethodInstance->GetOwner();
  13411. if (methodBaseType != mContext->mBfObjectType)
  13412. {
  13413. auto thisValue = GetThis();
  13414. auto baseValue = Cast(NULL, thisValue, methodBaseType, BfCastFlags_Explicit);
  13415. SizedArray<BfIRValue, 1> args;
  13416. if (moduleMethodInst.mMethodInstance->GetParamIsSplat(-1))
  13417. {
  13418. BfExprEvaluator exprEvaluator(this);
  13419. exprEvaluator.SplatArgs(baseValue, args);
  13420. }
  13421. else
  13422. {
  13423. args.push_back(baseValue.mValue);
  13424. }
  13425. mBfIRBuilder->CreateCall(moduleMethodInst.mFunc, args);
  13426. }
  13427. }
  13428. }
  13429. }
  13430. if (!methodDef->mIsStatic)
  13431. {
  13432. HashSet<int> objectOffsets;
  13433. EmitGCMarkValue(thisValue, mCurTypeInstance, 0, 0, objectOffsets, markFromGCThreadMethodInstance);
  13434. }
  13435. else
  13436. {
  13437. for (auto& fieldInst : mCurTypeInstance->mFieldInstances)
  13438. {
  13439. if (thisValue.IsSplat())
  13440. break;
  13441. auto fieldDef = fieldInst.GetFieldDef();
  13442. if (fieldDef == NULL)
  13443. continue;
  13444. if (fieldInst.mIsThreadLocal)
  13445. continue;
  13446. if (fieldDef->mIsStatic == methodDef->mIsStatic)
  13447. {
  13448. // For extensions, only handle these fields in the appropriate extension
  13449. if ((fieldDef->mDeclaringType->mTypeDeclaration != methodDef->mDeclaringType->mTypeDeclaration))
  13450. continue;
  13451. if (!fieldInst.mFieldIncluded)
  13452. continue;
  13453. auto fieldTypeInst = fieldInst.mResolvedType->ToTypeInstance();
  13454. if (fieldTypeInst != NULL)
  13455. {
  13456. auto fieldDef = fieldInst.GetFieldDef();
  13457. BfTypedValue markVal;
  13458. if (fieldDef->mIsConst)
  13459. continue;
  13460. if ((!fieldTypeInst->IsObjectOrInterface()) && (!fieldTypeInst->IsComposite()))
  13461. continue;
  13462. mBfIRBuilder->PopulateType(fieldTypeInst);
  13463. if (fieldTypeInst->IsValuelessType())
  13464. continue;
  13465. if ((fieldDef->mIsStatic) && (!fieldDef->mIsConst))
  13466. {
  13467. markVal = ReferenceStaticField(&fieldInst);
  13468. }
  13469. else if (!fieldDef->mIsStatic)
  13470. {
  13471. markVal = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(thisValue.mValue, 0, fieldInst.mDataIdx/*, fieldDef->mName*/), fieldInst.mResolvedType, true);
  13472. }
  13473. if (markVal)
  13474. EmitGCMarkValue(markVal, markFromGCThreadMethodInstance);
  13475. }
  13476. }
  13477. }
  13478. }
  13479. if (mCurMethodInstance->mChainType == BfMethodChainType_ChainHead)
  13480. CallChainedMethods(mCurMethodInstance, false);
  13481. }
  13482. }
  13483. }
  13484. void BfModule::EmitGCFindTLSMembers()
  13485. {
  13486. auto methodDef = mCurMethodInstance->mMethodDef;
  13487. auto gcTypeInst = ResolveTypeDef(mCompiler->mGCTypeDef)->ToTypeInstance();
  13488. auto reportTLSMark = GetMethodByName(gcTypeInst, "ReportTLSMember", 2);
  13489. BF_ASSERT(reportTLSMark);
  13490. for (auto& fieldInst : mCurTypeInstance->mFieldInstances)
  13491. {
  13492. auto fieldDef = fieldInst.GetFieldDef();
  13493. if (fieldDef == NULL)
  13494. continue;
  13495. if (!fieldInst.mIsThreadLocal)
  13496. continue;
  13497. // For extensions, only handle these fields in the appropriate extension
  13498. if ((fieldDef->mDeclaringType->mTypeDeclaration != methodDef->mDeclaringType->mTypeDeclaration))
  13499. continue;
  13500. if (!fieldInst.mFieldIncluded)
  13501. continue;
  13502. if (fieldDef->mIsConst)
  13503. continue;
  13504. auto fieldType = fieldInst.mResolvedType;
  13505. if ((!fieldType->IsObjectOrInterface()) && (!fieldType->IsComposite()))
  13506. continue;
  13507. if (fieldType->IsValuelessType())
  13508. continue;
  13509. BfTypedValue markVal = ReferenceStaticField(&fieldInst);
  13510. if (markVal)
  13511. {
  13512. BfIRValue fieldRefPtr = mBfIRBuilder->CreateBitCast(markVal.mValue, mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr)));
  13513. BfIRValue markFuncPtr = GetMarkFuncPtr(fieldType);
  13514. SizedArray<BfIRValue, 2> llvmArgs;
  13515. llvmArgs.push_back(fieldRefPtr);
  13516. llvmArgs.push_back(markFuncPtr);
  13517. mBfIRBuilder->CreateCall(reportTLSMark.mFunc, llvmArgs);
  13518. }
  13519. }
  13520. if (mCurMethodInstance->mChainType == BfMethodChainType_ChainHead)
  13521. CallChainedMethods(mCurMethodInstance, false);
  13522. }
  13523. void BfModule::ProcessMethod(BfMethodInstance* methodInstance, bool isInlineDup)
  13524. {
  13525. BP_ZONE_F("BfModule::ProcessMethod %s", BP_DYN_STR(methodInstance->mMethodDef->mName.c_str()));
  13526. if (mAwaitingInitFinish)
  13527. FinishInit();
  13528. if (!methodInstance->mIsReified)
  13529. BF_ASSERT(!mIsReified);
  13530. if (methodInstance->mMethodInfoEx != NULL)
  13531. {
  13532. for (auto methodGenericArg : methodInstance->mMethodInfoEx->mMethodGenericArguments)
  13533. {
  13534. if (methodGenericArg->IsMethodRef())
  13535. {
  13536. auto methodRefType = (BfMethodRefType*)methodGenericArg;
  13537. BF_ASSERT(methodRefType->mOwnerRevision == methodRefType->mOwner->mRevision);
  13538. }
  13539. }
  13540. }
  13541. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, mWantsIRIgnoreWrites || methodInstance->mIsUnspecialized);
  13542. bool ignoreWrites = mBfIRBuilder->mIgnoreWrites;
  13543. if ((HasCompiledOutput()) && (!mBfIRBuilder->mIgnoreWrites))
  13544. {
  13545. BF_ASSERT(!methodInstance->mIRFunction.IsFake() || (methodInstance->GetImportCallKind() != BfImportCallKind_None));
  13546. }
  13547. SetAndRestoreValue<BfSourceClassifier*> prevSourceClassifier;
  13548. if (((methodInstance->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend) || (methodInstance->mIsForeignMethodDef) || (methodInstance->IsSpecializedGenericMethod())) &&
  13549. (mCompiler->mResolvePassData != NULL))
  13550. {
  13551. // Don't classify on the CtorCalcAppend, just on the actual Ctor
  13552. prevSourceClassifier.Init(mCompiler->mResolvePassData->mSourceClassifier, NULL);
  13553. }
  13554. if (methodInstance->mHasBeenProcessed)
  13555. {
  13556. BfLogSysM("ProcessMethod %p HasBeenProcessed\n", methodInstance);
  13557. return;
  13558. }
  13559. if (methodInstance->mFailedConstraints)
  13560. {
  13561. // The only way this should be able to happen is if we fail our generic param check
  13562. BF_ASSERT(methodInstance->IsSpecializedGenericMethod());
  13563. BfLogSysM("Method instance marked as 'failed' at start of ProcessMethod %p\n", methodInstance);
  13564. methodInstance->mHasBeenProcessed = true;
  13565. return;
  13566. }
  13567. BfMethodInstance* defaultMethodInstance = methodInstance->mMethodInstanceGroup->mDefault;
  13568. BF_ASSERT(methodInstance->mMethodInstanceGroup->mOnDemandKind != BfMethodOnDemandKind_NotSet);
  13569. if ((methodInstance->mMethodInstanceGroup->mOnDemandKind != BfMethodOnDemandKind_AlwaysInclude) &&
  13570. (methodInstance->mMethodInstanceGroup->mOnDemandKind != BfMethodOnDemandKind_Referenced))
  13571. {
  13572. methodInstance->mMethodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_Referenced;
  13573. auto owningModule = methodInstance->GetOwner()->mModule;
  13574. if (owningModule->mIsScratchModule)
  13575. {
  13576. BF_ASSERT(owningModule->mOnDemandMethodCount == 0);
  13577. }
  13578. else
  13579. {
  13580. BF_ASSERT((owningModule->mOnDemandMethodCount > 0) || (!HasCompiledOutput()) || (owningModule->mExtensionCount > 0));
  13581. if (owningModule->mOnDemandMethodCount > 0)
  13582. owningModule->mOnDemandMethodCount--;
  13583. }
  13584. }
  13585. // We set mHasBeenProcessed to true immediately -- this helps avoid stack overflow during recursion for things like
  13586. // self-referencing append allocations in ctor@calcAppend
  13587. methodInstance->mHasBeenProcessed = true;
  13588. mIncompleteMethodCount--;
  13589. BF_ASSERT((mIsSpecialModule) || (mIncompleteMethodCount >= 0));
  13590. auto typeDef = methodInstance->mMethodInstanceGroup->mOwner->mTypeDef;
  13591. auto methodDef = methodInstance->mMethodDef;
  13592. auto methodDeclaration = methodDef->GetMethodDeclaration();
  13593. if ((methodInstance->mIsReified) && (methodInstance->mVirtualTableIdx != -1))
  13594. {
  13595. // If we reify a virtual method in a HotCompile then we need to make sure the type data gets written out
  13596. // so we get the new vdata for it
  13597. methodInstance->GetOwner()->mDirty = true;
  13598. }
  13599. int dependentGenericStartIdx = 0;
  13600. if (methodDef->mIsLocalMethod) // See DoMethodDeclaration for an explaination of dependentGenericStartIdx
  13601. dependentGenericStartIdx = (int)mCurMethodState->GetRootMethodState()->mMethodInstance->GetNumGenericArguments();
  13602. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, methodInstance);
  13603. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, methodInstance->mMethodInstanceGroup->mOwner);
  13604. SetAndRestoreValue<BfFilePosition> prevFilePos(mCurFilePosition);
  13605. SetAndRestoreValue<bool> prevHadBuildError(mHadBuildError, false);
  13606. SetAndRestoreValue<bool> prevHadWarning(mHadBuildWarning, false);
  13607. SetAndRestoreValue<bool> prevIgnoreWarnings(mIgnoreWarnings, false);
  13608. if ((methodInstance->mIsReified) &&
  13609. ((methodDef->mMethodType == BfMethodType_Ctor) || (methodDef->mMethodType == BfMethodType_CtorNoBody)))
  13610. {
  13611. mCurTypeInstance->mHasBeenInstantiated = true;
  13612. }
  13613. // Warnings are shown in the capture phase
  13614. if ((methodDef->mIsLocalMethod) || (mCurTypeInstance->IsClosure()))
  13615. mIgnoreWarnings = true;
  13616. if ((methodDeclaration == NULL) && (mCurMethodState == NULL))
  13617. UseDefaultSrcPos();
  13618. // We may not actually be populated in relatively rare autocompelte cases
  13619. PopulateType(mCurTypeInstance, BfPopulateType_DataAndMethods);
  13620. mBfIRBuilder->PopulateType(mCurTypeInstance, BfIRPopulateType_Full);
  13621. BfAstNode* nameNode = NULL;
  13622. if (methodDeclaration != NULL)
  13623. {
  13624. nameNode = methodDeclaration->mNameNode;
  13625. if (nameNode == NULL)
  13626. {
  13627. if (auto ctorDeclaration = BfNodeDynCast<BfConstructorDeclaration>(methodDeclaration))
  13628. nameNode = ctorDeclaration->mThisToken;
  13629. }
  13630. }
  13631. if ((mCompiler->mResolvePassData != NULL) && (methodDeclaration != NULL) && (nameNode != NULL) &&
  13632. (mCompiler->mResolvePassData->mGetSymbolReferenceKind == BfGetSymbolReferenceKind_Method) && (methodDef->mIdx >= 0))
  13633. {
  13634. if (methodInstance->GetExplicitInterface() == NULL)
  13635. mCompiler->mResolvePassData->HandleMethodReference(nameNode, typeDef, methodDef);
  13636. else
  13637. {
  13638. for (auto& ifaceEntry : mCurTypeInstance->mInterfaces)
  13639. {
  13640. auto ifaceInst = ifaceEntry.mInterfaceType;
  13641. int startIdx = ifaceEntry.mStartInterfaceTableIdx;
  13642. int iMethodCount = (int)ifaceInst->mMethodInstanceGroups.size();
  13643. if (methodInstance->GetExplicitInterface() != ifaceInst)
  13644. continue;
  13645. ifaceInst->mTypeDef->PopulateMemberSets();
  13646. BfMethodDef* nextMethod = NULL;
  13647. BfMemberSetEntry* entry = NULL;
  13648. if (ifaceInst->mTypeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  13649. nextMethod = (BfMethodDef*)entry->mMemberDef;
  13650. while (nextMethod != NULL)
  13651. {
  13652. auto checkMethod = nextMethod;
  13653. nextMethod = nextMethod->mNextWithSameName;
  13654. BfMethodInstance* implMethodInst = mCurTypeInstance->mInterfaceMethodTable[startIdx + checkMethod->mIdx].mMethodRef;
  13655. if (implMethodInst == methodInstance)
  13656. {
  13657. auto ifaceMethodDef = ifaceInst->mTypeDef->mMethods[checkMethod->mIdx];
  13658. mCompiler->mResolvePassData->HandleMethodReference(nameNode, ifaceInst->mTypeDef, ifaceMethodDef);
  13659. }
  13660. }
  13661. }
  13662. }
  13663. if (methodDef->mIsOverride)
  13664. {
  13665. for (int virtIdx = 0; virtIdx < (int)mCurTypeInstance->mVirtualMethodTable.size(); virtIdx++)
  13666. {
  13667. auto& ventry = mCurTypeInstance->mVirtualMethodTable[virtIdx];
  13668. if (ventry.mDeclaringMethod.mMethodNum == -1)
  13669. continue;
  13670. BfMethodInstance* virtMethod = ventry.mImplementingMethod;
  13671. if (virtMethod != NULL)
  13672. {
  13673. if (virtMethod == methodInstance)
  13674. {
  13675. // Is matching method
  13676. if (virtIdx < (int)mCurTypeInstance->mBaseType->mVirtualMethodTable.size())
  13677. {
  13678. auto baseType = mCurTypeInstance->mBaseType;
  13679. if (baseType != NULL)
  13680. {
  13681. while ((baseType->mBaseType != NULL) && (virtIdx < baseType->mBaseType->mVirtualMethodTableSize))
  13682. baseType = baseType->mBaseType;
  13683. BfMethodInstance* baseVirtMethod = baseType->mVirtualMethodTable[virtIdx].mImplementingMethod;
  13684. mCompiler->mResolvePassData->HandleMethodReference(nameNode, baseType->mTypeDef, baseVirtMethod->mMethodDef);
  13685. }
  13686. }
  13687. break;
  13688. }
  13689. }
  13690. }
  13691. }
  13692. }
  13693. BfLogSysM("ProcessMethod %p Unspecialized: %d Module: %p IRFunction: %d Reified: %d\n", methodInstance, mCurTypeInstance->IsUnspecializedType(), this, methodInstance->mIRFunction.mId, methodInstance->mIsReified);
  13694. if (methodInstance->GetImportCallKind() != BfImportCallKind_None)
  13695. {
  13696. if (mBfIRBuilder->mIgnoreWrites)
  13697. return;
  13698. BfLogSysM("DllImportGlobalVar processing %p\n", methodInstance);
  13699. if (!methodInstance->mIRFunction)
  13700. {
  13701. BfIRValue dllImportGlobalVar = CreateDllImportGlobalVar(methodInstance, true);
  13702. methodInstance->mIRFunction = mBfIRBuilder->GetFakeVal();
  13703. mFuncReferences[mCurMethodInstance] = dllImportGlobalVar;
  13704. }
  13705. if (HasCompiledOutput())
  13706. {
  13707. BfDllImportEntry dllImportEntry;
  13708. dllImportEntry.mFuncVar = methodInstance->mIRFunction;
  13709. dllImportEntry.mMethodInstance = mCurMethodInstance;
  13710. mDllImportEntries.push_back(dllImportEntry);
  13711. }
  13712. return;
  13713. }
  13714. StringT<128> mangledName;
  13715. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), mCurMethodInstance);
  13716. if (!methodInstance->mIRFunction)
  13717. {
  13718. bool isIntrinsic = false;
  13719. SetupIRFunction(methodInstance, mangledName, false, &isIntrinsic);
  13720. }
  13721. if (methodInstance->mIsIntrinsic)
  13722. return;
  13723. auto prevActiveFunction = mBfIRBuilder->GetActiveFunction();
  13724. mBfIRBuilder->SetActiveFunction(mCurMethodInstance->mIRFunction);
  13725. if (methodDef->mBody != NULL)
  13726. UpdateSrcPos(methodDef->mBody, BfSrcPosFlag_NoSetDebugLoc);
  13727. else if (methodDeclaration != NULL)
  13728. UpdateSrcPos(methodDeclaration, BfSrcPosFlag_NoSetDebugLoc);
  13729. else if (mCurTypeInstance->mTypeDef->mTypeDeclaration != NULL)
  13730. UpdateSrcPos(mCurTypeInstance->mTypeDef->mTypeDeclaration, BfSrcPosFlag_NoSetDebugLoc);
  13731. if (mCurMethodState == NULL) // Only do initial classify for the 'outer' method state, not any local methods or lambdas
  13732. {
  13733. if ((mCompiler->mIsResolveOnly) && (methodDef->mBody != NULL) && (!mCurTypeInstance->IsBoxed()) &&
  13734. (methodDef->mBody->IsFromParser(mCompiler->mResolvePassData->mParser)) && (mCompiler->mResolvePassData->mSourceClassifier != NULL))
  13735. {
  13736. mCompiler->mResolvePassData->mSourceClassifier->VisitChildNoRef(methodDef->mBody);
  13737. }
  13738. }
  13739. BfHotDataReferenceBuilder hotDataReferenceBuilder;
  13740. BfMethodState methodState;
  13741. if (mCurMethodState != NULL)
  13742. methodState.mClosureState = mCurMethodState->mClosureState;
  13743. if ((mCompiler->mOptions.mAllowHotSwapping) && (methodInstance->mIsReified) && (!methodInstance->mIsUnspecialized) && (!isInlineDup))
  13744. {
  13745. //BF_ASSERT(methodInstance->mHotMethod != NULL);
  13746. if (methodInstance->mHotMethod == NULL)
  13747. CheckHotMethod(methodInstance, mangledName);
  13748. methodState.mHotDataReferenceBuilder = &hotDataReferenceBuilder;
  13749. }
  13750. methodState.mPrevMethodState = mCurMethodState;
  13751. methodState.mMethodInstance = methodInstance;
  13752. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  13753. if (methodInstance->GetCustomAttributes() != NULL)
  13754. {
  13755. int typeOptionsIdx = GenerateTypeOptions(methodInstance->GetCustomAttributes(), mCurTypeInstance, false);
  13756. if (typeOptionsIdx != -1)
  13757. methodState.mMethodTypeOptions = mSystem->GetTypeOptions(typeOptionsIdx);
  13758. }
  13759. BfTypeState typeState(mCurTypeInstance);
  13760. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  13761. bool isGenericVariation = (methodInstance->mIsUnspecializedVariation) || (mCurTypeInstance->IsUnspecializedTypeVariation());
  13762. BfMethodInstance* unspecializedMethodInstance = NULL;
  13763. if ((prevMethodState.mPrevVal != NULL) &&
  13764. ((methodState.mClosureState == NULL) || (methodState.mClosureState->mActiveDeferredLocalMethod == NULL)))
  13765. {
  13766. // This is 'inner' (probably a closure) - use binding from outer function
  13767. methodState.mGenericTypeBindings = prevMethodState.mPrevVal->mGenericTypeBindings;
  13768. }
  13769. else if ((methodInstance->mIsUnspecialized) ||
  13770. ((mCurTypeInstance->IsUnspecializedType()) && (!isGenericVariation)))
  13771. {
  13772. methodState.mGenericTypeBindings = &methodInstance->GetMethodInfoEx()->mGenericTypeBindings;
  13773. }
  13774. else if ((((methodInstance->mMethodInfoEx != NULL) && ((int)methodInstance->mMethodInfoEx->mMethodGenericArguments.size() > dependentGenericStartIdx)) ||
  13775. ((mCurTypeInstance->IsGenericTypeInstance()) && (!isGenericVariation))))
  13776. {
  13777. unspecializedMethodInstance = GetUnspecializedMethodInstance(methodInstance);
  13778. BF_ASSERT(unspecializedMethodInstance != methodInstance);
  13779. if (!unspecializedMethodInstance->mHasBeenProcessed)
  13780. {
  13781. // Make sure the unspecialized method is processed so we can take its bindings
  13782. // Clear mCurMethodState so we don't think we're in a local method
  13783. SetAndRestoreValue<BfMethodState*> prevMethodState_Unspec(mCurMethodState, prevMethodState.mPrevVal);
  13784. mContext->ProcessMethod(unspecializedMethodInstance);
  13785. }
  13786. methodState.mGenericTypeBindings = &unspecializedMethodInstance->GetMethodInfoEx()->mGenericTypeBindings;
  13787. }
  13788. if (methodDef->mMethodType == BfMethodType_Operator)
  13789. {
  13790. auto operatorDef = (BfOperatorDef*) methodDef;
  13791. BfAstNode* refNode = operatorDef->mOperatorDeclaration->mOperatorToken;
  13792. auto paramErrorRefNode = refNode;
  13793. if (operatorDef->mOperatorDeclaration->mOpenParen != NULL)
  13794. paramErrorRefNode = operatorDef->mOperatorDeclaration->mOpenParen;
  13795. if ((mCurMethodInstance->GetParamCount() > 0) && (mCurMethodInstance->GetParamTypeRef(0) != NULL))
  13796. paramErrorRefNode = mCurMethodInstance->GetParamTypeRef(0);
  13797. if (operatorDef->mOperatorDeclaration->mBinOp != BfBinaryOp_None)
  13798. {
  13799. if (methodDef->mParams.size() != 2)
  13800. {
  13801. Fail("Binary operators must declare two parameters", paramErrorRefNode);
  13802. }
  13803. else
  13804. {
  13805. if ((mCurMethodInstance->GetParamType(0) != mCurTypeInstance) && (!mCurMethodInstance->GetParamType(0)->IsSelf()) &&
  13806. (mCurMethodInstance->GetParamType(1) != mCurTypeInstance) && (!mCurMethodInstance->GetParamType(1)->IsSelf()))
  13807. {
  13808. Fail("At least one of the parameters of a binary operator must be the containing type", paramErrorRefNode);
  13809. }
  13810. }
  13811. BfType* wantType = NULL;
  13812. if (operatorDef->mOperatorDeclaration->mBinOp == BfBinaryOp_Compare)
  13813. {
  13814. wantType = GetPrimitiveType(BfTypeCode_IntPtr);
  13815. }
  13816. if ((wantType != NULL) && (methodInstance->mReturnType != wantType))
  13817. Fail(StrFormat("The return type for the '%s' operator must be '%s'", BfGetOpName(operatorDef->mOperatorDeclaration->mBinOp),
  13818. TypeToString(wantType).c_str()), operatorDef->mOperatorDeclaration->mReturnType);
  13819. }
  13820. else if (operatorDef->mOperatorDeclaration->mUnaryOp != BfUnaryOp_None)
  13821. {
  13822. if (methodDef->mParams.size() != 1)
  13823. {
  13824. Fail("Unary operators must declare one parameter", paramErrorRefNode);
  13825. }
  13826. else if ((mCurMethodInstance->GetParamType(0) != mCurTypeInstance) && (!mCurMethodInstance->GetParamType(0)->IsSelf()))
  13827. {
  13828. Fail("The parameter of a unary operator must be the containing type", paramErrorRefNode);
  13829. }
  13830. if (((operatorDef->mOperatorDeclaration->mUnaryOp == BfUnaryOp_Increment) ||
  13831. (operatorDef->mOperatorDeclaration->mUnaryOp == BfUnaryOp_Decrement)) &&
  13832. (!TypeIsSubTypeOf(mCurMethodInstance->mReturnType->ToTypeInstance(), mCurTypeInstance)))
  13833. {
  13834. Fail("The return type for the '++' or '--' operator must match the parameter type or be derived from the parameter type", operatorDef->mOperatorDeclaration->mReturnType);
  13835. }
  13836. }
  13837. else if (operatorDef->mOperatorDeclaration->mAssignOp != BfAssignmentOp_None)
  13838. {
  13839. if (methodDef->mParams.size() != 1)
  13840. {
  13841. Fail("Assignment operators must declare one parameter", paramErrorRefNode);
  13842. }
  13843. if (mCurMethodInstance->mReturnType->IsVoid())
  13844. {
  13845. Fail("The return type for assignment operator must be 'void'", operatorDef->mOperatorDeclaration->mReturnType);
  13846. }
  13847. }
  13848. else // Conversion
  13849. {
  13850. if (!operatorDef->mOperatorDeclaration->mIsConvOperator)
  13851. {
  13852. if (operatorDef->mOperatorDeclaration->mReturnType != NULL)
  13853. Fail("Conversion operators must declare their target type after the 'operator' token, not before", operatorDef->mOperatorDeclaration->mReturnType);
  13854. }
  13855. if (methodDef->mParams.size() != 1)
  13856. {
  13857. auto refNode = paramErrorRefNode;
  13858. if (!operatorDef->mOperatorDeclaration->mCommas.empty())
  13859. refNode = operatorDef->mOperatorDeclaration->mCommas[0];
  13860. Fail("Conversion operators must declare one parameter", refNode);
  13861. }
  13862. else
  13863. {
  13864. if ((mCurMethodInstance->GetParamType(0) != mCurTypeInstance) && (!mCurMethodInstance->GetParamType(0)->IsSelf()) &&
  13865. (mCurMethodInstance->mReturnType != mCurTypeInstance) && (!mCurMethodInstance->mReturnType->IsSelf()))
  13866. Fail("User-defined conversion must convert to or from the enclosing type", paramErrorRefNode);
  13867. if (mCurMethodInstance->GetParamType(0) == mCurMethodInstance->mReturnType)
  13868. Fail("User-defined operator cannot take an object of the enclosing type and convert to an object of the enclosing type", operatorDef->mOperatorDeclaration->mReturnType);
  13869. // On type lookup error we default to 'object', so don't do the 'base class' error if that may have
  13870. // happened here
  13871. if ((!mHadBuildError) || ((mCurMethodInstance->mReturnType != mContext->mBfObjectType) && (mCurMethodInstance->GetParamType(0) != mContext->mBfObjectType)))
  13872. {
  13873. auto isToBase = TypeIsSubTypeOf(mCurTypeInstance->mBaseType, mCurMethodInstance->mReturnType->ToTypeInstance());
  13874. bool isFromBase = TypeIsSubTypeOf(mCurTypeInstance->mBaseType, mCurMethodInstance->GetParamType(0)->ToTypeInstance());
  13875. if ((mCurTypeInstance->IsObject()) && (isToBase || isFromBase))
  13876. Fail("User-defined conversions to or from a base class are not allowed", paramErrorRefNode);
  13877. else if ((mCurTypeInstance->IsStruct()) && (isToBase))
  13878. Fail("User-defined conversions to a base struct are not allowed", paramErrorRefNode);
  13879. }
  13880. }
  13881. }
  13882. }
  13883. bool wantsDIData = (mBfIRBuilder->DbgHasInfo()) && (!methodDef->IsEmptyPartial()) && (!mCurMethodInstance->mIsUnspecialized) && (mHasFullDebugInfo);
  13884. if (methodDef->mMethodType == BfMethodType_Mixin)
  13885. wantsDIData = false;
  13886. if ((mCurTypeInstance->IsBoxed()) && (methodDef->mMethodType != BfMethodType_Ctor))
  13887. wantsDIData = false;
  13888. bool wantsDIVariables = wantsDIData;
  13889. if (methodDef->mIsExtern)
  13890. wantsDIVariables = false;
  13891. SizedArray<BfIRMDNode, 8> diParams;
  13892. diParams.push_back(mBfIRBuilder->DbgGetType(methodInstance->mReturnType));
  13893. bool isThisStruct = mCurTypeInstance->IsStruct() && !mCurTypeInstance->IsTypedPrimitive();
  13894. BfType* thisType = NULL;
  13895. if (!methodDef->mIsStatic)
  13896. {
  13897. if ((methodState.mClosureState != NULL) && (methodState.mClosureState->mClosureType != NULL))
  13898. thisType = methodState.mClosureState->mClosureType;
  13899. else
  13900. thisType = mCurTypeInstance;
  13901. }
  13902. PopulateType(methodInstance->mReturnType, BfPopulateType_Data);
  13903. ProcessMethod_SetupParams(methodInstance, thisType, wantsDIData, &diParams);
  13904. //////////////////////////////////////////////////////////////////////////
  13905. //
  13906. {
  13907. if (methodDeclaration != NULL)
  13908. UpdateSrcPos(methodDeclaration, BfSrcPosFlag_NoSetDebugLoc);
  13909. else if (methodDef->mBody != NULL)
  13910. UpdateSrcPos(methodDef->mBody, BfSrcPosFlag_NoSetDebugLoc);
  13911. else if (mCurTypeInstance->mTypeDef->mTypeDeclaration != NULL)
  13912. UpdateSrcPos(mCurTypeInstance->mTypeDef->mTypeDeclaration, BfSrcPosFlag_NoSetDebugLoc);
  13913. }
  13914. BfIRMDNode diFunction;
  13915. if (wantsDIData)
  13916. {
  13917. BP_ZONE("BfModule::BfMethodDeclaration.DISetup");
  13918. BfIRMDNode diFuncType = mBfIRBuilder->DbgCreateSubroutineType(diParams);
  13919. int defLine = mCurFilePosition.mCurLine;
  13920. if (mDICompileUnit)
  13921. {
  13922. int flags = 0;
  13923. BfIRMDNode funcScope = mBfIRBuilder->DbgGetTypeInst(mCurTypeInstance);
  13924. if (methodDef->mProtection == BfProtection_Public)
  13925. flags = llvm::DINode::FlagPublic;
  13926. else if (methodDef->mProtection == BfProtection_Protected)
  13927. flags = llvm::DINode::FlagProtected;
  13928. else
  13929. flags = llvm::DINode::FlagPrivate;
  13930. if (methodDef->mIsOverride)
  13931. {
  13932. //flags |= llvm::DINode::FlagVirtual;
  13933. }
  13934. else if (methodDef->mIsVirtual)
  13935. flags |= llvm::DINode::FlagIntroducedVirtual;
  13936. if ((methodDef->mIsStatic) || (methodDef->mMethodType == BfMethodType_Mixin))
  13937. flags |= llvm::DINode::FlagStaticMember;
  13938. else
  13939. {
  13940. if ((mCurTypeInstance->IsValuelessType()) || (mCurTypeInstance->IsSplattable()))
  13941. flags |= llvm::DINode::FlagStaticMember;
  13942. }
  13943. flags |= llvm::DINode::FlagPrototyped;
  13944. if (methodDef->mMethodType == BfMethodType_Ctor)
  13945. {
  13946. flags |= llvm::DINode::FlagArtificial;
  13947. }
  13948. auto llvmFunction = methodInstance->mIRFunction;
  13949. SizedArray<BfIRMDNode, 1> genericArgs;
  13950. SizedArray<BfIRValue, 1> genericConstValueArgs;
  13951. String methodName;
  13952. if (methodInstance->GetForeignType() != NULL)
  13953. {
  13954. methodName += TypeToString(methodInstance->GetForeignType());
  13955. methodName += ".";
  13956. }
  13957. if (methodInstance->GetExplicitInterface() != NULL)
  13958. {
  13959. methodName += TypeToString(methodInstance->GetExplicitInterface());
  13960. methodName += ".";
  13961. }
  13962. methodName += methodDef->mName;
  13963. if (methodInstance->GetNumGenericArguments() != 0)
  13964. {
  13965. for (auto genericArg : methodInstance->mMethodInfoEx->mMethodGenericArguments)
  13966. {
  13967. if (genericArg->IsConstExprValue())
  13968. {
  13969. BfConstExprValueType* constExprValueType = (BfConstExprValueType*)genericArg;
  13970. while (genericConstValueArgs.size() < genericArgs.size())
  13971. genericConstValueArgs.push_back(BfIRValue());
  13972. genericConstValueArgs.push_back(mBfIRBuilder->CreateConst(BfTypeCode_UInt64, constExprValueType->mValue.mUInt64));
  13973. genericArgs.push_back(mBfIRBuilder->DbgGetType(GetPrimitiveType(BfTypeCode_Int64)));
  13974. }
  13975. else
  13976. genericArgs.push_back(mBfIRBuilder->DbgGetType(genericArg));
  13977. }
  13978. methodName += "<";
  13979. for (int i = 0; i < (int)methodInstance->mMethodInfoEx->mMethodGenericArguments.size(); i++)
  13980. {
  13981. if (i > 0)
  13982. methodName += ", ";
  13983. BfType* type = methodInstance->mMethodInfoEx->mMethodGenericArguments[i];
  13984. methodName += TypeToString(type);
  13985. }
  13986. methodName += ">";
  13987. }
  13988. if ((methodName.empty()) && (methodDeclaration != NULL))
  13989. {
  13990. if (auto operatorDecl = BfNodeDynCast<BfOperatorDeclaration>(methodDeclaration))
  13991. {
  13992. methodName += "operator";
  13993. if (operatorDecl->mIsConvOperator)
  13994. {
  13995. methodName += " ";
  13996. methodName += TypeToString(methodInstance->mReturnType);
  13997. }
  13998. else if (operatorDecl->mOpTypeToken != NULL)
  13999. methodName += operatorDecl->mOpTypeToken->ToString();
  14000. }
  14001. }
  14002. if (methodDef->mCheckedKind == BfCheckedKind_Checked)
  14003. methodName += "$CHK";
  14004. else if (methodDef->mCheckedKind == BfCheckedKind_Unchecked)
  14005. methodName += "$UCHK";
  14006. methodState.mDIFile = mCurFilePosition.mFileInstance->mDIFile;
  14007. // diFunction = mBfIRBuilder->DbgCreateMethod(funcScope, methodName, mangledName, methodState.mDIFile,
  14008. // defLine + 1, diFuncType, false, true,
  14009. // (methodInstance->mVirtualTableIdx != -1) ? llvm::dwarf::DW_VIRTUALITY_virtual : llvm::dwarf::DW_VIRTUALITY_none,
  14010. // (methodInstance->mVirtualTableIdx != -1) ? methodInstance->DbgGetVirtualMethodNum() : 0,
  14011. // nullptr, flags, IsOptimized(), llvmFunction, genericArgs, genericConstValueArgs);
  14012. diFunction = mBfIRBuilder->DbgCreateMethod(funcScope, methodName, mangledName, methodState.mDIFile,
  14013. defLine + 1, diFuncType, false, true,
  14014. llvm::dwarf::DW_VIRTUALITY_none,
  14015. 0,
  14016. nullptr, flags, IsOptimized(), llvmFunction, genericArgs, genericConstValueArgs);
  14017. }
  14018. }
  14019. //////////////////////////////////////////////////////////////////////////
  14020. // Head and Init get rolled into Entry afterwards.
  14021. methodState.mIRFunction = methodInstance->mIRFunction;
  14022. methodState.mIRHeadBlock = mBfIRBuilder->CreateBlock("head", true);
  14023. methodState.mIRInitBlock = mBfIRBuilder->CreateBlock("init", true);
  14024. methodState.mIREntryBlock = mBfIRBuilder->CreateBlock("entry", true);
  14025. methodState.mCurScope->mDIScope = diFunction;
  14026. auto llvmEntryBlock = methodState.mIREntryBlock;
  14027. mBfIRBuilder->SetInsertPoint(llvmEntryBlock);
  14028. if (methodDef->mBody != NULL)
  14029. {
  14030. UpdateSrcPos(methodDef->mBody, BfSrcPosFlag_NoSetDebugLoc);
  14031. }
  14032. else if ((mHasFullDebugInfo) && (diFunction) && (typeDef->mTypeDeclaration != NULL))
  14033. {
  14034. // We want to be able to step into delegate invokes -- we actually step over them
  14035. if (methodDef->mName != "Invoke")
  14036. {
  14037. UpdateSrcPos(typeDef->mTypeDeclaration);
  14038. mBfIRBuilder->DbgCreateAnnotation(diFunction, "StepOver", GetConstValue32(1));
  14039. }
  14040. }
  14041. // Clear out DebugLoc - to mark the ".addr" code as part of prologue
  14042. mBfIRBuilder->ClearDebugLocation();
  14043. bool isTypedPrimitiveFunc = mCurTypeInstance->IsTypedPrimitive() && (methodDef->mMethodType != BfMethodType_Ctor);
  14044. int irParamCount = methodInstance->GetIRFunctionParamCount(this);
  14045. if (methodInstance->GetImportKind() != BfImportKind_Import_Dynamic)
  14046. {
  14047. int localIdx = 0;
  14048. int argIdx = 0;
  14049. if (methodInstance->HasStructRet())
  14050. argIdx++;
  14051. //
  14052. bool doDbgAgg = false;
  14053. Array<BfIRValue> splatAddrValues;
  14054. for ( ; argIdx < irParamCount; localIdx++)
  14055. {
  14056. bool isThis = ((localIdx == 0) && (!mCurMethodInstance->mMethodDef->mIsStatic));
  14057. if ((isThis) && (thisType->IsValuelessType()))
  14058. isThis = false;
  14059. BfLocalVariable* paramVar = NULL;
  14060. while (true)
  14061. {
  14062. BF_ASSERT(localIdx < methodState.mLocals.size());
  14063. paramVar = methodState.mLocals[localIdx];
  14064. if ((paramVar->mCompositeCount == -1) &&
  14065. ((!paramVar->mResolvedType->IsValuelessType()) || (paramVar->mResolvedType->IsMethodRef())))
  14066. break;
  14067. localIdx++;
  14068. }
  14069. if ((isThis) && (mCurTypeInstance->IsValueType()) && (methodDef->mMethodType != BfMethodType_Ctor) && (!methodDef->HasNoThisSplat()))
  14070. {
  14071. paramVar->mIsReadOnly = true;
  14072. }
  14073. bool wantsAddr = (wantsDIVariables) || (!paramVar->mIsReadOnly) || (paramVar->mResolvedType->GetLoweredType() != BfTypeCode_None);
  14074. if (paramVar->mResolvedType->IsMethodRef())
  14075. wantsAddr = false;
  14076. // if ((methodDef->mHasAppend) && (argIdx == 1))
  14077. // {
  14078. // BF_ASSERT(paramVar->mName == "appendIdx");
  14079. // wantsAddr = true;
  14080. // }
  14081. if ((!doDbgAgg) && (paramVar->mIsSplat))
  14082. {
  14083. auto prevInsert = mBfIRBuilder->GetInsertBlock();
  14084. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  14085. BfTypeUtils::SplatIterate([&](BfType* checkType)
  14086. {
  14087. BfIRType splatIRType;
  14088. if (checkType->IsComposite())
  14089. splatIRType = mBfIRBuilder->MapType(CreatePointerType(checkType));
  14090. else
  14091. splatIRType = mBfIRBuilder->MapType(checkType);
  14092. auto allocaInst = mBfIRBuilder->CreateAlloca(splatIRType);
  14093. mBfIRBuilder->SetAllocaAlignment(allocaInst, checkType->mAlign);
  14094. if (!paramVar->mAddr)
  14095. paramVar->mAddr = allocaInst;
  14096. if (WantsLifetimes())
  14097. mCurMethodState->mCurScope->mDeferredLifetimeEnds.push_back(allocaInst);
  14098. splatAddrValues.push_back(allocaInst);
  14099. }, paramVar->mResolvedType);
  14100. mBfIRBuilder->SetInsertPoint(prevInsert);
  14101. }
  14102. else if (isThis)
  14103. {
  14104. if (wantsAddr)
  14105. {
  14106. auto prevInsert = mBfIRBuilder->GetInsertBlock();
  14107. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  14108. BfIRType thisAddrType = mBfIRBuilder->MapType(thisType);
  14109. if (paramVar->mIsSplat)
  14110. {
  14111. if (doDbgAgg)
  14112. {
  14113. auto allocaInst = mBfIRBuilder->CreateAlloca(thisAddrType);
  14114. mBfIRBuilder->SetName(allocaInst, paramVar->mName + ".addr");
  14115. mBfIRBuilder->SetAllocaAlignment(allocaInst, thisType->mAlign);
  14116. paramVar->mAddr = allocaInst;
  14117. if (WantsLifetimes())
  14118. mCurMethodState->mCurScope->mDeferredLifetimeEnds.push_back(allocaInst);
  14119. }
  14120. }
  14121. else
  14122. {
  14123. bool wantPtr = (thisType->IsComposite()) && (!paramVar->mIsLowered);
  14124. if ((thisType->IsTypedPrimitive()) && (methodDef->HasNoThisSplat()))
  14125. wantPtr = true;
  14126. if (wantPtr)
  14127. {
  14128. thisAddrType = mBfIRBuilder->MapTypeInstPtr(thisType->ToTypeInstance());
  14129. }
  14130. auto allocaInst = mBfIRBuilder->CreateAlloca(thisAddrType);
  14131. mBfIRBuilder->SetName(allocaInst, paramVar->mName + ".addr");
  14132. mBfIRBuilder->SetAllocaAlignment(allocaInst, mSystem->mPtrSize);
  14133. paramVar->mAddr = allocaInst;
  14134. if (WantsLifetimes())
  14135. mCurMethodState->mCurScope->mDeferredLifetimeEnds.push_back(allocaInst);
  14136. }
  14137. mBfIRBuilder->SetInsertPoint(prevInsert);
  14138. }
  14139. }
  14140. else if ((!isThis) && ((paramVar->mIsStruct) || (paramVar->mResolvedType->IsRef())))
  14141. {
  14142. // Address doesn't change so we don't have to alloca it
  14143. BfIRType allocType;
  14144. int alignSize = mSystem->mPtrSize;
  14145. if (paramVar->mResolvedType->IsRef())
  14146. {
  14147. allocType = mBfIRBuilder->MapType(paramVar->mResolvedType);
  14148. }
  14149. else if ((paramVar->mIsSplat) || (paramVar->mIsLowered))
  14150. {
  14151. allocType = mBfIRBuilder->MapType(paramVar->mResolvedType);
  14152. alignSize = paramVar->mResolvedType->mAlign;
  14153. }
  14154. else
  14155. {
  14156. paramVar->mHasLocalStructBacking = true;
  14157. auto typeInst = paramVar->mResolvedType->ToTypeInstance();
  14158. if (typeInst != NULL)
  14159. allocType = mBfIRBuilder->MapTypeInstPtr(paramVar->mResolvedType->ToTypeInstance());
  14160. else
  14161. allocType = mBfIRBuilder->MapType(CreatePointerType(paramVar->mResolvedType));
  14162. }
  14163. if (wantsAddr)
  14164. {
  14165. auto prevInsert = mBfIRBuilder->GetInsertBlock();
  14166. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  14167. mBfIRBuilder->PopulateType(paramVar->mResolvedType);
  14168. auto allocaInst = mBfIRBuilder->CreateAlloca(allocType);
  14169. mBfIRBuilder->SetName(allocaInst, paramVar->mName + ".addr");
  14170. mBfIRBuilder->SetAllocaAlignment(allocaInst, alignSize);
  14171. paramVar->mAddr = allocaInst;
  14172. mBfIRBuilder->SetInsertPoint(prevInsert);
  14173. if (WantsLifetimes())
  14174. mCurMethodState->mCurScope->mDeferredLifetimeEnds.push_back(allocaInst);
  14175. }
  14176. }
  14177. else if (wantsAddr)
  14178. {
  14179. auto allocaInst = CreateAlloca(paramVar->mResolvedType);
  14180. mBfIRBuilder->SetName(allocaInst, paramVar->mName + ".addr");
  14181. paramVar->mAddr = allocaInst;
  14182. }
  14183. if (paramVar->mIsSplat)
  14184. {
  14185. BfTypeUtils::SplatIterate([&](BfType* checkType) { argIdx++; }, paramVar->mResolvedType);
  14186. }
  14187. else
  14188. {
  14189. argIdx++;
  14190. }
  14191. }
  14192. if (methodDef->mBody != NULL)
  14193. UpdateSrcPos(methodDef->mBody);
  14194. else if (mCurTypeInstance->mTypeDef->mTypeDeclaration != NULL)
  14195. UpdateSrcPos(mCurTypeInstance->mTypeDef->mTypeDeclaration);
  14196. int declArgIdx = 0;
  14197. localIdx = 0;
  14198. argIdx = 0;
  14199. if (methodInstance->HasStructRet())
  14200. argIdx++;
  14201. int splatAddrIdx = 0;
  14202. while (localIdx < (int)methodState.mLocals.size())
  14203. {
  14204. int curLocalIdx = localIdx++;
  14205. BfLocalVariable* paramVar = methodState.mLocals[curLocalIdx];
  14206. if (!paramVar->IsParam())
  14207. continue;
  14208. if (paramVar->mCompositeCount != -1)
  14209. continue;
  14210. bool isThis = ((curLocalIdx == 0) && (!mCurMethodInstance->mMethodDef->mIsStatic));
  14211. if ((isThis) && (thisType->IsValuelessType()))
  14212. isThis = false;
  14213. BfIRMDNode diVariable;
  14214. if (wantsDIData)
  14215. {
  14216. String paramName = paramVar->mName;
  14217. BfIRMDNode diType = mBfIRBuilder->DbgGetType(paramVar->mResolvedType);
  14218. if (isThis)
  14219. {
  14220. if ((mCurMethodState->mClosureState != NULL) && (mCurMethodState->mClosureState->mClosureType != NULL))
  14221. paramName = "__closure";
  14222. if ((paramVar->mResolvedType->IsValueType()) && (!paramVar->mIsSplat) && (!paramVar->mIsLowered))
  14223. {
  14224. diType = mBfIRBuilder->DbgGetType(paramVar->mResolvedType);
  14225. bool wantRef = paramVar->mResolvedType->IsComposite();
  14226. if ((paramVar->mResolvedType->IsTypedPrimitive()) && (methodDef->HasNoThisSplat()))
  14227. wantRef = true;
  14228. if (wantRef)
  14229. diType = mBfIRBuilder->DbgCreateReferenceType(diType);
  14230. }
  14231. else if (!paramVar->mResolvedType->IsValueType())
  14232. {
  14233. diType = mBfIRBuilder->DbgCreateArtificialType(diType);
  14234. }
  14235. }
  14236. else
  14237. {
  14238. if ((paramVar->mResolvedType->IsComposite()) && (!paramVar->mIsSplat) && (!paramVar->mIsLowered))
  14239. {
  14240. diType = mBfIRBuilder->DbgGetType(paramVar->mResolvedType);
  14241. diType = mBfIRBuilder->DbgCreateReferenceType(diType);
  14242. diType = mBfIRBuilder->DbgCreateConstType(diType);
  14243. }
  14244. }
  14245. if ((!paramVar->mIsSplat) || (doDbgAgg))
  14246. {
  14247. if (paramVar->mResolvedType->IsValuelessType())
  14248. {
  14249. diVariable = mBfIRBuilder->DbgCreateAutoVariable(diFunction,
  14250. paramName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType);
  14251. }
  14252. else if (paramVar->mIsImplicitParam)
  14253. {
  14254. // Annotate this specially?
  14255. diVariable = mBfIRBuilder->DbgCreateParameterVariable(diFunction,
  14256. paramName, argIdx + 1, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType, true, 0);
  14257. }
  14258. else
  14259. {
  14260. diVariable = mBfIRBuilder->DbgCreateParameterVariable(diFunction,
  14261. paramName, argIdx + 1, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType, true, 0);
  14262. }
  14263. paramVar->mDbgVarInst = diVariable;
  14264. }
  14265. else if ((paramVar->mIsSplat) && (paramVar->mResolvedType->GetSplatCount() == 0))
  14266. {
  14267. // if ((mBfIRBuilder->HasDebugLocation()) && (wantsDIVariables))
  14268. // {
  14269. // // Only add this placeholder if we don't have any values
  14270. // auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(mCurMethodState->mCurScope->mDIScope,
  14271. // paramName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType);
  14272. // mBfIRBuilder->DbgInsertValueIntrinsic(GetConstValue(0), diVariable);
  14273. // }
  14274. }
  14275. }
  14276. bool isTypedPrimCtor = mCurTypeInstance->IsTypedPrimitive() && (methodDef->mMethodType == BfMethodType_Ctor);
  14277. if ((!paramVar->mParamFailed) && (paramVar->mAddr))
  14278. {
  14279. // Write our argument value into the .addr
  14280. mBfIRBuilder->ClearDebugLocation();
  14281. if (paramVar->mIsSplat)
  14282. {
  14283. mBfIRBuilder->PopulateType(paramVar->mResolvedType);
  14284. if (doDbgAgg)
  14285. {
  14286. auto curArgIdx = argIdx;
  14287. std::function<void(BfType*, BfIRValue)> checkTypeLambda = [&](BfType* checkType, BfIRValue curDestAddr)
  14288. {
  14289. if (checkType->IsStruct())
  14290. {
  14291. auto checkTypeInstance = checkType->ToTypeInstance();
  14292. if (checkTypeInstance->mBaseType != NULL)
  14293. {
  14294. auto baseDestAddr = mBfIRBuilder->CreateBitCast(curDestAddr, mBfIRBuilder->MapTypeInstPtr(checkTypeInstance->mBaseType));
  14295. checkTypeLambda(checkTypeInstance->mBaseType, baseDestAddr);
  14296. }
  14297. if (checkTypeInstance->mIsUnion)
  14298. {
  14299. auto unionInnerType = checkTypeInstance->GetUnionInnerType();
  14300. if (!unionInnerType->IsValuelessType())
  14301. {
  14302. auto newDestAddr = mBfIRBuilder->CreateInBoundsGEP(curDestAddr, 0, 1);
  14303. checkTypeLambda(unionInnerType, newDestAddr);
  14304. }
  14305. if (checkTypeInstance->IsEnum())
  14306. {
  14307. auto dscrType = checkTypeInstance->GetDiscriminatorType();
  14308. auto newDestAddr = mBfIRBuilder->CreateInBoundsGEP(curDestAddr, 0, 2);
  14309. checkTypeLambda(dscrType, newDestAddr);
  14310. }
  14311. }
  14312. else
  14313. {
  14314. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  14315. {
  14316. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  14317. if (fieldInstance->mDataIdx >= 0)
  14318. {
  14319. auto newDestAddr = mBfIRBuilder->CreateInBoundsGEP(curDestAddr, 0, fieldInstance->mDataIdx);
  14320. checkTypeLambda(fieldInstance->GetResolvedType(), newDestAddr);
  14321. }
  14322. }
  14323. }
  14324. }
  14325. else if (checkType->IsMethodRef())
  14326. {
  14327. BF_FATAL("Unimplemented");
  14328. // BfMethodRefType* methodRefType = (BfMethodRefType*)checkType;
  14329. // for (int dataIdx = 0; dataIdx < methodRefType->GetCaptureDataCount(); dataIdx++)
  14330. // {
  14331. // checkTypeLambda->
  14332. // }
  14333. }
  14334. else if (!checkType->IsValuelessType())
  14335. {
  14336. mBfIRBuilder->CreateAlignedStore(mBfIRBuilder->GetArgument(curArgIdx), curDestAddr, paramVar->mResolvedType->mAlign);
  14337. curArgIdx++;
  14338. }
  14339. };
  14340. checkTypeLambda(paramVar->mResolvedType, paramVar->mAddr);
  14341. }
  14342. }
  14343. else
  14344. {
  14345. bool handled = false;
  14346. //if ((!isThis) || (!methodDef->mIsMutating && !methodDef->mNoSplat))
  14347. if (paramVar->mIsLowered)
  14348. {
  14349. auto loweredTypeCode = paramVar->mResolvedType->GetLoweredType();
  14350. BF_ASSERT(loweredTypeCode != BfTypeCode_None);
  14351. if (loweredTypeCode != BfTypeCode_None)
  14352. {
  14353. // We have a lowered type coming in, so we have to cast the .addr before storing
  14354. auto primType = GetPrimitiveType(loweredTypeCode);
  14355. auto primPtrType = CreatePointerType(primType);
  14356. auto primPtrVal = mBfIRBuilder->CreateBitCast(paramVar->mAddr, mBfIRBuilder->MapType(primPtrType));
  14357. mBfIRBuilder->CreateAlignedStore(paramVar->mValue, primPtrVal, paramVar->mResolvedType->mSize);
  14358. // We don't want to allow directly using value
  14359. paramVar->mValue = BfIRValue();
  14360. handled = true;
  14361. }
  14362. }
  14363. if (!handled)
  14364. mBfIRBuilder->CreateAlignedStore(paramVar->mValue, paramVar->mAddr, paramVar->mResolvedType->mAlign);
  14365. }
  14366. }
  14367. if (!isThis)
  14368. declArgIdx++;
  14369. if (methodDef->mBody != NULL)
  14370. UpdateSrcPos(methodDef->mBody);
  14371. else if (methodDef->mDeclaringType->mTypeDeclaration != NULL)
  14372. UpdateSrcPos(methodDef->mDeclaringType->mTypeDeclaration);
  14373. else if (methodDeclaration == NULL)
  14374. UseDefaultSrcPos();
  14375. // Write our argument value into the .addr
  14376. if ((!doDbgAgg) && (paramVar->mIsSplat))
  14377. {
  14378. int splatComponentIdx = 0;
  14379. auto curArgIdx = argIdx;
  14380. auto _FinishSplats = [&] (BfType* checkType, const StringImpl& name)
  14381. {
  14382. BfIRValue splatAddrValue = splatAddrValues[splatAddrIdx++];
  14383. methodState.mSplatDecompAddrs.push_back(splatAddrValue);
  14384. auto storeInst = mBfIRBuilder->CreateAlignedStore(mBfIRBuilder->GetArgument(curArgIdx), splatAddrValue, checkType->mAlign);
  14385. mBfIRBuilder->ClearDebugLocation(storeInst);
  14386. if (wantsDIData)
  14387. {
  14388. BfIRMDNode diType;
  14389. if (checkType->IsComposite())
  14390. diType = mBfIRBuilder->DbgGetType(CreateRefType(checkType));
  14391. else
  14392. diType = mBfIRBuilder->DbgGetType(checkType);
  14393. auto diVariable = mBfIRBuilder->DbgCreateParameterVariable(diFunction,
  14394. name, curArgIdx + 1, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType);
  14395. if (wantsDIVariables)
  14396. {
  14397. mBfIRBuilder->DbgInsertDeclare(splatAddrValue, diVariable);
  14398. }
  14399. }
  14400. curArgIdx++;
  14401. splatComponentIdx++;
  14402. };
  14403. std::function<void(BfType*, const StringImpl&)> _FinishSplatsIterate = [&](BfType* checkType, const StringImpl& name)
  14404. {
  14405. if (checkType->IsStruct())
  14406. {
  14407. auto checkTypeInstance = checkType->ToTypeInstance();
  14408. if (checkTypeInstance->mBaseType != NULL)
  14409. {
  14410. _FinishSplatsIterate(checkTypeInstance->mBaseType, name + "$b");
  14411. }
  14412. if (checkTypeInstance->mIsUnion)
  14413. {
  14414. auto unionInnerType = checkTypeInstance->GetUnionInnerType();
  14415. if (!unionInnerType->IsValuelessType())
  14416. {
  14417. _FinishSplatsIterate(unionInnerType, name + "$u");
  14418. }
  14419. if (checkTypeInstance->IsEnum())
  14420. {
  14421. auto dscrType = checkTypeInstance->GetDiscriminatorType();
  14422. _FinishSplatsIterate(dscrType, name + "$d");
  14423. }
  14424. }
  14425. else
  14426. {
  14427. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  14428. {
  14429. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  14430. auto fieldDef = fieldInstance->GetFieldDef();
  14431. if (fieldInstance->mDataIdx >= 0)
  14432. {
  14433. _FinishSplatsIterate(fieldInstance->GetResolvedType(), name + "$m$" + fieldDef->mName);
  14434. }
  14435. }
  14436. }
  14437. }
  14438. else if (checkType->IsMethodRef())
  14439. {
  14440. auto methodRefType = (BfMethodRefType*)checkType;
  14441. BfMethodInstance* methodInstance = methodRefType->mMethodRef;
  14442. // int implicitParamCount = methodInstance->GetImplicitParamCount();
  14443. // for (int implicitParamIdx = methodInstance->HasThis() ? -1 : 0; implicitParamIdx < implicitParamCount; implicitParamIdx++)
  14444. // {
  14445. // auto paramType = methodInstance->GetParamType(implicitParamIdx);
  14446. // if (!paramType->IsValuelessType())
  14447. // _FinishSplats(paramType, name + "$m$" + methodInstance->GetParamName(implicitParamIdx));
  14448. // }
  14449. for (int dataIdx = 0; dataIdx < methodRefType->GetCaptureDataCount(); dataIdx++)
  14450. {
  14451. int paramIdx = methodRefType->GetParamIdxFromDataIdx(dataIdx);
  14452. String paramName = methodInstance->GetParamName(paramIdx);
  14453. if (paramName == "this")
  14454. paramName = "__this";
  14455. if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  14456. {
  14457. _FinishSplatsIterate(methodRefType->GetCaptureType(dataIdx), name + "$m$" + paramName);
  14458. }
  14459. else
  14460. {
  14461. _FinishSplats(methodRefType->GetCaptureType(dataIdx), name + "$m$" + paramName);
  14462. }
  14463. }
  14464. }
  14465. else if (!checkType->IsValuelessType())
  14466. {
  14467. _FinishSplats(checkType, name);
  14468. }
  14469. };
  14470. mBfIRBuilder->PopulateType(paramVar->mResolvedType);
  14471. if (!paramVar->mConstValue)
  14472. _FinishSplatsIterate(paramVar->mResolvedType, "$" + paramVar->mName);
  14473. }
  14474. BfIRValue declareCall;
  14475. if (diVariable)
  14476. {
  14477. if ((mBfIRBuilder->HasDebugLocation()) && (wantsDIVariables))
  14478. {
  14479. if (!paramVar->mAddr)
  14480. {
  14481. if ((!paramVar->mValue) || (paramVar->mValue.IsFake()))
  14482. {
  14483. if ((!paramVar->mIsThis) && (mCompiler->mOptions.mToolsetType != BfToolsetType_GNU)) // DWARF chokes on this:
  14484. {
  14485. // We don't need to set the location for this
  14486. mBfIRBuilder->DbgInsertValueIntrinsic(BfIRValue(), diVariable);
  14487. }
  14488. }
  14489. else
  14490. declareCall = mBfIRBuilder->DbgInsertDeclare(paramVar->mValue, diVariable);
  14491. }
  14492. else
  14493. {
  14494. declareCall = mBfIRBuilder->DbgInsertDeclare(paramVar->mAddr, diVariable);
  14495. }
  14496. }
  14497. }
  14498. if ((isThis) && (!paramVar->mIsSplat) && (paramVar->mAddr))
  14499. {
  14500. // We don't allow actually assignment to "this", so we just do a single load
  14501. // Keep in mind we don't use the ACTUAL mValue value because that's a register, but
  14502. // we need to store it in the stack frame for debugging purposes
  14503. auto loadedThis = mBfIRBuilder->CreateLoad(paramVar->mAddr/*, "this"*/);
  14504. mBfIRBuilder->ClearDebugLocation(loadedThis);
  14505. paramVar->mValue = loadedThis;
  14506. }
  14507. if ((wantsDIData) && (declareCall))
  14508. mBfIRBuilder->UpdateDebugLocation(declareCall);
  14509. if (paramVar->mIsSplat)
  14510. {
  14511. BfTypeUtils::SplatIterate([&](BfType* checkType) { argIdx++; }, paramVar->mResolvedType);
  14512. }
  14513. else if (!paramVar->mResolvedType->IsValuelessType())
  14514. {
  14515. argIdx++;
  14516. }
  14517. }
  14518. if (wantsDIData)
  14519. {
  14520. BF_ASSERT(splatAddrIdx == (int)splatAddrValues.size());
  14521. }
  14522. }
  14523. for (int varIdx = 0; varIdx < (int)mCurMethodState->mLocals.size(); varIdx++)
  14524. {
  14525. auto paramVar = mCurMethodState->mLocals[varIdx];
  14526. // 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
  14527. // splat member. If the "splat" is valueless then we do create a placeholder, but further up in this method
  14528. // if (paramVar->mIsSplat)
  14529. // {
  14530. // if (wantsDIVariables)
  14531. // {
  14532. // auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(diFunction, paramVar->mName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, mBfIRBuilder->DbgGetType(paramVar->mResolvedType));
  14533. // mBfIRBuilder->DbgInsertValueIntrinsic(mBfIRBuilder->CreateConst(BfTypeCode_Int64, 0), diVariable);
  14534. // }
  14535. // }
  14536. if (paramVar->mResolvedType->IsValuelessType())
  14537. {
  14538. if ((mBfIRBuilder->HasDebugLocation()) && (wantsDIVariables) && (mCompiler->mOptions.mToolsetType != BfToolsetType_GNU)) // DWARF chokes on this:
  14539. {
  14540. // Only add this placeholder if we don't have any values
  14541. auto diType = mBfIRBuilder->DbgGetType(paramVar->mResolvedType);
  14542. auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(mCurMethodState->mCurScope->mDIScope,
  14543. paramVar->mName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType);
  14544. mBfIRBuilder->DbgInsertValueIntrinsic(BfIRValue(), diVariable);
  14545. }
  14546. }
  14547. }
  14548. if (IsTargetingBeefBackend())
  14549. mCurMethodState->mCurScope->mValueScopeStart = mBfIRBuilder->CreateValueScopeStart();
  14550. if (methodState.mClosureState != NULL)
  14551. {
  14552. for (auto& constLocal : methodState.mClosureState->mConstLocals)
  14553. {
  14554. BfLocalVariable* localVar = new BfLocalVariable();
  14555. *localVar = constLocal;
  14556. AddLocalVariableDef(localVar, true);
  14557. }
  14558. }
  14559. bool wantsRemoveBody = false;
  14560. bool skipBody = false;
  14561. bool skipUpdateSrcPos = false;
  14562. bool skipEndChecks = false;
  14563. bool hasExternSpecifier = (methodDeclaration != NULL) && (methodDeclaration->mExternSpecifier != NULL) && (methodInstance->GetImportKind() != BfImportKind_Import_Dynamic);
  14564. auto propertyDeclaration = methodDef->GetPropertyDeclaration();
  14565. if ((methodDef != NULL) && (propertyDeclaration != NULL) && (propertyDeclaration->mExternSpecifier != NULL))
  14566. hasExternSpecifier = true;
  14567. // Allocate, clear, set classVData
  14568. if ((methodDef->mMethodType == BfMethodType_Ctor) && (methodDef->mIsStatic))
  14569. {
  14570. CreateStaticCtor();
  14571. }
  14572. else if ((mCurTypeInstance->IsBoxed()) && (methodDef->mMethodType != BfMethodType_Ctor) && (methodDef->mName != BF_METHODNAME_DYNAMICCAST) && (methodDef->mName != BF_METHODNAME_DYNAMICCAST_INTERFACE))
  14573. {
  14574. skipBody = true;
  14575. skipEndChecks = true;
  14576. if (HasCompiledOutput())
  14577. {
  14578. // Clear out DebugLoc - to mark the ".addr" code as part of prologue
  14579. mBfIRBuilder->ClearDebugLocation();
  14580. BfBoxedType* boxedType = (BfBoxedType*) mCurTypeInstance;
  14581. BfTypeInstance* innerType = boxedType->mElementType;
  14582. PopulateType(innerType, BfPopulateType_DataAndMethods);
  14583. mBfIRBuilder->PopulateType(mCurTypeInstance);
  14584. BfGetMethodInstanceFlags flags = BfGetMethodInstanceFlag_None;
  14585. if (methodInstance->mIsForeignMethodDef)
  14586. {
  14587. flags = BfGetMethodInstanceFlag_ForeignMethodDef;
  14588. }
  14589. BfTypeVector methodGenericArguments;
  14590. if (methodInstance->mMethodInfoEx != NULL)
  14591. methodGenericArguments = methodInstance->mMethodInfoEx->mMethodGenericArguments;
  14592. auto innerMethodInstance = GetMethodInstance(innerType, methodDef, methodGenericArguments, flags, methodInstance->GetForeignType());
  14593. if (innerMethodInstance.mMethodInstance->IsSkipCall())
  14594. {
  14595. if (!methodInstance->mReturnType->IsValuelessType())
  14596. {
  14597. auto retVal = GetDefaultValue(methodInstance->mReturnType);
  14598. CreateReturn(retVal);
  14599. }
  14600. }
  14601. else
  14602. {
  14603. BF_ASSERT(innerMethodInstance.mMethodInstance->mMethodDef == methodDef);
  14604. SizedArray<BfIRValue, 8> innerParams;
  14605. BfExprEvaluator exprEvaluator(this);
  14606. if (!innerType->IsValuelessType())
  14607. {
  14608. BfIRValue thisValue = mBfIRBuilder->CreateInBoundsGEP(mCurMethodState->mLocals[0]->mValue, 0, 1);
  14609. BfTypedValue innerVal(thisValue, innerType, true);
  14610. if (boxedType->IsBoxedStructPtr())
  14611. {
  14612. innerVal = LoadValue(innerVal);
  14613. innerVal = BfTypedValue(innerVal.mValue, innerType, true);
  14614. }
  14615. exprEvaluator.PushThis(NULL, innerVal, innerMethodInstance.mMethodInstance, innerParams);
  14616. }
  14617. for (int i = 1; i < (int)mCurMethodState->mLocals.size(); i++)
  14618. {
  14619. BfLocalVariable* localVar = mCurMethodState->mLocals[i];
  14620. BfTypedValue localVal = exprEvaluator.LoadLocal(localVar, true);
  14621. exprEvaluator.PushArg(localVal, innerParams);
  14622. }
  14623. if (!innerMethodInstance.mFunc)
  14624. {
  14625. BF_ASSERT(innerType->IsUnspecializedType());
  14626. }
  14627. else if (methodInstance->HasStructRet())
  14628. {
  14629. mBfIRBuilder->PopulateType(methodInstance->mReturnType);
  14630. auto returnType = BfTypedValue(mBfIRBuilder->GetArgument(0), methodInstance->mReturnType, true);
  14631. exprEvaluator.mReceivingValue = &returnType;
  14632. auto retVal = exprEvaluator.CreateCall(innerMethodInstance.mMethodInstance, innerMethodInstance.mFunc, true, innerParams, NULL, true);
  14633. BF_ASSERT(exprEvaluator.mReceivingValue == NULL); // Ensure it was actually used
  14634. mBfIRBuilder->CreateRetVoid();
  14635. }
  14636. else
  14637. {
  14638. mBfIRBuilder->PopulateType(methodInstance->mReturnType);
  14639. auto retVal = exprEvaluator.CreateCall(innerMethodInstance.mMethodInstance, innerMethodInstance.mFunc, true, innerParams, NULL, true);
  14640. if (mCurMethodInstance->mReturnType->IsValueType())
  14641. retVal = LoadValue(retVal);
  14642. CreateReturn(retVal.mValue);
  14643. }
  14644. }
  14645. }
  14646. mCurMethodState->SetHadReturn(true);
  14647. mCurMethodState->mLeftBlockUncond = true;
  14648. }
  14649. else if (methodDef->mMethodType == BfMethodType_CtorClear)
  14650. {
  14651. SetIllegalSrcPos();
  14652. mBfIRBuilder->ClearDebugLocation();
  14653. PopulateType(mCurTypeInstance, BfPopulateType_Data);
  14654. auto thisVal = GetThis();
  14655. int prevSize = mContext->mBfObjectType->mInstSize;
  14656. int curSize = mCurTypeInstance->mInstSize;
  14657. if (curSize > prevSize)
  14658. {
  14659. auto int8PtrType = CreatePointerType(GetPrimitiveType(BfTypeCode_Int8));
  14660. auto int8PtrVal = mBfIRBuilder->CreateBitCast(thisVal.mValue, mBfIRBuilder->MapType(int8PtrType));
  14661. int8PtrVal = mBfIRBuilder->CreateInBoundsGEP(int8PtrVal, GetConstValue(prevSize));
  14662. mBfIRBuilder->CreateMemSet(int8PtrVal, GetConstValue8(0), GetConstValue(curSize - prevSize), GetConstValue(mCurTypeInstance->mInstAlign));
  14663. }
  14664. skipUpdateSrcPos = true;
  14665. }
  14666. else if (((methodDef->mMethodType == BfMethodType_Ctor) || (methodDef->mMethodType == BfMethodType_CtorNoBody)) && (!hasExternSpecifier))
  14667. {
  14668. EmitCtorBody(skipBody);
  14669. }
  14670. else if ((methodDef->mMethodType == BfMethodType_Dtor) && (!hasExternSpecifier))
  14671. {
  14672. EmitDtorBody();
  14673. skipBody = true;
  14674. }
  14675. if ((!mCurTypeInstance->IsBoxed()) && (methodDeclaration != NULL) && (methodDeclaration->mHadYield) && (methodDef->mBody != NULL))
  14676. {
  14677. EmitIteratorBlock(skipBody);
  14678. }
  14679. if (methodDef->mName == BF_METHODNAME_MARKMEMBERS)
  14680. {
  14681. // We need to be able to mark deleted objects
  14682. mCurMethodState->mIgnoreObjectAccessCheck = true;
  14683. }
  14684. auto customAttributes = methodInstance->GetCustomAttributes();
  14685. if ((customAttributes != NULL) && (customAttributes->Contains(mCompiler->mDisableObjectAccessChecksAttributeTypeDef)))
  14686. mCurMethodState->mIgnoreObjectAccessCheck = true;
  14687. if ((customAttributes != NULL) && (customAttributes->Contains(mCompiler->mDisableChecksAttributeTypeDef)))
  14688. mCurMethodState->mDisableChecks = true;
  14689. if ((methodDef->mMethodType == BfMethodType_CtorNoBody) && (!methodDef->mIsStatic) &&
  14690. ((methodInstance->mChainType == BfMethodChainType_ChainHead) || (methodInstance->mChainType == BfMethodChainType_None)))
  14691. {
  14692. // We chain even non-default ctors to the default ctors
  14693. auto defaultCtor = methodInstance;
  14694. if (defaultCtor->mChainType == BfMethodChainType_ChainHead)
  14695. CallChainedMethods(defaultCtor, false);
  14696. }
  14697. auto bodyBlock = BfNodeDynCast<BfBlock>(methodDef->mBody);
  14698. if (methodDef->mBody == NULL)
  14699. {
  14700. if (methodDeclaration != NULL)
  14701. {
  14702. if (auto operatorDeclaration = BfNodeDynCast<BfOperatorDeclaration>(methodDeclaration))
  14703. {
  14704. if (operatorDeclaration->mIsConvOperator)
  14705. wantsRemoveBody = true;
  14706. }
  14707. }
  14708. bool isDllImport = false;
  14709. if (methodInstance->GetImportKind() == BfImportKind_Import_Static)
  14710. {
  14711. for (auto customAttr : methodInstance->GetCustomAttributes()->mAttributes)
  14712. {
  14713. if (customAttr.mType->mTypeDef->mFullName.ToString() == "System.ImportAttribute")
  14714. {
  14715. if (customAttr.mCtorArgs.size() == 1)
  14716. {
  14717. auto fileNameArg = customAttr.mCtorArgs[0];
  14718. int strNum = 0;
  14719. auto constant = mCurTypeInstance->mConstHolder->GetConstant(fileNameArg);
  14720. if (constant != NULL)
  14721. {
  14722. if (constant->IsNull())
  14723. continue; // Invalid
  14724. strNum = constant->mInt32;
  14725. }
  14726. else
  14727. {
  14728. strNum = GetStringPoolIdx(fileNameArg, mCurTypeInstance->mConstHolder);
  14729. }
  14730. if (!mImportFileNames.Contains(strNum))
  14731. mImportFileNames.Add(strNum);
  14732. }
  14733. }
  14734. }
  14735. //mImportFileNames
  14736. }
  14737. else if (methodInstance->GetImportKind() == BfImportKind_Import_Dynamic)
  14738. {
  14739. CreateDllImportMethod();
  14740. }
  14741. else if (((mCurTypeInstance->mTypeDef->mIsDelegate) || (mCurTypeInstance->mTypeDef->mIsFunction)) &&
  14742. (methodDef->mName == "Invoke") && (methodDef->mMethodType == BfMethodType_Normal))
  14743. {
  14744. if (mCurTypeInstance->mTypeDef->mIsFunction)
  14745. {
  14746. // Emit nothing
  14747. }
  14748. else
  14749. {
  14750. CreateDelegateInvokeMethod();
  14751. mCurMethodState->SetHadReturn(true);
  14752. mCurMethodState->mLeftBlockUncond = true;
  14753. }
  14754. }
  14755. else if ((methodDef->mName == BF_METHODNAME_DYNAMICCAST) || (methodDef->mName == BF_METHODNAME_DYNAMICCAST_INTERFACE))
  14756. {
  14757. if (mCurTypeInstance->IsObject())
  14758. {
  14759. CreateDynamicCastMethod();
  14760. }
  14761. else
  14762. {
  14763. mBfIRBuilder->CreateRet(GetDefaultValue(methodInstance->mReturnType));
  14764. mCurMethodState->mHadReturn = true;
  14765. }
  14766. }
  14767. else if ((methodDef->mName == BF_METHODNAME_ENUM_HASFLAG) && (mCurTypeInstance->IsEnum()) && (!mCurTypeInstance->IsBoxed()))
  14768. {
  14769. BfIRValue ret;
  14770. if (mCurMethodState->mLocals[1]->mResolvedType != mCurTypeInstance)
  14771. {
  14772. // This can happen if we provide an invalid name
  14773. AssertErrorState();
  14774. ret = mBfIRBuilder->CreateRet(GetDefaultValue(GetPrimitiveType(BfTypeCode_Boolean)));
  14775. }
  14776. else
  14777. {
  14778. // Unfortunate DebugLoc shenanigans-
  14779. // 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,
  14780. // so we only set the loc on the CreateRet which gets inlined out
  14781. mBfIRBuilder->SaveDebugLocation();
  14782. mBfIRBuilder->ClearDebugLocation();
  14783. BfIRValue fromBool;
  14784. if (!mCurTypeInstance->IsTypedPrimitive())
  14785. {
  14786. fromBool = GetDefaultValue(methodInstance->mReturnType);
  14787. }
  14788. else
  14789. {
  14790. auto andResult = mBfIRBuilder->CreateAnd(mCurMethodState->mLocals[0]->mValue, mCurMethodState->mLocals[1]->mValue);
  14791. auto toBool = mBfIRBuilder->CreateCmpNE(andResult, GetDefaultValue(mCurMethodState->mLocals[0]->mResolvedType));
  14792. fromBool = mBfIRBuilder->CreateNumericCast(toBool, false, BfTypeCode_Boolean);
  14793. }
  14794. mBfIRBuilder->RestoreDebugLocation();
  14795. ret = mBfIRBuilder->CreateRet(fromBool);
  14796. //ExtendLocalLifetimes(0);
  14797. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  14798. }
  14799. mCurMethodState->SetHadReturn(true);
  14800. mCurMethodState->mLeftBlockUncond = true;
  14801. }
  14802. else if (((methodDef->mName == BF_METHODNAME_ENUM_GETUNDERLYINGREF) || (methodDef->mName == BF_METHODNAME_ENUM_GETUNDERLYING)) &&
  14803. (mCurTypeInstance->IsEnum()) && (!mCurTypeInstance->IsBoxed()))
  14804. {
  14805. BfIRValue ret;
  14806. // Unfortunate DebugLoc shenanigans-
  14807. // 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,
  14808. // so we only set the loc on the CreateRet which gets inlined out
  14809. mBfIRBuilder->SaveDebugLocation();
  14810. mBfIRBuilder->ClearDebugLocation();
  14811. BfIRValue fromBool;
  14812. mBfIRBuilder->RestoreDebugLocation();
  14813. ret = mBfIRBuilder->CreateRet(GetThis().mValue);
  14814. //ExtendLocalLifetimes(0);
  14815. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  14816. mCurMethodState->SetHadReturn(true);
  14817. mCurMethodState->mLeftBlockUncond = true;
  14818. }
  14819. else if ((mCurTypeInstance->IsEnum()) && (!mCurTypeInstance->IsBoxed()) && (methodDef->mName == BF_METHODNAME_TO_STRING))
  14820. {
  14821. auto enumType = ResolveTypeDef(mCompiler->mEnumTypeDef);
  14822. if (HasCompiledOutput())
  14823. {
  14824. EmitEnumToStringBody();
  14825. }
  14826. mBfIRBuilder->CreateRetVoid();
  14827. mCurMethodState->SetHadReturn(true);
  14828. mCurMethodState->mLeftBlockUncond = true;
  14829. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  14830. }
  14831. else if ((mCurTypeInstance->IsTuple()) && (!mCurTypeInstance->IsBoxed()) && (methodDef->mName == BF_METHODNAME_TO_STRING))
  14832. {
  14833. auto enumType = ResolveTypeDef(mCompiler->mEnumTypeDef);
  14834. if (HasCompiledOutput())
  14835. {
  14836. EmitTupleToStringBody();
  14837. }
  14838. mBfIRBuilder->CreateRetVoid();
  14839. mCurMethodState->SetHadReturn(true);
  14840. mCurMethodState->mLeftBlockUncond = true;
  14841. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  14842. }
  14843. else if (methodDef->mName == BF_METHODNAME_DEFAULT_EQUALS)
  14844. {
  14845. CreateValueTypeEqualsMethod();
  14846. skipBody = true;
  14847. skipEndChecks = true;
  14848. }
  14849. else if ((methodDef->mName == BF_METHODNAME_EQUALS) && (typeDef == mCompiler->mValueTypeTypeDef))
  14850. {
  14851. CreateValueTypeEqualsMethod();
  14852. skipBody = true;
  14853. skipEndChecks = true;
  14854. }
  14855. else if (HasCompiledOutput())
  14856. {
  14857. if ((methodDef->mName == BF_METHODNAME_MARKMEMBERS) || (methodDef->mName == BF_METHODNAME_MARKMEMBERS_STATIC))
  14858. {
  14859. if (mCompiler->mOptions.mEnableRealtimeLeakCheck)
  14860. {
  14861. EmitGCMarkMembers();
  14862. }
  14863. else if (!mCurTypeInstance->IsObject())
  14864. {
  14865. }
  14866. }
  14867. else if (methodDef->mName == BF_METHODNAME_FIND_TLS_MEMBERS)
  14868. {
  14869. if (mCompiler->mOptions.mEnableRealtimeLeakCheck)
  14870. {
  14871. EmitGCFindTLSMembers();
  14872. }
  14873. }
  14874. }
  14875. }
  14876. else if (!skipBody)
  14877. {
  14878. bool isEmptyBodied = BfNodeDynCast<BfTokenNode>(methodDef->mBody) != NULL;
  14879. if (isEmptyBodied) // Generate autoProperty things
  14880. {
  14881. auto propertyDeclaration = methodDef->GetPropertyDeclaration();
  14882. if ((propertyDeclaration != NULL) && (!typeDef->HasAutoProperty(propertyDeclaration)))
  14883. {
  14884. if ((!mCurTypeInstance->IsInterface()) && (!hasExternSpecifier))
  14885. Fail("Body expected", methodDef->mBody);
  14886. }
  14887. else if (methodDef->mMethodType == BfMethodType_PropertyGetter)
  14888. {
  14889. if (methodInstance->mReturnType->IsValuelessType())
  14890. {
  14891. mBfIRBuilder->CreateRetVoid();
  14892. }
  14893. else if (HasCompiledOutput())
  14894. {
  14895. String autoPropName = typeDef->GetAutoPropertyName(propertyDeclaration);
  14896. BfFieldInstance* fieldInstance = GetFieldByName(mCurTypeInstance, autoPropName);
  14897. BfFieldDef* fieldDef = NULL;
  14898. if (fieldInstance != NULL)
  14899. fieldDef = fieldInstance->GetFieldDef();
  14900. BfType* retType = methodInstance->mReturnType;
  14901. if (retType->IsRef())
  14902. retType = retType->GetUnderlyingType();
  14903. if ((fieldInstance != NULL) && (fieldInstance->GetResolvedType() == retType) &&
  14904. ((fieldInstance->mDataIdx >= 0) || (fieldDef->IsNonConstStatic())))
  14905. {
  14906. BfTypedValue lookupValue;
  14907. if (fieldDef->IsNonConstStatic())
  14908. lookupValue = ReferenceStaticField(fieldInstance);
  14909. else if (mCurTypeInstance->IsObject())
  14910. lookupValue = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(GetThis().mValue, 0, fieldInstance->mDataIdx), fieldInstance->mResolvedType, true);
  14911. else
  14912. lookupValue = ExtractValue(GetThis(), fieldInstance, fieldInstance->mFieldIdx);
  14913. if (!methodInstance->mReturnType->IsRef())
  14914. lookupValue = LoadValue(lookupValue);
  14915. mBfIRBuilder->CreateRet(lookupValue.mValue);
  14916. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  14917. }
  14918. else
  14919. {
  14920. // This can happen if we have two properties with the same name but different types
  14921. AssertErrorState();
  14922. mBfIRBuilder->CreateRet(GetDefaultValue(methodInstance->mReturnType));
  14923. }
  14924. }
  14925. else
  14926. {
  14927. // During autocomplete, the actual type may not have the proper field instance
  14928. mBfIRBuilder->CreateRet(GetDefaultValue(methodInstance->mReturnType));
  14929. }
  14930. mCurMethodState->SetHadReturn(true);
  14931. }
  14932. else if (methodDef->mMethodType == BfMethodType_PropertySetter)
  14933. {
  14934. if (!mCompiler->IsAutocomplete())
  14935. {
  14936. String autoPropName = typeDef->GetAutoPropertyName(propertyDeclaration);
  14937. BfFieldInstance* fieldInstance = GetFieldByName(mCurTypeInstance, autoPropName);
  14938. auto fieldDef = fieldInstance->GetFieldDef();
  14939. auto& lastParam = mCurMethodState->mLocals.back();
  14940. if ((fieldInstance != NULL) && (fieldInstance->GetResolvedType() == lastParam->mResolvedType) &&
  14941. ((fieldInstance->mDataIdx >= 0) || (fieldDef->IsNonConstStatic())))
  14942. {
  14943. BfIRValue lookupAddr;
  14944. if (fieldDef->IsNonConstStatic())
  14945. lookupAddr = ReferenceStaticField(fieldInstance).mValue;
  14946. else
  14947. {
  14948. auto thisValue = GetThis();
  14949. if (thisValue.IsSplat())
  14950. {
  14951. BF_FATAL("Should not happen");
  14952. }
  14953. if (mCurTypeInstance->IsObject())
  14954. thisValue = LoadValue(thisValue);
  14955. lookupAddr = mBfIRBuilder->CreateInBoundsGEP(thisValue.mValue, 0, fieldInstance->mDataIdx);
  14956. }
  14957. mBfIRBuilder->CreateStore(lastParam->mValue, lookupAddr);
  14958. }
  14959. else if (!fieldInstance->mResolvedType->IsValuelessType())
  14960. {
  14961. // This can happen if we have two properties with the same name but different types
  14962. AssertErrorState();
  14963. }
  14964. }
  14965. }
  14966. }
  14967. if ((!mCurMethodInstance->mReturnType->IsValuelessType()) && (!isEmptyBodied))
  14968. {
  14969. mBfIRBuilder->PopulateType(mCurMethodInstance->mReturnType);
  14970. if (mCurMethodInstance->HasStructRet())
  14971. {
  14972. auto ptrType = CreatePointerType(mCurMethodInstance->mReturnType);
  14973. auto allocaInst = AllocLocalVariable(ptrType, "__return.addr", false);
  14974. auto storeInst = mBfIRBuilder->CreateStore(mBfIRBuilder->GetArgument(0), allocaInst);
  14975. mBfIRBuilder->ClearDebugLocation(storeInst);
  14976. mCurMethodState->mRetValAddr = allocaInst;
  14977. }
  14978. else
  14979. {
  14980. auto allocaInst = AllocLocalVariable(mCurMethodInstance->mReturnType, "__return", false);
  14981. mCurMethodState->mRetVal = BfTypedValue(allocaInst, mCurMethodInstance->mReturnType, true);
  14982. }
  14983. }
  14984. if (methodDef->mMethodType == BfMethodType_CtorCalcAppend)
  14985. {
  14986. mBfIRBuilder->CreateStore(GetConstValue(0), mCurMethodState->mRetVal.mValue);
  14987. BfGetSymbolReferenceKind prevSymbolKind;
  14988. BfAutoComplete* prevAutoComplete;
  14989. if (mCompiler->mResolvePassData != NULL)
  14990. {
  14991. prevSymbolKind = mCompiler->mResolvePassData->mGetSymbolReferenceKind;
  14992. prevAutoComplete = mCompiler->mResolvePassData->mAutoComplete;
  14993. mCompiler->mResolvePassData->mGetSymbolReferenceKind = BfGetSymbolReferenceKind_None;
  14994. }
  14995. EmitCtorCalcAppend();
  14996. if (mCompiler->mResolvePassData != NULL)
  14997. {
  14998. mCompiler->mResolvePassData->mGetSymbolReferenceKind = prevSymbolKind;
  14999. mCompiler->mResolvePassData->mAutoComplete = prevAutoComplete;
  15000. }
  15001. }
  15002. else if (!isEmptyBodied)
  15003. {
  15004. if (!mCurMethodState->mIRExitBlock)
  15005. mCurMethodState->mIRExitBlock = mBfIRBuilder->CreateBlock("exit", true);
  15006. bool isExpressionBody = false;
  15007. if (methodDeclaration != NULL)
  15008. {
  15009. if (methodDeclaration->mFatArrowToken != NULL)
  15010. isExpressionBody = true;
  15011. }
  15012. else if (auto propertyDeclaration = methodDef->GetPropertyDeclaration())
  15013. {
  15014. if (auto propBodyExpr = BfNodeDynCast<BfPropertyBodyExpression>(propertyDeclaration->mDefinitionBlock))
  15015. {
  15016. isExpressionBody = true;
  15017. }
  15018. }
  15019. else
  15020. {
  15021. if (auto block = BfNodeDynCast<BfBlock>(methodDef->mBody))
  15022. {
  15023. if (!block->mChildArr.IsEmpty())
  15024. {
  15025. if (auto exprStmt = BfNodeDynCast<BfExpressionStatement>(block->mChildArr.GetLast()))
  15026. {
  15027. if (exprStmt->mTrailingSemicolon == NULL)
  15028. isExpressionBody = true;
  15029. }
  15030. }
  15031. }
  15032. else
  15033. isExpressionBody = true;
  15034. }
  15035. if (auto fieldDtorBody = BfNodeDynCast<BfFieldDtorDeclaration>(methodDef->mBody))
  15036. {
  15037. while (fieldDtorBody != NULL)
  15038. {
  15039. VisitEmbeddedStatement(fieldDtorBody->mBody);
  15040. fieldDtorBody = fieldDtorBody->mNextFieldDtor;
  15041. }
  15042. }
  15043. else if (!isExpressionBody)
  15044. {
  15045. auto bodyBlock = BfNodeDynCast<BfBlock>(methodDef->mBody);
  15046. mCurMethodState->mHeadScope.mAstBlock = bodyBlock;
  15047. mCurMethodState->mHeadScope.mCloseNode = bodyBlock->mCloseBrace;
  15048. VisitCodeBlock(bodyBlock);
  15049. }
  15050. else if (auto expressionBody = BfNodeDynCast<BfExpression>(methodDef->mBody))
  15051. {
  15052. if ((methodDef->mMethodType != BfMethodType_Normal) && (propertyDeclaration == NULL))
  15053. {
  15054. BF_ASSERT(methodDeclaration->mFatArrowToken != NULL);
  15055. Fail("Only normal methods can have expression bodies", methodDeclaration->mFatArrowToken);
  15056. }
  15057. auto expectingType = mCurMethodInstance->mReturnType;
  15058. // if ((expectingType->IsVoid()) && (IsInSpecializedSection()))
  15059. // {
  15060. // Warn(0, "Using a 'void' return with an expression-bodied method isn't needed. Consider removing '=>' token", methodDeclaration->mFatArrowToken);
  15061. // }
  15062. //TODO: Why did we have all this stuff for handling void?
  15063. // if (expectingType->IsVoid())
  15064. // {
  15065. // bool wasReturnGenericParam = false;
  15066. // if ((mCurMethodState->mClosureState != NULL) && (mCurMethodState->mClosureState->mReturnType != NULL))
  15067. // {
  15068. // wasReturnGenericParam = mCurMethodState->mClosureState->mReturnType->IsGenericParam();
  15069. // }
  15070. // else
  15071. // {
  15072. // auto unspecializedMethodInstance = GetUnspecializedMethodInstance(mCurMethodInstance);
  15073. // if ((unspecializedMethodInstance != NULL) && (unspecializedMethodInstance->mReturnType->IsGenericParam()))
  15074. // wasReturnGenericParam = true;
  15075. // }
  15076. //
  15077. // // If we the void return was from a generic specialization, allow us to return a void result,
  15078. // // otherwise treat expression as though it must be a statement
  15079. // bool isStatement = expressionBody->VerifyIsStatement(mCompiler->mPassInstance, wasReturnGenericParam);
  15080. // if (isStatement)
  15081. // expectingType = NULL;
  15082. // }
  15083. UpdateSrcPos(expressionBody);
  15084. auto retVal = CreateValueFromExpression(expressionBody, expectingType);
  15085. if ((retVal) && (expectingType != NULL))
  15086. {
  15087. mCurMethodState->mHadReturn = true;
  15088. retVal = LoadValue(retVal);
  15089. EmitReturn(retVal.mValue);
  15090. }
  15091. }
  15092. }
  15093. }
  15094. BF_ASSERT(mCurMethodState->mCurScope == &mCurMethodState->mHeadScope);
  15095. if (skipUpdateSrcPos)
  15096. {
  15097. // Skip
  15098. }
  15099. else if ((bodyBlock != NULL) && (bodyBlock->mCloseBrace != NULL))
  15100. UpdateSrcPos(bodyBlock->mCloseBrace);
  15101. else if (methodDef->mBody != NULL)
  15102. UpdateSrcPos(methodDef->mBody);
  15103. else if (methodDeclaration != NULL)
  15104. UpdateSrcPos(methodDeclaration);
  15105. else if (methodDef->mDeclaringType->mTypeDeclaration != NULL)
  15106. UpdateSrcPos(methodDef->mDeclaringType->mTypeDeclaration);
  15107. else
  15108. UseDefaultSrcPos();
  15109. if (methodDef->mMethodType == BfMethodType_CtorCalcAppend)
  15110. {
  15111. if (mCurMethodState->mRetVal)
  15112. {
  15113. mCurMethodState->SetHadReturn(true);
  15114. auto retVal = mBfIRBuilder->CreateLoad(mCurMethodState->mRetVal.mValue);
  15115. mBfIRBuilder->CreateRet(retVal);
  15116. }
  15117. else
  15118. AssertErrorState();
  15119. }
  15120. if (!mCurMethodState->mHadReturn)
  15121. {
  15122. // Clear off the stackallocs that have occurred after a scopeData break
  15123. EmitDeferredScopeCalls(false, &mCurMethodState->mHeadScope, mCurMethodState->mIRExitBlock);
  15124. }
  15125. if (mCurMethodState->mIRExitBlock)
  15126. {
  15127. for (auto preExitBlock : mCurMethodState->mHeadScope.mAtEndBlocks)
  15128. mBfIRBuilder->MoveBlockToEnd(preExitBlock);
  15129. mBfIRBuilder->MoveBlockToEnd(mCurMethodState->mIRExitBlock);
  15130. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRExitBlock);
  15131. if (!mCurMethodState->mDIRetVal)
  15132. CreateDIRetVal();
  15133. }
  15134. for (auto localVar : mCurMethodState->mLocals)
  15135. {
  15136. if ((skipEndChecks) || (bodyBlock == NULL))
  15137. break;
  15138. LocalVariableDone(localVar, true);
  15139. }
  15140. if (mCurMethodState->mIRExitBlock)
  15141. {
  15142. if ((mCurMethodState->mRetVal) && (!mCurMethodInstance->HasStructRet()))
  15143. {
  15144. auto loadedVal = mBfIRBuilder->CreateLoad(mCurMethodState->mRetVal.mValue);
  15145. CreateReturn(loadedVal);
  15146. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  15147. if (mCurMethodState->mDIRetVal)
  15148. mBfIRBuilder->DbgLifetimeEnd(mCurMethodState->mDIRetVal);
  15149. }
  15150. else
  15151. {
  15152. // Have something on the last line to step onto
  15153. if (mHasFullDebugInfo)
  15154. {
  15155. if ((bodyBlock != NULL) && (bodyBlock->mCloseBrace != NULL))
  15156. UpdateSrcPos(bodyBlock->mCloseBrace);
  15157. EmitEnsureInstructionAt();
  15158. if ((irParamCount == 0) && (!IsTargetingBeefBackend()) && (mCompiler->mOptions.mAllowHotSwapping))
  15159. {
  15160. // This may be a case where we only emit 4 bytes, whereas we need 5 for a hot replace jump
  15161. mBfIRBuilder->EnsureFunctionPatchable();
  15162. }
  15163. }
  15164. mBfIRBuilder->CreateRetVoid();
  15165. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  15166. if (mCurMethodState->mDIRetVal)
  15167. mBfIRBuilder->DbgLifetimeEnd(mCurMethodState->mDIRetVal);
  15168. }
  15169. }
  15170. if ((mCurMethodInstance->mReturnType == NULL) || (mCurMethodInstance->mReturnType->IsValuelessType()))
  15171. {
  15172. if ((!mCurMethodState->mHadReturn) && (!mCurMethodState->mIRExitBlock))
  15173. {
  15174. if ((irParamCount == 0) && (!IsTargetingBeefBackend()) && (mCompiler->mOptions.mAllowHotSwapping))
  15175. {
  15176. // This may be a case where we only emit 4 bytes, whereas we need 5 for a hot replace jump
  15177. mBfIRBuilder->EnsureFunctionPatchable();
  15178. }
  15179. mBfIRBuilder->CreateRetVoid();
  15180. }
  15181. }
  15182. else
  15183. {
  15184. if (!mCurMethodState->mHadReturn)
  15185. {
  15186. auto refNode = mCurMethodInstance->mMethodDef->GetRefNode();
  15187. if (bodyBlock != NULL)
  15188. {
  15189. if (bodyBlock->mCloseBrace != NULL)
  15190. {
  15191. BfAstNode* target = bodyBlock->mCloseBrace;
  15192. Fail("Method must return value", target);
  15193. }
  15194. else
  15195. {
  15196. // It's possible to not have a closing brace if the method ends in an EOF
  15197. AssertErrorState();
  15198. }
  15199. }
  15200. }
  15201. }
  15202. // Move 'init' into 'entry'
  15203. mBfIRBuilder->MergeBlockDown(mCurMethodState->mIRInitBlock, mCurMethodState->mIREntryBlock);
  15204. mBfIRBuilder->MergeBlockDown(mCurMethodState->mIRHeadBlock, mCurMethodState->mIREntryBlock);
  15205. if ((mCurMethodInstance->mIsUnspecialized) /*|| (typeDef->mIsFunction)*/ || (mCurTypeInstance->IsUnspecializedType()))
  15206. {
  15207. // Don't keep instructions for unspecialized types
  15208. mBfIRBuilder->Func_DeleteBody(mCurMethodInstance->mIRFunction);
  15209. }
  15210. if ((hasExternSpecifier) && (!skipBody))
  15211. {
  15212. // If we hot swap, we want to make sure at least one method refers to this extern method so it gets pulled in
  15213. // incase it gets called later by some hot-loaded coded
  15214. if (mCompiler->mOptions.mAllowHotSwapping)
  15215. CreateFakeCallerMethod(mangledName);
  15216. mBfIRBuilder->Func_DeleteBody(mCurMethodInstance->mIRFunction);
  15217. }
  15218. else if ((methodInstance->GetImportKind() == BfImportKind_Import_Dynamic) && (!mCompiler->IsHotCompile()))
  15219. {
  15220. // We only need the DLL stub when we may be hot swapping
  15221. mBfIRBuilder->Func_DeleteBody(mCurMethodInstance->mIRFunction);
  15222. }
  15223. else if (wantsRemoveBody)
  15224. mBfIRBuilder->Func_DeleteBody(mCurMethodInstance->mIRFunction);
  15225. // We don't want to hold on to pointers to LLVMFunctions of unspecialized types.
  15226. // This allows us to delete the mScratchModule LLVM module without rebuilding all
  15227. // unspecialized types
  15228. if ((mCurTypeInstance->IsUnspecializedType()) || (mCurTypeInstance->IsInterface()))
  15229. {
  15230. BfLogSysM("ProcessMethod Clearing IRFunction: %p\n", methodInstance);
  15231. methodInstance->mIRFunction = BfIRFunction();
  15232. }
  15233. CheckAddFailType();
  15234. if (mHadBuildError)
  15235. prevHadBuildError.CancelRestore();
  15236. if (mHadBuildWarning)
  15237. prevHadWarning.CancelRestore();
  15238. if (!methodDef->mIsLocalMethod)
  15239. ProcessMethod_ProcessDeferredLocals();
  15240. mBfIRBuilder->SetActiveFunction(prevActiveFunction);
  15241. if (methodState.mHotDataReferenceBuilder != NULL)
  15242. {
  15243. AddHotDataReferences(&hotDataReferenceBuilder);
  15244. }
  15245. else
  15246. {
  15247. if ((methodInstance->mHotMethod != NULL) && (!methodInstance->mIsReified))
  15248. {
  15249. // Remove the hot method data
  15250. auto hotMethod = methodInstance->mHotMethod;
  15251. auto prevMethod = hotMethod->mPrevVersion;
  15252. if (prevMethod != NULL)
  15253. {
  15254. // If there's a prev method then pull its data into the main HotMethod.
  15255. // This, in effect, removes the 'hotMethod' data and rebases 'prevMethod'
  15256. // over to the main HotMethod definition to keep the HotMethod address
  15257. // invariant
  15258. for (auto ref : hotMethod->mReferences)
  15259. ref->Deref();
  15260. hotMethod->mReferences.Clear();
  15261. BF_ASSERT(prevMethod->mRefCount == 1);
  15262. hotMethod->mReferences = prevMethod->mReferences;
  15263. if (hotMethod->mSrcTypeVersion != NULL)
  15264. hotMethod->mSrcTypeVersion->Deref();
  15265. hotMethod->mSrcTypeVersion = prevMethod->mSrcTypeVersion;
  15266. prevMethod->mSrcTypeVersion = NULL;
  15267. prevMethod->mReferences.Clear();
  15268. hotMethod->mPrevVersion = prevMethod->mPrevVersion;
  15269. prevMethod->mPrevVersion = NULL;
  15270. prevMethod->Deref();
  15271. }
  15272. hotMethod->Deref();
  15273. methodInstance->mHotMethod = NULL;
  15274. }
  15275. }
  15276. }
  15277. String BfModule::GetLocalMethodName(const StringImpl& baseName, BfAstNode* anchorNode, BfMethodState* declMethodState, BfMixinState* declMixinState)
  15278. {
  15279. String name;
  15280. bool found = false;
  15281. auto checkMethodState = mCurMethodState;
  15282. while (checkMethodState != NULL)
  15283. {
  15284. if (checkMethodState->mClosureState == NULL)
  15285. break;
  15286. if (checkMethodState->mClosureState->mClosureMethodDef != NULL)
  15287. {
  15288. found = true;
  15289. name += checkMethodState->mClosureState->mClosureMethodDef->mName;
  15290. break;
  15291. }
  15292. checkMethodState = checkMethodState->mPrevMethodState;
  15293. }
  15294. if (!found)
  15295. name += mCurMethodInstance->mMethodDef->mName;
  15296. int prevSepPos = (int)name.LastIndexOf('$');
  15297. if (prevSepPos != -1)
  15298. {
  15299. name.RemoveToEnd(prevSepPos);
  15300. }
  15301. name += "@";
  15302. name += baseName;
  15303. HashContext hashCtx;
  15304. if (anchorNode != NULL)
  15305. {
  15306. hashCtx.Mixin(anchorNode->GetStartCharId());
  15307. }
  15308. //
  15309. {
  15310. auto checkMethodState = declMethodState;
  15311. auto checkMixinState = declMixinState;
  15312. while (checkMethodState != NULL)
  15313. {
  15314. if (checkMixinState != NULL)
  15315. {
  15316. hashCtx.Mixin(checkMixinState->mSource->GetStartCharId());
  15317. }
  15318. checkMethodState = checkMethodState->mPrevMethodState;
  15319. if (checkMethodState != NULL)
  15320. checkMixinState = checkMethodState->mMixinState;
  15321. }
  15322. }
  15323. auto rootMethodState = mCurMethodState->GetRootMethodState();
  15324. if (rootMethodState->mMethodInstance->mMethodInfoEx != NULL)
  15325. {
  15326. for (auto methodGenericArg : rootMethodState->mMethodInstance->mMethodInfoEx->mMethodGenericArguments)
  15327. {
  15328. StringT<128> genericTypeName;
  15329. BfMangler::Mangle(genericTypeName, mCompiler->GetMangleKind(), methodGenericArg);
  15330. hashCtx.MixinStr(genericTypeName);
  15331. }
  15332. }
  15333. uint64 hashVal = hashCtx.Finish64();
  15334. name += "$";
  15335. name += BfTypeUtils::HashEncode64(hashVal);
  15336. return name;
  15337. }
  15338. BfMethodDef* BfModule::GetLocalMethodDef(BfLocalMethod* localMethod)
  15339. {
  15340. if (localMethod->mMethodDef != NULL)
  15341. return localMethod->mMethodDef;
  15342. auto rootMethodState = mCurMethodState->GetRootMethodState();
  15343. auto declMethodState = localMethod->mDeclMethodState;
  15344. auto declMixinState = localMethod->mDeclMixinState;
  15345. auto typeInst = mCurTypeInstance;
  15346. BfAstNode* body = NULL;
  15347. BfAstNode* anchorNode = NULL;
  15348. auto _AllocDirectTypeRef = [&](BfType* type)
  15349. {
  15350. BfDirectTypeReference* directTypeRef = localMethod->mDirectTypeRefs.Alloc();
  15351. directTypeRef->Init(type);
  15352. return directTypeRef;
  15353. };
  15354. auto methodDeclaration = localMethod->mMethodDeclaration;
  15355. if (methodDeclaration != NULL)
  15356. {
  15357. body = methodDeclaration->mBody;
  15358. anchorNode = methodDeclaration->mOpenParen;
  15359. }
  15360. else
  15361. {
  15362. body = localMethod->mLambdaBindExpr->mBody;
  15363. anchorNode = localMethod->mLambdaBindExpr->mFatArrowToken;
  15364. }
  15365. BF_ASSERT(rootMethodState->mCurLocalVarId >= 0);
  15366. int methodLocalIdx = rootMethodState->mCurLocalVarId++;
  15367. BfMethodDef* methodDef;
  15368. if (methodDeclaration != NULL)
  15369. {
  15370. BfDefBuilder defBuilder(mCompiler->mSystem);
  15371. defBuilder.mPassInstance = mCompiler->mPassInstance;
  15372. defBuilder.mCurTypeDef = mCurMethodInstance->mMethodDef->mDeclaringType;
  15373. BfMethodDef* outerMethodDef = NULL;
  15374. if (localMethod->mOuterLocalMethod != NULL)
  15375. outerMethodDef = localMethod->mOuterLocalMethod->mMethodDef;
  15376. else
  15377. outerMethodDef = rootMethodState->mMethodInstance->mMethodDef;
  15378. methodDef = defBuilder.CreateMethodDef(methodDeclaration, outerMethodDef);
  15379. }
  15380. else
  15381. {
  15382. auto invokeMethod = localMethod->mLambdaInvokeMethodInstance;
  15383. methodDef = new BfMethodDef();
  15384. methodDef->mName = localMethod->mMethodName;
  15385. methodDef->mDeclaringType = mCurMethodInstance->mMethodDef->mDeclaringType;
  15386. methodDef->mReturnTypeRef = _AllocDirectTypeRef(invokeMethod->mReturnType);
  15387. methodDef->mBody = body;
  15388. for (int paramIdx = 0; paramIdx < invokeMethod->GetParamCount(); paramIdx++)
  15389. {
  15390. auto paramType = invokeMethod->GetParamType(paramIdx);
  15391. String paramName;
  15392. if (paramIdx < (int)localMethod->mLambdaBindExpr->mParams.size())
  15393. paramName = localMethod->mLambdaBindExpr->mParams[paramIdx]->ToString();
  15394. else
  15395. paramName = invokeMethod->GetParamName(paramIdx);
  15396. auto paramDef = new BfParameterDef();
  15397. paramDef->mTypeRef = _AllocDirectTypeRef(paramType);
  15398. paramDef->mName = paramName;
  15399. methodDef->mParams.Add(paramDef);
  15400. }
  15401. }
  15402. methodDef->mIdx = ~methodLocalIdx;
  15403. BF_ASSERT(!localMethod->mExpectedFullName.IsEmpty());
  15404. methodDef->mName = localMethod->mExpectedFullName;
  15405. // methodDef->mName = GetLocalMethodName(methodDef->mName, anchorNode, declMethodState, declMixinState);
  15406. //
  15407. // if (!localMethod->mExpectedFullName.IsEmpty())
  15408. // BF_ASSERT(methodDef->mName == localMethod->mExpectedFullName);
  15409. methodDef->mIsStatic = true;
  15410. methodDef->mIsLocalMethod = true;
  15411. methodDef->mIsVirtual = false;
  15412. localMethod->mMethodDef = methodDef;
  15413. auto methodInstanceGroup = new BfMethodInstanceGroup();
  15414. localMethod->mMethodInstanceGroup = methodInstanceGroup;
  15415. methodInstanceGroup->mMethodIdx = -1;
  15416. methodInstanceGroup->mOwner = mCurTypeInstance;
  15417. methodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  15418. if ((declMethodState->mMixinState != NULL) && (declMethodState->mMixinState->mTarget))
  15419. {
  15420. methodInstanceGroup->mOwner = declMethodState->mMixinState->mTarget.mType->ToTypeInstance();
  15421. BF_ASSERT(methodInstanceGroup->mOwner != NULL);
  15422. }
  15423. if ((mCompiler->mResolvePassData != NULL) && (methodDeclaration != NULL))
  15424. {
  15425. mCompiler->mResolvePassData->HandleLocalReference(methodDeclaration->mNameNode, typeInst->mTypeDef, rootMethodState->mMethodInstance->mMethodDef, methodLocalIdx);
  15426. auto autoComplete = mCompiler->mResolvePassData->mAutoComplete;
  15427. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(methodDeclaration->mNameNode)))
  15428. {
  15429. autoComplete->SetDefinitionLocation(methodDeclaration->mNameNode);
  15430. autoComplete->mInsertStartIdx = methodDeclaration->mNameNode->GetSrcStart();
  15431. autoComplete->mInsertEndIdx = methodDeclaration->mNameNode->GetSrcEnd();
  15432. autoComplete->mDefType = typeInst->mTypeDef;
  15433. autoComplete->mDefMethod = rootMethodState->mMethodInstance->mMethodDef;
  15434. autoComplete->mReplaceLocalId = methodLocalIdx;
  15435. }
  15436. }
  15437. return localMethod->mMethodDef;
  15438. }
  15439. BfModuleMethodInstance BfModule::GetLocalMethodInstance(BfLocalMethod* localMethod, const BfTypeVector& methodGenericArguments, BfMethodInstance* methodInstance, bool force)
  15440. {
  15441. BP_ZONE_F("GetLocalMethodInstance %s", localMethod->mMethodName.c_str());
  15442. BfLogSysM("GetLocalMethodInstance %p\n", localMethod);
  15443. auto rootMethodState = mCurMethodState->GetRootMethodState();
  15444. auto declMethodState = localMethod->mDeclMethodState;
  15445. auto declMixinState = localMethod->mDeclMixinState;
  15446. auto callerMethodState = mCurMethodState;
  15447. auto typeInst = mCurTypeInstance;
  15448. auto methodDef = GetLocalMethodDef(localMethod);
  15449. BfAstNode* body = NULL;
  15450. auto methodDeclaration = localMethod->mMethodDeclaration;
  15451. if (methodDeclaration != NULL)
  15452. {
  15453. body = methodDeclaration->mBody;
  15454. }
  15455. else
  15456. {
  15457. body = localMethod->mLambdaBindExpr->mBody;
  15458. }
  15459. bool hadConcreteInterfaceGenericArgument = false;
  15460. BfTypeVector sanitizedMethodGenericArguments;
  15461. // Ignore the outermost method's generic method arguments for the purpose of determining if we are the 'default' (ie: unspecialized)
  15462. // version of this method for this pass through the outermost method
  15463. int dependentGenericStartIdx = 0;
  15464. if (rootMethodState->mMethodInstance->mMethodInfoEx != NULL)
  15465. dependentGenericStartIdx = (int)rootMethodState->mMethodInstance->mMethodInfoEx->mMethodGenericArguments.size();
  15466. BfMethodInstance* outerMethodInstance = mCurMethodInstance;
  15467. if (methodGenericArguments.size() == 0)
  15468. {
  15469. if (rootMethodState->mMethodInstance->mMethodInfoEx != NULL)
  15470. sanitizedMethodGenericArguments = rootMethodState->mMethodInstance->mMethodInfoEx->mMethodGenericArguments;
  15471. }
  15472. else
  15473. {
  15474. int genericArgIdx = 0;
  15475. // for (; genericArgIdx < (int)outerMethodInstance->mMethodGenericArguments.size(); genericArgIdx++)
  15476. // {
  15477. // BF_ASSERT(methodGenericArguments[genericArgIdx] == outerMethodInstance->mMethodGenericArguments[genericArgIdx]);
  15478. // sanitizedMethodGenericArguments.push_back(methodGenericArguments[genericArgIdx]);
  15479. // }
  15480. for (; genericArgIdx < (int)methodGenericArguments.size(); genericArgIdx++)
  15481. {
  15482. auto genericArgType = methodGenericArguments[genericArgIdx];
  15483. BF_ASSERT(!genericArgType->IsRef());
  15484. if (genericArgType->IsConcreteInterfaceType())
  15485. {
  15486. hadConcreteInterfaceGenericArgument = true;
  15487. auto concreteInterfaceType = (BfConcreteInterfaceType*)genericArgType;
  15488. genericArgType = concreteInterfaceType->mInterface;
  15489. }
  15490. sanitizedMethodGenericArguments.push_back(genericArgType);
  15491. }
  15492. }
  15493. bool wantPrematureMethodInstance = false;
  15494. if (!force)
  15495. {
  15496. wantPrematureMethodInstance = (callerMethodState->mClosureState != NULL) && (callerMethodState->mClosureState->mCaptureVisitingBody);
  15497. }
  15498. auto methodInstGroup = localMethod->mMethodInstanceGroup;
  15499. bool isDefaultPass = true;
  15500. BfTypeVector lookupMethodGenericArguments;
  15501. for (int genericArgIdx = dependentGenericStartIdx; genericArgIdx < (int)methodGenericArguments.size(); genericArgIdx++)
  15502. {
  15503. auto genericArgType = methodGenericArguments[genericArgIdx];
  15504. BF_ASSERT(!genericArgType->IsRef());
  15505. lookupMethodGenericArguments.Add(genericArgType);
  15506. if (genericArgType->IsGenericParam())
  15507. {
  15508. auto genericParam = (BfGenericParamType*)genericArgType;
  15509. if ((genericParam->mGenericParamKind != BfGenericParamKind_Method) || (genericParam->mGenericParamIdx != genericArgIdx))
  15510. isDefaultPass = false;
  15511. }
  15512. else
  15513. {
  15514. isDefaultPass = false;
  15515. }
  15516. }
  15517. bool hadExistingMethodInstance = false;
  15518. if (methodInstance != NULL)
  15519. {
  15520. hadExistingMethodInstance = true;
  15521. }
  15522. else
  15523. {
  15524. if (isDefaultPass)
  15525. {
  15526. methodInstance = methodInstGroup->mDefault;
  15527. if (methodInstance != NULL)
  15528. {
  15529. hadExistingMethodInstance = true;
  15530. }
  15531. else
  15532. {
  15533. methodInstance = new BfMethodInstance();
  15534. methodInstGroup->mDefault = methodInstance;
  15535. }
  15536. }
  15537. else
  15538. {
  15539. BF_ASSERT(sanitizedMethodGenericArguments.size() != 0);
  15540. if (methodInstGroup->mMethodSpecializationMap == NULL)
  15541. methodInstGroup->mMethodSpecializationMap = new BfMethodInstanceGroup::MapType();
  15542. BfMethodInstance** methodInstancePtr = NULL;
  15543. if (!methodInstGroup->mMethodSpecializationMap->TryAdd(lookupMethodGenericArguments, NULL, &methodInstancePtr))
  15544. {
  15545. methodInstance = *methodInstancePtr;
  15546. hadExistingMethodInstance = true;
  15547. }
  15548. else
  15549. {
  15550. methodInstance = new BfMethodInstance();
  15551. *methodInstancePtr = methodInstance;
  15552. }
  15553. }
  15554. }
  15555. if (hadExistingMethodInstance)
  15556. {
  15557. if ((!methodInstance->mDisallowCalling) ||
  15558. ((wantPrematureMethodInstance) && (methodInstance->mDisallowCalling)))
  15559. return BfModuleMethodInstance(methodInstance);
  15560. BF_ASSERT((methodInstance->mMethodInfoEx == NULL) || (methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureClosureState == NULL));
  15561. }
  15562. else
  15563. {
  15564. auto methodInfoEx = methodInstance->GetMethodInfoEx();
  15565. methodInfoEx->mClosureInstanceInfo = new BfClosureInstanceInfo();
  15566. methodInfoEx->mClosureInstanceInfo->mLocalMethod = localMethod;
  15567. methodInstance->mIsReified = mCurMethodInstance->mIsReified;
  15568. methodInstance->mIsAutocompleteMethod = mCurMethodInstance->mIsAutocompleteMethod;
  15569. methodInstance->mMethodDef = methodDef;
  15570. methodInstance->mMethodInstanceGroup = localMethod->mMethodInstanceGroup;
  15571. if (hadConcreteInterfaceGenericArgument)
  15572. methodInstance->mIgnoreBody = true;
  15573. methodInfoEx->mMethodGenericArguments = sanitizedMethodGenericArguments;
  15574. for (auto genericArg : sanitizedMethodGenericArguments)
  15575. {
  15576. if (genericArg->IsPrimitiveType())
  15577. genericArg = GetWrappedStructType(genericArg);
  15578. AddDependency(genericArg, typeInst, BfDependencyMap::DependencyFlag_MethodGenericArg);
  15579. }
  15580. for (int genericParamIdx = (int)sanitizedMethodGenericArguments.size(); genericParamIdx < (int)methodDef->mGenericParams.size(); genericParamIdx++)
  15581. {
  15582. auto genericParamType = GetGenericParamType(BfGenericParamKind_Method, genericParamIdx);
  15583. methodInfoEx->mMethodGenericArguments.push_back(genericParamType);
  15584. }
  15585. SetupMethodIdHash(methodInstance);
  15586. }
  15587. auto _SetupMethodInstance = [&]()
  15588. {
  15589. BF_ASSERT(methodInstance->GetNumGenericParams() == 0);
  15590. // Generic constraints
  15591. for (int genericParamIdx = 0; genericParamIdx < (int)methodDef->mGenericParams.size(); genericParamIdx++)
  15592. {
  15593. auto genericParamInstance = new BfGenericMethodParamInstance(methodDef, genericParamIdx);
  15594. methodInstance->GetMethodInfoEx()->mGenericParams.push_back(genericParamInstance);
  15595. }
  15596. };
  15597. //////////////////////////////////////////////////////////////////////////
  15598. auto _VisitLambdaBody = [&]()
  15599. {
  15600. if (localMethod->mDeclOnly)
  15601. return;
  15602. if (mCompiler->mCanceling)
  15603. return;
  15604. if (auto blockBody = BfNodeDynCast<BfBlock>(body))
  15605. {
  15606. VisitCodeBlock(blockBody);
  15607. }
  15608. else if (auto bodyExpr = BfNodeDynCast<BfExpression>(body))
  15609. CreateValueFromExpression(bodyExpr);
  15610. };
  15611. auto _SafeResolveTypeRef = [&](BfTypeReference* typeRef)
  15612. {
  15613. SetAndRestoreValue<bool> prevIgnoreError(mIgnoreErrors, true);
  15614. auto result = ResolveTypeRef(typeRef);
  15615. if (result == NULL)
  15616. result = mContext->mBfObjectType;
  15617. return result;
  15618. };
  15619. BfTypeInstance* outerClosure = NULL;
  15620. if ((declMethodState->mClosureState != NULL) && (!declMethodState->mClosureState->mCapturing))
  15621. outerClosure = declMethodState->mClosureState->mClosureType;
  15622. BfMethodState methodState;
  15623. methodState.mPrevMethodState = declMethodState;//mCurMethodState;
  15624. BfIRFunctionType funcType;
  15625. auto voidType = GetPrimitiveType(BfTypeCode_None);
  15626. SizedArray<BfIRType, 0> paramTypes;
  15627. funcType = mBfIRBuilder->CreateFunctionType(mBfIRBuilder->MapType(voidType), paramTypes, false);
  15628. mBfIRBuilder->SaveDebugLocation();
  15629. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  15630. auto prevActiveFunction = mBfIRBuilder->GetActiveFunction();
  15631. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, true);
  15632. BfDeferredLocalAssignData deferredLocalAssignData;
  15633. //TODO: Why did we do this? It can cause us to pull in local variables that don't belong to us...
  15634. /*if (declMethodState->mDeferredLocalAssignData != NULL)
  15635. deferredLocalAssignData.ExtendFrom(declMethodState->mDeferredLocalAssignData);*/
  15636. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  15637. methodState.mIRHeadBlock = mBfIRBuilder->CreateBlock("head", true);
  15638. methodState.mIRInitBlock = mBfIRBuilder->CreateBlock("init", true);
  15639. methodState.mIREntryBlock = mBfIRBuilder->CreateBlock("entry", true);
  15640. methodState.mCurScope->mDIScope = localMethod->mDeclDIScope; //declMethodState->mCurScope->mDIScope ;
  15641. //methodState.mCurLocalVarId = declMethodState->mCurLocalVarId;
  15642. methodState.mIRFunction = declMethodState->mIRFunction;
  15643. methodState.mDeferredLocalAssignData = &deferredLocalAssignData;
  15644. mBfIRBuilder->SetInsertPoint(methodState.mIREntryBlock);
  15645. BfClosureState closureState;
  15646. if (methodDef->mMethodType == BfMethodType_Mixin)
  15647. {
  15648. if (declMethodState != NULL)
  15649. {
  15650. if ((declMethodState->mClosureState != NULL) && (declMethodState->mClosureState->mReturnType != NULL))
  15651. closureState.mReturnType = declMethodState->mClosureState->mReturnType;
  15652. else if (declMethodState->mMethodInstance != NULL)
  15653. closureState.mReturnType = declMethodState->mMethodInstance->mReturnType;
  15654. }
  15655. }
  15656. if (closureState.mReturnType == NULL)
  15657. closureState.mReturnType = _SafeResolveTypeRef(methodDef->mReturnTypeRef);
  15658. closureState.mCapturing = true;
  15659. closureState.mLocalMethod = localMethod;
  15660. closureState.mClosureInstanceInfo = methodInstance->mMethodInfoEx->mClosureInstanceInfo;
  15661. closureState.mDeclaringMethodIsMutating = mCurMethodInstance->mMethodDef->mIsMutating;
  15662. methodState.mClosureState = &closureState;
  15663. closureState.mClosureType = outerClosure;
  15664. int outerLocalsCount = (int)methodState.mLocals.size();
  15665. if (!hadExistingMethodInstance)
  15666. {
  15667. BfLogSysM("LocalMethod %p premature DoMethodDeclaration %p (Source:%p)\n", localMethod, methodInstance, (methodDeclaration != NULL) ? methodDeclaration->GetSourceData() : NULL);
  15668. SetAndRestoreValue<bool> prevIgnoreWrites(mWantsIRIgnoreWrites, true);
  15669. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, true);
  15670. // Prematurely do declaration. We will have to undo this later, so don't write this one and don't throw errors
  15671. auto declareModule = this;
  15672. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(declareModule->mCurMethodInstance, methodInstance);
  15673. SetAndRestoreValue<BfFilePosition> prevFilePos(declareModule->mCurFilePosition);
  15674. BF_ASSERT(declareModule != NULL);
  15675. methodInstance->mDeclModule = declareModule;
  15676. _SetupMethodInstance();
  15677. declareModule->DoMethodDeclaration(localMethod->mMethodDef->GetMethodDeclaration(), false, false);
  15678. methodInstance->mDisallowCalling = true; // Don't allow us to ACTUALLY call until we add the captures
  15679. }
  15680. if (wantPrematureMethodInstance)
  15681. {
  15682. // Return a premature methodInstance -- since we are partway through determining the capture of a local method, we can't rely on its
  15683. // capture information. This returned method instance can only be used for method matching, but we will visit it later to create
  15684. // its true method instance
  15685. //auto moduleMethodInstance = _CheckReturnedMethod(methodInstance);
  15686. //BF_ASSERT(moduleMethodInstance);
  15687. return BfModuleMethodInstance(methodInstance);
  15688. }
  15689. auto checkInsertBlock = mBfIRBuilder->GetInsertBlock();
  15690. BF_ASSERT(methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureClosureState == NULL);
  15691. closureState.mCaptureStartAccessId = mCurMethodState->GetRootMethodState()->mCurAccessId;
  15692. methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureClosureState = &closureState;
  15693. closureState.mClosureMethodDef = methodDef;
  15694. bool wantsVisitBody = true;
  15695. if ((methodDef->mMethodType == BfMethodType_Mixin) && (!methodGenericArguments.IsEmpty()))
  15696. wantsVisitBody = false;
  15697. if (methodInstance->mIsUnspecializedVariation)
  15698. wantsVisitBody = false;
  15699. if (wantsVisitBody)
  15700. {
  15701. BP_ZONE("VisitLambdaBody");
  15702. // For generic methods, we capture for each specialization, so make sure mIsStatic is set to 'true' for
  15703. // this capture stage for each of those times
  15704. SetAndRestoreValue<bool> prevWasStatis(methodDef->mIsStatic, true);
  15705. /*
  15706. // Only generate errors once. Also there are some errors that will occur during this scanning phase
  15707. // that will not occur during the actual lambda method generation, for example: returning a value
  15708. // when our current method is a 'void' method. This shouldn't affect capture scanning since all
  15709. // our AST nodes will still be visited
  15710. SetAndRestoreValue<bool> ignoreError(mIgnoreErrors, true);
  15711. */
  15712. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, methodInstance);
  15713. //SetAndRestoreValue<bool> wantsIgnoreWrites(mWantsISIgnoreWrites, true);
  15714. mBfIRBuilder->SaveDebugLocation();
  15715. closureState.mCaptureVisitingBody = true;
  15716. BF_ASSERT(methodInstance->mMethodInfoEx != NULL);
  15717. methodState.mGenericTypeBindings = &methodInstance->mMethodInfoEx->mGenericTypeBindings;
  15718. NewScopeState();
  15719. ProcessMethod_SetupParams(methodInstance, NULL, false, NULL);
  15720. if (methodInstance->mMethodDef->mMethodType == BfMethodType_Mixin)
  15721. {
  15722. // Allow assigning to arguments when we're capturing - which may or may not be legal at the injection site (we throw error there)
  15723. for (auto localDef : methodState.mLocals)
  15724. {
  15725. if (localDef->mResolvedType->IsVar())
  15726. continue;
  15727. localDef->mAddr = CreateAlloca(localDef->mResolvedType);
  15728. }
  15729. }
  15730. _VisitLambdaBody();
  15731. RestoreScopeState();
  15732. //ProcessMethod(methodInstance);
  15733. closureState.mCaptureVisitingBody = false;
  15734. mBfIRBuilder->RestoreDebugLocation();
  15735. }
  15736. // If we ended up being called by a method with a lower captureStartAccessId, propagate that to whoever is calling us, too...
  15737. if ((methodState.mPrevMethodState->mClosureState != NULL) && (methodState.mPrevMethodState->mClosureState->mCapturing))
  15738. {
  15739. auto prevClosureState = methodState.mPrevMethodState->mClosureState;
  15740. if (closureState.mCaptureStartAccessId < prevClosureState->mCaptureStartAccessId)
  15741. prevClosureState->mCaptureStartAccessId = closureState.mCaptureStartAccessId;
  15742. }
  15743. //RestoreScopeState();
  15744. // Actually get the referenced local methods. It's important we wait until after visiting the body, because then our own capture information
  15745. // can be used by these methods (which will be necessary if any of these methods call us directly or indirectly)
  15746. closureState.mClosureMethodDef = NULL;
  15747. for (auto methodInstance : closureState.mLocalMethodRefs)
  15748. {
  15749. GetLocalMethodInstance(methodInstance->mMethodInfoEx->mClosureInstanceInfo->mLocalMethod, BfTypeVector(), methodInstance);
  15750. }
  15751. methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureClosureState = NULL;
  15752. prevIgnoreWrites.Restore();
  15753. std::multiset<BfClosureCapturedEntry> capturedEntries;
  15754. //
  15755. {
  15756. auto varMethodState = declMethodState;
  15757. while (varMethodState != NULL)
  15758. {
  15759. if ((varMethodState->mMixinState != NULL) && (varMethodState->mMixinState->mLastTargetAccessId >= closureState.mCaptureStartAccessId))
  15760. {
  15761. BF_ASSERT(methodInstance->GetOwner() == varMethodState->mMixinState->mTarget.mType);
  15762. methodDef->mIsStatic = false;
  15763. if (rootMethodState->mMethodInstance->mMethodDef->mIsMutating)
  15764. methodDef->mIsMutating = true;
  15765. }
  15766. bool copyOuterCaptures = false;
  15767. for (int localIdx = 0; localIdx < varMethodState->mLocals.size(); localIdx++)
  15768. {
  15769. auto localVar = varMethodState->mLocals[localIdx];
  15770. if ((localVar->mReadFromId >= closureState.mCaptureStartAccessId) || (localVar->mWrittenToId >= closureState.mCaptureStartAccessId))
  15771. {
  15772. if (localVar->mIsThis)
  15773. {
  15774. // We can only set mutating if our owning type is mutating
  15775. if (localVar->mWrittenToId >= closureState.mCaptureStartAccessId)
  15776. {
  15777. if (mCurTypeInstance->IsValueType())
  15778. {
  15779. if (rootMethodState->mMethodInstance->mMethodDef->mIsMutating)
  15780. methodDef->mIsMutating = true;
  15781. }
  15782. }
  15783. methodDef->mIsStatic = false;
  15784. continue;
  15785. }
  15786. if ((localVar->mIsThis) && (outerClosure != NULL))
  15787. {
  15788. continue;
  15789. }
  15790. if ((localVar->mConstValue) || (localVar->mResolvedType->IsValuelessType()))
  15791. {
  15792. closureState.mConstLocals.push_back(*localVar);
  15793. continue;
  15794. }
  15795. BfClosureCapturedEntry capturedEntry;
  15796. auto capturedType = localVar->mResolvedType;
  15797. bool captureByRef = false;
  15798. if (!capturedType->IsRef())
  15799. {
  15800. if (localVar->mIsThis)
  15801. {
  15802. if ((localVar->mResolvedType->IsValueType()) && (mCurMethodInstance->mMethodDef->HasNoThisSplat()))
  15803. captureByRef = true;
  15804. }
  15805. else if ((!localVar->mIsReadOnly) && (localVar->mWrittenToId >= closureState.mCaptureStartAccessId))
  15806. captureByRef = true;
  15807. }
  15808. else
  15809. {
  15810. if (localVar->mWrittenToId < closureState.mCaptureStartAccessId)
  15811. {
  15812. capturedType = ((BfRefType*)capturedType)->mElementType;
  15813. }
  15814. }
  15815. if (captureByRef)
  15816. {
  15817. //capturedEntry.mIsByReference = true;
  15818. capturedType = CreateRefType(capturedType);
  15819. }
  15820. else
  15821. {
  15822. //capturedEntry.mIsByReference = false;
  15823. }
  15824. capturedEntry.mNameNode = localVar->mNameNode;
  15825. capturedEntry.mType = capturedType;
  15826. capturedEntry.mName = localVar->mName;
  15827. //capturedEntry.mLocalVarDef = localVar;
  15828. capturedEntries.insert(capturedEntry);
  15829. }
  15830. }
  15831. varMethodState = varMethodState->mPrevMethodState;
  15832. if ((varMethodState == NULL) ||
  15833. (varMethodState->mMixinState != NULL) ||
  15834. ((varMethodState->mClosureState != NULL) && (!varMethodState->mClosureState->mCapturing)))
  15835. break;
  15836. }
  15837. }
  15838. for (auto& copyField : closureState.mReferencedOuterClosureMembers)
  15839. {
  15840. auto fieldDef = copyField->GetFieldDef();
  15841. BfClosureCapturedEntry capturedEntry;
  15842. capturedEntry.mName = copyField->GetFieldDef()->mName;
  15843. capturedEntry.mType = copyField->mResolvedType;
  15844. if (capturedEntry.mType->IsRef())
  15845. {
  15846. // Keep by ref
  15847. }
  15848. else if (!fieldDef->mIsReadOnly)
  15849. {
  15850. capturedEntry.mType = CreateRefType(capturedEntry.mType);
  15851. }
  15852. capturedEntries.insert(capturedEntry);
  15853. }
  15854. int captureIdx = 0;
  15855. for (auto& capturedEntry : capturedEntries)
  15856. {
  15857. methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureEntries.Add(capturedEntry);
  15858. }
  15859. /*if (isDefaultPass)
  15860. {
  15861. // Insert captured members a params at the start. If we added at the end then it would screw up varargs methods
  15862. int captureIdx = 0;
  15863. for (auto& capturedEntry : capturedEntries)
  15864. {
  15865. methodInstance->mClosureInstanceInfo->mCaptureNodes.Add(BfNodeDynCast<BfIdentifierNode>(capturedEntry.mNameNode));
  15866. BfParameterDef* paramDef = new BfParameterDef();
  15867. paramDef->mName = capturedEntry.mName;
  15868. BfDirectTypeReference* directTypeRef = new BfDirectTypeReference();
  15869. directTypeRef->mType = capturedEntry.mType;
  15870. typeInst->mTypeDef->mDirectAllocNodes.push_back(directTypeRef);
  15871. paramDef->mTypeRef = directTypeRef;
  15872. paramDef->mParamKind = BfParamKind_ImplicitCapture;
  15873. methodDef->mParams.Insert(captureIdx, paramDef);
  15874. captureIdx++;
  15875. }
  15876. }
  15877. else
  15878. {
  15879. auto defaultMethodInstance = methodInstGroup->mDefault;
  15880. methodInstance->mClosureInstanceInfo->mCaptureNodes = defaultMethodInstance->mClosureInstanceInfo->mCaptureNodes;
  15881. }*/
  15882. methodState.Reset();
  15883. closureState.mCapturing = false;
  15884. //////////////////////////////////////////////////////////////////////////
  15885. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, false);
  15886. if (methodInstance->mReturnType != NULL)
  15887. {
  15888. BF_ASSERT(methodInstance->mDisallowCalling);
  15889. // We did a premature declaration (without captures)
  15890. methodInstance->UndoDeclaration();
  15891. methodInstance->mDisallowCalling = false;
  15892. BfLogSysM("LocalMethod %p UndoingDeclaration %p\n", localMethod, methodInstance);
  15893. }
  15894. auto declareModule = this;
  15895. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(declareModule->mCurMethodInstance, methodInstance);
  15896. SetAndRestoreValue<BfFilePosition> prevFilePos(declareModule->mCurFilePosition);
  15897. BF_ASSERT(declareModule != NULL);
  15898. methodInstance->mDeclModule = declareModule;
  15899. _SetupMethodInstance();
  15900. BfLogSysM("LocalMethod %p DoMethodDeclaration %p\n", localMethod, methodInstance);
  15901. declareModule->DoMethodDeclaration(localMethod->mMethodDef->GetMethodDeclaration(), false, false);
  15902. closureState.mReturnType = methodInstance->mReturnType;
  15903. mCompiler->mStats.mMethodsQueued++;
  15904. mCompiler->UpdateCompletion();
  15905. declareModule->mIncompleteMethodCount++;
  15906. mCompiler->mStats.mMethodsProcessed++;
  15907. if (!methodInstance->mIsReified)
  15908. mCompiler->mStats.mUnreifiedMethodsProcessed++;
  15909. auto deferMethodState = rootMethodState;
  15910. // 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)
  15911. if ((!localMethod->mDeclOnly) && (!methodInstance->mIsUnspecializedVariation) &&
  15912. (!mWantsIRIgnoreWrites) && (methodDef->mMethodType != BfMethodType_Mixin))
  15913. {
  15914. BP_ZONE("BfDeferredLocalMethod:create");
  15915. BfDeferredLocalMethod* deferredLocalMethod = new BfDeferredLocalMethod();
  15916. deferredLocalMethod->mLocalMethod = localMethod;
  15917. deferredLocalMethod->mConstLocals = closureState.mConstLocals;
  15918. deferredLocalMethod->mMethodInstance = methodInstance;
  15919. auto checkMethodState = declMethodState;
  15920. while (checkMethodState != NULL)
  15921. {
  15922. if ((checkMethodState->mClosureState != NULL) && (checkMethodState->mClosureState->mActiveDeferredLocalMethod != NULL))
  15923. {
  15924. for (auto& mixinRecord : checkMethodState->mClosureState->mActiveDeferredLocalMethod->mMixinStateRecords)
  15925. deferredLocalMethod->mMixinStateRecords.Add(mixinRecord);
  15926. }
  15927. if (checkMethodState->mMixinState != NULL)
  15928. {
  15929. BfMixinRecord mixinRecord;
  15930. mixinRecord.mSource = checkMethodState->mMixinState->mSource;
  15931. deferredLocalMethod->mMixinStateRecords.Add(mixinRecord);
  15932. }
  15933. checkMethodState = checkMethodState->mPrevMethodState;
  15934. }
  15935. rootMethodState->mDeferredLocalMethods.Add(deferredLocalMethod);
  15936. }
  15937. mBfIRBuilder->SetActiveFunction(prevActiveFunction);
  15938. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  15939. mBfIRBuilder->RestoreDebugLocation();
  15940. if (methodInstance == localMethod->mMethodInstanceGroup->mDefault)
  15941. {
  15942. auto checkMethodState = mCurMethodState;
  15943. while (checkMethodState != NULL)
  15944. {
  15945. BfLocalMethod* nextLocalMethod = NULL;
  15946. if (checkMethodState->mLocalMethodMap.TryGetValue(localMethod->mMethodName, &nextLocalMethod))
  15947. {
  15948. while (nextLocalMethod != NULL)
  15949. {
  15950. auto checkLocalMethod = nextLocalMethod;
  15951. nextLocalMethod = nextLocalMethod->mNextWithSameName;
  15952. if (checkLocalMethod == localMethod)
  15953. continue;
  15954. if (checkLocalMethod->mMethodInstanceGroup == NULL)
  15955. continue;
  15956. auto checkMethodInstance = checkLocalMethod->mMethodInstanceGroup->mDefault;
  15957. if (checkMethodInstance == NULL)
  15958. continue; // Not generated yet
  15959. if (CompareMethodSignatures(localMethod->mMethodInstanceGroup->mDefault, checkMethodInstance))
  15960. {
  15961. auto bfError = Fail("Method already declared with the same parameter types", methodInstance->mMethodDef->GetRefNode(), true);
  15962. if (bfError != NULL)
  15963. mCompiler->mPassInstance->MoreInfo("First declaration", checkMethodInstance->mMethodDef->GetRefNode());
  15964. }
  15965. }
  15966. }
  15967. checkMethodState = checkMethodState->mPrevMethodState;
  15968. }
  15969. }
  15970. return BfModuleMethodInstance(methodInstance);
  15971. }
  15972. int BfModule::GetLocalInferrableGenericArgCount(BfMethodDef* methodDef)
  15973. {
  15974. if ((!methodDef->mIsLocalMethod) || (methodDef->mGenericParams.size() == 0))
  15975. return 0;
  15976. auto rootMethodState = mCurMethodState->GetRootMethodState();
  15977. int rootMethodGenericParamCount = 0;
  15978. if (rootMethodState->mMethodInstance->mMethodInfoEx != NULL)
  15979. rootMethodGenericParamCount = (int)rootMethodState->mMethodInstance->mMethodInfoEx->mGenericParams.size();
  15980. if (mCurMethodInstance == NULL)
  15981. return rootMethodGenericParamCount;
  15982. if ((mCurMethodInstance->mMethodInfoEx == NULL) || (mCurMethodInstance->mMethodInfoEx->mClosureInstanceInfo == NULL))
  15983. return rootMethodGenericParamCount;
  15984. BfLocalMethod* callerLocalMethod = mCurMethodInstance->mMethodInfoEx->mClosureInstanceInfo->mLocalMethod;
  15985. if (callerLocalMethod == NULL)
  15986. return rootMethodGenericParamCount;
  15987. BfLocalMethod* calledLocalMethod = NULL;
  15988. rootMethodState->mLocalMethodCache.TryGetValue(methodDef->mName, &calledLocalMethod);
  15989. while ((calledLocalMethod != NULL) && (callerLocalMethod != NULL))
  15990. {
  15991. if (calledLocalMethod->mOuterLocalMethod == callerLocalMethod)
  15992. return (int)callerLocalMethod->mMethodDef->mGenericParams.size();
  15993. callerLocalMethod = calledLocalMethod->mOuterLocalMethod;
  15994. }
  15995. return rootMethodGenericParamCount;
  15996. }
  15997. void BfModule::GetMethodCustomAttributes(BfMethodInstance* methodInstance)
  15998. {
  15999. auto methodDef = methodInstance->mMethodDef;
  16000. if (methodInstance->GetCustomAttributes() != NULL)
  16001. return;
  16002. auto methodDeclaration = methodDef->GetMethodDeclaration();
  16003. auto propertyMethodDeclaration = methodDef->GetPropertyMethodDeclaration();
  16004. auto typeInstance = methodInstance->GetOwner();
  16005. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  16006. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, methodInstance);
  16007. if ((methodDeclaration != NULL) && (methodDeclaration->mAttributes != NULL))
  16008. {
  16009. if (methodInstance->GetMethodInfoEx()->mMethodCustomAttributes == NULL)
  16010. methodInstance->mMethodInfoEx->mMethodCustomAttributes = new BfMethodCustomAttributes();
  16011. methodInstance->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes = GetCustomAttributes(methodDeclaration->mAttributes,
  16012. ((methodDef->mMethodType == BfMethodType_Ctor) || (methodDef->mMethodType == BfMethodType_CtorCalcAppend)) ? BfAttributeTargets_Constructor : BfAttributeTargets_Method);
  16013. }
  16014. else if ((propertyMethodDeclaration != NULL) && (propertyMethodDeclaration->mAttributes != NULL))
  16015. {
  16016. if (methodInstance->GetMethodInfoEx()->mMethodCustomAttributes == NULL)
  16017. methodInstance->mMethodInfoEx->mMethodCustomAttributes = new BfMethodCustomAttributes();
  16018. methodInstance->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes = GetCustomAttributes(propertyMethodDeclaration->mAttributes, BfAttributeTargets_Method);
  16019. }
  16020. }
  16021. void BfModule::SetupIRFunction(BfMethodInstance* methodInstance, StringImpl& mangledName, bool isTemporaryFunc, bool* outIsIntrinsic)
  16022. {
  16023. if (methodInstance->GetImportCallKind() == BfImportCallKind_GlobalVar)
  16024. {
  16025. // Don't create a func
  16026. return;
  16027. }
  16028. auto typeInstance = methodInstance->GetOwner();
  16029. auto methodDef = methodInstance->mMethodDef;
  16030. BfIRFunctionType funcType = mBfIRBuilder->MapMethod(methodInstance);
  16031. // Don't set these pointers during resolve pass because they may become invalid if it's just a temporary autocomplete method
  16032. if (mCompiler->mResolvePassData == NULL)
  16033. {
  16034. if ((methodDef->mMethodType == BfMethodType_Ctor) && (methodDef->mIsStatic))
  16035. {
  16036. typeInstance->mHasStaticInitMethod = true;
  16037. }
  16038. if ((methodDef->mMethodType == BfMethodType_Dtor) && (methodDef->mIsStatic))
  16039. {
  16040. typeInstance->mHasStaticDtorMethod = true;
  16041. }
  16042. if ((methodDef->mMethodType == BfMethodType_Normal) && (methodDef->mIsStatic) && (methodDef->mName == BF_METHODNAME_MARKMEMBERS_STATIC))
  16043. {
  16044. typeInstance->mHasStaticMarkMethod = true;
  16045. }
  16046. if ((methodDef->mMethodType == BfMethodType_Normal) && (methodDef->mIsStatic) && (methodDef->mName == BF_METHODNAME_FIND_TLS_MEMBERS))
  16047. {
  16048. typeInstance->mHasTLSFindMethod = true;
  16049. }
  16050. }
  16051. if (isTemporaryFunc)
  16052. {
  16053. BF_ASSERT((mCompiler->mIsResolveOnly) && (mCompiler->mResolvePassData->mAutoComplete != NULL));
  16054. mangledName = "autocomplete_tmp";
  16055. }
  16056. if (!mBfIRBuilder->mIgnoreWrites)
  16057. {
  16058. BfIRFunction prevFunc;
  16059. // Remove old version (if we have one)
  16060. prevFunc = mBfIRBuilder->GetFunction(mangledName);
  16061. if (prevFunc)
  16062. {
  16063. if (methodDef->mIsExtern)
  16064. {
  16065. // Allow this
  16066. BfLogSysM("Function collision allowed multiple extern functions for %p: %d\n", methodInstance, prevFunc.mId);
  16067. }
  16068. else if (typeInstance->IsIRFuncUsed(prevFunc))
  16069. {
  16070. // We can have a collision of names when we have generic methods that differ only in
  16071. // their constraints, but they should only collide in their unspecialized form
  16072. // since only one will be chosen for a given concrete type
  16073. mCurMethodInstance->mMangleWithIdx = true;
  16074. mangledName.Clear();
  16075. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), mCurMethodInstance);
  16076. prevFunc = mBfIRBuilder->GetFunction(mangledName);
  16077. BfLogSysM("Function collision forced mangleWithIdx for %p: %d\n", methodInstance, prevFunc.mId);
  16078. }
  16079. else
  16080. {
  16081. BfLogSysM("Function collision erased prevFunc %p: %d\n", methodInstance, prevFunc.mId);
  16082. mBfIRBuilder->Func_EraseFromParent(prevFunc);
  16083. }
  16084. }
  16085. }
  16086. if (typeInstance != mContext->mBfObjectType)
  16087. {
  16088. // Only allow attributes on System.Object methods that can be handled inside the DefBuilder
  16089. GetMethodCustomAttributes(methodInstance);
  16090. }
  16091. // if (prevFunc)
  16092. // {
  16093. // if (methodDef->mIsExtern)
  16094. // {
  16095. // BfLogSysM("Reusing function for %p: %d\n", methodInstance, prevFunc.mId);
  16096. // methodInstance->mIRFunction = prevFunc;
  16097. // }
  16098. // else
  16099. // {
  16100. // if ((methodInstance->IsSpecializedByAutoCompleteMethod()) ||
  16101. // ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mResolveType >= BfResolveType_GoToDefinition)))
  16102. // {
  16103. // // If we're doing re-pass over the methods for something like BfResolveType_ShowFileSymbolReferences, then allow this collision
  16104. // BfLogSysM("Ignoring function name collision\n");
  16105. // }
  16106. // else
  16107. // {
  16108. // if (methodDef->mMethodDeclaration == NULL)
  16109. // {
  16110. // AssertErrorState();
  16111. // }
  16112. // else
  16113. // {
  16114. // BF_ASSERT(mIsSpecialModule);
  16115. // if ((mCompiler->mRevision == 1) && (HasCompiledOutput()))
  16116. // {
  16117. // // We shouldn't have name collisions on the first run!
  16118. // AssertErrorState();
  16119. // }
  16120. // }
  16121. // }
  16122. // BfLogSysM("Before erase\n");
  16123. // mBfIRBuilder->Func_EraseFromParent(prevFunc);
  16124. // }
  16125. // }
  16126. bool isIntrinsic = false;
  16127. if (!methodInstance->mIRFunction)
  16128. {
  16129. BfIRFunction func;
  16130. bool wantsLLVMFunc = ((!typeInstance->IsUnspecializedType()) && (!methodDef->IsEmptyPartial())) && (funcType);
  16131. /*if (mCurTypeInstance->mTypeDef->mName->ToString() == "ClassA")
  16132. {
  16133. if (!mIsReified)
  16134. wantsLLVMFunc = false;
  16135. }*/
  16136. if (wantsLLVMFunc)
  16137. {
  16138. func = GetIntrinsic(methodInstance, true);
  16139. if (func)
  16140. {
  16141. isIntrinsic = true;
  16142. }
  16143. else
  16144. {
  16145. func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, mangledName);
  16146. BfLogSysM("Creating FuncId:%d %s in module %p\n", func.mId, mangledName.c_str(), this);
  16147. if (methodInstance->mAlwaysInline)
  16148. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_AlwaysInline);
  16149. // if (prevFunc)
  16150. // BfLogSysM("Removing Func %d, replacing with %d\n", prevFunc.mId, func.mId);
  16151. }
  16152. methodInstance->mIRFunction = func;
  16153. //if (!ignoreWrites)
  16154. //BF_ASSERT(!func.IsFake());
  16155. }
  16156. }
  16157. if (outIsIntrinsic != NULL)
  16158. *outIsIntrinsic = isIntrinsic;
  16159. if (!isIntrinsic)
  16160. SetupIRMethod(methodInstance, methodInstance->mIRFunction, methodInstance->mAlwaysInline);
  16161. }
  16162. void BfModule::CheckHotMethod(BfMethodInstance* methodInstance, const StringImpl& inMangledName)
  16163. {
  16164. if (methodInstance->mHotMethod != NULL)
  16165. return;
  16166. if ((mCompiler->mOptions.mAllowHotSwapping) && (!methodInstance->mIsUnspecialized))
  16167. {
  16168. auto srcTypeInst = methodInstance->GetOwner();
  16169. StringT<128> mangledName = inMangledName;
  16170. if (mangledName.IsEmpty())
  16171. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), methodInstance);
  16172. // We always keep the current primary method at the same address
  16173. BfHotMethod* hotMethod;
  16174. BfHotMethod** hotMethodPtr;
  16175. if (mCompiler->mHotData->mMethodMap.TryAdd(mangledName, NULL, &hotMethodPtr))
  16176. {
  16177. hotMethod = new BfHotMethod();
  16178. *hotMethodPtr = hotMethod;
  16179. hotMethod->mRefCount = 1;
  16180. hotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_IsBound);
  16181. #ifdef BF_DBG_HOTMETHOD_IDX
  16182. static int sMethodIdx = 0;
  16183. hotMethod->mMethodIdx = sMethodIdx++;
  16184. #endif
  16185. BfLogSysM("HotMethodData %p created for method %p %s - %s\n", hotMethod, methodInstance, MethodToString(methodInstance).c_str(), mangledName.c_str());
  16186. }
  16187. else
  16188. {
  16189. hotMethod = *hotMethodPtr;
  16190. if ((hotMethod->mFlags & BfHotDepDataFlag_IsBound) != 0)
  16191. {
  16192. // This is a duplicate mangled name - we link to this new entry via a 'BfHotDupMethod'
  16193. auto prevHotMethod = *hotMethodPtr;
  16194. hotMethod = new BfHotMethod();
  16195. hotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_IsBound);
  16196. BfHotDupMethod* hotDupMethod = new BfHotDupMethod(hotMethod);
  16197. hotDupMethod->mRefCount++;
  16198. prevHotMethod->mReferences.Add(hotDupMethod);
  16199. prevHotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_HasDup);
  16200. BfLogSysM("HotMethodData %p (duplicate of %p) created for method %p %s - %s\n", hotMethod, prevHotMethod, methodInstance, MethodToString(methodInstance).c_str(), mangledName.c_str());
  16201. }
  16202. else if (mCompiler->IsHotCompile())
  16203. {
  16204. // Link the previous version into the mPrevVersion
  16205. BfHotMethod* prevMethod = new BfHotMethod();
  16206. prevMethod->mRefCount = 1;
  16207. prevMethod->mPrevVersion = hotMethod->mPrevVersion;
  16208. hotMethod->mPrevVersion = prevMethod;
  16209. prevMethod->mSrcTypeVersion = hotMethod->mSrcTypeVersion;
  16210. hotMethod->mSrcTypeVersion = NULL;
  16211. prevMethod->mFlags = hotMethod->mFlags;
  16212. hotMethod->mFlags = BfHotDepDataFlag_IsBound;
  16213. hotMethod->mReferences.MoveTo(prevMethod->mReferences);
  16214. #ifdef BF_DBG_HOTMETHOD_NAME
  16215. prevMethod->mMangledName = hotMethod->mMangledName;
  16216. #endif
  16217. BfLogSysM("HotMethodData %p created for prevmethod of %p for method %p %s\n", prevMethod, hotMethod, methodInstance, MethodToString(methodInstance).c_str());
  16218. }
  16219. else
  16220. {
  16221. BfLogSysM("HotMethodData %p used for method %p %s - %s\n", hotMethod, methodInstance, MethodToString(methodInstance).c_str(), mangledName.c_str());
  16222. hotMethod->Clear(true);
  16223. hotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_IsBound);
  16224. }
  16225. }
  16226. if (methodInstance->mIsClosure)
  16227. {
  16228. hotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_RetainMethodWithoutBinding);
  16229. }
  16230. hotMethod->mSrcTypeVersion = srcTypeInst->mHotTypeData->GetLatestVersion();
  16231. hotMethod->mSrcTypeVersion->mRefCount++;
  16232. hotMethod->mRefCount++;
  16233. #ifdef BF_DBG_HOTMETHOD_NAME
  16234. hotMethod->mMangledName = mangledName;
  16235. #endif
  16236. methodInstance->mHotMethod = hotMethod;
  16237. }
  16238. }
  16239. // methodDeclaration is NULL for default constructors
  16240. void BfModule::DoMethodDeclaration(BfMethodDeclaration* methodDeclaration, bool isTemporaryFunc, bool addToWorkList)
  16241. {
  16242. BP_ZONE("BfModule::BfMethodDeclaration");
  16243. // We could trigger a DoMethodDeclaration from a const resolver or other location, so we reset it here
  16244. // to effectively make mIgnoreWrites method-scoped
  16245. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, mWantsIRIgnoreWrites || mCurMethodInstance->mIsUnspecialized);
  16246. SetAndRestoreValue<bool> prevIsCapturingMethodMatchInfo;
  16247. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, NULL);
  16248. if (mCompiler->IsAutocomplete())
  16249. prevIsCapturingMethodMatchInfo.Init(mCompiler->mResolvePassData->mAutoComplete->mIsCapturingMethodMatchInfo, false);
  16250. if (mCurMethodInstance->mMethodInstanceGroup->mOnDemandKind == BfMethodOnDemandKind_NoDecl_AwaitingReference)
  16251. mCurMethodInstance->mMethodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_Decl_AwaitingReference;
  16252. bool ignoreWrites = mBfIRBuilder->mIgnoreWrites;
  16253. if (mAwaitingInitFinish)
  16254. FinishInit();
  16255. auto typeInstance = mCurTypeInstance;
  16256. auto typeDef = typeInstance->mTypeDef;
  16257. auto methodDef = mCurMethodInstance->mMethodDef;
  16258. BF_ASSERT(methodDef->mName != "__ASSERTNAME");
  16259. if (typeInstance->IsClosure())
  16260. {
  16261. if (methodDef->mName == "Invoke")
  16262. return;
  16263. }
  16264. auto methodInstance = mCurMethodInstance;
  16265. if ((methodInstance->IsSpecializedByAutoCompleteMethod()) || (mCurTypeInstance->IsFunction()))
  16266. addToWorkList = false;
  16267. bool hasNonGenericParams = false;
  16268. bool hasGenericParams = false;
  16269. int dependentGenericStartIdx = 0;
  16270. if (methodDef->mIsLocalMethod)
  16271. {
  16272. // If we're a local generic method inside an outer generic method, we can still be considered unspecialized
  16273. // if our outer method's generic args are specialized but ours are unspecialized. This is because locals get
  16274. // instantiated uniquely for each specialized or unspecialized pass through the outer method, but the local
  16275. // method still 'inherits' the outer's generic arguments -- but we still need to make an unspecialized pass
  16276. // over the local method each time
  16277. auto rootMethodInstance = prevMethodState.mPrevVal->GetRootMethodState()->mMethodInstance;
  16278. dependentGenericStartIdx = 0;
  16279. if (rootMethodInstance->mMethodInfoEx != NULL)
  16280. dependentGenericStartIdx = (int)rootMethodInstance->mMethodInfoEx->mMethodGenericArguments.size();
  16281. methodInstance->mIsUnspecialized = rootMethodInstance->mIsUnspecialized;
  16282. methodInstance->mIsUnspecializedVariation = rootMethodInstance->mIsUnspecializedVariation;
  16283. }
  16284. for (int genericArgIdx = dependentGenericStartIdx; genericArgIdx < (int) methodInstance->GetNumGenericArguments(); genericArgIdx++)
  16285. {
  16286. auto genericArgType = methodInstance->mMethodInfoEx->mMethodGenericArguments[genericArgIdx];
  16287. if (genericArgType->IsGenericParam())
  16288. {
  16289. hasGenericParams = true;
  16290. auto genericParam = (BfGenericParamType*)genericArgType;
  16291. methodInstance->mIsUnspecialized = true;
  16292. if ((genericParam->mGenericParamKind != BfGenericParamKind_Method) || (genericParam->mGenericParamIdx != genericArgIdx))
  16293. methodInstance->mIsUnspecializedVariation = true;
  16294. }
  16295. else
  16296. {
  16297. hasNonGenericParams = true;
  16298. if (genericArgType->IsUnspecializedType())
  16299. {
  16300. methodInstance->mIsUnspecialized = true;
  16301. methodInstance->mIsUnspecializedVariation = true;
  16302. }
  16303. }
  16304. }
  16305. if ((hasGenericParams) && (hasNonGenericParams))
  16306. {
  16307. methodInstance->mIsUnspecializedVariation = true;
  16308. }
  16309. if (typeInstance->IsUnspecializedType())
  16310. {
  16311. // A specialized method within an unspecialized type is considered an unspecialized variation -- in the sense that we don't
  16312. // actually want to do method processing on it
  16313. if ((!methodInstance->mIsUnspecialized) && (methodInstance->GetNumGenericArguments() != 0))
  16314. methodInstance->mIsUnspecializedVariation = true;
  16315. methodInstance->mIsUnspecialized = true;
  16316. }
  16317. methodInstance->mIsUnspecializedVariation |= typeInstance->IsUnspecializedTypeVariation();
  16318. for (auto genericParamDef : methodDef->mGenericParams)
  16319. {
  16320. if (mCompiler->IsAutocomplete())
  16321. {
  16322. auto autoComplete = mCompiler->mResolvePassData->mAutoComplete;
  16323. //autoComplete->CheckTypeRef()
  16324. }
  16325. }
  16326. if (methodInstance->mIsUnspecializedVariation)
  16327. {
  16328. }
  16329. if (methodInstance->mIsUnspecializedVariation)
  16330. BF_ASSERT(methodInstance->mIsUnspecialized);
  16331. if (methodDef->mMethodType == BfMethodType_Mixin)
  16332. methodInstance->mIsUnspecialized = true;
  16333. BfAutoComplete* bfAutocomplete = NULL;
  16334. if (mCompiler->mResolvePassData != NULL)
  16335. bfAutocomplete = mCompiler->mResolvePassData->mAutoComplete;
  16336. if (methodInstance->mMethodInfoEx != NULL)
  16337. {
  16338. for (int genericParamIdx = 0; genericParamIdx < (int)methodInstance->mMethodInfoEx->mGenericParams.size(); genericParamIdx++)
  16339. {
  16340. auto genericParam = methodInstance->mMethodInfoEx->mGenericParams[genericParamIdx];
  16341. if (genericParamIdx < (int)methodDef->mGenericParams.size())
  16342. {
  16343. genericParam->mExternType = GetGenericParamType(BfGenericParamKind_Method, genericParamIdx);
  16344. }
  16345. else
  16346. {
  16347. auto externConstraintDef = genericParam->GetExternConstraintDef();
  16348. genericParam->mExternType = ResolveTypeRef(externConstraintDef->mTypeRef);
  16349. auto autoComplete = mCompiler->GetAutoComplete();
  16350. if (autoComplete != NULL)
  16351. autoComplete->CheckTypeRef(externConstraintDef->mTypeRef, false);
  16352. if (genericParam->mExternType != NULL)
  16353. {
  16354. //
  16355. }
  16356. else
  16357. genericParam->mExternType = GetPrimitiveType(BfTypeCode_Var);
  16358. }
  16359. ResolveGenericParamConstraints(genericParam, methodInstance->mIsUnspecialized);
  16360. if (genericParamIdx < (int)methodDef->mGenericParams.size())
  16361. {
  16362. auto genericParamDef = methodDef->mGenericParams[genericParamIdx];
  16363. if (bfAutocomplete != NULL)
  16364. {
  16365. for (auto nameNode : genericParamDef->mNameNodes)
  16366. {
  16367. HandleMethodGenericParamRef(nameNode, typeDef, methodDef, genericParamIdx);
  16368. }
  16369. }
  16370. }
  16371. }
  16372. for (auto genericParam : methodInstance->mMethodInfoEx->mGenericParams)
  16373. {
  16374. for (auto constraintTypeInst : genericParam->mInterfaceConstraints)
  16375. AddDependency(constraintTypeInst, mCurTypeInstance, BfDependencyMap::DependencyFlag_Constraint);
  16376. if (genericParam->mTypeConstraint != NULL)
  16377. AddDependency(genericParam->mTypeConstraint, mCurTypeInstance, BfDependencyMap::DependencyFlag_Constraint);
  16378. }
  16379. }
  16380. if ((methodInstance->mIsAutocompleteMethod) && (methodDeclaration != NULL) && (!methodInstance->IsSpecializedGenericMethod()) && (methodDef->mIdx >= 0))
  16381. {
  16382. auto autoComplete = mCompiler->mResolvePassData->mAutoComplete;
  16383. BfAstNode* nameNode = methodDeclaration->mNameNode;
  16384. if (nameNode == NULL)
  16385. {
  16386. if (auto ctorDeclaration = BfNodeDynCast<BfConstructorDeclaration>(methodDeclaration))
  16387. nameNode = ctorDeclaration->mThisToken;
  16388. }
  16389. if (autoComplete->IsAutocompleteNode(nameNode))
  16390. {
  16391. autoComplete->mInsertStartIdx = nameNode->GetSrcStart();
  16392. autoComplete->mInsertEndIdx = nameNode->GetSrcEnd();
  16393. autoComplete->mDefType = typeDef;
  16394. autoComplete->mDefMethod = methodDef;
  16395. autoComplete->SetDefinitionLocation(nameNode);
  16396. if (methodDef->mIsOverride)
  16397. {
  16398. for (int virtIdx = 0; virtIdx < (int)typeInstance->mVirtualMethodTable.size(); virtIdx++)
  16399. {
  16400. auto& ventry = typeInstance->mVirtualMethodTable[virtIdx];
  16401. if (ventry.mDeclaringMethod.mMethodNum == -1)
  16402. continue;
  16403. BfMethodInstance* virtMethod = ventry.mImplementingMethod;
  16404. if (virtMethod != NULL)
  16405. {
  16406. auto virtMethodDeclaration = virtMethod->mMethodDef->GetMethodDeclaration();
  16407. if ((virtMethod->GetOwner() == typeInstance) && (virtMethodDeclaration != NULL) &&
  16408. (virtMethodDeclaration->GetSrcStart() == methodDeclaration->GetSrcStart()))
  16409. {
  16410. // Is matching method
  16411. if (virtIdx < (int)typeInstance->mBaseType->mVirtualMethodTable.size())
  16412. {
  16413. auto baseType = typeInstance->mBaseType;
  16414. if (baseType != NULL)
  16415. {
  16416. while ((baseType->mBaseType != NULL) && (virtIdx < baseType->mBaseType->mVirtualMethodTableSize))
  16417. baseType = baseType->mBaseType;
  16418. BfMethodInstance* baseVirtMethod = baseType->mVirtualMethodTable[virtIdx].mImplementingMethod;
  16419. autoComplete->SetDefinitionLocation(baseVirtMethod->mMethodDef->GetRefNode(), true);
  16420. autoComplete->mDefType = baseType->mTypeDef;
  16421. autoComplete->mDefMethod = baseVirtMethod->mMethodDef;
  16422. }
  16423. }
  16424. break;
  16425. }
  16426. }
  16427. }
  16428. }
  16429. }
  16430. }
  16431. bool reportErrors = true;
  16432. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL))
  16433. reportErrors = true;
  16434. // Only the defining contexts needs to report errors here
  16435. SetAndRestoreValue<bool> prevReporErrors(mReportErrors, reportErrors);
  16436. if (methodDef->mMethodType == BfMethodType_Dtor)
  16437. {
  16438. if (methodDef->mIsStatic)
  16439. {
  16440. }
  16441. else
  16442. {
  16443. if ((typeInstance->IsStruct()) || (typeInstance->IsTypedPrimitive()))
  16444. {
  16445. BfAstNode* refNode = methodDeclaration;
  16446. if (refNode == NULL)
  16447. {
  16448. // Whatever caused this ctor to be generated should have caused another failure
  16449. // But that failure might not be generated until the ctor is generated
  16450. }
  16451. else
  16452. {
  16453. auto dtorDecl = BfNodeDynCast<BfDestructorDeclaration>(methodDeclaration);
  16454. if (dtorDecl != NULL)
  16455. refNode = dtorDecl->mThisToken;
  16456. Fail("Structs cannot have destructors", refNode);
  16457. }
  16458. }
  16459. auto methodDeclaration = methodDef->GetMethodDeclaration();
  16460. if ((methodDeclaration != NULL) && (methodDeclaration->mVirtualSpecifier != NULL) &&
  16461. (mCurTypeInstance != mContext->mBfObjectType))
  16462. {
  16463. Fail("Virtual specifier is not required, all destructors are implicitly virtual.", methodDeclaration->mVirtualSpecifier);
  16464. }
  16465. }
  16466. }
  16467. BfType* resolvedReturnType = NULL;
  16468. if (((methodDef->mMethodType == BfMethodType_Normal) || (methodDef->mMethodType == BfMethodType_CtorCalcAppend) || (methodDef->mMethodType == BfMethodType_PropertyGetter) || (methodDef->mMethodType == BfMethodType_Operator)) &&
  16469. (methodDef->mReturnTypeRef != NULL))
  16470. {
  16471. SetAndRestoreValue<bool> prevIngoreErrors(mIgnoreErrors, mIgnoreErrors || (methodDef->GetPropertyDeclaration() != NULL));
  16472. resolvedReturnType = ResolveTypeRef(methodDef->mReturnTypeRef, BfPopulateType_Declaration,
  16473. (BfResolveTypeRefFlags)(BfResolveTypeRefFlag_NoResolveGenericParam | BfResolveTypeRefFlag_AllowRef | BfResolveTypeRefFlag_AllowRefGeneric));
  16474. if ((resolvedReturnType != NULL) && (resolvedReturnType->IsVar()) && (methodDef->mMethodType != BfMethodType_Mixin))
  16475. {
  16476. Fail("Cannot declare var return types", methodDef->mReturnTypeRef);
  16477. resolvedReturnType = GetPrimitiveType(BfTypeCode_Var);
  16478. }
  16479. if (resolvedReturnType == NULL)
  16480. resolvedReturnType = GetPrimitiveType(BfTypeCode_Var);
  16481. }
  16482. else
  16483. {
  16484. resolvedReturnType = ResolveTypeDef(mSystem->mTypeVoid);
  16485. }
  16486. BF_ASSERT(resolvedReturnType != NULL);
  16487. mCurMethodInstance->mReturnType = resolvedReturnType;
  16488. //TODO: We used to NOT add the return value dependency for specialized methods, but when we have types that are
  16489. // specialized based on the method's generic param then they can get deleted if no one else has referred to them (yet)
  16490. //if (!methodInstance->IsSpecializedGenericMethod())
  16491. AddDependency(resolvedReturnType, typeInstance, BfDependencyMap::DependencyFlag_ParamOrReturnValue);
  16492. if (methodDef->mExplicitInterface != NULL)
  16493. {
  16494. auto autoComplete = mCompiler->GetAutoComplete();
  16495. if (autoComplete != NULL)
  16496. autoComplete->CheckTypeRef(methodDef->mExplicitInterface, false);
  16497. auto explicitType = ResolveTypeRef(methodDef->mExplicitInterface, BfPopulateType_Declaration);
  16498. BfTypeInstance* explicitInterface = NULL;
  16499. if (explicitType != NULL)
  16500. explicitInterface = explicitType->ToTypeInstance();
  16501. if (explicitInterface != NULL)
  16502. {
  16503. mCurMethodInstance->GetMethodInfoEx()->mExplicitInterface = explicitInterface->ToTypeInstance();
  16504. if (autoComplete != NULL)
  16505. {
  16506. BfTokenNode* dotToken = NULL;
  16507. BfAstNode* nameNode = NULL;
  16508. if (auto methodDeclaration = BfNodeDynCast<BfMethodDeclaration>(methodDef->mMethodDeclaration))
  16509. {
  16510. dotToken = methodDeclaration->mExplicitInterfaceDotToken;
  16511. nameNode = methodDeclaration->mNameNode;
  16512. }
  16513. autoComplete->CheckExplicitInterface(explicitInterface, dotToken, nameNode);
  16514. }
  16515. }
  16516. if ((mCurMethodInstance->mMethodInfoEx != NULL) && (mCurMethodInstance->mMethodInfoEx->mExplicitInterface != NULL))
  16517. {
  16518. bool interfaceFound = false;
  16519. for (auto ifaceInst : typeInstance->mInterfaces)
  16520. interfaceFound |= ifaceInst.mInterfaceType == mCurMethodInstance->mMethodInfoEx->mExplicitInterface;
  16521. if (!interfaceFound)
  16522. {
  16523. if (methodDef->mMethodDeclaration != NULL)
  16524. Fail("Containing class has not declared to implement this interface", methodDef->mMethodDeclaration);
  16525. else
  16526. {
  16527. // For property decls, we should have already given the error during type population
  16528. if (mCompiler->mRevision == 1)
  16529. AssertErrorState();
  16530. }
  16531. }
  16532. }
  16533. }
  16534. bool isThisStruct = mCurTypeInstance->IsStruct();
  16535. BfType* thisType = NULL;
  16536. if ((!methodDef->mIsStatic) && (!mCurTypeInstance->IsValuelessType()))
  16537. {
  16538. if ((isThisStruct) || (mCurTypeInstance->IsTypedPrimitive()))
  16539. {
  16540. thisType = mCurTypeInstance;
  16541. if (thisType == NULL)
  16542. return;
  16543. if ((thisType->IsSplattable()) && (!methodDef->HasNoThisSplat()))
  16544. {
  16545. BfTypeUtils::SplatIterate([&](BfType* checkType)
  16546. {
  16547. PopulateType(checkType, BfPopulateType_Data);
  16548. }, thisType);
  16549. }
  16550. }
  16551. else
  16552. {
  16553. thisType = mCurTypeInstance;
  16554. PopulateType(thisType, BfPopulateType_Declaration);
  16555. }
  16556. }
  16557. int implicitParamCount = 0;
  16558. if ((mCurMethodInstance->mMethodInfoEx != NULL) && (mCurMethodInstance->mMethodInfoEx->mClosureInstanceInfo != NULL))
  16559. implicitParamCount = (int)methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureEntries.size();
  16560. methodInstance->mMethodDef->mParams.Reserve((int)methodDef->mParams.size());
  16561. bool hadDelegateParams = false;
  16562. bool hadParams = false;
  16563. for (int paramIdx = 0; paramIdx < (int)methodDef->mParams.size() + implicitParamCount; paramIdx++)
  16564. {
  16565. BfClosureCapturedEntry* closureCaptureEntry = NULL;
  16566. BfParameterDef* paramDef = NULL;
  16567. int paramDefIdx = -1;
  16568. if (paramIdx < implicitParamCount)
  16569. closureCaptureEntry = &methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureEntries[paramIdx];
  16570. else
  16571. {
  16572. paramDefIdx = paramIdx - implicitParamCount;
  16573. paramDef = methodDef->mParams[paramDefIdx];
  16574. }
  16575. if (hadParams)
  16576. break;
  16577. if ((paramDef != NULL) && (mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL) &&
  16578. (paramDef->mParamKind != BfParamKind_AppendIdx))
  16579. mCompiler->mResolvePassData->mAutoComplete->CheckTypeRef(paramDef->mTypeRef, false);
  16580. if ((paramDef != NULL) && (paramDef->mParamDeclaration != NULL) && (paramDef->mParamDeclaration->mAttributes != NULL))
  16581. {
  16582. if (methodInstance->GetMethodInfoEx()->mMethodCustomAttributes == NULL)
  16583. methodInstance->mMethodInfoEx->mMethodCustomAttributes = new BfMethodCustomAttributes();
  16584. while ((int)methodInstance->mMethodInfoEx->mMethodCustomAttributes->mParamCustomAttributes.size() < paramIdx)
  16585. methodInstance->mMethodInfoEx->mMethodCustomAttributes->mParamCustomAttributes.push_back(NULL);
  16586. auto customAttributes = GetCustomAttributes(paramDef->mParamDeclaration->mAttributes, BfAttributeTargets_Parameter);
  16587. methodInstance->mMethodInfoEx->mMethodCustomAttributes->mParamCustomAttributes.push_back(customAttributes);
  16588. }
  16589. BfType* resolvedParamType = NULL;
  16590. if (closureCaptureEntry != NULL)
  16591. resolvedParamType = closureCaptureEntry->mType;
  16592. else if (paramDef->mTypeRef->IsA<BfLetTypeReference>())
  16593. {
  16594. Fail("Cannot declare 'let' parameters", paramDef->mTypeRef);
  16595. resolvedParamType = mContext->mBfObjectType;
  16596. }
  16597. else if (paramDef->mTypeRef->IsA<BfVarTypeReference>())
  16598. {
  16599. if (methodDef->mMethodType != BfMethodType_Mixin)
  16600. {
  16601. Fail("Cannot declare var parameters", paramDef->mTypeRef);
  16602. resolvedParamType = mContext->mBfObjectType;
  16603. }
  16604. else
  16605. resolvedParamType = GetPrimitiveType(BfTypeCode_Var);
  16606. }
  16607. BfType* unresolvedParamType = resolvedParamType;
  16608. bool wasGenericParam = false;
  16609. if (resolvedParamType == NULL)
  16610. {
  16611. SetAndRestoreValue<bool> prevIngoreErrors(mIgnoreErrors, mIgnoreErrors || (methodDef->GetPropertyDeclaration() != NULL));
  16612. resolvedParamType = ResolveTypeRef(paramDef->mTypeRef, BfPopulateType_Declaration,
  16613. (BfResolveTypeRefFlags)(BfResolveTypeRefFlag_NoResolveGenericParam | BfResolveTypeRefFlag_AllowRef | BfResolveTypeRefFlag_AllowRefGeneric | BfResolveTypeRefFlag_AllowGenericMethodParamConstValue));
  16614. }
  16615. if (resolvedParamType == NULL)
  16616. {
  16617. resolvedParamType = GetPrimitiveType(BfTypeCode_Var);
  16618. unresolvedParamType = resolvedParamType;
  16619. if (mCurTypeInstance->IsBoxed())
  16620. {
  16621. auto boxedType = (BfBoxedType*)mCurTypeInstance;
  16622. // If we failed a lookup here then we better have also failed it in the original type
  16623. BF_ASSERT(boxedType->mElementType->mModule->mHadBuildError || mContext->mFailTypes.Contains(boxedType->mElementType));
  16624. }
  16625. }
  16626. if (!methodInstance->IsSpecializedGenericMethod())
  16627. AddDependency(resolvedParamType, typeInstance, BfDependencyMap::DependencyFlag_ParamOrReturnValue);
  16628. PopulateType(resolvedParamType, BfPopulateType_Declaration);
  16629. AddDependency(resolvedParamType, mCurTypeInstance, BfDependencyMap::DependencyFlag_LocalUsage);
  16630. if ((paramDef != NULL) && (paramDef->mParamDeclaration != NULL) && (paramDef->mParamDeclaration->mInitializer != NULL) &&
  16631. (!paramDef->mParamDeclaration->mInitializer->IsA<BfBlock>()))
  16632. {
  16633. BfMethodState methodState;
  16634. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  16635. methodState.mTempKind = BfMethodState::TempKind_Static;
  16636. BfTypedValue defaultValue;
  16637. if (resolvedParamType->IsConstExprValue())
  16638. {
  16639. auto constExprType = (BfConstExprValueType*)resolvedParamType;
  16640. BfExprEvaluator exprEvaluator(this);
  16641. exprEvaluator.mExpectingType = constExprType->mType;
  16642. exprEvaluator.GetLiteral(NULL, constExprType->mValue);
  16643. defaultValue = exprEvaluator.GetResult();
  16644. }
  16645. else
  16646. {
  16647. BfConstResolver constResolver(this);
  16648. defaultValue = constResolver.Resolve(paramDef->mParamDeclaration->mInitializer, resolvedParamType, BfConstResolveFlag_NoCast);
  16649. if ((defaultValue) && (defaultValue.mType != resolvedParamType))
  16650. {
  16651. SetAndRestoreValue<bool> prevIgnoreWrite(mBfIRBuilder->mIgnoreWrites, true);
  16652. auto castedDefaultValue = Cast(paramDef->mParamDeclaration->mInitializer, defaultValue, resolvedParamType, (BfCastFlags)(BfCastFlags_SilentFail | BfCastFlags_NoConversionOperator));
  16653. if ((castedDefaultValue) && (castedDefaultValue.mValue.IsConst()))
  16654. {
  16655. defaultValue = castedDefaultValue; // Good!
  16656. }
  16657. else if (!CanImplicitlyCast(defaultValue, resolvedParamType))
  16658. {
  16659. // We only care that we get a constant value that can be implicitly casted at the callsite- even if that requires
  16660. // a conversion operator.
  16661. // This should throw an error
  16662. defaultValue = Cast(paramDef->mParamDeclaration->mInitializer, defaultValue, resolvedParamType);
  16663. AssertErrorState();
  16664. if (!defaultValue.mValue.IsConst())
  16665. defaultValue = BfTypedValue();
  16666. }
  16667. }
  16668. }
  16669. if (!defaultValue)
  16670. {
  16671. defaultValue = GetDefaultTypedValue(resolvedParamType);
  16672. if (!defaultValue.mValue.IsConst())
  16673. defaultValue = BfTypedValue();
  16674. }
  16675. if (defaultValue)
  16676. {
  16677. BF_ASSERT(defaultValue.mValue.IsConst());
  16678. while ((int)mCurMethodInstance->mDefaultValues.size() < paramDefIdx)
  16679. mCurMethodInstance->mDefaultValues.Add(BfIRValue());
  16680. CurrentAddToConstHolder(defaultValue.mValue);
  16681. mCurMethodInstance->mDefaultValues.Add(defaultValue.mValue);
  16682. }
  16683. }
  16684. if ((paramDef != NULL) && (paramDef->mParamKind == BfParamKind_Params))
  16685. {
  16686. bool addParams = true;
  16687. bool isValid = false;
  16688. auto resolvedParamTypeInst = resolvedParamType->ToTypeInstance();
  16689. if ((resolvedParamTypeInst != NULL) && (resolvedParamTypeInst->mTypeDef == mCompiler->mSpanTypeDef))
  16690. {
  16691. // Span<T>
  16692. isValid = true;
  16693. }
  16694. else if (resolvedParamType->IsArray())
  16695. {
  16696. // Array is the 'normal' params type
  16697. isValid = true;
  16698. }
  16699. else if ((resolvedParamType->IsDelegate()) || (resolvedParamType->IsFunction()))
  16700. {
  16701. hadDelegateParams = true;
  16702. // This means we copy the params from a delegate
  16703. BfMethodParam methodParam;
  16704. methodParam.mResolvedType = resolvedParamType;
  16705. methodParam.mParamDefIdx = paramDefIdx;
  16706. methodParam.mDelegateParamIdx = 0;
  16707. auto invokeMethodInstance = methodParam.GetDelegateParamInvoke();
  16708. for (int delegateParamIdx = 0; delegateParamIdx < invokeMethodInstance->GetParamCount(); delegateParamIdx++)
  16709. {
  16710. methodParam.mDelegateParamIdx = delegateParamIdx;
  16711. mCurMethodInstance->mParams.Add(methodParam);
  16712. auto paramType = invokeMethodInstance->GetParamType(delegateParamIdx);
  16713. if (!methodInstance->IsSpecializedGenericMethod())
  16714. AddDependency(paramType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ParamOrReturnValue);
  16715. }
  16716. isValid = true;
  16717. addParams = false;
  16718. }
  16719. else if (resolvedParamType->IsGenericParam())
  16720. {
  16721. auto genericParamInstance = GetGenericParamInstance((BfGenericParamType*)resolvedParamType);
  16722. if (genericParamInstance->mTypeConstraint != NULL)
  16723. {
  16724. auto typeInstConstraint = genericParamInstance->mTypeConstraint->ToTypeInstance();
  16725. if (genericParamInstance->mTypeConstraint->IsArray())
  16726. {
  16727. BfMethodParam methodParam;
  16728. methodParam.mResolvedType = resolvedParamType;
  16729. methodParam.mParamDefIdx = paramDefIdx;
  16730. mCurMethodInstance->mParams.Add(methodParam);
  16731. isValid = true;
  16732. }
  16733. else if ((genericParamInstance->mTypeConstraint->IsDelegate()) || (genericParamInstance->mTypeConstraint->IsFunction()) ||
  16734. ((genericParamInstance != NULL) && (typeInstConstraint != NULL) &&
  16735. ((typeInstConstraint->mTypeDef == mCompiler->mDelegateTypeDef) || (typeInstConstraint->mTypeDef == mCompiler->mFunctionTypeDef))))
  16736. {
  16737. mCurMethodInstance->mHadGenericDelegateParams = true;
  16738. isValid = true;
  16739. addParams = false;
  16740. }
  16741. }
  16742. }
  16743. else
  16744. {
  16745. auto paramTypeInst = resolvedParamType->ToTypeInstance();
  16746. if ((paramTypeInst != NULL) &&
  16747. ((paramTypeInst->mTypeDef == mCompiler->mDelegateTypeDef) || (paramTypeInst->mTypeDef == mCompiler->mFunctionTypeDef)))
  16748. {
  16749. // If we have a 'params T' and 'T' gets specialized with actually 'Delegate' or 'Function' then just ignore it
  16750. isValid = true;
  16751. addParams = false;
  16752. }
  16753. }
  16754. if (!isValid)
  16755. {
  16756. Fail("Parameters with 'params' specifiers can only be used for array, span, delegate, or function types", paramDef->mParamDeclaration->mModToken);
  16757. // Failure case, make it an Object[]
  16758. resolvedParamType = CreateArrayType(mContext->mBfObjectType, 1);
  16759. }
  16760. if (addParams)
  16761. {
  16762. BfMethodParam methodParam;
  16763. methodParam.mResolvedType = resolvedParamType;
  16764. methodParam.mParamDefIdx = paramDefIdx;
  16765. mCurMethodInstance->mParams.push_back(methodParam);
  16766. }
  16767. if (paramDefIdx < (int)methodDef->mParams.size() - 1)
  16768. {
  16769. Fail("Only the last parameter can specify 'params'", paramDef->mParamDeclaration->mModToken);
  16770. }
  16771. }
  16772. else
  16773. {
  16774. BfMethodParam methodParam;
  16775. methodParam.mResolvedType = resolvedParamType;
  16776. methodParam.mParamDefIdx = paramDefIdx;
  16777. mCurMethodInstance->mParams.Add(methodParam);
  16778. }
  16779. }
  16780. if (hadDelegateParams)
  16781. {
  16782. HashSet<String> usedNames;
  16783. Dictionary<int, int> usedParamDefIdx;
  16784. for (auto methodParam : methodDef->mParams)
  16785. {
  16786. usedNames.Add(methodParam->mName);
  16787. }
  16788. for (auto& methodParam : mCurMethodInstance->mParams)
  16789. {
  16790. if ((methodParam.mParamDefIdx != -1) && (methodParam.mDelegateParamIdx == 0))
  16791. {
  16792. int* refCount = NULL;
  16793. usedParamDefIdx.TryAdd(methodParam.mParamDefIdx, NULL, &refCount);
  16794. (*refCount)++;
  16795. }
  16796. }
  16797. for (auto& methodParam : mCurMethodInstance->mParams)
  16798. {
  16799. if (methodParam.mDelegateParamIdx != -1)
  16800. {
  16801. if (usedParamDefIdx[methodParam.mParamDefIdx] > 1)
  16802. methodParam.mDelegateParamNameCombine = true;
  16803. BfMethodInstance* invokeMethodInstance = methodParam.GetDelegateParamInvoke();
  16804. String paramName = invokeMethodInstance->GetParamName(methodParam.mDelegateParamIdx);
  16805. if (usedNames.Contains(paramName))
  16806. methodParam.mDelegateParamNameCombine = true;
  16807. }
  16808. }
  16809. }
  16810. int argIdx = 0;
  16811. PopulateType(methodInstance->mReturnType, BfPopulateType_Data);
  16812. if (methodInstance->HasStructRet())
  16813. argIdx++;
  16814. if (!methodDef->mIsStatic)
  16815. {
  16816. if (methodInstance->GetParamIsSplat(-1))
  16817. argIdx += methodInstance->GetParamType(-1)->GetSplatCount();
  16818. else if (!methodInstance->GetOwner()->IsValuelessType())
  16819. argIdx++;
  16820. }
  16821. for (auto& methodParam : mCurMethodInstance->mParams)
  16822. {
  16823. if (methodParam.mResolvedType->IsMethodRef())
  16824. {
  16825. methodParam.mIsSplat = true;
  16826. }
  16827. else if (methodParam.mResolvedType->IsComposite())
  16828. {
  16829. PopulateType(methodParam.mResolvedType, BfPopulateType_Data);
  16830. if (methodParam.mResolvedType->IsSplattable())
  16831. {
  16832. int splatCount = methodParam.mResolvedType->GetSplatCount();
  16833. if (argIdx + splatCount <= mCompiler->mOptions.mMaxSplatRegs)
  16834. {
  16835. methodParam.mIsSplat = true;
  16836. argIdx += splatCount;
  16837. continue;
  16838. }
  16839. }
  16840. }
  16841. argIdx++;
  16842. }
  16843. bool hasExternSpecifier = (methodDeclaration != NULL) && (methodDeclaration->mExternSpecifier != NULL);
  16844. if ((hasExternSpecifier) && (methodDeclaration->mBody != NULL))
  16845. {
  16846. Fail("Cannot 'extern' and declare a body", methodDeclaration->mExternSpecifier);
  16847. }
  16848. else if ((methodDeclaration != NULL) && (methodDeclaration->mBody == NULL) && (!hasExternSpecifier) &&
  16849. (!typeInstance->IsInterface()) && (!mCurTypeInstance->IsDelegate()) && (!mCurTypeInstance->IsFunction()) &&
  16850. (!methodDef->mIsPartial) && (!methodDef->mIsAbstract) &&
  16851. (!methodDef->mIsSkipCall))
  16852. {
  16853. if (methodDeclaration->mEndSemicolon == NULL)
  16854. {
  16855. AssertParseErrorState();
  16856. }
  16857. else
  16858. {
  16859. bool isError = true;
  16860. if (typeInstance->IsTypedPrimitive())
  16861. {
  16862. if (auto operatorDeclaration = BfNodeDynCast<BfOperatorDeclaration>(methodDeclaration))
  16863. {
  16864. if ((operatorDeclaration->mIsConvOperator) && (methodInstance->mParams.size() == 1))
  16865. {
  16866. if (((methodInstance->mReturnType == typeInstance) && (methodInstance->GetParamType(0) == typeInstance->GetUnderlyingType())) ||
  16867. ((methodInstance->mReturnType == typeInstance->GetUnderlyingType()) && (methodInstance->GetParamType(0) == typeInstance)))
  16868. {
  16869. isError = false;
  16870. }
  16871. }
  16872. }
  16873. }
  16874. if (isError)
  16875. {
  16876. Fail(StrFormat("'%s' must declare a body because it is not marked abstract, extern, or partial",
  16877. MethodToString(methodInstance).c_str()),
  16878. methodDef->GetRefNode());
  16879. }
  16880. }
  16881. }
  16882. if (methodDef->IsEmptyPartial())
  16883. hasExternSpecifier = true;
  16884. if (!methodInstance->IsAutocompleteMethod())
  16885. {
  16886. auto defaultMethodInstance = methodInstance->mMethodInstanceGroup->mDefault;
  16887. int implicitParamCount = methodInstance->GetImplicitParamCount();
  16888. int defaultImplicitParamCount = defaultMethodInstance->GetImplicitParamCount();
  16889. int actualParamCount = (int)methodInstance->mParams.size() - implicitParamCount;
  16890. BF_ASSERT((actualParamCount == defaultMethodInstance->mParams.size() - defaultImplicitParamCount) || (defaultMethodInstance->mHadGenericDelegateParams));
  16891. mCurMethodInstance->mHadGenericDelegateParams = defaultMethodInstance->mHadGenericDelegateParams;
  16892. int paramIdx = 0;
  16893. int defaultParamIdx = 0;
  16894. while (true)
  16895. {
  16896. bool isDone = paramIdx + implicitParamCount >= (int)methodInstance->mParams.size();
  16897. bool isDefaultDone = defaultParamIdx + defaultImplicitParamCount >= (int)defaultMethodInstance->mParams.size();
  16898. if ((!isDone) && (methodInstance->mParams[paramIdx + implicitParamCount].mDelegateParamIdx >= 0))
  16899. {
  16900. paramIdx++;
  16901. continue;
  16902. }
  16903. if ((!isDefaultDone) && (defaultMethodInstance->mParams[defaultParamIdx + defaultImplicitParamCount].mDelegateParamIdx >= 0))
  16904. {
  16905. defaultParamIdx++;
  16906. continue;
  16907. }
  16908. if ((isDone) || (isDefaultDone))
  16909. {
  16910. // 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
  16911. // to cause us to throw an assertion in the declaration here
  16912. if (!defaultMethodInstance->mHadGenericDelegateParams)
  16913. BF_ASSERT((isDone) && (isDefaultDone));
  16914. break;
  16915. }
  16916. methodInstance->mParams[paramIdx + implicitParamCount].mWasGenericParam = defaultMethodInstance->mParams[defaultParamIdx + defaultImplicitParamCount].mResolvedType->IsGenericParam();
  16917. paramIdx++;
  16918. defaultParamIdx++;
  16919. }
  16920. }
  16921. StringT<128> mangledName;
  16922. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), mCurMethodInstance);
  16923. for (int paramIdx = 0; paramIdx < methodInstance->GetParamCount(); paramIdx++)
  16924. {
  16925. auto paramType = methodInstance->GetParamType(paramIdx);
  16926. if (paramType->IsComposite())
  16927. PopulateType(paramType, BfPopulateType_Data);
  16928. if (!methodInstance->IsParamSkipped(paramIdx))
  16929. {
  16930. if (paramType->IsStruct())
  16931. {
  16932. //
  16933. }
  16934. else
  16935. {
  16936. PopulateType(paramType, BfPopulateType_Declaration);
  16937. }
  16938. }
  16939. }
  16940. // Only process method in default unspecialized mode, not in variations
  16941. if (methodInstance->mIsUnspecializedVariation)
  16942. return;
  16943. PopulateType(resolvedReturnType, BfPopulateType_Data);
  16944. auto retLLVMType = mBfIRBuilder->MapType(resolvedReturnType);
  16945. if (resolvedReturnType->IsValuelessType())
  16946. retLLVMType = mBfIRBuilder->GetPrimitiveType(BfTypeCode_None);
  16947. if (!mBfIRBuilder->mIgnoreWrites)
  16948. {
  16949. bool isIntrinsic = false;
  16950. if (!methodInstance->mIRFunction)
  16951. SetupIRFunction(methodInstance, mangledName, isTemporaryFunc, &isIntrinsic);
  16952. if (isIntrinsic)
  16953. {
  16954. addToWorkList = false;
  16955. }
  16956. }
  16957. auto func = methodInstance->mIRFunction;
  16958. // if (methodInstance->mIsReified)
  16959. // CheckHotMethod(methodInstance, mangledName);
  16960. 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);
  16961. SizedArray<BfIRMDNode, 8> diParams;
  16962. diParams.push_back(mBfIRBuilder->DbgGetType(resolvedReturnType));
  16963. if ((!methodDef->mIsStatic) && (typeDef->mIsStatic) && (methodDef->mMethodDeclaration != NULL))
  16964. {
  16965. //CS0708
  16966. Fail("Cannot declare instance members in a static class", methodDef->GetRefNode());
  16967. }
  16968. if ((methodDef->mIsVirtual) && (methodDef->mGenericParams.size() != 0))
  16969. {
  16970. Fail("Virtual generic methods not supported", methodDeclaration->mVirtualSpecifier);
  16971. methodDef->mIsVirtual = false;
  16972. }
  16973. if ((methodDeclaration != NULL) && (methodDeclaration->mMutSpecifier != NULL) && (!mCurTypeInstance->IsBoxed()) && (!methodInstance->mIsForeignMethodDef))
  16974. {
  16975. if (methodDef->mIsStatic)
  16976. Warn(0, "Unnecessary 'mut' specifier, static methods have no implicit 'this' target to mutate", methodDeclaration->mMutSpecifier);
  16977. else if ((!mCurTypeInstance->IsValueType()) && (!mCurTypeInstance->IsInterface()))
  16978. Warn(0, "Unnecessary 'mut' specifier, methods of reference types are implicitly mutating", methodDeclaration->mMutSpecifier);
  16979. else if (methodDef->mMethodType == BfMethodType_Ctor)
  16980. Warn(0, "Unnecessary 'mut' specifier, constructors are implicitly mutating", methodDeclaration->mMutSpecifier);
  16981. else if (methodDef->mMethodType == BfMethodType_Dtor)
  16982. Warn(0, "Unnecessary 'mut' specifier, destructors are implicitly mutating", methodDeclaration->mMutSpecifier);
  16983. }
  16984. if (isTemporaryFunc)
  16985. {
  16986. // This handles temporary methods for autocomplete types
  16987. BF_ASSERT(mIsScratchModule);
  16988. BF_ASSERT(mCompiler->IsAutocomplete());
  16989. BfLogSysM("DoMethodDeclaration autocomplete bailout\n");
  16990. return; // Bail out early for autocomplete pass
  16991. }
  16992. //TODO: We used to have this (this != mContext->mExternalFuncModule) check, but it caused us to keep around
  16993. // an invalid mFuncRefernce (which came from GetMethodInstanceAtIdx) which later got remapped by the
  16994. // autocompleter. Why did we have this check anyway?
  16995. /*if ((typeInstance->mContext != mContext) && (!methodDef->IsEmptyPartial()))
  16996. {
  16997. AddMethodReference(methodInstance);
  16998. mFuncReferences[methodInstance] = func;
  16999. BfLogSysM("Adding func reference (DoMethodDeclaration). Module:%p MethodInst:%p LLVMFunc:%p\n", this, methodInstance, func);
  17000. }*/
  17001. if (mParentModule != NULL)
  17002. {
  17003. // For extension modules we need to keep track of our own methods so we can know which methods
  17004. // we have defined ourselves and which are from the parent module or other extensions
  17005. if (!func.IsFake())
  17006. mFuncReferences[methodInstance] = func;
  17007. }
  17008. if (addToWorkList)
  17009. {
  17010. bool wasAwaitingDecl = methodInstance->mMethodInstanceGroup->mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingDecl;
  17011. if (wasAwaitingDecl)
  17012. methodInstance->mMethodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_Decl_AwaitingReference;
  17013. if ((!methodDef->mIsAbstract) && (!methodInstance->mIgnoreBody))
  17014. {
  17015. if (!wasAwaitingDecl)
  17016. AddMethodToWorkList(methodInstance);
  17017. }
  17018. else
  17019. {
  17020. BfLogSysM("DoMethodDeclaration ignoring method body %d %d %d\n", hasExternSpecifier, methodDef->mIsAbstract, methodInstance->mIgnoreBody);
  17021. methodInstance->mIgnoreBody = true;
  17022. if (typeInstance->IsUnspecializedType())
  17023. {
  17024. // Don't hold on to actual Function for unspecialized types
  17025. methodInstance->mIRFunction = BfIRFunction();
  17026. }
  17027. }
  17028. }
  17029. if ((!methodInstance->IsSpecializedGenericMethodOrType()) && (!mCurTypeInstance->IsBoxed()) &&
  17030. (!methodDef->mIsLocalMethod) &&
  17031. (!CheckDefineMemberProtection(methodDef->mProtection, methodInstance->mReturnType)))
  17032. {
  17033. if (methodDef->mMethodType == BfMethodType_PropertyGetter)
  17034. {
  17035. //TODO:
  17036. //CS0053
  17037. Fail(StrFormat("Inconsistent accessibility: property type '%s' is less accessible than property '%s'",
  17038. TypeToString(methodInstance->mReturnType).c_str(), MethodToString(methodInstance).c_str()),
  17039. methodDef->mReturnTypeRef, true);
  17040. }
  17041. else
  17042. {
  17043. //CS0050
  17044. Fail(StrFormat("Inconsistent accessibility: return type '%s' is less accessible than method '%s'",
  17045. TypeToString(methodInstance->mReturnType).c_str(), MethodToString(methodInstance).c_str()),
  17046. methodDef->mReturnTypeRef, true);
  17047. }
  17048. }
  17049. if ((typeInstance->IsInterface()) && (methodDef->mMethodType == BfMethodType_Ctor))
  17050. {
  17051. Fail("Interfaces cannot contain constructors", methodDeclaration);
  17052. }
  17053. // Don't compare specialized generic methods against normal methods
  17054. if ((((mCurMethodInstance->mIsUnspecialized) || (mCurMethodInstance->mMethodDef->mGenericParams.size() == 0))) &&
  17055. (!methodDef->mIsLocalMethod))
  17056. {
  17057. if (!methodInstance->mIsForeignMethodDef)
  17058. {
  17059. typeDef->PopulateMemberSets();
  17060. BfMethodDef* nextMethod = NULL;
  17061. BfMemberSetEntry* entry = NULL;
  17062. if (typeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  17063. nextMethod = (BfMethodDef*)entry->mMemberDef;
  17064. while (nextMethod != NULL)
  17065. {
  17066. auto checkMethod = nextMethod;
  17067. nextMethod = nextMethod->mNextWithSameName;
  17068. if ((checkMethod != methodDef) && (typeInstance->mMethodInstanceGroups[checkMethod->mIdx].mDefault != NULL))
  17069. {
  17070. auto checkMethodInstance = typeInstance->mMethodInstanceGroups[checkMethod->mIdx].mDefault;
  17071. if (((checkMethodInstance->mChainType == BfMethodChainType_None) || (checkMethodInstance->mChainType == BfMethodChainType_ChainHead)) &&
  17072. (checkMethodInstance->GetExplicitInterface() == methodInstance->GetExplicitInterface()) &&
  17073. (CompareMethodSignatures(checkMethodInstance, mCurMethodInstance)))
  17074. {
  17075. bool canChain = false;
  17076. if ((methodDef->mParams.empty()) &&
  17077. (checkMethodInstance->mMethodDef->mIsStatic == methodInstance->mMethodDef->mIsStatic))
  17078. {
  17079. if ((methodDef->mMethodType == BfMethodType_CtorNoBody) || (methodDef->mMethodType == BfMethodType_Dtor))
  17080. canChain = true;
  17081. else if (methodDef->mMethodType == BfMethodType_Normal)
  17082. {
  17083. if ((methodDef->mName == BF_METHODNAME_MARKMEMBERS) ||
  17084. (methodDef->mName == BF_METHODNAME_MARKMEMBERS_STATIC) ||
  17085. (methodDef->mName == BF_METHODNAME_FIND_TLS_MEMBERS))
  17086. canChain = true;
  17087. }
  17088. }
  17089. if (canChain)
  17090. {
  17091. bool isBetter;
  17092. bool isWorse;
  17093. CompareDeclTypes(checkMethodInstance->mMethodDef->mDeclaringType, methodInstance->mMethodDef->mDeclaringType, isBetter, isWorse);
  17094. if (isBetter && !isWorse)
  17095. {
  17096. methodInstance->mChainType = BfMethodChainType_ChainHead;
  17097. checkMethodInstance->mChainType = BfMethodChainType_ChainMember;
  17098. }
  17099. else
  17100. {
  17101. checkMethodInstance->mChainType = BfMethodChainType_ChainHead;
  17102. methodInstance->mChainType = BfMethodChainType_ChainMember;
  17103. }
  17104. }
  17105. else if ((checkMethod->mBody == NULL) && (methodDef->mBody != NULL) &&
  17106. (checkMethod->mDeclaringType != methodDef->mDeclaringType))
  17107. {
  17108. // We're allowed to override an empty-bodied method
  17109. checkMethodInstance->mChainType = BfMethodChainType_ChainSkip;
  17110. }
  17111. else
  17112. {
  17113. if (!typeInstance->IsTypeMemberAccessible(checkMethod->mDeclaringType, methodDef->mDeclaringType))
  17114. continue;
  17115. bool silentlyAllow = false;
  17116. if (checkMethod->mDeclaringType != methodDef->mDeclaringType)
  17117. {
  17118. if (typeInstance->IsInterface())
  17119. {
  17120. if (methodDef->mIsOverride)
  17121. silentlyAllow = true;
  17122. }
  17123. else
  17124. silentlyAllow = true;
  17125. }
  17126. if ((checkMethod->mCommutableKind == BfCommutableKind_Reverse) || (methodDef->mCommutableKind == BfCommutableKind_Reverse))
  17127. silentlyAllow = true;
  17128. if (!silentlyAllow)
  17129. {
  17130. if ((!methodDef->mName.IsEmpty()) || (checkMethodInstance->mMethodDef->mIsOperator))
  17131. {
  17132. auto refNode = methodDef->GetRefNode();
  17133. auto bfError = Fail("Method already declared with the same parameter types", refNode, true);
  17134. if (bfError != NULL)
  17135. mCompiler->mPassInstance->MoreInfo("First declaration", checkMethod->GetRefNode());
  17136. }
  17137. }
  17138. }
  17139. }
  17140. }
  17141. }
  17142. }
  17143. // Virtual methods give their error while slotting
  17144. if ((!typeInstance->IsBoxed()) && (!methodDef->mIsVirtual) && (methodDef->mProtection != BfProtection_Private) &&
  17145. (!methodDef->mIsLocalMethod) &&
  17146. (!methodInstance->mIsForeignMethodDef) && (typeInstance->mBaseType != NULL) &&
  17147. (methodDef->mMethodType == BfMethodType_Normal) && (methodDef->mMethodDeclaration != NULL))
  17148. {
  17149. bool foundHiddenMethod = false;
  17150. auto baseType = typeInstance->mBaseType;
  17151. while (baseType != NULL)
  17152. {
  17153. //for (int checkMethodIdx = 0; checkMethodIdx < (int) baseType->mTypeDef->mMethods.size(); checkMethodIdx++)
  17154. auto baseTypeDef = baseType->mTypeDef;
  17155. baseTypeDef->PopulateMemberSets();
  17156. BfMethodDef* checkMethod = NULL;
  17157. BfMemberSetEntry* entry = NULL;
  17158. if (baseTypeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  17159. checkMethod = (BfMethodDef*)entry->mMemberDef;
  17160. while (checkMethod != NULL)
  17161. {
  17162. if (checkMethod->mMethodDeclaration == NULL)
  17163. continue;
  17164. if (baseType->mMethodInstanceGroups.size() == 0)
  17165. {
  17166. BF_ASSERT(baseType->IsIncomplete() && mCompiler->IsAutocomplete());
  17167. break;
  17168. }
  17169. if (checkMethod == methodDef)
  17170. continue;
  17171. if (checkMethod->mName != methodDef->mName)
  17172. continue;
  17173. auto checkMethodInstance = GetRawMethodInstanceAtIdx(baseType, checkMethod->mIdx);
  17174. if (checkMethodInstance != NULL)
  17175. {
  17176. if ((checkMethodInstance->GetExplicitInterface() == methodInstance->GetExplicitInterface()) &&
  17177. (checkMethod->mProtection != BfProtection_Private) &&
  17178. (CompareMethodSignatures(checkMethodInstance, mCurMethodInstance)))
  17179. {
  17180. if (!methodDef->mIsNew)
  17181. {
  17182. BfAstNode* refNode = methodInstance->mMethodDef->GetRefNode();
  17183. if (refNode != NULL)
  17184. {
  17185. 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?
  17186. if (bfError != NULL)
  17187. bfError->mIsPersistent = true;
  17188. }
  17189. }
  17190. foundHiddenMethod = true;
  17191. break;
  17192. }
  17193. }
  17194. checkMethod = checkMethod->mNextWithSameName;
  17195. }
  17196. if (foundHiddenMethod)
  17197. break;
  17198. baseType = baseType->mBaseType;
  17199. }
  17200. if ((methodDef->mIsNew) && (!foundHiddenMethod))
  17201. {
  17202. auto propertyDeclaration = methodDef->GetPropertyDeclaration();
  17203. auto tokenNode = (propertyDeclaration != NULL) ? propertyDeclaration->mNewSpecifier :
  17204. methodDeclaration->mNewSpecifier;
  17205. Fail("Method does not hide an inherited member. The 'new' keyword is not required", tokenNode, true);
  17206. }
  17207. }
  17208. }
  17209. mCompiler->mStats.mMethodDeclarations++;
  17210. mCompiler->UpdateCompletion();
  17211. }
  17212. void BfModule::UniqueSlotVirtualMethod(BfMethodInstance* methodInstance)
  17213. {
  17214. BF_ASSERT(methodInstance->GetOwner() == mCurTypeInstance);
  17215. auto typeInstance = mCurTypeInstance;
  17216. auto methodDef = methodInstance->mMethodDef;
  17217. int virtualMethodMatchIdx = -1;
  17218. if (typeInstance->mHotTypeData != NULL)
  17219. {
  17220. if (typeInstance->mHotTypeData->mVTableOrigLength != -1)
  17221. {
  17222. BF_ASSERT(mCompiler->IsHotCompile());
  17223. // In the 'normal' case we'd assert that mIsOverride is false, but if we can't find the declaring method then we
  17224. // may slot this override anyway (?)
  17225. int vTableStart = 0;
  17226. if (typeInstance->mBaseType != NULL)
  17227. vTableStart = typeInstance->mBaseType->mVirtualMethodTableSize;
  17228. StringT<128> mangledName;
  17229. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), methodInstance);
  17230. for (int checkIdxOfs = 0; checkIdxOfs < (int)typeInstance->mHotTypeData->mVTableEntries.size(); checkIdxOfs++)
  17231. {
  17232. // O(1) checking when virtual methods haven't changed
  17233. int checkIdx = (typeInstance->mVirtualMethodTableSize - vTableStart + checkIdxOfs) % (int)typeInstance->mHotTypeData->mVTableEntries.size();
  17234. auto& entry = typeInstance->mHotTypeData->mVTableEntries[checkIdx];
  17235. if (mangledName == entry.mFuncName)
  17236. {
  17237. virtualMethodMatchIdx = vTableStart + checkIdx;
  17238. break;
  17239. }
  17240. }
  17241. if (virtualMethodMatchIdx != -1)
  17242. {
  17243. methodInstance->mVirtualTableIdx = virtualMethodMatchIdx;
  17244. typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mDeclaringMethod = methodInstance;
  17245. typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mImplementingMethod = methodInstance;
  17246. }
  17247. typeInstance->mVirtualMethodTableSize = (int)typeInstance->mVirtualMethodTable.size();
  17248. }
  17249. }
  17250. if (virtualMethodMatchIdx == -1)
  17251. {
  17252. methodInstance->mVirtualTableIdx = typeInstance->mVirtualMethodTableSize++;
  17253. BfVirtualMethodEntry entry = { methodInstance, methodInstance };
  17254. typeInstance->mVirtualMethodTable.push_back(entry);
  17255. }
  17256. }
  17257. void BfModule::CompareDeclTypes(BfTypeDef* newDeclType, BfTypeDef* prevDeclType, bool& isBetter, bool& isWorse)
  17258. {
  17259. if ((!prevDeclType->IsExtension()) && (newDeclType->IsExtension()))
  17260. {
  17261. // When we provide an extension override in the same project a root type override
  17262. isBetter = true;
  17263. isWorse = false;
  17264. }
  17265. else
  17266. {
  17267. isBetter = newDeclType->mProject->ContainsReference(prevDeclType->mProject);
  17268. isWorse = prevDeclType->mProject->ContainsReference(newDeclType->mProject);
  17269. }
  17270. }
  17271. bool BfModule::SlotVirtualMethod(BfMethodInstance* methodInstance, BfAmbiguityContext* ambiguityContext)
  17272. {
  17273. BP_ZONE("BfModule::SlotVirtualMethod");
  17274. if (mCurTypeInstance->IsUnspecializedTypeVariation())
  17275. return false;
  17276. auto _AddVirtualDecl = [&](BfMethodInstance* declMethodInstance)
  17277. {
  17278. if (!mCompiler->mOptions.mAllowHotSwapping)
  17279. return;
  17280. if ((!methodInstance->mIsReified) || (!declMethodInstance->mIsReified))
  17281. return;
  17282. if (methodInstance->mHotMethod == NULL)
  17283. CheckHotMethod(methodInstance, "");
  17284. if (methodInstance->mHotMethod == NULL)
  17285. return;
  17286. //BF_ASSERT(declMethodInstance->mHotMethod != NULL);
  17287. if (declMethodInstance->mHotMethod == NULL)
  17288. CheckHotMethod(declMethodInstance, "");
  17289. auto virtualDecl = mCompiler->mHotData->GetVirtualDeclaration(declMethodInstance->mHotMethod);
  17290. virtualDecl->mRefCount++;
  17291. methodInstance->mHotMethod->mReferences.Add(virtualDecl);
  17292. };
  17293. auto typeInstance = mCurTypeInstance;
  17294. auto typeDef = typeInstance->mTypeDef;
  17295. auto methodDef = methodInstance->mMethodDef;
  17296. auto methodDeclaration = methodDef->GetMethodDeclaration();
  17297. auto propertyDeclaration = methodDef->GetPropertyDeclaration();
  17298. auto propertyMethodDeclaration = methodDef->GetPropertyMethodDeclaration();
  17299. BfAstNode* declaringNode = methodDeclaration;
  17300. if (propertyMethodDeclaration != NULL)
  17301. declaringNode = propertyMethodDeclaration->mNameNode;
  17302. BfMethodInstance* methodOverriden = NULL;
  17303. bool usedMethod = false;
  17304. BfTokenNode* virtualToken = NULL;
  17305. if (propertyDeclaration != NULL)
  17306. virtualToken = propertyDeclaration->mVirtualSpecifier;
  17307. else if (methodDeclaration != NULL)
  17308. virtualToken = methodDeclaration->mVirtualSpecifier;
  17309. if ((methodDef->mIsVirtual) && (methodDef->mIsStatic))
  17310. {
  17311. Fail("Static members cannot be marked as override, virtual, or abstract", virtualToken, true);
  17312. }
  17313. else if (methodDef->mIsVirtual)
  17314. {
  17315. if (mCompiler->IsHotCompile())
  17316. mContext->EnsureHotMangledVirtualMethodName(methodInstance);
  17317. if ((methodDef->mProtection == BfProtection_Private) && (virtualToken != NULL))
  17318. Fail("Virtual or abstract members cannot be private", virtualToken, true);
  17319. BfTypeInstance* checkBase = typeInstance;
  17320. // If we are in an extension, look in ourselves first
  17321. if (methodDef->mDeclaringType->mTypeDeclaration == typeInstance->mTypeDef->mTypeDeclaration)
  17322. checkBase = checkBase->mBaseType;
  17323. if (typeInstance->IsValueType())
  17324. {
  17325. if (typeInstance->mBaseType == NULL)
  17326. return false; // It's actually ValueType
  17327. // We allow structs to override object methods for when they get boxed, so just ignore 'override' keyword until it gets boxed
  17328. if (!methodDef->mIsOverride)
  17329. {
  17330. Fail("Structs cannot have virtual methods", virtualToken, true);
  17331. return false;
  17332. }
  17333. checkBase = mContext->mBfObjectType;
  17334. if (checkBase->mVirtualMethodTableSize == 0)
  17335. PopulateType(checkBase, BfPopulateType_Full);
  17336. if (checkBase->mDefineState < BfTypeDefineState_DefinedAndMethodsSlotted)
  17337. return false; // System circular ref, don't do struct checking on those
  17338. }
  17339. int virtualMethodMatchIdx = -1;
  17340. bool hadHidingError = false;
  17341. BfMethodInstance* bestOverrideMethodInstance = NULL;
  17342. BfMethodInstance* ambiguousOverrideMethodInstance = NULL;
  17343. int bestOverrideMethodIdx = -1;
  17344. int ambiguousOverrideMethodIdx = -1;
  17345. if (checkBase != NULL)
  17346. {
  17347. auto& baseVirtualMethodTable = checkBase->mVirtualMethodTable;
  17348. auto lookupType = checkBase;
  17349. while (lookupType != NULL)
  17350. {
  17351. lookupType->mTypeDef->PopulateMemberSets();
  17352. BfMethodDef* nextMethodDef = NULL;
  17353. BfMemberSetEntry* entry;
  17354. if (lookupType->mTypeDef->mMethodSet.TryGetWith(methodInstance->mMethodDef->mName, &entry))
  17355. nextMethodDef = (BfMethodDef*)entry->mMemberDef;
  17356. while (nextMethodDef != NULL)
  17357. {
  17358. auto checkMethodDef = nextMethodDef;
  17359. nextMethodDef = nextMethodDef->mNextWithSameName;
  17360. if ((!checkMethodDef->mIsVirtual) || (checkMethodDef->mIsOverride))
  17361. continue;
  17362. BfMethodInstance* lookupMethodInstance = lookupType->mMethodInstanceGroups[checkMethodDef->mIdx].mDefault;
  17363. if ((lookupMethodInstance == NULL) || (lookupMethodInstance->mVirtualTableIdx == -1))
  17364. continue;
  17365. int checkMethodIdx = lookupMethodInstance->mVirtualTableIdx;
  17366. auto& baseMethodRef = baseVirtualMethodTable[checkMethodIdx];
  17367. if (baseMethodRef.mDeclaringMethod.mMethodNum == -1)
  17368. {
  17369. BF_ASSERT(mCompiler->mOptions.mHasVDataExtender);
  17370. continue;
  17371. }
  17372. BfMethodInstance* baseMethodInstance = baseVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  17373. if (baseMethodInstance == NULL)
  17374. {
  17375. AssertErrorState();
  17376. continue;
  17377. }
  17378. if ((baseMethodInstance != NULL) && (CompareMethodSignatures(baseMethodInstance, methodInstance)))
  17379. {
  17380. if (methodDef->mIsOverride)
  17381. {
  17382. BfMethodInstance* checkMethodInstance;
  17383. if (typeInstance->IsValueType())
  17384. checkMethodInstance = checkBase->mVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  17385. else
  17386. checkMethodInstance = typeInstance->mVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  17387. auto newDeclType = checkMethodInstance->mMethodDef->mDeclaringType;
  17388. if (!typeInstance->IsTypeMemberAccessible(newDeclType, methodDef->mDeclaringType->mProject))
  17389. continue;
  17390. if (bestOverrideMethodInstance != NULL)
  17391. {
  17392. auto prevDeclType = bestOverrideMethodInstance->mMethodDef->mDeclaringType;
  17393. bool isBetter = newDeclType->mProject->ContainsReference(prevDeclType->mProject);
  17394. bool isWorse = prevDeclType->mProject->ContainsReference(newDeclType->mProject);
  17395. if (isBetter == isWorse)
  17396. {
  17397. ambiguousOverrideMethodInstance = bestOverrideMethodInstance;
  17398. }
  17399. else
  17400. {
  17401. if (isWorse)
  17402. continue;
  17403. ambiguousOverrideMethodInstance = NULL;
  17404. }
  17405. }
  17406. bestOverrideMethodInstance = checkMethodInstance;
  17407. bestOverrideMethodIdx = checkMethodIdx;
  17408. }
  17409. else
  17410. {
  17411. if ((baseMethodInstance->GetOwner() != methodInstance->GetOwner()) && (!methodDef->mIsNew))
  17412. {
  17413. if (!hadHidingError)
  17414. Warn(BfWarning_CS0114_MethodHidesInherited, StrFormat("Method hides inherited member from '%s'. Use either 'override' or 'new'.", TypeToString(checkBase).c_str()), declaringNode);
  17415. hadHidingError = true;
  17416. }
  17417. }
  17418. }
  17419. }
  17420. lookupType = lookupType->mBaseType;
  17421. }
  17422. }
  17423. //TODO:
  17424. if ((checkBase != NULL)
  17425. && (false)
  17426. )
  17427. {
  17428. auto& baseVirtualMethodTable = checkBase->mVirtualMethodTable;
  17429. for (int checkMethodIdx = (int) baseVirtualMethodTable.size() - 1; checkMethodIdx >= 0; checkMethodIdx--)
  17430. {
  17431. auto& baseMethodRef = baseVirtualMethodTable[checkMethodIdx];
  17432. if (baseMethodRef.mDeclaringMethod.mMethodNum == -1)
  17433. {
  17434. BF_ASSERT(mCompiler->mOptions.mHasVDataExtender);
  17435. continue;
  17436. }
  17437. BfMethodInstance* baseMethodInstance = baseVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  17438. if (baseMethodInstance == NULL)
  17439. {
  17440. AssertErrorState();
  17441. continue;
  17442. }
  17443. if ((baseMethodInstance != NULL) && (CompareMethodSignatures(baseMethodInstance, methodInstance)))
  17444. {
  17445. if (methodDef->mIsOverride)
  17446. {
  17447. BfMethodInstance* checkMethodInstance;
  17448. if (typeInstance->IsValueType())
  17449. checkMethodInstance = checkBase->mVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  17450. else
  17451. checkMethodInstance = typeInstance->mVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  17452. auto newDeclType = checkMethodInstance->mMethodDef->mDeclaringType;
  17453. if (!typeInstance->IsTypeMemberAccessible(newDeclType, methodDef->mDeclaringType->mProject))
  17454. continue;
  17455. if (bestOverrideMethodInstance != NULL)
  17456. {
  17457. auto prevDeclType = bestOverrideMethodInstance->mMethodDef->mDeclaringType;
  17458. bool isBetter = newDeclType->mProject->ContainsReference(prevDeclType->mProject);
  17459. bool isWorse = prevDeclType->mProject->ContainsReference(newDeclType->mProject);
  17460. if (isBetter == isWorse)
  17461. {
  17462. ambiguousOverrideMethodInstance = bestOverrideMethodInstance;
  17463. }
  17464. else
  17465. {
  17466. if (isWorse)
  17467. continue;
  17468. ambiguousOverrideMethodInstance = NULL;
  17469. }
  17470. }
  17471. bestOverrideMethodInstance = checkMethodInstance;
  17472. bestOverrideMethodIdx = checkMethodIdx;
  17473. }
  17474. else
  17475. {
  17476. if ((baseMethodInstance->GetOwner() != methodInstance->GetOwner()) && (!methodDef->mIsNew))
  17477. {
  17478. if (!hadHidingError)
  17479. Warn(BfWarning_CS0114_MethodHidesInherited, StrFormat("Method hides inherited member from '%s'. Use either 'override' or 'new'.", TypeToString(checkBase).c_str()), declaringNode);
  17480. hadHidingError = true;
  17481. }
  17482. }
  17483. }
  17484. }
  17485. }
  17486. if (bestOverrideMethodInstance != NULL)
  17487. {
  17488. if (ambiguousOverrideMethodInstance != NULL)
  17489. {
  17490. bool allow = false;
  17491. // 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.
  17492. // When when specialize, the specialized type will determine wither it has illegally pulled in both declarations or not
  17493. bool canSeeEachOther = false;
  17494. //
  17495. {
  17496. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, ambiguousOverrideMethodInstance);
  17497. if (bestOverrideMethodInstance->GetOwner()->IsTypeMemberIncluded(bestOverrideMethodInstance->mMethodDef->mDeclaringType, ambiguousOverrideMethodInstance->mMethodDef->mDeclaringType, this))
  17498. canSeeEachOther = true;
  17499. }
  17500. //
  17501. {
  17502. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, bestOverrideMethodInstance);
  17503. if (ambiguousOverrideMethodInstance->GetOwner()->IsTypeMemberIncluded(ambiguousOverrideMethodInstance->mMethodDef->mDeclaringType, bestOverrideMethodInstance->mMethodDef->mDeclaringType, this))
  17504. canSeeEachOther = true;
  17505. }
  17506. if (!canSeeEachOther)
  17507. {
  17508. BF_ASSERT(bestOverrideMethodInstance->GetOwner()->IsUnspecializedType() && ambiguousOverrideMethodInstance->GetOwner()->IsUnspecializedType());
  17509. }
  17510. else
  17511. {
  17512. auto error = Fail(StrFormat("Method '%s' is an ambiguous override", MethodToString(methodInstance).c_str()), methodDef->GetRefNode());
  17513. if (error != NULL)
  17514. {
  17515. mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' is a candidate", MethodToString(bestOverrideMethodInstance).c_str()), bestOverrideMethodInstance->mMethodDef->GetRefNode());
  17516. mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' is a candidate", MethodToString(ambiguousOverrideMethodInstance).c_str()), ambiguousOverrideMethodInstance->mMethodDef->GetRefNode());
  17517. }
  17518. }
  17519. }
  17520. auto& baseVirtualMethodTable = checkBase->mVirtualMethodTable;
  17521. BfMethodInstance* baseVirtualMethodInstance = baseVirtualMethodTable[bestOverrideMethodIdx].mDeclaringMethod;
  17522. if ((baseVirtualMethodInstance != methodInstance) && (methodDef->mIsOverride))
  17523. {
  17524. if (baseVirtualMethodInstance->mReturnType != methodInstance->mReturnType)
  17525. {
  17526. BfTypeReference* returnTypeRef;
  17527. if (auto propertyDeclaration = methodDef->GetPropertyDeclaration())
  17528. {
  17529. returnTypeRef = propertyDeclaration->mTypeRef;
  17530. Fail("Property differs from overridden property by type", returnTypeRef, true);
  17531. }
  17532. else if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  17533. {
  17534. returnTypeRef = methodDeclaration->mReturnType;
  17535. Fail("Method differs from overridden method by return value", returnTypeRef, true);
  17536. }
  17537. else
  17538. {
  17539. Fail(StrFormat("Internal error with method '%s'", MethodToString(methodInstance).c_str()));
  17540. }
  17541. return usedMethod;
  17542. }
  17543. }
  17544. if (methodDef->mIsOverride)
  17545. {
  17546. // We can have multiple matches when a virtual method is used to implement interface methods
  17547. // It doesn't matter what we set mVirtualTableIdx, as all base classes will override all matching
  17548. // vtable entries for this method signature
  17549. virtualMethodMatchIdx = bestOverrideMethodIdx;
  17550. if (!typeInstance->IsValueType())
  17551. methodInstance->mVirtualTableIdx = virtualMethodMatchIdx;
  17552. if (typeInstance->IsValueType())
  17553. {
  17554. methodOverriden = checkBase->mVirtualMethodTable[virtualMethodMatchIdx].mImplementingMethod;
  17555. }
  17556. else
  17557. {
  17558. methodInstance->mVirtualTableIdx = virtualMethodMatchIdx;
  17559. auto& overridenRef = typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mImplementingMethod;
  17560. if (overridenRef.mKind != BfMethodRefKind_AmbiguousRef)
  17561. {
  17562. methodOverriden = overridenRef;
  17563. BfMethodInstance* setMethodInstance = methodInstance;
  17564. bool doOverride = true;
  17565. if (methodOverriden->GetOwner() == methodInstance->GetOwner())
  17566. {
  17567. bool isBetter = false;
  17568. bool isWorse = false;
  17569. CompareDeclTypes(methodInstance->mMethodDef->mDeclaringType, methodOverriden->mMethodDef->mDeclaringType, isBetter, isWorse);
  17570. if (isBetter == isWorse)
  17571. {
  17572. // We have to resolve later per-project
  17573. if ((ambiguityContext != NULL) && (ambiguityContext->mIsProjectSpecific))
  17574. {
  17575. auto declMethodInstance = checkBase->mVirtualMethodTable[virtualMethodMatchIdx].mDeclaringMethod;
  17576. ambiguityContext->Add(virtualMethodMatchIdx, NULL, -1, methodOverriden, methodInstance);
  17577. }
  17578. if ((ambiguityContext == NULL) || (!ambiguityContext->mIsProjectSpecific))
  17579. typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mImplementingMethod.mKind = BfMethodRefKind_AmbiguousRef;
  17580. doOverride = false;
  17581. }
  17582. else
  17583. {
  17584. if ((isBetter) && (ambiguityContext != NULL))
  17585. {
  17586. ambiguityContext->Remove(virtualMethodMatchIdx);
  17587. }
  17588. doOverride = isBetter;
  17589. }
  17590. }
  17591. if (doOverride)
  17592. {
  17593. auto declMethodInstance = (BfMethodInstance*)typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mDeclaringMethod;
  17594. _AddVirtualDecl(declMethodInstance);
  17595. typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mImplementingMethod = setMethodInstance;
  17596. }
  17597. }
  17598. }
  17599. if (methodOverriden != NULL)
  17600. {
  17601. auto prevProtection = methodOverriden->mMethodDef->mProtection;
  17602. if ((methodDef->mProtection != prevProtection) && (methodDef->mMethodType != BfMethodType_Dtor))
  17603. {
  17604. const char* protectionNames[] = {"hidden", "private", "protected", "public"};
  17605. BfAstNode* protectionRefNode = NULL;
  17606. if (auto propertyMethodDeclaration = methodDef->GetPropertyMethodDeclaration())
  17607. {
  17608. protectionRefNode = propertyMethodDeclaration->mProtectionSpecifier;
  17609. if (protectionRefNode == NULL)
  17610. protectionRefNode = propertyMethodDeclaration->mPropertyDeclaration->mProtectionSpecifier;
  17611. if (protectionRefNode == NULL)
  17612. protectionRefNode = propertyMethodDeclaration->mPropertyDeclaration->mNameNode;
  17613. }
  17614. else if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  17615. {
  17616. protectionRefNode = methodDeclaration->mProtectionSpecifier;
  17617. if (protectionRefNode == NULL)
  17618. protectionRefNode = methodDeclaration->mNameNode;
  17619. }
  17620. if (protectionRefNode != NULL)
  17621. Fail(StrFormat("Cannot change access modifiers when overriding '%s' inherited member", protectionNames[(int)prevProtection]), protectionRefNode, true);
  17622. }
  17623. }
  17624. }
  17625. }
  17626. if ((virtualMethodMatchIdx == -1) && ((ambiguityContext == NULL) || (!ambiguityContext->mIsReslotting)))
  17627. {
  17628. if (methodDef->mIsOverride)
  17629. {
  17630. BfTokenNode* overrideToken = NULL;
  17631. if (auto propertyMethodDeclaration = methodDef->GetPropertyMethodDeclaration())
  17632. overrideToken = propertyMethodDeclaration->mPropertyDeclaration->mVirtualSpecifier;
  17633. else if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  17634. overrideToken = methodDeclaration->mVirtualSpecifier;
  17635. if (overrideToken != NULL)
  17636. {
  17637. if ((propertyDeclaration != NULL) && (propertyDeclaration->mNameNode != NULL) &&
  17638. ((methodDef->mMethodType == BfMethodType_PropertyGetter) || (methodDef->mMethodType == BfMethodType_PropertySetter)))
  17639. Fail(StrFormat("No suitable method found to override for '%s.%s'",
  17640. propertyDeclaration->mNameNode->ToString().c_str(), (methodDef->mMethodType == BfMethodType_PropertyGetter) ? "get" : "set"), overrideToken, true);
  17641. else
  17642. Fail("No suitable method found to override", overrideToken, true);
  17643. }
  17644. return usedMethod;
  17645. }
  17646. UniqueSlotVirtualMethod(methodInstance);
  17647. }
  17648. else
  17649. usedMethod = true;
  17650. if (typeInstance->IsValueType())
  17651. return usedMethod;
  17652. }
  17653. bool foundInterface = false;
  17654. bool hadAnyMatch = false;
  17655. // See if this method matches interfaces
  17656. for (auto& ifaceTypeInst : typeInstance->mInterfaces)
  17657. {
  17658. auto ifaceInst = ifaceTypeInst.mInterfaceType;
  17659. if (ifaceInst->IsIncomplete())
  17660. PopulateType(ifaceInst, BfPopulateType_DataAndMethods);
  17661. int startIdx = ifaceTypeInst.mStartInterfaceTableIdx;
  17662. int iMethodCount = (int)ifaceInst->mMethodInstanceGroups.size();
  17663. // See "bidirectional" rules mentioned in DoTypeInstanceMethodProcessing
  17664. if ((!typeInstance->IsTypeMemberAccessible(methodDef->mDeclaringType, ifaceTypeInst.mDeclaringType)) &&
  17665. (!typeInstance->IsTypeMemberAccessible(ifaceTypeInst.mDeclaringType, methodDef->mDeclaringType)))
  17666. continue;
  17667. if (!typeInstance->IsTypeMemberIncluded(methodDef->mDeclaringType, ifaceTypeInst.mDeclaringType, this))
  17668. continue;
  17669. bool hadMatch = false;
  17670. BfMethodInstance* hadNameMatch = NULL;
  17671. BfType* expectedReturnType = NULL;
  17672. bool showedError = false;
  17673. // We go through our VTable looking for NULL entries within the interface sections
  17674. // The only instance of finding a "better" method is when we have explicitly interface-dotted method
  17675. // because a normal method declared in this type could have matched earlier
  17676. //for (int iMethodIdx = 0; iMethodIdx < iMethodCount; iMethodIdx++)
  17677. ifaceInst->mTypeDef->PopulateMemberSets();
  17678. BfMethodDef* checkMethodDef = NULL;
  17679. BfMemberSetEntry* entry;
  17680. if (ifaceInst->mTypeDef->mMethodSet.TryGetWith(methodInstance->mMethodDef->mName, &entry))
  17681. checkMethodDef = (BfMethodDef*)entry->mMemberDef;
  17682. while (checkMethodDef != NULL)
  17683. {
  17684. int iMethodIdx = checkMethodDef->mIdx;
  17685. int iTableIdx = iMethodIdx + startIdx;
  17686. BfTypeInterfaceMethodEntry* interfaceMethodEntry = &typeInstance->mInterfaceMethodTable[iTableIdx];
  17687. auto iMethodPtr = &interfaceMethodEntry->mMethodRef;
  17688. bool storeIFaceMethod = false;
  17689. if ((mCompiler->mPassInstance->HasFailed()) && (iMethodIdx >= (int)ifaceInst->mMethodInstanceGroups.size()))
  17690. continue;
  17691. auto& iMethodGroup = ifaceInst->mMethodInstanceGroups[iMethodIdx];
  17692. auto iMethodInst = iMethodGroup.mDefault;
  17693. if (iMethodInst == NULL)
  17694. {
  17695. if ((!ifaceInst->IsGenericTypeInstance()) || (!ifaceInst->mTypeDef->mIsCombinedPartial))
  17696. AssertErrorState();
  17697. continue;
  17698. }
  17699. if (iMethodInst->mMethodDef->mName == methodInstance->mMethodDef->mName)
  17700. hadNameMatch = iMethodInst;
  17701. bool doesMethodSignatureMatch = CompareMethodSignatures(iMethodInst, methodInstance);
  17702. if ((!doesMethodSignatureMatch) && (iMethodInst->GetNumGenericParams() == 0) && (interfaceMethodEntry->mMethodRef.IsNull()))
  17703. {
  17704. doesMethodSignatureMatch = IsCompatibleInterfaceMethod(iMethodInst, methodInstance);
  17705. }
  17706. if ((doesMethodSignatureMatch) && (methodInstance->GetOwner()->IsValueType()))
  17707. {
  17708. if ((!iMethodInst->mMethodDef->mIsMutating) && (methodInstance->mMethodDef->mIsMutating))
  17709. {
  17710. if ((methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface == ifaceInst))
  17711. {
  17712. auto error = mCompiler->mPassInstance->Fail(StrFormat("Implementation method '%s' cannot specify 'mut' because the interface method does not allow it",
  17713. MethodToString(methodInstance).c_str()), methodInstance->mMethodDef->GetMutNode());
  17714. if (error != NULL)
  17715. mCompiler->mPassInstance->MoreInfo(StrFormat("Declare the interface method as 'mut' to allow matching 'mut' implementations"), iMethodInst->mMethodDef->mMethodDeclaration);
  17716. showedError = true;
  17717. }
  17718. }
  17719. }
  17720. if (doesMethodSignatureMatch)
  17721. {
  17722. usedMethod = true;
  17723. hadMatch = true;
  17724. hadAnyMatch = true;
  17725. storeIFaceMethod = true;
  17726. if ((iMethodPtr->mKind != BfMethodRefKind_AmbiguousRef) && (iMethodPtr->mTypeInstance != NULL))
  17727. {
  17728. auto prevMethod = (BfMethodInstance*)*iMethodPtr;
  17729. if ((mCompiler->mIsResolveOnly) && (prevMethod == methodInstance))
  17730. {
  17731. // When autocompletion regenerates a single method body but not the whole type then
  17732. // we will see ourselves in the vtable already
  17733. return usedMethod;
  17734. }
  17735. bool isBetter = false;
  17736. bool isWorse = false;
  17737. isBetter = (methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface != NULL);
  17738. isWorse = (prevMethod->mMethodInfoEx != NULL) && (prevMethod->mMethodInfoEx->mExplicitInterface != NULL);
  17739. if (isBetter == isWorse)
  17740. CompareDeclTypes(methodInstance->mMethodDef->mDeclaringType, prevMethod->mMethodDef->mDeclaringType, isBetter, isWorse);
  17741. if (isBetter == isWorse)
  17742. {
  17743. if (ambiguityContext != NULL)
  17744. {
  17745. ambiguityContext->Add(~iTableIdx, &ifaceTypeInst, iMethodIdx, prevMethod, methodInstance);
  17746. }
  17747. iMethodPtr->mKind = BfMethodRefKind_AmbiguousRef;
  17748. storeIFaceMethod = true;
  17749. }
  17750. else
  17751. {
  17752. if ((isBetter) && (ambiguityContext != NULL))
  17753. ambiguityContext->Remove(~iTableIdx);
  17754. storeIFaceMethod = isBetter;
  17755. }
  17756. }
  17757. }
  17758. if (storeIFaceMethod)
  17759. {
  17760. _AddVirtualDecl(iMethodInst);
  17761. *iMethodPtr = methodInstance;
  17762. }
  17763. checkMethodDef = checkMethodDef->mNextWithSameName;
  17764. }
  17765. if ((methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface == ifaceInst) && (!hadMatch) && (!showedError))
  17766. {
  17767. if (expectedReturnType != NULL)
  17768. Fail(StrFormat("Wrong return type, expected '%s'", TypeToString(expectedReturnType).c_str()), declaringNode, true);
  17769. else if (hadNameMatch != NULL)
  17770. {
  17771. auto error = Fail("Method parameters don't match interface method", declaringNode, true);
  17772. if (error != NULL)
  17773. mCompiler->mPassInstance->MoreInfo("See interface method declaration", hadNameMatch->mMethodDef->GetRefNode());
  17774. }
  17775. else
  17776. {
  17777. auto propertyDecl = methodDef->GetPropertyDeclaration();
  17778. if (propertyDecl != NULL)
  17779. {
  17780. auto propertyMethodDecl = methodDef->GetPropertyMethodDeclaration();
  17781. Fail(StrFormat("Property '%s' %s accessor not defined in interface '%s'", propertyDecl->mNameNode->ToString().c_str(),
  17782. (methodDef->mMethodType == BfMethodType_PropertyGetter) ? "get" : "set", TypeToString(ifaceInst).c_str()), methodDef->GetRefNode(), true);
  17783. }
  17784. else
  17785. Fail(StrFormat("Method '%s' not found in interface '%s'", methodDef->mName.c_str(), TypeToString(ifaceInst).c_str()), methodDef->GetRefNode(), true);
  17786. }
  17787. }
  17788. }
  17789. // Any overriden virtual methods that were used in interfaces also need to be replaced
  17790. if (methodOverriden != NULL)
  17791. {
  17792. for (auto& methodEntry : typeInstance->mInterfaceMethodTable)
  17793. {
  17794. if (methodEntry.mMethodRef == methodOverriden)
  17795. methodEntry.mMethodRef = methodInstance;
  17796. }
  17797. }
  17798. return usedMethod;
  17799. }
  17800. bool BfModule::SlotInterfaceMethod(BfMethodInstance* methodInstance)
  17801. {
  17802. auto typeInstance = mCurTypeInstance;
  17803. auto methodDef = methodInstance->mMethodDef;
  17804. if (methodDef->mMethodType == BfMethodType_Ctor)
  17805. return true;
  17806. bool foundOverride = false;
  17807. if ((methodDef->mBody == NULL) && (methodDef->mProtection == BfProtection_Private))
  17808. {
  17809. Fail("Private interface methods must provide a body", methodDef->GetMethodDeclaration()->mProtectionSpecifier);
  17810. }
  17811. if ((methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface != NULL) && (!methodDef->mIsOverride))
  17812. {
  17813. Fail("Explicit interfaces can only be specified for overrides in interface declarations", methodDef->GetMethodDeclaration()->mExplicitInterface);
  17814. }
  17815. BfAstNode* declaringNode = methodDef->GetRefNode();
  17816. for (auto& ifaceTypeInst : typeInstance->mInterfaces)
  17817. {
  17818. auto ifaceInst = ifaceTypeInst.mInterfaceType;
  17819. int startIdx = ifaceTypeInst.mStartInterfaceTableIdx;
  17820. int iMethodCount = (int)ifaceInst->mMethodInstanceGroups.size();
  17821. if ((methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface != ifaceInst))
  17822. continue;
  17823. ifaceInst->mTypeDef->PopulateMemberSets();
  17824. BfMethodDef* nextMethod = NULL;
  17825. BfMemberSetEntry* entry = NULL;
  17826. if (ifaceInst->mTypeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  17827. nextMethod = (BfMethodDef*)entry->mMemberDef;
  17828. while (nextMethod != NULL)
  17829. {
  17830. auto checkMethod = nextMethod;
  17831. nextMethod = nextMethod->mNextWithSameName;
  17832. auto ifaceMethod = ifaceInst->mMethodInstanceGroups[checkMethod->mIdx].mDefault;
  17833. if (ifaceMethod == NULL)
  17834. continue;
  17835. if (CompareMethodSignatures(ifaceMethod, methodInstance))
  17836. {
  17837. if (methodDef->mIsOverride)
  17838. {
  17839. if (ifaceMethod->mMethodDef->mProtection == BfProtection_Private)
  17840. {
  17841. auto error = Fail(StrFormat("Interface method '%s' cannot override private interface method '%s'", MethodToString(methodInstance).c_str(), MethodToString(ifaceMethod).c_str()), declaringNode);
  17842. if (error != NULL)
  17843. {
  17844. mCompiler->mPassInstance->MoreInfo("See base interface method", ifaceMethod->mMethodDef->GetRefNode());
  17845. }
  17846. }
  17847. foundOverride = true;
  17848. }
  17849. else if (!methodDef->mIsNew)
  17850. {
  17851. Warn(BfWarning_CS0114_MethodHidesInherited, StrFormat("Method hides inherited member from '%s'. Use the 'new' keyword if hiding was intentional.", TypeToString(ifaceInst).c_str()), declaringNode);
  17852. }
  17853. }
  17854. }
  17855. }
  17856. if ((methodDef->mIsOverride) && (!foundOverride))
  17857. {
  17858. // This allows us to declare a method in the base definition or in an extension and then provide
  17859. // an implementation in a more-specific extension
  17860. typeInstance->mTypeDef->PopulateMemberSets();
  17861. BfMethodDef* nextMethod = NULL;
  17862. BfMemberSetEntry* entry = NULL;
  17863. if (typeInstance->mTypeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  17864. nextMethod = (BfMethodDef*)entry->mMemberDef;
  17865. while (nextMethod != NULL)
  17866. {
  17867. auto checkMethod = nextMethod;
  17868. nextMethod = nextMethod->mNextWithSameName;
  17869. auto ifaceMethod = typeInstance->mMethodInstanceGroups[checkMethod->mIdx].mDefault;
  17870. if (ifaceMethod == NULL)
  17871. continue;
  17872. if (ifaceMethod->mMethodDef->mDeclaringType == methodInstance->mMethodDef->mDeclaringType)
  17873. continue;
  17874. if (CompareMethodSignatures(ifaceMethod, methodInstance))
  17875. {
  17876. foundOverride = true;
  17877. }
  17878. }
  17879. // for (int methodIdx = 0; methodIdx < typeInstance->mMethodInstanceGroups.size(); methodIdx++)
  17880. // {
  17881. // auto ifaceMethod = typeInstance->mMethodInstanceGroups[methodIdx].mDefault;
  17882. // if (ifaceMethod == NULL)
  17883. // continue;
  17884. // if (ifaceMethod->mMethodDef->mDeclaringType == methodInstance->mMethodDef->mDeclaringType)
  17885. // continue;
  17886. //
  17887. // if (CompareMethodSignatures(ifaceMethod, methodInstance))
  17888. // {
  17889. // foundOverride = true;
  17890. // }
  17891. // }
  17892. }
  17893. if (methodDef->mIsOverride)
  17894. {
  17895. if (!foundOverride)
  17896. {
  17897. BfTokenNode* overrideToken = NULL;
  17898. if (auto propertyDeclaration = methodDef->GetPropertyDeclaration())
  17899. overrideToken = propertyDeclaration->mVirtualSpecifier;
  17900. else if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  17901. overrideToken = methodDeclaration->mVirtualSpecifier;
  17902. if (overrideToken != NULL)
  17903. {
  17904. Fail("No suitable method found to override", overrideToken, true);
  17905. }
  17906. else
  17907. {
  17908. // Possible cause - DTOR with params
  17909. AssertErrorState();
  17910. }
  17911. }
  17912. return true;
  17913. }
  17914. // Generic methods can't be called virtually
  17915. if (methodInstance->GetNumGenericParams() != 0)
  17916. return true;
  17917. // Only public methods can be called virtually
  17918. if (methodDef->mProtection != BfProtection_Public)
  17919. return true;
  17920. UniqueSlotVirtualMethod(methodInstance);
  17921. return true;
  17922. }
  17923. void BfModule::DbgFinish()
  17924. {
  17925. if ((mBfIRBuilder == NULL) || (mExtensionCount != 0))
  17926. return;
  17927. if (mAwaitingInitFinish)
  17928. FinishInit();
  17929. if (mHasForceLinkMarker)
  17930. return;
  17931. String markerName;
  17932. BfIRValue linkMarker;
  17933. if (mBfIRBuilder->DbgHasInfo())
  17934. {
  17935. bool needForceLinking = false;
  17936. for (auto& ownedType : mOwnedTypeInstances)
  17937. {
  17938. bool hasConfirmedReference = false;
  17939. for (auto& methodInstGroup : ownedType->mMethodInstanceGroups)
  17940. {
  17941. if ((methodInstGroup.IsImplemented()) && (methodInstGroup.mDefault != NULL) &&
  17942. (!methodInstGroup.mDefault->mMethodDef->mIsStatic) && (methodInstGroup.mDefault->mIsReified) &&
  17943. ((methodInstGroup.mOnDemandKind == BfMethodOnDemandKind_AlwaysInclude) || (methodInstGroup.mOnDemandKind == BfMethodOnDemandKind_Referenced)))
  17944. {
  17945. hasConfirmedReference = true;
  17946. }
  17947. }
  17948. if ((!hasConfirmedReference) || (ownedType->IsBoxed()))
  17949. needForceLinking = true;
  17950. }
  17951. if ((needForceLinking) && (mProject->mCodeGenOptions.mAsmKind == BfAsmKind_None))
  17952. {
  17953. BfMethodState methodState;
  17954. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  17955. methodState.mTempKind = BfMethodState::TempKind_Static;
  17956. mHasForceLinkMarker = true;
  17957. auto voidType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_None));
  17958. SizedArray<BfIRType, 0> paramTypes;
  17959. BfIRFunctionType funcType = mBfIRBuilder->CreateFunctionType(voidType, paramTypes);
  17960. String linkName = "FORCELINKMOD_" + mModuleName;
  17961. BfIRFunction func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, linkName);
  17962. mBfIRBuilder->SetActiveFunction(func);
  17963. auto entryBlock = mBfIRBuilder->CreateBlock("main", true);
  17964. mBfIRBuilder->SetInsertPoint(entryBlock);
  17965. auto firstType = mOwnedTypeInstances[0];
  17966. UpdateSrcPos(mContext->mBfObjectType->mTypeDef->GetRefNode());
  17967. SizedArray<BfIRMDNode, 1> diParamTypes;
  17968. diParamTypes.Add(mBfIRBuilder->DbgGetType(GetPrimitiveType(BfTypeCode_None)));
  17969. BfIRMDNode diFuncType = mBfIRBuilder->DbgCreateSubroutineType(diParamTypes);
  17970. auto diScope = mBfIRBuilder->DbgCreateFunction(mDICompileUnit, "FORCELINKMOD", linkName, mCurFilePosition.mFileInstance->mDIFile,
  17971. mCurFilePosition.mCurLine + 1, diFuncType, false, true, mCurFilePosition.mCurLine + 1, 0, false, func);
  17972. methodState.mCurScope->mDIScope = diScope;
  17973. UpdateSrcPos(mContext->mBfObjectType->mTypeDef->GetRefNode(), BfSrcPosFlag_Force);
  17974. SizedArray<BfIRValue, 8> args;
  17975. BfExprEvaluator exprEvaluator(this);
  17976. for (auto& ownedType : mOwnedTypeInstances)
  17977. {
  17978. auto alloca = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_Int8)));
  17979. auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(diScope, "variable", mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, mBfIRBuilder->DbgGetType(ownedType));
  17980. mBfIRBuilder->DbgInsertDeclare(alloca, diVariable);
  17981. }
  17982. mBfIRBuilder->CreateRetVoid();
  17983. mBfIRBuilder->SetActiveFunction(BfIRFunction());
  17984. }
  17985. }
  17986. }
  17987. bool BfModule::Finish()
  17988. {
  17989. BP_ZONE("BfModule::Finish");
  17990. BfLogSysM("BfModule finish: %p\n", this);
  17991. if (mHadBuildError)
  17992. {
  17993. // Don't AssertErrorState here, this current pass may not have failed but
  17994. // the module was still queued in mFinishedModuleWorkList
  17995. ClearModule();
  17996. return true;
  17997. }
  17998. if (mUsedSlotCount != -1)
  17999. {
  18000. BF_ASSERT(mCompiler->mMaxInterfaceSlots != -1);
  18001. mUsedSlotCount = mCompiler->mMaxInterfaceSlots;
  18002. }
  18003. BF_ASSERT(mAddedToCount);
  18004. mAddedToCount = false;
  18005. mAwaitingFinish = false;
  18006. mCompiler->mStats.mModulesFinished++;
  18007. if (HasCompiledOutput())
  18008. {
  18009. DbgFinish();
  18010. if (mAwaitingInitFinish)
  18011. FinishInit();
  18012. for (auto ownedTypeInst : mOwnedTypeInstances)
  18013. {
  18014. // Generate dbg info and add global variables if we haven't already
  18015. mBfIRBuilder->PopulateType(ownedTypeInst);
  18016. }
  18017. if (mBfIRBuilder->DbgHasInfo())
  18018. {
  18019. mBfIRBuilder->DbgFinalize();
  18020. }
  18021. String objOutputPath;
  18022. String irOutputPath;
  18023. mIsModuleMutable = false;
  18024. //mOutFileNames.Clear();
  18025. BF_ASSERT((int)mOutFileNames.size() >= mExtensionCount);
  18026. bool writeModule = mBfIRBuilder->HasExports();
  18027. String outputPath;
  18028. BfCodeGenOptions codeGenOptions = mProject->mCodeGenOptions;
  18029. auto& compilerOpts = mCompiler->mOptions;
  18030. codeGenOptions.mSIMDSetting = compilerOpts.mSIMDSetting;
  18031. auto moduleOptions = GetModuleOptions();
  18032. codeGenOptions.mOptLevel = moduleOptions.mOptLevel;
  18033. codeGenOptions.mSIMDSetting = moduleOptions.mSIMDSetting;
  18034. codeGenOptions.mWriteLLVMIR = mCompiler->mOptions.mWriteIR;
  18035. codeGenOptions.mWriteObj = mCompiler->mOptions.mGenerateObj;
  18036. codeGenOptions.mWriteBitcode = mCompiler->mOptions.mGenerateBitcode;
  18037. codeGenOptions.mVirtualMethodOfs = 1 + mCompiler->GetDynCastVDataCount() + mCompiler->mMaxInterfaceSlots;
  18038. codeGenOptions.mDynSlotOfs = mSystem->mPtrSize - mCompiler->GetDynCastVDataCount() * 4;
  18039. mCompiler->mStats.mIRBytes += mBfIRBuilder->mStream.GetSize();
  18040. mCompiler->mStats.mConstBytes += mBfIRBuilder->mTempAlloc.GetAllocSize();
  18041. bool allowWriteToLib = true;
  18042. if ((allowWriteToLib) && (codeGenOptions.mOptLevel == BfOptLevel_OgPlus) && (mModuleName != "vdata"))
  18043. {
  18044. codeGenOptions.mWriteToLib = true;
  18045. mWroteToLib = true;
  18046. }
  18047. else
  18048. {
  18049. mWroteToLib = false;
  18050. }
  18051. for (int fileIdx = 0; fileIdx <= mExtensionCount; fileIdx++)
  18052. {
  18053. outputPath = mModuleName;
  18054. outputPath = mCompiler->mOutputDirectory + "/" + mProject->mName + "/" + outputPath;
  18055. BfModuleFileName moduleFileName;
  18056. if (mParentModule != NULL)
  18057. {
  18058. for (auto&& checkPair : mParentModule->mSpecializedMethodModules)
  18059. {
  18060. if (checkPair.mValue == this)
  18061. moduleFileName.mProjects = checkPair.mKey;
  18062. }
  18063. }
  18064. moduleFileName.mProjects.Add(mProject);
  18065. if (fileIdx > 0)
  18066. outputPath += StrFormat("@%d", fileIdx + 1);
  18067. if (mCompiler->mOptions.mWriteIR)
  18068. irOutputPath = outputPath + ".ll";
  18069. if (mCompiler->mOptions.mGenerateObj)
  18070. {
  18071. objOutputPath = outputPath + BF_OBJ_EXT;
  18072. moduleFileName.mFileName = objOutputPath;
  18073. }
  18074. else if (mCompiler->mOptions.mWriteIR)
  18075. {
  18076. moduleFileName.mFileName = irOutputPath;
  18077. }
  18078. else if ((!mCompiler->mOptions.mGenerateObj) && (!mCompiler->mOptions.mGenerateBitcode) && (!mCompiler->mOptions.mWriteIR))
  18079. {
  18080. BF_FATAL("Neither obj nor IR specified");
  18081. }
  18082. moduleFileName.mModuleWritten = writeModule;
  18083. moduleFileName.mWroteToLib = mWroteToLib;
  18084. if (!mOutFileNames.Contains(moduleFileName))
  18085. mOutFileNames.Add(moduleFileName);
  18086. }
  18087. if (mCompiler->IsHotCompile())
  18088. {
  18089. codeGenOptions.mIsHotCompile = true;
  18090. //TODO: Why did we have this 'mWroteToLib' check? 'vdata' didn't get this flag set, which
  18091. // is required for rebuilding vdata after we hot create a vdata
  18092. //if (mWroteToLib)
  18093. {
  18094. if (mParentModule != NULL)
  18095. mParentModule->mHadHotObjectWrites = true;
  18096. mHadHotObjectWrites = true;
  18097. }
  18098. }
  18099. //TODO: Testing VDATA
  18100. /*if (mModuleName == "vdata")
  18101. {
  18102. codeGenOptions.mOptLevel = 4;
  18103. }*/
  18104. codeGenOptions.GenerateHash();
  18105. BP_ZONE("BfModule::Finish.WriteObjectFile");
  18106. if ((writeModule) && (!mBfIRBuilder->mIgnoreWrites))
  18107. mCompiler->mCodeGen.WriteObjectFile(this, outputPath, codeGenOptions);
  18108. mLastModuleWrittenRevision = mCompiler->mRevision;
  18109. }
  18110. else
  18111. {
  18112. for (auto type : mOwnedTypeInstances)
  18113. {
  18114. BF_ASSERT(!type->IsIncomplete());
  18115. }
  18116. }
  18117. for (auto& specModulePair : mSpecializedMethodModules)
  18118. {
  18119. auto specModule = specModulePair.mValue;
  18120. if ((specModule->mIsModuleMutable) && (!specModule->mAwaitingFinish))
  18121. {
  18122. BfLogSysM(" Mutable spec module remaining: %p\n", specModule);
  18123. }
  18124. }
  18125. CleanupFileInstances();
  18126. // We can't ClearModuleData here because we need the mSpecializedMethodModules to remain valid until we Finish them too
  18127. return true;
  18128. }
  18129. void BfModule::ReportMemory(MemReporter* memReporter)
  18130. {
  18131. memReporter->Add(sizeof(BfModule));
  18132. if (mBfIRBuilder != NULL)
  18133. {
  18134. memReporter->BeginSection("IRBuilder_ConstData");
  18135. memReporter->Add("Used", mBfIRBuilder->mTempAlloc.GetAllocSize());
  18136. memReporter->Add("Unused", mBfIRBuilder->mTempAlloc.GetTotalAllocSize() - mBfIRBuilder->mTempAlloc.GetAllocSize());
  18137. memReporter->EndSection();
  18138. memReporter->BeginSection("IRBuilder_BFIR");
  18139. memReporter->Add("Used", (int)(mBfIRBuilder->mStream.GetSize()));
  18140. memReporter->Add("Unused", (int)(mBfIRBuilder->mStream.mPools.size() * ChunkedDataBuffer::ALLOC_SIZE) - mBfIRBuilder->mStream.GetSize());
  18141. memReporter->EndSection();
  18142. memReporter->Add(sizeof(BfIRBuilder));
  18143. }
  18144. memReporter->BeginSection("FileInstanceMap");
  18145. memReporter->AddMap(mFileInstanceMap);
  18146. memReporter->AddMap(mNamedFileInstanceMap);
  18147. memReporter->Add((int)mNamedFileInstanceMap.size() * sizeof(BfFileInstance));
  18148. memReporter->EndSection();
  18149. memReporter->AddVec(mOwnedTypeInstances, false);
  18150. memReporter->AddVec(mSpecializedMethodModules, false);
  18151. memReporter->AddVec(mOutFileNames, false);
  18152. memReporter->AddMap("FuncReferences", mFuncReferences, false);
  18153. memReporter->AddMap(mInterfaceSlotRefs, false);
  18154. memReporter->AddMap(mStaticFieldRefs, false);
  18155. memReporter->AddMap(mClassVDataRefs, false);
  18156. memReporter->AddMap("VDataExtMap", mClassVDataExtRefs, false);
  18157. memReporter->AddMap(mTypeDataRefs, false);
  18158. memReporter->AddMap(mDbgRawAllocDataRefs, false);
  18159. memReporter->AddMap(mDeferredMethodCallData, false);
  18160. memReporter->AddHashSet(mDeferredMethodIds, false);
  18161. memReporter->AddHashSet("ModuleRefs", mModuleRefs, false);
  18162. }
  18163. // ClearModuleData is called immediately after the module is compiled, so don't clear out any data that needs to
  18164. // be transient through the next compile
  18165. void BfModule::ClearModuleData()
  18166. {
  18167. BfLogSysM("ClearModuleData %p\n", this);
  18168. if (mAddedToCount)
  18169. {
  18170. mCompiler->mStats.mModulesFinished++;
  18171. mAddedToCount = false;
  18172. }
  18173. mDICompileUnit = BfIRMDNode();
  18174. mIsModuleMutable = false;
  18175. mIncompleteMethodCount = 0;
  18176. mHasGenericMethods = false;
  18177. // We don't want to clear these because we want it to persist through module extensions-
  18178. // otherwise we may think an extension succeeds even though the base module failed
  18179. //mHadBuildError = false;
  18180. //mHadBuildWarning = false;
  18181. mClassVDataRefs.Clear();
  18182. mClassVDataExtRefs.Clear();
  18183. for (auto& kv : mTypeDataRefs)
  18184. kv.mValue = BfIRValue();
  18185. mStringCharPtrPool.Clear();
  18186. mStringObjectPool.Clear();
  18187. mStaticFieldRefs.Clear();
  18188. BF_ASSERT(!mIgnoreErrors);
  18189. for (auto prevIRBuilder : mPrevIRBuilders)
  18190. delete prevIRBuilder;
  18191. mPrevIRBuilders.Clear();
  18192. for (auto& specPair : mSpecializedMethodModules)
  18193. {
  18194. auto specModule = specPair.mValue;
  18195. specModule->ClearModuleData();
  18196. }
  18197. for (int i = 0; i < BfBuiltInFuncType_Count; i++)
  18198. mBuiltInFuncs[i] = BfIRFunction();
  18199. if (mNextAltModule != NULL)
  18200. mNextAltModule->ClearModuleData();
  18201. BfLogSysM("ClearModuleData. Deleting IRBuilder: %p\n", mBfIRBuilder);
  18202. delete mBfIRBuilder;
  18203. mBfIRBuilder = NULL;
  18204. mWantsIRIgnoreWrites = false;
  18205. }
  18206. void BfModule::DisownMethods()
  18207. {
  18208. for (int i = 0; i < BfBuiltInFuncType_Count; i++)
  18209. mBuiltInFuncs[i] = BfIRFunction();
  18210. BfModule* methodModule = this;
  18211. if (mParentModule != NULL)
  18212. methodModule = mParentModule;
  18213. for (auto typeInst : methodModule->mOwnedTypeInstances)
  18214. {
  18215. for (auto& methodGroup : typeInst->mMethodInstanceGroups)
  18216. {
  18217. if (methodGroup.mDefault != NULL)
  18218. {
  18219. if (methodGroup.mDefault->mIRFunction)
  18220. {
  18221. BF_ASSERT(methodGroup.mDefault->mDeclModule != NULL);
  18222. if (methodGroup.mDefault->mDeclModule == this)
  18223. {
  18224. methodGroup.mDefault->mIRFunction = BfIRFunction();
  18225. }
  18226. }
  18227. }
  18228. if (methodGroup.mMethodSpecializationMap != NULL)
  18229. {
  18230. for (auto& mapPair : *methodGroup.mMethodSpecializationMap)
  18231. {
  18232. auto methodInstance = mapPair.mValue;
  18233. if (methodInstance->mDeclModule == this)
  18234. {
  18235. methodInstance->mIRFunction = BfIRFunction();
  18236. }
  18237. }
  18238. }
  18239. }
  18240. }
  18241. }
  18242. void BfModule::ClearModule()
  18243. {
  18244. ClearModuleData();
  18245. DisownMethods();
  18246. for (auto& specPair : mSpecializedMethodModules)
  18247. {
  18248. auto specModule = specPair.mValue;
  18249. specModule->ClearModule();
  18250. }
  18251. if (mNextAltModule != NULL)
  18252. mNextAltModule->ClearModule();
  18253. }