BfContext.cpp 95 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164
  1. #pragma warning(push)
  2. #pragma warning(disable:4800)
  3. #pragma warning(disable:4244)
  4. #pragma warning(disable:4141)
  5. #pragma warning(disable:4624)
  6. #pragma warning(disable:4146)
  7. #pragma warning(disable:4267)
  8. #pragma warning(disable:4291)
  9. #include "BfCompiler.h"
  10. #include "BfSystem.h"
  11. #include "BfParser.h"
  12. #include "BfExprEvaluator.h"
  13. #include "llvm/IR/Function.h"
  14. #include "llvm/IR/Module.h"
  15. #include "llvm/IR/BasicBlock.h"
  16. #include "llvm/Support/FileSystem.h"
  17. //#include "llvm/Support/Dwarf.h"
  18. #include "llvm/ADT/SparseSet.h"
  19. #include "llvm/Transforms/Utils/Cloning.h"
  20. #include <fcntl.h>
  21. #include "BfConstResolver.h"
  22. #include "BfMangler.h"
  23. #include "BeefySysLib/util/PerfTimer.h"
  24. #include "BeefySysLib/util/BeefPerf.h"
  25. #include "BfSourceClassifier.h"
  26. #include "BfAutoComplete.h"
  27. #include "BfResolvePass.h"
  28. #include "CeMachine.h"
  29. #pragma warning(pop)
  30. USING_NS_BF;
  31. using namespace llvm;
  32. BfContext::BfContext(BfCompiler* compiler) :
  33. mTypeDefTypeRefPool(true),
  34. mNamedTypeRefPool(true)
  35. {
  36. mCompiler = compiler;
  37. mSystem = compiler->mSystem;
  38. mBfTypeType = NULL;
  39. mBfClassVDataPtrType = NULL;
  40. mBfObjectType = NULL;
  41. mCanSkipObjectCtor = true;
  42. mCanSkipValueTypeCtor = true;
  43. mMappedObjectRevision = 0;
  44. mDeleting = false;
  45. mLockModules = false;
  46. mAllowLockYield = true;
  47. mCurTypeState = NULL;
  48. mCurNamespaceNodes = NULL;
  49. mCurConstraintState = NULL;
  50. mResolvingVarField = false;
  51. mAssertOnPopulateType = false;
  52. for (int i = 0; i < BfTypeCode_Length; i++)
  53. {
  54. mPrimitiveTypes[i] = NULL;
  55. mPrimitiveStructTypes[i] = NULL;
  56. }
  57. mScratchModule = new BfModule(this, "");
  58. mScratchModule->mIsSpecialModule = true;
  59. mScratchModule->mIsScratchModule = true;
  60. mScratchModule->mIsReified = true;
  61. mScratchModule->mGeneratesCode = false;
  62. mScratchModule->Init();
  63. mUnreifiedModule = new BfModule(this, "");
  64. mUnreifiedModule->mIsSpecialModule = true;
  65. mUnreifiedModule->mIsScratchModule = true;
  66. mUnreifiedModule->mIsReified = false;
  67. mUnreifiedModule->mGeneratesCode = false;
  68. mUnreifiedModule->Init();
  69. mValueTypeDeinitSentinel = (BfMethodInstance*)1;
  70. mCurStringObjectPoolId = 0;
  71. }
  72. void BfReportMemory();
  73. BfContext::~BfContext()
  74. {
  75. BfLogSysM("Deleting Context...\n");
  76. mDeleting = true;
  77. for (auto& kv : mSavedTypeDataMap)
  78. delete kv.mValue;
  79. for (auto localMethod : mLocalMethodGraveyard)
  80. delete localMethod;
  81. int numTypesDeleted = 0;
  82. for (auto type : mResolvedTypes)
  83. {
  84. //_CrtCheckMemory();
  85. delete type;
  86. }
  87. delete mScratchModule;
  88. delete mUnreifiedModule;
  89. for (auto module : mModules)
  90. delete module;
  91. BfReportMemory();
  92. }
  93. void BfContext::ReportMemory(MemReporter* memReporter)
  94. {
  95. memReporter->Add(sizeof(BfContext));
  96. }
  97. void BfContext::ProcessMethod(BfMethodInstance* methodInstance)
  98. {
  99. // When we are doing as resolveOnly pass over unused methods in the compiler,
  100. // we use the scratch module to ensure mIsResolveOnly flag is set when we
  101. // process the method
  102. auto defModule = methodInstance->mDeclModule;
  103. if ((!methodInstance->mIsReified) && (!mCompiler->mIsResolveOnly))
  104. defModule = mUnreifiedModule;
  105. auto typeInst = methodInstance->GetOwner();
  106. defModule->ProcessMethod(methodInstance);
  107. mCompiler->mStats.mMethodsProcessed++;
  108. if (!methodInstance->mIsReified)
  109. mCompiler->mStats.mUnreifiedMethodsProcessed++;
  110. mCompiler->UpdateCompletion();
  111. }
  112. int BfContext::GetStringLiteralId(const StringImpl& str)
  113. {
  114. // Note: We do need string pooling in resolve, for intrinsic names and such
  115. int* idPtr = NULL;
  116. if (mStringObjectPool.TryGetValue(str, &idPtr))
  117. return *idPtr;
  118. mCurStringObjectPoolId++;
  119. mStringObjectPool[str] = mCurStringObjectPoolId;
  120. BfStringPoolEntry stringPoolEntry;
  121. stringPoolEntry.mString = str;
  122. stringPoolEntry.mFirstUsedRevision = mCompiler->mRevision;
  123. stringPoolEntry.mLastUsedRevision = mCompiler->mRevision;
  124. mStringObjectIdMap[mCurStringObjectPoolId] = stringPoolEntry;
  125. return mCurStringObjectPoolId;
  126. }
  127. void BfContext::AssignModule(BfType* type)
  128. {
  129. auto typeInst = type->ToTypeInstance();
  130. if (typeInst->mModule != NULL)
  131. {
  132. BF_ASSERT(!typeInst->mModule->mIsReified);
  133. }
  134. BfModule* module = NULL;
  135. bool needsModuleInit = false;
  136. // We used to have this "IsReified" check, but we DO want to create modules for unreified types even if they remain unused.
  137. // What was that IsReified check catching?
  138. // It screwed up the reification of generic types- they just got switched to mScratchModule from mUnreifiedModule, but didn't ever generate code.
  139. if (/*(!type->IsReified()) ||*/ (type->IsUnspecializedType()) || (type->IsVar()) || (type->IsTypeAlias()) || (type->IsFunction()))
  140. {
  141. if (typeInst->mIsReified)
  142. module = mScratchModule;
  143. else
  144. module = mUnreifiedModule;
  145. typeInst->mModule = module;
  146. BfTypeProcessRequest* typeProcessEntry = mPopulateTypeWorkList.Alloc();
  147. typeProcessEntry->mType = type;
  148. BF_ASSERT(typeProcessEntry->mType->mContext == this);
  149. BfLogSysM("HandleTypeWorkItem: %p -> %p\n", type, typeProcessEntry->mType);
  150. mCompiler->mStats.mTypesQueued++;
  151. mCompiler->UpdateCompletion();
  152. }
  153. else
  154. {
  155. auto typeInst = type->ToTypeInstance();
  156. BF_ASSERT(typeInst != NULL);
  157. auto project = typeInst->mTypeDef->mProject;
  158. if ((project->mSingleModule) && (typeInst->mIsReified))
  159. {
  160. BfModule** modulePtr = NULL;
  161. if (mProjectModule.TryAdd(project, NULL, &modulePtr))
  162. {
  163. String moduleName = project->mName;
  164. module = new BfModule(this, moduleName);
  165. module->mIsReified = true;
  166. module->mProject = project;
  167. typeInst->mModule = module;
  168. BF_ASSERT(!mLockModules);
  169. mModules.push_back(module);
  170. *modulePtr = module;
  171. needsModuleInit = true;
  172. }
  173. else
  174. {
  175. module = *modulePtr;
  176. typeInst->mModule = module;
  177. }
  178. }
  179. else
  180. {
  181. String moduleName = GenerateModuleName(typeInst);
  182. module = new BfModule(this, moduleName);
  183. module->mIsReified = typeInst->mIsReified;
  184. module->mProject = project;
  185. typeInst->mModule = module;
  186. BF_ASSERT(!mLockModules);
  187. mModules.push_back(module);
  188. needsModuleInit = true;
  189. }
  190. }
  191. auto localTypeInst = type->ToTypeInstance();
  192. BF_ASSERT((localTypeInst != NULL) || (mCompiler->mPassInstance->HasFailed()));
  193. if ((localTypeInst != NULL) && (!module->mIsScratchModule))
  194. {
  195. BF_ASSERT(localTypeInst->mContext == this);
  196. module->mOwnedTypeInstances.push_back(localTypeInst);
  197. }
  198. module->CalcGeneratesCode();
  199. if (needsModuleInit)
  200. module->Init();
  201. }
  202. void BfContext::HandleTypeWorkItem(BfType* type)
  203. {
  204. AssignModule(type);
  205. }
  206. void BfContext::EnsureHotMangledVirtualMethodName(BfMethodInstance* methodInstance)
  207. {
  208. BP_ZONE("BfContext::EnsureHotMangledVirtualMethodName");
  209. if ((methodInstance != NULL) && (methodInstance->GetMethodInfoEx()->mMangledName.IsEmpty()))
  210. BfMangler::Mangle(methodInstance->GetMethodInfoEx()->mMangledName, mCompiler->GetMangleKind(), methodInstance);
  211. }
  212. void BfContext::EnsureHotMangledVirtualMethodNames()
  213. {
  214. BP_ZONE("BfContext::EnsureHotMangledVirtualMethodNames");
  215. for (auto type : mResolvedTypes)
  216. {
  217. auto typeInst = type->ToTypeInstance();
  218. if (typeInst == NULL)
  219. continue;
  220. for (auto& methodEntry : typeInst->mVirtualMethodTable)
  221. {
  222. BfMethodInstance* methodInstance = methodEntry.mImplementingMethod;
  223. if ((methodInstance != NULL) && (methodInstance->GetMethodInfoEx()->mMangledName.IsEmpty()))
  224. BfMangler::Mangle(methodInstance->GetMethodInfoEx()->mMangledName, mCompiler->GetMangleKind(), methodInstance);
  225. }
  226. }
  227. }
  228. void BfContext::CheckLockYield()
  229. {
  230. if (mAllowLockYield)
  231. mSystem->CheckLockYield();
  232. }
  233. bool BfContext::IsCancellingAndYield()
  234. {
  235. CheckLockYield();
  236. return mCompiler->mCanceling;
  237. }
  238. void BfContext::QueueFinishModule(BfModule* module)
  239. {
  240. bool needsDefer = false;
  241. BF_ASSERT(module != mScratchModule);
  242. BF_ASSERT(module != mUnreifiedModule);
  243. if (mCompiler->mMaxInterfaceSlots == -1)
  244. {
  245. if (module->mUsedSlotCount == 0)
  246. needsDefer = true;
  247. else if (module->mHasFullDebugInfo)
  248. {
  249. // The virtual index for methods requires waiting
  250. for (auto ownedTypeInst : module->mOwnedTypeInstances)
  251. {
  252. if (ownedTypeInst->IsInterface())
  253. needsDefer = true;
  254. else if (ownedTypeInst->IsObject())
  255. {
  256. for (auto& methodGroup : ownedTypeInst->mMethodInstanceGroups)
  257. {
  258. auto methodInstance = methodGroup.mDefault;
  259. if (methodInstance == NULL)
  260. continue;
  261. if ((methodInstance->mVirtualTableIdx != -1) && (!methodInstance->mMethodDef->mIsOverride))
  262. needsDefer = true;
  263. }
  264. }
  265. }
  266. }
  267. }
  268. if (!needsDefer)
  269. mFinishedModuleWorkList.push_back(module);
  270. module->mAwaitingFinish = true;
  271. }
  272. // For simplicity - if we're canceling then we just rebuild modules that had certain types of pending work items
  273. void BfContext::CancelWorkItems()
  274. {
  275. /*return;
  276. BfLogSysM("BfContext::CancelWorkItems\n");
  277. for (int workIdx = 0; workIdx < (int)mMethodSpecializationWorkList.size(); workIdx++)
  278. {
  279. auto workItemRef = mMethodSpecializationWorkList[workIdx];
  280. if (workItemRef != NULL)
  281. workItemRef->mFromModule->mHadBuildError = true;
  282. workIdx = mMethodSpecializationWorkList.RemoveAt(workIdx);
  283. }
  284. mMethodSpecializationWorkList.Clear();
  285. for (int workIdx = 0; workIdx < (int)mInlineMethodWorkList.size(); workIdx++)
  286. {
  287. auto workItemRef = mInlineMethodWorkList[workIdx];
  288. if (workItemRef != NULL)
  289. workItemRef->mFromModule->mHadBuildError = true;
  290. workIdx = mInlineMethodWorkList.RemoveAt(workIdx);
  291. }
  292. mInlineMethodWorkList.Clear();
  293. for (int workIdx = 0; workIdx < (int)mMethodWorkList.size(); workIdx++)
  294. {
  295. auto workItemRef = mMethodWorkList[workIdx];
  296. if (workItemRef != NULL)
  297. workItemRef->mFromModule->mHadBuildError = true;
  298. workIdx = mMethodWorkList.RemoveAt(workIdx);
  299. }
  300. mMethodWorkList.Clear();*/
  301. }
  302. bool BfContext::ProcessWorkList(bool onlyReifiedTypes, bool onlyReifiedMethods)
  303. {
  304. bool didAnyWork = false;
  305. while (!mCompiler->mCanceling)
  306. {
  307. BfParser* resolveParser = NULL;
  308. if (mCompiler->mResolvePassData != NULL)
  309. resolveParser = mCompiler->mResolvePassData->mParser;
  310. bool didWork = false;
  311. //for (auto itr = mReifyModuleWorkList.begin(); itr != mReifyModuleWorkList.end(); )
  312. for (int workIdx = 0; workIdx < mReifyModuleWorkList.size(); workIdx++)
  313. {
  314. BP_ZONE("PWL_ReifyModule");
  315. if (IsCancellingAndYield())
  316. break;
  317. BfModule* module = mReifyModuleWorkList[workIdx];
  318. if (module == NULL)
  319. {
  320. workIdx = mReifyModuleWorkList.RemoveAt(workIdx);
  321. continue;
  322. }
  323. if (!module->mIsReified)
  324. module->ReifyModule();
  325. workIdx = mReifyModuleWorkList.RemoveAt(workIdx);
  326. didWork = true;
  327. }
  328. for (int workIdx = 0; workIdx < (int)mPopulateTypeWorkList.size(); workIdx++)
  329. {
  330. //BP_ZONE("PWL_PopulateType");
  331. if (IsCancellingAndYield())
  332. break;
  333. auto workItemRef = mPopulateTypeWorkList[workIdx];
  334. if (workItemRef == NULL)
  335. {
  336. workIdx = mPopulateTypeWorkList.RemoveAt(workIdx);
  337. continue;
  338. }
  339. BfType* type = workItemRef->mType;
  340. bool rebuildType = workItemRef->mRebuildType;
  341. if ((onlyReifiedTypes) && (!type->IsReified()))
  342. {
  343. continue;
  344. }
  345. auto typeInst = type->ToTypeInstance();
  346. if ((typeInst != NULL) && (resolveParser != NULL))
  347. {
  348. if (!typeInst->mTypeDef->GetLatest()->HasSource(resolveParser))
  349. {
  350. continue;
  351. }
  352. }
  353. workIdx = mPopulateTypeWorkList.RemoveAt(workIdx);
  354. if (rebuildType)
  355. RebuildType(type);
  356. BF_ASSERT(this == type->mContext);
  357. auto useModule = type->GetModule();
  358. if (useModule == NULL)
  359. {
  360. if (mCompiler->mOptions.mCompileOnDemandKind == BfCompileOnDemandKind_AlwaysInclude)
  361. useModule = mScratchModule;
  362. else
  363. useModule = mUnreifiedModule;
  364. }
  365. useModule->PopulateType(type, BfPopulateType_Full);
  366. mCompiler->mStats.mQueuedTypesProcessed++;
  367. mCompiler->UpdateCompletion();
  368. didWork = true;
  369. }
  370. for (int workIdx = 0; workIdx < (int)mTypeRefVerifyWorkList.size(); workIdx++)
  371. {
  372. if (IsCancellingAndYield())
  373. break;
  374. auto workItemRef = mTypeRefVerifyWorkList[workIdx];
  375. if (workItemRef == NULL)
  376. {
  377. workIdx = mTypeRefVerifyWorkList.RemoveAt(workIdx);
  378. continue;
  379. }
  380. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(workItemRef->mFromModule->mCurTypeInstance, workItemRef->mCurTypeInstance);
  381. auto refTypeInst = workItemRef->mType->ToTypeInstance();
  382. if (refTypeInst->mCustomAttributes == NULL)
  383. workItemRef->mFromModule->PopulateType(refTypeInst, BfPopulateType_AllowStaticMethods);
  384. if (refTypeInst != NULL)
  385. workItemRef->mFromModule->CheckErrorAttributes(refTypeInst, NULL, refTypeInst->mCustomAttributes, workItemRef->mRefNode);
  386. workIdx = mTypeRefVerifyWorkList.RemoveAt(workIdx);
  387. didWork = true;
  388. }
  389. //while (mMethodSpecializationWorkList.size() != 0)
  390. // For the first pass, we want to handle the reified requests first. This helps rebuilds require
  391. // fewer reifications of methods
  392. for (int methodSpecializationPass = 0; methodSpecializationPass < 2; methodSpecializationPass++)
  393. {
  394. bool wantsReified = methodSpecializationPass == 0;
  395. for (int workIdx = 0; workIdx < (int)mMethodSpecializationWorkList.size(); workIdx++)
  396. {
  397. if (IsCancellingAndYield())
  398. break;
  399. auto workItemRef = mMethodSpecializationWorkList[workIdx];
  400. if (workItemRef == NULL)
  401. {
  402. workIdx = mMethodSpecializationWorkList.RemoveAt(workIdx);
  403. continue;
  404. }
  405. if (wantsReified != workItemRef->mFromModule->mIsReified)
  406. continue;
  407. auto methodSpecializationRequest = *workItemRef;
  408. auto module = workItemRef->mFromModule;
  409. workIdx = mMethodSpecializationWorkList.RemoveAt(workIdx);
  410. auto typeInst = methodSpecializationRequest.mType->ToTypeInstance();
  411. BfMethodDef* methodDef = NULL;
  412. if (methodSpecializationRequest.mForeignType != NULL)
  413. {
  414. module->PopulateType(methodSpecializationRequest.mForeignType);
  415. methodDef = methodSpecializationRequest.mForeignType->mTypeDef->mMethods[methodSpecializationRequest.mMethodIdx];
  416. }
  417. else
  418. {
  419. module->PopulateType(typeInst);
  420. if (methodSpecializationRequest.mMethodIdx >= typeInst->mTypeDef->mMethods.mSize)
  421. continue;
  422. methodDef = typeInst->mTypeDef->mMethods[methodSpecializationRequest.mMethodIdx];
  423. }
  424. module->GetMethodInstance(typeInst, methodDef, methodSpecializationRequest.mMethodGenericArguments,
  425. (BfGetMethodInstanceFlags)(methodSpecializationRequest.mFlags | BfGetMethodInstanceFlag_ResultNotUsed), methodSpecializationRequest.mForeignType);
  426. didWork = true;
  427. }
  428. }
  429. for (int workIdx = 0; workIdx < mMethodWorkList.size(); workIdx++)
  430. {
  431. BP_ZONE("PWL_ProcessMethod");
  432. mSystem->CheckLockYield();
  433. // Don't allow canceling out of the first pass - otherwise we'll just keep reprocessing the
  434. // head of the file over and over
  435. if ((resolveParser == NULL) && (mCompiler->mCanceling))
  436. break;
  437. auto workItem = mMethodWorkList[workIdx];
  438. if (workItem == NULL)
  439. {
  440. workIdx = mMethodWorkList.RemoveAt(workIdx);
  441. continue;
  442. }
  443. intptr prevPopulateTypeWorkListSize = mPopulateTypeWorkList.size();
  444. intptr prevInlineMethodWorkListSize = mInlineMethodWorkList.size();
  445. auto module = workItem->mFromModule;
  446. auto methodInstance = workItem->mMethodInstance;
  447. bool wantProcessMethod = methodInstance != NULL;
  448. if ((workItem->mFromModuleRebuildIdx != -1) && (workItem->mFromModuleRebuildIdx != module->mRebuildIdx))
  449. wantProcessMethod = false;
  450. if (methodInstance != NULL)
  451. BF_ASSERT(methodInstance->mMethodProcessRequest == workItem);
  452. bool hasBeenProcessed = true;
  453. if (wantProcessMethod)
  454. {
  455. if ((onlyReifiedMethods) && (!methodInstance->mIsReified))
  456. {
  457. continue;
  458. }
  459. auto owner = methodInstance->mMethodInstanceGroup->mOwner;
  460. BF_ASSERT(!module->mAwaitingFinish);
  461. if ((resolveParser != NULL) && (methodInstance->mMethodDef->mDeclaringType != NULL) && (methodInstance->mMethodDef->mDeclaringType->GetDefinition()->mSource != resolveParser))
  462. {
  463. continue;
  464. }
  465. hasBeenProcessed = methodInstance->mHasBeenProcessed;
  466. BF_ASSERT(module->mContext == this);
  467. if (owner->IsIncomplete())
  468. module->PopulateType(owner, BfPopulateType_Full);
  469. if (methodInstance->mDeclModule != NULL)
  470. {
  471. if (!mCompiler->mIsResolveOnly)
  472. BF_ASSERT(!methodInstance->mIsReified || methodInstance->mDeclModule->mIsModuleMutable);
  473. ProcessMethod(methodInstance);
  474. }
  475. }
  476. workIdx = mMethodWorkList.RemoveAt(workIdx);
  477. if (methodInstance != NULL)
  478. methodInstance->mMethodProcessRequest = NULL;
  479. if ((!module->mAwaitingFinish) && (module->WantsFinishModule()))
  480. {
  481. BfLogSysM("Module finished: %p %s HadBuildErrors:%d\n", module, module->mModuleName.c_str(), module->mHadBuildError);
  482. QueueFinishModule(module);
  483. }
  484. didWork = true;
  485. }
  486. // for (int workIdx = 0; workIdx < (int)mFinishedSlotAwaitModuleWorkList.size(); workIdx++)
  487. // {
  488. // auto& moduleRef = mFinishedSlotAwaitModuleWorkList[workIdx];
  489. // if (moduleRef == NULL)
  490. // {
  491. // workIdx = mFinishedSlotAwaitModuleWorkList.RemoveAt(workIdx);
  492. // continue;
  493. // }
  494. //
  495. // auto module = moduleRef;
  496. // if (mCompiler->mMaxInterfaceSlots >= 0)
  497. // {
  498. // mFinishedModuleWorkList.Add(module);
  499. // }
  500. //
  501. // workIdx = mFinishedSlotAwaitModuleWorkList.RemoveAt(workIdx);
  502. // didWork = true;
  503. // }
  504. for (int workIdx = 0; workIdx < (int)mFinishedModuleWorkList.size(); workIdx++)
  505. {
  506. //auto module = *moduleItr;
  507. auto& moduleRef = mFinishedModuleWorkList[workIdx];
  508. if (moduleRef == NULL)
  509. {
  510. workIdx = mFinishedModuleWorkList.RemoveAt(workIdx);
  511. continue;
  512. }
  513. auto module = moduleRef;
  514. if (!module->mAwaitingFinish)
  515. {
  516. BfLogSysM("mFinishedModuleWorkList removing old:%p\n", module);
  517. workIdx = mFinishedModuleWorkList.RemoveAt(workIdx);
  518. continue;
  519. }
  520. //if (module->mAwaitingFinish)
  521. BfLogSysM("mFinishedModuleWorkList handling:%p\n", module);
  522. mSystem->CheckLockYield();
  523. if (mPopulateTypeWorkList.size() > 0)
  524. {
  525. // We can't finish modules unless all DI forward references have been replaced
  526. break;
  527. }
  528. BP_ZONE("PWL_ProcessFinishedModule");
  529. bool hasUnfinishedSpecModule = false;
  530. for (auto& specModulePair : module->mSpecializedMethodModules)
  531. {
  532. auto specModule = specModulePair.mValue;
  533. if ((specModule->mAwaitingFinish) || (specModule->mIsModuleMutable))
  534. hasUnfinishedSpecModule = true;
  535. }
  536. if (hasUnfinishedSpecModule)
  537. {
  538. continue;
  539. }
  540. if (!module->mIsSpecialModule)
  541. {
  542. module->Finish();
  543. if (mCompiler->mIsResolveOnly)
  544. module->ClearModuleData();
  545. }
  546. mCompiler->UpdateCompletion();
  547. workIdx = mFinishedModuleWorkList.RemoveAt(workIdx);
  548. didWork = true;
  549. }
  550. for (int workIdx = 0; workIdx < (int)mInlineMethodWorkList.size(); workIdx++)
  551. {
  552. BP_ZONE("PWL_ProcessMethod");
  553. mSystem->CheckLockYield();
  554. // Don't allow canceling out of the first pass - otherwise we'll just keep reprocessing the
  555. // head of the file over and over
  556. if ((resolveParser == NULL) && (mCompiler->mCanceling))
  557. break;
  558. auto workItemRef = mInlineMethodWorkList[workIdx];
  559. if (workItemRef == NULL)
  560. {
  561. workIdx = mInlineMethodWorkList.RemoveAt(workIdx);
  562. continue;
  563. }
  564. auto workItem = *workItemRef;
  565. auto owner = workItem.mMethodInstance->mMethodInstanceGroup->mOwner;
  566. auto module = workItem.mFromModule;
  567. auto methodInstance = workItem.mMethodInstance;
  568. BF_ASSERT(module->mIsModuleMutable);
  569. module->PrepareForIRWriting(methodInstance->GetOwner());
  570. workIdx = mInlineMethodWorkList.RemoveAt(workIdx);
  571. BfLogSysM("Module %p inlining method %p into func:%p\n", module, methodInstance, workItem.mFunc);
  572. BfMethodInstance dupMethodInstance;
  573. dupMethodInstance.CopyFrom(methodInstance);
  574. dupMethodInstance.mIRFunction = workItem.mFunc;
  575. dupMethodInstance.mIsReified = true;
  576. dupMethodInstance.mInCEMachine = false; // Only have the original one
  577. BF_ASSERT(module->mIsReified); // We should only bother inlining in reified modules
  578. {
  579. // These errors SHOULD be duplicates, but if we have no other errors at all then we don't ignoreErrors, which
  580. // may help unveil some kinds of compiler bugs
  581. SetAndRestoreValue<bool> prevIgnoreErrors(module->mIgnoreErrors, mCompiler->mPassInstance->HasFailed());
  582. module->ProcessMethod(&dupMethodInstance, true);
  583. }
  584. static int sMethodIdx = 0;
  585. module->mBfIRBuilder->Func_SetLinkage(workItem.mFunc, BfIRLinkageType_Internal);
  586. BF_ASSERT(module->mContext == this);
  587. BF_ASSERT(module->mIsModuleMutable);
  588. if (module->WantsFinishModule())
  589. {
  590. BfLogSysM("Module finished: %s (from inlining)\n", module->mModuleName.c_str());
  591. QueueFinishModule(module);
  592. }
  593. didWork = true;
  594. }
  595. if (!didWork)
  596. {
  597. if ((mPopulateTypeWorkList.size() == 0) && (resolveParser == NULL))
  598. {
  599. BP_ZONE("PWL_CheckIncompleteGenerics");
  600. for (auto type : mResolvedTypes)
  601. {
  602. if ((type->IsIncomplete()) && (type->HasBeenReferenced()))
  603. {
  604. // The only reason a type instance wouldn't have already been in the work list is
  605. // because it's a generic specialization that was eligible for deletion,
  606. // but it has been referenced now so we need to complete it, OR
  607. // if this is from a newly-reified module
  608. if ((type->IsSpecializedByAutoCompleteMethod()) && (type->mDefineState >= BfTypeDefineState_Defined))
  609. {
  610. // We don't process methods for these
  611. }
  612. else
  613. {
  614. BfTypeProcessRequest* typeProcessRequest = mPopulateTypeWorkList.Alloc();
  615. typeProcessRequest->mType = type;
  616. mCompiler->mStats.mTypesQueued++;
  617. mCompiler->UpdateCompletion();
  618. didWork = true;
  619. }
  620. }
  621. }
  622. }
  623. }
  624. if (!didWork)
  625. break;
  626. didAnyWork = true;
  627. }
  628. return didAnyWork;
  629. }
  630. void BfContext::HandleChangedTypeDef(BfTypeDef* typeDef, bool isAutoCompleteTempType)
  631. {
  632. BF_ASSERT(typeDef->mEmitParent == NULL);
  633. if ((mCompiler->mResolvePassData == NULL) || (!typeDef->HasSource(mCompiler->mResolvePassData->mParser)))
  634. return;
  635. if (typeDef->mDefState != BfTypeDef::DefState_Defined)
  636. {
  637. if (mCompiler->mResolvePassData->mSourceClassifier != NULL)
  638. {
  639. auto _CheckSource = [&](BfTypeDef* checkTypeDef)
  640. {
  641. auto typeDecl = checkTypeDef->mTypeDeclaration;
  642. if (checkTypeDef->mNextRevision != NULL)
  643. typeDecl = checkTypeDef->mNextRevision->mTypeDeclaration;
  644. if (typeDecl == NULL)
  645. return;
  646. if (typeDecl->GetSourceData() == mCompiler->mResolvePassData->mParser->mSourceData)
  647. {
  648. SetAndRestoreValue<bool> prevSkipTypeDeclaration(mCompiler->mResolvePassData->mSourceClassifier->mSkipTypeDeclarations, true);
  649. auto classifier = mCompiler->mResolvePassData->mSourceClassifier;
  650. classifier->mSkipMethodInternals = isAutoCompleteTempType;
  651. classifier->Handle(typeDecl);
  652. }
  653. };
  654. if (typeDef->mIsCombinedPartial)
  655. {
  656. for (auto partial : typeDef->mPartials)
  657. _CheckSource(partial);
  658. }
  659. else
  660. {
  661. _CheckSource(typeDef);
  662. }
  663. }
  664. }
  665. if ((!typeDef->mIsPartial) && (!isAutoCompleteTempType))
  666. {
  667. if ((typeDef->mDefState == BfTypeDef::DefState_New) ||
  668. (typeDef->mDefState == BfTypeDef::DefState_Deleted) ||
  669. (typeDef->mDefState == BfTypeDef::DefState_Signature_Changed))
  670. {
  671. mCompiler->mPassInstance->mHadSignatureChanges = true;
  672. }
  673. }
  674. }
  675. BfType * BfContext::FindTypeById(int typeId)
  676. {
  677. for (auto type : mResolvedTypes)
  678. {
  679. if (type->mTypeId == typeId)
  680. return type;
  681. }
  682. return NULL;
  683. }
  684. void BfContext::AddTypeToWorkList(BfType* type)
  685. {
  686. //BF_ASSERT(!mAssertOnPopulateType);
  687. BF_ASSERT((type->mRebuildFlags & BfTypeRebuildFlag_InTempPool) == 0);
  688. if ((type->mRebuildFlags & BfTypeRebuildFlag_AddedToWorkList) == 0)
  689. {
  690. type->mRebuildFlags = (BfTypeRebuildFlags)(type->mRebuildFlags | BfTypeRebuildFlag_AddedToWorkList);
  691. BfTypeProcessRequest* typeProcessRequest = mPopulateTypeWorkList.Alloc();
  692. typeProcessRequest->mType = type;
  693. mCompiler->mStats.mTypesQueued++;
  694. mCompiler->UpdateCompletion();
  695. }
  696. }
  697. void BfContext::ValidateDependencies()
  698. {
  699. #if _DEBUG
  700. // BP_ZONE("BfContext::ValidateDependencies");
  701. // BfLogSysM("ValidateDependencies\n");
  702. //
  703. // bool deletedNewTypes = false;
  704. // auto itr = mResolvedTypes.begin();
  705. // while (itr != mResolvedTypes.end())
  706. // {
  707. // auto type = itr.mCurEntry->mValue;
  708. // if ((type->IsGenericTypeInstance()) && (type->mDefineState > BfTypeDefineState_Undefined))
  709. // {
  710. // // We can't contain deleted generic arguments without being deleted ourselves
  711. // BfTypeInstance* genericType = (BfTypeInstance*)type;
  712. //
  713. // for (auto genericTypeArg : genericType->mTypeGenericArguments)
  714. // {
  715. // auto depType = genericTypeArg->ToDependedType();
  716. // if (depType != NULL)
  717. // {
  718. // BF_ASSERT(depType->mDependencyMap.mTypeSet.ContainsKey(type));
  719. // }
  720. // }
  721. // }
  722. // ++itr;
  723. // }
  724. #endif
  725. }
  726. void BfContext::RebuildType(BfType* type, bool deleteOnDemandTypes, bool rebuildModule, bool placeSpecializiedInPurgatory)
  727. {
  728. BfTypeInstance* typeInst = type->ToTypeInstance();
  729. if (type->IsDeleting())
  730. {
  731. return;
  732. }
  733. type->mDirty = true;
  734. bool wantDeleteType = (type->IsOnDemand()) && (deleteOnDemandTypes);
  735. if (type->IsConstExprValue())
  736. {
  737. auto constExprType = (BfConstExprValueType*)type;
  738. if (constExprType->mType->mSize != mScratchModule->GetPrimitiveType(constExprType->mValue.mTypeCode)->mSize)
  739. wantDeleteType = true;
  740. }
  741. if (wantDeleteType)
  742. {
  743. BfLogSysM("On-demand type %p attempted rebuild - deleting\n", type);
  744. DeleteType(type);
  745. auto depType = type->ToDependedType();
  746. if (depType != NULL)
  747. RebuildDependentTypes(depType);
  748. return;
  749. }
  750. if (typeInst == NULL)
  751. {
  752. type->mDefineState = BfTypeDefineState_Undefined;
  753. BfTypeProcessRequest* typeProcessRequest = mPopulateTypeWorkList.Alloc();
  754. typeProcessRequest->mType = type;
  755. mCompiler->mStats.mTypesQueued++;
  756. mCompiler->UpdateCompletion();
  757. return;
  758. }
  759. BF_ASSERT_REL(typeInst->mDefineState != BfTypeDefineState_DefinedAndMethodsSlotting);
  760. // We need to verify lookups before we rebuild the type, because a type lookup change needs to count as a TypeDataChanged
  761. VerifyTypeLookups(typeInst);
  762. if (typeInst->mRevision != mCompiler->mRevision)
  763. {
  764. BfLogSysM("Setting revision. Type: %p Revision: %d\n", typeInst, mCompiler->mRevision);
  765. typeInst->mRevision = mCompiler->mRevision;
  766. }
  767. if ((typeInst->IsTypeAlias()) != (typeInst->mTypeDef->mTypeCode == BfTypeCode_TypeAlias))
  768. {
  769. BfLogSysM("TypeAlias %p status changed - deleting\n", typeInst);
  770. DeleteType(type);
  771. return;
  772. }
  773. if ((typeInst->IsBoxed()) && (typeInst->mTypeDef->mEmitParent != NULL))
  774. typeInst->mTypeDef = typeInst->mTypeDef->mEmitParent;
  775. if (mSystem->mWorkspaceConfigChanged)
  776. {
  777. typeInst->mTypeOptionsIdx = -2;
  778. }
  779. if (typeInst->mTypeFailed)
  780. {
  781. // The type definition failed, so we need to rebuild everyone that was depending on us
  782. RebuildDependentTypes(typeInst);
  783. }
  784. if (typeInst->mTypeDef->GetDefinition()->mDefState == BfTypeDef::DefState_Deleted)
  785. return;
  786. if (typeInst->mDefineState == BfTypeDefineState_Undefined)
  787. {
  788. // If we haven't added this type the worklist yet then we reprocess the type rebuilding
  789. if ((typeInst->mRebuildFlags & BfTypeRebuildFlag_AddedToWorkList) != 0)
  790. return;
  791. }
  792. typeInst->mRebuildFlags = (BfTypeRebuildFlags)(typeInst->mRebuildFlags & ~BfTypeRebuildFlag_AddedToWorkList);
  793. bool addToWorkList = true;
  794. if ((typeInst->IsGenericTypeInstance()) && (!typeInst->IsUnspecializedType()) && (placeSpecializiedInPurgatory))
  795. {
  796. mCompiler->mGenericInstancePurgatory.push_back(typeInst);
  797. addToWorkList = false;
  798. }
  799. String typeName = mScratchModule->TypeToString(typeInst, BfTypeNameFlags_None);
  800. BfLogSysM("%p Rebuild Type: %p %s deleted:%d\n", this, typeInst, typeName.c_str(), typeInst->IsDeleting());
  801. if (addToWorkList)
  802. {
  803. AddTypeToWorkList(typeInst);
  804. }
  805. // Why did we need to do this? This caused all struct types to be rebuilt when we needed to rebuild ValueType due to
  806. // ValueType.Equals<T> needing to rebuild -- which happens if any structs that have been compared have a signature change.
  807. /*for (auto depItr : typeInst->mDependencyMap)
  808. {
  809. auto dependentType = depItr.first;
  810. auto dependencyFlags = depItr.second.mFlags;
  811. if (dependencyFlags & BfDependencyMap::DependencyFlag_DerivedFrom)
  812. {
  813. //BfLogSysM("Setting BaseTypeMayBeIncomplete on %p from %p\n", dependentType, typeInst);
  814. //dependentType->mBaseTypeMayBeIncomplete = true;
  815. if (!dependentType->IsIncomplete())
  816. RebuildType(dependentType);
  817. }
  818. }*/
  819. if ((mCompiler->IsHotCompile()) && (!typeInst->IsTypeAlias()))
  820. {
  821. BF_ASSERT(typeInst->mHotTypeData != NULL);
  822. if (typeInst->mHotTypeData != NULL)
  823. {
  824. auto hotLatestVersionHead = typeInst->mHotTypeData->GetLatestVersionHead();
  825. if (!hotLatestVersionHead->mPopulatedInterfaceMapping)
  826. {
  827. typeInst->CalcHotVirtualData(&hotLatestVersionHead->mInterfaceMapping);
  828. hotLatestVersionHead->mPopulatedInterfaceMapping = true;
  829. }
  830. PopulateHotTypeDataVTable(typeInst);
  831. }
  832. }
  833. else
  834. {
  835. delete typeInst->mHotTypeData;
  836. typeInst->mHotTypeData = NULL;
  837. }
  838. auto typeDef = typeInst->mTypeDef;
  839. // Process deps before clearing mMethodInstanceGroups, to make sure we delete any methodrefs pointing to us before
  840. // deleting those methods
  841. for (auto& dep : typeInst->mDependencyMap)
  842. {
  843. auto depType = dep.mKey;
  844. auto depFlags = dep.mValue.mFlags;
  845. // If a MethodRef depends ON US, that means it's a local method that we own. MethodRefs directly point to
  846. // methodInstances, so these will be invalid now.
  847. if (depType->IsMethodRef())
  848. {
  849. auto methodRefType = (BfMethodRefType*)depType;
  850. BF_ASSERT(methodRefType->mOwner == typeInst);
  851. DeleteType(methodRefType);
  852. }
  853. if ((depFlags & BfDependencyMap::DependencyFlag_UnspecializedType) != 0)
  854. {
  855. if ((depType->mDefineState != BfTypeDefineState_Undefined) && (depType->mRevision != mCompiler->mRevision))
  856. {
  857. // Rebuild undefined type. This isn't necessary when we modify the typeDef, but when we change configurations then
  858. // the specialized types will rebuild
  859. //TODO: WE just added "no rebuild module" to this. I'm not sure what this is all about anyway...
  860. RebuildType(depType, true, false);
  861. }
  862. }
  863. }
  864. // At some point we thought we didn't have to do this for resolve-only, but this logic is important for removing
  865. // specialized methods that are causing errors
  866. if (addToWorkList)
  867. {
  868. if (typeDef->mDefState == BfTypeDef::DefState_Signature_Changed)
  869. {
  870. typeInst->mSignatureRevision = mCompiler->mRevision;
  871. }
  872. else
  873. {
  874. bool needMethodCallsRebuild = false;
  875. for (auto& methodInstGroup : typeInst->mMethodInstanceGroups)
  876. {
  877. if (methodInstGroup.mMethodSpecializationMap != NULL)
  878. {
  879. for (auto& methodSpecializationItr : *methodInstGroup.mMethodSpecializationMap)
  880. {
  881. auto methodInstance = methodSpecializationItr.mValue;
  882. if ((!methodInstance->mIsUnspecialized) && (methodInstance->mHasFailed))
  883. {
  884. // A specialized generic method has failed, but the unspecialized version did not. This
  885. // can only happen for 'var' constrained methods, and we need to cause all referring
  886. // types to rebuild to ensure we're really specializing only the correct methods
  887. needMethodCallsRebuild = true;
  888. }
  889. }
  890. }
  891. }
  892. if (needMethodCallsRebuild)
  893. {
  894. TypeMethodSignaturesChanged(typeInst);
  895. }
  896. }
  897. }
  898. typeInst->ReleaseData();
  899. type->mDefineState = BfTypeDefineState_Undefined;
  900. typeInst->mSpecializedMethodReferences.Clear();
  901. typeInst->mAlwaysIncludeFlags = BfAlwaysIncludeFlag_None;
  902. typeInst->mHasBeenInstantiated = false;
  903. typeInst->mLookupResults.Clear();
  904. typeInst->mIsUnion = false;
  905. typeInst->mIsCRepr = false;
  906. typeInst->mIsPacked = false;
  907. typeInst->mIsSplattable = false;
  908. typeInst->mHasUnderlyingArray = false;
  909. typeInst->mIsTypedPrimitive = false;
  910. typeInst->mMergedFieldDataCount = 0;
  911. typeInst->mTypeIncomplete = true;
  912. typeInst->mNeedsMethodProcessing = false;
  913. typeInst->mHasBeenInstantiated = false;
  914. typeInst->mHasParameterizedBase = false;
  915. typeInst->mTypeFailed = false;
  916. typeInst->mTypeWarned = false;
  917. typeInst->mHasUnderlyingArray = false;
  918. typeInst->mHasPackingHoles = false;
  919. typeInst->mWantsGCMarking = false;
  920. typeInst->mHasDeclError = false;
  921. delete typeInst->mTypeInfoEx;
  922. typeInst->mTypeInfoEx = NULL;
  923. if (typeInst->mCeTypeInfo != NULL)
  924. typeInst->mCeTypeInfo->mRebuildMap.Clear();
  925. if (typeInst->mTypeDef->mEmitParent != NULL)
  926. {
  927. auto emitTypeDef = typeInst->mTypeDef;
  928. typeInst->mTypeDef = emitTypeDef->mEmitParent;
  929. BfLogSysM("Type %p queueing delete of typeDef %p, resetting typeDef to %p\n", typeInst, emitTypeDef, typeInst->mTypeDef);
  930. emitTypeDef->mDefState = BfTypeDef::DefState_Deleted;
  931. AutoCrit autoCrit(mSystem->mDataLock);
  932. BF_ASSERT(!mSystem->mTypeDefDeleteQueue.Contains(emitTypeDef));
  933. mSystem->mTypeDefDeleteQueue.push_back(emitTypeDef);
  934. }
  935. //typeInst->mTypeDef->ClearEmitted();
  936. for (auto localMethod : typeInst->mOwnedLocalMethods)
  937. delete localMethod;
  938. typeInst->mOwnedLocalMethods.Clear();
  939. if (typeInst->IsGenericTypeInstance())
  940. {
  941. auto genericTypeInstance = (BfTypeInstance*)typeInst;
  942. genericTypeInstance->mGenericTypeInfo->mTypeGenericArgumentRefs.Clear();
  943. for (auto genericParam : genericTypeInstance->mGenericTypeInfo->mGenericParams)
  944. genericParam->Release();
  945. genericTypeInstance->mGenericTypeInfo->mInitializedGenericParams = false;
  946. genericTypeInstance->mGenericTypeInfo->mFinishedGenericParams = false;
  947. genericTypeInstance->mGenericTypeInfo->mGenericParams.Clear();
  948. genericTypeInstance->mGenericTypeInfo->mValidatedGenericConstraints = false;
  949. genericTypeInstance->mGenericTypeInfo->mHadValidateErrors = false;
  950. delete genericTypeInstance->mGenericTypeInfo->mGenericExtensionInfo;
  951. genericTypeInstance->mGenericTypeInfo->mGenericExtensionInfo = NULL;
  952. genericTypeInstance->mGenericTypeInfo->mProjectsReferenced.Clear();
  953. }
  954. typeInst->mStaticSearchMap.Clear();
  955. typeInst->mInternalAccessMap.Clear();
  956. typeInst->mInterfaces.Clear();
  957. typeInst->mInterfaceMethodTable.Clear();
  958. for (auto operatorInfo : typeInst->mOperatorInfo)
  959. delete operatorInfo;
  960. typeInst->mOperatorInfo.Clear();
  961. typeInst->mMethodInstanceGroups.Clear();
  962. typeInst->mFieldInstances.Clear();
  963. for (auto methodInst : typeInst->mInternalMethods)
  964. delete methodInst;
  965. typeInst->mInternalMethods.Clear();
  966. typeInst->mHasStaticInitMethod = false;
  967. typeInst->mHasStaticMarkMethod = false;
  968. typeInst->mHasStaticDtorMethod = false;
  969. typeInst->mHasTLSFindMethod = false;
  970. typeInst->mBaseType = NULL;
  971. delete typeInst->mCustomAttributes;
  972. typeInst->mCustomAttributes = NULL;
  973. delete typeInst->mAttributeData;
  974. typeInst->mAttributeData = NULL;
  975. typeInst->mVirtualMethodTableSize = 0;
  976. typeInst->mVirtualMethodTable.Clear();
  977. typeInst->mSize = -1;
  978. typeInst->mAlign = -1;
  979. typeInst->mInstSize = -1;
  980. typeInst->mInstAlign = -1;
  981. typeInst->mInheritDepth = 0;
  982. delete typeInst->mConstHolder;
  983. typeInst->mConstHolder = NULL;
  984. if ((typeInst->mModule != NULL) && (rebuildModule))
  985. {
  986. typeInst->mModule->StartNewRevision();
  987. typeInst->mRevision = mCompiler->mRevision;
  988. }
  989. }
  990. void BfContext::RebuildDependentTypes(BfDependedType* dType)
  991. {
  992. TypeDataChanged(dType, true);
  993. auto typeInst = dType->ToTypeInstance();
  994. if (typeInst != NULL)
  995. TypeMethodSignaturesChanged(typeInst);
  996. }
  997. // Dependencies cascade as such:
  998. // DerivedFrom / StructMemberData: these change the layout of memory for the dependent classes,
  999. // so not only do the dependent classes need to be rebuild, but any other classes relying on those derived classes
  1000. // (either by derivation, containment, or field reading) need to have their code recompiled as well.
  1001. // ReadFields: when ClassB depends on the data layout of ClassA, and ClassC reads a field from
  1002. // ClassB, it means that ClassC code needs to be recompiled if ClassA data layout changes, but performing a ReadField
  1003. // (obviously) doesn't change the data layout of ClassC
  1004. // Calls: non-cascading dependency, since it's independent of data layout ConstValue: non-cascading data change
  1005. void BfContext::TypeDataChanged(BfDependedType* dType, bool isNonStaticDataChange)
  1006. {
  1007. BfLogSysM("TypeDataChanged %p\n", dType);
  1008. auto rebuildFlag = isNonStaticDataChange ? BfTypeRebuildFlag_NonStaticChange : BfTypeRebuildFlag_StaticChange;
  1009. if ((dType->mRebuildFlags & rebuildFlag) != 0) // Already did this change?
  1010. return;
  1011. dType->mRebuildFlags = (BfTypeRebuildFlags)(dType->mRebuildFlags | rebuildFlag);
  1012. // We need to rebuild all other types that rely on our data layout
  1013. for (auto& depItr : dType->mDependencyMap)
  1014. {
  1015. auto dependentType = depItr.mKey;
  1016. auto dependencyFlags = depItr.mValue.mFlags;
  1017. auto dependentDType = dependentType->ToDependedType();
  1018. if (dependentDType != NULL)
  1019. {
  1020. auto dependentTypeInstance = dependentType->ToTypeInstance();
  1021. if (isNonStaticDataChange)
  1022. {
  1023. bool hadChange = false;
  1024. if ((dependencyFlags &
  1025. (BfDependencyMap::DependencyFlag_DerivedFrom |
  1026. BfDependencyMap::DependencyFlag_ValueTypeMemberData |
  1027. BfDependencyMap::DependencyFlag_NameReference |
  1028. BfDependencyMap::DependencyFlag_ValueTypeSizeDep)) != 0)
  1029. {
  1030. hadChange = true;
  1031. }
  1032. // This case is for when we were declared as a class on a previous compilation,
  1033. // but then we were changed to a struct
  1034. if ((dType->IsValueType()) &&
  1035. (dependencyFlags & BfDependencyMap::DependencyFlag_PtrMemberData))
  1036. {
  1037. hadChange = true;
  1038. }
  1039. if (mCompiler->IsHotCompile())
  1040. {
  1041. // VData layout may be changing if there's a data change...
  1042. if (dependencyFlags & BfDependencyMap::DependencyFlag_VirtualCall)
  1043. {
  1044. hadChange = true;
  1045. }
  1046. }
  1047. if (hadChange)
  1048. TypeDataChanged(dependentDType, true);
  1049. }
  1050. if (dependencyFlags & BfDependencyMap::DependencyFlag_ConstValue)
  1051. {
  1052. TypeDataChanged(dependentDType, false);
  1053. // The ConstValue dependency may be that dependentType used one of our consts as
  1054. // a default value to a method param, so assume callsites need rebuilding
  1055. if (dependentTypeInstance != NULL)
  1056. TypeMethodSignaturesChanged(dependentTypeInstance);
  1057. }
  1058. if (dependentType->mRevision != mCompiler->mRevision)
  1059. {
  1060. // We need to include DependencyFlag_ParamOrReturnValue because it could be a struct that changes its splatting ability
  1061. // We can't ONLY check against structs, though, because a type could change from a class to a struct
  1062. if (dependencyFlags &
  1063. (BfDependencyMap::DependencyFlag_ReadFields | BfDependencyMap::DependencyFlag_ParamOrReturnValue |
  1064. BfDependencyMap::DependencyFlag_LocalUsage | BfDependencyMap::DependencyFlag_MethodGenericArg |
  1065. BfDependencyMap::DependencyFlag_Allocates))
  1066. {
  1067. RebuildType(dependentType);
  1068. }
  1069. }
  1070. }
  1071. else
  1072. {
  1073. if (dependentType->mRevision != mCompiler->mRevision)
  1074. {
  1075. // Not a type instance, probably something like a sized array
  1076. RebuildType(dependentType);
  1077. }
  1078. }
  1079. }
  1080. if (dType->mRevision != mCompiler->mRevision)
  1081. RebuildType(dType);
  1082. }
  1083. void BfContext::TypeMethodSignaturesChanged(BfTypeInstance* typeInst)
  1084. {
  1085. if (typeInst->mRebuildFlags & BfTypeRebuildFlag_MethodSignatureChange) // Already did change?
  1086. return;
  1087. typeInst->mRebuildFlags = (BfTypeRebuildFlags) (typeInst->mRebuildFlags | BfTypeRebuildFlag_MethodSignatureChange);
  1088. BfLogSysM("TypeMethodSignaturesChanged %p\n", typeInst);
  1089. // These don't happen in TypeDataChanged because we don't need to cascade
  1090. for (auto& depItr : typeInst->mDependencyMap)
  1091. {
  1092. auto dependentType = depItr.mKey;
  1093. auto dependencyFlags = depItr.mValue.mFlags;
  1094. if (dependentType->mRevision != mCompiler->mRevision)
  1095. {
  1096. // We don't need to cascade rebuilding for method-based usage - just rebuild the type directly (unlike TypeDataChanged, which cascades)
  1097. if ((dependencyFlags & BfDependencyMap::DependencyFlag_Calls) ||
  1098. (dependencyFlags & BfDependencyMap::DependencyFlag_VirtualCall) ||
  1099. (dependencyFlags & BfDependencyMap::DependencyFlag_InlinedCall) ||
  1100. (dependencyFlags & BfDependencyMap::DependencyFlag_MethodGenericArg) ||
  1101. (dependencyFlags & BfDependencyMap::DependencyFlag_CustomAttribute) ||
  1102. (dependencyFlags & BfDependencyMap::DependencyFlag_DerivedFrom) ||
  1103. (dependencyFlags & BfDependencyMap::DependencyFlag_ImplementsInterface))
  1104. {
  1105. RebuildType(dependentType);
  1106. }
  1107. }
  1108. }
  1109. }
  1110. void BfContext::TypeInlineMethodInternalsChanged(BfTypeInstance* typeInst)
  1111. {
  1112. if (typeInst->mRebuildFlags & BfTypeRebuildFlag_MethodInlineInternalsChange) // Already did change?
  1113. return;
  1114. typeInst->mRebuildFlags = (BfTypeRebuildFlags)(typeInst->mRebuildFlags | BfTypeRebuildFlag_MethodInlineInternalsChange);
  1115. // These don't happen in TypeDataChanged because we don't need to cascade
  1116. for (auto& depItr : typeInst->mDependencyMap)
  1117. {
  1118. auto dependentType = depItr.mKey;
  1119. auto dependencyFlags = depItr.mValue.mFlags;
  1120. if (dependentType->mRevision != mCompiler->mRevision)
  1121. {
  1122. // We don't need to cascade rebuilding for method-based usage - just rebuild the type directly (unlike TypeDataChanged, which cascades)
  1123. if ((dependencyFlags & BfDependencyMap::DependencyFlag_InlinedCall) != 0)
  1124. {
  1125. RebuildType(dependentType);
  1126. }
  1127. }
  1128. }
  1129. }
  1130. void BfContext::TypeConstEvalChanged(BfTypeInstance* typeInst)
  1131. {
  1132. if (typeInst->mRebuildFlags & BfTypeRebuildFlag_ConstEvalChange) // Already did change?
  1133. return;
  1134. typeInst->mRebuildFlags = (BfTypeRebuildFlags)(typeInst->mRebuildFlags | BfTypeRebuildFlag_ConstEvalChange);
  1135. // These don't happen in TypeDataChanged because we don't need to cascade
  1136. for (auto& depItr : typeInst->mDependencyMap)
  1137. {
  1138. auto dependentType = depItr.mKey;
  1139. auto dependencyFlags = depItr.mValue.mFlags;
  1140. // We don't need to cascade rebuilding for method-based usage - just rebuild the type directly (unlike TypeDataChanged, which cascades)
  1141. if ((dependencyFlags & BfDependencyMap::DependencyFlag_ConstEval) != 0)
  1142. {
  1143. auto depTypeInst = dependentType->ToTypeInstance();
  1144. if (depTypeInst != NULL)
  1145. TypeConstEvalChanged(depTypeInst);
  1146. if (dependentType->mRevision != mCompiler->mRevision)
  1147. RebuildType(dependentType);
  1148. }
  1149. else if ((dependencyFlags & BfDependencyMap::DependencyFlag_ConstEvalConstField) != 0)
  1150. {
  1151. auto depTypeInst = dependentType->ToTypeInstance();
  1152. if (depTypeInst != NULL)
  1153. TypeConstEvalFieldChanged(depTypeInst);
  1154. if (dependentType->mRevision != mCompiler->mRevision)
  1155. RebuildType(dependentType);
  1156. }
  1157. }
  1158. }
  1159. void BfContext::TypeConstEvalFieldChanged(BfTypeInstance* typeInst)
  1160. {
  1161. if (typeInst->mRebuildFlags & BfTypeRebuildFlag_ConstEvalFieldChange) // Already did change?
  1162. return;
  1163. typeInst->mRebuildFlags = (BfTypeRebuildFlags)(typeInst->mRebuildFlags | BfTypeRebuildFlag_ConstEvalFieldChange);
  1164. // These don't happen in TypeDataChanged because we don't need to cascade
  1165. for (auto& depItr : typeInst->mDependencyMap)
  1166. {
  1167. auto dependentType = depItr.mKey;
  1168. auto dependencyFlags = depItr.mValue.mFlags;
  1169. if ((dependencyFlags & BfDependencyMap::DependencyFlag_ConstEvalConstField) != 0)
  1170. {
  1171. auto depTypeInst = dependentType->ToTypeInstance();
  1172. if (depTypeInst != NULL)
  1173. TypeConstEvalFieldChanged(depTypeInst);
  1174. if (dependentType->mRevision != mCompiler->mRevision)
  1175. RebuildType(dependentType);
  1176. }
  1177. }
  1178. }
  1179. void BfContext::PopulateHotTypeDataVTable(BfTypeInstance* typeInstance)
  1180. {
  1181. BP_ZONE("BfContext::PopulateHotTypeDataVTable");
  1182. if (typeInstance->IsTypeAlias())
  1183. return;
  1184. // The hot virtual table only holds our new entries, not the vtable entries inherited from our base classes
  1185. auto hotTypeData = typeInstance->mHotTypeData;
  1186. if (hotTypeData == NULL)
  1187. return;
  1188. if (typeInstance->IsIncomplete())
  1189. {
  1190. if (mCompiler->mHotState->mCommittedHotCompileIdx > 0)
  1191. {
  1192. // Should already be populated
  1193. BF_ASSERT(hotTypeData->mVTableOrigLength != -1);
  1194. }
  1195. return;
  1196. }
  1197. if (hotTypeData->mVTableOrigLength == -1)
  1198. {
  1199. auto committedHotTypeVersion = typeInstance->mHotTypeData->GetTypeVersion(mCompiler->mHotState->mCommittedHotCompileIdx);
  1200. if (committedHotTypeVersion != NULL)
  1201. {
  1202. hotTypeData->mVTableOrigLength = typeInstance->mVirtualMethodTableSize;
  1203. hotTypeData->mOrigInterfaceMethodsLength = typeInstance->GetIFaceVMethodSize();
  1204. }
  1205. BfLogSysM("PopulateHotTypeDataVTable set %p HotDataType->mVTableOrigLength To %d\n", typeInstance, hotTypeData->mVTableOrigLength);
  1206. }
  1207. int vTableStart = -1;
  1208. int primaryVTableSize = 0;
  1209. if (typeInstance->IsInterface())
  1210. {
  1211. // Interfaces don't have vext markers
  1212. vTableStart = 0;
  1213. #ifdef _DEBUG
  1214. for (int vIdx = 0; vIdx < (int)typeInstance->mVirtualMethodTable.size(); vIdx++)
  1215. {
  1216. auto& methodRef = typeInstance->mVirtualMethodTable[vIdx].mDeclaringMethod;
  1217. if (methodRef.mMethodNum == -1)
  1218. {
  1219. BF_DBG_FATAL("Shouldn't have vext marker");
  1220. }
  1221. }
  1222. #endif
  1223. }
  1224. else
  1225. {
  1226. for (int vIdx = 0; vIdx < (int)typeInstance->mVirtualMethodTable.size(); vIdx++)
  1227. {
  1228. auto& methodRef = typeInstance->mVirtualMethodTable[vIdx].mDeclaringMethod;
  1229. if (methodRef.mMethodNum == -1)
  1230. {
  1231. if (methodRef.mTypeInstance == typeInstance)
  1232. {
  1233. vTableStart = vIdx;
  1234. }
  1235. else if (vTableStart != -1)
  1236. {
  1237. BF_DBG_FATAL("Shouldn't have another vext marker");
  1238. break;
  1239. }
  1240. }
  1241. }
  1242. }
  1243. primaryVTableSize = (int)typeInstance->mVirtualMethodTable.size() - vTableStart;
  1244. BF_ASSERT(vTableStart != -1);
  1245. if (primaryVTableSize > (int)hotTypeData->mVTableEntries.size())
  1246. hotTypeData->mVTableEntries.Resize(primaryVTableSize);
  1247. int methodIdx = -1;
  1248. for (int vIdx = 0; vIdx < primaryVTableSize; vIdx++)
  1249. {
  1250. auto& methodRef = typeInstance->mVirtualMethodTable[vTableStart + vIdx].mDeclaringMethod;
  1251. methodIdx++;
  1252. auto methodInstance = (BfMethodInstance*)methodRef;
  1253. if (methodInstance == NULL)
  1254. continue;
  1255. BF_ASSERT(methodRef.mTypeInstance == typeInstance);
  1256. BF_ASSERT(methodInstance->mVirtualTableIdx != -1);
  1257. BF_ASSERT(!methodInstance->mMethodDef->mIsOverride);
  1258. // Find the original non-override method
  1259. /*while (methodInstance->mMethodDef->mIsOverride)
  1260. {
  1261. BfTypeInstance* parent = methodInstance->GetOwner()->mBaseType;
  1262. auto parentVirtualMethod = parent->mVirtualMethodTable[methodInstance->mVirtualTableIdx];
  1263. BF_ASSERT(parentVirtualMethod->mVirtualTableIdx != -1);
  1264. methodInstance = parentVirtualMethod;
  1265. }*/
  1266. BF_ASSERT(!methodInstance->mMethodInfoEx->mMangledName.IsEmpty());
  1267. auto& entry = hotTypeData->mVTableEntries[vIdx];
  1268. if (entry.mFuncName.empty())
  1269. {
  1270. entry.mFuncName = methodInstance->mMethodInfoEx->mMangledName;
  1271. }
  1272. else
  1273. {
  1274. // Make sure its the same still
  1275. BF_ASSERT(entry.mFuncName == methodInstance->mMethodInfoEx->mMangledName);
  1276. }
  1277. }
  1278. }
  1279. void BfContext::SaveDeletingType(BfType* type)
  1280. {
  1281. if (mCompiler->mIsResolveOnly)
  1282. return;
  1283. if ((type->mRebuildFlags) && ((type->mRebuildFlags & BfTypeRebuildFlag_TypeDataSaved) != 0))
  1284. return;
  1285. type->mRebuildFlags = (BfTypeRebuildFlags)(type->mRebuildFlags | BfTypeRebuildFlag_TypeDataSaved);
  1286. String mangledName = BfSafeMangler::Mangle(type, mUnreifiedModule);
  1287. BfLogSysM("Saving deleted type: %p %s\n", type, mangledName.c_str());
  1288. BfSavedTypeData** savedTypeDataPtr;
  1289. BfSavedTypeData* savedTypeData;
  1290. if (mSavedTypeDataMap.TryAdd(mangledName, NULL, &savedTypeDataPtr))
  1291. {
  1292. savedTypeData = new BfSavedTypeData();
  1293. *savedTypeDataPtr = savedTypeData;
  1294. }
  1295. else
  1296. {
  1297. // This can happen if we have a conflicting type definition
  1298. savedTypeData = *savedTypeDataPtr;
  1299. }
  1300. savedTypeData->mTypeId = type->mTypeId;
  1301. while ((int)mSavedTypeData.size() <= savedTypeData->mTypeId)
  1302. mSavedTypeData.Add(NULL);
  1303. mSavedTypeData[savedTypeData->mTypeId] = savedTypeData;
  1304. auto typeInst = type->ToTypeInstance();
  1305. if (typeInst != NULL)
  1306. {
  1307. delete savedTypeData->mHotTypeData;
  1308. if (mCompiler->IsHotCompile())
  1309. savedTypeData->mHotTypeData = typeInst->mHotTypeData;
  1310. else
  1311. delete typeInst->mHotTypeData;
  1312. typeInst->mHotTypeData = NULL;
  1313. }
  1314. }
  1315. BfType* BfContext::FindType(const StringImpl& fullTypeName)
  1316. {
  1317. int genericArgCount = 0;
  1318. String typeName = fullTypeName;
  1319. if (typeName.EndsWith('>'))
  1320. {
  1321. // Generic
  1322. }
  1323. BfTypeDef* typeDef = mSystem->FindTypeDef(typeName, genericArgCount);
  1324. if (typeDef == NULL)
  1325. return NULL;
  1326. return mUnreifiedModule->ResolveTypeDef(typeDef);
  1327. }
  1328. String BfContext::TypeIdToString(int typeId)
  1329. {
  1330. auto type = mTypes[typeId];
  1331. if (type != NULL)
  1332. return mScratchModule->TypeToString(type);
  1333. if (mCompiler->mHotState != NULL)
  1334. {
  1335. for (auto& kv : mCompiler->mHotState->mDeletedTypeNameMap)
  1336. {
  1337. if (kv.mValue == typeId)
  1338. return kv.mKey;
  1339. }
  1340. }
  1341. return StrFormat("#%d", typeId);
  1342. }
  1343. BfHotTypeData* BfContext::GetHotTypeData(int typeId)
  1344. {
  1345. auto type = mTypes[typeId];
  1346. if (type != NULL)
  1347. {
  1348. auto typeInst = type->ToTypeInstance();
  1349. if (typeInst != NULL)
  1350. return typeInst->mHotTypeData;
  1351. }
  1352. if (typeId < (int)mSavedTypeData.size())
  1353. {
  1354. auto savedTypeData = mSavedTypeData[typeId];
  1355. if (savedTypeData != NULL)
  1356. return savedTypeData->mHotTypeData;
  1357. }
  1358. return NULL;
  1359. }
  1360. void BfContext::ReflectInit()
  1361. {
  1362. auto bfModule = mScratchModule;
  1363. bfModule->CreatePointerType(bfModule->GetPrimitiveType(BfTypeCode_NullPtr));
  1364. ///
  1365. auto typeDefType = bfModule->ResolveTypeDef(mCompiler->mTypeTypeDef)->ToTypeInstance();
  1366. if (!typeDefType)
  1367. return;
  1368. BF_ASSERT(typeDefType != NULL);
  1369. mBfTypeType = typeDefType->ToTypeInstance();
  1370. auto typeInstanceDefType = bfModule->ResolveTypeDef(mCompiler->mReflectTypeInstanceTypeDef);
  1371. if (!typeInstanceDefType)
  1372. return;
  1373. auto typeInstanceDefTypeInstance = typeInstanceDefType->ToTypeInstance();
  1374. auto typeDef = mSystem->FindTypeDef("System.ClassVData");
  1375. BF_ASSERT(typeDef != NULL);
  1376. auto bfClassVDataType = bfModule->ResolveTypeDef(typeDef)->ToTypeInstance();
  1377. mBfClassVDataPtrType = bfModule->CreatePointerType(bfClassVDataType);
  1378. }
  1379. void BfContext::DeleteType(BfType* type, bool deferDepRebuilds)
  1380. {
  1381. if (type == mBfObjectType)
  1382. mBfObjectType = NULL;
  1383. if (type == mBfTypeType)
  1384. mBfObjectType = NULL;
  1385. if (type->mRebuildFlags & BfTypeRebuildFlag_Deleted)
  1386. return;
  1387. mCompiler->mStats.mTypesDeleted++;
  1388. BfDependedType* dType = type->ToDependedType();
  1389. BfTypeInstance* typeInst = type->ToTypeInstance();
  1390. if (typeInst != NULL)
  1391. {
  1392. if (mCompiler->mHotState != NULL)
  1393. {
  1394. if ((typeInst->mHotTypeData != NULL) && (typeInst->mHotTypeData->mPendingDataChange))
  1395. mCompiler->mHotState->RemovePendingChanges(typeInst);
  1396. String typeName = mScratchModule->TypeToString(typeInst);
  1397. mCompiler->mHotState->mDeletedTypeNameMap[typeName] = typeInst->mTypeId;
  1398. }
  1399. auto module = typeInst->mModule;
  1400. // Don't remove the mModule pointer in typeInst -- if the type ends up being a zombie then we still need
  1401. // to generate the VData from the type
  1402. if (module != NULL)
  1403. {
  1404. if (module->mIsScratchModule)
  1405. {
  1406. BF_ASSERT(module->mOwnedTypeInstances.size() == 0);
  1407. }
  1408. else
  1409. {
  1410. auto itr = std::find(module->mOwnedTypeInstances.begin(), module->mOwnedTypeInstances.end(), typeInst);
  1411. module->mOwnedTypeInstances.erase(itr);
  1412. if ((module->mOwnedTypeInstances.size() == 0) && (module != mScratchModule))
  1413. {
  1414. // This module is no longer needed
  1415. module->RemoveModuleData();
  1416. module->mIsDeleting = true;
  1417. auto itr = std::find(mModules.begin(), mModules.end(), module);
  1418. mModules.erase(itr);
  1419. // This was only needed for 'zombie modules', which we don't need anymore?
  1420. // To avoid linking errors. Used instead of directly removing from mModules.
  1421. mDeletingModules.push_back(module);
  1422. }
  1423. }
  1424. }
  1425. }
  1426. type->mRebuildFlags = (BfTypeRebuildFlags)((type->mRebuildFlags | BfTypeRebuildFlag_Deleted) & ~BfTypeRebuildFlag_DeleteQueued);
  1427. SaveDeletingType(type);
  1428. mTypes[type->mTypeId] = NULL;
  1429. BfLogSysM("Deleting Type: %p %s\n", type, mScratchModule->TypeToString(type).c_str());
  1430. // All dependencies cause rebuilds when we delete types
  1431. if (dType != NULL)
  1432. {
  1433. //TODO: Do PopulateHotTypeDataVTable then store the HotTypeDataData
  1434. if (dType->IsUnspecializedType())
  1435. {
  1436. /*auto itr = mScratchModule->mClassVDataRefs.find(typeInst);
  1437. if (itr != mScratchModule->mClassVDataRefs.end())
  1438. mScratchModule->mClassVDataRefs.erase(itr);*/
  1439. mScratchModule->mClassVDataRefs.Remove(typeInst);
  1440. }
  1441. //UH - I think this is not true.
  1442. // If A derives from B, and C derives from B, if we delete 'A' then it's true that
  1443. // 'C' won't rebuild otherwise, BUT 'B' would fail to build but it would do a TypeDataChanged once it WAS able to built. Right?
  1444. // Even though we do rebuilds on all types below, we specifically need to call
  1445. // TypeDataChanged here for cascading data dependencies
  1446. /*if (!deferDepRebuilds)
  1447. TypeDataChanged(typeInst, true);*/
  1448. Array<BfType*> rebuildTypeQueue;
  1449. for (auto& depItr : dType->mDependencyMap)
  1450. {
  1451. //bool rebuildType = false;
  1452. auto dependentType = depItr.mKey;
  1453. auto dependentTypeInst = dependentType->ToTypeInstance();
  1454. auto dependencyEntry = depItr.mValue;
  1455. if ((dependencyEntry.mFlags & (BfDependencyMap::DependencyFlag_MethodGenericArg)) != 0)
  1456. {
  1457. if (!dependentType->IsDeleting())
  1458. {
  1459. if ((deferDepRebuilds) && (dependentTypeInst != NULL))
  1460. mQueuedSpecializedMethodRebuildTypes.Add(dependentTypeInst);
  1461. }
  1462. }
  1463. if ((dependencyEntry.mFlags & (BfDependencyMap::DependencyFlag_TypeGenericArg)) != 0)
  1464. {
  1465. // This type can't exist anymore
  1466. DeleteType(dependentType, deferDepRebuilds);
  1467. continue;
  1468. }
  1469. if (dependentTypeInst == NULL)
  1470. {
  1471. // This was something like a sized array
  1472. DeleteType(dependentType, deferDepRebuilds);
  1473. continue;
  1474. }
  1475. if ((dependencyEntry.mFlags & ~(BfDependencyMap::DependencyFlag_UnspecializedType | BfDependencyMap::DependencyFlag_WeakReference)) == 0)
  1476. continue; // Not a cause for rebuilding
  1477. if (dependentTypeInst->IsOnDemand())
  1478. {
  1479. // Force on-demand dependencies to rebuild themselves
  1480. DeleteType(dependentType, deferDepRebuilds);
  1481. continue;
  1482. }
  1483. if (dType->IsBoxed())
  1484. {
  1485. // Allow these to just be implicitly used. This solves some issues with switching between ignoreWrites settings in resolveOnly compilation
  1486. continue;
  1487. }
  1488. if ((deferDepRebuilds) && (dependentTypeInst != NULL))
  1489. mFailTypes.Add(dependentTypeInst);
  1490. else
  1491. {
  1492. rebuildTypeQueue.Add(dependentType);
  1493. }
  1494. }
  1495. if (type->IsMethodRef())
  1496. {
  1497. // Detach
  1498. auto methodRefType = (BfMethodRefType*)type;
  1499. BfMethodInstance* methodInstance = methodRefType->mMethodRef;
  1500. BF_ASSERT(methodInstance->mMethodInstanceGroup->mRefCount > 0);
  1501. methodInstance->mMethodInstanceGroup->mRefCount--;
  1502. methodRefType->mMethodRef = NULL;
  1503. methodInstance->mHasMethodRefType = false;
  1504. }
  1505. for (auto dependentType : rebuildTypeQueue)
  1506. RebuildType(dependentType);
  1507. }
  1508. }
  1509. void BfContext::UpdateAfterDeletingTypes()
  1510. {
  1511. BP_ZONE("BfContext::UpdateAfterDeletingTypes");
  1512. BfLogSysM("UpdateAfterDeletingTypes\n");
  1513. int graveyardStart = (int)mTypeGraveyard.size();
  1514. while (true)
  1515. {
  1516. bool deletedNewTypes = false;
  1517. auto itr = mResolvedTypes.begin();
  1518. while (itr != mResolvedTypes.end())
  1519. {
  1520. auto type = itr.mCurEntry->mValue;
  1521. bool doDelete = false;
  1522. //BfLogSysM("Removing entry\n");
  1523. bool isDeleting = type->IsDeleting();
  1524. if ((!isDeleting) && (type->IsDependentOnUnderlyingType()))
  1525. {
  1526. auto underlyingType = type->GetUnderlyingType();
  1527. if ((underlyingType != NULL) && (underlyingType->IsDeleting()))
  1528. {
  1529. deletedNewTypes = true;
  1530. isDeleting = true;
  1531. DeleteType(type);
  1532. }
  1533. }
  1534. if (isDeleting)
  1535. {
  1536. doDelete = true;
  1537. }
  1538. else
  1539. {
  1540. #if _DEBUG
  1541. if (type->IsGenericTypeInstance())
  1542. {
  1543. // We can't contain deleted generic arguments without being deleted ourselves
  1544. BfTypeInstance* genericType = (BfTypeInstance*)type;
  1545. for (auto genericTypeArg : genericType->mGenericTypeInfo->mTypeGenericArguments)
  1546. {
  1547. BF_ASSERT((!genericTypeArg->IsDeleting()));
  1548. }
  1549. }
  1550. #endif
  1551. }
  1552. if (doDelete)
  1553. {
  1554. BF_ASSERT((type->mRebuildFlags & BfTypeRebuildFlag_Deleted) == BfTypeRebuildFlag_Deleted);
  1555. itr = mResolvedTypes.Erase(itr);
  1556. mTypeGraveyard.push_back(type);
  1557. }
  1558. else
  1559. ++itr;
  1560. }
  1561. if (!deletedNewTypes)
  1562. break;
  1563. }
  1564. #if _DEBUG
  1565. // auto itr = mResolvedTypes.begin();
  1566. // while (itr != mResolvedTypes.end())
  1567. // {
  1568. // auto type = itr.mCurEntry->mType;
  1569. // BF_ASSERT((type->mRebuildFlags & ~(BfTypeRebuildFlag_Deleted)) == 0);
  1570. // ++itr;
  1571. // }
  1572. #endif
  1573. if (!mCompiler->mIsResolveOnly)
  1574. {
  1575. BP_ZONE("BfContext::UpdateAfterDeletingTypes saving typeData");
  1576. for (int graveyardIdx = graveyardStart; graveyardIdx < (int)mTypeGraveyard.size(); graveyardIdx++)
  1577. {
  1578. auto type = mTypeGraveyard[graveyardIdx];
  1579. SaveDeletingType(type);
  1580. }
  1581. }
  1582. }
  1583. // This happens before the old defs have been injected
  1584. void BfContext::PreUpdateRevisedTypes()
  1585. {
  1586. // if (mCompiler->IsHotCompile())
  1587. // {
  1588. // for (auto typeEntry : mResolvedTypes)
  1589. // {
  1590. // auto type = typeEntry->mType;
  1591. // auto typeInst = type->ToTypeInstance();
  1592. // if (typeInst == NULL)
  1593. // continue;
  1594. //
  1595. // auto typeDef = typeInst->mTypeDef;
  1596. // if ((typeDef->mDefState != BfTypeDef::DefState_New) && (typeDef->mDefState != BfTypeDef::DefState_Defined))
  1597. // {
  1598. // if (typeInst->mHotTypeData == NULL)
  1599. // {
  1600. // typeInst->mHotTypeData = new BfHotTypeData();
  1601. // typeInst->CalcHotVirtualData(&typeInst->mHotTypeData->mInterfaceMapping);
  1602. // }
  1603. // PopulateHotTypeDataVTable(typeInst);
  1604. // }
  1605. // }
  1606. // }
  1607. }
  1608. // Note that this method can also cause modules to be build in other contexts.
  1609. // That's why we do our UpdateAfterDeletingTypes after all the contexts' UpdateRevisedTypes
  1610. void BfContext::UpdateRevisedTypes()
  1611. {
  1612. BP_ZONE("BfContext::UpdateRevisedTypes");
  1613. BfLogSysM("BfContext::UpdateRevisedTypes\n");
  1614. auto _CheckCanSkipCtor = [&](BfTypeDef* typeDef)
  1615. {
  1616. if (typeDef == NULL)
  1617. return true;
  1618. typeDef = typeDef->GetLatest();
  1619. for (auto fieldDef : typeDef->mFields)
  1620. {
  1621. if (fieldDef->mIsStatic)
  1622. continue;
  1623. if (fieldDef->mInitializer != NULL)
  1624. return false;
  1625. }
  1626. for (auto methodDef : typeDef->mMethods)
  1627. {
  1628. if (methodDef->mMethodType == BfMethodType_Init)
  1629. return false;
  1630. }
  1631. return true;
  1632. };
  1633. auto _CheckCanSkipCtorByName = [&](const StringImpl& name)
  1634. {
  1635. BfAtomComposite qualifiedFindName;
  1636. if (!mSystem->ParseAtomComposite(name, qualifiedFindName))
  1637. return true;
  1638. auto itr = mSystem->mTypeDefs.TryGet(qualifiedFindName);
  1639. while (itr)
  1640. {
  1641. BfTypeDef* typeDef = *itr;
  1642. if ((typeDef->mDefState != BfTypeDef::DefState_Deleted) &&
  1643. (!typeDef->mIsCombinedPartial))
  1644. {
  1645. if (typeDef->mFullNameEx == qualifiedFindName)
  1646. if (!_CheckCanSkipCtor(typeDef))
  1647. return false;
  1648. }
  1649. itr.MoveToNextHashMatch();
  1650. }
  1651. return true;
  1652. };
  1653. bool wantsCanSkipObjectCtor = _CheckCanSkipCtorByName("System.Object");
  1654. bool wantsCanSkipValueTypeCtor = _CheckCanSkipCtorByName("System.ValueType");
  1655. int wantPtrSize;
  1656. if ((mCompiler->mOptions.mMachineType == BfMachineType_x86) |
  1657. (mCompiler->mOptions.mMachineType == BfMachineType_ARM) ||
  1658. (mCompiler->mOptions.mMachineType == BfMachineType_Wasm32))
  1659. wantPtrSize = 4;
  1660. else
  1661. wantPtrSize = 8;
  1662. if ((wantPtrSize != mSystem->mPtrSize) || (wantsCanSkipObjectCtor != mCanSkipObjectCtor) || (wantsCanSkipValueTypeCtor != mCanSkipValueTypeCtor))
  1663. {
  1664. BfLogSysM("Full rebuild. Pointer: %d CanSkipObjectCtor:%d CanSkipValueTypeCtor:%d\n", wantPtrSize, wantsCanSkipObjectCtor, wantsCanSkipValueTypeCtor);
  1665. mSystem->mPtrSize = wantPtrSize;
  1666. mCanSkipObjectCtor = wantsCanSkipObjectCtor;
  1667. mCanSkipValueTypeCtor = wantsCanSkipValueTypeCtor;
  1668. auto intPtrType = mScratchModule->GetPrimitiveType(BfTypeCode_IntPtr);
  1669. auto uintPtrType = mScratchModule->GetPrimitiveType(BfTypeCode_UIntPtr);
  1670. if (intPtrType != NULL)
  1671. {
  1672. RebuildType(intPtrType);
  1673. mScratchModule->PopulateType(intPtrType);
  1674. }
  1675. if (uintPtrType != NULL)
  1676. {
  1677. RebuildType(uintPtrType);
  1678. mScratchModule->PopulateType(uintPtrType);
  1679. }
  1680. // Rebuild all types
  1681. for (auto type : mResolvedTypes)
  1682. {
  1683. RebuildType(type);
  1684. }
  1685. }
  1686. // Temporarily store failTypes - we may need to re-insert into them after another failure
  1687. auto failTypes = mFailTypes;
  1688. mFailTypes.Clear();
  1689. bool wantsDebugInfo = (mCompiler->mOptions.mEmitDebugInfo);
  1690. Array<BfTypeInstance*> defStateChangedQueue;
  1691. Array<BfTypeInstance*> defEmitParentCheckQueue;
  1692. Dictionary<String, uint64> lastWriteTimeMap;
  1693. bool rebuildAllFilesChanged = mCompiler->mRebuildChangedFileSet.Contains("*");
  1694. // Do primary 'rebuild' scan
  1695. for (auto type : mResolvedTypes)
  1696. {
  1697. auto typeInst = type->ToTypeInstance();
  1698. if (type == NULL)
  1699. {
  1700. BF_FATAL("We shouldn't have NULLs");
  1701. continue;
  1702. }
  1703. /*if ((!mCompiler->mIsResolveOnly) && (!type->IsNull()) && (!type->IsUnspecializedType()))
  1704. {
  1705. // We need to completely rebuild all types if we switch from having debug info to not having debug info
  1706. if ((typeInst != NULL) && (typeInst->mModule != NULL) && (typeInst->mModule->mHasDebugInfo != wantsDebugInfo))
  1707. {
  1708. RebuildType(type);
  1709. }
  1710. }*/
  1711. if (typeInst == NULL)
  1712. continue;
  1713. if (typeInst->IsDeleting())
  1714. continue;
  1715. auto typeDef = typeInst->mTypeDef;
  1716. if (typeDef->mEmitParent != NULL)
  1717. defEmitParentCheckQueue.Add(typeInst);
  1718. if (typeDef->mProject->mDisabled)
  1719. {
  1720. DeleteType(type);
  1721. continue;
  1722. }
  1723. typeInst->mRebuildFlags = BfTypeRebuildFlag_None;
  1724. if (typeDef->mIsPartial)
  1725. {
  1726. // This was a type that wasn't marked as partial before but now it is, so it doesn't need its own typedef
  1727. // since we will have a separate type instance for the combined partials
  1728. DeleteType(type);
  1729. continue;
  1730. }
  1731. if (typeInst->mCeTypeInfo != NULL)
  1732. {
  1733. bool changed = false;
  1734. for (auto& kv : typeInst->mCeTypeInfo->mRebuildMap)
  1735. {
  1736. mCompiler->mHasComptimeRebuilds = true;
  1737. if (kv.mKey.mKind == CeRebuildKey::Kind_File)
  1738. {
  1739. String* keyPtr = NULL;
  1740. uint64* valuePtr = NULL;
  1741. if (lastWriteTimeMap.TryAdd(kv.mKey.mString, &keyPtr, &valuePtr))
  1742. {
  1743. *valuePtr = BfpFile_GetTime_LastWrite(kv.mKey.mString.c_str());
  1744. }
  1745. if (*valuePtr != kv.mValue.mInt)
  1746. changed = true;
  1747. mCompiler->mRebuildFileSet.Add(kv.mKey.mString);
  1748. }
  1749. if ((kv.mKey.mKind == CeRebuildKey::Kind_File) || (kv.mKey.mKind == CeRebuildKey::Kind_Directory))
  1750. {
  1751. if ((rebuildAllFilesChanged) || (mCompiler->mRebuildChangedFileSet.Contains(kv.mKey.mString)))
  1752. changed = true;
  1753. mCompiler->mRebuildFileSet.Add(kv.mKey.mString);
  1754. }
  1755. }
  1756. if (changed)
  1757. {
  1758. RebuildType(typeInst);
  1759. }
  1760. }
  1761. if ((typeInst->mHotTypeData != NULL) && (!mCompiler->IsHotCompile()))
  1762. {
  1763. if (typeInst->mHotTypeData->GetLatestVersion()->mDeclHotCompileIdx != 0)
  1764. {
  1765. // Type was rebuilt with hot changes - rebuild back to normal
  1766. delete typeInst->mHotTypeData;
  1767. typeInst->mHotTypeData = NULL;
  1768. RebuildType(typeInst);
  1769. }
  1770. }
  1771. if (typeDef->mDefState == BfTypeDef::DefState_Defined)
  1772. {
  1773. BF_ASSERT(typeDef->mNextRevision == NULL);
  1774. continue;
  1775. }
  1776. if (typeDef->mDefState != BfTypeDef::DefState_New)
  1777. {
  1778. defStateChangedQueue.Add(typeInst);
  1779. }
  1780. }
  1781. // We consumed this above
  1782. mCompiler->mRebuildChangedFileSet.Clear();
  1783. for (auto typeInst : defStateChangedQueue)
  1784. {
  1785. BP_ZONE("BfContext::UpdateRevisedTypes defStateChangedQueue");
  1786. auto typeDef = typeInst->mTypeDef;
  1787. bool isTypeDefinedInContext = true;
  1788. if (typeDef->mEmitParent != NULL)
  1789. {
  1790. typeDef = typeDef->mEmitParent;
  1791. }
  1792. if (typeDef->mDefState == BfTypeDef::DefState_Deleted)
  1793. {
  1794. HandleChangedTypeDef(typeDef);
  1795. DeleteType(typeInst);
  1796. continue;
  1797. }
  1798. if (typeDef->mDefState == BfTypeDef::DefState_InlinedInternals_Changed)
  1799. {
  1800. TypeInlineMethodInternalsChanged(typeInst);
  1801. }
  1802. bool isSignatureChange = typeDef->mDefState == BfTypeDef::DefState_Signature_Changed;
  1803. if (((typeDef->mDefState == BfTypeDef::DefState_Internals_Changed) || (typeDef->mDefState == BfTypeDef::DefState_InlinedInternals_Changed)) &&
  1804. (typeInst->IsInterface()))
  1805. {
  1806. isSignatureChange = true;
  1807. }
  1808. if ((typeDef->mDefState != BfTypeDef::DefState_Refresh) && ((typeInst->mDependencyMap.mFlagsUnion & BfDependencyMap::DependencyFlag_ConstEval) != 0))
  1809. {
  1810. TypeConstEvalChanged(typeInst);
  1811. }
  1812. if (isSignatureChange)
  1813. {
  1814. TypeDataChanged(typeInst, true);
  1815. TypeMethodSignaturesChanged(typeInst);
  1816. }
  1817. /*if (!mCompiler->mIsResolveOnly)
  1818. {
  1819. OutputDebugStrF("TypeDef: %s %d %p\n", typeDef->mName.c_str(), typeDef->mDefState, &typeDef->mDefState);
  1820. }*/
  1821. RebuildType(typeInst);
  1822. }
  1823. for (auto typeInst : failTypes)
  1824. {
  1825. if (!typeInst->IsDeleting())
  1826. {
  1827. if (!typeInst->mTypeDef->mProject->mDisabled)
  1828. {
  1829. BfLogSysM("Rebuilding failed type %p\n", typeInst);
  1830. RebuildType(typeInst);
  1831. }
  1832. }
  1833. }
  1834. for (auto typeInst : defEmitParentCheckQueue)
  1835. {
  1836. if (typeInst->IsDeleting())
  1837. continue;
  1838. auto typeDef = typeInst->mTypeDef;
  1839. if (typeDef->mEmitParent != NULL)
  1840. {
  1841. if (typeDef->mDefState == BfTypeDef::DefState_Deleted)
  1842. {
  1843. BfLogSysM("Type %p typeDef %p deleted, setting to emitParent %p\n", typeInst, typeDef, typeDef->mEmitParent);
  1844. typeInst->mTypeDef = typeDef->mEmitParent;
  1845. }
  1846. else
  1847. {
  1848. auto emitTypeDef = typeDef;
  1849. typeDef = typeDef->mEmitParent;
  1850. if (typeDef->mNextRevision != NULL)
  1851. {
  1852. BfLogSysM("Type %p typeDef %p emitparent %p has next revision, setting emittedDirty\n", typeInst, emitTypeDef, typeDef);
  1853. emitTypeDef->mDefState = BfTypeDef::DefState_EmittedDirty;
  1854. }
  1855. }
  1856. }
  1857. }
  1858. //
  1859. {
  1860. AutoCrit autoCrit(mSystem->mDataLock);
  1861. auto options = &mCompiler->mOptions;
  1862. HashContext workspaceConfigHashCtx;
  1863. workspaceConfigHashCtx.MixinStr(options->mTargetTriple);
  1864. workspaceConfigHashCtx.Mixin(options->mForceRebuildIdx);
  1865. workspaceConfigHashCtx.Mixin(options->mMachineType);
  1866. workspaceConfigHashCtx.Mixin(options->mToolsetType);
  1867. workspaceConfigHashCtx.Mixin(options->mSIMDSetting);
  1868. workspaceConfigHashCtx.Mixin(options->mEmitDebugInfo);
  1869. workspaceConfigHashCtx.Mixin(options->mEmitLineInfo);
  1870. workspaceConfigHashCtx.Mixin(options->mNoFramePointerElim);
  1871. workspaceConfigHashCtx.Mixin(options->mInitLocalVariables);
  1872. workspaceConfigHashCtx.Mixin(options->mRuntimeChecks);
  1873. workspaceConfigHashCtx.Mixin(options->mAllowStructByVal);
  1874. workspaceConfigHashCtx.Mixin(options->mEmitDynamicCastCheck);
  1875. workspaceConfigHashCtx.Mixin(options->mAllowHotSwapping);
  1876. workspaceConfigHashCtx.Mixin(options->mObjectHasDebugFlags);
  1877. workspaceConfigHashCtx.Mixin(options->mEnableRealtimeLeakCheck);
  1878. workspaceConfigHashCtx.Mixin(options->mEmitObjectAccessCheck);
  1879. workspaceConfigHashCtx.Mixin(options->mArithmeticChecks);
  1880. workspaceConfigHashCtx.Mixin(options->mEnableCustodian);
  1881. workspaceConfigHashCtx.Mixin(options->mEnableSideStack);
  1882. workspaceConfigHashCtx.Mixin(options->mHasVDataExtender);
  1883. workspaceConfigHashCtx.Mixin(options->mDebugAlloc);
  1884. workspaceConfigHashCtx.Mixin(options->mOmitDebugHelpers);
  1885. workspaceConfigHashCtx.Mixin(options->mUseDebugBackingParams);
  1886. workspaceConfigHashCtx.Mixin(options->mWriteIR);
  1887. workspaceConfigHashCtx.Mixin(options->mGenerateObj);
  1888. workspaceConfigHashCtx.Mixin(options->mAllocStackCount);
  1889. workspaceConfigHashCtx.Mixin(options->mExtraResolveChecks);
  1890. workspaceConfigHashCtx.Mixin(options->mMaxSplatRegs);
  1891. workspaceConfigHashCtx.MixinStr(options->mMallocLinkName);
  1892. workspaceConfigHashCtx.MixinStr(options->mFreeLinkName);
  1893. for (auto& typeOptions : mSystem->mTypeOptions)
  1894. {
  1895. workspaceConfigHashCtx.Mixin(typeOptions.mTypeFilters.size());
  1896. for (auto& filter : typeOptions.mTypeFilters)
  1897. workspaceConfigHashCtx.MixinStr(filter);
  1898. workspaceConfigHashCtx.Mixin(typeOptions.mAttributeFilters.size());
  1899. for (auto& filter : typeOptions.mAttributeFilters)
  1900. workspaceConfigHashCtx.MixinStr(filter);
  1901. workspaceConfigHashCtx.Mixin(typeOptions.mSIMDSetting);
  1902. workspaceConfigHashCtx.Mixin(typeOptions.mOptimizationLevel);
  1903. workspaceConfigHashCtx.Mixin(typeOptions.mEmitDebugInfo);
  1904. workspaceConfigHashCtx.Mixin(typeOptions.mAndFlags);
  1905. workspaceConfigHashCtx.Mixin(typeOptions.mOrFlags);
  1906. workspaceConfigHashCtx.Mixin(typeOptions.mReflectMethodFilters.size());
  1907. for (auto& filter : typeOptions.mReflectMethodFilters)
  1908. {
  1909. workspaceConfigHashCtx.MixinStr(filter.mFilter);
  1910. workspaceConfigHashCtx.Mixin(filter.mAndFlags);
  1911. workspaceConfigHashCtx.Mixin(filter.mOrFlags);
  1912. }
  1913. workspaceConfigHashCtx.Mixin(typeOptions.mReflectMethodAttributeFilters.size());
  1914. for (auto& filter : typeOptions.mReflectMethodAttributeFilters)
  1915. {
  1916. workspaceConfigHashCtx.MixinStr(filter.mFilter);
  1917. workspaceConfigHashCtx.Mixin(filter.mAndFlags);
  1918. workspaceConfigHashCtx.Mixin(filter.mOrFlags);
  1919. }
  1920. workspaceConfigHashCtx.Mixin(typeOptions.mAllocStackTraceDepth);
  1921. }
  1922. // for (auto project : mSystem->mProjects)
  1923. // {
  1924. // workspaceConfigHashCtx.MixinStr(project->mName);
  1925. // }
  1926. Val128 workspaceConfigHash = workspaceConfigHashCtx.Finish128();
  1927. mSystem->mWorkspaceConfigChanged = mSystem->mWorkspaceConfigHash != workspaceConfigHash;
  1928. if (mSystem->mWorkspaceConfigChanged)
  1929. {
  1930. // If the type options have changed, we know we will rebuild all types and thus
  1931. // remap their mTypeOptionsIdx
  1932. mSystem->mMergedTypeOptions.Clear();
  1933. mSystem->mWorkspaceConfigHash = workspaceConfigHash;
  1934. }
  1935. for (auto project : mSystem->mProjects)
  1936. {
  1937. HashContext buildConfigHashCtx;
  1938. buildConfigHashCtx.Mixin(workspaceConfigHash);
  1939. if (!mCompiler->mIsResolveOnly)
  1940. {
  1941. auto& codeGenOptions = project->mCodeGenOptions;
  1942. buildConfigHashCtx.MixinStr(mCompiler->mOutputDirectory);
  1943. buildConfigHashCtx.Mixin(project->mAlwaysIncludeAll);
  1944. buildConfigHashCtx.Mixin(project->mSingleModule);
  1945. bool isTestConfig = project->mTargetType == BfTargetType_BeefTest;
  1946. buildConfigHashCtx.Mixin(isTestConfig);
  1947. buildConfigHashCtx.Mixin(codeGenOptions.mOptLevel);
  1948. buildConfigHashCtx.Mixin(codeGenOptions.mSizeLevel);
  1949. buildConfigHashCtx.Mixin(codeGenOptions.mUseCFLAA);
  1950. buildConfigHashCtx.Mixin(codeGenOptions.mUseNewSROA);
  1951. buildConfigHashCtx.Mixin(codeGenOptions.mDisableTailCalls);
  1952. buildConfigHashCtx.Mixin(codeGenOptions.mDisableUnitAtATime);
  1953. buildConfigHashCtx.Mixin(codeGenOptions.mDisableUnrollLoops);
  1954. buildConfigHashCtx.Mixin(codeGenOptions.mBBVectorize);
  1955. buildConfigHashCtx.Mixin(codeGenOptions.mSLPVectorize);
  1956. buildConfigHashCtx.Mixin(codeGenOptions.mLoopVectorize);
  1957. buildConfigHashCtx.Mixin(codeGenOptions.mRerollLoops);
  1958. buildConfigHashCtx.Mixin(codeGenOptions.mLoadCombine);
  1959. buildConfigHashCtx.Mixin(codeGenOptions.mDisableGVNLoadPRE);
  1960. buildConfigHashCtx.Mixin(codeGenOptions.mVerifyInput);
  1961. buildConfigHashCtx.Mixin(codeGenOptions.mVerifyOutput);
  1962. buildConfigHashCtx.Mixin(codeGenOptions.mStripDebug);
  1963. buildConfigHashCtx.Mixin(codeGenOptions.mMergeFunctions);
  1964. buildConfigHashCtx.Mixin(codeGenOptions.mEnableMLSM);
  1965. buildConfigHashCtx.Mixin(codeGenOptions.mRunSLPAfterLoopVectorization);
  1966. buildConfigHashCtx.Mixin(codeGenOptions.mUseGVNAfterVectorization);
  1967. }
  1968. buildConfigHashCtx.Mixin(project->mDisabled);
  1969. buildConfigHashCtx.Mixin(project->mTargetType);
  1970. for (auto dep : project->mDependencies)
  1971. {
  1972. String depName = dep->mName;
  1973. buildConfigHashCtx.MixinStr(depName);
  1974. }
  1975. Val128 buildConfigHash = buildConfigHashCtx.Finish128();
  1976. HashContext vDataConfigHashCtx;
  1977. vDataConfigHashCtx.Mixin(buildConfigHash);
  1978. vDataConfigHashCtx.MixinStr(project->mStartupObject);
  1979. vDataConfigHashCtx.Mixin(project->mTargetType);
  1980. //Val128 vDataConfigHash = buildConfigHash;
  1981. //vDataConfigHash = Hash128(project->mStartupObject.c_str(), (int)project->mStartupObject.length() + 1, vDataConfigHash);
  1982. //vDataConfigHash = Hash128(&project->mTargetType, sizeof(project->mTargetType), vDataConfigHash);
  1983. auto vDataConfigHash = vDataConfigHashCtx.Finish128();
  1984. project->mBuildConfigChanged = buildConfigHash != project->mBuildConfigHash;
  1985. project->mBuildConfigHash = buildConfigHash;
  1986. project->mVDataConfigHash = vDataConfigHash;
  1987. }
  1988. }
  1989. Array<BfModule*> moduleRebuildList;
  1990. for (int moduleIdx = 0; moduleIdx < (int)mModules.size(); moduleIdx++)
  1991. {
  1992. //mCompiler->mOutputDirectory
  1993. auto module = mModules[moduleIdx];
  1994. // This logic needs to run on both us and our mOptModule
  1995. //for (int subModuleIdx = 0; subModuleIdx < 2; subModuleIdx++)
  1996. auto subModule = module;
  1997. while (subModule != NULL)
  1998. {
  1999. //auto subModule = module;
  2000. //if (subModuleIdx == -1)
  2001. //subModule = module->mOptModule;
  2002. // If we canceled the last build, we could have specialized method modules referring to projects that have
  2003. // since been deleted or disabled - so remove those
  2004. for (auto methodModuleItr = subModule->mSpecializedMethodModules.begin(); methodModuleItr != subModule->mSpecializedMethodModules.end(); )
  2005. {
  2006. auto& projectList = methodModuleItr->mKey;
  2007. auto specModule = methodModuleItr->mValue;
  2008. bool hasDisabledProject = false;
  2009. for (auto checkProject : projectList)
  2010. hasDisabledProject |= checkProject->mDisabled;
  2011. if (hasDisabledProject)
  2012. {
  2013. delete specModule;
  2014. methodModuleItr = subModule->mSpecializedMethodModules.Remove(methodModuleItr);
  2015. }
  2016. else
  2017. ++methodModuleItr;
  2018. }
  2019. subModule = subModule->mNextAltModule;
  2020. }
  2021. if ((module->mProject != NULL) && (module->mProject->mDisabled))
  2022. {
  2023. continue;
  2024. }
  2025. // Module previously had error so we have to rebuild the whole thing
  2026. bool needsModuleRebuild = module->mHadBuildError;
  2027. if ((module->mHadHotObjectWrites) && (!mCompiler->IsHotCompile()))
  2028. {
  2029. module->mHadHotObjectWrites = false; // Handled, can reset now
  2030. needsModuleRebuild = true;
  2031. }
  2032. if (module->mProject != NULL)
  2033. {
  2034. if ((module->mIsHotModule) && (mCompiler->mOptions.mHotProject == NULL))
  2035. needsModuleRebuild = true;
  2036. if (module->mProject->mBuildConfigChanged)
  2037. needsModuleRebuild = true;
  2038. }
  2039. if (mCompiler->mInterfaceSlotCountChanged)
  2040. {
  2041. if ((module->mUsedSlotCount >= 0) && (module->mUsedSlotCount != mCompiler->mMaxInterfaceSlots))
  2042. needsModuleRebuild = true;
  2043. }
  2044. if (needsModuleRebuild)
  2045. moduleRebuildList.push_back(module);
  2046. if (module->mIsSpecialModule) // vdata, external, data
  2047. continue;
  2048. bool wantMethodSpecializations = !mCompiler->mIsResolveOnly;
  2049. // We don't really need this on for resolveOnly passes, but this is useful to force on for debugging.
  2050. // The following block is fairly useful for detecting dependency errors.
  2051. wantMethodSpecializations = true;
  2052. }
  2053. mCompiler->mInterfaceSlotCountChanged = false;
  2054. for (auto module : moduleRebuildList)
  2055. {
  2056. if (!module->mIsDeleting)
  2057. module->StartNewRevision();
  2058. }
  2059. // Ensure even unspecialized types an interfaces get rebuilt
  2060. // In particular, this is needed if we build a non-hotswap config and then
  2061. // build a hotswap config-- we need to make sure all those methods have
  2062. // HotMethodData
  2063. if (mSystem->mWorkspaceConfigChanged)
  2064. {
  2065. for (auto type : mResolvedTypes)
  2066. {
  2067. RebuildType(type);
  2068. }
  2069. }
  2070. }
  2071. void BfContext::VerifyTypeLookups(BfTypeInstance* typeInst)
  2072. {
  2073. for (auto& lookupEntryPair : typeInst->mLookupResults)
  2074. {
  2075. BfTypeLookupEntry& lookupEntry = lookupEntryPair.mKey;
  2076. bool isDirty = false;
  2077. if (lookupEntry.mName.IsEmpty())
  2078. {
  2079. // If the name lookup failed before, thats because we didn't have the right atoms. Are there new atoms now?
  2080. if (lookupEntry.mAtomUpdateIdx != mSystem->mAtomUpdateIdx)
  2081. isDirty = true;
  2082. }
  2083. else
  2084. {
  2085. // If any atoms have been placed in the graveyard, typesHash will be zero and thus cause a rebuild
  2086. uint32 atomUpdateIdx = lookupEntry.mName.GetAtomUpdateIdx();
  2087. if (atomUpdateIdx == 0)
  2088. {
  2089. isDirty = true;
  2090. }
  2091. else
  2092. {
  2093. // Sanity check, mostly checking that useTypeDef wasn't deleted
  2094. BF_ASSERT((lookupEntry.mUseTypeDef->mName->mAtomUpdateIdx >= 1) && (lookupEntry.mUseTypeDef->mName->mAtomUpdateIdx <= mSystem->mAtomUpdateIdx));
  2095. // Only do the actual lookup if types were added or removed whose name is contained in one of the name parts referenced
  2096. if (atomUpdateIdx != lookupEntry.mAtomUpdateIdx)
  2097. {
  2098. // NOTE: we purposely don't use mNextRevision here. If the the was NOT rebuilt then that means we didn't actually rebuild
  2099. // so the mNextRevision will be ignored
  2100. auto useTypeDef = lookupEntry.mUseTypeDef;
  2101. BfTypeDef* ambiguousTypeDef = NULL;
  2102. BfTypeLookupResult* lookupResult = &lookupEntryPair.mValue;
  2103. BfTypeLookupResultCtx lookupResultCtx;
  2104. lookupResultCtx.mResult = lookupResult;
  2105. lookupResultCtx.mIsVerify = true;
  2106. BfTypeDef* result = typeInst->mModule->FindTypeDefRaw(lookupEntry.mName, lookupEntry.mNumGenericParams, typeInst, useTypeDef, NULL, &lookupResultCtx);
  2107. if ((result == NULL) && (lookupResult->mFoundInnerType))
  2108. {
  2109. // Allow this- if there were new types added then the types would be rebuilt already
  2110. }
  2111. else if (result != lookupResult->mTypeDef)
  2112. {
  2113. isDirty = true;
  2114. }
  2115. else
  2116. lookupEntry.mAtomUpdateIdx = atomUpdateIdx;
  2117. }
  2118. }
  2119. }
  2120. if (isDirty)
  2121. {
  2122. // Clear lookup results to avoid infinite recursion
  2123. typeInst->mLookupResults.Clear();
  2124. // We need to treat this lookup as if it changed the whole type signature
  2125. TypeDataChanged(typeInst, true);
  2126. TypeMethodSignaturesChanged(typeInst);
  2127. RebuildType(typeInst);
  2128. break;
  2129. }
  2130. }
  2131. }
  2132. void BfContext::GenerateModuleName_TypeInst(BfTypeInstance* typeInst, String& name)
  2133. {
  2134. auto resolveModule = typeInst->mIsReified ? mScratchModule : mUnreifiedModule;
  2135. auto outerType = resolveModule->GetOuterType(typeInst);
  2136. int startGenericIdx = 0;
  2137. if (outerType != NULL)
  2138. {
  2139. startGenericIdx = (int)outerType->mTypeDef->mGenericParamDefs.size();
  2140. GenerateModuleName_Type(outerType, name);
  2141. /*if ((!name.empty()) && (name[name.length() - 1] != '_'))
  2142. name += '_';*/
  2143. }
  2144. else
  2145. {
  2146. for (int i = 0; i < typeInst->mTypeDef->mNamespace.mSize; i++)
  2147. {
  2148. auto atom = typeInst->mTypeDef->mNamespace.mParts[i];
  2149. if ((!name.empty()) && (name[name.length() - 1] != '_'))
  2150. name += '_';
  2151. name += atom->mString;
  2152. }
  2153. }
  2154. if ((!name.empty()) && (name[name.length() - 1] != '_'))
  2155. name += '_';
  2156. if (typeInst->mTypeDef->IsGlobalsContainer())
  2157. name += "GLOBALS_";
  2158. else
  2159. name += typeInst->mTypeDef->mName->mString;
  2160. if (typeInst->IsClosure())
  2161. {
  2162. auto closureType = (BfClosureType*)typeInst;
  2163. name += closureType->mNameAdd;
  2164. return;
  2165. }
  2166. if (typeInst->mGenericTypeInfo != NULL)
  2167. {
  2168. for (int genericIdx = startGenericIdx; genericIdx < (int)typeInst->mGenericTypeInfo->mTypeGenericArguments.size(); genericIdx++)
  2169. {
  2170. auto type = typeInst->mGenericTypeInfo->mTypeGenericArguments[genericIdx];
  2171. GenerateModuleName_Type(type, name);
  2172. }
  2173. }
  2174. }
  2175. void BfContext::GenerateModuleName_Type(BfType* type, String& name)
  2176. {
  2177. if ((!name.empty()) && (name[name.length() - 1] != '_'))
  2178. name += '_';
  2179. if (type->IsBoxed())
  2180. {
  2181. auto boxedType = (BfBoxedType*)type;
  2182. if (boxedType->IsBoxedStructPtr())
  2183. name += "BOXPTR_";
  2184. else
  2185. name += "BOX_";
  2186. GenerateModuleName_Type(boxedType->mElementType, name);
  2187. return;
  2188. }
  2189. if (type->IsPrimitiveType())
  2190. {
  2191. auto primType = (BfPrimitiveType*)type;
  2192. name += primType->mTypeDef->mName->mString;
  2193. return;
  2194. }
  2195. if (type->IsPointer())
  2196. {
  2197. auto ptrType = (BfPointerType*)type;
  2198. name += "PTR_";
  2199. GenerateModuleName_Type(ptrType->mElementType, name);
  2200. return;
  2201. }
  2202. if (type->IsTuple())
  2203. {
  2204. auto tupleType = (BfTypeInstance*)type;
  2205. name += "TUPLE_";
  2206. for (int fieldIdx = 0; fieldIdx < (int)tupleType->mFieldInstances.size(); fieldIdx++)
  2207. {
  2208. BfFieldInstance* fieldInstance = &tupleType->mFieldInstances[fieldIdx];
  2209. BfFieldDef* fieldDef = fieldInstance->GetFieldDef();
  2210. String fieldName = fieldDef->mName;
  2211. if ((fieldName[0] < '0') || (fieldName[0] > '9'))
  2212. name += StrFormat("U%d@%s", fieldName.length() + 1, fieldName.c_str());
  2213. GenerateModuleName_Type(fieldInstance->mResolvedType, name);
  2214. }
  2215. return;
  2216. }
  2217. if (type->IsDelegateFromTypeRef() || type->IsFunctionFromTypeRef())
  2218. {
  2219. auto typeInst = type->ToTypeInstance();
  2220. auto delegateInfo = type->GetDelegateInfo();
  2221. auto methodDef = typeInst->mTypeDef->mMethods[0];
  2222. if (type->IsDelegateFromTypeRef())
  2223. name += "DELEGATE_";
  2224. else
  2225. name += "FUNCTION_";
  2226. GenerateModuleName_Type(mScratchModule->ResolveTypeRef(methodDef->mReturnTypeRef), name);
  2227. name += "_";
  2228. for (int paramIdx = 0; paramIdx < methodDef->mParams.size(); paramIdx++)
  2229. {
  2230. if (paramIdx > 0)
  2231. name += "_";
  2232. auto paramDef = methodDef->mParams[paramIdx];
  2233. GenerateModuleName_Type(mScratchModule->ResolveTypeRef(paramDef->mTypeRef), name);
  2234. name += "_";
  2235. name += paramDef->mName;
  2236. }
  2237. return;
  2238. }
  2239. if (type->IsMethodRef())
  2240. {
  2241. auto methodRefType = (BfMethodRefType*)type;
  2242. BfMethodInstance* methodInstance = methodRefType->mMethodRef;
  2243. name += "METHOD_";
  2244. GenerateModuleName_Type(methodInstance->GetOwner(), name);
  2245. name += "_";
  2246. String addName = methodInstance->mMethodDef->mName;
  2247. for (auto&& c : addName)
  2248. {
  2249. if ((c == '$') || (c == '@'))
  2250. c = '_';
  2251. }
  2252. name += addName;
  2253. }
  2254. if (type->IsConstExprValue())
  2255. {
  2256. auto constExprType = (BfConstExprValueType*)type;
  2257. if (BfIRConstHolder::IsInt(constExprType->mValue.mTypeCode))
  2258. {
  2259. if (constExprType->mValue.mInt64 < 0)
  2260. name += StrFormat("_%ld", -constExprType->mValue.mInt64);
  2261. else
  2262. name += StrFormat("%ld", constExprType->mValue.mInt64);
  2263. return;
  2264. }
  2265. }
  2266. auto typeInst = type->ToTypeInstance();
  2267. if (typeInst != NULL)
  2268. {
  2269. GenerateModuleName_TypeInst(typeInst, name);
  2270. return;
  2271. }
  2272. }
  2273. String BfContext::GenerateModuleName(BfTypeInstance* typeInst)
  2274. {
  2275. String name;
  2276. GenerateModuleName_Type(typeInst, name);
  2277. int maxChars = 80;
  2278. if (name.length() > 80)
  2279. {
  2280. name.RemoveToEnd(80);
  2281. name += "__";
  2282. }
  2283. for (int i = 0; i < (int)name.length(); i++)
  2284. {
  2285. char c = name[i];
  2286. if (c == '@')
  2287. name[i] = '_';
  2288. }
  2289. String tryName = name;
  2290. for (int i = 2; true; i++)
  2291. {
  2292. if (!mUsedModuleNames.Contains(ToUpper(tryName)))
  2293. return tryName;
  2294. tryName = name + StrFormat("_%d", i);
  2295. }
  2296. return name;
  2297. }
  2298. bool BfContext::IsSentinelMethod(BfMethodInstance* methodInstance)
  2299. {
  2300. return (methodInstance != NULL) && ((uintptr)(methodInstance) <= 1);
  2301. }
  2302. void BfContext::VerifyTypeLookups()
  2303. {
  2304. BP_ZONE("BfContext::VerifyTypeLookups");
  2305. for (auto type : mResolvedTypes)
  2306. {
  2307. auto typeInst = type->ToTypeInstance();
  2308. if ((typeInst != NULL) && (!typeInst->IsDeleting()) && (!typeInst->IsIncomplete()))
  2309. {
  2310. VerifyTypeLookups(typeInst);
  2311. }
  2312. }
  2313. }
  2314. // When we are rebuilding 'typeInst' and we want to make sure that we rebuild all the methods that were
  2315. // actively referenced previously, this method will generate BfMethodSpecializationRequest for all used
  2316. // methods from previously-built modules
  2317. void BfContext::QueueMethodSpecializations(BfTypeInstance* typeInst, bool checkSpecializedMethodRebuildFlag)
  2318. {
  2319. BF_ASSERT(!typeInst->IsDeleting());
  2320. BP_ZONE("BfContext::QueueMethodSpecializations");
  2321. auto module = typeInst->mModule;
  2322. if (module == NULL)
  2323. return;
  2324. BfLogSysM("QueueMethodSpecializations typeInst %p module %p\n", typeInst, module);
  2325. if (!checkSpecializedMethodRebuildFlag)
  2326. {
  2327. // Modules that have already rebuilt have already explicitly added their method specialization requests.
  2328. // This pass is just for handling rebuilding old specialization requests
  2329. if (module->mRevision == mCompiler->mRevision)
  2330. return;
  2331. }
  2332. // Find any method specialization requests for types that are rebuilding, but from
  2333. // modules that are NOT rebuilding to be sure we generate those. Failure to do this
  2334. // will cause a link error from an old module
  2335. for (auto& methodRefKV : typeInst->mSpecializedMethodReferences)
  2336. {
  2337. auto& methodRef = methodRefKV.mKey;
  2338. auto& specializedMethodRefInfo = methodRefKV.mValue;
  2339. if (checkSpecializedMethodRebuildFlag)
  2340. {
  2341. if ((methodRef.mTypeInstance->mRebuildFlags & BfTypeRebuildFlag_SpecializedMethodRebuild) == 0)
  2342. continue;
  2343. }
  2344. else
  2345. {
  2346. if ((methodRef.mTypeInstance->mModule == NULL) ||
  2347. (methodRef.mTypeInstance->mModule->mRevision != mCompiler->mRevision))
  2348. continue;
  2349. }
  2350. bool allowMismatch = false;
  2351. if ((methodRef.mTypeInstance->IsInstanceOf(mCompiler->mInternalTypeDef)) || (methodRef.mTypeInstance->IsInstanceOf(mCompiler->mGCTypeDef)))
  2352. allowMismatch = true;
  2353. // The signature hash better not have changed, because if it did then we should have rebuilding 'module'
  2354. // because of dependencies! This infers a dependency error.
  2355. int newSignatureHash = (int)methodRef.mTypeInstance->mTypeDef->mSignatureHash;
  2356. BF_ASSERT((newSignatureHash == methodRef.mSignatureHash) || (allowMismatch));
  2357. BfMethodDef* methodDef = NULL;
  2358. if (methodRef.mMethodNum < methodRef.mTypeInstance->mTypeDef->mMethods.mSize)
  2359. methodDef = methodRef.mTypeInstance->mTypeDef->mMethods[methodRef.mMethodNum];
  2360. auto targetContext = methodRef.mTypeInstance->mContext;
  2361. BfMethodSpecializationRequest* specializationRequest = targetContext->mMethodSpecializationWorkList.Alloc();
  2362. if (specializedMethodRefInfo.mHasReifiedRef)
  2363. specializationRequest->mFromModule = typeInst->mModule;
  2364. else
  2365. specializationRequest->mFromModule = mUnreifiedModule;
  2366. specializationRequest->mFromModuleRevision = typeInst->mModule->mRevision;
  2367. specializationRequest->mMethodIdx = methodRef.mMethodNum;
  2368. //specializationRequest->mMethodDef = methodRef.mTypeInstance->mTypeDef->mMethods[methodRef.mMethodNum];
  2369. specializationRequest->mMethodGenericArguments = methodRef.mMethodGenericArguments;
  2370. specializationRequest->mType = methodRef.mTypeInstance;
  2371. BfLogSysM("QueueMethodSpecializations typeInst %p specializationRequest %p methodDef %p fromModule %p\n", typeInst, specializationRequest, methodDef, specializationRequest->mFromModule);
  2372. }
  2373. }
  2374. void BfContext::MarkAsReferenced(BfDependedType* depType)
  2375. {
  2376. BF_ASSERT((depType->mRebuildFlags & BfTypeRebuildFlag_AwaitingReference) != 0);
  2377. depType->mRebuildFlags = (BfTypeRebuildFlags)(depType->mRebuildFlags & ~BfTypeRebuildFlag_AwaitingReference);
  2378. // bool madeFullPass = true;
  2379. // if (mCompiler->mCanceling)
  2380. // madeFullPass = false;
  2381. // if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mParser != NULL))
  2382. // madeFullPass = false;
  2383. // Having this in caused errors when we canceled and then compiled again
  2384. auto typeInst = depType->ToTypeInstance();
  2385. if (typeInst != NULL)
  2386. {
  2387. QueueMethodSpecializations(typeInst, false);
  2388. }
  2389. }
  2390. static int gCheckIdx = 0;
  2391. template <typename T>
  2392. void ReportRemovedItem(T workItem)
  2393. {
  2394. }
  2395. template <>
  2396. void ReportRemovedItem<BfMethodProcessRequest*>(BfMethodProcessRequest* workItem)
  2397. {
  2398. if (workItem->mMethodInstance != NULL)
  2399. BfLogSys(workItem->mFromModule->mSystem, "DoRemoveInvalidWorkItems MethodInstance:%p\n", workItem->mMethodInstance);
  2400. }
  2401. template <typename T>
  2402. void DoRemoveInvalidWorkItems(BfContext* bfContext, WorkQueue<T>& workList, bool requireValidType)
  2403. {
  2404. //auto itr = workList.begin();
  2405. //while (itr != workList.end())
  2406. for (int workIdx = 0; workIdx < (int)workList.size(); workIdx++)
  2407. {
  2408. gCheckIdx++;
  2409. //auto& workItem = *itr;
  2410. auto workItem = workList[workIdx];
  2411. if (workItem == NULL)
  2412. continue;
  2413. BfTypeInstance* typeInst = workItem->mType->ToTypeInstance();
  2414. if ((workItem->mType->IsDeleting()) ||
  2415. (workItem->mType->mRebuildFlags & BfTypeRebuildFlag_Deleted) ||
  2416. ((workItem->mRevision != -1) && (typeInst != NULL) && (workItem->mRevision != typeInst->mRevision)) ||
  2417. ((workItem->mSignatureRevision != -1) && (typeInst != NULL) && (workItem->mSignatureRevision != typeInst->mSignatureRevision)) ||
  2418. ((workItem->mFromModuleRevision != -1) && (workItem->mFromModuleRevision != workItem->mFromModule->mRevision)) ||
  2419. ((workItem->mFromModule != NULL) && (workItem->mFromModule->mIsDeleting)) ||
  2420. ((requireValidType) && (workItem->mType->mDefineState == BfTypeDefineState_Undefined)))
  2421. {
  2422. if (typeInst != NULL)
  2423. {
  2424. BF_ASSERT(
  2425. (workItem->mRevision < typeInst->mRevision) ||
  2426. ((workItem->mFromModule != NULL) && (workItem->mFromModuleRebuildIdx != -1) && (workItem->mFromModule->mRebuildIdx != workItem->mFromModuleRebuildIdx)) ||
  2427. ((workItem->mRevision == typeInst->mRevision) && (workItem->mType->mRebuildFlags & BfTypeRebuildFlag_Deleted)) ||
  2428. (workItem->mType->mDefineState == BfTypeDefineState_Undefined));
  2429. }
  2430. BfLogSys(bfContext->mSystem, "Removing work item: %p ReqId:%d\n", workItem, workItem->mReqId);
  2431. ReportRemovedItem(workItem);
  2432. workIdx = workList.RemoveAt(workIdx);
  2433. //itr = workList.erase(itr);
  2434. }
  2435. //else
  2436. //++itr;
  2437. }
  2438. }
  2439. void BfContext::RemoveInvalidFailTypes()
  2440. {
  2441. for (auto itr = mFailTypes.begin(); itr != mFailTypes.end(); )
  2442. {
  2443. auto typeInst = *itr;
  2444. BfLogSysM("Checking FailType: %p\n", typeInst);
  2445. if ((typeInst->IsDeleting()) || (typeInst->mRebuildFlags & BfTypeRebuildFlag_Deleted))
  2446. {
  2447. BfLogSysM("Removing Invalid FailType: %p\n", typeInst);
  2448. itr = mFailTypes.Remove(itr);
  2449. }
  2450. else
  2451. itr++;
  2452. }
  2453. }
  2454. // These work items are left over from a previous canceled run, OR from explicit method
  2455. // specializations being rebuilt when the type is rebuilt
  2456. void BfContext::RemoveInvalidWorkItems()
  2457. {
  2458. BfLogSysM("RemoveInvalidWorkItems %p\n", this);
  2459. // Delete any request that include deleted types.
  2460. // For the list items referring to methods we check the LLVMType because that lets us know
  2461. // whether or not the type has been reset since these work items were requested
  2462. DoRemoveInvalidWorkItems<BfMethodProcessRequest>(this, mMethodWorkList, true);
  2463. DoRemoveInvalidWorkItems<BfInlineMethodRequest>(this, mInlineMethodWorkList, true);
  2464. //TODO: We used to pass true into requireValidType, but this gets populated from UpdateRevisedTypes right before RemoveInvalidWorkItems,
  2465. // so we're passing false in here now. Don't just switch it back and forth - find why 'false' was causing an issue.
  2466. // Same with mMethodSpecializationWorkList
  2467. DoRemoveInvalidWorkItems<BfTypeProcessRequest>(this, mPopulateTypeWorkList, false);
  2468. DoRemoveInvalidWorkItems<BfMethodSpecializationRequest>(this, mMethodSpecializationWorkList, false/*true*/);
  2469. DoRemoveInvalidWorkItems<BfTypeRefVerifyRequest>(this, mTypeRefVerifyWorkList, false);
  2470. #ifdef _DEBUG
  2471. for (auto& workItem : mMethodWorkList)
  2472. {
  2473. //BF_ASSERT(workItem.mMethodInstance->mDeclModule != NULL);
  2474. }
  2475. for (auto workItem : mMethodSpecializationWorkList)
  2476. {
  2477. if (workItem == NULL)
  2478. continue;
  2479. for (auto genericArg : workItem->mMethodGenericArguments)
  2480. {
  2481. BF_ASSERT((genericArg->mRebuildFlags & BfTypeRebuildFlag_Deleted) == 0);
  2482. BF_ASSERT(!genericArg->IsDeleting());
  2483. }
  2484. }
  2485. #endif
  2486. if (mCompiler->mRevision == mScratchModule->mRevision)
  2487. {
  2488. // We have deleted the old module so we need to recreate unspecialized LLVMFunctions
  2489. for (auto workListItem : mMethodWorkList)
  2490. {
  2491. if ((workListItem != NULL) && (workListItem->mType->IsUnspecializedType()))
  2492. {
  2493. workListItem->mMethodInstance->mIRFunction = BfIRFunction();
  2494. }
  2495. }
  2496. }
  2497. RemoveInvalidFailTypes();
  2498. }
  2499. void BfContext::RemapObject()
  2500. {
  2501. if (mCompiler->mBfObjectTypeDef == NULL)
  2502. return;
  2503. // There are several types that get their LLVM type mapped to Object, so make sure to remap that
  2504. // for when Object itself gets recreated
  2505. auto objectType = mScratchModule->ResolveTypeDef(mCompiler->mBfObjectTypeDef, BfPopulateType_Declaration);
  2506. auto objectTypeInst = objectType->ToTypeInstance();
  2507. if (objectTypeInst->mRevision == mMappedObjectRevision)
  2508. return;
  2509. mMappedObjectRevision = objectTypeInst->mRevision;
  2510. for (int paramKind = 0; paramKind < 2; paramKind++)
  2511. {
  2512. for (int paramIdx = 0; paramIdx < (int)mGenericParamTypes[paramKind].size(); paramIdx++)
  2513. {
  2514. auto genericParam = mGenericParamTypes[paramKind][paramIdx];
  2515. genericParam->mSize = objectType->mSize;
  2516. genericParam->mAlign = objectType->mAlign;
  2517. }
  2518. }
  2519. auto varType = mScratchModule->GetPrimitiveType(BfTypeCode_Var);
  2520. varType->mSize = objectType->mSize;
  2521. varType->mAlign = objectType->mAlign;
  2522. }
  2523. void BfContext::CheckSpecializedErrorData()
  2524. {
  2525. //TODO: Unecessary now?
  2526. /*for (auto& specializedErrorData : mSpecializedErrorData)
  2527. {
  2528. bool ignoreError = false;
  2529. if (specializedErrorData.mRefType->IsDeleting())
  2530. ignoreError = true;
  2531. if (specializedErrorData.mMethodInstance != NULL)
  2532. {
  2533. for (auto genericArg : specializedErrorData.mMethodInstance->mMethodGenericArguments)
  2534. if (genericArg->IsDeleting())
  2535. ignoreError = true;
  2536. }
  2537. if (ignoreError)
  2538. {
  2539. if (specializedErrorData.mMethodInstance->mIRFunction != NULL)
  2540. {
  2541. specializedErrorData.mMethodInstance->mIRFunction->eraseFromParent();
  2542. specializedErrorData.mMethodInstance->mIRFunction = NULL;
  2543. }
  2544. specializedErrorData.mError->mIgnore = true;
  2545. }
  2546. else
  2547. {
  2548. specializedErrorData.mModule->mHadBuildError = true;
  2549. mFailTypes.insert(specializedErrorData.mRefType);
  2550. }
  2551. }*/
  2552. }
  2553. void BfContext::TryUnreifyModules()
  2554. {
  2555. BP_ZONE("BfContext::TryUnreifyModules");
  2556. for (auto module : mModules)
  2557. {
  2558. if (module->mIsSpecialModule)
  2559. continue;
  2560. if (!module->mIsReified)
  2561. continue;
  2562. if (module->mLastUsedRevision == mCompiler->mRevision)
  2563. continue;
  2564. bool isRequired = false;
  2565. for (auto typeInst : module->mOwnedTypeInstances)
  2566. {
  2567. if (typeInst->mTypeDef->IsGlobalsContainer())
  2568. isRequired = true;
  2569. if (typeInst->IsAlwaysInclude())
  2570. isRequired = true;
  2571. }
  2572. if (isRequired)
  2573. continue;
  2574. module->UnreifyModule();
  2575. }
  2576. }
  2577. void BfContext::MarkUsedModules(BfProject* project, BfModule* module)
  2578. {
  2579. BP_ZONE("BfContext::MarkUsedModules");
  2580. BF_ASSERT(!module->mIsDeleting);
  2581. if (module->mIsScratchModule)
  2582. return;
  2583. if (project->mUsedModules.Contains(module))
  2584. return;
  2585. if (!mCompiler->IsModuleAccessible(module, project))
  2586. return;
  2587. project->mUsedModules.Add(module);
  2588. for (auto& typeDataKV : module->mTypeDataRefs)
  2589. project->mReferencedTypeData.Add(typeDataKV.mKey);
  2590. for (auto& slotKV : module->mInterfaceSlotRefs)
  2591. {
  2592. auto typeInstance = slotKV.mKey;
  2593. if ((typeInstance->mSlotNum < 0) && (mCompiler->mHotState != NULL))
  2594. mCompiler->mHotState->mHasNewInterfaceTypes = true;
  2595. mReferencedIFaceSlots.Add(typeInstance);
  2596. }
  2597. for (auto& kv : module->mStaticFieldRefs)
  2598. {
  2599. auto& fieldRef = kv.mKey;
  2600. auto typeInst = fieldRef.mTypeInstance;
  2601. BF_ASSERT(!typeInst->IsDataIncomplete());
  2602. BF_ASSERT(fieldRef.mFieldIdx < typeInst->mFieldInstances.size());
  2603. if (fieldRef.mFieldIdx < typeInst->mFieldInstances.size())
  2604. typeInst->mFieldInstances[fieldRef.mFieldIdx].mLastRevisionReferenced = mCompiler->mRevision;
  2605. }
  2606. module->mLastUsedRevision = mCompiler->mRevision;
  2607. for (auto usedModule : module->mModuleRefs)
  2608. {
  2609. MarkUsedModules(project, usedModule);
  2610. }
  2611. for (auto& kv : module->mSpecializedMethodModules)
  2612. {
  2613. MarkUsedModules(project, kv.mValue);
  2614. }
  2615. }
  2616. void BfContext::Finish()
  2617. {
  2618. }
  2619. void BfContext::Cleanup()
  2620. {
  2621. BfLogSysM("BfContext::Cleanup() MethodWorkList: %d LocalMethodGraveyard: %d\n", mMethodWorkList.size(), mLocalMethodGraveyard.size());
  2622. // Can't clean up LLVM types, they are allocated with a bump allocator
  2623. RemoveInvalidFailTypes();
  2624. mCompiler->mCompileState = BfCompiler::CompileState_Cleanup;
  2625. ///
  2626. {
  2627. Array<BfLocalMethod*> survivingLocalMethods;
  2628. for (auto localMethod : mLocalMethodGraveyard)
  2629. {
  2630. bool inCEMachine = false;
  2631. if (localMethod->mMethodInstanceGroup != NULL)
  2632. {
  2633. if ((localMethod->mMethodInstanceGroup->mDefault != NULL) && (localMethod->mMethodInstanceGroup->mDefault->mInCEMachine))
  2634. inCEMachine = true;
  2635. if (localMethod->mMethodInstanceGroup->mMethodSpecializationMap != NULL)
  2636. {
  2637. for (auto& kv : *localMethod->mMethodInstanceGroup->mMethodSpecializationMap)
  2638. if (kv.mValue->mInCEMachine)
  2639. inCEMachine = true;
  2640. }
  2641. }
  2642. if (inCEMachine)
  2643. {
  2644. localMethod->mMethodInstanceGroup->mOwner->mOwnedLocalMethods.Add(localMethod);
  2645. }
  2646. else if ((localMethod->mMethodInstanceGroup != NULL) && (localMethod->mMethodInstanceGroup->mRefCount > 0))
  2647. {
  2648. BfLogSysM("BfContext::Cleanup surviving local method with refs %p\n", localMethod);
  2649. localMethod->Dispose();
  2650. survivingLocalMethods.push_back(localMethod);
  2651. }
  2652. else if (!mMethodWorkList.empty())
  2653. {
  2654. // We can't remove the local methods if they still may be referenced by a BfMethodRefType used to specialize a method
  2655. BfLogSysM("BfContext::Cleanup surviving local method %p\n", localMethod);
  2656. localMethod->Dispose();
  2657. survivingLocalMethods.push_back(localMethod);
  2658. }
  2659. else
  2660. delete localMethod;
  2661. }
  2662. mLocalMethodGraveyard = survivingLocalMethods;
  2663. }
  2664. // Clean up deleted BfTypes
  2665. // These need to get deleted before the modules because we access mModule in the MethodInstance dtors
  2666. for (int pass = 0; pass < 2; pass++)
  2667. {
  2668. for (int i = 0; i < (int)mTypeGraveyard.size(); i++)
  2669. {
  2670. auto type = mTypeGraveyard[i];
  2671. if (type == NULL)
  2672. continue;
  2673. bool deleteNow = (type->IsBoxed() == (pass == 0));
  2674. if (!deleteNow)
  2675. continue;
  2676. BF_ASSERT(type->mRebuildFlags & BfTypeRebuildFlag_Deleted);
  2677. delete type;
  2678. mTypeGraveyard[i] = NULL;
  2679. }
  2680. }
  2681. mTypeGraveyard.Clear();
  2682. for (auto module : mDeletingModules)
  2683. {
  2684. int idx = (int)mFinishedModuleWorkList.IndexOf(module);
  2685. if (idx != -1)
  2686. mFinishedModuleWorkList.RemoveAt(idx);
  2687. idx = (int)mFinishedSlotAwaitModuleWorkList.IndexOf(module);
  2688. if (idx != -1)
  2689. mFinishedSlotAwaitModuleWorkList.RemoveAt(idx);
  2690. delete module;
  2691. }
  2692. mDeletingModules.Clear();
  2693. for (auto typeDef : mTypeDefGraveyard)
  2694. delete typeDef;
  2695. mTypeDefGraveyard.Clear();
  2696. mScratchModule->Cleanup();
  2697. mUnreifiedModule->Cleanup();
  2698. for (auto module : mModules)
  2699. module->Cleanup();
  2700. }