BfModule.cpp 707 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974
  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 == "IDE_ui_LaunchDialog")
  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) && (mCurMethodState != NULL))
  2155. {
  2156. auto checkMethodState = mCurMethodState;
  2157. while (checkMethodState != NULL)
  2158. {
  2159. auto methodInstance = checkMethodState->mMethodInstance;
  2160. if (methodInstance == NULL)
  2161. {
  2162. checkMethodState = checkMethodState->mPrevMethodState;
  2163. continue;
  2164. }
  2165. // Propogatea the fail all the way to the main method (assuming we're in a local method or lambda)
  2166. methodInstance->mHasFailed = true;
  2167. bool isSpecializedMethod = ((methodInstance != NULL) && (!methodInstance->mIsUnspecialized) && (methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mMethodGenericArguments.size() != 0));
  2168. if (isSpecializedMethod)
  2169. {
  2170. //auto unspecializedMethod = &mCurMethodInstance->mMethodInstanceGroup->mMethodSpecializationMap.begin()->second;
  2171. auto unspecializedMethod = methodInstance->mMethodInstanceGroup->mDefault;
  2172. if (unspecializedMethod->mHasFailed)
  2173. return NULL; // At least SOME error has already been reported
  2174. }
  2175. if (isSpecializedMethod)
  2176. {
  2177. errorString += StrFormat("\n while specializing method '%s'", MethodToString(methodInstance).c_str());
  2178. isWhileSpecializing = true;
  2179. isWhileSpecializingMethod = true;
  2180. }
  2181. else if ((methodInstance != NULL) && (methodInstance->mIsForeignMethodDef))
  2182. {
  2183. errorString += StrFormat("\n while implementing default interface method '%s'", MethodToString(methodInstance).c_str());
  2184. isWhileSpecializing = true;
  2185. isWhileSpecializingMethod = true;
  2186. }
  2187. else if ((mCurTypeInstance->IsGenericTypeInstance()) && (!mCurTypeInstance->IsUnspecializedType()))
  2188. {
  2189. errorString += StrFormat("\n while specializing type '%s'", TypeToString(mCurTypeInstance).c_str());
  2190. isWhileSpecializing = true;
  2191. }
  2192. checkMethodState = checkMethodState->mPrevMethodState;
  2193. }
  2194. // Keep in mind that all method specializations with generic type instances as its method generic params
  2195. // need to be deferred because the specified generic type instance might get deleted at the end of the
  2196. // compilation due to no longer having indirect references removed, and we have to ignore errors from
  2197. // those method specializations if that occurs
  2198. if (isWhileSpecializing)
  2199. {
  2200. BfError* bfError = mCompiler->mPassInstance->DeferFail(errorString, refNode);
  2201. if (bfError != NULL)
  2202. bfError->mIsWhileSpecializing = isWhileSpecializing;
  2203. return bfError;
  2204. }
  2205. }
  2206. if (!mHadBuildError)
  2207. mHadBuildError = true;
  2208. // Check mixins
  2209. {
  2210. auto checkMethodInstance = mCurMethodState;
  2211. while (checkMethodInstance != NULL)
  2212. {
  2213. auto rootMixinState = checkMethodInstance->GetRootMixinState();
  2214. if (rootMixinState != NULL)
  2215. {
  2216. BfError* bfError = mCompiler->mPassInstance->Fail(StrFormat("Failed to inject mixin '%s'", MethodToString(rootMixinState->mMixinMethodInstance).c_str()), rootMixinState->mSource);
  2217. mCompiler->mPassInstance->MoreInfo(errorString, refNode);
  2218. auto mixinState = checkMethodInstance->mMixinState;
  2219. while ((mixinState != NULL) && (mixinState->mPrevMixinState != NULL))
  2220. {
  2221. mCompiler->mPassInstance->MoreInfo(StrFormat("Injected from mixin '%s'", MethodToString(mixinState->mPrevMixinState->mMixinMethodInstance).c_str()), mixinState->mSource);
  2222. mixinState = mixinState->mPrevMixinState;
  2223. }
  2224. return bfError;
  2225. }
  2226. checkMethodInstance = checkMethodInstance->mPrevMethodState;
  2227. }
  2228. }
  2229. BfError* bfError = NULL;
  2230. if (refNode == NULL)
  2231. bfError = mCompiler->mPassInstance->Fail(errorString);
  2232. else
  2233. {
  2234. bfError = mCompiler->mPassInstance->Fail(errorString, refNode);
  2235. }
  2236. if (bfError != NULL)
  2237. {
  2238. bfError->mIsPersistent = isPersistent;
  2239. bfError->mIsWhileSpecializing = isWhileSpecializing;
  2240. if ((mCurMethodState != NULL) && (mCurMethodState->mDeferredCallEmitState != NULL) && (mCurMethodState->mDeferredCallEmitState->mCloseNode != NULL))
  2241. mCompiler->mPassInstance->MoreInfo("Error during deferred statement handling", mCurMethodState->mDeferredCallEmitState->mCloseNode);
  2242. }
  2243. return bfError;
  2244. }
  2245. BfError* BfModule::FailAfter(const StringImpl& error, BfAstNode* refNode)
  2246. {
  2247. if (mIgnoreErrors)
  2248. return NULL;
  2249. if (refNode != NULL)
  2250. refNode = BfNodeToNonTemporary(refNode);
  2251. mHadBuildError = true;
  2252. return mCompiler->mPassInstance->FailAfter(error, refNode);
  2253. }
  2254. BfError* BfModule::Warn(int warningNum, const StringImpl& warning, BfAstNode* refNode, bool isPersistent)
  2255. {
  2256. if (mIgnoreErrors || mIgnoreWarnings)
  2257. return NULL;
  2258. if (!mReportErrors)
  2259. {
  2260. mCompiler->mPassInstance->SilentFail();
  2261. return NULL;
  2262. }
  2263. BfAstNode* unwarnNode = refNode;
  2264. //
  2265. {
  2266. BfParentNodeEntry* parentNodeEntry = mParentNodeEntry;
  2267. while (parentNodeEntry != NULL)
  2268. {
  2269. if (auto block = BfNodeDynCast<BfBlock>(parentNodeEntry->mNode))
  2270. break;
  2271. unwarnNode = parentNodeEntry->mNode;
  2272. parentNodeEntry = parentNodeEntry->mPrev;
  2273. }
  2274. }
  2275. auto parser = unwarnNode->GetSourceData()->ToParserData();
  2276. if ((parser != NULL) && (parser->IsUnwarnedAt(unwarnNode)))
  2277. {
  2278. return NULL;
  2279. }
  2280. // Right now we're only warning on the unspecialized declarations, we may revisit this
  2281. if (mCurMethodInstance != NULL)
  2282. {
  2283. if (mCurMethodInstance->IsSpecializedGenericMethodOrType())
  2284. return NULL;
  2285. if (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend)
  2286. return NULL; // No ctorCalcAppend warnings
  2287. }
  2288. if ((mCurTypeInstance != NULL) && (mCurTypeInstance->IsSpecializedType()))
  2289. return NULL;
  2290. if (refNode != NULL)
  2291. refNode = BfNodeToNonTemporary(refNode);
  2292. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL))
  2293. {
  2294. // We used to bubble up warnings into the mixin injection site, BUT
  2295. // we are now assuming any relevant warnings will be given at the declaration site
  2296. return NULL;
  2297. // AddFailType(mCurTypeInstance);
  2298. //
  2299. // BfError* bfError = mCompiler->mPassInstance->Warn(warningNum, "Warning while injecting mixin", mCurMethodState->mMixinState->GetRoot()->mSource);
  2300. // if (bfError == NULL)
  2301. // return NULL;
  2302. // mHadBuildWarning = true;
  2303. // return mCompiler->mPassInstance->MoreInfo(warning, refNode);
  2304. }
  2305. BfError* bfError = mCompiler->mPassInstance->WarnAt(warningNum, warning, refNode->GetSourceData(), refNode->GetSrcStart(), refNode->GetSrcLength());
  2306. if (bfError != NULL)
  2307. {
  2308. AddFailType(mCurTypeInstance);
  2309. mHadBuildWarning = true;
  2310. bfError->mIsPersistent = isPersistent;
  2311. if ((mCompiler->IsAutocomplete()) && (mCompiler->mResolvePassData->mAutoComplete->CheckFixit((refNode))))
  2312. {
  2313. BfParserData* parser = refNode->GetSourceData()->ToParserData();
  2314. if (parser != NULL)
  2315. {
  2316. int fileLoc = BfFixitFinder::FindLineStartBefore(refNode);
  2317. mCompiler->mResolvePassData->mAutoComplete->AddEntry(AutoCompleteEntry("fixit", StrFormat("#unwarn\tunwarn|%s|%d|#unwarn|", parser->mFileName.c_str(), fileLoc).c_str()));
  2318. }
  2319. }
  2320. }
  2321. return bfError;
  2322. }
  2323. void BfModule::CheckRangeError(BfType* type, BfAstNode* refNode)
  2324. {
  2325. if (mBfIRBuilder->mOpFailed)
  2326. Fail(StrFormat("Result out of range for type '%s'", TypeToString(type).c_str()), refNode);
  2327. }
  2328. void BfModule::NotImpl(BfAstNode* astNode)
  2329. {
  2330. Fail("INTERNAL ERROR: Not implemented", astNode);
  2331. }
  2332. bool BfModule::CheckAccessMemberProtection(BfProtection protection, BfType* memberType)
  2333. {
  2334. bool allowPrivate = (memberType == mCurTypeInstance) || (IsInnerType(mCurTypeInstance, memberType));
  2335. if (!allowPrivate)
  2336. allowPrivate |= memberType->IsInterface();
  2337. bool allowProtected = allowPrivate;// allowPrivate || TypeIsSubTypeOf(mCurTypeInstance, memberType->ToTypeInstance());
  2338. if (!CheckProtection(protection, allowProtected, allowPrivate))
  2339. {
  2340. return false;
  2341. }
  2342. return true;
  2343. }
  2344. bool BfModule::CheckDefineMemberProtection(BfProtection protection, BfType* memberType)
  2345. {
  2346. // Use 'min' - exporting a 'public' from a 'private' class is really just 'private' still
  2347. protection = std::min(protection, mCurTypeInstance->mTypeDef->mProtection);
  2348. auto memberTypeInstance = memberType->ToTypeInstance();
  2349. if (memberTypeInstance == NULL)
  2350. {
  2351. auto underlyingType = memberType->GetUnderlyingType();
  2352. if (underlyingType != NULL)
  2353. return CheckDefineMemberProtection(protection, underlyingType);
  2354. return true;
  2355. }
  2356. if (memberTypeInstance->mTypeDef->mProtection < protection)
  2357. return false;
  2358. if (memberTypeInstance->IsGenericTypeInstance())
  2359. {
  2360. // When we're a generic struct, our data layout can depend on our generic parameters as well
  2361. auto genericTypeInstance = (BfGenericTypeInstance*) memberTypeInstance;
  2362. for (auto typeGenericArg : genericTypeInstance->mTypeGenericArguments)
  2363. {
  2364. if (!CheckDefineMemberProtection(protection, typeGenericArg))
  2365. return false;
  2366. }
  2367. }
  2368. return true;
  2369. }
  2370. void BfModule::AddDependency(BfType* usedType, BfType* usingType, BfDependencyMap::DependencyDependencyFlag flags)
  2371. {
  2372. if (usedType == usingType)
  2373. return;
  2374. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mIsAutocompleteMethod))
  2375. return;
  2376. if (usedType->IsSpecializedByAutoCompleteMethod())
  2377. return;
  2378. if ((mCurMethodState != NULL) && (mCurMethodState->mHotDataReferenceBuilder != NULL) && (usedType != mCurTypeInstance) &&
  2379. ((flags & (BfDependencyMap::DependencyFlag_ReadFields | BfDependencyMap::DependencyFlag_LocalUsage | BfDependencyMap::DependencyFlag_Allocates)) != 0))
  2380. {
  2381. bool addType = true;
  2382. auto checkType = usedType;
  2383. while (true)
  2384. {
  2385. if ((checkType->IsPointer()) || (checkType->IsRef()) || (checkType->IsSizedArray()))
  2386. checkType = checkType->GetUnderlyingType();
  2387. else if (checkType->IsArray())
  2388. {
  2389. checkType = ((BfGenericTypeInstance*)checkType)->mTypeGenericArguments[0];
  2390. }
  2391. else
  2392. break;
  2393. }
  2394. PopulateType(checkType, BfPopulateType_Data);
  2395. if (checkType->IsValuelessType())
  2396. addType = false;
  2397. else if (checkType->IsPrimitiveType())
  2398. addType = false;
  2399. else
  2400. {
  2401. auto checkTypeInst = checkType->ToTypeInstance();
  2402. if (checkTypeInst == NULL)
  2403. {
  2404. addType = false;
  2405. }
  2406. else
  2407. {
  2408. if (TypeIsSubTypeOf(mCurTypeInstance, checkTypeInst))
  2409. addType = false;
  2410. }
  2411. }
  2412. if (addType)
  2413. {
  2414. auto checkTypeInst = checkType->ToTypeInstance();
  2415. auto hotTypeVersion = checkTypeInst->mHotTypeData->GetLatestVersion();
  2416. BF_ASSERT(hotTypeVersion != NULL);
  2417. bool isAllocation = ((flags & BfDependencyMap::DependencyFlag_Allocates) != 0);
  2418. if (((flags & BfDependencyMap::DependencyFlag_LocalUsage) != 0) &&
  2419. (checkType->IsComposite()))
  2420. isAllocation = true;
  2421. if (isAllocation)
  2422. {
  2423. mCurMethodState->mHotDataReferenceBuilder->mAllocatedData.Add(hotTypeVersion);
  2424. }
  2425. else
  2426. mCurMethodState->mHotDataReferenceBuilder->mUsedData.Add(hotTypeVersion);
  2427. }
  2428. }
  2429. //BP_ZONE("BfModule::AddDependency");
  2430. /*if (usedType->IsMethodRef())
  2431. {
  2432. auto methodRefType = (BfMethodRefType*)usedType;
  2433. AddDependency(methodRefType->mMethodRef->GetOwner(), usingType, flags);
  2434. return;
  2435. }*/
  2436. // Why in the world were we doing this?
  2437. // This caused functions to get immediately deleted since they appear to have no references ever....
  2438. // if (usedType->IsFunction())
  2439. // {
  2440. // usedType = ResolveTypeDef(mCompiler->mFunctionTypeDef);
  2441. // }
  2442. if ((!mCompiler->mIsResolveOnly) && (mIsReified))
  2443. {
  2444. auto usingModule = usingType->GetModule();
  2445. BfModule* usedModule;
  2446. if (usedType->IsFunction())
  2447. {
  2448. auto typeInst = usedType->ToTypeInstance();
  2449. if (typeInst->mBaseType == NULL)
  2450. PopulateType(typeInst);
  2451. usedModule = typeInst->mBaseType->GetModule();
  2452. }
  2453. else
  2454. usedModule = usedType->GetModule();
  2455. if ((usingModule != NULL) && (!usingModule->mIsSpecialModule) &&
  2456. (usedModule != NULL) && (!usedModule->mIsSpecialModule))
  2457. {
  2458. usingModule->mModuleRefs.Add(usedModule);
  2459. }
  2460. }
  2461. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mMethodInfoEx != NULL) && (flags != BfDependencyMap::DependencyFlag_MethodGenericArg))
  2462. {
  2463. // When we are specializing a method, usage of that specialized type is already handled with DependencyFlag_MethodGenericArg
  2464. for (auto genericArg : mCurMethodInstance->mMethodInfoEx->mMethodGenericArguments)
  2465. if (genericArg == usedType)
  2466. return;
  2467. }
  2468. auto underlyingType = usedType->GetUnderlyingType();
  2469. if (underlyingType != NULL) // Not really a "GenericArg", but... same purpose.
  2470. AddDependency(underlyingType, usingType, BfDependencyMap::DependencyFlag_GenericArgRef);
  2471. BfDependedType* checkDType = usedType->ToDependedType();
  2472. if (checkDType == NULL)
  2473. return;
  2474. if ((usedType->mRebuildFlags & BfTypeRebuildFlag_AwaitingReference) != 0)
  2475. mContext->MarkAsReferenced(checkDType);
  2476. checkDType->mDependencyMap.AddUsedBy(usingType, flags);
  2477. if (checkDType->IsGenericTypeInstance())
  2478. {
  2479. auto genericTypeInstance = (BfGenericTypeInstance*) checkDType;
  2480. for (auto genericArg : genericTypeInstance->mTypeGenericArguments)
  2481. {
  2482. AddDependency(genericArg, usingType, BfDependencyMap::DependencyFlag_GenericArgRef);
  2483. }
  2484. }
  2485. }
  2486. void BfModule::AddCallDependency(BfMethodInstance* methodInstance, bool devirtualized)
  2487. {
  2488. if ((mCurMethodState != NULL) && (mCurMethodState->mHotDataReferenceBuilder != NULL))
  2489. {
  2490. if (methodInstance->mHotMethod == NULL)
  2491. CheckHotMethod(methodInstance, "");
  2492. BF_ASSERT(methodInstance->mHotMethod != NULL);
  2493. if (devirtualized)
  2494. mCurMethodState->mHotDataReferenceBuilder->mDevirtualizedCalledMethods.Add(methodInstance->mHotMethod);
  2495. else
  2496. mCurMethodState->mHotDataReferenceBuilder->mCalledMethods.Add(methodInstance->mHotMethod);
  2497. }
  2498. }
  2499. bool BfModule::IsAttribute(BfTypeInstance* typeInst)
  2500. {
  2501. auto checkTypeInst = typeInst;
  2502. while (checkTypeInst != NULL)
  2503. {
  2504. if (checkTypeInst->mTypeDef == mCompiler->mAttributeTypeDef)
  2505. return true;
  2506. checkTypeInst = checkTypeInst->mBaseType;
  2507. }
  2508. return false;
  2509. }
  2510. void BfModule::PopulateGlobalContainersList(const BfGlobalLookup& globalLookup)
  2511. {
  2512. if (mContext->mCurTypeState == NULL)
  2513. return;
  2514. BP_ZONE("PopulateGlobalContainersList");
  2515. BfTypeDef* userTypeDef = mContext->mCurTypeState->mCurTypeDef;
  2516. if (userTypeDef == NULL)
  2517. userTypeDef = mCurTypeInstance->mTypeDef;
  2518. if (mContext->mCurTypeState->mGlobalContainerCurUserTypeDef != userTypeDef)
  2519. {
  2520. mContext->mCurTypeState->mGlobalContainers.Clear();
  2521. for (int namespaceIdx = -1; namespaceIdx < (int)userTypeDef->mNamespaceSearch.size(); namespaceIdx++)
  2522. {
  2523. BfAtomComposite findStr;
  2524. if (namespaceIdx != -1)
  2525. findStr.Reference(userTypeDef->mNamespaceSearch[namespaceIdx]);
  2526. auto typeDefItr = mSystem->mTypeDefs.TryGet(findStr);
  2527. while (typeDefItr)
  2528. {
  2529. auto typeDef = *typeDefItr;
  2530. if ((typeDef->mFullName == findStr) && (typeDef->mIsCombinedPartial) && (typeDef->IsGlobalsContainer()))
  2531. {
  2532. if (typeDef->mProject->ContainsReference(typeDef->mProject))
  2533. {
  2534. BfGlobalContainerEntry globalEntry;
  2535. globalEntry.mTypeDef = typeDef;
  2536. globalEntry.mTypeInst = NULL;
  2537. typeDef->PopulateMemberSets();
  2538. mContext->mCurTypeState->mGlobalContainers.Add(globalEntry);
  2539. }
  2540. }
  2541. else if (!typeDef->mIsPartial)
  2542. {
  2543. //break;
  2544. }
  2545. typeDefItr.MoveToNextHashMatch();
  2546. }
  2547. }
  2548. mContext->mCurTypeState->mGlobalContainerCurUserTypeDef = userTypeDef;
  2549. }
  2550. // Only create actual typeInst when we have an applicable member. This helps in keeping unused globals from
  2551. // reifing types
  2552. for (auto& globalEntry : mContext->mCurTypeState->mGlobalContainers)
  2553. {
  2554. if (globalEntry.mTypeInst == NULL)
  2555. {
  2556. bool include = false;
  2557. if (globalLookup.mKind == BfGlobalLookup::Kind_All)
  2558. include = true;
  2559. else if (globalLookup.mKind == BfGlobalLookup::Kind_Field)
  2560. {
  2561. if (globalEntry.mTypeDef->mFieldSet.ContainsWith(globalLookup.mName))
  2562. include = true;
  2563. if (globalEntry.mTypeDef->mPropertySet.ContainsWith(globalLookup.mName))
  2564. include = true;
  2565. }
  2566. else if (globalLookup.mKind == BfGlobalLookup::Kind_Method)
  2567. {
  2568. if (globalEntry.mTypeDef->mMethodSet.ContainsWith(globalLookup.mName))
  2569. include = true;
  2570. }
  2571. if (include)
  2572. {
  2573. auto type = ResolveTypeDef(globalEntry.mTypeDef);
  2574. if (type != NULL)
  2575. globalEntry.mTypeInst = type->ToTypeInstance();
  2576. }
  2577. }
  2578. }
  2579. }
  2580. void PrintUsers(llvm::MDNode* md);
  2581. BfModuleOptions BfModule::GetModuleOptions()
  2582. {
  2583. if (mIsScratchModule)
  2584. return BfModuleOptions();
  2585. if (mModuleOptions != NULL)
  2586. return *mModuleOptions;
  2587. BfModuleOptions moduleOptions;
  2588. moduleOptions.mEmitDebugInfo = mCompiler->mOptions.mEmitDebugInfo ? 1 : mCompiler->mOptions.mEmitLineInfo ? 2 : 0;
  2589. if (mProject != NULL)
  2590. {
  2591. moduleOptions.mSIMDSetting = mProject->mCodeGenOptions.mSIMDSetting;
  2592. moduleOptions.mOptLevel = mProject->mCodeGenOptions.mOptLevel;
  2593. }
  2594. auto headModule = this;
  2595. while (headModule->mParentModule != NULL)
  2596. headModule = headModule->mParentModule;
  2597. BF_ASSERT((headModule->mOwnedTypeInstances.size() > 0) || (mModuleName == "vdata"));
  2598. if (headModule->mOwnedTypeInstances.size() > 0)
  2599. {
  2600. auto typeInst = headModule->mOwnedTypeInstances[0];
  2601. PopulateType(typeInst);
  2602. if (typeInst->mTypeOptionsIdx != -1)
  2603. {
  2604. auto typeOptions = mSystem->GetTypeOptions(typeInst->mTypeOptionsIdx);
  2605. moduleOptions.mSIMDSetting = (BfSIMDSetting)BfTypeOptions::Apply((int)moduleOptions.mSIMDSetting, typeOptions->mSIMDSetting);
  2606. moduleOptions.mEmitDebugInfo = BfTypeOptions::Apply(moduleOptions.mEmitDebugInfo, typeOptions->mEmitDebugInfo);
  2607. moduleOptions.mOptLevel = (BfOptLevel)BfTypeOptions::Apply((int)moduleOptions.mOptLevel, (int)typeOptions->mOptimizationLevel);
  2608. }
  2609. }
  2610. return moduleOptions;
  2611. }
  2612. BfCheckedKind BfModule::GetDefaultCheckedKind()
  2613. {
  2614. bool runtimeChecks = mCompiler->mOptions.mRuntimeChecks;
  2615. auto typeOptions = GetTypeOptions();
  2616. if (typeOptions != NULL)
  2617. runtimeChecks = BfTypeOptions::Apply(runtimeChecks, typeOptions->mRuntimeChecks);
  2618. return runtimeChecks ? BfCheckedKind_Checked : BfCheckedKind_Unchecked;
  2619. }
  2620. void BfModule::AddFailType(BfTypeInstance* typeInstance)
  2621. {
  2622. mContext->mFailTypes.Add(typeInstance);
  2623. }
  2624. void BfModule::CheckAddFailType()
  2625. {
  2626. //TODO: We removed this line, because failures in resolve-only generic method can occur in non-owning modules
  2627. // but we still need to add the owning type to the FailTypes list
  2628. //.. OLD:
  2629. // While we're inlining, it's possible that mCurTypeInstance belongs to another module, ignore it
  2630. /*if (mCurTypeInstance->mModule != this)
  2631. return;*/
  2632. // Using mHadBuildWarning to insert into mFailTypes is our core of our strategy for reasserting
  2633. // warnings on rebuilds where otherwise the warnings wouldn't be generated because no code was
  2634. // being recompiled. This forces types with warnings to be recompiled.
  2635. // We had this 'mIsResolveOnly' check for speed in resolveOnly, but we removed it so the IDE can be
  2636. // constantly warning-aware
  2637. if ((mHadBuildError) ||
  2638. (mHadBuildWarning /*&& !mCompiler->mIsResolveOnly*/))
  2639. {
  2640. //mContext->mFailTypes.Add(mCurTypeInstance);
  2641. }
  2642. }
  2643. void BfModule::MarkDerivedDirty(BfTypeInstance* typeInst)
  2644. {
  2645. if (!mCompiler->IsHotCompile())
  2646. return;
  2647. typeInst->mDirty = true;
  2648. for (auto& dep : typeInst->mDependencyMap)
  2649. {
  2650. auto depType = dep.mKey;
  2651. auto depFlags = dep.mValue.mFlags;
  2652. if ((depFlags & BfDependencyMap::DependencyFlag_DerivedFrom) != 0)
  2653. {
  2654. MarkDerivedDirty(depType->ToTypeInstance());
  2655. }
  2656. }
  2657. }
  2658. void BfModule::CreateStaticField(BfFieldInstance* fieldInstance, bool isThreadLocal)
  2659. {
  2660. auto fieldType = fieldInstance->GetResolvedType();
  2661. auto field = fieldInstance->GetFieldDef();
  2662. if (fieldType->IsVar())
  2663. return;
  2664. BfIRValue initValue;
  2665. if (field->mIsConst)
  2666. {
  2667. if (fieldType->IsPointer())
  2668. fieldType = fieldType->GetUnderlyingType();
  2669. }
  2670. if (!field->mIsExtern)
  2671. initValue = GetDefaultValue(fieldType);
  2672. if (fieldInstance->mOwner->IsUnspecializedType())
  2673. {
  2674. // Placeholder
  2675. auto ptrVal = CreatePointerType(fieldType);
  2676. mStaticFieldRefs[fieldInstance] = GetDefaultValue(ptrVal);
  2677. }
  2678. else
  2679. {
  2680. BfLogSysM("Creating static field Module:%p Type:%p\n", this, fieldType);
  2681. StringT<128> staticVarName;
  2682. BfMangler::Mangle(staticVarName, mCompiler->GetMangleKind(), fieldInstance);
  2683. if (!fieldType->IsValuelessType())
  2684. {
  2685. BfIRValue globalVar = mBfIRBuilder->CreateGlobalVariable(
  2686. mBfIRBuilder->MapType(fieldType, BfIRPopulateType_Eventually_Full),
  2687. false,
  2688. BfIRLinkageType_External,
  2689. initValue,
  2690. staticVarName,
  2691. isThreadLocal);
  2692. BF_ASSERT(globalVar);
  2693. mStaticFieldRefs[fieldInstance] = globalVar;
  2694. }
  2695. }
  2696. }
  2697. void BfModule::ResolveConstField(BfTypeInstance* typeInstance, BfFieldInstance* fieldInstance, BfFieldDef* fieldDef, bool forceResolve)
  2698. {
  2699. bool autoCompleteOnly = mCompiler->IsAutocomplete();
  2700. BfType* fieldType = NULL;
  2701. if (fieldInstance != NULL)
  2702. {
  2703. fieldType = fieldInstance->GetResolvedType();
  2704. if (fieldType == NULL)
  2705. fieldType = ResolveTypeRef(fieldDef->mTypeRef);
  2706. }
  2707. else
  2708. {
  2709. BF_ASSERT(mCompiler->IsAutocomplete());
  2710. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  2711. if ((typeInstance->IsEnum()) && (fieldDef->mTypeRef == NULL))
  2712. {
  2713. fieldType = typeInstance;
  2714. }
  2715. else
  2716. {
  2717. auto isLet = (fieldDef->mTypeRef != NULL) && (fieldDef->mTypeRef->IsExact<BfLetTypeReference>());
  2718. auto isVar = (fieldDef->mTypeRef != NULL) && (fieldDef->mTypeRef->IsExact<BfVarTypeReference>());
  2719. if (isLet || isVar)
  2720. fieldType = GetPrimitiveType(BfTypeCode_Var);
  2721. else
  2722. fieldType = ResolveTypeRef(fieldDef->mTypeRef);
  2723. if (fieldType == NULL)
  2724. fieldType = mContext->mBfObjectType;
  2725. }
  2726. }
  2727. if ((fieldInstance != NULL) && (fieldInstance->mConstIdx != -1) && (!forceResolve))
  2728. return;
  2729. if (mContext->mFieldResolveReentrys.size() > 1)
  2730. {
  2731. if (mContext->mFieldResolveReentrys.IndexOf(fieldInstance, 1) != -1)
  2732. {
  2733. String failStr = "Circular data reference detected between the following fields:";
  2734. for (int i = 1; i < (int)mContext->mFieldResolveReentrys.size(); i++)
  2735. {
  2736. if (i > 1)
  2737. failStr += ",";
  2738. failStr += "\n '" + TypeToString(typeInstance) + "." + mContext->mFieldResolveReentrys[i]->GetFieldDef()->mName + "'";
  2739. }
  2740. BfError* err = Fail(failStr, fieldDef->mFieldDeclaration);
  2741. if (err)
  2742. err->mIsPersistent = true;
  2743. return;
  2744. }
  2745. }
  2746. mContext->mFieldResolveReentrys.push_back(fieldInstance);
  2747. AutoPopBack<decltype (mContext->mFieldResolveReentrys)> popTypeResolveReentry(&mContext->mFieldResolveReentrys);
  2748. if (fieldInstance == NULL)
  2749. popTypeResolveReentry.Pop();
  2750. auto typeDef = typeInstance->mTypeDef;
  2751. BfIRValue constValue;
  2752. if (fieldDef->mIsExtern)
  2753. {
  2754. if (!fieldDef->mTypeRef->IsA<BfPointerTypeRef>())
  2755. {
  2756. Fail("Extern consts must be pointer types", fieldDef->mFieldDeclaration->mTypeRef);
  2757. }
  2758. if (fieldDef->mInitializer != NULL)
  2759. {
  2760. Fail("Extern consts cannot have initializers", fieldDef->mFieldDeclaration->mNameNode);
  2761. }
  2762. }
  2763. else if (fieldDef->mInitializer == NULL)
  2764. {
  2765. if (fieldDef->IsEnumCaseEntry())
  2766. {
  2767. if (typeInstance->IsTypedPrimitive())
  2768. {
  2769. BfFieldInstance* prevFieldInstance = NULL;
  2770. for (int i = fieldDef->mIdx - 1; i >= 0; i--)
  2771. {
  2772. BfFieldInstance* checkFieldInst = &typeInstance->mFieldInstances[i];
  2773. if (checkFieldInst->GetFieldDef()->IsEnumCaseEntry())
  2774. {
  2775. prevFieldInstance = checkFieldInst;
  2776. break;
  2777. }
  2778. }
  2779. if (prevFieldInstance == NULL)
  2780. constValue = GetConstValue(0, typeInstance);
  2781. else
  2782. {
  2783. ResolveConstField(typeInstance, prevFieldInstance, prevFieldInstance->GetFieldDef());
  2784. if (prevFieldInstance->mConstIdx == -1)
  2785. {
  2786. if (!mCompiler->IsAutocomplete())
  2787. AssertErrorState();
  2788. constValue = GetConstValue(0, typeInstance);
  2789. }
  2790. else
  2791. {
  2792. auto prevConstant = ConstantToCurrent(typeInstance->mConstHolder->GetConstantById(prevFieldInstance->mConstIdx), typeInstance->mConstHolder, typeInstance);
  2793. constValue = mBfIRBuilder->CreateAdd(prevConstant, GetConstValue(1, typeInstance));
  2794. }
  2795. }
  2796. }
  2797. }
  2798. else
  2799. {
  2800. Fail("Const requires initializer", fieldDef->mFieldDeclaration->mNameNode);
  2801. }
  2802. }
  2803. else
  2804. {
  2805. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  2806. SetAndRestoreValue<bool> prevIgnoreWrite(mBfIRBuilder->mIgnoreWrites, true);
  2807. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, NULL);
  2808. BfConstResolver constResolver(this);
  2809. BfMethodState methodState;
  2810. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  2811. methodState.mTempKind = BfMethodState::TempKind_Static;
  2812. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  2813. if (fieldType->IsVar())
  2814. {
  2815. auto initValue = GetFieldInitializerValue(fieldInstance, fieldDef->mInitializer, fieldDef, fieldType);
  2816. if (!initValue)
  2817. {
  2818. AssertErrorState();
  2819. initValue = GetDefaultTypedValue(mContext->mBfObjectType);
  2820. }
  2821. if (fieldInstance != NULL)
  2822. {
  2823. fieldInstance->mResolvedType = initValue.mType;
  2824. }
  2825. constValue = initValue.mValue;
  2826. }
  2827. else
  2828. {
  2829. auto uncastedInitValue = GetFieldInitializerValue(fieldInstance, fieldDef->mInitializer, fieldDef, fieldType);
  2830. constValue = uncastedInitValue.mValue;
  2831. }
  2832. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  2833. }
  2834. if (fieldInstance != NULL)
  2835. {
  2836. fieldType = fieldInstance->GetResolvedType();
  2837. if ((fieldType == NULL) || (fieldType->IsVar()))
  2838. {
  2839. AssertErrorState();
  2840. // Default const type is 'int'
  2841. BfTypedValue initValue = GetDefaultTypedValue(GetPrimitiveType(BfTypeCode_IntPtr));
  2842. if (fieldInstance != NULL)
  2843. {
  2844. fieldInstance->mResolvedType = initValue.mType;
  2845. }
  2846. constValue = initValue.mValue;
  2847. }
  2848. if ((constValue) && (fieldInstance->mConstIdx == -1))
  2849. {
  2850. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  2851. CurrentAddToConstHolder(constValue);
  2852. fieldInstance->mConstIdx = constValue.mId;
  2853. }
  2854. }
  2855. }
  2856. BfType* BfModule::ResolveVarFieldType(BfTypeInstance* typeInstance, BfFieldInstance* fieldInstance, BfFieldDef* field)
  2857. {
  2858. bool isDeclType = BfNodeDynCastExact<BfDeclTypeRef>(field->mFieldDeclaration->mTypeRef) != NULL;
  2859. auto fieldType = fieldInstance->GetResolvedType();
  2860. if ((field->mIsConst) && (!isDeclType))
  2861. {
  2862. ResolveConstField(typeInstance, fieldInstance, field);
  2863. return fieldInstance->GetResolvedType();
  2864. }
  2865. bool staticOnly = (field->mIsStatic) && (!isDeclType);
  2866. if (!fieldInstance->mIsInferredType)
  2867. return fieldType;
  2868. if (!fieldType->IsVar())
  2869. return fieldType;
  2870. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  2871. BfTypeState typeState(mCurTypeInstance, mContext->mCurTypeState);
  2872. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState, mContext->mCurTypeState->mTypeInstance != typeInstance);
  2873. auto typeDef = typeInstance->mTypeDef;
  2874. if ((!field->mIsStatic) && (typeDef->mIsStatic))
  2875. {
  2876. AssertErrorState();
  2877. return GetPrimitiveType(BfTypeCode_Var);
  2878. }
  2879. bool hadInferenceCycle = false;
  2880. if (mContext->mFieldResolveReentrys.size() > 1)
  2881. {
  2882. if (mContext->mFieldResolveReentrys.IndexOf(fieldInstance, 1) != -1)
  2883. {
  2884. for (int i = 1; i < (int)mContext->mFieldResolveReentrys.size(); i++)
  2885. {
  2886. auto fieldInst = mContext->mFieldResolveReentrys[i];
  2887. auto fieldDef = fieldInst->GetFieldDef();
  2888. auto fieldOwner = fieldInst->mOwner;
  2889. auto fieldModule = fieldOwner->mModule;
  2890. SetAndRestoreValue<bool> prevIgnoreError(fieldModule->mIgnoreErrors, false);
  2891. fieldModule->Fail(StrFormat("Field '%s.%s' creates a type inference cycle", TypeToString(fieldOwner).c_str(), fieldDef->mName.c_str()), fieldDef->mTypeRef, true);
  2892. }
  2893. return GetPrimitiveType(BfTypeCode_Var);
  2894. }
  2895. }
  2896. mContext->mFieldResolveReentrys.push_back(fieldInstance);
  2897. AutoPopBack<decltype (mContext->mFieldResolveReentrys)> popTypeResolveReentry(&mContext->mFieldResolveReentrys);
  2898. SetAndRestoreValue<bool> prevResolvingVar(typeInstance->mResolvingVarField, true);
  2899. SetAndRestoreValue<bool> prevCtxResolvingVar(mContext->mResolvingVarField, true);
  2900. if ((field->mInitializer == NULL) && (!isDeclType))
  2901. {
  2902. if ((field->mTypeRef->IsA<BfVarTypeReference>()) || (field->mTypeRef->IsA<BfLetTypeReference>()))
  2903. Fail("Implicitly-typed fields must be initialized", field->GetRefNode());
  2904. return GetPrimitiveType(BfTypeCode_Var);
  2905. }
  2906. BfType* resolvedType = NULL;
  2907. if (!hadInferenceCycle)
  2908. {
  2909. SetAndRestoreValue<bool> prevIgnoreWrite(mBfIRBuilder->mIgnoreWrites, true);
  2910. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, NULL/*ctorMethod.mMethodInstance*/);
  2911. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  2912. BfMethodState methodState;
  2913. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  2914. methodState.mTempKind = staticOnly ? BfMethodState::TempKind_Static : BfMethodState::TempKind_NonStatic;
  2915. if (!staticOnly)
  2916. {
  2917. //BfLocalVariable localVar;
  2918. //methodState.mLocals.push_back(localVar);
  2919. }
  2920. if (isDeclType)
  2921. {
  2922. auto fieldDef = fieldInstance->GetFieldDef();
  2923. resolvedType = ResolveTypeRef(fieldDef->mTypeRef, BfPopulateType_Identity);
  2924. }
  2925. else
  2926. {
  2927. BfTypedValue valueFromExpr;
  2928. valueFromExpr = GetFieldInitializerValue(fieldInstance);
  2929. FixIntUnknown(valueFromExpr);
  2930. resolvedType = valueFromExpr.mType;
  2931. }
  2932. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  2933. }
  2934. if (resolvedType == NULL)
  2935. return GetPrimitiveType(BfTypeCode_Var);
  2936. fieldInstance->SetResolvedType(resolvedType);
  2937. if (field->mIsStatic)
  2938. {
  2939. }
  2940. else if (fieldInstance->mDataIdx <= 0)
  2941. {
  2942. }
  2943. else
  2944. {
  2945. BF_ASSERT(typeInstance->IsIncomplete());
  2946. }
  2947. return resolvedType;
  2948. }
  2949. void BfModule::MarkFieldInitialized(BfFieldInstance* fieldInstance)
  2950. {
  2951. BF_ASSERT(fieldInstance->mOwner == mCurTypeInstance);
  2952. auto fieldType = fieldInstance->GetResolvedType();
  2953. if ((fieldInstance->mMergedDataIdx != -1) && (mCurMethodState != NULL))
  2954. {
  2955. int fieldDataCount = 1;
  2956. if (fieldType->IsStruct())
  2957. {
  2958. auto structTypeInst = fieldType->ToTypeInstance();
  2959. fieldDataCount = structTypeInst->mMergedFieldDataCount;
  2960. }
  2961. //TODO: Under what circumstances could 'thisVariable' be NULL?
  2962. auto thisVariable = GetThisVariable();
  2963. if (thisVariable != NULL)
  2964. {
  2965. for (int i = 0; i < fieldDataCount; i++)
  2966. mCurMethodState->LocalDefined(thisVariable, fieldInstance->mMergedDataIdx + i);
  2967. }
  2968. }
  2969. }
  2970. bool BfModule::IsThreadLocal(BfFieldInstance * fieldInstance)
  2971. {
  2972. if (fieldInstance->mCustomAttributes == NULL)
  2973. return false;
  2974. auto fieldDef = fieldInstance->GetFieldDef();
  2975. if (!fieldDef->mIsStatic)
  2976. return false;
  2977. bool isThreadLocal = false;
  2978. if (fieldInstance->mCustomAttributes != NULL)
  2979. {
  2980. for (auto customAttr : fieldInstance->mCustomAttributes->mAttributes)
  2981. {
  2982. if (customAttr.mType->ToTypeInstance()->mTypeDef == mCompiler->mThreadStaticAttributeTypeDef)
  2983. return true;
  2984. }
  2985. }
  2986. return false;
  2987. }
  2988. BfTypedValue BfModule::GetFieldInitializerValue(BfFieldInstance* fieldInstance, BfExpression* initializer, BfFieldDef* fieldDef, BfType* fieldType)
  2989. {
  2990. if (fieldDef == NULL)
  2991. fieldDef = fieldInstance->GetFieldDef();
  2992. if (fieldType == NULL)
  2993. fieldType = fieldInstance->GetResolvedType();
  2994. if (initializer == NULL)
  2995. {
  2996. if (fieldDef == NULL)
  2997. return BfTypedValue();
  2998. initializer = fieldDef->mInitializer;
  2999. }
  3000. BfTypedValue result;
  3001. if (initializer == NULL)
  3002. {
  3003. result = GetDefaultTypedValue(fieldInstance->mResolvedType);
  3004. }
  3005. else
  3006. {
  3007. if ((mCompiler->mIsResolveOnly) && (mCompiler->mResolvePassData->mSourceClassifier != NULL) && (initializer->IsFromParser(mCompiler->mResolvePassData->mParser)))
  3008. {
  3009. mCompiler->mResolvePassData->mSourceClassifier->SetElementType(initializer, BfSourceElementType_Normal);
  3010. mCompiler->mResolvePassData->mSourceClassifier->VisitChildNoRef(initializer);
  3011. }
  3012. if ((mCurTypeInstance->IsPayloadEnum()) && (fieldDef->IsEnumCaseEntry()))
  3013. {
  3014. Fail("Enums with payloads cannot have explicitly-defined discriminators", initializer);
  3015. BfConstResolver constResolver(this);
  3016. constResolver.Resolve(initializer);
  3017. return GetDefaultTypedValue(fieldType);
  3018. }
  3019. else if (fieldDef->mIsConst)
  3020. {
  3021. BfTypeState typeState;
  3022. typeState.mCurTypeDef = fieldDef->mDeclaringType;
  3023. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  3024. BfConstResolver constResolver(this);
  3025. if (fieldType->IsVar())
  3026. return constResolver.Resolve(initializer);
  3027. else
  3028. return constResolver.Resolve(initializer, fieldType);
  3029. }
  3030. if (fieldType->IsVar())
  3031. result = CreateValueFromExpression(initializer, NULL, (BfEvalExprFlags)(BfEvalExprFlags_NoValueAddr | BfEvalExprFlags_FieldInitializer));
  3032. else
  3033. result = CreateValueFromExpression(initializer, fieldType, (BfEvalExprFlags)(BfEvalExprFlags_NoValueAddr | BfEvalExprFlags_FieldInitializer));
  3034. }
  3035. if (fieldInstance != NULL)
  3036. MarkFieldInitialized(fieldInstance);
  3037. return result;
  3038. }
  3039. void BfModule::CheckInterfaceMethod(BfMethodInstance* methodInstance)
  3040. {
  3041. }
  3042. void BfModule::FindSubTypes(BfTypeInstance* classType, SizedArrayImpl<int>* outVals, SizedArrayImpl<BfTypeInstance*>* exChecks, bool isInterfacePass)
  3043. {
  3044. PopulateType(classType);
  3045. if (isInterfacePass)
  3046. {
  3047. for (auto ifaceInst : classType->mInterfaces)
  3048. {
  3049. if (exChecks->Contains(ifaceInst.mInterfaceType))
  3050. continue;
  3051. if (outVals->Contains(ifaceInst.mInterfaceType->mTypeId))
  3052. continue;
  3053. if (ifaceInst.mDeclaringType->IsExtension())
  3054. {
  3055. bool needsExCheck = false;
  3056. if (ifaceInst.mDeclaringType->mProject != classType->mTypeDef->mProject)
  3057. {
  3058. exChecks->push_back(ifaceInst.mInterfaceType);
  3059. continue;
  3060. }
  3061. }
  3062. outVals->push_back(ifaceInst.mInterfaceType->mTypeId);
  3063. }
  3064. }
  3065. else
  3066. {
  3067. outVals->push_back(classType->mTypeId);
  3068. }
  3069. if (classType->mBaseType != NULL)
  3070. {
  3071. FindSubTypes(classType->mBaseType, outVals, exChecks, isInterfacePass);
  3072. }
  3073. }
  3074. void BfModule::CreateDynamicCastMethod()
  3075. {
  3076. auto objType = mContext->mBfObjectType;
  3077. if ((mCompiler->mIsResolveOnly) || (!mIsReified))
  3078. {
  3079. // The main reason to punt on this method for ResolveOnly is because types can be created
  3080. // and destroyed quickly during autocomplete and the typeId creep can generate lots of
  3081. // entries in the LLVM ConstantInt pool, primarily from the FindSubTypes call. We can
  3082. // remove this punt when we recycle typeId's
  3083. mBfIRBuilder->CreateRet(mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapTypeInstPtr(objType)));
  3084. mCurMethodState->mHadReturn = true;
  3085. return;
  3086. }
  3087. bool isInterfacePass = mCurMethodInstance->mMethodDef->mName == BF_METHODNAME_DYNAMICCAST_INTERFACE;
  3088. auto func = mCurMethodState->mIRFunction;
  3089. auto thisValue = mBfIRBuilder->GetArgument(0);
  3090. auto typeIdValue = mBfIRBuilder->GetArgument(1);
  3091. auto intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  3092. auto int32Type = GetPrimitiveType(BfTypeCode_Int32);
  3093. typeIdValue = CastToValue(NULL, BfTypedValue(typeIdValue, intPtrType), int32Type, (BfCastFlags)(BfCastFlags_Explicit | BfCastFlags_SilentFail));
  3094. auto thisObject = mBfIRBuilder->CreateBitCast(thisValue, mBfIRBuilder->MapType(objType));
  3095. auto trueBB = mBfIRBuilder->CreateBlock("check.true");
  3096. //auto falseBB = mBfIRBuilder->CreateBlock("check.false");
  3097. auto exitBB = mBfIRBuilder->CreateBlock("exit");
  3098. SizedArray<int, 8> typeMatches;
  3099. SizedArray<BfTypeInstance*, 8> exChecks;
  3100. FindSubTypes(mCurTypeInstance, &typeMatches, &exChecks, isInterfacePass);
  3101. if ((mCurTypeInstance->IsGenericTypeInstance()) && (!mCurTypeInstance->IsUnspecializedType()))
  3102. {
  3103. // Add 'unbound' type id to cast list so things like "List<int> is List<>" work
  3104. auto genericTypeInst = mCurTypeInstance->mTypeDef;
  3105. BfTypeVector genericArgs;
  3106. for (int i = 0; i < (int) genericTypeInst->mGenericParamDefs.size(); i++)
  3107. genericArgs.push_back(GetGenericParamType(BfGenericParamKind_Type, i));
  3108. auto unboundType = ResolveTypeDef(mCurTypeInstance->mTypeDef, genericArgs, BfPopulateType_Declaration);
  3109. typeMatches.push_back(unboundType->mTypeId);
  3110. }
  3111. if (mCurTypeInstance->IsBoxed())
  3112. {
  3113. BfBoxedType* boxedType = (BfBoxedType*)mCurTypeInstance;
  3114. BfTypeInstance* innerType = boxedType->mElementType;
  3115. FindSubTypes(innerType, &typeMatches, &exChecks, isInterfacePass);
  3116. if (innerType->IsTypedPrimitive())
  3117. {
  3118. auto underlyingType = innerType->GetUnderlyingType();
  3119. typeMatches.push_back(underlyingType->mTypeId);
  3120. }
  3121. auto innerTypeInst = innerType->ToTypeInstance();
  3122. if ((innerTypeInst->mTypeDef == mCompiler->mSizedArrayTypeDef) ||
  3123. (innerTypeInst->mTypeDef == mCompiler->mPointerTTypeDef) ||
  3124. (innerTypeInst->mTypeDef == mCompiler->mMethodRefTypeDef))
  3125. {
  3126. PopulateType(innerTypeInst);
  3127. //TODO: What case was this supposed to handle?
  3128. //typeMatches.push_back(innerTypeInst->mFieldInstances[0].mResolvedType->mTypeId);
  3129. }
  3130. }
  3131. auto curBlock = mBfIRBuilder->GetInsertBlock();
  3132. BfIRValue vDataPtr;
  3133. if (!exChecks.empty())
  3134. {
  3135. BfType* intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  3136. auto ptrPtrType = mBfIRBuilder->GetPointerTo(mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapType(intPtrType)));
  3137. auto vDataPtrPtr = mBfIRBuilder->CreateBitCast(thisValue, ptrPtrType);
  3138. vDataPtr = FixClassVData(mBfIRBuilder->CreateLoad(vDataPtrPtr/*, "vtable"*/));
  3139. }
  3140. auto switchStatement = mBfIRBuilder->CreateSwitch(typeIdValue, exitBB, (int)typeMatches.size() + (int)exChecks.size());
  3141. for (auto typeMatch : typeMatches)
  3142. mBfIRBuilder->AddSwitchCase(switchStatement, GetConstValue32(typeMatch), trueBB);
  3143. Array<BfIRValue> incomingFalses;
  3144. for (auto ifaceTypeInst : exChecks)
  3145. {
  3146. BfIRBlock nextBB = mBfIRBuilder->CreateBlock("exCheck", true);
  3147. mBfIRBuilder->AddSwitchCase(switchStatement, GetConstValue32(ifaceTypeInst->mTypeId), nextBB);
  3148. mBfIRBuilder->SetInsertPoint(nextBB);
  3149. BfIRValue slotOfs = GetInterfaceSlotNum(ifaceTypeInst);
  3150. auto ifacePtrPtr = mBfIRBuilder->CreateInBoundsGEP(vDataPtr, slotOfs/*, "iface"*/);
  3151. auto ifacePtr = mBfIRBuilder->CreateLoad(ifacePtrPtr);
  3152. auto cmpResult = mBfIRBuilder->CreateCmpNE(ifacePtr, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 0));
  3153. mBfIRBuilder->CreateCondBr(cmpResult, trueBB, exitBB);
  3154. incomingFalses.push_back(nextBB);
  3155. }
  3156. mBfIRBuilder->AddBlock(trueBB);
  3157. mBfIRBuilder->SetInsertPoint(trueBB);
  3158. mBfIRBuilder->CreateBr(exitBB);
  3159. mBfIRBuilder->AddBlock(exitBB);
  3160. mBfIRBuilder->SetInsertPoint(exitBB);
  3161. auto phi = mBfIRBuilder->CreatePhi(mBfIRBuilder->MapTypeInstPtr(objType), 2);
  3162. mBfIRBuilder->AddPhiIncoming(phi, thisObject, trueBB);
  3163. auto nullValue = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapTypeInstPtr(objType));
  3164. for (auto incomingFalseBlock : incomingFalses)
  3165. mBfIRBuilder->AddPhiIncoming(phi, nullValue, incomingFalseBlock);
  3166. mBfIRBuilder->AddPhiIncoming(phi, nullValue, curBlock);
  3167. mBfIRBuilder->CreateRet(phi);
  3168. mCurMethodState->mHadReturn = true;
  3169. }
  3170. void BfModule::EmitEquals(BfTypedValue leftValue, BfTypedValue rightValue, BfIRBlock exitBB)
  3171. {
  3172. BfExprEvaluator exprEvaluator(this);
  3173. exprEvaluator.mExpectingType = mCurMethodInstance->mReturnType;
  3174. exprEvaluator.PerformBinaryOperation((BfAstNode*)NULL, (BfAstNode*)NULL, BfBinaryOp_Equality, NULL, BfBinOpFlag_None, leftValue, rightValue);
  3175. BfTypedValue result = exprEvaluator.GetResult();
  3176. if (result)
  3177. {
  3178. auto nextBB = mBfIRBuilder->CreateBlock("next");
  3179. mBfIRBuilder->CreateCondBr(result.mValue, nextBB, exitBB);
  3180. mBfIRBuilder->AddBlock(nextBB);
  3181. mBfIRBuilder->SetInsertPoint(nextBB);
  3182. }
  3183. }
  3184. void BfModule::CreateFakeCallerMethod(const String& funcName)
  3185. {
  3186. BF_ASSERT(mCurMethodInstance->mIRFunction);
  3187. auto voidType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_None));
  3188. SizedArray<BfIRType, 4> paramTypes;
  3189. BfIRFunctionType funcType = mBfIRBuilder->CreateFunctionType(voidType, paramTypes);
  3190. BfIRFunction func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_Internal, "FORCELINK_" + funcName);
  3191. mBfIRBuilder->SetActiveFunction(func);
  3192. auto entryBlock = mBfIRBuilder->CreateBlock("main", true);
  3193. mBfIRBuilder->SetInsertPoint(entryBlock);
  3194. SizedArray<BfIRValue, 8> args;
  3195. BfExprEvaluator exprEvaluator(this);
  3196. if (mCurMethodInstance->HasThis())
  3197. {
  3198. auto thisValue = GetDefaultTypedValue(mCurMethodInstance->GetOwner(), true);
  3199. exprEvaluator.PushThis(NULL, thisValue, mCurMethodInstance, args);
  3200. }
  3201. for (int paramIdx = 0; paramIdx < mCurMethodInstance->GetParamCount(); paramIdx++)
  3202. {
  3203. auto paramType = mCurMethodInstance->GetParamType(paramIdx);
  3204. if (paramType->IsValuelessType())
  3205. continue;
  3206. exprEvaluator.PushArg(GetDefaultTypedValue(paramType, true), args);
  3207. }
  3208. mBfIRBuilder->CreateCall(mCurMethodInstance->mIRFunction, args);
  3209. mBfIRBuilder->CreateRetVoid();
  3210. }
  3211. void BfModule::CreateValueTypeEqualsMethod()
  3212. {
  3213. if (mCurMethodInstance->mIsUnspecialized)
  3214. return;
  3215. if (mCurTypeInstance->IsTypedPrimitive())
  3216. return;
  3217. if (mBfIRBuilder->mIgnoreWrites)
  3218. return;
  3219. BF_ASSERT(!mCurTypeInstance->IsBoxed());
  3220. auto compareType = mCurMethodInstance->mParams[0].mResolvedType;
  3221. bool isValid = true;
  3222. auto compareDType = compareType->ToDependedType();
  3223. BfTypeInstance* compareTypeInst = compareType->ToTypeInstance();
  3224. if (compareTypeInst != NULL)
  3225. {
  3226. if (compareType->IsPrimitiveType())
  3227. compareTypeInst = GetWrappedStructType(compareType);
  3228. if ((compareTypeInst == NULL) || (!compareTypeInst->IsValueType()))
  3229. {
  3230. isValid = false;
  3231. }
  3232. mBfIRBuilder->PopulateType(compareTypeInst);
  3233. }
  3234. auto boolType = GetPrimitiveType(BfTypeCode_Boolean);
  3235. if (!isValid)
  3236. {
  3237. ClearLifetimeEnds();
  3238. mBfIRBuilder->CreateRet(GetDefaultValue(boolType));
  3239. return;
  3240. }
  3241. AddDependency(compareDType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ReadFields);
  3242. auto refNode = mCurTypeInstance->mTypeDef->GetRefNode();
  3243. if (refNode == NULL)
  3244. refNode = mCompiler->mValueTypeTypeDef->GetRefNode();
  3245. UpdateSrcPos(refNode);
  3246. SetIllegalSrcPos();
  3247. auto resultVal = CreateAlloca(boolType);
  3248. mBfIRBuilder->CreateStore(GetConstValue(0, boolType), resultVal);
  3249. auto exitBB = mBfIRBuilder->CreateBlock("exit");
  3250. if (compareType->IsSizedArray())
  3251. {
  3252. auto sizedArrayType = (BfSizedArrayType*)compareType;
  3253. if (sizedArrayType->mElementCount > 6)
  3254. {
  3255. auto intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  3256. auto itr = CreateAlloca(intPtrType);
  3257. mBfIRBuilder->CreateStore(GetDefaultValue(intPtrType), itr);
  3258. auto loopBB = mBfIRBuilder->CreateBlock("loop", true);
  3259. auto bodyBB = mBfIRBuilder->CreateBlock("body", true);
  3260. auto doneBB = mBfIRBuilder->CreateBlock("done", true);
  3261. mBfIRBuilder->CreateBr(loopBB);
  3262. mBfIRBuilder->SetInsertPoint(loopBB);
  3263. auto loadedItr = mBfIRBuilder->CreateLoad(itr);
  3264. auto cmpRes = mBfIRBuilder->CreateCmpGTE(loadedItr, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, (uint64)sizedArrayType->mElementCount), true);
  3265. mBfIRBuilder->CreateCondBr(cmpRes, doneBB, bodyBB);
  3266. mBfIRBuilder->SetInsertPoint(bodyBB);
  3267. BfTypedValue leftValue = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(mCurMethodState->mLocals[0]->mValue, GetDefaultValue(intPtrType), loadedItr), sizedArrayType->mElementType, BfTypedValueKind_Addr);
  3268. BfTypedValue rightValue = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(mCurMethodState->mLocals[1]->mValue, GetDefaultValue(intPtrType), loadedItr), sizedArrayType->mElementType, BfTypedValueKind_Addr);
  3269. EmitEquals(leftValue, rightValue, exitBB);
  3270. auto incValue = mBfIRBuilder->CreateAdd(loadedItr, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 1));
  3271. mBfIRBuilder->CreateStore(incValue, itr);
  3272. mBfIRBuilder->CreateBr(loopBB);
  3273. mBfIRBuilder->SetInsertPoint(doneBB);
  3274. }
  3275. else
  3276. {
  3277. for (int dataIdx = 0; dataIdx < sizedArrayType->mElementCount; dataIdx++)
  3278. {
  3279. BfTypedValue leftValue = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(mCurMethodState->mLocals[0]->mValue, 0, dataIdx), sizedArrayType->mElementType, BfTypedValueKind_Addr);
  3280. BfTypedValue rightValue = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(mCurMethodState->mLocals[1]->mValue, 0, dataIdx), sizedArrayType->mElementType, BfTypedValueKind_Addr);
  3281. EmitEquals(leftValue, rightValue, exitBB);
  3282. }
  3283. }
  3284. }
  3285. else if (compareType->IsMethodRef())
  3286. {
  3287. auto methodRefType = (BfMethodRefType*)compareType;
  3288. BfMethodInstance* methodInstance = methodRefType->mMethodRef;
  3289. BfExprEvaluator exprEvaluator(this);
  3290. BfTypedValue leftTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[0]);
  3291. BfTypedValue rightTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  3292. // We only need to compare the 'this' capture. The rationale is that it's impossible to capture any other non-matching
  3293. // values for the same method reference -- they will always refer back to the same local variables.
  3294. int dataIdx = methodRefType->GetDataIdxFromParamIdx(-1);
  3295. if (dataIdx != -1)
  3296. {
  3297. bool failed = false;
  3298. BfTypedValue leftValue = exprEvaluator.DoImplicitArgCapture(NULL, methodInstance, methodRefType->GetParamIdxFromDataIdx(dataIdx), failed, BfImplicitParamKind_General, leftTypedVal);
  3299. BfTypedValue rightValue = exprEvaluator.DoImplicitArgCapture(NULL, methodInstance, methodRefType->GetParamIdxFromDataIdx(dataIdx), failed, BfImplicitParamKind_General, rightTypedVal);
  3300. BF_ASSERT(!failed);
  3301. EmitEquals(leftValue, rightValue, exitBB);
  3302. }
  3303. }
  3304. else if (compareTypeInst->IsEnum())
  3305. {
  3306. //auto intType = GetPrimitiveType(BfTypeCode_Int32);
  3307. BfExprEvaluator exprEvaluator(this);
  3308. BfTypedValue leftTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[0]);
  3309. BfTypedValue rightTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  3310. auto dscrType = compareTypeInst->GetDiscriminatorType();
  3311. BfTypedValue leftValue = ExtractValue(leftTypedVal, NULL, 2);
  3312. leftValue = LoadValue(leftValue);
  3313. BfTypedValue rightValue = ExtractValue(rightTypedVal, NULL, 2);
  3314. rightValue = LoadValue(rightValue);
  3315. BfTypedValue leftPayload = ExtractValue(leftTypedVal, NULL, 1);
  3316. BfTypedValue rightPayload = ExtractValue(rightTypedVal, NULL, 1);
  3317. EmitEquals(leftValue, rightValue, exitBB);
  3318. int enumCount = 0;
  3319. for (auto& fieldRef : compareTypeInst->mFieldInstances)
  3320. {
  3321. BfFieldInstance* fieldInstance = &fieldRef;
  3322. BfFieldDef* fieldDef = fieldInstance->GetFieldDef();
  3323. if ((fieldDef != NULL) && (fieldDef->IsEnumCaseEntry()))
  3324. {
  3325. enumCount = -fieldInstance->mDataIdx;
  3326. }
  3327. }
  3328. if (enumCount > 0)
  3329. {
  3330. BfIRBlock matchedBlock = mBfIRBuilder->CreateBlock("matched");
  3331. auto switchVal = mBfIRBuilder->CreateSwitch(leftValue.mValue, exitBB, enumCount);
  3332. for (auto& fieldRef : compareTypeInst->mFieldInstances)
  3333. {
  3334. BfFieldInstance* fieldInstance = &fieldRef;
  3335. BfFieldDef* fieldDef = fieldInstance->GetFieldDef();
  3336. if ((fieldDef != NULL) && (fieldDef->IsEnumCaseEntry()))
  3337. {
  3338. int enumIdx = -fieldInstance->mDataIdx - 1;
  3339. if (fieldInstance->mResolvedType->mSize == 0)
  3340. {
  3341. mBfIRBuilder->AddSwitchCase(switchVal, mBfIRBuilder->CreateConst(dscrType->mTypeDef->mTypeCode, enumIdx), matchedBlock);
  3342. }
  3343. else
  3344. {
  3345. auto caseBlock = mBfIRBuilder->CreateBlock("case", true);
  3346. mBfIRBuilder->SetInsertPoint(caseBlock);
  3347. auto tuplePtr = CreatePointerType(fieldInstance->mResolvedType);
  3348. BfTypedValue leftTuple;
  3349. BfTypedValue rightTuple;
  3350. if (leftPayload.IsAddr())
  3351. {
  3352. leftTuple = BfTypedValue(mBfIRBuilder->CreateBitCast(leftPayload.mValue, mBfIRBuilder->MapType(tuplePtr)), fieldInstance->mResolvedType, true);
  3353. rightTuple = BfTypedValue(mBfIRBuilder->CreateBitCast(rightPayload.mValue, mBfIRBuilder->MapType(tuplePtr)), fieldInstance->mResolvedType, true);
  3354. }
  3355. else
  3356. {
  3357. leftTuple = Cast(NULL, leftPayload, fieldInstance->mResolvedType, BfCastFlags_Force);
  3358. rightTuple = Cast(NULL, rightPayload, fieldInstance->mResolvedType, BfCastFlags_Force);
  3359. }
  3360. EmitEquals(leftTuple, rightTuple, exitBB);
  3361. mBfIRBuilder->CreateBr(matchedBlock);
  3362. mBfIRBuilder->AddSwitchCase(switchVal, mBfIRBuilder->CreateConst(dscrType->mTypeDef->mTypeCode, enumIdx), caseBlock);
  3363. }
  3364. }
  3365. }
  3366. mBfIRBuilder->AddBlock(matchedBlock);
  3367. mBfIRBuilder->SetInsertPoint(matchedBlock);
  3368. }
  3369. }
  3370. else if (compareTypeInst->IsUnion())
  3371. {
  3372. auto innerType = compareTypeInst->GetUnionInnerType();
  3373. if (!innerType->IsValuelessType())
  3374. {
  3375. BfExprEvaluator exprEvaluator(this);
  3376. BfTypedValue leftTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[0]);
  3377. BfTypedValue leftUnionTypedVal = ExtractValue(leftTypedVal, NULL, 1);
  3378. BfTypedValue rightTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  3379. BfTypedValue rightUnionTypedVal = ExtractValue(rightTypedVal, NULL, 1);
  3380. EmitEquals(leftUnionTypedVal, rightUnionTypedVal, exitBB);
  3381. }
  3382. }
  3383. else
  3384. {
  3385. BfExprEvaluator exprEvaluator(this);
  3386. BfTypedValue leftTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[0]);
  3387. BfTypedValue rightTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  3388. bool hadComparison = false;
  3389. for (auto& fieldRef : compareTypeInst->mFieldInstances)
  3390. {
  3391. BfFieldInstance* fieldInstance = &fieldRef;
  3392. if (fieldInstance->mDataOffset == -1)
  3393. continue;
  3394. if (fieldInstance->mResolvedType->IsValuelessType())
  3395. continue;
  3396. BfTypedValue leftValue = ExtractValue(leftTypedVal, fieldInstance, fieldInstance->mDataIdx);
  3397. BfTypedValue rightValue = ExtractValue(rightTypedVal, fieldInstance, fieldInstance->mDataIdx);
  3398. if (!fieldInstance->mResolvedType->IsComposite())
  3399. {
  3400. leftValue = LoadValue(leftValue);
  3401. rightValue = LoadValue(rightValue);
  3402. }
  3403. EmitEquals(leftValue, rightValue, exitBB);
  3404. }
  3405. auto baseTypeInst = compareTypeInst->mBaseType;
  3406. if ((baseTypeInst != NULL) && (baseTypeInst->mTypeDef != mCompiler->mValueTypeTypeDef))
  3407. {
  3408. BfTypedValue leftOrigValue(mCurMethodState->mLocals[0]->mValue, compareTypeInst, true);
  3409. BfTypedValue rightOrigValue(mCurMethodState->mLocals[1]->mValue, compareTypeInst, true);
  3410. BfTypedValue leftValue = Cast(NULL, leftOrigValue, baseTypeInst);
  3411. BfTypedValue rightValue = Cast(NULL, rightOrigValue, baseTypeInst);
  3412. EmitEquals(leftValue, rightValue, exitBB);
  3413. }
  3414. }
  3415. mBfIRBuilder->CreateStore(GetConstValue(1, boolType), resultVal);
  3416. mBfIRBuilder->CreateBr(exitBB);
  3417. mBfIRBuilder->AddBlock(exitBB);
  3418. mBfIRBuilder->SetInsertPoint(exitBB);
  3419. auto loadedResult = mBfIRBuilder->CreateLoad(resultVal);
  3420. ClearLifetimeEnds();
  3421. mBfIRBuilder->CreateRet(loadedResult);
  3422. mCurMethodState->mHadReturn = true;
  3423. }
  3424. BfIRValue BfModule::CreateClassVDataGlobal(BfTypeInstance* typeInstance, int* outNumElements, String* outMangledName)
  3425. {
  3426. if (mBfIRBuilder->mIgnoreWrites)
  3427. return mBfIRBuilder->GetFakeVal();
  3428. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  3429. BfType* classVDataType = ResolveTypeDef(mCompiler->mClassVDataTypeDef);
  3430. BfIRValue* globalVariablePtr = NULL;
  3431. mClassVDataRefs.TryGetValue(typeInstance, &globalVariablePtr);
  3432. int numElements = 1;
  3433. if ((outNumElements != NULL) || (globalVariablePtr == NULL))
  3434. {
  3435. numElements += mCompiler->mMaxInterfaceSlots;
  3436. auto maxIFaceVirtIdx = 0;
  3437. if (!typeInstance->IsInterface())
  3438. {
  3439. int dynCastDataElems = 1 + mCompiler->mMaxInterfaceSlots;
  3440. numElements += ((dynCastDataElems * 4) + mSystem->mPtrSize - 1) / mSystem->mPtrSize;
  3441. numElements += typeInstance->GetOrigVTableSize();
  3442. int ifaceMethodLen = typeInstance->GetIFaceVMethodSize();
  3443. if (typeInstance->mHotTypeData != NULL)
  3444. {
  3445. if (typeInstance->mHotTypeData->mOrigInterfaceMethodsLength != -1)
  3446. ifaceMethodLen = typeInstance->mHotTypeData->mOrigInterfaceMethodsLength;
  3447. }
  3448. numElements += ifaceMethodLen;
  3449. }
  3450. if (outNumElements != NULL)
  3451. *outNumElements = numElements;
  3452. }
  3453. StringT<128> classVDataName;
  3454. String memberName = "sBfClassVData";
  3455. if ((typeInstance->mHotTypeData != NULL) && ((typeInstance->mHotTypeData->mHadDataChange) || (typeInstance->mHotTypeData->mPendingDataChange)))
  3456. {
  3457. auto curVersion = typeInstance->mHotTypeData->GetLatestVersion();
  3458. memberName += "_";
  3459. memberName += BfTypeUtils::HashEncode64(curVersion->mDataHash.mLow);
  3460. memberName += BfTypeUtils::HashEncode64(curVersion->mDataHash.mHigh);
  3461. }
  3462. BfMangler::MangleStaticFieldName(classVDataName, mCompiler->GetMangleKind(), typeInstance, memberName, classVDataType);
  3463. if (outMangledName != NULL)
  3464. *outMangledName = classVDataName;
  3465. /*if (itr != mClassVDataRefs.end())
  3466. {
  3467. globalVariable = itr->second;
  3468. }*/
  3469. BfIRValue globalVariable;
  3470. if (globalVariablePtr != NULL)
  3471. {
  3472. globalVariable = *globalVariablePtr;
  3473. }
  3474. else
  3475. {
  3476. BfLogSysM("Creating VData %s\n", classVDataName.c_str());
  3477. auto arrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr), numElements);
  3478. globalVariable = mBfIRBuilder->CreateGlobalVariable(
  3479. arrayType,
  3480. true,
  3481. BfIRLinkageType_External,
  3482. BfIRValue(),
  3483. classVDataName);
  3484. mClassVDataRefs[typeInstance] = globalVariable;
  3485. }
  3486. return globalVariable;
  3487. }
  3488. BfIRValue BfModule::GetClassVDataPtr(BfTypeInstance* typeInstance)
  3489. {
  3490. auto classVDataType = ResolveTypeDef(mCompiler->mClassVDataTypeDef);
  3491. return mBfIRBuilder->CreateBitCast(CreateClassVDataGlobal(typeInstance), mBfIRBuilder->MapType(CreatePointerType(classVDataType)));
  3492. }
  3493. BfIRValue BfModule::CreateClassVDataExtGlobal(BfTypeInstance* declTypeInst, BfTypeInstance* implTypeInst, int startVirtIdx)
  3494. {
  3495. if (mBfIRBuilder->mIgnoreWrites)
  3496. return mBfIRBuilder->GetFakeVal();
  3497. int numElements = declTypeInst->GetSelfVTableSize() - declTypeInst->GetOrigSelfVTableSize();
  3498. BF_ASSERT(numElements >= 0);
  3499. if (numElements <= 0)
  3500. return BfIRValue();
  3501. BF_ASSERT(implTypeInst->mVirtualMethodTable[startVirtIdx].mDeclaringMethod.mMethodNum == -1);
  3502. BF_ASSERT(implTypeInst->mVirtualMethodTable[startVirtIdx].mDeclaringMethod.mTypeInstance == declTypeInst);
  3503. if (declTypeInst->mInheritDepth == implTypeInst->mInheritDepth)
  3504. BF_ASSERT(declTypeInst == implTypeInst);
  3505. else
  3506. BF_ASSERT(implTypeInst->mInheritDepth > declTypeInst->mInheritDepth);
  3507. if (declTypeInst != implTypeInst)
  3508. {
  3509. BfTypeInstance* highestImpl = declTypeInst;
  3510. for (int virtIdx = startVirtIdx + 1; virtIdx < (int)declTypeInst->mVirtualMethodTable.size(); virtIdx++)
  3511. {
  3512. if (implTypeInst->mVirtualMethodTable[virtIdx].mDeclaringMethod.mMethodNum == -1)
  3513. break; // Start of an ext entry for another type
  3514. auto checkImplTypeInst = implTypeInst->mVirtualMethodTable[virtIdx].mImplementingMethod.mTypeInstance;
  3515. if ((checkImplTypeInst != NULL) && (checkImplTypeInst->mInheritDepth > highestImpl->mInheritDepth))
  3516. highestImpl = checkImplTypeInst;
  3517. }
  3518. if (highestImpl != implTypeInst)
  3519. return CreateClassVDataExtGlobal(declTypeInst, highestImpl, startVirtIdx);
  3520. }
  3521. BfVDataExtEntry mapEntry;
  3522. mapEntry.mDeclTypeInst = declTypeInst;
  3523. mapEntry.mImplTypeInst = implTypeInst;
  3524. BfIRValue* irValuePtr = NULL;
  3525. if (mClassVDataExtRefs.TryGetValue(mapEntry, &irValuePtr))
  3526. return *irValuePtr;
  3527. PopulateType(declTypeInst, BfPopulateType_DataAndMethods);
  3528. PopulateType(implTypeInst, BfPopulateType_DataAndMethods);
  3529. StringT<128> classVDataName;
  3530. BfMangler::MangleStaticFieldName(classVDataName, mCompiler->GetMangleKind(), implTypeInst, "bf_hs_replace_VDataExt");
  3531. if (declTypeInst != implTypeInst)
  3532. {
  3533. classVDataName += StrFormat("_%d", implTypeInst->mInheritDepth - declTypeInst->mInheritDepth);
  3534. }
  3535. auto voidPtrType = GetPrimitiveType(BfTypeCode_NullPtr);
  3536. auto voidPtrIRType = mBfIRBuilder->MapType(voidPtrType);
  3537. SizedArray<BfIRValue, 32> vData;
  3538. auto voidPtrNull = GetDefaultValue(voidPtrType);
  3539. for (int virtIdx = startVirtIdx + declTypeInst->GetOrigSelfVTableSize(); virtIdx < (int)declTypeInst->mVirtualMethodTable.size(); virtIdx++)
  3540. {
  3541. if (implTypeInst->mVirtualMethodTable[virtIdx].mDeclaringMethod.mMethodNum == -1)
  3542. break; // Start of an ext entry for another type
  3543. BfIRValue vValue;
  3544. auto& entry = implTypeInst->mVirtualMethodTable[virtIdx];
  3545. BfMethodInstance* declaringMethodInstance = (BfMethodInstance*)entry.mDeclaringMethod;
  3546. if ((declaringMethodInstance != NULL) && (declaringMethodInstance->mMethodInstanceGroup->IsImplemented()) && (declaringMethodInstance->mIsReified))
  3547. {
  3548. BF_ASSERT(entry.mImplementingMethod.mTypeInstance->mMethodInstanceGroups[entry.mImplementingMethod.mMethodNum].IsImplemented());
  3549. BF_ASSERT(entry.mImplementingMethod.mTypeInstance->mMethodInstanceGroups[entry.mImplementingMethod.mMethodNum].mDefault->mIsReified);
  3550. BfMethodInstance* methodInstance = (BfMethodInstance*)entry.mImplementingMethod;
  3551. if ((methodInstance != NULL) && (!methodInstance->mMethodDef->mIsAbstract))
  3552. {
  3553. BF_ASSERT(implTypeInst->IsTypeMemberAccessible(methodInstance->mMethodDef->mDeclaringType, mProject));
  3554. auto moduleMethodInst = GetMethodInstanceAtIdx(methodInstance->mMethodInstanceGroup->mOwner, methodInstance->mMethodInstanceGroup->mMethodIdx);
  3555. auto funcPtr = mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, voidPtrIRType);
  3556. vValue = funcPtr;
  3557. }
  3558. }
  3559. if (!vValue)
  3560. vValue = voidPtrNull;
  3561. vData.Add(vValue);
  3562. }
  3563. BF_ASSERT((int)vData.size() == numElements);
  3564. BfLogSysM("Creating VDataExt %s\n", classVDataName.c_str());
  3565. auto arrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr), numElements);
  3566. auto globalVariable = mBfIRBuilder->CreateGlobalVariable(arrayType, true,
  3567. BfIRLinkageType_External, BfIRValue(), classVDataName);
  3568. BfIRType extVTableType = mBfIRBuilder->GetSizedArrayType(voidPtrIRType, (int)vData.size());
  3569. BfIRValue extVTableConst = mBfIRBuilder->CreateConstArray(extVTableType, vData);
  3570. mBfIRBuilder->GlobalVar_SetInitializer(globalVariable, extVTableConst);
  3571. mClassVDataExtRefs[mapEntry] = globalVariable;
  3572. return globalVariable;
  3573. }
  3574. BfIRValue BfModule::CreateTypeDataRef(BfType* type)
  3575. {
  3576. if (mBfIRBuilder->mIgnoreWrites)
  3577. {
  3578. return mBfIRBuilder->CreateTypeOf(type);
  3579. }
  3580. BfIRValue globalVariable;
  3581. BfIRValue* globalVariablePtr = NULL;
  3582. if (mTypeDataRefs.TryGetValue(type, &globalVariablePtr))
  3583. {
  3584. globalVariable = *globalVariablePtr;
  3585. if (globalVariable)
  3586. return globalVariable;
  3587. }
  3588. auto typeTypeDef = ResolveTypeDef(mCompiler->mTypeTypeDef);
  3589. auto typeTypeInst = typeTypeDef->ToTypeInstance();
  3590. auto typeInstance = type->ToTypeInstance();
  3591. StringT<128> typeDataName;
  3592. if (typeInstance != NULL)
  3593. {
  3594. BfMangler::MangleStaticFieldName(typeDataName, mCompiler->GetMangleKind(), typeInstance, "sBfTypeData");
  3595. }
  3596. else
  3597. {
  3598. typeDataName += "sBfTypeData.";
  3599. BfMangler::Mangle(typeDataName, mCompiler->GetMangleKind(), type);
  3600. }
  3601. BfLogSysM("Creating TypeData %s\n", typeDataName.c_str());
  3602. globalVariable = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapTypeInst(typeTypeInst, BfIRPopulateType_Full), true, BfIRLinkageType_External, BfIRValue(), typeDataName);
  3603. mTypeDataRefs[type] = globalVariable;
  3604. return globalVariable;
  3605. }
  3606. BfIRValue BfModule::CreateTypeData(BfType* type, Dictionary<int, int>& usedStringIdMap, bool forceReflectFields, bool needsTypeData, bool needsTypeNames, bool needsVData)
  3607. {
  3608. if ((mCompiler->IsHotCompile()) && (!type->mDirty))
  3609. return BfIRValue();
  3610. BfIRValue* irValuePtr = NULL;
  3611. if (mTypeDataRefs.TryGetValue(type, &irValuePtr))
  3612. {
  3613. return *irValuePtr;
  3614. }
  3615. BfTypeInstance* typeInstance = type->ToTypeInstance();
  3616. BfType* typeInstanceType = ResolveTypeDef(mCompiler->mReflectTypeInstanceTypeDef);
  3617. mBfIRBuilder->PopulateType(typeInstanceType, BfIRPopulateType_Full_ForceDefinition);
  3618. if (typeInstanceType == NULL)
  3619. {
  3620. AssertErrorState();
  3621. return BfIRValue();
  3622. }
  3623. BfIRValue typeTypeData;
  3624. int typeFlags = 0;
  3625. if (needsTypeData)
  3626. {
  3627. BfTypeInstance* typeInstanceTypeInstance = typeInstanceType->ToTypeInstance();
  3628. BfTypeInstance* typeDataSource = NULL;
  3629. if (typeInstance != NULL)
  3630. {
  3631. if (typeInstance->IsUnspecializedType())
  3632. {
  3633. typeDataSource = ResolveTypeDef(mCompiler->mReflectUnspecializedGenericType)->ToTypeInstance();
  3634. typeFlags |= BfTypeFlags_UnspecializedGeneric;
  3635. }
  3636. else if (typeInstance->IsArray())
  3637. {
  3638. typeDataSource = ResolveTypeDef(mCompiler->mReflectArrayType)->ToTypeInstance();
  3639. typeFlags |= BfTypeFlags_Array;
  3640. }
  3641. else if (typeInstance->IsGenericTypeInstance())
  3642. {
  3643. typeDataSource = ResolveTypeDef(mCompiler->mReflectSpecializedGenericType)->ToTypeInstance();
  3644. typeFlags |= BfTypeFlags_SpecializedGeneric;
  3645. }
  3646. else
  3647. typeDataSource = typeInstanceTypeInstance;
  3648. }
  3649. else if (type->IsPointer())
  3650. typeDataSource = ResolveTypeDef(mCompiler->mReflectPointerType)->ToTypeInstance();
  3651. else if (type->IsSizedArray())
  3652. typeDataSource = ResolveTypeDef(mCompiler->mReflectSizedArrayType)->ToTypeInstance();
  3653. else
  3654. typeDataSource = mContext->mBfTypeType;
  3655. if ((!mTypeDataRefs.ContainsKey(typeDataSource)) && (typeDataSource != type))
  3656. {
  3657. CreateTypeData(typeDataSource, usedStringIdMap, false, true, needsTypeNames, true);
  3658. }
  3659. typeTypeData = CreateClassVDataGlobal(typeDataSource);
  3660. }
  3661. else
  3662. typeTypeData = CreateClassVDataGlobal(typeInstanceType->ToTypeInstance());
  3663. BfType* longType = GetPrimitiveType(BfTypeCode_Int64);
  3664. BfType* intType = GetPrimitiveType(BfTypeCode_Int32);
  3665. BfType* shortType = GetPrimitiveType(BfTypeCode_Int16);
  3666. BfType* byteType = GetPrimitiveType(BfTypeCode_Int8);
  3667. BfType* typeIdType = intType;
  3668. auto voidPtrType = GetPrimitiveType(BfTypeCode_NullPtr);
  3669. auto voidPtrIRType = mBfIRBuilder->MapType(voidPtrType);
  3670. auto voidPtrPtrIRType = mBfIRBuilder->GetPointerTo(voidPtrIRType);
  3671. auto voidPtrNull = GetDefaultValue(voidPtrType);
  3672. SizedArray<BfIRValue, 4> typeValueParams;
  3673. GetConstClassValueParam(typeTypeData, typeValueParams);
  3674. BfIRValue objectData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(mContext->mBfObjectType, BfIRPopulateType_Full), typeValueParams);
  3675. StringT<128> typeDataName;
  3676. if ((typeInstance != NULL) && (!typeInstance->IsTypeAlias()))
  3677. {
  3678. BfMangler::MangleStaticFieldName(typeDataName, mCompiler->GetMangleKind(), typeInstance, "sBfTypeData");
  3679. if (typeInstance->mTypeDef->IsGlobalsContainer())
  3680. typeDataName += "`G`" + typeInstance->mTypeDef->mProject->mName;
  3681. }
  3682. else
  3683. {
  3684. typeDataName += "sBfTypeData.";
  3685. BfMangler::Mangle(typeDataName, mCompiler->GetMangleKind(), type, mContext->mScratchModule);
  3686. }
  3687. int typeCode = BfTypeCode_None;
  3688. if (typeInstance != NULL)
  3689. {
  3690. typeCode = typeInstance->mTypeDef->mTypeCode;
  3691. }
  3692. else if (type->IsPrimitiveType())
  3693. {
  3694. BfPrimitiveType* primType = (BfPrimitiveType*)type;
  3695. typeCode = primType->mTypeDef->mTypeCode;
  3696. }
  3697. else if (type->IsPointer())
  3698. {
  3699. typeCode = BfTypeCode_Pointer;
  3700. typeFlags |= BfTypeFlags_Pointer;
  3701. }
  3702. if (type->IsObject())
  3703. {
  3704. typeFlags |= BfTypeFlags_Object;
  3705. BfMethodInstance* methodInstance = typeInstance->mVirtualMethodTable[mCompiler->GetVTableMethodOffset() + 0].mImplementingMethod;
  3706. if (methodInstance->GetOwner() != mContext->mBfObjectType)
  3707. typeFlags |= BfTypeFlags_HasDestructor;
  3708. }
  3709. if (type->IsStruct())
  3710. typeFlags |= BfTypeFlags_Struct;
  3711. if (type->IsBoxed())
  3712. {
  3713. typeFlags |= BfTypeFlags_Boxed;
  3714. if (((BfBoxedType*)type)->IsBoxedStructPtr())
  3715. typeFlags |= BfTypeFlags_Pointer;
  3716. }
  3717. if (type->IsPrimitiveType())
  3718. typeFlags |= BfTypeFlags_Primitive;
  3719. if (type->IsTypedPrimitive())
  3720. typeFlags |= BfTypeFlags_TypedPrimitive;
  3721. if (type->IsTuple())
  3722. typeFlags |= BfTypeFlags_Tuple;
  3723. if (type->IsNullable())
  3724. typeFlags |= BfTypeFlags_Nullable;
  3725. if (type->IsSizedArray())
  3726. typeFlags |= BfTypeFlags_SizedArray;
  3727. if (type->IsSplattable())
  3728. typeFlags |= BfTypeFlags_Splattable;
  3729. if (type->IsUnion())
  3730. typeFlags |= BfTypeFlags_Union;
  3731. if (type->IsDelegate())
  3732. typeFlags |= BfTypeFlags_Delegate;
  3733. if (type->WantsGCMarking())
  3734. typeFlags |= BfTypeFlags_WantsMarking;
  3735. int memberDataOffset = 0;
  3736. if (typeInstance != NULL)
  3737. {
  3738. for (auto& fieldInstance : typeInstance->mFieldInstances)
  3739. {
  3740. if (fieldInstance.mDataOffset != -1)
  3741. {
  3742. memberDataOffset = fieldInstance.mDataOffset;
  3743. break;
  3744. }
  3745. }
  3746. }
  3747. SizedArray<BfIRValue, 8> typeDataParams =
  3748. {
  3749. objectData,
  3750. GetConstValue(type->mSize, intType), // mSize
  3751. GetConstValue(type->mTypeId, typeIdType), // mTypeId
  3752. GetConstValue(typeFlags, intType), // mTypeFlags
  3753. GetConstValue(memberDataOffset, intType), // mMemberDataOffset
  3754. GetConstValue(typeCode, byteType), // mTypeCode
  3755. GetConstValue(type->mAlign, byteType),
  3756. };
  3757. auto typeData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(mContext->mBfTypeType, BfIRPopulateType_Full), typeDataParams);
  3758. if (typeInstance == NULL)
  3759. {
  3760. BfIRValue typeDataVar;
  3761. if (needsTypeData)
  3762. {
  3763. if (type->IsPointer())
  3764. {
  3765. auto pointerType = (BfPointerType*)type;
  3766. SizedArray<BfIRValue, 3> pointerTypeDataParms =
  3767. {
  3768. typeData,
  3769. GetConstValue(pointerType->mElementType->mTypeId, typeIdType),
  3770. };
  3771. auto reflectPointerType = ResolveTypeDef(mCompiler->mReflectPointerType)->ToTypeInstance();
  3772. auto pointerTypeData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(reflectPointerType, BfIRPopulateType_Full), pointerTypeDataParms);
  3773. typeDataVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapTypeInst(reflectPointerType), true,
  3774. BfIRLinkageType_External, pointerTypeData, typeDataName);
  3775. typeDataVar = mBfIRBuilder->CreateBitCast(typeDataVar, mBfIRBuilder->MapType(mContext->mBfTypeType));
  3776. }
  3777. else if (type->IsSizedArray())
  3778. {
  3779. auto sizedArrayType = (BfSizedArrayType*)type;
  3780. SizedArray<BfIRValue, 3> sizedArrayTypeDataParms =
  3781. {
  3782. typeData,
  3783. GetConstValue(sizedArrayType->mElementType->mTypeId, typeIdType),
  3784. GetConstValue(sizedArrayType->mElementCount, intType)
  3785. };
  3786. auto reflectSizedArrayType = ResolveTypeDef(mCompiler->mReflectSizedArrayType)->ToTypeInstance();
  3787. auto sizedArrayTypeData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(reflectSizedArrayType, BfIRPopulateType_Full), sizedArrayTypeDataParms);
  3788. typeDataVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapTypeInst(reflectSizedArrayType), true,
  3789. BfIRLinkageType_External, sizedArrayTypeData, typeDataName);
  3790. typeDataVar = mBfIRBuilder->CreateBitCast(typeDataVar, mBfIRBuilder->MapType(mContext->mBfTypeType));
  3791. }
  3792. else
  3793. {
  3794. typeDataVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapTypeInst(mContext->mBfTypeType), true,
  3795. BfIRLinkageType_External, typeData, typeDataName);
  3796. }
  3797. }
  3798. else
  3799. typeDataVar = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(mContext->mBfTypeType));
  3800. mTypeDataRefs[typeInstance] = typeDataVar;
  3801. return typeDataVar;
  3802. }
  3803. // Reserve position
  3804. mTypeDataRefs[typeInstance] = BfIRValue();
  3805. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  3806. BfTypeDef* typeDef = typeInstance->mTypeDef;
  3807. StringT<128> mangledName;
  3808. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), typeInstance, typeInstance->mModule);
  3809. for (int methodIdx = 0; methodIdx < (int)typeDef->mMethods.size(); methodIdx++)
  3810. {
  3811. auto methodDef = typeDef->mMethods[methodIdx];
  3812. auto methodInstance = typeInstance->mMethodInstanceGroups[methodIdx].mDefault;
  3813. if (methodInstance == NULL)
  3814. continue;
  3815. if (typeInstance->IsUnspecializedType())
  3816. continue;
  3817. if (!typeInstance->IsTypeMemberAccessible(methodDef->mDeclaringType, mProject))
  3818. {
  3819. if (methodInstance->mChainType == BfMethodChainType_ChainMember)
  3820. {
  3821. BF_ASSERT(!methodInstance->GetOwner()->IsUnspecializedType());
  3822. // We need to create an empty thunk for this chained method
  3823. BfIRFunction func = CreateFunctionFrom(methodInstance, false, methodInstance->mAlwaysInline);
  3824. mBfIRBuilder->SetActiveFunction(func);
  3825. auto block = mBfIRBuilder->CreateBlock("entry", true);
  3826. mBfIRBuilder->SetInsertPoint(block);
  3827. mBfIRBuilder->CreateRetVoid();
  3828. mBfIRBuilder->SetActiveFunction(BfIRFunction());
  3829. }
  3830. }
  3831. }
  3832. SizedArray<BfIRValue, 32> vData;
  3833. BfIRValue classVDataVar;
  3834. String classVDataName;
  3835. if (typeInstance->mSlotNum >= 0)
  3836. {
  3837. // For interfaces we ONLY emit the slot num
  3838. int virtSlotIdx = typeInstance->mSlotNum + 1 + mCompiler->GetDynCastVDataCount();
  3839. StringT<128> slotVarName;
  3840. BfMangler::MangleStaticFieldName(slotVarName, mCompiler->GetMangleKind(), typeInstance, "sBfSlotOfs");
  3841. auto intType = GetPrimitiveType(BfTypeCode_Int32);
  3842. auto slotNumVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapType(intType), true, BfIRLinkageType_External,
  3843. GetConstValue32(virtSlotIdx), slotVarName);
  3844. }
  3845. else if ((typeInstance->IsObject()) && (!typeInstance->IsUnspecializedType()) && (needsVData))
  3846. {
  3847. int dynCastDataElems = 0;
  3848. int numElements = 1;
  3849. int vDataOfs = 1; // The number of intptrs before the iface slot map
  3850. numElements += mCompiler->mMaxInterfaceSlots;
  3851. if (!typeInstance->IsInterface())
  3852. {
  3853. dynCastDataElems = 1 + mCompiler->mMaxInterfaceSlots;
  3854. numElements += mCompiler->GetDynCastVDataCount();
  3855. numElements += typeInstance->mVirtualMethodTableSize;
  3856. }
  3857. int expectNumElements = 0;
  3858. if (!typeDef->mIsStatic)
  3859. {
  3860. classVDataVar = CreateClassVDataGlobal(typeInstance, &expectNumElements, &classVDataName);
  3861. }
  3862. vData.push_back(BfIRValue()); // Type*
  3863. SizedArray<BfIRValue, 1> extVTableData;
  3864. SizedArrayImpl<BfIRValue>* vFuncDataExt = &extVTableData;
  3865. if (!typeInstance->IsInterface())
  3866. {
  3867. Array<int32> dynCastData;
  3868. if (typeInstance->IsBoxed())
  3869. {
  3870. auto underlyingType = typeInstance->GetUnderlyingType()->ToTypeInstance();
  3871. dynCastData.Add(underlyingType->mInheritanceId);
  3872. }
  3873. else
  3874. dynCastData.Add(typeInstance->mInheritanceId);
  3875. for (int i = 0; i < mCompiler->mMaxInterfaceSlots; i++)
  3876. dynCastData.Add(0);
  3877. dynCastData.Add(0);
  3878. auto checkTypeInst = typeInstance;
  3879. while (checkTypeInst != NULL)
  3880. {
  3881. for (auto&& interfaceEntry : checkTypeInst->mInterfaces)
  3882. {
  3883. if (interfaceEntry.mInterfaceType->mSlotNum >= 0)
  3884. {
  3885. if (dynCastData[interfaceEntry.mInterfaceType->mSlotNum + 1] == 0)
  3886. dynCastData[interfaceEntry.mInterfaceType->mSlotNum + 1] = interfaceEntry.mInterfaceType->mTypeId;
  3887. }
  3888. }
  3889. checkTypeInst = checkTypeInst->GetImplBaseType();
  3890. }
  3891. if (mSystem->mPtrSize == 8)
  3892. {
  3893. int intPtrCount = (dynCastDataElems + 1) / 2;
  3894. vDataOfs += intPtrCount;
  3895. uint64* intPtrData = (uint64*)&dynCastData[0];
  3896. for (int i = 0; i < intPtrCount; i++)
  3897. {
  3898. uint64 val = intPtrData[i];
  3899. if (val == 0)
  3900. {
  3901. vData.push_back(voidPtrNull);
  3902. }
  3903. else
  3904. {
  3905. auto intPtrVal = mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, val);
  3906. vData.push_back(mBfIRBuilder->CreateBitCast(intPtrVal, voidPtrIRType));
  3907. }
  3908. }
  3909. }
  3910. else
  3911. {
  3912. int intPtrCount = dynCastDataElems;
  3913. vDataOfs += intPtrCount;
  3914. uint32* intPtrData = (uint32*)&dynCastData[0];
  3915. for (int i = 0; i < intPtrCount; i++)
  3916. {
  3917. uint32 val = intPtrData[i];
  3918. if (val == 0)
  3919. {
  3920. vData.push_back(voidPtrNull);
  3921. }
  3922. else
  3923. {
  3924. auto intPtrVal = mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, (int)val);
  3925. vData.push_back(mBfIRBuilder->CreateBitCast(intPtrVal, voidPtrIRType));
  3926. }
  3927. }
  3928. }
  3929. }
  3930. for (int iSlotIdx = 0; iSlotIdx < mCompiler->mMaxInterfaceSlots; iSlotIdx++)
  3931. vData.push_back(voidPtrNull);
  3932. struct _InterfaceMatchEntry
  3933. {
  3934. BfTypeInterfaceEntry* mEntry;
  3935. BfTypeInstance* mEntrySource;
  3936. Array<BfTypeInterfaceEntry*> mAmbiguousEntries;
  3937. };
  3938. int highestIFaceVirtIdx = 0;
  3939. Dictionary<BfTypeInstance*, _InterfaceMatchEntry> interfaceMap;
  3940. auto checkTypeInst = typeInstance;
  3941. bool forceInterfaceSet = false;
  3942. while (checkTypeInst != NULL)
  3943. {
  3944. for (auto&& interfaceEntry : checkTypeInst->mInterfaces)
  3945. {
  3946. highestIFaceVirtIdx = BF_MAX(highestIFaceVirtIdx, interfaceEntry.mStartVirtualIdx + interfaceEntry.mInterfaceType->mVirtualMethodTableSize);
  3947. if (!typeInstance->IsTypeMemberAccessible(interfaceEntry.mDeclaringType, mProject))
  3948. continue;
  3949. _InterfaceMatchEntry* matchEntry = NULL;
  3950. if (interfaceMap.TryGetValue(interfaceEntry.mInterfaceType, &matchEntry))
  3951. {
  3952. auto prevEntry = matchEntry->mEntry;
  3953. bool isBetter = TypeIsSubTypeOf(checkTypeInst, matchEntry->mEntrySource);
  3954. bool isWorse = TypeIsSubTypeOf(matchEntry->mEntrySource, checkTypeInst);
  3955. if (forceInterfaceSet)
  3956. {
  3957. isBetter = true;
  3958. isWorse = false;
  3959. }
  3960. if (isBetter == isWorse)
  3961. CompareDeclTypes(interfaceEntry.mDeclaringType, prevEntry->mDeclaringType, isBetter, isWorse);
  3962. if (isBetter == isWorse)
  3963. {
  3964. if (matchEntry->mAmbiguousEntries.empty())
  3965. matchEntry->mAmbiguousEntries.push_back(prevEntry);
  3966. matchEntry->mAmbiguousEntries.push_back(&interfaceEntry);
  3967. continue;
  3968. }
  3969. else if (isBetter)
  3970. {
  3971. matchEntry->mEntry = &interfaceEntry;
  3972. matchEntry->mEntrySource = checkTypeInst;
  3973. matchEntry->mAmbiguousEntries.Clear();
  3974. }
  3975. else
  3976. continue;
  3977. }
  3978. else
  3979. {
  3980. _InterfaceMatchEntry matchEntry;
  3981. matchEntry.mEntry = &interfaceEntry;
  3982. matchEntry.mEntrySource = checkTypeInst;
  3983. interfaceMap[interfaceEntry.mInterfaceType] = matchEntry;
  3984. }
  3985. }
  3986. checkTypeInst = checkTypeInst->GetImplBaseType();
  3987. }
  3988. for (auto interfacePair : interfaceMap)
  3989. {
  3990. auto& interfaceMatchEntry = interfacePair.mValue;
  3991. if (!interfaceMatchEntry.mAmbiguousEntries.empty())
  3992. {
  3993. 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());
  3994. if (error != NULL)
  3995. {
  3996. for (auto ambiguiousEntry : interfaceMatchEntry.mAmbiguousEntries)
  3997. mCompiler->mPassInstance->MoreInfo("See other declaration", ambiguiousEntry->mDeclaringType->GetRefNode());
  3998. }
  3999. }
  4000. }
  4001. if ((!typeInstance->IsInterface()) && (typeInstance->mVirtualMethodTableSize > 0) && (needsVData))
  4002. {
  4003. int startTabIdx = (int)vData.size();
  4004. SizedArray<BfTypeInstance*, 8> origVirtTypeStack;
  4005. BfTypeInstance* checkTypeInst = typeInstance;
  4006. while (checkTypeInst != NULL)
  4007. {
  4008. origVirtTypeStack.push_back(checkTypeInst);
  4009. checkTypeInst = checkTypeInst->GetImplBaseType();
  4010. }
  4011. Array<BfVirtualMethodEntry> origVTable;
  4012. int origVirtIdx = 0;
  4013. if (typeInstance->mTypeDef->mIsCombinedPartial)
  4014. {
  4015. HashSet<String> reslotNames;
  4016. for (int virtIdx = 0; virtIdx < (int)typeInstance->mVirtualMethodTable.size(); virtIdx++)
  4017. {
  4018. auto& entry = typeInstance->mVirtualMethodTable[virtIdx];
  4019. if (entry.mDeclaringMethod.mMethodNum == -1)
  4020. continue;
  4021. BfMethodInstance* methodInstance = (BfMethodInstance*)entry.mImplementingMethod;
  4022. if ((methodInstance == NULL) || (!typeInstance->IsTypeMemberAccessible(methodInstance->mMethodDef->mDeclaringType, mProject)))
  4023. {
  4024. if (origVTable.empty())
  4025. origVTable = typeInstance->mVirtualMethodTable;
  4026. BfMethodInstance* declMethodInstance = entry.mDeclaringMethod;
  4027. if (typeInstance->IsTypeMemberAccessible(declMethodInstance->mMethodDef->mDeclaringType, mProject))
  4028. {
  4029. // Prepare to reslot...
  4030. entry.mImplementingMethod = entry.mDeclaringMethod;
  4031. reslotNames.Add(declMethodInstance->mMethodDef->mName);
  4032. }
  4033. else
  4034. {
  4035. // Decl isn't accessible, null out entry
  4036. entry.mImplementingMethod = BfMethodRef();
  4037. }
  4038. }
  4039. }
  4040. if (!reslotNames.IsEmpty())
  4041. {
  4042. BfAmbiguityContext ambiguityContext;
  4043. ambiguityContext.mTypeInstance = typeInstance;
  4044. ambiguityContext.mModule = this;
  4045. ambiguityContext.mIsProjectSpecific = true;
  4046. ambiguityContext.mIsReslotting = true;
  4047. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  4048. for (auto& methodGroup : typeInstance->mMethodInstanceGroups)
  4049. {
  4050. auto methodInstance = methodGroup.mDefault;
  4051. if ((methodInstance == NULL) || (!methodInstance->mMethodDef->mIsOverride))
  4052. continue;
  4053. if (!reslotNames.Contains(methodInstance->mMethodDef->mName))
  4054. continue;
  4055. if (!typeInstance->IsTypeMemberAccessible(methodInstance->mMethodDef->mDeclaringType, mProject))
  4056. continue;
  4057. if ((methodInstance->mChainType != BfMethodChainType_None) && (methodInstance->mChainType != BfMethodChainType_ChainHead))
  4058. continue;
  4059. SlotVirtualMethod(methodInstance, &ambiguityContext);
  4060. }
  4061. ambiguityContext.Finish();
  4062. }
  4063. }
  4064. bool isInExts = false;
  4065. for (int virtIdx = 0; virtIdx < (int)typeInstance->mVirtualMethodTable.size(); virtIdx++)
  4066. {
  4067. BfIRValue vValue = voidPtrNull;
  4068. auto& entry = typeInstance->mVirtualMethodTable[virtIdx];
  4069. BfModuleMethodInstance moduleMethodInst;
  4070. if (entry.mDeclaringMethod.mMethodNum == -1)
  4071. {
  4072. // mMethodNum of -1 indicates a vExt slot rather than an actual method reference
  4073. isInExts = true;
  4074. BfIRValue vExt = CreateClassVDataExtGlobal(entry.mDeclaringMethod.mTypeInstance, typeInstance, virtIdx);
  4075. if (vExt)
  4076. vValue = mBfIRBuilder->CreateBitCast(vExt, voidPtrIRType);
  4077. }
  4078. else
  4079. {
  4080. BfMethodInstance* declaringMethodInstance = (BfMethodInstance*)entry.mDeclaringMethod;
  4081. if ((declaringMethodInstance != NULL) && (declaringMethodInstance->mMethodInstanceGroup->IsImplemented()) && (declaringMethodInstance->mIsReified))
  4082. {
  4083. BF_ASSERT(entry.mImplementingMethod.mTypeInstance->mMethodInstanceGroups[entry.mImplementingMethod.mMethodNum].IsImplemented());
  4084. BF_ASSERT(entry.mImplementingMethod.mTypeInstance->mMethodInstanceGroups[entry.mImplementingMethod.mMethodNum].mDefault->mIsReified);
  4085. BfMethodInstance* methodInstance = (BfMethodInstance*)entry.mImplementingMethod;
  4086. if ((methodInstance != NULL) && (!methodInstance->mMethodDef->mIsAbstract))
  4087. {
  4088. BF_ASSERT(typeInstance->IsTypeMemberAccessible(methodInstance->mMethodDef->mDeclaringType, mProject));
  4089. moduleMethodInst = GetMethodInstanceAtIdx(methodInstance->mMethodInstanceGroup->mOwner, methodInstance->mMethodInstanceGroup->mMethodIdx);
  4090. auto funcPtr = mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, voidPtrIRType);
  4091. vValue = funcPtr;
  4092. }
  4093. }
  4094. }
  4095. while (origVirtTypeStack.size() != 0)
  4096. {
  4097. BfTypeInstance* useTypeInst = origVirtTypeStack[origVirtTypeStack.size() - 1];
  4098. if (virtIdx >= useTypeInst->mVirtualMethodTableSize)
  4099. {
  4100. // Moved past current base vtable size
  4101. origVirtTypeStack.pop_back();
  4102. continue;
  4103. }
  4104. if (origVirtIdx < useTypeInst->GetOrigVTableSize())
  4105. {
  4106. // We are within the original vtable size
  4107. int idx = startTabIdx + origVirtIdx;
  4108. origVirtIdx++;
  4109. vData.push_back(vValue);
  4110. }
  4111. else
  4112. {
  4113. // This is a new entry, it only gets added to the ext
  4114. BF_ASSERT(isInExts);
  4115. }
  4116. break;
  4117. }
  4118. }
  4119. if (!origVTable.empty())
  4120. typeInstance->mVirtualMethodTable = origVTable;
  4121. }
  4122. int ifaceMethodExtStart = (int)typeInstance->GetIFaceVMethodSize();
  4123. if (typeInstance->mHotTypeData != NULL)
  4124. {
  4125. if (typeInstance->mHotTypeData->mOrigInterfaceMethodsLength != -1)
  4126. ifaceMethodExtStart = typeInstance->mHotTypeData->mOrigInterfaceMethodsLength;
  4127. }
  4128. SizedArray<BfIRValue, 32> ifaceMethodExtData;
  4129. int iFaceMethodStartIdx = (int)vData.size();
  4130. vData.resize(iFaceMethodStartIdx + ifaceMethodExtStart);
  4131. for (int i = iFaceMethodStartIdx; i < iFaceMethodStartIdx + ifaceMethodExtStart; i++)
  4132. vData[i] = voidPtrNull;
  4133. if (expectNumElements != 0)
  4134. BF_ASSERT(expectNumElements == vData.size());
  4135. //BF_ASSERT(vData.size() == expectNumElements);
  4136. // for (int i = 0; i < (int)typeInstance->mInterfaceMethodTable.size() - ifaceMethodExtStart; i++)
  4137. // ifaceMethodExtData.Add(voidPtrNull);
  4138. int ifaceEntryIdx = iFaceMethodStartIdx;
  4139. for (auto& interfacePair : interfaceMap)
  4140. {
  4141. auto interfaceEntry = interfacePair.mValue.mEntry;
  4142. bool makeEmpty = false;
  4143. if (!typeInstance->IsTypeMemberAccessible(interfaceEntry->mDeclaringType, mProject))
  4144. makeEmpty = true;
  4145. int endVirtualIdx = interfaceEntry->mStartVirtualIdx + interfaceEntry->mInterfaceType->mVirtualMethodTableSize;
  4146. bool useExt = endVirtualIdx > ifaceMethodExtStart;
  4147. for (int methodIdx = 0; methodIdx < (int)interfaceEntry->mInterfaceType->mMethodInstanceGroups.size(); methodIdx++)
  4148. {
  4149. BfIRValue pushValue;
  4150. BfMethodInstance* ifaceMethodInstance = interfaceEntry->mInterfaceType->mMethodInstanceGroups[methodIdx].mDefault;
  4151. if ((ifaceMethodInstance == NULL) || (ifaceMethodInstance->mVirtualTableIdx == -1))
  4152. continue;
  4153. if ((!ifaceMethodInstance->mIsReified) || (!ifaceMethodInstance->mMethodInstanceGroup->IsImplemented()))
  4154. continue;
  4155. if (makeEmpty)
  4156. {
  4157. pushValue = voidPtrNull;
  4158. }
  4159. else
  4160. {
  4161. auto& methodRef = typeInstance->mInterfaceMethodTable[interfaceEntry->mStartInterfaceTableIdx + methodIdx].mMethodRef;
  4162. auto methodInstance = (BfMethodInstance*)methodRef;
  4163. if ((methodInstance != NULL) && (!methodInstance->mMethodDef->mIsAbstract))
  4164. {
  4165. BF_ASSERT(methodInstance->mIsReified);
  4166. // This doesn't work because we may have FOREIGN methods from implicit interface methods
  4167. //auto moduleMethodInst = GetMethodInstanceAtIdx(methodRef.mTypeInstance, methodRef.mMethodNum);
  4168. auto moduleMethodInst = ReferenceExternalMethodInstance(methodInstance);
  4169. auto funcPtr = mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, voidPtrIRType);
  4170. pushValue = funcPtr;
  4171. }
  4172. else
  4173. {
  4174. pushValue = voidPtrNull;
  4175. }
  4176. }
  4177. int idx = interfaceEntry->mStartVirtualIdx + ifaceMethodInstance->mVirtualTableIdx;
  4178. if (idx < ifaceMethodExtStart)
  4179. {
  4180. BF_ASSERT(iFaceMethodStartIdx + idx < (int)vData.size());
  4181. vData[iFaceMethodStartIdx + idx] = pushValue;
  4182. }
  4183. else
  4184. {
  4185. BF_ASSERT(useExt);
  4186. int extIdx = idx - ifaceMethodExtStart;
  4187. while (extIdx >= ifaceMethodExtData.size())
  4188. ifaceMethodExtData.Add(voidPtrNull);
  4189. ifaceMethodExtData[extIdx] = pushValue;
  4190. }
  4191. }
  4192. }
  4193. if (typeInstance->IsBoxed())
  4194. {
  4195. BfBoxedType* boxedType = (BfBoxedType*)typeInstance;
  4196. if (boxedType->IsBoxedStructPtr())
  4197. {
  4198. // Force override of GetHashCode so we use the pointer address as the hash code
  4199. checkTypeInst = CreateBoxedType(ResolveTypeDef(mCompiler->mPointerTypeDef));
  4200. // Force override of GetHashCode so we use the pointer address as the hash code
  4201. for (auto& checkIFace : checkTypeInst->mInterfaces)
  4202. {
  4203. for (int methodIdx = 0; methodIdx < (int)checkIFace.mInterfaceType->mMethodInstanceGroups.size(); methodIdx++)
  4204. {
  4205. BfIRValue pushValue;
  4206. BfMethodInstance* ifaceMethodInstance = checkIFace.mInterfaceType->mMethodInstanceGroups[methodIdx].mDefault;
  4207. if ((ifaceMethodInstance == NULL) || (ifaceMethodInstance->mVirtualTableIdx == -1))
  4208. continue;
  4209. if ((!ifaceMethodInstance->mIsReified) || (!ifaceMethodInstance->mMethodInstanceGroup->IsImplemented()))
  4210. continue;
  4211. auto& methodRef = checkTypeInst->mInterfaceMethodTable[checkIFace.mStartInterfaceTableIdx + methodIdx].mMethodRef;
  4212. auto methodInstance = (BfMethodInstance*)methodRef;
  4213. BF_ASSERT(methodInstance->mIsReified);
  4214. // This doesn't work because we may have FOREIGN methods from implicit interface methods
  4215. //auto moduleMethodInst = GetMethodInstanceAtIdx(methodRef.mTypeInstance, methodRef.mMethodNum);
  4216. auto moduleMethodInst = ReferenceExternalMethodInstance(methodInstance);
  4217. auto funcPtr = mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, voidPtrIRType);
  4218. int idx = checkIFace.mStartVirtualIdx + ifaceMethodInstance->mVirtualTableIdx;
  4219. vData[iFaceMethodStartIdx + idx] = funcPtr;
  4220. }
  4221. }
  4222. }
  4223. }
  4224. if ((needsVData) && (!typeInstance->mTypeDef->mIsStatic))
  4225. {
  4226. BfIRValue ifaceMethodExtVar;
  4227. if (!ifaceMethodExtData.IsEmpty())
  4228. {
  4229. StringT<128> classVDataName;
  4230. BfMangler::MangleStaticFieldName(classVDataName, mCompiler->GetMangleKind(), typeInstance, "bf_hs_replace_IFaceExt");
  4231. auto arrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr), (int)ifaceMethodExtData.size());
  4232. ifaceMethodExtVar = mBfIRBuilder->CreateGlobalVariable(arrayType, true,
  4233. BfIRLinkageType_External, BfIRValue(), classVDataName);
  4234. BfIRType extVTableType = mBfIRBuilder->GetSizedArrayType(voidPtrIRType, (int)ifaceMethodExtData.size());
  4235. BfIRValue extVTableConst = mBfIRBuilder->CreateConstArray(extVTableType, ifaceMethodExtData);
  4236. mBfIRBuilder->GlobalVar_SetInitializer(ifaceMethodExtVar, extVTableConst);
  4237. }
  4238. for (auto& ifaceInstPair : interfaceMap)
  4239. {
  4240. auto interfaceEntry = ifaceInstPair.mValue.mEntry;
  4241. int slotNum = interfaceEntry->mInterfaceType->mSlotNum;
  4242. if (slotNum >= 0)
  4243. {
  4244. BfIRValue vtablePtr;
  4245. int idx = interfaceEntry->mStartVirtualIdx;
  4246. int endVirtualIdx = interfaceEntry->mStartVirtualIdx + interfaceEntry->mInterfaceType->mVirtualMethodTableSize;
  4247. if (endVirtualIdx > ifaceMethodExtStart)
  4248. vtablePtr = mBfIRBuilder->CreateInBoundsGEP(ifaceMethodExtVar, 0, interfaceEntry->mStartVirtualIdx - ifaceMethodExtStart);
  4249. else
  4250. vtablePtr = mBfIRBuilder->CreateInBoundsGEP(classVDataVar, 0, iFaceMethodStartIdx + interfaceEntry->mStartVirtualIdx);
  4251. int slotVirtIdx = slotNum + vDataOfs;
  4252. if (vData[slotVirtIdx] == voidPtrNull)
  4253. {
  4254. vData[slotVirtIdx] = mBfIRBuilder->CreateBitCast(vtablePtr, voidPtrIRType);
  4255. }
  4256. else
  4257. {
  4258. if (mCompiler->IsHotCompile())
  4259. Fail("Interface slot collision error. Restart program or undo interface changes.", typeDef->GetRefNode());
  4260. else
  4261. Fail("Interface slot collision error", typeDef->GetRefNode());
  4262. }
  4263. }
  4264. }
  4265. }
  4266. }
  4267. BfIRValue typeNameConst;
  4268. BfIRValue namespaceConst;
  4269. if (needsTypeNames)
  4270. {
  4271. typeNameConst = GetStringObjectValue(typeDef->mName->mString, true);
  4272. namespaceConst = GetStringObjectValue(typeDef->mNamespace.ToString(), true);
  4273. }
  4274. else
  4275. {
  4276. auto stringType = ResolveTypeDef(mCompiler->mStringTypeDef);
  4277. typeNameConst = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(stringType));
  4278. namespaceConst = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(stringType));
  4279. }
  4280. int baseTypeId = 0;
  4281. if (typeInstance->mBaseType != NULL)
  4282. {
  4283. baseTypeId = typeInstance->mBaseType->mTypeId;
  4284. }
  4285. SizedArray<BfIRValue, 16> customAttrs;
  4286. BfTypeInstance* attributeType = mContext->mUnreifiedModule->ResolveTypeDef(mCompiler->mAttributeTypeDef)->ToTypeInstance();
  4287. BfIRValue castedClassVData;
  4288. if (classVDataVar)
  4289. castedClassVData = mBfIRBuilder->CreateBitCast(classVDataVar, mBfIRBuilder->MapType(mContext->mBfClassVDataPtrType));
  4290. else
  4291. castedClassVData = GetDefaultValue(mContext->mBfClassVDataPtrType);
  4292. bool freflectIncludeTypeData = false;
  4293. bool reflectIncludeAllFields = false;
  4294. bool reflectIncludeAllMethods = false;
  4295. if (TypeIsSubTypeOf(typeInstance, attributeType))
  4296. {
  4297. reflectIncludeAllFields = true;
  4298. reflectIncludeAllMethods = true;
  4299. }
  4300. enum ReflectKind
  4301. {
  4302. ReflectKind_None = 0,
  4303. ReflectKind_Type = 1,
  4304. ReflectKind_NonStaticFields = 2,
  4305. ReflectKind_StaticFields = 4,
  4306. ReflectKind_DefaultConstructor = 8,
  4307. ReflectKind_Constructors = 0x10,
  4308. ReflectKind_StaticMethods = 0x20,
  4309. ReflectKind_Methods = 0x40,
  4310. ReflectKind_User = 0x80,
  4311. ReflectKind_All = 0x7F,
  4312. ReflectKind_ApplyToInnerTypes = 0x80
  4313. };
  4314. ReflectKind reflectKind = ReflectKind_Type;
  4315. auto _GetReflectUser = [&](BfTypeInstance* attrType)
  4316. {
  4317. ReflectKind reflectKind = ReflectKind_None;
  4318. if (attrType->mCustomAttributes != NULL)
  4319. {
  4320. for (auto& customAttr : attrType->mCustomAttributes->mAttributes)
  4321. {
  4322. if (customAttr.mType->mTypeDef->mName->ToString() == "AttributeUsageAttribute")
  4323. {
  4324. for (auto& prop : customAttr.mSetProperties)
  4325. {
  4326. auto propDef = prop.mPropertyRef.mTypeInstance->mTypeDef->mProperties[prop.mPropertyRef.mPropIdx];
  4327. if (propDef->mName == "ReflectUser")
  4328. {
  4329. if (prop.mParam.mValue.IsConst())
  4330. {
  4331. auto constant = attrType->mConstHolder->GetConstant(prop.mParam.mValue);
  4332. reflectKind = (ReflectKind)(reflectKind | (ReflectKind)constant->mInt32);
  4333. }
  4334. }
  4335. }
  4336. // Check for Flags arg
  4337. if (customAttr.mCtorArgs.size() < 2)
  4338. continue;
  4339. auto constant = attrType->mConstHolder->GetConstant(customAttr.mCtorArgs[1]);
  4340. if (constant == NULL)
  4341. continue;
  4342. if (constant->mTypeCode == BfTypeCode_Boolean)
  4343. continue;
  4344. if ((constant->mInt8 & BfCustomAttributeFlags_ReflectAttribute) != 0)
  4345. reflectKind = (ReflectKind)(reflectKind | ReflectKind_User);
  4346. }
  4347. }
  4348. }
  4349. return reflectKind;
  4350. };
  4351. auto _GetReflectUserFromDirective = [&](BfAttributeDirective* attributesDirective, BfAttributeTargets attrTarget)
  4352. {
  4353. ReflectKind reflectKind = ReflectKind_None;
  4354. auto customAttrs = GetCustomAttributes(attributesDirective, attrTarget);
  4355. if (customAttrs != NULL)
  4356. {
  4357. for (auto& attr : customAttrs->mAttributes)
  4358. {
  4359. reflectKind = (ReflectKind)(reflectKind | _GetReflectUser(attr.mType));
  4360. }
  4361. }
  4362. return reflectKind;
  4363. };
  4364. //
  4365. {
  4366. auto checkTypeInstance = typeInstance;
  4367. while (checkTypeInstance != NULL)
  4368. {
  4369. if (checkTypeInstance->mCustomAttributes != NULL)
  4370. {
  4371. auto checkReflectKind = ReflectKind_None;
  4372. for (auto& customAttr : checkTypeInstance->mCustomAttributes->mAttributes)
  4373. {
  4374. if (customAttr.mType->mTypeDef->mName->ToString() == "ReflectAttribute")
  4375. {
  4376. if (customAttr.mCtorArgs.size() > 0)
  4377. {
  4378. auto constant = checkTypeInstance->mConstHolder->GetConstant(customAttr.mCtorArgs[0]);
  4379. checkReflectKind = (ReflectKind)((int)checkReflectKind | constant->mInt32);
  4380. }
  4381. else
  4382. {
  4383. checkReflectKind = ReflectKind_All;
  4384. }
  4385. }
  4386. else
  4387. {
  4388. auto userReflectKind = _GetReflectUser(customAttr.mType);
  4389. checkReflectKind = (ReflectKind)(checkReflectKind | userReflectKind);
  4390. }
  4391. }
  4392. if ((checkTypeInstance == typeInstance) ||
  4393. ((checkReflectKind & ReflectKind_ApplyToInnerTypes) != 0))
  4394. {
  4395. reflectKind = (ReflectKind)(reflectKind | checkReflectKind);
  4396. }
  4397. }
  4398. checkTypeInstance = GetOuterType(checkTypeInstance);
  4399. }
  4400. }
  4401. // Fields
  4402. BfType* reflectFieldDataType = ResolveTypeDef(mCompiler->mReflectFieldDataDef);
  4403. BfIRValue emptyValueType = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(reflectFieldDataType->ToTypeInstance()->mBaseType), SizedArray<BfIRValue, 1>());
  4404. auto _HandleCustomAttrs = [&](BfCustomAttributes* customAttributes)
  4405. {
  4406. if (customAttributes == NULL)
  4407. return -1;
  4408. Array<BfCustomAttribute*> reflectAttributes;
  4409. for (auto& attr : customAttributes->mAttributes)
  4410. {
  4411. bool wantAttribute = false;
  4412. if (attr.mType->mCustomAttributes != NULL)
  4413. {
  4414. auto usageAttribute = attr.mType->mCustomAttributes->Get(mCompiler->mAttributeUsageAttributeTypeDef);
  4415. if (usageAttribute != NULL)
  4416. {
  4417. // Check for Flags arg
  4418. if (usageAttribute->mCtorArgs.size() < 2)
  4419. continue;
  4420. auto constant = attr.mType->mConstHolder->GetConstant(usageAttribute->mCtorArgs[1]);
  4421. if (constant == NULL)
  4422. continue;
  4423. if (constant->mTypeCode == BfTypeCode_Boolean)
  4424. continue;
  4425. if ((constant->mInt8 & BfCustomAttributeFlags_ReflectAttribute) != 0)
  4426. wantAttribute = true;
  4427. }
  4428. }
  4429. if ((wantAttribute) && (attr.mType->mIsReified))
  4430. {
  4431. reflectAttributes.Add(&attr);
  4432. }
  4433. }
  4434. if (reflectAttributes.size() == 0)
  4435. return -1;
  4436. #define PUSH_INT8(val) data.push_back((uint8)val)
  4437. #define PUSH_INT16(val) { data.push_back(val & 0xFF); data.push_back((val >> 8) & 0xFF); }
  4438. #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); }
  4439. #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); \
  4440. data.push_back((val >> 32) & 0xFF); data.push_back((val >> 40) & 0xFF); data.push_back((val >> 48) & 0xFF); data.push_back((val >> 56) & 0xFF); }
  4441. SizedArray<uint8, 16> data;
  4442. int customAttrIdx = (int)customAttrs.size();
  4443. data.push_back((uint8)reflectAttributes.size());
  4444. for (auto attr : reflectAttributes)
  4445. {
  4446. // Size prefix
  4447. int sizeIdx = (int)data.size();
  4448. PUSH_INT16(0); // mSize
  4449. PUSH_INT32(attr->mType->mTypeId); // mType
  4450. PUSH_INT16(attr->mCtor->mIdx);
  4451. auto ctorMethodInstance = GetRawMethodInstanceAtIdx(attr->mType, attr->mCtor->mIdx);
  4452. int argIdx = 0;
  4453. for (auto arg : attr->mCtorArgs)
  4454. {
  4455. auto constant = typeInstance->mConstHolder->GetConstant(arg);
  4456. bool handled = false;
  4457. if (constant != NULL)
  4458. {
  4459. auto argType = ctorMethodInstance->GetParamType(argIdx);
  4460. if (argType->IsObject())
  4461. {
  4462. BF_ASSERT(argType->ToTypeInstance()->mTypeDef == mCompiler->mStringTypeDef);
  4463. int stringId = constant->mInt32;
  4464. int* orderedIdPtr;
  4465. if (usedStringIdMap.TryAdd(stringId, NULL, &orderedIdPtr))
  4466. {
  4467. *orderedIdPtr = (int)usedStringIdMap.size() - 1;
  4468. }
  4469. GetStringObjectValue(stringId);
  4470. PUSH_INT8(0xFF); // String
  4471. PUSH_INT32(*orderedIdPtr);
  4472. continue;
  4473. }
  4474. PUSH_INT8(constant->mTypeCode);
  4475. if ((constant->mTypeCode == BfTypeCode_Int64) ||
  4476. (constant->mTypeCode == BfTypeCode_UInt64) ||
  4477. (constant->mTypeCode == BfTypeCode_Double))
  4478. {
  4479. PUSH_INT64(constant->mInt64);
  4480. }
  4481. else if ((constant->mTypeCode == BfTypeCode_Int32) ||
  4482. (constant->mTypeCode == BfTypeCode_UInt32))
  4483. {
  4484. PUSH_INT32(constant->mInt32);
  4485. }
  4486. else if (constant->mTypeCode == BfTypeCode_Single)
  4487. {
  4488. float val = (float)constant->mDouble;
  4489. PUSH_INT32(*(int*)&val);
  4490. }
  4491. else if ((constant->mTypeCode == BfTypeCode_Int16) ||
  4492. (constant->mTypeCode == BfTypeCode_UInt16))
  4493. {
  4494. PUSH_INT16(constant->mInt16);
  4495. }
  4496. else if ((constant->mTypeCode == BfTypeCode_Int8) ||
  4497. (constant->mTypeCode == BfTypeCode_UInt8))
  4498. {
  4499. PUSH_INT8(constant->mInt8);
  4500. }
  4501. else if (constant->mTypeCode == BfTypeCode_Object)
  4502. {
  4503. BF_FATAL("Unhandled");
  4504. }
  4505. else
  4506. {
  4507. BF_FATAL("Unhandled");
  4508. }
  4509. }
  4510. else if (!handled)
  4511. {
  4512. BF_FATAL("Unhandled");
  4513. }
  4514. argIdx++;
  4515. }
  4516. int size = (int)data.size() - sizeIdx;
  4517. *((uint16*)&data[sizeIdx]) = size;
  4518. }
  4519. #undef PUSH_INT8
  4520. #undef PUSH_INT16
  4521. #undef PUSH_INT32
  4522. SizedArray<BfIRValue, 16> dataValues;
  4523. for (uint8 val : data)
  4524. dataValues.push_back(GetConstValue8(val));
  4525. auto dataArrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->MapType(byteType), (int)data.size());
  4526. auto customAttrConst = mBfIRBuilder->CreateConstArray(dataArrayType, dataValues);
  4527. BfIRValue customAttrArray = mBfIRBuilder->CreateGlobalVariable(dataArrayType, true, BfIRLinkageType_Internal,
  4528. customAttrConst, typeDataName + StrFormat(".customAttr%d", customAttrIdx));
  4529. BfIRValue customAttrArrayPtr = mBfIRBuilder->CreateBitCast(customAttrArray, voidPtrIRType);
  4530. customAttrs.push_back(customAttrArrayPtr);
  4531. return customAttrIdx;
  4532. };
  4533. int typeCustomAttrIdx = _HandleCustomAttrs(typeInstance->mCustomAttributes);
  4534. SizedArray<int, 16> reflectFieldIndices;
  4535. for (int pass = 0; pass < 2; pass++)
  4536. {
  4537. bool skippedField = false;
  4538. reflectFieldIndices.clear();
  4539. for (int fieldIdx = 0; fieldIdx < (int)typeInstance->mFieldInstances.size(); fieldIdx++)
  4540. {
  4541. BfFieldInstance* fieldInstance = &typeInstance->mFieldInstances[fieldIdx];
  4542. BfFieldDef* fieldDef = fieldInstance->GetFieldDef();
  4543. if (fieldDef == NULL)
  4544. continue;
  4545. auto fieldReflectKind = (ReflectKind)(reflectKind & ~ReflectKind_User);
  4546. bool includeField = reflectIncludeAllFields;
  4547. if (fieldInstance->mCustomAttributes != NULL)
  4548. {
  4549. for (auto& customAttr : fieldInstance->mCustomAttributes->mAttributes)
  4550. {
  4551. if (customAttr.mType->mTypeDef->mName->ToString() == "ReflectAttribute")
  4552. {
  4553. includeField = true;
  4554. }
  4555. else
  4556. {
  4557. auto userReflectKind = _GetReflectUser(customAttr.mType);
  4558. fieldReflectKind = (ReflectKind)(fieldReflectKind | userReflectKind);
  4559. }
  4560. }
  4561. }
  4562. if ((fieldReflectKind & ReflectKind_User) != 0)
  4563. includeField = true;
  4564. if ((!fieldDef->mIsStatic) && ((fieldReflectKind & ReflectKind_NonStaticFields) != 0))
  4565. includeField = true;
  4566. if ((fieldDef->mIsStatic) && ((fieldReflectKind & ReflectKind_StaticFields) != 0))
  4567. includeField = true;
  4568. includeField |= forceReflectFields;
  4569. if (!includeField)
  4570. {
  4571. skippedField = true;
  4572. continue;
  4573. }
  4574. reflectFieldIndices.Add(fieldIdx);
  4575. }
  4576. // For a splattable type, we need to either include all fields or zero fields. This is to allow us to correctly splat
  4577. // params for reflected method calls even if we don't have reflection field info for the splatted type. This is
  4578. // possible because we write out a SplatData structure containing just TypeIds in that case
  4579. if (pass == 0)
  4580. {
  4581. if (!typeInstance->IsSplattable())
  4582. break;
  4583. if (!skippedField)
  4584. break;
  4585. if (reflectFieldIndices.size() == 0)
  4586. break;
  4587. }
  4588. }
  4589. SizedArray<BfIRValue, 16> fieldTypes;
  4590. enum FieldFlags
  4591. {
  4592. FieldFlags_Protected = 3,
  4593. FieldFlags_Public = 6,
  4594. FieldFlags_Static = 0x10,
  4595. FieldFlags_Const = 0x40,
  4596. FieldFlags_SpecialName = 0x80,
  4597. FieldFlags_EnumPayload = 0x100,
  4598. FieldFlags_EnumDiscriminator = 0x200
  4599. };
  4600. if ((typeInstance->IsPayloadEnum()) && (!typeInstance->IsBoxed()))
  4601. {
  4602. BfType* payloadType = typeInstance->GetUnionInnerType();
  4603. if (!payloadType->IsValuelessType())
  4604. {
  4605. BfIRValue payloadNameConst = GetStringObjectValue("$payload", true);
  4606. SizedArray<BfIRValue, 8> payloadFieldVals =
  4607. {
  4608. emptyValueType,
  4609. payloadNameConst, // mName
  4610. GetConstValue(0, longType), // mConstValue
  4611. GetConstValue(0, intType), // mDataOffset
  4612. GetConstValue(payloadType->mTypeId, typeIdType), // mFieldTypeId
  4613. GetConstValue(FieldFlags_SpecialName | FieldFlags_EnumPayload, shortType), // mFlags
  4614. GetConstValue(-1, intType), // mCustomAttributesIdx
  4615. };
  4616. auto payloadFieldData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(reflectFieldDataType->ToTypeInstance(), BfIRPopulateType_Full), payloadFieldVals);
  4617. fieldTypes.push_back(payloadFieldData);
  4618. }
  4619. BfType* dscrType = typeInstance->GetDiscriminatorType();
  4620. BfIRValue dscrNameConst = GetStringObjectValue("$discriminator", true);
  4621. SizedArray<BfIRValue, 8> dscrFieldVals =
  4622. {
  4623. emptyValueType,
  4624. dscrNameConst, // mName
  4625. GetConstValue(0, longType), // mConstValue
  4626. GetConstValue(BF_ALIGN(payloadType->mSize, dscrType->mAlign), intType), // mDataOffset
  4627. GetConstValue(dscrType->mTypeId, typeIdType), // mFieldTypeId
  4628. GetConstValue(FieldFlags_SpecialName | FieldFlags_EnumDiscriminator, shortType), // mFlags
  4629. GetConstValue(-1, intType), // mCustomAttributesIdx
  4630. };
  4631. auto dscrFieldData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(reflectFieldDataType->ToTypeInstance(), BfIRPopulateType_Full), dscrFieldVals);
  4632. fieldTypes.push_back(dscrFieldData);
  4633. }
  4634. for (auto fieldIdx : reflectFieldIndices)
  4635. {
  4636. if (!needsTypeData)
  4637. break;
  4638. BfFieldInstance* fieldInstance = &typeInstance->mFieldInstances[fieldIdx];
  4639. BfFieldDef* fieldDef = fieldInstance->GetFieldDef();
  4640. BfIRValue fieldNameConst = GetStringObjectValue(fieldDef->mName, true);
  4641. int typeId = 0;
  4642. auto fieldType = fieldInstance->GetResolvedType();
  4643. if (fieldType->IsGenericParam())
  4644. {
  4645. //TODO:
  4646. }
  4647. else
  4648. typeId = fieldType->mTypeId;
  4649. FieldFlags fieldFlags = (FieldFlags)0;
  4650. if (fieldDef->mProtection == BfProtection_Protected)
  4651. fieldFlags = (FieldFlags)(fieldFlags | FieldFlags_Protected);
  4652. if (fieldDef->mProtection == BfProtection_Public)
  4653. fieldFlags = (FieldFlags)(fieldFlags | FieldFlags_Public);
  4654. if (fieldDef->mIsStatic)
  4655. fieldFlags = (FieldFlags)(fieldFlags | FieldFlags_Static);
  4656. if (fieldDef->mIsConst)
  4657. fieldFlags = (FieldFlags)(fieldFlags | FieldFlags_Const);
  4658. int customAttrIdx = _HandleCustomAttrs(fieldInstance->mCustomAttributes);
  4659. BfIRValue constValue = GetConstValue(0, longType);
  4660. if (fieldInstance->GetFieldDef()->mIsConst)
  4661. {
  4662. if (fieldInstance->mConstIdx != -1)
  4663. {
  4664. auto constant = typeInstance->mConstHolder->GetConstantById(fieldInstance->mConstIdx);
  4665. constValue = mBfIRBuilder->CreateConst(BfTypeCode_UInt64, constant->mUInt64);
  4666. }
  4667. }
  4668. SizedArray<BfIRValue, 8> fieldVals =
  4669. {
  4670. emptyValueType,
  4671. fieldNameConst, // mName
  4672. constValue, // mConstValue
  4673. GetConstValue(fieldInstance->mDataOffset, intType), // mDataOffset
  4674. GetConstValue(typeId, typeIdType), // mFieldTypeId
  4675. GetConstValue(fieldFlags, shortType), // mFlags
  4676. GetConstValue(customAttrIdx, intType), // mCustomAttributesIdx
  4677. };
  4678. auto fieldData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(reflectFieldDataType->ToTypeInstance(), BfIRPopulateType_Full), fieldVals);
  4679. fieldTypes.push_back(fieldData);
  4680. }
  4681. auto reflectFieldDataIRType = mBfIRBuilder->MapType(reflectFieldDataType);
  4682. BfIRValue fieldDataPtr;
  4683. BfIRType fieldDataPtrType = mBfIRBuilder->GetPointerTo(reflectFieldDataIRType);
  4684. if (fieldTypes.size() == 0)
  4685. {
  4686. if ((type->IsSplattable()) && (type->IsStruct()) && (!type->IsValuelessType()))
  4687. {
  4688. BfTypeInstance* reflectFieldSplatDataType = ResolveTypeDef(mCompiler->mReflectFieldSplatDataDef)->ToTypeInstance();
  4689. SizedArray<BfIRValue, 3> splatTypes;
  4690. SizedArray<BfIRValue, 3> splatOffsets;
  4691. std::function<void(BfType*, int)> _CheckSplat = [&](BfType* checkType, int offset)
  4692. {
  4693. auto checkTypeInstance = checkType->ToTypeInstance();
  4694. if ((checkTypeInstance != NULL) && (checkTypeInstance->IsValueType()) && (checkTypeInstance->IsDataIncomplete()))
  4695. PopulateType(checkTypeInstance);
  4696. if (checkType->IsStruct())
  4697. {
  4698. int dataEnd = offset;
  4699. if (checkTypeInstance->mBaseType != NULL)
  4700. _CheckSplat(checkTypeInstance->mBaseType, offset);
  4701. if (checkTypeInstance->mIsUnion)
  4702. {
  4703. BfType* unionInnerType = checkTypeInstance->GetUnionInnerType();
  4704. _CheckSplat(unionInnerType, offset);
  4705. }
  4706. else
  4707. {
  4708. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  4709. {
  4710. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  4711. if (fieldInstance->mDataIdx >= 0)
  4712. {
  4713. _CheckSplat(fieldInstance->GetResolvedType(), offset + fieldInstance->mDataOffset);
  4714. dataEnd = offset + fieldInstance->mDataOffset + fieldInstance->mResolvedType->mSize;
  4715. }
  4716. }
  4717. }
  4718. if (checkTypeInstance->IsEnum())
  4719. {
  4720. // Add discriminator
  4721. auto dscrType = checkTypeInstance->GetDiscriminatorType();
  4722. if (!checkTypeInstance->mIsPacked)
  4723. dataEnd = BF_ALIGN(dataEnd, dscrType->mAlign);
  4724. _CheckSplat(dscrType, dataEnd);
  4725. }
  4726. }
  4727. else if (checkType->IsMethodRef())
  4728. {
  4729. // auto methodRefType = (BfMethodRefType*)checkType;
  4730. // for (int dataIdx = 0; dataIdx < methodRefType->GetCaptureDataCount(); dataIdx++)
  4731. // {
  4732. // if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  4733. // _CheckSplat(methodRefType->GetCaptureType(dataIdx), offsetof);
  4734. // else
  4735. // dataLambda(methodRefType->GetCaptureType(dataIdx));
  4736. // }
  4737. }
  4738. else if (!checkType->IsValuelessType())
  4739. {
  4740. splatTypes.Add(GetConstValue(checkType->mTypeId, typeIdType));
  4741. splatOffsets.Add(GetConstValue(offset, intType));
  4742. }
  4743. };
  4744. _CheckSplat(type, 0);
  4745. while (splatTypes.size() < 3)
  4746. {
  4747. splatTypes.Add(GetConstValue(0, typeIdType));
  4748. splatOffsets.Add(GetConstValue(0, intType));
  4749. }
  4750. BfIRValue splatTypesConst = mBfIRBuilder->CreateConstArray(mBfIRBuilder->MapType(reflectFieldSplatDataType->mFieldInstances[0].mResolvedType), splatTypes);
  4751. BfIRValue splatOffsetsConst = mBfIRBuilder->CreateConstArray(mBfIRBuilder->MapType(reflectFieldSplatDataType->mFieldInstances[1].mResolvedType), splatOffsets);
  4752. SizedArray<BfIRValue, 8> splatVals =
  4753. {
  4754. emptyValueType,
  4755. splatTypesConst,
  4756. splatOffsetsConst
  4757. };
  4758. auto fieldSplatData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(reflectFieldSplatDataType->ToTypeInstance(), BfIRPopulateType_Full), splatVals);
  4759. BfIRValue fieldDataArray = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapType(reflectFieldSplatDataType), true, BfIRLinkageType_Internal,
  4760. fieldSplatData, typeDataName + ".splats");
  4761. fieldDataPtr = mBfIRBuilder->CreateBitCast(fieldDataArray, fieldDataPtrType);
  4762. }
  4763. else
  4764. fieldDataPtr = mBfIRBuilder->CreateConstNull(fieldDataPtrType);
  4765. }
  4766. else
  4767. {
  4768. BfIRType fieldDataConstType = mBfIRBuilder->GetSizedArrayType(reflectFieldDataIRType, (int)fieldTypes.size());
  4769. BfIRValue fieldDataConst = mBfIRBuilder->CreateConstArray(fieldDataConstType, fieldTypes);
  4770. BfIRValue fieldDataArray = mBfIRBuilder->CreateGlobalVariable(fieldDataConstType, true, BfIRLinkageType_Internal,
  4771. fieldDataConst, "fields." + typeDataName);
  4772. fieldDataPtr = mBfIRBuilder->CreateBitCast(fieldDataArray, fieldDataPtrType);
  4773. }
  4774. /// Methods
  4775. BfType* reflectMethodDataType = ResolveTypeDef(mCompiler->mReflectMethodDataDef);
  4776. BfType* reflectParamDataType = ResolveTypeDef(mCompiler->mReflectParamDataDef);
  4777. BfType* reflectParamDataPtrType = CreatePointerType(reflectParamDataType);
  4778. SizedArray<BfIRValue, 16> methodTypes;
  4779. for (int methodIdx = 0; methodIdx < (int)typeDef->mMethods.size(); methodIdx++)
  4780. {
  4781. if (!needsTypeData)
  4782. break;
  4783. auto methodInstanceGroup = &typeInstance->mMethodInstanceGroups[methodIdx];
  4784. if (!methodInstanceGroup->IsImplemented())
  4785. continue;
  4786. auto methodDef = typeDef->mMethods[methodIdx];
  4787. if (methodDef->mNoReflect)
  4788. continue;
  4789. auto defaultMethod = methodInstanceGroup->mDefault;
  4790. if (defaultMethod == NULL)
  4791. continue;
  4792. if (defaultMethod->mIsUnspecialized)
  4793. continue;
  4794. if (!defaultMethod->mIsReified)
  4795. continue;
  4796. if ((defaultMethod->mChainType == BfMethodChainType_ChainMember) || (defaultMethod->mChainType == BfMethodChainType_ChainSkip))
  4797. continue;
  4798. if (defaultMethod->mMethodDef->mMethodType == BfMethodType_CtorNoBody)
  4799. continue;
  4800. auto methodReflectKind = (ReflectKind)(reflectKind & ~ReflectKind_User);
  4801. bool includeMethod = reflectIncludeAllMethods;
  4802. BfCustomAttributes* methodCustomAttributes = NULL;
  4803. if ((defaultMethod->mMethodInfoEx != NULL) && (defaultMethod->mMethodInfoEx->mMethodCustomAttributes != NULL) && (defaultMethod->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes != NULL))
  4804. {
  4805. methodCustomAttributes = defaultMethod->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes;
  4806. for (auto& customAttr : defaultMethod->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes->mAttributes)
  4807. {
  4808. if (customAttr.mType->mTypeDef->mName->ToString() == "ReflectAttribute")
  4809. {
  4810. includeMethod = true;
  4811. }
  4812. else
  4813. {
  4814. auto userReflectKind = _GetReflectUser(customAttr.mType);
  4815. methodReflectKind = (ReflectKind)(methodReflectKind | userReflectKind);
  4816. }
  4817. }
  4818. }
  4819. if (!typeInstance->IsTypeMemberAccessible(methodDef->mDeclaringType, mProject))
  4820. continue;
  4821. if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  4822. {
  4823. for (BfParameterDeclaration* paramDecl : methodDeclaration->mParams)
  4824. {
  4825. if (paramDecl->mAttributes != NULL)
  4826. methodReflectKind = (ReflectKind)(methodReflectKind | _GetReflectUserFromDirective(paramDecl->mAttributes, BfAttributeTargets_Parameter));
  4827. }
  4828. if (methodDeclaration->mReturnAttributes != NULL)
  4829. methodReflectKind = (ReflectKind)(methodReflectKind | _GetReflectUserFromDirective(methodDeclaration->mReturnAttributes, BfAttributeTargets_ReturnValue));
  4830. }
  4831. if ((methodReflectKind & (ReflectKind_Methods | ReflectKind_User)) != 0)
  4832. includeMethod = true;
  4833. if ((methodDef->mIsStatic) && ((methodReflectKind & ReflectKind_StaticMethods) != 0))
  4834. includeMethod = true;
  4835. if (!includeMethod)
  4836. continue;
  4837. BfModuleMethodInstance moduleMethodInstance;
  4838. BfIRValue funcVal = voidPtrNull;
  4839. if (((!typeInstance->IsBoxed()) || (!methodDef->mIsStatic)) &&
  4840. (!typeInstance->IsUnspecializedType()) &&
  4841. (methodDef->mMethodType != BfMethodType_Ignore) &&
  4842. (methodDef->mMethodType != BfMethodType_Mixin) &&
  4843. (!methodDef->mIsAbstract) &&
  4844. (methodDef->mGenericParams.size() == 0))
  4845. {
  4846. moduleMethodInstance = GetMethodInstanceAtIdx(typeInstance, methodIdx);
  4847. if (moduleMethodInstance.mFunc)
  4848. funcVal = mBfIRBuilder->CreateBitCast(moduleMethodInstance.mFunc, voidPtrIRType);
  4849. }
  4850. BfIRValue methodNameConst = GetStringObjectValue(methodDef->mName, true);
  4851. enum MethodFlags
  4852. {
  4853. MethodFlags_Protected = 3,
  4854. MethodFlags_Public = 6,
  4855. MethodFlags_Static = 0x10,
  4856. MethodFlags_Virtual = 0x40,
  4857. MethodFlags_StdCall = 0x1000,
  4858. MethodFlags_FastCall = 0x2000,
  4859. MethodFlags_Mutating = 0x4000,
  4860. };
  4861. MethodFlags methodFlags = (MethodFlags)0;
  4862. if (methodDef->mProtection == BfProtection_Protected)
  4863. methodFlags = (MethodFlags)(methodFlags | MethodFlags_Protected);
  4864. if (methodDef->mProtection == BfProtection_Public)
  4865. methodFlags = (MethodFlags)(methodFlags | MethodFlags_Public);
  4866. if (methodDef->mIsStatic)
  4867. methodFlags = (MethodFlags)(methodFlags | MethodFlags_Static);
  4868. if (methodDef->mIsVirtual)
  4869. methodFlags = (MethodFlags)(methodFlags | MethodFlags_Virtual);
  4870. if (methodDef->mCallingConvention == BfCallingConvention_Fastcall)
  4871. methodFlags = (MethodFlags)(methodFlags | MethodFlags_FastCall);
  4872. if (methodDef->mIsMutating)
  4873. methodFlags = (MethodFlags)(methodFlags | MethodFlags_Mutating);
  4874. int customAttrIdx = _HandleCustomAttrs(methodCustomAttributes);
  4875. enum ParamFlags
  4876. {
  4877. ParamFlag_None = 0,
  4878. ParamFlag_Splat = 1,
  4879. ParamFlag_Implicit = 2,
  4880. };
  4881. SizedArray<BfIRValue, 8> paramVals;
  4882. for (int paramIdx = 0; paramIdx < defaultMethod->GetParamCount(); paramIdx++)
  4883. {
  4884. String paramName = defaultMethod->GetParamName(paramIdx);
  4885. BfType* paramType = defaultMethod->GetParamType(paramIdx);
  4886. ParamFlags paramFlags = ParamFlag_None;
  4887. if (defaultMethod->GetParamIsSplat(paramIdx))
  4888. paramFlags = (ParamFlags)(paramFlags | ParamFlag_Splat);
  4889. BfIRValue paramNameConst = GetStringObjectValue(paramName, true);
  4890. SizedArray<BfIRValue, 8> paramDataVals =
  4891. {
  4892. emptyValueType,
  4893. paramNameConst,
  4894. GetConstValue(paramType->mTypeId, typeIdType),
  4895. GetConstValue((int32)paramFlags, shortType),
  4896. GetConstValue(customAttrIdx, intType) // defaultIdx
  4897. };
  4898. auto paramData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapType(reflectParamDataType, BfIRPopulateType_Full), paramDataVals);
  4899. paramVals.Add(paramData);
  4900. }
  4901. BfIRValue paramsVal;
  4902. if (paramVals.size() > 0)
  4903. {
  4904. BfIRType paramDataArrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->MapType(reflectParamDataType, BfIRPopulateType_Full), (int)paramVals.size());
  4905. BfIRValue paramDataConst = mBfIRBuilder->CreateConstArray(paramDataArrayType, paramVals);
  4906. BfIRValue paramDataArray = mBfIRBuilder->CreateGlobalVariable(paramDataArrayType, true, BfIRLinkageType_Internal,
  4907. paramDataConst, typeDataName + StrFormat(".params%d", methodIdx));
  4908. paramsVal = mBfIRBuilder->CreateBitCast(paramDataArray, mBfIRBuilder->MapType(reflectParamDataPtrType));
  4909. }
  4910. else
  4911. paramsVal = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(reflectParamDataPtrType));
  4912. int vDataVal = -1;
  4913. if (defaultMethod->mVirtualTableIdx != -1)
  4914. {
  4915. int vDataIdx = -1;
  4916. vDataIdx = 1 + mCompiler->GetDynCastVDataCount() + mCompiler->mMaxInterfaceSlots;
  4917. if ((mCompiler->mOptions.mHasVDataExtender) && (mCompiler->IsHotCompile()))
  4918. {
  4919. auto typeInst = defaultMethod->mMethodInstanceGroup->mOwner;
  4920. int extMethodIdx = (defaultMethod->mVirtualTableIdx - typeInst->GetBaseVTableSize()) - typeInst->GetOrigSelfVTableSize();
  4921. if (extMethodIdx >= 0)
  4922. {
  4923. // Extension?
  4924. int vExtOfs = typeInst->GetOrigBaseVTableSize();
  4925. vDataVal = ((vDataIdx + vExtOfs + 1) << 20) | (extMethodIdx);
  4926. }
  4927. else
  4928. {
  4929. // Map this new virtual index back to the original index
  4930. vDataIdx += (defaultMethod->mVirtualTableIdx - typeInst->GetBaseVTableSize()) + typeInst->GetOrigBaseVTableSize();
  4931. }
  4932. }
  4933. else
  4934. {
  4935. vDataIdx += defaultMethod->mVirtualTableIdx;
  4936. }
  4937. if (vDataVal == -1)
  4938. vDataVal = vDataIdx * mSystem->mPtrSize;
  4939. }
  4940. SizedArray<BfIRValue, 8> methodDataVals =
  4941. {
  4942. emptyValueType,
  4943. methodNameConst, // mName
  4944. funcVal, // mFuncPtr
  4945. paramsVal,
  4946. GetConstValue(defaultMethod->mReturnType->mTypeId, typeIdType),
  4947. GetConstValue((int)paramVals.size(), shortType),
  4948. GetConstValue(methodFlags, shortType),
  4949. GetConstValue(vDataVal, intType),
  4950. GetConstValue(-1, intType),
  4951. };
  4952. auto methodData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(reflectMethodDataType->ToTypeInstance(), BfIRPopulateType_Full), methodDataVals);
  4953. methodTypes.push_back(methodData);
  4954. }
  4955. BfIRValue methodDataPtr;
  4956. BfIRType methodDataPtrType = mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapType(reflectMethodDataType));
  4957. if (methodTypes.size() == 0)
  4958. methodDataPtr = mBfIRBuilder->CreateConstNull(methodDataPtrType);
  4959. else
  4960. {
  4961. BfIRType methodDataArrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->MapType(reflectMethodDataType, BfIRPopulateType_Full), (int)methodTypes.size());
  4962. BfIRValue methodDataConst = mBfIRBuilder->CreateConstArray(methodDataArrayType, methodTypes);
  4963. BfIRValue methodDataArray = mBfIRBuilder->CreateGlobalVariable(methodDataArrayType, true, BfIRLinkageType_Internal,
  4964. methodDataConst, "methods." + typeDataName);
  4965. methodDataPtr = mBfIRBuilder->CreateBitCast(methodDataArray, methodDataPtrType);
  4966. }
  4967. /////
  4968. int underlyingType = 0;
  4969. if ((typeInstance->IsTypedPrimitive()) || (typeInstance->IsBoxed()))
  4970. {
  4971. underlyingType = typeInstance->GetUnderlyingType()->mTypeId;
  4972. }
  4973. int outerTypeId = 0;
  4974. auto outerType = GetOuterType(typeInstance);
  4975. if (outerType != NULL)
  4976. outerTypeId = outerType->mTypeId;
  4977. BfIRValue customAttrDataPtr;
  4978. if (customAttrs.size() > 0)
  4979. {
  4980. BfIRType customAttrsArrayType = mBfIRBuilder->GetSizedArrayType(voidPtrIRType, (int)customAttrs.size());
  4981. BfIRValue customAttrsConst = mBfIRBuilder->CreateConstArray(customAttrsArrayType, customAttrs);
  4982. BfIRValue customAttrsArray = mBfIRBuilder->CreateGlobalVariable(customAttrsArrayType, true, BfIRLinkageType_Internal,
  4983. customAttrsConst, "customAttrs." + typeDataName);
  4984. customAttrDataPtr = mBfIRBuilder->CreateBitCast(customAttrsArray, voidPtrPtrIRType);
  4985. }
  4986. else
  4987. {
  4988. customAttrDataPtr = mBfIRBuilder->CreateConstNull(voidPtrPtrIRType);
  4989. }
  4990. SizedArray<BfIRValue, 32> typeDataVals =
  4991. {
  4992. typeData,
  4993. castedClassVData, // mTypeClassVData
  4994. typeNameConst, // mName
  4995. namespaceConst, // mNamespace
  4996. GetConstValue(typeInstance->mInstSize, intType), // mInstSize
  4997. GetConstValue(typeInstance->mInstAlign, intType), // mInstAlign
  4998. GetConstValue(typeCustomAttrIdx, intType), // mCustomAttributes
  4999. GetConstValue(baseTypeId, typeIdType), // mBaseType
  5000. GetConstValue(underlyingType, typeIdType), // mUnderlyingType
  5001. GetConstValue(outerTypeId, typeIdType), // mOuterType
  5002. GetConstValue(typeInstance->mInheritanceId, intType), // mInheritanceId
  5003. GetConstValue(typeInstance->mInheritanceCount, intType), // mInheritanceCount
  5004. GetConstValue(typeInstance->mSlotNum, byteType), // mInterfaceSlot
  5005. GetConstValue(0, byteType), // mInterfaceCount
  5006. GetConstValue((int)methodTypes.size(), shortType), // mMethodDataCount
  5007. GetConstValue(0, shortType), // mPropertyDataCount
  5008. GetConstValue((int)fieldTypes.size(), shortType), // mFieldDataCount
  5009. GetConstValue(0, shortType), // mConstructorDataCount
  5010. voidPtrNull, // mInterfaceDataPtr
  5011. methodDataPtr, // mMethodDataPtr
  5012. voidPtrNull, // mPropertyDataPtr
  5013. fieldDataPtr, // mFieldDataPtr
  5014. voidPtrNull, // mConstructorDataPtr
  5015. customAttrDataPtr, // mCustomAttrDataPtr
  5016. };
  5017. BfIRType typeInstanceDataType = mBfIRBuilder->MapTypeInst(typeInstanceType->ToTypeInstance(), BfIRPopulateType_Full);
  5018. auto typeInstanceData = mBfIRBuilder->CreateConstStruct(typeInstanceDataType, typeDataVals);
  5019. if (!needsTypeData)
  5020. {
  5021. // No need for anything beyond typeInstanceData
  5022. }
  5023. else if ((typeInstance->IsGenericTypeInstance()) && (typeInstance->IsUnspecializedType()))
  5024. {
  5025. auto genericTypeInstance = typeInstance->ToGenericTypeInstance();
  5026. SizedArray<BfIRValue, 4> unspecializedData =
  5027. {
  5028. typeInstanceData,
  5029. GetConstValue((int)genericTypeInstance->mTypeGenericArguments.size(), byteType), // mGenericParamCount
  5030. };
  5031. auto reflectUnspecializedGenericType = ResolveTypeDef(mCompiler->mReflectUnspecializedGenericType);
  5032. typeInstanceDataType = mBfIRBuilder->MapTypeInst(reflectUnspecializedGenericType->ToTypeInstance(), BfIRPopulateType_Full);
  5033. typeInstanceData = mBfIRBuilder->CreateConstStruct(typeInstanceDataType, unspecializedData);
  5034. }
  5035. else if (typeInstance->IsGenericTypeInstance())
  5036. {
  5037. auto genericTypeInstance = typeInstance->ToGenericTypeInstance();
  5038. auto reflectSpecializedGenericType = ResolveTypeDef(mCompiler->mReflectSpecializedGenericType);
  5039. auto unspecializedType = ResolveTypeDef(typeInstance->mTypeDef);
  5040. SizedArray<BfIRValue, 4> resolvedTypes;
  5041. for (auto typeGenericArg : genericTypeInstance->mTypeGenericArguments)
  5042. resolvedTypes.push_back(GetConstValue(typeGenericArg->mTypeId, typeIdType));
  5043. auto typeIRType = mBfIRBuilder->MapType(typeIdType);
  5044. auto typePtrIRType = mBfIRBuilder->GetPointerTo(typeIRType);
  5045. auto genericArrayType = mBfIRBuilder->GetSizedArrayType(typeIRType, (int)resolvedTypes.size());
  5046. BfIRValue resolvedTypesConst = mBfIRBuilder->CreateConstArray(genericArrayType, resolvedTypes);
  5047. BfIRValue resolvedTypesArray = mBfIRBuilder->CreateGlobalVariable(genericArrayType, true, BfIRLinkageType_Internal,
  5048. resolvedTypesConst, "resolvedTypes." + typeDataName);
  5049. BfIRValue resovledTypesPtr = mBfIRBuilder->CreateBitCast(resolvedTypesArray, typePtrIRType);
  5050. SizedArray<BfIRValue, 3> specGenericData =
  5051. {
  5052. typeInstanceData,
  5053. GetConstValue(unspecializedType->mTypeId, typeIdType), // mUnspecialziedType
  5054. resovledTypesPtr, // mFieldDataPtr
  5055. };
  5056. typeInstanceDataType = mBfIRBuilder->MapTypeInst(reflectSpecializedGenericType->ToTypeInstance(), BfIRPopulateType_Full);
  5057. typeInstanceData = mBfIRBuilder->CreateConstStruct(typeInstanceDataType, specGenericData);
  5058. if (typeInstance->IsArray())
  5059. {
  5060. auto arrayType = (BfArrayType*)typeInstance;
  5061. BfType* elementType = genericTypeInstance->mTypeGenericArguments[0];
  5062. BfFieldInstance* elementFieldInstance = &genericTypeInstance->mFieldInstances[0];
  5063. SizedArray<BfIRValue, 4> arrayData =
  5064. {
  5065. typeInstanceData,
  5066. GetConstValue(elementType->mSize, intType), // mElementSize
  5067. GetConstValue(1, byteType), // mRank
  5068. GetConstValue(elementFieldInstance->mDataOffset, byteType), // mElementsDataOffset
  5069. };
  5070. auto reflectArrayType = ResolveTypeDef(mCompiler->mReflectArrayType);
  5071. typeInstanceDataType = mBfIRBuilder->MapTypeInst(reflectArrayType->ToTypeInstance(), BfIRPopulateType_Full);
  5072. typeInstanceData = mBfIRBuilder->CreateConstStruct(typeInstanceDataType, arrayData);
  5073. }
  5074. }
  5075. BfIRValue typeDataVar;
  5076. if (needsTypeData)
  5077. {
  5078. typeDataVar = mBfIRBuilder->CreateGlobalVariable(typeInstanceDataType, true,
  5079. BfIRLinkageType_External, typeInstanceData, typeDataName);
  5080. if (mBfIRBuilder->DbgHasInfo())
  5081. {
  5082. mBfIRBuilder->DbgCreateGlobalVariable(mDICompileUnit, typeDataName, typeDataName, NULL, 0, mBfIRBuilder->DbgGetTypeInst(typeInstanceType->ToTypeInstance()), false, typeDataVar);
  5083. }
  5084. }
  5085. else
  5086. {
  5087. typeDataVar = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(mContext->mBfTypeType));
  5088. }
  5089. typeDataVar = mBfIRBuilder->CreateBitCast(typeDataVar, mBfIRBuilder->MapType(mContext->mBfTypeType));
  5090. mTypeDataRefs[typeInstance] = typeDataVar;
  5091. if (classVDataVar)
  5092. {
  5093. BF_ASSERT(!classVDataName.IsEmpty());
  5094. vData[0] = mBfIRBuilder->CreateBitCast(typeDataVar, voidPtrIRType);
  5095. auto classVDataConstDataType = mBfIRBuilder->GetSizedArrayType(voidPtrIRType, (int)vData.size());
  5096. auto classVDataConstData = mBfIRBuilder->CreateConstArray(classVDataConstDataType, vData);
  5097. mBfIRBuilder->GlobalVar_SetInitializer(classVDataVar, classVDataConstData);
  5098. if (mCompiler->mOptions.mObjectHasDebugFlags)
  5099. mBfIRBuilder->GlobalVar_SetAlignment(classVDataVar, 256);
  5100. else
  5101. mBfIRBuilder->GlobalVar_SetAlignment(classVDataVar, mContext->mBfClassVDataPtrType->mAlign);
  5102. if (mBfIRBuilder->DbgHasInfo())
  5103. {
  5104. BfType* voidType = GetPrimitiveType(BfTypeCode_None);
  5105. BfType* voidPtrType = CreatePointerType(voidType);
  5106. BfType* classVDataType = ResolveTypeDef(mCompiler->mClassVDataTypeDef);
  5107. BfIRMDNode arrayType = mBfIRBuilder->DbgCreateArrayType(vData.size() * mSystem->mPtrSize * 8, mSystem->mPtrSize * 8, mBfIRBuilder->DbgGetType(voidPtrType), vData.size());
  5108. mBfIRBuilder->DbgCreateGlobalVariable(mDICompileUnit, classVDataName, classVDataName, NULL, 0, arrayType, false, classVDataVar);
  5109. }
  5110. }
  5111. return typeDataVar;
  5112. }
  5113. BfIRValue BfModule::FixClassVData(BfIRValue value)
  5114. {
  5115. if (!mCompiler->mOptions.mObjectHasDebugFlags)
  5116. return value;
  5117. auto intptrValue = mBfIRBuilder->CreatePtrToInt(value, BfTypeCode_IntPtr);
  5118. auto maskedValue = mBfIRBuilder->CreateAnd(intptrValue, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, (uint64)~0xFFULL));
  5119. return mBfIRBuilder->CreateIntToPtr(maskedValue, mBfIRBuilder->GetType(value));
  5120. }
  5121. void BfModule::CheckStaticAccess(BfTypeInstance* typeInstance)
  5122. {
  5123. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  5124. //TODO: Create a hashset of these, we don't need to repeatedly call static ctors for a given type
  5125. // When we access classes with static constructors FROM a static constructor,
  5126. // we call that other class's static constructor first. Recursion cannot occur, since
  5127. // we simply ignore subsequent attempts to re-enter the constructor
  5128. if (!typeInstance->mHasStaticInitMethod)
  5129. return;
  5130. if ((mCurMethodInstance == NULL) || ((mCurMethodInstance->mMethodDef->mMethodType != BfMethodType_Ctor) || (!mCurMethodInstance->mMethodDef->mIsStatic)))
  5131. return;
  5132. if (mCurMethodInstance->mMethodInstanceGroup->mOwner == typeInstance)
  5133. return;
  5134. auto checkTypeDef = typeInstance->mTypeDef;
  5135. checkTypeDef->PopulateMemberSets();
  5136. BfMethodDef* nextMethodDef = NULL;
  5137. BfMemberSetEntry* entry;
  5138. if (checkTypeDef->mMethodSet.TryGetWith(String("__BfStaticCtor"), &entry))
  5139. nextMethodDef = (BfMethodDef*)entry->mMemberDef;
  5140. while (nextMethodDef != NULL)
  5141. {
  5142. auto checkMethod = nextMethodDef;
  5143. nextMethodDef = nextMethodDef->mNextWithSameName;
  5144. auto methodModule = GetMethodInstance(typeInstance, checkMethod, BfTypeVector());
  5145. if (methodModule)
  5146. {
  5147. auto methodInstance = methodModule.mMethodInstance;
  5148. if ((methodInstance != NULL) &&
  5149. (methodInstance->mMethodDef->mIsStatic) &&
  5150. (methodInstance->mMethodDef->mMethodType == BfMethodType_Ctor) &&
  5151. ((methodInstance->mChainType == BfMethodChainType_ChainHead) || (methodInstance->mChainType == BfMethodChainType_None)))
  5152. {
  5153. mBfIRBuilder->CreateCall(methodModule.mFunc, SizedArray<BfIRValue, 0>());
  5154. break;
  5155. }
  5156. }
  5157. }
  5158. }
  5159. BfIRFunction BfModule::GetIntrinsic(BfMethodInstance* methodInstance, bool reportFailure)
  5160. {
  5161. auto methodOwner = methodInstance->GetOwner();
  5162. auto methodDef = methodInstance->mMethodDef;
  5163. auto methodDeclaration = methodDef->GetMethodDeclaration();
  5164. bool hasExternSpecifier = (methodDeclaration != NULL) && (methodDeclaration->mExternSpecifier != NULL);
  5165. if (!hasExternSpecifier)
  5166. return BfIRFunction();
  5167. if (methodInstance->GetCustomAttributes() == NULL)
  5168. return BfIRFunction();
  5169. for (auto& customAttribute : methodInstance->GetCustomAttributes()->mAttributes)
  5170. {
  5171. String typeName = TypeToString(customAttribute.mType);
  5172. if ((typeName == "System.IntrinsicAttribute") && (customAttribute.mCtorArgs.size() > 0))
  5173. {
  5174. methodInstance->mIsIntrinsic = true;
  5175. auto constant = methodOwner->mConstHolder->GetConstant(customAttribute.mCtorArgs[0]);
  5176. String error;
  5177. if ((constant != NULL) && (BfIRConstHolder::IsInt(constant->mTypeCode)))
  5178. {
  5179. int stringId = constant->mInt32;
  5180. auto entry = mContext->mStringObjectIdMap[stringId];
  5181. int intrinId = BfIRCodeGen::GetIntrinsicId(entry.mString);
  5182. if (intrinId != -1)
  5183. {
  5184. if (intrinId == BfIRIntrinsic_Malloc)
  5185. {
  5186. return GetBuiltInFunc(BfBuiltInFuncType_Malloc);
  5187. }
  5188. else if (intrinId == BfIRIntrinsic_Free)
  5189. {
  5190. return GetBuiltInFunc(BfBuiltInFuncType_Free);
  5191. }
  5192. SizedArray<BfIRType, 2> paramTypes;
  5193. for (auto& param : methodInstance->mParams)
  5194. paramTypes.push_back(mBfIRBuilder->MapType(param.mResolvedType));
  5195. return mBfIRBuilder->GetIntrinsic(intrinId, paramTypes);
  5196. }
  5197. else if (reportFailure)
  5198. error = StrFormat("Unable to find intrinsic '%s'", entry.mString.c_str());
  5199. }
  5200. else if (reportFailure)
  5201. error = "Intrinsic name must be a constant string";
  5202. if (reportFailure)
  5203. {
  5204. BfAstNode* ref = methodDeclaration->mAttributes;
  5205. Fail(error, ref);
  5206. }
  5207. }
  5208. }
  5209. return BfIRFunction();
  5210. }
  5211. BfIRFunction BfModule::GetBuiltInFunc(BfBuiltInFuncType funcTypeId)
  5212. {
  5213. if (mBfIRBuilder->mIgnoreWrites)
  5214. return mBfIRBuilder->GetFakeFunction();
  5215. if (!mBuiltInFuncs[(int)funcTypeId])
  5216. {
  5217. SizedArray<BfIRType, 4> paramTypes;
  5218. auto nullPtrType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr));
  5219. auto intType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_IntPtr));
  5220. auto int32Type = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_Int32));
  5221. auto intPtrType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_IntPtr));
  5222. auto byteType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_Int8));
  5223. auto voidType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_None));
  5224. auto objType = mBfIRBuilder->MapType(mContext->mBfObjectType);
  5225. BfIRFunctionType funcType;
  5226. BfIRFunction func;
  5227. switch (funcTypeId)
  5228. {
  5229. case BfBuiltInFuncType_PrintF:
  5230. funcType = mBfIRBuilder->CreateFunctionType(int32Type, paramTypes, true);
  5231. func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, "PrintF");
  5232. break;
  5233. case BfBuiltInFuncType_Malloc:
  5234. {
  5235. if (mCompiler->mOptions.mDebugAlloc)
  5236. {
  5237. func = GetInternalMethod("Dbg_RawAlloc", 1).mFunc;
  5238. }
  5239. else
  5240. {
  5241. String funcName = mCompiler->mOptions.mMallocLinkName;
  5242. if (funcName.IsEmpty())
  5243. funcName = "malloc";
  5244. func = mBfIRBuilder->GetFunction(funcName);
  5245. if (!func)
  5246. {
  5247. paramTypes.clear();
  5248. paramTypes.push_back(intType);
  5249. funcType = mBfIRBuilder->CreateFunctionType(nullPtrType, paramTypes);
  5250. func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, funcName);
  5251. mBfIRBuilder->Func_SetParamName(func, 1, "size");
  5252. }
  5253. }
  5254. }
  5255. break;
  5256. case BfBuiltInFuncType_Free:
  5257. {
  5258. if (mCompiler->mOptions.mDebugAlloc)
  5259. {
  5260. func = GetInternalMethod("Dbg_RawFree").mFunc;
  5261. }
  5262. else
  5263. {
  5264. String funcName = mCompiler->mOptions.mFreeLinkName;
  5265. if (funcName.IsEmpty())
  5266. funcName = "free";
  5267. func = mBfIRBuilder->GetFunction(funcName);
  5268. if (!func)
  5269. {
  5270. paramTypes.clear();
  5271. paramTypes.push_back(nullPtrType);
  5272. funcType = mBfIRBuilder->CreateFunctionType(voidType, paramTypes);
  5273. func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, funcName);
  5274. mBfIRBuilder->Func_SetParamName(func, 1, "ptr");
  5275. }
  5276. }
  5277. }
  5278. break;
  5279. case BfBuiltInFuncType_LoadSharedLibraries:
  5280. paramTypes.clear();
  5281. funcType = mBfIRBuilder->CreateFunctionType(voidType, paramTypes);
  5282. func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, "BfLoadSharedLibraries");
  5283. break;
  5284. default: break;
  5285. }
  5286. mBuiltInFuncs[(int)funcTypeId] = func;
  5287. return func;
  5288. }
  5289. return mBuiltInFuncs[(int)funcTypeId];
  5290. }
  5291. void BfModule::ResolveGenericParamConstraints(BfGenericParamInstance* genericParamInstance, bool isUnspecialized)
  5292. {
  5293. BfGenericParamDef* genericParamDef = genericParamInstance->GetGenericParamDef();
  5294. BfExternalConstraintDef* externConstraintDef = genericParamInstance->GetExternConstraintDef();
  5295. BfConstraintDef* constraintDef = genericParamInstance->GetConstraintDef();
  5296. BfType* startingTypeConstraint = genericParamInstance->mTypeConstraint;
  5297. BfAutoComplete* bfAutocomplete = NULL;
  5298. if ((mCompiler->mResolvePassData != NULL) && (isUnspecialized))
  5299. bfAutocomplete = mCompiler->mResolvePassData->mAutoComplete;
  5300. if ((bfAutocomplete != NULL) && (genericParamDef != NULL))
  5301. {
  5302. for (int nameIdx = 0; nameIdx < (int)genericParamDef->mNameNodes.size(); nameIdx++)
  5303. {
  5304. auto nameNode = genericParamDef->mNameNodes[nameIdx];
  5305. if (bfAutocomplete->IsAutocompleteNode(nameNode))
  5306. {
  5307. String filter = nameNode->ToString();
  5308. bfAutocomplete->mInsertStartIdx = nameNode->GetSrcStart();
  5309. bfAutocomplete->mInsertEndIdx = nameNode->GetSrcEnd();
  5310. if (nameIdx != 0)
  5311. {
  5312. bfAutocomplete->AddEntry(AutoCompleteEntry("generic", nameNode->ToString().c_str()), filter);
  5313. }
  5314. }
  5315. }
  5316. }
  5317. for (auto constraint : constraintDef->mConstraints)
  5318. {
  5319. if (auto opConstraint = BfNodeDynCast<BfGenericOperatorConstraint>(constraint))
  5320. {
  5321. BfGenericOperatorConstraintInstance opConstraintInstance;
  5322. if (opConstraint->mLeftType != NULL)
  5323. {
  5324. if (bfAutocomplete != NULL)
  5325. bfAutocomplete->CheckTypeRef(opConstraint->mLeftType, false);
  5326. opConstraintInstance.mLeftType = ResolveTypeRef(opConstraint->mLeftType);
  5327. if (opConstraintInstance.mLeftType == NULL)
  5328. continue;
  5329. }
  5330. if (opConstraint->mRightType == NULL)
  5331. {
  5332. // We had a failure in parsing
  5333. continue;
  5334. }
  5335. if (opConstraint->mRightType != NULL)
  5336. {
  5337. if (bfAutocomplete != NULL)
  5338. bfAutocomplete->CheckTypeRef(opConstraint->mRightType, false);
  5339. opConstraintInstance.mRightType = ResolveTypeRef(opConstraint->mRightType);
  5340. if (opConstraintInstance.mRightType == NULL)
  5341. continue;
  5342. }
  5343. if (opConstraint->mOpToken == NULL)
  5344. {
  5345. FailAfter("Missing operator", (opConstraint->mLeftType != NULL) ? (BfAstNode*)opConstraint->mLeftType : (BfAstNode*)opConstraint->mOperatorToken);
  5346. continue;
  5347. }
  5348. if (opConstraint->mLeftType != NULL)
  5349. {
  5350. if (opConstraint->mRightType == NULL)
  5351. {
  5352. // Parse should have failed
  5353. continue;
  5354. }
  5355. opConstraintInstance.mBinaryOp = BfTokenToBinaryOp(opConstraint->mOpToken->mToken);
  5356. if (opConstraintInstance.mBinaryOp == BfBinaryOp_None)
  5357. {
  5358. Fail("Invalid binary operator", opConstraint->mOpToken);
  5359. continue;
  5360. }
  5361. }
  5362. else if ((opConstraint->mOpToken->mToken == BfToken_Implicit) || (opConstraint->mOpToken->mToken == BfToken_Explicit))
  5363. {
  5364. opConstraintInstance.mCastToken = opConstraint->mOpToken->mToken;
  5365. }
  5366. else
  5367. {
  5368. opConstraintInstance.mUnaryOp = BfTokenToUnaryOp(opConstraint->mOpToken->mToken);
  5369. if (opConstraintInstance.mUnaryOp == BfBinaryOp_None)
  5370. {
  5371. Fail("Invalid unary operator", opConstraint->mOpToken);
  5372. continue;
  5373. }
  5374. }
  5375. if ((constraintDef->mGenericParamFlags & BfGenericParamFlag_Equals) != 0)
  5376. genericParamInstance->mGenericParamFlags = (BfGenericParamFlags)(genericParamInstance->mGenericParamFlags | BfGenericParamFlag_Equals_Op);
  5377. genericParamInstance->mOperatorConstraints.Add(opConstraintInstance);
  5378. continue;
  5379. }
  5380. auto constraintTypeRef = BfNodeDynCast<BfTypeReference>(constraint);
  5381. if (bfAutocomplete != NULL)
  5382. bfAutocomplete->CheckTypeRef(constraintTypeRef, true);
  5383. //TODO: Constraints may refer to other generic params (of either type or method)
  5384. // TO allow resolution, perhaps move this generic param initalization into GetMethodInstance (passing a genericPass bool)
  5385. auto constraintType = ResolveTypeRef(constraintTypeRef, BfPopulateType_Declaration, BfResolveTypeRefFlag_AllowGenericMethodParamConstValue);
  5386. if (constraintType != NULL)
  5387. {
  5388. if ((constraintDef->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  5389. {
  5390. bool isValidTypeCode = false;
  5391. BfTypeCode typeCode = BfTypeCode_None;
  5392. if (constraintType->IsTypedPrimitive())
  5393. {
  5394. auto underlyingType = constraintType->GetUnderlyingType();
  5395. if (underlyingType->IsPrimitiveType())
  5396. typeCode = ((BfPrimitiveType*)underlyingType)->mTypeDef->mTypeCode;
  5397. }
  5398. if (constraintType->IsPrimitiveType())
  5399. typeCode = ((BfPrimitiveType*)constraintType)->mTypeDef->mTypeCode;
  5400. switch (typeCode)
  5401. {
  5402. case BfTypeCode_Int8:
  5403. case BfTypeCode_UInt8:
  5404. case BfTypeCode_Int16:
  5405. case BfTypeCode_UInt16:
  5406. case BfTypeCode_Int32:
  5407. case BfTypeCode_UInt32:
  5408. case BfTypeCode_Int64:
  5409. case BfTypeCode_UInt64:
  5410. case BfTypeCode_IntPtr:
  5411. case BfTypeCode_UIntPtr:
  5412. case BfTypeCode_IntUnknown:
  5413. case BfTypeCode_UIntUnknown:
  5414. case BfTypeCode_Single:
  5415. case BfTypeCode_Double:
  5416. case BfTypeCode_Char8:
  5417. case BfTypeCode_Char16:
  5418. case BfTypeCode_Char32:
  5419. isValidTypeCode = true;
  5420. break;
  5421. default: break;
  5422. }
  5423. if (isValidTypeCode)
  5424. {
  5425. genericParamInstance->mTypeConstraint = constraintType;
  5426. }
  5427. else
  5428. {
  5429. Fail("Const constraint must be a primitive type", constraintTypeRef);
  5430. }
  5431. }
  5432. else
  5433. {
  5434. bool checkEquality = false;
  5435. if (constraintType->IsPrimitiveType())
  5436. {
  5437. if (isUnspecialized)
  5438. {
  5439. Fail("Primitive constraints are not allowed unless preceded with 'const'", constraintTypeRef);
  5440. continue;
  5441. }
  5442. checkEquality = true;
  5443. }
  5444. if (constraintType->IsArray())
  5445. {
  5446. if (isUnspecialized)
  5447. {
  5448. 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);
  5449. continue;
  5450. }
  5451. checkEquality = true;
  5452. }
  5453. if (constraintType->IsGenericParam())
  5454. {
  5455. continue;
  5456. }
  5457. if ((!constraintType->IsTypeInstance()) && (!constraintType->IsSizedArray()))
  5458. {
  5459. if (isUnspecialized)
  5460. {
  5461. Fail(StrFormat("Type '%s' is not allowed as a generic constraint", TypeToString(constraintType).c_str()), constraintTypeRef);
  5462. continue;
  5463. }
  5464. checkEquality = true;
  5465. }
  5466. if ((constraintDef->mGenericParamFlags & BfGenericParamFlag_Equals) != 0)
  5467. {
  5468. genericParamInstance->mGenericParamFlags = (BfGenericParamFlags)(genericParamInstance->mGenericParamFlags | BfGenericParamFlag_Equals_Type);
  5469. checkEquality = true;
  5470. }
  5471. if (checkEquality)
  5472. {
  5473. genericParamInstance->mTypeConstraint = constraintType;
  5474. }
  5475. else if (constraintType->IsInterface())
  5476. {
  5477. if ((constraintDef->mGenericParamFlags & BfGenericParamFlag_Equals) != 0)
  5478. genericParamInstance->mGenericParamFlags = (BfGenericParamFlags)(genericParamInstance->mGenericParamFlags | BfGenericParamFlag_Equals_IFace);
  5479. genericParamInstance->mInterfaceConstraints.push_back(constraintType->ToTypeInstance());
  5480. }
  5481. else
  5482. {
  5483. auto constraintTypeInst = constraintType->ToTypeInstance();
  5484. if (genericParamInstance->mTypeConstraint != NULL)
  5485. {
  5486. if ((constraintTypeInst != NULL) && (TypeIsSubTypeOf(constraintTypeInst, genericParamInstance->mTypeConstraint->ToTypeInstance(), false)))
  5487. {
  5488. // Allow more specific type
  5489. genericParamInstance->mTypeConstraint = constraintTypeInst;
  5490. }
  5491. else if ((constraintTypeInst != NULL) && (TypeIsSubTypeOf(genericParamInstance->mTypeConstraint->ToTypeInstance(), constraintTypeInst, false)))
  5492. {
  5493. // Silently ignore less-specific type
  5494. if ((startingTypeConstraint != NULL) && (startingTypeConstraint->IsDelegate()))
  5495. {
  5496. // 'System.Delegate' means that we are expecting an actual delegate instance. Simulate this by wanting a class.
  5497. genericParamInstance->mGenericParamFlags |= BfGenericParamFlag_Class;
  5498. }
  5499. }
  5500. else
  5501. {
  5502. Fail("Only one concrete type constraint may be specified", constraintTypeRef);
  5503. return;
  5504. }
  5505. }
  5506. else
  5507. genericParamInstance->mTypeConstraint = constraintType;
  5508. }
  5509. }
  5510. }
  5511. }
  5512. if (((constraintDef->mGenericParamFlags & BfGenericParamFlag_Const) != 0) &&
  5513. (genericParamInstance->mTypeConstraint == NULL))
  5514. genericParamInstance->mTypeConstraint = GetPrimitiveType(BfTypeCode_IntPtr);
  5515. }
  5516. String BfModule::GenericParamSourceToString(const BfGenericParamSource & genericParamSource)
  5517. {
  5518. if (genericParamSource.mMethodInstance != NULL)
  5519. {
  5520. auto methodInst = GetUnspecializedMethodInstance(genericParamSource.mMethodInstance);
  5521. SetAndRestoreValue<BfMethodInstance*> prevMethodInst(mCurMethodInstance, methodInst);
  5522. return MethodToString(methodInst);
  5523. }
  5524. else
  5525. {
  5526. auto typeInst = GetUnspecializedTypeInstance(genericParamSource.mTypeInstance);
  5527. SetAndRestoreValue<BfMethodInstance*> prevMethodInst(mCurMethodInstance, NULL);
  5528. SetAndRestoreValue<BfTypeInstance*> prevTypeInst(mCurTypeInstance, typeInst);
  5529. return TypeToString(typeInst);
  5530. }
  5531. }
  5532. bool BfModule::CheckGenericConstraints(const BfGenericParamSource& genericParamSource, BfType* checkArgType, BfAstNode* checkArgTypeRef, BfGenericParamInstance* genericParamInst, BfTypeVector* methodGenericArgs, BfError** errorOut)
  5533. {
  5534. bool ignoreErrors = mIgnoreErrors || (errorOut == NULL) ||
  5535. ((genericParamSource.mMethodInstance == NULL) && (genericParamSource.mTypeInstance == NULL));
  5536. BfType* origCheckArgType = checkArgType;
  5537. if (origCheckArgType->IsRef())
  5538. origCheckArgType = origCheckArgType->GetUnderlyingType();
  5539. bool argMayBeReferenceType = false;
  5540. int checkGenericParamFlags = 0;
  5541. if (checkArgType->IsGenericParam())
  5542. {
  5543. auto checkGenericParamInst = GetGenericParamInstance((BfGenericParamType*)checkArgType);
  5544. checkGenericParamFlags = checkGenericParamInst->mGenericParamFlags;
  5545. if (checkGenericParamInst->mTypeConstraint != NULL)
  5546. checkArgType = checkGenericParamInst->mTypeConstraint;
  5547. if ((checkGenericParamFlags & (BfGenericParamFlag_Struct | BfGenericParamFlag_StructPtr)) != 0)
  5548. {
  5549. argMayBeReferenceType = false;
  5550. }
  5551. else
  5552. {
  5553. argMayBeReferenceType = true;
  5554. }
  5555. }
  5556. if (checkArgType->IsObjectOrInterface())
  5557. argMayBeReferenceType = true;
  5558. BfTypeInstance* typeConstraintInst = NULL;
  5559. if (genericParamInst->mTypeConstraint != NULL)
  5560. typeConstraintInst = genericParamInst->mTypeConstraint->ToTypeInstance();
  5561. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Struct) &&
  5562. ((checkGenericParamFlags & (BfGenericParamFlag_Struct | BfGenericParamFlag_Var)) == 0) && (!checkArgType->IsValueType()))
  5563. {
  5564. if (!ignoreErrors)
  5565. *errorOut = Fail(StrFormat("The type '%s' must be a value type in order to use it as parameter '%s' for '%s'",
  5566. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  5567. return false;
  5568. }
  5569. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_StructPtr) &&
  5570. ((checkGenericParamFlags & (BfGenericParamFlag_StructPtr | BfGenericParamFlag_Var)) == 0) && (!checkArgType->IsPointer()))
  5571. {
  5572. if (!ignoreErrors)
  5573. *errorOut = Fail(StrFormat("The type '%s' must be a pointer type in order to use it as parameter '%s' for '%s'",
  5574. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  5575. return false;
  5576. }
  5577. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Class) &&
  5578. ((checkGenericParamFlags & (BfGenericParamFlag_Class | BfGenericParamFlag_Var)) == 0) && (!argMayBeReferenceType))
  5579. {
  5580. if (!ignoreErrors)
  5581. *errorOut = Fail(StrFormat("The type '%s' must be a reference type in order to use it as parameter '%s' for '%s'",
  5582. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  5583. return false;
  5584. }
  5585. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  5586. {
  5587. if (((checkGenericParamFlags & BfGenericParamFlag_Const) == 0) && (!checkArgType->IsConstExprValue()))
  5588. {
  5589. if (!ignoreErrors)
  5590. *errorOut = Fail(StrFormat("The type '%s' must be a const value in order to use it as parameter '%s' for '%s'",
  5591. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  5592. return false;
  5593. }
  5594. }
  5595. else
  5596. {
  5597. if (checkArgType->IsConstExprValue())
  5598. {
  5599. if (!ignoreErrors)
  5600. *errorOut = Fail(StrFormat("The value '%s' cannot be used for generic type parameter '%s' for '%s'",
  5601. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  5602. return false;
  5603. }
  5604. }
  5605. if ((genericParamInst->mInterfaceConstraints.IsEmpty()) && (genericParamInst->mOperatorConstraints.IsEmpty()) && (genericParamInst->mTypeConstraint == NULL))
  5606. return true;
  5607. if (checkArgType->IsPointer())
  5608. {
  5609. auto ptrType = (BfPointerType*)checkArgType;
  5610. checkArgType = ptrType->mElementType;
  5611. }
  5612. if (genericParamInst->mTypeConstraint != NULL)
  5613. {
  5614. bool constraintMatched = false;
  5615. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  5616. {
  5617. if (checkArgType->IsConstExprValue())
  5618. {
  5619. auto constExprValueType = (BfConstExprValueType*)checkArgType;
  5620. if (genericParamInst->mTypeConstraint->IsPrimitiveType())
  5621. {
  5622. auto primType = (BfPrimitiveType*)genericParamInst->mTypeConstraint;
  5623. // Let either an exact typematch or an undef pass through. Eventually instead of undefs we may want to do
  5624. // actual expression comparisons, but we are overly permissive now and then we may fail on specialization
  5625. if ((constExprValueType->mValue.mTypeCode != primType->mTypeDef->mTypeCode) &&
  5626. (constExprValueType->mValue.mTypeCode != BfTypeCode_Let) &&
  5627. (primType->mTypeDef->mTypeCode != BfTypeCode_Let))
  5628. {
  5629. if (BfIRConstHolder::IsInt(constExprValueType->mValue.mTypeCode))
  5630. {
  5631. if (BfIRConstHolder::IsInt(primType->mTypeDef->mTypeCode))
  5632. {
  5633. if (!mCompiler->mSystem->DoesLiteralFit(primType->mTypeDef->mTypeCode, constExprValueType->mValue.mInt64))
  5634. {
  5635. if (!ignoreErrors)
  5636. *errorOut = Fail(StrFormat("Const generic argument '%s', declared with const '%lld', does not fit into const constraint '%s' for '%s'", genericParamInst->GetName().c_str(),
  5637. constExprValueType->mValue.mInt64, TypeToString(genericParamInst->mTypeConstraint).c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  5638. return false;
  5639. }
  5640. }
  5641. else
  5642. {
  5643. if (!ignoreErrors)
  5644. *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(),
  5645. constExprValueType->mValue.mInt64, TypeToString(genericParamInst->mTypeConstraint).c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  5646. return false;
  5647. }
  5648. }
  5649. else
  5650. {
  5651. if (BfIRConstHolder::IsInt(primType->mTypeDef->mTypeCode))
  5652. {
  5653. char valStr[64];
  5654. ExactMinimalDoubleToStr(constExprValueType->mValue.mDouble, valStr);
  5655. if (!ignoreErrors)
  5656. *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(),
  5657. valStr, TypeToString(genericParamInst->mTypeConstraint).c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  5658. return false;
  5659. }
  5660. }
  5661. }
  5662. }
  5663. }
  5664. }
  5665. else
  5666. {
  5667. BfType* convCheckConstraint = genericParamInst->mTypeConstraint;
  5668. if ((convCheckConstraint->IsUnspecializedType()) && (methodGenericArgs != NULL))
  5669. convCheckConstraint = ResolveGenericType(convCheckConstraint, *methodGenericArgs);
  5670. if ((checkArgType->IsMethodRef()) && (convCheckConstraint->IsDelegate()))
  5671. {
  5672. auto methodRefType = (BfMethodRefType*)checkArgType;
  5673. auto invokeMethod = GetRawMethodInstanceAtIdx(convCheckConstraint->ToTypeInstance(), 0, "Invoke");
  5674. BfExprEvaluator exprEvaluator(this);
  5675. if (exprEvaluator.IsExactMethodMatch(methodRefType->mMethodRef, invokeMethod))
  5676. constraintMatched = true;
  5677. }
  5678. else if (CanImplicitlyCast(GetFakeTypedValue(checkArgType), convCheckConstraint))
  5679. {
  5680. constraintMatched = true;
  5681. }
  5682. else if (origCheckArgType->IsWrappableType())
  5683. {
  5684. if (origCheckArgType->IsSizedArray())
  5685. {
  5686. auto sizedArrayType = (BfSizedArrayType*)origCheckArgType;
  5687. if (convCheckConstraint->IsGenericTypeInstance())
  5688. {
  5689. auto convCheckConstraintInst = (BfGenericTypeInstance*)convCheckConstraint;
  5690. if (convCheckConstraintInst->mTypeDef == mCompiler->mSizedArrayTypeDef)
  5691. {
  5692. if (convCheckConstraintInst->mTypeGenericArguments[0] == sizedArrayType->mElementType)
  5693. {
  5694. auto constExprValueType = (BfConstExprValueType*)convCheckConstraintInst->mTypeGenericArguments[1];
  5695. if (sizedArrayType->mElementCount == constExprValueType->mValue.mInt64)
  5696. constraintMatched = true;
  5697. }
  5698. }
  5699. }
  5700. }
  5701. if (!constraintMatched)
  5702. {
  5703. BfType* wrappedStructType = GetWrappedStructType(origCheckArgType, false);
  5704. if (CanImplicitlyCast(GetFakeTypedValue(wrappedStructType), convCheckConstraint))
  5705. constraintMatched = true;
  5706. }
  5707. }
  5708. if (!constraintMatched)
  5709. {
  5710. if (!ignoreErrors)
  5711. *errorOut = Fail(StrFormat("Generic argument '%s', declared to be '%s' for '%s', must derive from '%s'", genericParamInst->GetName().c_str(),
  5712. TypeToString(origCheckArgType).c_str(), GenericParamSourceToString(genericParamSource).c_str(), TypeToString(convCheckConstraint).c_str(),
  5713. TypeToString(genericParamInst->mTypeConstraint).c_str()), checkArgTypeRef);
  5714. return false;
  5715. }
  5716. }
  5717. }
  5718. if ((genericParamInst->mInterfaceConstraints.size() > 0) && (origCheckArgType->IsInterface()))
  5719. {
  5720. PopulateType(origCheckArgType);
  5721. auto checkTypeInst = origCheckArgType->ToTypeInstance();
  5722. if (checkTypeInst->mTypeDef->mIsConcrete)
  5723. {
  5724. if (!ignoreErrors)
  5725. *errorOut = Fail(StrFormat("Generic argument '%s', declared to be concrete interface '%s' for '%s', must be a concrete type", genericParamInst->GetName().c_str(),
  5726. TypeToString(origCheckArgType).c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  5727. return false;
  5728. }
  5729. }
  5730. for (auto checkConstraint : genericParamInst->mInterfaceConstraints)
  5731. {
  5732. BfType* convCheckConstraint = checkConstraint;
  5733. if (convCheckConstraint->IsUnspecializedType())
  5734. convCheckConstraint = ResolveGenericType(convCheckConstraint, *methodGenericArgs);
  5735. BfTypeInstance* typeConstraintInst = convCheckConstraint->ToTypeInstance();
  5736. bool implementsInterface = false;
  5737. if (origCheckArgType != checkArgType)
  5738. {
  5739. implementsInterface = CanImplicitlyCast(origCheckArgType, convCheckConstraint);
  5740. }
  5741. if (!implementsInterface)
  5742. implementsInterface = CanImplicitlyCast(checkArgType, convCheckConstraint);
  5743. if ((!implementsInterface) && (origCheckArgType->IsWrappableType()))
  5744. {
  5745. BfTypeInstance* wrappedStructType = GetWrappedStructType(origCheckArgType, false);
  5746. if (TypeIsSubTypeOf(wrappedStructType, typeConstraintInst))
  5747. implementsInterface = true;
  5748. }
  5749. if ((!implementsInterface) && (origCheckArgType->IsTypedPrimitive()))
  5750. {
  5751. auto underlyingType = origCheckArgType->GetUnderlyingType();
  5752. BfTypeInstance* wrappedStructType = GetWrappedStructType(underlyingType, false);
  5753. if (TypeIsSubTypeOf(wrappedStructType, typeConstraintInst))
  5754. implementsInterface = true;
  5755. }
  5756. if (!implementsInterface)
  5757. {
  5758. if (!ignoreErrors)
  5759. *errorOut = Fail(StrFormat("Generic argument '%s', declared to be '%s' for '%s', must implement '%s'", genericParamInst->GetName().c_str(),
  5760. TypeToString(origCheckArgType).c_str(), GenericParamSourceToString(genericParamSource).c_str(), TypeToString(checkConstraint).c_str()), checkArgTypeRef);
  5761. return false;
  5762. }
  5763. }
  5764. for (auto& checkOpConstraint : genericParamInst->mOperatorConstraints)
  5765. {
  5766. auto leftType = checkOpConstraint.mLeftType;
  5767. if ((leftType != NULL) && (leftType->IsUnspecializedType()))
  5768. leftType = ResolveGenericType(leftType, *methodGenericArgs);
  5769. if (leftType != NULL)
  5770. leftType = FixIntUnknown(leftType);
  5771. auto rightType = checkOpConstraint.mRightType;
  5772. if ((rightType != NULL) && (rightType->IsUnspecializedType()))
  5773. rightType = ResolveGenericType(rightType, *methodGenericArgs);
  5774. if (rightType != NULL)
  5775. rightType = FixIntUnknown(rightType);
  5776. if (checkOpConstraint.mBinaryOp != BfBinaryOp_None)
  5777. {
  5778. BfExprEvaluator exprEvaluator(this);
  5779. BfTypedValue leftValue(mBfIRBuilder->GetFakeVal(), leftType);
  5780. BfTypedValue rightValue(mBfIRBuilder->GetFakeVal(), rightType);
  5781. //
  5782. {
  5783. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, true);
  5784. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, true);
  5785. exprEvaluator.PerformBinaryOperation(NULL, NULL, checkOpConstraint.mBinaryOp, NULL, BfBinOpFlag_NoClassify, leftValue, rightValue);
  5786. }
  5787. if ((exprEvaluator.mResult == NULL) ||
  5788. (!CanImplicitlyCast(exprEvaluator.mResult, origCheckArgType)))
  5789. {
  5790. if (!ignoreErrors)
  5791. *errorOut = Fail(StrFormat("Generic argument '%s', declared to be '%s' for '%s', must result from binary operation '%s %s %s'", genericParamInst->GetName().c_str(),
  5792. TypeToString(origCheckArgType).c_str(), GenericParamSourceToString(genericParamSource).c_str(),
  5793. TypeToString(leftType).c_str(), BfGetOpName(checkOpConstraint.mBinaryOp), TypeToString(rightType).c_str()
  5794. ), checkArgTypeRef);
  5795. return false;
  5796. }
  5797. }
  5798. else
  5799. {
  5800. BfTypedValue rightValue(mBfIRBuilder->GetFakeVal(), rightType);
  5801. StringT<128> failedOpName;
  5802. if (checkOpConstraint.mCastToken == BfToken_Implicit)
  5803. {
  5804. if (!CanImplicitlyCast(rightValue, origCheckArgType, BfCastFlags_SilentFail))
  5805. failedOpName = "implicit conversion from '";
  5806. }
  5807. else
  5808. {
  5809. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, true);
  5810. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, true);
  5811. if (checkOpConstraint.mCastToken == BfToken_Explicit)
  5812. {
  5813. if (!CastToValue(NULL, rightValue, origCheckArgType, (BfCastFlags)(BfCastFlags_Explicit | BfCastFlags_SilentFail)))
  5814. failedOpName = "explicit conversion from '";
  5815. }
  5816. else
  5817. {
  5818. BfExprEvaluator exprEvaluator(this);
  5819. exprEvaluator.mResult = rightValue;
  5820. exprEvaluator.PerformUnaryOperation(NULL, checkOpConstraint.mUnaryOp, NULL);
  5821. if ((exprEvaluator.mResult == NULL) ||
  5822. (!CanImplicitlyCast(exprEvaluator.mResult, origCheckArgType)))
  5823. {
  5824. failedOpName += "unary operation '";
  5825. failedOpName += BfGetOpName(checkOpConstraint.mUnaryOp);
  5826. }
  5827. }
  5828. }
  5829. if (!failedOpName.IsEmpty())
  5830. {
  5831. if (!ignoreErrors)
  5832. *errorOut = Fail(StrFormat("Generic argument '%s', declared to be '%s' for '%s', must result from %s%s'", genericParamInst->GetName().c_str(),
  5833. TypeToString(origCheckArgType).c_str(), GenericParamSourceToString(genericParamSource).c_str(),
  5834. failedOpName.c_str(), TypeToString(rightType).c_str()
  5835. ), checkArgTypeRef);
  5836. return false;
  5837. }
  5838. }
  5839. }
  5840. return true;
  5841. }
  5842. BfGenericParamType* BfModule::GetGenericParamType(BfGenericParamKind paramKind, int paramIdx)
  5843. {
  5844. if (paramIdx < (int)mContext->mGenericParamTypes[paramKind].size())
  5845. {
  5846. auto genericParamType = mContext->mGenericParamTypes[paramKind][paramIdx];
  5847. return genericParamType;
  5848. }
  5849. auto genericParamType = new BfGenericParamType();
  5850. genericParamType->mContext = mContext;
  5851. genericParamType->mGenericParamKind = paramKind;
  5852. genericParamType->mGenericParamIdx = paramIdx;
  5853. PopulateType(genericParamType);
  5854. BF_ASSERT(paramIdx == (int)mContext->mGenericParamTypes[paramKind].size());
  5855. mContext->mGenericParamTypes[paramKind].push_back(genericParamType);
  5856. BfResolvedTypeSet::LookupContext lookupCtx;
  5857. lookupCtx.mModule = this;
  5858. BfResolvedTypeSet::Entry* typeEntry = NULL;
  5859. auto inserted = mContext->mResolvedTypes.Insert(genericParamType, &lookupCtx, &typeEntry);
  5860. BF_ASSERT(inserted);
  5861. typeEntry->mValue = genericParamType;
  5862. return genericParamType;
  5863. }
  5864. static int sValueFromExprIdx = 0;
  5865. BfTypedValue BfModule::FlushNullConditional(BfTypedValue result, bool ignoreNullable)
  5866. {
  5867. auto pendingNullCond = mCurMethodState->mPendingNullConditional;
  5868. if ((result) && (!ignoreNullable))
  5869. {
  5870. auto notNullBB = mBfIRBuilder->GetInsertBlock();
  5871. //TODO: Make this work, needed for 'void' and such
  5872. BfType* nullableType = NULL;
  5873. if ((result.mType->IsValueType()) && (!result.mType->IsNullable()))
  5874. {
  5875. BfTypeVector typeVec;
  5876. typeVec.push_back(result.mType);
  5877. nullableType = ResolveTypeDef(mCompiler->mNullableTypeDef, typeVec);
  5878. BF_ASSERT(nullableType != NULL);
  5879. }
  5880. // Go back to start and do any setup we need
  5881. mBfIRBuilder->SetInsertPoint(pendingNullCond->mPrevBB);
  5882. BfTypedValue nullableTypedValue;
  5883. if (nullableType != NULL)
  5884. {
  5885. nullableTypedValue = BfTypedValue(CreateAlloca(nullableType, true, "nullCond.nullable"), nullableType, true);
  5886. mBfIRBuilder->CreateMemSet(nullableTypedValue.mValue, GetConstValue(0, GetPrimitiveType(BfTypeCode_Int8)),
  5887. GetConstValue(nullableType->mSize), nullableType->mAlign);
  5888. }
  5889. mBfIRBuilder->CreateBr(pendingNullCond->mCheckBB);
  5890. // Now that we have the nullableTypedValue we can set that, or just jump if we didn't need it
  5891. mBfIRBuilder->SetInsertPoint(notNullBB);
  5892. result = LoadValue(result);
  5893. if (nullableTypedValue)
  5894. {
  5895. auto elementType = nullableType->GetUnderlyingType();
  5896. if (elementType->IsValuelessType())
  5897. {
  5898. BfIRValue ptrValue = mBfIRBuilder->CreateInBoundsGEP(nullableTypedValue.mValue, 0, 1); // mHasValue
  5899. mBfIRBuilder->CreateStore(GetConstValue(1, GetPrimitiveType(BfTypeCode_Boolean)), ptrValue);
  5900. result = nullableTypedValue;
  5901. }
  5902. else
  5903. {
  5904. BfIRValue ptrValue = mBfIRBuilder->CreateInBoundsGEP(nullableTypedValue.mValue, 0, 1); // mValue
  5905. mBfIRBuilder->CreateStore(result.mValue, ptrValue);
  5906. ptrValue = mBfIRBuilder->CreateInBoundsGEP(nullableTypedValue.mValue, 0, 2); // mHasValue
  5907. mBfIRBuilder->CreateStore(GetConstValue(1, GetPrimitiveType(BfTypeCode_Boolean)), ptrValue);
  5908. result = nullableTypedValue;
  5909. }
  5910. }
  5911. mBfIRBuilder->CreateBr(pendingNullCond->mDoneBB);
  5912. AddBasicBlock(pendingNullCond->mDoneBB);
  5913. if (nullableType == NULL)
  5914. {
  5915. auto phi = mBfIRBuilder->CreatePhi(mBfIRBuilder->MapType(result.mType), 2);
  5916. mBfIRBuilder->AddPhiIncoming(phi, result.mValue, notNullBB);
  5917. mBfIRBuilder->AddPhiIncoming(phi, GetDefaultValue(result.mType), pendingNullCond->mCheckBB);
  5918. result.mValue = phi;
  5919. }
  5920. }
  5921. else
  5922. {
  5923. mBfIRBuilder->CreateBr(pendingNullCond->mDoneBB);
  5924. mBfIRBuilder->SetInsertPoint(pendingNullCond->mPrevBB);
  5925. mBfIRBuilder->CreateBr(pendingNullCond->mCheckBB);
  5926. AddBasicBlock(pendingNullCond->mDoneBB);
  5927. }
  5928. delete mCurMethodState->mPendingNullConditional;
  5929. mCurMethodState->mPendingNullConditional = NULL;
  5930. return result;
  5931. }
  5932. BF_NOINLINE void BfModule::EvaluateWithNewScope(BfExprEvaluator& exprEvaluator, BfExpression* expr, BfEvalExprFlags flags)
  5933. {
  5934. BfScopeData newScope;
  5935. newScope.mOuterIsConditional = true;
  5936. newScope.mAllowTargeting = false;
  5937. mCurMethodState->AddScope(&newScope);
  5938. NewScopeState();
  5939. exprEvaluator.mBfEvalExprFlags = flags;
  5940. exprEvaluator.Evaluate(expr, (flags & BfEvalExprFlags_PropogateNullConditional) != 0, (flags & BfEvalExprFlags_IgnoreNullConditional) != 0, true);
  5941. RestoreScopeState();
  5942. }
  5943. BfTypedValue BfModule::CreateValueFromExpression(BfExprEvaluator& exprEvaluator, BfExpression* expr, BfType* wantTypeRef, BfEvalExprFlags flags, BfType** outOrigType)
  5944. {
  5945. //
  5946. {
  5947. BP_ZONE("CreateValueFromExpression:CheckStack");
  5948. StackHelper stackHelper;
  5949. if (!stackHelper.CanStackExpand(64 * 1024))
  5950. {
  5951. BfTypedValue result;
  5952. if (!stackHelper.Execute([&]()
  5953. {
  5954. result = CreateValueFromExpression(exprEvaluator, expr, wantTypeRef, flags, outOrigType);
  5955. }))
  5956. {
  5957. Fail("Expression too complex to compile", expr);
  5958. }
  5959. return result;
  5960. }
  5961. }
  5962. BP_ZONE("BfModule::CreateValueFromExpression");
  5963. if (outOrigType != NULL)
  5964. *outOrigType = NULL;
  5965. exprEvaluator.mExpectingType = wantTypeRef;
  5966. exprEvaluator.mBfEvalExprFlags = flags;
  5967. exprEvaluator.mExplicitCast = (flags & BfEvalExprFlags_ExplicitCast) != 0;
  5968. if ((flags & BfEvalExprFlags_CreateConditionalScope) != 0)
  5969. {
  5970. EvaluateWithNewScope(exprEvaluator, expr, flags);
  5971. }
  5972. else
  5973. exprEvaluator.Evaluate(expr, (flags & BfEvalExprFlags_PropogateNullConditional) != 0, (flags & BfEvalExprFlags_IgnoreNullConditional) != 0, true);
  5974. if (!exprEvaluator.mResult)
  5975. {
  5976. if (!mCompiler->mPassInstance->HasFailed())
  5977. Fail("INTERNAL ERROR: No expression result returned but no error caught in expression evaluator", expr);
  5978. return BfTypedValue();
  5979. }
  5980. auto typedVal = exprEvaluator.mResult;
  5981. if (typedVal.mKind == BfTypedValueKind_GenericConstValue)
  5982. {
  5983. BF_ASSERT(typedVal.mType->IsGenericParam());
  5984. auto genericParamDef = GetGenericParamInstance((BfGenericParamType*)typedVal.mType);
  5985. bool handled = false;
  5986. if ((genericParamDef->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  5987. {
  5988. auto genericTypeConstraint = genericParamDef->mTypeConstraint;
  5989. if (genericTypeConstraint != NULL)
  5990. {
  5991. auto primType = genericTypeConstraint->ToPrimitiveType();
  5992. if (primType != NULL)
  5993. {
  5994. BfTypedValue result;
  5995. result.mKind = BfTypedValueKind_Value;
  5996. result.mType = genericTypeConstraint;
  5997. result.mValue = mBfIRBuilder->GetUndefConstValue(primType->mTypeDef->mTypeCode);
  5998. typedVal = result;
  5999. handled = true;
  6000. }
  6001. }
  6002. }
  6003. if (!handled)
  6004. {
  6005. //Fail("Only const generic parameters can be used as values", expr);
  6006. AssertErrorState();
  6007. return BfTypedValue();
  6008. }
  6009. }
  6010. if ((flags & BfEvalExprFlags_AllowIntUnknown) == 0)
  6011. FixIntUnknown(typedVal);
  6012. exprEvaluator.CheckResultForReading(typedVal);
  6013. if ((wantTypeRef == NULL) || (!wantTypeRef->IsRef()))
  6014. {
  6015. if ((flags & BfEvalExprFlags_NoCast) == 0)
  6016. {
  6017. // Only allow a 'ref' type if we have an explicit 'ref' operator
  6018. bool allowRef = false;
  6019. BfExpression* checkExpr = expr;
  6020. while (auto parenExpr = BfNodeDynCast<BfParenthesizedExpression>(checkExpr))
  6021. checkExpr = parenExpr->mExpression;
  6022. if (auto unaryOp = BfNodeDynCast<BfUnaryOperatorExpression>(checkExpr))
  6023. {
  6024. if ((unaryOp->mOp == BfUnaryOp_Ref) || (unaryOp->mOp == BfUnaryOp_Mut))
  6025. allowRef = true;
  6026. }
  6027. if (!allowRef)
  6028. typedVal = RemoveRef(typedVal);
  6029. }
  6030. }
  6031. if (!typedVal.mType->IsComposite()) // Load non-structs by default
  6032. typedVal = LoadValue(typedVal, 0, exprEvaluator.mIsVolatileReference);
  6033. if (wantTypeRef != NULL)
  6034. {
  6035. if (outOrigType != NULL)
  6036. *outOrigType = typedVal.mType;
  6037. if ((flags & BfEvalExprFlags_NoCast) == 0)
  6038. {
  6039. BfCastFlags castFlags = ((flags & BfEvalExprFlags_ExplicitCast) != 0) ? BfCastFlags_Explicit : BfCastFlags_None;
  6040. if ((flags & BfEvalExprFlags_FieldInitializer) != 0)
  6041. castFlags = (BfCastFlags)(castFlags | BfCastFlags_WarnOnBox);
  6042. typedVal = Cast(expr, typedVal, wantTypeRef, castFlags);
  6043. if (!typedVal)
  6044. return typedVal;
  6045. }
  6046. //WTF- why did we have this?
  6047. /*if ((flags & BfEvalExprFlags_ExplicitCast) == 0)
  6048. typedVal = LoadValue(typedVal, 0, exprEvaluator.mIsVolatileReference);*/
  6049. if (exprEvaluator.mIsVolatileReference)
  6050. typedVal = LoadValue(typedVal, 0, exprEvaluator.mIsVolatileReference);
  6051. }
  6052. // if ((typedVal.IsSplat()) && ((flags & BfEvalExprFlags_AllowSplat) == 0))
  6053. // typedVal = MakeAddressable(typedVal);
  6054. //typedVal = AggregateSplat(typedVal);
  6055. if ((typedVal.mType->IsValueType()) && ((flags & BfEvalExprFlags_NoValueAddr) != 0))
  6056. typedVal = LoadValue(typedVal, 0, exprEvaluator.mIsVolatileReference);
  6057. return typedVal;
  6058. }
  6059. BfTypedValue BfModule::CreateValueFromExpression(BfExpression* expr, BfType* wantTypeRef, BfEvalExprFlags flags, BfType** outOrigType)
  6060. {
  6061. BfExprEvaluator exprEvaluator(this);
  6062. return CreateValueFromExpression(exprEvaluator, expr, wantTypeRef, flags, outOrigType);
  6063. }
  6064. BfTypedValue BfModule::GetOrCreateVarAddr(BfExpression* expr)
  6065. {
  6066. BfExprEvaluator exprEvaluator(this);
  6067. exprEvaluator.Evaluate(expr);
  6068. if (!exprEvaluator.mResult)
  6069. {
  6070. Fail("Invalid expression type", expr);
  6071. return BfTypedValue();
  6072. }
  6073. if (!exprEvaluator.mResult.IsAddr())
  6074. {
  6075. Fail("Cannot assign to value", expr);
  6076. return BfTypedValue();
  6077. }
  6078. return exprEvaluator.mResult;
  6079. }
  6080. // Clear memory, set classVData, call init. Actual ctor is called elsewhere.
  6081. void BfModule::InitTypeInst(BfTypedValue typedValue, BfScopeData* scopeData, bool zeroMemory, BfIRValue sizeValue)
  6082. {
  6083. auto typeInstance = typedValue.mType->ToTypeInstance();
  6084. if (zeroMemory)
  6085. {
  6086. int zeroAlign = typedValue.mType->mAlign;
  6087. if (typeInstance != NULL)
  6088. zeroAlign = typeInstance->mInstAlign;
  6089. mBfIRBuilder->CreateMemSet(typedValue.mValue, GetConstValue8(0), sizeValue, zeroAlign);
  6090. }
  6091. if (!typedValue.mType->IsObject())
  6092. {
  6093. return;
  6094. }
  6095. if ((scopeData == NULL) && (mCurMethodState != NULL))
  6096. return; // Handled in heap alloc funcs
  6097. auto typeDef = typeInstance->mTypeDef;
  6098. mBfIRBuilder->PopulateType(typedValue.mType);
  6099. auto vObjectAddr = mBfIRBuilder->CreateInBoundsGEP(typedValue.mValue, 0, 0);
  6100. bool isAutocomplete = mCompiler->IsAutocomplete();
  6101. BfIRValue vDataRef;
  6102. if (!isAutocomplete)
  6103. {
  6104. vDataRef = GetClassVDataPtr(typeInstance);
  6105. }
  6106. auto i8Type = GetPrimitiveType(BfTypeCode_Int8);
  6107. auto ptrType = CreatePointerType(i8Type);
  6108. auto ptrPtrType = CreatePointerType(ptrType);
  6109. PopulateType(ptrPtrType, BfPopulateType_Declaration);
  6110. PopulateType(ptrType, BfPopulateType_Declaration);
  6111. auto destAddr = mBfIRBuilder->CreateBitCast(vObjectAddr, mBfIRBuilder->MapType(ptrPtrType));
  6112. if (!isAutocomplete)
  6113. {
  6114. if (mCompiler->mOptions.mObjectHasDebugFlags)
  6115. {
  6116. auto objectPtr = mBfIRBuilder->CreateBitCast(destAddr, mBfIRBuilder->MapType(mContext->mBfObjectType));
  6117. SizedArray<BfIRValue, 4> llvmArgs;
  6118. llvmArgs.push_back(objectPtr);
  6119. llvmArgs.push_back(vDataRef);
  6120. auto objectStackInitMethod = GetInternalMethod("Dbg_ObjectStackInit");
  6121. if (objectStackInitMethod)
  6122. mBfIRBuilder->CreateCall(objectStackInitMethod.mFunc, llvmArgs);
  6123. }
  6124. else
  6125. {
  6126. auto srcVal = mBfIRBuilder->CreateBitCast(vDataRef, mBfIRBuilder->MapType(ptrType));
  6127. auto objectPtr = mBfIRBuilder->CreateBitCast(destAddr, mBfIRBuilder->MapType(ptrType));
  6128. mBfIRBuilder->CreateStore(srcVal, destAddr);
  6129. }
  6130. }
  6131. }
  6132. BfIRValue BfModule::AllocBytes(BfAstNode* refNode, const BfAllocTarget& allocTarget, BfType* type, BfIRValue sizeValue, BfIRValue alignValue, BfAllocFlags allocFlags/*, bool zeroMemory, bool defaultToMalloc*/)
  6133. {
  6134. BfIRValue result;
  6135. BfType* ptrType;
  6136. if ((type->IsObject()) && ((allocFlags & BfAllocFlags_RawArray) == 0))
  6137. ptrType = type;
  6138. else
  6139. ptrType = CreatePointerType(type);
  6140. if ((allocTarget.mScopedInvocationTarget != NULL) || (allocTarget.mCustomAllocator))
  6141. {
  6142. auto intType = GetPrimitiveType(BfTypeCode_IntPtr);
  6143. SizedArray<BfExpression*, 2> argExprs;
  6144. BfTypedValueExpression typedValueExpr;
  6145. typedValueExpr.Init(BfTypedValue(sizeValue, intType));
  6146. typedValueExpr.mRefNode = refNode;
  6147. argExprs.push_back(&typedValueExpr);
  6148. BfTypedValueExpression appendSizeValueExpr;
  6149. appendSizeValueExpr.Init(BfTypedValue(alignValue, intType));
  6150. appendSizeValueExpr.mRefNode = refNode;
  6151. argExprs.push_back(&appendSizeValueExpr);
  6152. BfExprEvaluator exprEvaluator(this);
  6153. BfTypedValue allocResult;
  6154. if (allocTarget.mScopedInvocationTarget != NULL)
  6155. {
  6156. SizedArray<BfTypeReference*, 2> genericArgs;
  6157. exprEvaluator.DoInvocation(allocTarget.mScopedInvocationTarget, NULL, argExprs, NULL);
  6158. allocResult = LoadValue(exprEvaluator.mResult);
  6159. }
  6160. else if (allocTarget.mCustomAllocator)
  6161. {
  6162. auto customTypeInst = allocTarget.mCustomAllocator.mType->ToTypeInstance();
  6163. if (customTypeInst != NULL)
  6164. {
  6165. BfTypedValueExpression typeValueExpr;
  6166. String allocMethodName = "Alloc";
  6167. if (GetRawMethodByName(customTypeInst, "AllocTyped", -1, true, true))
  6168. {
  6169. allocMethodName = "AllocTyped";
  6170. auto typeType = ResolveTypeDef(mCompiler->mTypeTypeDef);
  6171. auto typeRefVal = CreateTypeDataRef(type);
  6172. typeValueExpr.Init(BfTypedValue(typeRefVal, typeType));
  6173. typeValueExpr.mRefNode = refNode;
  6174. argExprs.Insert(0, &typeValueExpr);
  6175. }
  6176. if (HasMixin(customTypeInst, allocMethodName, 2))
  6177. {
  6178. BfSizedArray<BfExpression*> argExprArr;
  6179. argExprArr.mSize = (int)argExprs.size();
  6180. argExprArr.mVals = &argExprs[0];
  6181. exprEvaluator.InjectMixin(refNode, allocTarget.mCustomAllocator, false, allocMethodName, argExprs, {});
  6182. allocResult = exprEvaluator.GetResult();
  6183. }
  6184. else
  6185. {
  6186. BfSizedArray<BfExpression*> sizedArgExprs(argExprs);
  6187. BfResolvedArgs argValues(&sizedArgExprs);
  6188. exprEvaluator.ResolveArgValues(argValues);
  6189. SetAndRestoreValue<bool> prevNoBind(mCurMethodState->mNoBind, true);
  6190. allocResult = exprEvaluator.MatchMethod(refNode, NULL, allocTarget.mCustomAllocator, false, false, allocMethodName, argValues, NULL);
  6191. }
  6192. }
  6193. }
  6194. if (allocResult)
  6195. {
  6196. if (allocResult.mType->IsVoidPtr())
  6197. result = mBfIRBuilder->CreateBitCast(allocResult.mValue, mBfIRBuilder->MapType(ptrType));
  6198. else
  6199. result = CastToValue(refNode, allocResult, ptrType, BfCastFlags_Explicit);
  6200. return result;
  6201. }
  6202. }
  6203. if ((allocFlags & BfAllocFlags_NoDefaultToMalloc) != 0)
  6204. return result;
  6205. if (mCompiler->mOptions.mDebugAlloc)
  6206. {
  6207. BfIRValue allocData = GetDbgRawAllocData(type);
  6208. BfModuleMethodInstance allocMethod = GetInternalMethod("Dbg_RawAlloc", 2);
  6209. SizedArray<BfIRValue, 2> llvmArgs;
  6210. llvmArgs.push_back(sizeValue);
  6211. llvmArgs.push_back(allocData);
  6212. BfIRValue bitData = mBfIRBuilder->CreateCall(allocMethod.mFunc, llvmArgs);
  6213. return mBfIRBuilder->CreateBitCast(bitData, mBfIRBuilder->MapType(ptrType));
  6214. }
  6215. BfModuleMethodInstance moduleMethodInstance;
  6216. moduleMethodInstance = GetInternalMethod("Malloc");
  6217. SizedArray<BfIRValue, 1> llvmArgs;
  6218. llvmArgs.push_back(sizeValue);
  6219. auto func = moduleMethodInstance.mFunc;
  6220. if ((!func) || (func.IsFake()))
  6221. {
  6222. BF_ASSERT((mCompiler->mIsResolveOnly) || (mBfIRBuilder->mIgnoreWrites));
  6223. return mBfIRBuilder->CreateUndefValue(mBfIRBuilder->MapType(ptrType));
  6224. }
  6225. BfIRValue bitData = mBfIRBuilder->CreateCall(func, llvmArgs);
  6226. if ((allocFlags & BfAllocFlags_ZeroMemory) != 0)
  6227. mBfIRBuilder->CreateMemSet(bitData, GetConstValue8(0), sizeValue, alignValue);
  6228. result = mBfIRBuilder->CreateBitCast(bitData, mBfIRBuilder->MapType(ptrType));
  6229. return result;
  6230. }
  6231. BfIRValue BfModule::GetMarkFuncPtr(BfType* type)
  6232. {
  6233. if (type->IsStruct())
  6234. {
  6235. auto typeInstance = type->ToTypeInstance();
  6236. BfModuleMethodInstance moduleMethodInst = GetMethodByName(typeInstance, BF_METHODNAME_MARKMEMBERS, 0, true);
  6237. return mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr)));
  6238. }
  6239. else if (type->IsObjectOrInterface())
  6240. {
  6241. auto gcType = ResolveTypeDef(mCompiler->mGCTypeDef)->ToTypeInstance();
  6242. BfModuleMethodInstance moduleMethodInst = GetMethodByName(gcType, "MarkDerefedObject");
  6243. BF_ASSERT(moduleMethodInst.mFunc);
  6244. return mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr)));
  6245. }
  6246. else
  6247. {
  6248. auto gcType = ResolveTypeDef(mCompiler->mGCTypeDef)->ToTypeInstance();
  6249. BfExprEvaluator exprEvaluator(this);
  6250. SizedArray<BfResolvedArg, 1> resolvedArgs;
  6251. BfResolvedArg resolvedArg;
  6252. resolvedArg.mTypedValue = BfTypedValue(mBfIRBuilder->GetFakeVal(), type, type->IsComposite());
  6253. resolvedArgs.Add(resolvedArg);
  6254. BfMethodMatcher methodMatcher(NULL, this, "Mark", resolvedArgs, NULL);
  6255. methodMatcher.CheckType(gcType, BfTypedValue(), false);
  6256. BfModuleMethodInstance moduleMethodInst = exprEvaluator.GetSelectedMethod(NULL, methodMatcher.mBestMethodTypeInstance, methodMatcher.mBestMethodDef, methodMatcher);
  6257. BF_ASSERT(moduleMethodInst.mFunc);
  6258. return mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr)));
  6259. }
  6260. return BfIRValue();
  6261. }
  6262. BfIRValue BfModule::GetDbgRawAllocData(BfType* type)
  6263. {
  6264. BfIRValue allocDataValue;
  6265. if (mDbgRawAllocDataRefs.TryGetValue(type, &allocDataValue))
  6266. return allocDataValue;
  6267. BfIRValue markFuncPtr;
  6268. if (type->WantsGCMarking())
  6269. markFuncPtr = GetMarkFuncPtr(type);
  6270. else
  6271. markFuncPtr = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr)));
  6272. BfIRValue typeDataRef = CreateTypeDataRef(type);
  6273. auto dbgRawAllocDataType = ResolveTypeDef(mCompiler->mDbgRawAllocDataTypeDef)->ToTypeInstance();
  6274. BfTypeInstance* typeInstance = type->ToTypeInstance();
  6275. if (typeInstance == NULL)
  6276. {
  6277. typeInstance = GetWrappedStructType(type);
  6278. if (typeInstance != NULL)
  6279. AddDependency(typeInstance, mCurTypeInstance, BfDependencyMap::DependencyFlag_Allocates);
  6280. }
  6281. if (typeInstance != NULL)
  6282. PopulateType(typeInstance);
  6283. int stackCount = mCompiler->mOptions.mAllocStackCount;
  6284. if ((typeInstance != NULL) && (typeInstance->mTypeOptionsIdx != -1))
  6285. {
  6286. auto typeOptions = mSystem->GetTypeOptions(typeInstance->mTypeOptionsIdx);
  6287. stackCount = BfTypeOptions::Apply(stackCount, typeOptions->mAllocStackTraceDepth);
  6288. }
  6289. SizedArray<BfIRValue, 2> dataValues;
  6290. dataValues.Add(mBfIRBuilder->CreateConstStructZero(mBfIRBuilder->MapType(dbgRawAllocDataType->mBaseType, BfIRPopulateType_Full)));
  6291. dataValues.Add(typeDataRef);
  6292. dataValues.Add(markFuncPtr);
  6293. dataValues.Add(mBfIRBuilder->CreateConst(BfTypeCode_Int32, stackCount));
  6294. BfIRValue dataStruct = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapType(dbgRawAllocDataType, BfIRPopulateType_Full), dataValues);
  6295. allocDataValue = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapType(dbgRawAllocDataType), true, BfIRLinkageType_Internal, dataStruct, "__allocData_" + BfSafeMangler::Mangle(type));
  6296. mDbgRawAllocDataRefs.TryAdd(type, allocDataValue);
  6297. return allocDataValue;
  6298. }
  6299. BfIRValue BfModule::AllocFromType(BfType* type, const BfAllocTarget& allocTarget, BfIRValue appendSizeValue, BfIRValue arraySize, int arrayDim, BfAllocFlags allocFlags, int alignOverride)
  6300. {
  6301. BP_ZONE("AllocFromType");
  6302. BfScopeData* scopeData = allocTarget.mScopeData;
  6303. auto typeInstance = type->ToTypeInstance();
  6304. if ((typeInstance == NULL) && (type->IsGenericParam()))
  6305. typeInstance = mContext->mBfObjectType;
  6306. bool isHeapAlloc = scopeData == NULL;
  6307. bool isScopeAlloc = scopeData != NULL;
  6308. bool isLoopedAlloc = (scopeData != NULL) && (mCurMethodState->mCurScope->IsLooped(scopeData));
  6309. bool isDynAlloc = (scopeData != NULL) && (mCurMethodState->mCurScope->IsDyn(scopeData));
  6310. bool isRawArrayAlloc = (allocFlags & BfAllocFlags_RawArray) != 0;
  6311. bool zeroMemory = (allocFlags & BfAllocFlags_ZeroMemory) != 0;
  6312. bool noDtorCall = (allocFlags & BfAllocFlags_NoDtorCall) != 0;
  6313. if ((type->IsValuelessType()) && ((!arraySize) || (isRawArrayAlloc)))
  6314. {
  6315. BfPointerType* ptrType = CreatePointerType(type);
  6316. auto val = mBfIRBuilder->CreateIntToPtr(mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 1), mBfIRBuilder->MapType(ptrType));
  6317. return val;
  6318. }
  6319. if (typeInstance != NULL)
  6320. mBfIRBuilder->PopulateType(typeInstance);
  6321. bool hasCustomAllocator = (allocTarget.mCustomAllocator) || (allocTarget.mScopedInvocationTarget != NULL);
  6322. if ((!hasCustomAllocator) && (mBfIRBuilder->mIgnoreWrites))
  6323. {
  6324. if (arraySize)
  6325. {
  6326. if (isRawArrayAlloc)
  6327. {
  6328. BfPointerType* ptrType = CreatePointerType(type);
  6329. return GetDefaultValue(ptrType);
  6330. }
  6331. BfArrayType* arrayType = CreateArrayType(type, arrayDim);
  6332. return GetDefaultValue(arrayType);
  6333. }
  6334. if (type->IsValueType())
  6335. {
  6336. BfPointerType* ptrType = CreatePointerType(type);
  6337. return GetDefaultValue(ptrType);
  6338. }
  6339. return mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(type));
  6340. }
  6341. AddDependency(type, mCurTypeInstance, BfDependencyMap::DependencyFlag_Allocates);
  6342. BfIRValue sizeValue;
  6343. BfIRType allocType = mBfIRBuilder->MapType(type);
  6344. int allocSize = type->mSize;
  6345. int allocAlign = type->mAlign;
  6346. if (typeInstance != NULL)
  6347. {
  6348. if (!mBfIRBuilder->mIgnoreWrites)
  6349. typeInstance->mHasBeenInstantiated = true;
  6350. allocSize = typeInstance->mInstSize;
  6351. allocAlign = typeInstance->mInstAlign;
  6352. //if (typeInstance->IsEnum())
  6353. //allocType = typeInstance->mIRType;
  6354. allocType = mBfIRBuilder->MapTypeInst(typeInstance);
  6355. }
  6356. if (alignOverride != -1)
  6357. allocAlign = alignOverride;
  6358. // The "dynSize" cases:
  6359. // If we are not dyn, but we are a variable size and could be looped over multiple times then we attempt to reuse
  6360. // the last stack space. We won't use StackSave and StackRestore because a scoped alloc that occurs after this but
  6361. // needs to be retained after the current scopeData (ie: scopeData::), then it would cause these allocs to accumulate even
  6362. // though we'd expect their stack space to be released
  6363. auto _CreateDynAlloc = [&](const BfIRValue& sizeValue, int align)
  6364. {
  6365. MarkDynStack(scopeData);
  6366. BfType* intType = GetPrimitiveType(BfTypeCode_IntPtr);
  6367. // For dynamically sized scoped allocs, we need to check the previous size to see if we need to realloc
  6368. BfType* voidType = GetPrimitiveType(BfTypeCode_None);
  6369. BfType* voidPtrType = CreatePointerType(voidType);
  6370. if (!mCurMethodState->mDynStackRevIdx)
  6371. {
  6372. mCurMethodState->mDynStackRevIdx = CreateAlloca(intType, false, "curDynStackRevIdx");
  6373. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  6374. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRInitBlock);
  6375. auto storeInst = mBfIRBuilder->CreateStore(GetConstValue(0), mCurMethodState->mDynStackRevIdx);
  6376. mBfIRBuilder->ClearDebugLocation(storeInst);
  6377. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  6378. }
  6379. auto byteType = GetPrimitiveType(BfTypeCode_Int8);
  6380. auto bytePtrType = CreatePointerType(byteType);
  6381. auto dynSizeAllocaInst = CreateAlloca(intType, false, "dynSize");
  6382. auto dynStackRevIdx = CreateAlloca(intType, false, "dynStackRevIdx");
  6383. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  6384. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRInitBlock);
  6385. auto storeInst = mBfIRBuilder->CreateStore(GetConstValue(0), dynSizeAllocaInst);
  6386. mBfIRBuilder->ClearDebugLocation(storeInst);
  6387. storeInst = mBfIRBuilder->CreateStore(GetConstValue(0), dynStackRevIdx);
  6388. mBfIRBuilder->ClearDebugLocation(storeInst);
  6389. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  6390. auto dynPtrAllocaInst = CreateAlloca(bytePtrType, false, "dynPtr");
  6391. if (IsTargetingBeefBackend())
  6392. {
  6393. // Since we don't allocate a debug variable for this, with LifetimeExtends, the easiest way
  6394. // to ensure there isn't any register collision during looping is just to not allow it to
  6395. // bind to a register at all
  6396. mBfIRBuilder->SetAllocaForceMem(dynSizeAllocaInst);
  6397. mBfIRBuilder->SetAllocaForceMem(dynPtrAllocaInst);
  6398. }
  6399. auto resizeBB = mBfIRBuilder->CreateBlock("dynAlloc.resize");
  6400. auto endBB = mBfIRBuilder->CreateBlock("dynAlloc.end");
  6401. auto verCheckBB = mBfIRBuilder->CreateBlock("dynAlloc.verCheck");
  6402. auto curDynStackRevIdx = mBfIRBuilder->CreateLoad(mCurMethodState->mDynStackRevIdx);
  6403. auto prevSize = mBfIRBuilder->CreateLoad(dynSizeAllocaInst);
  6404. auto isGreater = mBfIRBuilder->CreateCmpGT(sizeValue, prevSize, true);
  6405. mBfIRBuilder->CreateCondBr(isGreater, resizeBB, verCheckBB);
  6406. mBfIRBuilder->AddBlock(verCheckBB);
  6407. mBfIRBuilder->SetInsertPoint(verCheckBB);
  6408. auto prevDynStackRevIdx = mBfIRBuilder->CreateLoad(dynStackRevIdx);
  6409. auto dynStackChanged = mBfIRBuilder->CreateCmpNE(prevDynStackRevIdx, curDynStackRevIdx);
  6410. mBfIRBuilder->CreateCondBr(dynStackChanged, resizeBB, endBB);
  6411. mBfIRBuilder->AddBlock(resizeBB);
  6412. mBfIRBuilder->SetInsertPoint(resizeBB);
  6413. auto allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(byteType), sizeValue);
  6414. mBfIRBuilder->SetAllocaAlignment(allocaInst, align);
  6415. mBfIRBuilder->CreateStore(allocaInst, dynPtrAllocaInst);
  6416. mBfIRBuilder->CreateStore(sizeValue, dynSizeAllocaInst);
  6417. mBfIRBuilder->CreateStore(curDynStackRevIdx, dynStackRevIdx);
  6418. mBfIRBuilder->CreateBr(endBB);
  6419. mBfIRBuilder->AddBlock(endBB);
  6420. mBfIRBuilder->SetInsertPoint(endBB);
  6421. return mBfIRBuilder->CreateLoad(dynPtrAllocaInst);
  6422. };
  6423. if (isScopeAlloc)
  6424. {
  6425. if (arraySize)
  6426. {
  6427. bool isConstantArraySize = arraySize.IsConst();
  6428. if (isRawArrayAlloc)
  6429. {
  6430. BfPointerType* ptrType = CreatePointerType(type);
  6431. if ((!isDynAlloc) && (!isConstantArraySize) && (mCurMethodState->mCurScope->IsLooped(NULL)))
  6432. {
  6433. BfIRValue sizeValue = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySize);
  6434. auto loadedPtr = _CreateDynAlloc(sizeValue, type->mAlign);
  6435. InitTypeInst(BfTypedValue(loadedPtr, ptrType), scopeData, zeroMemory, sizeValue);
  6436. return mBfIRBuilder->CreateBitCast(loadedPtr, mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapType(type)));
  6437. }
  6438. else
  6439. {
  6440. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  6441. isDynAlloc = (isDynAlloc) || (!arraySize.IsConst());
  6442. if (!isDynAlloc)
  6443. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  6444. else
  6445. {
  6446. MarkDynStack(scopeData);
  6447. SaveStackState(scopeData);
  6448. }
  6449. int typeSize = type->GetStride();
  6450. BfIRValue allocaInst;
  6451. BfIRValue result;
  6452. if ((typeInstance == NULL) || (typeInstance->mIsCRepr))
  6453. {
  6454. sizeValue = mBfIRBuilder->CreateMul(GetConstValue(typeSize), arraySize);
  6455. allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(type), arraySize);
  6456. result = allocaInst;
  6457. }
  6458. else
  6459. {
  6460. if (typeInstance->IsStruct())
  6461. typeSize = typeInstance->GetInstStride();
  6462. auto byteType = GetPrimitiveStructType(BfTypeCode_Int8);
  6463. sizeValue = mBfIRBuilder->CreateMul(GetConstValue(typeSize), arraySize);
  6464. allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(byteType), sizeValue);
  6465. auto ptrType = CreatePointerType(typeInstance);
  6466. result = mBfIRBuilder->CreateBitCast(allocaInst, mBfIRBuilder->MapType(ptrType));
  6467. if (!isDynAlloc)
  6468. mBfIRBuilder->ClearDebugLocation(result);
  6469. }
  6470. if (!isDynAlloc)
  6471. mBfIRBuilder->ClearDebugLocation(allocaInst);
  6472. mBfIRBuilder->SetAllocaAlignment(allocaInst, type->mAlign);
  6473. if (!isDynAlloc)
  6474. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  6475. auto typedVal = BfTypedValue(result, type, BfTypedValueKind_Addr);
  6476. if (arraySize.IsConst())
  6477. {
  6478. auto constant = mBfIRBuilder->GetConstant(arraySize);
  6479. if (constant->mInt64 == 0)
  6480. noDtorCall = true;
  6481. }
  6482. if (!noDtorCall)
  6483. {
  6484. bool isConstSize = arraySize.IsConst();
  6485. BfIRBlock clearBlock;
  6486. BfIRBlock contBlock;
  6487. if (!isConstSize)
  6488. {
  6489. clearBlock = mBfIRBuilder->CreateBlock("clear");
  6490. contBlock = mBfIRBuilder->CreateBlock("clearCont");
  6491. mBfIRBuilder->CreateCondBr(mBfIRBuilder->CreateCmpNE(arraySize, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 0)), clearBlock, contBlock);
  6492. mBfIRBuilder->AddBlock(clearBlock);
  6493. mBfIRBuilder->SetInsertPoint(clearBlock);
  6494. }
  6495. AddStackAlloc(typedVal, NULL, scopeData, false, true);
  6496. if (!isConstSize)
  6497. {
  6498. mBfIRBuilder->CreateBr(contBlock);
  6499. mBfIRBuilder->AddBlock(contBlock);
  6500. mBfIRBuilder->SetInsertPoint(contBlock);
  6501. }
  6502. }
  6503. //InitTypeInst(typedVal, scopeData, zeroMemory, sizeValue);
  6504. return result;
  6505. }
  6506. }
  6507. else
  6508. {
  6509. if ((!isDynAlloc) && (!arraySize.IsConst()) && (mCurMethodState->mCurScope->IsLooped(NULL)))
  6510. {
  6511. // Generate and check new size
  6512. BfArrayType* arrayType = CreateArrayType(type, arrayDim);
  6513. auto firstElementField = &arrayType->mFieldInstances.back();
  6514. int arrayClassSize = firstElementField->mDataOffset;
  6515. sizeValue = GetConstValue(arrayClassSize);
  6516. BfIRValue elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySize);
  6517. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, elementDataSize);
  6518. auto loadedPtr = _CreateDynAlloc(sizeValue, arrayType->mAlign);
  6519. auto typedVal = BfTypedValue(mBfIRBuilder->CreateBitCast(loadedPtr, mBfIRBuilder->MapType(arrayType)), arrayType);
  6520. if (!noDtorCall)
  6521. AddStackAlloc(typedVal, NULL, scopeData, false, true);
  6522. InitTypeInst(typedVal, scopeData, zeroMemory, sizeValue);
  6523. return typedVal.mValue;
  6524. }
  6525. else
  6526. {
  6527. BfArrayType* arrayType = CreateArrayType(type, arrayDim);
  6528. auto firstElementField = &arrayType->mFieldInstances.back();
  6529. int arrayClassSize = firstElementField->mDataOffset;
  6530. sizeValue = GetConstValue(arrayClassSize);
  6531. BfIRValue elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySize);
  6532. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, elementDataSize);
  6533. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  6534. isDynAlloc = (isDynAlloc) || (!sizeValue.IsConst());
  6535. if (!isDynAlloc)
  6536. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  6537. else
  6538. {
  6539. MarkDynStack(scopeData);
  6540. SaveStackState(scopeData);
  6541. }
  6542. BfType* byteType = GetPrimitiveType(BfTypeCode_Int8);
  6543. auto allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(byteType), sizeValue);
  6544. if (!isDynAlloc)
  6545. mBfIRBuilder->ClearDebugLocation(allocaInst);
  6546. mBfIRBuilder->SetAllocaAlignment(allocaInst, arrayType->mAlign);
  6547. auto typedVal = BfTypedValue(mBfIRBuilder->CreateBitCast(allocaInst, mBfIRBuilder->MapType(arrayType)), arrayType);
  6548. mBfIRBuilder->ClearDebugLocation_Last();
  6549. if (!isDynAlloc)
  6550. mBfIRBuilder->SetInsertPoint(prevBlock);
  6551. if (!noDtorCall)
  6552. AddStackAlloc(typedVal, NULL, scopeData, false, true);
  6553. InitTypeInst(typedVal, scopeData, zeroMemory, sizeValue);
  6554. return typedVal.mValue;
  6555. }
  6556. }
  6557. }
  6558. else if (appendSizeValue)
  6559. {
  6560. // It may seem that we should check IsLooped against only the requested scope, BUT- if later on we perform
  6561. // a scoped alloc that crosses our boundary then we won't be able to reclaim the stack space, so we always
  6562. // use the "dynSize" version conservatively
  6563. if ((!isDynAlloc) && (!appendSizeValue.IsConst()) && (mCurMethodState->mCurScope->IsLooped(NULL)))
  6564. {
  6565. // Generate and check new size
  6566. sizeValue = GetConstValue(typeInstance->mInstSize);
  6567. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, appendSizeValue);
  6568. auto loadedPtr = _CreateDynAlloc(sizeValue, typeInstance->mAlign);
  6569. auto typedVal = BfTypedValue(mBfIRBuilder->CreateBitCast(loadedPtr, mBfIRBuilder->MapTypeInstPtr(typeInstance)), typeInstance);
  6570. if (!noDtorCall)
  6571. AddStackAlloc(typedVal, NULL, scopeData, mCurMethodState->mInConditionalBlock, true);
  6572. InitTypeInst(typedVal, scopeData, zeroMemory, sizeValue);
  6573. return typedVal.mValue;
  6574. }
  6575. else // stack alloc, unlooped, with append
  6576. {
  6577. sizeValue = GetConstValue(typeInstance->mInstSize);
  6578. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, appendSizeValue);
  6579. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  6580. bool wasDynAlloc = isDynAlloc;
  6581. isDynAlloc = (isDynAlloc) || (!sizeValue.IsConst());
  6582. if (!isDynAlloc)
  6583. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  6584. else
  6585. {
  6586. MarkDynStack(scopeData);
  6587. SaveStackState(scopeData);
  6588. }
  6589. auto sbyteType = GetPrimitiveType(BfTypeCode_Int8);
  6590. auto allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(sbyteType), sizeValue);
  6591. if (!isDynAlloc)
  6592. {
  6593. mBfIRBuilder->ClearDebugLocation(allocaInst);
  6594. }
  6595. mBfIRBuilder->SetAllocaAlignment(allocaInst, allocAlign);
  6596. bool mayBeLarge = false;
  6597. if (sizeValue.IsConst())
  6598. {
  6599. auto constantInt = mBfIRBuilder->GetConstant(sizeValue);
  6600. if (constantInt->mInt64 >= 4096)
  6601. mayBeLarge = true;
  6602. }
  6603. else
  6604. mayBeLarge = true;
  6605. if (((type->IsObject() && (!mayBeLarge))) ||
  6606. // If we create a memset that can fill in backwards (or at least 4k chunked backward) then we can remove the '!mayBeLarge' cond
  6607. ((zeroMemory) && (!mayBeLarge)))
  6608. {
  6609. mBfIRBuilder->SetAllocaNoChkStkHint(allocaInst);
  6610. }
  6611. BfIRValue castedVal;
  6612. if (!isDynAlloc)
  6613. {
  6614. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRInitBlock);
  6615. castedVal = mBfIRBuilder->CreateBitCast(allocaInst, mBfIRBuilder->MapTypeInstPtr(typeInstance));
  6616. mBfIRBuilder->ClearDebugLocation(castedVal);
  6617. mBfIRBuilder->SetInsertPoint(prevBlock);
  6618. if (WantsLifetimes())
  6619. {
  6620. mBfIRBuilder->CreateLifetimeStart(allocaInst);
  6621. scopeData->mDeferredLifetimeEnds.push_back(allocaInst);
  6622. }
  6623. }
  6624. else
  6625. {
  6626. castedVal = mBfIRBuilder->CreateBitCast(allocaInst, mBfIRBuilder->MapTypeInstPtr(typeInstance));
  6627. }
  6628. auto typedVal = BfTypedValue(castedVal, typeInstance);
  6629. if (!noDtorCall)
  6630. {
  6631. bool doCondAlloca = false;
  6632. if (!IsTargetingBeefBackend())
  6633. doCondAlloca = !wasDynAlloc && isDynAlloc && mCurMethodState->mInConditionalBlock;
  6634. AddStackAlloc(typedVal, NULL, scopeData, doCondAlloca, true);
  6635. }
  6636. InitTypeInst(typedVal, scopeData, zeroMemory, sizeValue);
  6637. return typedVal.mValue;
  6638. }
  6639. }
  6640. else // "Normal" stack alloc
  6641. {
  6642. BF_ASSERT(!sizeValue);
  6643. //TODO: If sizeValue is a constant then do this in the head IR builder
  6644. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  6645. if (!isLoopedAlloc)
  6646. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  6647. else
  6648. {
  6649. MarkDynStack(scopeData);
  6650. SaveStackState(scopeData);
  6651. }
  6652. auto allocaInst = mBfIRBuilder->CreateAlloca(allocType);
  6653. if (!isLoopedAlloc)
  6654. mBfIRBuilder->ClearDebugLocation(allocaInst);
  6655. mBfIRBuilder->SetAllocaAlignment(allocaInst, allocAlign);
  6656. bool mayBeLarge = allocSize >= 4096;
  6657. if (((typeInstance != NULL) && (typeInstance->IsObject()) && (!mayBeLarge)) ||
  6658. // If we create a memset that can fill in backwards (or at least 4k chunked backward) then we can remove the '!mayBeLarge' cond
  6659. ((zeroMemory) && (!mayBeLarge)))
  6660. {
  6661. // With an object, we know we will at least set the vdata pointer which will probe the start of the new address,
  6662. // and memset is always safe
  6663. mBfIRBuilder->SetAllocaNoChkStkHint(allocaInst);
  6664. }
  6665. auto typedVal = BfTypedValue(allocaInst, type);
  6666. if (!isLoopedAlloc)
  6667. {
  6668. mBfIRBuilder->ClearDebugLocation(allocaInst);
  6669. mBfIRBuilder->SetInsertPoint(prevBlock);
  6670. if (WantsLifetimes())
  6671. {
  6672. mBfIRBuilder->CreateLifetimeStart(allocaInst);
  6673. scopeData->mDeferredLifetimeEnds.push_back(allocaInst);
  6674. }
  6675. }
  6676. if (!noDtorCall)
  6677. AddStackAlloc(typedVal, NULL, scopeData, false, true);
  6678. if (typeInstance != NULL)
  6679. {
  6680. InitTypeInst(typedVal, scopeData, zeroMemory, GetConstValue(typeInstance->mInstSize));
  6681. }
  6682. else
  6683. {
  6684. mBfIRBuilder->CreateMemSet(allocaInst, GetConstValue8(0), GetConstValue(allocSize), allocAlign);
  6685. }
  6686. return allocaInst;
  6687. }
  6688. }
  6689. else if (arraySize)
  6690. {
  6691. if (isRawArrayAlloc)
  6692. {
  6693. sizeValue = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySize);
  6694. return AllocBytes(allocTarget.mRefNode, allocTarget, type, sizeValue, GetConstValue(allocAlign), allocFlags);
  6695. }
  6696. else
  6697. {
  6698. BfArrayType* arrayType = CreateArrayType(type, arrayDim);
  6699. typeInstance = arrayType;
  6700. BfIRValue arraySizeMinusOne = mBfIRBuilder->CreateSub(arraySize, GetConstValue(1));
  6701. BfIRValue elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySizeMinusOne);
  6702. appendSizeValue = elementDataSize;
  6703. if (!type->IsSizeAligned())
  6704. {
  6705. appendSizeValue = mBfIRBuilder->CreateAdd(appendSizeValue, GetConstValue(type->GetStride() - type->mSize));
  6706. }
  6707. }
  6708. }
  6709. if ((typeInstance != NULL) && (typeInstance->IsObject()))
  6710. {
  6711. auto vDataRef = GetClassVDataPtr(typeInstance);
  6712. BfIRValue result;
  6713. bool isResultInitialized = false;
  6714. int stackCount = mCompiler->mOptions.mAllocStackCount;
  6715. if (typeInstance->mTypeOptionsIdx != -1)
  6716. {
  6717. auto typeOptions = mSystem->GetTypeOptions(typeInstance->mTypeOptionsIdx);
  6718. stackCount = BfTypeOptions::Apply(stackCount, typeOptions->mAllocStackTraceDepth);
  6719. }
  6720. if (!sizeValue)
  6721. sizeValue = GetConstValue(typeInstance->mInstSize);
  6722. if (appendSizeValue)
  6723. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, appendSizeValue);
  6724. BfIRValue origSizeValue = sizeValue;
  6725. bool isAllocEx = hasCustomAllocator && (stackCount > 1);
  6726. if (isAllocEx)
  6727. {
  6728. auto prepareStackTraceMethod = GetInternalMethod("Dbg_PrepareStackTrace");
  6729. if (prepareStackTraceMethod)
  6730. {
  6731. SizedArray<BfIRValue, 2> irArgs;
  6732. irArgs.Add(sizeValue);
  6733. irArgs.Add(GetConstValue(stackCount));
  6734. auto addlBytes = mBfIRBuilder->CreateCall(prepareStackTraceMethod.mFunc, irArgs);
  6735. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, addlBytes);
  6736. }
  6737. }
  6738. if (allocTarget.mCustomAllocator)
  6739. {
  6740. auto customAlloc = allocTarget.mCustomAllocator.mType->ToTypeInstance();
  6741. // Use AllocObject if we have it, otherwise we just use AllocBytes further down
  6742. if ((customAlloc != NULL) && (GetRawMethodByName(customAlloc, "AllocObject", -1, true, true) != NULL))
  6743. {
  6744. auto classVDataType = ResolveTypeDef(mCompiler->mClassVDataTypeDef);
  6745. mBfIRBuilder->PopulateType(classVDataType);
  6746. auto typeInstType = ResolveTypeDef(mCompiler->mReflectTypeInstanceTypeDef)->ToTypeInstance();
  6747. mBfIRBuilder->PopulateType(typeInstType);
  6748. auto typePtrPtr = mBfIRBuilder->CreateInBoundsGEP(vDataRef, 0, 1); // mType
  6749. auto typePtr = mBfIRBuilder->CreateLoad(typePtrPtr);
  6750. auto typeInstPtr = mBfIRBuilder->CreateBitCast(typePtr, mBfIRBuilder->MapTypeInstPtr(typeInstType));
  6751. BfTypedValueExpression typedValueExpr;
  6752. typedValueExpr.Init(BfTypedValue(typeInstPtr, typeInstType));
  6753. typedValueExpr.mRefNode = allocTarget.mRefNode;
  6754. BfExprEvaluator exprEvaluator(this);
  6755. SizedArray<BfExpression*, 2> argExprs;
  6756. argExprs.push_back(&typedValueExpr);
  6757. BfTypedValueExpression sizeValueExpr;
  6758. sizeValueExpr.Init(BfTypedValue(sizeValue, GetPrimitiveType(BfTypeCode_IntPtr)));
  6759. sizeValueExpr.mRefNode = allocTarget.mRefNode;
  6760. argExprs.push_back(&sizeValueExpr);
  6761. BfSizedArray<BfExpression*> sizedArgExprs(argExprs);
  6762. BfResolvedArgs argValues(&sizedArgExprs);
  6763. exprEvaluator.ResolveArgValues(argValues);
  6764. exprEvaluator.mNoBind = true;
  6765. BfTypedValue allocResult = exprEvaluator.MatchMethod(allocTarget.mRefNode, NULL, allocTarget.mCustomAllocator, false, false, "AllocObject", argValues, NULL);
  6766. if (allocResult)
  6767. {
  6768. if ((allocResult.mType->IsVoidPtr()) || (allocResult.mType == mContext->mBfObjectType))
  6769. result = mBfIRBuilder->CreateBitCast(allocResult.mValue, mBfIRBuilder->MapType(typeInstance));
  6770. else
  6771. result = CastToValue(allocTarget.mRefNode, allocResult, typeInstance, BfCastFlags_Explicit);
  6772. isResultInitialized = true;
  6773. }
  6774. }
  6775. }
  6776. if (!result)
  6777. {
  6778. if (hasCustomAllocator)
  6779. result = AllocBytes(allocTarget.mRefNode, allocTarget, typeInstance, sizeValue, GetConstValue(typeInstance->mInstAlign), (BfAllocFlags)(BfAllocFlags_ZeroMemory | BfAllocFlags_NoDefaultToMalloc));
  6780. }
  6781. if (result)
  6782. {
  6783. if (mCompiler->mOptions.mObjectHasDebugFlags)
  6784. {
  6785. auto objectPtr = mBfIRBuilder->CreateBitCast(result, mBfIRBuilder->MapTypeInstPtr(mContext->mBfObjectType));
  6786. SizedArray<BfIRValue, 4> llvmArgs;
  6787. llvmArgs.push_back(objectPtr);
  6788. llvmArgs.push_back(origSizeValue);
  6789. llvmArgs.push_back(vDataRef);
  6790. auto objectCreatedMethod = GetInternalMethod(isAllocEx ?
  6791. (isResultInitialized ? "Dbg_ObjectCreatedEx" : "Dbg_ObjectAllocatedEx") :
  6792. (isResultInitialized ? "Dbg_ObjectCreated" : "Dbg_ObjectAllocated"));
  6793. mBfIRBuilder->CreateCall(objectCreatedMethod.mFunc, llvmArgs);
  6794. }
  6795. else
  6796. {
  6797. auto ptrType = mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr);
  6798. auto vDataPtr = mBfIRBuilder->CreateBitCast(vDataRef, ptrType);
  6799. auto vDataMemberPtr = mBfIRBuilder->CreateBitCast(result, mBfIRBuilder->GetPointerTo(ptrType));
  6800. mBfIRBuilder->CreateStore(vDataPtr, vDataMemberPtr);
  6801. }
  6802. }
  6803. else
  6804. {
  6805. if ((mBfIRBuilder->mIgnoreWrites) || (mCompiler->mIsResolveOnly))
  6806. return GetDefaultValue(typeInstance);
  6807. auto classVDataType = ResolveTypeDef(mCompiler->mClassVDataTypeDef);
  6808. auto vData = mBfIRBuilder->CreateBitCast(vDataRef, mBfIRBuilder->MapTypeInstPtr(classVDataType->ToTypeInstance()));
  6809. if (mCompiler->mOptions.mObjectHasDebugFlags)
  6810. {
  6811. SizedArray<BfIRValue, 4> llvmArgs;
  6812. llvmArgs.push_back(vData);
  6813. llvmArgs.push_back(sizeValue);
  6814. llvmArgs.push_back(GetConstValue(typeInstance->mAlign));
  6815. llvmArgs.push_back(GetConstValue(stackCount));
  6816. auto moduleMethodInstance = GetInternalMethod("Dbg_ObjectAlloc", 4);
  6817. BfIRValue objectVal = mBfIRBuilder->CreateCall(moduleMethodInstance.mFunc, llvmArgs);
  6818. result = mBfIRBuilder->CreateBitCast(objectVal, mBfIRBuilder->MapType(typeInstance));
  6819. }
  6820. else
  6821. {
  6822. SizedArray<BfIRValue, 4> llvmArgs;
  6823. llvmArgs.push_back(sizeValue);
  6824. BfIRFunction irFunc;
  6825. if (mCompiler->mOptions.mDebugAlloc)
  6826. {
  6827. auto moduleMethodInstance = GetInternalMethod("Dbg_RawObjectAlloc", 1);
  6828. irFunc = moduleMethodInstance.mFunc;
  6829. }
  6830. if (!irFunc)
  6831. irFunc = GetBuiltInFunc(BfBuiltInFuncType_Malloc);
  6832. BfIRValue objectVal = mBfIRBuilder->CreateCall(irFunc, llvmArgs);
  6833. auto objResult = mBfIRBuilder->CreateBitCast(objectVal, mBfIRBuilder->MapType(mContext->mBfObjectType, BfIRPopulateType_Full));
  6834. auto vdataPtr = mBfIRBuilder->CreateInBoundsGEP(objResult, 0, 0);
  6835. mBfIRBuilder->CreateStore(vData, vdataPtr);
  6836. result = mBfIRBuilder->CreateBitCast(objectVal, mBfIRBuilder->MapType(typeInstance));
  6837. }
  6838. }
  6839. if ((zeroMemory) && (arraySize))
  6840. {
  6841. BfArrayType* arrayType = CreateArrayType(type, arrayDim);
  6842. typeInstance = arrayType;
  6843. auto firstElementField = &arrayType->mFieldInstances.back();
  6844. int arrayClassSize = firstElementField->mDataOffset;
  6845. BfIRValue elementDataSize;
  6846. bool skipZero = false;
  6847. if (arraySize.IsConst())
  6848. {
  6849. BfIRValue arraySizeMinusOne = mBfIRBuilder->CreateSub(arraySize, GetConstValue(1));
  6850. elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySizeMinusOne);
  6851. elementDataSize = mBfIRBuilder->CreateAdd(elementDataSize, GetConstValue(type->mSize));
  6852. auto constVal = mBfIRBuilder->GetConstant(elementDataSize);
  6853. if (constVal->mInt64 <= 0)
  6854. skipZero = true;
  6855. }
  6856. else
  6857. {
  6858. // For non const, don't use an unpadded last element - saves us checking against negative numbers going into memset for the zero-length case
  6859. elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySize);
  6860. }
  6861. if (!skipZero)
  6862. {
  6863. auto i8Type = GetPrimitiveType(BfTypeCode_Int8);
  6864. auto ptrType = CreatePointerType(i8Type);
  6865. auto ptrVal = mBfIRBuilder->CreateBitCast(result, mBfIRBuilder->MapType(ptrType));
  6866. ptrVal = mBfIRBuilder->CreateInBoundsGEP(ptrVal, arrayClassSize);
  6867. mBfIRBuilder->CreateMemSet(ptrVal, GetConstValue8(0), elementDataSize, type->mAlign);
  6868. appendSizeValue = elementDataSize;
  6869. }
  6870. }
  6871. return result;
  6872. }
  6873. else
  6874. {
  6875. if (!sizeValue)
  6876. sizeValue = GetConstValue(allocSize);
  6877. return AllocBytes(allocTarget.mRefNode, allocTarget, type, sizeValue, GetConstValue(allocAlign), zeroMemory ? BfAllocFlags_ZeroMemory : BfAllocFlags_None);
  6878. }
  6879. }
  6880. void BfModule::ValidateAllocation(BfType* type, BfAstNode* refNode)
  6881. {
  6882. if ((type == NULL) || (refNode == NULL))
  6883. return;
  6884. auto typeInstance = type->ToTypeInstance();
  6885. if ((typeInstance != NULL) && (typeInstance->mTypeDef->mIsOpaque))
  6886. Fail(StrFormat("Unable to allocate opaque type '%s'", TypeToString(type).c_str()), refNode);
  6887. }
  6888. void BfModule::EmitAlign(BfIRValue& appendCurIdx, int align)
  6889. {
  6890. appendCurIdx = mBfIRBuilder->CreateAdd(appendCurIdx, GetConstValue(align - 1));
  6891. appendCurIdx = mBfIRBuilder->CreateAnd(appendCurIdx, GetConstValue(~(align - 1)));
  6892. }
  6893. void BfModule::EmitAppendAlign(int align, int sizeMultiple)
  6894. {
  6895. if (sizeMultiple == 0)
  6896. sizeMultiple = align;
  6897. if ((mCurMethodState->mCurAppendAlign != 0) && (mCurMethodState->mCurAppendAlign % align != 0))
  6898. {
  6899. if (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_Ctor)
  6900. {
  6901. auto localVar = mCurMethodState->GetRootMethodState()->mLocals[1];
  6902. BF_ASSERT(localVar->mName == "appendIdx");
  6903. auto appendIdxVal = BfTypedValue(localVar->mValue, localVar->mResolvedType, true);
  6904. BfIRValue appendCurIdx = mBfIRBuilder->CreateLoad(appendIdxVal.mValue);
  6905. if (align > 1)
  6906. {
  6907. appendCurIdx = mBfIRBuilder->CreateAdd(appendCurIdx, GetConstValue(align - 1));
  6908. appendCurIdx = mBfIRBuilder->CreateAnd(appendCurIdx, GetConstValue(~(align - 1)));
  6909. }
  6910. mBfIRBuilder->CreateStore(appendCurIdx, appendIdxVal.mValue);
  6911. }
  6912. else
  6913. {
  6914. BF_ASSERT(mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend);
  6915. BfIRValue appendCurIdxPtr = mCurMethodState->mRetVal.mValue;
  6916. BfIRValue appendCurIdx = mBfIRBuilder->CreateLoad(appendCurIdxPtr);
  6917. appendCurIdx = mBfIRBuilder->CreateAdd(appendCurIdx, GetConstValue(align - 1));
  6918. appendCurIdx = mBfIRBuilder->CreateAnd(appendCurIdx, GetConstValue(~(align - 1)));
  6919. mBfIRBuilder->CreateStore(appendCurIdx, appendCurIdxPtr);
  6920. }
  6921. }
  6922. if (mCurMethodState->mCurAppendAlign == 0)
  6923. mCurMethodState->mCurAppendAlign = sizeMultiple;
  6924. else
  6925. {
  6926. if (sizeMultiple % align == 0)
  6927. mCurMethodState->mCurAppendAlign = align;
  6928. else
  6929. mCurMethodState->mCurAppendAlign = sizeMultiple % align;
  6930. }
  6931. }
  6932. BfIRValue BfModule::AppendAllocFromType(BfType* type, BfIRValue appendSizeValue, int appendAllocAlign, BfIRValue arraySize, int arrayDim, bool isRawArrayAlloc, bool zeroMemory)
  6933. {
  6934. auto localVar = mCurMethodState->GetRootMethodState()->mLocals[1];
  6935. BF_ASSERT(localVar->mName == "appendIdx");
  6936. BfTypedValue appendIdxVal(localVar->mValue, localVar->mResolvedType, true);
  6937. BfIRValue retValue;
  6938. BfTypeInstance* retTypeInstance = NULL;
  6939. auto intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  6940. auto voidPtrType = GetPrimitiveType(BfTypeCode_NullPtr);
  6941. if (arraySize)
  6942. {
  6943. if (isRawArrayAlloc)
  6944. {
  6945. EmitAppendAlign(type->mAlign);
  6946. BfPointerType* ptrType = CreatePointerType(type);
  6947. BfIRValue sizeValue = mBfIRBuilder->CreateMul(GetConstValue(type->mSize), arraySize);
  6948. auto curIdxVal = mBfIRBuilder->CreateLoad(appendIdxVal.mValue);
  6949. if (mSystem->mPtrSize != 4)
  6950. sizeValue = mBfIRBuilder->CreateNumericCast(sizeValue, true, (intPtrType->mSize == 4) ? BfTypeCode_Int32 : BfTypeCode_Int64);
  6951. auto newIdxVal = mBfIRBuilder->CreateAdd(curIdxVal, sizeValue);
  6952. mBfIRBuilder->CreateStore(newIdxVal, appendIdxVal.mValue);
  6953. if (zeroMemory)
  6954. {
  6955. auto ptr = mBfIRBuilder->CreateIntToPtr(curIdxVal, mBfIRBuilder->MapType(voidPtrType));
  6956. mBfIRBuilder->CreateMemSet(ptr, GetConstValue8(0), sizeValue, type->mAlign);
  6957. }
  6958. return mBfIRBuilder->CreateIntToPtr(curIdxVal, mBfIRBuilder->MapType(ptrType));
  6959. }
  6960. else
  6961. {
  6962. BfArrayType* arrayType = CreateArrayType(type, arrayDim);
  6963. EmitAppendAlign(arrayType->mAlign, type->mSize);
  6964. auto firstElementField = &arrayType->mFieldInstances.back();
  6965. int arrayClassSize = arrayType->mInstSize - firstElementField->mDataSize;
  6966. BfIRValue sizeValue = GetConstValue(arrayClassSize);
  6967. BfIRValue elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->mSize), arraySize);
  6968. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, elementDataSize);
  6969. auto curIdxVal = mBfIRBuilder->CreateLoad(appendIdxVal.mValue);
  6970. if (mSystem->mPtrSize != 4)
  6971. sizeValue = mBfIRBuilder->CreateNumericCast(sizeValue, true, (intPtrType->mSize == 4) ? BfTypeCode_Int32 : BfTypeCode_Int64);
  6972. auto newIdxVal = mBfIRBuilder->CreateAdd(curIdxVal, sizeValue);
  6973. mBfIRBuilder->CreateStore(newIdxVal, appendIdxVal.mValue);
  6974. if (zeroMemory)
  6975. {
  6976. // Only zero out the actual elements
  6977. int dataOffset = arrayType->mFieldInstances.back().mDataOffset;
  6978. auto newOffset = mBfIRBuilder->CreateAdd(curIdxVal, GetConstValue(dataOffset));
  6979. auto newSize = mBfIRBuilder->CreateSub(sizeValue, GetConstValue(dataOffset));
  6980. auto ptr = mBfIRBuilder->CreateIntToPtr(newOffset, mBfIRBuilder->MapType(voidPtrType));
  6981. mBfIRBuilder->CreateMemSet(ptr, GetConstValue8(0), newSize, type->mAlign);
  6982. }
  6983. retTypeInstance = arrayType;
  6984. retValue = mBfIRBuilder->CreateIntToPtr(curIdxVal, mBfIRBuilder->MapType(arrayType));
  6985. }
  6986. }
  6987. else
  6988. {
  6989. auto typeInst = type->ToTypeInstance();
  6990. BfIRValue sizeValue;
  6991. BfIRType toType;
  6992. if (typeInst != NULL)
  6993. {
  6994. EmitAppendAlign(typeInst->mInstAlign, typeInst->mInstSize);
  6995. sizeValue = GetConstValue(typeInst->mInstSize);
  6996. toType = mBfIRBuilder->MapTypeInstPtr(typeInst);
  6997. }
  6998. else
  6999. {
  7000. EmitAppendAlign(type->mAlign, type->mSize);
  7001. sizeValue = GetConstValue(type->mSize);
  7002. auto toPtrType = CreatePointerType(type);
  7003. toType = mBfIRBuilder->MapType(toPtrType);
  7004. }
  7005. auto curIdxVal = mBfIRBuilder->CreateLoad(appendIdxVal.mValue);
  7006. auto newIdxVal = mBfIRBuilder->CreateAdd(curIdxVal, sizeValue);
  7007. mBfIRBuilder->CreateStore(newIdxVal, appendIdxVal.mValue);
  7008. retTypeInstance = typeInst;
  7009. retValue = mBfIRBuilder->CreateIntToPtr(curIdxVal, toType);
  7010. }
  7011. if ((retTypeInstance != NULL) && (retTypeInstance->IsObject()))
  7012. {
  7013. mBfIRBuilder->PopulateType(retTypeInstance);
  7014. auto int8Type = mBfIRBuilder->GetPrimitiveType(BfTypeCode_Int8);
  7015. auto ptrType = mBfIRBuilder->GetPointerTo(int8Type);
  7016. auto ptrPtrType = mBfIRBuilder->GetPointerTo(ptrType);
  7017. auto curThis = GetThis();
  7018. BfIRValue newFlags;
  7019. if (mCompiler->mOptions.mObjectHasDebugFlags)
  7020. {
  7021. auto thisFlagsPtr = mBfIRBuilder->CreateBitCast(curThis.mValue, ptrType);
  7022. auto thisFlags = mBfIRBuilder->CreateLoad(thisFlagsPtr);
  7023. auto maskedThisFlags = mBfIRBuilder->CreateAnd(thisFlags, GetConstValue8(BfObjectFlag_StackAlloc)); // Take 'stack' flag from 'this'
  7024. newFlags = mBfIRBuilder->CreateOr(maskedThisFlags, GetConstValue8(BfObjectFlag_AppendAlloc));
  7025. }
  7026. auto vObjectAddr = mBfIRBuilder->CreateInBoundsGEP(retValue, 0, 0);
  7027. auto vDataRef = CreateClassVDataGlobal(retTypeInstance);
  7028. auto destAddr = mBfIRBuilder->CreateBitCast(vObjectAddr, ptrPtrType);
  7029. auto srcVal = mBfIRBuilder->CreateBitCast(vDataRef, ptrType);
  7030. mBfIRBuilder->CreateStore(srcVal, destAddr);
  7031. if (mCompiler->mOptions.mObjectHasDebugFlags)
  7032. {
  7033. auto flagsPtr = mBfIRBuilder->CreateBitCast(destAddr, ptrType);
  7034. mBfIRBuilder->CreateStore(newFlags, flagsPtr);
  7035. }
  7036. }
  7037. if (appendSizeValue)
  7038. {
  7039. EmitAppendAlign(appendAllocAlign);
  7040. auto curIdxVal = mBfIRBuilder->CreateLoad(appendIdxVal.mValue);
  7041. auto newIdxVal = mBfIRBuilder->CreateAdd(curIdxVal, appendSizeValue);
  7042. mBfIRBuilder->CreateStore(newIdxVal, appendIdxVal.mValue);
  7043. }
  7044. return retValue;
  7045. }
  7046. bool BfModule::IsOptimized()
  7047. {
  7048. if (mProject == NULL)
  7049. return false;
  7050. int optLevel = GetModuleOptions().mOptLevel;
  7051. return (optLevel >= BfOptLevel_O1) && (optLevel <= BfOptLevel_O3);
  7052. }
  7053. bool BfModule::IsTargetingBeefBackend()
  7054. {
  7055. if (mProject == NULL)
  7056. return false;
  7057. return GetModuleOptions().mOptLevel == BfOptLevel_OgPlus;
  7058. }
  7059. bool BfModule::WantsLifetimes()
  7060. {
  7061. if (mProject == NULL)
  7062. return false;
  7063. return GetModuleOptions().mOptLevel == BfOptLevel_OgPlus;
  7064. }
  7065. bool BfModule::HasCompiledOutput()
  7066. {
  7067. return (!mSystem->mIsResolveOnly) && (mIsReified);
  7068. }
  7069. // We will skip the object access check for any occurances of this value
  7070. void BfModule::SkipObjectAccessCheck(BfTypedValue typedVal)
  7071. {
  7072. if ((mBfIRBuilder->mIgnoreWrites) || (!typedVal.mType->IsObjectOrInterface()) || (mCurMethodState == NULL) || (mCurMethodState->mIgnoreObjectAccessCheck))
  7073. return;
  7074. if (!mCompiler->mOptions.mObjectHasDebugFlags)
  7075. return;
  7076. if ((typedVal.mValue.mFlags & BfIRValueFlags_Value) == 0)
  7077. return;
  7078. mCurMethodState->mSkipObjectAccessChecks.Add(typedVal.mValue.mId);
  7079. }
  7080. void BfModule::EmitObjectAccessCheck(BfTypedValue typedVal)
  7081. {
  7082. if ((mBfIRBuilder->mIgnoreWrites) || (!typedVal.mType->IsObjectOrInterface()) || (mCurMethodState == NULL) || (mCurMethodState->mIgnoreObjectAccessCheck))
  7083. return;
  7084. if (!mCompiler->mOptions.mObjectHasDebugFlags)
  7085. return;
  7086. bool emitObjectAccessCheck = mCompiler->mOptions.mEmitObjectAccessCheck;
  7087. auto typeOptions = GetTypeOptions();
  7088. if (typeOptions != NULL)
  7089. emitObjectAccessCheck = BfTypeOptions::Apply(emitObjectAccessCheck, typeOptions->mEmitObjectAccessCheck);
  7090. if (!emitObjectAccessCheck)
  7091. return;
  7092. if ((typedVal.mValue.mFlags & BfIRValueFlags_Value) != 0)
  7093. {
  7094. if (mCurMethodState->mSkipObjectAccessChecks.Contains(typedVal.mValue.mId))
  7095. return;
  7096. }
  7097. if (typedVal.IsAddr())
  7098. typedVal = LoadValue(typedVal);
  7099. mBfIRBuilder->CreateObjectAccessCheck(typedVal.mValue, !IsOptimized());
  7100. }
  7101. void BfModule::EmitEnsureInstructionAt()
  7102. {
  7103. if (mProject == NULL)
  7104. return;
  7105. if ((mBfIRBuilder->mIgnoreWrites) || (!mHasFullDebugInfo) || (IsOptimized()) || (mCompiler->mOptions.mOmitDebugHelpers))
  7106. return;
  7107. mBfIRBuilder->CreateEnsureInstructionAt();
  7108. }
  7109. void BfModule::EmitDynamicCastCheck(const BfTypedValue& targetValue, BfType* targetType, BfIRBlock trueBlock, BfIRBlock falseBlock, bool nullSucceeds)
  7110. {
  7111. if (mBfIRBuilder->mIgnoreWrites)
  7112. return; // Nothing needed here
  7113. auto irb = mBfIRBuilder;
  7114. auto checkBB = irb->CreateBlock("as.check");
  7115. auto isNull = irb->CreateIsNull(targetValue.mValue);
  7116. mBfIRBuilder->CreateCondBr(isNull, nullSucceeds ? trueBlock : falseBlock, checkBB);
  7117. auto intType = GetPrimitiveType(BfTypeCode_IntPtr);
  7118. auto intPtrType = CreatePointerType(intType);
  7119. auto intPtrPtrType = CreatePointerType(intPtrType);
  7120. auto int32Type = GetPrimitiveType(BfTypeCode_Int32);
  7121. auto int32PtrType = CreatePointerType(int32Type);
  7122. auto typeTypeInstance = ResolveTypeDef(mCompiler->mReflectTypeInstanceTypeDef)->ToTypeInstance();
  7123. if (mCompiler->mOptions.mAllowHotSwapping)
  7124. {
  7125. BfExprEvaluator exprEvaluator(this);
  7126. AddBasicBlock(checkBB);
  7127. auto objectParam = mBfIRBuilder->CreateBitCast(targetValue.mValue, mBfIRBuilder->MapType(mContext->mBfObjectType));
  7128. auto moduleMethodInstance = GetMethodByName(mContext->mBfObjectType, targetType->IsInterface() ? "DynamicCastToInterface" : "DynamicCastToTypeId");
  7129. SizedArray<BfIRValue, 4> irArgs;
  7130. irArgs.push_back(objectParam);
  7131. irArgs.push_back(GetConstValue32(targetType->mTypeId));
  7132. auto callResult = exprEvaluator.CreateCall(moduleMethodInstance.mMethodInstance, moduleMethodInstance.mFunc, false, irArgs);
  7133. auto resultType = ResolveTypeDef(mSystem->mTypeBool);
  7134. auto cmpResult = mBfIRBuilder->CreateCmpNE(callResult.mValue, GetDefaultValue(callResult.mType));
  7135. irb->CreateCondBr(cmpResult, trueBlock, falseBlock);
  7136. }
  7137. else
  7138. {
  7139. AddBasicBlock(checkBB);
  7140. BfIRValue vDataPtr = irb->CreateBitCast(targetValue.mValue, irb->MapType(intPtrType));
  7141. vDataPtr = irb->CreateLoad(vDataPtr);
  7142. if (mCompiler->mOptions.mObjectHasDebugFlags)
  7143. vDataPtr = irb->CreateAnd(vDataPtr, irb->CreateConst(BfTypeCode_IntPtr, (uint64)~0xFFULL));
  7144. if (targetType->IsInterface())
  7145. {
  7146. auto targetTypeInst = targetType->ToTypeInstance();
  7147. AddDependency(targetType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ExprTypeReference);
  7148. // Skip past mType, but since a 'GetDynCastVDataCount()' data is included in the sSlotOfs, we need to remove that
  7149. //int inheritanceIdOfs = mSystem->mPtrSize - (mCompiler->GetDynCastVDataCount())*4;
  7150. //vDataPtr = irb->CreateAdd(vDataPtr, irb->CreateConst(BfTypeCode_IntPtr, inheritanceIdOfs));
  7151. vDataPtr = irb->CreateAdd(vDataPtr, irb->GetConfigConst(BfIRConfigConst_DynSlotOfs, BfTypeCode_IntPtr));
  7152. BfIRValue slotOfs = GetInterfaceSlotNum(targetType->ToTypeInstance());
  7153. BfIRValue slotByteOfs = irb->CreateMul(slotOfs, irb->CreateConst(BfTypeCode_Int32, 4));
  7154. slotByteOfs = irb->CreateNumericCast(slotByteOfs, false, BfTypeCode_IntPtr);
  7155. vDataPtr = irb->CreateAdd(vDataPtr, slotByteOfs);
  7156. vDataPtr = irb->CreateIntToPtr(vDataPtr, irb->MapType(int32PtrType));
  7157. BfIRValue typeId = irb->CreateLoad(vDataPtr);
  7158. BfIRValue cmpResult = irb->CreateCmpEQ(typeId, irb->CreateConst(BfTypeCode_Int32, targetType->mTypeId));
  7159. irb->CreateCondBr(cmpResult, trueBlock, falseBlock);
  7160. }
  7161. else
  7162. {
  7163. if (!targetType->IsTypeInstance())
  7164. targetType = GetWrappedStructType(targetType);
  7165. AddDependency(targetType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ExprTypeReference);
  7166. int inheritanceIdOfs = mSystem->mPtrSize;
  7167. vDataPtr = irb->CreateAdd(vDataPtr, irb->CreateConst(BfTypeCode_IntPtr, inheritanceIdOfs));
  7168. vDataPtr = irb->CreateIntToPtr(vDataPtr, irb->MapType(int32PtrType));
  7169. BfIRValue objInheritanceId = irb->CreateLoad(vDataPtr);
  7170. BfIRValue typeDataRef = CreateTypeDataRef(targetType);
  7171. BfIRValue typeInstDataRef = irb->CreateBitCast(typeDataRef, irb->MapType(typeTypeInstance, BfIRPopulateType_Full));
  7172. auto fieldInst = &typeTypeInstance->mFieldInstances[9];
  7173. BF_ASSERT(fieldInst->GetFieldDef()->mName == "mInheritanceId");
  7174. BfIRValue gepValue = irb->CreateInBoundsGEP(typeInstDataRef, 0, fieldInst->mDataIdx);
  7175. BfIRValue wantInheritanceId = irb->CreateLoad(gepValue);
  7176. fieldInst = &typeTypeInstance->mFieldInstances[10];
  7177. BF_ASSERT(fieldInst->GetFieldDef()->mName == "mInheritanceCount");
  7178. gepValue = irb->CreateInBoundsGEP(typeInstDataRef, 0, fieldInst->mDataIdx);
  7179. BfIRValue inheritanceCount = irb->CreateLoad(gepValue);
  7180. BfIRValue idDiff = irb->CreateSub(objInheritanceId, wantInheritanceId);
  7181. BfIRValue cmpResult = irb->CreateCmpLTE(idDiff, inheritanceCount, false);
  7182. irb->CreateCondBr(cmpResult, trueBlock, falseBlock);
  7183. }
  7184. }
  7185. }
  7186. void BfModule::EmitDynamicCastCheck(BfTypedValue typedVal, BfType* type, bool allowNull)
  7187. {
  7188. if (mBfIRBuilder->mIgnoreWrites)
  7189. return;
  7190. bool emitDynamicCastCheck = mCompiler->mOptions.mEmitDynamicCastCheck;
  7191. auto typeOptions = GetTypeOptions();
  7192. if (typeOptions != NULL)
  7193. emitDynamicCastCheck = BfTypeOptions::Apply(emitDynamicCastCheck, typeOptions->mEmitDynamicCastCheck);
  7194. if (emitDynamicCastCheck)
  7195. {
  7196. int wantTypeId = 0;
  7197. if (!type->IsGenericParam())
  7198. wantTypeId = type->mTypeId;
  7199. BfIRBlock failBlock = mBfIRBuilder->CreateBlock("dynFail");
  7200. BfIRBlock endBlock = mBfIRBuilder->CreateBlock("dynEnd");
  7201. EmitDynamicCastCheck(typedVal, type, endBlock, failBlock, allowNull ? true : false);
  7202. AddBasicBlock(failBlock);
  7203. SizedArray<BfIRValue, 8> llvmArgs;
  7204. auto bitAddr = mBfIRBuilder->CreateBitCast(typedVal.mValue, mBfIRBuilder->MapType(mContext->mBfObjectType));
  7205. llvmArgs.push_back(bitAddr);
  7206. llvmArgs.push_back(GetConstValue32(wantTypeId));
  7207. auto objDynCheck = GetInternalMethod("ObjectDynCheckFailed");
  7208. BF_ASSERT(objDynCheck);
  7209. if (objDynCheck)
  7210. {
  7211. auto callInst = mBfIRBuilder->CreateCall(objDynCheck.mFunc, llvmArgs);
  7212. }
  7213. mBfIRBuilder->CreateBr(endBlock);
  7214. AddBasicBlock(endBlock);
  7215. }
  7216. }
  7217. BfTypedValue BfModule::BoxValue(BfAstNode* srcNode, BfTypedValue typedVal, BfType* toType, const BfAllocTarget& allocTarget, bool callDtor)
  7218. {
  7219. if (mBfIRBuilder->mIgnoreWrites)
  7220. {
  7221. if (toType == mContext->mBfObjectType)
  7222. return BfTypedValue(mBfIRBuilder->GetFakeVal(), toType);
  7223. }
  7224. BP_ZONE("BoxValue");
  7225. BfTypeInstance* fromStructTypeInstance = typedVal.mType->ToTypeInstance();
  7226. if (typedVal.mType->IsNullable())
  7227. {
  7228. typedVal = MakeAddressable(typedVal);
  7229. auto innerType = typedVal.mType->GetUnderlyingType();
  7230. if (!innerType->IsValueType())
  7231. {
  7232. if (!mIgnoreErrors)
  7233. Fail("Only value types can be boxed", srcNode);
  7234. return BfTypedValue();
  7235. }
  7236. auto boxedType = CreateBoxedType(innerType);
  7237. auto resultType = toType;
  7238. if (resultType == NULL)
  7239. resultType = boxedType;
  7240. if (mBfIRBuilder->mIgnoreWrites)
  7241. return BfTypedValue(mBfIRBuilder->GetFakeVal(), resultType);
  7242. auto prevBB = mBfIRBuilder->GetInsertBlock();
  7243. auto boxBB = mBfIRBuilder->CreateBlock("boxedN.notNull");
  7244. auto endBB = mBfIRBuilder->CreateBlock("boxedN.end");
  7245. mBfIRBuilder->PopulateType(typedVal.mType);
  7246. auto hasValueAddr = mBfIRBuilder->CreateInBoundsGEP(typedVal.mValue, 0, innerType->IsValuelessType() ? 1 : 2); // has_value
  7247. auto hasValue = mBfIRBuilder->CreateLoad(hasValueAddr);
  7248. mBfIRBuilder->CreateCondBr(hasValue, boxBB, endBB);
  7249. AddDependency(boxedType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ReadFields);
  7250. mBfIRBuilder->AddBlock(boxBB);
  7251. mBfIRBuilder->SetInsertPoint(boxBB);
  7252. BfScopeData newScope;
  7253. newScope.mOuterIsConditional = true;
  7254. mCurMethodState->AddScope(&newScope);
  7255. NewScopeState();
  7256. BfIRValue nullableValueAddr;
  7257. BfIRValue loadedVal;
  7258. if (innerType->IsValuelessType())
  7259. {
  7260. loadedVal = mBfIRBuilder->GetFakeVal();
  7261. }
  7262. else
  7263. {
  7264. nullableValueAddr = mBfIRBuilder->CreateInBoundsGEP(typedVal.mValue, 0, 1); // value
  7265. loadedVal = mBfIRBuilder->CreateLoad(nullableValueAddr);
  7266. }
  7267. auto boxedVal = BoxValue(srcNode, BfTypedValue(loadedVal, fromStructTypeInstance->GetUnderlyingType()), resultType, allocTarget, callDtor);
  7268. RestoreScopeState();
  7269. if (!boxedVal)
  7270. return BfTypedValue();
  7271. mBfIRBuilder->CreateBr(endBB);
  7272. auto boxBBEnd = mBfIRBuilder->GetInsertBlock();
  7273. mBfIRBuilder->AddBlock(endBB);
  7274. mBfIRBuilder->SetInsertPoint(endBB);
  7275. auto phi = mBfIRBuilder->CreatePhi(mBfIRBuilder->MapType(resultType), 2);
  7276. mBfIRBuilder->AddPhiIncoming(phi, boxedVal.mValue, boxBBEnd);
  7277. mBfIRBuilder->AddPhiIncoming(phi, GetDefaultValue(resultType), prevBB);
  7278. return BfTypedValue(phi, resultType);
  7279. }
  7280. bool alreadyCheckedCast = false;
  7281. BfTypeInstance* toTypeInstance = NULL;
  7282. if (toType != NULL)
  7283. toTypeInstance = toType->ToTypeInstance();
  7284. bool isStructPtr = typedVal.mType->IsStructPtr();
  7285. if (fromStructTypeInstance == NULL)
  7286. {
  7287. auto primType = (BfPrimitiveType*)typedVal.mType;
  7288. fromStructTypeInstance = GetWrappedStructType(typedVal.mType);
  7289. if (isStructPtr)
  7290. {
  7291. if ((toTypeInstance != NULL) && (TypeIsSubTypeOf(fromStructTypeInstance, toTypeInstance)))
  7292. alreadyCheckedCast = true;
  7293. fromStructTypeInstance = typedVal.mType->GetUnderlyingType()->ToTypeInstance();
  7294. }
  7295. }
  7296. if (fromStructTypeInstance == NULL)
  7297. return BfTypedValue();
  7298. // Need to box it
  7299. bool isBoxedType = (fromStructTypeInstance != NULL) && (toType->IsBoxed());
  7300. if ((toType == NULL) || (toType == mContext->mBfObjectType) || (isBoxedType) || (alreadyCheckedCast) || (TypeIsSubTypeOf(fromStructTypeInstance, toTypeInstance)))
  7301. {
  7302. if (mBfIRBuilder->mIgnoreWrites)
  7303. return BfTypedValue(mBfIRBuilder->GetFakeVal(), (toType != NULL) ? toType : CreateBoxedType(typedVal.mType));
  7304. auto boxedType = CreateBoxedType(typedVal.mType);
  7305. mBfIRBuilder->PopulateType(boxedType);
  7306. AddDependency(boxedType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ReadFields);
  7307. auto allocaInst = AllocFromType(boxedType, allocTarget, BfIRValue(), BfIRValue(), 0, callDtor ? BfAllocFlags_None : BfAllocFlags_NoDtorCall);
  7308. BfTypedValue boxedTypedValue(allocaInst, boxedType);
  7309. mBfIRBuilder->SetName(allocaInst, "boxed." + fromStructTypeInstance->mTypeDef->mName->ToString());
  7310. if (boxedType->IsUnspecializedType())
  7311. {
  7312. BF_ASSERT((srcNode == NULL) || (mCurMethodInstance->mIsUnspecialized));
  7313. }
  7314. else
  7315. {
  7316. PopulateType(fromStructTypeInstance);
  7317. if (!fromStructTypeInstance->IsValuelessType())
  7318. {
  7319. typedVal = LoadValue(typedVal);
  7320. auto valPtr = mBfIRBuilder->CreateInBoundsGEP(allocaInst, 0, 1);
  7321. if ((typedVal.mType != fromStructTypeInstance) && (!isStructPtr))
  7322. {
  7323. auto ptrType = CreatePointerType(typedVal.mType);
  7324. valPtr = mBfIRBuilder->CreateBitCast(valPtr, mBfIRBuilder->MapType(ptrType));
  7325. }
  7326. if (typedVal.IsSplat())
  7327. {
  7328. AggregateSplatIntoAddr(typedVal, valPtr);
  7329. }
  7330. else
  7331. mBfIRBuilder->CreateStore(typedVal.mValue, valPtr);
  7332. }
  7333. }
  7334. if (toType == NULL)
  7335. {
  7336. return BfTypedValue(allocaInst, boxedType);
  7337. }
  7338. else
  7339. {
  7340. auto castedValue = mBfIRBuilder->CreateBitCast(allocaInst, mBfIRBuilder->MapType(toType));
  7341. return BfTypedValue(castedValue, toType);
  7342. }
  7343. }
  7344. return BfTypedValue();
  7345. }
  7346. bool BfModule::GetBasePropertyDef(BfPropertyDef*& propDef, BfTypeInstance*& typeInst)
  7347. {
  7348. BfTypeInstance* checkTypeInst = typeInst;
  7349. while (checkTypeInst != NULL)
  7350. {
  7351. for (auto checkProp : checkTypeInst->mTypeDef->mProperties)
  7352. {
  7353. if (checkProp->mName == propDef->mName)
  7354. {
  7355. auto checkPropDeclaration = BfNodeDynCast<BfPropertyDeclaration>(checkProp->mFieldDeclaration);
  7356. if ((checkPropDeclaration == NULL) || (checkPropDeclaration->mVirtualSpecifier == NULL) || (checkPropDeclaration->mVirtualSpecifier->GetToken() == BfToken_Virtual))
  7357. {
  7358. propDef = checkProp;
  7359. typeInst = checkTypeInst;
  7360. return true;
  7361. }
  7362. }
  7363. }
  7364. checkTypeInst = checkTypeInst->mBaseType;
  7365. }
  7366. return false;
  7367. }
  7368. BfMethodInstance* BfModule::GetRawMethodInstanceAtIdx(BfTypeInstance* typeInstance, int methodIdx, const char* assertName)
  7369. {
  7370. if (!typeInstance->mResolvingVarField)
  7371. {
  7372. if (typeInstance->IsIncomplete())
  7373. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  7374. }
  7375. else
  7376. {
  7377. if (methodIdx >= (int)typeInstance->mMethodInstanceGroups.size())
  7378. {
  7379. AssertErrorState();
  7380. return NULL;
  7381. }
  7382. }
  7383. if (assertName != NULL)
  7384. {
  7385. BF_ASSERT(typeInstance->mTypeDef->mMethods[methodIdx]->mName == assertName);
  7386. }
  7387. auto& methodGroup = typeInstance->mMethodInstanceGroups[methodIdx];
  7388. if (methodGroup.mDefault == NULL)
  7389. {
  7390. if (!mCompiler->mIsResolveOnly)
  7391. {
  7392. BF_ASSERT((methodGroup.mOnDemandKind == BfMethodOnDemandKind_NoDecl_AwaitingReference) || (methodGroup.mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingDecl));
  7393. methodGroup.mOnDemandKind = BfMethodOnDemandKind_Decl_AwaitingDecl;
  7394. // Get it from the owning module so we don't create a reference prematurely...
  7395. auto declModule = typeInstance->mModule;
  7396. return declModule->GetMethodInstance(typeInstance, typeInstance->mTypeDef->mMethods[methodIdx], BfTypeVector(), (BfGetMethodInstanceFlags)(BfGetMethodInstanceFlag_UnspecializedPass | BfGetMethodInstanceFlag_Unreified)).mMethodInstance;
  7397. }
  7398. else
  7399. {
  7400. auto declModule = typeInstance->mModule;
  7401. return declModule->GetMethodInstance(typeInstance, typeInstance->mTypeDef->mMethods[methodIdx], BfTypeVector(), (BfGetMethodInstanceFlags)(BfGetMethodInstanceFlag_UnspecializedPass)).mMethodInstance;
  7402. }
  7403. }
  7404. auto methodInstance = typeInstance->mMethodInstanceGroups[methodIdx].mDefault;
  7405. //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
  7406. // be from a call to the NON-raw version
  7407. // if (!methodInstance->mMethodInstanceGroup->IsImplemented())
  7408. // {
  7409. // methodInstance->mIsReified = mIsReified;
  7410. // if (methodInstance->mMethodProcessRequest == NULL)
  7411. // typeInstance->mModule->AddMethodToWorkList(methodInstance);
  7412. // }
  7413. return methodInstance;
  7414. }
  7415. BfMethodInstance* BfModule::GetRawMethodInstance(BfTypeInstance* typeInstance, BfMethodDef* methodDef)
  7416. {
  7417. if (methodDef->mIsLocalMethod)
  7418. {
  7419. return GetMethodInstance(typeInstance, methodDef, BfTypeVector()).mMethodInstance;
  7420. }
  7421. return GetRawMethodInstanceAtIdx(typeInstance, methodDef->mIdx);
  7422. }
  7423. BfMethodInstance* BfModule::GetRawMethodByName(BfTypeInstance* typeInstance, const StringImpl& methodName, int paramCount, bool checkBase, bool allowMixin)
  7424. {
  7425. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  7426. while (typeInstance != NULL)
  7427. {
  7428. typeInstance->mTypeDef->PopulateMemberSets();
  7429. BfMemberSetEntry* entry = NULL;
  7430. BfMethodDef* methodDef = NULL;
  7431. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(methodName, &entry))
  7432. methodDef = (BfMethodDef*)entry->mMemberDef;
  7433. while (methodDef != NULL)
  7434. {
  7435. if (((allowMixin) || (methodDef->mMethodType != BfMethodType_Mixin)) &&
  7436. (methodDef->mGenericParams.size() == 0) &&
  7437. ((paramCount == -1) || (paramCount == (int)methodDef->mParams.size())))
  7438. return GetRawMethodInstance(typeInstance, methodDef);
  7439. methodDef = methodDef->mNextWithSameName;
  7440. }
  7441. if (!checkBase)
  7442. break;
  7443. typeInstance = typeInstance->mBaseType;
  7444. }
  7445. return NULL;
  7446. }
  7447. BfMethodInstance* BfModule::GetUnspecializedMethodInstance(BfMethodInstance* methodInstance)
  7448. {
  7449. if ((methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mMethodGenericArguments.size() != 0))
  7450. methodInstance = methodInstance->mMethodInstanceGroup->mDefault;
  7451. auto owner = methodInstance->mMethodInstanceGroup->mOwner;
  7452. if (!owner->IsGenericTypeInstance())
  7453. return methodInstance;
  7454. auto genericType = (BfGenericTypeInstance*)owner;
  7455. if (genericType->IsUnspecializedType())
  7456. return methodInstance;
  7457. auto unspecializedType = ResolveTypeDef(genericType->mTypeDef);
  7458. if (unspecializedType == NULL)
  7459. {
  7460. AssertErrorState();
  7461. return methodInstance;
  7462. }
  7463. if (unspecializedType == NULL)
  7464. return methodInstance;
  7465. auto unspecializedTypeInst = unspecializedType->ToTypeInstance();
  7466. return GetRawMethodInstanceAtIdx(unspecializedTypeInst, methodInstance->mMethodDef->mIdx);
  7467. }
  7468. int BfModule::GetGenericParamAndReturnCount(BfMethodInstance* methodInstance)
  7469. {
  7470. int genericCount = 0;
  7471. auto unspecializedMethodInstance = GetUnspecializedMethodInstance(methodInstance);
  7472. for (int paramIdx = 0; paramIdx < unspecializedMethodInstance->GetParamCount(); paramIdx++)
  7473. {
  7474. auto param = unspecializedMethodInstance->GetParamType(paramIdx);
  7475. if (param->IsGenericParam())
  7476. genericCount++;
  7477. }
  7478. if (unspecializedMethodInstance->mReturnType->IsGenericParam())
  7479. genericCount++;
  7480. return genericCount;
  7481. }
  7482. BfModule* BfModule::GetSpecializedMethodModule(const SizedArrayImpl<BfProject*>& projectList)
  7483. {
  7484. BF_ASSERT(!mIsScratchModule);
  7485. BF_ASSERT(mIsReified);
  7486. BfModule* mainModule = this;
  7487. if (mParentModule != NULL)
  7488. mainModule = mParentModule;
  7489. BfModule* specModule = NULL;
  7490. BfModule** specModulePtr = NULL;
  7491. if (mainModule->mSpecializedMethodModules.TryGetValueWith(projectList, &specModulePtr))
  7492. {
  7493. return *specModulePtr;
  7494. }
  7495. else
  7496. {
  7497. String specModuleName = mModuleName;
  7498. for (auto bfProject : projectList)
  7499. specModuleName += StrFormat("@%s", bfProject->mName.c_str());
  7500. specModule = new BfModule(mContext, specModuleName);
  7501. specModule->mProject = mainModule->mProject;
  7502. specModule->mParentModule = mainModule;
  7503. specModule->mIsSpecializedMethodModuleRoot = true;
  7504. specModule->Init();
  7505. Array<BfProject*> projList;
  7506. for (auto project : projectList)
  7507. projList.Add(project);
  7508. mainModule->mSpecializedMethodModules[projList] = specModule;
  7509. }
  7510. return specModule;
  7511. }
  7512. BfIRValue BfModule::CreateFunctionFrom(BfMethodInstance* methodInstance, bool tryExisting, bool isInlined)
  7513. {
  7514. if (mCompiler->IsSkippingExtraResolveChecks())
  7515. return BfIRValue();
  7516. if (methodInstance->mMethodInstanceGroup->mOwner->IsInterface())
  7517. {
  7518. //BF_ASSERT(!methodInstance->mIRFunction);
  7519. return BfIRValue();
  7520. }
  7521. auto methodDef = methodInstance->mMethodDef;
  7522. StringT<128> methodName;
  7523. BfMangler::Mangle(methodName, mCompiler->GetMangleKind(), methodInstance);
  7524. if (isInlined != methodInstance->mAlwaysInline)
  7525. {
  7526. if (isInlined)
  7527. methodName += "__INLINE";
  7528. else
  7529. methodName += "__NOINLINE";
  7530. }
  7531. if (tryExisting)
  7532. {
  7533. auto func = mBfIRBuilder->GetFunction(methodName);
  7534. if (func)
  7535. return func;
  7536. }
  7537. if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  7538. {
  7539. if (methodDeclaration->mExternSpecifier != NULL)
  7540. {
  7541. auto intrinsic = GetIntrinsic(methodInstance);
  7542. if (intrinsic)
  7543. return intrinsic;
  7544. // If we have multiple entries with the same name, they could have different arguments and will generate other errors...
  7545. /*auto func = mBfIRBuilder->GetFunction(methodName);
  7546. if (func)
  7547. return func;*/
  7548. }
  7549. }
  7550. if (methodInstance->GetImportCallKind() != BfImportCallKind_None)
  7551. {
  7552. return CreateDllImportGlobalVar(methodInstance, false);
  7553. }
  7554. BfIRType returnType;
  7555. SizedArray<BfIRType, 8> paramTypes;
  7556. methodInstance->GetIRFunctionInfo(this, returnType, paramTypes);
  7557. auto funcType = mBfIRBuilder->CreateFunctionType(returnType, paramTypes);
  7558. auto func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, methodName);
  7559. auto callingConv = GetCallingConvention(methodInstance->GetOwner(), methodDef);
  7560. if (callingConv != BfIRCallingConv_CDecl)
  7561. mBfIRBuilder->SetFuncCallingConv(func, callingConv);
  7562. SetupIRMethod(methodInstance, func, isInlined);
  7563. // auto srcModule = methodInstance->GetOwner()->GetModule();
  7564. // if ((srcModule != NULL) && (srcModule->mProject != mProject))
  7565. // {
  7566. // if (srcModule->mProject->mTargetType == BfTargetType_BeefDynLib)
  7567. // {
  7568. // mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_DllImport);
  7569. // }
  7570. // }
  7571. return func;
  7572. }
  7573. BfModuleMethodInstance BfModule::GetMethodInstanceAtIdx(BfTypeInstance* typeInstance, int methodIdx, const char* assertName)
  7574. {
  7575. if (assertName != NULL)
  7576. {
  7577. BF_ASSERT(typeInstance->mTypeDef->mMethods[methodIdx]->mName == assertName);
  7578. }
  7579. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  7580. auto methodInstance = typeInstance->mMethodInstanceGroups[methodIdx].mDefault;
  7581. if ((methodInstance != NULL) && (mIsReified) && (!methodInstance->mIsReified))
  7582. {
  7583. // Can't use it, not reified
  7584. methodInstance = NULL;
  7585. }
  7586. if ((methodInstance != NULL) && (mBfIRBuilder != NULL) && (mBfIRBuilder->mIgnoreWrites) &&
  7587. (methodInstance->mMethodInstanceGroup->IsImplemented()))
  7588. {
  7589. BfIRFunction func(mBfIRBuilder->GetFakeVal());
  7590. return BfModuleMethodInstance(methodInstance, func);
  7591. }
  7592. return GetMethodInstance(typeInstance, typeInstance->mTypeDef->mMethods[methodIdx], BfTypeVector());
  7593. }
  7594. BfModuleMethodInstance BfModule::GetMethodByName(BfTypeInstance* typeInstance, const StringImpl& methodName, int paramCount, bool checkBase)
  7595. {
  7596. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  7597. while (typeInstance != NULL)
  7598. {
  7599. typeInstance->mTypeDef->PopulateMemberSets();
  7600. BfMemberSetEntry* entry = NULL;
  7601. BfMethodDef* methodDef = NULL;
  7602. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(methodName, &entry))
  7603. methodDef = (BfMethodDef*)entry->mMemberDef;
  7604. while (methodDef != NULL)
  7605. {
  7606. if ((methodDef->mMethodType != BfMethodType_Mixin) &&
  7607. (methodDef->mGenericParams.size() == 0) &&
  7608. ((paramCount == -1) || (paramCount == (int)methodDef->mParams.size())))
  7609. return GetMethodInstanceAtIdx(typeInstance, methodDef->mIdx);
  7610. methodDef = methodDef->mNextWithSameName;
  7611. }
  7612. if (!checkBase)
  7613. break;
  7614. typeInstance = typeInstance->mBaseType;
  7615. }
  7616. return BfModuleMethodInstance();
  7617. }
  7618. BfModuleMethodInstance BfModule::GetMethodByName(BfTypeInstance* typeInstance, const StringImpl& methodName, const Array<BfType*>& paramTypes, bool checkBase)
  7619. {
  7620. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  7621. while (typeInstance != NULL)
  7622. {
  7623. typeInstance->mTypeDef->PopulateMemberSets();
  7624. BfMemberSetEntry* entry = NULL;
  7625. BfMethodDef* methodDef = NULL;
  7626. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(methodName, &entry))
  7627. methodDef = (BfMethodDef*)entry->mMemberDef;
  7628. while (methodDef != NULL)
  7629. {
  7630. if ((methodDef->mMethodType != BfMethodType_Mixin) &&
  7631. (methodDef->mGenericParams.size() == 0) &&
  7632. (paramTypes.size() == methodDef->mParams.size()))
  7633. {
  7634. auto moduleMethodInstance = GetMethodInstanceAtIdx(typeInstance, methodDef->mIdx);
  7635. if (moduleMethodInstance.mMethodInstance != NULL)
  7636. {
  7637. bool matches = true;
  7638. for (int paramIdx = 0; paramIdx < (int)paramTypes.size(); paramIdx++)
  7639. {
  7640. if (moduleMethodInstance.mMethodInstance->GetParamType(paramIdx) != paramTypes[paramIdx])
  7641. matches = false;
  7642. }
  7643. if (matches)
  7644. return moduleMethodInstance;
  7645. }
  7646. }
  7647. methodDef = methodDef->mNextWithSameName;
  7648. }
  7649. if (!checkBase)
  7650. break;
  7651. typeInstance = typeInstance->mBaseType;
  7652. }
  7653. return BfModuleMethodInstance();
  7654. }
  7655. BfModuleMethodInstance BfModule::GetInternalMethod(const StringImpl& methodName, int paramCount)
  7656. {
  7657. auto internalType = ResolveTypeDef(mCompiler->mInternalTypeDef);
  7658. PopulateType(internalType);
  7659. auto moduleMethodInstance = GetMethodByName(internalType->ToTypeInstance(), methodName, paramCount);
  7660. if (!moduleMethodInstance)
  7661. {
  7662. Fail(StrFormat("Failed to find System.Internal method '%s'", methodName.c_str()));
  7663. }
  7664. return moduleMethodInstance;
  7665. }
  7666. bool BfModule::IsMethodImplementedAndReified(BfTypeInstance* typeInstance, const StringImpl& methodName, int paramCount, bool checkBase)
  7667. {
  7668. while (typeInstance != NULL)
  7669. {
  7670. typeInstance->mTypeDef->PopulateMemberSets();
  7671. BfMemberSetEntry* entry = NULL;
  7672. BfMethodDef* methodDef = NULL;
  7673. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(methodName, &entry))
  7674. methodDef = (BfMethodDef*)entry->mMemberDef;
  7675. while (methodDef != NULL)
  7676. {
  7677. if ((methodDef->mMethodType != BfMethodType_Mixin) &&
  7678. (methodDef->mGenericParams.size() == 0) &&
  7679. ((paramCount == -1) || (paramCount == (int)methodDef->mParams.size())))
  7680. {
  7681. auto& methodInstanceGroup = typeInstance->mMethodInstanceGroups[methodDef->mIdx];
  7682. if (!methodInstanceGroup.IsImplemented())
  7683. return false;
  7684. if (methodInstanceGroup.mDefault == NULL)
  7685. return false;
  7686. return methodInstanceGroup.mDefault->mIsReified;
  7687. }
  7688. methodDef = methodDef->mNextWithSameName;
  7689. }
  7690. if (!checkBase)
  7691. break;
  7692. typeInstance = typeInstance->mBaseType;
  7693. }
  7694. return false;
  7695. }
  7696. bool BfModule::HasMixin(BfTypeInstance* typeInstance, const StringImpl& methodName, int paramCount, bool checkBase)
  7697. {
  7698. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  7699. while (typeInstance != NULL)
  7700. {
  7701. typeInstance->mTypeDef->PopulateMemberSets();
  7702. BfMemberSetEntry* entry = NULL;
  7703. BfMethodDef* methodDef = NULL;
  7704. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(methodName, &entry))
  7705. methodDef = (BfMethodDef*)entry->mMemberDef;
  7706. while (methodDef != NULL)
  7707. {
  7708. if ((methodDef->mMethodType == BfMethodType_Mixin) &&
  7709. ((paramCount == -1) || (paramCount == (int)methodDef->mParams.size())))
  7710. return true;
  7711. methodDef = methodDef->mNextWithSameName;
  7712. }
  7713. if (!checkBase)
  7714. break;
  7715. typeInstance = typeInstance->mBaseType;
  7716. }
  7717. return BfModuleMethodInstance();
  7718. }
  7719. BfFieldInstance* BfModule::GetFieldByName(BfTypeInstance* typeInstance, const StringImpl& fieldName)
  7720. {
  7721. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  7722. typeInstance->mTypeDef->PopulateMemberSets();
  7723. BfMemberSetEntry* entry = NULL;
  7724. BfFieldDef* fieldDef = NULL;
  7725. if (typeInstance->mTypeDef->mFieldSet.TryGetWith(fieldName, &entry))
  7726. {
  7727. fieldDef = (BfFieldDef*)entry->mMemberDef;
  7728. return &typeInstance->mFieldInstances[fieldDef->mIdx];
  7729. }
  7730. // for (auto& fieldInst : typeInstance->mFieldInstances)
  7731. // {
  7732. // auto fieldDef = fieldInst.GetFieldDef();
  7733. // if ((fieldDef != NULL) && (fieldDef->mName == fieldName))
  7734. // return &fieldInst;
  7735. // }
  7736. return NULL;
  7737. }
  7738. String BfModule::MethodToString(BfMethodInstance* methodInst, BfMethodNameFlags methodNameFlags, BfTypeVector* methodGenericArgs)
  7739. {
  7740. auto methodDef = methodInst->mMethodDef;
  7741. bool allowResolveGenericParamNames = ((methodNameFlags & BfMethodNameFlag_ResolveGenericParamNames) != 0);
  7742. BfTypeNameFlags typeNameFlags = BfTypeNameFlags_None;
  7743. if ((mCurTypeInstance == NULL) || (!mCurTypeInstance->IsUnspecializedTypeVariation()))
  7744. typeNameFlags = BfTypeNameFlag_ResolveGenericParamNames;
  7745. BfType* type = methodInst->mMethodInstanceGroup->mOwner;
  7746. if ((methodGenericArgs != NULL) && (type->IsUnspecializedType()))
  7747. type = ResolveGenericType(type, *methodGenericArgs);
  7748. String methodName;
  7749. if ((methodNameFlags & BfMethodNameFlag_OmitTypeName) == 0)
  7750. {
  7751. methodName = TypeToString(type, typeNameFlags);
  7752. if (methodName == "$")
  7753. methodName = "";
  7754. else
  7755. methodName += ".";
  7756. }
  7757. String accessorString;
  7758. StringT<64> methodDefName = methodInst->mMethodDef->mName;
  7759. if (methodInst->mMethodDef->mIsLocalMethod)
  7760. {
  7761. int atPos = (int)methodDefName.IndexOf('$');
  7762. methodDefName.RemoveToEnd(atPos);
  7763. methodDefName.Replace("@", ".");
  7764. }
  7765. else
  7766. {
  7767. int atPos = (int)methodDefName.IndexOf('$');
  7768. if (atPos != -1)
  7769. {
  7770. accessorString = methodDefName.Substring(0, atPos);
  7771. if ((accessorString == "get") || (accessorString == "set"))
  7772. {
  7773. methodDefName = methodDefName.Substring(atPos + 1);
  7774. }
  7775. else
  7776. accessorString = "";
  7777. }
  7778. }
  7779. if ((methodInst->mMethodInfoEx != NULL) && (methodInst->mMethodInfoEx->mForeignType != NULL))
  7780. {
  7781. BfTypeNameFlags typeNameFlags = BfTypeNameFlags_None;
  7782. if (!methodInst->mIsUnspecializedVariation && allowResolveGenericParamNames)
  7783. typeNameFlags = BfTypeNameFlag_ResolveGenericParamNames;
  7784. methodName += TypeToString(methodInst->mMethodInfoEx->mForeignType, typeNameFlags);
  7785. methodName += ".";
  7786. }
  7787. if ((methodInst->mMethodInfoEx != NULL) && (methodInst->mMethodInfoEx->mExplicitInterface != NULL))
  7788. {
  7789. BfTypeNameFlags typeNameFlags = BfTypeNameFlags_None;
  7790. if (!methodInst->mIsUnspecializedVariation && allowResolveGenericParamNames)
  7791. typeNameFlags = BfTypeNameFlag_ResolveGenericParamNames;
  7792. methodName += TypeToString(methodInst->mMethodInfoEx->mExplicitInterface, typeNameFlags);
  7793. methodName += ".";
  7794. }
  7795. if (methodDef->mMethodType == BfMethodType_Operator)
  7796. {
  7797. BfOperatorDef* operatorDef = (BfOperatorDef*)methodDef;
  7798. if (operatorDef->mOperatorDeclaration->mIsConvOperator)
  7799. {
  7800. // Don't add explicit/implicit part, since that's not available in GCC mangling
  7801. /*if (operatorDef->mOperatorDeclaration->mExplicitToken != NULL)
  7802. {
  7803. if (operatorDef->mOperatorDeclaration->mExplicitToken->GetToken() == BfToken_Explicit)
  7804. methodName += "explicit ";
  7805. else if (operatorDef->mOperatorDeclaration->mExplicitToken->GetToken() == BfToken_Explicit)
  7806. methodName += "explicit ";
  7807. }*/
  7808. methodName += "operator ";
  7809. if (methodInst->mReturnType != NULL)
  7810. methodName += TypeToString(methodInst->mReturnType);
  7811. }
  7812. else
  7813. {
  7814. methodName += "operator";
  7815. if (operatorDef->mOperatorDeclaration->mOpTypeToken != NULL)
  7816. methodName += BfTokenToString(operatorDef->mOperatorDeclaration->mOpTypeToken->GetToken());
  7817. }
  7818. }
  7819. else if (methodDef->mMethodType == BfMethodType_Ctor)
  7820. {
  7821. if (methodDef->mIsStatic)
  7822. methodName += "__BfStaticCtor";
  7823. else
  7824. methodName += "this";
  7825. accessorString = "";
  7826. }
  7827. else if (methodDef->mMethodType == BfMethodType_PropertyGetter)
  7828. {
  7829. methodDef->GetRefNode()->ToString(methodName);
  7830. methodName += " get accessor";
  7831. return methodName;
  7832. }
  7833. else if (methodDef->mMethodType == BfMethodType_PropertySetter)
  7834. {
  7835. methodDef->GetRefNode()->ToString(methodName);
  7836. methodName += " set accessor";
  7837. return methodName;
  7838. }
  7839. else
  7840. methodName += methodDefName;
  7841. BfTypeVector newMethodGenericArgs;
  7842. if ((methodInst->mMethodInfoEx != NULL) && (methodInst->mMethodInfoEx->mMethodGenericArguments.size() != 0))
  7843. {
  7844. methodName += "<";
  7845. for (int i = 0; i < (int) methodInst->mMethodInfoEx->mMethodGenericArguments.size(); i++)
  7846. {
  7847. if (i > 0)
  7848. methodName += ", ";
  7849. BfTypeNameFlags typeNameFlags = BfTypeNameFlags_None;
  7850. //Why did we have this methodInst->mIsUnspecializedVariation check? Sometimes we do need to show errors calling methods that refer back to our types
  7851. //if (!methodInst->mIsUnspecializedVariation && allowResolveGenericParamNames)
  7852. if (allowResolveGenericParamNames)
  7853. typeNameFlags = BfTypeNameFlag_ResolveGenericParamNames;
  7854. BfType* type = methodInst->mMethodInfoEx->mMethodGenericArguments[i];
  7855. if ((methodGenericArgs != NULL) && (type->IsUnspecializedType()))
  7856. {
  7857. bool hasEmpty = false;
  7858. for (auto arg : *methodGenericArgs)
  7859. {
  7860. if (arg == NULL)
  7861. hasEmpty = true;
  7862. }
  7863. if (hasEmpty)
  7864. {
  7865. for (int genericIdx = 0; genericIdx < (int)methodGenericArgs->size(); genericIdx++)
  7866. {
  7867. auto arg = (*methodGenericArgs)[genericIdx];
  7868. if (arg != NULL)
  7869. newMethodGenericArgs.push_back(arg);
  7870. else
  7871. {
  7872. auto genericParamInst = methodInst->mMethodInfoEx->mGenericParams[genericIdx];
  7873. if (genericParamInst->mTypeConstraint != NULL)
  7874. newMethodGenericArgs.push_back(genericParamInst->mTypeConstraint);
  7875. else
  7876. newMethodGenericArgs.push_back(mContext->mBfObjectType); // Default
  7877. }
  7878. }
  7879. methodGenericArgs = &newMethodGenericArgs;
  7880. }
  7881. if (type->IsUnspecializedType())
  7882. type = ResolveGenericType(type, *methodGenericArgs);
  7883. }
  7884. methodName += TypeToString(type, typeNameFlags);
  7885. }
  7886. methodName += ">";
  7887. }
  7888. if (accessorString.length() == 0)
  7889. {
  7890. int dispParamIdx = 0;
  7891. methodName += "(";
  7892. for (int paramIdx = 0; paramIdx < (int) methodInst->GetParamCount(); paramIdx++)
  7893. {
  7894. int paramKind = methodInst->GetParamKind(paramIdx);
  7895. if (paramKind == BfParamKind_ImplicitCapture)
  7896. continue;
  7897. if (dispParamIdx > 0)
  7898. methodName += ", ";
  7899. if (paramKind == BfParamKind_Params)
  7900. methodName += "params ";
  7901. typeNameFlags = BfTypeNameFlag_ResolveGenericParamNames;
  7902. BfType* type = methodInst->GetParamType(paramIdx);
  7903. if ((methodGenericArgs != NULL) && (type->IsUnspecializedType()))
  7904. type = ResolveGenericType(type, *methodGenericArgs);
  7905. methodName += TypeToString(type, typeNameFlags);
  7906. methodName += " ";
  7907. methodName += methodInst->GetParamName(paramIdx);
  7908. dispParamIdx++;
  7909. }
  7910. methodName += ")";
  7911. }
  7912. if (accessorString.length() != 0)
  7913. {
  7914. methodName += " " + accessorString;
  7915. }
  7916. return methodName;
  7917. }
  7918. static void AddAttributeTargetName(BfAttributeTargets& flagsLeft, BfAttributeTargets checkFlag, String& str, String addString)
  7919. {
  7920. if ((flagsLeft & checkFlag) == 0)
  7921. return;
  7922. if (!str.empty())
  7923. {
  7924. if (flagsLeft == checkFlag)
  7925. {
  7926. if ((int)str.IndexOf(',') != -1)
  7927. str += ", and ";
  7928. else
  7929. str += " and ";
  7930. }
  7931. else
  7932. str += ", ";
  7933. }
  7934. str += addString;
  7935. flagsLeft = (BfAttributeTargets)(flagsLeft & ~checkFlag);
  7936. }
  7937. static String GetAttributesTargetListString(BfAttributeTargets attrTarget)
  7938. {
  7939. String resultStr;
  7940. auto flagsLeft = attrTarget;
  7941. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Assembly, resultStr, "assembly declarations");
  7942. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Module, resultStr, "module declarations");
  7943. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Class, resultStr, "class declarations");
  7944. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Struct, resultStr, "struct declarations");
  7945. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Enum, resultStr, "enum declarations");
  7946. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Constructor, resultStr, "constructor declarations");
  7947. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Method, resultStr, "method declarations");
  7948. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Property, resultStr, "property declarations");
  7949. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Field, resultStr, "field declarations");
  7950. AddAttributeTargetName(flagsLeft, BfAttributeTargets_StaticField, resultStr, "static field declarations");
  7951. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Interface, resultStr, "interface declarations");
  7952. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Parameter, resultStr, "parameter declarations");
  7953. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Delegate, resultStr, "delegate declarations");
  7954. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Function, resultStr, "function declarations");
  7955. AddAttributeTargetName(flagsLeft, BfAttributeTargets_ReturnValue, resultStr, "return value");
  7956. AddAttributeTargetName(flagsLeft, BfAttributeTargets_GenericParameter, resultStr, "generic parameters");
  7957. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Invocation, resultStr, "invocations");
  7958. AddAttributeTargetName(flagsLeft, BfAttributeTargets_MemberAccess, resultStr, "member access");
  7959. if (resultStr.IsEmpty())
  7960. return "<nothing>";
  7961. return resultStr;
  7962. }
  7963. void BfModule::CurrentAddToConstHolder(BfIRValue& irVal)
  7964. {
  7965. auto constant = mBfIRBuilder->GetConstant(irVal);
  7966. int stringPoolIdx = GetStringPoolIdx(irVal, mBfIRBuilder);
  7967. if (stringPoolIdx != -1)
  7968. {
  7969. irVal = mCurTypeInstance->GetOrCreateConstHolder()->CreateConst(BfTypeCode_Int32, stringPoolIdx);
  7970. return;
  7971. }
  7972. if (constant->mConstType == BfConstType_Array)
  7973. {
  7974. auto constArray = (BfConstantArray*)constant;
  7975. SizedArray<BfIRValue, 8> newVals;
  7976. for (auto val : constArray->mValues)
  7977. {
  7978. auto newVal = val;
  7979. CurrentAddToConstHolder(newVal);
  7980. newVals.push_back(newVal);
  7981. }
  7982. irVal = mCurTypeInstance->mConstHolder->CreateConstArray(constArray->mType, newVals);
  7983. return;
  7984. }
  7985. auto origConst = irVal;
  7986. if ((constant->mConstType == BfConstType_BitCast) || (constant->mConstType == BfConstType_BitCastNull))
  7987. {
  7988. auto bitcast = (BfConstantBitCast*)constant;
  7989. constant = mBfIRBuilder->GetConstantById(bitcast->mTarget);
  7990. }
  7991. irVal = mCurTypeInstance->CreateConst(constant, mBfIRBuilder);
  7992. }
  7993. void BfModule::ClearConstData()
  7994. {
  7995. mBfIRBuilder->ClearConstData();
  7996. mStringObjectPool.Clear();
  7997. mStringCharPtrPool.Clear();
  7998. mStringPoolRefs.Clear();
  7999. }
  8000. BfTypedValue BfModule::GetTypedValueFromConstant(BfConstant* constant, BfIRConstHolder* constHolder, BfType* wantType)
  8001. {
  8002. bool isString = false;
  8003. isString = (wantType->IsObject()) && (wantType->ToTypeInstance()->mTypeDef == mCompiler->mStringTypeDef);
  8004. if (wantType->IsPointer())
  8005. isString = true;
  8006. if (!isString)
  8007. {
  8008. switch (constant->mTypeCode)
  8009. {
  8010. case BfTypeCode_Boolean:
  8011. case BfTypeCode_Int8:
  8012. case BfTypeCode_UInt8:
  8013. case BfTypeCode_Int16:
  8014. case BfTypeCode_UInt16:
  8015. case BfTypeCode_Int32:
  8016. case BfTypeCode_UInt32:
  8017. case BfTypeCode_Int64:
  8018. case BfTypeCode_UInt64:
  8019. case BfTypeCode_IntPtr:
  8020. case BfTypeCode_UIntPtr:
  8021. case BfTypeCode_IntUnknown:
  8022. case BfTypeCode_UIntUnknown:
  8023. case BfTypeCode_Char8:
  8024. case BfTypeCode_Char16:
  8025. case BfTypeCode_Char32:
  8026. case BfTypeCode_Single:
  8027. case BfTypeCode_Double:
  8028. {
  8029. auto constVal = mBfIRBuilder->CreateConst(constant, constHolder);
  8030. auto typedValue = BfTypedValue(constVal, GetPrimitiveType(constant->mTypeCode));
  8031. if (typedValue.mType == wantType)
  8032. return typedValue;
  8033. if (wantType->IsTypedPrimitive())
  8034. {
  8035. if (typedValue.mType == wantType->GetUnderlyingType())
  8036. {
  8037. typedValue.mType = wantType;
  8038. return typedValue;
  8039. }
  8040. }
  8041. auto castedTypedValue = Cast(NULL, typedValue, wantType, (BfCastFlags)(BfCastFlags_SilentFail | BfCastFlags_Explicit));
  8042. BF_ASSERT(castedTypedValue);
  8043. return castedTypedValue;
  8044. }
  8045. break;
  8046. default: break;
  8047. }
  8048. }
  8049. BfIRValue irValue = ConstantToCurrent(constant, constHolder, wantType);
  8050. BF_ASSERT(irValue);
  8051. if (!irValue)
  8052. return BfTypedValue();
  8053. return BfTypedValue(irValue, wantType, false);
  8054. }
  8055. BfIRValue BfModule::ConstantToCurrent(BfConstant* constant, BfIRConstHolder* constHolder, BfType* wantType)
  8056. {
  8057. if (constant->mTypeCode == BfTypeCode_NullPtr)
  8058. {
  8059. return GetDefaultValue(wantType);
  8060. }
  8061. bool isString = false;
  8062. isString = (wantType->IsObject()) && (wantType->ToTypeInstance()->mTypeDef == mCompiler->mStringTypeDef);
  8063. if (((wantType->IsPointer()) || (isString)) && (mBfIRBuilder->IsInt(constant->mTypeCode)))
  8064. {
  8065. const StringImpl& str = mContext->mStringObjectIdMap[constant->mInt32].mString;
  8066. BfIRValue stringObjConst = GetStringObjectValue(str);
  8067. if (wantType->IsObject())
  8068. return stringObjConst;
  8069. return GetStringCharPtr(stringObjConst);
  8070. }
  8071. if (constant->mConstType == BfConstType_Array)
  8072. {
  8073. auto elementType = wantType->GetUnderlyingType();
  8074. auto constArray = (BfConstantArray*)constant;
  8075. SizedArray<BfIRValue, 8> newVals;
  8076. for (auto val : constArray->mValues)
  8077. {
  8078. newVals.push_back(ConstantToCurrent(constHolder->GetConstant(val), constHolder, elementType));
  8079. }
  8080. return mBfIRBuilder->CreateConstArray(mBfIRBuilder->MapType(wantType), newVals);
  8081. }
  8082. return mBfIRBuilder->CreateConst(constant, constHolder);
  8083. }
  8084. void BfModule::ValidateCustomAttributes(BfCustomAttributes* customAttributes, BfAttributeTargets attrTarget)
  8085. {
  8086. if (attrTarget == BfAttributeTargets_SkipValidate)
  8087. return;
  8088. for (auto& customAttribute : customAttributes->mAttributes)
  8089. {
  8090. if (!customAttribute.mAwaitingValidation)
  8091. continue;
  8092. if ((customAttribute.mType->mAttributeData->mAttributeTargets & attrTarget) == 0)
  8093. {
  8094. Fail(StrFormat("Attribute '%s' is not valid on this declaration type. It is only valid on %s.",
  8095. customAttribute.mRef->ToString().c_str(), GetAttributesTargetListString(customAttribute.mType->mAttributeData->mAttributeTargets).c_str()), customAttribute.mRef->mAttributeTypeRef); // CS0592
  8096. }
  8097. customAttribute.mAwaitingValidation = false;
  8098. }
  8099. }
  8100. void BfModule::GetCustomAttributes(BfCustomAttributes* customAttributes, BfAttributeDirective* attributesDirective, BfAttributeTargets attrTarget)
  8101. {
  8102. if ((attributesDirective != NULL) && (mCompiler->mResolvePassData != NULL) &&
  8103. (attributesDirective->IsFromParser(mCompiler->mResolvePassData->mParser)) && (mCompiler->mResolvePassData->mSourceClassifier != NULL))
  8104. {
  8105. mCompiler->mResolvePassData->mSourceClassifier->VisitChild(attributesDirective);
  8106. }
  8107. SetAndRestoreValue<bool> prevIsCapturingMethodMatchInfo;
  8108. if (mCompiler->IsAutocomplete())
  8109. prevIsCapturingMethodMatchInfo.Init(mCompiler->mResolvePassData->mAutoComplete->mIsCapturingMethodMatchInfo, false);
  8110. BfTypeInstance* baseAttrTypeInst = mContext->mUnreifiedModule->ResolveTypeDef(mCompiler->mAttributeTypeDef)->ToTypeInstance();
  8111. BfAttributeTargets targetOverride = (BfAttributeTargets)0;
  8112. BfAutoComplete* autoComplete = NULL;
  8113. if (mCompiler->mResolvePassData != NULL)
  8114. autoComplete = mCompiler->mResolvePassData->mAutoComplete;
  8115. for (; attributesDirective != NULL; attributesDirective = attributesDirective->mNextAttribute)
  8116. {
  8117. BfAutoParentNodeEntry autoParentNodeEntry(this, attributesDirective);
  8118. BfCustomAttribute customAttribute;
  8119. customAttribute.mAwaitingValidation = true;
  8120. customAttribute.mRef = attributesDirective;
  8121. if (attributesDirective->mAttrOpenToken != NULL)
  8122. targetOverride = (BfAttributeTargets)0;
  8123. if (attributesDirective->mAttributeTypeRef == NULL)
  8124. {
  8125. AssertErrorState();
  8126. continue;
  8127. }
  8128. String attrName = attributesDirective->mAttributeTypeRef->ToString();
  8129. BfType* attrType = NULL;
  8130. BfAtomComposite nameComposite;
  8131. BfTypeDef* attrTypeDef = NULL;
  8132. if (mSystem->ParseAtomComposite(attrName + "Attribute", nameComposite))
  8133. {
  8134. BfTypeLookupError error;
  8135. error.mRefNode = attributesDirective->mAttributeTypeRef;
  8136. attrTypeDef = FindTypeDefRaw(nameComposite, 0, mCurTypeInstance, GetActiveTypeDef(NULL, true), &error);
  8137. }
  8138. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL))
  8139. {
  8140. mCompiler->mResolvePassData->mAutoComplete->CheckAttributeTypeRef(attributesDirective->mAttributeTypeRef);
  8141. if (attrTypeDef != NULL)
  8142. mCompiler->mResolvePassData->HandleTypeReference(attributesDirective->mAttributeTypeRef, attrTypeDef);
  8143. }
  8144. if (attrTypeDef == NULL)
  8145. {
  8146. TypeRefNotFound(attributesDirective->mAttributeTypeRef, "Attribute");
  8147. continue;
  8148. }
  8149. bool isBypassedAttr = false;
  8150. if (attrTypeDef != NULL)
  8151. {
  8152. attrType = mContext->mUnreifiedModule->ResolveTypeDef(attrTypeDef, BfPopulateType_Identity);
  8153. // 'Object' has some dependencies on some attributes, but those attributes are classes so we have a circular dependency issue
  8154. // We solve it by having a 'bypass' for known attributes that Object depends on
  8155. if ((attributesDirective->mArguments.empty()) && (autoComplete == NULL) && (attrType != NULL) && (attrType->IsTypeInstance()))
  8156. {
  8157. if (attrTypeDef == mCompiler->mCReprAttributeTypeDef)
  8158. {
  8159. BfTypeInstance* attrTypeInst = attrType->ToTypeInstance();
  8160. for (auto methodDef : attrTypeDef->mMethods)
  8161. {
  8162. if ((methodDef->mMethodType == BfMethodType_Ctor) && (methodDef->mProtection == BfProtection_Public))
  8163. {
  8164. customAttribute.mType = attrType->ToTypeInstance();
  8165. customAttribute.mCtor = methodDef;
  8166. isBypassedAttr = true;
  8167. break;
  8168. }
  8169. }
  8170. }
  8171. }
  8172. if (isBypassedAttr)
  8173. {
  8174. customAttribute.mAwaitingValidation = false;
  8175. customAttributes->mAttributes.push_back(customAttribute);
  8176. continue;
  8177. }
  8178. if (mContext->mCurTypeState != NULL)
  8179. {
  8180. SetAndRestoreValue<BfTypeReference*> prevTypeRef(mContext->mCurTypeState->mCurAttributeTypeRef, attributesDirective->mAttributeTypeRef);
  8181. mContext->mUnreifiedModule->ResolveTypeResult(attributesDirective->mAttributeTypeRef, attrType, BfPopulateType_BaseType, (BfResolveTypeRefFlags)0);
  8182. }
  8183. else
  8184. {
  8185. mContext->mUnreifiedModule->ResolveTypeResult(attributesDirective->mAttributeTypeRef, attrType, BfPopulateType_BaseType, (BfResolveTypeRefFlags)0);
  8186. }
  8187. }
  8188. // Don't allow this
  8189. /*else if (mContext->mCurTypeState != NULL)
  8190. {
  8191. SetAndRestoreValue<BfTypeReference*> prevTypeRef(mContext->mCurTypeState->mCurAttributeTypeRef, attributesDirective->mAttributeTypeRef);
  8192. attrType = mContext->mUnreifiedModule->ResolveTypeRef(attributesDirective->mAttributeTypeRef, BfPopulateType_DataAndMethods);
  8193. }
  8194. else
  8195. {
  8196. attrType = mContext->mUnreifiedModule->ResolveTypeRef(attributesDirective->mAttributeTypeRef);
  8197. }*/
  8198. BfTypeInstance* attrTypeInst = NULL;
  8199. if (attrType == NULL)
  8200. continue;
  8201. mContext->mUnreifiedModule->PopulateType(attrType, BfPopulateType_DataAndMethods);
  8202. attrTypeInst = attrType->ToTypeInstance();
  8203. if ((attrTypeInst == NULL) || (!TypeIsSubTypeOf(attrTypeInst, baseAttrTypeInst)) || (attrTypeInst->mAttributeData == NULL))
  8204. {
  8205. Fail(StrFormat("'%s' is not an attribute class", TypeToString(attrType).c_str()), attributesDirective->mAttributeTypeRef); //CS0616
  8206. continue;
  8207. }
  8208. if (mCurTypeInstance != NULL)
  8209. AddDependency(attrTypeInst, mCurTypeInstance, BfDependencyMap::DependencyFlag_CustomAttribute);
  8210. customAttribute.mType = attrTypeInst;
  8211. BfConstResolver constResolver(this);
  8212. bool inPropSet = false;
  8213. SizedArray<BfResolvedArg, 2> argValues;
  8214. for (BfExpression* arg : attributesDirective->mArguments)
  8215. {
  8216. if (arg == NULL)
  8217. {
  8218. continue;
  8219. }
  8220. if (autoComplete != NULL)
  8221. autoComplete->mShowAttributeProperties = attrTypeInst;
  8222. if (auto assignExpr = BfNodeDynCast<BfAssignmentExpression>(arg))
  8223. {
  8224. inPropSet = true;
  8225. if (autoComplete != NULL)
  8226. autoComplete->CheckNode(assignExpr->mLeft);
  8227. String findName = assignExpr->mLeft->ToString();
  8228. BfPropertyDef* bestProp = NULL;
  8229. BfTypeInstance* bestPropTypeInst = NULL;
  8230. BfFieldDef* bestField = NULL;
  8231. BfTypeInstance* bestFieldTypeInst = NULL;
  8232. auto checkTypeInst = attrTypeInst;
  8233. while (checkTypeInst != NULL)
  8234. {
  8235. mContext->mUnreifiedModule->PopulateType(checkTypeInst, BfPopulateType_Data);
  8236. for (auto prop : checkTypeInst->mTypeDef->mProperties)
  8237. {
  8238. if (prop->mName == findName)
  8239. {
  8240. if ((bestProp == NULL) || (bestProp->mProtection != BfProtection_Public))
  8241. {
  8242. bestProp = prop;
  8243. bestPropTypeInst = checkTypeInst;
  8244. }
  8245. }
  8246. }
  8247. for (auto field : checkTypeInst->mTypeDef->mFields)
  8248. {
  8249. if (field->mName == findName)
  8250. {
  8251. if ((bestField == NULL) || (bestField->mProtection != BfProtection_Public))
  8252. {
  8253. bestField = field;
  8254. bestFieldTypeInst = checkTypeInst;
  8255. }
  8256. }
  8257. }
  8258. if ((bestProp != NULL) || (bestField != NULL))
  8259. break;
  8260. checkTypeInst = checkTypeInst->mBaseType;
  8261. }
  8262. bool handledExpr = false;
  8263. if (bestField != NULL)
  8264. {
  8265. handledExpr = true;
  8266. if (mCompiler->mResolvePassData != NULL)
  8267. {
  8268. mCompiler->mResolvePassData->HandleFieldReference(assignExpr->mLeft, attrTypeDef, bestField);
  8269. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(assignExpr->mLeft)))
  8270. {
  8271. autoComplete->mDefField = bestField;
  8272. autoComplete->mDefType = attrTypeDef;
  8273. }
  8274. }
  8275. if (bestField->mProtection != BfProtection_Public)
  8276. Fail(StrFormat("'%s.%s' is inaccessible due to its protection level", TypeToString(bestFieldTypeInst).c_str(), findName.c_str()), assignExpr->mLeft); // CS0122
  8277. AddDependency(bestFieldTypeInst, mCurTypeInstance, BfDependencyMap::DependencyFlag_CustomAttribute);
  8278. BfCustomAttributeSetField setField;
  8279. setField.mFieldRef = BfFieldRef(bestFieldTypeInst, bestField);
  8280. auto& fieldTypeInst = checkTypeInst->mFieldInstances[bestField->mIdx];
  8281. if (assignExpr->mRight != NULL)
  8282. {
  8283. BfTypedValue result = constResolver.Resolve(assignExpr->mRight, fieldTypeInst.mResolvedType);
  8284. if (result)
  8285. {
  8286. CurrentAddToConstHolder(result.mValue);
  8287. setField.mParam = result;
  8288. customAttribute.mSetField.push_back(setField);
  8289. }
  8290. }
  8291. }
  8292. else if (bestProp == NULL)
  8293. {
  8294. Fail(StrFormat("'%s' does not contain a field or property named '%s'", TypeToString(attrTypeInst).c_str(), findName.c_str()), assignExpr->mLeft);
  8295. }
  8296. else
  8297. {
  8298. BfMethodDef* setMethod = NULL;
  8299. for (auto methodDef : bestProp->mMethods)
  8300. {
  8301. if (methodDef->mMethodType == BfMethodType_PropertySetter)
  8302. {
  8303. setMethod = methodDef;
  8304. break;
  8305. }
  8306. }
  8307. if (setMethod == NULL)
  8308. {
  8309. Fail("Property has no setter", assignExpr->mLeft);
  8310. }
  8311. else
  8312. {
  8313. if (mCompiler->mResolvePassData != NULL)
  8314. {
  8315. mCompiler->mResolvePassData->HandlePropertyReference(assignExpr->mLeft, attrTypeDef, bestProp);
  8316. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(assignExpr->mLeft)))
  8317. {
  8318. autoComplete->mDefProp = bestProp;
  8319. autoComplete->mDefType = attrTypeDef;
  8320. }
  8321. }
  8322. handledExpr = true;
  8323. if (bestProp->mProtection != BfProtection_Public)
  8324. Fail(StrFormat("'%s.%s' is inaccessible due to its protection level", TypeToString(bestPropTypeInst).c_str(), findName.c_str()), assignExpr->mLeft); // CS0122
  8325. BfResolvedArg resolvedArg;
  8326. AddDependency(bestPropTypeInst, mCurTypeInstance, BfDependencyMap::DependencyFlag_CustomAttribute);
  8327. BfCustomAttributeSetProperty setProperty;
  8328. setProperty.mPropertyRef = BfPropertyRef(bestPropTypeInst, bestProp);
  8329. // We don't actually need the mFunc, so get the ModuleMethodInstance from the native module
  8330. auto methodInstance = bestPropTypeInst->mModule->GetMethodInstance(bestPropTypeInst, setMethod, BfTypeVector());
  8331. if (methodInstance.mMethodInstance != NULL)
  8332. {
  8333. auto propType = methodInstance.mMethodInstance->GetParamType(0);
  8334. if (assignExpr->mRight != NULL)
  8335. {
  8336. BfTypedValue result = constResolver.Resolve(assignExpr->mRight, propType);
  8337. if (result)
  8338. {
  8339. BF_ASSERT(result.mType == propType);
  8340. CurrentAddToConstHolder(result.mValue);
  8341. setProperty.mParam = result;
  8342. customAttribute.mSetProperties.push_back(setProperty);
  8343. }
  8344. }
  8345. }
  8346. }
  8347. }
  8348. if ((!handledExpr) && (assignExpr->mRight != NULL))
  8349. constResolver.Resolve(assignExpr->mRight);
  8350. }
  8351. else
  8352. {
  8353. if (inPropSet)
  8354. {
  8355. Fail("Named attribute argument expected", arg); // CS1016
  8356. }
  8357. BfDeferEvalChecker deferEvalChecker;
  8358. arg->Accept(&deferEvalChecker);
  8359. bool deferParamEval = deferEvalChecker.mNeedsDeferEval;
  8360. BfResolvedArg resolvedArg;
  8361. resolvedArg.mExpression = arg;
  8362. if (deferParamEval)
  8363. {
  8364. resolvedArg.mArgFlags = BfArgFlag_DeferredEval;
  8365. }
  8366. else
  8367. resolvedArg.mTypedValue = constResolver.Resolve(arg);
  8368. if (!inPropSet)
  8369. argValues.push_back(resolvedArg);
  8370. }
  8371. if (autoComplete != NULL)
  8372. autoComplete->mShowAttributeProperties = NULL;
  8373. }
  8374. auto wasCapturingMethodInfo = false;
  8375. if (autoComplete != NULL)
  8376. {
  8377. wasCapturingMethodInfo = autoComplete->mIsCapturingMethodMatchInfo;
  8378. if (attributesDirective->mCtorOpenParen != NULL)
  8379. autoComplete->CheckInvocation(attributesDirective, attributesDirective->mCtorOpenParen, attributesDirective->mCtorCloseParen, attributesDirective->mCommas);
  8380. }
  8381. BfMethodMatcher methodMatcher(attributesDirective, this, "", argValues, NULL);
  8382. attrTypeDef = attrTypeInst->mTypeDef;
  8383. bool success = true;
  8384. bool isFailurePass = false;
  8385. for (int pass = 0; pass < 2; pass++)
  8386. {
  8387. bool isFailurePass = pass == 1;
  8388. for (auto checkMethod : attrTypeDef->mMethods)
  8389. {
  8390. if ((isFailurePass) && (checkMethod->mMethodDeclaration == NULL))
  8391. continue; // Don't match private default ctor if there's a user-defined one
  8392. if ((checkMethod->mIsStatic) || (checkMethod->mMethodType != BfMethodType_Ctor))
  8393. continue;
  8394. if ((!isFailurePass) && (!CheckProtection(checkMethod->mProtection, false, false)))
  8395. continue;
  8396. methodMatcher.CheckMethod(attrTypeInst, checkMethod, isFailurePass);
  8397. }
  8398. if ((methodMatcher.mBestMethodDef != NULL) || (methodMatcher.mBackupMethodDef != NULL))
  8399. break;
  8400. }
  8401. if (autoComplete != NULL)
  8402. {
  8403. if ((wasCapturingMethodInfo) && (!autoComplete->mIsCapturingMethodMatchInfo))
  8404. {
  8405. autoComplete->mIsCapturingMethodMatchInfo = true;
  8406. BF_ASSERT(autoComplete->mMethodMatchInfo != NULL);
  8407. }
  8408. else
  8409. autoComplete->mIsCapturingMethodMatchInfo = false;
  8410. }
  8411. if (methodMatcher.mBestMethodDef == NULL)
  8412. methodMatcher.mBestMethodDef = methodMatcher.mBackupMethodDef;
  8413. BF_ASSERT(methodMatcher.mBestMethodDef != NULL);
  8414. customAttribute.mCtor = methodMatcher.mBestMethodDef;
  8415. if (methodMatcher.mBestMethodTypeInstance == mCurTypeInstance)
  8416. {
  8417. Fail("Custom attribute circular reference", attributesDirective);
  8418. }
  8419. if (mCurTypeInstance != NULL)
  8420. AddDependency(methodMatcher.mBestMethodTypeInstance, mCurTypeInstance, BfDependencyMap::DependencyFlag_CustomAttribute);
  8421. if (!constResolver.PrepareMethodArguments(attributesDirective->mAttributeTypeRef, &methodMatcher, customAttribute.mCtorArgs))
  8422. success = false;
  8423. for (auto& arg : argValues)
  8424. {
  8425. if ((arg.mArgFlags & BfArgFlag_DeferredEval) != 0)
  8426. {
  8427. if (auto expr = BfNodeDynCast<BfExpression>(arg.mExpression))
  8428. constResolver.Resolve(expr);
  8429. }
  8430. }
  8431. // Move all those to the constHolder
  8432. for (auto& ctorArg : customAttribute.mCtorArgs)
  8433. {
  8434. CurrentAddToConstHolder(ctorArg);
  8435. }
  8436. if (attributesDirective->mAttributeTargetSpecifier != NULL)
  8437. {
  8438. targetOverride = BfAttributeTargets_ReturnValue;
  8439. if (attrTarget != BfAttributeTargets_Method)
  8440. {
  8441. 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.",
  8442. GetAttributesTargetListString(targetOverride).c_str(), GetAttributesTargetListString(attrTarget).c_str()), attributesDirective->mAttributeTargetSpecifier); // CS0657
  8443. }
  8444. success = false;
  8445. }
  8446. if ((success) && (targetOverride != (BfAttributeTargets)0))
  8447. {
  8448. if ((targetOverride == BfAttributeTargets_ReturnValue) && (attrTarget == BfAttributeTargets_Method))
  8449. {
  8450. auto methodInfoEx = mCurMethodInstance->GetMethodInfoEx();
  8451. if (methodInfoEx->mMethodCustomAttributes == NULL)
  8452. methodInfoEx->mMethodCustomAttributes = new BfMethodCustomAttributes();
  8453. if (success)
  8454. {
  8455. if (methodInfoEx->mMethodCustomAttributes->mReturnCustomAttributes == NULL)
  8456. methodInfoEx->mMethodCustomAttributes->mReturnCustomAttributes = new BfCustomAttributes();
  8457. methodInfoEx->mMethodCustomAttributes->mReturnCustomAttributes->mAttributes.push_back(customAttribute);
  8458. }
  8459. }
  8460. else
  8461. {
  8462. // Failed - ignore
  8463. success = false;
  8464. }
  8465. }
  8466. if (success)
  8467. {
  8468. if (!attrTypeInst->mAttributeData->mAllowMultiple)
  8469. {
  8470. for (auto& prevCustomAttribute : customAttributes->mAttributes)
  8471. {
  8472. if (prevCustomAttribute.mType == attrTypeInst)
  8473. {
  8474. Fail(StrFormat("Duplicate '%s' attribute", attributesDirective->mAttributeTypeRef->ToString().c_str()), attributesDirective->mAttributeTypeRef); // CS0579
  8475. }
  8476. }
  8477. }
  8478. }
  8479. if (success)
  8480. {
  8481. customAttributes->mAttributes.push_back(customAttribute);
  8482. }
  8483. }
  8484. ValidateCustomAttributes(customAttributes, attrTarget);
  8485. }
  8486. BfCustomAttributes* BfModule::GetCustomAttributes(BfAttributeDirective* attributesDirective, BfAttributeTargets attrType)
  8487. {
  8488. BfCustomAttributes* customAttributes = new BfCustomAttributes();
  8489. GetCustomAttributes(customAttributes, attributesDirective, attrType);
  8490. return customAttributes;
  8491. }
  8492. void BfModule::ProcessTypeInstCustomAttributes(bool& isPacked, bool& isUnion, bool& isCRepr, bool& isOrdered)
  8493. {
  8494. if (mCurTypeInstance->mCustomAttributes != NULL)
  8495. {
  8496. for (auto& customAttribute : mCurTypeInstance->mCustomAttributes->mAttributes)
  8497. {
  8498. String typeName = TypeToString(customAttribute.mType);
  8499. if (typeName == "System.PackedAttribute")
  8500. {
  8501. isPacked = true;
  8502. }
  8503. else if (typeName == "System.UnionAttribute")
  8504. {
  8505. isUnion = true;
  8506. }
  8507. else if (typeName == "System.CReprAttribute")
  8508. {
  8509. isCRepr = true;
  8510. isOrdered = true;
  8511. }
  8512. else if (typeName == "System.OrderedAttribute")
  8513. {
  8514. isOrdered = true;
  8515. }
  8516. else if (typeName == "System.AlwaysIncludeAttribute")
  8517. {
  8518. for (auto setProp : customAttribute.mSetProperties)
  8519. {
  8520. BfPropertyDef* propertyDef = setProp.mPropertyRef;
  8521. if (propertyDef->mName == "AssumeInstantiated")
  8522. {
  8523. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  8524. if ((constant != NULL) && (constant->mBool))
  8525. mCurTypeInstance->mHasBeenInstantiated = true;
  8526. }
  8527. }
  8528. }
  8529. }
  8530. }
  8531. }
  8532. // Checking to see if we're an attribute or not
  8533. void BfModule::ProcessCustomAttributeData()
  8534. {
  8535. bool isAttribute = false;
  8536. auto checkTypeInst = mCurTypeInstance->mBaseType;
  8537. while (checkTypeInst != NULL)
  8538. {
  8539. if (checkTypeInst->mTypeDef == mCompiler->mAttributeTypeDef)
  8540. isAttribute = true;
  8541. checkTypeInst = checkTypeInst->mBaseType;
  8542. }
  8543. if (!isAttribute)
  8544. return;
  8545. auto attributeData = new BfAttributeData();
  8546. bool hasCustomAttribute = false;
  8547. if (mCurTypeInstance->mCustomAttributes != NULL)
  8548. {
  8549. for (auto& customAttribute : mCurTypeInstance->mCustomAttributes->mAttributes)
  8550. {
  8551. if (customAttribute.mType->mTypeDef == mCompiler->mAttributeUsageAttributeTypeDef)
  8552. {
  8553. if (customAttribute.mCtorArgs.size() > 0)
  8554. {
  8555. auto constant = mCurTypeInstance->mConstHolder->GetConstant(customAttribute.mCtorArgs[0]);
  8556. if ((constant != NULL) && (mBfIRBuilder->IsInt(constant->mTypeCode)))
  8557. attributeData->mAttributeTargets = (BfAttributeTargets)constant->mInt32;
  8558. }
  8559. for (auto& setProp : customAttribute.mSetProperties)
  8560. {
  8561. BfPropertyDef* propDef = setProp.mPropertyRef;
  8562. if (propDef->mName == "AllowMultiple")
  8563. {
  8564. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  8565. if (constant != NULL)
  8566. attributeData->mAllowMultiple = constant->mBool;
  8567. }
  8568. else if (propDef->mName == "Inherited")
  8569. {
  8570. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  8571. if (constant != NULL)
  8572. attributeData->mInherited = constant->mBool;
  8573. }
  8574. else if (propDef->mName == "ValidOn")
  8575. {
  8576. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  8577. if (constant != NULL)
  8578. attributeData->mAttributeTargets = (BfAttributeTargets)constant->mInt32;
  8579. }
  8580. }
  8581. hasCustomAttribute = true;
  8582. }
  8583. }
  8584. }
  8585. if ((!hasCustomAttribute) && (mCurTypeInstance->mBaseType->mAttributeData != NULL))
  8586. {
  8587. attributeData->mAttributeTargets = mCurTypeInstance->mBaseType->mAttributeData->mAttributeTargets;
  8588. attributeData->mInherited = mCurTypeInstance->mBaseType->mAttributeData->mInherited;
  8589. attributeData->mAllowMultiple = mCurTypeInstance->mBaseType->mAttributeData->mAllowMultiple;
  8590. }
  8591. mCurTypeInstance->mAttributeData = attributeData;
  8592. }
  8593. bool BfModule::TryGetConstString(BfIRConstHolder* constHolder, BfIRValue irValue, StringImpl& str)
  8594. {
  8595. auto constant = constHolder->GetConstant(irValue);
  8596. if (constant == NULL)
  8597. return false;
  8598. if (!BfIRConstHolder::IsInt(constant->mTypeCode))
  8599. return false;
  8600. int stringId = constant->mInt32;
  8601. BfStringPoolEntry* entry = NULL;
  8602. if (mContext->mStringObjectIdMap.TryGetValue(stringId, &entry))
  8603. {
  8604. str = entry->mString;
  8605. }
  8606. else
  8607. {
  8608. BF_DBG_FATAL("Failed to find string by id");
  8609. }
  8610. return true;
  8611. }
  8612. BfVariant BfModule::TypedValueToVariant(BfAstNode* refNode, const BfTypedValue& value, bool allowUndef)
  8613. {
  8614. BfVariant variant;
  8615. variant.mTypeCode = BfTypeCode_None;
  8616. BfType* primType = NULL;
  8617. if (value.mType->IsPrimitiveType())
  8618. primType = (BfPrimitiveType*)value.mType;
  8619. else if (value.mType->IsTypedPrimitive())
  8620. primType = value.mType->GetUnderlyingType();
  8621. if (primType)
  8622. {
  8623. auto constant = mBfIRBuilder->GetConstant(value.mValue);
  8624. if (constant != NULL)
  8625. {
  8626. if ((allowUndef) && (constant->mConstType == BfConstType_Undef))
  8627. {
  8628. variant.mTypeCode = BfTypeCode_Let;
  8629. return variant;
  8630. }
  8631. switch (constant->mTypeCode)
  8632. {
  8633. case BfTypeCode_Int8:
  8634. case BfTypeCode_UInt8:
  8635. case BfTypeCode_Int16:
  8636. case BfTypeCode_UInt16:
  8637. case BfTypeCode_Int32:
  8638. case BfTypeCode_UInt32:
  8639. case BfTypeCode_Int64:
  8640. case BfTypeCode_UInt64:
  8641. case BfTypeCode_IntPtr:
  8642. case BfTypeCode_UIntPtr:
  8643. case BfTypeCode_IntUnknown:
  8644. case BfTypeCode_UIntUnknown:
  8645. case BfTypeCode_Single:
  8646. case BfTypeCode_Double:
  8647. case BfTypeCode_Char8:
  8648. case BfTypeCode_Char16:
  8649. case BfTypeCode_Char32:
  8650. variant.mTypeCode = constant->mTypeCode;
  8651. variant.mInt64 = constant->mInt64;
  8652. break;
  8653. default:
  8654. if (refNode != NULL)
  8655. Fail("Invalid const expression type", refNode);
  8656. break;
  8657. }
  8658. }
  8659. }
  8660. return variant;
  8661. }
  8662. BfTypedValue BfModule::RemoveRef(BfTypedValue typedValue)
  8663. {
  8664. if ((typedValue.mType != NULL) && (typedValue.mType->IsRef()))
  8665. {
  8666. auto elementType = typedValue.mType->GetUnderlyingType();
  8667. if (typedValue.IsAddr())
  8668. {
  8669. if (elementType->IsValuelessType())
  8670. {
  8671. BF_ASSERT(!typedValue.mValue);
  8672. typedValue = BfTypedValue(typedValue.mValue, elementType, true);
  8673. }
  8674. else
  8675. typedValue = BfTypedValue(mBfIRBuilder->CreateLoad(typedValue.mValue), elementType, true);
  8676. }
  8677. else
  8678. typedValue = BfTypedValue(typedValue.mValue, elementType, true);
  8679. if (typedValue.mType->IsValuelessType())
  8680. {
  8681. BF_ASSERT(typedValue.mValue.IsFake());
  8682. }
  8683. }
  8684. return typedValue;
  8685. }
  8686. BfTypedValue BfModule::LoadValue(BfTypedValue typedValue, BfAstNode* refNode, bool isVolatile)
  8687. {
  8688. if (!typedValue.IsAddr())
  8689. return typedValue;
  8690. if (typedValue.mType->IsValuelessType())
  8691. return BfTypedValue(mBfIRBuilder->GetFakeVal(), typedValue.mType, false);
  8692. BfIRValue loadedVal = typedValue.mValue;
  8693. if (loadedVal)
  8694. {
  8695. if (typedValue.mType->IsVar())
  8696. {
  8697. return BfTypedValue(loadedVal, typedValue.mType, false);
  8698. }
  8699. /*if (isVolatile)
  8700. mBfIRBuilder->CreateFence(BfIRFenceType_AcquireRelease);*/
  8701. PopulateType(typedValue.mType, BfPopulateType_Data);
  8702. loadedVal = mBfIRBuilder->CreateAlignedLoad(loadedVal, std::max(1, (int)typedValue.mType->mAlign), isVolatile);
  8703. }
  8704. return BfTypedValue(loadedVal, typedValue.mType, false);
  8705. }
  8706. BfTypedValue BfModule::LoadOrAggregateValue(BfTypedValue typedValue)
  8707. {
  8708. if (typedValue.IsSplat())
  8709. return AggregateSplat(typedValue);
  8710. if (typedValue.IsAddr())
  8711. return LoadValue(typedValue);
  8712. return typedValue;
  8713. }
  8714. BfTypedValue BfModule::AggregateSplat(BfTypedValue typedValue, BfIRValue* valueArrPtr)
  8715. {
  8716. if (!typedValue.IsSplat())
  8717. return typedValue;
  8718. if (typedValue.mType->IsValuelessType())
  8719. return typedValue;
  8720. int elementIdx = 0;
  8721. auto _ExtractValue = [&](BfType* checkType)
  8722. {
  8723. if (valueArrPtr != NULL)
  8724. return valueArrPtr[elementIdx++];
  8725. return ExtractSplatValue(typedValue, elementIdx++, checkType);
  8726. };
  8727. std::function<BfIRValue(BfType*)> checkTypeLambda = [&](BfType* checkType)
  8728. {
  8729. if (checkType->IsStruct())
  8730. {
  8731. BfIRValue curValue = mBfIRBuilder->CreateUndefValue(mBfIRBuilder->MapType(checkType, BfIRPopulateType_Full));
  8732. auto checkTypeInstance = checkType->ToTypeInstance();
  8733. if (checkTypeInstance->mBaseType != NULL)
  8734. {
  8735. mBfIRBuilder->PopulateType(checkTypeInstance->mBaseType, BfIRPopulateType_Full);
  8736. BfIRValue baseValue = checkTypeLambda(checkTypeInstance->mBaseType);
  8737. curValue = mBfIRBuilder->CreateInsertValue(curValue, baseValue, 0);
  8738. }
  8739. if (checkTypeInstance->mIsUnion)
  8740. {
  8741. auto unionInnerType = checkTypeInstance->GetUnionInnerType();
  8742. if (!unionInnerType->IsValuelessType())
  8743. {
  8744. BfIRValue fieldValue = checkTypeLambda(unionInnerType);
  8745. curValue = mBfIRBuilder->CreateInsertValue(curValue, fieldValue, 1);
  8746. }
  8747. if (checkTypeInstance->IsEnum())
  8748. {
  8749. auto dscrType = checkTypeInstance->GetDiscriminatorType();
  8750. BfIRValue fieldValue = checkTypeLambda(dscrType);
  8751. curValue = mBfIRBuilder->CreateInsertValue(curValue, fieldValue, 2);
  8752. }
  8753. }
  8754. else
  8755. {
  8756. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  8757. {
  8758. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  8759. if (fieldInstance->mDataIdx >= 0)
  8760. {
  8761. BfIRValue fieldValue = checkTypeLambda(fieldInstance->GetResolvedType());
  8762. curValue = mBfIRBuilder->CreateInsertValue(curValue, fieldValue, fieldInstance->mDataIdx);
  8763. }
  8764. }
  8765. }
  8766. return curValue;
  8767. }
  8768. else if (checkType->IsMethodRef())
  8769. {
  8770. BfMethodRefType* methodRefType = (BfMethodRefType*)checkType;
  8771. BfIRValue curValue = mBfIRBuilder->CreateUndefValue(mBfIRBuilder->MapType(checkType, BfIRPopulateType_Full));
  8772. for (int dataIdx = 0; dataIdx < methodRefType->GetCaptureDataCount(); dataIdx++)
  8773. {
  8774. BfIRValue fieldValue;
  8775. auto checkType = methodRefType->GetCaptureType(dataIdx);
  8776. if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  8777. {
  8778. fieldValue = checkTypeLambda(checkType);
  8779. }
  8780. else
  8781. {
  8782. fieldValue = _ExtractValue(checkType);
  8783. }
  8784. curValue = mBfIRBuilder->CreateInsertValue(curValue, fieldValue, dataIdx);
  8785. }
  8786. return curValue;
  8787. }
  8788. else if (!checkType->IsValuelessType())
  8789. {
  8790. return _ExtractValue(checkType);
  8791. }
  8792. return BfIRValue();
  8793. };
  8794. BfIRValue value = checkTypeLambda(typedValue.mType);
  8795. return BfTypedValue(value, typedValue.mType, typedValue.IsThis() ? BfTypedValueKind_ThisValue : BfTypedValueKind_Value);
  8796. }
  8797. void BfModule::AggregateSplatIntoAddr(BfTypedValue typedValue, BfIRValue addrVal)
  8798. {
  8799. if (!typedValue.IsSplat())
  8800. return;
  8801. if (typedValue.mType->IsValuelessType())
  8802. return;
  8803. /*static int sCallIdx = 0;
  8804. if (!mCompiler->mIsResolveOnly)
  8805. sCallIdx++;
  8806. int callIdx = sCallIdx;*/
  8807. int elementIdx = 0;
  8808. std::function<void(BfType*, BfIRValue)> checkTypeLambda = [&](BfType* checkType, BfIRValue curAddrVal)
  8809. {
  8810. if (checkType->IsStruct())
  8811. {
  8812. auto checkTypeInstance = checkType->ToTypeInstance();
  8813. if (checkTypeInstance->mBaseType != NULL)
  8814. {
  8815. mBfIRBuilder->PopulateType(checkTypeInstance->mBaseType);
  8816. auto baseAddrVal = mBfIRBuilder->CreateInBoundsGEP(curAddrVal, 0, 0);
  8817. checkTypeLambda(checkTypeInstance->mBaseType, baseAddrVal);
  8818. }
  8819. if (checkTypeInstance->mIsUnion)
  8820. {
  8821. auto unionInnerType = checkTypeInstance->GetUnionInnerType();
  8822. if (!unionInnerType->IsValuelessType())
  8823. {
  8824. auto fieldAddrVal = mBfIRBuilder->CreateInBoundsGEP(curAddrVal, 0, 1);
  8825. checkTypeLambda(unionInnerType, fieldAddrVal);
  8826. }
  8827. if (checkTypeInstance->IsEnum())
  8828. {
  8829. auto dscrType = checkTypeInstance->GetDiscriminatorType();
  8830. auto fieldAddrVal = mBfIRBuilder->CreateInBoundsGEP(curAddrVal, 0, 2);
  8831. checkTypeLambda(dscrType, fieldAddrVal);
  8832. }
  8833. }
  8834. else
  8835. {
  8836. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  8837. {
  8838. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  8839. if (fieldInstance->mDataIdx >= 0)
  8840. {
  8841. auto fieldAddrVal = mBfIRBuilder->CreateInBoundsGEP(curAddrVal, 0, fieldInstance->mDataIdx);
  8842. checkTypeLambda(fieldInstance->mResolvedType, fieldAddrVal);
  8843. }
  8844. }
  8845. }
  8846. }
  8847. else if (checkType->IsMethodRef())
  8848. {
  8849. BfMethodRefType* methodRefType = (BfMethodRefType*)checkType;
  8850. for (int dataIdx = 0; dataIdx < methodRefType->GetCaptureDataCount(); dataIdx++)
  8851. {
  8852. auto dataType = methodRefType->GetCaptureType(dataIdx);
  8853. auto fieldAddrVal = mBfIRBuilder->CreateInBoundsGEP(curAddrVal, 0, dataIdx);
  8854. if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  8855. {
  8856. checkTypeLambda(methodRefType->GetCaptureType(dataIdx), fieldAddrVal);
  8857. }
  8858. else
  8859. {
  8860. // static int sItrCount = 0;
  8861. // sItrCount++;
  8862. // int curItr = sItrCount;
  8863. // if (curItr == 1)
  8864. // {
  8865. // NOP;
  8866. // }
  8867. auto val = ExtractSplatValue(typedValue, elementIdx++, dataType);
  8868. mBfIRBuilder->CreateStore(val, fieldAddrVal);
  8869. }
  8870. }
  8871. }
  8872. else if (!checkType->IsValuelessType())
  8873. {
  8874. auto val = ExtractSplatValue(typedValue, elementIdx++, checkType);
  8875. mBfIRBuilder->CreateStore(val, curAddrVal);
  8876. }
  8877. };
  8878. checkTypeLambda(typedValue.mType, addrVal);
  8879. }
  8880. BfTypedValue BfModule::MakeAddressable(BfTypedValue typedVal)
  8881. {
  8882. bool wasReadOnly = typedVal.IsReadOnly();
  8883. if ((typedVal.mType->IsValueType()) &&
  8884. (!typedVal.mType->IsValuelessType()))
  8885. {
  8886. wasReadOnly = true; // Any non-addr is implicitly read-only
  8887. //static int gCallIdx = 0;
  8888. if (typedVal.IsAddr())
  8889. return typedVal;
  8890. BfType* type = typedVal.mType;
  8891. PopulateType(type);
  8892. auto tempVar = CreateAlloca(type);
  8893. if (typedVal.IsSplat())
  8894. AggregateSplatIntoAddr(typedVal, tempVar);
  8895. else
  8896. mBfIRBuilder->CreateAlignedStore(typedVal.mValue, tempVar, type->mAlign);
  8897. return BfTypedValue(tempVar, type,
  8898. typedVal.IsThis() ?
  8899. (wasReadOnly ? BfTypedValueKind_ReadOnlyThisAddr : BfTypedValueKind_ThisAddr) :
  8900. (wasReadOnly ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Addr));
  8901. }
  8902. return LoadValue(typedVal);
  8903. }
  8904. BfTypedValue BfModule::RemoveReadOnly(BfTypedValue typedValue)
  8905. {
  8906. if (typedValue.mKind == BfTypedValueKind_ReadOnlyAddr)
  8907. typedValue.mKind = BfTypedValueKind_Addr;
  8908. return typedValue;
  8909. }
  8910. BfIRValue BfModule::ExtractSplatValue(BfTypedValue typedValue, int componentIdx, BfType* wantType, bool* isAddr)
  8911. {
  8912. BfIRValue val;
  8913. if (typedValue.mValue.IsArg())
  8914. {
  8915. val = mBfIRBuilder->GetArgument(typedValue.mValue.mId + componentIdx);
  8916. if (isAddr != NULL)
  8917. {
  8918. if (wantType != NULL)
  8919. *isAddr = wantType->IsComposite();
  8920. else
  8921. *isAddr = false;
  8922. }
  8923. else if (wantType->IsComposite())
  8924. val = mBfIRBuilder->CreateLoad(val);
  8925. }
  8926. if (!val)
  8927. {
  8928. auto checkMethodState = mCurMethodState;
  8929. while (checkMethodState != NULL)
  8930. {
  8931. for (int idx = 0; idx < (int)checkMethodState->mSplatDecompAddrs.size(); idx++)
  8932. {
  8933. auto decompAddr = checkMethodState->mSplatDecompAddrs[idx];
  8934. if (decompAddr == typedValue.mValue)
  8935. {
  8936. val = checkMethodState->mSplatDecompAddrs[idx + componentIdx];
  8937. if ((wantType->IsComposite()) && (typedValue.mType->IsMethodRef()))
  8938. {
  8939. // This is really backing for a POINTER to a composite inside a methodRef
  8940. val = mBfIRBuilder->CreateLoad(val);
  8941. }
  8942. if ((isAddr != NULL) && (typedValue.mKind != BfTypedValueKind_SplatHead_NeedsCasting))
  8943. {
  8944. *isAddr = true;
  8945. return val;
  8946. }
  8947. else
  8948. {
  8949. val = mBfIRBuilder->CreateLoad(val);
  8950. break;
  8951. }
  8952. }
  8953. }
  8954. if (val)
  8955. break;
  8956. checkMethodState = checkMethodState->mPrevMethodState;
  8957. }
  8958. }
  8959. if (val)
  8960. {
  8961. if (typedValue.mKind == BfTypedValueKind_SplatHead_NeedsCasting)
  8962. {
  8963. BF_ASSERT(wantType != NULL);
  8964. if (wantType != NULL)
  8965. return mBfIRBuilder->CreateBitCast(val, mBfIRBuilder->MapType(wantType));
  8966. }
  8967. return val;
  8968. }
  8969. BF_FATAL("Splat not found");
  8970. return BfIRValue();
  8971. }
  8972. BfTypedValue BfModule::ExtractValue(BfTypedValue typedValue, BfFieldInstance* fieldInstance, int fieldIdx)
  8973. {
  8974. int useFieldIdx = fieldIdx;
  8975. BfType* fieldType = NULL;
  8976. if (fieldInstance != NULL)
  8977. {
  8978. fieldType = fieldInstance->mResolvedType;
  8979. if (typedValue.mType->IsUnion())
  8980. {
  8981. if (fieldIdx == 1)
  8982. {
  8983. if (typedValue.IsSplat())
  8984. {
  8985. BfTypedValue innerVal = typedValue;
  8986. innerVal.mType = fieldType;
  8987. return innerVal;
  8988. }
  8989. }
  8990. }
  8991. }
  8992. else
  8993. {
  8994. if (typedValue.mType->IsPayloadEnum())
  8995. {
  8996. auto typeInst = typedValue.mType->ToTypeInstance();
  8997. if (fieldIdx == 1)
  8998. fieldType = typeInst->GetUnionInnerType();
  8999. else if (fieldIdx == 2)
  9000. {
  9001. fieldType = typeInst->GetDiscriminatorType(&useFieldIdx);
  9002. }
  9003. }
  9004. else if (typedValue.mType->IsUnion())
  9005. {
  9006. if (fieldIdx == 1)
  9007. {
  9008. fieldType = typedValue.mType->ToTypeInstance()->GetUnionInnerType();
  9009. if (typedValue.IsSplat())
  9010. {
  9011. BfTypedValue innerVal = typedValue;
  9012. innerVal.mType = fieldType;
  9013. return innerVal;
  9014. }
  9015. }
  9016. }
  9017. }
  9018. BF_ASSERT(typedValue.mType->IsStruct());
  9019. if (typedValue.IsSplat())
  9020. {
  9021. if (typedValue.mType->IsPayloadEnum())
  9022. {
  9023. if (fieldIdx == 1)
  9024. {
  9025. // Payload
  9026. auto typeInst = typedValue.mType->ToTypeInstance();
  9027. auto unionInnerType = typeInst->GetUnionInnerType();
  9028. bool isAddr = false;
  9029. BfIRValue irVal = ExtractSplatValue(typedValue, 0, unionInnerType, &isAddr);
  9030. return BfTypedValue(irVal, unionInnerType, BfTypedValueKind_SplatHead);
  9031. }
  9032. if (fieldIdx == 2)
  9033. {
  9034. // Discriminator
  9035. auto typeInst = typedValue.mType->ToTypeInstance();
  9036. auto unionInnerType = typeInst->GetUnionInnerType();
  9037. auto dscrType = typeInst->GetDiscriminatorType();
  9038. int argIdx = typedValue.mValue.mId;
  9039. int componentIdx = 0;
  9040. BfTypeUtils::SplatIterate([&](BfType* checkType) { componentIdx++; }, unionInnerType);
  9041. bool isAddr;
  9042. BfIRValue irVal = ExtractSplatValue(typedValue, componentIdx, dscrType, &isAddr);
  9043. return BfTypedValue(irVal, dscrType, isAddr);
  9044. }
  9045. }
  9046. int componentIdx = 0;
  9047. BfTypedValue retVal;
  9048. BfFieldInstance* wantFieldInstance = fieldInstance;
  9049. std::function<void(BfType*)> checkTypeLambda = [&](BfType* checkType)
  9050. {
  9051. if (checkType->IsStruct())
  9052. {
  9053. auto checkTypeInstance = checkType->ToTypeInstance();
  9054. if ((checkType->IsUnion()) || (checkType->IsEnum()))
  9055. {
  9056. //TODO: Why did we have this removed? It messed up an extraction from a nullable splattable
  9057. fieldType = checkTypeInstance->GetUnionInnerType();
  9058. checkTypeLambda(fieldType);
  9059. if (checkType->IsEnum())
  9060. {
  9061. // Past discriminator...
  9062. componentIdx++;
  9063. }
  9064. return;
  9065. }
  9066. if (checkTypeInstance->mBaseType != NULL)
  9067. checkTypeLambda(checkTypeInstance->mBaseType);
  9068. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  9069. {
  9070. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  9071. if (fieldInstance == wantFieldInstance)
  9072. {
  9073. bool isAddr = false;
  9074. BfIRValue val = ExtractSplatValue(typedValue, componentIdx, fieldInstance->mResolvedType, &isAddr);
  9075. retVal = BfTypedValue(val, fieldInstance->mResolvedType,
  9076. fieldInstance->mResolvedType->IsComposite() ? BfTypedValueKind_SplatHead :
  9077. isAddr ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Value);
  9078. if ((retVal.IsAddr()) && (!fieldInstance->mResolvedType->IsValueType()))
  9079. {
  9080. retVal = LoadValue(retVal);
  9081. }
  9082. break;
  9083. }
  9084. if (fieldInstance->mDataIdx >= 0)
  9085. checkTypeLambda(fieldInstance->GetResolvedType());
  9086. }
  9087. }
  9088. else if (!checkType->IsValuelessType())
  9089. {
  9090. componentIdx++;
  9091. //argIdx++;
  9092. }
  9093. };
  9094. checkTypeLambda(typedValue.mType);
  9095. BF_ASSERT(retVal);
  9096. return retVal;
  9097. }
  9098. if (typedValue.IsAddr())
  9099. {
  9100. BF_ASSERT(fieldType != NULL);
  9101. auto valRef = mBfIRBuilder->CreateInBoundsGEP(typedValue.mValue, 0, useFieldIdx);
  9102. return BfTypedValue(valRef, fieldType, BfTypedValueKind_ReadOnlyAddr);
  9103. }
  9104. else
  9105. {
  9106. BF_ASSERT(fieldType != NULL);
  9107. return BfTypedValue(mBfIRBuilder->CreateExtractValue(typedValue.mValue, useFieldIdx), fieldType, BfTypedValueKind_Value);
  9108. }
  9109. }
  9110. BfIRValue BfModule::ExtractValue(BfTypedValue typedValue, int dataIdx)
  9111. {
  9112. if (typedValue.IsAddr())
  9113. {
  9114. auto addrVal = mBfIRBuilder->CreateInBoundsGEP(typedValue.mValue, 0, dataIdx);
  9115. return mBfIRBuilder->CreateLoad(addrVal);
  9116. }
  9117. return mBfIRBuilder->CreateExtractValue(typedValue.mValue, dataIdx);
  9118. }
  9119. BfIRValue BfModule::CreateIndexedValue(BfType* elementType, BfIRValue value, BfIRValue indexValue, bool isElementIndex)
  9120. {
  9121. if (elementType->IsSizeAligned())
  9122. {
  9123. if (isElementIndex)
  9124. return mBfIRBuilder->CreateInBoundsGEP(value, GetConstValue(0), indexValue);
  9125. else
  9126. return mBfIRBuilder->CreateInBoundsGEP(value, indexValue);
  9127. }
  9128. auto ptrType = CreatePointerType(elementType);
  9129. auto ofsVal = mBfIRBuilder->CreateNumericCast(indexValue, true, BfTypeCode_IntPtr);
  9130. auto ofsScaledVal = mBfIRBuilder->CreateMul(ofsVal, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, elementType->GetStride()));
  9131. auto intVal = mBfIRBuilder->CreatePtrToInt(value, BfTypeCode_IntPtr);
  9132. auto newIntVal = mBfIRBuilder->CreateAdd(intVal, ofsScaledVal);
  9133. return mBfIRBuilder->CreateIntToPtr(newIntVal, mBfIRBuilder->MapType(ptrType));
  9134. }
  9135. BfIRValue BfModule::CreateIndexedValue(BfType* elementType, BfIRValue value, int indexValue, bool isElementIndex)
  9136. {
  9137. if (elementType->IsSizeAligned())
  9138. {
  9139. if (isElementIndex)
  9140. return mBfIRBuilder->CreateInBoundsGEP(value, 0, indexValue);
  9141. else
  9142. return mBfIRBuilder->CreateInBoundsGEP(value, indexValue);
  9143. }
  9144. return CreateIndexedValue(elementType, value, GetConstValue(indexValue), isElementIndex);
  9145. }
  9146. bool BfModule::CheckModifyValue(BfTypedValue& typedValue, BfAstNode* refNode, const char* modifyType)
  9147. {
  9148. if (modifyType == NULL)
  9149. modifyType = "modify";
  9150. if (typedValue.mType->IsVar())
  9151. return true;
  9152. if (typedValue.IsReadOnly())
  9153. {
  9154. Fail(StrFormat("Cannot %s read-only variable", modifyType), refNode);
  9155. return false;
  9156. }
  9157. if ((!typedValue.IsAddr()) && (!typedValue.mType->IsValuelessType()))
  9158. {
  9159. Fail(StrFormat("Cannot %s value", modifyType), refNode);
  9160. return false;
  9161. }
  9162. if (typedValue.mKind == BfTypedValueKind_TempAddr)
  9163. {
  9164. Fail(StrFormat("Cannot %s value", modifyType), refNode);
  9165. return false;
  9166. }
  9167. return true;
  9168. }
  9169. bool BfModule::CompareMethodSignatures(BfMethodInstance* methodA, BfMethodInstance* methodB)
  9170. {
  9171. // If one is an interface and the other is an impl, B is the impl
  9172. auto implOwner = methodB->GetOwner();
  9173. if (methodA->mMethodDef->mIsLocalMethod)
  9174. {
  9175. int sepPosA = (int)BF_MIN(methodA->mMethodDef->mName.IndexOf('@'), methodA->mMethodDef->mName.length());
  9176. int sepPosB = (int)BF_MIN(methodB->mMethodDef->mName.IndexOf('@'), methodB->mMethodDef->mName.length());
  9177. if (sepPosA != sepPosB)
  9178. return false;
  9179. if (strncmp(methodA->mMethodDef->mName.c_str(), methodB->mMethodDef->mName.c_str(), sepPosA) != 0)
  9180. return false;
  9181. }
  9182. else if (methodA->mMethodDef->mName != methodB->mMethodDef->mName)
  9183. return false;
  9184. if (methodA->mMethodDef->mCheckedKind != methodB->mMethodDef->mCheckedKind)
  9185. return false;
  9186. if (methodA->mMethodDef->mMethodType == BfMethodType_Ctor)
  9187. {
  9188. if (methodA->mMethodDef->mIsStatic != methodB->mMethodDef->mIsStatic)
  9189. return false;
  9190. }
  9191. if (methodA->mMethodDef->mMethodType == BfMethodType_Operator)
  9192. {
  9193. if (methodB->mMethodDef->mMethodType != BfMethodType_Operator)
  9194. return false;
  9195. auto operatorA = (BfOperatorDef*)methodA->mMethodDef;
  9196. auto operatorB = (BfOperatorDef*)methodB->mMethodDef;
  9197. if (operatorA->mOperatorDeclaration->mBinOp != operatorB->mOperatorDeclaration->mBinOp)
  9198. return false;
  9199. if (operatorA->mOperatorDeclaration->mUnaryOp != operatorB->mOperatorDeclaration->mUnaryOp)
  9200. return false;
  9201. if (operatorA->mOperatorDeclaration->mIsConvOperator)
  9202. {
  9203. if (!BfTypeUtils::TypeEquals(methodA->mReturnType, methodB->mReturnType, implOwner))
  9204. return false;
  9205. }
  9206. }
  9207. int implicitParamCountA = methodA->GetImplicitParamCount();
  9208. int implicitParamCountB = methodB->GetImplicitParamCount();
  9209. if (methodA->GetParamCount() - implicitParamCountA != methodB->GetParamCount() - implicitParamCountB)
  9210. return false;
  9211. if (methodA->mHadGenericDelegateParams != methodB->mHadGenericDelegateParams)
  9212. return false;
  9213. for (int paramIdx = 0; paramIdx < (int)methodA->GetParamCount() - implicitParamCountA; paramIdx++)
  9214. {
  9215. if ((!BfTypeUtils::TypeEquals(methodA->GetParamType(paramIdx + implicitParamCountA), methodB->GetParamType(paramIdx + implicitParamCountB), implOwner)) ||
  9216. (methodA->GetParamKind(paramIdx + implicitParamCountA) != methodB->GetParamKind(paramIdx + implicitParamCountB)))
  9217. return false;
  9218. }
  9219. // Compare generic params. Generic params are part of the method signature here
  9220. if (methodA->GetNumGenericParams() != methodB->GetNumGenericParams())
  9221. return false;
  9222. for (int genericParamIdx = 0; genericParamIdx < (int)methodA->GetNumGenericParams(); genericParamIdx++)
  9223. {
  9224. auto genericParamA = methodA->mMethodInfoEx->mGenericParams[genericParamIdx];
  9225. auto genericParamB = methodB->mMethodInfoEx->mGenericParams[genericParamIdx];
  9226. if (genericParamA->mGenericParamFlags != genericParamB->mGenericParamFlags)
  9227. return false;
  9228. if (genericParamA->mTypeConstraint != genericParamB->mTypeConstraint)
  9229. return false;
  9230. if (genericParamA->mInterfaceConstraints.size() != genericParamB->mInterfaceConstraints.size())
  9231. return false;
  9232. for (int interfaceIdx = 0; interfaceIdx < (int)genericParamA->mInterfaceConstraints.size(); interfaceIdx++)
  9233. if (genericParamA->mInterfaceConstraints[interfaceIdx] != genericParamB->mInterfaceConstraints[interfaceIdx])
  9234. return false;
  9235. }
  9236. return true;
  9237. }
  9238. bool BfModule::IsCompatibleInterfaceMethod(BfMethodInstance* iMethodInst, BfMethodInstance* methodInstance)
  9239. {
  9240. if (iMethodInst->mMethodDef->mName != methodInstance->mMethodDef->mName)
  9241. return false;
  9242. if (iMethodInst->mMethodDef->mIsOperator != methodInstance->mMethodDef->mIsOperator)
  9243. return false;
  9244. if (iMethodInst->mMethodDef->mIsOperator)
  9245. {
  9246. auto iOperatorDef = (BfOperatorDef*)iMethodInst->mMethodDef;
  9247. auto operatorDef = (BfOperatorDef*)methodInstance->mMethodDef;
  9248. if (iOperatorDef->mOperatorDeclaration->mUnaryOp != operatorDef->mOperatorDeclaration->mUnaryOp)
  9249. return false;
  9250. if (iOperatorDef->mOperatorDeclaration->mBinOp != operatorDef->mOperatorDeclaration->mBinOp)
  9251. return false;
  9252. }
  9253. if (iMethodInst->GetParamCount() != methodInstance->GetParamCount())
  9254. return false;
  9255. for (int paramIdx = 0; paramIdx < (int)iMethodInst->GetParamCount(); paramIdx++)
  9256. {
  9257. if (iMethodInst->GetParamKind(paramIdx) != methodInstance->GetParamKind(paramIdx))
  9258. return false;
  9259. BfType* iParamType = iMethodInst->GetParamType(paramIdx);
  9260. BfType* methodParamType = methodInstance->GetParamType(paramIdx);
  9261. if (iParamType->IsSelf())
  9262. {
  9263. if (methodParamType != methodInstance->GetOwner())
  9264. return false;
  9265. }
  9266. else if (!iParamType->IsGenericParam())
  9267. {
  9268. if (methodParamType != iParamType)
  9269. return false;
  9270. }
  9271. else
  9272. {
  9273. if (!methodParamType->IsGenericParam())
  9274. return false;
  9275. auto genericParamType = (BfGenericParamType*)methodParamType;
  9276. if (genericParamType->mGenericParamKind == BfGenericParamKind_Type)
  9277. return false;
  9278. auto genericParam = methodInstance->mMethodInfoEx->mGenericParams[genericParamType->mGenericParamIdx];
  9279. bool hadInterface = false;
  9280. for (auto interfaceConstraint : genericParam->mInterfaceConstraints)
  9281. if (interfaceConstraint == iParamType)
  9282. hadInterface = true;
  9283. if (!hadInterface)
  9284. return false;
  9285. }
  9286. }
  9287. return true;
  9288. }
  9289. void BfModule::AddMethodReference(const BfMethodRef& methodRef, BfGetMethodInstanceFlags flags)
  9290. {
  9291. BfMethodInstance* methodInstance = methodRef;
  9292. if ((mCurTypeInstance != NULL) && (!mCompiler->IsAutocomplete()))
  9293. {
  9294. auto methodInstanceGroup = methodInstance->mMethodInstanceGroup;
  9295. if ((methodInstance->IsSpecializedGenericMethod()) || (methodInstanceGroup->mOnDemandKind != BfMethodOnDemandKind_AlwaysInclude))
  9296. {
  9297. BF_ASSERT(!methodRef.mTypeInstance->IsFunction());
  9298. BfMethodRef methodRef = methodInstance;
  9299. BfSpecializedMethodRefInfo* specializedMethodRefInfo = NULL;
  9300. bool isNew = mCurTypeInstance->mSpecializedMethodReferences.TryAdd(methodRef, NULL, &specializedMethodRefInfo);
  9301. if (((flags & BfGetMethodInstanceFlag_Unreified) == 0) &&
  9302. ((flags & BfGetMethodInstanceFlag_NoForceReification) == 0) &&
  9303. (mIsReified))
  9304. {
  9305. specializedMethodRefInfo->mHasReifiedRef = true;
  9306. }
  9307. }
  9308. }
  9309. }
  9310. BfModuleMethodInstance BfModule::ReferenceExternalMethodInstance(BfMethodInstance* methodInstance, BfGetMethodInstanceFlags flags)
  9311. {
  9312. if ((flags & BfGetMethodInstanceFlag_ResultNotUsed) != 0)
  9313. return BfModuleMethodInstance(methodInstance, BfIRValue());
  9314. if (mBfIRBuilder == NULL)
  9315. return BfModuleMethodInstance(methodInstance, BfIRValue());
  9316. if (methodInstance->GetOwner()->IsFunction())
  9317. {
  9318. // No actual ref needed- not an actual generated function
  9319. return BfModuleMethodInstance(methodInstance, BfIRValue());
  9320. }
  9321. bool isGenFunction = methodInstance->mMethodInstanceGroup->mMethodIdx < 0;
  9322. if (!isGenFunction)
  9323. AddMethodReference(methodInstance, flags);
  9324. if (mBfIRBuilder->mIgnoreWrites)
  9325. return BfModuleMethodInstance(methodInstance, mBfIRBuilder->GetFakeVal());
  9326. if (mCompiler->IsSkippingExtraResolveChecks())
  9327. return BfModuleMethodInstance(methodInstance, BfIRFunction());
  9328. if (methodInstance->mMethodDef->mMethodType == BfMethodType_Mixin)
  9329. {
  9330. return BfModuleMethodInstance(methodInstance, BfIRFunction());
  9331. }
  9332. bool isInlined = (methodInstance->mAlwaysInline) || ((flags & BfGetMethodInstanceFlag_ForceInline) != 0);
  9333. BfMethodRef methodRef = methodInstance;
  9334. if (isInlined)
  9335. methodRef.mMethodRefFlags = (BfMethodRefFlags)(methodRef.mMethodRefFlags | BfMethodRefFlag_AlwaysInclude);
  9336. else
  9337. methodRef.mMethodRefFlags = BfMethodRefFlag_None;
  9338. if (!isGenFunction)
  9339. {
  9340. BfIRValue* irFuncPtr = NULL;
  9341. if (mFuncReferences.TryGetValue(methodRef, &irFuncPtr))
  9342. return BfModuleMethodInstance(methodInstance, *irFuncPtr);
  9343. }
  9344. if (mAwaitingInitFinish)
  9345. FinishInit();
  9346. BfIRValue func = CreateFunctionFrom(methodInstance, isGenFunction, isInlined);
  9347. if (!isGenFunction)
  9348. mFuncReferences[methodRef] = func;
  9349. BfLogSysM("Adding func reference. Module:%p MethodInst:%p NewLLVMFunc:%d OldLLVMFunc:%d\n", this, methodInstance, func.mId, methodInstance->mIRFunction.mId);
  9350. if ((isInlined) && (!mIsScratchModule))
  9351. {
  9352. // We can't just add a dependency to mCurTypeInstance because we may have nested inlined functions, and
  9353. // mCurTypeInstance will just reflect the owner of the method currently being inlined, not the top-level
  9354. // type instance
  9355. // Be smarter about this if we ever insert a lot of type instances into a single module - track in a field
  9356. BF_ASSERT(mOwnedTypeInstances.size() <= 1);
  9357. for (auto ownedTypeInst : mOwnedTypeInstances)
  9358. AddDependency(methodInstance->GetOwner(), ownedTypeInst, BfDependencyMap::DependencyFlag_InlinedCall);
  9359. if ((!mCompiler->mIsResolveOnly) && (mIsReified) && (!methodInstance->mIsUnspecialized))
  9360. {
  9361. mIncompleteMethodCount++;
  9362. BfInlineMethodRequest* inlineMethodRequest = mContext->mInlineMethodWorkList.Alloc();
  9363. inlineMethodRequest->mType = methodInstance->GetOwner();
  9364. inlineMethodRequest->mFromModule = this;
  9365. inlineMethodRequest->mFunc = func;
  9366. inlineMethodRequest->mFromModuleRevision = mRevision;
  9367. inlineMethodRequest->mMethodInstance = methodInstance;
  9368. BF_ASSERT(mIsModuleMutable);
  9369. BfLogSysM("mInlineMethodWorkList %p for method %p in module %p in ReferenceExternalMethodInstance\n", inlineMethodRequest, methodInstance, this);
  9370. }
  9371. }
  9372. return BfModuleMethodInstance(methodInstance, func);
  9373. }
  9374. BfModule* BfModule::GetOrCreateMethodModule(BfMethodInstance* methodInstance)
  9375. {
  9376. BfTypeInstance* typeInst = methodInstance->mMethodInstanceGroup->mOwner;
  9377. if (mBfIRBuilder == NULL)
  9378. {
  9379. // To allow for custom attribute data
  9380. PrepareForIRWriting(typeInst);
  9381. }
  9382. BfModule* declareModule = this;
  9383. // Get to the optionless branch head -- but this could still be a specialized method module, not the true root
  9384. while ((declareModule->mParentModule != NULL) && (!declareModule->mIsSpecializedMethodModuleRoot))
  9385. declareModule = declareModule->mParentModule;
  9386. // Check for attributes
  9387. if (typeInst == mContext->mBfObjectType)
  9388. {
  9389. auto methodDecl = methodInstance->mMethodDef->GetMethodDeclaration();
  9390. if (methodDecl != NULL)
  9391. {
  9392. auto attributesDirective = methodDecl->mAttributes;
  9393. if ((attributesDirective != NULL) && (mCompiler->mResolvePassData != NULL) &&
  9394. (attributesDirective->IsFromParser(mCompiler->mResolvePassData->mParser)) && (mCompiler->mResolvePassData->mSourceClassifier != NULL))
  9395. {
  9396. mCompiler->mResolvePassData->mSourceClassifier->VisitChild(attributesDirective);
  9397. }
  9398. }
  9399. }
  9400. else
  9401. {
  9402. // Only allow attributes on System.Object methods that can be handled inside the DefBuilder
  9403. GetMethodCustomAttributes(methodInstance);
  9404. }
  9405. BF_ASSERT(mModuleOptions == NULL);
  9406. if (methodInstance->GetCustomAttributes() != NULL)
  9407. {
  9408. auto project = typeInst->mTypeDef->mProject;
  9409. BfModuleOptions moduleOptions = declareModule->GetModuleOptions();
  9410. BfModuleOptions wantOptions = moduleOptions;
  9411. auto typeOptions = mSystem->GetTypeOptions(typeInst->mTypeOptionsIdx);
  9412. if (typeOptions != NULL)
  9413. {
  9414. wantOptions.mOptLevel = (BfOptLevel)BfTypeOptions::Apply((int)wantOptions.mOptLevel, (int)typeOptions->mOptimizationLevel);
  9415. wantOptions.mSIMDSetting = (BfSIMDSetting)BfTypeOptions::Apply((int)wantOptions.mSIMDSetting, typeOptions->mSIMDSetting);
  9416. wantOptions.mEmitDebugInfo = (BfSIMDSetting)BfTypeOptions::Apply((int)wantOptions.mEmitDebugInfo, typeOptions->mEmitDebugInfo);
  9417. }
  9418. if (!mCompiler->mAttributeTypeOptionMap.IsEmpty())
  9419. {
  9420. StringT<128> attrName;
  9421. for (auto& customAttrs : methodInstance->GetCustomAttributes()->mAttributes)
  9422. {
  9423. attrName.Clear();
  9424. customAttrs.mType->mTypeDef->mFullName.ToString(attrName);
  9425. Array<int>* arrPtr;
  9426. if (mCompiler->mAttributeTypeOptionMap.TryGetValue(attrName, &arrPtr))
  9427. {
  9428. for (auto optionsIdx : *arrPtr)
  9429. {
  9430. auto& typeOptions = mCompiler->mSystem->mTypeOptions[optionsIdx];
  9431. wantOptions.mOptLevel = (BfOptLevel)BfTypeOptions::Apply((int)wantOptions.mOptLevel, (int)typeOptions.mOptimizationLevel);
  9432. wantOptions.mSIMDSetting = (BfSIMDSetting)BfTypeOptions::Apply((int)wantOptions.mSIMDSetting, typeOptions.mSIMDSetting);
  9433. wantOptions.mEmitDebugInfo = (BfSIMDSetting)BfTypeOptions::Apply((int)wantOptions.mEmitDebugInfo, typeOptions.mEmitDebugInfo);
  9434. }
  9435. }
  9436. }
  9437. }
  9438. if ((HasCompiledOutput()) && (wantOptions != moduleOptions) && (!mIsScratchModule))
  9439. {
  9440. auto lastCheckModule = this;
  9441. auto checkModule = this->mNextAltModule;
  9442. while (checkModule != NULL)
  9443. {
  9444. if (*checkModule->mModuleOptions == wantOptions)
  9445. {
  9446. declareModule = checkModule;
  9447. break;
  9448. }
  9449. lastCheckModule = checkModule;
  9450. checkModule = checkModule->mNextAltModule;
  9451. }
  9452. // Not found?
  9453. if (declareModule == this)
  9454. {
  9455. String specModuleName = mModuleName + "@@";
  9456. if (wantOptions.mOptLevel != moduleOptions.mOptLevel)
  9457. specModuleName += StrFormat("O%d", wantOptions.mOptLevel);
  9458. if (wantOptions.mSIMDSetting != moduleOptions.mSIMDSetting)
  9459. specModuleName += StrFormat("SIMD%d", wantOptions.mSIMDSetting);
  9460. declareModule = new BfModule(mContext, specModuleName);
  9461. declareModule->mProject = project;
  9462. declareModule->mModuleOptions = new BfModuleOptions();
  9463. *declareModule->mModuleOptions = wantOptions;
  9464. declareModule->mParentModule = lastCheckModule;
  9465. declareModule->Init();
  9466. lastCheckModule->mNextAltModule = declareModule;
  9467. }
  9468. }
  9469. }
  9470. declareModule->PrepareForIRWriting(typeInst);
  9471. return declareModule;
  9472. }
  9473. BfModuleMethodInstance BfModule::GetMethodInstance(BfTypeInstance* typeInst, BfMethodDef* methodDef, const BfTypeVector& methodGenericArguments, BfGetMethodInstanceFlags flags, BfTypeInstance* foreignType)
  9474. {
  9475. if (((flags & BfGetMethodInstanceFlag_ForceInline) != 0) && (mCompiler->mIsResolveOnly))
  9476. {
  9477. // Don't bother inlining for resolve-only
  9478. flags = (BfGetMethodInstanceFlags)(flags & ~BfGetMethodInstanceFlag_ForceInline);
  9479. }
  9480. bool processNow = false;
  9481. bool keepInCurrentModule = false;
  9482. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mIsUnspecialized))
  9483. flags = (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_NoForceReification);
  9484. if (!typeInst->IsTypeMemberIncluded(methodDef->mDeclaringType))
  9485. {
  9486. return BfModuleMethodInstance();
  9487. }
  9488. if (methodDef->mIsLocalMethod)
  9489. {
  9490. auto rootMethodState = mCurMethodState->GetRootMethodState();
  9491. BfLocalMethod* localMethod;
  9492. if (rootMethodState->mLocalMethodCache.TryGetValue(methodDef->mName, &localMethod))
  9493. {
  9494. // Handle the def in the correct method state
  9495. return GetLocalMethodInstance(localMethod, methodGenericArguments);
  9496. }
  9497. BF_FATAL("Cannot find local method");
  9498. return BfModuleMethodInstance();
  9499. }
  9500. #ifdef _DEBUG
  9501. for (auto arg : methodGenericArguments)
  9502. BF_ASSERT(!arg->IsVar());
  9503. #endif
  9504. BF_ASSERT(methodDef->mMethodType != BfMethodType_Ignore);
  9505. // We need to do the 'mNeedsMethodProcessing' check because we want to do a proper initial "awaiting reference" population
  9506. // on the methods before we handle an on-demand situation. This also ensures that our type options are set before doing
  9507. // a FinishInit
  9508. if ((typeInst->IsIncomplete()) &&
  9509. (!typeInst->mResolvingVarField) && (!typeInst->mTypeFailed))
  9510. {
  9511. // For autocomplete, we still may not actually generate methods. This shouldn't matter, and on-demand works differently
  9512. // for resolve-only because we don't differentiate between reified/unreified there
  9513. PopulateType(typeInst, BfPopulateType_Full);
  9514. }
  9515. bool tryModuleMethodLookup = false;
  9516. BfModuleMethodInstance moduleMethodInst;
  9517. BfModule* instModule = typeInst->mModule;
  9518. if (keepInCurrentModule)
  9519. {
  9520. // Stay here
  9521. instModule = this;
  9522. }
  9523. if (this == mContext->mUnreifiedModule)
  9524. {
  9525. // Stay in this 'resolve only' module here
  9526. }
  9527. else if (flags & BfGetMethodInstanceFlag_ExplicitResolveOnlyPass)
  9528. {
  9529. BF_ASSERT(this == mContext->mUnreifiedModule);
  9530. }
  9531. else if (flags & BfGetMethodInstanceFlag_ExplicitSpecializedModule)
  9532. {
  9533. BF_ASSERT(instModule == mParentModule);
  9534. }
  9535. else if (instModule != this)
  9536. {
  9537. if ((!mIsReified) && (instModule->mIsReified))
  9538. {
  9539. BF_ASSERT(!mCompiler->mIsResolveOnly);
  9540. // A resolve-only module is specializing a method from a type in a reified module,
  9541. // we need to take care that this doesn't cause anything new to become reified
  9542. return mContext->mUnreifiedModule->GetMethodInstance(typeInst, methodDef, methodGenericArguments, (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_ExplicitResolveOnlyPass), foreignType);
  9543. }
  9544. else
  9545. {
  9546. if ((mIsReified) && (!instModule->mIsReified))
  9547. {
  9548. if (!instModule->mReifyQueued)
  9549. {
  9550. BF_ASSERT((mCompiler->mCompileState != BfCompiler::CompileState_Unreified) && (mCompiler->mCompileState != BfCompiler::CompileState_VData));
  9551. BfLogSysM("Queueing ReifyModule: %p\n", instModule);
  9552. mContext->mReifyModuleWorkList.Add(instModule);
  9553. instModule->mReifyQueued = true;
  9554. }
  9555. // This ensures that the method will actually be created when it gets reified
  9556. BfMethodSpecializationRequest* specializationRequest = mContext->mMethodSpecializationWorkList.Alloc();
  9557. specializationRequest->mFromModule = typeInst->mModule;
  9558. specializationRequest->mFromModuleRevision = typeInst->mModule->mRevision;
  9559. specializationRequest->mMethodDef = methodDef;
  9560. specializationRequest->mMethodGenericArguments = methodGenericArguments;
  9561. specializationRequest->mType = typeInst;
  9562. }
  9563. auto defFlags = (BfGetMethodInstanceFlags)(flags & ~BfGetMethodInstanceFlag_ForceInline);
  9564. // Not extern
  9565. // Create the instance in the proper module and then create a reference in this one
  9566. moduleMethodInst = instModule->GetMethodInstance(typeInst, methodDef, methodGenericArguments, defFlags, foreignType);
  9567. tryModuleMethodLookup = true;
  9568. if ((mIsReified) && (!moduleMethodInst.mMethodInstance->mIsReified))
  9569. {
  9570. CheckHotMethod(moduleMethodInst.mMethodInstance, "");
  9571. }
  9572. }
  9573. }
  9574. if (tryModuleMethodLookup)
  9575. return ReferenceExternalMethodInstance(moduleMethodInst.mMethodInstance, flags);
  9576. if (((flags & BfGetMethodInstanceFlag_ForceInline) != 0) && (!methodDef->mAlwaysInline))
  9577. {
  9578. auto moduleMethodInstance = GetMethodInstance(typeInst, methodDef, methodGenericArguments, (BfGetMethodInstanceFlags)(flags & ~BfGetMethodInstanceFlag_ForceInline), foreignType);
  9579. if (moduleMethodInstance)
  9580. return ReferenceExternalMethodInstance(moduleMethodInstance.mMethodInstance, flags);
  9581. return moduleMethodInst;
  9582. }
  9583. bool isReified = mIsReified /* || ((flags & BfGetMethodInstanceFlag_ExplicitResolveOnlyPass) != 0)*/;
  9584. bool hadConcreteInterfaceGenericArgument = false;
  9585. if ((flags & BfGetMethodInstanceFlag_Unreified) != 0)
  9586. isReified = false;
  9587. if ((flags & BfGetMethodInstanceFlag_ExplicitResolveOnlyPass) != 0)
  9588. {
  9589. isReified = false;
  9590. }
  9591. BfTypeVector sanitizedMethodGenericArguments;
  9592. SizedArray<BfProject*, 4> projectList;
  9593. bool isUnspecializedPass = (flags & BfGetMethodInstanceFlag_UnspecializedPass) != 0;
  9594. if ((isUnspecializedPass) && (methodDef->mGenericParams.size() == 0))
  9595. isUnspecializedPass = false;
  9596. // 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
  9597. bool isExternalExtensionMethod = false;
  9598. if ((!typeInst->IsUnspecializedType()) && (!isUnspecializedPass))
  9599. {
  9600. if (((flags & BfGetMethodInstanceFlag_ForeignMethodDef) == 0) && (methodDef->mDeclaringType->mProject != typeInst->mTypeDef->mProject))
  9601. {
  9602. auto specProject = methodDef->mDeclaringType->mProject;
  9603. isExternalExtensionMethod = true;
  9604. if (typeInst->IsGenericTypeInstance())
  9605. {
  9606. auto genericTypeInst = (BfGenericTypeInstance*)typeInst;
  9607. if (genericTypeInst->mProjectsReferenced.empty())
  9608. genericTypeInst->GenerateProjectsReferenced();
  9609. if (genericTypeInst->mProjectsReferenced.Contains(specProject))
  9610. {
  9611. // This is a generic type where a generic param is already confined to the project in question
  9612. isExternalExtensionMethod = false;
  9613. }
  9614. }
  9615. if (isExternalExtensionMethod)
  9616. {
  9617. BF_ASSERT(typeInst->mTypeDef->mIsCombinedPartial);
  9618. projectList.push_back(methodDef->mDeclaringType->mProject);
  9619. }
  9620. }
  9621. }
  9622. if ((!isUnspecializedPass) && (methodGenericArguments.size() != 0))
  9623. {
  9624. int typeProjectsCounts = 0;
  9625. if (typeInst->IsGenericTypeInstance())
  9626. {
  9627. auto genericTypeInst = (BfGenericTypeInstance*)typeInst;
  9628. if (genericTypeInst->mProjectsReferenced.empty())
  9629. genericTypeInst->GenerateProjectsReferenced();
  9630. typeProjectsCounts = (int)genericTypeInst->mProjectsReferenced.size();
  9631. projectList.Insert(0, &genericTypeInst->mProjectsReferenced[0], genericTypeInst->mProjectsReferenced.size());
  9632. }
  9633. else
  9634. {
  9635. typeProjectsCounts = 1;
  9636. projectList.Insert(0, typeInst->mTypeDef->mProject);
  9637. }
  9638. isUnspecializedPass = true;
  9639. for (int genericArgIdx = 0; genericArgIdx < (int) methodGenericArguments.size(); genericArgIdx++)
  9640. {
  9641. auto genericArgType = methodGenericArguments[genericArgIdx];
  9642. //BF_ASSERT(!genericArgType->IsRef());
  9643. if (genericArgType->IsConcreteInterfaceType())
  9644. {
  9645. hadConcreteInterfaceGenericArgument = true;
  9646. auto concreteInterfaceType = (BfConcreteInterfaceType*)genericArgType;
  9647. genericArgType = concreteInterfaceType->mInterface;
  9648. }
  9649. if (genericArgType->IsGenericParam())
  9650. {
  9651. auto genericParam = (BfGenericParamType*) genericArgType;
  9652. if ((genericParam->mGenericParamKind != BfGenericParamKind_Method) || (genericParam->mGenericParamIdx != genericArgIdx))
  9653. isUnspecializedPass = false;
  9654. }
  9655. else
  9656. {
  9657. BfTypeUtils::GetProjectList(genericArgType, &projectList, typeProjectsCounts);
  9658. isUnspecializedPass = false;
  9659. }
  9660. sanitizedMethodGenericArguments.push_back(genericArgType);
  9661. }
  9662. if ((int)projectList.size() > typeProjectsCounts)
  9663. {
  9664. // Just leave the new items
  9665. projectList.RemoveRange(0, typeProjectsCounts);
  9666. std::sort(projectList.begin(), projectList.end(), [](BfProject* lhs, BfProject*rhs)
  9667. {
  9668. return lhs->mName < rhs->mName;
  9669. });
  9670. }
  9671. else
  9672. {
  9673. projectList.Clear();
  9674. }
  9675. }
  9676. const BfTypeVector& lookupMethodGenericArguments = isUnspecializedPass ? BfTypeVector() : sanitizedMethodGenericArguments;
  9677. BfMethodInstanceGroup* methodInstGroup = NULL;
  9678. if ((flags & BfGetMethodInstanceFlag_ForeignMethodDef) != 0)
  9679. {
  9680. BF_ASSERT(!typeInst->IsInterface());
  9681. //for (auto& checkGroup : typeInst->mMethodInstanceGroups)
  9682. for (int methodIdx = (int)typeInst->mTypeDef->mMethods.size(); methodIdx < (int)typeInst->mMethodInstanceGroups.size(); methodIdx++)
  9683. {
  9684. auto& checkGroup = typeInst->mMethodInstanceGroups[methodIdx];
  9685. // if (checkGroup.mDefault == NULL)
  9686. // {
  9687. // // This should only be for when we explicitly add a spot so we can set mOnDemandKind
  9688. // BF_ASSERT(methodIdx == typeInst->mMethodInstanceGroups.size() - 1);
  9689. // methodInstGroup = &checkGroup;
  9690. // break;
  9691. // }
  9692. if ((checkGroup.mDefault != NULL) && (checkGroup.mDefault->mMethodDef == methodDef))
  9693. {
  9694. methodInstGroup = &checkGroup;
  9695. break;
  9696. }
  9697. }
  9698. if (methodInstGroup == NULL)
  9699. {
  9700. // Allocate a new entry
  9701. typeInst->mMethodInstanceGroups.Resize(typeInst->mMethodInstanceGroups.size() + 1);
  9702. methodInstGroup = &typeInst->mMethodInstanceGroups.back();
  9703. methodInstGroup->mMethodIdx = (int)typeInst->mMethodInstanceGroups.size() - 1;
  9704. methodInstGroup->mOwner = typeInst;
  9705. // if (methodInstGroup->mOnDemandKind == BfMethodOnDemandKind_NotSet)
  9706. // methodInstGroup->mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  9707. if (mCompiler->mOptions.mCompileOnDemandKind == BfCompileOnDemandKind_AlwaysInclude)
  9708. methodInstGroup->mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  9709. else
  9710. methodInstGroup->mOnDemandKind = BfMethodOnDemandKind_Decl_AwaitingDecl;
  9711. }
  9712. }
  9713. else
  9714. {
  9715. methodInstGroup = &typeInst->mMethodInstanceGroups[methodDef->mIdx];
  9716. }
  9717. if (methodInstGroup->mOnDemandKind == BfMethodOnDemandKind_NotSet)
  9718. {
  9719. BfLogSysM("Forcing BfMethodOnDemandKind_NotSet to BfMethodOnDemandKind_AlwaysInclude for Method:%s in Type:%p\n", methodDef->mName.c_str(), typeInst);
  9720. methodInstGroup->mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  9721. }
  9722. BfIRFunction prevIRFunc;
  9723. bool doingRedeclare = false;
  9724. BfMethodInstance* methodInstance = NULL;
  9725. auto _SetReified = [&]()
  9726. {
  9727. methodInstance->mIsReified = true;
  9728. };
  9729. if (lookupMethodGenericArguments.size() == 0)
  9730. {
  9731. methodInstance = methodInstGroup->mDefault;
  9732. if ((methodInstance != NULL) && (isReified) && (!methodInstance->mIsReified))
  9733. {
  9734. MarkDerivedDirty(typeInst);
  9735. if (mIsScratchModule)
  9736. {
  9737. BfLogSysM("Marking scratch module method instance as reified: %p\n", methodInstance);
  9738. _SetReified();
  9739. CheckHotMethod(methodInstance, "");
  9740. }
  9741. else if ((flags & BfGetMethodInstanceFlag_NoForceReification) != 0)
  9742. {
  9743. // We don't need to force reification if we're in an unspecialized generic- we can wait for
  9744. // the specializations to handle that for us
  9745. return BfModuleMethodInstance(methodInstance);
  9746. }
  9747. else if (methodInstGroup->mOnDemandKind == BfMethodOnDemandKind_Referenced)
  9748. {
  9749. if (methodDef->mIsAbstract)
  9750. {
  9751. BfLogSysM("Reifying abstract unreified method instance: %p IRFunction:%d\n", methodInstance, methodInstance->mIRFunction.mId);
  9752. _SetReified();
  9753. }
  9754. else
  9755. {
  9756. BfLogSysM("Re-declaring processed but unreified method instance: %p IRFunction:%d\n", methodInstance, methodInstance->mIRFunction.mId);
  9757. methodInstGroup->mOnDemandKind = BfMethodOnDemandKind_NoDecl_AwaitingReference;
  9758. methodInstance->UndoDeclaration(!methodInstance->mIRFunction.IsFake());
  9759. doingRedeclare = true;
  9760. mOnDemandMethodCount++;
  9761. }
  9762. }
  9763. else
  9764. {
  9765. BfLogSysM("Marking unprocessed method instance as reified: %p\n", methodInstance);
  9766. // We haven't processed it yet
  9767. _SetReified();
  9768. CheckHotMethod(methodInstance, "");
  9769. if (methodInstance->mDeclModule == this)
  9770. {
  9771. if (methodInstance->mMethodProcessRequest != NULL)
  9772. {
  9773. // Disconnect method process request
  9774. BF_ASSERT(methodInstance->mMethodProcessRequest->mFromModule == this);
  9775. }
  9776. }
  9777. else
  9778. {
  9779. if (methodInstance->mMethodProcessRequest != NULL)
  9780. {
  9781. // Disconnect method process request
  9782. BF_ASSERT(methodInstance->mMethodProcessRequest->mFromModule == mContext->mUnreifiedModule);
  9783. methodInstance->mMethodProcessRequest->mMethodInstance = NULL;
  9784. methodInstance->mMethodProcessRequest = NULL;
  9785. }
  9786. if (methodInstance->mDeclModule == mContext->mUnreifiedModule)
  9787. {
  9788. // Add new request in proper module
  9789. methodInstance->mDeclModule = this;
  9790. }
  9791. else
  9792. {
  9793. if (methodInstance->mDeclModule == NULL)
  9794. {
  9795. //
  9796. }
  9797. else if (methodInstance->mDeclModule != this)
  9798. {
  9799. // Is from specialized module?
  9800. BF_ASSERT(methodInstance->mDeclModule->mParentModule == this);
  9801. }
  9802. }
  9803. if ((!methodInstance->mIRFunction) || (methodInstance->mIRFunction.IsFake()))
  9804. {
  9805. methodInstance->mIRFunction = BfIRFunction();
  9806. if (!mIsModuleMutable)
  9807. StartExtension();
  9808. if ((!mBfIRBuilder->mIgnoreWrites) && (methodInstance->mDeclModule != NULL))
  9809. {
  9810. StringT<128> mangledName;
  9811. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), methodInstance);
  9812. bool isIntrinsic = false;
  9813. SetupIRFunction(methodInstance, mangledName, false, &isIntrinsic);
  9814. BfLogSysM("Creating new IRFunction %d\n", methodInstance->mIRFunction.mId);
  9815. }
  9816. }
  9817. AddMethodToWorkList(methodInstance);
  9818. }
  9819. }
  9820. }
  9821. }
  9822. else
  9823. {
  9824. BF_ASSERT(lookupMethodGenericArguments.size() != 0);
  9825. if (methodInstGroup->mMethodSpecializationMap == NULL)
  9826. methodInstGroup->mMethodSpecializationMap = new BfMethodInstanceGroup::MapType();
  9827. BfMethodInstance** methodInstancePtr = NULL;
  9828. if (methodInstGroup->mMethodSpecializationMap->TryGetValue(lookupMethodGenericArguments, &methodInstancePtr))
  9829. {
  9830. methodInstance = *methodInstancePtr;
  9831. if ((isReified) && (!methodInstance->mIsReified))
  9832. {
  9833. MarkDerivedDirty(typeInst);
  9834. if (methodInstance->mHasBeenProcessed)
  9835. {
  9836. BfLogSysM("Deleting processed but unreified specialized method instance %p\n", methodInstance);
  9837. delete methodInstance;
  9838. methodInstGroup->mMethodSpecializationMap->Remove(lookupMethodGenericArguments);
  9839. methodInstance = NULL;
  9840. }
  9841. else if ((!methodInstance->mIRFunction) || (methodInstance->mIRFunction.IsFake()))
  9842. {
  9843. BfLogSysM("Deleting declared but uncreated specialized method instance %p\n", methodInstance);
  9844. delete methodInstance;
  9845. methodInstGroup->mMethodSpecializationMap->Remove(lookupMethodGenericArguments);
  9846. methodInstance = NULL;
  9847. }
  9848. else
  9849. {
  9850. BfLogSysM("Reifying declared but unreified method instance %p\n", methodInstance);
  9851. // We haven't processed it yet
  9852. _SetReified();
  9853. CheckHotMethod(methodInstance, "");
  9854. }
  9855. }
  9856. }
  9857. }
  9858. if ((methodInstance != NULL) && (!doingRedeclare))
  9859. {
  9860. if (methodInstance->mMethodInstanceGroup->mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingReference)
  9861. {
  9862. /*if ((!mCompiler->mIsResolveOnly) && (!isReified))
  9863. BF_ASSERT(!methodInstance->mIsReified);*/
  9864. if (methodInstance->mIsReified != isReified)
  9865. BfLogSysM("GetMethodInstance %p Decl_AwaitingReference setting reified to %d\n", methodInstance, isReified);
  9866. if ((!isReified) &&
  9867. ((methodInstance->mDeclModule == NULL) || (!methodInstance->mDeclModule->mIsModuleMutable)))
  9868. {
  9869. methodInstance->mDeclModule = mContext->mUnreifiedModule;
  9870. methodInstance->mIRFunction = BfIRFunction();
  9871. }
  9872. methodInstance->mIsReified = isReified;
  9873. if ((methodInstance->mHotMethod != NULL) && (!mCompiler->IsHotCompile()) && (isReified))
  9874. {
  9875. methodInstance->mHotMethod->mFlags = (BfHotDepDataFlags)(methodInstance->mHotMethod->mFlags | BfHotDepDataFlag_IsOriginalBuild);
  9876. }
  9877. if (!methodInstance->mMethodDef->mIsAbstract)
  9878. {
  9879. AddMethodToWorkList(methodInstance);
  9880. }
  9881. else
  9882. {
  9883. methodInstance->mMethodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_Referenced;
  9884. }
  9885. }
  9886. if (mExtensionCount > 0)
  9887. {
  9888. if ((mIsModuleMutable) && (!methodInstance->mIRFunction) &&
  9889. ((projectList.IsEmpty() || ((flags & BfGetMethodInstanceFlag_ExplicitSpecializedModule) != 0))))
  9890. {
  9891. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, false);
  9892. if (mAwaitingInitFinish)
  9893. FinishInit();
  9894. // We need to refer to a function that was defined in a prior module
  9895. bool isInlined = (methodInstance->mAlwaysInline) || ((flags & BfGetMethodInstanceFlag_ForceInline) != 0);
  9896. methodInstance->mIRFunction = CreateFunctionFrom(methodInstance, false, isInlined);
  9897. BF_ASSERT((methodInstance->mDeclModule == this) || (methodInstance->mDeclModule == mContext->mUnreifiedModule) || (methodInstance->mDeclModule == NULL));
  9898. methodInstance->mDeclModule = this;
  9899. // Add this inlined def to ourselves
  9900. if ((methodInstance->mAlwaysInline) && (HasCompiledOutput()) && (!methodInstance->mIsUnspecialized))
  9901. {
  9902. mIncompleteMethodCount++;
  9903. BfInlineMethodRequest* inlineMethodRequest = mContext->mInlineMethodWorkList.Alloc();
  9904. inlineMethodRequest->mType = typeInst;
  9905. inlineMethodRequest->mFromModule = this;
  9906. inlineMethodRequest->mFunc = methodInstance->mIRFunction;
  9907. inlineMethodRequest->mFromModuleRevision = mRevision;
  9908. inlineMethodRequest->mMethodInstance = methodInstance;
  9909. BfLogSysM("mInlineMethodWorkList %p for method %p in module %p in GetMethodInstance\n", inlineMethodRequest, methodInstance, this);
  9910. BF_ASSERT(mIsModuleMutable);
  9911. }
  9912. }
  9913. }
  9914. if (mCompiler->IsSkippingExtraResolveChecks())
  9915. return BfModuleMethodInstance(methodInstance, BfIRFunction());
  9916. else
  9917. {
  9918. if (methodInstance->mDeclModule != this)
  9919. return ReferenceExternalMethodInstance(methodInstance, flags);
  9920. if ((!methodInstance->mIRFunction) && (mIsModuleMutable) && (!mBfIRBuilder->mIgnoreWrites))
  9921. {
  9922. auto importKind = methodInstance->GetImportCallKind();
  9923. if (importKind != BfImportCallKind_None)
  9924. {
  9925. BfLogSysM("DllImportGlobalVar creating %p\n", methodInstance);
  9926. methodInstance->mIRFunction = mBfIRBuilder->GetFakeVal();
  9927. mFuncReferences[methodInstance] = CreateDllImportGlobalVar(methodInstance, true);;
  9928. }
  9929. }
  9930. return BfModuleMethodInstance(methodInstance);
  9931. }
  9932. }
  9933. if (!doingRedeclare)
  9934. {
  9935. BfModule* specModule = NULL;
  9936. if ((!keepInCurrentModule) && (projectList.size() > 0) && (!isUnspecializedPass) && (HasCompiledOutput()) && (!mIsScratchModule))
  9937. {
  9938. specModule = GetSpecializedMethodModule(projectList);
  9939. }
  9940. if ((specModule != NULL) && (specModule != this))
  9941. {
  9942. auto specMethodInstance = specModule->GetMethodInstance(typeInst, methodDef, methodGenericArguments, (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_ExplicitSpecializedModule));
  9943. if (mAwaitingInitFinish)
  9944. return BfModuleMethodInstance(specMethodInstance.mMethodInstance, BfIRFunction());
  9945. return ReferenceExternalMethodInstance(specMethodInstance.mMethodInstance, flags);
  9946. }
  9947. if ((!isUnspecializedPass) && (methodGenericArguments.size() != 0) && (methodInstGroup->mDefault == NULL))
  9948. {
  9949. // We are attempting to specialize but we don't have the unspecialized method yet. Generate that first.
  9950. GetMethodInstance(typeInst, methodDef, BfTypeVector(), BfGetMethodInstanceFlag_UnspecializedPass);
  9951. }
  9952. }
  9953. if (methodInstance == NULL)
  9954. {
  9955. if (lookupMethodGenericArguments.size() == 0)
  9956. {
  9957. BF_ASSERT(methodInstGroup->mDefault == NULL);
  9958. methodInstance = new BfMethodInstance();
  9959. methodInstGroup->mDefault = methodInstance;
  9960. BfLogSysM("Created Default MethodInst: %p TypeInst: %p Group: %p\n", methodInstance, typeInst, methodInstGroup);
  9961. }
  9962. else
  9963. {
  9964. BfMethodInstance** methodInstancePtr = NULL;
  9965. bool added = methodInstGroup->mMethodSpecializationMap->TryAdd(lookupMethodGenericArguments, NULL, &methodInstancePtr);
  9966. BF_ASSERT(added);
  9967. methodInstance = new BfMethodInstance();
  9968. *methodInstancePtr = methodInstance;
  9969. BfLogSysM("Created Specialized MethodInst: %p TypeInst: %p\n", methodInstance, typeInst);
  9970. }
  9971. if ((prevIRFunc) && (!prevIRFunc.IsFake()))
  9972. methodInstance->mIRFunction = prevIRFunc; // Take it over
  9973. }
  9974. /*// 24 bits for typeid, 20 for method id, 20 for specialization index
  9975. methodInstance->mMethodId = ((int64)typeInst->mTypeId) + ((int64)methodInstGroup->mMethodIdx << 24);
  9976. if (methodInstGroup->mMethodSpecializationMap != NULL)
  9977. methodInstance->mMethodId += ((int64)methodInstGroup->mMethodSpecializationMap->size() << 44);*/
  9978. methodInstance->mMethodDef = methodDef;
  9979. methodInstance->mAlwaysInline = methodDef->mAlwaysInline;
  9980. methodInstance->mMethodInstanceGroup = methodInstGroup;
  9981. methodInstance->mIsReified = isReified;
  9982. SetupMethodIdHash(methodInstance);
  9983. if (hadConcreteInterfaceGenericArgument)
  9984. methodInstance->mIgnoreBody = true;
  9985. if ((flags & BfGetMethodInstanceFlag_ForeignMethodDef) != 0)
  9986. {
  9987. methodInstance->mIsForeignMethodDef = true;
  9988. BF_ASSERT(foreignType != NULL);
  9989. methodInstance->GetMethodInfoEx()->mForeignType = foreignType;
  9990. }
  9991. if ((typeInst->mTypeDef == mCompiler->mValueTypeTypeDef) && (methodDef->mName == BF_METHODNAME_EQUALS))
  9992. {
  9993. if (!lookupMethodGenericArguments.empty())
  9994. {
  9995. auto compareType = lookupMethodGenericArguments[0];
  9996. PopulateType(compareType, BfPopulateType_Data);
  9997. if (compareType->IsSplattable())
  9998. methodInstance->mAlwaysInline = true;
  9999. }
  10000. }
  10001. if (methodDef->mDeclaringType->mTypeDeclaration != typeInst->mTypeDef->mTypeDeclaration)
  10002. {
  10003. // With extensions we can have multiple definitions of the same method
  10004. //methodInstance->mMangleWithIdx = true;
  10005. }
  10006. BfModule* declareModule = GetOrCreateMethodModule(methodInstance);
  10007. BF_ASSERT(typeInst == methodInstance->GetOwner());
  10008. auto methodDeclaration = methodDef->GetMethodDeclaration();
  10009. if (isUnspecializedPass)
  10010. {
  10011. for (int genericParamIdx = 0; genericParamIdx < (int) methodDef->mGenericParams.size(); genericParamIdx++)
  10012. {
  10013. auto genericParamType = GetGenericParamType(BfGenericParamKind_Method, genericParamIdx);
  10014. methodInstance->GetMethodInfoEx()->mMethodGenericArguments.Add(genericParamType);
  10015. }
  10016. }
  10017. else if ((methodDeclaration != NULL) && (methodDeclaration->mGenericParams != NULL))
  10018. {
  10019. if (!sanitizedMethodGenericArguments.IsEmpty())
  10020. methodInstance->GetMethodInfoEx()->mMethodGenericArguments = sanitizedMethodGenericArguments;
  10021. if (methodDef->mGenericParams.size() != sanitizedMethodGenericArguments.size())
  10022. {
  10023. Fail("Internal error");
  10024. BF_FATAL("Generic method argument counts mismatch");
  10025. return NULL;
  10026. }
  10027. for (auto genericArg : sanitizedMethodGenericArguments)
  10028. {
  10029. if (genericArg->IsPrimitiveType())
  10030. genericArg = GetWrappedStructType(genericArg);
  10031. AddDependency(genericArg, typeInst, BfDependencyMap::DependencyFlag_MethodGenericArg);
  10032. if (genericArg->IsMethodRef())
  10033. {
  10034. auto methodRefType = (BfMethodRefType*)genericArg;
  10035. //AddDependency(genericArg, typeInst, BfDependencyMap::DependencyFlag_);
  10036. }
  10037. }
  10038. }
  10039. // Generic constraints
  10040. for (int genericParamIdx = 0; genericParamIdx < (int)methodDef->mGenericParams.size(); genericParamIdx++)
  10041. {
  10042. auto genericParamInstance = new BfGenericMethodParamInstance(methodDef, genericParamIdx);
  10043. methodInstance->GetMethodInfoEx()->mGenericParams.push_back(genericParamInstance);
  10044. }
  10045. for (int externConstraintIdx = 0; externConstraintIdx < (int)methodDef->mExternalConstraints.size(); externConstraintIdx++)
  10046. {
  10047. auto genericParamInstance = new BfGenericMethodParamInstance(methodDef, externConstraintIdx + (int)methodDef->mGenericParams.size());
  10048. methodInstance->GetMethodInfoEx()->mGenericParams.push_back(genericParamInstance);
  10049. }
  10050. bool addToWorkList = !processNow;
  10051. if (mCompiler->GetAutoComplete() != NULL)
  10052. {
  10053. if (typeInst->IsSpecializedByAutoCompleteMethod())
  10054. addToWorkList = false;
  10055. }
  10056. BF_ASSERT(declareModule != NULL);
  10057. methodInstance->mDeclModule = declareModule;
  10058. if ((!methodInstance->mIsReified) && (mCompiler->mCompileState != BfCompiler::CompileState_Normal))
  10059. {
  10060. // We can be sure this method won't become reified later. Normally we can "go either way" with an unreified method
  10061. // of a reified module -
  10062. // If we declare it in the reified module then we can switch it to "reified" before actual processing without any extra work,
  10063. // BUT if we don't reify it then we have to remove the body after processing.
  10064. // 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
  10065. // the proper reified module.
  10066. declareModule = mContext->mUnreifiedModule;
  10067. }
  10068. else if ((!declareModule->mIsModuleMutable) && (!mCompiler->mIsResolveOnly))
  10069. {
  10070. BF_ASSERT(!methodInstance->mIsReified);
  10071. declareModule = mContext->mUnreifiedModule;
  10072. }
  10073. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(declareModule->mCurMethodInstance, methodInstance);
  10074. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(declareModule->mCurTypeInstance, typeInst);
  10075. SetAndRestoreValue<BfFilePosition> prevFilePos(declareModule->mCurFilePosition);
  10076. declareModule->DoMethodDeclaration(methodDef->GetMethodDeclaration(), false, addToWorkList);
  10077. if (processNow)
  10078. {
  10079. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, NULL);
  10080. ProcessMethod(methodInstance);
  10081. }
  10082. if (mCompiler->IsSkippingExtraResolveChecks())
  10083. return BfModuleMethodInstance(methodInstance, BfIRFunction());
  10084. return BfModuleMethodInstance(methodInstance);
  10085. }
  10086. BfModuleMethodInstance BfModule::GetMethodInstance(BfMethodInstance* methodInstance, BfGetMethodInstanceFlags flags)
  10087. {
  10088. BF_ASSERT((methodInstance->mMethodInfoEx == NULL) || (methodInstance->mMethodInfoEx->mGenericParams.IsEmpty()));
  10089. if (methodInstance->mIsForeignMethodDef)
  10090. flags = (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_ForeignMethodDef);
  10091. return GetMethodInstance(methodInstance->GetOwner(), methodInstance->mMethodDef, BfTypeVector(), flags);
  10092. }
  10093. BfMethodInstance* BfModule::GetOuterMethodInstance(BfMethodInstance* methodInstance)
  10094. {
  10095. if (!methodInstance->mMethodDef->mIsLocalMethod)
  10096. return NULL;
  10097. auto outerLocal = methodInstance->mMethodInfoEx->mClosureInstanceInfo->mLocalMethod->mOuterLocalMethod;
  10098. if (outerLocal == NULL)
  10099. return NULL;
  10100. BfTypeVector genericArgs;
  10101. for (int i = 0; i < (int)outerLocal->mMethodDef->mGenericParams.size(); i++)
  10102. genericArgs.Add(methodInstance->mMethodInfoEx->mMethodGenericArguments[i]);
  10103. return GetLocalMethodInstance(outerLocal, genericArgs).mMethodInstance;
  10104. }
  10105. void BfModule::SetupMethodIdHash(BfMethodInstance* methodInstance)
  10106. {
  10107. HashContext hashCtx;
  10108. std::function<void(BfMethodInstance*)> _MixinMethodInstance = [&](BfMethodInstance* methodInstance)
  10109. {
  10110. hashCtx.Mixin(methodInstance->GetOwner()->mTypeId);
  10111. hashCtx.Mixin(methodInstance->mMethodDef->mIdx);
  10112. if (methodInstance->GetNumGenericArguments() != 0)
  10113. {
  10114. hashCtx.Mixin((int32)methodInstance->mMethodInfoEx->mMethodGenericArguments.size());
  10115. for (auto methodGenericArg : methodInstance->mMethodInfoEx->mMethodGenericArguments)
  10116. hashCtx.Mixin(methodGenericArg->mTypeId);
  10117. }
  10118. };
  10119. _MixinMethodInstance(methodInstance);
  10120. if (methodInstance->mMethodDef->mIsLocalMethod)
  10121. {
  10122. auto outmostMethodInstance = mCurMethodState->GetRootMethodState()->mMethodInstance;
  10123. BF_ASSERT((outmostMethodInstance->mIdHash != 0) || (outmostMethodInstance->mIsAutocompleteMethod));
  10124. hashCtx.Mixin(outmostMethodInstance->mIdHash);
  10125. }
  10126. methodInstance->mIdHash = (int64)hashCtx.Finish64();
  10127. }
  10128. BfIRValue BfModule::GetInterfaceSlotNum(BfTypeInstance* ifaceType)
  10129. {
  10130. BfIRValue globalValue;
  10131. BfIRValue* globalValuePtr = NULL;
  10132. if (mInterfaceSlotRefs.TryGetValue(ifaceType, &globalValuePtr))
  10133. {
  10134. globalValue = *globalValuePtr;
  10135. }
  10136. if (!globalValue)
  10137. {
  10138. // This is necessary to reify the interface type
  10139. PopulateType(ifaceType);
  10140. StringT<128> slotVarName;
  10141. BfMangler::MangleStaticFieldName(slotVarName, mCompiler->GetMangleKind(), ifaceType, "sBfSlotOfs");
  10142. BfType* intType = GetPrimitiveType(BfTypeCode_Int32);
  10143. BfIRValue value;
  10144. if ((mCompiler->mHotState != NULL) && (ifaceType->mSlotNum >= 0))
  10145. {
  10146. /*// If this interface already existed before this hot compile but we never indirectly called any of its methods
  10147. // then the sBfSlotOfs could have gotten its symbol stripped, so actually define it here.
  10148. int virtSlotIdx = ifaceType->mSlotNum + 1;
  10149. value = GetConstValue32(virtSlotIdx);*/
  10150. mCompiler->mHotState->mSlotDefineTypeIds.Add(ifaceType->mTypeId);
  10151. ifaceType->mDirty = true; // Makes sure we create interface in vdata
  10152. }
  10153. globalValue = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapType(intType), true, BfIRLinkageType_External, value, slotVarName);
  10154. mInterfaceSlotRefs[ifaceType] = globalValue;
  10155. }
  10156. return mBfIRBuilder->CreateLoad(globalValue/*, "slotOfs"*/);
  10157. }
  10158. void BfModule::HadSlotCountDependency()
  10159. {
  10160. if (mCompiler->mIsResolveOnly)
  10161. return;
  10162. BF_ASSERT(!mBfIRBuilder->mIgnoreWrites);
  10163. BF_ASSERT((mUsedSlotCount == BF_MAX(mCompiler->mMaxInterfaceSlots, 0)) || (mUsedSlotCount == -1));
  10164. mUsedSlotCount = BF_MAX(mCompiler->mMaxInterfaceSlots, 0);
  10165. }
  10166. BfTypedValue BfModule::ReferenceStaticField(BfFieldInstance* fieldInstance)
  10167. {
  10168. if (fieldInstance->mResolvedType->IsVar())
  10169. {
  10170. NOP;
  10171. }
  10172. if (mIsScratchModule)
  10173. {
  10174. // Just fake it for the extern and unspecialized modules
  10175. auto ptrType = CreatePointerType(fieldInstance->GetResolvedType());
  10176. return BfTypedValue(GetDefaultValue(ptrType), fieldInstance->GetResolvedType(), true);
  10177. }
  10178. BfIRValue globalValue;
  10179. auto fieldDef = fieldInstance->GetFieldDef();
  10180. if ((fieldDef->mIsConst) && (!fieldDef->mIsExtern))
  10181. {
  10182. if (fieldInstance->mConstIdx != -1)
  10183. {
  10184. auto constant = fieldInstance->mOwner->mConstHolder->GetConstantById(fieldInstance->mConstIdx);
  10185. return BfTypedValue(ConstantToCurrent(constant, fieldInstance->mOwner->mConstHolder, fieldInstance->GetResolvedType()), fieldInstance->GetResolvedType());
  10186. }
  10187. else
  10188. {
  10189. return GetDefaultTypedValue(fieldInstance->GetResolvedType());
  10190. }
  10191. }
  10192. BfIRValue* globalValuePtr = NULL;
  10193. if (mStaticFieldRefs.TryGetValue(fieldInstance, &globalValuePtr))
  10194. {
  10195. globalValue = *globalValuePtr;
  10196. BF_ASSERT(globalValue);
  10197. }
  10198. else
  10199. {
  10200. StringT<128> staticVarName;
  10201. BfMangler::Mangle(staticVarName, mCompiler->GetMangleKind(), fieldInstance);
  10202. auto typeType = fieldInstance->GetResolvedType();
  10203. if ((fieldDef->mIsExtern) && (fieldDef->mIsConst) && (typeType->IsPointer()))
  10204. {
  10205. typeType = typeType->GetUnderlyingType();
  10206. }
  10207. PopulateType(typeType);
  10208. if ((typeType != NULL) && (!typeType->IsValuelessType()))
  10209. {
  10210. globalValue = mBfIRBuilder->CreateGlobalVariable(
  10211. mBfIRBuilder->MapType(typeType),
  10212. false,
  10213. BfIRLinkageType_External,
  10214. BfIRValue(),
  10215. staticVarName,
  10216. IsThreadLocal(fieldInstance));
  10217. if (!mBfIRBuilder->mIgnoreWrites)
  10218. {
  10219. // Only store this if we actually did the creation
  10220. BF_ASSERT(globalValue);
  10221. mStaticFieldRefs[fieldInstance] = globalValue;
  10222. }
  10223. BfLogSysM("Mod:%p Type:%p ReferenceStaticField %p -> %p\n", this, fieldInstance->mOwner, fieldInstance, globalValue);
  10224. }
  10225. }
  10226. auto type = fieldInstance->GetResolvedType();
  10227. if (type->IsValuelessType())
  10228. return BfTypedValue(globalValue, type);
  10229. return BfTypedValue(globalValue, type, !fieldDef->mIsConst);
  10230. }
  10231. BfTypedValue BfModule::GetThis()
  10232. {
  10233. auto useMethodState = mCurMethodState;
  10234. while ((useMethodState != NULL) && (useMethodState->mClosureState != NULL) && (useMethodState->mClosureState->mCapturing))
  10235. {
  10236. useMethodState = useMethodState->mPrevMethodState;
  10237. }
  10238. if (useMethodState != NULL)
  10239. {
  10240. // Fake a 'this' for var field resolution
  10241. if (useMethodState->mTempKind == BfMethodState::TempKind_NonStatic)
  10242. {
  10243. auto thisType = mCurTypeInstance;
  10244. if (thisType->IsValueType())
  10245. return BfTypedValue(mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapTypeInstPtr(thisType)), thisType, BfTypedValueKind_ThisAddr);
  10246. else
  10247. return BfTypedValue(mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapTypeInst(thisType)), thisType, BfTypedValueKind_ThisValue);
  10248. }
  10249. else if (useMethodState->mTempKind == BfMethodState::TempKind_Static)
  10250. {
  10251. return BfTypedValue();
  10252. }
  10253. }
  10254. else
  10255. {
  10256. //TODO: Do we allow useMethodState to be NULL anymore?
  10257. return BfTypedValue();
  10258. }
  10259. // if (useMethodState->HasNonStaticMixin())
  10260. // {
  10261. // auto checkMethodState = useMethodState;
  10262. // while (checkMethodState != NULL)
  10263. // {
  10264. // for (int localIdx = (int)checkMethodState->mLocals.size() - 1; localIdx >= 0; localIdx--)
  10265. // {
  10266. // auto varDecl = checkMethodState->mLocals[localIdx];
  10267. // if (varDecl->mName == "this")
  10268. // {
  10269. // varDecl->mReadFromId = useMethodState->GetRootMethodState()->mCurAccessId++;
  10270. // if (varDecl->mIsSplat)
  10271. // {
  10272. // return BfTypedValue(varDecl->mValue, varDecl->mResolvedType, BfTypedValueKind_ThisSplatHead);
  10273. // }
  10274. // else if ((varDecl->mResolvedType->IsValueType()) && (varDecl->mAddr))
  10275. // {
  10276. // return BfTypedValue(varDecl->mAddr, varDecl->mResolvedType, BfTypedValueKind_ThisAddr);
  10277. // }
  10278. // return BfTypedValue(varDecl->mValue, varDecl->mResolvedType, varDecl->mResolvedType->IsValueType() ? BfTypedValueKind_ThisAddr : BfTypedValueKind_ThisValue);
  10279. // }
  10280. // }
  10281. //
  10282. // checkMethodState = checkMethodState->mPrevMethodState;
  10283. // }
  10284. // }
  10285. // Check mixin state for 'this'
  10286. {
  10287. auto checkMethodState = useMethodState;
  10288. while (checkMethodState != NULL)
  10289. {
  10290. if (checkMethodState->mMixinState != NULL)
  10291. {
  10292. BfTypedValue thisValue = checkMethodState->mMixinState->mTarget;
  10293. if (thisValue)
  10294. {
  10295. checkMethodState->mMixinState->mLastTargetAccessId = useMethodState->GetRootMethodState()->mCurAccessId++;
  10296. if (!thisValue.mType->IsValueType())
  10297. thisValue = LoadValue(thisValue);
  10298. return thisValue;
  10299. }
  10300. }
  10301. checkMethodState = checkMethodState->mPrevMethodState;
  10302. }
  10303. }
  10304. auto curMethodInstance = mCurMethodInstance;
  10305. if (useMethodState->mMethodInstance != NULL)
  10306. curMethodInstance = useMethodState->mMethodInstance;
  10307. if ((curMethodInstance == NULL) /*|| (!mCurMethodInstance->mIRFunction)*/ || (curMethodInstance->mMethodDef->mIsStatic))
  10308. {
  10309. if ((useMethodState->mClosureState != NULL) && (!useMethodState->mClosureState->mConstLocals.empty()))
  10310. {
  10311. auto& constLocal = useMethodState->mClosureState->mConstLocals[0];
  10312. if (constLocal.mIsThis)
  10313. {
  10314. BF_ASSERT(constLocal.mResolvedType->IsValuelessType());
  10315. return BfTypedValue(mBfIRBuilder->GetFakeVal(), constLocal.mResolvedType);
  10316. }
  10317. }
  10318. return BfTypedValue();
  10319. }
  10320. bool preferValue = !IsTargetingBeefBackend();
  10321. if (useMethodState->mLocals.IsEmpty())
  10322. {
  10323. // 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
  10324. BF_ASSERT(useMethodState->mPrevMethodState != NULL);
  10325. return BfTypedValue();
  10326. }
  10327. auto thisLocal = useMethodState->mLocals[0];
  10328. BF_ASSERT(thisLocal->mIsThis);
  10329. BfIRValue thisValue;
  10330. if ((preferValue) || (!thisLocal->mAddr) /*|| (thisLocal->mIsSplat)*/)
  10331. thisValue = thisLocal->mValue;
  10332. else if ((thisLocal->mIsSplat) || (thisLocal->mIsLowered))
  10333. thisValue = thisLocal->mAddr;
  10334. else
  10335. thisValue = mBfIRBuilder->CreateLoad(thisLocal->mAddr);
  10336. useMethodState->mLocals[0]->mReadFromId = useMethodState->GetRootMethodState()->mCurAccessId++;
  10337. if (useMethodState->mClosureState != NULL)
  10338. {
  10339. auto closureTypeInst = useMethodState->mClosureState->mClosureType;
  10340. if (closureTypeInst != NULL)
  10341. {
  10342. if (closureTypeInst->mFieldInstances.size() > 0)
  10343. {
  10344. auto& field = closureTypeInst->mFieldInstances[0];
  10345. auto fieldDef = field.GetFieldDef();
  10346. if (fieldDef->mName == "__this")
  10347. {
  10348. if (mCurMethodState->mClosureState->mCapturing)
  10349. mCurMethodState->mClosureState->mReferencedOuterClosureMembers.Add(&field);
  10350. // This is a captured 'this'
  10351. BfTypedValue result = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(thisValue, 0, field.mDataIdx), field.mResolvedType, true);
  10352. if (field.mResolvedType->IsRef())
  10353. {
  10354. auto refType = (BfRefType*)field.mResolvedType;
  10355. auto underlyingType = refType->GetUnderlyingType();
  10356. result = BfTypedValue(mBfIRBuilder->CreateLoad(result.mValue), underlyingType, true);
  10357. }
  10358. if (field.mResolvedType->IsObject())
  10359. {
  10360. result = LoadValue(result);
  10361. result.mKind = BfTypedValueKind_ThisValue;
  10362. }
  10363. else
  10364. {
  10365. if (fieldDef->mIsReadOnly)
  10366. result.mKind = BfTypedValueKind_ReadOnlyThisAddr;
  10367. else
  10368. result.mKind = BfTypedValueKind_ThisAddr;
  10369. }
  10370. return result;
  10371. }
  10372. }
  10373. return BfTypedValue();
  10374. }
  10375. if (useMethodState->mClosureState->mCapturing)
  10376. {
  10377. auto thisType = useMethodState->mLocals[0]->mResolvedType;
  10378. if (thisType->IsValueType())
  10379. return BfTypedValue(CreateAlloca(thisType), thisType, BfTypedValueKind_ThisAddr);
  10380. else
  10381. return BfTypedValue(GetDefaultValue(thisType), thisType, BfTypedValueKind_ThisValue);
  10382. }
  10383. }
  10384. auto localDef = useMethodState->mLocals[0];
  10385. auto curMethodOwner = mCurMethodInstance->mMethodInstanceGroup->mOwner;
  10386. if ((curMethodOwner->IsStruct()) || (curMethodOwner->IsTypedPrimitive()))
  10387. {
  10388. if ((localDef->mResolvedType->IsTypedPrimitive()) && (!mCurMethodInstance->mMethodDef->mIsMutating))
  10389. {
  10390. return BfTypedValue(thisValue, useMethodState->mLocals[0]->mResolvedType, BfTypedValueKind_ReadOnlyThisValue);
  10391. }
  10392. if (localDef->mIsSplat)
  10393. {
  10394. return BfTypedValue(thisValue, useMethodState->mLocals[0]->mResolvedType, BfTypedValueKind_ThisSplatHead);
  10395. }
  10396. return BfTypedValue(thisValue, useMethodState->mLocals[0]->mResolvedType, localDef->mIsReadOnly ? BfTypedValueKind_ReadOnlyThisAddr : BfTypedValueKind_ThisAddr);
  10397. }
  10398. return BfTypedValue(thisValue, mCurMethodInstance->mMethodInstanceGroup->mOwner, BfTypedValueKind_ThisValue);
  10399. }
  10400. BfLocalVariable* BfModule::GetThisVariable()
  10401. {
  10402. if (mCurMethodState == NULL)
  10403. return NULL;
  10404. auto methodState = mCurMethodState->GetNonCaptureState();
  10405. if ((methodState->mLocals.size() > 0) && (methodState->mLocals[0]->mIsThis))
  10406. return methodState->mLocals[0];
  10407. return NULL;
  10408. }
  10409. bool BfModule::IsInGeneric()
  10410. {
  10411. return (mCurMethodInstance->GetNumGenericArguments() != 0) || (mCurTypeInstance->IsGenericTypeInstance());
  10412. }
  10413. bool BfModule::IsInSpecializedGeneric()
  10414. {
  10415. if ((mCurMethodInstance == NULL) || (mCurMethodInstance->mIsUnspecialized))
  10416. return false;
  10417. return (mCurMethodInstance->GetNumGenericArguments() != 0) || (mCurTypeInstance->IsGenericTypeInstance());
  10418. }
  10419. bool BfModule::IsInSpecializedSection()
  10420. {
  10421. return IsInSpecializedGeneric() ||
  10422. ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL));
  10423. }
  10424. bool BfModule::IsInUnspecializedGeneric()
  10425. {
  10426. if (mCurMethodInstance != NULL)
  10427. return mCurMethodInstance->mIsUnspecialized;
  10428. return false;
  10429. }
  10430. //////////////////////////////////////////////////////////////////////////
  10431. BfIRValue BfModule::AllocLocalVariable(BfType* type, const StringImpl& name, bool doLifetimeEnd)
  10432. {
  10433. //if ((type->IsValuelessType()) || (type->IsMethodRef()))
  10434. if (type->IsValuelessType())
  10435. return mBfIRBuilder->GetFakeVal();
  10436. auto allocaInst = CreateAlloca(type, doLifetimeEnd, name.c_str());
  10437. if ((!doLifetimeEnd) && (WantsLifetimes()))
  10438. {
  10439. auto lifetimeStart = mBfIRBuilder->CreateLifetimeStart(allocaInst);
  10440. mBfIRBuilder->ClearDebugLocation(lifetimeStart);
  10441. }
  10442. bool initLocalVariables = mCompiler->mOptions.mInitLocalVariables;
  10443. auto typeOptions = GetTypeOptions();
  10444. if (typeOptions != NULL)
  10445. initLocalVariables = BfTypeOptions::Apply(initLocalVariables, typeOptions->mInitLocalVariables);
  10446. // Local variable inits are implicitly handled in the Beef Backend
  10447. if ((initLocalVariables) && (!IsTargetingBeefBackend()))
  10448. {
  10449. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  10450. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRInitBlock);
  10451. auto storeInst = mBfIRBuilder->CreateAlignedStore(GetDefaultValue(type), allocaInst, type->mAlign);
  10452. mBfIRBuilder->ClearDebugLocation(storeInst);
  10453. mBfIRBuilder->SetInsertPoint(prevBlock);
  10454. }
  10455. return allocaInst;
  10456. }
  10457. void BfModule::DoAddLocalVariable(BfLocalVariable* localVar)
  10458. {
  10459. localVar->mLocalVarIdx = (int)mCurMethodState->mLocals.size();
  10460. mCurMethodState->mLocals.push_back(localVar);
  10461. BfLocalVarEntry* localVarEntryPtr;
  10462. if (!mCurMethodState->mLocalVarSet.TryAdd(BfLocalVarEntry(localVar), &localVarEntryPtr))
  10463. {
  10464. localVar->mShadowedLocal = localVarEntryPtr->mLocalVar;
  10465. localVarEntryPtr->mLocalVar = localVar;
  10466. }
  10467. }
  10468. BfLocalVariable* BfModule::AddLocalVariableDef(BfLocalVariable* localVarDef, bool addDebugInfo, bool doAliasValue, BfIRValue declareBefore, BfIRInitType initType)
  10469. {
  10470. if ((localVarDef->mValue) && (!localVarDef->mAddr) && (IsTargetingBeefBackend()))
  10471. {
  10472. if ((!localVarDef->mValue.IsConst()) && (!localVarDef->mValue.IsArg()) && (!localVarDef->mValue.IsFake()))
  10473. {
  10474. mBfIRBuilder->CreateValueScopeRetain(localVarDef->mValue);
  10475. mCurMethodState->mCurScope->mHadScopeValueRetain = true;
  10476. }
  10477. }
  10478. if ((addDebugInfo) && (mBfIRBuilder->DbgHasInfo()) &&
  10479. ((mCurMethodInstance == NULL) || (!mCurMethodInstance->mIsUnspecialized)) &&
  10480. (mHasFullDebugInfo) &&
  10481. ((mCurMethodState->mClosureState == NULL) || (!mCurMethodState->mClosureState->mCapturing)))
  10482. {
  10483. auto varType = localVarDef->mResolvedType;
  10484. if (localVarDef->mResolvedType->IsValuelessType())
  10485. {
  10486. }
  10487. else
  10488. {
  10489. bool isByAddr = false;
  10490. auto diValue = localVarDef->mValue;
  10491. if (localVarDef->mConstValue)
  10492. diValue = localVarDef->mConstValue;
  10493. else if (localVarDef->mAddr)
  10494. {
  10495. diValue = localVarDef->mAddr;
  10496. isByAddr = true;
  10497. }
  10498. auto diType = mBfIRBuilder->DbgGetType(localVarDef->mResolvedType);
  10499. bool didConstToMem = false;
  10500. bool isConstant = false;
  10501. if ((localVarDef->mIsReadOnly) && (localVarDef->mAddr))
  10502. diType = mBfIRBuilder->DbgCreateConstType(diType);
  10503. else if (localVarDef->mConstValue)
  10504. {
  10505. auto constant = mBfIRBuilder->GetConstant(localVarDef->mConstValue);
  10506. isConstant =
  10507. (constant->mConstType < BfConstType_GlobalVar) ||
  10508. (constant->mConstType == BfConstType_AggZero) ||
  10509. (constant->mConstType == BfConstType_Array);
  10510. if (isConstant)
  10511. {
  10512. if (localVarDef->mResolvedType->IsComposite())
  10513. {
  10514. mBfIRBuilder->PopulateType(localVarDef->mResolvedType);
  10515. auto constMem = mBfIRBuilder->ConstToMemory(localVarDef->mConstValue);
  10516. if (IsTargetingBeefBackend())
  10517. {
  10518. diValue = mBfIRBuilder->CreateAliasValue(constMem);
  10519. didConstToMem = true;
  10520. diType = mBfIRBuilder->DbgCreateReferenceType(diType);
  10521. }
  10522. else
  10523. {
  10524. isByAddr = true;
  10525. mBfIRBuilder->SaveDebugLocation();
  10526. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  10527. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRInitBlock);
  10528. mBfIRBuilder->ClearDebugLocation();
  10529. auto ptrType = CreatePointerType(localVarDef->mResolvedType);
  10530. auto addrVal = CreateAlloca(ptrType);
  10531. mBfIRBuilder->CreateStore(constMem, addrVal);
  10532. diType = mBfIRBuilder->DbgCreateReferenceType(diType);
  10533. diValue = addrVal;
  10534. didConstToMem = true;
  10535. mBfIRBuilder->SetInsertPoint(prevBlock);
  10536. mBfIRBuilder->RestoreDebugLocation();
  10537. }
  10538. }
  10539. if (mCompiler->mOptions.IsCodeView())
  10540. diType = mBfIRBuilder->DbgCreateConstType(diType);
  10541. }
  10542. }
  10543. auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(mCurMethodState->mCurScope->mDIScope,
  10544. localVarDef->mName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType, initType);
  10545. localVarDef->mDbgVarInst = diVariable;
  10546. if (mBfIRBuilder->HasDebugLocation())
  10547. {
  10548. if ((isConstant) && (!didConstToMem))
  10549. {
  10550. localVarDef->mDbgDeclareInst = mBfIRBuilder->DbgInsertValueIntrinsic(localVarDef->mConstValue, diVariable);
  10551. }
  10552. else
  10553. {
  10554. if ((IsTargetingBeefBackend()) && (doAliasValue))
  10555. {
  10556. diValue = mBfIRBuilder->CreateAliasValue(diValue);
  10557. mCurMethodState->mCurScope->mDeferredLifetimeEnds.Add(diValue);
  10558. }
  10559. if (isByAddr)
  10560. localVarDef->mDbgDeclareInst = mBfIRBuilder->DbgInsertDeclare(diValue, diVariable, declareBefore);
  10561. else if (diValue)
  10562. {
  10563. localVarDef->mDbgDeclareInst = mBfIRBuilder->DbgInsertValueIntrinsic(diValue, diVariable);
  10564. }
  10565. else if (mCompiler->mOptions.mToolsetType != BfToolsetType_GNU) // DWARF chokes on this:
  10566. localVarDef->mDbgDeclareInst = mBfIRBuilder->DbgInsertValueIntrinsic(BfIRValue(), diVariable);
  10567. }
  10568. }
  10569. }
  10570. }
  10571. localVarDef->mDeclBlock = mBfIRBuilder->GetInsertBlock();
  10572. DoAddLocalVariable(localVarDef);
  10573. auto rootMethodState = mCurMethodState->GetRootMethodState();
  10574. if (localVarDef->mLocalVarId == -1)
  10575. {
  10576. BF_ASSERT(rootMethodState->mCurLocalVarId >= 0);
  10577. localVarDef->mLocalVarId = rootMethodState->mCurLocalVarId++;
  10578. }
  10579. if ((localVarDef->mNameNode != NULL) && (mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL))
  10580. mCompiler->mResolvePassData->mAutoComplete->CheckLocalDef(localVarDef->mNameNode, localVarDef);
  10581. if ((localVarDef->mNameNode != NULL) && (mCurMethodInstance != NULL))
  10582. {
  10583. bool isClosureProcessing = (mCurMethodState->mClosureState != NULL) && (!mCurMethodState->mClosureState->mCapturing);
  10584. if ((!isClosureProcessing) && (mCompiler->mResolvePassData != NULL) && (localVarDef->mNameNode != NULL))
  10585. mCompiler->mResolvePassData->HandleLocalReference(localVarDef->mNameNode, rootMethodState->mMethodInstance->GetOwner()->mTypeDef, rootMethodState->mMethodInstance->mMethodDef, localVarDef->mLocalVarId);
  10586. }
  10587. return localVarDef;
  10588. }
  10589. void BfModule::CreateDIRetVal()
  10590. {
  10591. if (!WantsDebugInfo())
  10592. return;
  10593. /*if (!mCurMethodState->mRetVal)
  10594. {
  10595. if (mCurMethodInstance->mMethodDef->mName != "Ziggle")
  10596. return;
  10597. }*/
  10598. if ((mCurMethodState->mRetVal) || (mCurMethodState->mRetValAddr))
  10599. {
  10600. BfType* dbgType = mCurMethodInstance->mReturnType;
  10601. BfIRValue dbgValue = mCurMethodState->mRetVal.mValue;
  10602. if (mCurMethodInstance->HasStructRet())
  10603. {
  10604. BF_ASSERT(mCurMethodState->mRetValAddr);
  10605. dbgType = CreatePointerType(dbgType);
  10606. dbgValue = mCurMethodState->mRetValAddr;
  10607. }
  10608. else
  10609. {
  10610. BF_ASSERT(!mCurMethodState->mRetValAddr);
  10611. }
  10612. mCurMethodState->mDIRetVal = mBfIRBuilder->DbgCreateAutoVariable(mCurMethodState->mCurScope->mDIScope,
  10613. "__return", mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, mBfIRBuilder->DbgGetType(dbgType));
  10614. auto declareCall = mBfIRBuilder->DbgInsertDeclare(dbgValue, mCurMethodState->mDIRetVal);
  10615. }
  10616. }
  10617. void BfModule::CheckVariableDef(BfLocalVariable* variableDef)
  10618. {
  10619. BfLocalVarEntry* localVarEntryPtr = NULL;
  10620. if ((mCurMethodState != NULL) && (mCurMethodState->mLocalVarSet.TryGet(BfLocalVarEntry(variableDef), &localVarEntryPtr)))
  10621. {
  10622. auto checkLocal = localVarEntryPtr->mLocalVar;
  10623. if ((checkLocal->mLocalVarIdx >= mCurMethodState->GetLocalStartIdx()) && (!checkLocal->mIsShadow))
  10624. {
  10625. BfError* error;
  10626. if (checkLocal->mIsImplicitParam)
  10627. return; // Ignore 'redefinition'
  10628. if (checkLocal->IsParam())
  10629. error = Fail(StrFormat("A parameter named '%s' has already been declared.", variableDef->mName.c_str()), variableDef->mNameNode);
  10630. else if (checkLocal->mLocalVarIdx < mCurMethodState->mCurScope->mLocalVarStart)
  10631. error = Fail(StrFormat("A variable named '%s' has already been declared in this parent's scope.", variableDef->mName.c_str()), variableDef->mNameNode);
  10632. else
  10633. error = Fail(StrFormat("A variable named '%s' has already been declared in this scope.", variableDef->mName.c_str()), variableDef->mNameNode);
  10634. if ((checkLocal->mNameNode != NULL) && (error != NULL))
  10635. mCompiler->mPassInstance->MoreInfo("Previous declaration", checkLocal->mNameNode);
  10636. return;
  10637. }
  10638. }
  10639. }
  10640. BfScopeData* BfModule::FindScope(BfAstNode* scopeName, BfMixinState* fromMixinState, bool allowAcrossDeferredBlock)
  10641. {
  10642. bool inMixinDecl = (mCurMethodInstance != NULL) && (mCurMethodInstance->IsMixin());
  10643. if (auto tokenNode = BfNodeDynCast<BfTokenNode>(scopeName))
  10644. {
  10645. if (tokenNode->GetToken() == BfToken_Colon)
  10646. {
  10647. if ((!allowAcrossDeferredBlock) && (mCurMethodState->mInDeferredBlock))
  10648. {
  10649. Fail("Cannot access method scope across deferred block boundary", scopeName);
  10650. return NULL;
  10651. }
  10652. return &mCurMethodState->mHeadScope;
  10653. }
  10654. else if (tokenNode->GetToken() == BfToken_Mixin)
  10655. {
  10656. if (fromMixinState == NULL)
  10657. {
  10658. if (mCurMethodInstance->mMethodDef->mMethodType != BfMethodType_Mixin)
  10659. Fail("'mixin' scope specifier can only be used within a mixin declaration", scopeName);
  10660. return mCurMethodState->mCurScope;
  10661. }
  10662. fromMixinState->mUsedInvocationScope = true;
  10663. return fromMixinState->mTargetScope;
  10664. }
  10665. else if (tokenNode->GetToken() == BfToken_New)
  10666. return NULL;
  10667. }
  10668. if (auto identifier = BfNodeDynCast<BfIdentifierNode>(scopeName))
  10669. {
  10670. auto findLabel = scopeName->ToString();
  10671. bool crossedDeferredBlock = false;
  10672. auto checkScope = mCurMethodState->mCurScope;
  10673. while (checkScope != NULL)
  10674. {
  10675. if (checkScope->mIsDeferredBlock)
  10676. crossedDeferredBlock = true;
  10677. if (checkScope->mLabel == findLabel)
  10678. {
  10679. if ((crossedDeferredBlock) && (!allowAcrossDeferredBlock))
  10680. {
  10681. Fail(StrFormat("Cannot access scope '%s' across deferred block boundary", findLabel.c_str()), scopeName);
  10682. return NULL;
  10683. }
  10684. return checkScope;
  10685. }
  10686. checkScope = checkScope->mPrevScope;
  10687. }
  10688. if (!inMixinDecl)
  10689. Fail(StrFormat("Unable to locate label '%s'", findLabel.c_str()), scopeName);
  10690. }
  10691. if (auto scopeNode = BfNodeDynCast<BfScopeNode>(scopeName))
  10692. {
  10693. return FindScope(scopeNode->mTargetNode, allowAcrossDeferredBlock);
  10694. }
  10695. return mCurMethodState->mCurScope;
  10696. }
  10697. BfScopeData* BfModule::FindScope(BfAstNode* scopeName, bool allowAcrossDeferredBlock)
  10698. {
  10699. return FindScope(scopeName, mCurMethodState->mMixinState, allowAcrossDeferredBlock);
  10700. }
  10701. BfBreakData* BfModule::FindBreakData(BfAstNode* scopeName)
  10702. {
  10703. auto scopeData = FindScope(scopeName, false);
  10704. if (scopeData == NULL)
  10705. return NULL;
  10706. int scopeDepth = scopeData->GetDepth();
  10707. // Find the first break data that is at or below the depth of our requested scope
  10708. auto breakData = mCurMethodState->mBreakData;
  10709. while ((breakData != NULL) && (scopeDepth < breakData->mScope->GetDepth()))
  10710. {
  10711. if (breakData->mScope->mIsConditional)
  10712. return NULL;
  10713. breakData = breakData->mPrevBreakData;
  10714. }
  10715. return breakData;
  10716. }
  10717. void BfModule::EmitLifetimeEnds(BfScopeData* scopeData)
  10718. {
  10719. // LLVM is stricter about the placement of these (ie: they can't occur after a 'ret')
  10720. if (!IsTargetingBeefBackend())
  10721. return;
  10722. for (auto lifetimeEnd : scopeData->mDeferredLifetimeEnds)
  10723. {
  10724. mBfIRBuilder->CreateLifetimeEnd(lifetimeEnd);
  10725. }
  10726. }
  10727. void BfModule::ClearLifetimeEnds()
  10728. {
  10729. auto scopeData = mCurMethodState->mCurScope;
  10730. while (scopeData != NULL)
  10731. {
  10732. scopeData->mDeferredLifetimeEnds.Clear();
  10733. scopeData = scopeData->mPrevScope;
  10734. }
  10735. }
  10736. bool BfModule::WantsDebugInfo()
  10737. {
  10738. if ((mCurMethodInstance != NULL) &&
  10739. ((mCurMethodInstance->mIsUnspecialized) || (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_Mixin)))
  10740. return false;
  10741. return (mBfIRBuilder->DbgHasInfo()) && (mHasFullDebugInfo) &&
  10742. ((mCurMethodState == NULL) || (mCurMethodState->mClosureState == NULL) || (!mCurMethodState->mClosureState->mCapturing));
  10743. }
  10744. BfTypeOptions* BfModule::GetTypeOptions()
  10745. {
  10746. if ((mCurMethodState != NULL) && (mCurMethodState->mMethodTypeOptions != NULL))
  10747. return mCurMethodState->mMethodTypeOptions;
  10748. return mSystem->GetTypeOptions(mCurTypeInstance->mTypeOptionsIdx);
  10749. }
  10750. bool BfModule::HasDeferredScopeCalls(BfScopeData* scope)
  10751. {
  10752. BfScopeData* checkScope = mCurMethodState->mCurScope;
  10753. while (checkScope != NULL)
  10754. {
  10755. if ((!checkScope->mDeferredCallEntries.IsEmpty()) || (!checkScope->mDeferredLifetimeEnds.empty()))
  10756. return true;
  10757. if (checkScope == scope)
  10758. break;
  10759. checkScope = checkScope->mPrevScope;
  10760. }
  10761. return false;
  10762. }
  10763. void BfModule::EmitDeferredScopeCalls(bool useSrcPositions, BfScopeData* scopeData, BfIRBlock doneBlock)
  10764. {
  10765. // Is there anything we need to do here?
  10766. if (mBfIRBuilder->mIgnoreWrites)
  10767. {
  10768. // Just visit deferred blocks
  10769. BfScopeData* checkScope = mCurMethodState->mCurScope;
  10770. while (checkScope != NULL)
  10771. {
  10772. BfDeferredCallEntry* deferredCallEntry = checkScope->mDeferredCallEntries.mHead;
  10773. while (deferredCallEntry != NULL)
  10774. {
  10775. if (deferredCallEntry->mDeferredBlock != NULL)
  10776. {
  10777. VisitEmbeddedStatement(deferredCallEntry->mDeferredBlock, NULL, BfEmbeddedStatementFlags_IsDeferredBlock);
  10778. }
  10779. deferredCallEntry = deferredCallEntry->mNext;
  10780. }
  10781. if (checkScope == scopeData)
  10782. break;
  10783. checkScope = checkScope->mPrevScope;
  10784. }
  10785. return;
  10786. }
  10787. // Why did we want to do SetIllegalSrcPos here?
  10788. // Don't we always want to step onto these instances?
  10789. // Find a case where we don't and perhaps only do it there.
  10790. // The downside was that 'EmitEnsureInstructionAt' on the end of block statements causes
  10791. // a (seemingly) unneeded NOP when we do SetIllegalSrcPos
  10792. //SetIllegalSrcPos();
  10793. bool setSrcPos = false;
  10794. bool wantsNop = true;
  10795. BfAstNode* deferCloseNode = NULL;
  10796. if (mCurMethodState->mInPostReturn)
  10797. {
  10798. // These won't get used, they are post-return
  10799. return;
  10800. }
  10801. SizedArray<BfIRValue, 8> deferredLifetimeEnds;
  10802. BfScopeData* scopeJumpBlock = NULL;
  10803. bool hadExtraDeferredLifetimeEnds = false;
  10804. auto _FlushLifetimeEnds = [&]()
  10805. {
  10806. for (auto lifetimeEnd : deferredLifetimeEnds)
  10807. {
  10808. mBfIRBuilder->CreateLifetimeEnd(lifetimeEnd);
  10809. mBfIRBuilder->ClearDebugLocation_Last();
  10810. }
  10811. deferredLifetimeEnds.clear();
  10812. };
  10813. BfScopeData* checkScope = mCurMethodState->mCurScope;
  10814. while (checkScope != NULL)
  10815. {
  10816. if (checkScope->mCloseNode != NULL)
  10817. deferCloseNode = checkScope->mCloseNode;
  10818. if (doneBlock)
  10819. {
  10820. // Try to find a match where we've already emitted these calls and then jumped to the correct block
  10821. for (auto& checkHandler : checkScope->mDeferredHandlers)
  10822. {
  10823. if (checkHandler.mDoneBlock == doneBlock)
  10824. {
  10825. scopeJumpBlock = checkScope;
  10826. mBfIRBuilder->CreateBr(checkHandler.mHandlerBlock);
  10827. mBfIRBuilder->ClearDebugLocation_Last();
  10828. _FlushLifetimeEnds();
  10829. break;
  10830. }
  10831. }
  10832. if (scopeJumpBlock != NULL)
  10833. break;
  10834. }
  10835. bool hasWork = (checkScope->mSavedStack) || (checkScope->mDeferredCallEntries.mHead != NULL);
  10836. if (checkScope != scopeData) // Only emit a block for deferred lifetimes if we're going back beyond this entry
  10837. hasWork |= (!deferredLifetimeEnds.IsEmpty());
  10838. if (hasWork)
  10839. {
  10840. SetAndRestoreValue<BfScopeData*> prevScope(mCurMethodState->mCurScope, checkScope);
  10841. if (deferCloseNode != NULL)
  10842. {
  10843. UpdateSrcPos(deferCloseNode);
  10844. }
  10845. if (doneBlock)
  10846. {
  10847. bool crossingMixin = mCurMethodState->mCurScope->mMixinDepth != checkScope->mMixinDepth;
  10848. String blockName = "deferredCalls";
  10849. //blockName += StrFormat("_%d", mBfIRBuilder->mBlockCount);
  10850. BfDeferredHandler deferredHandler;
  10851. if ((!crossingMixin) && (deferredLifetimeEnds.IsEmpty()))
  10852. {
  10853. mBfIRBuilder->SaveDebugLocation();
  10854. mBfIRBuilder->ClearDebugLocation();
  10855. deferredHandler.mHandlerBlock = mBfIRBuilder->MaybeChainNewBlock(blockName);
  10856. mBfIRBuilder->RestoreDebugLocation();
  10857. }
  10858. else
  10859. {
  10860. // Definitely chain
  10861. deferredHandler.mHandlerBlock = mBfIRBuilder->CreateBlock(blockName);
  10862. mBfIRBuilder->CreateBr(deferredHandler.mHandlerBlock);
  10863. mBfIRBuilder->ClearDebugLocation_Last();
  10864. _FlushLifetimeEnds();
  10865. mBfIRBuilder->AddBlock(deferredHandler.mHandlerBlock);
  10866. mBfIRBuilder->SetInsertPoint(deferredHandler.mHandlerBlock);
  10867. }
  10868. deferredHandler.mDoneBlock = doneBlock;
  10869. if (!mBfIRBuilder->mIgnoreWrites)
  10870. checkScope->mDeferredHandlers.push_back(deferredHandler);
  10871. if (checkScope == &mCurMethodState->mHeadScope)
  10872. {
  10873. if (!mCurMethodState->mDIRetVal)
  10874. {
  10875. // 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
  10876. // be scoped to the physical method
  10877. /*if (deferCloseNode != NULL)
  10878. {
  10879. UpdateSrcPos(deferCloseNode);
  10880. }*/
  10881. CreateDIRetVal();
  10882. }
  10883. }
  10884. if (checkScope != mCurMethodState->mTailScope)
  10885. {
  10886. if (deferredHandler.mHandlerBlock.IsFake())
  10887. {
  10888. BF_ASSERT(mBfIRBuilder->mIgnoreWrites);
  10889. }
  10890. if (!mBfIRBuilder->mIgnoreWrites)
  10891. checkScope->mAtEndBlocks.push_back(deferredHandler.mHandlerBlock);
  10892. }
  10893. }
  10894. std::unordered_set<BfDeferredCallEntry*> handledSet;
  10895. BfDeferredCallEntry* deferredCallEntry = checkScope->mDeferredCallEntries.mHead;
  10896. while (deferredCallEntry != NULL)
  10897. {
  10898. BfDeferredCallEmitState deferredCallEmitState;
  10899. deferredCallEmitState.mCloseNode = deferCloseNode;
  10900. SetAndRestoreValue<BfDeferredCallEmitState*> prevDeferredCallEmitState(mCurMethodState->mDeferredCallEmitState, &deferredCallEmitState);
  10901. SetAndRestoreValue<bool> prevIgnoredWrites(mBfIRBuilder->mIgnoreWrites, deferredCallEntry->mIgnored);
  10902. if (deferCloseNode != NULL)
  10903. {
  10904. UpdateSrcPos(deferCloseNode);
  10905. }
  10906. if (wantsNop)
  10907. EmitEnsureInstructionAt();
  10908. wantsNop = false;
  10909. if (deferredCallEntry->mDeferredBlock != NULL)
  10910. {
  10911. auto itr = handledSet.insert(deferredCallEntry);
  10912. if (!itr.second)
  10913. {
  10914. // Already handled, can happen if we defer again within the block
  10915. deferredCallEntry = deferredCallEntry->mNext;
  10916. continue;
  10917. }
  10918. auto prevHead = checkScope->mDeferredCallEntries.mHead;
  10919. EmitDeferredCall(*deferredCallEntry);
  10920. if (prevHead != checkScope->mDeferredCallEntries.mHead)
  10921. {
  10922. // The list changed, start over and ignore anything we've already handled
  10923. deferredCallEntry = checkScope->mDeferredCallEntries.mHead;
  10924. }
  10925. else
  10926. deferredCallEntry = deferredCallEntry->mNext;
  10927. }
  10928. else
  10929. {
  10930. EmitDeferredCall(*deferredCallEntry);
  10931. deferredCallEntry = deferredCallEntry->mNext;
  10932. }
  10933. }
  10934. if (checkScope->mSavedStack)
  10935. {
  10936. checkScope->mSavedStackUses.Add(mBfIRBuilder->CreateStackRestore(checkScope->mSavedStack));
  10937. if (mCurMethodState->mDynStackRevIdx)
  10938. {
  10939. auto curValue = mBfIRBuilder->CreateLoad(mCurMethodState->mDynStackRevIdx);
  10940. auto newValue = mBfIRBuilder->CreateAdd(curValue, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 1));
  10941. mBfIRBuilder->CreateStore(newValue, mCurMethodState->mDynStackRevIdx);
  10942. }
  10943. }
  10944. }
  10945. if (!checkScope->mIsScopeHead)
  10946. {
  10947. // We manually emit function-level lifetime ends after the 'ret' in ProcessMethod
  10948. if (!IsTargetingBeefBackend())
  10949. {
  10950. for (auto lifetimeEnd : checkScope->mDeferredLifetimeEnds)
  10951. {
  10952. mBfIRBuilder->CreateLifetimeEnd(lifetimeEnd);
  10953. }
  10954. }
  10955. else
  10956. {
  10957. for (auto lifetimeEnd : checkScope->mDeferredLifetimeEnds)
  10958. {
  10959. deferredLifetimeEnds.Add(lifetimeEnd);
  10960. }
  10961. }
  10962. }
  10963. if (checkScope == scopeData)
  10964. break;
  10965. checkScope = checkScope->mPrevScope;
  10966. }
  10967. if ((doneBlock) && (scopeJumpBlock == NULL))
  10968. {
  10969. mBfIRBuilder->CreateBr(doneBlock);
  10970. mBfIRBuilder->ClearDebugLocation_Last();
  10971. }
  10972. // Keeping CreateLifetimeEnds until the end messes up when we chain to old mDeferredHandlers that
  10973. // may have been created when other scope lifetimes were available
  10974. _FlushLifetimeEnds();
  10975. // Emit lifetimeEnds after the branch for Beef
  10976. /*if (IsTargetingBeefBackend())
  10977. {
  10978. bool needsEnsureInst = (!doneBlock) && (scopeJumpBlock == NULL);
  10979. BfScopeData* checkScope = mCurMethodState->mCurScope;
  10980. while (checkScope != NULL)
  10981. {
  10982. if (checkScope == scopeJumpBlock)
  10983. break;
  10984. if (!checkScope->mIsScopeHead)
  10985. {
  10986. for (auto lifetimeEnd : checkScope->mDeferredLifetimeEnds)
  10987. {
  10988. if (needsEnsureInst)
  10989. {
  10990. needsEnsureInst = false;
  10991. }
  10992. mBfIRBuilder->CreateLifetimeEnd(lifetimeEnd);
  10993. }
  10994. }
  10995. if (checkScope == scopeData)
  10996. break;
  10997. checkScope = checkScope->mPrevScope;
  10998. }
  10999. }*/
  11000. }
  11001. void BfModule::MarkScopeLeft(BfScopeData* scopeData)
  11002. {
  11003. if (mCurMethodState->mDeferredLocalAssignData != NULL)
  11004. {
  11005. auto deferredLocalAssignData = mCurMethodState->mDeferredLocalAssignData;
  11006. while (deferredLocalAssignData != NULL)
  11007. {
  11008. if ((deferredLocalAssignData->mScopeData == NULL) || (deferredLocalAssignData->mScopeData->mScopeDepth < scopeData->mScopeDepth))
  11009. break;
  11010. if ((deferredLocalAssignData->mScopeData != NULL) && (deferredLocalAssignData->mScopeData->mScopeDepth == scopeData->mScopeDepth))
  11011. deferredLocalAssignData->mIsUnconditional = false;
  11012. deferredLocalAssignData = deferredLocalAssignData->mChainedAssignData;
  11013. }
  11014. }
  11015. //for (int localIdx = scopeData->mLocalVarStart; localIdx < (int)mCurMethodState->mLocals.size(); localIdx++)
  11016. // We mark all unassigned variables as assigned now, for avoiding "may be unassigned" usage cases like:
  11017. // int b;
  11018. // if (cond) return;
  11019. // else b = 1;
  11020. // Use(b);
  11021. for (int localIdx = 0; localIdx < (int)mCurMethodState->mLocals.size(); localIdx++)
  11022. {
  11023. auto localDef = mCurMethodState->mLocals[localIdx];
  11024. if ((!localDef->mIsAssigned) && (!localDef->IsParam()))
  11025. mCurMethodState->LocalDefined(localDef);
  11026. }
  11027. }
  11028. void BfModule::CreateReturn(BfIRValue val)
  11029. {
  11030. if (mCurMethodInstance->mReturnType->IsComposite())
  11031. {
  11032. // Store to sret
  11033. BF_ASSERT(val);
  11034. mBfIRBuilder->CreateStore(val, mBfIRBuilder->GetArgument(0));
  11035. mBfIRBuilder->CreateRetVoid();
  11036. }
  11037. else
  11038. {
  11039. if (mCurMethodInstance->mReturnType->IsValuelessType())
  11040. {
  11041. mBfIRBuilder->CreateRetVoid();
  11042. }
  11043. else
  11044. {
  11045. BF_ASSERT(val);
  11046. mBfIRBuilder->CreateRet(val);
  11047. }
  11048. }
  11049. }
  11050. void BfModule::EmitReturn(BfIRValue val)
  11051. {
  11052. if (mCurMethodState->mIRExitBlock)
  11053. {
  11054. if (!mCurMethodInstance->mReturnType->IsValuelessType())
  11055. {
  11056. if (val) // We allow for val to be empty if we know we've already written the value to mRetVal
  11057. {
  11058. BfIRValue retVal = mCurMethodState->mRetVal.mValue;
  11059. if (!mCurMethodState->mRetVal)
  11060. retVal = mBfIRBuilder->CreateLoad(mCurMethodState->mRetValAddr);
  11061. mBfIRBuilder->CreateStore(val, retVal);
  11062. }
  11063. }
  11064. EmitDeferredScopeCalls(true, NULL, mCurMethodState->mIRExitBlock);
  11065. }
  11066. else
  11067. {
  11068. EmitDeferredScopeCalls(false, NULL);
  11069. if (mCurMethodInstance->mReturnType->IsValuelessType())
  11070. mBfIRBuilder->CreateRetVoid();
  11071. else
  11072. mBfIRBuilder->CreateRet(val);
  11073. }
  11074. mCurMethodState->SetHadReturn(true);
  11075. mCurMethodState->mLeftBlockUncond = true;
  11076. }
  11077. void BfModule::EmitDefaultReturn()
  11078. {
  11079. if (mCurMethodState->mInDeferredBlock)
  11080. return;
  11081. if (mCurMethodState->mIRExitBlock)
  11082. {
  11083. EmitDeferredScopeCalls(true, NULL, mCurMethodState->mIRExitBlock);
  11084. }
  11085. else
  11086. {
  11087. if (mCurMethodInstance->mReturnType->IsVoid())
  11088. mBfIRBuilder->CreateRetVoid();
  11089. else
  11090. mBfIRBuilder->CreateRet(GetDefaultValue(mCurMethodInstance->mReturnType));
  11091. }
  11092. mCurMethodState->SetHadReturn(true);
  11093. mCurMethodState->mLeftBlockUncond = true;
  11094. }
  11095. void BfModule::AssertErrorState()
  11096. {
  11097. if (mIgnoreErrors)
  11098. return;
  11099. if (mHadBuildError)
  11100. return;
  11101. if (mCurTypeInstance != NULL)
  11102. {
  11103. if (mCurTypeInstance->IsUnspecializedTypeVariation())
  11104. return;
  11105. }
  11106. if (mCurMethodInstance != NULL)
  11107. {
  11108. if (mCurMethodInstance->mIsUnspecializedVariation)
  11109. return;
  11110. }
  11111. // We want the module to be marked as failed even if it's just an error in the parser
  11112. if (mCurMethodInstance != NULL)
  11113. mCurMethodInstance->mHasFailed = true;
  11114. mHadBuildError = true;
  11115. // We check for either the parsing to have failed (possibly on a previous run), or for the current instance to have failed
  11116. if (mCurTypeInstance != NULL)
  11117. {
  11118. if (mCurTypeInstance->mTypeFailed)
  11119. return;
  11120. if (mCurTypeInstance->mTypeDef->mSource->mParsingFailed)
  11121. return;
  11122. }
  11123. if (mCurMethodInstance != NULL)
  11124. {
  11125. if ((mCurMethodInstance->mMethodDef->mDeclaringType != NULL) && (mCurMethodInstance->mMethodDef->mDeclaringType->mSource->mParsingFailed))
  11126. return;
  11127. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL) && (mCurMethodState->mMixinState->mMixinMethodInstance->mMethodDef->mDeclaringType->mSource->mParsingFailed))
  11128. return;
  11129. }
  11130. BF_ASSERT(mCompiler->mPassInstance->HasFailed());
  11131. }
  11132. void BfModule::AssertParseErrorState()
  11133. {
  11134. if (mCompiler->mRevision == 1)
  11135. AssertErrorState();
  11136. }
  11137. BfType* BfModule::GetDelegateReturnType(BfType* delegateType)
  11138. {
  11139. BF_ASSERT(delegateType->IsDelegate());
  11140. auto typeInst = delegateType->ToTypeInstance();
  11141. PopulateType(typeInst, BfPopulateType_DataAndMethods);
  11142. BfMethodInstance* invokeMethodInstance = GetRawMethodInstanceAtIdx(typeInst->ToTypeInstance(), 0, "Invoke");
  11143. return invokeMethodInstance->mReturnType;
  11144. }
  11145. BfMethodInstance* BfModule::GetDelegateInvokeMethod(BfTypeInstance* typeInstance)
  11146. {
  11147. return GetRawMethodInstanceAtIdx(typeInstance, 0, "Invoke");
  11148. }
  11149. void BfModule::CreateDelegateInvokeMethod()
  11150. {
  11151. // Clear out debug loc - otherwise we'll single step onto the delegate type declaration
  11152. //mBfIRBuilder->ClearDebugLocation();
  11153. SetIllegalSrcPos();
  11154. auto typeInstance = mCurTypeInstance;
  11155. auto memberFuncType = mBfIRBuilder->MapMethod(mCurMethodInstance);
  11156. SizedArray<BfIRType, 4> staticParamTypes;
  11157. SizedArray<BfIRValue, 4> staticFuncArgs;
  11158. SizedArray<BfIRValue, 4> memberFuncArgs;
  11159. auto multicastDelegateType = typeInstance->mBaseType;
  11160. if (multicastDelegateType->mFieldInstances.size() != 2)
  11161. {
  11162. AssertErrorState();
  11163. return;
  11164. }
  11165. auto multicastDelegate = mBfIRBuilder->CreateBitCast(mCurMethodState->mLocals[0]->mValue, mBfIRBuilder->MapType(multicastDelegateType));
  11166. auto fieldPtr = mBfIRBuilder->CreateInBoundsGEP(multicastDelegate, 0, 2); // Load 'delegate.mTarget'
  11167. auto fieldVal = mBfIRBuilder->CreateLoad(fieldPtr);
  11168. BfExprEvaluator exprEvaluator(this);
  11169. SizedArray<BfIRType, 8> origParamTypes;
  11170. BfIRType origReturnType;
  11171. mCurMethodInstance->GetIRFunctionInfo(this, origReturnType, origParamTypes);
  11172. if (mCurMethodInstance->mReturnType->IsValueType())
  11173. mBfIRBuilder->PopulateType(mCurMethodInstance->mReturnType, BfIRPopulateType_Full);
  11174. int thisIdx = 0;
  11175. if (mCurMethodInstance->HasStructRet())
  11176. {
  11177. thisIdx = 1;
  11178. staticFuncArgs.push_back(mBfIRBuilder->GetArgument(0));
  11179. memberFuncArgs.push_back(mBfIRBuilder->GetArgument(0));
  11180. }
  11181. memberFuncArgs.push_back(BfIRValue()); // Push 'target'
  11182. mCurMethodInstance->GetIRFunctionInfo(this, origReturnType, staticParamTypes, true);
  11183. for (int i = 1; i < (int)mCurMethodState->mLocals.size(); i++)
  11184. {
  11185. BfTypedValue localVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[i], true);
  11186. exprEvaluator.PushArg(localVal, staticFuncArgs);
  11187. exprEvaluator.PushArg(localVal, memberFuncArgs);
  11188. }
  11189. auto staticFunc = mBfIRBuilder->CreateFunctionType(origReturnType, staticParamTypes, false);
  11190. auto staticFuncPtr = mBfIRBuilder->GetPointerTo(staticFunc);
  11191. auto staticFuncPtrPtr = mBfIRBuilder->GetPointerTo(staticFuncPtr);
  11192. auto trueBB = mBfIRBuilder->CreateBlock("if.then", true);
  11193. auto falseBB = mBfIRBuilder->CreateBlock("if.else");
  11194. auto doneBB = mBfIRBuilder->CreateBlock("done");
  11195. auto checkTargetNull = mBfIRBuilder->CreateIsNotNull(fieldVal);
  11196. mBfIRBuilder->CreateCondBr(checkTargetNull, trueBB, falseBB);
  11197. BfIRValue nonStaticResult;
  11198. BfIRValue staticResult;
  11199. auto callingConv = GetCallingConvention(mCurTypeInstance, mCurMethodInstance->mMethodDef);
  11200. /// Non-static invocation
  11201. {
  11202. auto memberFuncPtr = mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapMethod(mCurMethodInstance));
  11203. auto memberFuncPtrPtr = mBfIRBuilder->GetPointerTo(memberFuncPtr);
  11204. mBfIRBuilder->SetInsertPoint(trueBB);
  11205. memberFuncArgs[thisIdx] = mBfIRBuilder->CreateBitCast(fieldVal, mBfIRBuilder->MapType(mCurTypeInstance));
  11206. auto fieldPtr = mBfIRBuilder->CreateInBoundsGEP(multicastDelegate, 0, 1); // Load 'delegate.mFuncPtr'
  11207. auto funcPtrPtr = mBfIRBuilder->CreateBitCast(fieldPtr, memberFuncPtrPtr);
  11208. auto funcPtr = mBfIRBuilder->CreateLoad(funcPtrPtr);
  11209. nonStaticResult = mBfIRBuilder->CreateCall(funcPtr, memberFuncArgs);
  11210. if (callingConv != BfIRCallingConv_CDecl)
  11211. mBfIRBuilder->SetCallCallingConv(nonStaticResult, callingConv);
  11212. mCurMethodState->SetHadReturn(false);
  11213. mCurMethodState->mLeftBlockUncond = false;
  11214. mCurMethodState->mLeftBlockCond = false;
  11215. mBfIRBuilder->CreateBr(doneBB);
  11216. }
  11217. // Static invocation
  11218. {
  11219. mBfIRBuilder->AddBlock(falseBB);
  11220. mBfIRBuilder->SetInsertPoint(falseBB);
  11221. auto fieldPtr = mBfIRBuilder->CreateInBoundsGEP(multicastDelegate, 0, 1); // Load 'delegate.mFuncPtr'
  11222. auto funcPtrPtr = mBfIRBuilder->CreateBitCast(fieldPtr, staticFuncPtrPtr);
  11223. auto funcPtr = mBfIRBuilder->CreateLoad(funcPtrPtr);
  11224. staticResult = mBfIRBuilder->CreateCall(funcPtr, staticFuncArgs);
  11225. if (callingConv == BfIRCallingConv_ThisCall)
  11226. callingConv = BfIRCallingConv_CDecl;
  11227. if (callingConv != BfIRCallingConv_CDecl)
  11228. mBfIRBuilder->SetCallCallingConv(staticResult, callingConv);
  11229. // if (!mSystem->IsCompatibleCallingConvention(BfCallingConvention_Unspecified, mCurMethodInstance->mMethodDef->mCallingConvention))
  11230. // {
  11231. // if (mCurMethodInstance->mMethodDef->mCallingConvention == BfCallingConvention_Stdcall)
  11232. //
  11233. // }
  11234. mCurMethodState->SetHadReturn(false);
  11235. mCurMethodState->mLeftBlockUncond = false;
  11236. mCurMethodState->mLeftBlockCond = false;
  11237. mBfIRBuilder->CreateBr(doneBB);
  11238. }
  11239. mBfIRBuilder->AddBlock(doneBB);
  11240. mBfIRBuilder->SetInsertPoint(doneBB);
  11241. if ((mCurMethodInstance->mReturnType->IsValuelessType()) || (mCurMethodInstance->HasStructRet()))
  11242. {
  11243. mBfIRBuilder->CreateRetVoid();
  11244. }
  11245. else
  11246. {
  11247. auto phi = mBfIRBuilder->CreatePhi(mBfIRBuilder->MapType(mCurMethodInstance->mReturnType), 2);
  11248. mBfIRBuilder->AddPhiIncoming(phi, nonStaticResult, trueBB);
  11249. mBfIRBuilder->AddPhiIncoming(phi, staticResult, falseBB);
  11250. mBfIRBuilder->CreateRet(phi);
  11251. }
  11252. }
  11253. // "Interested" here means every method for a normal compile, and just the method the cursor is on for autocompletion
  11254. bool BfModule::IsInterestedInMethod(BfTypeInstance* typeInstance, BfMethodDef* methodDef)
  11255. {
  11256. auto typeDef = typeInstance->mTypeDef;
  11257. auto methodDeclaration = methodDef->mMethodDeclaration;
  11258. if (!mCompiler->mIsResolveOnly)
  11259. return true;
  11260. if (typeInstance->IsGenericTypeInstance())
  11261. {
  11262. // We only really want to process the unspecialized type for autocompletion
  11263. if ((!typeInstance->IsUnspecializedType()) || (typeInstance->IsUnspecializedTypeVariation()))
  11264. return false;
  11265. }
  11266. BfAstNode* checkNode = methodDeclaration;
  11267. if (methodDeclaration == NULL)
  11268. checkNode = methodDef->mBody;
  11269. if ((mCompiler->mResolvePassData->mParser != NULL) && (typeDef->mTypeDeclaration->IsFromParser(mCompiler->mResolvePassData->mParser)))
  11270. {
  11271. if (mCompiler->mResolvePassData->mAutoComplete == NULL)
  11272. return true;
  11273. }
  11274. return false;
  11275. }
  11276. void BfModule::CalcAppendAlign(BfMethodInstance* methodInst)
  11277. {
  11278. methodInst->mAppendAllocAlign = 1;
  11279. }
  11280. BfTypedValue BfModule::TryConstCalcAppend(BfMethodInstance* methodInst, SizedArrayImpl<BfIRValue>& args)
  11281. {
  11282. BP_ZONE("BfModule::TryConstCalcAppend");
  11283. if (mCompiler->mIsResolveOnly)
  11284. return BfTypedValue();
  11285. // We want to regenerate all ctor calls when the method internals change
  11286. {
  11287. auto checkTypeInst = methodInst->GetOwner();
  11288. while (checkTypeInst->mTypeDef->mHasAppendCtor)
  11289. {
  11290. AddDependency(checkTypeInst, mCurTypeInstance, BfDependencyMap::DependencyFlag_InlinedCall);
  11291. checkTypeInst = GetBaseType(checkTypeInst);
  11292. }
  11293. }
  11294. if (!methodInst->mMayBeConst)
  11295. return BfTypedValue();
  11296. // Do we need to iterate in order to resolve mAppendAllocAlign?
  11297. bool isFirstRun = methodInst->mAppendAllocAlign < 0;
  11298. bool wasAllConst = true;
  11299. int argIdx = 0;
  11300. int paramIdx = 0;
  11301. while (true)
  11302. {
  11303. if (argIdx >= (int)args.size())
  11304. break;
  11305. auto paramType = methodInst->GetParamType(paramIdx);
  11306. PopulateType(paramType);
  11307. int argCount = 0;
  11308. if (!paramType->IsValuelessType())
  11309. {
  11310. if (methodInst->GetParamIsSplat(paramIdx))
  11311. argCount = paramType->GetSplatCount();
  11312. else
  11313. argCount = 1;
  11314. for (int argOfs = 0; argOfs < argCount; argOfs++)
  11315. {
  11316. auto arg = args[argIdx + argOfs];
  11317. if (!arg.IsConst())
  11318. {
  11319. wasAllConst = false;
  11320. if (!isFirstRun)
  11321. {
  11322. auto& param = methodInst->mParams[argIdx];
  11323. if (param.mReferencedInConstPass)
  11324. {
  11325. // If this param is required as part of the const calculation then
  11326. // we require that it be const...
  11327. return BfTypedValue();
  11328. }
  11329. }
  11330. }
  11331. }
  11332. }
  11333. paramIdx++;
  11334. argIdx += argCount;
  11335. }
  11336. auto methodDef = methodInst->mMethodDef;
  11337. auto methodDecl = methodDef->GetMethodDeclaration();
  11338. auto methodDeclBlock = BfNodeDynCast<BfBlock>(methodDecl->mBody);
  11339. if (methodDeclBlock == NULL)
  11340. return BfTypedValue();
  11341. BfTypedValue constValue;
  11342. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  11343. auto checkState = mCurMethodState->mConstResolveState;
  11344. while (checkState != NULL)
  11345. {
  11346. if (checkState->mMethodInstance == methodInst)
  11347. {
  11348. return BfTypedValue();
  11349. }
  11350. checkState = checkState->mPrevConstResolveState;
  11351. }
  11352. //auto accumValue = GetConstValue(0);
  11353. bool failed = false;
  11354. //
  11355. {
  11356. BfConstResolveState constResolveState;
  11357. constResolveState.mMethodInstance = methodInst;
  11358. constResolveState.mPrevConstResolveState = mCurMethodState->mConstResolveState;
  11359. SetAndRestoreValue<bool> ignoreWrites(mBfIRBuilder->mIgnoreWrites, true);
  11360. BfMethodState methodState;
  11361. SetAndRestoreValue<BfTypeInstance*> prevTypeInst(mCurTypeInstance, methodInst->GetOwner());
  11362. SetAndRestoreValue<BfMethodInstance*> prevMethodInst(mCurMethodInstance, methodInst);
  11363. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  11364. methodState.mTempKind = BfMethodState::TempKind_NonStatic;
  11365. methodState.mConstResolveState = &constResolveState;
  11366. int argIdx = 0;
  11367. for (int paramIdx = 0; paramIdx < methodInst->GetParamCount(); paramIdx++)
  11368. {
  11369. if (methodInst->GetParamKind(paramIdx) == BfParamKind_AppendIdx)
  11370. continue;
  11371. auto paramType = methodInst->GetParamType(paramIdx);
  11372. // Fix this after we allow structs to be consts
  11373. //BF_ASSERT(!paramType->IsSplattable());
  11374. BfLocalVariable* localVar = new BfLocalVariable();
  11375. localVar->mName = methodInst->GetParamName(paramIdx);
  11376. localVar->mResolvedType = paramType;
  11377. localVar->mConstValue = args[argIdx];
  11378. localVar->mParamIdx = paramIdx;
  11379. AddLocalVariableDef(localVar);
  11380. argIdx++;
  11381. }
  11382. AppendAllocVisitor appendAllocVisitor;
  11383. appendAllocVisitor.mConstAccum = GetDefaultTypedValue(GetPrimitiveType(BfTypeCode_IntPtr));
  11384. appendAllocVisitor.mIsFirstConstPass = isFirstRun;
  11385. BfTypedValue baseCtorAppendValue = CallBaseCtorCalc(true);
  11386. if (baseCtorAppendValue)
  11387. {
  11388. if (baseCtorAppendValue.mValue.IsFake())
  11389. appendAllocVisitor.mFailed = true;
  11390. else
  11391. appendAllocVisitor.mConstAccum = baseCtorAppendValue;
  11392. }
  11393. appendAllocVisitor.mModule = this;
  11394. appendAllocVisitor.VisitChild(methodDecl->mBody);
  11395. if (!appendAllocVisitor.mFailed)
  11396. constValue = appendAllocVisitor.mConstAccum;
  11397. if (isFirstRun)
  11398. mCurMethodInstance->mEndingAppendAllocAlign = appendAllocVisitor.mCurAppendAlign;
  11399. if (isFirstRun)
  11400. {
  11401. for (int paramIdx = 0; paramIdx < methodInst->GetParamCount(); paramIdx++)
  11402. {
  11403. auto localVar = mCurMethodState->mLocals[paramIdx];
  11404. if (localVar->mReadFromId != -1)
  11405. {
  11406. auto& param = methodInst->mParams[paramIdx];
  11407. param.mReferencedInConstPass = true;
  11408. }
  11409. }
  11410. }
  11411. }
  11412. mBfIRBuilder->SetInsertPoint(prevBlock);
  11413. if (!constValue)
  11414. {
  11415. // If we did a 'force' then some params may not have been const -- only clear mMayBeConst if we had
  11416. // all-const args
  11417. if (wasAllConst)
  11418. {
  11419. methodInst->mMayBeConst = false;
  11420. }
  11421. }
  11422. return constValue;
  11423. }
  11424. BfTypedValue BfModule::CallBaseCtorCalc(bool constOnly)
  11425. {
  11426. // Any errors should only be shown in the actual CTOR call
  11427. SetAndRestoreValue<bool> prevIgnoreWrites(mIgnoreErrors, true);
  11428. auto methodDef = mCurMethodInstance->mMethodDef;
  11429. BF_ASSERT((methodDef->mMethodType == BfMethodType_Ctor) || (methodDef->mMethodType == BfMethodType_CtorCalcAppend));
  11430. auto ctorDeclaration = (BfConstructorDeclaration*)methodDef->mMethodDeclaration;
  11431. BfTypeInstance* targetType = NULL;
  11432. if (ctorDeclaration->mInitializer != NULL)
  11433. {
  11434. auto targetToken = BfNodeDynCast<BfTokenNode>(ctorDeclaration->mInitializer->mTarget);
  11435. targetType = (targetToken->GetToken() == BfToken_This) ? mCurTypeInstance : mCurTypeInstance->mBaseType;
  11436. }
  11437. else
  11438. targetType = mCurTypeInstance->mBaseType;
  11439. if ((targetType == NULL) || (targetType == mContext->mBfObjectType))
  11440. return NULL;
  11441. auto targetRefNode = methodDef->GetRefNode();
  11442. BfType* targetThisType = targetType;
  11443. BfTypedValue target(mBfIRBuilder->GetFakeVal(), targetThisType);
  11444. BfExprEvaluator exprEvaluator(this);
  11445. BfResolvedArgs argValues;
  11446. if ((ctorDeclaration != NULL) && (ctorDeclaration->mInitializer != NULL))
  11447. {
  11448. argValues.Init(&ctorDeclaration->mInitializer->mArguments);
  11449. }
  11450. //
  11451. {
  11452. }
  11453. BfFunctionBindResult bindResult;
  11454. bindResult.mSkipThis = true;
  11455. bindResult.mWantsArgs = true;
  11456. {
  11457. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, true);
  11458. exprEvaluator.ResolveArgValues(argValues, BfResolveArgFlag_DeferParamEval);
  11459. SetAndRestoreValue<BfFunctionBindResult*> prevBindResult(exprEvaluator.mFunctionBindResult, &bindResult);
  11460. exprEvaluator.MatchConstructor(targetRefNode, NULL, target, targetType, argValues, true, true);
  11461. }
  11462. if (bindResult.mMethodInstance == NULL)
  11463. {
  11464. AssertErrorState();
  11465. return BfTypedValue();
  11466. }
  11467. if (!bindResult.mMethodInstance->mMethodDef->mHasAppend)
  11468. {
  11469. return BfTypedValue();
  11470. }
  11471. BF_ASSERT(bindResult.mIRArgs[0].IsFake());
  11472. bindResult.mIRArgs.RemoveAt(0);
  11473. auto calcAppendMethodModule = GetMethodInstanceAtIdx(bindResult.mMethodInstance->GetOwner(), bindResult.mMethodInstance->mMethodDef->mIdx + 1, BF_METHODNAME_CALCAPPEND);
  11474. BfTypedValue appendSizeTypedValue = TryConstCalcAppend(calcAppendMethodModule.mMethodInstance, bindResult.mIRArgs);
  11475. BF_ASSERT(calcAppendMethodModule.mMethodInstance->mAppendAllocAlign >= 0);
  11476. mCurMethodInstance->mAppendAllocAlign = BF_MAX((int)mCurMethodInstance->mAppendAllocAlign, calcAppendMethodModule.mMethodInstance->mAppendAllocAlign);
  11477. BF_ASSERT(calcAppendMethodModule.mMethodInstance->mEndingAppendAllocAlign > -1);
  11478. mCurMethodState->mCurAppendAlign = BF_MAX(calcAppendMethodModule.mMethodInstance->mEndingAppendAllocAlign, 0);
  11479. if (appendSizeTypedValue)
  11480. return appendSizeTypedValue;
  11481. if (constOnly)
  11482. return BfTypedValue(mBfIRBuilder->GetFakeVal(), GetPrimitiveType(BfTypeCode_IntPtr));
  11483. bool needsRecalc = false;
  11484. for (auto irArg : bindResult.mIRArgs)
  11485. {
  11486. if (irArg.IsFake())
  11487. needsRecalc = true;
  11488. }
  11489. auto calcAppendArgs = bindResult.mIRArgs;
  11490. if (needsRecalc)
  11491. {
  11492. // Do it again, but without mIgnoreWrites set
  11493. BfResolvedArgs argValues;
  11494. argValues.Init(&ctorDeclaration->mInitializer->mArguments);
  11495. exprEvaluator.ResolveArgValues(argValues, BfResolveArgFlag_DeferParamEval);
  11496. BfFunctionBindResult bindResult;
  11497. bindResult.mSkipThis = true;
  11498. bindResult.mWantsArgs = true;
  11499. SetAndRestoreValue<BfFunctionBindResult*> prevBindResult(exprEvaluator.mFunctionBindResult, &bindResult);
  11500. exprEvaluator.MatchConstructor(targetRefNode, NULL, target, targetType, argValues, true, true);
  11501. BF_ASSERT(bindResult.mIRArgs[0].IsFake());
  11502. bindResult.mIRArgs.RemoveAt(0);
  11503. calcAppendArgs = bindResult.mIRArgs;
  11504. }
  11505. BF_ASSERT(calcAppendMethodModule.mFunc);
  11506. appendSizeTypedValue = exprEvaluator.CreateCall(calcAppendMethodModule.mMethodInstance, calcAppendMethodModule.mFunc, false, calcAppendArgs);
  11507. BF_ASSERT(appendSizeTypedValue.mType == GetPrimitiveType(BfTypeCode_IntPtr));
  11508. return appendSizeTypedValue;
  11509. }
  11510. // This method never throws errors - it relies on the proper ctor actually throwing the errors
  11511. void BfModule::EmitCtorCalcAppend()
  11512. {
  11513. if (mCompiler->mIsResolveOnly)
  11514. return;
  11515. auto methodDef = mCurMethodInstance->mMethodDef;
  11516. auto methodDecl = methodDef->GetMethodDeclaration();
  11517. Array<BfAstNode*> deferredNodeList;
  11518. auto methodDeclBlock = BfNodeDynCast<BfBlock>(methodDecl->mBody);
  11519. if (methodDeclBlock == NULL)
  11520. return;
  11521. AppendAllocVisitor appendAllocVisitor;
  11522. auto baseCalcAppend = CallBaseCtorCalc(false);
  11523. if (baseCalcAppend)
  11524. {
  11525. mBfIRBuilder->CreateStore(baseCalcAppend.mValue, mCurMethodState->mRetVal.mValue);
  11526. }
  11527. appendAllocVisitor.mModule = this;
  11528. appendAllocVisitor.VisitChild(methodDecl->mBody);
  11529. }
  11530. void BfModule::CreateStaticCtor()
  11531. {
  11532. auto typeDef = mCurTypeInstance->mTypeDef;
  11533. auto methodDef = mCurMethodInstance->mMethodDef;
  11534. BfIRBlock exitBB;
  11535. if ((HasCompiledOutput()) && (!mCurMethodInstance->mIsUnspecialized) && (mCurMethodInstance->mChainType != BfMethodChainType_ChainMember))
  11536. {
  11537. auto boolType = GetPrimitiveType(BfTypeCode_Boolean);
  11538. auto didStaticInitVarAddr = mBfIRBuilder->CreateGlobalVariable(
  11539. mBfIRBuilder->MapType(boolType),
  11540. false,
  11541. BfIRLinkageType_Internal,
  11542. GetDefaultValue(boolType),
  11543. "didStaticInit");
  11544. auto initBB = mBfIRBuilder->CreateBlock("init", true);
  11545. mCurMethodState->mIRExitBlock = mBfIRBuilder->CreateBlock("exit", true);
  11546. auto didStaticInitVar = mBfIRBuilder->CreateLoad(didStaticInitVarAddr);
  11547. mBfIRBuilder->CreateCondBr(didStaticInitVar, mCurMethodState->mIRExitBlock, initBB);
  11548. mBfIRBuilder->SetInsertPoint(initBB);
  11549. mBfIRBuilder->CreateStore(GetConstValue(1, boolType), didStaticInitVarAddr);
  11550. }
  11551. // Do DLL imports
  11552. if (!mDllImportEntries.empty())
  11553. {
  11554. auto internalType = ResolveTypeDef(mCompiler->mInternalTypeDef);
  11555. PopulateType(internalType);
  11556. auto getSharedProcAddressInstance = GetMethodByName(internalType->ToTypeInstance(), "GetSharedProcAddress");
  11557. if (!getSharedProcAddressInstance)
  11558. {
  11559. if (!mCompiler->mPassInstance->HasFailed())
  11560. Fail("Internal error: System.Internal doesn't contain LoadSharedLibrary method");
  11561. }
  11562. }
  11563. // Fill in initializer values
  11564. if ((!mCompiler->mIsResolveOnly) || (mCompiler->mResolvePassData->mAutoComplete == NULL))
  11565. {
  11566. for (auto fieldDef : typeDef->mFields)
  11567. {
  11568. if ((!fieldDef->mIsConst) && (fieldDef->mIsStatic) && (fieldDef->mInitializer != NULL))
  11569. {
  11570. // For extensions, only handle these fields in the appropriate extension
  11571. if ((fieldDef->mDeclaringType->mTypeDeclaration != methodDef->mDeclaringType->mTypeDeclaration))
  11572. continue;
  11573. UpdateSrcPos(fieldDef->mInitializer);
  11574. auto fieldInst = &mCurTypeInstance->mFieldInstances[fieldDef->mIdx];
  11575. if (!fieldInst->mFieldIncluded)
  11576. continue;
  11577. if (fieldInst->mResolvedType->IsVar())
  11578. {
  11579. continue;
  11580. }
  11581. auto assignValue = GetFieldInitializerValue(fieldInst);
  11582. if (assignValue)
  11583. {
  11584. assignValue = LoadValue(assignValue);
  11585. if (!assignValue.mType->IsValuelessType())
  11586. {
  11587. auto staticVarRef = ReferenceStaticField(fieldInst).mValue;
  11588. mBfIRBuilder->CreateStore(assignValue.mValue, staticVarRef);
  11589. }
  11590. }
  11591. }
  11592. }
  11593. }
  11594. else
  11595. {
  11596. for (auto tempTypeDef : mCompiler->mResolvePassData->mAutoCompleteTempTypes)
  11597. {
  11598. if (tempTypeDef->mFullName == typeDef->mFullName)
  11599. {
  11600. for (auto fieldDef : tempTypeDef->mFields)
  11601. {
  11602. if ((fieldDef->mIsStatic) && (!fieldDef->mIsConst))
  11603. {
  11604. if (fieldDef->mInitializer != NULL)
  11605. {
  11606. if (mCompiler->mResolvePassData->mSourceClassifier != NULL)
  11607. {
  11608. mCompiler->mResolvePassData->mSourceClassifier->SetElementType(fieldDef->mInitializer, BfSourceElementType_Normal);
  11609. mCompiler->mResolvePassData->mSourceClassifier->VisitChild(fieldDef->mInitializer);
  11610. }
  11611. BfType* wantType = NULL;
  11612. if ((!BfNodeIsA<BfVarTypeReference>(fieldDef->mTypeRef)) && (!BfNodeIsA<BfLetTypeReference>(fieldDef->mTypeRef)))
  11613. {
  11614. wantType = ResolveTypeRef(fieldDef->mTypeRef);
  11615. }
  11616. CreateValueFromExpression(fieldDef->mInitializer, wantType, BfEvalExprFlags_FieldInitializer);
  11617. }
  11618. }
  11619. }
  11620. }
  11621. }
  11622. }
  11623. if (mCurMethodInstance->mChainType == BfMethodChainType_ChainHead)
  11624. CallChainedMethods(mCurMethodInstance, false);
  11625. }
  11626. void BfModule::EmitDtorBody()
  11627. {
  11628. if (mCurTypeInstance->IsClosure())
  11629. {
  11630. BfFieldInstance* fieldInstance = &mCurTypeInstance->mFieldInstances.back();
  11631. BF_ASSERT(fieldInstance->GetFieldDef()->mName == "__dtorThunk");
  11632. auto thisVal = GetThis();
  11633. auto dtorThunkPtr = mBfIRBuilder->CreateInBoundsGEP(thisVal.mValue, 0, fieldInstance->mDataIdx);
  11634. auto dtorThunk = mBfIRBuilder->CreateLoad(dtorThunkPtr);
  11635. auto funcPtrType = mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapMethod(mCurMethodInstance));
  11636. auto dtorPtr = mBfIRBuilder->CreateBitCast(dtorThunk, funcPtrType);
  11637. SizedArray<BfIRValue, 1> args;
  11638. args.push_back(thisVal.mValue);
  11639. auto result = mBfIRBuilder->CreateCall(dtorPtr, args);
  11640. mBfIRBuilder->SetCallCallingConv(result, BfIRCallingConv_CDecl);
  11641. // Fall through to Object::~this call
  11642. auto dtorFunc = GetMethodByName(mContext->mBfObjectType, "~this");
  11643. auto basePtr = mBfIRBuilder->CreateBitCast(thisVal.mValue, mBfIRBuilder->MapTypeInstPtr(mContext->mBfObjectType));
  11644. SizedArray<BfIRValue, 1> vals = { basePtr };
  11645. result = mBfIRBuilder->CreateCall(dtorFunc.mFunc, vals);
  11646. mBfIRBuilder->SetCallCallingConv(result, GetCallingConvention(dtorFunc.mMethodInstance));
  11647. mBfIRBuilder->SetTailCall(result);
  11648. return;
  11649. }
  11650. auto typeDef = mCurTypeInstance->mTypeDef;
  11651. auto methodDef = mCurMethodInstance->mMethodDef;
  11652. auto methodDeclaration = methodDef->GetMethodDeclaration();
  11653. if (mCurMethodInstance->mChainType == BfMethodChainType_ChainHead)
  11654. CallChainedMethods(mCurMethodInstance, true);
  11655. if (auto bodyBlock = BfNodeDynCast<BfBlock>(methodDef->mBody))
  11656. {
  11657. VisitCodeBlock(bodyBlock);
  11658. if (bodyBlock->mCloseBrace != NULL)
  11659. {
  11660. UpdateSrcPos(bodyBlock->mCloseBrace);
  11661. }
  11662. }
  11663. else
  11664. {
  11665. if (methodDeclaration != NULL)
  11666. UpdateSrcPos(methodDeclaration);
  11667. else if (typeDef->mTypeDeclaration != NULL)
  11668. UpdateSrcPos(typeDef->mTypeDeclaration);
  11669. if ((methodDeclaration != NULL) && (methodDeclaration->mFatArrowToken != NULL))
  11670. {
  11671. Fail("Destructors cannot have expression bodies", methodDeclaration->mFatArrowToken);
  11672. }
  11673. }
  11674. if ((!mCompiler->mIsResolveOnly) || (mCompiler->mResolvePassData->mAutoComplete == NULL))
  11675. {
  11676. for (int fieldIdx = (int)mCurTypeInstance->mFieldInstances.size() - 1; fieldIdx >= 0; fieldIdx--)
  11677. {
  11678. auto fieldInst = &mCurTypeInstance->mFieldInstances[fieldIdx];
  11679. auto fieldDef = fieldInst->GetFieldDef();
  11680. if ((fieldDef != NULL) && (fieldDef->mIsStatic == methodDef->mIsStatic) && (fieldDef->mFieldDeclaration != NULL) && (fieldDef->mFieldDeclaration->mFieldDtor != NULL))
  11681. {
  11682. if ((!methodDef->mIsStatic) && (mCurTypeInstance->IsValueType()))
  11683. {
  11684. Fail("Structs cannot have field destructors", fieldDef->mFieldDeclaration->mFieldDtor->mTildeToken);
  11685. }
  11686. SetAndRestoreValue<BfFilePosition> prevFilePos(mCurFilePosition);
  11687. auto fieldDtor = fieldDef->mFieldDeclaration->mFieldDtor;
  11688. if ((fieldDef->mIsStatic) != (methodDef->mIsStatic))
  11689. continue;
  11690. UpdateSrcPos(fieldDtor);
  11691. BfScopeData scopeData;
  11692. mCurMethodState->AddScope(&scopeData);
  11693. NewScopeState();
  11694. UpdateSrcPos(fieldDtor);
  11695. bool hasDbgInfo = (!fieldDef->mIsConst);
  11696. if (hasDbgInfo)
  11697. {
  11698. mBfIRBuilder->SaveDebugLocation();
  11699. mBfIRBuilder->ClearDebugLocation();
  11700. }
  11701. BfIRValue value;
  11702. if (fieldDef->mIsStatic)
  11703. {
  11704. value = ReferenceStaticField(fieldInst).mValue;
  11705. }
  11706. else
  11707. {
  11708. if (!mCurTypeInstance->IsValueType())
  11709. {
  11710. auto thisValue = GetThis();
  11711. value = mBfIRBuilder->CreateInBoundsGEP(thisValue.mValue, 0, fieldInst->mDataIdx);
  11712. }
  11713. else
  11714. {
  11715. AssertErrorState();
  11716. value = mBfIRBuilder->CreateConstNull(mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapType(fieldInst->mResolvedType)));
  11717. }
  11718. }
  11719. BfIRValue staticVal;
  11720. if (hasDbgInfo)
  11721. {
  11722. BfIRValue dbgShowValue = value;
  11723. BfLocalVariable* localDef = new BfLocalVariable();
  11724. localDef->mName = "_";
  11725. localDef->mResolvedType = fieldInst->mResolvedType;
  11726. localDef->mAddr = value;
  11727. if ((mBfIRBuilder->DbgHasInfo()) && (!IsTargetingBeefBackend()))
  11728. {
  11729. // Create another pointer indirection, a ref to the gep
  11730. auto refFieldType = CreateRefType(fieldInst->mResolvedType);
  11731. auto allocaInst = CreateAlloca(refFieldType);
  11732. auto storeResult = mBfIRBuilder->CreateStore(value, allocaInst);
  11733. localDef->mResolvedType = refFieldType;
  11734. localDef->mAddr = allocaInst;
  11735. }
  11736. mBfIRBuilder->RestoreDebugLocation();
  11737. auto defLocalVar = AddLocalVariableDef(localDef, true);
  11738. // Put back so we actually modify the correct value*/
  11739. defLocalVar->mResolvedType = fieldInst->mResolvedType;
  11740. defLocalVar->mAddr = value;
  11741. }
  11742. while (fieldDtor != NULL)
  11743. {
  11744. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mSourceClassifier != NULL))
  11745. {
  11746. mCompiler->mResolvePassData->mSourceClassifier->SetElementType(fieldDtor, BfSourceElementType_Normal);
  11747. mCompiler->mResolvePassData->mSourceClassifier->VisitChild(fieldDtor);
  11748. }
  11749. UpdateSrcPos(fieldDtor);
  11750. VisitEmbeddedStatement(fieldDtor->mBody);
  11751. fieldDtor = fieldDtor->mNextFieldDtor;
  11752. }
  11753. RestoreScopeState();
  11754. }
  11755. }
  11756. if (!methodDef->mIsStatic)
  11757. {
  11758. auto checkBaseType = mCurTypeInstance->mBaseType;
  11759. while (checkBaseType != NULL)
  11760. {
  11761. if (auto bodyBlock = BfNodeDynCast<BfBlock>(methodDef->mBody))
  11762. {
  11763. if (bodyBlock->mCloseBrace != NULL)
  11764. UpdateSrcPos(bodyBlock->mCloseBrace);
  11765. }
  11766. else
  11767. {
  11768. UpdateSrcPos(typeDef->mTypeDeclaration->mNameNode);
  11769. }
  11770. if (checkBaseType->mTypeDef->mDtorDef != NULL)
  11771. {
  11772. auto dtorMethodInstance = GetMethodInstance(checkBaseType, checkBaseType->mTypeDef->mDtorDef, BfTypeVector());
  11773. if (mCompiler->IsSkippingExtraResolveChecks())
  11774. {
  11775. // Nothing
  11776. }
  11777. else if (dtorMethodInstance.mMethodInstance->GetParamCount() == 0)
  11778. {
  11779. if ((!mCompiler->IsSkippingExtraResolveChecks()) && (!checkBaseType->IsUnspecializedType()))
  11780. {
  11781. auto basePtr = mBfIRBuilder->CreateBitCast(mCurMethodState->mLocals[0]->mValue, mBfIRBuilder->MapTypeInstPtr(checkBaseType));
  11782. SizedArray<BfIRValue, 1> vals = { basePtr };
  11783. auto callInst = mBfIRBuilder->CreateCall(dtorMethodInstance.mFunc, vals);
  11784. mBfIRBuilder->SetCallCallingConv(callInst, GetCallingConvention(dtorMethodInstance.mMethodInstance));
  11785. }
  11786. }
  11787. else
  11788. {
  11789. // Invalid base dtor declaration
  11790. AssertErrorState();
  11791. }
  11792. break;
  11793. }
  11794. checkBaseType = checkBaseType->mBaseType;
  11795. }
  11796. }
  11797. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  11798. }
  11799. else
  11800. {
  11801. // The reason we can't just do the 'normal' path for this is that the BfTypeInstance here is NOT the
  11802. // autocomplete type instance, so FieldInstance initializer values contain expressions from the full
  11803. // resolve pass, NOT the autocomplete expression
  11804. for (auto tempTypeDef : mCompiler->mResolvePassData->mAutoCompleteTempTypes)
  11805. {
  11806. if (tempTypeDef->mFullName == typeDef->mFullName)
  11807. {
  11808. for (auto fieldDef : tempTypeDef->mFields)
  11809. {
  11810. if ((fieldDef->mIsStatic == methodDef->mIsStatic) && (fieldDef->mFieldDeclaration != NULL) &&
  11811. (fieldDef->mFieldDeclaration->mFieldDtor != NULL) && (mCompiler->mResolvePassData->mSourceClassifier != NULL))
  11812. {
  11813. BfType* fieldType = NULL;
  11814. for (int curFieldIdx = 0; curFieldIdx < (int)mCurTypeInstance->mFieldInstances.size(); curFieldIdx++)
  11815. {
  11816. auto curFieldInstance = &mCurTypeInstance->mFieldInstances[curFieldIdx];
  11817. auto curFieldDef = curFieldInstance->GetFieldDef();
  11818. if ((curFieldDef != NULL) && (fieldDef->mName == curFieldDef->mName))
  11819. fieldType = curFieldInstance->GetResolvedType();
  11820. }
  11821. auto fieldDtor = fieldDef->mFieldDeclaration->mFieldDtor;
  11822. BfScopeData scopeData;
  11823. mCurMethodState->AddScope(&scopeData);
  11824. NewScopeState();
  11825. // This is just for autocomplete, it doesn't matter that mAddr is incorrect
  11826. if (fieldType != NULL)
  11827. {
  11828. BfLocalVariable* localDef = new BfLocalVariable();
  11829. localDef->mName = "_";
  11830. localDef->mResolvedType = fieldType;
  11831. localDef->mAddr = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(fieldType));
  11832. localDef->mIsAssigned = true;
  11833. AddLocalVariableDef(localDef);
  11834. }
  11835. while (fieldDtor != NULL)
  11836. {
  11837. mCompiler->mResolvePassData->mSourceClassifier->SetElementType(fieldDtor, BfSourceElementType_Normal);
  11838. mCompiler->mResolvePassData->mSourceClassifier->VisitChild(fieldDtor);
  11839. UpdateSrcPos(fieldDtor);
  11840. VisitEmbeddedStatement(fieldDtor->mBody);
  11841. fieldDtor = fieldDtor->mNextFieldDtor;
  11842. }
  11843. RestoreScopeState();
  11844. }
  11845. }
  11846. }
  11847. }
  11848. }
  11849. }
  11850. BfIRValue BfModule::CreateDllImportGlobalVar(BfMethodInstance* methodInstance, bool define)
  11851. {
  11852. auto typeInstance = methodInstance->GetOwner();
  11853. bool foundDllImportAttr = false;
  11854. BfCallingConvention callingConvention = methodInstance->mMethodDef->mCallingConvention;
  11855. for (auto customAttr : methodInstance->GetCustomAttributes()->mAttributes)
  11856. {
  11857. if (customAttr.mType->mTypeDef->mFullName.ToString() == "System.ImportAttribute")
  11858. {
  11859. foundDllImportAttr = true;
  11860. }
  11861. }
  11862. if (!foundDllImportAttr)
  11863. {
  11864. AssertErrorState();
  11865. return BfIRValue();
  11866. }
  11867. String name = "bf_hs_preserve@";
  11868. BfMangler::Mangle(name, mCompiler->GetMangleKind(), methodInstance);
  11869. name += "__imp";
  11870. BfIRType returnType;
  11871. SizedArray<BfIRType, 8> paramTypes;
  11872. methodInstance->GetIRFunctionInfo(this, returnType, paramTypes);
  11873. BfIRFunctionType externFunctionType = mBfIRBuilder->CreateFunctionType(returnType, paramTypes, false);
  11874. auto ptrType = mBfIRBuilder->GetPointerTo(externFunctionType);
  11875. BfIRValue initVal;
  11876. if (define)
  11877. {
  11878. if (methodInstance->GetImportCallKind() != BfImportCallKind_None)
  11879. initVal = mBfIRBuilder->CreateConstNull(ptrType);
  11880. }
  11881. auto globalVar = mBfIRBuilder->CreateGlobalVariable(ptrType, false, BfIRLinkageType_External, initVal, name);
  11882. if ((define) && (mBfIRBuilder->DbgHasInfo()))
  11883. {
  11884. auto voidType = GetPrimitiveType(BfTypeCode_None);
  11885. auto ptrType = CreatePointerType(voidType);
  11886. mBfIRBuilder->DbgCreateGlobalVariable(mDICompileUnit, name, name, BfIRMDNode(), 0, mBfIRBuilder->DbgGetType(ptrType), false, globalVar);
  11887. }
  11888. return globalVar;
  11889. }
  11890. void BfModule::CreateDllImportMethod()
  11891. {
  11892. if (mBfIRBuilder->mIgnoreWrites)
  11893. return;
  11894. auto globalVar = mFuncReferences[mCurMethodInstance];
  11895. if (!globalVar)
  11896. return;
  11897. bool allowTailCall = true;
  11898. mBfIRBuilder->ClearDebugLocation();
  11899. bool isHotCompile = mCompiler->IsHotCompile();
  11900. // If we are hot swapping, we need to have this stub because we may need to call the LoadSharedLibraries on demand
  11901. if (isHotCompile)
  11902. {
  11903. auto loadSharedLibsFunc = GetBuiltInFunc(BfBuiltInFuncType_LoadSharedLibraries);
  11904. mBfIRBuilder->CreateCall(loadSharedLibsFunc, SizedArray<BfIRValue, 0>());
  11905. }
  11906. auto callingConvention = GetCallingConvention(mCurTypeInstance, mCurMethodInstance->mMethodDef);
  11907. BfIRType returnType;
  11908. SizedArray<BfIRType, 8> paramTypes;
  11909. mCurMethodInstance->GetIRFunctionInfo(this, returnType, paramTypes);
  11910. SizedArray<BfIRValue, 8> args;
  11911. for (int i = 0; i < (int)paramTypes.size(); i++)
  11912. args.push_back(mBfIRBuilder->GetArgument(i));
  11913. BfIRFunctionType externFunctionType = mBfIRBuilder->CreateFunctionType(returnType, paramTypes, false);
  11914. if (isHotCompile)
  11915. {
  11916. BfIRValue funcVal = mBfIRBuilder->CreateLoad(globalVar);
  11917. auto result = mBfIRBuilder->CreateCall(funcVal, args);
  11918. if (callingConvention == BfIRCallingConv_StdCall)
  11919. mBfIRBuilder->SetCallCallingConv(result, BfIRCallingConv_StdCall);
  11920. else
  11921. mBfIRBuilder->SetCallCallingConv(result, BfIRCallingConv_CDecl);
  11922. if (allowTailCall)
  11923. mBfIRBuilder->SetTailCall(result);
  11924. CreateReturn(result);
  11925. mCurMethodState->mHadReturn = true;
  11926. }
  11927. if (HasCompiledOutput())
  11928. {
  11929. BfDllImportEntry dllImportEntry;
  11930. dllImportEntry.mFuncVar = globalVar;
  11931. dllImportEntry.mMethodInstance = mCurMethodInstance;
  11932. mDllImportEntries.push_back(dllImportEntry);
  11933. }
  11934. }
  11935. BfIRCallingConv BfModule::GetCallingConvention(BfTypeInstance* typeInst, BfMethodDef* methodDef)
  11936. {
  11937. if ((mCompiler->mOptions.mMachineType != BfMachineType_x86) || (mCompiler->mOptions.mPlatformType != BfPlatformType_Windows))
  11938. return BfIRCallingConv_CDecl;
  11939. if (methodDef->mCallingConvention == BfCallingConvention_Stdcall)
  11940. return BfIRCallingConv_StdCall;
  11941. if ((!methodDef->mIsStatic) && (!typeInst->IsValuelessType()) &&
  11942. ((!typeInst->IsSplattable()) || (methodDef->HasNoThisSplat())))
  11943. return BfIRCallingConv_ThisCall;
  11944. return BfIRCallingConv_CDecl;
  11945. }
  11946. BfIRCallingConv BfModule::GetCallingConvention(BfMethodInstance* methodInstance)
  11947. {
  11948. return GetCallingConvention(methodInstance->GetOwner(), methodInstance->mMethodDef);
  11949. }
  11950. void BfModule::SetupIRMethod(BfMethodInstance* methodInstance, BfIRFunction func, bool isInlined)
  11951. {
  11952. BfMethodDef* methodDef = NULL;
  11953. if (methodInstance != NULL)
  11954. methodDef = methodInstance->mMethodDef;
  11955. if (!func)
  11956. return;
  11957. if (mCompiler->mOptions.mNoFramePointerElim)
  11958. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_NoFramePointerElim);
  11959. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_NoUnwind);
  11960. if (mSystem->mPtrSize == 8) // We need unwind info for debugging
  11961. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_UWTable);
  11962. if (methodInstance == NULL)
  11963. return;
  11964. if (methodDef->mImportKind == BfImportKind_Export)
  11965. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_DllExport);
  11966. if (methodDef->mNoReturn)
  11967. mBfIRBuilder->Func_AddAttribute(func, -1, BfIRAttribute_NoReturn);
  11968. auto callingConv = GetCallingConvention(methodInstance->GetOwner(), methodDef);
  11969. if (callingConv != BfIRCallingConv_CDecl)
  11970. mBfIRBuilder->SetFuncCallingConv(func, callingConv);
  11971. if (isInlined)
  11972. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_AlwaysInline);
  11973. int argIdx = 0;
  11974. int paramIdx = 0;
  11975. if (methodInstance->HasThis())
  11976. {
  11977. paramIdx = -1;
  11978. }
  11979. int argCount = methodInstance->GetIRFunctionParamCount(this);
  11980. if (methodInstance->HasStructRet())
  11981. {
  11982. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_NoAlias);
  11983. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_StructRet);
  11984. argIdx++;
  11985. }
  11986. while (argIdx < argCount)
  11987. {
  11988. while ((paramIdx != -1) && (methodInstance->IsParamSkipped(paramIdx)))
  11989. paramIdx++;
  11990. BfType* resolvedTypeRef = NULL;
  11991. String paramName;
  11992. bool isSplattable = false;
  11993. bool isThis = paramIdx == -1;
  11994. if (isThis)
  11995. {
  11996. paramName = "this";
  11997. if (methodInstance->mIsClosure)
  11998. resolvedTypeRef = mCurMethodState->mClosureState->mClosureType;
  11999. else
  12000. resolvedTypeRef = methodInstance->GetOwner();
  12001. isSplattable = (resolvedTypeRef->IsSplattable()) && (!methodDef->HasNoThisSplat());
  12002. }
  12003. else if (!methodDef->mNoSplat)
  12004. {
  12005. paramName = methodInstance->GetParamName(paramIdx);
  12006. resolvedTypeRef = methodInstance->GetParamType(paramIdx);
  12007. if (resolvedTypeRef->IsMethodRef())
  12008. isSplattable = true;
  12009. else if (resolvedTypeRef->IsSplattable())
  12010. {
  12011. if (resolvedTypeRef->GetSplatCount() + argIdx <= mCompiler->mOptions.mMaxSplatRegs)
  12012. isSplattable = true;
  12013. }
  12014. }
  12015. //
  12016. {
  12017. auto loweredTypeCode = resolvedTypeRef->GetLoweredType();
  12018. if (loweredTypeCode != BfTypeCode_None)
  12019. resolvedTypeRef = GetPrimitiveType(loweredTypeCode);
  12020. }
  12021. auto _SetupParam = [&](const StringImpl& paramName, BfType* resolvedTypeRef)
  12022. {
  12023. mBfIRBuilder->Func_SetParamName(func, argIdx + 1, paramName);
  12024. int addDeref = -1;
  12025. if (resolvedTypeRef->IsRef())
  12026. {
  12027. auto refType = (BfRefType*)resolvedTypeRef;
  12028. auto elementType = refType->mElementType;
  12029. PopulateType(elementType, BfPopulateType_Data);
  12030. addDeref = elementType->mSize;
  12031. if ((addDeref <= 0) && (!elementType->IsValuelessType()))
  12032. AssertErrorState();
  12033. }
  12034. if ((resolvedTypeRef->IsComposite()) && (!resolvedTypeRef->IsTypedPrimitive()))
  12035. {
  12036. if (mCompiler->mOptions.mAllowStructByVal)
  12037. {
  12038. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_ByVal);
  12039. }
  12040. else
  12041. {
  12042. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_NoCapture);
  12043. PopulateType(resolvedTypeRef, BfPopulateType_Data);
  12044. addDeref = resolvedTypeRef->mSize;
  12045. }
  12046. }
  12047. else if (resolvedTypeRef->IsPrimitiveType())
  12048. {
  12049. auto primType = (BfPrimitiveType*)resolvedTypeRef;
  12050. if (primType->mTypeDef->mTypeCode == BfTypeCode_Boolean)
  12051. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_ZExt);
  12052. }
  12053. if (addDeref >= 0)
  12054. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_Dereferencable, addDeref);
  12055. argIdx++;
  12056. };
  12057. if (isSplattable)
  12058. {
  12059. std::function<void(BfType*, const StringImpl&)> checkTypeLambda = [&](BfType* checkType, const StringImpl& curName)
  12060. {
  12061. if (checkType->IsStruct())
  12062. {
  12063. auto checkTypeInstance = checkType->ToTypeInstance();
  12064. if (checkTypeInstance->mBaseType != NULL)
  12065. checkTypeLambda(checkTypeInstance->mBaseType, curName);
  12066. if (checkTypeInstance->mIsUnion)
  12067. {
  12068. BfType* unionInnerType = checkTypeInstance->GetUnionInnerType();
  12069. checkTypeLambda(unionInnerType, curName + "_data");
  12070. }
  12071. else
  12072. {
  12073. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  12074. {
  12075. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  12076. auto fieldDef = fieldInstance->GetFieldDef();
  12077. if (fieldInstance->mDataIdx >= 0)
  12078. {
  12079. checkTypeLambda(fieldInstance->GetResolvedType(), curName + "_" + fieldInstance->GetFieldDef()->mName);
  12080. }
  12081. }
  12082. }
  12083. if (checkTypeInstance->IsEnum())
  12084. {
  12085. mBfIRBuilder->Func_SetParamName(func, argIdx + 1, curName + "_dscr");
  12086. argIdx++;
  12087. }
  12088. }
  12089. else if (checkType->IsMethodRef())
  12090. {
  12091. auto methodRefType = (BfMethodRefType*)checkType;
  12092. BfMethodInstance* methodRefMethodInst = methodRefType->mMethodRef;
  12093. for (int dataIdx = 0; dataIdx < (int)methodRefType->GetCaptureDataCount(); dataIdx++)
  12094. {
  12095. int methodRefParamIdx = methodRefType->GetParamIdxFromDataIdx(dataIdx);
  12096. if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  12097. {
  12098. checkTypeLambda(methodRefType->GetCaptureType(dataIdx), curName + "_" + methodRefMethodInst->GetParamName(methodRefParamIdx));
  12099. }
  12100. else
  12101. {
  12102. _SetupParam(curName + "_" + methodRefMethodInst->GetParamName(methodRefParamIdx), methodRefType->GetCaptureType(dataIdx));
  12103. }
  12104. }
  12105. }
  12106. else if (!checkType->IsValuelessType())
  12107. {
  12108. _SetupParam(curName, checkType);
  12109. }
  12110. };
  12111. checkTypeLambda(resolvedTypeRef, paramName);
  12112. paramIdx++;
  12113. continue;
  12114. }
  12115. _SetupParam(paramName, resolvedTypeRef);
  12116. //argIdx++;
  12117. paramIdx++;
  12118. }
  12119. }
  12120. void BfModule::EmitCtorBody(bool& skipBody)
  12121. {
  12122. auto methodInstance = mCurMethodInstance;
  12123. auto methodDef = methodInstance->mMethodDef;
  12124. auto methodDeclaration = methodDef->mMethodDeclaration;
  12125. auto ctorDeclaration = (BfConstructorDeclaration*)methodDef->mMethodDeclaration;
  12126. auto typeDef = mCurTypeInstance->mTypeDef;
  12127. // Prologue
  12128. mBfIRBuilder->ClearDebugLocation();
  12129. bool hadThisInitializer = false;
  12130. if ((ctorDeclaration != NULL) && (ctorDeclaration->mInitializer != NULL))
  12131. {
  12132. auto targetToken = BfNodeDynCast<BfTokenNode>(ctorDeclaration->mInitializer->mTarget);
  12133. auto targetType = (targetToken->GetToken() == BfToken_This) ? mCurTypeInstance : mCurTypeInstance->mBaseType;
  12134. if (targetToken->GetToken() == BfToken_This)
  12135. {
  12136. hadThisInitializer = true;
  12137. // Since we call a 'this', it's that other ctor's responsibility to fully assign the fields
  12138. mCurMethodState->LocalDefined(GetThisVariable());
  12139. }
  12140. }
  12141. // Zero out memory for default ctor
  12142. if ((methodDeclaration == NULL) && (mCurTypeInstance->IsStruct()))
  12143. {
  12144. if (mCurTypeInstance->IsTypedPrimitive())
  12145. {
  12146. auto thisRef = mCurMethodState->mLocals[0]->mValue;
  12147. mBfIRBuilder->CreateStore(GetDefaultValue(mCurTypeInstance), thisRef);
  12148. }
  12149. else if (mCurTypeInstance->mInstSize > 0)
  12150. {
  12151. BfIRValue fillValue = GetConstValue8(0);
  12152. BfIRValue sizeValue = GetConstValue(mCurTypeInstance->mInstSize);
  12153. auto thisRef = mCurMethodState->mLocals[0]->mValue;
  12154. BfIRValue destBits = mBfIRBuilder->CreateBitCast(thisRef, mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr));
  12155. mBfIRBuilder->CreateMemSet(destBits, fillValue, sizeValue, mCurTypeInstance->mAlign);
  12156. }
  12157. }
  12158. BfAstNode* baseCtorNode = NULL;
  12159. if ((ctorDeclaration != NULL) && (ctorDeclaration->mInitializer != NULL) && (ctorDeclaration->mInitializer->mTarget != NULL))
  12160. baseCtorNode = ctorDeclaration->mInitializer->mTarget;
  12161. else if (methodDef->mBody != NULL)
  12162. baseCtorNode = methodDef->mBody;
  12163. else if (ctorDeclaration != NULL)
  12164. baseCtorNode = ctorDeclaration;
  12165. else if (mCurTypeInstance->mTypeDef->mTypeDeclaration != NULL)
  12166. baseCtorNode = mCurTypeInstance->mTypeDef->mTypeDeclaration->mNameNode;
  12167. else if ((mCurTypeInstance->mBaseType != NULL) && (mCurTypeInstance->mBaseType->mTypeDef->mTypeDeclaration != NULL))
  12168. baseCtorNode = mCurTypeInstance->mBaseType->mTypeDef->mTypeDeclaration;
  12169. else
  12170. baseCtorNode = mContext->mBfObjectType->mTypeDef->mTypeDeclaration;
  12171. if ((!mCurTypeInstance->IsBoxed()) && (methodDef->mMethodType == BfMethodType_Ctor))
  12172. {
  12173. // Call the root type's default ctor (with no body) to initialize its fields and call the chained ctors
  12174. if (methodDef->mDeclaringType->mTypeCode == BfTypeCode_Extension)
  12175. {
  12176. BfMethodDef* defaultCtor = NULL;
  12177. for (auto methodDef : mCurTypeInstance->mTypeDef->mMethods)
  12178. {
  12179. if ((methodDef->mMethodType == BfMethodType_CtorNoBody) && (methodDef->mDeclaringType->mTypeCode != BfTypeCode_Extension))
  12180. {
  12181. defaultCtor = methodDef;
  12182. }
  12183. }
  12184. if (defaultCtor != NULL)
  12185. {
  12186. UpdateSrcPos(mCurTypeInstance->mTypeDef->GetRefNode());
  12187. SetIllegalSrcPos();
  12188. auto moduleMethodInstance = GetMethodInstance(mCurTypeInstance, defaultCtor, BfTypeVector());
  12189. BfExprEvaluator exprEvaluator(this);
  12190. SizedArray<BfIRValue, 1> irArgs;
  12191. exprEvaluator.PushThis(NULL, GetThis(), moduleMethodInstance.mMethodInstance, irArgs);
  12192. exprEvaluator.CreateCall(moduleMethodInstance.mMethodInstance, moduleMethodInstance.mFunc, false, irArgs);
  12193. }
  12194. }
  12195. }
  12196. // Initialize fields (if applicable)
  12197. if (mCurTypeInstance->IsBoxed())
  12198. {
  12199. skipBody = true;
  12200. }
  12201. else if ((methodDef->mMethodType == BfMethodType_Ctor) && (methodDef->mDeclaringType->mTypeCode == BfTypeCode_Extension))
  12202. {
  12203. // Field initializers occur in CtorNoBody methods for extensions
  12204. }
  12205. else if (!hadThisInitializer)
  12206. {
  12207. // If we had a 'this' initializer, that other ctor will have initialized our fields
  12208. if ((!mCompiler->mIsResolveOnly) ||
  12209. (mCompiler->mResolvePassData->mAutoComplete == NULL) ||
  12210. (mCompiler->mResolvePassData->mAutoComplete->mResolveType == BfResolveType_ShowFileSymbolReferences))
  12211. {
  12212. bool hadInlineInitBlock = false;
  12213. BfScopeData scopeData;
  12214. for (auto fieldDef : typeDef->mFields)
  12215. {
  12216. // For extensions, only handle these fields in the appropriate extension
  12217. if ((fieldDef->mDeclaringType->mTypeDeclaration != methodDef->mDeclaringType->mTypeDeclaration))
  12218. continue;
  12219. if ((!fieldDef->mIsConst) && (!fieldDef->mIsStatic))
  12220. {
  12221. auto fieldInst = &mCurTypeInstance->mFieldInstances[fieldDef->mIdx];
  12222. if (!fieldInst->mFieldIncluded)
  12223. continue;
  12224. if (fieldInst->mDataIdx < 0)
  12225. continue;
  12226. if (fieldDef->mInitializer == NULL)
  12227. {
  12228. if (fieldDef->mProtection != BfProtection_Hidden)
  12229. continue;
  12230. if (mCurTypeInstance->IsObject()) // Already zeroed out
  12231. continue;
  12232. }
  12233. if (fieldInst->mResolvedType == NULL)
  12234. {
  12235. BF_ASSERT(mHadBuildError);
  12236. continue;
  12237. }
  12238. if (fieldDef->mInitializer != NULL)
  12239. {
  12240. if (!hadInlineInitBlock)
  12241. {
  12242. if ((mBfIRBuilder->DbgHasInfo()) && (!mCurTypeInstance->IsUnspecializedType()) && (mHasFullDebugInfo))
  12243. {
  12244. UpdateSrcPos(baseCtorNode);
  12245. // 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
  12246. EmitEnsureInstructionAt();
  12247. BfType* thisType = mCurTypeInstance;
  12248. if (thisType->IsValueType())
  12249. thisType = CreateRefType(thisType);
  12250. SizedArray<BfIRMDNode, 1> diParamTypes;
  12251. BfIRMDNode diFuncType = mBfIRBuilder->DbgCreateSubroutineType(diParamTypes);
  12252. mCurMethodState->AddScope(&scopeData);
  12253. NewScopeState();
  12254. int flags = 0;
  12255. mCurMethodState->mCurScope->mDIInlinedAt = mBfIRBuilder->DbgGetCurrentLocation();
  12256. BF_ASSERT(mCurMethodState->mCurScope->mDIInlinedAt);
  12257. // mCurMethodState->mCurScope->mDIInlinedAt may still be null ifwe don't have an explicit ctor
  12258. mCurMethodState->mCurScope->mDIScope = mBfIRBuilder->DbgCreateFunction(mBfIRBuilder->DbgGetTypeInst(mCurTypeInstance), "this$initFields", "", mCurFilePosition.mFileInstance->mDIFile,
  12259. mCurFilePosition.mCurLine + 1, diFuncType, false, true, mCurFilePosition.mCurLine + 1, flags, false, BfIRValue());
  12260. UpdateSrcPos(fieldDef->mInitializer);
  12261. auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(mCurMethodState->mCurScope->mDIScope,
  12262. "this", mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, mBfIRBuilder->DbgGetType(thisType));
  12263. //
  12264. {
  12265. auto loadedThis = GetThis();
  12266. // LLVM can't handle two variables pointing to the same value
  12267. BfIRValue copiedThisPtr;
  12268. copiedThisPtr = CreateAlloca(thisType);
  12269. auto storeInst = mBfIRBuilder->CreateStore(loadedThis.mValue, copiedThisPtr);
  12270. mBfIRBuilder->ClearDebugLocation(storeInst);
  12271. mBfIRBuilder->DbgInsertDeclare(copiedThisPtr, diVariable);
  12272. }
  12273. hadInlineInitBlock = true;
  12274. }
  12275. }
  12276. UpdateSrcPos(fieldDef->mInitializer);
  12277. }
  12278. BfIRValue fieldAddr;
  12279. if (!mCurTypeInstance->IsTypedPrimitive())
  12280. {
  12281. fieldAddr = mBfIRBuilder->CreateInBoundsGEP(mCurMethodState->mLocals[0]->mValue, 0, fieldInst->mDataIdx /*, fieldDef->mName*/);
  12282. }
  12283. else
  12284. {
  12285. AssertErrorState();
  12286. }
  12287. auto assignValue = GetFieldInitializerValue(fieldInst);
  12288. if ((fieldAddr) && (assignValue))
  12289. mBfIRBuilder->CreateStore(assignValue.mValue, fieldAddr);
  12290. }
  12291. }
  12292. if (hadInlineInitBlock)
  12293. {
  12294. RestoreScopeState();
  12295. // This gets set to false because of AddScope but we actually are still in the head block
  12296. mCurMethodState->mInHeadScope = true;
  12297. }
  12298. }
  12299. else // Autocomplete case
  12300. {
  12301. // The reason we can't just do the 'normal' path for this is that the BfTypeInstance here is NOT the
  12302. // autocomplete type instance, so FieldInstance initializer values contain expressions from the full
  12303. // resolve pass, NOT the autocomplete expression
  12304. for (auto tempTypeDef : mCompiler->mResolvePassData->mAutoCompleteTempTypes)
  12305. {
  12306. if (tempTypeDef->mFullName == typeDef->mFullName)
  12307. {
  12308. for (auto fieldDef : tempTypeDef->mFields)
  12309. {
  12310. if ((!fieldDef->mIsStatic) && (fieldDef->mInitializer != NULL) && (mCompiler->mResolvePassData->mSourceClassifier != NULL))
  12311. {
  12312. mCompiler->mResolvePassData->mSourceClassifier->SetElementType(fieldDef->mInitializer, BfSourceElementType_Normal);
  12313. mCompiler->mResolvePassData->mSourceClassifier->VisitChild(fieldDef->mInitializer);
  12314. auto wantType = ResolveTypeRef(fieldDef->mTypeRef);
  12315. if ((wantType != NULL) &&
  12316. ((wantType->IsVar()) || (wantType->IsLet()) || (wantType->IsRef())))
  12317. wantType = NULL;
  12318. CreateValueFromExpression(fieldDef->mInitializer, wantType, BfEvalExprFlags_FieldInitializer);
  12319. }
  12320. }
  12321. }
  12322. }
  12323. // Mark fields from full type with initializers as initialized, to give proper initialization errors within ctor
  12324. for (auto fieldDef : typeDef->mFields)
  12325. {
  12326. if ((!fieldDef->mIsConst) && (!fieldDef->mIsStatic) && (fieldDef->mInitializer != NULL))
  12327. {
  12328. auto fieldInst = &mCurTypeInstance->mFieldInstances[fieldDef->mIdx];
  12329. if (fieldDef->mInitializer != NULL)
  12330. MarkFieldInitialized(fieldInst);
  12331. }
  12332. }
  12333. }
  12334. }
  12335. // Call base ctor (if applicable)
  12336. BfTypeInstance* targetType = NULL;
  12337. BfAstNode* targetRefNode = NULL;
  12338. if (ctorDeclaration != NULL)
  12339. targetRefNode = ctorDeclaration->mInitializer;
  12340. if (auto invocationExpr = BfNodeDynCast<BfInvocationExpression>(targetRefNode))
  12341. targetRefNode = invocationExpr->mTarget;
  12342. if (baseCtorNode != NULL)
  12343. {
  12344. UpdateSrcPos(baseCtorNode);
  12345. }
  12346. if ((ctorDeclaration != NULL) && (ctorDeclaration->mInitializer != NULL))
  12347. {
  12348. auto targetToken = BfNodeDynCast<BfTokenNode>(ctorDeclaration->mInitializer->mTarget);
  12349. targetType = (targetToken->GetToken() == BfToken_This) ? mCurTypeInstance : mCurTypeInstance->mBaseType;
  12350. }
  12351. else if ((mCurTypeInstance->mBaseType != NULL) && (!mCurTypeInstance->IsUnspecializedType()))
  12352. {
  12353. auto baseType = mCurTypeInstance->mBaseType;
  12354. if ((!mCurTypeInstance->IsTypedPrimitive()) &&
  12355. (baseType->mTypeDef != mCompiler->mValueTypeTypeDef) &&
  12356. (baseType->mTypeDef != mCompiler->mBfObjectTypeDef))
  12357. {
  12358. // Try to find a ctor without any params first
  12359. bool foundBaseCtor = false;
  12360. bool hadCtorWithAllDefaults = false;
  12361. for (int pass = 0; pass < 2; pass++)
  12362. {
  12363. for (auto checkMethodDef : baseType->mTypeDef->mMethods)
  12364. {
  12365. bool allowPriv = checkMethodDef->mProtection != BfProtection_Private;
  12366. // Allow calling of the default base ctor if it is implicitly defined
  12367. if ((checkMethodDef->mMethodDeclaration == NULL) && (pass == 1) && (!hadCtorWithAllDefaults))
  12368. allowPriv = true;
  12369. if ((checkMethodDef->mMethodType == BfMethodType_Ctor) && (!checkMethodDef->mIsStatic) && (allowPriv))
  12370. {
  12371. if (checkMethodDef->mParams.size() == 0)
  12372. {
  12373. foundBaseCtor = true;
  12374. if (HasCompiledOutput())
  12375. {
  12376. SizedArray<BfIRValue, 1> args;
  12377. auto ctorBodyMethodInstance = GetMethodInstance(mCurTypeInstance->mBaseType, checkMethodDef, BfTypeVector());
  12378. if (!mCurTypeInstance->mBaseType->IsValuelessType())
  12379. {
  12380. auto basePtr = mBfIRBuilder->CreateBitCast(mCurMethodState->mLocals[0]->mValue, mBfIRBuilder->MapTypeInstPtr(mCurTypeInstance->mBaseType));
  12381. args.push_back(basePtr);
  12382. }
  12383. AddCallDependency(ctorBodyMethodInstance.mMethodInstance, true);
  12384. auto callInst = mBfIRBuilder->CreateCall(ctorBodyMethodInstance.mFunc, args);
  12385. auto callingConv = GetCallingConvention(ctorBodyMethodInstance.mMethodInstance->GetOwner(), ctorBodyMethodInstance.mMethodInstance->mMethodDef);
  12386. if (callingConv != BfIRCallingConv_CDecl)
  12387. mBfIRBuilder->SetCallCallingConv(callInst, callingConv);
  12388. // if (!mCurTypeInstance->mBaseType->IsValuelessType())
  12389. // mBfIRBuilder->SetCallCallingConv(callInst, BfIRCallingConv_ThisCall);
  12390. break;
  12391. }
  12392. }
  12393. else if ((checkMethodDef->mParams[0]->mParamDeclaration != NULL) && (checkMethodDef->mParams[0]->mParamDeclaration->mInitializer != NULL))
  12394. hadCtorWithAllDefaults = true;
  12395. }
  12396. }
  12397. if (foundBaseCtor)
  12398. break;
  12399. }
  12400. if (!foundBaseCtor)
  12401. {
  12402. targetType = mCurTypeInstance->mBaseType;
  12403. if (ctorDeclaration != NULL)
  12404. targetRefNode = ctorDeclaration->mThisToken;
  12405. else if (typeDef->mTypeDeclaration != NULL)
  12406. targetRefNode = typeDef->mTypeDeclaration->mNameNode;
  12407. }
  12408. }
  12409. }
  12410. if (methodDef->mHasAppend)
  12411. {
  12412. mCurMethodState->mCurAppendAlign = methodInstance->mAppendAllocAlign;
  12413. }
  12414. if (targetType != NULL)
  12415. {
  12416. auto autoComplete = mCompiler->GetAutoComplete();
  12417. auto wasCapturingMethodInfo = (autoComplete != NULL) && (autoComplete->mIsCapturingMethodMatchInfo);
  12418. if ((autoComplete != NULL) && (ctorDeclaration != NULL) && (ctorDeclaration->mInitializer != NULL))
  12419. {
  12420. auto invocationExpr = ctorDeclaration->mInitializer;
  12421. autoComplete->CheckInvocation(invocationExpr, invocationExpr->mOpenParen, invocationExpr->mCloseParen, invocationExpr->mCommas);
  12422. }
  12423. BfType* targetThisType = targetType;
  12424. auto target = Cast(targetRefNode, GetThis(), targetThisType);
  12425. BfExprEvaluator exprEvaluator(this);
  12426. BfResolvedArgs argValues;
  12427. if ((ctorDeclaration != NULL) && (ctorDeclaration->mInitializer != NULL))
  12428. {
  12429. argValues.Init(&ctorDeclaration->mInitializer->mArguments);
  12430. if (gDebugStuff)
  12431. {
  12432. OutputDebugStrF("Expr: %@ %d\n", argValues.mArguments->mVals, argValues.mArguments->mSize);
  12433. }
  12434. }
  12435. exprEvaluator.ResolveArgValues(argValues, BfResolveArgFlag_DeferParamEval);
  12436. BfTypedValue appendIdxVal;
  12437. if (methodDef->mHasAppend)
  12438. {
  12439. auto localVar = mCurMethodState->GetRootMethodState()->mLocals[1];
  12440. BF_ASSERT(localVar->mName == "appendIdx");
  12441. auto intRefType = CreateRefType(localVar->mResolvedType);
  12442. appendIdxVal = BfTypedValue(localVar->mValue, intRefType);
  12443. mCurMethodState->mCurAppendAlign = 1; // Don't make any assumptions about how the base leaves the alignment
  12444. }
  12445. exprEvaluator.MatchConstructor(targetRefNode, NULL, target, targetType, argValues, true, methodDef->mHasAppend, &appendIdxVal);
  12446. if (autoComplete != NULL)
  12447. {
  12448. if ((wasCapturingMethodInfo) && (!autoComplete->mIsCapturingMethodMatchInfo))
  12449. {
  12450. if (autoComplete->mMethodMatchInfo != NULL)
  12451. autoComplete->mIsCapturingMethodMatchInfo = true;
  12452. else
  12453. autoComplete->mIsCapturingMethodMatchInfo = false;
  12454. }
  12455. else
  12456. autoComplete->mIsCapturingMethodMatchInfo = false;
  12457. }
  12458. }
  12459. }
  12460. void BfModule::EmitEnumToStringBody()
  12461. {
  12462. auto stringType = ResolveTypeDef(mCompiler->mStringTypeDef);
  12463. auto strVal = CreateAlloca(stringType);
  12464. auto int64StructType = GetPrimitiveStructType(BfTypeCode_Int64);
  12465. BfExprEvaluator exprEvaluator(this);
  12466. auto stringDestAddr = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  12467. BfIRBlock appendBlock = mBfIRBuilder->CreateBlock("append");
  12468. BfIRBlock noMatchBlock = mBfIRBuilder->CreateBlock("noMatch");
  12469. BfIRBlock endBlock = mBfIRBuilder->CreateBlock("end");
  12470. BfType* discriminatorType = NULL;
  12471. BfTypedValue rawPayload;
  12472. BfIRValue enumVal;
  12473. if (mCurTypeInstance->IsPayloadEnum())
  12474. {
  12475. discriminatorType = mCurTypeInstance->GetDiscriminatorType();
  12476. auto enumTypedValue = ExtractValue(GetThis(), NULL, 2);
  12477. enumTypedValue = LoadValue(enumTypedValue);
  12478. enumVal = enumTypedValue.mValue;
  12479. rawPayload = ExtractValue(GetThis(), NULL, 1);
  12480. }
  12481. else
  12482. enumVal = mBfIRBuilder->GetArgument(0);
  12483. Array<BfType*> paramTypes;
  12484. paramTypes.Add(stringType);
  12485. auto appendModuleMethodInstance = GetMethodByName(stringType->ToTypeInstance(), "Append", paramTypes);
  12486. auto switchVal = mBfIRBuilder->CreateSwitch(enumVal, noMatchBlock, (int)mCurTypeInstance->mFieldInstances.size());
  12487. HashSet<int64> handledCases;
  12488. for (auto& fieldInstance : mCurTypeInstance->mFieldInstances)
  12489. {
  12490. if (fieldInstance.mIsEnumPayloadCase)
  12491. {
  12492. int tagId = -fieldInstance.mDataIdx - 1;
  12493. BfIRBlock caseBlock = mBfIRBuilder->CreateBlock("case");
  12494. mBfIRBuilder->AddBlock(caseBlock);
  12495. mBfIRBuilder->SetInsertPoint(caseBlock);
  12496. BF_ASSERT(discriminatorType->IsPrimitiveType());
  12497. auto constVal = mBfIRBuilder->CreateConst(((BfPrimitiveType*)discriminatorType)->mTypeDef->mTypeCode, tagId);
  12498. mBfIRBuilder->AddSwitchCase(switchVal, constVal, caseBlock);
  12499. auto caseStr = GetStringObjectValue(fieldInstance.GetFieldDef()->mName);
  12500. auto stringDestVal = LoadValue(stringDestAddr);
  12501. SizedArray<BfIRValue, 2> args;
  12502. args.Add(stringDestVal.mValue);
  12503. args.Add(caseStr);
  12504. exprEvaluator.CreateCall(appendModuleMethodInstance.mMethodInstance, appendModuleMethodInstance.mFunc, false, args);
  12505. auto payloadType = fieldInstance.mResolvedType->ToTypeInstance();
  12506. BF_ASSERT(payloadType->IsTuple());
  12507. if (payloadType->mFieldInstances.size() != 0)
  12508. {
  12509. auto payload = rawPayload;
  12510. if (payload.mType != payloadType)
  12511. {
  12512. payload = Cast(NULL, payload, payloadType, BfCastFlags_Force);
  12513. }
  12514. auto toStringMethod = GetMethodByName(payloadType->ToTypeInstance(), "ToString");
  12515. SizedArray<BfIRValue, 2> irArgs;
  12516. exprEvaluator.PushThis(NULL, payload, toStringMethod.mMethodInstance, irArgs);
  12517. stringDestVal = LoadValue(stringDestAddr);
  12518. irArgs.Add(stringDestVal.mValue);
  12519. exprEvaluator.CreateCall(toStringMethod.mMethodInstance, toStringMethod.mFunc, true, irArgs);
  12520. }
  12521. mBfIRBuilder->CreateBr(endBlock);
  12522. continue;
  12523. }
  12524. if (fieldInstance.mConstIdx == -1)
  12525. continue;
  12526. auto constant = mCurTypeInstance->mConstHolder->GetConstantById(fieldInstance.mConstIdx);
  12527. if (!handledCases.TryAdd(constant->mInt64, NULL))
  12528. {
  12529. // Duplicate
  12530. continue;
  12531. }
  12532. BfIRBlock caseBlock = mBfIRBuilder->CreateBlock("case");
  12533. mBfIRBuilder->AddBlock(caseBlock);
  12534. mBfIRBuilder->SetInsertPoint(caseBlock);
  12535. BfIRValue constVal = ConstantToCurrent(constant, mCurTypeInstance->mConstHolder, mCurTypeInstance);
  12536. mBfIRBuilder->AddSwitchCase(switchVal, constVal, caseBlock);
  12537. auto caseStr = GetStringObjectValue(fieldInstance.GetFieldDef()->mName);
  12538. mBfIRBuilder->CreateStore(caseStr, strVal);
  12539. mBfIRBuilder->CreateBr(appendBlock);
  12540. }
  12541. mBfIRBuilder->AddBlock(appendBlock);
  12542. mBfIRBuilder->SetInsertPoint(appendBlock);
  12543. SizedArray<BfIRValue, 2> args;
  12544. auto stringDestVal = LoadValue(stringDestAddr);
  12545. args.Add(stringDestVal.mValue);
  12546. args.Add(mBfIRBuilder->CreateLoad(strVal));
  12547. exprEvaluator.CreateCall(appendModuleMethodInstance.mMethodInstance, appendModuleMethodInstance.mFunc, false, args);
  12548. mBfIRBuilder->CreateBr(endBlock);
  12549. mBfIRBuilder->AddBlock(noMatchBlock);
  12550. mBfIRBuilder->SetInsertPoint(noMatchBlock);
  12551. auto int64Val = mBfIRBuilder->CreateNumericCast(enumVal, false, BfTypeCode_Int64);
  12552. auto toStringModuleMethodInstance = GetMethodByName(int64StructType, "ToString", 1);
  12553. args.clear();
  12554. args.Add(int64Val);
  12555. stringDestVal = LoadValue(stringDestAddr);
  12556. args.Add(stringDestVal.mValue);
  12557. exprEvaluator.CreateCall(toStringModuleMethodInstance.mMethodInstance, toStringModuleMethodInstance.mFunc, false, args);
  12558. mBfIRBuilder->CreateBr(endBlock);
  12559. mBfIRBuilder->AddBlock(endBlock);
  12560. mBfIRBuilder->SetInsertPoint(endBlock);
  12561. }
  12562. void BfModule::EmitTupleToStringBody()
  12563. {
  12564. auto stringType = ResolveTypeDef(mCompiler->mStringTypeDef);
  12565. BfExprEvaluator exprEvaluator(this);
  12566. auto stringDestRef = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  12567. Array<BfType*> paramTypes;
  12568. paramTypes.Add(GetPrimitiveType(BfTypeCode_Char8));
  12569. auto appendCharModuleMethodInstance = GetMethodByName(stringType->ToTypeInstance(), "Append", paramTypes);
  12570. paramTypes.Clear();
  12571. paramTypes.Add(stringType);
  12572. auto appendModuleMethodInstance = GetMethodByName(stringType->ToTypeInstance(), "Append", paramTypes);
  12573. auto _AppendChar = [&](char c)
  12574. {
  12575. SizedArray<BfIRValue, 2> args;
  12576. auto stringDestVal = LoadValue(stringDestRef);
  12577. args.Add(stringDestVal.mValue);
  12578. args.Add(mBfIRBuilder->CreateConst(BfTypeCode_Char8, (int)c));
  12579. exprEvaluator.CreateCall(appendCharModuleMethodInstance.mMethodInstance, appendCharModuleMethodInstance.mFunc, false, args);
  12580. };
  12581. int fieldIdx = 0;
  12582. auto thisValue = GetThis();
  12583. auto toStringModuleMethodInstance = GetMethodByName(mContext->mBfObjectType, "ToString", 1);
  12584. auto toStringSafeModuleMethodInstance = GetMethodByName(mContext->mBfObjectType, "ToString", 2);
  12585. BfIRValue commaStr;
  12586. auto iPrintableType = ResolveTypeDef(mCompiler->mIPrintableTypeDef)->ToTypeInstance();
  12587. auto printModuleMethodInstance = GetMethodByName(iPrintableType, "Print");
  12588. _AppendChar('(');
  12589. for (auto& fieldInstance : mCurTypeInstance->mFieldInstances)
  12590. {
  12591. if (fieldInstance.mDataIdx == -1)
  12592. continue;
  12593. if (fieldIdx > 0)
  12594. {
  12595. if (!commaStr)
  12596. commaStr = GetStringObjectValue(", ");
  12597. SizedArray<BfIRValue, 2> args;
  12598. auto stringDestVal = LoadValue(stringDestRef);
  12599. args.Add(stringDestVal.mValue);
  12600. args.Add(commaStr);
  12601. exprEvaluator.CreateCall(appendModuleMethodInstance.mMethodInstance, appendModuleMethodInstance.mFunc, false, args);
  12602. }
  12603. fieldIdx++;
  12604. if (fieldInstance.mResolvedType->IsValuelessType())
  12605. continue;
  12606. BfTypedValue fieldValue = ExtractValue(thisValue, &fieldInstance, fieldInstance.mDataIdx);
  12607. if (fieldValue.mType->IsPrimitiveType())
  12608. {
  12609. fieldValue.mType = GetPrimitiveStructType(((BfPrimitiveType*)fieldValue.mType)->mTypeDef->mTypeCode);
  12610. }
  12611. auto typeInstance = fieldValue.mType->ToTypeInstance();
  12612. if ((typeInstance != NULL) && (TypeIsSubTypeOf(typeInstance, iPrintableType, false)))
  12613. {
  12614. BfExprEvaluator exprEvaluator(this);
  12615. SizedArray<BfResolvedArg, 0> resolvedArgs;
  12616. BfMethodMatcher methodMatcher(NULL, this, printModuleMethodInstance.mMethodInstance, resolvedArgs);
  12617. methodMatcher.mBestMethodDef = printModuleMethodInstance.mMethodInstance->mMethodDef;
  12618. methodMatcher.mBestMethodTypeInstance = iPrintableType;
  12619. methodMatcher.TryDevirtualizeCall(fieldValue);
  12620. BfTypedValue callVal = Cast(NULL, fieldValue, methodMatcher.mBestMethodTypeInstance);
  12621. BfResolvedArg resolvedArg;
  12622. auto stringDestVal = LoadValue(stringDestRef);
  12623. resolvedArg.mTypedValue = stringDestVal;
  12624. resolvedArg.mResolvedType = stringDestVal.mType;
  12625. resolvedArgs.Add(resolvedArg);
  12626. exprEvaluator.CreateCall(&methodMatcher, callVal);
  12627. continue;
  12628. }
  12629. if (fieldValue.mType->IsObjectOrInterface())
  12630. {
  12631. BF_ASSERT(!fieldValue.IsAddr());
  12632. SizedArray<BfIRValue, 2> args;
  12633. args.Add(mBfIRBuilder->CreateBitCast(fieldValue.mValue, mBfIRBuilder->MapType(mContext->mBfObjectType)));
  12634. auto stringDestVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  12635. stringDestVal = LoadValue(stringDestVal);
  12636. args.Add(stringDestVal.mValue);
  12637. exprEvaluator.CreateCall(toStringSafeModuleMethodInstance.mMethodInstance, toStringSafeModuleMethodInstance.mFunc, false, args);
  12638. continue;
  12639. }
  12640. BfExprEvaluator exprEvaluator(this);
  12641. SizedArray<BfResolvedArg, 0> resolvedArgs;
  12642. BfMethodMatcher methodMatcher(NULL, this, toStringModuleMethodInstance.mMethodInstance, resolvedArgs);
  12643. methodMatcher.mBestMethodDef = toStringModuleMethodInstance.mMethodInstance->mMethodDef;
  12644. methodMatcher.mBestMethodTypeInstance = mContext->mBfObjectType;
  12645. methodMatcher.TryDevirtualizeCall(fieldValue);
  12646. if (methodMatcher.mBestMethodTypeInstance == mContext->mBfObjectType)
  12647. {
  12648. AddCallDependency(appendModuleMethodInstance.mMethodInstance);
  12649. AddDependency(fieldValue.mType, mCurTypeInstance, BfDependencyMap::DependencyFlag_Calls);
  12650. // Just append the type name
  12651. String typeName = TypeToString(fieldInstance.mResolvedType);
  12652. auto strVal = GetStringObjectValue(typeName);
  12653. SizedArray<BfIRValue, 2> args;
  12654. auto stringDestVal = LoadValue(stringDestRef);
  12655. args.Add(stringDestVal.mValue);
  12656. args.Add(strVal);
  12657. exprEvaluator.CreateCall(appendModuleMethodInstance.mMethodInstance, appendModuleMethodInstance.mFunc, false, args);
  12658. continue;
  12659. }
  12660. BfTypedValue callVal = Cast(NULL, fieldValue, methodMatcher.mBestMethodTypeInstance);
  12661. BfResolvedArg resolvedArg;
  12662. auto stringDestVal = LoadValue(stringDestRef);
  12663. resolvedArg.mTypedValue = stringDestVal;
  12664. resolvedArg.mResolvedType = stringDestVal.mType;
  12665. resolvedArgs.Add(resolvedArg);
  12666. exprEvaluator.CreateCall(&methodMatcher, callVal);
  12667. }
  12668. _AppendChar(')');
  12669. }
  12670. void BfModule::EmitIteratorBlock(bool& skipBody)
  12671. {
  12672. auto methodInstance = mCurMethodInstance;
  12673. auto methodDef = methodInstance->mMethodDef;
  12674. auto methodDeclaration = methodDef->GetMethodDeclaration();
  12675. auto typeDef = mCurTypeInstance->mTypeDef;
  12676. BfType* innerRetType = NULL;
  12677. BfTypeInstance* usingInterface = NULL;
  12678. auto retTypeInst = mCurMethodInstance->mReturnType->ToGenericTypeInstance();
  12679. if (retTypeInst != NULL)
  12680. {
  12681. if ((retTypeInst->mTypeDef == mCompiler->mGenericIEnumerableTypeDef) ||
  12682. (retTypeInst->mTypeDef == mCompiler->mGenericIEnumeratorTypeDef))
  12683. {
  12684. innerRetType = retTypeInst->mTypeGenericArguments[0];
  12685. }
  12686. }
  12687. if (innerRetType == NULL)
  12688. {
  12689. Fail("Methods with yields must return either System.IEnumerable<T> or System.IEnumerator<T>", methodDeclaration->mReturnType);
  12690. return;
  12691. }
  12692. auto blockBody = BfNodeDynCast<BfBlock>(methodDeclaration->mBody);
  12693. if (blockBody == NULL)
  12694. return;
  12695. }
  12696. void BfModule::EmitGCMarkValue(BfTypedValue markVal, BfModuleMethodInstance markFromGCThreadMethodInstance)
  12697. {
  12698. auto fieldTypeInst = markVal.mType->ToTypeInstance();
  12699. if (fieldTypeInst == NULL)
  12700. return;
  12701. if (!markVal.mType->IsComposite())
  12702. markVal = LoadValue(markVal);
  12703. BfExprEvaluator exprEvaluator(this);
  12704. PopulateType(markVal.mType, BfPopulateType_Data);
  12705. if (markVal.mType->IsObjectOrInterface())
  12706. {
  12707. BfIRValue val = markVal.mValue;
  12708. val = mBfIRBuilder->CreateBitCast(val, mBfIRBuilder->MapType(mContext->mBfObjectType));
  12709. SizedArray<BfIRValue, 1> args;
  12710. args.push_back(val);
  12711. exprEvaluator.CreateCall(markFromGCThreadMethodInstance.mMethodInstance, markFromGCThreadMethodInstance.mFunc, false, args);
  12712. }
  12713. else if ((fieldTypeInst->IsComposite()) && (!fieldTypeInst->IsTypedPrimitive()))
  12714. {
  12715. auto markMemberMethodInstance = GetMethodByName(fieldTypeInst, BF_METHODNAME_MARKMEMBERS, 0, true);
  12716. if (markMemberMethodInstance)
  12717. {
  12718. SizedArray<BfIRValue, 1> args;
  12719. //(1, markVal.mValue);
  12720. //exprEvaluator.PushArg(markVal, args);
  12721. exprEvaluator.PushThis(NULL, markVal, markMemberMethodInstance.mMethodInstance, args);
  12722. exprEvaluator.CreateCall(markMemberMethodInstance.mMethodInstance, markMemberMethodInstance.mFunc, false, args);
  12723. }
  12724. }
  12725. }
  12726. void BfModule::CallChainedMethods(BfMethodInstance* methodInstance, bool reverse)
  12727. {
  12728. Array<BfMethodInstance*> methodInstances;
  12729. for (int methodIdx = 0; methodIdx < (int)mCurTypeInstance->mMethodInstanceGroups.size(); methodIdx++)
  12730. {
  12731. auto& methodInstGroup = mCurTypeInstance->mMethodInstanceGroups[methodIdx];
  12732. auto chainedMethodInst = methodInstGroup.mDefault;
  12733. if ((chainedMethodInst != NULL) && (chainedMethodInst->mChainType == BfMethodChainType_ChainMember))
  12734. {
  12735. if ((chainedMethodInst->mMethodDef->mIsStatic == methodInstance->mMethodDef->mIsStatic) &&
  12736. (CompareMethodSignatures(methodInstance, chainedMethodInst)))
  12737. {
  12738. methodInstances.push_back(chainedMethodInst);
  12739. }
  12740. }
  12741. }
  12742. std::stable_sort(methodInstances.begin(), methodInstances.end(),
  12743. [&](BfMethodInstance* lhs, BfMethodInstance* rhs)
  12744. {
  12745. bool isBetter;
  12746. bool isWorse;
  12747. CompareDeclTypes(lhs->mMethodDef->mDeclaringType, rhs->mMethodDef->mDeclaringType, isBetter, isWorse);
  12748. if (isBetter == isWorse)
  12749. {
  12750. return false;
  12751. }
  12752. return isWorse;
  12753. });
  12754. if (reverse)
  12755. std::reverse(methodInstances.begin(), methodInstances.end());
  12756. for (auto chainedMethodInst : methodInstances)
  12757. {
  12758. auto declModule = this;
  12759. BfGetMethodInstanceFlags flags = BfGetMethodInstanceFlag_None;
  12760. auto moduleMethodInst = declModule->GetMethodInstance(mCurTypeInstance, chainedMethodInst->mMethodDef, BfTypeVector(), flags);
  12761. BfExprEvaluator exprEvaluator(this);
  12762. SizedArray<BfIRValue, 1> args;
  12763. exprEvaluator.PushThis(chainedMethodInst->mMethodDef->GetRefNode(), GetThis(), chainedMethodInst, args);
  12764. exprEvaluator.CreateCall(moduleMethodInst.mMethodInstance, moduleMethodInst.mFunc, true, args);
  12765. }
  12766. }
  12767. void BfModule::AddHotDataReferences(BfHotDataReferenceBuilder* builder)
  12768. {
  12769. BF_ASSERT(mCurMethodInstance->mIsReified);
  12770. if (mCurTypeInstance->mHotTypeData == NULL)
  12771. mCurTypeInstance->mHotTypeData = new BfHotTypeData();
  12772. auto hotMethod = mCurMethodInstance->mHotMethod;
  12773. for (auto depData : hotMethod->mReferences)
  12774. {
  12775. // Only virtual decls are allowed to already be there
  12776. BF_ASSERT((depData->mDataKind == BfHotDepDataKind_VirtualDecl) || (depData->mDataKind == BfHotDepDataKind_DupMethod));
  12777. }
  12778. BF_ASSERT(hotMethod->mSrcTypeVersion != NULL);
  12779. int prevSize = (int)hotMethod->mReferences.size();
  12780. int refCount = (int)(prevSize + builder->mUsedData.size() + builder->mCalledMethods.size() + builder->mDevirtualizedCalledMethods.size());
  12781. if (!mCurMethodInstance->mMethodDef->mIsStatic)
  12782. refCount++;
  12783. hotMethod->mReferences.Reserve(refCount);
  12784. if (!mCurMethodInstance->mMethodDef->mIsStatic)
  12785. {
  12786. auto hotThis = mCompiler->mHotData->GetThisType(mCurMethodInstance->GetOwner()->mHotTypeData->GetLatestVersion());
  12787. hotThis->mRefCount++;
  12788. hotMethod->mReferences.Insert(0, hotThis);
  12789. prevSize++;
  12790. }
  12791. for (auto val : builder->mAllocatedData)
  12792. {
  12793. auto hotAllocation = mCompiler->mHotData->GetAllocation(val);
  12794. hotMethod->mReferences.Add(hotAllocation);
  12795. }
  12796. for (auto val : builder->mUsedData)
  12797. hotMethod->mReferences.Add(val);
  12798. for (auto val : builder->mCalledMethods)
  12799. hotMethod->mReferences.Add(val);
  12800. for (auto val : builder->mDevirtualizedCalledMethods)
  12801. {
  12802. auto devirtualizedMethod = mCompiler->mHotData->GetDevirtualizedMethod(val);
  12803. hotMethod->mReferences.Add(devirtualizedMethod);
  12804. }
  12805. for (auto val : builder->mFunctionPtrs)
  12806. {
  12807. auto funcRef = mCompiler->mHotData->GetFunctionReference(val);
  12808. hotMethod->mReferences.Add(funcRef);
  12809. }
  12810. for (auto val : builder->mInnerMethods)
  12811. {
  12812. auto innerMethod = mCompiler->mHotData->GetInnerMethod(val);
  12813. hotMethod->mReferences.Add(innerMethod);
  12814. }
  12815. for (int refIdx = prevSize; refIdx < (int)hotMethod->mReferences.size(); refIdx++)
  12816. {
  12817. auto depData = hotMethod->mReferences[refIdx];
  12818. BF_ASSERT(depData != NULL);
  12819. depData->mRefCount++;
  12820. }
  12821. //hotMethod->mReferences.Sort([](BfHotDepData* lhs, BfHotDepData* rhs) { return lhs < rhs; });
  12822. }
  12823. void BfModule::ProcessMethod_SetupParams(BfMethodInstance* methodInstance, BfType* thisType, bool wantsDIData, SizedArrayImpl<BfIRMDNode>* diParams)
  12824. {
  12825. auto methodDef = methodInstance->mMethodDef;
  12826. auto methodDeclaration = methodDef->mMethodDeclaration;
  12827. bool isThisStruct = false;
  12828. if (thisType != NULL)
  12829. isThisStruct = thisType->IsStruct() && !thisType->IsTypedPrimitive();
  12830. int argIdx = 0;
  12831. if (methodInstance->HasStructRet())
  12832. argIdx++;
  12833. if (!methodDef->mIsStatic)
  12834. {
  12835. BfLocalVariable* paramVar = new BfLocalVariable();
  12836. paramVar->mResolvedType = thisType;
  12837. paramVar->mName = "this";
  12838. if (!thisType->IsValuelessType())
  12839. paramVar->mValue = mBfIRBuilder->GetArgument(argIdx);
  12840. else
  12841. paramVar->mValue = mBfIRBuilder->GetFakeVal();
  12842. if ((thisType->IsComposite()) && (!methodDef->HasNoThisSplat()))
  12843. {
  12844. if (thisType->IsSplattable())
  12845. paramVar->mIsSplat = true;
  12846. else
  12847. paramVar->mIsLowered = thisType->GetLoweredType() != BfTypeCode_None;
  12848. }
  12849. auto thisTypeInst = thisType->ToTypeInstance();
  12850. paramVar->mIsStruct = isThisStruct;
  12851. paramVar->mAddr = BfIRValue();
  12852. paramVar->mIsThis = true;
  12853. paramVar->mParamIdx = -1;
  12854. if ((methodDef->mMethodType == BfMethodType_Ctor) && (mCurTypeInstance->IsStruct()))
  12855. {
  12856. paramVar->mIsAssigned = false;
  12857. }
  12858. else
  12859. {
  12860. paramVar->mIsAssigned = true;
  12861. }
  12862. paramVar->mReadFromId = -1;
  12863. paramVar->Init();
  12864. if (methodDeclaration == NULL)
  12865. UseDefaultSrcPos();
  12866. AddLocalVariableDef(paramVar);
  12867. if (!thisType->IsValuelessType())
  12868. {
  12869. if (wantsDIData)
  12870. {
  12871. BfType* thisPtrType = thisType;
  12872. auto diType = mBfIRBuilder->DbgGetType(thisPtrType);
  12873. if (!thisType->IsValueType())
  12874. diType = mBfIRBuilder->DbgCreateArtificialType(diType);
  12875. diParams->push_back(diType);
  12876. }
  12877. if (paramVar->mIsSplat)
  12878. {
  12879. BfTypeUtils::SplatIterate([&](BfType* checkType) { argIdx++; }, paramVar->mResolvedType);
  12880. }
  12881. else
  12882. {
  12883. argIdx++;
  12884. }
  12885. }
  12886. }
  12887. bool hadParams = false;
  12888. bool hasDefault = false;
  12889. int compositeVariableIdx = -1;
  12890. int paramIdx = 0;
  12891. for (paramIdx = 0; paramIdx < methodInstance->GetParamCount(); paramIdx++)
  12892. {
  12893. // We already issues a type error for this param if we had one in declaration processing
  12894. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, true);
  12895. BfLocalVariable* paramVar = new BfLocalVariable();
  12896. bool isParamSkipped = methodInstance->IsParamSkipped(paramIdx);
  12897. BfType* unresolvedType = methodInstance->GetParamType(paramIdx, false);
  12898. if (unresolvedType == NULL)
  12899. {
  12900. AssertErrorState();
  12901. unresolvedType = mContext->mBfObjectType;
  12902. paramVar->mParamFailed = true;
  12903. }
  12904. auto resolvedType = methodInstance->GetParamType(paramIdx, true);
  12905. prevIgnoreErrors.Restore();
  12906. PopulateType(resolvedType, BfPopulateType_Declaration);
  12907. paramVar->mResolvedType = resolvedType;
  12908. paramVar->mName = methodInstance->GetParamName(paramIdx);
  12909. paramVar->mNameNode = methodInstance->GetParamNameNode(paramIdx);
  12910. if (!isParamSkipped)
  12911. {
  12912. paramVar->mValue = mBfIRBuilder->GetArgument(argIdx);
  12913. if (resolvedType->IsMethodRef())
  12914. {
  12915. paramVar->mIsSplat = true;
  12916. }
  12917. else if (resolvedType->IsComposite() && resolvedType->IsSplattable())
  12918. {
  12919. int splatCount = resolvedType->GetSplatCount();
  12920. if (argIdx + splatCount <= mCompiler->mOptions.mMaxSplatRegs)
  12921. paramVar->mIsSplat = true;
  12922. }
  12923. }
  12924. else
  12925. {
  12926. paramVar->mIsSplat = true; // Treat skipped (valueless) as a splat
  12927. paramVar->mValue = mBfIRBuilder->GetFakeVal();
  12928. }
  12929. paramVar->mIsLowered = resolvedType->GetLoweredType() != BfTypeCode_None;
  12930. paramVar->mIsStruct = resolvedType->IsComposite() && !resolvedType->IsTypedPrimitive();
  12931. paramVar->mParamIdx = paramIdx;
  12932. paramVar->mIsImplicitParam = methodInstance->IsImplicitCapture(paramIdx);
  12933. paramVar->mReadFromId = 0;
  12934. if (resolvedType->IsRef())
  12935. {
  12936. auto refType = (BfRefType*)resolvedType;
  12937. paramVar->mIsAssigned = refType->mRefKind != BfRefType::RefKind_Out;
  12938. }
  12939. else
  12940. {
  12941. paramVar->mIsAssigned = true;
  12942. if (methodDef->mMethodType != BfMethodType_Mixin)
  12943. paramVar->mIsReadOnly = true;
  12944. }
  12945. if (paramVar->mResolvedType->IsGenericParam())
  12946. {
  12947. auto genericParamInst = GetGenericParamInstance((BfGenericParamType*)paramVar->mResolvedType);
  12948. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  12949. {
  12950. auto typedVal = GetDefaultTypedValue(genericParamInst->mTypeConstraint, false, BfDefaultValueKind_Undef);
  12951. paramVar->mResolvedType = typedVal.mType;
  12952. paramVar->mConstValue = typedVal.mValue;
  12953. }
  12954. }
  12955. if (paramVar->mResolvedType->IsConstExprValue())
  12956. {
  12957. BfConstExprValueType* constExprValueType = (BfConstExprValueType*)paramVar->mResolvedType;
  12958. auto unspecializedMethodInstance = GetUnspecializedMethodInstance(methodInstance);
  12959. auto unspecParamType = unspecializedMethodInstance->GetParamType(paramIdx);
  12960. BF_ASSERT(unspecParamType->IsGenericParam());
  12961. if (unspecParamType->IsGenericParam())
  12962. {
  12963. BfGenericParamType* genericParamType = (BfGenericParamType*)unspecParamType;
  12964. if (genericParamType->mGenericParamKind == BfGenericParamKind_Method)
  12965. {
  12966. auto genericParamInst = unspecializedMethodInstance->mMethodInfoEx->mGenericParams[genericParamType->mGenericParamIdx];
  12967. if (genericParamInst->mTypeConstraint != NULL)
  12968. {
  12969. BfExprEvaluator exprEvaluator(this);
  12970. exprEvaluator.mExpectingType = genericParamInst->mTypeConstraint;
  12971. exprEvaluator.GetLiteral(NULL, constExprValueType->mValue);
  12972. auto checkType = genericParamInst->mTypeConstraint;
  12973. if (checkType->IsTypedPrimitive())
  12974. checkType = checkType->GetUnderlyingType();
  12975. if (exprEvaluator.mResult.mType == checkType)
  12976. {
  12977. paramVar->mResolvedType = genericParamInst->mTypeConstraint;
  12978. paramVar->mConstValue = exprEvaluator.mResult.mValue;
  12979. BF_ASSERT(paramVar->mConstValue.IsConst());
  12980. }
  12981. else
  12982. {
  12983. AssertErrorState();
  12984. paramVar->mResolvedType = genericParamInst->mTypeConstraint;
  12985. paramVar->mConstValue = GetDefaultValue(genericParamInst->mTypeConstraint);
  12986. }
  12987. }
  12988. }
  12989. }
  12990. //BF_ASSERT(!paramVar->mResolvedType->IsConstExprValue());
  12991. if (paramVar->mResolvedType->IsConstExprValue())
  12992. {
  12993. Fail("Invalid use of constant expression", methodInstance->GetParamTypeRef(paramIdx));
  12994. //AssertErrorState();
  12995. paramVar->mResolvedType = GetPrimitiveType(BfTypeCode_IntPtr);
  12996. paramVar->mConstValue = GetDefaultValue(paramVar->mResolvedType);
  12997. }
  12998. }
  12999. if (methodInstance->GetParamKind(paramIdx) == BfParamKind_DelegateParam)
  13000. {
  13001. if (compositeVariableIdx == -1)
  13002. {
  13003. compositeVariableIdx = (int)mCurMethodState->mLocals.size();
  13004. BfLocalVariable* localVar = new BfLocalVariable();
  13005. auto paramInst = &methodInstance->mParams[paramIdx];
  13006. auto paramDef = methodDef->mParams[paramInst->mParamDefIdx];
  13007. localVar->mName = paramDef->mName;
  13008. localVar->mResolvedType = ResolveTypeRef(paramDef->mTypeRef, BfPopulateType_Declaration, BfResolveTypeRefFlag_NoResolveGenericParam);
  13009. localVar->mCompositeCount = 0;
  13010. DoAddLocalVariable(localVar);
  13011. }
  13012. mCurMethodState->mLocals[compositeVariableIdx]->mCompositeCount++;
  13013. }
  13014. CheckVariableDef(paramVar);
  13015. paramVar->Init();
  13016. AddLocalVariableDef(paramVar);
  13017. if (!isParamSkipped)
  13018. {
  13019. if (wantsDIData)
  13020. diParams->push_back(mBfIRBuilder->DbgGetType(resolvedType));
  13021. if (paramVar->mIsSplat)
  13022. {
  13023. BfTypeUtils::SplatIterate([&](BfType* checkType) { argIdx++; }, paramVar->mResolvedType);
  13024. }
  13025. else
  13026. {
  13027. argIdx++;
  13028. }
  13029. }
  13030. }
  13031. // Try to find an ending delegate params composite
  13032. if ((compositeVariableIdx == -1) && (methodDef->mParams.size() > 0))
  13033. {
  13034. auto paramDef = methodDef->mParams.back();
  13035. if (paramDef->mParamKind == BfParamKind_Params)
  13036. {
  13037. auto paramsType = ResolveTypeRef(paramDef->mTypeRef, BfPopulateType_Declaration, BfResolveTypeRefFlag_NoResolveGenericParam);
  13038. if (paramsType == NULL)
  13039. {
  13040. AssertErrorState();
  13041. }
  13042. else if (paramsType->IsGenericParam())
  13043. {
  13044. auto genericParamInstance = GetGenericParamInstance((BfGenericParamType*)paramsType);
  13045. if (genericParamInstance->mTypeConstraint != NULL)
  13046. {
  13047. auto typeInstConstraint = genericParamInstance->mTypeConstraint->ToTypeInstance();
  13048. if ((genericParamInstance->mTypeConstraint->IsDelegate()) || (genericParamInstance->mTypeConstraint->IsFunction()) ||
  13049. ((typeInstConstraint != NULL) &&
  13050. ((typeInstConstraint->mTypeDef == mCompiler->mDelegateTypeDef) || (typeInstConstraint->mTypeDef == mCompiler->mFunctionTypeDef))))
  13051. {
  13052. BfLocalVariable* localVar = new BfLocalVariable();
  13053. localVar->mName = paramDef->mName;
  13054. localVar->mResolvedType = paramsType;
  13055. localVar->mCompositeCount = 0;
  13056. DoAddLocalVariable(localVar);
  13057. }
  13058. }
  13059. }
  13060. else if (paramsType->IsDelegate())
  13061. {
  13062. BfMethodInstance* invokeMethodInstance = GetRawMethodInstanceAtIdx(paramsType->ToTypeInstance(), 0, "Invoke");
  13063. if (invokeMethodInstance != NULL)
  13064. {
  13065. // This is only for the case where the delegate didn't actually have any params so the composite is zero-sized
  13066. // and wasn't cleared by the preceding loop
  13067. BF_ASSERT(invokeMethodInstance->GetParamCount() == 0);
  13068. BfLocalVariable* localVar = new BfLocalVariable();
  13069. localVar->mName = paramDef->mName;
  13070. localVar->mResolvedType = paramsType;
  13071. localVar->mCompositeCount = 0;
  13072. DoAddLocalVariable(localVar);
  13073. }
  13074. }
  13075. }
  13076. }
  13077. }
  13078. void BfModule::ProcessMethod_ProcessDeferredLocals(int startIdx)
  13079. {
  13080. // if (mCurMethodState->mPrevMethodState != NULL) // Re-entry
  13081. // return;
  13082. auto _ClearState = [&]()
  13083. {
  13084. mCurMethodState->mLocalMethods.Clear();
  13085. for (auto& local : mCurMethodState->mLocals)
  13086. delete local;
  13087. mCurMethodState->mLocals.Clear();
  13088. mCurMethodState->mLocalVarSet.Clear();
  13089. };
  13090. // 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
  13091. // we show errors in the capture phase. If we somehow pass the capture phase without error then this method WILL show any errors here,
  13092. // however (compiler bug), so this is the safest way
  13093. if (!mCurMethodState->mDeferredLocalMethods.IsEmpty())
  13094. {
  13095. for (int deferredLocalMethodIdx = 0; deferredLocalMethodIdx < (int)mCurMethodState->mDeferredLocalMethods.size(); deferredLocalMethodIdx++)
  13096. {
  13097. auto deferredLocalMethod = mCurMethodState->mDeferredLocalMethods[deferredLocalMethodIdx];
  13098. BfLogSysM("Processing deferred local method %p\n", deferredLocalMethod);
  13099. if (!mHadBuildError)
  13100. {
  13101. // Process as a closure - that allows us to look back and see the const locals and stuff
  13102. BfClosureState closureState;
  13103. mCurMethodState->mClosureState = &closureState;
  13104. closureState.mConstLocals = deferredLocalMethod->mConstLocals;
  13105. closureState.mReturnType = deferredLocalMethod->mMethodInstance->mReturnType;
  13106. closureState.mActiveDeferredLocalMethod = deferredLocalMethod;
  13107. closureState.mLocalMethod = deferredLocalMethod->mLocalMethod;
  13108. if (deferredLocalMethod->mMethodInstance->mMethodInfoEx != NULL)
  13109. closureState.mClosureInstanceInfo = deferredLocalMethod->mMethodInstance->mMethodInfoEx->mClosureInstanceInfo;
  13110. mCurMethodState->mMixinState = deferredLocalMethod->mLocalMethod->mDeclMixinState;
  13111. _ClearState();
  13112. for (auto& constLocal : deferredLocalMethod->mConstLocals)
  13113. {
  13114. auto localVar = new BfLocalVariable();
  13115. *localVar = constLocal;
  13116. DoAddLocalVariable(localVar);
  13117. }
  13118. mCurMethodState->mLocalMethods = deferredLocalMethod->mLocalMethods;
  13119. bool doProcess = !mCompiler->mCanceling;
  13120. if (doProcess)
  13121. {
  13122. BP_ZONE_F("ProcessMethod local %s", deferredLocalMethod->mMethodInstance->mMethodDef->mName.c_str());
  13123. ProcessMethod(deferredLocalMethod->mMethodInstance);
  13124. }
  13125. }
  13126. delete deferredLocalMethod;
  13127. mSystem->CheckLockYield();
  13128. }
  13129. }
  13130. for (auto& kv : mCurMethodState->mLocalMethodCache)
  13131. {
  13132. BF_ASSERT((kv.mValue->mMethodDef == NULL) || (kv.mKey == kv.mValue->mMethodDef->mName));
  13133. }
  13134. if ((!mCurMethodState->mDeferredLambdaInstances.IsEmpty()) && (!mHadBuildError))
  13135. {
  13136. for (int deferredLambdaIdx = 0; deferredLambdaIdx < (int)mCurMethodState->mDeferredLambdaInstances.size(); deferredLambdaIdx++)
  13137. {
  13138. auto lambdaInstance = mCurMethodState->mDeferredLambdaInstances[deferredLambdaIdx];
  13139. BfLogSysM("Processing deferred lambdaInstance %p\n", lambdaInstance);
  13140. BfClosureState closureState;
  13141. mCurMethodState->mClosureState = &closureState;
  13142. //closureState.mConstLocals = deferredLocalMethod->mConstLocals;
  13143. closureState.mReturnType = lambdaInstance->mMethodInstance->mReturnType;
  13144. if (lambdaInstance->mClosureTypeInstance != NULL)
  13145. closureState.mClosureType = lambdaInstance->mClosureTypeInstance;
  13146. else
  13147. closureState.mClosureType = lambdaInstance->mDelegateTypeInstance;
  13148. closureState.mClosureInstanceInfo = lambdaInstance->mMethodInstance->mMethodInfoEx->mClosureInstanceInfo;
  13149. mCurMethodState->mMixinState = lambdaInstance->mDeclMixinState;
  13150. _ClearState();
  13151. for (auto& constLocal : lambdaInstance->mConstLocals)
  13152. {
  13153. //if (constLocal.mIsThis)
  13154. {
  13155. // Valueless 'this'
  13156. closureState.mConstLocals.Add(constLocal);
  13157. }
  13158. /*else
  13159. {
  13160. auto localVar = new BfLocalVariable();
  13161. *localVar = constLocal;
  13162. DoAddLocalVariable(localVar);
  13163. }*/
  13164. }
  13165. BfMethodInstanceGroup methodInstanceGroup;
  13166. methodInstanceGroup.mOwner = mCurTypeInstance;
  13167. methodInstanceGroup.mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  13168. bool doProcess = !mCompiler->mCanceling;
  13169. if (doProcess)
  13170. {
  13171. BP_ZONE_F("ProcessMethod lambdaInstance %s", lambdaInstance->mMethodInstance->mMethodDef->mName.c_str());
  13172. lambdaInstance->mMethodInstance->mMethodInstanceGroup = &methodInstanceGroup;
  13173. ProcessMethod(lambdaInstance->mMethodInstance);
  13174. if (lambdaInstance->mDtorMethodInstance != NULL)
  13175. {
  13176. lambdaInstance->mDtorMethodInstance->mMethodInstanceGroup = &methodInstanceGroup;
  13177. ProcessMethod(lambdaInstance->mDtorMethodInstance);
  13178. }
  13179. }
  13180. }
  13181. mSystem->CheckLockYield();
  13182. }
  13183. }
  13184. void BfModule::EmitGCMarkValue(BfTypedValue& thisValue, BfType* checkType, int memberDepth, int curOffset, HashSet<int>& objectOffsets, BfModuleMethodInstance markFromGCThreadMethodInstance)
  13185. {
  13186. if (checkType->IsComposite())
  13187. PopulateType(checkType, BfPopulateType_Data);
  13188. if (!checkType->WantsGCMarking())
  13189. return;
  13190. auto typeInstance = checkType->ToTypeInstance();
  13191. bool callMarkMethod = false;
  13192. // Call the actual marking method
  13193. if (memberDepth == 0)
  13194. {
  13195. // Don't call marking method on self
  13196. }
  13197. else if (checkType->IsObjectOrInterface())
  13198. {
  13199. if (!objectOffsets.Add(curOffset))
  13200. {
  13201. return;
  13202. }
  13203. callMarkMethod = true;
  13204. }
  13205. else if (checkType->IsSizedArray())
  13206. {
  13207. callMarkMethod = true;
  13208. }
  13209. else if (typeInstance != NULL)
  13210. {
  13211. typeInstance->mTypeDef->PopulateMemberSets();
  13212. BfMemberSetEntry* entry = NULL;
  13213. BfMethodDef* methodDef = NULL;
  13214. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(String(BF_METHODNAME_MARKMEMBERS), &entry))
  13215. {
  13216. methodDef = (BfMethodDef*)entry->mMemberDef;
  13217. if (methodDef->HasBody())
  13218. {
  13219. callMarkMethod = true;
  13220. }
  13221. }
  13222. }
  13223. if (callMarkMethod)
  13224. {
  13225. BfTypedValue markValue;
  13226. auto memberType = checkType;
  13227. if (memberType->IsObjectOrInterface())
  13228. memberType = mContext->mBfObjectType; // Just to avoid that extra cast for the call itself
  13229. auto memberPtrType = CreatePointerType(memberType);
  13230. if (curOffset == 0)
  13231. {
  13232. markValue = BfTypedValue(mBfIRBuilder->CreateBitCast(thisValue.mValue, mBfIRBuilder->MapType(memberPtrType)), memberType, true);
  13233. }
  13234. else
  13235. {
  13236. if (!thisValue.mType->IsPointer())
  13237. {
  13238. auto int8Type = GetPrimitiveType(BfTypeCode_UInt8);
  13239. auto int8PtrType = CreatePointerType(int8Type);
  13240. thisValue = BfTypedValue(mBfIRBuilder->CreateBitCast(thisValue.mValue, mBfIRBuilder->MapType(int8PtrType)), int8PtrType);
  13241. }
  13242. auto offsetValue = mBfIRBuilder->CreateInBoundsGEP(thisValue.mValue, curOffset);
  13243. markValue = BfTypedValue(mBfIRBuilder->CreateBitCast(offsetValue, mBfIRBuilder->MapType(memberPtrType)), memberType, true);
  13244. }
  13245. EmitGCMarkValue(markValue, markFromGCThreadMethodInstance);
  13246. return;
  13247. }
  13248. auto methodDef = mCurMethodInstance->mMethodDef;
  13249. if (checkType->IsPayloadEnum())
  13250. {
  13251. for (auto& fieldInst : typeInstance->mFieldInstances)
  13252. {
  13253. if (!fieldInst.mIsEnumPayloadCase)
  13254. continue;
  13255. auto fieldDef = fieldInst.GetFieldDef();
  13256. EmitGCMarkValue(thisValue, fieldInst.mResolvedType, memberDepth + 1, curOffset, objectOffsets, markFromGCThreadMethodInstance);
  13257. }
  13258. return;
  13259. }
  13260. if (typeInstance == NULL)
  13261. return;
  13262. for (auto& fieldInst : typeInstance->mFieldInstances)
  13263. {
  13264. auto fieldDef = fieldInst.GetFieldDef();
  13265. if (fieldDef == NULL)
  13266. continue;
  13267. if (fieldDef->mIsStatic)
  13268. continue;
  13269. if (typeInstance == mCurTypeInstance)
  13270. {
  13271. // Note: we don't do method chaining when we are marking members of members. Theoretically this means
  13272. // we may be marking member values that can never contain a value anyway, but this is benign
  13273. if ((fieldDef->mDeclaringType->mTypeDeclaration != methodDef->mDeclaringType->mTypeDeclaration))
  13274. continue;
  13275. }
  13276. EmitGCMarkValue(thisValue, fieldInst.mResolvedType, memberDepth + 1, curOffset + fieldInst.mDataOffset, objectOffsets, markFromGCThreadMethodInstance);
  13277. }
  13278. if ((typeInstance->mBaseType != NULL) && (typeInstance->mBaseType != mContext->mBfObjectType))
  13279. {
  13280. EmitGCMarkValue(thisValue, typeInstance->mBaseType, memberDepth, curOffset, objectOffsets, markFromGCThreadMethodInstance);
  13281. }
  13282. }
  13283. void BfModule::EmitGCMarkMembers()
  13284. {
  13285. auto methodDef = mCurMethodInstance->mMethodDef;
  13286. auto gcType = ResolveTypeDef(mCompiler->mGCTypeDef, BfPopulateType_DataAndMethods);
  13287. BfModuleMethodInstance markFromGCThreadMethodInstance;
  13288. if (gcType != NULL)
  13289. markFromGCThreadMethodInstance = GetMethodByName(gcType->ToTypeInstance(), "Mark", 1);
  13290. if ((markFromGCThreadMethodInstance.mMethodInstance != NULL) && (!mCurMethodInstance->mIsUnspecialized))
  13291. {
  13292. if (mCurTypeInstance->IsBoxed())
  13293. {
  13294. // This already gets filled in by the normal boxed forwarding
  13295. }
  13296. else
  13297. {
  13298. auto thisValue = GetThis();
  13299. if (thisValue.IsSplat())
  13300. {
  13301. BfIRFunction func = mCurMethodInstance->mIRFunction;
  13302. int argIdx = 0;
  13303. std::function<void(BfType*)> checkTypeLambda = [&](BfType* checkType)
  13304. {
  13305. if (checkType->IsStruct())
  13306. {
  13307. auto checkTypeInstance = checkType->ToTypeInstance();
  13308. if (checkTypeInstance->mBaseType != NULL)
  13309. checkTypeLambda(checkTypeInstance->mBaseType);
  13310. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  13311. {
  13312. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  13313. if (fieldInstance->mDataIdx >= 0)
  13314. checkTypeLambda(fieldInstance->GetResolvedType());
  13315. }
  13316. }
  13317. else if (checkType->IsMethodRef())
  13318. {
  13319. BF_FATAL("Not handled");
  13320. }
  13321. else if (checkType->WantsGCMarking())
  13322. {
  13323. BfTypedValue markValue(mBfIRBuilder->GetArgument(argIdx), checkType);
  13324. EmitGCMarkValue(markValue, markFromGCThreadMethodInstance);
  13325. argIdx++;
  13326. }
  13327. };
  13328. checkTypeLambda(thisValue.mType);
  13329. }
  13330. else if (!methodDef->mIsStatic)
  13331. {
  13332. if ((mCurTypeInstance->mBaseType != NULL) && (!mCurTypeInstance->IsTypedPrimitive()) && (mCurTypeInstance->mBaseType->WantsGCMarking()))
  13333. {
  13334. BfModuleMethodInstance moduleMethodInst = GetMethodByName(mCurTypeInstance->mBaseType, BF_METHODNAME_MARKMEMBERS, 0, true);
  13335. if (moduleMethodInst)
  13336. {
  13337. auto methodBaseType = moduleMethodInst.mMethodInstance->GetOwner();
  13338. if (methodBaseType != mContext->mBfObjectType)
  13339. {
  13340. auto thisValue = GetThis();
  13341. auto baseValue = Cast(NULL, thisValue, methodBaseType, BfCastFlags_Explicit);
  13342. SizedArray<BfIRValue, 1> args;
  13343. if (moduleMethodInst.mMethodInstance->GetParamIsSplat(-1))
  13344. {
  13345. BfExprEvaluator exprEvaluator(this);
  13346. exprEvaluator.SplatArgs(baseValue, args);
  13347. }
  13348. else
  13349. {
  13350. args.push_back(baseValue.mValue);
  13351. }
  13352. mBfIRBuilder->CreateCall(moduleMethodInst.mFunc, args);
  13353. }
  13354. }
  13355. }
  13356. }
  13357. if (!methodDef->mIsStatic)
  13358. {
  13359. HashSet<int> objectOffsets;
  13360. EmitGCMarkValue(thisValue, mCurTypeInstance, 0, 0, objectOffsets, markFromGCThreadMethodInstance);
  13361. }
  13362. else
  13363. {
  13364. for (auto& fieldInst : mCurTypeInstance->mFieldInstances)
  13365. {
  13366. if (thisValue.IsSplat())
  13367. break;
  13368. auto fieldDef = fieldInst.GetFieldDef();
  13369. if (fieldDef == NULL)
  13370. continue;
  13371. if (fieldInst.mIsThreadLocal)
  13372. continue;
  13373. if (fieldDef->mIsStatic == methodDef->mIsStatic)
  13374. {
  13375. // For extensions, only handle these fields in the appropriate extension
  13376. if ((fieldDef->mDeclaringType->mTypeDeclaration != methodDef->mDeclaringType->mTypeDeclaration))
  13377. continue;
  13378. if (!fieldInst.mFieldIncluded)
  13379. continue;
  13380. auto fieldTypeInst = fieldInst.mResolvedType->ToTypeInstance();
  13381. if (fieldTypeInst != NULL)
  13382. {
  13383. auto fieldDef = fieldInst.GetFieldDef();
  13384. BfTypedValue markVal;
  13385. if (fieldDef->mIsConst)
  13386. continue;
  13387. if ((!fieldTypeInst->IsObjectOrInterface()) && (!fieldTypeInst->IsComposite()))
  13388. continue;
  13389. mBfIRBuilder->PopulateType(fieldTypeInst);
  13390. if (fieldTypeInst->IsValuelessType())
  13391. continue;
  13392. if ((fieldDef->mIsStatic) && (!fieldDef->mIsConst))
  13393. {
  13394. markVal = ReferenceStaticField(&fieldInst);
  13395. }
  13396. else if (!fieldDef->mIsStatic)
  13397. {
  13398. markVal = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(thisValue.mValue, 0, fieldInst.mDataIdx/*, fieldDef->mName*/), fieldInst.mResolvedType, true);
  13399. }
  13400. if (markVal)
  13401. EmitGCMarkValue(markVal, markFromGCThreadMethodInstance);
  13402. }
  13403. }
  13404. }
  13405. }
  13406. if (mCurMethodInstance->mChainType == BfMethodChainType_ChainHead)
  13407. CallChainedMethods(mCurMethodInstance, false);
  13408. }
  13409. }
  13410. }
  13411. void BfModule::EmitGCFindTLSMembers()
  13412. {
  13413. auto methodDef = mCurMethodInstance->mMethodDef;
  13414. auto gcTypeInst = ResolveTypeDef(mCompiler->mGCTypeDef)->ToTypeInstance();
  13415. auto reportTLSMark = GetMethodByName(gcTypeInst, "ReportTLSMember", 2);
  13416. BF_ASSERT(reportTLSMark);
  13417. for (auto& fieldInst : mCurTypeInstance->mFieldInstances)
  13418. {
  13419. auto fieldDef = fieldInst.GetFieldDef();
  13420. if (fieldDef == NULL)
  13421. continue;
  13422. if (!fieldInst.mIsThreadLocal)
  13423. continue;
  13424. // For extensions, only handle these fields in the appropriate extension
  13425. if ((fieldDef->mDeclaringType->mTypeDeclaration != methodDef->mDeclaringType->mTypeDeclaration))
  13426. continue;
  13427. if (!fieldInst.mFieldIncluded)
  13428. continue;
  13429. if (fieldDef->mIsConst)
  13430. continue;
  13431. auto fieldType = fieldInst.mResolvedType;
  13432. if ((!fieldType->IsObjectOrInterface()) && (!fieldType->IsComposite()))
  13433. continue;
  13434. if (fieldType->IsValuelessType())
  13435. continue;
  13436. BfTypedValue markVal = ReferenceStaticField(&fieldInst);
  13437. if (markVal)
  13438. {
  13439. BfIRValue fieldRefPtr = mBfIRBuilder->CreateBitCast(markVal.mValue, mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr)));
  13440. BfIRValue markFuncPtr = GetMarkFuncPtr(fieldType);
  13441. SizedArray<BfIRValue, 2> llvmArgs;
  13442. llvmArgs.push_back(fieldRefPtr);
  13443. llvmArgs.push_back(markFuncPtr);
  13444. mBfIRBuilder->CreateCall(reportTLSMark.mFunc, llvmArgs);
  13445. }
  13446. }
  13447. if (mCurMethodInstance->mChainType == BfMethodChainType_ChainHead)
  13448. CallChainedMethods(mCurMethodInstance, false);
  13449. }
  13450. void BfModule::ProcessMethod(BfMethodInstance* methodInstance, bool isInlineDup)
  13451. {
  13452. BP_ZONE_F("BfModule::ProcessMethod %s", BP_DYN_STR(methodInstance->mMethodDef->mName.c_str()));
  13453. if (mAwaitingInitFinish)
  13454. FinishInit();
  13455. if (!methodInstance->mIsReified)
  13456. BF_ASSERT(!mIsReified);
  13457. if (methodInstance->mMethodInfoEx != NULL)
  13458. {
  13459. for (auto methodGenericArg : methodInstance->mMethodInfoEx->mMethodGenericArguments)
  13460. {
  13461. if (methodGenericArg->IsMethodRef())
  13462. {
  13463. auto methodRefType = (BfMethodRefType*)methodGenericArg;
  13464. BF_ASSERT(methodRefType->mOwnerRevision == methodRefType->mOwner->mRevision);
  13465. }
  13466. }
  13467. }
  13468. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, mWantsIRIgnoreWrites || methodInstance->mIsUnspecialized);
  13469. bool ignoreWrites = mBfIRBuilder->mIgnoreWrites;
  13470. if ((HasCompiledOutput()) && (!mBfIRBuilder->mIgnoreWrites))
  13471. {
  13472. BF_ASSERT(!methodInstance->mIRFunction.IsFake() || (methodInstance->GetImportCallKind() != BfImportCallKind_None));
  13473. }
  13474. SetAndRestoreValue<BfSourceClassifier*> prevSourceClassifier;
  13475. if (((methodInstance->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend) || (methodInstance->mIsForeignMethodDef) || (methodInstance->IsSpecializedGenericMethod())) &&
  13476. (mCompiler->mResolvePassData != NULL))
  13477. {
  13478. // Don't classify on the CtorCalcAppend, just on the actual Ctor
  13479. prevSourceClassifier.Init(mCompiler->mResolvePassData->mSourceClassifier, NULL);
  13480. }
  13481. if (methodInstance->mHasBeenProcessed)
  13482. {
  13483. BfLogSysM("ProcessMethod %p HasBeenProcessed\n", methodInstance);
  13484. return;
  13485. }
  13486. if (methodInstance->mFailedConstraints)
  13487. {
  13488. // The only way this should be able to happen is if we fail our generic param check
  13489. BF_ASSERT(methodInstance->IsSpecializedGenericMethod());
  13490. BfLogSysM("Method instance marked as 'failed' at start of ProcessMethod %p\n", methodInstance);
  13491. methodInstance->mHasBeenProcessed = true;
  13492. return;
  13493. }
  13494. BfMethodInstance* defaultMethodInstance = methodInstance->mMethodInstanceGroup->mDefault;
  13495. BF_ASSERT(methodInstance->mMethodInstanceGroup->mOnDemandKind != BfMethodOnDemandKind_NotSet);
  13496. if ((methodInstance->mMethodInstanceGroup->mOnDemandKind != BfMethodOnDemandKind_AlwaysInclude) &&
  13497. (methodInstance->mMethodInstanceGroup->mOnDemandKind != BfMethodOnDemandKind_Referenced))
  13498. {
  13499. methodInstance->mMethodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_Referenced;
  13500. auto owningModule = methodInstance->GetOwner()->mModule;
  13501. if (owningModule->mIsScratchModule)
  13502. {
  13503. BF_ASSERT(owningModule->mOnDemandMethodCount == 0);
  13504. }
  13505. else
  13506. {
  13507. BF_ASSERT((owningModule->mOnDemandMethodCount > 0) || (!HasCompiledOutput()) || (owningModule->mExtensionCount > 0));
  13508. if (owningModule->mOnDemandMethodCount > 0)
  13509. owningModule->mOnDemandMethodCount--;
  13510. }
  13511. }
  13512. // We set mHasBeenProcessed to true immediately -- this helps avoid stack overflow during recursion for things like
  13513. // self-referencing append allocations in ctor@calcAppend
  13514. methodInstance->mHasBeenProcessed = true;
  13515. mIncompleteMethodCount--;
  13516. BF_ASSERT((mIsSpecialModule) || (mIncompleteMethodCount >= 0));
  13517. auto typeDef = methodInstance->mMethodInstanceGroup->mOwner->mTypeDef;
  13518. auto methodDef = methodInstance->mMethodDef;
  13519. auto methodDeclaration = methodDef->GetMethodDeclaration();
  13520. if ((methodInstance->mIsReified) && (methodInstance->mVirtualTableIdx != -1))
  13521. {
  13522. // If we reify a virtual method in a HotCompile then we need to make sure the type data gets written out
  13523. // so we get the new vdata for it
  13524. methodInstance->GetOwner()->mDirty = true;
  13525. }
  13526. int dependentGenericStartIdx = 0;
  13527. if (methodDef->mIsLocalMethod) // See DoMethodDeclaration for an explaination of dependentGenericStartIdx
  13528. dependentGenericStartIdx = (int)mCurMethodState->GetRootMethodState()->mMethodInstance->GetNumGenericArguments();
  13529. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, methodInstance);
  13530. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, methodInstance->mMethodInstanceGroup->mOwner);
  13531. SetAndRestoreValue<BfFilePosition> prevFilePos(mCurFilePosition);
  13532. SetAndRestoreValue<bool> prevHadBuildError(mHadBuildError, false);
  13533. SetAndRestoreValue<bool> prevHadWarning(mHadBuildWarning, false);
  13534. SetAndRestoreValue<bool> prevIgnoreWarnings(mIgnoreWarnings, false);
  13535. if ((methodInstance->mIsReified) &&
  13536. ((methodDef->mMethodType == BfMethodType_Ctor) || (methodDef->mMethodType == BfMethodType_CtorNoBody)))
  13537. {
  13538. mCurTypeInstance->mHasBeenInstantiated = true;
  13539. }
  13540. // Warnings are shown in the capture phase
  13541. if ((methodDef->mIsLocalMethod) || (mCurTypeInstance->IsClosure()))
  13542. mIgnoreWarnings = true;
  13543. if ((methodDeclaration == NULL) && (mCurMethodState == NULL))
  13544. UseDefaultSrcPos();
  13545. // We may not actually be populated in relatively rare autocompelte cases
  13546. PopulateType(mCurTypeInstance, BfPopulateType_DataAndMethods);
  13547. mBfIRBuilder->PopulateType(mCurTypeInstance, BfIRPopulateType_Full);
  13548. BfAstNode* nameNode = NULL;
  13549. if (methodDeclaration != NULL)
  13550. {
  13551. nameNode = methodDeclaration->mNameNode;
  13552. if (nameNode == NULL)
  13553. {
  13554. if (auto ctorDeclaration = BfNodeDynCast<BfConstructorDeclaration>(methodDeclaration))
  13555. nameNode = ctorDeclaration->mThisToken;
  13556. }
  13557. }
  13558. if ((mCompiler->mResolvePassData != NULL) && (methodDeclaration != NULL) && (nameNode != NULL) &&
  13559. (mCompiler->mResolvePassData->mGetSymbolReferenceKind == BfGetSymbolReferenceKind_Method) && (methodDef->mIdx >= 0))
  13560. {
  13561. if (methodInstance->GetExplicitInterface() == NULL)
  13562. mCompiler->mResolvePassData->HandleMethodReference(nameNode, typeDef, methodDef);
  13563. else
  13564. {
  13565. for (auto& ifaceEntry : mCurTypeInstance->mInterfaces)
  13566. {
  13567. auto ifaceInst = ifaceEntry.mInterfaceType;
  13568. int startIdx = ifaceEntry.mStartInterfaceTableIdx;
  13569. int iMethodCount = (int)ifaceInst->mMethodInstanceGroups.size();
  13570. if (methodInstance->GetExplicitInterface() != ifaceInst)
  13571. continue;
  13572. ifaceInst->mTypeDef->PopulateMemberSets();
  13573. BfMethodDef* nextMethod = NULL;
  13574. BfMemberSetEntry* entry = NULL;
  13575. if (ifaceInst->mTypeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  13576. nextMethod = (BfMethodDef*)entry->mMemberDef;
  13577. while (nextMethod != NULL)
  13578. {
  13579. auto checkMethod = nextMethod;
  13580. nextMethod = nextMethod->mNextWithSameName;
  13581. BfMethodInstance* implMethodInst = mCurTypeInstance->mInterfaceMethodTable[startIdx + checkMethod->mIdx].mMethodRef;
  13582. if (implMethodInst == methodInstance)
  13583. {
  13584. auto ifaceMethodDef = ifaceInst->mTypeDef->mMethods[checkMethod->mIdx];
  13585. mCompiler->mResolvePassData->HandleMethodReference(nameNode, ifaceInst->mTypeDef, ifaceMethodDef);
  13586. }
  13587. }
  13588. }
  13589. }
  13590. if (methodDef->mIsOverride)
  13591. {
  13592. for (int virtIdx = 0; virtIdx < (int)mCurTypeInstance->mVirtualMethodTable.size(); virtIdx++)
  13593. {
  13594. auto& ventry = mCurTypeInstance->mVirtualMethodTable[virtIdx];
  13595. if (ventry.mDeclaringMethod.mMethodNum == -1)
  13596. continue;
  13597. BfMethodInstance* virtMethod = ventry.mImplementingMethod;
  13598. if (virtMethod != NULL)
  13599. {
  13600. if (virtMethod == methodInstance)
  13601. {
  13602. // Is matching method
  13603. if (virtIdx < (int)mCurTypeInstance->mBaseType->mVirtualMethodTable.size())
  13604. {
  13605. auto baseType = mCurTypeInstance->mBaseType;
  13606. if (baseType != NULL)
  13607. {
  13608. while ((baseType->mBaseType != NULL) && (virtIdx < baseType->mBaseType->mVirtualMethodTableSize))
  13609. baseType = baseType->mBaseType;
  13610. BfMethodInstance* baseVirtMethod = baseType->mVirtualMethodTable[virtIdx].mImplementingMethod;
  13611. mCompiler->mResolvePassData->HandleMethodReference(nameNode, baseType->mTypeDef, baseVirtMethod->mMethodDef);
  13612. }
  13613. }
  13614. break;
  13615. }
  13616. }
  13617. }
  13618. }
  13619. }
  13620. BfLogSysM("ProcessMethod %p Unspecialized: %d Module: %p IRFunction: %d Reified: %d\n", methodInstance, mCurTypeInstance->IsUnspecializedType(), this, methodInstance->mIRFunction.mId, methodInstance->mIsReified);
  13621. if (methodInstance->GetImportCallKind() != BfImportCallKind_None)
  13622. {
  13623. if (mBfIRBuilder->mIgnoreWrites)
  13624. return;
  13625. BfLogSysM("DllImportGlobalVar processing %p\n", methodInstance);
  13626. if (!methodInstance->mIRFunction)
  13627. {
  13628. BfIRValue dllImportGlobalVar = CreateDllImportGlobalVar(methodInstance, true);
  13629. methodInstance->mIRFunction = mBfIRBuilder->GetFakeVal();
  13630. mFuncReferences[mCurMethodInstance] = dllImportGlobalVar;
  13631. }
  13632. if (HasCompiledOutput())
  13633. {
  13634. BfDllImportEntry dllImportEntry;
  13635. dllImportEntry.mFuncVar = methodInstance->mIRFunction;
  13636. dllImportEntry.mMethodInstance = mCurMethodInstance;
  13637. mDllImportEntries.push_back(dllImportEntry);
  13638. }
  13639. return;
  13640. }
  13641. StringT<128> mangledName;
  13642. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), mCurMethodInstance);
  13643. if (!methodInstance->mIRFunction)
  13644. {
  13645. bool isIntrinsic = false;
  13646. SetupIRFunction(methodInstance, mangledName, false, &isIntrinsic);
  13647. }
  13648. if (methodInstance->mIsIntrinsic)
  13649. return;
  13650. auto prevActiveFunction = mBfIRBuilder->GetActiveFunction();
  13651. mBfIRBuilder->SetActiveFunction(mCurMethodInstance->mIRFunction);
  13652. if (methodDef->mBody != NULL)
  13653. UpdateSrcPos(methodDef->mBody, BfSrcPosFlag_NoSetDebugLoc);
  13654. else if (methodDeclaration != NULL)
  13655. UpdateSrcPos(methodDeclaration, BfSrcPosFlag_NoSetDebugLoc);
  13656. else if (mCurTypeInstance->mTypeDef->mTypeDeclaration != NULL)
  13657. UpdateSrcPos(mCurTypeInstance->mTypeDef->mTypeDeclaration, BfSrcPosFlag_NoSetDebugLoc);
  13658. if (mCurMethodState == NULL) // Only do initial classify for the 'outer' method state, not any local methods or lambdas
  13659. {
  13660. if ((mCompiler->mIsResolveOnly) && (methodDef->mBody != NULL) && (!mCurTypeInstance->IsBoxed()) &&
  13661. (methodDef->mBody->IsFromParser(mCompiler->mResolvePassData->mParser)) && (mCompiler->mResolvePassData->mSourceClassifier != NULL))
  13662. {
  13663. mCompiler->mResolvePassData->mSourceClassifier->VisitChildNoRef(methodDef->mBody);
  13664. }
  13665. }
  13666. BfHotDataReferenceBuilder hotDataReferenceBuilder;
  13667. BfMethodState methodState;
  13668. if (mCurMethodState != NULL)
  13669. methodState.mClosureState = mCurMethodState->mClosureState;
  13670. if ((mCompiler->mOptions.mAllowHotSwapping) && (methodInstance->mIsReified) && (!methodInstance->mIsUnspecialized) && (!isInlineDup))
  13671. {
  13672. //BF_ASSERT(methodInstance->mHotMethod != NULL);
  13673. if (methodInstance->mHotMethod == NULL)
  13674. CheckHotMethod(methodInstance, mangledName);
  13675. methodState.mHotDataReferenceBuilder = &hotDataReferenceBuilder;
  13676. }
  13677. methodState.mPrevMethodState = mCurMethodState;
  13678. methodState.mMethodInstance = methodInstance;
  13679. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  13680. if (methodInstance->GetCustomAttributes() != NULL)
  13681. {
  13682. int typeOptionsIdx = GenerateTypeOptions(methodInstance->GetCustomAttributes(), mCurTypeInstance, false);
  13683. if (typeOptionsIdx != -1)
  13684. methodState.mMethodTypeOptions = mSystem->GetTypeOptions(typeOptionsIdx);
  13685. }
  13686. BfTypeState typeState(mCurTypeInstance);
  13687. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  13688. bool isGenericVariation = (methodInstance->mIsUnspecializedVariation) || (mCurTypeInstance->IsUnspecializedTypeVariation());
  13689. BfMethodInstance* unspecializedMethodInstance = NULL;
  13690. if ((prevMethodState.mPrevVal != NULL) &&
  13691. ((methodState.mClosureState == NULL) || (methodState.mClosureState->mActiveDeferredLocalMethod == NULL)))
  13692. {
  13693. // This is 'inner' (probably a closure) - use binding from outer function
  13694. methodState.mGenericTypeBindings = prevMethodState.mPrevVal->mGenericTypeBindings;
  13695. }
  13696. else if ((methodInstance->mIsUnspecialized) ||
  13697. ((mCurTypeInstance->IsUnspecializedType()) && (!isGenericVariation)))
  13698. {
  13699. methodState.mGenericTypeBindings = &methodInstance->GetMethodInfoEx()->mGenericTypeBindings;
  13700. }
  13701. else if ((((methodInstance->mMethodInfoEx != NULL) && ((int)methodInstance->mMethodInfoEx->mMethodGenericArguments.size() > dependentGenericStartIdx)) ||
  13702. ((mCurTypeInstance->IsGenericTypeInstance()) && (!isGenericVariation))))
  13703. {
  13704. unspecializedMethodInstance = GetUnspecializedMethodInstance(methodInstance);
  13705. BF_ASSERT(unspecializedMethodInstance != methodInstance);
  13706. if (!unspecializedMethodInstance->mHasBeenProcessed)
  13707. {
  13708. // Make sure the unspecialized method is processed so we can take its bindings
  13709. // Clear mCurMethodState so we don't think we're in a local method
  13710. SetAndRestoreValue<BfMethodState*> prevMethodState_Unspec(mCurMethodState, prevMethodState.mPrevVal);
  13711. mContext->ProcessMethod(unspecializedMethodInstance);
  13712. }
  13713. methodState.mGenericTypeBindings = &unspecializedMethodInstance->GetMethodInfoEx()->mGenericTypeBindings;
  13714. }
  13715. if (methodDef->mMethodType == BfMethodType_Operator)
  13716. {
  13717. auto operatorDef = (BfOperatorDef*) methodDef;
  13718. BfAstNode* refNode = operatorDef->mOperatorDeclaration->mOperatorToken;
  13719. auto paramErrorRefNode = refNode;
  13720. if (operatorDef->mOperatorDeclaration->mOpenParen != NULL)
  13721. paramErrorRefNode = operatorDef->mOperatorDeclaration->mOpenParen;
  13722. if ((mCurMethodInstance->GetParamCount() > 0) && (mCurMethodInstance->GetParamTypeRef(0) != NULL))
  13723. paramErrorRefNode = mCurMethodInstance->GetParamTypeRef(0);
  13724. if (operatorDef->mOperatorDeclaration->mBinOp != BfBinaryOp_None)
  13725. {
  13726. if (methodDef->mParams.size() != 2)
  13727. {
  13728. Fail("Binary operators must declare two parameters", paramErrorRefNode);
  13729. }
  13730. else
  13731. {
  13732. if ((mCurMethodInstance->GetParamType(0) != mCurTypeInstance) && (!mCurMethodInstance->GetParamType(0)->IsSelf()) &&
  13733. (mCurMethodInstance->GetParamType(1) != mCurTypeInstance) && (!mCurMethodInstance->GetParamType(1)->IsSelf()))
  13734. {
  13735. Fail("At least one of the parameters of a binary operator must be the containing type", paramErrorRefNode);
  13736. }
  13737. }
  13738. BfType* wantType = NULL;
  13739. if (operatorDef->mOperatorDeclaration->mBinOp == BfBinaryOp_Compare)
  13740. {
  13741. wantType = GetPrimitiveType(BfTypeCode_IntPtr);
  13742. }
  13743. if ((wantType != NULL) && (methodInstance->mReturnType != wantType))
  13744. Fail(StrFormat("The return type for the '%s' operator must be '%s'", BfGetOpName(operatorDef->mOperatorDeclaration->mBinOp),
  13745. TypeToString(wantType).c_str()), operatorDef->mOperatorDeclaration->mReturnType);
  13746. }
  13747. else if (operatorDef->mOperatorDeclaration->mUnaryOp != BfUnaryOp_None)
  13748. {
  13749. if (methodDef->mParams.size() != 1)
  13750. {
  13751. Fail("Unary operators must declare one parameter", paramErrorRefNode);
  13752. }
  13753. else if ((mCurMethodInstance->GetParamType(0) != mCurTypeInstance) && (!mCurMethodInstance->GetParamType(0)->IsSelf()))
  13754. {
  13755. Fail("The parameter of a unary operator must be the containing type", paramErrorRefNode);
  13756. }
  13757. if (((operatorDef->mOperatorDeclaration->mUnaryOp == BfUnaryOp_Increment) ||
  13758. (operatorDef->mOperatorDeclaration->mUnaryOp == BfUnaryOp_Decrement)) &&
  13759. (!TypeIsSubTypeOf(mCurMethodInstance->mReturnType->ToTypeInstance(), mCurTypeInstance)))
  13760. {
  13761. Fail("The return type for the '++' or '--' operator must match the parameter type or be derived from the parameter type", operatorDef->mOperatorDeclaration->mReturnType);
  13762. }
  13763. }
  13764. else if (operatorDef->mOperatorDeclaration->mAssignOp != BfAssignmentOp_None)
  13765. {
  13766. if (methodDef->mParams.size() != 1)
  13767. {
  13768. Fail("Assignment operators must declare one parameter", paramErrorRefNode);
  13769. }
  13770. if (mCurMethodInstance->mReturnType->IsVoid())
  13771. {
  13772. Fail("The return type for assignment operator must be 'void'", operatorDef->mOperatorDeclaration->mReturnType);
  13773. }
  13774. }
  13775. else // Conversion
  13776. {
  13777. if (!operatorDef->mOperatorDeclaration->mIsConvOperator)
  13778. {
  13779. if (operatorDef->mOperatorDeclaration->mReturnType != NULL)
  13780. Fail("Conversion operators must declare their target type after the 'operator' token, not before", operatorDef->mOperatorDeclaration->mReturnType);
  13781. }
  13782. if (methodDef->mParams.size() != 1)
  13783. {
  13784. auto refNode = paramErrorRefNode;
  13785. if (!operatorDef->mOperatorDeclaration->mCommas.empty())
  13786. refNode = operatorDef->mOperatorDeclaration->mCommas[0];
  13787. Fail("Conversion operators must declare one parameter", refNode);
  13788. }
  13789. else
  13790. {
  13791. if ((mCurMethodInstance->GetParamType(0) != mCurTypeInstance) && (!mCurMethodInstance->GetParamType(0)->IsSelf()) &&
  13792. (mCurMethodInstance->mReturnType != mCurTypeInstance) && (!mCurMethodInstance->mReturnType->IsSelf()))
  13793. Fail("User-defined conversion must convert to or from the enclosing type", paramErrorRefNode);
  13794. if (mCurMethodInstance->GetParamType(0) == mCurMethodInstance->mReturnType)
  13795. Fail("User-defined operator cannot take an object of the enclosing type and convert to an object of the enclosing type", operatorDef->mOperatorDeclaration->mReturnType);
  13796. // On type lookup error we default to 'object', so don't do the 'base class' error if that may have
  13797. // happened here
  13798. if ((!mHadBuildError) || ((mCurMethodInstance->mReturnType != mContext->mBfObjectType) && (mCurMethodInstance->GetParamType(0) != mContext->mBfObjectType)))
  13799. {
  13800. auto isToBase = TypeIsSubTypeOf(mCurTypeInstance->mBaseType, mCurMethodInstance->mReturnType->ToTypeInstance());
  13801. bool isFromBase = TypeIsSubTypeOf(mCurTypeInstance->mBaseType, mCurMethodInstance->GetParamType(0)->ToTypeInstance());
  13802. if ((mCurTypeInstance->IsObject()) && (isToBase || isFromBase))
  13803. Fail("User-defined conversions to or from a base class are not allowed", paramErrorRefNode);
  13804. else if ((mCurTypeInstance->IsStruct()) && (isToBase))
  13805. Fail("User-defined conversions to a base struct are not allowed", paramErrorRefNode);
  13806. }
  13807. }
  13808. }
  13809. }
  13810. bool wantsDIData = (mBfIRBuilder->DbgHasInfo()) && (!methodDef->IsEmptyPartial()) && (!mCurMethodInstance->mIsUnspecialized) && (mHasFullDebugInfo);
  13811. if (methodDef->mMethodType == BfMethodType_Mixin)
  13812. wantsDIData = false;
  13813. if ((mCurTypeInstance->IsBoxed()) && (methodDef->mMethodType != BfMethodType_Ctor))
  13814. wantsDIData = false;
  13815. bool wantsDIVariables = wantsDIData;
  13816. if (methodDef->mIsExtern)
  13817. wantsDIVariables = false;
  13818. SizedArray<BfIRMDNode, 8> diParams;
  13819. diParams.push_back(mBfIRBuilder->DbgGetType(methodInstance->mReturnType));
  13820. bool isThisStruct = mCurTypeInstance->IsStruct() && !mCurTypeInstance->IsTypedPrimitive();
  13821. BfType* thisType = NULL;
  13822. if (!methodDef->mIsStatic)
  13823. {
  13824. if ((methodState.mClosureState != NULL) && (methodState.mClosureState->mClosureType != NULL))
  13825. thisType = methodState.mClosureState->mClosureType;
  13826. else
  13827. thisType = mCurTypeInstance;
  13828. }
  13829. PopulateType(methodInstance->mReturnType, BfPopulateType_Data);
  13830. ProcessMethod_SetupParams(methodInstance, thisType, wantsDIData, &diParams);
  13831. //////////////////////////////////////////////////////////////////////////
  13832. //
  13833. {
  13834. if (methodDeclaration != NULL)
  13835. UpdateSrcPos(methodDeclaration, BfSrcPosFlag_NoSetDebugLoc);
  13836. else if (methodDef->mBody != NULL)
  13837. UpdateSrcPos(methodDef->mBody, BfSrcPosFlag_NoSetDebugLoc);
  13838. else if (mCurTypeInstance->mTypeDef->mTypeDeclaration != NULL)
  13839. UpdateSrcPos(mCurTypeInstance->mTypeDef->mTypeDeclaration, BfSrcPosFlag_NoSetDebugLoc);
  13840. }
  13841. BfIRMDNode diFunction;
  13842. if (wantsDIData)
  13843. {
  13844. BP_ZONE("BfModule::BfMethodDeclaration.DISetup");
  13845. BfIRMDNode diFuncType = mBfIRBuilder->DbgCreateSubroutineType(diParams);
  13846. int defLine = mCurFilePosition.mCurLine;
  13847. if (mDICompileUnit)
  13848. {
  13849. int flags = 0;
  13850. BfIRMDNode funcScope = mBfIRBuilder->DbgGetTypeInst(mCurTypeInstance);
  13851. if (methodDef->mProtection == BfProtection_Public)
  13852. flags = llvm::DINode::FlagPublic;
  13853. else if (methodDef->mProtection == BfProtection_Protected)
  13854. flags = llvm::DINode::FlagProtected;
  13855. else
  13856. flags = llvm::DINode::FlagPrivate;
  13857. if (methodDef->mIsOverride)
  13858. {
  13859. //flags |= llvm::DINode::FlagVirtual;
  13860. }
  13861. else if (methodDef->mIsVirtual)
  13862. flags |= llvm::DINode::FlagIntroducedVirtual;
  13863. if ((methodDef->mIsStatic) || (methodDef->mMethodType == BfMethodType_Mixin))
  13864. flags |= llvm::DINode::FlagStaticMember;
  13865. else
  13866. {
  13867. if ((mCurTypeInstance->IsValuelessType()) || (mCurTypeInstance->IsSplattable()))
  13868. flags |= llvm::DINode::FlagStaticMember;
  13869. }
  13870. flags |= llvm::DINode::FlagPrototyped;
  13871. if (methodDef->mMethodType == BfMethodType_Ctor)
  13872. {
  13873. flags |= llvm::DINode::FlagArtificial;
  13874. }
  13875. auto llvmFunction = methodInstance->mIRFunction;
  13876. SizedArray<BfIRMDNode, 1> genericArgs;
  13877. SizedArray<BfIRValue, 1> genericConstValueArgs;
  13878. String methodName;
  13879. if (methodInstance->GetForeignType() != NULL)
  13880. {
  13881. methodName += TypeToString(methodInstance->GetForeignType());
  13882. methodName += ".";
  13883. }
  13884. if (methodInstance->GetExplicitInterface() != NULL)
  13885. {
  13886. methodName += TypeToString(methodInstance->GetExplicitInterface());
  13887. methodName += ".";
  13888. }
  13889. methodName += methodDef->mName;
  13890. if (methodInstance->GetNumGenericArguments() != 0)
  13891. {
  13892. for (auto genericArg : methodInstance->mMethodInfoEx->mMethodGenericArguments)
  13893. {
  13894. if (genericArg->IsConstExprValue())
  13895. {
  13896. BfConstExprValueType* constExprValueType = (BfConstExprValueType*)genericArg;
  13897. while (genericConstValueArgs.size() < genericArgs.size())
  13898. genericConstValueArgs.push_back(BfIRValue());
  13899. genericConstValueArgs.push_back(mBfIRBuilder->CreateConst(BfTypeCode_UInt64, constExprValueType->mValue.mUInt64));
  13900. genericArgs.push_back(mBfIRBuilder->DbgGetType(GetPrimitiveType(BfTypeCode_Int64)));
  13901. }
  13902. else
  13903. genericArgs.push_back(mBfIRBuilder->DbgGetType(genericArg));
  13904. }
  13905. methodName += "<";
  13906. for (int i = 0; i < (int)methodInstance->mMethodInfoEx->mMethodGenericArguments.size(); i++)
  13907. {
  13908. if (i > 0)
  13909. methodName += ", ";
  13910. BfType* type = methodInstance->mMethodInfoEx->mMethodGenericArguments[i];
  13911. methodName += TypeToString(type);
  13912. }
  13913. methodName += ">";
  13914. }
  13915. if ((methodName.empty()) && (methodDeclaration != NULL))
  13916. {
  13917. if (auto operatorDecl = BfNodeDynCast<BfOperatorDeclaration>(methodDeclaration))
  13918. {
  13919. methodName += "operator";
  13920. if (operatorDecl->mIsConvOperator)
  13921. {
  13922. methodName += " ";
  13923. methodName += TypeToString(methodInstance->mReturnType);
  13924. }
  13925. else if (operatorDecl->mOpTypeToken != NULL)
  13926. methodName += operatorDecl->mOpTypeToken->ToString();
  13927. }
  13928. }
  13929. methodState.mDIFile = mCurFilePosition.mFileInstance->mDIFile;
  13930. // diFunction = mBfIRBuilder->DbgCreateMethod(funcScope, methodName, mangledName, methodState.mDIFile,
  13931. // defLine + 1, diFuncType, false, true,
  13932. // (methodInstance->mVirtualTableIdx != -1) ? llvm::dwarf::DW_VIRTUALITY_virtual : llvm::dwarf::DW_VIRTUALITY_none,
  13933. // (methodInstance->mVirtualTableIdx != -1) ? methodInstance->DbgGetVirtualMethodNum() : 0,
  13934. // nullptr, flags, IsOptimized(), llvmFunction, genericArgs, genericConstValueArgs);
  13935. diFunction = mBfIRBuilder->DbgCreateMethod(funcScope, methodName, mangledName, methodState.mDIFile,
  13936. defLine + 1, diFuncType, false, true,
  13937. llvm::dwarf::DW_VIRTUALITY_none,
  13938. 0,
  13939. nullptr, flags, IsOptimized(), llvmFunction, genericArgs, genericConstValueArgs);
  13940. }
  13941. }
  13942. //////////////////////////////////////////////////////////////////////////
  13943. // Head and Init get rolled into Entry afterwards.
  13944. methodState.mIRFunction = methodInstance->mIRFunction;
  13945. methodState.mIRHeadBlock = mBfIRBuilder->CreateBlock("head", true);
  13946. methodState.mIRInitBlock = mBfIRBuilder->CreateBlock("init", true);
  13947. methodState.mIREntryBlock = mBfIRBuilder->CreateBlock("entry", true);
  13948. methodState.mCurScope->mDIScope = diFunction;
  13949. auto llvmEntryBlock = methodState.mIREntryBlock;
  13950. mBfIRBuilder->SetInsertPoint(llvmEntryBlock);
  13951. if (methodDef->mBody != NULL)
  13952. {
  13953. UpdateSrcPos(methodDef->mBody, BfSrcPosFlag_NoSetDebugLoc);
  13954. }
  13955. else if ((mHasFullDebugInfo) && (diFunction) && (typeDef->mTypeDeclaration != NULL))
  13956. {
  13957. // We want to be able to step into delegate invokes -- we actually step over them
  13958. if (methodDef->mName != "Invoke")
  13959. {
  13960. UpdateSrcPos(typeDef->mTypeDeclaration);
  13961. mBfIRBuilder->DbgCreateAnnotation(diFunction, "StepOver", GetConstValue32(1));
  13962. }
  13963. }
  13964. // Clear out DebugLoc - to mark the ".addr" code as part of prologue
  13965. mBfIRBuilder->ClearDebugLocation();
  13966. bool isTypedPrimitiveFunc = mCurTypeInstance->IsTypedPrimitive() && (methodDef->mMethodType != BfMethodType_Ctor);
  13967. int irParamCount = methodInstance->GetIRFunctionParamCount(this);
  13968. if (methodDef->mImportKind != BfImportKind_Dynamic)
  13969. {
  13970. int localIdx = 0;
  13971. int argIdx = 0;
  13972. if (methodInstance->HasStructRet())
  13973. argIdx++;
  13974. //
  13975. bool doDbgAgg = false;
  13976. Array<BfIRValue> splatAddrValues;
  13977. for ( ; argIdx < irParamCount; localIdx++)
  13978. {
  13979. bool isThis = ((localIdx == 0) && (!mCurMethodInstance->mMethodDef->mIsStatic));
  13980. if ((isThis) && (thisType->IsValuelessType()))
  13981. isThis = false;
  13982. BfLocalVariable* paramVar = NULL;
  13983. while (true)
  13984. {
  13985. BF_ASSERT(localIdx < methodState.mLocals.size());
  13986. paramVar = methodState.mLocals[localIdx];
  13987. if ((paramVar->mCompositeCount == -1) &&
  13988. ((!paramVar->mResolvedType->IsValuelessType()) || (paramVar->mResolvedType->IsMethodRef())))
  13989. break;
  13990. localIdx++;
  13991. }
  13992. if ((isThis) && (mCurTypeInstance->IsValueType()) && (methodDef->mMethodType != BfMethodType_Ctor) && (!methodDef->HasNoThisSplat()))
  13993. {
  13994. paramVar->mIsReadOnly = true;
  13995. }
  13996. bool wantsAddr = (wantsDIVariables) || (!paramVar->mIsReadOnly) || (paramVar->mResolvedType->GetLoweredType() != BfTypeCode_None);
  13997. if (paramVar->mResolvedType->IsMethodRef())
  13998. wantsAddr = false;
  13999. // if ((methodDef->mHasAppend) && (argIdx == 1))
  14000. // {
  14001. // BF_ASSERT(paramVar->mName == "appendIdx");
  14002. // wantsAddr = true;
  14003. // }
  14004. if ((!doDbgAgg) && (paramVar->mIsSplat))
  14005. {
  14006. auto prevInsert = mBfIRBuilder->GetInsertBlock();
  14007. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  14008. BfTypeUtils::SplatIterate([&](BfType* checkType)
  14009. {
  14010. BfIRType splatIRType;
  14011. if (checkType->IsComposite())
  14012. splatIRType = mBfIRBuilder->MapType(CreatePointerType(checkType));
  14013. else
  14014. splatIRType = mBfIRBuilder->MapType(checkType);
  14015. auto allocaInst = mBfIRBuilder->CreateAlloca(splatIRType);
  14016. mBfIRBuilder->SetAllocaAlignment(allocaInst, checkType->mAlign);
  14017. if (!paramVar->mAddr)
  14018. paramVar->mAddr = allocaInst;
  14019. if (WantsLifetimes())
  14020. mCurMethodState->mCurScope->mDeferredLifetimeEnds.push_back(allocaInst);
  14021. splatAddrValues.push_back(allocaInst);
  14022. }, paramVar->mResolvedType);
  14023. mBfIRBuilder->SetInsertPoint(prevInsert);
  14024. }
  14025. else if (isThis)
  14026. {
  14027. if (wantsAddr)
  14028. {
  14029. auto prevInsert = mBfIRBuilder->GetInsertBlock();
  14030. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  14031. BfIRType thisAddrType = mBfIRBuilder->MapType(thisType);
  14032. if (paramVar->mIsSplat)
  14033. {
  14034. if (doDbgAgg)
  14035. {
  14036. auto allocaInst = mBfIRBuilder->CreateAlloca(thisAddrType);
  14037. mBfIRBuilder->SetName(allocaInst, paramVar->mName + ".addr");
  14038. mBfIRBuilder->SetAllocaAlignment(allocaInst, thisType->mAlign);
  14039. paramVar->mAddr = allocaInst;
  14040. if (WantsLifetimes())
  14041. mCurMethodState->mCurScope->mDeferredLifetimeEnds.push_back(allocaInst);
  14042. }
  14043. }
  14044. else
  14045. {
  14046. bool wantPtr = (thisType->IsComposite()) && (!paramVar->mIsLowered);
  14047. if ((thisType->IsTypedPrimitive()) && (methodDef->HasNoThisSplat()))
  14048. wantPtr = true;
  14049. if (wantPtr)
  14050. {
  14051. thisAddrType = mBfIRBuilder->MapTypeInstPtr(thisType->ToTypeInstance());
  14052. }
  14053. auto allocaInst = mBfIRBuilder->CreateAlloca(thisAddrType);
  14054. mBfIRBuilder->SetName(allocaInst, paramVar->mName + ".addr");
  14055. mBfIRBuilder->SetAllocaAlignment(allocaInst, mSystem->mPtrSize);
  14056. paramVar->mAddr = allocaInst;
  14057. if (WantsLifetimes())
  14058. mCurMethodState->mCurScope->mDeferredLifetimeEnds.push_back(allocaInst);
  14059. }
  14060. mBfIRBuilder->SetInsertPoint(prevInsert);
  14061. }
  14062. }
  14063. else if ((!isThis) && ((paramVar->mIsStruct) || (paramVar->mResolvedType->IsRef())))
  14064. {
  14065. // Address doesn't change so we don't have to alloca it
  14066. BfIRType allocType;
  14067. int alignSize = mSystem->mPtrSize;
  14068. if (paramVar->mResolvedType->IsRef())
  14069. {
  14070. allocType = mBfIRBuilder->MapType(paramVar->mResolvedType);
  14071. }
  14072. else if ((paramVar->mIsSplat) || (paramVar->mIsLowered))
  14073. {
  14074. allocType = mBfIRBuilder->MapType(paramVar->mResolvedType);
  14075. alignSize = paramVar->mResolvedType->mAlign;
  14076. }
  14077. else
  14078. {
  14079. paramVar->mHasLocalStructBacking = true;
  14080. auto typeInst = paramVar->mResolvedType->ToTypeInstance();
  14081. if (typeInst != NULL)
  14082. allocType = mBfIRBuilder->MapTypeInstPtr(paramVar->mResolvedType->ToTypeInstance());
  14083. else
  14084. allocType = mBfIRBuilder->MapType(CreatePointerType(paramVar->mResolvedType));
  14085. }
  14086. if (wantsAddr)
  14087. {
  14088. auto prevInsert = mBfIRBuilder->GetInsertBlock();
  14089. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  14090. mBfIRBuilder->PopulateType(paramVar->mResolvedType);
  14091. auto allocaInst = mBfIRBuilder->CreateAlloca(allocType);
  14092. mBfIRBuilder->SetName(allocaInst, paramVar->mName + ".addr");
  14093. mBfIRBuilder->SetAllocaAlignment(allocaInst, alignSize);
  14094. paramVar->mAddr = allocaInst;
  14095. mBfIRBuilder->SetInsertPoint(prevInsert);
  14096. if (WantsLifetimes())
  14097. mCurMethodState->mCurScope->mDeferredLifetimeEnds.push_back(allocaInst);
  14098. }
  14099. }
  14100. else if (wantsAddr)
  14101. {
  14102. auto allocaInst = CreateAlloca(paramVar->mResolvedType);
  14103. mBfIRBuilder->SetName(allocaInst, paramVar->mName + ".addr");
  14104. paramVar->mAddr = allocaInst;
  14105. }
  14106. if (paramVar->mIsSplat)
  14107. {
  14108. BfTypeUtils::SplatIterate([&](BfType* checkType) { argIdx++; }, paramVar->mResolvedType);
  14109. }
  14110. else
  14111. {
  14112. argIdx++;
  14113. }
  14114. }
  14115. if (methodDef->mBody != NULL)
  14116. UpdateSrcPos(methodDef->mBody);
  14117. else if (mCurTypeInstance->mTypeDef->mTypeDeclaration != NULL)
  14118. UpdateSrcPos(mCurTypeInstance->mTypeDef->mTypeDeclaration);
  14119. int declArgIdx = 0;
  14120. localIdx = 0;
  14121. argIdx = 0;
  14122. if (methodInstance->HasStructRet())
  14123. argIdx++;
  14124. int splatAddrIdx = 0;
  14125. while (localIdx < (int)methodState.mLocals.size())
  14126. {
  14127. int curLocalIdx = localIdx++;
  14128. BfLocalVariable* paramVar = methodState.mLocals[curLocalIdx];
  14129. if (!paramVar->IsParam())
  14130. continue;
  14131. if (paramVar->mCompositeCount != -1)
  14132. continue;
  14133. bool isThis = ((curLocalIdx == 0) && (!mCurMethodInstance->mMethodDef->mIsStatic));
  14134. if ((isThis) && (thisType->IsValuelessType()))
  14135. isThis = false;
  14136. BfIRMDNode diVariable;
  14137. if (wantsDIData)
  14138. {
  14139. String paramName = paramVar->mName;
  14140. BfIRMDNode diType = mBfIRBuilder->DbgGetType(paramVar->mResolvedType);
  14141. if (isThis)
  14142. {
  14143. if ((mCurMethodState->mClosureState != NULL) && (mCurMethodState->mClosureState->mClosureType != NULL))
  14144. paramName = "__closure";
  14145. if ((paramVar->mResolvedType->IsValueType()) && (!paramVar->mIsSplat) && (!paramVar->mIsLowered))
  14146. {
  14147. diType = mBfIRBuilder->DbgGetType(paramVar->mResolvedType);
  14148. bool wantRef = paramVar->mResolvedType->IsComposite();
  14149. if ((paramVar->mResolvedType->IsTypedPrimitive()) && (methodDef->HasNoThisSplat()))
  14150. wantRef = true;
  14151. if (wantRef)
  14152. diType = mBfIRBuilder->DbgCreateReferenceType(diType);
  14153. }
  14154. else if (!paramVar->mResolvedType->IsValueType())
  14155. {
  14156. diType = mBfIRBuilder->DbgCreateArtificialType(diType);
  14157. }
  14158. }
  14159. else
  14160. {
  14161. if ((paramVar->mResolvedType->IsComposite()) && (!paramVar->mIsSplat) && (!paramVar->mIsLowered))
  14162. {
  14163. diType = mBfIRBuilder->DbgGetType(paramVar->mResolvedType);
  14164. diType = mBfIRBuilder->DbgCreateReferenceType(diType);
  14165. diType = mBfIRBuilder->DbgCreateConstType(diType);
  14166. }
  14167. }
  14168. if ((!paramVar->mIsSplat) || (doDbgAgg))
  14169. {
  14170. if (paramVar->mResolvedType->IsValuelessType())
  14171. {
  14172. diVariable = mBfIRBuilder->DbgCreateAutoVariable(diFunction,
  14173. paramName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType);
  14174. }
  14175. else if (paramVar->mIsImplicitParam)
  14176. {
  14177. // Annotate this specially?
  14178. diVariable = mBfIRBuilder->DbgCreateParameterVariable(diFunction,
  14179. paramName, argIdx + 1, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType, true, 0);
  14180. }
  14181. else
  14182. {
  14183. diVariable = mBfIRBuilder->DbgCreateParameterVariable(diFunction,
  14184. paramName, argIdx + 1, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType, true, 0);
  14185. }
  14186. paramVar->mDbgVarInst = diVariable;
  14187. }
  14188. else if ((paramVar->mIsSplat) && (paramVar->mResolvedType->GetSplatCount() == 0))
  14189. {
  14190. // if ((mBfIRBuilder->HasDebugLocation()) && (wantsDIVariables))
  14191. // {
  14192. // // Only add this placeholder if we don't have any values
  14193. // auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(mCurMethodState->mCurScope->mDIScope,
  14194. // paramName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType);
  14195. // mBfIRBuilder->DbgInsertValueIntrinsic(GetConstValue(0), diVariable);
  14196. // }
  14197. }
  14198. }
  14199. bool isTypedPrimCtor = mCurTypeInstance->IsTypedPrimitive() && (methodDef->mMethodType == BfMethodType_Ctor);
  14200. if ((!paramVar->mParamFailed) && (paramVar->mAddr))
  14201. {
  14202. // Write our argument value into the .addr
  14203. mBfIRBuilder->ClearDebugLocation();
  14204. if (paramVar->mIsSplat)
  14205. {
  14206. mBfIRBuilder->PopulateType(paramVar->mResolvedType);
  14207. if (doDbgAgg)
  14208. {
  14209. auto curArgIdx = argIdx;
  14210. std::function<void(BfType*, BfIRValue)> checkTypeLambda = [&](BfType* checkType, BfIRValue curDestAddr)
  14211. {
  14212. if (checkType->IsStruct())
  14213. {
  14214. auto checkTypeInstance = checkType->ToTypeInstance();
  14215. if (checkTypeInstance->mBaseType != NULL)
  14216. {
  14217. auto baseDestAddr = mBfIRBuilder->CreateBitCast(curDestAddr, mBfIRBuilder->MapTypeInstPtr(checkTypeInstance->mBaseType));
  14218. checkTypeLambda(checkTypeInstance->mBaseType, baseDestAddr);
  14219. }
  14220. if (checkTypeInstance->mIsUnion)
  14221. {
  14222. auto unionInnerType = checkTypeInstance->GetUnionInnerType();
  14223. if (!unionInnerType->IsValuelessType())
  14224. {
  14225. auto newDestAddr = mBfIRBuilder->CreateInBoundsGEP(curDestAddr, 0, 1);
  14226. checkTypeLambda(unionInnerType, newDestAddr);
  14227. }
  14228. if (checkTypeInstance->IsEnum())
  14229. {
  14230. auto dscrType = checkTypeInstance->GetDiscriminatorType();
  14231. auto newDestAddr = mBfIRBuilder->CreateInBoundsGEP(curDestAddr, 0, 2);
  14232. checkTypeLambda(dscrType, newDestAddr);
  14233. }
  14234. }
  14235. else
  14236. {
  14237. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  14238. {
  14239. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  14240. if (fieldInstance->mDataIdx >= 0)
  14241. {
  14242. auto newDestAddr = mBfIRBuilder->CreateInBoundsGEP(curDestAddr, 0, fieldInstance->mDataIdx);
  14243. checkTypeLambda(fieldInstance->GetResolvedType(), newDestAddr);
  14244. }
  14245. }
  14246. }
  14247. }
  14248. else if (checkType->IsMethodRef())
  14249. {
  14250. BF_FATAL("Unimplemented");
  14251. // BfMethodRefType* methodRefType = (BfMethodRefType*)checkType;
  14252. // for (int dataIdx = 0; dataIdx < methodRefType->GetCaptureDataCount(); dataIdx++)
  14253. // {
  14254. // checkTypeLambda->
  14255. // }
  14256. }
  14257. else if (!checkType->IsValuelessType())
  14258. {
  14259. mBfIRBuilder->CreateAlignedStore(mBfIRBuilder->GetArgument(curArgIdx), curDestAddr, paramVar->mResolvedType->mAlign);
  14260. curArgIdx++;
  14261. }
  14262. };
  14263. checkTypeLambda(paramVar->mResolvedType, paramVar->mAddr);
  14264. }
  14265. }
  14266. else
  14267. {
  14268. bool handled = false;
  14269. //if ((!isThis) || (!methodDef->mIsMutating && !methodDef->mNoSplat))
  14270. if (paramVar->mIsLowered)
  14271. {
  14272. auto loweredTypeCode = paramVar->mResolvedType->GetLoweredType();
  14273. BF_ASSERT(loweredTypeCode != BfTypeCode_None);
  14274. if (loweredTypeCode != BfTypeCode_None)
  14275. {
  14276. // We have a lowered type coming in, so we have to cast the .addr before storing
  14277. auto primType = GetPrimitiveType(loweredTypeCode);
  14278. auto primPtrType = CreatePointerType(primType);
  14279. auto primPtrVal = mBfIRBuilder->CreateBitCast(paramVar->mAddr, mBfIRBuilder->MapType(primPtrType));
  14280. mBfIRBuilder->CreateAlignedStore(paramVar->mValue, primPtrVal, paramVar->mResolvedType->mSize);
  14281. // We don't want to allow directly using value
  14282. paramVar->mValue = BfIRValue();
  14283. handled = true;
  14284. }
  14285. }
  14286. if (!handled)
  14287. mBfIRBuilder->CreateAlignedStore(paramVar->mValue, paramVar->mAddr, paramVar->mResolvedType->mAlign);
  14288. }
  14289. }
  14290. if (!isThis)
  14291. declArgIdx++;
  14292. if (methodDef->mBody != NULL)
  14293. UpdateSrcPos(methodDef->mBody);
  14294. else if (methodDef->mDeclaringType->mTypeDeclaration != NULL)
  14295. UpdateSrcPos(methodDef->mDeclaringType->mTypeDeclaration);
  14296. else if (methodDeclaration == NULL)
  14297. UseDefaultSrcPos();
  14298. // Write our argument value into the .addr
  14299. if ((!doDbgAgg) && (paramVar->mIsSplat))
  14300. {
  14301. int splatComponentIdx = 0;
  14302. auto curArgIdx = argIdx;
  14303. auto _FinishSplats = [&] (BfType* checkType, const StringImpl& name)
  14304. {
  14305. BfIRValue splatAddrValue = splatAddrValues[splatAddrIdx++];
  14306. methodState.mSplatDecompAddrs.push_back(splatAddrValue);
  14307. auto storeInst = mBfIRBuilder->CreateAlignedStore(mBfIRBuilder->GetArgument(curArgIdx), splatAddrValue, checkType->mAlign);
  14308. mBfIRBuilder->ClearDebugLocation(storeInst);
  14309. if (wantsDIData)
  14310. {
  14311. BfIRMDNode diType;
  14312. if (checkType->IsComposite())
  14313. diType = mBfIRBuilder->DbgGetType(CreateRefType(checkType));
  14314. else
  14315. diType = mBfIRBuilder->DbgGetType(checkType);
  14316. auto diVariable = mBfIRBuilder->DbgCreateParameterVariable(diFunction,
  14317. name, curArgIdx + 1, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType);
  14318. if (wantsDIVariables)
  14319. {
  14320. mBfIRBuilder->DbgInsertDeclare(splatAddrValue, diVariable);
  14321. }
  14322. }
  14323. curArgIdx++;
  14324. splatComponentIdx++;
  14325. };
  14326. std::function<void(BfType*, const StringImpl&)> _FinishSplatsIterate = [&](BfType* checkType, const StringImpl& name)
  14327. {
  14328. if (checkType->IsStruct())
  14329. {
  14330. auto checkTypeInstance = checkType->ToTypeInstance();
  14331. if (checkTypeInstance->mBaseType != NULL)
  14332. {
  14333. _FinishSplatsIterate(checkTypeInstance->mBaseType, name + "$b");
  14334. }
  14335. if (checkTypeInstance->mIsUnion)
  14336. {
  14337. auto unionInnerType = checkTypeInstance->GetUnionInnerType();
  14338. if (!unionInnerType->IsValuelessType())
  14339. {
  14340. _FinishSplatsIterate(unionInnerType, name + "$u");
  14341. }
  14342. if (checkTypeInstance->IsEnum())
  14343. {
  14344. auto dscrType = checkTypeInstance->GetDiscriminatorType();
  14345. _FinishSplatsIterate(dscrType, name + "$d");
  14346. }
  14347. }
  14348. else
  14349. {
  14350. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  14351. {
  14352. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  14353. auto fieldDef = fieldInstance->GetFieldDef();
  14354. if (fieldInstance->mDataIdx >= 0)
  14355. {
  14356. _FinishSplatsIterate(fieldInstance->GetResolvedType(), name + "$m$" + fieldDef->mName);
  14357. }
  14358. }
  14359. }
  14360. }
  14361. else if (checkType->IsMethodRef())
  14362. {
  14363. auto methodRefType = (BfMethodRefType*)checkType;
  14364. BfMethodInstance* methodInstance = methodRefType->mMethodRef;
  14365. // int implicitParamCount = methodInstance->GetImplicitParamCount();
  14366. // for (int implicitParamIdx = methodInstance->HasThis() ? -1 : 0; implicitParamIdx < implicitParamCount; implicitParamIdx++)
  14367. // {
  14368. // auto paramType = methodInstance->GetParamType(implicitParamIdx);
  14369. // if (!paramType->IsValuelessType())
  14370. // _FinishSplats(paramType, name + "$m$" + methodInstance->GetParamName(implicitParamIdx));
  14371. // }
  14372. for (int dataIdx = 0; dataIdx < methodRefType->GetCaptureDataCount(); dataIdx++)
  14373. {
  14374. int paramIdx = methodRefType->GetParamIdxFromDataIdx(dataIdx);
  14375. String paramName = methodInstance->GetParamName(paramIdx);
  14376. if (paramName == "this")
  14377. paramName = "__this";
  14378. if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  14379. {
  14380. _FinishSplatsIterate(methodRefType->GetCaptureType(dataIdx), name + "$m$" + paramName);
  14381. }
  14382. else
  14383. {
  14384. _FinishSplats(methodRefType->GetCaptureType(dataIdx), name + "$m$" + paramName);
  14385. }
  14386. }
  14387. }
  14388. else if (!checkType->IsValuelessType())
  14389. {
  14390. _FinishSplats(checkType, name);
  14391. }
  14392. };
  14393. mBfIRBuilder->PopulateType(paramVar->mResolvedType);
  14394. if (!paramVar->mConstValue)
  14395. _FinishSplatsIterate(paramVar->mResolvedType, "$" + paramVar->mName);
  14396. }
  14397. BfIRValue declareCall;
  14398. if (diVariable)
  14399. {
  14400. if ((mBfIRBuilder->HasDebugLocation()) && (wantsDIVariables))
  14401. {
  14402. if (!paramVar->mAddr)
  14403. {
  14404. if ((!paramVar->mValue) || (paramVar->mValue.IsFake()))
  14405. {
  14406. if ((!paramVar->mIsThis) && (mCompiler->mOptions.mToolsetType != BfToolsetType_GNU)) // DWARF chokes on this:
  14407. {
  14408. // We don't need to set the location for this
  14409. mBfIRBuilder->DbgInsertValueIntrinsic(BfIRValue(), diVariable);
  14410. }
  14411. }
  14412. else
  14413. declareCall = mBfIRBuilder->DbgInsertDeclare(paramVar->mValue, diVariable);
  14414. }
  14415. else
  14416. {
  14417. declareCall = mBfIRBuilder->DbgInsertDeclare(paramVar->mAddr, diVariable);
  14418. }
  14419. }
  14420. }
  14421. if ((isThis) && (!paramVar->mIsSplat) && (paramVar->mAddr))
  14422. {
  14423. // We don't allow actually assignment to "this", so we just do a single load
  14424. // Keep in mind we don't use the ACTUAL mValue value because that's a register, but
  14425. // we need to store it in the stack frame for debugging purposes
  14426. auto loadedThis = mBfIRBuilder->CreateLoad(paramVar->mAddr/*, "this"*/);
  14427. mBfIRBuilder->ClearDebugLocation(loadedThis);
  14428. paramVar->mValue = loadedThis;
  14429. }
  14430. if ((wantsDIData) && (declareCall))
  14431. mBfIRBuilder->UpdateDebugLocation(declareCall);
  14432. if (paramVar->mIsSplat)
  14433. {
  14434. BfTypeUtils::SplatIterate([&](BfType* checkType) { argIdx++; }, paramVar->mResolvedType);
  14435. }
  14436. else if (!paramVar->mResolvedType->IsValuelessType())
  14437. {
  14438. argIdx++;
  14439. }
  14440. }
  14441. if (wantsDIData)
  14442. {
  14443. BF_ASSERT(splatAddrIdx == (int)splatAddrValues.size());
  14444. }
  14445. }
  14446. for (int varIdx = 0; varIdx < (int)mCurMethodState->mLocals.size(); varIdx++)
  14447. {
  14448. auto paramVar = mCurMethodState->mLocals[varIdx];
  14449. // 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
  14450. // splat member. If the "splat" is valueless then we do create a placeholder, but further up in this method
  14451. // if (paramVar->mIsSplat)
  14452. // {
  14453. // if (wantsDIVariables)
  14454. // {
  14455. // auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(diFunction, paramVar->mName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, mBfIRBuilder->DbgGetType(paramVar->mResolvedType));
  14456. // mBfIRBuilder->DbgInsertValueIntrinsic(mBfIRBuilder->CreateConst(BfTypeCode_Int64, 0), diVariable);
  14457. // }
  14458. // }
  14459. if (paramVar->mResolvedType->IsValuelessType())
  14460. {
  14461. if ((mBfIRBuilder->HasDebugLocation()) && (wantsDIVariables) && (mCompiler->mOptions.mToolsetType != BfToolsetType_GNU)) // DWARF chokes on this:
  14462. {
  14463. // Only add this placeholder if we don't have any values
  14464. auto diType = mBfIRBuilder->DbgGetType(paramVar->mResolvedType);
  14465. auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(mCurMethodState->mCurScope->mDIScope,
  14466. paramVar->mName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType);
  14467. mBfIRBuilder->DbgInsertValueIntrinsic(BfIRValue(), diVariable);
  14468. }
  14469. }
  14470. }
  14471. if (IsTargetingBeefBackend())
  14472. mCurMethodState->mCurScope->mValueScopeStart = mBfIRBuilder->CreateValueScopeStart();
  14473. if (methodState.mClosureState != NULL)
  14474. {
  14475. for (auto& constLocal : methodState.mClosureState->mConstLocals)
  14476. {
  14477. BfLocalVariable* localVar = new BfLocalVariable();
  14478. *localVar = constLocal;
  14479. AddLocalVariableDef(localVar, true);
  14480. }
  14481. }
  14482. bool wantsRemoveBody = false;
  14483. bool skipBody = false;
  14484. bool skipUpdateSrcPos = false;
  14485. bool skipEndChecks = false;
  14486. bool hasExternSpecifier = (methodDeclaration != NULL) && (methodDeclaration->mExternSpecifier != NULL) && (methodDef->mImportKind != BfImportKind_Dynamic);
  14487. auto propertyDeclaration = methodDef->GetPropertyDeclaration();
  14488. if ((methodDef != NULL) && (propertyDeclaration != NULL) && (propertyDeclaration->mExternSpecifier != NULL))
  14489. hasExternSpecifier = true;
  14490. // Allocate, clear, set classVData
  14491. if ((methodDef->mMethodType == BfMethodType_Ctor) && (methodDef->mIsStatic))
  14492. {
  14493. CreateStaticCtor();
  14494. }
  14495. else if ((mCurTypeInstance->IsBoxed()) && (methodDef->mMethodType != BfMethodType_Ctor) && (methodDef->mName != BF_METHODNAME_DYNAMICCAST) && (methodDef->mName != BF_METHODNAME_DYNAMICCAST_INTERFACE))
  14496. {
  14497. skipBody = true;
  14498. skipEndChecks = true;
  14499. if (HasCompiledOutput())
  14500. {
  14501. // Clear out DebugLoc - to mark the ".addr" code as part of prologue
  14502. mBfIRBuilder->ClearDebugLocation();
  14503. BfBoxedType* boxedType = (BfBoxedType*) mCurTypeInstance;
  14504. BfTypeInstance* innerType = boxedType->mElementType;
  14505. PopulateType(innerType, BfPopulateType_DataAndMethods);
  14506. mBfIRBuilder->PopulateType(mCurTypeInstance);
  14507. BfGetMethodInstanceFlags flags = BfGetMethodInstanceFlag_None;
  14508. if (methodInstance->mIsForeignMethodDef)
  14509. {
  14510. flags = BfGetMethodInstanceFlag_ForeignMethodDef;
  14511. }
  14512. BfTypeVector methodGenericArguments;
  14513. if (methodInstance->mMethodInfoEx != NULL)
  14514. methodGenericArguments = methodInstance->mMethodInfoEx->mMethodGenericArguments;
  14515. auto innerMethodInstance = GetMethodInstance(innerType, methodDef, methodGenericArguments, flags, methodInstance->GetForeignType());
  14516. if (innerMethodInstance.mMethodInstance->IsSkipCall())
  14517. {
  14518. if (!methodInstance->mReturnType->IsValuelessType())
  14519. {
  14520. auto retVal = GetDefaultValue(methodInstance->mReturnType);
  14521. CreateReturn(retVal);
  14522. }
  14523. }
  14524. else
  14525. {
  14526. BF_ASSERT(innerMethodInstance.mMethodInstance->mMethodDef == methodDef);
  14527. SizedArray<BfIRValue, 8> innerParams;
  14528. BfExprEvaluator exprEvaluator(this);
  14529. if (!innerType->IsValuelessType())
  14530. {
  14531. BfIRValue thisValue = mBfIRBuilder->CreateInBoundsGEP(mCurMethodState->mLocals[0]->mValue, 0, 1);
  14532. BfTypedValue innerVal(thisValue, innerType, true);
  14533. if (boxedType->IsBoxedStructPtr())
  14534. {
  14535. innerVal = LoadValue(innerVal);
  14536. innerVal = BfTypedValue(innerVal.mValue, innerType, true);
  14537. }
  14538. exprEvaluator.PushThis(NULL, innerVal, innerMethodInstance.mMethodInstance, innerParams);
  14539. }
  14540. for (int i = 1; i < (int)mCurMethodState->mLocals.size(); i++)
  14541. {
  14542. BfLocalVariable* localVar = mCurMethodState->mLocals[i];
  14543. BfTypedValue localVal = exprEvaluator.LoadLocal(localVar, true);
  14544. exprEvaluator.PushArg(localVal, innerParams);
  14545. }
  14546. if (!innerMethodInstance.mFunc)
  14547. {
  14548. BF_ASSERT(innerType->IsUnspecializedType());
  14549. }
  14550. else if (methodInstance->HasStructRet())
  14551. {
  14552. mBfIRBuilder->PopulateType(methodInstance->mReturnType);
  14553. auto returnType = BfTypedValue(mBfIRBuilder->GetArgument(0), methodInstance->mReturnType, true);
  14554. exprEvaluator.mReceivingValue = &returnType;
  14555. auto retVal = exprEvaluator.CreateCall(innerMethodInstance.mMethodInstance, innerMethodInstance.mFunc, true, innerParams, NULL, true);
  14556. BF_ASSERT(exprEvaluator.mReceivingValue == NULL); // Ensure it was actually used
  14557. mBfIRBuilder->CreateRetVoid();
  14558. }
  14559. else
  14560. {
  14561. mBfIRBuilder->PopulateType(methodInstance->mReturnType);
  14562. auto retVal = exprEvaluator.CreateCall(innerMethodInstance.mMethodInstance, innerMethodInstance.mFunc, true, innerParams, NULL, true);
  14563. if (mCurMethodInstance->mReturnType->IsValueType())
  14564. retVal = LoadValue(retVal);
  14565. CreateReturn(retVal.mValue);
  14566. }
  14567. }
  14568. }
  14569. mCurMethodState->SetHadReturn(true);
  14570. mCurMethodState->mLeftBlockUncond = true;
  14571. }
  14572. else if (methodDef->mMethodType == BfMethodType_CtorClear)
  14573. {
  14574. SetIllegalSrcPos();
  14575. mBfIRBuilder->ClearDebugLocation();
  14576. PopulateType(mCurTypeInstance, BfPopulateType_Data);
  14577. auto thisVal = GetThis();
  14578. int prevSize = mContext->mBfObjectType->mInstSize;
  14579. int curSize = mCurTypeInstance->mInstSize;
  14580. if (curSize > prevSize)
  14581. {
  14582. auto int8PtrType = CreatePointerType(GetPrimitiveType(BfTypeCode_Int8));
  14583. auto int8PtrVal = mBfIRBuilder->CreateBitCast(thisVal.mValue, mBfIRBuilder->MapType(int8PtrType));
  14584. int8PtrVal = mBfIRBuilder->CreateInBoundsGEP(int8PtrVal, GetConstValue(prevSize));
  14585. mBfIRBuilder->CreateMemSet(int8PtrVal, GetConstValue8(0), GetConstValue(curSize - prevSize), GetConstValue(mCurTypeInstance->mInstAlign));
  14586. }
  14587. skipUpdateSrcPos = true;
  14588. }
  14589. else if (((methodDef->mMethodType == BfMethodType_Ctor) || (methodDef->mMethodType == BfMethodType_CtorNoBody)) && (!hasExternSpecifier))
  14590. {
  14591. EmitCtorBody(skipBody);
  14592. }
  14593. else if ((methodDef->mMethodType == BfMethodType_Dtor) && (!hasExternSpecifier))
  14594. {
  14595. EmitDtorBody();
  14596. skipBody = true;
  14597. }
  14598. if ((!mCurTypeInstance->IsBoxed()) && (methodDeclaration != NULL) && (methodDeclaration->mHadYield) && (methodDef->mBody != NULL))
  14599. {
  14600. EmitIteratorBlock(skipBody);
  14601. }
  14602. if (methodDef->mName == BF_METHODNAME_MARKMEMBERS)
  14603. {
  14604. // We need to be able to mark deleted objects
  14605. mCurMethodState->mIgnoreObjectAccessCheck = true;
  14606. }
  14607. auto customAttributes = methodInstance->GetCustomAttributes();
  14608. if ((customAttributes != NULL) && (customAttributes->Contains(mCompiler->mDisableObjectAccessChecksAttributeTypeDef)))
  14609. mCurMethodState->mIgnoreObjectAccessCheck = true;
  14610. if ((methodDef->mMethodType == BfMethodType_CtorNoBody) && (!methodDef->mIsStatic) &&
  14611. ((methodInstance->mChainType == BfMethodChainType_ChainHead) || (methodInstance->mChainType == BfMethodChainType_None)))
  14612. {
  14613. // We chain even non-default ctors to the default ctors
  14614. auto defaultCtor = methodInstance;
  14615. if (defaultCtor->mChainType == BfMethodChainType_ChainHead)
  14616. CallChainedMethods(defaultCtor, false);
  14617. }
  14618. auto bodyBlock = BfNodeDynCast<BfBlock>(methodDef->mBody);
  14619. if (methodDef->mBody == NULL)
  14620. {
  14621. if (methodDeclaration != NULL)
  14622. {
  14623. if (auto operatorDeclaration = BfNodeDynCast<BfOperatorDeclaration>(methodDeclaration))
  14624. {
  14625. if (operatorDeclaration->mIsConvOperator)
  14626. wantsRemoveBody = true;
  14627. }
  14628. }
  14629. bool isDllImport = false;
  14630. if (methodDef->mImportKind == BfImportKind_Static)
  14631. {
  14632. for (auto customAttr : methodInstance->GetCustomAttributes()->mAttributes)
  14633. {
  14634. if (customAttr.mType->mTypeDef->mFullName.ToString() == "System.ImportAttribute")
  14635. {
  14636. if (customAttr.mCtorArgs.size() == 1)
  14637. {
  14638. auto fileNameArg = customAttr.mCtorArgs[0];
  14639. int strNum = 0;
  14640. auto constant = mCurTypeInstance->mConstHolder->GetConstant(fileNameArg);
  14641. if (constant != NULL)
  14642. {
  14643. if (constant->IsNull())
  14644. continue; // Invalid
  14645. strNum = constant->mInt32;
  14646. }
  14647. else
  14648. {
  14649. strNum = GetStringPoolIdx(fileNameArg, mCurTypeInstance->mConstHolder);
  14650. }
  14651. if (!mImportFileNames.Contains(strNum))
  14652. mImportFileNames.Add(strNum);
  14653. }
  14654. }
  14655. }
  14656. //mImportFileNames
  14657. }
  14658. else if (methodDef->mImportKind == BfImportKind_Dynamic)
  14659. {
  14660. CreateDllImportMethod();
  14661. }
  14662. else if (((mCurTypeInstance->mTypeDef->mIsDelegate) || (mCurTypeInstance->mTypeDef->mIsFunction)) &&
  14663. (methodDef->mName == "Invoke") && (methodDef->mMethodType == BfMethodType_Normal))
  14664. {
  14665. if (mCurTypeInstance->mTypeDef->mIsFunction)
  14666. {
  14667. // Emit nothing
  14668. }
  14669. else
  14670. {
  14671. CreateDelegateInvokeMethod();
  14672. mCurMethodState->SetHadReturn(true);
  14673. mCurMethodState->mLeftBlockUncond = true;
  14674. }
  14675. }
  14676. else if ((methodDef->mName == BF_METHODNAME_DYNAMICCAST) || (methodDef->mName == BF_METHODNAME_DYNAMICCAST_INTERFACE))
  14677. {
  14678. if (mCurTypeInstance->IsObject())
  14679. {
  14680. CreateDynamicCastMethod();
  14681. }
  14682. else
  14683. {
  14684. mBfIRBuilder->CreateRet(GetDefaultValue(methodInstance->mReturnType));
  14685. mCurMethodState->mHadReturn = true;
  14686. }
  14687. }
  14688. else if ((methodDef->mName == BF_METHODNAME_ENUM_HASFLAG) && (mCurTypeInstance->IsEnum()) && (!mCurTypeInstance->IsBoxed()))
  14689. {
  14690. BfIRValue ret;
  14691. if (mCurMethodState->mLocals[1]->mResolvedType != mCurTypeInstance)
  14692. {
  14693. // This can happen if we provide an invalid name
  14694. AssertErrorState();
  14695. ret = mBfIRBuilder->CreateRet(GetDefaultValue(GetPrimitiveType(BfTypeCode_Boolean)));
  14696. }
  14697. else
  14698. {
  14699. // Unfortunate DebugLoc shenanigans-
  14700. // 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,
  14701. // so we only set the loc on the CreateRet which gets inlined out
  14702. mBfIRBuilder->SaveDebugLocation();
  14703. mBfIRBuilder->ClearDebugLocation();
  14704. BfIRValue fromBool;
  14705. if (!mCurTypeInstance->IsTypedPrimitive())
  14706. {
  14707. fromBool = GetDefaultValue(methodInstance->mReturnType);
  14708. }
  14709. else
  14710. {
  14711. auto andResult = mBfIRBuilder->CreateAnd(mCurMethodState->mLocals[0]->mValue, mCurMethodState->mLocals[1]->mValue);
  14712. auto toBool = mBfIRBuilder->CreateCmpNE(andResult, GetDefaultValue(mCurMethodState->mLocals[0]->mResolvedType));
  14713. fromBool = mBfIRBuilder->CreateNumericCast(toBool, false, BfTypeCode_Boolean);
  14714. }
  14715. mBfIRBuilder->RestoreDebugLocation();
  14716. ret = mBfIRBuilder->CreateRet(fromBool);
  14717. //ExtendLocalLifetimes(0);
  14718. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  14719. }
  14720. mCurMethodState->SetHadReturn(true);
  14721. mCurMethodState->mLeftBlockUncond = true;
  14722. }
  14723. else if (((methodDef->mName == BF_METHODNAME_ENUM_GETUNDERLYINGREF) || (methodDef->mName == BF_METHODNAME_ENUM_GETUNDERLYING)) &&
  14724. (mCurTypeInstance->IsEnum()) && (!mCurTypeInstance->IsBoxed()))
  14725. {
  14726. BfIRValue ret;
  14727. // Unfortunate DebugLoc shenanigans-
  14728. // 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,
  14729. // so we only set the loc on the CreateRet which gets inlined out
  14730. mBfIRBuilder->SaveDebugLocation();
  14731. mBfIRBuilder->ClearDebugLocation();
  14732. BfIRValue fromBool;
  14733. mBfIRBuilder->RestoreDebugLocation();
  14734. ret = mBfIRBuilder->CreateRet(GetThis().mValue);
  14735. //ExtendLocalLifetimes(0);
  14736. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  14737. mCurMethodState->SetHadReturn(true);
  14738. mCurMethodState->mLeftBlockUncond = true;
  14739. }
  14740. else if ((mCurTypeInstance->IsEnum()) && (!mCurTypeInstance->IsBoxed()) && (methodDef->mName == BF_METHODNAME_TO_STRING))
  14741. {
  14742. auto enumType = ResolveTypeDef(mCompiler->mEnumTypeDef);
  14743. if (HasCompiledOutput())
  14744. {
  14745. EmitEnumToStringBody();
  14746. }
  14747. mBfIRBuilder->CreateRetVoid();
  14748. mCurMethodState->SetHadReturn(true);
  14749. mCurMethodState->mLeftBlockUncond = true;
  14750. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  14751. }
  14752. else if ((mCurTypeInstance->IsTuple()) && (!mCurTypeInstance->IsBoxed()) && (methodDef->mName == BF_METHODNAME_TO_STRING))
  14753. {
  14754. auto enumType = ResolveTypeDef(mCompiler->mEnumTypeDef);
  14755. if (HasCompiledOutput())
  14756. {
  14757. EmitTupleToStringBody();
  14758. }
  14759. mBfIRBuilder->CreateRetVoid();
  14760. mCurMethodState->SetHadReturn(true);
  14761. mCurMethodState->mLeftBlockUncond = true;
  14762. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  14763. }
  14764. else if (methodDef->mName == BF_METHODNAME_DEFAULT_EQUALS)
  14765. {
  14766. CreateValueTypeEqualsMethod();
  14767. skipBody = true;
  14768. skipEndChecks = true;
  14769. }
  14770. else if ((methodDef->mName == BF_METHODNAME_EQUALS) && (typeDef == mCompiler->mValueTypeTypeDef))
  14771. {
  14772. CreateValueTypeEqualsMethod();
  14773. skipBody = true;
  14774. skipEndChecks = true;
  14775. }
  14776. else if (HasCompiledOutput())
  14777. {
  14778. if ((methodDef->mName == BF_METHODNAME_MARKMEMBERS) || (methodDef->mName == BF_METHODNAME_MARKMEMBERS_STATIC))
  14779. {
  14780. if (mCompiler->mOptions.mEnableRealtimeLeakCheck)
  14781. {
  14782. EmitGCMarkMembers();
  14783. }
  14784. else if (!mCurTypeInstance->IsObject())
  14785. {
  14786. }
  14787. }
  14788. else if (methodDef->mName == BF_METHODNAME_FIND_TLS_MEMBERS)
  14789. {
  14790. if (mCompiler->mOptions.mEnableRealtimeLeakCheck)
  14791. {
  14792. EmitGCFindTLSMembers();
  14793. }
  14794. }
  14795. }
  14796. }
  14797. else if (!skipBody)
  14798. {
  14799. bool isEmptyBodied = BfNodeDynCast<BfTokenNode>(methodDef->mBody) != NULL;
  14800. if (isEmptyBodied) // Generate autoProperty things
  14801. {
  14802. auto propertyDeclaration = methodDef->GetPropertyDeclaration();
  14803. if ((propertyDeclaration != NULL) && (!typeDef->HasAutoProperty(propertyDeclaration)))
  14804. {
  14805. if ((!mCurTypeInstance->IsInterface()) && (!hasExternSpecifier))
  14806. Fail("Body expected", methodDef->mBody);
  14807. }
  14808. else if (methodDef->mMethodType == BfMethodType_PropertyGetter)
  14809. {
  14810. if (methodInstance->mReturnType->IsValuelessType())
  14811. {
  14812. mBfIRBuilder->CreateRetVoid();
  14813. }
  14814. else if (HasCompiledOutput())
  14815. {
  14816. String autoPropName = typeDef->GetAutoPropertyName(propertyDeclaration);
  14817. BfFieldInstance* fieldInstance = GetFieldByName(mCurTypeInstance, autoPropName);
  14818. BfFieldDef* fieldDef = NULL;
  14819. if (fieldInstance != NULL)
  14820. fieldDef = fieldInstance->GetFieldDef();
  14821. BfType* retType = methodInstance->mReturnType;
  14822. if (retType->IsRef())
  14823. retType = retType->GetUnderlyingType();
  14824. if ((fieldInstance != NULL) && (fieldInstance->GetResolvedType() == retType) &&
  14825. ((fieldInstance->mDataIdx >= 0) || (fieldDef->IsNonConstStatic())))
  14826. {
  14827. BfTypedValue lookupValue;
  14828. if (fieldDef->IsNonConstStatic())
  14829. lookupValue = ReferenceStaticField(fieldInstance);
  14830. else if (mCurTypeInstance->IsObject())
  14831. lookupValue = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(GetThis().mValue, 0, fieldInstance->mDataIdx), fieldInstance->mResolvedType, true);
  14832. else
  14833. lookupValue = ExtractValue(GetThis(), fieldInstance, fieldInstance->mFieldIdx);
  14834. if (!methodInstance->mReturnType->IsRef())
  14835. lookupValue = LoadValue(lookupValue);
  14836. mBfIRBuilder->CreateRet(lookupValue.mValue);
  14837. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  14838. }
  14839. else
  14840. {
  14841. // This can happen if we have two properties with the same name but different types
  14842. AssertErrorState();
  14843. mBfIRBuilder->CreateRet(GetDefaultValue(methodInstance->mReturnType));
  14844. }
  14845. }
  14846. else
  14847. {
  14848. // During autocomplete, the actual type may not have the proper field instance
  14849. mBfIRBuilder->CreateRet(GetDefaultValue(methodInstance->mReturnType));
  14850. }
  14851. mCurMethodState->SetHadReturn(true);
  14852. }
  14853. else if (methodDef->mMethodType == BfMethodType_PropertySetter)
  14854. {
  14855. if (!mCompiler->IsAutocomplete())
  14856. {
  14857. String autoPropName = typeDef->GetAutoPropertyName(propertyDeclaration);
  14858. BfFieldInstance* fieldInstance = GetFieldByName(mCurTypeInstance, autoPropName);
  14859. auto fieldDef = fieldInstance->GetFieldDef();
  14860. auto& lastParam = mCurMethodState->mLocals.back();
  14861. if ((fieldInstance != NULL) && (fieldInstance->GetResolvedType() == lastParam->mResolvedType) &&
  14862. ((fieldInstance->mDataIdx >= 0) || (fieldDef->IsNonConstStatic())))
  14863. {
  14864. BfIRValue lookupAddr;
  14865. if (fieldDef->IsNonConstStatic())
  14866. lookupAddr = ReferenceStaticField(fieldInstance).mValue;
  14867. else
  14868. {
  14869. auto thisValue = GetThis();
  14870. if (thisValue.IsSplat())
  14871. {
  14872. BF_FATAL("Should not happen");
  14873. }
  14874. if (mCurTypeInstance->IsObject())
  14875. thisValue = LoadValue(thisValue);
  14876. lookupAddr = mBfIRBuilder->CreateInBoundsGEP(thisValue.mValue, 0, fieldInstance->mDataIdx);
  14877. }
  14878. mBfIRBuilder->CreateStore(lastParam->mValue, lookupAddr);
  14879. }
  14880. else if (!fieldInstance->mResolvedType->IsValuelessType())
  14881. {
  14882. // This can happen if we have two properties with the same name but different types
  14883. AssertErrorState();
  14884. }
  14885. }
  14886. }
  14887. }
  14888. if ((!mCurMethodInstance->mReturnType->IsValuelessType()) && (!isEmptyBodied))
  14889. {
  14890. mBfIRBuilder->PopulateType(mCurMethodInstance->mReturnType);
  14891. if (mCurMethodInstance->HasStructRet())
  14892. {
  14893. auto ptrType = CreatePointerType(mCurMethodInstance->mReturnType);
  14894. auto allocaInst = AllocLocalVariable(ptrType, "__return.addr", false);
  14895. auto storeInst = mBfIRBuilder->CreateStore(mBfIRBuilder->GetArgument(0), allocaInst);
  14896. mBfIRBuilder->ClearDebugLocation(storeInst);
  14897. mCurMethodState->mRetValAddr = allocaInst;
  14898. }
  14899. else
  14900. {
  14901. auto allocaInst = AllocLocalVariable(mCurMethodInstance->mReturnType, "__return", false);
  14902. mCurMethodState->mRetVal = BfTypedValue(allocaInst, mCurMethodInstance->mReturnType, true);
  14903. }
  14904. }
  14905. if (methodDef->mMethodType == BfMethodType_CtorCalcAppend)
  14906. {
  14907. mBfIRBuilder->CreateStore(GetConstValue(0), mCurMethodState->mRetVal.mValue);
  14908. BfGetSymbolReferenceKind prevSymbolKind;
  14909. BfAutoComplete* prevAutoComplete;
  14910. if (mCompiler->mResolvePassData != NULL)
  14911. {
  14912. prevSymbolKind = mCompiler->mResolvePassData->mGetSymbolReferenceKind;
  14913. prevAutoComplete = mCompiler->mResolvePassData->mAutoComplete;
  14914. mCompiler->mResolvePassData->mGetSymbolReferenceKind = BfGetSymbolReferenceKind_None;
  14915. }
  14916. EmitCtorCalcAppend();
  14917. if (mCompiler->mResolvePassData != NULL)
  14918. {
  14919. mCompiler->mResolvePassData->mGetSymbolReferenceKind = prevSymbolKind;
  14920. mCompiler->mResolvePassData->mAutoComplete = prevAutoComplete;
  14921. }
  14922. }
  14923. else if (!isEmptyBodied)
  14924. {
  14925. if (!mCurMethodState->mIRExitBlock)
  14926. mCurMethodState->mIRExitBlock = mBfIRBuilder->CreateBlock("exit", true);
  14927. bool isExpressionBody = false;
  14928. if (methodDeclaration != NULL)
  14929. {
  14930. if (methodDeclaration->mFatArrowToken != NULL)
  14931. isExpressionBody = true;
  14932. }
  14933. else if (auto propertyDeclaration = methodDef->GetPropertyDeclaration())
  14934. {
  14935. if (auto propBodyExpr = BfNodeDynCast<BfPropertyBodyExpression>(propertyDeclaration->mDefinitionBlock))
  14936. {
  14937. isExpressionBody = true;
  14938. }
  14939. }
  14940. else
  14941. {
  14942. if (auto block = BfNodeDynCast<BfBlock>(methodDef->mBody))
  14943. {
  14944. if (!block->mChildArr.IsEmpty())
  14945. {
  14946. if (auto exprStmt = BfNodeDynCast<BfExpressionStatement>(block->mChildArr.GetLast()))
  14947. {
  14948. if (exprStmt->mTrailingSemicolon == NULL)
  14949. isExpressionBody = true;
  14950. }
  14951. }
  14952. }
  14953. else
  14954. isExpressionBody = true;
  14955. }
  14956. if (auto fieldDtorBody = BfNodeDynCast<BfFieldDtorDeclaration>(methodDef->mBody))
  14957. {
  14958. while (fieldDtorBody != NULL)
  14959. {
  14960. VisitEmbeddedStatement(fieldDtorBody->mBody);
  14961. fieldDtorBody = fieldDtorBody->mNextFieldDtor;
  14962. }
  14963. }
  14964. else if (!isExpressionBody)
  14965. {
  14966. auto bodyBlock = BfNodeDynCast<BfBlock>(methodDef->mBody);
  14967. mCurMethodState->mHeadScope.mAstBlock = bodyBlock;
  14968. mCurMethodState->mHeadScope.mCloseNode = bodyBlock->mCloseBrace;
  14969. VisitCodeBlock(bodyBlock);
  14970. }
  14971. else if (auto expressionBody = BfNodeDynCast<BfExpression>(methodDef->mBody))
  14972. {
  14973. if ((methodDef->mMethodType != BfMethodType_Normal) && (propertyDeclaration == NULL))
  14974. {
  14975. BF_ASSERT(methodDeclaration->mFatArrowToken != NULL);
  14976. Fail("Only normal methods can have expression bodies", methodDeclaration->mFatArrowToken);
  14977. }
  14978. auto expectingType = mCurMethodInstance->mReturnType;
  14979. // if ((expectingType->IsVoid()) && (IsInSpecializedSection()))
  14980. // {
  14981. // Warn(0, "Using a 'void' return with an expression-bodied method isn't needed. Consider removing '=>' token", methodDeclaration->mFatArrowToken);
  14982. // }
  14983. //TODO: Why did we have all this stuff for handling void?
  14984. // if (expectingType->IsVoid())
  14985. // {
  14986. // bool wasReturnGenericParam = false;
  14987. // if ((mCurMethodState->mClosureState != NULL) && (mCurMethodState->mClosureState->mReturnType != NULL))
  14988. // {
  14989. // wasReturnGenericParam = mCurMethodState->mClosureState->mReturnType->IsGenericParam();
  14990. // }
  14991. // else
  14992. // {
  14993. // auto unspecializedMethodInstance = GetUnspecializedMethodInstance(mCurMethodInstance);
  14994. // if ((unspecializedMethodInstance != NULL) && (unspecializedMethodInstance->mReturnType->IsGenericParam()))
  14995. // wasReturnGenericParam = true;
  14996. // }
  14997. //
  14998. // // If we the void return was from a generic specialization, allow us to return a void result,
  14999. // // otherwise treat expression as though it must be a statement
  15000. // bool isStatement = expressionBody->VerifyIsStatement(mCompiler->mPassInstance, wasReturnGenericParam);
  15001. // if (isStatement)
  15002. // expectingType = NULL;
  15003. // }
  15004. UpdateSrcPos(expressionBody);
  15005. auto retVal = CreateValueFromExpression(expressionBody, expectingType);
  15006. if ((retVal) && (expectingType != NULL))
  15007. {
  15008. mCurMethodState->mHadReturn = true;
  15009. retVal = LoadValue(retVal);
  15010. EmitReturn(retVal.mValue);
  15011. }
  15012. }
  15013. }
  15014. }
  15015. BF_ASSERT(mCurMethodState->mCurScope == &mCurMethodState->mHeadScope);
  15016. if (skipUpdateSrcPos)
  15017. {
  15018. // Skip
  15019. }
  15020. else if ((bodyBlock != NULL) && (bodyBlock->mCloseBrace != NULL))
  15021. UpdateSrcPos(bodyBlock->mCloseBrace);
  15022. else if (methodDef->mBody != NULL)
  15023. UpdateSrcPos(methodDef->mBody);
  15024. else if (methodDeclaration != NULL)
  15025. UpdateSrcPos(methodDeclaration);
  15026. else if (methodDef->mDeclaringType->mTypeDeclaration != NULL)
  15027. UpdateSrcPos(methodDef->mDeclaringType->mTypeDeclaration);
  15028. else
  15029. UseDefaultSrcPos();
  15030. if (methodDef->mMethodType == BfMethodType_CtorCalcAppend)
  15031. {
  15032. if (mCurMethodState->mRetVal)
  15033. {
  15034. mCurMethodState->SetHadReturn(true);
  15035. auto retVal = mBfIRBuilder->CreateLoad(mCurMethodState->mRetVal.mValue);
  15036. mBfIRBuilder->CreateRet(retVal);
  15037. }
  15038. else
  15039. AssertErrorState();
  15040. }
  15041. if (!mCurMethodState->mHadReturn)
  15042. {
  15043. // Clear off the stackallocs that have occurred after a scopeData break
  15044. EmitDeferredScopeCalls(false, &mCurMethodState->mHeadScope, mCurMethodState->mIRExitBlock);
  15045. }
  15046. if (mCurMethodState->mIRExitBlock)
  15047. {
  15048. for (auto preExitBlock : mCurMethodState->mHeadScope.mAtEndBlocks)
  15049. mBfIRBuilder->MoveBlockToEnd(preExitBlock);
  15050. mBfIRBuilder->MoveBlockToEnd(mCurMethodState->mIRExitBlock);
  15051. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRExitBlock);
  15052. if (!mCurMethodState->mDIRetVal)
  15053. CreateDIRetVal();
  15054. }
  15055. for (auto localVar : mCurMethodState->mLocals)
  15056. {
  15057. if ((skipEndChecks) || (bodyBlock == NULL))
  15058. break;
  15059. LocalVariableDone(localVar, true);
  15060. }
  15061. if (mCurMethodState->mIRExitBlock)
  15062. {
  15063. if ((mCurMethodState->mRetVal) && (!mCurMethodInstance->HasStructRet()))
  15064. {
  15065. auto loadedVal = mBfIRBuilder->CreateLoad(mCurMethodState->mRetVal.mValue);
  15066. CreateReturn(loadedVal);
  15067. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  15068. if (mCurMethodState->mDIRetVal)
  15069. mBfIRBuilder->DbgLifetimeEnd(mCurMethodState->mDIRetVal);
  15070. }
  15071. else
  15072. {
  15073. // Have something on the last line to step onto
  15074. if (mHasFullDebugInfo)
  15075. {
  15076. if ((bodyBlock != NULL) && (bodyBlock->mCloseBrace != NULL))
  15077. UpdateSrcPos(bodyBlock->mCloseBrace);
  15078. EmitEnsureInstructionAt();
  15079. if ((irParamCount == 0) && (!IsTargetingBeefBackend()) && (mCompiler->mOptions.mAllowHotSwapping))
  15080. {
  15081. // This may be a case where we only emit 4 bytes, whereas we need 5 for a hot replace jump
  15082. mBfIRBuilder->EnsureFunctionPatchable();
  15083. }
  15084. }
  15085. mBfIRBuilder->CreateRetVoid();
  15086. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  15087. if (mCurMethodState->mDIRetVal)
  15088. mBfIRBuilder->DbgLifetimeEnd(mCurMethodState->mDIRetVal);
  15089. }
  15090. }
  15091. if ((mCurMethodInstance->mReturnType == NULL) || (mCurMethodInstance->mReturnType->IsValuelessType()))
  15092. {
  15093. if ((!mCurMethodState->mHadReturn) && (!mCurMethodState->mIRExitBlock))
  15094. {
  15095. if ((irParamCount == 0) && (!IsTargetingBeefBackend()) && (mCompiler->mOptions.mAllowHotSwapping))
  15096. {
  15097. // This may be a case where we only emit 4 bytes, whereas we need 5 for a hot replace jump
  15098. mBfIRBuilder->EnsureFunctionPatchable();
  15099. }
  15100. mBfIRBuilder->CreateRetVoid();
  15101. }
  15102. }
  15103. else
  15104. {
  15105. if (!mCurMethodState->mHadReturn)
  15106. {
  15107. auto refNode = mCurMethodInstance->mMethodDef->GetRefNode();
  15108. if (bodyBlock != NULL)
  15109. {
  15110. if (bodyBlock->mCloseBrace != NULL)
  15111. {
  15112. BfAstNode* target = bodyBlock->mCloseBrace;
  15113. Fail("Method must return value", target);
  15114. }
  15115. else
  15116. {
  15117. // It's possible to not have a closing brace if the method ends in an EOF
  15118. AssertErrorState();
  15119. }
  15120. }
  15121. }
  15122. }
  15123. // Move 'init' into 'entry'
  15124. mBfIRBuilder->MergeBlockDown(mCurMethodState->mIRInitBlock, mCurMethodState->mIREntryBlock);
  15125. mBfIRBuilder->MergeBlockDown(mCurMethodState->mIRHeadBlock, mCurMethodState->mIREntryBlock);
  15126. if ((mCurMethodInstance->mIsUnspecialized) /*|| (typeDef->mIsFunction)*/ || (mCurTypeInstance->IsUnspecializedType()))
  15127. {
  15128. // Don't keep instructions for unspecialized types
  15129. mBfIRBuilder->Func_DeleteBody(mCurMethodInstance->mIRFunction);
  15130. }
  15131. if ((hasExternSpecifier) && (!skipBody))
  15132. {
  15133. // If we hot swap, we want to make sure at least one method refers to this extern method so it gets pulled in
  15134. // incase it gets called later by some hot-loaded coded
  15135. if (mCompiler->mOptions.mAllowHotSwapping)
  15136. CreateFakeCallerMethod(mangledName);
  15137. mBfIRBuilder->Func_DeleteBody(mCurMethodInstance->mIRFunction);
  15138. }
  15139. else if ((methodDef->mImportKind == BfImportKind_Dynamic) && (!mCompiler->IsHotCompile()))
  15140. {
  15141. // We only need the DLL stub when we may be hot swapping
  15142. mBfIRBuilder->Func_DeleteBody(mCurMethodInstance->mIRFunction);
  15143. }
  15144. else if (wantsRemoveBody)
  15145. mBfIRBuilder->Func_DeleteBody(mCurMethodInstance->mIRFunction);
  15146. // We don't want to hold on to pointers to LLVMFunctions of unspecialized types.
  15147. // This allows us to delete the mScratchModule LLVM module without rebuilding all
  15148. // unspecialized types
  15149. if ((mCurTypeInstance->IsUnspecializedType()) || (mCurTypeInstance->IsInterface()))
  15150. {
  15151. BfLogSysM("ProcessMethod Clearing IRFunction: %p\n", methodInstance);
  15152. methodInstance->mIRFunction = BfIRFunction();
  15153. }
  15154. CheckAddFailType();
  15155. if (mHadBuildError)
  15156. prevHadBuildError.CancelRestore();
  15157. if (mHadBuildWarning)
  15158. prevHadWarning.CancelRestore();
  15159. if (!methodDef->mIsLocalMethod)
  15160. ProcessMethod_ProcessDeferredLocals();
  15161. mBfIRBuilder->SetActiveFunction(prevActiveFunction);
  15162. if (methodState.mHotDataReferenceBuilder != NULL)
  15163. {
  15164. AddHotDataReferences(&hotDataReferenceBuilder);
  15165. }
  15166. else
  15167. {
  15168. if ((methodInstance->mHotMethod != NULL) && (!methodInstance->mIsReified))
  15169. {
  15170. // Remove the hot method data
  15171. auto hotMethod = methodInstance->mHotMethod;
  15172. auto prevMethod = hotMethod->mPrevVersion;
  15173. if (prevMethod != NULL)
  15174. {
  15175. // If there's a prev method then pull its data into the main HotMethod.
  15176. // This, in effect, removes the 'hotMethod' data and rebases 'prevMethod'
  15177. // over to the main HotMethod definition to keep the HotMethod address
  15178. // invariant
  15179. for (auto ref : hotMethod->mReferences)
  15180. ref->Deref();
  15181. hotMethod->mReferences.Clear();
  15182. BF_ASSERT(prevMethod->mRefCount == 1);
  15183. hotMethod->mReferences = prevMethod->mReferences;
  15184. if (hotMethod->mSrcTypeVersion != NULL)
  15185. hotMethod->mSrcTypeVersion->Deref();
  15186. hotMethod->mSrcTypeVersion = prevMethod->mSrcTypeVersion;
  15187. prevMethod->mSrcTypeVersion = NULL;
  15188. prevMethod->mReferences.Clear();
  15189. hotMethod->mPrevVersion = prevMethod->mPrevVersion;
  15190. prevMethod->mPrevVersion = NULL;
  15191. prevMethod->Deref();
  15192. }
  15193. hotMethod->Deref();
  15194. methodInstance->mHotMethod = NULL;
  15195. }
  15196. }
  15197. }
  15198. String BfModule::GetLocalMethodName(const StringImpl& baseName, BfAstNode* anchorNode, BfMethodState* declMethodState, BfMixinState* declMixinState)
  15199. {
  15200. String name;
  15201. bool found = false;
  15202. auto checkMethodState = mCurMethodState;
  15203. while (checkMethodState != NULL)
  15204. {
  15205. if (checkMethodState->mClosureState == NULL)
  15206. break;
  15207. if (checkMethodState->mClosureState->mClosureMethodDef != NULL)
  15208. {
  15209. found = true;
  15210. name += checkMethodState->mClosureState->mClosureMethodDef->mName;
  15211. break;
  15212. }
  15213. checkMethodState = checkMethodState->mPrevMethodState;
  15214. }
  15215. if (!found)
  15216. name += mCurMethodInstance->mMethodDef->mName;
  15217. int prevSepPos = (int)name.LastIndexOf('$');
  15218. if (prevSepPos != -1)
  15219. {
  15220. name.RemoveToEnd(prevSepPos);
  15221. }
  15222. name += "@";
  15223. name += baseName;
  15224. HashContext hashCtx;
  15225. if (anchorNode != NULL)
  15226. {
  15227. hashCtx.Mixin(anchorNode->GetStartCharId());
  15228. }
  15229. //
  15230. {
  15231. auto checkMethodState = declMethodState;
  15232. auto checkMixinState = declMixinState;
  15233. while (checkMethodState != NULL)
  15234. {
  15235. if (checkMixinState != NULL)
  15236. {
  15237. hashCtx.Mixin(checkMixinState->mSource->GetStartCharId());
  15238. }
  15239. checkMethodState = checkMethodState->mPrevMethodState;
  15240. if (checkMethodState != NULL)
  15241. checkMixinState = checkMethodState->mMixinState;
  15242. }
  15243. }
  15244. auto rootMethodState = mCurMethodState->GetRootMethodState();
  15245. if (rootMethodState->mMethodInstance->mMethodInfoEx != NULL)
  15246. {
  15247. for (auto methodGenericArg : rootMethodState->mMethodInstance->mMethodInfoEx->mMethodGenericArguments)
  15248. {
  15249. StringT<128> genericTypeName;
  15250. BfMangler::Mangle(genericTypeName, mCompiler->GetMangleKind(), methodGenericArg);
  15251. hashCtx.MixinStr(genericTypeName);
  15252. }
  15253. }
  15254. uint64 hashVal = hashCtx.Finish64();
  15255. name += "$";
  15256. name += BfTypeUtils::HashEncode64(hashVal);
  15257. return name;
  15258. }
  15259. BfMethodDef* BfModule::GetLocalMethodDef(BfLocalMethod* localMethod)
  15260. {
  15261. if (localMethod->mMethodDef != NULL)
  15262. return localMethod->mMethodDef;
  15263. auto rootMethodState = mCurMethodState->GetRootMethodState();
  15264. auto declMethodState = localMethod->mDeclMethodState;
  15265. auto declMixinState = localMethod->mDeclMixinState;
  15266. auto typeInst = mCurTypeInstance;
  15267. BfAstNode* body = NULL;
  15268. BfAstNode* anchorNode = NULL;
  15269. auto _AllocDirectTypeRef = [&](BfType* type)
  15270. {
  15271. BfDirectTypeReference* directTypeRef = localMethod->mDirectTypeRefs.Alloc();
  15272. directTypeRef->Init(type);
  15273. return directTypeRef;
  15274. };
  15275. auto methodDeclaration = localMethod->mMethodDeclaration;
  15276. if (methodDeclaration != NULL)
  15277. {
  15278. body = methodDeclaration->mBody;
  15279. anchorNode = methodDeclaration->mOpenParen;
  15280. }
  15281. else
  15282. {
  15283. body = localMethod->mLambdaBindExpr->mBody;
  15284. anchorNode = localMethod->mLambdaBindExpr->mFatArrowToken;
  15285. }
  15286. BF_ASSERT(rootMethodState->mCurLocalVarId >= 0);
  15287. int methodLocalIdx = rootMethodState->mCurLocalVarId++;
  15288. BfMethodDef* methodDef;
  15289. if (methodDeclaration != NULL)
  15290. {
  15291. BfDefBuilder defBuilder(mCompiler->mSystem);
  15292. defBuilder.mPassInstance = mCompiler->mPassInstance;
  15293. defBuilder.mCurTypeDef = mCurMethodInstance->mMethodDef->mDeclaringType;
  15294. BfMethodDef* outerMethodDef = NULL;
  15295. if (localMethod->mOuterLocalMethod != NULL)
  15296. outerMethodDef = localMethod->mOuterLocalMethod->mMethodDef;
  15297. else
  15298. outerMethodDef = rootMethodState->mMethodInstance->mMethodDef;
  15299. methodDef = defBuilder.CreateMethodDef(methodDeclaration, outerMethodDef);
  15300. }
  15301. else
  15302. {
  15303. auto invokeMethod = localMethod->mLambdaInvokeMethodInstance;
  15304. methodDef = new BfMethodDef();
  15305. methodDef->mName = localMethod->mMethodName;
  15306. methodDef->mDeclaringType = mCurMethodInstance->mMethodDef->mDeclaringType;
  15307. methodDef->mReturnTypeRef = _AllocDirectTypeRef(invokeMethod->mReturnType);
  15308. methodDef->mBody = body;
  15309. for (int paramIdx = 0; paramIdx < invokeMethod->GetParamCount(); paramIdx++)
  15310. {
  15311. auto paramType = invokeMethod->GetParamType(paramIdx);
  15312. String paramName;
  15313. if (paramIdx < (int)localMethod->mLambdaBindExpr->mParams.size())
  15314. paramName = localMethod->mLambdaBindExpr->mParams[paramIdx]->ToString();
  15315. else
  15316. paramName = invokeMethod->GetParamName(paramIdx);
  15317. auto paramDef = new BfParameterDef();
  15318. paramDef->mTypeRef = _AllocDirectTypeRef(paramType);
  15319. paramDef->mName = paramName;
  15320. methodDef->mParams.Add(paramDef);
  15321. }
  15322. }
  15323. methodDef->mIdx = ~methodLocalIdx;
  15324. BF_ASSERT(!localMethod->mExpectedFullName.IsEmpty());
  15325. methodDef->mName = localMethod->mExpectedFullName;
  15326. // methodDef->mName = GetLocalMethodName(methodDef->mName, anchorNode, declMethodState, declMixinState);
  15327. //
  15328. // if (!localMethod->mExpectedFullName.IsEmpty())
  15329. // BF_ASSERT(methodDef->mName == localMethod->mExpectedFullName);
  15330. methodDef->mIsStatic = true;
  15331. methodDef->mIsLocalMethod = true;
  15332. methodDef->mIsVirtual = false;
  15333. localMethod->mMethodDef = methodDef;
  15334. auto methodInstanceGroup = new BfMethodInstanceGroup();
  15335. localMethod->mMethodInstanceGroup = methodInstanceGroup;
  15336. methodInstanceGroup->mMethodIdx = -1;
  15337. methodInstanceGroup->mOwner = mCurTypeInstance;
  15338. methodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  15339. if ((declMethodState->mMixinState != NULL) && (declMethodState->mMixinState->mTarget))
  15340. {
  15341. methodInstanceGroup->mOwner = declMethodState->mMixinState->mTarget.mType->ToTypeInstance();
  15342. BF_ASSERT(methodInstanceGroup->mOwner != NULL);
  15343. }
  15344. if ((mCompiler->mResolvePassData != NULL) && (methodDeclaration != NULL))
  15345. {
  15346. mCompiler->mResolvePassData->HandleLocalReference(methodDeclaration->mNameNode, typeInst->mTypeDef, rootMethodState->mMethodInstance->mMethodDef, methodLocalIdx);
  15347. auto autoComplete = mCompiler->mResolvePassData->mAutoComplete;
  15348. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(methodDeclaration->mNameNode)))
  15349. {
  15350. autoComplete->SetDefinitionLocation(methodDeclaration->mNameNode);
  15351. autoComplete->mInsertStartIdx = methodDeclaration->mNameNode->GetSrcStart();
  15352. autoComplete->mInsertEndIdx = methodDeclaration->mNameNode->GetSrcEnd();
  15353. autoComplete->mDefType = typeInst->mTypeDef;
  15354. autoComplete->mDefMethod = rootMethodState->mMethodInstance->mMethodDef;
  15355. autoComplete->mReplaceLocalId = methodLocalIdx;
  15356. }
  15357. }
  15358. return localMethod->mMethodDef;
  15359. }
  15360. BfModuleMethodInstance BfModule::GetLocalMethodInstance(BfLocalMethod* localMethod, const BfTypeVector& methodGenericArguments, BfMethodInstance* methodInstance, bool force)
  15361. {
  15362. BP_ZONE_F("GetLocalMethodInstance %s", localMethod->mMethodName.c_str());
  15363. BfLogSysM("GetLocalMethodInstance %p\n", localMethod);
  15364. auto rootMethodState = mCurMethodState->GetRootMethodState();
  15365. auto declMethodState = localMethod->mDeclMethodState;
  15366. auto declMixinState = localMethod->mDeclMixinState;
  15367. auto callerMethodState = mCurMethodState;
  15368. auto typeInst = mCurTypeInstance;
  15369. auto methodDef = GetLocalMethodDef(localMethod);
  15370. BfAstNode* body = NULL;
  15371. auto methodDeclaration = localMethod->mMethodDeclaration;
  15372. if (methodDeclaration != NULL)
  15373. {
  15374. body = methodDeclaration->mBody;
  15375. }
  15376. else
  15377. {
  15378. body = localMethod->mLambdaBindExpr->mBody;
  15379. }
  15380. bool hadConcreteInterfaceGenericArgument = false;
  15381. BfTypeVector sanitizedMethodGenericArguments;
  15382. // Ignore the outermost method's generic method arguments for the purpose of determining if we are the 'default' (ie: unspecialized)
  15383. // version of this method for this pass through the outermost method
  15384. int dependentGenericStartIdx = 0;
  15385. if (rootMethodState->mMethodInstance->mMethodInfoEx != NULL)
  15386. dependentGenericStartIdx = (int)rootMethodState->mMethodInstance->mMethodInfoEx->mMethodGenericArguments.size();
  15387. BfMethodInstance* outerMethodInstance = mCurMethodInstance;
  15388. if (methodGenericArguments.size() == 0)
  15389. {
  15390. if (rootMethodState->mMethodInstance->mMethodInfoEx != NULL)
  15391. sanitizedMethodGenericArguments = rootMethodState->mMethodInstance->mMethodInfoEx->mMethodGenericArguments;
  15392. }
  15393. else
  15394. {
  15395. int genericArgIdx = 0;
  15396. // for (; genericArgIdx < (int)outerMethodInstance->mMethodGenericArguments.size(); genericArgIdx++)
  15397. // {
  15398. // BF_ASSERT(methodGenericArguments[genericArgIdx] == outerMethodInstance->mMethodGenericArguments[genericArgIdx]);
  15399. // sanitizedMethodGenericArguments.push_back(methodGenericArguments[genericArgIdx]);
  15400. // }
  15401. for (; genericArgIdx < (int)methodGenericArguments.size(); genericArgIdx++)
  15402. {
  15403. auto genericArgType = methodGenericArguments[genericArgIdx];
  15404. BF_ASSERT(!genericArgType->IsRef());
  15405. if (genericArgType->IsConcreteInterfaceType())
  15406. {
  15407. hadConcreteInterfaceGenericArgument = true;
  15408. auto concreteInterfaceType = (BfConcreteInterfaceType*)genericArgType;
  15409. genericArgType = concreteInterfaceType->mInterface;
  15410. }
  15411. sanitizedMethodGenericArguments.push_back(genericArgType);
  15412. }
  15413. }
  15414. bool wantPrematureMethodInstance = false;
  15415. if (!force)
  15416. {
  15417. wantPrematureMethodInstance = (callerMethodState->mClosureState != NULL) && (callerMethodState->mClosureState->mCaptureVisitingBody);
  15418. }
  15419. auto methodInstGroup = localMethod->mMethodInstanceGroup;
  15420. bool isDefaultPass = true;
  15421. BfTypeVector lookupMethodGenericArguments;
  15422. for (int genericArgIdx = dependentGenericStartIdx; genericArgIdx < (int)methodGenericArguments.size(); genericArgIdx++)
  15423. {
  15424. auto genericArgType = methodGenericArguments[genericArgIdx];
  15425. BF_ASSERT(!genericArgType->IsRef());
  15426. lookupMethodGenericArguments.Add(genericArgType);
  15427. if (genericArgType->IsGenericParam())
  15428. {
  15429. auto genericParam = (BfGenericParamType*)genericArgType;
  15430. if ((genericParam->mGenericParamKind != BfGenericParamKind_Method) || (genericParam->mGenericParamIdx != genericArgIdx))
  15431. isDefaultPass = false;
  15432. }
  15433. else
  15434. {
  15435. isDefaultPass = false;
  15436. }
  15437. }
  15438. bool hadExistingMethodInstance = false;
  15439. if (methodInstance != NULL)
  15440. {
  15441. hadExistingMethodInstance = true;
  15442. }
  15443. else
  15444. {
  15445. if (isDefaultPass)
  15446. {
  15447. methodInstance = methodInstGroup->mDefault;
  15448. if (methodInstance != NULL)
  15449. {
  15450. hadExistingMethodInstance = true;
  15451. }
  15452. else
  15453. {
  15454. methodInstance = new BfMethodInstance();
  15455. methodInstGroup->mDefault = methodInstance;
  15456. }
  15457. }
  15458. else
  15459. {
  15460. BF_ASSERT(sanitizedMethodGenericArguments.size() != 0);
  15461. if (methodInstGroup->mMethodSpecializationMap == NULL)
  15462. methodInstGroup->mMethodSpecializationMap = new BfMethodInstanceGroup::MapType();
  15463. BfMethodInstance** methodInstancePtr = NULL;
  15464. if (!methodInstGroup->mMethodSpecializationMap->TryAdd(lookupMethodGenericArguments, NULL, &methodInstancePtr))
  15465. {
  15466. methodInstance = *methodInstancePtr;
  15467. hadExistingMethodInstance = true;
  15468. }
  15469. else
  15470. {
  15471. methodInstance = new BfMethodInstance();
  15472. *methodInstancePtr = methodInstance;
  15473. }
  15474. }
  15475. }
  15476. if (hadExistingMethodInstance)
  15477. {
  15478. if ((!methodInstance->mDisallowCalling) ||
  15479. ((wantPrematureMethodInstance) && (methodInstance->mDisallowCalling)))
  15480. return BfModuleMethodInstance(methodInstance);
  15481. BF_ASSERT((methodInstance->mMethodInfoEx == NULL) || (methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureClosureState == NULL));
  15482. }
  15483. else
  15484. {
  15485. auto methodInfoEx = methodInstance->GetMethodInfoEx();
  15486. methodInfoEx->mClosureInstanceInfo = new BfClosureInstanceInfo();
  15487. methodInfoEx->mClosureInstanceInfo->mLocalMethod = localMethod;
  15488. methodInstance->mIsReified = mCurMethodInstance->mIsReified;
  15489. methodInstance->mIsAutocompleteMethod = mCurMethodInstance->mIsAutocompleteMethod;
  15490. methodInstance->mMethodDef = methodDef;
  15491. methodInstance->mMethodInstanceGroup = localMethod->mMethodInstanceGroup;
  15492. if (hadConcreteInterfaceGenericArgument)
  15493. methodInstance->mIgnoreBody = true;
  15494. methodInfoEx->mMethodGenericArguments = sanitizedMethodGenericArguments;
  15495. for (auto genericArg : sanitizedMethodGenericArguments)
  15496. {
  15497. if (genericArg->IsPrimitiveType())
  15498. genericArg = GetWrappedStructType(genericArg);
  15499. AddDependency(genericArg, typeInst, BfDependencyMap::DependencyFlag_MethodGenericArg);
  15500. }
  15501. for (int genericParamIdx = (int)sanitizedMethodGenericArguments.size(); genericParamIdx < (int)methodDef->mGenericParams.size(); genericParamIdx++)
  15502. {
  15503. auto genericParamType = GetGenericParamType(BfGenericParamKind_Method, genericParamIdx);
  15504. methodInfoEx->mMethodGenericArguments.push_back(genericParamType);
  15505. }
  15506. SetupMethodIdHash(methodInstance);
  15507. }
  15508. auto _SetupMethodInstance = [&]()
  15509. {
  15510. BF_ASSERT(methodInstance->GetNumGenericParams() == 0);
  15511. // Generic constraints
  15512. for (int genericParamIdx = 0; genericParamIdx < (int)methodDef->mGenericParams.size(); genericParamIdx++)
  15513. {
  15514. auto genericParamInstance = new BfGenericMethodParamInstance(methodDef, genericParamIdx);
  15515. methodInstance->GetMethodInfoEx()->mGenericParams.push_back(genericParamInstance);
  15516. }
  15517. };
  15518. //////////////////////////////////////////////////////////////////////////
  15519. auto _VisitLambdaBody = [&]()
  15520. {
  15521. if (localMethod->mDeclOnly)
  15522. return;
  15523. if (mCompiler->mCanceling)
  15524. return;
  15525. if (auto blockBody = BfNodeDynCast<BfBlock>(body))
  15526. {
  15527. VisitCodeBlock(blockBody);
  15528. }
  15529. else if (auto bodyExpr = BfNodeDynCast<BfExpression>(body))
  15530. CreateValueFromExpression(bodyExpr);
  15531. };
  15532. auto _SafeResolveTypeRef = [&](BfTypeReference* typeRef)
  15533. {
  15534. SetAndRestoreValue<bool> prevIgnoreError(mIgnoreErrors, true);
  15535. auto result = ResolveTypeRef(typeRef);
  15536. if (result == NULL)
  15537. result = mContext->mBfObjectType;
  15538. return result;
  15539. };
  15540. BfTypeInstance* outerClosure = NULL;
  15541. if ((declMethodState->mClosureState != NULL) && (!declMethodState->mClosureState->mCapturing))
  15542. outerClosure = declMethodState->mClosureState->mClosureType;
  15543. BfMethodState methodState;
  15544. methodState.mPrevMethodState = declMethodState;//mCurMethodState;
  15545. BfIRFunctionType funcType;
  15546. auto voidType = GetPrimitiveType(BfTypeCode_None);
  15547. SizedArray<BfIRType, 0> paramTypes;
  15548. funcType = mBfIRBuilder->CreateFunctionType(mBfIRBuilder->MapType(voidType), paramTypes, false);
  15549. mBfIRBuilder->SaveDebugLocation();
  15550. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  15551. auto prevActiveFunction = mBfIRBuilder->GetActiveFunction();
  15552. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, true);
  15553. BfDeferredLocalAssignData deferredLocalAssignData;
  15554. //TODO: Why did we do this? It can cause us to pull in local variables that don't belong to us...
  15555. /*if (declMethodState->mDeferredLocalAssignData != NULL)
  15556. deferredLocalAssignData.ExtendFrom(declMethodState->mDeferredLocalAssignData);*/
  15557. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  15558. methodState.mIRHeadBlock = mBfIRBuilder->CreateBlock("head", true);
  15559. methodState.mIRInitBlock = mBfIRBuilder->CreateBlock("init", true);
  15560. methodState.mIREntryBlock = mBfIRBuilder->CreateBlock("entry", true);
  15561. methodState.mCurScope->mDIScope = localMethod->mDeclDIScope; //declMethodState->mCurScope->mDIScope ;
  15562. //methodState.mCurLocalVarId = declMethodState->mCurLocalVarId;
  15563. methodState.mIRFunction = declMethodState->mIRFunction;
  15564. methodState.mDeferredLocalAssignData = &deferredLocalAssignData;
  15565. mBfIRBuilder->SetInsertPoint(methodState.mIREntryBlock);
  15566. BfClosureState closureState;
  15567. if (methodDef->mMethodType == BfMethodType_Mixin)
  15568. {
  15569. if (declMethodState != NULL)
  15570. {
  15571. if ((declMethodState->mClosureState != NULL) && (declMethodState->mClosureState->mReturnType != NULL))
  15572. closureState.mReturnType = declMethodState->mClosureState->mReturnType;
  15573. else if (declMethodState->mMethodInstance != NULL)
  15574. closureState.mReturnType = declMethodState->mMethodInstance->mReturnType;
  15575. }
  15576. }
  15577. if (closureState.mReturnType == NULL)
  15578. closureState.mReturnType = _SafeResolveTypeRef(methodDef->mReturnTypeRef);
  15579. closureState.mCapturing = true;
  15580. closureState.mLocalMethod = localMethod;
  15581. closureState.mClosureInstanceInfo = methodInstance->mMethodInfoEx->mClosureInstanceInfo;
  15582. closureState.mDeclaringMethodIsMutating = mCurMethodInstance->mMethodDef->mIsMutating;
  15583. methodState.mClosureState = &closureState;
  15584. closureState.mClosureType = outerClosure;
  15585. int outerLocalsCount = (int)methodState.mLocals.size();
  15586. if (!hadExistingMethodInstance)
  15587. {
  15588. BfLogSysM("LocalMethod %p premature DoMethodDeclaration %p (Source:%p)\n", localMethod, methodInstance, (methodDeclaration != NULL) ? methodDeclaration->GetSourceData() : NULL);
  15589. SetAndRestoreValue<bool> prevIgnoreWrites(mWantsIRIgnoreWrites, true);
  15590. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, true);
  15591. // Prematurely do declaration. We will have to undo this later, so don't write this one and don't throw errors
  15592. auto declareModule = this;
  15593. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(declareModule->mCurMethodInstance, methodInstance);
  15594. SetAndRestoreValue<BfFilePosition> prevFilePos(declareModule->mCurFilePosition);
  15595. BF_ASSERT(declareModule != NULL);
  15596. methodInstance->mDeclModule = declareModule;
  15597. _SetupMethodInstance();
  15598. declareModule->DoMethodDeclaration(localMethod->mMethodDef->GetMethodDeclaration(), false, false);
  15599. methodInstance->mDisallowCalling = true; // Don't allow us to ACTUALLY call until we add the captures
  15600. }
  15601. if (wantPrematureMethodInstance)
  15602. {
  15603. // Return a premature methodInstance -- since we are partway through determining the capture of a local method, we can't rely on its
  15604. // capture information. This returned method instance can only be used for method matching, but we will visit it later to create
  15605. // its true method instance
  15606. //auto moduleMethodInstance = _CheckReturnedMethod(methodInstance);
  15607. //BF_ASSERT(moduleMethodInstance);
  15608. return BfModuleMethodInstance(methodInstance);
  15609. }
  15610. auto checkInsertBlock = mBfIRBuilder->GetInsertBlock();
  15611. BF_ASSERT(methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureClosureState == NULL);
  15612. closureState.mCaptureStartAccessId = mCurMethodState->GetRootMethodState()->mCurAccessId;
  15613. methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureClosureState = &closureState;
  15614. closureState.mClosureMethodDef = methodDef;
  15615. bool wantsVisitBody = true;
  15616. if ((methodDef->mMethodType == BfMethodType_Mixin) && (!methodGenericArguments.IsEmpty()))
  15617. wantsVisitBody = false;
  15618. if (methodInstance->mIsUnspecializedVariation)
  15619. wantsVisitBody = false;
  15620. if (wantsVisitBody)
  15621. {
  15622. BP_ZONE("VisitLambdaBody");
  15623. // For generic methods, we capture for each specialization, so make sure mIsStatic is set to 'true' for
  15624. // this capture stage for each of those times
  15625. SetAndRestoreValue<bool> prevWasStatis(methodDef->mIsStatic, true);
  15626. /*
  15627. // Only generate errors once. Also there are some errors that will occur during this scanning phase
  15628. // that will not occur during the actual lambda method generation, for example: returning a value
  15629. // when our current method is a 'void' method. This shouldn't affect capture scanning since all
  15630. // our AST nodes will still be visited
  15631. SetAndRestoreValue<bool> ignoreError(mIgnoreErrors, true);
  15632. */
  15633. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, methodInstance);
  15634. //SetAndRestoreValue<bool> wantsIgnoreWrites(mWantsISIgnoreWrites, true);
  15635. mBfIRBuilder->SaveDebugLocation();
  15636. closureState.mCaptureVisitingBody = true;
  15637. BF_ASSERT(methodInstance->mMethodInfoEx != NULL);
  15638. methodState.mGenericTypeBindings = &methodInstance->mMethodInfoEx->mGenericTypeBindings;
  15639. NewScopeState();
  15640. ProcessMethod_SetupParams(methodInstance, NULL, false, NULL);
  15641. if (methodInstance->mMethodDef->mMethodType == BfMethodType_Mixin)
  15642. {
  15643. // Allow assigning to arguments when we're capturing - which may or may not be legal at the injection site (we throw error there)
  15644. for (auto localDef : methodState.mLocals)
  15645. {
  15646. if (localDef->mResolvedType->IsVar())
  15647. continue;
  15648. localDef->mAddr = CreateAlloca(localDef->mResolvedType);
  15649. }
  15650. }
  15651. _VisitLambdaBody();
  15652. RestoreScopeState();
  15653. //ProcessMethod(methodInstance);
  15654. closureState.mCaptureVisitingBody = false;
  15655. mBfIRBuilder->RestoreDebugLocation();
  15656. }
  15657. // If we ended up being called by a method with a lower captureStartAccessId, propagate that to whoever is calling us, too...
  15658. if ((methodState.mPrevMethodState->mClosureState != NULL) && (methodState.mPrevMethodState->mClosureState->mCapturing))
  15659. {
  15660. auto prevClosureState = methodState.mPrevMethodState->mClosureState;
  15661. if (closureState.mCaptureStartAccessId < prevClosureState->mCaptureStartAccessId)
  15662. prevClosureState->mCaptureStartAccessId = closureState.mCaptureStartAccessId;
  15663. }
  15664. //RestoreScopeState();
  15665. // Actually get the referenced local methods. It's important we wait until after visiting the body, because then our own capture information
  15666. // can be used by these methods (which will be necessary if any of these methods call us directly or indirectly)
  15667. closureState.mClosureMethodDef = NULL;
  15668. for (auto methodInstance : closureState.mLocalMethodRefs)
  15669. {
  15670. GetLocalMethodInstance(methodInstance->mMethodInfoEx->mClosureInstanceInfo->mLocalMethod, BfTypeVector(), methodInstance);
  15671. }
  15672. methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureClosureState = NULL;
  15673. prevIgnoreWrites.Restore();
  15674. std::multiset<BfClosureCapturedEntry> capturedEntries;
  15675. //
  15676. {
  15677. auto varMethodState = declMethodState;
  15678. while (varMethodState != NULL)
  15679. {
  15680. if ((varMethodState->mMixinState != NULL) && (varMethodState->mMixinState->mLastTargetAccessId >= closureState.mCaptureStartAccessId))
  15681. {
  15682. BF_ASSERT(methodInstance->GetOwner() == varMethodState->mMixinState->mTarget.mType);
  15683. methodDef->mIsStatic = false;
  15684. if (rootMethodState->mMethodInstance->mMethodDef->mIsMutating)
  15685. methodDef->mIsMutating = true;
  15686. }
  15687. bool copyOuterCaptures = false;
  15688. for (int localIdx = 0; localIdx < varMethodState->mLocals.size(); localIdx++)
  15689. {
  15690. auto localVar = varMethodState->mLocals[localIdx];
  15691. if ((localVar->mReadFromId >= closureState.mCaptureStartAccessId) || (localVar->mWrittenToId >= closureState.mCaptureStartAccessId))
  15692. {
  15693. if (localVar->mIsThis)
  15694. {
  15695. // We can only set mutating if our owning type is mutating
  15696. if (localVar->mWrittenToId >= closureState.mCaptureStartAccessId)
  15697. {
  15698. if (mCurTypeInstance->IsValueType())
  15699. {
  15700. if (rootMethodState->mMethodInstance->mMethodDef->mIsMutating)
  15701. methodDef->mIsMutating = true;
  15702. }
  15703. }
  15704. methodDef->mIsStatic = false;
  15705. continue;
  15706. }
  15707. if ((localVar->mIsThis) && (outerClosure != NULL))
  15708. {
  15709. continue;
  15710. }
  15711. if ((localVar->mConstValue) || (localVar->mResolvedType->IsValuelessType()))
  15712. {
  15713. closureState.mConstLocals.push_back(*localVar);
  15714. continue;
  15715. }
  15716. BfClosureCapturedEntry capturedEntry;
  15717. auto capturedType = localVar->mResolvedType;
  15718. bool captureByRef = false;
  15719. if (!capturedType->IsRef())
  15720. {
  15721. if (localVar->mIsThis)
  15722. {
  15723. if ((localVar->mResolvedType->IsValueType()) && (mCurMethodInstance->mMethodDef->HasNoThisSplat()))
  15724. captureByRef = true;
  15725. }
  15726. else if ((!localVar->mIsReadOnly) && (localVar->mWrittenToId >= closureState.mCaptureStartAccessId))
  15727. captureByRef = true;
  15728. }
  15729. else
  15730. {
  15731. if (localVar->mWrittenToId < closureState.mCaptureStartAccessId)
  15732. {
  15733. capturedType = ((BfRefType*)capturedType)->mElementType;
  15734. }
  15735. }
  15736. if (captureByRef)
  15737. {
  15738. //capturedEntry.mIsByReference = true;
  15739. capturedType = CreateRefType(capturedType);
  15740. }
  15741. else
  15742. {
  15743. //capturedEntry.mIsByReference = false;
  15744. }
  15745. capturedEntry.mNameNode = localVar->mNameNode;
  15746. capturedEntry.mType = capturedType;
  15747. capturedEntry.mName = localVar->mName;
  15748. //capturedEntry.mLocalVarDef = localVar;
  15749. capturedEntries.insert(capturedEntry);
  15750. }
  15751. }
  15752. varMethodState = varMethodState->mPrevMethodState;
  15753. if ((varMethodState == NULL) ||
  15754. (varMethodState->mMixinState != NULL) ||
  15755. ((varMethodState->mClosureState != NULL) && (!varMethodState->mClosureState->mCapturing)))
  15756. break;
  15757. }
  15758. }
  15759. for (auto& copyField : closureState.mReferencedOuterClosureMembers)
  15760. {
  15761. auto fieldDef = copyField->GetFieldDef();
  15762. BfClosureCapturedEntry capturedEntry;
  15763. capturedEntry.mName = copyField->GetFieldDef()->mName;
  15764. capturedEntry.mType = copyField->mResolvedType;
  15765. if (capturedEntry.mType->IsRef())
  15766. {
  15767. // Keep by ref
  15768. }
  15769. else if (!fieldDef->mIsReadOnly)
  15770. {
  15771. capturedEntry.mType = CreateRefType(capturedEntry.mType);
  15772. }
  15773. capturedEntries.insert(capturedEntry);
  15774. }
  15775. int captureIdx = 0;
  15776. for (auto& capturedEntry : capturedEntries)
  15777. {
  15778. methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureEntries.Add(capturedEntry);
  15779. }
  15780. /*if (isDefaultPass)
  15781. {
  15782. // Insert captured members a params at the start. If we added at the end then it would screw up varargs methods
  15783. int captureIdx = 0;
  15784. for (auto& capturedEntry : capturedEntries)
  15785. {
  15786. methodInstance->mClosureInstanceInfo->mCaptureNodes.Add(BfNodeDynCast<BfIdentifierNode>(capturedEntry.mNameNode));
  15787. BfParameterDef* paramDef = new BfParameterDef();
  15788. paramDef->mName = capturedEntry.mName;
  15789. BfDirectTypeReference* directTypeRef = new BfDirectTypeReference();
  15790. directTypeRef->mType = capturedEntry.mType;
  15791. typeInst->mTypeDef->mDirectAllocNodes.push_back(directTypeRef);
  15792. paramDef->mTypeRef = directTypeRef;
  15793. paramDef->mParamKind = BfParamKind_ImplicitCapture;
  15794. methodDef->mParams.Insert(captureIdx, paramDef);
  15795. captureIdx++;
  15796. }
  15797. }
  15798. else
  15799. {
  15800. auto defaultMethodInstance = methodInstGroup->mDefault;
  15801. methodInstance->mClosureInstanceInfo->mCaptureNodes = defaultMethodInstance->mClosureInstanceInfo->mCaptureNodes;
  15802. }*/
  15803. methodState.Reset();
  15804. closureState.mCapturing = false;
  15805. //////////////////////////////////////////////////////////////////////////
  15806. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, false);
  15807. if (methodInstance->mReturnType != NULL)
  15808. {
  15809. BF_ASSERT(methodInstance->mDisallowCalling);
  15810. // We did a premature declaration (without captures)
  15811. methodInstance->UndoDeclaration();
  15812. methodInstance->mDisallowCalling = false;
  15813. BfLogSysM("LocalMethod %p UndoingDeclaration %p\n", localMethod, methodInstance);
  15814. }
  15815. auto declareModule = this;
  15816. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(declareModule->mCurMethodInstance, methodInstance);
  15817. SetAndRestoreValue<BfFilePosition> prevFilePos(declareModule->mCurFilePosition);
  15818. BF_ASSERT(declareModule != NULL);
  15819. methodInstance->mDeclModule = declareModule;
  15820. _SetupMethodInstance();
  15821. BfLogSysM("LocalMethod %p DoMethodDeclaration %p\n", localMethod, methodInstance);
  15822. declareModule->DoMethodDeclaration(localMethod->mMethodDef->GetMethodDeclaration(), false, false);
  15823. closureState.mReturnType = methodInstance->mReturnType;
  15824. mCompiler->mStats.mMethodsQueued++;
  15825. mCompiler->UpdateCompletion();
  15826. declareModule->mIncompleteMethodCount++;
  15827. mCompiler->mStats.mMethodsProcessed++;
  15828. if (!methodInstance->mIsReified)
  15829. mCompiler->mStats.mUnreifiedMethodsProcessed++;
  15830. auto deferMethodState = rootMethodState;
  15831. // 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)
  15832. if ((!localMethod->mDeclOnly) && (!methodInstance->mIsUnspecializedVariation) &&
  15833. (!mWantsIRIgnoreWrites) && (methodDef->mMethodType != BfMethodType_Mixin))
  15834. {
  15835. BP_ZONE("BfDeferredLocalMethod:create");
  15836. BfDeferredLocalMethod* deferredLocalMethod = new BfDeferredLocalMethod();
  15837. deferredLocalMethod->mLocalMethod = localMethod;
  15838. deferredLocalMethod->mConstLocals = closureState.mConstLocals;
  15839. deferredLocalMethod->mMethodInstance = methodInstance;
  15840. auto checkMethodState = declMethodState;
  15841. while (checkMethodState != NULL)
  15842. {
  15843. if ((checkMethodState->mClosureState != NULL) && (checkMethodState->mClosureState->mActiveDeferredLocalMethod != NULL))
  15844. {
  15845. for (auto& mixinRecord : checkMethodState->mClosureState->mActiveDeferredLocalMethod->mMixinStateRecords)
  15846. deferredLocalMethod->mMixinStateRecords.Add(mixinRecord);
  15847. }
  15848. if (checkMethodState->mMixinState != NULL)
  15849. {
  15850. BfMixinRecord mixinRecord;
  15851. mixinRecord.mSource = checkMethodState->mMixinState->mSource;
  15852. deferredLocalMethod->mMixinStateRecords.Add(mixinRecord);
  15853. }
  15854. checkMethodState = checkMethodState->mPrevMethodState;
  15855. }
  15856. rootMethodState->mDeferredLocalMethods.Add(deferredLocalMethod);
  15857. }
  15858. mBfIRBuilder->SetActiveFunction(prevActiveFunction);
  15859. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  15860. mBfIRBuilder->RestoreDebugLocation();
  15861. if (methodInstance == localMethod->mMethodInstanceGroup->mDefault)
  15862. {
  15863. auto checkMethodState = mCurMethodState;
  15864. while (checkMethodState != NULL)
  15865. {
  15866. BfLocalMethod* nextLocalMethod = NULL;
  15867. if (checkMethodState->mLocalMethodMap.TryGetValue(localMethod->mMethodName, &nextLocalMethod))
  15868. {
  15869. while (nextLocalMethod != NULL)
  15870. {
  15871. auto checkLocalMethod = nextLocalMethod;
  15872. nextLocalMethod = nextLocalMethod->mNextWithSameName;
  15873. if (checkLocalMethod == localMethod)
  15874. continue;
  15875. if (checkLocalMethod->mMethodInstanceGroup == NULL)
  15876. continue;
  15877. auto checkMethodInstance = checkLocalMethod->mMethodInstanceGroup->mDefault;
  15878. if (checkMethodInstance == NULL)
  15879. continue; // Not generated yet
  15880. if (CompareMethodSignatures(localMethod->mMethodInstanceGroup->mDefault, checkMethodInstance))
  15881. {
  15882. auto bfError = Fail("Method already declared with the same parameter types", methodInstance->mMethodDef->GetRefNode(), true);
  15883. if (bfError != NULL)
  15884. mCompiler->mPassInstance->MoreInfo("First declaration", checkMethodInstance->mMethodDef->GetRefNode());
  15885. }
  15886. }
  15887. }
  15888. checkMethodState = checkMethodState->mPrevMethodState;
  15889. }
  15890. }
  15891. return BfModuleMethodInstance(methodInstance);
  15892. }
  15893. int BfModule::GetLocalInferrableGenericArgCount(BfMethodDef* methodDef)
  15894. {
  15895. if ((!methodDef->mIsLocalMethod) || (methodDef->mGenericParams.size() == 0))
  15896. return 0;
  15897. auto rootMethodState = mCurMethodState->GetRootMethodState();
  15898. int rootMethodGenericParamCount = 0;
  15899. if (rootMethodState->mMethodInstance->mMethodInfoEx != NULL)
  15900. rootMethodGenericParamCount = (int)rootMethodState->mMethodInstance->mMethodInfoEx->mGenericParams.size();
  15901. if (mCurMethodInstance == NULL)
  15902. return rootMethodGenericParamCount;
  15903. if ((mCurMethodInstance->mMethodInfoEx == NULL) || (mCurMethodInstance->mMethodInfoEx->mClosureInstanceInfo == NULL))
  15904. return rootMethodGenericParamCount;
  15905. BfLocalMethod* callerLocalMethod = mCurMethodInstance->mMethodInfoEx->mClosureInstanceInfo->mLocalMethod;
  15906. if (callerLocalMethod == NULL)
  15907. return rootMethodGenericParamCount;
  15908. BfLocalMethod* calledLocalMethod = NULL;
  15909. rootMethodState->mLocalMethodCache.TryGetValue(methodDef->mName, &calledLocalMethod);
  15910. while ((calledLocalMethod != NULL) && (callerLocalMethod != NULL))
  15911. {
  15912. if (calledLocalMethod->mOuterLocalMethod == callerLocalMethod)
  15913. return (int)callerLocalMethod->mMethodDef->mGenericParams.size();
  15914. callerLocalMethod = calledLocalMethod->mOuterLocalMethod;
  15915. }
  15916. return rootMethodGenericParamCount;
  15917. }
  15918. void BfModule::GetMethodCustomAttributes(BfMethodInstance* methodInstance)
  15919. {
  15920. auto methodDef = methodInstance->mMethodDef;
  15921. if (methodInstance->GetCustomAttributes() != NULL)
  15922. return;
  15923. auto methodDeclaration = methodDef->GetMethodDeclaration();
  15924. auto propertyMethodDeclaration = methodDef->GetPropertyMethodDeclaration();
  15925. auto typeInstance = methodInstance->GetOwner();
  15926. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  15927. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, methodInstance);
  15928. if ((methodDeclaration != NULL) && (methodDeclaration->mAttributes != NULL))
  15929. {
  15930. if (methodInstance->GetMethodInfoEx()->mMethodCustomAttributes == NULL)
  15931. methodInstance->mMethodInfoEx->mMethodCustomAttributes = new BfMethodCustomAttributes();
  15932. methodInstance->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes = GetCustomAttributes(methodDeclaration->mAttributes,
  15933. ((methodDef->mMethodType == BfMethodType_Ctor) || (methodDef->mMethodType == BfMethodType_CtorCalcAppend)) ? BfAttributeTargets_Constructor : BfAttributeTargets_Method);
  15934. }
  15935. else if ((propertyMethodDeclaration != NULL) && (propertyMethodDeclaration->mAttributes != NULL))
  15936. {
  15937. if (methodInstance->GetMethodInfoEx()->mMethodCustomAttributes == NULL)
  15938. methodInstance->mMethodInfoEx->mMethodCustomAttributes = new BfMethodCustomAttributes();
  15939. methodInstance->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes = GetCustomAttributes(propertyMethodDeclaration->mAttributes, BfAttributeTargets_Method);
  15940. }
  15941. }
  15942. void BfModule::SetupIRFunction(BfMethodInstance* methodInstance, StringImpl& mangledName, bool isTemporaryFunc, bool* outIsIntrinsic)
  15943. {
  15944. if (methodInstance->GetImportCallKind() == BfImportCallKind_GlobalVar)
  15945. {
  15946. // Don't create a func
  15947. return;
  15948. }
  15949. auto typeInstance = methodInstance->GetOwner();
  15950. auto methodDef = methodInstance->mMethodDef;
  15951. BfIRFunctionType funcType = mBfIRBuilder->MapMethod(methodInstance);
  15952. // Don't set these pointers during resolve pass because they may become invalid if it's just a temporary autocomplete method
  15953. if (mCompiler->mResolvePassData == NULL)
  15954. {
  15955. if ((methodDef->mMethodType == BfMethodType_Ctor) && (methodDef->mIsStatic))
  15956. {
  15957. typeInstance->mHasStaticInitMethod = true;
  15958. }
  15959. if ((methodDef->mMethodType == BfMethodType_Dtor) && (methodDef->mIsStatic))
  15960. {
  15961. typeInstance->mHasStaticDtorMethod = true;
  15962. }
  15963. if ((methodDef->mMethodType == BfMethodType_Normal) && (methodDef->mIsStatic) && (methodDef->mName == BF_METHODNAME_MARKMEMBERS_STATIC))
  15964. {
  15965. typeInstance->mHasStaticMarkMethod = true;
  15966. }
  15967. if ((methodDef->mMethodType == BfMethodType_Normal) && (methodDef->mIsStatic) && (methodDef->mName == BF_METHODNAME_FIND_TLS_MEMBERS))
  15968. {
  15969. typeInstance->mHasTLSFindMethod = true;
  15970. }
  15971. }
  15972. if (isTemporaryFunc)
  15973. {
  15974. BF_ASSERT((mCompiler->mIsResolveOnly) && (mCompiler->mResolvePassData->mAutoComplete != NULL));
  15975. mangledName = "autocomplete_tmp";
  15976. }
  15977. if (!mBfIRBuilder->mIgnoreWrites)
  15978. {
  15979. BfIRFunction prevFunc;
  15980. // Remove old version (if we have one)
  15981. prevFunc = mBfIRBuilder->GetFunction(mangledName);
  15982. if (prevFunc)
  15983. {
  15984. if (methodDef->mIsExtern)
  15985. {
  15986. // Allow this
  15987. BfLogSysM("Function collision allowed multiple extern functions for %p: %d\n", methodInstance, prevFunc.mId);
  15988. }
  15989. else if (typeInstance->IsIRFuncUsed(prevFunc))
  15990. {
  15991. // We can have a collision of names when we have generic methods that differ only in
  15992. // their constraints, but they should only collide in their unspecialized form
  15993. // since only one will be chosen for a given concrete type
  15994. mCurMethodInstance->mMangleWithIdx = true;
  15995. mangledName.Clear();
  15996. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), mCurMethodInstance);
  15997. prevFunc = mBfIRBuilder->GetFunction(mangledName);
  15998. BfLogSysM("Function collision forced mangleWithIdx for %p: %d\n", methodInstance, prevFunc.mId);
  15999. }
  16000. else
  16001. {
  16002. BfLogSysM("Function collision erased prevFunc %p: %d\n", methodInstance, prevFunc.mId);
  16003. mBfIRBuilder->Func_EraseFromParent(prevFunc);
  16004. }
  16005. }
  16006. }
  16007. if (typeInstance != mContext->mBfObjectType)
  16008. {
  16009. // Only allow attributes on System.Object methods that can be handled inside the DefBuilder
  16010. GetMethodCustomAttributes(methodInstance);
  16011. }
  16012. // if (prevFunc)
  16013. // {
  16014. // if (methodDef->mIsExtern)
  16015. // {
  16016. // BfLogSysM("Reusing function for %p: %d\n", methodInstance, prevFunc.mId);
  16017. // methodInstance->mIRFunction = prevFunc;
  16018. // }
  16019. // else
  16020. // {
  16021. // if ((methodInstance->IsSpecializedByAutoCompleteMethod()) ||
  16022. // ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mResolveType >= BfResolveType_GoToDefinition)))
  16023. // {
  16024. // // If we're doing re-pass over the methods for something like BfResolveType_ShowFileSymbolReferences, then allow this collision
  16025. // BfLogSysM("Ignoring function name collision\n");
  16026. // }
  16027. // else
  16028. // {
  16029. // if (methodDef->mMethodDeclaration == NULL)
  16030. // {
  16031. // AssertErrorState();
  16032. // }
  16033. // else
  16034. // {
  16035. // BF_ASSERT(mIsSpecialModule);
  16036. // if ((mCompiler->mRevision == 1) && (HasCompiledOutput()))
  16037. // {
  16038. // // We shouldn't have name collisions on the first run!
  16039. // AssertErrorState();
  16040. // }
  16041. // }
  16042. // }
  16043. // BfLogSysM("Before erase\n");
  16044. // mBfIRBuilder->Func_EraseFromParent(prevFunc);
  16045. // }
  16046. // }
  16047. bool isIntrinsic = false;
  16048. if (!methodInstance->mIRFunction)
  16049. {
  16050. BfIRFunction func;
  16051. bool wantsLLVMFunc = ((!typeInstance->IsUnspecializedType()) && (!methodDef->IsEmptyPartial())) && (funcType);
  16052. /*if (mCurTypeInstance->mTypeDef->mName->ToString() == "ClassA")
  16053. {
  16054. if (!mIsReified)
  16055. wantsLLVMFunc = false;
  16056. }*/
  16057. if (wantsLLVMFunc)
  16058. {
  16059. func = GetIntrinsic(methodInstance, true);
  16060. if (func)
  16061. {
  16062. isIntrinsic = true;
  16063. }
  16064. else
  16065. {
  16066. func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, mangledName);
  16067. BfLogSysM("Creating FuncId:%d %s in module %p\n", func.mId, mangledName.c_str(), this);
  16068. if (methodInstance->mAlwaysInline)
  16069. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_AlwaysInline);
  16070. // if (prevFunc)
  16071. // BfLogSysM("Removing Func %d, replacing with %d\n", prevFunc.mId, func.mId);
  16072. }
  16073. methodInstance->mIRFunction = func;
  16074. //if (!ignoreWrites)
  16075. //BF_ASSERT(!func.IsFake());
  16076. }
  16077. }
  16078. if (outIsIntrinsic != NULL)
  16079. *outIsIntrinsic = isIntrinsic;
  16080. if (!isIntrinsic)
  16081. SetupIRMethod(methodInstance, methodInstance->mIRFunction, methodInstance->mAlwaysInline);
  16082. }
  16083. void BfModule::CheckHotMethod(BfMethodInstance* methodInstance, const StringImpl& inMangledName)
  16084. {
  16085. if (methodInstance->mHotMethod != NULL)
  16086. return;
  16087. if ((mCompiler->mOptions.mAllowHotSwapping) && (!methodInstance->mIsUnspecialized))
  16088. {
  16089. auto srcTypeInst = methodInstance->GetOwner();
  16090. StringT<128> mangledName = inMangledName;
  16091. if (mangledName.IsEmpty())
  16092. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), methodInstance);
  16093. // We always keep the current primary method at the same address
  16094. BfHotMethod* hotMethod;
  16095. BfHotMethod** hotMethodPtr;
  16096. if (mCompiler->mHotData->mMethodMap.TryAdd(mangledName, NULL, &hotMethodPtr))
  16097. {
  16098. hotMethod = new BfHotMethod();
  16099. *hotMethodPtr = hotMethod;
  16100. hotMethod->mRefCount = 1;
  16101. hotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_IsBound);
  16102. #ifdef BF_DBG_HOTMETHOD_IDX
  16103. static int sMethodIdx = 0;
  16104. hotMethod->mMethodIdx = sMethodIdx++;
  16105. #endif
  16106. BfLogSysM("HotMethodData %p created for method %p %s - %s\n", hotMethod, methodInstance, MethodToString(methodInstance).c_str(), mangledName.c_str());
  16107. }
  16108. else
  16109. {
  16110. hotMethod = *hotMethodPtr;
  16111. if ((hotMethod->mFlags & BfHotDepDataFlag_IsBound) != 0)
  16112. {
  16113. // This is a duplicate mangled name - we link to this new entry via a 'BfHotDupMethod'
  16114. auto prevHotMethod = *hotMethodPtr;
  16115. hotMethod = new BfHotMethod();
  16116. hotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_IsBound);
  16117. BfHotDupMethod* hotDupMethod = new BfHotDupMethod(hotMethod);
  16118. hotDupMethod->mRefCount++;
  16119. prevHotMethod->mReferences.Add(hotDupMethod);
  16120. prevHotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_HasDup);
  16121. BfLogSysM("HotMethodData %p (duplicate of %p) created for method %p %s - %s\n", hotMethod, prevHotMethod, methodInstance, MethodToString(methodInstance).c_str(), mangledName.c_str());
  16122. }
  16123. else if (mCompiler->IsHotCompile())
  16124. {
  16125. // Link the previous version into the mPrevVersion
  16126. BfHotMethod* prevMethod = new BfHotMethod();
  16127. prevMethod->mRefCount = 1;
  16128. prevMethod->mPrevVersion = hotMethod->mPrevVersion;
  16129. hotMethod->mPrevVersion = prevMethod;
  16130. prevMethod->mSrcTypeVersion = hotMethod->mSrcTypeVersion;
  16131. hotMethod->mSrcTypeVersion = NULL;
  16132. prevMethod->mFlags = hotMethod->mFlags;
  16133. hotMethod->mFlags = BfHotDepDataFlag_IsBound;
  16134. hotMethod->mReferences.MoveTo(prevMethod->mReferences);
  16135. #ifdef BF_DBG_HOTMETHOD_NAME
  16136. prevMethod->mMangledName = hotMethod->mMangledName;
  16137. #endif
  16138. BfLogSysM("HotMethodData %p created for prevmethod of %p for method %p %s\n", prevMethod, hotMethod, methodInstance, MethodToString(methodInstance).c_str());
  16139. }
  16140. else
  16141. {
  16142. BfLogSysM("HotMethodData %p used for method %p %s - %s\n", hotMethod, methodInstance, MethodToString(methodInstance).c_str(), mangledName.c_str());
  16143. hotMethod->Clear(true);
  16144. hotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_IsBound);
  16145. }
  16146. }
  16147. if (methodInstance->mIsClosure)
  16148. {
  16149. hotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_RetainMethodWithoutBinding);
  16150. }
  16151. hotMethod->mSrcTypeVersion = srcTypeInst->mHotTypeData->GetLatestVersion();
  16152. hotMethod->mSrcTypeVersion->mRefCount++;
  16153. hotMethod->mRefCount++;
  16154. #ifdef BF_DBG_HOTMETHOD_NAME
  16155. hotMethod->mMangledName = mangledName;
  16156. #endif
  16157. methodInstance->mHotMethod = hotMethod;
  16158. }
  16159. }
  16160. // methodDeclaration is NULL for default constructors
  16161. void BfModule::DoMethodDeclaration(BfMethodDeclaration* methodDeclaration, bool isTemporaryFunc, bool addToWorkList)
  16162. {
  16163. BP_ZONE("BfModule::BfMethodDeclaration");
  16164. // We could trigger a DoMethodDeclaration from a const resolver or other location, so we reset it here
  16165. // to effectively make mIgnoreWrites method-scoped
  16166. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, mWantsIRIgnoreWrites || mCurMethodInstance->mIsUnspecialized);
  16167. SetAndRestoreValue<bool> prevIsCapturingMethodMatchInfo;
  16168. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, NULL);
  16169. if (mCompiler->IsAutocomplete())
  16170. prevIsCapturingMethodMatchInfo.Init(mCompiler->mResolvePassData->mAutoComplete->mIsCapturingMethodMatchInfo, false);
  16171. if (mCurMethodInstance->mMethodInstanceGroup->mOnDemandKind == BfMethodOnDemandKind_NoDecl_AwaitingReference)
  16172. mCurMethodInstance->mMethodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_Decl_AwaitingReference;
  16173. bool ignoreWrites = mBfIRBuilder->mIgnoreWrites;
  16174. if (mAwaitingInitFinish)
  16175. FinishInit();
  16176. auto typeInstance = mCurTypeInstance;
  16177. auto typeDef = typeInstance->mTypeDef;
  16178. auto methodDef = mCurMethodInstance->mMethodDef;
  16179. BF_ASSERT(methodDef->mName != "__ASSERTNAME");
  16180. if (typeInstance->IsClosure())
  16181. {
  16182. if (methodDef->mName == "Invoke")
  16183. return;
  16184. }
  16185. auto methodInstance = mCurMethodInstance;
  16186. if ((methodInstance->IsSpecializedByAutoCompleteMethod()) || (mCurTypeInstance->IsFunction()))
  16187. addToWorkList = false;
  16188. bool hasNonGenericParams = false;
  16189. bool hasGenericParams = false;
  16190. int dependentGenericStartIdx = 0;
  16191. if (methodDef->mIsLocalMethod)
  16192. {
  16193. // If we're a local generic method inside an outer generic method, we can still be considered unspecialized
  16194. // if our outer method's generic args are specialized but ours are unspecialized. This is because locals get
  16195. // instantiated uniquely for each specialized or unspecialized pass through the outer method, but the local
  16196. // method still 'inherits' the outer's generic arguments -- but we still need to make an unspecialized pass
  16197. // over the local method each time
  16198. auto rootMethodInstance = prevMethodState.mPrevVal->GetRootMethodState()->mMethodInstance;
  16199. dependentGenericStartIdx = 0;
  16200. if (rootMethodInstance->mMethodInfoEx != NULL)
  16201. dependentGenericStartIdx = (int)rootMethodInstance->mMethodInfoEx->mMethodGenericArguments.size();
  16202. methodInstance->mIsUnspecialized = rootMethodInstance->mIsUnspecialized;
  16203. methodInstance->mIsUnspecializedVariation = rootMethodInstance->mIsUnspecializedVariation;
  16204. }
  16205. for (int genericArgIdx = dependentGenericStartIdx; genericArgIdx < (int) methodInstance->GetNumGenericArguments(); genericArgIdx++)
  16206. {
  16207. auto genericArgType = methodInstance->mMethodInfoEx->mMethodGenericArguments[genericArgIdx];
  16208. if (genericArgType->IsGenericParam())
  16209. {
  16210. hasGenericParams = true;
  16211. auto genericParam = (BfGenericParamType*)genericArgType;
  16212. methodInstance->mIsUnspecialized = true;
  16213. if ((genericParam->mGenericParamKind != BfGenericParamKind_Method) || (genericParam->mGenericParamIdx != genericArgIdx))
  16214. methodInstance->mIsUnspecializedVariation = true;
  16215. }
  16216. else
  16217. {
  16218. hasNonGenericParams = true;
  16219. if (genericArgType->IsUnspecializedType())
  16220. {
  16221. methodInstance->mIsUnspecialized = true;
  16222. methodInstance->mIsUnspecializedVariation = true;
  16223. }
  16224. }
  16225. }
  16226. if ((hasGenericParams) && (hasNonGenericParams))
  16227. {
  16228. methodInstance->mIsUnspecializedVariation = true;
  16229. }
  16230. if (typeInstance->IsUnspecializedType())
  16231. {
  16232. // A specialized method within an unspecialized type is considered an unspecialized variation -- in the sense that we don't
  16233. // actually want to do method processing on it
  16234. if ((!methodInstance->mIsUnspecialized) && (methodInstance->GetNumGenericArguments() != 0))
  16235. methodInstance->mIsUnspecializedVariation = true;
  16236. methodInstance->mIsUnspecialized = true;
  16237. }
  16238. methodInstance->mIsUnspecializedVariation |= typeInstance->IsUnspecializedTypeVariation();
  16239. for (auto genericParamDef : methodDef->mGenericParams)
  16240. {
  16241. if (mCompiler->IsAutocomplete())
  16242. {
  16243. auto autoComplete = mCompiler->mResolvePassData->mAutoComplete;
  16244. //autoComplete->CheckTypeRef()
  16245. }
  16246. }
  16247. if (methodInstance->mIsUnspecializedVariation)
  16248. {
  16249. }
  16250. if (methodInstance->mIsUnspecializedVariation)
  16251. BF_ASSERT(methodInstance->mIsUnspecialized);
  16252. if (methodDef->mMethodType == BfMethodType_Mixin)
  16253. methodInstance->mIsUnspecialized = true;
  16254. BfAutoComplete* bfAutocomplete = NULL;
  16255. if (mCompiler->mResolvePassData != NULL)
  16256. bfAutocomplete = mCompiler->mResolvePassData->mAutoComplete;
  16257. if (methodInstance->mMethodInfoEx != NULL)
  16258. {
  16259. for (int genericParamIdx = 0; genericParamIdx < (int)methodInstance->mMethodInfoEx->mGenericParams.size(); genericParamIdx++)
  16260. {
  16261. auto genericParam = methodInstance->mMethodInfoEx->mGenericParams[genericParamIdx];
  16262. if (genericParamIdx < (int)methodDef->mGenericParams.size())
  16263. {
  16264. genericParam->mExternType = GetGenericParamType(BfGenericParamKind_Method, genericParamIdx);
  16265. }
  16266. else
  16267. {
  16268. auto externConstraintDef = genericParam->GetExternConstraintDef();
  16269. genericParam->mExternType = ResolveTypeRef(externConstraintDef->mTypeRef);
  16270. auto autoComplete = mCompiler->GetAutoComplete();
  16271. if (autoComplete != NULL)
  16272. autoComplete->CheckTypeRef(externConstraintDef->mTypeRef, false);
  16273. if (genericParam->mExternType != NULL)
  16274. {
  16275. //
  16276. }
  16277. else
  16278. genericParam->mExternType = GetPrimitiveType(BfTypeCode_Var);
  16279. }
  16280. ResolveGenericParamConstraints(genericParam, methodInstance->mIsUnspecialized);
  16281. if (genericParamIdx < (int)methodDef->mGenericParams.size())
  16282. {
  16283. auto genericParamDef = methodDef->mGenericParams[genericParamIdx];
  16284. if (bfAutocomplete != NULL)
  16285. {
  16286. for (auto nameNode : genericParamDef->mNameNodes)
  16287. {
  16288. HandleMethodGenericParamRef(nameNode, typeDef, methodDef, genericParamIdx);
  16289. }
  16290. }
  16291. }
  16292. }
  16293. for (auto genericParam : methodInstance->mMethodInfoEx->mGenericParams)
  16294. {
  16295. for (auto constraintTypeInst : genericParam->mInterfaceConstraints)
  16296. AddDependency(constraintTypeInst, mCurTypeInstance, BfDependencyMap::DependencyFlag_Constraint);
  16297. if (genericParam->mTypeConstraint != NULL)
  16298. AddDependency(genericParam->mTypeConstraint, mCurTypeInstance, BfDependencyMap::DependencyFlag_Constraint);
  16299. }
  16300. }
  16301. if ((methodInstance->mIsAutocompleteMethod) && (methodDeclaration != NULL) && (!methodInstance->IsSpecializedGenericMethod()) && (methodDef->mIdx >= 0))
  16302. {
  16303. auto autoComplete = mCompiler->mResolvePassData->mAutoComplete;
  16304. BfAstNode* nameNode = methodDeclaration->mNameNode;
  16305. if (nameNode == NULL)
  16306. {
  16307. if (auto ctorDeclaration = BfNodeDynCast<BfConstructorDeclaration>(methodDeclaration))
  16308. nameNode = ctorDeclaration->mThisToken;
  16309. }
  16310. if (autoComplete->IsAutocompleteNode(nameNode))
  16311. {
  16312. autoComplete->mInsertStartIdx = nameNode->GetSrcStart();
  16313. autoComplete->mInsertEndIdx = nameNode->GetSrcEnd();
  16314. autoComplete->mDefType = typeDef;
  16315. autoComplete->mDefMethod = methodDef;
  16316. autoComplete->SetDefinitionLocation(nameNode);
  16317. if (methodDef->mIsOverride)
  16318. {
  16319. for (int virtIdx = 0; virtIdx < (int)typeInstance->mVirtualMethodTable.size(); virtIdx++)
  16320. {
  16321. auto& ventry = typeInstance->mVirtualMethodTable[virtIdx];
  16322. if (ventry.mDeclaringMethod.mMethodNum == -1)
  16323. continue;
  16324. BfMethodInstance* virtMethod = ventry.mImplementingMethod;
  16325. if (virtMethod != NULL)
  16326. {
  16327. auto virtMethodDeclaration = virtMethod->mMethodDef->GetMethodDeclaration();
  16328. if ((virtMethod->GetOwner() == typeInstance) && (virtMethodDeclaration != NULL) &&
  16329. (virtMethodDeclaration->GetSrcStart() == methodDeclaration->GetSrcStart()))
  16330. {
  16331. // Is matching method
  16332. if (virtIdx < (int)typeInstance->mBaseType->mVirtualMethodTable.size())
  16333. {
  16334. auto baseType = typeInstance->mBaseType;
  16335. if (baseType != NULL)
  16336. {
  16337. while ((baseType->mBaseType != NULL) && (virtIdx < baseType->mBaseType->mVirtualMethodTableSize))
  16338. baseType = baseType->mBaseType;
  16339. BfMethodInstance* baseVirtMethod = baseType->mVirtualMethodTable[virtIdx].mImplementingMethod;
  16340. autoComplete->SetDefinitionLocation(baseVirtMethod->mMethodDef->GetRefNode(), true);
  16341. autoComplete->mDefType = baseType->mTypeDef;
  16342. autoComplete->mDefMethod = baseVirtMethod->mMethodDef;
  16343. }
  16344. }
  16345. break;
  16346. }
  16347. }
  16348. }
  16349. }
  16350. }
  16351. }
  16352. bool reportErrors = true;
  16353. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL))
  16354. reportErrors = true;
  16355. // Only the defining contexts needs to report errors here
  16356. SetAndRestoreValue<bool> prevReporErrors(mReportErrors, reportErrors);
  16357. if (methodDef->mMethodType == BfMethodType_Dtor)
  16358. {
  16359. if (methodDef->mIsStatic)
  16360. {
  16361. }
  16362. else
  16363. {
  16364. if ((typeInstance->IsStruct()) || (typeInstance->IsTypedPrimitive()))
  16365. {
  16366. BfAstNode* refNode = methodDeclaration;
  16367. if (refNode == NULL)
  16368. {
  16369. // Whatever caused this ctor to be generated should have caused another failure
  16370. // But that failure might not be generated until the ctor is generated
  16371. }
  16372. else
  16373. {
  16374. auto dtorDecl = BfNodeDynCast<BfDestructorDeclaration>(methodDeclaration);
  16375. if (dtorDecl != NULL)
  16376. refNode = dtorDecl->mThisToken;
  16377. Fail("Structs cannot have destructors", refNode);
  16378. }
  16379. }
  16380. auto methodDeclaration = methodDef->GetMethodDeclaration();
  16381. if ((methodDeclaration != NULL) && (methodDeclaration->mVirtualSpecifier != NULL) &&
  16382. (mCurTypeInstance != mContext->mBfObjectType))
  16383. {
  16384. Fail("Virtual specifier is not required, all destructors are implicitly virtual.", methodDeclaration->mVirtualSpecifier);
  16385. }
  16386. }
  16387. }
  16388. BfType* resolvedReturnType = NULL;
  16389. if (((methodDef->mMethodType == BfMethodType_Normal) || (methodDef->mMethodType == BfMethodType_CtorCalcAppend) || (methodDef->mMethodType == BfMethodType_PropertyGetter) || (methodDef->mMethodType == BfMethodType_Operator)) &&
  16390. (methodDef->mReturnTypeRef != NULL))
  16391. {
  16392. SetAndRestoreValue<bool> prevIngoreErrors(mIgnoreErrors, mIgnoreErrors || (methodDef->GetPropertyDeclaration() != NULL));
  16393. resolvedReturnType = ResolveTypeRef(methodDef->mReturnTypeRef, BfPopulateType_Declaration,
  16394. (BfResolveTypeRefFlags)(BfResolveTypeRefFlag_NoResolveGenericParam | BfResolveTypeRefFlag_AllowRef | BfResolveTypeRefFlag_AllowRefGeneric));
  16395. if ((resolvedReturnType != NULL) && (resolvedReturnType->IsVar()) && (methodDef->mMethodType != BfMethodType_Mixin))
  16396. {
  16397. Fail("Cannot declare var return types", methodDef->mReturnTypeRef);
  16398. resolvedReturnType = GetPrimitiveType(BfTypeCode_Var);
  16399. }
  16400. if (resolvedReturnType == NULL)
  16401. resolvedReturnType = GetPrimitiveType(BfTypeCode_Var);
  16402. }
  16403. else
  16404. {
  16405. resolvedReturnType = ResolveTypeDef(mSystem->mTypeVoid);
  16406. }
  16407. BF_ASSERT(resolvedReturnType != NULL);
  16408. mCurMethodInstance->mReturnType = resolvedReturnType;
  16409. //TODO: We used to NOT add the return value dependency for specialized methods, but when we have types that are
  16410. // specialized based on the method's generic param then they can get deleted if no one else has referred to them (yet)
  16411. //if (!methodInstance->IsSpecializedGenericMethod())
  16412. AddDependency(resolvedReturnType, typeInstance, BfDependencyMap::DependencyFlag_ParamOrReturnValue);
  16413. if (methodDef->mExplicitInterface != NULL)
  16414. {
  16415. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL))
  16416. mCompiler->mResolvePassData->mAutoComplete->CheckTypeRef(methodDef->mExplicitInterface, false);
  16417. auto explicitInterface = ResolveTypeRef(methodDef->mExplicitInterface, BfPopulateType_Declaration);
  16418. if (explicitInterface != NULL)
  16419. mCurMethodInstance->GetMethodInfoEx()->mExplicitInterface = explicitInterface->ToTypeInstance();
  16420. if ((mCurMethodInstance->mMethodInfoEx != NULL) && (mCurMethodInstance->mMethodInfoEx->mExplicitInterface != NULL))
  16421. {
  16422. bool interfaceFound = false;
  16423. for (auto ifaceInst : typeInstance->mInterfaces)
  16424. interfaceFound |= ifaceInst.mInterfaceType == mCurMethodInstance->mMethodInfoEx->mExplicitInterface;
  16425. if (!interfaceFound)
  16426. {
  16427. if (methodDef->mMethodDeclaration != NULL)
  16428. Fail("Containing class has not declared to implement this interface", methodDef->mMethodDeclaration);
  16429. else
  16430. {
  16431. // For property decls, we should have already given the error during type population
  16432. if (mCompiler->mRevision == 1)
  16433. AssertErrorState();
  16434. }
  16435. }
  16436. }
  16437. }
  16438. bool isThisStruct = mCurTypeInstance->IsStruct();
  16439. BfType* thisType = NULL;
  16440. if ((!methodDef->mIsStatic) && (!mCurTypeInstance->IsValuelessType()))
  16441. {
  16442. if ((isThisStruct) || (mCurTypeInstance->IsTypedPrimitive()))
  16443. {
  16444. thisType = mCurTypeInstance;
  16445. if (thisType == NULL)
  16446. return;
  16447. if ((thisType->IsSplattable()) && (!methodDef->HasNoThisSplat()))
  16448. {
  16449. BfTypeUtils::SplatIterate([&](BfType* checkType)
  16450. {
  16451. PopulateType(checkType, BfPopulateType_Data);
  16452. }, thisType);
  16453. }
  16454. }
  16455. else
  16456. {
  16457. thisType = mCurTypeInstance;
  16458. PopulateType(thisType, BfPopulateType_Declaration);
  16459. }
  16460. }
  16461. int implicitParamCount = 0;
  16462. if ((mCurMethodInstance->mMethodInfoEx != NULL) && (mCurMethodInstance->mMethodInfoEx->mClosureInstanceInfo != NULL))
  16463. implicitParamCount = (int)methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureEntries.size();
  16464. methodInstance->mMethodDef->mParams.Reserve((int)methodDef->mParams.size());
  16465. bool hadDelegateParams = false;
  16466. bool hadParams = false;
  16467. for (int paramIdx = 0; paramIdx < (int)methodDef->mParams.size() + implicitParamCount; paramIdx++)
  16468. {
  16469. BfClosureCapturedEntry* closureCaptureEntry = NULL;
  16470. BfParameterDef* paramDef = NULL;
  16471. int paramDefIdx = -1;
  16472. if (paramIdx < implicitParamCount)
  16473. closureCaptureEntry = &methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureEntries[paramIdx];
  16474. else
  16475. {
  16476. paramDefIdx = paramIdx - implicitParamCount;
  16477. paramDef = methodDef->mParams[paramDefIdx];
  16478. }
  16479. if (hadParams)
  16480. break;
  16481. if ((paramDef != NULL) && (mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL) &&
  16482. (paramDef->mParamKind != BfParamKind_AppendIdx))
  16483. mCompiler->mResolvePassData->mAutoComplete->CheckTypeRef(paramDef->mTypeRef, false);
  16484. if ((paramDef != NULL) && (paramDef->mParamDeclaration != NULL) && (paramDef->mParamDeclaration->mAttributes != NULL))
  16485. {
  16486. if (methodInstance->GetMethodInfoEx()->mMethodCustomAttributes == NULL)
  16487. methodInstance->mMethodInfoEx->mMethodCustomAttributes = new BfMethodCustomAttributes();
  16488. while ((int)methodInstance->mMethodInfoEx->mMethodCustomAttributes->mParamCustomAttributes.size() < paramIdx)
  16489. methodInstance->mMethodInfoEx->mMethodCustomAttributes->mParamCustomAttributes.push_back(NULL);
  16490. auto customAttributes = GetCustomAttributes(paramDef->mParamDeclaration->mAttributes, BfAttributeTargets_Parameter);
  16491. methodInstance->mMethodInfoEx->mMethodCustomAttributes->mParamCustomAttributes.push_back(customAttributes);
  16492. }
  16493. BfType* resolvedParamType = NULL;
  16494. if (closureCaptureEntry != NULL)
  16495. resolvedParamType = closureCaptureEntry->mType;
  16496. else if (paramDef->mTypeRef->IsA<BfLetTypeReference>())
  16497. {
  16498. Fail("Cannot declare 'let' parameters", paramDef->mTypeRef);
  16499. resolvedParamType = mContext->mBfObjectType;
  16500. }
  16501. else if (paramDef->mTypeRef->IsA<BfVarTypeReference>())
  16502. {
  16503. if (methodDef->mMethodType != BfMethodType_Mixin)
  16504. {
  16505. Fail("Cannot declare var parameters", paramDef->mTypeRef);
  16506. resolvedParamType = mContext->mBfObjectType;
  16507. }
  16508. else
  16509. resolvedParamType = GetPrimitiveType(BfTypeCode_Var);
  16510. }
  16511. BfType* unresolvedParamType = resolvedParamType;
  16512. bool wasGenericParam = false;
  16513. if (resolvedParamType == NULL)
  16514. {
  16515. SetAndRestoreValue<bool> prevIngoreErrors(mIgnoreErrors, mIgnoreErrors || (methodDef->GetPropertyDeclaration() != NULL));
  16516. resolvedParamType = ResolveTypeRef(paramDef->mTypeRef, BfPopulateType_Declaration,
  16517. (BfResolveTypeRefFlags)(BfResolveTypeRefFlag_NoResolveGenericParam | BfResolveTypeRefFlag_AllowRef | BfResolveTypeRefFlag_AllowRefGeneric | BfResolveTypeRefFlag_AllowGenericMethodParamConstValue));
  16518. }
  16519. if (resolvedParamType == NULL)
  16520. {
  16521. resolvedParamType = GetPrimitiveType(BfTypeCode_Var);
  16522. unresolvedParamType = resolvedParamType;
  16523. if (mCurTypeInstance->IsBoxed())
  16524. {
  16525. auto boxedType = (BfBoxedType*)mCurTypeInstance;
  16526. // If we failed a lookup here then we better have also failed it in the original type
  16527. BF_ASSERT(boxedType->mElementType->mModule->mHadBuildError || mContext->mFailTypes.Contains(boxedType->mElementType));
  16528. }
  16529. }
  16530. if (!methodInstance->IsSpecializedGenericMethod())
  16531. AddDependency(resolvedParamType, typeInstance, BfDependencyMap::DependencyFlag_ParamOrReturnValue);
  16532. PopulateType(resolvedParamType, BfPopulateType_Declaration);
  16533. AddDependency(resolvedParamType, mCurTypeInstance, BfDependencyMap::DependencyFlag_LocalUsage);
  16534. if ((paramDef != NULL) && (paramDef->mParamDeclaration != NULL) && (paramDef->mParamDeclaration->mInitializer != NULL) &&
  16535. (!paramDef->mParamDeclaration->mInitializer->IsA<BfBlock>()))
  16536. {
  16537. BfMethodState methodState;
  16538. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  16539. methodState.mTempKind = BfMethodState::TempKind_Static;
  16540. BfTypedValue defaultValue;
  16541. if (resolvedParamType->IsConstExprValue())
  16542. {
  16543. auto constExprType = (BfConstExprValueType*)resolvedParamType;
  16544. BfExprEvaluator exprEvaluator(this);
  16545. exprEvaluator.mExpectingType = constExprType->mType;
  16546. exprEvaluator.GetLiteral(NULL, constExprType->mValue);
  16547. defaultValue = exprEvaluator.GetResult();
  16548. }
  16549. else
  16550. {
  16551. BfConstResolver constResolver(this);
  16552. defaultValue = constResolver.Resolve(paramDef->mParamDeclaration->mInitializer, resolvedParamType, BfConstResolveFlag_NoCast);
  16553. if ((defaultValue) && (defaultValue.mType != resolvedParamType))
  16554. {
  16555. SetAndRestoreValue<bool> prevIgnoreWrite(mBfIRBuilder->mIgnoreWrites, true);
  16556. auto castedDefaultValue = Cast(paramDef->mParamDeclaration->mInitializer, defaultValue, resolvedParamType, (BfCastFlags)(BfCastFlags_SilentFail | BfCastFlags_NoConversionOperator));
  16557. if ((castedDefaultValue) && (castedDefaultValue.mValue.IsConst()))
  16558. {
  16559. defaultValue = castedDefaultValue; // Good!
  16560. }
  16561. else if (!CanImplicitlyCast(defaultValue, resolvedParamType))
  16562. {
  16563. // We only care that we get a constant value that can be implicitly casted at the callsite- even if that requires
  16564. // a conversion operator.
  16565. // This should throw an error
  16566. defaultValue = Cast(paramDef->mParamDeclaration->mInitializer, defaultValue, resolvedParamType);
  16567. AssertErrorState();
  16568. if (!defaultValue.mValue.IsConst())
  16569. defaultValue = BfTypedValue();
  16570. }
  16571. }
  16572. }
  16573. if (!defaultValue)
  16574. {
  16575. defaultValue = GetDefaultTypedValue(resolvedParamType);
  16576. if (!defaultValue.mValue.IsConst())
  16577. defaultValue = BfTypedValue();
  16578. }
  16579. if (defaultValue)
  16580. {
  16581. BF_ASSERT(defaultValue.mValue.IsConst());
  16582. while ((int)mCurMethodInstance->mDefaultValues.size() < paramDefIdx)
  16583. mCurMethodInstance->mDefaultValues.Add(BfIRValue());
  16584. CurrentAddToConstHolder(defaultValue.mValue);
  16585. mCurMethodInstance->mDefaultValues.Add(defaultValue.mValue);
  16586. }
  16587. }
  16588. if ((paramDef != NULL) && (paramDef->mParamKind == BfParamKind_Params))
  16589. {
  16590. bool addParams = true;
  16591. bool isValid = false;
  16592. auto resolvedParamTypeInst = resolvedParamType->ToTypeInstance();
  16593. if ((resolvedParamTypeInst != NULL) && (resolvedParamTypeInst->mTypeDef == mCompiler->mSpanTypeDef))
  16594. {
  16595. // Span<T>
  16596. isValid = true;
  16597. }
  16598. else if (resolvedParamType->IsArray())
  16599. {
  16600. // Array is the 'normal' params type
  16601. isValid = true;
  16602. }
  16603. else if ((resolvedParamType->IsDelegate()) || (resolvedParamType->IsFunction()))
  16604. {
  16605. hadDelegateParams = true;
  16606. // This means we copy the params from a delegate
  16607. BfMethodParam methodParam;
  16608. methodParam.mResolvedType = resolvedParamType;
  16609. methodParam.mParamDefIdx = paramDefIdx;
  16610. methodParam.mDelegateParamIdx = 0;
  16611. auto invokeMethodInstance = methodParam.GetDelegateParamInvoke();
  16612. for (int delegateParamIdx = 0; delegateParamIdx < invokeMethodInstance->GetParamCount(); delegateParamIdx++)
  16613. {
  16614. methodParam.mDelegateParamIdx = delegateParamIdx;
  16615. mCurMethodInstance->mParams.Add(methodParam);
  16616. auto paramType = invokeMethodInstance->GetParamType(delegateParamIdx);
  16617. if (!methodInstance->IsSpecializedGenericMethod())
  16618. AddDependency(paramType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ParamOrReturnValue);
  16619. }
  16620. isValid = true;
  16621. addParams = false;
  16622. }
  16623. else if (resolvedParamType->IsGenericParam())
  16624. {
  16625. auto genericParamInstance = GetGenericParamInstance((BfGenericParamType*)resolvedParamType);
  16626. if (genericParamInstance->mTypeConstraint != NULL)
  16627. {
  16628. auto typeInstConstraint = genericParamInstance->mTypeConstraint->ToTypeInstance();
  16629. if (genericParamInstance->mTypeConstraint->IsArray())
  16630. {
  16631. BfMethodParam methodParam;
  16632. methodParam.mResolvedType = resolvedParamType;
  16633. methodParam.mParamDefIdx = paramDefIdx;
  16634. mCurMethodInstance->mParams.Add(methodParam);
  16635. isValid = true;
  16636. }
  16637. else if ((genericParamInstance->mTypeConstraint->IsDelegate()) || (genericParamInstance->mTypeConstraint->IsFunction()) ||
  16638. ((genericParamInstance != NULL) && (typeInstConstraint != NULL) &&
  16639. ((typeInstConstraint->mTypeDef == mCompiler->mDelegateTypeDef) || (typeInstConstraint->mTypeDef == mCompiler->mFunctionTypeDef))))
  16640. {
  16641. mCurMethodInstance->mHadGenericDelegateParams = true;
  16642. isValid = true;
  16643. addParams = false;
  16644. }
  16645. }
  16646. }
  16647. else
  16648. {
  16649. auto paramTypeInst = resolvedParamType->ToTypeInstance();
  16650. if ((paramTypeInst != NULL) &&
  16651. ((paramTypeInst->mTypeDef == mCompiler->mDelegateTypeDef) || (paramTypeInst->mTypeDef == mCompiler->mFunctionTypeDef)))
  16652. {
  16653. // If we have a 'params T' and 'T' gets specialized with actually 'Delegate' or 'Function' then just ignore it
  16654. isValid = true;
  16655. addParams = false;
  16656. }
  16657. }
  16658. if (!isValid)
  16659. {
  16660. Fail("Parameters with 'params' specifiers can only be used for array, span, delegate, or function types", paramDef->mParamDeclaration->mModToken);
  16661. // Failure case, make it an Object[]
  16662. resolvedParamType = CreateArrayType(mContext->mBfObjectType, 1);
  16663. }
  16664. if (addParams)
  16665. {
  16666. BfMethodParam methodParam;
  16667. methodParam.mResolvedType = resolvedParamType;
  16668. methodParam.mParamDefIdx = paramDefIdx;
  16669. mCurMethodInstance->mParams.push_back(methodParam);
  16670. }
  16671. if (paramDefIdx < (int)methodDef->mParams.size() - 1)
  16672. {
  16673. Fail("Only the last parameter can specify 'params'", paramDef->mParamDeclaration->mModToken);
  16674. }
  16675. }
  16676. else
  16677. {
  16678. BfMethodParam methodParam;
  16679. methodParam.mResolvedType = resolvedParamType;
  16680. methodParam.mParamDefIdx = paramDefIdx;
  16681. mCurMethodInstance->mParams.Add(methodParam);
  16682. }
  16683. }
  16684. if (hadDelegateParams)
  16685. {
  16686. HashSet<String> usedNames;
  16687. Dictionary<int, int> usedParamDefIdx;
  16688. for (auto methodParam : methodDef->mParams)
  16689. {
  16690. usedNames.Add(methodParam->mName);
  16691. }
  16692. for (auto& methodParam : mCurMethodInstance->mParams)
  16693. {
  16694. if ((methodParam.mParamDefIdx != -1) && (methodParam.mDelegateParamIdx == 0))
  16695. {
  16696. int* refCount = NULL;
  16697. usedParamDefIdx.TryAdd(methodParam.mParamDefIdx, NULL, &refCount);
  16698. (*refCount)++;
  16699. }
  16700. }
  16701. for (auto& methodParam : mCurMethodInstance->mParams)
  16702. {
  16703. if (methodParam.mDelegateParamIdx != -1)
  16704. {
  16705. if (usedParamDefIdx[methodParam.mParamDefIdx] > 1)
  16706. methodParam.mDelegateParamNameCombine = true;
  16707. BfMethodInstance* invokeMethodInstance = methodParam.GetDelegateParamInvoke();
  16708. String paramName = invokeMethodInstance->GetParamName(methodParam.mDelegateParamIdx);
  16709. if (usedNames.Contains(paramName))
  16710. methodParam.mDelegateParamNameCombine = true;
  16711. }
  16712. }
  16713. }
  16714. int argIdx = 0;
  16715. PopulateType(methodInstance->mReturnType, BfPopulateType_Data);
  16716. if (methodInstance->HasStructRet())
  16717. argIdx++;
  16718. if (!methodDef->mIsStatic)
  16719. {
  16720. if (methodInstance->GetParamIsSplat(-1))
  16721. argIdx += methodInstance->GetParamType(-1)->GetSplatCount();
  16722. else if (!methodInstance->GetOwner()->IsValuelessType())
  16723. argIdx++;
  16724. }
  16725. for (auto& methodParam : mCurMethodInstance->mParams)
  16726. {
  16727. if (methodParam.mResolvedType->IsMethodRef())
  16728. {
  16729. methodParam.mIsSplat = true;
  16730. }
  16731. else if (methodParam.mResolvedType->IsComposite())
  16732. {
  16733. PopulateType(methodParam.mResolvedType, BfPopulateType_Data);
  16734. if (methodParam.mResolvedType->IsSplattable())
  16735. {
  16736. int splatCount = methodParam.mResolvedType->GetSplatCount();
  16737. if (argIdx + splatCount <= mCompiler->mOptions.mMaxSplatRegs)
  16738. {
  16739. methodParam.mIsSplat = true;
  16740. argIdx += splatCount;
  16741. continue;
  16742. }
  16743. }
  16744. }
  16745. argIdx++;
  16746. }
  16747. bool hasExternSpecifier = (methodDeclaration != NULL) && (methodDeclaration->mExternSpecifier != NULL);
  16748. if ((hasExternSpecifier) && (methodDeclaration->mBody != NULL))
  16749. {
  16750. Fail("Cannot 'extern' and declare a body", methodDeclaration->mExternSpecifier);
  16751. }
  16752. else if ((methodDeclaration != NULL) && (methodDeclaration->mBody == NULL) && (!hasExternSpecifier) &&
  16753. (!typeInstance->IsInterface()) && (!mCurTypeInstance->IsDelegate()) && (!mCurTypeInstance->IsFunction()) &&
  16754. (!methodDef->mIsPartial) && (!methodDef->mIsAbstract) &&
  16755. (!methodDef->mIsSkipCall))
  16756. {
  16757. if (methodDeclaration->mEndSemicolon == NULL)
  16758. {
  16759. AssertParseErrorState();
  16760. }
  16761. else
  16762. {
  16763. bool isError = true;
  16764. if (typeInstance->IsTypedPrimitive())
  16765. {
  16766. if (auto operatorDeclaration = BfNodeDynCast<BfOperatorDeclaration>(methodDeclaration))
  16767. {
  16768. if ((operatorDeclaration->mIsConvOperator) && (methodInstance->mParams.size() == 1))
  16769. {
  16770. if (((methodInstance->mReturnType == typeInstance) && (methodInstance->GetParamType(0) == typeInstance->GetUnderlyingType())) ||
  16771. ((methodInstance->mReturnType == typeInstance->GetUnderlyingType()) && (methodInstance->GetParamType(0) == typeInstance)))
  16772. {
  16773. isError = false;
  16774. }
  16775. }
  16776. }
  16777. }
  16778. if (isError)
  16779. {
  16780. Fail(StrFormat("'%s' must declare a body because it is not marked abstract, extern, or partial",
  16781. MethodToString(methodInstance).c_str()),
  16782. methodDef->GetRefNode());
  16783. }
  16784. }
  16785. }
  16786. if (methodDef->IsEmptyPartial())
  16787. hasExternSpecifier = true;
  16788. if (!methodInstance->IsAutocompleteMethod())
  16789. {
  16790. auto defaultMethodInstance = methodInstance->mMethodInstanceGroup->mDefault;
  16791. int implicitParamCount = methodInstance->GetImplicitParamCount();
  16792. int defaultImplicitParamCount = defaultMethodInstance->GetImplicitParamCount();
  16793. int actualParamCount = (int)methodInstance->mParams.size() - implicitParamCount;
  16794. BF_ASSERT((actualParamCount == defaultMethodInstance->mParams.size() - defaultImplicitParamCount) || (defaultMethodInstance->mHadGenericDelegateParams));
  16795. mCurMethodInstance->mHadGenericDelegateParams = defaultMethodInstance->mHadGenericDelegateParams;
  16796. int paramIdx = 0;
  16797. int defaultParamIdx = 0;
  16798. while (true)
  16799. {
  16800. bool isDone = paramIdx + implicitParamCount >= (int)methodInstance->mParams.size();
  16801. bool isDefaultDone = defaultParamIdx + defaultImplicitParamCount >= (int)defaultMethodInstance->mParams.size();
  16802. if ((!isDone) && (methodInstance->mParams[paramIdx + implicitParamCount].mDelegateParamIdx >= 0))
  16803. {
  16804. paramIdx++;
  16805. continue;
  16806. }
  16807. if ((!isDefaultDone) && (defaultMethodInstance->mParams[defaultParamIdx + defaultImplicitParamCount].mDelegateParamIdx >= 0))
  16808. {
  16809. defaultParamIdx++;
  16810. continue;
  16811. }
  16812. if ((isDone) || (isDefaultDone))
  16813. {
  16814. // 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
  16815. // to cause us to throw an assertion in the declaration here
  16816. if (!defaultMethodInstance->mHadGenericDelegateParams)
  16817. BF_ASSERT((isDone) && (isDefaultDone));
  16818. break;
  16819. }
  16820. methodInstance->mParams[paramIdx + implicitParamCount].mWasGenericParam = defaultMethodInstance->mParams[defaultParamIdx + defaultImplicitParamCount].mResolvedType->IsGenericParam();
  16821. paramIdx++;
  16822. defaultParamIdx++;
  16823. }
  16824. }
  16825. StringT<128> mangledName;
  16826. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), mCurMethodInstance);
  16827. for (int paramIdx = 0; paramIdx < methodInstance->GetParamCount(); paramIdx++)
  16828. {
  16829. auto paramType = methodInstance->GetParamType(paramIdx);
  16830. if (paramType->IsComposite())
  16831. PopulateType(paramType, BfPopulateType_Data);
  16832. if (!methodInstance->IsParamSkipped(paramIdx))
  16833. {
  16834. if (paramType->IsStruct())
  16835. {
  16836. //
  16837. }
  16838. else
  16839. {
  16840. PopulateType(paramType, BfPopulateType_Declaration);
  16841. }
  16842. }
  16843. }
  16844. // Only process method in default unspecialized mode, not in variations
  16845. if (methodInstance->mIsUnspecializedVariation)
  16846. return;
  16847. PopulateType(resolvedReturnType, BfPopulateType_Data);
  16848. auto retLLVMType = mBfIRBuilder->MapType(resolvedReturnType);
  16849. if (resolvedReturnType->IsValuelessType())
  16850. retLLVMType = mBfIRBuilder->GetPrimitiveType(BfTypeCode_None);
  16851. if (!mBfIRBuilder->mIgnoreWrites)
  16852. {
  16853. bool isIntrinsic = false;
  16854. if (!methodInstance->mIRFunction)
  16855. SetupIRFunction(methodInstance, mangledName, isTemporaryFunc, &isIntrinsic);
  16856. if (isIntrinsic)
  16857. {
  16858. addToWorkList = false;
  16859. }
  16860. }
  16861. auto func = methodInstance->mIRFunction;
  16862. // if (methodInstance->mIsReified)
  16863. // CheckHotMethod(methodInstance, mangledName);
  16864. 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);
  16865. SizedArray<BfIRMDNode, 8> diParams;
  16866. diParams.push_back(mBfIRBuilder->DbgGetType(resolvedReturnType));
  16867. if ((!methodDef->mIsStatic) && (typeDef->mIsStatic) && (methodDef->mMethodDeclaration != NULL))
  16868. {
  16869. //CS0708
  16870. Fail("Cannot declare instance members in a static class", methodDef->GetRefNode());
  16871. }
  16872. if ((methodDef->mIsVirtual) && (methodDef->mGenericParams.size() != 0))
  16873. {
  16874. Fail("Virtual generic methods not supported", methodDeclaration->mVirtualSpecifier);
  16875. methodDef->mIsVirtual = false;
  16876. }
  16877. if ((methodDeclaration != NULL) && (methodDeclaration->mMutSpecifier != NULL) && (!mCurTypeInstance->IsBoxed()) && (!methodInstance->mIsForeignMethodDef))
  16878. {
  16879. if (methodDef->mIsStatic)
  16880. Warn(0, "Unnecessary 'mut' specifier, static methods have no implicit 'this' target to mutate", methodDeclaration->mMutSpecifier);
  16881. else if ((!mCurTypeInstance->IsValueType()) && (!mCurTypeInstance->IsInterface()))
  16882. Warn(0, "Unnecessary 'mut' specifier, methods of reference types are implicitly mutating", methodDeclaration->mMutSpecifier);
  16883. else if (methodDef->mMethodType == BfMethodType_Ctor)
  16884. Warn(0, "Unnecessary 'mut' specifier, constructors are implicitly mutating", methodDeclaration->mMutSpecifier);
  16885. else if (methodDef->mMethodType == BfMethodType_Dtor)
  16886. Warn(0, "Unnecessary 'mut' specifier, destructors are implicitly mutating", methodDeclaration->mMutSpecifier);
  16887. }
  16888. if (isTemporaryFunc)
  16889. {
  16890. // This handles temporary methods for autocomplete types
  16891. BF_ASSERT(mIsScratchModule);
  16892. BF_ASSERT(mCompiler->IsAutocomplete());
  16893. BfLogSysM("DoMethodDeclaration autocomplete bailout\n");
  16894. return; // Bail out early for autocomplete pass
  16895. }
  16896. //TODO: We used to have this (this != mContext->mExternalFuncModule) check, but it caused us to keep around
  16897. // an invalid mFuncRefernce (which came from GetMethodInstanceAtIdx) which later got remapped by the
  16898. // autocompleter. Why did we have this check anyway?
  16899. /*if ((typeInstance->mContext != mContext) && (!methodDef->IsEmptyPartial()))
  16900. {
  16901. AddMethodReference(methodInstance);
  16902. mFuncReferences[methodInstance] = func;
  16903. BfLogSysM("Adding func reference (DoMethodDeclaration). Module:%p MethodInst:%p LLVMFunc:%p\n", this, methodInstance, func);
  16904. }*/
  16905. if (mParentModule != NULL)
  16906. {
  16907. // For extension modules we need to keep track of our own methods so we can know which methods
  16908. // we have defined ourselves and which are from the parent module or other extensions
  16909. if (!func.IsFake())
  16910. mFuncReferences[methodInstance] = func;
  16911. }
  16912. if (addToWorkList)
  16913. {
  16914. bool wasAwaitingDecl = methodInstance->mMethodInstanceGroup->mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingDecl;
  16915. if (wasAwaitingDecl)
  16916. methodInstance->mMethodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_Decl_AwaitingReference;
  16917. if ((!methodDef->mIsAbstract) && (!methodInstance->mIgnoreBody))
  16918. {
  16919. if (!wasAwaitingDecl)
  16920. AddMethodToWorkList(methodInstance);
  16921. }
  16922. else
  16923. {
  16924. BfLogSysM("DoMethodDeclaration ignoring method body %d %d %d\n", hasExternSpecifier, methodDef->mIsAbstract, methodInstance->mIgnoreBody);
  16925. methodInstance->mIgnoreBody = true;
  16926. if (typeInstance->IsUnspecializedType())
  16927. {
  16928. // Don't hold on to actual Function for unspecialized types
  16929. methodInstance->mIRFunction = BfIRFunction();
  16930. }
  16931. }
  16932. }
  16933. if ((!methodInstance->IsSpecializedGenericMethodOrType()) && (!mCurTypeInstance->IsBoxed()) &&
  16934. (!methodDef->mIsLocalMethod) &&
  16935. (!CheckDefineMemberProtection(methodDef->mProtection, methodInstance->mReturnType)))
  16936. {
  16937. if (methodDef->mMethodType == BfMethodType_PropertyGetter)
  16938. {
  16939. //TODO:
  16940. //CS0053
  16941. Fail(StrFormat("Inconsistent accessibility: property type '%s' is less accessible than property '%s'",
  16942. TypeToString(methodInstance->mReturnType).c_str(), MethodToString(methodInstance).c_str()),
  16943. methodDef->mReturnTypeRef, true);
  16944. }
  16945. else
  16946. {
  16947. //CS0050
  16948. Fail(StrFormat("Inconsistent accessibility: return type '%s' is less accessible than method '%s'",
  16949. TypeToString(methodInstance->mReturnType).c_str(), MethodToString(methodInstance).c_str()),
  16950. methodDef->mReturnTypeRef, true);
  16951. }
  16952. }
  16953. if ((typeInstance->IsInterface()) && (methodDef->mMethodType == BfMethodType_Ctor))
  16954. {
  16955. Fail("Interfaces cannot contain constructors", methodDeclaration);
  16956. }
  16957. // Don't compare specialized generic methods against normal methods
  16958. if ((((mCurMethodInstance->mIsUnspecialized) || (mCurMethodInstance->mMethodDef->mGenericParams.size() == 0))) &&
  16959. (!methodDef->mIsLocalMethod))
  16960. {
  16961. if (!methodInstance->mIsForeignMethodDef)
  16962. {
  16963. typeDef->PopulateMemberSets();
  16964. BfMethodDef* nextMethod = NULL;
  16965. BfMemberSetEntry* entry = NULL;
  16966. if (typeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  16967. nextMethod = (BfMethodDef*)entry->mMemberDef;
  16968. while (nextMethod != NULL)
  16969. {
  16970. auto checkMethod = nextMethod;
  16971. nextMethod = nextMethod->mNextWithSameName;
  16972. if ((checkMethod != methodDef) && (typeInstance->mMethodInstanceGroups[checkMethod->mIdx].mDefault != NULL))
  16973. {
  16974. auto checkMethodInstance = typeInstance->mMethodInstanceGroups[checkMethod->mIdx].mDefault;
  16975. if (((checkMethodInstance->mChainType == BfMethodChainType_None) || (checkMethodInstance->mChainType == BfMethodChainType_ChainHead)) &&
  16976. (checkMethodInstance->GetExplicitInterface() == methodInstance->GetExplicitInterface()) &&
  16977. (CompareMethodSignatures(checkMethodInstance, mCurMethodInstance)))
  16978. {
  16979. bool canChain = false;
  16980. if ((methodDef->mParams.empty()) &&
  16981. (checkMethodInstance->mMethodDef->mIsStatic == methodInstance->mMethodDef->mIsStatic))
  16982. {
  16983. if ((methodDef->mMethodType == BfMethodType_CtorNoBody) || (methodDef->mMethodType == BfMethodType_Dtor))
  16984. canChain = true;
  16985. else if (methodDef->mMethodType == BfMethodType_Normal)
  16986. {
  16987. if ((methodDef->mName == BF_METHODNAME_MARKMEMBERS) ||
  16988. (methodDef->mName == BF_METHODNAME_MARKMEMBERS_STATIC) ||
  16989. (methodDef->mName == BF_METHODNAME_FIND_TLS_MEMBERS))
  16990. canChain = true;
  16991. }
  16992. }
  16993. if (canChain)
  16994. {
  16995. bool isBetter;
  16996. bool isWorse;
  16997. CompareDeclTypes(checkMethodInstance->mMethodDef->mDeclaringType, methodInstance->mMethodDef->mDeclaringType, isBetter, isWorse);
  16998. if (isBetter && !isWorse)
  16999. {
  17000. methodInstance->mChainType = BfMethodChainType_ChainHead;
  17001. checkMethodInstance->mChainType = BfMethodChainType_ChainMember;
  17002. }
  17003. else
  17004. {
  17005. checkMethodInstance->mChainType = BfMethodChainType_ChainHead;
  17006. methodInstance->mChainType = BfMethodChainType_ChainMember;
  17007. }
  17008. }
  17009. else if ((checkMethod->mBody == NULL) && (methodDef->mBody != NULL) &&
  17010. (checkMethod->mDeclaringType != methodDef->mDeclaringType))
  17011. {
  17012. // We're allowed to override an empty-bodied method
  17013. checkMethodInstance->mChainType = BfMethodChainType_ChainSkip;
  17014. }
  17015. else
  17016. {
  17017. if (!typeInstance->IsTypeMemberAccessible(checkMethod->mDeclaringType, methodDef->mDeclaringType))
  17018. continue;
  17019. bool silentlyAllow = false;
  17020. if (checkMethod->mDeclaringType != methodDef->mDeclaringType)
  17021. {
  17022. if (typeInstance->IsInterface())
  17023. {
  17024. if (methodDef->mIsOverride)
  17025. silentlyAllow = true;
  17026. }
  17027. else
  17028. silentlyAllow = true;
  17029. }
  17030. if ((checkMethod->mCommutableKind == BfCommutableKind_Reverse) || (methodDef->mCommutableKind == BfCommutableKind_Reverse))
  17031. silentlyAllow = true;
  17032. if (!silentlyAllow)
  17033. {
  17034. if ((!methodDef->mName.IsEmpty()) || (checkMethodInstance->mMethodDef->mIsOperator))
  17035. {
  17036. auto refNode = methodDef->GetRefNode();
  17037. auto bfError = Fail("Method already declared with the same parameter types", refNode, true);
  17038. if (bfError != NULL)
  17039. mCompiler->mPassInstance->MoreInfo("First declaration", checkMethod->GetRefNode());
  17040. }
  17041. }
  17042. }
  17043. }
  17044. }
  17045. }
  17046. }
  17047. // Virtual methods give their error while slotting
  17048. if ((!typeInstance->IsBoxed()) && (!methodDef->mIsVirtual) && (methodDef->mProtection != BfProtection_Private) &&
  17049. (!methodDef->mIsLocalMethod) &&
  17050. (!methodInstance->mIsForeignMethodDef) && (typeInstance->mBaseType != NULL) &&
  17051. (methodDef->mMethodType == BfMethodType_Normal) && (methodDef->mMethodDeclaration != NULL))
  17052. {
  17053. bool foundHiddenMethod = false;
  17054. auto baseType = typeInstance->mBaseType;
  17055. while (baseType != NULL)
  17056. {
  17057. //for (int checkMethodIdx = 0; checkMethodIdx < (int) baseType->mTypeDef->mMethods.size(); checkMethodIdx++)
  17058. auto baseTypeDef = baseType->mTypeDef;
  17059. baseTypeDef->PopulateMemberSets();
  17060. BfMethodDef* checkMethod = NULL;
  17061. BfMemberSetEntry* entry = NULL;
  17062. if (baseTypeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  17063. checkMethod = (BfMethodDef*)entry->mMemberDef;
  17064. while (checkMethod != NULL)
  17065. {
  17066. if (checkMethod->mMethodDeclaration == NULL)
  17067. continue;
  17068. if (baseType->mMethodInstanceGroups.size() == 0)
  17069. {
  17070. BF_ASSERT(baseType->IsIncomplete() && mCompiler->IsAutocomplete());
  17071. break;
  17072. }
  17073. if (checkMethod == methodDef)
  17074. continue;
  17075. if (checkMethod->mName != methodDef->mName)
  17076. continue;
  17077. auto checkMethodInstance = GetRawMethodInstanceAtIdx(baseType, checkMethod->mIdx);
  17078. if (checkMethodInstance != NULL)
  17079. {
  17080. if ((checkMethodInstance->GetExplicitInterface() == methodInstance->GetExplicitInterface()) &&
  17081. (checkMethod->mProtection != BfProtection_Private) &&
  17082. (CompareMethodSignatures(checkMethodInstance, mCurMethodInstance)))
  17083. {
  17084. if (!methodDef->mIsNew)
  17085. {
  17086. BfAstNode* refNode = methodInstance->mMethodDef->GetRefNode();
  17087. if (refNode != NULL)
  17088. {
  17089. 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?
  17090. if (bfError != NULL)
  17091. bfError->mIsPersistent = true;
  17092. }
  17093. }
  17094. foundHiddenMethod = true;
  17095. break;
  17096. }
  17097. }
  17098. checkMethod = checkMethod->mNextWithSameName;
  17099. }
  17100. if (foundHiddenMethod)
  17101. break;
  17102. baseType = baseType->mBaseType;
  17103. }
  17104. if ((methodDef->mIsNew) && (!foundHiddenMethod))
  17105. {
  17106. auto propertyDeclaration = methodDef->GetPropertyDeclaration();
  17107. auto tokenNode = (propertyDeclaration != NULL) ? propertyDeclaration->mNewSpecifier :
  17108. methodDeclaration->mNewSpecifier;
  17109. Fail("Method does not hide an inherited member. The 'new' keyword is not required", tokenNode, true);
  17110. }
  17111. }
  17112. }
  17113. mCompiler->mStats.mMethodDeclarations++;
  17114. mCompiler->UpdateCompletion();
  17115. }
  17116. void BfModule::UniqueSlotVirtualMethod(BfMethodInstance* methodInstance)
  17117. {
  17118. BF_ASSERT(methodInstance->GetOwner() == mCurTypeInstance);
  17119. auto typeInstance = mCurTypeInstance;
  17120. auto methodDef = methodInstance->mMethodDef;
  17121. int virtualMethodMatchIdx = -1;
  17122. if (typeInstance->mHotTypeData != NULL)
  17123. {
  17124. if (typeInstance->mHotTypeData->mVTableOrigLength != -1)
  17125. {
  17126. BF_ASSERT(mCompiler->IsHotCompile());
  17127. // In the 'normal' case we'd assert that mIsOverride is false, but if we can't find the declaring method then we
  17128. // may slot this override anyway (?)
  17129. int vTableStart = 0;
  17130. if (typeInstance->mBaseType != NULL)
  17131. vTableStart = typeInstance->mBaseType->mVirtualMethodTableSize;
  17132. StringT<128> mangledName;
  17133. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), methodInstance);
  17134. for (int checkIdxOfs = 0; checkIdxOfs < (int)typeInstance->mHotTypeData->mVTableEntries.size(); checkIdxOfs++)
  17135. {
  17136. // O(1) checking when virtual methods haven't changed
  17137. int checkIdx = (typeInstance->mVirtualMethodTableSize - vTableStart + checkIdxOfs) % (int)typeInstance->mHotTypeData->mVTableEntries.size();
  17138. auto& entry = typeInstance->mHotTypeData->mVTableEntries[checkIdx];
  17139. if (mangledName == entry.mFuncName)
  17140. {
  17141. virtualMethodMatchIdx = vTableStart + checkIdx;
  17142. break;
  17143. }
  17144. }
  17145. if (virtualMethodMatchIdx != -1)
  17146. {
  17147. methodInstance->mVirtualTableIdx = virtualMethodMatchIdx;
  17148. typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mDeclaringMethod = methodInstance;
  17149. typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mImplementingMethod = methodInstance;
  17150. }
  17151. typeInstance->mVirtualMethodTableSize = (int)typeInstance->mVirtualMethodTable.size();
  17152. }
  17153. }
  17154. if (virtualMethodMatchIdx == -1)
  17155. {
  17156. methodInstance->mVirtualTableIdx = typeInstance->mVirtualMethodTableSize++;
  17157. BfVirtualMethodEntry entry = { methodInstance, methodInstance };
  17158. typeInstance->mVirtualMethodTable.push_back(entry);
  17159. }
  17160. }
  17161. void BfModule::CompareDeclTypes(BfTypeDef* newDeclType, BfTypeDef* prevDeclType, bool& isBetter, bool& isWorse)
  17162. {
  17163. if ((!prevDeclType->IsExtension()) && (newDeclType->IsExtension()))
  17164. {
  17165. // When we provide an extension override in the same project a root type override
  17166. isBetter = true;
  17167. isWorse = false;
  17168. }
  17169. else
  17170. {
  17171. isBetter = newDeclType->mProject->ContainsReference(prevDeclType->mProject);
  17172. isWorse = prevDeclType->mProject->ContainsReference(newDeclType->mProject);
  17173. }
  17174. }
  17175. bool BfModule::SlotVirtualMethod(BfMethodInstance* methodInstance, BfAmbiguityContext* ambiguityContext)
  17176. {
  17177. BP_ZONE("BfModule::SlotVirtualMethod");
  17178. if (mCurTypeInstance->IsUnspecializedTypeVariation())
  17179. return false;
  17180. auto _AddVirtualDecl = [&](BfMethodInstance* declMethodInstance)
  17181. {
  17182. if (!mCompiler->mOptions.mAllowHotSwapping)
  17183. return;
  17184. if ((!methodInstance->mIsReified) || (!declMethodInstance->mIsReified))
  17185. return;
  17186. if (methodInstance->mHotMethod == NULL)
  17187. CheckHotMethod(methodInstance, "");
  17188. if (methodInstance->mHotMethod == NULL)
  17189. return;
  17190. //BF_ASSERT(declMethodInstance->mHotMethod != NULL);
  17191. if (declMethodInstance->mHotMethod == NULL)
  17192. CheckHotMethod(declMethodInstance, "");
  17193. auto virtualDecl = mCompiler->mHotData->GetVirtualDeclaration(declMethodInstance->mHotMethod);
  17194. virtualDecl->mRefCount++;
  17195. methodInstance->mHotMethod->mReferences.Add(virtualDecl);
  17196. };
  17197. auto typeInstance = mCurTypeInstance;
  17198. auto typeDef = typeInstance->mTypeDef;
  17199. auto methodDef = methodInstance->mMethodDef;
  17200. auto methodDeclaration = methodDef->GetMethodDeclaration();
  17201. auto propertyDeclaration = methodDef->GetPropertyDeclaration();
  17202. auto propertyMethodDeclaration = methodDef->GetPropertyMethodDeclaration();
  17203. BfAstNode* declaringNode = methodDeclaration;
  17204. if (propertyMethodDeclaration != NULL)
  17205. declaringNode = propertyMethodDeclaration->mNameNode;
  17206. BfMethodInstance* methodOverriden = NULL;
  17207. bool usedMethod = false;
  17208. BfTokenNode* virtualToken = NULL;
  17209. if (propertyDeclaration != NULL)
  17210. virtualToken = propertyDeclaration->mVirtualSpecifier;
  17211. else if (methodDeclaration != NULL)
  17212. virtualToken = methodDeclaration->mVirtualSpecifier;
  17213. if ((methodDef->mIsVirtual) && (methodDef->mIsStatic))
  17214. {
  17215. Fail("Static members cannot be marked as override, virtual, or abstract", virtualToken, true);
  17216. }
  17217. else if (methodDef->mIsVirtual)
  17218. {
  17219. if (mCompiler->IsHotCompile())
  17220. mContext->EnsureHotMangledVirtualMethodName(methodInstance);
  17221. if ((methodDef->mProtection == BfProtection_Private) && (virtualToken != NULL))
  17222. Fail("Virtual or abstract members cannot be private", virtualToken, true);
  17223. BfTypeInstance* checkBase = typeInstance;
  17224. // If we are in an extension, look in ourselves first
  17225. if (methodDef->mDeclaringType->mTypeDeclaration == typeInstance->mTypeDef->mTypeDeclaration)
  17226. checkBase = checkBase->mBaseType;
  17227. if (typeInstance->IsValueType())
  17228. {
  17229. if (typeInstance->mBaseType == NULL)
  17230. return false; // It's actually ValueType
  17231. // We allow structs to override object methods for when they get boxed, so just ignore 'override' keyword until it gets boxed
  17232. if (!methodDef->mIsOverride)
  17233. {
  17234. Fail("Structs cannot have virtual methods", virtualToken, true);
  17235. return false;
  17236. }
  17237. checkBase = mContext->mBfObjectType;
  17238. if (checkBase->mVirtualMethodTableSize == 0)
  17239. PopulateType(checkBase, BfPopulateType_Full);
  17240. if (checkBase->mDefineState < BfTypeDefineState_DefinedAndMethodsSlotted)
  17241. return false; // System circular ref, don't do struct checking on those
  17242. }
  17243. int virtualMethodMatchIdx = -1;
  17244. bool hadHidingError = false;
  17245. BfMethodInstance* bestOverrideMethodInstance = NULL;
  17246. BfMethodInstance* ambiguousOverrideMethodInstance = NULL;
  17247. int bestOverrideMethodIdx = -1;
  17248. int ambiguousOverrideMethodIdx = -1;
  17249. if (checkBase != NULL)
  17250. {
  17251. auto& baseVirtualMethodTable = checkBase->mVirtualMethodTable;
  17252. auto lookupType = checkBase;
  17253. while (lookupType != NULL)
  17254. {
  17255. lookupType->mTypeDef->PopulateMemberSets();
  17256. BfMethodDef* nextMethodDef = NULL;
  17257. BfMemberSetEntry* entry;
  17258. if (lookupType->mTypeDef->mMethodSet.TryGetWith(methodInstance->mMethodDef->mName, &entry))
  17259. nextMethodDef = (BfMethodDef*)entry->mMemberDef;
  17260. while (nextMethodDef != NULL)
  17261. {
  17262. auto checkMethodDef = nextMethodDef;
  17263. nextMethodDef = nextMethodDef->mNextWithSameName;
  17264. if ((!checkMethodDef->mIsVirtual) || (checkMethodDef->mIsOverride))
  17265. continue;
  17266. BfMethodInstance* lookupMethodInstance = lookupType->mMethodInstanceGroups[checkMethodDef->mIdx].mDefault;
  17267. if ((lookupMethodInstance == NULL) || (lookupMethodInstance->mVirtualTableIdx == -1))
  17268. continue;
  17269. int checkMethodIdx = lookupMethodInstance->mVirtualTableIdx;
  17270. auto& baseMethodRef = baseVirtualMethodTable[checkMethodIdx];
  17271. if (baseMethodRef.mDeclaringMethod.mMethodNum == -1)
  17272. {
  17273. BF_ASSERT(mCompiler->mOptions.mHasVDataExtender);
  17274. continue;
  17275. }
  17276. BfMethodInstance* baseMethodInstance = baseVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  17277. if (baseMethodInstance == NULL)
  17278. {
  17279. AssertErrorState();
  17280. continue;
  17281. }
  17282. if ((baseMethodInstance != NULL) && (CompareMethodSignatures(baseMethodInstance, methodInstance)))
  17283. {
  17284. if (methodDef->mIsOverride)
  17285. {
  17286. BfMethodInstance* checkMethodInstance;
  17287. if (typeInstance->IsValueType())
  17288. checkMethodInstance = checkBase->mVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  17289. else
  17290. checkMethodInstance = typeInstance->mVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  17291. auto newDeclType = checkMethodInstance->mMethodDef->mDeclaringType;
  17292. if (!typeInstance->IsTypeMemberAccessible(newDeclType, methodDef->mDeclaringType->mProject))
  17293. continue;
  17294. if (bestOverrideMethodInstance != NULL)
  17295. {
  17296. auto prevDeclType = bestOverrideMethodInstance->mMethodDef->mDeclaringType;
  17297. bool isBetter = newDeclType->mProject->ContainsReference(prevDeclType->mProject);
  17298. bool isWorse = prevDeclType->mProject->ContainsReference(newDeclType->mProject);
  17299. if (isBetter == isWorse)
  17300. {
  17301. ambiguousOverrideMethodInstance = bestOverrideMethodInstance;
  17302. }
  17303. else
  17304. {
  17305. if (isWorse)
  17306. continue;
  17307. ambiguousOverrideMethodInstance = NULL;
  17308. }
  17309. }
  17310. bestOverrideMethodInstance = checkMethodInstance;
  17311. bestOverrideMethodIdx = checkMethodIdx;
  17312. }
  17313. else
  17314. {
  17315. if ((baseMethodInstance->GetOwner() != methodInstance->GetOwner()) && (!methodDef->mIsNew))
  17316. {
  17317. if (!hadHidingError)
  17318. Warn(BfWarning_CS0114_MethodHidesInherited, StrFormat("Method hides inherited member from '%s'. Use either 'override' or 'new'.", TypeToString(checkBase).c_str()), declaringNode);
  17319. hadHidingError = true;
  17320. }
  17321. }
  17322. }
  17323. }
  17324. lookupType = lookupType->mBaseType;
  17325. }
  17326. }
  17327. //TODO:
  17328. if ((checkBase != NULL)
  17329. && (false)
  17330. )
  17331. {
  17332. auto& baseVirtualMethodTable = checkBase->mVirtualMethodTable;
  17333. for (int checkMethodIdx = (int) baseVirtualMethodTable.size() - 1; checkMethodIdx >= 0; checkMethodIdx--)
  17334. {
  17335. auto& baseMethodRef = baseVirtualMethodTable[checkMethodIdx];
  17336. if (baseMethodRef.mDeclaringMethod.mMethodNum == -1)
  17337. {
  17338. BF_ASSERT(mCompiler->mOptions.mHasVDataExtender);
  17339. continue;
  17340. }
  17341. BfMethodInstance* baseMethodInstance = baseVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  17342. if (baseMethodInstance == NULL)
  17343. {
  17344. AssertErrorState();
  17345. continue;
  17346. }
  17347. if ((baseMethodInstance != NULL) && (CompareMethodSignatures(baseMethodInstance, methodInstance)))
  17348. {
  17349. if (methodDef->mIsOverride)
  17350. {
  17351. BfMethodInstance* checkMethodInstance;
  17352. if (typeInstance->IsValueType())
  17353. checkMethodInstance = checkBase->mVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  17354. else
  17355. checkMethodInstance = typeInstance->mVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  17356. auto newDeclType = checkMethodInstance->mMethodDef->mDeclaringType;
  17357. if (!typeInstance->IsTypeMemberAccessible(newDeclType, methodDef->mDeclaringType->mProject))
  17358. continue;
  17359. if (bestOverrideMethodInstance != NULL)
  17360. {
  17361. auto prevDeclType = bestOverrideMethodInstance->mMethodDef->mDeclaringType;
  17362. bool isBetter = newDeclType->mProject->ContainsReference(prevDeclType->mProject);
  17363. bool isWorse = prevDeclType->mProject->ContainsReference(newDeclType->mProject);
  17364. if (isBetter == isWorse)
  17365. {
  17366. ambiguousOverrideMethodInstance = bestOverrideMethodInstance;
  17367. }
  17368. else
  17369. {
  17370. if (isWorse)
  17371. continue;
  17372. ambiguousOverrideMethodInstance = NULL;
  17373. }
  17374. }
  17375. bestOverrideMethodInstance = checkMethodInstance;
  17376. bestOverrideMethodIdx = checkMethodIdx;
  17377. }
  17378. else
  17379. {
  17380. if ((baseMethodInstance->GetOwner() != methodInstance->GetOwner()) && (!methodDef->mIsNew))
  17381. {
  17382. if (!hadHidingError)
  17383. Warn(BfWarning_CS0114_MethodHidesInherited, StrFormat("Method hides inherited member from '%s'. Use either 'override' or 'new'.", TypeToString(checkBase).c_str()), declaringNode);
  17384. hadHidingError = true;
  17385. }
  17386. }
  17387. }
  17388. }
  17389. }
  17390. if (bestOverrideMethodInstance != NULL)
  17391. {
  17392. if (ambiguousOverrideMethodInstance != NULL)
  17393. {
  17394. bool allow = false;
  17395. // 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.
  17396. // When when specialize, the specialized type will determine wither it has illegally pulled in both declarations or not
  17397. bool canSeeEachOther = false;
  17398. //
  17399. {
  17400. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, ambiguousOverrideMethodInstance);
  17401. if (bestOverrideMethodInstance->GetOwner()->IsTypeMemberIncluded(bestOverrideMethodInstance->mMethodDef->mDeclaringType, ambiguousOverrideMethodInstance->mMethodDef->mDeclaringType, this))
  17402. canSeeEachOther = true;
  17403. }
  17404. //
  17405. {
  17406. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, bestOverrideMethodInstance);
  17407. if (ambiguousOverrideMethodInstance->GetOwner()->IsTypeMemberIncluded(ambiguousOverrideMethodInstance->mMethodDef->mDeclaringType, bestOverrideMethodInstance->mMethodDef->mDeclaringType, this))
  17408. canSeeEachOther = true;
  17409. }
  17410. if (!canSeeEachOther)
  17411. {
  17412. BF_ASSERT(bestOverrideMethodInstance->GetOwner()->IsUnspecializedType() && ambiguousOverrideMethodInstance->GetOwner()->IsUnspecializedType());
  17413. }
  17414. else
  17415. {
  17416. auto error = Fail(StrFormat("Method '%s' is an ambiguous override", MethodToString(methodInstance).c_str()), methodDef->GetRefNode());
  17417. if (error != NULL)
  17418. {
  17419. mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' is a candidate", MethodToString(bestOverrideMethodInstance).c_str()), bestOverrideMethodInstance->mMethodDef->GetRefNode());
  17420. mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' is a candidate", MethodToString(ambiguousOverrideMethodInstance).c_str()), ambiguousOverrideMethodInstance->mMethodDef->GetRefNode());
  17421. }
  17422. }
  17423. }
  17424. auto& baseVirtualMethodTable = checkBase->mVirtualMethodTable;
  17425. BfMethodInstance* baseVirtualMethodInstance = baseVirtualMethodTable[bestOverrideMethodIdx].mDeclaringMethod;
  17426. if ((baseVirtualMethodInstance != methodInstance) && (methodDef->mIsOverride))
  17427. {
  17428. if (baseVirtualMethodInstance->mReturnType != methodInstance->mReturnType)
  17429. {
  17430. BfTypeReference* returnTypeRef;
  17431. if (auto propertyDeclaration = methodDef->GetPropertyDeclaration())
  17432. {
  17433. returnTypeRef = propertyDeclaration->mTypeRef;
  17434. Fail("Property differs from overridden property by type", returnTypeRef, true);
  17435. }
  17436. else if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  17437. {
  17438. returnTypeRef = methodDeclaration->mReturnType;
  17439. Fail("Method differs from overridden method by return value", returnTypeRef, true);
  17440. }
  17441. else
  17442. {
  17443. Fail(StrFormat("Internal error with method '%s'", MethodToString(methodInstance).c_str()));
  17444. }
  17445. return usedMethod;
  17446. }
  17447. }
  17448. if (methodDef->mIsOverride)
  17449. {
  17450. // We can have multiple matches when a virtual method is used to implement interface methods
  17451. // It doesn't matter what we set mVirtualTableIdx, as all base classes will override all matching
  17452. // vtable entries for this method signature
  17453. virtualMethodMatchIdx = bestOverrideMethodIdx;
  17454. if (!typeInstance->IsValueType())
  17455. methodInstance->mVirtualTableIdx = virtualMethodMatchIdx;
  17456. if (typeInstance->IsValueType())
  17457. {
  17458. methodOverriden = checkBase->mVirtualMethodTable[virtualMethodMatchIdx].mImplementingMethod;
  17459. }
  17460. else
  17461. {
  17462. methodInstance->mVirtualTableIdx = virtualMethodMatchIdx;
  17463. auto& overridenRef = typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mImplementingMethod;
  17464. if (overridenRef.mKind != BfMethodRefKind_AmbiguousRef)
  17465. {
  17466. methodOverriden = overridenRef;
  17467. BfMethodInstance* setMethodInstance = methodInstance;
  17468. bool doOverride = true;
  17469. if (methodOverriden->GetOwner() == methodInstance->GetOwner())
  17470. {
  17471. bool isBetter = false;
  17472. bool isWorse = false;
  17473. CompareDeclTypes(methodInstance->mMethodDef->mDeclaringType, methodOverriden->mMethodDef->mDeclaringType, isBetter, isWorse);
  17474. if (isBetter == isWorse)
  17475. {
  17476. // We have to resolve later per-project
  17477. if ((ambiguityContext != NULL) && (ambiguityContext->mIsProjectSpecific))
  17478. {
  17479. auto declMethodInstance = checkBase->mVirtualMethodTable[virtualMethodMatchIdx].mDeclaringMethod;
  17480. ambiguityContext->Add(virtualMethodMatchIdx, NULL, -1, methodOverriden, methodInstance);
  17481. }
  17482. if ((ambiguityContext == NULL) || (!ambiguityContext->mIsProjectSpecific))
  17483. typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mImplementingMethod.mKind = BfMethodRefKind_AmbiguousRef;
  17484. doOverride = false;
  17485. }
  17486. else
  17487. {
  17488. if ((isBetter) && (ambiguityContext != NULL))
  17489. {
  17490. ambiguityContext->Remove(virtualMethodMatchIdx);
  17491. }
  17492. doOverride = isBetter;
  17493. }
  17494. }
  17495. if (doOverride)
  17496. {
  17497. auto declMethodInstance = (BfMethodInstance*)typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mDeclaringMethod;
  17498. _AddVirtualDecl(declMethodInstance);
  17499. typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mImplementingMethod = setMethodInstance;
  17500. }
  17501. }
  17502. }
  17503. if (methodOverriden != NULL)
  17504. {
  17505. auto prevProtection = methodOverriden->mMethodDef->mProtection;
  17506. if ((methodDef->mProtection != prevProtection) && (methodDef->mMethodType != BfMethodType_Dtor))
  17507. {
  17508. const char* protectionNames[] = {"hidden", "private", "protected", "public"};
  17509. BfAstNode* protectionRefNode = NULL;
  17510. if (auto propertyMethodDeclaration = methodDef->GetPropertyMethodDeclaration())
  17511. {
  17512. protectionRefNode = propertyMethodDeclaration->mProtectionSpecifier;
  17513. if (protectionRefNode == NULL)
  17514. protectionRefNode = propertyMethodDeclaration->mPropertyDeclaration->mProtectionSpecifier;
  17515. if (protectionRefNode == NULL)
  17516. protectionRefNode = propertyMethodDeclaration->mPropertyDeclaration->mNameNode;
  17517. }
  17518. else if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  17519. {
  17520. protectionRefNode = methodDeclaration->mProtectionSpecifier;
  17521. if (protectionRefNode == NULL)
  17522. protectionRefNode = methodDeclaration->mNameNode;
  17523. }
  17524. if (protectionRefNode != NULL)
  17525. Fail(StrFormat("Cannot change access modifiers when overriding '%s' inherited member", protectionNames[(int)prevProtection]), protectionRefNode, true);
  17526. }
  17527. }
  17528. }
  17529. }
  17530. if ((virtualMethodMatchIdx == -1) && ((ambiguityContext == NULL) || (!ambiguityContext->mIsReslotting)))
  17531. {
  17532. if (methodDef->mIsOverride)
  17533. {
  17534. BfTokenNode* overrideToken = NULL;
  17535. if (auto propertyMethodDeclaration = methodDef->GetPropertyMethodDeclaration())
  17536. overrideToken = propertyMethodDeclaration->mPropertyDeclaration->mVirtualSpecifier;
  17537. else if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  17538. overrideToken = methodDeclaration->mVirtualSpecifier;
  17539. if (overrideToken != NULL)
  17540. {
  17541. if ((propertyDeclaration != NULL) && (propertyDeclaration->mNameNode != NULL) &&
  17542. ((methodDef->mMethodType == BfMethodType_PropertyGetter) || (methodDef->mMethodType == BfMethodType_PropertySetter)))
  17543. Fail(StrFormat("No suitable method found to override for '%s.%s'",
  17544. propertyDeclaration->mNameNode->ToString().c_str(), (methodDef->mMethodType == BfMethodType_PropertyGetter) ? "get" : "set"), overrideToken, true);
  17545. else
  17546. Fail("No suitable method found to override", overrideToken, true);
  17547. }
  17548. return usedMethod;
  17549. }
  17550. UniqueSlotVirtualMethod(methodInstance);
  17551. }
  17552. else
  17553. usedMethod = true;
  17554. if (typeInstance->IsValueType())
  17555. return usedMethod;
  17556. }
  17557. bool foundInterface = false;
  17558. bool hadAnyMatch = false;
  17559. // See if this method matches interfaces
  17560. for (auto& ifaceTypeInst : typeInstance->mInterfaces)
  17561. {
  17562. auto ifaceInst = ifaceTypeInst.mInterfaceType;
  17563. if (ifaceInst->IsIncomplete())
  17564. PopulateType(ifaceInst, BfPopulateType_DataAndMethods);
  17565. int startIdx = ifaceTypeInst.mStartInterfaceTableIdx;
  17566. int iMethodCount = (int)ifaceInst->mMethodInstanceGroups.size();
  17567. // See "bidirectional" rules mentioned in DoTypeInstanceMethodProcessing
  17568. if ((!typeInstance->IsTypeMemberAccessible(methodDef->mDeclaringType, ifaceTypeInst.mDeclaringType)) &&
  17569. (!typeInstance->IsTypeMemberAccessible(ifaceTypeInst.mDeclaringType, methodDef->mDeclaringType)))
  17570. continue;
  17571. if (!typeInstance->IsTypeMemberIncluded(methodDef->mDeclaringType, ifaceTypeInst.mDeclaringType, this))
  17572. continue;
  17573. bool hadMatch = false;
  17574. bool hadNameMatch = false;
  17575. BfType* expectedReturnType = NULL;
  17576. bool showedError = false;
  17577. // We go through our VTable looking for NULL entries within the interface sections
  17578. // The only instance of finding a "better" method is when we have explicitly interface-dotted method
  17579. // because a normal method declared in this type could have matched earlier
  17580. //for (int iMethodIdx = 0; iMethodIdx < iMethodCount; iMethodIdx++)
  17581. ifaceInst->mTypeDef->PopulateMemberSets();
  17582. BfMethodDef* checkMethodDef = NULL;
  17583. BfMemberSetEntry* entry;
  17584. if (ifaceInst->mTypeDef->mMethodSet.TryGetWith(methodInstance->mMethodDef->mName, &entry))
  17585. checkMethodDef = (BfMethodDef*)entry->mMemberDef;
  17586. while (checkMethodDef != NULL)
  17587. {
  17588. int iMethodIdx = checkMethodDef->mIdx;
  17589. int iTableIdx = iMethodIdx + startIdx;
  17590. BfTypeInterfaceMethodEntry* interfaceMethodEntry = &typeInstance->mInterfaceMethodTable[iTableIdx];
  17591. auto iMethodPtr = &interfaceMethodEntry->mMethodRef;
  17592. bool storeIFaceMethod = false;
  17593. if ((mCompiler->mPassInstance->HasFailed()) && (iMethodIdx >= (int)ifaceInst->mMethodInstanceGroups.size()))
  17594. continue;
  17595. auto& iMethodGroup = ifaceInst->mMethodInstanceGroups[iMethodIdx];
  17596. auto iMethodInst = iMethodGroup.mDefault;
  17597. if (iMethodInst == NULL)
  17598. {
  17599. if ((!ifaceInst->IsGenericTypeInstance()) || (!ifaceInst->mTypeDef->mIsCombinedPartial))
  17600. AssertErrorState();
  17601. continue;
  17602. }
  17603. if (iMethodInst->mMethodDef->mName == methodInstance->mMethodDef->mName)
  17604. hadNameMatch = true;
  17605. bool doesMethodSignatureMatch = CompareMethodSignatures(iMethodInst, methodInstance);
  17606. if ((!doesMethodSignatureMatch) && (iMethodInst->GetNumGenericParams() == 0) && (interfaceMethodEntry->mMethodRef.IsNull()))
  17607. {
  17608. doesMethodSignatureMatch = IsCompatibleInterfaceMethod(iMethodInst, methodInstance);
  17609. }
  17610. if ((doesMethodSignatureMatch) && (methodInstance->GetOwner()->IsValueType()))
  17611. {
  17612. if ((!iMethodInst->mMethodDef->mIsMutating) && (methodInstance->mMethodDef->mIsMutating))
  17613. {
  17614. if ((methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface == ifaceInst))
  17615. {
  17616. auto error = mCompiler->mPassInstance->Fail(StrFormat("Implementation method '%s' cannot specify 'mut' because the interface method does not allow it",
  17617. MethodToString(methodInstance).c_str()), methodInstance->mMethodDef->GetMutNode());
  17618. if (error != NULL)
  17619. mCompiler->mPassInstance->MoreInfo(StrFormat("Declare the interface method as 'mut' to allow matching 'mut' implementations"), iMethodInst->mMethodDef->mMethodDeclaration);
  17620. showedError = true;
  17621. }
  17622. }
  17623. }
  17624. if (doesMethodSignatureMatch)
  17625. {
  17626. usedMethod = true;
  17627. hadMatch = true;
  17628. hadAnyMatch = true;
  17629. storeIFaceMethod = true;
  17630. if ((iMethodPtr->mKind != BfMethodRefKind_AmbiguousRef) && (iMethodPtr->mTypeInstance != NULL))
  17631. {
  17632. auto prevMethod = (BfMethodInstance*)*iMethodPtr;
  17633. if ((mCompiler->mIsResolveOnly) && (prevMethod == methodInstance))
  17634. {
  17635. // When autocompletion regenerates a single method body but not the whole type then
  17636. // we will see ourselves in the vtable already
  17637. return usedMethod;
  17638. }
  17639. bool isBetter = false;
  17640. bool isWorse = false;
  17641. isBetter = (methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface != NULL);
  17642. isWorse = (prevMethod->mMethodInfoEx != NULL) && (prevMethod->mMethodInfoEx->mExplicitInterface != NULL);
  17643. if (isBetter == isWorse)
  17644. CompareDeclTypes(methodInstance->mMethodDef->mDeclaringType, prevMethod->mMethodDef->mDeclaringType, isBetter, isWorse);
  17645. if (isBetter == isWorse)
  17646. {
  17647. if (ambiguityContext != NULL)
  17648. {
  17649. ambiguityContext->Add(~iTableIdx, &ifaceTypeInst, iMethodIdx, prevMethod, methodInstance);
  17650. }
  17651. iMethodPtr->mKind = BfMethodRefKind_AmbiguousRef;
  17652. storeIFaceMethod = true;
  17653. }
  17654. else
  17655. {
  17656. if ((isBetter) && (ambiguityContext != NULL))
  17657. ambiguityContext->Remove(~iTableIdx);
  17658. storeIFaceMethod = isBetter;
  17659. }
  17660. }
  17661. }
  17662. if (storeIFaceMethod)
  17663. {
  17664. _AddVirtualDecl(iMethodInst);
  17665. *iMethodPtr = methodInstance;
  17666. }
  17667. checkMethodDef = checkMethodDef->mNextWithSameName;
  17668. }
  17669. if ((methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface == ifaceInst) && (!hadMatch) && (!showedError))
  17670. {
  17671. if (expectedReturnType != NULL)
  17672. Fail(StrFormat("Wrong return type, expected '%s'", TypeToString(expectedReturnType).c_str()), declaringNode, true);
  17673. else if (hadNameMatch)
  17674. Fail("Method parameters don't match interface method", declaringNode, true);
  17675. else
  17676. Fail("Method name not found in interface", methodDef->GetRefNode(), true);
  17677. }
  17678. }
  17679. // Any overriden virtual methods that were used in interfaces also need to be replaced
  17680. if (methodOverriden != NULL)
  17681. {
  17682. for (auto& methodEntry : typeInstance->mInterfaceMethodTable)
  17683. {
  17684. if (methodEntry.mMethodRef == methodOverriden)
  17685. methodEntry.mMethodRef = methodInstance;
  17686. }
  17687. }
  17688. return usedMethod;
  17689. }
  17690. bool BfModule::SlotInterfaceMethod(BfMethodInstance* methodInstance)
  17691. {
  17692. auto typeInstance = mCurTypeInstance;
  17693. auto methodDef = methodInstance->mMethodDef;
  17694. if (methodDef->mMethodType == BfMethodType_Ctor)
  17695. return true;
  17696. bool foundOverride = false;
  17697. if ((methodDef->mBody == NULL) && (methodDef->mProtection == BfProtection_Private))
  17698. {
  17699. Fail("Private interface methods must provide a body", methodDef->GetMethodDeclaration()->mProtectionSpecifier);
  17700. }
  17701. if ((methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface != NULL) && (!methodDef->mIsOverride))
  17702. {
  17703. Fail("Explicit interfaces can only be specified for overrides in interface declarations", methodDef->GetMethodDeclaration()->mExplicitInterface);
  17704. }
  17705. BfAstNode* declaringNode = methodDef->GetRefNode();
  17706. for (auto& ifaceTypeInst : typeInstance->mInterfaces)
  17707. {
  17708. auto ifaceInst = ifaceTypeInst.mInterfaceType;
  17709. int startIdx = ifaceTypeInst.mStartInterfaceTableIdx;
  17710. int iMethodCount = (int)ifaceInst->mMethodInstanceGroups.size();
  17711. if ((methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface != ifaceInst))
  17712. continue;
  17713. ifaceInst->mTypeDef->PopulateMemberSets();
  17714. BfMethodDef* nextMethod = NULL;
  17715. BfMemberSetEntry* entry = NULL;
  17716. if (ifaceInst->mTypeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  17717. nextMethod = (BfMethodDef*)entry->mMemberDef;
  17718. while (nextMethod != NULL)
  17719. {
  17720. auto checkMethod = nextMethod;
  17721. nextMethod = nextMethod->mNextWithSameName;
  17722. auto ifaceMethod = ifaceInst->mMethodInstanceGroups[checkMethod->mIdx].mDefault;
  17723. if (ifaceMethod == NULL)
  17724. continue;
  17725. if (CompareMethodSignatures(ifaceMethod, methodInstance))
  17726. {
  17727. if (methodDef->mIsOverride)
  17728. {
  17729. if (ifaceMethod->mMethodDef->mProtection == BfProtection_Private)
  17730. {
  17731. auto error = Fail(StrFormat("Interface method '%s' cannot override private interface method '%s'", MethodToString(methodInstance).c_str(), MethodToString(ifaceMethod).c_str()), declaringNode);
  17732. if (error != NULL)
  17733. {
  17734. mCompiler->mPassInstance->MoreInfo("See base interface method", ifaceMethod->mMethodDef->GetRefNode());
  17735. }
  17736. }
  17737. foundOverride = true;
  17738. }
  17739. else if (!methodDef->mIsNew)
  17740. {
  17741. Warn(BfWarning_CS0114_MethodHidesInherited, StrFormat("Method hides inherited member from '%s'. Use the 'new' keyword if hiding was intentional.", TypeToString(ifaceInst).c_str()), declaringNode);
  17742. }
  17743. }
  17744. }
  17745. }
  17746. if ((methodDef->mIsOverride) && (!foundOverride))
  17747. {
  17748. // This allows us to declare a method in the base definition or in an extension and then provide
  17749. // an implementation in a more-specific extension
  17750. typeInstance->mTypeDef->PopulateMemberSets();
  17751. BfMethodDef* nextMethod = NULL;
  17752. BfMemberSetEntry* entry = NULL;
  17753. if (typeInstance->mTypeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  17754. nextMethod = (BfMethodDef*)entry->mMemberDef;
  17755. while (nextMethod != NULL)
  17756. {
  17757. auto checkMethod = nextMethod;
  17758. nextMethod = nextMethod->mNextWithSameName;
  17759. auto ifaceMethod = typeInstance->mMethodInstanceGroups[checkMethod->mIdx].mDefault;
  17760. if (ifaceMethod == NULL)
  17761. continue;
  17762. if (ifaceMethod->mMethodDef->mDeclaringType == methodInstance->mMethodDef->mDeclaringType)
  17763. continue;
  17764. if (CompareMethodSignatures(ifaceMethod, methodInstance))
  17765. {
  17766. foundOverride = true;
  17767. }
  17768. }
  17769. // for (int methodIdx = 0; methodIdx < typeInstance->mMethodInstanceGroups.size(); methodIdx++)
  17770. // {
  17771. // auto ifaceMethod = typeInstance->mMethodInstanceGroups[methodIdx].mDefault;
  17772. // if (ifaceMethod == NULL)
  17773. // continue;
  17774. // if (ifaceMethod->mMethodDef->mDeclaringType == methodInstance->mMethodDef->mDeclaringType)
  17775. // continue;
  17776. //
  17777. // if (CompareMethodSignatures(ifaceMethod, methodInstance))
  17778. // {
  17779. // foundOverride = true;
  17780. // }
  17781. // }
  17782. }
  17783. if (methodDef->mIsOverride)
  17784. {
  17785. if (!foundOverride)
  17786. {
  17787. BfTokenNode* overrideToken = NULL;
  17788. if (auto propertyDeclaration = methodDef->GetPropertyDeclaration())
  17789. overrideToken = propertyDeclaration->mVirtualSpecifier;
  17790. else if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  17791. overrideToken = methodDeclaration->mVirtualSpecifier;
  17792. if (overrideToken != NULL)
  17793. {
  17794. Fail("No suitable method found to override", overrideToken, true);
  17795. }
  17796. else
  17797. {
  17798. // Possible cause - DTOR with params
  17799. AssertErrorState();
  17800. }
  17801. }
  17802. return true;
  17803. }
  17804. // Generic methods can't be called virtually
  17805. if (methodInstance->GetNumGenericParams() != 0)
  17806. return true;
  17807. // Only public methods can be called virtually
  17808. if (methodDef->mProtection != BfProtection_Public)
  17809. return true;
  17810. UniqueSlotVirtualMethod(methodInstance);
  17811. return true;
  17812. }
  17813. void BfModule::DbgFinish()
  17814. {
  17815. if ((mBfIRBuilder == NULL) || (mExtensionCount != 0))
  17816. return;
  17817. if (mAwaitingInitFinish)
  17818. FinishInit();
  17819. if (mHasForceLinkMarker)
  17820. return;
  17821. String markerName;
  17822. BfIRValue linkMarker;
  17823. if (mBfIRBuilder->DbgHasInfo())
  17824. {
  17825. bool needForceLinking = false;
  17826. for (auto& ownedType : mOwnedTypeInstances)
  17827. {
  17828. bool hasConfirmedReference = false;
  17829. for (auto& methodInstGroup : ownedType->mMethodInstanceGroups)
  17830. {
  17831. if ((methodInstGroup.IsImplemented()) && (methodInstGroup.mDefault != NULL) &&
  17832. (!methodInstGroup.mDefault->mMethodDef->mIsStatic) && (methodInstGroup.mDefault->mIsReified) &&
  17833. ((methodInstGroup.mOnDemandKind == BfMethodOnDemandKind_AlwaysInclude) || (methodInstGroup.mOnDemandKind == BfMethodOnDemandKind_Referenced)))
  17834. {
  17835. hasConfirmedReference = true;
  17836. }
  17837. }
  17838. if ((!hasConfirmedReference) || (ownedType->IsBoxed()))
  17839. needForceLinking = true;
  17840. }
  17841. if ((needForceLinking) && (mProject->mCodeGenOptions.mAsmKind == BfAsmKind_None))
  17842. {
  17843. BfMethodState methodState;
  17844. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  17845. methodState.mTempKind = BfMethodState::TempKind_Static;
  17846. mHasForceLinkMarker = true;
  17847. auto voidType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_None));
  17848. SizedArray<BfIRType, 0> paramTypes;
  17849. BfIRFunctionType funcType = mBfIRBuilder->CreateFunctionType(voidType, paramTypes);
  17850. String linkName = "FORCELINKMOD_" + mModuleName;
  17851. BfIRFunction func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, linkName);
  17852. mBfIRBuilder->SetActiveFunction(func);
  17853. auto entryBlock = mBfIRBuilder->CreateBlock("main", true);
  17854. mBfIRBuilder->SetInsertPoint(entryBlock);
  17855. auto firstType = mOwnedTypeInstances[0];
  17856. UpdateSrcPos(mContext->mBfObjectType->mTypeDef->GetRefNode());
  17857. SizedArray<BfIRMDNode, 1> diParamTypes;
  17858. diParamTypes.Add(mBfIRBuilder->DbgGetType(GetPrimitiveType(BfTypeCode_None)));
  17859. BfIRMDNode diFuncType = mBfIRBuilder->DbgCreateSubroutineType(diParamTypes);
  17860. auto diScope = mBfIRBuilder->DbgCreateFunction(mDICompileUnit, "FORCELINKMOD", linkName, mCurFilePosition.mFileInstance->mDIFile,
  17861. mCurFilePosition.mCurLine + 1, diFuncType, false, true, mCurFilePosition.mCurLine + 1, 0, false, func);
  17862. methodState.mCurScope->mDIScope = diScope;
  17863. UpdateSrcPos(mContext->mBfObjectType->mTypeDef->GetRefNode(), BfSrcPosFlag_Force);
  17864. SizedArray<BfIRValue, 8> args;
  17865. BfExprEvaluator exprEvaluator(this);
  17866. for (auto& ownedType : mOwnedTypeInstances)
  17867. {
  17868. auto alloca = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_Int8)));
  17869. auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(diScope, "variable", mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, mBfIRBuilder->DbgGetType(ownedType));
  17870. mBfIRBuilder->DbgInsertDeclare(alloca, diVariable);
  17871. }
  17872. mBfIRBuilder->CreateRetVoid();
  17873. mBfIRBuilder->SetActiveFunction(BfIRFunction());
  17874. }
  17875. }
  17876. }
  17877. bool BfModule::Finish()
  17878. {
  17879. BP_ZONE("BfModule::Finish");
  17880. BfLogSysM("BfModule finish: %p\n", this);
  17881. if (mHadBuildError)
  17882. {
  17883. // Don't AssertErrorState here, this current pass may not have failed but
  17884. // the module was still queued in mFinishedModuleWorkList
  17885. ClearModule();
  17886. return true;
  17887. }
  17888. if (mUsedSlotCount != -1)
  17889. {
  17890. BF_ASSERT(mCompiler->mMaxInterfaceSlots != -1);
  17891. mUsedSlotCount = mCompiler->mMaxInterfaceSlots;
  17892. }
  17893. BF_ASSERT(mAddedToCount);
  17894. mAddedToCount = false;
  17895. mAwaitingFinish = false;
  17896. mCompiler->mStats.mModulesFinished++;
  17897. if (HasCompiledOutput())
  17898. {
  17899. DbgFinish();
  17900. if (mAwaitingInitFinish)
  17901. FinishInit();
  17902. for (auto ownedTypeInst : mOwnedTypeInstances)
  17903. {
  17904. // Generate dbg info and add global variables if we haven't already
  17905. mBfIRBuilder->PopulateType(ownedTypeInst);
  17906. }
  17907. if (mBfIRBuilder->DbgHasInfo())
  17908. {
  17909. mBfIRBuilder->DbgFinalize();
  17910. }
  17911. String objOutputPath;
  17912. String irOutputPath;
  17913. mIsModuleMutable = false;
  17914. //mOutFileNames.Clear();
  17915. BF_ASSERT((int)mOutFileNames.size() >= mExtensionCount);
  17916. bool writeModule = mBfIRBuilder->HasExports();
  17917. String outputPath;
  17918. BfCodeGenOptions codeGenOptions = mProject->mCodeGenOptions;
  17919. auto& compilerOpts = mCompiler->mOptions;
  17920. codeGenOptions.mSIMDSetting = compilerOpts.mSIMDSetting;
  17921. auto moduleOptions = GetModuleOptions();
  17922. codeGenOptions.mOptLevel = moduleOptions.mOptLevel;
  17923. codeGenOptions.mSIMDSetting = moduleOptions.mSIMDSetting;
  17924. codeGenOptions.mWriteLLVMIR = mCompiler->mOptions.mWriteIR;
  17925. codeGenOptions.mWriteObj = mCompiler->mOptions.mGenerateObj;
  17926. codeGenOptions.mWriteBitcode = mCompiler->mOptions.mGenerateBitcode;
  17927. codeGenOptions.mVirtualMethodOfs = 1 + mCompiler->GetDynCastVDataCount() + mCompiler->mMaxInterfaceSlots;
  17928. codeGenOptions.mDynSlotOfs = mSystem->mPtrSize - mCompiler->GetDynCastVDataCount() * 4;
  17929. mCompiler->mStats.mIRBytes += mBfIRBuilder->mStream.GetSize();
  17930. mCompiler->mStats.mConstBytes += mBfIRBuilder->mTempAlloc.GetAllocSize();
  17931. bool allowWriteToLib = true;
  17932. if ((allowWriteToLib) && (codeGenOptions.mOptLevel == BfOptLevel_OgPlus) && (mModuleName != "vdata"))
  17933. {
  17934. codeGenOptions.mWriteToLib = true;
  17935. mWroteToLib = true;
  17936. }
  17937. else
  17938. {
  17939. mWroteToLib = false;
  17940. }
  17941. for (int fileIdx = 0; fileIdx <= mExtensionCount; fileIdx++)
  17942. {
  17943. outputPath = mModuleName;
  17944. outputPath = mCompiler->mOutputDirectory + "/" + mProject->mName + "/" + outputPath;
  17945. BfModuleFileName moduleFileName;
  17946. if (mParentModule != NULL)
  17947. {
  17948. for (auto&& checkPair : mParentModule->mSpecializedMethodModules)
  17949. {
  17950. if (checkPair.mValue == this)
  17951. moduleFileName.mProjects = checkPair.mKey;
  17952. }
  17953. }
  17954. moduleFileName.mProjects.Add(mProject);
  17955. if (fileIdx > 0)
  17956. outputPath += StrFormat("@%d", fileIdx + 1);
  17957. if (mCompiler->mOptions.mWriteIR)
  17958. irOutputPath = outputPath + ".ll";
  17959. if (mCompiler->mOptions.mGenerateObj)
  17960. {
  17961. objOutputPath = outputPath + BF_OBJ_EXT;
  17962. moduleFileName.mFileName = objOutputPath;
  17963. }
  17964. else if (mCompiler->mOptions.mWriteIR)
  17965. {
  17966. moduleFileName.mFileName = irOutputPath;
  17967. }
  17968. else if ((!mCompiler->mOptions.mGenerateObj) && (!mCompiler->mOptions.mGenerateBitcode) && (!mCompiler->mOptions.mWriteIR))
  17969. {
  17970. BF_FATAL("Neither obj nor IR specified");
  17971. }
  17972. moduleFileName.mModuleWritten = writeModule;
  17973. moduleFileName.mWroteToLib = mWroteToLib;
  17974. if (!mOutFileNames.Contains(moduleFileName))
  17975. mOutFileNames.Add(moduleFileName);
  17976. }
  17977. if (mCompiler->IsHotCompile())
  17978. {
  17979. codeGenOptions.mIsHotCompile = true;
  17980. //TODO: Why did we have this 'mWroteToLib' check? 'vdata' didn't get this flag set, which
  17981. // is required for rebuilding vdata after we hot create a vdata
  17982. //if (mWroteToLib)
  17983. {
  17984. if (mParentModule != NULL)
  17985. mParentModule->mHadHotObjectWrites = true;
  17986. mHadHotObjectWrites = true;
  17987. }
  17988. }
  17989. //TODO: Testing VDATA
  17990. /*if (mModuleName == "vdata")
  17991. {
  17992. codeGenOptions.mOptLevel = 4;
  17993. }*/
  17994. codeGenOptions.GenerateHash();
  17995. BP_ZONE("BfModule::Finish.WriteObjectFile");
  17996. if ((writeModule) && (!mBfIRBuilder->mIgnoreWrites))
  17997. mCompiler->mCodeGen.WriteObjectFile(this, outputPath, codeGenOptions);
  17998. mLastModuleWrittenRevision = mCompiler->mRevision;
  17999. }
  18000. else
  18001. {
  18002. for (auto type : mOwnedTypeInstances)
  18003. {
  18004. BF_ASSERT(!type->IsIncomplete());
  18005. }
  18006. }
  18007. for (auto& specModulePair : mSpecializedMethodModules)
  18008. {
  18009. auto specModule = specModulePair.mValue;
  18010. if ((specModule->mIsModuleMutable) && (!specModule->mAwaitingFinish))
  18011. {
  18012. BfLogSysM(" Mutable spec module remaining: %p\n", specModule);
  18013. }
  18014. }
  18015. CleanupFileInstances();
  18016. // We can't ClearModuleData here because we need the mSpecializedMethodModules to remain valid until we Finish them too
  18017. return true;
  18018. }
  18019. void BfModule::ReportMemory(MemReporter* memReporter)
  18020. {
  18021. memReporter->Add(sizeof(BfModule));
  18022. if (mBfIRBuilder != NULL)
  18023. {
  18024. memReporter->BeginSection("IRBuilder_ConstData");
  18025. memReporter->Add("Used", mBfIRBuilder->mTempAlloc.GetAllocSize());
  18026. memReporter->Add("Unused", mBfIRBuilder->mTempAlloc.GetTotalAllocSize() - mBfIRBuilder->mTempAlloc.GetAllocSize());
  18027. memReporter->EndSection();
  18028. memReporter->BeginSection("IRBuilder_BFIR");
  18029. memReporter->Add("Used", (int)(mBfIRBuilder->mStream.GetSize()));
  18030. memReporter->Add("Unused", (int)(mBfIRBuilder->mStream.mPools.size() * ChunkedDataBuffer::ALLOC_SIZE) - mBfIRBuilder->mStream.GetSize());
  18031. memReporter->EndSection();
  18032. memReporter->Add(sizeof(BfIRBuilder));
  18033. }
  18034. memReporter->BeginSection("FileInstanceMap");
  18035. memReporter->AddMap(mFileInstanceMap);
  18036. memReporter->AddMap(mNamedFileInstanceMap);
  18037. memReporter->Add((int)mNamedFileInstanceMap.size() * sizeof(BfFileInstance));
  18038. memReporter->EndSection();
  18039. memReporter->AddVec(mOwnedTypeInstances, false);
  18040. memReporter->AddVec(mSpecializedMethodModules, false);
  18041. memReporter->AddVec(mOutFileNames, false);
  18042. memReporter->AddMap("FuncReferences", mFuncReferences, false);
  18043. memReporter->AddMap(mInterfaceSlotRefs, false);
  18044. memReporter->AddMap(mStaticFieldRefs, false);
  18045. memReporter->AddMap(mClassVDataRefs, false);
  18046. memReporter->AddMap("VDataExtMap", mClassVDataExtRefs, false);
  18047. memReporter->AddMap(mTypeDataRefs, false);
  18048. memReporter->AddMap(mDbgRawAllocDataRefs, false);
  18049. memReporter->AddMap(mDeferredMethodCallData, false);
  18050. memReporter->AddHashSet(mDeferredMethodIds, false);
  18051. memReporter->AddHashSet("ModuleRefs", mModuleRefs, false);
  18052. }
  18053. // ClearModuleData is called immediately after the module is compiled, so don't clear out any data that needs to
  18054. // be transient through the next compile
  18055. void BfModule::ClearModuleData()
  18056. {
  18057. BfLogSysM("ClearModuleData %p\n", this);
  18058. if (mAddedToCount)
  18059. {
  18060. mCompiler->mStats.mModulesFinished++;
  18061. mAddedToCount = false;
  18062. }
  18063. mDICompileUnit = BfIRMDNode();
  18064. mIsModuleMutable = false;
  18065. mIncompleteMethodCount = 0;
  18066. mHasGenericMethods = false;
  18067. // We don't want to clear these because we want it to persist through module extensions-
  18068. // otherwise we may think an extension succeeds even though the base module failed
  18069. //mHadBuildError = false;
  18070. //mHadBuildWarning = false;
  18071. mClassVDataRefs.Clear();
  18072. mClassVDataExtRefs.Clear();
  18073. for (auto& kv : mTypeDataRefs)
  18074. kv.mValue = BfIRValue();
  18075. mStringCharPtrPool.Clear();
  18076. mStringObjectPool.Clear();
  18077. mStaticFieldRefs.Clear();
  18078. BF_ASSERT(!mIgnoreErrors);
  18079. for (auto prevIRBuilder : mPrevIRBuilders)
  18080. delete prevIRBuilder;
  18081. mPrevIRBuilders.Clear();
  18082. for (auto& specPair : mSpecializedMethodModules)
  18083. {
  18084. auto specModule = specPair.mValue;
  18085. specModule->ClearModuleData();
  18086. }
  18087. for (int i = 0; i < BfBuiltInFuncType_Count; i++)
  18088. mBuiltInFuncs[i] = BfIRFunction();
  18089. if (mNextAltModule != NULL)
  18090. mNextAltModule->ClearModuleData();
  18091. BfLogSysM("ClearModuleData. Deleting IRBuilder: %p\n", mBfIRBuilder);
  18092. delete mBfIRBuilder;
  18093. mBfIRBuilder = NULL;
  18094. mWantsIRIgnoreWrites = false;
  18095. }
  18096. void BfModule::DisownMethods()
  18097. {
  18098. for (int i = 0; i < BfBuiltInFuncType_Count; i++)
  18099. mBuiltInFuncs[i] = BfIRFunction();
  18100. BfModule* methodModule = this;
  18101. if (mParentModule != NULL)
  18102. methodModule = mParentModule;
  18103. for (auto typeInst : methodModule->mOwnedTypeInstances)
  18104. {
  18105. for (auto& methodGroup : typeInst->mMethodInstanceGroups)
  18106. {
  18107. if (methodGroup.mDefault != NULL)
  18108. {
  18109. if (methodGroup.mDefault->mIRFunction)
  18110. {
  18111. BF_ASSERT(methodGroup.mDefault->mDeclModule != NULL);
  18112. if (methodGroup.mDefault->mDeclModule == this)
  18113. {
  18114. methodGroup.mDefault->mIRFunction = BfIRFunction();
  18115. }
  18116. }
  18117. }
  18118. if (methodGroup.mMethodSpecializationMap != NULL)
  18119. {
  18120. for (auto& mapPair : *methodGroup.mMethodSpecializationMap)
  18121. {
  18122. auto methodInstance = mapPair.mValue;
  18123. if (methodInstance->mDeclModule == this)
  18124. {
  18125. methodInstance->mIRFunction = BfIRFunction();
  18126. }
  18127. }
  18128. }
  18129. }
  18130. }
  18131. }
  18132. void BfModule::ClearModule()
  18133. {
  18134. ClearModuleData();
  18135. DisownMethods();
  18136. for (auto& specPair : mSpecializedMethodModules)
  18137. {
  18138. auto specModule = specPair.mValue;
  18139. specModule->ClearModule();
  18140. }
  18141. if (mNextAltModule != NULL)
  18142. mNextAltModule->ClearModule();
  18143. }