BfModule.cpp 699 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737
  1. //#define USE_THUNKED_MddLLOC..
  2. #include "BeefySysLib/util/AllocDebug.h"
  3. #pragma warning(push) // 6
  4. #pragma warning(disable:4996)
  5. #include "BfCompiler.h"
  6. #include "BfSystem.h"
  7. #include "BfParser.h"
  8. #include "BfCodeGen.h"
  9. #include "BfExprEvaluator.h"
  10. #include "../Backend/BeLibManger.h"
  11. #include <fcntl.h>
  12. #include "BfConstResolver.h"
  13. #include "BfMangler.h"
  14. #include "BeefySysLib/util/PerfTimer.h"
  15. #include "BeefySysLib/util/BeefPerf.h"
  16. #include "BeefySysLib/util/StackHelper.h"
  17. #include "BfSourceClassifier.h"
  18. #include "BfAutoComplete.h"
  19. #include "BfDemangler.h"
  20. #include "BfResolvePass.h"
  21. #include "BfFixits.h"
  22. #include "BfIRCodeGen.h"
  23. #include "BfDefBuilder.h"
  24. #include "BfDeferEvalChecker.h"
  25. #pragma warning(pop)
  26. //////////////////////////////////////////////////////////////////////////
  27. static bool gDebugStuff = false;
  28. USING_NS_BF;
  29. //////////////////////////////////////////////////////////////////////////
  30. void BfLocalVariable::Init()
  31. {
  32. if (mResolvedType->IsValuelessType())
  33. {
  34. mIsAssigned = true;
  35. return;
  36. }
  37. if (mIsAssigned)
  38. return;
  39. bool isStruct = mResolvedType->IsStruct();
  40. if (mResolvedType->IsRef())
  41. isStruct = mResolvedType->GetUnderlyingType()->IsStruct();
  42. if ((isStruct) || ((mIsThis) && (mResolvedType->IsStructOrStructPtr())))
  43. {
  44. auto resolvedTypeRef = mResolvedType;
  45. if ((resolvedTypeRef->IsPointer()) || (resolvedTypeRef->IsRef()))
  46. resolvedTypeRef = resolvedTypeRef->GetUnderlyingType();
  47. auto typeInstance = resolvedTypeRef->ToTypeInstance();
  48. mUnassignedFieldFlags = (1 << typeInstance->mMergedFieldDataCount) - 1;
  49. if ((mIsThis) && (typeInstance->mBaseType != NULL))
  50. {
  51. // Base ctor is responsible for initializing its own fields
  52. mUnassignedFieldFlags &= ~(((int64)1 << typeInstance->mBaseType->mMergedFieldDataCount) - 1);
  53. }
  54. if (mUnassignedFieldFlags == 0)
  55. mIsAssigned = true;
  56. }
  57. else
  58. {
  59. mUnassignedFieldFlags = 1;
  60. }
  61. }
  62. BfLocalMethod::~BfLocalMethod()
  63. {
  64. BfLogSys(mSystem, "~BfLocalMethod %p\n", this);
  65. if (mMethodDeclaration != NULL)
  66. {
  67. mSource->mRefCount--;
  68. BF_ASSERT(mSource->mRefCount >= 0);
  69. }
  70. delete mMethodDef;
  71. delete mMethodInstanceGroup;
  72. }
  73. void BfDeferredLocalAssignData::ExtendFrom(BfDeferredLocalAssignData* outerLocalAssignData, bool doChain)
  74. {
  75. mIsChained = doChain;
  76. if (outerLocalAssignData == NULL)
  77. return;
  78. mChainedAssignData = outerLocalAssignData;
  79. if (!doChain)
  80. {
  81. outerLocalAssignData->BreakExtendChain();
  82. mAssignedLocals = outerLocalAssignData->mAssignedLocals;
  83. }
  84. mVarIdBarrier = outerLocalAssignData->mVarIdBarrier;
  85. }
  86. // The "extend chain" is broken when we have a conditional where the variable may not be defined after the block.
  87. // IE: "a" will be defined after the following, but "b" will not necessarily be defined.
  88. // if ((GetValue(out a)) && (GetValue(out b)) {}
  89. void BfDeferredLocalAssignData::BreakExtendChain()
  90. {
  91. if (!mIsChained)
  92. return;
  93. mIsChained = false;
  94. if (mChainedAssignData == NULL)
  95. return;
  96. mChainedAssignData->BreakExtendChain();
  97. mAssignedLocals = mChainedAssignData->mAssignedLocals;
  98. }
  99. void BfDeferredLocalAssignData::SetIntersection(const BfDeferredLocalAssignData& otherLocalAssignData)
  100. {
  101. BreakExtendChain();
  102. //TODO: We got rid of this case because we now set the proper assigned data when we do a return
  103. // If one of these had a return then treat that case as if it did have an assign -- because it doesn't
  104. // cause an UNASSIGNED value to be used
  105. // if (mHadReturn || otherLocalAssignData.mHadReturn)
  106. // {
  107. // SetUnion(otherLocalAssignData);
  108. // mHadFallthrough = mHadFallthrough && otherLocalAssignData.mHadFallthrough;
  109. // return;
  110. // }
  111. for (int i = 0; i < (int)mAssignedLocals.size(); )
  112. {
  113. auto& local = mAssignedLocals[i];
  114. if (!otherLocalAssignData.mAssignedLocals.Contains(local))
  115. {
  116. mAssignedLocals.RemoveAt(i);
  117. }
  118. else
  119. i++;
  120. }
  121. mHadFallthrough = mHadFallthrough && otherLocalAssignData.mHadFallthrough;
  122. }
  123. void BfDeferredLocalAssignData::Validate() const
  124. {
  125. for (auto var : mAssignedLocals)
  126. {
  127. BF_ASSERT((uintptr)var.mLocalVar->mName.length() < 100000);
  128. }
  129. }
  130. void BfDeferredLocalAssignData::SetUnion(const BfDeferredLocalAssignData& otherLocalAssignData)
  131. {
  132. BreakExtendChain();
  133. Validate();
  134. otherLocalAssignData.Validate();
  135. auto otherItr = otherLocalAssignData.mAssignedLocals.begin();
  136. while (otherItr != otherLocalAssignData.mAssignedLocals.end())
  137. {
  138. if (!mAssignedLocals.Contains(*otherItr))
  139. mAssignedLocals.push_back(*otherItr);
  140. ++otherItr;
  141. }
  142. mHadFallthrough = mHadFallthrough || otherLocalAssignData.mHadFallthrough;
  143. }
  144. BfMethodState::~BfMethodState()
  145. {
  146. BF_ASSERT(mPendingNullConditional == NULL);
  147. if (mPrevMethodState != NULL)
  148. {
  149. BF_ASSERT(mCurAccessId == 1);
  150. BF_ASSERT(mCurLocalVarId <= 0);
  151. }
  152. for (auto local : mLocals)
  153. delete local;
  154. for (auto& kv : mLambdaCache)
  155. delete kv.mValue;
  156. }
  157. BfMethodState* BfMethodState::GetMethodStateForLocal(BfLocalVariable* localVar)
  158. {
  159. auto checkMethodState = this;
  160. while (checkMethodState != NULL)
  161. {
  162. if ((localVar->mLocalVarIdx < checkMethodState->mLocals.size()) &&
  163. (checkMethodState->mLocals[localVar->mLocalVarIdx] == localVar))
  164. return checkMethodState;
  165. checkMethodState = checkMethodState->mPrevMethodState;
  166. }
  167. BF_FATAL("Failed to find method state for localvar");
  168. return NULL;
  169. }
  170. void BfMethodState::LocalDefined(BfLocalVariable* localVar, int fieldIdx)
  171. {
  172. auto localVarMethodState = GetMethodStateForLocal(localVar);
  173. if (localVarMethodState != this)
  174. {
  175. return;
  176. }
  177. //BF_ASSERT(localVarMethodState == this);
  178. if (!localVar->mIsAssigned)
  179. {
  180. BfDeferredLocalAssignData* ifDeferredLocalAssignData = NULL;
  181. // 'a' is always defined, but 'b' isn't:
  182. // if (Check(out a) || Check(out b)) { } int z = a;
  183. auto deferredLocalAssignData = mDeferredLocalAssignData;
  184. if ((deferredLocalAssignData != NULL) &&
  185. (deferredLocalAssignData->mIsIfCondition) &&
  186. (!deferredLocalAssignData->mIfMayBeSkipped))
  187. {
  188. ifDeferredLocalAssignData = deferredLocalAssignData;
  189. deferredLocalAssignData = deferredLocalAssignData->mChainedAssignData;
  190. }
  191. while ((deferredLocalAssignData != NULL) &&
  192. ((deferredLocalAssignData->mIsChained) || (deferredLocalAssignData->mIsUnconditional)))
  193. deferredLocalAssignData = deferredLocalAssignData->mChainedAssignData;
  194. if ((deferredLocalAssignData == NULL) || (localVar->mLocalVarId >= deferredLocalAssignData->mVarIdBarrier))
  195. {
  196. if (fieldIdx >= 0)
  197. {
  198. localVar->mUnassignedFieldFlags &= ~((int64)1 << fieldIdx);
  199. /*if ((localVar->mResolvedTypeRef != NULL) && (localVar->mResolvedTypeRef->IsUnion()))
  200. {
  201. }*/
  202. if (localVar->mUnassignedFieldFlags == 0)
  203. localVar->mIsAssigned = true;
  204. }
  205. else
  206. {
  207. localVar->mIsAssigned = true;
  208. }
  209. }
  210. else
  211. {
  212. BF_ASSERT(deferredLocalAssignData->mVarIdBarrier != -1);
  213. BfAssignedLocal defineVal = {localVar, fieldIdx + 1};
  214. auto& assignedLocals = deferredLocalAssignData->mAssignedLocals;
  215. if (!assignedLocals.Contains(defineVal))
  216. assignedLocals.push_back(defineVal);
  217. if (ifDeferredLocalAssignData != NULL)
  218. {
  219. auto& assignedLocals = ifDeferredLocalAssignData->mAssignedLocals;
  220. if (!assignedLocals.Contains(defineVal))
  221. assignedLocals.push_back(defineVal);
  222. }
  223. }
  224. }
  225. localVar->mWrittenToId = GetRootMethodState()->mCurAccessId++;
  226. }
  227. void BfMethodState::ApplyDeferredLocalAssignData(const BfDeferredLocalAssignData& deferredLocalAssignData)
  228. {
  229. BF_ASSERT(&deferredLocalAssignData != mDeferredLocalAssignData);
  230. for (auto& assignedLocal : deferredLocalAssignData.mAssignedLocals)
  231. {
  232. LocalDefined(assignedLocal.mLocalVar);
  233. }
  234. }
  235. void BfMethodState::Reset()
  236. {
  237. mHeadScope.mDeferredCallEntries.DeleteAll();
  238. }
  239. //////////////////////////////////////////////////////////////////////////
  240. void BfAmbiguityContext::Add(int id, BfTypeInterfaceEntry* interfaceEntry, int methodIdx, BfMethodInstance* candidateA, BfMethodInstance* candidateB)
  241. {
  242. Entry* entry = NULL;
  243. if (mEntries.TryAdd(id, NULL, &entry))
  244. {
  245. entry->mInterfaceEntry = interfaceEntry;
  246. entry->mMethodIdx = methodIdx;
  247. }
  248. if (!entry->mCandidates.Contains(candidateA))
  249. entry->mCandidates.push_back(candidateA);
  250. if (!entry->mCandidates.Contains(candidateB))
  251. entry->mCandidates.push_back(candidateB);
  252. }
  253. void BfAmbiguityContext::Remove(int id)
  254. {
  255. mEntries.Remove(id);
  256. }
  257. void BfAmbiguityContext::Finish()
  258. {
  259. for (auto& entryPair : mEntries)
  260. {
  261. int id = entryPair.mKey;
  262. auto entry = &entryPair.mValue;
  263. if (id >= 0)
  264. {
  265. auto declMethodInstance = mTypeInstance->mVirtualMethodTable[id].mDeclaringMethod;
  266. auto error = mModule->Fail(StrFormat("Method '%s' has ambiguous overrides", mModule->MethodToString(declMethodInstance).c_str()), declMethodInstance->mMethodDef->GetRefNode());
  267. for (auto candidate : entry->mCandidates)
  268. {
  269. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' is a candidate", mModule->MethodToString(candidate).c_str()), candidate->mMethodDef->GetRefNode());
  270. }
  271. }
  272. else
  273. {
  274. auto iMethodInst = entry->mInterfaceEntry->mInterfaceType->mMethodInstanceGroups[entry->mMethodIdx].mDefault;
  275. auto error = mModule->Fail(StrFormat("Interface method '%s' has ambiguous implementations", mModule->MethodToString(iMethodInst).c_str()), entry->mInterfaceEntry->mDeclaringType->GetRefNode());
  276. for (auto candidate : entry->mCandidates)
  277. {
  278. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' is a candidate", mModule->MethodToString(candidate).c_str()), candidate->mMethodDef->GetRefNode());
  279. }
  280. }
  281. }
  282. }
  283. //////////////////////////////////////////////////////////////////////////
  284. class HasAppendAllocVisitor : BfElementVisitor
  285. {
  286. public:
  287. bool mHas;
  288. public:
  289. HasAppendAllocVisitor()
  290. {
  291. mHas = false;
  292. }
  293. void Visit(BfObjectCreateExpression* objCreateExpr)
  294. {
  295. if (auto newToken = BfNodeDynCast<BfTokenNode>(objCreateExpr->mNewNode))
  296. {
  297. if (newToken->GetToken() == BfToken_Append)
  298. {
  299. mHas = true;
  300. }
  301. }
  302. }
  303. bool HasAppendAlloc(BfAstNode* node)
  304. {
  305. mHas = false;
  306. VisitChild(node);
  307. return mHas;
  308. }
  309. };
  310. class AppendAllocVisitor : public BfStructuralVisitor
  311. {
  312. public:
  313. BfModule* mModule;
  314. HasAppendAllocVisitor mHasAppendAllocVisitor;
  315. BfTypedValue mConstAccum;
  316. bool mFailed;
  317. bool mIsFirstConstPass;
  318. int mCurAppendAlign;
  319. public:
  320. AppendAllocVisitor()
  321. {
  322. mFailed = false;
  323. mIsFirstConstPass = false;
  324. mCurAppendAlign = 0;
  325. }
  326. void EmitAppendAlign(int align, int sizeMultiple = 0)
  327. {
  328. if (mIsFirstConstPass)
  329. mModule->mCurMethodInstance->mAppendAllocAlign = BF_MAX((int)mModule->mCurMethodInstance->mAppendAllocAlign, align);
  330. if (sizeMultiple == 0)
  331. sizeMultiple = align;
  332. if (mCurAppendAlign == 0)
  333. mCurAppendAlign = sizeMultiple;
  334. else
  335. {
  336. if (sizeMultiple % align == 0)
  337. mCurAppendAlign = align;
  338. else
  339. mCurAppendAlign = sizeMultiple % align;
  340. }
  341. if (mConstAccum)
  342. {
  343. auto constant = mModule->mBfIRBuilder->GetConstant(mConstAccum.mValue);
  344. if (constant != NULL)
  345. mConstAccum.mValue = mModule->GetConstValue(BF_ALIGN(constant->mInt64, align));
  346. else
  347. BF_ASSERT(mIsFirstConstPass);
  348. return;
  349. }
  350. mModule->EmitAppendAlign(align, sizeMultiple);
  351. }
  352. void Visit(BfAstNode* astNode) override
  353. {
  354. mModule->VisitChild(astNode);
  355. }
  356. void DoObjectCreate(BfObjectCreateExpression* objCreateExpr, BfVariableDeclaration* variableDecl)
  357. {
  358. if (auto newToken = BfNodeDynCast<BfTokenNode>(objCreateExpr->mNewNode))
  359. {
  360. if (newToken->GetToken() == BfToken_Append)
  361. {
  362. //auto variableDecl = BfNodeDynCast<BfVariableDeclaration>(objCreateExpr->mParent);
  363. auto accumValuePtr = mModule->mCurMethodState->mRetVal.mValue;
  364. auto intPtrType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  365. BfArrayType* arrayType = NULL;
  366. bool isArrayAlloc = false;
  367. bool isRawArrayAlloc = objCreateExpr->mStarToken != NULL;
  368. SizedArray<BfIRValue, 2> dimLengthVals;
  369. BfType* origResolvedTypeRef = NULL;
  370. if (auto dotTypeRef = BfNodeDynCast<BfDotTypeReference>(objCreateExpr->mTypeRef))
  371. {
  372. if (variableDecl != NULL)
  373. {
  374. origResolvedTypeRef = mModule->ResolveTypeRef(variableDecl->mTypeRef, BfPopulateType_Data, BfResolveTypeRefFlag_NoResolveGenericParam);
  375. if (origResolvedTypeRef->IsObject())
  376. {
  377. if (origResolvedTypeRef->IsArray())
  378. {
  379. arrayType = (BfArrayType*)origResolvedTypeRef;
  380. origResolvedTypeRef = origResolvedTypeRef->GetUnderlyingType();
  381. isArrayAlloc = true;
  382. }
  383. }
  384. else if (origResolvedTypeRef->IsPointer())
  385. {
  386. origResolvedTypeRef = origResolvedTypeRef->GetUnderlyingType();
  387. }
  388. }
  389. }
  390. else if (auto arrayTypeRef = BfNodeDynCast<BfArrayTypeRef>(objCreateExpr->mTypeRef))
  391. {
  392. isArrayAlloc = true;
  393. origResolvedTypeRef = mModule->ResolveTypeRef(arrayTypeRef->mElementType);
  394. int dimensions = 1;
  395. if (arrayTypeRef->mParams.size() != 0)
  396. {
  397. auto intType = mModule->ResolveTypeDef(mModule->mSystem->mTypeIntPtr);
  398. for (auto arg : arrayTypeRef->mParams)
  399. {
  400. if (auto tokenNode = BfNodeDynCastExact<BfTokenNode>(arg))
  401. {
  402. if (tokenNode->GetToken() == BfToken_Comma)
  403. {
  404. if (isRawArrayAlloc)
  405. {
  406. mModule->Fail("Sized arrays cannot be multidimensional", tokenNode);
  407. continue;
  408. }
  409. dimensions++;
  410. continue;
  411. }
  412. }
  413. auto expr = BfNodeDynCast<BfExpression>(arg);
  414. if ((isRawArrayAlloc) && (!dimLengthVals.IsEmpty()))
  415. {
  416. mModule->CreateValueFromExpression(expr, intType);
  417. continue;
  418. }
  419. BfTypedValue dimLength;
  420. if (expr == NULL)
  421. {
  422. // Not specified
  423. dimLengthVals.push_back(BfIRValue());
  424. continue;
  425. }
  426. if (arg != NULL)
  427. dimLength = mModule->CreateValueFromExpression(expr, intType);
  428. if (!dimLength)
  429. {
  430. dimLength = mModule->GetDefaultTypedValue(intType);
  431. }
  432. dimLengthVals.push_back(dimLength.mValue);
  433. }
  434. }
  435. if (!isRawArrayAlloc)
  436. arrayType = mModule->CreateArrayType(origResolvedTypeRef, dimensions);
  437. }
  438. if (origResolvedTypeRef == NULL)
  439. origResolvedTypeRef = mModule->ResolveTypeRef(objCreateExpr->mTypeRef, BfPopulateType_Data, BfResolveTypeRefFlag_NoResolveGenericParam);
  440. if (origResolvedTypeRef == NULL)
  441. {
  442. mModule->AssertErrorState();
  443. return;
  444. }
  445. bool isGenericParam = origResolvedTypeRef->IsGenericParam();
  446. auto resolvedTypeRef = origResolvedTypeRef;
  447. auto resultType = resolvedTypeRef;
  448. BfIRValue sizeValue;
  449. int curAlign = 0;
  450. if (isArrayAlloc)
  451. {
  452. int dimensions = 1;
  453. if (arrayType != NULL)
  454. dimensions = arrayType->mDimensions;
  455. bool sizeFailed = false;
  456. //
  457. {
  458. BfAstNode* initNode = objCreateExpr;
  459. for (int dim = 0; dim < dimensions; dim++)
  460. {
  461. BfAstNode* nextInitNode = NULL;
  462. int dimSize = -1;
  463. if (initNode == objCreateExpr)
  464. {
  465. dimSize = objCreateExpr->mArguments.size();
  466. if (!objCreateExpr->mArguments.IsEmpty())
  467. nextInitNode = objCreateExpr->mArguments[0];
  468. }
  469. else if (auto tupleNode = BfNodeDynCast<BfTupleExpression>(initNode))
  470. {
  471. dimSize = (int)tupleNode->mCommas.size() + 1;
  472. }
  473. if (dimSize >= 0)
  474. {
  475. if (dim >= dimLengthVals.size())
  476. dimLengthVals.Add(mModule->GetConstValue(dimSize));
  477. }
  478. else
  479. {
  480. sizeFailed = true;
  481. }
  482. }
  483. }
  484. BfIRValue allocCount;
  485. if (!sizeFailed)
  486. {
  487. if (!dimLengthVals.IsEmpty())
  488. {
  489. allocCount = dimLengthVals[0];
  490. for (int dim = 1; dim < (int)dimLengthVals.size(); dim++)
  491. allocCount = mModule->mBfIRBuilder->CreateMul(allocCount, dimLengthVals[dim]);
  492. }
  493. }
  494. if (!allocCount)
  495. {
  496. mFailed = true;
  497. if (!mIsFirstConstPass)
  498. {
  499. if (!mConstAccum)
  500. mModule->Fail("Unable to determine append alloc size", objCreateExpr->mNewNode);
  501. return;
  502. }
  503. }
  504. if (isRawArrayAlloc)
  505. {
  506. curAlign = resultType->mAlign;
  507. EmitAppendAlign(resultType->mAlign);
  508. sizeValue = mModule->mBfIRBuilder->CreateMul(mModule->GetConstValue(resultType->mSize), allocCount);
  509. }
  510. else
  511. {
  512. if (arrayType == NULL)
  513. arrayType = mModule->CreateArrayType(resultType, 1);
  514. // Array is a special case where the total size isn't aligned with mAlign
  515. // since we add arbitrary elements to the end without padding the end to align
  516. EmitAppendAlign(arrayType->mAlign, resultType->mAlign);
  517. curAlign = arrayType->mAlign;
  518. auto firstElementField = &arrayType->mFieldInstances.back();
  519. int arrayClassSize = arrayType->mInstSize - firstElementField->mDataSize;
  520. sizeValue = mModule->GetConstValue(arrayClassSize);
  521. BfIRValue elementDataSize = mModule->mBfIRBuilder->CreateMul(mModule->GetConstValue(resultType->mSize), allocCount);
  522. sizeValue = mModule->mBfIRBuilder->CreateAdd(sizeValue, elementDataSize);
  523. }
  524. }
  525. else
  526. {
  527. auto typeInst = resultType->ToTypeInstance();
  528. if (typeInst != NULL)
  529. {
  530. curAlign = typeInst->mInstAlign;
  531. EmitAppendAlign(typeInst->mInstAlign, typeInst->mInstSize);
  532. sizeValue = mModule->GetConstValue(typeInst->mInstSize);
  533. }
  534. else
  535. {
  536. curAlign = resultType->mAlign;
  537. EmitAppendAlign(resultType->mAlign, resultType->mSize);
  538. sizeValue = mModule->GetConstValue(resultType->mSize);
  539. }
  540. BfTypedValue emtpyThis(mModule->mBfIRBuilder->GetFakeVal(), resultType, (typeInst == NULL) || (typeInst->IsComposite()));
  541. BfExprEvaluator exprEvaluator(mModule);
  542. SetAndRestoreValue<bool> prevNoBind(exprEvaluator.mNoBind, exprEvaluator.mNoBind || isGenericParam);
  543. BfFunctionBindResult bindResult;
  544. bindResult.mWantsArgs = true;
  545. exprEvaluator.mFunctionBindResult = &bindResult;
  546. SizedArray<BfExpression*, 8> copiedArgs;
  547. for (BfExpression* arg : objCreateExpr->mArguments)
  548. copiedArgs.push_back(arg);
  549. BfSizedArray<BfExpression*> sizedArgExprs(copiedArgs);
  550. BfResolvedArgs argValues(&sizedArgExprs);
  551. if (typeInst != NULL)
  552. {
  553. exprEvaluator.ResolveArgValues(argValues);
  554. exprEvaluator.MatchConstructor(objCreateExpr->mTypeRef, objCreateExpr, emtpyThis, typeInst, argValues, false, true);
  555. }
  556. exprEvaluator.mFunctionBindResult = NULL;
  557. if (bindResult.mMethodInstance != NULL)
  558. {
  559. if (bindResult.mMethodInstance->mMethodDef->mHasAppend)
  560. {
  561. auto calcAppendArgs = bindResult.mIRArgs;
  562. BF_ASSERT(calcAppendArgs[0].IsFake());
  563. calcAppendArgs.RemoveRange(0, 2); // Remove 'this' and 'appendIdx'
  564. auto calcAppendMethodModule = mModule->GetMethodInstanceAtIdx(bindResult.mMethodInstance->GetOwner(), bindResult.mMethodInstance->mMethodDef->mIdx + 1, BF_METHODNAME_CALCAPPEND);
  565. auto subDependSize = mModule->TryConstCalcAppend(bindResult.mMethodInstance, calcAppendArgs);
  566. if (calcAppendMethodModule.mMethodInstance->mAppendAllocAlign > 0)
  567. {
  568. EmitAppendAlign(calcAppendMethodModule.mMethodInstance->mAppendAllocAlign);
  569. BF_ASSERT(calcAppendMethodModule.mMethodInstance->mEndingAppendAllocAlign > -1);
  570. mModule->mCurMethodState->mCurAppendAlign = BF_MAX(calcAppendMethodModule.mMethodInstance->mEndingAppendAllocAlign, 0);
  571. }
  572. curAlign = std::max(curAlign, (int)calcAppendMethodModule.mMethodInstance->mAppendAllocAlign);
  573. if ((!subDependSize) && (!mConstAccum))
  574. {
  575. BF_ASSERT(calcAppendMethodModule.mFunc);
  576. subDependSize = exprEvaluator.CreateCall(calcAppendMethodModule.mMethodInstance, calcAppendMethodModule.mFunc, false, calcAppendArgs);
  577. BF_ASSERT(subDependSize.mType == mModule->GetPrimitiveType(BfTypeCode_IntPtr));
  578. }
  579. if (subDependSize)
  580. sizeValue = mModule->mBfIRBuilder->CreateAdd(sizeValue, subDependSize.mValue);
  581. else
  582. mFailed = true;
  583. }
  584. }
  585. }
  586. if (sizeValue)
  587. {
  588. if (mConstAccum)
  589. {
  590. if (!sizeValue.IsConst())
  591. {
  592. mFailed = true;
  593. if (!mIsFirstConstPass)
  594. return;
  595. }
  596. mConstAccum.mValue = mModule->mBfIRBuilder->CreateAdd(sizeValue, mConstAccum.mValue);
  597. }
  598. else
  599. {
  600. auto prevVal = mModule->mBfIRBuilder->CreateLoad(accumValuePtr);
  601. auto addedVal = mModule->mBfIRBuilder->CreateAdd(sizeValue, prevVal);
  602. mModule->mBfIRBuilder->CreateStore(addedVal, accumValuePtr);
  603. }
  604. }
  605. }
  606. }
  607. }
  608. void Visit(BfObjectCreateExpression* objCreateExpr) override
  609. {
  610. DoObjectCreate(objCreateExpr, NULL);
  611. }
  612. void Visit(BfVariableDeclaration* varDecl) override
  613. {
  614. if (mHasAppendAllocVisitor.HasAppendAlloc(varDecl))
  615. {
  616. if (auto objectCreateExpr = BfNodeDynCast<BfObjectCreateExpression>(varDecl->mInitializer))
  617. DoObjectCreate(objectCreateExpr, varDecl);
  618. else
  619. VisitChild(varDecl->mInitializer);
  620. if (varDecl->mNameNode != NULL)
  621. {
  622. BfLocalVariable* localDef = new BfLocalVariable();
  623. localDef->mName = varDecl->mNameNode->ToString();
  624. localDef->mNameNode = BfNodeDynCast<BfIdentifierNode>(varDecl->mNameNode);
  625. localDef->mResolvedType = mModule->GetPrimitiveType(BfTypeCode_None);
  626. localDef->mIsReadOnly = true;
  627. localDef->mParamFailed = true;
  628. localDef->mReadFromId = 0;
  629. mModule->AddLocalVariableDef(localDef);
  630. }
  631. }
  632. else
  633. {
  634. mModule->Visit(varDecl);
  635. }
  636. }
  637. void Visit(BfExpressionStatement* exprStatement) override
  638. {
  639. VisitChild(exprStatement->mExpression);
  640. }
  641. // void Visit(BfIfStatement* ifStmt) override
  642. // {
  643. // mModule->DoIfStatement(ifStmt,
  644. // mHasAppendAllocVisitor.HasAppendAlloc(ifStmt->mTrueStatement),
  645. // mHasAppendAllocVisitor.HasAppendAlloc(ifStmt->mFalseStatement));
  646. // }
  647. void Visit(BfBlock* block) override
  648. {
  649. if (!mHasAppendAllocVisitor.HasAppendAlloc(block))
  650. return;
  651. int appendAllocIdx = -1;
  652. for (int childIdx = block->mChildArr.mSize - 1; childIdx >= 0; childIdx--)
  653. {
  654. auto child = block->mChildArr.mVals[childIdx];
  655. if (mHasAppendAllocVisitor.HasAppendAlloc(child))
  656. {
  657. for (int emitIdx = 0; emitIdx <= childIdx; emitIdx++)
  658. {
  659. auto emitChild = block->mChildArr.mVals[emitIdx];
  660. mModule->UpdateSrcPos(emitChild);
  661. VisitChild(emitChild);
  662. if ((mFailed) && (!mIsFirstConstPass))
  663. break;
  664. }
  665. break;
  666. }
  667. }
  668. }
  669. };
  670. //////////////////////////////////////////////////////////////////////////
  671. BfModule* gLastCreatedModule = NULL;
  672. BfModule::BfModule(BfContext* context, const StringImpl& moduleName)
  673. {
  674. BfLogSys(context->mSystem, "BfModule::BFModule %p %s\n", this, moduleName.c_str());
  675. gLastCreatedModule = this;
  676. mContext = context;
  677. mModuleName = moduleName;
  678. if (!moduleName.empty())
  679. mContext->mUsedModuleNames.Add(ToUpper(moduleName));
  680. mAddedToCount = false;
  681. mParentModule = NULL;
  682. mNextAltModule = NULL;
  683. mBfIRBuilder = NULL;
  684. mWantsIRIgnoreWrites = false;
  685. mModuleOptions = NULL;
  686. mLastUsedRevision = -1;
  687. mUsedSlotCount = -1;
  688. mIsReified = true;
  689. mReifyQueued = false;
  690. mIsSpecialModule = false;
  691. mIsScratchModule = false;
  692. mIsSpecializedMethodModuleRoot = false; // There may be mNextAltModules extending from this
  693. mHadBuildError = false;
  694. mHadBuildWarning = false;
  695. mIgnoreErrors = false;
  696. mIgnoreWarnings = false;
  697. mHadIgnoredError = false;
  698. mReportErrors = true;
  699. mIsInsideAutoComplete = false;
  700. mIsDeleting = false;
  701. mSkipInnerLookup = false;
  702. mIsHotModule = false;
  703. mSetIllegalSrcPosition = false;
  704. mNoResolveGenericParams = false;
  705. mWroteToLib = false;
  706. mContext = context;
  707. mCompiler = context->mCompiler;
  708. mSystem = mCompiler->mSystem;
  709. mProject = NULL;
  710. mCurMethodState = NULL;
  711. mAttributeState = NULL;
  712. mCurLocalMethodId = 0;
  713. mParentNodeEntry = NULL;
  714. mRevision = -1;
  715. mRebuildIdx = 0;
  716. mLastModuleWrittenRevision = 0;
  717. mIsModuleMutable = false;
  718. mExtensionCount = 0;
  719. mIncompleteMethodCount = 0;
  720. mOnDemandMethodCount = 0;
  721. mHasGenericMethods = false;
  722. mCurMethodInstance = NULL;
  723. mCurTypeInstance = NULL;
  724. mAwaitingInitFinish = false;
  725. mAwaitingFinish = false;
  726. mHasFullDebugInfo = false;
  727. mHadHotObjectWrites = false;
  728. for (int i = 0; i < BfBuiltInFuncType_Count; i++)
  729. mBuiltInFuncs[i] = BfIRFunction();
  730. BfLogSysM("Creating module %p: %s Reified: %d ResolveOnly: %d\n", this, mModuleName.c_str(), mIsReified, mCompiler->mIsResolveOnly);
  731. }
  732. void BfReportMemory();
  733. BfModule::~BfModule()
  734. {
  735. BfLogSysM("Deleting module %p: %s \n", this, mModuleName.c_str());
  736. if (!mIsDeleting)
  737. RemoveModuleData();
  738. }
  739. void BfModule::RemoveModuleData()
  740. {
  741. BF_ASSERT(!mIsDeleting);
  742. if (!mModuleName.empty())
  743. {
  744. // Note: module names not necessarily unique
  745. mContext->mUsedModuleNames.Remove(ToUpper(mModuleName));
  746. }
  747. CleanupFileInstances();
  748. delete mBfIRBuilder;
  749. mBfIRBuilder = NULL;
  750. //delete mCpu;
  751. for (auto prevModule : mPrevIRBuilders)
  752. delete prevModule;
  753. mPrevIRBuilders.Clear();
  754. for (auto& pairVal : mDeferredMethodCallData)
  755. delete pairVal.mValue;
  756. mDeferredMethodCallData.Clear();
  757. mDeferredMethodIds.Clear();
  758. for (auto& specModulePair : mSpecializedMethodModules)
  759. delete specModulePair.mValue;
  760. mSpecializedMethodModules.Clear();
  761. if (mNextAltModule != NULL)
  762. delete mNextAltModule;
  763. mNextAltModule = NULL;
  764. if (mModuleOptions != NULL)
  765. delete mModuleOptions;
  766. mModuleOptions = NULL;
  767. BfReportMemory();
  768. }
  769. void BfModule::Init(bool isFullRebuild)
  770. {
  771. mContext->mFinishedModuleWorkList.Remove(this);
  772. if ((mCompiler->mIsResolveOnly) && (this != mContext->mUnreifiedModule))
  773. BF_ASSERT(mIsReified);
  774. if (!mIsScratchModule)
  775. {
  776. mCompiler->mStats.mModulesStarted++;
  777. if (mIsReified)
  778. mCompiler->mStats.mReifiedModuleCount++;
  779. mAddedToCount = true;
  780. }
  781. mIsHotModule = (mProject != NULL) && (mCompiler->mOptions.mHotProject != NULL) && (mCompiler->mOptions.mHotProject->ContainsReference(mProject));
  782. mFuncReferences.Clear();
  783. mClassVDataRefs.Clear();
  784. mClassVDataExtRefs.Clear();
  785. //mTypeDataRefs.Clear();
  786. mDbgRawAllocDataRefs.Clear();
  787. CleanupFileInstances();
  788. mStaticFieldRefs.Clear();
  789. //mInterfaceSlotRefs.Clear();
  790. // If we are just doing an extension then the ownede types aren't rebuilt.
  791. // If we set mRevision then QueueMethodSpecializations wouldn't actually queue up required specializations
  792. // and we'd end up with link errors if the original module uniquely referred to any generic methods
  793. if (isFullRebuild)
  794. mRevision = mCompiler->mRevision;
  795. BF_ASSERT(mCurTypeInstance == NULL);
  796. mIsModuleMutable = true;
  797. BF_ASSERT((mBfIRBuilder == NULL) || (mCompiler->mIsResolveOnly));
  798. #ifdef _DEBUG
  799. EnsureIRBuilder(mCompiler->mLastAutocompleteModule == this);
  800. #else
  801. EnsureIRBuilder(false);
  802. #endif
  803. mCurMethodState = NULL;
  804. mAwaitingInitFinish = true;
  805. mOnDemandMethodCount = 0;
  806. mAwaitingFinish = false;
  807. mHasForceLinkMarker = false;
  808. mUsedSlotCount = -1;
  809. }
  810. bool BfModule::WantsFinishModule()
  811. {
  812. return (mIncompleteMethodCount == 0) && (mOnDemandMethodCount == 0) && (!mHasGenericMethods) && (!mIsScratchModule) && (mExtensionCount == 0) && (mParentModule == NULL);
  813. }
  814. void BfModule::FinishInit()
  815. {
  816. BF_ASSERT(mAwaitingInitFinish);
  817. auto moduleOptions = GetModuleOptions();
  818. mBfIRBuilder->Start(mModuleName, mCompiler->mSystem->mPtrSize, IsOptimized());
  819. mBfIRBuilder->Module_SetTargetTriple(mCompiler->mOptions.mTargetTriple);
  820. mBfIRBuilder->SetBackend(IsTargetingBeefBackend());
  821. if (moduleOptions.mOptLevel == BfOptLevel_OgPlus)
  822. {
  823. // Og+ requires debug info
  824. moduleOptions.mEmitDebugInfo = 1;
  825. }
  826. mHasFullDebugInfo = moduleOptions.mEmitDebugInfo == 1;
  827. if ((!mCompiler->mIsResolveOnly) && (!mIsScratchModule) && (moduleOptions.mEmitDebugInfo != 0) && (mIsReified))
  828. {
  829. mBfIRBuilder->DbgInit();
  830. }
  831. else
  832. mHasFullDebugInfo = false;
  833. if ((mBfIRBuilder->DbgHasInfo()) && (mModuleName != "") &&
  834. ((moduleOptions.mEmitDebugInfo != 0)))
  835. {
  836. if (mCompiler->mOptions.IsCodeView())
  837. {
  838. mBfIRBuilder->Module_AddModuleFlag("CodeView", 1);
  839. }
  840. else
  841. {
  842. mBfIRBuilder->Module_AddModuleFlag("Dwarf Version", 4);
  843. }
  844. mBfIRBuilder->Module_AddModuleFlag("Debug Info Version", 3);
  845. mDICompileUnit = mBfIRBuilder->DbgCreateCompileUnit(llvm::dwarf::DW_LANG_C_plus_plus, mModuleName, ".", "Beef Compiler 0.42", /*moduleOptions.mOptLevel > 0*/false, "", 0, !mHasFullDebugInfo);
  846. }
  847. mAwaitingInitFinish = false;
  848. }
  849. void BfModule::ReifyModule()
  850. {
  851. BF_ASSERT((mCompiler->mCompileState != BfCompiler::CompileState_Unreified) && (mCompiler->mCompileState != BfCompiler::CompileState_VData));
  852. BfLogSysM("ReifyModule %@ %s\n", this, mModuleName.c_str());
  853. BF_ASSERT((this != mContext->mScratchModule) && (this != mContext->mUnreifiedModule));
  854. mIsReified = true;
  855. mReifyQueued = false;
  856. StartNewRevision(RebuildKind_SkipOnDemandTypes, true);
  857. mCompiler->mStats.mModulesReified++;
  858. }
  859. void BfModule::UnreifyModule()
  860. {
  861. BfLogSysM("UnreifyModule %p %s\n", this, mModuleName.c_str());
  862. BF_ASSERT((this != mContext->mScratchModule) && (this != mContext->mUnreifiedModule));
  863. mIsReified = false;
  864. mReifyQueued = false;
  865. StartNewRevision(RebuildKind_None, true);
  866. mCompiler->mStats.mModulesUnreified++;
  867. }
  868. void BfModule::CleanupFileInstances()
  869. {
  870. for (auto& itr : mNamedFileInstanceMap)
  871. {
  872. BfLogSysM("FileInstance deleted: %p\n", itr.mValue);
  873. delete itr.mValue;
  874. }
  875. mCurFilePosition.mFileInstance = NULL;//
  876. mFileInstanceMap.Clear();
  877. mNamedFileInstanceMap.Clear();
  878. }
  879. void BfModule::Cleanup()
  880. {
  881. CleanupFileInstances();
  882. }
  883. void BfModule::PrepareForIRWriting(BfTypeInstance* typeInst)
  884. {
  885. if (HasCompiledOutput())
  886. {
  887. // It's possible that the target's code hasn't changed but we're requesting a new generic method specialization
  888. if ((!mIsModuleMutable) && (!typeInst->IsUnspecializedType()) && (!typeInst->mResolvingVarField))
  889. {
  890. StartExtension();
  891. }
  892. }
  893. else
  894. {
  895. EnsureIRBuilder();
  896. }
  897. }
  898. void BfModule::EnsureIRBuilder(bool dbgVerifyCodeGen)
  899. {
  900. BF_ASSERT(!mIsDeleting);
  901. if (mBfIRBuilder == NULL)
  902. {
  903. if ((!mIsScratchModule) && (!mAddedToCount))
  904. {
  905. mCompiler->mStats.mModulesStarted++;
  906. mAddedToCount = true;
  907. }
  908. BF_ASSERT(mStaticFieldRefs.GetCount() == 0);
  909. /*if (mCompiler->mIsResolveOnly)
  910. BF_ASSERT(mIsResolveOnly);*/
  911. mBfIRBuilder = new BfIRBuilder(this);
  912. BfLogSysM("Created mBfIRBuilder %p in %p %s Reified: %d\n", mBfIRBuilder, this, mModuleName.c_str(), mIsReified);
  913. if (mIsScratchModule)
  914. {
  915. mBfIRBuilder->mIgnoreWrites = true;
  916. BF_ASSERT(!dbgVerifyCodeGen);
  917. }
  918. #ifdef _DEBUG
  919. if (mCompiler->mIsResolveOnly)
  920. {
  921. // For "deep" verification testing
  922. /*if (!mIsSpecialModule)
  923. dbgVerifyCodeGen = true;*/
  924. // We only want to turn this off on smaller builds for testing
  925. mBfIRBuilder->mIgnoreWrites = true;
  926. if (dbgVerifyCodeGen)
  927. mBfIRBuilder->mIgnoreWrites = false;
  928. if (!mBfIRBuilder->mIgnoreWrites)
  929. {
  930. // The only purpose of not ignoring writes is so we can verify the codegen one instruction at a time
  931. mBfIRBuilder->mDbgVerifyCodeGen = true;
  932. }
  933. }
  934. else if (!mIsReified)
  935. {
  936. mBfIRBuilder->mIgnoreWrites = true;
  937. }
  938. else
  939. {
  940. // We almost always want this to be 'false' unless we need need to be able to inspect the generated LLVM
  941. // code as we walk the AST
  942. //mBfIRBuilder->mDbgVerifyCodeGen = true;
  943. if (
  944. (mModuleName == "Program")
  945. //|| (mModuleName == "System_Internal")
  946. //|| (mModuleName == "vdata")
  947. //|| (mModuleName == "Hey_Dude_Bro_TestClass")
  948. )
  949. mBfIRBuilder->mDbgVerifyCodeGen = true;
  950. // Just for testing!
  951. //mBfIRBuilder->mIgnoreWrites = true;
  952. }
  953. #else
  954. if (mCompiler->mIsResolveOnly)
  955. {
  956. // Always ignore writes in resolveOnly for release builds
  957. mBfIRBuilder->mIgnoreWrites = true;
  958. }
  959. else
  960. {
  961. // Just for memory testing! This breaks everything.
  962. //mBfIRBuilder->mIgnoreWrites = true;
  963. // For "deep" verification testing
  964. //mBfIRBuilder->mDbgVerifyCodeGen = true;
  965. }
  966. #endif
  967. mWantsIRIgnoreWrites = mBfIRBuilder->mIgnoreWrites;
  968. }
  969. }
  970. BfIRValue BfModule::CreateForceLinkMarker(BfModule* module, String* outName)
  971. {
  972. String name = "FORCELINKMOD_" + module->mModuleName;
  973. if (outName != NULL)
  974. *outName = name;
  975. auto markerType = GetPrimitiveType(BfTypeCode_Int8);
  976. return mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapType(markerType), true, BfIRLinkageType_External, (module == this) ? mBfIRBuilder->CreateConst(BfTypeCode_Int8, 0) : BfIRValue(), name);
  977. }
  978. void BfModule::StartNewRevision(RebuildKind rebuildKind, bool force)
  979. {
  980. BP_ZONE("BfModule::StartNewRevision");
  981. // The project MAY be deleted because disabling a project can cause types to be deleted which
  982. // causes other types rebuild BEFORE they get deleted, which is okay (though wasteful)
  983. //BF_ASSERT((mProject == NULL) || (!mProject->mDisabled));
  984. // Already on new revision?
  985. if ((mRevision == mCompiler->mRevision) && (!force))
  986. return;
  987. mHadBuildError = false;
  988. mHadBuildWarning = false;
  989. mExtensionCount = 0;
  990. mRevision = mCompiler->mRevision;
  991. mRebuildIdx++;
  992. ClearModuleData();
  993. // Clear this here, not in ClearModuleData, so we preserve those references even after writing out module
  994. if (rebuildKind != BfModule::RebuildKind_None) // Leave string pool refs for when we need to use things like [LinkName("")] methods bofore re-reification
  995. mStringPoolRefs.Clear();
  996. mDllImportEntries.Clear();
  997. mImportFileNames.Clear();
  998. for (auto& pairVal : mDeferredMethodCallData)
  999. delete pairVal.mValue;
  1000. mDeferredMethodCallData.Clear();
  1001. mDeferredMethodIds.Clear();
  1002. mModuleRefs.Clear();
  1003. mOutFileNames.Clear();
  1004. mTypeDataRefs.Clear();
  1005. mInterfaceSlotRefs.Clear();
  1006. if (rebuildKind == BfModule::RebuildKind_None)
  1007. {
  1008. for (auto& specPair : mSpecializedMethodModules)
  1009. {
  1010. auto specModule = specPair.mValue;
  1011. if (specModule->mIsReified != mIsReified)
  1012. {
  1013. if (mIsReified)
  1014. specModule->ReifyModule();
  1015. else
  1016. specModule->UnreifyModule();
  1017. }
  1018. }
  1019. }
  1020. else
  1021. {
  1022. for (auto& specPair : mSpecializedMethodModules)
  1023. {
  1024. auto specModule = specPair.mValue;
  1025. delete specModule;
  1026. }
  1027. }
  1028. mSpecializedMethodModules.Clear();
  1029. delete mNextAltModule;
  1030. mNextAltModule = NULL;
  1031. BF_ASSERT(mModuleOptions == NULL);
  1032. BfLogSysM("Mod:%p StartNewRevision: %s Revision: %d\n", this, mModuleName.c_str(), mRevision);
  1033. bool needsTypePopulated = false;
  1034. int oldOnDemandCount = 0;
  1035. // We don't have to rebuild types in the unspecialized module because there is no
  1036. // data that's needed -- their method instances are all NULL and the module
  1037. // doesn't get included in the build
  1038. if (this != mContext->mScratchModule)
  1039. {
  1040. for (int typeIdx = 0; typeIdx < (int)mOwnedTypeInstances.size(); typeIdx++)
  1041. {
  1042. auto typeInst = mOwnedTypeInstances[typeIdx];
  1043. if (!typeInst->IsDeleting())
  1044. {
  1045. typeInst->mIsReified = mIsReified;
  1046. if (rebuildKind != BfModule::RebuildKind_None)
  1047. {
  1048. if (typeInst->IsOnDemand())
  1049. {
  1050. // Changing config should require on demand types to be recreated, but reifying a module shouldn't cause the type to be deleted
  1051. if (rebuildKind == BfModule::RebuildKind_All)
  1052. mContext->DeleteType(typeInst);
  1053. else
  1054. {
  1055. RebuildMethods(typeInst);
  1056. }
  1057. }
  1058. else
  1059. mContext->RebuildType(typeInst, false, false, false);
  1060. }
  1061. else
  1062. {
  1063. for (auto& methodGroup : typeInst->mMethodInstanceGroups)
  1064. if ((methodGroup.mOnDemandKind == BfMethodOnDemandKind_NoDecl_AwaitingReference) ||
  1065. (methodGroup.mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingReference))
  1066. {
  1067. oldOnDemandCount++;
  1068. }
  1069. }
  1070. if (typeInst->IsDeleting())
  1071. typeIdx--;
  1072. }
  1073. }
  1074. }
  1075. if (!mIsDeleting)
  1076. Init();
  1077. mOnDemandMethodCount += oldOnDemandCount;
  1078. }
  1079. void BfModule::StartExtension()
  1080. {
  1081. BF_ASSERT(!mIsModuleMutable);
  1082. BfLogSysM("Extension started of module %p\n", this);
  1083. mExtensionCount++;
  1084. if (mBfIRBuilder != NULL)
  1085. mPrevIRBuilders.push_back(mBfIRBuilder);
  1086. mBfIRBuilder = NULL;
  1087. mWantsIRIgnoreWrites = false;
  1088. mFuncReferences.Clear();
  1089. mClassVDataRefs.Clear();
  1090. mClassVDataExtRefs.Clear();
  1091. for (auto& kv : mTypeDataRefs)
  1092. kv.mValue = BfIRValue();
  1093. mDbgRawAllocDataRefs.Clear();
  1094. mStringCharPtrPool.Clear();
  1095. mStringObjectPool.Clear();
  1096. mStaticFieldRefs.Clear();
  1097. for (auto& kv : mInterfaceSlotRefs)
  1098. kv.mValue = BfIRValue();
  1099. mDeferredMethodCallData.Clear();
  1100. mDeferredMethodIds.Clear();
  1101. DisownMethods();
  1102. BfLogSysM("Mod:%p StartExtension: %s\n", this, mModuleName.c_str());
  1103. bool wasAwaitingInitFinish = mAwaitingInitFinish;
  1104. int prevOnDemandMethodCount = mOnDemandMethodCount;
  1105. Init(false);
  1106. if (!wasAwaitingInitFinish)
  1107. FinishInit();
  1108. mOnDemandMethodCount = prevOnDemandMethodCount;
  1109. }
  1110. void BfModule::GetConstClassValueParam(BfIRValue classVData, SizedArrayImpl<BfIRValue>& typeValueParams)
  1111. {
  1112. BfIRValue vDataValue;
  1113. if (mCompiler->mOptions.mObjectHasDebugFlags)
  1114. vDataValue = mBfIRBuilder->CreatePtrToInt(classVData, BfTypeCode_IntPtr);
  1115. else
  1116. vDataValue = mBfIRBuilder->CreateBitCast(classVData, mBfIRBuilder->MapType(mContext->mBfClassVDataPtrType));
  1117. typeValueParams.push_back(vDataValue);
  1118. if (mCompiler->mOptions.mObjectHasDebugFlags)
  1119. {
  1120. auto primType = GetPrimitiveType(BfTypeCode_IntPtr);
  1121. typeValueParams.push_back(GetDefaultValue(primType));
  1122. }
  1123. }
  1124. BfIRValue BfModule::GetConstValue(int64 val)
  1125. {
  1126. return mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, (uint64)val);
  1127. }
  1128. BfIRValue BfModule::GetConstValue(int64 val, BfType* type)
  1129. {
  1130. BfType* checkType = type;
  1131. if (type->IsTypedPrimitive())
  1132. {
  1133. checkType = type->GetUnderlyingType();
  1134. }
  1135. if (checkType->IsPrimitiveType())
  1136. {
  1137. auto primType = (BfPrimitiveType*)checkType;
  1138. if (checkType->IsFloat())
  1139. return mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, (double)val);
  1140. else
  1141. return mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, (uint64)val);
  1142. }
  1143. return BfIRValue();
  1144. }
  1145. BfIRValue BfModule::GetConstValue8(int val)
  1146. {
  1147. return mBfIRBuilder->CreateConst(BfTypeCode_Int8, (uint64)val);
  1148. }
  1149. BfIRValue BfModule::GetConstValue32(int32 val)
  1150. {
  1151. return mBfIRBuilder->CreateConst(BfTypeCode_Int32, (uint64)val);
  1152. }
  1153. BfIRValue BfModule::GetConstValue64(int64 val)
  1154. {
  1155. return mBfIRBuilder->CreateConst(BfTypeCode_Int64, (uint64)val);
  1156. }
  1157. BfIRValue BfModule::GetDefaultValue(BfType* type)
  1158. {
  1159. PopulateType(type, BfPopulateType_Data);
  1160. mBfIRBuilder->PopulateType(type, BfIRPopulateType_Declaration);
  1161. if (type->IsTypedPrimitive())
  1162. {
  1163. auto underlyingType = type->GetUnderlyingType();
  1164. if (underlyingType == NULL)
  1165. return mBfIRBuilder->CreateConst(BfTypeCode_Int64, 0);
  1166. return GetDefaultValue(type->GetUnderlyingType());
  1167. }
  1168. if (type->IsPointer() || type->IsObjectOrInterface() || type->IsGenericParam() || type->IsVar() || type->IsRef() || type->IsNull() ||
  1169. type->IsRetTypeType() || type->IsConcreteInterfaceType())
  1170. return mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(type));
  1171. if ((type->IsIntegral()) || (type->IsBoolean()))
  1172. {
  1173. auto primType = (BfPrimitiveType*)type;
  1174. return mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, (uint64)0);
  1175. }
  1176. if (type->IsFloat())
  1177. {
  1178. auto primType = (BfPrimitiveType*)type;
  1179. return mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, 0.0);
  1180. }
  1181. if (type->IsVoid())
  1182. return mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(type));
  1183. return mBfIRBuilder->CreateConstStructZero(mBfIRBuilder->MapType(type));
  1184. }
  1185. BfTypedValue BfModule::GetFakeTypedValue(BfType* type)
  1186. {
  1187. // This is a conservative "IsValueless", since it's not an error to use a fakeVal even if we don't need one
  1188. if (type->mSize == 0)
  1189. return BfTypedValue(BfIRValue(), type);
  1190. else
  1191. return BfTypedValue(mBfIRBuilder->GetFakeVal(), type);
  1192. }
  1193. BfTypedValue BfModule::GetDefaultTypedValue(BfType* type, bool allowRef, BfDefaultValueKind defaultValueKind)
  1194. {
  1195. PopulateType(type, BfPopulateType_Data);
  1196. mBfIRBuilder->PopulateType(type, type->IsValueType() ? BfIRPopulateType_Full : BfIRPopulateType_Declaration);
  1197. if (defaultValueKind == BfDefaultValueKind_Undef)
  1198. {
  1199. auto primType = type->ToPrimitiveType();
  1200. if (primType != NULL)
  1201. {
  1202. return BfTypedValue(mBfIRBuilder->GetUndefConstValue(primType->mTypeDef->mTypeCode), type);
  1203. }
  1204. return BfTypedValue(mBfIRBuilder->CreateUndefValue(mBfIRBuilder->MapType(type)), type);
  1205. }
  1206. BfTypedValue typedValue;
  1207. if ((defaultValueKind != BfDefaultValueKind_Const) && (!type->IsValuelessType()))
  1208. {
  1209. if (type->IsRef())
  1210. {
  1211. BfRefType* refType = (BfRefType*)type;
  1212. BfType* underlyingType = refType->GetUnderlyingType();
  1213. typedValue = BfTypedValue(CreateAlloca(underlyingType), underlyingType, BfTypedValueKind_Addr);
  1214. }
  1215. else
  1216. {
  1217. typedValue = BfTypedValue(CreateAlloca(type), type, BfTypedValueKind_Addr);
  1218. }
  1219. if (!mBfIRBuilder->mIgnoreWrites)
  1220. {
  1221. mBfIRBuilder->CreateMemSet(typedValue.mValue, GetConstValue(0, GetPrimitiveType(BfTypeCode_Int8)),
  1222. GetConstValue(type->mSize), type->mAlign);
  1223. }
  1224. if ((defaultValueKind == BfDefaultValueKind_Value) && (!type->IsRef()))
  1225. typedValue = LoadValue(typedValue);
  1226. return typedValue;
  1227. }
  1228. if ((type->IsRef()) && (!allowRef))
  1229. {
  1230. BfRefType* refType = (BfRefType*)type;
  1231. BfType* underlyingType = refType->GetUnderlyingType();
  1232. if (underlyingType->IsValuelessType())
  1233. typedValue = BfTypedValue(mBfIRBuilder->GetFakeVal(), underlyingType, true);
  1234. else
  1235. typedValue = BfTypedValue(mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(type)), underlyingType, true);
  1236. }
  1237. else
  1238. {
  1239. typedValue = BfTypedValue(GetDefaultValue(type), type, (defaultValueKind == BfDefaultValueKind_Addr) ? BfTypedValueKind_Addr : BfTypedValueKind_Value);
  1240. }
  1241. return typedValue;
  1242. }
  1243. BfIRValue BfModule::CreateStringCharPtr(const StringImpl& str, int stringId, bool define)
  1244. {
  1245. String stringDataName = StrFormat("__bfStrData%d", stringId);
  1246. BfIRType strCharType;
  1247. //
  1248. {
  1249. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, mWantsIRIgnoreWrites);
  1250. strCharType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->GetPrimitiveType(BfTypeCode_Char8), (int)str.length() + 1);
  1251. }
  1252. BfIRValue strConstant;
  1253. if (define)
  1254. {
  1255. strConstant = mBfIRBuilder->CreateConstString(str);
  1256. }
  1257. BfIRValue gv = mBfIRBuilder->CreateGlobalVariable(strCharType,
  1258. true, BfIRLinkageType_External,
  1259. strConstant, stringDataName);
  1260. if (define)
  1261. mBfIRBuilder->GlobalVar_SetUnnamedAddr(gv, true);
  1262. return mBfIRBuilder->CreateInBoundsGEP(gv, 0, 0);
  1263. }
  1264. BfIRValue BfModule::CreateStringObjectValue(const StringImpl& str, int stringId, bool define)
  1265. {
  1266. auto stringTypeInst = ResolveTypeDef(mCompiler->mStringTypeDef, define ? BfPopulateType_Data : BfPopulateType_Declaration)->ToTypeInstance();
  1267. mBfIRBuilder->PopulateType(stringTypeInst);
  1268. auto classVDataGlobal = CreateClassVDataGlobal(stringTypeInst);
  1269. String stringObjName = StrFormat("__bfStrObj%d", stringId);
  1270. BfIRValue stringValData;
  1271. if (define)
  1272. {
  1273. BfIRValue stringCharsVal = CreateStringCharPtr(str, stringId, define);
  1274. mStringCharPtrPool[stringId] = stringCharsVal;
  1275. SizedArray<BfIRValue, 8> typeValueParams;
  1276. GetConstClassValueParam(classVDataGlobal, typeValueParams);
  1277. auto objData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(stringTypeInst->mBaseType, BfIRPopulateType_Full), typeValueParams);
  1278. auto lenByteCount = stringTypeInst->mFieldInstances[0].mResolvedType->mSize;
  1279. typeValueParams.clear();
  1280. typeValueParams.push_back(objData);
  1281. if (lenByteCount == 4)
  1282. {
  1283. typeValueParams.push_back(GetConstValue32((int)str.length())); // mLength
  1284. typeValueParams.push_back(GetConstValue32((int32)(0x40000000 + str.length() + 1))); // mAllocSizeAndFlags
  1285. }
  1286. else
  1287. {
  1288. typeValueParams.push_back(GetConstValue64(str.length())); // mLength
  1289. typeValueParams.push_back(GetConstValue64(0x4000000000000000LL + str.length() + 1)); // mAllocSizeAndFlags
  1290. }
  1291. typeValueParams.push_back(stringCharsVal); // mPtr
  1292. stringValData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(stringTypeInst, BfIRPopulateType_Full), typeValueParams);
  1293. }
  1294. auto stringValLiteral = mBfIRBuilder->CreateGlobalVariable(
  1295. mBfIRBuilder->MapTypeInst(stringTypeInst),
  1296. true,
  1297. BfIRLinkageType_External,
  1298. define ? stringValData : BfIRValue(),
  1299. stringObjName);
  1300. auto stringVal = mBfIRBuilder->CreateBitCast(stringValLiteral, mBfIRBuilder->MapType(stringTypeInst, BfIRPopulateType_Full));
  1301. return stringVal;
  1302. }
  1303. int BfModule::GetStringPoolIdx(BfIRValue constantStr, BfIRConstHolder* constHolder)
  1304. {
  1305. BF_ASSERT(constantStr.IsConst());
  1306. if (constHolder == NULL)
  1307. constHolder = mBfIRBuilder;
  1308. auto constant = constHolder->GetConstant(constantStr);
  1309. if (constant->mTypeCode == BfTypeCode_Int32)
  1310. {
  1311. return constant->mInt32;
  1312. }
  1313. while (constant->mConstType == BfConstType_BitCast)
  1314. {
  1315. auto constBitCast = (BfConstantBitCast*)constant;
  1316. constant = constHolder->GetConstantById(constBitCast->mTarget);
  1317. }
  1318. if (constant->mConstType == BfConstType_GEP32_2)
  1319. {
  1320. auto constGEP = (BfConstantGEP32_2*)constant;
  1321. constant = constHolder->GetConstantById(constGEP->mTarget);
  1322. }
  1323. if (constant->mConstType == BfConstType_GlobalVar)
  1324. {
  1325. auto constGV = (BfGlobalVar*)constant;
  1326. const char* strDataPrefix = "__bfStrData";
  1327. if (strncmp(constGV->mName, strDataPrefix, strlen(strDataPrefix)) == 0)
  1328. return atoi(constGV->mName + strlen(strDataPrefix));
  1329. const char* strObjPrefix = "__bfStrObj";
  1330. if (strncmp(constGV->mName, strObjPrefix, strlen(strObjPrefix)) == 0)
  1331. return atoi(constGV->mName + strlen(strObjPrefix));
  1332. }
  1333. return -1;
  1334. }
  1335. String* BfModule::GetStringPoolString(BfIRValue constantStr, BfIRConstHolder * constHolder)
  1336. {
  1337. int strId = GetStringPoolIdx(constantStr, constHolder);
  1338. if (strId != -1)
  1339. {
  1340. auto& entry = mContext->mStringObjectIdMap[strId];
  1341. return &entry.mString;
  1342. }
  1343. return NULL;
  1344. }
  1345. BfIRValue BfModule::GetStringCharPtr(int stringId)
  1346. {
  1347. BfIRValue* irValue = NULL;
  1348. if (!mStringCharPtrPool.TryAdd(stringId, NULL, &irValue))
  1349. return *irValue;
  1350. // If this wasn't in neither dictionary yet, add to mStringPoolRefs
  1351. if (!mStringObjectPool.ContainsKey(stringId))
  1352. mStringPoolRefs.Add(stringId);
  1353. const StringImpl& str = mContext->mStringObjectIdMap[stringId].mString;
  1354. BfIRValue strCharPtrConst = CreateStringCharPtr(str, stringId, false);
  1355. *irValue = strCharPtrConst;
  1356. return strCharPtrConst;
  1357. }
  1358. BfIRValue BfModule::GetStringCharPtr(BfIRValue strValue)
  1359. {
  1360. if (strValue.IsConst())
  1361. {
  1362. int stringId = GetStringPoolIdx(strValue);
  1363. BF_ASSERT(stringId != -1);
  1364. return GetStringCharPtr(stringId);
  1365. }
  1366. BfIRValue charPtrPtr = mBfIRBuilder->CreateInBoundsGEP(strValue, 0, 1);
  1367. BfIRValue charPtr = mBfIRBuilder->CreateLoad(charPtrPtr);
  1368. return charPtr;
  1369. }
  1370. BfIRValue BfModule::GetStringCharPtr(const StringImpl& str)
  1371. {
  1372. return GetStringCharPtr(GetStringObjectValue(str));
  1373. }
  1374. BfIRValue BfModule::GetStringObjectValue(int strId)
  1375. {
  1376. BfIRValue* objValue;
  1377. if (mStringObjectPool.TryGetValue(strId, &objValue))
  1378. return *objValue;
  1379. auto stringPoolEntry = mContext->mStringObjectIdMap[strId];
  1380. return GetStringObjectValue(stringPoolEntry.mString, true);
  1381. }
  1382. BfIRValue BfModule::GetStringObjectValue(const StringImpl& str, bool define)
  1383. {
  1384. auto stringType = ResolveTypeDef(mCompiler->mStringTypeDef, define ? BfPopulateType_Data : BfPopulateType_Declaration);
  1385. mBfIRBuilder->PopulateType(stringType);
  1386. int strId = mContext->GetStringLiteralId(str);
  1387. BfIRValue* irValuePtr = NULL;
  1388. if (!mStringObjectPool.TryAdd(strId, NULL, &irValuePtr))
  1389. return *irValuePtr;
  1390. // If this wasn't in neither dictionary yet, add to mStringPoolRefs
  1391. if (!mStringCharPtrPool.ContainsKey(strId))
  1392. mStringPoolRefs.Add(strId);
  1393. BfIRValue strObject = CreateStringObjectValue(str, strId, define);
  1394. *irValuePtr = strObject;
  1395. mStringPoolRefs.Add(strId);
  1396. return strObject;
  1397. }
  1398. BfIRValue BfModule::CreateGlobalConstValue(const StringImpl& name, BfIRValue constant, BfIRType type, bool external)
  1399. {
  1400. auto newConst = mBfIRBuilder->CreateGlobalVariable(
  1401. type,
  1402. true,
  1403. external ? BfIRLinkageType_External : BfIRLinkageType_Internal,
  1404. constant,
  1405. name.c_str());
  1406. return newConst;
  1407. }
  1408. void BfModule::NewScopeState(bool createLexicalBlock, bool flushValueScope)
  1409. {
  1410. auto curScope = mCurMethodState->mCurScope;
  1411. if (curScope->mLabelNode != NULL)
  1412. curScope->mLabelNode->ToString(curScope->mLabel);
  1413. if (!mCurMethodState->mCurScope->mLabel.IsEmpty())
  1414. {
  1415. auto checkScope = mCurMethodState->mCurScope->mPrevScope;
  1416. while (checkScope != NULL)
  1417. {
  1418. if (checkScope->mLabel == mCurMethodState->mCurScope->mLabel)
  1419. {
  1420. auto errorNode = Fail("Duplicate scope label", curScope->mLabelNode);
  1421. if (errorNode != NULL)
  1422. mCompiler->mPassInstance->MoreInfo("See previous scope label", checkScope->mLabelNode);
  1423. break;
  1424. }
  1425. checkScope = checkScope->mPrevScope;
  1426. }
  1427. }
  1428. auto prevScope = mCurMethodState->mCurScope->mPrevScope;
  1429. if ((flushValueScope) && (prevScope != NULL) && (prevScope->mValueScopeStart))
  1430. {
  1431. if (prevScope->mHadScopeValueRetain)
  1432. mBfIRBuilder->CreateValueScopeSoftEnd(prevScope->mValueScopeStart);
  1433. else
  1434. mBfIRBuilder->CreateValueScopeHardEnd(prevScope->mValueScopeStart);
  1435. }
  1436. mCurMethodState->mBlockNestLevel++;
  1437. if ((createLexicalBlock) && (mBfIRBuilder->DbgHasInfo()) && (mHasFullDebugInfo))
  1438. {
  1439. // DIScope could be NULL if we're in an unspecialized method (for example)
  1440. if (mCurMethodState->mCurScope->mDIScope)
  1441. mCurMethodState->mCurScope->mDIScope = mBfIRBuilder->DbgCreateLexicalBlock(mCurMethodState->mCurScope->mDIScope, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, mCurFilePosition.mCurColumn);
  1442. }
  1443. mCurMethodState->mCurScope->mLocalVarStart = (int)mCurMethodState->mLocals.size();
  1444. mCurMethodState->mCurScope->mBlock = mBfIRBuilder->MaybeChainNewBlock((!mCurMethodState->mCurScope->mLabel.empty()) ? mCurMethodState->mCurScope->mLabel : "newScope");
  1445. }
  1446. void BfModule::RestoreScoreState_LocalVariables()
  1447. {
  1448. while (mCurMethodState->mCurScope->mLocalVarStart < (int)mCurMethodState->mLocals.size())
  1449. {
  1450. auto localVar = mCurMethodState->mLocals.back();
  1451. LocalVariableDone(localVar, false);
  1452. mCurMethodState->mLocals.pop_back();
  1453. if (localVar->mShadowedLocal != NULL)
  1454. {
  1455. BfLocalVarEntry* localVarEntryPtr;
  1456. if (mCurMethodState->mLocalVarSet.TryGet(BfLocalVarEntry(localVar), &localVarEntryPtr))
  1457. {
  1458. localVarEntryPtr->mLocalVar = localVar->mShadowedLocal;
  1459. }
  1460. }
  1461. else
  1462. {
  1463. mCurMethodState->mLocalVarSet.Remove(BfLocalVarEntry(localVar));
  1464. }
  1465. delete localVar;
  1466. }
  1467. }
  1468. void BfModule::RestoreScopeState()
  1469. {
  1470. BfScopeData* prevScopeData = mCurMethodState->mCurScope->mPrevScope;
  1471. mCurMethodState->mBlockNestLevel--;
  1472. if (!mCurMethodState->mCurScope->mAtEndBlocks.empty())
  1473. {
  1474. BfIRBlock afterEndBlock;
  1475. if (!mCurMethodState->mLeftBlockUncond)
  1476. {
  1477. afterEndBlock = mBfIRBuilder->CreateBlock("scopeAfterEnd");
  1478. mBfIRBuilder->CreateBr(afterEndBlock);
  1479. mBfIRBuilder->ClearDebugLocation_Last();
  1480. }
  1481. for (auto preExitBlock : mCurMethodState->mCurScope->mAtEndBlocks)
  1482. mBfIRBuilder->MoveBlockToEnd(preExitBlock);
  1483. if (afterEndBlock)
  1484. {
  1485. mBfIRBuilder->AddBlock(afterEndBlock);
  1486. mBfIRBuilder->SetInsertPoint(afterEndBlock);
  1487. }
  1488. }
  1489. if (!mCurMethodState->mLeftBlockUncond)
  1490. EmitDeferredScopeCalls(true, mCurMethodState->mCurScope);
  1491. RestoreScoreState_LocalVariables();
  1492. if (mCurMethodState->mCurScope->mValueScopeStart)
  1493. mBfIRBuilder->CreateValueScopeHardEnd(mCurMethodState->mCurScope->mValueScopeStart);
  1494. mCurMethodState->mCurScope = prevScopeData;
  1495. mCurMethodState->mTailScope = mCurMethodState->mCurScope;
  1496. }
  1497. BfIRValue BfModule::CreateAlloca(BfType* type, bool addLifetime, const char* name, BfIRValue arraySize)
  1498. {
  1499. if (mBfIRBuilder->mIgnoreWrites)
  1500. return mBfIRBuilder->GetFakeVal();
  1501. BF_ASSERT((*(int8*)&addLifetime == 1) || (*(int8*)&addLifetime == 0));
  1502. mBfIRBuilder->PopulateType(type);
  1503. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  1504. if (!mBfIRBuilder->mIgnoreWrites)
  1505. BF_ASSERT(!prevInsertBlock.IsFake());
  1506. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  1507. BfIRValue allocaInst;
  1508. if (arraySize)
  1509. allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(type), arraySize);
  1510. else
  1511. allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(type));
  1512. mBfIRBuilder->SetAllocaAlignment(allocaInst, type->mAlign);
  1513. mBfIRBuilder->ClearDebugLocation(allocaInst);
  1514. if (name != NULL)
  1515. mBfIRBuilder->SetName(allocaInst, name);
  1516. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  1517. if ((addLifetime) && (WantsLifetimes()))
  1518. {
  1519. auto lifetimeStart = mBfIRBuilder->CreateLifetimeStart(allocaInst);
  1520. mBfIRBuilder->ClearDebugLocation(lifetimeStart);
  1521. mCurMethodState->mCurScope->mDeferredLifetimeEnds.push_back(allocaInst);
  1522. }
  1523. return allocaInst;
  1524. }
  1525. BfIRValue BfModule::CreateAllocaInst(BfTypeInstance* typeInst, bool addLifetime, const char* name)
  1526. {
  1527. if (mBfIRBuilder->mIgnoreWrites)
  1528. return mBfIRBuilder->GetFakeVal();
  1529. BF_ASSERT((*(int8*)&addLifetime == 1) || (*(int8*)&addLifetime == 0));
  1530. mBfIRBuilder->PopulateType(typeInst);
  1531. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  1532. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  1533. auto allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapTypeInst(typeInst));
  1534. mBfIRBuilder->SetAllocaAlignment(allocaInst, typeInst->mInstAlign);
  1535. mBfIRBuilder->ClearDebugLocation(allocaInst);
  1536. if (name != NULL)
  1537. mBfIRBuilder->SetName(allocaInst, name);
  1538. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  1539. if ((addLifetime) && (WantsLifetimes()))
  1540. {
  1541. auto lifetimeStart = mBfIRBuilder->CreateLifetimeStart(allocaInst);
  1542. mBfIRBuilder->ClearDebugLocation(lifetimeStart);
  1543. mCurMethodState->mCurScope->mDeferredLifetimeEnds.push_back(allocaInst);
  1544. }
  1545. return allocaInst;
  1546. }
  1547. void BfModule::AddStackAlloc(BfTypedValue val, BfAstNode* refNode, BfScopeData* scopeData, bool condAlloca, bool mayEscape)
  1548. {
  1549. //This was removed because we want the alloc to be added to the __deferred list if it's actually a "stack"
  1550. // 'stack' in a head scopeData is really the same as 'scopeData', so use the simpler scopeData handling
  1551. /*if (mCurMethodState->mInHeadScope)
  1552. isScopeAlloc = true;*/
  1553. if (scopeData == NULL)
  1554. return;
  1555. auto checkBaseType = val.mType->ToTypeInstance();
  1556. if ((checkBaseType != NULL) && (checkBaseType->IsObject()))
  1557. {
  1558. bool hadDtorCall = false;
  1559. while (checkBaseType != NULL)
  1560. {
  1561. if ((checkBaseType->mTypeDef->mDtorDef != NULL) /*&& (checkBaseType != mContext->mBfObjectType)*/)
  1562. {
  1563. bool isDynAlloc = (scopeData != NULL) && (mCurMethodState->mCurScope->IsDyn(scopeData));
  1564. auto dtorMethodInstance = GetMethodInstance(checkBaseType, checkBaseType->mTypeDef->mDtorDef, BfTypeVector());
  1565. BfIRValue useVal = val.mValue;
  1566. useVal = mBfIRBuilder->CreateBitCast(val.mValue, mBfIRBuilder->MapTypeInstPtr(checkBaseType));
  1567. if (isDynAlloc)
  1568. {
  1569. //
  1570. }
  1571. else if (condAlloca)
  1572. {
  1573. BF_ASSERT(!IsTargetingBeefBackend());
  1574. BF_ASSERT(!isDynAlloc);
  1575. auto valPtr = CreateAlloca(checkBaseType);
  1576. mBfIRBuilder->CreateStore(useVal, valPtr);
  1577. useVal = valPtr;
  1578. }
  1579. SizedArray<BfIRValue, 1> llvmArgs;
  1580. llvmArgs.push_back(useVal);
  1581. auto deferredCall = AddDeferredCall(dtorMethodInstance, llvmArgs, scopeData, refNode, true);
  1582. if (deferredCall != NULL)
  1583. {
  1584. deferredCall->mCastThis = (val.mType != checkBaseType) && (!isDynAlloc);
  1585. if (condAlloca)
  1586. deferredCall->mArgsNeedLoad = true;
  1587. }
  1588. hadDtorCall = true;
  1589. break;
  1590. }
  1591. checkBaseType = checkBaseType->mBaseType;
  1592. }
  1593. return;
  1594. }
  1595. //TODO: In the future we could be smarter about statically determining that our value hasn't escaped and eliding this
  1596. if (mayEscape)
  1597. {
  1598. // Is this worth it?
  1599. // if ((!IsOptimized()) && (val.mType->IsComposite()) && (!val.mType->IsValuelessType()) && (!mBfIRBuilder->mIgnoreWrites) && (!mCompiler->mIsResolveOnly))
  1600. // {
  1601. // auto nullPtrType = GetPrimitiveType(BfTypeCode_NullPtr);
  1602. // bool isDyn = mCurMethodState->mCurScope->IsDyn(scopeData);
  1603. // if (!isDyn)
  1604. // {
  1605. // int clearSize = val.mType->mSize;
  1606. // BfModuleMethodInstance dtorMethodInstance = GetInternalMethod("MemSet");
  1607. // BF_ASSERT(dtorMethodInstance.mMethodInstance != NULL);
  1608. // SizedArray<BfIRValue, 1> llvmArgs;
  1609. // llvmArgs.push_back(mBfIRBuilder->CreateBitCast(val.mValue, mBfIRBuilder->MapType(nullPtrType)));
  1610. // llvmArgs.push_back(GetConstValue8(0xDD));
  1611. // llvmArgs.push_back(GetConstValue(clearSize));
  1612. // llvmArgs.push_back(GetConstValue32(val.mType->mAlign));
  1613. // llvmArgs.push_back(mBfIRBuilder->CreateConst(BfTypeCode_Boolean, 0));
  1614. // AddDeferredCall(dtorMethodInstance, llvmArgs, scopeData, refNode, true);
  1615. // }
  1616. // else
  1617. // {
  1618. // const char* funcName = "SetDeleted1";
  1619. // if (val.mType->mSize >= 16)
  1620. // funcName = "SetDeleted16";
  1621. // else if (val.mType->mSize >= 8)
  1622. // funcName = "SetDeleted8";
  1623. // else if (val.mType->mSize >= 4)
  1624. // funcName = "SetDeleted4";
  1625. //
  1626. // BfModuleMethodInstance dtorMethodInstance = GetInternalMethod(funcName);
  1627. // BF_ASSERT(dtorMethodInstance.mMethodInstance != NULL);
  1628. // SizedArray<BfIRValue, 1> llvmArgs;
  1629. // llvmArgs.push_back(mBfIRBuilder->CreateBitCast(val.mValue, mBfIRBuilder->MapType(nullPtrType)));
  1630. // AddDeferredCall(dtorMethodInstance, llvmArgs, scopeData, refNode, true);
  1631. // }
  1632. // }
  1633. }
  1634. }
  1635. bool BfModule::TryLocalVariableInit(BfLocalVariable* localVar)
  1636. {
  1637. auto startTypeInstance = localVar->mResolvedType->ToTypeInstance();
  1638. if ((startTypeInstance == NULL) || (!startTypeInstance->IsStruct()))
  1639. return false;
  1640. auto checkTypeInstance = startTypeInstance;
  1641. while (checkTypeInstance != NULL)
  1642. {
  1643. for (auto& fieldInstance : checkTypeInstance->mFieldInstances)
  1644. {
  1645. if (fieldInstance.mMergedDataIdx != -1)
  1646. {
  1647. int64 checkMask = (int64)1 << fieldInstance.mMergedDataIdx;
  1648. if ((localVar->mUnassignedFieldFlags & checkMask) != 0)
  1649. {
  1650. // For fields added in extensions, we automatically initialize those if necessary
  1651. auto fieldDef = fieldInstance.GetFieldDef();
  1652. if (!fieldDef->mDeclaringType->IsExtension())
  1653. return false;
  1654. if ((fieldInstance.mDataIdx != -1) && (!mBfIRBuilder->mIgnoreWrites) && (!mCompiler->mIsResolveOnly))
  1655. {
  1656. auto curInsertBlock = mBfIRBuilder->GetInsertBlock();
  1657. mBfIRBuilder->SaveDebugLocation();
  1658. if (localVar->IsParam())
  1659. mBfIRBuilder->SetInsertPointAtStart(mCurMethodState->mIRInitBlock);
  1660. else
  1661. {
  1662. BF_ASSERT(localVar->mDeclBlock);
  1663. mBfIRBuilder->SetInsertPointAtStart(localVar->mDeclBlock);
  1664. }
  1665. mBfIRBuilder->ClearDebugLocation();
  1666. BfIRValue curVal;
  1667. if (localVar->mIsThis)
  1668. curVal = mBfIRBuilder->GetArgument(0);
  1669. else
  1670. curVal = localVar->mAddr;
  1671. auto subTypeInstance = startTypeInstance;
  1672. while (subTypeInstance != checkTypeInstance)
  1673. {
  1674. curVal = mBfIRBuilder->CreateInBoundsGEP(curVal, 0, 0);
  1675. subTypeInstance = subTypeInstance->mBaseType;
  1676. }
  1677. auto fieldPtr = mBfIRBuilder->CreateInBoundsGEP(curVal, 0, fieldInstance.mDataIdx);
  1678. auto defVal = GetDefaultValue(fieldInstance.mResolvedType);
  1679. auto storeInst = mBfIRBuilder->CreateStore(defVal, fieldPtr);
  1680. mBfIRBuilder->SetInsertPoint(curInsertBlock);
  1681. mBfIRBuilder->RestoreDebugLocation();
  1682. }
  1683. localVar->mUnassignedFieldFlags &= ~checkMask;
  1684. if (localVar->mUnassignedFieldFlags == 0)
  1685. localVar->mIsAssigned = true;
  1686. }
  1687. }
  1688. }
  1689. checkTypeInstance = checkTypeInstance->mBaseType;
  1690. }
  1691. return localVar->mIsAssigned;
  1692. }
  1693. void BfModule::LocalVariableDone(BfLocalVariable* localVar, bool isMethodExit)
  1694. {
  1695. //if (localVar->mAddr == NULL)
  1696. /*if ((localVar->mValue) && (!localVar->mAddr) && (IsTargetingBeefBackend()))
  1697. {
  1698. if ((!localVar->mValue.IsConst()) && (!localVar->mValue.IsArg()) && (!localVar->mValue.IsFake()))
  1699. {
  1700. if (mCurMethodInstance->mMethodDef->mName == "FuncA")
  1701. mBfIRBuilder->CreateLifetimeEnd(localVar->mValue);
  1702. }
  1703. }*/
  1704. BfAstNode* localNameNode = localVar->mNameNode;
  1705. if (localVar->mIsThis)
  1706. {
  1707. localNameNode = mCurMethodInstance->mMethodDef->GetRefNode();
  1708. }
  1709. if (localNameNode != NULL)
  1710. {
  1711. bool isOut = false;
  1712. if (localVar->mResolvedType->IsRef())
  1713. {
  1714. auto refType = (BfRefType*)localVar->mResolvedType;
  1715. isOut = refType->mRefKind == BfRefType::RefKind_Out;
  1716. }
  1717. if ((localVar->mReadFromId == -1) || (isOut) || ((localVar->mIsThis) && (mCurTypeInstance->IsStruct())))
  1718. {
  1719. if ((!localVar->mIsAssigned) & (localVar->IsParam()))
  1720. TryLocalVariableInit(localVar);
  1721. // We may skip processing of local methods, so we won't know if it bind to any of our local variables or not
  1722. bool deferFullAnalysis = mCurMethodState->GetRootMethodState()->mLocalMethodCache.size() != 0;
  1723. //bool deferFullAnalysis = true;
  1724. bool deferUsageWarning = deferFullAnalysis && mCompiler->IsAutocomplete();
  1725. if (!localVar->mIsAssigned)
  1726. {
  1727. if (deferUsageWarning)
  1728. {
  1729. // Ignore
  1730. }
  1731. else if (localVar->mIsThis)
  1732. {
  1733. bool foundFields = false;
  1734. auto checkTypeInstance = mCurTypeInstance;
  1735. while (checkTypeInstance != NULL)
  1736. {
  1737. for (auto& fieldInstance : checkTypeInstance->mFieldInstances)
  1738. {
  1739. if (fieldInstance.mMergedDataIdx != -1)
  1740. {
  1741. int checkMask = 1 << fieldInstance.mMergedDataIdx;
  1742. if ((localVar->mUnassignedFieldFlags & checkMask) != 0)
  1743. {
  1744. auto fieldDef = fieldInstance.GetFieldDef();
  1745. if (fieldDef->mProtection != BfProtection_Hidden)
  1746. {
  1747. if (checkTypeInstance == mCurTypeInstance)
  1748. {
  1749. Fail(StrFormat("Field '%s' must be fully assigned before control is returned to the caller",
  1750. fieldDef->mName.c_str()), localNameNode, deferFullAnalysis); // 0171
  1751. }
  1752. else
  1753. {
  1754. Fail(StrFormat("Field '%s.%s' must be fully assigned before control is returned to the caller",
  1755. TypeToString(checkTypeInstance).c_str(),
  1756. fieldDef->mName.c_str()), localNameNode, deferFullAnalysis); // 0171
  1757. }
  1758. }
  1759. foundFields = true;
  1760. }
  1761. }
  1762. }
  1763. checkTypeInstance = checkTypeInstance->mBaseType;
  1764. }
  1765. if (!foundFields)
  1766. {
  1767. if (mCurTypeInstance->mInstSize > 0)
  1768. Fail(StrFormat("The variable '%s' must be fully assigned to before control leaves the current method", localVar->mName.c_str()), localNameNode); // 0177
  1769. }
  1770. }
  1771. else if (localVar->IsParam())
  1772. Fail(StrFormat("The out parameter '%s' must be assigned to before control leaves the current method", localVar->mName.c_str()), localNameNode, deferFullAnalysis); // 0177
  1773. else if (!deferUsageWarning)
  1774. Warn(BfWarning_CS0168_VariableDeclaredButNeverUsed, StrFormat("The variable '%s' is declared but never used", localVar->mName.c_str()), localNameNode, deferFullAnalysis);
  1775. }
  1776. else if ((localVar->mReadFromId == -1) && (!localVar->IsParam()) && (!deferUsageWarning))
  1777. Warn(BfWarning_CS0168_VariableDeclaredButNeverUsed, StrFormat("The variable '%s' is assigned but its value is never used", localVar->mName.c_str()), localNameNode, deferFullAnalysis);
  1778. }
  1779. }
  1780. }
  1781. void BfModule::MarkDynStack(BfScopeData* scopeData)
  1782. {
  1783. auto checkScope = mCurMethodState->mCurScope;
  1784. while (true)
  1785. {
  1786. if (checkScope == scopeData)
  1787. break;
  1788. checkScope->mHadOuterDynStack = true;
  1789. checkScope = checkScope->mPrevScope;
  1790. }
  1791. }
  1792. void BfModule::SaveStackState(BfScopeData* scopeData)
  1793. {
  1794. // If we push a value on the stack that needs to survive until the end of scopeData, we need to make sure that no
  1795. // scopes within scopeData restore the stack
  1796. auto checkScope = mCurMethodState->mCurScope;
  1797. while (true)
  1798. {
  1799. if (checkScope == scopeData)
  1800. {
  1801. if ((!checkScope->mSavedStack) && (checkScope->mBlock) && (!checkScope->mIsScopeHead) && (!checkScope->mHadOuterDynStack))
  1802. {
  1803. if (mBfIRBuilder->mHasDebugInfo)
  1804. mBfIRBuilder->SaveDebugLocation();
  1805. auto prevPos = mBfIRBuilder->GetInsertBlock();
  1806. mBfIRBuilder->SetInsertPointAtStart(checkScope->mBlock);
  1807. checkScope->mSavedStack = mBfIRBuilder->CreateStackSave();
  1808. mBfIRBuilder->ClearDebugLocation(checkScope->mSavedStack);
  1809. mBfIRBuilder->SetInsertPoint(prevPos);
  1810. if (mBfIRBuilder->mHasDebugInfo)
  1811. mBfIRBuilder->RestoreDebugLocation();
  1812. }
  1813. break;
  1814. }
  1815. if (checkScope->mSavedStack)
  1816. {
  1817. for (auto usage : checkScope->mSavedStackUses)
  1818. mBfIRBuilder->EraseInstFromParent(usage);
  1819. checkScope->mSavedStackUses.Clear();
  1820. mBfIRBuilder->EraseInstFromParent(checkScope->mSavedStack);
  1821. checkScope->mSavedStack = BfIRValue();
  1822. }
  1823. checkScope = checkScope->mPrevScope;
  1824. }
  1825. }
  1826. BfIRValue BfModule::ValueScopeStart()
  1827. {
  1828. if (IsTargetingBeefBackend())
  1829. return mBfIRBuilder->CreateValueScopeStart();
  1830. return BfIRValue();
  1831. }
  1832. void BfModule::ValueScopeEnd(BfIRValue valueScopeStart)
  1833. {
  1834. if (valueScopeStart)
  1835. mBfIRBuilder->CreateValueScopeHardEnd(valueScopeStart);
  1836. }
  1837. BfFileInstance* BfModule::GetFileFromNode(BfAstNode* astNode)
  1838. {
  1839. auto bfParser = astNode->GetSourceData()->ToParserData();
  1840. if (bfParser == NULL)
  1841. return NULL;
  1842. BfFileInstance** fileInstancePtr = NULL;
  1843. if (!mFileInstanceMap.TryAdd(bfParser, NULL, &fileInstancePtr))
  1844. {
  1845. return *fileInstancePtr;
  1846. }
  1847. else
  1848. {
  1849. // It's possible two parsers have the same file name (ie: mNextRevision)
  1850. BfFileInstance** namedFileInstancePtr = NULL;
  1851. if (!mNamedFileInstanceMap.TryAdd(bfParser->mFileName, NULL, &namedFileInstancePtr))
  1852. {
  1853. auto bfFileInstance = *namedFileInstancePtr;
  1854. *fileInstancePtr = bfFileInstance;
  1855. return bfFileInstance;
  1856. }
  1857. int slashPos = (int)bfParser->mFileName.LastIndexOf(DIR_SEP_CHAR);
  1858. auto bfFileInstance = new BfFileInstance();
  1859. *fileInstancePtr = bfFileInstance;
  1860. *namedFileInstancePtr = bfFileInstance;
  1861. bfFileInstance->mPrevPosition.mFileInstance = bfFileInstance;
  1862. bfFileInstance->mParser = bfParser;
  1863. BfLogSysM("GetFileFromNode new file. Mod: %p FileInstance: %p Parser: %p\n", this, bfFileInstance, bfParser);
  1864. if ((mBfIRBuilder != NULL) && (mBfIRBuilder->DbgHasInfo()))
  1865. {
  1866. String fileName = bfParser->mFileName;
  1867. for (int i = 0; i < (int)fileName.length(); i++)
  1868. {
  1869. if (fileName[i] == DIR_SEP_CHAR_ALT)
  1870. fileName[i] = DIR_SEP_CHAR;
  1871. }
  1872. bfFileInstance->mDIFile = mBfIRBuilder->DbgCreateFile(fileName.Substring(slashPos + 1), fileName.Substring(0, slashPos));
  1873. }
  1874. return bfFileInstance;
  1875. }
  1876. }
  1877. void BfModule::UpdateSrcPos(BfAstNode* astNode, BfSrcPosFlags flags, int debugLocOffset)
  1878. {
  1879. // We set force to true when we MUST get the line position set (for navigation purposes, for example)
  1880. if (((mBfIRBuilder->mIgnoreWrites)) && ((flags & BfSrcPosFlag_Force) == 0))
  1881. return;
  1882. BF_ASSERT((!mAwaitingInitFinish) || (mBfIRBuilder->mIgnoreWrites));
  1883. if (astNode == NULL)
  1884. return;
  1885. auto bfParser = astNode->GetSourceData()->ToParserData();
  1886. if (bfParser == NULL)
  1887. return;
  1888. if ((mCurFilePosition.mFileInstance == NULL) || (mCurFilePosition.mFileInstance->mParser != bfParser))
  1889. {
  1890. if (mCurFilePosition.mFileInstance != NULL)
  1891. {
  1892. BF_ASSERT(mFileInstanceMap.GetCount() != 0);
  1893. mCurFilePosition.mFileInstance->mPrevPosition = mCurFilePosition;
  1894. }
  1895. auto bfFileInstance = GetFileFromNode(astNode);
  1896. if (bfFileInstance->mPrevPosition.mFileInstance != NULL)
  1897. {
  1898. mCurFilePosition = bfFileInstance->mPrevPosition;
  1899. }
  1900. else
  1901. {
  1902. mCurFilePosition.mFileInstance = bfFileInstance;
  1903. mCurFilePosition.mCurLine = 0;
  1904. mCurFilePosition.mCurSrcPos = 0;
  1905. }
  1906. }
  1907. int srcPos = astNode->GetSrcStart() + debugLocOffset;
  1908. BF_ASSERT(srcPos < bfParser->mSrcLength);
  1909. auto* jumpEntry = bfParser->mJumpTable + (srcPos / PARSER_JUMPTABLE_DIVIDE);
  1910. if (jumpEntry->mCharIdx > srcPos)
  1911. jumpEntry--;
  1912. mCurFilePosition.mCurLine = jumpEntry->mLineNum;
  1913. mCurFilePosition.mCurSrcPos = jumpEntry->mCharIdx;
  1914. mCurFilePosition.mCurColumn = 0;
  1915. while (mCurFilePosition.mCurSrcPos < srcPos)
  1916. {
  1917. if (bfParser->mSrc[mCurFilePosition.mCurSrcPos] == '\n')
  1918. {
  1919. mCurFilePosition.mCurLine++;
  1920. mCurFilePosition.mCurColumn = 0;
  1921. }
  1922. else
  1923. {
  1924. mCurFilePosition.mCurColumn++;
  1925. }
  1926. mCurFilePosition.mCurSrcPos++;
  1927. }
  1928. //TODO: if we bail on the "mCurMethodState == NULL" case then we don't get it set during type declarations
  1929. if (((flags & BfSrcPosFlag_NoSetDebugLoc) == 0) && (mBfIRBuilder->DbgHasInfo()) && (mCurMethodState != NULL))
  1930. {
  1931. int column = mCurFilePosition.mCurColumn + 1;
  1932. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend))
  1933. {
  1934. // Set to illegal position
  1935. column = 0;
  1936. }
  1937. if (mSetIllegalSrcPosition)
  1938. column = 0;
  1939. BfIRMDNode useDIScope = mCurMethodState->mCurScope->mDIScope;
  1940. auto wantDIFile = mCurFilePosition.mFileInstance->mDIFile;
  1941. if ((wantDIFile != mCurMethodState->mDIFile) && (mCurMethodState->mDIFile))
  1942. {
  1943. // This is from a different scope...
  1944. if (wantDIFile != mCurMethodState->mCurScope->mAltDIFile)
  1945. {
  1946. mCurMethodState->mCurScope->mAltDIFile = wantDIFile;
  1947. mCurMethodState->mCurScope->mAltDIScope = mBfIRBuilder->DbgCreateLexicalBlock(mCurMethodState->mCurScope->mDIScope, wantDIFile, mCurFilePosition.mCurLine + 1, column);
  1948. }
  1949. if (mCurMethodState->mCurScope->mAltDIScope) // This may not be set if mAltDIFile is set by a mixin
  1950. useDIScope = mCurMethodState->mCurScope->mAltDIScope;
  1951. }
  1952. else
  1953. {
  1954. if (mCurMethodState->mCurScope->mAltDIFile)
  1955. {
  1956. mCurMethodState->mCurScope->mAltDIFile = BfIRMDNode();
  1957. mCurMethodState->mCurScope->mAltDIScope = BfIRMDNode();
  1958. }
  1959. }
  1960. auto inlineAt = mCurMethodState->mCurScope->mDIInlinedAt;
  1961. if (mCurMethodState->mCrossingMixin)
  1962. inlineAt = BfIRMDNode();
  1963. mBfIRBuilder->SetCurrentDebugLocation(mCurFilePosition.mCurLine + 1, column, useDIScope, inlineAt);
  1964. if ((flags & BfSrcPosFlag_Expression) == 0)
  1965. mBfIRBuilder->CreateStatementStart();
  1966. }
  1967. }
  1968. void BfModule::UpdateExprSrcPos(BfAstNode* astNode, BfSrcPosFlags flags)
  1969. {
  1970. // We've turned off expr src pos (for now?)
  1971. //UpdateSrcPos(astNode, (BfSrcPosFlags)(flags | BfSrcPosFlag_Expression));
  1972. }
  1973. void BfModule::UseDefaultSrcPos(BfSrcPosFlags flags, int debugLocOffset)
  1974. {
  1975. UpdateSrcPos(mCompiler->mBfObjectTypeDef->mTypeDeclaration, flags, debugLocOffset);
  1976. }
  1977. void BfModule::SetIllegalSrcPos(BfSrcPosFlags flags)
  1978. {
  1979. if ((mBfIRBuilder->DbgHasInfo()) && (mCurMethodState != NULL))
  1980. {
  1981. if ((mCurMethodState->mCurScope->mDIInlinedAt) && (mCompiler->mOptions.IsCodeView()))
  1982. {
  1983. // Currently, CodeView does not record column positions so we can't use an illegal column position as an "invalid" marker
  1984. mBfIRBuilder->SetCurrentDebugLocation(0, 0, mCurMethodState->mCurScope->mDIScope, mCurMethodState->mCurScope->mDIInlinedAt);
  1985. }
  1986. else
  1987. {
  1988. // Set to whatever it previously was but at column zero, which we will know to be illegal
  1989. mBfIRBuilder->SetCurrentDebugLocation(mCurFilePosition.mCurLine + 1, 0, mCurMethodState->mCurScope->mDIScope, mCurMethodState->mCurScope->mDIInlinedAt);
  1990. }
  1991. if ((flags & BfSrcPosFlag_Expression) == 0)
  1992. mBfIRBuilder->CreateStatementStart();
  1993. }
  1994. }
  1995. void BfModule::SetIllegalExprSrcPos(BfSrcPosFlags flags)
  1996. {
  1997. // We've turned off expr src pos (for now?)
  1998. //SetIllegalSrcPos((BfSrcPosFlags)(flags | BfSrcPosFlag_Expression));
  1999. }
  2000. bool BfModule::CheckProtection(BfProtection protection, bool allowProtected, bool allowPrivate)
  2001. {
  2002. if ((protection == BfProtection_Public) ||
  2003. ((protection == BfProtection_Protected) && (allowProtected)) ||
  2004. ((protection == BfProtection_Private) && (allowPrivate)))
  2005. return true;
  2006. if ((mAttributeState != NULL) && (mAttributeState->mCustomAttributes != NULL) && (mAttributeState->mCustomAttributes->Contains(mCompiler->mFriendAttributeTypeDef)))
  2007. return true;
  2008. return false;
  2009. }
  2010. void BfModule::GetAccessAllowed(BfTypeInstance* checkType, bool &allowProtected, bool &allowPrivate)
  2011. {
  2012. allowPrivate = (checkType == mCurTypeInstance) || (IsInnerType(mCurTypeInstance, checkType));
  2013. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL))
  2014. {
  2015. auto mixinOwner = mCurMethodState->mMixinState->mMixinMethodInstance->GetOwner();
  2016. allowPrivate |= (checkType == mixinOwner) || (IsInnerType(mixinOwner, checkType));
  2017. }
  2018. allowProtected = allowPrivate;
  2019. }
  2020. bool BfModule::CheckProtection(BfProtectionCheckFlags& flags, BfTypeInstance* memberOwner, BfProtection memberProtection, BfTypeInstance* lookupStartType)
  2021. {
  2022. if (memberProtection == BfProtection_Hidden)
  2023. return false;
  2024. if (memberProtection == BfProtection_Public)
  2025. return true;
  2026. if ((flags & BfProtectionCheckFlag_CheckedPrivate) == 0)
  2027. {
  2028. BfTypeInstance* curCheckType = mCurTypeInstance;
  2029. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL))
  2030. {
  2031. auto mixinOwner = mCurMethodState->mMixinState->mMixinMethodInstance->GetOwner();
  2032. curCheckType = mixinOwner;
  2033. }
  2034. bool allowPrivate = (memberOwner->mTypeDef == curCheckType->mTypeDef) || (IsInnerType(curCheckType->mTypeDef, memberOwner->mTypeDef));
  2035. if (allowPrivate)
  2036. flags = (BfProtectionCheckFlags)(flags | BfProtectionCheckFlag_AllowPrivate | BfProtectionCheckFlag_CheckedPrivate);
  2037. else
  2038. flags = (BfProtectionCheckFlags)(flags | BfProtectionCheckFlag_CheckedPrivate);
  2039. }
  2040. if ((flags & BfProtectionCheckFlag_AllowPrivate) != 0)
  2041. return true;
  2042. if (memberProtection == BfProtection_Protected)
  2043. {
  2044. if ((flags & BfProtectionCheckFlag_CheckedProtected) == 0)
  2045. {
  2046. bool allowProtected = false;
  2047. auto memberOwnerTypeDef = memberOwner->mTypeDef;
  2048. auto curCheckType = mCurTypeInstance;
  2049. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL))
  2050. {
  2051. auto mixinOwner = mCurMethodState->mMixinState->mMixinMethodInstance->GetOwner();
  2052. curCheckType = mixinOwner;
  2053. }
  2054. auto lookupCheckType = lookupStartType;
  2055. while (lookupCheckType->mInheritDepth >= curCheckType->mInheritDepth)
  2056. {
  2057. if (lookupCheckType == curCheckType)
  2058. {
  2059. allowProtected = true;
  2060. break;
  2061. }
  2062. if (lookupCheckType == memberOwner)
  2063. break;
  2064. lookupCheckType = lookupCheckType->mBaseType;
  2065. if (lookupCheckType == NULL)
  2066. break;
  2067. }
  2068. if (!allowProtected)
  2069. {
  2070. // It's possible our outer type is derived from 'memberOwner'
  2071. while (curCheckType->mTypeDef->mNestDepth > 0)
  2072. {
  2073. curCheckType = GetOuterType(curCheckType);
  2074. if (curCheckType == NULL)
  2075. break;
  2076. auto lookupCheckType = lookupStartType;
  2077. while (lookupCheckType->mInheritDepth >= curCheckType->mInheritDepth)
  2078. {
  2079. if (lookupCheckType == curCheckType)
  2080. {
  2081. allowProtected = true;
  2082. break;
  2083. }
  2084. if (lookupCheckType == memberOwner)
  2085. break;
  2086. lookupCheckType = lookupCheckType->mBaseType;
  2087. if (lookupCheckType == NULL)
  2088. break;
  2089. }
  2090. }
  2091. }
  2092. if (allowProtected)
  2093. flags = (BfProtectionCheckFlags)(flags | BfProtectionCheckFlag_CheckedProtected | BfProtectionCheckFlag_AllowProtected);
  2094. else
  2095. flags = (BfProtectionCheckFlags)(flags | BfProtectionCheckFlag_CheckedProtected);
  2096. }
  2097. if ((flags & BfProtectionCheckFlag_AllowProtected) != 0)
  2098. return true;
  2099. }
  2100. if ((mAttributeState != NULL) && (mAttributeState->mCustomAttributes != NULL) && (mAttributeState->mCustomAttributes->Contains(mCompiler->mFriendAttributeTypeDef)))
  2101. return true;
  2102. return false;
  2103. }
  2104. void BfModule::SetElementType(BfAstNode* astNode, BfSourceElementType elementType)
  2105. {
  2106. if ((mCompiler->mResolvePassData != NULL) &&
  2107. (mCompiler->mResolvePassData->mSourceClassifier != NULL) &&
  2108. (astNode->IsFromParser( mCompiler->mResolvePassData->mParser)))
  2109. {
  2110. mCompiler->mResolvePassData->mSourceClassifier->SetElementType(astNode, elementType);
  2111. }
  2112. }
  2113. void BfModule::SetHadVarUsage()
  2114. {
  2115. mHadVarUsage = true;
  2116. mHadBuildError = true;
  2117. }
  2118. BfError* BfModule::Fail(const StringImpl& error, BfAstNode* refNode, bool isPersistent)
  2119. {
  2120. BP_ZONE("BfModule::Fail");
  2121. if (mIgnoreErrors)
  2122. {
  2123. mHadIgnoredError = true;
  2124. return NULL;
  2125. }
  2126. if (!mReportErrors)
  2127. {
  2128. mCompiler->mPassInstance->SilentFail();
  2129. return NULL;
  2130. }
  2131. if (refNode != NULL)
  2132. refNode = BfNodeToNonTemporary(refNode);
  2133. //BF_ASSERT(refNode != NULL);
  2134. if (mCurMethodInstance != NULL)
  2135. mCurMethodInstance->mHasFailed = true;
  2136. if ((mCurTypeInstance != NULL) && (mCurTypeInstance->IsUnspecializedTypeVariation()))
  2137. return NULL;
  2138. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mIsUnspecializedVariation))
  2139. return NULL; // Ignore errors on unspecialized variations, they are always dups
  2140. if (!mHadBuildError)
  2141. mHadBuildError = true;
  2142. if (mParentModule != NULL)
  2143. mParentModule->mHadBuildError = true;
  2144. if (mCurTypeInstance != NULL)
  2145. AddFailType(mCurTypeInstance);
  2146. BfLogSysM("BfModule::Fail module %p type %p %s\n", this, mCurTypeInstance, error.c_str());
  2147. String errorString = error;
  2148. bool isWhileSpecializing = false;
  2149. bool isWhileSpecializingMethod = false;
  2150. if ((mIsSpecialModule) && (mModuleName == "vdata"))
  2151. errorString += StrFormat("\n while generating vdata for project '%s'", mProject->mName.c_str());
  2152. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend))
  2153. errorString += StrFormat("\n while generating append size calculating method");
  2154. else if (refNode == NULL)
  2155. {
  2156. if (mCurTypeInstance != NULL)
  2157. errorString += StrFormat("\n while compiling '%s'", TypeToString(mCurTypeInstance, BfTypeNameFlags_None).c_str());
  2158. else if (mProject != NULL)
  2159. errorString += StrFormat("\n while compiling project '%s'", mProject->mName.c_str());
  2160. }
  2161. if ((mCurTypeInstance != NULL) && (mCurMethodState != NULL))
  2162. {
  2163. auto checkMethodState = mCurMethodState;
  2164. while (checkMethodState != NULL)
  2165. {
  2166. auto methodInstance = checkMethodState->mMethodInstance;
  2167. if (methodInstance == NULL)
  2168. {
  2169. checkMethodState = checkMethodState->mPrevMethodState;
  2170. continue;
  2171. }
  2172. // Propogatea the fail all the way to the main method (assuming we're in a local method or lambda)
  2173. methodInstance->mHasFailed = true;
  2174. bool isSpecializedMethod = ((methodInstance != NULL) && (!methodInstance->mIsUnspecialized) && (methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mMethodGenericArguments.size() != 0));
  2175. if (isSpecializedMethod)
  2176. {
  2177. //auto unspecializedMethod = &mCurMethodInstance->mMethodInstanceGroup->mMethodSpecializationMap.begin()->second;
  2178. auto unspecializedMethod = methodInstance->mMethodInstanceGroup->mDefault;
  2179. if (unspecializedMethod->mHasFailed)
  2180. return NULL; // At least SOME error has already been reported
  2181. }
  2182. if (isSpecializedMethod)
  2183. {
  2184. errorString += StrFormat("\n while specializing method '%s'", MethodToString(methodInstance).c_str());
  2185. isWhileSpecializing = true;
  2186. isWhileSpecializingMethod = true;
  2187. }
  2188. else if ((methodInstance != NULL) && (methodInstance->mIsForeignMethodDef))
  2189. {
  2190. errorString += StrFormat("\n while implementing default interface method '%s'", MethodToString(methodInstance).c_str());
  2191. isWhileSpecializing = true;
  2192. isWhileSpecializingMethod = true;
  2193. }
  2194. else if ((mCurTypeInstance->IsGenericTypeInstance()) && (!mCurTypeInstance->IsUnspecializedType()))
  2195. {
  2196. errorString += StrFormat("\n while specializing type '%s'", TypeToString(mCurTypeInstance).c_str());
  2197. isWhileSpecializing = true;
  2198. }
  2199. checkMethodState = checkMethodState->mPrevMethodState;
  2200. }
  2201. // Keep in mind that all method specializations with generic type instances as its method generic params
  2202. // need to be deferred because the specified generic type instance might get deleted at the end of the
  2203. // compilation due to no longer having indirect references removed, and we have to ignore errors from
  2204. // those method specializations if that occurs
  2205. if (isWhileSpecializing)
  2206. {
  2207. BfError* bfError = mCompiler->mPassInstance->DeferFail(errorString, refNode);
  2208. if (bfError != NULL)
  2209. bfError->mIsWhileSpecializing = isWhileSpecializing;
  2210. return bfError;
  2211. }
  2212. }
  2213. if (!mHadBuildError)
  2214. mHadBuildError = true;
  2215. // Check mixins
  2216. {
  2217. auto checkMethodInstance = mCurMethodState;
  2218. while (checkMethodInstance != NULL)
  2219. {
  2220. auto rootMixinState = checkMethodInstance->GetRootMixinState();
  2221. if (rootMixinState != NULL)
  2222. {
  2223. BfError* bfError = mCompiler->mPassInstance->Fail(StrFormat("Failed to inject mixin '%s'", MethodToString(rootMixinState->mMixinMethodInstance).c_str()), rootMixinState->mSource);
  2224. mCompiler->mPassInstance->MoreInfo(errorString, refNode);
  2225. auto mixinState = checkMethodInstance->mMixinState;
  2226. while ((mixinState != NULL) && (mixinState->mPrevMixinState != NULL))
  2227. {
  2228. mCompiler->mPassInstance->MoreInfo(StrFormat("Injected from mixin '%s'", MethodToString(mixinState->mPrevMixinState->mMixinMethodInstance).c_str()), mixinState->mSource);
  2229. mixinState = mixinState->mPrevMixinState;
  2230. }
  2231. return bfError;
  2232. }
  2233. checkMethodInstance = checkMethodInstance->mPrevMethodState;
  2234. }
  2235. }
  2236. BfError* bfError = NULL;
  2237. if (refNode == NULL)
  2238. bfError = mCompiler->mPassInstance->Fail(errorString);
  2239. else
  2240. {
  2241. bfError = mCompiler->mPassInstance->Fail(errorString, refNode);
  2242. }
  2243. if (bfError != NULL)
  2244. {
  2245. bfError->mIsPersistent = isPersistent;
  2246. bfError->mIsWhileSpecializing = isWhileSpecializing;
  2247. if ((mCurMethodState != NULL) && (mCurMethodState->mDeferredCallEmitState != NULL) && (mCurMethodState->mDeferredCallEmitState->mCloseNode != NULL))
  2248. mCompiler->mPassInstance->MoreInfo("Error during deferred statement handling", mCurMethodState->mDeferredCallEmitState->mCloseNode);
  2249. }
  2250. return bfError;
  2251. }
  2252. BfError* BfModule::FailAfter(const StringImpl& error, BfAstNode* refNode)
  2253. {
  2254. if (mIgnoreErrors)
  2255. return NULL;
  2256. if (refNode != NULL)
  2257. refNode = BfNodeToNonTemporary(refNode);
  2258. mHadBuildError = true;
  2259. return mCompiler->mPassInstance->FailAfter(error, refNode);
  2260. }
  2261. BfError* BfModule::Warn(int warningNum, const StringImpl& warning, BfAstNode* refNode, bool isPersistent)
  2262. {
  2263. if (mIgnoreErrors || mIgnoreWarnings)
  2264. return NULL;
  2265. if (!mReportErrors)
  2266. {
  2267. mCompiler->mPassInstance->SilentFail();
  2268. return NULL;
  2269. }
  2270. BfAstNode* unwarnNode = refNode;
  2271. //
  2272. {
  2273. BfParentNodeEntry* parentNodeEntry = mParentNodeEntry;
  2274. while (parentNodeEntry != NULL)
  2275. {
  2276. if (auto block = BfNodeDynCast<BfBlock>(parentNodeEntry->mNode))
  2277. break;
  2278. unwarnNode = parentNodeEntry->mNode;
  2279. parentNodeEntry = parentNodeEntry->mPrev;
  2280. }
  2281. }
  2282. auto parser = unwarnNode->GetSourceData()->ToParserData();
  2283. if ((parser != NULL) && (parser->IsUnwarnedAt(unwarnNode)))
  2284. {
  2285. return NULL;
  2286. }
  2287. // Right now we're only warning on the unspecialized declarations, we may revisit this
  2288. if (mCurMethodInstance != NULL)
  2289. {
  2290. if (mCurMethodInstance->IsSpecializedGenericMethodOrType())
  2291. return NULL;
  2292. if (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend)
  2293. return NULL; // No ctorCalcAppend warnings
  2294. }
  2295. if ((mCurTypeInstance != NULL) && (mCurTypeInstance->IsSpecializedType()))
  2296. return NULL;
  2297. if (refNode != NULL)
  2298. refNode = BfNodeToNonTemporary(refNode);
  2299. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL))
  2300. {
  2301. // We used to bubble up warnings into the mixin injection site, BUT
  2302. // we are now assuming any relevant warnings will be given at the declaration site
  2303. return NULL;
  2304. // AddFailType(mCurTypeInstance);
  2305. //
  2306. // BfError* bfError = mCompiler->mPassInstance->Warn(warningNum, "Warning while injecting mixin", mCurMethodState->mMixinState->GetRoot()->mSource);
  2307. // if (bfError == NULL)
  2308. // return NULL;
  2309. // mHadBuildWarning = true;
  2310. // return mCompiler->mPassInstance->MoreInfo(warning, refNode);
  2311. }
  2312. BfError* bfError = mCompiler->mPassInstance->WarnAt(warningNum, warning, refNode->GetSourceData(), refNode->GetSrcStart(), refNode->GetSrcLength());
  2313. if (bfError != NULL)
  2314. {
  2315. AddFailType(mCurTypeInstance);
  2316. mHadBuildWarning = true;
  2317. bfError->mIsPersistent = isPersistent;
  2318. if ((mCompiler->IsAutocomplete()) && (mCompiler->mResolvePassData->mAutoComplete->CheckFixit((refNode))))
  2319. {
  2320. BfParserData* parser = refNode->GetSourceData()->ToParserData();
  2321. if (parser != NULL)
  2322. {
  2323. int fileLoc = BfFixitFinder::FindLineStartBefore(refNode);
  2324. mCompiler->mResolvePassData->mAutoComplete->AddEntry(AutoCompleteEntry("fixit", StrFormat("#unwarn\tunwarn|%s|%d|#unwarn|", parser->mFileName.c_str(), fileLoc).c_str()));
  2325. }
  2326. }
  2327. }
  2328. return bfError;
  2329. }
  2330. void BfModule::CheckRangeError(BfType* type, BfAstNode* refNode)
  2331. {
  2332. if (mBfIRBuilder->mOpFailed)
  2333. Fail(StrFormat("Result out of range for type '%s'", TypeToString(type).c_str()), refNode);
  2334. }
  2335. void BfModule::NotImpl(BfAstNode* astNode)
  2336. {
  2337. Fail("INTERNAL ERROR: Not implemented", astNode);
  2338. }
  2339. bool BfModule::CheckAccessMemberProtection(BfProtection protection, BfType* memberType)
  2340. {
  2341. bool allowPrivate = (memberType == mCurTypeInstance) || (IsInnerType(mCurTypeInstance, memberType));
  2342. if (!allowPrivate)
  2343. allowPrivate |= memberType->IsInterface();
  2344. bool allowProtected = allowPrivate;// allowPrivate || TypeIsSubTypeOf(mCurTypeInstance, memberType->ToTypeInstance());
  2345. if (!CheckProtection(protection, allowProtected, allowPrivate))
  2346. {
  2347. return false;
  2348. }
  2349. return true;
  2350. }
  2351. bool BfModule::CheckDefineMemberProtection(BfProtection protection, BfType* memberType)
  2352. {
  2353. // Use 'min' - exporting a 'public' from a 'private' class is really just 'private' still
  2354. protection = std::min(protection, mCurTypeInstance->mTypeDef->mProtection);
  2355. auto memberTypeInstance = memberType->ToTypeInstance();
  2356. if (memberTypeInstance == NULL)
  2357. {
  2358. auto underlyingType = memberType->GetUnderlyingType();
  2359. if (underlyingType != NULL)
  2360. return CheckDefineMemberProtection(protection, underlyingType);
  2361. return true;
  2362. }
  2363. if (memberTypeInstance->mTypeDef->mProtection < protection)
  2364. return false;
  2365. if (memberTypeInstance->IsGenericTypeInstance())
  2366. {
  2367. // When we're a generic struct, our data layout can depend on our generic parameters as well
  2368. auto genericTypeInstance = (BfGenericTypeInstance*) memberTypeInstance;
  2369. for (auto typeGenericArg : genericTypeInstance->mTypeGenericArguments)
  2370. {
  2371. if (!CheckDefineMemberProtection(protection, typeGenericArg))
  2372. return false;
  2373. }
  2374. }
  2375. return true;
  2376. }
  2377. void BfModule::AddDependency(BfType* usedType, BfType* usingType, BfDependencyMap::DependencyDependencyFlag flags)
  2378. {
  2379. if (usedType == usingType)
  2380. return;
  2381. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mIsAutocompleteMethod))
  2382. return;
  2383. if (usedType->IsSpecializedByAutoCompleteMethod())
  2384. return;
  2385. if ((mCurMethodState != NULL) && (mCurMethodState->mHotDataReferenceBuilder != NULL) && (usedType != mCurTypeInstance) &&
  2386. ((flags & (BfDependencyMap::DependencyFlag_ReadFields | BfDependencyMap::DependencyFlag_LocalUsage | BfDependencyMap::DependencyFlag_Allocates)) != 0))
  2387. {
  2388. bool addType = true;
  2389. auto checkType = usedType;
  2390. while (true)
  2391. {
  2392. if ((checkType->IsPointer()) || (checkType->IsRef()) || (checkType->IsSizedArray()))
  2393. checkType = checkType->GetUnderlyingType();
  2394. else if (checkType->IsArray())
  2395. {
  2396. checkType = ((BfGenericTypeInstance*)checkType)->mTypeGenericArguments[0];
  2397. }
  2398. else
  2399. break;
  2400. }
  2401. PopulateType(checkType, BfPopulateType_Data);
  2402. if (checkType->IsValuelessType())
  2403. addType = false;
  2404. else if (checkType->IsPrimitiveType())
  2405. addType = false;
  2406. else
  2407. {
  2408. auto checkTypeInst = checkType->ToTypeInstance();
  2409. if (checkTypeInst == NULL)
  2410. {
  2411. addType = false;
  2412. }
  2413. else
  2414. {
  2415. if (TypeIsSubTypeOf(mCurTypeInstance, checkTypeInst))
  2416. addType = false;
  2417. }
  2418. }
  2419. if (addType)
  2420. {
  2421. auto checkTypeInst = checkType->ToTypeInstance();
  2422. auto hotTypeVersion = checkTypeInst->mHotTypeData->GetLatestVersion();
  2423. BF_ASSERT(hotTypeVersion != NULL);
  2424. bool isAllocation = ((flags & BfDependencyMap::DependencyFlag_Allocates) != 0);
  2425. if (((flags & BfDependencyMap::DependencyFlag_LocalUsage) != 0) &&
  2426. (checkType->IsComposite()))
  2427. isAllocation = true;
  2428. if (isAllocation)
  2429. {
  2430. mCurMethodState->mHotDataReferenceBuilder->mAllocatedData.Add(hotTypeVersion);
  2431. }
  2432. else
  2433. mCurMethodState->mHotDataReferenceBuilder->mUsedData.Add(hotTypeVersion);
  2434. }
  2435. }
  2436. //BP_ZONE("BfModule::AddDependency");
  2437. /*if (usedType->IsMethodRef())
  2438. {
  2439. auto methodRefType = (BfMethodRefType*)usedType;
  2440. AddDependency(methodRefType->mMethodRef->GetOwner(), usingType, flags);
  2441. return;
  2442. }*/
  2443. // Why in the world were we doing this?
  2444. // This caused functions to get immediately deleted since they appear to have no references ever....
  2445. // if (usedType->IsFunction())
  2446. // {
  2447. // usedType = ResolveTypeDef(mCompiler->mFunctionTypeDef);
  2448. // }
  2449. if ((!mCompiler->mIsResolveOnly) && (mIsReified))
  2450. {
  2451. auto usingModule = usingType->GetModule();
  2452. BfModule* usedModule;
  2453. if (usedType->IsFunction())
  2454. {
  2455. auto typeInst = usedType->ToTypeInstance();
  2456. if (typeInst->mBaseType == NULL)
  2457. PopulateType(typeInst);
  2458. usedModule = typeInst->mBaseType->GetModule();
  2459. }
  2460. else
  2461. usedModule = usedType->GetModule();
  2462. if ((usingModule != NULL) && (!usingModule->mIsSpecialModule) &&
  2463. (usedModule != NULL) && (!usedModule->mIsSpecialModule))
  2464. {
  2465. usingModule->mModuleRefs.Add(usedModule);
  2466. }
  2467. }
  2468. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mMethodInfoEx != NULL) && (flags != BfDependencyMap::DependencyFlag_MethodGenericArg))
  2469. {
  2470. // When we are specializing a method, usage of that specialized type is already handled with DependencyFlag_MethodGenericArg
  2471. for (auto genericArg : mCurMethodInstance->mMethodInfoEx->mMethodGenericArguments)
  2472. if (genericArg == usedType)
  2473. return;
  2474. }
  2475. auto underlyingType = usedType->GetUnderlyingType();
  2476. if (underlyingType != NULL) // Not really a "GenericArg", but... same purpose.
  2477. AddDependency(underlyingType, usingType, BfDependencyMap::DependencyFlag_GenericArgRef);
  2478. BfDependedType* checkDType = usedType->ToDependedType();
  2479. if (checkDType == NULL)
  2480. return;
  2481. if ((usedType->mRebuildFlags & BfTypeRebuildFlag_AwaitingReference) != 0)
  2482. mContext->MarkAsReferenced(checkDType);
  2483. checkDType->mDependencyMap.AddUsedBy(usingType, flags);
  2484. if (checkDType->IsGenericTypeInstance())
  2485. {
  2486. auto genericTypeInstance = (BfGenericTypeInstance*) checkDType;
  2487. for (auto genericArg : genericTypeInstance->mTypeGenericArguments)
  2488. {
  2489. AddDependency(genericArg, usingType, BfDependencyMap::DependencyFlag_GenericArgRef);
  2490. }
  2491. }
  2492. }
  2493. void BfModule::AddCallDependency(BfMethodInstance* methodInstance, bool devirtualized)
  2494. {
  2495. if ((mCurMethodState != NULL) && (mCurMethodState->mHotDataReferenceBuilder != NULL))
  2496. {
  2497. if (methodInstance->mHotMethod == NULL)
  2498. CheckHotMethod(methodInstance, "");
  2499. BF_ASSERT(methodInstance->mHotMethod != NULL);
  2500. if (devirtualized)
  2501. mCurMethodState->mHotDataReferenceBuilder->mDevirtualizedCalledMethods.Add(methodInstance->mHotMethod);
  2502. else
  2503. mCurMethodState->mHotDataReferenceBuilder->mCalledMethods.Add(methodInstance->mHotMethod);
  2504. }
  2505. }
  2506. bool BfModule::IsAttribute(BfTypeInstance* typeInst)
  2507. {
  2508. auto checkTypeInst = typeInst;
  2509. while (checkTypeInst != NULL)
  2510. {
  2511. if (checkTypeInst->mTypeDef == mCompiler->mAttributeTypeDef)
  2512. return true;
  2513. checkTypeInst = checkTypeInst->mBaseType;
  2514. }
  2515. return false;
  2516. }
  2517. void BfModule::PopulateGlobalContainersList(const BfGlobalLookup& globalLookup)
  2518. {
  2519. if (mContext->mCurTypeState == NULL)
  2520. return;
  2521. BP_ZONE("PopulateGlobalContainersList");
  2522. BfTypeDef* userTypeDef = mContext->mCurTypeState->mCurTypeDef;
  2523. if (userTypeDef == NULL)
  2524. userTypeDef = mCurTypeInstance->mTypeDef;
  2525. if (mContext->mCurTypeState->mGlobalContainerCurUserTypeDef != userTypeDef)
  2526. {
  2527. mContext->mCurTypeState->mGlobalContainers.Clear();
  2528. for (int namespaceIdx = -1; namespaceIdx < (int)userTypeDef->mNamespaceSearch.size(); namespaceIdx++)
  2529. {
  2530. BfAtomComposite findStr;
  2531. if (namespaceIdx != -1)
  2532. findStr.Reference(userTypeDef->mNamespaceSearch[namespaceIdx]);
  2533. auto typeDefItr = mSystem->mTypeDefs.TryGet(findStr);
  2534. while (typeDefItr)
  2535. {
  2536. auto typeDef = *typeDefItr;
  2537. if ((typeDef->mFullName == findStr) && (typeDef->mIsCombinedPartial) && (typeDef->IsGlobalsContainer()))
  2538. {
  2539. if (typeDef->mProject->ContainsReference(typeDef->mProject))
  2540. {
  2541. BfGlobalContainerEntry globalEntry;
  2542. globalEntry.mTypeDef = typeDef;
  2543. globalEntry.mTypeInst = NULL;
  2544. typeDef->PopulateMemberSets();
  2545. mContext->mCurTypeState->mGlobalContainers.Add(globalEntry);
  2546. }
  2547. }
  2548. else if (!typeDef->mIsPartial)
  2549. {
  2550. //break;
  2551. }
  2552. typeDefItr.MoveToNextHashMatch();
  2553. }
  2554. }
  2555. mContext->mCurTypeState->mGlobalContainerCurUserTypeDef = userTypeDef;
  2556. }
  2557. // Only create actual typeInst when we have an applicable member. This helps in keeping unused globals from
  2558. // reifing types
  2559. for (auto& globalEntry : mContext->mCurTypeState->mGlobalContainers)
  2560. {
  2561. if (globalEntry.mTypeInst == NULL)
  2562. {
  2563. bool include = false;
  2564. if (globalLookup.mKind == BfGlobalLookup::Kind_All)
  2565. include = true;
  2566. else if (globalLookup.mKind == BfGlobalLookup::Kind_Field)
  2567. {
  2568. if (globalEntry.mTypeDef->mFieldSet.ContainsWith(globalLookup.mName))
  2569. include = true;
  2570. if (globalEntry.mTypeDef->mPropertySet.ContainsWith(globalLookup.mName))
  2571. include = true;
  2572. }
  2573. else if (globalLookup.mKind == BfGlobalLookup::Kind_Method)
  2574. {
  2575. if (globalEntry.mTypeDef->mMethodSet.ContainsWith(globalLookup.mName))
  2576. include = true;
  2577. }
  2578. if (include)
  2579. {
  2580. auto type = ResolveTypeDef(globalEntry.mTypeDef);
  2581. if (type != NULL)
  2582. globalEntry.mTypeInst = type->ToTypeInstance();
  2583. }
  2584. }
  2585. }
  2586. }
  2587. void PrintUsers(llvm::MDNode* md);
  2588. BfModuleOptions BfModule::GetModuleOptions()
  2589. {
  2590. if (mIsScratchModule)
  2591. return BfModuleOptions();
  2592. if (mModuleOptions != NULL)
  2593. return *mModuleOptions;
  2594. BfModuleOptions moduleOptions;
  2595. moduleOptions.mEmitDebugInfo = mCompiler->mOptions.mEmitDebugInfo ? 1 : mCompiler->mOptions.mEmitLineInfo ? 2 : 0;
  2596. if (mProject != NULL)
  2597. {
  2598. moduleOptions.mSIMDSetting = mProject->mCodeGenOptions.mSIMDSetting;
  2599. moduleOptions.mOptLevel = mProject->mCodeGenOptions.mOptLevel;
  2600. }
  2601. auto headModule = this;
  2602. while (headModule->mParentModule != NULL)
  2603. headModule = headModule->mParentModule;
  2604. BF_ASSERT((headModule->mOwnedTypeInstances.size() > 0) || (mModuleName == "vdata"));
  2605. if (headModule->mOwnedTypeInstances.size() > 0)
  2606. {
  2607. auto typeInst = headModule->mOwnedTypeInstances[0];
  2608. PopulateType(typeInst);
  2609. if (typeInst->mTypeOptionsIdx != -1)
  2610. {
  2611. auto typeOptions = mSystem->GetTypeOptions(typeInst->mTypeOptionsIdx);
  2612. moduleOptions.mSIMDSetting = (BfSIMDSetting)BfTypeOptions::Apply((int)moduleOptions.mSIMDSetting, typeOptions->mSIMDSetting);
  2613. moduleOptions.mEmitDebugInfo = BfTypeOptions::Apply(moduleOptions.mEmitDebugInfo, typeOptions->mEmitDebugInfo);
  2614. moduleOptions.mOptLevel = (BfOptLevel)BfTypeOptions::Apply((int)moduleOptions.mOptLevel, (int)typeOptions->mOptimizationLevel);
  2615. }
  2616. }
  2617. return moduleOptions;
  2618. }
  2619. BfCheckedKind BfModule::GetDefaultCheckedKind()
  2620. {
  2621. bool runtimeChecks = mCompiler->mOptions.mRuntimeChecks;
  2622. auto typeOptions = GetTypeOptions();
  2623. if (typeOptions != NULL)
  2624. runtimeChecks = BfTypeOptions::Apply(runtimeChecks, typeOptions->mRuntimeChecks);
  2625. return runtimeChecks ? BfCheckedKind_Checked : BfCheckedKind_Unchecked;
  2626. }
  2627. void BfModule::AddFailType(BfTypeInstance* typeInstance)
  2628. {
  2629. mContext->mFailTypes.Add(typeInstance);
  2630. }
  2631. void BfModule::CheckAddFailType()
  2632. {
  2633. //TODO: We removed this line, because failures in resolve-only generic method can occur in non-owning modules
  2634. // but we still need to add the owning type to the FailTypes list
  2635. //.. OLD:
  2636. // While we're inlining, it's possible that mCurTypeInstance belongs to another module, ignore it
  2637. /*if (mCurTypeInstance->mModule != this)
  2638. return;*/
  2639. // Using mHadBuildWarning to insert into mFailTypes is our core of our strategy for reasserting
  2640. // warnings on rebuilds where otherwise the warnings wouldn't be generated because no code was
  2641. // being recompiled. This forces types with warnings to be recompiled.
  2642. // We had this 'mIsResolveOnly' check for speed in resolveOnly, but we removed it so the IDE can be
  2643. // constantly warning-aware
  2644. if ((mHadBuildError) ||
  2645. (mHadBuildWarning /*&& !mCompiler->mIsResolveOnly*/))
  2646. {
  2647. //mContext->mFailTypes.Add(mCurTypeInstance);
  2648. }
  2649. }
  2650. void BfModule::MarkDerivedDirty(BfTypeInstance* typeInst)
  2651. {
  2652. if (!mCompiler->IsHotCompile())
  2653. return;
  2654. typeInst->mDirty = true;
  2655. for (auto& dep : typeInst->mDependencyMap)
  2656. {
  2657. auto depType = dep.mKey;
  2658. auto depFlags = dep.mValue.mFlags;
  2659. if ((depFlags & BfDependencyMap::DependencyFlag_DerivedFrom) != 0)
  2660. {
  2661. MarkDerivedDirty(depType->ToTypeInstance());
  2662. }
  2663. }
  2664. }
  2665. void BfModule::CreateStaticField(BfFieldInstance* fieldInstance, bool isThreadLocal)
  2666. {
  2667. auto fieldType = fieldInstance->GetResolvedType();
  2668. auto field = fieldInstance->GetFieldDef();
  2669. if (fieldType->IsVar())
  2670. return;
  2671. BfIRValue initValue;
  2672. if (field->mIsConst)
  2673. {
  2674. if (fieldType->IsPointer())
  2675. fieldType = fieldType->GetUnderlyingType();
  2676. }
  2677. if (!field->mIsExtern)
  2678. initValue = GetDefaultValue(fieldType);
  2679. if (fieldInstance->mOwner->IsUnspecializedType())
  2680. {
  2681. // Placeholder
  2682. auto ptrVal = CreatePointerType(fieldType);
  2683. mStaticFieldRefs[fieldInstance] = GetDefaultValue(ptrVal);
  2684. }
  2685. else
  2686. {
  2687. BfLogSysM("Creating static field Module:%p Type:%p\n", this, fieldType);
  2688. StringT<128> staticVarName;
  2689. BfMangler::Mangle(staticVarName, mCompiler->GetMangleKind(), fieldInstance);
  2690. if (!fieldType->IsValuelessType())
  2691. {
  2692. BfIRValue globalVar = mBfIRBuilder->CreateGlobalVariable(
  2693. mBfIRBuilder->MapType(fieldType, BfIRPopulateType_Eventually_Full),
  2694. false,
  2695. BfIRLinkageType_External,
  2696. initValue,
  2697. staticVarName,
  2698. isThreadLocal);
  2699. BF_ASSERT(globalVar);
  2700. mStaticFieldRefs[fieldInstance] = globalVar;
  2701. }
  2702. }
  2703. }
  2704. void BfModule::ResolveConstField(BfTypeInstance* typeInstance, BfFieldInstance* fieldInstance, BfFieldDef* fieldDef, bool forceResolve)
  2705. {
  2706. bool autoCompleteOnly = mCompiler->IsAutocomplete();
  2707. BfType* fieldType = NULL;
  2708. if (fieldInstance != NULL)
  2709. {
  2710. fieldType = fieldInstance->GetResolvedType();
  2711. if (fieldType == NULL)
  2712. fieldType = ResolveTypeRef(fieldDef->mTypeRef);
  2713. }
  2714. else
  2715. {
  2716. BF_ASSERT(mCompiler->IsAutocomplete());
  2717. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  2718. if ((typeInstance->IsEnum()) && (fieldDef->mTypeRef == NULL))
  2719. {
  2720. fieldType = typeInstance;
  2721. }
  2722. else
  2723. {
  2724. auto isLet = (fieldDef->mTypeRef != NULL) && (fieldDef->mTypeRef->IsExact<BfLetTypeReference>());
  2725. auto isVar = (fieldDef->mTypeRef != NULL) && (fieldDef->mTypeRef->IsExact<BfVarTypeReference>());
  2726. if (isLet || isVar)
  2727. fieldType = GetPrimitiveType(BfTypeCode_Var);
  2728. else
  2729. fieldType = ResolveTypeRef(fieldDef->mTypeRef);
  2730. if (fieldType == NULL)
  2731. fieldType = mContext->mBfObjectType;
  2732. }
  2733. }
  2734. if ((fieldInstance != NULL) && (fieldInstance->mConstIdx != -1) && (!forceResolve))
  2735. return;
  2736. if (mContext->mFieldResolveReentrys.size() > 1)
  2737. {
  2738. if (mContext->mFieldResolveReentrys.IndexOf(fieldInstance, 1) != -1)
  2739. {
  2740. String failStr = "Circular data reference detected between the following fields:";
  2741. for (int i = 1; i < (int)mContext->mFieldResolveReentrys.size(); i++)
  2742. {
  2743. if (i > 1)
  2744. failStr += ",";
  2745. failStr += "\n '" + TypeToString(typeInstance) + "." + mContext->mFieldResolveReentrys[i]->GetFieldDef()->mName + "'";
  2746. }
  2747. BfError* err = Fail(failStr, fieldDef->mFieldDeclaration);
  2748. if (err)
  2749. err->mIsPersistent = true;
  2750. return;
  2751. }
  2752. }
  2753. mContext->mFieldResolveReentrys.push_back(fieldInstance);
  2754. AutoPopBack<decltype (mContext->mFieldResolveReentrys)> popTypeResolveReentry(&mContext->mFieldResolveReentrys);
  2755. if (fieldInstance == NULL)
  2756. popTypeResolveReentry.Pop();
  2757. auto typeDef = typeInstance->mTypeDef;
  2758. BfIRValue constValue;
  2759. if (fieldDef->mIsExtern)
  2760. {
  2761. if (!fieldDef->mTypeRef->IsA<BfPointerTypeRef>())
  2762. {
  2763. Fail("Extern consts must be pointer types", fieldDef->mFieldDeclaration->mTypeRef);
  2764. }
  2765. if (fieldDef->mInitializer != NULL)
  2766. {
  2767. Fail("Extern consts cannot have initializers", fieldDef->mFieldDeclaration->mNameNode);
  2768. }
  2769. }
  2770. else if (fieldDef->mInitializer == NULL)
  2771. {
  2772. if (fieldDef->IsEnumCaseEntry())
  2773. {
  2774. if (typeInstance->IsTypedPrimitive())
  2775. {
  2776. BfFieldInstance* prevFieldInstance = NULL;
  2777. for (int i = fieldDef->mIdx - 1; i >= 0; i--)
  2778. {
  2779. BfFieldInstance* checkFieldInst = &typeInstance->mFieldInstances[i];
  2780. if (checkFieldInst->GetFieldDef()->IsEnumCaseEntry())
  2781. {
  2782. prevFieldInstance = checkFieldInst;
  2783. break;
  2784. }
  2785. }
  2786. if (prevFieldInstance == NULL)
  2787. constValue = GetConstValue(0, typeInstance);
  2788. else
  2789. {
  2790. ResolveConstField(typeInstance, prevFieldInstance, prevFieldInstance->GetFieldDef());
  2791. if (prevFieldInstance->mConstIdx == -1)
  2792. {
  2793. if (!mCompiler->IsAutocomplete())
  2794. AssertErrorState();
  2795. constValue = GetConstValue(0, typeInstance);
  2796. }
  2797. else
  2798. {
  2799. auto prevConstant = ConstantToCurrent(typeInstance->mConstHolder->GetConstantById(prevFieldInstance->mConstIdx), typeInstance->mConstHolder, typeInstance);
  2800. constValue = mBfIRBuilder->CreateAdd(prevConstant, GetConstValue(1, typeInstance));
  2801. }
  2802. }
  2803. }
  2804. }
  2805. else
  2806. {
  2807. Fail("Const requires initializer", fieldDef->mFieldDeclaration->mNameNode);
  2808. }
  2809. }
  2810. else
  2811. {
  2812. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  2813. SetAndRestoreValue<bool> prevIgnoreWrite(mBfIRBuilder->mIgnoreWrites, true);
  2814. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, NULL);
  2815. BfConstResolver constResolver(this);
  2816. BfMethodState methodState;
  2817. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  2818. methodState.mTempKind = BfMethodState::TempKind_Static;
  2819. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  2820. if (fieldType->IsVar())
  2821. {
  2822. auto initValue = GetFieldInitializerValue(fieldInstance, fieldDef->mInitializer, fieldDef, fieldType);
  2823. if (!initValue)
  2824. {
  2825. AssertErrorState();
  2826. initValue = GetDefaultTypedValue(mContext->mBfObjectType);
  2827. }
  2828. if (fieldInstance != NULL)
  2829. {
  2830. fieldInstance->mResolvedType = initValue.mType;
  2831. }
  2832. constValue = initValue.mValue;
  2833. }
  2834. else
  2835. {
  2836. auto uncastedInitValue = GetFieldInitializerValue(fieldInstance, fieldDef->mInitializer, fieldDef, fieldType);
  2837. constValue = uncastedInitValue.mValue;
  2838. }
  2839. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  2840. }
  2841. if (fieldInstance != NULL)
  2842. {
  2843. fieldType = fieldInstance->GetResolvedType();
  2844. if ((fieldType == NULL) || (fieldType->IsVar()))
  2845. {
  2846. AssertErrorState();
  2847. // Default const type is 'int'
  2848. BfTypedValue initValue = GetDefaultTypedValue(GetPrimitiveType(BfTypeCode_IntPtr));
  2849. if (fieldInstance != NULL)
  2850. {
  2851. fieldInstance->mResolvedType = initValue.mType;
  2852. }
  2853. constValue = initValue.mValue;
  2854. }
  2855. if ((constValue) && (fieldInstance->mConstIdx == -1))
  2856. {
  2857. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  2858. CurrentAddToConstHolder(constValue);
  2859. fieldInstance->mConstIdx = constValue.mId;
  2860. }
  2861. }
  2862. }
  2863. BfType* BfModule::ResolveVarFieldType(BfTypeInstance* typeInstance, BfFieldInstance* fieldInstance, BfFieldDef* field)
  2864. {
  2865. bool isDeclType = BfNodeDynCastExact<BfDeclTypeRef>(field->mFieldDeclaration->mTypeRef) != NULL;
  2866. auto fieldType = fieldInstance->GetResolvedType();
  2867. if ((field->mIsConst) && (!isDeclType))
  2868. {
  2869. ResolveConstField(typeInstance, fieldInstance, field);
  2870. return fieldInstance->GetResolvedType();
  2871. }
  2872. bool staticOnly = (field->mIsStatic) && (!isDeclType);
  2873. if (!fieldInstance->mIsInferredType)
  2874. return fieldType;
  2875. if (!fieldType->IsVar())
  2876. return fieldType;
  2877. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  2878. BfTypeState typeState(mCurTypeInstance, mContext->mCurTypeState);
  2879. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState, mContext->mCurTypeState->mTypeInstance != typeInstance);
  2880. auto typeDef = typeInstance->mTypeDef;
  2881. if ((!field->mIsStatic) && (typeDef->mIsStatic))
  2882. {
  2883. AssertErrorState();
  2884. SetHadVarUsage();
  2885. return GetPrimitiveType(BfTypeCode_Var);
  2886. }
  2887. bool hadInferenceCycle = false;
  2888. if (mContext->mFieldResolveReentrys.size() > 1)
  2889. {
  2890. if (mContext->mFieldResolveReentrys.IndexOf(fieldInstance, 1) != -1)
  2891. {
  2892. for (int i = 1; i < (int)mContext->mFieldResolveReentrys.size(); i++)
  2893. {
  2894. auto fieldInst = mContext->mFieldResolveReentrys[i];
  2895. auto fieldDef = fieldInst->GetFieldDef();
  2896. auto fieldOwner = fieldInst->mOwner;
  2897. auto fieldModule = fieldOwner->mModule;
  2898. SetAndRestoreValue<bool> prevIgnoreError(fieldModule->mIgnoreErrors, false);
  2899. fieldModule->Fail(StrFormat("Field '%s.%s' creates a type inference cycle", TypeToString(fieldOwner).c_str(), fieldDef->mName.c_str()), fieldDef->mTypeRef, true);
  2900. }
  2901. SetHadVarUsage();
  2902. return GetPrimitiveType(BfTypeCode_Var);
  2903. }
  2904. }
  2905. mContext->mFieldResolveReentrys.push_back(fieldInstance);
  2906. AutoPopBack<decltype (mContext->mFieldResolveReentrys)> popTypeResolveReentry(&mContext->mFieldResolveReentrys);
  2907. SetAndRestoreValue<bool> prevResolvingVar(typeInstance->mResolvingVarField, true);
  2908. SetAndRestoreValue<bool> prevCtxResolvingVar(mContext->mResolvingVarField, true);
  2909. if ((field->mInitializer == NULL) && (!isDeclType))
  2910. {
  2911. if ((field->mTypeRef->IsA<BfVarTypeReference>()) || (field->mTypeRef->IsA<BfLetTypeReference>()))
  2912. Fail("Implicitly-typed fields must be initialized", field->GetRefNode());
  2913. SetHadVarUsage();
  2914. return GetPrimitiveType(BfTypeCode_Var);
  2915. }
  2916. BfType* resolvedType = NULL;
  2917. if (!hadInferenceCycle)
  2918. {
  2919. SetAndRestoreValue<bool> prevIgnoreWrite(mBfIRBuilder->mIgnoreWrites, true);
  2920. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, NULL/*ctorMethod.mMethodInstance*/);
  2921. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  2922. BfMethodState methodState;
  2923. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  2924. methodState.mTempKind = staticOnly ? BfMethodState::TempKind_Static : BfMethodState::TempKind_NonStatic;
  2925. if (!staticOnly)
  2926. {
  2927. //BfLocalVariable localVar;
  2928. //methodState.mLocals.push_back(localVar);
  2929. }
  2930. if (isDeclType)
  2931. {
  2932. auto fieldDef = fieldInstance->GetFieldDef();
  2933. resolvedType = ResolveTypeRef(fieldDef->mTypeRef, BfPopulateType_Identity);
  2934. }
  2935. else
  2936. {
  2937. BfTypedValue valueFromExpr;
  2938. valueFromExpr = GetFieldInitializerValue(fieldInstance);
  2939. FixIntUnknown(valueFromExpr);
  2940. resolvedType = valueFromExpr.mType;
  2941. }
  2942. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  2943. }
  2944. if (resolvedType == NULL)
  2945. return GetPrimitiveType(BfTypeCode_Var);
  2946. fieldInstance->SetResolvedType(resolvedType);
  2947. if (field->mIsStatic)
  2948. {
  2949. }
  2950. else if (fieldInstance->mDataIdx <= 0)
  2951. {
  2952. }
  2953. else
  2954. {
  2955. BF_ASSERT(typeInstance->IsIncomplete());
  2956. }
  2957. return resolvedType;
  2958. }
  2959. void BfModule::MarkFieldInitialized(BfFieldInstance* fieldInstance)
  2960. {
  2961. BF_ASSERT(fieldInstance->mOwner == mCurTypeInstance);
  2962. auto fieldType = fieldInstance->GetResolvedType();
  2963. if ((fieldInstance->mMergedDataIdx != -1) && (mCurMethodState != NULL))
  2964. {
  2965. int fieldDataCount = 1;
  2966. if (fieldType->IsStruct())
  2967. {
  2968. auto structTypeInst = fieldType->ToTypeInstance();
  2969. fieldDataCount = structTypeInst->mMergedFieldDataCount;
  2970. }
  2971. //TODO: Under what circumstances could 'thisVariable' be NULL?
  2972. auto thisVariable = GetThisVariable();
  2973. if (thisVariable != NULL)
  2974. {
  2975. for (int i = 0; i < fieldDataCount; i++)
  2976. mCurMethodState->LocalDefined(thisVariable, fieldInstance->mMergedDataIdx + i);
  2977. }
  2978. }
  2979. }
  2980. bool BfModule::IsThreadLocal(BfFieldInstance * fieldInstance)
  2981. {
  2982. if (fieldInstance->mCustomAttributes == NULL)
  2983. return false;
  2984. auto fieldDef = fieldInstance->GetFieldDef();
  2985. if (!fieldDef->mIsStatic)
  2986. return false;
  2987. bool isThreadLocal = false;
  2988. if (fieldInstance->mCustomAttributes != NULL)
  2989. {
  2990. for (auto customAttr : fieldInstance->mCustomAttributes->mAttributes)
  2991. {
  2992. if (customAttr.mType->ToTypeInstance()->mTypeDef == mCompiler->mThreadStaticAttributeTypeDef)
  2993. return true;
  2994. }
  2995. }
  2996. return false;
  2997. }
  2998. BfTypedValue BfModule::GetFieldInitializerValue(BfFieldInstance* fieldInstance, BfExpression* initializer, BfFieldDef* fieldDef, BfType* fieldType)
  2999. {
  3000. if (fieldDef == NULL)
  3001. fieldDef = fieldInstance->GetFieldDef();
  3002. if (fieldType == NULL)
  3003. fieldType = fieldInstance->GetResolvedType();
  3004. if (initializer == NULL)
  3005. {
  3006. if (fieldDef == NULL)
  3007. return BfTypedValue();
  3008. initializer = fieldDef->mInitializer;
  3009. }
  3010. BfTypedValue result;
  3011. if (initializer == NULL)
  3012. {
  3013. result = GetDefaultTypedValue(fieldInstance->mResolvedType);
  3014. }
  3015. else
  3016. {
  3017. if ((mCompiler->mIsResolveOnly) && (mCompiler->mResolvePassData->mSourceClassifier != NULL) && (initializer->IsFromParser(mCompiler->mResolvePassData->mParser)))
  3018. {
  3019. mCompiler->mResolvePassData->mSourceClassifier->SetElementType(initializer, BfSourceElementType_Normal);
  3020. mCompiler->mResolvePassData->mSourceClassifier->VisitChildNoRef(initializer);
  3021. }
  3022. if ((mCurTypeInstance->IsPayloadEnum()) && (fieldDef->IsEnumCaseEntry()))
  3023. {
  3024. Fail("Enums with payloads cannot have explicitly-defined discriminators", initializer);
  3025. BfConstResolver constResolver(this);
  3026. constResolver.Resolve(initializer);
  3027. return GetDefaultTypedValue(fieldType);
  3028. }
  3029. else if (fieldDef->mIsConst)
  3030. {
  3031. BfTypeState typeState;
  3032. typeState.mCurTypeDef = fieldDef->mDeclaringType;
  3033. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  3034. BfConstResolver constResolver(this);
  3035. if (fieldType->IsVar())
  3036. return constResolver.Resolve(initializer);
  3037. else
  3038. return constResolver.Resolve(initializer, fieldType);
  3039. }
  3040. if (fieldType->IsVar())
  3041. result = CreateValueFromExpression(initializer, NULL, (BfEvalExprFlags)(BfEvalExprFlags_NoValueAddr | BfEvalExprFlags_FieldInitializer));
  3042. else
  3043. result = CreateValueFromExpression(initializer, fieldType, (BfEvalExprFlags)(BfEvalExprFlags_NoValueAddr | BfEvalExprFlags_FieldInitializer));
  3044. }
  3045. if (fieldInstance != NULL)
  3046. MarkFieldInitialized(fieldInstance);
  3047. return result;
  3048. }
  3049. void BfModule::CheckInterfaceMethod(BfMethodInstance* methodInstance)
  3050. {
  3051. }
  3052. void BfModule::FindSubTypes(BfTypeInstance* classType, SizedArrayImpl<int>* outVals, SizedArrayImpl<BfTypeInstance*>* exChecks, bool isInterfacePass)
  3053. {
  3054. PopulateType(classType);
  3055. if (isInterfacePass)
  3056. {
  3057. for (auto ifaceInst : classType->mInterfaces)
  3058. {
  3059. if (exChecks->Contains(ifaceInst.mInterfaceType))
  3060. continue;
  3061. if (outVals->Contains(ifaceInst.mInterfaceType->mTypeId))
  3062. continue;
  3063. if (ifaceInst.mDeclaringType->IsExtension())
  3064. {
  3065. bool needsExCheck = false;
  3066. if (ifaceInst.mDeclaringType->mProject != classType->mTypeDef->mProject)
  3067. {
  3068. exChecks->push_back(ifaceInst.mInterfaceType);
  3069. continue;
  3070. }
  3071. }
  3072. outVals->push_back(ifaceInst.mInterfaceType->mTypeId);
  3073. }
  3074. }
  3075. else
  3076. {
  3077. outVals->push_back(classType->mTypeId);
  3078. }
  3079. if (classType->mBaseType != NULL)
  3080. {
  3081. FindSubTypes(classType->mBaseType, outVals, exChecks, isInterfacePass);
  3082. }
  3083. }
  3084. void BfModule::CreateDynamicCastMethod()
  3085. {
  3086. auto objType = mContext->mBfObjectType;
  3087. if ((mCompiler->mIsResolveOnly) || (!mIsReified))
  3088. {
  3089. // The main reason to punt on this method for ResolveOnly is because types can be created
  3090. // and destroyed quickly during autocomplete and the typeId creep can generate lots of
  3091. // entries in the LLVM ConstantInt pool, primarily from the FindSubTypes call. We can
  3092. // remove this punt when we recycle typeId's
  3093. mBfIRBuilder->CreateRet(mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapTypeInstPtr(objType)));
  3094. mCurMethodState->mHadReturn = true;
  3095. return;
  3096. }
  3097. bool isInterfacePass = mCurMethodInstance->mMethodDef->mName == BF_METHODNAME_DYNAMICCAST_INTERFACE;
  3098. auto func = mCurMethodState->mIRFunction;
  3099. auto thisValue = mBfIRBuilder->GetArgument(0);
  3100. auto typeIdValue = mBfIRBuilder->GetArgument(1);
  3101. auto intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  3102. auto int32Type = GetPrimitiveType(BfTypeCode_Int32);
  3103. typeIdValue = CastToValue(NULL, BfTypedValue(typeIdValue, intPtrType), int32Type, (BfCastFlags)(BfCastFlags_Explicit | BfCastFlags_SilentFail));
  3104. auto thisObject = mBfIRBuilder->CreateBitCast(thisValue, mBfIRBuilder->MapType(objType));
  3105. auto trueBB = mBfIRBuilder->CreateBlock("check.true");
  3106. //auto falseBB = mBfIRBuilder->CreateBlock("check.false");
  3107. auto exitBB = mBfIRBuilder->CreateBlock("exit");
  3108. SizedArray<int, 8> typeMatches;
  3109. SizedArray<BfTypeInstance*, 8> exChecks;
  3110. FindSubTypes(mCurTypeInstance, &typeMatches, &exChecks, isInterfacePass);
  3111. if ((mCurTypeInstance->IsGenericTypeInstance()) && (!mCurTypeInstance->IsUnspecializedType()))
  3112. {
  3113. // Add 'unbound' type id to cast list so things like "List<int> is List<>" work
  3114. auto genericTypeInst = mCurTypeInstance->mTypeDef;
  3115. BfTypeVector genericArgs;
  3116. for (int i = 0; i < (int) genericTypeInst->mGenericParamDefs.size(); i++)
  3117. genericArgs.push_back(GetGenericParamType(BfGenericParamKind_Type, i));
  3118. auto unboundType = ResolveTypeDef(mCurTypeInstance->mTypeDef, genericArgs, BfPopulateType_Declaration);
  3119. typeMatches.push_back(unboundType->mTypeId);
  3120. }
  3121. if (mCurTypeInstance->IsBoxed())
  3122. {
  3123. BfBoxedType* boxedType = (BfBoxedType*)mCurTypeInstance;
  3124. BfTypeInstance* innerType = boxedType->mElementType;
  3125. FindSubTypes(innerType, &typeMatches, &exChecks, isInterfacePass);
  3126. if (innerType->IsTypedPrimitive())
  3127. {
  3128. auto underlyingType = innerType->GetUnderlyingType();
  3129. typeMatches.push_back(underlyingType->mTypeId);
  3130. }
  3131. auto innerTypeInst = innerType->ToTypeInstance();
  3132. if ((innerTypeInst->mTypeDef == mCompiler->mSizedArrayTypeDef) ||
  3133. (innerTypeInst->mTypeDef == mCompiler->mPointerTTypeDef) ||
  3134. (innerTypeInst->mTypeDef == mCompiler->mMethodRefTypeDef))
  3135. {
  3136. PopulateType(innerTypeInst);
  3137. //TODO: What case was this supposed to handle?
  3138. //typeMatches.push_back(innerTypeInst->mFieldInstances[0].mResolvedType->mTypeId);
  3139. }
  3140. }
  3141. auto curBlock = mBfIRBuilder->GetInsertBlock();
  3142. BfIRValue vDataPtr;
  3143. if (!exChecks.empty())
  3144. {
  3145. BfType* intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  3146. auto ptrPtrType = mBfIRBuilder->GetPointerTo(mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapType(intPtrType)));
  3147. auto vDataPtrPtr = mBfIRBuilder->CreateBitCast(thisValue, ptrPtrType);
  3148. vDataPtr = FixClassVData(mBfIRBuilder->CreateLoad(vDataPtrPtr/*, "vtable"*/));
  3149. }
  3150. auto switchStatement = mBfIRBuilder->CreateSwitch(typeIdValue, exitBB, (int)typeMatches.size() + (int)exChecks.size());
  3151. for (auto typeMatch : typeMatches)
  3152. mBfIRBuilder->AddSwitchCase(switchStatement, GetConstValue32(typeMatch), trueBB);
  3153. Array<BfIRValue> incomingFalses;
  3154. for (auto ifaceTypeInst : exChecks)
  3155. {
  3156. BfIRBlock nextBB = mBfIRBuilder->CreateBlock("exCheck", true);
  3157. mBfIRBuilder->AddSwitchCase(switchStatement, GetConstValue32(ifaceTypeInst->mTypeId), nextBB);
  3158. mBfIRBuilder->SetInsertPoint(nextBB);
  3159. BfIRValue slotOfs = GetInterfaceSlotNum(ifaceTypeInst);
  3160. auto ifacePtrPtr = mBfIRBuilder->CreateInBoundsGEP(vDataPtr, slotOfs/*, "iface"*/);
  3161. auto ifacePtr = mBfIRBuilder->CreateLoad(ifacePtrPtr);
  3162. auto cmpResult = mBfIRBuilder->CreateCmpNE(ifacePtr, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 0));
  3163. mBfIRBuilder->CreateCondBr(cmpResult, trueBB, exitBB);
  3164. incomingFalses.push_back(nextBB);
  3165. }
  3166. mBfIRBuilder->AddBlock(trueBB);
  3167. mBfIRBuilder->SetInsertPoint(trueBB);
  3168. mBfIRBuilder->CreateBr(exitBB);
  3169. mBfIRBuilder->AddBlock(exitBB);
  3170. mBfIRBuilder->SetInsertPoint(exitBB);
  3171. auto phi = mBfIRBuilder->CreatePhi(mBfIRBuilder->MapTypeInstPtr(objType), 2);
  3172. mBfIRBuilder->AddPhiIncoming(phi, thisObject, trueBB);
  3173. auto nullValue = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapTypeInstPtr(objType));
  3174. for (auto incomingFalseBlock : incomingFalses)
  3175. mBfIRBuilder->AddPhiIncoming(phi, nullValue, incomingFalseBlock);
  3176. mBfIRBuilder->AddPhiIncoming(phi, nullValue, curBlock);
  3177. mBfIRBuilder->CreateRet(phi);
  3178. mCurMethodState->mHadReturn = true;
  3179. }
  3180. void BfModule::EmitEquals(BfTypedValue leftValue, BfTypedValue rightValue, BfIRBlock exitBB)
  3181. {
  3182. BfExprEvaluator exprEvaluator(this);
  3183. exprEvaluator.mExpectingType = mCurMethodInstance->mReturnType;
  3184. exprEvaluator.PerformBinaryOperation((BfAstNode*)NULL, (BfAstNode*)NULL, BfBinaryOp_Equality, NULL, BfBinOpFlag_None, leftValue, rightValue);
  3185. BfTypedValue result = exprEvaluator.GetResult();
  3186. if (result)
  3187. {
  3188. auto nextBB = mBfIRBuilder->CreateBlock("next");
  3189. mBfIRBuilder->CreateCondBr(result.mValue, nextBB, exitBB);
  3190. mBfIRBuilder->AddBlock(nextBB);
  3191. mBfIRBuilder->SetInsertPoint(nextBB);
  3192. }
  3193. }
  3194. void BfModule::CreateFakeCallerMethod(const String& funcName)
  3195. {
  3196. BF_ASSERT(mCurMethodInstance->mIRFunction);
  3197. auto voidType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_None));
  3198. SizedArray<BfIRType, 4> paramTypes;
  3199. BfIRFunctionType funcType = mBfIRBuilder->CreateFunctionType(voidType, paramTypes);
  3200. BfIRFunction func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_Internal, "FORCELINK_" + funcName);
  3201. mBfIRBuilder->SetActiveFunction(func);
  3202. auto entryBlock = mBfIRBuilder->CreateBlock("main", true);
  3203. mBfIRBuilder->SetInsertPoint(entryBlock);
  3204. SizedArray<BfIRValue, 8> args;
  3205. BfExprEvaluator exprEvaluator(this);
  3206. if (mCurMethodInstance->HasThis())
  3207. {
  3208. auto thisValue = GetDefaultTypedValue(mCurMethodInstance->GetOwner(), true);
  3209. exprEvaluator.PushThis(NULL, thisValue, mCurMethodInstance, args);
  3210. }
  3211. for (int paramIdx = 0; paramIdx < mCurMethodInstance->GetParamCount(); paramIdx++)
  3212. {
  3213. auto paramType = mCurMethodInstance->GetParamType(paramIdx);
  3214. if (paramType->IsValuelessType())
  3215. continue;
  3216. exprEvaluator.PushArg(GetDefaultTypedValue(paramType, true), args);
  3217. }
  3218. mBfIRBuilder->CreateCall(mCurMethodInstance->mIRFunction, args);
  3219. mBfIRBuilder->CreateRetVoid();
  3220. }
  3221. void BfModule::CreateValueTypeEqualsMethod()
  3222. {
  3223. if (mCurMethodInstance->mIsUnspecialized)
  3224. return;
  3225. if (mCurTypeInstance->IsTypedPrimitive())
  3226. return;
  3227. if (mBfIRBuilder->mIgnoreWrites)
  3228. return;
  3229. BF_ASSERT(!mCurTypeInstance->IsBoxed());
  3230. auto compareType = mCurMethodInstance->mParams[0].mResolvedType;
  3231. bool isValid = true;
  3232. auto compareDType = compareType->ToDependedType();
  3233. BfTypeInstance* compareTypeInst = compareType->ToTypeInstance();
  3234. if (compareTypeInst != NULL)
  3235. {
  3236. if (compareType->IsPrimitiveType())
  3237. compareTypeInst = GetWrappedStructType(compareType);
  3238. if ((compareTypeInst == NULL) || (!compareTypeInst->IsValueType()))
  3239. {
  3240. isValid = false;
  3241. }
  3242. mBfIRBuilder->PopulateType(compareTypeInst);
  3243. }
  3244. auto boolType = GetPrimitiveType(BfTypeCode_Boolean);
  3245. if (!isValid)
  3246. {
  3247. ClearLifetimeEnds();
  3248. mBfIRBuilder->CreateRet(GetDefaultValue(boolType));
  3249. return;
  3250. }
  3251. AddDependency(compareDType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ReadFields);
  3252. auto refNode = mCurTypeInstance->mTypeDef->GetRefNode();
  3253. if (refNode == NULL)
  3254. refNode = mCompiler->mValueTypeTypeDef->GetRefNode();
  3255. UpdateSrcPos(refNode);
  3256. SetIllegalSrcPos();
  3257. auto resultVal = CreateAlloca(boolType);
  3258. mBfIRBuilder->CreateStore(GetConstValue(0, boolType), resultVal);
  3259. auto exitBB = mBfIRBuilder->CreateBlock("exit");
  3260. if (compareType->IsSizedArray())
  3261. {
  3262. auto sizedArrayType = (BfSizedArrayType*)compareType;
  3263. if (sizedArrayType->mElementCount > 6)
  3264. {
  3265. auto intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  3266. auto itr = CreateAlloca(intPtrType);
  3267. mBfIRBuilder->CreateStore(GetDefaultValue(intPtrType), itr);
  3268. auto loopBB = mBfIRBuilder->CreateBlock("loop", true);
  3269. auto bodyBB = mBfIRBuilder->CreateBlock("body", true);
  3270. auto doneBB = mBfIRBuilder->CreateBlock("done", true);
  3271. mBfIRBuilder->CreateBr(loopBB);
  3272. mBfIRBuilder->SetInsertPoint(loopBB);
  3273. auto loadedItr = mBfIRBuilder->CreateLoad(itr);
  3274. auto cmpRes = mBfIRBuilder->CreateCmpGTE(loadedItr, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, (uint64)sizedArrayType->mElementCount), true);
  3275. mBfIRBuilder->CreateCondBr(cmpRes, doneBB, bodyBB);
  3276. mBfIRBuilder->SetInsertPoint(bodyBB);
  3277. BfTypedValue leftValue = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(mCurMethodState->mLocals[0]->mValue, GetDefaultValue(intPtrType), loadedItr), sizedArrayType->mElementType, BfTypedValueKind_Addr);
  3278. BfTypedValue rightValue = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(mCurMethodState->mLocals[1]->mValue, GetDefaultValue(intPtrType), loadedItr), sizedArrayType->mElementType, BfTypedValueKind_Addr);
  3279. EmitEquals(leftValue, rightValue, exitBB);
  3280. auto incValue = mBfIRBuilder->CreateAdd(loadedItr, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 1));
  3281. mBfIRBuilder->CreateStore(incValue, itr);
  3282. mBfIRBuilder->CreateBr(loopBB);
  3283. mBfIRBuilder->SetInsertPoint(doneBB);
  3284. }
  3285. else
  3286. {
  3287. for (int dataIdx = 0; dataIdx < sizedArrayType->mElementCount; dataIdx++)
  3288. {
  3289. BfTypedValue leftValue = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(mCurMethodState->mLocals[0]->mValue, 0, dataIdx), sizedArrayType->mElementType, BfTypedValueKind_Addr);
  3290. BfTypedValue rightValue = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(mCurMethodState->mLocals[1]->mValue, 0, dataIdx), sizedArrayType->mElementType, BfTypedValueKind_Addr);
  3291. EmitEquals(leftValue, rightValue, exitBB);
  3292. }
  3293. }
  3294. }
  3295. else if (compareType->IsMethodRef())
  3296. {
  3297. auto methodRefType = (BfMethodRefType*)compareType;
  3298. BfMethodInstance* methodInstance = methodRefType->mMethodRef;
  3299. BfExprEvaluator exprEvaluator(this);
  3300. BfTypedValue leftTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[0]);
  3301. BfTypedValue rightTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  3302. // We only need to compare the 'this' capture. The rationale is that it's impossible to capture any other non-matching
  3303. // values for the same method reference -- they will always refer back to the same local variables.
  3304. int dataIdx = methodRefType->GetDataIdxFromParamIdx(-1);
  3305. if (dataIdx != -1)
  3306. {
  3307. bool failed = false;
  3308. BfTypedValue leftValue = exprEvaluator.DoImplicitArgCapture(NULL, methodInstance, methodRefType->GetParamIdxFromDataIdx(dataIdx), failed, BfImplicitParamKind_General, leftTypedVal);
  3309. BfTypedValue rightValue = exprEvaluator.DoImplicitArgCapture(NULL, methodInstance, methodRefType->GetParamIdxFromDataIdx(dataIdx), failed, BfImplicitParamKind_General, rightTypedVal);
  3310. BF_ASSERT(!failed);
  3311. EmitEquals(leftValue, rightValue, exitBB);
  3312. }
  3313. }
  3314. else if (compareTypeInst->IsEnum())
  3315. {
  3316. //auto intType = GetPrimitiveType(BfTypeCode_Int32);
  3317. BfExprEvaluator exprEvaluator(this);
  3318. BfTypedValue leftTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[0]);
  3319. BfTypedValue rightTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  3320. auto dscrType = compareTypeInst->GetDiscriminatorType();
  3321. BfTypedValue leftValue = ExtractValue(leftTypedVal, NULL, 2);
  3322. leftValue = LoadValue(leftValue);
  3323. BfTypedValue rightValue = ExtractValue(rightTypedVal, NULL, 2);
  3324. rightValue = LoadValue(rightValue);
  3325. BfTypedValue leftPayload = ExtractValue(leftTypedVal, NULL, 1);
  3326. BfTypedValue rightPayload = ExtractValue(rightTypedVal, NULL, 1);
  3327. EmitEquals(leftValue, rightValue, exitBB);
  3328. int enumCount = 0;
  3329. for (auto& fieldRef : compareTypeInst->mFieldInstances)
  3330. {
  3331. BfFieldInstance* fieldInstance = &fieldRef;
  3332. BfFieldDef* fieldDef = fieldInstance->GetFieldDef();
  3333. if ((fieldDef != NULL) && (fieldDef->IsEnumCaseEntry()))
  3334. {
  3335. enumCount = -fieldInstance->mDataIdx;
  3336. }
  3337. }
  3338. if (enumCount > 0)
  3339. {
  3340. BfIRBlock matchedBlock = mBfIRBuilder->CreateBlock("matched");
  3341. auto switchVal = mBfIRBuilder->CreateSwitch(leftValue.mValue, exitBB, enumCount);
  3342. for (auto& fieldRef : compareTypeInst->mFieldInstances)
  3343. {
  3344. BfFieldInstance* fieldInstance = &fieldRef;
  3345. BfFieldDef* fieldDef = fieldInstance->GetFieldDef();
  3346. if ((fieldDef != NULL) && (fieldDef->IsEnumCaseEntry()))
  3347. {
  3348. int enumIdx = -fieldInstance->mDataIdx - 1;
  3349. if (fieldInstance->mResolvedType->mSize == 0)
  3350. {
  3351. mBfIRBuilder->AddSwitchCase(switchVal, mBfIRBuilder->CreateConst(dscrType->mTypeDef->mTypeCode, enumIdx), matchedBlock);
  3352. }
  3353. else
  3354. {
  3355. auto caseBlock = mBfIRBuilder->CreateBlock("case", true);
  3356. mBfIRBuilder->SetInsertPoint(caseBlock);
  3357. auto tuplePtr = CreatePointerType(fieldInstance->mResolvedType);
  3358. BfTypedValue leftTuple;
  3359. BfTypedValue rightTuple;
  3360. if (leftPayload.IsAddr())
  3361. {
  3362. leftTuple = BfTypedValue(mBfIRBuilder->CreateBitCast(leftPayload.mValue, mBfIRBuilder->MapType(tuplePtr)), fieldInstance->mResolvedType, true);
  3363. rightTuple = BfTypedValue(mBfIRBuilder->CreateBitCast(rightPayload.mValue, mBfIRBuilder->MapType(tuplePtr)), fieldInstance->mResolvedType, true);
  3364. }
  3365. else
  3366. {
  3367. leftTuple = Cast(NULL, leftPayload, fieldInstance->mResolvedType, BfCastFlags_Force);
  3368. rightTuple = Cast(NULL, rightPayload, fieldInstance->mResolvedType, BfCastFlags_Force);
  3369. }
  3370. EmitEquals(leftTuple, rightTuple, exitBB);
  3371. mBfIRBuilder->CreateBr(matchedBlock);
  3372. mBfIRBuilder->AddSwitchCase(switchVal, mBfIRBuilder->CreateConst(dscrType->mTypeDef->mTypeCode, enumIdx), caseBlock);
  3373. }
  3374. }
  3375. }
  3376. mBfIRBuilder->AddBlock(matchedBlock);
  3377. mBfIRBuilder->SetInsertPoint(matchedBlock);
  3378. }
  3379. }
  3380. else if (compareTypeInst->IsUnion())
  3381. {
  3382. auto innerType = compareTypeInst->GetUnionInnerType();
  3383. if (!innerType->IsValuelessType())
  3384. {
  3385. BfExprEvaluator exprEvaluator(this);
  3386. BfTypedValue leftTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[0]);
  3387. BfTypedValue leftUnionTypedVal = ExtractValue(leftTypedVal, NULL, 1);
  3388. BfTypedValue rightTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  3389. BfTypedValue rightUnionTypedVal = ExtractValue(rightTypedVal, NULL, 1);
  3390. EmitEquals(leftUnionTypedVal, rightUnionTypedVal, exitBB);
  3391. }
  3392. }
  3393. else
  3394. {
  3395. BfExprEvaluator exprEvaluator(this);
  3396. BfTypedValue leftTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[0]);
  3397. BfTypedValue rightTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  3398. bool hadComparison = false;
  3399. for (auto& fieldRef : compareTypeInst->mFieldInstances)
  3400. {
  3401. BfFieldInstance* fieldInstance = &fieldRef;
  3402. if (fieldInstance->mDataOffset == -1)
  3403. continue;
  3404. if (fieldInstance->mResolvedType->IsValuelessType())
  3405. continue;
  3406. BfTypedValue leftValue = ExtractValue(leftTypedVal, fieldInstance, fieldInstance->mDataIdx);
  3407. BfTypedValue rightValue = ExtractValue(rightTypedVal, fieldInstance, fieldInstance->mDataIdx);
  3408. if (!fieldInstance->mResolvedType->IsComposite())
  3409. {
  3410. leftValue = LoadValue(leftValue);
  3411. rightValue = LoadValue(rightValue);
  3412. }
  3413. EmitEquals(leftValue, rightValue, exitBB);
  3414. }
  3415. auto baseTypeInst = compareTypeInst->mBaseType;
  3416. if ((baseTypeInst != NULL) && (baseTypeInst->mTypeDef != mCompiler->mValueTypeTypeDef))
  3417. {
  3418. BfTypedValue leftOrigValue(mCurMethodState->mLocals[0]->mValue, compareTypeInst, true);
  3419. BfTypedValue rightOrigValue(mCurMethodState->mLocals[1]->mValue, compareTypeInst, true);
  3420. BfTypedValue leftValue = Cast(NULL, leftOrigValue, baseTypeInst);
  3421. BfTypedValue rightValue = Cast(NULL, rightOrigValue, baseTypeInst);
  3422. EmitEquals(leftValue, rightValue, exitBB);
  3423. }
  3424. }
  3425. mBfIRBuilder->CreateStore(GetConstValue(1, boolType), resultVal);
  3426. mBfIRBuilder->CreateBr(exitBB);
  3427. mBfIRBuilder->AddBlock(exitBB);
  3428. mBfIRBuilder->SetInsertPoint(exitBB);
  3429. auto loadedResult = mBfIRBuilder->CreateLoad(resultVal);
  3430. ClearLifetimeEnds();
  3431. mBfIRBuilder->CreateRet(loadedResult);
  3432. mCurMethodState->mHadReturn = true;
  3433. }
  3434. BfIRValue BfModule::CreateClassVDataGlobal(BfTypeInstance* typeInstance, int* outNumElements, String* outMangledName)
  3435. {
  3436. if (mBfIRBuilder->mIgnoreWrites)
  3437. return mBfIRBuilder->GetFakeVal();
  3438. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  3439. BfType* classVDataType = ResolveTypeDef(mCompiler->mClassVDataTypeDef);
  3440. BfIRValue* globalVariablePtr = NULL;
  3441. mClassVDataRefs.TryGetValue(typeInstance, &globalVariablePtr);
  3442. int numElements = 1;
  3443. if ((outNumElements != NULL) || (globalVariablePtr == NULL))
  3444. {
  3445. numElements += mCompiler->mMaxInterfaceSlots;
  3446. auto maxIFaceVirtIdx = 0;
  3447. if (!typeInstance->IsInterface())
  3448. {
  3449. int dynCastDataElems = 1 + mCompiler->mMaxInterfaceSlots;
  3450. numElements += ((dynCastDataElems * 4) + mSystem->mPtrSize - 1) / mSystem->mPtrSize;
  3451. numElements += typeInstance->GetOrigVTableSize();
  3452. int ifaceMethodLen = typeInstance->GetIFaceVMethodSize();
  3453. if (typeInstance->mHotTypeData != NULL)
  3454. {
  3455. if (typeInstance->mHotTypeData->mOrigInterfaceMethodsLength != -1)
  3456. ifaceMethodLen = typeInstance->mHotTypeData->mOrigInterfaceMethodsLength;
  3457. }
  3458. numElements += ifaceMethodLen;
  3459. }
  3460. if (outNumElements != NULL)
  3461. *outNumElements = numElements;
  3462. }
  3463. StringT<128> classVDataName;
  3464. String memberName = "sBfClassVData";
  3465. if ((typeInstance->mHotTypeData != NULL) && ((typeInstance->mHotTypeData->mHadDataChange) || (typeInstance->mHotTypeData->mPendingDataChange)))
  3466. {
  3467. auto curVersion = typeInstance->mHotTypeData->GetLatestVersion();
  3468. memberName += "_";
  3469. memberName += BfTypeUtils::HashEncode64(curVersion->mDataHash.mLow);
  3470. memberName += BfTypeUtils::HashEncode64(curVersion->mDataHash.mHigh);
  3471. }
  3472. BfMangler::MangleStaticFieldName(classVDataName, mCompiler->GetMangleKind(), typeInstance, memberName, classVDataType);
  3473. if (outMangledName != NULL)
  3474. *outMangledName = classVDataName;
  3475. /*if (itr != mClassVDataRefs.end())
  3476. {
  3477. globalVariable = itr->second;
  3478. }*/
  3479. BfIRValue globalVariable;
  3480. if (globalVariablePtr != NULL)
  3481. {
  3482. globalVariable = *globalVariablePtr;
  3483. }
  3484. else
  3485. {
  3486. BfLogSysM("Creating VData %s\n", classVDataName.c_str());
  3487. auto arrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr), numElements);
  3488. globalVariable = mBfIRBuilder->CreateGlobalVariable(
  3489. arrayType,
  3490. true,
  3491. BfIRLinkageType_External,
  3492. BfIRValue(),
  3493. classVDataName);
  3494. mClassVDataRefs[typeInstance] = globalVariable;
  3495. }
  3496. return globalVariable;
  3497. }
  3498. BfIRValue BfModule::GetClassVDataPtr(BfTypeInstance* typeInstance)
  3499. {
  3500. auto classVDataType = ResolveTypeDef(mCompiler->mClassVDataTypeDef);
  3501. return mBfIRBuilder->CreateBitCast(CreateClassVDataGlobal(typeInstance), mBfIRBuilder->MapType(CreatePointerType(classVDataType)));
  3502. }
  3503. BfIRValue BfModule::CreateClassVDataExtGlobal(BfTypeInstance* declTypeInst, BfTypeInstance* implTypeInst, int startVirtIdx)
  3504. {
  3505. if (mBfIRBuilder->mIgnoreWrites)
  3506. return mBfIRBuilder->GetFakeVal();
  3507. int numElements = declTypeInst->GetSelfVTableSize() - declTypeInst->GetOrigSelfVTableSize();
  3508. BF_ASSERT(numElements >= 0);
  3509. if (numElements <= 0)
  3510. return BfIRValue();
  3511. BF_ASSERT(implTypeInst->mVirtualMethodTable[startVirtIdx].mDeclaringMethod.mMethodNum == -1);
  3512. BF_ASSERT(implTypeInst->mVirtualMethodTable[startVirtIdx].mDeclaringMethod.mTypeInstance == declTypeInst);
  3513. if (declTypeInst->mInheritDepth == implTypeInst->mInheritDepth)
  3514. BF_ASSERT(declTypeInst == implTypeInst);
  3515. else
  3516. BF_ASSERT(implTypeInst->mInheritDepth > declTypeInst->mInheritDepth);
  3517. if (declTypeInst != implTypeInst)
  3518. {
  3519. BfTypeInstance* highestImpl = declTypeInst;
  3520. for (int virtIdx = startVirtIdx + 1; virtIdx < (int)declTypeInst->mVirtualMethodTable.size(); virtIdx++)
  3521. {
  3522. if (implTypeInst->mVirtualMethodTable[virtIdx].mDeclaringMethod.mMethodNum == -1)
  3523. break; // Start of an ext entry for another type
  3524. auto checkImplTypeInst = implTypeInst->mVirtualMethodTable[virtIdx].mImplementingMethod.mTypeInstance;
  3525. if ((checkImplTypeInst != NULL) && (checkImplTypeInst->mInheritDepth > highestImpl->mInheritDepth))
  3526. highestImpl = checkImplTypeInst;
  3527. }
  3528. if (highestImpl != implTypeInst)
  3529. return CreateClassVDataExtGlobal(declTypeInst, highestImpl, startVirtIdx);
  3530. }
  3531. BfVDataExtEntry mapEntry;
  3532. mapEntry.mDeclTypeInst = declTypeInst;
  3533. mapEntry.mImplTypeInst = implTypeInst;
  3534. BfIRValue* irValuePtr = NULL;
  3535. if (mClassVDataExtRefs.TryGetValue(mapEntry, &irValuePtr))
  3536. return *irValuePtr;
  3537. PopulateType(declTypeInst, BfPopulateType_DataAndMethods);
  3538. PopulateType(implTypeInst, BfPopulateType_DataAndMethods);
  3539. StringT<128> classVDataName;
  3540. BfMangler::MangleStaticFieldName(classVDataName, mCompiler->GetMangleKind(), implTypeInst, "bf_hs_replace_VDataExt");
  3541. if (declTypeInst != implTypeInst)
  3542. {
  3543. classVDataName += StrFormat("_%d", implTypeInst->mInheritDepth - declTypeInst->mInheritDepth);
  3544. }
  3545. auto voidPtrType = GetPrimitiveType(BfTypeCode_NullPtr);
  3546. auto voidPtrIRType = mBfIRBuilder->MapType(voidPtrType);
  3547. SizedArray<BfIRValue, 32> vData;
  3548. auto voidPtrNull = GetDefaultValue(voidPtrType);
  3549. for (int virtIdx = startVirtIdx + declTypeInst->GetOrigSelfVTableSize(); virtIdx < (int)declTypeInst->mVirtualMethodTable.size(); virtIdx++)
  3550. {
  3551. if (implTypeInst->mVirtualMethodTable[virtIdx].mDeclaringMethod.mMethodNum == -1)
  3552. break; // Start of an ext entry for another type
  3553. BfIRValue vValue;
  3554. auto& entry = implTypeInst->mVirtualMethodTable[virtIdx];
  3555. BfMethodInstance* declaringMethodInstance = (BfMethodInstance*)entry.mDeclaringMethod;
  3556. if ((declaringMethodInstance != NULL) && (declaringMethodInstance->mMethodInstanceGroup->IsImplemented()) && (declaringMethodInstance->mIsReified))
  3557. {
  3558. BF_ASSERT(entry.mImplementingMethod.mTypeInstance->mMethodInstanceGroups[entry.mImplementingMethod.mMethodNum].IsImplemented());
  3559. BF_ASSERT(entry.mImplementingMethod.mTypeInstance->mMethodInstanceGroups[entry.mImplementingMethod.mMethodNum].mDefault->mIsReified);
  3560. BfMethodInstance* methodInstance = (BfMethodInstance*)entry.mImplementingMethod;
  3561. if ((methodInstance != NULL) && (!methodInstance->mMethodDef->mIsAbstract))
  3562. {
  3563. BF_ASSERT(implTypeInst->IsTypeMemberAccessible(methodInstance->mMethodDef->mDeclaringType, mProject));
  3564. auto moduleMethodInst = GetMethodInstanceAtIdx(methodInstance->mMethodInstanceGroup->mOwner, methodInstance->mMethodInstanceGroup->mMethodIdx);
  3565. auto funcPtr = mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, voidPtrIRType);
  3566. vValue = funcPtr;
  3567. }
  3568. }
  3569. if (!vValue)
  3570. vValue = voidPtrNull;
  3571. vData.Add(vValue);
  3572. }
  3573. BF_ASSERT((int)vData.size() == numElements);
  3574. BfLogSysM("Creating VDataExt %s\n", classVDataName.c_str());
  3575. auto arrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr), numElements);
  3576. auto globalVariable = mBfIRBuilder->CreateGlobalVariable(arrayType, true,
  3577. BfIRLinkageType_External, BfIRValue(), classVDataName);
  3578. BfIRType extVTableType = mBfIRBuilder->GetSizedArrayType(voidPtrIRType, (int)vData.size());
  3579. BfIRValue extVTableConst = mBfIRBuilder->CreateConstArray(extVTableType, vData);
  3580. mBfIRBuilder->GlobalVar_SetInitializer(globalVariable, extVTableConst);
  3581. mClassVDataExtRefs[mapEntry] = globalVariable;
  3582. return globalVariable;
  3583. }
  3584. BfIRValue BfModule::CreateTypeDataRef(BfType* type)
  3585. {
  3586. if (mBfIRBuilder->mIgnoreWrites)
  3587. {
  3588. return mBfIRBuilder->CreateTypeOf(type);
  3589. }
  3590. BfIRValue globalVariable;
  3591. BfIRValue* globalVariablePtr = NULL;
  3592. if (mTypeDataRefs.TryGetValue(type, &globalVariablePtr))
  3593. {
  3594. globalVariable = *globalVariablePtr;
  3595. if (globalVariable)
  3596. return globalVariable;
  3597. }
  3598. auto typeTypeDef = ResolveTypeDef(mCompiler->mTypeTypeDef);
  3599. auto typeTypeInst = typeTypeDef->ToTypeInstance();
  3600. auto typeInstance = type->ToTypeInstance();
  3601. StringT<128> typeDataName;
  3602. if (typeInstance != NULL)
  3603. {
  3604. BfMangler::MangleStaticFieldName(typeDataName, mCompiler->GetMangleKind(), typeInstance, "sBfTypeData");
  3605. }
  3606. else
  3607. {
  3608. typeDataName += "sBfTypeData.";
  3609. BfMangler::Mangle(typeDataName, mCompiler->GetMangleKind(), type);
  3610. }
  3611. BfLogSysM("Creating TypeData %s\n", typeDataName.c_str());
  3612. globalVariable = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapTypeInst(typeTypeInst, BfIRPopulateType_Full), true, BfIRLinkageType_External, BfIRValue(), typeDataName);
  3613. mTypeDataRefs[type] = globalVariable;
  3614. return globalVariable;
  3615. }
  3616. BfIRValue BfModule::CreateTypeData(BfType* type, Dictionary<int, int>& usedStringIdMap, bool forceReflectFields, bool needsTypeData, bool needsTypeNames, bool needsVData)
  3617. {
  3618. if ((mCompiler->IsHotCompile()) && (!type->mDirty))
  3619. return BfIRValue();
  3620. BfIRValue* irValuePtr = NULL;
  3621. if (mTypeDataRefs.TryGetValue(type, &irValuePtr))
  3622. {
  3623. return *irValuePtr;
  3624. }
  3625. BfTypeInstance* typeInstance = type->ToTypeInstance();
  3626. BfType* typeInstanceType = ResolveTypeDef(mCompiler->mReflectTypeInstanceTypeDef);
  3627. mBfIRBuilder->PopulateType(typeInstanceType, BfIRPopulateType_Full_ForceDefinition);
  3628. if (typeInstanceType == NULL)
  3629. {
  3630. AssertErrorState();
  3631. return BfIRValue();
  3632. }
  3633. BfIRValue typeTypeData;
  3634. int typeFlags = 0;
  3635. if (needsTypeData)
  3636. {
  3637. BfTypeInstance* typeInstanceTypeInstance = typeInstanceType->ToTypeInstance();
  3638. BfTypeInstance* typeDataSource = NULL;
  3639. if (typeInstance != NULL)
  3640. {
  3641. if (typeInstance->IsUnspecializedType())
  3642. {
  3643. typeDataSource = ResolveTypeDef(mCompiler->mReflectUnspecializedGenericType)->ToTypeInstance();
  3644. typeFlags |= BfTypeFlags_UnspecializedGeneric;
  3645. }
  3646. else if (typeInstance->IsArray())
  3647. {
  3648. typeDataSource = ResolveTypeDef(mCompiler->mReflectArrayType)->ToTypeInstance();
  3649. typeFlags |= BfTypeFlags_Array;
  3650. }
  3651. else if (typeInstance->IsGenericTypeInstance())
  3652. {
  3653. typeDataSource = ResolveTypeDef(mCompiler->mReflectSpecializedGenericType)->ToTypeInstance();
  3654. typeFlags |= BfTypeFlags_SpecializedGeneric;
  3655. }
  3656. else
  3657. typeDataSource = typeInstanceTypeInstance;
  3658. }
  3659. else if (type->IsPointer())
  3660. typeDataSource = ResolveTypeDef(mCompiler->mReflectPointerType)->ToTypeInstance();
  3661. else if (type->IsSizedArray())
  3662. typeDataSource = ResolveTypeDef(mCompiler->mReflectSizedArrayType)->ToTypeInstance();
  3663. else
  3664. typeDataSource = mContext->mBfTypeType;
  3665. if ((!mTypeDataRefs.ContainsKey(typeDataSource)) && (typeDataSource != type))
  3666. {
  3667. CreateTypeData(typeDataSource, usedStringIdMap, false, true, needsTypeNames, true);
  3668. }
  3669. typeTypeData = CreateClassVDataGlobal(typeDataSource);
  3670. }
  3671. else
  3672. typeTypeData = CreateClassVDataGlobal(typeInstanceType->ToTypeInstance());
  3673. BfType* longType = GetPrimitiveType(BfTypeCode_Int64);
  3674. BfType* intType = GetPrimitiveType(BfTypeCode_Int32);
  3675. BfType* shortType = GetPrimitiveType(BfTypeCode_Int16);
  3676. BfType* byteType = GetPrimitiveType(BfTypeCode_Int8);
  3677. BfType* typeIdType = intType;
  3678. auto voidPtrType = GetPrimitiveType(BfTypeCode_NullPtr);
  3679. auto voidPtrIRType = mBfIRBuilder->MapType(voidPtrType);
  3680. auto voidPtrPtrIRType = mBfIRBuilder->GetPointerTo(voidPtrIRType);
  3681. auto voidPtrNull = GetDefaultValue(voidPtrType);
  3682. SizedArray<BfIRValue, 4> typeValueParams;
  3683. GetConstClassValueParam(typeTypeData, typeValueParams);
  3684. BfIRValue objectData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(mContext->mBfObjectType, BfIRPopulateType_Full), typeValueParams);
  3685. StringT<128> typeDataName;
  3686. if ((typeInstance != NULL) && (!typeInstance->IsTypeAlias()))
  3687. {
  3688. BfMangler::MangleStaticFieldName(typeDataName, mCompiler->GetMangleKind(), typeInstance, "sBfTypeData");
  3689. if (typeInstance->mTypeDef->IsGlobalsContainer())
  3690. typeDataName += "`G`" + typeInstance->mTypeDef->mProject->mName;
  3691. }
  3692. else
  3693. {
  3694. typeDataName += "sBfTypeData.";
  3695. BfMangler::Mangle(typeDataName, mCompiler->GetMangleKind(), type, mContext->mScratchModule);
  3696. }
  3697. int typeCode = BfTypeCode_None;
  3698. if (typeInstance != NULL)
  3699. {
  3700. typeCode = typeInstance->mTypeDef->mTypeCode;
  3701. }
  3702. else if (type->IsPrimitiveType())
  3703. {
  3704. BfPrimitiveType* primType = (BfPrimitiveType*)type;
  3705. typeCode = primType->mTypeDef->mTypeCode;
  3706. }
  3707. else if (type->IsPointer())
  3708. {
  3709. typeCode = BfTypeCode_Pointer;
  3710. typeFlags |= BfTypeFlags_Pointer;
  3711. }
  3712. if (type->IsObject())
  3713. {
  3714. typeFlags |= BfTypeFlags_Object;
  3715. BfMethodInstance* methodInstance = typeInstance->mVirtualMethodTable[mCompiler->GetVTableMethodOffset() + 0].mImplementingMethod;
  3716. if (methodInstance->GetOwner() != mContext->mBfObjectType)
  3717. typeFlags |= BfTypeFlags_HasDestructor;
  3718. }
  3719. if (type->IsStruct())
  3720. typeFlags |= BfTypeFlags_Struct;
  3721. if (type->IsBoxed())
  3722. {
  3723. typeFlags |= BfTypeFlags_Boxed;
  3724. if (((BfBoxedType*)type)->IsBoxedStructPtr())
  3725. typeFlags |= BfTypeFlags_Pointer;
  3726. }
  3727. if (type->IsPrimitiveType())
  3728. typeFlags |= BfTypeFlags_Primitive;
  3729. if (type->IsTypedPrimitive())
  3730. typeFlags |= BfTypeFlags_TypedPrimitive;
  3731. if (type->IsTuple())
  3732. typeFlags |= BfTypeFlags_Tuple;
  3733. if (type->IsNullable())
  3734. typeFlags |= BfTypeFlags_Nullable;
  3735. if (type->IsSizedArray())
  3736. typeFlags |= BfTypeFlags_SizedArray;
  3737. if (type->IsSplattable())
  3738. typeFlags |= BfTypeFlags_Splattable;
  3739. if (type->IsUnion())
  3740. typeFlags |= BfTypeFlags_Union;
  3741. if (type->IsDelegate())
  3742. typeFlags |= BfTypeFlags_Delegate;
  3743. if (type->WantsGCMarking())
  3744. typeFlags |= BfTypeFlags_WantsMarking;
  3745. int memberDataOffset = 0;
  3746. if (typeInstance != NULL)
  3747. {
  3748. for (auto& fieldInstance : typeInstance->mFieldInstances)
  3749. {
  3750. if (fieldInstance.mDataOffset != -1)
  3751. {
  3752. memberDataOffset = fieldInstance.mDataOffset;
  3753. break;
  3754. }
  3755. }
  3756. }
  3757. SizedArray<BfIRValue, 8> typeDataParams =
  3758. {
  3759. objectData,
  3760. GetConstValue(type->mSize, intType), // mSize
  3761. GetConstValue(type->mTypeId, typeIdType), // mTypeId
  3762. GetConstValue(typeFlags, intType), // mTypeFlags
  3763. GetConstValue(memberDataOffset, intType), // mMemberDataOffset
  3764. GetConstValue(typeCode, byteType), // mTypeCode
  3765. GetConstValue(type->mAlign, byteType),
  3766. };
  3767. auto typeData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(mContext->mBfTypeType, BfIRPopulateType_Full), typeDataParams);
  3768. if (typeInstance == NULL)
  3769. {
  3770. BfIRValue typeDataVar;
  3771. if (needsTypeData)
  3772. {
  3773. if (type->IsPointer())
  3774. {
  3775. auto pointerType = (BfPointerType*)type;
  3776. SizedArray<BfIRValue, 3> pointerTypeDataParms =
  3777. {
  3778. typeData,
  3779. GetConstValue(pointerType->mElementType->mTypeId, typeIdType),
  3780. };
  3781. auto reflectPointerType = ResolveTypeDef(mCompiler->mReflectPointerType)->ToTypeInstance();
  3782. auto pointerTypeData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(reflectPointerType, BfIRPopulateType_Full), pointerTypeDataParms);
  3783. typeDataVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapTypeInst(reflectPointerType), true,
  3784. BfIRLinkageType_External, pointerTypeData, typeDataName);
  3785. typeDataVar = mBfIRBuilder->CreateBitCast(typeDataVar, mBfIRBuilder->MapType(mContext->mBfTypeType));
  3786. }
  3787. else if (type->IsSizedArray())
  3788. {
  3789. auto sizedArrayType = (BfSizedArrayType*)type;
  3790. SizedArray<BfIRValue, 3> sizedArrayTypeDataParms =
  3791. {
  3792. typeData,
  3793. GetConstValue(sizedArrayType->mElementType->mTypeId, typeIdType),
  3794. GetConstValue(sizedArrayType->mElementCount, intType)
  3795. };
  3796. auto reflectSizedArrayType = ResolveTypeDef(mCompiler->mReflectSizedArrayType)->ToTypeInstance();
  3797. auto sizedArrayTypeData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(reflectSizedArrayType, BfIRPopulateType_Full), sizedArrayTypeDataParms);
  3798. typeDataVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapTypeInst(reflectSizedArrayType), true,
  3799. BfIRLinkageType_External, sizedArrayTypeData, typeDataName);
  3800. typeDataVar = mBfIRBuilder->CreateBitCast(typeDataVar, mBfIRBuilder->MapType(mContext->mBfTypeType));
  3801. }
  3802. else
  3803. {
  3804. typeDataVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapTypeInst(mContext->mBfTypeType), true,
  3805. BfIRLinkageType_External, typeData, typeDataName);
  3806. }
  3807. }
  3808. else
  3809. typeDataVar = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(mContext->mBfTypeType));
  3810. mTypeDataRefs[typeInstance] = typeDataVar;
  3811. return typeDataVar;
  3812. }
  3813. // Reserve position
  3814. mTypeDataRefs[typeInstance] = BfIRValue();
  3815. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  3816. BfTypeDef* typeDef = typeInstance->mTypeDef;
  3817. StringT<128> mangledName;
  3818. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), typeInstance, typeInstance->mModule);
  3819. for (int methodIdx = 0; methodIdx < (int)typeDef->mMethods.size(); methodIdx++)
  3820. {
  3821. auto methodDef = typeDef->mMethods[methodIdx];
  3822. auto methodInstance = typeInstance->mMethodInstanceGroups[methodIdx].mDefault;
  3823. if (methodInstance == NULL)
  3824. continue;
  3825. if (typeInstance->IsUnspecializedType())
  3826. continue;
  3827. if (!typeInstance->IsTypeMemberAccessible(methodDef->mDeclaringType, mProject))
  3828. {
  3829. if (methodInstance->mChainType == BfMethodChainType_ChainMember)
  3830. {
  3831. BF_ASSERT(!methodInstance->GetOwner()->IsUnspecializedType());
  3832. // We need to create an empty thunk for this chained method
  3833. BfIRFunction func = CreateFunctionFrom(methodInstance, false, methodInstance->mAlwaysInline);
  3834. mBfIRBuilder->SetActiveFunction(func);
  3835. auto block = mBfIRBuilder->CreateBlock("entry", true);
  3836. mBfIRBuilder->SetInsertPoint(block);
  3837. mBfIRBuilder->CreateRetVoid();
  3838. mBfIRBuilder->SetActiveFunction(BfIRFunction());
  3839. }
  3840. }
  3841. }
  3842. SizedArray<BfIRValue, 32> vData;
  3843. BfIRValue classVDataVar;
  3844. String classVDataName;
  3845. if (typeInstance->mSlotNum >= 0)
  3846. {
  3847. // For interfaces we ONLY emit the slot num
  3848. int virtSlotIdx = typeInstance->mSlotNum + 1 + mCompiler->GetDynCastVDataCount();
  3849. StringT<128> slotVarName;
  3850. BfMangler::MangleStaticFieldName(slotVarName, mCompiler->GetMangleKind(), typeInstance, "sBfSlotOfs");
  3851. auto intType = GetPrimitiveType(BfTypeCode_Int32);
  3852. auto slotNumVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapType(intType), true, BfIRLinkageType_External,
  3853. GetConstValue32(virtSlotIdx), slotVarName);
  3854. }
  3855. else if ((typeInstance->IsObject()) && (!typeInstance->IsUnspecializedType()) && (needsVData))
  3856. {
  3857. int dynCastDataElems = 0;
  3858. int numElements = 1;
  3859. int vDataOfs = 1; // The number of intptrs before the iface slot map
  3860. numElements += mCompiler->mMaxInterfaceSlots;
  3861. if (!typeInstance->IsInterface())
  3862. {
  3863. dynCastDataElems = 1 + mCompiler->mMaxInterfaceSlots;
  3864. numElements += mCompiler->GetDynCastVDataCount();
  3865. numElements += typeInstance->mVirtualMethodTableSize;
  3866. }
  3867. int expectNumElements = 0;
  3868. if (!typeDef->mIsStatic)
  3869. {
  3870. classVDataVar = CreateClassVDataGlobal(typeInstance, &expectNumElements, &classVDataName);
  3871. }
  3872. vData.push_back(BfIRValue()); // Type*
  3873. SizedArray<BfIRValue, 1> extVTableData;
  3874. SizedArrayImpl<BfIRValue>* vFuncDataExt = &extVTableData;
  3875. if (!typeInstance->IsInterface())
  3876. {
  3877. Array<int32> dynCastData;
  3878. if (typeInstance->IsBoxed())
  3879. {
  3880. auto underlyingType = typeInstance->GetUnderlyingType()->ToTypeInstance();
  3881. dynCastData.Add(underlyingType->mInheritanceId);
  3882. }
  3883. else
  3884. dynCastData.Add(typeInstance->mInheritanceId);
  3885. for (int i = 0; i < mCompiler->mMaxInterfaceSlots; i++)
  3886. dynCastData.Add(0);
  3887. dynCastData.Add(0);
  3888. auto checkTypeInst = typeInstance;
  3889. while (checkTypeInst != NULL)
  3890. {
  3891. for (auto&& interfaceEntry : checkTypeInst->mInterfaces)
  3892. {
  3893. if (interfaceEntry.mInterfaceType->mSlotNum >= 0)
  3894. {
  3895. if (dynCastData[interfaceEntry.mInterfaceType->mSlotNum + 1] == 0)
  3896. dynCastData[interfaceEntry.mInterfaceType->mSlotNum + 1] = interfaceEntry.mInterfaceType->mTypeId;
  3897. }
  3898. }
  3899. checkTypeInst = checkTypeInst->GetImplBaseType();
  3900. }
  3901. if (mSystem->mPtrSize == 8)
  3902. {
  3903. int intPtrCount = (dynCastDataElems + 1) / 2;
  3904. vDataOfs += intPtrCount;
  3905. uint64* intPtrData = (uint64*)&dynCastData[0];
  3906. for (int i = 0; i < intPtrCount; i++)
  3907. {
  3908. uint64 val = intPtrData[i];
  3909. if (val == 0)
  3910. {
  3911. vData.push_back(voidPtrNull);
  3912. }
  3913. else
  3914. {
  3915. auto intPtrVal = mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, val);
  3916. vData.push_back(mBfIRBuilder->CreateBitCast(intPtrVal, voidPtrIRType));
  3917. }
  3918. }
  3919. }
  3920. else
  3921. {
  3922. int intPtrCount = dynCastDataElems;
  3923. vDataOfs += intPtrCount;
  3924. uint32* intPtrData = (uint32*)&dynCastData[0];
  3925. for (int i = 0; i < intPtrCount; i++)
  3926. {
  3927. uint32 val = intPtrData[i];
  3928. if (val == 0)
  3929. {
  3930. vData.push_back(voidPtrNull);
  3931. }
  3932. else
  3933. {
  3934. auto intPtrVal = mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, (int)val);
  3935. vData.push_back(mBfIRBuilder->CreateBitCast(intPtrVal, voidPtrIRType));
  3936. }
  3937. }
  3938. }
  3939. }
  3940. for (int iSlotIdx = 0; iSlotIdx < mCompiler->mMaxInterfaceSlots; iSlotIdx++)
  3941. vData.push_back(voidPtrNull);
  3942. struct _InterfaceMatchEntry
  3943. {
  3944. BfTypeInterfaceEntry* mEntry;
  3945. BfTypeInstance* mEntrySource;
  3946. Array<BfTypeInterfaceEntry*> mAmbiguousEntries;
  3947. };
  3948. int highestIFaceVirtIdx = 0;
  3949. Dictionary<BfTypeInstance*, _InterfaceMatchEntry> interfaceMap;
  3950. auto checkTypeInst = typeInstance;
  3951. bool forceInterfaceSet = false;
  3952. while (checkTypeInst != NULL)
  3953. {
  3954. for (auto&& interfaceEntry : checkTypeInst->mInterfaces)
  3955. {
  3956. highestIFaceVirtIdx = BF_MAX(highestIFaceVirtIdx, interfaceEntry.mStartVirtualIdx + interfaceEntry.mInterfaceType->mVirtualMethodTableSize);
  3957. if (!typeInstance->IsTypeMemberAccessible(interfaceEntry.mDeclaringType, mProject))
  3958. continue;
  3959. _InterfaceMatchEntry* matchEntry = NULL;
  3960. if (interfaceMap.TryGetValue(interfaceEntry.mInterfaceType, &matchEntry))
  3961. {
  3962. auto prevEntry = matchEntry->mEntry;
  3963. bool isBetter = TypeIsSubTypeOf(checkTypeInst, matchEntry->mEntrySource);
  3964. bool isWorse = TypeIsSubTypeOf(matchEntry->mEntrySource, checkTypeInst);
  3965. if (forceInterfaceSet)
  3966. {
  3967. isBetter = true;
  3968. isWorse = false;
  3969. }
  3970. if (isBetter == isWorse)
  3971. CompareDeclTypes(interfaceEntry.mDeclaringType, prevEntry->mDeclaringType, isBetter, isWorse);
  3972. if (isBetter == isWorse)
  3973. {
  3974. if (matchEntry->mAmbiguousEntries.empty())
  3975. matchEntry->mAmbiguousEntries.push_back(prevEntry);
  3976. matchEntry->mAmbiguousEntries.push_back(&interfaceEntry);
  3977. continue;
  3978. }
  3979. else if (isBetter)
  3980. {
  3981. matchEntry->mEntry = &interfaceEntry;
  3982. matchEntry->mEntrySource = checkTypeInst;
  3983. matchEntry->mAmbiguousEntries.Clear();
  3984. }
  3985. else
  3986. continue;
  3987. }
  3988. else
  3989. {
  3990. _InterfaceMatchEntry matchEntry;
  3991. matchEntry.mEntry = &interfaceEntry;
  3992. matchEntry.mEntrySource = checkTypeInst;
  3993. interfaceMap[interfaceEntry.mInterfaceType] = matchEntry;
  3994. }
  3995. }
  3996. checkTypeInst = checkTypeInst->GetImplBaseType();
  3997. }
  3998. for (auto interfacePair : interfaceMap)
  3999. {
  4000. auto& interfaceMatchEntry = interfacePair.mValue;
  4001. if (!interfaceMatchEntry.mAmbiguousEntries.empty())
  4002. {
  4003. 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());
  4004. if (error != NULL)
  4005. {
  4006. for (auto ambiguiousEntry : interfaceMatchEntry.mAmbiguousEntries)
  4007. mCompiler->mPassInstance->MoreInfo("See other declaration", ambiguiousEntry->mDeclaringType->GetRefNode());
  4008. }
  4009. }
  4010. }
  4011. if ((!typeInstance->IsInterface()) && (typeInstance->mVirtualMethodTableSize > 0) && (needsVData))
  4012. {
  4013. int startTabIdx = (int)vData.size();
  4014. SizedArray<BfTypeInstance*, 8> origVirtTypeStack;
  4015. BfTypeInstance* checkTypeInst = typeInstance;
  4016. while (checkTypeInst != NULL)
  4017. {
  4018. origVirtTypeStack.push_back(checkTypeInst);
  4019. checkTypeInst = checkTypeInst->GetImplBaseType();
  4020. }
  4021. Array<BfVirtualMethodEntry> origVTable;
  4022. int origVirtIdx = 0;
  4023. if (typeInstance->mTypeDef->mIsCombinedPartial)
  4024. {
  4025. HashSet<String> reslotNames;
  4026. for (int virtIdx = 0; virtIdx < (int)typeInstance->mVirtualMethodTable.size(); virtIdx++)
  4027. {
  4028. auto& entry = typeInstance->mVirtualMethodTable[virtIdx];
  4029. if (entry.mDeclaringMethod.mMethodNum == -1)
  4030. continue;
  4031. BfMethodInstance* methodInstance = (BfMethodInstance*)entry.mImplementingMethod;
  4032. if ((methodInstance == NULL) || (!typeInstance->IsTypeMemberAccessible(methodInstance->mMethodDef->mDeclaringType, mProject)))
  4033. {
  4034. if (origVTable.empty())
  4035. origVTable = typeInstance->mVirtualMethodTable;
  4036. BfMethodInstance* declMethodInstance = entry.mDeclaringMethod;
  4037. if (typeInstance->IsTypeMemberAccessible(declMethodInstance->mMethodDef->mDeclaringType, mProject))
  4038. {
  4039. // Prepare to reslot...
  4040. entry.mImplementingMethod = entry.mDeclaringMethod;
  4041. reslotNames.Add(declMethodInstance->mMethodDef->mName);
  4042. }
  4043. else
  4044. {
  4045. // Decl isn't accessible, null out entry
  4046. entry.mImplementingMethod = BfMethodRef();
  4047. }
  4048. }
  4049. }
  4050. if (!reslotNames.IsEmpty())
  4051. {
  4052. BfAmbiguityContext ambiguityContext;
  4053. ambiguityContext.mTypeInstance = typeInstance;
  4054. ambiguityContext.mModule = this;
  4055. ambiguityContext.mIsProjectSpecific = true;
  4056. ambiguityContext.mIsReslotting = true;
  4057. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  4058. for (auto& methodGroup : typeInstance->mMethodInstanceGroups)
  4059. {
  4060. auto methodInstance = methodGroup.mDefault;
  4061. if ((methodInstance == NULL) || (!methodInstance->mMethodDef->mIsOverride))
  4062. continue;
  4063. if (!reslotNames.Contains(methodInstance->mMethodDef->mName))
  4064. continue;
  4065. if (!typeInstance->IsTypeMemberAccessible(methodInstance->mMethodDef->mDeclaringType, mProject))
  4066. continue;
  4067. if ((methodInstance->mChainType != BfMethodChainType_None) && (methodInstance->mChainType != BfMethodChainType_ChainHead))
  4068. continue;
  4069. SlotVirtualMethod(methodInstance, &ambiguityContext);
  4070. }
  4071. ambiguityContext.Finish();
  4072. }
  4073. }
  4074. bool isInExts = false;
  4075. for (int virtIdx = 0; virtIdx < (int)typeInstance->mVirtualMethodTable.size(); virtIdx++)
  4076. {
  4077. BfIRValue vValue = voidPtrNull;
  4078. auto& entry = typeInstance->mVirtualMethodTable[virtIdx];
  4079. BfModuleMethodInstance moduleMethodInst;
  4080. if (entry.mDeclaringMethod.mMethodNum == -1)
  4081. {
  4082. // mMethodNum of -1 indicates a vExt slot rather than an actual method reference
  4083. isInExts = true;
  4084. BfIRValue vExt = CreateClassVDataExtGlobal(entry.mDeclaringMethod.mTypeInstance, typeInstance, virtIdx);
  4085. if (vExt)
  4086. vValue = mBfIRBuilder->CreateBitCast(vExt, voidPtrIRType);
  4087. }
  4088. else
  4089. {
  4090. BfMethodInstance* declaringMethodInstance = (BfMethodInstance*)entry.mDeclaringMethod;
  4091. if ((declaringMethodInstance != NULL) && (declaringMethodInstance->mMethodInstanceGroup->IsImplemented()) && (declaringMethodInstance->mIsReified))
  4092. {
  4093. BF_ASSERT(entry.mImplementingMethod.mTypeInstance->mMethodInstanceGroups[entry.mImplementingMethod.mMethodNum].IsImplemented());
  4094. BF_ASSERT(entry.mImplementingMethod.mTypeInstance->mMethodInstanceGroups[entry.mImplementingMethod.mMethodNum].mDefault->mIsReified);
  4095. BfMethodInstance* methodInstance = (BfMethodInstance*)entry.mImplementingMethod;
  4096. if ((methodInstance != NULL) && (!methodInstance->mMethodDef->mIsAbstract))
  4097. {
  4098. BF_ASSERT(typeInstance->IsTypeMemberAccessible(methodInstance->mMethodDef->mDeclaringType, mProject));
  4099. moduleMethodInst = GetMethodInstanceAtIdx(methodInstance->mMethodInstanceGroup->mOwner, methodInstance->mMethodInstanceGroup->mMethodIdx);
  4100. auto funcPtr = mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, voidPtrIRType);
  4101. vValue = funcPtr;
  4102. }
  4103. }
  4104. }
  4105. while (origVirtTypeStack.size() != 0)
  4106. {
  4107. BfTypeInstance* useTypeInst = origVirtTypeStack[origVirtTypeStack.size() - 1];
  4108. if (virtIdx >= useTypeInst->mVirtualMethodTableSize)
  4109. {
  4110. // Moved past current base vtable size
  4111. origVirtTypeStack.pop_back();
  4112. continue;
  4113. }
  4114. if (origVirtIdx < useTypeInst->GetOrigVTableSize())
  4115. {
  4116. // We are within the original vtable size
  4117. int idx = startTabIdx + origVirtIdx;
  4118. origVirtIdx++;
  4119. vData.push_back(vValue);
  4120. }
  4121. else
  4122. {
  4123. // This is a new entry, it only gets added to the ext
  4124. BF_ASSERT(isInExts);
  4125. }
  4126. break;
  4127. }
  4128. }
  4129. if (!origVTable.empty())
  4130. typeInstance->mVirtualMethodTable = origVTable;
  4131. }
  4132. int ifaceMethodExtStart = (int)typeInstance->GetIFaceVMethodSize();
  4133. if (typeInstance->mHotTypeData != NULL)
  4134. {
  4135. if (typeInstance->mHotTypeData->mOrigInterfaceMethodsLength != -1)
  4136. ifaceMethodExtStart = typeInstance->mHotTypeData->mOrigInterfaceMethodsLength;
  4137. }
  4138. SizedArray<BfIRValue, 32> ifaceMethodExtData;
  4139. int iFaceMethodStartIdx = (int)vData.size();
  4140. vData.resize(iFaceMethodStartIdx + ifaceMethodExtStart);
  4141. for (int i = iFaceMethodStartIdx; i < iFaceMethodStartIdx + ifaceMethodExtStart; i++)
  4142. vData[i] = voidPtrNull;
  4143. if (expectNumElements != 0)
  4144. BF_ASSERT(expectNumElements == vData.size());
  4145. //BF_ASSERT(vData.size() == expectNumElements);
  4146. // for (int i = 0; i < (int)typeInstance->mInterfaceMethodTable.size() - ifaceMethodExtStart; i++)
  4147. // ifaceMethodExtData.Add(voidPtrNull);
  4148. int ifaceEntryIdx = iFaceMethodStartIdx;
  4149. for (auto& interfacePair : interfaceMap)
  4150. {
  4151. auto interfaceEntry = interfacePair.mValue.mEntry;
  4152. bool makeEmpty = false;
  4153. if (!typeInstance->IsTypeMemberAccessible(interfaceEntry->mDeclaringType, mProject))
  4154. makeEmpty = true;
  4155. int endVirtualIdx = interfaceEntry->mStartVirtualIdx + interfaceEntry->mInterfaceType->mVirtualMethodTableSize;
  4156. bool useExt = endVirtualIdx > ifaceMethodExtStart;
  4157. for (int methodIdx = 0; methodIdx < (int)interfaceEntry->mInterfaceType->mMethodInstanceGroups.size(); methodIdx++)
  4158. {
  4159. BfIRValue pushValue;
  4160. BfMethodInstance* ifaceMethodInstance = interfaceEntry->mInterfaceType->mMethodInstanceGroups[methodIdx].mDefault;
  4161. if ((ifaceMethodInstance == NULL) || (ifaceMethodInstance->mVirtualTableIdx == -1))
  4162. continue;
  4163. if ((!ifaceMethodInstance->mIsReified) || (!ifaceMethodInstance->mMethodInstanceGroup->IsImplemented()))
  4164. continue;
  4165. if (makeEmpty)
  4166. {
  4167. pushValue = voidPtrNull;
  4168. }
  4169. else
  4170. {
  4171. auto& methodRef = typeInstance->mInterfaceMethodTable[interfaceEntry->mStartInterfaceTableIdx + methodIdx].mMethodRef;
  4172. auto methodInstance = (BfMethodInstance*)methodRef;
  4173. if ((methodInstance != NULL) && (!methodInstance->mMethodDef->mIsAbstract))
  4174. {
  4175. BF_ASSERT(methodInstance->mIsReified);
  4176. // This doesn't work because we may have FOREIGN methods from implicit interface methods
  4177. //auto moduleMethodInst = GetMethodInstanceAtIdx(methodRef.mTypeInstance, methodRef.mMethodNum);
  4178. auto moduleMethodInst = ReferenceExternalMethodInstance(methodInstance);
  4179. auto funcPtr = mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, voidPtrIRType);
  4180. pushValue = funcPtr;
  4181. }
  4182. else
  4183. {
  4184. pushValue = voidPtrNull;
  4185. }
  4186. }
  4187. int idx = interfaceEntry->mStartVirtualIdx + ifaceMethodInstance->mVirtualTableIdx;
  4188. if (idx < ifaceMethodExtStart)
  4189. {
  4190. BF_ASSERT(iFaceMethodStartIdx + idx < (int)vData.size());
  4191. vData[iFaceMethodStartIdx + idx] = pushValue;
  4192. }
  4193. else
  4194. {
  4195. BF_ASSERT(useExt);
  4196. int extIdx = idx - ifaceMethodExtStart;
  4197. while (extIdx >= ifaceMethodExtData.size())
  4198. ifaceMethodExtData.Add(voidPtrNull);
  4199. ifaceMethodExtData[extIdx] = pushValue;
  4200. }
  4201. }
  4202. }
  4203. if (typeInstance->IsBoxed())
  4204. {
  4205. BfBoxedType* boxedType = (BfBoxedType*)typeInstance;
  4206. if (boxedType->IsBoxedStructPtr())
  4207. {
  4208. // Force override of GetHashCode so we use the pointer address as the hash code
  4209. checkTypeInst = CreateBoxedType(ResolveTypeDef(mCompiler->mPointerTypeDef));
  4210. // Force override of GetHashCode so we use the pointer address as the hash code
  4211. for (auto& checkIFace : checkTypeInst->mInterfaces)
  4212. {
  4213. for (int methodIdx = 0; methodIdx < (int)checkIFace.mInterfaceType->mMethodInstanceGroups.size(); methodIdx++)
  4214. {
  4215. BfIRValue pushValue;
  4216. BfMethodInstance* ifaceMethodInstance = checkIFace.mInterfaceType->mMethodInstanceGroups[methodIdx].mDefault;
  4217. if ((ifaceMethodInstance == NULL) || (ifaceMethodInstance->mVirtualTableIdx == -1))
  4218. continue;
  4219. if ((!ifaceMethodInstance->mIsReified) || (!ifaceMethodInstance->mMethodInstanceGroup->IsImplemented()))
  4220. continue;
  4221. auto& methodRef = checkTypeInst->mInterfaceMethodTable[checkIFace.mStartInterfaceTableIdx + methodIdx].mMethodRef;
  4222. auto methodInstance = (BfMethodInstance*)methodRef;
  4223. BF_ASSERT(methodInstance->mIsReified);
  4224. // This doesn't work because we may have FOREIGN methods from implicit interface methods
  4225. //auto moduleMethodInst = GetMethodInstanceAtIdx(methodRef.mTypeInstance, methodRef.mMethodNum);
  4226. auto moduleMethodInst = ReferenceExternalMethodInstance(methodInstance);
  4227. auto funcPtr = mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, voidPtrIRType);
  4228. int idx = checkIFace.mStartVirtualIdx + ifaceMethodInstance->mVirtualTableIdx;
  4229. vData[iFaceMethodStartIdx + idx] = funcPtr;
  4230. }
  4231. }
  4232. }
  4233. }
  4234. if ((needsVData) && (!typeInstance->mTypeDef->mIsStatic))
  4235. {
  4236. BfIRValue ifaceMethodExtVar;
  4237. if (!ifaceMethodExtData.IsEmpty())
  4238. {
  4239. StringT<128> classVDataName;
  4240. BfMangler::MangleStaticFieldName(classVDataName, mCompiler->GetMangleKind(), typeInstance, "bf_hs_replace_IFaceExt");
  4241. auto arrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr), (int)ifaceMethodExtData.size());
  4242. ifaceMethodExtVar = mBfIRBuilder->CreateGlobalVariable(arrayType, true,
  4243. BfIRLinkageType_External, BfIRValue(), classVDataName);
  4244. BfIRType extVTableType = mBfIRBuilder->GetSizedArrayType(voidPtrIRType, (int)ifaceMethodExtData.size());
  4245. BfIRValue extVTableConst = mBfIRBuilder->CreateConstArray(extVTableType, ifaceMethodExtData);
  4246. mBfIRBuilder->GlobalVar_SetInitializer(ifaceMethodExtVar, extVTableConst);
  4247. }
  4248. for (auto& ifaceInstPair : interfaceMap)
  4249. {
  4250. auto interfaceEntry = ifaceInstPair.mValue.mEntry;
  4251. int slotNum = interfaceEntry->mInterfaceType->mSlotNum;
  4252. if (slotNum >= 0)
  4253. {
  4254. BfIRValue vtablePtr;
  4255. int idx = interfaceEntry->mStartVirtualIdx;
  4256. int endVirtualIdx = interfaceEntry->mStartVirtualIdx + interfaceEntry->mInterfaceType->mVirtualMethodTableSize;
  4257. if (endVirtualIdx > ifaceMethodExtStart)
  4258. vtablePtr = mBfIRBuilder->CreateInBoundsGEP(ifaceMethodExtVar, 0, interfaceEntry->mStartVirtualIdx - ifaceMethodExtStart);
  4259. else
  4260. vtablePtr = mBfIRBuilder->CreateInBoundsGEP(classVDataVar, 0, iFaceMethodStartIdx + interfaceEntry->mStartVirtualIdx);
  4261. int slotVirtIdx = slotNum + vDataOfs;
  4262. if (vData[slotVirtIdx] == voidPtrNull)
  4263. {
  4264. vData[slotVirtIdx] = mBfIRBuilder->CreateBitCast(vtablePtr, voidPtrIRType);
  4265. }
  4266. else
  4267. {
  4268. if (mCompiler->IsHotCompile())
  4269. Fail("Interface slot collision error. Restart program or undo interface changes.", typeDef->GetRefNode());
  4270. else
  4271. Fail("Interface slot collision error", typeDef->GetRefNode());
  4272. }
  4273. }
  4274. }
  4275. }
  4276. }
  4277. BfIRValue typeNameConst;
  4278. BfIRValue namespaceConst;
  4279. if (needsTypeNames)
  4280. {
  4281. typeNameConst = GetStringObjectValue(typeDef->mName->mString, true);
  4282. namespaceConst = GetStringObjectValue(typeDef->mNamespace.ToString(), true);
  4283. }
  4284. else
  4285. {
  4286. auto stringType = ResolveTypeDef(mCompiler->mStringTypeDef);
  4287. typeNameConst = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(stringType));
  4288. namespaceConst = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(stringType));
  4289. }
  4290. int baseTypeId = 0;
  4291. if (typeInstance->mBaseType != NULL)
  4292. {
  4293. baseTypeId = typeInstance->mBaseType->mTypeId;
  4294. }
  4295. SizedArray<BfIRValue, 16> customAttrs;
  4296. BfTypeInstance* attributeType = mContext->mUnreifiedModule->ResolveTypeDef(mCompiler->mAttributeTypeDef)->ToTypeInstance();
  4297. BfIRValue castedClassVData;
  4298. if (classVDataVar)
  4299. castedClassVData = mBfIRBuilder->CreateBitCast(classVDataVar, mBfIRBuilder->MapType(mContext->mBfClassVDataPtrType));
  4300. else
  4301. castedClassVData = GetDefaultValue(mContext->mBfClassVDataPtrType);
  4302. bool freflectIncludeTypeData = false;
  4303. bool reflectIncludeAllFields = false;
  4304. bool reflectIncludeAllMethods = false;
  4305. if (TypeIsSubTypeOf(typeInstance, attributeType))
  4306. {
  4307. reflectIncludeAllFields = true;
  4308. reflectIncludeAllMethods = true;
  4309. }
  4310. enum ReflectKind
  4311. {
  4312. ReflectKind_None = 0,
  4313. ReflectKind_Type = 1,
  4314. ReflectKind_NonStaticFields = 2,
  4315. ReflectKind_StaticFields = 4,
  4316. ReflectKind_DefaultConstructor = 8,
  4317. ReflectKind_Constructors = 0x10,
  4318. ReflectKind_StaticMethods = 0x20,
  4319. ReflectKind_Methods = 0x40,
  4320. ReflectKind_User = 0x80,
  4321. ReflectKind_All = 0x7F,
  4322. ReflectKind_ApplyToInnerTypes = 0x80
  4323. };
  4324. ReflectKind reflectKind = ReflectKind_Type;
  4325. auto _GetReflectUser = [&](BfTypeInstance* attrType)
  4326. {
  4327. ReflectKind reflectKind = ReflectKind_None;
  4328. if (attrType->mCustomAttributes != NULL)
  4329. {
  4330. for (auto& customAttr : attrType->mCustomAttributes->mAttributes)
  4331. {
  4332. if (customAttr.mType->mTypeDef->mName->ToString() == "AttributeUsageAttribute")
  4333. {
  4334. for (auto& prop : customAttr.mSetProperties)
  4335. {
  4336. auto propDef = prop.mPropertyRef.mTypeInstance->mTypeDef->mProperties[prop.mPropertyRef.mPropIdx];
  4337. if (propDef->mName == "ReflectUser")
  4338. {
  4339. if (prop.mParam.mValue.IsConst())
  4340. {
  4341. auto constant = attrType->mConstHolder->GetConstant(prop.mParam.mValue);
  4342. reflectKind = (ReflectKind)(reflectKind | (ReflectKind)constant->mInt32);
  4343. }
  4344. }
  4345. }
  4346. // Check for Flags arg
  4347. if (customAttr.mCtorArgs.size() < 2)
  4348. continue;
  4349. auto constant = attrType->mConstHolder->GetConstant(customAttr.mCtorArgs[1]);
  4350. if (constant == NULL)
  4351. continue;
  4352. if (constant->mTypeCode == BfTypeCode_Boolean)
  4353. continue;
  4354. if ((constant->mInt8 & BfCustomAttributeFlags_ReflectAttribute) != 0)
  4355. reflectKind = (ReflectKind)(reflectKind | ReflectKind_User);
  4356. }
  4357. }
  4358. }
  4359. return reflectKind;
  4360. };
  4361. auto _GetReflectUserFromDirective = [&](BfAttributeDirective* attributesDirective, BfAttributeTargets attrTarget)
  4362. {
  4363. ReflectKind reflectKind = ReflectKind_None;
  4364. auto customAttrs = GetCustomAttributes(attributesDirective, attrTarget);
  4365. if (customAttrs != NULL)
  4366. {
  4367. for (auto& attr : customAttrs->mAttributes)
  4368. {
  4369. reflectKind = (ReflectKind)(reflectKind | _GetReflectUser(attr.mType));
  4370. }
  4371. }
  4372. return reflectKind;
  4373. };
  4374. //
  4375. {
  4376. auto checkTypeInstance = typeInstance;
  4377. while (checkTypeInstance != NULL)
  4378. {
  4379. if (checkTypeInstance->mCustomAttributes != NULL)
  4380. {
  4381. auto checkReflectKind = ReflectKind_None;
  4382. for (auto& customAttr : checkTypeInstance->mCustomAttributes->mAttributes)
  4383. {
  4384. if (customAttr.mType->mTypeDef->mName->ToString() == "ReflectAttribute")
  4385. {
  4386. if (customAttr.mCtorArgs.size() > 0)
  4387. {
  4388. auto constant = checkTypeInstance->mConstHolder->GetConstant(customAttr.mCtorArgs[0]);
  4389. checkReflectKind = (ReflectKind)((int)checkReflectKind | constant->mInt32);
  4390. }
  4391. else
  4392. {
  4393. checkReflectKind = ReflectKind_All;
  4394. }
  4395. }
  4396. else
  4397. {
  4398. auto userReflectKind = _GetReflectUser(customAttr.mType);
  4399. checkReflectKind = (ReflectKind)(checkReflectKind | userReflectKind);
  4400. }
  4401. }
  4402. if ((checkTypeInstance == typeInstance) ||
  4403. ((checkReflectKind & ReflectKind_ApplyToInnerTypes) != 0))
  4404. {
  4405. reflectKind = (ReflectKind)(reflectKind | checkReflectKind);
  4406. }
  4407. }
  4408. checkTypeInstance = GetOuterType(checkTypeInstance);
  4409. }
  4410. }
  4411. // Fields
  4412. BfType* reflectFieldDataType = ResolveTypeDef(mCompiler->mReflectFieldDataDef);
  4413. BfIRValue emptyValueType = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(reflectFieldDataType->ToTypeInstance()->mBaseType), SizedArray<BfIRValue, 1>());
  4414. auto _HandleCustomAttrs = [&](BfCustomAttributes* customAttributes)
  4415. {
  4416. if (customAttributes == NULL)
  4417. return -1;
  4418. Array<BfCustomAttribute*> reflectAttributes;
  4419. for (auto& attr : customAttributes->mAttributes)
  4420. {
  4421. bool wantAttribute = false;
  4422. if (attr.mType->mCustomAttributes != NULL)
  4423. {
  4424. auto usageAttribute = attr.mType->mCustomAttributes->Get(mCompiler->mAttributeUsageAttributeTypeDef);
  4425. if (usageAttribute != NULL)
  4426. {
  4427. // Check for Flags arg
  4428. if (usageAttribute->mCtorArgs.size() < 2)
  4429. continue;
  4430. auto constant = attr.mType->mConstHolder->GetConstant(usageAttribute->mCtorArgs[1]);
  4431. if (constant == NULL)
  4432. continue;
  4433. if (constant->mTypeCode == BfTypeCode_Boolean)
  4434. continue;
  4435. if ((constant->mInt8 & BfCustomAttributeFlags_ReflectAttribute) != 0)
  4436. wantAttribute = true;
  4437. }
  4438. }
  4439. if ((wantAttribute) && (attr.mType->mIsReified))
  4440. {
  4441. reflectAttributes.Add(&attr);
  4442. }
  4443. }
  4444. if (reflectAttributes.size() == 0)
  4445. return -1;
  4446. #define PUSH_INT8(val) data.push_back((uint8)val)
  4447. #define PUSH_INT16(val) { data.push_back(val & 0xFF); data.push_back((val >> 8) & 0xFF); }
  4448. #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); }
  4449. #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); \
  4450. data.push_back((val >> 32) & 0xFF); data.push_back((val >> 40) & 0xFF); data.push_back((val >> 48) & 0xFF); data.push_back((val >> 56) & 0xFF); }
  4451. SizedArray<uint8, 16> data;
  4452. int customAttrIdx = (int)customAttrs.size();
  4453. data.push_back((uint8)reflectAttributes.size());
  4454. for (auto attr : reflectAttributes)
  4455. {
  4456. // Size prefix
  4457. int sizeIdx = (int)data.size();
  4458. PUSH_INT16(0); // mSize
  4459. PUSH_INT32(attr->mType->mTypeId); // mType
  4460. PUSH_INT16(attr->mCtor->mIdx);
  4461. auto ctorMethodInstance = GetRawMethodInstanceAtIdx(attr->mType, attr->mCtor->mIdx);
  4462. int argIdx = 0;
  4463. for (auto arg : attr->mCtorArgs)
  4464. {
  4465. auto constant = typeInstance->mConstHolder->GetConstant(arg);
  4466. bool handled = false;
  4467. if (constant != NULL)
  4468. {
  4469. auto argType = ctorMethodInstance->GetParamType(argIdx);
  4470. if (argType->IsObject())
  4471. {
  4472. BF_ASSERT(argType->ToTypeInstance()->mTypeDef == mCompiler->mStringTypeDef);
  4473. int stringId = constant->mInt32;
  4474. int* orderedIdPtr;
  4475. if (usedStringIdMap.TryAdd(stringId, NULL, &orderedIdPtr))
  4476. {
  4477. *orderedIdPtr = (int)usedStringIdMap.size() - 1;
  4478. }
  4479. GetStringObjectValue(stringId);
  4480. PUSH_INT8(0xFF); // String
  4481. PUSH_INT32(*orderedIdPtr);
  4482. continue;
  4483. }
  4484. PUSH_INT8(constant->mTypeCode);
  4485. if ((constant->mTypeCode == BfTypeCode_Int64) ||
  4486. (constant->mTypeCode == BfTypeCode_UInt64) ||
  4487. (constant->mTypeCode == BfTypeCode_Double))
  4488. {
  4489. PUSH_INT64(constant->mInt64);
  4490. }
  4491. else if ((constant->mTypeCode == BfTypeCode_Int32) ||
  4492. (constant->mTypeCode == BfTypeCode_UInt32))
  4493. {
  4494. PUSH_INT32(constant->mInt32);
  4495. }
  4496. else if (constant->mTypeCode == BfTypeCode_Single)
  4497. {
  4498. float val = (float)constant->mDouble;
  4499. PUSH_INT32(*(int*)&val);
  4500. }
  4501. else if ((constant->mTypeCode == BfTypeCode_Int16) ||
  4502. (constant->mTypeCode == BfTypeCode_UInt16))
  4503. {
  4504. PUSH_INT16(constant->mInt16);
  4505. }
  4506. else if ((constant->mTypeCode == BfTypeCode_Int8) ||
  4507. (constant->mTypeCode == BfTypeCode_UInt8))
  4508. {
  4509. PUSH_INT8(constant->mInt8);
  4510. }
  4511. else if (constant->mTypeCode == BfTypeCode_Object)
  4512. {
  4513. BF_FATAL("Unhandled");
  4514. }
  4515. else
  4516. {
  4517. BF_FATAL("Unhandled");
  4518. }
  4519. }
  4520. else if (!handled)
  4521. {
  4522. BF_FATAL("Unhandled");
  4523. }
  4524. argIdx++;
  4525. }
  4526. int size = (int)data.size() - sizeIdx;
  4527. *((uint16*)&data[sizeIdx]) = size;
  4528. }
  4529. #undef PUSH_INT8
  4530. #undef PUSH_INT16
  4531. #undef PUSH_INT32
  4532. SizedArray<BfIRValue, 16> dataValues;
  4533. for (uint8 val : data)
  4534. dataValues.push_back(GetConstValue8(val));
  4535. auto dataArrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->MapType(byteType), (int)data.size());
  4536. auto customAttrConst = mBfIRBuilder->CreateConstArray(dataArrayType, dataValues);
  4537. BfIRValue customAttrArray = mBfIRBuilder->CreateGlobalVariable(dataArrayType, true, BfIRLinkageType_Internal,
  4538. customAttrConst, typeDataName + StrFormat(".customAttr%d", customAttrIdx));
  4539. BfIRValue customAttrArrayPtr = mBfIRBuilder->CreateBitCast(customAttrArray, voidPtrIRType);
  4540. customAttrs.push_back(customAttrArrayPtr);
  4541. return customAttrIdx;
  4542. };
  4543. int typeCustomAttrIdx = _HandleCustomAttrs(typeInstance->mCustomAttributes);
  4544. SizedArray<int, 16> reflectFieldIndices;
  4545. for (int pass = 0; pass < 2; pass++)
  4546. {
  4547. bool skippedField = false;
  4548. reflectFieldIndices.clear();
  4549. for (int fieldIdx = 0; fieldIdx < (int)typeInstance->mFieldInstances.size(); fieldIdx++)
  4550. {
  4551. BfFieldInstance* fieldInstance = &typeInstance->mFieldInstances[fieldIdx];
  4552. BfFieldDef* fieldDef = fieldInstance->GetFieldDef();
  4553. if (fieldDef == NULL)
  4554. continue;
  4555. auto fieldReflectKind = (ReflectKind)(reflectKind & ~ReflectKind_User);
  4556. bool includeField = reflectIncludeAllFields;
  4557. if (fieldInstance->mCustomAttributes != NULL)
  4558. {
  4559. for (auto& customAttr : fieldInstance->mCustomAttributes->mAttributes)
  4560. {
  4561. if (customAttr.mType->mTypeDef->mName->ToString() == "ReflectAttribute")
  4562. {
  4563. includeField = true;
  4564. }
  4565. else
  4566. {
  4567. auto userReflectKind = _GetReflectUser(customAttr.mType);
  4568. fieldReflectKind = (ReflectKind)(fieldReflectKind | userReflectKind);
  4569. }
  4570. }
  4571. }
  4572. if ((fieldReflectKind & ReflectKind_User) != 0)
  4573. includeField = true;
  4574. if ((!fieldDef->mIsStatic) && ((fieldReflectKind & ReflectKind_NonStaticFields) != 0))
  4575. includeField = true;
  4576. if ((fieldDef->mIsStatic) && ((fieldReflectKind & ReflectKind_StaticFields) != 0))
  4577. includeField = true;
  4578. includeField |= forceReflectFields;
  4579. if (!includeField)
  4580. {
  4581. skippedField = true;
  4582. continue;
  4583. }
  4584. reflectFieldIndices.Add(fieldIdx);
  4585. }
  4586. // For a splattable type, we need to either include all fields or zero fields. This is to allow us to correctly splat
  4587. // params for reflected method calls even if we don't have reflection field info for the splatted type. This is
  4588. // possible because we write out a SplatData structure containing just TypeIds in that case
  4589. if (pass == 0)
  4590. {
  4591. if (!typeInstance->IsSplattable())
  4592. break;
  4593. if (!skippedField)
  4594. break;
  4595. if (reflectFieldIndices.size() == 0)
  4596. break;
  4597. }
  4598. }
  4599. SizedArray<BfIRValue, 16> fieldTypes;
  4600. enum FieldFlags
  4601. {
  4602. FieldFlags_Protected = 3,
  4603. FieldFlags_Public = 6,
  4604. FieldFlags_Static = 0x10,
  4605. FieldFlags_Const = 0x40,
  4606. FieldFlags_SpecialName = 0x80,
  4607. FieldFlags_EnumPayload = 0x100,
  4608. FieldFlags_EnumDiscriminator = 0x200
  4609. };
  4610. if ((typeInstance->IsPayloadEnum()) && (!typeInstance->IsBoxed()))
  4611. {
  4612. BfType* payloadType = typeInstance->GetUnionInnerType();
  4613. if (!payloadType->IsValuelessType())
  4614. {
  4615. BfIRValue payloadNameConst = GetStringObjectValue("$payload", true);
  4616. SizedArray<BfIRValue, 8> payloadFieldVals =
  4617. {
  4618. emptyValueType,
  4619. payloadNameConst, // mName
  4620. GetConstValue(0, longType), // mConstValue
  4621. GetConstValue(0, intType), // mDataOffset
  4622. GetConstValue(payloadType->mTypeId, typeIdType), // mFieldTypeId
  4623. GetConstValue(FieldFlags_SpecialName | FieldFlags_EnumPayload, shortType), // mFlags
  4624. GetConstValue(-1, intType), // mCustomAttributesIdx
  4625. };
  4626. auto payloadFieldData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(reflectFieldDataType->ToTypeInstance(), BfIRPopulateType_Full), payloadFieldVals);
  4627. fieldTypes.push_back(payloadFieldData);
  4628. }
  4629. BfType* dscrType = typeInstance->GetDiscriminatorType();
  4630. BfIRValue dscrNameConst = GetStringObjectValue("$discriminator", true);
  4631. SizedArray<BfIRValue, 8> dscrFieldVals =
  4632. {
  4633. emptyValueType,
  4634. dscrNameConst, // mName
  4635. GetConstValue(0, longType), // mConstValue
  4636. GetConstValue(BF_ALIGN(payloadType->mSize, dscrType->mAlign), intType), // mDataOffset
  4637. GetConstValue(dscrType->mTypeId, typeIdType), // mFieldTypeId
  4638. GetConstValue(FieldFlags_SpecialName | FieldFlags_EnumDiscriminator, shortType), // mFlags
  4639. GetConstValue(-1, intType), // mCustomAttributesIdx
  4640. };
  4641. auto dscrFieldData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(reflectFieldDataType->ToTypeInstance(), BfIRPopulateType_Full), dscrFieldVals);
  4642. fieldTypes.push_back(dscrFieldData);
  4643. }
  4644. for (auto fieldIdx : reflectFieldIndices)
  4645. {
  4646. if (!needsTypeData)
  4647. break;
  4648. BfFieldInstance* fieldInstance = &typeInstance->mFieldInstances[fieldIdx];
  4649. BfFieldDef* fieldDef = fieldInstance->GetFieldDef();
  4650. BfIRValue fieldNameConst = GetStringObjectValue(fieldDef->mName, true);
  4651. int typeId = 0;
  4652. auto fieldType = fieldInstance->GetResolvedType();
  4653. if (fieldType->IsGenericParam())
  4654. {
  4655. //TODO:
  4656. }
  4657. else
  4658. typeId = fieldType->mTypeId;
  4659. FieldFlags fieldFlags = (FieldFlags)0;
  4660. if (fieldDef->mProtection == BfProtection_Protected)
  4661. fieldFlags = (FieldFlags)(fieldFlags | FieldFlags_Protected);
  4662. if (fieldDef->mProtection == BfProtection_Public)
  4663. fieldFlags = (FieldFlags)(fieldFlags | FieldFlags_Public);
  4664. if (fieldDef->mIsStatic)
  4665. fieldFlags = (FieldFlags)(fieldFlags | FieldFlags_Static);
  4666. if (fieldDef->mIsConst)
  4667. fieldFlags = (FieldFlags)(fieldFlags | FieldFlags_Const);
  4668. int customAttrIdx = _HandleCustomAttrs(fieldInstance->mCustomAttributes);
  4669. BfIRValue constValue = GetConstValue(0, longType);
  4670. if (fieldInstance->GetFieldDef()->mIsConst)
  4671. {
  4672. if (fieldInstance->mConstIdx != -1)
  4673. {
  4674. auto constant = typeInstance->mConstHolder->GetConstantById(fieldInstance->mConstIdx);
  4675. constValue = mBfIRBuilder->CreateConst(BfTypeCode_UInt64, constant->mUInt64);
  4676. }
  4677. }
  4678. SizedArray<BfIRValue, 8> fieldVals =
  4679. {
  4680. emptyValueType,
  4681. fieldNameConst, // mName
  4682. constValue, // mConstValue
  4683. GetConstValue(fieldInstance->mDataOffset, intType), // mDataOffset
  4684. GetConstValue(typeId, typeIdType), // mFieldTypeId
  4685. GetConstValue(fieldFlags, shortType), // mFlags
  4686. GetConstValue(customAttrIdx, intType), // mCustomAttributesIdx
  4687. };
  4688. auto fieldData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(reflectFieldDataType->ToTypeInstance(), BfIRPopulateType_Full), fieldVals);
  4689. fieldTypes.push_back(fieldData);
  4690. }
  4691. auto reflectFieldDataIRType = mBfIRBuilder->MapType(reflectFieldDataType);
  4692. BfIRValue fieldDataPtr;
  4693. BfIRType fieldDataPtrType = mBfIRBuilder->GetPointerTo(reflectFieldDataIRType);
  4694. if (fieldTypes.size() == 0)
  4695. {
  4696. if ((type->IsSplattable()) && (type->IsStruct()) && (!type->IsValuelessType()))
  4697. {
  4698. BfTypeInstance* reflectFieldSplatDataType = ResolveTypeDef(mCompiler->mReflectFieldSplatDataDef)->ToTypeInstance();
  4699. SizedArray<BfIRValue, 3> splatTypes;
  4700. SizedArray<BfIRValue, 3> splatOffsets;
  4701. std::function<void(BfType*, int)> _CheckSplat = [&](BfType* checkType, int offset)
  4702. {
  4703. auto checkTypeInstance = checkType->ToTypeInstance();
  4704. if ((checkTypeInstance != NULL) && (checkTypeInstance->IsValueType()) && (checkTypeInstance->IsDataIncomplete()))
  4705. PopulateType(checkTypeInstance);
  4706. if (checkType->IsStruct())
  4707. {
  4708. int dataEnd = offset;
  4709. if (checkTypeInstance->mBaseType != NULL)
  4710. _CheckSplat(checkTypeInstance->mBaseType, offset);
  4711. if (checkTypeInstance->mIsUnion)
  4712. {
  4713. BfType* unionInnerType = checkTypeInstance->GetUnionInnerType();
  4714. _CheckSplat(unionInnerType, offset);
  4715. }
  4716. else
  4717. {
  4718. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  4719. {
  4720. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  4721. if (fieldInstance->mDataIdx >= 0)
  4722. {
  4723. _CheckSplat(fieldInstance->GetResolvedType(), offset + fieldInstance->mDataOffset);
  4724. dataEnd = offset + fieldInstance->mDataOffset + fieldInstance->mResolvedType->mSize;
  4725. }
  4726. }
  4727. }
  4728. if (checkTypeInstance->IsEnum())
  4729. {
  4730. // Add discriminator
  4731. auto dscrType = checkTypeInstance->GetDiscriminatorType();
  4732. if (!checkTypeInstance->mIsPacked)
  4733. dataEnd = BF_ALIGN(dataEnd, dscrType->mAlign);
  4734. _CheckSplat(dscrType, dataEnd);
  4735. }
  4736. }
  4737. else if (checkType->IsMethodRef())
  4738. {
  4739. // auto methodRefType = (BfMethodRefType*)checkType;
  4740. // for (int dataIdx = 0; dataIdx < methodRefType->GetCaptureDataCount(); dataIdx++)
  4741. // {
  4742. // if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  4743. // _CheckSplat(methodRefType->GetCaptureType(dataIdx), offsetof);
  4744. // else
  4745. // dataLambda(methodRefType->GetCaptureType(dataIdx));
  4746. // }
  4747. }
  4748. else if (!checkType->IsValuelessType())
  4749. {
  4750. splatTypes.Add(GetConstValue(checkType->mTypeId, typeIdType));
  4751. splatOffsets.Add(GetConstValue(offset, intType));
  4752. }
  4753. };
  4754. _CheckSplat(type, 0);
  4755. while (splatTypes.size() < 3)
  4756. {
  4757. splatTypes.Add(GetConstValue(0, typeIdType));
  4758. splatOffsets.Add(GetConstValue(0, intType));
  4759. }
  4760. BfIRValue splatTypesConst = mBfIRBuilder->CreateConstArray(mBfIRBuilder->MapType(reflectFieldSplatDataType->mFieldInstances[0].mResolvedType), splatTypes);
  4761. BfIRValue splatOffsetsConst = mBfIRBuilder->CreateConstArray(mBfIRBuilder->MapType(reflectFieldSplatDataType->mFieldInstances[1].mResolvedType), splatOffsets);
  4762. SizedArray<BfIRValue, 8> splatVals =
  4763. {
  4764. emptyValueType,
  4765. splatTypesConst,
  4766. splatOffsetsConst
  4767. };
  4768. auto fieldSplatData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(reflectFieldSplatDataType->ToTypeInstance(), BfIRPopulateType_Full), splatVals);
  4769. BfIRValue fieldDataArray = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapType(reflectFieldSplatDataType), true, BfIRLinkageType_Internal,
  4770. fieldSplatData, typeDataName + ".splats");
  4771. fieldDataPtr = mBfIRBuilder->CreateBitCast(fieldDataArray, fieldDataPtrType);
  4772. }
  4773. else
  4774. fieldDataPtr = mBfIRBuilder->CreateConstNull(fieldDataPtrType);
  4775. }
  4776. else
  4777. {
  4778. BfIRType fieldDataConstType = mBfIRBuilder->GetSizedArrayType(reflectFieldDataIRType, (int)fieldTypes.size());
  4779. BfIRValue fieldDataConst = mBfIRBuilder->CreateConstArray(fieldDataConstType, fieldTypes);
  4780. BfIRValue fieldDataArray = mBfIRBuilder->CreateGlobalVariable(fieldDataConstType, true, BfIRLinkageType_Internal,
  4781. fieldDataConst, "fields." + typeDataName);
  4782. fieldDataPtr = mBfIRBuilder->CreateBitCast(fieldDataArray, fieldDataPtrType);
  4783. }
  4784. /// Methods
  4785. BfType* reflectMethodDataType = ResolveTypeDef(mCompiler->mReflectMethodDataDef);
  4786. BfType* reflectParamDataType = ResolveTypeDef(mCompiler->mReflectParamDataDef);
  4787. BfType* reflectParamDataPtrType = CreatePointerType(reflectParamDataType);
  4788. SizedArray<BfIRValue, 16> methodTypes;
  4789. for (int methodIdx = 0; methodIdx < (int)typeDef->mMethods.size(); methodIdx++)
  4790. {
  4791. if (!needsTypeData)
  4792. break;
  4793. auto methodInstanceGroup = &typeInstance->mMethodInstanceGroups[methodIdx];
  4794. if (!methodInstanceGroup->IsImplemented())
  4795. continue;
  4796. auto methodDef = typeDef->mMethods[methodIdx];
  4797. if (methodDef->mNoReflect)
  4798. continue;
  4799. auto defaultMethod = methodInstanceGroup->mDefault;
  4800. if (defaultMethod == NULL)
  4801. continue;
  4802. if (defaultMethod->mIsUnspecialized)
  4803. continue;
  4804. if (!defaultMethod->mIsReified)
  4805. continue;
  4806. if ((defaultMethod->mChainType == BfMethodChainType_ChainMember) || (defaultMethod->mChainType == BfMethodChainType_ChainSkip))
  4807. continue;
  4808. if (defaultMethod->mMethodDef->mMethodType == BfMethodType_CtorNoBody)
  4809. continue;
  4810. auto methodReflectKind = (ReflectKind)(reflectKind & ~ReflectKind_User);
  4811. bool includeMethod = reflectIncludeAllMethods;
  4812. BfCustomAttributes* methodCustomAttributes = NULL;
  4813. if ((defaultMethod->mMethodInfoEx != NULL) && (defaultMethod->mMethodInfoEx->mMethodCustomAttributes != NULL) && (defaultMethod->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes != NULL))
  4814. {
  4815. methodCustomAttributes = defaultMethod->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes;
  4816. for (auto& customAttr : defaultMethod->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes->mAttributes)
  4817. {
  4818. if (customAttr.mType->mTypeDef->mName->ToString() == "ReflectAttribute")
  4819. {
  4820. includeMethod = true;
  4821. }
  4822. else
  4823. {
  4824. auto userReflectKind = _GetReflectUser(customAttr.mType);
  4825. methodReflectKind = (ReflectKind)(methodReflectKind | userReflectKind);
  4826. }
  4827. }
  4828. }
  4829. if (!typeInstance->IsTypeMemberAccessible(methodDef->mDeclaringType, mProject))
  4830. continue;
  4831. if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  4832. {
  4833. for (BfParameterDeclaration* paramDecl : methodDeclaration->mParams)
  4834. {
  4835. if (paramDecl->mAttributes != NULL)
  4836. methodReflectKind = (ReflectKind)(methodReflectKind | _GetReflectUserFromDirective(paramDecl->mAttributes, BfAttributeTargets_Parameter));
  4837. }
  4838. if (methodDeclaration->mReturnAttributes != NULL)
  4839. methodReflectKind = (ReflectKind)(methodReflectKind | _GetReflectUserFromDirective(methodDeclaration->mReturnAttributes, BfAttributeTargets_ReturnValue));
  4840. }
  4841. if ((methodReflectKind & (ReflectKind_Methods | ReflectKind_User)) != 0)
  4842. includeMethod = true;
  4843. if ((methodDef->mIsStatic) && ((methodReflectKind & ReflectKind_StaticMethods) != 0))
  4844. includeMethod = true;
  4845. if (!includeMethod)
  4846. continue;
  4847. BfModuleMethodInstance moduleMethodInstance;
  4848. BfIRValue funcVal = voidPtrNull;
  4849. if (((!typeInstance->IsBoxed()) || (!methodDef->mIsStatic)) &&
  4850. (!typeInstance->IsUnspecializedType()) &&
  4851. (methodDef->mMethodType != BfMethodType_Ignore) &&
  4852. (methodDef->mMethodType != BfMethodType_Mixin) &&
  4853. (!methodDef->mIsAbstract) &&
  4854. (methodDef->mGenericParams.size() == 0))
  4855. {
  4856. moduleMethodInstance = GetMethodInstanceAtIdx(typeInstance, methodIdx);
  4857. if (moduleMethodInstance.mFunc)
  4858. funcVal = mBfIRBuilder->CreateBitCast(moduleMethodInstance.mFunc, voidPtrIRType);
  4859. }
  4860. BfIRValue methodNameConst = GetStringObjectValue(methodDef->mName, true);
  4861. enum MethodFlags
  4862. {
  4863. MethodFlags_Protected = 3,
  4864. MethodFlags_Public = 6,
  4865. MethodFlags_Static = 0x10,
  4866. MethodFlags_Virtual = 0x40,
  4867. MethodFlags_StdCall = 0x1000,
  4868. MethodFlags_FastCall = 0x2000,
  4869. MethodFlags_Mutating = 0x4000,
  4870. };
  4871. MethodFlags methodFlags = (MethodFlags)0;
  4872. if (methodDef->mProtection == BfProtection_Protected)
  4873. methodFlags = (MethodFlags)(methodFlags | MethodFlags_Protected);
  4874. if (methodDef->mProtection == BfProtection_Public)
  4875. methodFlags = (MethodFlags)(methodFlags | MethodFlags_Public);
  4876. if (methodDef->mIsStatic)
  4877. methodFlags = (MethodFlags)(methodFlags | MethodFlags_Static);
  4878. if (methodDef->mIsVirtual)
  4879. methodFlags = (MethodFlags)(methodFlags | MethodFlags_Virtual);
  4880. if (methodDef->mCallingConvention == BfCallingConvention_Fastcall)
  4881. methodFlags = (MethodFlags)(methodFlags | MethodFlags_FastCall);
  4882. if (methodDef->mIsMutating)
  4883. methodFlags = (MethodFlags)(methodFlags | MethodFlags_Mutating);
  4884. int customAttrIdx = _HandleCustomAttrs(methodCustomAttributes);
  4885. enum ParamFlags
  4886. {
  4887. ParamFlag_None = 0,
  4888. ParamFlag_Splat = 1,
  4889. ParamFlag_Implicit = 2,
  4890. };
  4891. SizedArray<BfIRValue, 8> paramVals;
  4892. for (int paramIdx = 0; paramIdx < defaultMethod->GetParamCount(); paramIdx++)
  4893. {
  4894. String paramName = defaultMethod->GetParamName(paramIdx);
  4895. BfType* paramType = defaultMethod->GetParamType(paramIdx);
  4896. ParamFlags paramFlags = ParamFlag_None;
  4897. if (defaultMethod->GetParamIsSplat(paramIdx))
  4898. paramFlags = (ParamFlags)(paramFlags | ParamFlag_Splat);
  4899. BfIRValue paramNameConst = GetStringObjectValue(paramName, true);
  4900. SizedArray<BfIRValue, 8> paramDataVals =
  4901. {
  4902. emptyValueType,
  4903. paramNameConst,
  4904. GetConstValue(paramType->mTypeId, typeIdType),
  4905. GetConstValue((int32)paramFlags, shortType),
  4906. GetConstValue(customAttrIdx, intType) // defaultIdx
  4907. };
  4908. auto paramData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapType(reflectParamDataType, BfIRPopulateType_Full), paramDataVals);
  4909. paramVals.Add(paramData);
  4910. }
  4911. BfIRValue paramsVal;
  4912. if (paramVals.size() > 0)
  4913. {
  4914. BfIRType paramDataArrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->MapType(reflectParamDataType, BfIRPopulateType_Full), (int)paramVals.size());
  4915. BfIRValue paramDataConst = mBfIRBuilder->CreateConstArray(paramDataArrayType, paramVals);
  4916. BfIRValue paramDataArray = mBfIRBuilder->CreateGlobalVariable(paramDataArrayType, true, BfIRLinkageType_Internal,
  4917. paramDataConst, typeDataName + StrFormat(".params%d", methodIdx));
  4918. paramsVal = mBfIRBuilder->CreateBitCast(paramDataArray, mBfIRBuilder->MapType(reflectParamDataPtrType));
  4919. }
  4920. else
  4921. paramsVal = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(reflectParamDataPtrType));
  4922. int vDataVal = -1;
  4923. if (defaultMethod->mVirtualTableIdx != -1)
  4924. {
  4925. int vDataIdx = -1;
  4926. vDataIdx = 1 + mCompiler->GetDynCastVDataCount() + mCompiler->mMaxInterfaceSlots;
  4927. if ((mCompiler->mOptions.mHasVDataExtender) && (mCompiler->IsHotCompile()))
  4928. {
  4929. auto typeInst = defaultMethod->mMethodInstanceGroup->mOwner;
  4930. int extMethodIdx = (defaultMethod->mVirtualTableIdx - typeInst->GetBaseVTableSize()) - typeInst->GetOrigSelfVTableSize();
  4931. if (extMethodIdx >= 0)
  4932. {
  4933. // Extension?
  4934. int vExtOfs = typeInst->GetOrigBaseVTableSize();
  4935. vDataVal = ((vDataIdx + vExtOfs + 1) << 20) | (extMethodIdx);
  4936. }
  4937. else
  4938. {
  4939. // Map this new virtual index back to the original index
  4940. vDataIdx += (defaultMethod->mVirtualTableIdx - typeInst->GetBaseVTableSize()) + typeInst->GetOrigBaseVTableSize();
  4941. }
  4942. }
  4943. else
  4944. {
  4945. vDataIdx += defaultMethod->mVirtualTableIdx;
  4946. }
  4947. if (vDataVal == -1)
  4948. vDataVal = vDataIdx * mSystem->mPtrSize;
  4949. }
  4950. SizedArray<BfIRValue, 8> methodDataVals =
  4951. {
  4952. emptyValueType,
  4953. methodNameConst, // mName
  4954. funcVal, // mFuncPtr
  4955. paramsVal,
  4956. GetConstValue(defaultMethod->mReturnType->mTypeId, typeIdType),
  4957. GetConstValue((int)paramVals.size(), shortType),
  4958. GetConstValue(methodFlags, shortType),
  4959. GetConstValue(vDataVal, intType),
  4960. GetConstValue(-1, intType),
  4961. };
  4962. auto methodData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(reflectMethodDataType->ToTypeInstance(), BfIRPopulateType_Full), methodDataVals);
  4963. methodTypes.push_back(methodData);
  4964. }
  4965. BfIRValue methodDataPtr;
  4966. BfIRType methodDataPtrType = mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapType(reflectMethodDataType));
  4967. if (methodTypes.size() == 0)
  4968. methodDataPtr = mBfIRBuilder->CreateConstNull(methodDataPtrType);
  4969. else
  4970. {
  4971. BfIRType methodDataArrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->MapType(reflectMethodDataType, BfIRPopulateType_Full), (int)methodTypes.size());
  4972. BfIRValue methodDataConst = mBfIRBuilder->CreateConstArray(methodDataArrayType, methodTypes);
  4973. BfIRValue methodDataArray = mBfIRBuilder->CreateGlobalVariable(methodDataArrayType, true, BfIRLinkageType_Internal,
  4974. methodDataConst, "methods." + typeDataName);
  4975. methodDataPtr = mBfIRBuilder->CreateBitCast(methodDataArray, methodDataPtrType);
  4976. }
  4977. /////
  4978. int underlyingType = 0;
  4979. if ((typeInstance->IsTypedPrimitive()) || (typeInstance->IsBoxed()))
  4980. {
  4981. underlyingType = typeInstance->GetUnderlyingType()->mTypeId;
  4982. }
  4983. int outerTypeId = 0;
  4984. auto outerType = GetOuterType(typeInstance);
  4985. if (outerType != NULL)
  4986. outerTypeId = outerType->mTypeId;
  4987. BfIRValue customAttrDataPtr;
  4988. if (customAttrs.size() > 0)
  4989. {
  4990. BfIRType customAttrsArrayType = mBfIRBuilder->GetSizedArrayType(voidPtrIRType, (int)customAttrs.size());
  4991. BfIRValue customAttrsConst = mBfIRBuilder->CreateConstArray(customAttrsArrayType, customAttrs);
  4992. BfIRValue customAttrsArray = mBfIRBuilder->CreateGlobalVariable(customAttrsArrayType, true, BfIRLinkageType_Internal,
  4993. customAttrsConst, "customAttrs." + typeDataName);
  4994. customAttrDataPtr = mBfIRBuilder->CreateBitCast(customAttrsArray, voidPtrPtrIRType);
  4995. }
  4996. else
  4997. {
  4998. customAttrDataPtr = mBfIRBuilder->CreateConstNull(voidPtrPtrIRType);
  4999. }
  5000. SizedArray<BfIRValue, 32> typeDataVals =
  5001. {
  5002. typeData,
  5003. castedClassVData, // mTypeClassVData
  5004. typeNameConst, // mName
  5005. namespaceConst, // mNamespace
  5006. GetConstValue(typeInstance->mInstSize, intType), // mInstSize
  5007. GetConstValue(typeInstance->mInstAlign, intType), // mInstAlign
  5008. GetConstValue(typeCustomAttrIdx, intType), // mCustomAttributes
  5009. GetConstValue(baseTypeId, typeIdType), // mBaseType
  5010. GetConstValue(underlyingType, typeIdType), // mUnderlyingType
  5011. GetConstValue(outerTypeId, typeIdType), // mOuterType
  5012. GetConstValue(typeInstance->mInheritanceId, intType), // mInheritanceId
  5013. GetConstValue(typeInstance->mInheritanceCount, intType), // mInheritanceCount
  5014. GetConstValue(typeInstance->mSlotNum, byteType), // mInterfaceSlot
  5015. GetConstValue(0, byteType), // mInterfaceCount
  5016. GetConstValue((int)methodTypes.size(), shortType), // mMethodDataCount
  5017. GetConstValue(0, shortType), // mPropertyDataCount
  5018. GetConstValue((int)fieldTypes.size(), shortType), // mFieldDataCount
  5019. GetConstValue(0, shortType), // mConstructorDataCount
  5020. voidPtrNull, // mInterfaceDataPtr
  5021. methodDataPtr, // mMethodDataPtr
  5022. voidPtrNull, // mPropertyDataPtr
  5023. fieldDataPtr, // mFieldDataPtr
  5024. voidPtrNull, // mConstructorDataPtr
  5025. customAttrDataPtr, // mCustomAttrDataPtr
  5026. };
  5027. BfIRType typeInstanceDataType = mBfIRBuilder->MapTypeInst(typeInstanceType->ToTypeInstance(), BfIRPopulateType_Full);
  5028. auto typeInstanceData = mBfIRBuilder->CreateConstStruct(typeInstanceDataType, typeDataVals);
  5029. if (!needsTypeData)
  5030. {
  5031. // No need for anything beyond typeInstanceData
  5032. }
  5033. else if ((typeInstance->IsGenericTypeInstance()) && (typeInstance->IsUnspecializedType()))
  5034. {
  5035. auto genericTypeInstance = typeInstance->ToGenericTypeInstance();
  5036. SizedArray<BfIRValue, 4> unspecializedData =
  5037. {
  5038. typeInstanceData,
  5039. GetConstValue((int)genericTypeInstance->mTypeGenericArguments.size(), byteType), // mGenericParamCount
  5040. };
  5041. auto reflectUnspecializedGenericType = ResolveTypeDef(mCompiler->mReflectUnspecializedGenericType);
  5042. typeInstanceDataType = mBfIRBuilder->MapTypeInst(reflectUnspecializedGenericType->ToTypeInstance(), BfIRPopulateType_Full);
  5043. typeInstanceData = mBfIRBuilder->CreateConstStruct(typeInstanceDataType, unspecializedData);
  5044. }
  5045. else if (typeInstance->IsGenericTypeInstance())
  5046. {
  5047. auto genericTypeInstance = typeInstance->ToGenericTypeInstance();
  5048. auto reflectSpecializedGenericType = ResolveTypeDef(mCompiler->mReflectSpecializedGenericType);
  5049. auto unspecializedType = ResolveTypeDef(typeInstance->mTypeDef);
  5050. SizedArray<BfIRValue, 4> resolvedTypes;
  5051. for (auto typeGenericArg : genericTypeInstance->mTypeGenericArguments)
  5052. resolvedTypes.push_back(GetConstValue(typeGenericArg->mTypeId, typeIdType));
  5053. auto typeIRType = mBfIRBuilder->MapType(typeIdType);
  5054. auto typePtrIRType = mBfIRBuilder->GetPointerTo(typeIRType);
  5055. auto genericArrayType = mBfIRBuilder->GetSizedArrayType(typeIRType, (int)resolvedTypes.size());
  5056. BfIRValue resolvedTypesConst = mBfIRBuilder->CreateConstArray(genericArrayType, resolvedTypes);
  5057. BfIRValue resolvedTypesArray = mBfIRBuilder->CreateGlobalVariable(genericArrayType, true, BfIRLinkageType_Internal,
  5058. resolvedTypesConst, "resolvedTypes." + typeDataName);
  5059. BfIRValue resovledTypesPtr = mBfIRBuilder->CreateBitCast(resolvedTypesArray, typePtrIRType);
  5060. SizedArray<BfIRValue, 3> specGenericData =
  5061. {
  5062. typeInstanceData,
  5063. GetConstValue(unspecializedType->mTypeId, typeIdType), // mUnspecialziedType
  5064. resovledTypesPtr, // mFieldDataPtr
  5065. };
  5066. typeInstanceDataType = mBfIRBuilder->MapTypeInst(reflectSpecializedGenericType->ToTypeInstance(), BfIRPopulateType_Full);
  5067. typeInstanceData = mBfIRBuilder->CreateConstStruct(typeInstanceDataType, specGenericData);
  5068. if (typeInstance->IsArray())
  5069. {
  5070. auto arrayType = (BfArrayType*)typeInstance;
  5071. BfType* elementType = genericTypeInstance->mTypeGenericArguments[0];
  5072. BfFieldInstance* elementFieldInstance = &genericTypeInstance->mFieldInstances[0];
  5073. SizedArray<BfIRValue, 4> arrayData =
  5074. {
  5075. typeInstanceData,
  5076. GetConstValue(elementType->mSize, intType), // mElementSize
  5077. GetConstValue(1, byteType), // mRank
  5078. GetConstValue(elementFieldInstance->mDataOffset, byteType), // mElementsDataOffset
  5079. };
  5080. auto reflectArrayType = ResolveTypeDef(mCompiler->mReflectArrayType);
  5081. typeInstanceDataType = mBfIRBuilder->MapTypeInst(reflectArrayType->ToTypeInstance(), BfIRPopulateType_Full);
  5082. typeInstanceData = mBfIRBuilder->CreateConstStruct(typeInstanceDataType, arrayData);
  5083. }
  5084. }
  5085. BfIRValue typeDataVar;
  5086. if (needsTypeData)
  5087. {
  5088. typeDataVar = mBfIRBuilder->CreateGlobalVariable(typeInstanceDataType, true,
  5089. BfIRLinkageType_External, typeInstanceData, typeDataName);
  5090. if (mBfIRBuilder->DbgHasInfo())
  5091. {
  5092. mBfIRBuilder->DbgCreateGlobalVariable(mDICompileUnit, typeDataName, typeDataName, NULL, 0, mBfIRBuilder->DbgGetTypeInst(typeInstanceType->ToTypeInstance()), false, typeDataVar);
  5093. }
  5094. }
  5095. else
  5096. {
  5097. typeDataVar = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(mContext->mBfTypeType));
  5098. }
  5099. typeDataVar = mBfIRBuilder->CreateBitCast(typeDataVar, mBfIRBuilder->MapType(mContext->mBfTypeType));
  5100. mTypeDataRefs[typeInstance] = typeDataVar;
  5101. if (classVDataVar)
  5102. {
  5103. BF_ASSERT(!classVDataName.IsEmpty());
  5104. vData[0] = mBfIRBuilder->CreateBitCast(typeDataVar, voidPtrIRType);
  5105. auto classVDataConstDataType = mBfIRBuilder->GetSizedArrayType(voidPtrIRType, (int)vData.size());
  5106. auto classVDataConstData = mBfIRBuilder->CreateConstArray(classVDataConstDataType, vData);
  5107. mBfIRBuilder->GlobalVar_SetInitializer(classVDataVar, classVDataConstData);
  5108. if (mCompiler->mOptions.mObjectHasDebugFlags)
  5109. mBfIRBuilder->GlobalVar_SetAlignment(classVDataVar, 256);
  5110. else
  5111. mBfIRBuilder->GlobalVar_SetAlignment(classVDataVar, mContext->mBfClassVDataPtrType->mAlign);
  5112. if (mBfIRBuilder->DbgHasInfo())
  5113. {
  5114. BfType* voidType = GetPrimitiveType(BfTypeCode_None);
  5115. BfType* voidPtrType = CreatePointerType(voidType);
  5116. BfType* classVDataType = ResolveTypeDef(mCompiler->mClassVDataTypeDef);
  5117. BfIRMDNode arrayType = mBfIRBuilder->DbgCreateArrayType(vData.size() * mSystem->mPtrSize * 8, mSystem->mPtrSize * 8, mBfIRBuilder->DbgGetType(voidPtrType), vData.size());
  5118. mBfIRBuilder->DbgCreateGlobalVariable(mDICompileUnit, classVDataName, classVDataName, NULL, 0, arrayType, false, classVDataVar);
  5119. }
  5120. }
  5121. return typeDataVar;
  5122. }
  5123. BfIRValue BfModule::FixClassVData(BfIRValue value)
  5124. {
  5125. if (!mCompiler->mOptions.mObjectHasDebugFlags)
  5126. return value;
  5127. auto intptrValue = mBfIRBuilder->CreatePtrToInt(value, BfTypeCode_IntPtr);
  5128. auto maskedValue = mBfIRBuilder->CreateAnd(intptrValue, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, (uint64)~0xFFULL));
  5129. return mBfIRBuilder->CreateIntToPtr(maskedValue, mBfIRBuilder->GetType(value));
  5130. }
  5131. void BfModule::CheckStaticAccess(BfTypeInstance* typeInstance)
  5132. {
  5133. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  5134. //TODO: Create a hashset of these, we don't need to repeatedly call static ctors for a given type
  5135. // When we access classes with static constructors FROM a static constructor,
  5136. // we call that other class's static constructor first. Recursion cannot occur, since
  5137. // we simply ignore subsequent attempts to re-enter the constructor
  5138. if (!typeInstance->mHasStaticInitMethod)
  5139. return;
  5140. if ((mCurMethodInstance == NULL) || ((mCurMethodInstance->mMethodDef->mMethodType != BfMethodType_Ctor) || (!mCurMethodInstance->mMethodDef->mIsStatic)))
  5141. return;
  5142. if (mCurMethodInstance->mMethodInstanceGroup->mOwner == typeInstance)
  5143. return;
  5144. auto checkTypeDef = typeInstance->mTypeDef;
  5145. checkTypeDef->PopulateMemberSets();
  5146. BfMethodDef* nextMethodDef = NULL;
  5147. BfMemberSetEntry* entry;
  5148. if (checkTypeDef->mMethodSet.TryGetWith(String("__BfStaticCtor"), &entry))
  5149. nextMethodDef = (BfMethodDef*)entry->mMemberDef;
  5150. while (nextMethodDef != NULL)
  5151. {
  5152. auto checkMethod = nextMethodDef;
  5153. nextMethodDef = nextMethodDef->mNextWithSameName;
  5154. auto methodModule = GetMethodInstance(typeInstance, checkMethod, BfTypeVector());
  5155. if (methodModule)
  5156. {
  5157. auto methodInstance = methodModule.mMethodInstance;
  5158. if ((methodInstance != NULL) &&
  5159. (methodInstance->mMethodDef->mIsStatic) &&
  5160. (methodInstance->mMethodDef->mMethodType == BfMethodType_Ctor) &&
  5161. ((methodInstance->mChainType == BfMethodChainType_ChainHead) || (methodInstance->mChainType == BfMethodChainType_None)))
  5162. {
  5163. mBfIRBuilder->CreateCall(methodModule.mFunc, SizedArray<BfIRValue, 0>());
  5164. break;
  5165. }
  5166. }
  5167. }
  5168. }
  5169. BfIRFunction BfModule::GetIntrinsic(BfMethodInstance* methodInstance, bool reportFailure)
  5170. {
  5171. auto methodOwner = methodInstance->GetOwner();
  5172. auto methodDef = methodInstance->mMethodDef;
  5173. auto methodDeclaration = methodDef->GetMethodDeclaration();
  5174. bool hasExternSpecifier = (methodDeclaration != NULL) && (methodDeclaration->mExternSpecifier != NULL);
  5175. if (!hasExternSpecifier)
  5176. return BfIRFunction();
  5177. if (methodInstance->GetCustomAttributes() == NULL)
  5178. return BfIRFunction();
  5179. for (auto& customAttribute : methodInstance->GetCustomAttributes()->mAttributes)
  5180. {
  5181. String typeName = TypeToString(customAttribute.mType);
  5182. if ((typeName == "System.IntrinsicAttribute") && (customAttribute.mCtorArgs.size() > 0))
  5183. {
  5184. methodInstance->mIsIntrinsic = true;
  5185. auto constant = methodOwner->mConstHolder->GetConstant(customAttribute.mCtorArgs[0]);
  5186. String error;
  5187. if ((constant != NULL) && (BfIRConstHolder::IsInt(constant->mTypeCode)))
  5188. {
  5189. int stringId = constant->mInt32;
  5190. auto entry = mContext->mStringObjectIdMap[stringId];
  5191. int intrinId = BfIRCodeGen::GetIntrinsicId(entry.mString);
  5192. if (intrinId != -1)
  5193. {
  5194. if (intrinId == BfIRIntrinsic_Malloc)
  5195. {
  5196. return GetBuiltInFunc(BfBuiltInFuncType_Malloc);
  5197. }
  5198. else if (intrinId == BfIRIntrinsic_Free)
  5199. {
  5200. return GetBuiltInFunc(BfBuiltInFuncType_Free);
  5201. }
  5202. SizedArray<BfIRType, 2> paramTypes;
  5203. for (auto& param : methodInstance->mParams)
  5204. paramTypes.push_back(mBfIRBuilder->MapType(param.mResolvedType));
  5205. return mBfIRBuilder->GetIntrinsic(intrinId, paramTypes);
  5206. }
  5207. else if (reportFailure)
  5208. error = StrFormat("Unable to find intrinsic '%s'", entry.mString.c_str());
  5209. }
  5210. else if (reportFailure)
  5211. error = "Intrinsic name must be a constant string";
  5212. if (reportFailure)
  5213. {
  5214. BfAstNode* ref = methodDeclaration->mAttributes;
  5215. Fail(error, ref);
  5216. }
  5217. }
  5218. }
  5219. return BfIRFunction();
  5220. }
  5221. BfIRFunction BfModule::GetBuiltInFunc(BfBuiltInFuncType funcTypeId)
  5222. {
  5223. if (mBfIRBuilder->mIgnoreWrites)
  5224. return mBfIRBuilder->GetFakeFunction();
  5225. if (!mBuiltInFuncs[(int)funcTypeId])
  5226. {
  5227. SizedArray<BfIRType, 4> paramTypes;
  5228. auto nullPtrType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr));
  5229. auto intType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_IntPtr));
  5230. auto int32Type = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_Int32));
  5231. auto intPtrType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_IntPtr));
  5232. auto byteType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_Int8));
  5233. auto voidType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_None));
  5234. auto objType = mBfIRBuilder->MapType(mContext->mBfObjectType);
  5235. BfIRFunctionType funcType;
  5236. BfIRFunction func;
  5237. switch (funcTypeId)
  5238. {
  5239. case BfBuiltInFuncType_PrintF:
  5240. funcType = mBfIRBuilder->CreateFunctionType(int32Type, paramTypes, true);
  5241. func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, "PrintF");
  5242. break;
  5243. case BfBuiltInFuncType_Malloc:
  5244. {
  5245. if (mCompiler->mOptions.mDebugAlloc)
  5246. {
  5247. func = GetInternalMethod("Dbg_RawAlloc", 1).mFunc;
  5248. }
  5249. else
  5250. {
  5251. String funcName = mCompiler->mOptions.mMallocLinkName;
  5252. if (funcName.IsEmpty())
  5253. funcName = "malloc";
  5254. func = mBfIRBuilder->GetFunction(funcName);
  5255. if (!func)
  5256. {
  5257. paramTypes.clear();
  5258. paramTypes.push_back(intType);
  5259. funcType = mBfIRBuilder->CreateFunctionType(nullPtrType, paramTypes);
  5260. func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, funcName);
  5261. mBfIRBuilder->Func_SetParamName(func, 1, "size");
  5262. }
  5263. }
  5264. }
  5265. break;
  5266. case BfBuiltInFuncType_Free:
  5267. {
  5268. if (mCompiler->mOptions.mDebugAlloc)
  5269. {
  5270. func = GetInternalMethod("Dbg_RawFree").mFunc;
  5271. }
  5272. else
  5273. {
  5274. String funcName = mCompiler->mOptions.mFreeLinkName;
  5275. if (funcName.IsEmpty())
  5276. funcName = "free";
  5277. func = mBfIRBuilder->GetFunction(funcName);
  5278. if (!func)
  5279. {
  5280. paramTypes.clear();
  5281. paramTypes.push_back(nullPtrType);
  5282. funcType = mBfIRBuilder->CreateFunctionType(voidType, paramTypes);
  5283. func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, funcName);
  5284. mBfIRBuilder->Func_SetParamName(func, 1, "ptr");
  5285. }
  5286. }
  5287. }
  5288. break;
  5289. case BfBuiltInFuncType_LoadSharedLibraries:
  5290. paramTypes.clear();
  5291. funcType = mBfIRBuilder->CreateFunctionType(voidType, paramTypes);
  5292. func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, "BfLoadSharedLibraries");
  5293. break;
  5294. default: break;
  5295. }
  5296. mBuiltInFuncs[(int)funcTypeId] = func;
  5297. return func;
  5298. }
  5299. return mBuiltInFuncs[(int)funcTypeId];
  5300. }
  5301. void BfModule::ResolveGenericParamConstraints(BfGenericParamInstance* genericParamInstance, const Array<BfGenericParamDef*>& genericParamDefs, int genericParamIdx)
  5302. {
  5303. BfGenericParamDef* genericParamDef = genericParamDefs[genericParamIdx];
  5304. BfType* startingTypeConstraint = genericParamInstance->mTypeConstraint;
  5305. BfAutoComplete* bfAutocomplete = NULL;
  5306. if (mCompiler->mResolvePassData != NULL)
  5307. bfAutocomplete = mCompiler->mResolvePassData->mAutoComplete;
  5308. if (bfAutocomplete != NULL)
  5309. {
  5310. for (int nameIdx = 0; nameIdx < (int)genericParamDef->mNameNodes.size(); nameIdx++)
  5311. {
  5312. auto nameNode = genericParamDef->mNameNodes[nameIdx];
  5313. if (bfAutocomplete->IsAutocompleteNode(nameNode))
  5314. {
  5315. String filter = nameNode->ToString();
  5316. bfAutocomplete->mInsertStartIdx = nameNode->GetSrcStart();
  5317. bfAutocomplete->mInsertEndIdx = nameNode->GetSrcEnd();
  5318. if (nameIdx != 0)
  5319. {
  5320. for (auto checkGenericParam : genericParamDefs)
  5321. bfAutocomplete->AddEntry(AutoCompleteEntry("generic", checkGenericParam->mName.c_str()), filter);
  5322. }
  5323. }
  5324. }
  5325. }
  5326. for (auto constraintTypeRef : genericParamDef->mInterfaceConstraints)
  5327. {
  5328. if (bfAutocomplete != NULL)
  5329. bfAutocomplete->CheckTypeRef(constraintTypeRef, true);
  5330. //TODO: Constraints may refer to other generic params (of either type or method)
  5331. // TO allow resolution, perhaps move this generic param initalization into GetMethodInstance (passing a genericPass bool)
  5332. auto constraintType = ResolveTypeRef(constraintTypeRef, BfPopulateType_Declaration, BfResolveTypeRefFlag_AllowGenericMethodParamConstValue);
  5333. if (constraintType != NULL)
  5334. {
  5335. if ((genericParamDef->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  5336. {
  5337. bool isValidTypeCode = false;
  5338. BfTypeCode typeCode = BfTypeCode_None;
  5339. if (constraintType->IsTypedPrimitive())
  5340. {
  5341. auto underlyingType = constraintType->GetUnderlyingType();
  5342. if (underlyingType->IsPrimitiveType())
  5343. typeCode = ((BfPrimitiveType*)underlyingType)->mTypeDef->mTypeCode;
  5344. }
  5345. if (constraintType->IsPrimitiveType())
  5346. typeCode = ((BfPrimitiveType*)constraintType)->mTypeDef->mTypeCode;
  5347. switch (typeCode)
  5348. {
  5349. case BfTypeCode_Int8:
  5350. case BfTypeCode_UInt8:
  5351. case BfTypeCode_Int16:
  5352. case BfTypeCode_UInt16:
  5353. case BfTypeCode_Int32:
  5354. case BfTypeCode_UInt32:
  5355. case BfTypeCode_Int64:
  5356. case BfTypeCode_UInt64:
  5357. case BfTypeCode_IntPtr:
  5358. case BfTypeCode_UIntPtr:
  5359. case BfTypeCode_IntUnknown:
  5360. case BfTypeCode_UIntUnknown:
  5361. case BfTypeCode_Single:
  5362. case BfTypeCode_Double:
  5363. case BfTypeCode_Char8:
  5364. case BfTypeCode_Char16:
  5365. case BfTypeCode_Char32:
  5366. isValidTypeCode = true;
  5367. break;
  5368. default: break;
  5369. }
  5370. if (isValidTypeCode)
  5371. {
  5372. genericParamInstance->mTypeConstraint = constraintType;
  5373. }
  5374. else
  5375. {
  5376. Fail("Const constraint must be a primitive type", constraintTypeRef);
  5377. }
  5378. }
  5379. else
  5380. {
  5381. if (constraintType->IsPrimitiveType())
  5382. {
  5383. Fail("Primitive constraints are not allowed unless preceded with 'const'", constraintTypeRef);
  5384. continue;
  5385. }
  5386. if (constraintType->IsArray())
  5387. {
  5388. 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);
  5389. continue;
  5390. }
  5391. if ((!constraintType->IsTypeInstance()) && (!constraintType->IsSizedArray()))
  5392. {
  5393. Fail(StrFormat("Type '%s' is not allowed as a generic constraint", TypeToString(constraintType).c_str()), constraintTypeRef);
  5394. continue;
  5395. }
  5396. if (constraintType->IsInterface())
  5397. {
  5398. genericParamInstance->mInterfaceConstraints.push_back(constraintType->ToTypeInstance());
  5399. }
  5400. else
  5401. {
  5402. auto constraintTypeInst = constraintType->ToTypeInstance();
  5403. if (genericParamInstance->mTypeConstraint != NULL)
  5404. {
  5405. if ((constraintTypeInst != NULL) && (TypeIsSubTypeOf(constraintTypeInst, genericParamInstance->mTypeConstraint->ToTypeInstance(), false)))
  5406. {
  5407. // Allow more specific type
  5408. genericParamInstance->mTypeConstraint = constraintTypeInst;
  5409. }
  5410. else if ((constraintTypeInst != NULL) && (TypeIsSubTypeOf(genericParamInstance->mTypeConstraint->ToTypeInstance(), constraintTypeInst, false)))
  5411. {
  5412. // Silently ignore less-specific type
  5413. if ((startingTypeConstraint != NULL) && (startingTypeConstraint->IsDelegate()))
  5414. {
  5415. // 'System.Delegate' means that we are expecting an actual delegate instance. Simulate this by wanting a class.
  5416. genericParamInstance->mGenericParamFlags |= BfGenericParamFlag_Class;
  5417. }
  5418. }
  5419. else
  5420. {
  5421. Fail("Only one concrete type constraint may be specified", constraintTypeRef);
  5422. return;
  5423. }
  5424. }
  5425. else
  5426. genericParamInstance->mTypeConstraint = constraintType;
  5427. }
  5428. }
  5429. }
  5430. }
  5431. if (((genericParamDef->mGenericParamFlags & BfGenericParamFlag_Const) != 0) &&
  5432. (genericParamInstance->mTypeConstraint == NULL))
  5433. genericParamInstance->mTypeConstraint = GetPrimitiveType(BfTypeCode_IntPtr);
  5434. }
  5435. String BfModule::GenericParamSourceToString(const BfGenericParamSource & genericParamSource)
  5436. {
  5437. if (genericParamSource.mMethodInstance != NULL)
  5438. {
  5439. auto methodInst = GetUnspecializedMethodInstance(genericParamSource.mMethodInstance);
  5440. SetAndRestoreValue<BfMethodInstance*> prevMethodInst(mCurMethodInstance, methodInst);
  5441. return MethodToString(methodInst);
  5442. }
  5443. else
  5444. {
  5445. auto typeInst = GetUnspecializedTypeInstance(genericParamSource.mTypeInstance);
  5446. SetAndRestoreValue<BfMethodInstance*> prevMethodInst(mCurMethodInstance, NULL);
  5447. SetAndRestoreValue<BfTypeInstance*> prevTypeInst(mCurTypeInstance, typeInst);
  5448. return TypeToString(typeInst);
  5449. }
  5450. }
  5451. bool BfModule::CheckGenericConstraints(const BfGenericParamSource& genericParamSource, BfType* checkArgType, BfAstNode* checkArgTypeRef, BfGenericParamInstance* genericParamInst, BfTypeVector* methodGenericArgs, BfError** errorOut)
  5452. {
  5453. bool ignoreErrors = mIgnoreErrors || (errorOut == NULL) ||
  5454. ((genericParamSource.mMethodInstance == NULL) && (genericParamSource.mTypeInstance == NULL));
  5455. BfType* origCheckArgType = checkArgType;
  5456. if (origCheckArgType->IsRef())
  5457. origCheckArgType = origCheckArgType->GetUnderlyingType();
  5458. bool argMayBeReferenceType = false;
  5459. int checkGenericParamFlags = 0;
  5460. if (checkArgType->IsGenericParam())
  5461. {
  5462. auto checkGenericParamInst = GetGenericParamInstance((BfGenericParamType*)checkArgType);
  5463. checkGenericParamFlags = checkGenericParamInst->mGenericParamFlags;
  5464. if (checkGenericParamInst->mTypeConstraint != NULL)
  5465. checkArgType = checkGenericParamInst->mTypeConstraint;
  5466. if ((checkGenericParamFlags & (BfGenericParamFlag_Struct | BfGenericParamFlag_StructPtr)) != 0)
  5467. {
  5468. argMayBeReferenceType = false;
  5469. }
  5470. else
  5471. {
  5472. argMayBeReferenceType = true;
  5473. }
  5474. }
  5475. if (checkArgType->IsObjectOrInterface())
  5476. argMayBeReferenceType = true;
  5477. BfTypeInstance* typeConstraintInst = NULL;
  5478. if (genericParamInst->mTypeConstraint != NULL)
  5479. typeConstraintInst = genericParamInst->mTypeConstraint->ToTypeInstance();
  5480. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Struct) &&
  5481. ((checkGenericParamFlags & (BfGenericParamFlag_Struct | BfGenericParamFlag_Var)) == 0) && (!checkArgType->IsValueType()))
  5482. {
  5483. if (!ignoreErrors)
  5484. *errorOut = Fail(StrFormat("The type '%s' must be a value type in order to use it as parameter '%s' for '%s'",
  5485. TypeToString(origCheckArgType).c_str(), genericParamInst->GetGenericParamDef()->mName.c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  5486. return false;
  5487. }
  5488. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_StructPtr) &&
  5489. ((checkGenericParamFlags & (BfGenericParamFlag_StructPtr | BfGenericParamFlag_Var)) == 0) && (!checkArgType->IsPointer()))
  5490. {
  5491. if (!ignoreErrors)
  5492. *errorOut = Fail(StrFormat("The type '%s' must be a pointer type in order to use it as parameter '%s' for '%s'",
  5493. TypeToString(origCheckArgType).c_str(), genericParamInst->GetGenericParamDef()->mName.c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  5494. return false;
  5495. }
  5496. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Class) &&
  5497. ((checkGenericParamFlags & (BfGenericParamFlag_Class | BfGenericParamFlag_Var)) == 0) && (!argMayBeReferenceType))
  5498. {
  5499. if (!ignoreErrors)
  5500. *errorOut = Fail(StrFormat("The type '%s' must be a reference type in order to use it as parameter '%s' for '%s'",
  5501. TypeToString(origCheckArgType).c_str(), genericParamInst->GetGenericParamDef()->mName.c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  5502. return false;
  5503. }
  5504. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  5505. {
  5506. if (((checkGenericParamFlags & BfGenericParamFlag_Const) == 0) && (!checkArgType->IsConstExprValue()))
  5507. {
  5508. if (!ignoreErrors)
  5509. *errorOut = Fail(StrFormat("The type '%s' must be a const value in order to use it as parameter '%s' for '%s'",
  5510. TypeToString(origCheckArgType).c_str(), genericParamInst->GetGenericParamDef()->mName.c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  5511. return false;
  5512. }
  5513. }
  5514. else
  5515. {
  5516. if (checkArgType->IsConstExprValue())
  5517. {
  5518. if (!ignoreErrors)
  5519. *errorOut = Fail(StrFormat("The value '%s' cannot be used for generic type parameter '%s' for '%s'",
  5520. TypeToString(origCheckArgType).c_str(), genericParamInst->GetGenericParamDef()->mName.c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  5521. return false;
  5522. }
  5523. }
  5524. if ((genericParamInst->mInterfaceConstraints.size() == 0) && (genericParamInst->mTypeConstraint == NULL))
  5525. return true;
  5526. if (checkArgType->IsPointer())
  5527. {
  5528. auto ptrType = (BfPointerType*)checkArgType;
  5529. checkArgType = ptrType->mElementType;
  5530. }
  5531. if (genericParamInst->mTypeConstraint != NULL)
  5532. {
  5533. bool constraintMatched = false;
  5534. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  5535. {
  5536. if (checkArgType->IsConstExprValue())
  5537. {
  5538. auto constExprValueType = (BfConstExprValueType*)checkArgType;
  5539. if (genericParamInst->mTypeConstraint->IsPrimitiveType())
  5540. {
  5541. auto primType = (BfPrimitiveType*)genericParamInst->mTypeConstraint;
  5542. // Let either an exact typematch or an undef pass through. Eventually instead of undefs we may want to do
  5543. // actual expression comparisons, but we are overly permissive now and then we may fail on specialization
  5544. if ((constExprValueType->mValue.mTypeCode != primType->mTypeDef->mTypeCode) &&
  5545. (constExprValueType->mValue.mTypeCode != BfTypeCode_Let) &&
  5546. (primType->mTypeDef->mTypeCode != BfTypeCode_Let))
  5547. {
  5548. if (BfIRConstHolder::IsInt(constExprValueType->mValue.mTypeCode))
  5549. {
  5550. if (BfIRConstHolder::IsInt(primType->mTypeDef->mTypeCode))
  5551. {
  5552. if (!mCompiler->mSystem->DoesLiteralFit(primType->mTypeDef->mTypeCode, constExprValueType->mValue.mInt64))
  5553. {
  5554. if (!ignoreErrors)
  5555. *errorOut = Fail(StrFormat("Const generic argument '%s', declared with const '%lld', does not fit into const constraint '%s' for '%s'", genericParamInst->GetGenericParamDef()->mName.c_str(),
  5556. constExprValueType->mValue.mInt64, TypeToString(genericParamInst->mTypeConstraint).c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  5557. return false;
  5558. }
  5559. }
  5560. else
  5561. {
  5562. if (!ignoreErrors)
  5563. *errorOut = Fail(StrFormat("Const generic argument '%s', declared with integer const '%lld', is not compatible with const constraint '%s' for '%s'", genericParamInst->GetGenericParamDef()->mName.c_str(),
  5564. constExprValueType->mValue.mInt64, TypeToString(genericParamInst->mTypeConstraint).c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  5565. return false;
  5566. }
  5567. }
  5568. else
  5569. {
  5570. if (BfIRConstHolder::IsInt(primType->mTypeDef->mTypeCode))
  5571. {
  5572. char valStr[64];
  5573. ExactMinimalDoubleToStr(constExprValueType->mValue.mDouble, valStr);
  5574. if (!ignoreErrors)
  5575. *errorOut = Fail(StrFormat("Const generic argument '%s', declared with floating point const '%s', is not compatible with const constraint '%s' for '%s'", genericParamInst->GetGenericParamDef()->mName.c_str(),
  5576. valStr, TypeToString(genericParamInst->mTypeConstraint).c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  5577. return false;
  5578. }
  5579. }
  5580. }
  5581. }
  5582. }
  5583. }
  5584. else
  5585. {
  5586. BfType* convCheckConstraint = genericParamInst->mTypeConstraint;
  5587. if ((convCheckConstraint->IsUnspecializedType()) && (methodGenericArgs != NULL))
  5588. convCheckConstraint = ResolveGenericType(convCheckConstraint, *methodGenericArgs);
  5589. if ((checkArgType->IsMethodRef()) && (convCheckConstraint->IsDelegate()))
  5590. {
  5591. auto methodRefType = (BfMethodRefType*)checkArgType;
  5592. auto invokeMethod = GetRawMethodInstanceAtIdx(convCheckConstraint->ToTypeInstance(), 0, "Invoke");
  5593. BfExprEvaluator exprEvaluator(this);
  5594. if (exprEvaluator.IsExactMethodMatch(methodRefType->mMethodRef, invokeMethod))
  5595. constraintMatched = true;
  5596. }
  5597. else if (CanImplicitlyCast(GetFakeTypedValue(checkArgType), convCheckConstraint))
  5598. {
  5599. constraintMatched = true;
  5600. }
  5601. else if (origCheckArgType->IsWrappableType())
  5602. {
  5603. if (origCheckArgType->IsSizedArray())
  5604. {
  5605. auto sizedArrayType = (BfSizedArrayType*)origCheckArgType;
  5606. if (convCheckConstraint->IsGenericTypeInstance())
  5607. {
  5608. auto convCheckConstraintInst = (BfGenericTypeInstance*)convCheckConstraint;
  5609. if (convCheckConstraintInst->mTypeDef == mCompiler->mSizedArrayTypeDef)
  5610. {
  5611. if (convCheckConstraintInst->mTypeGenericArguments[0] == sizedArrayType->mElementType)
  5612. {
  5613. auto constExprValueType = (BfConstExprValueType*)convCheckConstraintInst->mTypeGenericArguments[1];
  5614. if (sizedArrayType->mElementCount == constExprValueType->mValue.mInt64)
  5615. constraintMatched = true;
  5616. }
  5617. }
  5618. }
  5619. }
  5620. if (!constraintMatched)
  5621. {
  5622. BfType* wrappedStructType = GetWrappedStructType(origCheckArgType, false);
  5623. if (CanImplicitlyCast(GetFakeTypedValue(wrappedStructType), convCheckConstraint))
  5624. constraintMatched = true;
  5625. }
  5626. }
  5627. if (!constraintMatched)
  5628. {
  5629. if (!ignoreErrors)
  5630. *errorOut = Fail(StrFormat("Generic argument '%s', declared to be '%s' for '%s', must derive from '%s'", genericParamInst->GetGenericParamDef()->mName.c_str(),
  5631. TypeToString(origCheckArgType).c_str(), GenericParamSourceToString(genericParamSource).c_str(), TypeToString(convCheckConstraint).c_str(),
  5632. TypeToString(genericParamInst->mTypeConstraint).c_str()), checkArgTypeRef);
  5633. return false;
  5634. }
  5635. }
  5636. }
  5637. if ((genericParamInst->mInterfaceConstraints.size() > 0) && (origCheckArgType->IsInterface()))
  5638. {
  5639. PopulateType(origCheckArgType);
  5640. auto checkTypeInst = origCheckArgType->ToTypeInstance();
  5641. if (checkTypeInst->mTypeDef->mIsConcrete)
  5642. {
  5643. if (!ignoreErrors)
  5644. *errorOut = Fail(StrFormat("Generic argument '%s', declared to be concrete interface '%s' for '%s', must be a concrete type", genericParamInst->GetGenericParamDef()->mName.c_str(),
  5645. TypeToString(origCheckArgType).c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  5646. return false;
  5647. }
  5648. }
  5649. for (auto checkConstraint : genericParamInst->mInterfaceConstraints)
  5650. {
  5651. BfType* convCheckConstraint = checkConstraint;
  5652. if (convCheckConstraint->IsUnspecializedType())
  5653. convCheckConstraint = ResolveGenericType(convCheckConstraint, *methodGenericArgs);
  5654. BfTypeInstance* typeConstraintInst = convCheckConstraint->ToTypeInstance();
  5655. bool implementsInterface = false;
  5656. if (origCheckArgType != checkArgType)
  5657. {
  5658. implementsInterface = CanImplicitlyCast(origCheckArgType, convCheckConstraint);
  5659. }
  5660. if (!implementsInterface)
  5661. implementsInterface = CanImplicitlyCast(checkArgType, convCheckConstraint);
  5662. if ((!implementsInterface) && (origCheckArgType->IsWrappableType()))
  5663. {
  5664. BfTypeInstance* wrappedStructType = GetWrappedStructType(origCheckArgType, false);
  5665. if (TypeIsSubTypeOf(wrappedStructType, typeConstraintInst))
  5666. implementsInterface = true;
  5667. }
  5668. if ((!implementsInterface) && (origCheckArgType->IsTypedPrimitive()))
  5669. {
  5670. auto underlyingType = origCheckArgType->GetUnderlyingType();
  5671. BfTypeInstance* wrappedStructType = GetWrappedStructType(underlyingType, false);
  5672. if (TypeIsSubTypeOf(wrappedStructType, typeConstraintInst))
  5673. implementsInterface = true;
  5674. }
  5675. if (!implementsInterface)
  5676. {
  5677. if (!ignoreErrors)
  5678. *errorOut = Fail(StrFormat("Generic argument '%s', declared to be '%s' for '%s', must implement '%s'", genericParamInst->GetGenericParamDef()->mName.c_str(),
  5679. TypeToString(origCheckArgType).c_str(), GenericParamSourceToString(genericParamSource).c_str(), TypeToString(checkConstraint).c_str()), checkArgTypeRef);
  5680. return false;
  5681. }
  5682. }
  5683. return true;
  5684. }
  5685. BfGenericParamType* BfModule::GetGenericParamType(BfGenericParamKind paramKind, int paramIdx)
  5686. {
  5687. if (paramIdx < (int)mContext->mGenericParamTypes[paramKind].size())
  5688. {
  5689. auto genericParamType = mContext->mGenericParamTypes[paramKind][paramIdx];
  5690. return genericParamType;
  5691. }
  5692. auto genericParamType = new BfGenericParamType();
  5693. genericParamType->mContext = mContext;
  5694. genericParamType->mGenericParamKind = paramKind;
  5695. genericParamType->mGenericParamIdx = paramIdx;
  5696. PopulateType(genericParamType);
  5697. BF_ASSERT(paramIdx == (int)mContext->mGenericParamTypes[paramKind].size());
  5698. mContext->mGenericParamTypes[paramKind].push_back(genericParamType);
  5699. BfResolvedTypeSet::LookupContext lookupCtx;
  5700. lookupCtx.mModule = this;
  5701. BfResolvedTypeSet::Entry* typeEntry = NULL;
  5702. auto inserted = mContext->mResolvedTypes.Insert(genericParamType, &lookupCtx, &typeEntry);
  5703. BF_ASSERT(inserted);
  5704. typeEntry->mValue = genericParamType;
  5705. return genericParamType;
  5706. }
  5707. static int sValueFromExprIdx = 0;
  5708. BfTypedValue BfModule::FlushNullConditional(BfTypedValue result, bool ignoreNullable)
  5709. {
  5710. auto pendingNullCond = mCurMethodState->mPendingNullConditional;
  5711. if ((result) && (!ignoreNullable))
  5712. {
  5713. auto notNullBB = mBfIRBuilder->GetInsertBlock();
  5714. //TODO: Make this work, needed for 'void' and such
  5715. BfType* nullableType = NULL;
  5716. if ((result.mType->IsValueType()) && (!result.mType->IsNullable()))
  5717. {
  5718. BfTypeVector typeVec;
  5719. typeVec.push_back(result.mType);
  5720. nullableType = ResolveTypeDef(mCompiler->mNullableTypeDef, typeVec);
  5721. BF_ASSERT(nullableType != NULL);
  5722. }
  5723. // Go back to start and do any setup we need
  5724. mBfIRBuilder->SetInsertPoint(pendingNullCond->mPrevBB);
  5725. BfTypedValue nullableTypedValue;
  5726. if (nullableType != NULL)
  5727. {
  5728. nullableTypedValue = BfTypedValue(CreateAlloca(nullableType, true, "nullCond.nullable"), nullableType, true);
  5729. mBfIRBuilder->CreateMemSet(nullableTypedValue.mValue, GetConstValue(0, GetPrimitiveType(BfTypeCode_Int8)),
  5730. GetConstValue(nullableType->mSize), nullableType->mAlign);
  5731. }
  5732. mBfIRBuilder->CreateBr(pendingNullCond->mCheckBB);
  5733. // Now that we have the nullableTypedValue we can set that, or just jump if we didn't need it
  5734. mBfIRBuilder->SetInsertPoint(notNullBB);
  5735. result = LoadValue(result);
  5736. if (nullableTypedValue)
  5737. {
  5738. auto elementType = nullableType->GetUnderlyingType();
  5739. if (elementType->IsValuelessType())
  5740. {
  5741. BfIRValue ptrValue = mBfIRBuilder->CreateInBoundsGEP(nullableTypedValue.mValue, 0, 1); // mHasValue
  5742. mBfIRBuilder->CreateStore(GetConstValue(1, GetPrimitiveType(BfTypeCode_Boolean)), ptrValue);
  5743. result = nullableTypedValue;
  5744. }
  5745. else
  5746. {
  5747. BfIRValue ptrValue = mBfIRBuilder->CreateInBoundsGEP(nullableTypedValue.mValue, 0, 1); // mValue
  5748. mBfIRBuilder->CreateStore(result.mValue, ptrValue);
  5749. ptrValue = mBfIRBuilder->CreateInBoundsGEP(nullableTypedValue.mValue, 0, 2); // mHasValue
  5750. mBfIRBuilder->CreateStore(GetConstValue(1, GetPrimitiveType(BfTypeCode_Boolean)), ptrValue);
  5751. result = nullableTypedValue;
  5752. }
  5753. }
  5754. mBfIRBuilder->CreateBr(pendingNullCond->mDoneBB);
  5755. AddBasicBlock(pendingNullCond->mDoneBB);
  5756. if (nullableType == NULL)
  5757. {
  5758. auto phi = mBfIRBuilder->CreatePhi(mBfIRBuilder->MapType(result.mType), 2);
  5759. mBfIRBuilder->AddPhiIncoming(phi, result.mValue, notNullBB);
  5760. mBfIRBuilder->AddPhiIncoming(phi, GetDefaultValue(result.mType), pendingNullCond->mCheckBB);
  5761. result.mValue = phi;
  5762. }
  5763. }
  5764. else
  5765. {
  5766. mBfIRBuilder->CreateBr(pendingNullCond->mDoneBB);
  5767. mBfIRBuilder->SetInsertPoint(pendingNullCond->mPrevBB);
  5768. mBfIRBuilder->CreateBr(pendingNullCond->mCheckBB);
  5769. AddBasicBlock(pendingNullCond->mDoneBB);
  5770. }
  5771. delete mCurMethodState->mPendingNullConditional;
  5772. mCurMethodState->mPendingNullConditional = NULL;
  5773. return result;
  5774. }
  5775. BF_NOINLINE void BfModule::EvaluateWithNewScope(BfExprEvaluator& exprEvaluator, BfExpression* expr, BfEvalExprFlags flags)
  5776. {
  5777. BfScopeData newScope;
  5778. newScope.mOuterIsConditional = true;
  5779. newScope.mAllowTargeting = false;
  5780. mCurMethodState->AddScope(&newScope);
  5781. NewScopeState();
  5782. exprEvaluator.mBfEvalExprFlags = flags;
  5783. exprEvaluator.Evaluate(expr, (flags & BfEvalExprFlags_PropogateNullConditional) != 0, (flags & BfEvalExprFlags_IgnoreNullConditional) != 0, true);
  5784. RestoreScopeState();
  5785. }
  5786. BfTypedValue BfModule::CreateValueFromExpression(BfExprEvaluator& exprEvaluator, BfExpression* expr, BfType* wantTypeRef, BfEvalExprFlags flags, BfType** outOrigType)
  5787. {
  5788. //
  5789. {
  5790. BP_ZONE("CreateValueFromExpression:CheckStack");
  5791. StackHelper stackHelper;
  5792. if (!stackHelper.CanStackExpand(64 * 1024))
  5793. {
  5794. BfTypedValue result;
  5795. if (!stackHelper.Execute([&]()
  5796. {
  5797. result = CreateValueFromExpression(exprEvaluator, expr, wantTypeRef, flags, outOrigType);
  5798. }))
  5799. {
  5800. Fail("Expression too complex to compile", expr);
  5801. }
  5802. return result;
  5803. }
  5804. }
  5805. BP_ZONE("BfModule::CreateValueFromExpression");
  5806. if (outOrigType != NULL)
  5807. *outOrigType = NULL;
  5808. exprEvaluator.mExpectingType = wantTypeRef;
  5809. exprEvaluator.mBfEvalExprFlags = flags;
  5810. exprEvaluator.mExplicitCast = (flags & BfEvalExprFlags_ExplicitCast) != 0;
  5811. if ((flags & BfEvalExprFlags_CreateConditionalScope) != 0)
  5812. {
  5813. EvaluateWithNewScope(exprEvaluator, expr, flags);
  5814. }
  5815. else
  5816. exprEvaluator.Evaluate(expr, (flags & BfEvalExprFlags_PropogateNullConditional) != 0, (flags & BfEvalExprFlags_IgnoreNullConditional) != 0, true);
  5817. if (!exprEvaluator.mResult)
  5818. {
  5819. if (!mCompiler->mPassInstance->HasFailed())
  5820. Fail("INTERNAL ERROR: No expression result returned but no error caught in expression evaluator", expr);
  5821. return BfTypedValue();
  5822. }
  5823. auto typedVal = exprEvaluator.mResult;
  5824. if (typedVal.mKind == BfTypedValueKind_GenericConstValue)
  5825. {
  5826. BF_ASSERT(typedVal.mType->IsGenericParam());
  5827. auto genericParamDef = GetGenericParamInstance((BfGenericParamType*)typedVal.mType);
  5828. bool handled = false;
  5829. if ((genericParamDef->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  5830. {
  5831. auto genericTypeConstraint = genericParamDef->mTypeConstraint;
  5832. if (genericTypeConstraint != NULL)
  5833. {
  5834. auto primType = genericTypeConstraint->ToPrimitiveType();
  5835. if (primType != NULL)
  5836. {
  5837. BfTypedValue result;
  5838. result.mKind = BfTypedValueKind_Value;
  5839. result.mType = genericTypeConstraint;
  5840. result.mValue = mBfIRBuilder->GetUndefConstValue(primType->mTypeDef->mTypeCode);
  5841. typedVal = result;
  5842. handled = true;
  5843. }
  5844. }
  5845. }
  5846. if (!handled)
  5847. {
  5848. //Fail("Only const generic parameters can be used as values", expr);
  5849. AssertErrorState();
  5850. return BfTypedValue();
  5851. }
  5852. }
  5853. if ((flags & BfEvalExprFlags_AllowIntUnknown) == 0)
  5854. FixIntUnknown(typedVal);
  5855. exprEvaluator.CheckResultForReading(typedVal);
  5856. if ((wantTypeRef == NULL) || (!wantTypeRef->IsRef()))
  5857. {
  5858. if ((flags & BfEvalExprFlags_NoCast) == 0)
  5859. {
  5860. // Only allow a 'ref' type if we have an explicit 'ref' operator
  5861. bool allowRef = false;
  5862. BfExpression* checkExpr = expr;
  5863. while (auto parenExpr = BfNodeDynCast<BfParenthesizedExpression>(checkExpr))
  5864. checkExpr = parenExpr->mExpression;
  5865. if (auto unaryOp = BfNodeDynCast<BfUnaryOperatorExpression>(checkExpr))
  5866. {
  5867. if ((unaryOp->mOp == BfUnaryOp_Ref) || (unaryOp->mOp == BfUnaryOp_Mut))
  5868. allowRef = true;
  5869. }
  5870. if (!allowRef)
  5871. typedVal = RemoveRef(typedVal);
  5872. }
  5873. }
  5874. if (!typedVal.mType->IsComposite()) // Load non-structs by default
  5875. typedVal = LoadValue(typedVal, 0, exprEvaluator.mIsVolatileReference);
  5876. if (wantTypeRef != NULL)
  5877. {
  5878. if (outOrigType != NULL)
  5879. *outOrigType = typedVal.mType;
  5880. if ((flags & BfEvalExprFlags_NoCast) == 0)
  5881. {
  5882. BfCastFlags castFlags = ((flags & BfEvalExprFlags_ExplicitCast) != 0) ? BfCastFlags_Explicit : BfCastFlags_None;
  5883. if ((flags & BfEvalExprFlags_FieldInitializer) != 0)
  5884. castFlags = (BfCastFlags)(castFlags | BfCastFlags_WarnOnBox);
  5885. typedVal = Cast(expr, typedVal, wantTypeRef, castFlags);
  5886. if (!typedVal)
  5887. return typedVal;
  5888. }
  5889. //WTF- why did we have this?
  5890. /*if ((flags & BfEvalExprFlags_ExplicitCast) == 0)
  5891. typedVal = LoadValue(typedVal, 0, exprEvaluator.mIsVolatileReference);*/
  5892. if (exprEvaluator.mIsVolatileReference)
  5893. typedVal = LoadValue(typedVal, 0, exprEvaluator.mIsVolatileReference);
  5894. }
  5895. // if ((typedVal.IsSplat()) && ((flags & BfEvalExprFlags_AllowSplat) == 0))
  5896. // typedVal = MakeAddressable(typedVal);
  5897. //typedVal = AggregateSplat(typedVal);
  5898. if ((typedVal.mType->IsValueType()) && ((flags & BfEvalExprFlags_NoValueAddr) != 0))
  5899. typedVal = LoadValue(typedVal, 0, exprEvaluator.mIsVolatileReference);
  5900. return typedVal;
  5901. }
  5902. BfTypedValue BfModule::CreateValueFromExpression(BfExpression* expr, BfType* wantTypeRef, BfEvalExprFlags flags, BfType** outOrigType)
  5903. {
  5904. BfExprEvaluator exprEvaluator(this);
  5905. return CreateValueFromExpression(exprEvaluator, expr, wantTypeRef, flags, outOrigType);
  5906. }
  5907. BfTypedValue BfModule::GetOrCreateVarAddr(BfExpression* expr)
  5908. {
  5909. BfExprEvaluator exprEvaluator(this);
  5910. exprEvaluator.Evaluate(expr);
  5911. if (!exprEvaluator.mResult)
  5912. {
  5913. Fail("Invalid expression type", expr);
  5914. return BfTypedValue();
  5915. }
  5916. if (!exprEvaluator.mResult.IsAddr())
  5917. {
  5918. Fail("Cannot assign to value", expr);
  5919. return BfTypedValue();
  5920. }
  5921. return exprEvaluator.mResult;
  5922. }
  5923. // Clear memory, set classVData, call init. Actual ctor is called elsewhere.
  5924. void BfModule::InitTypeInst(BfTypedValue typedValue, BfScopeData* scopeData, bool zeroMemory, BfIRValue sizeValue)
  5925. {
  5926. auto typeInstance = typedValue.mType->ToTypeInstance();
  5927. if (zeroMemory)
  5928. {
  5929. int zeroAlign = typedValue.mType->mAlign;
  5930. if (typeInstance != NULL)
  5931. zeroAlign = typeInstance->mInstAlign;
  5932. mBfIRBuilder->CreateMemSet(typedValue.mValue, GetConstValue8(0), sizeValue, zeroAlign);
  5933. }
  5934. if (!typedValue.mType->IsObject())
  5935. {
  5936. return;
  5937. }
  5938. if ((scopeData == NULL) && (mCurMethodState != NULL))
  5939. return; // Handled in heap alloc funcs
  5940. auto typeDef = typeInstance->mTypeDef;
  5941. mBfIRBuilder->PopulateType(typedValue.mType);
  5942. auto vObjectAddr = mBfIRBuilder->CreateInBoundsGEP(typedValue.mValue, 0, 0);
  5943. bool isAutocomplete = mCompiler->IsAutocomplete();
  5944. BfIRValue vDataRef;
  5945. if (!isAutocomplete)
  5946. {
  5947. vDataRef = GetClassVDataPtr(typeInstance);
  5948. }
  5949. auto i8Type = GetPrimitiveType(BfTypeCode_Int8);
  5950. auto ptrType = CreatePointerType(i8Type);
  5951. auto ptrPtrType = CreatePointerType(ptrType);
  5952. PopulateType(ptrPtrType, BfPopulateType_Declaration);
  5953. PopulateType(ptrType, BfPopulateType_Declaration);
  5954. auto destAddr = mBfIRBuilder->CreateBitCast(vObjectAddr, mBfIRBuilder->MapType(ptrPtrType));
  5955. if (!isAutocomplete)
  5956. {
  5957. if (mCompiler->mOptions.mObjectHasDebugFlags)
  5958. {
  5959. auto objectPtr = mBfIRBuilder->CreateBitCast(destAddr, mBfIRBuilder->MapType(mContext->mBfObjectType));
  5960. SizedArray<BfIRValue, 4> llvmArgs;
  5961. llvmArgs.push_back(objectPtr);
  5962. llvmArgs.push_back(vDataRef);
  5963. auto objectStackInitMethod = GetInternalMethod("Dbg_ObjectStackInit");
  5964. if (objectStackInitMethod)
  5965. mBfIRBuilder->CreateCall(objectStackInitMethod.mFunc, llvmArgs);
  5966. }
  5967. else
  5968. {
  5969. auto srcVal = mBfIRBuilder->CreateBitCast(vDataRef, mBfIRBuilder->MapType(ptrType));
  5970. auto objectPtr = mBfIRBuilder->CreateBitCast(destAddr, mBfIRBuilder->MapType(ptrType));
  5971. mBfIRBuilder->CreateStore(srcVal, destAddr);
  5972. }
  5973. }
  5974. }
  5975. BfIRValue BfModule::AllocBytes(BfAstNode* refNode, const BfAllocTarget& allocTarget, BfType* type, BfIRValue sizeValue, BfIRValue alignValue, BfAllocFlags allocFlags/*, bool zeroMemory, bool defaultToMalloc*/)
  5976. {
  5977. BfIRValue result;
  5978. BfType* ptrType;
  5979. if ((type->IsObject()) && ((allocFlags & BfAllocFlags_RawArray) == 0))
  5980. ptrType = type;
  5981. else
  5982. ptrType = CreatePointerType(type);
  5983. if ((allocTarget.mScopedInvocationTarget != NULL) || (allocTarget.mCustomAllocator))
  5984. {
  5985. auto intType = GetPrimitiveType(BfTypeCode_IntPtr);
  5986. SizedArray<BfExpression*, 2> argExprs;
  5987. BfTypedValueExpression typedValueExpr;
  5988. typedValueExpr.Init(BfTypedValue(sizeValue, intType));
  5989. typedValueExpr.mRefNode = refNode;
  5990. argExprs.push_back(&typedValueExpr);
  5991. BfTypedValueExpression appendSizeValueExpr;
  5992. appendSizeValueExpr.Init(BfTypedValue(alignValue, intType));
  5993. appendSizeValueExpr.mRefNode = refNode;
  5994. argExprs.push_back(&appendSizeValueExpr);
  5995. BfExprEvaluator exprEvaluator(this);
  5996. BfTypedValue allocResult;
  5997. if (allocTarget.mScopedInvocationTarget != NULL)
  5998. {
  5999. SizedArray<BfTypeReference*, 2> genericArgs;
  6000. exprEvaluator.DoInvocation(allocTarget.mScopedInvocationTarget, NULL, argExprs, NULL);
  6001. allocResult = LoadValue(exprEvaluator.mResult);
  6002. }
  6003. else if (allocTarget.mCustomAllocator)
  6004. {
  6005. auto customTypeInst = allocTarget.mCustomAllocator.mType->ToTypeInstance();
  6006. if (customTypeInst != NULL)
  6007. {
  6008. BfTypedValueExpression typeValueExpr;
  6009. String allocMethodName = "Alloc";
  6010. if (GetRawMethodByName(customTypeInst, "AllocTyped", -1, true, true))
  6011. {
  6012. allocMethodName = "AllocTyped";
  6013. auto typeType = ResolveTypeDef(mCompiler->mTypeTypeDef);
  6014. auto typeRefVal = CreateTypeDataRef(type);
  6015. typeValueExpr.Init(BfTypedValue(typeRefVal, typeType));
  6016. typeValueExpr.mRefNode = refNode;
  6017. argExprs.Insert(0, &typeValueExpr);
  6018. }
  6019. if (HasMixin(customTypeInst, allocMethodName, 2))
  6020. {
  6021. BfSizedArray<BfExpression*> argExprArr;
  6022. argExprArr.mSize = (int)argExprs.size();
  6023. argExprArr.mVals = &argExprs[0];
  6024. exprEvaluator.InjectMixin(refNode, allocTarget.mCustomAllocator, false, allocMethodName, argExprs, {});
  6025. allocResult = exprEvaluator.GetResult();
  6026. }
  6027. else
  6028. {
  6029. BfSizedArray<BfExpression*> sizedArgExprs(argExprs);
  6030. BfResolvedArgs argValues(&sizedArgExprs);
  6031. exprEvaluator.ResolveArgValues(argValues);
  6032. SetAndRestoreValue<bool> prevNoBind(mCurMethodState->mNoBind, true);
  6033. allocResult = exprEvaluator.MatchMethod(refNode, NULL, allocTarget.mCustomAllocator, false, false, allocMethodName, argValues, NULL);
  6034. }
  6035. }
  6036. }
  6037. if (allocResult)
  6038. {
  6039. if (allocResult.mType->IsVoidPtr())
  6040. result = mBfIRBuilder->CreateBitCast(allocResult.mValue, mBfIRBuilder->MapType(ptrType));
  6041. else
  6042. result = CastToValue(refNode, allocResult, ptrType, BfCastFlags_Explicit);
  6043. return result;
  6044. }
  6045. }
  6046. if ((allocFlags & BfAllocFlags_NoDefaultToMalloc) != 0)
  6047. return result;
  6048. if (mCompiler->mOptions.mDebugAlloc)
  6049. {
  6050. BfIRValue allocData = GetDbgRawAllocData(type);
  6051. BfModuleMethodInstance allocMethod = GetInternalMethod("Dbg_RawAlloc", 2);
  6052. SizedArray<BfIRValue, 2> llvmArgs;
  6053. llvmArgs.push_back(sizeValue);
  6054. llvmArgs.push_back(allocData);
  6055. BfIRValue bitData = mBfIRBuilder->CreateCall(allocMethod.mFunc, llvmArgs);
  6056. return mBfIRBuilder->CreateBitCast(bitData, mBfIRBuilder->MapType(ptrType));
  6057. }
  6058. BfModuleMethodInstance moduleMethodInstance;
  6059. moduleMethodInstance = GetInternalMethod("Malloc");
  6060. SizedArray<BfIRValue, 1> llvmArgs;
  6061. llvmArgs.push_back(sizeValue);
  6062. auto func = moduleMethodInstance.mFunc;
  6063. if ((!func) || (func.IsFake()))
  6064. {
  6065. BF_ASSERT((mCompiler->mIsResolveOnly) || (mBfIRBuilder->mIgnoreWrites));
  6066. return mBfIRBuilder->CreateUndefValue(mBfIRBuilder->MapType(ptrType));
  6067. }
  6068. BfIRValue bitData = mBfIRBuilder->CreateCall(func, llvmArgs);
  6069. if ((allocFlags & BfAllocFlags_ZeroMemory) != 0)
  6070. mBfIRBuilder->CreateMemSet(bitData, GetConstValue8(0), sizeValue, alignValue);
  6071. result = mBfIRBuilder->CreateBitCast(bitData, mBfIRBuilder->MapType(ptrType));
  6072. return result;
  6073. }
  6074. BfIRValue BfModule::GetMarkFuncPtr(BfType* type)
  6075. {
  6076. if (type->IsStruct())
  6077. {
  6078. auto typeInstance = type->ToTypeInstance();
  6079. BfModuleMethodInstance moduleMethodInst = GetMethodByName(typeInstance, BF_METHODNAME_MARKMEMBERS, 0, true);
  6080. return mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr)));
  6081. }
  6082. else if (type->IsObjectOrInterface())
  6083. {
  6084. auto gcType = ResolveTypeDef(mCompiler->mGCTypeDef)->ToTypeInstance();
  6085. BfModuleMethodInstance moduleMethodInst = GetMethodByName(gcType, "MarkDerefedObject");
  6086. BF_ASSERT(moduleMethodInst.mFunc);
  6087. return mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr)));
  6088. }
  6089. else
  6090. {
  6091. auto gcType = ResolveTypeDef(mCompiler->mGCTypeDef)->ToTypeInstance();
  6092. BfExprEvaluator exprEvaluator(this);
  6093. SizedArray<BfResolvedArg, 1> resolvedArgs;
  6094. BfResolvedArg resolvedArg;
  6095. resolvedArg.mTypedValue = BfTypedValue(mBfIRBuilder->GetFakeVal(), type, type->IsComposite());
  6096. resolvedArgs.Add(resolvedArg);
  6097. BfMethodMatcher methodMatcher(NULL, this, "Mark", resolvedArgs, NULL);
  6098. methodMatcher.CheckType(gcType, BfTypedValue(), false);
  6099. BfModuleMethodInstance moduleMethodInst = exprEvaluator.GetSelectedMethod(NULL, methodMatcher.mBestMethodTypeInstance, methodMatcher.mBestMethodDef, methodMatcher);
  6100. BF_ASSERT(moduleMethodInst.mFunc);
  6101. return mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr)));
  6102. }
  6103. return BfIRValue();
  6104. }
  6105. BfIRValue BfModule::GetDbgRawAllocData(BfType* type)
  6106. {
  6107. BfIRValue allocDataValue;
  6108. if (mDbgRawAllocDataRefs.TryGetValue(type, &allocDataValue))
  6109. return allocDataValue;
  6110. BfIRValue markFuncPtr;
  6111. if (type->WantsGCMarking())
  6112. markFuncPtr = GetMarkFuncPtr(type);
  6113. else
  6114. markFuncPtr = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr)));
  6115. BfIRValue typeDataRef = CreateTypeDataRef(type);
  6116. auto dbgRawAllocDataType = ResolveTypeDef(mCompiler->mDbgRawAllocDataTypeDef)->ToTypeInstance();
  6117. BfTypeInstance* typeInstance = type->ToTypeInstance();
  6118. if (typeInstance == NULL)
  6119. {
  6120. typeInstance = GetWrappedStructType(type);
  6121. if (typeInstance != NULL)
  6122. AddDependency(typeInstance, mCurTypeInstance, BfDependencyMap::DependencyFlag_Allocates);
  6123. }
  6124. if (typeInstance != NULL)
  6125. PopulateType(typeInstance);
  6126. int stackCount = mCompiler->mOptions.mAllocStackCount;
  6127. if ((typeInstance != NULL) && (typeInstance->mTypeOptionsIdx != -1))
  6128. {
  6129. auto typeOptions = mSystem->GetTypeOptions(typeInstance->mTypeOptionsIdx);
  6130. stackCount = BfTypeOptions::Apply(stackCount, typeOptions->mAllocStackTraceDepth);
  6131. }
  6132. SizedArray<BfIRValue, 2> dataValues;
  6133. dataValues.Add(mBfIRBuilder->CreateConstStructZero(mBfIRBuilder->MapType(dbgRawAllocDataType->mBaseType, BfIRPopulateType_Full)));
  6134. dataValues.Add(typeDataRef);
  6135. dataValues.Add(markFuncPtr);
  6136. dataValues.Add(mBfIRBuilder->CreateConst(BfTypeCode_Int32, stackCount));
  6137. BfIRValue dataStruct = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapType(dbgRawAllocDataType, BfIRPopulateType_Full), dataValues);
  6138. allocDataValue = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapType(dbgRawAllocDataType), true, BfIRLinkageType_Internal, dataStruct, "__allocData_" + BfSafeMangler::Mangle(type));
  6139. mDbgRawAllocDataRefs.TryAdd(type, allocDataValue);
  6140. return allocDataValue;
  6141. }
  6142. BfIRValue BfModule::AllocFromType(BfType* type, const BfAllocTarget& allocTarget, BfIRValue appendSizeValue, BfIRValue arraySize, int arrayDim, BfAllocFlags allocFlags, int alignOverride)
  6143. {
  6144. BP_ZONE("AllocFromType");
  6145. BfScopeData* scopeData = allocTarget.mScopeData;
  6146. auto typeInstance = type->ToTypeInstance();
  6147. if ((typeInstance == NULL) && (type->IsGenericParam()))
  6148. typeInstance = mContext->mBfObjectType;
  6149. bool isHeapAlloc = scopeData == NULL;
  6150. bool isScopeAlloc = scopeData != NULL;
  6151. bool isLoopedAlloc = (scopeData != NULL) && (mCurMethodState->mCurScope->IsLooped(scopeData));
  6152. bool isDynAlloc = (scopeData != NULL) && (mCurMethodState->mCurScope->IsDyn(scopeData));
  6153. bool isRawArrayAlloc = (allocFlags & BfAllocFlags_RawArray) != 0;
  6154. bool zeroMemory = (allocFlags & BfAllocFlags_ZeroMemory) != 0;
  6155. bool noDtorCall = (allocFlags & BfAllocFlags_NoDtorCall) != 0;
  6156. if ((type->IsValuelessType()) && ((!arraySize) || (isRawArrayAlloc)))
  6157. {
  6158. BfPointerType* ptrType = CreatePointerType(type);
  6159. auto val = mBfIRBuilder->CreateIntToPtr(mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 1), mBfIRBuilder->MapType(ptrType));
  6160. return val;
  6161. }
  6162. if (typeInstance != NULL)
  6163. mBfIRBuilder->PopulateType(typeInstance);
  6164. bool hasCustomAllocator = (allocTarget.mCustomAllocator) || (allocTarget.mScopedInvocationTarget != NULL);
  6165. if ((!hasCustomAllocator) && (mBfIRBuilder->mIgnoreWrites))
  6166. {
  6167. if (arraySize)
  6168. {
  6169. if (isRawArrayAlloc)
  6170. {
  6171. BfPointerType* ptrType = CreatePointerType(type);
  6172. return GetDefaultValue(ptrType);
  6173. }
  6174. BfArrayType* arrayType = CreateArrayType(type, arrayDim);
  6175. return GetDefaultValue(arrayType);
  6176. }
  6177. if (type->IsValueType())
  6178. {
  6179. BfPointerType* ptrType = CreatePointerType(type);
  6180. return GetDefaultValue(ptrType);
  6181. }
  6182. return mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(type));
  6183. }
  6184. AddDependency(type, mCurTypeInstance, BfDependencyMap::DependencyFlag_Allocates);
  6185. BfIRValue sizeValue;
  6186. BfIRType allocType = mBfIRBuilder->MapType(type);
  6187. int allocSize = type->mSize;
  6188. int allocAlign = type->mAlign;
  6189. if (typeInstance != NULL)
  6190. {
  6191. if (!mBfIRBuilder->mIgnoreWrites)
  6192. typeInstance->mHasBeenInstantiated = true;
  6193. allocSize = typeInstance->mInstSize;
  6194. allocAlign = typeInstance->mInstAlign;
  6195. //if (typeInstance->IsEnum())
  6196. //allocType = typeInstance->mIRType;
  6197. allocType = mBfIRBuilder->MapTypeInst(typeInstance);
  6198. }
  6199. if (alignOverride != -1)
  6200. allocAlign = alignOverride;
  6201. // The "dynSize" cases:
  6202. // If we are not dyn, but we are a variable size and could be looped over multiple times then we attempt to reuse
  6203. // the last stack space. We won't use StackSave and StackRestore because a scoped alloc that occurs after this but
  6204. // needs to be retained after the current scopeData (ie: scopeData::), then it would cause these allocs to accumulate even
  6205. // though we'd expect their stack space to be released
  6206. auto _CreateDynAlloc = [&](const BfIRValue& sizeValue, int align)
  6207. {
  6208. MarkDynStack(scopeData);
  6209. BfType* intType = GetPrimitiveType(BfTypeCode_IntPtr);
  6210. // For dynamically sized scoped allocs, we need to check the previous size to see if we need to realloc
  6211. BfType* voidType = GetPrimitiveType(BfTypeCode_None);
  6212. BfType* voidPtrType = CreatePointerType(voidType);
  6213. if (!mCurMethodState->mDynStackRevIdx)
  6214. {
  6215. mCurMethodState->mDynStackRevIdx = CreateAlloca(intType, false, "curDynStackRevIdx");
  6216. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  6217. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRInitBlock);
  6218. auto storeInst = mBfIRBuilder->CreateStore(GetConstValue(0), mCurMethodState->mDynStackRevIdx);
  6219. mBfIRBuilder->ClearDebugLocation(storeInst);
  6220. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  6221. }
  6222. auto byteType = GetPrimitiveType(BfTypeCode_Int8);
  6223. auto bytePtrType = CreatePointerType(byteType);
  6224. auto dynSizeAllocaInst = CreateAlloca(intType, false, "dynSize");
  6225. auto dynStackRevIdx = CreateAlloca(intType, false, "dynStackRevIdx");
  6226. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  6227. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRInitBlock);
  6228. auto storeInst = mBfIRBuilder->CreateStore(GetConstValue(0), dynSizeAllocaInst);
  6229. mBfIRBuilder->ClearDebugLocation(storeInst);
  6230. storeInst = mBfIRBuilder->CreateStore(GetConstValue(0), dynStackRevIdx);
  6231. mBfIRBuilder->ClearDebugLocation(storeInst);
  6232. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  6233. auto dynPtrAllocaInst = CreateAlloca(bytePtrType, false, "dynPtr");
  6234. if (IsTargetingBeefBackend())
  6235. {
  6236. // Since we don't allocate a debug variable for this, with LifetimeExtends, the easiest way
  6237. // to ensure there isn't any register collision during looping is just to not allow it to
  6238. // bind to a register at all
  6239. mBfIRBuilder->SetAllocaForceMem(dynSizeAllocaInst);
  6240. mBfIRBuilder->SetAllocaForceMem(dynPtrAllocaInst);
  6241. }
  6242. auto resizeBB = mBfIRBuilder->CreateBlock("dynAlloc.resize");
  6243. auto endBB = mBfIRBuilder->CreateBlock("dynAlloc.end");
  6244. auto verCheckBB = mBfIRBuilder->CreateBlock("dynAlloc.verCheck");
  6245. auto curDynStackRevIdx = mBfIRBuilder->CreateLoad(mCurMethodState->mDynStackRevIdx);
  6246. auto prevSize = mBfIRBuilder->CreateLoad(dynSizeAllocaInst);
  6247. auto isGreater = mBfIRBuilder->CreateCmpGT(sizeValue, prevSize, true);
  6248. mBfIRBuilder->CreateCondBr(isGreater, resizeBB, verCheckBB);
  6249. mBfIRBuilder->AddBlock(verCheckBB);
  6250. mBfIRBuilder->SetInsertPoint(verCheckBB);
  6251. auto prevDynStackRevIdx = mBfIRBuilder->CreateLoad(dynStackRevIdx);
  6252. auto dynStackChanged = mBfIRBuilder->CreateCmpNE(prevDynStackRevIdx, curDynStackRevIdx);
  6253. mBfIRBuilder->CreateCondBr(dynStackChanged, resizeBB, endBB);
  6254. mBfIRBuilder->AddBlock(resizeBB);
  6255. mBfIRBuilder->SetInsertPoint(resizeBB);
  6256. auto allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(byteType), sizeValue);
  6257. mBfIRBuilder->SetAllocaAlignment(allocaInst, align);
  6258. mBfIRBuilder->CreateStore(allocaInst, dynPtrAllocaInst);
  6259. mBfIRBuilder->CreateStore(sizeValue, dynSizeAllocaInst);
  6260. mBfIRBuilder->CreateStore(curDynStackRevIdx, dynStackRevIdx);
  6261. mBfIRBuilder->CreateBr(endBB);
  6262. mBfIRBuilder->AddBlock(endBB);
  6263. mBfIRBuilder->SetInsertPoint(endBB);
  6264. return mBfIRBuilder->CreateLoad(dynPtrAllocaInst);
  6265. };
  6266. if (isScopeAlloc)
  6267. {
  6268. if (arraySize)
  6269. {
  6270. bool isConstantArraySize = arraySize.IsConst();
  6271. if (isRawArrayAlloc)
  6272. {
  6273. BfPointerType* ptrType = CreatePointerType(type);
  6274. if ((!isDynAlloc) && (!isConstantArraySize) && (mCurMethodState->mCurScope->IsLooped(NULL)))
  6275. {
  6276. BfIRValue sizeValue = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySize);
  6277. auto loadedPtr = _CreateDynAlloc(sizeValue, type->mAlign);
  6278. InitTypeInst(BfTypedValue(loadedPtr, ptrType), scopeData, zeroMemory, sizeValue);
  6279. return mBfIRBuilder->CreateBitCast(loadedPtr, mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapType(type)));
  6280. }
  6281. else
  6282. {
  6283. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  6284. isDynAlloc = (isDynAlloc) || (!arraySize.IsConst());
  6285. if (!isDynAlloc)
  6286. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  6287. else
  6288. {
  6289. MarkDynStack(scopeData);
  6290. SaveStackState(scopeData);
  6291. }
  6292. int typeSize = type->GetStride();
  6293. BfIRValue allocaInst;
  6294. BfIRValue result;
  6295. if ((typeInstance == NULL) || (typeInstance->mIsCRepr))
  6296. {
  6297. sizeValue = mBfIRBuilder->CreateMul(GetConstValue(typeSize), arraySize);
  6298. allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(type), arraySize);
  6299. result = allocaInst;
  6300. }
  6301. else
  6302. {
  6303. if (typeInstance->IsStruct())
  6304. typeSize = typeInstance->GetInstStride();
  6305. auto byteType = GetPrimitiveStructType(BfTypeCode_Int8);
  6306. sizeValue = mBfIRBuilder->CreateMul(GetConstValue(typeSize), arraySize);
  6307. allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(byteType), sizeValue);
  6308. auto ptrType = CreatePointerType(typeInstance);
  6309. result = mBfIRBuilder->CreateBitCast(allocaInst, mBfIRBuilder->MapType(ptrType));
  6310. if (!isDynAlloc)
  6311. mBfIRBuilder->ClearDebugLocation(result);
  6312. }
  6313. if (!isDynAlloc)
  6314. mBfIRBuilder->ClearDebugLocation(allocaInst);
  6315. mBfIRBuilder->SetAllocaAlignment(allocaInst, type->mAlign);
  6316. if (!isDynAlloc)
  6317. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  6318. auto typedVal = BfTypedValue(result, type, BfTypedValueKind_Addr);
  6319. if (arraySize.IsConst())
  6320. {
  6321. auto constant = mBfIRBuilder->GetConstant(arraySize);
  6322. if (constant->mInt64 == 0)
  6323. noDtorCall = true;
  6324. }
  6325. if (!noDtorCall)
  6326. {
  6327. bool isConstSize = arraySize.IsConst();
  6328. BfIRBlock clearBlock;
  6329. BfIRBlock contBlock;
  6330. if (!isConstSize)
  6331. {
  6332. clearBlock = mBfIRBuilder->CreateBlock("clear");
  6333. contBlock = mBfIRBuilder->CreateBlock("clearCont");
  6334. mBfIRBuilder->CreateCondBr(mBfIRBuilder->CreateCmpNE(arraySize, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 0)), clearBlock, contBlock);
  6335. mBfIRBuilder->AddBlock(clearBlock);
  6336. mBfIRBuilder->SetInsertPoint(clearBlock);
  6337. }
  6338. AddStackAlloc(typedVal, NULL, scopeData, false, true);
  6339. if (!isConstSize)
  6340. {
  6341. mBfIRBuilder->CreateBr(contBlock);
  6342. mBfIRBuilder->AddBlock(contBlock);
  6343. mBfIRBuilder->SetInsertPoint(contBlock);
  6344. }
  6345. }
  6346. //InitTypeInst(typedVal, scopeData, zeroMemory, sizeValue);
  6347. return result;
  6348. }
  6349. }
  6350. else
  6351. {
  6352. if ((!isDynAlloc) && (!arraySize.IsConst()) && (mCurMethodState->mCurScope->IsLooped(NULL)))
  6353. {
  6354. // Generate and check new size
  6355. BfArrayType* arrayType = CreateArrayType(type, arrayDim);
  6356. auto firstElementField = &arrayType->mFieldInstances.back();
  6357. int arrayClassSize = firstElementField->mDataOffset;
  6358. sizeValue = GetConstValue(arrayClassSize);
  6359. BfIRValue elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySize);
  6360. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, elementDataSize);
  6361. auto loadedPtr = _CreateDynAlloc(sizeValue, arrayType->mAlign);
  6362. auto typedVal = BfTypedValue(mBfIRBuilder->CreateBitCast(loadedPtr, mBfIRBuilder->MapType(arrayType)), arrayType);
  6363. if (!noDtorCall)
  6364. AddStackAlloc(typedVal, NULL, scopeData, false, true);
  6365. InitTypeInst(typedVal, scopeData, zeroMemory, sizeValue);
  6366. return typedVal.mValue;
  6367. }
  6368. else
  6369. {
  6370. BfArrayType* arrayType = CreateArrayType(type, arrayDim);
  6371. auto firstElementField = &arrayType->mFieldInstances.back();
  6372. int arrayClassSize = firstElementField->mDataOffset;
  6373. sizeValue = GetConstValue(arrayClassSize);
  6374. BfIRValue elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySize);
  6375. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, elementDataSize);
  6376. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  6377. isDynAlloc = (isDynAlloc) || (!sizeValue.IsConst());
  6378. if (!isDynAlloc)
  6379. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  6380. else
  6381. {
  6382. MarkDynStack(scopeData);
  6383. SaveStackState(scopeData);
  6384. }
  6385. BfType* byteType = GetPrimitiveType(BfTypeCode_Int8);
  6386. auto allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(byteType), sizeValue);
  6387. if (!isDynAlloc)
  6388. mBfIRBuilder->ClearDebugLocation(allocaInst);
  6389. mBfIRBuilder->SetAllocaAlignment(allocaInst, arrayType->mAlign);
  6390. auto typedVal = BfTypedValue(mBfIRBuilder->CreateBitCast(allocaInst, mBfIRBuilder->MapType(arrayType)), arrayType);
  6391. mBfIRBuilder->ClearDebugLocation_Last();
  6392. if (!isDynAlloc)
  6393. mBfIRBuilder->SetInsertPoint(prevBlock);
  6394. if (!noDtorCall)
  6395. AddStackAlloc(typedVal, NULL, scopeData, false, true);
  6396. InitTypeInst(typedVal, scopeData, zeroMemory, sizeValue);
  6397. return typedVal.mValue;
  6398. }
  6399. }
  6400. }
  6401. else if (appendSizeValue)
  6402. {
  6403. // It may seem that we should check IsLooped against only the requested scope, BUT- if later on we perform
  6404. // a scoped alloc that crosses our boundary then we won't be able to reclaim the stack space, so we always
  6405. // use the "dynSize" version conservatively
  6406. if ((!isDynAlloc) && (!appendSizeValue.IsConst()) && (mCurMethodState->mCurScope->IsLooped(NULL)))
  6407. {
  6408. // Generate and check new size
  6409. sizeValue = GetConstValue(typeInstance->mInstSize);
  6410. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, appendSizeValue);
  6411. auto loadedPtr = _CreateDynAlloc(sizeValue, typeInstance->mAlign);
  6412. auto typedVal = BfTypedValue(mBfIRBuilder->CreateBitCast(loadedPtr, mBfIRBuilder->MapTypeInstPtr(typeInstance)), typeInstance);
  6413. if (!noDtorCall)
  6414. AddStackAlloc(typedVal, NULL, scopeData, mCurMethodState->mInConditionalBlock, true);
  6415. InitTypeInst(typedVal, scopeData, zeroMemory, sizeValue);
  6416. return typedVal.mValue;
  6417. }
  6418. else // stack alloc, unlooped, with append
  6419. {
  6420. sizeValue = GetConstValue(typeInstance->mInstSize);
  6421. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, appendSizeValue);
  6422. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  6423. bool wasDynAlloc = isDynAlloc;
  6424. isDynAlloc = (isDynAlloc) || (!sizeValue.IsConst());
  6425. if (!isDynAlloc)
  6426. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  6427. else
  6428. {
  6429. MarkDynStack(scopeData);
  6430. SaveStackState(scopeData);
  6431. }
  6432. auto sbyteType = GetPrimitiveType(BfTypeCode_Int8);
  6433. auto allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(sbyteType), sizeValue);
  6434. if (!isDynAlloc)
  6435. {
  6436. mBfIRBuilder->ClearDebugLocation(allocaInst);
  6437. }
  6438. mBfIRBuilder->SetAllocaAlignment(allocaInst, allocAlign);
  6439. bool mayBeLarge = false;
  6440. if (sizeValue.IsConst())
  6441. {
  6442. auto constantInt = mBfIRBuilder->GetConstant(sizeValue);
  6443. if (constantInt->mInt64 >= 4096)
  6444. mayBeLarge = true;
  6445. }
  6446. else
  6447. mayBeLarge = true;
  6448. if (((type->IsObject() && (!mayBeLarge))) ||
  6449. // If we create a memset that can fill in backwards (or at least 4k chunked backward) then we can remove the '!mayBeLarge' cond
  6450. ((zeroMemory) && (!mayBeLarge)))
  6451. {
  6452. mBfIRBuilder->SetAllocaNoChkStkHint(allocaInst);
  6453. }
  6454. BfIRValue castedVal;
  6455. if (!isDynAlloc)
  6456. {
  6457. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRInitBlock);
  6458. castedVal = mBfIRBuilder->CreateBitCast(allocaInst, mBfIRBuilder->MapTypeInstPtr(typeInstance));
  6459. mBfIRBuilder->ClearDebugLocation(castedVal);
  6460. mBfIRBuilder->SetInsertPoint(prevBlock);
  6461. if (WantsLifetimes())
  6462. {
  6463. mBfIRBuilder->CreateLifetimeStart(allocaInst);
  6464. scopeData->mDeferredLifetimeEnds.push_back(allocaInst);
  6465. }
  6466. }
  6467. else
  6468. {
  6469. castedVal = mBfIRBuilder->CreateBitCast(allocaInst, mBfIRBuilder->MapTypeInstPtr(typeInstance));
  6470. }
  6471. auto typedVal = BfTypedValue(castedVal, typeInstance);
  6472. if (!noDtorCall)
  6473. {
  6474. bool doCondAlloca = false;
  6475. if (!IsTargetingBeefBackend())
  6476. doCondAlloca = !wasDynAlloc && isDynAlloc && mCurMethodState->mInConditionalBlock;
  6477. AddStackAlloc(typedVal, NULL, scopeData, doCondAlloca, true);
  6478. }
  6479. InitTypeInst(typedVal, scopeData, zeroMemory, sizeValue);
  6480. return typedVal.mValue;
  6481. }
  6482. }
  6483. else // "Normal" stack alloc
  6484. {
  6485. BF_ASSERT(!sizeValue);
  6486. //TODO: If sizeValue is a constant then do this in the head IR builder
  6487. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  6488. if (!isLoopedAlloc)
  6489. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  6490. else
  6491. {
  6492. MarkDynStack(scopeData);
  6493. SaveStackState(scopeData);
  6494. }
  6495. auto allocaInst = mBfIRBuilder->CreateAlloca(allocType);
  6496. if (!isLoopedAlloc)
  6497. mBfIRBuilder->ClearDebugLocation(allocaInst);
  6498. mBfIRBuilder->SetAllocaAlignment(allocaInst, allocAlign);
  6499. bool mayBeLarge = allocSize >= 4096;
  6500. if (((typeInstance != NULL) && (typeInstance->IsObject()) && (!mayBeLarge)) ||
  6501. // If we create a memset that can fill in backwards (or at least 4k chunked backward) then we can remove the '!mayBeLarge' cond
  6502. ((zeroMemory) && (!mayBeLarge)))
  6503. {
  6504. // With an object, we know we will at least set the vdata pointer which will probe the start of the new address,
  6505. // and memset is always safe
  6506. mBfIRBuilder->SetAllocaNoChkStkHint(allocaInst);
  6507. }
  6508. auto typedVal = BfTypedValue(allocaInst, type);
  6509. if (!isLoopedAlloc)
  6510. {
  6511. mBfIRBuilder->ClearDebugLocation(allocaInst);
  6512. mBfIRBuilder->SetInsertPoint(prevBlock);
  6513. if (WantsLifetimes())
  6514. {
  6515. mBfIRBuilder->CreateLifetimeStart(allocaInst);
  6516. scopeData->mDeferredLifetimeEnds.push_back(allocaInst);
  6517. }
  6518. }
  6519. if (!noDtorCall)
  6520. AddStackAlloc(typedVal, NULL, scopeData, false, true);
  6521. if (typeInstance != NULL)
  6522. {
  6523. InitTypeInst(typedVal, scopeData, zeroMemory, GetConstValue(typeInstance->mInstSize));
  6524. }
  6525. else
  6526. {
  6527. mBfIRBuilder->CreateMemSet(allocaInst, GetConstValue8(0), GetConstValue(allocSize), allocAlign);
  6528. }
  6529. return allocaInst;
  6530. }
  6531. }
  6532. else if (arraySize)
  6533. {
  6534. if (isRawArrayAlloc)
  6535. {
  6536. sizeValue = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySize);
  6537. return AllocBytes(allocTarget.mRefNode, allocTarget, type, sizeValue, GetConstValue(allocAlign), allocFlags);
  6538. }
  6539. else
  6540. {
  6541. BfArrayType* arrayType = CreateArrayType(type, arrayDim);
  6542. typeInstance = arrayType;
  6543. BfIRValue arraySizeMinusOne = mBfIRBuilder->CreateSub(arraySize, GetConstValue(1));
  6544. BfIRValue elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySizeMinusOne);
  6545. appendSizeValue = elementDataSize;
  6546. if (!type->IsSizeAligned())
  6547. {
  6548. appendSizeValue = mBfIRBuilder->CreateAdd(appendSizeValue, GetConstValue(type->GetStride() - type->mSize));
  6549. }
  6550. }
  6551. }
  6552. if ((typeInstance != NULL) && (typeInstance->IsObject()))
  6553. {
  6554. auto vDataRef = GetClassVDataPtr(typeInstance);
  6555. BfIRValue result;
  6556. bool isResultInitialized = false;
  6557. int stackCount = mCompiler->mOptions.mAllocStackCount;
  6558. if (typeInstance->mTypeOptionsIdx != -1)
  6559. {
  6560. auto typeOptions = mSystem->GetTypeOptions(typeInstance->mTypeOptionsIdx);
  6561. stackCount = BfTypeOptions::Apply(stackCount, typeOptions->mAllocStackTraceDepth);
  6562. }
  6563. if (!sizeValue)
  6564. sizeValue = GetConstValue(typeInstance->mInstSize);
  6565. if (appendSizeValue)
  6566. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, appendSizeValue);
  6567. BfIRValue origSizeValue = sizeValue;
  6568. bool isAllocEx = hasCustomAllocator && (stackCount > 1);
  6569. if (isAllocEx)
  6570. {
  6571. auto prepareStackTraceMethod = GetInternalMethod("Dbg_PrepareStackTrace");
  6572. if (prepareStackTraceMethod)
  6573. {
  6574. SizedArray<BfIRValue, 2> irArgs;
  6575. irArgs.Add(sizeValue);
  6576. irArgs.Add(GetConstValue(stackCount));
  6577. auto addlBytes = mBfIRBuilder->CreateCall(prepareStackTraceMethod.mFunc, irArgs);
  6578. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, addlBytes);
  6579. }
  6580. }
  6581. if (allocTarget.mCustomAllocator)
  6582. {
  6583. auto customAlloc = allocTarget.mCustomAllocator.mType->ToTypeInstance();
  6584. // Use AllocObject if we have it, otherwise we just use AllocBytes further down
  6585. if ((customAlloc != NULL) && (GetRawMethodByName(customAlloc, "AllocObject", -1, true, true) != NULL))
  6586. {
  6587. auto classVDataType = ResolveTypeDef(mCompiler->mClassVDataTypeDef);
  6588. mBfIRBuilder->PopulateType(classVDataType);
  6589. auto typeInstType = ResolveTypeDef(mCompiler->mReflectTypeInstanceTypeDef)->ToTypeInstance();
  6590. mBfIRBuilder->PopulateType(typeInstType);
  6591. auto typePtrPtr = mBfIRBuilder->CreateInBoundsGEP(vDataRef, 0, 1); // mType
  6592. auto typePtr = mBfIRBuilder->CreateLoad(typePtrPtr);
  6593. auto typeInstPtr = mBfIRBuilder->CreateBitCast(typePtr, mBfIRBuilder->MapTypeInstPtr(typeInstType));
  6594. BfTypedValueExpression typedValueExpr;
  6595. typedValueExpr.Init(BfTypedValue(typeInstPtr, typeInstType));
  6596. typedValueExpr.mRefNode = allocTarget.mRefNode;
  6597. BfExprEvaluator exprEvaluator(this);
  6598. SizedArray<BfExpression*, 2> argExprs;
  6599. argExprs.push_back(&typedValueExpr);
  6600. BfTypedValueExpression sizeValueExpr;
  6601. sizeValueExpr.Init(BfTypedValue(sizeValue, GetPrimitiveType(BfTypeCode_IntPtr)));
  6602. sizeValueExpr.mRefNode = allocTarget.mRefNode;
  6603. argExprs.push_back(&sizeValueExpr);
  6604. BfSizedArray<BfExpression*> sizedArgExprs(argExprs);
  6605. BfResolvedArgs argValues(&sizedArgExprs);
  6606. exprEvaluator.ResolveArgValues(argValues);
  6607. exprEvaluator.mNoBind = true;
  6608. BfTypedValue allocResult = exprEvaluator.MatchMethod(allocTarget.mRefNode, NULL, allocTarget.mCustomAllocator, false, false, "AllocObject", argValues, NULL);
  6609. if (allocResult)
  6610. {
  6611. if ((allocResult.mType->IsVoidPtr()) || (allocResult.mType == mContext->mBfObjectType))
  6612. result = mBfIRBuilder->CreateBitCast(allocResult.mValue, mBfIRBuilder->MapType(typeInstance));
  6613. else
  6614. result = CastToValue(allocTarget.mRefNode, allocResult, typeInstance, BfCastFlags_Explicit);
  6615. isResultInitialized = true;
  6616. }
  6617. }
  6618. }
  6619. if (!result)
  6620. {
  6621. if (hasCustomAllocator)
  6622. result = AllocBytes(allocTarget.mRefNode, allocTarget, typeInstance, sizeValue, GetConstValue(typeInstance->mInstAlign), (BfAllocFlags)(BfAllocFlags_ZeroMemory | BfAllocFlags_NoDefaultToMalloc));
  6623. }
  6624. if (result)
  6625. {
  6626. if (mCompiler->mOptions.mObjectHasDebugFlags)
  6627. {
  6628. auto objectPtr = mBfIRBuilder->CreateBitCast(result, mBfIRBuilder->MapTypeInstPtr(mContext->mBfObjectType));
  6629. SizedArray<BfIRValue, 4> llvmArgs;
  6630. llvmArgs.push_back(objectPtr);
  6631. llvmArgs.push_back(origSizeValue);
  6632. llvmArgs.push_back(vDataRef);
  6633. auto objectCreatedMethod = GetInternalMethod(isAllocEx ?
  6634. (isResultInitialized ? "Dbg_ObjectCreatedEx" : "Dbg_ObjectAllocatedEx") :
  6635. (isResultInitialized ? "Dbg_ObjectCreated" : "Dbg_ObjectAllocated"));
  6636. mBfIRBuilder->CreateCall(objectCreatedMethod.mFunc, llvmArgs);
  6637. }
  6638. else
  6639. {
  6640. auto ptrType = mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr);
  6641. auto vDataPtr = mBfIRBuilder->CreateBitCast(vDataRef, ptrType);
  6642. auto vDataMemberPtr = mBfIRBuilder->CreateBitCast(result, mBfIRBuilder->GetPointerTo(ptrType));
  6643. mBfIRBuilder->CreateStore(vDataPtr, vDataMemberPtr);
  6644. }
  6645. }
  6646. else
  6647. {
  6648. if ((mBfIRBuilder->mIgnoreWrites) || (mCompiler->mIsResolveOnly))
  6649. return GetDefaultValue(typeInstance);
  6650. auto classVDataType = ResolveTypeDef(mCompiler->mClassVDataTypeDef);
  6651. auto vData = mBfIRBuilder->CreateBitCast(vDataRef, mBfIRBuilder->MapTypeInstPtr(classVDataType->ToTypeInstance()));
  6652. if (mCompiler->mOptions.mObjectHasDebugFlags)
  6653. {
  6654. SizedArray<BfIRValue, 4> llvmArgs;
  6655. llvmArgs.push_back(vData);
  6656. llvmArgs.push_back(sizeValue);
  6657. llvmArgs.push_back(GetConstValue(typeInstance->mAlign));
  6658. llvmArgs.push_back(GetConstValue(stackCount));
  6659. auto moduleMethodInstance = GetInternalMethod("Dbg_ObjectAlloc", 4);
  6660. BfIRValue objectVal = mBfIRBuilder->CreateCall(moduleMethodInstance.mFunc, llvmArgs);
  6661. result = mBfIRBuilder->CreateBitCast(objectVal, mBfIRBuilder->MapType(typeInstance));
  6662. }
  6663. else
  6664. {
  6665. SizedArray<BfIRValue, 4> llvmArgs;
  6666. llvmArgs.push_back(sizeValue);
  6667. BfIRFunction irFunc;
  6668. if (mCompiler->mOptions.mDebugAlloc)
  6669. {
  6670. auto moduleMethodInstance = GetInternalMethod("Dbg_RawObjectAlloc", 1);
  6671. irFunc = moduleMethodInstance.mFunc;
  6672. }
  6673. if (!irFunc)
  6674. irFunc = GetBuiltInFunc(BfBuiltInFuncType_Malloc);
  6675. BfIRValue objectVal = mBfIRBuilder->CreateCall(irFunc, llvmArgs);
  6676. auto objResult = mBfIRBuilder->CreateBitCast(objectVal, mBfIRBuilder->MapType(mContext->mBfObjectType, BfIRPopulateType_Full));
  6677. auto vdataPtr = mBfIRBuilder->CreateInBoundsGEP(objResult, 0, 0);
  6678. mBfIRBuilder->CreateStore(vData, vdataPtr);
  6679. result = mBfIRBuilder->CreateBitCast(objectVal, mBfIRBuilder->MapType(typeInstance));
  6680. }
  6681. }
  6682. if ((zeroMemory) && (arraySize))
  6683. {
  6684. BfArrayType* arrayType = CreateArrayType(type, arrayDim);
  6685. typeInstance = arrayType;
  6686. auto firstElementField = &arrayType->mFieldInstances.back();
  6687. int arrayClassSize = firstElementField->mDataOffset;
  6688. BfIRValue elementDataSize;
  6689. bool skipZero = false;
  6690. if (arraySize.IsConst())
  6691. {
  6692. BfIRValue arraySizeMinusOne = mBfIRBuilder->CreateSub(arraySize, GetConstValue(1));
  6693. elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySizeMinusOne);
  6694. elementDataSize = mBfIRBuilder->CreateAdd(elementDataSize, GetConstValue(type->mSize));
  6695. auto constVal = mBfIRBuilder->GetConstant(elementDataSize);
  6696. if (constVal->mInt64 <= 0)
  6697. skipZero = true;
  6698. }
  6699. else
  6700. {
  6701. // For non const, don't use an unpadded last element - saves us checking against negative numbers going into memset for the zero-length case
  6702. elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySize);
  6703. }
  6704. if (!skipZero)
  6705. {
  6706. auto i8Type = GetPrimitiveType(BfTypeCode_Int8);
  6707. auto ptrType = CreatePointerType(i8Type);
  6708. auto ptrVal = mBfIRBuilder->CreateBitCast(result, mBfIRBuilder->MapType(ptrType));
  6709. ptrVal = mBfIRBuilder->CreateInBoundsGEP(ptrVal, arrayClassSize);
  6710. mBfIRBuilder->CreateMemSet(ptrVal, GetConstValue8(0), elementDataSize, type->mAlign);
  6711. appendSizeValue = elementDataSize;
  6712. }
  6713. }
  6714. return result;
  6715. }
  6716. else
  6717. {
  6718. if (!sizeValue)
  6719. sizeValue = GetConstValue(allocSize);
  6720. return AllocBytes(allocTarget.mRefNode, allocTarget, type, sizeValue, GetConstValue(allocAlign), zeroMemory ? BfAllocFlags_ZeroMemory : BfAllocFlags_None);
  6721. }
  6722. }
  6723. void BfModule::ValidateAllocation(BfType* type, BfAstNode* refNode)
  6724. {
  6725. if ((type == NULL) || (refNode == NULL))
  6726. return;
  6727. auto typeInstance = type->ToTypeInstance();
  6728. if ((typeInstance != NULL) && (typeInstance->mTypeDef->mIsOpaque))
  6729. Fail(StrFormat("Unable to allocate opaque type '%s'", TypeToString(type).c_str()), refNode);
  6730. }
  6731. void BfModule::EmitAlign(BfIRValue& appendCurIdx, int align)
  6732. {
  6733. appendCurIdx = mBfIRBuilder->CreateAdd(appendCurIdx, GetConstValue(align - 1));
  6734. appendCurIdx = mBfIRBuilder->CreateAnd(appendCurIdx, GetConstValue(~(align - 1)));
  6735. }
  6736. void BfModule::EmitAppendAlign(int align, int sizeMultiple)
  6737. {
  6738. if (sizeMultiple == 0)
  6739. sizeMultiple = align;
  6740. if ((mCurMethodState->mCurAppendAlign != 0) && (mCurMethodState->mCurAppendAlign % align != 0))
  6741. {
  6742. if (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_Ctor)
  6743. {
  6744. auto localVar = mCurMethodState->GetRootMethodState()->mLocals[1];
  6745. BF_ASSERT(localVar->mName == "appendIdx");
  6746. auto appendIdxVal = BfTypedValue(localVar->mValue, localVar->mResolvedType, true);
  6747. BfIRValue appendCurIdx = mBfIRBuilder->CreateLoad(appendIdxVal.mValue);
  6748. if (align > 1)
  6749. {
  6750. appendCurIdx = mBfIRBuilder->CreateAdd(appendCurIdx, GetConstValue(align - 1));
  6751. appendCurIdx = mBfIRBuilder->CreateAnd(appendCurIdx, GetConstValue(~(align - 1)));
  6752. }
  6753. mBfIRBuilder->CreateStore(appendCurIdx, appendIdxVal.mValue);
  6754. }
  6755. else
  6756. {
  6757. BF_ASSERT(mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend);
  6758. BfIRValue appendCurIdxPtr = mCurMethodState->mRetVal.mValue;
  6759. BfIRValue appendCurIdx = mBfIRBuilder->CreateLoad(appendCurIdxPtr);
  6760. appendCurIdx = mBfIRBuilder->CreateAdd(appendCurIdx, GetConstValue(align - 1));
  6761. appendCurIdx = mBfIRBuilder->CreateAnd(appendCurIdx, GetConstValue(~(align - 1)));
  6762. mBfIRBuilder->CreateStore(appendCurIdx, appendCurIdxPtr);
  6763. }
  6764. }
  6765. if (mCurMethodState->mCurAppendAlign == 0)
  6766. mCurMethodState->mCurAppendAlign = sizeMultiple;
  6767. else
  6768. {
  6769. if (sizeMultiple % align == 0)
  6770. mCurMethodState->mCurAppendAlign = align;
  6771. else
  6772. mCurMethodState->mCurAppendAlign = sizeMultiple % align;
  6773. }
  6774. }
  6775. BfIRValue BfModule::AppendAllocFromType(BfType* type, BfIRValue appendSizeValue, int appendAllocAlign, BfIRValue arraySize, int arrayDim, bool isRawArrayAlloc, bool zeroMemory)
  6776. {
  6777. auto localVar = mCurMethodState->GetRootMethodState()->mLocals[1];
  6778. BF_ASSERT(localVar->mName == "appendIdx");
  6779. BfTypedValue appendIdxVal(localVar->mValue, localVar->mResolvedType, true);
  6780. BfIRValue retValue;
  6781. BfTypeInstance* retTypeInstance = NULL;
  6782. auto intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  6783. auto voidPtrType = GetPrimitiveType(BfTypeCode_NullPtr);
  6784. if (arraySize)
  6785. {
  6786. if (isRawArrayAlloc)
  6787. {
  6788. EmitAppendAlign(type->mAlign);
  6789. BfPointerType* ptrType = CreatePointerType(type);
  6790. BfIRValue sizeValue = mBfIRBuilder->CreateMul(GetConstValue(type->mSize), arraySize);
  6791. auto curIdxVal = mBfIRBuilder->CreateLoad(appendIdxVal.mValue);
  6792. if (mSystem->mPtrSize != 4)
  6793. sizeValue = mBfIRBuilder->CreateNumericCast(sizeValue, true, (intPtrType->mSize == 4) ? BfTypeCode_Int32 : BfTypeCode_Int64);
  6794. auto newIdxVal = mBfIRBuilder->CreateAdd(curIdxVal, sizeValue);
  6795. mBfIRBuilder->CreateStore(newIdxVal, appendIdxVal.mValue);
  6796. if (zeroMemory)
  6797. {
  6798. auto ptr = mBfIRBuilder->CreateIntToPtr(curIdxVal, mBfIRBuilder->MapType(voidPtrType));
  6799. mBfIRBuilder->CreateMemSet(ptr, GetConstValue8(0), sizeValue, type->mAlign);
  6800. }
  6801. return mBfIRBuilder->CreateIntToPtr(curIdxVal, mBfIRBuilder->MapType(ptrType));
  6802. }
  6803. else
  6804. {
  6805. BfArrayType* arrayType = CreateArrayType(type, arrayDim);
  6806. EmitAppendAlign(arrayType->mAlign, type->mSize);
  6807. auto firstElementField = &arrayType->mFieldInstances.back();
  6808. int arrayClassSize = arrayType->mInstSize - firstElementField->mDataSize;
  6809. BfIRValue sizeValue = GetConstValue(arrayClassSize);
  6810. BfIRValue elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->mSize), arraySize);
  6811. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, elementDataSize);
  6812. auto curIdxVal = mBfIRBuilder->CreateLoad(appendIdxVal.mValue);
  6813. if (mSystem->mPtrSize != 4)
  6814. sizeValue = mBfIRBuilder->CreateNumericCast(sizeValue, true, (intPtrType->mSize == 4) ? BfTypeCode_Int32 : BfTypeCode_Int64);
  6815. auto newIdxVal = mBfIRBuilder->CreateAdd(curIdxVal, sizeValue);
  6816. mBfIRBuilder->CreateStore(newIdxVal, appendIdxVal.mValue);
  6817. if (zeroMemory)
  6818. {
  6819. // Only zero out the actual elements
  6820. int dataOffset = arrayType->mFieldInstances.back().mDataOffset;
  6821. auto newOffset = mBfIRBuilder->CreateAdd(curIdxVal, GetConstValue(dataOffset));
  6822. auto newSize = mBfIRBuilder->CreateSub(sizeValue, GetConstValue(dataOffset));
  6823. auto ptr = mBfIRBuilder->CreateIntToPtr(newOffset, mBfIRBuilder->MapType(voidPtrType));
  6824. mBfIRBuilder->CreateMemSet(ptr, GetConstValue8(0), newSize, type->mAlign);
  6825. }
  6826. retTypeInstance = arrayType;
  6827. retValue = mBfIRBuilder->CreateIntToPtr(curIdxVal, mBfIRBuilder->MapType(arrayType));
  6828. }
  6829. }
  6830. else
  6831. {
  6832. auto typeInst = type->ToTypeInstance();
  6833. BfIRValue sizeValue;
  6834. BfIRType toType;
  6835. if (typeInst != NULL)
  6836. {
  6837. EmitAppendAlign(typeInst->mInstAlign, typeInst->mInstSize);
  6838. sizeValue = GetConstValue(typeInst->mInstSize);
  6839. toType = mBfIRBuilder->MapTypeInstPtr(typeInst);
  6840. }
  6841. else
  6842. {
  6843. EmitAppendAlign(type->mAlign, type->mSize);
  6844. sizeValue = GetConstValue(type->mSize);
  6845. auto toPtrType = CreatePointerType(type);
  6846. toType = mBfIRBuilder->MapType(toPtrType);
  6847. }
  6848. auto curIdxVal = mBfIRBuilder->CreateLoad(appendIdxVal.mValue);
  6849. auto newIdxVal = mBfIRBuilder->CreateAdd(curIdxVal, sizeValue);
  6850. mBfIRBuilder->CreateStore(newIdxVal, appendIdxVal.mValue);
  6851. retTypeInstance = typeInst;
  6852. retValue = mBfIRBuilder->CreateIntToPtr(curIdxVal, toType);
  6853. }
  6854. if ((retTypeInstance != NULL) && (retTypeInstance->IsObject()))
  6855. {
  6856. mBfIRBuilder->PopulateType(retTypeInstance);
  6857. auto int8Type = mBfIRBuilder->GetPrimitiveType(BfTypeCode_Int8);
  6858. auto ptrType = mBfIRBuilder->GetPointerTo(int8Type);
  6859. auto ptrPtrType = mBfIRBuilder->GetPointerTo(ptrType);
  6860. auto curThis = GetThis();
  6861. BfIRValue newFlags;
  6862. if (mCompiler->mOptions.mObjectHasDebugFlags)
  6863. {
  6864. auto thisFlagsPtr = mBfIRBuilder->CreateBitCast(curThis.mValue, ptrType);
  6865. auto thisFlags = mBfIRBuilder->CreateLoad(thisFlagsPtr);
  6866. auto maskedThisFlags = mBfIRBuilder->CreateAnd(thisFlags, GetConstValue8(BfObjectFlag_StackAlloc)); // Take 'stack' flag from 'this'
  6867. newFlags = mBfIRBuilder->CreateOr(maskedThisFlags, GetConstValue8(BfObjectFlag_AppendAlloc));
  6868. }
  6869. auto vObjectAddr = mBfIRBuilder->CreateInBoundsGEP(retValue, 0, 0);
  6870. auto vDataRef = CreateClassVDataGlobal(retTypeInstance);
  6871. auto destAddr = mBfIRBuilder->CreateBitCast(vObjectAddr, ptrPtrType);
  6872. auto srcVal = mBfIRBuilder->CreateBitCast(vDataRef, ptrType);
  6873. mBfIRBuilder->CreateStore(srcVal, destAddr);
  6874. if (mCompiler->mOptions.mObjectHasDebugFlags)
  6875. {
  6876. auto flagsPtr = mBfIRBuilder->CreateBitCast(destAddr, ptrType);
  6877. mBfIRBuilder->CreateStore(newFlags, flagsPtr);
  6878. }
  6879. }
  6880. if (appendSizeValue)
  6881. {
  6882. EmitAppendAlign(appendAllocAlign);
  6883. auto curIdxVal = mBfIRBuilder->CreateLoad(appendIdxVal.mValue);
  6884. auto newIdxVal = mBfIRBuilder->CreateAdd(curIdxVal, appendSizeValue);
  6885. mBfIRBuilder->CreateStore(newIdxVal, appendIdxVal.mValue);
  6886. }
  6887. return retValue;
  6888. }
  6889. bool BfModule::IsOptimized()
  6890. {
  6891. if (mProject == NULL)
  6892. return false;
  6893. int optLevel = GetModuleOptions().mOptLevel;
  6894. return (optLevel >= BfOptLevel_O1) && (optLevel <= BfOptLevel_O3);
  6895. }
  6896. bool BfModule::IsTargetingBeefBackend()
  6897. {
  6898. if (mProject == NULL)
  6899. return false;
  6900. return GetModuleOptions().mOptLevel == BfOptLevel_OgPlus;
  6901. }
  6902. bool BfModule::WantsLifetimes()
  6903. {
  6904. if (mProject == NULL)
  6905. return false;
  6906. return GetModuleOptions().mOptLevel == BfOptLevel_OgPlus;
  6907. }
  6908. bool BfModule::HasCompiledOutput()
  6909. {
  6910. return (!mSystem->mIsResolveOnly) && (mIsReified);
  6911. }
  6912. // We will skip the object access check for any occurances of this value
  6913. void BfModule::SkipObjectAccessCheck(BfTypedValue typedVal)
  6914. {
  6915. if ((mBfIRBuilder->mIgnoreWrites) || (!typedVal.mType->IsObjectOrInterface()) || (mCurMethodState == NULL) || (mCurMethodState->mIgnoreObjectAccessCheck))
  6916. return;
  6917. if (!mCompiler->mOptions.mObjectHasDebugFlags)
  6918. return;
  6919. if ((typedVal.mValue.mFlags & BfIRValueFlags_Value) == 0)
  6920. return;
  6921. mCurMethodState->mSkipObjectAccessChecks.Add(typedVal.mValue.mId);
  6922. }
  6923. void BfModule::EmitObjectAccessCheck(BfTypedValue typedVal)
  6924. {
  6925. if ((mBfIRBuilder->mIgnoreWrites) || (!typedVal.mType->IsObjectOrInterface()) || (mCurMethodState == NULL) || (mCurMethodState->mIgnoreObjectAccessCheck))
  6926. return;
  6927. if (!mCompiler->mOptions.mObjectHasDebugFlags)
  6928. return;
  6929. bool emitObjectAccessCheck = mCompiler->mOptions.mEmitObjectAccessCheck;
  6930. auto typeOptions = GetTypeOptions();
  6931. if (typeOptions != NULL)
  6932. emitObjectAccessCheck = BfTypeOptions::Apply(emitObjectAccessCheck, typeOptions->mEmitObjectAccessCheck);
  6933. if (!emitObjectAccessCheck)
  6934. return;
  6935. if ((typedVal.mValue.mFlags & BfIRValueFlags_Value) != 0)
  6936. {
  6937. if (mCurMethodState->mSkipObjectAccessChecks.Contains(typedVal.mValue.mId))
  6938. return;
  6939. }
  6940. if (typedVal.IsAddr())
  6941. typedVal = LoadValue(typedVal);
  6942. mBfIRBuilder->CreateObjectAccessCheck(typedVal.mValue, !IsOptimized());
  6943. }
  6944. void BfModule::EmitEnsureInstructionAt()
  6945. {
  6946. if (mProject == NULL)
  6947. return;
  6948. if ((mBfIRBuilder->mIgnoreWrites) || (!mHasFullDebugInfo) || (IsOptimized()) || (mCompiler->mOptions.mOmitDebugHelpers))
  6949. return;
  6950. mBfIRBuilder->CreateEnsureInstructionAt();
  6951. }
  6952. void BfModule::EmitDynamicCastCheck(const BfTypedValue& targetValue, BfType* targetType, BfIRBlock trueBlock, BfIRBlock falseBlock, bool nullSucceeds)
  6953. {
  6954. if (mBfIRBuilder->mIgnoreWrites)
  6955. return; // Nothing needed here
  6956. auto irb = mBfIRBuilder;
  6957. auto checkBB = irb->CreateBlock("as.check");
  6958. auto isNull = irb->CreateIsNull(targetValue.mValue);
  6959. mBfIRBuilder->CreateCondBr(isNull, nullSucceeds ? trueBlock : falseBlock, checkBB);
  6960. auto intType = GetPrimitiveType(BfTypeCode_IntPtr);
  6961. auto intPtrType = CreatePointerType(intType);
  6962. auto intPtrPtrType = CreatePointerType(intPtrType);
  6963. auto int32Type = GetPrimitiveType(BfTypeCode_Int32);
  6964. auto int32PtrType = CreatePointerType(int32Type);
  6965. auto typeTypeInstance = ResolveTypeDef(mCompiler->mReflectTypeInstanceTypeDef)->ToTypeInstance();
  6966. if (mCompiler->mOptions.mAllowHotSwapping)
  6967. {
  6968. BfExprEvaluator exprEvaluator(this);
  6969. AddBasicBlock(checkBB);
  6970. auto objectParam = mBfIRBuilder->CreateBitCast(targetValue.mValue, mBfIRBuilder->MapType(mContext->mBfObjectType));
  6971. auto moduleMethodInstance = GetMethodByName(mContext->mBfObjectType, targetType->IsInterface() ? "DynamicCastToInterface" : "DynamicCastToTypeId");
  6972. SizedArray<BfIRValue, 4> irArgs;
  6973. irArgs.push_back(objectParam);
  6974. irArgs.push_back(GetConstValue32(targetType->mTypeId));
  6975. auto callResult = exprEvaluator.CreateCall(moduleMethodInstance.mMethodInstance, moduleMethodInstance.mFunc, false, irArgs);
  6976. auto resultType = ResolveTypeDef(mSystem->mTypeBool);
  6977. auto cmpResult = mBfIRBuilder->CreateCmpNE(callResult.mValue, GetDefaultValue(callResult.mType));
  6978. irb->CreateCondBr(cmpResult, trueBlock, falseBlock);
  6979. }
  6980. else
  6981. {
  6982. AddBasicBlock(checkBB);
  6983. BfIRValue vDataPtr = irb->CreateBitCast(targetValue.mValue, irb->MapType(intPtrType));
  6984. vDataPtr = irb->CreateLoad(vDataPtr);
  6985. if (mCompiler->mOptions.mObjectHasDebugFlags)
  6986. vDataPtr = irb->CreateAnd(vDataPtr, irb->CreateConst(BfTypeCode_IntPtr, (uint64)~0xFFULL));
  6987. if (targetType->IsInterface())
  6988. {
  6989. auto targetTypeInst = targetType->ToTypeInstance();
  6990. AddDependency(targetType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ExprTypeReference);
  6991. // Skip past mType, but since a 'GetDynCastVDataCount()' data is included in the sSlotOfs, we need to remove that
  6992. //int inheritanceIdOfs = mSystem->mPtrSize - (mCompiler->GetDynCastVDataCount())*4;
  6993. //vDataPtr = irb->CreateAdd(vDataPtr, irb->CreateConst(BfTypeCode_IntPtr, inheritanceIdOfs));
  6994. vDataPtr = irb->CreateAdd(vDataPtr, irb->GetConfigConst(BfIRConfigConst_DynSlotOfs, BfTypeCode_IntPtr));
  6995. BfIRValue slotOfs = GetInterfaceSlotNum(targetType->ToTypeInstance());
  6996. BfIRValue slotByteOfs = irb->CreateMul(slotOfs, irb->CreateConst(BfTypeCode_Int32, 4));
  6997. slotByteOfs = irb->CreateNumericCast(slotByteOfs, false, BfTypeCode_IntPtr);
  6998. vDataPtr = irb->CreateAdd(vDataPtr, slotByteOfs);
  6999. vDataPtr = irb->CreateIntToPtr(vDataPtr, irb->MapType(int32PtrType));
  7000. BfIRValue typeId = irb->CreateLoad(vDataPtr);
  7001. BfIRValue cmpResult = irb->CreateCmpEQ(typeId, irb->CreateConst(BfTypeCode_Int32, targetType->mTypeId));
  7002. irb->CreateCondBr(cmpResult, trueBlock, falseBlock);
  7003. }
  7004. else
  7005. {
  7006. if (!targetType->IsTypeInstance())
  7007. targetType = GetWrappedStructType(targetType);
  7008. AddDependency(targetType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ExprTypeReference);
  7009. int inheritanceIdOfs = mSystem->mPtrSize;
  7010. vDataPtr = irb->CreateAdd(vDataPtr, irb->CreateConst(BfTypeCode_IntPtr, inheritanceIdOfs));
  7011. vDataPtr = irb->CreateIntToPtr(vDataPtr, irb->MapType(int32PtrType));
  7012. BfIRValue objInheritanceId = irb->CreateLoad(vDataPtr);
  7013. BfIRValue typeDataRef = CreateTypeDataRef(targetType);
  7014. BfIRValue typeInstDataRef = irb->CreateBitCast(typeDataRef, irb->MapType(typeTypeInstance, BfIRPopulateType_Full));
  7015. auto fieldInst = &typeTypeInstance->mFieldInstances[9];
  7016. BF_ASSERT(fieldInst->GetFieldDef()->mName == "mInheritanceId");
  7017. BfIRValue gepValue = irb->CreateInBoundsGEP(typeInstDataRef, 0, fieldInst->mDataIdx);
  7018. BfIRValue wantInheritanceId = irb->CreateLoad(gepValue);
  7019. fieldInst = &typeTypeInstance->mFieldInstances[10];
  7020. BF_ASSERT(fieldInst->GetFieldDef()->mName == "mInheritanceCount");
  7021. gepValue = irb->CreateInBoundsGEP(typeInstDataRef, 0, fieldInst->mDataIdx);
  7022. BfIRValue inheritanceCount = irb->CreateLoad(gepValue);
  7023. BfIRValue idDiff = irb->CreateSub(objInheritanceId, wantInheritanceId);
  7024. BfIRValue cmpResult = irb->CreateCmpLTE(idDiff, inheritanceCount, false);
  7025. irb->CreateCondBr(cmpResult, trueBlock, falseBlock);
  7026. }
  7027. }
  7028. }
  7029. void BfModule::EmitDynamicCastCheck(BfTypedValue typedVal, BfType* type, bool allowNull)
  7030. {
  7031. bool emitDynamicCastCheck = mCompiler->mOptions.mEmitDynamicCastCheck;
  7032. auto typeOptions = GetTypeOptions();
  7033. if (typeOptions != NULL)
  7034. emitDynamicCastCheck = BfTypeOptions::Apply(emitDynamicCastCheck, typeOptions->mEmitDynamicCastCheck);
  7035. if (emitDynamicCastCheck)
  7036. {
  7037. int wantTypeId = 0;
  7038. if (!type->IsGenericParam())
  7039. wantTypeId = type->mTypeId;
  7040. BfIRBlock failBlock = mBfIRBuilder->CreateBlock("dynFail");
  7041. BfIRBlock endBlock = mBfIRBuilder->CreateBlock("dynEnd");
  7042. EmitDynamicCastCheck(typedVal, type, endBlock, failBlock, allowNull ? true : false);
  7043. AddBasicBlock(failBlock);
  7044. SizedArray<BfIRValue, 8> llvmArgs;
  7045. auto bitAddr = mBfIRBuilder->CreateBitCast(typedVal.mValue, mBfIRBuilder->MapType(mContext->mBfObjectType));
  7046. llvmArgs.push_back(bitAddr);
  7047. llvmArgs.push_back(GetConstValue32(wantTypeId));
  7048. auto objDynCheck = GetInternalMethod("ObjectDynCheckFailed");
  7049. BF_ASSERT(objDynCheck);
  7050. if (objDynCheck)
  7051. {
  7052. auto callInst = mBfIRBuilder->CreateCall(objDynCheck.mFunc, llvmArgs);
  7053. }
  7054. mBfIRBuilder->CreateBr(endBlock);
  7055. AddBasicBlock(endBlock);
  7056. }
  7057. }
  7058. BfTypedValue BfModule::BoxValue(BfAstNode* srcNode, BfTypedValue typedVal, BfType* toType, const BfAllocTarget& allocTarget, bool callDtor)
  7059. {
  7060. BP_ZONE("BoxValue");
  7061. BfTypeInstance* fromStructTypeInstance = typedVal.mType->ToTypeInstance();
  7062. if (typedVal.mType->IsNullable())
  7063. {
  7064. typedVal = MakeAddressable(typedVal);
  7065. auto innerType = typedVal.mType->GetUnderlyingType();
  7066. if (!innerType->IsValueType())
  7067. {
  7068. Fail("Only value types can be boxed", srcNode);
  7069. return BfTypedValue();
  7070. }
  7071. auto prevBB = mBfIRBuilder->GetInsertBlock();
  7072. auto boxBB = mBfIRBuilder->CreateBlock("boxedN.notNull");
  7073. auto endBB = mBfIRBuilder->CreateBlock("boxedN.end");
  7074. mBfIRBuilder->PopulateType(typedVal.mType);
  7075. auto hasValueAddr = mBfIRBuilder->CreateInBoundsGEP(typedVal.mValue, 0, innerType->IsValuelessType() ? 1 : 2); // has_value
  7076. auto hasValue = mBfIRBuilder->CreateLoad(hasValueAddr);
  7077. mBfIRBuilder->CreateCondBr(hasValue, boxBB, endBB);
  7078. auto boxedType = CreateBoxedType(innerType);
  7079. AddDependency(boxedType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ReadFields);
  7080. auto resultType = toType;
  7081. if (resultType == NULL)
  7082. resultType = boxedType;
  7083. mBfIRBuilder->AddBlock(boxBB);
  7084. mBfIRBuilder->SetInsertPoint(boxBB);
  7085. BfScopeData newScope;
  7086. newScope.mOuterIsConditional = true;
  7087. mCurMethodState->AddScope(&newScope);
  7088. NewScopeState();
  7089. BfIRValue nullableValueAddr;
  7090. BfIRValue loadedVal;
  7091. if (innerType->IsValuelessType())
  7092. {
  7093. loadedVal = mBfIRBuilder->GetFakeVal();
  7094. }
  7095. else
  7096. {
  7097. nullableValueAddr = mBfIRBuilder->CreateInBoundsGEP(typedVal.mValue, 0, 1); // value
  7098. loadedVal = mBfIRBuilder->CreateLoad(nullableValueAddr);
  7099. }
  7100. auto boxedVal = BoxValue(srcNode, BfTypedValue(loadedVal, fromStructTypeInstance->GetUnderlyingType()), resultType, allocTarget, callDtor);
  7101. RestoreScopeState();
  7102. if (!boxedVal)
  7103. return BfTypedValue();
  7104. mBfIRBuilder->CreateBr(endBB);
  7105. auto boxBBEnd = mBfIRBuilder->GetInsertBlock();
  7106. mBfIRBuilder->AddBlock(endBB);
  7107. mBfIRBuilder->SetInsertPoint(endBB);
  7108. auto phi = mBfIRBuilder->CreatePhi(mBfIRBuilder->MapType(resultType), 2);
  7109. mBfIRBuilder->AddPhiIncoming(phi, boxedVal.mValue, boxBBEnd);
  7110. mBfIRBuilder->AddPhiIncoming(phi, GetDefaultValue(resultType), prevBB);
  7111. return BfTypedValue(phi, resultType);
  7112. }
  7113. bool alreadyCheckedCast = false;
  7114. BfTypeInstance* toTypeInstance = NULL;
  7115. if (toType != NULL)
  7116. toTypeInstance = toType->ToTypeInstance();
  7117. bool isStructPtr = typedVal.mType->IsStructPtr();
  7118. if (fromStructTypeInstance == NULL)
  7119. {
  7120. auto primType = (BfPrimitiveType*)typedVal.mType;
  7121. fromStructTypeInstance = GetWrappedStructType(typedVal.mType);
  7122. if (isStructPtr)
  7123. {
  7124. if ((toTypeInstance != NULL) && (TypeIsSubTypeOf(fromStructTypeInstance, toTypeInstance)))
  7125. alreadyCheckedCast = true;
  7126. fromStructTypeInstance = typedVal.mType->GetUnderlyingType()->ToTypeInstance();
  7127. }
  7128. }
  7129. if (fromStructTypeInstance == NULL)
  7130. return BfTypedValue();
  7131. // Need to box it
  7132. auto boxedType = CreateBoxedType(typedVal.mType);
  7133. bool isBoxedType = (fromStructTypeInstance != NULL) && (toType->IsBoxed()) && (boxedType == toType);
  7134. if ((toType == NULL) || (toType == mContext->mBfObjectType) || (isBoxedType) || (alreadyCheckedCast) || (TypeIsSubTypeOf(fromStructTypeInstance, toTypeInstance)))
  7135. {
  7136. if (typedVal.mType->IsPointer())
  7137. {
  7138. NOP;
  7139. }
  7140. mBfIRBuilder->PopulateType(boxedType);
  7141. AddDependency(boxedType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ReadFields);
  7142. auto allocaInst = AllocFromType(boxedType, allocTarget, BfIRValue(), BfIRValue(), 0, callDtor ? BfAllocFlags_None : BfAllocFlags_NoDtorCall);
  7143. BfTypedValue boxedTypedValue(allocaInst, boxedType);
  7144. mBfIRBuilder->SetName(allocaInst, "boxed." + fromStructTypeInstance->mTypeDef->mName->ToString());
  7145. if (boxedType->IsUnspecializedType())
  7146. {
  7147. BF_ASSERT(mCurMethodInstance->mIsUnspecialized);
  7148. }
  7149. else
  7150. {
  7151. PopulateType(fromStructTypeInstance);
  7152. if (!fromStructTypeInstance->IsValuelessType())
  7153. {
  7154. typedVal = LoadValue(typedVal);
  7155. auto valPtr = mBfIRBuilder->CreateInBoundsGEP(allocaInst, 0, 1);
  7156. if ((typedVal.mType != fromStructTypeInstance) && (!isStructPtr))
  7157. {
  7158. auto ptrType = CreatePointerType(typedVal.mType);
  7159. valPtr = mBfIRBuilder->CreateBitCast(valPtr, mBfIRBuilder->MapType(ptrType));
  7160. }
  7161. if (typedVal.IsSplat())
  7162. {
  7163. AggregateSplatIntoAddr(typedVal, valPtr);
  7164. }
  7165. else
  7166. mBfIRBuilder->CreateStore(typedVal.mValue, valPtr);
  7167. }
  7168. }
  7169. if (toType == NULL)
  7170. {
  7171. return BfTypedValue(allocaInst, boxedType);
  7172. }
  7173. else
  7174. {
  7175. auto castedValue = mBfIRBuilder->CreateBitCast(allocaInst, mBfIRBuilder->MapType(toType));
  7176. return BfTypedValue(castedValue, toType);
  7177. }
  7178. }
  7179. return BfTypedValue();
  7180. }
  7181. bool BfModule::GetBasePropertyDef(BfPropertyDef*& propDef, BfTypeInstance*& typeInst)
  7182. {
  7183. BfTypeInstance* checkTypeInst = typeInst;
  7184. while (checkTypeInst != NULL)
  7185. {
  7186. for (auto checkProp : checkTypeInst->mTypeDef->mProperties)
  7187. {
  7188. if (checkProp->mName == propDef->mName)
  7189. {
  7190. auto checkPropDeclaration = BfNodeDynCast<BfPropertyDeclaration>(checkProp->mFieldDeclaration);
  7191. if ((checkPropDeclaration == NULL) || (checkPropDeclaration->mVirtualSpecifier == NULL) || (checkPropDeclaration->mVirtualSpecifier->GetToken() == BfToken_Virtual))
  7192. {
  7193. propDef = checkProp;
  7194. typeInst = checkTypeInst;
  7195. return true;
  7196. }
  7197. }
  7198. }
  7199. checkTypeInst = checkTypeInst->mBaseType;
  7200. }
  7201. return false;
  7202. }
  7203. BfMethodInstance* BfModule::GetRawMethodInstanceAtIdx(BfTypeInstance* typeInstance, int methodIdx, const char* assertName)
  7204. {
  7205. if (!typeInstance->mResolvingVarField)
  7206. {
  7207. if (typeInstance->IsIncomplete())
  7208. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  7209. }
  7210. else
  7211. {
  7212. if (methodIdx >= (int)typeInstance->mMethodInstanceGroups.size())
  7213. {
  7214. AssertErrorState();
  7215. return NULL;
  7216. }
  7217. }
  7218. if (assertName != NULL)
  7219. {
  7220. BF_ASSERT(typeInstance->mTypeDef->mMethods[methodIdx]->mName == assertName);
  7221. }
  7222. auto& methodGroup = typeInstance->mMethodInstanceGroups[methodIdx];
  7223. if (methodGroup.mDefault == NULL)
  7224. {
  7225. if (!mCompiler->mIsResolveOnly)
  7226. {
  7227. BF_ASSERT((methodGroup.mOnDemandKind == BfMethodOnDemandKind_NoDecl_AwaitingReference) || (methodGroup.mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingDecl));
  7228. methodGroup.mOnDemandKind = BfMethodOnDemandKind_Decl_AwaitingDecl;
  7229. // Get it from the owning module so we don't create a reference prematurely...
  7230. auto declModule = typeInstance->mModule;
  7231. return declModule->GetMethodInstance(typeInstance, typeInstance->mTypeDef->mMethods[methodIdx], BfTypeVector(), (BfGetMethodInstanceFlags)(BfGetMethodInstanceFlag_UnspecializedPass | BfGetMethodInstanceFlag_Unreified)).mMethodInstance;
  7232. }
  7233. else
  7234. {
  7235. auto declModule = typeInstance->mModule;
  7236. return declModule->GetMethodInstance(typeInstance, typeInstance->mTypeDef->mMethods[methodIdx], BfTypeVector(), (BfGetMethodInstanceFlags)(BfGetMethodInstanceFlag_UnspecializedPass)).mMethodInstance;
  7237. }
  7238. }
  7239. auto methodInstance = typeInstance->mMethodInstanceGroups[methodIdx].mDefault;
  7240. //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
  7241. // be from a call to the NON-raw version
  7242. // if (!methodInstance->mMethodInstanceGroup->IsImplemented())
  7243. // {
  7244. // methodInstance->mIsReified = mIsReified;
  7245. // if (methodInstance->mMethodProcessRequest == NULL)
  7246. // typeInstance->mModule->AddMethodToWorkList(methodInstance);
  7247. // }
  7248. return methodInstance;
  7249. }
  7250. BfMethodInstance* BfModule::GetRawMethodInstance(BfTypeInstance* typeInstance, BfMethodDef* methodDef)
  7251. {
  7252. if (methodDef->mIsLocalMethod)
  7253. {
  7254. return GetMethodInstance(typeInstance, methodDef, BfTypeVector()).mMethodInstance;
  7255. }
  7256. return GetRawMethodInstanceAtIdx(typeInstance, methodDef->mIdx);
  7257. }
  7258. BfMethodInstance* BfModule::GetRawMethodByName(BfTypeInstance* typeInstance, const StringImpl& methodName, int paramCount, bool checkBase, bool allowMixin)
  7259. {
  7260. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  7261. while (typeInstance != NULL)
  7262. {
  7263. typeInstance->mTypeDef->PopulateMemberSets();
  7264. BfMemberSetEntry* entry = NULL;
  7265. BfMethodDef* methodDef = NULL;
  7266. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(methodName, &entry))
  7267. methodDef = (BfMethodDef*)entry->mMemberDef;
  7268. while (methodDef != NULL)
  7269. {
  7270. if (((allowMixin) || (methodDef->mMethodType != BfMethodType_Mixin)) &&
  7271. (methodDef->mGenericParams.size() == 0) &&
  7272. ((paramCount == -1) || (paramCount == (int)methodDef->mParams.size())))
  7273. return GetRawMethodInstance(typeInstance, methodDef);
  7274. methodDef = methodDef->mNextWithSameName;
  7275. }
  7276. if (!checkBase)
  7277. break;
  7278. typeInstance = typeInstance->mBaseType;
  7279. }
  7280. return NULL;
  7281. }
  7282. BfMethodInstance* BfModule::GetUnspecializedMethodInstance(BfMethodInstance* methodInstance)
  7283. {
  7284. if ((methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mMethodGenericArguments.size() != 0))
  7285. methodInstance = methodInstance->mMethodInstanceGroup->mDefault;
  7286. auto owner = methodInstance->mMethodInstanceGroup->mOwner;
  7287. if (!owner->IsGenericTypeInstance())
  7288. return methodInstance;
  7289. auto genericType = (BfGenericTypeInstance*)owner;
  7290. if (genericType->IsUnspecializedType())
  7291. return methodInstance;
  7292. auto unspecializedType = ResolveTypeDef(genericType->mTypeDef);
  7293. if (unspecializedType == NULL)
  7294. {
  7295. AssertErrorState();
  7296. return methodInstance;
  7297. }
  7298. if (unspecializedType == NULL)
  7299. return methodInstance;
  7300. auto unspecializedTypeInst = unspecializedType->ToTypeInstance();
  7301. return GetRawMethodInstanceAtIdx(unspecializedTypeInst, methodInstance->mMethodDef->mIdx);
  7302. }
  7303. int BfModule::GetGenericParamAndReturnCount(BfMethodInstance* methodInstance)
  7304. {
  7305. int genericCount = 0;
  7306. auto unspecializedMethodInstance = GetUnspecializedMethodInstance(methodInstance);
  7307. for (int paramIdx = 0; paramIdx < unspecializedMethodInstance->GetParamCount(); paramIdx++)
  7308. {
  7309. auto param = unspecializedMethodInstance->GetParamType(paramIdx);
  7310. if (param->IsGenericParam())
  7311. genericCount++;
  7312. }
  7313. if (unspecializedMethodInstance->mReturnType->IsGenericParam())
  7314. genericCount++;
  7315. return genericCount;
  7316. }
  7317. BfModule* BfModule::GetSpecializedMethodModule(const Array<BfProject*>& projectList)
  7318. {
  7319. BF_ASSERT(!mIsScratchModule);
  7320. BF_ASSERT(mIsReified);
  7321. BfModule* mainModule = this;
  7322. if (mParentModule != NULL)
  7323. mainModule = mParentModule;
  7324. BfModule* specModule = NULL;
  7325. BfModule** specModulePtr = NULL;
  7326. if (mainModule->mSpecializedMethodModules.TryGetValue(projectList, &specModulePtr))
  7327. {
  7328. return *specModulePtr;
  7329. }
  7330. else
  7331. {
  7332. String specModuleName = mModuleName;
  7333. for (auto bfProject : projectList)
  7334. specModuleName += StrFormat("@%s", bfProject->mName.c_str());
  7335. specModule = new BfModule(mContext, specModuleName);
  7336. specModule->mProject = mainModule->mProject;
  7337. specModule->mParentModule = mainModule;
  7338. specModule->mIsSpecializedMethodModuleRoot = true;
  7339. specModule->Init();
  7340. mainModule->mSpecializedMethodModules[projectList] = specModule;
  7341. }
  7342. return specModule;
  7343. }
  7344. BfIRValue BfModule::CreateFunctionFrom(BfMethodInstance* methodInstance, bool tryExisting, bool isInlined)
  7345. {
  7346. if (mCompiler->IsSkippingExtraResolveChecks())
  7347. return BfIRValue();
  7348. if (methodInstance->mMethodInstanceGroup->mOwner->IsInterface())
  7349. {
  7350. //BF_ASSERT(!methodInstance->mIRFunction);
  7351. return BfIRValue();
  7352. }
  7353. auto methodDef = methodInstance->mMethodDef;
  7354. StringT<128> methodName;
  7355. BfMangler::Mangle(methodName, mCompiler->GetMangleKind(), methodInstance);
  7356. if (isInlined != methodInstance->mAlwaysInline)
  7357. {
  7358. if (isInlined)
  7359. methodName += "__INLINE";
  7360. else
  7361. methodName += "__NOINLINE";
  7362. }
  7363. if (tryExisting)
  7364. {
  7365. auto func = mBfIRBuilder->GetFunction(methodName);
  7366. if (func)
  7367. return func;
  7368. }
  7369. if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  7370. {
  7371. if (methodDeclaration->mExternSpecifier != NULL)
  7372. {
  7373. auto intrinsic = GetIntrinsic(methodInstance);
  7374. if (intrinsic)
  7375. return intrinsic;
  7376. // If we have multiple entries with the same name, they could have different arguments and will generate other errors...
  7377. /*auto func = mBfIRBuilder->GetFunction(methodName);
  7378. if (func)
  7379. return func;*/
  7380. }
  7381. }
  7382. if (methodInstance->GetImportCallKind() != BfImportCallKind_None)
  7383. {
  7384. return CreateDllImportGlobalVar(methodInstance, false);
  7385. }
  7386. BfIRType returnType;
  7387. SizedArray<BfIRType, 8> paramTypes;
  7388. methodInstance->GetIRFunctionInfo(this, returnType, paramTypes);
  7389. auto funcType = mBfIRBuilder->CreateFunctionType(returnType, paramTypes);
  7390. auto func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, methodName);
  7391. auto callingConv = GetCallingConvention(methodInstance->GetOwner(), methodDef);
  7392. if (callingConv != BfIRCallingConv_CDecl)
  7393. mBfIRBuilder->SetFuncCallingConv(func, callingConv);
  7394. SetupIRMethod(methodInstance, func, isInlined);
  7395. // auto srcModule = methodInstance->GetOwner()->GetModule();
  7396. // if ((srcModule != NULL) && (srcModule->mProject != mProject))
  7397. // {
  7398. // if (srcModule->mProject->mTargetType == BfTargetType_BeefDynLib)
  7399. // {
  7400. // mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_DllImport);
  7401. // }
  7402. // }
  7403. return func;
  7404. }
  7405. BfModuleMethodInstance BfModule::GetMethodInstanceAtIdx(BfTypeInstance* typeInstance, int methodIdx, const char* assertName)
  7406. {
  7407. if (assertName != NULL)
  7408. {
  7409. BF_ASSERT(typeInstance->mTypeDef->mMethods[methodIdx]->mName == assertName);
  7410. }
  7411. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  7412. auto methodInstance = typeInstance->mMethodInstanceGroups[methodIdx].mDefault;
  7413. if ((methodInstance != NULL) && (mIsReified) && (!methodInstance->mIsReified))
  7414. {
  7415. // Can't use it, not reified
  7416. methodInstance = NULL;
  7417. }
  7418. if ((methodInstance != NULL) && (mBfIRBuilder != NULL) && (mBfIRBuilder->mIgnoreWrites) &&
  7419. (methodInstance->mMethodInstanceGroup->IsImplemented()))
  7420. {
  7421. BfIRFunction func(mBfIRBuilder->GetFakeVal());
  7422. return BfModuleMethodInstance(methodInstance, func);
  7423. }
  7424. return GetMethodInstance(typeInstance, typeInstance->mTypeDef->mMethods[methodIdx], BfTypeVector());
  7425. }
  7426. BfModuleMethodInstance BfModule::GetMethodByName(BfTypeInstance* typeInstance, const StringImpl& methodName, int paramCount, bool checkBase)
  7427. {
  7428. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  7429. while (typeInstance != NULL)
  7430. {
  7431. typeInstance->mTypeDef->PopulateMemberSets();
  7432. BfMemberSetEntry* entry = NULL;
  7433. BfMethodDef* methodDef = NULL;
  7434. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(methodName, &entry))
  7435. methodDef = (BfMethodDef*)entry->mMemberDef;
  7436. while (methodDef != NULL)
  7437. {
  7438. if ((methodDef->mMethodType != BfMethodType_Mixin) &&
  7439. (methodDef->mGenericParams.size() == 0) &&
  7440. ((paramCount == -1) || (paramCount == (int)methodDef->mParams.size())))
  7441. return GetMethodInstanceAtIdx(typeInstance, methodDef->mIdx);
  7442. methodDef = methodDef->mNextWithSameName;
  7443. }
  7444. if (!checkBase)
  7445. break;
  7446. typeInstance = typeInstance->mBaseType;
  7447. }
  7448. return BfModuleMethodInstance();
  7449. }
  7450. BfModuleMethodInstance BfModule::GetMethodByName(BfTypeInstance* typeInstance, const StringImpl& methodName, const Array<BfType*>& paramTypes, bool checkBase)
  7451. {
  7452. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  7453. while (typeInstance != NULL)
  7454. {
  7455. typeInstance->mTypeDef->PopulateMemberSets();
  7456. BfMemberSetEntry* entry = NULL;
  7457. BfMethodDef* methodDef = NULL;
  7458. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(methodName, &entry))
  7459. methodDef = (BfMethodDef*)entry->mMemberDef;
  7460. while (methodDef != NULL)
  7461. {
  7462. if ((methodDef->mMethodType != BfMethodType_Mixin) &&
  7463. (methodDef->mGenericParams.size() == 0) &&
  7464. (paramTypes.size() == methodDef->mParams.size()))
  7465. {
  7466. auto moduleMethodInstance = GetMethodInstanceAtIdx(typeInstance, methodDef->mIdx);
  7467. if (moduleMethodInstance.mMethodInstance != NULL)
  7468. {
  7469. bool matches = true;
  7470. for (int paramIdx = 0; paramIdx < (int)paramTypes.size(); paramIdx++)
  7471. {
  7472. if (moduleMethodInstance.mMethodInstance->GetParamType(paramIdx) != paramTypes[paramIdx])
  7473. matches = false;
  7474. }
  7475. if (matches)
  7476. return moduleMethodInstance;
  7477. }
  7478. }
  7479. methodDef = methodDef->mNextWithSameName;
  7480. }
  7481. if (!checkBase)
  7482. break;
  7483. typeInstance = typeInstance->mBaseType;
  7484. }
  7485. return BfModuleMethodInstance();
  7486. }
  7487. BfModuleMethodInstance BfModule::GetInternalMethod(const StringImpl& methodName, int paramCount)
  7488. {
  7489. auto internalType = ResolveTypeDef(mCompiler->mInternalTypeDef);
  7490. PopulateType(internalType);
  7491. auto moduleMethodInstance = GetMethodByName(internalType->ToTypeInstance(), methodName, paramCount);
  7492. if (!moduleMethodInstance)
  7493. {
  7494. Fail(StrFormat("Failed to find System.Internal method '%s'", methodName.c_str()));
  7495. }
  7496. return moduleMethodInstance;
  7497. }
  7498. bool BfModule::IsMethodImplementedAndReified(BfTypeInstance* typeInstance, const StringImpl& methodName, int paramCount, bool checkBase)
  7499. {
  7500. while (typeInstance != NULL)
  7501. {
  7502. typeInstance->mTypeDef->PopulateMemberSets();
  7503. BfMemberSetEntry* entry = NULL;
  7504. BfMethodDef* methodDef = NULL;
  7505. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(methodName, &entry))
  7506. methodDef = (BfMethodDef*)entry->mMemberDef;
  7507. while (methodDef != NULL)
  7508. {
  7509. if ((methodDef->mMethodType != BfMethodType_Mixin) &&
  7510. (methodDef->mGenericParams.size() == 0) &&
  7511. ((paramCount == -1) || (paramCount == (int)methodDef->mParams.size())))
  7512. {
  7513. auto& methodInstanceGroup = typeInstance->mMethodInstanceGroups[methodDef->mIdx];
  7514. if (!methodInstanceGroup.IsImplemented())
  7515. return false;
  7516. if (methodInstanceGroup.mDefault == NULL)
  7517. return false;
  7518. return methodInstanceGroup.mDefault->mIsReified;
  7519. }
  7520. methodDef = methodDef->mNextWithSameName;
  7521. }
  7522. if (!checkBase)
  7523. break;
  7524. typeInstance = typeInstance->mBaseType;
  7525. }
  7526. return false;
  7527. }
  7528. bool BfModule::HasMixin(BfTypeInstance* typeInstance, const StringImpl& methodName, int paramCount, bool checkBase)
  7529. {
  7530. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  7531. while (typeInstance != NULL)
  7532. {
  7533. typeInstance->mTypeDef->PopulateMemberSets();
  7534. BfMemberSetEntry* entry = NULL;
  7535. BfMethodDef* methodDef = NULL;
  7536. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(methodName, &entry))
  7537. methodDef = (BfMethodDef*)entry->mMemberDef;
  7538. while (methodDef != NULL)
  7539. {
  7540. if ((methodDef->mMethodType == BfMethodType_Mixin) &&
  7541. ((paramCount == -1) || (paramCount == (int)methodDef->mParams.size())))
  7542. return true;
  7543. methodDef = methodDef->mNextWithSameName;
  7544. }
  7545. if (!checkBase)
  7546. break;
  7547. typeInstance = typeInstance->mBaseType;
  7548. }
  7549. return BfModuleMethodInstance();
  7550. }
  7551. BfFieldInstance* BfModule::GetFieldByName(BfTypeInstance* typeInstance, const StringImpl& fieldName)
  7552. {
  7553. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  7554. typeInstance->mTypeDef->PopulateMemberSets();
  7555. BfMemberSetEntry* entry = NULL;
  7556. BfFieldDef* fieldDef = NULL;
  7557. if (typeInstance->mTypeDef->mFieldSet.TryGetWith(fieldName, &entry))
  7558. {
  7559. fieldDef = (BfFieldDef*)entry->mMemberDef;
  7560. return &typeInstance->mFieldInstances[fieldDef->mIdx];
  7561. }
  7562. // for (auto& fieldInst : typeInstance->mFieldInstances)
  7563. // {
  7564. // auto fieldDef = fieldInst.GetFieldDef();
  7565. // if ((fieldDef != NULL) && (fieldDef->mName == fieldName))
  7566. // return &fieldInst;
  7567. // }
  7568. return NULL;
  7569. }
  7570. String BfModule::MethodToString(BfMethodInstance* methodInst, BfMethodNameFlags methodNameFlags, BfTypeVector* methodGenericArgs)
  7571. {
  7572. auto methodDef = methodInst->mMethodDef;
  7573. bool allowResolveGenericParamNames = ((methodNameFlags & BfMethodNameFlag_ResolveGenericParamNames) != 0);
  7574. BfTypeNameFlags typeNameFlags = BfTypeNameFlags_None;
  7575. if ((mCurTypeInstance == NULL) || (!mCurTypeInstance->IsUnspecializedTypeVariation()))
  7576. typeNameFlags = BfTypeNameFlag_ResolveGenericParamNames;
  7577. BfType* type = methodInst->mMethodInstanceGroup->mOwner;
  7578. if ((methodGenericArgs != NULL) && (type->IsUnspecializedType()))
  7579. type = ResolveGenericType(type, *methodGenericArgs);
  7580. String methodName;
  7581. if ((methodNameFlags & BfMethodNameFlag_OmitTypeName) == 0)
  7582. {
  7583. methodName = TypeToString(type, typeNameFlags);
  7584. if (methodName == "$")
  7585. methodName = "";
  7586. else
  7587. methodName += ".";
  7588. }
  7589. String accessorString;
  7590. StringT<64> methodDefName = methodInst->mMethodDef->mName;
  7591. if (methodInst->mMethodDef->mIsLocalMethod)
  7592. {
  7593. int atPos = (int)methodDefName.IndexOf('$');
  7594. methodDefName.RemoveToEnd(atPos);
  7595. methodDefName.Replace("@", ".");
  7596. }
  7597. else
  7598. {
  7599. int atPos = (int)methodDefName.IndexOf('$');
  7600. if (atPos != -1)
  7601. {
  7602. accessorString = methodDefName.Substring(0, atPos);
  7603. if ((accessorString == "get") || (accessorString == "set"))
  7604. {
  7605. methodDefName = methodDefName.Substring(atPos + 1);
  7606. }
  7607. else
  7608. accessorString = "";
  7609. }
  7610. }
  7611. if ((methodInst->mMethodInfoEx != NULL) && (methodInst->mMethodInfoEx->mForeignType != NULL))
  7612. {
  7613. BfTypeNameFlags typeNameFlags = BfTypeNameFlags_None;
  7614. if (!methodInst->mIsUnspecializedVariation && allowResolveGenericParamNames)
  7615. typeNameFlags = BfTypeNameFlag_ResolveGenericParamNames;
  7616. methodName += TypeToString(methodInst->mMethodInfoEx->mForeignType, typeNameFlags);
  7617. methodName += ".";
  7618. }
  7619. if ((methodInst->mMethodInfoEx != NULL) && (methodInst->mMethodInfoEx->mExplicitInterface != NULL))
  7620. {
  7621. BfTypeNameFlags typeNameFlags = BfTypeNameFlags_None;
  7622. if (!methodInst->mIsUnspecializedVariation && allowResolveGenericParamNames)
  7623. typeNameFlags = BfTypeNameFlag_ResolveGenericParamNames;
  7624. methodName += TypeToString(methodInst->mMethodInfoEx->mExplicitInterface, typeNameFlags);
  7625. methodName += ".";
  7626. }
  7627. if (methodDef->mMethodType == BfMethodType_Operator)
  7628. {
  7629. BfOperatorDef* operatorDef = (BfOperatorDef*)methodDef;
  7630. if (operatorDef->mOperatorDeclaration->mIsConvOperator)
  7631. {
  7632. // Don't add explicit/implicit part, since that's not available in GCC mangling
  7633. /*if (operatorDef->mOperatorDeclaration->mExplicitToken != NULL)
  7634. {
  7635. if (operatorDef->mOperatorDeclaration->mExplicitToken->GetToken() == BfToken_Explicit)
  7636. methodName += "explicit ";
  7637. else if (operatorDef->mOperatorDeclaration->mExplicitToken->GetToken() == BfToken_Explicit)
  7638. methodName += "explicit ";
  7639. }*/
  7640. methodName += "operator ";
  7641. if (methodInst->mReturnType != NULL)
  7642. methodName += TypeToString(methodInst->mReturnType);
  7643. }
  7644. else
  7645. {
  7646. methodName += "operator";
  7647. if (operatorDef->mOperatorDeclaration->mOpTypeToken != NULL)
  7648. methodName += BfTokenToString(operatorDef->mOperatorDeclaration->mOpTypeToken->GetToken());
  7649. }
  7650. }
  7651. else if (methodDef->mMethodType == BfMethodType_Ctor)
  7652. {
  7653. if (methodDef->mIsStatic)
  7654. methodName += "__BfStaticCtor";
  7655. else
  7656. methodName += "this";
  7657. accessorString = "";
  7658. }
  7659. else if (methodDef->mMethodType == BfMethodType_PropertyGetter)
  7660. {
  7661. methodDef->GetRefNode()->ToString(methodName);
  7662. methodName += " get accessor";
  7663. return methodName;
  7664. }
  7665. else if (methodDef->mMethodType == BfMethodType_PropertySetter)
  7666. {
  7667. methodDef->GetRefNode()->ToString(methodName);
  7668. methodName += " set accessor";
  7669. return methodName;
  7670. }
  7671. else
  7672. methodName += methodDefName;
  7673. BfTypeVector newMethodGenericArgs;
  7674. if ((methodInst->mMethodInfoEx != NULL) && (methodInst->mMethodInfoEx->mMethodGenericArguments.size() != 0))
  7675. {
  7676. methodName += "<";
  7677. for (int i = 0; i < (int) methodInst->mMethodInfoEx->mMethodGenericArguments.size(); i++)
  7678. {
  7679. if (i > 0)
  7680. methodName += ", ";
  7681. BfTypeNameFlags typeNameFlags = BfTypeNameFlags_None;
  7682. //Why did we have this methodInst->mIsUnspecializedVariation check? Sometimes we do need to show errors calling methods that refer back to our types
  7683. //if (!methodInst->mIsUnspecializedVariation && allowResolveGenericParamNames)
  7684. if (allowResolveGenericParamNames)
  7685. typeNameFlags = BfTypeNameFlag_ResolveGenericParamNames;
  7686. BfType* type = methodInst->mMethodInfoEx->mMethodGenericArguments[i];
  7687. if ((methodGenericArgs != NULL) && (type->IsUnspecializedType()))
  7688. {
  7689. bool hasEmpty = false;
  7690. for (auto arg : *methodGenericArgs)
  7691. {
  7692. if (arg == NULL)
  7693. hasEmpty = true;
  7694. }
  7695. if (hasEmpty)
  7696. {
  7697. for (int genericIdx = 0; genericIdx < (int)methodGenericArgs->size(); genericIdx++)
  7698. {
  7699. auto arg = (*methodGenericArgs)[genericIdx];
  7700. if (arg != NULL)
  7701. newMethodGenericArgs.push_back(arg);
  7702. else
  7703. {
  7704. auto genericParamInst = methodInst->mMethodInfoEx->mGenericParams[genericIdx];
  7705. if (genericParamInst->mTypeConstraint != NULL)
  7706. newMethodGenericArgs.push_back(genericParamInst->mTypeConstraint);
  7707. else
  7708. newMethodGenericArgs.push_back(mContext->mBfObjectType); // Default
  7709. }
  7710. }
  7711. methodGenericArgs = &newMethodGenericArgs;
  7712. }
  7713. if (type->IsUnspecializedType())
  7714. type = ResolveGenericType(type, *methodGenericArgs);
  7715. }
  7716. methodName += TypeToString(type, typeNameFlags);
  7717. }
  7718. methodName += ">";
  7719. }
  7720. if (accessorString.length() == 0)
  7721. {
  7722. int dispParamIdx = 0;
  7723. methodName += "(";
  7724. for (int paramIdx = 0; paramIdx < (int) methodInst->GetParamCount(); paramIdx++)
  7725. {
  7726. int paramKind = methodInst->GetParamKind(paramIdx);
  7727. if (paramKind == BfParamKind_ImplicitCapture)
  7728. continue;
  7729. if (dispParamIdx > 0)
  7730. methodName += ", ";
  7731. if (paramKind == BfParamKind_Params)
  7732. methodName += "params ";
  7733. typeNameFlags = BfTypeNameFlag_ResolveGenericParamNames;
  7734. BfType* type = methodInst->GetParamType(paramIdx);
  7735. if ((methodGenericArgs != NULL) && (type->IsUnspecializedType()))
  7736. type = ResolveGenericType(type, *methodGenericArgs);
  7737. methodName += TypeToString(type, typeNameFlags);
  7738. methodName += " ";
  7739. methodName += methodInst->GetParamName(paramIdx);
  7740. dispParamIdx++;
  7741. }
  7742. methodName += ")";
  7743. }
  7744. if (accessorString.length() != 0)
  7745. {
  7746. methodName += " " + accessorString;
  7747. }
  7748. return methodName;
  7749. }
  7750. static void AddAttributeTargetName(BfAttributeTargets& flagsLeft, BfAttributeTargets checkFlag, String& str, String addString)
  7751. {
  7752. if ((flagsLeft & checkFlag) == 0)
  7753. return;
  7754. if (!str.empty())
  7755. {
  7756. if (flagsLeft == checkFlag)
  7757. {
  7758. if ((int)str.IndexOf(',') != -1)
  7759. str += ", and ";
  7760. else
  7761. str += " and ";
  7762. }
  7763. else
  7764. str += ", ";
  7765. }
  7766. str += addString;
  7767. flagsLeft = (BfAttributeTargets)(flagsLeft & ~checkFlag);
  7768. }
  7769. static String GetAttributesTargetListString(BfAttributeTargets attrTarget)
  7770. {
  7771. String resultStr;
  7772. auto flagsLeft = attrTarget;
  7773. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Assembly, resultStr, "assembly declarations");
  7774. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Module, resultStr, "module declarations");
  7775. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Class, resultStr, "class declarations");
  7776. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Struct, resultStr, "struct declarations");
  7777. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Enum, resultStr, "enum declarations");
  7778. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Constructor, resultStr, "constructor declarations");
  7779. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Method, resultStr, "method declarations");
  7780. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Property, resultStr, "property declarations");
  7781. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Field, resultStr, "field declarations");
  7782. AddAttributeTargetName(flagsLeft, BfAttributeTargets_StaticField, resultStr, "static field declarations");
  7783. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Interface, resultStr, "interface declarations");
  7784. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Parameter, resultStr, "parameter declarations");
  7785. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Delegate, resultStr, "delegate declarations");
  7786. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Function, resultStr, "function declarations");
  7787. AddAttributeTargetName(flagsLeft, BfAttributeTargets_ReturnValue, resultStr, "return value");
  7788. AddAttributeTargetName(flagsLeft, BfAttributeTargets_GenericParameter, resultStr, "generic parameters");
  7789. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Invocation, resultStr, "invocations");
  7790. AddAttributeTargetName(flagsLeft, BfAttributeTargets_MemberAccess, resultStr, "member access");
  7791. if (resultStr.IsEmpty())
  7792. return "<nothing>";
  7793. return resultStr;
  7794. }
  7795. void BfModule::CurrentAddToConstHolder(BfIRValue& irVal)
  7796. {
  7797. auto constant = mBfIRBuilder->GetConstant(irVal);
  7798. int stringPoolIdx = GetStringPoolIdx(irVal, mBfIRBuilder);
  7799. if (stringPoolIdx != -1)
  7800. {
  7801. irVal = mCurTypeInstance->GetOrCreateConstHolder()->CreateConst(BfTypeCode_Int32, stringPoolIdx);
  7802. return;
  7803. }
  7804. if (constant->mConstType == BfConstType_Array)
  7805. {
  7806. auto constArray = (BfConstantArray*)constant;
  7807. SizedArray<BfIRValue, 8> newVals;
  7808. for (auto val : constArray->mValues)
  7809. {
  7810. auto newVal = val;
  7811. CurrentAddToConstHolder(newVal);
  7812. newVals.push_back(newVal);
  7813. }
  7814. irVal = mCurTypeInstance->mConstHolder->CreateConstArray(constArray->mType, newVals);
  7815. return;
  7816. }
  7817. auto origConst = irVal;
  7818. if ((constant->mConstType == BfConstType_BitCast) || (constant->mConstType == BfConstType_BitCastNull))
  7819. {
  7820. auto bitcast = (BfConstantBitCast*)constant;
  7821. constant = mBfIRBuilder->GetConstantById(bitcast->mTarget);
  7822. }
  7823. irVal = mCurTypeInstance->CreateConst(constant, mBfIRBuilder);
  7824. }
  7825. void BfModule::ClearConstData()
  7826. {
  7827. mBfIRBuilder->ClearConstData();
  7828. mStringObjectPool.Clear();
  7829. mStringCharPtrPool.Clear();
  7830. mStringPoolRefs.Clear();
  7831. }
  7832. BfTypedValue BfModule::GetTypedValueFromConstant(BfConstant* constant, BfIRConstHolder* constHolder, BfType* wantType)
  7833. {
  7834. bool isString = false;
  7835. isString = (wantType->IsObject()) && (wantType->ToTypeInstance()->mTypeDef == mCompiler->mStringTypeDef);
  7836. if (wantType->IsPointer())
  7837. isString = true;
  7838. if (!isString)
  7839. {
  7840. switch (constant->mTypeCode)
  7841. {
  7842. case BfTypeCode_Boolean:
  7843. case BfTypeCode_Int8:
  7844. case BfTypeCode_UInt8:
  7845. case BfTypeCode_Int16:
  7846. case BfTypeCode_UInt16:
  7847. case BfTypeCode_Int32:
  7848. case BfTypeCode_UInt32:
  7849. case BfTypeCode_Int64:
  7850. case BfTypeCode_UInt64:
  7851. case BfTypeCode_IntPtr:
  7852. case BfTypeCode_UIntPtr:
  7853. case BfTypeCode_IntUnknown:
  7854. case BfTypeCode_UIntUnknown:
  7855. case BfTypeCode_Char8:
  7856. case BfTypeCode_Char16:
  7857. case BfTypeCode_Char32:
  7858. case BfTypeCode_Single:
  7859. case BfTypeCode_Double:
  7860. {
  7861. auto constVal = mBfIRBuilder->CreateConst(constant, constHolder);
  7862. auto typedValue = BfTypedValue(constVal, GetPrimitiveType(constant->mTypeCode));
  7863. if (typedValue.mType == wantType)
  7864. return typedValue;
  7865. if (wantType->IsTypedPrimitive())
  7866. {
  7867. if (typedValue.mType == wantType->GetUnderlyingType())
  7868. {
  7869. typedValue.mType = wantType;
  7870. return typedValue;
  7871. }
  7872. }
  7873. auto castedTypedValue = Cast(NULL, typedValue, wantType, (BfCastFlags)(BfCastFlags_SilentFail | BfCastFlags_Explicit));
  7874. BF_ASSERT(castedTypedValue);
  7875. return castedTypedValue;
  7876. }
  7877. break;
  7878. default: break;
  7879. }
  7880. }
  7881. BfIRValue irValue = ConstantToCurrent(constant, constHolder, wantType);
  7882. BF_ASSERT(irValue);
  7883. if (!irValue)
  7884. return BfTypedValue();
  7885. return BfTypedValue(irValue, wantType, false);
  7886. }
  7887. BfIRValue BfModule::ConstantToCurrent(BfConstant* constant, BfIRConstHolder* constHolder, BfType* wantType)
  7888. {
  7889. if (constant->mTypeCode == BfTypeCode_NullPtr)
  7890. {
  7891. return GetDefaultValue(wantType);
  7892. }
  7893. bool isString = false;
  7894. isString = (wantType->IsObject()) && (wantType->ToTypeInstance()->mTypeDef == mCompiler->mStringTypeDef);
  7895. if (((wantType->IsPointer()) || (isString)) && (mBfIRBuilder->IsInt(constant->mTypeCode)))
  7896. {
  7897. const StringImpl& str = mContext->mStringObjectIdMap[constant->mInt32].mString;
  7898. BfIRValue stringObjConst = GetStringObjectValue(str);
  7899. if (wantType->IsObject())
  7900. return stringObjConst;
  7901. return GetStringCharPtr(stringObjConst);
  7902. }
  7903. if (constant->mConstType == BfConstType_Array)
  7904. {
  7905. auto elementType = wantType->GetUnderlyingType();
  7906. auto constArray = (BfConstantArray*)constant;
  7907. SizedArray<BfIRValue, 8> newVals;
  7908. for (auto val : constArray->mValues)
  7909. {
  7910. newVals.push_back(ConstantToCurrent(constHolder->GetConstant(val), constHolder, elementType));
  7911. }
  7912. return mBfIRBuilder->CreateConstArray(mBfIRBuilder->MapType(wantType), newVals);
  7913. }
  7914. return mBfIRBuilder->CreateConst(constant, constHolder);
  7915. }
  7916. void BfModule::ValidateCustomAttributes(BfCustomAttributes* customAttributes, BfAttributeTargets attrTarget)
  7917. {
  7918. if (attrTarget == BfAttributeTargets_SkipValidate)
  7919. return;
  7920. for (auto& customAttribute : customAttributes->mAttributes)
  7921. {
  7922. if (!customAttribute.mAwaitingValidation)
  7923. continue;
  7924. if ((customAttribute.mType->mAttributeData->mAttributeTargets & attrTarget) == 0)
  7925. {
  7926. Fail(StrFormat("Attribute '%s' is not valid on this declaration type. It is only valid on %s.",
  7927. customAttribute.mRef->ToString().c_str(), GetAttributesTargetListString(customAttribute.mType->mAttributeData->mAttributeTargets).c_str()), customAttribute.mRef->mAttributeTypeRef); // CS0592
  7928. }
  7929. customAttribute.mAwaitingValidation = false;
  7930. }
  7931. }
  7932. void BfModule::GetCustomAttributes(BfCustomAttributes* customAttributes, BfAttributeDirective* attributesDirective, BfAttributeTargets attrTarget)
  7933. {
  7934. if ((attributesDirective != NULL) && (mCompiler->mResolvePassData != NULL) &&
  7935. (attributesDirective->IsFromParser(mCompiler->mResolvePassData->mParser)) && (mCompiler->mResolvePassData->mSourceClassifier != NULL))
  7936. {
  7937. mCompiler->mResolvePassData->mSourceClassifier->VisitChild(attributesDirective);
  7938. }
  7939. SetAndRestoreValue<bool> prevIsCapturingMethodMatchInfo;
  7940. if (mCompiler->IsAutocomplete())
  7941. prevIsCapturingMethodMatchInfo.Init(mCompiler->mResolvePassData->mAutoComplete->mIsCapturingMethodMatchInfo, false);
  7942. BfTypeInstance* baseAttrTypeInst = mContext->mUnreifiedModule->ResolveTypeDef(mCompiler->mAttributeTypeDef)->ToTypeInstance();
  7943. BfAttributeTargets targetOverride = (BfAttributeTargets)0;
  7944. BfAutoComplete* autoComplete = NULL;
  7945. if (mCompiler->mResolvePassData != NULL)
  7946. autoComplete = mCompiler->mResolvePassData->mAutoComplete;
  7947. for (; attributesDirective != NULL; attributesDirective = attributesDirective->mNextAttribute)
  7948. {
  7949. BfAutoParentNodeEntry autoParentNodeEntry(this, attributesDirective);
  7950. BfCustomAttribute customAttribute;
  7951. customAttribute.mAwaitingValidation = true;
  7952. customAttribute.mRef = attributesDirective;
  7953. if (attributesDirective->mAttrOpenToken != NULL)
  7954. targetOverride = (BfAttributeTargets)0;
  7955. if (attributesDirective->mAttributeTypeRef == NULL)
  7956. {
  7957. AssertErrorState();
  7958. continue;
  7959. }
  7960. String attrName = attributesDirective->mAttributeTypeRef->ToString();
  7961. BfType* attrType = NULL;
  7962. BfAtomComposite nameComposite;
  7963. BfTypeDef* attrTypeDef = NULL;
  7964. if (mSystem->ParseAtomComposite(attrName + "Attribute", nameComposite))
  7965. {
  7966. BfTypeLookupError error;
  7967. error.mRefNode = attributesDirective->mAttributeTypeRef;
  7968. attrTypeDef = FindTypeDefRaw(nameComposite, 0, mCurTypeInstance, GetActiveTypeDef(NULL, true), &error);
  7969. }
  7970. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL))
  7971. {
  7972. mCompiler->mResolvePassData->mAutoComplete->CheckAttributeTypeRef(attributesDirective->mAttributeTypeRef);
  7973. if (attrTypeDef != NULL)
  7974. mCompiler->mResolvePassData->HandleTypeReference(attributesDirective->mAttributeTypeRef, attrTypeDef);
  7975. }
  7976. if (attrTypeDef == NULL)
  7977. {
  7978. TypeRefNotFound(attributesDirective->mAttributeTypeRef, "Attribute");
  7979. continue;
  7980. }
  7981. bool isBypassedAttr = false;
  7982. if (attrTypeDef != NULL)
  7983. {
  7984. attrType = mContext->mUnreifiedModule->ResolveTypeDef(attrTypeDef, BfPopulateType_Identity);
  7985. // 'Object' has some dependencies on some attributes, but those attributes are classes so we have a circular dependency issue
  7986. // We solve it by having a 'bypass' for known attributes that Object depends on
  7987. if ((attributesDirective->mArguments.empty()) && (autoComplete == NULL) && (attrType != NULL) && (attrType->IsTypeInstance()))
  7988. {
  7989. if (attrTypeDef == mCompiler->mCReprAttributeTypeDef)
  7990. {
  7991. BfTypeInstance* attrTypeInst = attrType->ToTypeInstance();
  7992. for (auto methodDef : attrTypeDef->mMethods)
  7993. {
  7994. if ((methodDef->mMethodType == BfMethodType_Ctor) && (methodDef->mProtection == BfProtection_Public))
  7995. {
  7996. customAttribute.mType = attrType->ToTypeInstance();
  7997. customAttribute.mCtor = methodDef;
  7998. isBypassedAttr = true;
  7999. break;
  8000. }
  8001. }
  8002. }
  8003. }
  8004. if (isBypassedAttr)
  8005. {
  8006. customAttribute.mAwaitingValidation = false;
  8007. customAttributes->mAttributes.push_back(customAttribute);
  8008. continue;
  8009. }
  8010. if (mContext->mCurTypeState != NULL)
  8011. {
  8012. SetAndRestoreValue<BfTypeReference*> prevTypeRef(mContext->mCurTypeState->mCurAttributeTypeRef, attributesDirective->mAttributeTypeRef);
  8013. mContext->mUnreifiedModule->ResolveTypeResult(attributesDirective->mAttributeTypeRef, attrType, BfPopulateType_BaseType, (BfResolveTypeRefFlags)0);
  8014. }
  8015. else
  8016. {
  8017. mContext->mUnreifiedModule->ResolveTypeResult(attributesDirective->mAttributeTypeRef, attrType, BfPopulateType_BaseType, (BfResolveTypeRefFlags)0);
  8018. }
  8019. }
  8020. // Don't allow this
  8021. /*else if (mContext->mCurTypeState != NULL)
  8022. {
  8023. SetAndRestoreValue<BfTypeReference*> prevTypeRef(mContext->mCurTypeState->mCurAttributeTypeRef, attributesDirective->mAttributeTypeRef);
  8024. attrType = mContext->mUnreifiedModule->ResolveTypeRef(attributesDirective->mAttributeTypeRef, BfPopulateType_DataAndMethods);
  8025. }
  8026. else
  8027. {
  8028. attrType = mContext->mUnreifiedModule->ResolveTypeRef(attributesDirective->mAttributeTypeRef);
  8029. }*/
  8030. BfTypeInstance* attrTypeInst = NULL;
  8031. if (attrType == NULL)
  8032. continue;
  8033. mContext->mUnreifiedModule->PopulateType(attrType, BfPopulateType_DataAndMethods);
  8034. attrTypeInst = attrType->ToTypeInstance();
  8035. if ((attrTypeInst == NULL) || (!TypeIsSubTypeOf(attrTypeInst, baseAttrTypeInst)) || (attrTypeInst->mAttributeData == NULL))
  8036. {
  8037. Fail(StrFormat("'%s' is not an attribute class", TypeToString(attrType).c_str()), attributesDirective->mAttributeTypeRef); //CS0616
  8038. continue;
  8039. }
  8040. if (mCurTypeInstance != NULL)
  8041. AddDependency(attrTypeInst, mCurTypeInstance, BfDependencyMap::DependencyFlag_CustomAttribute);
  8042. customAttribute.mType = attrTypeInst;
  8043. BfConstResolver constResolver(this);
  8044. bool inPropSet = false;
  8045. SizedArray<BfResolvedArg, 2> argValues;
  8046. for (BfExpression* arg : attributesDirective->mArguments)
  8047. {
  8048. if (arg == NULL)
  8049. {
  8050. continue;
  8051. }
  8052. if (autoComplete != NULL)
  8053. autoComplete->mShowAttributeProperties = attrTypeInst;
  8054. if (auto assignExpr = BfNodeDynCast<BfAssignmentExpression>(arg))
  8055. {
  8056. inPropSet = true;
  8057. if (autoComplete != NULL)
  8058. autoComplete->CheckNode(assignExpr->mLeft);
  8059. String findName = assignExpr->mLeft->ToString();
  8060. BfPropertyDef* bestProp = NULL;
  8061. BfTypeInstance* bestPropTypeInst = NULL;
  8062. BfFieldDef* bestField = NULL;
  8063. BfTypeInstance* bestFieldTypeInst = NULL;
  8064. auto checkTypeInst = attrTypeInst;
  8065. while (checkTypeInst != NULL)
  8066. {
  8067. mContext->mUnreifiedModule->PopulateType(checkTypeInst, BfPopulateType_Data);
  8068. for (auto prop : checkTypeInst->mTypeDef->mProperties)
  8069. {
  8070. if (prop->mName == findName)
  8071. {
  8072. if ((bestProp == NULL) || (bestProp->mProtection != BfProtection_Public))
  8073. {
  8074. bestProp = prop;
  8075. bestPropTypeInst = checkTypeInst;
  8076. }
  8077. }
  8078. }
  8079. for (auto field : checkTypeInst->mTypeDef->mFields)
  8080. {
  8081. if (field->mName == findName)
  8082. {
  8083. if ((bestField == NULL) || (bestField->mProtection != BfProtection_Public))
  8084. {
  8085. bestField = field;
  8086. bestFieldTypeInst = checkTypeInst;
  8087. }
  8088. }
  8089. }
  8090. if ((bestProp != NULL) || (bestField != NULL))
  8091. break;
  8092. checkTypeInst = checkTypeInst->mBaseType;
  8093. }
  8094. bool handledExpr = false;
  8095. if (bestField != NULL)
  8096. {
  8097. handledExpr = true;
  8098. if (mCompiler->mResolvePassData != NULL)
  8099. {
  8100. mCompiler->mResolvePassData->HandleFieldReference(assignExpr->mLeft, attrTypeDef, bestField);
  8101. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(assignExpr->mLeft)))
  8102. {
  8103. autoComplete->mDefField = bestField;
  8104. autoComplete->mDefType = attrTypeDef;
  8105. }
  8106. }
  8107. if (bestField->mProtection != BfProtection_Public)
  8108. Fail(StrFormat("'%s.%s' is inaccessible due to its protection level", TypeToString(bestFieldTypeInst).c_str(), findName.c_str()), assignExpr->mLeft); // CS0122
  8109. AddDependency(bestFieldTypeInst, mCurTypeInstance, BfDependencyMap::DependencyFlag_CustomAttribute);
  8110. BfCustomAttributeSetField setField;
  8111. setField.mFieldRef = BfFieldRef(bestFieldTypeInst, bestField);
  8112. auto& fieldTypeInst = checkTypeInst->mFieldInstances[bestField->mIdx];
  8113. if (assignExpr->mRight != NULL)
  8114. {
  8115. BfTypedValue result = constResolver.Resolve(assignExpr->mRight, fieldTypeInst.mResolvedType);
  8116. if (result)
  8117. {
  8118. CurrentAddToConstHolder(result.mValue);
  8119. setField.mParam = result;
  8120. customAttribute.mSetField.push_back(setField);
  8121. }
  8122. }
  8123. }
  8124. else if (bestProp == NULL)
  8125. {
  8126. Fail(StrFormat("'%s' does not contain a field or property named '%s'", TypeToString(attrTypeInst).c_str(), findName.c_str()), assignExpr->mLeft);
  8127. }
  8128. else
  8129. {
  8130. BfMethodDef* setMethod = NULL;
  8131. for (auto methodDef : bestProp->mMethods)
  8132. {
  8133. if (methodDef->mMethodType == BfMethodType_PropertySetter)
  8134. {
  8135. setMethod = methodDef;
  8136. break;
  8137. }
  8138. }
  8139. if (setMethod == NULL)
  8140. {
  8141. Fail("Property has no setter", assignExpr->mLeft);
  8142. }
  8143. else
  8144. {
  8145. if (mCompiler->mResolvePassData != NULL)
  8146. {
  8147. mCompiler->mResolvePassData->HandlePropertyReference(assignExpr->mLeft, attrTypeDef, bestProp);
  8148. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(assignExpr->mLeft)))
  8149. {
  8150. autoComplete->mDefProp = bestProp;
  8151. autoComplete->mDefType = attrTypeDef;
  8152. }
  8153. }
  8154. handledExpr = true;
  8155. if (bestProp->mProtection != BfProtection_Public)
  8156. Fail(StrFormat("'%s.%s' is inaccessible due to its protection level", TypeToString(bestPropTypeInst).c_str(), findName.c_str()), assignExpr->mLeft); // CS0122
  8157. BfResolvedArg resolvedArg;
  8158. AddDependency(bestPropTypeInst, mCurTypeInstance, BfDependencyMap::DependencyFlag_CustomAttribute);
  8159. BfCustomAttributeSetProperty setProperty;
  8160. setProperty.mPropertyRef = BfPropertyRef(bestPropTypeInst, bestProp);
  8161. // We don't actually need the mFunc, so get the ModuleMethodInstance from the native module
  8162. auto methodInstance = bestPropTypeInst->mModule->GetMethodInstance(bestPropTypeInst, setMethod, BfTypeVector());
  8163. if (methodInstance.mMethodInstance != NULL)
  8164. {
  8165. auto propType = methodInstance.mMethodInstance->GetParamType(0);
  8166. if (assignExpr->mRight != NULL)
  8167. {
  8168. BfTypedValue result = constResolver.Resolve(assignExpr->mRight, propType);
  8169. if (result)
  8170. {
  8171. BF_ASSERT(result.mType == propType);
  8172. CurrentAddToConstHolder(result.mValue);
  8173. setProperty.mParam = result;
  8174. customAttribute.mSetProperties.push_back(setProperty);
  8175. }
  8176. }
  8177. }
  8178. }
  8179. }
  8180. if ((!handledExpr) && (assignExpr->mRight != NULL))
  8181. constResolver.Resolve(assignExpr->mRight);
  8182. }
  8183. else
  8184. {
  8185. if (inPropSet)
  8186. {
  8187. Fail("Named attribute argument expected", arg); // CS1016
  8188. }
  8189. BfDeferEvalChecker deferEvalChecker;
  8190. arg->Accept(&deferEvalChecker);
  8191. bool deferParamEval = deferEvalChecker.mNeedsDeferEval;
  8192. BfResolvedArg resolvedArg;
  8193. resolvedArg.mExpression = arg;
  8194. if (deferParamEval)
  8195. {
  8196. resolvedArg.mArgFlags = BfArgFlag_DeferredEval;
  8197. }
  8198. else
  8199. resolvedArg.mTypedValue = constResolver.Resolve(arg);
  8200. if (!inPropSet)
  8201. argValues.push_back(resolvedArg);
  8202. }
  8203. if (autoComplete != NULL)
  8204. autoComplete->mShowAttributeProperties = NULL;
  8205. }
  8206. auto wasCapturingMethodInfo = false;
  8207. if (autoComplete != NULL)
  8208. {
  8209. wasCapturingMethodInfo = autoComplete->mIsCapturingMethodMatchInfo;
  8210. if (attributesDirective->mCtorOpenParen != NULL)
  8211. autoComplete->CheckInvocation(attributesDirective, attributesDirective->mCtorOpenParen, attributesDirective->mCtorCloseParen, attributesDirective->mCommas);
  8212. }
  8213. BfMethodMatcher methodMatcher(attributesDirective, this, "", argValues, NULL);
  8214. attrTypeDef = attrTypeInst->mTypeDef;
  8215. bool success = true;
  8216. bool isFailurePass = false;
  8217. for (int pass = 0; pass < 2; pass++)
  8218. {
  8219. bool isFailurePass = pass == 1;
  8220. for (auto checkMethod : attrTypeDef->mMethods)
  8221. {
  8222. if ((isFailurePass) && (checkMethod->mMethodDeclaration == NULL))
  8223. continue; // Don't match private default ctor if there's a user-defined one
  8224. if ((checkMethod->mIsStatic) || (checkMethod->mMethodType != BfMethodType_Ctor))
  8225. continue;
  8226. if ((!isFailurePass) && (!CheckProtection(checkMethod->mProtection, false, false)))
  8227. continue;
  8228. methodMatcher.CheckMethod(attrTypeInst, checkMethod, isFailurePass);
  8229. }
  8230. if ((methodMatcher.mBestMethodDef != NULL) || (methodMatcher.mBackupMethodDef != NULL))
  8231. break;
  8232. }
  8233. if (autoComplete != NULL)
  8234. {
  8235. if ((wasCapturingMethodInfo) && (!autoComplete->mIsCapturingMethodMatchInfo))
  8236. {
  8237. autoComplete->mIsCapturingMethodMatchInfo = true;
  8238. BF_ASSERT(autoComplete->mMethodMatchInfo != NULL);
  8239. }
  8240. else
  8241. autoComplete->mIsCapturingMethodMatchInfo = false;
  8242. }
  8243. if (methodMatcher.mBestMethodDef == NULL)
  8244. methodMatcher.mBestMethodDef = methodMatcher.mBackupMethodDef;
  8245. BF_ASSERT(methodMatcher.mBestMethodDef != NULL);
  8246. customAttribute.mCtor = methodMatcher.mBestMethodDef;
  8247. if (methodMatcher.mBestMethodTypeInstance == mCurTypeInstance)
  8248. {
  8249. Fail("Custom attribute circular reference", attributesDirective);
  8250. }
  8251. if (mCurTypeInstance != NULL)
  8252. AddDependency(methodMatcher.mBestMethodTypeInstance, mCurTypeInstance, BfDependencyMap::DependencyFlag_CustomAttribute);
  8253. if (!constResolver.PrepareMethodArguments(attributesDirective->mAttributeTypeRef, &methodMatcher, customAttribute.mCtorArgs))
  8254. success = false;
  8255. for (auto& arg : argValues)
  8256. {
  8257. if ((arg.mArgFlags & BfArgFlag_DeferredEval) != 0)
  8258. {
  8259. if (auto expr = BfNodeDynCast<BfExpression>(arg.mExpression))
  8260. constResolver.Resolve(expr);
  8261. }
  8262. }
  8263. // Move all those to the constHolder
  8264. for (auto& ctorArg : customAttribute.mCtorArgs)
  8265. {
  8266. CurrentAddToConstHolder(ctorArg);
  8267. }
  8268. if (attributesDirective->mAttributeTargetSpecifier != NULL)
  8269. {
  8270. targetOverride = BfAttributeTargets_ReturnValue;
  8271. if (attrTarget != BfAttributeTargets_Method)
  8272. {
  8273. 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.",
  8274. GetAttributesTargetListString(targetOverride).c_str(), GetAttributesTargetListString(attrTarget).c_str()), attributesDirective->mAttributeTargetSpecifier); // CS0657
  8275. }
  8276. success = false;
  8277. }
  8278. if ((success) && (targetOverride != (BfAttributeTargets)0))
  8279. {
  8280. if ((targetOverride == BfAttributeTargets_ReturnValue) && (attrTarget == BfAttributeTargets_Method))
  8281. {
  8282. auto methodInfoEx = mCurMethodInstance->GetMethodInfoEx();
  8283. if (methodInfoEx->mMethodCustomAttributes == NULL)
  8284. methodInfoEx->mMethodCustomAttributes = new BfMethodCustomAttributes();
  8285. if (success)
  8286. {
  8287. if (methodInfoEx->mMethodCustomAttributes->mReturnCustomAttributes == NULL)
  8288. methodInfoEx->mMethodCustomAttributes->mReturnCustomAttributes = new BfCustomAttributes();
  8289. methodInfoEx->mMethodCustomAttributes->mReturnCustomAttributes->mAttributes.push_back(customAttribute);
  8290. }
  8291. }
  8292. else
  8293. {
  8294. // Failed - ignore
  8295. success = false;
  8296. }
  8297. }
  8298. if (success)
  8299. {
  8300. if (!attrTypeInst->mAttributeData->mAllowMultiple)
  8301. {
  8302. for (auto& prevCustomAttribute : customAttributes->mAttributes)
  8303. {
  8304. if (prevCustomAttribute.mType == attrTypeInst)
  8305. {
  8306. Fail(StrFormat("Duplicate '%s' attribute", attributesDirective->mAttributeTypeRef->ToString().c_str()), attributesDirective->mAttributeTypeRef); // CS0579
  8307. }
  8308. }
  8309. }
  8310. }
  8311. if (success)
  8312. {
  8313. customAttributes->mAttributes.push_back(customAttribute);
  8314. }
  8315. }
  8316. ValidateCustomAttributes(customAttributes, attrTarget);
  8317. }
  8318. BfCustomAttributes* BfModule::GetCustomAttributes(BfAttributeDirective* attributesDirective, BfAttributeTargets attrType)
  8319. {
  8320. BfCustomAttributes* customAttributes = new BfCustomAttributes();
  8321. GetCustomAttributes(customAttributes, attributesDirective, attrType);
  8322. return customAttributes;
  8323. }
  8324. void BfModule::ProcessTypeInstCustomAttributes(bool& isPacked, bool& isUnion, bool& isCRepr, bool& isOrdered)
  8325. {
  8326. if (mCurTypeInstance->mCustomAttributes != NULL)
  8327. {
  8328. for (auto& customAttribute : mCurTypeInstance->mCustomAttributes->mAttributes)
  8329. {
  8330. String typeName = TypeToString(customAttribute.mType);
  8331. if (typeName == "System.PackedAttribute")
  8332. {
  8333. isPacked = true;
  8334. }
  8335. else if (typeName == "System.UnionAttribute")
  8336. {
  8337. isUnion = true;
  8338. }
  8339. else if (typeName == "System.CReprAttribute")
  8340. {
  8341. isCRepr = true;
  8342. isOrdered = true;
  8343. }
  8344. else if (typeName == "System.OrderedAttribute")
  8345. {
  8346. isOrdered = true;
  8347. }
  8348. else if (typeName == "System.AlwaysIncludeAttribute")
  8349. {
  8350. for (auto setProp : customAttribute.mSetProperties)
  8351. {
  8352. BfPropertyDef* propertyDef = setProp.mPropertyRef;
  8353. if (propertyDef->mName == "AssumeInstantiated")
  8354. {
  8355. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  8356. if ((constant != NULL) && (constant->mBool))
  8357. mCurTypeInstance->mHasBeenInstantiated = true;
  8358. }
  8359. }
  8360. }
  8361. }
  8362. }
  8363. }
  8364. // Checking to see if we're an attribute or not
  8365. void BfModule::ProcessCustomAttributeData()
  8366. {
  8367. bool isAttribute = false;
  8368. auto checkTypeInst = mCurTypeInstance->mBaseType;
  8369. while (checkTypeInst != NULL)
  8370. {
  8371. if (checkTypeInst->mTypeDef == mCompiler->mAttributeTypeDef)
  8372. isAttribute = true;
  8373. checkTypeInst = checkTypeInst->mBaseType;
  8374. }
  8375. if (!isAttribute)
  8376. return;
  8377. auto attributeData = new BfAttributeData();
  8378. bool hasCustomAttribute = false;
  8379. if (mCurTypeInstance->mCustomAttributes != NULL)
  8380. {
  8381. for (auto& customAttribute : mCurTypeInstance->mCustomAttributes->mAttributes)
  8382. {
  8383. if (customAttribute.mType->mTypeDef == mCompiler->mAttributeUsageAttributeTypeDef)
  8384. {
  8385. if (customAttribute.mCtorArgs.size() > 0)
  8386. {
  8387. auto constant = mCurTypeInstance->mConstHolder->GetConstant(customAttribute.mCtorArgs[0]);
  8388. if ((constant != NULL) && (mBfIRBuilder->IsInt(constant->mTypeCode)))
  8389. attributeData->mAttributeTargets = (BfAttributeTargets)constant->mInt32;
  8390. }
  8391. for (auto& setProp : customAttribute.mSetProperties)
  8392. {
  8393. BfPropertyDef* propDef = setProp.mPropertyRef;
  8394. if (propDef->mName == "AllowMultiple")
  8395. {
  8396. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  8397. if (constant != NULL)
  8398. attributeData->mAllowMultiple = constant->mBool;
  8399. }
  8400. else if (propDef->mName == "Inherited")
  8401. {
  8402. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  8403. if (constant != NULL)
  8404. attributeData->mInherited = constant->mBool;
  8405. }
  8406. else if (propDef->mName == "ValidOn")
  8407. {
  8408. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  8409. if (constant != NULL)
  8410. attributeData->mAttributeTargets = (BfAttributeTargets)constant->mInt32;
  8411. }
  8412. }
  8413. hasCustomAttribute = true;
  8414. }
  8415. }
  8416. }
  8417. if ((!hasCustomAttribute) && (mCurTypeInstance->mBaseType->mAttributeData != NULL))
  8418. {
  8419. attributeData->mAttributeTargets = mCurTypeInstance->mBaseType->mAttributeData->mAttributeTargets;
  8420. attributeData->mInherited = mCurTypeInstance->mBaseType->mAttributeData->mInherited;
  8421. attributeData->mAllowMultiple = mCurTypeInstance->mBaseType->mAttributeData->mAllowMultiple;
  8422. }
  8423. mCurTypeInstance->mAttributeData = attributeData;
  8424. }
  8425. bool BfModule::TryGetConstString(BfIRConstHolder* constHolder, BfIRValue irValue, StringImpl& str)
  8426. {
  8427. auto constant = constHolder->GetConstant(irValue);
  8428. if (constant == NULL)
  8429. return false;
  8430. if (!BfIRConstHolder::IsInt(constant->mTypeCode))
  8431. return false;
  8432. int stringId = constant->mInt32;
  8433. BfStringPoolEntry* entry = NULL;
  8434. if (mContext->mStringObjectIdMap.TryGetValue(stringId, &entry))
  8435. {
  8436. str = entry->mString;
  8437. }
  8438. else
  8439. {
  8440. BF_DBG_FATAL("Failed to find string by id");
  8441. }
  8442. return true;
  8443. }
  8444. BfVariant BfModule::TypedValueToVariant(BfAstNode* refNode, const BfTypedValue& value, bool allowUndef)
  8445. {
  8446. BfVariant variant;
  8447. variant.mTypeCode = BfTypeCode_None;
  8448. BfType* primType = NULL;
  8449. if (value.mType->IsPrimitiveType())
  8450. primType = (BfPrimitiveType*)value.mType;
  8451. else if (value.mType->IsTypedPrimitive())
  8452. primType = value.mType->GetUnderlyingType();
  8453. if (primType)
  8454. {
  8455. auto constant = mBfIRBuilder->GetConstant(value.mValue);
  8456. if (constant != NULL)
  8457. {
  8458. if ((allowUndef) && (constant->mConstType == BfConstType_Undef))
  8459. {
  8460. variant.mTypeCode = BfTypeCode_Let;
  8461. return variant;
  8462. }
  8463. switch (constant->mTypeCode)
  8464. {
  8465. case BfTypeCode_Int8:
  8466. case BfTypeCode_UInt8:
  8467. case BfTypeCode_Int16:
  8468. case BfTypeCode_UInt16:
  8469. case BfTypeCode_Int32:
  8470. case BfTypeCode_UInt32:
  8471. case BfTypeCode_Int64:
  8472. case BfTypeCode_UInt64:
  8473. case BfTypeCode_IntPtr:
  8474. case BfTypeCode_UIntPtr:
  8475. case BfTypeCode_IntUnknown:
  8476. case BfTypeCode_UIntUnknown:
  8477. case BfTypeCode_Single:
  8478. case BfTypeCode_Double:
  8479. case BfTypeCode_Char8:
  8480. case BfTypeCode_Char16:
  8481. case BfTypeCode_Char32:
  8482. variant.mTypeCode = constant->mTypeCode;
  8483. variant.mInt64 = constant->mInt64;
  8484. break;
  8485. default:
  8486. if (refNode != NULL)
  8487. Fail("Invalid const expression type", refNode);
  8488. break;
  8489. }
  8490. }
  8491. }
  8492. return variant;
  8493. }
  8494. BfTypedValue BfModule::RemoveRef(BfTypedValue typedValue)
  8495. {
  8496. if ((typedValue.mType != NULL) && (typedValue.mType->IsRef()))
  8497. {
  8498. auto elementType = typedValue.mType->GetUnderlyingType();
  8499. if (typedValue.IsAddr())
  8500. {
  8501. if (elementType->IsValuelessType())
  8502. {
  8503. BF_ASSERT(!typedValue.mValue);
  8504. typedValue = BfTypedValue(typedValue.mValue, elementType, true);
  8505. }
  8506. else
  8507. typedValue = BfTypedValue(mBfIRBuilder->CreateLoad(typedValue.mValue), elementType, true);
  8508. }
  8509. else
  8510. typedValue = BfTypedValue(typedValue.mValue, elementType, true);
  8511. if (typedValue.mType->IsValuelessType())
  8512. {
  8513. BF_ASSERT(typedValue.mValue.IsFake());
  8514. }
  8515. }
  8516. return typedValue;
  8517. }
  8518. BfTypedValue BfModule::LoadValue(BfTypedValue typedValue, BfAstNode* refNode, bool isVolatile)
  8519. {
  8520. if (!typedValue.IsAddr())
  8521. return typedValue;
  8522. if (typedValue.mType->IsValuelessType())
  8523. return BfTypedValue(mBfIRBuilder->GetFakeVal(), typedValue.mType, false);
  8524. BfIRValue loadedVal = typedValue.mValue;
  8525. if (loadedVal)
  8526. {
  8527. /*if (isVolatile)
  8528. mBfIRBuilder->CreateFence(BfIRFenceType_AcquireRelease);*/
  8529. PopulateType(typedValue.mType, BfPopulateType_Data);
  8530. loadedVal = mBfIRBuilder->CreateAlignedLoad(loadedVal, std::max(1, (int)typedValue.mType->mAlign), isVolatile);
  8531. }
  8532. return BfTypedValue(loadedVal, typedValue.mType, false);
  8533. }
  8534. BfTypedValue BfModule::LoadOrAggregateValue(BfTypedValue typedValue)
  8535. {
  8536. if (typedValue.IsSplat())
  8537. return AggregateSplat(typedValue);
  8538. if (typedValue.IsAddr())
  8539. return LoadValue(typedValue);
  8540. return typedValue;
  8541. }
  8542. BfTypedValue BfModule::AggregateSplat(BfTypedValue typedValue, BfIRValue* valueArrPtr)
  8543. {
  8544. if (!typedValue.IsSplat())
  8545. return typedValue;
  8546. if (typedValue.mType->IsValuelessType())
  8547. return typedValue;
  8548. int elementIdx = 0;
  8549. auto _ExtractValue = [&](BfType* checkType)
  8550. {
  8551. if (valueArrPtr != NULL)
  8552. return valueArrPtr[elementIdx++];
  8553. return ExtractSplatValue(typedValue, elementIdx++, checkType);
  8554. };
  8555. std::function<BfIRValue(BfType*)> checkTypeLambda = [&](BfType* checkType)
  8556. {
  8557. if (checkType->IsStruct())
  8558. {
  8559. BfIRValue curValue = mBfIRBuilder->CreateUndefValue(mBfIRBuilder->MapType(checkType, BfIRPopulateType_Full));
  8560. auto checkTypeInstance = checkType->ToTypeInstance();
  8561. if (checkTypeInstance->mBaseType != NULL)
  8562. {
  8563. mBfIRBuilder->PopulateType(checkTypeInstance->mBaseType, BfIRPopulateType_Full);
  8564. BfIRValue baseValue = checkTypeLambda(checkTypeInstance->mBaseType);
  8565. curValue = mBfIRBuilder->CreateInsertValue(curValue, baseValue, 0);
  8566. }
  8567. if (checkTypeInstance->mIsUnion)
  8568. {
  8569. auto unionInnerType = checkTypeInstance->GetUnionInnerType();
  8570. if (!unionInnerType->IsValuelessType())
  8571. {
  8572. BfIRValue fieldValue = checkTypeLambda(unionInnerType);
  8573. curValue = mBfIRBuilder->CreateInsertValue(curValue, fieldValue, 1);
  8574. }
  8575. if (checkTypeInstance->IsEnum())
  8576. {
  8577. auto dscrType = checkTypeInstance->GetDiscriminatorType();
  8578. BfIRValue fieldValue = checkTypeLambda(dscrType);
  8579. curValue = mBfIRBuilder->CreateInsertValue(curValue, fieldValue, 2);
  8580. }
  8581. }
  8582. else
  8583. {
  8584. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  8585. {
  8586. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  8587. if (fieldInstance->mDataIdx >= 0)
  8588. {
  8589. BfIRValue fieldValue = checkTypeLambda(fieldInstance->GetResolvedType());
  8590. curValue = mBfIRBuilder->CreateInsertValue(curValue, fieldValue, fieldInstance->mDataIdx);
  8591. }
  8592. }
  8593. }
  8594. return curValue;
  8595. }
  8596. else if (checkType->IsMethodRef())
  8597. {
  8598. BfMethodRefType* methodRefType = (BfMethodRefType*)checkType;
  8599. BfIRValue curValue = mBfIRBuilder->CreateUndefValue(mBfIRBuilder->MapType(checkType, BfIRPopulateType_Full));
  8600. for (int dataIdx = 0; dataIdx < methodRefType->GetCaptureDataCount(); dataIdx++)
  8601. {
  8602. BfIRValue fieldValue;
  8603. auto checkType = methodRefType->GetCaptureType(dataIdx);
  8604. if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  8605. {
  8606. fieldValue = checkTypeLambda(checkType);
  8607. }
  8608. else
  8609. {
  8610. fieldValue = _ExtractValue(checkType);
  8611. }
  8612. curValue = mBfIRBuilder->CreateInsertValue(curValue, fieldValue, dataIdx);
  8613. }
  8614. return curValue;
  8615. }
  8616. else if (!checkType->IsValuelessType())
  8617. {
  8618. return _ExtractValue(checkType);
  8619. }
  8620. return BfIRValue();
  8621. };
  8622. BfIRValue value = checkTypeLambda(typedValue.mType);
  8623. return BfTypedValue(value, typedValue.mType, typedValue.IsThis() ? BfTypedValueKind_ThisValue : BfTypedValueKind_Value);
  8624. }
  8625. void BfModule::AggregateSplatIntoAddr(BfTypedValue typedValue, BfIRValue addrVal)
  8626. {
  8627. if (!typedValue.IsSplat())
  8628. return;
  8629. if (typedValue.mType->IsValuelessType())
  8630. return;
  8631. /*static int sCallIdx = 0;
  8632. if (!mCompiler->mIsResolveOnly)
  8633. sCallIdx++;
  8634. int callIdx = sCallIdx;*/
  8635. int elementIdx = 0;
  8636. std::function<void(BfType*, BfIRValue)> checkTypeLambda = [&](BfType* checkType, BfIRValue curAddrVal)
  8637. {
  8638. if (checkType->IsStruct())
  8639. {
  8640. auto checkTypeInstance = checkType->ToTypeInstance();
  8641. if (checkTypeInstance->mBaseType != NULL)
  8642. {
  8643. mBfIRBuilder->PopulateType(checkTypeInstance->mBaseType);
  8644. auto baseAddrVal = mBfIRBuilder->CreateInBoundsGEP(curAddrVal, 0, 0);
  8645. checkTypeLambda(checkTypeInstance->mBaseType, baseAddrVal);
  8646. }
  8647. if (checkTypeInstance->mIsUnion)
  8648. {
  8649. auto unionInnerType = checkTypeInstance->GetUnionInnerType();
  8650. if (!unionInnerType->IsValuelessType())
  8651. {
  8652. auto fieldAddrVal = mBfIRBuilder->CreateInBoundsGEP(curAddrVal, 0, 1);
  8653. checkTypeLambda(unionInnerType, fieldAddrVal);
  8654. }
  8655. if (checkTypeInstance->IsEnum())
  8656. {
  8657. auto dscrType = checkTypeInstance->GetDiscriminatorType();
  8658. auto fieldAddrVal = mBfIRBuilder->CreateInBoundsGEP(curAddrVal, 0, 2);
  8659. checkTypeLambda(dscrType, fieldAddrVal);
  8660. }
  8661. }
  8662. else
  8663. {
  8664. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  8665. {
  8666. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  8667. if (fieldInstance->mDataIdx >= 0)
  8668. {
  8669. auto fieldAddrVal = mBfIRBuilder->CreateInBoundsGEP(curAddrVal, 0, fieldInstance->mDataIdx);
  8670. checkTypeLambda(fieldInstance->mResolvedType, fieldAddrVal);
  8671. }
  8672. }
  8673. }
  8674. }
  8675. else if (checkType->IsMethodRef())
  8676. {
  8677. BfMethodRefType* methodRefType = (BfMethodRefType*)checkType;
  8678. for (int dataIdx = 0; dataIdx < methodRefType->GetCaptureDataCount(); dataIdx++)
  8679. {
  8680. auto dataType = methodRefType->GetCaptureType(dataIdx);
  8681. auto fieldAddrVal = mBfIRBuilder->CreateInBoundsGEP(curAddrVal, 0, dataIdx);
  8682. if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  8683. {
  8684. checkTypeLambda(methodRefType->GetCaptureType(dataIdx), fieldAddrVal);
  8685. }
  8686. else
  8687. {
  8688. // static int sItrCount = 0;
  8689. // sItrCount++;
  8690. // int curItr = sItrCount;
  8691. // if (curItr == 1)
  8692. // {
  8693. // NOP;
  8694. // }
  8695. auto val = ExtractSplatValue(typedValue, elementIdx++, dataType);
  8696. mBfIRBuilder->CreateStore(val, fieldAddrVal);
  8697. }
  8698. }
  8699. }
  8700. else if (!checkType->IsValuelessType())
  8701. {
  8702. auto val = ExtractSplatValue(typedValue, elementIdx++, checkType);
  8703. mBfIRBuilder->CreateStore(val, curAddrVal);
  8704. }
  8705. };
  8706. checkTypeLambda(typedValue.mType, addrVal);
  8707. }
  8708. BfTypedValue BfModule::MakeAddressable(BfTypedValue typedVal)
  8709. {
  8710. bool wasReadOnly = typedVal.IsReadOnly();
  8711. if ((typedVal.mType->IsValueType()) &&
  8712. (!typedVal.mType->IsValuelessType()))
  8713. {
  8714. wasReadOnly = true; // Any non-addr is implicitly read-only
  8715. //static int gCallIdx = 0;
  8716. if (typedVal.IsAddr())
  8717. return typedVal;
  8718. BfType* type = typedVal.mType;
  8719. PopulateType(type);
  8720. auto tempVar = CreateAlloca(type);
  8721. if (typedVal.IsSplat())
  8722. AggregateSplatIntoAddr(typedVal, tempVar);
  8723. else
  8724. mBfIRBuilder->CreateAlignedStore(typedVal.mValue, tempVar, type->mAlign);
  8725. return BfTypedValue(tempVar, type,
  8726. typedVal.IsThis() ?
  8727. (wasReadOnly ? BfTypedValueKind_ReadOnlyThisAddr : BfTypedValueKind_ThisAddr) :
  8728. (wasReadOnly ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Addr));
  8729. }
  8730. return LoadValue(typedVal);
  8731. }
  8732. BfTypedValue BfModule::RemoveReadOnly(BfTypedValue typedValue)
  8733. {
  8734. if (typedValue.mKind == BfTypedValueKind_ReadOnlyAddr)
  8735. typedValue.mKind = BfTypedValueKind_Addr;
  8736. return typedValue;
  8737. }
  8738. BfIRValue BfModule::ExtractSplatValue(BfTypedValue typedValue, int componentIdx, BfType* wantType, bool* isAddr)
  8739. {
  8740. BfIRValue val;
  8741. if (typedValue.mValue.IsArg())
  8742. {
  8743. val = mBfIRBuilder->GetArgument(typedValue.mValue.mId + componentIdx);
  8744. if (isAddr != NULL)
  8745. {
  8746. if (wantType != NULL)
  8747. *isAddr = wantType->IsComposite();
  8748. else
  8749. *isAddr = false;
  8750. }
  8751. else if (wantType->IsComposite())
  8752. val = mBfIRBuilder->CreateLoad(val);
  8753. }
  8754. if (!val)
  8755. {
  8756. auto checkMethodState = mCurMethodState;
  8757. while (checkMethodState != NULL)
  8758. {
  8759. for (int idx = 0; idx < (int)checkMethodState->mSplatDecompAddrs.size(); idx++)
  8760. {
  8761. auto decompAddr = checkMethodState->mSplatDecompAddrs[idx];
  8762. if (decompAddr == typedValue.mValue)
  8763. {
  8764. val = checkMethodState->mSplatDecompAddrs[idx + componentIdx];
  8765. if ((wantType->IsComposite()) && (typedValue.mType->IsMethodRef()))
  8766. {
  8767. // This is really backing for a POINTER to a composite inside a methodRef
  8768. val = mBfIRBuilder->CreateLoad(val);
  8769. }
  8770. if ((isAddr != NULL) && (typedValue.mKind != BfTypedValueKind_SplatHead_NeedsCasting))
  8771. {
  8772. *isAddr = true;
  8773. return val;
  8774. }
  8775. else
  8776. {
  8777. val = mBfIRBuilder->CreateLoad(val);
  8778. break;
  8779. }
  8780. }
  8781. }
  8782. if (val)
  8783. break;
  8784. checkMethodState = checkMethodState->mPrevMethodState;
  8785. }
  8786. }
  8787. if (val)
  8788. {
  8789. if (typedValue.mKind == BfTypedValueKind_SplatHead_NeedsCasting)
  8790. {
  8791. BF_ASSERT(wantType != NULL);
  8792. if (wantType != NULL)
  8793. return mBfIRBuilder->CreateBitCast(val, mBfIRBuilder->MapType(wantType));
  8794. }
  8795. return val;
  8796. }
  8797. BF_FATAL("Splat not found");
  8798. return BfIRValue();
  8799. }
  8800. BfTypedValue BfModule::ExtractValue(BfTypedValue typedValue, BfFieldInstance* fieldInstance, int fieldIdx)
  8801. {
  8802. int useFieldIdx = fieldIdx;
  8803. BfType* fieldType = NULL;
  8804. if (fieldInstance != NULL)
  8805. {
  8806. fieldType = fieldInstance->mResolvedType;
  8807. if (typedValue.mType->IsUnion())
  8808. {
  8809. if (fieldIdx == 1)
  8810. {
  8811. if (typedValue.IsSplat())
  8812. {
  8813. BfTypedValue innerVal = typedValue;
  8814. innerVal.mType = fieldType;
  8815. return innerVal;
  8816. }
  8817. }
  8818. }
  8819. }
  8820. else
  8821. {
  8822. if (typedValue.mType->IsPayloadEnum())
  8823. {
  8824. auto typeInst = typedValue.mType->ToTypeInstance();
  8825. if (fieldIdx == 1)
  8826. fieldType = typeInst->GetUnionInnerType();
  8827. else if (fieldIdx == 2)
  8828. {
  8829. fieldType = typeInst->GetDiscriminatorType(&useFieldIdx);
  8830. }
  8831. }
  8832. else if (typedValue.mType->IsUnion())
  8833. {
  8834. if (fieldIdx == 1)
  8835. {
  8836. fieldType = typedValue.mType->ToTypeInstance()->GetUnionInnerType();
  8837. if (typedValue.IsSplat())
  8838. {
  8839. BfTypedValue innerVal = typedValue;
  8840. innerVal.mType = fieldType;
  8841. return innerVal;
  8842. }
  8843. }
  8844. }
  8845. }
  8846. BF_ASSERT(typedValue.mType->IsStruct());
  8847. if (typedValue.IsSplat())
  8848. {
  8849. if (typedValue.mType->IsPayloadEnum())
  8850. {
  8851. if (fieldIdx == 1)
  8852. {
  8853. // Payload
  8854. auto typeInst = typedValue.mType->ToTypeInstance();
  8855. auto unionInnerType = typeInst->GetUnionInnerType();
  8856. bool isAddr = false;
  8857. BfIRValue irVal = ExtractSplatValue(typedValue, 0, unionInnerType, &isAddr);
  8858. return BfTypedValue(irVal, unionInnerType, BfTypedValueKind_SplatHead);
  8859. }
  8860. if (fieldIdx == 2)
  8861. {
  8862. // Discriminator
  8863. auto typeInst = typedValue.mType->ToTypeInstance();
  8864. auto unionInnerType = typeInst->GetUnionInnerType();
  8865. auto dscrType = typeInst->GetDiscriminatorType();
  8866. int argIdx = typedValue.mValue.mId;
  8867. int componentIdx = 0;
  8868. BfTypeUtils::SplatIterate([&](BfType* checkType) { componentIdx++; }, unionInnerType);
  8869. bool isAddr;
  8870. BfIRValue irVal = ExtractSplatValue(typedValue, componentIdx, dscrType, &isAddr);
  8871. return BfTypedValue(irVal, dscrType, isAddr);
  8872. }
  8873. }
  8874. int componentIdx = 0;
  8875. BfTypedValue retVal;
  8876. BfFieldInstance* wantFieldInstance = fieldInstance;
  8877. std::function<void(BfType*)> checkTypeLambda = [&](BfType* checkType)
  8878. {
  8879. if (checkType->IsStruct())
  8880. {
  8881. auto checkTypeInstance = checkType->ToTypeInstance();
  8882. if ((checkType->IsUnion()) || (checkType->IsEnum()))
  8883. {
  8884. //TODO: Why did we have this removed? It messed up an extraction from a nullable splattable
  8885. fieldType = checkTypeInstance->GetUnionInnerType();
  8886. checkTypeLambda(fieldType);
  8887. if (checkType->IsEnum())
  8888. {
  8889. // Past discriminator...
  8890. componentIdx++;
  8891. }
  8892. return;
  8893. }
  8894. if (checkTypeInstance->mBaseType != NULL)
  8895. checkTypeLambda(checkTypeInstance->mBaseType);
  8896. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  8897. {
  8898. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  8899. if (fieldInstance == wantFieldInstance)
  8900. {
  8901. bool isAddr = false;
  8902. BfIRValue val = ExtractSplatValue(typedValue, componentIdx, fieldInstance->mResolvedType, &isAddr);
  8903. retVal = BfTypedValue(val, fieldInstance->mResolvedType,
  8904. fieldInstance->mResolvedType->IsComposite() ? BfTypedValueKind_SplatHead :
  8905. isAddr ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Value);
  8906. if ((retVal.IsAddr()) && (!fieldInstance->mResolvedType->IsValueType()))
  8907. {
  8908. retVal = LoadValue(retVal);
  8909. }
  8910. break;
  8911. }
  8912. if (fieldInstance->mDataIdx >= 0)
  8913. checkTypeLambda(fieldInstance->GetResolvedType());
  8914. }
  8915. }
  8916. else if (!checkType->IsValuelessType())
  8917. {
  8918. componentIdx++;
  8919. //argIdx++;
  8920. }
  8921. };
  8922. checkTypeLambda(typedValue.mType);
  8923. BF_ASSERT(retVal);
  8924. return retVal;
  8925. }
  8926. if (typedValue.IsAddr())
  8927. {
  8928. BF_ASSERT(fieldType != NULL);
  8929. auto valRef = mBfIRBuilder->CreateInBoundsGEP(typedValue.mValue, 0, useFieldIdx);
  8930. return BfTypedValue(valRef, fieldType, BfTypedValueKind_ReadOnlyAddr);
  8931. }
  8932. else
  8933. {
  8934. BF_ASSERT(fieldType != NULL);
  8935. return BfTypedValue(mBfIRBuilder->CreateExtractValue(typedValue.mValue, useFieldIdx), fieldType, BfTypedValueKind_Value);
  8936. }
  8937. }
  8938. BfIRValue BfModule::ExtractValue(BfTypedValue typedValue, int dataIdx)
  8939. {
  8940. if (typedValue.IsAddr())
  8941. {
  8942. auto addrVal = mBfIRBuilder->CreateInBoundsGEP(typedValue.mValue, 0, dataIdx);
  8943. return mBfIRBuilder->CreateLoad(addrVal);
  8944. }
  8945. return mBfIRBuilder->CreateExtractValue(typedValue.mValue, dataIdx);
  8946. }
  8947. BfIRValue BfModule::CreateIndexedValue(BfType* elementType, BfIRValue value, BfIRValue indexValue, bool isElementIndex)
  8948. {
  8949. if (elementType->IsSizeAligned())
  8950. {
  8951. if (isElementIndex)
  8952. return mBfIRBuilder->CreateInBoundsGEP(value, GetConstValue(0), indexValue);
  8953. else
  8954. return mBfIRBuilder->CreateInBoundsGEP(value, indexValue);
  8955. }
  8956. auto ptrType = CreatePointerType(elementType);
  8957. auto ofsVal = mBfIRBuilder->CreateNumericCast(indexValue, true, BfTypeCode_IntPtr);
  8958. auto ofsScaledVal = mBfIRBuilder->CreateMul(ofsVal, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, elementType->GetStride()));
  8959. auto intVal = mBfIRBuilder->CreatePtrToInt(value, BfTypeCode_IntPtr);
  8960. auto newIntVal = mBfIRBuilder->CreateAdd(intVal, ofsScaledVal);
  8961. return mBfIRBuilder->CreateIntToPtr(newIntVal, mBfIRBuilder->MapType(ptrType));
  8962. }
  8963. BfIRValue BfModule::CreateIndexedValue(BfType* elementType, BfIRValue value, int indexValue, bool isElementIndex)
  8964. {
  8965. if (elementType->IsSizeAligned())
  8966. {
  8967. if (isElementIndex)
  8968. return mBfIRBuilder->CreateInBoundsGEP(value, 0, indexValue);
  8969. else
  8970. return mBfIRBuilder->CreateInBoundsGEP(value, indexValue);
  8971. }
  8972. return CreateIndexedValue(elementType, value, GetConstValue(indexValue), isElementIndex);
  8973. }
  8974. bool BfModule::CheckModifyValue(BfTypedValue& typedValue, BfAstNode* refNode, const char* modifyType)
  8975. {
  8976. if (modifyType == NULL)
  8977. modifyType = "modify";
  8978. if (typedValue.mType->IsVar())
  8979. return true;
  8980. if (typedValue.IsReadOnly())
  8981. {
  8982. Fail(StrFormat("Cannot %s read-only variable", modifyType), refNode);
  8983. return false;
  8984. }
  8985. if ((!typedValue.IsAddr()) && (!typedValue.mType->IsValuelessType()))
  8986. {
  8987. Fail(StrFormat("Cannot %s value", modifyType), refNode);
  8988. return false;
  8989. }
  8990. if (typedValue.mKind == BfTypedValueKind_TempAddr)
  8991. {
  8992. Fail(StrFormat("Cannot %s value", modifyType), refNode);
  8993. return false;
  8994. }
  8995. return true;
  8996. }
  8997. bool BfModule::CompareMethodSignatures(BfMethodInstance* methodA, BfMethodInstance* methodB)
  8998. {
  8999. if (methodA->mMethodDef->mIsLocalMethod)
  9000. {
  9001. int sepPosA = (int)BF_MIN(methodA->mMethodDef->mName.IndexOf('@'), methodA->mMethodDef->mName.length());
  9002. int sepPosB = (int)BF_MIN(methodB->mMethodDef->mName.IndexOf('@'), methodB->mMethodDef->mName.length());
  9003. if (sepPosA != sepPosB)
  9004. return false;
  9005. if (strncmp(methodA->mMethodDef->mName.c_str(), methodB->mMethodDef->mName.c_str(), sepPosA) != 0)
  9006. return false;
  9007. }
  9008. else if (methodA->mMethodDef->mName != methodB->mMethodDef->mName)
  9009. return false;
  9010. if (methodA->mMethodDef->mCheckedKind != methodB->mMethodDef->mCheckedKind)
  9011. return false;
  9012. if (methodA->mMethodDef->mMethodType == BfMethodType_Ctor)
  9013. {
  9014. if (methodA->mMethodDef->mIsStatic != methodB->mMethodDef->mIsStatic)
  9015. return false;
  9016. }
  9017. if (methodA->mMethodDef->mMethodType == BfMethodType_Operator)
  9018. {
  9019. if (methodB->mMethodDef->mMethodType != BfMethodType_Operator)
  9020. return false;
  9021. auto operatorA = (BfOperatorDef*)methodA->mMethodDef;
  9022. auto operatorB = (BfOperatorDef*)methodB->mMethodDef;
  9023. if (operatorA->mOperatorDeclaration->mBinOp != operatorB->mOperatorDeclaration->mBinOp)
  9024. return false;
  9025. if (operatorA->mOperatorDeclaration->mUnaryOp != operatorB->mOperatorDeclaration->mUnaryOp)
  9026. return false;
  9027. if (operatorA->mOperatorDeclaration->mIsConvOperator)
  9028. {
  9029. if (methodA->mReturnType != methodB->mReturnType)
  9030. return false;
  9031. }
  9032. }
  9033. int implicitParamCountA = methodA->GetImplicitParamCount();
  9034. int implicitParamCountB = methodB->GetImplicitParamCount();
  9035. if (methodA->GetParamCount() - implicitParamCountA != methodB->GetParamCount() - implicitParamCountB)
  9036. return false;
  9037. if (methodA->mHadGenericDelegateParams != methodB->mHadGenericDelegateParams)
  9038. return false;
  9039. for (int paramIdx = 0; paramIdx < (int)methodA->GetParamCount() - implicitParamCountA; paramIdx++)
  9040. {
  9041. if ((methodA->GetParamType(paramIdx + implicitParamCountA) != methodB->GetParamType(paramIdx + implicitParamCountB)) ||
  9042. (methodA->GetParamKind(paramIdx + implicitParamCountA) != methodB->GetParamKind(paramIdx + implicitParamCountB)))
  9043. return false;
  9044. }
  9045. // Compare generic params. Generic params are part of the method signature here
  9046. if (methodA->GetNumGenericParams() != methodB->GetNumGenericParams())
  9047. return false;
  9048. for (int genericParamIdx = 0; genericParamIdx < (int)methodA->GetNumGenericParams(); genericParamIdx++)
  9049. {
  9050. auto genericParamA = methodA->mMethodInfoEx->mGenericParams[genericParamIdx];
  9051. auto genericParamB = methodB->mMethodInfoEx->mGenericParams[genericParamIdx];
  9052. if (genericParamA->mGenericParamFlags != genericParamB->mGenericParamFlags)
  9053. return false;
  9054. if (genericParamA->mTypeConstraint != genericParamB->mTypeConstraint)
  9055. return false;
  9056. if (genericParamA->mInterfaceConstraints.size() != genericParamB->mInterfaceConstraints.size())
  9057. return false;
  9058. for (int interfaceIdx = 0; interfaceIdx < (int)genericParamA->mInterfaceConstraints.size(); interfaceIdx++)
  9059. if (genericParamA->mInterfaceConstraints[interfaceIdx] != genericParamB->mInterfaceConstraints[interfaceIdx])
  9060. return false;
  9061. }
  9062. return true;
  9063. }
  9064. bool BfModule::IsCompatibleInterfaceMethod(BfMethodInstance* iMethodInst, BfMethodInstance* methodInstance)
  9065. {
  9066. if (iMethodInst->mMethodDef->mName != methodInstance->mMethodDef->mName)
  9067. return false;
  9068. if (iMethodInst->mMethodDef->mIsOperator != methodInstance->mMethodDef->mIsOperator)
  9069. return false;
  9070. if (iMethodInst->mMethodDef->mIsOperator)
  9071. {
  9072. auto iOperatorDef = (BfOperatorDef*)iMethodInst->mMethodDef;
  9073. auto operatorDef = (BfOperatorDef*)methodInstance->mMethodDef;
  9074. if (iOperatorDef->mOperatorDeclaration->mUnaryOp != operatorDef->mOperatorDeclaration->mUnaryOp)
  9075. return false;
  9076. if (iOperatorDef->mOperatorDeclaration->mBinOp != operatorDef->mOperatorDeclaration->mBinOp)
  9077. return false;
  9078. }
  9079. if (iMethodInst->GetParamCount() != methodInstance->GetParamCount())
  9080. return false;
  9081. for (int paramIdx = 0; paramIdx < (int)iMethodInst->GetParamCount(); paramIdx++)
  9082. {
  9083. if (iMethodInst->GetParamKind(paramIdx) != methodInstance->GetParamKind(paramIdx))
  9084. return false;
  9085. BfType* iParamType = iMethodInst->GetParamType(paramIdx);
  9086. BfType* methodParamType = methodInstance->GetParamType(paramIdx);
  9087. if (iParamType->IsSelf())
  9088. {
  9089. if (methodParamType != methodInstance->GetOwner())
  9090. return false;
  9091. }
  9092. else if (!iParamType->IsGenericParam())
  9093. {
  9094. if (methodParamType != iParamType)
  9095. return false;
  9096. }
  9097. else
  9098. {
  9099. if (!methodParamType->IsGenericParam())
  9100. return false;
  9101. auto genericParamType = (BfGenericParamType*)methodParamType;
  9102. if (genericParamType->mGenericParamKind == BfGenericParamKind_Type)
  9103. return false;
  9104. auto genericParam = methodInstance->mMethodInfoEx->mGenericParams[genericParamType->mGenericParamIdx];
  9105. bool hadInterface = false;
  9106. for (auto interfaceConstraint : genericParam->mInterfaceConstraints)
  9107. if (interfaceConstraint == iParamType)
  9108. hadInterface = true;
  9109. if (!hadInterface)
  9110. return false;
  9111. }
  9112. }
  9113. return true;
  9114. }
  9115. void BfModule::AddMethodReference(const BfMethodRef& methodRef, BfGetMethodInstanceFlags flags)
  9116. {
  9117. BfMethodInstance* methodInstance = methodRef;
  9118. if ((mCurTypeInstance != NULL) && (!mCompiler->IsAutocomplete()))
  9119. {
  9120. auto methodInstanceGroup = methodInstance->mMethodInstanceGroup;
  9121. if ((methodInstance->IsSpecializedGenericMethod()) || (methodInstanceGroup->mOnDemandKind != BfMethodOnDemandKind_AlwaysInclude))
  9122. {
  9123. BF_ASSERT(!methodRef.mTypeInstance->IsFunction());
  9124. BfMethodRef methodRef = methodInstance;
  9125. BfSpecializedMethodRefInfo* specializedMethodRefInfo = NULL;
  9126. bool isNew = mCurTypeInstance->mSpecializedMethodReferences.TryAdd(methodRef, NULL, &specializedMethodRefInfo);
  9127. if (((flags & BfGetMethodInstanceFlag_Unreified) == 0) &&
  9128. ((flags & BfGetMethodInstanceFlag_NoForceReification) == 0) &&
  9129. (mIsReified))
  9130. {
  9131. specializedMethodRefInfo->mHasReifiedRef = true;
  9132. }
  9133. }
  9134. }
  9135. }
  9136. BfModuleMethodInstance BfModule::ReferenceExternalMethodInstance(BfMethodInstance* methodInstance, BfGetMethodInstanceFlags flags)
  9137. {
  9138. if ((flags & BfGetMethodInstanceFlag_ResultNotUsed) != 0)
  9139. return BfModuleMethodInstance(methodInstance, BfIRValue());
  9140. if (mBfIRBuilder == NULL)
  9141. return BfModuleMethodInstance(methodInstance, BfIRValue());
  9142. if (methodInstance->GetOwner()->IsFunction())
  9143. {
  9144. // No actual ref needed- not an actual generated function
  9145. return BfModuleMethodInstance(methodInstance, BfIRValue());
  9146. }
  9147. bool isGenFunction = methodInstance->mMethodInstanceGroup->mMethodIdx < 0;
  9148. if (!isGenFunction)
  9149. AddMethodReference(methodInstance, flags);
  9150. if (mBfIRBuilder->mIgnoreWrites)
  9151. return BfModuleMethodInstance(methodInstance, mBfIRBuilder->GetFakeVal());
  9152. if (mCompiler->IsSkippingExtraResolveChecks())
  9153. return BfModuleMethodInstance(methodInstance, BfIRFunction());
  9154. if (methodInstance->mMethodDef->mMethodType == BfMethodType_Mixin)
  9155. {
  9156. return BfModuleMethodInstance(methodInstance, BfIRFunction());
  9157. }
  9158. bool isInlined = (methodInstance->mAlwaysInline) || ((flags & BfGetMethodInstanceFlag_ForceInline) != 0);
  9159. BfMethodRef methodRef = methodInstance;
  9160. if (isInlined)
  9161. methodRef.mMethodRefFlags = (BfMethodRefFlags)(methodRef.mMethodRefFlags | BfMethodRefFlag_AlwaysInclude);
  9162. else
  9163. methodRef.mMethodRefFlags = BfMethodRefFlag_None;
  9164. if (!isGenFunction)
  9165. {
  9166. BfIRValue* irFuncPtr = NULL;
  9167. if (mFuncReferences.TryGetValue(methodRef, &irFuncPtr))
  9168. return BfModuleMethodInstance(methodInstance, *irFuncPtr);
  9169. }
  9170. if (mAwaitingInitFinish)
  9171. FinishInit();
  9172. BfIRValue func = CreateFunctionFrom(methodInstance, isGenFunction, isInlined);
  9173. if (!isGenFunction)
  9174. mFuncReferences[methodRef] = func;
  9175. BfLogSysM("Adding func reference. Module:%p MethodInst:%p NewLLVMFunc:%d OldLLVMFunc:%d\n", this, methodInstance, func.mId, methodInstance->mIRFunction.mId);
  9176. if ((isInlined) && (!mIsScratchModule))
  9177. {
  9178. // We can't just add a dependency to mCurTypeInstance because we may have nested inlined functions, and
  9179. // mCurTypeInstance will just reflect the owner of the method currently being inlined, not the top-level
  9180. // type instance
  9181. // Be smarter about this if we ever insert a lot of type instances into a single module - track in a field
  9182. BF_ASSERT(mOwnedTypeInstances.size() <= 1);
  9183. for (auto ownedTypeInst : mOwnedTypeInstances)
  9184. AddDependency(methodInstance->GetOwner(), ownedTypeInst, BfDependencyMap::DependencyFlag_InlinedCall);
  9185. if ((!mCompiler->mIsResolveOnly) && (mIsReified) && (!methodInstance->mIsUnspecialized))
  9186. {
  9187. mIncompleteMethodCount++;
  9188. BfInlineMethodRequest* inlineMethodRequest = mContext->mInlineMethodWorkList.Alloc();
  9189. inlineMethodRequest->mType = methodInstance->GetOwner();
  9190. inlineMethodRequest->mFromModule = this;
  9191. inlineMethodRequest->mFunc = func;
  9192. inlineMethodRequest->mFromModuleRevision = mRevision;
  9193. inlineMethodRequest->mMethodInstance = methodInstance;
  9194. BF_ASSERT(mIsModuleMutable);
  9195. BfLogSysM("mInlineMethodWorkList %p for method %p in module %p in ReferenceExternalMethodInstance\n", inlineMethodRequest, methodInstance, this);
  9196. }
  9197. }
  9198. return BfModuleMethodInstance(methodInstance, func);
  9199. }
  9200. BfModule* BfModule::GetOrCreateMethodModule(BfMethodInstance* methodInstance)
  9201. {
  9202. BfTypeInstance* typeInst = methodInstance->mMethodInstanceGroup->mOwner;
  9203. if (mBfIRBuilder == NULL)
  9204. {
  9205. // To allow for custom attribute data
  9206. PrepareForIRWriting(typeInst);
  9207. }
  9208. BfModule* declareModule = this;
  9209. // Get to the optionless branch head -- but this could still be a specialized method module, not the true root
  9210. while ((declareModule->mParentModule != NULL) && (!declareModule->mIsSpecializedMethodModuleRoot))
  9211. declareModule = declareModule->mParentModule;
  9212. // Check for attributes
  9213. if (typeInst == mContext->mBfObjectType)
  9214. {
  9215. auto methodDecl = methodInstance->mMethodDef->GetMethodDeclaration();
  9216. if (methodDecl != NULL)
  9217. {
  9218. auto attributesDirective = methodDecl->mAttributes;
  9219. if ((attributesDirective != NULL) && (mCompiler->mResolvePassData != NULL) &&
  9220. (attributesDirective->IsFromParser(mCompiler->mResolvePassData->mParser)) && (mCompiler->mResolvePassData->mSourceClassifier != NULL))
  9221. {
  9222. mCompiler->mResolvePassData->mSourceClassifier->VisitChild(attributesDirective);
  9223. }
  9224. }
  9225. }
  9226. else
  9227. {
  9228. // Only allow attributes on System.Object methods that can be handled inside the DefBuilder
  9229. GetMethodCustomAttributes(methodInstance);
  9230. }
  9231. BF_ASSERT(mModuleOptions == NULL);
  9232. if (methodInstance->GetCustomAttributes() != NULL)
  9233. {
  9234. auto project = typeInst->mTypeDef->mProject;
  9235. BfModuleOptions moduleOptions = declareModule->GetModuleOptions();
  9236. BfModuleOptions wantOptions = moduleOptions;
  9237. auto typeOptions = mSystem->GetTypeOptions(typeInst->mTypeOptionsIdx);
  9238. if (typeOptions != NULL)
  9239. {
  9240. wantOptions.mOptLevel = (BfOptLevel)BfTypeOptions::Apply((int)wantOptions.mOptLevel, (int)typeOptions->mOptimizationLevel);
  9241. wantOptions.mSIMDSetting = (BfSIMDSetting)BfTypeOptions::Apply((int)wantOptions.mSIMDSetting, typeOptions->mSIMDSetting);
  9242. wantOptions.mEmitDebugInfo = (BfSIMDSetting)BfTypeOptions::Apply((int)wantOptions.mEmitDebugInfo, typeOptions->mEmitDebugInfo);
  9243. }
  9244. if (!mCompiler->mAttributeTypeOptionMap.IsEmpty())
  9245. {
  9246. StringT<128> attrName;
  9247. for (auto& customAttrs : methodInstance->GetCustomAttributes()->mAttributes)
  9248. {
  9249. attrName.Clear();
  9250. customAttrs.mType->mTypeDef->mFullName.ToString(attrName);
  9251. Array<int>* arrPtr;
  9252. if (mCompiler->mAttributeTypeOptionMap.TryGetValue(attrName, &arrPtr))
  9253. {
  9254. for (auto optionsIdx : *arrPtr)
  9255. {
  9256. auto& typeOptions = mCompiler->mSystem->mTypeOptions[optionsIdx];
  9257. wantOptions.mOptLevel = (BfOptLevel)BfTypeOptions::Apply((int)wantOptions.mOptLevel, (int)typeOptions.mOptimizationLevel);
  9258. wantOptions.mSIMDSetting = (BfSIMDSetting)BfTypeOptions::Apply((int)wantOptions.mSIMDSetting, typeOptions.mSIMDSetting);
  9259. wantOptions.mEmitDebugInfo = (BfSIMDSetting)BfTypeOptions::Apply((int)wantOptions.mEmitDebugInfo, typeOptions.mEmitDebugInfo);
  9260. }
  9261. }
  9262. }
  9263. }
  9264. if ((HasCompiledOutput()) && (wantOptions != moduleOptions) && (!mIsScratchModule))
  9265. {
  9266. auto lastCheckModule = this;
  9267. auto checkModule = this->mNextAltModule;
  9268. while (checkModule != NULL)
  9269. {
  9270. if (*checkModule->mModuleOptions == wantOptions)
  9271. {
  9272. declareModule = checkModule;
  9273. break;
  9274. }
  9275. lastCheckModule = checkModule;
  9276. checkModule = checkModule->mNextAltModule;
  9277. }
  9278. // Not found?
  9279. if (declareModule == this)
  9280. {
  9281. String specModuleName = mModuleName + "@@";
  9282. if (wantOptions.mOptLevel != moduleOptions.mOptLevel)
  9283. specModuleName += StrFormat("O%d", wantOptions.mOptLevel);
  9284. if (wantOptions.mSIMDSetting != moduleOptions.mSIMDSetting)
  9285. specModuleName += StrFormat("SIMD%d", wantOptions.mSIMDSetting);
  9286. declareModule = new BfModule(mContext, specModuleName);
  9287. declareModule->mProject = project;
  9288. declareModule->mModuleOptions = new BfModuleOptions();
  9289. *declareModule->mModuleOptions = wantOptions;
  9290. declareModule->mParentModule = lastCheckModule;
  9291. declareModule->Init();
  9292. lastCheckModule->mNextAltModule = declareModule;
  9293. }
  9294. }
  9295. }
  9296. declareModule->PrepareForIRWriting(typeInst);
  9297. return declareModule;
  9298. }
  9299. BfModuleMethodInstance BfModule::GetMethodInstance(BfTypeInstance* typeInst, BfMethodDef* methodDef, const BfTypeVector& methodGenericArguments, BfGetMethodInstanceFlags flags, BfTypeInstance* foreignType)
  9300. {
  9301. if (((flags & BfGetMethodInstanceFlag_ForceInline) != 0) && (mCompiler->mIsResolveOnly))
  9302. {
  9303. // Don't bother inlining for resolve-only
  9304. flags = (BfGetMethodInstanceFlags)(flags & ~BfGetMethodInstanceFlag_ForceInline);
  9305. }
  9306. bool processNow = false;
  9307. bool keepInCurrentModule = false;
  9308. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mIsUnspecialized))
  9309. flags = (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_NoForceReification);
  9310. if (!typeInst->IsTypeMemberIncluded(methodDef->mDeclaringType))
  9311. {
  9312. return BfModuleMethodInstance();
  9313. }
  9314. if (methodDef->mIsLocalMethod)
  9315. {
  9316. auto rootMethodState = mCurMethodState->GetRootMethodState();
  9317. BfLocalMethod* localMethod;
  9318. if (rootMethodState->mLocalMethodCache.TryGetValue(methodDef->mName, &localMethod))
  9319. {
  9320. // Handle the def in the correct method state
  9321. return GetLocalMethodInstance(localMethod, methodGenericArguments);
  9322. }
  9323. BF_FATAL("Cannot find local method");
  9324. return BfModuleMethodInstance();
  9325. }
  9326. #ifdef _DEBUG
  9327. for (auto arg : methodGenericArguments)
  9328. BF_ASSERT(!arg->IsVar());
  9329. #endif
  9330. BF_ASSERT(methodDef->mMethodType != BfMethodType_Ignore);
  9331. // We need to do the 'mNeedsMethodProcessing' check because we want to do a proper initial "awaiting reference" population
  9332. // on the methods before we handle an on-demand situation. This also ensures that our type options are set before doing
  9333. // a FinishInit
  9334. if ((typeInst->IsIncomplete()) &&
  9335. (!typeInst->mResolvingVarField) && (!typeInst->mTypeFailed))
  9336. {
  9337. // For autocomplete, we still may not actually generate methods. This shouldn't matter, and on-demand works differently
  9338. // for resolve-only because we don't differentiate between reified/unreified there
  9339. PopulateType(typeInst, BfPopulateType_Full);
  9340. }
  9341. bool tryModuleMethodLookup = false;
  9342. BfModuleMethodInstance moduleMethodInst;
  9343. BfModule* instModule = typeInst->mModule;
  9344. if (keepInCurrentModule)
  9345. {
  9346. // Stay here
  9347. instModule = this;
  9348. }
  9349. if (this == mContext->mUnreifiedModule)
  9350. {
  9351. // Stay in this 'resolve only' module here
  9352. }
  9353. else if (flags & BfGetMethodInstanceFlag_ExplicitResolveOnlyPass)
  9354. {
  9355. BF_ASSERT(this == mContext->mUnreifiedModule);
  9356. }
  9357. else if (flags & BfGetMethodInstanceFlag_ExplicitSpecializedModule)
  9358. {
  9359. BF_ASSERT(instModule == mParentModule);
  9360. }
  9361. else if (instModule != this)
  9362. {
  9363. if ((!mIsReified) && (instModule->mIsReified))
  9364. {
  9365. BF_ASSERT(!mCompiler->mIsResolveOnly);
  9366. // A resolve-only module is specializing a method from a type in a reified module,
  9367. // we need to take care that this doesn't cause anything new to become reified
  9368. return mContext->mUnreifiedModule->GetMethodInstance(typeInst, methodDef, methodGenericArguments, (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_ExplicitResolveOnlyPass), foreignType);
  9369. }
  9370. else
  9371. {
  9372. if ((mIsReified) && (!instModule->mIsReified))
  9373. {
  9374. if (!instModule->mReifyQueued)
  9375. {
  9376. BF_ASSERT((mCompiler->mCompileState != BfCompiler::CompileState_Unreified) && (mCompiler->mCompileState != BfCompiler::CompileState_VData));
  9377. BfLogSysM("Queueing ReifyModule: %p\n", instModule);
  9378. mContext->mReifyModuleWorkList.Add(instModule);
  9379. instModule->mReifyQueued = true;
  9380. }
  9381. // This ensures that the method will actually be created when it gets reified
  9382. BfMethodSpecializationRequest* specializationRequest = mContext->mMethodSpecializationWorkList.Alloc();
  9383. specializationRequest->mFromModule = typeInst->mModule;
  9384. specializationRequest->mFromModuleRevision = typeInst->mModule->mRevision;
  9385. specializationRequest->mMethodDef = methodDef;
  9386. specializationRequest->mMethodGenericArguments = methodGenericArguments;
  9387. specializationRequest->mType = typeInst;
  9388. }
  9389. auto defFlags = (BfGetMethodInstanceFlags)(flags & ~BfGetMethodInstanceFlag_ForceInline);
  9390. // Not extern
  9391. // Create the instance in the proper module and then create a reference in this one
  9392. moduleMethodInst = instModule->GetMethodInstance(typeInst, methodDef, methodGenericArguments, defFlags, foreignType);
  9393. tryModuleMethodLookup = true;
  9394. if ((mIsReified) && (!moduleMethodInst.mMethodInstance->mIsReified))
  9395. {
  9396. CheckHotMethod(moduleMethodInst.mMethodInstance, "");
  9397. }
  9398. }
  9399. }
  9400. if (tryModuleMethodLookup)
  9401. return ReferenceExternalMethodInstance(moduleMethodInst.mMethodInstance, flags);
  9402. if (((flags & BfGetMethodInstanceFlag_ForceInline) != 0) && (!methodDef->mAlwaysInline))
  9403. {
  9404. auto moduleMethodInstance = GetMethodInstance(typeInst, methodDef, methodGenericArguments, (BfGetMethodInstanceFlags)(flags & ~BfGetMethodInstanceFlag_ForceInline), foreignType);
  9405. if (moduleMethodInstance)
  9406. return ReferenceExternalMethodInstance(moduleMethodInstance.mMethodInstance, flags);
  9407. return moduleMethodInst;
  9408. }
  9409. bool isReified = mIsReified /* || ((flags & BfGetMethodInstanceFlag_ExplicitResolveOnlyPass) != 0)*/;
  9410. bool hadConcreteInterfaceGenericArgument = false;
  9411. if ((flags & BfGetMethodInstanceFlag_Unreified) != 0)
  9412. isReified = false;
  9413. if ((flags & BfGetMethodInstanceFlag_ExplicitResolveOnlyPass) != 0)
  9414. {
  9415. isReified = false;
  9416. }
  9417. BfTypeVector sanitizedMethodGenericArguments;
  9418. Array<BfProject*> projectList;
  9419. bool isUnspecializedPass = (flags & BfGetMethodInstanceFlag_UnspecializedPass) != 0;
  9420. if ((isUnspecializedPass) && (methodDef->mGenericParams.size() == 0))
  9421. isUnspecializedPass = false;
  9422. // 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
  9423. bool isExternalExtensionMethod = false;
  9424. if ((!typeInst->IsUnspecializedType()) && (!isUnspecializedPass))
  9425. {
  9426. if (((flags & BfGetMethodInstanceFlag_ForeignMethodDef) == 0) && (methodDef->mDeclaringType->mProject != typeInst->mTypeDef->mProject))
  9427. {
  9428. auto specProject = methodDef->mDeclaringType->mProject;
  9429. isExternalExtensionMethod = true;
  9430. if (typeInst->IsGenericTypeInstance())
  9431. {
  9432. auto genericTypeInst = (BfGenericTypeInstance*)typeInst;
  9433. if (genericTypeInst->mProjectsReferenced.empty())
  9434. genericTypeInst->GenerateProjectsReferenced();
  9435. if (genericTypeInst->mProjectsReferenced.Contains(specProject))
  9436. {
  9437. // This is a generic type where a generic param is already confined to the project in question
  9438. isExternalExtensionMethod = false;
  9439. }
  9440. }
  9441. if (isExternalExtensionMethod)
  9442. {
  9443. BF_ASSERT(typeInst->mTypeDef->mIsCombinedPartial);
  9444. projectList.push_back(methodDef->mDeclaringType->mProject);
  9445. }
  9446. }
  9447. }
  9448. if ((!isUnspecializedPass) && (methodGenericArguments.size() != 0))
  9449. {
  9450. int typeProjectsCounts = 0;
  9451. if (typeInst->IsGenericTypeInstance())
  9452. {
  9453. auto genericTypeInst = (BfGenericTypeInstance*)typeInst;
  9454. if (genericTypeInst->mProjectsReferenced.empty())
  9455. genericTypeInst->GenerateProjectsReferenced();
  9456. typeProjectsCounts = (int)genericTypeInst->mProjectsReferenced.size();
  9457. projectList.Insert(0, &genericTypeInst->mProjectsReferenced[0], genericTypeInst->mProjectsReferenced.size());
  9458. }
  9459. else
  9460. {
  9461. typeProjectsCounts = 1;
  9462. projectList.Insert(0, typeInst->mTypeDef->mProject);
  9463. }
  9464. isUnspecializedPass = true;
  9465. for (int genericArgIdx = 0; genericArgIdx < (int) methodGenericArguments.size(); genericArgIdx++)
  9466. {
  9467. auto genericArgType = methodGenericArguments[genericArgIdx];
  9468. //BF_ASSERT(!genericArgType->IsRef());
  9469. if (genericArgType->IsConcreteInterfaceType())
  9470. {
  9471. hadConcreteInterfaceGenericArgument = true;
  9472. auto concreteInterfaceType = (BfConcreteInterfaceType*)genericArgType;
  9473. genericArgType = concreteInterfaceType->mInterface;
  9474. }
  9475. if (genericArgType->IsGenericParam())
  9476. {
  9477. auto genericParam = (BfGenericParamType*) genericArgType;
  9478. if ((genericParam->mGenericParamKind != BfGenericParamKind_Method) || (genericParam->mGenericParamIdx != genericArgIdx))
  9479. isUnspecializedPass = false;
  9480. }
  9481. else
  9482. {
  9483. BfTypeUtils::GetProjectList(genericArgType, &projectList, typeProjectsCounts);
  9484. isUnspecializedPass = false;
  9485. }
  9486. sanitizedMethodGenericArguments.push_back(genericArgType);
  9487. }
  9488. if ((int)projectList.size() > typeProjectsCounts)
  9489. {
  9490. // Just leave the new items
  9491. projectList.RemoveRange(0, typeProjectsCounts);
  9492. std::sort(projectList.begin(), projectList.end(), [](BfProject* lhs, BfProject*rhs)
  9493. {
  9494. return lhs->mName < rhs->mName;
  9495. });
  9496. }
  9497. else
  9498. {
  9499. projectList.Clear();
  9500. }
  9501. }
  9502. const BfTypeVector& lookupMethodGenericArguments = isUnspecializedPass ? BfTypeVector() : sanitizedMethodGenericArguments;
  9503. BfMethodInstanceGroup* methodInstGroup = NULL;
  9504. if ((flags & BfGetMethodInstanceFlag_ForeignMethodDef) != 0)
  9505. {
  9506. BF_ASSERT(!typeInst->IsInterface());
  9507. //for (auto& checkGroup : typeInst->mMethodInstanceGroups)
  9508. for (int methodIdx = (int)typeInst->mTypeDef->mMethods.size(); methodIdx < (int)typeInst->mMethodInstanceGroups.size(); methodIdx++)
  9509. {
  9510. auto& checkGroup = typeInst->mMethodInstanceGroups[methodIdx];
  9511. // if (checkGroup.mDefault == NULL)
  9512. // {
  9513. // // This should only be for when we explicitly add a spot so we can set mOnDemandKind
  9514. // BF_ASSERT(methodIdx == typeInst->mMethodInstanceGroups.size() - 1);
  9515. // methodInstGroup = &checkGroup;
  9516. // break;
  9517. // }
  9518. if ((checkGroup.mDefault != NULL) && (checkGroup.mDefault->mMethodDef == methodDef))
  9519. {
  9520. methodInstGroup = &checkGroup;
  9521. break;
  9522. }
  9523. }
  9524. if (methodInstGroup == NULL)
  9525. {
  9526. // Allocate a new entry
  9527. typeInst->mMethodInstanceGroups.Resize(typeInst->mMethodInstanceGroups.size() + 1);
  9528. methodInstGroup = &typeInst->mMethodInstanceGroups.back();
  9529. methodInstGroup->mMethodIdx = (int)typeInst->mMethodInstanceGroups.size() - 1;
  9530. methodInstGroup->mOwner = typeInst;
  9531. // if (methodInstGroup->mOnDemandKind == BfMethodOnDemandKind_NotSet)
  9532. // methodInstGroup->mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  9533. if (mCompiler->mOptions.mCompileOnDemandKind == BfCompileOnDemandKind_AlwaysInclude)
  9534. methodInstGroup->mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  9535. else
  9536. methodInstGroup->mOnDemandKind = BfMethodOnDemandKind_Decl_AwaitingDecl;
  9537. }
  9538. }
  9539. else
  9540. {
  9541. methodInstGroup = &typeInst->mMethodInstanceGroups[methodDef->mIdx];
  9542. }
  9543. if (methodInstGroup->mOnDemandKind == BfMethodOnDemandKind_NotSet)
  9544. {
  9545. BfLogSysM("Forcing BfMethodOnDemandKind_NotSet to BfMethodOnDemandKind_AlwaysInclude for Method:%s in Type:%p\n", methodDef->mName.c_str(), typeInst);
  9546. methodInstGroup->mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  9547. }
  9548. BfIRFunction prevIRFunc;
  9549. bool doingRedeclare = false;
  9550. BfMethodInstance* methodInstance = NULL;
  9551. auto _SetReified = [&]()
  9552. {
  9553. methodInstance->mIsReified = true;
  9554. };
  9555. if (lookupMethodGenericArguments.size() == 0)
  9556. {
  9557. methodInstance = methodInstGroup->mDefault;
  9558. if ((methodInstance != NULL) && (isReified) && (!methodInstance->mIsReified))
  9559. {
  9560. MarkDerivedDirty(typeInst);
  9561. if (mIsScratchModule)
  9562. {
  9563. BfLogSysM("Marking scratch module method instance as reified: %p\n", methodInstance);
  9564. _SetReified();
  9565. CheckHotMethod(methodInstance, "");
  9566. }
  9567. else if ((flags & BfGetMethodInstanceFlag_NoForceReification) != 0)
  9568. {
  9569. // We don't need to force reification if we're in an unspecialized generic- we can wait for
  9570. // the specializations to handle that for us
  9571. return BfModuleMethodInstance(methodInstance);
  9572. }
  9573. else if (methodInstGroup->mOnDemandKind == BfMethodOnDemandKind_Referenced)
  9574. {
  9575. if (methodDef->mIsAbstract)
  9576. {
  9577. BfLogSysM("Reifying abstract unreified method instance: %p IRFunction:%d\n", methodInstance, methodInstance->mIRFunction.mId);
  9578. _SetReified();
  9579. }
  9580. else
  9581. {
  9582. BfLogSysM("Re-declaring processed but unreified method instance: %p IRFunction:%d\n", methodInstance, methodInstance->mIRFunction.mId);
  9583. methodInstGroup->mOnDemandKind = BfMethodOnDemandKind_NoDecl_AwaitingReference;
  9584. methodInstance->UndoDeclaration(!methodInstance->mIRFunction.IsFake());
  9585. doingRedeclare = true;
  9586. mOnDemandMethodCount++;
  9587. }
  9588. }
  9589. else
  9590. {
  9591. BfLogSysM("Marking unprocessed method instance as reified: %p\n", methodInstance);
  9592. // We haven't processed it yet
  9593. _SetReified();
  9594. CheckHotMethod(methodInstance, "");
  9595. if (methodInstance->mDeclModule == this)
  9596. {
  9597. if (methodInstance->mMethodProcessRequest != NULL)
  9598. {
  9599. // Disconnect method process request
  9600. BF_ASSERT(methodInstance->mMethodProcessRequest->mFromModule == this);
  9601. }
  9602. }
  9603. else
  9604. {
  9605. if (methodInstance->mMethodProcessRequest != NULL)
  9606. {
  9607. // Disconnect method process request
  9608. BF_ASSERT(methodInstance->mMethodProcessRequest->mFromModule == mContext->mUnreifiedModule);
  9609. methodInstance->mMethodProcessRequest->mMethodInstance = NULL;
  9610. methodInstance->mMethodProcessRequest = NULL;
  9611. }
  9612. if (methodInstance->mDeclModule == mContext->mUnreifiedModule)
  9613. {
  9614. // Add new request in proper module
  9615. methodInstance->mDeclModule = this;
  9616. }
  9617. else
  9618. {
  9619. if (methodInstance->mDeclModule == NULL)
  9620. {
  9621. //
  9622. }
  9623. else if (methodInstance->mDeclModule != this)
  9624. {
  9625. // Is from specialized module?
  9626. BF_ASSERT(methodInstance->mDeclModule->mParentModule == this);
  9627. }
  9628. }
  9629. if ((!methodInstance->mIRFunction) || (methodInstance->mIRFunction.IsFake()))
  9630. {
  9631. methodInstance->mIRFunction = BfIRFunction();
  9632. if (!mIsModuleMutable)
  9633. StartExtension();
  9634. if ((!mBfIRBuilder->mIgnoreWrites) && (methodInstance->mDeclModule != NULL))
  9635. {
  9636. StringT<128> mangledName;
  9637. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), methodInstance);
  9638. bool isIntrinsic = false;
  9639. SetupIRFunction(methodInstance, mangledName, false, &isIntrinsic);
  9640. BfLogSysM("Creating new IRFunction %d\n", methodInstance->mIRFunction.mId);
  9641. }
  9642. }
  9643. AddMethodToWorkList(methodInstance);
  9644. }
  9645. }
  9646. }
  9647. }
  9648. else
  9649. {
  9650. BF_ASSERT(lookupMethodGenericArguments.size() != 0);
  9651. if (methodInstGroup->mMethodSpecializationMap == NULL)
  9652. methodInstGroup->mMethodSpecializationMap = new BfMethodInstanceGroup::MapType();
  9653. BfMethodInstance** methodInstancePtr = NULL;
  9654. if (methodInstGroup->mMethodSpecializationMap->TryGetValue(lookupMethodGenericArguments, &methodInstancePtr))
  9655. {
  9656. methodInstance = *methodInstancePtr;
  9657. if ((isReified) && (!methodInstance->mIsReified))
  9658. {
  9659. MarkDerivedDirty(typeInst);
  9660. if (methodInstance->mHasBeenProcessed)
  9661. {
  9662. BfLogSysM("Deleting processed but unreified specialized method instance %p\n", methodInstance);
  9663. delete methodInstance;
  9664. methodInstGroup->mMethodSpecializationMap->Remove(lookupMethodGenericArguments);
  9665. methodInstance = NULL;
  9666. }
  9667. else if ((!methodInstance->mIRFunction) || (methodInstance->mIRFunction.IsFake()))
  9668. {
  9669. BfLogSysM("Deleting declared but uncreated specialized method instance %p\n", methodInstance);
  9670. delete methodInstance;
  9671. methodInstGroup->mMethodSpecializationMap->Remove(lookupMethodGenericArguments);
  9672. methodInstance = NULL;
  9673. }
  9674. else
  9675. {
  9676. BfLogSysM("Reifying declared but unreified method instance %p\n", methodInstance);
  9677. // We haven't processed it yet
  9678. _SetReified();
  9679. CheckHotMethod(methodInstance, "");
  9680. }
  9681. }
  9682. }
  9683. }
  9684. if ((methodInstance != NULL) && (!doingRedeclare))
  9685. {
  9686. if (methodInstance->mMethodInstanceGroup->mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingReference)
  9687. {
  9688. /*if ((!mCompiler->mIsResolveOnly) && (!isReified))
  9689. BF_ASSERT(!methodInstance->mIsReified);*/
  9690. if (methodInstance->mIsReified != isReified)
  9691. BfLogSysM("GetMethodInstance %p Decl_AwaitingReference setting reified to %d\n", methodInstance, isReified);
  9692. if ((!isReified) &&
  9693. ((methodInstance->mDeclModule == NULL) || (!methodInstance->mDeclModule->mIsModuleMutable)))
  9694. {
  9695. methodInstance->mDeclModule = mContext->mUnreifiedModule;
  9696. methodInstance->mIRFunction = BfIRFunction();
  9697. }
  9698. methodInstance->mIsReified = isReified;
  9699. if ((methodInstance->mHotMethod != NULL) && (!mCompiler->IsHotCompile()) && (isReified))
  9700. {
  9701. methodInstance->mHotMethod->mFlags = (BfHotDepDataFlags)(methodInstance->mHotMethod->mFlags | BfHotDepDataFlag_IsOriginalBuild);
  9702. }
  9703. if (!methodInstance->mMethodDef->mIsAbstract)
  9704. {
  9705. AddMethodToWorkList(methodInstance);
  9706. }
  9707. else
  9708. {
  9709. methodInstance->mMethodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_Referenced;
  9710. }
  9711. }
  9712. if (mExtensionCount > 0)
  9713. {
  9714. if ((mIsModuleMutable) && (!methodInstance->mIRFunction) &&
  9715. ((projectList.IsEmpty() || ((flags & BfGetMethodInstanceFlag_ExplicitSpecializedModule) != 0))))
  9716. {
  9717. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, false);
  9718. if (mAwaitingInitFinish)
  9719. FinishInit();
  9720. // We need to refer to a function that was defined in a prior module
  9721. bool isInlined = (methodInstance->mAlwaysInline) || ((flags & BfGetMethodInstanceFlag_ForceInline) != 0);
  9722. methodInstance->mIRFunction = CreateFunctionFrom(methodInstance, false, isInlined);
  9723. BF_ASSERT((methodInstance->mDeclModule == this) || (methodInstance->mDeclModule == mContext->mUnreifiedModule) || (methodInstance->mDeclModule == NULL));
  9724. methodInstance->mDeclModule = this;
  9725. // Add this inlined def to ourselves
  9726. if ((methodInstance->mAlwaysInline) && (HasCompiledOutput()) && (!methodInstance->mIsUnspecialized))
  9727. {
  9728. mIncompleteMethodCount++;
  9729. BfInlineMethodRequest* inlineMethodRequest = mContext->mInlineMethodWorkList.Alloc();
  9730. inlineMethodRequest->mType = typeInst;
  9731. inlineMethodRequest->mFromModule = this;
  9732. inlineMethodRequest->mFunc = methodInstance->mIRFunction;
  9733. inlineMethodRequest->mFromModuleRevision = mRevision;
  9734. inlineMethodRequest->mMethodInstance = methodInstance;
  9735. BfLogSysM("mInlineMethodWorkList %p for method %p in module %p in GetMethodInstance\n", inlineMethodRequest, methodInstance, this);
  9736. BF_ASSERT(mIsModuleMutable);
  9737. }
  9738. }
  9739. }
  9740. if (mCompiler->IsSkippingExtraResolveChecks())
  9741. return BfModuleMethodInstance(methodInstance, BfIRFunction());
  9742. else
  9743. {
  9744. if (methodInstance->mDeclModule != this)
  9745. return ReferenceExternalMethodInstance(methodInstance, flags);
  9746. if ((!methodInstance->mIRFunction) && (mIsModuleMutable) && (!mBfIRBuilder->mIgnoreWrites))
  9747. {
  9748. auto importKind = methodInstance->GetImportCallKind();
  9749. if (importKind != BfImportCallKind_None)
  9750. {
  9751. BfLogSysM("DllImportGlobalVar creating %p\n", methodInstance);
  9752. methodInstance->mIRFunction = mBfIRBuilder->GetFakeVal();
  9753. mFuncReferences[methodInstance] = CreateDllImportGlobalVar(methodInstance, true);;
  9754. }
  9755. }
  9756. return BfModuleMethodInstance(methodInstance);
  9757. }
  9758. }
  9759. if (!doingRedeclare)
  9760. {
  9761. BfModule* specModule = NULL;
  9762. if ((!keepInCurrentModule) && (projectList.size() > 0) && (!isUnspecializedPass) && (HasCompiledOutput()) && (!mIsScratchModule))
  9763. {
  9764. specModule = GetSpecializedMethodModule(projectList);
  9765. }
  9766. if ((specModule != NULL) && (specModule != this))
  9767. {
  9768. auto specMethodInstance = specModule->GetMethodInstance(typeInst, methodDef, methodGenericArguments, (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_ExplicitSpecializedModule));
  9769. if (mAwaitingInitFinish)
  9770. return BfModuleMethodInstance(specMethodInstance.mMethodInstance, BfIRFunction());
  9771. return ReferenceExternalMethodInstance(specMethodInstance.mMethodInstance, flags);
  9772. }
  9773. if ((!isUnspecializedPass) && (methodGenericArguments.size() != 0) && (methodInstGroup->mDefault == NULL))
  9774. {
  9775. // We are attempting to specialize but we don't have the unspecialized method yet. Generate that first.
  9776. GetMethodInstance(typeInst, methodDef, BfTypeVector(), BfGetMethodInstanceFlag_UnspecializedPass);
  9777. }
  9778. }
  9779. if (methodInstance == NULL)
  9780. {
  9781. if (lookupMethodGenericArguments.size() == 0)
  9782. {
  9783. BF_ASSERT(methodInstGroup->mDefault == NULL);
  9784. methodInstance = new BfMethodInstance();
  9785. methodInstGroup->mDefault = methodInstance;
  9786. BfLogSysM("Created Default MethodInst: %p TypeInst: %p Group: %p\n", methodInstance, typeInst, methodInstGroup);
  9787. }
  9788. else
  9789. {
  9790. BfMethodInstance** methodInstancePtr = NULL;
  9791. bool added = methodInstGroup->mMethodSpecializationMap->TryAdd(lookupMethodGenericArguments, NULL, &methodInstancePtr);
  9792. BF_ASSERT(added);
  9793. methodInstance = new BfMethodInstance();
  9794. *methodInstancePtr = methodInstance;
  9795. BfLogSysM("Created Specialized MethodInst: %p TypeInst: %p\n", methodInstance, typeInst);
  9796. }
  9797. if ((prevIRFunc) && (!prevIRFunc.IsFake()))
  9798. methodInstance->mIRFunction = prevIRFunc; // Take it over
  9799. }
  9800. /*// 24 bits for typeid, 20 for method id, 20 for specialization index
  9801. methodInstance->mMethodId = ((int64)typeInst->mTypeId) + ((int64)methodInstGroup->mMethodIdx << 24);
  9802. if (methodInstGroup->mMethodSpecializationMap != NULL)
  9803. methodInstance->mMethodId += ((int64)methodInstGroup->mMethodSpecializationMap->size() << 44);*/
  9804. methodInstance->mMethodDef = methodDef;
  9805. methodInstance->mAlwaysInline = methodDef->mAlwaysInline;
  9806. methodInstance->mMethodInstanceGroup = methodInstGroup;
  9807. methodInstance->mIsReified = isReified;
  9808. SetupMethodIdHash(methodInstance);
  9809. if (hadConcreteInterfaceGenericArgument)
  9810. methodInstance->mIgnoreBody = true;
  9811. if ((flags & BfGetMethodInstanceFlag_ForeignMethodDef) != 0)
  9812. {
  9813. methodInstance->mIsForeignMethodDef = true;
  9814. BF_ASSERT(foreignType != NULL);
  9815. methodInstance->GetMethodInfoEx()->mForeignType = foreignType;
  9816. }
  9817. if ((typeInst->mTypeDef == mCompiler->mValueTypeTypeDef) && (methodDef->mName == BF_METHODNAME_EQUALS))
  9818. {
  9819. if (!lookupMethodGenericArguments.empty())
  9820. {
  9821. auto compareType = lookupMethodGenericArguments[0];
  9822. PopulateType(compareType, BfPopulateType_Data);
  9823. if (compareType->IsSplattable())
  9824. methodInstance->mAlwaysInline = true;
  9825. }
  9826. }
  9827. if (methodDef->mDeclaringType->mTypeDeclaration != typeInst->mTypeDef->mTypeDeclaration)
  9828. {
  9829. // With extensions we can have multiple definitions of the same method
  9830. //methodInstance->mMangleWithIdx = true;
  9831. }
  9832. BfModule* declareModule = GetOrCreateMethodModule(methodInstance);
  9833. BF_ASSERT(typeInst == methodInstance->GetOwner());
  9834. auto methodDeclaration = methodDef->GetMethodDeclaration();
  9835. if (isUnspecializedPass)
  9836. {
  9837. for (int genericParamIdx = 0; genericParamIdx < (int) methodDef->mGenericParams.size(); genericParamIdx++)
  9838. {
  9839. auto genericParamType = GetGenericParamType(BfGenericParamKind_Method, genericParamIdx);
  9840. methodInstance->GetMethodInfoEx()->mMethodGenericArguments.Add(genericParamType);
  9841. }
  9842. }
  9843. else if ((methodDeclaration != NULL) && (methodDeclaration->mGenericParams != NULL))
  9844. {
  9845. if (!sanitizedMethodGenericArguments.IsEmpty())
  9846. methodInstance->GetMethodInfoEx()->mMethodGenericArguments = sanitizedMethodGenericArguments;
  9847. if (methodDef->mGenericParams.size() != sanitizedMethodGenericArguments.size())
  9848. {
  9849. Fail("Internal error");
  9850. BF_FATAL("Generic method argument counts mismatch");
  9851. return NULL;
  9852. }
  9853. for (auto genericArg : sanitizedMethodGenericArguments)
  9854. {
  9855. if (genericArg->IsPrimitiveType())
  9856. genericArg = GetWrappedStructType(genericArg);
  9857. AddDependency(genericArg, typeInst, BfDependencyMap::DependencyFlag_MethodGenericArg);
  9858. if (genericArg->IsMethodRef())
  9859. {
  9860. auto methodRefType = (BfMethodRefType*)genericArg;
  9861. //AddDependency(genericArg, typeInst, BfDependencyMap::DependencyFlag_);
  9862. }
  9863. }
  9864. }
  9865. // Generic constraints
  9866. for (int genericParamIdx = 0; genericParamIdx < (int)methodDef->mGenericParams.size(); genericParamIdx++)
  9867. {
  9868. auto genericParamInstance = new BfGenericMethodParamInstance(methodDef, genericParamIdx);
  9869. methodInstance->GetMethodInfoEx()->mGenericParams.push_back(genericParamInstance);
  9870. }
  9871. bool addToWorkList = !processNow;
  9872. if (mCompiler->GetAutoComplete() != NULL)
  9873. {
  9874. if (typeInst->IsSpecializedByAutoCompleteMethod())
  9875. addToWorkList = false;
  9876. }
  9877. BF_ASSERT(declareModule != NULL);
  9878. methodInstance->mDeclModule = declareModule;
  9879. if ((!methodInstance->mIsReified) && (mCompiler->mCompileState != BfCompiler::CompileState_Normal))
  9880. {
  9881. // We can be sure this method won't become reified later. Normally we can "go either way" with an unreified method
  9882. // of a reified module -
  9883. // If we declare it in the reified module then we can switch it to "reified" before actual processing without any extra work,
  9884. // BUT if we don't reify it then we have to remove the body after processing.
  9885. // 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
  9886. // the proper reified module.
  9887. declareModule = mContext->mUnreifiedModule;
  9888. }
  9889. else if ((!declareModule->mIsModuleMutable) && (!mCompiler->mIsResolveOnly))
  9890. {
  9891. BF_ASSERT(!methodInstance->mIsReified);
  9892. declareModule = mContext->mUnreifiedModule;
  9893. }
  9894. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(declareModule->mCurMethodInstance, methodInstance);
  9895. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(declareModule->mCurTypeInstance, typeInst);
  9896. SetAndRestoreValue<BfFilePosition> prevFilePos(declareModule->mCurFilePosition);
  9897. declareModule->DoMethodDeclaration(methodDef->GetMethodDeclaration(), false, addToWorkList);
  9898. if (processNow)
  9899. {
  9900. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, NULL);
  9901. ProcessMethod(methodInstance);
  9902. }
  9903. if (mCompiler->IsSkippingExtraResolveChecks())
  9904. return BfModuleMethodInstance(methodInstance, BfIRFunction());
  9905. return BfModuleMethodInstance(methodInstance);
  9906. }
  9907. BfModuleMethodInstance BfModule::GetMethodInstance(BfMethodInstance* methodInstance, BfGetMethodInstanceFlags flags)
  9908. {
  9909. BF_ASSERT((methodInstance->mMethodInfoEx == NULL) || (methodInstance->mMethodInfoEx->mGenericParams.IsEmpty()));
  9910. if (methodInstance->mIsForeignMethodDef)
  9911. flags = (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_ForeignMethodDef);
  9912. return GetMethodInstance(methodInstance->GetOwner(), methodInstance->mMethodDef, BfTypeVector(), flags);
  9913. }
  9914. BfMethodInstance* BfModule::GetOuterMethodInstance(BfMethodInstance* methodInstance)
  9915. {
  9916. if (!methodInstance->mMethodDef->mIsLocalMethod)
  9917. return NULL;
  9918. auto outerLocal = methodInstance->mMethodInfoEx->mClosureInstanceInfo->mLocalMethod->mOuterLocalMethod;
  9919. if (outerLocal == NULL)
  9920. return NULL;
  9921. BfTypeVector genericArgs;
  9922. for (int i = 0; i < (int)outerLocal->mMethodDef->mGenericParams.size(); i++)
  9923. genericArgs.Add(methodInstance->mMethodInfoEx->mMethodGenericArguments[i]);
  9924. return GetLocalMethodInstance(outerLocal, genericArgs).mMethodInstance;
  9925. }
  9926. void BfModule::SetupMethodIdHash(BfMethodInstance* methodInstance)
  9927. {
  9928. HashContext hashCtx;
  9929. std::function<void(BfMethodInstance*)> _MixinMethodInstance = [&](BfMethodInstance* methodInstance)
  9930. {
  9931. hashCtx.Mixin(methodInstance->GetOwner()->mTypeId);
  9932. hashCtx.Mixin(methodInstance->mMethodDef->mIdx);
  9933. if (methodInstance->GetNumGenericArguments() != 0)
  9934. {
  9935. hashCtx.Mixin((int32)methodInstance->mMethodInfoEx->mMethodGenericArguments.size());
  9936. for (auto methodGenericArg : methodInstance->mMethodInfoEx->mMethodGenericArguments)
  9937. hashCtx.Mixin(methodGenericArg->mTypeId);
  9938. }
  9939. };
  9940. _MixinMethodInstance(methodInstance);
  9941. if (methodInstance->mMethodDef->mIsLocalMethod)
  9942. {
  9943. auto outmostMethodInstance = mCurMethodState->GetRootMethodState()->mMethodInstance;
  9944. BF_ASSERT((outmostMethodInstance->mIdHash != 0) || (outmostMethodInstance->mIsAutocompleteMethod));
  9945. hashCtx.Mixin(outmostMethodInstance->mIdHash);
  9946. }
  9947. methodInstance->mIdHash = (int64)hashCtx.Finish64();
  9948. }
  9949. BfIRValue BfModule::GetInterfaceSlotNum(BfTypeInstance* ifaceType)
  9950. {
  9951. BfIRValue globalValue;
  9952. BfIRValue* globalValuePtr = NULL;
  9953. if (mInterfaceSlotRefs.TryGetValue(ifaceType, &globalValuePtr))
  9954. {
  9955. globalValue = *globalValuePtr;
  9956. }
  9957. if (!globalValue)
  9958. {
  9959. // This is necessary to reify the interface type
  9960. PopulateType(ifaceType);
  9961. StringT<128> slotVarName;
  9962. BfMangler::MangleStaticFieldName(slotVarName, mCompiler->GetMangleKind(), ifaceType, "sBfSlotOfs");
  9963. BfType* intType = GetPrimitiveType(BfTypeCode_Int32);
  9964. BfIRValue value;
  9965. if ((mCompiler->mHotState != NULL) && (ifaceType->mSlotNum >= 0))
  9966. {
  9967. /*// If this interface already existed before this hot compile but we never indirectly called any of its methods
  9968. // then the sBfSlotOfs could have gotten its symbol stripped, so actually define it here.
  9969. int virtSlotIdx = ifaceType->mSlotNum + 1;
  9970. value = GetConstValue32(virtSlotIdx);*/
  9971. mCompiler->mHotState->mSlotDefineTypeIds.Add(ifaceType->mTypeId);
  9972. ifaceType->mDirty = true; // Makes sure we create interface in vdata
  9973. }
  9974. globalValue = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapType(intType), true, BfIRLinkageType_External, value, slotVarName);
  9975. mInterfaceSlotRefs[ifaceType] = globalValue;
  9976. }
  9977. return mBfIRBuilder->CreateLoad(globalValue/*, "slotOfs"*/);
  9978. }
  9979. void BfModule::HadSlotCountDependency()
  9980. {
  9981. if (mCompiler->mIsResolveOnly)
  9982. return;
  9983. BF_ASSERT(!mBfIRBuilder->mIgnoreWrites);
  9984. BF_ASSERT((mUsedSlotCount == BF_MAX(mCompiler->mMaxInterfaceSlots, 0)) || (mUsedSlotCount == -1));
  9985. mUsedSlotCount = BF_MAX(mCompiler->mMaxInterfaceSlots, 0);
  9986. }
  9987. BfTypedValue BfModule::ReferenceStaticField(BfFieldInstance* fieldInstance)
  9988. {
  9989. if (mIsScratchModule)
  9990. {
  9991. // Just fake it for the extern and unspecialized modules
  9992. auto ptrType = CreatePointerType(fieldInstance->GetResolvedType());
  9993. return BfTypedValue(GetDefaultValue(ptrType), fieldInstance->GetResolvedType(), true);
  9994. }
  9995. BfIRValue globalValue;
  9996. auto fieldDef = fieldInstance->GetFieldDef();
  9997. if ((fieldDef->mIsConst) && (!fieldDef->mIsExtern))
  9998. {
  9999. if (fieldInstance->mConstIdx != -1)
  10000. {
  10001. auto constant = fieldInstance->mOwner->mConstHolder->GetConstantById(fieldInstance->mConstIdx);
  10002. return BfTypedValue(ConstantToCurrent(constant, fieldInstance->mOwner->mConstHolder, fieldInstance->GetResolvedType()), fieldInstance->GetResolvedType());
  10003. }
  10004. else
  10005. {
  10006. return GetDefaultTypedValue(fieldInstance->GetResolvedType());
  10007. }
  10008. }
  10009. BfIRValue* globalValuePtr = NULL;
  10010. if (mStaticFieldRefs.TryGetValue(fieldInstance, &globalValuePtr))
  10011. {
  10012. globalValue = *globalValuePtr;
  10013. BF_ASSERT(globalValue);
  10014. }
  10015. else
  10016. {
  10017. StringT<128> staticVarName;
  10018. BfMangler::Mangle(staticVarName, mCompiler->GetMangleKind(), fieldInstance);
  10019. auto typeType = fieldInstance->GetResolvedType();
  10020. if ((fieldDef->mIsExtern) && (fieldDef->mIsConst) && (typeType->IsPointer()))
  10021. {
  10022. typeType = typeType->GetUnderlyingType();
  10023. }
  10024. PopulateType(typeType);
  10025. if ((typeType != NULL) && (!typeType->IsValuelessType()))
  10026. {
  10027. globalValue = mBfIRBuilder->CreateGlobalVariable(
  10028. mBfIRBuilder->MapType(typeType),
  10029. false,
  10030. BfIRLinkageType_External,
  10031. BfIRValue(),
  10032. staticVarName,
  10033. IsThreadLocal(fieldInstance));
  10034. if (!mBfIRBuilder->mIgnoreWrites)
  10035. {
  10036. // Only store this if we actually did the creation
  10037. BF_ASSERT(globalValue);
  10038. mStaticFieldRefs[fieldInstance] = globalValue;
  10039. }
  10040. BfLogSysM("Mod:%p Type:%p ReferenceStaticField %p -> %p\n", this, fieldInstance->mOwner, fieldInstance, globalValue);
  10041. }
  10042. }
  10043. auto type = fieldInstance->GetResolvedType();
  10044. if (type->IsValuelessType())
  10045. return BfTypedValue(globalValue, type);
  10046. return BfTypedValue(globalValue, type, !fieldDef->mIsConst);
  10047. }
  10048. BfTypedValue BfModule::GetThis()
  10049. {
  10050. auto useMethodState = mCurMethodState;
  10051. while ((useMethodState != NULL) && (useMethodState->mClosureState != NULL) && (useMethodState->mClosureState->mCapturing))
  10052. {
  10053. useMethodState = useMethodState->mPrevMethodState;
  10054. }
  10055. if (useMethodState != NULL)
  10056. {
  10057. // Fake a 'this' for var field resolution
  10058. if (useMethodState->mTempKind == BfMethodState::TempKind_NonStatic)
  10059. {
  10060. auto thisType = mCurTypeInstance;
  10061. if (thisType->IsValueType())
  10062. return BfTypedValue(mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapTypeInstPtr(thisType)), thisType, BfTypedValueKind_ThisAddr);
  10063. else
  10064. return BfTypedValue(mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapTypeInst(thisType)), thisType, BfTypedValueKind_ThisValue);
  10065. }
  10066. else if (useMethodState->mTempKind == BfMethodState::TempKind_Static)
  10067. {
  10068. return BfTypedValue();
  10069. }
  10070. }
  10071. else
  10072. {
  10073. //TODO: Do we allow useMethodState to be NULL anymore?
  10074. return BfTypedValue();
  10075. }
  10076. // if (useMethodState->HasNonStaticMixin())
  10077. // {
  10078. // auto checkMethodState = useMethodState;
  10079. // while (checkMethodState != NULL)
  10080. // {
  10081. // for (int localIdx = (int)checkMethodState->mLocals.size() - 1; localIdx >= 0; localIdx--)
  10082. // {
  10083. // auto varDecl = checkMethodState->mLocals[localIdx];
  10084. // if (varDecl->mName == "this")
  10085. // {
  10086. // varDecl->mReadFromId = useMethodState->GetRootMethodState()->mCurAccessId++;
  10087. // if (varDecl->mIsSplat)
  10088. // {
  10089. // return BfTypedValue(varDecl->mValue, varDecl->mResolvedType, BfTypedValueKind_ThisSplatHead);
  10090. // }
  10091. // else if ((varDecl->mResolvedType->IsValueType()) && (varDecl->mAddr))
  10092. // {
  10093. // return BfTypedValue(varDecl->mAddr, varDecl->mResolvedType, BfTypedValueKind_ThisAddr);
  10094. // }
  10095. // return BfTypedValue(varDecl->mValue, varDecl->mResolvedType, varDecl->mResolvedType->IsValueType() ? BfTypedValueKind_ThisAddr : BfTypedValueKind_ThisValue);
  10096. // }
  10097. // }
  10098. //
  10099. // checkMethodState = checkMethodState->mPrevMethodState;
  10100. // }
  10101. // }
  10102. // Check mixin state for 'this'
  10103. {
  10104. auto checkMethodState = useMethodState;
  10105. while (checkMethodState != NULL)
  10106. {
  10107. if (checkMethodState->mMixinState != NULL)
  10108. {
  10109. BfTypedValue thisValue = checkMethodState->mMixinState->mTarget;
  10110. if (thisValue)
  10111. {
  10112. checkMethodState->mMixinState->mLastTargetAccessId = useMethodState->GetRootMethodState()->mCurAccessId++;
  10113. if (!thisValue.mType->IsValueType())
  10114. thisValue = LoadValue(thisValue);
  10115. return thisValue;
  10116. }
  10117. }
  10118. checkMethodState = checkMethodState->mPrevMethodState;
  10119. }
  10120. }
  10121. auto curMethodInstance = mCurMethodInstance;
  10122. if (useMethodState->mMethodInstance != NULL)
  10123. curMethodInstance = useMethodState->mMethodInstance;
  10124. if ((curMethodInstance == NULL) /*|| (!mCurMethodInstance->mIRFunction)*/ || (curMethodInstance->mMethodDef->mIsStatic))
  10125. {
  10126. if ((useMethodState->mClosureState != NULL) && (!useMethodState->mClosureState->mConstLocals.empty()))
  10127. {
  10128. auto& constLocal = useMethodState->mClosureState->mConstLocals[0];
  10129. if (constLocal.mIsThis)
  10130. {
  10131. BF_ASSERT(constLocal.mResolvedType->IsValuelessType());
  10132. return BfTypedValue(mBfIRBuilder->GetFakeVal(), constLocal.mResolvedType);
  10133. }
  10134. }
  10135. return BfTypedValue();
  10136. }
  10137. bool preferValue = !IsTargetingBeefBackend();
  10138. if (useMethodState->mLocals.IsEmpty())
  10139. {
  10140. // 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
  10141. BF_ASSERT(useMethodState->mPrevMethodState != NULL);
  10142. return BfTypedValue();
  10143. }
  10144. auto thisLocal = useMethodState->mLocals[0];
  10145. BF_ASSERT(thisLocal->mIsThis);
  10146. BfIRValue thisValue;
  10147. if ((preferValue) || (!thisLocal->mAddr) /*|| (thisLocal->mIsSplat)*/)
  10148. thisValue = thisLocal->mValue;
  10149. else if ((thisLocal->mIsSplat) || (thisLocal->mIsLowered))
  10150. thisValue = thisLocal->mAddr;
  10151. else
  10152. thisValue = mBfIRBuilder->CreateLoad(thisLocal->mAddr);
  10153. useMethodState->mLocals[0]->mReadFromId = useMethodState->GetRootMethodState()->mCurAccessId++;
  10154. if (useMethodState->mClosureState != NULL)
  10155. {
  10156. auto closureTypeInst = useMethodState->mClosureState->mClosureType;
  10157. if (closureTypeInst != NULL)
  10158. {
  10159. if (closureTypeInst->mFieldInstances.size() > 0)
  10160. {
  10161. auto& field = closureTypeInst->mFieldInstances[0];
  10162. auto fieldDef = field.GetFieldDef();
  10163. if (fieldDef->mName == "__this")
  10164. {
  10165. if (mCurMethodState->mClosureState->mCapturing)
  10166. mCurMethodState->mClosureState->mReferencedOuterClosureMembers.Add(&field);
  10167. // This is a captured 'this'
  10168. BfTypedValue result = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(thisValue, 0, field.mDataIdx), field.mResolvedType, true);
  10169. if (field.mResolvedType->IsRef())
  10170. {
  10171. auto refType = (BfRefType*)field.mResolvedType;
  10172. auto underlyingType = refType->GetUnderlyingType();
  10173. result = BfTypedValue(mBfIRBuilder->CreateLoad(result.mValue), underlyingType, true);
  10174. }
  10175. if (field.mResolvedType->IsObject())
  10176. {
  10177. result = LoadValue(result);
  10178. result.mKind = BfTypedValueKind_ThisValue;
  10179. }
  10180. else
  10181. {
  10182. if (fieldDef->mIsReadOnly)
  10183. result.mKind = BfTypedValueKind_ReadOnlyThisAddr;
  10184. else
  10185. result.mKind = BfTypedValueKind_ThisAddr;
  10186. }
  10187. return result;
  10188. }
  10189. }
  10190. return BfTypedValue();
  10191. }
  10192. if (useMethodState->mClosureState->mCapturing)
  10193. {
  10194. auto thisType = useMethodState->mLocals[0]->mResolvedType;
  10195. if (thisType->IsValueType())
  10196. return BfTypedValue(CreateAlloca(thisType), thisType, BfTypedValueKind_ThisAddr);
  10197. else
  10198. return BfTypedValue(GetDefaultValue(thisType), thisType, BfTypedValueKind_ThisValue);
  10199. }
  10200. }
  10201. auto localDef = useMethodState->mLocals[0];
  10202. auto curMethodOwner = mCurMethodInstance->mMethodInstanceGroup->mOwner;
  10203. if ((curMethodOwner->IsStruct()) || (curMethodOwner->IsTypedPrimitive()))
  10204. {
  10205. if ((localDef->mResolvedType->IsTypedPrimitive()) && (!mCurMethodInstance->mMethodDef->mIsMutating))
  10206. {
  10207. return BfTypedValue(thisValue, useMethodState->mLocals[0]->mResolvedType, BfTypedValueKind_ReadOnlyThisValue);
  10208. }
  10209. if (localDef->mIsSplat)
  10210. {
  10211. return BfTypedValue(thisValue, useMethodState->mLocals[0]->mResolvedType, BfTypedValueKind_ThisSplatHead);
  10212. }
  10213. return BfTypedValue(thisValue, useMethodState->mLocals[0]->mResolvedType, localDef->mIsReadOnly ? BfTypedValueKind_ReadOnlyThisAddr : BfTypedValueKind_ThisAddr);
  10214. }
  10215. return BfTypedValue(thisValue, mCurMethodInstance->mMethodInstanceGroup->mOwner, BfTypedValueKind_ThisValue);
  10216. }
  10217. BfLocalVariable* BfModule::GetThisVariable()
  10218. {
  10219. if (mCurMethodState == NULL)
  10220. return NULL;
  10221. auto methodState = mCurMethodState->GetNonCaptureState();
  10222. if ((methodState->mLocals.size() > 0) && (methodState->mLocals[0]->mIsThis))
  10223. return methodState->mLocals[0];
  10224. return NULL;
  10225. }
  10226. bool BfModule::IsInGeneric()
  10227. {
  10228. return (mCurMethodInstance->GetNumGenericArguments() != 0) || (mCurTypeInstance->IsGenericTypeInstance());
  10229. }
  10230. bool BfModule::IsInSpecializedGeneric()
  10231. {
  10232. if ((mCurMethodInstance == NULL) || (mCurMethodInstance->mIsUnspecialized))
  10233. return false;
  10234. return (mCurMethodInstance->GetNumGenericArguments() != 0) || (mCurTypeInstance->IsGenericTypeInstance());
  10235. }
  10236. bool BfModule::IsInSpecializedSection()
  10237. {
  10238. return IsInSpecializedGeneric() ||
  10239. ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL));
  10240. }
  10241. bool BfModule::IsInUnspecializedGeneric()
  10242. {
  10243. if (mCurMethodInstance != NULL)
  10244. return mCurMethodInstance->mIsUnspecialized;
  10245. return false;
  10246. }
  10247. //////////////////////////////////////////////////////////////////////////
  10248. BfIRValue BfModule::AllocLocalVariable(BfType* type, const StringImpl& name, bool doLifetimeEnd)
  10249. {
  10250. //if ((type->IsValuelessType()) || (type->IsMethodRef()))
  10251. if (type->IsValuelessType())
  10252. return mBfIRBuilder->GetFakeVal();
  10253. auto allocaInst = CreateAlloca(type, doLifetimeEnd, name.c_str());
  10254. if ((!doLifetimeEnd) && (WantsLifetimes()))
  10255. {
  10256. auto lifetimeStart = mBfIRBuilder->CreateLifetimeStart(allocaInst);
  10257. mBfIRBuilder->ClearDebugLocation(lifetimeStart);
  10258. }
  10259. bool initLocalVariables = mCompiler->mOptions.mInitLocalVariables;
  10260. auto typeOptions = GetTypeOptions();
  10261. if (typeOptions != NULL)
  10262. initLocalVariables = BfTypeOptions::Apply(initLocalVariables, typeOptions->mInitLocalVariables);
  10263. // Local variable inits are implicitly handled in the Beef Backend
  10264. if ((initLocalVariables) && (!IsTargetingBeefBackend()))
  10265. {
  10266. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  10267. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRInitBlock);
  10268. auto storeInst = mBfIRBuilder->CreateAlignedStore(GetDefaultValue(type), allocaInst, type->mAlign);
  10269. mBfIRBuilder->ClearDebugLocation(storeInst);
  10270. mBfIRBuilder->SetInsertPoint(prevBlock);
  10271. }
  10272. return allocaInst;
  10273. }
  10274. void BfModule::DoAddLocalVariable(BfLocalVariable* localVar)
  10275. {
  10276. if (localVar->mResolvedType->IsVar())
  10277. {
  10278. BF_ASSERT((mCurMethodInstance->mIsUnspecialized) || (mCurMethodState->mClosureState != NULL) || (mHadVarUsage));
  10279. }
  10280. localVar->mLocalVarIdx = (int)mCurMethodState->mLocals.size();
  10281. mCurMethodState->mLocals.push_back(localVar);
  10282. BfLocalVarEntry* localVarEntryPtr;
  10283. if (!mCurMethodState->mLocalVarSet.TryAdd(BfLocalVarEntry(localVar), &localVarEntryPtr))
  10284. {
  10285. localVar->mShadowedLocal = localVarEntryPtr->mLocalVar;
  10286. localVarEntryPtr->mLocalVar = localVar;
  10287. }
  10288. }
  10289. BfLocalVariable* BfModule::AddLocalVariableDef(BfLocalVariable* localVarDef, bool addDebugInfo, bool doAliasValue, BfIRValue declareBefore, BfIRInitType initType)
  10290. {
  10291. if ((localVarDef->mValue) && (!localVarDef->mAddr) && (IsTargetingBeefBackend()))
  10292. {
  10293. if ((!localVarDef->mValue.IsConst()) && (!localVarDef->mValue.IsArg()) && (!localVarDef->mValue.IsFake()))
  10294. {
  10295. mBfIRBuilder->CreateValueScopeRetain(localVarDef->mValue);
  10296. mCurMethodState->mCurScope->mHadScopeValueRetain = true;
  10297. }
  10298. }
  10299. if ((addDebugInfo) && (mBfIRBuilder->DbgHasInfo()) &&
  10300. ((mCurMethodInstance == NULL) || (!mCurMethodInstance->mIsUnspecialized)) &&
  10301. (mHasFullDebugInfo) &&
  10302. ((mCurMethodState->mClosureState == NULL) || (!mCurMethodState->mClosureState->mCapturing)))
  10303. {
  10304. auto varType = localVarDef->mResolvedType;
  10305. if (localVarDef->mResolvedType->IsValuelessType())
  10306. {
  10307. }
  10308. else
  10309. {
  10310. bool isByAddr = false;
  10311. auto diValue = localVarDef->mValue;
  10312. if (localVarDef->mConstValue)
  10313. diValue = localVarDef->mConstValue;
  10314. else if (localVarDef->mAddr)
  10315. {
  10316. diValue = localVarDef->mAddr;
  10317. isByAddr = true;
  10318. }
  10319. auto diType = mBfIRBuilder->DbgGetType(localVarDef->mResolvedType);
  10320. bool didConstToMem = false;
  10321. bool isConstant = false;
  10322. if ((localVarDef->mIsReadOnly) && (localVarDef->mAddr))
  10323. diType = mBfIRBuilder->DbgCreateConstType(diType);
  10324. else if (localVarDef->mConstValue)
  10325. {
  10326. auto constant = mBfIRBuilder->GetConstant(localVarDef->mConstValue);
  10327. isConstant =
  10328. (constant->mConstType < BfConstType_GlobalVar) ||
  10329. (constant->mConstType == BfConstType_AggZero) ||
  10330. (constant->mConstType == BfConstType_Array);
  10331. if (isConstant)
  10332. {
  10333. if (localVarDef->mResolvedType->IsComposite())
  10334. {
  10335. mBfIRBuilder->PopulateType(localVarDef->mResolvedType);
  10336. auto constMem = mBfIRBuilder->ConstToMemory(localVarDef->mConstValue);
  10337. if (IsTargetingBeefBackend())
  10338. {
  10339. diValue = mBfIRBuilder->CreateAliasValue(constMem);
  10340. didConstToMem = true;
  10341. diType = mBfIRBuilder->DbgCreateReferenceType(diType);
  10342. }
  10343. else
  10344. {
  10345. isByAddr = true;
  10346. mBfIRBuilder->SaveDebugLocation();
  10347. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  10348. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRInitBlock);
  10349. mBfIRBuilder->ClearDebugLocation();
  10350. auto ptrType = CreatePointerType(localVarDef->mResolvedType);
  10351. auto addrVal = CreateAlloca(ptrType);
  10352. mBfIRBuilder->CreateStore(constMem, addrVal);
  10353. diType = mBfIRBuilder->DbgCreateReferenceType(diType);
  10354. diValue = addrVal;
  10355. didConstToMem = true;
  10356. mBfIRBuilder->SetInsertPoint(prevBlock);
  10357. mBfIRBuilder->RestoreDebugLocation();
  10358. }
  10359. }
  10360. if (mCompiler->mOptions.IsCodeView())
  10361. diType = mBfIRBuilder->DbgCreateConstType(diType);
  10362. }
  10363. }
  10364. auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(mCurMethodState->mCurScope->mDIScope,
  10365. localVarDef->mName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType, initType);
  10366. localVarDef->mDbgVarInst = diVariable;
  10367. if (mBfIRBuilder->HasDebugLocation())
  10368. {
  10369. if ((isConstant) && (!didConstToMem))
  10370. {
  10371. localVarDef->mDbgDeclareInst = mBfIRBuilder->DbgInsertValueIntrinsic(localVarDef->mConstValue, diVariable);
  10372. }
  10373. else
  10374. {
  10375. if ((IsTargetingBeefBackend()) && (doAliasValue))
  10376. {
  10377. diValue = mBfIRBuilder->CreateAliasValue(diValue);
  10378. mCurMethodState->mCurScope->mDeferredLifetimeEnds.Add(diValue);
  10379. }
  10380. if (isByAddr)
  10381. localVarDef->mDbgDeclareInst = mBfIRBuilder->DbgInsertDeclare(diValue, diVariable, declareBefore);
  10382. else if (diValue)
  10383. {
  10384. localVarDef->mDbgDeclareInst = mBfIRBuilder->DbgInsertValueIntrinsic(diValue, diVariable);
  10385. }
  10386. else if (mCompiler->mOptions.mToolsetType != BfToolsetType_GNU) // DWARF chokes on this:
  10387. localVarDef->mDbgDeclareInst = mBfIRBuilder->DbgInsertValueIntrinsic(BfIRValue(), diVariable);
  10388. }
  10389. }
  10390. }
  10391. }
  10392. localVarDef->mDeclBlock = mBfIRBuilder->GetInsertBlock();
  10393. DoAddLocalVariable(localVarDef);
  10394. auto rootMethodState = mCurMethodState->GetRootMethodState();
  10395. if (localVarDef->mLocalVarId == -1)
  10396. {
  10397. BF_ASSERT(rootMethodState->mCurLocalVarId >= 0);
  10398. localVarDef->mLocalVarId = rootMethodState->mCurLocalVarId++;
  10399. }
  10400. if ((localVarDef->mNameNode != NULL) && (mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL))
  10401. mCompiler->mResolvePassData->mAutoComplete->CheckLocalDef(localVarDef->mNameNode, localVarDef);
  10402. if ((localVarDef->mNameNode != NULL) && (mCurMethodInstance != NULL))
  10403. {
  10404. bool isClosureProcessing = (mCurMethodState->mClosureState != NULL) && (!mCurMethodState->mClosureState->mCapturing);
  10405. if ((!isClosureProcessing) && (mCompiler->mResolvePassData != NULL) && (localVarDef->mNameNode != NULL))
  10406. mCompiler->mResolvePassData->HandleLocalReference(localVarDef->mNameNode, rootMethodState->mMethodInstance->GetOwner()->mTypeDef, rootMethodState->mMethodInstance->mMethodDef, localVarDef->mLocalVarId);
  10407. }
  10408. return localVarDef;
  10409. }
  10410. void BfModule::CreateDIRetVal()
  10411. {
  10412. if (!WantsDebugInfo())
  10413. return;
  10414. /*if (!mCurMethodState->mRetVal)
  10415. {
  10416. if (mCurMethodInstance->mMethodDef->mName != "Ziggle")
  10417. return;
  10418. }*/
  10419. if ((mCurMethodState->mRetVal) || (mCurMethodState->mRetValAddr))
  10420. {
  10421. BF_ASSERT((!mBfIRBuilder->mIgnoreWrites) || (mHadVarUsage));
  10422. BfType* dbgType = mCurMethodInstance->mReturnType;
  10423. BfIRValue dbgValue = mCurMethodState->mRetVal.mValue;
  10424. if (mCurMethodInstance->HasStructRet())
  10425. {
  10426. BF_ASSERT(mCurMethodState->mRetValAddr);
  10427. dbgType = CreatePointerType(dbgType);
  10428. dbgValue = mCurMethodState->mRetValAddr;
  10429. }
  10430. else
  10431. {
  10432. BF_ASSERT(!mCurMethodState->mRetValAddr);
  10433. }
  10434. mCurMethodState->mDIRetVal = mBfIRBuilder->DbgCreateAutoVariable(mCurMethodState->mCurScope->mDIScope,
  10435. "__return", mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, mBfIRBuilder->DbgGetType(dbgType));
  10436. auto declareCall = mBfIRBuilder->DbgInsertDeclare(dbgValue, mCurMethodState->mDIRetVal);
  10437. }
  10438. }
  10439. void BfModule::CheckVariableDef(BfLocalVariable* variableDef)
  10440. {
  10441. BfLocalVarEntry* localVarEntryPtr = NULL;
  10442. if ((mCurMethodState != NULL) && (mCurMethodState->mLocalVarSet.TryGet(BfLocalVarEntry(variableDef), &localVarEntryPtr)))
  10443. {
  10444. auto checkLocal = localVarEntryPtr->mLocalVar;
  10445. if ((checkLocal->mLocalVarIdx >= mCurMethodState->GetLocalStartIdx()) && (!checkLocal->mIsShadow))
  10446. {
  10447. BfError* error;
  10448. if (checkLocal->mIsImplicitParam)
  10449. return; // Ignore 'redefinition'
  10450. if (checkLocal->IsParam())
  10451. error = Fail(StrFormat("A parameter named '%s' has already been declared.", variableDef->mName.c_str()), variableDef->mNameNode);
  10452. else if (checkLocal->mLocalVarIdx < mCurMethodState->mCurScope->mLocalVarStart)
  10453. error = Fail(StrFormat("A variable named '%s' has already been declared in this parent's scope.", variableDef->mName.c_str()), variableDef->mNameNode);
  10454. else
  10455. error = Fail(StrFormat("A variable named '%s' has already been declared in this scope.", variableDef->mName.c_str()), variableDef->mNameNode);
  10456. if ((checkLocal->mNameNode != NULL) && (error != NULL))
  10457. mCompiler->mPassInstance->MoreInfo("Previous declaration", checkLocal->mNameNode);
  10458. return;
  10459. }
  10460. }
  10461. }
  10462. BfScopeData* BfModule::FindScope(BfAstNode* scopeName, BfMixinState* fromMixinState, bool allowAcrossDeferredBlock)
  10463. {
  10464. bool inMixinDecl = (mCurMethodInstance != NULL) && (mCurMethodInstance->IsMixin());
  10465. if (auto tokenNode = BfNodeDynCast<BfTokenNode>(scopeName))
  10466. {
  10467. if (tokenNode->GetToken() == BfToken_Colon)
  10468. {
  10469. if ((!allowAcrossDeferredBlock) && (mCurMethodState->mInDeferredBlock))
  10470. {
  10471. Fail("Cannot access method scope across deferred block boundary", scopeName);
  10472. return NULL;
  10473. }
  10474. return &mCurMethodState->mHeadScope;
  10475. }
  10476. else if (tokenNode->GetToken() == BfToken_Mixin)
  10477. {
  10478. if (fromMixinState == NULL)
  10479. {
  10480. if (mCurMethodInstance->mMethodDef->mMethodType != BfMethodType_Mixin)
  10481. Fail("'mixin' scope specifier can only be used within a mixin declaration", scopeName);
  10482. return mCurMethodState->mCurScope;
  10483. }
  10484. fromMixinState->mUsedInvocationScope = true;
  10485. return fromMixinState->mTargetScope;
  10486. }
  10487. else if (tokenNode->GetToken() == BfToken_New)
  10488. return NULL;
  10489. }
  10490. if (auto identifier = BfNodeDynCast<BfIdentifierNode>(scopeName))
  10491. {
  10492. auto findLabel = scopeName->ToString();
  10493. bool crossedDeferredBlock = false;
  10494. auto checkScope = mCurMethodState->mCurScope;
  10495. while (checkScope != NULL)
  10496. {
  10497. if (checkScope->mIsDeferredBlock)
  10498. crossedDeferredBlock = true;
  10499. if (checkScope->mLabel == findLabel)
  10500. {
  10501. if ((crossedDeferredBlock) && (!allowAcrossDeferredBlock))
  10502. {
  10503. Fail(StrFormat("Cannot access scope '%s' across deferred block boundary", findLabel.c_str()), scopeName);
  10504. return NULL;
  10505. }
  10506. return checkScope;
  10507. }
  10508. checkScope = checkScope->mPrevScope;
  10509. }
  10510. if (!inMixinDecl)
  10511. Fail(StrFormat("Unable to locate label '%s'", findLabel.c_str()), scopeName);
  10512. }
  10513. if (auto scopeNode = BfNodeDynCast<BfScopeNode>(scopeName))
  10514. {
  10515. return FindScope(scopeNode->mTargetNode, allowAcrossDeferredBlock);
  10516. }
  10517. return mCurMethodState->mCurScope;
  10518. }
  10519. BfScopeData* BfModule::FindScope(BfAstNode* scopeName, bool allowAcrossDeferredBlock)
  10520. {
  10521. return FindScope(scopeName, mCurMethodState->mMixinState, allowAcrossDeferredBlock);
  10522. }
  10523. BfBreakData* BfModule::FindBreakData(BfAstNode* scopeName)
  10524. {
  10525. auto scopeData = FindScope(scopeName, false);
  10526. if (scopeData == NULL)
  10527. return NULL;
  10528. int scopeDepth = scopeData->GetDepth();
  10529. // Find the first break data that is at or below the depth of our requested scope
  10530. auto breakData = mCurMethodState->mBreakData;
  10531. while ((breakData != NULL) && (scopeDepth < breakData->mScope->GetDepth()))
  10532. {
  10533. if (breakData->mScope->mIsConditional)
  10534. return NULL;
  10535. breakData = breakData->mPrevBreakData;
  10536. }
  10537. return breakData;
  10538. }
  10539. void BfModule::EmitLifetimeEnds(BfScopeData* scopeData)
  10540. {
  10541. // LLVM is stricter about the placement of these (ie: they can't occur after a 'ret')
  10542. if (!IsTargetingBeefBackend())
  10543. return;
  10544. for (auto lifetimeEnd : scopeData->mDeferredLifetimeEnds)
  10545. {
  10546. mBfIRBuilder->CreateLifetimeEnd(lifetimeEnd);
  10547. }
  10548. }
  10549. void BfModule::ClearLifetimeEnds()
  10550. {
  10551. auto scopeData = mCurMethodState->mCurScope;
  10552. while (scopeData != NULL)
  10553. {
  10554. scopeData->mDeferredLifetimeEnds.Clear();
  10555. scopeData = scopeData->mPrevScope;
  10556. }
  10557. }
  10558. bool BfModule::WantsDebugInfo()
  10559. {
  10560. if ((mCurMethodInstance != NULL) &&
  10561. ((mCurMethodInstance->mIsUnspecialized) || (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_Mixin)))
  10562. return false;
  10563. return (mBfIRBuilder->DbgHasInfo()) && (mHasFullDebugInfo) &&
  10564. ((mCurMethodState == NULL) || (mCurMethodState->mClosureState == NULL) || (!mCurMethodState->mClosureState->mCapturing));
  10565. }
  10566. BfTypeOptions* BfModule::GetTypeOptions()
  10567. {
  10568. if ((mCurMethodState != NULL) && (mCurMethodState->mMethodTypeOptions != NULL))
  10569. return mCurMethodState->mMethodTypeOptions;
  10570. return mSystem->GetTypeOptions(mCurTypeInstance->mTypeOptionsIdx);
  10571. }
  10572. bool BfModule::HasDeferredScopeCalls(BfScopeData* scope)
  10573. {
  10574. BfScopeData* checkScope = mCurMethodState->mCurScope;
  10575. while (checkScope != NULL)
  10576. {
  10577. if ((!checkScope->mDeferredCallEntries.IsEmpty()) || (!checkScope->mDeferredLifetimeEnds.empty()))
  10578. return true;
  10579. if (checkScope == scope)
  10580. break;
  10581. checkScope = checkScope->mPrevScope;
  10582. }
  10583. return false;
  10584. }
  10585. void BfModule::EmitDeferredScopeCalls(bool useSrcPositions, BfScopeData* scopeData, BfIRBlock doneBlock)
  10586. {
  10587. // Is there anything we need to do here?
  10588. if (mBfIRBuilder->mIgnoreWrites)
  10589. {
  10590. // Just visit deferred blocks
  10591. BfScopeData* checkScope = mCurMethodState->mCurScope;
  10592. while (checkScope != NULL)
  10593. {
  10594. BfDeferredCallEntry* deferredCallEntry = checkScope->mDeferredCallEntries.mHead;
  10595. while (deferredCallEntry != NULL)
  10596. {
  10597. if (deferredCallEntry->mDeferredBlock != NULL)
  10598. {
  10599. VisitEmbeddedStatement(deferredCallEntry->mDeferredBlock, NULL, BfEmbeddedStatementFlags_IsDeferredBlock);
  10600. }
  10601. deferredCallEntry = deferredCallEntry->mNext;
  10602. }
  10603. if (checkScope == scopeData)
  10604. break;
  10605. checkScope = checkScope->mPrevScope;
  10606. }
  10607. return;
  10608. }
  10609. // Why did we want to do SetIllegalSrcPos here?
  10610. // Don't we always want to step onto these instances?
  10611. // Find a case where we don't and perhaps only do it there.
  10612. // The downside was that 'EmitEnsureInstructionAt' on the end of block statements causes
  10613. // a (seemingly) unneeded NOP when we do SetIllegalSrcPos
  10614. //SetIllegalSrcPos();
  10615. bool setSrcPos = false;
  10616. bool wantsNop = true;
  10617. BfAstNode* deferCloseNode = NULL;
  10618. if (mCurMethodState->mInPostReturn)
  10619. {
  10620. // These won't get used, they are post-return
  10621. return;
  10622. }
  10623. SizedArray<BfIRValue, 8> deferredLifetimeEnds;
  10624. BfScopeData* scopeJumpBlock = NULL;
  10625. bool hadExtraDeferredLifetimeEnds = false;
  10626. auto _FlushLifetimeEnds = [&]()
  10627. {
  10628. for (auto lifetimeEnd : deferredLifetimeEnds)
  10629. {
  10630. mBfIRBuilder->CreateLifetimeEnd(lifetimeEnd);
  10631. mBfIRBuilder->ClearDebugLocation_Last();
  10632. }
  10633. deferredLifetimeEnds.clear();
  10634. };
  10635. BfScopeData* checkScope = mCurMethodState->mCurScope;
  10636. while (checkScope != NULL)
  10637. {
  10638. if (checkScope->mCloseNode != NULL)
  10639. deferCloseNode = checkScope->mCloseNode;
  10640. if (doneBlock)
  10641. {
  10642. // Try to find a match where we've already emitted these calls and then jumped to the correct block
  10643. for (auto& checkHandler : checkScope->mDeferredHandlers)
  10644. {
  10645. if (checkHandler.mDoneBlock == doneBlock)
  10646. {
  10647. scopeJumpBlock = checkScope;
  10648. mBfIRBuilder->CreateBr(checkHandler.mHandlerBlock);
  10649. mBfIRBuilder->ClearDebugLocation_Last();
  10650. _FlushLifetimeEnds();
  10651. break;
  10652. }
  10653. }
  10654. if (scopeJumpBlock != NULL)
  10655. break;
  10656. }
  10657. bool hasWork = (checkScope->mSavedStack) || (checkScope->mDeferredCallEntries.mHead != NULL);
  10658. if (checkScope != scopeData) // Only emit a block for deferred lifetimes if we're going back beyond this entry
  10659. hasWork |= (!deferredLifetimeEnds.IsEmpty());
  10660. if (hasWork)
  10661. {
  10662. SetAndRestoreValue<BfScopeData*> prevScope(mCurMethodState->mCurScope, checkScope);
  10663. if (deferCloseNode != NULL)
  10664. {
  10665. UpdateSrcPos(deferCloseNode);
  10666. }
  10667. if (doneBlock)
  10668. {
  10669. bool crossingMixin = mCurMethodState->mCurScope->mMixinDepth != checkScope->mMixinDepth;
  10670. String blockName = "deferredCalls";
  10671. //blockName += StrFormat("_%d", mBfIRBuilder->mBlockCount);
  10672. BfDeferredHandler deferredHandler;
  10673. if ((!crossingMixin) && (deferredLifetimeEnds.IsEmpty()))
  10674. {
  10675. mBfIRBuilder->SaveDebugLocation();
  10676. mBfIRBuilder->ClearDebugLocation();
  10677. deferredHandler.mHandlerBlock = mBfIRBuilder->MaybeChainNewBlock(blockName);
  10678. mBfIRBuilder->RestoreDebugLocation();
  10679. }
  10680. else
  10681. {
  10682. // Definitely chain
  10683. deferredHandler.mHandlerBlock = mBfIRBuilder->CreateBlock(blockName);
  10684. mBfIRBuilder->CreateBr(deferredHandler.mHandlerBlock);
  10685. mBfIRBuilder->ClearDebugLocation_Last();
  10686. _FlushLifetimeEnds();
  10687. mBfIRBuilder->AddBlock(deferredHandler.mHandlerBlock);
  10688. mBfIRBuilder->SetInsertPoint(deferredHandler.mHandlerBlock);
  10689. }
  10690. deferredHandler.mDoneBlock = doneBlock;
  10691. if (!mBfIRBuilder->mIgnoreWrites)
  10692. checkScope->mDeferredHandlers.push_back(deferredHandler);
  10693. if (checkScope == &mCurMethodState->mHeadScope)
  10694. {
  10695. if (!mCurMethodState->mDIRetVal)
  10696. {
  10697. // 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
  10698. // be scoped to the physical method
  10699. /*if (deferCloseNode != NULL)
  10700. {
  10701. UpdateSrcPos(deferCloseNode);
  10702. }*/
  10703. CreateDIRetVal();
  10704. }
  10705. }
  10706. if (checkScope != mCurMethodState->mTailScope)
  10707. {
  10708. if (deferredHandler.mHandlerBlock.IsFake())
  10709. {
  10710. BF_ASSERT(mBfIRBuilder->mIgnoreWrites);
  10711. }
  10712. if (!mBfIRBuilder->mIgnoreWrites)
  10713. checkScope->mAtEndBlocks.push_back(deferredHandler.mHandlerBlock);
  10714. }
  10715. }
  10716. std::unordered_set<BfDeferredCallEntry*> handledSet;
  10717. BfDeferredCallEntry* deferredCallEntry = checkScope->mDeferredCallEntries.mHead;
  10718. while (deferredCallEntry != NULL)
  10719. {
  10720. BfDeferredCallEmitState deferredCallEmitState;
  10721. deferredCallEmitState.mCloseNode = deferCloseNode;
  10722. SetAndRestoreValue<BfDeferredCallEmitState*> prevDeferredCallEmitState(mCurMethodState->mDeferredCallEmitState, &deferredCallEmitState);
  10723. SetAndRestoreValue<bool> prevIgnoredWrites(mBfIRBuilder->mIgnoreWrites, deferredCallEntry->mIgnored);
  10724. if (deferCloseNode != NULL)
  10725. {
  10726. UpdateSrcPos(deferCloseNode);
  10727. }
  10728. if (wantsNop)
  10729. EmitEnsureInstructionAt();
  10730. wantsNop = false;
  10731. if (deferredCallEntry->mDeferredBlock != NULL)
  10732. {
  10733. auto itr = handledSet.insert(deferredCallEntry);
  10734. if (!itr.second)
  10735. {
  10736. // Already handled, can happen if we defer again within the block
  10737. deferredCallEntry = deferredCallEntry->mNext;
  10738. continue;
  10739. }
  10740. auto prevHead = checkScope->mDeferredCallEntries.mHead;
  10741. EmitDeferredCall(*deferredCallEntry);
  10742. if (prevHead != checkScope->mDeferredCallEntries.mHead)
  10743. {
  10744. // The list changed, start over and ignore anything we've already handled
  10745. deferredCallEntry = checkScope->mDeferredCallEntries.mHead;
  10746. }
  10747. else
  10748. deferredCallEntry = deferredCallEntry->mNext;
  10749. }
  10750. else
  10751. {
  10752. EmitDeferredCall(*deferredCallEntry);
  10753. deferredCallEntry = deferredCallEntry->mNext;
  10754. }
  10755. }
  10756. if (checkScope->mSavedStack)
  10757. {
  10758. checkScope->mSavedStackUses.Add(mBfIRBuilder->CreateStackRestore(checkScope->mSavedStack));
  10759. if (mCurMethodState->mDynStackRevIdx)
  10760. {
  10761. auto curValue = mBfIRBuilder->CreateLoad(mCurMethodState->mDynStackRevIdx);
  10762. auto newValue = mBfIRBuilder->CreateAdd(curValue, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 1));
  10763. mBfIRBuilder->CreateStore(newValue, mCurMethodState->mDynStackRevIdx);
  10764. }
  10765. }
  10766. }
  10767. if (!checkScope->mIsScopeHead)
  10768. {
  10769. // We manually emit function-level lifetime ends after the 'ret' in ProcessMethod
  10770. if (!IsTargetingBeefBackend())
  10771. {
  10772. for (auto lifetimeEnd : checkScope->mDeferredLifetimeEnds)
  10773. {
  10774. mBfIRBuilder->CreateLifetimeEnd(lifetimeEnd);
  10775. }
  10776. }
  10777. else
  10778. {
  10779. for (auto lifetimeEnd : checkScope->mDeferredLifetimeEnds)
  10780. {
  10781. deferredLifetimeEnds.Add(lifetimeEnd);
  10782. }
  10783. }
  10784. }
  10785. if (checkScope == scopeData)
  10786. break;
  10787. checkScope = checkScope->mPrevScope;
  10788. }
  10789. if ((doneBlock) && (scopeJumpBlock == NULL))
  10790. {
  10791. mBfIRBuilder->CreateBr(doneBlock);
  10792. mBfIRBuilder->ClearDebugLocation_Last();
  10793. }
  10794. // Keeping CreateLifetimeEnds until the end messes up when we chain to old mDeferredHandlers that
  10795. // may have been created when other scope lifetimes were available
  10796. _FlushLifetimeEnds();
  10797. // Emit lifetimeEnds after the branch for Beef
  10798. /*if (IsTargetingBeefBackend())
  10799. {
  10800. bool needsEnsureInst = (!doneBlock) && (scopeJumpBlock == NULL);
  10801. BfScopeData* checkScope = mCurMethodState->mCurScope;
  10802. while (checkScope != NULL)
  10803. {
  10804. if (checkScope == scopeJumpBlock)
  10805. break;
  10806. if (!checkScope->mIsScopeHead)
  10807. {
  10808. for (auto lifetimeEnd : checkScope->mDeferredLifetimeEnds)
  10809. {
  10810. if (needsEnsureInst)
  10811. {
  10812. needsEnsureInst = false;
  10813. }
  10814. mBfIRBuilder->CreateLifetimeEnd(lifetimeEnd);
  10815. }
  10816. }
  10817. if (checkScope == scopeData)
  10818. break;
  10819. checkScope = checkScope->mPrevScope;
  10820. }
  10821. }*/
  10822. }
  10823. void BfModule::MarkScopeLeft(BfScopeData* scopeData)
  10824. {
  10825. if (mCurMethodState->mDeferredLocalAssignData != NULL)
  10826. {
  10827. auto deferredLocalAssignData = mCurMethodState->mDeferredLocalAssignData;
  10828. while (deferredLocalAssignData != NULL)
  10829. {
  10830. if ((deferredLocalAssignData->mScopeData == NULL) || (deferredLocalAssignData->mScopeData->mScopeDepth < scopeData->mScopeDepth))
  10831. break;
  10832. if ((deferredLocalAssignData->mScopeData != NULL) && (deferredLocalAssignData->mScopeData->mScopeDepth == scopeData->mScopeDepth))
  10833. deferredLocalAssignData->mIsUnconditional = false;
  10834. deferredLocalAssignData = deferredLocalAssignData->mChainedAssignData;
  10835. }
  10836. }
  10837. //for (int localIdx = scopeData->mLocalVarStart; localIdx < (int)mCurMethodState->mLocals.size(); localIdx++)
  10838. // We mark all unassigned variables as assigned now, for avoiding "may be unassigned" usage cases like:
  10839. // int b;
  10840. // if (cond) return;
  10841. // else b = 1;
  10842. // Use(b);
  10843. for (int localIdx = 0; localIdx < (int)mCurMethodState->mLocals.size(); localIdx++)
  10844. {
  10845. auto localDef = mCurMethodState->mLocals[localIdx];
  10846. if ((!localDef->mIsAssigned) && (!localDef->IsParam()))
  10847. mCurMethodState->LocalDefined(localDef);
  10848. }
  10849. }
  10850. void BfModule::CreateReturn(BfIRValue val)
  10851. {
  10852. if (mCurMethodInstance->mReturnType->IsComposite())
  10853. {
  10854. // Store to sret
  10855. BF_ASSERT(val);
  10856. mBfIRBuilder->CreateStore(val, mBfIRBuilder->GetArgument(0));
  10857. mBfIRBuilder->CreateRetVoid();
  10858. }
  10859. else
  10860. {
  10861. if (mCurMethodInstance->mReturnType->IsValuelessType())
  10862. {
  10863. mBfIRBuilder->CreateRetVoid();
  10864. }
  10865. else
  10866. {
  10867. BF_ASSERT(val);
  10868. mBfIRBuilder->CreateRet(val);
  10869. }
  10870. }
  10871. }
  10872. void BfModule::EmitReturn(BfIRValue val)
  10873. {
  10874. if (mCurMethodState->mIRExitBlock)
  10875. {
  10876. if (!mCurMethodInstance->mReturnType->IsValuelessType())
  10877. {
  10878. if (val) // We allow for val to be empty if we know we've already written the value to mRetVal
  10879. {
  10880. BfIRValue retVal = mCurMethodState->mRetVal.mValue;
  10881. if (!mCurMethodState->mRetVal)
  10882. retVal = mBfIRBuilder->CreateLoad(mCurMethodState->mRetValAddr);
  10883. mBfIRBuilder->CreateStore(val, retVal);
  10884. }
  10885. }
  10886. EmitDeferredScopeCalls(true, NULL, mCurMethodState->mIRExitBlock);
  10887. }
  10888. else
  10889. {
  10890. EmitDeferredScopeCalls(false, NULL);
  10891. if (mCurMethodInstance->mReturnType->IsValuelessType())
  10892. mBfIRBuilder->CreateRetVoid();
  10893. else
  10894. mBfIRBuilder->CreateRet(val);
  10895. }
  10896. mCurMethodState->SetHadReturn(true);
  10897. mCurMethodState->mLeftBlockUncond = true;
  10898. }
  10899. void BfModule::EmitDefaultReturn()
  10900. {
  10901. if (mCurMethodState->mInDeferredBlock)
  10902. return;
  10903. if (mCurMethodState->mIRExitBlock)
  10904. {
  10905. EmitDeferredScopeCalls(true, NULL, mCurMethodState->mIRExitBlock);
  10906. }
  10907. else
  10908. {
  10909. if (mCurMethodInstance->mReturnType->IsVoid())
  10910. mBfIRBuilder->CreateRetVoid();
  10911. else
  10912. mBfIRBuilder->CreateRet(GetDefaultValue(mCurMethodInstance->mReturnType));
  10913. }
  10914. mCurMethodState->SetHadReturn(true);
  10915. mCurMethodState->mLeftBlockUncond = true;
  10916. }
  10917. void BfModule::AssertErrorState()
  10918. {
  10919. if (mIgnoreErrors)
  10920. return;
  10921. if (mHadBuildError)
  10922. return;
  10923. if (mCurTypeInstance != NULL)
  10924. {
  10925. if (mCurTypeInstance->IsUnspecializedTypeVariation())
  10926. return;
  10927. }
  10928. if (mCurMethodInstance != NULL)
  10929. {
  10930. if (mCurMethodInstance->mIsUnspecializedVariation)
  10931. return;
  10932. }
  10933. // We want the module to be marked as failed even if it's just an error in the parser
  10934. if (mCurMethodInstance != NULL)
  10935. mCurMethodInstance->mHasFailed = true;
  10936. mHadBuildError = true;
  10937. // We check for either the parsing to have failed (possibly on a previous run), or for the current instance to have failed
  10938. if (mCurTypeInstance != NULL)
  10939. {
  10940. if (mCurTypeInstance->mTypeFailed)
  10941. return;
  10942. if (mCurTypeInstance->mTypeDef->mSource->mParsingFailed)
  10943. return;
  10944. }
  10945. if (mCurMethodInstance != NULL)
  10946. {
  10947. if ((mCurMethodInstance->mMethodDef->mDeclaringType != NULL) && (mCurMethodInstance->mMethodDef->mDeclaringType->mSource->mParsingFailed))
  10948. return;
  10949. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL) && (mCurMethodState->mMixinState->mMixinMethodInstance->mMethodDef->mDeclaringType->mSource->mParsingFailed))
  10950. return;
  10951. }
  10952. BF_ASSERT(mCompiler->mPassInstance->HasFailed());
  10953. }
  10954. void BfModule::AssertParseErrorState()
  10955. {
  10956. if (mCompiler->mRevision == 1)
  10957. AssertErrorState();
  10958. }
  10959. BfType* BfModule::GetDelegateReturnType(BfType* delegateType)
  10960. {
  10961. BF_ASSERT(delegateType->IsDelegate());
  10962. auto typeInst = delegateType->ToTypeInstance();
  10963. PopulateType(typeInst, BfPopulateType_DataAndMethods);
  10964. BfMethodInstance* invokeMethodInstance = GetRawMethodInstanceAtIdx(typeInst->ToTypeInstance(), 0, "Invoke");
  10965. return invokeMethodInstance->mReturnType;
  10966. }
  10967. BfMethodInstance* BfModule::GetDelegateInvokeMethod(BfTypeInstance* typeInstance)
  10968. {
  10969. return GetRawMethodInstanceAtIdx(typeInstance, 0, "Invoke");
  10970. }
  10971. void BfModule::CreateDelegateInvokeMethod()
  10972. {
  10973. // Clear out debug loc - otherwise we'll single step onto the delegate type declaration
  10974. //mBfIRBuilder->ClearDebugLocation();
  10975. SetIllegalSrcPos();
  10976. auto typeInstance = mCurTypeInstance;
  10977. auto memberFuncType = mBfIRBuilder->MapMethod(mCurMethodInstance);
  10978. SizedArray<BfIRType, 4> staticParamTypes;
  10979. SizedArray<BfIRValue, 4> staticFuncArgs;
  10980. SizedArray<BfIRValue, 4> memberFuncArgs;
  10981. auto multicastDelegateType = typeInstance->mBaseType;
  10982. if (multicastDelegateType->mFieldInstances.size() != 2)
  10983. {
  10984. AssertErrorState();
  10985. return;
  10986. }
  10987. auto multicastDelegate = mBfIRBuilder->CreateBitCast(mCurMethodState->mLocals[0]->mValue, mBfIRBuilder->MapType(multicastDelegateType));
  10988. auto fieldPtr = mBfIRBuilder->CreateInBoundsGEP(multicastDelegate, 0, 2); // Load 'delegate.mTarget'
  10989. auto fieldVal = mBfIRBuilder->CreateLoad(fieldPtr);
  10990. BfExprEvaluator exprEvaluator(this);
  10991. SizedArray<BfIRType, 8> origParamTypes;
  10992. BfIRType origReturnType;
  10993. mCurMethodInstance->GetIRFunctionInfo(this, origReturnType, origParamTypes);
  10994. if (mCurMethodInstance->mReturnType->IsValueType())
  10995. mBfIRBuilder->PopulateType(mCurMethodInstance->mReturnType, BfIRPopulateType_Full);
  10996. int thisIdx = 0;
  10997. if (mCurMethodInstance->HasStructRet())
  10998. {
  10999. thisIdx = 1;
  11000. staticFuncArgs.push_back(mBfIRBuilder->GetArgument(0));
  11001. memberFuncArgs.push_back(mBfIRBuilder->GetArgument(0));
  11002. }
  11003. memberFuncArgs.push_back(BfIRValue()); // Push 'target'
  11004. mCurMethodInstance->GetIRFunctionInfo(this, origReturnType, staticParamTypes, true);
  11005. for (int i = 1; i < (int)mCurMethodState->mLocals.size(); i++)
  11006. {
  11007. BfTypedValue localVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[i], true);
  11008. exprEvaluator.PushArg(localVal, staticFuncArgs);
  11009. exprEvaluator.PushArg(localVal, memberFuncArgs);
  11010. }
  11011. auto staticFunc = mBfIRBuilder->CreateFunctionType(origReturnType, staticParamTypes, false);
  11012. auto staticFuncPtr = mBfIRBuilder->GetPointerTo(staticFunc);
  11013. auto staticFuncPtrPtr = mBfIRBuilder->GetPointerTo(staticFuncPtr);
  11014. auto trueBB = mBfIRBuilder->CreateBlock("if.then", true);
  11015. auto falseBB = mBfIRBuilder->CreateBlock("if.else");
  11016. auto doneBB = mBfIRBuilder->CreateBlock("done");
  11017. auto checkTargetNull = mBfIRBuilder->CreateIsNotNull(fieldVal);
  11018. mBfIRBuilder->CreateCondBr(checkTargetNull, trueBB, falseBB);
  11019. BfIRValue nonStaticResult;
  11020. BfIRValue staticResult;
  11021. auto callingConv = GetCallingConvention(mCurTypeInstance, mCurMethodInstance->mMethodDef);
  11022. /// Non-static invocation
  11023. {
  11024. auto memberFuncPtr = mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapMethod(mCurMethodInstance));
  11025. auto memberFuncPtrPtr = mBfIRBuilder->GetPointerTo(memberFuncPtr);
  11026. mBfIRBuilder->SetInsertPoint(trueBB);
  11027. memberFuncArgs[thisIdx] = mBfIRBuilder->CreateBitCast(fieldVal, mBfIRBuilder->MapType(mCurTypeInstance));
  11028. auto fieldPtr = mBfIRBuilder->CreateInBoundsGEP(multicastDelegate, 0, 1); // Load 'delegate.mFuncPtr'
  11029. auto funcPtrPtr = mBfIRBuilder->CreateBitCast(fieldPtr, memberFuncPtrPtr);
  11030. auto funcPtr = mBfIRBuilder->CreateLoad(funcPtrPtr);
  11031. nonStaticResult = mBfIRBuilder->CreateCall(funcPtr, memberFuncArgs);
  11032. if (callingConv != BfIRCallingConv_CDecl)
  11033. mBfIRBuilder->SetCallCallingConv(nonStaticResult, callingConv);
  11034. mCurMethodState->SetHadReturn(false);
  11035. mCurMethodState->mLeftBlockUncond = false;
  11036. mCurMethodState->mLeftBlockCond = false;
  11037. mBfIRBuilder->CreateBr(doneBB);
  11038. }
  11039. // Static invocation
  11040. {
  11041. mBfIRBuilder->AddBlock(falseBB);
  11042. mBfIRBuilder->SetInsertPoint(falseBB);
  11043. auto fieldPtr = mBfIRBuilder->CreateInBoundsGEP(multicastDelegate, 0, 1); // Load 'delegate.mFuncPtr'
  11044. auto funcPtrPtr = mBfIRBuilder->CreateBitCast(fieldPtr, staticFuncPtrPtr);
  11045. auto funcPtr = mBfIRBuilder->CreateLoad(funcPtrPtr);
  11046. staticResult = mBfIRBuilder->CreateCall(funcPtr, staticFuncArgs);
  11047. if (callingConv == BfIRCallingConv_ThisCall)
  11048. callingConv = BfIRCallingConv_CDecl;
  11049. if (callingConv != BfIRCallingConv_CDecl)
  11050. mBfIRBuilder->SetCallCallingConv(staticResult, callingConv);
  11051. // if (!mSystem->IsCompatibleCallingConvention(BfCallingConvention_Unspecified, mCurMethodInstance->mMethodDef->mCallingConvention))
  11052. // {
  11053. // if (mCurMethodInstance->mMethodDef->mCallingConvention == BfCallingConvention_Stdcall)
  11054. //
  11055. // }
  11056. mCurMethodState->SetHadReturn(false);
  11057. mCurMethodState->mLeftBlockUncond = false;
  11058. mCurMethodState->mLeftBlockCond = false;
  11059. mBfIRBuilder->CreateBr(doneBB);
  11060. }
  11061. mBfIRBuilder->AddBlock(doneBB);
  11062. mBfIRBuilder->SetInsertPoint(doneBB);
  11063. if ((mCurMethodInstance->mReturnType->IsValuelessType()) || (mCurMethodInstance->HasStructRet()))
  11064. {
  11065. mBfIRBuilder->CreateRetVoid();
  11066. }
  11067. else
  11068. {
  11069. auto phi = mBfIRBuilder->CreatePhi(mBfIRBuilder->MapType(mCurMethodInstance->mReturnType), 2);
  11070. mBfIRBuilder->AddPhiIncoming(phi, nonStaticResult, trueBB);
  11071. mBfIRBuilder->AddPhiIncoming(phi, staticResult, falseBB);
  11072. mBfIRBuilder->CreateRet(phi);
  11073. }
  11074. }
  11075. // "Interested" here means every method for a normal compile, and just the method the cursor is on for autocompletion
  11076. bool BfModule::IsInterestedInMethod(BfTypeInstance* typeInstance, BfMethodDef* methodDef)
  11077. {
  11078. auto typeDef = typeInstance->mTypeDef;
  11079. auto methodDeclaration = methodDef->mMethodDeclaration;
  11080. if (!mCompiler->mIsResolveOnly)
  11081. return true;
  11082. if (typeInstance->IsGenericTypeInstance())
  11083. {
  11084. // We only really want to process the unspecialized type for autocompletion
  11085. if ((!typeInstance->IsUnspecializedType()) || (typeInstance->IsUnspecializedTypeVariation()))
  11086. return false;
  11087. }
  11088. BfAstNode* checkNode = methodDeclaration;
  11089. if (methodDeclaration == NULL)
  11090. checkNode = methodDef->mBody;
  11091. if ((mCompiler->mResolvePassData->mParser != NULL) && (typeDef->mTypeDeclaration->IsFromParser(mCompiler->mResolvePassData->mParser)))
  11092. {
  11093. if (mCompiler->mResolvePassData->mAutoComplete == NULL)
  11094. return true;
  11095. }
  11096. return false;
  11097. }
  11098. void BfModule::CalcAppendAlign(BfMethodInstance* methodInst)
  11099. {
  11100. methodInst->mAppendAllocAlign = 1;
  11101. }
  11102. BfTypedValue BfModule::TryConstCalcAppend(BfMethodInstance* methodInst, SizedArrayImpl<BfIRValue>& args)
  11103. {
  11104. BP_ZONE("BfModule::TryConstCalcAppend");
  11105. if (mCompiler->mIsResolveOnly)
  11106. return BfTypedValue();
  11107. // We want to regenerate all ctor calls when the method internals change
  11108. {
  11109. auto checkTypeInst = methodInst->GetOwner();
  11110. while (checkTypeInst->mTypeDef->mHasAppendCtor)
  11111. {
  11112. AddDependency(checkTypeInst, mCurTypeInstance, BfDependencyMap::DependencyFlag_InlinedCall);
  11113. checkTypeInst = GetBaseType(checkTypeInst);
  11114. }
  11115. }
  11116. if (!methodInst->mMayBeConst)
  11117. return BfTypedValue();
  11118. // Do we need to iterate in order to resolve mAppendAllocAlign?
  11119. bool isFirstRun = methodInst->mAppendAllocAlign < 0;
  11120. bool wasAllConst = true;
  11121. int argIdx = 0;
  11122. int paramIdx = 0;
  11123. while (true)
  11124. {
  11125. if (argIdx >= (int)args.size())
  11126. break;
  11127. auto paramType = methodInst->GetParamType(paramIdx);
  11128. PopulateType(paramType);
  11129. int argCount = 0;
  11130. if (!paramType->IsValuelessType())
  11131. {
  11132. if (methodInst->GetParamIsSplat(paramIdx))
  11133. argCount = paramType->GetSplatCount();
  11134. else
  11135. argCount = 1;
  11136. for (int argOfs = 0; argOfs < argCount; argOfs++)
  11137. {
  11138. auto arg = args[argIdx + argOfs];
  11139. if (!arg.IsConst())
  11140. {
  11141. wasAllConst = false;
  11142. if (!isFirstRun)
  11143. {
  11144. auto& param = methodInst->mParams[argIdx];
  11145. if (param.mReferencedInConstPass)
  11146. {
  11147. // If this param is required as part of the const calculation then
  11148. // we require that it be const...
  11149. return BfTypedValue();
  11150. }
  11151. }
  11152. }
  11153. }
  11154. }
  11155. paramIdx++;
  11156. argIdx += argCount;
  11157. }
  11158. auto methodDef = methodInst->mMethodDef;
  11159. auto methodDecl = methodDef->GetMethodDeclaration();
  11160. auto methodDeclBlock = BfNodeDynCast<BfBlock>(methodDecl->mBody);
  11161. if (methodDeclBlock == NULL)
  11162. return BfTypedValue();
  11163. BfTypedValue constValue;
  11164. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  11165. auto checkState = mCurMethodState->mConstResolveState;
  11166. while (checkState != NULL)
  11167. {
  11168. if (checkState->mMethodInstance == methodInst)
  11169. {
  11170. return BfTypedValue();
  11171. }
  11172. checkState = checkState->mPrevConstResolveState;
  11173. }
  11174. //auto accumValue = GetConstValue(0);
  11175. bool failed = false;
  11176. //
  11177. {
  11178. BfConstResolveState constResolveState;
  11179. constResolveState.mMethodInstance = methodInst;
  11180. constResolveState.mPrevConstResolveState = mCurMethodState->mConstResolveState;
  11181. SetAndRestoreValue<bool> ignoreWrites(mBfIRBuilder->mIgnoreWrites, true);
  11182. BfMethodState methodState;
  11183. SetAndRestoreValue<BfTypeInstance*> prevTypeInst(mCurTypeInstance, methodInst->GetOwner());
  11184. SetAndRestoreValue<BfMethodInstance*> prevMethodInst(mCurMethodInstance, methodInst);
  11185. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  11186. methodState.mTempKind = BfMethodState::TempKind_NonStatic;
  11187. methodState.mConstResolveState = &constResolveState;
  11188. int argIdx = 0;
  11189. for (int paramIdx = 0; paramIdx < methodInst->GetParamCount(); paramIdx++)
  11190. {
  11191. if (methodInst->GetParamKind(paramIdx) == BfParamKind_AppendIdx)
  11192. continue;
  11193. auto paramType = methodInst->GetParamType(paramIdx);
  11194. // Fix this after we allow structs to be consts
  11195. //BF_ASSERT(!paramType->IsSplattable());
  11196. BfLocalVariable* localVar = new BfLocalVariable();
  11197. localVar->mName = methodInst->GetParamName(paramIdx);
  11198. localVar->mResolvedType = paramType;
  11199. localVar->mConstValue = args[argIdx];
  11200. localVar->mParamIdx = paramIdx;
  11201. AddLocalVariableDef(localVar);
  11202. argIdx++;
  11203. }
  11204. AppendAllocVisitor appendAllocVisitor;
  11205. appendAllocVisitor.mConstAccum = GetDefaultTypedValue(GetPrimitiveType(BfTypeCode_IntPtr));
  11206. appendAllocVisitor.mIsFirstConstPass = isFirstRun;
  11207. BfTypedValue baseCtorAppendValue = CallBaseCtorCalc(true);
  11208. if (baseCtorAppendValue)
  11209. {
  11210. if (baseCtorAppendValue.mValue.IsFake())
  11211. appendAllocVisitor.mFailed = true;
  11212. else
  11213. appendAllocVisitor.mConstAccum = baseCtorAppendValue;
  11214. }
  11215. appendAllocVisitor.mModule = this;
  11216. appendAllocVisitor.VisitChild(methodDecl->mBody);
  11217. if (!appendAllocVisitor.mFailed)
  11218. constValue = appendAllocVisitor.mConstAccum;
  11219. if (isFirstRun)
  11220. mCurMethodInstance->mEndingAppendAllocAlign = appendAllocVisitor.mCurAppendAlign;
  11221. if (isFirstRun)
  11222. {
  11223. for (int paramIdx = 0; paramIdx < methodInst->GetParamCount(); paramIdx++)
  11224. {
  11225. auto localVar = mCurMethodState->mLocals[paramIdx];
  11226. if (localVar->mReadFromId != -1)
  11227. {
  11228. auto& param = methodInst->mParams[paramIdx];
  11229. param.mReferencedInConstPass = true;
  11230. }
  11231. }
  11232. }
  11233. }
  11234. mBfIRBuilder->SetInsertPoint(prevBlock);
  11235. if (!constValue)
  11236. {
  11237. // If we did a 'force' then some params may not have been const -- only clear mMayBeConst if we had
  11238. // all-const args
  11239. if (wasAllConst)
  11240. {
  11241. methodInst->mMayBeConst = false;
  11242. }
  11243. }
  11244. return constValue;
  11245. }
  11246. BfTypedValue BfModule::CallBaseCtorCalc(bool constOnly)
  11247. {
  11248. // Any errors should only be shown in the actual CTOR call
  11249. SetAndRestoreValue<bool> prevIgnoreWrites(mIgnoreErrors, true);
  11250. auto methodDef = mCurMethodInstance->mMethodDef;
  11251. BF_ASSERT((methodDef->mMethodType == BfMethodType_Ctor) || (methodDef->mMethodType == BfMethodType_CtorCalcAppend));
  11252. auto ctorDeclaration = (BfConstructorDeclaration*)methodDef->mMethodDeclaration;
  11253. BfTypeInstance* targetType = NULL;
  11254. if (ctorDeclaration->mInitializer != NULL)
  11255. {
  11256. auto targetToken = BfNodeDynCast<BfTokenNode>(ctorDeclaration->mInitializer->mTarget);
  11257. targetType = (targetToken->GetToken() == BfToken_This) ? mCurTypeInstance : mCurTypeInstance->mBaseType;
  11258. }
  11259. else
  11260. targetType = mCurTypeInstance->mBaseType;
  11261. if ((targetType == NULL) || (targetType == mContext->mBfObjectType))
  11262. return NULL;
  11263. auto targetRefNode = methodDef->GetRefNode();
  11264. BfType* targetThisType = targetType;
  11265. BfTypedValue target(mBfIRBuilder->GetFakeVal(), targetThisType);
  11266. BfExprEvaluator exprEvaluator(this);
  11267. BfResolvedArgs argValues;
  11268. if ((ctorDeclaration != NULL) && (ctorDeclaration->mInitializer != NULL))
  11269. {
  11270. argValues.Init(&ctorDeclaration->mInitializer->mArguments);
  11271. }
  11272. //
  11273. {
  11274. }
  11275. BfFunctionBindResult bindResult;
  11276. bindResult.mSkipThis = true;
  11277. bindResult.mWantsArgs = true;
  11278. {
  11279. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, true);
  11280. exprEvaluator.ResolveArgValues(argValues, BfResolveArgFlag_DeferParamEval);
  11281. SetAndRestoreValue<BfFunctionBindResult*> prevBindResult(exprEvaluator.mFunctionBindResult, &bindResult);
  11282. exprEvaluator.MatchConstructor(targetRefNode, NULL, target, targetType, argValues, true, true);
  11283. }
  11284. if (bindResult.mMethodInstance == NULL)
  11285. {
  11286. AssertErrorState();
  11287. return BfTypedValue();
  11288. }
  11289. if (!bindResult.mMethodInstance->mMethodDef->mHasAppend)
  11290. {
  11291. return BfTypedValue();
  11292. }
  11293. BF_ASSERT(bindResult.mIRArgs[0].IsFake());
  11294. bindResult.mIRArgs.RemoveAt(0);
  11295. auto calcAppendMethodModule = GetMethodInstanceAtIdx(bindResult.mMethodInstance->GetOwner(), bindResult.mMethodInstance->mMethodDef->mIdx + 1, BF_METHODNAME_CALCAPPEND);
  11296. BfTypedValue appendSizeTypedValue = TryConstCalcAppend(calcAppendMethodModule.mMethodInstance, bindResult.mIRArgs);
  11297. BF_ASSERT(calcAppendMethodModule.mMethodInstance->mAppendAllocAlign >= 0);
  11298. mCurMethodInstance->mAppendAllocAlign = BF_MAX((int)mCurMethodInstance->mAppendAllocAlign, calcAppendMethodModule.mMethodInstance->mAppendAllocAlign);
  11299. BF_ASSERT(calcAppendMethodModule.mMethodInstance->mEndingAppendAllocAlign > -1);
  11300. mCurMethodState->mCurAppendAlign = BF_MAX(calcAppendMethodModule.mMethodInstance->mEndingAppendAllocAlign, 0);
  11301. if (appendSizeTypedValue)
  11302. return appendSizeTypedValue;
  11303. if (constOnly)
  11304. return BfTypedValue(mBfIRBuilder->GetFakeVal(), GetPrimitiveType(BfTypeCode_IntPtr));
  11305. bool needsRecalc = false;
  11306. for (auto irArg : bindResult.mIRArgs)
  11307. {
  11308. if (irArg.IsFake())
  11309. needsRecalc = true;
  11310. }
  11311. auto calcAppendArgs = bindResult.mIRArgs;
  11312. if (needsRecalc)
  11313. {
  11314. // Do it again, but without mIgnoreWrites set
  11315. BfResolvedArgs argValues;
  11316. argValues.Init(&ctorDeclaration->mInitializer->mArguments);
  11317. exprEvaluator.ResolveArgValues(argValues, BfResolveArgFlag_DeferParamEval);
  11318. BfFunctionBindResult bindResult;
  11319. bindResult.mSkipThis = true;
  11320. bindResult.mWantsArgs = true;
  11321. SetAndRestoreValue<BfFunctionBindResult*> prevBindResult(exprEvaluator.mFunctionBindResult, &bindResult);
  11322. exprEvaluator.MatchConstructor(targetRefNode, NULL, target, targetType, argValues, true, true);
  11323. BF_ASSERT(bindResult.mIRArgs[0].IsFake());
  11324. bindResult.mIRArgs.RemoveAt(0);
  11325. calcAppendArgs = bindResult.mIRArgs;
  11326. }
  11327. BF_ASSERT(calcAppendMethodModule.mFunc);
  11328. appendSizeTypedValue = exprEvaluator.CreateCall(calcAppendMethodModule.mMethodInstance, calcAppendMethodModule.mFunc, false, calcAppendArgs);
  11329. BF_ASSERT(appendSizeTypedValue.mType == GetPrimitiveType(BfTypeCode_IntPtr));
  11330. return appendSizeTypedValue;
  11331. }
  11332. // This method never throws errors - it relies on the proper ctor actually throwing the errors
  11333. void BfModule::EmitCtorCalcAppend()
  11334. {
  11335. if (mCompiler->mIsResolveOnly)
  11336. return;
  11337. auto methodDef = mCurMethodInstance->mMethodDef;
  11338. auto methodDecl = methodDef->GetMethodDeclaration();
  11339. Array<BfAstNode*> deferredNodeList;
  11340. auto methodDeclBlock = BfNodeDynCast<BfBlock>(methodDecl->mBody);
  11341. if (methodDeclBlock == NULL)
  11342. return;
  11343. AppendAllocVisitor appendAllocVisitor;
  11344. auto baseCalcAppend = CallBaseCtorCalc(false);
  11345. if (baseCalcAppend)
  11346. {
  11347. mBfIRBuilder->CreateStore(baseCalcAppend.mValue, mCurMethodState->mRetVal.mValue);
  11348. }
  11349. appendAllocVisitor.mModule = this;
  11350. appendAllocVisitor.VisitChild(methodDecl->mBody);
  11351. }
  11352. void BfModule::CreateStaticCtor()
  11353. {
  11354. auto typeDef = mCurTypeInstance->mTypeDef;
  11355. auto methodDef = mCurMethodInstance->mMethodDef;
  11356. BfIRBlock exitBB;
  11357. if ((HasCompiledOutput()) && (!mCurMethodInstance->mIsUnspecialized) && (mCurMethodInstance->mChainType != BfMethodChainType_ChainMember))
  11358. {
  11359. auto boolType = GetPrimitiveType(BfTypeCode_Boolean);
  11360. auto didStaticInitVarAddr = mBfIRBuilder->CreateGlobalVariable(
  11361. mBfIRBuilder->MapType(boolType),
  11362. false,
  11363. BfIRLinkageType_Internal,
  11364. GetDefaultValue(boolType),
  11365. "didStaticInit");
  11366. auto initBB = mBfIRBuilder->CreateBlock("init", true);
  11367. mCurMethodState->mIRExitBlock = mBfIRBuilder->CreateBlock("exit", true);
  11368. auto didStaticInitVar = mBfIRBuilder->CreateLoad(didStaticInitVarAddr);
  11369. mBfIRBuilder->CreateCondBr(didStaticInitVar, mCurMethodState->mIRExitBlock, initBB);
  11370. mBfIRBuilder->SetInsertPoint(initBB);
  11371. mBfIRBuilder->CreateStore(GetConstValue(1, boolType), didStaticInitVarAddr);
  11372. }
  11373. // Do DLL imports
  11374. if (!mDllImportEntries.empty())
  11375. {
  11376. auto internalType = ResolveTypeDef(mCompiler->mInternalTypeDef);
  11377. PopulateType(internalType);
  11378. auto getSharedProcAddressInstance = GetMethodByName(internalType->ToTypeInstance(), "GetSharedProcAddress");
  11379. if (!getSharedProcAddressInstance)
  11380. {
  11381. if (!mCompiler->mPassInstance->HasFailed())
  11382. Fail("Internal error: System.Internal doesn't contain LoadSharedLibrary method");
  11383. }
  11384. }
  11385. // Fill in initializer values
  11386. if ((!mCompiler->mIsResolveOnly) || (mCompiler->mResolvePassData->mAutoComplete == NULL))
  11387. {
  11388. for (auto fieldDef : typeDef->mFields)
  11389. {
  11390. if ((!fieldDef->mIsConst) && (fieldDef->mIsStatic) && (fieldDef->mInitializer != NULL))
  11391. {
  11392. // For extensions, only handle these fields in the appropriate extension
  11393. if ((fieldDef->mDeclaringType->mTypeDeclaration != methodDef->mDeclaringType->mTypeDeclaration))
  11394. continue;
  11395. UpdateSrcPos(fieldDef->mInitializer);
  11396. auto fieldInst = &mCurTypeInstance->mFieldInstances[fieldDef->mIdx];
  11397. if (!fieldInst->mFieldIncluded)
  11398. continue;
  11399. if (fieldInst->mResolvedType->IsVar())
  11400. {
  11401. BF_ASSERT(mHadVarUsage);
  11402. continue;
  11403. }
  11404. auto assignValue = GetFieldInitializerValue(fieldInst);
  11405. if (assignValue)
  11406. {
  11407. assignValue = LoadValue(assignValue);
  11408. if (!assignValue.mType->IsValuelessType())
  11409. {
  11410. auto staticVarRef = ReferenceStaticField(fieldInst).mValue;
  11411. mBfIRBuilder->CreateStore(assignValue.mValue, staticVarRef);
  11412. }
  11413. }
  11414. }
  11415. }
  11416. }
  11417. else
  11418. {
  11419. for (auto tempTypeDef : mCompiler->mResolvePassData->mAutoCompleteTempTypes)
  11420. {
  11421. if (tempTypeDef->mFullName == typeDef->mFullName)
  11422. {
  11423. for (auto fieldDef : tempTypeDef->mFields)
  11424. {
  11425. if ((fieldDef->mIsStatic) && (!fieldDef->mIsConst))
  11426. {
  11427. if (fieldDef->mInitializer != NULL)
  11428. {
  11429. if (mCompiler->mResolvePassData->mSourceClassifier != NULL)
  11430. {
  11431. mCompiler->mResolvePassData->mSourceClassifier->SetElementType(fieldDef->mInitializer, BfSourceElementType_Normal);
  11432. mCompiler->mResolvePassData->mSourceClassifier->VisitChild(fieldDef->mInitializer);
  11433. }
  11434. BfType* wantType = NULL;
  11435. if ((!BfNodeIsA<BfVarTypeReference>(fieldDef->mTypeRef)) && (!BfNodeIsA<BfLetTypeReference>(fieldDef->mTypeRef)))
  11436. {
  11437. wantType = ResolveTypeRef(fieldDef->mTypeRef);
  11438. }
  11439. CreateValueFromExpression(fieldDef->mInitializer, wantType, BfEvalExprFlags_FieldInitializer);
  11440. }
  11441. }
  11442. }
  11443. }
  11444. }
  11445. }
  11446. if (mCurMethodInstance->mChainType == BfMethodChainType_ChainHead)
  11447. CallChainedMethods(mCurMethodInstance, false);
  11448. }
  11449. void BfModule::EmitDtorBody()
  11450. {
  11451. if (mCurTypeInstance->IsClosure())
  11452. {
  11453. BfFieldInstance* fieldInstance = &mCurTypeInstance->mFieldInstances.back();
  11454. BF_ASSERT(fieldInstance->GetFieldDef()->mName == "__dtorThunk");
  11455. auto thisVal = GetThis();
  11456. auto dtorThunkPtr = mBfIRBuilder->CreateInBoundsGEP(thisVal.mValue, 0, fieldInstance->mDataIdx);
  11457. auto dtorThunk = mBfIRBuilder->CreateLoad(dtorThunkPtr);
  11458. auto funcPtrType = mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapMethod(mCurMethodInstance));
  11459. auto dtorPtr = mBfIRBuilder->CreateBitCast(dtorThunk, funcPtrType);
  11460. SizedArray<BfIRValue, 1> args;
  11461. args.push_back(thisVal.mValue);
  11462. auto result = mBfIRBuilder->CreateCall(dtorPtr, args);
  11463. mBfIRBuilder->SetCallCallingConv(result, BfIRCallingConv_CDecl);
  11464. // Fall through to Object::~this call
  11465. auto dtorFunc = GetMethodByName(mContext->mBfObjectType, "~this");
  11466. auto basePtr = mBfIRBuilder->CreateBitCast(thisVal.mValue, mBfIRBuilder->MapTypeInstPtr(mContext->mBfObjectType));
  11467. SizedArray<BfIRValue, 1> vals = { basePtr };
  11468. result = mBfIRBuilder->CreateCall(dtorFunc.mFunc, vals);
  11469. mBfIRBuilder->SetCallCallingConv(result, GetCallingConvention(dtorFunc.mMethodInstance));
  11470. mBfIRBuilder->SetTailCall(result);
  11471. return;
  11472. }
  11473. auto typeDef = mCurTypeInstance->mTypeDef;
  11474. auto methodDef = mCurMethodInstance->mMethodDef;
  11475. auto methodDeclaration = methodDef->GetMethodDeclaration();
  11476. if (mCurMethodInstance->mChainType == BfMethodChainType_ChainHead)
  11477. CallChainedMethods(mCurMethodInstance, true);
  11478. if (auto bodyBlock = BfNodeDynCast<BfBlock>(methodDef->mBody))
  11479. {
  11480. VisitCodeBlock(bodyBlock);
  11481. if (bodyBlock->mCloseBrace != NULL)
  11482. {
  11483. UpdateSrcPos(bodyBlock->mCloseBrace);
  11484. }
  11485. }
  11486. else
  11487. {
  11488. if (methodDeclaration != NULL)
  11489. UpdateSrcPos(methodDeclaration);
  11490. else if (typeDef->mTypeDeclaration != NULL)
  11491. UpdateSrcPos(typeDef->mTypeDeclaration);
  11492. if ((methodDeclaration != NULL) && (methodDeclaration->mFatArrowToken != NULL))
  11493. {
  11494. Fail("Destructors cannot have expression bodies", methodDeclaration->mFatArrowToken);
  11495. }
  11496. }
  11497. if ((!mCompiler->mIsResolveOnly) || (mCompiler->mResolvePassData->mAutoComplete == NULL))
  11498. {
  11499. for (int fieldIdx = (int)mCurTypeInstance->mFieldInstances.size() - 1; fieldIdx >= 0; fieldIdx--)
  11500. {
  11501. auto fieldInst = &mCurTypeInstance->mFieldInstances[fieldIdx];
  11502. auto fieldDef = fieldInst->GetFieldDef();
  11503. if ((fieldDef != NULL) && (fieldDef->mIsStatic == methodDef->mIsStatic) && (fieldDef->mFieldDeclaration != NULL) && (fieldDef->mFieldDeclaration->mFieldDtor != NULL))
  11504. {
  11505. if ((!methodDef->mIsStatic) && (mCurTypeInstance->IsValueType()))
  11506. {
  11507. Fail("Structs cannot have field destructors", fieldDef->mFieldDeclaration->mFieldDtor->mTildeToken);
  11508. }
  11509. SetAndRestoreValue<BfFilePosition> prevFilePos(mCurFilePosition);
  11510. auto fieldDtor = fieldDef->mFieldDeclaration->mFieldDtor;
  11511. if ((fieldDef->mIsStatic) != (methodDef->mIsStatic))
  11512. continue;
  11513. UpdateSrcPos(fieldDtor);
  11514. BfScopeData scopeData;
  11515. mCurMethodState->AddScope(&scopeData);
  11516. NewScopeState();
  11517. UpdateSrcPos(fieldDtor);
  11518. bool hasDbgInfo = (!fieldDef->mIsConst);
  11519. if (hasDbgInfo)
  11520. {
  11521. mBfIRBuilder->SaveDebugLocation();
  11522. mBfIRBuilder->ClearDebugLocation();
  11523. }
  11524. BfIRValue value;
  11525. if (fieldDef->mIsStatic)
  11526. {
  11527. value = ReferenceStaticField(fieldInst).mValue;
  11528. }
  11529. else
  11530. {
  11531. if (!mCurTypeInstance->IsValueType())
  11532. {
  11533. auto thisValue = GetThis();
  11534. value = mBfIRBuilder->CreateInBoundsGEP(thisValue.mValue, 0, fieldInst->mDataIdx);
  11535. }
  11536. else
  11537. {
  11538. AssertErrorState();
  11539. value = mBfIRBuilder->CreateConstNull(mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapType(fieldInst->mResolvedType)));
  11540. }
  11541. }
  11542. BfIRValue staticVal;
  11543. if (hasDbgInfo)
  11544. {
  11545. BfIRValue dbgShowValue = value;
  11546. BfLocalVariable* localDef = new BfLocalVariable();
  11547. localDef->mName = "_";
  11548. localDef->mResolvedType = fieldInst->mResolvedType;
  11549. localDef->mAddr = value;
  11550. if ((mBfIRBuilder->DbgHasInfo()) && (!IsTargetingBeefBackend()))
  11551. {
  11552. // Create another pointer indirection, a ref to the gep
  11553. auto refFieldType = CreateRefType(fieldInst->mResolvedType);
  11554. auto allocaInst = CreateAlloca(refFieldType);
  11555. auto storeResult = mBfIRBuilder->CreateStore(value, allocaInst);
  11556. localDef->mResolvedType = refFieldType;
  11557. localDef->mAddr = allocaInst;
  11558. }
  11559. mBfIRBuilder->RestoreDebugLocation();
  11560. auto defLocalVar = AddLocalVariableDef(localDef, true);
  11561. // Put back so we actually modify the correct value*/
  11562. defLocalVar->mResolvedType = fieldInst->mResolvedType;
  11563. defLocalVar->mAddr = value;
  11564. }
  11565. while (fieldDtor != NULL)
  11566. {
  11567. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mSourceClassifier != NULL))
  11568. {
  11569. mCompiler->mResolvePassData->mSourceClassifier->SetElementType(fieldDtor, BfSourceElementType_Normal);
  11570. mCompiler->mResolvePassData->mSourceClassifier->VisitChild(fieldDtor);
  11571. }
  11572. UpdateSrcPos(fieldDtor);
  11573. VisitEmbeddedStatement(fieldDtor->mBody);
  11574. fieldDtor = fieldDtor->mNextFieldDtor;
  11575. }
  11576. RestoreScopeState();
  11577. }
  11578. }
  11579. if (!methodDef->mIsStatic)
  11580. {
  11581. auto checkBaseType = mCurTypeInstance->mBaseType;
  11582. while (checkBaseType != NULL)
  11583. {
  11584. if (auto bodyBlock = BfNodeDynCast<BfBlock>(methodDef->mBody))
  11585. {
  11586. if (bodyBlock->mCloseBrace != NULL)
  11587. UpdateSrcPos(bodyBlock->mCloseBrace);
  11588. }
  11589. else
  11590. {
  11591. UpdateSrcPos(typeDef->mTypeDeclaration->mNameNode);
  11592. }
  11593. if (checkBaseType->mTypeDef->mDtorDef != NULL)
  11594. {
  11595. auto dtorMethodInstance = GetMethodInstance(checkBaseType, checkBaseType->mTypeDef->mDtorDef, BfTypeVector());
  11596. if (mCompiler->IsSkippingExtraResolveChecks())
  11597. {
  11598. // Nothing
  11599. }
  11600. else if (dtorMethodInstance.mMethodInstance->GetParamCount() == 0)
  11601. {
  11602. if ((!mCompiler->IsSkippingExtraResolveChecks()) && (!checkBaseType->IsUnspecializedType()))
  11603. {
  11604. auto basePtr = mBfIRBuilder->CreateBitCast(mCurMethodState->mLocals[0]->mValue, mBfIRBuilder->MapTypeInstPtr(checkBaseType));
  11605. SizedArray<BfIRValue, 1> vals = { basePtr };
  11606. auto callInst = mBfIRBuilder->CreateCall(dtorMethodInstance.mFunc, vals);
  11607. mBfIRBuilder->SetCallCallingConv(callInst, GetCallingConvention(dtorMethodInstance.mMethodInstance));
  11608. }
  11609. }
  11610. else
  11611. {
  11612. // Invalid base dtor declaration
  11613. AssertErrorState();
  11614. }
  11615. break;
  11616. }
  11617. checkBaseType = checkBaseType->mBaseType;
  11618. }
  11619. }
  11620. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  11621. }
  11622. else
  11623. {
  11624. // The reason we can't just do the 'normal' path for this is that the BfTypeInstance here is NOT the
  11625. // autocomplete type instance, so FieldInstance initializer values contain expressions from the full
  11626. // resolve pass, NOT the autocomplete expression
  11627. for (auto tempTypeDef : mCompiler->mResolvePassData->mAutoCompleteTempTypes)
  11628. {
  11629. if (tempTypeDef->mFullName == typeDef->mFullName)
  11630. {
  11631. for (auto fieldDef : tempTypeDef->mFields)
  11632. {
  11633. if ((fieldDef->mIsStatic == methodDef->mIsStatic) && (fieldDef->mFieldDeclaration != NULL) &&
  11634. (fieldDef->mFieldDeclaration->mFieldDtor != NULL) && (mCompiler->mResolvePassData->mSourceClassifier != NULL))
  11635. {
  11636. BfType* fieldType = NULL;
  11637. for (int curFieldIdx = 0; curFieldIdx < (int)mCurTypeInstance->mFieldInstances.size(); curFieldIdx++)
  11638. {
  11639. auto curFieldInstance = &mCurTypeInstance->mFieldInstances[curFieldIdx];
  11640. auto curFieldDef = curFieldInstance->GetFieldDef();
  11641. if ((curFieldDef != NULL) && (fieldDef->mName == curFieldDef->mName))
  11642. fieldType = curFieldInstance->GetResolvedType();
  11643. }
  11644. auto fieldDtor = fieldDef->mFieldDeclaration->mFieldDtor;
  11645. BfScopeData scopeData;
  11646. mCurMethodState->AddScope(&scopeData);
  11647. NewScopeState();
  11648. // This is just for autocomplete, it doesn't matter that mAddr is incorrect
  11649. if (fieldType != NULL)
  11650. {
  11651. BfLocalVariable* localDef = new BfLocalVariable();
  11652. localDef->mName = "_";
  11653. localDef->mResolvedType = fieldType;
  11654. localDef->mAddr = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(fieldType));
  11655. localDef->mIsAssigned = true;
  11656. AddLocalVariableDef(localDef);
  11657. }
  11658. while (fieldDtor != NULL)
  11659. {
  11660. mCompiler->mResolvePassData->mSourceClassifier->SetElementType(fieldDtor, BfSourceElementType_Normal);
  11661. mCompiler->mResolvePassData->mSourceClassifier->VisitChild(fieldDtor);
  11662. UpdateSrcPos(fieldDtor);
  11663. VisitEmbeddedStatement(fieldDtor->mBody);
  11664. fieldDtor = fieldDtor->mNextFieldDtor;
  11665. }
  11666. RestoreScopeState();
  11667. }
  11668. }
  11669. }
  11670. }
  11671. }
  11672. }
  11673. BfIRValue BfModule::CreateDllImportGlobalVar(BfMethodInstance* methodInstance, bool define)
  11674. {
  11675. auto typeInstance = methodInstance->GetOwner();
  11676. bool foundDllImportAttr = false;
  11677. BfCallingConvention callingConvention = methodInstance->mMethodDef->mCallingConvention;
  11678. for (auto customAttr : methodInstance->GetCustomAttributes()->mAttributes)
  11679. {
  11680. if (customAttr.mType->mTypeDef->mFullName.ToString() == "System.ImportAttribute")
  11681. {
  11682. foundDllImportAttr = true;
  11683. }
  11684. }
  11685. if (!foundDllImportAttr)
  11686. {
  11687. AssertErrorState();
  11688. return BfIRValue();
  11689. }
  11690. String name = "bf_hs_preserve@";
  11691. BfMangler::Mangle(name, mCompiler->GetMangleKind(), methodInstance);
  11692. name += "__imp";
  11693. BfIRType returnType;
  11694. SizedArray<BfIRType, 8> paramTypes;
  11695. methodInstance->GetIRFunctionInfo(this, returnType, paramTypes);
  11696. BfIRFunctionType externFunctionType = mBfIRBuilder->CreateFunctionType(returnType, paramTypes, false);
  11697. auto ptrType = mBfIRBuilder->GetPointerTo(externFunctionType);
  11698. BfIRValue initVal;
  11699. if (define)
  11700. {
  11701. if (methodInstance->GetImportCallKind() != BfImportCallKind_None)
  11702. initVal = mBfIRBuilder->CreateConstNull(ptrType);
  11703. }
  11704. auto globalVar = mBfIRBuilder->CreateGlobalVariable(ptrType, false, BfIRLinkageType_External, initVal, name);
  11705. if ((define) && (mBfIRBuilder->DbgHasInfo()))
  11706. {
  11707. auto voidType = GetPrimitiveType(BfTypeCode_None);
  11708. auto ptrType = CreatePointerType(voidType);
  11709. mBfIRBuilder->DbgCreateGlobalVariable(mDICompileUnit, name, name, BfIRMDNode(), 0, mBfIRBuilder->DbgGetType(ptrType), false, globalVar);
  11710. }
  11711. return globalVar;
  11712. }
  11713. void BfModule::CreateDllImportMethod()
  11714. {
  11715. if (mBfIRBuilder->mIgnoreWrites)
  11716. return;
  11717. auto globalVar = mFuncReferences[mCurMethodInstance];
  11718. if (!globalVar)
  11719. return;
  11720. bool allowTailCall = true;
  11721. mBfIRBuilder->ClearDebugLocation();
  11722. bool isHotCompile = mCompiler->IsHotCompile();
  11723. // If we are hot swapping, we need to have this stub because we may need to call the LoadSharedLibraries on demand
  11724. if (isHotCompile)
  11725. {
  11726. auto loadSharedLibsFunc = GetBuiltInFunc(BfBuiltInFuncType_LoadSharedLibraries);
  11727. mBfIRBuilder->CreateCall(loadSharedLibsFunc, SizedArray<BfIRValue, 0>());
  11728. }
  11729. auto callingConvention = GetCallingConvention(mCurTypeInstance, mCurMethodInstance->mMethodDef);
  11730. BfIRType returnType;
  11731. SizedArray<BfIRType, 8> paramTypes;
  11732. mCurMethodInstance->GetIRFunctionInfo(this, returnType, paramTypes);
  11733. SizedArray<BfIRValue, 8> args;
  11734. for (int i = 0; i < (int)paramTypes.size(); i++)
  11735. args.push_back(mBfIRBuilder->GetArgument(i));
  11736. BfIRFunctionType externFunctionType = mBfIRBuilder->CreateFunctionType(returnType, paramTypes, false);
  11737. if (isHotCompile)
  11738. {
  11739. BfIRValue funcVal = mBfIRBuilder->CreateLoad(globalVar);
  11740. auto result = mBfIRBuilder->CreateCall(funcVal, args);
  11741. if (callingConvention == BfIRCallingConv_StdCall)
  11742. mBfIRBuilder->SetCallCallingConv(result, BfIRCallingConv_StdCall);
  11743. else
  11744. mBfIRBuilder->SetCallCallingConv(result, BfIRCallingConv_CDecl);
  11745. if (allowTailCall)
  11746. mBfIRBuilder->SetTailCall(result);
  11747. CreateReturn(result);
  11748. mCurMethodState->mHadReturn = true;
  11749. }
  11750. if (HasCompiledOutput())
  11751. {
  11752. BfDllImportEntry dllImportEntry;
  11753. dllImportEntry.mFuncVar = globalVar;
  11754. dllImportEntry.mMethodInstance = mCurMethodInstance;
  11755. mDllImportEntries.push_back(dllImportEntry);
  11756. }
  11757. }
  11758. BfIRCallingConv BfModule::GetCallingConvention(BfTypeInstance* typeInst, BfMethodDef* methodDef)
  11759. {
  11760. if ((mCompiler->mOptions.mMachineType != BfMachineType_x86) || (mCompiler->mOptions.mPlatformType != BfPlatformType_Windows))
  11761. return BfIRCallingConv_CDecl;
  11762. if (methodDef->mCallingConvention == BfCallingConvention_Stdcall)
  11763. return BfIRCallingConv_StdCall;
  11764. if ((!methodDef->mIsStatic) && (!typeInst->IsValuelessType()) &&
  11765. ((!typeInst->IsSplattable()) || (methodDef->HasNoThisSplat())))
  11766. return BfIRCallingConv_ThisCall;
  11767. return BfIRCallingConv_CDecl;
  11768. }
  11769. BfIRCallingConv BfModule::GetCallingConvention(BfMethodInstance* methodInstance)
  11770. {
  11771. return GetCallingConvention(methodInstance->GetOwner(), methodInstance->mMethodDef);
  11772. }
  11773. void BfModule::SetupIRMethod(BfMethodInstance* methodInstance, BfIRFunction func, bool isInlined)
  11774. {
  11775. BfMethodDef* methodDef = NULL;
  11776. if (methodInstance != NULL)
  11777. methodDef = methodInstance->mMethodDef;
  11778. if (!func)
  11779. return;
  11780. if (mCompiler->mOptions.mNoFramePointerElim)
  11781. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_NoFramePointerElim);
  11782. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_NoUnwind);
  11783. if (mSystem->mPtrSize == 8) // We need unwind info for debugging
  11784. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_UWTable);
  11785. if (methodInstance == NULL)
  11786. return;
  11787. if (methodDef->mImportKind == BfImportKind_Export)
  11788. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_DllExport);
  11789. if (methodDef->mNoReturn)
  11790. mBfIRBuilder->Func_AddAttribute(func, -1, BfIRAttribute_NoReturn);
  11791. auto callingConv = GetCallingConvention(methodInstance->GetOwner(), methodDef);
  11792. if (callingConv != BfIRCallingConv_CDecl)
  11793. mBfIRBuilder->SetFuncCallingConv(func, callingConv);
  11794. if (isInlined)
  11795. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_AlwaysInline);
  11796. int argIdx = 0;
  11797. int paramIdx = 0;
  11798. if (methodInstance->HasThis())
  11799. {
  11800. paramIdx = -1;
  11801. }
  11802. int argCount = methodInstance->GetIRFunctionParamCount(this);
  11803. if (methodInstance->HasStructRet())
  11804. {
  11805. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_NoAlias);
  11806. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_StructRet);
  11807. argIdx++;
  11808. }
  11809. while (argIdx < argCount)
  11810. {
  11811. while ((paramIdx != -1) && (methodInstance->IsParamSkipped(paramIdx)))
  11812. paramIdx++;
  11813. BfType* resolvedTypeRef = NULL;
  11814. String paramName;
  11815. bool isSplattable = false;
  11816. bool isThis = paramIdx == -1;
  11817. if (isThis)
  11818. {
  11819. paramName = "this";
  11820. if (methodInstance->mIsClosure)
  11821. resolvedTypeRef = mCurMethodState->mClosureState->mClosureType;
  11822. else
  11823. resolvedTypeRef = methodInstance->GetOwner();
  11824. isSplattable = (resolvedTypeRef->IsSplattable()) && (!methodDef->HasNoThisSplat());
  11825. }
  11826. else if (!methodDef->mNoSplat)
  11827. {
  11828. paramName = methodInstance->GetParamName(paramIdx);
  11829. resolvedTypeRef = methodInstance->GetParamType(paramIdx);
  11830. if (resolvedTypeRef->IsMethodRef())
  11831. isSplattable = true;
  11832. else if (resolvedTypeRef->IsSplattable())
  11833. {
  11834. if (resolvedTypeRef->GetSplatCount() + argIdx <= mCompiler->mOptions.mMaxSplatRegs)
  11835. isSplattable = true;
  11836. }
  11837. }
  11838. //
  11839. {
  11840. auto loweredTypeCode = resolvedTypeRef->GetLoweredType();
  11841. if (loweredTypeCode != BfTypeCode_None)
  11842. resolvedTypeRef = GetPrimitiveType(loweredTypeCode);
  11843. }
  11844. auto _SetupParam = [&](const StringImpl& paramName, BfType* resolvedTypeRef)
  11845. {
  11846. mBfIRBuilder->Func_SetParamName(func, argIdx + 1, paramName);
  11847. int addDeref = -1;
  11848. if (resolvedTypeRef->IsRef())
  11849. {
  11850. auto refType = (BfRefType*)resolvedTypeRef;
  11851. auto elementType = refType->mElementType;
  11852. PopulateType(elementType, BfPopulateType_Data);
  11853. addDeref = elementType->mSize;
  11854. if ((addDeref <= 0) && (!elementType->IsValuelessType()))
  11855. AssertErrorState();
  11856. }
  11857. if ((resolvedTypeRef->IsComposite()) && (!resolvedTypeRef->IsTypedPrimitive()))
  11858. {
  11859. if (mCompiler->mOptions.mAllowStructByVal)
  11860. {
  11861. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_ByVal);
  11862. }
  11863. else
  11864. {
  11865. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_NoCapture);
  11866. PopulateType(resolvedTypeRef, BfPopulateType_Data);
  11867. addDeref = resolvedTypeRef->mSize;
  11868. }
  11869. }
  11870. else if (resolvedTypeRef->IsPrimitiveType())
  11871. {
  11872. auto primType = (BfPrimitiveType*)resolvedTypeRef;
  11873. if (primType->mTypeDef->mTypeCode == BfTypeCode_Boolean)
  11874. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_ZExt);
  11875. }
  11876. if (addDeref >= 0)
  11877. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_Dereferencable, addDeref);
  11878. argIdx++;
  11879. };
  11880. if (isSplattable)
  11881. {
  11882. std::function<void(BfType*, const StringImpl&)> checkTypeLambda = [&](BfType* checkType, const StringImpl& curName)
  11883. {
  11884. if (checkType->IsStruct())
  11885. {
  11886. auto checkTypeInstance = checkType->ToTypeInstance();
  11887. if (checkTypeInstance->mBaseType != NULL)
  11888. checkTypeLambda(checkTypeInstance->mBaseType, curName);
  11889. if (checkTypeInstance->mIsUnion)
  11890. {
  11891. BfType* unionInnerType = checkTypeInstance->GetUnionInnerType();
  11892. checkTypeLambda(unionInnerType, curName + "_data");
  11893. }
  11894. else
  11895. {
  11896. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  11897. {
  11898. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  11899. auto fieldDef = fieldInstance->GetFieldDef();
  11900. if (fieldInstance->mDataIdx >= 0)
  11901. {
  11902. checkTypeLambda(fieldInstance->GetResolvedType(), curName + "_" + fieldInstance->GetFieldDef()->mName);
  11903. }
  11904. }
  11905. }
  11906. if (checkTypeInstance->IsEnum())
  11907. {
  11908. mBfIRBuilder->Func_SetParamName(func, argIdx + 1, curName + "_dscr");
  11909. argIdx++;
  11910. }
  11911. }
  11912. else if (checkType->IsMethodRef())
  11913. {
  11914. auto methodRefType = (BfMethodRefType*)checkType;
  11915. BfMethodInstance* methodRefMethodInst = methodRefType->mMethodRef;
  11916. for (int dataIdx = 0; dataIdx < (int)methodRefType->GetCaptureDataCount(); dataIdx++)
  11917. {
  11918. int methodRefParamIdx = methodRefType->GetParamIdxFromDataIdx(dataIdx);
  11919. if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  11920. {
  11921. checkTypeLambda(methodRefType->GetCaptureType(dataIdx), curName + "_" + methodRefMethodInst->GetParamName(methodRefParamIdx));
  11922. }
  11923. else
  11924. {
  11925. _SetupParam(curName + "_" + methodRefMethodInst->GetParamName(methodRefParamIdx), methodRefType->GetCaptureType(dataIdx));
  11926. }
  11927. }
  11928. }
  11929. else if (!checkType->IsValuelessType())
  11930. {
  11931. _SetupParam(curName, checkType);
  11932. }
  11933. };
  11934. checkTypeLambda(resolvedTypeRef, paramName);
  11935. paramIdx++;
  11936. continue;
  11937. }
  11938. _SetupParam(paramName, resolvedTypeRef);
  11939. //argIdx++;
  11940. paramIdx++;
  11941. }
  11942. }
  11943. void BfModule::EmitCtorBody(bool& skipBody)
  11944. {
  11945. auto methodInstance = mCurMethodInstance;
  11946. auto methodDef = methodInstance->mMethodDef;
  11947. auto methodDeclaration = methodDef->mMethodDeclaration;
  11948. auto ctorDeclaration = (BfConstructorDeclaration*)methodDef->mMethodDeclaration;
  11949. auto typeDef = mCurTypeInstance->mTypeDef;
  11950. // Prologue
  11951. mBfIRBuilder->ClearDebugLocation();
  11952. bool hadThisInitializer = false;
  11953. if ((ctorDeclaration != NULL) && (ctorDeclaration->mInitializer != NULL))
  11954. {
  11955. auto targetToken = BfNodeDynCast<BfTokenNode>(ctorDeclaration->mInitializer->mTarget);
  11956. auto targetType = (targetToken->GetToken() == BfToken_This) ? mCurTypeInstance : mCurTypeInstance->mBaseType;
  11957. if (targetToken->GetToken() == BfToken_This)
  11958. {
  11959. hadThisInitializer = true;
  11960. // Since we call a 'this', it's that other ctor's responsibility to fully assign the fields
  11961. mCurMethodState->LocalDefined(GetThisVariable());
  11962. }
  11963. }
  11964. // Zero out memory for default ctor
  11965. if ((methodDeclaration == NULL) && (mCurTypeInstance->IsStruct()))
  11966. {
  11967. if (mCurTypeInstance->IsTypedPrimitive())
  11968. {
  11969. auto thisRef = mCurMethodState->mLocals[0]->mValue;
  11970. mBfIRBuilder->CreateStore(GetDefaultValue(mCurTypeInstance), thisRef);
  11971. }
  11972. else if (mCurTypeInstance->mInstSize > 0)
  11973. {
  11974. BfIRValue fillValue = GetConstValue8(0);
  11975. BfIRValue sizeValue = GetConstValue(mCurTypeInstance->mInstSize);
  11976. auto thisRef = mCurMethodState->mLocals[0]->mValue;
  11977. BfIRValue destBits = mBfIRBuilder->CreateBitCast(thisRef, mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr));
  11978. mBfIRBuilder->CreateMemSet(destBits, fillValue, sizeValue, mCurTypeInstance->mAlign);
  11979. }
  11980. }
  11981. BfAstNode* baseCtorNode = NULL;
  11982. if ((ctorDeclaration != NULL) && (ctorDeclaration->mInitializer != NULL) && (ctorDeclaration->mInitializer->mTarget != NULL))
  11983. baseCtorNode = ctorDeclaration->mInitializer->mTarget;
  11984. else if (methodDef->mBody != NULL)
  11985. baseCtorNode = methodDef->mBody;
  11986. else if (ctorDeclaration != NULL)
  11987. baseCtorNode = ctorDeclaration;
  11988. else if (mCurTypeInstance->mTypeDef->mTypeDeclaration != NULL)
  11989. baseCtorNode = mCurTypeInstance->mTypeDef->mTypeDeclaration->mNameNode;
  11990. else if ((mCurTypeInstance->mBaseType != NULL) && (mCurTypeInstance->mBaseType->mTypeDef->mTypeDeclaration != NULL))
  11991. baseCtorNode = mCurTypeInstance->mBaseType->mTypeDef->mTypeDeclaration;
  11992. else
  11993. baseCtorNode = mContext->mBfObjectType->mTypeDef->mTypeDeclaration;
  11994. if ((!mCurTypeInstance->IsBoxed()) && (methodDef->mMethodType == BfMethodType_Ctor))
  11995. {
  11996. // Call the root type's default ctor (with no body) to initialize its fields and call the chained ctors
  11997. if (methodDef->mDeclaringType->mTypeCode == BfTypeCode_Extension)
  11998. {
  11999. BfMethodDef* defaultCtor = NULL;
  12000. for (auto methodDef : mCurTypeInstance->mTypeDef->mMethods)
  12001. {
  12002. if ((methodDef->mMethodType == BfMethodType_CtorNoBody) && (methodDef->mDeclaringType->mTypeCode != BfTypeCode_Extension))
  12003. {
  12004. defaultCtor = methodDef;
  12005. }
  12006. }
  12007. if (defaultCtor != NULL)
  12008. {
  12009. UpdateSrcPos(mCurTypeInstance->mTypeDef->GetRefNode());
  12010. SetIllegalSrcPos();
  12011. auto moduleMethodInstance = GetMethodInstance(mCurTypeInstance, defaultCtor, BfTypeVector());
  12012. BfExprEvaluator exprEvaluator(this);
  12013. SizedArray<BfIRValue, 1> irArgs;
  12014. exprEvaluator.PushThis(NULL, GetThis(), moduleMethodInstance.mMethodInstance, irArgs);
  12015. exprEvaluator.CreateCall(moduleMethodInstance.mMethodInstance, moduleMethodInstance.mFunc, false, irArgs);
  12016. }
  12017. }
  12018. }
  12019. // Initialize fields (if applicable)
  12020. if (mCurTypeInstance->IsBoxed())
  12021. {
  12022. skipBody = true;
  12023. }
  12024. else if ((methodDef->mMethodType == BfMethodType_Ctor) && (methodDef->mDeclaringType->mTypeCode == BfTypeCode_Extension))
  12025. {
  12026. // Field initializers occur in CtorNoBody methods for extensions
  12027. }
  12028. else if (!hadThisInitializer)
  12029. {
  12030. // If we had a 'this' initializer, that other ctor will have initialized our fields
  12031. if ((!mCompiler->mIsResolveOnly) ||
  12032. (mCompiler->mResolvePassData->mAutoComplete == NULL) ||
  12033. (mCompiler->mResolvePassData->mAutoComplete->mResolveType == BfResolveType_ShowFileSymbolReferences))
  12034. {
  12035. bool hadInlineInitBlock = false;
  12036. BfScopeData scopeData;
  12037. for (auto fieldDef : typeDef->mFields)
  12038. {
  12039. // For extensions, only handle these fields in the appropriate extension
  12040. if ((fieldDef->mDeclaringType->mTypeDeclaration != methodDef->mDeclaringType->mTypeDeclaration))
  12041. continue;
  12042. if ((!fieldDef->mIsConst) && (!fieldDef->mIsStatic))
  12043. {
  12044. auto fieldInst = &mCurTypeInstance->mFieldInstances[fieldDef->mIdx];
  12045. if (!fieldInst->mFieldIncluded)
  12046. continue;
  12047. if (fieldInst->mDataIdx < 0)
  12048. continue;
  12049. if (fieldDef->mInitializer == NULL)
  12050. {
  12051. if (fieldDef->mProtection != BfProtection_Hidden)
  12052. continue;
  12053. if (mCurTypeInstance->IsObject()) // Already zeroed out
  12054. continue;
  12055. }
  12056. if (fieldInst->mResolvedType == NULL)
  12057. {
  12058. BF_ASSERT(mHadBuildError);
  12059. continue;
  12060. }
  12061. if (fieldDef->mInitializer != NULL)
  12062. {
  12063. if (!hadInlineInitBlock)
  12064. {
  12065. if ((mBfIRBuilder->DbgHasInfo()) && (!mCurTypeInstance->IsUnspecializedType()) && (mHasFullDebugInfo))
  12066. {
  12067. UpdateSrcPos(baseCtorNode);
  12068. // 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
  12069. EmitEnsureInstructionAt();
  12070. BfType* thisType = mCurTypeInstance;
  12071. if (thisType->IsValueType())
  12072. thisType = CreateRefType(thisType);
  12073. SizedArray<BfIRMDNode, 1> diParamTypes;
  12074. BfIRMDNode diFuncType = mBfIRBuilder->DbgCreateSubroutineType(diParamTypes);
  12075. mCurMethodState->AddScope(&scopeData);
  12076. NewScopeState();
  12077. int flags = 0;
  12078. mCurMethodState->mCurScope->mDIInlinedAt = mBfIRBuilder->DbgGetCurrentLocation();
  12079. BF_ASSERT(mCurMethodState->mCurScope->mDIInlinedAt);
  12080. // mCurMethodState->mCurScope->mDIInlinedAt may still be null ifwe don't have an explicit ctor
  12081. mCurMethodState->mCurScope->mDIScope = mBfIRBuilder->DbgCreateFunction(mBfIRBuilder->DbgGetTypeInst(mCurTypeInstance), "this$initFields", "", mCurFilePosition.mFileInstance->mDIFile,
  12082. mCurFilePosition.mCurLine + 1, diFuncType, false, true, mCurFilePosition.mCurLine + 1, flags, false, BfIRValue());
  12083. UpdateSrcPos(fieldDef->mInitializer);
  12084. auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(mCurMethodState->mCurScope->mDIScope,
  12085. "this", mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, mBfIRBuilder->DbgGetType(thisType));
  12086. //
  12087. {
  12088. auto loadedThis = GetThis();
  12089. // LLVM can't handle two variables pointing to the same value
  12090. BfIRValue copiedThisPtr;
  12091. copiedThisPtr = CreateAlloca(thisType);
  12092. auto storeInst = mBfIRBuilder->CreateStore(loadedThis.mValue, copiedThisPtr);
  12093. mBfIRBuilder->ClearDebugLocation(storeInst);
  12094. mBfIRBuilder->DbgInsertDeclare(copiedThisPtr, diVariable);
  12095. }
  12096. hadInlineInitBlock = true;
  12097. }
  12098. }
  12099. UpdateSrcPos(fieldDef->mInitializer);
  12100. }
  12101. BfIRValue fieldAddr;
  12102. if (!mCurTypeInstance->IsTypedPrimitive())
  12103. {
  12104. fieldAddr = mBfIRBuilder->CreateInBoundsGEP(mCurMethodState->mLocals[0]->mValue, 0, fieldInst->mDataIdx /*, fieldDef->mName*/);
  12105. }
  12106. else
  12107. {
  12108. AssertErrorState();
  12109. }
  12110. auto assignValue = GetFieldInitializerValue(fieldInst);
  12111. if ((fieldAddr) && (assignValue))
  12112. mBfIRBuilder->CreateStore(assignValue.mValue, fieldAddr);
  12113. }
  12114. }
  12115. if (hadInlineInitBlock)
  12116. {
  12117. RestoreScopeState();
  12118. // This gets set to false because of AddScope but we actually are still in the head block
  12119. mCurMethodState->mInHeadScope = true;
  12120. }
  12121. }
  12122. else // Autocomplete case
  12123. {
  12124. // The reason we can't just do the 'normal' path for this is that the BfTypeInstance here is NOT the
  12125. // autocomplete type instance, so FieldInstance initializer values contain expressions from the full
  12126. // resolve pass, NOT the autocomplete expression
  12127. for (auto tempTypeDef : mCompiler->mResolvePassData->mAutoCompleteTempTypes)
  12128. {
  12129. if (tempTypeDef->mFullName == typeDef->mFullName)
  12130. {
  12131. for (auto fieldDef : tempTypeDef->mFields)
  12132. {
  12133. if ((!fieldDef->mIsStatic) && (fieldDef->mInitializer != NULL) && (mCompiler->mResolvePassData->mSourceClassifier != NULL))
  12134. {
  12135. mCompiler->mResolvePassData->mSourceClassifier->SetElementType(fieldDef->mInitializer, BfSourceElementType_Normal);
  12136. mCompiler->mResolvePassData->mSourceClassifier->VisitChild(fieldDef->mInitializer);
  12137. auto wantType = ResolveTypeRef(fieldDef->mTypeRef);
  12138. if ((wantType != NULL) &&
  12139. ((wantType->IsVar()) || (wantType->IsLet()) || (wantType->IsRef())))
  12140. wantType = NULL;
  12141. CreateValueFromExpression(fieldDef->mInitializer, wantType, BfEvalExprFlags_FieldInitializer);
  12142. }
  12143. }
  12144. }
  12145. }
  12146. // Mark fields from full type with initializers as initialized, to give proper initialization errors within ctor
  12147. for (auto fieldDef : typeDef->mFields)
  12148. {
  12149. if ((!fieldDef->mIsConst) && (!fieldDef->mIsStatic) && (fieldDef->mInitializer != NULL))
  12150. {
  12151. auto fieldInst = &mCurTypeInstance->mFieldInstances[fieldDef->mIdx];
  12152. if (fieldDef->mInitializer != NULL)
  12153. MarkFieldInitialized(fieldInst);
  12154. }
  12155. }
  12156. }
  12157. }
  12158. // Call base ctor (if applicable)
  12159. BfTypeInstance* targetType = NULL;
  12160. BfAstNode* targetRefNode = NULL;
  12161. if (ctorDeclaration != NULL)
  12162. targetRefNode = ctorDeclaration->mInitializer;
  12163. if (auto invocationExpr = BfNodeDynCast<BfInvocationExpression>(targetRefNode))
  12164. targetRefNode = invocationExpr->mTarget;
  12165. if (baseCtorNode != NULL)
  12166. {
  12167. UpdateSrcPos(baseCtorNode);
  12168. }
  12169. if ((ctorDeclaration != NULL) && (ctorDeclaration->mInitializer != NULL))
  12170. {
  12171. auto targetToken = BfNodeDynCast<BfTokenNode>(ctorDeclaration->mInitializer->mTarget);
  12172. targetType = (targetToken->GetToken() == BfToken_This) ? mCurTypeInstance : mCurTypeInstance->mBaseType;
  12173. }
  12174. else if ((mCurTypeInstance->mBaseType != NULL) && (!mCurTypeInstance->IsUnspecializedType()))
  12175. {
  12176. auto baseType = mCurTypeInstance->mBaseType;
  12177. if ((!mCurTypeInstance->IsTypedPrimitive()) &&
  12178. (baseType->mTypeDef != mCompiler->mValueTypeTypeDef) &&
  12179. (baseType->mTypeDef != mCompiler->mBfObjectTypeDef))
  12180. {
  12181. // Try to find a ctor without any params first
  12182. bool foundBaseCtor = false;
  12183. bool hadCtorWithAllDefaults = false;
  12184. for (int pass = 0; pass < 2; pass++)
  12185. {
  12186. for (auto checkMethodDef : baseType->mTypeDef->mMethods)
  12187. {
  12188. bool allowPriv = checkMethodDef->mProtection != BfProtection_Private;
  12189. // Allow calling of the default base ctor if it is implicitly defined
  12190. if ((checkMethodDef->mMethodDeclaration == NULL) && (pass == 1) && (!hadCtorWithAllDefaults))
  12191. allowPriv = true;
  12192. if ((checkMethodDef->mMethodType == BfMethodType_Ctor) && (!checkMethodDef->mIsStatic) && (allowPriv))
  12193. {
  12194. if (checkMethodDef->mParams.size() == 0)
  12195. {
  12196. foundBaseCtor = true;
  12197. if (HasCompiledOutput())
  12198. {
  12199. SizedArray<BfIRValue, 1> args;
  12200. auto ctorBodyMethodInstance = GetMethodInstance(mCurTypeInstance->mBaseType, checkMethodDef, BfTypeVector());
  12201. if (!mCurTypeInstance->mBaseType->IsValuelessType())
  12202. {
  12203. auto basePtr = mBfIRBuilder->CreateBitCast(mCurMethodState->mLocals[0]->mValue, mBfIRBuilder->MapTypeInstPtr(mCurTypeInstance->mBaseType));
  12204. args.push_back(basePtr);
  12205. }
  12206. AddCallDependency(ctorBodyMethodInstance.mMethodInstance, true);
  12207. auto callInst = mBfIRBuilder->CreateCall(ctorBodyMethodInstance.mFunc, args);
  12208. auto callingConv = GetCallingConvention(ctorBodyMethodInstance.mMethodInstance->GetOwner(), ctorBodyMethodInstance.mMethodInstance->mMethodDef);
  12209. if (callingConv != BfIRCallingConv_CDecl)
  12210. mBfIRBuilder->SetCallCallingConv(callInst, callingConv);
  12211. // if (!mCurTypeInstance->mBaseType->IsValuelessType())
  12212. // mBfIRBuilder->SetCallCallingConv(callInst, BfIRCallingConv_ThisCall);
  12213. break;
  12214. }
  12215. }
  12216. else if ((checkMethodDef->mParams[0]->mParamDeclaration != NULL) && (checkMethodDef->mParams[0]->mParamDeclaration->mInitializer != NULL))
  12217. hadCtorWithAllDefaults = true;
  12218. }
  12219. }
  12220. if (foundBaseCtor)
  12221. break;
  12222. }
  12223. if (!foundBaseCtor)
  12224. {
  12225. targetType = mCurTypeInstance->mBaseType;
  12226. if (ctorDeclaration != NULL)
  12227. targetRefNode = ctorDeclaration->mThisToken;
  12228. else if (typeDef->mTypeDeclaration != NULL)
  12229. targetRefNode = typeDef->mTypeDeclaration->mNameNode;
  12230. }
  12231. }
  12232. }
  12233. if (methodDef->mHasAppend)
  12234. {
  12235. mCurMethodState->mCurAppendAlign = methodInstance->mAppendAllocAlign;
  12236. }
  12237. if (targetType != NULL)
  12238. {
  12239. auto autoComplete = mCompiler->GetAutoComplete();
  12240. auto wasCapturingMethodInfo = (autoComplete != NULL) && (autoComplete->mIsCapturingMethodMatchInfo);
  12241. if ((autoComplete != NULL) && (ctorDeclaration != NULL) && (ctorDeclaration->mInitializer != NULL))
  12242. {
  12243. auto invocationExpr = ctorDeclaration->mInitializer;
  12244. autoComplete->CheckInvocation(invocationExpr, invocationExpr->mOpenParen, invocationExpr->mCloseParen, invocationExpr->mCommas);
  12245. }
  12246. BfType* targetThisType = targetType;
  12247. auto target = Cast(targetRefNode, GetThis(), targetThisType);
  12248. BfExprEvaluator exprEvaluator(this);
  12249. BfResolvedArgs argValues;
  12250. if ((ctorDeclaration != NULL) && (ctorDeclaration->mInitializer != NULL))
  12251. {
  12252. argValues.Init(&ctorDeclaration->mInitializer->mArguments);
  12253. if (gDebugStuff)
  12254. {
  12255. OutputDebugStrF("Expr: %@ %d\n", argValues.mArguments->mVals, argValues.mArguments->mSize);
  12256. }
  12257. }
  12258. exprEvaluator.ResolveArgValues(argValues, BfResolveArgFlag_DeferParamEval);
  12259. BfTypedValue appendIdxVal;
  12260. if (methodDef->mHasAppend)
  12261. {
  12262. auto localVar = mCurMethodState->GetRootMethodState()->mLocals[1];
  12263. BF_ASSERT(localVar->mName == "appendIdx");
  12264. auto intRefType = CreateRefType(localVar->mResolvedType);
  12265. appendIdxVal = BfTypedValue(localVar->mValue, intRefType);
  12266. mCurMethodState->mCurAppendAlign = 1; // Don't make any assumptions about how the base leaves the alignment
  12267. }
  12268. exprEvaluator.MatchConstructor(targetRefNode, NULL, target, targetType, argValues, true, methodDef->mHasAppend, &appendIdxVal);
  12269. if (autoComplete != NULL)
  12270. {
  12271. if ((wasCapturingMethodInfo) && (!autoComplete->mIsCapturingMethodMatchInfo))
  12272. {
  12273. if (autoComplete->mMethodMatchInfo != NULL)
  12274. autoComplete->mIsCapturingMethodMatchInfo = true;
  12275. else
  12276. autoComplete->mIsCapturingMethodMatchInfo = false;
  12277. }
  12278. else
  12279. autoComplete->mIsCapturingMethodMatchInfo = false;
  12280. }
  12281. }
  12282. }
  12283. void BfModule::EmitEnumToStringBody()
  12284. {
  12285. auto stringType = ResolveTypeDef(mCompiler->mStringTypeDef);
  12286. auto strVal = CreateAlloca(stringType);
  12287. auto int64StructType = GetPrimitiveStructType(BfTypeCode_Int64);
  12288. BfExprEvaluator exprEvaluator(this);
  12289. auto stringDestAddr = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  12290. BfIRBlock appendBlock = mBfIRBuilder->CreateBlock("append");
  12291. BfIRBlock noMatchBlock = mBfIRBuilder->CreateBlock("noMatch");
  12292. BfIRBlock endBlock = mBfIRBuilder->CreateBlock("end");
  12293. BfType* discriminatorType = NULL;
  12294. BfTypedValue rawPayload;
  12295. BfIRValue enumVal;
  12296. if (mCurTypeInstance->IsPayloadEnum())
  12297. {
  12298. discriminatorType = mCurTypeInstance->GetDiscriminatorType();
  12299. auto enumTypedValue = ExtractValue(GetThis(), NULL, 2);
  12300. enumTypedValue = LoadValue(enumTypedValue);
  12301. enumVal = enumTypedValue.mValue;
  12302. rawPayload = ExtractValue(GetThis(), NULL, 1);
  12303. }
  12304. else
  12305. enumVal = mBfIRBuilder->GetArgument(0);
  12306. Array<BfType*> paramTypes;
  12307. paramTypes.Add(stringType);
  12308. auto appendModuleMethodInstance = GetMethodByName(stringType->ToTypeInstance(), "Append", paramTypes);
  12309. auto switchVal = mBfIRBuilder->CreateSwitch(enumVal, noMatchBlock, (int)mCurTypeInstance->mFieldInstances.size());
  12310. HashSet<int64> handledCases;
  12311. for (auto& fieldInstance : mCurTypeInstance->mFieldInstances)
  12312. {
  12313. if (fieldInstance.mIsEnumPayloadCase)
  12314. {
  12315. int tagId = -fieldInstance.mDataIdx - 1;
  12316. BfIRBlock caseBlock = mBfIRBuilder->CreateBlock("case");
  12317. mBfIRBuilder->AddBlock(caseBlock);
  12318. mBfIRBuilder->SetInsertPoint(caseBlock);
  12319. BF_ASSERT(discriminatorType->IsPrimitiveType());
  12320. auto constVal = mBfIRBuilder->CreateConst(((BfPrimitiveType*)discriminatorType)->mTypeDef->mTypeCode, tagId);
  12321. mBfIRBuilder->AddSwitchCase(switchVal, constVal, caseBlock);
  12322. auto caseStr = GetStringObjectValue(fieldInstance.GetFieldDef()->mName);
  12323. auto stringDestVal = LoadValue(stringDestAddr);
  12324. SizedArray<BfIRValue, 2> args;
  12325. args.Add(stringDestVal.mValue);
  12326. args.Add(caseStr);
  12327. exprEvaluator.CreateCall(appendModuleMethodInstance.mMethodInstance, appendModuleMethodInstance.mFunc, false, args);
  12328. auto payloadType = fieldInstance.mResolvedType->ToTypeInstance();
  12329. BF_ASSERT(payloadType->IsTuple());
  12330. if (payloadType->mFieldInstances.size() != 0)
  12331. {
  12332. auto payload = rawPayload;
  12333. if (payload.mType != payloadType)
  12334. {
  12335. payload = Cast(NULL, payload, payloadType, BfCastFlags_Force);
  12336. }
  12337. auto toStringMethod = GetMethodByName(payloadType->ToTypeInstance(), "ToString");
  12338. SizedArray<BfIRValue, 2> irArgs;
  12339. exprEvaluator.PushThis(NULL, payload, toStringMethod.mMethodInstance, irArgs);
  12340. stringDestVal = LoadValue(stringDestAddr);
  12341. irArgs.Add(stringDestVal.mValue);
  12342. exprEvaluator.CreateCall(toStringMethod.mMethodInstance, toStringMethod.mFunc, true, irArgs);
  12343. }
  12344. mBfIRBuilder->CreateBr(endBlock);
  12345. continue;
  12346. }
  12347. if (fieldInstance.mConstIdx == -1)
  12348. continue;
  12349. auto constant = mCurTypeInstance->mConstHolder->GetConstantById(fieldInstance.mConstIdx);
  12350. if (!handledCases.TryAdd(constant->mInt64, NULL))
  12351. {
  12352. // Duplicate
  12353. continue;
  12354. }
  12355. BfIRBlock caseBlock = mBfIRBuilder->CreateBlock("case");
  12356. mBfIRBuilder->AddBlock(caseBlock);
  12357. mBfIRBuilder->SetInsertPoint(caseBlock);
  12358. BfIRValue constVal = ConstantToCurrent(constant, mCurTypeInstance->mConstHolder, mCurTypeInstance);
  12359. mBfIRBuilder->AddSwitchCase(switchVal, constVal, caseBlock);
  12360. auto caseStr = GetStringObjectValue(fieldInstance.GetFieldDef()->mName);
  12361. mBfIRBuilder->CreateStore(caseStr, strVal);
  12362. mBfIRBuilder->CreateBr(appendBlock);
  12363. }
  12364. mBfIRBuilder->AddBlock(appendBlock);
  12365. mBfIRBuilder->SetInsertPoint(appendBlock);
  12366. SizedArray<BfIRValue, 2> args;
  12367. auto stringDestVal = LoadValue(stringDestAddr);
  12368. args.Add(stringDestVal.mValue);
  12369. args.Add(mBfIRBuilder->CreateLoad(strVal));
  12370. exprEvaluator.CreateCall(appendModuleMethodInstance.mMethodInstance, appendModuleMethodInstance.mFunc, false, args);
  12371. mBfIRBuilder->CreateBr(endBlock);
  12372. mBfIRBuilder->AddBlock(noMatchBlock);
  12373. mBfIRBuilder->SetInsertPoint(noMatchBlock);
  12374. auto int64Val = mBfIRBuilder->CreateNumericCast(enumVal, false, BfTypeCode_Int64);
  12375. auto toStringModuleMethodInstance = GetMethodByName(int64StructType, "ToString", 1);
  12376. args.clear();
  12377. args.Add(int64Val);
  12378. stringDestVal = LoadValue(stringDestAddr);
  12379. args.Add(stringDestVal.mValue);
  12380. exprEvaluator.CreateCall(toStringModuleMethodInstance.mMethodInstance, toStringModuleMethodInstance.mFunc, false, args);
  12381. mBfIRBuilder->CreateBr(endBlock);
  12382. mBfIRBuilder->AddBlock(endBlock);
  12383. mBfIRBuilder->SetInsertPoint(endBlock);
  12384. }
  12385. void BfModule::EmitTupleToStringBody()
  12386. {
  12387. auto stringType = ResolveTypeDef(mCompiler->mStringTypeDef);
  12388. BfExprEvaluator exprEvaluator(this);
  12389. auto stringDestRef = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  12390. Array<BfType*> paramTypes;
  12391. paramTypes.Add(GetPrimitiveType(BfTypeCode_Char8));
  12392. auto appendCharModuleMethodInstance = GetMethodByName(stringType->ToTypeInstance(), "Append", paramTypes);
  12393. paramTypes.Clear();
  12394. paramTypes.Add(stringType);
  12395. auto appendModuleMethodInstance = GetMethodByName(stringType->ToTypeInstance(), "Append", paramTypes);
  12396. auto _AppendChar = [&](char c)
  12397. {
  12398. SizedArray<BfIRValue, 2> args;
  12399. auto stringDestVal = LoadValue(stringDestRef);
  12400. args.Add(stringDestVal.mValue);
  12401. args.Add(mBfIRBuilder->CreateConst(BfTypeCode_Char8, (int)c));
  12402. exprEvaluator.CreateCall(appendCharModuleMethodInstance.mMethodInstance, appendCharModuleMethodInstance.mFunc, false, args);
  12403. };
  12404. int fieldIdx = 0;
  12405. auto thisValue = GetThis();
  12406. auto toStringModuleMethodInstance = GetMethodByName(mContext->mBfObjectType, "ToString", 1);
  12407. auto toStringSafeModuleMethodInstance = GetMethodByName(mContext->mBfObjectType, "ToString", 2);
  12408. BfIRValue commaStr;
  12409. auto iPrintableType = ResolveTypeDef(mCompiler->mIPrintableTypeDef)->ToTypeInstance();
  12410. auto printModuleMethodInstance = GetMethodByName(iPrintableType, "Print");
  12411. _AppendChar('(');
  12412. for (auto& fieldInstance : mCurTypeInstance->mFieldInstances)
  12413. {
  12414. if (fieldInstance.mDataIdx == -1)
  12415. continue;
  12416. if (fieldIdx > 0)
  12417. {
  12418. if (!commaStr)
  12419. commaStr = GetStringObjectValue(", ");
  12420. SizedArray<BfIRValue, 2> args;
  12421. auto stringDestVal = LoadValue(stringDestRef);
  12422. args.Add(stringDestVal.mValue);
  12423. args.Add(commaStr);
  12424. exprEvaluator.CreateCall(appendModuleMethodInstance.mMethodInstance, appendModuleMethodInstance.mFunc, false, args);
  12425. }
  12426. fieldIdx++;
  12427. if (fieldInstance.mResolvedType->IsValuelessType())
  12428. continue;
  12429. BfTypedValue fieldValue = ExtractValue(thisValue, &fieldInstance, fieldInstance.mDataIdx);
  12430. if (fieldValue.mType->IsPrimitiveType())
  12431. {
  12432. fieldValue.mType = GetPrimitiveStructType(((BfPrimitiveType*)fieldValue.mType)->mTypeDef->mTypeCode);
  12433. }
  12434. auto typeInstance = fieldValue.mType->ToTypeInstance();
  12435. if ((typeInstance != NULL) && (TypeIsSubTypeOf(typeInstance, iPrintableType, false)))
  12436. {
  12437. BfExprEvaluator exprEvaluator(this);
  12438. SizedArray<BfResolvedArg, 0> resolvedArgs;
  12439. BfMethodMatcher methodMatcher(NULL, this, printModuleMethodInstance.mMethodInstance, resolvedArgs);
  12440. methodMatcher.mBestMethodDef = printModuleMethodInstance.mMethodInstance->mMethodDef;
  12441. methodMatcher.mBestMethodTypeInstance = iPrintableType;
  12442. methodMatcher.TryDevirtualizeCall(fieldValue);
  12443. BfTypedValue callVal = Cast(NULL, fieldValue, methodMatcher.mBestMethodTypeInstance);
  12444. BfResolvedArg resolvedArg;
  12445. auto stringDestVal = LoadValue(stringDestRef);
  12446. resolvedArg.mTypedValue = stringDestVal;
  12447. resolvedArg.mResolvedType = stringDestVal.mType;
  12448. resolvedArgs.Add(resolvedArg);
  12449. exprEvaluator.CreateCall(&methodMatcher, callVal);
  12450. continue;
  12451. }
  12452. if (fieldValue.mType->IsObjectOrInterface())
  12453. {
  12454. BF_ASSERT(!fieldValue.IsAddr());
  12455. SizedArray<BfIRValue, 2> args;
  12456. args.Add(mBfIRBuilder->CreateBitCast(fieldValue.mValue, mBfIRBuilder->MapType(mContext->mBfObjectType)));
  12457. auto stringDestVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  12458. stringDestVal = LoadValue(stringDestVal);
  12459. args.Add(stringDestVal.mValue);
  12460. exprEvaluator.CreateCall(toStringSafeModuleMethodInstance.mMethodInstance, toStringSafeModuleMethodInstance.mFunc, false, args);
  12461. continue;
  12462. }
  12463. BfExprEvaluator exprEvaluator(this);
  12464. SizedArray<BfResolvedArg, 0> resolvedArgs;
  12465. BfMethodMatcher methodMatcher(NULL, this, toStringModuleMethodInstance.mMethodInstance, resolvedArgs);
  12466. methodMatcher.mBestMethodDef = toStringModuleMethodInstance.mMethodInstance->mMethodDef;
  12467. methodMatcher.mBestMethodTypeInstance = mContext->mBfObjectType;
  12468. methodMatcher.TryDevirtualizeCall(fieldValue);
  12469. if (methodMatcher.mBestMethodTypeInstance == mContext->mBfObjectType)
  12470. {
  12471. AddCallDependency(appendModuleMethodInstance.mMethodInstance);
  12472. AddDependency(fieldValue.mType, mCurTypeInstance, BfDependencyMap::DependencyFlag_Calls);
  12473. // Just append the type name
  12474. String typeName = TypeToString(fieldInstance.mResolvedType);
  12475. auto strVal = GetStringObjectValue(typeName);
  12476. SizedArray<BfIRValue, 2> args;
  12477. auto stringDestVal = LoadValue(stringDestRef);
  12478. args.Add(stringDestVal.mValue);
  12479. args.Add(strVal);
  12480. exprEvaluator.CreateCall(appendModuleMethodInstance.mMethodInstance, appendModuleMethodInstance.mFunc, false, args);
  12481. continue;
  12482. }
  12483. BfTypedValue callVal = Cast(NULL, fieldValue, methodMatcher.mBestMethodTypeInstance);
  12484. BfResolvedArg resolvedArg;
  12485. auto stringDestVal = LoadValue(stringDestRef);
  12486. resolvedArg.mTypedValue = stringDestVal;
  12487. resolvedArg.mResolvedType = stringDestVal.mType;
  12488. resolvedArgs.Add(resolvedArg);
  12489. exprEvaluator.CreateCall(&methodMatcher, callVal);
  12490. }
  12491. _AppendChar(')');
  12492. }
  12493. void BfModule::EmitIteratorBlock(bool& skipBody)
  12494. {
  12495. auto methodInstance = mCurMethodInstance;
  12496. auto methodDef = methodInstance->mMethodDef;
  12497. auto methodDeclaration = methodDef->GetMethodDeclaration();
  12498. auto typeDef = mCurTypeInstance->mTypeDef;
  12499. BfType* innerRetType = NULL;
  12500. BfTypeInstance* usingInterface = NULL;
  12501. auto retTypeInst = mCurMethodInstance->mReturnType->ToGenericTypeInstance();
  12502. if (retTypeInst != NULL)
  12503. {
  12504. if ((retTypeInst->mTypeDef == mCompiler->mGenericIEnumerableTypeDef) ||
  12505. (retTypeInst->mTypeDef == mCompiler->mGenericIEnumeratorTypeDef))
  12506. {
  12507. innerRetType = retTypeInst->mTypeGenericArguments[0];
  12508. }
  12509. }
  12510. if (innerRetType == NULL)
  12511. {
  12512. Fail("Methods with yields must return either System.IEnumerable<T> or System.IEnumerator<T>", methodDeclaration->mReturnType);
  12513. return;
  12514. }
  12515. auto blockBody = BfNodeDynCast<BfBlock>(methodDeclaration->mBody);
  12516. if (blockBody == NULL)
  12517. return;
  12518. }
  12519. void BfModule::EmitGCMarkValue(BfTypedValue markVal, BfModuleMethodInstance markFromGCThreadMethodInstance)
  12520. {
  12521. auto fieldTypeInst = markVal.mType->ToTypeInstance();
  12522. if (fieldTypeInst == NULL)
  12523. return;
  12524. if (!markVal.mType->IsComposite())
  12525. markVal = LoadValue(markVal);
  12526. BfExprEvaluator exprEvaluator(this);
  12527. PopulateType(markVal.mType, BfPopulateType_Data);
  12528. if (markVal.mType->IsObjectOrInterface())
  12529. {
  12530. BfIRValue val = markVal.mValue;
  12531. val = mBfIRBuilder->CreateBitCast(val, mBfIRBuilder->MapType(mContext->mBfObjectType));
  12532. SizedArray<BfIRValue, 1> args;
  12533. args.push_back(val);
  12534. exprEvaluator.CreateCall(markFromGCThreadMethodInstance.mMethodInstance, markFromGCThreadMethodInstance.mFunc, false, args);
  12535. }
  12536. else if ((fieldTypeInst->IsComposite()) && (!fieldTypeInst->IsTypedPrimitive()))
  12537. {
  12538. auto markMemberMethodInstance = GetMethodByName(fieldTypeInst, BF_METHODNAME_MARKMEMBERS, 0, true);
  12539. if (markMemberMethodInstance)
  12540. {
  12541. SizedArray<BfIRValue, 1> args;
  12542. //(1, markVal.mValue);
  12543. //exprEvaluator.PushArg(markVal, args);
  12544. exprEvaluator.PushThis(NULL, markVal, markMemberMethodInstance.mMethodInstance, args);
  12545. exprEvaluator.CreateCall(markMemberMethodInstance.mMethodInstance, markMemberMethodInstance.mFunc, false, args);
  12546. }
  12547. }
  12548. }
  12549. void BfModule::CallChainedMethods(BfMethodInstance* methodInstance, bool reverse)
  12550. {
  12551. Array<BfMethodInstance*> methodInstances;
  12552. for (int methodIdx = 0; methodIdx < (int)mCurTypeInstance->mMethodInstanceGroups.size(); methodIdx++)
  12553. {
  12554. auto& methodInstGroup = mCurTypeInstance->mMethodInstanceGroups[methodIdx];
  12555. auto chainedMethodInst = methodInstGroup.mDefault;
  12556. if ((chainedMethodInst != NULL) && (chainedMethodInst->mChainType == BfMethodChainType_ChainMember))
  12557. {
  12558. if ((chainedMethodInst->mMethodDef->mIsStatic == methodInstance->mMethodDef->mIsStatic) &&
  12559. (CompareMethodSignatures(methodInstance, chainedMethodInst)))
  12560. {
  12561. methodInstances.push_back(chainedMethodInst);
  12562. }
  12563. }
  12564. }
  12565. std::stable_sort(methodInstances.begin(), methodInstances.end(),
  12566. [&](BfMethodInstance* lhs, BfMethodInstance* rhs)
  12567. {
  12568. bool isBetter;
  12569. bool isWorse;
  12570. CompareDeclTypes(lhs->mMethodDef->mDeclaringType, rhs->mMethodDef->mDeclaringType, isBetter, isWorse);
  12571. if (isBetter == isWorse)
  12572. {
  12573. return false;
  12574. }
  12575. return isWorse;
  12576. });
  12577. if (reverse)
  12578. std::reverse(methodInstances.begin(), methodInstances.end());
  12579. for (auto chainedMethodInst : methodInstances)
  12580. {
  12581. auto declModule = this;
  12582. BfGetMethodInstanceFlags flags = BfGetMethodInstanceFlag_None;
  12583. auto moduleMethodInst = declModule->GetMethodInstance(mCurTypeInstance, chainedMethodInst->mMethodDef, BfTypeVector(), flags);
  12584. BfExprEvaluator exprEvaluator(this);
  12585. SizedArray<BfIRValue, 1> args;
  12586. exprEvaluator.PushThis(chainedMethodInst->mMethodDef->GetRefNode(), GetThis(), chainedMethodInst, args);
  12587. exprEvaluator.CreateCall(moduleMethodInst.mMethodInstance, moduleMethodInst.mFunc, true, args);
  12588. }
  12589. }
  12590. void BfModule::AddHotDataReferences(BfHotDataReferenceBuilder* builder)
  12591. {
  12592. BF_ASSERT(mCurMethodInstance->mIsReified);
  12593. if (mCurTypeInstance->mHotTypeData == NULL)
  12594. mCurTypeInstance->mHotTypeData = new BfHotTypeData();
  12595. auto hotMethod = mCurMethodInstance->mHotMethod;
  12596. for (auto depData : hotMethod->mReferences)
  12597. {
  12598. // Only virtual decls are allowed to already be there
  12599. BF_ASSERT((depData->mDataKind == BfHotDepDataKind_VirtualDecl) || (depData->mDataKind == BfHotDepDataKind_DupMethod));
  12600. }
  12601. BF_ASSERT(hotMethod->mSrcTypeVersion != NULL);
  12602. int prevSize = (int)hotMethod->mReferences.size();
  12603. int refCount = (int)(prevSize + builder->mUsedData.size() + builder->mCalledMethods.size() + builder->mDevirtualizedCalledMethods.size());
  12604. if (!mCurMethodInstance->mMethodDef->mIsStatic)
  12605. refCount++;
  12606. hotMethod->mReferences.Reserve(refCount);
  12607. if (!mCurMethodInstance->mMethodDef->mIsStatic)
  12608. {
  12609. auto hotThis = mCompiler->mHotData->GetThisType(mCurMethodInstance->GetOwner()->mHotTypeData->GetLatestVersion());
  12610. hotThis->mRefCount++;
  12611. hotMethod->mReferences.Insert(0, hotThis);
  12612. prevSize++;
  12613. }
  12614. for (auto val : builder->mAllocatedData)
  12615. {
  12616. auto hotAllocation = mCompiler->mHotData->GetAllocation(val);
  12617. hotMethod->mReferences.Add(hotAllocation);
  12618. }
  12619. for (auto val : builder->mUsedData)
  12620. hotMethod->mReferences.Add(val);
  12621. for (auto val : builder->mCalledMethods)
  12622. hotMethod->mReferences.Add(val);
  12623. for (auto val : builder->mDevirtualizedCalledMethods)
  12624. {
  12625. auto devirtualizedMethod = mCompiler->mHotData->GetDevirtualizedMethod(val);
  12626. hotMethod->mReferences.Add(devirtualizedMethod);
  12627. }
  12628. for (auto val : builder->mFunctionPtrs)
  12629. {
  12630. auto funcRef = mCompiler->mHotData->GetFunctionReference(val);
  12631. hotMethod->mReferences.Add(funcRef);
  12632. }
  12633. for (auto val : builder->mInnerMethods)
  12634. {
  12635. auto innerMethod = mCompiler->mHotData->GetInnerMethod(val);
  12636. hotMethod->mReferences.Add(innerMethod);
  12637. }
  12638. for (int refIdx = prevSize; refIdx < (int)hotMethod->mReferences.size(); refIdx++)
  12639. {
  12640. auto depData = hotMethod->mReferences[refIdx];
  12641. BF_ASSERT(depData != NULL);
  12642. depData->mRefCount++;
  12643. }
  12644. //hotMethod->mReferences.Sort([](BfHotDepData* lhs, BfHotDepData* rhs) { return lhs < rhs; });
  12645. }
  12646. void BfModule::ProcessMethod_SetupParams(BfMethodInstance* methodInstance, BfType* thisType, bool wantsDIData, SizedArrayImpl<BfIRMDNode>* diParams)
  12647. {
  12648. auto methodDef = methodInstance->mMethodDef;
  12649. auto methodDeclaration = methodDef->mMethodDeclaration;
  12650. bool isThisStruct = false;
  12651. if (thisType != NULL)
  12652. isThisStruct = thisType->IsStruct() && !thisType->IsTypedPrimitive();
  12653. int argIdx = 0;
  12654. if (methodInstance->HasStructRet())
  12655. argIdx++;
  12656. if (!methodDef->mIsStatic)
  12657. {
  12658. BfLocalVariable* paramVar = new BfLocalVariable();
  12659. paramVar->mResolvedType = thisType;
  12660. paramVar->mName = "this";
  12661. if (!thisType->IsValuelessType())
  12662. paramVar->mValue = mBfIRBuilder->GetArgument(argIdx);
  12663. else
  12664. paramVar->mValue = mBfIRBuilder->GetFakeVal();
  12665. if ((thisType->IsComposite()) && (!methodDef->HasNoThisSplat()))
  12666. {
  12667. if (thisType->IsSplattable())
  12668. paramVar->mIsSplat = true;
  12669. else
  12670. paramVar->mIsLowered = thisType->GetLoweredType() != BfTypeCode_None;
  12671. }
  12672. auto thisTypeInst = thisType->ToTypeInstance();
  12673. paramVar->mIsStruct = isThisStruct;
  12674. paramVar->mAddr = BfIRValue();
  12675. paramVar->mIsThis = true;
  12676. paramVar->mParamIdx = -1;
  12677. if ((methodDef->mMethodType == BfMethodType_Ctor) && (mCurTypeInstance->IsStruct()))
  12678. {
  12679. paramVar->mIsAssigned = false;
  12680. }
  12681. else
  12682. {
  12683. paramVar->mIsAssigned = true;
  12684. }
  12685. paramVar->mReadFromId = -1;
  12686. paramVar->Init();
  12687. if (methodDeclaration == NULL)
  12688. UseDefaultSrcPos();
  12689. AddLocalVariableDef(paramVar);
  12690. if (!thisType->IsValuelessType())
  12691. {
  12692. if (wantsDIData)
  12693. {
  12694. BfType* thisPtrType = thisType;
  12695. auto diType = mBfIRBuilder->DbgGetType(thisPtrType);
  12696. if (!thisType->IsValueType())
  12697. diType = mBfIRBuilder->DbgCreateArtificialType(diType);
  12698. diParams->push_back(diType);
  12699. }
  12700. if (paramVar->mIsSplat)
  12701. {
  12702. BfTypeUtils::SplatIterate([&](BfType* checkType) { argIdx++; }, paramVar->mResolvedType);
  12703. }
  12704. else
  12705. {
  12706. argIdx++;
  12707. }
  12708. }
  12709. }
  12710. bool hadParams = false;
  12711. bool hasDefault = false;
  12712. int compositeVariableIdx = -1;
  12713. int paramIdx = 0;
  12714. for (paramIdx = 0; paramIdx < methodInstance->GetParamCount(); paramIdx++)
  12715. {
  12716. // We already issues a type error for this param if we had one in declaration processing
  12717. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, true);
  12718. BfLocalVariable* paramVar = new BfLocalVariable();
  12719. bool isParamSkipped = methodInstance->IsParamSkipped(paramIdx);
  12720. BfType* unresolvedType = methodInstance->GetParamType(paramIdx, false);
  12721. if (unresolvedType == NULL)
  12722. {
  12723. AssertErrorState();
  12724. unresolvedType = mContext->mBfObjectType;
  12725. paramVar->mParamFailed = true;
  12726. }
  12727. auto resolvedType = methodInstance->GetParamType(paramIdx, true);
  12728. prevIgnoreErrors.Restore();
  12729. PopulateType(resolvedType, BfPopulateType_Declaration);
  12730. paramVar->mResolvedType = resolvedType;
  12731. paramVar->mName = methodInstance->GetParamName(paramIdx);
  12732. paramVar->mNameNode = methodInstance->GetParamNameNode(paramIdx);
  12733. if (!isParamSkipped)
  12734. {
  12735. paramVar->mValue = mBfIRBuilder->GetArgument(argIdx);
  12736. if (resolvedType->IsMethodRef())
  12737. {
  12738. paramVar->mIsSplat = true;
  12739. }
  12740. else if (resolvedType->IsComposite() && resolvedType->IsSplattable())
  12741. {
  12742. int splatCount = resolvedType->GetSplatCount();
  12743. if (argIdx + splatCount <= mCompiler->mOptions.mMaxSplatRegs)
  12744. paramVar->mIsSplat = true;
  12745. }
  12746. }
  12747. else
  12748. {
  12749. paramVar->mIsSplat = true; // Treat skipped (valueless) as a splat
  12750. paramVar->mValue = mBfIRBuilder->GetFakeVal();
  12751. }
  12752. paramVar->mIsLowered = resolvedType->GetLoweredType() != BfTypeCode_None;
  12753. paramVar->mIsStruct = resolvedType->IsComposite() && !resolvedType->IsTypedPrimitive();
  12754. paramVar->mParamIdx = paramIdx;
  12755. paramVar->mIsImplicitParam = methodInstance->IsImplicitCapture(paramIdx);
  12756. paramVar->mReadFromId = 0;
  12757. if (resolvedType->IsRef())
  12758. {
  12759. auto refType = (BfRefType*)resolvedType;
  12760. paramVar->mIsAssigned = refType->mRefKind != BfRefType::RefKind_Out;
  12761. }
  12762. else
  12763. {
  12764. paramVar->mIsAssigned = true;
  12765. if (methodDef->mMethodType != BfMethodType_Mixin)
  12766. paramVar->mIsReadOnly = true;
  12767. }
  12768. if (paramVar->mResolvedType->IsGenericParam())
  12769. {
  12770. auto genericParamInst = GetGenericParamInstance((BfGenericParamType*)paramVar->mResolvedType);
  12771. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  12772. {
  12773. auto typedVal = GetDefaultTypedValue(genericParamInst->mTypeConstraint, false, BfDefaultValueKind_Undef);
  12774. paramVar->mResolvedType = typedVal.mType;
  12775. paramVar->mConstValue = typedVal.mValue;
  12776. }
  12777. }
  12778. if (paramVar->mResolvedType->IsConstExprValue())
  12779. {
  12780. BfConstExprValueType* constExprValueType = (BfConstExprValueType*)paramVar->mResolvedType;
  12781. auto unspecializedMethodInstance = GetUnspecializedMethodInstance(methodInstance);
  12782. auto unspecParamType = unspecializedMethodInstance->GetParamType(paramIdx);
  12783. BF_ASSERT(unspecParamType->IsGenericParam());
  12784. if (unspecParamType->IsGenericParam())
  12785. {
  12786. BfGenericParamType* genericParamType = (BfGenericParamType*)unspecParamType;
  12787. if (genericParamType->mGenericParamKind == BfGenericParamKind_Method)
  12788. {
  12789. auto genericParamInst = unspecializedMethodInstance->mMethodInfoEx->mGenericParams[genericParamType->mGenericParamIdx];
  12790. if (genericParamInst->mTypeConstraint != NULL)
  12791. {
  12792. BfExprEvaluator exprEvaluator(this);
  12793. exprEvaluator.mExpectingType = genericParamInst->mTypeConstraint;
  12794. exprEvaluator.GetLiteral(NULL, constExprValueType->mValue);
  12795. auto checkType = genericParamInst->mTypeConstraint;
  12796. if (checkType->IsTypedPrimitive())
  12797. checkType = checkType->GetUnderlyingType();
  12798. if (exprEvaluator.mResult.mType == checkType)
  12799. {
  12800. paramVar->mResolvedType = genericParamInst->mTypeConstraint;
  12801. paramVar->mConstValue = exprEvaluator.mResult.mValue;
  12802. BF_ASSERT(paramVar->mConstValue.IsConst());
  12803. }
  12804. else
  12805. {
  12806. AssertErrorState();
  12807. paramVar->mResolvedType = genericParamInst->mTypeConstraint;
  12808. paramVar->mConstValue = GetDefaultValue(genericParamInst->mTypeConstraint);
  12809. }
  12810. }
  12811. }
  12812. }
  12813. //BF_ASSERT(!paramVar->mResolvedType->IsConstExprValue());
  12814. if (paramVar->mResolvedType->IsConstExprValue())
  12815. {
  12816. Fail("Invalid use of constant expression", methodInstance->GetParamTypeRef(paramIdx));
  12817. //AssertErrorState();
  12818. paramVar->mResolvedType = GetPrimitiveType(BfTypeCode_IntPtr);
  12819. paramVar->mConstValue = GetDefaultValue(paramVar->mResolvedType);
  12820. }
  12821. }
  12822. if (methodInstance->GetParamKind(paramIdx) == BfParamKind_DelegateParam)
  12823. {
  12824. if (compositeVariableIdx == -1)
  12825. {
  12826. compositeVariableIdx = (int)mCurMethodState->mLocals.size();
  12827. BfLocalVariable* localVar = new BfLocalVariable();
  12828. auto paramInst = &methodInstance->mParams[paramIdx];
  12829. auto paramDef = methodDef->mParams[paramInst->mParamDefIdx];
  12830. localVar->mName = paramDef->mName;
  12831. localVar->mResolvedType = ResolveTypeRef(paramDef->mTypeRef, BfPopulateType_Declaration, BfResolveTypeRefFlag_NoResolveGenericParam);
  12832. localVar->mCompositeCount = 0;
  12833. DoAddLocalVariable(localVar);
  12834. }
  12835. mCurMethodState->mLocals[compositeVariableIdx]->mCompositeCount++;
  12836. }
  12837. CheckVariableDef(paramVar);
  12838. paramVar->Init();
  12839. AddLocalVariableDef(paramVar);
  12840. if (!isParamSkipped)
  12841. {
  12842. if (wantsDIData)
  12843. diParams->push_back(mBfIRBuilder->DbgGetType(resolvedType));
  12844. if (paramVar->mIsSplat)
  12845. {
  12846. BfTypeUtils::SplatIterate([&](BfType* checkType) { argIdx++; }, paramVar->mResolvedType);
  12847. }
  12848. else
  12849. {
  12850. argIdx++;
  12851. }
  12852. }
  12853. }
  12854. // Try to find an ending delegate params composite
  12855. if ((compositeVariableIdx == -1) && (methodDef->mParams.size() > 0))
  12856. {
  12857. auto paramDef = methodDef->mParams.back();
  12858. if (paramDef->mParamKind == BfParamKind_Params)
  12859. {
  12860. auto paramsType = ResolveTypeRef(paramDef->mTypeRef, BfPopulateType_Declaration, BfResolveTypeRefFlag_NoResolveGenericParam);
  12861. if (paramsType == NULL)
  12862. {
  12863. AssertErrorState();
  12864. }
  12865. else if (paramsType->IsGenericParam())
  12866. {
  12867. auto genericParamInstance = GetGenericParamInstance((BfGenericParamType*)paramsType);
  12868. if (genericParamInstance->mTypeConstraint != NULL)
  12869. {
  12870. auto typeInstConstraint = genericParamInstance->mTypeConstraint->ToTypeInstance();
  12871. if ((genericParamInstance->mTypeConstraint->IsDelegate()) || (genericParamInstance->mTypeConstraint->IsFunction()) ||
  12872. ((typeInstConstraint != NULL) &&
  12873. ((typeInstConstraint->mTypeDef == mCompiler->mDelegateTypeDef) || (typeInstConstraint->mTypeDef == mCompiler->mFunctionTypeDef))))
  12874. {
  12875. BfLocalVariable* localVar = new BfLocalVariable();
  12876. localVar->mName = paramDef->mName;
  12877. localVar->mResolvedType = paramsType;
  12878. localVar->mCompositeCount = 0;
  12879. DoAddLocalVariable(localVar);
  12880. }
  12881. }
  12882. }
  12883. else if (paramsType->IsDelegate())
  12884. {
  12885. BfMethodInstance* invokeMethodInstance = GetRawMethodInstanceAtIdx(paramsType->ToTypeInstance(), 0, "Invoke");
  12886. if (invokeMethodInstance != NULL)
  12887. {
  12888. // This is only for the case where the delegate didn't actually have any params so the composite is zero-sized
  12889. // and wasn't cleared by the preceding loop
  12890. BF_ASSERT(invokeMethodInstance->GetParamCount() == 0);
  12891. BfLocalVariable* localVar = new BfLocalVariable();
  12892. localVar->mName = paramDef->mName;
  12893. localVar->mResolvedType = paramsType;
  12894. localVar->mCompositeCount = 0;
  12895. DoAddLocalVariable(localVar);
  12896. }
  12897. }
  12898. }
  12899. }
  12900. }
  12901. void BfModule::ProcessMethod_ProcessDeferredLocals(int startIdx)
  12902. {
  12903. // if (mCurMethodState->mPrevMethodState != NULL) // Re-entry
  12904. // return;
  12905. auto _ClearState = [&]()
  12906. {
  12907. mCurMethodState->mLocalMethods.Clear();
  12908. for (auto& local : mCurMethodState->mLocals)
  12909. delete local;
  12910. mCurMethodState->mLocals.Clear();
  12911. mCurMethodState->mLocalVarSet.Clear();
  12912. };
  12913. // 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
  12914. // we show errors in the capture phase. If we somehow pass the capture phase without error then this method WILL show any errors here,
  12915. // however (compiler bug), so this is the safest way
  12916. if (!mCurMethodState->mDeferredLocalMethods.IsEmpty())
  12917. {
  12918. for (int deferredLocalMethodIdx = 0; deferredLocalMethodIdx < (int)mCurMethodState->mDeferredLocalMethods.size(); deferredLocalMethodIdx++)
  12919. {
  12920. auto deferredLocalMethod = mCurMethodState->mDeferredLocalMethods[deferredLocalMethodIdx];
  12921. BfLogSysM("Processing deferred local method %p\n", deferredLocalMethod);
  12922. if (!mHadBuildError)
  12923. {
  12924. // Process as a closure - that allows us to look back and see the const locals and stuff
  12925. BfClosureState closureState;
  12926. mCurMethodState->mClosureState = &closureState;
  12927. closureState.mConstLocals = deferredLocalMethod->mConstLocals;
  12928. closureState.mReturnType = deferredLocalMethod->mMethodInstance->mReturnType;
  12929. closureState.mActiveDeferredLocalMethod = deferredLocalMethod;
  12930. closureState.mLocalMethod = deferredLocalMethod->mLocalMethod;
  12931. if (deferredLocalMethod->mMethodInstance->mMethodInfoEx != NULL)
  12932. closureState.mClosureInstanceInfo = deferredLocalMethod->mMethodInstance->mMethodInfoEx->mClosureInstanceInfo;
  12933. mCurMethodState->mMixinState = deferredLocalMethod->mLocalMethod->mDeclMixinState;
  12934. _ClearState();
  12935. for (auto& constLocal : deferredLocalMethod->mConstLocals)
  12936. {
  12937. auto localVar = new BfLocalVariable();
  12938. *localVar = constLocal;
  12939. DoAddLocalVariable(localVar);
  12940. }
  12941. mCurMethodState->mLocalMethods = deferredLocalMethod->mLocalMethods;
  12942. bool doProcess = !mCompiler->mCanceling;
  12943. if (doProcess)
  12944. {
  12945. BP_ZONE_F("ProcessMethod local %s", deferredLocalMethod->mMethodInstance->mMethodDef->mName.c_str());
  12946. ProcessMethod(deferredLocalMethod->mMethodInstance);
  12947. }
  12948. }
  12949. delete deferredLocalMethod;
  12950. mSystem->CheckLockYield();
  12951. }
  12952. }
  12953. for (auto& kv : mCurMethodState->mLocalMethodCache)
  12954. {
  12955. BF_ASSERT((kv.mValue->mMethodDef == NULL) || (kv.mKey == kv.mValue->mMethodDef->mName));
  12956. }
  12957. if ((!mCurMethodState->mDeferredLambdaInstances.IsEmpty()) && (!mHadBuildError))
  12958. {
  12959. for (int deferredLambdaIdx = 0; deferredLambdaIdx < (int)mCurMethodState->mDeferredLambdaInstances.size(); deferredLambdaIdx++)
  12960. {
  12961. auto lambdaInstance = mCurMethodState->mDeferredLambdaInstances[deferredLambdaIdx];
  12962. BfLogSysM("Processing deferred lambdaInstance %p\n", lambdaInstance);
  12963. BfClosureState closureState;
  12964. mCurMethodState->mClosureState = &closureState;
  12965. //closureState.mConstLocals = deferredLocalMethod->mConstLocals;
  12966. closureState.mReturnType = lambdaInstance->mMethodInstance->mReturnType;
  12967. if (lambdaInstance->mClosureTypeInstance != NULL)
  12968. closureState.mClosureType = lambdaInstance->mClosureTypeInstance;
  12969. else
  12970. closureState.mClosureType = lambdaInstance->mDelegateTypeInstance;
  12971. closureState.mClosureInstanceInfo = lambdaInstance->mMethodInstance->mMethodInfoEx->mClosureInstanceInfo;
  12972. mCurMethodState->mMixinState = lambdaInstance->mDeclMixinState;
  12973. _ClearState();
  12974. for (auto& constLocal : lambdaInstance->mConstLocals)
  12975. {
  12976. //if (constLocal.mIsThis)
  12977. {
  12978. // Valueless 'this'
  12979. closureState.mConstLocals.Add(constLocal);
  12980. }
  12981. /*else
  12982. {
  12983. auto localVar = new BfLocalVariable();
  12984. *localVar = constLocal;
  12985. DoAddLocalVariable(localVar);
  12986. }*/
  12987. }
  12988. BfMethodInstanceGroup methodInstanceGroup;
  12989. methodInstanceGroup.mOwner = mCurTypeInstance;
  12990. methodInstanceGroup.mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  12991. bool doProcess = !mCompiler->mCanceling;
  12992. if (doProcess)
  12993. {
  12994. BP_ZONE_F("ProcessMethod lambdaInstance %s", lambdaInstance->mMethodInstance->mMethodDef->mName.c_str());
  12995. lambdaInstance->mMethodInstance->mMethodInstanceGroup = &methodInstanceGroup;
  12996. ProcessMethod(lambdaInstance->mMethodInstance);
  12997. if (lambdaInstance->mDtorMethodInstance != NULL)
  12998. {
  12999. lambdaInstance->mDtorMethodInstance->mMethodInstanceGroup = &methodInstanceGroup;
  13000. ProcessMethod(lambdaInstance->mDtorMethodInstance);
  13001. }
  13002. }
  13003. }
  13004. mSystem->CheckLockYield();
  13005. }
  13006. }
  13007. void BfModule::EmitGCMarkValue(BfTypedValue& thisValue, BfType* checkType, int memberDepth, int curOffset, HashSet<int>& objectOffsets, BfModuleMethodInstance markFromGCThreadMethodInstance)
  13008. {
  13009. if (checkType->IsComposite())
  13010. PopulateType(checkType, BfPopulateType_Data);
  13011. if (!checkType->WantsGCMarking())
  13012. return;
  13013. auto typeInstance = checkType->ToTypeInstance();
  13014. bool callMarkMethod = false;
  13015. // Call the actual marking method
  13016. if (memberDepth == 0)
  13017. {
  13018. // Don't call marking method on self
  13019. }
  13020. else if (checkType->IsObjectOrInterface())
  13021. {
  13022. if (!objectOffsets.Add(curOffset))
  13023. {
  13024. return;
  13025. }
  13026. callMarkMethod = true;
  13027. }
  13028. else if (checkType->IsSizedArray())
  13029. {
  13030. callMarkMethod = true;
  13031. }
  13032. else if (typeInstance != NULL)
  13033. {
  13034. typeInstance->mTypeDef->PopulateMemberSets();
  13035. BfMemberSetEntry* entry = NULL;
  13036. BfMethodDef* methodDef = NULL;
  13037. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(String(BF_METHODNAME_MARKMEMBERS), &entry))
  13038. {
  13039. methodDef = (BfMethodDef*)entry->mMemberDef;
  13040. if (methodDef->HasBody())
  13041. {
  13042. callMarkMethod = true;
  13043. }
  13044. }
  13045. }
  13046. if (callMarkMethod)
  13047. {
  13048. BfTypedValue markValue;
  13049. auto memberType = checkType;
  13050. if (memberType->IsObjectOrInterface())
  13051. memberType = mContext->mBfObjectType; // Just to avoid that extra cast for the call itself
  13052. auto memberPtrType = CreatePointerType(memberType);
  13053. if (curOffset == 0)
  13054. {
  13055. markValue = BfTypedValue(mBfIRBuilder->CreateBitCast(thisValue.mValue, mBfIRBuilder->MapType(memberPtrType)), memberType, true);
  13056. }
  13057. else
  13058. {
  13059. if (!thisValue.mType->IsPointer())
  13060. {
  13061. auto int8Type = GetPrimitiveType(BfTypeCode_UInt8);
  13062. auto int8PtrType = CreatePointerType(int8Type);
  13063. thisValue = BfTypedValue(mBfIRBuilder->CreateBitCast(thisValue.mValue, mBfIRBuilder->MapType(int8PtrType)), int8PtrType);
  13064. }
  13065. auto offsetValue = mBfIRBuilder->CreateInBoundsGEP(thisValue.mValue, curOffset);
  13066. markValue = BfTypedValue(mBfIRBuilder->CreateBitCast(offsetValue, mBfIRBuilder->MapType(memberPtrType)), memberType, true);
  13067. }
  13068. EmitGCMarkValue(markValue, markFromGCThreadMethodInstance);
  13069. return;
  13070. }
  13071. auto methodDef = mCurMethodInstance->mMethodDef;
  13072. if (checkType->IsPayloadEnum())
  13073. {
  13074. for (auto& fieldInst : typeInstance->mFieldInstances)
  13075. {
  13076. if (!fieldInst.mIsEnumPayloadCase)
  13077. continue;
  13078. auto fieldDef = fieldInst.GetFieldDef();
  13079. EmitGCMarkValue(thisValue, fieldInst.mResolvedType, memberDepth + 1, curOffset, objectOffsets, markFromGCThreadMethodInstance);
  13080. }
  13081. return;
  13082. }
  13083. if (typeInstance == NULL)
  13084. return;
  13085. for (auto& fieldInst : typeInstance->mFieldInstances)
  13086. {
  13087. auto fieldDef = fieldInst.GetFieldDef();
  13088. if (fieldDef == NULL)
  13089. continue;
  13090. if (fieldDef->mIsStatic)
  13091. continue;
  13092. if (typeInstance == mCurTypeInstance)
  13093. {
  13094. // Note: we don't do method chaining when we are marking members of members. Theoretically this means
  13095. // we may be marking member values that can never contain a value anyway, but this is benign
  13096. if ((fieldDef->mDeclaringType->mTypeDeclaration != methodDef->mDeclaringType->mTypeDeclaration))
  13097. continue;
  13098. }
  13099. EmitGCMarkValue(thisValue, fieldInst.mResolvedType, memberDepth + 1, curOffset + fieldInst.mDataOffset, objectOffsets, markFromGCThreadMethodInstance);
  13100. }
  13101. if ((typeInstance->mBaseType != NULL) && (typeInstance->mBaseType != mContext->mBfObjectType))
  13102. {
  13103. EmitGCMarkValue(thisValue, typeInstance->mBaseType, memberDepth, curOffset, objectOffsets, markFromGCThreadMethodInstance);
  13104. }
  13105. }
  13106. void BfModule::EmitGCMarkMembers()
  13107. {
  13108. auto methodDef = mCurMethodInstance->mMethodDef;
  13109. auto gcType = ResolveTypeDef(mCompiler->mGCTypeDef, BfPopulateType_DataAndMethods);
  13110. BfModuleMethodInstance markFromGCThreadMethodInstance;
  13111. if (gcType != NULL)
  13112. markFromGCThreadMethodInstance = GetMethodByName(gcType->ToTypeInstance(), "Mark", 1);
  13113. if ((markFromGCThreadMethodInstance.mMethodInstance != NULL) && (!mCurMethodInstance->mIsUnspecialized))
  13114. {
  13115. if (mCurTypeInstance->IsBoxed())
  13116. {
  13117. // This already gets filled in by the normal boxed forwarding
  13118. }
  13119. else
  13120. {
  13121. auto thisValue = GetThis();
  13122. if (thisValue.IsSplat())
  13123. {
  13124. BfIRFunction func = mCurMethodInstance->mIRFunction;
  13125. int argIdx = 0;
  13126. std::function<void(BfType*)> checkTypeLambda = [&](BfType* checkType)
  13127. {
  13128. if (checkType->IsStruct())
  13129. {
  13130. auto checkTypeInstance = checkType->ToTypeInstance();
  13131. if (checkTypeInstance->mBaseType != NULL)
  13132. checkTypeLambda(checkTypeInstance->mBaseType);
  13133. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  13134. {
  13135. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  13136. if (fieldInstance->mDataIdx >= 0)
  13137. checkTypeLambda(fieldInstance->GetResolvedType());
  13138. }
  13139. }
  13140. else if (checkType->IsMethodRef())
  13141. {
  13142. BF_FATAL("Not handled");
  13143. }
  13144. else if (checkType->WantsGCMarking())
  13145. {
  13146. BfTypedValue markValue(mBfIRBuilder->GetArgument(argIdx), checkType);
  13147. EmitGCMarkValue(markValue, markFromGCThreadMethodInstance);
  13148. argIdx++;
  13149. }
  13150. };
  13151. checkTypeLambda(thisValue.mType);
  13152. }
  13153. else if (!methodDef->mIsStatic)
  13154. {
  13155. if ((mCurTypeInstance->mBaseType != NULL) && (!mCurTypeInstance->IsTypedPrimitive()) && (mCurTypeInstance->mBaseType->WantsGCMarking()))
  13156. {
  13157. BfModuleMethodInstance moduleMethodInst = GetMethodByName(mCurTypeInstance->mBaseType, BF_METHODNAME_MARKMEMBERS, 0, true);
  13158. if (moduleMethodInst)
  13159. {
  13160. auto methodBaseType = moduleMethodInst.mMethodInstance->GetOwner();
  13161. if (methodBaseType != mContext->mBfObjectType)
  13162. {
  13163. auto thisValue = GetThis();
  13164. auto baseValue = Cast(NULL, thisValue, methodBaseType, BfCastFlags_Explicit);
  13165. SizedArray<BfIRValue, 1> args;
  13166. if (moduleMethodInst.mMethodInstance->GetParamIsSplat(-1))
  13167. {
  13168. BfExprEvaluator exprEvaluator(this);
  13169. exprEvaluator.SplatArgs(baseValue, args);
  13170. }
  13171. else
  13172. {
  13173. args.push_back(baseValue.mValue);
  13174. }
  13175. mBfIRBuilder->CreateCall(moduleMethodInst.mFunc, args);
  13176. }
  13177. }
  13178. }
  13179. }
  13180. if (!methodDef->mIsStatic)
  13181. {
  13182. HashSet<int> objectOffsets;
  13183. EmitGCMarkValue(thisValue, mCurTypeInstance, 0, 0, objectOffsets, markFromGCThreadMethodInstance);
  13184. }
  13185. else
  13186. {
  13187. for (auto& fieldInst : mCurTypeInstance->mFieldInstances)
  13188. {
  13189. if (thisValue.IsSplat())
  13190. break;
  13191. auto fieldDef = fieldInst.GetFieldDef();
  13192. if (fieldDef == NULL)
  13193. continue;
  13194. if (fieldInst.mIsThreadLocal)
  13195. continue;
  13196. if (fieldDef->mIsStatic == methodDef->mIsStatic)
  13197. {
  13198. // For extensions, only handle these fields in the appropriate extension
  13199. if ((fieldDef->mDeclaringType->mTypeDeclaration != methodDef->mDeclaringType->mTypeDeclaration))
  13200. continue;
  13201. if (!fieldInst.mFieldIncluded)
  13202. continue;
  13203. auto fieldTypeInst = fieldInst.mResolvedType->ToTypeInstance();
  13204. if (fieldTypeInst != NULL)
  13205. {
  13206. auto fieldDef = fieldInst.GetFieldDef();
  13207. BfTypedValue markVal;
  13208. if (fieldDef->mIsConst)
  13209. continue;
  13210. if ((!fieldTypeInst->IsObjectOrInterface()) && (!fieldTypeInst->IsComposite()))
  13211. continue;
  13212. mBfIRBuilder->PopulateType(fieldTypeInst);
  13213. if (fieldTypeInst->IsValuelessType())
  13214. continue;
  13215. if ((fieldDef->mIsStatic) && (!fieldDef->mIsConst))
  13216. {
  13217. markVal = ReferenceStaticField(&fieldInst);
  13218. }
  13219. else if (!fieldDef->mIsStatic)
  13220. {
  13221. markVal = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(thisValue.mValue, 0, fieldInst.mDataIdx/*, fieldDef->mName*/), fieldInst.mResolvedType, true);
  13222. }
  13223. if (markVal)
  13224. EmitGCMarkValue(markVal, markFromGCThreadMethodInstance);
  13225. }
  13226. }
  13227. }
  13228. }
  13229. if (mCurMethodInstance->mChainType == BfMethodChainType_ChainHead)
  13230. CallChainedMethods(mCurMethodInstance, false);
  13231. }
  13232. }
  13233. }
  13234. void BfModule::EmitGCFindTLSMembers()
  13235. {
  13236. auto methodDef = mCurMethodInstance->mMethodDef;
  13237. auto gcTypeInst = ResolveTypeDef(mCompiler->mGCTypeDef)->ToTypeInstance();
  13238. auto reportTLSMark = GetMethodByName(gcTypeInst, "ReportTLSMember", 2);
  13239. BF_ASSERT(reportTLSMark);
  13240. for (auto& fieldInst : mCurTypeInstance->mFieldInstances)
  13241. {
  13242. auto fieldDef = fieldInst.GetFieldDef();
  13243. if (fieldDef == NULL)
  13244. continue;
  13245. if (!fieldInst.mIsThreadLocal)
  13246. continue;
  13247. // For extensions, only handle these fields in the appropriate extension
  13248. if ((fieldDef->mDeclaringType->mTypeDeclaration != methodDef->mDeclaringType->mTypeDeclaration))
  13249. continue;
  13250. if (!fieldInst.mFieldIncluded)
  13251. continue;
  13252. if (fieldDef->mIsConst)
  13253. continue;
  13254. auto fieldType = fieldInst.mResolvedType;
  13255. if ((!fieldType->IsObjectOrInterface()) && (!fieldType->IsComposite()))
  13256. continue;
  13257. if (fieldType->IsValuelessType())
  13258. continue;
  13259. BfTypedValue markVal = ReferenceStaticField(&fieldInst);
  13260. if (markVal)
  13261. {
  13262. BfIRValue fieldRefPtr = mBfIRBuilder->CreateBitCast(markVal.mValue, mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr)));
  13263. BfIRValue markFuncPtr = GetMarkFuncPtr(fieldType);
  13264. SizedArray<BfIRValue, 2> llvmArgs;
  13265. llvmArgs.push_back(fieldRefPtr);
  13266. llvmArgs.push_back(markFuncPtr);
  13267. mBfIRBuilder->CreateCall(reportTLSMark.mFunc, llvmArgs);
  13268. }
  13269. }
  13270. if (mCurMethodInstance->mChainType == BfMethodChainType_ChainHead)
  13271. CallChainedMethods(mCurMethodInstance, false);
  13272. }
  13273. void BfModule::ProcessMethod(BfMethodInstance* methodInstance, bool isInlineDup)
  13274. {
  13275. BP_ZONE_F("BfModule::ProcessMethod %s", BP_DYN_STR(methodInstance->mMethodDef->mName.c_str()));
  13276. if (mAwaitingInitFinish)
  13277. FinishInit();
  13278. if (!methodInstance->mIsReified)
  13279. BF_ASSERT(!mIsReified);
  13280. if (methodInstance->mMethodInfoEx != NULL)
  13281. {
  13282. for (auto methodGenericArg : methodInstance->mMethodInfoEx->mMethodGenericArguments)
  13283. {
  13284. if (methodGenericArg->IsMethodRef())
  13285. {
  13286. auto methodRefType = (BfMethodRefType*)methodGenericArg;
  13287. BF_ASSERT(methodRefType->mOwnerRevision == methodRefType->mOwner->mRevision);
  13288. }
  13289. }
  13290. }
  13291. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, mWantsIRIgnoreWrites || methodInstance->mIsUnspecialized);
  13292. bool ignoreWrites = mBfIRBuilder->mIgnoreWrites;
  13293. if ((HasCompiledOutput()) && (!mBfIRBuilder->mIgnoreWrites))
  13294. {
  13295. BF_ASSERT(!methodInstance->mIRFunction.IsFake() || (methodInstance->GetImportCallKind() != BfImportCallKind_None));
  13296. }
  13297. SetAndRestoreValue<BfSourceClassifier*> prevSourceClassifier;
  13298. if (((methodInstance->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend) || (methodInstance->mIsForeignMethodDef) || (methodInstance->IsSpecializedGenericMethod())) &&
  13299. (mCompiler->mResolvePassData != NULL))
  13300. {
  13301. // Don't classify on the CtorCalcAppend, just on the actual Ctor
  13302. prevSourceClassifier.Init(mCompiler->mResolvePassData->mSourceClassifier, NULL);
  13303. }
  13304. if (methodInstance->mHasBeenProcessed)
  13305. {
  13306. BfLogSysM("ProcessMethod %p HasBeenProcessed\n", methodInstance);
  13307. return;
  13308. }
  13309. if (methodInstance->mFailedConstraints)
  13310. {
  13311. // The only way this should be able to happen is if we fail our generic param check
  13312. BF_ASSERT(methodInstance->IsSpecializedGenericMethod());
  13313. BfLogSysM("Method instance marked as 'failed' at start of ProcessMethod %p\n", methodInstance);
  13314. methodInstance->mHasBeenProcessed = true;
  13315. return;
  13316. }
  13317. BfMethodInstance* defaultMethodInstance = methodInstance->mMethodInstanceGroup->mDefault;
  13318. BF_ASSERT(methodInstance->mMethodInstanceGroup->mOnDemandKind != BfMethodOnDemandKind_NotSet);
  13319. if ((methodInstance->mMethodInstanceGroup->mOnDemandKind != BfMethodOnDemandKind_AlwaysInclude) &&
  13320. (methodInstance->mMethodInstanceGroup->mOnDemandKind != BfMethodOnDemandKind_Referenced))
  13321. {
  13322. methodInstance->mMethodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_Referenced;
  13323. auto owningModule = methodInstance->GetOwner()->mModule;
  13324. if (owningModule->mIsScratchModule)
  13325. {
  13326. BF_ASSERT(owningModule->mOnDemandMethodCount == 0);
  13327. }
  13328. else
  13329. {
  13330. BF_ASSERT((owningModule->mOnDemandMethodCount > 0) || (!HasCompiledOutput()) || (owningModule->mExtensionCount > 0));
  13331. if (owningModule->mOnDemandMethodCount > 0)
  13332. owningModule->mOnDemandMethodCount--;
  13333. }
  13334. }
  13335. // We set mHasBeenProcessed to true immediately -- this helps avoid stack overflow during recursion for things like
  13336. // self-referencing append allocations in ctor@calcAppend
  13337. methodInstance->mHasBeenProcessed = true;
  13338. mIncompleteMethodCount--;
  13339. BF_ASSERT((mIsSpecialModule) || (mIncompleteMethodCount >= 0));
  13340. auto typeDef = methodInstance->mMethodInstanceGroup->mOwner->mTypeDef;
  13341. auto methodDef = methodInstance->mMethodDef;
  13342. auto methodDeclaration = methodDef->GetMethodDeclaration();
  13343. if ((methodInstance->mIsReified) && (methodInstance->mVirtualTableIdx != -1))
  13344. {
  13345. // If we reify a virtual method in a HotCompile then we need to make sure the type data gets written out
  13346. // so we get the new vdata for it
  13347. methodInstance->GetOwner()->mDirty = true;
  13348. }
  13349. int dependentGenericStartIdx = 0;
  13350. if (methodDef->mIsLocalMethod) // See DoMethodDeclaration for an explaination of dependentGenericStartIdx
  13351. dependentGenericStartIdx = (int)mCurMethodState->GetRootMethodState()->mMethodInstance->GetNumGenericArguments();
  13352. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, methodInstance);
  13353. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, methodInstance->mMethodInstanceGroup->mOwner);
  13354. SetAndRestoreValue<BfFilePosition> prevFilePos(mCurFilePosition);
  13355. SetAndRestoreValue<bool> prevHadBuildError(mHadBuildError, false);
  13356. SetAndRestoreValue<bool> prevHadWarning(mHadBuildWarning, false);
  13357. SetAndRestoreValue<bool> prevIgnoreWarnings(mIgnoreWarnings, false);
  13358. if ((methodInstance->mIsReified) &&
  13359. ((methodDef->mMethodType == BfMethodType_Ctor) || (methodDef->mMethodType == BfMethodType_CtorNoBody)))
  13360. {
  13361. mCurTypeInstance->mHasBeenInstantiated = true;
  13362. }
  13363. // Warnings are shown in the capture phase
  13364. if ((methodDef->mIsLocalMethod) || (mCurTypeInstance->IsClosure()))
  13365. mIgnoreWarnings = true;
  13366. if ((methodDeclaration == NULL) && (mCurMethodState == NULL))
  13367. UseDefaultSrcPos();
  13368. // We may not actually be populated in relatively rare autocompelte cases
  13369. PopulateType(mCurTypeInstance, BfPopulateType_DataAndMethods);
  13370. mBfIRBuilder->PopulateType(mCurTypeInstance, BfIRPopulateType_Full);
  13371. BfAstNode* nameNode = NULL;
  13372. if (methodDeclaration != NULL)
  13373. {
  13374. nameNode = methodDeclaration->mNameNode;
  13375. if (nameNode == NULL)
  13376. {
  13377. if (auto ctorDeclaration = BfNodeDynCast<BfConstructorDeclaration>(methodDeclaration))
  13378. nameNode = ctorDeclaration->mThisToken;
  13379. }
  13380. }
  13381. if ((mCompiler->mResolvePassData != NULL) && (methodDeclaration != NULL) && (nameNode != NULL) &&
  13382. (mCompiler->mResolvePassData->mGetSymbolReferenceKind == BfGetSymbolReferenceKind_Method) && (methodDef->mIdx >= 0))
  13383. {
  13384. if (methodInstance->GetExplicitInterface() == NULL)
  13385. mCompiler->mResolvePassData->HandleMethodReference(nameNode, typeDef, methodDef);
  13386. else
  13387. {
  13388. for (auto& ifaceEntry : mCurTypeInstance->mInterfaces)
  13389. {
  13390. auto ifaceInst = ifaceEntry.mInterfaceType;
  13391. int startIdx = ifaceEntry.mStartInterfaceTableIdx;
  13392. int iMethodCount = (int)ifaceInst->mMethodInstanceGroups.size();
  13393. if (methodInstance->GetExplicitInterface() != ifaceInst)
  13394. continue;
  13395. ifaceInst->mTypeDef->PopulateMemberSets();
  13396. BfMethodDef* nextMethod = NULL;
  13397. BfMemberSetEntry* entry = NULL;
  13398. if (ifaceInst->mTypeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  13399. nextMethod = (BfMethodDef*)entry->mMemberDef;
  13400. while (nextMethod != NULL)
  13401. {
  13402. auto checkMethod = nextMethod;
  13403. nextMethod = nextMethod->mNextWithSameName;
  13404. BfMethodInstance* implMethodInst = mCurTypeInstance->mInterfaceMethodTable[startIdx + checkMethod->mIdx].mMethodRef;
  13405. if (implMethodInst == methodInstance)
  13406. {
  13407. auto ifaceMethodDef = ifaceInst->mTypeDef->mMethods[checkMethod->mIdx];
  13408. mCompiler->mResolvePassData->HandleMethodReference(nameNode, ifaceInst->mTypeDef, ifaceMethodDef);
  13409. }
  13410. }
  13411. }
  13412. }
  13413. if (methodDef->mIsOverride)
  13414. {
  13415. for (int virtIdx = 0; virtIdx < (int)mCurTypeInstance->mVirtualMethodTable.size(); virtIdx++)
  13416. {
  13417. auto& ventry = mCurTypeInstance->mVirtualMethodTable[virtIdx];
  13418. if (ventry.mDeclaringMethod.mMethodNum == -1)
  13419. continue;
  13420. BfMethodInstance* virtMethod = ventry.mImplementingMethod;
  13421. if (virtMethod != NULL)
  13422. {
  13423. if (virtMethod == methodInstance)
  13424. {
  13425. // Is matching method
  13426. if (virtIdx < (int)mCurTypeInstance->mBaseType->mVirtualMethodTable.size())
  13427. {
  13428. auto baseType = mCurTypeInstance->mBaseType;
  13429. if (baseType != NULL)
  13430. {
  13431. while ((baseType->mBaseType != NULL) && (virtIdx < baseType->mBaseType->mVirtualMethodTableSize))
  13432. baseType = baseType->mBaseType;
  13433. BfMethodInstance* baseVirtMethod = baseType->mVirtualMethodTable[virtIdx].mImplementingMethod;
  13434. mCompiler->mResolvePassData->HandleMethodReference(nameNode, baseType->mTypeDef, baseVirtMethod->mMethodDef);
  13435. }
  13436. }
  13437. break;
  13438. }
  13439. }
  13440. }
  13441. }
  13442. }
  13443. BfLogSysM("ProcessMethod %p Unspecialized: %d Module: %p IRFunction: %d Reified: %d\n", methodInstance, mCurTypeInstance->IsUnspecializedType(), this, methodInstance->mIRFunction.mId, methodInstance->mIsReified);
  13444. if (methodInstance->GetImportCallKind() != BfImportCallKind_None)
  13445. {
  13446. if (mBfIRBuilder->mIgnoreWrites)
  13447. return;
  13448. BfLogSysM("DllImportGlobalVar processing %p\n", methodInstance);
  13449. if (!methodInstance->mIRFunction)
  13450. {
  13451. BfIRValue dllImportGlobalVar = CreateDllImportGlobalVar(methodInstance, true);
  13452. methodInstance->mIRFunction = mBfIRBuilder->GetFakeVal();
  13453. mFuncReferences[mCurMethodInstance] = dllImportGlobalVar;
  13454. }
  13455. if (HasCompiledOutput())
  13456. {
  13457. BfDllImportEntry dllImportEntry;
  13458. dllImportEntry.mFuncVar = methodInstance->mIRFunction;
  13459. dllImportEntry.mMethodInstance = mCurMethodInstance;
  13460. mDllImportEntries.push_back(dllImportEntry);
  13461. }
  13462. return;
  13463. }
  13464. StringT<128> mangledName;
  13465. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), mCurMethodInstance);
  13466. if (!methodInstance->mIRFunction)
  13467. {
  13468. bool isIntrinsic = false;
  13469. SetupIRFunction(methodInstance, mangledName, false, &isIntrinsic);
  13470. }
  13471. if (methodInstance->mIsIntrinsic)
  13472. return;
  13473. auto prevActiveFunction = mBfIRBuilder->GetActiveFunction();
  13474. mBfIRBuilder->SetActiveFunction(mCurMethodInstance->mIRFunction);
  13475. if (methodDef->mBody != NULL)
  13476. UpdateSrcPos(methodDef->mBody, BfSrcPosFlag_NoSetDebugLoc);
  13477. else if (methodDeclaration != NULL)
  13478. UpdateSrcPos(methodDeclaration, BfSrcPosFlag_NoSetDebugLoc);
  13479. else if (mCurTypeInstance->mTypeDef->mTypeDeclaration != NULL)
  13480. UpdateSrcPos(mCurTypeInstance->mTypeDef->mTypeDeclaration, BfSrcPosFlag_NoSetDebugLoc);
  13481. if (mCurMethodState == NULL) // Only do initial classify for the 'outer' method state, not any local methods or lambdas
  13482. {
  13483. if ((mCompiler->mIsResolveOnly) && (methodDef->mBody != NULL) && (!mCurTypeInstance->IsBoxed()) &&
  13484. (methodDef->mBody->IsFromParser(mCompiler->mResolvePassData->mParser)) && (mCompiler->mResolvePassData->mSourceClassifier != NULL))
  13485. {
  13486. mCompiler->mResolvePassData->mSourceClassifier->VisitChildNoRef(methodDef->mBody);
  13487. }
  13488. }
  13489. BfHotDataReferenceBuilder hotDataReferenceBuilder;
  13490. BfMethodState methodState;
  13491. if (mCurMethodState != NULL)
  13492. methodState.mClosureState = mCurMethodState->mClosureState;
  13493. if ((mCompiler->mOptions.mAllowHotSwapping) && (methodInstance->mIsReified) && (!methodInstance->mIsUnspecialized) && (!isInlineDup))
  13494. {
  13495. //BF_ASSERT(methodInstance->mHotMethod != NULL);
  13496. if (methodInstance->mHotMethod == NULL)
  13497. CheckHotMethod(methodInstance, mangledName);
  13498. methodState.mHotDataReferenceBuilder = &hotDataReferenceBuilder;
  13499. }
  13500. methodState.mPrevMethodState = mCurMethodState;
  13501. methodState.mMethodInstance = methodInstance;
  13502. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  13503. if (methodInstance->GetCustomAttributes() != NULL)
  13504. {
  13505. int typeOptionsIdx = GenerateTypeOptions(methodInstance->GetCustomAttributes(), mCurTypeInstance, false);
  13506. if (typeOptionsIdx != -1)
  13507. methodState.mMethodTypeOptions = mSystem->GetTypeOptions(typeOptionsIdx);
  13508. }
  13509. BfTypeState typeState(mCurTypeInstance);
  13510. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  13511. bool isGenericVariation = (methodInstance->mIsUnspecializedVariation) || (mCurTypeInstance->IsUnspecializedTypeVariation());
  13512. BfMethodInstance* unspecializedMethodInstance = NULL;
  13513. if ((prevMethodState.mPrevVal != NULL) &&
  13514. ((methodState.mClosureState == NULL) || (methodState.mClosureState->mActiveDeferredLocalMethod == NULL)))
  13515. {
  13516. // This is 'inner' (probably a closure) - use binding from outer function
  13517. methodState.mGenericTypeBindings = prevMethodState.mPrevVal->mGenericTypeBindings;
  13518. }
  13519. else if ((methodInstance->mIsUnspecialized) ||
  13520. ((mCurTypeInstance->IsUnspecializedType()) && (!isGenericVariation)))
  13521. {
  13522. methodState.mGenericTypeBindings = &methodInstance->GetMethodInfoEx()->mGenericTypeBindings;
  13523. }
  13524. else if ((((methodInstance->mMethodInfoEx != NULL) && ((int)methodInstance->mMethodInfoEx->mMethodGenericArguments.size() > dependentGenericStartIdx)) ||
  13525. ((mCurTypeInstance->IsGenericTypeInstance()) && (!isGenericVariation))))
  13526. {
  13527. unspecializedMethodInstance = GetUnspecializedMethodInstance(methodInstance);
  13528. BF_ASSERT(unspecializedMethodInstance != methodInstance);
  13529. if (!unspecializedMethodInstance->mHasBeenProcessed)
  13530. {
  13531. // Make sure the unspecialized method is processed so we can take its bindings
  13532. // Clear mCurMethodState so we don't think we're in a local method
  13533. SetAndRestoreValue<BfMethodState*> prevMethodState_Unspec(mCurMethodState, prevMethodState.mPrevVal);
  13534. mContext->ProcessMethod(unspecializedMethodInstance);
  13535. }
  13536. methodState.mGenericTypeBindings = &unspecializedMethodInstance->GetMethodInfoEx()->mGenericTypeBindings;
  13537. }
  13538. if (methodDef->mMethodType == BfMethodType_Operator)
  13539. {
  13540. auto operatorDef = (BfOperatorDef*) methodDef;
  13541. BfAstNode* refNode = operatorDef->mOperatorDeclaration->mOperatorToken;
  13542. auto paramErrorRefNode = refNode;
  13543. if (operatorDef->mOperatorDeclaration->mOpenParen != NULL)
  13544. paramErrorRefNode = operatorDef->mOperatorDeclaration->mOpenParen;
  13545. if ((mCurMethodInstance->GetParamCount() > 0) && (mCurMethodInstance->GetParamTypeRef(0) != NULL))
  13546. paramErrorRefNode = mCurMethodInstance->GetParamTypeRef(0);
  13547. if (operatorDef->mOperatorDeclaration->mBinOp != BfBinaryOp_None)
  13548. {
  13549. if (methodDef->mParams.size() != 2)
  13550. {
  13551. Fail("Binary operators must declare two parameters", paramErrorRefNode);
  13552. }
  13553. else
  13554. {
  13555. if ((mCurMethodInstance->GetParamType(0) != mCurTypeInstance) && (!mCurMethodInstance->GetParamType(0)->IsSelf()) &&
  13556. (mCurMethodInstance->GetParamType(1) != mCurTypeInstance) && (!mCurMethodInstance->GetParamType(1)->IsSelf()))
  13557. {
  13558. Fail("At least one of the parameters of a binary operator must be the containing type", paramErrorRefNode);
  13559. }
  13560. }
  13561. BfType* wantType = NULL;
  13562. if (operatorDef->mOperatorDeclaration->mBinOp == BfBinaryOp_Compare)
  13563. {
  13564. wantType = GetPrimitiveType(BfTypeCode_IntPtr);
  13565. }
  13566. if ((wantType != NULL) && (methodInstance->mReturnType != wantType))
  13567. Fail(StrFormat("The return type for the '%s' operator must be '%s'", BfGetOpName(operatorDef->mOperatorDeclaration->mBinOp),
  13568. TypeToString(wantType).c_str()), operatorDef->mOperatorDeclaration->mReturnType);
  13569. }
  13570. else if (operatorDef->mOperatorDeclaration->mUnaryOp != BfUnaryOp_None)
  13571. {
  13572. if (methodDef->mParams.size() != 1)
  13573. {
  13574. Fail("Unary operators must declare one parameter", paramErrorRefNode);
  13575. }
  13576. else if ((mCurMethodInstance->GetParamType(0) != mCurTypeInstance) && (!mCurMethodInstance->GetParamType(0)->IsSelf()))
  13577. {
  13578. Fail("The parameter of a unary operator must be the containing type", paramErrorRefNode);
  13579. }
  13580. if (((operatorDef->mOperatorDeclaration->mUnaryOp == BfUnaryOp_Increment) ||
  13581. (operatorDef->mOperatorDeclaration->mUnaryOp == BfUnaryOp_Decrement)) &&
  13582. (!TypeIsSubTypeOf(mCurMethodInstance->mReturnType->ToTypeInstance(), mCurTypeInstance)))
  13583. {
  13584. Fail("The return type for the '++' or '--' operator must match the parameter type or be derived from the parameter type", operatorDef->mOperatorDeclaration->mReturnType);
  13585. }
  13586. }
  13587. else if (operatorDef->mOperatorDeclaration->mAssignOp != BfAssignmentOp_None)
  13588. {
  13589. if (methodDef->mParams.size() != 1)
  13590. {
  13591. Fail("Assignment operators must declare one parameter", paramErrorRefNode);
  13592. }
  13593. if (mCurMethodInstance->mReturnType->IsVoid())
  13594. {
  13595. Fail("The return type for assignment operator must be 'void'", operatorDef->mOperatorDeclaration->mReturnType);
  13596. }
  13597. }
  13598. else // Conversion
  13599. {
  13600. if (!operatorDef->mOperatorDeclaration->mIsConvOperator)
  13601. {
  13602. if (operatorDef->mOperatorDeclaration->mReturnType != NULL)
  13603. Fail("Conversion operators must declare their target type after the 'operator' token, not before", operatorDef->mOperatorDeclaration->mReturnType);
  13604. }
  13605. if (methodDef->mParams.size() != 1)
  13606. {
  13607. auto refNode = paramErrorRefNode;
  13608. if (!operatorDef->mOperatorDeclaration->mCommas.empty())
  13609. refNode = operatorDef->mOperatorDeclaration->mCommas[0];
  13610. Fail("Conversion operators must declare one parameter", refNode);
  13611. }
  13612. else
  13613. {
  13614. if ((mCurMethodInstance->GetParamType(0) != mCurTypeInstance) && (!mCurMethodInstance->GetParamType(0)->IsSelf()) &&
  13615. (mCurMethodInstance->mReturnType != mCurTypeInstance) && (!mCurMethodInstance->mReturnType->IsSelf()))
  13616. Fail("User-defined conversion must convert to or from the enclosing type", paramErrorRefNode);
  13617. if (mCurMethodInstance->GetParamType(0) == mCurMethodInstance->mReturnType)
  13618. Fail("User-defined operator cannot take an object of the enclosing type and convert to an object of the enclosing type", operatorDef->mOperatorDeclaration->mReturnType);
  13619. // On type lookup error we default to 'object', so don't do the 'base class' error if that may have
  13620. // happened here
  13621. if ((!mHadBuildError) || ((mCurMethodInstance->mReturnType != mContext->mBfObjectType) && (mCurMethodInstance->GetParamType(0) != mContext->mBfObjectType)))
  13622. {
  13623. auto isToBase = TypeIsSubTypeOf(mCurTypeInstance->mBaseType, mCurMethodInstance->mReturnType->ToTypeInstance());
  13624. bool isFromBase = TypeIsSubTypeOf(mCurTypeInstance->mBaseType, mCurMethodInstance->GetParamType(0)->ToTypeInstance());
  13625. if ((mCurTypeInstance->IsObject()) && (isToBase || isFromBase))
  13626. Fail("User-defined conversions to or from a base class are not allowed", paramErrorRefNode);
  13627. else if ((mCurTypeInstance->IsStruct()) && (isToBase))
  13628. Fail("User-defined conversions to a base struct are not allowed", paramErrorRefNode);
  13629. }
  13630. }
  13631. }
  13632. }
  13633. bool wantsDIData = (mBfIRBuilder->DbgHasInfo()) && (!methodDef->IsEmptyPartial()) && (!mCurMethodInstance->mIsUnspecialized) && (mHasFullDebugInfo);
  13634. if (methodDef->mMethodType == BfMethodType_Mixin)
  13635. wantsDIData = false;
  13636. if ((mCurTypeInstance->IsBoxed()) && (methodDef->mMethodType != BfMethodType_Ctor))
  13637. wantsDIData = false;
  13638. bool wantsDIVariables = wantsDIData;
  13639. if (methodDef->mIsExtern)
  13640. wantsDIVariables = false;
  13641. SizedArray<BfIRMDNode, 8> diParams;
  13642. diParams.push_back(mBfIRBuilder->DbgGetType(methodInstance->mReturnType));
  13643. bool isThisStruct = mCurTypeInstance->IsStruct() && !mCurTypeInstance->IsTypedPrimitive();
  13644. BfType* thisType = NULL;
  13645. if (!methodDef->mIsStatic)
  13646. {
  13647. if ((methodState.mClosureState != NULL) && (methodState.mClosureState->mClosureType != NULL))
  13648. thisType = methodState.mClosureState->mClosureType;
  13649. else
  13650. thisType = mCurTypeInstance;
  13651. }
  13652. PopulateType(methodInstance->mReturnType, BfPopulateType_Data);
  13653. ProcessMethod_SetupParams(methodInstance, thisType, wantsDIData, &diParams);
  13654. //////////////////////////////////////////////////////////////////////////
  13655. //
  13656. {
  13657. if (methodDeclaration != NULL)
  13658. UpdateSrcPos(methodDeclaration, BfSrcPosFlag_NoSetDebugLoc);
  13659. else if (methodDef->mBody != NULL)
  13660. UpdateSrcPos(methodDef->mBody, BfSrcPosFlag_NoSetDebugLoc);
  13661. else if (mCurTypeInstance->mTypeDef->mTypeDeclaration != NULL)
  13662. UpdateSrcPos(mCurTypeInstance->mTypeDef->mTypeDeclaration, BfSrcPosFlag_NoSetDebugLoc);
  13663. }
  13664. BfIRMDNode diFunction;
  13665. if (wantsDIData)
  13666. {
  13667. BP_ZONE("BfModule::BfMethodDeclaration.DISetup");
  13668. BfIRMDNode diFuncType = mBfIRBuilder->DbgCreateSubroutineType(diParams);
  13669. int defLine = mCurFilePosition.mCurLine;
  13670. if (mDICompileUnit)
  13671. {
  13672. int flags = 0;
  13673. BfIRMDNode funcScope = mBfIRBuilder->DbgGetTypeInst(mCurTypeInstance);
  13674. if (methodDef->mProtection == BfProtection_Public)
  13675. flags = llvm::DINode::FlagPublic;
  13676. else if (methodDef->mProtection == BfProtection_Protected)
  13677. flags = llvm::DINode::FlagProtected;
  13678. else
  13679. flags = llvm::DINode::FlagPrivate;
  13680. if (methodDef->mIsOverride)
  13681. {
  13682. //flags |= llvm::DINode::FlagVirtual;
  13683. }
  13684. else if (methodDef->mIsVirtual)
  13685. flags |= llvm::DINode::FlagIntroducedVirtual;
  13686. if ((methodDef->mIsStatic) || (methodDef->mMethodType == BfMethodType_Mixin))
  13687. flags |= llvm::DINode::FlagStaticMember;
  13688. else
  13689. {
  13690. if ((mCurTypeInstance->IsValuelessType()) || (mCurTypeInstance->IsSplattable()))
  13691. flags |= llvm::DINode::FlagStaticMember;
  13692. }
  13693. flags |= llvm::DINode::FlagPrototyped;
  13694. if (methodDef->mMethodType == BfMethodType_Ctor)
  13695. {
  13696. flags |= llvm::DINode::FlagArtificial;
  13697. }
  13698. auto llvmFunction = methodInstance->mIRFunction;
  13699. SizedArray<BfIRMDNode, 1> genericArgs;
  13700. SizedArray<BfIRValue, 1> genericConstValueArgs;
  13701. String methodName;
  13702. if (methodInstance->GetForeignType() != NULL)
  13703. {
  13704. methodName += TypeToString(methodInstance->GetForeignType());
  13705. methodName += ".";
  13706. }
  13707. if (methodInstance->GetExplicitInterface() != NULL)
  13708. {
  13709. methodName += TypeToString(methodInstance->GetExplicitInterface());
  13710. methodName += ".";
  13711. }
  13712. methodName += methodDef->mName;
  13713. if (methodInstance->GetNumGenericArguments() != 0)
  13714. {
  13715. for (auto genericArg : methodInstance->mMethodInfoEx->mMethodGenericArguments)
  13716. {
  13717. if (genericArg->IsConstExprValue())
  13718. {
  13719. BfConstExprValueType* constExprValueType = (BfConstExprValueType*)genericArg;
  13720. while (genericConstValueArgs.size() < genericArgs.size())
  13721. genericConstValueArgs.push_back(BfIRValue());
  13722. genericConstValueArgs.push_back(mBfIRBuilder->CreateConst(BfTypeCode_UInt64, constExprValueType->mValue.mUInt64));
  13723. genericArgs.push_back(mBfIRBuilder->DbgGetType(GetPrimitiveType(BfTypeCode_Int64)));
  13724. }
  13725. else
  13726. genericArgs.push_back(mBfIRBuilder->DbgGetType(genericArg));
  13727. }
  13728. methodName += "<";
  13729. for (int i = 0; i < (int)methodInstance->mMethodInfoEx->mMethodGenericArguments.size(); i++)
  13730. {
  13731. if (i > 0)
  13732. methodName += ", ";
  13733. BfType* type = methodInstance->mMethodInfoEx->mMethodGenericArguments[i];
  13734. methodName += TypeToString(type);
  13735. }
  13736. methodName += ">";
  13737. }
  13738. if ((methodName.empty()) && (methodDeclaration != NULL))
  13739. {
  13740. if (auto operatorDecl = BfNodeDynCast<BfOperatorDeclaration>(methodDeclaration))
  13741. {
  13742. methodName += "operator";
  13743. if (operatorDecl->mIsConvOperator)
  13744. {
  13745. methodName += " ";
  13746. methodName += TypeToString(methodInstance->mReturnType);
  13747. }
  13748. else if (operatorDecl->mOpTypeToken != NULL)
  13749. methodName += operatorDecl->mOpTypeToken->ToString();
  13750. }
  13751. }
  13752. methodState.mDIFile = mCurFilePosition.mFileInstance->mDIFile;
  13753. // diFunction = mBfIRBuilder->DbgCreateMethod(funcScope, methodName, mangledName, methodState.mDIFile,
  13754. // defLine + 1, diFuncType, false, true,
  13755. // (methodInstance->mVirtualTableIdx != -1) ? llvm::dwarf::DW_VIRTUALITY_virtual : llvm::dwarf::DW_VIRTUALITY_none,
  13756. // (methodInstance->mVirtualTableIdx != -1) ? methodInstance->DbgGetVirtualMethodNum() : 0,
  13757. // nullptr, flags, IsOptimized(), llvmFunction, genericArgs, genericConstValueArgs);
  13758. diFunction = mBfIRBuilder->DbgCreateMethod(funcScope, methodName, mangledName, methodState.mDIFile,
  13759. defLine + 1, diFuncType, false, true,
  13760. llvm::dwarf::DW_VIRTUALITY_none,
  13761. 0,
  13762. nullptr, flags, IsOptimized(), llvmFunction, genericArgs, genericConstValueArgs);
  13763. }
  13764. }
  13765. //////////////////////////////////////////////////////////////////////////
  13766. // Head and Init get rolled into Entry afterwards.
  13767. methodState.mIRFunction = methodInstance->mIRFunction;
  13768. methodState.mIRHeadBlock = mBfIRBuilder->CreateBlock("head", true);
  13769. methodState.mIRInitBlock = mBfIRBuilder->CreateBlock("init", true);
  13770. methodState.mIREntryBlock = mBfIRBuilder->CreateBlock("entry", true);
  13771. methodState.mCurScope->mDIScope = diFunction;
  13772. auto llvmEntryBlock = methodState.mIREntryBlock;
  13773. mBfIRBuilder->SetInsertPoint(llvmEntryBlock);
  13774. if (methodDef->mBody != NULL)
  13775. {
  13776. UpdateSrcPos(methodDef->mBody, BfSrcPosFlag_NoSetDebugLoc);
  13777. }
  13778. else if ((mHasFullDebugInfo) && (diFunction) && (typeDef->mTypeDeclaration != NULL))
  13779. {
  13780. // We want to be able to step into delegate invokes -- we actually step over them
  13781. if (methodDef->mName != "Invoke")
  13782. {
  13783. UpdateSrcPos(typeDef->mTypeDeclaration);
  13784. mBfIRBuilder->DbgCreateAnnotation(diFunction, "StepOver", GetConstValue32(1));
  13785. }
  13786. }
  13787. // Clear out DebugLoc - to mark the ".addr" code as part of prologue
  13788. mBfIRBuilder->ClearDebugLocation();
  13789. bool isTypedPrimitiveFunc = mCurTypeInstance->IsTypedPrimitive() && (methodDef->mMethodType != BfMethodType_Ctor);
  13790. int irParamCount = methodInstance->GetIRFunctionParamCount(this);
  13791. if (methodDef->mImportKind != BfImportKind_Dynamic)
  13792. {
  13793. int localIdx = 0;
  13794. int argIdx = 0;
  13795. if (methodInstance->HasStructRet())
  13796. argIdx++;
  13797. //
  13798. bool doDbgAgg = false;
  13799. Array<BfIRValue> splatAddrValues;
  13800. for ( ; argIdx < irParamCount; localIdx++)
  13801. {
  13802. bool isThis = ((localIdx == 0) && (!mCurMethodInstance->mMethodDef->mIsStatic));
  13803. if ((isThis) && (thisType->IsValuelessType()))
  13804. isThis = false;
  13805. BfLocalVariable* paramVar = NULL;
  13806. while (true)
  13807. {
  13808. BF_ASSERT(localIdx < methodState.mLocals.size());
  13809. paramVar = methodState.mLocals[localIdx];
  13810. if ((paramVar->mCompositeCount == -1) &&
  13811. ((!paramVar->mResolvedType->IsValuelessType()) || (paramVar->mResolvedType->IsMethodRef())))
  13812. break;
  13813. localIdx++;
  13814. }
  13815. if ((isThis) && (mCurTypeInstance->IsValueType()) && (methodDef->mMethodType != BfMethodType_Ctor) && (!methodDef->HasNoThisSplat()))
  13816. {
  13817. paramVar->mIsReadOnly = true;
  13818. }
  13819. bool wantsAddr = (wantsDIVariables) || (!paramVar->mIsReadOnly) || (paramVar->mResolvedType->GetLoweredType() != BfTypeCode_None);
  13820. if (paramVar->mResolvedType->IsMethodRef())
  13821. wantsAddr = false;
  13822. // if ((methodDef->mHasAppend) && (argIdx == 1))
  13823. // {
  13824. // BF_ASSERT(paramVar->mName == "appendIdx");
  13825. // wantsAddr = true;
  13826. // }
  13827. if ((!doDbgAgg) && (paramVar->mIsSplat))
  13828. {
  13829. auto prevInsert = mBfIRBuilder->GetInsertBlock();
  13830. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  13831. BfTypeUtils::SplatIterate([&](BfType* checkType)
  13832. {
  13833. BfIRType splatIRType;
  13834. if (checkType->IsComposite())
  13835. splatIRType = mBfIRBuilder->MapType(CreatePointerType(checkType));
  13836. else
  13837. splatIRType = mBfIRBuilder->MapType(checkType);
  13838. auto allocaInst = mBfIRBuilder->CreateAlloca(splatIRType);
  13839. mBfIRBuilder->SetAllocaAlignment(allocaInst, checkType->mAlign);
  13840. if (!paramVar->mAddr)
  13841. paramVar->mAddr = allocaInst;
  13842. if (WantsLifetimes())
  13843. mCurMethodState->mCurScope->mDeferredLifetimeEnds.push_back(allocaInst);
  13844. splatAddrValues.push_back(allocaInst);
  13845. }, paramVar->mResolvedType);
  13846. mBfIRBuilder->SetInsertPoint(prevInsert);
  13847. }
  13848. else if (isThis)
  13849. {
  13850. if (wantsAddr)
  13851. {
  13852. auto prevInsert = mBfIRBuilder->GetInsertBlock();
  13853. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  13854. BfIRType thisAddrType = mBfIRBuilder->MapType(thisType);
  13855. if (paramVar->mIsSplat)
  13856. {
  13857. if (doDbgAgg)
  13858. {
  13859. auto allocaInst = mBfIRBuilder->CreateAlloca(thisAddrType);
  13860. mBfIRBuilder->SetName(allocaInst, paramVar->mName + ".addr");
  13861. mBfIRBuilder->SetAllocaAlignment(allocaInst, thisType->mAlign);
  13862. paramVar->mAddr = allocaInst;
  13863. if (WantsLifetimes())
  13864. mCurMethodState->mCurScope->mDeferredLifetimeEnds.push_back(allocaInst);
  13865. }
  13866. }
  13867. else
  13868. {
  13869. bool wantPtr = (thisType->IsComposite()) && (!paramVar->mIsLowered);
  13870. if ((thisType->IsTypedPrimitive()) && (methodDef->HasNoThisSplat()))
  13871. wantPtr = true;
  13872. if (wantPtr)
  13873. {
  13874. thisAddrType = mBfIRBuilder->MapTypeInstPtr(thisType->ToTypeInstance());
  13875. }
  13876. auto allocaInst = mBfIRBuilder->CreateAlloca(thisAddrType);
  13877. mBfIRBuilder->SetName(allocaInst, paramVar->mName + ".addr");
  13878. mBfIRBuilder->SetAllocaAlignment(allocaInst, mSystem->mPtrSize);
  13879. paramVar->mAddr = allocaInst;
  13880. if (WantsLifetimes())
  13881. mCurMethodState->mCurScope->mDeferredLifetimeEnds.push_back(allocaInst);
  13882. }
  13883. mBfIRBuilder->SetInsertPoint(prevInsert);
  13884. }
  13885. }
  13886. else if ((!isThis) && ((paramVar->mIsStruct) || (paramVar->mResolvedType->IsRef())))
  13887. {
  13888. // Address doesn't change so we don't have to alloca it
  13889. BfIRType allocType;
  13890. int alignSize = mSystem->mPtrSize;
  13891. if (paramVar->mResolvedType->IsRef())
  13892. {
  13893. allocType = mBfIRBuilder->MapType(paramVar->mResolvedType);
  13894. }
  13895. else if ((paramVar->mIsSplat) || (paramVar->mIsLowered))
  13896. {
  13897. allocType = mBfIRBuilder->MapType(paramVar->mResolvedType);
  13898. alignSize = paramVar->mResolvedType->mAlign;
  13899. }
  13900. else
  13901. {
  13902. paramVar->mHasLocalStructBacking = true;
  13903. auto typeInst = paramVar->mResolvedType->ToTypeInstance();
  13904. if (typeInst != NULL)
  13905. allocType = mBfIRBuilder->MapTypeInstPtr(paramVar->mResolvedType->ToTypeInstance());
  13906. else
  13907. allocType = mBfIRBuilder->MapType(CreatePointerType(paramVar->mResolvedType));
  13908. }
  13909. if (wantsAddr)
  13910. {
  13911. auto prevInsert = mBfIRBuilder->GetInsertBlock();
  13912. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  13913. mBfIRBuilder->PopulateType(paramVar->mResolvedType);
  13914. auto allocaInst = mBfIRBuilder->CreateAlloca(allocType);
  13915. mBfIRBuilder->SetName(allocaInst, paramVar->mName + ".addr");
  13916. mBfIRBuilder->SetAllocaAlignment(allocaInst, alignSize);
  13917. paramVar->mAddr = allocaInst;
  13918. mBfIRBuilder->SetInsertPoint(prevInsert);
  13919. if (WantsLifetimes())
  13920. mCurMethodState->mCurScope->mDeferredLifetimeEnds.push_back(allocaInst);
  13921. }
  13922. }
  13923. else if (wantsAddr)
  13924. {
  13925. auto allocaInst = CreateAlloca(paramVar->mResolvedType);
  13926. mBfIRBuilder->SetName(allocaInst, paramVar->mName + ".addr");
  13927. paramVar->mAddr = allocaInst;
  13928. }
  13929. if (paramVar->mIsSplat)
  13930. {
  13931. BfTypeUtils::SplatIterate([&](BfType* checkType) { argIdx++; }, paramVar->mResolvedType);
  13932. }
  13933. else
  13934. {
  13935. argIdx++;
  13936. }
  13937. }
  13938. if (methodDef->mBody != NULL)
  13939. UpdateSrcPos(methodDef->mBody);
  13940. else if (mCurTypeInstance->mTypeDef->mTypeDeclaration != NULL)
  13941. UpdateSrcPos(mCurTypeInstance->mTypeDef->mTypeDeclaration);
  13942. int declArgIdx = 0;
  13943. localIdx = 0;
  13944. argIdx = 0;
  13945. if (methodInstance->HasStructRet())
  13946. argIdx++;
  13947. int splatAddrIdx = 0;
  13948. while (localIdx < (int)methodState.mLocals.size())
  13949. {
  13950. int curLocalIdx = localIdx++;
  13951. BfLocalVariable* paramVar = methodState.mLocals[curLocalIdx];
  13952. if (!paramVar->IsParam())
  13953. continue;
  13954. if (paramVar->mCompositeCount != -1)
  13955. continue;
  13956. bool isThis = ((curLocalIdx == 0) && (!mCurMethodInstance->mMethodDef->mIsStatic));
  13957. if ((isThis) && (thisType->IsValuelessType()))
  13958. isThis = false;
  13959. BfIRMDNode diVariable;
  13960. if (wantsDIData)
  13961. {
  13962. String paramName = paramVar->mName;
  13963. BfIRMDNode diType = mBfIRBuilder->DbgGetType(paramVar->mResolvedType);
  13964. if (isThis)
  13965. {
  13966. if ((mCurMethodState->mClosureState != NULL) && (mCurMethodState->mClosureState->mClosureType != NULL))
  13967. paramName = "__closure";
  13968. if ((paramVar->mResolvedType->IsValueType()) && (!paramVar->mIsSplat) && (!paramVar->mIsLowered))
  13969. {
  13970. diType = mBfIRBuilder->DbgGetType(paramVar->mResolvedType);
  13971. bool wantRef = paramVar->mResolvedType->IsComposite();
  13972. if ((paramVar->mResolvedType->IsTypedPrimitive()) && (methodDef->HasNoThisSplat()))
  13973. wantRef = true;
  13974. if (wantRef)
  13975. diType = mBfIRBuilder->DbgCreateReferenceType(diType);
  13976. }
  13977. else if (!paramVar->mResolvedType->IsValueType())
  13978. {
  13979. diType = mBfIRBuilder->DbgCreateArtificialType(diType);
  13980. }
  13981. }
  13982. else
  13983. {
  13984. if ((paramVar->mResolvedType->IsComposite()) && (!paramVar->mIsSplat) && (!paramVar->mIsLowered))
  13985. {
  13986. diType = mBfIRBuilder->DbgGetType(paramVar->mResolvedType);
  13987. diType = mBfIRBuilder->DbgCreateReferenceType(diType);
  13988. diType = mBfIRBuilder->DbgCreateConstType(diType);
  13989. }
  13990. }
  13991. if ((!paramVar->mIsSplat) || (doDbgAgg))
  13992. {
  13993. if (paramVar->mResolvedType->IsValuelessType())
  13994. {
  13995. diVariable = mBfIRBuilder->DbgCreateAutoVariable(diFunction,
  13996. paramName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType);
  13997. }
  13998. else if (paramVar->mIsImplicitParam)
  13999. {
  14000. // Annotate this specially?
  14001. diVariable = mBfIRBuilder->DbgCreateParameterVariable(diFunction,
  14002. paramName, argIdx + 1, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType, true, 0);
  14003. }
  14004. else
  14005. {
  14006. diVariable = mBfIRBuilder->DbgCreateParameterVariable(diFunction,
  14007. paramName, argIdx + 1, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType, true, 0);
  14008. }
  14009. paramVar->mDbgVarInst = diVariable;
  14010. }
  14011. else if ((paramVar->mIsSplat) && (paramVar->mResolvedType->GetSplatCount() == 0))
  14012. {
  14013. // if ((mBfIRBuilder->HasDebugLocation()) && (wantsDIVariables))
  14014. // {
  14015. // // Only add this placeholder if we don't have any values
  14016. // auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(mCurMethodState->mCurScope->mDIScope,
  14017. // paramName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType);
  14018. // mBfIRBuilder->DbgInsertValueIntrinsic(GetConstValue(0), diVariable);
  14019. // }
  14020. }
  14021. }
  14022. bool isTypedPrimCtor = mCurTypeInstance->IsTypedPrimitive() && (methodDef->mMethodType == BfMethodType_Ctor);
  14023. if ((!paramVar->mParamFailed) && (paramVar->mAddr))
  14024. {
  14025. // Write our argument value into the .addr
  14026. mBfIRBuilder->ClearDebugLocation();
  14027. if (paramVar->mIsSplat)
  14028. {
  14029. mBfIRBuilder->PopulateType(paramVar->mResolvedType);
  14030. if (doDbgAgg)
  14031. {
  14032. auto curArgIdx = argIdx;
  14033. std::function<void(BfType*, BfIRValue)> checkTypeLambda = [&](BfType* checkType, BfIRValue curDestAddr)
  14034. {
  14035. if (checkType->IsStruct())
  14036. {
  14037. auto checkTypeInstance = checkType->ToTypeInstance();
  14038. if (checkTypeInstance->mBaseType != NULL)
  14039. {
  14040. auto baseDestAddr = mBfIRBuilder->CreateBitCast(curDestAddr, mBfIRBuilder->MapTypeInstPtr(checkTypeInstance->mBaseType));
  14041. checkTypeLambda(checkTypeInstance->mBaseType, baseDestAddr);
  14042. }
  14043. if (checkTypeInstance->mIsUnion)
  14044. {
  14045. auto unionInnerType = checkTypeInstance->GetUnionInnerType();
  14046. if (!unionInnerType->IsValuelessType())
  14047. {
  14048. auto newDestAddr = mBfIRBuilder->CreateInBoundsGEP(curDestAddr, 0, 1);
  14049. checkTypeLambda(unionInnerType, newDestAddr);
  14050. }
  14051. if (checkTypeInstance->IsEnum())
  14052. {
  14053. auto dscrType = checkTypeInstance->GetDiscriminatorType();
  14054. auto newDestAddr = mBfIRBuilder->CreateInBoundsGEP(curDestAddr, 0, 2);
  14055. checkTypeLambda(dscrType, newDestAddr);
  14056. }
  14057. }
  14058. else
  14059. {
  14060. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  14061. {
  14062. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  14063. if (fieldInstance->mDataIdx >= 0)
  14064. {
  14065. auto newDestAddr = mBfIRBuilder->CreateInBoundsGEP(curDestAddr, 0, fieldInstance->mDataIdx);
  14066. checkTypeLambda(fieldInstance->GetResolvedType(), newDestAddr);
  14067. }
  14068. }
  14069. }
  14070. }
  14071. else if (checkType->IsMethodRef())
  14072. {
  14073. BF_FATAL("Unimplemented");
  14074. // BfMethodRefType* methodRefType = (BfMethodRefType*)checkType;
  14075. // for (int dataIdx = 0; dataIdx < methodRefType->GetCaptureDataCount(); dataIdx++)
  14076. // {
  14077. // checkTypeLambda->
  14078. // }
  14079. }
  14080. else if (!checkType->IsValuelessType())
  14081. {
  14082. mBfIRBuilder->CreateAlignedStore(mBfIRBuilder->GetArgument(curArgIdx), curDestAddr, paramVar->mResolvedType->mAlign);
  14083. curArgIdx++;
  14084. }
  14085. };
  14086. checkTypeLambda(paramVar->mResolvedType, paramVar->mAddr);
  14087. }
  14088. }
  14089. else
  14090. {
  14091. bool handled = false;
  14092. //if ((!isThis) || (!methodDef->mIsMutating && !methodDef->mNoSplat))
  14093. if (paramVar->mIsLowered)
  14094. {
  14095. auto loweredTypeCode = paramVar->mResolvedType->GetLoweredType();
  14096. BF_ASSERT(loweredTypeCode != BfTypeCode_None);
  14097. if (loweredTypeCode != BfTypeCode_None)
  14098. {
  14099. // We have a lowered type coming in, so we have to cast the .addr before storing
  14100. auto primType = GetPrimitiveType(loweredTypeCode);
  14101. auto primPtrType = CreatePointerType(primType);
  14102. auto primPtrVal = mBfIRBuilder->CreateBitCast(paramVar->mAddr, mBfIRBuilder->MapType(primPtrType));
  14103. mBfIRBuilder->CreateAlignedStore(paramVar->mValue, primPtrVal, paramVar->mResolvedType->mSize);
  14104. // We don't want to allow directly using value
  14105. paramVar->mValue = BfIRValue();
  14106. handled = true;
  14107. }
  14108. }
  14109. if (!handled)
  14110. mBfIRBuilder->CreateAlignedStore(paramVar->mValue, paramVar->mAddr, paramVar->mResolvedType->mAlign);
  14111. }
  14112. }
  14113. if (!isThis)
  14114. declArgIdx++;
  14115. if (methodDef->mBody != NULL)
  14116. UpdateSrcPos(methodDef->mBody);
  14117. else if (methodDef->mDeclaringType->mTypeDeclaration != NULL)
  14118. UpdateSrcPos(methodDef->mDeclaringType->mTypeDeclaration);
  14119. else if (methodDeclaration == NULL)
  14120. UseDefaultSrcPos();
  14121. // Write our argument value into the .addr
  14122. if ((!doDbgAgg) && (paramVar->mIsSplat))
  14123. {
  14124. int splatComponentIdx = 0;
  14125. auto curArgIdx = argIdx;
  14126. auto _FinishSplats = [&] (BfType* checkType, const StringImpl& name)
  14127. {
  14128. BfIRValue splatAddrValue = splatAddrValues[splatAddrIdx++];
  14129. methodState.mSplatDecompAddrs.push_back(splatAddrValue);
  14130. auto storeInst = mBfIRBuilder->CreateAlignedStore(mBfIRBuilder->GetArgument(curArgIdx), splatAddrValue, checkType->mAlign);
  14131. mBfIRBuilder->ClearDebugLocation(storeInst);
  14132. if (wantsDIData)
  14133. {
  14134. BfIRMDNode diType;
  14135. if (checkType->IsComposite())
  14136. diType = mBfIRBuilder->DbgGetType(CreateRefType(checkType));
  14137. else
  14138. diType = mBfIRBuilder->DbgGetType(checkType);
  14139. auto diVariable = mBfIRBuilder->DbgCreateParameterVariable(diFunction,
  14140. name, curArgIdx + 1, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType);
  14141. if (wantsDIVariables)
  14142. {
  14143. mBfIRBuilder->DbgInsertDeclare(splatAddrValue, diVariable);
  14144. }
  14145. }
  14146. curArgIdx++;
  14147. splatComponentIdx++;
  14148. };
  14149. std::function<void(BfType*, const StringImpl&)> _FinishSplatsIterate = [&](BfType* checkType, const StringImpl& name)
  14150. {
  14151. if (checkType->IsStruct())
  14152. {
  14153. auto checkTypeInstance = checkType->ToTypeInstance();
  14154. if (checkTypeInstance->mBaseType != NULL)
  14155. {
  14156. _FinishSplatsIterate(checkTypeInstance->mBaseType, name + "$b");
  14157. }
  14158. if (checkTypeInstance->mIsUnion)
  14159. {
  14160. auto unionInnerType = checkTypeInstance->GetUnionInnerType();
  14161. if (!unionInnerType->IsValuelessType())
  14162. {
  14163. _FinishSplatsIterate(unionInnerType, name + "$u");
  14164. }
  14165. if (checkTypeInstance->IsEnum())
  14166. {
  14167. auto dscrType = checkTypeInstance->GetDiscriminatorType();
  14168. _FinishSplatsIterate(dscrType, name + "$d");
  14169. }
  14170. }
  14171. else
  14172. {
  14173. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  14174. {
  14175. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  14176. auto fieldDef = fieldInstance->GetFieldDef();
  14177. if (fieldInstance->mDataIdx >= 0)
  14178. {
  14179. _FinishSplatsIterate(fieldInstance->GetResolvedType(), name + "$m$" + fieldDef->mName);
  14180. }
  14181. }
  14182. }
  14183. }
  14184. else if (checkType->IsMethodRef())
  14185. {
  14186. auto methodRefType = (BfMethodRefType*)checkType;
  14187. BfMethodInstance* methodInstance = methodRefType->mMethodRef;
  14188. // int implicitParamCount = methodInstance->GetImplicitParamCount();
  14189. // for (int implicitParamIdx = methodInstance->HasThis() ? -1 : 0; implicitParamIdx < implicitParamCount; implicitParamIdx++)
  14190. // {
  14191. // auto paramType = methodInstance->GetParamType(implicitParamIdx);
  14192. // if (!paramType->IsValuelessType())
  14193. // _FinishSplats(paramType, name + "$m$" + methodInstance->GetParamName(implicitParamIdx));
  14194. // }
  14195. for (int dataIdx = 0; dataIdx < methodRefType->GetCaptureDataCount(); dataIdx++)
  14196. {
  14197. int paramIdx = methodRefType->GetParamIdxFromDataIdx(dataIdx);
  14198. String paramName = methodInstance->GetParamName(paramIdx);
  14199. if (paramName == "this")
  14200. paramName = "__this";
  14201. if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  14202. {
  14203. _FinishSplatsIterate(methodRefType->GetCaptureType(dataIdx), name + "$m$" + paramName);
  14204. }
  14205. else
  14206. {
  14207. _FinishSplats(methodRefType->GetCaptureType(dataIdx), name + "$m$" + paramName);
  14208. }
  14209. }
  14210. }
  14211. else if (!checkType->IsValuelessType())
  14212. {
  14213. _FinishSplats(checkType, name);
  14214. }
  14215. };
  14216. mBfIRBuilder->PopulateType(paramVar->mResolvedType);
  14217. if (!paramVar->mConstValue)
  14218. _FinishSplatsIterate(paramVar->mResolvedType, "$" + paramVar->mName);
  14219. }
  14220. BfIRValue declareCall;
  14221. if (diVariable)
  14222. {
  14223. if ((mBfIRBuilder->HasDebugLocation()) && (wantsDIVariables))
  14224. {
  14225. if (!paramVar->mAddr)
  14226. {
  14227. if ((!paramVar->mValue) || (paramVar->mValue.IsFake()))
  14228. {
  14229. if ((!paramVar->mIsThis) && (mCompiler->mOptions.mToolsetType != BfToolsetType_GNU)) // DWARF chokes on this:
  14230. {
  14231. // We don't need to set the location for this
  14232. mBfIRBuilder->DbgInsertValueIntrinsic(BfIRValue(), diVariable);
  14233. }
  14234. }
  14235. else
  14236. declareCall = mBfIRBuilder->DbgInsertDeclare(paramVar->mValue, diVariable);
  14237. }
  14238. else
  14239. {
  14240. declareCall = mBfIRBuilder->DbgInsertDeclare(paramVar->mAddr, diVariable);
  14241. }
  14242. }
  14243. }
  14244. if ((isThis) && (!paramVar->mIsSplat) && (paramVar->mAddr))
  14245. {
  14246. // We don't allow actually assignment to "this", so we just do a single load
  14247. // Keep in mind we don't use the ACTUAL mValue value because that's a register, but
  14248. // we need to store it in the stack frame for debugging purposes
  14249. auto loadedThis = mBfIRBuilder->CreateLoad(paramVar->mAddr/*, "this"*/);
  14250. mBfIRBuilder->ClearDebugLocation(loadedThis);
  14251. paramVar->mValue = loadedThis;
  14252. }
  14253. if ((wantsDIData) && (declareCall))
  14254. mBfIRBuilder->UpdateDebugLocation(declareCall);
  14255. if (paramVar->mIsSplat)
  14256. {
  14257. BfTypeUtils::SplatIterate([&](BfType* checkType) { argIdx++; }, paramVar->mResolvedType);
  14258. }
  14259. else if (!paramVar->mResolvedType->IsValuelessType())
  14260. {
  14261. argIdx++;
  14262. }
  14263. }
  14264. if (wantsDIData)
  14265. {
  14266. BF_ASSERT(splatAddrIdx == (int)splatAddrValues.size());
  14267. }
  14268. }
  14269. for (int varIdx = 0; varIdx < (int)mCurMethodState->mLocals.size(); varIdx++)
  14270. {
  14271. auto paramVar = mCurMethodState->mLocals[varIdx];
  14272. // 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
  14273. // splat member. If the "splat" is valueless then we do create a placeholder, but further up in this method
  14274. // if (paramVar->mIsSplat)
  14275. // {
  14276. // if (wantsDIVariables)
  14277. // {
  14278. // auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(diFunction, paramVar->mName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, mBfIRBuilder->DbgGetType(paramVar->mResolvedType));
  14279. // mBfIRBuilder->DbgInsertValueIntrinsic(mBfIRBuilder->CreateConst(BfTypeCode_Int64, 0), diVariable);
  14280. // }
  14281. // }
  14282. if (paramVar->mResolvedType->IsValuelessType())
  14283. {
  14284. if ((mBfIRBuilder->HasDebugLocation()) && (wantsDIVariables) && (mCompiler->mOptions.mToolsetType != BfToolsetType_GNU)) // DWARF chokes on this:
  14285. {
  14286. // Only add this placeholder if we don't have any values
  14287. auto diType = mBfIRBuilder->DbgGetType(paramVar->mResolvedType);
  14288. auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(mCurMethodState->mCurScope->mDIScope,
  14289. paramVar->mName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType);
  14290. mBfIRBuilder->DbgInsertValueIntrinsic(BfIRValue(), diVariable);
  14291. }
  14292. }
  14293. }
  14294. if (IsTargetingBeefBackend())
  14295. mCurMethodState->mCurScope->mValueScopeStart = mBfIRBuilder->CreateValueScopeStart();
  14296. if (methodState.mClosureState != NULL)
  14297. {
  14298. for (auto& constLocal : methodState.mClosureState->mConstLocals)
  14299. {
  14300. BfLocalVariable* localVar = new BfLocalVariable();
  14301. *localVar = constLocal;
  14302. AddLocalVariableDef(localVar, true);
  14303. }
  14304. }
  14305. bool wantsRemoveBody = false;
  14306. bool skipBody = false;
  14307. bool skipUpdateSrcPos = false;
  14308. bool skipEndChecks = false;
  14309. bool hasExternSpecifier = (methodDeclaration != NULL) && (methodDeclaration->mExternSpecifier != NULL) && (methodDef->mImportKind != BfImportKind_Dynamic);
  14310. auto propertyDeclaration = methodDef->GetPropertyDeclaration();
  14311. if ((methodDef != NULL) && (propertyDeclaration != NULL) && (propertyDeclaration->mExternSpecifier != NULL))
  14312. hasExternSpecifier = true;
  14313. // Allocate, clear, set classVData
  14314. if ((methodDef->mMethodType == BfMethodType_Ctor) && (methodDef->mIsStatic))
  14315. {
  14316. CreateStaticCtor();
  14317. }
  14318. else if ((mCurTypeInstance->IsBoxed()) && (methodDef->mMethodType != BfMethodType_Ctor) && (methodDef->mName != BF_METHODNAME_DYNAMICCAST) && (methodDef->mName != BF_METHODNAME_DYNAMICCAST_INTERFACE))
  14319. {
  14320. skipBody = true;
  14321. skipEndChecks = true;
  14322. if (HasCompiledOutput())
  14323. {
  14324. // Clear out DebugLoc - to mark the ".addr" code as part of prologue
  14325. mBfIRBuilder->ClearDebugLocation();
  14326. BfBoxedType* boxedType = (BfBoxedType*) mCurTypeInstance;
  14327. BfTypeInstance* innerType = boxedType->mElementType;
  14328. PopulateType(innerType, BfPopulateType_DataAndMethods);
  14329. mBfIRBuilder->PopulateType(mCurTypeInstance);
  14330. BfGetMethodInstanceFlags flags = BfGetMethodInstanceFlag_None;
  14331. if (methodInstance->mIsForeignMethodDef)
  14332. {
  14333. flags = BfGetMethodInstanceFlag_ForeignMethodDef;
  14334. }
  14335. BfTypeVector methodGenericArguments;
  14336. if (methodInstance->mMethodInfoEx != NULL)
  14337. methodGenericArguments = methodInstance->mMethodInfoEx->mMethodGenericArguments;
  14338. auto innerMethodInstance = GetMethodInstance(innerType, methodDef, methodGenericArguments, flags, methodInstance->GetForeignType());
  14339. if (innerMethodInstance.mMethodInstance->IsSkipCall())
  14340. {
  14341. if (!methodInstance->mReturnType->IsValuelessType())
  14342. {
  14343. auto retVal = GetDefaultValue(methodInstance->mReturnType);
  14344. CreateReturn(retVal);
  14345. }
  14346. }
  14347. else
  14348. {
  14349. BF_ASSERT(innerMethodInstance.mMethodInstance->mMethodDef == methodDef);
  14350. SizedArray<BfIRValue, 8> innerParams;
  14351. BfExprEvaluator exprEvaluator(this);
  14352. if (!innerType->IsValuelessType())
  14353. {
  14354. BfIRValue thisValue = mBfIRBuilder->CreateInBoundsGEP(mCurMethodState->mLocals[0]->mValue, 0, 1);
  14355. BfTypedValue innerVal(thisValue, innerType, true);
  14356. if (boxedType->IsBoxedStructPtr())
  14357. {
  14358. innerVal = LoadValue(innerVal);
  14359. innerVal = BfTypedValue(innerVal.mValue, innerType, true);
  14360. }
  14361. exprEvaluator.PushThis(NULL, innerVal, innerMethodInstance.mMethodInstance, innerParams);
  14362. }
  14363. for (int i = 1; i < (int)mCurMethodState->mLocals.size(); i++)
  14364. {
  14365. BfLocalVariable* localVar = mCurMethodState->mLocals[i];
  14366. BfTypedValue localVal = exprEvaluator.LoadLocal(localVar, true);
  14367. exprEvaluator.PushArg(localVal, innerParams);
  14368. }
  14369. if (!innerMethodInstance.mFunc)
  14370. {
  14371. BF_ASSERT(innerType->IsUnspecializedType());
  14372. }
  14373. else if (methodInstance->HasStructRet())
  14374. {
  14375. mBfIRBuilder->PopulateType(methodInstance->mReturnType);
  14376. auto returnType = BfTypedValue(mBfIRBuilder->GetArgument(0), methodInstance->mReturnType, true);
  14377. exprEvaluator.mReceivingValue = &returnType;
  14378. auto retVal = exprEvaluator.CreateCall(innerMethodInstance.mMethodInstance, innerMethodInstance.mFunc, true, innerParams, NULL, true);
  14379. BF_ASSERT(exprEvaluator.mReceivingValue == NULL); // Ensure it was actually used
  14380. mBfIRBuilder->CreateRetVoid();
  14381. }
  14382. else
  14383. {
  14384. mBfIRBuilder->PopulateType(methodInstance->mReturnType);
  14385. auto retVal = exprEvaluator.CreateCall(innerMethodInstance.mMethodInstance, innerMethodInstance.mFunc, true, innerParams, NULL, true);
  14386. if (mCurMethodInstance->mReturnType->IsValueType())
  14387. retVal = LoadValue(retVal);
  14388. CreateReturn(retVal.mValue);
  14389. }
  14390. }
  14391. }
  14392. mCurMethodState->SetHadReturn(true);
  14393. mCurMethodState->mLeftBlockUncond = true;
  14394. }
  14395. else if (methodDef->mMethodType == BfMethodType_CtorClear)
  14396. {
  14397. SetIllegalSrcPos();
  14398. mBfIRBuilder->ClearDebugLocation();
  14399. PopulateType(mCurTypeInstance, BfPopulateType_Data);
  14400. auto thisVal = GetThis();
  14401. int prevSize = mContext->mBfObjectType->mInstSize;
  14402. int curSize = mCurTypeInstance->mInstSize;
  14403. if (curSize > prevSize)
  14404. {
  14405. auto int8PtrType = CreatePointerType(GetPrimitiveType(BfTypeCode_Int8));
  14406. auto int8PtrVal = mBfIRBuilder->CreateBitCast(thisVal.mValue, mBfIRBuilder->MapType(int8PtrType));
  14407. int8PtrVal = mBfIRBuilder->CreateInBoundsGEP(int8PtrVal, GetConstValue(prevSize));
  14408. mBfIRBuilder->CreateMemSet(int8PtrVal, GetConstValue8(0), GetConstValue(curSize - prevSize), GetConstValue(mCurTypeInstance->mInstAlign));
  14409. }
  14410. skipUpdateSrcPos = true;
  14411. }
  14412. else if (((methodDef->mMethodType == BfMethodType_Ctor) || (methodDef->mMethodType == BfMethodType_CtorNoBody)) && (!hasExternSpecifier))
  14413. {
  14414. EmitCtorBody(skipBody);
  14415. }
  14416. else if ((methodDef->mMethodType == BfMethodType_Dtor) && (!hasExternSpecifier))
  14417. {
  14418. EmitDtorBody();
  14419. skipBody = true;
  14420. }
  14421. if ((!mCurTypeInstance->IsBoxed()) && (methodDeclaration != NULL) && (methodDeclaration->mHadYield) && (methodDef->mBody != NULL))
  14422. {
  14423. EmitIteratorBlock(skipBody);
  14424. }
  14425. if (methodDef->mName == BF_METHODNAME_MARKMEMBERS)
  14426. {
  14427. // We need to be able to mark deleted objects
  14428. mCurMethodState->mIgnoreObjectAccessCheck = true;
  14429. }
  14430. auto customAttributes = methodInstance->GetCustomAttributes();
  14431. if ((customAttributes != NULL) && (customAttributes->Contains(mCompiler->mDisableObjectAccessChecksAttributeTypeDef)))
  14432. mCurMethodState->mIgnoreObjectAccessCheck = true;
  14433. if ((methodDef->mMethodType == BfMethodType_CtorNoBody) && (!methodDef->mIsStatic) &&
  14434. ((methodInstance->mChainType == BfMethodChainType_ChainHead) || (methodInstance->mChainType == BfMethodChainType_None)))
  14435. {
  14436. // We chain even non-default ctors to the default ctors
  14437. auto defaultCtor = methodInstance;
  14438. if (defaultCtor->mChainType == BfMethodChainType_ChainHead)
  14439. CallChainedMethods(defaultCtor, false);
  14440. }
  14441. auto bodyBlock = BfNodeDynCast<BfBlock>(methodDef->mBody);
  14442. if (methodDef->mBody == NULL)
  14443. {
  14444. if (methodDeclaration != NULL)
  14445. {
  14446. if (auto operatorDeclaration = BfNodeDynCast<BfOperatorDeclaration>(methodDeclaration))
  14447. {
  14448. if (operatorDeclaration->mIsConvOperator)
  14449. wantsRemoveBody = true;
  14450. }
  14451. }
  14452. bool isDllImport = false;
  14453. if (methodDef->mImportKind == BfImportKind_Static)
  14454. {
  14455. for (auto customAttr : methodInstance->GetCustomAttributes()->mAttributes)
  14456. {
  14457. if (customAttr.mType->mTypeDef->mFullName.ToString() == "System.ImportAttribute")
  14458. {
  14459. if (customAttr.mCtorArgs.size() == 1)
  14460. {
  14461. auto fileNameArg = customAttr.mCtorArgs[0];
  14462. int strNum = 0;
  14463. auto constant = mCurTypeInstance->mConstHolder->GetConstant(fileNameArg);
  14464. if (constant != NULL)
  14465. {
  14466. if (constant->IsNull())
  14467. continue; // Invalid
  14468. strNum = constant->mInt32;
  14469. }
  14470. else
  14471. {
  14472. strNum = GetStringPoolIdx(fileNameArg, mCurTypeInstance->mConstHolder);
  14473. }
  14474. if (!mImportFileNames.Contains(strNum))
  14475. mImportFileNames.Add(strNum);
  14476. }
  14477. }
  14478. }
  14479. //mImportFileNames
  14480. }
  14481. else if (methodDef->mImportKind == BfImportKind_Dynamic)
  14482. {
  14483. CreateDllImportMethod();
  14484. }
  14485. else if (((mCurTypeInstance->mTypeDef->mIsDelegate) || (mCurTypeInstance->mTypeDef->mIsFunction)) &&
  14486. (methodDef->mName == "Invoke") && (methodDef->mMethodType == BfMethodType_Normal))
  14487. {
  14488. if (mCurTypeInstance->mTypeDef->mIsFunction)
  14489. {
  14490. // Emit nothing
  14491. }
  14492. else
  14493. {
  14494. CreateDelegateInvokeMethod();
  14495. mCurMethodState->SetHadReturn(true);
  14496. mCurMethodState->mLeftBlockUncond = true;
  14497. }
  14498. }
  14499. else if ((methodDef->mName == BF_METHODNAME_DYNAMICCAST) || (methodDef->mName == BF_METHODNAME_DYNAMICCAST_INTERFACE))
  14500. {
  14501. if (mCurTypeInstance->IsObject())
  14502. {
  14503. CreateDynamicCastMethod();
  14504. }
  14505. else
  14506. {
  14507. mBfIRBuilder->CreateRet(GetDefaultValue(methodInstance->mReturnType));
  14508. mCurMethodState->mHadReturn = true;
  14509. }
  14510. }
  14511. else if ((methodDef->mName == BF_METHODNAME_ENUM_HASFLAG) && (mCurTypeInstance->IsEnum()) && (!mCurTypeInstance->IsBoxed()))
  14512. {
  14513. BfIRValue ret;
  14514. if (mCurMethodState->mLocals[1]->mResolvedType != mCurTypeInstance)
  14515. {
  14516. // This can happen if we provide an invalid name
  14517. AssertErrorState();
  14518. ret = mBfIRBuilder->CreateRet(GetDefaultValue(GetPrimitiveType(BfTypeCode_Boolean)));
  14519. }
  14520. else
  14521. {
  14522. // Unfortunate DebugLoc shenanigans-
  14523. // 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,
  14524. // so we only set the loc on the CreateRet which gets inlined out
  14525. mBfIRBuilder->SaveDebugLocation();
  14526. mBfIRBuilder->ClearDebugLocation();
  14527. BfIRValue fromBool;
  14528. if (!mCurTypeInstance->IsTypedPrimitive())
  14529. {
  14530. fromBool = GetDefaultValue(methodInstance->mReturnType);
  14531. }
  14532. else
  14533. {
  14534. auto andResult = mBfIRBuilder->CreateAnd(mCurMethodState->mLocals[0]->mValue, mCurMethodState->mLocals[1]->mValue);
  14535. auto toBool = mBfIRBuilder->CreateCmpNE(andResult, GetDefaultValue(mCurMethodState->mLocals[0]->mResolvedType));
  14536. fromBool = mBfIRBuilder->CreateNumericCast(toBool, false, BfTypeCode_Boolean);
  14537. }
  14538. mBfIRBuilder->RestoreDebugLocation();
  14539. ret = mBfIRBuilder->CreateRet(fromBool);
  14540. //ExtendLocalLifetimes(0);
  14541. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  14542. }
  14543. mCurMethodState->SetHadReturn(true);
  14544. mCurMethodState->mLeftBlockUncond = true;
  14545. }
  14546. else if (((methodDef->mName == BF_METHODNAME_ENUM_GETUNDERLYINGREF) || (methodDef->mName == BF_METHODNAME_ENUM_GETUNDERLYING)) &&
  14547. (mCurTypeInstance->IsEnum()) && (!mCurTypeInstance->IsBoxed()))
  14548. {
  14549. BfIRValue ret;
  14550. // Unfortunate DebugLoc shenanigans-
  14551. // 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,
  14552. // so we only set the loc on the CreateRet which gets inlined out
  14553. mBfIRBuilder->SaveDebugLocation();
  14554. mBfIRBuilder->ClearDebugLocation();
  14555. BfIRValue fromBool;
  14556. mBfIRBuilder->RestoreDebugLocation();
  14557. ret = mBfIRBuilder->CreateRet(GetThis().mValue);
  14558. //ExtendLocalLifetimes(0);
  14559. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  14560. mCurMethodState->SetHadReturn(true);
  14561. mCurMethodState->mLeftBlockUncond = true;
  14562. }
  14563. else if ((mCurTypeInstance->IsEnum()) && (!mCurTypeInstance->IsBoxed()) && (methodDef->mName == BF_METHODNAME_TO_STRING))
  14564. {
  14565. auto enumType = ResolveTypeDef(mCompiler->mEnumTypeDef);
  14566. if (HasCompiledOutput())
  14567. {
  14568. EmitEnumToStringBody();
  14569. }
  14570. mBfIRBuilder->CreateRetVoid();
  14571. mCurMethodState->SetHadReturn(true);
  14572. mCurMethodState->mLeftBlockUncond = true;
  14573. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  14574. }
  14575. else if ((mCurTypeInstance->IsTuple()) && (!mCurTypeInstance->IsBoxed()) && (methodDef->mName == BF_METHODNAME_TO_STRING))
  14576. {
  14577. auto enumType = ResolveTypeDef(mCompiler->mEnumTypeDef);
  14578. if (HasCompiledOutput())
  14579. {
  14580. EmitTupleToStringBody();
  14581. }
  14582. mBfIRBuilder->CreateRetVoid();
  14583. mCurMethodState->SetHadReturn(true);
  14584. mCurMethodState->mLeftBlockUncond = true;
  14585. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  14586. }
  14587. else if (methodDef->mName == BF_METHODNAME_DEFAULT_EQUALS)
  14588. {
  14589. CreateValueTypeEqualsMethod();
  14590. skipBody = true;
  14591. skipEndChecks = true;
  14592. }
  14593. else if ((methodDef->mName == BF_METHODNAME_EQUALS) && (typeDef == mCompiler->mValueTypeTypeDef))
  14594. {
  14595. CreateValueTypeEqualsMethod();
  14596. skipBody = true;
  14597. skipEndChecks = true;
  14598. }
  14599. else if (HasCompiledOutput())
  14600. {
  14601. if ((methodDef->mName == BF_METHODNAME_MARKMEMBERS) || (methodDef->mName == BF_METHODNAME_MARKMEMBERS_STATIC))
  14602. {
  14603. if (mCompiler->mOptions.mEnableRealtimeLeakCheck)
  14604. {
  14605. EmitGCMarkMembers();
  14606. }
  14607. else if (!mCurTypeInstance->IsObject())
  14608. {
  14609. }
  14610. }
  14611. else if (methodDef->mName == BF_METHODNAME_FIND_TLS_MEMBERS)
  14612. {
  14613. if (mCompiler->mOptions.mEnableRealtimeLeakCheck)
  14614. {
  14615. EmitGCFindTLSMembers();
  14616. }
  14617. }
  14618. }
  14619. }
  14620. else if (!skipBody)
  14621. {
  14622. bool isEmptyBodied = BfNodeDynCast<BfTokenNode>(methodDef->mBody) != NULL;
  14623. if (isEmptyBodied) // Generate autoProperty things
  14624. {
  14625. auto propertyDeclaration = methodDef->GetPropertyDeclaration();
  14626. if ((propertyDeclaration != NULL) && (!typeDef->HasAutoProperty(propertyDeclaration)))
  14627. {
  14628. if ((!mCurTypeInstance->IsInterface()) && (!hasExternSpecifier))
  14629. Fail("Body expected", methodDef->mBody);
  14630. }
  14631. else if (methodDef->mMethodType == BfMethodType_PropertyGetter)
  14632. {
  14633. if (methodInstance->mReturnType->IsValuelessType())
  14634. {
  14635. mBfIRBuilder->CreateRetVoid();
  14636. }
  14637. else if (HasCompiledOutput())
  14638. {
  14639. String autoPropName = typeDef->GetAutoPropertyName(propertyDeclaration);
  14640. BfFieldInstance* fieldInstance = GetFieldByName(mCurTypeInstance, autoPropName);
  14641. BfFieldDef* fieldDef = NULL;
  14642. if (fieldInstance != NULL)
  14643. fieldDef = fieldInstance->GetFieldDef();
  14644. BfType* retType = methodInstance->mReturnType;
  14645. if (retType->IsRef())
  14646. retType = retType->GetUnderlyingType();
  14647. if ((fieldInstance != NULL) && (fieldInstance->GetResolvedType() == retType) &&
  14648. ((fieldInstance->mDataIdx >= 0) || (fieldDef->IsNonConstStatic())))
  14649. {
  14650. BfTypedValue lookupValue;
  14651. if (fieldDef->IsNonConstStatic())
  14652. lookupValue = ReferenceStaticField(fieldInstance);
  14653. else if (mCurTypeInstance->IsObject())
  14654. lookupValue = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(GetThis().mValue, 0, fieldInstance->mDataIdx), fieldInstance->mResolvedType, true);
  14655. else
  14656. lookupValue = ExtractValue(GetThis(), fieldInstance, fieldInstance->mFieldIdx);
  14657. if (!methodInstance->mReturnType->IsRef())
  14658. lookupValue = LoadValue(lookupValue);
  14659. mBfIRBuilder->CreateRet(lookupValue.mValue);
  14660. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  14661. }
  14662. else
  14663. {
  14664. // This can happen if we have two properties with the same name but different types
  14665. AssertErrorState();
  14666. mBfIRBuilder->CreateRet(GetDefaultValue(methodInstance->mReturnType));
  14667. }
  14668. }
  14669. else
  14670. {
  14671. // During autocomplete, the actual type may not have the proper field instance
  14672. mBfIRBuilder->CreateRet(GetDefaultValue(methodInstance->mReturnType));
  14673. }
  14674. mCurMethodState->SetHadReturn(true);
  14675. }
  14676. else if (methodDef->mMethodType == BfMethodType_PropertySetter)
  14677. {
  14678. if (!mCompiler->IsAutocomplete())
  14679. {
  14680. String autoPropName = typeDef->GetAutoPropertyName(propertyDeclaration);
  14681. BfFieldInstance* fieldInstance = GetFieldByName(mCurTypeInstance, autoPropName);
  14682. auto fieldDef = fieldInstance->GetFieldDef();
  14683. auto& lastParam = mCurMethodState->mLocals.back();
  14684. if ((fieldInstance != NULL) && (fieldInstance->GetResolvedType() == lastParam->mResolvedType) &&
  14685. ((fieldInstance->mDataIdx >= 0) || (fieldDef->IsNonConstStatic())))
  14686. {
  14687. BfIRValue lookupAddr;
  14688. if (fieldDef->IsNonConstStatic())
  14689. lookupAddr = ReferenceStaticField(fieldInstance).mValue;
  14690. else
  14691. {
  14692. auto thisValue = GetThis();
  14693. if (thisValue.IsSplat())
  14694. {
  14695. BF_FATAL("Should not happen");
  14696. }
  14697. if (mCurTypeInstance->IsObject())
  14698. thisValue = LoadValue(thisValue);
  14699. lookupAddr = mBfIRBuilder->CreateInBoundsGEP(thisValue.mValue, 0, fieldInstance->mDataIdx);
  14700. }
  14701. mBfIRBuilder->CreateStore(lastParam->mValue, lookupAddr);
  14702. }
  14703. else if (!fieldInstance->mResolvedType->IsValuelessType())
  14704. {
  14705. // This can happen if we have two properties with the same name but different types
  14706. AssertErrorState();
  14707. }
  14708. }
  14709. }
  14710. }
  14711. if ((!mCurMethodInstance->mReturnType->IsValuelessType()) && (!isEmptyBodied))
  14712. {
  14713. mBfIRBuilder->PopulateType(mCurMethodInstance->mReturnType);
  14714. if (mCurMethodInstance->HasStructRet())
  14715. {
  14716. auto ptrType = CreatePointerType(mCurMethodInstance->mReturnType);
  14717. auto allocaInst = AllocLocalVariable(ptrType, "__return.addr", false);
  14718. auto storeInst = mBfIRBuilder->CreateStore(mBfIRBuilder->GetArgument(0), allocaInst);
  14719. mBfIRBuilder->ClearDebugLocation(storeInst);
  14720. mCurMethodState->mRetValAddr = allocaInst;
  14721. }
  14722. else
  14723. {
  14724. auto allocaInst = AllocLocalVariable(mCurMethodInstance->mReturnType, "__return", false);
  14725. mCurMethodState->mRetVal = BfTypedValue(allocaInst, mCurMethodInstance->mReturnType, true);
  14726. }
  14727. }
  14728. if (methodDef->mMethodType == BfMethodType_CtorCalcAppend)
  14729. {
  14730. mBfIRBuilder->CreateStore(GetConstValue(0), mCurMethodState->mRetVal.mValue);
  14731. BfGetSymbolReferenceKind prevSymbolKind;
  14732. BfAutoComplete* prevAutoComplete;
  14733. if (mCompiler->mResolvePassData != NULL)
  14734. {
  14735. prevSymbolKind = mCompiler->mResolvePassData->mGetSymbolReferenceKind;
  14736. prevAutoComplete = mCompiler->mResolvePassData->mAutoComplete;
  14737. mCompiler->mResolvePassData->mGetSymbolReferenceKind = BfGetSymbolReferenceKind_None;
  14738. }
  14739. EmitCtorCalcAppend();
  14740. if (mCompiler->mResolvePassData != NULL)
  14741. {
  14742. mCompiler->mResolvePassData->mGetSymbolReferenceKind = prevSymbolKind;
  14743. mCompiler->mResolvePassData->mAutoComplete = prevAutoComplete;
  14744. }
  14745. }
  14746. else if (!isEmptyBodied)
  14747. {
  14748. if (!mCurMethodState->mIRExitBlock)
  14749. mCurMethodState->mIRExitBlock = mBfIRBuilder->CreateBlock("exit", true);
  14750. bool isExpressionBody = false;
  14751. if (methodDeclaration != NULL)
  14752. {
  14753. if (methodDeclaration->mFatArrowToken != NULL)
  14754. isExpressionBody = true;
  14755. }
  14756. else if (auto propertyDeclaration = methodDef->GetPropertyDeclaration())
  14757. {
  14758. if (auto propBodyExpr = BfNodeDynCast<BfPropertyBodyExpression>(propertyDeclaration->mDefinitionBlock))
  14759. {
  14760. isExpressionBody = true;
  14761. }
  14762. }
  14763. else
  14764. {
  14765. if (auto block = BfNodeDynCast<BfBlock>(methodDef->mBody))
  14766. {
  14767. if (!block->mChildArr.IsEmpty())
  14768. {
  14769. if (auto exprStmt = BfNodeDynCast<BfExpressionStatement>(block->mChildArr.GetLast()))
  14770. {
  14771. if (exprStmt->mTrailingSemicolon == NULL)
  14772. isExpressionBody = true;
  14773. }
  14774. }
  14775. }
  14776. else
  14777. isExpressionBody = true;
  14778. }
  14779. if (auto fieldDtorBody = BfNodeDynCast<BfFieldDtorDeclaration>(methodDef->mBody))
  14780. {
  14781. while (fieldDtorBody != NULL)
  14782. {
  14783. VisitEmbeddedStatement(fieldDtorBody->mBody);
  14784. fieldDtorBody = fieldDtorBody->mNextFieldDtor;
  14785. }
  14786. }
  14787. else if (!isExpressionBody)
  14788. {
  14789. auto bodyBlock = BfNodeDynCast<BfBlock>(methodDef->mBody);
  14790. mCurMethodState->mHeadScope.mAstBlock = bodyBlock;
  14791. mCurMethodState->mHeadScope.mCloseNode = bodyBlock->mCloseBrace;
  14792. VisitCodeBlock(bodyBlock);
  14793. }
  14794. else if (auto expressionBody = BfNodeDynCast<BfExpression>(methodDef->mBody))
  14795. {
  14796. if ((methodDef->mMethodType != BfMethodType_Normal) && (propertyDeclaration == NULL))
  14797. {
  14798. BF_ASSERT(methodDeclaration->mFatArrowToken != NULL);
  14799. Fail("Only normal methods can have expression bodies", methodDeclaration->mFatArrowToken);
  14800. }
  14801. auto expectingType = mCurMethodInstance->mReturnType;
  14802. // if ((expectingType->IsVoid()) && (IsInSpecializedSection()))
  14803. // {
  14804. // Warn(0, "Using a 'void' return with an expression-bodied method isn't needed. Consider removing '=>' token", methodDeclaration->mFatArrowToken);
  14805. // }
  14806. //TODO: Why did we have all this stuff for handling void?
  14807. // if (expectingType->IsVoid())
  14808. // {
  14809. // bool wasReturnGenericParam = false;
  14810. // if ((mCurMethodState->mClosureState != NULL) && (mCurMethodState->mClosureState->mReturnType != NULL))
  14811. // {
  14812. // wasReturnGenericParam = mCurMethodState->mClosureState->mReturnType->IsGenericParam();
  14813. // }
  14814. // else
  14815. // {
  14816. // auto unspecializedMethodInstance = GetUnspecializedMethodInstance(mCurMethodInstance);
  14817. // if ((unspecializedMethodInstance != NULL) && (unspecializedMethodInstance->mReturnType->IsGenericParam()))
  14818. // wasReturnGenericParam = true;
  14819. // }
  14820. //
  14821. // // If we the void return was from a generic specialization, allow us to return a void result,
  14822. // // otherwise treat expression as though it must be a statement
  14823. // bool isStatement = expressionBody->VerifyIsStatement(mCompiler->mPassInstance, wasReturnGenericParam);
  14824. // if (isStatement)
  14825. // expectingType = NULL;
  14826. // }
  14827. UpdateSrcPos(expressionBody);
  14828. auto retVal = CreateValueFromExpression(expressionBody, expectingType);
  14829. if ((retVal) && (expectingType != NULL))
  14830. {
  14831. mCurMethodState->mHadReturn = true;
  14832. retVal = LoadValue(retVal);
  14833. EmitReturn(retVal.mValue);
  14834. }
  14835. }
  14836. }
  14837. }
  14838. BF_ASSERT(mCurMethodState->mCurScope == &mCurMethodState->mHeadScope);
  14839. if (skipUpdateSrcPos)
  14840. {
  14841. // Skip
  14842. }
  14843. else if ((bodyBlock != NULL) && (bodyBlock->mCloseBrace != NULL))
  14844. UpdateSrcPos(bodyBlock->mCloseBrace);
  14845. else if (methodDef->mBody != NULL)
  14846. UpdateSrcPos(methodDef->mBody);
  14847. else if (methodDeclaration != NULL)
  14848. UpdateSrcPos(methodDeclaration);
  14849. else if (methodDef->mDeclaringType->mTypeDeclaration != NULL)
  14850. UpdateSrcPos(methodDef->mDeclaringType->mTypeDeclaration);
  14851. else
  14852. UseDefaultSrcPos();
  14853. if (methodDef->mMethodType == BfMethodType_CtorCalcAppend)
  14854. {
  14855. if (mCurMethodState->mRetVal)
  14856. {
  14857. mCurMethodState->SetHadReturn(true);
  14858. auto retVal = mBfIRBuilder->CreateLoad(mCurMethodState->mRetVal.mValue);
  14859. mBfIRBuilder->CreateRet(retVal);
  14860. }
  14861. else
  14862. AssertErrorState();
  14863. }
  14864. if (!mCurMethodState->mHadReturn)
  14865. {
  14866. // Clear off the stackallocs that have occurred after a scopeData break
  14867. EmitDeferredScopeCalls(false, &mCurMethodState->mHeadScope, mCurMethodState->mIRExitBlock);
  14868. }
  14869. if (mCurMethodState->mIRExitBlock)
  14870. {
  14871. for (auto preExitBlock : mCurMethodState->mHeadScope.mAtEndBlocks)
  14872. mBfIRBuilder->MoveBlockToEnd(preExitBlock);
  14873. mBfIRBuilder->MoveBlockToEnd(mCurMethodState->mIRExitBlock);
  14874. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRExitBlock);
  14875. if (!mCurMethodState->mDIRetVal)
  14876. CreateDIRetVal();
  14877. }
  14878. for (auto localVar : mCurMethodState->mLocals)
  14879. {
  14880. if ((skipEndChecks) || (bodyBlock == NULL))
  14881. break;
  14882. LocalVariableDone(localVar, true);
  14883. }
  14884. if (mCurMethodState->mIRExitBlock)
  14885. {
  14886. if ((mCurMethodState->mRetVal) && (!mCurMethodInstance->HasStructRet()))
  14887. {
  14888. auto loadedVal = mBfIRBuilder->CreateLoad(mCurMethodState->mRetVal.mValue);
  14889. CreateReturn(loadedVal);
  14890. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  14891. if (mCurMethodState->mDIRetVal)
  14892. mBfIRBuilder->DbgLifetimeEnd(mCurMethodState->mDIRetVal);
  14893. }
  14894. else
  14895. {
  14896. // Have something on the last line to step onto
  14897. if (mHasFullDebugInfo)
  14898. {
  14899. if ((bodyBlock != NULL) && (bodyBlock->mCloseBrace != NULL))
  14900. UpdateSrcPos(bodyBlock->mCloseBrace);
  14901. EmitEnsureInstructionAt();
  14902. if ((irParamCount == 0) && (!IsTargetingBeefBackend()) && (mCompiler->mOptions.mAllowHotSwapping))
  14903. {
  14904. // This may be a case where we only emit 4 bytes, whereas we need 5 for a hot replace jump
  14905. mBfIRBuilder->EnsureFunctionPatchable();
  14906. }
  14907. }
  14908. mBfIRBuilder->CreateRetVoid();
  14909. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  14910. if (mCurMethodState->mDIRetVal)
  14911. mBfIRBuilder->DbgLifetimeEnd(mCurMethodState->mDIRetVal);
  14912. }
  14913. }
  14914. if ((mCurMethodInstance->mReturnType == NULL) || (mCurMethodInstance->mReturnType->IsValuelessType()))
  14915. {
  14916. if ((!mCurMethodState->mHadReturn) && (!mCurMethodState->mIRExitBlock))
  14917. {
  14918. if ((irParamCount == 0) && (!IsTargetingBeefBackend()) && (mCompiler->mOptions.mAllowHotSwapping))
  14919. {
  14920. // This may be a case where we only emit 4 bytes, whereas we need 5 for a hot replace jump
  14921. mBfIRBuilder->EnsureFunctionPatchable();
  14922. }
  14923. mBfIRBuilder->CreateRetVoid();
  14924. }
  14925. }
  14926. else
  14927. {
  14928. if (!mCurMethodState->mHadReturn)
  14929. {
  14930. auto refNode = mCurMethodInstance->mMethodDef->GetRefNode();
  14931. if (bodyBlock != NULL)
  14932. {
  14933. if (bodyBlock->mCloseBrace != NULL)
  14934. {
  14935. BfAstNode* target = bodyBlock->mCloseBrace;
  14936. Fail("Method must return value", target);
  14937. }
  14938. else
  14939. {
  14940. // It's possible to not have a closing brace if the method ends in an EOF
  14941. AssertErrorState();
  14942. }
  14943. }
  14944. }
  14945. }
  14946. // Move 'init' into 'entry'
  14947. mBfIRBuilder->MergeBlockDown(mCurMethodState->mIRInitBlock, mCurMethodState->mIREntryBlock);
  14948. mBfIRBuilder->MergeBlockDown(mCurMethodState->mIRHeadBlock, mCurMethodState->mIREntryBlock);
  14949. if ((mCurMethodInstance->mIsUnspecialized) /*|| (typeDef->mIsFunction)*/ || (mCurTypeInstance->IsUnspecializedType()))
  14950. {
  14951. // Don't keep instructions for unspecialized types
  14952. mBfIRBuilder->Func_DeleteBody(mCurMethodInstance->mIRFunction);
  14953. }
  14954. if ((hasExternSpecifier) && (!skipBody))
  14955. {
  14956. // If we hot swap, we want to make sure at least one method refers to this extern method so it gets pulled in
  14957. // incase it gets called later by some hot-loaded coded
  14958. if (mCompiler->mOptions.mAllowHotSwapping)
  14959. CreateFakeCallerMethod(mangledName);
  14960. mBfIRBuilder->Func_DeleteBody(mCurMethodInstance->mIRFunction);
  14961. }
  14962. else if ((methodDef->mImportKind == BfImportKind_Dynamic) && (!mCompiler->IsHotCompile()))
  14963. {
  14964. // We only need the DLL stub when we may be hot swapping
  14965. mBfIRBuilder->Func_DeleteBody(mCurMethodInstance->mIRFunction);
  14966. }
  14967. else if (wantsRemoveBody)
  14968. mBfIRBuilder->Func_DeleteBody(mCurMethodInstance->mIRFunction);
  14969. // We don't want to hold on to pointers to LLVMFunctions of unspecialized types.
  14970. // This allows us to delete the mScratchModule LLVM module without rebuilding all
  14971. // unspecialized types
  14972. if ((mCurTypeInstance->IsUnspecializedType()) || (mCurTypeInstance->IsInterface()))
  14973. {
  14974. BfLogSysM("ProcessMethod Clearing IRFunction: %p\n", methodInstance);
  14975. methodInstance->mIRFunction = BfIRFunction();
  14976. }
  14977. CheckAddFailType();
  14978. if (mHadBuildError)
  14979. prevHadBuildError.CancelRestore();
  14980. if (mHadBuildWarning)
  14981. prevHadWarning.CancelRestore();
  14982. if (!methodDef->mIsLocalMethod)
  14983. ProcessMethod_ProcessDeferredLocals();
  14984. mBfIRBuilder->SetActiveFunction(prevActiveFunction);
  14985. if (methodState.mHotDataReferenceBuilder != NULL)
  14986. {
  14987. AddHotDataReferences(&hotDataReferenceBuilder);
  14988. }
  14989. else
  14990. {
  14991. if ((methodInstance->mHotMethod != NULL) && (!methodInstance->mIsReified))
  14992. {
  14993. // Remove the hot method data
  14994. auto hotMethod = methodInstance->mHotMethod;
  14995. auto prevMethod = hotMethod->mPrevVersion;
  14996. if (prevMethod != NULL)
  14997. {
  14998. // If there's a prev method then pull its data into the main HotMethod.
  14999. // This, in effect, removes the 'hotMethod' data and rebases 'prevMethod'
  15000. // over to the main HotMethod definition to keep the HotMethod address
  15001. // invariant
  15002. for (auto ref : hotMethod->mReferences)
  15003. ref->Deref();
  15004. hotMethod->mReferences.Clear();
  15005. BF_ASSERT(prevMethod->mRefCount == 1);
  15006. hotMethod->mReferences = prevMethod->mReferences;
  15007. if (hotMethod->mSrcTypeVersion != NULL)
  15008. hotMethod->mSrcTypeVersion->Deref();
  15009. hotMethod->mSrcTypeVersion = prevMethod->mSrcTypeVersion;
  15010. prevMethod->mSrcTypeVersion = NULL;
  15011. prevMethod->mReferences.Clear();
  15012. hotMethod->mPrevVersion = prevMethod->mPrevVersion;
  15013. prevMethod->mPrevVersion = NULL;
  15014. prevMethod->Deref();
  15015. }
  15016. hotMethod->Deref();
  15017. methodInstance->mHotMethod = NULL;
  15018. }
  15019. }
  15020. }
  15021. String BfModule::GetLocalMethodName(const StringImpl& baseName, BfAstNode* anchorNode, BfMethodState* declMethodState, BfMixinState* declMixinState)
  15022. {
  15023. String name;
  15024. bool found = false;
  15025. auto checkMethodState = mCurMethodState;
  15026. while (checkMethodState != NULL)
  15027. {
  15028. if (checkMethodState->mClosureState == NULL)
  15029. break;
  15030. if (checkMethodState->mClosureState->mClosureMethodDef != NULL)
  15031. {
  15032. found = true;
  15033. name += checkMethodState->mClosureState->mClosureMethodDef->mName;
  15034. break;
  15035. }
  15036. checkMethodState = checkMethodState->mPrevMethodState;
  15037. }
  15038. if (!found)
  15039. name += mCurMethodInstance->mMethodDef->mName;
  15040. int prevSepPos = (int)name.LastIndexOf('$');
  15041. if (prevSepPos != -1)
  15042. {
  15043. name.RemoveToEnd(prevSepPos);
  15044. }
  15045. name += "@";
  15046. name += baseName;
  15047. HashContext hashCtx;
  15048. if (anchorNode != NULL)
  15049. {
  15050. hashCtx.Mixin(anchorNode->GetStartCharId());
  15051. }
  15052. //
  15053. {
  15054. auto checkMethodState = declMethodState;
  15055. auto checkMixinState = declMixinState;
  15056. while (checkMethodState != NULL)
  15057. {
  15058. if (checkMixinState != NULL)
  15059. {
  15060. hashCtx.Mixin(checkMixinState->mSource->GetStartCharId());
  15061. }
  15062. checkMethodState = checkMethodState->mPrevMethodState;
  15063. if (checkMethodState != NULL)
  15064. checkMixinState = checkMethodState->mMixinState;
  15065. }
  15066. }
  15067. auto rootMethodState = mCurMethodState->GetRootMethodState();
  15068. if (rootMethodState->mMethodInstance->mMethodInfoEx != NULL)
  15069. {
  15070. for (auto methodGenericArg : rootMethodState->mMethodInstance->mMethodInfoEx->mMethodGenericArguments)
  15071. {
  15072. StringT<128> genericTypeName;
  15073. BfMangler::Mangle(genericTypeName, mCompiler->GetMangleKind(), methodGenericArg);
  15074. hashCtx.MixinStr(genericTypeName);
  15075. }
  15076. }
  15077. uint64 hashVal = hashCtx.Finish64();
  15078. name += "$";
  15079. name += BfTypeUtils::HashEncode64(hashVal);
  15080. return name;
  15081. }
  15082. BfMethodDef* BfModule::GetLocalMethodDef(BfLocalMethod* localMethod)
  15083. {
  15084. if (localMethod->mMethodDef != NULL)
  15085. return localMethod->mMethodDef;
  15086. auto rootMethodState = mCurMethodState->GetRootMethodState();
  15087. auto declMethodState = localMethod->mDeclMethodState;
  15088. auto declMixinState = localMethod->mDeclMixinState;
  15089. auto typeInst = mCurTypeInstance;
  15090. BfAstNode* body = NULL;
  15091. BfAstNode* anchorNode = NULL;
  15092. auto _AllocDirectTypeRef = [&](BfType* type)
  15093. {
  15094. BfDirectTypeReference* directTypeRef = localMethod->mDirectTypeRefs.Alloc();
  15095. directTypeRef->Init(type);
  15096. return directTypeRef;
  15097. };
  15098. auto methodDeclaration = localMethod->mMethodDeclaration;
  15099. if (methodDeclaration != NULL)
  15100. {
  15101. body = methodDeclaration->mBody;
  15102. anchorNode = methodDeclaration->mOpenParen;
  15103. }
  15104. else
  15105. {
  15106. body = localMethod->mLambdaBindExpr->mBody;
  15107. anchorNode = localMethod->mLambdaBindExpr->mFatArrowToken;
  15108. }
  15109. BF_ASSERT(rootMethodState->mCurLocalVarId >= 0);
  15110. int methodLocalIdx = rootMethodState->mCurLocalVarId++;
  15111. BfMethodDef* methodDef;
  15112. if (methodDeclaration != NULL)
  15113. {
  15114. BfDefBuilder defBuilder(mCompiler->mSystem);
  15115. defBuilder.mPassInstance = mCompiler->mPassInstance;
  15116. defBuilder.mCurTypeDef = mCurMethodInstance->mMethodDef->mDeclaringType;
  15117. BfMethodDef* outerMethodDef = NULL;
  15118. if (localMethod->mOuterLocalMethod != NULL)
  15119. outerMethodDef = localMethod->mOuterLocalMethod->mMethodDef;
  15120. else
  15121. outerMethodDef = rootMethodState->mMethodInstance->mMethodDef;
  15122. methodDef = defBuilder.CreateMethodDef(methodDeclaration, outerMethodDef);
  15123. }
  15124. else
  15125. {
  15126. auto invokeMethod = localMethod->mLambdaInvokeMethodInstance;
  15127. methodDef = new BfMethodDef();
  15128. methodDef->mName = localMethod->mMethodName;
  15129. methodDef->mDeclaringType = mCurMethodInstance->mMethodDef->mDeclaringType;
  15130. methodDef->mReturnTypeRef = _AllocDirectTypeRef(invokeMethod->mReturnType);
  15131. methodDef->mBody = body;
  15132. for (int paramIdx = 0; paramIdx < invokeMethod->GetParamCount(); paramIdx++)
  15133. {
  15134. auto paramType = invokeMethod->GetParamType(paramIdx);
  15135. String paramName;
  15136. if (paramIdx < (int)localMethod->mLambdaBindExpr->mParams.size())
  15137. paramName = localMethod->mLambdaBindExpr->mParams[paramIdx]->ToString();
  15138. else
  15139. paramName = invokeMethod->GetParamName(paramIdx);
  15140. auto paramDef = new BfParameterDef();
  15141. paramDef->mTypeRef = _AllocDirectTypeRef(paramType);
  15142. paramDef->mName = paramName;
  15143. methodDef->mParams.Add(paramDef);
  15144. }
  15145. }
  15146. methodDef->mIdx = ~methodLocalIdx;
  15147. BF_ASSERT(!localMethod->mExpectedFullName.IsEmpty());
  15148. methodDef->mName = localMethod->mExpectedFullName;
  15149. // methodDef->mName = GetLocalMethodName(methodDef->mName, anchorNode, declMethodState, declMixinState);
  15150. //
  15151. // if (!localMethod->mExpectedFullName.IsEmpty())
  15152. // BF_ASSERT(methodDef->mName == localMethod->mExpectedFullName);
  15153. methodDef->mIsStatic = true;
  15154. methodDef->mIsLocalMethod = true;
  15155. methodDef->mIsVirtual = false;
  15156. localMethod->mMethodDef = methodDef;
  15157. auto methodInstanceGroup = new BfMethodInstanceGroup();
  15158. localMethod->mMethodInstanceGroup = methodInstanceGroup;
  15159. methodInstanceGroup->mMethodIdx = -1;
  15160. methodInstanceGroup->mOwner = mCurTypeInstance;
  15161. methodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  15162. if ((declMethodState->mMixinState != NULL) && (declMethodState->mMixinState->mTarget))
  15163. {
  15164. methodInstanceGroup->mOwner = declMethodState->mMixinState->mTarget.mType->ToTypeInstance();
  15165. BF_ASSERT(methodInstanceGroup->mOwner != NULL);
  15166. }
  15167. if ((mCompiler->mResolvePassData != NULL) && (methodDeclaration != NULL))
  15168. {
  15169. mCompiler->mResolvePassData->HandleLocalReference(methodDeclaration->mNameNode, typeInst->mTypeDef, rootMethodState->mMethodInstance->mMethodDef, methodLocalIdx);
  15170. auto autoComplete = mCompiler->mResolvePassData->mAutoComplete;
  15171. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(methodDeclaration->mNameNode)))
  15172. {
  15173. autoComplete->SetDefinitionLocation(methodDeclaration->mNameNode);
  15174. autoComplete->mInsertStartIdx = methodDeclaration->mNameNode->GetSrcStart();
  15175. autoComplete->mInsertEndIdx = methodDeclaration->mNameNode->GetSrcEnd();
  15176. autoComplete->mDefType = typeInst->mTypeDef;
  15177. autoComplete->mDefMethod = rootMethodState->mMethodInstance->mMethodDef;
  15178. autoComplete->mReplaceLocalId = methodLocalIdx;
  15179. }
  15180. }
  15181. return localMethod->mMethodDef;
  15182. }
  15183. BfModuleMethodInstance BfModule::GetLocalMethodInstance(BfLocalMethod* localMethod, const BfTypeVector& methodGenericArguments, BfMethodInstance* methodInstance, bool force)
  15184. {
  15185. BP_ZONE_F("GetLocalMethodInstance %s", localMethod->mMethodName.c_str());
  15186. BfLogSysM("GetLocalMethodInstance %p\n", localMethod);
  15187. auto rootMethodState = mCurMethodState->GetRootMethodState();
  15188. auto declMethodState = localMethod->mDeclMethodState;
  15189. auto declMixinState = localMethod->mDeclMixinState;
  15190. auto callerMethodState = mCurMethodState;
  15191. auto typeInst = mCurTypeInstance;
  15192. auto methodDef = GetLocalMethodDef(localMethod);
  15193. BfAstNode* body = NULL;
  15194. auto methodDeclaration = localMethod->mMethodDeclaration;
  15195. if (methodDeclaration != NULL)
  15196. {
  15197. body = methodDeclaration->mBody;
  15198. }
  15199. else
  15200. {
  15201. body = localMethod->mLambdaBindExpr->mBody;
  15202. }
  15203. bool hadConcreteInterfaceGenericArgument = false;
  15204. BfTypeVector sanitizedMethodGenericArguments;
  15205. // Ignore the outermost method's generic method arguments for the purpose of determining if we are the 'default' (ie: unspecialized)
  15206. // version of this method for this pass through the outermost method
  15207. int dependentGenericStartIdx = 0;
  15208. if (rootMethodState->mMethodInstance->mMethodInfoEx != NULL)
  15209. dependentGenericStartIdx = (int)rootMethodState->mMethodInstance->mMethodInfoEx->mMethodGenericArguments.size();
  15210. BfMethodInstance* outerMethodInstance = mCurMethodInstance;
  15211. if (methodGenericArguments.size() == 0)
  15212. {
  15213. if (rootMethodState->mMethodInstance->mMethodInfoEx != NULL)
  15214. sanitizedMethodGenericArguments = rootMethodState->mMethodInstance->mMethodInfoEx->mMethodGenericArguments;
  15215. }
  15216. else
  15217. {
  15218. int genericArgIdx = 0;
  15219. // for (; genericArgIdx < (int)outerMethodInstance->mMethodGenericArguments.size(); genericArgIdx++)
  15220. // {
  15221. // BF_ASSERT(methodGenericArguments[genericArgIdx] == outerMethodInstance->mMethodGenericArguments[genericArgIdx]);
  15222. // sanitizedMethodGenericArguments.push_back(methodGenericArguments[genericArgIdx]);
  15223. // }
  15224. for (; genericArgIdx < (int)methodGenericArguments.size(); genericArgIdx++)
  15225. {
  15226. auto genericArgType = methodGenericArguments[genericArgIdx];
  15227. BF_ASSERT(!genericArgType->IsRef());
  15228. if (genericArgType->IsConcreteInterfaceType())
  15229. {
  15230. hadConcreteInterfaceGenericArgument = true;
  15231. auto concreteInterfaceType = (BfConcreteInterfaceType*)genericArgType;
  15232. genericArgType = concreteInterfaceType->mInterface;
  15233. }
  15234. sanitizedMethodGenericArguments.push_back(genericArgType);
  15235. }
  15236. }
  15237. bool wantPrematureMethodInstance = false;
  15238. if (!force)
  15239. {
  15240. wantPrematureMethodInstance = (callerMethodState->mClosureState != NULL) && (callerMethodState->mClosureState->mCaptureVisitingBody);
  15241. }
  15242. auto methodInstGroup = localMethod->mMethodInstanceGroup;
  15243. bool isDefaultPass = true;
  15244. BfTypeVector lookupMethodGenericArguments;
  15245. for (int genericArgIdx = dependentGenericStartIdx; genericArgIdx < (int)methodGenericArguments.size(); genericArgIdx++)
  15246. {
  15247. auto genericArgType = methodGenericArguments[genericArgIdx];
  15248. BF_ASSERT(!genericArgType->IsRef());
  15249. lookupMethodGenericArguments.Add(genericArgType);
  15250. if (genericArgType->IsGenericParam())
  15251. {
  15252. auto genericParam = (BfGenericParamType*)genericArgType;
  15253. if ((genericParam->mGenericParamKind != BfGenericParamKind_Method) || (genericParam->mGenericParamIdx != genericArgIdx))
  15254. isDefaultPass = false;
  15255. }
  15256. else
  15257. {
  15258. isDefaultPass = false;
  15259. }
  15260. }
  15261. bool hadExistingMethodInstance = false;
  15262. if (methodInstance != NULL)
  15263. {
  15264. hadExistingMethodInstance = true;
  15265. }
  15266. else
  15267. {
  15268. if (isDefaultPass)
  15269. {
  15270. methodInstance = methodInstGroup->mDefault;
  15271. if (methodInstance != NULL)
  15272. {
  15273. hadExistingMethodInstance = true;
  15274. }
  15275. else
  15276. {
  15277. methodInstance = new BfMethodInstance();
  15278. methodInstGroup->mDefault = methodInstance;
  15279. }
  15280. }
  15281. else
  15282. {
  15283. BF_ASSERT(sanitizedMethodGenericArguments.size() != 0);
  15284. if (methodInstGroup->mMethodSpecializationMap == NULL)
  15285. methodInstGroup->mMethodSpecializationMap = new BfMethodInstanceGroup::MapType();
  15286. BfMethodInstance** methodInstancePtr = NULL;
  15287. if (!methodInstGroup->mMethodSpecializationMap->TryAdd(lookupMethodGenericArguments, NULL, &methodInstancePtr))
  15288. {
  15289. methodInstance = *methodInstancePtr;
  15290. hadExistingMethodInstance = true;
  15291. }
  15292. else
  15293. {
  15294. methodInstance = new BfMethodInstance();
  15295. *methodInstancePtr = methodInstance;
  15296. }
  15297. }
  15298. }
  15299. if (hadExistingMethodInstance)
  15300. {
  15301. if ((!methodInstance->mDisallowCalling) ||
  15302. ((wantPrematureMethodInstance) && (methodInstance->mDisallowCalling)))
  15303. return BfModuleMethodInstance(methodInstance);
  15304. BF_ASSERT((methodInstance->mMethodInfoEx == NULL) || (methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureClosureState == NULL));
  15305. }
  15306. else
  15307. {
  15308. auto methodInfoEx = methodInstance->GetMethodInfoEx();
  15309. methodInfoEx->mClosureInstanceInfo = new BfClosureInstanceInfo();
  15310. methodInfoEx->mClosureInstanceInfo->mLocalMethod = localMethod;
  15311. methodInstance->mIsReified = mCurMethodInstance->mIsReified;
  15312. methodInstance->mIsAutocompleteMethod = mCurMethodInstance->mIsAutocompleteMethod;
  15313. methodInstance->mMethodDef = methodDef;
  15314. methodInstance->mMethodInstanceGroup = localMethod->mMethodInstanceGroup;
  15315. if (hadConcreteInterfaceGenericArgument)
  15316. methodInstance->mIgnoreBody = true;
  15317. methodInfoEx->mMethodGenericArguments = sanitizedMethodGenericArguments;
  15318. for (auto genericArg : sanitizedMethodGenericArguments)
  15319. {
  15320. if (genericArg->IsPrimitiveType())
  15321. genericArg = GetWrappedStructType(genericArg);
  15322. AddDependency(genericArg, typeInst, BfDependencyMap::DependencyFlag_MethodGenericArg);
  15323. }
  15324. for (int genericParamIdx = (int)sanitizedMethodGenericArguments.size(); genericParamIdx < (int)methodDef->mGenericParams.size(); genericParamIdx++)
  15325. {
  15326. auto genericParamType = GetGenericParamType(BfGenericParamKind_Method, genericParamIdx);
  15327. methodInfoEx->mMethodGenericArguments.push_back(genericParamType);
  15328. }
  15329. SetupMethodIdHash(methodInstance);
  15330. }
  15331. auto _SetupMethodInstance = [&]()
  15332. {
  15333. BF_ASSERT(methodInstance->GetNumGenericParams() == 0);
  15334. // Generic constraints
  15335. for (int genericParamIdx = 0; genericParamIdx < (int)methodDef->mGenericParams.size(); genericParamIdx++)
  15336. {
  15337. auto genericParamInstance = new BfGenericMethodParamInstance(methodDef, genericParamIdx);
  15338. methodInstance->GetMethodInfoEx()->mGenericParams.push_back(genericParamInstance);
  15339. }
  15340. };
  15341. //////////////////////////////////////////////////////////////////////////
  15342. auto _VisitLambdaBody = [&]()
  15343. {
  15344. if (localMethod->mDeclOnly)
  15345. return;
  15346. if (mCompiler->mCanceling)
  15347. return;
  15348. if (auto blockBody = BfNodeDynCast<BfBlock>(body))
  15349. {
  15350. VisitCodeBlock(blockBody);
  15351. }
  15352. else if (auto bodyExpr = BfNodeDynCast<BfExpression>(body))
  15353. CreateValueFromExpression(bodyExpr);
  15354. };
  15355. auto _SafeResolveTypeRef = [&](BfTypeReference* typeRef)
  15356. {
  15357. SetAndRestoreValue<bool> prevIgnoreError(mIgnoreErrors, true);
  15358. auto result = ResolveTypeRef(typeRef);
  15359. if (result == NULL)
  15360. result = mContext->mBfObjectType;
  15361. return result;
  15362. };
  15363. BfTypeInstance* outerClosure = NULL;
  15364. if ((declMethodState->mClosureState != NULL) && (!declMethodState->mClosureState->mCapturing))
  15365. outerClosure = declMethodState->mClosureState->mClosureType;
  15366. BfMethodState methodState;
  15367. methodState.mPrevMethodState = declMethodState;//mCurMethodState;
  15368. BfIRFunctionType funcType;
  15369. auto voidType = GetPrimitiveType(BfTypeCode_None);
  15370. SizedArray<BfIRType, 0> paramTypes;
  15371. funcType = mBfIRBuilder->CreateFunctionType(mBfIRBuilder->MapType(voidType), paramTypes, false);
  15372. mBfIRBuilder->SaveDebugLocation();
  15373. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  15374. auto prevActiveFunction = mBfIRBuilder->GetActiveFunction();
  15375. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, true);
  15376. BfDeferredLocalAssignData deferredLocalAssignData;
  15377. //TODO: Why did we do this? It can cause us to pull in local variables that don't belong to us...
  15378. /*if (declMethodState->mDeferredLocalAssignData != NULL)
  15379. deferredLocalAssignData.ExtendFrom(declMethodState->mDeferredLocalAssignData);*/
  15380. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  15381. methodState.mIRHeadBlock = mBfIRBuilder->CreateBlock("head", true);
  15382. methodState.mIRInitBlock = mBfIRBuilder->CreateBlock("init", true);
  15383. methodState.mIREntryBlock = mBfIRBuilder->CreateBlock("entry", true);
  15384. methodState.mCurScope->mDIScope = localMethod->mDeclDIScope; //declMethodState->mCurScope->mDIScope ;
  15385. //methodState.mCurLocalVarId = declMethodState->mCurLocalVarId;
  15386. methodState.mIRFunction = declMethodState->mIRFunction;
  15387. methodState.mDeferredLocalAssignData = &deferredLocalAssignData;
  15388. mBfIRBuilder->SetInsertPoint(methodState.mIREntryBlock);
  15389. BfClosureState closureState;
  15390. if (methodDef->mMethodType == BfMethodType_Mixin)
  15391. {
  15392. if (declMethodState != NULL)
  15393. {
  15394. if ((declMethodState->mClosureState != NULL) && (declMethodState->mClosureState->mReturnType != NULL))
  15395. closureState.mReturnType = declMethodState->mClosureState->mReturnType;
  15396. else if (declMethodState->mMethodInstance != NULL)
  15397. closureState.mReturnType = declMethodState->mMethodInstance->mReturnType;
  15398. }
  15399. }
  15400. if (closureState.mReturnType == NULL)
  15401. closureState.mReturnType = _SafeResolveTypeRef(methodDef->mReturnTypeRef);
  15402. closureState.mCapturing = true;
  15403. closureState.mLocalMethod = localMethod;
  15404. closureState.mClosureInstanceInfo = methodInstance->mMethodInfoEx->mClosureInstanceInfo;
  15405. closureState.mDeclaringMethodIsMutating = mCurMethodInstance->mMethodDef->mIsMutating;
  15406. methodState.mClosureState = &closureState;
  15407. closureState.mClosureType = outerClosure;
  15408. int outerLocalsCount = (int)methodState.mLocals.size();
  15409. if (!hadExistingMethodInstance)
  15410. {
  15411. BfLogSysM("LocalMethod %p premature DoMethodDeclaration %p (Source:%p)\n", localMethod, methodInstance, (methodDeclaration != NULL) ? methodDeclaration->GetSourceData() : NULL);
  15412. SetAndRestoreValue<bool> prevIgnoreWrites(mWantsIRIgnoreWrites, true);
  15413. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, true);
  15414. // Prematurely do declaration. We will have to undo this later, so don't write this one and don't throw errors
  15415. auto declareModule = this;
  15416. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(declareModule->mCurMethodInstance, methodInstance);
  15417. SetAndRestoreValue<BfFilePosition> prevFilePos(declareModule->mCurFilePosition);
  15418. BF_ASSERT(declareModule != NULL);
  15419. methodInstance->mDeclModule = declareModule;
  15420. _SetupMethodInstance();
  15421. declareModule->DoMethodDeclaration(localMethod->mMethodDef->GetMethodDeclaration(), false, false);
  15422. methodInstance->mDisallowCalling = true; // Don't allow us to ACTUALLY call until we add the captures
  15423. }
  15424. if (wantPrematureMethodInstance)
  15425. {
  15426. // Return a premature methodInstance -- since we are partway through determining the capture of a local method, we can't rely on its
  15427. // capture information. This returned method instance can only be used for method matching, but we will visit it later to create
  15428. // its true method instance
  15429. //auto moduleMethodInstance = _CheckReturnedMethod(methodInstance);
  15430. //BF_ASSERT(moduleMethodInstance);
  15431. return BfModuleMethodInstance(methodInstance);
  15432. }
  15433. auto checkInsertBlock = mBfIRBuilder->GetInsertBlock();
  15434. BF_ASSERT(methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureClosureState == NULL);
  15435. closureState.mCaptureStartAccessId = mCurMethodState->GetRootMethodState()->mCurAccessId;
  15436. methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureClosureState = &closureState;
  15437. closureState.mClosureMethodDef = methodDef;
  15438. bool wantsVisitBody = true;
  15439. if ((methodDef->mMethodType == BfMethodType_Mixin) && (!methodGenericArguments.IsEmpty()))
  15440. wantsVisitBody = false;
  15441. if (methodInstance->mIsUnspecializedVariation)
  15442. wantsVisitBody = false;
  15443. if (wantsVisitBody)
  15444. {
  15445. BP_ZONE("VisitLambdaBody");
  15446. // For generic methods, we capture for each specialization, so make sure mIsStatic is set to 'true' for
  15447. // this capture stage for each of those times
  15448. SetAndRestoreValue<bool> prevWasStatis(methodDef->mIsStatic, true);
  15449. /*
  15450. // Only generate errors once. Also there are some errors that will occur during this scanning phase
  15451. // that will not occur during the actual lambda method generation, for example: returning a value
  15452. // when our current method is a 'void' method. This shouldn't affect capture scanning since all
  15453. // our AST nodes will still be visited
  15454. SetAndRestoreValue<bool> ignoreError(mIgnoreErrors, true);
  15455. */
  15456. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, methodInstance);
  15457. //SetAndRestoreValue<bool> wantsIgnoreWrites(mWantsISIgnoreWrites, true);
  15458. mBfIRBuilder->SaveDebugLocation();
  15459. closureState.mCaptureVisitingBody = true;
  15460. BF_ASSERT(methodInstance->mMethodInfoEx != NULL);
  15461. methodState.mGenericTypeBindings = &methodInstance->mMethodInfoEx->mGenericTypeBindings;
  15462. NewScopeState();
  15463. ProcessMethod_SetupParams(methodInstance, NULL, false, NULL);
  15464. if (methodInstance->mMethodDef->mMethodType == BfMethodType_Mixin)
  15465. {
  15466. // Allow assigning to arguments when we're capturing - which may or may not be legal at the injection site (we throw error there)
  15467. for (auto localDef : methodState.mLocals)
  15468. {
  15469. if (localDef->mResolvedType->IsVar())
  15470. continue;
  15471. localDef->mAddr = CreateAlloca(localDef->mResolvedType);
  15472. }
  15473. }
  15474. _VisitLambdaBody();
  15475. RestoreScopeState();
  15476. //ProcessMethod(methodInstance);
  15477. closureState.mCaptureVisitingBody = false;
  15478. mBfIRBuilder->RestoreDebugLocation();
  15479. }
  15480. // If we ended up being called by a method with a lower captureStartAccessId, propagate that to whoever is calling us, too...
  15481. if ((methodState.mPrevMethodState->mClosureState != NULL) && (methodState.mPrevMethodState->mClosureState->mCapturing))
  15482. {
  15483. auto prevClosureState = methodState.mPrevMethodState->mClosureState;
  15484. if (closureState.mCaptureStartAccessId < prevClosureState->mCaptureStartAccessId)
  15485. prevClosureState->mCaptureStartAccessId = closureState.mCaptureStartAccessId;
  15486. }
  15487. //RestoreScopeState();
  15488. // Actually get the referenced local methods. It's important we wait until after visiting the body, because then our own capture information
  15489. // can be used by these methods (which will be necessary if any of these methods call us directly or indirectly)
  15490. closureState.mClosureMethodDef = NULL;
  15491. for (auto methodInstance : closureState.mLocalMethodRefs)
  15492. {
  15493. GetLocalMethodInstance(methodInstance->mMethodInfoEx->mClosureInstanceInfo->mLocalMethod, BfTypeVector(), methodInstance);
  15494. }
  15495. methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureClosureState = NULL;
  15496. prevIgnoreWrites.Restore();
  15497. std::multiset<BfClosureCapturedEntry> capturedEntries;
  15498. //
  15499. {
  15500. auto varMethodState = declMethodState;
  15501. while (varMethodState != NULL)
  15502. {
  15503. if ((varMethodState->mMixinState != NULL) && (varMethodState->mMixinState->mLastTargetAccessId >= closureState.mCaptureStartAccessId))
  15504. {
  15505. BF_ASSERT(methodInstance->GetOwner() == varMethodState->mMixinState->mTarget.mType);
  15506. methodDef->mIsStatic = false;
  15507. if (rootMethodState->mMethodInstance->mMethodDef->mIsMutating)
  15508. methodDef->mIsMutating = true;
  15509. }
  15510. bool copyOuterCaptures = false;
  15511. for (int localIdx = 0; localIdx < varMethodState->mLocals.size(); localIdx++)
  15512. {
  15513. auto localVar = varMethodState->mLocals[localIdx];
  15514. if ((localVar->mReadFromId >= closureState.mCaptureStartAccessId) || (localVar->mWrittenToId >= closureState.mCaptureStartAccessId))
  15515. {
  15516. if (localVar->mIsThis)
  15517. {
  15518. // We can only set mutating if our owning type is mutating
  15519. if (localVar->mWrittenToId >= closureState.mCaptureStartAccessId)
  15520. {
  15521. if (mCurTypeInstance->IsValueType())
  15522. {
  15523. if (rootMethodState->mMethodInstance->mMethodDef->mIsMutating)
  15524. methodDef->mIsMutating = true;
  15525. }
  15526. }
  15527. methodDef->mIsStatic = false;
  15528. continue;
  15529. }
  15530. if ((localVar->mIsThis) && (outerClosure != NULL))
  15531. {
  15532. continue;
  15533. }
  15534. if ((localVar->mConstValue) || (localVar->mResolvedType->IsValuelessType()))
  15535. {
  15536. closureState.mConstLocals.push_back(*localVar);
  15537. continue;
  15538. }
  15539. BfClosureCapturedEntry capturedEntry;
  15540. auto capturedType = localVar->mResolvedType;
  15541. bool captureByRef = false;
  15542. if (!capturedType->IsRef())
  15543. {
  15544. if (localVar->mIsThis)
  15545. {
  15546. if ((localVar->mResolvedType->IsValueType()) && (mCurMethodInstance->mMethodDef->HasNoThisSplat()))
  15547. captureByRef = true;
  15548. }
  15549. else if ((!localVar->mIsReadOnly) && (localVar->mWrittenToId >= closureState.mCaptureStartAccessId))
  15550. captureByRef = true;
  15551. }
  15552. else
  15553. {
  15554. if (localVar->mWrittenToId < closureState.mCaptureStartAccessId)
  15555. {
  15556. capturedType = ((BfRefType*)capturedType)->mElementType;
  15557. }
  15558. }
  15559. if (captureByRef)
  15560. {
  15561. //capturedEntry.mIsByReference = true;
  15562. capturedType = CreateRefType(capturedType);
  15563. }
  15564. else
  15565. {
  15566. //capturedEntry.mIsByReference = false;
  15567. }
  15568. capturedEntry.mNameNode = localVar->mNameNode;
  15569. capturedEntry.mType = capturedType;
  15570. capturedEntry.mName = localVar->mName;
  15571. //capturedEntry.mLocalVarDef = localVar;
  15572. capturedEntries.insert(capturedEntry);
  15573. }
  15574. }
  15575. varMethodState = varMethodState->mPrevMethodState;
  15576. if ((varMethodState == NULL) ||
  15577. (varMethodState->mMixinState != NULL) ||
  15578. ((varMethodState->mClosureState != NULL) && (!varMethodState->mClosureState->mCapturing)))
  15579. break;
  15580. }
  15581. }
  15582. for (auto& copyField : closureState.mReferencedOuterClosureMembers)
  15583. {
  15584. auto fieldDef = copyField->GetFieldDef();
  15585. BfClosureCapturedEntry capturedEntry;
  15586. capturedEntry.mName = copyField->GetFieldDef()->mName;
  15587. capturedEntry.mType = copyField->mResolvedType;
  15588. if (capturedEntry.mType->IsRef())
  15589. {
  15590. // Keep by ref
  15591. }
  15592. else if (!fieldDef->mIsReadOnly)
  15593. {
  15594. capturedEntry.mType = CreateRefType(capturedEntry.mType);
  15595. }
  15596. capturedEntries.insert(capturedEntry);
  15597. }
  15598. int captureIdx = 0;
  15599. for (auto& capturedEntry : capturedEntries)
  15600. {
  15601. methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureEntries.Add(capturedEntry);
  15602. }
  15603. /*if (isDefaultPass)
  15604. {
  15605. // Insert captured members a params at the start. If we added at the end then it would screw up varargs methods
  15606. int captureIdx = 0;
  15607. for (auto& capturedEntry : capturedEntries)
  15608. {
  15609. methodInstance->mClosureInstanceInfo->mCaptureNodes.Add(BfNodeDynCast<BfIdentifierNode>(capturedEntry.mNameNode));
  15610. BfParameterDef* paramDef = new BfParameterDef();
  15611. paramDef->mName = capturedEntry.mName;
  15612. BfDirectTypeReference* directTypeRef = new BfDirectTypeReference();
  15613. directTypeRef->mType = capturedEntry.mType;
  15614. typeInst->mTypeDef->mDirectAllocNodes.push_back(directTypeRef);
  15615. paramDef->mTypeRef = directTypeRef;
  15616. paramDef->mParamKind = BfParamKind_ImplicitCapture;
  15617. methodDef->mParams.Insert(captureIdx, paramDef);
  15618. captureIdx++;
  15619. }
  15620. }
  15621. else
  15622. {
  15623. auto defaultMethodInstance = methodInstGroup->mDefault;
  15624. methodInstance->mClosureInstanceInfo->mCaptureNodes = defaultMethodInstance->mClosureInstanceInfo->mCaptureNodes;
  15625. }*/
  15626. methodState.Reset();
  15627. closureState.mCapturing = false;
  15628. //////////////////////////////////////////////////////////////////////////
  15629. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, false);
  15630. if (methodInstance->mReturnType != NULL)
  15631. {
  15632. BF_ASSERT(methodInstance->mDisallowCalling);
  15633. // We did a premature declaration (without captures)
  15634. methodInstance->UndoDeclaration();
  15635. methodInstance->mDisallowCalling = false;
  15636. BfLogSysM("LocalMethod %p UndoingDeclaration %p\n", localMethod, methodInstance);
  15637. }
  15638. auto declareModule = this;
  15639. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(declareModule->mCurMethodInstance, methodInstance);
  15640. SetAndRestoreValue<BfFilePosition> prevFilePos(declareModule->mCurFilePosition);
  15641. BF_ASSERT(declareModule != NULL);
  15642. methodInstance->mDeclModule = declareModule;
  15643. _SetupMethodInstance();
  15644. BfLogSysM("LocalMethod %p DoMethodDeclaration %p\n", localMethod, methodInstance);
  15645. declareModule->DoMethodDeclaration(localMethod->mMethodDef->GetMethodDeclaration(), false, false);
  15646. closureState.mReturnType = methodInstance->mReturnType;
  15647. mCompiler->mStats.mMethodsQueued++;
  15648. mCompiler->UpdateCompletion();
  15649. declareModule->mIncompleteMethodCount++;
  15650. mCompiler->mStats.mMethodsProcessed++;
  15651. if (!methodInstance->mIsReified)
  15652. mCompiler->mStats.mUnreifiedMethodsProcessed++;
  15653. auto deferMethodState = rootMethodState;
  15654. // 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)
  15655. if ((!localMethod->mDeclOnly) && (!methodInstance->mIsUnspecializedVariation) &&
  15656. (!mWantsIRIgnoreWrites) && (methodDef->mMethodType != BfMethodType_Mixin))
  15657. {
  15658. BP_ZONE("BfDeferredLocalMethod:create");
  15659. BfDeferredLocalMethod* deferredLocalMethod = new BfDeferredLocalMethod();
  15660. deferredLocalMethod->mLocalMethod = localMethod;
  15661. deferredLocalMethod->mConstLocals = closureState.mConstLocals;
  15662. deferredLocalMethod->mMethodInstance = methodInstance;
  15663. auto checkMethodState = declMethodState;
  15664. while (checkMethodState != NULL)
  15665. {
  15666. if ((checkMethodState->mClosureState != NULL) && (checkMethodState->mClosureState->mActiveDeferredLocalMethod != NULL))
  15667. {
  15668. for (auto& mixinRecord : checkMethodState->mClosureState->mActiveDeferredLocalMethod->mMixinStateRecords)
  15669. deferredLocalMethod->mMixinStateRecords.Add(mixinRecord);
  15670. }
  15671. if (checkMethodState->mMixinState != NULL)
  15672. {
  15673. BfMixinRecord mixinRecord;
  15674. mixinRecord.mSource = checkMethodState->mMixinState->mSource;
  15675. deferredLocalMethod->mMixinStateRecords.Add(mixinRecord);
  15676. }
  15677. checkMethodState = checkMethodState->mPrevMethodState;
  15678. }
  15679. rootMethodState->mDeferredLocalMethods.Add(deferredLocalMethod);
  15680. }
  15681. mBfIRBuilder->SetActiveFunction(prevActiveFunction);
  15682. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  15683. mBfIRBuilder->RestoreDebugLocation();
  15684. if (methodInstance == localMethod->mMethodInstanceGroup->mDefault)
  15685. {
  15686. auto checkMethodState = mCurMethodState;
  15687. while (checkMethodState != NULL)
  15688. {
  15689. BfLocalMethod* nextLocalMethod = NULL;
  15690. if (checkMethodState->mLocalMethodMap.TryGetValue(localMethod->mMethodName, &nextLocalMethod))
  15691. {
  15692. while (nextLocalMethod != NULL)
  15693. {
  15694. auto checkLocalMethod = nextLocalMethod;
  15695. nextLocalMethod = nextLocalMethod->mNextWithSameName;
  15696. if (checkLocalMethod == localMethod)
  15697. continue;
  15698. if (checkLocalMethod->mMethodInstanceGroup == NULL)
  15699. continue;
  15700. auto checkMethodInstance = checkLocalMethod->mMethodInstanceGroup->mDefault;
  15701. if (checkMethodInstance == NULL)
  15702. continue; // Not generated yet
  15703. if (CompareMethodSignatures(localMethod->mMethodInstanceGroup->mDefault, checkMethodInstance))
  15704. {
  15705. auto bfError = Fail("Method already declared with the same parameter types", methodInstance->mMethodDef->GetRefNode(), true);
  15706. if (bfError != NULL)
  15707. mCompiler->mPassInstance->MoreInfo("First declaration", checkMethodInstance->mMethodDef->GetRefNode());
  15708. }
  15709. }
  15710. }
  15711. checkMethodState = checkMethodState->mPrevMethodState;
  15712. }
  15713. }
  15714. return BfModuleMethodInstance(methodInstance);
  15715. }
  15716. int BfModule::GetLocalInferrableGenericArgCount(BfMethodDef* methodDef)
  15717. {
  15718. if ((!methodDef->mIsLocalMethod) || (methodDef->mGenericParams.size() == 0))
  15719. return 0;
  15720. auto rootMethodState = mCurMethodState->GetRootMethodState();
  15721. int rootMethodGenericParamCount = 0;
  15722. if (rootMethodState->mMethodInstance->mMethodInfoEx != NULL)
  15723. rootMethodGenericParamCount = (int)rootMethodState->mMethodInstance->mMethodInfoEx->mGenericParams.size();
  15724. if (mCurMethodInstance == NULL)
  15725. return rootMethodGenericParamCount;
  15726. if ((mCurMethodInstance->mMethodInfoEx == NULL) || (mCurMethodInstance->mMethodInfoEx->mClosureInstanceInfo == NULL))
  15727. return rootMethodGenericParamCount;
  15728. BfLocalMethod* callerLocalMethod = mCurMethodInstance->mMethodInfoEx->mClosureInstanceInfo->mLocalMethod;
  15729. if (callerLocalMethod == NULL)
  15730. return rootMethodGenericParamCount;
  15731. BfLocalMethod* calledLocalMethod = NULL;
  15732. rootMethodState->mLocalMethodCache.TryGetValue(methodDef->mName, &calledLocalMethod);
  15733. while ((calledLocalMethod != NULL) && (callerLocalMethod != NULL))
  15734. {
  15735. if (calledLocalMethod->mOuterLocalMethod == callerLocalMethod)
  15736. return (int)callerLocalMethod->mMethodDef->mGenericParams.size();
  15737. callerLocalMethod = calledLocalMethod->mOuterLocalMethod;
  15738. }
  15739. return rootMethodGenericParamCount;
  15740. }
  15741. void BfModule::GetMethodCustomAttributes(BfMethodInstance* methodInstance)
  15742. {
  15743. auto methodDef = methodInstance->mMethodDef;
  15744. if (methodInstance->GetCustomAttributes() != NULL)
  15745. return;
  15746. auto methodDeclaration = methodDef->GetMethodDeclaration();
  15747. auto propertyMethodDeclaration = methodDef->GetPropertyMethodDeclaration();
  15748. auto typeInstance = methodInstance->GetOwner();
  15749. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  15750. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, methodInstance);
  15751. if ((methodDeclaration != NULL) && (methodDeclaration->mAttributes != NULL))
  15752. {
  15753. if (methodInstance->GetMethodInfoEx()->mMethodCustomAttributes == NULL)
  15754. methodInstance->mMethodInfoEx->mMethodCustomAttributes = new BfMethodCustomAttributes();
  15755. methodInstance->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes = GetCustomAttributes(methodDeclaration->mAttributes,
  15756. ((methodDef->mMethodType == BfMethodType_Ctor) || (methodDef->mMethodType == BfMethodType_CtorCalcAppend)) ? BfAttributeTargets_Constructor : BfAttributeTargets_Method);
  15757. }
  15758. else if ((propertyMethodDeclaration != NULL) && (propertyMethodDeclaration->mAttributes != NULL))
  15759. {
  15760. if (methodInstance->GetMethodInfoEx()->mMethodCustomAttributes == NULL)
  15761. methodInstance->mMethodInfoEx->mMethodCustomAttributes = new BfMethodCustomAttributes();
  15762. methodInstance->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes = GetCustomAttributes(propertyMethodDeclaration->mAttributes, BfAttributeTargets_Method);
  15763. }
  15764. }
  15765. void BfModule::SetupIRFunction(BfMethodInstance* methodInstance, StringImpl& mangledName, bool isTemporaryFunc, bool* outIsIntrinsic)
  15766. {
  15767. if (methodInstance->GetImportCallKind() == BfImportCallKind_GlobalVar)
  15768. {
  15769. // Don't create a func
  15770. return;
  15771. }
  15772. auto typeInstance = methodInstance->GetOwner();
  15773. auto methodDef = methodInstance->mMethodDef;
  15774. BfIRFunctionType funcType = mBfIRBuilder->MapMethod(methodInstance);
  15775. // Don't set these pointers during resolve pass because they may become invalid if it's just a temporary autocomplete method
  15776. if (mCompiler->mResolvePassData == NULL)
  15777. {
  15778. if ((methodDef->mMethodType == BfMethodType_Ctor) && (methodDef->mIsStatic))
  15779. {
  15780. typeInstance->mHasStaticInitMethod = true;
  15781. }
  15782. if ((methodDef->mMethodType == BfMethodType_Dtor) && (methodDef->mIsStatic))
  15783. {
  15784. typeInstance->mHasStaticDtorMethod = true;
  15785. }
  15786. if ((methodDef->mMethodType == BfMethodType_Normal) && (methodDef->mIsStatic) && (methodDef->mName == BF_METHODNAME_MARKMEMBERS_STATIC))
  15787. {
  15788. typeInstance->mHasStaticMarkMethod = true;
  15789. }
  15790. if ((methodDef->mMethodType == BfMethodType_Normal) && (methodDef->mIsStatic) && (methodDef->mName == BF_METHODNAME_FIND_TLS_MEMBERS))
  15791. {
  15792. typeInstance->mHasTLSFindMethod = true;
  15793. }
  15794. }
  15795. if (isTemporaryFunc)
  15796. {
  15797. BF_ASSERT((mCompiler->mIsResolveOnly) && (mCompiler->mResolvePassData->mAutoComplete != NULL));
  15798. mangledName = "autocomplete_tmp";
  15799. }
  15800. if (!mBfIRBuilder->mIgnoreWrites)
  15801. {
  15802. BfIRFunction prevFunc;
  15803. // Remove old version (if we have one)
  15804. prevFunc = mBfIRBuilder->GetFunction(mangledName);
  15805. if (prevFunc)
  15806. {
  15807. if (methodDef->mIsExtern)
  15808. {
  15809. // Allow this
  15810. BfLogSysM("Function collision allowed multiple extern functions for %p: %d\n", methodInstance, prevFunc.mId);
  15811. }
  15812. else if (typeInstance->IsIRFuncUsed(prevFunc))
  15813. {
  15814. // We can have a collision of names when we have generic methods that differ only in
  15815. // their constraints, but they should only collide in their unspecialized form
  15816. // since only one will be chosen for a given concrete type
  15817. mCurMethodInstance->mMangleWithIdx = true;
  15818. mangledName.Clear();
  15819. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), mCurMethodInstance);
  15820. prevFunc = mBfIRBuilder->GetFunction(mangledName);
  15821. BfLogSysM("Function collision forced mangleWithIdx for %p: %d\n", methodInstance, prevFunc.mId);
  15822. }
  15823. else
  15824. {
  15825. BfLogSysM("Function collision erased prevFunc %p: %d\n", methodInstance, prevFunc.mId);
  15826. mBfIRBuilder->Func_EraseFromParent(prevFunc);
  15827. }
  15828. }
  15829. }
  15830. if (typeInstance != mContext->mBfObjectType)
  15831. {
  15832. // Only allow attributes on System.Object methods that can be handled inside the DefBuilder
  15833. GetMethodCustomAttributes(methodInstance);
  15834. }
  15835. // if (prevFunc)
  15836. // {
  15837. // if (methodDef->mIsExtern)
  15838. // {
  15839. // BfLogSysM("Reusing function for %p: %d\n", methodInstance, prevFunc.mId);
  15840. // methodInstance->mIRFunction = prevFunc;
  15841. // }
  15842. // else
  15843. // {
  15844. // if ((methodInstance->IsSpecializedByAutoCompleteMethod()) ||
  15845. // ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mResolveType >= BfResolveType_GoToDefinition)))
  15846. // {
  15847. // // If we're doing re-pass over the methods for something like BfResolveType_ShowFileSymbolReferences, then allow this collision
  15848. // BfLogSysM("Ignoring function name collision\n");
  15849. // }
  15850. // else
  15851. // {
  15852. // if (methodDef->mMethodDeclaration == NULL)
  15853. // {
  15854. // AssertErrorState();
  15855. // }
  15856. // else
  15857. // {
  15858. // BF_ASSERT(mIsSpecialModule);
  15859. // if ((mCompiler->mRevision == 1) && (HasCompiledOutput()))
  15860. // {
  15861. // // We shouldn't have name collisions on the first run!
  15862. // AssertErrorState();
  15863. // }
  15864. // }
  15865. // }
  15866. // BfLogSysM("Before erase\n");
  15867. // mBfIRBuilder->Func_EraseFromParent(prevFunc);
  15868. // }
  15869. // }
  15870. bool isIntrinsic = false;
  15871. if (!methodInstance->mIRFunction)
  15872. {
  15873. BfIRFunction func;
  15874. bool wantsLLVMFunc = ((!typeInstance->IsUnspecializedType()) && (!methodDef->IsEmptyPartial())) && (funcType);
  15875. /*if (mCurTypeInstance->mTypeDef->mName->ToString() == "ClassA")
  15876. {
  15877. if (!mIsReified)
  15878. wantsLLVMFunc = false;
  15879. }*/
  15880. if (wantsLLVMFunc)
  15881. {
  15882. func = GetIntrinsic(methodInstance, true);
  15883. if (func)
  15884. {
  15885. isIntrinsic = true;
  15886. }
  15887. else
  15888. {
  15889. func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, mangledName);
  15890. BfLogSysM("Creating FuncId:%d %s in module %p\n", func.mId, mangledName.c_str(), this);
  15891. if (methodInstance->mAlwaysInline)
  15892. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_AlwaysInline);
  15893. // if (prevFunc)
  15894. // BfLogSysM("Removing Func %d, replacing with %d\n", prevFunc.mId, func.mId);
  15895. }
  15896. methodInstance->mIRFunction = func;
  15897. //if (!ignoreWrites)
  15898. //BF_ASSERT(!func.IsFake());
  15899. }
  15900. }
  15901. if (outIsIntrinsic != NULL)
  15902. *outIsIntrinsic = isIntrinsic;
  15903. if (!isIntrinsic)
  15904. SetupIRMethod(methodInstance, methodInstance->mIRFunction, methodInstance->mAlwaysInline);
  15905. }
  15906. void BfModule::CheckHotMethod(BfMethodInstance* methodInstance, const StringImpl& inMangledName)
  15907. {
  15908. if (methodInstance->mHotMethod != NULL)
  15909. return;
  15910. if ((mCompiler->mOptions.mAllowHotSwapping) && (!methodInstance->mIsUnspecialized))
  15911. {
  15912. auto srcTypeInst = methodInstance->GetOwner();
  15913. StringT<128> mangledName = inMangledName;
  15914. if (mangledName.IsEmpty())
  15915. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), methodInstance);
  15916. // We always keep the current primary method at the same address
  15917. BfHotMethod* hotMethod;
  15918. BfHotMethod** hotMethodPtr;
  15919. if (mCompiler->mHotData->mMethodMap.TryAdd(mangledName, NULL, &hotMethodPtr))
  15920. {
  15921. hotMethod = new BfHotMethod();
  15922. *hotMethodPtr = hotMethod;
  15923. hotMethod->mRefCount = 1;
  15924. hotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_IsBound);
  15925. #ifdef BF_DBG_HOTMETHOD_IDX
  15926. static int sMethodIdx = 0;
  15927. hotMethod->mMethodIdx = sMethodIdx++;
  15928. #endif
  15929. BfLogSysM("HotMethodData %p created for method %p %s - %s\n", hotMethod, methodInstance, MethodToString(methodInstance).c_str(), mangledName.c_str());
  15930. }
  15931. else
  15932. {
  15933. hotMethod = *hotMethodPtr;
  15934. if ((hotMethod->mFlags & BfHotDepDataFlag_IsBound) != 0)
  15935. {
  15936. // This is a duplicate mangled name - we link to this new entry via a 'BfHotDupMethod'
  15937. auto prevHotMethod = *hotMethodPtr;
  15938. hotMethod = new BfHotMethod();
  15939. hotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_IsBound);
  15940. BfHotDupMethod* hotDupMethod = new BfHotDupMethod(hotMethod);
  15941. hotDupMethod->mRefCount++;
  15942. prevHotMethod->mReferences.Add(hotDupMethod);
  15943. prevHotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_HasDup);
  15944. BfLogSysM("HotMethodData %p (duplicate of %p) created for method %p %s - %s\n", hotMethod, prevHotMethod, methodInstance, MethodToString(methodInstance).c_str(), mangledName.c_str());
  15945. }
  15946. else if (mCompiler->IsHotCompile())
  15947. {
  15948. // Link the previous version into the mPrevVersion
  15949. BfHotMethod* prevMethod = new BfHotMethod();
  15950. prevMethod->mRefCount = 1;
  15951. prevMethod->mPrevVersion = hotMethod->mPrevVersion;
  15952. hotMethod->mPrevVersion = prevMethod;
  15953. prevMethod->mSrcTypeVersion = hotMethod->mSrcTypeVersion;
  15954. hotMethod->mSrcTypeVersion = NULL;
  15955. prevMethod->mFlags = hotMethod->mFlags;
  15956. hotMethod->mFlags = BfHotDepDataFlag_IsBound;
  15957. hotMethod->mReferences.MoveTo(prevMethod->mReferences);
  15958. #ifdef BF_DBG_HOTMETHOD_NAME
  15959. prevMethod->mMangledName = hotMethod->mMangledName;
  15960. #endif
  15961. BfLogSysM("HotMethodData %p created for prevmethod of %p for method %p %s\n", prevMethod, hotMethod, methodInstance, MethodToString(methodInstance).c_str());
  15962. }
  15963. else
  15964. {
  15965. BfLogSysM("HotMethodData %p used for method %p %s - %s\n", hotMethod, methodInstance, MethodToString(methodInstance).c_str(), mangledName.c_str());
  15966. hotMethod->Clear(true);
  15967. hotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_IsBound);
  15968. }
  15969. }
  15970. if (methodInstance->mIsClosure)
  15971. {
  15972. hotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_RetainMethodWithoutBinding);
  15973. }
  15974. hotMethod->mSrcTypeVersion = srcTypeInst->mHotTypeData->GetLatestVersion();
  15975. hotMethod->mSrcTypeVersion->mRefCount++;
  15976. hotMethod->mRefCount++;
  15977. #ifdef BF_DBG_HOTMETHOD_NAME
  15978. hotMethod->mMangledName = mangledName;
  15979. #endif
  15980. methodInstance->mHotMethod = hotMethod;
  15981. }
  15982. }
  15983. // methodDeclaration is NULL for default constructors
  15984. void BfModule::DoMethodDeclaration(BfMethodDeclaration* methodDeclaration, bool isTemporaryFunc, bool addToWorkList)
  15985. {
  15986. BP_ZONE("BfModule::BfMethodDeclaration");
  15987. // We could trigger a DoMethodDeclaration from a const resolver or other location, so we reset it here
  15988. // to effectively make mIgnoreWrites method-scoped
  15989. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, mWantsIRIgnoreWrites || mCurMethodInstance->mIsUnspecialized);
  15990. SetAndRestoreValue<bool> prevIsCapturingMethodMatchInfo;
  15991. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, NULL);
  15992. if (mCompiler->IsAutocomplete())
  15993. prevIsCapturingMethodMatchInfo.Init(mCompiler->mResolvePassData->mAutoComplete->mIsCapturingMethodMatchInfo, false);
  15994. if (mCurMethodInstance->mMethodInstanceGroup->mOnDemandKind == BfMethodOnDemandKind_NoDecl_AwaitingReference)
  15995. mCurMethodInstance->mMethodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_Decl_AwaitingReference;
  15996. bool ignoreWrites = mBfIRBuilder->mIgnoreWrites;
  15997. if (mAwaitingInitFinish)
  15998. FinishInit();
  15999. auto typeInstance = mCurTypeInstance;
  16000. auto typeDef = typeInstance->mTypeDef;
  16001. auto methodDef = mCurMethodInstance->mMethodDef;
  16002. BF_ASSERT(methodDef->mName != "__ASSERTNAME");
  16003. if (typeInstance->IsClosure())
  16004. {
  16005. if (methodDef->mName == "Invoke")
  16006. return;
  16007. }
  16008. auto methodInstance = mCurMethodInstance;
  16009. if ((methodInstance->IsSpecializedByAutoCompleteMethod()) || (mCurTypeInstance->IsFunction()))
  16010. addToWorkList = false;
  16011. bool hasNonGenericParams = false;
  16012. bool hasGenericParams = false;
  16013. int dependentGenericStartIdx = 0;
  16014. if (methodDef->mIsLocalMethod)
  16015. {
  16016. // If we're a local generic method inside an outer generic method, we can still be considered unspecialized
  16017. // if our outer method's generic args are specialized but ours are unspecialized. This is because locals get
  16018. // instantiated uniquely for each specialized or unspecialized pass through the outer method, but the local
  16019. // method still 'inherits' the outer's generic arguments -- but we still need to make an unspecialized pass
  16020. // over the local method each time
  16021. auto rootMethodInstance = prevMethodState.mPrevVal->GetRootMethodState()->mMethodInstance;
  16022. dependentGenericStartIdx = 0;
  16023. if (rootMethodInstance->mMethodInfoEx != NULL)
  16024. dependentGenericStartIdx = (int)rootMethodInstance->mMethodInfoEx->mMethodGenericArguments.size();
  16025. methodInstance->mIsUnspecialized = rootMethodInstance->mIsUnspecialized;
  16026. methodInstance->mIsUnspecializedVariation = rootMethodInstance->mIsUnspecializedVariation;
  16027. }
  16028. for (int genericArgIdx = dependentGenericStartIdx; genericArgIdx < (int) methodInstance->GetNumGenericArguments(); genericArgIdx++)
  16029. {
  16030. auto genericArgType = methodInstance->mMethodInfoEx->mMethodGenericArguments[genericArgIdx];
  16031. if (genericArgType->IsGenericParam())
  16032. {
  16033. hasGenericParams = true;
  16034. auto genericParam = (BfGenericParamType*)genericArgType;
  16035. methodInstance->mIsUnspecialized = true;
  16036. if ((genericParam->mGenericParamKind != BfGenericParamKind_Method) || (genericParam->mGenericParamIdx != genericArgIdx))
  16037. methodInstance->mIsUnspecializedVariation = true;
  16038. }
  16039. else
  16040. {
  16041. hasNonGenericParams = true;
  16042. if (genericArgType->IsUnspecializedType())
  16043. {
  16044. methodInstance->mIsUnspecialized = true;
  16045. methodInstance->mIsUnspecializedVariation = true;
  16046. }
  16047. }
  16048. }
  16049. if ((hasGenericParams) && (hasNonGenericParams))
  16050. {
  16051. methodInstance->mIsUnspecializedVariation = true;
  16052. }
  16053. if (typeInstance->IsUnspecializedType())
  16054. {
  16055. // A specialized method within an unspecialized type is considered an unspecialized variation -- in the sense that we don't
  16056. // actually want to do method processing on it
  16057. if ((!methodInstance->mIsUnspecialized) && (methodInstance->GetNumGenericArguments() != 0))
  16058. methodInstance->mIsUnspecializedVariation = true;
  16059. methodInstance->mIsUnspecialized = true;
  16060. }
  16061. methodInstance->mIsUnspecializedVariation |= typeInstance->IsUnspecializedTypeVariation();
  16062. for (auto genericParamDef : methodDef->mGenericParams)
  16063. {
  16064. if (mCompiler->IsAutocomplete())
  16065. {
  16066. auto autoComplete = mCompiler->mResolvePassData->mAutoComplete;
  16067. //autoComplete->CheckTypeRef()
  16068. }
  16069. }
  16070. if (methodInstance->mIsUnspecializedVariation)
  16071. {
  16072. }
  16073. if (methodInstance->mIsUnspecializedVariation)
  16074. BF_ASSERT(methodInstance->mIsUnspecialized);
  16075. if (methodDef->mMethodType == BfMethodType_Mixin)
  16076. methodInstance->mIsUnspecialized = true;
  16077. BfAutoComplete* bfAutocomplete = NULL;
  16078. if (mCompiler->mResolvePassData != NULL)
  16079. bfAutocomplete = mCompiler->mResolvePassData->mAutoComplete;
  16080. for (int genericParamIdx = 0; genericParamIdx < (int)methodInstance->GetNumGenericArguments(); genericParamIdx++)
  16081. {
  16082. auto genericParamDef = methodDef->mGenericParams[genericParamIdx];
  16083. ResolveGenericParamConstraints(methodInstance->mMethodInfoEx->mGenericParams[genericParamIdx], methodDef->mGenericParams, genericParamIdx);
  16084. if (bfAutocomplete != NULL)
  16085. {
  16086. for (auto nameNode : genericParamDef->mNameNodes)
  16087. {
  16088. HandleMethodGenericParamRef(nameNode, typeDef, methodDef, genericParamIdx);
  16089. }
  16090. }
  16091. }
  16092. if (methodInstance->mMethodInfoEx != NULL)
  16093. {
  16094. for (auto genericParam : methodInstance->mMethodInfoEx->mGenericParams)
  16095. {
  16096. for (auto constraintTypeInst : genericParam->mInterfaceConstraints)
  16097. AddDependency(constraintTypeInst, mCurTypeInstance, BfDependencyMap::DependencyFlag_Constraint);
  16098. if (genericParam->mTypeConstraint != NULL)
  16099. AddDependency(genericParam->mTypeConstraint, mCurTypeInstance, BfDependencyMap::DependencyFlag_Constraint);
  16100. }
  16101. }
  16102. if ((methodInstance->mIsAutocompleteMethod) && (methodDeclaration != NULL) && (!methodInstance->IsSpecializedGenericMethod()) && (methodDef->mIdx >= 0))
  16103. {
  16104. auto autoComplete = mCompiler->mResolvePassData->mAutoComplete;
  16105. BfAstNode* nameNode = methodDeclaration->mNameNode;
  16106. if (nameNode == NULL)
  16107. {
  16108. if (auto ctorDeclaration = BfNodeDynCast<BfConstructorDeclaration>(methodDeclaration))
  16109. nameNode = ctorDeclaration->mThisToken;
  16110. }
  16111. if (autoComplete->IsAutocompleteNode(nameNode))
  16112. {
  16113. autoComplete->mInsertStartIdx = nameNode->GetSrcStart();
  16114. autoComplete->mInsertEndIdx = nameNode->GetSrcEnd();
  16115. autoComplete->mDefType = typeDef;
  16116. autoComplete->mDefMethod = methodDef;
  16117. autoComplete->SetDefinitionLocation(nameNode);
  16118. if (methodDef->mIsOverride)
  16119. {
  16120. for (int virtIdx = 0; virtIdx < (int)typeInstance->mVirtualMethodTable.size(); virtIdx++)
  16121. {
  16122. auto& ventry = typeInstance->mVirtualMethodTable[virtIdx];
  16123. if (ventry.mDeclaringMethod.mMethodNum == -1)
  16124. continue;
  16125. BfMethodInstance* virtMethod = ventry.mImplementingMethod;
  16126. if (virtMethod != NULL)
  16127. {
  16128. auto virtMethodDeclaration = virtMethod->mMethodDef->GetMethodDeclaration();
  16129. if ((virtMethod->GetOwner() == typeInstance) && (virtMethodDeclaration != NULL) &&
  16130. (virtMethodDeclaration->GetSrcStart() == methodDeclaration->GetSrcStart()))
  16131. {
  16132. // Is matching method
  16133. if (virtIdx < (int)typeInstance->mBaseType->mVirtualMethodTable.size())
  16134. {
  16135. auto baseType = typeInstance->mBaseType;
  16136. if (baseType != NULL)
  16137. {
  16138. while ((baseType->mBaseType != NULL) && (virtIdx < baseType->mBaseType->mVirtualMethodTableSize))
  16139. baseType = baseType->mBaseType;
  16140. BfMethodInstance* baseVirtMethod = baseType->mVirtualMethodTable[virtIdx].mImplementingMethod;
  16141. autoComplete->SetDefinitionLocation(baseVirtMethod->mMethodDef->GetRefNode(), true);
  16142. autoComplete->mDefType = baseType->mTypeDef;
  16143. autoComplete->mDefMethod = baseVirtMethod->mMethodDef;
  16144. }
  16145. }
  16146. break;
  16147. }
  16148. }
  16149. }
  16150. }
  16151. }
  16152. }
  16153. bool reportErrors = true;
  16154. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL))
  16155. reportErrors = true;
  16156. // Only the defining contexts needs to report errors here
  16157. SetAndRestoreValue<bool> prevReporErrors(mReportErrors, reportErrors);
  16158. if (methodDef->mMethodType == BfMethodType_Dtor)
  16159. {
  16160. if (methodDef->mIsStatic)
  16161. {
  16162. }
  16163. else
  16164. {
  16165. if ((typeInstance->IsStruct()) || (typeInstance->IsTypedPrimitive()))
  16166. {
  16167. BfAstNode* refNode = methodDeclaration;
  16168. if (refNode == NULL)
  16169. {
  16170. // Whatever caused this ctor to be generated should have caused another failure
  16171. // But that failure might not be generated until the ctor is generated
  16172. }
  16173. else
  16174. {
  16175. auto dtorDecl = BfNodeDynCast<BfDestructorDeclaration>(methodDeclaration);
  16176. if (dtorDecl != NULL)
  16177. refNode = dtorDecl->mThisToken;
  16178. Fail("Structs cannot have destructors", refNode);
  16179. }
  16180. }
  16181. auto methodDeclaration = methodDef->GetMethodDeclaration();
  16182. if ((methodDeclaration != NULL) && (methodDeclaration->mVirtualSpecifier != NULL) &&
  16183. (mCurTypeInstance != mContext->mBfObjectType))
  16184. {
  16185. Fail("Virtual specifier is not required, all destructors are implicitly virtual.", methodDeclaration->mVirtualSpecifier);
  16186. }
  16187. }
  16188. }
  16189. BfType* resolvedReturnType = NULL;
  16190. if (((methodDef->mMethodType == BfMethodType_Normal) || (methodDef->mMethodType == BfMethodType_CtorCalcAppend) || (methodDef->mMethodType == BfMethodType_PropertyGetter) || (methodDef->mMethodType == BfMethodType_Operator)) &&
  16191. (methodDef->mReturnTypeRef != NULL))
  16192. {
  16193. SetAndRestoreValue<bool> prevIngoreErrors(mIgnoreErrors, mIgnoreErrors || (methodDef->GetPropertyDeclaration() != NULL));
  16194. resolvedReturnType = ResolveTypeRef(methodDef->mReturnTypeRef, BfPopulateType_Declaration,
  16195. (BfResolveTypeRefFlags)(BfResolveTypeRefFlag_NoResolveGenericParam | BfResolveTypeRefFlag_AllowRef | BfResolveTypeRefFlag_AllowRefGeneric));
  16196. if ((resolvedReturnType != NULL) && (resolvedReturnType->IsVar()) && (methodDef->mMethodType != BfMethodType_Mixin))
  16197. {
  16198. Fail("Cannot declare var return types", methodDef->mReturnTypeRef);
  16199. resolvedReturnType = GetPrimitiveType(BfTypeCode_Var);
  16200. }
  16201. if (resolvedReturnType == NULL)
  16202. resolvedReturnType = GetPrimitiveType(BfTypeCode_Var);
  16203. }
  16204. else
  16205. {
  16206. resolvedReturnType = ResolveTypeDef(mSystem->mTypeVoid);
  16207. }
  16208. BF_ASSERT(resolvedReturnType != NULL);
  16209. mCurMethodInstance->mReturnType = resolvedReturnType;
  16210. //TODO: We used to NOT add the return value dependency for specialized methods, but when we have types that are
  16211. // specialized based on the method's generic param then they can get deleted if no one else has referred to them (yet)
  16212. //if (!methodInstance->IsSpecializedGenericMethod())
  16213. AddDependency(resolvedReturnType, typeInstance, BfDependencyMap::DependencyFlag_ParamOrReturnValue);
  16214. if (methodDef->mExplicitInterface != NULL)
  16215. {
  16216. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL))
  16217. mCompiler->mResolvePassData->mAutoComplete->CheckTypeRef(methodDef->mExplicitInterface, false);
  16218. auto explicitInterface = ResolveTypeRef(methodDef->mExplicitInterface, BfPopulateType_Declaration);
  16219. if (explicitInterface != NULL)
  16220. mCurMethodInstance->GetMethodInfoEx()->mExplicitInterface = explicitInterface->ToTypeInstance();
  16221. if ((mCurMethodInstance->mMethodInfoEx != NULL) && (mCurMethodInstance->mMethodInfoEx->mExplicitInterface != NULL))
  16222. {
  16223. bool interfaceFound = false;
  16224. for (auto ifaceInst : typeInstance->mInterfaces)
  16225. interfaceFound |= ifaceInst.mInterfaceType == mCurMethodInstance->mMethodInfoEx->mExplicitInterface;
  16226. if (!interfaceFound)
  16227. {
  16228. if (methodDef->mMethodDeclaration != NULL)
  16229. Fail("Containing class has not declared to implement this interface", methodDef->mMethodDeclaration);
  16230. else
  16231. {
  16232. // For property decls, we should have already given the error during type population
  16233. if (mCompiler->mRevision == 1)
  16234. AssertErrorState();
  16235. }
  16236. }
  16237. }
  16238. }
  16239. bool isThisStruct = mCurTypeInstance->IsStruct();
  16240. BfType* thisType = NULL;
  16241. if ((!methodDef->mIsStatic) && (!mCurTypeInstance->IsValuelessType()))
  16242. {
  16243. if ((isThisStruct) || (mCurTypeInstance->IsTypedPrimitive()))
  16244. {
  16245. thisType = mCurTypeInstance;
  16246. if (thisType == NULL)
  16247. return;
  16248. if ((thisType->IsSplattable()) && (!methodDef->HasNoThisSplat()))
  16249. {
  16250. BfTypeUtils::SplatIterate([&](BfType* checkType)
  16251. {
  16252. PopulateType(checkType, BfPopulateType_Data);
  16253. }, thisType);
  16254. }
  16255. }
  16256. else
  16257. {
  16258. thisType = mCurTypeInstance;
  16259. PopulateType(thisType, BfPopulateType_Declaration);
  16260. }
  16261. }
  16262. int implicitParamCount = 0;
  16263. if ((mCurMethodInstance->mMethodInfoEx != NULL) && (mCurMethodInstance->mMethodInfoEx->mClosureInstanceInfo != NULL))
  16264. implicitParamCount = (int)methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureEntries.size();
  16265. methodInstance->mMethodDef->mParams.Reserve((int)methodDef->mParams.size());
  16266. bool hadDelegateParams = false;
  16267. bool hadParams = false;
  16268. for (int paramIdx = 0; paramIdx < (int)methodDef->mParams.size() + implicitParamCount; paramIdx++)
  16269. {
  16270. BfClosureCapturedEntry* closureCaptureEntry = NULL;
  16271. BfParameterDef* paramDef = NULL;
  16272. int paramDefIdx = -1;
  16273. if (paramIdx < implicitParamCount)
  16274. closureCaptureEntry = &methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureEntries[paramIdx];
  16275. else
  16276. {
  16277. paramDefIdx = paramIdx - implicitParamCount;
  16278. paramDef = methodDef->mParams[paramDefIdx];
  16279. }
  16280. if (hadParams)
  16281. break;
  16282. if ((paramDef != NULL) && (mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL) &&
  16283. (paramDef->mParamKind != BfParamKind_AppendIdx))
  16284. mCompiler->mResolvePassData->mAutoComplete->CheckTypeRef(paramDef->mTypeRef, false);
  16285. if ((paramDef != NULL) && (paramDef->mParamDeclaration != NULL) && (paramDef->mParamDeclaration->mAttributes != NULL))
  16286. {
  16287. if (methodInstance->GetMethodInfoEx()->mMethodCustomAttributes == NULL)
  16288. methodInstance->mMethodInfoEx->mMethodCustomAttributes = new BfMethodCustomAttributes();
  16289. while ((int)methodInstance->mMethodInfoEx->mMethodCustomAttributes->mParamCustomAttributes.size() < paramIdx)
  16290. methodInstance->mMethodInfoEx->mMethodCustomAttributes->mParamCustomAttributes.push_back(NULL);
  16291. auto customAttributes = GetCustomAttributes(paramDef->mParamDeclaration->mAttributes, BfAttributeTargets_Parameter);
  16292. methodInstance->mMethodInfoEx->mMethodCustomAttributes->mParamCustomAttributes.push_back(customAttributes);
  16293. }
  16294. BfType* resolvedParamType = NULL;
  16295. if (closureCaptureEntry != NULL)
  16296. resolvedParamType = closureCaptureEntry->mType;
  16297. else if (paramDef->mTypeRef->IsA<BfLetTypeReference>())
  16298. {
  16299. Fail("Cannot declare 'let' parameters", paramDef->mTypeRef);
  16300. resolvedParamType = mContext->mBfObjectType;
  16301. }
  16302. else if (paramDef->mTypeRef->IsA<BfVarTypeReference>())
  16303. {
  16304. if (methodDef->mMethodType != BfMethodType_Mixin)
  16305. {
  16306. Fail("Cannot declare var parameters", paramDef->mTypeRef);
  16307. resolvedParamType = mContext->mBfObjectType;
  16308. }
  16309. else
  16310. resolvedParamType = GetPrimitiveType(BfTypeCode_Var);
  16311. }
  16312. BfType* unresolvedParamType = resolvedParamType;
  16313. bool wasGenericParam = false;
  16314. if (resolvedParamType == NULL)
  16315. {
  16316. SetAndRestoreValue<bool> prevIngoreErrors(mIgnoreErrors, mIgnoreErrors || (methodDef->GetPropertyDeclaration() != NULL));
  16317. resolvedParamType = ResolveTypeRef(paramDef->mTypeRef, BfPopulateType_Declaration,
  16318. (BfResolveTypeRefFlags)(BfResolveTypeRefFlag_NoResolveGenericParam | BfResolveTypeRefFlag_AllowRef | BfResolveTypeRefFlag_AllowRefGeneric | BfResolveTypeRefFlag_AllowGenericMethodParamConstValue));
  16319. }
  16320. if (resolvedParamType == NULL)
  16321. {
  16322. resolvedParamType = GetPrimitiveType(BfTypeCode_Var);
  16323. unresolvedParamType = resolvedParamType;
  16324. if (mCurTypeInstance->IsBoxed())
  16325. {
  16326. auto boxedType = (BfBoxedType*)mCurTypeInstance;
  16327. // If we failed a lookup here then we better have also failed it in the original type
  16328. BF_ASSERT(boxedType->mElementType->mModule->mHadBuildError || mContext->mFailTypes.Contains(boxedType->mElementType));
  16329. }
  16330. }
  16331. if (!methodInstance->IsSpecializedGenericMethod())
  16332. AddDependency(resolvedParamType, typeInstance, BfDependencyMap::DependencyFlag_ParamOrReturnValue);
  16333. PopulateType(resolvedParamType, BfPopulateType_Declaration);
  16334. AddDependency(resolvedParamType, mCurTypeInstance, BfDependencyMap::DependencyFlag_LocalUsage);
  16335. if ((paramDef != NULL) && (paramDef->mParamDeclaration != NULL) && (paramDef->mParamDeclaration->mInitializer != NULL) &&
  16336. (!paramDef->mParamDeclaration->mInitializer->IsA<BfBlock>()))
  16337. {
  16338. BfMethodState methodState;
  16339. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  16340. methodState.mTempKind = BfMethodState::TempKind_Static;
  16341. BfTypedValue defaultValue;
  16342. if (resolvedParamType->IsConstExprValue())
  16343. {
  16344. auto constExprType = (BfConstExprValueType*)resolvedParamType;
  16345. BfExprEvaluator exprEvaluator(this);
  16346. exprEvaluator.mExpectingType = constExprType->mType;
  16347. exprEvaluator.GetLiteral(NULL, constExprType->mValue);
  16348. defaultValue = exprEvaluator.GetResult();
  16349. }
  16350. else
  16351. {
  16352. BfConstResolver constResolver(this);
  16353. defaultValue = constResolver.Resolve(paramDef->mParamDeclaration->mInitializer, resolvedParamType, BfConstResolveFlag_NoCast);
  16354. if ((defaultValue) && (defaultValue.mType != resolvedParamType))
  16355. {
  16356. SetAndRestoreValue<bool> prevIgnoreWrite(mBfIRBuilder->mIgnoreWrites, true);
  16357. auto castedDefaultValue = Cast(paramDef->mParamDeclaration->mInitializer, defaultValue, resolvedParamType, (BfCastFlags)(BfCastFlags_SilentFail | BfCastFlags_NoConversionOperator));
  16358. if ((castedDefaultValue) && (castedDefaultValue.mValue.IsConst()))
  16359. {
  16360. defaultValue = castedDefaultValue; // Good!
  16361. }
  16362. else if (!CanImplicitlyCast(defaultValue, resolvedParamType))
  16363. {
  16364. // We only care that we get a constant value that can be implicitly casted at the callsite- even if that requires
  16365. // a conversion operator.
  16366. // This should throw an error
  16367. defaultValue = Cast(paramDef->mParamDeclaration->mInitializer, defaultValue, resolvedParamType);
  16368. AssertErrorState();
  16369. if (!defaultValue.mValue.IsConst())
  16370. defaultValue = BfTypedValue();
  16371. }
  16372. }
  16373. }
  16374. if (!defaultValue)
  16375. {
  16376. defaultValue = GetDefaultTypedValue(resolvedParamType);
  16377. if (!defaultValue.mValue.IsConst())
  16378. defaultValue = BfTypedValue();
  16379. }
  16380. if (defaultValue)
  16381. {
  16382. BF_ASSERT(defaultValue.mValue.IsConst());
  16383. while ((int)mCurMethodInstance->mDefaultValues.size() < paramDefIdx)
  16384. mCurMethodInstance->mDefaultValues.Add(BfIRValue());
  16385. CurrentAddToConstHolder(defaultValue.mValue);
  16386. mCurMethodInstance->mDefaultValues.Add(defaultValue.mValue);
  16387. }
  16388. }
  16389. if ((paramDef != NULL) && (paramDef->mParamKind == BfParamKind_Params))
  16390. {
  16391. bool addParams = true;
  16392. bool isValid = false;
  16393. auto resolvedParamTypeInst = resolvedParamType->ToTypeInstance();
  16394. if ((resolvedParamTypeInst != NULL) && (resolvedParamTypeInst->mTypeDef == mCompiler->mSpanTypeDef))
  16395. {
  16396. // Span<T>
  16397. isValid = true;
  16398. }
  16399. else if (resolvedParamType->IsArray())
  16400. {
  16401. // Array is the 'normal' params type
  16402. isValid = true;
  16403. }
  16404. else if ((resolvedParamType->IsDelegate()) || (resolvedParamType->IsFunction()))
  16405. {
  16406. hadDelegateParams = true;
  16407. // This means we copy the params from a delegate
  16408. BfMethodParam methodParam;
  16409. methodParam.mResolvedType = resolvedParamType;
  16410. methodParam.mParamDefIdx = paramDefIdx;
  16411. methodParam.mDelegateParamIdx = 0;
  16412. auto invokeMethodInstance = methodParam.GetDelegateParamInvoke();
  16413. for (int delegateParamIdx = 0; delegateParamIdx < invokeMethodInstance->GetParamCount(); delegateParamIdx++)
  16414. {
  16415. methodParam.mDelegateParamIdx = delegateParamIdx;
  16416. mCurMethodInstance->mParams.Add(methodParam);
  16417. auto paramType = invokeMethodInstance->GetParamType(delegateParamIdx);
  16418. if (!methodInstance->IsSpecializedGenericMethod())
  16419. AddDependency(paramType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ParamOrReturnValue);
  16420. }
  16421. isValid = true;
  16422. addParams = false;
  16423. }
  16424. else if (resolvedParamType->IsGenericParam())
  16425. {
  16426. auto genericParamInstance = GetGenericParamInstance((BfGenericParamType*)resolvedParamType);
  16427. if (genericParamInstance->mTypeConstraint != NULL)
  16428. {
  16429. auto typeInstConstraint = genericParamInstance->mTypeConstraint->ToTypeInstance();
  16430. if (genericParamInstance->mTypeConstraint->IsArray())
  16431. {
  16432. BfMethodParam methodParam;
  16433. methodParam.mResolvedType = resolvedParamType;
  16434. methodParam.mParamDefIdx = paramDefIdx;
  16435. mCurMethodInstance->mParams.Add(methodParam);
  16436. isValid = true;
  16437. }
  16438. else if ((genericParamInstance->mTypeConstraint->IsDelegate()) || (genericParamInstance->mTypeConstraint->IsFunction()) ||
  16439. ((genericParamInstance != NULL) && (typeInstConstraint != NULL) &&
  16440. ((typeInstConstraint->mTypeDef == mCompiler->mDelegateTypeDef) || (typeInstConstraint->mTypeDef == mCompiler->mFunctionTypeDef))))
  16441. {
  16442. mCurMethodInstance->mHadGenericDelegateParams = true;
  16443. isValid = true;
  16444. addParams = false;
  16445. }
  16446. }
  16447. }
  16448. else
  16449. {
  16450. auto paramTypeInst = resolvedParamType->ToTypeInstance();
  16451. if ((paramTypeInst != NULL) &&
  16452. ((paramTypeInst->mTypeDef == mCompiler->mDelegateTypeDef) || (paramTypeInst->mTypeDef == mCompiler->mFunctionTypeDef)))
  16453. {
  16454. // If we have a 'params T' and 'T' gets specialized with actually 'Delegate' or 'Function' then just ignore it
  16455. isValid = true;
  16456. addParams = false;
  16457. }
  16458. }
  16459. if (!isValid)
  16460. {
  16461. Fail("Parameters with 'params' specifiers can only be used for array, span, delegate, or function types", paramDef->mParamDeclaration->mModToken);
  16462. // Failure case, make it an Object[]
  16463. resolvedParamType = CreateArrayType(mContext->mBfObjectType, 1);
  16464. }
  16465. if (addParams)
  16466. {
  16467. BfMethodParam methodParam;
  16468. methodParam.mResolvedType = resolvedParamType;
  16469. methodParam.mParamDefIdx = paramDefIdx;
  16470. mCurMethodInstance->mParams.push_back(methodParam);
  16471. }
  16472. if (paramDefIdx < (int)methodDef->mParams.size() - 1)
  16473. {
  16474. Fail("Only the last parameter can specify 'params'", paramDef->mParamDeclaration->mModToken);
  16475. }
  16476. }
  16477. else
  16478. {
  16479. BfMethodParam methodParam;
  16480. methodParam.mResolvedType = resolvedParamType;
  16481. methodParam.mParamDefIdx = paramDefIdx;
  16482. mCurMethodInstance->mParams.Add(methodParam);
  16483. }
  16484. }
  16485. if (hadDelegateParams)
  16486. {
  16487. HashSet<String> usedNames;
  16488. Dictionary<int, int> usedParamDefIdx;
  16489. for (auto methodParam : methodDef->mParams)
  16490. {
  16491. usedNames.Add(methodParam->mName);
  16492. }
  16493. for (auto& methodParam : mCurMethodInstance->mParams)
  16494. {
  16495. if ((methodParam.mParamDefIdx != -1) && (methodParam.mDelegateParamIdx == 0))
  16496. {
  16497. int* refCount = NULL;
  16498. usedParamDefIdx.TryAdd(methodParam.mParamDefIdx, NULL, &refCount);
  16499. (*refCount)++;
  16500. }
  16501. }
  16502. for (auto& methodParam : mCurMethodInstance->mParams)
  16503. {
  16504. if (methodParam.mDelegateParamIdx != -1)
  16505. {
  16506. if (usedParamDefIdx[methodParam.mParamDefIdx] > 1)
  16507. methodParam.mDelegateParamNameCombine = true;
  16508. BfMethodInstance* invokeMethodInstance = methodParam.GetDelegateParamInvoke();
  16509. String paramName = invokeMethodInstance->GetParamName(methodParam.mDelegateParamIdx);
  16510. if (usedNames.Contains(paramName))
  16511. methodParam.mDelegateParamNameCombine = true;
  16512. }
  16513. }
  16514. }
  16515. int argIdx = 0;
  16516. PopulateType(methodInstance->mReturnType, BfPopulateType_Data);
  16517. if (methodInstance->HasStructRet())
  16518. argIdx++;
  16519. if (!methodDef->mIsStatic)
  16520. {
  16521. if (methodInstance->GetParamIsSplat(-1))
  16522. argIdx += methodInstance->GetParamType(-1)->GetSplatCount();
  16523. else if (!methodInstance->GetOwner()->IsValuelessType())
  16524. argIdx++;
  16525. }
  16526. for (auto& methodParam : mCurMethodInstance->mParams)
  16527. {
  16528. if (methodParam.mResolvedType->IsMethodRef())
  16529. {
  16530. methodParam.mIsSplat = true;
  16531. }
  16532. else if (methodParam.mResolvedType->IsComposite())
  16533. {
  16534. PopulateType(methodParam.mResolvedType, BfPopulateType_Data);
  16535. if (methodParam.mResolvedType->IsSplattable())
  16536. {
  16537. int splatCount = methodParam.mResolvedType->GetSplatCount();
  16538. if (argIdx + splatCount <= mCompiler->mOptions.mMaxSplatRegs)
  16539. {
  16540. methodParam.mIsSplat = true;
  16541. argIdx += splatCount;
  16542. continue;
  16543. }
  16544. }
  16545. }
  16546. argIdx++;
  16547. }
  16548. bool hasExternSpecifier = (methodDeclaration != NULL) && (methodDeclaration->mExternSpecifier != NULL);
  16549. if ((hasExternSpecifier) && (methodDeclaration->mBody != NULL))
  16550. {
  16551. Fail("Cannot 'extern' and declare a body", methodDeclaration->mExternSpecifier);
  16552. }
  16553. else if ((methodDeclaration != NULL) && (methodDeclaration->mBody == NULL) && (!hasExternSpecifier) &&
  16554. (!typeInstance->IsInterface()) && (!mCurTypeInstance->IsDelegate()) && (!mCurTypeInstance->IsFunction()) &&
  16555. (!methodDef->mIsPartial) && (!methodDef->mIsAbstract) &&
  16556. (!methodDef->mIsSkipCall))
  16557. {
  16558. if (methodDeclaration->mEndSemicolon == NULL)
  16559. {
  16560. AssertParseErrorState();
  16561. }
  16562. else
  16563. {
  16564. bool isError = true;
  16565. if (typeInstance->IsTypedPrimitive())
  16566. {
  16567. if (auto operatorDeclaration = BfNodeDynCast<BfOperatorDeclaration>(methodDeclaration))
  16568. {
  16569. if ((operatorDeclaration->mIsConvOperator) && (methodInstance->mParams.size() == 1))
  16570. {
  16571. if (((methodInstance->mReturnType == typeInstance) && (methodInstance->GetParamType(0) == typeInstance->GetUnderlyingType())) ||
  16572. ((methodInstance->mReturnType == typeInstance->GetUnderlyingType()) && (methodInstance->GetParamType(0) == typeInstance)))
  16573. {
  16574. isError = false;
  16575. }
  16576. }
  16577. }
  16578. }
  16579. if (isError)
  16580. {
  16581. Fail(StrFormat("'%s' must declare a body because it is not marked abstract, extern, or partial",
  16582. MethodToString(methodInstance).c_str()),
  16583. methodDef->GetRefNode());
  16584. }
  16585. }
  16586. }
  16587. if (methodDef->IsEmptyPartial())
  16588. hasExternSpecifier = true;
  16589. if (!methodInstance->IsAutocompleteMethod())
  16590. {
  16591. auto defaultMethodInstance = methodInstance->mMethodInstanceGroup->mDefault;
  16592. int implicitParamCount = methodInstance->GetImplicitParamCount();
  16593. int defaultImplicitParamCount = defaultMethodInstance->GetImplicitParamCount();
  16594. int actualParamCount = (int)methodInstance->mParams.size() - implicitParamCount;
  16595. BF_ASSERT((actualParamCount == defaultMethodInstance->mParams.size() - defaultImplicitParamCount) || (defaultMethodInstance->mHadGenericDelegateParams));
  16596. mCurMethodInstance->mHadGenericDelegateParams = defaultMethodInstance->mHadGenericDelegateParams;
  16597. int paramIdx = 0;
  16598. int defaultParamIdx = 0;
  16599. while (true)
  16600. {
  16601. bool isDone = paramIdx + implicitParamCount >= (int)methodInstance->mParams.size();
  16602. bool isDefaultDone = defaultParamIdx + defaultImplicitParamCount >= (int)defaultMethodInstance->mParams.size();
  16603. if ((!isDone) && (methodInstance->mParams[paramIdx + implicitParamCount].mDelegateParamIdx >= 0))
  16604. {
  16605. paramIdx++;
  16606. continue;
  16607. }
  16608. if ((!isDefaultDone) && (defaultMethodInstance->mParams[defaultParamIdx + defaultImplicitParamCount].mDelegateParamIdx >= 0))
  16609. {
  16610. defaultParamIdx++;
  16611. continue;
  16612. }
  16613. if ((isDone) || (isDefaultDone))
  16614. {
  16615. // 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
  16616. // to cause us to throw an assertion in the declaration here
  16617. if (!defaultMethodInstance->mHadGenericDelegateParams)
  16618. BF_ASSERT((isDone) && (isDefaultDone));
  16619. break;
  16620. }
  16621. methodInstance->mParams[paramIdx + implicitParamCount].mWasGenericParam = defaultMethodInstance->mParams[defaultParamIdx + defaultImplicitParamCount].mResolvedType->IsGenericParam();
  16622. paramIdx++;
  16623. defaultParamIdx++;
  16624. }
  16625. }
  16626. StringT<128> mangledName;
  16627. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), mCurMethodInstance);
  16628. for (int paramIdx = 0; paramIdx < methodInstance->GetParamCount(); paramIdx++)
  16629. {
  16630. auto paramType = methodInstance->GetParamType(paramIdx);
  16631. if (paramType->IsComposite())
  16632. PopulateType(paramType, BfPopulateType_Data);
  16633. if (!methodInstance->IsParamSkipped(paramIdx))
  16634. {
  16635. if (paramType->IsStruct())
  16636. {
  16637. //
  16638. }
  16639. else
  16640. {
  16641. PopulateType(paramType, BfPopulateType_Declaration);
  16642. }
  16643. }
  16644. }
  16645. // Only process method in default unspecialized mode, not in variations
  16646. if (methodInstance->mIsUnspecializedVariation)
  16647. return;
  16648. PopulateType(resolvedReturnType, BfPopulateType_Data);
  16649. auto retLLVMType = mBfIRBuilder->MapType(resolvedReturnType);
  16650. if (resolvedReturnType->IsValuelessType())
  16651. retLLVMType = mBfIRBuilder->GetPrimitiveType(BfTypeCode_None);
  16652. if (!mBfIRBuilder->mIgnoreWrites)
  16653. {
  16654. bool isIntrinsic = false;
  16655. if (!methodInstance->mIRFunction)
  16656. SetupIRFunction(methodInstance, mangledName, isTemporaryFunc, &isIntrinsic);
  16657. if (isIntrinsic)
  16658. {
  16659. addToWorkList = false;
  16660. }
  16661. }
  16662. auto func = methodInstance->mIRFunction;
  16663. // if (methodInstance->mIsReified)
  16664. // CheckHotMethod(methodInstance, mangledName);
  16665. 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);
  16666. SizedArray<BfIRMDNode, 8> diParams;
  16667. diParams.push_back(mBfIRBuilder->DbgGetType(resolvedReturnType));
  16668. if ((!methodDef->mIsStatic) && (typeDef->mIsStatic) && (methodDef->mMethodDeclaration != NULL))
  16669. {
  16670. //CS0708
  16671. Fail("Cannot declare instance members in a static class", methodDef->GetRefNode());
  16672. }
  16673. if ((methodDef->mIsVirtual) && (methodDef->mGenericParams.size() != 0))
  16674. {
  16675. Fail("Virtual generic methods not supported", methodDeclaration->mVirtualSpecifier);
  16676. methodDef->mIsVirtual = false;
  16677. }
  16678. if ((methodDeclaration != NULL) && (methodDeclaration->mMutSpecifier != NULL) && (!mCurTypeInstance->IsBoxed()) && (!methodInstance->mIsForeignMethodDef))
  16679. {
  16680. if (methodDef->mIsStatic)
  16681. Warn(0, "Unnecessary 'mut' specifier, static methods have no implicit 'this' target to mutate", methodDeclaration->mMutSpecifier);
  16682. else if ((!mCurTypeInstance->IsValueType()) && (!mCurTypeInstance->IsInterface()))
  16683. Warn(0, "Unnecessary 'mut' specifier, methods of reference types are implicitly mutating", methodDeclaration->mMutSpecifier);
  16684. else if (methodDef->mMethodType == BfMethodType_Ctor)
  16685. Warn(0, "Unnecessary 'mut' specifier, constructors are implicitly mutating", methodDeclaration->mMutSpecifier);
  16686. else if (methodDef->mMethodType == BfMethodType_Dtor)
  16687. Warn(0, "Unnecessary 'mut' specifier, destructors are implicitly mutating", methodDeclaration->mMutSpecifier);
  16688. }
  16689. if (isTemporaryFunc)
  16690. {
  16691. // This handles temporary methods for autocomplete types
  16692. BF_ASSERT(mIsScratchModule);
  16693. BF_ASSERT(mCompiler->IsAutocomplete());
  16694. BfLogSysM("DoMethodDeclaration autocomplete bailout\n");
  16695. return; // Bail out early for autocomplete pass
  16696. }
  16697. //TODO: We used to have this (this != mContext->mExternalFuncModule) check, but it caused us to keep around
  16698. // an invalid mFuncRefernce (which came from GetMethodInstanceAtIdx) which later got remapped by the
  16699. // autocompleter. Why did we have this check anyway?
  16700. /*if ((typeInstance->mContext != mContext) && (!methodDef->IsEmptyPartial()))
  16701. {
  16702. AddMethodReference(methodInstance);
  16703. mFuncReferences[methodInstance] = func;
  16704. BfLogSysM("Adding func reference (DoMethodDeclaration). Module:%p MethodInst:%p LLVMFunc:%p\n", this, methodInstance, func);
  16705. }*/
  16706. if (mParentModule != NULL)
  16707. {
  16708. // For extension modules we need to keep track of our own methods so we can know which methods
  16709. // we have defined ourselves and which are from the parent module or other extensions
  16710. if (!func.IsFake())
  16711. mFuncReferences[methodInstance] = func;
  16712. }
  16713. if (addToWorkList)
  16714. {
  16715. bool wasAwaitingDecl = methodInstance->mMethodInstanceGroup->mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingDecl;
  16716. if (wasAwaitingDecl)
  16717. methodInstance->mMethodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_Decl_AwaitingReference;
  16718. if ((!methodDef->mIsAbstract) && (!methodInstance->mIgnoreBody))
  16719. {
  16720. if (!wasAwaitingDecl)
  16721. AddMethodToWorkList(methodInstance);
  16722. }
  16723. else
  16724. {
  16725. BfLogSysM("DoMethodDeclaration ignoring method body %d %d %d\n", hasExternSpecifier, methodDef->mIsAbstract, methodInstance->mIgnoreBody);
  16726. methodInstance->mIgnoreBody = true;
  16727. if (typeInstance->IsUnspecializedType())
  16728. {
  16729. // Don't hold on to actual Function for unspecialized types
  16730. methodInstance->mIRFunction = BfIRFunction();
  16731. }
  16732. }
  16733. }
  16734. if ((!methodInstance->IsSpecializedGenericMethodOrType()) && (!mCurTypeInstance->IsBoxed()) &&
  16735. (!methodDef->mIsLocalMethod) &&
  16736. (!CheckDefineMemberProtection(methodDef->mProtection, methodInstance->mReturnType)))
  16737. {
  16738. if (methodDef->mMethodType == BfMethodType_PropertyGetter)
  16739. {
  16740. //TODO:
  16741. //CS0053
  16742. Fail(StrFormat("Inconsistent accessibility: property type '%s' is less accessible than property '%s'",
  16743. TypeToString(methodInstance->mReturnType).c_str(), MethodToString(methodInstance).c_str()),
  16744. methodDef->mReturnTypeRef, true);
  16745. }
  16746. else
  16747. {
  16748. //CS0050
  16749. Fail(StrFormat("Inconsistent accessibility: return type '%s' is less accessible than method '%s'",
  16750. TypeToString(methodInstance->mReturnType).c_str(), MethodToString(methodInstance).c_str()),
  16751. methodDef->mReturnTypeRef, true);
  16752. }
  16753. }
  16754. if ((typeInstance->IsInterface()) && (methodDef->mMethodType == BfMethodType_Ctor))
  16755. {
  16756. Fail("Interfaces cannot contain constructors", methodDeclaration);
  16757. }
  16758. // Don't compare specialized generic methods against normal methods
  16759. if ((((mCurMethodInstance->mIsUnspecialized) || (mCurMethodInstance->mMethodDef->mGenericParams.size() == 0))) &&
  16760. (!methodDef->mIsLocalMethod))
  16761. {
  16762. if (!methodInstance->mIsForeignMethodDef)
  16763. {
  16764. typeDef->PopulateMemberSets();
  16765. BfMethodDef* nextMethod = NULL;
  16766. BfMemberSetEntry* entry = NULL;
  16767. if (typeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  16768. nextMethod = (BfMethodDef*)entry->mMemberDef;
  16769. while (nextMethod != NULL)
  16770. {
  16771. auto checkMethod = nextMethod;
  16772. nextMethod = nextMethod->mNextWithSameName;
  16773. if ((checkMethod != methodDef) && (typeInstance->mMethodInstanceGroups[checkMethod->mIdx].mDefault != NULL))
  16774. {
  16775. auto checkMethodInstance = typeInstance->mMethodInstanceGroups[checkMethod->mIdx].mDefault;
  16776. if (((checkMethodInstance->mChainType == BfMethodChainType_None) || (checkMethodInstance->mChainType == BfMethodChainType_ChainHead)) &&
  16777. (checkMethodInstance->GetExplicitInterface() == methodInstance->GetExplicitInterface()) &&
  16778. (CompareMethodSignatures(checkMethodInstance, mCurMethodInstance)))
  16779. {
  16780. bool canChain = false;
  16781. if ((methodDef->mParams.empty()) &&
  16782. (checkMethodInstance->mMethodDef->mIsStatic == methodInstance->mMethodDef->mIsStatic))
  16783. {
  16784. if ((methodDef->mMethodType == BfMethodType_CtorNoBody) || (methodDef->mMethodType == BfMethodType_Dtor))
  16785. canChain = true;
  16786. else if (methodDef->mMethodType == BfMethodType_Normal)
  16787. {
  16788. if ((methodDef->mName == BF_METHODNAME_MARKMEMBERS) ||
  16789. (methodDef->mName == BF_METHODNAME_MARKMEMBERS_STATIC) ||
  16790. (methodDef->mName == BF_METHODNAME_FIND_TLS_MEMBERS))
  16791. canChain = true;
  16792. }
  16793. }
  16794. if (canChain)
  16795. {
  16796. bool isBetter;
  16797. bool isWorse;
  16798. CompareDeclTypes(checkMethodInstance->mMethodDef->mDeclaringType, methodInstance->mMethodDef->mDeclaringType, isBetter, isWorse);
  16799. if (isBetter && !isWorse)
  16800. {
  16801. methodInstance->mChainType = BfMethodChainType_ChainHead;
  16802. checkMethodInstance->mChainType = BfMethodChainType_ChainMember;
  16803. }
  16804. else
  16805. {
  16806. checkMethodInstance->mChainType = BfMethodChainType_ChainHead;
  16807. methodInstance->mChainType = BfMethodChainType_ChainMember;
  16808. }
  16809. }
  16810. else if ((checkMethod->mBody == NULL) && (methodDef->mBody != NULL) &&
  16811. (checkMethod->mDeclaringType != methodDef->mDeclaringType))
  16812. {
  16813. // We're allowed to override an empty-bodied method
  16814. checkMethodInstance->mChainType = BfMethodChainType_ChainSkip;
  16815. }
  16816. else
  16817. {
  16818. if (!typeInstance->IsTypeMemberAccessible(checkMethod->mDeclaringType, methodDef->mDeclaringType))
  16819. continue;
  16820. bool silentlyAllow = false;
  16821. if (checkMethod->mDeclaringType != methodDef->mDeclaringType)
  16822. {
  16823. if (typeInstance->IsInterface())
  16824. {
  16825. if (methodDef->mIsOverride)
  16826. silentlyAllow = true;
  16827. }
  16828. else
  16829. silentlyAllow = true;
  16830. }
  16831. if (!silentlyAllow)
  16832. {
  16833. if (!methodDef->mName.IsEmpty())
  16834. {
  16835. auto refNode = methodDef->GetRefNode();
  16836. auto bfError = Fail("Method already declared with the same parameter types", refNode, true);
  16837. if (bfError != NULL)
  16838. mCompiler->mPassInstance->MoreInfo("First declaration", checkMethod->GetRefNode());
  16839. }
  16840. }
  16841. }
  16842. }
  16843. }
  16844. }
  16845. }
  16846. // Virtual methods give their error while slotting
  16847. if ((!typeInstance->IsBoxed()) && (!methodDef->mIsVirtual) && (methodDef->mProtection != BfProtection_Private) &&
  16848. (!methodDef->mIsLocalMethod) &&
  16849. (!methodInstance->mIsForeignMethodDef) && (typeInstance->mBaseType != NULL) &&
  16850. (methodDef->mMethodType == BfMethodType_Normal) && (methodDef->mMethodDeclaration != NULL))
  16851. {
  16852. bool foundHiddenMethod = false;
  16853. auto baseType = typeInstance->mBaseType;
  16854. while (baseType != NULL)
  16855. {
  16856. //for (int checkMethodIdx = 0; checkMethodIdx < (int) baseType->mTypeDef->mMethods.size(); checkMethodIdx++)
  16857. auto baseTypeDef = baseType->mTypeDef;
  16858. baseTypeDef->PopulateMemberSets();
  16859. BfMethodDef* checkMethod = NULL;
  16860. BfMemberSetEntry* entry = NULL;
  16861. if (baseTypeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  16862. checkMethod = (BfMethodDef*)entry->mMemberDef;
  16863. while (checkMethod != NULL)
  16864. {
  16865. if (checkMethod->mMethodDeclaration == NULL)
  16866. continue;
  16867. if (baseType->mMethodInstanceGroups.size() == 0)
  16868. {
  16869. BF_ASSERT(baseType->IsIncomplete() && mCompiler->IsAutocomplete());
  16870. break;
  16871. }
  16872. if (checkMethod == methodDef)
  16873. continue;
  16874. if (checkMethod->mName != methodDef->mName)
  16875. continue;
  16876. auto checkMethodInstance = GetRawMethodInstanceAtIdx(baseType, checkMethod->mIdx);
  16877. if (checkMethodInstance != NULL)
  16878. {
  16879. if ((checkMethodInstance->GetExplicitInterface() == methodInstance->GetExplicitInterface()) &&
  16880. (checkMethod->mProtection != BfProtection_Private) &&
  16881. (CompareMethodSignatures(checkMethodInstance, mCurMethodInstance)))
  16882. {
  16883. if (!methodDef->mIsNew)
  16884. {
  16885. BfAstNode* refNode = methodInstance->mMethodDef->GetRefNode();
  16886. if (refNode != NULL)
  16887. {
  16888. 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?
  16889. if (bfError != NULL)
  16890. bfError->mIsPersistent = true;
  16891. }
  16892. }
  16893. foundHiddenMethod = true;
  16894. break;
  16895. }
  16896. }
  16897. checkMethod = checkMethod->mNextWithSameName;
  16898. }
  16899. if (foundHiddenMethod)
  16900. break;
  16901. baseType = baseType->mBaseType;
  16902. }
  16903. if ((methodDef->mIsNew) && (!foundHiddenMethod))
  16904. {
  16905. auto propertyDeclaration = methodDef->GetPropertyDeclaration();
  16906. auto tokenNode = (propertyDeclaration != NULL) ? propertyDeclaration->mNewSpecifier :
  16907. methodDeclaration->mNewSpecifier;
  16908. Fail("Method does not hide an inherited member. The 'new' keyword is not required", tokenNode, true);
  16909. }
  16910. }
  16911. }
  16912. mCompiler->mStats.mMethodDeclarations++;
  16913. mCompiler->UpdateCompletion();
  16914. }
  16915. void BfModule::UniqueSlotVirtualMethod(BfMethodInstance* methodInstance)
  16916. {
  16917. BF_ASSERT(methodInstance->GetOwner() == mCurTypeInstance);
  16918. auto typeInstance = mCurTypeInstance;
  16919. auto methodDef = methodInstance->mMethodDef;
  16920. int virtualMethodMatchIdx = -1;
  16921. if (typeInstance->mHotTypeData != NULL)
  16922. {
  16923. if (typeInstance->mHotTypeData->mVTableOrigLength != -1)
  16924. {
  16925. BF_ASSERT(mCompiler->IsHotCompile());
  16926. // In the 'normal' case we'd assert that mIsOverride is false, but if we can't find the declaring method then we
  16927. // may slot this override anyway (?)
  16928. int vTableStart = 0;
  16929. if (typeInstance->mBaseType != NULL)
  16930. vTableStart = typeInstance->mBaseType->mVirtualMethodTableSize;
  16931. StringT<128> mangledName;
  16932. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), methodInstance);
  16933. for (int checkIdxOfs = 0; checkIdxOfs < (int)typeInstance->mHotTypeData->mVTableEntries.size(); checkIdxOfs++)
  16934. {
  16935. // O(1) checking when virtual methods haven't changed
  16936. int checkIdx = (typeInstance->mVirtualMethodTableSize - vTableStart + checkIdxOfs) % (int)typeInstance->mHotTypeData->mVTableEntries.size();
  16937. auto& entry = typeInstance->mHotTypeData->mVTableEntries[checkIdx];
  16938. if (mangledName == entry.mFuncName)
  16939. {
  16940. virtualMethodMatchIdx = vTableStart + checkIdx;
  16941. break;
  16942. }
  16943. }
  16944. if (virtualMethodMatchIdx != -1)
  16945. {
  16946. methodInstance->mVirtualTableIdx = virtualMethodMatchIdx;
  16947. typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mDeclaringMethod = methodInstance;
  16948. typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mImplementingMethod = methodInstance;
  16949. }
  16950. typeInstance->mVirtualMethodTableSize = (int)typeInstance->mVirtualMethodTable.size();
  16951. }
  16952. }
  16953. if (virtualMethodMatchIdx == -1)
  16954. {
  16955. methodInstance->mVirtualTableIdx = typeInstance->mVirtualMethodTableSize++;
  16956. BfVirtualMethodEntry entry = { methodInstance, methodInstance };
  16957. typeInstance->mVirtualMethodTable.push_back(entry);
  16958. }
  16959. }
  16960. void BfModule::CompareDeclTypes(BfTypeDef* newDeclType, BfTypeDef* prevDeclType, bool& isBetter, bool& isWorse)
  16961. {
  16962. if ((!prevDeclType->IsExtension()) && (newDeclType->IsExtension()))
  16963. {
  16964. // When we provide an extension override in the same project a root type override
  16965. isBetter = true;
  16966. isWorse = false;
  16967. }
  16968. else
  16969. {
  16970. isBetter = newDeclType->mProject->ContainsReference(prevDeclType->mProject);
  16971. isWorse = prevDeclType->mProject->ContainsReference(newDeclType->mProject);
  16972. }
  16973. }
  16974. bool BfModule::SlotVirtualMethod(BfMethodInstance* methodInstance, BfAmbiguityContext* ambiguityContext)
  16975. {
  16976. BP_ZONE("BfModule::SlotVirtualMethod");
  16977. if (mCurTypeInstance->IsUnspecializedTypeVariation())
  16978. return false;
  16979. auto _AddVirtualDecl = [&](BfMethodInstance* declMethodInstance)
  16980. {
  16981. if (!mCompiler->mOptions.mAllowHotSwapping)
  16982. return;
  16983. if ((!methodInstance->mIsReified) || (!declMethodInstance->mIsReified))
  16984. return;
  16985. if (methodInstance->mHotMethod == NULL)
  16986. CheckHotMethod(methodInstance, "");
  16987. if (methodInstance->mHotMethod == NULL)
  16988. return;
  16989. //BF_ASSERT(declMethodInstance->mHotMethod != NULL);
  16990. if (declMethodInstance->mHotMethod == NULL)
  16991. CheckHotMethod(declMethodInstance, "");
  16992. auto virtualDecl = mCompiler->mHotData->GetVirtualDeclaration(declMethodInstance->mHotMethod);
  16993. virtualDecl->mRefCount++;
  16994. methodInstance->mHotMethod->mReferences.Add(virtualDecl);
  16995. };
  16996. auto typeInstance = mCurTypeInstance;
  16997. auto typeDef = typeInstance->mTypeDef;
  16998. auto methodDef = methodInstance->mMethodDef;
  16999. auto methodDeclaration = methodDef->GetMethodDeclaration();
  17000. auto propertyDeclaration = methodDef->GetPropertyDeclaration();
  17001. auto propertyMethodDeclaration = methodDef->GetPropertyMethodDeclaration();
  17002. BfAstNode* declaringNode = methodDeclaration;
  17003. if (propertyMethodDeclaration != NULL)
  17004. declaringNode = propertyMethodDeclaration->mNameNode;
  17005. BfMethodInstance* methodOverriden = NULL;
  17006. bool usedMethod = false;
  17007. BfTokenNode* virtualToken = NULL;
  17008. if (propertyDeclaration != NULL)
  17009. virtualToken = propertyDeclaration->mVirtualSpecifier;
  17010. else if (methodDeclaration != NULL)
  17011. virtualToken = methodDeclaration->mVirtualSpecifier;
  17012. if ((methodDef->mIsVirtual) && (methodDef->mIsStatic))
  17013. {
  17014. Fail("Static members cannot be marked as override, virtual, or abstract", virtualToken, true);
  17015. }
  17016. else if (methodDef->mIsVirtual)
  17017. {
  17018. if (mCompiler->IsHotCompile())
  17019. mContext->EnsureHotMangledVirtualMethodName(methodInstance);
  17020. if ((methodDef->mProtection == BfProtection_Private) && (virtualToken != NULL))
  17021. Fail("Virtual or abstract members cannot be private", virtualToken, true);
  17022. BfTypeInstance* checkBase = typeInstance;
  17023. // If we are in an extension, look in ourselves first
  17024. if (methodDef->mDeclaringType->mTypeDeclaration == typeInstance->mTypeDef->mTypeDeclaration)
  17025. checkBase = checkBase->mBaseType;
  17026. if (typeInstance->IsValueType())
  17027. {
  17028. if (typeInstance->mBaseType == NULL)
  17029. return false; // It's actually ValueType
  17030. // We allow structs to override object methods for when they get boxed, so just ignore 'override' keyword until it gets boxed
  17031. if (!methodDef->mIsOverride)
  17032. {
  17033. Fail("Structs cannot have virtual methods", virtualToken, true);
  17034. return false;
  17035. }
  17036. checkBase = mContext->mBfObjectType;
  17037. if (checkBase->mVirtualMethodTableSize == 0)
  17038. PopulateType(checkBase, BfPopulateType_Full);
  17039. if (checkBase->mDefineState < BfTypeDefineState_DefinedAndMethodsSlotted)
  17040. return false; // System circular ref, don't do struct checking on those
  17041. }
  17042. int virtualMethodMatchIdx = -1;
  17043. bool hadHidingError = false;
  17044. BfMethodInstance* bestOverrideMethodInstance = NULL;
  17045. BfMethodInstance* ambiguousOverrideMethodInstance = NULL;
  17046. int bestOverrideMethodIdx = -1;
  17047. int ambiguousOverrideMethodIdx = -1;
  17048. if (checkBase != NULL)
  17049. {
  17050. auto& baseVirtualMethodTable = checkBase->mVirtualMethodTable;
  17051. auto lookupType = checkBase;
  17052. while (lookupType != NULL)
  17053. {
  17054. lookupType->mTypeDef->PopulateMemberSets();
  17055. BfMethodDef* nextMethodDef = NULL;
  17056. BfMemberSetEntry* entry;
  17057. if (lookupType->mTypeDef->mMethodSet.TryGetWith(methodInstance->mMethodDef->mName, &entry))
  17058. nextMethodDef = (BfMethodDef*)entry->mMemberDef;
  17059. while (nextMethodDef != NULL)
  17060. {
  17061. auto checkMethodDef = nextMethodDef;
  17062. nextMethodDef = nextMethodDef->mNextWithSameName;
  17063. if ((!checkMethodDef->mIsVirtual) || (checkMethodDef->mIsOverride))
  17064. continue;
  17065. BfMethodInstance* lookupMethodInstance = lookupType->mMethodInstanceGroups[checkMethodDef->mIdx].mDefault;
  17066. if ((lookupMethodInstance == NULL) || (lookupMethodInstance->mVirtualTableIdx == -1))
  17067. continue;
  17068. int checkMethodIdx = lookupMethodInstance->mVirtualTableIdx;
  17069. auto& baseMethodRef = baseVirtualMethodTable[checkMethodIdx];
  17070. if (baseMethodRef.mDeclaringMethod.mMethodNum == -1)
  17071. {
  17072. BF_ASSERT(mCompiler->mOptions.mHasVDataExtender);
  17073. continue;
  17074. }
  17075. BfMethodInstance* baseMethodInstance = baseVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  17076. if (baseMethodInstance == NULL)
  17077. {
  17078. AssertErrorState();
  17079. continue;
  17080. }
  17081. if ((baseMethodInstance != NULL) && (CompareMethodSignatures(baseMethodInstance, methodInstance)))
  17082. {
  17083. if (methodDef->mIsOverride)
  17084. {
  17085. BfMethodInstance* checkMethodInstance;
  17086. if (typeInstance->IsValueType())
  17087. checkMethodInstance = checkBase->mVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  17088. else
  17089. checkMethodInstance = typeInstance->mVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  17090. auto newDeclType = checkMethodInstance->mMethodDef->mDeclaringType;
  17091. if (!typeInstance->IsTypeMemberAccessible(newDeclType, methodDef->mDeclaringType->mProject))
  17092. continue;
  17093. if (bestOverrideMethodInstance != NULL)
  17094. {
  17095. auto prevDeclType = bestOverrideMethodInstance->mMethodDef->mDeclaringType;
  17096. bool isBetter = newDeclType->mProject->ContainsReference(prevDeclType->mProject);
  17097. bool isWorse = prevDeclType->mProject->ContainsReference(newDeclType->mProject);
  17098. if (isBetter == isWorse)
  17099. {
  17100. ambiguousOverrideMethodInstance = bestOverrideMethodInstance;
  17101. }
  17102. else
  17103. {
  17104. if (isWorse)
  17105. continue;
  17106. ambiguousOverrideMethodInstance = NULL;
  17107. }
  17108. }
  17109. bestOverrideMethodInstance = checkMethodInstance;
  17110. bestOverrideMethodIdx = checkMethodIdx;
  17111. }
  17112. else
  17113. {
  17114. if ((baseMethodInstance->GetOwner() != methodInstance->GetOwner()) && (!methodDef->mIsNew))
  17115. {
  17116. if (!hadHidingError)
  17117. Warn(BfWarning_CS0114_MethodHidesInherited, StrFormat("Method hides inherited member from '%s'. Use either 'override' or 'new'.", TypeToString(checkBase).c_str()), declaringNode);
  17118. hadHidingError = true;
  17119. }
  17120. }
  17121. }
  17122. }
  17123. lookupType = lookupType->mBaseType;
  17124. }
  17125. }
  17126. //TODO:
  17127. if ((checkBase != NULL)
  17128. && (false)
  17129. )
  17130. {
  17131. auto& baseVirtualMethodTable = checkBase->mVirtualMethodTable;
  17132. for (int checkMethodIdx = (int) baseVirtualMethodTable.size() - 1; checkMethodIdx >= 0; checkMethodIdx--)
  17133. {
  17134. auto& baseMethodRef = baseVirtualMethodTable[checkMethodIdx];
  17135. if (baseMethodRef.mDeclaringMethod.mMethodNum == -1)
  17136. {
  17137. BF_ASSERT(mCompiler->mOptions.mHasVDataExtender);
  17138. continue;
  17139. }
  17140. BfMethodInstance* baseMethodInstance = baseVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  17141. if (baseMethodInstance == NULL)
  17142. {
  17143. AssertErrorState();
  17144. continue;
  17145. }
  17146. if ((baseMethodInstance != NULL) && (CompareMethodSignatures(baseMethodInstance, methodInstance)))
  17147. {
  17148. if (methodDef->mIsOverride)
  17149. {
  17150. BfMethodInstance* checkMethodInstance;
  17151. if (typeInstance->IsValueType())
  17152. checkMethodInstance = checkBase->mVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  17153. else
  17154. checkMethodInstance = typeInstance->mVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  17155. auto newDeclType = checkMethodInstance->mMethodDef->mDeclaringType;
  17156. if (!typeInstance->IsTypeMemberAccessible(newDeclType, methodDef->mDeclaringType->mProject))
  17157. continue;
  17158. if (bestOverrideMethodInstance != NULL)
  17159. {
  17160. auto prevDeclType = bestOverrideMethodInstance->mMethodDef->mDeclaringType;
  17161. bool isBetter = newDeclType->mProject->ContainsReference(prevDeclType->mProject);
  17162. bool isWorse = prevDeclType->mProject->ContainsReference(newDeclType->mProject);
  17163. if (isBetter == isWorse)
  17164. {
  17165. ambiguousOverrideMethodInstance = bestOverrideMethodInstance;
  17166. }
  17167. else
  17168. {
  17169. if (isWorse)
  17170. continue;
  17171. ambiguousOverrideMethodInstance = NULL;
  17172. }
  17173. }
  17174. bestOverrideMethodInstance = checkMethodInstance;
  17175. bestOverrideMethodIdx = checkMethodIdx;
  17176. }
  17177. else
  17178. {
  17179. if ((baseMethodInstance->GetOwner() != methodInstance->GetOwner()) && (!methodDef->mIsNew))
  17180. {
  17181. if (!hadHidingError)
  17182. Warn(BfWarning_CS0114_MethodHidesInherited, StrFormat("Method hides inherited member from '%s'. Use either 'override' or 'new'.", TypeToString(checkBase).c_str()), declaringNode);
  17183. hadHidingError = true;
  17184. }
  17185. }
  17186. }
  17187. }
  17188. }
  17189. if (bestOverrideMethodInstance != NULL)
  17190. {
  17191. if (ambiguousOverrideMethodInstance != NULL)
  17192. {
  17193. bool allow = false;
  17194. // 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.
  17195. // When when specialize, the specialized type will determine wither it has illegally pulled in both declarations or not
  17196. bool canSeeEachOther = false;
  17197. //
  17198. {
  17199. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, ambiguousOverrideMethodInstance);
  17200. if (bestOverrideMethodInstance->GetOwner()->IsTypeMemberIncluded(bestOverrideMethodInstance->mMethodDef->mDeclaringType, ambiguousOverrideMethodInstance->mMethodDef->mDeclaringType, this))
  17201. canSeeEachOther = true;
  17202. }
  17203. //
  17204. {
  17205. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, bestOverrideMethodInstance);
  17206. if (ambiguousOverrideMethodInstance->GetOwner()->IsTypeMemberIncluded(ambiguousOverrideMethodInstance->mMethodDef->mDeclaringType, bestOverrideMethodInstance->mMethodDef->mDeclaringType, this))
  17207. canSeeEachOther = true;
  17208. }
  17209. if (!canSeeEachOther)
  17210. {
  17211. BF_ASSERT(bestOverrideMethodInstance->GetOwner()->IsUnspecializedType() && ambiguousOverrideMethodInstance->GetOwner()->IsUnspecializedType());
  17212. }
  17213. else
  17214. {
  17215. auto error = Fail(StrFormat("Method '%s' is an ambiguous override", MethodToString(methodInstance).c_str()), methodDef->GetRefNode());
  17216. if (error != NULL)
  17217. {
  17218. mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' is a candidate", MethodToString(bestOverrideMethodInstance).c_str()), bestOverrideMethodInstance->mMethodDef->GetRefNode());
  17219. mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' is a candidate", MethodToString(ambiguousOverrideMethodInstance).c_str()), ambiguousOverrideMethodInstance->mMethodDef->GetRefNode());
  17220. }
  17221. }
  17222. }
  17223. auto& baseVirtualMethodTable = checkBase->mVirtualMethodTable;
  17224. BfMethodInstance* baseVirtualMethodInstance = baseVirtualMethodTable[bestOverrideMethodIdx].mDeclaringMethod;
  17225. if ((baseVirtualMethodInstance != methodInstance) && (methodDef->mIsOverride))
  17226. {
  17227. if (baseVirtualMethodInstance->mReturnType != methodInstance->mReturnType)
  17228. {
  17229. BfTypeReference* returnTypeRef;
  17230. if (auto propertyDeclaration = methodDef->GetPropertyDeclaration())
  17231. {
  17232. returnTypeRef = propertyDeclaration->mTypeRef;
  17233. Fail("Property differs from overridden property by type", returnTypeRef, true);
  17234. }
  17235. else if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  17236. {
  17237. returnTypeRef = methodDeclaration->mReturnType;
  17238. Fail("Method differs from overridden method by return value", returnTypeRef, true);
  17239. }
  17240. else
  17241. {
  17242. Fail(StrFormat("Internal error with method '%s'", MethodToString(methodInstance).c_str()));
  17243. }
  17244. return usedMethod;
  17245. }
  17246. }
  17247. if (methodDef->mIsOverride)
  17248. {
  17249. // We can have multiple matches when a virtual method is used to implement interface methods
  17250. // It doesn't matter what we set mVirtualTableIdx, as all base classes will override all matching
  17251. // vtable entries for this method signature
  17252. virtualMethodMatchIdx = bestOverrideMethodIdx;
  17253. if (!typeInstance->IsValueType())
  17254. methodInstance->mVirtualTableIdx = virtualMethodMatchIdx;
  17255. if (typeInstance->IsValueType())
  17256. {
  17257. methodOverriden = checkBase->mVirtualMethodTable[virtualMethodMatchIdx].mImplementingMethod;
  17258. }
  17259. else
  17260. {
  17261. methodInstance->mVirtualTableIdx = virtualMethodMatchIdx;
  17262. auto& overridenRef = typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mImplementingMethod;
  17263. if (overridenRef.mKind != BfMethodRefKind_AmbiguousRef)
  17264. {
  17265. methodOverriden = overridenRef;
  17266. BfMethodInstance* setMethodInstance = methodInstance;
  17267. bool doOverride = true;
  17268. if (methodOverriden->GetOwner() == methodInstance->GetOwner())
  17269. {
  17270. bool isBetter = false;
  17271. bool isWorse = false;
  17272. CompareDeclTypes(methodInstance->mMethodDef->mDeclaringType, methodOverriden->mMethodDef->mDeclaringType, isBetter, isWorse);
  17273. if (isBetter == isWorse)
  17274. {
  17275. // We have to resolve later per-project
  17276. if ((ambiguityContext != NULL) && (ambiguityContext->mIsProjectSpecific))
  17277. {
  17278. auto declMethodInstance = checkBase->mVirtualMethodTable[virtualMethodMatchIdx].mDeclaringMethod;
  17279. ambiguityContext->Add(virtualMethodMatchIdx, NULL, -1, methodOverriden, methodInstance);
  17280. }
  17281. if ((ambiguityContext == NULL) || (!ambiguityContext->mIsProjectSpecific))
  17282. typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mImplementingMethod.mKind = BfMethodRefKind_AmbiguousRef;
  17283. doOverride = false;
  17284. }
  17285. else
  17286. {
  17287. if ((isBetter) && (ambiguityContext != NULL))
  17288. {
  17289. ambiguityContext->Remove(virtualMethodMatchIdx);
  17290. }
  17291. doOverride = isBetter;
  17292. }
  17293. }
  17294. if (doOverride)
  17295. {
  17296. auto declMethodInstance = (BfMethodInstance*)typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mDeclaringMethod;
  17297. _AddVirtualDecl(declMethodInstance);
  17298. typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mImplementingMethod = setMethodInstance;
  17299. }
  17300. }
  17301. }
  17302. if (methodOverriden != NULL)
  17303. {
  17304. auto prevProtection = methodOverriden->mMethodDef->mProtection;
  17305. if ((methodDef->mProtection != prevProtection) && (methodDef->mMethodType != BfMethodType_Dtor))
  17306. {
  17307. const char* protectionNames[] = {"hidden", "private", "protected", "public"};
  17308. BfAstNode* protectionRefNode = NULL;
  17309. if (auto propertyMethodDeclaration = methodDef->GetPropertyMethodDeclaration())
  17310. {
  17311. protectionRefNode = propertyMethodDeclaration->mProtectionSpecifier;
  17312. if (protectionRefNode == NULL)
  17313. protectionRefNode = propertyMethodDeclaration->mPropertyDeclaration->mProtectionSpecifier;
  17314. if (protectionRefNode == NULL)
  17315. protectionRefNode = propertyMethodDeclaration->mPropertyDeclaration->mNameNode;
  17316. }
  17317. else if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  17318. {
  17319. protectionRefNode = methodDeclaration->mProtectionSpecifier;
  17320. if (protectionRefNode == NULL)
  17321. protectionRefNode = methodDeclaration->mNameNode;
  17322. }
  17323. if (protectionRefNode != NULL)
  17324. Fail(StrFormat("Cannot change access modifiers when overriding '%s' inherited member", protectionNames[(int)prevProtection]), protectionRefNode, true);
  17325. }
  17326. }
  17327. }
  17328. }
  17329. if ((virtualMethodMatchIdx == -1) && ((ambiguityContext == NULL) || (!ambiguityContext->mIsReslotting)))
  17330. {
  17331. if (methodDef->mIsOverride)
  17332. {
  17333. BfTokenNode* overrideToken = NULL;
  17334. if (auto propertyMethodDeclaration = methodDef->GetPropertyMethodDeclaration())
  17335. overrideToken = propertyMethodDeclaration->mPropertyDeclaration->mVirtualSpecifier;
  17336. else if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  17337. overrideToken = methodDeclaration->mVirtualSpecifier;
  17338. if (overrideToken != NULL)
  17339. {
  17340. if ((propertyDeclaration != NULL) && (propertyDeclaration->mNameNode != NULL) &&
  17341. ((methodDef->mMethodType == BfMethodType_PropertyGetter) || (methodDef->mMethodType == BfMethodType_PropertySetter)))
  17342. Fail(StrFormat("No suitable method found to override for '%s.%s'",
  17343. propertyDeclaration->mNameNode->ToString().c_str(), (methodDef->mMethodType == BfMethodType_PropertyGetter) ? "get" : "set"), overrideToken, true);
  17344. else
  17345. Fail("No suitable method found to override", overrideToken, true);
  17346. }
  17347. return usedMethod;
  17348. }
  17349. UniqueSlotVirtualMethod(methodInstance);
  17350. }
  17351. else
  17352. usedMethod = true;
  17353. if (typeInstance->IsValueType())
  17354. return usedMethod;
  17355. }
  17356. bool foundInterface = false;
  17357. bool hadAnyMatch = false;
  17358. // See if this method matches interfaces
  17359. for (auto& ifaceTypeInst : typeInstance->mInterfaces)
  17360. {
  17361. auto ifaceInst = ifaceTypeInst.mInterfaceType;
  17362. if (ifaceInst->IsIncomplete())
  17363. PopulateType(ifaceInst, BfPopulateType_DataAndMethods);
  17364. int startIdx = ifaceTypeInst.mStartInterfaceTableIdx;
  17365. int iMethodCount = (int)ifaceInst->mMethodInstanceGroups.size();
  17366. // See "bidirectional" rules mentioned in DoTypeInstanceMethodProcessing
  17367. if ((!typeInstance->IsTypeMemberAccessible(methodDef->mDeclaringType, ifaceTypeInst.mDeclaringType)) &&
  17368. (!typeInstance->IsTypeMemberAccessible(ifaceTypeInst.mDeclaringType, methodDef->mDeclaringType)))
  17369. continue;
  17370. if (!typeInstance->IsTypeMemberIncluded(methodDef->mDeclaringType, ifaceTypeInst.mDeclaringType, this))
  17371. continue;
  17372. bool hadMatch = false;
  17373. bool hadNameMatch = false;
  17374. BfType* expectedReturnType = NULL;
  17375. bool showedError = false;
  17376. // We go through our VTable looking for NULL entries within the interface sections
  17377. // The only instance of finding a "better" method is when we have explicitly interface-dotted method
  17378. // because a normal method declared in this type could have matched earlier
  17379. //for (int iMethodIdx = 0; iMethodIdx < iMethodCount; iMethodIdx++)
  17380. ifaceInst->mTypeDef->PopulateMemberSets();
  17381. BfMethodDef* checkMethodDef = NULL;
  17382. BfMemberSetEntry* entry;
  17383. if (ifaceInst->mTypeDef->mMethodSet.TryGetWith(methodInstance->mMethodDef->mName, &entry))
  17384. checkMethodDef = (BfMethodDef*)entry->mMemberDef;
  17385. while (checkMethodDef != NULL)
  17386. {
  17387. int iMethodIdx = checkMethodDef->mIdx;
  17388. int iTableIdx = iMethodIdx + startIdx;
  17389. BfTypeInterfaceMethodEntry* interfaceMethodEntry = &typeInstance->mInterfaceMethodTable[iTableIdx];
  17390. auto iMethodPtr = &interfaceMethodEntry->mMethodRef;
  17391. bool storeIFaceMethod = false;
  17392. if ((mCompiler->mPassInstance->HasFailed()) && (iMethodIdx >= (int)ifaceInst->mMethodInstanceGroups.size()))
  17393. continue;
  17394. auto& iMethodGroup = ifaceInst->mMethodInstanceGroups[iMethodIdx];
  17395. auto iMethodInst = iMethodGroup.mDefault;
  17396. if (iMethodInst == NULL)
  17397. {
  17398. if ((!ifaceInst->IsGenericTypeInstance()) || (!ifaceInst->mTypeDef->mIsCombinedPartial))
  17399. AssertErrorState();
  17400. continue;
  17401. }
  17402. if (iMethodInst->mMethodDef->mName == methodInstance->mMethodDef->mName)
  17403. hadNameMatch = true;
  17404. bool doesMethodSignatureMatch = CompareMethodSignatures(iMethodInst, methodInstance);
  17405. if ((!doesMethodSignatureMatch) && (iMethodInst->GetNumGenericParams() == 0) && (interfaceMethodEntry->mMethodRef.IsNull()))
  17406. {
  17407. doesMethodSignatureMatch = IsCompatibleInterfaceMethod(iMethodInst, methodInstance);
  17408. }
  17409. if ((doesMethodSignatureMatch) && (methodInstance->GetOwner()->IsValueType()))
  17410. {
  17411. if ((!iMethodInst->mMethodDef->mIsMutating) && (methodInstance->mMethodDef->mIsMutating))
  17412. {
  17413. if ((methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface == ifaceInst))
  17414. {
  17415. auto error = mCompiler->mPassInstance->Fail(StrFormat("Implementation method '%s' cannot specify 'mut' because the interface method does not allow it",
  17416. MethodToString(methodInstance).c_str()), methodInstance->mMethodDef->GetMutNode());
  17417. if (error != NULL)
  17418. mCompiler->mPassInstance->MoreInfo(StrFormat("Declare the interface method as 'mut' to allow matching 'mut' implementations"), iMethodInst->mMethodDef->mMethodDeclaration);
  17419. showedError = true;
  17420. }
  17421. }
  17422. }
  17423. if (doesMethodSignatureMatch)
  17424. {
  17425. usedMethod = true;
  17426. hadMatch = true;
  17427. hadAnyMatch = true;
  17428. storeIFaceMethod = true;
  17429. if ((iMethodPtr->mKind != BfMethodRefKind_AmbiguousRef) && (iMethodPtr->mTypeInstance != NULL))
  17430. {
  17431. auto prevMethod = (BfMethodInstance*)*iMethodPtr;
  17432. if ((mCompiler->mIsResolveOnly) && (prevMethod == methodInstance))
  17433. {
  17434. // When autocompletion regenerates a single method body but not the whole type then
  17435. // we will see ourselves in the vtable already
  17436. return usedMethod;
  17437. }
  17438. bool isBetter = false;
  17439. bool isWorse = false;
  17440. isBetter = (methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface != NULL);
  17441. isWorse = (prevMethod->mMethodInfoEx != NULL) && (prevMethod->mMethodInfoEx->mExplicitInterface != NULL);
  17442. if (isBetter == isWorse)
  17443. CompareDeclTypes(methodInstance->mMethodDef->mDeclaringType, prevMethod->mMethodDef->mDeclaringType, isBetter, isWorse);
  17444. if (isBetter == isWorse)
  17445. {
  17446. if (ambiguityContext != NULL)
  17447. {
  17448. ambiguityContext->Add(~iTableIdx, &ifaceTypeInst, iMethodIdx, prevMethod, methodInstance);
  17449. }
  17450. iMethodPtr->mKind = BfMethodRefKind_AmbiguousRef;
  17451. storeIFaceMethod = true;
  17452. }
  17453. else
  17454. {
  17455. if ((isBetter) && (ambiguityContext != NULL))
  17456. ambiguityContext->Remove(~iTableIdx);
  17457. storeIFaceMethod = isBetter;
  17458. }
  17459. }
  17460. }
  17461. if (storeIFaceMethod)
  17462. {
  17463. _AddVirtualDecl(iMethodInst);
  17464. *iMethodPtr = methodInstance;
  17465. }
  17466. checkMethodDef = checkMethodDef->mNextWithSameName;
  17467. }
  17468. if ((methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface == ifaceInst) && (!hadMatch) && (!showedError))
  17469. {
  17470. if (expectedReturnType != NULL)
  17471. Fail(StrFormat("Wrong return type, expected '%s'", TypeToString(expectedReturnType).c_str()), declaringNode, true);
  17472. else if (hadNameMatch)
  17473. Fail("Method parameters don't match interface method", declaringNode, true);
  17474. else
  17475. Fail("Method name not found in interface", methodDef->GetRefNode(), true);
  17476. }
  17477. }
  17478. // Any overriden virtual methods that were used in interfaces also need to be replaced
  17479. if (methodOverriden != NULL)
  17480. {
  17481. for (auto& methodEntry : typeInstance->mInterfaceMethodTable)
  17482. {
  17483. if (methodEntry.mMethodRef == methodOverriden)
  17484. methodEntry.mMethodRef = methodInstance;
  17485. }
  17486. }
  17487. return usedMethod;
  17488. }
  17489. bool BfModule::SlotInterfaceMethod(BfMethodInstance* methodInstance)
  17490. {
  17491. auto typeInstance = mCurTypeInstance;
  17492. auto methodDef = methodInstance->mMethodDef;
  17493. if (methodDef->mMethodType == BfMethodType_Ctor)
  17494. return true;
  17495. bool foundOverride = false;
  17496. if ((methodDef->mBody == NULL) && (methodDef->mProtection == BfProtection_Private))
  17497. {
  17498. Fail("Private interface methods must provide a body", methodDef->GetMethodDeclaration()->mProtectionSpecifier);
  17499. }
  17500. if ((methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface != NULL) && (!methodDef->mIsOverride))
  17501. {
  17502. Fail("Explicit interfaces can only be specified for overrides in interface declarations", methodDef->GetMethodDeclaration()->mExplicitInterface);
  17503. }
  17504. BfAstNode* declaringNode = methodDef->GetRefNode();
  17505. for (auto& ifaceTypeInst : typeInstance->mInterfaces)
  17506. {
  17507. auto ifaceInst = ifaceTypeInst.mInterfaceType;
  17508. int startIdx = ifaceTypeInst.mStartInterfaceTableIdx;
  17509. int iMethodCount = (int)ifaceInst->mMethodInstanceGroups.size();
  17510. if ((methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface != ifaceInst))
  17511. continue;
  17512. ifaceInst->mTypeDef->PopulateMemberSets();
  17513. BfMethodDef* nextMethod = NULL;
  17514. BfMemberSetEntry* entry = NULL;
  17515. if (ifaceInst->mTypeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  17516. nextMethod = (BfMethodDef*)entry->mMemberDef;
  17517. while (nextMethod != NULL)
  17518. {
  17519. auto checkMethod = nextMethod;
  17520. nextMethod = nextMethod->mNextWithSameName;
  17521. auto ifaceMethod = ifaceInst->mMethodInstanceGroups[checkMethod->mIdx].mDefault;
  17522. if (ifaceMethod == NULL)
  17523. continue;
  17524. if (CompareMethodSignatures(ifaceMethod, methodInstance))
  17525. {
  17526. if (methodDef->mIsOverride)
  17527. {
  17528. if (ifaceMethod->mMethodDef->mProtection == BfProtection_Private)
  17529. {
  17530. auto error = Fail(StrFormat("Interface method '%s' cannot override private interface method '%s'", MethodToString(methodInstance).c_str(), MethodToString(ifaceMethod).c_str()), declaringNode);
  17531. if (error != NULL)
  17532. {
  17533. mCompiler->mPassInstance->MoreInfo("See base interface method", ifaceMethod->mMethodDef->GetRefNode());
  17534. }
  17535. }
  17536. foundOverride = true;
  17537. }
  17538. else if (!methodDef->mIsNew)
  17539. {
  17540. Warn(BfWarning_CS0114_MethodHidesInherited, StrFormat("Method hides inherited member from '%s'. Use the 'new' keyword if hiding was intentional.", TypeToString(ifaceInst).c_str()), declaringNode);
  17541. }
  17542. }
  17543. }
  17544. }
  17545. if ((methodDef->mIsOverride) && (!foundOverride))
  17546. {
  17547. // This allows us to declare a method in the base definition or in an extension and then provide
  17548. // an implementation in a more-specific extension
  17549. typeInstance->mTypeDef->PopulateMemberSets();
  17550. BfMethodDef* nextMethod = NULL;
  17551. BfMemberSetEntry* entry = NULL;
  17552. if (typeInstance->mTypeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  17553. nextMethod = (BfMethodDef*)entry->mMemberDef;
  17554. while (nextMethod != NULL)
  17555. {
  17556. auto checkMethod = nextMethod;
  17557. nextMethod = nextMethod->mNextWithSameName;
  17558. auto ifaceMethod = typeInstance->mMethodInstanceGroups[checkMethod->mIdx].mDefault;
  17559. if (ifaceMethod == NULL)
  17560. continue;
  17561. if (ifaceMethod->mMethodDef->mDeclaringType == methodInstance->mMethodDef->mDeclaringType)
  17562. continue;
  17563. if (CompareMethodSignatures(ifaceMethod, methodInstance))
  17564. {
  17565. foundOverride = true;
  17566. }
  17567. }
  17568. // for (int methodIdx = 0; methodIdx < typeInstance->mMethodInstanceGroups.size(); methodIdx++)
  17569. // {
  17570. // auto ifaceMethod = typeInstance->mMethodInstanceGroups[methodIdx].mDefault;
  17571. // if (ifaceMethod == NULL)
  17572. // continue;
  17573. // if (ifaceMethod->mMethodDef->mDeclaringType == methodInstance->mMethodDef->mDeclaringType)
  17574. // continue;
  17575. //
  17576. // if (CompareMethodSignatures(ifaceMethod, methodInstance))
  17577. // {
  17578. // foundOverride = true;
  17579. // }
  17580. // }
  17581. }
  17582. if (methodDef->mIsOverride)
  17583. {
  17584. if (!foundOverride)
  17585. {
  17586. BfTokenNode* overrideToken = NULL;
  17587. if (auto propertyDeclaration = methodDef->GetPropertyDeclaration())
  17588. overrideToken = propertyDeclaration->mVirtualSpecifier;
  17589. else if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  17590. overrideToken = methodDeclaration->mVirtualSpecifier;
  17591. if (overrideToken != NULL)
  17592. {
  17593. Fail("No suitable method found to override", overrideToken, true);
  17594. }
  17595. else
  17596. {
  17597. // Possible cause - DTOR with params
  17598. AssertErrorState();
  17599. }
  17600. }
  17601. return true;
  17602. }
  17603. // Generic methods can't be called virtually
  17604. if (methodInstance->GetNumGenericParams() != 0)
  17605. return true;
  17606. // Only public methods can be called virtually
  17607. if (methodDef->mProtection != BfProtection_Public)
  17608. return true;
  17609. UniqueSlotVirtualMethod(methodInstance);
  17610. return true;
  17611. }
  17612. void BfModule::DbgFinish()
  17613. {
  17614. if ((mBfIRBuilder == NULL) || (mExtensionCount != 0))
  17615. return;
  17616. if (mAwaitingInitFinish)
  17617. FinishInit();
  17618. if (mHasForceLinkMarker)
  17619. return;
  17620. String markerName;
  17621. BfIRValue linkMarker;
  17622. if (mBfIRBuilder->DbgHasInfo())
  17623. {
  17624. bool needForceLinking = false;
  17625. for (auto& ownedType : mOwnedTypeInstances)
  17626. {
  17627. bool hasConfirmedReference = false;
  17628. for (auto& methodInstGroup : ownedType->mMethodInstanceGroups)
  17629. {
  17630. if ((methodInstGroup.IsImplemented()) && (methodInstGroup.mDefault != NULL) &&
  17631. (!methodInstGroup.mDefault->mMethodDef->mIsStatic) && (methodInstGroup.mDefault->mIsReified) &&
  17632. ((methodInstGroup.mOnDemandKind == BfMethodOnDemandKind_AlwaysInclude) || (methodInstGroup.mOnDemandKind == BfMethodOnDemandKind_Referenced)))
  17633. {
  17634. hasConfirmedReference = true;
  17635. }
  17636. }
  17637. if ((!hasConfirmedReference) || (ownedType->IsBoxed()))
  17638. needForceLinking = true;
  17639. }
  17640. if ((needForceLinking) && (mProject->mCodeGenOptions.mAsmKind == BfAsmKind_None))
  17641. {
  17642. BfMethodState methodState;
  17643. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  17644. methodState.mTempKind = BfMethodState::TempKind_Static;
  17645. mHasForceLinkMarker = true;
  17646. auto voidType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_None));
  17647. SizedArray<BfIRType, 0> paramTypes;
  17648. BfIRFunctionType funcType = mBfIRBuilder->CreateFunctionType(voidType, paramTypes);
  17649. String linkName = "FORCELINKMOD_" + mModuleName;
  17650. BfIRFunction func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, linkName);
  17651. mBfIRBuilder->SetActiveFunction(func);
  17652. auto entryBlock = mBfIRBuilder->CreateBlock("main", true);
  17653. mBfIRBuilder->SetInsertPoint(entryBlock);
  17654. auto firstType = mOwnedTypeInstances[0];
  17655. UpdateSrcPos(mContext->mBfObjectType->mTypeDef->GetRefNode());
  17656. SizedArray<BfIRMDNode, 1> diParamTypes;
  17657. diParamTypes.Add(mBfIRBuilder->DbgGetType(GetPrimitiveType(BfTypeCode_None)));
  17658. BfIRMDNode diFuncType = mBfIRBuilder->DbgCreateSubroutineType(diParamTypes);
  17659. auto diScope = mBfIRBuilder->DbgCreateFunction(mDICompileUnit, "FORCELINKMOD", linkName, mCurFilePosition.mFileInstance->mDIFile,
  17660. mCurFilePosition.mCurLine + 1, diFuncType, false, true, mCurFilePosition.mCurLine + 1, 0, false, func);
  17661. methodState.mCurScope->mDIScope = diScope;
  17662. UpdateSrcPos(mContext->mBfObjectType->mTypeDef->GetRefNode(), BfSrcPosFlag_Force);
  17663. SizedArray<BfIRValue, 8> args;
  17664. BfExprEvaluator exprEvaluator(this);
  17665. for (auto& ownedType : mOwnedTypeInstances)
  17666. {
  17667. auto alloca = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_Int8)));
  17668. auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(diScope, "variable", mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, mBfIRBuilder->DbgGetType(ownedType));
  17669. mBfIRBuilder->DbgInsertDeclare(alloca, diVariable);
  17670. }
  17671. mBfIRBuilder->CreateRetVoid();
  17672. mBfIRBuilder->SetActiveFunction(BfIRFunction());
  17673. }
  17674. }
  17675. }
  17676. bool BfModule::Finish()
  17677. {
  17678. BP_ZONE("BfModule::Finish");
  17679. BfLogSysM("BfModule finish: %p\n", this);
  17680. if (mHadBuildError)
  17681. {
  17682. // Don't AssertErrorState here, this current pass may not have failed but
  17683. // the module was still queued in mFinishedModuleWorkList
  17684. ClearModule();
  17685. return true;
  17686. }
  17687. if (mUsedSlotCount != -1)
  17688. {
  17689. BF_ASSERT(mCompiler->mMaxInterfaceSlots != -1);
  17690. mUsedSlotCount = mCompiler->mMaxInterfaceSlots;
  17691. }
  17692. BF_ASSERT(mAddedToCount);
  17693. mAddedToCount = false;
  17694. mAwaitingFinish = false;
  17695. mCompiler->mStats.mModulesFinished++;
  17696. if (HasCompiledOutput())
  17697. {
  17698. DbgFinish();
  17699. if (mAwaitingInitFinish)
  17700. FinishInit();
  17701. for (auto ownedTypeInst : mOwnedTypeInstances)
  17702. {
  17703. // Generate dbg info and add global variables if we haven't already
  17704. mBfIRBuilder->PopulateType(ownedTypeInst);
  17705. }
  17706. if (mBfIRBuilder->DbgHasInfo())
  17707. {
  17708. mBfIRBuilder->DbgFinalize();
  17709. }
  17710. String objOutputPath;
  17711. String irOutputPath;
  17712. mIsModuleMutable = false;
  17713. //mOutFileNames.Clear();
  17714. BF_ASSERT((int)mOutFileNames.size() >= mExtensionCount);
  17715. bool writeModule = mBfIRBuilder->HasExports();
  17716. String outputPath;
  17717. BfCodeGenOptions codeGenOptions = mProject->mCodeGenOptions;
  17718. auto& compilerOpts = mCompiler->mOptions;
  17719. codeGenOptions.mSIMDSetting = compilerOpts.mSIMDSetting;
  17720. auto moduleOptions = GetModuleOptions();
  17721. codeGenOptions.mOptLevel = moduleOptions.mOptLevel;
  17722. codeGenOptions.mSIMDSetting = moduleOptions.mSIMDSetting;
  17723. codeGenOptions.mWriteLLVMIR = mCompiler->mOptions.mWriteIR;
  17724. codeGenOptions.mWriteObj = mCompiler->mOptions.mGenerateObj;
  17725. codeGenOptions.mVirtualMethodOfs = 1 + mCompiler->GetDynCastVDataCount() + mCompiler->mMaxInterfaceSlots;
  17726. codeGenOptions.mDynSlotOfs = mSystem->mPtrSize - mCompiler->GetDynCastVDataCount() * 4;
  17727. mCompiler->mStats.mIRBytes += mBfIRBuilder->mStream.GetSize();
  17728. mCompiler->mStats.mConstBytes += mBfIRBuilder->mTempAlloc.GetAllocSize();
  17729. bool allowWriteToLib = true;
  17730. if ((allowWriteToLib) && (codeGenOptions.mOptLevel == BfOptLevel_OgPlus) && (mModuleName != "vdata"))
  17731. {
  17732. codeGenOptions.mWriteToLib = true;
  17733. mWroteToLib = true;
  17734. }
  17735. else
  17736. {
  17737. mWroteToLib = false;
  17738. }
  17739. for (int fileIdx = 0; fileIdx <= mExtensionCount; fileIdx++)
  17740. {
  17741. outputPath = mModuleName;
  17742. outputPath = mCompiler->mOutputDirectory + "/" + mProject->mName + "/" + outputPath;
  17743. BfModuleFileName moduleFileName;
  17744. if (mParentModule != NULL)
  17745. {
  17746. for (auto&& checkPair : mParentModule->mSpecializedMethodModules)
  17747. {
  17748. if (checkPair.mValue == this)
  17749. moduleFileName.mProjects = checkPair.mKey;
  17750. }
  17751. }
  17752. moduleFileName.mProjects.Add(mProject);
  17753. if (fileIdx > 0)
  17754. outputPath += StrFormat("@%d", fileIdx + 1);
  17755. if (mCompiler->mOptions.mWriteIR)
  17756. irOutputPath = outputPath + ".ll";
  17757. if (mCompiler->mOptions.mGenerateObj)
  17758. {
  17759. objOutputPath = outputPath + BF_OBJ_EXT;
  17760. moduleFileName.mFileName = objOutputPath;
  17761. }
  17762. else if (mCompiler->mOptions.mWriteIR)
  17763. {
  17764. moduleFileName.mFileName = irOutputPath;
  17765. }
  17766. else if ((!mCompiler->mOptions.mGenerateObj) && (!mCompiler->mOptions.mWriteIR))
  17767. {
  17768. BF_FATAL("Neither obj nor IR specified");
  17769. }
  17770. moduleFileName.mModuleWritten = writeModule;
  17771. moduleFileName.mWroteToLib = mWroteToLib;
  17772. if (!mOutFileNames.Contains(moduleFileName))
  17773. mOutFileNames.Add(moduleFileName);
  17774. }
  17775. if (mCompiler->IsHotCompile())
  17776. {
  17777. codeGenOptions.mIsHotCompile = true;
  17778. //TODO: Why did we have this 'mWroteToLib' check? 'vdata' didn't get this flag set, which
  17779. // is required for rebuilding vdata after we hot create a vdata
  17780. //if (mWroteToLib)
  17781. {
  17782. if (mParentModule != NULL)
  17783. mParentModule->mHadHotObjectWrites = true;
  17784. mHadHotObjectWrites = true;
  17785. }
  17786. }
  17787. //TODO: Testing VDATA
  17788. /*if (mModuleName == "vdata")
  17789. {
  17790. codeGenOptions.mOptLevel = 4;
  17791. }*/
  17792. codeGenOptions.GenerateHash();
  17793. BP_ZONE("BfModule::Finish.WriteObjectFile");
  17794. if ((writeModule) && (!mBfIRBuilder->mIgnoreWrites))
  17795. mCompiler->mCodeGen.WriteObjectFile(this, outputPath, codeGenOptions);
  17796. mLastModuleWrittenRevision = mCompiler->mRevision;
  17797. }
  17798. else
  17799. {
  17800. for (auto type : mOwnedTypeInstances)
  17801. {
  17802. BF_ASSERT(!type->IsIncomplete());
  17803. }
  17804. }
  17805. for (auto& specModulePair : mSpecializedMethodModules)
  17806. {
  17807. auto specModule = specModulePair.mValue;
  17808. if ((specModule->mIsModuleMutable) && (!specModule->mAwaitingFinish))
  17809. {
  17810. BfLogSysM(" Mutable spec module remaining: %p\n", specModule);
  17811. }
  17812. }
  17813. CleanupFileInstances();
  17814. // We can't ClearModuleData here because we need the mSpecializedMethodModules to remain valid until we Finish them too
  17815. return true;
  17816. }
  17817. void BfModule::ReportMemory(MemReporter* memReporter)
  17818. {
  17819. memReporter->Add(sizeof(BfModule));
  17820. if (mBfIRBuilder != NULL)
  17821. {
  17822. memReporter->BeginSection("IRBuilder_ConstData");
  17823. memReporter->Add("Used", mBfIRBuilder->mTempAlloc.GetAllocSize());
  17824. memReporter->Add("Unused", mBfIRBuilder->mTempAlloc.GetTotalAllocSize() - mBfIRBuilder->mTempAlloc.GetAllocSize());
  17825. memReporter->EndSection();
  17826. memReporter->BeginSection("IRBuilder_BFIR");
  17827. memReporter->Add("Used", (int)(mBfIRBuilder->mStream.GetSize()));
  17828. memReporter->Add("Unused", (int)(mBfIRBuilder->mStream.mPools.size() * ChunkedDataBuffer::ALLOC_SIZE) - mBfIRBuilder->mStream.GetSize());
  17829. memReporter->EndSection();
  17830. memReporter->Add(sizeof(BfIRBuilder));
  17831. }
  17832. memReporter->BeginSection("FileInstanceMap");
  17833. memReporter->AddMap(mFileInstanceMap);
  17834. memReporter->AddMap(mNamedFileInstanceMap);
  17835. memReporter->Add((int)mNamedFileInstanceMap.size() * sizeof(BfFileInstance));
  17836. memReporter->EndSection();
  17837. memReporter->AddVec(mOwnedTypeInstances, false);
  17838. memReporter->AddVec(mSpecializedMethodModules, false);
  17839. memReporter->AddVec(mOutFileNames, false);
  17840. memReporter->AddMap("FuncReferences", mFuncReferences, false);
  17841. memReporter->AddMap(mInterfaceSlotRefs, false);
  17842. memReporter->AddMap(mStaticFieldRefs, false);
  17843. memReporter->AddMap(mClassVDataRefs, false);
  17844. memReporter->AddMap("VDataExtMap", mClassVDataExtRefs, false);
  17845. memReporter->AddMap(mTypeDataRefs, false);
  17846. memReporter->AddMap(mDbgRawAllocDataRefs, false);
  17847. memReporter->AddMap(mDeferredMethodCallData, false);
  17848. memReporter->AddHashSet(mDeferredMethodIds, false);
  17849. memReporter->AddHashSet("ModuleRefs", mModuleRefs, false);
  17850. }
  17851. // ClearModuleData is called immediately after the module is compiled, so don't clear out any data that needs to
  17852. // be transient through the next compile
  17853. void BfModule::ClearModuleData()
  17854. {
  17855. BfLogSysM("ClearModuleData %p\n", this);
  17856. if (mAddedToCount)
  17857. {
  17858. mCompiler->mStats.mModulesFinished++;
  17859. mAddedToCount = false;
  17860. }
  17861. mDICompileUnit = BfIRMDNode();
  17862. mIsModuleMutable = false;
  17863. mIncompleteMethodCount = 0;
  17864. mHasGenericMethods = false;
  17865. // We don't want to clear these because we want it to persist through module extensions-
  17866. // otherwise we may think an extension succeeds even though the base module failed
  17867. //mHadBuildError = false;
  17868. //mHadBuildWarning = false;
  17869. mClassVDataRefs.Clear();
  17870. mClassVDataExtRefs.Clear();
  17871. for (auto& kv : mTypeDataRefs)
  17872. kv.mValue = BfIRValue();
  17873. mStringCharPtrPool.Clear();
  17874. mStringObjectPool.Clear();
  17875. mStaticFieldRefs.Clear();
  17876. BF_ASSERT(!mIgnoreErrors);
  17877. for (auto prevIRBuilder : mPrevIRBuilders)
  17878. delete prevIRBuilder;
  17879. mPrevIRBuilders.Clear();
  17880. for (auto& specPair : mSpecializedMethodModules)
  17881. {
  17882. auto specModule = specPair.mValue;
  17883. specModule->ClearModuleData();
  17884. }
  17885. for (int i = 0; i < BfBuiltInFuncType_Count; i++)
  17886. mBuiltInFuncs[i] = BfIRFunction();
  17887. if (mNextAltModule != NULL)
  17888. mNextAltModule->ClearModuleData();
  17889. BfLogSysM("ClearModuleData. Deleting IRBuilder: %p\n", mBfIRBuilder);
  17890. delete mBfIRBuilder;
  17891. mBfIRBuilder = NULL;
  17892. mWantsIRIgnoreWrites = false;
  17893. }
  17894. void BfModule::DisownMethods()
  17895. {
  17896. for (int i = 0; i < BfBuiltInFuncType_Count; i++)
  17897. mBuiltInFuncs[i] = BfIRFunction();
  17898. BfModule* methodModule = this;
  17899. if (mParentModule != NULL)
  17900. methodModule = mParentModule;
  17901. for (auto typeInst : methodModule->mOwnedTypeInstances)
  17902. {
  17903. for (auto& methodGroup : typeInst->mMethodInstanceGroups)
  17904. {
  17905. if (methodGroup.mDefault != NULL)
  17906. {
  17907. if (methodGroup.mDefault->mIRFunction)
  17908. {
  17909. BF_ASSERT(methodGroup.mDefault->mDeclModule != NULL);
  17910. if (methodGroup.mDefault->mDeclModule == this)
  17911. {
  17912. methodGroup.mDefault->mIRFunction = BfIRFunction();
  17913. }
  17914. }
  17915. }
  17916. if (methodGroup.mMethodSpecializationMap != NULL)
  17917. {
  17918. for (auto& mapPair : *methodGroup.mMethodSpecializationMap)
  17919. {
  17920. auto methodInstance = mapPair.mValue;
  17921. if (methodInstance->mDeclModule == this)
  17922. {
  17923. methodInstance->mIRFunction = BfIRFunction();
  17924. }
  17925. }
  17926. }
  17927. }
  17928. }
  17929. }
  17930. void BfModule::ClearModule()
  17931. {
  17932. ClearModuleData();
  17933. DisownMethods();
  17934. for (auto& specPair : mSpecializedMethodModules)
  17935. {
  17936. auto specModule = specPair.mValue;
  17937. specModule->ClearModule();
  17938. }
  17939. if (mNextAltModule != NULL)
  17940. mNextAltModule->ClearModule();
  17941. }