Delete code under `FEATURE_NATIVE_IMAGE_GENERATION` (#57669)
authorElinor Fung <elfung@microsoft.com>
Wed, 18 Aug 2021 19:21:28 +0000 (12:21 -0700)
committerGitHub <noreply@github.com>
Wed, 18 Aug 2021 19:21:28 +0000 (12:21 -0700)
78 files changed:
src/coreclr/debug/daccess/dacfn.cpp
src/coreclr/debug/daccess/nidump.cpp
src/coreclr/ildasm/dasm.cpp
src/coreclr/inc/corcompile.h
src/coreclr/inc/zapper.h [deleted file]
src/coreclr/md/enc/metamodelrw.cpp
src/coreclr/md/hotdata/hotheapwriter.cpp
src/coreclr/utilcode/stgpool.cpp
src/coreclr/vm/appdomain.cpp
src/coreclr/vm/arm/stubs.cpp
src/coreclr/vm/arm/virtualcallstubcpu.hpp
src/coreclr/vm/arm64/stubs.cpp
src/coreclr/vm/assembly.cpp
src/coreclr/vm/binder.cpp
src/coreclr/vm/binder.h
src/coreclr/vm/ceeload.cpp
src/coreclr/vm/ceeload.h
src/coreclr/vm/class.cpp
src/coreclr/vm/class.h
src/coreclr/vm/classcompat.cpp
src/coreclr/vm/classhash.cpp
src/coreclr/vm/classhash.h
src/coreclr/vm/clsload.cpp
src/coreclr/vm/compile.cpp [deleted file]
src/coreclr/vm/compile.h [deleted file]
src/coreclr/vm/contractimpl.cpp
src/coreclr/vm/contractimpl.h
src/coreclr/vm/coreassemblyspec.cpp
src/coreclr/vm/crossgencompile.cpp [deleted file]
src/coreclr/vm/dataimage.cpp [deleted file]
src/coreclr/vm/dataimagesection.h [deleted file]
src/coreclr/vm/dllimport.cpp
src/coreclr/vm/domainfile.cpp
src/coreclr/vm/eedbginterfaceimpl.h
src/coreclr/vm/eehash.h
src/coreclr/vm/field.cpp
src/coreclr/vm/field.h
src/coreclr/vm/fieldmarshaler.h
src/coreclr/vm/genericdict.cpp
src/coreclr/vm/genericdict.h
src/coreclr/vm/i386/cgenx86.cpp
src/coreclr/vm/i386/stublinkerx86.cpp
src/coreclr/vm/ilstubcache.cpp
src/coreclr/vm/ilstubcache.h
src/coreclr/vm/inlinetracking.cpp
src/coreclr/vm/inlinetracking.h
src/coreclr/vm/instmethhash.cpp
src/coreclr/vm/instmethhash.h
src/coreclr/vm/jithelpers.cpp
src/coreclr/vm/jitinterface.cpp
src/coreclr/vm/jitinterface.h
src/coreclr/vm/method.cpp
src/coreclr/vm/method.hpp
src/coreclr/vm/methodimpl.cpp
src/coreclr/vm/methodimpl.h
src/coreclr/vm/methodtable.cpp
src/coreclr/vm/methodtable.h
src/coreclr/vm/methodtablebuilder.cpp
src/coreclr/vm/mlinfo.cpp
src/coreclr/vm/ngenhash.h
src/coreclr/vm/ngenhash.inl
src/coreclr/vm/pefile.cpp
src/coreclr/vm/peimage.cpp
src/coreclr/vm/precode.cpp
src/coreclr/vm/precode.h
src/coreclr/vm/prestub.cpp
src/coreclr/vm/readytoruninfo.cpp
src/coreclr/vm/siginfo.cpp
src/coreclr/vm/typedesc.cpp
src/coreclr/vm/typedesc.h
src/coreclr/vm/typeequivalencehash.hpp
src/coreclr/vm/typehandle.cpp
src/coreclr/vm/typehandle.h
src/coreclr/vm/typehash.cpp
src/coreclr/vm/typehash.h
src/coreclr/vm/vars.hpp
src/coreclr/vm/virtualcallstub.cpp
src/coreclr/vm/zapsig.cpp

index a76e6be..c8ac208 100644 (file)
@@ -12,9 +12,6 @@
 #include "stdafx.h"
 
 #include <encee.h>
-#ifdef FEATURE_PREJIT
-#include "compile.h"
-#endif // FEATURE_PREJIT
 #include <virtualcallstub.h>
 #include "peimagelayout.inl"
 
index 06f02a3..ccd6427 100644 (file)
@@ -33,8 +33,6 @@
 #define _ASSERTE(x) assert(x)
 #endif
 
-#include <compile.h>
-
 #ifdef USE_GC_INFO_DECODER
 #include <gcinfodecoder.h>
 #endif
index 6fc7988..efe6652 100644 (file)
 #pragma warning(disable : 4640)
 #endif
 
-#if defined(_DEBUG) && defined(FEATURE_PREJIT)
-#include <corcompile.h>
-#endif
-
 #ifdef TARGET_UNIX
 #include "resourcestring.h"
 #define NATIVE_STRING_RESOURCE_NAME dasm_rc
index 283124c..c98c2eb 100644 (file)
@@ -1093,213 +1093,6 @@ enum CorCompileILRegion
     CORCOMPILE_ILREGION_COUNT,
 };
 
-/*********************************************************************************
- * ICorCompilePreloader is used to query preloaded EE data structures
- *********************************************************************************/
-
-class ICorCompilePreloader
-{
- public:
-    typedef void (__stdcall *CORCOMPILE_CompileStubCallback)(LPVOID pContext, CORINFO_METHOD_HANDLE hStub, CORJIT_FLAGS jitFlags);
-
-    //
-    // Map methods are available after Serialize() is called
-    // (which will cause it to allocate its data.) Note that returned
-    // results are RVAs into the image.
-    //
-    // If compiling after serializing the preloaded image, these methods can
-    // be used to avoid making entries in the various info tables.
-    // Else, use ICorCompileInfo::CanEmbedXXX()
-    //
-
-    virtual DWORD MapMethodEntryPoint(
-            CORINFO_METHOD_HANDLE handle
-            ) = 0;
-
-    virtual DWORD MapClassHandle(
-            CORINFO_CLASS_HANDLE handle
-            ) = 0;
-
-    virtual DWORD MapMethodHandle(
-            CORINFO_METHOD_HANDLE handle
-            ) = 0;
-
-    virtual DWORD MapFieldHandle(
-            CORINFO_FIELD_HANDLE handle
-            ) = 0;
-
-    virtual DWORD MapAddressOfPInvokeFixup(
-            CORINFO_METHOD_HANDLE handle
-            ) = 0;
-
-    virtual DWORD MapGenericHandle(
-            CORINFO_GENERIC_HANDLE handle
-            ) = 0;
-
-    virtual DWORD MapModuleIDHandle(
-            CORINFO_MODULE_HANDLE handle
-            )  = 0;
-
-    // Load a method for the specified method def
-    // If the class or method is generic, instantiate all parameters with <object>
-    virtual CORINFO_METHOD_HANDLE LookupMethodDef(mdMethodDef token) = 0;
-
-    // For the given ftnHnd fill in the methInfo structure and return true if successful.
-    virtual bool GetMethodInfo(mdMethodDef token, CORINFO_METHOD_HANDLE ftnHnd, CORINFO_METHOD_INFO * methInfo) = 0;
-
-    // Returns region that the IL should be emitted in
-    virtual CorCompileILRegion GetILRegion(mdMethodDef token) = 0;
-
-    // Find the (parameterized) method for the given blob from the profile data
-    virtual CORINFO_METHOD_HANDLE FindMethodForProfileEntry(CORBBTPROF_BLOB_PARAM_SIG_ENTRY * profileBlobEntry) = 0;
-
-    virtual void ReportInlining(CORINFO_METHOD_HANDLE inliner, CORINFO_METHOD_HANDLE inlinee) = 0;
-
-    //
-    // Call Link when you want all the fixups
-    // to be applied.  You may call this e.g. after
-    // compiling all the code for the module.
-    // Return some stats about the types in the ngen image
-    //
-    virtual void Link() = 0;
-
-    virtual void FixupRVAs() = 0;
-
-    virtual void SetRVAsForFields(IMetaDataEmit * pEmit) = 0;
-
-    virtual void GetRVAFieldData(mdFieldDef fd, PVOID * ppData, DWORD * pcbSize, DWORD * pcbAlignment) = 0;
-
-    // The preloader also maintains a set of uncompiled generic
-    // methods or methods in generic classes. A single method can be
-    // registered or all the methods in a class can be registered.
-    // The method is added to the set only if it should be compiled
-    // into this ngen image
-    //
-    // The zapper registers methods and classes that are resolved by
-    // findClass and findMethod during compilation
-    virtual void AddMethodToTransitiveClosureOfInstantiations(CORINFO_METHOD_HANDLE handle) = 0;
-    virtual void AddTypeToTransitiveClosureOfInstantiations(CORINFO_CLASS_HANDLE handle) = 0;
-
-    // Report reference to the given method from compiled code
-    virtual void MethodReferencedByCompiledCode(CORINFO_METHOD_HANDLE handle) = 0;
-
-    virtual BOOL IsUncompiledMethod(CORINFO_METHOD_HANDLE handle) = 0;
-
-    virtual BOOL ShouldSuppressGCTransition(CORINFO_METHOD_HANDLE handle) = 0;
-
-    // Return a method handle that was previously registered and
-    // hasn't been compiled already, and remove it from the set
-    // of uncompiled methods.
-    // Return NULL if the set is empty
-    virtual CORINFO_METHOD_HANDLE NextUncompiledMethod() = 0;
-
-    // Prepare a method and its statically determinable call graph if
-    // a hint attribute has been applied. This is called to save
-    // additional preparation information into the ngen image that
-    // wouldn't normally be there (since we can't automatically
-    // determine it's needed).
-    virtual void PrePrepareMethodIfNecessary(CORINFO_METHOD_HANDLE hMethod) = 0;
-
-    // If a method requires stubs, this will call back passing method
-    // handles for those stubs.
-    virtual void GenerateMethodStubs(
-            CORINFO_METHOD_HANDLE hMethod,
-            bool                  fNgenProfileImage,
-            CORCOMPILE_CompileStubCallback pfnCallback,
-            LPVOID                pCallbackContext) = 0;
-
-    // Determines whether or not a method is a dynamic method.  This is used
-    // to prevent operations that may require metadata knowledge at times other
-    // than compile time.
-    virtual bool IsDynamicMethod(CORINFO_METHOD_HANDLE hMethod) = 0;
-
-    // Set method profiling flags for layout of EE datastructures
-    virtual void SetMethodProfilingFlags(CORINFO_METHOD_HANDLE hMethod, DWORD flags) = 0;
-
-    // Returns false if precompiled code must ensure that
-    // the EE's DoPrestub function gets run before the
-    // code for the method is used, i.e. if it returns false
-    // then an indirect call must be made.
-    //
-    // Returning true does not guaratee that a direct call can be made:
-    // there can be other reasons why the entry point cannot be embedded.
-    //
-    virtual bool CanSkipMethodPreparation (
-            CORINFO_METHOD_HANDLE   callerHnd,      /* IN  */
-            CORINFO_METHOD_HANDLE   calleeHnd,      /* IN  */
-            CorInfoIndirectCallReason *pReason = NULL,
-            CORINFO_ACCESS_FLAGS    accessFlags = CORINFO_ACCESS_ANY) = 0;
-
-    virtual BOOL CanEmbedModuleHandle(
-            CORINFO_MODULE_HANDLE    moduleHandle) = 0;
-
-    // These check if we can hardbind to a handle.  They guarantee either that
-    // the structure referred to by the handle is in a referenced zapped image
-    // or will be saved into the module currently being zapped.  That is the
-    // corresponding GetLoaderModuleForEmeddableXYZ call will return
-    // either the module currently being zapped or a referenced zapped module.
-    virtual BOOL CanEmbedClassID(CORINFO_CLASS_HANDLE    typeHandle) = 0;
-    virtual BOOL CanEmbedModuleID(CORINFO_MODULE_HANDLE    moduleHandle) = 0;
-    virtual BOOL CanEmbedClassHandle(CORINFO_CLASS_HANDLE    typeHandle) = 0;
-    virtual BOOL CanEmbedMethodHandle(CORINFO_METHOD_HANDLE    methodHandle, CORINFO_METHOD_HANDLE contextHandle = NULL) = 0;
-    virtual BOOL CanEmbedFieldHandle(CORINFO_FIELD_HANDLE    fieldHandle) = 0;
-
-    // Return true if we can both embed a direct hardbind to the handle _and_
-    // no "restore" action is needed on the handle.  Equivalent to "CanEmbed + Prerestored".
-    //
-    // Typically a handle needs runtime restore it has embedded cross-module references
-    // or other data that cannot be persisted directly.
-    virtual BOOL CanPrerestoreEmbedClassHandle(
-            CORINFO_CLASS_HANDLE classHnd) = 0;
-
-    // Return true if a method needs runtime restore
-    // This is only the case if it is instantiated and any of its type arguments need restoring.
-    virtual BOOL CanPrerestoreEmbedMethodHandle(
-            CORINFO_METHOD_HANDLE methodHnd) = 0;
-
-    // Can a method entry point be embedded?
-    virtual BOOL CanEmbedFunctionEntryPoint(
-            CORINFO_METHOD_HANDLE   methodHandle,
-            CORINFO_METHOD_HANDLE   contextHandle = NULL,
-            CORINFO_ACCESS_FLAGS    accessFlags = CORINFO_ACCESS_ANY
-            ) = 0;
-
-    // Prestub is not able to handle method restore in all cases for generics.
-    // If it is the case the method has to be restored explicitly upfront.
-    // See the comment inside the implemenation method for more details.
-    virtual BOOL DoesMethodNeedRestoringBeforePrestubIsRun(
-            CORINFO_METHOD_HANDLE   methodHandle
-            ) = 0;
-
-    // Returns true if the given activation fixup is not necessary
-    virtual BOOL CanSkipDependencyActivation(
-            CORINFO_METHOD_HANDLE   context,
-            CORINFO_MODULE_HANDLE   moduleFrom,
-            CORINFO_MODULE_HANDLE   moduleTo) = 0;
-
-    virtual CORINFO_MODULE_HANDLE GetPreferredZapModuleForClassHandle(
-            CORINFO_CLASS_HANDLE classHnd
-            ) = 0;
-
-    virtual void NoteDeduplicatedCode(
-            CORINFO_METHOD_HANDLE method,
-            CORINFO_METHOD_HANDLE duplicateMethod) = 0;
-
-#ifdef FEATURE_READYTORUN_COMPILER
-    // Returns a compressed encoding of the inline tracking map
-    // for this compilation
-    virtual void GetSerializedInlineTrackingMap(
-            IN OUT SBuffer    * pSerializedInlineTrackingMap
-            ) = 0;
-#endif
-
-    //
-    // Release frees the preloader
-    //
-
-    virtual ULONG Release() = 0;
-};
-
 //
 // The DataImage provides several "sections", which can be used
 // to sort data into different sets for locality control.  The Arrange
@@ -1349,8 +1142,6 @@ enum VerboseLevel
     CORCOMPILE_VERBOSE
 };
 
-class ZapImage;
-
 // When NGEN install /Profile is run, the ZapProfilingHandleImport fixup table contains
 // these 5 values per MethodDesc
 enum
@@ -1364,400 +1155,6 @@ enum
     kZapProfilingHandleImportValueIndexCount
 };
 
-class ICorCompileDataStore
-{
- public:
-    // Returns ZapImage
-    virtual ZapImage * GetZapImage() = 0;
-
-    // Report an error during preloading:
-    // 'token' is the metadata token that triggered the error
-    // hr is the HRESULT from the thrown Exception, or S_OK if we don't have an thrown exception
-    // resID is the resourceID with additional information from the thrown Exception, or 0
-    //
-    virtual void Error(mdToken token, HRESULT hr, UINT _resID, LPCWSTR description) = 0;
-};
-
-
-class ICorCompilationDomain
-{
- public:
-
-    // Sets the application context for fusion
-    // to use when binding, using a shell exe file path
-    virtual HRESULT SetContextInfo(
-            LPCWSTR                 path,
-            BOOL                    isExe
-            ) = 0;
-
-    // Retrieves the dependencies of the code which
-    // has been compiled
-    virtual HRESULT GetDependencies(
-            CORCOMPILE_DEPENDENCY   **ppDependencies,
-            DWORD                   *cDependencies
-            ) = 0;
-};
-
-/*********************************************************************************
- * ICorCompileInfo is the interface for a compiler
- *********************************************************************************/
-// Define function pointer ENCODEMODULE_CALLBACK
-typedef DWORD (*ENCODEMODULE_CALLBACK)(LPVOID pModuleContext, CORINFO_MODULE_HANDLE moduleHandle);
-
-// Define function pointer DEFINETOKEN_CALLBACK
-typedef void (*DEFINETOKEN_CALLBACK)(LPVOID pModuleContext, CORINFO_MODULE_HANDLE moduleHandle, DWORD index, mdTypeRef* token);
-
-class ICorCompileInfo
-{
-  public:
-
-
-    //
-    // Currently no other instance of the EE may be running inside
-    // a process that is used as an NGEN compilation process.
-    //
-    // So, the host must call StartupAsCompilationProcess before compiling
-    // any code, and Shutdown after finishing.
-    //
-    // The arguments control which native image of CoreLib to use.
-    // This matters for hardbinding.
-    //
-
-    virtual HRESULT Startup(
-            BOOL fForceDebug,
-            BOOL fForceProfiling,
-            BOOL fForceInstrument) = 0;
-
-    // Creates a new compilation domain
-    // The BOOL arguments control what kind of a native image is
-    // to be generated. Other factors affect what kind of a native image
-    // will actually be generated. GetAssemblyVersionInfo() ultimately reflects
-    // the kind of native image that will be generated
-    //
-    // pEmitter - sets this as the emitter to use when generating tokens for
-    // the dependency list.  If this is NULL, dependencies won't be computed.
-
-    virtual HRESULT CreateDomain(
-            ICorCompilationDomain **ppDomain, // [OUT]
-            IMetaDataAssemblyEmit   *pEmitter,
-            BOOL fForceDebug,
-            BOOL fForceProfiling,
-            BOOL fForceInstrument
-            ) = 0;
-
-    // Destroys a compilation domain
-    virtual HRESULT DestroyDomain(
-            ICorCompilationDomain *pDomain
-            ) = 0;
-
-    // Loads an assembly manifest module into the EE
-    // and returns a handle to it.
-    virtual HRESULT LoadAssemblyByPath(
-            LPCWSTR                  wzPath,
-            BOOL                     fExplicitBindToNativeImage,
-            CORINFO_ASSEMBLY_HANDLE *pHandle
-            ) = 0;
-
-    virtual BOOL IsInCurrentVersionBubble(CORINFO_MODULE_HANDLE hModule) = 0;
-
-    // Loads a module from an assembly into the EE
-    // and returns a handle to it.
-    virtual HRESULT LoadAssemblyModule(
-            CORINFO_ASSEMBLY_HANDLE assembly,
-            mdFile                  file,
-            CORINFO_MODULE_HANDLE   *pHandle
-            ) = 0;
-
-
-    // Checks to see if an up to date zap exists for the
-    // assembly
-    virtual BOOL CheckAssemblyZap(
-        CORINFO_ASSEMBLY_HANDLE assembly,
-      __out_ecount_opt(*cAssemblyManifestModulePath)
-        LPWSTR                  assemblyManifestModulePath,
-        LPDWORD                 cAssemblyManifestModulePath
-        ) = 0;
-
-    // Sets up the compilation target in the EE
-    virtual HRESULT SetCompilationTarget(
-            CORINFO_ASSEMBLY_HANDLE     assembly,
-            CORINFO_MODULE_HANDLE       module
-            ) = 0;
-
-
-    // Returns the dependency load setting for an assembly ref
-    virtual HRESULT GetLoadHint(
-            CORINFO_ASSEMBLY_HANDLE hAssembly,
-            CORINFO_ASSEMBLY_HANDLE hAssemblyDependency,
-            LoadHintEnum *loadHint,
-            LoadHintEnum *defaultLoadHint = NULL
-            ) = 0;
-
-    // Returns information on how the assembly has been loaded
-    virtual HRESULT GetAssemblyVersionInfo(
-            CORINFO_ASSEMBLY_HANDLE hAssembly,
-            CORCOMPILE_VERSION_INFO *pInfo
-            ) = 0;
-
-    // Returns the manifest metadata for an assembly
-    // Use the internal IMDInternalImport for performance.
-    // Creation of the public IMetaDataImport * triggers
-    // conversion to R/W metadata that slows down all subsequent accesses.
-    virtual IMDInternalImport * GetAssemblyMetaDataImport(
-            CORINFO_ASSEMBLY_HANDLE assembly
-            ) = 0;
-
-    // Returns an interface to query the metadata for a loaded module
-    // Use the internal IMDInternalImport for performance.
-    // Creation of the public IMetaDataAssemblyImport * triggers
-    // conversion to R/W metadata that slows down all subsequent accesses.
-    virtual IMDInternalImport * GetModuleMetaDataImport(
-            CORINFO_MODULE_HANDLE   module
-            ) = 0;
-
-    // Returns the module of the assembly which contains the manifest,
-    // or NULL if the manifest is standalone.
-    virtual CORINFO_MODULE_HANDLE GetAssemblyModule(
-            CORINFO_ASSEMBLY_HANDLE assembly
-            ) = 0;
-
-    // Returns the assembly of a loaded module
-    virtual CORINFO_ASSEMBLY_HANDLE GetModuleAssembly(
-            CORINFO_MODULE_HANDLE   module
-            ) = 0;
-
-    // Returns the current PEDecoder of a loaded module.
-    virtual PEDecoder * GetModuleDecoder(
-            CORINFO_MODULE_HANDLE   module
-            ) = 0;
-
-    // Gets the full file name, including path, of a loaded module
-    virtual void GetModuleFileName(
-        CORINFO_MODULE_HANDLE module,
-        SString               &result
-        ) = 0;
-
-    // Get a class def token
-    virtual HRESULT GetTypeDef(
-            CORINFO_CLASS_HANDLE    classHandle,
-            mdTypeDef              *token
-            ) = 0;
-
-    // Get a method def token
-    virtual HRESULT GetMethodDef(
-            CORINFO_METHOD_HANDLE   methodHandle,
-            mdMethodDef            *token
-            ) = 0;
-
-    // Get a field def token
-    virtual HRESULT GetFieldDef(
-            CORINFO_FIELD_HANDLE    fieldHandle,
-            mdFieldDef             *token
-            ) = 0;
-
-    // Get the loader module for CoreLib
-    virtual CORINFO_MODULE_HANDLE GetLoaderModuleForCoreLib() = 0;
-
-    // Get the loader module for a type (where the type is regarded as
-    // living for the purposes of loading, unloading, and ngen).
-    //
-    // classHandle must have passed CanEmbedClassHandle, since the zapper
-    // should only care about the module where a type
-    // prefers to be saved if it knows that that module is either
-    // an zapped module or is the module currently being compiled.
-    // See vm\ceeload.h for more information
-    virtual CORINFO_MODULE_HANDLE GetLoaderModuleForEmbeddableType(
-            CORINFO_CLASS_HANDLE   classHandle
-            ) = 0;
-
-    // Get the loader module for a method (where the method is regarded as
-    // living for the purposes of loading, unloading, and ngen)
-    //
-    // methodHandle must have passed CanEmbedMethodHandle, since the zapper
-    // should only care about the module where a type
-    // prefers to be saved if it knows that that module is either
-    // an zapped module or is the module currently being compiled.
-    // See vm\ceeload.h for more information
-    virtual CORINFO_MODULE_HANDLE GetLoaderModuleForEmbeddableMethod(
-            CORINFO_METHOD_HANDLE   methodHandle
-            ) = 0;
-
-    // Get the loader module for a method (where the method is regarded as
-    // living for the purposes of loading, unloading, and ngen)
-    // See vm\ceeload.h for more information
-    virtual CORINFO_MODULE_HANDLE GetLoaderModuleForEmbeddableField(
-            CORINFO_FIELD_HANDLE   fieldHandle
-            ) = 0;
-
-    // Set the list of assemblies we can hard bind to
-    virtual void SetAssemblyHardBindList(
-      __in_ecount(cHardBindList)
-        LPWSTR * pHardBindList,
-        DWORD    cHardBindList
-        ) = 0;
-
-    // Encode a module for the imports table
-    virtual void EncodeModuleAsIndex(
-            CORINFO_MODULE_HANDLE fromHandle,
-            CORINFO_MODULE_HANDLE handle,
-            DWORD *pIndex,
-            IMetaDataAssemblyEmit *pAssemblyEmit) = 0;
-
-
-    // Encode a class into the given SigBuilder.
-    virtual void EncodeClass(
-            CORINFO_MODULE_HANDLE referencingModule,
-            CORINFO_CLASS_HANDLE classHandle,
-            SigBuilder * pSigBuilder,
-            LPVOID encodeContext,
-            ENCODEMODULE_CALLBACK pfnEncodeModule) = 0;
-
-    // Encode a method into the given SigBuilder.
-    virtual void EncodeMethod(
-            CORINFO_MODULE_HANDLE referencingModule,
-            CORINFO_METHOD_HANDLE handle,
-            SigBuilder * pSigBuilder,
-            LPVOID encodeContext,
-            ENCODEMODULE_CALLBACK pfnEncodeModule,
-            CORINFO_RESOLVED_TOKEN * pResolvedToken = NULL,
-            CORINFO_RESOLVED_TOKEN * pConstrainedResolvedToken = NULL,
-            BOOL fEncodeUsingResolvedTokenSpecStreams = FALSE) = 0;
-
-    // Returns non-null methoddef or memberref token if it is sufficient to encode the method (no generic instantiations, etc.)
-    virtual mdToken TryEncodeMethodAsToken(
-            CORINFO_METHOD_HANDLE handle,
-            CORINFO_RESOLVED_TOKEN * pResolvedToken,
-            CORINFO_MODULE_HANDLE * referencingModule) = 0;
-
-    // Returns method slot (for encoding virtual stub dispatch)
-    virtual DWORD TryEncodeMethodSlot(
-            CORINFO_METHOD_HANDLE handle) = 0;
-
-    // Encode a field into the given SigBuilder.
-    virtual void EncodeField(
-            CORINFO_MODULE_HANDLE referencingModule,
-            CORINFO_FIELD_HANDLE handle,
-            SigBuilder * pSigBuilder,
-            LPVOID encodeContext,
-            ENCODEMODULE_CALLBACK pfnEncodeModule,
-            CORINFO_RESOLVED_TOKEN * pResolvedToken = NULL,
-            BOOL fEncodeUsingResolvedTokenSpecStreams = FALSE) = 0;
-
-
-    // Encode generic dictionary signature
-    virtual void EncodeGenericSignature(
-            LPVOID signature,
-            BOOL fMethod,
-            SigBuilder * pSigBuilder,
-            LPVOID encodeContext,
-            ENCODEMODULE_CALLBACK pfnEncodeModule) = 0;
-
-
-    virtual BOOL IsEmptyString(
-            mdString token,
-            CORINFO_MODULE_HANDLE module) = 0;
-
-
-    // Preload a modules' EE data structures
-    // directly into an executable image
-
-    virtual ICorCompilePreloader * PreloadModule(
-            CORINFO_MODULE_HANDLE   moduleHandle,
-            ICorCompileDataStore    *pData,
-            CorProfileData          *profileData
-            ) = 0;
-
-    // Gets the codebase URL for the assembly
-    virtual void GetAssemblyCodeBase(
-            CORINFO_ASSEMBLY_HANDLE hAssembly,
-            SString                 &result) = 0;
-
-    // Returns the GC-information for a method. This is the simple representation
-    // and can be used when a code that can trigger a GC does not have access
-    // to the CORINFO_METHOD_HANDLE (which is normally used to access the GC information)
-    //
-    // Returns S_FALSE if there is no simple representation for the method's GC info
-    //
-    virtual void GetCallRefMap(
-            CORINFO_METHOD_HANDLE hMethod,
-            GCRefMapBuilder * pBuilder,
-            bool isDispatchCell) = 0;
-
-    // Returns a compressed block of debug information
-    //
-    // Uncompressed debug maps are passed in.
-    // Writes to outgoing SBuffer.
-    // Throws on failure.
-    virtual void CompressDebugInfo(
-            IN ICorDebugInfo::OffsetMapping  * pOffsetMapping,
-            IN ULONG            iOffsetMapping,
-            IN ICorDebugInfo::NativeVarInfo  * pNativeVarInfo,
-            IN ULONG            iNativeVarInfo,
-            IN OUT SBuffer    * pDebugInfoBuffer
-            ) = 0;
-
-
-
-    // Allows to set verbose level for log messages, enabled in retail build too for stats
-    virtual HRESULT SetVerboseLevel(
-            IN  VerboseLevel            level) = 0;
-
-    // Get the compilation flags that are shared between JIT and NGen
-    virtual HRESULT GetBaseJitFlags(
-            IN  CORINFO_METHOD_HANDLE   hMethod,
-            OUT CORJIT_FLAGS           *pFlags) = 0;
-
-    virtual ICorJitHost* GetJitHost() = 0;
-
-    // needed for stubs to obtain the number of bytes to copy into the native image
-    // return the beginning of the stub and the size to copy (in bytes)
-    virtual void* GetStubSize(void *pStubAddress, DWORD *pSizeToCopy) = 0;
-
-    // Takes a stub and blits it into the buffer, resetting the reference count
-    // to 1 on the clone. The buffer has to be large enough to hold the stub object and the code
-    virtual HRESULT GetStubClone(void *pStub, BYTE *pBuffer, DWORD dwBufferSize) = 0;
-
-    // true if the method has [UnmanagedCallConvAttribute]
-    virtual BOOL IsUnmanagedCallConvMethod(CORINFO_METHOD_HANDLE handle) = 0;
-
-    // true if the method has [UnmanagedCallersOnlyAttribute]
-    virtual BOOL IsUnmanagedCallersOnlyMethod(CORINFO_METHOD_HANDLE handle) = 0;
-
-    virtual BOOL GetIsGeneratingNgenPDB() = 0;
-    virtual void SetIsGeneratingNgenPDB(BOOL fGeneratingNgenPDB) = 0;
-
-#ifdef FEATURE_READYTORUN_COMPILER
-    virtual CORCOMPILE_FIXUP_BLOB_KIND GetFieldBaseOffset(
-            CORINFO_CLASS_HANDLE classHnd,
-            DWORD * pBaseOffset
-            ) = 0;
-
-    virtual BOOL NeedsTypeLayoutCheck(CORINFO_CLASS_HANDLE classHnd) = 0;
-    virtual void EncodeTypeLayout(CORINFO_CLASS_HANDLE classHandle, SigBuilder * pSigBuilder) = 0;
-
-    virtual BOOL AreAllClassesFullyLoaded(CORINFO_MODULE_HANDLE moduleHandle) = 0;
-
-    virtual int GetVersionResilientTypeHashCode(CORINFO_MODULE_HANDLE moduleHandle, mdToken token) = 0;
-
-    virtual int GetVersionResilientMethodHashCode(CORINFO_METHOD_HANDLE methodHandle) = 0;
-
-    virtual BOOL EnumMethodsForStub(CORINFO_METHOD_HANDLE hMethod, void** enumerator) = 0;
-    virtual BOOL EnumNextMethodForStub(void * enumerator, CORINFO_METHOD_HANDLE *hMethod) = 0;
-    virtual void EnumCloseForStubEnumerator(void *enumerator) = 0;
-
-#endif
-
-    virtual BOOL HasCustomAttribute(CORINFO_METHOD_HANDLE method, LPCSTR customAttributeName) = 0;
-};
-
-// Returns the global instance of JIT->EE interface for NGen
-
-extern "C" ICorDynamicInfo * __stdcall GetZapJitInfo();
-
-// Returns the global instance of Zapper->EE interface
-
-extern "C" ICorCompileInfo * __stdcall GetCompileInfo();
-
 // Stress mode to leave some methods/types uncompiled in the ngen image.
 // Those methods will be JIT-compiled at runtime as needed.
 
diff --git a/src/coreclr/inc/zapper.h b/src/coreclr/inc/zapper.h
deleted file mode 100644 (file)
index b88d4d5..0000000
+++ /dev/null
@@ -1,447 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-
-#ifndef ZAPPER_H_
-#define ZAPPER_H_
-
-#include <winwrap.h>
-#include <windows.h>
-#include <stdlib.h>
-#include <objbase.h>
-#include <stddef.h>
-#include <float.h>
-#include <limits.h>
-
-#include "sarray.h"
-#include "sstring.h"
-#include "shash.h"
-#include "utilcode.h"
-#include "corjit.h"
-#include "corcompile.h"
-#include "corhlprpriv.h"
-#include "ngen.h"
-#include "corbbtprof.h"
-#include "pedecoder.h"
-#include "mscorsvc.h"
-#include "holderinst.h"
-#include "corpriv.h"
-
-// For side by side issues, it's best to use the exported API calls to generate a
-// Zapper Object instead of creating one on your own.
-
-STDAPI NGenCreateNGenWorker(ICorSvcWorker **pCorSvcWorker, ILocalServerLifetime *pLocalServerLifetime, ICorSvcLogger *pCorSvcLogger);
-STDAPI NGenCreateZapper(HANDLE* hZapper, NGenOptions* opt);
-STDAPI NGenFreeZapper(HANDLE hZapper);
-STDAPI NGenTryEnumerateFusionCache(HANDLE hZapper, LPCWSTR assemblyName, bool fPrint, bool fDelete);
-STDAPI_(BOOL) NGenCompile(HANDLE hZapper, LPCWSTR path);
-
-
-/* --------------------------------------------------------------------------- *
- * Zapper classes
- * --------------------------------------------------------------------------- */
-
-class ZapperOptions;
-class ZapperAttributionStats;
-class ZapImage;
-class ZapInfo;
-
-typedef enum CorZapLogLevel
-{
-        CORZAP_LOGLEVEL_ERROR,
-        CORZAP_LOGLEVEL_WARNING,
-        CORZAP_LOGLEVEL_SUCCESS,
-        CORZAP_LOGLEVEL_INFO,
-} CorZapLogLevel;
-
-class Zapper
-{
-    friend class ZapImage;
-    friend class ZapInfo;
-    friend class ZapILMetaData;
-
- private:
-
-    //
-    // Interfaces
-    //
-
-    ICorDynamicInfo         *m_pEEJitInfo;
-    ICorCompileInfo         *m_pEECompileInfo;
-    ICorJitCompiler         *m_pJitCompiler;
-    IMetaDataDispenserEx    *m_pMetaDataDispenser;
-    HMODULE                  m_hJitLib;
-#ifdef TARGET_AMD64
-    HMODULE                  m_hJitLegacy;
-#endif
-
-#ifdef ALLOW_SXS_JIT_NGEN
-    ICorJitCompiler         *m_alternateJit;
-    HMODULE                  m_hAltJITCompiler;
-#endif // ALLOW_SXS_JIT_NGEN
-
-    //
-    // Options
-    //
-
-    ZapperOptions *         m_pOpt;
-    BOOL                    m_fFreeZapperOptions;
-
-    SString                 m_exeName;      // If an EXE is specified
-
-    bool                    m_fromDllHost;
-
-    //
-    // Current assembly info
-    //
-
-    ICorCompilationDomain  *m_pDomain;
-    CORINFO_ASSEMBLY_HANDLE m_hAssembly;
-    IMDInternalImport      *m_pAssemblyImport;
-
-    SString                 m_outputPath; // Temp folder for creating the output file
-
-    IMetaDataAssemblyEmit  *m_pAssemblyEmit;
-    IMetaDataAssemblyEmit  *CreateAssemblyEmitter();
-
-    //
-    //
-    // Status info
-    //
-
-    BOOL                    m_failed;
-    CorInfoRegionKind       m_currentRegionKind;
-
-    SString                 m_platformAssembliesPaths;
-    SString                 m_trustedPlatformAssemblies;
-    SString                 m_platformResourceRoots;
-    SString                 m_appPaths;
-    SString                 m_appNiPaths;
-
-#if !defined(FEATURE_MERGE_JIT_AND_ENGINE)
-    SString                 m_CLRJITPath;
-    bool                    m_fDontLoadJit;
-#endif // !defined(FEATURE_MERGE_JIT_AND_ENGINE)
-#if !defined(NO_NGENPDB)
-    SString                 m_DiasymreaderPath;
-#endif // !defined(NO_NGENPDB)
-
-    SString                 m_outputFilename;
-
-    SIZE_T                  m_customBaseAddress;
-
-  public:
-
-    struct assemblyDependencies
-    {
-        struct DependencyEntry
-        {
-            BSTR bstr;
-            LoadHintEnum loadHint;
-            NGenHintEnum ngenHint;
-        };
-
-        SArray<DependencyEntry> dependencyArray;
-        NGenHintEnum ngenHint;
-        SString displayName;
-
-        assemblyDependencies()
-        {
-            Initialize();
-            ngenHint = NGenDefault;
-        }
-
-        ~assemblyDependencies()
-        {
-            Cleanup();
-        }
-
-        void Reinitialize()
-        {
-            Cleanup();
-            Initialize();
-        }
-
-        void SetNGenHint(NGenHintEnum ngenHint)
-        {
-            this->ngenHint = ngenHint;
-        }
-
-        NGenHintEnum GetNGenHint()
-        {
-            return ngenHint;
-        }
-
-        void SetDisplayName(const WCHAR *pStr)
-        {
-            displayName.Set(pStr);
-        }
-
-        const WCHAR *GetDisplayName()
-        {
-            return displayName.GetUnicode();
-        }
-
-        void Append(const WCHAR *pStr, LoadHintEnum loadHint = LoadDefault, NGenHintEnum ngenHint = NGenDefault)
-        {
-            // Don't append string if it's a duplicate
-            for (COUNT_T i = 0; i < dependencyArray.GetCount(); i++)
-            {
-                if (wcscmp(dependencyArray[i].bstr, pStr) == 0)
-                    return;
-            }
-
-            BSTRHolder bstr(::SysAllocString(pStr));
-            DependencyEntry dependencyEntry;
-            dependencyEntry.bstr = bstr.GetValue();
-            dependencyEntry.loadHint = loadHint;
-            dependencyEntry.ngenHint = ngenHint;
-
-            dependencyArray.Append(dependencyEntry);
-            bstr.SuppressRelease();
-        }
-
-        SAFEARRAY *GetSAFEARRAY()
-        {
-            SafeArrayHolder pDependencies(SafeArrayCreateVector(VT_BSTR, 0, dependencyArray.GetCount()));
-            if (pDependencies.GetValue() == NULL) ThrowLastError();
-
-            for (COUNT_T i = 0; i < dependencyArray.GetCount(); i++)
-            {
-                LONG indices[1];
-                indices[0] = (LONG) i;
-                IfFailThrow(SafeArrayPutElement(pDependencies, indices, this->dependencyArray[i].bstr));
-            }
-
-            pDependencies.SuppressRelease();
-            return pDependencies.GetValue();
-        }
-
-        SAFEARRAY *GetLoadHintSAFEARRAY()
-        {
-            SafeArrayHolder pSettings(SafeArrayCreateVector(VT_UI4, 0, dependencyArray.GetCount()));
-            if (pSettings.GetValue() == NULL) ThrowLastError();
-
-            for (COUNT_T i = 0; i < dependencyArray.GetCount(); i++)
-            {
-                LONG indices[1];
-                indices[0] = (LONG) i;
-                IfFailThrow(SafeArrayPutElement(pSettings, indices, &this->dependencyArray[i].loadHint));
-            }
-
-            pSettings.SuppressRelease();
-            return pSettings.GetValue();
-        }
-
-        SAFEARRAY *GetNGenHintSAFEARRAY()
-        {
-            SafeArrayHolder pSettings(SafeArrayCreateVector(VT_UI4, 0, dependencyArray.GetCount()));
-            if (pSettings.GetValue() == NULL) ThrowLastError();
-
-            for (COUNT_T i = 0; i < dependencyArray.GetCount(); i++)
-            {
-                LONG indices[1];
-                indices[0] = (LONG) i;
-                IfFailThrow(SafeArrayPutElement(pSettings, indices, &this->dependencyArray[i].ngenHint));
-            }
-
-            pSettings.SuppressRelease();
-            return pSettings.GetValue();
-        }
-
-    private:
-        void Initialize()
-        {
-            dependencyArray.SetCount(0);
-            // Should we reinitialize ngenHint to the default value as well?
-        }
-
-        void Cleanup()
-        {
-            for (COUNT_T i = 0; i < dependencyArray.GetCount(); i++)
-            {
-                ::SysFreeString(dependencyArray[i].bstr);
-            }
-        }
-    } m_assemblyDependencies;
-
-
-  public:
-
-    Zapper(ZapperOptions *pOpt);
-    Zapper(NGenOptions *pOpt, bool fromDllHost = false);
-
-    void Init(ZapperOptions *pOpt, bool fFreeZapperOptions= false);
-
-    static Zapper *NewZapper(NGenOptions *pOpt, bool fromDllHost = false)
-    {
-        CONTRACTL
-        {
-            THROWS;
-            GC_NOTRIGGER;
-        }
-        CONTRACTL_END;
-        return new Zapper(pOpt, fromDllHost);
-    }
-
-    ~Zapper();
-
-    // The arguments control which native image of CoreLib to use.
-    // This matters for hardbinding.
-    void InitEE(BOOL fForceDebug, BOOL fForceProfile, BOOL fForceInstrument);
-    void LoadAndInitializeJITForNgen(LPCWSTR pwzJitName, OUT HINSTANCE* phJit, OUT ICorJitCompiler** ppICorJitCompiler);
-
-
-    BOOL IsAssembly(LPCWSTR path);
-
-    void CreateDependenciesLookupDomain();
-    void ComputeDependencies(LPCWSTR pAssemblyName, CORCOMPILE_NGEN_SIGNATURE * pNativeImageSig);
-    void ComputeAssemblyDependencies(CORINFO_ASSEMBLY_HANDLE hAssembly);
-
-    void CreatePdb(BSTR pAssemblyPathOrName, BSTR pNativeImagePath, BSTR pPdbPath, BOOL pdbLines, BSTR pManagedPdbSearchPath);
-
-    void DefineOutputAssembly(SString& strAssemblyName, ULONG * pHashAlgId);
-
-    HRESULT Compile(LPCWSTR path, CORCOMPILE_NGEN_SIGNATURE * pNativeImageSig = NULL);
-    void    DontUseProfileData();
-    bool    HasProfileData();
-
-    void CompileAssembly(CORCOMPILE_NGEN_SIGNATURE * pNativeImageSig);
-    ZapImage * CompileModule(CORINFO_MODULE_HANDLE hModule,
-                             IMetaDataAssemblyEmit *pEmit);
-    void InstallCompiledAssembly(LPCWSTR szAssemblyName, LPCWSTR szNativeImagePath, HANDLE hFile, SArray<HANDLE> &hFiles);
-
-    HRESULT GetExceptionHR();
-
-    void Success(LPCWSTR format, ...);
-    void Error(LPCWSTR format, ...);
-    void Warning(LPCWSTR format, ...);
-    void Info(LPCWSTR format, ...);
-    void Print(CorZapLogLevel level, LPCWSTR format, ...);
-    void Print(CorZapLogLevel level, LPCWSTR format, va_list args);
-    void PrintErrorMessage(CorZapLogLevel level, Exception *ex);
-    void PrintErrorMessage(CorZapLogLevel level, HRESULT hr);
-
-    BOOL            CheckAssemblyUpToDate(CORINFO_ASSEMBLY_HANDLE hAssembly, CORCOMPILE_NGEN_SIGNATURE * pNativeImageSig);
-    BOOL            TryToInstallFromRepository(CORINFO_ASSEMBLY_HANDLE hAssembly, CORCOMPILE_NGEN_SIGNATURE * pNativeImageSig);
-    BOOL            TryToInstallFromRepositoryDir(SString &strNativeImageDir,
-                                                  SString &strSimpleName,
-                                                  CORCOMPILE_NGEN_SIGNATURE *pNativeImageSig,
-                                                  BOOL *pfHitMismatchedVersion,
-                                                  BOOL *pfHitMismatchedDependencies,
-                                                  BOOL useHardLink = FALSE);
-    void            CopyAndInstallFromRepository(LPCWSTR lpszNativeImageDir,
-                                                 LPCWSTR lpszNativeImageName,
-                                                 CORCOMPILE_NGEN_SIGNATURE * pNativeImageSig,
-                                                 BOOL useHardLink = FALSE);
-    void            InstallFromRepository(LPCWSTR lpszNativeImage,
-                                          CORCOMPILE_NGEN_SIGNATURE * pNativeImageSig);
-
-    void            CopyDirectory(LPCWSTR srcPath, LPCWSTR dstPath);
-    void            CleanDirectory(LPCWSTR path);
-    void            TryCleanDirectory(LPCWSTR path);
-    static void     TryCleanDirectory(Zapper * pZapper);
-
-    void            GetOutputFolder();
-
-    void SetPlatformAssembliesPaths(LPCWSTR pwzPlatformAssembliesPaths);
-    void SetTrustedPlatformAssemblies(LPCWSTR pwzTrustedPlatformAssemblies);
-    void SetPlatformResourceRoots(LPCWSTR pwzPlatformResourceRoots);
-    void SetAppPaths(LPCWSTR pwzAppPaths);
-    void SetAppNiPaths(LPCWSTR pwzAppNiPaths);
-
-#if !defined(FEATURE_MERGE_JIT_AND_ENGINE)
-    void SetCLRJITPath(LPCWSTR pwszCLRJITPath);
-    void SetDontLoadJit();
-#endif // !defined(FEATURE_MERGE_JIT_AND_ENGINE)
-
-#if !defined(NO_NGENPDB)
-    void SetDiasymreaderPath(LPCWSTR pwzDiasymreaderPath);
-#endif // !defined(NO_NGENPDB)
-
-    void SetOutputFilename(LPCWSTR pwszOutputFilename);
-    SString GetOutputFileName();
-
-    void SetCustomBaseAddress(SIZE_T baseAddress);
-    SIZE_T GetCustomBaseAddress();
-
- private:
-
-    void DestroyDomain();
-    void CleanupAssembly();
-
-    void CreateCompilationDomain();
-    void SetContextInfo(LPCWSTR assemblyName = NULL);
-
-    void InitializeCompilerFlags(CORCOMPILE_VERSION_INFO * pVersionInfo);
-
-    // DomainCallback is subclassed by each method that would like to compile in a given domain
-    class DomainCallback
-    {
-    public:
-        virtual void doCallback() = NULL;
-    };
-
-    void CompileInCurrentDomain(__in LPCWSTR path, CORCOMPILE_NGEN_SIGNATURE * pNativeImageSig);
-    void ComputeDependenciesInCurrentDomain(LPCWSTR pAssemblyName, CORCOMPILE_NGEN_SIGNATURE * pNativeImageSig);
-    void CreateDependenciesLookupDomainInCurrentDomain();
-
-    void HangWorker(LPCWSTR hangKey, LPCWSTR insideHangKey);
-};
-
-class ZapperOptions
-{
-  public:
-    enum StatOptions
-    {
-        NO_STATS            = 0,
-        DEFAULT_STATS       = 1,
-        FIXUP_STATS         = DEFAULT_STATS << 1,
-        CALL_STATS          = FIXUP_STATS << 1,
-        ATTRIB_STATS        = CALL_STATS << 1,
-        ALL_STATS           = ~NO_STATS,
-    };
-
-    LPWSTR      m_zapSet;               // Add to zap string. Use to get a private scope of ngen images, for debugging/testing
-
-    LPCWSTR     m_repositoryDir;        // Directory with prebuilt native images
-    RepositoryFlags m_repositoryFlags;  // Copy the native images back to NativeImagesDir
-
-    bool        m_autodebug;            // Use the debug setting specified by the IL module
-
-    MethodNamesList* m_onlyMethods;     // only methods to process
-    MethodNamesList* m_excludeMethods;  // excluded these methods
-    mdToken          m_onlyOneMethod;   // only compile method with matching token
-
-    bool        m_silent;               // Dont spew any text output
-    bool        m_verbose;              // Spew extra text ouput
-    bool        m_ignoreErrors;         // Continue in the face of errors
-    unsigned    m_statOptions;          // print statisitcs on number of methods, size of code ...
-    bool        m_ngenProfileImage;     // ngening with "/prof"
-
-                                        // Which optimizations should be done
-    bool        m_ignoreProfileData;    // Don't use profile data
-    bool        m_noProcedureSplitting; // Don't do procedure splitting
-
-    bool        m_fHasAnyProfileData;   // true if we successfully loaded and used
-                                        //  any profile data when compiling this assembly
-
-    bool        m_fPartialNGen;         // Generate partial NGen images using IBC data
-
-    bool        m_fPartialNGenSet;      // m_fPartialNGen has been set through the environment
-
-    bool        m_fAutoNGen;            // This is an automatic NGen request
-
-    bool        m_fRepositoryOnly;      // Install from repository only, no real NGen
-
-    bool        m_fNGenLastRetry;       // This is retry of the compilation
-
-    CORJIT_FLAGS m_compilerFlags;
-
-    void SetCompilerFlags(void);
-
-    ZapperOptions();
-    ~ZapperOptions();
-};
-
-#endif // ZAPPER_H_
-
index 5f62e5f..ffa8fb7 100644 (file)
 
 #include "../hotdata/hotdataformat.h"
 
-#ifdef FEATURE_PREJIT
-#include "corcompile.h"
-#endif
-
 #ifdef _MSC_VER
 #pragma intrinsic(memcpy)
 #endif
index c3a483b..82a271d 100644 (file)
 
 #include "hotdataformat.h"
 
-#ifdef FEATURE_PREJIT
-// Cannot be included without FEATURE_PREJIT:
-#include <corcompile.h>
-#endif //FEATURE_PREJIT
-
 namespace MetaData
 {
 
index 7c4c203..70ef2f0 100644 (file)
 
 #include "ex.h"
 
-#ifdef FEATURE_PREJIT
-#include <corcompile.h>
-#endif
-
 using namespace StreamUtil;
 
 #define MAX_CHAIN_LENGTH 20             // Max chain length before rehashing.
index f7bf57c..30c5da6 100644 (file)
 #include "finalizerthread.h"
 #include "threadsuspend.h"
 
-#ifdef FEATURE_PREJIT
-#include "corcompile.h"
-#include "compile.h"
-#endif // FEATURE_PREJIT
-
 #ifdef FEATURE_COMINTEROP
 #include "comtoclrcall.h"
 #include "runtimecallablewrapper.h"
@@ -5853,14 +5848,3 @@ PTR_NativeImage AppDomain::SetNativeImage(LPCUTF8 simpleFileName, PTR_NativeImag
     return nullptr;
 }
 #endif//DACCESS_COMPILE
-
-#if !defined(DACCESS_COMPILE) && defined(FEATURE_NATIVE_IMAGE_GENERATION)
-
-void ZapperSetBindingPaths(ICorCompilationDomain *pDomain, SString &trustedPlatformAssemblies, SString &platformResourceRoots, SString &appPaths, SString &appNiPaths)
-{
-    CLRPrivBinderCoreCLR *pBinder = ((CompilationDomain *)pDomain)->GetTPABinderContext();
-    _ASSERTE(pBinder != NULL);
-    pBinder->SetupBindingPaths(trustedPlatformAssemblies, platformResourceRoots, appPaths, appNiPaths);
-}
-
-#endif
index 6e32957..0c003da 100644 (file)
@@ -765,23 +765,6 @@ void StubPrecode::Init(StubPrecode* pPrecodeRX, MethodDesc* pMD, LoaderAllocator
     m_pMethodDesc = (TADDR)pMD;
 }
 
-#ifdef FEATURE_NATIVE_IMAGE_GENERATION
-void StubPrecode::Fixup(DataImage *image)
-{
-    WRAPPER_NO_CONTRACT;
-
-    image->FixupFieldToNode(this, offsetof(StubPrecode, m_pTarget),
-                            image->GetHelperThunk(CORINFO_HELP_EE_PRESTUB),
-                            0,
-                            IMAGE_REL_BASED_PTR);
-
-    image->FixupField(this, offsetof(StubPrecode, m_pMethodDesc),
-                      (void*)GetMethodDesc(),
-                      0,
-                      IMAGE_REL_BASED_PTR);
-}
-#endif // FEATURE_NATIVE_IMAGE_GENERATION
-
 void NDirectImportPrecode::Init(NDirectImportPrecode* pPrecodeRX, MethodDesc* pMD, LoaderAllocator *pLoaderAllocator)
 {
     WRAPPER_NO_CONTRACT;
@@ -799,23 +782,6 @@ void NDirectImportPrecode::Init(NDirectImportPrecode* pPrecodeRX, MethodDesc* pM
     m_pTarget = GetEEFuncEntryPoint(NDirectImportThunk);
 }
 
-#ifdef FEATURE_NATIVE_IMAGE_GENERATION
-void NDirectImportPrecode::Fixup(DataImage *image)
-{
-    WRAPPER_NO_CONTRACT;
-
-    image->FixupField(this, offsetof(NDirectImportPrecode, m_pMethodDesc),
-                      (void*)GetMethodDesc(),
-                      0,
-                      IMAGE_REL_BASED_PTR);
-
-    image->FixupFieldToNode(this, offsetof(NDirectImportPrecode, m_pTarget),
-                            image->GetHelperThunk(CORINFO_HELP_EE_PINVOKE_FIXUP),
-                            0,
-                            IMAGE_REL_BASED_PTR);
-}
-#endif
-
 void FixupPrecode::Init(FixupPrecode* pPrecodeRX, MethodDesc* pMD, LoaderAllocator *pLoaderAllocator, int iMethodDescChunkIndex /*=0*/, int iPrecodeChunkIndex /*=0*/)
 {
     WRAPPER_NO_CONTRACT;
@@ -851,53 +817,6 @@ void FixupPrecode::Init(FixupPrecode* pPrecodeRX, MethodDesc* pMD, LoaderAllocat
     }
 }
 
-#ifdef FEATURE_NATIVE_IMAGE_GENERATION
-// Partial initialization. Used to save regrouped chunks.
-void FixupPrecode::InitForSave(int iPrecodeChunkIndex)
-{
-    STANDARD_VM_CONTRACT;
-
-    m_rgCode[0] = 0x46fc;   // mov r12, pc
-    m_rgCode[1] = 0xf8df;   // ldr pc, [pc, #4]
-    m_rgCode[2] = 0xf004;
-
-    _ASSERTE(FitsInU1(iPrecodeChunkIndex));
-    m_PrecodeChunkIndex = static_cast<BYTE>(iPrecodeChunkIndex);
-
-    // The rest is initialized in code:FixupPrecode::Fixup
-}
-
-void FixupPrecode::Fixup(DataImage *image, MethodDesc * pMD)
-{
-    STANDARD_VM_CONTRACT;
-
-    // Note that GetMethodDesc() does not return the correct value because of
-    // regrouping of MethodDescs into hot and cold blocks. That's why the caller
-    // has to supply the actual MethodDesc
-
-    SSIZE_T mdChunkOffset;
-    ZapNode * pMDChunkNode = image->GetNodeForStructure(pMD, &mdChunkOffset);
-    ZapNode * pHelperThunk = image->GetHelperThunk(CORINFO_HELP_EE_PRECODE_FIXUP);
-
-    image->FixupFieldToNode(this, offsetof(FixupPrecode, m_pTarget), pHelperThunk);
-
-    // Set the actual chunk index
-    FixupPrecode * pNewPrecode = (FixupPrecode *)image->GetImagePointer(this);
-
-    size_t mdOffset   = mdChunkOffset - sizeof(MethodDescChunk);
-    size_t chunkIndex = mdOffset / MethodDesc::ALIGNMENT;
-    _ASSERTE(FitsInU1(chunkIndex));
-    pNewPrecode->m_MethodDescChunkIndex = (BYTE) chunkIndex;
-
-    // Fixup the base of MethodDescChunk
-    if (m_PrecodeChunkIndex == 0)
-    {
-        image->FixupFieldToNode(this, (BYTE *)GetBase() - (BYTE *)this,
-            pMDChunkNode, sizeof(MethodDescChunk));
-    }
-}
-#endif // FEATURE_NATIVE_IMAGE_GENERATION
-
 void ThisPtrRetBufPrecode::Init(MethodDesc* pMD, LoaderAllocator *pLoaderAllocator)
 {
     WRAPPER_NO_CONTRACT;
index 919845c..38065f2 100644 (file)
@@ -8,9 +8,6 @@
 
 #ifdef DECLARE_DATA
 #include "asmconstants.h"
-#ifdef FEATURE_PREJIT
-#include "compile.h"
-#endif
 #endif
 
 //#define STUB_LOGGING
index 12d56dd..ebef5cd 100644 (file)
@@ -583,23 +583,6 @@ void StubPrecode::Init(StubPrecode* pPrecodeRX, MethodDesc* pMD, LoaderAllocator
     m_pMethodDesc = (TADDR)pMD;
 }
 
-#ifdef FEATURE_NATIVE_IMAGE_GENERATION
-void StubPrecode::Fixup(DataImage *image)
-{
-    WRAPPER_NO_CONTRACT;
-
-    image->FixupFieldToNode(this, offsetof(StubPrecode, m_pTarget),
-                            image->GetHelperThunk(CORINFO_HELP_EE_PRESTUB),
-                            0,
-                            IMAGE_REL_BASED_PTR);
-
-    image->FixupField(this, offsetof(StubPrecode, m_pMethodDesc),
-                      (void*)GetMethodDesc(),
-                      0,
-                      IMAGE_REL_BASED_PTR);
-}
-#endif // FEATURE_NATIVE_IMAGE_GENERATION
-
 void NDirectImportPrecode::Init(NDirectImportPrecode* pPrecodeRX, MethodDesc* pMD, LoaderAllocator *pLoaderAllocator)
 {
     WRAPPER_NO_CONTRACT;
@@ -616,23 +599,6 @@ void NDirectImportPrecode::Init(NDirectImportPrecode* pPrecodeRX, MethodDesc* pM
     m_pMethodDesc = (TADDR)pMD;
 }
 
-#ifdef FEATURE_NATIVE_IMAGE_GENERATION
-void NDirectImportPrecode::Fixup(DataImage *image)
-{
-    WRAPPER_NO_CONTRACT;
-
-    image->FixupField(this, offsetof(NDirectImportPrecode, m_pMethodDesc),
-                      (void*)GetMethodDesc(),
-                      0,
-                      IMAGE_REL_BASED_PTR);
-
-    image->FixupFieldToNode(this, offsetof(NDirectImportPrecode, m_pTarget),
-                            image->GetHelperThunk(CORINFO_HELP_EE_PINVOKE_FIXUP),
-                            0,
-                            IMAGE_REL_BASED_PTR);
-}
-#endif
-
 void FixupPrecode::Init(FixupPrecode* pPrecodeRX, MethodDesc* pMD, LoaderAllocator *pLoaderAllocator, int iMethodDescChunkIndex /*=0*/, int iPrecodeChunkIndex /*=0*/)
 {
     WRAPPER_NO_CONTRACT;
@@ -666,51 +632,6 @@ void FixupPrecode::Init(FixupPrecode* pPrecodeRX, MethodDesc* pMD, LoaderAllocat
     }
 }
 
-#ifdef FEATURE_NATIVE_IMAGE_GENERATION
-// Partial initialization. Used to save regrouped chunks.
-void FixupPrecode::InitForSave(int iPrecodeChunkIndex)
-{
-    STANDARD_VM_CONTRACT;
-
-    InitCommon();
-
-    _ASSERTE(FitsInU1(iPrecodeChunkIndex));
-    m_PrecodeChunkIndex = static_cast<BYTE>(iPrecodeChunkIndex);
-    // The rest is initialized in code:FixupPrecode::Fixup
-}
-
-void FixupPrecode::Fixup(DataImage *image, MethodDesc * pMD)
-{
-    STANDARD_VM_CONTRACT;
-
-    // Note that GetMethodDesc() does not return the correct value because of
-    // regrouping of MethodDescs into hot and cold blocks. That's why the caller
-    // has to supply the actual MethodDesc
-
-    SSIZE_T mdChunkOffset;
-    ZapNode * pMDChunkNode = image->GetNodeForStructure(pMD, &mdChunkOffset);
-    ZapNode * pHelperThunk = image->GetHelperThunk(CORINFO_HELP_EE_PRECODE_FIXUP);
-
-    image->FixupFieldToNode(this, offsetof(FixupPrecode, m_pTarget), pHelperThunk);
-
-    // Set the actual chunk index
-    FixupPrecode * pNewPrecode = (FixupPrecode *)image->GetImagePointer(this);
-
-    size_t mdOffset = mdChunkOffset - sizeof(MethodDescChunk);
-    size_t chunkIndex = mdOffset / MethodDesc::ALIGNMENT;
-    _ASSERTE(FitsInU1(chunkIndex));
-    pNewPrecode->m_MethodDescChunkIndex = (BYTE)chunkIndex;
-
-    // Fixup the base of MethodDescChunk
-    if (m_PrecodeChunkIndex == 0)
-    {
-        image->FixupFieldToNode(this, (BYTE *)GetBase() - (BYTE *)this,
-            pMDChunkNode, sizeof(MethodDescChunk));
-    }
-}
-#endif // FEATURE_NATIVE_IMAGE_GENERATION
-
-
 void ThisPtrRetBufPrecode::Init(MethodDesc* pMD, LoaderAllocator *pLoaderAllocator)
 {
     WRAPPER_NO_CONTRACT;
index 564693f..666045b 100644 (file)
 #include "assemblynative.hpp"
 #include "threadsuspend.h"
 
-#ifdef FEATURE_PREJIT
-#include "corcompile.h"
-#endif
-
 #include "appdomainnative.hpp"
 #include "customattribute.h"
 #include "winnls.h"
index 042718a..cefa77c 100644 (file)
 #include "sigbuilder.h"
 #include "olevariant.h"
 
-#ifdef FEATURE_PREJIT
-#include "compile.h"
-#endif
-
 //
 // Retrieve structures from ID.
 //
@@ -1240,95 +1236,6 @@ PTR_MethodTable CoreLibBinder::LoadPrimitiveType(CorElementType et)
     return pMT;
 }
 
-#ifdef FEATURE_NATIVE_IMAGE_GENERATION
-void CoreLibBinder::BindAll()
-{
-    STANDARD_VM_CONTRACT;
-
-    for (BinderClassID cID = (BinderClassID) 1; cID < m_cClasses; cID = (BinderClassID) (cID + 1))
-    {
-        if (m_classDescriptions[cID].name != NULL) // Allow for CorSigElement entries with no classes
-            GetClassLocal(cID);
-    }
-
-    for (BinderMethodID mID = (BinderMethodID) 1; mID < m_cMethods; mID = (BinderMethodID) (mID + 1))
-        GetMethodLocal(mID);
-
-    for (BinderFieldID fID = (BinderFieldID) 1; fID < m_cFields; fID = (BinderFieldID) (fID + 1))
-        GetFieldLocal(fID);
-}
-
-void CoreLibBinder::Save(DataImage *image)
-{
-    STANDARD_VM_CONTRACT;
-
-    image->StoreStructure(this, sizeof(CoreLibBinder),
-                          DataImage::ITEM_BINDER);
-
-    image->StoreStructure(m_pClasses, m_cClasses * sizeof(*m_pClasses),
-                          DataImage::ITEM_BINDER_ITEMS);
-
-    image->StoreStructure(m_pMethods, m_cMethods * sizeof(*m_pMethods),
-                          DataImage::ITEM_BINDER_ITEMS);
-
-    image->StoreStructure(m_pFields, m_cFields * sizeof(*m_pFields),
-                          DataImage::ITEM_BINDER_ITEMS);
-}
-
-void CoreLibBinder::Fixup(DataImage *image)
-{
-    STANDARD_VM_CONTRACT;
-
-    image->FixupPointerField(this, offsetof(CoreLibBinder, m_pModule));
-
-    int i;
-
-    image->FixupPointerField(this, offsetof(CoreLibBinder, m_pClasses));
-    for (i = 1; i < m_cClasses; i++)
-    {
-#if _DEBUG
-        //
-        // We do not want to check for restore at runtime for performance reasons.
-        // If there is ever a case that requires restore, it should be special
-        // cased here and restored explicitly by GetClass/GetField/GetMethod caller.
-        //
-        // Profiling NGen images force restore for all types. We are still going to save
-        // the binder for nidump, but we are not going to use it at runtime.
-        //
-        if (m_pClasses[i] != NULL && !GetAppDomain()->ToCompilationDomain()->m_fForceProfiling)
-        {
-            _ASSERTE(!m_pClasses[i]->NeedsRestore(image));
-        }
-#endif
-        image->FixupPointerField(m_pClasses, i * sizeof(m_pClasses[0]));
-    }
-
-    image->FixupPointerField(this, offsetof(CoreLibBinder, m_pMethods));
-    for (i = 1; i < m_cMethods; i++)
-    {
-#if _DEBUG
-        // See comment above.
-        if (m_pMethods[i] != NULL && !GetAppDomain()->ToCompilationDomain()->m_fForceProfiling)
-        {
-            _ASSERTE(!m_pMethods[i]->NeedsRestore(image));
-        }
-#endif
-
-        image->FixupPointerField(m_pMethods, i * sizeof(m_pMethods[0]));
-    }
-
-    image->FixupPointerField(this, offsetof(CoreLibBinder, m_pFields));
-    for (i = 1; i < m_cFields; i++)
-    {
-        image->FixupPointerField(m_pFields, i * sizeof(m_pFields[0]));
-    }
-
-    image->ZeroPointerField(this, offsetof(CoreLibBinder, m_classDescriptions));
-    image->ZeroPointerField(this, offsetof(CoreLibBinder, m_methodDescriptions));
-    image->ZeroPointerField(this, offsetof(CoreLibBinder, m_fieldDescriptions));
-}
-#endif // FEATURE_NATIVE_IMAGE_GENERATION
-
 #endif // #ifndef DACCESS_COMPILE
 
 #ifdef DACCESS_COMPILE
index 4ff115d..111eede 100644 (file)
@@ -237,16 +237,6 @@ class CoreLibBinder
     //
     static void AttachModule(Module *pModule);
 
-#ifdef FEATURE_PREJIT
-    //
-    // Store the binding arrays to a prejit image
-    // so we don't have to do name lookup at runtime
-    //
-    void BindAll();
-    void Save(DataImage *image);
-    void Fixup(DataImage *image);
-#endif
-
 #ifdef _DEBUG
     void Check();
     void CheckExtended();
index b8e7ab0..d418fee 100644 (file)
 #include "threads.h"
 #include "nativeimage.h"
 
-#ifdef FEATURE_PREJIT
-#include "exceptionhandling.h"
-#include "corcompile.h"
-#include "compile.h"
-#include "nibblestream.h"
-#include "zapsig.h"
-#endif //FEATURE_PREJIT
-
 #ifdef FEATURE_COMINTEROP
 #include "runtimecallablewrapper.h"
 #include "comcallablewrapper.h"
@@ -687,11 +679,6 @@ void Module::Initialize(AllocMemTracker *pamTracker, LPCWSTR szName)
         InitializeForProfiling();
     }
 
-#ifdef FEATURE_NATIVE_IMAGE_GENERATION
-    if (g_CorCompileVerboseLevel)
-        m_pNgenStats = new NgenStats();
-#endif
-
     if (!IsResource() && (m_AssemblyRefByNameTable == NULL))
     {
         Module::CreateAssemblyRefByNameTable(pamTracker);
@@ -870,37 +857,6 @@ DWORD GuidToMethodTableHashTable::GetCount()
     return BaseGetElementCount();
 }
 
-#if defined(FEATURE_NATIVE_IMAGE_GENERATION) && !defined(DACCESS_COMPILE)
-
-void GuidToMethodTableHashTable::Save(DataImage *pImage, CorProfileData *pProfileData)
-{
-    WRAPPER_NO_CONTRACT;
-    Base_t::BaseSave(pImage, pProfileData);
-}
-
-void GuidToMethodTableHashTable::Fixup(DataImage *pImage)
-{
-    WRAPPER_NO_CONTRACT;
-    Base_t::BaseFixup(pImage);
-}
-
-bool GuidToMethodTableHashTable::SaveEntry(DataImage *pImage, CorProfileData *pProfileData,
-                    GuidToMethodTableEntry *pOldEntry, GuidToMethodTableEntry *pNewEntry,
-                    EntryMappingTable *pMap)
-{
-    LIMITED_METHOD_CONTRACT;
-    return false;
-}
-
-void GuidToMethodTableHashTable::FixupEntry(DataImage *pImage, GuidToMethodTableEntry *pEntry, void *pFixupBase, DWORD cbFixupOffset)
-{
-    WRAPPER_NO_CONTRACT;
-    pImage->FixupField(pFixupBase, cbFixupOffset + offsetof(GuidToMethodTableEntry, m_pMT), pEntry->m_pMT);
-    pImage->FixupField(pFixupBase, cbFixupOffset + offsetof(GuidToMethodTableEntry, m_Guid), pEntry->m_Guid);
-}
-
-#endif // FEATURE_NATIVE_IMAGE_GENERATION && !DACCESS_COMPILE
-
 #endif // FEATURE_COMINTEROP
 
 #ifndef DACCESS_COMPILE
@@ -1002,47 +958,6 @@ MemberRefToDescHashEntry* MemberRefToDescHashTable::Insert(mdMemberRef token , M
     return pEntry;
 }
 
-#if defined(FEATURE_NATIVE_IMAGE_GENERATION)
-void MemberRefToDescHashTable::Save(DataImage *pImage, CorProfileData *pProfileData)
-{
-    STANDARD_VM_CONTRACT;
-
-    // Mark if the tokens are hot
-    if (pProfileData)
-    {
-        DWORD numInTokenList = pProfileData->GetHotTokens(mdtMemberRef>>24, 1<<RidMap, 1<<RidMap, NULL, 0);
-
-        if (numInTokenList > 0)
-        {
-            LookupContext sAltContext;
-
-            mdToken *tokenList = (mdToken*)(void*)pImage->GetModule()->GetLoaderAllocator()->GetHighFrequencyHeap()->AllocMem(S_SIZE_T(sizeof(mdToken)) * S_SIZE_T(numInTokenList));
-
-            pProfileData->GetHotTokens(mdtMemberRef>>24, 1<<RidMap, 1<<RidMap, tokenList, numInTokenList);
-            for (DWORD i = 0; i < numInTokenList; i++)
-            {
-                DWORD rid = RidFromToken(tokenList[i]);
-                MemberRefToDescHashEntry *pEntry = (PTR_MemberRefToDescHashEntry) BaseFindFirstEntryByHash(RidFromToken(tokenList[i]), &sAltContext);
-                if (pEntry != NULL)
-                {
-                    _ASSERTE((pEntry->m_value & 0x1) == 0);
-                    pEntry->m_value |= 0x1;
-                }
-            }
-        }
-    }
-
-    BaseSave(pImage, pProfileData);
-}
-
-void MemberRefToDescHashTable::FixupEntry(DataImage *pImage, MemberRefToDescHashEntry *pEntry, void *pFixupBase, DWORD cbFixupOffset)
-{
-    //As there is no more hard binding initialize MemberRef* to NULL
-    pImage->ZeroPointerField(pFixupBase, cbFixupOffset + offsetof(MemberRefToDescHashEntry, m_value));
-}
-
-#endif // FEATURE_NATIVE_IMAGE_GENERATION
-
 #endif // !DACCESS_COMPILE
 
 PTR_MemberRef MemberRefToDescHashTable::GetValue(mdMemberRef token, BOOL *pfIsMethod)
@@ -3171,23 +3086,7 @@ void Module::StartUnload()
 BOOL Module::IsInCurrentVersionBubble()
 {
     LIMITED_METHOD_CONTRACT;
-
-#ifdef FEATURE_NATIVE_IMAGE_GENERATION
-    if (!IsCompilationProcess())
-        return TRUE;
-
-    // The module being compiled is always part of the current version bubble
-    AppDomain * pAppDomain = GetAppDomain();
-    if (pAppDomain->IsCompilationDomain() && pAppDomain->ToCompilationDomain()->GetTargetModule() == this)
-        return TRUE;
-
-    if (IsReadyToRunCompilation())
-        return IsLargeVersionBubbleEnabled();
-
-    return TRUE;
-#else // FEATURE_NATIVE_IMAGE_GENERATION
     return TRUE;
-#endif // FEATURE_NATIVE_IMAGE_GENERATION
 }
 
 #if defined(FEATURE_READYTORUN) && !defined(FEATURE_READYTORUN_COMPILER)
@@ -4920,82 +4819,6 @@ TypeHandle Module::LookupTypeRef(mdTypeRef token)
     return entry;
 }
 
-#ifdef FEATURE_NATIVE_IMAGE_GENERATION
-mdTypeRef Module::LookupTypeRefByMethodTable(MethodTable *pMT)
-{
-    STANDARD_VM_CONTRACT;
-
-    HENUMInternalHolder hEnumTypeRefs(GetMDImport());
-    mdTypeRef token;
-    hEnumTypeRefs.EnumAllInit(mdtTypeRef);
-    while (hEnumTypeRefs.EnumNext(&token))
-    {
-        TypeHandle thRef = LookupTypeRef(token);
-        if (thRef.IsNull() || thRef.IsTypeDesc())
-        {
-            continue;
-        }
-
-        MethodTable *pMTRef = thRef.AsMethodTable();
-        if (pMT->HasSameTypeDefAs(pMTRef))
-        {
-            _ASSERTE(pMTRef->IsTypicalTypeDefinition());
-            return token;
-        }
-    }
-
-#ifdef FEATURE_READYTORUN_COMPILER
-    if (IsReadyToRunCompilation())
-    {
-        if (pMT->GetClass()->IsEquivalentType())
-        {
-            if (g_CorCompileVerboseLevel >= CORCOMPILE_VERBOSE)
-                GetSvcLogger()->Log(W("ReadyToRun: Type reference to equivalent type cannot be encoded\n"));
-            ThrowHR(E_NOTIMPL);
-        }
-
-        // FUTURE: Encoding of new cross-module references for ReadyToRun
-        // This warning is hit for recursive cross-module inlining. It is commented out to avoid noise.
-        // if (g_CorCompileVerboseLevel >= CORCOMPILE_VERBOSE)
-        //     GetSvcLogger()->Log(W("ReadyToRun: Type reference outside of current version bubble cannot be encoded\n"));
-        ThrowHR(E_NOTIMPL);
-    }
-    else
-#endif // FEATURE_READYTORUN_COMPILER
-    {
-        // FUTURE TODO: Version resilience
-        _ASSERTE(!"Cross module type reference not found");
-    }
-    ThrowHR(E_FAIL);
-}
-
-mdMemberRef Module::LookupMemberRefByMethodDesc(MethodDesc *pMD)
-{
-    STANDARD_VM_CONTRACT;
-
-    HENUMInternalHolder hEnumMemberRefs(GetMDImport());
-    mdMemberRef token;
-    hEnumMemberRefs.EnumAllInit(mdtMemberRef);
-    while (hEnumMemberRefs.EnumNext(&token))
-    {
-        BOOL fIsMethod = FALSE;
-        TADDR addr = LookupMemberRef(token, &fIsMethod);
-        if (fIsMethod)
-        {
-            MethodDesc *pCurMD = dac_cast<PTR_MethodDesc>(addr);
-            if (pCurMD == pMD)
-            {
-                return token;
-            }
-        }
-    }
-
-    // FUTURE TODO: Version resilience
-    _ASSERTE(!"Cross module method reference not found");
-    ThrowHR(E_FAIL);
-}
-#endif // FEATURE_NATIVE_IMAGE_GENERATION
-
 #ifndef DACCESS_COMPILE
 
 //
@@ -5574,71 +5397,6 @@ HRESULT Module::GetPropertyInfoForMethodDef(mdMethodDef md, mdProperty *ppd, LPC
     return GetMDImport()->GetPropertyInfoForMethodDef(md, ppd, pName, pSemantic);
 }
 
-#ifdef FEATURE_NATIVE_IMAGE_GENERATION
-// Fill the m_propertyNameSet hash filter with data that represents every
-// property and its name in the module.
-void Module::PrecomputeMatchingProperties(DataImage *image)
-{
-    CONTRACTL
-    {
-        STANDARD_VM_CHECK;
-        PRECONDITION(IsCompilationProcess());
-    }
-    CONTRACTL_END;
-
-    IMDInternalImport* mdImport = GetMDImport();
-
-    m_nPropertyNameSet = mdImport->GetCountWithTokenKind(mdtProperty);
-
-    if (m_nPropertyNameSet == 0)
-    {
-        return;
-    }
-
-    m_propertyNameSet = new (image->GetHeap()) BYTE[m_nPropertyNameSet];
-
-    DWORD nEnumeratedProperties = 0;
-
-    HENUMInternalHolder   hEnumTypes(mdImport);
-    hEnumTypes.EnumAllInit(mdtTypeDef);
-
-    // Enumerate all properties of all types
-    mdTypeDef tkType;
-    while (hEnumTypes.EnumNext(&tkType))
-    {
-        HENUMInternalHolder   hEnumPropertiesForType(mdImport);
-        hEnumPropertiesForType.EnumInit(mdtProperty, tkType);
-
-        mdProperty tkProperty;
-        while (hEnumPropertiesForType.EnumNext(&tkProperty))
-        {
-            LPCSTR name;
-            HRESULT hr = GetMDImport()->GetPropertyProps(tkProperty, &name, NULL, NULL, NULL);
-            IfFailThrow(hr);
-
-            ++nEnumeratedProperties;
-
-            // Use a case-insensitive hash so that we can use this value for
-            // both case-sensitive and case-insensitive name lookups
-            SString ssName(SString::Utf8Literal, name);
-            ULONG nameHashValue = ssName.HashCaseInsensitive();
-
-            // Set one bit in m_propertyNameSet per iteration
-            // This will allow lookup to ensure that the bit from each iteration is set
-            // and if any are not set, know that the (tkProperty,name) pair is not valid
-            for (DWORD i = 0; i < NUM_PROPERTY_SET_HASHES; ++i)
-            {
-                DWORD currentHashValue = HashThreeToOne(tkProperty, nameHashValue, i);
-                DWORD bitPos = currentHashValue % (m_nPropertyNameSet * 8);
-                m_propertyNameSet[bitPos / 8] |= (1 << bitPos % 8);
-            }
-        }
-    }
-
-    _ASSERTE(nEnumeratedProperties == m_nPropertyNameSet);
-}
-#endif // FEATURE_NATIVE_IMAGE_GENERATION
-
 // Check whether the module might possibly have a property with a name with
 // the passed hash value without accessing the property's name.  This is done
 // by consulting a hash filter populated at NGen time.
@@ -5679,50 +5437,6 @@ BOOL Module::MightContainMatchingProperty(mdProperty tkProperty, ULONG nameHash)
     return TRUE;
 }
 
-#ifdef FEATURE_NATIVE_IMAGE_GENERATION
-// Ensure that all elements and flags that we want persisted in the LookupMaps are present
-void Module::FinalizeLookupMapsPreSave(DataImage *image)
-{
-    CONTRACTL
-    {
-        STANDARD_VM_CHECK;
-        PRECONDITION(IsCompilationProcess());
-    }
-    CONTRACTL_END;
-
-    // For each typedef, if it does not need a restore, add the ZAPPED_TYPE_NEEDS_NO_RESTORE flag
-    {
-        LookupMap<PTR_MethodTable>::Iterator typeDefIter(&m_TypeDefToMethodTableMap);
-
-        while (typeDefIter.Next())
-        {
-            MethodTable * pMT = typeDefIter.GetElement();
-
-            if (pMT != NULL && !pMT->NeedsRestore(image))
-            {
-                m_TypeDefToMethodTableMap.AddFlag(RidFromToken(pMT->GetCl()), ZAPPED_TYPE_NEEDS_NO_RESTORE);
-            }
-        }
-    }
-
-    // For each canonical instantiation of a generic type def, if it does not need a restore, add the ZAPPED_GENERIC_TYPE_NEEDS_NO_RESTORE flag
-    {
-        LookupMap<PTR_MethodTable>::Iterator genericTypeDefIter(&m_GenericTypeDefToCanonMethodTableMap);
-
-        while (genericTypeDefIter.Next())
-        {
-            MethodTable * pMT = genericTypeDefIter.GetElement();
-
-            if (pMT != NULL && !pMT->NeedsRestore(image))
-            {
-                m_GenericTypeDefToCanonMethodTableMap.AddFlag(RidFromToken(pMT->GetCl()), ZAPPED_GENERIC_TYPE_NEEDS_NO_RESTORE);
-            }
-        }
-    }
-
-}
-#endif // FEATURE_NATIVE_IMAGE_GENERATION
-
 // Return true if this module has any live (jitted) JMC functions.
 // If a module has no jitted JMC functions, then it's as if it's a
 // non-user module.
@@ -6340,3600 +6054,114 @@ LoaderHeap *Module::GetThunkHeap()
 }
 #endif // !CROSSGEN_COMPILE
 
-#ifdef FEATURE_NATIVE_IMAGE_GENERATION
-
-// These helpers are used in Module::ExpandAll
-// to avoid EX_TRY/EX_CATCH in a loop (uses _alloca and guzzles stack)
-
-static TypeHandle LoadTypeDefOrRefHelper(DataImage * image, Module * pModule, mdToken tk)
+Module *Module::GetModuleFromIndex(DWORD ix)
 {
-    STANDARD_VM_CONTRACT;
-
-    TypeHandle th;
+    CONTRACT(Module*)
+    {
+        INSTANCE_CHECK;
+        THROWS;
+        GC_TRIGGERS;
+        MODE_ANY;
+        POSTCONDITION(CheckPointer(RETVAL, NULL_OK));
+    }
+    CONTRACT_END;
 
-    EX_TRY
+    if (HasNativeOrReadyToRunImage())
     {
-        th = ClassLoader::LoadTypeDefOrRefThrowing(pModule, tk,
-                                              ClassLoader::ThrowIfNotFound,
-                                              ClassLoader::PermitUninstDefOrRef);
+        RETURN ZapSig::DecodeModuleFromIndex(this, ix);
     }
-    EX_CATCH
+    else
     {
-        image->GetPreloader()->Error(tk, GET_EXCEPTION());
+        mdAssemblyRef mdAssemblyRefToken = TokenFromRid(ix, mdtAssemblyRef);
+        Assembly *pAssembly = this->LookupAssemblyRef(mdAssemblyRefToken);
+        if (pAssembly)
+        {
+            RETURN pAssembly->GetManifestModule();
+        }
+        else
+        {
+            // GetModuleFromIndex failed
+            RETURN NULL;
+        }
     }
-    EX_END_CATCH(SwallowAllExceptions)
-
-    return th;
 }
 
-static TypeHandle LoadTypeSpecHelper(DataImage * image, Module * pModule, mdToken tk,
-                                     PCCOR_SIGNATURE pSig, ULONG cSig)
+#endif // !DACCESS_COMPILE
+
+Module *Module::GetModuleFromIndexIfLoaded(DWORD ix)
 {
-    STANDARD_VM_CONTRACT;
+    CONTRACT(Module*)
+    {
+        INSTANCE_CHECK;
+        NOTHROW;
+        GC_NOTRIGGER;
+        MODE_ANY;
+        PRECONDITION(HasNativeOrReadyToRunImage());
+        POSTCONDITION(CheckPointer(RETVAL, NULL_OK));
+    }
+    CONTRACT_END;
 
-    TypeHandle th;
+#ifndef DACCESS_COMPILE
+    RETURN ZapSig::DecodeModuleFromIndexIfLoaded(this, ix);
+#else // DACCESS_COMPILE
+    DacNotImpl();
+    RETURN NULL;
+#endif // DACCESS_COMPILE
+}
 
-    EX_TRY
+#ifndef DACCESS_COMPILE
+IMDInternalImport* Module::GetNativeAssemblyImport(BOOL loadAllowed)
+{
+    CONTRACT(IMDInternalImport*)
     {
-        SigPointer p(pSig, cSig);
-        SigTypeContext typeContext;
-        th = p.GetTypeHandleThrowing(pModule, &typeContext);
+        INSTANCE_CHECK;
+        if (loadAllowed) GC_TRIGGERS;                    else GC_NOTRIGGER;
+        if (loadAllowed) THROWS;                         else NOTHROW;
+        if (loadAllowed) INJECT_FAULT(COMPlusThrowOM()); else FORBID_FAULT;
+        MODE_ANY;
+        PRECONDITION(HasNativeOrReadyToRunImage());
+        POSTCONDITION(loadAllowed ?
+            CheckPointer(RETVAL) :
+            CheckPointer(RETVAL, NULL_OK));
     }
-    EX_CATCH
+    CONTRACT_END;
+
+#ifdef FEATURE_PREJIT
+    // Check if image is R2R
+    if (!GetFile()->IsILImageReadyToRun())
     {
-        image->GetPreloader()->Error(tk, GET_EXCEPTION());
+        RETURN GetFile()->GetPersistentNativeImage()->GetNativeMDImport(loadAllowed);
     }
-    EX_END_CATCH(SwallowAllExceptions)
+#endif
 
-    return th;
+    RETURN GetFile()->GetOpenedILimage()->GetNativeMDImport(loadAllowed);
 }
 
-static TypeHandle LoadGenericInstantiationHelper(DataImage * image, Module * pModule, mdToken tk, Instantiation inst)
+BYTE* Module::GetNativeFixupBlobData(RVA rva)
 {
-    STANDARD_VM_CONTRACT;
-
-    TypeHandle th;
-
-    EX_TRY
-    {
-        th = ClassLoader::LoadGenericInstantiationThrowing(pModule, tk, inst);
-    }
-    EX_CATCH
+    CONTRACT(BYTE*)
     {
-        image->GetPreloader()->Error(tk, GET_EXCEPTION());
+        INSTANCE_CHECK;
+        NOTHROW;
+        GC_NOTRIGGER;
+        MODE_ANY;
+        POSTCONDITION(CheckPointer(RETVAL));
     }
-    EX_END_CATCH(SwallowAllExceptions)
+    CONTRACT_END;
 
-    return th;
+    RETURN(BYTE*) GetNativeOrReadyToRunImage()->GetRvaData(rva);
 }
+#endif // DACCESS_COMPILE
+
+#ifndef DACCESS_COMPILE
+//-----------------------------------------------------------------------------
 
-static void GetDescFromMemberRefHelper(DataImage * image, Module * pModule, mdToken tk)
+void Module::RunEagerFixups()
 {
     STANDARD_VM_CONTRACT;
 
-    EX_TRY
-    {
-        MethodDesc * pMD = NULL;
-        FieldDesc * pFD = NULL;
-        TypeHandle th;
-
-        // Note: using an empty type context is now OK, because even though the token is a MemberRef
-        // neither the token nor its parent will directly refer to type variables.
-        // @TODO GENERICS: want to allow loads of generic methods here but need strict metadata checks on parent
-        SigTypeContext typeContext;
-        MemberLoader::GetDescFromMemberRef(pModule, tk, &pMD, &pFD,
-                &typeContext,
-                FALSE /* strict metadata checks */, &th);
-    }
-    EX_CATCH
-    {
-        image->GetPreloader()->Error(tk, GET_EXCEPTION());
-    }
-    EX_END_CATCH(SwallowAllExceptions)
-}
-
-void Module::SetProfileData(CorProfileData * profileData)
-{
-    LIMITED_METHOD_CONTRACT;
-    m_pProfileData = profileData;
-}
-
-CorProfileData * Module::GetProfileData()
-{
-    LIMITED_METHOD_CONTRACT;
-    return m_pProfileData;
-}
-
-mdTypeDef Module::LookupIbcTypeToken(Module *  pExternalModule, mdToken ibcToken, SString* optionalFullNameOut)
-{
-    CONTRACTL
-    {
-        THROWS;
-        GC_TRIGGERS;
-        MODE_ANY;
-    }
-    CONTRACTL_END
-
-    _ASSERTE(TypeFromToken(ibcToken) == ibcExternalType);
-
-    CorProfileData *  profileData  = this->GetProfileData();
-
-    CORBBTPROF_BLOB_TYPE_DEF_ENTRY *  blobTypeDefEntry;
-    blobTypeDefEntry = profileData->GetBlobExternalTypeDef(ibcToken);
-
-    if (blobTypeDefEntry == NULL)
-        return mdTypeDefNil;
-
-    IbcNameHandle  ibcName;
-    ibcName.szName           = &blobTypeDefEntry->name[0];
-    ibcName.tkIbcNameSpace   = blobTypeDefEntry->nameSpaceToken;
-    ibcName.tkIbcNestedClass = blobTypeDefEntry->nestedClassToken;
-    ibcName.szNamespace      = NULL;
-    ibcName.tkEnclosingClass = mdTypeDefNil;
-
-    if (!IsNilToken(blobTypeDefEntry->nameSpaceToken))
-    {
-        _ASSERTE(IsNilToken(blobTypeDefEntry->nestedClassToken));
-
-        idExternalNamespace nameSpaceToken = blobTypeDefEntry->nameSpaceToken;
-        _ASSERTE(TypeFromToken(nameSpaceToken) == ibcExternalNamespace);
-
-        CORBBTPROF_BLOB_NAMESPACE_DEF_ENTRY *  blobNamespaceDefEntry;
-        blobNamespaceDefEntry = profileData->GetBlobExternalNamespaceDef(nameSpaceToken);
-
-        if (blobNamespaceDefEntry == NULL)
-            return mdTypeDefNil;
-
-        ibcName.szNamespace = &blobNamespaceDefEntry->name[0];
-
-        if (optionalFullNameOut != NULL)
-        {
-            optionalFullNameOut->Append(W("["));
-            optionalFullNameOut->AppendUTF8(pExternalModule->GetSimpleName());
-            optionalFullNameOut->Append(W("]"));
-
-            if ((ibcName.szNamespace != NULL) && ((*ibcName.szNamespace) != W('\0')))
-            {
-                optionalFullNameOut->AppendUTF8(ibcName.szNamespace);
-                optionalFullNameOut->Append(W("."));
-            }
-            optionalFullNameOut->AppendUTF8(ibcName.szName);
-        }
-    }
-    else if (!IsNilToken(blobTypeDefEntry->nestedClassToken))
-    {
-        idExternalType nestedClassToken = blobTypeDefEntry->nestedClassToken;
-        _ASSERTE(TypeFromToken(nestedClassToken) == ibcExternalType);
-
-        ibcName.tkEnclosingClass = LookupIbcTypeToken(pExternalModule, nestedClassToken, optionalFullNameOut);
-
-        if (optionalFullNameOut != NULL)
-        {
-            optionalFullNameOut->Append(W("+"));
-            optionalFullNameOut->AppendUTF8(ibcName.szName);
-        }
-
-        if (IsNilToken(ibcName.tkEnclosingClass))
-            return  mdTypeDefNil;
-    }
-
-    //*****************************************
-    // look up function for TypeDef
-    //*****************************************
-    // STDMETHOD(FindTypeDef)(
-    //     LPCSTR      szNamespace,            // [IN] Namespace for the TypeDef.
-    //     LPCSTR      szName,                 // [IN] Name of the TypeDef.
-    //     mdToken     tkEnclosingClass,       // [IN] TypeRef/TypeDef Token for the enclosing class.
-    //     mdTypeDef   *ptypedef) PURE;        // [IN] return typedef
-
-    IMDInternalImport *pInternalImport = pExternalModule->GetMDImport();
-
-    mdTypeDef mdResult = mdTypeDefNil;
-
-    HRESULT hr = pInternalImport->FindTypeDef(ibcName.szNamespace, ibcName.szName, ibcName.tkEnclosingClass, &mdResult);
-
-    if(FAILED(hr))
-        mdResult = mdTypeDefNil;
-
-    return mdResult;
-}
-
-struct IbcCompareContext
-{
-    Module *         pModule;
-    TypeHandle       enclosingType;
-    DWORD            cMatch;      // count of methods that had a matching method name
-    bool             useBestSig;  // if true we should use the BestSig when we don't find an exact match
-    PCCOR_SIGNATURE  pvBestSig;   // Current Best matching signature
-    DWORD            cbBestSig;   //
-};
-
-//---------------------------------------------------------------------------------------
-//
-// Compare two signatures from the same scope.
-//
-BOOL
-CompareIbcMethodSigs(
-    PCCOR_SIGNATURE pvCandidateSig, // Candidate signature
-    DWORD           cbCandidateSig, //
-    PCCOR_SIGNATURE pvIbcSignature, // The Ibc signature that we want to match
-    DWORD           cbIbcSignature, //
-    void *          pvContext)      // void pointer to IbcCompareContext
-{
-    CONTRACTL
-    {
-        THROWS;
-        GC_TRIGGERS;
-        MODE_ANY;
-    }
-    CONTRACTL_END
-
-    //
-    // Same pointer return TRUE
-    //
-    if (pvCandidateSig == pvIbcSignature)
-    {
-        _ASSERTE(cbCandidateSig == cbIbcSignature);
-        return TRUE;
-    }
-
-    //
-    // Check for exact match
-    //
-    if (cbCandidateSig == cbIbcSignature)
-    {
-        if (memcmp(pvCandidateSig, pvIbcSignature, cbIbcSignature) == 0)
-        {
-            return TRUE;
-        }
-    }
-
-    IbcCompareContext * context = (IbcCompareContext *) pvContext;
-
-    //
-    // No exact match, we will return FALSE and keep looking at other matching method names
-    //
-    // However since the method name was an exact match we will remember this signature,
-    // so that if it is the best match we can look it up again and return it's methodDef token
-    //
-    if (context->cMatch == 0)
-    {
-        context->pvBestSig = pvCandidateSig;
-        context->cbBestSig = cbCandidateSig;
-        context->cMatch = 1;
-        context->useBestSig = true;
-    }
-    else
-    {
-        context->cMatch++;
-
-        SigTypeContext emptyTypeContext;
-        SigTypeContext ibcTypeContext =  SigTypeContext(context->enclosingType);
-        MetaSig ibcSignature (pvIbcSignature, cbIbcSignature, context->pModule, &ibcTypeContext);
-
-        MetaSig candidateSig (pvCandidateSig, cbCandidateSig, context->pModule, &emptyTypeContext);
-        MetaSig bestSignature(context->pvBestSig, context->cbBestSig, context->pModule, &emptyTypeContext);
-        //
-        // Is candidateSig a better match than bestSignature?
-        //
-        // First check the calling convention
-        //
-        if (candidateSig.GetCallingConventionInfo() != bestSignature.GetCallingConventionInfo())
-        {
-            if (bestSignature.GetCallingConventionInfo() == ibcSignature.GetCallingConventionInfo())
-                goto LEAVE_BEST;
-            if (candidateSig.GetCallingConventionInfo() == ibcSignature.GetCallingConventionInfo())
-                goto SELECT_CANDIDATE;
-            //
-            // Neither one is a match
-            //
-            goto USE_NEITHER;
-        }
-
-        //
-        // Next check the number of arguments
-        //
-        if (candidateSig.NumFixedArgs() != bestSignature.NumFixedArgs())
-        {
-            //
-            // Does one of the two have the same number of args?
-            //
-            if (bestSignature.NumFixedArgs() == ibcSignature.NumFixedArgs())
-                goto LEAVE_BEST;
-            if (candidateSig.NumFixedArgs() == ibcSignature.NumFixedArgs())
-                goto SELECT_CANDIDATE;
-            //
-            // Neither one is a match
-            //
-            goto USE_NEITHER;
-        }
-        else if (candidateSig.NumFixedArgs() != ibcSignature.NumFixedArgs())
-        {
-            //
-            // Neither one is a match
-            //
-            goto USE_NEITHER;
-        }
-
-        CorElementType  etIbc;
-        CorElementType  etCandidate;
-        CorElementType  etBest;
-        //
-        // Next get the return element type
-        //
-        // etIbc = ibcSignature.GetReturnProps().PeekElemTypeClosed(ibcSignature.GetSigTypeContext());
-        IfFailThrow(ibcSignature.GetReturnProps().PeekElemType(&etIbc));
-        IfFailThrow(candidateSig.GetReturnProps().PeekElemType(&etCandidate));
-        IfFailThrow(bestSignature.GetReturnProps().PeekElemType(&etBest));
-        //
-        // Do they have different return types?
-        //
-        if (etCandidate != etBest)
-        {
-            if (etBest == etIbc)
-                goto LEAVE_BEST;
-
-            if (etCandidate == etIbc)
-                goto SELECT_CANDIDATE;
-        }
-
-        //
-        // Now iterate over the method argument types to see which signature
-        // is the better match
-        //
-        for (DWORD i = 0; (i < ibcSignature.NumFixedArgs()); i++)
-        {
-            ibcSignature.SkipArg();
-            IfFailThrow(ibcSignature.GetArgProps().PeekElemType(&etIbc));
-
-            candidateSig.SkipArg();
-            IfFailThrow(candidateSig.GetArgProps().PeekElemType(&etCandidate));
-
-            bestSignature.SkipArg();
-            IfFailThrow(bestSignature.GetArgProps().PeekElemType(&etBest));
-
-            //
-            // Do they have different argument types?
-            //
-            if (etCandidate != etBest)
-            {
-                if (etBest == etIbc)
-                    goto LEAVE_BEST;
-
-                if (etCandidate == etIbc)
-                    goto SELECT_CANDIDATE;
-            }
-        }
-        // When we fall though to here we did not find any differences
-        // that we could base a choice on
-        //
-         context->useBestSig = true;
-
-SELECT_CANDIDATE:
-        context->pvBestSig = pvCandidateSig;
-        context->cbBestSig = cbCandidateSig;
-        context->useBestSig = true;
-        return FALSE;
-
-USE_NEITHER:
-        context->useBestSig = false;
-        return FALSE;
-    }
-
-LEAVE_BEST:
-    return FALSE;
-} // CompareIbcMethodSigs
-
-mdMethodDef Module::LookupIbcMethodToken(TypeHandle enclosingType, mdToken ibcToken, SString* optionalFullNameOut)
-{
-    CONTRACTL
-    {
-        THROWS;
-        GC_TRIGGERS;
-        MODE_ANY;
-    }
-    CONTRACTL_END
-
-    _ASSERTE(TypeFromToken(ibcToken) == ibcExternalMethod);
-
-    CorProfileData *  profileData  = this->GetProfileData();
-
-    CORBBTPROF_BLOB_METHOD_DEF_ENTRY *  blobMethodDefEntry;
-    blobMethodDefEntry = profileData->GetBlobExternalMethodDef(ibcToken);
-
-    if (blobMethodDefEntry == NULL)
-        return mdMethodDefNil;
-
-    idExternalType signatureToken = blobMethodDefEntry->signatureToken;
-    _ASSERTE(!IsNilToken(signatureToken));
-    _ASSERTE(TypeFromToken(signatureToken) == ibcExternalSignature);
-
-    CORBBTPROF_BLOB_SIGNATURE_DEF_ENTRY *  blobSignatureDefEntry;
-    blobSignatureDefEntry = profileData->GetBlobExternalSignatureDef(signatureToken);
-
-    if (blobSignatureDefEntry == NULL)
-        return mdMethodDefNil;
-
-    IbcNameHandle    ibcName;
-    ibcName.szName                    = &blobMethodDefEntry->name[0];
-    ibcName.tkIbcNestedClass          = blobMethodDefEntry->nestedClassToken;
-    ibcName.tkIbcNameSpace            = idExternalNamespaceNil;
-    ibcName.szNamespace               = NULL;
-    ibcName.tkEnclosingClass          = mdTypeDefNil;
-
-    Module *         pExternalModule  = enclosingType.GetModule();
-    PCCOR_SIGNATURE  pvSig            = NULL;
-    ULONG            cbSig            = 0;
-
-    _ASSERTE(!IsNilToken(ibcName.tkIbcNestedClass));
-    _ASSERTE(TypeFromToken(ibcName.tkIbcNestedClass) == ibcExternalType);
-
-    ibcName.tkEnclosingClass = LookupIbcTypeToken(pExternalModule, ibcName.tkIbcNestedClass, optionalFullNameOut);
-
-    if (IsNilToken(ibcName.tkEnclosingClass))
-    {
-        COMPlusThrow(kTypeLoadException, IDS_IBC_MISSING_EXTERNAL_TYPE);
-    }
-
-    if (optionalFullNameOut != NULL)
-    {
-        optionalFullNameOut->Append(W("."));
-        optionalFullNameOut->AppendUTF8(ibcName.szName);    // MethodName
-        optionalFullNameOut->Append(W("()"));
-    }
-
-    pvSig = blobSignatureDefEntry->sig;
-    cbSig = blobSignatureDefEntry->cSig;
-
-    //*****************************************
-    // look up functions for TypeDef
-    //*****************************************
-    // STDMETHOD(FindMethodDefUsingCompare)(
-    //     mdTypeDef   classdef,               // [IN] given typedef
-    //     LPCSTR      szName,                 // [IN] member name
-    //     PCCOR_SIGNATURE pvSigBlob,          // [IN] point to a blob value of CLR signature
-    //     ULONG       cbSigBlob,              // [IN] count of bytes in the signature blob
-    //     PSIGCOMPARE pSignatureCompare,      // [IN] Routine to compare signatures
-    //     void*       pSignatureArgs,         // [IN] Additional info to supply the compare function
-    //     mdMethodDef *pmd) PURE;             // [OUT] matching memberdef
-    //
-
-    IMDInternalImport *  pInternalImport = pExternalModule->GetMDImport();
-
-    IbcCompareContext context;
-    memset(&context, 0, sizeof(IbcCompareContext));
-    context.pModule = this;
-    context.enclosingType = enclosingType;
-    context.cMatch = 0;
-    context.useBestSig = false;
-
-    mdMethodDef mdResult = mdMethodDefNil;
-    HRESULT hr = pInternalImport->FindMethodDefUsingCompare(ibcName.tkEnclosingClass, ibcName.szName,
-                                                            pvSig, cbSig,
-                                                            CompareIbcMethodSigs, (void *) &context,
-                                                            &mdResult);
-    if (SUCCEEDED(hr))
-    {
-        _ASSERTE(mdResult != mdMethodDefNil);
-    }
-    else if (context.useBestSig)
-    {
-        hr = pInternalImport->FindMethodDefUsingCompare(ibcName.tkEnclosingClass, ibcName.szName,
-                                                        context.pvBestSig, context.cbBestSig,
-                                                        CompareIbcMethodSigs, (void *) &context,
-                                                        &mdResult);
-        _ASSERTE(SUCCEEDED(hr));
-        _ASSERTE(mdResult != mdMethodDefNil);
-    }
-    else
-    {
-        mdResult = mdMethodDefNil;
-    }
-
-    return mdResult;
-}
-
-TypeHandle Module::LoadIBCTypeHelper(DataImage *image, CORBBTPROF_BLOB_PARAM_SIG_ENTRY *pBlobSigEntry)
-{
-    CONTRACT(TypeHandle)
-    {
-        NOTHROW;
-        GC_TRIGGERS;
-        MODE_ANY;
-        INJECT_FAULT(COMPlusThrowOM());
-        PRECONDITION(CheckPointer(pBlobSigEntry));
-    }
-    CONTRACT_END
-
-    TypeHandle         loadedType;
-
-    PCCOR_SIGNATURE    pSig = pBlobSigEntry->sig;
-    ULONG              cSig = pBlobSigEntry->cSig;
-
-    SigPointer         p(pSig, cSig);
-
-    ZapSig::Context    zapSigContext(this, (void *)this, ZapSig::IbcTokens);
-    ZapSig::Context *  pZapSigContext = &zapSigContext;
-
-    EX_TRY
-    {
-        // This is what ZapSig::FindTypeHandleFromSignature does...
-        //
-        SigTypeContext typeContext;  // empty type context
-
-        loadedType = p.GetTypeHandleThrowing( this,
-                                              &typeContext,
-                                              ClassLoader::LoadTypes,
-                                              CLASS_LOADED,
-                                              FALSE,
-                                              NULL,
-                                              pZapSigContext);
-#if defined(_DEBUG) && !defined(DACCESS_COMPILE)
-        g_pConfig->DebugCheckAndForceIBCFailure(EEConfig::CallSite_1);
-#endif
-    }
-    EX_CATCH
-    {
-        if (g_CorCompileVerboseLevel >= CORCOMPILE_VERBOSE)
-            image->GetPreloader()->Error(pBlobSigEntry->blob.token, GET_EXCEPTION());
-
-        loadedType = TypeHandle();
-    }
-    EX_END_CATCH(SwallowAllExceptions)
-
-    RETURN loadedType;
-}
-
-//---------------------------------------------------------------------------------------
-//
-MethodDesc* Module::LoadIBCMethodHelper(DataImage *image, CORBBTPROF_BLOB_PARAM_SIG_ENTRY * pBlobSigEntry)
-{
-    CONTRACT(MethodDesc*)
-    {
-        NOTHROW;
-        GC_TRIGGERS;
-        MODE_ANY;
-        INJECT_FAULT(COMPlusThrowOM());
-        PRECONDITION(CheckPointer(pBlobSigEntry));
-    }
-    CONTRACT_END
-
-    MethodDesc* pMethod = NULL;
-
-    PCCOR_SIGNATURE    pSig = pBlobSigEntry->sig;
-    ULONG              cSig = pBlobSigEntry->cSig;
-
-    SigPointer p(pSig, cSig);
-
-    ZapSig::Context    zapSigContext(this, (void *)this, ZapSig::IbcTokens);
-    ZapSig::Context *  pZapSigContext = &zapSigContext;
-
-    TypeHandle         enclosingType;
-
-    //
-    //  First Decode and Load the enclosing type for this method
-    //
-    EX_TRY
-    {
-        // This is what ZapSig::FindTypeHandleFromSignature does...
-        //
-        SigTypeContext typeContext;   // empty type context
-
-        enclosingType = p.GetTypeHandleThrowing( this,
-                                  &typeContext,
-                                  ClassLoader::LoadTypes,
-                                  CLASS_LOADED,
-                                  FALSE,
-                                  NULL,
-                                  pZapSigContext);
-        IfFailThrow(p.SkipExactlyOne());
-#if defined(_DEBUG) && !defined(DACCESS_COMPILE)
-        g_pConfig->DebugCheckAndForceIBCFailure(EEConfig::CallSite_2);
-#endif
-    }
-    EX_CATCH
-    {
-        if (g_CorCompileVerboseLevel >= CORCOMPILE_VERBOSE)
-            image->GetPreloader()->Error(pBlobSigEntry->blob.token, GET_EXCEPTION());
-
-        enclosingType = TypeHandle();
-    }
-    EX_END_CATCH(SwallowAllExceptions)
-
-    if (enclosingType.IsNull())
-        return NULL;
-
-    //
-    //  Now Decode and Load the method
-    //
-    EX_TRY
-    {
-        MethodTable *pOwnerMT = enclosingType.GetMethodTable();
-        _ASSERTE(pOwnerMT != NULL);
-
-        // decode flags
-        uint32_t methodFlags;
-        IfFailThrow(p.GetData(&methodFlags));
-        BOOL isInstantiatingStub = ((methodFlags & ENCODE_METHOD_SIG_InstantiatingStub) == ENCODE_METHOD_SIG_InstantiatingStub);
-        BOOL isUnboxingStub = ((methodFlags & ENCODE_METHOD_SIG_UnboxingStub) == ENCODE_METHOD_SIG_UnboxingStub);
-        BOOL fMethodNeedsInstantiation = ((methodFlags & ENCODE_METHOD_SIG_MethodInstantiation) == ENCODE_METHOD_SIG_MethodInstantiation);
-        BOOL fMethodUsesSlotEncoding = ((methodFlags & ENCODE_METHOD_SIG_SlotInsteadOfToken) == ENCODE_METHOD_SIG_SlotInsteadOfToken);
-
-        if ( fMethodUsesSlotEncoding )
-        {
-            // get the method desc using slot number
-            uint32_t slot;
-            IfFailThrow(p.GetData(&slot));
-
-            if (slot >= pOwnerMT->GetNumVtableSlots())
-            {
-                COMPlusThrow(kTypeLoadException, IDS_IBC_MISSING_EXTERNAL_METHOD);
-            }
-
-            pMethod = pOwnerMT->GetMethodDescForSlot(slot);
-        }
-        else  // otherwise we use the normal metadata MethodDef token encoding and we handle ibc tokens.
-        {
-            //
-            // decode method token
-            //
-            RID methodRid;
-            IfFailThrow(p.GetData(&methodRid));
-
-            mdMethodDef methodToken;
-
-            //
-            //  Is our enclosingType from another module?
-            //
-            if (this == enclosingType.GetModule())
-            {
-                //
-                // The enclosing type is from our module
-                // The method token is a normal MethodDef token
-                //
-                methodToken = TokenFromRid(methodRid, mdtMethodDef);
-            }
-            else
-            {
-                //
-                // The enclosing type is from an external module
-                // The method token is a ibcExternalMethod token
-                //
-                idExternalType ibcToken = RidToToken(methodRid, ibcExternalMethod);
-                methodToken = this->LookupIbcMethodToken(enclosingType, ibcToken);
-
-                if (IsNilToken(methodToken))
-                {
-                    COMPlusThrow(kTypeLoadException, IDS_IBC_MISSING_EXTERNAL_METHOD);
-                }
-            }
-
-            SigTypeContext methodTypeContext( enclosingType );
-            pMethod = MemberLoader::GetMethodDescFromMemberDefOrRefOrSpec(
-                                                  pOwnerMT->GetModule(),
-                                                  methodToken,
-                                                  &methodTypeContext,
-                                                  FALSE,
-                                                  FALSE );
-        }
-
-        Instantiation inst;
-
-        // Instantiate the method if needed, or create a stub to a static method in a generic class.
-        if (fMethodNeedsInstantiation && pMethod->HasMethodInstantiation())
-        {
-            DWORD nargs = pMethod->GetNumGenericMethodArgs();
-            SIZE_T cbMem;
-
-            if (!ClrSafeInt<SIZE_T>::multiply(nargs, sizeof(TypeHandle), cbMem/* passed by ref */))
-                ThrowHR(COR_E_OVERFLOW);
-
-            TypeHandle * pInst = (TypeHandle*) _alloca(cbMem);
-            SigTypeContext typeContext;   // empty type context
-
-            for (DWORD i = 0; i < nargs; i++)
-            {
-                TypeHandle curInst;
-
-                curInst = p.GetTypeHandleThrowing( this,
-                              &typeContext,
-                              ClassLoader::LoadTypes,
-                              CLASS_LOADED,
-                              FALSE,
-                              NULL,
-                              pZapSigContext);
-
-                // curInst will be nullptr when the type fails the versioning bubble check
-                if (curInst.IsNull() && IsReadyToRunCompilation())
-                {
-                    COMPlusThrow(kTypeLoadException, IDS_IBC_MISSING_EXTERNAL_TYPE);
-                }
-
-                pInst[i] = curInst;
-                IfFailThrow(p.SkipExactlyOne());
-            }
-
-            inst = Instantiation(pInst, nargs);
-        }
-        else
-        {
-            inst = pMethod->LoadMethodInstantiation();
-        }
-
-        // We should now be able to create an instantiation for this generic method
-
-        // This must be called even if nargs == 0, in order to create an instantiating
-        // stub for static methods in generic classees if needed, also for BoxedEntryPointStubs
-        // in non-generic structs.
-        const bool allowInstParam = !(isInstantiatingStub || isUnboxingStub);
-
-        pMethod = MethodDesc::FindOrCreateAssociatedMethodDesc(pMethod, pOwnerMT,
-                                                               isUnboxingStub,
-                                                               inst, allowInstParam);
-
-#if defined(_DEBUG) && !defined(DACCESS_COMPILE)
-        g_pConfig->DebugCheckAndForceIBCFailure(EEConfig::CallSite_3);
-#endif
-    }
-    EX_CATCH
-    {
-        // Catch any kTypeLoadException that we may have thrown above
-        //
-        image->GetPreloader()->Error(pBlobSigEntry->blob.token, GET_EXCEPTION());
-        pMethod = NULL;
-    }
-    EX_END_CATCH(SwallowAllExceptions)
-
-    RETURN pMethod;
-} // Module::LoadIBCMethodHelper
-
-//---------------------------------------------------------------------------------------
-//
-void Module::ExpandAll(DataImage *image)
-{
-    CONTRACTL
-    {
-        STANDARD_VM_CHECK;
-        PRECONDITION(!IsResource());
-    }
-    CONTRACTL_END
-
-    mdToken tk;
-    DWORD assemblyFlags = GetAssembly()->GetFlags();
-
-    //
-    // Explicitly load the global class.
-    //
-
-    MethodTable *pGlobalMT = GetGlobalMethodTable();
-
-    //
-    // Load all classes.  This also fills out the
-    // RID maps for the typedefs, method defs,
-    // and field defs.
-    //
-
-    IMDInternalImport *pInternalImport = GetMDImport();
-    {
-        HENUMInternalHolder hEnum(pInternalImport);
-        hEnum.EnumTypeDefInit();
-
-        while (pInternalImport->EnumNext(&hEnum, &tk))
-        {
-            TypeHandle t = LoadTypeDefOrRefHelper(image, this, tk);
-
-            if (t.IsNull()) // Skip this type
-                continue;
-
-            if (!t.HasInstantiation())
-            {
-                EEClassHashEntry_t *pBucket = NULL;
-                HashDatum           data;
-                StackSString        ssFullyQualifiedName;
-                mdToken             mdEncloser;
-                EEClassHashTable   *pTable = GetAvailableClassHash();
-
-                _ASSERTE(pTable != NULL);
-
-                t.GetName(ssFullyQualifiedName);
-
-                // Convert to UTF8
-                StackScratchBuffer scratch;
-                LPCUTF8 szFullyQualifiedName = ssFullyQualifiedName.GetUTF8(scratch);
-
-                BOOL isNested = ClassLoader::IsNested(this, tk, &mdEncloser);
-                EEClassHashTable::LookupContext sContext;
-                pBucket = pTable->GetValue(szFullyQualifiedName, &data, isNested, &sContext);
-
-                if (isNested)
-                {
-                    while (pBucket != NULL)
-                    {
-                        _ASSERTE (TypeFromToken(tk) == mdtTypeDef);
-                        BOOL match = GetClassLoader()->CompareNestedEntryWithTypeDef( pInternalImport,
-                                                                                      mdEncloser,
-                                                                                      GetAvailableClassHash(),
-                                                                                      pBucket->GetEncloser());
-                        if (match)
-                            break;
-
-                        pBucket = pTable->FindNextNestedClass(szFullyQualifiedName, &data, &sContext);
-                    }
-                }
-
-                // Save the typehandle instead of the token in the hash entry so that ngen'ed images
-                // don't have to lookup based on token and update this entry
-                if ((pBucket != NULL) && !t.IsNull() && t.IsRestored())
-                    pBucket->SetData(t.AsPtr());
-            }
-
-            DWORD nGenericClassParams = t.GetNumGenericArgs();
-            if (nGenericClassParams != 0)
-            {
-                // For generic types, load the instantiation at Object
-                SIZE_T cbMem;
-                if (!ClrSafeInt<SIZE_T>::multiply(sizeof(TypeHandle), nGenericClassParams, cbMem/* passed by ref */))
-                {
-                    ThrowHR(COR_E_OVERFLOW);
-                }
-                CQuickBytes qbGenericClassArgs;
-                TypeHandle *genericClassArgs = reinterpret_cast<TypeHandle*>(qbGenericClassArgs.AllocThrows(cbMem));
-                for (DWORD i = 0; i < nGenericClassParams; i++)
-                {
-                    genericClassArgs[i] = TypeHandle(g_pCanonMethodTableClass);
-                }
-
-                TypeHandle thCanonInst = LoadGenericInstantiationHelper(image, this, tk, Instantiation(genericClassArgs, nGenericClassParams));
-
-                // If successful, add the instantiation to the Module's map of generic types instantiated at Object
-                if (!thCanonInst.IsNull() && !thCanonInst.IsTypeDesc())
-                {
-                    MethodTable * pCanonMT = thCanonInst.AsMethodTable();
-                    m_GenericTypeDefToCanonMethodTableMap.AddElement(this, RidFromToken(pCanonMT->GetCl()), pCanonMT);
-                }
-            }
-        }
-    }
-
-    //
-    // Fill out TypeRef RID map
-    //
-
-    {
-        HENUMInternalHolder hEnum(pInternalImport);
-        hEnum.EnumAllInit(mdtTypeRef);
-
-        while (pInternalImport->EnumNext(&hEnum, &tk))
-        {
-            mdToken tkResolutionScope = mdTokenNil;
-            pInternalImport->GetResolutionScopeOfTypeRef(tk, &tkResolutionScope);
-            TypeHandle t = LoadTypeDefOrRefHelper(image, this, tk);
-
-            if (t.IsNull()) // Skip this type
-                continue;
-        }
-    }
-
-    //
-    // Load all type specs
-    //
-
-    {
-        HENUMInternalHolder hEnum(pInternalImport);
-        hEnum.EnumAllInit(mdtTypeSpec);
-
-        while (pInternalImport->EnumNext(&hEnum, &tk))
-        {
-            ULONG cSig;
-            PCCOR_SIGNATURE pSig;
-
-            IfFailThrow(pInternalImport->GetTypeSpecFromToken(tk, &pSig, &cSig));
-
-            // Load all types specs that do not contain variables
-            if (SigPointer(pSig, cSig).IsPolyType(NULL) == hasNoVars)
-            {
-                LoadTypeSpecHelper(image, this, tk, pSig, cSig);
-            }
-        }
-    }
-
-    //
-    // Load all the reported parameterized types and methods
-    //
-    CorProfileData *  profileData = this->GetProfileData();
-    CORBBTPROF_BLOB_ENTRY *pBlobEntry = profileData ? profileData->GetBlobStream() : NULL;
-
-    if (pBlobEntry != NULL)
-    {
-        while (pBlobEntry->TypeIsValid())
-        {
-            if (TypeFromToken(pBlobEntry->token) == ibcTypeSpec)
-            {
-                _ASSERTE(pBlobEntry->type == ParamTypeSpec);
-                CORBBTPROF_BLOB_PARAM_SIG_ENTRY *pBlobSigEntry = (CORBBTPROF_BLOB_PARAM_SIG_ENTRY *) pBlobEntry;
-
-                TypeHandle th = LoadIBCTypeHelper(image, pBlobSigEntry);
-
-                if (!th.IsNull())
-                {
-                    image->GetPreloader()->TriageTypeForZap(th, TRUE);
-                }
-            }
-            else if (TypeFromToken(pBlobEntry->token) == ibcMethodSpec)
-            {
-                _ASSERTE(pBlobEntry->type == ParamMethodSpec);
-                CORBBTPROF_BLOB_PARAM_SIG_ENTRY *pBlobSigEntry = (CORBBTPROF_BLOB_PARAM_SIG_ENTRY *) pBlobEntry;
-
-                MethodDesc *pMD = LoadIBCMethodHelper(image, pBlobSigEntry);
-            }
-            pBlobEntry = pBlobEntry->GetNextEntry();
-        }
-        _ASSERTE(pBlobEntry->type == EndOfBlobStream);
-    }
-
-    if (profileData)
-    {
-        //
-        // Record references to all of the hot methods specifiled by MethodProfilingData array
-        // We call MethodReferencedByCompiledCode to indicate that we plan on compiling this method
-        //
-        CORBBTPROF_TOKEN_INFO * pMethodProfilingData = profileData->GetTokenFlagsData(MethodProfilingData);
-        DWORD                   cMethodProfilingData = profileData->GetTokenFlagsCount(MethodProfilingData);
-
-        for (unsigned int i = 0; (i < cMethodProfilingData); i++)
-        {
-            mdToken token = pMethodProfilingData[i].token;
-            DWORD   profilingFlags = pMethodProfilingData[i].flags;
-
-            // We call MethodReferencedByCompiledCode only when the profile data indicates that
-            // we executed (i.e read) the code for the method
-            //
-            if (profilingFlags & (1 << ReadMethodCode))
-            {
-                if (TypeFromToken(token) == mdtMethodDef)
-                {
-                    MethodDesc *  pMD = LookupMethodDef(token);
-
-                    if (pMD != NULL)
-                    {
-                        //
-                        // Record a reference to a hot non-generic method
-                        //
-                        image->GetPreloader()->MethodReferencedByCompiledCode((CORINFO_METHOD_HANDLE)pMD);
-                    }
-                }
-                else if (TypeFromToken(token) == ibcMethodSpec)
-                {
-                    CORBBTPROF_BLOB_PARAM_SIG_ENTRY *pBlobSigEntry = profileData->GetBlobSigEntry(token);
-
-                    if (pBlobSigEntry != NULL)
-                    {
-                        _ASSERTE(pBlobSigEntry->blob.token == token);
-                        MethodDesc * pMD = LoadIBCMethodHelper(image, pBlobSigEntry);
-
-                        if (pMD != NULL)
-                        {
-                            // Occasionally a non-instantiated generic method shows up in the IBC data, we should NOT compile it.
-                            if (!pMD->IsTypicalMethodDefinition())
-                            {
-                                //
-                                // Record a reference to a hot instantiated generic method
-                                //
-                                image->GetPreloader()->MethodReferencedByCompiledCode((CORINFO_METHOD_HANDLE)pMD);
-                            }
-                        }
-                    }
-                }
-            }
-        }
-    }
-
-    {
-        //
-        // Fill out MemberRef RID map and va sig cookies for
-        // varargs member refs.
-        //
-
-        HENUMInternalHolder hEnum(pInternalImport);
-        hEnum.EnumAllInit(mdtMemberRef);
-
-        while (pInternalImport->EnumNext(&hEnum, &tk))
-        {
-            mdTypeRef parent;
-            IfFailThrow(pInternalImport->GetParentOfMemberRef(tk, &parent));
-
-            // If the MethodRef has a TypeSpec as a parent (i.e. refers to a method on an array type
-            // or on a generic class), then it could in turn refer to type variables of
-            // an unknown class/method. So we don't preresolve any MemberRefs which have TypeSpecs as
-            // parents.  The RID maps are not filled out for such tokens anyway.
-            if (TypeFromToken(parent) != mdtTypeSpec)
-            {
-                GetDescFromMemberRefHelper(image, this, tk);
-            }
-        }
-    }
-
-    //
-    // Fill out binder
-    //
-
-    if (m_pBinder != NULL)
-    {
-        m_pBinder->BindAll();
-    }
-
-} // Module::ExpandAll
-
-/* static */
-void Module::SaveMethodTable(DataImage *    image,
-                             MethodTable *  pMT,
-                             DWORD          profilingFlags)
-{
-    STANDARD_VM_CONTRACT;
-
-    if (image->IsStored(pMT))
-        return;
-
-    pMT->Save(image, profilingFlags);
-}
-
-
-/* static */
-void Module::SaveTypeHandle(DataImage *  image,
-                            TypeHandle   t,
-                            DWORD        profilingFlags)
-{
-    STANDARD_VM_CONTRACT;
-
-    t.CheckRestore();
-    if (t.IsTypeDesc())
-    {
-        TypeDesc *pTD = t.AsTypeDesc();
-        if (!image->IsStored(pTD))
-        {
-            pTD->Save(image);
-        }
-    }
-    else
-    {
-        MethodTable *pMT = t.AsMethodTable();
-        if (pMT != NULL && !image->IsStored(pMT))
-        {
-            SaveMethodTable(image, pMT, profilingFlags);
-            _ASSERTE(image->IsStored(pMT));
-        }
-    }
-#ifdef _DEBUG
-    if (LoggingOn(LF_JIT, LL_INFO100))
-    {
-        Module *pPrefModule = Module::GetPreferredZapModuleForTypeHandle(t);
-        if (image->GetModule() != pPrefModule)
-        {
-            StackSString typeName;
-            t.CheckRestore();
-            TypeString::AppendTypeDebug(typeName, t);
-            LOG((LF_ZAP, LL_INFO100, "The type %S was saved outside its preferred module %S\n", typeName.GetUnicode(), pPrefModule->GetPath().GetUnicode()));
-        }
-    }
-#endif // _DEBUG
-}
-
-#ifndef DACCESS_COMPILE
-
-void ModuleCtorInfo::Save(DataImage *image, CorProfileData *profileData)
-{
-    STANDARD_VM_CONTRACT;
-
-    if (!numElements)
-        return;
-
-    DWORD i = 0;
-    DWORD totalBoxedStatics = 0;
-
-    // sort the tables so that
-    // - the hot ppMT entries are at the beginning of the ppMT table
-    // - the hot cctor entries are at the beginning of the cctorInfoHot table
-    // - the cold cctor entries are at the end, and we make cctorInfoCold point
-    //   the first cold entry
-    //
-    // the invariant in this loop is:
-    // items 0...numElementsHot-1 are hot
-    // items numElementsHot...i-1 are cold
-    for (i = 0; i < numElements; i++)
-    {
-        MethodTable *ppMTTemp = ppMT[i].GetValue();
-
-        // Count the number of boxed statics along the way
-        totalBoxedStatics += ppMTTemp->GetNumBoxedRegularStatics();
-
-        bool hot = true; // if there's no profiling data, assume the entries are all hot.
-        if (profileData && profileData->GetTokenFlagsData(TypeProfilingData))
-        {
-            if ((profileData->GetTypeProfilingFlagsOfToken(ppMTTemp->GetCl()) & (1 << ReadCCtorInfo)) == 0)
-                hot = false;
-        }
-        if (hot)
-        {
-            // swap ppMT[i] and ppMT[numElementsHot] to maintain the loop invariant
-            ppMT[i].SetValue(ppMT[numElementsHot].GetValue());
-            ppMT[numElementsHot].SetValue(ppMTTemp);
-
-            numElementsHot++;
-        }
-    }
-
-    numHotHashes = numElementsHot ? RoundUpToPower2((numElementsHot * sizeof(PTR_MethodTable)) / CACHE_LINE_SIZE) : 0;
-    numColdHashes = (numElements - numElementsHot) ? RoundUpToPower2(((numElements - numElementsHot) *
-                                                                    sizeof(PTR_MethodTable)) / CACHE_LINE_SIZE) : 0;
-
-    LOG((LF_ZAP, LL_INFO10, "ModuleCtorInfo::numHotHashes:  0x%4x\n", numHotHashes));
-    if (numColdHashes != 0)
-    {
-        LOG((LF_ZAP, LL_INFO10, "ModuleCtorInfo::numColdHashes: 0x%4x\n", numColdHashes));
-    }
-
-    // The "plus one" is so we can store the offset to the end of the array at the end of
-    // the hashoffsets arrays, enabling faster lookups.
-    hotHashOffsets = new DWORD[numHotHashes + 1];
-    coldHashOffsets = new DWORD[numColdHashes + 1];
-
-    DWORD *hashArray = new DWORD[numElements];
-
-    for (i = 0; i < numElementsHot; i++)
-    {
-        hashArray[i] = GenerateHash(ppMT[i].GetValue(), HOT);
-    }
-    for (i = numElementsHot; i < numElements; i++)
-    {
-        hashArray[i] = GenerateHash(ppMT[i].GetValue(), COLD);
-    }
-
-    // Sort the two arrays by hash values to create regions with the same hash values.
-    ClassCtorInfoEntryArraySort cctorInfoHotSort(hashArray, ppMT, numElementsHot);
-    ClassCtorInfoEntryArraySort cctorInfoColdSort(hashArray + numElementsHot, ppMT + numElementsHot,
-                                                    numElements - numElementsHot);
-    cctorInfoHotSort.Sort();
-    cctorInfoColdSort.Sort();
-
-    // Generate the indices that index into the correct "hash region" in the hot part of the ppMT array, and store
-    // them in the hotHashOffests arrays.
-    DWORD curHash = 0;
-    i = 0;
-    while (i < numElementsHot)
-    {
-        if (curHash < hashArray[i])
-        {
-            hotHashOffsets[curHash++] = i;
-        }
-        else if (curHash == hashArray[i])
-        {
-            hotHashOffsets[curHash++] = i++;
-        }
-        else
-        {
-            i++;
-        }
-    }
-    while (curHash <= numHotHashes)
-    {
-        hotHashOffsets[curHash++] = numElementsHot;
-    }
-
-    // Generate the indices that index into the correct "hash region" in the hot part of the ppMT array, and store
-    // them in the coldHashOffsets arrays.
-    curHash = 0;
-    i = numElementsHot;
-    while (i < numElements)
-    {
-        if (curHash < hashArray[i])
-        {
-            coldHashOffsets[curHash++] = i;
-        }
-        else if (curHash == hashArray[i])
-        {
-            coldHashOffsets[curHash++] = i++;
-        }
-        else i++;
-    }
-    while (curHash <= numColdHashes)
-    {
-        coldHashOffsets[curHash++] = numElements;
-    }
-
-    delete[] hashArray;
-
-
-    cctorInfoHot    = new ClassCtorInfoEntry[numElements];
-
-    // make cctorInfoCold point to the first cold element
-    cctorInfoCold   = cctorInfoHot + numElementsHot;
-
-    ppHotGCStaticsMTs   = (totalBoxedStatics != 0) ? new RelativeFixupPointer<PTR_MethodTable>[totalBoxedStatics] : NULL;
-    numHotGCStaticsMTs  = totalBoxedStatics;
-
-    DWORD iGCStaticMT = 0;
-
-    for (i = 0; i < numElements; i++)
-    {
-        if (numElements == numElementsHot)
-        {
-            numHotGCStaticsMTs  = iGCStaticMT;
-            numColdGCStaticsMTs = (totalBoxedStatics - iGCStaticMT);
-
-            // make ppColdGCStaticsMTs point to the first cold element
-            ppColdGCStaticsMTs = ppHotGCStaticsMTs + numHotGCStaticsMTs;
-        }
-
-        MethodTable* pMT = ppMT[i].GetValue();
-        ClassCtorInfoEntry* pEntry = &cctorInfoHot[i];
-
-        WORD numBoxedStatics = pMT->GetNumBoxedRegularStatics();
-        pEntry->numBoxedStatics = numBoxedStatics;
-        pEntry->hasFixedAddressVTStatics = !!pMT->HasFixedAddressVTStatics();
-
-        FieldDesc *pField = pMT->HasGenericsStaticsInfo() ?
-            pMT->GetGenericsStaticFieldDescs() : (pMT->GetApproxFieldDescListRaw() + pMT->GetNumIntroducedInstanceFields());
-        FieldDesc *pFieldEnd = pField + pMT->GetNumStaticFields();
-
-        pEntry->firstBoxedStaticOffset = (DWORD)-1;
-        pEntry->firstBoxedStaticMTIndex = (DWORD)-1;
-
-        DWORD numFoundBoxedStatics = 0;
-        while (pField < pFieldEnd)
-        {
-            _ASSERTE(pField->IsStatic());
-
-            if (!pField->IsSpecialStatic() && pField->IsByValue())
-            {
-                if (pEntry->firstBoxedStaticOffset == (DWORD)-1)
-                {
-                    pEntry->firstBoxedStaticOffset = pField->GetOffset();
-                    pEntry->firstBoxedStaticMTIndex = iGCStaticMT;
-                }
-                _ASSERTE(pField->GetOffset() - pEntry->firstBoxedStaticOffset
-                    == (iGCStaticMT - pEntry->firstBoxedStaticMTIndex) * sizeof(MethodTable*));
-
-                TypeHandle th = pField->GetFieldTypeHandleThrowing();
-                ppHotGCStaticsMTs[iGCStaticMT++].SetValueMaybeNull(th.GetMethodTable());
-
-                numFoundBoxedStatics++;
-            }
-            pField++;
-        }
-        _ASSERTE(numBoxedStatics == numFoundBoxedStatics);
-    }
-    _ASSERTE(iGCStaticMT == totalBoxedStatics);
-
-    if (numElementsHot > 0)
-    {
-        image->StoreStructure(cctorInfoHot,
-                                sizeof(ClassCtorInfoEntry) * numElementsHot,
-                                DataImage::ITEM_MODULE_CCTOR_INFO_HOT);
-
-        image->StoreStructure(hotHashOffsets,
-                                sizeof(DWORD) * (numHotHashes + 1),
-                                DataImage::ITEM_MODULE_CCTOR_INFO_HOT);
-    }
-
-    if (numElements > 0)
-        image->StoreStructure(ppMT,
-                                sizeof(RelativePointer<MethodTable *>) * numElements,
-                                DataImage::ITEM_MODULE_CCTOR_INFO_HOT);
-
-    if (numElements > numElementsHot)
-    {
-        image->StoreStructure(cctorInfoCold,
-                                sizeof(ClassCtorInfoEntry) * (numElements - numElementsHot),
-                                DataImage::ITEM_MODULE_CCTOR_INFO_COLD);
-
-        image->StoreStructure(coldHashOffsets,
-                                sizeof(DWORD) * (numColdHashes + 1),
-                                DataImage::ITEM_MODULE_CCTOR_INFO_COLD);
-    }
-
-    if ( numHotGCStaticsMTs )
-    {
-        // Save the mt templates
-        image->StoreStructure( ppHotGCStaticsMTs, numHotGCStaticsMTs * sizeof(RelativeFixupPointer<MethodTable*>),
-                                DataImage::ITEM_GC_STATIC_HANDLES_HOT);
-    }
-    else
-    {
-        ppHotGCStaticsMTs = NULL;
-    }
-
-    if ( numColdGCStaticsMTs )
-    {
-        // Save the hot mt templates
-        image->StoreStructure( ppColdGCStaticsMTs, numColdGCStaticsMTs * sizeof(RelativeFixupPointer<MethodTable*>),
-                                DataImage::ITEM_GC_STATIC_HANDLES_COLD);
-    }
-    else
-    {
-        ppColdGCStaticsMTs = NULL;
-    }
-}
-
-#endif // !DACCESS_COMPILE
-
-bool Module::AreAllClassesFullyLoaded()
-{
-    STANDARD_VM_CONTRACT;
-
-    // Adjust for unused space
-    IMDInternalImport *pImport = GetMDImport();
-
-    HENUMInternalHolder hEnum(pImport);
-    hEnum.EnumAllInit(mdtTypeDef);
-
-    mdTypeDef token;
-    while (pImport->EnumNext(&hEnum, &token))
-    {
-        _ASSERTE(TypeFromToken(token) == mdtTypeDef);
-
-        // Special care has to been taken with COR_GLOBAL_PARENT_TOKEN, as the class
-        // may not be needed, (but we have to distinguish between not needed and threw error).
-        if (token == COR_GLOBAL_PARENT_TOKEN &&
-            !NeedsGlobalMethodTable())
-        {
-            // No EEClass for this token if there was no need for a global method table
-            continue;
-        }
-
-        TypeHandle th = LookupTypeDef(token);
-        if (th.IsNull())
-            return false;
-
-        if (!th.AsMethodTable()->IsFullyLoaded())
-            return false;
-    }
-
-    return true;
-}
-
-void Module::PrepareTypesForSave(DataImage *image)
-{
-    STANDARD_VM_CONTRACT;
-
-    //
-    // Prepare typedefs
-    //
-    {
-        LookupMap<PTR_MethodTable>::Iterator typeDefIter(&m_TypeDefToMethodTableMap);
-        while (typeDefIter.Next())
-        {
-            MethodTable * pMT = typeDefIter.GetElement();
-
-            if (pMT == NULL || !pMT->IsFullyLoaded())
-                continue;
-
-
-        }
-    }
-
-    //
-    // Prepare typespecs
-    //
-    {
-        // Create a local copy in case the new elements are added to the hashtable during population
-        InlineSArray<TypeHandle, 20> pTypes;
-
-        // Make sure the iterator is destroyed before there is a chance of loading new types
-        {
-            EETypeHashTable::Iterator it(m_pAvailableParamTypes);
-            EETypeHashEntry *pEntry;
-            while (m_pAvailableParamTypes->FindNext(&it, &pEntry))
-            {
-                TypeHandle t = pEntry->GetTypeHandle();
-
-                if (t.IsTypeDesc())
-                    continue;
-
-                if (!image->GetPreloader()->IsTypeInTransitiveClosureOfInstantiations(CORINFO_CLASS_HANDLE(t.AsPtr())))
-                    continue;
-
-                pTypes.Append(t);
-            }
-        }
-
-    }
-
-    image->GetPreloader()->TriageForZap(FALSE, FALSE);
-}
-
-static const char* const MethodTableRestoreReasonDescription[TotalMethodTables + 1] =
-{
-    #undef RESTORE_REASON_FUNC
-    #define RESTORE_REASON_FUNC(s) #s,
-
-    METHODTABLE_RESTORE_REASON()
-
-    #undef RESTORE_REASON
-
-    "TotalMethodTablesEvaluated"
-};
-
-
-// MethodDescByMethodTableTraits could be a local class in Module::Save(), but g++ doesn't like
-// instantiating templates with private classes.
-class MethodDescByMethodTableTraits : public NoRemoveSHashTraits< DefaultSHashTraits<MethodDesc *> >
-{
-public:
-    typedef MethodTable * key_t;
-    static MethodDesc * Null() { return NULL; }
-    static bool IsNull(MethodDesc * pMD) { return pMD == NULL; }
-    static MethodTable * GetKey(MethodDesc * pMD) { return pMD->GetMethodTable_NoLogging(); }
-    static count_t Hash(MethodTable * pMT) { LIMITED_METHOD_CONTRACT; return (count_t) (UINT_PTR) pMT->GetTypeDefRid_NoLogging(); }
-    static BOOL Equals(MethodTable * pMT1, MethodTable * pMT2)
-    {
-        return pMT1 == pMT2;
-    }
-};
-
-void Module::Save(DataImage *image)
-{
-    STANDARD_VM_CONTRACT;
-
-    // Precompute type specific auxiliary information saved into NGen image
-    // Note that this operation can load new types.
-    PrepareTypesForSave(image);
-
-    // Cache values of all persisted flags computed from custom attributes
-    IsNoStringInterning();
-    IsRuntimeWrapExceptions();
-    IsPreV4Assembly();
-
-    HasDefaultDllImportSearchPathsAttribute();
-
-    // Precompute property information to avoid runtime metadata lookup
-    PopulatePropertyInfoMap();
-
-    // Any any elements and compute values of any LookupMap flags that were not available previously
-    FinalizeLookupMapsPreSave(image);
-
-    //
-    // Save the module
-    //
-
-    ZapStoredStructure * pModuleNode = image->StoreStructure(this, sizeof(Module),
-                                    DataImage::ITEM_MODULE);
-
-    m_pNGenLayoutInfo = (NGenLayoutInfo *)(void *)image->GetModule()->GetLoaderAllocator()->
-        GetHighFrequencyHeap()->AllocMem(S_SIZE_T(sizeof(NGenLayoutInfo)));
-    image->StoreStructure(m_pNGenLayoutInfo, sizeof(NGenLayoutInfo), DataImage::ITEM_BINDER_ITEMS);
-
-    //
-    // If we are NGening, we don't need to keep a list of va
-    // sig cookies, as we already have a complete set (of course we do
-    // have to persist the cookies themselves, though.
-    //
-
-    //
-    // Initialize maps of child data structures.  Note that each tables's blocks are
-    // concantentated to a single block in the process.
-    //
-    CorProfileData * profileData = GetProfileData();
-
-    m_TypeRefToMethodTableMap.Save(image, DataImage::ITEM_TYPEREF_MAP, profileData, mdtTypeRef);
-    image->BindPointer(&m_TypeRefToMethodTableMap, pModuleNode, offsetof(Module, m_TypeRefToMethodTableMap));
-
-    if(m_pMemberRefToDescHashTable)
-        m_pMemberRefToDescHashTable->Save(image, profileData);
-
-    m_TypeDefToMethodTableMap.Save(image, DataImage::ITEM_TYPEDEF_MAP, profileData, mdtTypeDef);
-    image->BindPointer(&m_TypeDefToMethodTableMap, pModuleNode, offsetof(Module, m_TypeDefToMethodTableMap));
-
-    m_MethodDefToDescMap.Save(image, DataImage::ITEM_METHODDEF_MAP, profileData, mdtMethodDef);
-    image->BindPointer(&m_MethodDefToDescMap, pModuleNode, offsetof(Module, m_MethodDefToDescMap));
-
-    m_FieldDefToDescMap.Save(image, DataImage::ITEM_FIELDDEF_MAP, profileData, mdtFieldDef);
-    image->BindPointer(&m_FieldDefToDescMap, pModuleNode, offsetof(Module, m_FieldDefToDescMap));
-
-    m_GenericParamToDescMap.Save(image, DataImage::ITEM_GENERICPARAM_MAP, profileData, mdtGenericParam);
-    image->BindPointer(&m_GenericParamToDescMap, pModuleNode, offsetof(Module, m_GenericParamToDescMap));
-
-    m_GenericTypeDefToCanonMethodTableMap.Save(image, DataImage::ITEM_GENERICTYPEDEF_MAP, profileData, mdtTypeDef);
-    image->BindPointer(&m_GenericTypeDefToCanonMethodTableMap, pModuleNode, offsetof(Module, m_GenericTypeDefToCanonMethodTableMap));
-
-    if (m_pAvailableClasses)
-        m_pAvailableClasses->Save(image, profileData);
-
-    //
-    // Also save the parent maps; the contents will
-    // need to be rewritten, but we can allocate the
-    // space in the image.
-    //
-
-    // these items have no hot list and no attribution
-    m_FileReferencesMap.Save(image, DataImage::ITEM_FILEREF_MAP, profileData, 0);
-    image->BindPointer(&m_FileReferencesMap, pModuleNode, offsetof(Module, m_FileReferencesMap));
-
-    m_ManifestModuleReferencesMap.Save(image, DataImage::ITEM_ASSEMREF_MAP, profileData, 0);
-    image->BindPointer(&m_ManifestModuleReferencesMap, pModuleNode, offsetof(Module, m_ManifestModuleReferencesMap));
-
-    m_MethodDefToPropertyInfoMap.Save(image, DataImage::ITEM_PROPERTYINFO_MAP, profileData, 0, TRUE /*fCopyValues*/);
-    image->BindPointer(&m_MethodDefToPropertyInfoMap, pModuleNode, offsetof(Module, m_MethodDefToPropertyInfoMap));
-
-    if (m_pBinder != NULL)
-        m_pBinder->Save(image);
-
-    if (profileData)
-    {
-        // Store types.
-
-        // Saving hot things first is a very good thing, because we place items
-        // in the order they are saved and things that have hot items are also
-        // more likely to have their other structures touched, hence these should
-        // also be placed together, at least if we don't have any further information to go on.
-        // Note we place particular hot items with more care in the Arrange phase.
-        //
-        CORBBTPROF_TOKEN_INFO * pTypeProfilingData = profileData->GetTokenFlagsData(TypeProfilingData);
-        DWORD                   cTypeProfilingData = profileData->GetTokenFlagsCount(TypeProfilingData);
-
-        for (unsigned int i = 0; i < cTypeProfilingData; i++)
-        {
-            CORBBTPROF_TOKEN_INFO *entry = &pTypeProfilingData[i];
-            mdToken token = entry->token;
-            DWORD   flags = entry->flags;
-#if defined(_DEBUG) && !defined(DACCESS_COMPILE)
-            g_pConfig->DebugCheckAndForceIBCFailure(EEConfig::CallSite_4);
-#endif
-
-            if ((flags & (1 << ReadMethodTable)) == 0)
-                continue;
-
-            if (TypeFromToken(token) == mdtTypeDef)
-            {
-                MethodTable *pMT = LookupTypeDef(token).GetMethodTable();
-                if (pMT && pMT->IsFullyLoaded())
-                {
-                    SaveMethodTable(image, pMT, flags);
-                }
-            }
-            else  if (TypeFromToken(token) == ibcTypeSpec)
-            {
-                CORBBTPROF_BLOB_ENTRY *pBlobEntry = profileData->GetBlobStream();
-                if (pBlobEntry)
-                {
-                    while (pBlobEntry->TypeIsValid())
-                    {
-                        if (TypeFromToken(pBlobEntry->token) == ibcTypeSpec)
-                        {
-                            _ASSERTE(pBlobEntry->type == ParamTypeSpec);
-
-                            if (pBlobEntry->token == token)
-                            {
-                                CORBBTPROF_BLOB_PARAM_SIG_ENTRY *pBlobSigEntry = (CORBBTPROF_BLOB_PARAM_SIG_ENTRY *) pBlobEntry;
-                                TypeHandle th = LoadIBCTypeHelper(image, pBlobSigEntry);
-
-                                if (!th.IsNull())
-                                {
-                                    // When we have stale IBC data the type could have been rejected from this image.
-                                    if (image->GetPreloader()->IsTypeInTransitiveClosureOfInstantiations(CORINFO_CLASS_HANDLE(th.AsPtr())))
-                                    {
-                                        SaveTypeHandle(image, th, flags);
-                                    }
-                                }
-                            }
-                        }
-                        pBlobEntry = pBlobEntry->GetNextEntry();
-                    }
-                    _ASSERTE(pBlobEntry->type == EndOfBlobStream);
-                }
-            }
-        }
-
-        if (m_pAvailableParamTypes != NULL)
-        {
-            // If we have V1 IBC data then we save the hot
-            //  out-of-module generic instantiations here
-
-            CORBBTPROF_TOKEN_INFO * tokens_begin = profileData ? profileData->GetTokenFlagsData(GenericTypeProfilingData) : NULL;
-            CORBBTPROF_TOKEN_INFO * tokens_end = tokens_begin + (profileData ? profileData->GetTokenFlagsCount(GenericTypeProfilingData) : 0);
-
-            if (tokens_begin != tokens_end)
-            {
-                SArray<CORBBTPROF_TOKEN_INFO> tokens(tokens_begin, tokens_end);
-                tokens_begin = &tokens[0];
-                tokens_end = tokens_begin + tokens.GetCount();
-
-                util::sort(tokens_begin, tokens_end);
-
-                // enumerate AvailableParamTypes map and find all hot generic instantiations
-                EETypeHashTable::Iterator it(m_pAvailableParamTypes);
-                EETypeHashEntry *pEntry;
-                while (m_pAvailableParamTypes->FindNext(&it, &pEntry))
-                {
-                    TypeHandle t = pEntry->GetTypeHandle();
-#if defined(_DEBUG) && !defined(DACCESS_COMPILE)
-                    g_pConfig->DebugCheckAndForceIBCFailure(EEConfig::CallSite_5);
-#endif
-
-                    if (t.HasInstantiation())
-                    {
-                        SString tokenName;
-                        t.GetName(tokenName);
-                        unsigned cur_token = tokenName.Hash() & 0xffff;
-
-                        CORBBTPROF_TOKEN_INFO * found = util::lower_bound(tokens_begin, tokens_end, CORBBTPROF_TOKEN_INFO(cur_token));
-                        if (found != tokens_end && found->token == cur_token && (found->flags & (1 << ReadMethodTable)))
-                        {
-                            // When we have stale IBC data the type could have been rejected from this image.
-                            if (image->GetPreloader()->IsTypeInTransitiveClosureOfInstantiations(CORINFO_CLASS_HANDLE(t.AsPtr())))
-                                SaveTypeHandle(image, t, found->flags);
-                        }
-                    }
-                }
-            }
-        }
-    }
-
-    //
-    // Now save any types in the TypeDefToMethodTableMap map
-
-    {
-        LookupMap<PTR_MethodTable>::Iterator typeDefIter(&m_TypeDefToMethodTableMap);
-
-        while (typeDefIter.Next())
-        {
-            MethodTable * pMT = typeDefIter.GetElement();
-
-            if (pMT != NULL &&
-                !image->IsStored(pMT) && pMT->IsFullyLoaded())
-            {
-                image->BeginAssociatingStoredObjectsWithMethodTable(pMT);
-                SaveMethodTable(image, pMT, 0);
-                image->EndAssociatingStoredObjectsWithMethodTable();
-            }
-        }
-    }
-
-    //
-    // Now save any TypeDescs in m_GenericParamToDescMap map
-
-    {
-        LookupMap<PTR_TypeVarTypeDesc>::Iterator genericParamIter(&m_GenericParamToDescMap);
-
-        while (genericParamIter.Next())
-        {
-            TypeVarTypeDesc *pTD = genericParamIter.GetElement();
-
-            if (pTD != NULL)
-            {
-                pTD->Save(image);
-            }
-        }
-    }
-
-#ifdef _DEBUG
-    SealGenericTypesAndMethods();
-#endif
-
-    //
-    // Now save any  types in the AvailableParamTypes map
-    //
-    if (m_pAvailableParamTypes != NULL)
-    {
-        EETypeHashTable::Iterator it(m_pAvailableParamTypes);
-        EETypeHashEntry *pEntry;
-        while (m_pAvailableParamTypes->FindNext(&it, &pEntry))
-        {
-            TypeHandle t = pEntry->GetTypeHandle();
-
-            if (image->GetPreloader()->IsTypeInTransitiveClosureOfInstantiations(CORINFO_CLASS_HANDLE(t.AsPtr())))
-            {
-                if (t.GetCanonicalMethodTable() != NULL)
-                {
-                    image->BeginAssociatingStoredObjectsWithMethodTable(t.GetCanonicalMethodTable());
-                    SaveTypeHandle(image, t, 0);
-                    image->EndAssociatingStoredObjectsWithMethodTable();
-                }
-                else
-                {
-                    SaveTypeHandle(image, t, 0);
-                }
-            }
-        }
-    }
-
-    //
-    // Now save any methods in the InstMethodHashTable
-    //
-    if (m_pInstMethodHashTable != NULL)
-    {
-        //
-        // Find all MethodDescs that we are going to save, and hash them with MethodTable as the key
-        //
-
-        typedef SHash<MethodDescByMethodTableTraits> MethodDescByMethodTableHash;
-
-        MethodDescByMethodTableHash methodDescs;
-
-        InstMethodHashTable::Iterator it(m_pInstMethodHashTable);
-        InstMethodHashEntry *pEntry;
-        while (m_pInstMethodHashTable->FindNext(&it, &pEntry))
-        {
-            MethodDesc *pMD = pEntry->GetMethod();
-
-            _ASSERTE(!pMD->IsTightlyBoundToMethodTable());
-
-            if (!image->IsStored(pMD) &&
-                image->GetPreloader()->IsMethodInTransitiveClosureOfInstantiations(CORINFO_METHOD_HANDLE(pMD)))
-            {
-                methodDescs.Add(pMD);
-            }
-        }
-
-        //
-        // Save all MethodDescs on the same MethodTable using one chunk builder
-        //
-
-        for (MethodDescByMethodTableHash::Iterator i1 = methodDescs.Begin(), end1 = methodDescs.End(); i1 != end1; i1++)
-        {
-            MethodDesc * pMD = *(i1);
-            if (image->IsStored(pMD))
-                continue;
-
-            MethodTable * pMT = pMD->GetMethodTable();
-
-            MethodDesc::SaveChunk methodDescSaveChunk(image);
-
-            for (MethodDescByMethodTableHash::KeyIterator i2 = methodDescs.Begin(pMT), end2 = methodDescs.End(pMT); i2 != end2; i2++)
-            {
-                _ASSERTE(!image->IsStored(*i2));
-                methodDescSaveChunk.Append(*i2);
-            }
-
-            methodDescSaveChunk.Save();
-        }
-    }
-
-    // Now save the tables themselves
-    if (m_pAvailableParamTypes != NULL)
-    {
-        m_pAvailableParamTypes->Save(image, this, profileData);
-    }
-
-    if (m_pInstMethodHashTable != NULL)
-    {
-        m_pInstMethodHashTable->Save(image, profileData);
-    }
-
-    {
-        MethodTable * pStubMT = GetILStubCache()->GetStubMethodTable();
-        if (pStubMT != NULL)
-        {
-            SaveMethodTable(image, pStubMT, 0);
-        }
-    }
-
-    if (m_pStubMethodHashTable != NULL)
-    {
-        m_pStubMethodHashTable->Save(image, profileData);
-    }
-
-    // Compute and save the property name set
-    PrecomputeMatchingProperties(image);
-    image->StoreStructure(m_propertyNameSet,
-                          m_nPropertyNameSet * sizeof(BYTE),
-                          DataImage::ITEM_PROPERTY_NAME_SET);
-
-
-    // Sort the list of RVA statics in an ascending order wrt the RVA
-    // and save them.
-    image->SaveRvaStructure();
-
-    // Save static data
-    LOG((LF_CLASSLOADER, LL_INFO10000, "STATICS: Saving module static data\n"));
-
-    // We have this scenario where ngen will fail to load some classes but will generate
-    // a valid exe, or it will choose not to save some loaded classes due to some error
-    // conditions, where statics will be committed at runtime for the classes that ngen
-    // wasn't able to load or save. So we can't cut down the static block size blindly if we've
-    // failed to load or save any class. We don't think this scenario deserves complicated code
-    // paths to get the extra working set perf (you would be pulling in the jitter if
-    // you need any of these classes), So we are basically simplifying this down, if we failed
-    // to load or save any class we won't compress the statics block and will persist the original
-    // estimation.
-
-    // All classes were loaded and saved, cut down the block
-    if (AreAllClassesFullyLoaded())
-    {
-        // Set a mark indicating we had all our classes loaded
-        m_pRegularStaticOffsets = (PTR_DWORD) NGEN_STATICS_ALLCLASSES_WERE_LOADED;
-        m_pThreadStaticOffsets = (PTR_DWORD) NGEN_STATICS_ALLCLASSES_WERE_LOADED;
-    }
-    else
-    {
-        // Since not all of the classes loaded we want to zero the pointers to the offset tables so they'll be
-        // recalculated at runtime. But we can't do that here since we might try to reload some of the failed
-        // types during the arrange phase (as the result of trying to parse profiling data). So we'll defer
-        // zero'ing anything until the fixup phase.
-
-        // Not all classes were stored, revert to uncompressed maps to support run-time changes
-        m_TypeDefToMethodTableMap.ConvertSavedMapToUncompressed(image, DataImage::ITEM_TYPEDEF_MAP);
-        m_MethodDefToDescMap.ConvertSavedMapToUncompressed(image, DataImage::ITEM_METHODDEF_MAP);
-    }
-
-    m_ModuleCtorInfo.Save(image, profileData);
-    image->BindPointer(&m_ModuleCtorInfo, pModuleNode, offsetof(Module, m_ModuleCtorInfo));
-
-    if (m_pDynamicStaticsInfo)
-    {
-        image->StoreStructure(m_pDynamicStaticsInfo, m_maxDynamicEntries*sizeof(DynamicStaticsInfo),
-                                          DataImage::ITEM_DYNAMIC_STATICS_INFO_TABLE);
-    }
-
-    InlineTrackingMap *inlineTrackingMap = image->GetInlineTrackingMap();
-    if (inlineTrackingMap)
-    {
-        m_pPersistentInlineTrackingMapNGen = new (image->GetHeap()) PersistentInlineTrackingMapNGen(this);
-        m_pPersistentInlineTrackingMapNGen->Save(image, inlineTrackingMap);
-    }
-
-    if (m_pNgenStats && g_CorCompileVerboseLevel >= CORCOMPILE_STATS)
-    {
-        GetSvcLogger()->Printf ("%-35s: %s\n", "MethodTable Restore Reason", "Count");
-        DWORD dwTotal = 0;
-        for (int i=0; i<TotalMethodTables; i++)
-        {
-            GetSvcLogger()->Printf ("%-35s: %d\n", MethodTableRestoreReasonDescription[i], m_pNgenStats->MethodTableRestoreNumReasons[i]);
-            dwTotal += m_pNgenStats->MethodTableRestoreNumReasons[i];
-        }
-        GetSvcLogger()->Printf ("%-35s: %d\n", "TotalMethodTablesNeedRestore", dwTotal);
-        GetSvcLogger()->Printf ("%-35s: %d\n", MethodTableRestoreReasonDescription[TotalMethodTables], m_pNgenStats->MethodTableRestoreNumReasons[TotalMethodTables]);
-    }
-}
-
-
-#ifdef _DEBUG
-//
-// We call these methods to seal the
-// lists: m_pAvailableClasses and m_pAvailableParamTypes
-//
-void Module::SealGenericTypesAndMethods()
-{
-    LIMITED_METHOD_CONTRACT;
-    // Enforce that after this point in ngen that no more types or methods will be loaded.
-    //
-    // We increment the seal count here and only decrement it after we have completed the ngen image
-    //
-    if (m_pAvailableParamTypes != NULL)
-    {
-        m_pAvailableParamTypes->Seal();
-    }
-    if (m_pInstMethodHashTable != NULL)
-    {
-        m_pInstMethodHashTable->Seal();
-    }
-}
-//
-// We call these methods to unseal the
-// lists: m_pAvailableClasses and m_pAvailableParamTypes
-//
-void Module::UnsealGenericTypesAndMethods()
-{
-    LIMITED_METHOD_CONTRACT;
-    // Allow us to create generic types and methods again
-    //
-    // We only decrement it after we have completed the ngen image
-    //
-    if (m_pAvailableParamTypes != NULL)
-    {
-        m_pAvailableParamTypes->Unseal();
-    }
-    if (m_pInstMethodHashTable != NULL)
-    {
-        m_pInstMethodHashTable->Unseal();
-    }
-}
-#endif
-
-
-void Module::PrepopulateDictionaries(DataImage *image, BOOL nonExpansive)
-{
-    STANDARD_VM_CONTRACT;
-
-    // Prepopulating the dictionaries for instantiated types
-    // is in theory an iteraive process, i.e. filling in
-    // a dictionary slot may result in a class load of a new type whose
-    // dictionary may itself need to be prepopulated.  The type expressions
-    // involved can get larger, so there's no a-priori reason to expect this
-    // process to terminate.
-    //
-    // Given a starting set of instantiated types, several strategies are
-    // thus possible - no prepopulation (call this PP0), or
-    // prepopulate only the dictionaries of the types that are in the initial
-    // set (call this PP1), or do two iterations (call this PP2) etc. etc.
-    // Whichever strategy we choose we can always afford to do
-    // one round of prepopulation where we populate slots
-    // whose corresponding resulting method/types are already loaded.
-    // Call this PPn+PP-FINAL.
-    //
-    // Below we implement PP1+PP-FINAL for instantiated types and PP0+PP-FINAL
-    // for instantiations of generic methods.  We use PP1 because most collection
-    // classes (List, Dictionary etc.) only require one pass of prepopulation in order
-    // to fully prepopulate the dictionary.
-
-    // Do PP1 for instantiated types... Do one iteration where we force type loading...
-    // Because this phase may cause new entries to appear in the hash table we
-    // copy the array of types to the stack before we do anything else.
-    if (!nonExpansive && CLRConfig::GetConfigValue(CLRConfig::EXTERNAL_Prepopulate1))
-    {
-        if (m_pAvailableParamTypes != NULL)
-        {
-            // Create a local copy in case the new elements are added to the hashtable during population
-            InlineSArray<TypeHandle, 20> pTypes;
-
-            EETypeHashTable::Iterator it(m_pAvailableParamTypes);
-            EETypeHashEntry *pEntry;
-            while (m_pAvailableParamTypes->FindNext(&it, &pEntry))
-            {
-                TypeHandle th = pEntry->GetTypeHandle();
-                if (th.IsTypeDesc())
-                    continue;
-
-                // Don't do prepopulation for open types - they shouldn't really have dictionaries anyway.
-                MethodTable * pMT = th.AsMethodTable();
-                if (pMT->ContainsGenericVariables())
-                    continue;
-
-                // Only do PP1 on things that land in their preferred Zap module.
-                // Forcing the load of dictionary entries in the case where we are
-                // speculatively saving a copy of an instantiation outside its preferred
-                // zap module is too expensive for the common collection class cases.
-                ///
-                // Invalid generic instantiations will not be fully loaded.
-                // We want to ignore them as touching them will re-raise the TypeLoadException
-                if (pMT->IsFullyLoaded() && image->GetModule() == GetPreferredZapModuleForMethodTable(pMT))
-                {
-                    pTypes.Append(th);
-                }
-            }
-            it.Reset();
-
-            for(COUNT_T i = 0; i < pTypes.GetCount(); i ++)
-            {
-                TypeHandle th = pTypes[i];
-                _ASSERTE(image->GetModule() == GetPreferredZapModuleForTypeHandle(th) );
-                _ASSERTE(!th.IsTypeDesc() && !th.ContainsGenericVariables());
-                th.AsMethodTable()->PrepopulateDictionary(image, FALSE /* not nonExpansive, i.e. can load types */);
-            }
-        }
-    }
-
-    // PP-FINAL for instantiated types.
-    // This is the final stage where we hardbind any remaining entries that map
-    // to results that have already been loaded...
-    // Thus we set the "nonExpansive" flag on PrepopulateDictionary
-    // below, which may in turn greatly limit the amount of prepopulating we do
-    // (partly because it's quite difficult to determine if some potential entries
-    // in the dictionary are already loaded)
-
-    if (m_pAvailableParamTypes != NULL)
-    {
-        INDEBUG(DWORD nTypes = m_pAvailableParamTypes->GetCount());
-
-        EETypeHashTable::Iterator it(m_pAvailableParamTypes);
-        EETypeHashEntry *pEntry;
-        while (m_pAvailableParamTypes->FindNext(&it, &pEntry))
-        {
-            TypeHandle th = pEntry->GetTypeHandle();
-            if (th.IsTypeDesc())
-                continue;
-
-            MethodTable * pMT = th.AsMethodTable();
-            if (pMT->ContainsGenericVariables())
-                continue;
-
-            pMT->PrepopulateDictionary(image, TRUE /* nonExpansive */);
-        }
-
-        // No new instantiations should be added by nonExpansive prepopulation
-        _ASSERTE(nTypes == m_pAvailableParamTypes->GetCount());
-    }
-
-    // PP-FINAL for instantiations of generic methods.
-    if (m_pInstMethodHashTable != NULL)
-    {
-        INDEBUG(DWORD nMethods = m_pInstMethodHashTable->GetCount());
-
-        InstMethodHashTable::Iterator it(m_pInstMethodHashTable);
-        InstMethodHashEntry *pEntry;
-        while (m_pInstMethodHashTable->FindNext(&it, &pEntry))
-        {
-            MethodDesc *pMD = pEntry->GetMethod();
-            if (!pMD->ContainsGenericVariables())
-            {
-                pMD->PrepopulateDictionary(image, TRUE /* nonExpansive */);
-            }
-        }
-
-        // No new instantiations should be added by nonExpansive prepopulation
-        _ASSERTE(nMethods == m_pInstMethodHashTable->GetCount());
-    }
-}
-
-void Module::PlaceType(DataImage *image, TypeHandle th, DWORD profilingFlags)
-{
-    STANDARD_VM_CONTRACT;
-
-    if (th.IsNull())
-        return;
-
-    MethodTable *pMT = th.GetMethodTable();
-
-    if (pMT && pMT->GetLoaderModule() == this)
-    {
-        EEClass *pClass = pMT->GetClass();
-
-        if (profilingFlags & (1 << WriteMethodTableWriteableData))
-        {
-            image->PlaceStructureForAddress(pMT->GetWriteableData(),CORCOMPILE_SECTION_WRITE);
-        }
-
-        if (profilingFlags & (1 << ReadMethodTable))
-        {
-            CorCompileSection section = CORCOMPILE_SECTION_READONLY_HOT;
-            if (pMT->IsWriteable())
-                section = CORCOMPILE_SECTION_HOT_WRITEABLE;
-            image->PlaceStructureForAddress(pMT, section);
-
-            if (pMT->HasInterfaceMap())
-                image->PlaceInternedStructureForAddress(pMT->GetInterfaceMap(), CORCOMPILE_SECTION_READONLY_SHARED_HOT, CORCOMPILE_SECTION_READONLY_HOT);
-
-            MethodTable::VtableIndirectionSlotIterator it = pMT->IterateVtableIndirectionSlots();
-            while (it.Next())
-            {
-                image->PlaceInternedStructureForAddress(it.GetIndirectionSlot(), CORCOMPILE_SECTION_READONLY_SHARED_HOT, CORCOMPILE_SECTION_READONLY_HOT);
-            }
-
-            image->PlaceStructureForAddress(pMT->GetWriteableData(), CORCOMPILE_SECTION_HOT);
-        }
-
-        if (profilingFlags & (1 << ReadNonVirtualSlots))
-        {
-            if (pMT->HasNonVirtualSlotsArray())
-                image->PlaceStructureForAddress(pMT->GetNonVirtualSlotsArray(), CORCOMPILE_SECTION_READONLY_HOT);
-        }
-
-        if (profilingFlags & (1 << ReadDispatchMap) && pMT->HasDispatchMapSlot())
-        {
-            image->PlaceInternedStructureForAddress(pMT->GetDispatchMap(), CORCOMPILE_SECTION_READONLY_SHARED_HOT, CORCOMPILE_SECTION_READONLY_HOT);
-        }
-
-        if (profilingFlags & (1 << WriteEEClass))
-        {
-            image->PlaceStructureForAddress(pClass, CORCOMPILE_SECTION_WRITE);
-
-            if (pClass->HasOptionalFields())
-                image->PlaceStructureForAddress(pClass->GetOptionalFields(), CORCOMPILE_SECTION_WRITE);
-        }
-
-        else if (profilingFlags & (1 << ReadEEClass))
-        {
-            image->PlaceStructureForAddress(pClass, CORCOMPILE_SECTION_HOT);
-
-            if (pClass->HasOptionalFields())
-                image->PlaceStructureForAddress(pClass->GetOptionalFields(), CORCOMPILE_SECTION_HOT);
-
-            if (pClass->GetVarianceInfo() != NULL)
-                image->PlaceInternedStructureForAddress(pClass->GetVarianceInfo(), CORCOMPILE_SECTION_READONLY_WARM, CORCOMPILE_SECTION_READONLY_WARM);
-
-#ifdef FEATURE_COMINTEROP
-            if (pClass->GetSparseCOMInteropVTableMap() != NULL)
-            {
-                image->PlaceStructureForAddress(pClass->GetSparseCOMInteropVTableMap(), CORCOMPILE_SECTION_WARM);
-                image->PlaceInternedStructureForAddress(pClass->GetSparseCOMInteropVTableMap()->GetMapList(), CORCOMPILE_SECTION_READONLY_WARM, CORCOMPILE_SECTION_READONLY_WARM);
-            }
-#endif
-        }
-
-        if (profilingFlags & (1 << ReadFieldDescs))
-        {
-            image->PlaceStructureForAddress(pMT->GetApproxFieldDescListRaw(), CORCOMPILE_SECTION_READONLY_HOT);
-        }
-
-        if (profilingFlags != 0)
-        {
-            if (pMT->HasPerInstInfo())
-            {
-                DPTR(MethodTable::PerInstInfoElem_t) pPerInstInfo = pMT->GetPerInstInfo();
-
-                BOOL fIsEagerBound = pMT->CanEagerBindToParentDictionaries(image, NULL);
-
-                if (fIsEagerBound)
-                {
-                    if (MethodTable::PerInstInfoElem_t::isRelative)
-                    {
-                        image->PlaceStructureForAddress(pPerInstInfo, CORCOMPILE_SECTION_READONLY_HOT);
-                    }
-                    else
-                    {
-                        image->PlaceInternedStructureForAddress(pPerInstInfo, CORCOMPILE_SECTION_READONLY_SHARED_HOT, CORCOMPILE_SECTION_READONLY_HOT);
-                    }
-                }
-                else
-                {
-                    image->PlaceStructureForAddress(pPerInstInfo, CORCOMPILE_SECTION_WRITE);
-                }
-            }
-
-            Dictionary * pDictionary = pMT->GetDictionary();
-            if (pDictionary != NULL)
-            {
-                BOOL fIsWriteable;
-
-                if (!pMT->IsCanonicalMethodTable())
-                {
-                    // CanEagerBindToMethodTable would not work for targeted patching here. The dictionary
-                    // layout is sensitive to compilation order that can be changed by TP compatible changes.
-                    BOOL canSaveSlots = (image->GetModule() == pMT->GetCanonicalMethodTable()->GetLoaderModule());
-
-                    fIsWriteable = pDictionary->IsWriteable(image, canSaveSlots,
-                                           pMT->GetNumGenericArgs(),
-                                           pMT->GetModule(),
-                                           pClass->GetDictionaryLayout());
-                }
-                else
-                {
-                    fIsWriteable = FALSE;
-                }
-
-                if (fIsWriteable)
-                {
-                    image->PlaceStructureForAddress(pDictionary, CORCOMPILE_SECTION_HOT_WRITEABLE);
-                    image->PlaceStructureForAddress(pClass->GetDictionaryLayout(), CORCOMPILE_SECTION_WARM);
-                }
-                else
-                {
-                    image->PlaceInternedStructureForAddress(pDictionary, CORCOMPILE_SECTION_READONLY_SHARED_HOT, CORCOMPILE_SECTION_READONLY_HOT);
-                }
-            }
-        }
-    }
-    if (th.IsTypeDesc())
-    {
-        if (profilingFlags & (1 << WriteTypeDesc))
-            image->PlaceStructureForAddress(th.AsTypeDesc(), CORCOMPILE_SECTION_WRITE);
-        else if  (profilingFlags & (1 << ReadTypeDesc))
-            image->PlaceStructureForAddress(th.AsTypeDesc(), CORCOMPILE_SECTION_HOT);
-        else
-            image->PlaceStructureForAddress(th.AsTypeDesc(), CORCOMPILE_SECTION_WARM);
-    }
-}
-
-void Module::PlaceMethod(DataImage *image, MethodDesc *pMD, DWORD profilingFlags)
-{
-    STANDARD_VM_CONTRACT;
-
-    if (pMD == NULL)
-        return;
-
-    if (pMD->GetLoaderModule() != this)
-        return;
-
-    if (profilingFlags & (1 << ReadMethodCode))
-    {
-        if (pMD->IsNDirect())
-        {
-            NDirectMethodDesc *pNMD = (NDirectMethodDesc *)pMD;
-            image->PlaceStructureForAddress((void*) pNMD->GetWriteableData(), CORCOMPILE_SECTION_WRITE);
-
-#ifdef HAS_NDIRECT_IMPORT_PRECODE
-            // The NDirect import thunk glue is used only if no marshaling is required
-            if (!pNMD->MarshalingRequired())
-            {
-                image->PlaceStructureForAddress((void*) pNMD->GetNDirectImportThunkGlue(), CORCOMPILE_SECTION_METHOD_PRECODE_HOT);
-            }
-#endif // HAS_NDIRECT_IMPORT_PRECODE
-
-            // Late bound NDirect methods require their LibName at startup.
-            if (!pNMD->IsQCall())
-            {
-                image->PlaceStructureForAddress((void*) pNMD->GetLibName(), CORCOMPILE_SECTION_READONLY_HOT);
-                image->PlaceStructureForAddress((void*) pNMD->GetEntrypointName(), CORCOMPILE_SECTION_READONLY_HOT);
-            }
-        }
-
-#ifdef FEATURE_COMINTEROP
-        if (pMD->IsComPlusCall())
-        {
-            ComPlusCallMethodDesc *pCMD = (ComPlusCallMethodDesc *)pMD;
-
-            // If the ComPlusCallMethodDesc was actually used for interop, its ComPlusCallInfo should be hot.
-            image->PlaceStructureForAddress((void*) pCMD->m_pComPlusCallInfo, CORCOMPILE_SECTION_HOT);
-       }
-#endif // FEATURE_COMINTEROP
-
-        // Stubs-as-IL have writeable signatures sometimes, so can't place them
-        // into read-only section. We should not get here for stubs-as-il anyway,
-        // but we will filter them out just to be sure.
-        if (pMD->HasStoredSig() && !pMD->IsILStub())
-        {
-            StoredSigMethodDesc *pSMD = (StoredSigMethodDesc*) pMD;
-
-            if (pSMD->HasStoredMethodSig())
-            {
-                image->PlaceInternedStructureForAddress((void*) pSMD->GetStoredMethodSig(), CORCOMPILE_SECTION_READONLY_SHARED_HOT, CORCOMPILE_SECTION_READONLY_HOT);
-            }
-        }
-    }
-
-    // We store the entire hot chunk in the SECTION_WRITE section
-    if (profilingFlags & (1 << WriteMethodDesc))
-    {
-        image->PlaceStructureForAddress(pMD, CORCOMPILE_SECTION_WRITE);
-    }
-
-
-    if (profilingFlags & (1 << WriteMethodPrecode))
-    {
-        Precode* pPrecode = pMD->GetSavedPrecodeOrNull(image);
-        // protect against stale IBC data
-        if (pPrecode != NULL)
-        {
-            CorCompileSection section = CORCOMPILE_SECTION_METHOD_PRECODE_WRITE;
-            if (pPrecode->IsPrebound(image))
-                section = CORCOMPILE_SECTION_METHOD_PRECODE_HOT;
-            // Note: This is going to place the entire PRECODE_FIXUP chunk if we have one
-            image->PlaceStructureForAddress(pPrecode, section);
-        }
-    }
-    else if (profilingFlags & (1 << ReadMethodPrecode))
-    {
-        Precode* pPrecode = pMD->GetSavedPrecodeOrNull(image);
-        // protect against stale IBC data
-        if (pPrecode != NULL)
-        {
-            // Note: This is going to place the entire PRECODE_FIXUP chunk if we have one
-            image->PlaceStructureForAddress(pPrecode, CORCOMPILE_SECTION_METHOD_PRECODE_HOT);
-        }
-    }
-}
-
-void Module::Arrange(DataImage *image)
-{
-    STANDARD_VM_CONTRACT;
-
-    // We collect IBC logging profiling data and use that to guide the layout of the image.
-    image->PlaceStructureForAddress(this, CORCOMPILE_SECTION_MODULE);
-
-    // The stub method table is shared by all IL stubs in the module, so place it into the hot section
-    MethodTable * pStubMT = GetILStubCache()->GetStubMethodTable();
-    if (pStubMT != NULL)
-        PlaceType(image, pStubMT, ReadMethodTable);
-
-    CorProfileData * profileData = GetProfileData();
-    if (profileData)
-    {
-        //
-        // Place hot type structues in the order specifiled by TypeProfilingData array
-        //
-        CORBBTPROF_TOKEN_INFO * pTypeProfilingData = profileData->GetTokenFlagsData(TypeProfilingData);
-        DWORD                   cTypeProfilingData = profileData->GetTokenFlagsCount(TypeProfilingData);
-        for (unsigned int i = 0; (i < cTypeProfilingData); i++)
-        {
-            CORBBTPROF_TOKEN_INFO * entry = &pTypeProfilingData[i];
-            mdToken                 token = entry->token;
-            DWORD                   flags = entry->flags;
-#if defined(_DEBUG) && !defined(DACCESS_COMPILE)
-            g_pConfig->DebugCheckAndForceIBCFailure(EEConfig::CallSite_6);
-#endif
-
-            if (TypeFromToken(token) == mdtTypeDef)
-            {
-                TypeHandle th = LookupTypeDef(token);
-                //
-                // Place a hot normal type and it's data
-                //
-                PlaceType(image, th, flags);
-            }
-            else if (TypeFromToken(token) == ibcTypeSpec)
-            {
-                CORBBTPROF_BLOB_PARAM_SIG_ENTRY *pBlobSigEntry = profileData->GetBlobSigEntry(token);
-
-                if (pBlobSigEntry == NULL)
-                {
-                    //
-                    // Print an error message for the type load failure
-                    //
-                    StackSString msg(W("Did not find definition for type token "));
-
-                    char buff[16];
-                    sprintf_s(buff, COUNTOF(buff), "%08x", token);
-                    StackSString szToken(SString::Ascii, &buff[0]);
-                    msg += szToken;
-                    msg += W(" in profile data.\n");
-
-                    GetSvcLogger()->Log(msg, LogLevel_Info);
-                }
-                else // (pBlobSigEntry  != NULL)
-                {
-                    _ASSERTE(pBlobSigEntry->blob.token == token);
-                    //
-                    // decode generic type signature
-                    //
-                    TypeHandle th = LoadIBCTypeHelper(image, pBlobSigEntry);
-
-                    //
-                    // Place a hot instantiated type and it's data
-                    //
-                    PlaceType(image, th, flags);
-                }
-            }
-            else if (TypeFromToken(token) == mdtFieldDef)
-            {
-                FieldDesc *pFD = LookupFieldDef(token);
-                if (pFD && pFD->IsRVA())
-                {
-                    if (entry->flags & (1 << RVAFieldData))
-                    {
-                        BYTE *pRVAData = (BYTE*) pFD->GetStaticAddressHandle(NULL);
-                        //
-                        // Place a hot RVA static field
-                        //
-                        image->PlaceStructureForAddress(pRVAData, CORCOMPILE_SECTION_RVA_STATICS_HOT);
-                    }
-                }
-            }
-        }
-
-        //
-        // Place hot methods and method data in the order specifiled by MethodProfilingData array
-        //
-        CORBBTPROF_TOKEN_INFO * pMethodProfilingData = profileData->GetTokenFlagsData(MethodProfilingData);
-        DWORD                   cMethodProfilingData = profileData->GetTokenFlagsCount(MethodProfilingData);
-        for (unsigned int i = 0; (i < cMethodProfilingData); i++)
-        {
-            mdToken token          = pMethodProfilingData[i].token;
-            DWORD   profilingFlags = pMethodProfilingData[i].flags;
-#if defined(_DEBUG) && !defined(DACCESS_COMPILE)
-            g_pConfig->DebugCheckAndForceIBCFailure(EEConfig::CallSite_7);
-#endif
-
-            if (TypeFromToken(token) == mdtMethodDef)
-            {
-                MethodDesc *  pMD = LookupMethodDef(token);
-                //
-                // Place a hot normal method and it's data
-                //
-                PlaceMethod(image, pMD, profilingFlags);
-            }
-            else if (TypeFromToken(token) == ibcMethodSpec)
-            {
-                CORBBTPROF_BLOB_PARAM_SIG_ENTRY *pBlobSigEntry = profileData->GetBlobSigEntry(token);
-
-                if (pBlobSigEntry == NULL)
-                {
-                    //
-                    // Print an error message for the type load failure
-                    //
-                    StackSString msg(W("Did not find definition for method token "));
-
-                    char buff[16];
-                    sprintf_s(buff, COUNTOF(buff), "%08x", token);
-                    StackSString szToken(SString::Ascii, &buff[0]);
-                    msg += szToken;
-                    msg += W(" in profile data.\n");
-
-                    GetSvcLogger()->Log(msg, LogLevel_Info);
-                }
-                else // (pBlobSigEntry  != NULL)
-                {
-                    _ASSERTE(pBlobSigEntry->blob.token == token);
-                    MethodDesc * pMD = LoadIBCMethodHelper(image, pBlobSigEntry);
-
-                    if (pMD != NULL)
-                    {
-                        //
-                        // Place a hot instantiated method and it's data
-                        //
-                        PlaceMethod(image, pMD, profilingFlags);
-                    }
-                }
-            }
-        }
-    }
-
-    // Now place all remaining items
-    image->PlaceRemainingStructures();
-}
-
-void ModuleCtorInfo::Fixup(DataImage *image)
-{
-    STANDARD_VM_CONTRACT;
-
-    if (numElementsHot > 0)
-    {
-        image->FixupPointerField(this, offsetof(ModuleCtorInfo, cctorInfoHot));
-        image->FixupPointerField(this, offsetof(ModuleCtorInfo, hotHashOffsets));
-    }
-    else
-    {
-        image->ZeroPointerField(this, offsetof(ModuleCtorInfo, cctorInfoHot));
-        image->ZeroPointerField(this, offsetof(ModuleCtorInfo, hotHashOffsets));
-    }
-
-    _ASSERTE(numElements > numElementsHot || numElements == numElementsHot);
-    if (numElements > numElementsHot)
-    {
-        image->FixupPointerField(this, offsetof(ModuleCtorInfo, cctorInfoCold));
-        image->FixupPointerField(this, offsetof(ModuleCtorInfo, coldHashOffsets));
-    }
-    else
-    {
-        image->ZeroPointerField(this, offsetof(ModuleCtorInfo, cctorInfoCold));
-        image->ZeroPointerField(this, offsetof(ModuleCtorInfo, coldHashOffsets));
-    }
-
-    if (numElements > 0)
-    {
-        image->FixupPointerField(this, offsetof(ModuleCtorInfo, ppMT));
-
-        for (DWORD i=0; i<numElements; i++)
-        {
-            image->FixupRelativePointerField(ppMT, i * sizeof(ppMT[0]));
-        }
-    }
-    else
-    {
-        image->ZeroPointerField(this, offsetof(ModuleCtorInfo, ppMT));
-    }
-
-    if (numHotGCStaticsMTs > 0)
-    {
-        image->FixupPointerField(this, offsetof(ModuleCtorInfo, ppHotGCStaticsMTs));
-
-        image->BeginRegion(CORINFO_REGION_HOT);
-        for (DWORD i=0; i < numHotGCStaticsMTs; i++)
-        {
-            image->FixupMethodTablePointer(ppHotGCStaticsMTs, &ppHotGCStaticsMTs[i]);
-        }
-        image->EndRegion(CORINFO_REGION_HOT);
-    }
-    else
-    {
-        image->ZeroPointerField(this, offsetof(ModuleCtorInfo, ppHotGCStaticsMTs));
-    }
-
-    if (numColdGCStaticsMTs > 0)
-    {
-        image->FixupPointerField(this, offsetof(ModuleCtorInfo, ppColdGCStaticsMTs));
-
-        image->BeginRegion(CORINFO_REGION_COLD);
-        for (DWORD i=0; i < numColdGCStaticsMTs; i++)
-        {
-            image->FixupMethodTablePointer(ppColdGCStaticsMTs, &ppColdGCStaticsMTs[i]);
-        }
-        image->EndRegion(CORINFO_REGION_COLD);
-    }
-    else
-    {
-        image->ZeroPointerField(this, offsetof(ModuleCtorInfo, ppColdGCStaticsMTs));
-    }
-}
-
-#ifdef _PREFAST_
-#pragma warning(push)
-#pragma warning(disable:21000) // Suppress PREFast warning about overly large function
-#endif
-void Module::Fixup(DataImage *image)
-{
-    STANDARD_VM_CONTRACT;
-
-    // Propagate all changes to the image copy
-    memcpy(image->GetImagePointer(this), (void*)this, sizeof(Module));
-
-    //
-    // Zero out VTable
-    //
-
-    image->ZeroPointerField(this, 0);
-
-    image->FixupPointerField(this, offsetof(Module, m_pNGenLayoutInfo));
-
-    image->ZeroField(this, offsetof(Module, m_pSimpleName), sizeof(m_pSimpleName));
-
-    image->ZeroField(this, offsetof(Module, m_file), sizeof(m_file));
-
-    image->ZeroField(this, offsetof(Module, m_dwTransientFlags), sizeof(m_dwTransientFlags));
-
-    image->ZeroField(this, offsetof(Module, m_pVASigCookieBlock), sizeof(m_pVASigCookieBlock));
-    image->ZeroField(this, offsetof(Module, m_pAssembly), sizeof(m_pAssembly));
-    image->ZeroField(this, offsetof(Module, m_moduleRef), sizeof(m_moduleRef));
-
-    image->ZeroField(this, offsetof(Module, m_Crst), sizeof(m_Crst));
-    image->ZeroField(this, offsetof(Module, m_FixupCrst), sizeof(m_FixupCrst));
-
-    image->ZeroField(this, offsetof(Module, m_pProfilingBlobTable), sizeof(m_pProfilingBlobTable));
-    image->ZeroField(this, offsetof(Module, m_pProfileData), sizeof(m_pProfileData));
-
-    image->ZeroPointerField(this, offsetof(Module, m_pNgenStats));
-
-    // Fixup the property name set
-    image->FixupPointerField(this, offsetof(Module, m_propertyNameSet));
-
-    //
-    // Fixup the method table
-    //
-
-    image->ZeroField(this, offsetof(Module, m_pISymUnmanagedReader), sizeof(m_pISymUnmanagedReader));
-    image->ZeroField(this, offsetof(Module, m_ISymUnmanagedReaderCrst), sizeof(m_ISymUnmanagedReaderCrst));
-
-    image->ZeroField(this, offsetof(Module, m_LookupTableCrst), sizeof(m_LookupTableCrst));
-
-    m_TypeDefToMethodTableMap.Fixup(image);
-    m_TypeRefToMethodTableMap.Fixup(image, FALSE);
-    m_MethodDefToDescMap.Fixup(image);
-    m_FieldDefToDescMap.Fixup(image);
-    if(m_pMemberRefToDescHashTable != NULL)
-    {
-        image->FixupPointerField(this, offsetof(Module, m_pMemberRefToDescHashTable));
-        m_pMemberRefToDescHashTable->Fixup(image);
-    }
-    m_GenericParamToDescMap.Fixup(image);
-    m_GenericTypeDefToCanonMethodTableMap.Fixup(image);
-    m_FileReferencesMap.Fixup(image, FALSE);
-    m_ManifestModuleReferencesMap.Fixup(image, FALSE);
-    m_MethodDefToPropertyInfoMap.Fixup(image, FALSE);
-
-    image->ZeroPointerField(this, offsetof(Module, m_pILStubCache));
-
-    if (m_pAvailableClasses != NULL) {
-        image->FixupPointerField(this, offsetof(Module, m_pAvailableClasses));
-        m_pAvailableClasses->Fixup(image);
-    }
-
-    image->ZeroField(this, offsetof(Module, m_pAvailableClassesCaseIns), sizeof(m_pAvailableClassesCaseIns));
-    image->ZeroField(this, offsetof(Module, m_InstMethodHashTableCrst), sizeof(m_InstMethodHashTableCrst));
-
-    image->BeginRegion(CORINFO_REGION_COLD);
-
-    if (m_pAvailableParamTypes) {
-        image->FixupPointerField(this, offsetof(Module, m_pAvailableParamTypes));
-        m_pAvailableParamTypes->Fixup(image);
-    }
-
-    if (m_pInstMethodHashTable) {
-        image->FixupPointerField(this, offsetof(Module, m_pInstMethodHashTable));
-        m_pInstMethodHashTable->Fixup(image);
-    }
-
-    {
-        MethodTable * pStubMT = GetILStubCache()->GetStubMethodTable();
-        if (pStubMT != NULL)
-            pStubMT->Fixup(image);
-    }
-
-    if (m_pStubMethodHashTable) {
-        image->FixupPointerField(this, offsetof(Module, m_pStubMethodHashTable));
-        m_pStubMethodHashTable->Fixup(image);
-    }
-
-    image->EndRegion(CORINFO_REGION_COLD);
-
-#ifdef _DEBUG
-    //
-    // Unseal the generic tables:
-    //
-    // - We need to run managed code to serialize the Security attributes of the ngen image
-    //   and we are now using generic types in the Security/Reflection code.
-    // - Compilation of other modules of multimodule assemblies may add more types
-    //   to the generic tables.
-    //
-    UnsealGenericTypesAndMethods();
-#endif
-
-    m_ModuleCtorInfo.Fixup(image);
-
-    //
-    // Fixup binder
-    //
-
-    if (m_pBinder != NULL)
-    {
-        image->FixupPointerField(this, offsetof(Module, m_pBinder));
-        m_pBinder->Fixup(image);
-    }
-
-
-    //
-    // Fixup classes
-    //
-
-    {
-        LookupMap<PTR_MethodTable>::Iterator typeDefIter(&m_TypeDefToMethodTableMap);
-
-        image->BeginRegion(CORINFO_REGION_COLD);
-        while (typeDefIter.Next())
-        {
-            MethodTable * t = typeDefIter.GetElement();
-            if (image->IsStored(t))
-                t->Fixup(image);
-        }
-        image->EndRegion(CORINFO_REGION_COLD);
-    }
-
-    {
-        LookupMap<PTR_TypeRef>::Iterator typeRefIter(&m_TypeRefToMethodTableMap);
-        DWORD rid = 0;
-
-        image->BeginRegion(CORINFO_REGION_HOT);
-        while (typeRefIter.Next())
-        {
-            TADDR flags;
-            TypeHandle th = TypeHandle::FromTAddr(dac_cast<TADDR>(typeRefIter.GetElementAndFlags(&flags)));
-
-            if (!th.IsNull())
-            {
-                if (th.GetLoaderModule() != this || image->IsStored(th.AsPtr()))
-                {
-                    PTR_TADDR hotItemValuePtr = m_TypeRefToMethodTableMap.FindHotItemValuePtr(rid);
-                    BOOL fSet = FALSE;
-
-                    if (image->CanEagerBindToTypeHandle(th))
-                    {
-                        if (image->CanHardBindToZapModule(th.GetLoaderModule()))
-                        {
-                            PVOID pTarget = th.IsTypeDesc() ? th.AsTypeDesc() : th.AsPtr();
-                            SSIZE_T offset = th.IsTypeDesc() ? 2 : 0;
-
-                            _ASSERTE((flags & offset) == 0);
-
-                            image->FixupField(m_TypeRefToMethodTableMap.pTable, rid * sizeof(TADDR),
-                                pTarget, flags | offset, IMAGE_REL_BASED_RelativePointer);
-
-                            // In case this item is also in the hot item subtable, fix it up there as well
-                            if (hotItemValuePtr != NULL)
-                            {
-                                image->FixupField(m_TypeRefToMethodTableMap.hotItemList,
-                                    (BYTE *)hotItemValuePtr - (BYTE *)m_TypeRefToMethodTableMap.hotItemList,
-                                    pTarget, flags | offset, IMAGE_REL_BASED_RelativePointer);
-                            }
-                            fSet = TRUE;
-                        }
-                        else
-                        // Create the indirection only if the entry is hot or we do have indirection cell already
-                        if (hotItemValuePtr != NULL || image->GetExistingTypeHandleImport(th) != NULL)
-                        {
-                            _ASSERTE((flags & FIXUP_POINTER_INDIRECTION) == 0);
-
-                            ZapNode * pImport = image->GetTypeHandleImport(th);
-                            image->FixupFieldToNode(m_TypeRefToMethodTableMap.pTable, rid * sizeof(TADDR),
-                                pImport, flags | FIXUP_POINTER_INDIRECTION, IMAGE_REL_BASED_RelativePointer);
-                            if (hotItemValuePtr != NULL)
-                            {
-                                image->FixupFieldToNode(m_TypeRefToMethodTableMap.hotItemList,
-                                    (BYTE *)hotItemValuePtr - (BYTE *)m_TypeRefToMethodTableMap.hotItemList,
-                                    pImport, flags | FIXUP_POINTER_INDIRECTION, IMAGE_REL_BASED_RelativePointer);
-                            }
-                            fSet = TRUE;
-                        }
-                    }
-
-                    if (!fSet)
-                    {
-                        image->ZeroPointerField(m_TypeRefToMethodTableMap.pTable, rid * sizeof(TADDR));
-                        // In case this item is also in the hot item subtable, fix it up there as well
-                        if (hotItemValuePtr != NULL)
-                        {
-                            image->ZeroPointerField(m_TypeRefToMethodTableMap.hotItemList,
-                                (BYTE *)hotItemValuePtr - (BYTE *)m_TypeRefToMethodTableMap.hotItemList);
-                        }
-                    }
-                }
-            }
-
-            rid++;
-        }
-        image->EndRegion(CORINFO_REGION_HOT);
-    }
-
-    {
-        LookupMap<PTR_TypeVarTypeDesc>::Iterator genericParamIter(&m_GenericParamToDescMap);
-
-        while (genericParamIter.Next())
-        {
-            TypeVarTypeDesc * pTypeDesc = genericParamIter.GetElement();
-
-            if (pTypeDesc != NULL)
-            {
-                _ASSERTE(image->IsStored(pTypeDesc));
-                pTypeDesc->Fixup(image);
-            }
-        }
-    }
-
-    //
-    // Fixup the assembly reference map table
-    //
-
-    {
-        LookupMap<PTR_Module>::Iterator manifestModuleIter(&m_ManifestModuleReferencesMap);
-        DWORD rid = 0;
-
-        while (manifestModuleIter.Next())
-        {
-            TADDR flags;
-            Module * pModule = manifestModuleIter.GetElementAndFlags(&flags);
-
-            if (pModule != NULL)
-            {
-                if (image->CanEagerBindToModule(pModule))
-                {
-                    if (image->CanHardBindToZapModule(pModule))
-                    {
-                        image->FixupField(m_ManifestModuleReferencesMap.pTable, rid * sizeof(TADDR),
-                            pModule, flags, IMAGE_REL_BASED_RelativePointer);
-                    }
-                    else
-                    {
-                        image->ZeroPointerField(m_ManifestModuleReferencesMap.pTable, rid * sizeof(TADDR));
-                    }
-                }
-                else
-                {
-                    image->ZeroPointerField(m_ManifestModuleReferencesMap.pTable, rid * sizeof(TADDR));
-                }
-            }
-
-            rid++;
-        }
-    }
-
-    //
-    // Zero out file references table.
-    //
-    image->ZeroField(m_FileReferencesMap.pTable, 0,
-                     m_FileReferencesMap.GetSize() * sizeof(void*));
-
-
-    image->ZeroField(this, offsetof(Module, m_debuggerSpecificData), sizeof(m_debuggerSpecificData));
-
-    image->ZeroField(this, offsetof(Module, m_AssemblyRefByNameCount), sizeof(m_AssemblyRefByNameCount));
-    image->ZeroPointerField(this, offsetof(Module, m_AssemblyRefByNameTable));
-
-#ifdef FEATURE_READYTORUN
-    // For composite ready-to-run images, the manifest assembly ref map is stored in the native image
-    // and shared by all its component images.
-    if (m_pNativeImage == NULL)
-#endif
-    {
-        image->ZeroPointerField(this,offsetof(Module, m_NativeMetadataAssemblyRefMap));
-    }
-
-    //
-    // Fixup statics
-    //
-    LOG((LF_CLASSLOADER, LL_INFO10000, "STATICS: fixing up module static data\n"));
-
-    image->ZeroPointerField(this, offsetof(Module, m_ModuleID));
-    image->ZeroField(this, offsetof(Module, m_ModuleIndex), sizeof(m_ModuleIndex));
-
-    image->FixupPointerField(this, offsetof(Module, m_pDynamicStaticsInfo));
-
-    DynamicStaticsInfo* pDSI = m_pDynamicStaticsInfo;
-    for (DWORD i = 0; i < m_cDynamicEntries; i++, pDSI++)
-    {
-        if (pDSI->pEnclosingMT->GetLoaderModule() == this &&
-            // CEEPreloader::TriageTypeForZap() could have rejected this type
-            image->IsStored(pDSI->pEnclosingMT))
-        {
-            image->FixupPointerField(m_pDynamicStaticsInfo, (BYTE *)&pDSI->pEnclosingMT - (BYTE *)m_pDynamicStaticsInfo);
-        }
-        else
-        {
-            // Some other (mutually-recursive) dependency must have loaded
-            // a generic instantiation whose static were pumped into the
-            // assembly being ngenned.
-            image->ZeroPointerField(m_pDynamicStaticsInfo, (BYTE *)&pDSI->pEnclosingMT - (BYTE *)m_pDynamicStaticsInfo);
-        }
-    }
-
-    // If we failed to load some types we need to reset the pointers to the static offset tables so they'll be
-    // rebuilt at runtime.
-    if (m_pRegularStaticOffsets != (PTR_DWORD)NGEN_STATICS_ALLCLASSES_WERE_LOADED)
-    {
-        _ASSERTE(m_pThreadStaticOffsets != (PTR_DWORD)NGEN_STATICS_ALLCLASSES_WERE_LOADED);
-        image->ZeroPointerField(this, offsetof(Module, m_pRegularStaticOffsets));
-        image->ZeroPointerField(this, offsetof(Module, m_pThreadStaticOffsets));
-    }
-
-    // Fix up inlining data
-    if(m_pPersistentInlineTrackingMapNGen)
-    {
-        image->FixupPointerField(this, offsetof(Module, m_pPersistentInlineTrackingMapNGen));
-        m_pPersistentInlineTrackingMapNGen->Fixup(image);
-    }
-    else
-    {
-        image->ZeroPointerField(this, offsetof(Module, m_pPersistentInlineTrackingMapNGen));
-    }
-
-    SetIsModuleSaved();
-}
-#ifdef _PREFAST_
-#pragma warning(pop)
-#endif
-
-#endif // FEATURE_NATIVE_IMAGE_GENERATION
-
-#ifdef FEATURE_PREJIT
-//
-// Is "address" a data-structure in the native image?
-//
-
-BOOL Module::IsPersistedObject(void *address)
-{
-    CONTRACTL
-    {
-        INSTANCE_CHECK;
-        NOTHROW;
-        GC_NOTRIGGER;
-        MODE_ANY;
-        FORBID_FAULT;
-    }
-    CONTRACTL_END;
-
-    if (!HasNativeImage())
-        return FALSE;
-
-    PEImageLayout *pLayout = GetNativeImage();
-    _ASSERTE(pLayout->IsMapped());
-
-    return (address >= pLayout->GetBase()
-            && address < (BYTE*)pLayout->GetBase() + pLayout->GetVirtualSize());
-}
-#endif // FEATURE_PREJIT
-
-Module *Module::GetModuleFromIndex(DWORD ix)
-{
-    CONTRACT(Module*)
-    {
-        INSTANCE_CHECK;
-        THROWS;
-        GC_TRIGGERS;
-        MODE_ANY;
-        POSTCONDITION(CheckPointer(RETVAL, NULL_OK));
-    }
-    CONTRACT_END;
-
-    if (HasNativeOrReadyToRunImage())
-    {
-        RETURN ZapSig::DecodeModuleFromIndex(this, ix);
-    }
-    else
-    {
-        mdAssemblyRef mdAssemblyRefToken = TokenFromRid(ix, mdtAssemblyRef);
-        Assembly *pAssembly = this->LookupAssemblyRef(mdAssemblyRefToken);
-        if (pAssembly)
-        {
-            RETURN pAssembly->GetManifestModule();
-        }
-        else
-        {
-            // GetModuleFromIndex failed
-            RETURN NULL;
-        }
-    }
-}
-
-#endif // !DACCESS_COMPILE
-
-Module *Module::GetModuleFromIndexIfLoaded(DWORD ix)
-{
-    CONTRACT(Module*)
-    {
-        INSTANCE_CHECK;
-        NOTHROW;
-        GC_NOTRIGGER;
-        MODE_ANY;
-        PRECONDITION(HasNativeOrReadyToRunImage());
-        POSTCONDITION(CheckPointer(RETVAL, NULL_OK));
-    }
-    CONTRACT_END;
-
-#ifndef DACCESS_COMPILE
-    RETURN ZapSig::DecodeModuleFromIndexIfLoaded(this, ix);
-#else // DACCESS_COMPILE
-    DacNotImpl();
-    RETURN NULL;
-#endif // DACCESS_COMPILE
-}
-
-#ifndef DACCESS_COMPILE
-IMDInternalImport* Module::GetNativeAssemblyImport(BOOL loadAllowed)
-{
-    CONTRACT(IMDInternalImport*)
-    {
-        INSTANCE_CHECK;
-        if (loadAllowed) GC_TRIGGERS;                    else GC_NOTRIGGER;
-        if (loadAllowed) THROWS;                         else NOTHROW;
-        if (loadAllowed) INJECT_FAULT(COMPlusThrowOM()); else FORBID_FAULT;
-        MODE_ANY;
-        PRECONDITION(HasNativeOrReadyToRunImage());
-        POSTCONDITION(loadAllowed ?
-            CheckPointer(RETVAL) :
-            CheckPointer(RETVAL, NULL_OK));
-    }
-    CONTRACT_END;
-
-#ifdef FEATURE_PREJIT
-    // Check if image is R2R
-    if (!GetFile()->IsILImageReadyToRun())
-    {
-        RETURN GetFile()->GetPersistentNativeImage()->GetNativeMDImport(loadAllowed);
-    }
-#endif
-
-    RETURN GetFile()->GetOpenedILimage()->GetNativeMDImport(loadAllowed);
-}
-
-BYTE* Module::GetNativeFixupBlobData(RVA rva)
-{
-    CONTRACT(BYTE*)
-    {
-        INSTANCE_CHECK;
-        NOTHROW;
-        GC_NOTRIGGER;
-        MODE_ANY;
-        POSTCONDITION(CheckPointer(RETVAL));
-    }
-    CONTRACT_END;
-
-    RETURN(BYTE*) GetNativeOrReadyToRunImage()->GetRvaData(rva);
-}
-#endif // DACCESS_COMPILE
-
-#ifdef FEATURE_PREJIT
-
-#ifndef DACCESS_COMPILE
-
-/*static*/
-void Module::RestoreMethodTablePointerRaw(MethodTable ** ppMT,
-                                          Module *pContainingModule,
-                                          ClassLoadLevel level)
-{
-    CONTRACTL
-    {
-        THROWS;
-        GC_TRIGGERS;
-        MODE_ANY;
-    }
-    CONTRACTL_END;
-
-    // Ensure that the compiler won't fetch the value twice
-    TADDR fixup = VolatileLoadWithoutBarrier((TADDR *)ppMT);
-
-#ifdef _DEBUG
-    if (pContainingModule != NULL)
-    {
-        Module * dbg_pZapModule = ExecutionManager::FindZapModule(dac_cast<TADDR>(ppMT));
-        _ASSERTE((dbg_pZapModule == NULL) || (pContainingModule == dbg_pZapModule));
-    }
-#endif //_DEBUG
-
-    if (CORCOMPILE_IS_POINTER_TAGGED(fixup))
-    {
-#ifdef HOST_64BIT
-        CONSISTENCY_CHECK((CORCOMPILE_UNTAG_TOKEN(fixup)>>32) == 0);
-#endif
-
-        RVA fixupRva = (RVA) CORCOMPILE_UNTAG_TOKEN(fixup);
-
-        if (pContainingModule == NULL)
-            pContainingModule = ExecutionManager::FindZapModule(dac_cast<TADDR>(ppMT));
-        PREFIX_ASSUME(pContainingModule != NULL);
-
-        _ASSERTE((*pContainingModule->GetNativeFixupBlobData(fixupRva) & ~ENCODE_MODULE_OVERRIDE) == ENCODE_TYPE_HANDLE);
-
-        Module * pInfoModule;
-        PCCOR_SIGNATURE pBlobData = pContainingModule->GetEncodedSig(fixupRva, &pInfoModule);
-
-        TypeHandle  th          = ZapSig::DecodeType(pContainingModule,
-                                                             pInfoModule,
-                                                             pBlobData,
-                                                             level);
-        *ppMT = th.AsMethodTable();
-    }
-    else if (*ppMT)
-    {
-        ClassLoader::EnsureLoaded(*ppMT, level);
-    }
-}
-
-/*static*/
-void Module::RestoreMethodTablePointer(FixupPointer<PTR_MethodTable> * ppMT,
-                                       Module *pContainingModule,
-                                       ClassLoadLevel level)
-{
-    CONTRACTL
-    {
-        THROWS;
-        GC_TRIGGERS;
-        MODE_ANY;
-    }
-    CONTRACTL_END;
-
-    if (ppMT->IsNull())
-        return;
-
-    if (ppMT->IsTagged())
-    {
-        RestoreMethodTablePointerRaw(ppMT->GetValuePtr(), pContainingModule, level);
-    }
-    else
-    {
-        ClassLoader::EnsureLoaded(ppMT->GetValue(), level);
-    }
-}
-
-/*static*/
-void Module::RestoreMethodTablePointer(RelativeFixupPointer<PTR_MethodTable> * ppMT,
-                                       Module *pContainingModule,
-                                       ClassLoadLevel level)
-{
-    CONTRACTL
-    {
-        THROWS;
-        GC_TRIGGERS;
-        MODE_ANY;
-    }
-    CONTRACTL_END;
-
-    if (ppMT->IsNull())
-        return;
-
-    if (ppMT->IsTagged((TADDR)ppMT))
-    {
-        RestoreMethodTablePointerRaw(ppMT->GetValuePtr(), pContainingModule, level);
-    }
-    else
-    {
-        ClassLoader::EnsureLoaded(ppMT->GetValue(), level);
-    }
-}
-
-#endif // !DACCESS_COMPILE
-
-BOOL Module::IsZappedCode(PCODE code)
-{
-    CONTRACTL
-    {
-        NOTHROW;
-        GC_NOTRIGGER;
-        SUPPORTS_DAC;
-    }
-    CONTRACTL_END;
-
-    if (!HasNativeImage())
-        return FALSE;
-
-    PEImageLayout *pNativeImage = GetNativeImage();
-
-    UINT32 cCode = 0;
-    PCODE pCodeSection;
-
-    pCodeSection = pNativeImage->GetNativeHotCode(&cCode);
-    if ((pCodeSection <= code) && (code < pCodeSection + cCode))
-    {
-        return TRUE;
-    }
-
-    pCodeSection = pNativeImage->GetNativeCode(&cCode);
-    if ((pCodeSection <= code) && (code < pCodeSection + cCode))
-    {
-        return TRUE;
-    }
-
-    return FALSE;
-}
-
-BOOL Module::IsZappedPrecode(PCODE code)
-{
-    CONTRACTL
-    {
-        NOTHROW;
-        GC_NOTRIGGER;
-        SUPPORTS_DAC;
-    }
-    CONTRACTL_END;
-
-    if (m_pNGenLayoutInfo == NULL)
-        return FALSE;
-
-    for (SIZE_T i = 0; i < COUNTOF(m_pNGenLayoutInfo->m_Precodes); i++)
-    {
-        if (m_pNGenLayoutInfo->m_Precodes[i].IsInRange(code))
-            return TRUE;
-    }
-
-    return FALSE;
-}
-
-PCCOR_SIGNATURE Module::GetEncodedSig(RVA fixupRva, Module **ppDefiningModule)
-{
-    CONTRACT(PCCOR_SIGNATURE)
-    {
-        INSTANCE_CHECK;
-        THROWS;
-        GC_TRIGGERS;
-        MODE_ANY;
-        POSTCONDITION(CheckPointer(RETVAL));
-        SUPPORTS_DAC;
-    }
-    CONTRACT_END;
-
-#ifndef DACCESS_COMPILE
-    PCCOR_SIGNATURE pBuffer = GetNativeFixupBlobData(fixupRva);
-
-    BYTE kind = *pBuffer++;
-
-    *ppDefiningModule = (kind & ENCODE_MODULE_OVERRIDE) ? GetModuleFromIndex(CorSigUncompressData(pBuffer)) : this;
-
-    RETURN pBuffer;
-#else
-    RETURN NULL;
-#endif // DACCESS_COMPILE
-}
-
-PCCOR_SIGNATURE Module::GetEncodedSigIfLoaded(RVA fixupRva, Module **ppDefiningModule)
-{
-    CONTRACT(PCCOR_SIGNATURE)
-    {
-        INSTANCE_CHECK;
-        NOTHROW;
-        GC_NOTRIGGER;
-        MODE_ANY;
-        POSTCONDITION(CheckPointer(RETVAL));
-        SUPPORTS_DAC;
-    }
-    CONTRACT_END;
-
-#ifndef DACCESS_COMPILE
-    PCCOR_SIGNATURE pBuffer = GetNativeFixupBlobData(fixupRva);
-
-    BYTE kind = *pBuffer++;
-
-    *ppDefiningModule = (kind & ENCODE_MODULE_OVERRIDE) ? GetModuleFromIndexIfLoaded(CorSigUncompressData(pBuffer)) : this;
-
-    RETURN pBuffer;
-#else
-    *ppDefiningModule = NULL;
-    RETURN NULL;
-#endif // DACCESS_COMPILE
-}
-
-/*static*/
-PTR_Module Module::RestoreModulePointerIfLoaded(DPTR(RelativeFixupPointer<PTR_Module>) ppModule, Module *pContainingModule)
-{
-    CONTRACTL
-    {
-        NOTHROW;
-        GC_NOTRIGGER;
-        MODE_ANY;
-        FORBID_FAULT;
-        SUPPORTS_DAC;
-    }
-    CONTRACTL_END;
-
-    if (!ppModule->IsTagged(dac_cast<TADDR>(ppModule)))
-        return ppModule->GetValue(dac_cast<TADDR>(ppModule));
-
-#ifndef DACCESS_COMPILE
-    PTR_Module * ppValue = ppModule->GetValuePtr();
-
-    // Ensure that the compiler won't fetch the value twice
-    TADDR fixup = VolatileLoadWithoutBarrier((TADDR *)ppValue);
-
-    if (CORCOMPILE_IS_POINTER_TAGGED(fixup))
-    {
-
-#ifdef HOST_64BIT
-        CONSISTENCY_CHECK((CORCOMPILE_UNTAG_TOKEN(fixup)>>32) == 0);
-#endif
-
-        RVA fixupRva = (RVA) CORCOMPILE_UNTAG_TOKEN(fixup);
-
-        _ASSERTE((*pContainingModule->GetNativeFixupBlobData(fixupRva) & ~ENCODE_MODULE_OVERRIDE) == ENCODE_MODULE_HANDLE);
-
-        Module * pInfoModule;
-        PCCOR_SIGNATURE pBlobData = pContainingModule->GetEncodedSigIfLoaded(fixupRva, &pInfoModule);
-
-        if (pInfoModule)
-        {
-            *ppValue = pInfoModule;
-        }
-        return pInfoModule;
-    }
-    else
-    {
-        return PTR_Module(fixup);
-    }
-#else
-    DacNotImpl();
-    return NULL;
-#endif
-}
-
-#ifndef DACCESS_COMPILE
-
-/*static*/
-void Module::RestoreModulePointer(RelativeFixupPointer<PTR_Module> * ppModule, Module *pContainingModule)
-{
-    CONTRACTL
-    {
-        THROWS;
-        GC_TRIGGERS;
-        MODE_ANY;
-        INJECT_FAULT(COMPlusThrowOM());
-    }
-    CONTRACTL_END;
-
-    if (!ppModule->IsTagged((TADDR)ppModule))
-        return;
-
-    PTR_Module * ppValue = ppModule->GetValuePtr();
-
-    // Ensure that the compiler won't fetch the value twice
-    TADDR fixup = VolatileLoadWithoutBarrier((TADDR *)ppValue);
-
-    if (CORCOMPILE_IS_POINTER_TAGGED(fixup))
-    {
-#ifdef HOST_64BIT
-        CONSISTENCY_CHECK((CORCOMPILE_UNTAG_TOKEN(fixup)>>32) == 0);
-#endif
-
-        RVA fixupRva = (RVA) CORCOMPILE_UNTAG_TOKEN(fixup);
-
-        _ASSERTE((*pContainingModule->GetNativeFixupBlobData(fixupRva) & ~ENCODE_MODULE_OVERRIDE) == ENCODE_MODULE_HANDLE);
-
-        Module * pInfoModule;
-        PCCOR_SIGNATURE pBlobData = pContainingModule->GetEncodedSig(fixupRva, &pInfoModule);
-
-        *ppValue = pInfoModule;
-    }
-}
-
-/*static*/
-void Module::RestoreTypeHandlePointerRaw(TypeHandle *pHandle, Module* pContainingModule, ClassLoadLevel level)
-{
-    CONTRACTL
-    {
-        if (FORBIDGC_LOADER_USE_ENABLED()) NOTHROW; else THROWS;
-        if (FORBIDGC_LOADER_USE_ENABLED()) GC_NOTRIGGER; else GC_TRIGGERS;
-        if (FORBIDGC_LOADER_USE_ENABLED()) FORBID_FAULT; else {INJECT_FAULT(COMPlusThrowOM(););}
-        MODE_ANY;
-    }
-    CONTRACTL_END;
-
-#ifdef _DEBUG
-    if (pContainingModule != NULL)
-    {
-        Module * dbg_pZapModule = ExecutionManager::FindZapModule(dac_cast<TADDR>(pHandle));
-        _ASSERTE((dbg_pZapModule == NULL) || (pContainingModule == dbg_pZapModule));
-    }
-#endif //_DEBUG
-
-    TADDR fixup;
-
-    if (IS_ALIGNED(pHandle, sizeof(TypeHandle)))
-    {
-        // Ensure that the compiler won't fetch the value twice
-        fixup = VolatileLoadWithoutBarrier((TADDR *)pHandle);
-    }
-    else
-    {
-        // This is necessary to handle in-place fixups (see by FixupTypeHandlePointerInplace)
-        // in stubs-as-il signatures.
-
-        //
-        // protect this unaligned read with the Module Crst for the rare case that
-        // the TypeHandle to fixup is in a signature and unaligned.
-        //
-        if (NULL == pContainingModule)
-        {
-            pContainingModule = ExecutionManager::FindZapModule(dac_cast<TADDR>(pHandle));
-        }
-        CrstHolder ch(&pContainingModule->m_Crst);
-        fixup = *(TADDR UNALIGNED *)pHandle;
-    }
-
-    if (CORCOMPILE_IS_POINTER_TAGGED(fixup))
-    {
-#ifdef HOST_64BIT
-        CONSISTENCY_CHECK((CORCOMPILE_UNTAG_TOKEN(fixup)>>32) == 0);
-#endif
-
-        RVA fixupRva = (RVA) CORCOMPILE_UNTAG_TOKEN(fixup);
-
-        if (NULL == pContainingModule)
-        {
-            pContainingModule = ExecutionManager::FindZapModule(dac_cast<TADDR>(pHandle));
-        }
-        PREFIX_ASSUME(pContainingModule != NULL);
-
-        _ASSERTE((*pContainingModule->GetNativeFixupBlobData(fixupRva) & ~ENCODE_MODULE_OVERRIDE) == ENCODE_TYPE_HANDLE);
-
-        Module * pInfoModule;
-        PCCOR_SIGNATURE pBlobData = pContainingModule->GetEncodedSig(fixupRva, &pInfoModule);
-
-        TypeHandle thResolved = ZapSig::DecodeType(pContainingModule,
-                                                           pInfoModule,
-                                                           pBlobData,
-                                                           level);
-        if (IS_ALIGNED(pHandle, sizeof(TypeHandle)))
-        {
-            *pHandle = thResolved;
-        }
-        else
-        {
-            //
-            // protect this unaligned write with the Module Crst for the rare case that
-            // the TypeHandle to fixup is in a signature and unaligned.
-            //
-            CrstHolder ch(&pContainingModule->m_Crst);
-            *(TypeHandle UNALIGNED *)pHandle = thResolved;
-        }
-    }
-    else if (fixup != NULL)
-    {
-        ClassLoader::EnsureLoaded(TypeHandle::FromTAddr(fixup), level);
-    }
-}
-
-/*static*/
-void Module::RestoreTypeHandlePointer(FixupPointer<TypeHandle> * pHandle,
-                                      Module *pContainingModule,
-                                      ClassLoadLevel level)
-{
-    CONTRACTL
-    {
-        THROWS;
-        GC_TRIGGERS;
-        MODE_ANY;
-    }
-    CONTRACTL_END;
-
-    if (pHandle->IsNull())
-        return;
-
-    if (pHandle->IsTagged())
-    {
-        RestoreTypeHandlePointerRaw(pHandle->GetValuePtr(), pContainingModule, level);
-    }
-    else
-    {
-        ClassLoader::EnsureLoaded(pHandle->GetValue(), level);
-    }
-}
-
-/*static*/
-void Module::RestoreTypeHandlePointer(RelativeFixupPointer<TypeHandle> * pHandle,
-                                      Module *pContainingModule,
-                                      ClassLoadLevel level)
-{
-    CONTRACTL
-    {
-        THROWS;
-        GC_TRIGGERS;
-        MODE_ANY;
-    }
-    CONTRACTL_END;
-
-    if (pHandle->IsNull())
-        return;
-
-    if (pHandle->IsTagged((TADDR)pHandle))
-    {
-        RestoreTypeHandlePointerRaw(pHandle->GetValuePtr(), pContainingModule, level);
-    }
-    else
-    {
-        ClassLoader::EnsureLoaded(pHandle->GetValue((TADDR)pHandle), level);
-    }
-}
-
-/*static*/
-void Module::RestoreMethodDescPointerRaw(PTR_MethodDesc * ppMD, Module *pContainingModule, ClassLoadLevel level)
-{
-    CONTRACTL
-    {
-        THROWS;
-        GC_TRIGGERS;
-        MODE_ANY;
-    }
-    CONTRACTL_END;
-
-    // Ensure that the compiler won't fetch the value twice
-    TADDR fixup = VolatileLoadWithoutBarrier((TADDR *)ppMD);
-
-#ifdef _DEBUG
-    if (pContainingModule != NULL)
-    {
-        Module * dbg_pZapModule = ExecutionManager::FindZapModule(dac_cast<TADDR>(ppMD));
-        _ASSERTE((dbg_pZapModule == NULL) || (pContainingModule == dbg_pZapModule));
-    }
-#endif //_DEBUG
-
-    if (CORCOMPILE_IS_POINTER_TAGGED(fixup))
-    {
-        GCX_PREEMP();
-
-#ifdef HOST_64BIT
-        CONSISTENCY_CHECK((CORCOMPILE_UNTAG_TOKEN(fixup)>>32) == 0);
-#endif
-
-        RVA fixupRva = (RVA) CORCOMPILE_UNTAG_TOKEN(fixup);
-
-        if (pContainingModule == NULL)
-            pContainingModule = ExecutionManager::FindZapModule(dac_cast<TADDR>(ppMD));
-        PREFIX_ASSUME(pContainingModule != NULL);
-
-        _ASSERTE((*pContainingModule->GetNativeFixupBlobData(fixupRva) & ~ENCODE_MODULE_OVERRIDE) == ENCODE_METHOD_HANDLE);
-
-        Module * pInfoModule;
-        PCCOR_SIGNATURE pBlobData = pContainingModule->GetEncodedSig(fixupRva, &pInfoModule);
-
-        *ppMD =  ZapSig::DecodeMethod(pContainingModule,
-                                      pInfoModule,
-                                      pBlobData);
-    }
-    else if (*ppMD) {
-        (*ppMD)->CheckRestore(level);
-    }
-}
-
-/*static*/
-void Module::RestoreMethodDescPointer(FixupPointer<PTR_MethodDesc> * ppMD,
-                                      Module *pContainingModule,
-                                      ClassLoadLevel level)
-{
-    CONTRACTL
-    {
-        THROWS;
-        GC_TRIGGERS;
-        MODE_ANY;
-    }
-    CONTRACTL_END;
-
-    if (ppMD->IsNull())
-        return;
-
-    if (ppMD->IsTagged())
-    {
-        RestoreMethodDescPointerRaw(ppMD->GetValuePtr(), pContainingModule, level);
-    }
-    else
-    {
-        ppMD->GetValue()->CheckRestore(level);
-    }
-}
-
-/*static*/
-void Module::RestoreMethodDescPointer(RelativeFixupPointer<PTR_MethodDesc> * ppMD,
-                                      Module *pContainingModule,
-                                      ClassLoadLevel level)
-{
-    CONTRACTL
-    {
-        THROWS;
-        GC_TRIGGERS;
-        MODE_ANY;
-    }
-    CONTRACTL_END;
-
-    if (ppMD->IsNull())
-        return;
-
-    if (ppMD->IsTagged((TADDR)ppMD))
-    {
-        RestoreMethodDescPointerRaw(ppMD->GetValuePtr(), pContainingModule, level);
-    }
-    else
-    {
-        ppMD->GetValue((TADDR)ppMD)->CheckRestore(level);
-    }
-}
-
-/*static*/
-void Module::RestoreFieldDescPointer(RelativeFixupPointer<PTR_FieldDesc> * ppFD)
-{
-    CONTRACTL
-    {
-        THROWS;
-        GC_TRIGGERS;
-        MODE_ANY;
-    }
-    CONTRACTL_END;
-
-    if (!ppFD->IsTagged())
-        return;
-
-    PTR_FieldDesc * ppValue = ppFD->GetValuePtr();
-
-    // Ensure that the compiler won't fetch the value twice
-    TADDR fixup = VolatileLoadWithoutBarrier((TADDR *)ppValue);
-
-    if (CORCOMPILE_IS_POINTER_TAGGED(fixup))
-    {
-#ifdef HOST_64BIT
-        CONSISTENCY_CHECK((CORCOMPILE_UNTAG_TOKEN(fixup)>>32) == 0);
-#endif
-
-        Module * pContainingModule = ExecutionManager::FindZapModule((TADDR)ppValue);
-        PREFIX_ASSUME(pContainingModule != NULL);
-
-        RVA fixupRva = (RVA) CORCOMPILE_UNTAG_TOKEN(fixup);
-
-        _ASSERTE((*pContainingModule->GetNativeFixupBlobData(fixupRva) & ~ENCODE_MODULE_OVERRIDE) == ENCODE_FIELD_HANDLE);
-
-        Module * pInfoModule;
-        PCCOR_SIGNATURE pBlobData = pContainingModule->GetEncodedSig(fixupRva, &pInfoModule);
-
-        *ppValue =  ZapSig::DecodeField(pContainingModule,
-                                        pInfoModule,
-                                        pBlobData);
-    }
-}
-
-
-//-----------------------------------------------------------------------------
-
-#if 0
-
-        This diagram illustrates the layout of fixups in the ngen image.
-        This is the case where function foo2 has a class-restore fixup
-        for class C1 in b.dll.
-
-                                  zapBase+curTableVA+rva /         FixupList (see Fixup Encoding below)
-                                  m_pFixupBlobs
-                                                            +-------------------+
-                  pEntry->VA +--------------------+         |     non-NULL      | foo1
-                             |Handles             |         +-------------------+
-ZapHeader.ImportTable        |                    |         |     non-NULL      |
-                             |                    |         +-------------------+
-   +------------+            +--------------------+         |     non-NULL      |
-   |a.dll       |            |Class cctors        |<---+    +-------------------+
-   |            |            |                    |     \   |         0         |
-   |            |     p->VA/ |                    |<---+ \  +===================+
-   |            |      blobs +--------------------+     \ +-------non-NULL      | foo2
-   +------------+            |Class restore       |      \  +-------------------+
-   |b.dll       |            |                    |       +-------non-NULL      |
-   |            |            |                    |         +-------------------+
-   |  token_C1  |<--------------blob(=>fixedUp/0) |<--pBlob--------index        |
-   |            | \          |                    |         +-------------------+
-   |            |  \         +--------------------+         |     non-NULL      |
-   |            |   \        |                    |         +-------------------+
-   |            |    \       |        .           |         |         0         |
-   |            |     \      |        .           |         +===================+
-   +------------+      \     |        .           |         |         0         | foo3
-                        \    |                    |         +===================+
-                         \   +--------------------+         |     non-NULL      | foo4
-                          \  |Various fixups that |         +-------------------+
-                           \ |need too happen     |         |         0         |
-                            \|                    |         +===================+
-                             |(CorCompileTokenTable)
-                             |                    |
-               pEntryEnd->VA +--------------------+
-
-
-
-#endif // 0
-
-#endif
-#endif
-
-#ifndef DACCESS_COMPILE
-//-----------------------------------------------------------------------------
-
-void Module::RunEagerFixups()
-{
-    STANDARD_VM_CONTRACT;
-
-    COUNT_T nSections;
-    PTR_CORCOMPILE_IMPORT_SECTION pSections = GetImportSections(&nSections);
+    COUNT_T nSections;
+    PTR_CORCOMPILE_IMPORT_SECTION pSections = GetImportSections(&nSections);
 
     if (nSections == 0)
         return;
@@ -12805,276 +9033,6 @@ VASigCookie *Module::GetVASigCookie(Signature vaSignature)
     RETURN pCookie;
 }
 
-// ===========================================================================
-// LookupMap
-// ===========================================================================
-#ifdef FEATURE_NATIVE_IMAGE_GENERATION
-
-int __cdecl LookupMapBase::HotItem::Cmp(const void* a_, const void* b_)
-{
-    LIMITED_METHOD_CONTRACT;
-    const HotItem *a = (const HotItem *)a_;
-    const HotItem *b = (const HotItem *)b_;
-
-    if (a->rid < b->rid)
-        return -1;
-    else if (a->rid > b->rid)
-        return 1;
-    else
-        return 0;
-}
-
-void LookupMapBase::CreateHotItemList(DataImage *image, CorProfileData *profileData, int table, BOOL fSkipNullEntries /*= FALSE*/)
-{
-    STANDARD_VM_CONTRACT;
-    _ASSERTE(!MapIsCompressed());
-
-    if (profileData)
-    {
-        DWORD numInTokenList = profileData->GetHotTokens(table, 1<<RidMap, 1<<RidMap, NULL, 0);
-
-        if (numInTokenList > 0)
-        {
-            HotItem *itemList = (HotItem*)(void*)image->GetModule()->GetLoaderAllocator()->GetHighFrequencyHeap()->AllocMem(S_SIZE_T(sizeof(HotItem)) * S_SIZE_T(numInTokenList));
-            mdToken *tokenList = (mdToken*)(void*)image->GetModule()->GetLoaderAllocator()->GetHighFrequencyHeap()->AllocMem(S_SIZE_T(sizeof(mdToken)) * S_SIZE_T(numInTokenList));
-
-            profileData->GetHotTokens(table, 1<<RidMap, 1<<RidMap, tokenList, numInTokenList);
-            DWORD numItems = 0;
-            for (DWORD i = 0; i < numInTokenList; i++)
-            {
-                DWORD rid = RidFromToken(tokenList[i]);
-                TADDR value = RelativePointer<TADDR>::GetValueMaybeNullAtPtr(dac_cast<TADDR>(GetElementPtr(RidFromToken(tokenList[i]))));
-                if (!fSkipNullEntries || value != NULL)
-                {
-                    itemList[numItems].rid = rid;
-                    itemList[numItems].value = value;
-                    ++numItems;
-                }
-            }
-
-            if (numItems > 0)
-            {
-                qsort(itemList,          // start of array
-                      numItems,          // array size in elements
-                      sizeof(HotItem),      // element size in bytes
-                      HotItem::Cmp);        // comparer function
-
-                // Eliminate any duplicates in the list. Due to the qsort, they must be adjacent now.
-                // We do this by walking the array and copying entries that are not duplicates of the previous one.
-                // We can start the loop at +1, because 0 is not a duplicate of the previous entry, and does not
-                // need to be copied either.
-                DWORD j = 1;
-                for (DWORD i = 1; i < numItems; i++)
-                {
-                    if (itemList[i].rid != itemList[i-1].rid)
-                    {
-                        itemList[j].rid   = itemList[i].rid;
-                        itemList[j].value = itemList[i].value;
-                        j++;
-                    }
-                }
-                _ASSERTE(j <= numItems);
-                numItems = j;
-
-                // We have treated the values as normal TADDRs to let qsort move them around freely.
-                // Fix them up to be the relative pointers now.
-                for (DWORD ii = 0; ii < numItems; ii++)
-                {
-                    if (itemList[ii].value != NULL)
-                    {
-                        RelativePointer<TADDR> *pRelPtr = (RelativePointer<TADDR> *)&itemList[ii].value;
-                        pRelPtr->SetValueMaybeNull(itemList[ii].value);
-                    }
-                }
-
-                if (itemList != NULL)
-                    image->StoreStructure(itemList, sizeof(HotItem)*numItems,
-                                          DataImage::ITEM_RID_MAP_HOT);
-
-                hotItemList = itemList;
-                dwNumHotItems = numItems;
-            }
-        }
-    }
-}
-
-void LookupMapBase::Save(DataImage *image, DataImage::ItemKind kind, CorProfileData *profileData, int table, BOOL fCopyValues /*= FALSE*/)
-{
-    STANDARD_VM_CONTRACT;
-
-    // the table index that comes in is a token mask, the upper 8 bits are the table type for the tokens, that's all we want
-    table >>= 24;
-
-    dwNumHotItems = 0;
-    hotItemList = NULL;
-
-    if (table != 0)
-    {
-        // Because we use the same IBC encoding to record a touch to the m_GenericTypeDefToCanonMethodTableMap as
-        // to the m_TypeDefToMethodTableMap, the hot items we get in both will be the union of the touches.  This limitation
-        // in the IBC infrastructure does not hurt us much because touching an entry for a generic type in one map often if
-        // not always implies touching the corresponding entry in the other.  But when saving the GENERICTYPEDEF_MAP it
-        // does mean that we need to be prepared to see "hot" items whose data is NULL in this map (specifically, the non-
-        // generic types).  We don't want the hot list to be unnecessarily big with these entries, so tell CreateHotItemList to
-        // skip them.
-        BOOL fSkipNullEntries = (kind == DataImage::ITEM_GENERICTYPEDEF_MAP);
-        CreateHotItemList(image, profileData, table, fSkipNullEntries);
-    }
-
-    // Determine whether we want to compress this lookup map (to improve density of cold pages in the map on
-    // hot item cache misses). We only enable this optimization for the TypeDefToMethodTable, the
-    // GenericTypeDefToCanonMethodTable, and the MethodDefToDesc maps since (a) they're the largest and
-    // as a result reap the most space savings and (b) these maps are fully populated in an ngen image and immutable
-    // at runtime, something that's important when dealing with a compressed version of the table.
-    if (kind == DataImage::ITEM_TYPEDEF_MAP || kind == DataImage::ITEM_GENERICTYPEDEF_MAP || kind == DataImage::ITEM_METHODDEF_MAP)
-    {
-        // The bulk of the compression work is done in the later stages of ngen image generation (since it
-        // relies on knowing the final RVAs of each value stored in the table). So we create a specialzed
-        // ZapNode that knows how to perform the compression for us.
-        image->StoreCompressedLayoutMap(this, DataImage::ITEM_COMPRESSED_MAP);
-
-        // We need to know we decided to compress during the Fixup stage but the table kind is not available
-        // there. So we use the cIndexEntryBits field as a flag (this will be initialized to zero and is only
-        // set to a meaningful value near the end of ngen image generation, during the compression of the
-        // table itself).
-        cIndexEntryBits = 1;
-
-        // The ZapNode we allocated above takes care of all the rest of the processing for this map, so we're
-        // done here.
-        return;
-    }
-
-    SaveUncompressedMap(image, kind, fCopyValues);
-}
-
-void LookupMapBase::SaveUncompressedMap(DataImage *image, DataImage::ItemKind kind, BOOL fCopyValues /*= FALSE*/)
-{
-    STANDARD_VM_CONTRACT;
-
-    // We should only be calling this once per map
-    _ASSERTE(!image->IsStored(pTable));
-
-    //
-    // We will only store one (big) node instead of the full list,
-    // and make the one node large enough to fit all the RIDs
-    //
-
-    ZapStoredStructure * pTableNode = image->StoreStructure(NULL, GetSize() * sizeof(TADDR), kind);
-
-    LookupMapBase *map = this;
-    DWORD offsetIntoCombo = 0;
-    while (map != NULL)
-    {
-        DWORD len = map->dwCount * sizeof(void*);
-
-        if (fCopyValues)
-            image->CopyDataToOffset(pTableNode, offsetIntoCombo, map->pTable, len);
-
-        image->BindPointer(map->pTable,pTableNode,offsetIntoCombo);
-        offsetIntoCombo += len;
-        map = map->pNext;
-    }
-}
-
-void LookupMapBase::ConvertSavedMapToUncompressed(DataImage *image, DataImage::ItemKind kind)
-{
-    STANDARD_VM_CONTRACT;
-
-    // Check whether we decided to compress this map (see Save() above).
-    if (cIndexEntryBits == 0)
-        return;
-
-    cIndexEntryBits = 0;
-    SaveUncompressedMap(image, kind);
-}
-
-void LookupMapBase::Fixup(DataImage *image, BOOL fFixupEntries /*=TRUE*/)
-{
-    STANDARD_VM_CONTRACT;
-
-    if (hotItemList != NULL)
-        image->FixupPointerField(this, offsetof(LookupMapBase, hotItemList));
-
-    // Find the biggest RID supported by the entire list of LookupMaps.
-    // We will only store one LookupMap node instead of the full list,
-    // and make it big enough to fit all RIDs.
-    *(DWORD *)image->GetImagePointer(this, offsetof(LookupMapBase, dwCount)) = GetSize();
-
-    // Persist the supportedFlags that this particular instance was created with.
-    *(TADDR *)image->GetImagePointer(this, offsetof(LookupMapBase, supportedFlags)) = supportedFlags;
-
-    image->ZeroPointerField(this, offsetof(LookupMapBase, pNext));
-
-    // Check whether we've decided to compress this map (see Save() above).
-    if (cIndexEntryBits == 1)
-    {
-        // In the compressed case most of the Fixup logic is performed by the specialized ZapNode we allocated
-        // during Save(). But we still have to record fixups for any hot items we've cached (these aren't
-        // compressed).
-        for (DWORD i = 0; i < dwNumHotItems; i++)
-        {
-            TADDR *pHotValueLoc = &hotItemList[i].value;
-            TADDR pHotValue = RelativePointer<TADDR>::GetValueMaybeNullAtPtr((TADDR)pHotValueLoc);
-            TADDR flags = pHotValue & supportedFlags;
-            pHotValue -= flags;
-
-            if (image->IsStored((PVOID)pHotValue))
-            {
-                image->FixupField(hotItemList,
-                                  (BYTE *)pHotValueLoc - (BYTE *)hotItemList,
-                                  (PVOID)pHotValue, flags, IMAGE_REL_BASED_RelativePointer);
-            }
-            else
-            {
-                image->ZeroPointerField(hotItemList, (BYTE *)pHotValueLoc - (BYTE *)hotItemList);
-            }
-        }
-
-        // The ZapNode will handle everything else so we're done.
-        return;
-    }
-
-    // Note that the caller is responsible for calling FixupPointerField()
-    // or zeroing out the contents of pTable as appropriate
-    image->FixupPointerField(this, offsetof(LookupMapBase, pTable));
-
-    if (fFixupEntries)
-    {
-        LookupMap<PVOID>::Iterator iter((LookupMap<PVOID> *)this);
-        DWORD rid = 0;
-
-        while (iter.Next())
-        {
-            TADDR flags;
-            PVOID p = iter.GetElementAndFlags(&flags);
-            PTR_TADDR hotItemValuePtr = FindHotItemValuePtr(rid);
-
-            if (image->IsStored(p))
-            {
-                image->FixupField(pTable, rid * sizeof(TADDR),
-                    p, flags, IMAGE_REL_BASED_RelativePointer);
-
-                // In case this item is also in the hot item subtable, fix it up there as well
-                if (hotItemValuePtr != NULL)
-                    image->FixupField(hotItemList,
-                        (BYTE *)hotItemValuePtr - (BYTE *)hotItemList,
-                        p, flags, IMAGE_REL_BASED_RelativePointer);
-            }
-            else
-            {
-                image->ZeroPointerField(pTable, rid * sizeof(TADDR));
-                // In case this item is also in the hot item subtable, zero it there as well
-                if (hotItemValuePtr != NULL)
-                    image->ZeroPointerField(hotItemList,
-                        (BYTE *)hotItemValuePtr - (BYTE *)hotItemList);
-            }
-
-            rid++;
-        }
-    }
-}
-#endif // FEATURE_NATIVE_IMAGE_GENERATION
-
 #endif // !DACCESS_COMPILE
 
 #ifdef DACCESS_COMPILE
index fc8d76e..bebb24e 100644 (file)
 
 #include "wellknownattributes.h"
 
-#ifdef FEATURE_PREJIT
-#include "dataimage.h"
-#endif // FEATURE_PREJIT
-
 #ifdef FEATURE_READYTORUN
 #include "readytoruninfo.h"
 #endif
@@ -222,58 +218,6 @@ struct LookupMapBase
     // Set of flags that the map supports writing on top of the data value
     TADDR               supportedFlags;
 
-#ifdef FEATURE_PREJIT
-    struct  HotItem
-    {
-        DWORD   rid;
-        TADDR   value;
-        static int __cdecl Cmp(const void* a_, const void* b_);
-    };
-    DWORD               dwNumHotItems;
-    ArrayDPTR(HotItem)  hotItemList;
-    PTR_TADDR FindHotItemValuePtr(DWORD rid);
-
-    //
-    // Compressed map support
-    //
-    PTR_CBYTE           pIndex;             // Bookmark for every kLookupMapIndexStride'th entry in the table
-    DWORD               cIndexEntryBits;    // Number of bits in every index entry
-    DWORD               cbTable;            // Number of bytes of compressed table data at pTable
-    DWORD               cbIndex;            // Number of bytes of index data at pIndex
-    BYTE                rgEncodingLengths[kLookupMapLengthEntries]; // Table of delta encoding lengths for
-                                                                    // compressed values
-
-    // Returns true if this map instance is compressed (this can only happen at runtime when running against
-    // an ngen image). Currently and for the forseeable future only TypeDefToMethodTable and MethodDefToDesc
-    // tables can be compressed.
-    bool MapIsCompressed()
-    {
-        LIMITED_METHOD_DAC_CONTRACT;
-        return pIndex != NULL;
-    }
-
-protected:
-    // Internal routine used to iterate though one entry in the compressed table.
-    INT32 GetNextCompressedEntry(BitStreamReader *pTableStream, INT32 iLastValue);
-
-public:
-    // Public method used to retrieve the full value (non-RVA) of a compressed table entry.
-    TADDR GetValueFromCompressedMap(DWORD rid);
-
-#ifndef DACCESS_COMPILE
-    void CreateHotItemList(DataImage *image, CorProfileData *profileData, int table, BOOL fSkipNullEntries = FALSE);
-    void Save(DataImage *image, DataImage::ItemKind kind, CorProfileData *profileData, int table, BOOL fCopyValues = FALSE);
-    void SaveUncompressedMap(DataImage *image, DataImage::ItemKind kind, BOOL fCopyValues = FALSE);
-    void ConvertSavedMapToUncompressed(DataImage *image, DataImage::ItemKind kind);
-    void Fixup(DataImage *image, BOOL fFixupEntries = TRUE);
-#endif // !DACCESS_COMPILE
-
-#ifdef _DEBUG
-    void    CheckConsistentHotItemList();
-#endif
-
-#endif // FEATURE_PREJIT
-
 #ifdef DACCESS_COMPILE
     void EnumMemoryRegions(CLRDataEnumMemoryFlags flags,
                            bool enumThis);
@@ -677,7 +621,6 @@ struct ModuleCtorInfo
 
 #ifdef FEATURE_PREJIT
 
-    void AddElement(MethodTable *pMethodTable);
     void Save(DataImage *image, CorProfileData *profileData);
     void Fixup(DataImage *image);
 
@@ -1170,29 +1113,6 @@ public:
     void EnumMemoryRegionsForEntry(GuidToMethodTableEntry *pEntry, CLRDataEnumMemoryFlags flags)
     { SUPPORTS_DAC; }
 #endif // DACCESS_COMPILE
-
-#if defined(FEATURE_PREJIT) && !defined(DACCESS_COMPILE)
-
-public:
-    void Save(DataImage *pImage, CorProfileData *pProfileData);
-    void Fixup(DataImage *pImage);
-
-private:
-    // We save all entries
-    bool ShouldSave(DataImage *pImage, GuidToMethodTableEntry *pEntry)
-    { LIMITED_METHOD_CONTRACT; return true; }
-
-    bool IsHotEntry(GuidToMethodTableEntry *pEntry, CorProfileData *pProfileData)
-    { LIMITED_METHOD_CONTRACT; return false; }
-
-    bool SaveEntry(DataImage *pImage, CorProfileData *pProfileData,
-                        GuidToMethodTableEntry *pOldEntry, GuidToMethodTableEntry *pNewEntry,
-                        EntryMappingTable *pMap);
-
-    void FixupEntry(DataImage *pImage, GuidToMethodTableEntry *pEntry, void *pFixupBase, DWORD cbFixupOffset);
-
-#endif // FEATURE_PREJIT && !DACCESS_COMPILE
-
 };
 
 #endif // FEATURE_COMINTEROP
@@ -1245,46 +1165,6 @@ public:
     { SUPPORTS_DAC; }
 
 #endif
-
-#if defined(FEATURE_PREJIT) && !defined(DACCESS_COMPILE)
-
-    void Fixup(DataImage *pImage)
-    {
-        WRAPPER_NO_CONTRACT;
-        BaseFixup(pImage);
-    }
-
-    void Save(DataImage *pImage, CorProfileData *pProfileData);
-
-
-private:
-    bool ShouldSave(DataImage *pImage, MemberRefToDescHashEntry *pEntry)
-    {
-        return IsHotEntry(pEntry, NULL);
-    }
-
-    bool IsHotEntry(MemberRefToDescHashEntry *pEntry, CorProfileData *pProfileData) // yes according to IBC data
-    {
-               LIMITED_METHOD_CONTRACT;
-
-        _ASSERTE(pEntry != NULL);
-               // Low order bit of data field indicates a hot entry.
-               return (pEntry->m_value & 0x1) != 0;
-
-    }
-
-
-    bool SaveEntry(DataImage *pImage, CorProfileData *pProfileData,
-                        MemberRefToDescHashEntry *pOldEntry, MemberRefToDescHashEntry *pNewEntry,
-                        EntryMappingTable *pMap)
-    {
-        //The entries are mutable
-        return FALSE;
-    }
-
-    void FixupEntry(DataImage *pImage, MemberRefToDescHashEntry *pEntry, void *pFixupBase, DWORD cbFixupOffset);
-
-#endif
 };
 
 #ifdef FEATURE_READYTORUN
@@ -2184,10 +2064,6 @@ public:
 
     TypeHandle LookupTypeRef(mdTypeRef token);
 
-    mdTypeRef LookupTypeRefByMethodTable(MethodTable *pMT);
-
-    mdMemberRef LookupMemberRefByMethodDesc(MethodDesc *pMD);
-
 #ifndef DACCESS_COMPILE
     //
     // Increase the size of the TypeRef-to-MethodTable LookupMap to make sure the specified token
@@ -2399,10 +2275,6 @@ public:
 
 #endif // !DACCESS_COMPILE
 
-#ifdef FEATURE_PREJIT
-    void FinalizeLookupMapsPreSave(DataImage *image);
-#endif
-
     DWORD GetAssemblyRefMax() {LIMITED_METHOD_CONTRACT;  return m_ManifestModuleReferencesMap.GetSize(); }
 
     MethodDesc *FindMethodThrowing(mdToken pMethod);
@@ -2412,9 +2284,6 @@ public:
     HRESULT GetPropertyInfoForMethodDef(mdMethodDef md, mdProperty *ppd, LPCSTR *pName, ULONG *pSemantic);
 
     #define NUM_PROPERTY_SET_HASHES 4
-#ifdef FEATURE_PREJIT
-    void PrecomputeMatchingProperties(DataImage *image);
-#endif
     BOOL MightContainMatchingProperty(mdProperty tkProperty, ULONG nameHash);
 
 private:
index 5c5004f..1ef7fd3 100644 (file)
@@ -2743,372 +2743,8 @@ WORD SparseVTableMap::GetNumVTableSlots()
     return m_VTSlot;
 }
 
-#ifdef FEATURE_NATIVE_IMAGE_GENERATION
-//*******************************************************************************
-void SparseVTableMap::Save(DataImage *image)
-{
-    STANDARD_VM_CONTRACT;
-
-    image->StoreStructure(this, sizeof(SparseVTableMap),
-                                    DataImage::ITEM_SPARSE_VTABLE_MAP_TABLE);
-
-    // Trim unused portion of the table
-    m_Allocated = m_MapEntries;
-
-    image->StoreInternedStructure(m_MapList, m_Allocated * sizeof(Entry),
-                                    DataImage::ITEM_SPARSE_VTABLE_MAP_ENTRIES);
-}
-
-//*******************************************************************************
-void SparseVTableMap::Fixup(DataImage *image)
-{
-    STANDARD_VM_CONTRACT;
-
-    image->FixupPointerField(this, offsetof(SparseVTableMap, m_MapList));
-}
-#endif //FEATURE_NATIVE_IMAGE_GENERATION
 #endif //FEATURE_COMINTEROP
 
-#ifdef FEATURE_NATIVE_IMAGE_GENERATION
-
-//*******************************************************************************
-void EEClass::Save(DataImage *image, MethodTable *pMT)
-{
-    CONTRACTL
-    {
-        STANDARD_VM_CHECK;
-        PRECONDITION(this == pMT->GetClass());
-        PRECONDITION(pMT->IsCanonicalMethodTable());
-        PRECONDITION(pMT->IsFullyLoaded());
-        PRECONDITION(!image->IsStored(this));
-        PRECONDITION(image->GetModule()->GetAssembly() ==
-                 GetAppDomain()->ToCompilationDomain()->GetTargetAssembly());
-    }
-    CONTRACTL_END;
-
-    LOG((LF_ZAP, LL_INFO10000, "EEClass::Save %s (%p)\n", m_szDebugClassName, this));
-
-    m_fFieldsArePacked = GetPackedFields()->PackFields();
-
-    DWORD cbSize = GetSize();
-
-    // ***************************************************************
-    // Only put new actions in this function if they really relate to EEClass
-    // rather than MethodTable.  For example, if you need to allocate
-    // a per-type entry in some table in the NGEN image, then you will probably
-    // need to allocate one such entry per MethodTable, e.g. per generic
-    // instantiation.  You probably don't want to allocate one that is common
-    // to a group of shared instantiations.
-    // ***************************************************************
-
-    DataImage::ItemKind item =
-        (!pMT->IsGenericTypeDefinition() && pMT->ContainsGenericVariables())
-        ? DataImage::ITEM_EECLASS_COLD
-        // Until we get all the access paths for generics tidied up, many paths touch the EEClass, e.g. GetInstantiation()
-        : pMT->HasInstantiation()
-        ? DataImage::ITEM_EECLASS_WARM
-        : DataImage::ITEM_EECLASS;
-
-    // Save optional fields if we have any.
-    if (HasOptionalFields())
-        image->StoreStructure(GetOptionalFields(),
-                              sizeof(EEClassOptionalFields),
-                              item);
-
-#ifdef _DEBUG
-    if (!image->IsStored(m_szDebugClassName))
-        image->StoreStructure(m_szDebugClassName, (ULONG)(strlen(m_szDebugClassName)+1),
-                              DataImage::ITEM_DEBUG,
-                              1);
-#endif // _DEBUG
-
-#ifdef FEATURE_COMINTEROP
-    if (GetSparseCOMInteropVTableMap() != NULL)
-        GetSparseCOMInteropVTableMap()->Save(image);
-#endif // FEATURE_COMINTEROP
-
-    //
-    // Save MethodDescs
-    //
-
-    MethodDescChunk *chunk = GetChunks();
-    if (chunk != NULL)
-    {
-        MethodDesc::SaveChunk methodDescSaveChunk(image);
-
-        MethodTable::IntroducedMethodIterator it(pMT, TRUE);
-        for (; it.IsValid(); it.Next())
-        {
-            MethodDesc * pMD = it.GetMethodDesc();
-
-            // Do not save IL stubs that we have failed to generate code for
-            if (pMD->IsILStub() && image->GetCodeAddress(pMD) == NULL)
-                continue;
-
-            methodDescSaveChunk.Append(pMD);
-        }
-
-        ZapStoredStructure * pChunksNode = methodDescSaveChunk.Save();
-        if (pChunksNode != NULL)
-            image->BindPointer(chunk, pChunksNode, 0);
-
-    }
-
-    //
-    // Save FieldDescs
-    //
-
-    SIZE_T fieldCount = FieldDescListSize(pMT);
-
-    if (fieldCount != 0)
-    {
-        FieldDesc *pFDStart = GetFieldDescList();
-        FieldDesc *pFDEnd = pFDStart + fieldCount;
-
-        FieldDesc *pFD = pFDStart;
-        while (pFD < pFDEnd)
-        {
-            pFD->PrecomputeNameHash();
-            pFD++;
-        }
-
-        ZapStoredStructure * pFDNode = image->StoreStructure(pFDStart, (ULONG)(fieldCount * sizeof(FieldDesc)),
-                                        DataImage::ITEM_FIELD_DESC_LIST);
-
-        pFD = pFDStart;
-        while (pFD < pFDEnd)
-        {
-            pFD->SaveContents(image);
-            if (pFD != pFDStart)
-                image->BindPointer(pFD, pFDNode, (BYTE *)pFD - (BYTE *)pFDStart);
-            pFD++;
-        }
-    }
-
-    // Save dictionary layout information
-    DictionaryLayout *pDictLayout = GetDictionaryLayout();
-    if (pMT->IsSharedByGenericInstantiations() && pDictLayout != NULL)
-    {
-        pDictLayout->Save(image);
-        LOG((LF_ZAP, LL_INFO10000, "ZAP: dictionary for %s has %d slots used out of possible %d\n", m_szDebugClassName,
-             pDictLayout->GetNumUsedSlots(), pDictLayout->GetMaxSlots()));
-    }
-
-    if (GetVarianceInfo() != NULL)
-        image->StoreInternedStructure(GetVarianceInfo(),
-                              pMT->GetNumGenericArgs(),
-                              DataImage::ITEM_CLASS_VARIANCE_INFO);
-
-    image->StoreStructure(this, cbSize, item);
-
-    if (pMT->IsInterface())
-    {
-        GUID dummy;
-        if (SUCCEEDED(pMT->GetGuidNoThrow(&dummy, TRUE, FALSE)))
-        {
-            GuidInfo* pGuidInfo = GetGuidInfo();
-            _ASSERTE(pGuidInfo != NULL);
-
-            image->StoreStructure(pGuidInfo, sizeof(GuidInfo),
-                                    DataImage::ITEM_GUID_INFO);
-        }
-        else
-        {
-            // make sure we don't store a GUID_NULL guid in the NGEN image
-            // instead we'll compute the GUID at runtime, and throw, if appropriate
-            m_pGuidInfo.SetValueMaybeNull(NULL);
-        }
-    }
-
-#ifdef FEATURE_COMINTEROP
-    if (IsDelegate())
-    {
-        DelegateEEClass *pDelegateClass = (DelegateEEClass *)this;
-        ComPlusCallInfo *pComInfo = pDelegateClass->m_pComPlusCallInfo;
-
-        if (pComInfo != NULL && pComInfo->ShouldSave(image))
-        {
-            image->StoreStructure(pDelegateClass->m_pComPlusCallInfo,
-                                  sizeof(ComPlusCallInfo),
-                                  item);
-        }
-    }
-#endif // FEATURE_COMINTEROP
-
-    LOG((LF_ZAP, LL_INFO10000, "EEClass::Save %s (%p) complete.\n", m_szDebugClassName, this));
-}
-
-//*******************************************************************************
-DWORD EEClass::FieldDescListSize(MethodTable * pMT)
-{
-    LIMITED_METHOD_CONTRACT;
-
-    EEClass * pClass = pMT->GetClass();
-    DWORD fieldCount = pClass->GetNumInstanceFields() + pClass->GetNumStaticFields();
-
-    MethodTable * pParentMT = pMT->GetParentMethodTable();
-    if (pParentMT != NULL)
-        fieldCount -= pParentMT->GetNumInstanceFields();
-    return fieldCount;
-}
-
-//*******************************************************************************
-void EEClass::Fixup(DataImage *image, MethodTable *pMT)
-{
-    CONTRACTL
-    {
-        STANDARD_VM_CHECK;
-        PRECONDITION(this == pMT->GetClass());
-        PRECONDITION(pMT->IsCanonicalMethodTable());
-        PRECONDITION(pMT->IsFullyLoaded());
-        PRECONDITION(image->IsStored(this));
-    }
-    CONTRACTL_END;
-
-    LOG((LF_ZAP, LL_INFO10000, "EEClass::Fixup %s (%p)\n", GetDebugClassName(), this));
-
-    // Fixup pointer to optional fields if this class has any. This pointer is a relative pointer (to avoid
-    // the need for base relocation fixups) and thus needs to use the IMAGE_REL_BASED_RELPTR fixup type.
-    if (HasOptionalFields())
-        image->FixupRelativePointerField(this, offsetof(EEClass, m_rpOptionalFields));
-
-#ifdef _DEBUG
-    image->FixupPointerField(this, offsetof(EEClass, m_szDebugClassName));
-#endif
-
-#ifdef FEATURE_COMINTEROP
-    if (GetSparseCOMInteropVTableMap() != NULL)
-    {
-        image->FixupPointerField(GetOptionalFields(), offsetof(EEClassOptionalFields, m_pSparseVTableMap));
-        GetSparseCOMInteropVTableMap()->Fixup(image);
-    }
-#endif // FEATURE_COMINTEROP
-
-    DictionaryLayout *pDictLayout = GetDictionaryLayout();
-    if (pDictLayout != NULL)
-    {
-        pDictLayout->Fixup(image, FALSE);
-        image->FixupPointerField(GetOptionalFields(), offsetof(EEClassOptionalFields, m_pDictLayout));
-    }
-
-    if (HasOptionalFields())
-        image->FixupRelativePointerField(GetOptionalFields(), offsetof(EEClassOptionalFields, m_pVarianceInfo));
-
-    //
-    // We pass in the method table, because some classes (e.g. remoting proxy)
-    // have fake method tables set up in them & we want to restore the regular
-    // one.
-    //
-    image->FixupField(this, offsetof(EEClass, m_pMethodTable), pMT, 0, IMAGE_REL_BASED_RelativePointer);
-
-    //
-    // Fixup MethodDescChunk and MethodDescs
-    //
-    MethodDescChunk* pChunks = GetChunks();
-
-    if (pChunks!= NULL && image->IsStored(pChunks))
-    {
-        image->FixupRelativePointerField(this, offsetof(EEClass, m_pChunks));
-
-        MethodTable::IntroducedMethodIterator it(pMT, TRUE);
-        for (; it.IsValid(); it.Next())
-        {
-            MethodDesc * pMD = it.GetMethodDesc();
-
-            // Skip IL stubs that were not saved into the image
-            if (pMD->IsILStub() && !image->IsStored(pMD))
-                continue;
-
-            it.GetMethodDesc()->Fixup(image);
-        }
-
-    }
-    else
-    {
-        image->ZeroPointerField(this, offsetof(EEClass, m_pChunks));
-    }
-
-    //
-    // Fixup FieldDescs
-    //
-
-    SIZE_T fieldCount = FieldDescListSize(pMT);
-
-    if (fieldCount != 0)
-    {
-        image->FixupRelativePointerField(this, offsetof(EEClass, m_pFieldDescList));
-
-        FieldDesc *pField = GetFieldDescList();
-        FieldDesc *pFieldEnd = pField + fieldCount;
-        while (pField < pFieldEnd)
-        {
-            pField->Fixup(image);
-            pField++;
-        }
-    }
-
-#ifdef FEATURE_COMINTEROP
-    // These fields will be lazy inited if we zero them
-    if (HasOptionalFields())
-        image->ZeroPointerField(GetOptionalFields(), offsetof(EEClassOptionalFields, m_pCoClassForIntf));
-#ifdef FEATURE_COMINTEROP_UNMANAGED_ACTIVATION
-    if (HasOptionalFields())
-        image->ZeroPointerField(GetOptionalFields(), offsetof(EEClassOptionalFields, m_pClassFactory));
-#endif
-    image->ZeroPointerField(this, offsetof(EEClass, m_pccwTemplate));
-#endif // FEATURE_COMINTEROP
-
-
-    if (HasLayout())
-    {
-        image->ZeroPointerField(this, offsetof(LayoutEEClass, m_nativeLayoutInfo));
-    }
-    else if (IsDelegate())
-    {
-        image->FixupRelativePointerField(this, offsetof(DelegateEEClass, m_pInvokeMethod));
-        image->FixupRelativePointerField(this, offsetof(DelegateEEClass, m_pBeginInvokeMethod));
-        image->FixupRelativePointerField(this, offsetof(DelegateEEClass, m_pEndInvokeMethod));
-
-        image->ZeroPointerField(this, offsetof(DelegateEEClass, m_pUMThunkMarshInfo));
-        image->ZeroPointerField(this, offsetof(DelegateEEClass, m_pStaticCallStub));
-        image->ZeroPointerField(this, offsetof(DelegateEEClass, m_pMultiCastInvokeStub));
-        image->ZeroPointerField(this, offsetof(DelegateEEClass, m_pWrapperDelegateInvokeStub));
-        image->ZeroPointerField(this, offsetof(DelegateEEClass, m_pMarshalStub));
-
-#ifdef FEATURE_COMINTEROP
-        DelegateEEClass *pDelegateClass = (DelegateEEClass *)this;
-        ComPlusCallInfo *pComInfo = pDelegateClass->m_pComPlusCallInfo;
-
-        if (image->IsStored(pComInfo))
-        {
-            image->FixupPointerField(this, offsetof(DelegateEEClass, m_pComPlusCallInfo));
-            pComInfo->Fixup(image);
-        }
-        else
-        {
-            image->ZeroPointerField(this, offsetof(DelegateEEClass, m_pComPlusCallInfo));
-        }
-#endif // FEATURE_COMINTEROP
-
-        image->FixupPointerField(this, offsetof(DelegateEEClass, m_pForwardStubMD));
-        image->FixupPointerField(this, offsetof(DelegateEEClass, m_pReverseStubMD));
-    }
-
-    //
-    // This field must be initialized at
-    // load time
-    //
-
-    if (IsInterface() && GetGuidInfo() != NULL)
-        image->FixupRelativePointerField(this, offsetof(EEClass, m_pGuidInfo));
-    else
-        image->ZeroPointerField(this, offsetof(EEClass, m_pGuidInfo));
-
-    LOG((LF_ZAP, LL_INFO10000, "EEClass::Fixup %s (%p) complete.\n", GetDebugClassName(), this));
-}
-#endif // FEATURE_NATIVE_IMAGE_GENERATION
-
-
 //*******************************************************************************
 void EEClass::AddChunk (MethodDescChunk* pNewChunk)
 {
index 300ed22..a5a1249 100644 (file)
@@ -311,12 +311,6 @@ public:
         return (void*)m_MapList;
     }
 
-#ifdef FEATURE_PREJIT
-    // Methods to persist structure
-    void Save(DataImage *image);
-    void Fixup(DataImage *image);
-#endif // FEATURE_PREJIT
-
 private:
 
     enum { MapGrow = 4 };
@@ -782,9 +776,6 @@ public:
 
 #ifdef FEATURE_PREJIT
     DWORD GetSize();
-
-    void Save(DataImage *image, MethodTable *pMT);
-    void Fixup(DataImage *image, MethodTable *pMT);
 #endif // FEATURE_PREJIT
 
     EEClassLayoutInfo *GetLayoutInfo();
index ffd5b0f..1d9e902 100644 (file)
@@ -45,7 +45,6 @@
 #include "eeconfig.h"
 #include "contractimpl.h"
 #include "prettyprintsig.h"
-#include "compile.h"
 
 #include "comcallablewrapper.h"
 #include "clrtocomcall.h"
@@ -2591,7 +2590,7 @@ VOID    MethodTableBuilder::EnumerateClassMethods()
 
         // Some interface checks.
         // We only need them if default interface method support is disabled or if this is fragile crossgen
-#if !defined(FEATURE_DEFAULT_INTERFACES) || defined(FEATURE_NATIVE_IMAGE_GENERATION)
+#if !defined(FEATURE_DEFAULT_INTERFACES)
         if (fIsClassInterface
 #if defined(FEATURE_DEFAULT_INTERFACES)
             // Only fragile crossgen wasn't upgraded to deal with default interface methods.
@@ -2615,7 +2614,7 @@ VOID    MethodTableBuilder::EnumerateClassMethods()
                 }
             }
         }
-#endif // !defined(FEATURE_DEFAULT_INTERFACES) || defined(FEATURE_NATIVE_IMAGE_GENERATION)
+#endif // !defined(FEATURE_DEFAULT_INTERFACES)
 
         // No synchronized methods in ValueTypes
         if(fIsClassValueType && IsMiSynchronized(dwImplFlags))
index 28f4c69..e745059 100644 (file)
@@ -756,245 +756,6 @@ BOOL EEClassHashTable::CompareKeys(PTR_EEClassHashEntry pEntry, LPCUTF8 * pKey2)
 
 #ifndef DACCESS_COMPILE
 
-#ifdef FEATURE_NATIVE_IMAGE_GENERATION
-void EEClassHashTable::Save(DataImage *image, CorProfileData *profileData)
-{
-    STANDARD_VM_CONTRACT;
-
-    // See comment on PrepareExportedTypesForSaving for what's going on here.
-    if (GetModule()->IsManifest())
-        PrepareExportedTypesForSaving(image);
-
-    // The base class handles most of the saving logic (it controls the layout of the hash memory). It will
-    // call us back for some per-entry related details (should we save this entry?, is this entry hot? etc.).
-    // See the methods immediately following this one.
-    BaseSave(image, profileData);
-}
-
-// Should a particular entry be persisted into the ngen image?
-bool EEClassHashTable::ShouldSave(DataImage *pImage, EEClassHashEntry_t *pEntry)
-{
-    LIMITED_METHOD_CONTRACT;
-
-    // We always save all entries.
-    return true;
-}
-
-// Does profile data indicate that this entry is hot (likely to be read at runtime)?
-bool EEClassHashTable::IsHotEntry(EEClassHashEntry_t *pEntry, CorProfileData *pProfileData)
-{
-    STANDARD_VM_CONTRACT;
-
-    PTR_VOID datum = pEntry->GetData();
-    mdToken token;
-
-    if (m_bCaseInsensitive)
-        datum = PTR_EEClassHashEntry((TADDR)datum)->GetData();
-
-    if ((((ULONG_PTR) datum) & EECLASSHASH_TYPEHANDLE_DISCR) == 0)
-    {
-        TypeHandle t = TypeHandle::FromPtr(datum);
-        _ASSERTE(!t.IsNull());
-        MethodTable *pMT = t.GetMethodTable();
-        if (pMT == NULL)
-            return false;
-
-        token = pMT->GetCl();
-    }
-    else if (((ULONG_PTR)datum & EECLASSHASH_MDEXPORT_DISCR) == 0)
-    {
-        DWORD dwDatum = (DWORD)(DWORD_PTR)(datum);
-        token = ((dwDatum >> 1) & 0x00ffffff) | mdtTypeDef;
-    }
-    else
-        return false;
-
-    if (pProfileData->GetTypeProfilingFlagsOfToken(token) & (1 << ReadClassHashTable))
-        return true;
-
-    return false;
-}
-
-// This is our chance to fixup our hash entries before they're committed to the ngen image. Return true if the
-// entry will remain immutable at runtime (this might allow the entry to be stored in a read-only, shareable
-// portion of the image).
-bool EEClassHashTable::SaveEntry(DataImage *pImage, CorProfileData *pProfileData, EEClassHashEntry_t *pOldEntry, EEClassHashEntry_t *pNewEntry, EntryMappingTable *pMap)
-{
-    STANDARD_VM_CONTRACT;
-
-    // If we're a nested class we have a reference to the entry of our enclosing class. But this reference
-    // will have been broken by the saving process (the base class re-creates and re-orders all entries in
-    // order to optimize them for ngen images). So we read the old encloser address from the old version of
-    // our entry and, if there is one, we use the supplied map to transform that address into the new version.
-    // We can then write the updated address back into our encloser field in the new copy of the entry.
-    EEClassHashEntry_t *pOldEncloser = pOldEntry->GetEncloser();
-    if (pOldEncloser)
-        pNewEntry->SetEncloser(pMap->GetNewEntryAddress(pOldEncloser));
-
-    // We have to do something similar with our TypeHandle references (because they're stored as relative
-    // pointers which became invalid when the entry was moved). The following sequence is a no-op if the data
-    // field contains a token rather than a TypeHandle.
-    PTR_VOID oldData = pOldEntry->GetData();
-    pNewEntry->SetData(oldData);
-
-#ifdef _DEBUG
-    if (!pImage->IsStored(pNewEntry->DebugKey[0]))
-        pImage->StoreStructure(pNewEntry->DebugKey[0], (ULONG)(strlen(pNewEntry->DebugKey[0])+1), DataImage::ITEM_DEBUG);
-    if (!pImage->IsStored(pNewEntry->DebugKey[1]))
-        pImage->StoreStructure(pNewEntry->DebugKey[1], (ULONG)(strlen(pNewEntry->DebugKey[1])+1), DataImage::ITEM_DEBUG);
-#endif // _DEBUG
-
-    // The entry is immutable at runtime if it's encoded as a TypeHandle. If it's a token then it might be
-    // bashed into a TypeHandle later on.
-    return ((TADDR)pNewEntry->GetData() & EECLASSHASH_TYPEHANDLE_DISCR) == 0;
-}
-
-// The manifest module contains exported type entries in the EEClassHashTables. During ngen, these entries get
-// populated to the corresponding TypeHandle. However, at runtime, it is not guaranteed for the module
-// containing the exported type to be loaded. Hence, we cannot use the TypeHandle. Instead, we bash the
-// TypeHandle back to the export token.
-void EEClassHashTable::PrepareExportedTypesForSaving(DataImage *image)
-{
-    CONTRACTL
-    {
-        THROWS;
-        GC_TRIGGERS;
-        PRECONDITION(GetAppDomain()->IsCompilationDomain());
-        PRECONDITION(GetModule()->IsManifest());
-    }
-    CONTRACTL_END
-
-    IMDInternalImport *pImport = GetModule()->GetMDImport();
-
-    HENUMInternalHolder phEnum(pImport);
-    phEnum.EnumInit(mdtExportedType, mdTokenNil);
-    mdToken mdExportedType;
-
-    for (int i = 0; pImport->EnumNext(&phEnum, &mdExportedType); i++)
-    {
-        mdTypeDef typeDef;
-        LPCSTR pszNameSpace, pszName;
-        mdToken mdImpl;
-        DWORD dwFlags;
-        if (FAILED(pImport->GetExportedTypeProps(
-            mdExportedType,
-            &pszNameSpace,
-            &pszName,
-            &mdImpl,
-            &typeDef,
-            &dwFlags)))
-        {
-            THROW_BAD_FORMAT(BFA_NOFIND_EXPORTED_TYPE, GetModule());
-            continue;
-        }
-
-        CorTokenType tokenType = (CorTokenType) TypeFromToken(mdImpl);
-        CONSISTENCY_CHECK(tokenType == mdtFile ||
-                          tokenType == mdtAssemblyRef ||
-                          tokenType == mdtExportedType);
-
-        // If mdImpl is a file or an assembly, than it points to the location
-        // of the type. If mdImpl is another exported type, then it is the enclosing
-        // exported type for current (nested) type.
-        BOOL isNested = (tokenType == mdtExportedType);
-
-        // ilasm does not consistently set the dwFlags to correctly reflect nesting
-        //CONSISTENCY_CHECK(!isNested || IsTdNested(dwFlags));
-
-        EEClassHashEntry_t * pEntry = NULL;
-
-        if (!isNested)
-        {
-            pEntry = FindItem(pszNameSpace, pszName, FALSE/*nested*/, NULL);
-        }
-        else
-        {
-            PTR_VOID data;
-            LookupContext sContext;
-
-            // This following line finds the 1st "nested" class EEClassHashEntry_t.
-            if ((pEntry = FindItem(pszNameSpace, pszName, TRUE/*nested*/, &sContext)) != NULL)
-            {
-                // The (immediate) encloser of EEClassHashEntry_t (i.e. pEntry) is stored in pEntry->pEncloser.
-                // It needs to be a type of "mdImpl".
-                // "CompareNestedEntryWithExportedType" will check if "pEntry->pEncloser" is a type of "mdImpl",
-                // as well as walking up the enclosing chain.
-                _ASSERTE (TypeFromToken(mdImpl) == mdtExportedType);
-                while ((!GetModule()->GetClassLoader()->CompareNestedEntryWithExportedType(pImport,
-                                                                                           mdImpl,
-                                                                                           this,
-                                                                                           pEntry->GetEncloser()))
-                       && (pEntry = FindNextNestedClass(pszNameSpace, pszName, &data, &sContext)) != NULL)
-                {
-                    ;
-                }
-            }
-        }
-
-        if (!pEntry) {
-            THROW_BAD_FORMAT(BFA_NOFIND_EXPORTED_TYPE, GetModule());
-            continue;
-        }
-
-        if (((ULONG_PTR)(pEntry->GetData())) & EECLASSHASH_TYPEHANDLE_DISCR)
-            continue;
-
-        TypeHandle th = TypeHandle::FromPtr(pEntry->GetData());
-
-#ifdef _DEBUG
-        MethodTable * pMT = th.GetMethodTable();
-        _ASSERTE(tokenType != mdtFile || pMT->GetModule()->GetModuleRef() == mdImpl);
-        // "typeDef" is just a hint for unsigned assemblies, and ILASM sets it to 0
-        // Hence, we need to relax this assert.
-        _ASSERTE(pMT->GetCl() == typeDef || typeDef == mdTokenNil);
-#endif
-
-        if (image->CanEagerBindToTypeHandle(th) && image->CanHardBindToZapModule(th.GetLoaderModule()))
-            continue;
-
-        // Bash the TypeHandle back to the export token
-        pEntry->SetData(EEClassHashTable::CompressClassDef(mdExportedType));
-    }
-}
-
-void EEClassHashTable::Fixup(DataImage *pImage)
-{
-    STANDARD_VM_CONTRACT;
-
-    // The base class does all the main fixup work. We're called back at FixupEntry below for each entry so we
-    // can fixup additional pointers.
-    BaseFixup(pImage);
-}
-
-void EEClassHashTable::FixupEntry(DataImage *pImage, EEClassHashEntry_t *pEntry, void *pFixupBase, DWORD cbFixupOffset)
-{
-    STANDARD_VM_CONTRACT;
-
-    // Cross-entry references require special fixup. Fortunately they know how to do this themselves.
-    pEntry->m_pEncloser.Fixup(pImage, this);
-
-#ifdef _DEBUG
-    pImage->FixupPointerField(pFixupBase, cbFixupOffset + offsetof(EEClassHashEntry_t, DebugKey[0]));
-    pImage->FixupPointerField(pFixupBase, cbFixupOffset + offsetof(EEClassHashEntry_t, DebugKey[1]));
-#endif // _DEBUG
-
-    // Case insensitive tables and normal hash entries pointing to TypeHandles contain relative pointers.
-    // These don't require runtime fixups (because relative pointers remain constant even in the presence of
-    // base relocations) but we still have to register a fixup of type IMAGE_REL_BASED_RELPTR. This does the
-    // work necessary to update the value of the relative pointer once the ngen image is finally layed out
-    // (the layout process can change the relationship between this field and the target it points to, so we
-    // don't know the final delta until the image is just about to be written out).
-    if (m_bCaseInsensitive || ((TADDR)pEntry->GetData() & EECLASSHASH_TYPEHANDLE_DISCR) == 0)
-    {
-        pImage->FixupField(pFixupBase,
-                           cbFixupOffset + offsetof(EEClassHashEntry_t, m_Data),
-                           pEntry->GetData(),
-                           0,
-                           IMAGE_REL_BASED_RELPTR);
-    }
-}
-#endif // FEATURE_NATIVE_IMAGE_GENERATION
-
 /*===========================MakeCaseInsensitiveTable===========================
 **Action: Creates a case-insensitive lookup table for class names.  We create a
 **        full path (namespace & class name) in lowercase and then use that as the
index d3a747c..46ca317 100644 (file)
@@ -111,21 +111,6 @@ public:
     void EnumMemoryRegionsForEntry(EEClassHashEntry_t *pEntry, CLRDataEnumMemoryFlags flags);
 #endif
 
-#if defined(FEATURE_PREJIT) && !defined(DACCESS_COMPILE)
-    void Save(DataImage *pImage, CorProfileData *pProfileData);
-    void Fixup(DataImage *pImage);
-
-private:
-    friend class NgenHashTable<EEClassHashTable, EEClassHashEntry, 4>;
-
-    void PrepareExportedTypesForSaving(DataImage *image);
-
-    bool ShouldSave(DataImage *pImage, EEClassHashEntry_t *pEntry);
-    bool IsHotEntry(EEClassHashEntry_t *pEntry, CorProfileData *pProfileData);
-    bool SaveEntry(DataImage *pImage, CorProfileData *pProfileData, EEClassHashEntry_t *pOldEntry, EEClassHashEntry_t *pNewEntry, EntryMappingTable *pMap);
-    void FixupEntry(DataImage *pImage, EEClassHashEntry_t *pEntry, void *pFixupBase, DWORD cbFixupOffset);
-#endif // FEATURE_PREJIT && !DACCESS_COMPILE
-
 private:
 #ifndef DACCESS_COMPILE
     EEClassHashTable(Module *pModule, LoaderHeap *pHeap, DWORD cInitialBuckets) :
index 77a1a7c..c3bf713 100644 (file)
@@ -89,22 +89,6 @@ PTR_Module ClassLoader::ComputeLoaderModuleWorker(
     if (classInst.IsEmpty() && methodInst.IsEmpty())
         RETURN PTR_Module(pDefinitionModule);
 
-#ifndef DACCESS_COMPILE
-#ifdef FEATURE_NATIVE_IMAGE_GENERATION
-    //
-    // Use special loader module placement during compilation of fragile native images.
-    //
-    // ComputeLoaderModuleForCompilation algorithm assumes that we are using fragile native image
-    // for CoreLib (or compiling CoreLib itself). It is not the case for ReadyToRun compilation because
-    // CoreLib as always treated as IL there (see code:PEFile::ShouldTreatNIAsMSIL for details).
-    //
-    if (IsCompilationProcess() && !IsReadyToRunCompilation())
-    {
-        RETURN(ComputeLoaderModuleForCompilation(pDefinitionModule, token, classInst, methodInst));
-    }
-#endif // FEATURE_PREJIT
-#endif // #ifndef DACCESS_COMPILE
-
     Module *pLoaderModule = NULL;
 
     if (pDefinitionModule)
@@ -187,135 +171,6 @@ ComputeCollectibleLoaderModule:
     RETURN PTR_Module(pLoaderModule);
 }
 
-#ifndef DACCESS_COMPILE
-#ifdef FEATURE_NATIVE_IMAGE_GENERATION
-/* static */
-PTR_Module ClassLoader::ComputeLoaderModuleForCompilation(
-    Module *     pDefinitionModule,  // the module that declares the generic type or method
-    mdToken      token,              // method or class token for this item
-    Instantiation classInst,         // the type arguments to the type (if any)
-    Instantiation methodInst)        // the type arguments to the method (if any)
-{
-    CONTRACT(Module*)
-    {
-        NOTHROW;
-        GC_NOTRIGGER;
-        FORBID_FAULT;
-        MODE_ANY;
-        PRECONDITION(CheckPointer(pDefinitionModule, NULL_OK));
-        POSTCONDITION(CheckPointer(RETVAL));
-    }
-    CONTRACT_END
-
-    // The NGEN rule for compiling constructed types and instantiated methods
-    // into modules other than their "natural" LoaderModule. This is at the heart of
-    // "full generics NGEN".
-    //
-    // If this instantiation doesn't have a unique home then use the ngen module
-
-    // OK, we're certainly NGEN'ing.  And if we're NGEN'ing then we're not on the debugger thread.
-    CONSISTENCY_CHECK(((GetThreadNULLOk() && GetAppDomain()) || IsGCThread()) &&
-        "unexpected: running a load on debug thread but IsCompilationProcess() returned TRUE");
-
-    // Save it into its PreferredZapModule if it's always going to be saved there.
-    // This is a stable choice - no need to record it in the table (as we do for others below)
-    if (Module::IsAlwaysSavedInPreferredZapModule(classInst, methodInst))
-    {
-        RETURN (Module::ComputePreferredZapModule(pDefinitionModule, classInst, methodInst));
-    }
-
-    // Check if this compilation process has already decided on an adjustment.  Once we decide
-    // on the LoaderModule for an item it must be stable for the duration of a
-    // compilation process, no matter how many modules get NGEN'd.
-
-    ZapperLoaderModuleTableKey key(pDefinitionModule,
-                                   token,
-                                   classInst,
-                                   methodInst);
-
-    Module * pZapperLoaderModule = g_pCEECompileInfo->LookupZapperLoaderModule(&key);
-    if (pZapperLoaderModule != NULL)
-    {
-        RETURN (pZapperLoaderModule);
-    }
-
-    // OK, we need to compute a non-standard zapping module.
-
-    Module * pPreferredZapModule = Module::ComputePreferredZapModule(pDefinitionModule, classInst, methodInst);
-
-    // Check if we're NGEN'ing but where perhaps the compilation domain
-    // isn't set up yet.  This can happen in following situations:
-    // - Managed code running during startup before compilation domain is setup.
-    // - Exceptions (e.g. invalid program exceptions) thrown from compilation domain and caught in default domain
-
-    // We're a little stuck - we can't force the item into an NGEN image at this point.  So just bail out
-    // and use the loader module we've computed without recording the choice. The loader module should always
-    // be CoreLib in this case.
-    AppDomain * pAppDomain = GetAppDomain();
-    if (!pAppDomain->IsCompilationDomain() ||
-        !pAppDomain->ToCompilationDomain()->GetTargetModule())
-    {
-        _ASSERTE(pPreferredZapModule->IsSystem() || IsNgenPDBCompilationProcess());
-        RETURN (pPreferredZapModule);
-    }
-
-    Module * pTargetModule = pAppDomain->ToCompilationDomain()->GetTargetModule();
-
-    // If it is multi-module assembly and we have not saved PZM yet, do not create
-    // speculative instantiation - just save it in PZM.
-    if (pTargetModule->GetAssembly() == pPreferredZapModule->GetAssembly() &&
-        !pPreferredZapModule->IsModuleSaved())
-    {
-        pZapperLoaderModule = pPreferredZapModule;
-    }
-    else
-    {
-        // Everything else can be saved into the current module.
-        pZapperLoaderModule = pTargetModule;
-    }
-
-    // Record this choice just in case we're NGEN'ing multiple modules
-    // to make sure we always do the same thing if we're asked to compute
-    // the loader module again.
-
-    // Note this whole code path only happens while NGEN'ing, so this violation
-    // is not so bad.  It is needed since we allocate stuff on the heap.
-    CONTRACT_VIOLATION(ThrowsViolation|FaultViolation);
-
-    // Copy the instantiation arrays so they can escape the scope of this method.
-    // Since this is a permanent entry in a table for this compilation process
-    // we do not need to collect these.  If we did have to we would do it when we deleteed the
-    // ZapperLoaderModuleTable.
-    NewArrayHolder<TypeHandle> pClassArgs = NULL;
-    if (!classInst.IsEmpty())
-    {
-        pClassArgs = new TypeHandle[classInst.GetNumArgs()];
-        for (unsigned int i = 0; i < classInst.GetNumArgs(); i++)
-            pClassArgs[i] = classInst[i];
-    }
-
-    NewArrayHolder<TypeHandle> pMethodArgs = NULL;
-    if (!methodInst.IsEmpty())
-    {
-        pMethodArgs = new TypeHandle[methodInst.GetNumArgs()];
-        for (unsigned int i = 0; i < methodInst.GetNumArgs(); i++)
-            pMethodArgs[i] = methodInst[i];
-    }
-
-    ZapperLoaderModuleTableKey key2(pDefinitionModule,
-                                    token,
-                                    Instantiation(pClassArgs, classInst.GetNumArgs()),
-                                    Instantiation(pMethodArgs, methodInst.GetNumArgs()));
-    g_pCEECompileInfo->RecordZapperLoaderModule(&key2, pZapperLoaderModule);
-
-    pClassArgs.SuppressRelease();
-    pMethodArgs.SuppressRelease();
-
-    RETURN (pZapperLoaderModule);
-}
-#endif // FEATURE_NATIVE_IMAGE_GENERATION
-#endif // #ifndef DACCESS_COMPILE
-
 /*static*/
 Module * ClassLoader::ComputeLoaderModule(MethodTable * pMT,
                                           mdToken       token,
diff --git a/src/coreclr/vm/compile.cpp b/src/coreclr/vm/compile.cpp
deleted file mode 100644 (file)
index b36840a..0000000
+++ /dev/null
@@ -1,6785 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// ===========================================================================
-// File: compile.cpp
-//
-
-//
-// Support for zap compiler and zap files
-// ===========================================================================
-
-
-
-#include "common.h"
-
-#ifdef FEATURE_PREJIT
-
-#include <corcompile.h>
-
-#include "assemblyspec.hpp"
-
-#include "compile.h"
-#include "excep.h"
-#include "field.h"
-#include "eeconfig.h"
-#include "zapsig.h"
-#include "gcrefmap.h"
-
-
-#include "virtualcallstub.h"
-#include "typeparse.h"
-#include "typestring.h"
-#include "dllimport.h"
-#include "comdelegate.h"
-#include "stringarraylist.h"
-
-#ifdef FEATURE_COMINTEROP
-#include "clrtocomcall.h"
-#include "comtoclrcall.h"
-#endif // FEATURE_COMINTEROP
-
-#include "dllimportcallback.h"
-#include "caparser.h"
-#include "sigbuilder.h"
-#include "cgensys.h"
-#include "peimagelayout.inl"
-
-#ifndef NO_NGENPDB
-#include <cvinfo.h>
-#endif
-
-#ifdef FEATURE_PERFMAP
-#include "perfmap.h"
-#endif
-
-#include "argdestination.h"
-
-#include "versionresilienthashcode.h"
-#include "inlinetracking.h"
-#include "jithost.h"
-#include "stubgen.h"
-
-#ifdef CROSSGEN_COMPILE
-CompilationDomain * theDomain;
-#ifdef FEATURE_READYTORUN_COMPILER
-MapSHash<CORINFO_METHOD_HANDLE, CORINFO_METHOD_HANDLE> s_stubMethodsOfMethod;
-#endif // FEATURE_READYTORUN_COMPILER
-#endif
-
-VerboseLevel g_CorCompileVerboseLevel = CORCOMPILE_NO_LOG;
-
-//
-// CEECompileInfo implements most of ICorCompileInfo
-//
-
-HRESULT CEECompileInfo::Startup(  BOOL fForceDebug,
-                                  BOOL fForceProfiling,
-                                  BOOL fForceInstrument)
-{
-    SystemDomain::SetCompilationOverrides(fForceDebug,
-                                          fForceProfiling,
-                                          fForceInstrument);
-
-    HRESULT hr = S_OK;
-
-    m_fCachingOfInliningHintsEnabled = TRUE;
-
-    _ASSERTE(!g_fEEStarted && !g_fEEInit && "You cannot run the EE inside an NGEN compilation process");
-
-    if (!g_fEEStarted && !g_fEEInit)
-    {
-#ifdef CROSSGEN_COMPILE
-        GetSystemInfo(&g_SystemInfo);
-
-        theDomain = new CompilationDomain(fForceDebug,
-                                          fForceProfiling,
-                                          fForceInstrument);
-#endif
-
-        // When NGEN'ing this call may execute EE code, e.g. the managed code to set up
-        // the SharedDomain.
-        hr = EnsureEEStarted();
-    }
-
-    //
-    // JIT interface expects to be called with
-    // preemptive GC enabled
-    //
-    if (SUCCEEDED(hr)) {
-#ifdef _DEBUG
-        Thread *pThread = GetThreadNULLOk();
-        _ASSERTE(pThread);
-#endif
-
-        GCX_PREEMP_NO_DTOR();
-    }
-
-    return hr;
-}
-
-HRESULT CEECompileInfo::CreateDomain(ICorCompilationDomain **ppDomain,
-                                     IMetaDataAssemblyEmit *pEmitter,
-                                     BOOL fForceDebug,
-                                     BOOL fForceProfiling,
-                                     BOOL fForceInstrument)
-{
-    STANDARD_VM_CONTRACT;
-
-    COOPERATIVE_TRANSITION_BEGIN();
-
-    CompilationDomain * pCompilationDomain = theDomain;
-
-    {
-        SystemDomain::LockHolder lh;
-        pCompilationDomain->Init();
-    }
-
-    if (pEmitter)
-        pCompilationDomain->SetDependencyEmitter(pEmitter);
-
-
-#ifdef DEBUGGING_SUPPORTED
-    // Notify the debugger here, before the thread transitions into the
-    // AD to finish the setup, and before any assemblies are loaded into it.
-    SystemDomain::PublishAppDomainAndInformDebugger(pCompilationDomain);
-#endif // DEBUGGING_SUPPORTED
-
-    pCompilationDomain->LoadSystemAssemblies();
-
-    pCompilationDomain->SetupSharedStatics();
-
-    *ppDomain = static_cast<ICorCompilationDomain*>(pCompilationDomain);
-
-    {
-        GCX_COOP();
-
-        pCompilationDomain->CreateBinderContext();
-
-        pCompilationDomain->SetFriendlyName(W("Compilation Domain"));
-        SystemDomain::System()->LoadDomain(pCompilationDomain);
-    }
-
-    COOPERATIVE_TRANSITION_END();
-
-    return S_OK;
-}
-
-
-HRESULT CEECompileInfo::DestroyDomain(ICorCompilationDomain *pDomain)
-{
-    STANDARD_VM_CONTRACT;
-
-#ifndef CROSSGEN_COMPILE
-    COOPERATIVE_TRANSITION_BEGIN();
-
-    GCX_COOP();
-
-    CompilationDomain *pCompilationDomain = (CompilationDomain *) pDomain;
-
-    // DDB 175659: Make sure that canCallNeedsRestore() returns FALSE during compilation
-    // domain shutdown.
-    pCompilationDomain->setCannotCallNeedsRestore();
-
-    pCompilationDomain->Unload(TRUE);
-
-    COOPERATIVE_TRANSITION_END();
-#endif
-
-    return S_OK;
-}
-
-#ifdef TRITON_STRESS_NEED_IMPL
-int LogToSvcLogger(LPCWSTR format, ...)
-{
-    STANDARD_VM_CONTRACT;
-
-    StackSString s;
-
-    va_list args;
-    va_start(args, format);
-    s.VPrintf(format, args);
-    va_end(args);
-
-    GetSvcLogger()->Printf(W("%s"), s.GetUnicode());
-
-    return 0;
-}
-#endif
-
-HRESULT CEECompileInfo::LoadAssemblyByPath(
-    LPCWSTR                  wzPath,
-
-    // Normally this is FALSE, but crossgen /CreatePDB sets this to TRUE, so it can
-    // explicitly load an NI by path
-    BOOL                     fExplicitBindToNativeImage,
-
-    CORINFO_ASSEMBLY_HANDLE *pHandle)
-{
-    STANDARD_VM_CONTRACT;
-
-    HRESULT hr = S_OK;
-
-    COOPERATIVE_TRANSITION_BEGIN();
-
-    Assembly * pAssembly;
-    HRESULT    hrProcessLibraryBitnessMismatch = S_OK;
-
-    // We don't want to do a LoadFrom, since they do not work with ngen. Instead,
-    // read the metadata from the file and do a bind based on that.
-
-    EX_TRY
-    {
-        // Pre-open the image so we can grab some metadata to help initialize the
-        // binder's AssemblySpec, which we'll use later to load the assembly for real.
-
-        PEImageHolder pImage;
-
-
-        if (pImage == NULL)
-        {
-            pImage = PEImage::OpenImage(
-                wzPath,
-
-                // If we're explicitly binding to an NGEN image, we do not want the cache
-                // this PEImage for use later, as pointers that need fixup
-                // Normal caching is done when we open it "for real" further down when we
-                // call LoadDomainAssembly().
-                fExplicitBindToNativeImage ? MDInternalImport_NoCache : MDInternalImport_Default);
-        }
-
-        if (fExplicitBindToNativeImage && !pImage->HasReadyToRunHeader())
-        {
-            pImage->VerifyIsNIAssembly();
-        }
-        else
-        {
-            pImage->VerifyIsAssembly();
-        }
-
-        // Check to make sure the bitness of the assembly matches the bitness of the process
-        // we will be loading it into and store the result.  If a COR_IMAGE_ERROR gets thrown
-        // by LoadAssembly then we can blame it on bitness mismatch.  We do the check here
-        // and not in the CATCH to distinguish between the COR_IMAGE_ERROR that can be thrown by
-        // VerifyIsAssembly (not necessarily a bitness mismatch) and that from LoadAssembly
-#ifdef TARGET_64BIT
-        if (pImage->Has32BitNTHeaders())
-        {
-            hrProcessLibraryBitnessMismatch = PEFMT_E_32BIT;
-        }
-#else // !TARGET_64BIT
-        if (!pImage->Has32BitNTHeaders())
-        {
-            hrProcessLibraryBitnessMismatch = PEFMT_E_64BIT;
-        }
-#endif // !TARGET_64BIT
-
-        AssemblySpec spec;
-        spec.InitializeSpec(TokenFromRid(1, mdtAssembly), pImage->GetMDImport(), NULL);
-
-        if (spec.IsCoreLib())
-        {
-            pAssembly = SystemDomain::System()->SystemAssembly();
-        }
-        else
-        {
-            AppDomain * pDomain = AppDomain::GetCurrentDomain();
-
-            PEAssemblyHolder pAssemblyHolder;
-
-            //ExplicitBind
-            CoreBindResult bindResult;
-            spec.SetCodeBase(pImage->GetPath());
-            spec.Bind(
-                pDomain,
-                TRUE,                   // fThrowOnFileNotFound
-                &bindResult,
-
-                // fNgenExplicitBind: Generally during NGEN compilation, this is
-                // TRUE, meaning "I am NGEN, and I am doing an explicit bind to the IL
-                // image, so don't infer the NI and try to open it, because I already
-                // have it open". But if we're executing crossgen /CreatePDB, this should
-                // be FALSE so that downstream code doesn't assume we're explicitly
-                // trying to bind to an IL image (we're actually explicitly trying to
-                // open an NI).
-                !fExplicitBindToNativeImage,
-
-                // fExplicitBindToNativeImage: Most callers want this FALSE; but crossgen
-                // /CreatePDB explicitly specifies NI names to open, and cannot assume
-                // that IL assemblies will be available.
-                fExplicitBindToNativeImage
-                );
-            pAssemblyHolder = PEAssembly::Open(&bindResult,FALSE);
-
-            // Now load assembly into domain.
-            DomainAssembly * pDomainAssembly = pDomain->LoadDomainAssembly(&spec, pAssemblyHolder, FILE_LOAD_BEGIN);
-
-            pDomain->AddAssemblyToCache(&spec, pDomainAssembly);
-
-            pAssembly = pDomain->LoadAssembly(&spec, pAssemblyHolder, FILE_LOADED);
-
-            // Add a dependency to the current assembly.  This is done to match the behavior
-            // of LoadAssemblyFusion, so that the same native image is generated whether we
-            // ngen install by file name or by assembly name.
-            pDomain->ToCompilationDomain()->AddDependency(&spec, pAssemblyHolder);
-        }
-
-        // Kind of a workaround - if we could have loaded this assembly via normal load,
-
-        *pHandle = CORINFO_ASSEMBLY_HANDLE(pAssembly);
-    }
-    EX_CATCH_HRESULT(hr);
-
-    if ( hrProcessLibraryBitnessMismatch != S_OK && ( hr == COR_E_BADIMAGEFORMAT || hr == HRESULT_FROM_WIN32(ERROR_BAD_EXE_FORMAT) ) )
-    {
-        hr = hrProcessLibraryBitnessMismatch;
-    }
-
-    COOPERATIVE_TRANSITION_END();
-
-    return hr;
-}
-
-BOOL CEECompileInfo::IsInCurrentVersionBubble(CORINFO_MODULE_HANDLE hModule)
-{
-    WRAPPER_NO_CONTRACT;
-
-    return ((Module*)hModule)->IsInCurrentVersionBubble();
-}
-
-HRESULT CEECompileInfo::LoadAssemblyModule(
-    CORINFO_ASSEMBLY_HANDLE assembly,
-    mdFile                  file,
-    CORINFO_MODULE_HANDLE   *pHandle)
-{
-    STANDARD_VM_CONTRACT;
-
-    COOPERATIVE_TRANSITION_BEGIN();
-
-    Assembly *pAssembly = (Assembly*) assembly;
-
-    Module *pModule = pAssembly->GetManifestModule()->LoadModule(GetAppDomain(), file, TRUE)->GetModule();
-
-    //
-    // Return the module handle
-    //
-
-    *pHandle = CORINFO_MODULE_HANDLE(pModule);
-
-    COOPERATIVE_TRANSITION_END();
-
-    return S_OK;
-}
-
-
-BOOL CEECompileInfo::CheckAssemblyZap(
-    CORINFO_ASSEMBLY_HANDLE assembly,
-  __out_ecount_opt(*cAssemblyManifestModulePath)
-    LPWSTR                  assemblyManifestModulePath,
-    LPDWORD                 cAssemblyManifestModulePath)
-{
-    STANDARD_VM_CONTRACT;
-
-    BOOL result = FALSE;
-
-    COOPERATIVE_TRANSITION_BEGIN();
-
-    Assembly *pAssembly = (Assembly*) assembly;
-
-    if (pAssembly->GetManifestFile()->HasNativeImage())
-    {
-        PEImage *pImage = pAssembly->GetManifestFile()->GetPersistentNativeImage();
-
-        if (assemblyManifestModulePath != NULL)
-        {
-            DWORD length = pImage->GetPath().GetCount();
-            if (length > *cAssemblyManifestModulePath)
-            {
-                length = *cAssemblyManifestModulePath - 1;
-                wcsncpy_s(assemblyManifestModulePath, *cAssemblyManifestModulePath, pImage->GetPath(), length);
-                assemblyManifestModulePath[length] = 0;
-            }
-            else
-                wcscpy_s(assemblyManifestModulePath, *cAssemblyManifestModulePath, pImage->GetPath());
-        }
-
-        result = TRUE;
-    }
-
-    COOPERATIVE_TRANSITION_END();
-
-    return result;
-}
-
-HRESULT CEECompileInfo::SetCompilationTarget(CORINFO_ASSEMBLY_HANDLE     assembly,
-                                             CORINFO_MODULE_HANDLE       module)
-{
-    STANDARD_VM_CONTRACT;
-
-    Assembly *pAssembly = (Assembly *) assembly;
-    Module *pModule = (Module *) module;
-
-    CompilationDomain *pDomain = (CompilationDomain *) GetAppDomain();
-    pDomain->SetTarget(pAssembly, pModule);
-
-    if (!pAssembly->IsSystem())
-    {
-        // It is possible to get through a compile without calling BindAssemblySpec on CoreLib.  This
-        // is because refs to CoreLib are short circuited in a number of places.  So, we will explicitly
-        // add it to our dependencies.
-
-        AssemblySpec corelib;
-        corelib.InitializeSpec(SystemDomain::SystemFile());
-        GetAppDomain()->BindAssemblySpec(&corelib,TRUE);
-    }
-
-    if (IsReadyToRunCompilation() && !pModule->GetFile()->IsILOnly())
-    {
-        GetSvcLogger()->Printf(LogLevel_Error, W("Error: ReadyToRun is not supported for mixed mode assemblies\n"));
-        return E_FAIL;
-    }
-
-    return S_OK;
-}
-
-IMDInternalImport *
-    CEECompileInfo::GetAssemblyMetaDataImport(CORINFO_ASSEMBLY_HANDLE assembly)
-{
-    STANDARD_VM_CONTRACT;
-
-    IMDInternalImport * import;
-
-    COOPERATIVE_TRANSITION_BEGIN();
-
-    import = ((Assembly*)assembly)->GetManifestImport();
-    import->AddRef();
-
-    COOPERATIVE_TRANSITION_END();
-
-    return import;
-}
-
-IMDInternalImport *
-    CEECompileInfo::GetModuleMetaDataImport(CORINFO_MODULE_HANDLE scope)
-{
-    STANDARD_VM_CONTRACT;
-
-    IMDInternalImport * import;
-
-    COOPERATIVE_TRANSITION_BEGIN();
-
-    import = ((Module*)scope)->GetMDImport();
-    import->AddRef();
-
-    COOPERATIVE_TRANSITION_END();
-
-    return import;
-}
-
-CORINFO_MODULE_HANDLE
-    CEECompileInfo::GetAssemblyModule(CORINFO_ASSEMBLY_HANDLE assembly)
-{
-    STANDARD_VM_CONTRACT;
-
-    CANNOTTHROWCOMPLUSEXCEPTION();
-
-    return (CORINFO_MODULE_HANDLE) ((Assembly*)assembly)->GetManifestModule();
-}
-
-PEDecoder * CEECompileInfo::GetModuleDecoder(CORINFO_MODULE_HANDLE scope)
-{
-    STANDARD_VM_CONTRACT;
-
-    PEDecoder *result;
-
-    COOPERATIVE_TRANSITION_BEGIN();
-
-    //
-    // Note that we go ahead and return the native image if we are using that.
-    // It contains everything we need to ngen.  However, the caller must be
-    // aware and check for the native image case, since some fields will need to come
-    // from the CORCOMPILE_ZAP_HEADER rather than the PE headers.
-    //
-
-    PEFile *pFile = ((Module *) scope)->GetFile();
-
-    if (pFile->HasNativeImage())
-        result = pFile->GetLoadedNative();
-    else
-        result = pFile->GetLoadedIL();
-
-    COOPERATIVE_TRANSITION_END();
-
-    return result;
-
-}
-
-void CEECompileInfo::GetModuleFileName(CORINFO_MODULE_HANDLE scope,
-                                       SString               &result)
-{
-    STANDARD_VM_CONTRACT;
-
-    COOPERATIVE_TRANSITION_BEGIN();
-
-    result.Set(((Module*)scope)->GetPath());
-
-    COOPERATIVE_TRANSITION_END();
-}
-
-CORINFO_ASSEMBLY_HANDLE
-    CEECompileInfo::GetModuleAssembly(CORINFO_MODULE_HANDLE module)
-{
-    STANDARD_VM_CONTRACT;
-
-    CANNOTTHROWCOMPLUSEXCEPTION();
-
-    return (CORINFO_ASSEMBLY_HANDLE) GetModule(module)->GetAssembly();
-}
-
-//-----------------------------------------------------------------------------
-// For an assembly with a full name of "Foo, Version=2.0.0.0, Culture=neutral",
-// we want any of these attributes specifications to match:
-//    DependencyAttribute("Foo", LoadHint.Always)
-//    DependencyAttribute("Foo,", LoadHint.Always)
-//    DependencyAttribute("Foo, Version=2.0.0.0, Culture=neutral", LoadHint.Always)
-// The second case of "Foo," is needed only for intra-V2 compat as
-// it was supported at one point during V2. We may be able to get rid of it.
-template <typename ASSEMBLY>
-BOOL IsAssemblySpecifiedInCA(ASSEMBLY * pAssembly, SString dependencyNameFromCA)
-{
-    STANDARD_VM_CONTRACT;
-
-    // First, check for this:
-    //    DependencyAttribute("Foo", LoadHint.Always)
-    StackSString simpleName(SString::Utf8, pAssembly->GetSimpleName());
-    if (simpleName.EqualsCaseInsensitive(dependencyNameFromCA))
-        return TRUE;
-
-    // Now, check for this:
-    //    DependencyAttribute("Foo,", LoadHint.Always)
-    SString comma(W(","));
-    StackSString simpleNameWithComma(simpleName, comma);
-    if (simpleNameWithComma.EqualsCaseInsensitive(dependencyNameFromCA))
-        return TRUE;
-
-    // Finally:
-    //    DependencyAttribute("Foo, Version=2.0.0.0, Culture=neutral", LoadHint.Always)
-    StackSString fullName;
-    pAssembly->GetDisplayName(fullName);
-    if (fullName.EqualsCaseInsensitive(dependencyNameFromCA))
-        return TRUE;
-
-    return FALSE;
-}
-
-template <typename ASSEMBLY>
-void GetLoadHint(ASSEMBLY * pAssembly, ASSEMBLY *pAssemblyDependency,
-                 LoadHintEnum *loadHint, LoadHintEnum *defaultLoadHint = NULL)
-{
-    STANDARD_VM_CONTRACT;
-
-    *loadHint = LoadDefault;
-
-    const BYTE  *pbAttr;                // Custom attribute data as a BYTE*.
-    ULONG       cbAttr;                 // Size of custom attribute data.
-    mdToken     mdAssembly;
-
-    // Look for the binding custom attribute
-    {
-        IMDInternalImport *pImport = pAssembly->GetManifestImport();
-
-        IfFailThrow(pImport->GetAssemblyFromScope(&mdAssembly));
-
-        MDEnumHolder hEnum(pImport);        // Enumerator for custom attributes
-        IfFailThrow(pImport->EnumCustomAttributeByNameInit(mdAssembly, DEPENDENCY_TYPE, &hEnum));
-
-        mdCustomAttribute tkAttribute;      // A custom attribute on this assembly.
-        while (pImport->EnumNext(&hEnum, &tkAttribute))
-        {
-            // Get raw custom attribute.
-            IfFailThrow(pImport->GetCustomAttributeAsBlob(tkAttribute, (const void**)&pbAttr, &cbAttr));
-
-            CustomAttributeParser cap(pbAttr, cbAttr);
-
-            IfFailThrow(cap.ValidateProlog());
-
-            // Extract string from custom attribute
-            LPCUTF8 szString;
-            ULONG   cbString;
-            IfFailThrow(cap.GetNonNullString(&szString, &cbString));
-
-            // Convert the string to Unicode.
-            StackSString dependencyNameFromCA(SString::Utf8, szString, cbString);
-
-            if (IsAssemblySpecifiedInCA(pAssemblyDependency, dependencyNameFromCA))
-            {
-                // Get dependency setting
-                UINT32 u4;
-                IfFailThrow(cap.GetU4(&u4));
-                *loadHint = (LoadHintEnum)u4;
-                break;
-            }
-        }
-    }
-
-    // If not preference is specified, look for the built-in assembly preference
-    if (*loadHint == LoadDefault || defaultLoadHint != NULL)
-    {
-        IMDInternalImport *pImportDependency = pAssemblyDependency->GetManifestImport();
-
-        IfFailThrow(pImportDependency->GetAssemblyFromScope(&mdAssembly));
-
-        HRESULT hr = pImportDependency->GetCustomAttributeByName(mdAssembly,
-            DEFAULTDEPENDENCY_TYPE,
-            (const void**)&pbAttr, &cbAttr);
-        IfFailThrow(hr);
-
-        // Parse the attribute
-        if (hr == S_OK)
-        {
-            CustomAttributeParser cap(pbAttr, cbAttr);
-            IfFailThrow(cap.ValidateProlog());
-
-            // Get default bind setting
-            UINT32 u4 = 0;
-            IfFailThrow(cap.GetU4(&u4));
-
-            if (defaultLoadHint)
-                *defaultLoadHint = (LoadHintEnum) u4;
-            else
-                *loadHint = (LoadHintEnum) u4;
-        }
-    }
-}
-
-HRESULT CEECompileInfo::GetLoadHint(CORINFO_ASSEMBLY_HANDLE hAssembly,
-                                    CORINFO_ASSEMBLY_HANDLE hAssemblyDependency,
-                                    LoadHintEnum *loadHint,
-                                    LoadHintEnum *defaultLoadHint)
-{
-    STANDARD_VM_CONTRACT;
-
-    HRESULT hr = S_OK;
-
-    EX_TRY
-    {
-        Assembly *pAssembly           = (Assembly *) hAssembly;
-        Assembly *pAssemblyDependency = (Assembly *) hAssemblyDependency;
-
-        ::GetLoadHint(pAssembly, pAssemblyDependency, loadHint, defaultLoadHint);
-    }
-    EX_CATCH_HRESULT(hr);
-
-    return hr;
-}
-
-HRESULT CEECompileInfo::GetAssemblyVersionInfo(CORINFO_ASSEMBLY_HANDLE hAssembly,
-                                               CORCOMPILE_VERSION_INFO *pInfo)
-{
-    STANDARD_VM_CONTRACT;
-
-    Assembly *pAssembly = (Assembly *) hAssembly;
-
-    pAssembly->GetDomainAssembly()->GetCurrentVersionInfo(pInfo);
-
-    return S_OK;
-}
-
-void CEECompileInfo::GetAssemblyCodeBase(CORINFO_ASSEMBLY_HANDLE hAssembly, SString &result)
-{
-    STANDARD_VM_CONTRACT;
-
-    COOPERATIVE_TRANSITION_BEGIN();
-
-    Assembly *pAssembly = (Assembly *)hAssembly;
-    _ASSERTE(pAssembly != NULL);
-
-    pAssembly->GetCodeBase(result);
-
-    COOPERATIVE_TRANSITION_END();
-}
-
-void CEECompileInfo::GetCallRefMap(CORINFO_METHOD_HANDLE hMethod, GCRefMapBuilder * pBuilder, bool isDispatchCell)
-{
-    MethodDesc *pMD = (MethodDesc *)hMethod;
-    ComputeCallRefMap(pMD, pBuilder, isDispatchCell);
-}
-
-void CEECompileInfo::CompressDebugInfo(
-    IN ICorDebugInfo::OffsetMapping * pOffsetMapping,
-    IN ULONG            iOffsetMapping,
-    IN ICorDebugInfo::NativeVarInfo * pNativeVarInfo,
-    IN ULONG            iNativeVarInfo,
-    IN OUT SBuffer    * pDebugInfoBuffer
-    )
-{
-    STANDARD_VM_CONTRACT;
-
-    CompressDebugInfo::CompressBoundariesAndVars(pOffsetMapping, iOffsetMapping, pNativeVarInfo, iNativeVarInfo, NULL, pDebugInfoBuffer, NULL);
-}
-
-ICorJitHost* CEECompileInfo::GetJitHost()
-{
-    return JitHost::getJitHost();
-}
-
-HRESULT CEECompileInfo::GetBaseJitFlags(
-        IN  CORINFO_METHOD_HANDLE   hMethod,
-        OUT CORJIT_FLAGS           *pFlags)
-{
-    STANDARD_VM_CONTRACT;
-
-    MethodDesc *pMD = (MethodDesc *)hMethod;
-    *pFlags = CEEInfo::GetBaseCompileFlags(pMD);
-
-    return S_OK;
-}
-
-//=================================================================================
-
-#ifdef _DEBUG
-
-static struct
-{
-    size_t total;
-    size_t noEmbed;
-    size_t array;
-    size_t primitives;
-    size_t szarray;
-} embedStats;
-
-#endif // _DEBUG
-
-BOOL CEEPreloader::CanEmbedClassID(CORINFO_CLASS_HANDLE    typeHandle)
-{
-    STANDARD_VM_CONTRACT;
-
-    TypeHandle hnd = (TypeHandle) typeHandle;
-    return m_image->CanEagerBindToTypeHandle(hnd) &&
-        !hnd.AsMethodTable()->NeedsCrossModuleGenericsStaticsInfo();
-}
-
-BOOL CEEPreloader::CanEmbedModuleID(CORINFO_MODULE_HANDLE    moduleHandle)
-{
-    STANDARD_VM_CONTRACT;
-
-    return m_image->CanEagerBindToModule((Module *)moduleHandle);
-}
-
-BOOL CEEPreloader::CanEmbedModuleHandle(CORINFO_MODULE_HANDLE    moduleHandle)
-{
-    STANDARD_VM_CONTRACT;
-
-    return m_image->CanEagerBindToModule((Module *)moduleHandle);
-
-}
-BOOL CEEPreloader::CanEmbedClassHandle(CORINFO_CLASS_HANDLE    typeHandle)
-{
-    STANDARD_VM_CONTRACT;
-
-    TypeHandle hnd = (TypeHandle) typeHandle;
-
-    BOOL decision = m_image->CanEagerBindToTypeHandle(hnd);
-
-#ifdef _DEBUG
-    embedStats.total++;
-
-    if (!decision)
-        embedStats.noEmbed++;
-
-    if (hnd.IsArray())
-    {
-        embedStats.array++;
-
-        CorElementType arrType = hnd.GetInternalCorElementType();
-        if (arrType == ELEMENT_TYPE_SZARRAY)
-            embedStats.szarray++;
-
-        CorElementType elemType = hnd.GetArrayElementTypeHandle().GetInternalCorElementType();
-        if (elemType <= ELEMENT_TYPE_R8)
-            embedStats.primitives++;
-    }
-#endif // _DEBUG
-    return decision;
-}
-
-
-/*static*/ BOOL CanEmbedMethodDescViaContext(MethodDesc * pMethod, MethodDesc * pContext)
-{
-    STANDARD_VM_CONTRACT;
-
-    if (pContext != NULL)
-    {
-        _ASSERTE(pContext->GetLoaderModule() == GetAppDomain()->ToCompilationDomain()->GetTargetModule());
-
-        // a method can always embed its own handle
-        if (pContext == pMethod)
-        {
-            return TRUE;
-        }
-
-        // Methods that are tightly bound to the same method table can
-        // always refer each other directly. This check allows methods
-        // within one speculative generic instantiations to call each
-        // other directly.
-        //
-        if ((pContext->GetMethodTable() == pMethod->GetMethodTable()) &&
-            pContext->IsTightlyBoundToMethodTable() &&
-            pMethod->IsTightlyBoundToMethodTable())
-        {
-            return TRUE;
-        }
-    }
-    return FALSE;
-}
-
-BOOL CEEPreloader::CanEmbedMethodHandle(CORINFO_METHOD_HANDLE methodHandle,
-                                        CORINFO_METHOD_HANDLE contextHandle)
-{
-    STANDARD_VM_CONTRACT;
-
-    MethodDesc * pContext = GetMethod(contextHandle);
-    MethodDesc * pMethod  = GetMethod(methodHandle);
-
-    if (CanEmbedMethodDescViaContext(pMethod, pContext))
-        return TRUE;
-
-    return m_image->CanEagerBindToMethodDesc(pMethod);
-}
-
-BOOL CEEPreloader::CanEmbedFieldHandle(CORINFO_FIELD_HANDLE    fieldHandle)
-{
-    STANDARD_VM_CONTRACT;
-
-    return m_image->CanEagerBindToFieldDesc((FieldDesc *) fieldHandle);
-
-}
-
-void* CEECompileInfo::GetStubSize(void *pStubAddress, DWORD *pSizeToCopy)
-{
-    CONTRACT(void*)
-    {
-        STANDARD_VM_CHECK;
-        PRECONDITION(pStubAddress && pSizeToCopy);
-    }
-    CONTRACT_END;
-
-    Stub *stub = Stub::RecoverStubAndSize((TADDR)pStubAddress, pSizeToCopy);
-    _ASSERTE(*pSizeToCopy > sizeof(Stub));
-    RETURN stub;
-}
-
-HRESULT CEECompileInfo::GetStubClone(void *pStub, BYTE *pBuffer, DWORD dwBufferSize)
-{
-    STANDARD_VM_CONTRACT;
-
-    if (pStub == NULL)
-    {
-        return E_INVALIDARG;
-    }
-
-    return (reinterpret_cast<Stub *>(pStub)->CloneStub(pBuffer, dwBufferSize));
-}
-
-HRESULT CEECompileInfo::GetTypeDef(CORINFO_CLASS_HANDLE classHandle,
-                                   mdTypeDef *token)
-{
-    STANDARD_VM_CONTRACT;
-
-    CANNOTTHROWCOMPLUSEXCEPTION();
-
-    TypeHandle hClass(classHandle);
-
-    *token = hClass.GetCl();
-
-    return S_OK;
-}
-
-HRESULT CEECompileInfo::GetMethodDef(CORINFO_METHOD_HANDLE methodHandle,
-                                     mdMethodDef *token)
-{
-    STANDARD_VM_CONTRACT;
-
-    CANNOTTHROWCOMPLUSEXCEPTION();
-
-    *token = ((MethodDesc*)methodHandle)->GetMemberDef();
-
-    return S_OK;
-}
-
-/*********************************************************************/
-// Used to determine if a methodHandle can be embedded in an ngen image.
-// Depends on what things are persisted by CEEPreloader
-
-BOOL CEEPreloader::CanEmbedFunctionEntryPoint(
-    CORINFO_METHOD_HANDLE   methodHandle,
-    CORINFO_METHOD_HANDLE   contextHandle, /* = NULL */
-    CORINFO_ACCESS_FLAGS    accessFlags /*=CORINFO_ACCESS_ANY*/)
-{
-    STANDARD_VM_CONTRACT;
-
-    MethodDesc * pMethod = GetMethod(methodHandle);
-
-    // Methods with UnmanagedCallersOnlyAttribute are special, since
-    // they are used as LDFTN targets. UnmanagedCallersOnly methods
-    // uses the same code path as reverse pinvoke and embedding them
-    // in an ngen image require saving the reverse pinvoke stubs.
-    if (pMethod->HasUnmanagedCallersOnlyAttribute())
-        return FALSE;
-
-    return TRUE;
-}
-
-BOOL CEEPreloader::DoesMethodNeedRestoringBeforePrestubIsRun(
-        CORINFO_METHOD_HANDLE   methodHandle)
-{
-    STANDARD_VM_CONTRACT;
-
-    MethodDesc * ftn = GetMethod(methodHandle);
-
-    // The restore mechanism for InstantiatedMethodDescs (IMDs) is complicated, and causes
-    // circular dependency complications with the GC if we hardbind to the prestub/precode
-    // of an unrestored IMD. As such, we're eliminating hardbinding to unrestored MethodDescs
-    // that belong to generic types.
-
-    //@TODO: The reduction may be overkill, and we may consider refining the cases.
-
-    // Specifically, InstantiatedMethodDescs can have preferred zap modules different than
-    // the zap modules for their owning types. As such, in a soft-binding case a MethodDesc
-    // may not be able to trace back to its owning Module without hitting an unrestored
-    // fixup token. For example, the 64-bit JIT can not yet provide generic type arguments
-    // and uses instantiating stubs to call static methods on generic types. If such an stub
-    // belong to a module other than the module in which the generic type is declared, then
-    // it is possible for the MethodTable::m_pEEClass or the EEClass::m_pModule pointers to
-    // be unrestored. The complication arises when a call to the prestub/precode of such
-    // an unrestored IMD causes us try to restore the IMD and this in turn causes us to
-    // transition to preemptive GC and as such GC needs the metadata signature from the IMD
-    // to iterate its arguments. But since we're currently restoring the IMD, we may not be
-    // able to get to the signature, and as such we're stuck.
-
-    // The same problem exists for instantiation arguments. We may need the instantiation
-    // arguments while walking the signature during GC, and if they are not restored we're stuck.
-
-    if (ftn->HasClassOrMethodInstantiation())
-    {
-        if (ftn->NeedsRestore(m_image))
-            return TRUE;
-    }
-
-    return FALSE;
-}
-
-BOOL CEECompileInfo::IsUnmanagedCallConvMethod(CORINFO_METHOD_HANDLE handle)
-{
-    WRAPPER_NO_CONTRACT;
-
-    MethodDesc * pMethod = GetMethod(handle);
-    return pMethod->HasUnmanagedCallConvAttribute();
-}
-
-BOOL CEECompileInfo::IsUnmanagedCallersOnlyMethod(CORINFO_METHOD_HANDLE handle)
-{
-    WRAPPER_NO_CONTRACT;
-
-    MethodDesc * pMethod = GetMethod(handle);
-    return pMethod->HasUnmanagedCallersOnlyAttribute();
-}
-
-BOOL CEEPreloader::CanSkipDependencyActivation(CORINFO_METHOD_HANDLE   context,
-                                               CORINFO_MODULE_HANDLE   moduleFrom,
-                                               CORINFO_MODULE_HANDLE   moduleTo)
-{
-    STANDARD_VM_CONTRACT;
-
-    // Can't skip any fixups for speculative generic instantiations
-    if (Module::GetPreferredZapModuleForMethodDesc(GetMethod(context)) != m_image->GetModule())
-        return FALSE;
-
-    // We don't need a fixup for eager bound dependencies since we are going to have
-    // an uncontional one already.
-    return m_image->CanEagerBindToModule((Module *)moduleTo);
-}
-
-CORINFO_MODULE_HANDLE CEEPreloader::GetPreferredZapModuleForClassHandle(
-        CORINFO_CLASS_HANDLE classHnd)
-{
-    STANDARD_VM_CONTRACT;
-
-    return CORINFO_MODULE_HANDLE(Module::GetPreferredZapModuleForTypeHandle(TypeHandle(classHnd)));
-}
-
-// This method is called directly from zapper
-extern BOOL CanDeduplicateCode(CORINFO_METHOD_HANDLE method, CORINFO_METHOD_HANDLE duplicateMethod);
-
-BOOL CanDeduplicateCode(CORINFO_METHOD_HANDLE method, CORINFO_METHOD_HANDLE duplicateMethod)
-{
-    CONTRACTL
-    {
-        NOTHROW;
-        GC_NOTRIGGER;
-    }
-    CONTRACTL_END;
-
-    ENABLE_FORBID_GC_LOADER_USE_IN_THIS_SCOPE();
-
-    // For now, the deduplication is supported for IL stubs only
-    DynamicMethodDesc * pMethod = GetMethod(method)->AsDynamicMethodDesc();
-    DynamicMethodDesc * pDuplicateMethod = GetMethod(duplicateMethod)->AsDynamicMethodDesc();
-
-    //
-    // Make sure that the IL stub flags match
-    //
-
-    if (pMethod->GetExtendedFlags() != pDuplicateMethod->GetExtendedFlags())
-        return FALSE;
-
-    return TRUE;
-}
-
-void CEEPreloader::NoteDeduplicatedCode(CORINFO_METHOD_HANDLE method, CORINFO_METHOD_HANDLE duplicateMethod)
-{
-    STANDARD_VM_CONTRACT;
-
-#ifndef FEATURE_FULL_NGEN // Deduplication
-    DuplicateMethodEntry e;
-    e.pMD = GetMethod(method);
-    e.pDuplicateMD = GetMethod(duplicateMethod);
-    m_duplicateMethodsHash.Add(e);
-#endif
-}
-
-HRESULT CEECompileInfo::GetFieldDef(CORINFO_FIELD_HANDLE fieldHandle,
-                                    mdFieldDef *token)
-{
-    STANDARD_VM_CONTRACT;
-
-    CANNOTTHROWCOMPLUSEXCEPTION();
-
-    *token = ((FieldDesc*)fieldHandle)->GetMemberDef();
-
-    return S_OK;
-}
-
-void CEECompileInfo::EncodeModuleAsIndex(CORINFO_MODULE_HANDLE  fromHandle,
-                                         CORINFO_MODULE_HANDLE  handle,
-                                         DWORD*                 pIndex,
-                                         IMetaDataAssemblyEmit* pAssemblyEmit)
-{
-    STANDARD_VM_CONTRACT;
-
-    COOPERATIVE_TRANSITION_BEGIN();
-
-    Module *fromModule = GetModule(fromHandle);
-    Assembly *fromAssembly = fromModule->GetAssembly();
-
-    Module *module = GetModule(handle);
-    Assembly *assembly = module->GetAssembly();
-
-    if (assembly == fromAssembly)
-        *pIndex = 0;
-    else
-    {
-        UPTR    result;
-        mdToken token;
-
-        CompilationDomain *pDomain = GetAppDomain()->ToCompilationDomain();
-
-        RefCache *pRefCache = pDomain->GetRefCache(fromModule);
-        if (!pRefCache)
-            ThrowOutOfMemory();
-
-        result = pRefCache->m_sAssemblyRefMap.LookupValue((UPTR)assembly, NULL);
-
-        if (result == (UPTR)INVALIDENTRY)
-            token = fromModule->FindAssemblyRef(assembly);
-        else
-            token = (mdAssemblyRef) result;
-
-        if (IsNilToken(token))
-        {
-            token = fromAssembly->AddAssemblyRef(assembly, pAssemblyEmit);
-            token += fromModule->GetAssemblyRefMax();
-        }
-
-        *pIndex = RidFromToken(token);
-
-        pRefCache->m_sAssemblyRefMap.InsertValue((UPTR) assembly, (UPTR)token);
-    }
-
-    COOPERATIVE_TRANSITION_END();
-}
-
-void CEECompileInfo::EncodeClass(
-                         CORINFO_MODULE_HANDLE referencingModule,
-                         CORINFO_CLASS_HANDLE  classHandle,
-                         SigBuilder *          pSigBuilder,
-                         LPVOID                pEncodeModuleContext,
-                         ENCODEMODULE_CALLBACK pfnEncodeModule)
-{
-    STANDARD_VM_CONTRACT;
-
-    TypeHandle th(classHandle);
-
-    ZapSig zapSig((Module *)referencingModule, pEncodeModuleContext, ZapSig::NormalTokens,
-                  (EncodeModuleCallback) pfnEncodeModule, NULL);
-
-    COOPERATIVE_TRANSITION_BEGIN();
-
-    BOOL fSuccess;
-    fSuccess = zapSig.GetSignatureForTypeHandle(th, pSigBuilder);
-    _ASSERTE(fSuccess);
-
-    COOPERATIVE_TRANSITION_END();
-}
-
-CORINFO_MODULE_HANDLE CEECompileInfo::GetLoaderModuleForCoreLib()
-{
-    STANDARD_VM_CONTRACT;
-
-    return CORINFO_MODULE_HANDLE(SystemDomain::SystemModule());
-}
-
-CORINFO_MODULE_HANDLE CEECompileInfo::GetLoaderModuleForEmbeddableType(CORINFO_CLASS_HANDLE clsHnd)
-{
-    STANDARD_VM_CONTRACT;
-
-    TypeHandle t = TypeHandle(clsHnd);
-    return CORINFO_MODULE_HANDLE(t.GetLoaderModule());
-}
-
-CORINFO_MODULE_HANDLE CEECompileInfo::GetLoaderModuleForEmbeddableMethod(CORINFO_METHOD_HANDLE methHnd)
-{
-    STANDARD_VM_CONTRACT;
-
-    MethodDesc *pMD = GetMethod(methHnd);
-    return CORINFO_MODULE_HANDLE(pMD->GetLoaderModule());
-}
-
-CORINFO_MODULE_HANDLE CEECompileInfo::GetLoaderModuleForEmbeddableField(CORINFO_FIELD_HANDLE fieldHnd)
-{
-    STANDARD_VM_CONTRACT;
-
-    FieldDesc *pFD = (FieldDesc *) fieldHnd;
-    return CORINFO_MODULE_HANDLE(pFD->GetLoaderModule());
-}
-
-void CEECompileInfo::EncodeMethod(
-                          CORINFO_MODULE_HANDLE referencingModule,
-                          CORINFO_METHOD_HANDLE handle,
-                          SigBuilder *          pSigBuilder,
-                          LPVOID                pEncodeModuleContext,
-                          ENCODEMODULE_CALLBACK pfnEncodeModule,
-                          CORINFO_RESOLVED_TOKEN * pResolvedToken,
-                          CORINFO_RESOLVED_TOKEN * pConstrainedResolvedToken,
-                          BOOL                  fEncodeUsingResolvedTokenSpecStreams)
-{
-    STANDARD_VM_CONTRACT;
-
-    COOPERATIVE_TRANSITION_BEGIN();
-
-    _ASSERTE(referencingModule);
-    MethodDesc *pMethod = GetMethod(handle);
-
-    BOOL fSuccess;
-    fSuccess = ZapSig::EncodeMethod(pMethod,
-                              (Module *) referencingModule,
-                              pSigBuilder,
-                              pEncodeModuleContext,
-                              pfnEncodeModule, NULL,
-                              pResolvedToken, pConstrainedResolvedToken,
-                              fEncodeUsingResolvedTokenSpecStreams);
-    _ASSERTE(fSuccess);
-
-    COOPERATIVE_TRANSITION_END();
-}
-
-mdToken CEECompileInfo::TryEncodeMethodAsToken(
-                CORINFO_METHOD_HANDLE handle,
-                CORINFO_RESOLVED_TOKEN * pResolvedToken,
-                CORINFO_MODULE_HANDLE * referencingModule)
-{
-    STANDARD_VM_CONTRACT;
-
-    MethodDesc * pMethod = GetMethod(handle);
-
-#ifdef FEATURE_READYTORUN_COMPILER
-    if (IsReadyToRunCompilation())
-    {
-        _ASSERTE(pResolvedToken != NULL);
-
-        Module * pReferencingModule = GetModule(pResolvedToken->tokenScope);
-
-        if (!pReferencingModule->IsInCurrentVersionBubble())
-            return mdTokenNil;
-
-        // If this is a MemberRef with TypeSpec, we might come to here because we resolved the method
-        // into a non-generic base class in the same version bubble. However, since we don't have the
-        // proper type context during ExternalMethodFixupWorker, we can't really encode using token
-        if (pResolvedToken->pTypeSpec != NULL)
-            return mdTokenNil;
-
-        unsigned methodToken = pResolvedToken->token;
-
-        switch (TypeFromToken(methodToken))
-        {
-        case mdtMethodDef:
-            if (pReferencingModule->LookupMethodDef(methodToken) != pMethod)
-                return mdTokenNil;
-            break;
-
-        case mdtMemberRef:
-            if (pReferencingModule->LookupMemberRefAsMethod(methodToken) != pMethod)
-                return mdTokenNil;
-            break;
-
-        default:
-            return mdTokenNil;
-        }
-
-        *referencingModule = CORINFO_MODULE_HANDLE(pReferencingModule);
-        return methodToken;
-    }
-#endif // FEATURE_READYTORUN_COMPILER
-
-    Module *pModule = pMethod->GetModule();
-    if (!pModule->IsInCurrentVersionBubble())
-    {
-        Module * pTargetModule = GetAppDomain()->ToCompilationDomain()->GetTargetModule();
-        *referencingModule = CORINFO_MODULE_HANDLE(pTargetModule);
-        return pTargetModule->LookupMemberRefByMethodDesc(pMethod);
-    }
-    else
-    {
-        mdToken defToken = pMethod->GetMemberDef();
-        if (pModule->LookupMethodDef(defToken) == pMethod)
-        {
-            *referencingModule = CORINFO_MODULE_HANDLE(pModule);
-            return defToken;
-        }
-    }
-
-    return mdTokenNil;
-}
-
-DWORD CEECompileInfo::TryEncodeMethodSlot(CORINFO_METHOD_HANDLE handle)
-{
-    STANDARD_VM_CONTRACT;
-
-    MethodDesc * pMethod = GetMethod(handle);
-
-#ifdef FEATURE_READYTORUN_COMPILER
-    if (IsReadyToRunCompilation())
-    {
-        // We can only encode real interface methods as slots
-        if (!pMethod->IsInterface() || pMethod->IsStatic())
-            return (DWORD)-1;
-
-        // And only if the interface lives in the current version bubble
-        // If may be possible to relax this restriction if we can guarantee that the external interfaces are
-        // really not changing. We will play it safe for now.
-        if (!pMethod->GetModule()->IsInCurrentVersionBubble())
-            return (DWORD)-1;
-    }
-#endif
-
-    return pMethod->GetSlot();
-}
-
-void EncodeTypeInDictionarySignature(
-            Module * pInfoModule,
-            SigPointer ptr,
-            SigBuilder * pSigBuilder,
-            LPVOID encodeContext,
-            ENCODEMODULE_CALLBACK pfnEncodeModule)
-{
-    STANDARD_VM_CONTRACT;
-
-    CorElementType typ = ELEMENT_TYPE_END;
-    IfFailThrow(ptr.GetElemType(&typ));
-
-    if (typ == ELEMENT_TYPE_INTERNAL)
-    {
-        TypeHandle th;
-
-        IfFailThrow(ptr.GetPointer((void**)&th));
-
-        ZapSig zapSig(pInfoModule, encodeContext, ZapSig::NormalTokens,
-                      (EncodeModuleCallback) pfnEncodeModule, NULL);
-
-        //
-        // Write class
-        //
-        BOOL fSuccess;
-        fSuccess = zapSig.GetSignatureForTypeHandle(th, pSigBuilder);
-        _ASSERTE(fSuccess);
-
-        return;
-    }
-    else
-    if (typ == ELEMENT_TYPE_GENERICINST)
-    {
-        //
-        // SigParser expects ELEMENT_TYPE_MODULE_ZAPSIG to be before ELEMENT_TYPE_GENERICINST
-        //
-        SigPointer peek(ptr);
-        uint32_t instType = 0;
-        IfFailThrow(peek.GetData(&instType));
-        _ASSERTE(instType == ELEMENT_TYPE_INTERNAL);
-
-        TypeHandle th;
-        IfFailThrow(peek.GetPointer((void **)&th));
-
-        Module * pTypeHandleModule = th.GetModule();
-
-        if (!pTypeHandleModule->IsInCurrentVersionBubble())
-        {
-            pTypeHandleModule = GetAppDomain()->ToCompilationDomain()->GetTargetModule();
-        }
-
-        if (pTypeHandleModule != pInfoModule)
-        {
-            DWORD index = pfnEncodeModule(encodeContext, (CORINFO_MODULE_HANDLE)pTypeHandleModule);
-            _ASSERTE(index != ENCODE_MODULE_FAILED);
-
-            pSigBuilder->AppendElementType((CorElementType) ELEMENT_TYPE_MODULE_ZAPSIG);
-            pSigBuilder->AppendData(index);
-        }
-
-        pSigBuilder->AppendElementType(ELEMENT_TYPE_GENERICINST);
-
-        EncodeTypeInDictionarySignature(pTypeHandleModule, ptr, pSigBuilder, encodeContext, pfnEncodeModule);
-        IfFailThrow(ptr.SkipExactlyOne());
-
-        uint32_t argCnt = 0; // Get number of parameters
-        IfFailThrow(ptr.GetData(&argCnt));
-        pSigBuilder->AppendData(argCnt);
-
-        while (argCnt--)
-        {
-            EncodeTypeInDictionarySignature(pInfoModule, ptr, pSigBuilder, encodeContext, pfnEncodeModule);
-            IfFailThrow(ptr.SkipExactlyOne());
-        }
-
-        return;
-    }
-
-    pSigBuilder->AppendElementType(typ);
-
-    if (!CorIsPrimitiveType(typ))
-    {
-        switch (typ)
-        {
-            case ELEMENT_TYPE_VAR:
-            case ELEMENT_TYPE_MVAR:
-                {
-                    uint32_t varNum;
-                    // Skip variable number
-                    IfFailThrow(ptr.GetData(&varNum));
-                    pSigBuilder->AppendData(varNum);
-                }
-                break;
-            case ELEMENT_TYPE_OBJECT:
-            case ELEMENT_TYPE_STRING:
-            case ELEMENT_TYPE_TYPEDBYREF:
-                break;
-
-            case ELEMENT_TYPE_BYREF: //fallthru
-            case ELEMENT_TYPE_PTR:
-            case ELEMENT_TYPE_PINNED:
-            case ELEMENT_TYPE_SZARRAY:
-                EncodeTypeInDictionarySignature(pInfoModule, ptr, pSigBuilder, encodeContext, pfnEncodeModule);
-                IfFailThrow(ptr.SkipExactlyOne());
-                break;
-
-            case ELEMENT_TYPE_ARRAY:
-                {
-                    EncodeTypeInDictionarySignature(pInfoModule, ptr, pSigBuilder, encodeContext, pfnEncodeModule);
-                    IfFailThrow(ptr.SkipExactlyOne());
-
-                    uint32_t rank = 0; // Get rank
-                    IfFailThrow(ptr.GetData(&rank));
-                    pSigBuilder->AppendData(rank);
-
-                    if (rank)
-                    {
-                        uint32_t nsizes = 0;
-                        IfFailThrow(ptr.GetData(&nsizes));
-                        pSigBuilder->AppendData(nsizes);
-
-                        while (nsizes--)
-                        {
-                            uint32_t data = 0;
-                            IfFailThrow(ptr.GetData(&data));
-                            pSigBuilder->AppendData(data);
-                        }
-
-                        uint32_t nlbounds = 0;
-                        IfFailThrow(ptr.GetData(&nlbounds));
-                        pSigBuilder->AppendData(nlbounds);
-
-                        while (nlbounds--)
-                        {
-                            uint32_t data = 0;
-                            IfFailThrow(ptr.GetData(&data));
-                            pSigBuilder->AppendData(data);
-                        }
-                    }
-                }
-                break;
-
-            default:
-                _ASSERTE(!"Unexpected element in signature");
-        }
-    }
-}
-
-void CEECompileInfo::EncodeGenericSignature(
-            LPVOID signature,
-            BOOL fMethod,
-            SigBuilder * pSigBuilder,
-            LPVOID encodeContext,
-            ENCODEMODULE_CALLBACK pfnEncodeModule)
-{
-    STANDARD_VM_CONTRACT;
-
-    Module * pInfoModule = CoreLibBinder::GetModule();
-
-    SigPointer ptr((PCCOR_SIGNATURE)signature);
-
-    uint32_t entryKind; // DictionaryEntryKind
-    IfFailThrow(ptr.GetData(&entryKind));
-    pSigBuilder->AppendData(entryKind);
-
-    if (!fMethod)
-    {
-        uint32_t dictionaryIndex = 0;
-        IfFailThrow(ptr.GetData(&dictionaryIndex));
-
-        pSigBuilder->AppendData(dictionaryIndex);
-    }
-
-    switch (entryKind)
-    {
-    case DeclaringTypeHandleSlot:
-        EncodeTypeInDictionarySignature(pInfoModule, ptr, pSigBuilder, encodeContext, pfnEncodeModule);
-        IfFailThrow(ptr.SkipExactlyOne());
-        FALLTHROUGH;
-
-    case TypeHandleSlot:
-        EncodeTypeInDictionarySignature(pInfoModule, ptr, pSigBuilder, encodeContext, pfnEncodeModule);
-        IfFailThrow(ptr.SkipExactlyOne());
-        break;
-
-    case ConstrainedMethodEntrySlot:
-        EncodeTypeInDictionarySignature(pInfoModule, ptr, pSigBuilder, encodeContext, pfnEncodeModule);
-        IfFailThrow(ptr.SkipExactlyOne());
-        FALLTHROUGH;
-
-    case MethodDescSlot:
-    case MethodEntrySlot:
-    case DispatchStubAddrSlot:
-        {
-            EncodeTypeInDictionarySignature(pInfoModule, ptr, pSigBuilder, encodeContext, pfnEncodeModule);
-            IfFailThrow(ptr.SkipExactlyOne());
-
-            uint32_t methodFlags;
-            IfFailThrow(ptr.GetData(&methodFlags));
-            pSigBuilder->AppendData(methodFlags);
-
-            if ((methodFlags & ENCODE_METHOD_SIG_SlotInsteadOfToken) == 0)
-            {
-                EncodeTypeInDictionarySignature(pInfoModule, ptr, pSigBuilder, encodeContext, pfnEncodeModule);
-                IfFailThrow(ptr.SkipExactlyOne());
-            }
-
-            uint32_t tokenOrSlot;
-            IfFailThrow(ptr.GetData(&tokenOrSlot));
-            pSigBuilder->AppendData(tokenOrSlot);
-
-            if (methodFlags & ENCODE_METHOD_SIG_MethodInstantiation)
-            {
-                uint32_t nGenericMethodArgs;
-                IfFailThrow(ptr.GetData(&nGenericMethodArgs));
-                pSigBuilder->AppendData(nGenericMethodArgs);
-
-                for (DWORD i = 0; i < nGenericMethodArgs; i++)
-                {
-                    EncodeTypeInDictionarySignature(pInfoModule, ptr, pSigBuilder, encodeContext, pfnEncodeModule);
-                    IfFailThrow(ptr.SkipExactlyOne());
-                }
-            }
-        }
-        break;
-
-    case FieldDescSlot:
-        {
-            EncodeTypeInDictionarySignature(pInfoModule, ptr, pSigBuilder, encodeContext, pfnEncodeModule);
-            IfFailThrow(ptr.SkipExactlyOne());
-
-            uint32_t fieldIndex;
-            IfFailThrow(ptr.GetData(&fieldIndex));
-            pSigBuilder->AppendData(fieldIndex);
-        }
-        break;
-
-    default:
-        _ASSERTE(false);
-    }
-
-    uint32_t dictionarySlot;
-    IfFailThrow(ptr.GetData(&dictionarySlot));
-    pSigBuilder->AppendData(dictionarySlot);
-}
-
-void CEECompileInfo::EncodeField(
-                         CORINFO_MODULE_HANDLE referencingModule,
-                         CORINFO_FIELD_HANDLE  handle,
-                         SigBuilder *          pSigBuilder,
-                         LPVOID                encodeContext,
-                         ENCODEMODULE_CALLBACK pfnEncodeModule,
-                         CORINFO_RESOLVED_TOKEN * pResolvedToken,
-                         BOOL fEncodeUsingResolvedTokenSpecStreams)
-{
-    STANDARD_VM_CONTRACT;
-
-    COOPERATIVE_TRANSITION_BEGIN();
-
-    ZapSig::EncodeField(GetField(handle),
-                        (Module *) referencingModule,
-                        pSigBuilder,
-                        encodeContext,
-                        pfnEncodeModule,
-                        pResolvedToken,
-                        fEncodeUsingResolvedTokenSpecStreams);
-
-    COOPERATIVE_TRANSITION_END();
-}
-
-BOOL CEECompileInfo::IsEmptyString(mdString token,
-                                   CORINFO_MODULE_HANDLE module)
-{
-    STANDARD_VM_CONTRACT;
-
-    BOOL fRet = FALSE;
-
-    COOPERATIVE_TRANSITION_BEGIN();
-
-    EEStringData strData;
-    ((Module *)module)->InitializeStringData(token, &strData, NULL);
-    fRet = (strData.GetCharCount() == 0);
-
-    COOPERATIVE_TRANSITION_END();
-
-    return fRet;
-}
-
-#ifdef FEATURE_READYTORUN_COMPILER
-CORCOMPILE_FIXUP_BLOB_KIND CEECompileInfo::GetFieldBaseOffset(
-        CORINFO_CLASS_HANDLE classHnd,
-        DWORD * pBaseOffset)
-{
-    STANDARD_VM_CONTRACT;
-
-    MethodTable * pMT = (MethodTable *)classHnd;
-    Module * pModule = pMT->GetModule();
-
-    if (!pMT->IsLayoutFixedInCurrentVersionBubble())
-    {
-        return pMT->IsValueType() ? ENCODE_CHECK_FIELD_OFFSET : ENCODE_FIELD_OFFSET;
-    }
-
-    if (pMT->IsValueType())
-    {
-        return ENCODE_NONE;
-    }
-
-    if (pMT->GetParentMethodTable()->IsInheritanceChainLayoutFixedInCurrentVersionBubble())
-    {
-        return ENCODE_NONE;
-    }
-
-    if (pMT->HasLayout())
-    {
-        // We won't try to be smart for classes with layout.
-        // They are complex to get right, and very rare anyway.
-        return ENCODE_FIELD_OFFSET;
-    }
-
-    *pBaseOffset = ReadyToRunInfo::GetFieldBaseOffset(pMT);
-    return ENCODE_FIELD_BASE_OFFSET;
-}
-
-BOOL CEECompileInfo::NeedsTypeLayoutCheck(CORINFO_CLASS_HANDLE classHnd)
-{
-    STANDARD_VM_CONTRACT;
-
-    TypeHandle th(classHnd);
-
-    if (th.IsTypeDesc())
-        return FALSE;
-
-    MethodTable * pMT = th.AsMethodTable();
-
-    if (!pMT->IsValueType())
-        return FALSE;
-
-    // Skip this check for equivalent types. Equivalent types are used for interop that ensures
-    // matching layout.
-    if (pMT->GetClass()->IsEquivalentType())
-        return FALSE;
-
-    return !pMT->IsLayoutFixedInCurrentVersionBubble();
-}
-
-extern void ComputeGCRefMap(MethodTable * pMT, BYTE * pGCRefMap, size_t cbGCRefMap);
-
-void CEECompileInfo::EncodeTypeLayout(CORINFO_CLASS_HANDLE classHandle, SigBuilder * pSigBuilder)
-{
-    STANDARD_VM_CONTRACT;
-
-    MethodTable * pMT = TypeHandle(classHandle).AsMethodTable();
-    _ASSERTE(pMT->IsValueType());
-
-    DWORD dwSize = pMT->GetNumInstanceFieldBytes();
-    DWORD dwAlignment = CEEInfo::getClassAlignmentRequirementStatic(pMT);
-
-    DWORD dwFlags = 0;
-
-#ifdef FEATURE_HFA
-    if (pMT->IsHFA())
-        dwFlags |= READYTORUN_LAYOUT_HFA;
-#endif
-
-    // Check everything
-    dwFlags |= READYTORUN_LAYOUT_Alignment;
-    if (dwAlignment == TARGET_POINTER_SIZE)
-        dwFlags |= READYTORUN_LAYOUT_Alignment_Native;
-
-    dwFlags |= READYTORUN_LAYOUT_GCLayout;
-    if (!pMT->ContainsPointers())
-        dwFlags |= READYTORUN_LAYOUT_GCLayout_Empty;
-
-    pSigBuilder->AppendData(dwFlags);
-
-    // Size is checked unconditionally
-    pSigBuilder->AppendData(dwSize);
-
-#ifdef FEATURE_HFA
-    if (dwFlags & READYTORUN_LAYOUT_HFA)
-    {
-        pSigBuilder->AppendData(pMT->GetHFAType());
-    }
-#endif
-
-    if ((dwFlags & READYTORUN_LAYOUT_Alignment) && !(dwFlags & READYTORUN_LAYOUT_Alignment_Native))
-    {
-        pSigBuilder->AppendData(dwAlignment);
-    }
-
-    if ((dwFlags & READYTORUN_LAYOUT_GCLayout) && !(dwFlags & READYTORUN_LAYOUT_GCLayout_Empty))
-    {
-        size_t cbGCRefMap = (dwSize / TARGET_POINTER_SIZE + 7) / 8;
-        _ASSERTE(cbGCRefMap > 0);
-
-        BYTE * pGCRefMap = (BYTE *)_alloca(cbGCRefMap);
-
-        ComputeGCRefMap(pMT, pGCRefMap, cbGCRefMap);
-
-        for (size_t i = 0; i < cbGCRefMap; i++)
-            pSigBuilder->AppendByte(pGCRefMap[i]);
-    }
-}
-
-BOOL CEECompileInfo::AreAllClassesFullyLoaded(CORINFO_MODULE_HANDLE moduleHandle)
-{
-    STANDARD_VM_CONTRACT;
-
-    return ((Module *)moduleHandle)->AreAllClassesFullyLoaded();
-}
-
-int CEECompileInfo::GetVersionResilientTypeHashCode(CORINFO_MODULE_HANDLE moduleHandle, mdToken token)
-{
-    STANDARD_VM_CONTRACT;
-
-    int dwHashCode;
-    if (!::GetVersionResilientTypeHashCode(((Module *)moduleHandle)->GetMDImport(), token, &dwHashCode))
-        ThrowHR(COR_E_BADIMAGEFORMAT);
-
-    return dwHashCode;
-}
-
-int CEECompileInfo::GetVersionResilientMethodHashCode(CORINFO_METHOD_HANDLE methodHandle)
-{
-    STANDARD_VM_CONTRACT;
-
-    return ::GetVersionResilientMethodHashCode(GetMethod(methodHandle));
-}
-
-#endif // FEATURE_READYTORUN_COMPILER
-
-BOOL CEECompileInfo::HasCustomAttribute(CORINFO_METHOD_HANDLE method, LPCSTR customAttributeName)
-{
-    STANDARD_VM_CONTRACT;
-
-    MethodDesc * pMD = GetMethod(method);
-    return S_OK == pMD->GetMDImport()->GetCustomAttributeByName(pMD->GetMemberDef(), customAttributeName, NULL, NULL);
-}
-
-#define OMFConst_Read            0x0001
-#define OMFConst_Write           0x0002
-#define OMFConst_Exec            0x0004
-#define OMFConst_F32Bit          0x0008
-#define OMFConst_ReservedBits1   0x00f0
-#define OMFConst_FSel            0x0100
-#define OMFConst_FAbs            0x0200
-#define OMFConst_ReservedBits2   0x0C00
-#define OMFConst_FGroup          0x1000
-#define OMFConst_ReservedBits3   0xE000
-
-#define OMF_StandardText  (OMFConst_FSel|OMFConst_F32Bit|OMFConst_Exec|OMFConst_Read) // 0x10D
-#define OMF_SentinelType  (OMFConst_FAbs|OMFConst_F32Bit) // 0x208
-
-
-// ----------------------------------------------------------------------------
-// NGEN PDB SUPPORT
-//
-// The NGEN PDB format consists of structs stacked together into buffers, which are
-// passed to the PDB API. For a description of the structures, see
-// InternalApis\vctools\inc\cvinfo.h.
-//
-// The interface to the PDB used below is NGEN-specific, and is exposed via
-// diasymreader.dll. For a description of this interface, see ISymNGenWriter2 inside
-// public\devdiv\inc\corsym.h and debugger\sh\symwrtr\ngenpdbwriter.h,cpp
-// ----------------------------------------------------------------------------
-
-#if defined(NO_NGENPDB) && !defined(FEATURE_PERFMAP)
-BOOL CEECompileInfo::GetIsGeneratingNgenPDB()
-{
-    return FALSE;
-}
-
-void CEECompileInfo::SetIsGeneratingNgenPDB(BOOL fGeneratingNgenPDB)
-{
-}
-
-BOOL IsNgenPDBCompilationProcess()
-{
-    return FALSE;
-}
-#else
-BOOL CEECompileInfo::GetIsGeneratingNgenPDB()
-{
-    LIMITED_METHOD_DAC_CONTRACT;
-    return m_fGeneratingNgenPDB;
-}
-
-void CEECompileInfo::SetIsGeneratingNgenPDB(BOOL fGeneratingNgenPDB)
-{
-    LIMITED_METHOD_DAC_CONTRACT;
-    m_fGeneratingNgenPDB = fGeneratingNgenPDB;
-}
-
-BOOL IsNgenPDBCompilationProcess()
-{
-    LIMITED_METHOD_DAC_CONTRACT;
-    return IsCompilationProcess() && g_pCEECompileInfo->GetIsGeneratingNgenPDB();
-}
-
-#endif // NO_NGENPDB && !FEATURE_PERFMAP
-
-#ifndef NO_NGENPDB
-// This is the prototype of "CreateNGenPdbWriter" exported by diasymreader.dll
-typedef HRESULT (__stdcall *CreateNGenPdbWriter_t)(const WCHAR *pwszNGenImagePath, const WCHAR *pwszPdbPath, void **ppvObj);
-
-// Allocator to specify when requesting boundaries information for PDB
-BYTE* SimpleNew(void *, size_t cBytes)
-{
-    CONTRACTL
-    {
-        THROWS;
-        GC_NOTRIGGER;
-        MODE_ANY;
-    }
-    CONTRACTL_END;
-
-    BYTE * p = new BYTE[cBytes];
-    return p;
-}
-
-// PDB convention has any IPs that don't map to source code (e.g., prolog, epilog, etc.)
-// to be mapped to line number "0xFeeFee".
-const int kUnmappedIP = 0xFeeFee;
-
-
-// ----------------------------------------------------------------------------
-// Simple pair of offsets for each source file name.  Pair includes its offset into the
-// PDB string table, and its offset in the files checksum table.
-//
-struct DocNameOffsets
-{
-    ULONG32 m_dwStrTableOffset;
-    ULONG32 m_dwChksumTableOffset;
-    DocNameOffsets(ULONG32 dwStrTableOffset, ULONG32 dwChksumTableOffset)
-        : m_dwStrTableOffset(dwStrTableOffset), m_dwChksumTableOffset(dwChksumTableOffset)
-    {
-        LIMITED_METHOD_CONTRACT;
-    }
-
-    DocNameOffsets()
-        : m_dwStrTableOffset((ULONG32) -1), m_dwChksumTableOffset((ULONG32) -1)
-    {
-        LIMITED_METHOD_CONTRACT;
-    }
-};
-
-
-// ----------------------------------------------------------------------------
-// This is used when creating the hash table which maps source file names to
-// DocNameOffsets instances.  The only interesting stuff here is that:
-//     * Equality is determined by a case-insensitive comparison on the source file
-//         names
-//     * Hashing is done by hashing the source file names
-//
-struct DocNameToOffsetMapTraits : public NoRemoveSHashTraits < MapSHashTraits<LPCSTR, DocNameOffsets> >
-{
-public:
-    static BOOL Equals(key_t k1, key_t k2)
-    {
-        LIMITED_METHOD_CONTRACT;
-
-        if (k1 == NULL && k2 == NULL)
-            return TRUE;
-        if (k1 == NULL || k2 == NULL)
-            return FALSE;
-        return _stricmp(k1, k2) == 0;
-    }
-
-    static count_t Hash(key_t k)
-    {
-        LIMITED_METHOD_CONTRACT;
-
-        if (k == NULL)
-            return 0;
-        else
-            return HashiStringA(k);
-    }
-
-    typedef LPCSTR KEY;
-    typedef DocNameOffsets VALUE;
-    typedef NoRemoveSHashTraits < MapSHashTraits<LPCSTR, DocNameOffsets> > PARENT;
-    typedef PARENT::element_t element_t;
-    static const element_t Null() { LIMITED_METHOD_CONTRACT; return element_t((KEY)0,VALUE((ULONG32) -1, (ULONG32) -1)); }
-    static bool IsNull(const element_t &e) { LIMITED_METHOD_CONTRACT; return e.Key() == (KEY)0; }
-};
-
-
-// ----------------------------------------------------------------------------
-// Hash table that maps the UTF-8 string of a source file name to its corresponding
-// DocNameToOffsetMapTraits
-//
-class DocNameToOffsetMap : public SHash<DocNameToOffsetMapTraits>
-{
-    typedef SHash<DocNameToOffsetMapTraits> PARENT;
-    typedef LPCSTR KEY;
-    typedef DocNameOffsets VALUE;
-
-public:
-    void Add(KEY key, VALUE value)
-    {
-        CONTRACTL
-        {
-            THROWS;
-            GC_NOTRIGGER;
-            PRECONDITION(key != (KEY)0);
-        }
-        CONTRACTL_END;
-
-        PARENT::Add(KeyValuePair<KEY,VALUE>(key, value));
-    }
-
-    void AddOrReplace(KEY key, VALUE value)
-    {
-        CONTRACTL
-        {
-            THROWS;
-            GC_NOTRIGGER;
-            PRECONDITION(key != (KEY)0);
-        }
-        CONTRACTL_END;
-
-        PARENT::AddOrReplace(KeyValuePair<KEY,VALUE>(key, value));
-    }
-
-    BOOL Lookup(KEY key, VALUE* pValue)
-    {
-        CONTRACTL
-        {
-            NOTHROW;
-            GC_NOTRIGGER;
-            PRECONDITION(key != (KEY)0);
-        }
-        CONTRACTL_END;
-
-        const KeyValuePair<KEY,VALUE> *pRet = PARENT::LookupPtr(key);
-        if (pRet == NULL)
-            return FALSE;
-
-        *pValue = pRet->Value();
-        return TRUE;
-    }
-};
-
-// ----------------------------------------------------------------------------
-// Simple class to sort ICorDebugInfo::OffsetMapping arrays by IL offset
-//
-class QuickSortILNativeMapByIL : public CQuickSort<ICorDebugInfo::OffsetMapping>
-{
-  public:
-    QuickSortILNativeMapByIL(
-        ICorDebugInfo::OffsetMapping * rgMap,
-        int cEntries)
-      : CQuickSort<ICorDebugInfo::OffsetMapping>(rgMap, cEntries)
-    {
-        LIMITED_METHOD_CONTRACT;
-    }
-
-    int Compare(ICorDebugInfo::OffsetMapping * pFirst,
-                ICorDebugInfo::OffsetMapping * pSecond)
-    {
-        LIMITED_METHOD_CONTRACT;
-
-        if (pFirst->ilOffset < pSecond->ilOffset)
-            return -1;
-        else if (pFirst->ilOffset == pSecond->ilOffset)
-            return 0;
-        else
-            return 1;
-    }
-};
-
-// ----------------------------------------------------------------------------
-// Simple class to sort IL to Native mapping arrays by Native offset
-//
-class QuickSortILNativeMapByNativeOffset : public CQuickSort<ICorDebugInfo::OffsetMapping>
-{
-public:
-    QuickSortILNativeMapByNativeOffset(
-        ICorDebugInfo::OffsetMapping * rgMap,
-        int cEntries)
-        : CQuickSort<ICorDebugInfo::OffsetMapping>(rgMap, cEntries)
-    {
-        LIMITED_METHOD_CONTRACT;
-    }
-
-    int Compare(ICorDebugInfo::OffsetMapping * pFirst,
-        ICorDebugInfo::OffsetMapping * pSecond)
-    {
-        LIMITED_METHOD_CONTRACT;
-
-        if (pFirst->nativeOffset < pSecond->nativeOffset)
-            return -1;
-        else if (pFirst->nativeOffset == pSecond->nativeOffset)
-            return 0;
-        else
-            return 1;
-    }
-};
-
-// ----------------------------------------------------------------------------
-// Simple structure used when merging the JIT manager's IL-to-native maps
-// (ICorDebugInfo::OffsetMapping) with the IL PDB's source-to-IL map.
-//
-struct MapIndexPair
-{
-public:
-    // Index into ICorDebugInfo::OffsetMapping
-    ULONG32 m_iIlNativeMap;
-
-    // Corresponding index into the IL PDB's sequence point arrays
-    ULONG32 m_iSeqPoints;
-
-    MapIndexPair() :
-        m_iIlNativeMap((ULONG32) -1),
-        m_iSeqPoints((ULONG32) -1)
-    {
-        LIMITED_METHOD_CONTRACT;
-    }
-};
-
-// ----------------------------------------------------------------------------
-// Simple class to sort MapIndexPairs by native IP offset. A MapIndexPair sorts "earlier"
-// if its m_iIlNativeMap index gives you an IP offset (i.e.,
-// m_rgIlNativeMap[m_iIlNativeMap].nativeOffset) that is smaller.
-//
-class QuickSortMapIndexPairsByNativeOffset : public CQuickSort<MapIndexPair>
-{
-  public:
-    QuickSortMapIndexPairsByNativeOffset(
-        MapIndexPair * rgMap,
-        int cEntries,
-        ICorDebugInfo::OffsetMapping * rgIlNativeMap,
-        ULONG32 cIlNativeMap)
-        : CQuickSort<MapIndexPair>(rgMap, cEntries),
-          m_rgIlNativeMap(rgIlNativeMap),
-          m_cIlNativeMap(cIlNativeMap)
-    {
-        LIMITED_METHOD_CONTRACT;
-    }
-
-    int Compare(MapIndexPair * pFirst,
-                MapIndexPair * pSecond)
-    {
-        LIMITED_METHOD_CONTRACT;
-
-        _ASSERTE(pFirst->m_iIlNativeMap < m_cIlNativeMap);
-        _ASSERTE(pSecond->m_iIlNativeMap < m_cIlNativeMap);
-
-        DWORD dwFirstNativeOffset = m_rgIlNativeMap[pFirst->m_iIlNativeMap].nativeOffset;
-        DWORD dwSecondNativeOffset = m_rgIlNativeMap[pSecond->m_iIlNativeMap].nativeOffset;
-
-        if (dwFirstNativeOffset < dwSecondNativeOffset)
-            return -1;
-        else if (dwFirstNativeOffset == dwSecondNativeOffset)
-            return 0;
-        else
-            return 1;
-    }
-
-protected:
-    ICorDebugInfo::OffsetMapping * m_rgIlNativeMap;
-    ULONG32 m_cIlNativeMap;
-};
-
-// ----------------------------------------------------------------------------
-// The following 3 classes contain the code to generate PDBs
-//
-
-// NGEN always generates PDBs with public symbols lists (so tools can map IP ranges to
-// methods).  This bitmask indicates what extra info should be added to the PDB
-enum PDBExtraData
-{
-    // Add string table subsection, files checksum subsection, and lines subsection to
-    // allow tools to map IP ranges to source lines.
-    kPDBLines  = 0x00000001,
-};
-
-
-// ----------------------------------------------------------------------------
-// Manages generating all PDB data for an NGENd image.  One of these is instantiated per
-// run of "ngen createpdb"
-//
-class NGenPdbWriter
-{
-private:
-    CreateNGenPdbWriter_t m_Create;
-    HMODULE m_hModule;
-    ReleaseHolder<ISymUnmanagedBinder> m_pBinder;
-    LPCWSTR m_wszPdbPath;
-    DWORD m_dwExtraData;
-    LPCWSTR m_wszManagedPDBSearchPath;
-
-public:
-    NGenPdbWriter (LPCWSTR wszNativeImagePath, LPCWSTR wszPdbPath, DWORD dwExtraData, LPCWSTR wszManagedPDBSearchPath)
-        : m_Create(NULL),
-          m_hModule(NULL),
-          m_wszPdbPath(wszPdbPath),
-          m_dwExtraData(dwExtraData),
-          m_wszManagedPDBSearchPath(wszManagedPDBSearchPath)
-    {
-        LIMITED_METHOD_CONTRACT;
-    }
-
-#define WRITER_LOAD_ERROR_MESSAGE W("Unable to load ") NATIVE_SYMBOL_READER_DLL W(".  Please ensure that ") NATIVE_SYMBOL_READER_DLL W(" is on the path.  Error='%d'\n")
-
-    HRESULT Load(LPCWSTR wszDiasymreaderPath = nullptr)
-    {
-        STANDARD_VM_CONTRACT;
-
-        HRESULT hr = S_OK;
-
-        m_hModule = WszLoadLibrary(wszDiasymreaderPath != nullptr ? wszDiasymreaderPath : (LPCWSTR)NATIVE_SYMBOL_READER_DLL);
-        if (m_hModule == NULL)
-        {
-            hr = HRESULT_FROM_WIN32(GetLastError());
-            GetSvcLogger()->Printf(WRITER_LOAD_ERROR_MESSAGE, GetLastError());
-            return hr;
-        }
-
-        m_Create = reinterpret_cast<CreateNGenPdbWriter_t>(GetProcAddress(m_hModule, "CreateNGenPdbWriter"));
-        if (m_Create == NULL)
-        {
-            hr = HRESULT_FROM_WIN32(GetLastError());
-            GetSvcLogger()->Printf(WRITER_LOAD_ERROR_MESSAGE, GetLastError());
-            return hr;
-        }
-
-        if ((m_dwExtraData & kPDBLines) != 0)
-        {
-            hr = FakeCoCreateInstanceEx(
-                CLSID_CorSymBinder_SxS,
-                wszDiasymreaderPath != nullptr ? wszDiasymreaderPath : (LPCWSTR)NATIVE_SYMBOL_READER_DLL,
-                IID_ISymUnmanagedBinder,
-                (void**)&m_pBinder,
-                NULL);
-        }
-
-        return hr;
-    }
-
-    HRESULT WritePDBDataForModule(Module * pModule);
-
-    ~NGenPdbWriter()
-    {
-        LIMITED_METHOD_CONTRACT;
-
-        if (m_hModule)
-            FreeLibrary(m_hModule);
-
-        m_Create = NULL;
-    }
-};
-
-#define UNKNOWN_SOURCE_FILE_PATH W("unknown")
-
-// ----------------------------------------------------------------------------
-// Manages generating all PDB data for an EE Module. Directly responsible for writing the
-// string table and file checksum subsections. One of these is instantiated per Module
-// found when using the ModuleIterator over the CORINFO_ASSEMBLY_HANDLE corresponding to
-// this invocation of NGEN createpdb.
-//
-class NGenModulePdbWriter
-{
-private:
-    // Simple holder to coordinate the PDB calls to OpenModW and CloseMod on a given PDB
-    // Mod *.
-    class PDBModHolder
-    {
-    private:
-        ReleaseHolder<ISymNGenWriter2> m_pWriter;
-        LPBYTE m_pMod;
-
-    public:
-        PDBModHolder()
-            : m_pWriter(NULL),
-              m_pMod(NULL)
-        {
-            LIMITED_METHOD_CONTRACT;
-        }
-
-        ~PDBModHolder()
-        {
-            LIMITED_METHOD_CONTRACT;
-
-            if ((m_pWriter != NULL) && (m_pMod != NULL))
-            {
-                m_pWriter->CloseMod(m_pMod);
-            }
-        }
-
-        HRESULT Open(ISymNGenWriter2 * pWriter, LPCWSTR wszModule, LPCWSTR wszObjFile)
-        {
-            LIMITED_METHOD_CONTRACT;
-
-            _ASSERTE(m_pWriter == NULL);
-
-            m_pWriter = pWriter;
-            m_pWriter->AddRef();
-
-            _ASSERTE(m_pMod == NULL);
-
-            HRESULT hr = m_pWriter->OpenModW(wszModule, wszObjFile, &m_pMod);
-            if (FAILED(hr))
-            {
-                m_pMod = NULL;
-            }
-            return hr;
-        }
-
-        LPBYTE GetModPtr()
-        {
-            LIMITED_METHOD_CONTRACT;
-
-            _ASSERTE(m_pMod != NULL);
-            return m_pMod;
-        }
-    };
-
-private:
-    // This holder ensures we delete a half-generated PDB file if we manage to create it
-    // on disk, but fail at some point after it was created. When NGenModulePdbWriter is
-    // destroyed, m_deletePDBFileHolder's destructor will delete the PDB file if there
-    // was a prior error.
-    //
-    //************* NOTE! *************
-    //
-    // These members should appear FIRST so that they get destructed last. That way, if
-    // we encounter an error generating the PDB file, we ensure that we release all PDB
-    // interfaces and close the PDB file BEFORE this holder tries to *delete* the PDB
-    // file. Also, keep these two in this relative order, so that m_deletePDBFileHolder
-    // is destructed before m_wszPDBFilePath.
-    WCHAR m_wszPDBFilePath[MAX_LONGPATH];
-    DeleteFileHolder m_deletePDBFileHolder;
-    //
-    // ************* NOTE! *************
-
-    CreateNGenPdbWriter_t m_Create;
-    LPCWSTR m_wszPdbPath;
-    ReleaseHolder<ISymNGenWriter2> m_pWriter;
-    Module * m_pModule;
-    DWORD m_dwExtraData;
-    LPCWSTR m_wszManagedPDBSearchPath;
-
-    // Currently The DiasymWriter does not use the correct PDB signature for NGEN PDBS unless
-    // the NGEN DLL whose symbols are being generated end in .ni.dll.   Thus we copy
-    // to this name if it does not follow this covention (as is true with readyToRun
-    // dlls).   This variable remembers this temp file path so we can delete it after
-    // Pdb generation.   If DiaSymWriter is fixed, we can remove this.
-    SString m_tempSourceDllName;
-
-    // Interfaces for reading IL PDB info
-    ReleaseHolder<ISymUnmanagedBinder> m_pBinder;
-    ReleaseHolder<ISymUnmanagedReader> m_pReader;
-    NewInterfaceArrayHolder<ISymUnmanagedDocument> m_rgpDocs;       // All docs in the PDB Mod
-    // I know m_ilPdbCount and m_finalPdbDocCount are confusing.Here is the reason :
-    // For NGenMethodLinesPdbWriter::WriteDebugSILLinesSubsection, we won't write the path info.
-    // In order to let WriteDebugSILLinesSubsection find "UNKNOWN_SOURCE_FILE_PATH" which does
-    // not exist in m_rgpDocs, no matter if we have IL PDB or not, we let m_finalPdbDocCount
-    // equal m_ilPdbDocCount + 1 and write the extra one path as "UNKNOWN_SOURCE_FILE_PATH"
-    ULONG32 m_ilPdbDocCount;
-    ULONG32 m_finalPdbDocCount;
-
-    // Keeps track of source file names and how they map to offsets in the relevant PDB
-    // subsections.
-    DocNameToOffsetMap m_docNameToOffsetMap;
-
-    // Holds a PDB Mod *
-    PDBModHolder m_pdbMod;
-
-    // Buffer in which to store the entire string table (i.e., list of all source file
-    // names).  This buffer is held alive as long as m_docNameToOffsetMap is needed, as
-    // the latter contains offsets into this buffer.
-    NewArrayHolder<BYTE> m_rgbStringTableSubsection;
-
-    HRESULT InitILPdbData();
-    HRESULT WriteStringTable();
-    HRESULT WriteFileChecksums();
-
-public:
-    NGenModulePdbWriter(CreateNGenPdbWriter_t Create, LPCWSTR wszPdbPath, DWORD dwExtraData, ISymUnmanagedBinder * pBinder, Module * pModule, LPCWSTR wszManagedPDBSearchPath)
-        : m_Create(Create),
-          m_wszPdbPath(wszPdbPath),
-          m_pWriter(NULL),
-          m_pModule(pModule),
-          m_dwExtraData(dwExtraData),
-          m_wszManagedPDBSearchPath(wszManagedPDBSearchPath),
-          m_pBinder(pBinder),
-          m_ilPdbDocCount(0),
-          m_finalPdbDocCount(1)
-    {
-        LIMITED_METHOD_CONTRACT;
-
-        if (m_pBinder != NULL)
-            m_pBinder->AddRef();
-
-        ZeroMemory(m_wszPDBFilePath, sizeof(m_wszPDBFilePath));
-    }
-
-    ~NGenModulePdbWriter();
-
-    HRESULT WritePDBData();
-
-    HRESULT WriteMethodPDBData(PEImageLayout * pLoadedLayout, USHORT iCodeSection, BYTE *pCodeBase, MethodDesc * hotDesc, PCODE start, bool isILPDBProvided);
-};
-
-// ----------------------------------------------------------------------------
-// Manages generating the lines subsection in the PDB data for a given managed method.
-// One of these is instantiated per managed method we find when iterating through all
-// methods in a Module.
-//
-class NGenMethodLinesPdbWriter
-{
-private:
-    ISymNGenWriter2 * m_pWriter;
-    LPBYTE m_pMod;
-    ISymUnmanagedReader * m_pReader;
-    MethodDesc * m_hotDesc;
-    PCODE m_start;
-    USHORT m_iCodeSection;
-    TADDR m_addrCodeSection;
-    const IJitManager::MethodRegionInfo * m_pMethodRegionInfo;
-    EECodeInfo * m_pCodeInfo;
-    DocNameToOffsetMap * m_pDocNameToOffsetMap;
-    bool m_isILPDBProvided;
-
-    // IL-to-native map from JIT manager
-    ULONG32 m_cIlNativeMap;
-    NewArrayHolder<ICorDebugInfo::OffsetMapping> m_rgIlNativeMap;
-
-    // IL PDB info for this one method
-    NewInterfaceArrayHolder<ISymUnmanagedDocument> m_rgpDocs;  // Source files defining this method.
-    NewArrayHolder<ULONG32> m_rgilOffsets;                     // Array of IL offsets for this method
-    NewArrayHolder<ULONG32> m_rgnLineStarts;                   // Array of source lines for this method
-    ULONG32 m_cSeqPoints;                                      // Count of above two parallel arrays
-
-    HRESULT WriteNativeILMapPDBData();
-    LPBYTE InitDebugLinesHeaderSection(
-        DEBUG_S_SUBSECTION_TYPE type,
-        ULONG32 ulCodeStartOffset,
-        ULONG32 cbCode,
-        ULONG32 lineSize,
-        CV_DebugSSubsectionHeader_t **ppSubSectHeader /*out*/,
-        CV_DebugSLinesHeader_t ** ppLinesHeader /*out*/,
-        LPBYTE * ppbLinesSubsectionCur /*out*/);
-
-    HRESULT WriteDebugSLinesSubsection(
-        ULONG32 ulCodeStartOffset,
-        ULONG32 cbCode,
-        MapIndexPair * rgMapIndexPairs,
-        ULONG32 cMapIndexPairs);
-
-    HRESULT WriteDebugSILLinesSubsection(
-        ULONG32 ulCodeStartOffset,
-        ULONG32 cbCode,
-        ICorDebugInfo::OffsetMapping * rgILNativeMap,
-        ULONG32 rgILNativeMapAdjustSize);
-
-    BOOL FinalizeLinesFileBlock(
-        CV_DebugSLinesFileBlockHeader_t * pLinesFileBlockHeader,
-        CV_Line_t * pLineBlockStart,
-        CV_Line_t * pLineBlockAfterEnd
-#ifdef _DEBUG
-        , BOOL ignorekUnmappedIPCheck = false
-#endif
-        );
-
-public:
-    NGenMethodLinesPdbWriter(
-        ISymNGenWriter2 * pWriter,
-        LPBYTE pMod,
-        ISymUnmanagedReader * pReader,
-        MethodDesc * hotDesc,
-        PCODE start,
-        USHORT iCodeSection,
-        TADDR addrCodeSection,
-        const IJitManager::MethodRegionInfo * pMethodRegionInfo,
-        EECodeInfo * pCodeInfo,
-        DocNameToOffsetMap * pDocNameToOffsetMap,
-        bool isILPDBProvided)
-        : m_pWriter(pWriter),
-          m_pMod(pMod),
-          m_pReader(pReader),
-          m_hotDesc(hotDesc),
-          m_start(start),
-          m_iCodeSection(iCodeSection),
-          m_addrCodeSection(addrCodeSection),
-          m_pMethodRegionInfo(pMethodRegionInfo),
-          m_pCodeInfo(pCodeInfo),
-          m_pDocNameToOffsetMap(pDocNameToOffsetMap),
-          m_isILPDBProvided(isILPDBProvided),
-          m_cIlNativeMap(0),
-          m_cSeqPoints(0)
-    {
-        LIMITED_METHOD_CONTRACT;
-    }
-
-    HRESULT WritePDBData();
-};
-
-// ----------------------------------------------------------------------------
-// NGenPdbWriter implementation
-
-
-
-//---------------------------------------------------------------------------------------
-//
-// Coordinates calling all the other classes & methods to generate PDB info for the
-// given Module
-//
-// Arguments:
-//      pModule - EE Module to write PDB data for
-//
-
-HRESULT NGenPdbWriter::WritePDBDataForModule(Module * pModule)
-{
-    STANDARD_VM_CONTRACT;
-    NGenModulePdbWriter ngenModulePdbWriter(m_Create, m_wszPdbPath, m_dwExtraData, m_pBinder, pModule, m_wszManagedPDBSearchPath);
-    return ngenModulePdbWriter.WritePDBData();
-}
-
-
-// ----------------------------------------------------------------------------
-// NGenModulePdbWriter implementation
-
-
-//---------------------------------------------------------------------------------------
-//
-// Writes out all source files into the string table subsection for the PDB Mod*
-// controlled by this NGenModulePdbWriter.  Updates m_docNameToOffsetMap to add string
-// table offset for each source file as it gets added.
-//
-HRESULT NGenModulePdbWriter::WriteStringTable()
-{
-    STANDARD_VM_CONTRACT;
-
-    _ASSERTE(m_pWriter != NULL);
-
-    HRESULT hr;
-    UINT64 cbStringTableEstimate =
-        sizeof(DWORD) +
-        sizeof(CV_DebugSSubsectionHeader_t) +
-        m_finalPdbDocCount * (MAX_LONGPATH + 1);
-    if (!FitsIn<ULONG32>(cbStringTableEstimate))
-    {
-        return HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER);
-    }
-
-    m_rgbStringTableSubsection = new BYTE[ULONG32(cbStringTableEstimate)];
-    LPBYTE pbStringTableSubsectionCur = m_rgbStringTableSubsection;
-
-    // Subsection signature
-    *((DWORD *) pbStringTableSubsectionCur) = CV_SIGNATURE_C13;
-    pbStringTableSubsectionCur += sizeof(DWORD);
-
-    // Subsection header
-    CV_DebugSSubsectionHeader_t * pSubSectHeader = (CV_DebugSSubsectionHeader_t *) pbStringTableSubsectionCur;
-    memset(pSubSectHeader, 0, sizeof(*pSubSectHeader));
-    pSubSectHeader->type = DEBUG_S_STRINGTABLE;
-    pbStringTableSubsectionCur += sizeof(*pSubSectHeader);
-    // pSubSectHeader->cbLen counts the number of bytes that appear AFTER the subsection
-    // header above (i.e., the size of the string table itself). We'll fill out
-    // pSubSectHeader->cbLen below, once it's calculated
-
-    LPBYTE pbStringTableStart = pbStringTableSubsectionCur;
-
-    // The actual strings
-    for (ULONG32 i = 0; i < m_finalPdbDocCount; i++)
-    {
-        // For NGenMethodLinesPdbWriter::WriteDebugSILLinesSubsection, we won't write the path info.
-        // In order to let WriteDebugSILLinesSubsection can find "UNKNOWN_SOURCE_FILE_PATH" which is
-        // not existed in m_rgpDocs, no matter we have IL PDB or not, we let m_finalPdbDocCount equals to
-        // m_ilPdbDocCount + 1 and write the extra one path as "UNKNOWN_SOURCE_FILE_PATH". That also explains
-        // why we have a inconsistence between m_finalPdbDocCount and m_ilPdbDocCount.
-        WCHAR wszURL[MAX_LONGPATH] = UNKNOWN_SOURCE_FILE_PATH;
-        ULONG32 cchURL;
-        if (i < m_ilPdbDocCount)
-        {
-            hr = m_rgpDocs[i]->GetURL(_countof(wszURL), &cchURL, wszURL);
-            if (FAILED(hr))
-                return hr;
-        }
-        int cbWritten = WideCharToMultiByte(
-            CP_UTF8,
-            0,                                      // dwFlags
-            wszURL,
-            -1,                                     // i.e., input is NULL-terminated
-            (LPSTR) pbStringTableSubsectionCur,     // output: UTF8 string starts here
-            ULONG32(cbStringTableEstimate) -
-                int(pbStringTableSubsectionCur - m_rgbStringTableSubsection),    // Available space
-            NULL,                                   // lpDefaultChar
-            NULL                                    // lpUsedDefaultChar
-            );
-        if (cbWritten == 0)
-            return HRESULT_FROM_WIN32(GetLastError());
-
-        // Remember the string table offset for later
-        m_docNameToOffsetMap.AddOrReplace(
-            (LPCSTR) pbStringTableSubsectionCur,
-            DocNameOffsets(
-                ULONG32(pbStringTableSubsectionCur - pbStringTableStart),
-                (ULONG32) -1));
-
-        pbStringTableSubsectionCur += cbWritten;
-        if (pbStringTableSubsectionCur >= (m_rgbStringTableSubsection + cbStringTableEstimate))
-            return HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER);
-    }
-
-    // Now that we know pSubSectHeader->cbLen, fill it in
-    pSubSectHeader->cbLen = CV_off32_t(pbStringTableSubsectionCur - pbStringTableStart);
-
-    // Subsection is now filled out, so use the PDB API to add it
-    hr = m_pWriter->ModAddSymbols(
-        m_pdbMod.GetModPtr(),
-        m_rgbStringTableSubsection,
-        int(pbStringTableSubsectionCur - m_rgbStringTableSubsection));
-    if (FAILED(hr))
-        return hr;
-
-    return S_OK;
-}
-
-//---------------------------------------------------------------------------------------
-//
-// This takes care of actually loading the IL PDB itself, and initializing the
-// ISymUnmanaged* interfaces with module-level data from the IL PDB.
-//
-HRESULT NGenModulePdbWriter::InitILPdbData()
-{
-    // Load the managed PDB
-
-    ReleaseHolder<IUnknown> pUnk = NULL;
-    HRESULT hr = m_pModule->GetReadablePublicMetaDataInterface(ofReadOnly, IID_IMetaDataImport, (LPVOID *) &pUnk);
-    if (FAILED(hr))
-    {
-        GetSvcLogger()->Printf(
-            W("Unable to obtain metadata for '%s'  Error: '0x%x'.\n"),
-            LPCWSTR(m_pModule->GetFile()->GetILimage()->GetPath()),
-            hr);
-        return hr;
-    }
-
-    hr = m_pBinder->GetReaderForFile(
-        pUnk,
-        m_pModule->GetFile()->GetILimage()->GetPath(),
-        m_wszManagedPDBSearchPath,
-        &m_pReader);
-    if (FAILED(hr))
-    {
-        GetSvcLogger()->Printf(
-            W("Unable to find managed PDB matching '%s'.  Managed PDB search path: '%s'\n"),
-            LPCWSTR(m_pModule->GetFile()->GetILimage()->GetPath()),
-            (((m_wszManagedPDBSearchPath == NULL) || (*m_wszManagedPDBSearchPath == W('\0'))) ?
-                W("(not specified)") :
-                m_wszManagedPDBSearchPath));
-        return hr;
-    }
-
-    GetSvcLogger()->Log(W("Loaded managed PDB"));
-
-    // Grab the full path of the managed PDB so we can log it
-    WCHAR wszIlPdbPath[MAX_LONGPATH];
-    ULONG32 cchIlPdbPath;
-    hr = m_pReader->GetSymbolStoreFileName(
-        _countof(wszIlPdbPath),
-        &cchIlPdbPath,
-        wszIlPdbPath);
-    if (FAILED(hr))
-    {
-        GetSvcLogger()->Log(W("\n"));
-    }
-    else
-    {
-        GetSvcLogger()->Printf(W(": '%s'\n"), wszIlPdbPath);
-    }
-
-    // Read all source files names from the IL PDB
-    ULONG32 cDocs;
-    hr = m_pReader->GetDocuments(
-        0,              // cDocsRequested
-        &cDocs,
-        NULL            // Array
-        );
-    if (FAILED(hr))
-        return hr;
-
-    m_rgpDocs = new ISymUnmanagedDocument * [cDocs];
-    hr = m_pReader->GetDocuments(
-        cDocs,
-        &m_ilPdbDocCount,
-        m_rgpDocs);
-    if (FAILED(hr))
-        return hr;
-    m_finalPdbDocCount = m_ilPdbDocCount + 1;
-    // Commit m_rgpDocs to calling Release() on each ISymUnmanagedDocument* in the array
-    m_rgpDocs.SetElementCount(m_ilPdbDocCount);
-
-    return S_OK;
-}
-
-NGenModulePdbWriter::~NGenModulePdbWriter()
-{
-    // Delete any temporary files we created.
-    if (m_tempSourceDllName.GetCount() != 0)
-        DeleteFileW(m_tempSourceDllName);
-    m_tempSourceDllName.Clear();
-}
-
-//---------------------------------------------------------------------------------------
-//
-// This manages writing all Module-level data to the PDB, including public symbols,
-// string table, files checksum, section contribution table, and, indirectly, the lines
-// subsection
-//
-HRESULT NGenModulePdbWriter::WritePDBData()
-{
-    STANDARD_VM_CONTRACT;
-
-    _ASSERTE(m_pWriter == NULL);
-
-    HRESULT hr;
-
-    // This will try to open the managed PDB if lines info was requested.  This is a
-    // likely failure point, so intentionally do this before creating the NGEN PDB file
-    // on disk.
-    bool isILPDBProvided = false;
-    if ((m_dwExtraData & kPDBLines) != 0)
-    {
-        hr = InitILPdbData();
-        if (FAILED(hr))
-            return hr;
-        isILPDBProvided = true;
-    }
-
-    // Create the PDB file we will write into.
-
-    _ASSERTE(m_Create != NULL);
-    _ASSERTE(m_pModule != NULL);
-
-    PEImageLayout * pLoadedLayout = m_pModule->GetFile()->GetLoaded();
-
-    // Currently DiaSymReader does not work properly generating NGEN PDBS unless
-    // the DLL whose PDB is being generated ends in .ni.*.   Unfortunately, readyToRun
-    // images do not follow this convention and end up producing bad PDBS.  To fix
-    // this (without changing diasymreader.dll which ships indepdendently of .NET Core)
-    // we copy the file to somethign with this convention before generating the PDB
-    // and delete it when we are done.
-    SString dllPath = pLoadedLayout->GetPath();
-    if (!dllPath.EndsWithCaseInsensitive(W(".ni.dll")) && !dllPath.EndsWithCaseInsensitive(W(".ni.exe")))
-    {
-        SString::Iterator fileNameStart = dllPath.End();
-        if (!dllPath.FindBack(fileNameStart, DIRECTORY_SEPARATOR_STR_W))
-            fileNameStart = dllPath.Begin();
-
-        SString::Iterator ext = dllPath.End();
-        dllPath.FindBack(ext, '.');
-
-        // m_tempSourceDllName = Convertion of  INPUT.dll  to INPUT.ni.dll where the PDB lives.
-        m_tempSourceDllName = m_wszPdbPath;
-        m_tempSourceDllName += SString(dllPath, fileNameStart, ext - fileNameStart);
-        m_tempSourceDllName += W(".ni");
-        m_tempSourceDllName += SString(dllPath, ext, dllPath.End() - ext);
-        CopyFileW(dllPath, m_tempSourceDllName, false);
-        dllPath = m_tempSourceDllName;
-    }
-
-    ReleaseHolder<ISymNGenWriter> pWriter1;
-    hr = m_Create(dllPath, m_wszPdbPath, &pWriter1);
-    if (FAILED(hr))
-        return hr;
-
-    hr = pWriter1->QueryInterface(IID_ISymNGenWriter2, (LPVOID*) &m_pWriter);
-    if (FAILED(hr))
-    {
-        GetSvcLogger()->Printf(
-            W("An incorrect version of diasymreader.dll was found.  Please ensure that version 11 or greater of diasymreader.dll is on the path.  You can typically find this DLL in the desktop .NET install directory for 4.5 or greater.  Error='0x%x'\n"),
-            hr);
-        return hr;
-    }
-
-    // PDB file is now created.  Get its path and initialize the holder so the PDB file
-    // can be deleted if we don't make it successfully to the end
-
-    hr = m_pWriter->QueryPDBNameExW(m_wszPDBFilePath, _countof(m_wszPDBFilePath));
-    if (SUCCEEDED(hr))
-    {
-        // A failure in QueryPDBNameExW above isn't fatal--it just means we can't
-        // initialize m_deletePDBFileHolder, and thus may leave the PDB file on disk if
-        // there's *another* error later on. And if we do hit another error, NGEN will
-        // still return an error exit code, so the worst we'll have is a bogus PDB file
-        // that no one should expect works anyway.
-        m_deletePDBFileHolder.Assign(m_wszPDBFilePath);
-    }
-
-
-    hr = m_pdbMod.Open(m_pWriter, pLoadedLayout->GetPath(), m_pModule->GetPath());
-    if (FAILED(hr))
-        return hr;
-
-    hr = WriteStringTable();
-    if (FAILED(hr))
-        return hr;
-
-    hr = WriteFileChecksums();
-    if (FAILED(hr))
-        return hr;
-
-
-    COUNT_T sectionCount = pLoadedLayout->GetNumberOfSections();
-    IMAGE_SECTION_HEADER *section = pLoadedLayout->FindFirstSection();
-    COUNT_T sectionIndex = 0;
-    USHORT iCodeSection = 0;
-    BYTE *pCodeBase = NULL;
-    while (sectionIndex < sectionCount)
-    {
-        hr = m_pWriter->AddSection((USHORT)(sectionIndex + 1),
-                                 OMF_StandardText,
-                                 0,
-                                 section[sectionIndex].SizeOfRawData);
-        if (FAILED(hr))
-            return hr;
-
-        if (strcmp((const char *)&section[sectionIndex].Name[0], ".text") == 0) {
-            _ASSERTE((iCodeSection == 0) && (pCodeBase == NULL));
-            iCodeSection = (USHORT)(sectionIndex + 1);
-            pCodeBase = (BYTE *)(size_t)section[sectionIndex].VirtualAddress;
-        }
-
-        // In order to support the DIA RVA-to-lines API against the PDB we're
-        // generating, we need to update the section contribution table with each
-        // section we add.
-        hr = m_pWriter->ModAddSecContribEx(
-            m_pdbMod.GetModPtr(),
-            (USHORT)(sectionIndex + 1),
-            0,
-            section[sectionIndex].SizeOfRawData,
-            section[sectionIndex].Characteristics,
-            0,          // dwDataCrc
-            0           // dwRelocCrc
-            );
-        if (FAILED(hr))
-            return hr;
-
-        sectionIndex++;
-    }
-
-    _ASSERTE(iCodeSection != 0);
-    _ASSERTE(pCodeBase != NULL);
-
-
-    // To support lines info, we need a "dummy" section, indexed as 0, for use as a
-    // sentinel when MSPDB sets up its section contribution table
-    hr = m_pWriter->AddSection(0,           // Dummy section 0
-        OMF_SentinelType,
-        0,
-        0xFFFFffff);
-    if (FAILED(hr))
-        return hr;
-
-
-#ifdef FEATURE_READYTORUN_COMPILER
-    if (pLoadedLayout->HasReadyToRunHeader())
-    {
-        ReadyToRunInfo::MethodIterator mi(m_pModule->GetReadyToRunInfo());
-        while (mi.Next())
-        {
-            MethodDesc *hotDesc = mi.GetMethodDesc();
-
-            hr = WriteMethodPDBData(pLoadedLayout, iCodeSection, pCodeBase, hotDesc, mi.GetMethodStartAddress(), isILPDBProvided);
-            if (FAILED(hr))
-                return hr;
-        }
-    }
-    else
-#endif // FEATURE_READYTORUN_COMPILER
-    {
-        MethodIterator mi(m_pModule);
-        while (mi.Next())
-        {
-            MethodDesc *hotDesc = mi.GetMethodDesc();
-            hotDesc->CheckRestore();
-
-            hr = WriteMethodPDBData(pLoadedLayout, iCodeSection, pCodeBase, hotDesc, mi.GetMethodStartAddress(), isILPDBProvided);
-            if (FAILED(hr))
-                return hr;
-        }
-    }
-
-    // We made it successfully to the end, so don't delete the PDB file.
-    m_deletePDBFileHolder.SuppressRelease();
-    return S_OK;
-}
-
-HRESULT NGenModulePdbWriter::WriteMethodPDBData(PEImageLayout * pLoadedLayout, USHORT iCodeSection, BYTE *pCodeBase, MethodDesc * hotDesc, PCODE start, bool isILPDBProvided)
-{
-    STANDARD_VM_CONTRACT;
-
-    HRESULT hr;
-
-    EECodeInfo codeInfo(start);
-    _ASSERTE(codeInfo.IsValid());
-
-    IJitManager::MethodRegionInfo methodRegionInfo;
-    codeInfo.GetMethodRegionInfo(&methodRegionInfo);
-
-    PCODE pHotCodeStart = methodRegionInfo.hotStartAddress;
-    _ASSERTE(pHotCodeStart);
-
-    PCODE pColdCodeStart = methodRegionInfo.coldStartAddress;
-    SString mAssemblyName;
-    mAssemblyName.SetUTF8(m_pModule->GetAssembly()->GetSimpleName());
-    SString assemblyName;
-    assemblyName.SetUTF8(hotDesc->GetAssembly()->GetSimpleName());
-    SString methodToken;
-    methodToken.Printf("%X", hotDesc->GetMemberDef());
-
-    // Hot name
-    {
-        SString fullName;
-        TypeString::AppendMethodInternal(
-            fullName,
-            hotDesc,
-            TypeString::FormatNamespace | TypeString::FormatSignature);
-        fullName.Append(W("$#"));
-        if (!mAssemblyName.Equals(assemblyName))
-            fullName.Append(assemblyName);
-        fullName.Append(W("#"));
-        fullName.Append(methodToken);
-        BSTRHolder hotNameHolder(SysAllocString(fullName.GetUnicode()));
-        hr = m_pWriter->AddSymbol(hotNameHolder,
-                                iCodeSection,
-                                (pHotCodeStart - (TADDR)pLoadedLayout->GetBase() - (TADDR)pCodeBase));
-        if (FAILED(hr))
-            return hr;
-    }
-
-    // Cold name
-    {
-        if (pColdCodeStart) {
-
-            SString fullNameCold;
-            fullNameCold.Append(W("[COLD] "));
-            TypeString::AppendMethodInternal(
-                fullNameCold,
-                hotDesc,
-                TypeString::FormatNamespace | TypeString::FormatSignature);
-            fullNameCold.Append(W("$#"));
-            if (!mAssemblyName.Equals(assemblyName))
-                fullNameCold.Append(assemblyName);
-            fullNameCold.Append(W("#"));
-            fullNameCold.Append(methodToken);
-
-            BSTRHolder coldNameHolder(SysAllocString(fullNameCold.GetUnicode()));
-            hr = m_pWriter->AddSymbol(coldNameHolder,
-                                    iCodeSection,
-                                    (pColdCodeStart - (TADDR)pLoadedLayout->GetBase() - (TADDR)pCodeBase));
-
-            if (FAILED(hr))
-                return hr;
-
-        }
-    }
-
-    // Offset / lines mapping
-    // Skip functions that are too big for PDB lines format
-    if (FitsIn<DWORD>(methodRegionInfo.hotSize) &&
-        FitsIn<DWORD>(methodRegionInfo.coldSize))
-    {
-        NGenMethodLinesPdbWriter methodLinesWriter(
-            m_pWriter,
-            m_pdbMod.GetModPtr(),
-            m_pReader,
-            hotDesc,
-            start,
-            iCodeSection,
-            (TADDR)pLoadedLayout->GetBase() + (TADDR)pCodeBase,
-            &methodRegionInfo,
-            &codeInfo,
-            &m_docNameToOffsetMap,
-            isILPDBProvided);
-
-        hr = methodLinesWriter.WritePDBData();
-        if (FAILED(hr))
-            return hr;
-    }
-
-    return S_OK;
-}
-
-// ----------------------------------------------------------------------------
-// Handles writing the file checksums subsection to the PDB
-//
-HRESULT NGenModulePdbWriter::WriteFileChecksums()
-{
-    STANDARD_VM_CONTRACT;
-
-    _ASSERTE(m_pWriter != NULL);
-
-    // The file checksums subsection of the PDB (i.e., "DEBUG_S_FILECHKSMS"), is a blob
-    // consisting of a few structs stacked one after the other:
-    //
-    // * (1) DWORD = CV_SIGNATURE_C13 -- the usual subsection signature DWORD
-    // * (2) CV_DebugSSubsectionHeader_t -- the usual subsection header, with type =
-    //     DEBUG_S_FILECHKSMS
-    // * (3) Blob consisting of an array of checksum data -- the format of this piece is
-    //     not defined via structs (not sure why), but is defined in
-    //     vctools\PDB\doc\lines.docx
-    //
-    HRESULT hr;
-
-    // PDB format requires that the checksum size can always be expressed in a BYTE.
-    const BYTE kcbEachChecksumEstimate = 0xFF;
-
-    UINT64 cbChecksumSubsectionEstimate =
-        sizeof(DWORD) +
-        sizeof(CV_DebugSSubsectionHeader_t) +
-        m_finalPdbDocCount * kcbEachChecksumEstimate;
-    if (!FitsIn<ULONG32>(cbChecksumSubsectionEstimate))
-    {
-        return HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER);
-    }
-
-    NewArrayHolder<BYTE> rgbChksumSubsection(new BYTE[ULONG32(cbChecksumSubsectionEstimate)]);
-    LPBYTE pbChksumSubsectionCur = rgbChksumSubsection;
-
-    // (1) Subsection signature
-    *((DWORD *) pbChksumSubsectionCur) = CV_SIGNATURE_C13;
-    pbChksumSubsectionCur += sizeof(DWORD);
-
-    // (2) Subsection header
-    CV_DebugSSubsectionHeader_t * pSubSectHeader = (CV_DebugSSubsectionHeader_t *) pbChksumSubsectionCur;
-    memset(pSubSectHeader, 0, sizeof(*pSubSectHeader));
-    pSubSectHeader->type = DEBUG_S_FILECHKSMS;
-    pbChksumSubsectionCur += sizeof(*pSubSectHeader);
-    // pSubSectHeader->cblen to be filled in later once we know the size
-
-    LPBYTE pbChksumDataStart = pbChksumSubsectionCur;
-
-    // (3) Iterate through source files, steal their checksum info from the IL PDB, and
-    // write it into the NGEN PDB.
-    for (ULONG32 i = 0; i < m_finalPdbDocCount; i++)
-    {
-        WCHAR wszURL[MAX_LONGPATH] = UNKNOWN_SOURCE_FILE_PATH;
-        char szURL[MAX_LONGPATH];
-        ULONG32 cchURL;
-
-
-        bool isKnownSourcePath = i < m_ilPdbDocCount;
-        if (isKnownSourcePath)
-        {
-            // For NGenMethodLinesPdbWriter::WriteDebugSILLinesSubsection, we won't write the path info.
-            // In order to let WriteDebugSILLinesSubsection can find "UNKNOWN_SOURCE_FILE_PATH" which is
-            // not existed in m_rgpDocs, no matter we have IL PDB or not, we let m_finalPdbDocCount equals to
-            // m_ilPdbDocCount + 1 and write the extra one path as "UNKNOWN_SOURCE_FILE_PATH". That also explains
-            // why we have a inconsistence between m_finalPdbDocCount and m_ilPdbDocCount.
-            hr = m_rgpDocs[i]->GetURL(_countof(wszURL), &cchURL, wszURL);
-            if (FAILED(hr))
-                return hr;
-        }
-
-        int cbWritten = WideCharToMultiByte(
-            CP_UTF8,
-            0,                                      // dwFlags
-            wszURL,
-            -1,                                     // i.e., input is NULL-terminated
-            szURL,                                  // output: UTF8 string starts here
-            _countof(szURL),                        // Available space
-            NULL,                                   // lpDefaultChar
-            NULL                                    // lpUsedDefaultChar
-            );
-        if (cbWritten == 0)
-            return HRESULT_FROM_WIN32(GetLastError());
-
-        // find offset into string table and add to blob; meanwhile update hash to
-        // remember the offset into the cksum table
-        const KeyValuePair<LPCSTR,DocNameOffsets> * pMapEntry =
-            m_docNameToOffsetMap.LookupPtr(szURL);
-        if (pMapEntry == NULL)
-        {
-            // Should never happen, as it implies we found a source file that was never
-            // written to the string table
-            return E_UNEXPECTED;
-        }
-        DocNameOffsets docNameOffsets(pMapEntry->Value());
-        docNameOffsets.m_dwChksumTableOffset = ULONG32(pbChksumSubsectionCur - pbChksumDataStart);
-
-        // Update the map with the new docNameOffsets that contains the cksum table
-        // offset as well. Note that we must ensure the key (LPCSTR) remains the same
-        // (thus we explicitly ask for the Key()). This class guarantees that string
-        // pointer (which comes from the string table buffer field) will remain allocated
-        // as long as the map is.
-        m_docNameToOffsetMap.AddOrReplace(pMapEntry->Key(), docNameOffsets);
-        * (ULONG32 *) pbChksumSubsectionCur = docNameOffsets.m_dwStrTableOffset;
-        pbChksumSubsectionCur += sizeof(ULONG32);
-
-        // Checksum algorithm and bytes
-
-        BYTE rgbChecksum[kcbEachChecksumEstimate];
-        ULONG32 cbChecksum = 0;
-        BYTE bChecksumAlgorithmType = CHKSUM_TYPE_NONE;
-        if (isKnownSourcePath)
-        {
-            GUID guidChecksumAlgorithm;
-            hr = m_rgpDocs[i]->GetCheckSumAlgorithmId(&guidChecksumAlgorithm);
-            if (SUCCEEDED(hr))
-            {
-                // If we got the checksum algorithm, we can write it all out to the buffer.
-                // Else, we'll just omit the checksum info
-                if (memcmp(&guidChecksumAlgorithm, &CorSym_SourceHash_MD5, sizeof(GUID)) == 0)
-                    bChecksumAlgorithmType = CHKSUM_TYPE_MD5;
-                else if (memcmp(&guidChecksumAlgorithm, &CorSym_SourceHash_SHA1, sizeof(GUID)) == 0)
-                    bChecksumAlgorithmType = CHKSUM_TYPE_SHA1;
-            }
-        }
-
-        if (bChecksumAlgorithmType != CHKSUM_TYPE_NONE)
-        {
-            hr = m_rgpDocs[i]->GetCheckSum(sizeof(rgbChecksum), &cbChecksum, rgbChecksum);
-            if (FAILED(hr) || !FitsIn<BYTE>(cbChecksum))
-            {
-                // Should never happen, but just in case checksum data is invalid, just put
-                // no checksum into the NGEN PDB
-                bChecksumAlgorithmType = CHKSUM_TYPE_NONE;
-                cbChecksum = 0;
-            }
-        }
-
-        // checksum length & algorithm
-        *pbChksumSubsectionCur = (BYTE) cbChecksum;
-        pbChksumSubsectionCur++;
-        *pbChksumSubsectionCur = bChecksumAlgorithmType;
-        pbChksumSubsectionCur++;
-
-        // checksum data bytes
-        memcpy(pbChksumSubsectionCur, rgbChecksum, cbChecksum);
-        pbChksumSubsectionCur += cbChecksum;
-
-        // Must align to the next 4-byte boundary
-        LPBYTE pbChksumSubsectionCurAligned = (LPBYTE) ALIGN_UP(pbChksumSubsectionCur, 4);
-        memset(pbChksumSubsectionCur, 0, pbChksumSubsectionCurAligned-pbChksumSubsectionCur);
-        pbChksumSubsectionCur = pbChksumSubsectionCurAligned;
-    }
-
-    // Now that we know pSubSectHeader->cbLen, fill it in
-    pSubSectHeader->cbLen = CV_off32_t(pbChksumSubsectionCur - pbChksumDataStart);
-
-    // Subsection is now filled out, so add it
-    hr = m_pWriter->ModAddSymbols(
-        m_pdbMod.GetModPtr(),
-        rgbChksumSubsection,
-        int(pbChksumSubsectionCur - rgbChksumSubsection));
-    if (FAILED(hr))
-        return hr;
-
-    return S_OK;
-}
-
-// ----------------------------------------------------------------------------
-// NGenMethodLinesPdbWriter implementation
-
-
-//---------------------------------------------------------------------------------------
-//
-// Manages the writing of all lines-file subsections requred for a given method.  if a
-// method is hot/cold split, this will write two line-file subsections to the PDB--one
-// for the hot region, and one for the cold.
-//
-
-HRESULT NGenMethodLinesPdbWriter::WritePDBData()
-{
-    STANDARD_VM_CONTRACT;
-
-    if (m_hotDesc->IsNoMetadata())
-    {
-        // IL stubs will not have data in the IL PDB, so just skip them.
-        return S_OK;
-    }
-
-    //
-    // First, we'll need to merge the IL-to-native map from the JIT manager with the
-    // IL-to-source map from the IL PDB. This merging is done into a single piece that
-    // includes all regions of the code when it's split
-    //
-
-    // Grab the IL-to-native map from the JIT manager
-    DebugInfoRequest debugInfoRequest;
-    debugInfoRequest.InitFromStartingAddr(m_hotDesc, m_start);
-    BOOL fSuccess = m_pCodeInfo->GetJitManager()->GetBoundariesAndVars(
-        debugInfoRequest,
-        SimpleNew, NULL,            // Allocator
-        &m_cIlNativeMap,
-        &m_rgIlNativeMap,
-        NULL, NULL);
-    if (!fSuccess)
-    {
-        // Shouldn't happen, but just skip this method if it does
-        return S_OK;
-    }
-    HRESULT hr;
-    if (FAILED(hr = WriteNativeILMapPDBData()))
-    {
-        return hr;
-    }
-
-    if (!m_isILPDBProvided)
-    {
-        return S_OK;
-    }
-
-    // We will traverse this IL-to-native map (from the JIT) in parallel with the
-    // source-to-IL map provided by the IL PDB (below).  Both need to be sorted by IL so
-    // we can easily find matching entries in the two maps
-    QuickSortILNativeMapByIL sorterByIl(m_rgIlNativeMap, m_cIlNativeMap);
-    sorterByIl.Sort();
-
-    // Now grab IL-to-source map from the IL PDBs (just known as "sequence points"
-    // according to the IL PDB API)
-
-    ReleaseHolder<ISymUnmanagedMethod> pMethod;
-    hr = m_pReader->GetMethod(
-        m_hotDesc->GetMemberDef(),
-        &pMethod);
-    if (FAILED(hr))
-    {
-        // Ignore any methods not included in the IL PDB.  Although we've already
-        // excluded LCG & IL stubs from methods we're considering, there can still be
-        // methods in the NGEN module that are not in the IL PDB (e.g., implicit ctors).
-        return S_OK;
-    }
-
-    ULONG32 cSeqPointsExpected;
-    hr = pMethod->GetSequencePointCount(&cSeqPointsExpected);
-    if (FAILED(hr))
-    {
-        // Should never happen, but we can just skip this function if the IL PDB can't
-        // find sequence point info
-        return S_OK;
-    }
-
-    ULONG32 cSeqPointsReturned;
-    m_rgilOffsets = new ULONG32[cSeqPointsExpected];
-    m_rgpDocs = new ISymUnmanagedDocument * [cSeqPointsExpected];
-    m_rgnLineStarts = new ULONG32[cSeqPointsExpected];
-
-    //  This is guaranteed to return the sequence points sorted in order of the IL
-    //  offsets (m_rgilOffsets)
-    hr = pMethod->GetSequencePoints(
-        cSeqPointsExpected,
-        &cSeqPointsReturned,
-        m_rgilOffsets,
-        m_rgpDocs,
-        m_rgnLineStarts,
-        NULL,       // ColumnStarts not needed
-        NULL,       // LineEnds not needed
-        NULL);      // ColumnEnds not needed
-    if (FAILED(hr))
-    {
-        // Shouldn't happen, but just skip this method if it does
-        return S_OK;
-    }
-    // Commit m_rgpDocs to calling Release() on all ISymUnmanagedDocument* returned into
-    // the array.
-    m_rgpDocs.SetElementCount(cSeqPointsReturned);
-
-    // Now merge the two maps together into an array of MapIndexPair structures. Traverse
-    // both maps in parallel (both ordered by IL offset), looking for IL offset matches.
-    // Range matching: If an entry in the IL-to-native map has no matching entry in the
-    // IL PDB, then seek up in the IL PDB to the previous sequence point and merge to
-    // that (assuming that previous sequence point from the IL PDB did not already have
-    // an exact match to some other entry in the IL-to-native map).
-    ULONG32 cMapIndexPairsMax = m_cIlNativeMap;
-    NewArrayHolder<MapIndexPair> rgMapIndexPairs(new MapIndexPair [cMapIndexPairsMax]);
-    ULONG32 iSeqPoints = 0;
-
-    // Keep track (via iSeqPointLastUnmatched) of the most recent entry in the IL PDB
-    // that we passed over because it had no matching entry in the IL-to-native map. We
-    // may use this to do a range-match if necessary. We'll set iSeqPointLastUnmatched to
-    // the currently interated IL PDB entry after our cursor in the il-to-native map
-    // passed it by, but only if fCurSeqPointMatched is FALSE
-    ULONG32 iSeqPointLastUnmatched = (ULONG32) -1;
-    BOOL fCurSeqPointMatched = FALSE;
-
-    ULONG32 iIlNativeMap = 0;
-    ULONG32 iMapIndexPairs = 0;
-
-    // Traverse IL PDB entries and IL-to-native map entries (both sorted by IL) in
-    // parallel
-    //
-    //     * Record matching indices in our output map, rgMapIndexPairs, indexed by
-    //         iMapIndexPairs.
-    //
-    //     * We will have at most m_cIlNativeMap entries in rgMapIndexPairs by the time
-    //         we're done. (Each il-to-native map entry will be considered for inclusion
-    //         in this output. Those il-to-native map entries with a match in the il PDB
-    //         will be included, the rest skipped.)
-    //
-    //     * iSeqPointLastUnmatched != -1 iff it equals a prior entry in the IL PDB that
-    //         we skipped over because it could not be exactly matched to an entry in the
-    //         il-to-native map.  In such a case, it will be considered for a
-    //         range-match to the next il-to-native map entry
-    while (iIlNativeMap < m_cIlNativeMap)
-    {
-        _ASSERTE (iMapIndexPairs < cMapIndexPairsMax);
-
-        // IP addresses that map to "special" places (prolog, epilog, or
-        // other hidden code), will just map to 0xFeeFee, as per convention
-        if ((m_rgIlNativeMap[iIlNativeMap].ilOffset == NO_MAPPING) ||
-            (m_rgIlNativeMap[iIlNativeMap].ilOffset == PROLOG) ||
-            (m_rgIlNativeMap[iIlNativeMap].ilOffset == EPILOG))
-        {
-            rgMapIndexPairs[iMapIndexPairs].m_iIlNativeMap = iIlNativeMap;
-            rgMapIndexPairs[iMapIndexPairs].m_iSeqPoints = kUnmappedIP;
-            iMapIndexPairs++;
-
-            // If we were remembering a prior unmatched entry in the IL PDB, reset it
-            iSeqPointLastUnmatched = (ULONG32) -1;
-
-            // Advance il-native map, NOT il-source map
-            iIlNativeMap++;
-            continue;
-        }
-
-        // Cases below actually look at the IL PDB sequence point, so ensure it's still
-        // in range; otherwise, we're done.
-        if (iSeqPoints >= cSeqPointsReturned)
-            break;
-
-        if (m_rgIlNativeMap[iIlNativeMap].ilOffset < m_rgilOffsets[iSeqPoints])
-        {
-            // Our cursor over the ilnative map is behind the sourceil
-            // map
-
-            if (iSeqPointLastUnmatched != (ULONG32) -1)
-            {
-                // Range matching: This ilnative entry is behind our cursor in the
-                // sourceil map, but this ilnative entry is also ahead of the previous
-                // (unmatched) entry in the sourceil map. So this is a case where the JIT
-                // generated sequence points that surround, without matching, that
-                // previous entry in the sourceil map. So match to that previous
-                // (unmatched) entry in the sourceil map.
-                _ASSERTE(m_rgilOffsets[iSeqPointLastUnmatched] < m_rgIlNativeMap[iIlNativeMap].ilOffset);
-                rgMapIndexPairs[iMapIndexPairs].m_iIlNativeMap = iIlNativeMap;
-                rgMapIndexPairs[iMapIndexPairs].m_iSeqPoints = iSeqPointLastUnmatched;
-                iMapIndexPairs++;
-
-                // Reset our memory of the last unmatched entry in the IL PDB
-                iSeqPointLastUnmatched = (ULONG32) -1;
-            }
-            else if (iMapIndexPairs > 0)
-            {
-                DWORD lastMatchedilNativeIndex = rgMapIndexPairs[iMapIndexPairs - 1].m_iIlNativeMap;
-                if (m_rgIlNativeMap[iIlNativeMap].ilOffset == m_rgIlNativeMap[lastMatchedilNativeIndex].ilOffset &&
-                    m_rgIlNativeMap[iIlNativeMap].nativeOffset < m_rgIlNativeMap[lastMatchedilNativeIndex].nativeOffset)
-                {
-                    rgMapIndexPairs[iMapIndexPairs - 1].m_iIlNativeMap = iIlNativeMap;
-                }
-
-            }
-            // Go to next ilnative map entry
-            iIlNativeMap++;
-            continue;
-        }
-
-        if (m_rgilOffsets[iSeqPoints] < m_rgIlNativeMap[iIlNativeMap].ilOffset)
-        {
-            // Our cursor over the ilnative map is ahead of the sourceil
-            // map, so go to next sourceil map entry.  Remember that we're passing over
-            // this entry in the sourceil map, in case we choose to match to it later.
-            if (!fCurSeqPointMatched)
-            {
-                iSeqPointLastUnmatched = iSeqPoints;
-            }
-            iSeqPoints++;
-            fCurSeqPointMatched = FALSE;
-            continue;
-        }
-
-        // At a match
-        _ASSERTE(m_rgilOffsets[iSeqPoints] == m_rgIlNativeMap[iIlNativeMap].ilOffset);
-        rgMapIndexPairs[iMapIndexPairs].m_iIlNativeMap = iIlNativeMap;
-        rgMapIndexPairs[iMapIndexPairs].m_iSeqPoints = iSeqPoints;
-
-        // If we were remembering a prior unmatched entry in the IL PDB, reset it
-        iSeqPointLastUnmatched = (ULONG32) -1;
-
-        // Advance il-native map, do not advance il-source map in case the next il-native
-        // entry matches this current il-source map entry, but remember that this current
-        // il-source map entry has found an exact match
-        iMapIndexPairs++;
-        iIlNativeMap++;
-        fCurSeqPointMatched = TRUE;
-    }
-
-    ULONG32 cMapIndexPairs = iMapIndexPairs;
-
-    // PDB format requires the lines array to be sorted by IP offset
-    QuickSortMapIndexPairsByNativeOffset sorterByIp(rgMapIndexPairs, cMapIndexPairs, m_rgIlNativeMap, m_cIlNativeMap);
-    sorterByIp.Sort();
-
-    //
-    // Now that the maps are merged and sorted, determine whether there's a hot/cold
-    // split, where that split is, and then call WriteLinesSubsection to write out each
-    // region into its own lines-file subsection
-    //
-
-    // Find the point where the code got split
-    ULONG32 iMapIndexPairsFirstEntryInColdSection = cMapIndexPairs;
-    for (iMapIndexPairs = 0; iMapIndexPairs < cMapIndexPairs; iMapIndexPairs++)
-    {
-        DWORD dwNativeOffset = m_rgIlNativeMap[rgMapIndexPairs[iMapIndexPairs].m_iIlNativeMap].nativeOffset;
-        if (dwNativeOffset >= m_pMethodRegionInfo->hotSize)
-        {
-            iMapIndexPairsFirstEntryInColdSection = iMapIndexPairs;
-            break;
-        }
-    }
-
-    // Adjust the cold offsets (if any) to be relative to the cold start
-    for (iMapIndexPairs = iMapIndexPairsFirstEntryInColdSection; iMapIndexPairs < cMapIndexPairs; iMapIndexPairs++)
-    {
-        DWORD dwNativeOffset = m_rgIlNativeMap[rgMapIndexPairs[iMapIndexPairs].m_iIlNativeMap].nativeOffset;
-        _ASSERTE (dwNativeOffset >= m_pMethodRegionInfo->hotSize);
-
-        // Adjust offset so it's relative to the cold region start
-        dwNativeOffset -= DWORD(m_pMethodRegionInfo->hotSize);
-        _ASSERTE(dwNativeOffset < m_pMethodRegionInfo->coldSize);
-        m_rgIlNativeMap[rgMapIndexPairs[iMapIndexPairs].m_iIlNativeMap].nativeOffset = dwNativeOffset;
-    }
-
-    // Write out the hot region into its own lines-file subsection
-    hr = WriteDebugSLinesSubsection(
-        ULONG32(m_pMethodRegionInfo->hotStartAddress - m_addrCodeSection),
-        ULONG32(m_pMethodRegionInfo->hotSize),
-        rgMapIndexPairs,
-        iMapIndexPairsFirstEntryInColdSection);
-    if (FAILED(hr))
-        return hr;
-
-    // If there was a hot/cold split, write a separate lines-file subsection for the cold
-    // region
-    if (iMapIndexPairsFirstEntryInColdSection < cMapIndexPairs)
-    {
-        hr = WriteDebugSLinesSubsection(
-            ULONG32(m_pMethodRegionInfo->coldStartAddress - m_addrCodeSection),
-            ULONG32(m_pMethodRegionInfo->coldSize),
-            &rgMapIndexPairs[iMapIndexPairsFirstEntryInColdSection],
-            cMapIndexPairs - iMapIndexPairsFirstEntryInColdSection);
-        if (FAILED(hr))
-            return hr;
-    }
-
-    return S_OK;
-}
-
-//---------------------------------------------------------------------------------------
-//
-// Manages the writing of all native-IL subsections requred for a given method. Almost do
-// the same thing as NGenMethodLinesPdbWriter::WritePDBData. But we will write the native-IL
-// map this time.
-//
-
-HRESULT NGenMethodLinesPdbWriter::WriteNativeILMapPDBData()
-{
-    STANDARD_VM_CONTRACT;
-
-    HRESULT hr;
-
-    QuickSortILNativeMapByNativeOffset sorterByNativeOffset(m_rgIlNativeMap, m_cIlNativeMap);
-    sorterByNativeOffset.Sort();
-
-    ULONG32 iIlNativeMap = 0;
-    ULONG32 ilNativeMapFirstEntryInColdeSection = m_cIlNativeMap;
-    for (iIlNativeMap = 0; iIlNativeMap < m_cIlNativeMap; iIlNativeMap++)
-    {
-        if (m_rgIlNativeMap[iIlNativeMap].nativeOffset >= m_pMethodRegionInfo->hotSize)
-        {
-            ilNativeMapFirstEntryInColdeSection = iIlNativeMap;
-            break;
-        }
-    }
-
-    NewArrayHolder<ICorDebugInfo::OffsetMapping> coldRgIlNativeMap(new ICorDebugInfo::OffsetMapping[m_cIlNativeMap - ilNativeMapFirstEntryInColdeSection]);
-    // Adjust the cold offsets (if any) to be relative to the cold start
-    for (iIlNativeMap = ilNativeMapFirstEntryInColdeSection; iIlNativeMap < m_cIlNativeMap; iIlNativeMap++)
-    {
-        DWORD dwNativeOffset = m_rgIlNativeMap[iIlNativeMap].nativeOffset;
-        _ASSERTE(dwNativeOffset >= m_pMethodRegionInfo->hotSize);
-
-        // Adjust offset so it's relative to the cold region start
-        dwNativeOffset -= DWORD(m_pMethodRegionInfo->hotSize);
-        _ASSERTE(dwNativeOffset < m_pMethodRegionInfo->coldSize);
-        coldRgIlNativeMap[iIlNativeMap - ilNativeMapFirstEntryInColdeSection].ilOffset = m_rgIlNativeMap[iIlNativeMap].ilOffset;
-        coldRgIlNativeMap[iIlNativeMap - ilNativeMapFirstEntryInColdeSection].nativeOffset = dwNativeOffset;
-        coldRgIlNativeMap[iIlNativeMap - ilNativeMapFirstEntryInColdeSection].source = m_rgIlNativeMap[iIlNativeMap].source;
-    }
-
-    // Write out the hot region into its own lines-file subsection
-    hr = WriteDebugSILLinesSubsection(
-        ULONG32(m_pMethodRegionInfo->hotStartAddress - m_addrCodeSection),
-        ULONG32(m_pMethodRegionInfo->hotSize),
-        m_rgIlNativeMap,
-        ilNativeMapFirstEntryInColdeSection);
-    if (FAILED(hr))
-        return hr;
-
-    // If there was a hot/cold split, write a separate lines-file subsection for the cold
-    // region
-    if (ilNativeMapFirstEntryInColdeSection < m_cIlNativeMap)
-    {
-        hr = WriteDebugSILLinesSubsection(
-            ULONG32(m_pMethodRegionInfo->coldStartAddress - m_addrCodeSection),
-            ULONG32(m_pMethodRegionInfo->coldSize),
-            coldRgIlNativeMap,
-            m_cIlNativeMap - ilNativeMapFirstEntryInColdeSection);
-        if (FAILED(hr))
-            return hr;
-    }
-
-    return S_OK;
-}
-
-
-//---------------------------------------------------------------------------------------
-//
-// Helper called by NGenMethodLinesPdbWriter::WriteDebugSLinesSubsection and
-// NGenMethodLinesPdbWriter::WriteDebugSILLinesSubsection to initial the DEBUG_S*_LINE
-// subsection headers.
-//
-// Arguments:
-//      * ulCodeStartOffset - Offset relative to the code section, or where this region
-//          of code begins
-//      * type - the subsection's type
-//      * lineSize - how many lines mapping the subsection will have.
-//      * cbCode - Size in bytes of this region of code
-//      * ppSubSectHeader -  output value which returns the intialed CV_DebugSLinesHeader_t struct pointer.
-//      * ppLinesHeader - output value which returns the initialed CV_DebugSLinesHeader_t struct pointer.
-//      * ppbLinesSubsectionCur - output value which points to the address right after the DebugSLinesHeader
-//
-// Return Value:
-//      * Pointer which points the staring address of the SubSection.
-//
-
-LPBYTE NGenMethodLinesPdbWriter::InitDebugLinesHeaderSection(
-    DEBUG_S_SUBSECTION_TYPE type,
-    ULONG32 ulCodeStartOffset,
-    ULONG32 cbCode,
-    ULONG32 lineSize,
-    CV_DebugSSubsectionHeader_t **ppSubSectHeader /*out*/,
-    CV_DebugSLinesHeader_t ** ppLinesHeader /*out*/,
-    LPBYTE * ppbLinesSubsectionCur /*out*/)
-{
-    STANDARD_VM_CONTRACT;
-
-    UINT64 cbLinesSubsectionEstimate =
-        sizeof(DWORD) +
-        sizeof(CV_DebugSSubsectionHeader_t) +
-        sizeof(CV_DebugSLinesHeader_t) +
-        // Worst case: assume each sequence point will require its own
-        // CV_DebugSLinesFileBlockHeader_t
-        (lineSize * (sizeof(CV_DebugSLinesFileBlockHeader_t) + sizeof(CV_Line_t)));
-    if (!FitsIn<ULONG32>(cbLinesSubsectionEstimate))
-    {
-        return NULL;
-    }
-
-    LPBYTE rgbLinesSubsection = new BYTE[ULONG32(cbLinesSubsectionEstimate)];
-    LPBYTE pbLinesSubsectionCur = rgbLinesSubsection;
-
-    // * (1) DWORD = CV_SIGNATURE_C13 -- the usual subsection signature DWORD
-    *((DWORD *)pbLinesSubsectionCur) = CV_SIGNATURE_C13;
-    pbLinesSubsectionCur += sizeof(DWORD);
-
-    // * (2) CV_DebugSSubsectionHeader_t
-    CV_DebugSSubsectionHeader_t * pSubSectHeader = (CV_DebugSSubsectionHeader_t *)pbLinesSubsectionCur;
-    memset(pSubSectHeader, 0, sizeof(*pSubSectHeader));
-    pSubSectHeader->type = type;
-    *ppSubSectHeader = pSubSectHeader;
-    // pSubSectHeader->cblen to be filled in later once we know the size
-    pbLinesSubsectionCur += sizeof(*pSubSectHeader);
-
-    // * (3) CV_DebugSLinesHeader_t
-    CV_DebugSLinesHeader_t * pLinesHeader = (CV_DebugSLinesHeader_t *)pbLinesSubsectionCur;
-    memset(pLinesHeader, 0, sizeof(*pLinesHeader));
-    pLinesHeader->offCon = ulCodeStartOffset;
-    pLinesHeader->segCon = m_iCodeSection;
-    pLinesHeader->flags = 0;   // 0 means line info, but not column info, is included
-    pLinesHeader->cbCon = cbCode;
-    *ppLinesHeader = pLinesHeader;
-    pbLinesSubsectionCur += sizeof(*pLinesHeader);
-    *ppbLinesSubsectionCur = pbLinesSubsectionCur;
-    return rgbLinesSubsection;
-}
-
-//---------------------------------------------------------------------------------------
-//
-// Helper called by NGenMethodLinesPdbWriter::WritePDBData to do the actual PDB writing of a single
-// lines-subsection.  This is called once for the hot region, and once for the cold
-// region, of a given method that has been split.  That means you get two
-// lines-subsections for split methods.
-//
-// Arguments:
-//      * ulCodeStartOffset - Offset relative to the code section, or where this region
-//          of code begins
-//      * cbCode - Size in bytes of this region of code
-//      * rgMapIndexPairs - Array of indices forming the merged data from the JIT
-//          Manager's IL-to-native map and the IL PDB's IL-to-source map.  It is assumed
-//          that this array has indices sorted such that the native offsets increase
-//      * cMapIndexPairs - Size in entries of above array.
-//
-// Assumptions:
-//      rgMapIndexPairs must be sorted in order of nativeOffset, i.e.,
-//      m_rgIlNativeMap[rgMapIndexPairs[i].m_iIlNativeMap].nativeOffset increases with i.
-//
-
-HRESULT NGenMethodLinesPdbWriter::WriteDebugSLinesSubsection(
-    ULONG32 ulCodeStartOffset,
-    ULONG32 cbCode,
-    MapIndexPair * rgMapIndexPairs,
-    ULONG32 cMapIndexPairs)
-{
-    STANDARD_VM_CONTRACT;
-
-    // The lines subsection of the PDB (i.e., "DEBUG_S_LINES"), is a blob consisting of a
-    // few structs stacked one after the other:
-    //
-    // * (1) DWORD = CV_SIGNATURE_C13 -- the usual subsection signature DWORD
-    // * (2) CV_DebugSSubsectionHeader_t -- the usual subsection header, with type =
-    //     DEBUG_S_LINES
-    // * (3) CV_DebugSLinesHeader_t -- a single header for the entire subsection.  Its
-    //     purpose is to specify the native function being described, and to specify the
-    //     size of the variable-sized "blocks" that follow
-    // * (4) CV_DebugSLinesFileBlockHeader_t -- For each block, you get one of these.  A
-    //     block is defined by a set of sequence points that map to the same source
-    //     file.  While iterating through the offsets, we need to define new blocks
-    //     whenever the source file changes.  In C#, this typically only happens when
-    //     you advance to (or away from) an unmapped IP (0xFeeFee).
-    // * (5) CV_Line_t (Line array entries) -- For each block, you get several line
-    //     array entries, one entry for the beginning of each sequence point.
-
-    HRESULT hr;
-
-
-    CV_DebugSSubsectionHeader_t * pSubSectHeader = NULL;
-    CV_DebugSLinesHeader_t * pLinesHeader = NULL;
-    CV_DebugSLinesFileBlockHeader_t * LinesFileBlockHeader = NULL;
-
-    // the InitDebugLinesHeaderSection will help us taking care of
-    // * (1) DWORD = CV_SIGNATURE_C13
-    // * (2) CV_DebugSSubsectionHeader_t
-    // * (3) CV_DebugSLinesHeader_t
-    LPBYTE pbLinesSubsectionCur;
-    LPBYTE prgbLinesSubsection = InitDebugLinesHeaderSection(
-        DEBUG_S_LINES,
-        ulCodeStartOffset,
-        cbCode,
-        cMapIndexPairs,
-        &pSubSectHeader,
-        &pLinesHeader,
-        &pbLinesSubsectionCur);
-
-    if (pbLinesSubsectionCur == NULL)
-    {
-        return HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER);
-    }
-
-    NewArrayHolder<BYTE> rgbLinesSubsection(prgbLinesSubsection);
-
-    // The loop below takes care of
-    //     * (4) CV_DebugSLinesFileBlockHeader_t
-    //     * (5) CV_Line_t (Line array entries)
-    //
-    BOOL fAtLeastOneBlockWritten = FALSE;
-    CV_DebugSLinesFileBlockHeader_t * pLinesFileBlockHeader = NULL;
-    CV_Line_t * pLineCur = NULL;
-    CV_Line_t * pLinePrev = NULL;
-    CV_Line_t * pLineBlockStart = NULL;
-    BOOL fBeginNewBlock = TRUE;
-    ULONG32 iSeqPointsPrev = (ULONG32) -1;
-    DWORD dwNativeOffsetPrev = (DWORD) -1;
-    DWORD ilOffsetPrev = (DWORD) -1;
-    WCHAR wszURLPrev[MAX_LONGPATH];
-    memset(&wszURLPrev, 0, sizeof(wszURLPrev));
-    LPBYTE pbEnd = NULL;
-
-    for (ULONG32 iMapIndexPairs=0; iMapIndexPairs < cMapIndexPairs; iMapIndexPairs++)
-    {
-        ULONG32 iSeqPoints = rgMapIndexPairs[iMapIndexPairs].m_iSeqPoints;
-        ULONG32 iIlNativeMap = rgMapIndexPairs[iMapIndexPairs].m_iIlNativeMap;
-
-        // Sometimes the JIT manager will give us duplicate IPs in the IL-to-native
-        // offset mapping. PDB format frowns on that. Since rgMapIndexPairs is being
-        // iterated in native offset order, it's easy to find these dupes right now, and
-        // skip all but the first map containing a given IP offset.
-        if (pLinePrev != NULL && m_rgIlNativeMap[iIlNativeMap].nativeOffset == pLinePrev->offset)
-        {
-            if (ilOffsetPrev == kUnmappedIP)
-            {
-                // if the previous IL offset is kUnmappedIP, then we should rewrite it.
-                pLineCur = pLinePrev;
-            }
-            else if (iSeqPoints != kUnmappedIP && m_rgilOffsets[iSeqPoints] < ilOffsetPrev)
-            {
-                pLineCur = pLinePrev;
-            }
-            else
-            {
-                // Found a native offset dupe, ignore the current map entry
-                continue;
-            }
-        }
-
-        if ((iSeqPoints != kUnmappedIP) && (iSeqPoints != iSeqPointsPrev))
-        {
-            // This is the first iteration where we're looking at this iSeqPoints.  So
-            // check whether the document name has changed on us.  If it has, that means
-            // we need to start a new block.
-            WCHAR wszURL[MAX_LONGPATH];
-            ULONG32 cchURL;
-            hr = m_rgpDocs[iSeqPoints]->GetURL(_countof(wszURL), &cchURL, wszURL);
-            if (FAILED(hr))
-            {
-                // Skip function if IL PDB has data missing
-                return S_OK;
-            }
-
-            // wszURL is the best we have for a unique identifier of documents.  See
-            // whether the previous document's URL is different
-            if (_wcsicmp(wszURL, wszURLPrev) != 0)
-            {
-                // New document.  Update wszURLPrev, and remember that we need to start a
-                // new file block
-                if (wcscpy_s(wszURLPrev, _countof(wszURLPrev), wszURL) != 0)
-                {
-                    continue;
-                }
-                fBeginNewBlock = TRUE;
-            }
-
-            iSeqPointsPrev = iSeqPoints;
-        }
-        if (fBeginNewBlock)
-        {
-            // We've determined that we need to start a new block. So perform fixups
-            // against the previous block (if any) first
-            if (FinalizeLinesFileBlock(pLinesFileBlockHeader, pLineBlockStart, pLineCur))
-            {
-                fAtLeastOneBlockWritten = TRUE;
-            }
-            else if (pLinesFileBlockHeader != NULL)
-            {
-                // Previous block had no usable data.  So rewind back to the previous
-                // block header, and we'll start there with the next block
-                pbLinesSubsectionCur = LPBYTE(pLinesFileBlockHeader);
-                pLineCur = (CV_Line_t *) pbLinesSubsectionCur;
-            }
-
-            // Now get the info we'll need for the next block
-            char szURL[MAX_LONGPATH];
-            int cbWritten = WideCharToMultiByte(
-                CP_UTF8,
-                0,                                      // dwFlags
-                wszURLPrev,
-                -1,                                     // i.e., input is NULL-terminated
-                szURL,                                  // output: UTF8 string starts here
-                _countof(szURL),                        // Available space
-                NULL,                                   // lpDefaultChar
-                NULL                                    // lpUsedDefaultChar
-                );
-            if (cbWritten == 0)
-                continue;
-
-            DocNameOffsets docNameOffsets;
-            BOOL fExists = m_pDocNameToOffsetMap->Lookup(szURL, &docNameOffsets);
-            if (fExists)
-            {
-                _ASSERTE(docNameOffsets.m_dwChksumTableOffset != (ULONG32) -1);
-            }
-            else
-            {
-                // We may get back an invalid document in the 0xFeeFee case (i.e., a
-                // sequence point that intentionally doesn't map back to a publicly
-                // available source code line).  In that case, we'll use the bogus cksum
-                // offset of -1 for now, and verify we're in the 0xFeeFee case later on
-                // (see code:NGenMethodLinesPdbWriter::FinalizeLinesFileBlock).
-                _ASSERTE(szURL[0] == '\0');
-                _ASSERTE(docNameOffsets.m_dwChksumTableOffset == (ULONG32) -1);
-            }
-
-
-            // * (4) CV_DebugSLinesFileBlockHeader_t
-            if (pLineCur == NULL)
-            {
-                // First lines file block, so begin the block header immediately after the
-                // subsection headers
-                pLinesFileBlockHeader = (CV_DebugSLinesFileBlockHeader_t *) pbLinesSubsectionCur;
-            }
-            else
-            {
-                // We've had blocks before this one, so add this block at our current
-                // location in the blob
-                pLinesFileBlockHeader = (CV_DebugSLinesFileBlockHeader_t *) pLineCur;
-            }
-
-            // PDB structure sizes guarantee this is the case, though their docs are
-            // explicit that each lines-file block header must be 4-byte aligned.
-            _ASSERTE(IS_ALIGNED(pLinesFileBlockHeader, 4));
-
-            memset(pLinesFileBlockHeader, 0, sizeof(*pLinesFileBlockHeader));
-            pLinesFileBlockHeader->offFile = docNameOffsets.m_dwChksumTableOffset;
-            // pLinesFileBlockHeader->nLines to be filled in when block is complete
-            // pLinesFileBlockHeader->cbBlock to be filled in when block is complete
-
-            pLineCur = (CV_Line_t *) (pLinesFileBlockHeader + 1);
-            pLineBlockStart = pLineCur;
-            fBeginNewBlock = FALSE;
-        }
-
-
-        pLineCur->offset = m_rgIlNativeMap[iIlNativeMap].nativeOffset;
-        pLineCur->linenumStart =
-            (iSeqPoints == kUnmappedIP) ?
-            kUnmappedIP :
-            m_rgnLineStarts[iSeqPoints];
-        pLineCur->deltaLineEnd = 0;
-        pLineCur->fStatement = 1;
-        ilOffsetPrev = (iSeqPoints == kUnmappedIP) ? kUnmappedIP : m_rgilOffsets[iSeqPoints];
-        pLinePrev = pLineCur;
-        pLineCur++;
-    }       // for (ULONG32 iMapIndexPairs=0; iMapIndexPairs < cMapIndexPairs; iMapIndexPairs++)
-
-    if (pLineCur == NULL)
-    {
-        // There were no lines data for this function, so don't write anything
-        return S_OK;
-    }
-
-    // Perform fixups against the last block we wrote
-    if (FinalizeLinesFileBlock(pLinesFileBlockHeader, pLineBlockStart, pLineCur))
-        fAtLeastOneBlockWritten = TRUE;
-
-    if (!fAtLeastOneBlockWritten)
-    {
-        // There were no valid blocks to write for this function, so don't bother
-        // calling PDB writing API.  No problem.
-        return S_OK;
-    }
-
-    // Now that we know pSubSectHeader->cbLen, fill it in
-    pSubSectHeader->cbLen = CV_off32_t(LPBYTE(pLineCur) - LPBYTE(pLinesHeader));
-
-    // Subsection is now filled out, so add it.
-    hr = m_pWriter->ModAddSymbols(
-        m_pMod,
-        rgbLinesSubsection,
-
-        // The size we pass here is the size of the entire byte array that we pass in.
-        int(LPBYTE(pLineCur) - rgbLinesSubsection));
-
-    if (FAILED(hr))
-        return hr;
-
-    return S_OK;
-}
-
-//---------------------------------------------------------------------------------------
-//
-// Helper called by NGenMethodLinesPdbWriter::WriteNativeILMapPDBData to do the actual PDB writing of a single
-// lines-subsection.  This is called once for the hot region, and once for the cold
-// region, of a given method that has been split.  That means you get two
-// lines-subsections for split methods.
-//
-// Arguments:
-//      * ulCodeStartOffset - Offset relative to the code section, or where this region
-//          of code begins
-//      * cbCode - Size in bytes of this region of code
-//      * rgIlNativeMap - IL to Native map array.
-//      * rgILNativeMapAdjustSize - the number of elements we need to read in rgILNativeMap.
-//
-
-HRESULT NGenMethodLinesPdbWriter::WriteDebugSILLinesSubsection(
-    ULONG32 ulCodeStartOffset,
-    ULONG32 cbCode,
-    ICorDebugInfo::OffsetMapping * rgIlNativeMap,
-    ULONG32 rgILNativeMapAdjustSize)
-{
-    STANDARD_VM_CONTRACT;
-
-    // The lines subsection of the PDB (i.e., "DEBUG_S_IL_LINES"), is a blob consisting of a
-    // few structs stacked one after the other:
-    //
-    // * (1) DWORD = CV_SIGNATURE_C13 -- the usual subsection signature DWORD
-    // * (2) CV_DebugSSubsectionHeader_t -- the usual subsection header, with type =
-    //     DEBUG_S_LINES
-    // * (3) CV_DebugSLinesHeader_t -- a single header for the entire subsection.  Its
-    //     purpose is to specify the native function being described, and to specify the
-    //     size of the variable-sized "blocks" that follow
-    // * (4) CV_DebugSLinesFileBlockHeader_t -- For each block, you get one of these.  A
-    //     block is defined by a set of sequence points that map to the same source
-    //     file.  While iterating through the offsets, we need to define new blocks
-    //     whenever the source file changes.  In C#, this typically only happens when
-    //     you advance to (or away from) an unmapped IP (0xFeeFee).
-    // * (5) CV_Line_t (Line array entries) -- For each block, you get several line
-    //     array entries, one entry for the beginning of each sequence point.
-
-    HRESULT hr;
-
-    CV_DebugSSubsectionHeader_t * pSubSectHeader = NULL;
-    CV_DebugSLinesHeader_t * pLinesHeader = NULL;
-    CV_DebugSLinesFileBlockHeader_t * pLinesFileBlockHeader = NULL;
-
-    // the InitDebugLinesHeaderSection will help us taking care of
-    // * (1) DWORD = CV_SIGNATURE_C13
-    // * (2) CV_DebugSSubsectionHeader_t
-    // * (3) CV_DebugSLinesHeader_t
-    LPBYTE pbLinesSubsectionCur;
-    LPBYTE prgbLinesSubsection = InitDebugLinesHeaderSection(
-        DEBUG_S_IL_LINES,
-        ulCodeStartOffset,
-        cbCode,
-        rgILNativeMapAdjustSize,
-        &pSubSectHeader,
-        &pLinesHeader,
-        &pbLinesSubsectionCur);
-
-    if (prgbLinesSubsection == NULL)
-    {
-        return HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER);
-    }
-
-    NewArrayHolder<BYTE> rgbLinesSubsection(prgbLinesSubsection);
-
-    // The loop below takes care of
-    //     * (4) CV_DebugSLinesFileBlockHeader_t
-    //     * (5) CV_Line_t (Line array entries)
-    //
-    CV_Line_t * pLineCur = NULL;
-    CV_Line_t * pLineBlockStart = NULL;
-    BOOL fBeginNewBlock = TRUE;
-    LPBYTE pbEnd = NULL;
-
-    pLinesFileBlockHeader = (CV_DebugSLinesFileBlockHeader_t *)pbLinesSubsectionCur;
-    // PDB structure sizes guarantee this is the case, though their docs are
-    // explicit that each lines-file block header must be 4-byte aligned.
-    _ASSERTE(IS_ALIGNED(pLinesFileBlockHeader, 4));
-
-    memset(pLinesFileBlockHeader, 0, sizeof(*pLinesFileBlockHeader));
-    char szURL[MAX_PATH];
-    int cbWritten = WideCharToMultiByte(
-        CP_UTF8,
-        0,                                      // dwFlags
-        UNKNOWN_SOURCE_FILE_PATH,
-        -1,                                     // i.e., input is NULL-terminated
-        szURL,                                  // output: UTF8 string starts here
-        _countof(szURL),                        // Available space
-        NULL,                                   // lpDefaultChar
-        NULL                                    // lpUsedDefaultChar
-        );
-    _ASSERTE(cbWritten > 0);
-    DocNameOffsets docNameOffsets;
-    m_pDocNameToOffsetMap->Lookup(szURL, &docNameOffsets);
-    pLinesFileBlockHeader->offFile = docNameOffsets.m_dwChksumTableOffset;
-    // pLinesFileBlockHeader->nLines to be filled in when block is complete
-    // pLinesFileBlockHeader->cbBlock to be filled in when block is complete
-
-    pLineCur = (CV_Line_t *)(pLinesFileBlockHeader + 1);
-    pLineBlockStart = pLineCur;
-    CV_Line_t * pLinePrev = NULL;
-
-    for (ULONG32 iINativeMap = 0;iINativeMap < rgILNativeMapAdjustSize; iINativeMap++)
-    {
-        if ((rgIlNativeMap[iINativeMap].ilOffset == NO_MAPPING) ||
-            (rgIlNativeMap[iINativeMap].ilOffset == PROLOG) ||
-            (rgIlNativeMap[iINativeMap].ilOffset == EPILOG))
-        {
-            rgIlNativeMap[iINativeMap].ilOffset = kUnmappedIP;
-        }
-
-        // Sometimes the JIT manager will give us duplicate native offset in the IL-to-native
-        // offset mapping. PDB format frowns on that. Since rgMapIndexPairs is being
-        // iterated in native offset order, it's easy to find these dupes right now, and
-        // skip all but the first map containing a given IP offset.
-        if (pLinePrev != NULL &&
-            rgIlNativeMap[iINativeMap].nativeOffset == pLinePrev->offset)
-        {
-            if (pLinePrev->linenumStart == kUnmappedIP)
-            {
-                // if the previous IL offset is kUnmappedIP, then we should rewrite it.
-                pLineCur = pLinePrev;
-            }
-            else if (rgIlNativeMap[iINativeMap].ilOffset != kUnmappedIP &&
-                rgIlNativeMap[iINativeMap].ilOffset < pLinePrev->linenumStart)
-            {
-                pLineCur = pLinePrev;
-            }
-            else
-            {
-                // Found a native offset dupe, ignore the current map entry
-                continue;
-            }
-        }
-
-        pLineCur->linenumStart = rgIlNativeMap[iINativeMap].ilOffset;
-
-        pLineCur->offset = rgIlNativeMap[iINativeMap].nativeOffset;
-        pLineCur->fStatement = 1;
-        pLineCur->deltaLineEnd = 0;
-        pLinePrev = pLineCur;
-        pLineCur++;
-    }
-
-    if (pLineCur == NULL)
-    {
-        // There were no lines data for this function, so don't write anything
-        return S_OK;
-    }
-
-    if (!FinalizeLinesFileBlock(pLinesFileBlockHeader, pLineBlockStart, pLineCur
-#ifdef _DEBUG
-        , true
-#endif
-        ))
-    {
-        return S_OK;
-    }
-
-    // Now that we know pSubSectHeader->cbLen, fill it in
-    pSubSectHeader->cbLen = CV_off32_t(LPBYTE(pLineCur) - LPBYTE(pLinesHeader));
-
-    // Subsection is now filled out, so add it.
-    hr = m_pWriter->ModAddSymbols(
-        m_pMod,
-        rgbLinesSubsection,
-
-        // The size we pass here is the size of the entire byte array that we pass in.
-        long(LPBYTE(pLineCur) - rgbLinesSubsection));
-
-    if (FAILED(hr))
-        return hr;
-
-    return S_OK;
-}
-
-//---------------------------------------------------------------------------------------
-//
-// Performs final fixups on the last lines-file block we completed, specifically writing
-// in the size of the block, now that it's known.  Also responsible for determining
-// whether there is even any data to write in the first place.
-//
-// Arguments:
-//      * pLinesFileBlockHeader - lines-file block header to write to
-//      * pLineBlockStart - First CV_Line_t * of this block
-//      * pLineBlockAfterEnd - Last CV_Line_t * of this block plus 1
-//
-// Return Value:
-//      * TRUE: lines-file block was nonempty, and is now finalized
-//      * FALSE: lines-file block was empty, and caller should toss it out.
-//
-
-BOOL NGenMethodLinesPdbWriter::FinalizeLinesFileBlock(
-    CV_DebugSLinesFileBlockHeader_t * pLinesFileBlockHeader,
-    CV_Line_t * pLineBlockStart,
-    CV_Line_t * pLineBlockAfterEnd
-#ifdef _DEBUG
-  , BOOL ignorekUnmappedIPCheck
-#endif
-    )
-{
-    LIMITED_METHOD_CONTRACT;
-
-    if (pLinesFileBlockHeader == NULL)
-    {
-        // If a given function has no sequence points at all, pLinesFileBlockHeader can
-        // be NULL.  No problem
-        return FALSE;
-    }
-
-    if (pLineBlockStart == pLineBlockAfterEnd)
-    {
-        // If we start a lines file block and then realize that there are no entries
-        // (i.e., no valid sequence points to map), then we end up with an empty block.
-        // No problem, just skip the block.
-        return FALSE;
-    }
-
-    _ASSERTE(pLineBlockStart != NULL);
-    _ASSERTE(pLineBlockAfterEnd != NULL);
-    _ASSERTE(pLineBlockAfterEnd > pLineBlockStart);
-
-    if (pLinesFileBlockHeader->offFile == (ULONG32) -1)
-    {
-        // The file offset we set for this block is invalid. This should be due to the
-        // 0xFeeFee case (i.e., sequence points that intentionally don't map back to a
-        // publicly available source code line). Fix up the offset to be valid (point it
-        // at the first file), but the offset will generally be ignored by the PDB
-        // reader.
-#ifdef _DEBUG
-    {
-        if (!ignorekUnmappedIPCheck)
-        {
-            for (CV_Line_t * pLineCur = pLineBlockStart; pLineCur < pLineBlockAfterEnd; pLineCur++)
-            {
-                _ASSERTE(pLineCur->linenumStart == kUnmappedIP);
-            }
-        }
-    }
-#endif // _DEBUG
-        pLinesFileBlockHeader->offFile = 0;
-    }
-
-    // Now that we know the size of the block, finish filling out the lines file block
-    // header
-    pLinesFileBlockHeader->nLines = CV_off32_t(pLineBlockAfterEnd - pLineBlockStart);
-    pLinesFileBlockHeader->cbBlock = pLinesFileBlockHeader->nLines * sizeof(CV_Line_t);
-
-    return TRUE;
-}
-#endif // NO_NGENPDB
-#if defined(FEATURE_PERFMAP) || !defined(NO_NGENPDB)
-HRESULT __stdcall CreatePdb(CORINFO_ASSEMBLY_HANDLE hAssembly, BSTR pNativeImagePath, BSTR pPdbPath, BOOL pdbLines, BSTR pManagedPdbSearchPath, LPCWSTR pDiasymreaderPath)
-{
-    STANDARD_VM_CONTRACT;
-
-    Assembly *pAssembly = reinterpret_cast<Assembly *>(hAssembly);
-    _ASSERTE(pAssembly);
-    _ASSERTE(pNativeImagePath);
-    _ASSERTE(pPdbPath);
-
-#if !defined(NO_NGENPDB)
-    NGenPdbWriter pdbWriter(
-        pNativeImagePath,
-        pPdbPath,
-        pdbLines ? kPDBLines : 0,
-        pManagedPdbSearchPath);
-    IfFailThrow(pdbWriter.Load(pDiasymreaderPath));
-#elif defined(FEATURE_PERFMAP)
-    NativeImagePerfMap perfMap(pAssembly, pPdbPath);
-#endif
-
-    ModuleIterator moduleIterator = pAssembly->IterateModules();
-    Module *pModule = NULL;
-    BOOL fAtLeastOneNativeModuleFound = FALSE;
-
-    while (moduleIterator.Next())
-    {
-        pModule = moduleIterator.GetModule();
-
-        if (pModule->HasNativeOrReadyToRunImage())
-        {
-#if !defined(NO_NGENPDB)
-            IfFailThrow(pdbWriter.WritePDBDataForModule(pModule));
-#elif defined(FEATURE_PERFMAP)
-            perfMap.LogDataForModule(pModule);
-#endif
-            fAtLeastOneNativeModuleFound = TRUE;
-        }
-    }
-
-    if (!fAtLeastOneNativeModuleFound)
-    {
-        GetSvcLogger()->Printf(
-            W("Loaded image '%s' (for input file '%s') is not a native image.\n"),
-            pAssembly->GetManifestFile()->GetPath().GetUnicode(),
-            pNativeImagePath);
-        return CORDBG_E_NO_IMAGE_AVAILABLE;
-    }
-
-    GetSvcLogger()->Printf(
-#if !defined(NO_NGENPDB)
-        W("Successfully generated PDB for native assembly '%s'.\n"),
-#elif defined(FEATURE_PERFMAP)
-        W("Successfully generated perfmap for native assembly '%s'.\n"),
-#endif
-        pNativeImagePath);
-
-    return S_OK;
-}
-#else
-HRESULT __stdcall CreatePdb(CORINFO_ASSEMBLY_HANDLE hAssembly, BSTR pNativeImagePath, BSTR pPdbPath, BOOL pdbLines, BSTR pManagedPdbSearchPath, LPCWSTR pDiasymreaderPath)
-{
-    return E_NOTIMPL;
-}
-#endif // defined(FEATURE_PERFMAP) || !defined(NO_NGENPDB)
-
-// End of PDB writing code
-// ----------------------------------------------------------------------------
-
-
-BOOL CEEPreloader::CanPrerestoreEmbedClassHandle(CORINFO_CLASS_HANDLE handle)
-{
-    STANDARD_VM_CONTRACT;
-
-    if (IsReadyToRunCompilation())
-        return FALSE;
-
-    TypeHandle th(handle);
-
-    return m_image->CanPrerestoreEagerBindToTypeHandle(th, NULL);
-}
-
-BOOL CEEPreloader::CanPrerestoreEmbedMethodHandle(CORINFO_METHOD_HANDLE handle)
-{
-    STANDARD_VM_CONTRACT;
-
-    if (IsReadyToRunCompilation())
-        return FALSE;
-
-    MethodDesc *pMD = (MethodDesc*) handle;
-
-    return m_image->CanPrerestoreEagerBindToMethodDesc(pMD, NULL);
-}
-
-ICorCompilePreloader * CEECompileInfo::PreloadModule(CORINFO_MODULE_HANDLE module,
-                                                ICorCompileDataStore *pData,
-                                                CorProfileData       *profileData)
-{
-    STANDARD_VM_CONTRACT;
-
-    NewHolder<CEEPreloader> pPreloader(new CEEPreloader((Module *) module, pData));
-
-    COOPERATIVE_TRANSITION_BEGIN();
-
-    if (PartialNGenStressPercentage() == 0)
-    {
-        pPreloader->Preload(profileData);
-    }
-
-    COOPERATIVE_TRANSITION_END();
-
-    return pPreloader.Extract();
-}
-
-void CEECompileInfo::SetAssemblyHardBindList(
-    __in_ecount( cHardBindList )
-        LPWSTR *pHardBindList,
-    DWORD  cHardBindList)
-{
-    STANDARD_VM_CONTRACT;
-
-}
-
-HRESULT CEECompileInfo::SetVerboseLevel(
-         IN  VerboseLevel            level)
-{
-    LIMITED_METHOD_CONTRACT;
-    HRESULT hr = S_OK;
-    g_CorCompileVerboseLevel = level;
-    return hr;
-}
-
-//
-// Preloader:
-//
-CEEPreloader::CEEPreloader(Module *pModule,
-             ICorCompileDataStore *pData)
-    : m_pData(pData)
-{
-    m_image = new DataImage(pModule, this);
-
-    CONSISTENCY_CHECK(pModule == GetAppDomain()->ToCompilationDomain()->GetTargetModule());
-
-    GetAppDomain()->ToCompilationDomain()->SetTargetImage(m_image, this);
-
-    m_methodCompileLimit = pModule->GetMDImport()->GetCountWithTokenKind(mdtMethodDef) * 10;
-}
-
-CEEPreloader::~CEEPreloader()
-{
-    WRAPPER_NO_CONTRACT;
-    delete m_image;
-}
-
-void CEEPreloader::Preload(CorProfileData * profileData)
-{
-    STANDARD_VM_CONTRACT;
-
-    bool doNothingNgen = false;
-#ifdef _DEBUG
-    static ConfigDWORD fDoNothingNGen;
-    doNothingNgen = !!fDoNothingNGen.val(CLRConfig::INTERNAL_ZapDoNothing);
-#endif
-
-    if (!doNothingNgen)
-    {
-        m_image->GetModule()->SetProfileData(profileData);
-        m_image->GetModule()->ExpandAll(m_image);
-    }
-
-    // Triage all items created by initial expansion.
-    // We will try to accept all items created by initial expansion.
-    TriageForZap(TRUE);
-}
-
-//
-// ICorCompilerPreloader
-//
-
-DWORD CEEPreloader::MapMethodEntryPoint(CORINFO_METHOD_HANDLE handle)
-{
-    STANDARD_VM_CONTRACT;
-
-    MethodDesc *pMD = GetMethod(handle);
-    Precode * pPrecode = pMD->GetSavedPrecode(m_image);
-
-    return m_image->GetRVA(pPrecode);
-}
-
-DWORD CEEPreloader::MapClassHandle(CORINFO_CLASS_HANDLE handle)
-{
-    STANDARD_VM_CONTRACT;
-
-    TypeHandle th = TypeHandle::FromPtr(handle);
-    if (th.IsTypeDesc())
-        return m_image->GetRVA(th.AsTypeDesc()) | 2;
-    else
-        return m_image->GetRVA(th.AsMethodTable());
-}
-
-DWORD CEEPreloader::MapMethodHandle(CORINFO_METHOD_HANDLE handle)
-{
-    STANDARD_VM_CONTRACT;
-
-    return m_image->GetRVA(handle);
-}
-
-DWORD CEEPreloader::MapFieldHandle(CORINFO_FIELD_HANDLE handle)
-{
-    STANDARD_VM_CONTRACT;
-
-    return m_image->GetRVA(handle);
-}
-
-DWORD CEEPreloader::MapAddressOfPInvokeFixup(CORINFO_METHOD_HANDLE handle)
-{
-    STANDARD_VM_CONTRACT;
-
-    MethodDesc *pMD = GetMethod(handle);
-
-    _ASSERTE(pMD->IsNDirect());
-    NDirectWriteableData * pMDWriteableData = ((NDirectMethodDesc *)pMD)->GetWriteableData();
-
-    return m_image->GetRVA(pMDWriteableData) + offsetof(NDirectWriteableData, m_pNDirectTarget);
-}
-
-DWORD CEEPreloader::MapGenericHandle(CORINFO_GENERIC_HANDLE handle)
-{
-    STANDARD_VM_CONTRACT;
-
-    return m_image->GetRVA(handle);
-}
-
-DWORD CEEPreloader::MapModuleIDHandle(CORINFO_MODULE_HANDLE handle)
-{
-    STANDARD_VM_CONTRACT;
-
-    return m_image->GetRVA(handle) + (DWORD)Module::GetOffsetOfModuleID();
-}
-
-CORINFO_METHOD_HANDLE CEEPreloader::NextUncompiledMethod()
-{
-    STANDARD_VM_CONTRACT;
-
-    // If we have run out of methods to compile, ensure that we have code for all methods
-    // that we are about to save.
-    if (m_uncompiledMethods.GetCount() == 0)
-    {
-        // The subsequent populations are done in non-expansive way (won't load new types)
-        m_image->GetModule()->PrepopulateDictionaries(m_image, TRUE);
-
-        // Make sure that we have generated code for all instantiations that we are going to save
-        // The new items that we encounter here were most likely side effects of verification or failed inlining,
-        // so do not try to save them eagerly.
-        while (TriageForZap(FALSE)) {
-            // Loop as long as new types are added
-        }
-    }
-
-    // Take next uncompiled method
-    COUNT_T count = m_uncompiledMethods.GetCount();
-    if (count == 0)
-        return NULL;
-
-    MethodDesc * pMD = m_uncompiledMethods[count - 1];
-    m_uncompiledMethods.SetCount(count - 1);
-
-#ifdef _DEBUG
-    if (LoggingOn(LF_ZAP, LL_INFO10000))
-    {
-        StackSString methodString;
-        TypeString::AppendMethodDebug(methodString, pMD);
-
-        LOG((LF_ZAP, LL_INFO10000, "CEEPreloader::NextUncompiledMethod: %S\n", methodString.GetUnicode()));
-    }
-#endif // _DEBUG
-
-    return (CORINFO_METHOD_HANDLE) pMD;
-}
-
-void CEEPreloader::AddMethodToTransitiveClosureOfInstantiations(CORINFO_METHOD_HANDLE handle)
-{
-    STANDARD_VM_CONTRACT;
-
-    TriageMethodForZap(GetMethod(handle), TRUE);
-}
-
-BOOL CEEPreloader::IsMethodInTransitiveClosureOfInstantiations(CORINFO_METHOD_HANDLE handle)
-{
-    STANDARD_VM_CONTRACT;
-
-    MethodDesc *pMD = GetMethod(handle);
-
-    return (m_acceptedMethods.Lookup(pMD) != NULL) && (m_rejectedMethods.Lookup(pMD) == NULL);
-}
-
-BOOL CEEPreloader::IsTypeInTransitiveClosureOfInstantiations(CORINFO_CLASS_HANDLE handle)
-{
-    STANDARD_VM_CONTRACT;
-
-    TypeHandle th = (TypeHandle) handle;
-
-    return (m_acceptedTypes.Lookup(th) != NULL) && (m_rejectedTypes.Lookup(th) == NULL);
-}
-
-void CEEPreloader::MethodReferencedByCompiledCode(CORINFO_METHOD_HANDLE handle)
-{
-    STANDARD_VM_CONTRACT;
-
-#ifndef FEATURE_FULL_NGEN // Unreferenced methods
-    //
-    // Keep track of methods that are actually referenced by the code. We use this information
-    // to avoid generating code for unreferenced methods not visible outside the assembly.
-    // These methods are very unlikely to be ever used at runtime because of they only ever be
-    // called via private reflection.
-    //
-    MethodDesc *pMD = GetMethod(handle);
-
-    const CompileMethodEntry * pEntry = m_compileMethodsHash.LookupPtr(pMD);
-    if (pEntry != NULL)
-    {
-        if (pEntry->fReferenced)
-            return;
-        const_cast<CompileMethodEntry *>(pEntry)->fReferenced = true;
-
-        if (pEntry->fScheduled)
-            return;
-        AppendUncompiledMethod(pMD);
-    }
-    else
-    {
-        CompileMethodEntry entry;
-        entry.pMD = pMD;
-        entry.fReferenced = true;
-        entry.fScheduled = false;
-        m_compileMethodsHash.Add(entry);
-    }
-
-    if (pMD->IsWrapperStub())
-        MethodReferencedByCompiledCode((CORINFO_METHOD_HANDLE)pMD->GetWrappedMethodDesc());
-#endif // FEATURE_FULL_NGEN
-}
-
-BOOL CEEPreloader::IsUncompiledMethod(CORINFO_METHOD_HANDLE handle)
-{
-    STANDARD_VM_CONTRACT;
-
-    MethodDesc *pMD = GetMethod(handle);
-
-#ifndef FEATURE_FULL_NGEN // Unreferenced methods
-    const CompileMethodEntry * pEntry = m_compileMethodsHash.LookupPtr(pMD);
-    return (pEntry != NULL) && (pEntry->fScheduled || !pEntry->fReferenced);
-#else
-    return m_compileMethodsHash.LookupPtr(pMD) != NULL;
-#endif
-}
-
-BOOL CEEPreloader::ShouldSuppressGCTransition(CORINFO_METHOD_HANDLE handle)
-{
-    STANDARD_VM_CONTRACT;
-
-    MethodDesc *pMD = GetMethod(handle);
-    return pMD->ShouldSuppressGCTransition();
-}
-
-static bool IsTypeAccessibleOutsideItsAssembly(TypeHandle th)
-{
-    STANDARD_VM_CONTRACT;
-
-    if (th.HasTypeParam())
-    {
-        return IsTypeAccessibleOutsideItsAssembly(th.GetTypeParam());
-    }
-
-    if (th.IsTypeDesc())
-        return true;
-
-    MethodTable * pMT = th.AsMethodTable();
-
-    if (pMT == g_pCanonMethodTableClass)
-        return true;
-
-    switch (pMT->GetClass()->GetProtection())
-    {
-    case tdPublic:
-        break;
-    case tdNestedPublic:
-    case tdNestedFamily:
-    case tdNestedFamORAssem:
-        {
-            MethodTable * pMTEnclosing = pMT->LoadEnclosingMethodTable();
-            if (pMTEnclosing == NULL)
-                return false;
-            if (!IsTypeAccessibleOutsideItsAssembly(pMTEnclosing))
-                return false;
-        }
-        break;
-
-    default:
-        return false;
-    }
-
-    if (pMT->HasInstantiation())
-    {
-        Instantiation instantiation = pMT->GetInstantiation();
-        for (DWORD i = 0; i < instantiation.GetNumArgs(); i++)
-        {
-            if (!IsTypeAccessibleOutsideItsAssembly(instantiation[i]))
-                return false;
-        }
-    }
-
-    return true;
-}
-
-static bool IsMethodAccessibleOutsideItsAssembly(MethodDesc * pMD)
-{
-    STANDARD_VM_CONTRACT;
-
-    // Note that this ignores friend access.
-
-    switch (pMD->GetAttrs() & mdMemberAccessMask)
-    {
-    case mdFamily:
-    case mdFamORAssem:
-    case mdPublic:
-        break;
-
-    default:
-        return false;
-    }
-
-    if (!IsTypeAccessibleOutsideItsAssembly(pMD->GetMethodTable()))
-        return false;
-
-    if (pMD->HasMethodInstantiation())
-    {
-        Instantiation instantiation = pMD->GetMethodInstantiation();
-        for (DWORD i = 0; i < instantiation.GetNumArgs(); i++)
-        {
-            if (!IsTypeAccessibleOutsideItsAssembly(instantiation[i]))
-                return false;
-        }
-    }
-
-    return true;
-}
-
-static bool IsMethodCallableOutsideItsAssembly(MethodDesc * pMD)
-{
-    STANDARD_VM_CONTRACT;
-
-    // Virtual methods can be called via interfaces, etc. We would need to do
-    // more analysis to trim them. For now, assume that they can be referenced outside this assembly.
-    if (pMD->IsVirtual())
-        return true;
-
-    // Class constructors are often used with reflection. Always generate code for them.
-    if (pMD->IsClassConstructorOrCtor())
-        return true;
-
-    if (IsMethodAccessibleOutsideItsAssembly(pMD))
-        return true;
-
-    return false;
-}
-
-BOOL IsGenericTooDeeplyNested(TypeHandle t);
-void CEEPreloader::AddToUncompiledMethods(MethodDesc *pMD, BOOL fForStubs)
-{
-    STANDARD_VM_CONTRACT;
-
-    // TriageTypeForZap() and TriageMethodForZap() should ensure this.
-    _ASSERTE(m_image->GetModule() == pMD->GetLoaderModule());
-
-    if (!fForStubs)
-    {
-        if (!pMD->IsIL())
-            return;
-
-        if (!pMD->MayHaveNativeCode() && !pMD->IsWrapperStub())
-            return;
-    }
-
-    // If it's already been compiled, don't add it to the set of uncompiled methods
-    if (m_image->GetCodeAddress(pMD) != NULL)
-        return;
-
-    // If it's already in the queue to be compiled don't add it again
-    const CompileMethodEntry * pEntry = m_compileMethodsHash.LookupPtr(pMD);
-
-#ifndef FEATURE_FULL_NGEN // Unreferenced methods
-   if (pEntry != NULL)
-    {
-        if (pEntry->fScheduled)
-            return;
-
-        if (!pEntry->fReferenced)
-            return;
-
-        const_cast<CompileMethodEntry *>(pEntry)->fScheduled = true;
-    }
-    else
-    {
-        // The unreferenced methods optimization works for generic methods and methods on generic types only.
-        // Non-generic methods take different path.
-        //
-        // It unclear whether it is worth it to enable it for non-generic methods too. The benefit
-        // for non-generic methods is small, and the non-generic methods are more likely to be called
-        // via private reflection.
-
-        bool fSchedule = fForStubs || IsMethodCallableOutsideItsAssembly(pMD);
-
-        CompileMethodEntry entry;
-        entry.pMD = pMD;
-        entry.fScheduled = fSchedule;
-        entry.fReferenced = false;
-        m_compileMethodsHash.Add(entry);
-
-        if (!fSchedule)
-            return;
-    }
-#else // // FEATURE_FULL_NGEN
-    // Schedule the method for compilation
-    if (pEntry != NULL)
-        return;
-    CompileMethodEntry entry;
-    entry.pMD = pMD;
-    m_compileMethodsHash.Add(entry);
-#endif // FEATURE_FULL_NGEN
-
-    if (pMD->HasMethodInstantiation())
-    {
-        Instantiation instantiation = pMD->GetMethodInstantiation();
-        for (DWORD i = 0; i < instantiation.GetNumArgs(); i++)
-        {
-            if (IsGenericTooDeeplyNested(instantiation[i]))
-                return;
-        }
-    }
-
-    // Add it to the set of uncompiled methods
-    AppendUncompiledMethod(pMD);
-}
-
-//
-// Used to validate instantiations produced by the production rules before we actually try to instantiate them.
-//
-static BOOL CanSatisfyConstraints(Instantiation typicalInst, Instantiation candidateInst)
-{
-    STANDARD_VM_CONTRACT;
-
-    // The dependency must be of the form C<T> --> D<T>
-    _ASSERTE(typicalInst.GetNumArgs() == candidateInst.GetNumArgs());
-    if (typicalInst.GetNumArgs() != candidateInst.GetNumArgs())
-        return FALSE;
-
-    SigTypeContext typeContext(candidateInst, Instantiation());
-
-    for (DWORD i = 0; i < candidateInst.GetNumArgs(); i++)
-    {
-        TypeHandle thArg = candidateInst[i];
-
-        // If this is "__Canon" and we are code sharing then we can't rule out that some
-        // compatible instantiation may meet the constraints
-        if (thArg == TypeHandle(g_pCanonMethodTableClass))
-            continue;
-
-        // Otherwise we approximate, and just assume that we have "parametric" constraints
-        // of the form "T : IComparable<T>" rather than "odd" constraints such as "T : IComparable<string>".
-        // That is, we assume checking the constraint at the canonical type is sufficient
-        // to tell us if the constraint holds for all compatible types.
-        //
-        // For example of where this does not hold, consider if
-        //     class C<T>
-        //     class D<T> where T : IComparable<T>
-        //     struct Struct<T> : IComparable<string>
-        // Assume we generate C<Struct<object>>.  Now the constraint
-        //     Struct<object> : IComparable<object>
-        // does not hold, so we do not generate the instantiation, even though strictly speaking
-        // the compatible instantiation C<Struct<string>> will satisfy the constraint
-        //     Struct<string> : IComparable<string>
-
-        TypeVarTypeDesc* tyvar = typicalInst[i].AsGenericVariable();
-
-        tyvar->LoadConstraints();
-
-        if (!tyvar->SatisfiesConstraints(&typeContext,thArg)) {
-#ifdef _DEBUG
-            /*
-            // In case we want to know which illegal instantiations we ngen'ed
-            StackSString candidateInstName;
-            StackScratchBuffer buffer;
-            thArg.GetName(candidateInstName);
-            char output[1024];
-            _snprintf_s(output, _countof(output), _TRUNCATE, "Generics TypeDependencyAttribute processing: Couldn't satisfy a constraint.  Class with Attribute: %s  Bad candidate instantiated type: %s\r\n", pMT->GetDebugClassName(), candidateInstName.GetANSI(buffer));
-            OutputDebugStringA(output);
-            */
-#endif
-            return FALSE;
-        }
-    }
-
-    return TRUE;
-}
-
-
-//
-// This method has duplicated logic from coreclr\System.Private.CoreLib\src\System\Collections\Generic\ComparerHelpers.cs
-//
-static void SpecializeComparer(SString& ss, Instantiation& inst)
-{
-    STANDARD_VM_CONTRACT;
-
-    if (inst.GetNumArgs() != 1) {
-        _ASSERTE(!"Improper use of a TypeDependencyAttribute for Comparer");
-        return;
-    }
-
-    TypeHandle elemTypeHnd = inst[0];
-
-    //
-    // Override the default ObjectComparer for special cases
-    //
-    if (elemTypeHnd.CanCastTo(
-        TypeHandle(CoreLibBinder::GetClass(CLASS__ICOMPARABLEGENERIC)).Instantiate(Instantiation(&elemTypeHnd, 1))))
-    {
-        ss.Set(W("System.Collections.Generic.GenericComparer`1"));
-        return;
-    }
-
-    if (Nullable::IsNullableType(elemTypeHnd))
-    {
-        Instantiation nullableInst = elemTypeHnd.AsMethodTable()->GetInstantiation();
-        if (nullableInst[0].CanCastTo(
-            TypeHandle(CoreLibBinder::GetClass(CLASS__ICOMPARABLEGENERIC)).Instantiate(nullableInst)))
-        {
-            ss.Set(W("System.Collections.Generic.NullableComparer`1"));
-            inst = nullableInst;
-            return;
-        }
-    }
-
-    if (elemTypeHnd.IsEnum())
-    {
-        CorElementType et = elemTypeHnd.GetVerifierCorElementType();
-        if (et == ELEMENT_TYPE_I1 ||
-            et == ELEMENT_TYPE_I2 ||
-            et == ELEMENT_TYPE_I4 ||
-            et == ELEMENT_TYPE_I8 ||
-            et == ELEMENT_TYPE_U1 ||
-            et == ELEMENT_TYPE_U2 ||
-            et == ELEMENT_TYPE_U4 ||
-            et == ELEMENT_TYPE_U8)
-        {
-            ss.Set(W("System.Collections.Generic.EnumComparer`1"));
-            return;
-        }
-    }
-}
-
-//
-// This method has duplicated logic from coreclr\System.Private.CoreLib\src\System\Collections\Generic\ComparerHelpers.cs
-// and matching logic in jitinterface.cpp
-//
-static void SpecializeEqualityComparer(SString& ss, Instantiation& inst)
-{
-    STANDARD_VM_CONTRACT;
-
-    if (inst.GetNumArgs() != 1) {
-        _ASSERTE(!"Improper use of a TypeDependencyAttribute for EqualityComparer");
-        return;
-    }
-
-    TypeHandle elemTypeHnd = inst[0];
-
-    //
-    // Override the default ObjectEqualityComparer for special cases
-    //
-    if (elemTypeHnd.CanCastTo(
-        TypeHandle(CoreLibBinder::GetClass(CLASS__IEQUATABLEGENERIC)).Instantiate(Instantiation(&elemTypeHnd, 1))))
-    {
-        ss.Set(W("System.Collections.Generic.GenericEqualityComparer`1"));
-        return;
-    }
-
-    if (Nullable::IsNullableType(elemTypeHnd))
-    {
-        Instantiation nullableInst = elemTypeHnd.AsMethodTable()->GetInstantiation();
-        if (nullableInst[0].CanCastTo(
-            TypeHandle(CoreLibBinder::GetClass(CLASS__IEQUATABLEGENERIC)).Instantiate(nullableInst)))
-        {
-            ss.Set(W("System.Collections.Generic.NullableEqualityComparer`1"));
-            inst = nullableInst;
-            return;
-        }
-    }
-
-    if (elemTypeHnd.IsEnum())
-    {
-        CorElementType et = elemTypeHnd.GetVerifierCorElementType();
-        if (et == ELEMENT_TYPE_I1 ||
-            et == ELEMENT_TYPE_I2 ||
-            et == ELEMENT_TYPE_I4 ||
-            et == ELEMENT_TYPE_I8 ||
-            et == ELEMENT_TYPE_U1 ||
-            et == ELEMENT_TYPE_U2 ||
-            et == ELEMENT_TYPE_U4 ||
-            et == ELEMENT_TYPE_U8)
-        {
-            ss.Set(W("System.Collections.Generic.EnumEqualityComparer`1"));
-            return;
-        }
-    }
-}
-
-void CEEPreloader::ApplyTypeDependencyProductionsForType(TypeHandle t)
-{
-    STANDARD_VM_CONTRACT;
-
-    // Only actual types
-    if (t.IsTypeDesc() || t.IsArray())
-        return;
-
-    MethodTable * pMT = t.AsMethodTable();
-
-    if (!pMT->HasInstantiation() || pMT->ContainsGenericVariables())
-        return;
-
-    pMT = pMT->GetCanonicalMethodTable();
-
-    // The TypeDependencyAttribute attribute is currently only allowed on CoreLib types
-    // Don't even look for the attribute on types in other assemblies.
-    if(!pMT->GetModule()->IsSystem()) {
-        return;
-    }
-
-    // Part 1. - check for an NGEN production rule specified by a use of CompilerServices.TypeDependencyAttribute
-    //  e.g. C<T> --> D<T>
-    //
-    // For example, if C<int> is generated then we produce D<int>.
-    //
-    // Normally NGEN can detect such productions through the process of compilation, but there are some
-    // legitimate uses of reflection to generate generic instantiations which NGEN cannot detect.
-    // In particular typically D<T> will have more constraints than C<T>, e.g.
-    //     class D<T> where T : IComparable<T>
-    // Uses of dynamic constraints are an example - consider making a Comparer<T>, where we can have a
-    // FastComparer<T> where T : IComparable<T>, and the "slow" version checks for the non-generic
-    // IComparer interface.
-    // Also, T[] : IList<T>, IReadOnlyList<T>, and both of those interfaces should have a type dependency on SZArrayHelper's generic methods.
-    //
-    IMDInternalImport *pImport = pMT->GetMDImport();
-    HRESULT hr;
-
-    _ASSERTE(pImport);
-    //walk all of the TypeDependencyAttributes
-    MDEnumHolder hEnum(pImport);
-    hr = pImport->EnumCustomAttributeByNameInit(pMT->GetCl(),
-                                                g_CompilerServicesTypeDependencyAttribute, &hEnum);
-    if (SUCCEEDED(hr))
-    {
-        mdCustomAttribute tkAttribute;
-        const BYTE *pbAttr;
-        ULONG cbAttr;
-
-        while (pImport->EnumNext(&hEnum, &tkAttribute))
-        {
-            //get attribute and validate format
-            if (FAILED(pImport->GetCustomAttributeAsBlob(
-                tkAttribute,
-                reinterpret_cast<const void **>(&pbAttr),
-                &cbAttr)))
-            {
-                continue;
-            }
-
-            CustomAttributeParser cap(pbAttr, cbAttr);
-            if (FAILED(cap.SkipProlog()))
-                continue;
-
-            LPCUTF8 szString;
-            ULONG   cbString;
-            if (FAILED(cap.GetNonNullString(&szString, &cbString)))
-                continue;
-
-            StackSString ss(SString::Utf8, szString, cbString);
-            Instantiation inst = pMT->GetInstantiation();
-
-#ifndef FEATURE_FULL_NGEN
-            // Do not expand non-canonical instantiations. They are not that expensive to create at runtime
-            // using code:ClassLoader::CreateTypeHandleForNonCanonicalGenericInstantiation if necessary.
-            if (!ClassLoader::IsCanonicalGenericInstantiation(inst))
-                continue;
-#endif
-
-            if (ss.Equals(W("System.Collections.Generic.ObjectComparer`1")))
-            {
-                SpecializeComparer(ss, inst);
-            }
-            else
-            if (ss.Equals(W("System.Collections.Generic.ObjectEqualityComparer`1")))
-            {
-                SpecializeEqualityComparer(ss, inst);
-            }
-
-            // Try to load the class using its name as a fully qualified name. If that fails,
-            // then we try to load it in the assembly of the current class.
-            TypeHandle typicalDepTH = TypeName::GetTypeUsingCASearchRules(ss.GetUnicode(), pMT->GetAssembly());
-
-            _ASSERTE(!typicalDepTH.IsNull());
-            // This attribute is currently only allowed to refer to CoreLib types
-            _ASSERTE(typicalDepTH.GetModule()->IsSystem());
-            if (!typicalDepTH.GetModule()->IsSystem())
-                continue;
-
-            // For IList<T>, ICollection<T>, IEnumerable<T>, IReadOnlyCollection<T> & IReadOnlyList<T>, include SZArrayHelper's
-            // generic methods (or at least the relevant ones) in the ngen image in
-            // case someone casts a T[] to an IList<T> (or ICollection<T> or IEnumerable<T>, etc).
-            if (CoreLibBinder::IsClass(typicalDepTH.AsMethodTable(), CLASS__SZARRAYHELPER))
-            {
-#ifdef FEATURE_FULL_NGEN
-                if (pMT->GetNumGenericArgs() != 1 || !pMT->IsInterface()) {
-                    _ASSERTE(!"Improper use of a TypeDependencyAttribute for SZArrayHelper");
-                    continue;
-                }
-                TypeHandle elemTypeHnd = pMT->GetInstantiation()[0];
-                if (elemTypeHnd.IsValueType())
-                    ApplyTypeDependencyForSZArrayHelper(pMT, elemTypeHnd);
-#endif
-                continue;
-            }
-
-            _ASSERTE(typicalDepTH.IsTypicalTypeDefinition());
-            if (!typicalDepTH.IsTypicalTypeDefinition())
-                continue;
-
-            // It certainly can't be immediately recursive...
-            _ASSERTE(!typicalDepTH.GetMethodTable()->HasSameTypeDefAs(pMT));
-
-            // We want to rule out some cases where we know for sure that the generated type
-            // won't satisfy its constraints.  However, some generated types may represent
-            // canonicals in sets of shared instantaitions,
-
-            if (CanSatisfyConstraints(typicalDepTH.GetInstantiation(), inst))
-            {
-                TypeHandle instDepTH =
-                    ClassLoader::LoadGenericInstantiationThrowing(typicalDepTH.GetModule(), typicalDepTH.GetCl(), inst);
-
-                _ASSERTE(!instDepTH.ContainsGenericVariables());
-                _ASSERTE(instDepTH.GetNumGenericArgs() == typicalDepTH.GetNumGenericArgs());
-                _ASSERTE(instDepTH.GetMethodTable()->HasSameTypeDefAs(typicalDepTH.GetMethodTable()));
-
-                // OK, add the generated type to the dependency set
-                TriageTypeForZap(instDepTH, TRUE);
-            }
-        }
-    }
-} // CEEPreloader::ApplyTypeDependencyProductionsForType
-
-
-// Given IEnumerable<Foo>, we want to add System.SZArrayHelper.GetEnumerator<Foo>
-// to the ngen image.  This way we can cast a T[] to an IList<T> and
-// use methods on it (from SZArrayHelper) without pulling in the JIT.
-// Do the same for ICollection<T>/IReadOnlyCollection<T> and
-// IList<T>/IReadOnlyList<T>, but only add the relevant methods
-// from those interfaces.
-void CEEPreloader::ApplyTypeDependencyForSZArrayHelper(MethodTable * pInterfaceMT, TypeHandle elemTypeHnd)
-{
-    STANDARD_VM_CONTRACT;
-
-    _ASSERTE(elemTypeHnd.AsMethodTable()->IsValueType());
-
-    // We expect this to only be called for IList<T>/IReadOnlyList<T>, ICollection<T>/IReadOnlyCollection<T>, IEnumerable<T>.
-    _ASSERTE(pInterfaceMT->IsInterface());
-    _ASSERTE(pInterfaceMT->GetNumGenericArgs() == 1);
-
-    // This is the list of methods that don't throw exceptions on SZArrayHelper.
-    static const BinderMethodID SZArrayHelperMethodIDs[] = {
-        // Read-only methods that are present on both regular and read-only interfaces.
-        METHOD__SZARRAYHELPER__GETENUMERATOR,
-        METHOD__SZARRAYHELPER__GET_COUNT,
-        METHOD__SZARRAYHELPER__GET_ITEM,
-        // The rest of the methods is present on regular interfaces only.
-        METHOD__SZARRAYHELPER__SET_ITEM,
-        METHOD__SZARRAYHELPER__COPYTO,
-        METHOD__SZARRAYHELPER__INDEXOF,
-        METHOD__SZARRAYHELPER__CONTAINS };
-
-    static const int cReadOnlyMethods = 3;
-    static const int cAllMethods = 7;
-
-    static const BinderMethodID LastMethodOnGenericArrayInterfaces[] = {
-        METHOD__SZARRAYHELPER__GETENUMERATOR, // Last method of IEnumerable<T>
-        METHOD__SZARRAYHELPER__REMOVE, // Last method of ICollection<T>.
-        METHOD__SZARRAYHELPER__REMOVEAT, // Last method of IList<T>
-    };
-
-    // Assuming the binder ID's are properly laid out in corelib.h
-#if _DEBUG
-    for(unsigned int i=0; i < NumItems(LastMethodOnGenericArrayInterfaces) - 1; i++) {
-        _ASSERTE(LastMethodOnGenericArrayInterfaces[i] < LastMethodOnGenericArrayInterfaces[i+1]);
-    }
-#endif
-
-    MethodTable* pExactMT = CoreLibBinder::GetClass(CLASS__SZARRAYHELPER);
-
-    // Subtract one from the non-generic IEnumerable that the generic IEnumerable<T>
-    // inherits from.
-    unsigned inheritanceDepth = pInterfaceMT->GetNumInterfaces() - 1;
-    PREFIX_ASSUME(0 <= inheritanceDepth && inheritanceDepth < NumItems(LastMethodOnGenericArrayInterfaces));
-
-    // Read-only interfaces happen to always have one method
-    bool fIsReadOnly = pInterfaceMT->GetNumVirtuals() == 1;
-
-    for(int i=0; i < (fIsReadOnly ? cReadOnlyMethods : cAllMethods); i++)
-    {
-        // Check whether the method applies for this type.
-        if (SZArrayHelperMethodIDs[i] > LastMethodOnGenericArrayInterfaces[inheritanceDepth])
-            continue;
-
-        MethodDesc * pPrimaryMD = CoreLibBinder::GetMethod(SZArrayHelperMethodIDs[i]);
-
-        MethodDesc * pInstantiatedMD = MethodDesc::FindOrCreateAssociatedMethodDesc(pPrimaryMD,
-                                           pExactMT, false, Instantiation(&elemTypeHnd, 1), false);
-
-        TriageMethodForZap(pInstantiatedMD, true);
-    }
-}
-
-
-void CEEPreloader::AddTypeToTransitiveClosureOfInstantiations(CORINFO_CLASS_HANDLE handle)
-{
-    STANDARD_VM_CONTRACT;
-
-    TriageTypeForZap((TypeHandle) handle, TRUE);
-}
-
-const unsigned MAX_ZAP_INSTANTIATION_NESTING = 10;
-
-BOOL IsGenericTooDeeplyNested(TypeHandle t)
-{
-    CONTRACTL
-    {
-        NOTHROW;
-        MODE_ANY;
-    }
-    CONTRACTL_END;
-    //if this type is more than N levels nested deep, do not add it to the
-    //closure.  Build a queue for a DFS of the depth of instantiation.
-
-    //the current index in the queue we're visiting
-    int currentQueueIdx; //use -1 to indicate that we're done.
-    //the current generic arg type.
-    TypeHandle currentVisitingType[MAX_ZAP_INSTANTIATION_NESTING];
-
-    //the ordinal in the GetInstantiation for the current type (over [0,
-    //GetNumGenericArg())
-    unsigned currentGenericArgEdge[MAX_ZAP_INSTANTIATION_NESTING];
-
-    //initialize the DFS.
-    memset(currentGenericArgEdge, 0, sizeof(currentGenericArgEdge));
-    currentVisitingType[0] = t;
-    currentQueueIdx = 0;
-
-    while( currentQueueIdx >= 0 )
-    {
-        //see if we're done with this node
-        if( currentVisitingType[currentQueueIdx].GetNumGenericArgs()
-            <= currentGenericArgEdge[currentQueueIdx] )
-        {
-            --currentQueueIdx;
-        }
-        else
-        {
-            //more edges to visit.  So visit one edge
-            _ASSERTE(currentGenericArgEdge[currentQueueIdx] < currentVisitingType[currentQueueIdx].GetNumGenericArgs());
-            TypeHandle current = currentVisitingType[currentQueueIdx].GetInstantiation()[currentGenericArgEdge[currentQueueIdx]];
-            ++currentGenericArgEdge[currentQueueIdx];
-            //only value types cause a problem because of "approximate" type
-            //loading, so only worry about scanning value type arguments.
-            if( current.HasInstantiation() && current.IsValueType()  )
-            {
-                //new edge.  Make sure there is space in the queue.
-                if( (currentQueueIdx + 1) >= (int)NumItems(currentGenericArgEdge) )
-                {
-                    //exceeded the allowable depth.  Stop processing.
-                    return TRUE;
-                }
-                else
-                {
-                    ++currentQueueIdx;
-                    currentGenericArgEdge[currentQueueIdx] = 0;
-                    currentVisitingType[currentQueueIdx] = current;
-                }
-            }
-        }
-    }
-
-    return FALSE;
-}
-
-void CEEPreloader::TriageTypeForZap(TypeHandle th, BOOL fAcceptIfNotSure, BOOL fExpandDependencies)
-{
-    STANDARD_VM_CONTRACT;
-
-    // We care about param types only
-    if (th.IsTypicalTypeDefinition() && !(th.IsTypeDesc() || th.IsArray()))
-        return;
-
-    // We care about types from our module only
-    if (m_image->GetModule() != th.GetLoaderModule())
-        return;
-
-    // Check if we have decided to accept this type already.
-    if (m_acceptedTypes.Lookup(th) != NULL)
-        return;
-
-    // Check if we have decided to reject this type already.
-    if (m_rejectedTypes.Lookup(th) != NULL)
-        return;
-
-    enum { Investigate, Accepted, Rejected } triage = Investigate;
-
-    const char * rejectReason = NULL;
-
-    // TypeVarTypeDesc are saved via links from code:Module::m_GenericParamToDescMap
-    if (th.IsGenericVariable())
-    {
-        triage = Rejected;
-        rejectReason = "type is a Generic variable";
-        goto Done;
-    }
-
-    /* Consider this example:
-
-    class A<T> {}
-    class B<U> : A<U> {}
-
-    class C<V> : B<V>
-    {
-        void foo<W>()
-        {
-            typeof(C<W>);
-            typeof(B<A<W>>);
-
-            typeof(List<V>);
-        }
-    }
-
-    The open instantiations can be divided into the following 3 categories:
-
-    1. A<T>,  B<U>, A<U>,  C<V>, B<V>, A<V> are open instantiations involving
-       ELEMENT_TYPE_VARs that need to be saved in the ngen image.
-    2. List<V> is an instantiations that also involves ELEMENT_TYPE_VARs.
-       However, it need not be saved since it will only be needed during the
-       verification of foo<W>().
-    3. C<W>, A<W>, B<A<W>> are open instantiations involving ELEMENT_TYPE_MVARs
-       that need not be saved since they will only be needed during the
-       verification of foo<W>().
-
-    Distinguishing between 1 and 2 requires walking C<V> and determining
-    which ones are field/parent/interface types required by c<V>. However,
-    category 3 is easy to detect, and can easily be pruned out. Hence,
-    we pass in methodTypeVarsOnly=TRUE here.
-    */
-    if (th.ContainsGenericVariables(TRUE/*methodTypeVarsOnly*/))
-    {
-        triage = Rejected;
-        rejectReason = "type contains method generic variables";
-        goto Done;
-    }
-
-    // Filter out weird cases we do not care about.
-    if (!m_image->GetModule()->GetAvailableParamTypes()->ContainsValue(th))
-    {
-        triage = Rejected;
-        rejectReason = "type is not in the current module";
-        return;
-    }
-
-    // Reject invalid generic instantiations. They will not be fully loaded
-    // as they will throw a TypeLoadException before they reach CLASS_LOAD_LEVEL_FINAL.
-    if (!th.IsFullyLoaded())
-    {
-        // This may load new types. May load new types.
-        ClassLoader::TryEnsureLoaded(th);
-
-        if (!th.IsFullyLoaded())
-        {
-            triage = Rejected;
-            rejectReason = "type could not be fully loaded, possibly because it does not satisfy its constraints";
-            goto Done;
-        }
-    }
-
-    // Do not save any types containing generic class parameters from another module
-    Module *pOpenModule;
-    pOpenModule = th.GetDefiningModuleForOpenType();
-    if (pOpenModule != NULL && pOpenModule != m_image->GetModule())
-    {
-        triage = Rejected;
-        rejectReason = "type contains generic variables from another module";
-        goto Done;
-    }
-
-    // Always store items in their preferred zap module even if we are not sure
-    if (Module::GetPreferredZapModuleForTypeHandle(th) == m_image->GetModule())
-    {
-        triage = Accepted;
-        goto Done;
-    }
-
-#ifdef FEATURE_FULL_NGEN
-    // Only save arrays and param types in their preferred zap modules,
-    // i.e. never duplicate them.
-    if (th.IsTypeDesc() || th.IsArray())
-    {
-        triage = Rejected;
-        rejectReason = "type is a TypeDesc";
-        goto Done;
-    }
-
-    {
-        // Do not save instantiations found in one of our hardbound dependencies
-        PtrHashMap::PtrIterator iter = GetAppDomain()->ToCompilationDomain()->IterateHardBoundModules();
-        for (/**/; !iter.end(); ++iter)
-        {
-            Module * hardBoundModule = (Module*)iter.GetValue();
-            if (hardBoundModule->GetAvailableParamTypes()->ContainsValue(th))
-            {
-                triage = Rejected;
-                rejectReason = "type was found in a hardbound dependency";
-                goto Done;
-            }
-        }
-    }
-
-    // We are not really sure about this type. Accept it only if we have been asked to.
-    if (fAcceptIfNotSure)
-    {
-        if (!m_fSpeculativeTriage)
-        {
-            // We will take a look later before we actually start compiling the instantiations
-            m_speculativeTypes.Append(th);
-            m_acceptedTypes.Add(th);
-            return;
-        }
-
-        triage = Accepted;
-        goto Done;
-    }
-#else
-    rejectReason = "type is not in the preferred module";
-    triage = Rejected;
-#endif
-
-Done:
-    switch (triage)
-    {
-    case Accepted:
-        m_acceptedTypes.Add(th);
-        if (fExpandDependencies)
-        {
-            ExpandTypeDependencies(th);
-        }
-        break;
-
-    case Rejected:
-
-        m_rejectedTypes.Add(th);
-
-#ifdef LOGGING
-        // It is expensive to call th.GetName, only do it when we are actually logging
-        if (LoggingEnabled())
-        {
-            SString typeName;
-            th.GetName(typeName);
-            LOG((LF_ZAP, LL_INFO10000, "TriageTypeForZap rejects %S (%08x) because %s\n",
-                 typeName.GetUnicode(), th.AsPtr(), rejectReason));
-        }
-#endif
-        break;
-
-    default:
-        // We have not found a compeling reason to accept or reject the type yet. Maybe next time...
-        break;
-    }
-}
-
-void CEEPreloader::ExpandTypeDependencies(TypeHandle th)
-{
-    STANDARD_VM_CONTRACT;
-
-    if (th.IsTypeDesc())
-        return;
-
-    MethodTable* pMT = th.AsMethodTable();
-
-    if (pMT->IsCanonicalMethodTable())
-    {
-        // Cutoff infinite recursion.
-        if (!IsGenericTooDeeplyNested(th))
-        {
-            // Make sure all methods are compiled
-            // We only want to check the method bodies owned by this type,
-            // and not any method bodies owned by a parent type, as the
-            // parent type may not get saved in this ngen image.
-            MethodTable::IntroducedMethodIterator itr(pMT);
-            for (/**/; itr.IsValid(); itr.Next())
-            {
-                AddToUncompiledMethods(itr.GetMethodDesc(), FALSE);
-            }
-        }
-    }
-    else
-    {
-        // Make sure canonical method table is saved
-        TriageTypeForZap(pMT->GetCanonicalMethodTable(), TRUE);
-    }
-
-    // Make sure parent type is saved
-    TriageTypeForZap(pMT->GetParentMethodTable(), TRUE);
-
-    // Make sure all instantiation arguments are saved
-    Instantiation inst = pMT->GetInstantiation();
-    for (DWORD iArg = 0; iArg < inst.GetNumArgs(); iArg++)
-    {
-        TriageTypeForZap(inst[iArg], TRUE);
-    }
-
-    // Make sure all interfaces implemeted by the class are saved
-    MethodTable::InterfaceMapIterator intIterator = pMT->IterateInterfaceMap();
-    while (intIterator.Next())
-    {
-        TriageTypeForZap(intIterator.GetInterfaceApprox(), TRUE);
-    }
-
-    // Make sure approx types for all fields are saved
-    ApproxFieldDescIterator fdIterator(pMT, ApproxFieldDescIterator::ALL_FIELDS);
-    FieldDesc* pFD;
-    while ((pFD = fdIterator.Next()) != NULL)
-    {
-        if (pFD->GetFieldType() == ELEMENT_TYPE_VALUETYPE)
-        {
-            TriageTypeForZap(pFD->GetFieldTypeHandleThrowing(), TRUE);
-        }
-    }
-
-    // Make sure types for all generic static fields are saved
-
-    if (pMT->HasGenericsStaticsInfo())
-    {
-        FieldDesc *pGenStaticFields = pMT->GetGenericsStaticFieldDescs();
-        DWORD nFields = pMT->GetNumStaticFields();
-        for (DWORD iField = 0; iField < nFields; iField++)
-        {
-            FieldDesc* pField = &pGenStaticFields[iField];
-            if (pField->GetFieldType() == ELEMENT_TYPE_VALUETYPE)
-            {
-                TriageTypeForZap(pField->GetFieldTypeHandleThrowing(), TRUE);
-            }
-        }
-    }
-
-    // Expand type using the custom rules. May load new types.
-    ApplyTypeDependencyProductionsForType(th);
-}
-
-// Triage instantiations of generic methods
-
-void CEEPreloader::TriageMethodForZap(MethodDesc* pMD, BOOL fAcceptIfNotSure, BOOL fExpandDependencies)
-{
-    STANDARD_VM_CONTRACT;
-
-    // Submit the method type for triage
-    TriageTypeForZap(TypeHandle(pMD->GetMethodTable()), fAcceptIfNotSure);
-
-    // We care about instantiated methods only
-    if (pMD->IsTypicalMethodDefinition())
-        return;
-
-    // We care about methods from our module only
-    if (m_image->GetModule() != pMD->GetLoaderModule())
-        return;
-
-    // Check if we have decided to accept this method already.
-    if (m_acceptedMethods.Lookup(pMD) != NULL)
-        return;
-
-    // Check if we have decided to reject this method already.
-    if (m_rejectedMethods.Lookup(pMD) != NULL)
-        return;
-
-    enum { Investigate, Accepted, Rejected } triage = Investigate;
-
-    const char * rejectReason = NULL;
-
-    // Do not save open methods
-    if (pMD->ContainsGenericVariables())
-    {
-        triage = Rejected;
-        rejectReason = "method contains method generic variables";
-        goto Done;
-    }
-
-    // Always store items in their preferred zap module even if we are not sure
-    if (Module::GetPreferredZapModuleForMethodDesc(pMD) == m_image->GetModule())
-    {
-        triage = Accepted;
-        goto Done;
-    }
-
-#ifdef FEATURE_FULL_NGEN
-    {
-        // Do not save instantiations found in one of our hardbound dependencies
-        PtrHashMap::PtrIterator iter = GetAppDomain()->ToCompilationDomain()->IterateHardBoundModules();
-        for (/**/; !iter.end(); ++iter)
-        {
-            Module * hardBoundModule = (Module*)iter.GetValue();
-            if (hardBoundModule->GetInstMethodHashTable()->ContainsMethodDesc(pMD))
-            {
-                triage = Rejected;
-                rejectReason = "method was found in a hardbound dependency";
-                goto Done;
-            }
-        }
-    }
-
-    // We are not really sure about this method. Accept it only if we have been asked to.
-    if (fAcceptIfNotSure)
-    {
-        // It does not seem worth it to go through extra hoops to eliminate redundant
-        // speculative method instatiations from softbound dependencies like we do for types
-        // if (!m_fSpeculativeTriage)
-        // {
-        //    // We will take a look later before we actually start compiling the instantiations
-        //    ...
-        // }
-
-        triage = Accepted;
-        goto Done;
-    }
-#else
-    triage = Rejected;
-#endif
-
-Done:
-    switch (triage)
-    {
-    case Accepted:
-        m_acceptedMethods.Add(pMD);
-        if (fExpandDependencies)
-        {
-            ExpandMethodDependencies(pMD);
-        }
-        break;
-
-    case Rejected:
-        m_rejectedMethods.Add(pMD);
-        LOG((LF_ZAP, LL_INFO10000, "TriageMethodForZap rejects %s (%08x) because %s\n",
-            pMD->m_pszDebugMethodName, pMD, rejectReason));
-        break;
-
-    default:
-        // We have not found a compeling reason to accept or reject the method yet. Maybe next time...
-        break;
-    }
-}
-
-void CEEPreloader::ExpandMethodDependencies(MethodDesc * pMD)
-{
-    STANDARD_VM_CONTRACT;
-
-    AddToUncompiledMethods(pMD, FALSE);
-
-    {
-        // Make sure all instantiation arguments are saved
-        Instantiation inst = pMD->GetMethodInstantiation();
-        for (DWORD iArg = 0; iArg < inst.GetNumArgs(); iArg++)
-        {
-            TriageTypeForZap(inst[iArg], TRUE);
-        }
-    }
-
-    // Make sure to add wrapped method desc
-    if (pMD->IsWrapperStub())
-        TriageMethodForZap(pMD->GetWrappedMethodDesc(), TRUE);
-}
-
-void CEEPreloader::TriageTypeFromSoftBoundModule(TypeHandle th, Module * pSoftBoundModule)
-{
-    STANDARD_VM_CONTRACT;
-
-    // We care about types from our module only
-    if (m_image->GetModule() != th.GetLoaderModule())
-        return;
-
-    // Nothing to do if we have rejected the type already.
-    if (m_rejectedTypes.Lookup(th) != NULL)
-        return;
-
-    // We make guarantees about types living in its own PZM only
-    if (Module::GetPreferredZapModuleForTypeHandle(th) != pSoftBoundModule)
-        return;
-
-    // Reject the type - it is guaranteed to be saved in PZM
-    m_rejectedTypes.Add(th);
-
-    if (!th.IsTypeDesc())
-    {
-        // Reject the canonical method table if possible.
-        MethodTable* pMT = th.AsMethodTable();
-        if (!pMT->IsCanonicalMethodTable())
-            TriageTypeFromSoftBoundModule(pMT->GetCanonicalMethodTable(), pSoftBoundModule);
-
-        // Reject parent method table if possible.
-        TriageTypeFromSoftBoundModule(pMT->GetParentMethodTable(), pSoftBoundModule);
-
-        // Reject all interfaces implemented by the type if possible.
-        MethodTable::InterfaceMapIterator intIterator = pMT->IterateInterfaceMap();
-        while (intIterator.Next())
-        {
-            TriageTypeFromSoftBoundModule(intIterator.GetInterfaceApprox(), pSoftBoundModule);
-        }
-
-        // It does not seem worth it to reject the remaining items
-        // expanded by CEEPreloader::ExpandTypeDependencies here.
-    }
-}
-
-#ifdef FEATURE_FULL_NGEN
-static TypeHandle TryToLoadTypeSpecHelper(Module * pModule, PCCOR_SIGNATURE pSig, ULONG cSig)
-{
-    STANDARD_VM_CONTRACT;
-
-    TypeHandle th;
-
-    EX_TRY
-    {
-        SigPointer p(pSig, cSig);
-        SigTypeContext typeContext;    // empty context is OK: encoding should not contain type variables.
-
-        th = p.GetTypeHandleThrowing(pModule, &typeContext, ClassLoader::DontLoadTypes);
-    }
-    EX_CATCH
-    {
-    }
-    EX_END_CATCH(SwallowAllExceptions)
-
-    return th;
-}
-
-void CEEPreloader::TriageTypeSpecsFromSoftBoundModule(Module * pSoftBoundModule)
-{
-    STANDARD_VM_CONTRACT;
-
-    //
-    // Reject all typespecs that are guranteed to be found in soft bound PZM
-    //
-
-    IMDInternalImport *pInternalImport = pSoftBoundModule->GetMDImport();
-
-    HENUMInternalHolder hEnum(pInternalImport);
-    hEnum.EnumAllInit(mdtTypeSpec);
-
-    mdToken tk;
-    while (pInternalImport->EnumNext(&hEnum, &tk))
-    {
-        ULONG cSig;
-        PCCOR_SIGNATURE pSig;
-
-        if (FAILED(pInternalImport->GetTypeSpecFromToken(tk, &pSig, &cSig)))
-        {
-            pSig = NULL;
-            cSig = 0;
-        }
-
-        // Check all types specs that do not contain variables
-        if (SigPointer(pSig, cSig).IsPolyType(NULL) == hasNoVars)
-        {
-            TypeHandle th = TryToLoadTypeSpecHelper(pSoftBoundModule, pSig, cSig);
-
-            if (th.IsNull())
-                continue;
-
-            TriageTypeFromSoftBoundModule(th, pSoftBoundModule);
-        }
-    }
-}
-
-void CEEPreloader::TriageSpeculativeType(TypeHandle th)
-{
-    STANDARD_VM_CONTRACT;
-
-    // Nothing to do if we have rejected the type already
-    if (m_rejectedTypes.Lookup(th) != NULL)
-        return;
-
-    Module * pPreferredZapModule = Module::GetPreferredZapModuleForTypeHandle(th);
-    BOOL fHardBoundPreferredZapModule = FALSE;
-
-    //
-    // Even though we have done this check already earlier, do it again here in case we have picked up
-    // any eager-bound dependency in the meantime
-    //
-    // Do not save instantiations found in one of our eager-bound dependencies
-    PtrHashMap::PtrIterator iter = GetAppDomain()->ToCompilationDomain()->IterateHardBoundModules();
-    for (/**/; !iter.end(); ++iter)
-    {
-        Module * hardBoundModule = (Module*)iter.GetValue();
-        if (hardBoundModule->GetAvailableParamTypes()->ContainsValue(th))
-        {
-            m_rejectedTypes.Add(th);
-            return;
-        }
-
-        if (hardBoundModule == pPreferredZapModule)
-        {
-            fHardBoundPreferredZapModule = TRUE;
-        }
-    }
-
-    if (!fHardBoundPreferredZapModule && !pPreferredZapModule->AreTypeSpecsTriaged())
-    {
-        // Reject all types that are guaranteed to be instantiated in soft bound PZM
-        TriageTypeSpecsFromSoftBoundModule(pPreferredZapModule);
-        pPreferredZapModule->SetTypeSpecsTriaged();
-
-        if (m_rejectedTypes.Lookup(th) != NULL)
-            return;
-    }
-
-    // We have to no other option but to accept and expand the type
-    ExpandTypeDependencies(th);
-}
-
-void CEEPreloader::TriageSpeculativeInstantiations()
-{
-    STANDARD_VM_CONTRACT;
-
-    // Get definitive triage answer for speculative types that we have run into earlier
-    // Note that m_speculativeTypes may be growing as this loop runs
-    for (COUNT_T i = 0; i < m_speculativeTypes.GetCount(); i++)
-    {
-        TriageSpeculativeType(m_speculativeTypes[i]);
-    }
-
-    // We are done - the array of speculative types is no longer necessary
-    m_speculativeTypes.Clear();
-}
-#endif // FEATURE_FULL_NGEN
-
-BOOL CEEPreloader::TriageForZap(BOOL fAcceptIfNotSure, BOOL fExpandDependencies)
-{
-    STANDARD_VM_CONTRACT;
-
-    DWORD dwNumTypes = m_image->GetModule()->GetAvailableParamTypes()->GetCount();
-    DWORD dwNumMethods = m_image->GetModule()->GetInstMethodHashTable()->GetCount();
-
-    // Triage types
-    {
-        // Create a local copy in case the new elements are added to the hashtable during population
-        InlineSArray<TypeHandle, 20> pTypes;
-
-        // Make sure the iterator is destroyed before there is a chance of loading new types
-        {
-            EETypeHashTable* pTable = m_image->GetModule()->GetAvailableParamTypes();
-
-            EETypeHashTable::Iterator it(pTable);
-            EETypeHashEntry *pEntry;
-            while (pTable->FindNext(&it, &pEntry))
-            {
-                TypeHandle th = pEntry->GetTypeHandle();
-                if (m_acceptedTypes.Lookup(th) == NULL && m_rejectedTypes.Lookup(th) == NULL)
-                    pTypes.Append(th);
-            }
-        }
-
-        for(COUNT_T i = 0; i < pTypes.GetCount(); i ++)
-        {
-            TriageTypeForZap(pTypes[i], fAcceptIfNotSure, fExpandDependencies);
-        }
-    }
-
-    // Triage methods
-    {
-        // Create a local copy in case the new elements are added to the hashtable during population
-        InlineSArray<MethodDesc*, 20> pMethods;
-
-        // Make sure the iterator is destroyed before there is a chance of loading new methods
-        {
-            InstMethodHashTable* pTable = m_image->GetModule()->GetInstMethodHashTable();
-
-            InstMethodHashTable::Iterator it(pTable);
-            InstMethodHashEntry *pEntry;
-            while (pTable->FindNext(&it, &pEntry))
-            {
-                MethodDesc* pMD = pEntry->GetMethod();
-                if (m_acceptedMethods.Lookup(pMD) == NULL && m_rejectedMethods.Lookup(pMD) == NULL)
-                    pMethods.Append(pMD);
-            }
-        }
-
-        for(COUNT_T i = 0; i < pMethods.GetCount(); i ++)
-        {
-            TriageMethodForZap(pMethods[i], fAcceptIfNotSure, fExpandDependencies);
-        }
-    }
-
-    // Returns TRUE if new types or methods has been added by the triage
-    return (dwNumTypes != m_image->GetModule()->GetAvailableParamTypes()->GetCount()) ||
-           (dwNumMethods != m_image->GetModule()->GetInstMethodHashTable()->GetCount());
-}
-
-void CEEPreloader::PrePrepareMethodIfNecessary(CORINFO_METHOD_HANDLE hMethod)
-{
-    STANDARD_VM_CONTRACT;
-
-}
-
-static void SetStubMethodDescOnInteropMethodDesc(MethodDesc* pInteropMD, MethodDesc* pStubMD, bool fReverseStub)
-{
-    CONTRACTL
-    {
-        THROWS;
-        GC_TRIGGERS;
-        MODE_ANY;
-
-        // We store NGENed stubs on these MethodDesc types
-        PRECONDITION(pInteropMD->IsNDirect() || pInteropMD->IsComPlusCall() || pInteropMD->IsGenericComPlusCall() || pInteropMD->IsEEImpl());
-    }
-    CONTRACTL_END;
-
-    if (pInteropMD->IsNDirect())
-    {
-        _ASSERTE(!fReverseStub);
-        NDirectMethodDesc* pNMD = (NDirectMethodDesc*)pInteropMD;
-        pNMD->ndirect.m_pStubMD.SetValue(pStubMD);
-    }
-#ifdef FEATURE_COMINTEROP
-    else if (pInteropMD->IsComPlusCall() || pInteropMD->IsGenericComPlusCall())
-    {
-        _ASSERTE(!fReverseStub);
-        ComPlusCallInfo *pComInfo = ComPlusCallInfo::FromMethodDesc(pInteropMD);
-       pComInfo->m_pStubMD.SetValue(pStubMD);
-    }
-#endif // FEATURE_COMINTEROP
-    else if (pInteropMD->IsEEImpl())
-    {
-        DelegateEEClass* pDelegateClass = (DelegateEEClass*)pInteropMD->GetClass();
-        if (fReverseStub)
-        {
-            pDelegateClass->m_pReverseStubMD = pStubMD;
-        }
-        else
-        {
-            pDelegateClass->m_pForwardStubMD = pStubMD;
-        }
-    }
-    else
-    {
-        UNREACHABLE_MSG("unexpected type of MethodDesc");
-    }
-}
-
-MethodDesc * CEEPreloader::CompileMethodStubIfNeeded(
-        MethodDesc *pMD,
-        MethodDesc *pStubMD,
-        ICorCompilePreloader::CORCOMPILE_CompileStubCallback pfnCallback,
-        LPVOID pCallbackContext)
-{
-    STANDARD_VM_CONTRACT;
-
-    LOG((LF_ZAP, LL_INFO10000, "NGEN_ILSTUB: %s::%s -> %s::%s\n",
-         pMD->m_pszDebugClassName, pMD->m_pszDebugMethodName, pStubMD->m_pszDebugClassName, pStubMD->m_pszDebugMethodName));
-
-    // It is possible that the StubMD is a normal method pointed by InteropStubMethodAttribute,
-    // and in that case we don't need to compile it here
-    if (pStubMD->IsDynamicMethod())
-    {
-        if (!pStubMD->AsDynamicMethodDesc()->GetILStubResolver()->IsCompiled())
-        {
-            CORJIT_FLAGS jitFlags = pStubMD->AsDynamicMethodDesc()->GetILStubResolver()->GetJitFlags();
-
-            pfnCallback(pCallbackContext, (CORINFO_METHOD_HANDLE)pStubMD, jitFlags);
-        }
-
-#ifndef FEATURE_FULL_NGEN // Deduplication
-        const DuplicateMethodEntry * pDuplicate = m_duplicateMethodsHash.LookupPtr(pStubMD);
-        if (pDuplicate != NULL)
-            return pDuplicate->pDuplicateMD;
-#endif
-    }
-
-//We do not store ILStubs so if the compilation failed for them
-//It does not make sense to keep the MD corresponding to the IL
-    if (pStubMD->IsILStub() && m_image->GetCodeAddress(pStubMD) == NULL)
-        pStubMD=NULL;
-
-    return pStubMD;
-}
-
-void CEEPreloader::GenerateMethodStubs(
-        CORINFO_METHOD_HANDLE hMethod,
-        bool                  fNgenProfilerImage,
-        CORCOMPILE_CompileStubCallback pfnCallback,
-        LPVOID                pCallbackContext)
-{
-    CONTRACTL
-    {
-        STANDARD_VM_CHECK;
-        PRECONDITION(hMethod != NULL && pfnCallback != NULL);
-    }
-    CONTRACTL_END;
-
-    MethodDesc* pMD = GetMethod(hMethod);
-    MethodDesc* pStubMD = NULL;
-
-    // Do not generate IL stubs when generating ReadyToRun images except for System.Private.Corelib
-    // This prevents versionability concerns around IL stubs exposing internal
-    // implementation details of the CLR.
-    if (IsReadyToRunCompilation() && (!GetAppDomain()->ToCompilationDomain()->GetTargetModule()->IsSystem() || !pMD->IsNDirect()))
-        return;
-
-    DWORD dwNGenStubFlags = NDIRECTSTUB_FL_NGENEDSTUB;
-
-    if (fNgenProfilerImage)
-        dwNGenStubFlags |= NDIRECTSTUB_FL_NGENEDSTUBFORPROFILING;
-
-    //
-    // Generate IL stubs. If failed, we go through normal NGEN path
-    // Catch any exceptions that occur when we try to create the IL_STUB
-    //
-    EX_TRY
-    {
-        //
-        // Take care of forward stubs
-        //
-        if (pMD->IsNDirect())
-        {
-            NDirectMethodDesc* pNMD = (NDirectMethodDesc*)pMD;
-            PInvokeStaticSigInfo sigInfo;
-            NDirect::InitializeSigInfoAndPopulateNDirectMethodDesc(pNMD, &sigInfo);
-            pStubMD = NDirect::GetILStubMethodDesc((NDirectMethodDesc*)pMD, &sigInfo, dwNGenStubFlags);
-        }
-#ifdef FEATURE_COMINTEROP
-        else if (pMD->IsComPlusCall() || pMD->IsGenericComPlusCall())
-        {
-            if (MethodNeedsForwardComStub(pMD, m_image))
-            {
-                // Look for predefined IL stubs in forward com interop scenario.
-                // If we've found a stub, that's what we'll use
-                DWORD dwStubFlags;
-                ComPlusCall::PopulateComPlusCallMethodDesc(pMD, &dwStubFlags);
-                if (FAILED(FindPredefinedILStubMethod(pMD, dwStubFlags, &pStubMD)))
-                {
-                    pStubMD = ComPlusCall::GetILStubMethodDesc(pMD, dwStubFlags | dwNGenStubFlags);
-                }
-            }
-        }
-#endif // FEATURE_COMINTEROP
-        else if (pMD->IsEEImpl())
-        {
-            MethodTable* pMT = pMD->GetMethodTable();
-            CONSISTENCY_CHECK(pMT->IsDelegate());
-
-            if (!pMD->HasClassOrMethodInstantiation())
-            {
-                if (COMDelegate::IsDelegateInvokeMethod(pMD)) // build forward stub
-                {
-                    // Build the stub only if the delegate is decorated with UnmanagedFunctionPointerAttribute.
-                    // Forward delegate stubs are rare so we require this opt-in to avoid bloating NGEN images.
-
-                    if (S_OK == pMT->GetMDImport()->GetCustomAttributeByName(
-                        pMT->GetCl(), g_UnmanagedFunctionPointerAttribute, NULL, NULL))
-                    {
-                        pStubMD = COMDelegate::GetILStubMethodDesc((EEImplMethodDesc *)pMD, dwNGenStubFlags);
-                    }
-                }
-            }
-        }
-
-        // compile the forward stub
-        if (pStubMD != NULL)
-        {
-            pStubMD = CompileMethodStubIfNeeded(pMD, pStubMD, pfnCallback, pCallbackContext);
-
-            // We store the MethodDesc of the Stub on the NDirectMethodDesc/ComPlusCallMethodDesc/DelegateEEClass
-            // that we can recover the stub MethodDesc at prestub time, do the fixups, and wire up the native code
-            if (pStubMD != NULL)
-            {
-#ifdef FEATURE_READYTORUN_COMPILER
-                if (IsReadyToRunCompilation())
-                {
-                    s_stubMethodsOfMethod.Add(CORINFO_METHOD_HANDLE(pStubMD), CORINFO_METHOD_HANDLE(pMD));
-                }
-#endif // FEATURE_READYTORUN_COMPILER
-                SetStubMethodDescOnInteropMethodDesc(pMD, pStubMD, false /* fReverseStub */);
-                pStubMD = NULL;
-            }
-
-        }
-    }
-    EX_CATCH
-    {
-        LOG((LF_ZAP, LL_WARNING, "NGEN_ILSTUB: Generating forward interop stub FAILED: %s::%s\n", pMD->m_pszDebugClassName, pMD->m_pszDebugMethodName));
-    }
-    EX_END_CATCH(RethrowTransientExceptions);
-
-    // Only P/Invoke stubs are eligible to be created in R2R
-    if (IsReadyToRunCompilation())
-        return;
-
-    //
-    // Now take care of reverse P/Invoke stubs for delegates
-    //
-    if (pMD->IsEEImpl() && COMDelegate::IsDelegateInvokeMethod(pMD))
-    {
-        // Reverse P/Invoke is not supported for generic methods
-        if (!pMD->HasClassOrMethodInstantiation())
-        {
-            EX_TRY
-            {
-#ifdef TARGET_X86
-                // on x86, we call the target directly if Invoke has a no-marshal signature
-                if (NDirect::MarshalingRequired(pMD))
-#endif // TARGET_X86
-                {
-                    PInvokeStaticSigInfo sigInfo(pMD);
-                    pStubMD = UMThunkMarshInfo::GetILStubMethodDesc(pMD, &sigInfo, NDIRECTSTUB_FL_DELEGATE | dwNGenStubFlags);
-
-                    if (pStubMD != NULL)
-                    {
-                        // compile the reverse stub
-                        pStubMD = CompileMethodStubIfNeeded(pMD, pStubMD, pfnCallback, pCallbackContext);
-
-                        // We store the MethodDesc of the Stub on the DelegateEEClass
-                        if (pStubMD != NULL)
-                        {
-                            SetStubMethodDescOnInteropMethodDesc(pMD, pStubMD, true /* fReverseStub */);
-                        }
-                    }
-                }
-            }
-            EX_CATCH
-            {
-                LOG((LF_ZAP, LL_WARNING, "NGEN_ILSTUB: Generating reverse interop stub for delegate FAILED: %s::%s\n", pMD->m_pszDebugClassName, pMD->m_pszDebugMethodName));
-            }
-            EX_END_CATCH(RethrowTransientExceptions);
-        }
-    }
-
-#ifdef FEATURE_COMINTEROP
-    //
-    // And finally generate reverse COM stubs
-    //
-    EX_TRY
-    {
-        // The method doesn't have to have a special type to be exposed to COM, in particular it doesn't
-        // have to be ComPlusCallMethodDesc. However, it must have certain properties (custom attributes,
-        // public visibility, etc.)
-        if (MethodNeedsReverseComStub(pMD))
-        {
-            // initialize ComCallMethodDesc
-            ComCallMethodDesc ccmd;
-            ComCallMethodDescHolder ccmdHolder(&ccmd);
-            ccmd.InitMethod(pMD, NULL);
-
-            // generate the IL stub
-            DWORD dwStubFlags;
-            ComCall::PopulateComCallMethodDesc(&ccmd, &dwStubFlags);
-            pStubMD = ComCall::GetILStubMethodDesc(pMD, dwStubFlags | dwNGenStubFlags);
-
-            if (pStubMD != NULL)
-            {
-                // compile the reverse stub
-                pStubMD = CompileMethodStubIfNeeded(pMD, pStubMD, pfnCallback, pCallbackContext);
-
-                if (pStubMD != NULL)
-                {
-                    // store the stub in a hash table on the module
-                    m_image->GetModule()->GetStubMethodHashTable()->InsertMethodDesc(pMD, pStubMD);
-                }
-            }
-        }
-    }
-    EX_CATCH
-    {
-        LOG((LF_ZAP, LL_WARNING, "NGEN_ILSTUB: Generating reverse interop stub FAILED: %s::%s\n", pMD->m_pszDebugClassName, pMD->m_pszDebugMethodName));
-    }
-    EX_END_CATCH(RethrowTransientExceptions);
-#endif // FEATURE_COMINTEROP
-}
-
-bool CEEPreloader::IsDynamicMethod(CORINFO_METHOD_HANDLE hMethod)
-{
-    STANDARD_VM_CONTRACT;
-
-    MethodDesc* pMD = GetMethod(hMethod);
-
-    if (pMD)
-    {
-        return pMD->IsDynamicMethod();
-    }
-
-    return false;
-}
-
-// Set method profiling flags for layout of EE datastructures
-void CEEPreloader::SetMethodProfilingFlags(CORINFO_METHOD_HANDLE hMethod, DWORD flags)
-{
-    STANDARD_VM_CONTRACT;
-
-    _ASSERTE(hMethod != NULL);
-    _ASSERTE(flags != 0);
-
-    return m_image->SetMethodProfilingFlags(GetMethod(hMethod), flags);
-}
-
-/*********************************************************************/
-// canSkipMethodPreparation: Is there a need for all calls from
-// NGEN'd code to a particular MethodDesc to go through DoPrestub,
-// depending on the method sematics?  If so return FALSE.
-//
-// This is used to rule out both ngen-hardbinds and intra-ngen-module
-// direct calls.
-//
-// The cases where direct calls are not allowed are typically where
-// a stub must be inserted by DoPrestub (we do not save stubs) or where
-// we haven't saved the code for some reason or another, or where fixups
-// are required in the MethodDesc.
-//
-// callerHnd=NULL implies any/unspecified caller.
-//
-// Note that there may be other requirements for going through the prestub
-// which vary based on the scenario. These need to be handled separately
-
-bool CEEPreloader::CanSkipMethodPreparation (
-        CORINFO_METHOD_HANDLE   callerHnd,
-        CORINFO_METHOD_HANDLE   calleeHnd,
-        CorInfoIndirectCallReason *pReason,
-        CORINFO_ACCESS_FLAGS    accessFlags/*=CORINFO_ACCESS_ANY*/)
-{
-    STANDARD_VM_CONTRACT;
-
-    bool result = false;
-
-    COOPERATIVE_TRANSITION_BEGIN();
-
-    MethodDesc *  calleeMD    = (MethodDesc *)calleeHnd;
-    MethodDesc *  callerMD    = (MethodDesc *)callerHnd;
-
-    {
-        result = calleeMD->CanSkipDoPrestub(callerMD, pReason, accessFlags);
-    }
-
-    COOPERATIVE_TRANSITION_END();
-
-    return result;
-}
-
-CORINFO_METHOD_HANDLE CEEPreloader::LookupMethodDef(mdMethodDef token)
-{
-    STANDARD_VM_CONTRACT;
-    MethodDesc *resultMD = nullptr;
-
-    EX_TRY
-    {
-        MethodDesc *pMD = MemberLoader::GetMethodDescFromMethodDef(m_image->GetModule(), token, FALSE);
-
-        if (IsReadyToRunCompilation() && pMD->HasClassOrMethodInstantiation())
-        {
-            _ASSERTE(IsCompilationProcess() && pMD->GetModule_NoLogging() == GetAppDomain()->ToCompilationDomain()->GetTargetModule());
-        }
-
-        resultMD = pMD->FindOrCreateTypicalSharedInstantiation();
-    }
-    EX_CATCH
-    {
-        this->Error(token, GET_EXCEPTION());
-    }
-    EX_END_CATCH(SwallowAllExceptions)
-
-    return CORINFO_METHOD_HANDLE(resultMD);
-}
-
-bool CEEPreloader::GetMethodInfo(mdMethodDef token, CORINFO_METHOD_HANDLE ftnHnd, CORINFO_METHOD_INFO * methInfo)
-{
-    STANDARD_VM_CONTRACT;
-    bool result = false;
-
-    EX_TRY
-    {
-        result = GetZapJitInfo()->getMethodInfo(ftnHnd, methInfo);
-    }
-    EX_CATCH
-    {
-        result = false;
-        this->Error(token, GET_EXCEPTION());
-    }
-    EX_END_CATCH(SwallowAllExceptions)
-
-    return result;
-}
-
-static BOOL MethodIsVisibleOutsideItsAssembly(DWORD dwMethodAttr)
-{
-    LIMITED_METHOD_CONTRACT;
-    return (IsMdPublic(dwMethodAttr) ||
-        IsMdFamORAssem(dwMethodAttr) ||
-        IsMdFamily(dwMethodAttr));
-}
-
-static BOOL ClassIsVisibleOutsideItsAssembly(DWORD dwClassAttr, BOOL fIsGlobalClass)
-{
-    LIMITED_METHOD_CONTRACT;
-
-    if (fIsGlobalClass)
-    {
-        return TRUE;
-    }
-
-    return (IsTdPublic(dwClassAttr) ||
-        IsTdNestedPublic(dwClassAttr) ||
-        IsTdNestedFamily(dwClassAttr) ||
-        IsTdNestedFamORAssem(dwClassAttr));
-}
-
-static BOOL MethodIsVisibleOutsideItsAssembly(MethodDesc * pMD)
-{
-    LIMITED_METHOD_CONTRACT;
-
-    MethodTable * pMT = pMD->GetMethodTable();
-
-    if (!ClassIsVisibleOutsideItsAssembly(pMT->GetAttrClass(), pMT->IsGlobalClass()))
-        return FALSE;
-
-    return MethodIsVisibleOutsideItsAssembly(pMD->GetAttrs());
-}
-
-CorCompileILRegion CEEPreloader::GetILRegion(mdMethodDef token)
-{
-    STANDARD_VM_CONTRACT;
-
-    // Since we are running managed code during NGen the inlining hint may be
-    // changing underneeth us as the code is JITed. We need to prevent the inlining
-    // hints from changing once we start to use them to place IL in the image.
-    g_pCEECompileInfo->DisableCachingOfInliningHints();
-
-    // Default if there is something completely wrong, e.g. the type failed to load.
-    // We may need the IL at runtime.
-    CorCompileILRegion region = CORCOMPILE_ILREGION_WARM;
-
-    EX_TRY
-    {
-        MethodDesc *pMD = m_image->GetModule()->LookupMethodDef(token);
-
-        if (pMD == NULL || !pMD->GetMethodTable()->IsFullyLoaded())
-        {
-            // Something is completely wrong - use the default
-        }
-        else
-        if (m_image->IsStored(pMD))
-        {
-            if (pMD->IsNotInline())
-            {
-                if (pMD->HasClassOrMethodInstantiation())
-                {
-                    region = CORCOMPILE_ILREGION_GENERICS;
-                }
-                else
-                {
-                    region = CORCOMPILE_ILREGION_COLD;
-                }
-            }
-            else
-            if (MethodIsVisibleOutsideItsAssembly(pMD))
-            {
-                // We are inlining only leaf methods, except for CoreLib. Thus we can assume that only methods
-                // visible outside its assembly are likely to be inlined.
-                region = CORCOMPILE_ILREGION_INLINEABLE;
-            }
-            else
-            {
-                // We may still need the IL of the non-nonvisible methods for inlining in certain scenarios:
-                // dynamically emitted IL, friend assemblies or JITing of generic instantiations
-                region = CORCOMPILE_ILREGION_WARM;
-            }
-        }
-    }
-    EX_CATCH
-    {
-    }
-    EX_END_CATCH(SwallowAllExceptions)
-
-    return region;
-}
-
-
-CORINFO_METHOD_HANDLE CEEPreloader::FindMethodForProfileEntry(CORBBTPROF_BLOB_PARAM_SIG_ENTRY * profileBlobEntry)
-{
-    STANDARD_VM_CONTRACT;
-    MethodDesc *  pMethod = nullptr;
-
-    _ASSERTE(profileBlobEntry->blob.type == ParamMethodSpec);
-
-    if (PartialNGenStressPercentage() != 0)
-        return CORINFO_METHOD_HANDLE( NULL );
-
-    Module * pModule = GetAppDomain()->ToCompilationDomain()->GetTargetModule();
-    pMethod = pModule->LoadIBCMethodHelper(m_image, profileBlobEntry);
-
-    return CORINFO_METHOD_HANDLE( pMethod );
-}
-
-void CEEPreloader::ReportInlining(CORINFO_METHOD_HANDLE inliner, CORINFO_METHOD_HANDLE inlinee)
-{
-    STANDARD_VM_CONTRACT;
-    m_image->ReportInlining(inliner, inlinee);
-}
-
-void CEEPreloader::Link()
-{
-    STANDARD_VM_CONTRACT;
-
-    COOPERATIVE_TRANSITION_BEGIN();
-
-    m_image->PreSave();
-
-    m_image->GetModule()->Save(m_image);
-    m_image->GetModule()->Arrange(m_image);
-    m_image->GetModule()->Fixup(m_image);
-
-    m_image->PostSave();
-
-    COOPERATIVE_TRANSITION_END();
-}
-
-void CEEPreloader::FixupRVAs()
-{
-    STANDARD_VM_CONTRACT;
-
-    COOPERATIVE_TRANSITION_BEGIN();
-
-    m_image->FixupRVAs();
-
-    COOPERATIVE_TRANSITION_END();
-}
-
-void CEEPreloader::SetRVAsForFields(IMetaDataEmit * pEmit)
-{
-    STANDARD_VM_CONTRACT;
-
-    COOPERATIVE_TRANSITION_BEGIN();
-
-    m_image->SetRVAsForFields(pEmit);
-
-    COOPERATIVE_TRANSITION_END();
-}
-
-void CEEPreloader::GetRVAFieldData(mdFieldDef fd, PVOID * ppData, DWORD * pcbSize, DWORD * pcbAlignment)
-{
-    STANDARD_VM_CONTRACT;
-
-    COOPERATIVE_TRANSITION_BEGIN();
-
-    FieldDesc * pFD = m_image->GetModule()->LookupFieldDef(fd);
-    if (pFD == NULL)
-        ThrowHR(COR_E_TYPELOAD);
-
-    _ASSERTE(pFD->IsRVA());
-
-    UINT size = pFD->LoadSize();
-
-    //
-    // Compute an alignment for the data based on the alignment
-    // of the RVA.  We'll align up to 8 bytes.
-    //
-
-    UINT align = 1;
-    DWORD rva = pFD->GetOffset();
-    DWORD rvaTemp = rva;
-
-    while ((rvaTemp&1) == 0 && align < 8 && align < size)
-    {
-        align <<= 1;
-        rvaTemp >>= 1;
-    }
-
-
-    *ppData = pFD->GetStaticAddressHandle(NULL);
-    *pcbSize = size;
-    *pcbAlignment = align;
-
-    COOPERATIVE_TRANSITION_END();
-}
-
-ULONG CEEPreloader::Release()
-{
-    CONTRACTL {
-        NOTHROW;
-        GC_NOTRIGGER;
-        MODE_ANY;
-    } CONTRACTL_END;
-
-    delete this;
-    return 0;
-}
-
-#ifdef FEATURE_READYTORUN_COMPILER
-void CEEPreloader::GetSerializedInlineTrackingMap(SBuffer* pBuffer)
-{
-    InlineTrackingMap * pInlineTrackingMap = m_image->GetInlineTrackingMap();
-    PersistentInlineTrackingMapR2R::Save(m_image->GetHeap(), pBuffer, pInlineTrackingMap);
-}
-#endif
-
-void CEEPreloader::Error(mdToken token, Exception * pException)
-{
-    STANDARD_VM_CONTRACT;
-
-    HRESULT hr = pException->GetHR();
-    UINT    resID = 0;
-
-    StackSString msg;
-
-#ifdef CROSSGEN_COMPILE
-    pException->GetMessage(msg);
-
-    // Do we have an EEException with a resID?
-    if (EEMessageException::IsEEMessageException(pException))
-    {
-        EEMessageException * pEEMessageException = (EEMessageException *) pException;
-        resID = pEEMessageException->GetResID();
-    }
-#else
-    {
-        GCX_COOP();
-
-        // Going though throwable gives more verbose error messages in certain cases that our tests depend on.
-        OBJECTREF throwable = NingenEnabled() ? NULL : CLRException::GetThrowableFromException(pException);
-
-        if (throwable != NULL)
-        {
-            GetExceptionMessage(throwable, msg);
-        }
-        else
-        {
-            pException->GetMessage(msg);
-        }
-    }
-#endif
-
-    m_pData->Error(token, hr, resID, msg.GetUnicode());
-}
-
-CEEInfo *g_pCEEInfo = NULL;
-
-ICorDynamicInfo * __stdcall GetZapJitInfo()
-{
-    STANDARD_VM_CONTRACT;
-
-    if (g_pCEEInfo == NULL)
-    {
-        CEEInfo * p = new CEEInfo();
-        if (InterlockedCompareExchangeT(&g_pCEEInfo, p, NULL) != NULL)
-            delete p;
-    }
-
-    return g_pCEEInfo;
-}
-
-CEECompileInfo *g_pCEECompileInfo = NULL;
-
-ICorCompileInfo * __stdcall GetCompileInfo()
-{
-    STANDARD_VM_CONTRACT;
-
-    if (g_pCEECompileInfo == NULL)
-    {
-        CEECompileInfo * p = new CEECompileInfo();
-        if (InterlockedCompareExchangeT(&g_pCEECompileInfo, p, NULL) != NULL)
-            delete p;
-    }
-
-    return g_pCEECompileInfo;
-}
-
-//
-// CompilationDomain
-//
-
-CompilationDomain::CompilationDomain(BOOL fForceDebug,
-                                     BOOL fForceProfiling,
-                                     BOOL fForceInstrument)
-  : m_fForceDebug(fForceDebug),
-    m_fForceProfiling(fForceProfiling),
-    m_fForceInstrument(fForceInstrument),
-    m_pTargetAssembly(NULL),
-    m_pTargetModule(NULL),
-    m_pTargetImage(NULL),
-    m_pEmit(NULL),
-    m_pDependencyRefSpecs(NULL),
-    m_pDependencies(NULL),
-    m_cDependenciesCount(0),
-    m_cDependenciesAlloc(0)
-{
-    STANDARD_VM_CONTRACT;
-
-}
-
-void CompilationDomain::ReleaseDependencyEmitter()
-{
-    m_pDependencyRefSpecs.Release();
-
-    m_pEmit.Release();
-}
-
-CompilationDomain::~CompilationDomain()
-{
-    CONTRACTL
-    {
-        NOTHROW;
-        GC_TRIGGERS;
-        MODE_ANY;
-    }
-    CONTRACTL_END;
-
-    if (m_pDependencies != NULL)
-        delete [] m_pDependencies;
-
-    ReleaseDependencyEmitter();
-
-    for (unsigned i = 0; i < m_rRefCaches.Size(); i++)
-    {
-        delete m_rRefCaches[i];
-        m_rRefCaches[i]=NULL;
-    }
-
-}
-
-void CompilationDomain::Init()
-{
-    STANDARD_VM_CONTRACT;
-
-#ifndef CROSSGEN_COMPILE
-    AppDomain::Init();
-#endif
-
-#ifndef CROSSGEN_COMPILE
-    // allocate a Virtual Call Stub Manager for the compilation domain
-    InitVSD();
-#endif
-
-    SetCompilationDomain();
-}
-
-HRESULT CompilationDomain::AddDependencyEntry(PEAssembly *pFile,
-                                           mdAssemblyRef ref,
-                                           mdAssemblyRef def)
-{
-#ifdef _DEBUG
-    // This method is not multi-thread safe.  This is OK because it is only called by NGen compiling, which is
-    // effectively single-threaded.  The following code verifies that we're not called on multiple threads.
-    static volatile LONG threadId = 0;
-    if (threadId == 0)
-    {
-        InterlockedCompareExchange(&threadId, GetCurrentThreadId(), 0);
-    }
-    _ASSERTE((LONG)GetCurrentThreadId() == threadId);
-#endif // _DEBUG
-
-    _ASSERTE((pFile == NULL) == (def == mdAssemblyRefNil));
-
-    if (m_cDependenciesCount == m_cDependenciesAlloc)
-    {
-        // Save the new count in a local variable.  Can't update m_cDependenciesAlloc until the new
-        // CORCOMPILE_DEPENDENCY array is allocated, otherwise an out-of-memory exception from new[]
-        // operator would put the data in an inconsistent state, causing heap corruption later.
-        USHORT cNewDependenciesAlloc = m_cDependenciesAlloc == 0 ? 20 : m_cDependenciesAlloc * 2;
-
-        // Grow m_pDependencies
-
-        NewArrayHolder<CORCOMPILE_DEPENDENCY> pNewDependencies(new CORCOMPILE_DEPENDENCY[cNewDependenciesAlloc]);
-        {
-            // This block must execute transactionally. No throwing allowed. No bailing allowed.
-            FAULT_FORBID();
-
-            memset(pNewDependencies,  0, cNewDependenciesAlloc*sizeof(CORCOMPILE_DEPENDENCY));
-
-            if (m_pDependencies)
-            {
-                memcpy(pNewDependencies, m_pDependencies,
-                       m_cDependenciesCount*sizeof(CORCOMPILE_DEPENDENCY));
-
-                delete [] m_pDependencies;
-            }
-
-            m_pDependencies = pNewDependencies.Extract();
-            m_cDependenciesAlloc = cNewDependenciesAlloc;
-        }
-    }
-
-    CORCOMPILE_DEPENDENCY *pDependency = &m_pDependencies[m_cDependenciesCount++];
-
-    // Clear memory so that we won't write random data into the zapped file
-    ZeroMemory(pDependency, sizeof(CORCOMPILE_DEPENDENCY));
-
-    pDependency->dwAssemblyRef = ref;
-
-    pDependency->dwAssemblyDef = def;
-
-    pDependency->signNativeImage = INVALID_NGEN_SIGNATURE;
-
-    if (pFile)
-    {
-        DomainAssembly *pAssembly = GetAppDomain()->LoadDomainAssembly(NULL, pFile, FILE_LOAD_CREATE);
-        // Note that this can trigger an assembly load (of CoreLib)
-        pAssembly->GetOptimizedIdentitySignature(&pDependency->signAssemblyDef);
-
-
-
-        //
-        // This is done in CompilationDomain::CanEagerBindToZapFile with full support for hardbinding
-        //
-        if (pFile->IsSystem() && pFile->HasNativeImage())
-        {
-            CORCOMPILE_VERSION_INFO * pNativeVersion = pFile->GetLoadedNative()->GetNativeVersionInfo();
-            pDependency->signNativeImage = pNativeVersion->signature;
-        }
-
-    }
-
-    return S_OK;
-}
-
-HRESULT CompilationDomain::AddDependency(AssemblySpec *pRefSpec,
-                                         PEAssembly * pFile)
-{
-    HRESULT hr;
-
-    //
-    // Record the dependency
-    //
-
-    // This assert prevents dependencies from silently being loaded without being recorded.
-    _ASSERTE(m_pEmit);
-
-    // Normalize any reference to CoreLib; we don't want to record other non-canonical
-    // CoreLib references in the ngen image since fusion doesn't understand how to bind them.
-    // (Not to mention the fact that they are redundant.)
-    AssemblySpec spec;
-    if (pRefSpec->IsCoreLib())
-    {
-        _ASSERTE(pFile); // CoreLib had better not be missing
-        if (!pFile)
-            return E_UNEXPECTED;
-
-        // Don't store a binding from CoreLib to itself.
-        if (m_pTargetAssembly == SystemDomain::SystemAssembly())
-            return S_OK;
-
-        spec.InitializeSpec(pFile);
-        pRefSpec = &spec;
-    }
-    else if (m_pTargetAssembly == NULL && pFile)
-    {
-        // If target assembly is still NULL, we must be loading either the target assembly or CoreLib.
-        // CoreLib is already handled above, so we must be loading the target assembly if we get here.
-        // Use the assembly name given in the target assembly so that the native image is deterministic
-        // regardless of how the target assembly is specified on the command line.
-        spec.InitializeSpec(pFile);
-        if (spec.IsStrongNamed() && spec.HasPublicKey())
-        {
-            spec.ConvertPublicKeyToToken();
-        }
-        pRefSpec = &spec;
-    }
-    else if (pRefSpec->IsStrongNamed() && pRefSpec->HasPublicKey())
-    {
-        // Normalize to always use public key token.  Otherwise we may insert one reference
-        // using public key, and another reference using public key token.
-        spec.CopyFrom(pRefSpec);
-        spec.ConvertPublicKeyToToken();
-        pRefSpec = &spec;
-    }
-
-    //
-    // See if we've already added the contents of the ref
-    // Else, emit token for the ref
-    //
-
-    if (m_pDependencyRefSpecs->Store(pRefSpec))
-        return S_OK;
-
-    mdAssemblyRef refToken;
-    IfFailRet(pRefSpec->EmitToken(m_pEmit, &refToken));
-
-    //
-    // Make a spec for the bound assembly
-    //
-
-    mdAssemblyRef defToken = mdAssemblyRefNil;
-
-    // All dependencies of a shared assembly need to be shared. So for a shared
-    // assembly, we want to remember the missing assembly ref during ngen, so that
-    // we can probe eagerly for the dependency at load time, and make sure that
-    // it is loaded as shared.
-    // In such a case, pFile will be NULL
-    if (pFile)
-    {
-        AssemblySpec assemblySpec;
-        assemblySpec.InitializeSpec(pFile);
-
-        IfFailRet(assemblySpec.EmitToken(m_pEmit, &defToken));
-    }
-
-    //
-    // Add the entry.  Include the PEFile if we are not doing explicit bindings.
-    //
-
-    IfFailRet(AddDependencyEntry(pFile, refToken, defToken));
-
-    return S_OK;
-}
-
-//----------------------------------------------------------------------------
-AssemblySpec* CompilationDomain::FindAssemblyRefSpecForDefSpec(
-    AssemblySpec* pDefSpec)
-{
-    WRAPPER_NO_CONTRACT;
-
-    if (pDefSpec == nullptr)
-        return nullptr;
-
-    const AssemblySpecDefRefMapEntry * pEntry = m_dependencyDefRefMap.LookupPtr(pDefSpec);
-    _ASSERTE(pEntry != NULL);
-
-    return (pEntry != NULL) ? pEntry->m_pRef : NULL;
-}
-
-
-//----------------------------------------------------------------------------
-// Is it OK to embed direct pointers to an ngen dependency?
-// true if hardbinding is OK, false otherwise
-//
-// targetModule - The pointer points into the native image of this Module.
-//                If this native image gets relocated, the native image of
-//                the source Module is invalidated unless the embedded
-//                pointer can be fixed up appropriately.
-// limitToHardBindList - Is it OK to hard-bind to a dependency even if it is
-//                not asked for explicitly?
-
-BOOL CompilationDomain::CanEagerBindToZapFile(Module *targetModule, BOOL limitToHardBindList)
-{
-    // We do this check before checking the hashtables because m_cantHardBindModules
-    // will contain non-manifest modules. However, we do want them to be able
-    // to hard-bind to themselves
-    if (targetModule == m_pTargetModule)
-    {
-        return TRUE;
-    }
-
-    //
-    // CoreCLR does not have attributes for fine grained eager binding control.
-    // We hard bind to CoreLib only.
-    //
-    return targetModule->IsSystem();
-}
-
-
-void CompilationDomain::SetTarget(Assembly *pAssembly, Module *pModule)
-{
-    STANDARD_VM_CONTRACT;
-
-    m_pTargetAssembly = pAssembly;
-    m_pTargetModule = pModule;
-}
-
-void CompilationDomain::SetTargetImage(DataImage *pImage, CEEPreloader * pPreloader)
-{
-    STANDARD_VM_CONTRACT;
-
-    m_pTargetImage = pImage;
-    m_pTargetPreloader = pPreloader;
-
-    _ASSERTE(pImage->GetModule() == GetTargetModule());
-}
-
-void ReportMissingDependency(Exception * e)
-{
-    // Avoid duplicate error messages
-    if (FAILED(g_hrFatalError))
-        return;
-
-    SString s;
-
-    e->GetMessage(s);
-    GetSvcLogger()->Printf(LogLevel_Error, W("Error: %s\n"), s.GetUnicode());
-
-    g_hrFatalError = COR_E_FILELOAD;
-}
-
-PEAssembly *CompilationDomain::BindAssemblySpec(
-    AssemblySpec *pSpec,
-    BOOL fThrowOnFileNotFound)
-{
-    PEAssembly *pFile = NULL;
-    //
-    // Do the binding
-    //
-
-    EX_TRY
-    {
-        //
-        // Use normal binding rules
-        // (possibly with our custom IApplicationContext)
-        //
-        pFile = AppDomain::BindAssemblySpec(
-            pSpec,
-            fThrowOnFileNotFound);
-    }
-    EX_HOOK
-    {
-        if (!g_fNGenMissingDependenciesOk)
-        {
-            ReportMissingDependency(GET_EXCEPTION());
-            EX_RETHROW;
-        }
-
-        //
-        // Record missing dependencies
-        //
-        IfFailThrow(AddDependency(pSpec, NULL));
-    }
-    EX_END_HOOK
-
-    IfFailThrow(AddDependency(pSpec, pFile));
-
-    return pFile;
-}
-
-HRESULT
-    CompilationDomain::SetContextInfo(LPCWSTR path, BOOL isExe)
-{
-    STANDARD_VM_CONTRACT;
-
-    HRESULT hr = S_OK;
-
-    COOPERATIVE_TRANSITION_BEGIN();
-
-
-    COOPERATIVE_TRANSITION_END();
-
-    return hr;
-}
-
-void CompilationDomain::SetDependencyEmitter(IMetaDataAssemblyEmit *pEmit)
-{
-    STANDARD_VM_CONTRACT;
-
-    pEmit->AddRef();
-    m_pEmit = pEmit;
-
-    m_pDependencyRefSpecs = new AssemblySpecHash();
-}
-
-
-HRESULT
-    CompilationDomain::GetDependencies(CORCOMPILE_DEPENDENCY **ppDependencies,
-                                       DWORD *pcDependencies)
-{
-    STANDARD_VM_CONTRACT;
-
-
-    //
-    // Return the bindings.
-    //
-
-    *ppDependencies = m_pDependencies;
-    *pcDependencies = m_cDependenciesCount;
-
-    // Cannot add any more dependencies
-    ReleaseDependencyEmitter();
-
-    return S_OK;
-}
-
-
-#ifdef CROSSGEN_COMPILE
-
-#ifdef FEATURE_READYTORUN_COMPILER
-
-class MethodsForStubEnumerator
-{
-    SHash<NoRemoveSHashTraits<MapSHashTraits<CORINFO_METHOD_HANDLE, CORINFO_METHOD_HANDLE>>>::KeyIterator current;
-    SHash<NoRemoveSHashTraits<MapSHashTraits<CORINFO_METHOD_HANDLE, CORINFO_METHOD_HANDLE>>>::KeyIterator end;
-    bool started = false;
-    bool complete = false;
-
-public:
-    MethodsForStubEnumerator(CORINFO_METHOD_HANDLE hMethod) :
-        current(s_stubMethodsOfMethod.Begin(hMethod)),
-        end(s_stubMethodsOfMethod.End(hMethod))
-    {
-        complete = current == end;
-    }
-
-    bool Next()
-    {
-        if (complete)
-            return false;
-
-        if (started)
-        {
-            ++current;
-        }
-        else
-        {
-            started = true;
-        }
-
-        if (current == end)
-        {
-            complete = true;
-            return false;
-        }
-        return true;
-    }
-
-    CORINFO_METHOD_HANDLE Current()
-    {
-        return current->Value();
-    }
-};
-#endif // FEATURE_READYTORUN_COMPILER
-
-BOOL CEECompileInfo::EnumMethodsForStub(CORINFO_METHOD_HANDLE hMethod, void** enumerator)
-{
-#ifdef FEATURE_READYTORUN_COMPILER
-    *enumerator = NULL;
-    if (s_stubMethodsOfMethod.LookupPtr(hMethod) == NULL)
-        return FALSE;
-
-    *enumerator = new MethodsForStubEnumerator(hMethod);
-    return TRUE;
-#else
-    return FALSE;
-#endif // FEATURE_READYTORUN_COMPILER
-}
-
-BOOL CEECompileInfo::EnumNextMethodForStub(void * enumerator, CORINFO_METHOD_HANDLE *hMethod)
-{
-    *hMethod = NULL;
-#ifdef FEATURE_READYTORUN_COMPILER
-    auto stubEnum = (MethodsForStubEnumerator*)enumerator;
-    if (stubEnum->Next())
-    {
-        *hMethod = stubEnum->Current();
-        return TRUE;
-    }
-    else
-    {
-        return FALSE;
-    }
-#else
-    return FALSE;
-#endif // FEATURE_READYTORUN_COMPILER
-}
-
-void CEECompileInfo::EnumCloseForStubEnumerator(void *enumerator)
-{
-#ifdef FEATURE_READYTORUN_COMPILER
-    auto stubEnum = (MethodsForStubEnumerator*)enumerator;
-    delete stubEnum;
-#endif // FEATURE_READYTORUN_COMPILER
-}
-
-#endif // CROSSGEN_COMPILE
-
-
-#endif // FEATURE_PREJIT
diff --git a/src/coreclr/vm/compile.h b/src/coreclr/vm/compile.h
deleted file mode 100644 (file)
index 6280497..0000000
+++ /dev/null
@@ -1,842 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// ===========================================================================
-// File: compile.h
-//
-// Interfaces and support for zap compiler and zap files
-//
-
-// ===========================================================================
-
-
-/*
-
-The preloader is used to serialize internal EE data structures in the
-zapped image.  The object model looks like the following:
-
-                    +--------------------+
-                    |                    |
-                    |    ZapperModule    |
-                    |                    |
-                    +--------------------+
-                              |
-                              *
-                     ICorCompileDataStore           Zapper
-
-           =====================================================
-
-                     ICorCompilePreloader           EE
-                              *
-                              |
-                    +--------------------+
-                    |                    |
-                    |    CEEPreloader    |
-                    |                    |
-                    +--------------------+
-                              |
-                              *
-                     DataImage::IDataStore
-
-
-                    +--------------------+
-                    |                    |
-                    |     DataImage      |
-                    |                    |
-                    +--------------------+
-
-ZapperModule - Created by the zapper for each module.  It implements the
-               ICorCompileDataStore interface that the preloader uses to
-               allocate space for the EE data structures.  Currently it
-               allocates space in a single PE section (though the DataImage
-               has logic to further subdivide the space into subsections).
-
-CEEPreloader - Created by ZapperModule in order to serialize EE
-               data structures.  It implements two interfaces.
-               ICorCompilePreloader is used by ZapperModule to inquire
-               about the offsets of various EE data structures inside
-               the preloader section.  DataImage::IDataStore is used
-               by DataImage to manage the PE section memory, and the
-               implementation in the CEEPreloader mostly forwards the calls
-               to the zapper (ICorCompileDataStore).
-
-DataImage    - Created by CEEPreloader to keep track of memory used by
-               EE data structures.  Even though it uses only one PE
-               section, it allows the EE to allocate memory in multiple
-               subsections.  This is accomplished by splitting the work into
-               three phases (there are comments in dataimage.h that explain
-               this in detail).
-
-
-The CEEPreloader is created when ZapperModule::Preload calls
-m_zapper->m_pEECompileInfo->PreloadModule.  PreloadModule creates
-the CEEPreloader and then calls its Preload method, which explicitely
-loads all the EE objects into memory (Module::ExpandAll), and then
-allocates space for them in the preloader section (Module::Save).
-
-Each EE data structure that needs to be serialized implements a Save
-method.  A Save method is required to:
-1) Store all of its data (including strings and other buffers that it
-   uses) in the preloader section.  This is accomplished by calling on
-   one of the DataImage storage methods (such as DataImage::StoreStructure).
-2) Call the Save method on the objects that it owns.  The interesting
-   part of the hierarchy looks like:
-
-   Module::Save
-     MethodTable::Save (in profile order)
-       EEClass::Save
-         MethodDescChunk::Save (method desc chunks can be split into hot
-                                and cold based on profile info)
-           MethodDesc::Save
-
-Note that while the architecture requires the data structures in the
-preloader sections to look like their EE counterparts, it is possible
-to work around that limitation by constructing multiple submappings of
-these data structures.  Sometimes the submappings require a change to the actual
-data (i.e. each method desc has information that tells you how far it is
-from the MethodDescChunk, and that needs to change when reordering method
-descs).  In such cases you create new copies of that memory and construct
-a regular copying map for each of the new updated copies (DataImage::StoreStructure),
-and a pointer update map for each of the original EE data structures
-(DataImage::StoreStructureUsingSurrogate).  See MethodDescChunk::Save for
-an example on how to do this.
-
-Fixups:  once everything has been layout out in memory, the ZapperModule
-calls CEEPreloader::Link to generate fixups for the data.  CEEPreloader::Link
-calls Module::Fixup, which results in a data structure walk very similar to
-that of Module::Save.  Each data structure calls one of the FixupPointerField
-methods on the DataImage, which in turn forwards the call to
-CEEPreloader::AddFixup, which forwards it to the zapper
-(ZapperModule::AddFixup).
-
-*/
-
-#ifndef COMPILE_H_
-#define COMPILE_H_
-
-#ifdef FEATURE_NATIVE_IMAGE_GENERATION
-
-struct ZapperLoaderModuleTableKey {
-    ZapperLoaderModuleTableKey(Module *pDefinitionModule,
-        mdToken token,
-        Instantiation classInst,
-        Instantiation methodInst)
-        : m_inst(classInst, methodInst)
-    { WRAPPER_NO_CONTRACT;
-      this->m_pDefinitionModule = pDefinitionModule;
-      this->m_token = token;  }
-
-    Module *m_pDefinitionModule;
-    mdToken m_token;
-    SigTypeContext m_inst;
-} ;
-
-struct ZapperLoaderModuleTableEntry {
-    ZapperLoaderModuleTableEntry(): key(0,0,Instantiation(),Instantiation()) { WRAPPER_NO_CONTRACT; this->result = 0; }
-    ZapperLoaderModuleTableEntry(const ZapperLoaderModuleTableKey &_key,Module *_result)
-        : key(_key)
-    { this->result = _result; }
-
-    ZapperLoaderModuleTableKey key;
-    Module *result;
-} ;
-
-class ZapperLoaderModuleTableTraits : public NoRemoveSHashTraits<DefaultSHashTraits<ZapperLoaderModuleTableEntry> >
-{
-
-public:
-    typedef const ZapperLoaderModuleTableKey *key_t;
-    static const ZapperLoaderModuleTableKey * GetKey(const ZapperLoaderModuleTableEntry &e) { return &e.key; }
-    static count_t Hash(const ZapperLoaderModuleTableKey * k)
-    {
-        LIMITED_METHOD_CONTRACT;
-
-        DWORD dwHash = 5381;
-
-        dwHash = ((dwHash << 5) + dwHash) ^ (unsigned int)(SIZE_T)k->m_pDefinitionModule;
-        dwHash = ((dwHash << 5) + dwHash) ^ (unsigned int)(SIZE_T)k->m_token;
-        dwHash = ((dwHash << 5) + dwHash) ^ EEInstantiationHashTableHelper:: Hash(&k->m_inst);
-        return dwHash;
-    }
-
-    static BOOL Equals(const ZapperLoaderModuleTableKey *e1, const ZapperLoaderModuleTableKey *e2)
-    {
-        WRAPPER_NO_CONTRACT;
-        return e1->m_pDefinitionModule == e2->m_pDefinitionModule &&
-            e1->m_token == e2->m_token &&
-            SigTypeContext::Equal(&e1->m_inst, &e2->m_inst);
-    }
-    static const ZapperLoaderModuleTableEntry Null()
-    { return ZapperLoaderModuleTableEntry(); }
-
-    static bool IsNull(const ZapperLoaderModuleTableEntry &e)
-    { LIMITED_METHOD_CONTRACT; return e.key.m_pDefinitionModule == 0 && e.key.m_token == 0 && e.key.m_inst.IsEmpty(); }
-
-};
-
-
-typedef  SHash<ZapperLoaderModuleTableTraits> ZapperLoaderModuleTable;
-
-class CEECompileInfo : public ICorCompileInfo
-{
-  public:
-    CEECompileInfo()
-       : m_fGeneratingNgenPDB(FALSE)
-    {
-    }
-
-    virtual ~CEECompileInfo()
-    {
-        WRAPPER_NO_CONTRACT;
-    }
-
-    HRESULT Startup(     BOOL                     fForceDebug,
-                         BOOL                     fForceProfiling,
-                         BOOL                     fForceInstrument);
-
-    HRESULT CreateDomain(ICorCompilationDomain **ppDomain,
-                         IMetaDataAssemblyEmit    *pEmitter,
-                         BOOL                     fForceDebug,
-                         BOOL                     fForceProfiling,
-                         BOOL                     fForceInstrument);
-
-    HRESULT DestroyDomain(ICorCompilationDomain   *pDomain);
-
-    HRESULT LoadAssemblyByPath(LPCWSTR                  wzPath,
-                               BOOL                     fExplicitBindToNativeImage,
-                               CORINFO_ASSEMBLY_HANDLE *pHandle);
-
-    BOOL IsInCurrentVersionBubble(CORINFO_MODULE_HANDLE hModule);
-
-    HRESULT LoadAssemblyModule(CORINFO_ASSEMBLY_HANDLE assembly,
-                               mdFile                  file,
-                               CORINFO_MODULE_HANDLE   *pHandle);
-
-
-    BOOL CheckAssemblyZap(
-        CORINFO_ASSEMBLY_HANDLE assembly,
-      __out_ecount_opt(*cAssemblyManifestModulePath)
-        LPWSTR                  assemblyManifestModulePath,
-        LPDWORD                 cAssemblyManifestModulePath);
-
-    HRESULT SetCompilationTarget(CORINFO_ASSEMBLY_HANDLE     assembly,
-                                 CORINFO_MODULE_HANDLE       module);
-
-    IMDInternalImport * GetAssemblyMetaDataImport(CORINFO_ASSEMBLY_HANDLE scope);
-
-    IMDInternalImport * GetModuleMetaDataImport(CORINFO_MODULE_HANDLE scope);
-
-    CORINFO_MODULE_HANDLE GetAssemblyModule(CORINFO_ASSEMBLY_HANDLE module);
-
-    CORINFO_ASSEMBLY_HANDLE GetModuleAssembly(CORINFO_MODULE_HANDLE module);
-
-    PEDecoder * GetModuleDecoder(CORINFO_MODULE_HANDLE scope);
-
-    void GetModuleFileName(CORINFO_MODULE_HANDLE module,
-                           SString               &result);
-
-    void EncodeModuleAsIndex( CORINFO_MODULE_HANDLE   fromHandle,
-                              CORINFO_MODULE_HANDLE   handle,
-                              DWORD                   *pIndex,
-                              IMetaDataAssemblyEmit   *pAssemblyEmit);
-
-    void EncodeClass(  CORINFO_MODULE_HANDLE   referencingModule,
-                       CORINFO_CLASS_HANDLE    classHandle,
-                       SigBuilder              *pSigBuilder,
-                       LPVOID                  encodeContext,
-                       ENCODEMODULE_CALLBACK   pfnEncodeModule);
-
-    void EncodeMethod( CORINFO_MODULE_HANDLE   referencingModule,
-                       CORINFO_METHOD_HANDLE   methHnd,
-                       SigBuilder              *pSigBuilder,
-                       LPVOID                  encodeContext,
-                       ENCODEMODULE_CALLBACK   pfnEncodeModule,
-                       CORINFO_RESOLVED_TOKEN  *pResolvedToken,
-                       CORINFO_RESOLVED_TOKEN  *pConstrainedResolvedToken,
-                       BOOL                    fEncodeUsingResolvedTokenSpecStreams);
-
-    virtual mdToken TryEncodeMethodAsToken(CORINFO_METHOD_HANDLE handle,
-                                           CORINFO_RESOLVED_TOKEN * pResolvedToken,
-                                           CORINFO_MODULE_HANDLE * referencingModule);
-
-    virtual DWORD TryEncodeMethodSlot(CORINFO_METHOD_HANDLE handle);
-
-    void EncodeField(  CORINFO_MODULE_HANDLE   referencingModule,
-                       CORINFO_FIELD_HANDLE    handle,
-                       SigBuilder              *pSigBuilder,
-                       LPVOID                  encodeContext,
-                       ENCODEMODULE_CALLBACK   pfnEncodeModule,
-                       CORINFO_RESOLVED_TOKEN  *pResolvedToken,
-                       BOOL                    fEncodeUsingResolvedTokenSpecStreams);
-
-    // Encode generic dictionary signature
-    virtual void EncodeGenericSignature(
-            LPVOID signature,
-            BOOL fMethod,
-            SigBuilder * pSigBuilder,
-            LPVOID encodeContext,
-            ENCODEMODULE_CALLBACK pfnEncodeModule);
-
-
-    BOOL IsEmptyString(mdString token,
-                       CORINFO_MODULE_HANDLE module);
-
-    BOOL IsUnmanagedCallConvMethod(CORINFO_METHOD_HANDLE handle);
-
-    BOOL IsUnmanagedCallersOnlyMethod(CORINFO_METHOD_HANDLE handle);
-
-    BOOL IsCachingOfInliningHintsEnabled()
-    {
-        return m_fCachingOfInliningHintsEnabled;
-    }
-
-    void DisableCachingOfInliningHints()
-    {
-        m_fCachingOfInliningHintsEnabled = FALSE;
-    }
-
-    HRESULT GetTypeDef(   CORINFO_CLASS_HANDLE    classHandle,
-                          mdTypeDef               *token);
-    HRESULT GetMethodDef( CORINFO_METHOD_HANDLE   methodHandle,
-                          mdMethodDef             *token);
-    HRESULT GetFieldDef(  CORINFO_FIELD_HANDLE    fieldHandle,
-                          mdFieldDef              *token);
-
-    void SetAssemblyHardBindList(__in_ecount( cHardBindList )
-                                 LPWSTR *pHardBindList,
-                                 DWORD cHardBindList);
-
-    CORINFO_MODULE_HANDLE GetLoaderModuleForCoreLib();
-    CORINFO_MODULE_HANDLE GetLoaderModuleForEmbeddableType(CORINFO_CLASS_HANDLE classHandle);
-    CORINFO_MODULE_HANDLE GetLoaderModuleForEmbeddableMethod(CORINFO_METHOD_HANDLE methodHandle);
-    CORINFO_MODULE_HANDLE GetLoaderModuleForEmbeddableField(CORINFO_FIELD_HANDLE fieldHandle);
-
-    ICorCompilePreloader * PreloadModule(CORINFO_MODULE_HANDLE   moduleHandle,
-                                    ICorCompileDataStore    *pData,
-                                    CorProfileData          *profileData);
-
-
-    HRESULT GetLoadHint(CORINFO_ASSEMBLY_HANDLE   hAssembly,
-                        CORINFO_ASSEMBLY_HANDLE hAssemblyDependency,
-                        LoadHintEnum           *loadHint,
-                        LoadHintEnum           *defaultLoadHint);
-
-    HRESULT GetAssemblyVersionInfo(CORINFO_ASSEMBLY_HANDLE Handle,
-                                    CORCOMPILE_VERSION_INFO *pInfo);
-
-    void GetAssemblyCodeBase(CORINFO_ASSEMBLY_HANDLE hAssembly,
-                             SString                &result);
-
-    void GetCallRefMap(CORINFO_METHOD_HANDLE hMethod,
-                       GCRefMapBuilder * pBuilder,
-                       bool isDispatchCell);
-
-    void CompressDebugInfo(
-                                    IN ICorDebugInfo::OffsetMapping * pOffsetMapping,
-                                    IN ULONG            iOffsetMapping,
-                                    IN ICorDebugInfo::NativeVarInfo * pNativeVarInfo,
-                                    IN ULONG            iNativeVarInfo,
-                                    IN OUT SBuffer    * pDebugInfoBuffer);
-
-    HRESULT SetVerboseLevel(
-                                    IN  VerboseLevel        level);
-
-    HRESULT GetBaseJitFlags(
-            IN  CORINFO_METHOD_HANDLE    hMethod,
-            OUT CORJIT_FLAGS            *pFlags);
-
-    ICorJitHost* GetJitHost();
-
-    void* GetStubSize(void *pStubAddress, DWORD *pSizeToCopy);
-
-    HRESULT GetStubClone(void *pStub, BYTE *pBuffer, DWORD dwBufferSize);
-
-    BOOL GetIsGeneratingNgenPDB();
-    void SetIsGeneratingNgenPDB(BOOL fGeneratingNgenPDB);
-
-#ifdef FEATURE_READYTORUN_COMPILER
-    CORCOMPILE_FIXUP_BLOB_KIND GetFieldBaseOffset(
-            CORINFO_CLASS_HANDLE classHnd,
-            DWORD * pBaseOffset);
-
-    BOOL NeedsTypeLayoutCheck(CORINFO_CLASS_HANDLE classHnd);
-    void EncodeTypeLayout(CORINFO_CLASS_HANDLE classHandle, SigBuilder * pSigBuilder);
-
-    BOOL AreAllClassesFullyLoaded(CORINFO_MODULE_HANDLE moduleHandle);
-
-    int GetVersionResilientTypeHashCode(CORINFO_MODULE_HANDLE moduleHandle, mdToken token);
-
-    int GetVersionResilientMethodHashCode(CORINFO_METHOD_HANDLE methodHandle);
-
-    BOOL EnumMethodsForStub(CORINFO_METHOD_HANDLE hMethod, void** enumerator);
-    BOOL EnumNextMethodForStub(void * enumerator, CORINFO_METHOD_HANDLE *hMethod);
-    void EnumCloseForStubEnumerator(void *enumerator);
-#endif
-
-    BOOL HasCustomAttribute(CORINFO_METHOD_HANDLE method, LPCSTR customAttributeName);
-
-    //--------------------------------------------------------------------
-    // ZapperLoaderModules and the ZapperLoaderModuleTable
-    //
-    // When NGEN'ing we want to adjust the
-    // places where some items (i.e. generic instantiations) are placed, in order to get some of them
-    // placed into the module we are compiling.  However, the
-    // results of ComputeLoaderModule must be stable for the duration
-    // of an entire instance of the VM, i.e. for the duration of a compilation
-    // process.  Thus each time we place an item into a non-standard LoaderModule we record
-    // that fact.
-
-    Module *LookupZapperLoaderModule(const ZapperLoaderModuleTableKey *pKey)
-    {
-        WRAPPER_NO_CONTRACT;
-        const ZapperLoaderModuleTableEntry *pEntry = m_ZapperLoaderModuleTable.LookupPtr(pKey);
-        if (pEntry)
-            return pEntry->result;
-        return NULL;
-    }
-
-    void RecordZapperLoaderModule(const ZapperLoaderModuleTableKey *pKey,
-                                  Module *pZapperLoaderModuleTable)
-    {
-        CONTRACTL
-        {
-            THROWS;
-            GC_NOTRIGGER;
-            MODE_ANY;
-        }
-        CONTRACTL_END;
-        ZapperLoaderModuleTableEntry entry(*pKey, pZapperLoaderModuleTable);
-        m_ZapperLoaderModuleTable.Add(entry);
-    }
-
-    ZapperLoaderModuleTable m_ZapperLoaderModuleTable;
-
-private:
-    BOOL m_fCachingOfInliningHintsEnabled;
-    BOOL m_fGeneratingNgenPDB;
-};
-
-extern CEECompileInfo *g_pCEECompileInfo;
-
-BOOL IsNgenPDBCompilationProcess();
-
-//
-// See comment at top of file for an explanation on the preloader
-// architecture.
-//
-
-class CEEPreloader : public ICorCompilePreloader
-{
-  private:
-    DataImage              *m_image;
-    ICorCompileDataStore   *m_pData;
-
-    class MethodSetTraits : public NoRemoveSHashTraits< DefaultSHashTraits<MethodDesc *> >
-    {
-    public:
-        typedef MethodDesc *key_t;
-        static MethodDesc * GetKey(MethodDesc *md) { return md; }
-        static count_t Hash(MethodDesc *md) { return (count_t) (UINT_PTR) md; }
-        static BOOL Equals(MethodDesc *md1, MethodDesc *md2)
-        {
-            return md1 == md2;
-        }
-    };
-
-    class TypeSetTraits : public NoRemoveSHashTraits< DefaultSHashTraits<TypeHandle> >
-    {
-    public:
-        typedef TypeHandle key_t;
-        static const TypeHandle Null() { return TypeHandle(); }
-        static bool IsNull(const TypeHandle &th) { return !!th.IsNull(); }
-        static TypeHandle GetKey(TypeHandle th) { return th; }
-        static count_t Hash(TypeHandle th) { return (count_t) th.AsTAddr(); }
-        static BOOL Equals(TypeHandle th1, TypeHandle th2) { return th1 == th2; }
-    };
-
-    // Cached results of instantiations triage
-    SHash<TypeSetTraits>    m_acceptedTypes;
-    SHash<MethodSetTraits>  m_acceptedMethods;
-    SHash<TypeSetTraits>    m_rejectedTypes;
-    SHash<MethodSetTraits>  m_rejectedMethods;
-
-#ifdef FEATURE_FULL_NGEN
-    // Tentatively accepted instantiations
-    InlineSArray<TypeHandle, 20>    m_speculativeTypes;
-    BOOL                            m_fSpeculativeTriage;
-    BOOL                            m_fDictionariesPopulated;
-#endif
-
-    struct CompileMethodEntry
-    {
-        MethodDesc * pMD;
-#ifndef FEATURE_FULL_NGEN // Unreferenced methods
-        bool fReferenced; // true when this method was referenced by other code
-        bool fScheduled;  // true when this method was scheduled for compilation
-#endif
-    };
-
-    class CompileMethodSetTraits : public NoRemoveSHashTraits< DefaultSHashTraits<CompileMethodEntry> >
-    {
-    public:
-        typedef MethodDesc *key_t;
-        static MethodDesc * GetKey(CompileMethodEntry e) { return e.pMD; }
-        static count_t Hash(MethodDesc *md) { return (count_t) (UINT_PTR) md; }
-        static BOOL Equals(MethodDesc *md1, MethodDesc *md2)
-        {
-            return md1 == md2;
-        }
-        static const CompileMethodEntry Null() { CompileMethodEntry e; e.pMD = NULL; return e; }
-        static bool IsNull(const CompileMethodEntry &e) { return e.pMD == NULL; }
-    };
-
-    SHash<CompileMethodSetTraits> m_compileMethodsHash;
-
-    // Array of methods that we need to compile.
-    SArray<MethodDesc*> m_uncompiledMethods;
-
-    int m_methodCompileLimit;
-
-    void AppendUncompiledMethod(MethodDesc *pMD)
-    {
-        STANDARD_VM_CONTRACT;
-        if (m_methodCompileLimit > 0)
-        {
-            m_uncompiledMethods.Append(pMD);
-            m_methodCompileLimit--;
-        }
-    }
-
-    struct DuplicateMethodEntry
-    {
-        MethodDesc * pMD;
-        MethodDesc * pDuplicateMD;
-    };
-
-    class DuplicateMethodTraits : public NoRemoveSHashTraits< DefaultSHashTraits<DuplicateMethodEntry> >
-    {
-    public:
-        typedef MethodDesc *key_t;
-        static MethodDesc * GetKey(DuplicateMethodEntry e) { return e.pMD; }
-        static count_t Hash(MethodDesc *md) { return (count_t) (UINT_PTR) md; }
-        static BOOL Equals(MethodDesc *md1, MethodDesc *md2)
-        {
-            return md1 == md2;
-        }
-        static const DuplicateMethodEntry Null() { DuplicateMethodEntry e; e.pMD = NULL; return e; }
-        static bool IsNull(const DuplicateMethodEntry &e) { return e.pMD == NULL; }
-    };
-
-    SHash<DuplicateMethodTraits> m_duplicateMethodsHash;
-
-    MethodDesc * CompileMethodStubIfNeeded(
-            MethodDesc *pMD,
-            MethodDesc *pStubMD,
-            ICorCompilePreloader::CORCOMPILE_CompileStubCallback pfnCallback,
-            LPVOID pCallbackContext);
-
-  public:
-    CEEPreloader(Module *pModule,
-                 ICorCompileDataStore *pData);
-    virtual ~CEEPreloader();
-
-    void Preload(CorProfileData * profileData);
-    DataImage * GetDataImage() { LIMITED_METHOD_CONTRACT; return m_image; }
-    ICorCompileDataStore * GetDataStore() { LIMITED_METHOD_CONTRACT; return m_pData; }
-
-    //
-    // ICorCompilerPreloader
-    //
-
-    DWORD MapMethodEntryPoint(CORINFO_METHOD_HANDLE handle);
-    DWORD MapClassHandle(CORINFO_CLASS_HANDLE handle);
-    DWORD MapMethodHandle(CORINFO_METHOD_HANDLE handle);
-    DWORD MapFieldHandle(CORINFO_FIELD_HANDLE handle);
-    DWORD MapAddressOfPInvokeFixup(CORINFO_METHOD_HANDLE handle);
-    DWORD MapGenericHandle(CORINFO_GENERIC_HANDLE handle);
-    DWORD MapModuleIDHandle(CORINFO_MODULE_HANDLE handle);
-
-    void AddMethodToTransitiveClosureOfInstantiations(CORINFO_METHOD_HANDLE handle);
-    void AddTypeToTransitiveClosureOfInstantiations(CORINFO_CLASS_HANDLE handle);
-    BOOL IsMethodInTransitiveClosureOfInstantiations(CORINFO_METHOD_HANDLE handle);
-    BOOL IsTypeInTransitiveClosureOfInstantiations(CORINFO_CLASS_HANDLE handle);
-
-    void MethodReferencedByCompiledCode(CORINFO_METHOD_HANDLE handle);
-
-    BOOL IsUncompiledMethod(CORINFO_METHOD_HANDLE handle);
-    BOOL ShouldSuppressGCTransition(CORINFO_METHOD_HANDLE handle);
-
-private:
-    void AddToUncompiledMethods(MethodDesc *pMethod, BOOL fForStubs);
-
-    void ApplyTypeDependencyProductionsForType(TypeHandle t);
-    void ApplyTypeDependencyForSZArrayHelper(MethodTable * pInterfaceMT, TypeHandle elemTypeHnd);
-
-    friend class Module;
-    void TriageTypeForZap(TypeHandle th, BOOL fAcceptIfNotSure, BOOL fExpandDependencies = TRUE);
-    void TriageMethodForZap(MethodDesc* pMethod, BOOL fAcceptIfNotSure, BOOL fExpandDependencies = TRUE);
-
-    void ExpandTypeDependencies(TypeHandle th);
-    void ExpandMethodDependencies(MethodDesc * pMD);
-
-    void TriageTypeSpecsFromSoftBoundModule(Module * pSoftBoundModule);
-    void TriageTypeFromSoftBoundModule(TypeHandle th, Module * pSoftBoundModule);
-    void TriageSpeculativeType(TypeHandle th);
-    void TriageSpeculativeInstantiations();
-
-    // Returns TRUE if new types or methods have been added by the triage
-    BOOL TriageForZap(BOOL fAcceptIfNotSure, BOOL fExpandDependencies = TRUE);
-
-public:
-    CORINFO_METHOD_HANDLE NextUncompiledMethod();
-
-    void PrePrepareMethodIfNecessary(CORINFO_METHOD_HANDLE hMethod);
-
-    void GenerateMethodStubs(
-            CORINFO_METHOD_HANDLE hMethod,
-            bool                  fNgenProfileImage,
-            CORCOMPILE_CompileStubCallback pfnCallback,
-            LPVOID                pCallbackContext);
-
-    bool IsDynamicMethod(CORINFO_METHOD_HANDLE hMethod);
-    void SetMethodProfilingFlags(CORINFO_METHOD_HANDLE hMethod, DWORD flags);
-
-    bool CanSkipMethodPreparation (
-            CORINFO_METHOD_HANDLE   callerHnd,      /* IN  */
-            CORINFO_METHOD_HANDLE   calleeHnd,      /* IN  */
-            CorInfoIndirectCallReason *pReason = NULL,
-            CORINFO_ACCESS_FLAGS    accessFlags = CORINFO_ACCESS_ANY);
-
-    BOOL CanEmbedClassID     (CORINFO_CLASS_HANDLE    typeHandle);
-    BOOL CanEmbedModuleID    (CORINFO_MODULE_HANDLE   moduleHandle);
-    BOOL CanEmbedModuleHandle(CORINFO_MODULE_HANDLE   moduleHandle);
-    BOOL CanEmbedClassHandle (CORINFO_CLASS_HANDLE    typeHandle);
-    BOOL CanEmbedMethodHandle(CORINFO_METHOD_HANDLE   methodHandle,
-                              CORINFO_METHOD_HANDLE   contextHandle);
-    BOOL CanEmbedFieldHandle (CORINFO_FIELD_HANDLE    fieldHandle);
-
-    BOOL CanPrerestoreEmbedClassHandle (CORINFO_CLASS_HANDLE  classHnd);
-    BOOL CanPrerestoreEmbedMethodHandle(CORINFO_METHOD_HANDLE methodHnd);
-
-    BOOL CanEmbedFunctionEntryPoint(CORINFO_METHOD_HANDLE   methodHandle,
-                                    CORINFO_METHOD_HANDLE   contextHandle,
-                                    CORINFO_ACCESS_FLAGS    accessFlags = CORINFO_ACCESS_ANY);
-
-    BOOL DoesMethodNeedRestoringBeforePrestubIsRun(CORINFO_METHOD_HANDLE   methodHandle);
-
-    BOOL CanSkipDependencyActivation(CORINFO_METHOD_HANDLE   context,
-                                     CORINFO_MODULE_HANDLE   moduleFrom,
-                                     CORINFO_MODULE_HANDLE   moduleTo);
-
-    CORINFO_MODULE_HANDLE GetPreferredZapModuleForClassHandle(CORINFO_CLASS_HANDLE classHnd);
-
-    void NoteDeduplicatedCode(CORINFO_METHOD_HANDLE method, CORINFO_METHOD_HANDLE duplicateMethod);
-
-    CORINFO_METHOD_HANDLE LookupMethodDef(mdMethodDef token);
-    bool GetMethodInfo(mdMethodDef token, CORINFO_METHOD_HANDLE ftnHnd, CORINFO_METHOD_INFO * methInfo);
-
-    CorCompileILRegion GetILRegion(mdMethodDef token);
-
-    CORINFO_METHOD_HANDLE FindMethodForProfileEntry(CORBBTPROF_BLOB_PARAM_SIG_ENTRY * profileBlobEntry);
-
-    void ReportInlining(CORINFO_METHOD_HANDLE inliner, CORINFO_METHOD_HANDLE inlinee);
-
-    void Link();
-    void FixupRVAs();
-
-    void SetRVAsForFields(IMetaDataEmit * pEmit);
-
-    void GetRVAFieldData(mdFieldDef fd, PVOID * ppData, DWORD * pcbSize, DWORD * pcbAlignment);
-
-    ULONG Release();
-
-#ifdef FEATURE_READYTORUN_COMPILER
-    void GetSerializedInlineTrackingMap(SBuffer* pBuffer);
-#endif
-
-    void Error(mdToken token, Exception * pException);
-};
-
-
-struct RefCache
-{
-    RefCache(Module *pModule)
-    {
-        CONTRACTL
-        {
-            NOTHROW;
-            GC_NOTRIGGER;
-            FORBID_FAULT;
-        }
-        CONTRACTL_END
-
-
-        m_pModule = pModule;
-
-        {
-            // HashMap::Init can throw due to OOM. Our ctor can't. Since this whole
-            // thing is for use inside CEECompileInfo methods, it doesn't make sense to
-            // use an exception model. Thus we probably have to move the hashmap init
-            // calls out of the ctor so can catch these exceptions and translate them to
-            // hresults.
-            //
-            CONTRACT_VIOLATION(ThrowsViolation|FaultViolation);
-
-            m_sAssemblyRefMap.Init(FALSE,NULL);
-        }
-    }
-
-    Module *m_pModule;
-
-    HashMap m_sAssemblyRefMap;
-};
-
-struct AssemblySpecDefRefMapEntry {
-    AssemblySpec * m_pDef;
-    AssemblySpec * m_pRef;
-};
-
-class AssemblySpecDefRefMapTraits : public NoRemoveSHashTraits<DefaultSHashTraits<AssemblySpecDefRefMapEntry> >
-{
-public:
-    typedef const AssemblySpec *key_t;
-    static const AssemblySpec * GetKey(const AssemblySpecDefRefMapEntry &e) { return e.m_pDef; }
-
-    static count_t Hash(const AssemblySpec * k)
-    {
-        return const_cast<AssemblySpec *>(k)->Hash();
-    }
-
-    static BOOL Equals(const AssemblySpec * lhs, const AssemblySpec * rhs)
-    {
-        return const_cast<AssemblySpec *>(lhs)->CompareEx(const_cast<AssemblySpec *>(rhs), AssemblySpec::ASC_DefinitionEquality);
-    }
-
-    static const AssemblySpecDefRefMapEntry Null() { AssemblySpecDefRefMapEntry e; e.m_pDef = NULL; return e; }
-    static bool IsNull(const AssemblySpecDefRefMapEntry &e) { return e.m_pDef == NULL; }
-
-    void OnDestructPerEntryCleanupAction(const AssemblySpecDefRefMapEntry& e)
-    {
-        WRAPPER_NO_CONTRACT;
-        delete e.m_pDef;
-        delete e.m_pRef;
-    }
-    static const bool s_DestructPerEntryCleanupAction = true;
-};
-
-typedef SHash<AssemblySpecDefRefMapTraits> AssemblySpecMapDefRefMapTable;
-
-class CompilationDomain : public AppDomain,
-                          public ICorCompilationDomain
-{
-
- public:
-    BOOL                    m_fForceDebug;
-    BOOL                    m_fForceProfiling;
-    BOOL                    m_fForceInstrument;
-
-    // TODO:  During ngen, we need to determine whether we can call NeedsRestore
-    // before the preloader has been initialized.  This is accomplished via this
-    // method.  This code needs to be cleaned up.  See bug #284709 for background.
-    BOOL canCallNeedsRestore() { return  (m_pTargetImage != NULL); };
-
-    // DDB 175659: Make sure that canCallNeedsRestore() returns FALSE during compilation
-    // domain shutdown.
-    void setCannotCallNeedsRestore() { m_pTargetImage = NULL; }
-
-  private:
-
-    Assembly                *m_pTargetAssembly;     // Assembly being compiled
-    Module                  *m_pTargetModule;       // Module currently being compiled. Needed for multi-module assemblies
-    DataImage               *m_pTargetImage;        // Data image
-    CEEPreloader            *m_pTargetPreloader;
-
-    ReleaseHolder<IMetaDataAssemblyEmit>    m_pEmit;
-
-    NewHolder<AssemblySpecHash>             m_pDependencyRefSpecs;
-
-    AssemblySpecMapDefRefMapTable           m_dependencyDefRefMap;
-
-    CORCOMPILE_DEPENDENCY   *m_pDependencies;
-    USHORT                   m_cDependenciesCount, m_cDependenciesAlloc;
-
-    CQuickArray<RefCache*> m_rRefCaches;
-
-    HRESULT AddDependencyEntry(PEAssembly *pFile, mdAssemblyRef ref,mdAssemblyRef def);
-    void ReleaseDependencyEmitter();
-
-
-  public:
-
-#ifndef DACCESS_COMPILE
-    CompilationDomain(BOOL fForceDebug = FALSE,
-                      BOOL fForceProfiling = FALSE,
-                      BOOL fForceInstrument = FALSE);
-    ~CompilationDomain();
-#endif
-
-    void Init();
-
-    HRESULT AddDependency(AssemblySpec *pRefSpec, PEAssembly *pFile);
-
-    AssemblySpec* FindAssemblyRefSpecForDefSpec(
-        AssemblySpec* pDefSpec);
-
-    PEAssembly *BindAssemblySpec(
-        AssemblySpec *pSpec,
-        BOOL fThrowOnFileNotFound) DAC_EMPTY_RET(NULL);
-
-    BOOL CanEagerBindToZapFile(Module *targetModule, BOOL limitToHardBindList = TRUE);
-
-
-
-    // Returns NULL on out-of-memory
-    RefCache *GetRefCache(Module *pModule)
-    {
-        CONTRACTL
-        {
-            NOTHROW;
-            GC_NOTRIGGER;
-            INJECT_FAULT(return NULL;);
-        }
-        CONTRACTL_END
-
-        unsigned uSize = (unsigned) m_rRefCaches.Size();
-        for (unsigned i = 0; i < uSize; i++)
-            if (m_rRefCaches[i]->m_pModule == pModule)
-                return m_rRefCaches[i];
-
-        // Add a new cache entry
-        HRESULT hr;
-
-        if (FAILED(hr = m_rRefCaches.ReSizeNoThrow(uSize + 1)))
-        {
-            _ASSERTE(hr == E_OUTOFMEMORY);
-            return NULL;
-        }
-
-        m_rRefCaches[uSize] = new (nothrow) RefCache(pModule);
-        return m_rRefCaches[uSize];
-    }
-
-    void SetTarget(Assembly * pAssembly, Module *pModule);
-
-    void SetTargetImage(DataImage * pImage, CEEPreloader * pPreloader);
-    DataImage * GetTargetImage() { LIMITED_METHOD_CONTRACT; return m_pTargetImage; }
-
-    Assembly * GetTargetAssembly()
-        { LIMITED_METHOD_CONTRACT; return m_pTargetAssembly; }
-    Module * GetTargetModule()
-        { LIMITED_METHOD_CONTRACT; return m_pTargetModule; }
-
-    // ICorCompilationDomain
-
-    HRESULT SetContextInfo(LPCWSTR exePath, BOOL isExe) DAC_EMPTY_RET(E_FAIL);
-    HRESULT GetDependencies(CORCOMPILE_DEPENDENCY **ppDependencies,
-                            DWORD *cDependencies) DAC_EMPTY_RET(E_FAIL);
-
-    void SetDependencyEmitter(IMetaDataAssemblyEmit *pEmitter);
-};
-
-#endif // FEATURE_NATIVE_IMAGE_GENERATION
-
-#endif // COMPILE_H_
index c59d8ad..e568a29 100644 (file)
 #include "virtualcallstub.h"
 #include "decodemd.h"
 
-#ifdef FEATURE_PREJIT
-#include "compile.h"
-#endif
-
 #if defined(_DEBUG)
 DummyGlobalContract ___contract;
 #endif
@@ -487,37 +483,6 @@ DispatchMap::CreateEncodedMapping(
 #endif //_DEBUG
 } // DispatchMap::CreateEncodedMapping
 
-#ifdef FEATURE_NATIVE_IMAGE_GENERATION
-//------------------------------------------------------------------------
-void DispatchMap::Save(DataImage * image)
-{
-    STANDARD_VM_CONTRACT;
-
-    CONSISTENCY_CHECK(!image->IsStored(this));
-
-    UINT32 cbMap = GetMapSize();
-    UINT32 cbObj = GetObjectSize(cbMap);
-
-    image->StoreInternedStructure(
-        this,
-        cbObj,
-        DataImage::ITEM_DISPATCH_MAP,
-        sizeof(void *));
-
-#ifdef LOGGING
-    g_sdStats.m_cNGENDispatchMap++;
-    g_sdStats.m_cbNGENDispatchMap += cbObj;
-#endif //LOGGING
-}
-
-//------------------------------------------------------------------------
-void DispatchMap::Fixup(DataImage *image)
-{
-    STANDARD_VM_CONTRACT;
-}
-
-#endif //FEATURE_NATIVE_IMAGE_GENERATION
-
 #endif //!DACCESS_COMPILE
 
 //------------------------------------------------------------------------
index b00f016..c5b7917 100644 (file)
@@ -913,14 +913,6 @@ public:
     void EnumMemoryRegions(CLRDataEnumMemoryFlags flags);
 #endif
 
-#ifdef FEATURE_PREJIT
-    //------------------------------------------------------------------------
-    void Save(DataImage *image);
-
-    //------------------------------------------------------------------------
-    void Fixup(DataImage *image);
-#endif //FEATURE_PREJIT
-
     //------------------------------------------------------------------------
     class EncodedMapIterator
     {
index c58ea07..6709eed 100644 (file)
 #include "strongnameinternal.h"
 #include "strongnameholders.h"
 
-#ifdef FEATURE_PREJIT
-#include "compile.h"
-#endif
-
 #include "../binder/inc/textualidentityparser.hpp"
 #include "../binder/inc/assemblyidentity.hpp"
 #include "../binder/inc/assembly.hpp"
diff --git a/src/coreclr/vm/crossgencompile.cpp b/src/coreclr/vm/crossgencompile.cpp
deleted file mode 100644 (file)
index 8622505..0000000
+++ /dev/null
@@ -1,395 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// ===========================================================================
-// File: crosscomp.cpp
-//
-
-// ===========================================================================
-// This file contains stubbed out implementations for cross-platform NGen.
-//
-// The stubbed out implementations are concentrated in this file to reduce number
-// of ifdefs that has to be sprinkled through the code.
-// ===========================================================================
-
-#include "common.h"
-
-#include "comdelegate.h"
-#include "compile.h"
-#include "invokeutil.h"
-#include "comcallablewrapper.h"
-
-//---------------------------------------------------------------------------------------
-//
-// Pull in some implementation files from other places in the tree
-//
-
-#include "../../dlls/mscoree/mscoree.cpp"
-
-//---------------------------------------------------------------------------------------
-//
-// Helper function for features unsupported under crossgen
-//
-
-#undef ExitProcess
-
-void CrossGenNotSupported(const char * message)
-{
-    _ASSERTE(!"CrossGenNotSupported");
-    fprintf(stderr, "Fatal error: %s\n", message);
-    ExitProcess(CORSECATTR_E_BAD_ACTION);
-}
-
-//---------------------------------------------------------------------------------------
-//
-// There is always only one thread and one appdomain in crossgen.
-//
-
-extern CompilationDomain * theDomain;
-
-AppDomain * GetAppDomain()
-{
-    return theDomain;
-}
-
-Thread theThread;
-
-Thread * GetThread()
-{
-    return (Thread*)&theThread;
-}
-
-Thread * GetThreadNULLOk()
-{
-    return GetThread();
-}
-
-#ifdef _DEBUG
-BOOL Debug_IsLockedViaThreadSuspension()
-{
-    LIMITED_METHOD_CONTRACT;
-    return FALSE;
-}
-#endif // _DEBUG
-
-//---------------------------------------------------------------------------------------
-//
-// All locks are nops because of there is always only one thread.
-//
-
-void CrstBase::InitWorker(INDEBUG_COMMA(CrstType crstType) CrstFlags flags)
-{
-    m_dwFlags = flags;
-}
-
-void CrstBase::Destroy()
-{
-}
-
-void CrstBase::Enter(INDEBUG(enum CrstBase::NoLevelCheckFlag))
-{
-}
-
-void CrstBase::Leave()
-{
-}
-
-BOOL __SwitchToThread(DWORD, DWORD)
-{
-    return TRUE;
-}
-
-//---------------------------------------------------------------------------------------
-//
-// Globals and misc other
-//
-
-GPTR_IMPL(IGCHeap,g_pGCHeap);
-
-GVAL_IMPL_INIT(GCHeapType, g_heap_type, GC_HEAP_WKS);
-
-HRESULT GetExceptionHResult(OBJECTREF throwable)
-{
-    return E_FAIL;
-}
-
-DWORD GetCurrentExceptionCode()
-{
-    return 0;
-}
-
-//---------------------------------------------------------------------------------------
-//
-// Dynamically unreachable implementation of profiler callbacks. Note that we can't just
-// disable PROFILING_SUPPORTED for crossgen because of it affects data layout and FCall tables.
-//
-
-UINT_PTR EEToProfInterfaceImpl::EEFunctionIDMapper(FunctionID funcId, BOOL *pbHookFunction)
-{
-    UNREACHABLE();
-}
-
-HRESULT EEToProfInterfaceImpl::JITInlining(
-    /* [in] */  FunctionID    callerId,
-    /* [in] */  FunctionID    calleeId,
-    /* [out] */ BOOL *        pfShouldInline)
-{
-    UNREACHABLE();
-}
-
-HRESULT EEToProfInterfaceImpl::ModuleLoadStarted(ModuleID moduleId)
-{
-    UNREACHABLE();
-}
-
-HRESULT EEToProfInterfaceImpl::ModuleLoadFinished(
-    ModuleID    moduleId,
-    HRESULT        hrStatus)
-{
-    UNREACHABLE();
-}
-
-HRESULT EEToProfInterfaceImpl::ModuleUnloadStarted(
-    ModuleID    moduleId)
-{
-    UNREACHABLE();
-}
-
-HRESULT EEToProfInterfaceImpl::ModuleUnloadFinished(
-    ModuleID    moduleId,
-    HRESULT        hrStatus)
-{
-    UNREACHABLE();
-}
-
-HRESULT EEToProfInterfaceImpl::ModuleAttachedToAssembly(
-    ModuleID    moduleId,
-    AssemblyID  AssemblyId)
-{
-    UNREACHABLE();
-}
-
-HRESULT EEToProfInterfaceImpl::ClassLoadStarted(
-    ClassID     classId)
-{
-    UNREACHABLE();
-}
-
-HRESULT EEToProfInterfaceImpl::ClassLoadFinished(
-    ClassID     classId,
-    HRESULT     hrStatus)
-{
-    UNREACHABLE();
-}
-
-HRESULT EEToProfInterfaceImpl::AppDomainCreationFinished(
-    AppDomainID appDomainId,
-    HRESULT     hrStatus)
-{
-    UNREACHABLE();
-}
-
-HRESULT EEToProfInterfaceImpl::AppDomainCreationStarted(
-    AppDomainID appDomainId)
-{
-    UNREACHABLE();
-}
-
-HRESULT EEToProfInterfaceImpl::AppDomainShutdownFinished(
-    AppDomainID appDomainId,
-    HRESULT     hrStatus)
-{
-    UNREACHABLE();
-}
-
-HRESULT EEToProfInterfaceImpl::AppDomainShutdownStarted(
-    AppDomainID appDomainId)
-{
-    UNREACHABLE();
-}
-
-HRESULT EEToProfInterfaceImpl::AssemblyLoadStarted(
-    AssemblyID  assemblyId)
-{
-    UNREACHABLE();
-}
-
-HRESULT EEToProfInterfaceImpl::AssemblyLoadFinished(
-    AssemblyID  assemblyId,
-    HRESULT     hrStatus)
-{
-    UNREACHABLE();
-}
-
-ClassID TypeHandleToClassID(TypeHandle th)
-{
-    UNREACHABLE();
-}
-
-//---------------------------------------------------------------------------------------
-//
-// Stubed-out implementations of functions that can do anything useful only when we are actually running managed code
-//
-
-FuncPtrStubs::FuncPtrStubs()
-    : m_hashTableCrst(CrstFuncPtrStubs, CRST_UNSAFE_ANYMODE)
-{
-}
-
-PCODE MethodDesc::GetMultiCallableAddrOfCode(CORINFO_ACCESS_FLAGS accessFlags)
-{
-    return 0x321;
-}
-
-PCODE MethodDesc::TryGetMultiCallableAddrOfCode(CORINFO_ACCESS_FLAGS accessFlags)
-{
-    return 0x321;
-}
-
-#ifdef TARGET_AMD64
-INT32 rel32UsingJumpStub(INT32 UNALIGNED * pRel32, PCODE target, MethodDesc *pMethod,
-    LoaderAllocator *pLoaderAllocator /* = NULL */, bool throwOnOutOfMemoryWithinRange /*= true*/)
-{
-    // crossgen does not have jump stubs
-    return 0;
-}
-
-INT32 rel32UsingPreallocatedJumpStub(INT32 UNALIGNED * pRel32, PCODE target, PCODE jumpStubAddrRX, PCODE jumpStubAddrRW, bool emitJump)
-{
-    // crossgen does not have jump stubs
-    return 0;
-}
-#endif
-
-
-CORINFO_GENERIC_HANDLE JIT_GenericHandleWorker(MethodDesc *  pMD, MethodTable * pMT, LPVOID signature, DWORD dictionaryIndexAndSlot, Module* pModule)
-{
-    UNREACHABLE();
-}
-
-void CrawlFrame::GetExactGenericInstantiations(Instantiation *pClassInst, Instantiation *pMethodInst)
-{
-    UNREACHABLE();
-}
-
-void SetObjectReferenceUnchecked(OBJECTREF *dst,OBJECTREF ref)
-{
-    UNREACHABLE();
-}
-
-BOOL Object::SupportsInterface(OBJECTREF pObj, MethodTable* pInterfaceMT)
-{
-    UNREACHABLE();
-}
-
-GCFrame::GCFrame(Thread* pThread, OBJECTREF *pObjRefs, UINT numObjRefs, BOOL maybeInterior)
-{
-}
-
-void GCFrame::GcScanRoots(promote_func *fn, ScanContext* sc)
-{
-    UNREACHABLE();
-}
-
-void HijackFrame::GcScanRoots(promote_func *fn, ScanContext* sc)
-{
-    UNREACHABLE();
-}
-
-void Frame::Push()
-{
-}
-
-void Frame::Pop()
-{
-}
-
-PCODE COMDelegate::GetWrapperInvoke(MethodDesc* pMD)
-{
-    return (PCODE)(0x12345);
-}
-
-Assembly * SystemDomain::GetCallersAssembly(StackCrawlMark * stackMark)
-{
-    return NULL;
-}
-
-void EnableStressHeapHelper()
-{
-    UNREACHABLE();
-}
-
-void ReflectionModule::CaptureModuleMetaDataToMemory()
-{
-}
-
-//---------------------------------------------------------------------------------------
-//
-// Empty implementations of shutdown-related functions. We don't do any cleanup for shutdown during crossgen.
-//
-
-Assembly::~Assembly()
-{
-}
-
-void Assembly::StartUnload()
-{
-}
-
-void Module::StartUnload()
-{
-}
-
-void DynamicMethodTable::Destroy()
-{
-}
-
-void SyncClean::AddEEHashTable(EEHashEntry** entry)
-{
-}
-
-void SyncClean::AddHashMap(Bucket *bucket)
-{
-}
-
-#ifdef FEATURE_COMINTEROP
-LONG ComCallWrapperTemplate::Release()
-{
-    UNREACHABLE();
-}
-#endif
-
-extern "C" UINT_PTR STDCALL GetCurrentIP()
-{
-    return 0;
-}
-
-// This method must return a value to avoid getting non-actionable dumps on x86.
-// If this method were a DECLSPEC_NORETURN then dumps would not provide the necessary
-// context at the point of the failure
-int NOINLINE EEPolicy::HandleFatalError(UINT exitCode, UINT_PTR address, LPCWSTR pszMessage, PEXCEPTION_POINTERS pExceptionInfo, LPCWSTR errorSource, LPCWSTR argExceptionString)
-{
-    fprintf(stderr, "Fatal error: %08x\n", exitCode);
-    ExitProcess(exitCode);
-    return -1;
-}
-
-//---------------------------------------------------------------------------------------
-
-Assembly * AppDomain::RaiseAssemblyResolveEvent(AssemblySpec * pSpec)
-{
-    return NULL;
-}
-
-Assembly * AppDomain::RaiseResourceResolveEvent(DomainAssembly* pAssembly, LPCSTR szName)
-{
-    return NULL;
-}
-
-DomainAssembly * AppDomain::RaiseTypeResolveEventThrowing(DomainAssembly* pAssembly, LPCSTR szName, ASSEMBLYREF *pResultingAssemblyRef)
-{
-    return NULL;
-}
-
-void AppDomain::RaiseLoadingAssemblyEvent(DomainAssembly *pAssembly)
-{
-}
diff --git a/src/coreclr/vm/dataimage.cpp b/src/coreclr/vm/dataimage.cpp
deleted file mode 100644 (file)
index de8569c..0000000
+++ /dev/null
@@ -1,2428 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-
-
-
-#include "common.h"
-
-#ifdef FEATURE_PREJIT
-
-#include "dataimage.h"
-#include "compile.h"
-
-#include "field.h"
-
-//
-// Include Zapper infrastructure here
-//
-// dataimage.cpp is the only place where Zapper infrasture should be used directly in the VM.
-// The rest of the VM should never use Zapper infrastructure directly for good layering.
-// The long term goal is to move all NGen specific parts like Save and Fixup methods out of the VM,
-// and remove the dataimage.cpp completely.
-//
-#include "zapper.h"
-#include "../zap/zapwriter.h"
-#include "../zap/zapimage.h"
-#include "../zap/zapimport.h"
-#include "inlinetracking.h"
-
-#define NodeTypeForItemKind(kind) ((ZapNodeType)(ZapNodeType_StoredStructure + (kind)))
-
-class ZapStoredStructure : public ZapNode
-{
-    DWORD  m_dwSize;
-    BYTE    m_kind;
-    BYTE    m_align;
-
-public:
-    ZapStoredStructure(DWORD dwSize, BYTE kind, BYTE align)
-        : m_dwSize(dwSize), m_kind(kind), m_align(align)
-    {
-    }
-
-    void * GetData()
-    {
-        return this + 1;
-    }
-
-    DataImage::ItemKind GetKind()
-    {
-        return (DataImage::ItemKind)m_kind;
-    }
-
-    virtual DWORD GetSize()
-    {
-        return m_dwSize;
-    }
-
-    virtual UINT GetAlignment()
-    {
-        return m_align;
-    }
-
-    virtual ZapNodeType GetType()
-    {
-        return NodeTypeForItemKind(m_kind);
-    }
-
-    virtual void Save(ZapWriter * pZapWriter);
-};
-
-inline ZapStoredStructure * AsStoredStructure(ZapNode * pNode)
-{
-    // Verify that it is one of the StoredStructure subtypes
-    _ASSERTE(pNode->GetType() >= ZapNodeType_StoredStructure);
-    return (ZapStoredStructure *)pNode;
-}
-
-struct InternedStructureKey
-{
-    InternedStructureKey(const void * data, DWORD dwSize, DataImage::ItemKind kind)
-        : m_data(data), m_dwSize(dwSize), m_kind(kind)
-    {
-    }
-
-    const void *m_data;
-    DWORD       m_dwSize;
-    DataImage::ItemKind    m_kind;
-};
-
-class InternedStructureTraits : public NoRemoveSHashTraits< DefaultSHashTraits<ZapStoredStructure *> >
-{
-public:
-    typedef InternedStructureKey key_t;
-
-    static key_t GetKey(element_t e)
-    {
-        LIMITED_METHOD_CONTRACT;
-        return InternedStructureKey(e->GetData(), e->GetSize(), e->GetKind());
-    }
-    static BOOL Equals(key_t k1, key_t k2)
-    {
-        LIMITED_METHOD_CONTRACT;
-        return (k1.m_dwSize == k2.m_dwSize) &&
-               (k1.m_kind == k2.m_kind) &&
-               memcmp(k1.m_data, k2.m_data, k1.m_dwSize) == 0;
-    }
-    static count_t Hash(key_t k)
-    {
-        LIMITED_METHOD_CONTRACT;
-        return (count_t)k.m_dwSize ^ (count_t)k.m_kind ^ HashBytes((BYTE *)k.m_data, k.m_dwSize);
-    }
-
-    static element_t Null() { LIMITED_METHOD_CONTRACT; return NULL; }
-    static bool IsNull(const element_t &e) { LIMITED_METHOD_CONTRACT; return e == NULL; }
-};
-
-DataImage::DataImage(Module *module, CEEPreloader *preloader)
-    : m_module(module),
-      m_preloader(preloader),
-      m_iCurrentFixup(0),       // Dev11 bug 181494 instrumentation
-      m_pInternedStructures(NULL),
-      m_pCurrentAssociatedMethodTable(NULL)
-{
-    m_pZapImage = m_preloader->GetDataStore()->GetZapImage();
-    m_pZapImage->m_pDataImage = this;
-
-    m_pInternedStructures = new InternedStructureHashTable();
-    m_inlineTrackingMap = new InlineTrackingMap();
-}
-
-DataImage::~DataImage()
-{
-    delete m_pInternedStructures;
-    delete m_inlineTrackingMap;
-}
-
-void DataImage::PreSave()
-{
-#ifndef ZAP_HASHTABLE_TUNING
-    Preallocate();
-#endif
-}
-
-void DataImage::PostSave()
-{
-#ifdef ZAP_HASHTABLE_TUNING
-    // If ZAP_HASHTABLE_TUNING is defined, preallocate is overloaded to print the tunning constants
-    Preallocate();
-#endif
-}
-
-DWORD DataImage::GetMethodProfilingFlags(MethodDesc * pMD)
-{
-    STANDARD_VM_CONTRACT;
-
-    // We are not differentiating unboxing stubs vs. normal method descs in IBC data yet
-    if (pMD->IsUnboxingStub())
-        pMD = pMD->GetWrappedMethodDesc();
-
-    const MethodProfilingData * pData = m_methodProfilingData.LookupPtr(pMD);
-    return (pData != NULL) ? pData->flags : 0;
-}
-
-void DataImage::SetMethodProfilingFlags(MethodDesc * pMD, DWORD flags)
-{
-    STANDARD_VM_CONTRACT;
-
-    const MethodProfilingData * pData = m_methodProfilingData.LookupPtr(pMD);
-    if (pData != NULL)
-    {
-        const_cast<MethodProfilingData *>(pData)->flags |= flags;
-        return;
-    }
-
-    MethodProfilingData data;
-    data.pMD = pMD;
-    data.flags = flags;
-    m_methodProfilingData.Add(data);
-}
-
-void DataImage::Preallocate()
-{
-    STANDARD_VM_CONTRACT;
-
-    // TODO: Move to ZapImage
-
-    PEDecoder pe((void *)m_module->GetFile()->GetManagedFileContents());
-
-    COUNT_T cbILImage = pe.GetSize();
-
-    // Curb the estimate to handle corner cases gracefuly
-    cbILImage = min(cbILImage, 50000000);
-
-    PREALLOCATE_HASHTABLE(DataImage::m_structures, 0.019, cbILImage);
-    PREALLOCATE_ARRAY(DataImage::m_structuresInOrder, 0.0088, cbILImage);
-    PREALLOCATE_ARRAY(DataImage::m_Fixups, 0.046, cbILImage);
-    PREALLOCATE_HASHTABLE(DataImage::m_surrogates, 0.0025, cbILImage);
-    PREALLOCATE_HASHTABLE((*DataImage::m_pInternedStructures), 0.0007, cbILImage);
-}
-
-ZapHeap * DataImage::GetHeap()
-{
-    LIMITED_METHOD_CONTRACT;
-    return m_pZapImage->GetHeap();
-}
-
-void DataImage::AddStructureInOrder(ZapNode *pNode, BOOL fMaintainSaveOrder /*=FALSE*/)
-{
-    WRAPPER_NO_CONTRACT;
-
-    SavedNodeEntry entry;
-    entry.pNode = pNode;
-    entry.dwAssociatedOrder = 0;
-
-    if (fMaintainSaveOrder)
-    {
-        entry.dwAssociatedOrder = MAINTAIN_SAVE_ORDER;
-    }
-    else if (m_pCurrentAssociatedMethodTable)
-    {
-        TypeHandle th = TypeHandle(m_pCurrentAssociatedMethodTable);
-        entry.dwAssociatedOrder = m_pZapImage->LookupClassLayoutOrder(CORINFO_CLASS_HANDLE(th.AsPtr()));
-    }
-
-    m_structuresInOrder.Append(entry);
-}
-
-ZapStoredStructure * DataImage::StoreStructureHelper(const void *data, SIZE_T size,
-                       DataImage::ItemKind kind,
-                       int align,
-                       BOOL fMaintainSaveOrder)
-{
-    STANDARD_VM_CONTRACT;
-
-    S_SIZE_T cbAllocSize = S_SIZE_T(sizeof(ZapStoredStructure)) + S_SIZE_T(size);
-    if(cbAllocSize.IsOverflow())
-        ThrowHR(COR_E_OVERFLOW);
-
-    void * pMemory = new (GetHeap()) BYTE[cbAllocSize.Value()];
-
-    // PE files cannot be larger than 4 GB
-    if (DWORD(size) != size)
-        ThrowHR(E_UNEXPECTED);
-
-    ZapStoredStructure * pStructure = new (pMemory) ZapStoredStructure((DWORD)size, static_cast<BYTE>(kind), static_cast<BYTE>(align));
-
-    if (data != NULL)
-    {
-        CopyMemory(pStructure->GetData(), data, size);
-        BindPointer(data, pStructure, 0);
-    }
-
-    m_pLastLookup = NULL;
-
-    AddStructureInOrder(pStructure, fMaintainSaveOrder);
-
-    return pStructure;
-}
-
-// Bind pointer to the relative offset in ZapNode
-void DataImage::BindPointer(const void *p, ZapNode * pNode, SSIZE_T offset)
-{
-    STANDARD_VM_CONTRACT;
-
-    _ASSERTE(m_structures.LookupPtr(p) == NULL);
-
-    StructureEntry e;
-    e.ptr = p;
-    e.pNode = pNode;
-    e.offset = offset;
-    m_structures.Add(e);
-
-    m_pLastLookup = NULL;
-}
-
-void DataImage::CopyData(ZapStoredStructure * pNode, const void * p, ULONG size)
-{
-    memcpy(pNode->GetData(), p, size);
-}
-
-void DataImage::CopyDataToOffset(ZapStoredStructure * pNode, ULONG offset, const void * p, ULONG size)
-{
-    SIZE_T target = (SIZE_T) (pNode->GetData());
-    target += offset;
-
-    memcpy((void *) target, p, size);
-}
-
-void DataImage::PlaceStructureForAddress(const void * data, CorCompileSection section)
-{
-    STANDARD_VM_CONTRACT;
-
-    if (data == NULL)
-        return;
-
-    const StructureEntry * pEntry = m_structures.LookupPtr(data);
-    if (pEntry == NULL)
-        return;
-
-    ZapNode * pNode = pEntry->pNode;
-    if (!pNode->IsPlaced())
-    {
-        ZapVirtualSection * pSection = m_pZapImage->GetSection(section);
-        pSection->Place(pNode);
-    }
-}
-
-void DataImage::PlaceInternedStructureForAddress(const void * data, CorCompileSection sectionIfReused, CorCompileSection sectionIfSingleton)
-{
-    STANDARD_VM_CONTRACT;
-
-    if (data == NULL)
-        return;
-
-    const StructureEntry * pEntry = m_structures.LookupPtr(data);
-    if (pEntry == NULL)
-        return;
-
-    ZapNode * pNode = pEntry->pNode;
-    if (!pNode->IsPlaced())
-    {
-        CorCompileSection section = m_reusedStructures.Contains(pNode) ? sectionIfReused : sectionIfSingleton;
-        ZapVirtualSection * pSection = m_pZapImage->GetSection(section);
-        pSection->Place(pNode);
-    }
-}
-
-void DataImage::FixupPointerField(PVOID p, SSIZE_T offset)
-{
-    STANDARD_VM_CONTRACT;
-
-    PVOID pTarget = *(PVOID UNALIGNED *)((BYTE *)p + offset);
-
-    if (pTarget == NULL)
-    {
-        ZeroPointerField(p, offset);
-        return;
-    }
-
-    FixupField(p, offset, pTarget);
-}
-
-void DataImage::FixupRelativePointerField(PVOID p, SSIZE_T offset)
-{
-    STANDARD_VM_CONTRACT;
-
-    PVOID pTarget = RelativePointer<PTR_VOID>::GetValueMaybeNullAtPtr((TADDR)p + offset);
-
-    if (pTarget == NULL)
-    {
-        ZeroPointerField(p, offset);
-        return;
-    }
-
-    FixupField(p, offset, pTarget, 0, IMAGE_REL_BASED_RELPTR);
-}
-
-static void EncodeTargetOffset(PVOID pLocation, SSIZE_T targetOffset, ZapRelocationType type)
-{
-    // Store the targetOffset into the location of the reloc temporarily
-    switch (type)
-    {
-    case IMAGE_REL_BASED_PTR:
-    case IMAGE_REL_BASED_RELPTR:
-        *(UNALIGNED TADDR *)pLocation = (TADDR)targetOffset;
-        break;
-
-    case IMAGE_REL_BASED_ABSOLUTE:
-        *(UNALIGNED DWORD *)pLocation = (DWORD)targetOffset;
-        break;
-
-    case IMAGE_REL_BASED_ABSOLUTE_TAGGED:
-        _ASSERTE(targetOffset == 0);
-        *(UNALIGNED TADDR *)pLocation = 0;
-        break;
-
-#if defined(TARGET_X86) || defined(TARGET_AMD64)
-    case IMAGE_REL_BASED_REL32:
-        *(UNALIGNED INT32 *)pLocation = (INT32)targetOffset;
-        break;
-#endif // TARGET_X86 || TARGET_AMD64
-
-    default:
-        _ASSERTE(0);
-    }
-}
-
-static SSIZE_T DecodeTargetOffset(PVOID pLocation, ZapRelocationType type)
-{
-    // Store the targetOffset into the location of the reloc temporarily
-    switch (type)
-    {
-    case IMAGE_REL_BASED_PTR:
-    case IMAGE_REL_BASED_RELPTR:
-        return (SSIZE_T)*(UNALIGNED TADDR *)pLocation;
-
-    case IMAGE_REL_BASED_ABSOLUTE:
-        return *(UNALIGNED DWORD *)pLocation;
-
-    case IMAGE_REL_BASED_ABSOLUTE_TAGGED:
-        _ASSERTE(*(UNALIGNED TADDR *)pLocation == 0);
-        return 0;
-
-#if defined(TARGET_X86) || defined(TARGET_AMD64)
-    case IMAGE_REL_BASED_REL32:
-        return *(UNALIGNED INT32 *)pLocation;
-#endif // TARGET_X86 || TARGET_AMD64
-
-    default:
-        _ASSERTE(0);
-        return 0;
-    }
-}
-
-void DataImage::FixupField(PVOID p, SSIZE_T offset, PVOID pTarget, SSIZE_T targetOffset, ZapRelocationType type)
-{
-    STANDARD_VM_CONTRACT;
-
-    m_iCurrentFixup++;      // Dev11 bug 181494 instrumentation
-
-    const StructureEntry * pEntry = m_pLastLookup;
-    if (pEntry == NULL || pEntry->ptr != p)
-    {
-        pEntry = m_structures.LookupPtr(p);
-        _ASSERTE(pEntry != NULL &&
-            "StoreStructure or BindPointer have to be called on all save data.");
-        m_pLastLookup = pEntry;
-    }
-    offset += pEntry->offset;
-    _ASSERTE(0 <= offset && (DWORD)offset < pEntry->pNode->GetSize());
-
-    const StructureEntry * pTargetEntry = m_pLastLookup;
-    if (pTargetEntry == NULL || pTargetEntry->ptr != pTarget)
-    {
-        pTargetEntry = m_structures.LookupPtr(pTarget);
-
-        _ASSERTE(pTargetEntry != NULL &&
-            "The target of the fixup is not saved into the image");
-    }
-    targetOffset += pTargetEntry->offset;
-    _ASSERTE(0 <= targetOffset && (DWORD)targetOffset <= pTargetEntry->pNode->GetSize());
-
-    FixupEntry entry;
-    entry.m_type = type;
-    entry.m_offset = (DWORD)offset;
-    entry.m_pLocation = AsStoredStructure(pEntry->pNode);
-    entry.m_pTargetNode = pTargetEntry->pNode;
-    AppendFixup(entry);
-
-    EncodeTargetOffset((BYTE *)AsStoredStructure(pEntry->pNode)->GetData() + offset, targetOffset, type);
-}
-
-void DataImage::FixupFieldToNode(PVOID p, SSIZE_T offset, ZapNode * pTarget, SSIZE_T targetOffset, ZapRelocationType type)
-{
-    STANDARD_VM_CONTRACT;
-
-    m_iCurrentFixup++;      // Dev11 bug 181494 instrumentation
-
-    const StructureEntry * pEntry = m_pLastLookup;
-    if (pEntry == NULL || pEntry->ptr != p)
-    {
-        pEntry = m_structures.LookupPtr(p);
-        _ASSERTE(pEntry != NULL &&
-            "StoreStructure or BindPointer have to be called on all save data.");
-        m_pLastLookup = pEntry;
-    }
-    offset += pEntry->offset;
-    _ASSERTE(0 <= offset && (DWORD)offset < pEntry->pNode->GetSize());
-
-    _ASSERTE(pTarget != NULL);
-
-    FixupEntry entry;
-    entry.m_type = type;
-    entry.m_offset = (DWORD)offset;
-    entry.m_pLocation = AsStoredStructure(pEntry->pNode);
-    entry.m_pTargetNode = pTarget;
-    AppendFixup(entry);
-
-    EncodeTargetOffset((BYTE *)AsStoredStructure(pEntry->pNode)->GetData() + offset, targetOffset, type);
-}
-
-DWORD DataImage::GetRVA(const void *data)
-{
-    STANDARD_VM_CONTRACT;
-
-    const StructureEntry * pEntry = m_structures.LookupPtr(data);
-    _ASSERTE(pEntry != NULL);
-
-    return pEntry->pNode->GetRVA() + (DWORD)pEntry->offset;
-}
-
-void DataImage::ZeroField(PVOID p, SSIZE_T offset, SIZE_T size)
-{
-    STANDARD_VM_CONTRACT;
-
-    ZeroMemory(GetImagePointer(p, offset), size);
-}
-
-void * DataImage::GetImagePointer(ZapStoredStructure * pNode)
-{
-    return pNode->GetData();
-}
-
-void * DataImage::GetImagePointer(PVOID p, SSIZE_T offset)
-{
-    STANDARD_VM_CONTRACT;
-
-    const StructureEntry * pEntry = m_pLastLookup;
-    if (pEntry == NULL || pEntry->ptr != p)
-    {
-        pEntry = m_structures.LookupPtr(p);
-        _ASSERTE(pEntry != NULL &&
-            "StoreStructure or BindPointer have to be called on all save data.");
-        m_pLastLookup = pEntry;
-    }
-    offset += pEntry->offset;
-    _ASSERTE(0 <= offset && (DWORD)offset < pEntry->pNode->GetSize());
-
-    return (BYTE *)AsStoredStructure(pEntry->pNode)->GetData() + offset;
-}
-
-ZapNode * DataImage::GetNodeForStructure(PVOID p, SSIZE_T * pOffset)
-{
-    const StructureEntry * pEntry = m_pLastLookup;
-    if (pEntry == NULL || pEntry->ptr != p)
-    {
-        pEntry = m_structures.LookupPtr(p);
-        _ASSERTE(pEntry != NULL &&
-            "StoreStructure or BindPointer have to be called on all save data.");
-    }
-    *pOffset = pEntry->offset;
-    return pEntry->pNode;
-}
-
-ZapStoredStructure * DataImage::StoreInternedStructure(const void *data, ULONG size,
-                       DataImage::ItemKind kind,
-                       int align)
-{
-    STANDARD_VM_CONTRACT;
-
-    ZapStoredStructure * pStructure = m_pInternedStructures->Lookup(InternedStructureKey(data, size, kind));
-
-    if (pStructure != NULL)
-    {
-        // Just add a new mapping for to the interned structure
-        BindPointer(data, pStructure, 0);
-
-        // Track that this structure has been successfully reused by interning
-        NoteReusedStructure(data);
-    }
-    else
-    {
-        // We have not seen this structure yet. Create a new one.
-        pStructure = StoreStructure(data, size, kind);
-        m_pInternedStructures->Add(pStructure);
-    }
-
-    return pStructure;
-}
-
-void DataImage::NoteReusedStructure(const void *data)
-{
-    STANDARD_VM_CONTRACT;
-
-    _ASSERTE(IsStored(data));
-
-    const StructureEntry * pEntry = m_structures.LookupPtr(data);
-
-    if (!m_reusedStructures.Contains(pEntry->pNode))
-    {
-        m_reusedStructures.Add(pEntry->pNode);
-    }
-}
-
-// Save the info of an RVA into m_rvaInfoVector.
-void DataImage::StoreRvaInfo(FieldDesc * pFD,
-                             DWORD      rva,
-                             UINT       size,
-                             UINT       align)
-{
-    RvaInfoStructure rvaInfo;
-
-    _ASSERTE(m_module == pFD->GetModule());
-    _ASSERTE(m_module == pFD->GetLoaderModule());
-
-    rvaInfo.pFD = pFD;
-    rvaInfo.rva = rva;
-    rvaInfo.size = size;
-    rvaInfo.align = align;
-
-    m_rvaInfoVector.Append(rvaInfo);
-}
-
-// qsort compare function.
-// Primary key: rva (ascending order). Secondary key: size (descending order).
-int __cdecl DataImage::rvaInfoVectorEntryCmp(const void* a_, const void* b_)
-{
-    LIMITED_METHOD_CONTRACT;
-    DataImage::RvaInfoStructure *a = (DataImage::RvaInfoStructure *)a_;
-    DataImage::RvaInfoStructure *b = (DataImage::RvaInfoStructure *)b_;
-    int rvaComparisonResult = (int)(a->rva - b->rva);
-    if (rvaComparisonResult!=0)
-        return rvaComparisonResult;        // Ascending order on rva
-    return (int)(b->size - a->size); // Descending order on size
-}
-
-// Sort the list of RVA statics in an ascending order wrt the RVA and save them.
-// For RVA structures with the same RVA, we will only store the one with the largest size.
-void DataImage::SaveRvaStructure()
-{
-    if (m_rvaInfoVector.IsEmpty())
-        return;  // No RVA static to save
-
-    // Use qsort to sort the m_rvaInfoVector
-    qsort (&m_rvaInfoVector[0],               // start of array
-           m_rvaInfoVector.GetCount(),        // array size in elements
-           sizeof(RvaInfoStructure),        // element size in bytes
-           rvaInfoVectorEntryCmp);          // comparere function
-
-    RvaInfoStructure * previousRvaInfo = NULL;
-
-    for (COUNT_T i=0; i<m_rvaInfoVector.GetCount(); i++) {
-
-        RvaInfoStructure * rvaInfo = &(m_rvaInfoVector[i]);
-
-        // Verify that rvaInfo->rva are actually monotonically increasing and
-        // rvaInfo->size are monotonically decreasing if rva are the same.
-        _ASSERTE(previousRvaInfo==NULL ||
-                 previousRvaInfo->rva < rvaInfo->rva ||
-                 ((previousRvaInfo->rva == rvaInfo->rva) && (previousRvaInfo->size >= rvaInfo->size))
-                );
-
-        if (previousRvaInfo==NULL || previousRvaInfo->rva != rvaInfo->rva) {
-            void * pRVAData = rvaInfo->pFD->GetStaticAddressHandle(NULL);
-
-            // Note that we force the structures to be laid out in the order we save them
-            StoreStructureInOrder(pRVAData, rvaInfo->size,
-                           DataImage::ITEM_RVA_STATICS,
-                           rvaInfo->align);
-        }
-
-        previousRvaInfo = rvaInfo;
-    }
-}
-
-void DataImage::RegisterSurrogate(PVOID ptr, PVOID surrogate)
-{
-    STANDARD_VM_CONTRACT;
-
-    m_surrogates.Add(ptr, surrogate);
-}
-
-PVOID DataImage::LookupSurrogate(PVOID ptr)
-{
-    STANDARD_VM_CONTRACT;
-
-    const KeyValuePair<PVOID, PVOID> * pEntry = m_surrogates.LookupPtr(ptr);
-    if (pEntry == NULL)
-        return NULL;
-    return pEntry->Value();
-}
-
-// Please read comments in corcompile.h for ZapVirtualSectionType before
-// putting data items into sections.
-FORCEINLINE static CorCompileSection GetSectionForNodeType(ZapNodeType type)
-{
-    LIMITED_METHOD_CONTRACT;
-
-    switch ((int)type)
-    {
-    // SECTION_MODULE
-    case NodeTypeForItemKind(DataImage::ITEM_MODULE):
-        return CORCOMPILE_SECTION_MODULE;
-
-    // CORCOMPILE_SECTION_WRITE       (Hot Writeable)
-    // things only go in here if they are:
-    //    (a) explicitly identified by profiling data
-    // or (b) if we have no profiling for these items but they are frequently written to
-    case NodeTypeForItemKind(DataImage::ITEM_FILEREF_MAP):
-    case NodeTypeForItemKind(DataImage::ITEM_ASSEMREF_MAP):
-    case NodeTypeForItemKind(DataImage::ITEM_DYNAMIC_STATICS_INFO_TABLE):
-    case NodeTypeForItemKind(DataImage::ITEM_DYNAMIC_STATICS_INFO_ENTRY):
-    case NodeTypeForItemKind(DataImage::ITEM_CER_RESTORE_FLAGS):
-        return CORCOMPILE_SECTION_WRITE;
-
-    // CORCOMPILE_SECTION_WRITEABLE   (Cold Writeable)
-    case NodeTypeForItemKind(DataImage::ITEM_METHOD_TABLE_SPECIAL_WRITEABLE):
-    case NodeTypeForItemKind(DataImage::ITEM_METHOD_TABLE_DATA_COLD_WRITEABLE):
-    case NodeTypeForItemKind(DataImage::ITEM_DICTIONARY_WRITEABLE):
-    case NodeTypeForItemKind(DataImage::ITEM_FROZEN_OBJECTS): // sometimes the objhdr is modified
-        return CORCOMPILE_SECTION_WRITEABLE;
-
-    // SECTION_HOT
-    // Other things go in here if
-    //   (a) identified as reads by the profiling runs
-    //   (b) if we have no profiling for these items but are identified as typically being read
-    case NodeTypeForItemKind(DataImage::ITEM_CER_ROOT_TABLE):
-    case NodeTypeForItemKind(DataImage::ITEM_RID_MAP_HOT):
-    case NodeTypeForItemKind(DataImage::ITEM_BINDER):
-    case NodeTypeForItemKind(DataImage::ITEM_MODULE_SECDESC):
-    case NodeTypeForItemKind(DataImage::ITEM_METHOD_DESC_HOT):
-        return CORCOMPILE_SECTION_HOT;
-
-    case NodeTypeForItemKind(DataImage::ITEM_BINDER_ITEMS):         // these are the guaranteed to be hot items
-        return CORCOMPILE_SECTION_READONLY_SHARED_HOT;
-
-    // SECTION_READONLY_HOT
-    case NodeTypeForItemKind(DataImage::ITEM_GC_STATIC_HANDLES_HOT): // this is assumed to be hot.  it is not written to.
-    case NodeTypeForItemKind(DataImage::ITEM_MODULE_CCTOR_INFO_HOT):
-    case NodeTypeForItemKind(DataImage::ITEM_NGEN_HASH_BUCKETLIST_HOT):
-    case NodeTypeForItemKind(DataImage::ITEM_NGEN_HASH_ENTRIES_RO_HOT):
-        return CORCOMPILE_SECTION_READONLY_HOT;
-
-    // SECTION_HOT_WRITEABLE
-    case NodeTypeForItemKind(DataImage::ITEM_METHOD_DESC_HOT_WRITEABLE):
-    case NodeTypeForItemKind(DataImage::ITEM_METHOD_TABLE_DATA_HOT_WRITEABLE):
-    case NodeTypeForItemKind(DataImage::ITEM_NGEN_HASH_HOT):
-    case NodeTypeForItemKind(DataImage::ITEM_NGEN_HASH_ENTRIES_HOT):
-        return CORCOMPILE_SECTION_HOT_WRITEABLE;
-
-    case NodeTypeForItemKind(DataImage::ITEM_METHOD_PRECODE_HOT_WRITEABLE):
-        return CORCOMPILE_SECTION_METHOD_PRECODE_WRITE;
-
-    case NodeTypeForItemKind(DataImage::ITEM_METHOD_PRECODE_HOT):
-        return CORCOMPILE_SECTION_METHOD_PRECODE_HOT;
-
-    // SECTION_RVA_STATICS
-    case NodeTypeForItemKind(DataImage::ITEM_RVA_STATICS):
-        return CORCOMPILE_SECTION_RVA_STATICS_COLD; // This MUST go in this section
-
-    // SECTION_WARM
-    case NodeTypeForItemKind(DataImage::ITEM_GUID_INFO):
-    case NodeTypeForItemKind(DataImage::ITEM_DICTIONARY_LAYOUT):
-    case NodeTypeForItemKind(DataImage::ITEM_EECLASS_WARM):
-        return CORCOMPILE_SECTION_WARM;
-
-    // SECTION_READONLY_WARM
-    case NodeTypeForItemKind(DataImage::ITEM_METHOD_TABLE):
-    case NodeTypeForItemKind(DataImage::ITEM_INTERFACE_MAP):
-    case NodeTypeForItemKind(DataImage::ITEM_DISPATCH_MAP):
-    case NodeTypeForItemKind(DataImage::ITEM_GENERICS_STATIC_FIELDDESCS):
-    case NodeTypeForItemKind(DataImage::ITEM_GC_STATIC_HANDLES_COLD):
-    case NodeTypeForItemKind(DataImage::ITEM_MODULE_CCTOR_INFO_COLD):
-    case NodeTypeForItemKind(DataImage::ITEM_STORED_METHOD_NAME):
-    case NodeTypeForItemKind(DataImage::ITEM_PROPERTY_NAME_SET):
-    case NodeTypeForItemKind(DataImage::ITEM_STORED_METHOD_SIG_READONLY_WARM):
-        return CORCOMPILE_SECTION_READONLY_WARM;
-
-    case NodeTypeForItemKind(DataImage::ITEM_DICTIONARY):
-        return CORCOMPILE_SECTION_READONLY_DICTIONARY;
-
-    case NodeTypeForItemKind(DataImage::ITEM_VTABLE_CHUNK):
-        return CORCOMPILE_SECTION_READONLY_VCHUNKS;
-
-    // SECTION_CLASS_COLD
-    case NodeTypeForItemKind(DataImage::ITEM_PARAM_TYPEDESC):
-    case NodeTypeForItemKind(DataImage::ITEM_ARRAY_TYPEDESC):
-    case NodeTypeForItemKind(DataImage::ITEM_EECLASS):
-    case NodeTypeForItemKind(DataImage::ITEM_FPTR_TYPEDESC):
-#ifdef FEATURE_COMINTEROP
-    case NodeTypeForItemKind(DataImage::ITEM_SPARSE_VTABLE_MAP_TABLE):
-#endif // FEATURE_COMINTEROP
-        return CORCOMPILE_SECTION_CLASS_COLD;
-
-    //SECTION_READONLY_COLD
-    case NodeTypeForItemKind(DataImage::ITEM_FIELD_DESC_LIST):
-    case NodeTypeForItemKind(DataImage::ITEM_ENUM_VALUES):
-    case NodeTypeForItemKind(DataImage::ITEM_ENUM_NAME_POINTERS):
-    case NodeTypeForItemKind(DataImage::ITEM_ENUM_NAME):
-    case NodeTypeForItemKind(DataImage::ITEM_NGEN_HASH_BUCKETLIST_COLD):
-    case NodeTypeForItemKind(DataImage::ITEM_NGEN_HASH_ENTRIES_RO_COLD):
-    case NodeTypeForItemKind(DataImage::ITEM_STORED_METHOD_SIG_READONLY):
-#ifdef FEATURE_COMINTEROP
-    case NodeTypeForItemKind(DataImage::ITEM_SPARSE_VTABLE_MAP_ENTRIES):
-#endif // FEATURE_COMINTEROP
-    case NodeTypeForItemKind(DataImage::ITEM_CLASS_VARIANCE_INFO):
-        return CORCOMPILE_SECTION_READONLY_COLD;
-
-    // SECTION_CROSS_DOMAIN_INFO
-    case NodeTypeForItemKind(DataImage::ITEM_CROSS_DOMAIN_INFO):
-    case NodeTypeForItemKind(DataImage::ITEM_VTS_INFO):
-        return CORCOMPILE_SECTION_CROSS_DOMAIN_INFO;
-
-    // SECTION_METHOD_DESC_COLD
-    case NodeTypeForItemKind(DataImage::ITEM_METHOD_DESC_COLD):
-        return CORCOMPILE_SECTION_METHOD_DESC_COLD;
-
-    case NodeTypeForItemKind(DataImage::ITEM_METHOD_DESC_COLD_WRITEABLE):
-    case NodeTypeForItemKind(DataImage::ITEM_STORED_METHOD_SIG):
-        return CORCOMPILE_SECTION_METHOD_DESC_COLD_WRITEABLE;
-
-    case NodeTypeForItemKind(DataImage::ITEM_METHOD_PRECODE_COLD):
-        return CORCOMPILE_SECTION_METHOD_PRECODE_COLD;
-
-    case NodeTypeForItemKind(DataImage::ITEM_METHOD_PRECODE_COLD_WRITEABLE):
-        return CORCOMPILE_SECTION_METHOD_PRECODE_COLD_WRITEABLE;
-
-    // SECTION_MODULE_COLD
-    case NodeTypeForItemKind(DataImage::ITEM_TYPEDEF_MAP):
-    case NodeTypeForItemKind(DataImage::ITEM_TYPEREF_MAP):
-    case NodeTypeForItemKind(DataImage::ITEM_METHODDEF_MAP):
-    case NodeTypeForItemKind(DataImage::ITEM_FIELDDEF_MAP):
-    case NodeTypeForItemKind(DataImage::ITEM_MEMBERREF_MAP):
-    case NodeTypeForItemKind(DataImage::ITEM_GENERICPARAM_MAP):
-    case NodeTypeForItemKind(DataImage::ITEM_GENERICTYPEDEF_MAP):
-    case NodeTypeForItemKind(DataImage::ITEM_PROPERTYINFO_MAP):
-    case NodeTypeForItemKind(DataImage::ITEM_TYVAR_TYPEDESC):
-    case NodeTypeForItemKind(DataImage::ITEM_EECLASS_COLD):
-    case NodeTypeForItemKind(DataImage::ITEM_CER_METHOD_LIST):
-    case NodeTypeForItemKind(DataImage::ITEM_NGEN_HASH_COLD):
-    case NodeTypeForItemKind(DataImage::ITEM_NGEN_HASH_ENTRIES_COLD):
-        return CORCOMPILE_SECTION_MODULE_COLD;
-
-    // SECTION_DEBUG_COLD
-    case NodeTypeForItemKind(DataImage::ITEM_DEBUG):
-    case NodeTypeForItemKind(DataImage::ITEM_INLINING_DATA):
-        return CORCOMPILE_SECTION_DEBUG_COLD;
-
-    // SECTION_COMPRESSED_MAPS
-    case NodeTypeForItemKind(DataImage::ITEM_COMPRESSED_MAP):
-        return CORCOMPILE_SECTION_COMPRESSED_MAPS;
-
-    default:
-        _ASSERTE(!"Missing mapping between type and section");
-        return CORCOMPILE_SECTION_MODULE_COLD;
-    }
-}
-
-static int __cdecl LayoutOrderCmp(const void* a_, const void* b_)
-{
-    DWORD a = ((DataImage::SavedNodeEntry*)a_)->dwAssociatedOrder;
-    DWORD b = ((DataImage::SavedNodeEntry*)b_)->dwAssociatedOrder;
-
-    if (a > b)
-    {
-        return 1;
-    }
-    else
-    {
-        return (a < b) ? -1 : 0;
-    }
-}
-
-void DataImage::PlaceRemainingStructures()
-{
-    if (m_pZapImage->HasClassLayoutOrder())
-    {
-        // The structures are currently in save order; since we are going to change
-        // that to class layout order, first place any that require us to maintain save order.
-        // Note that this is necessary because qsort is not stable.
-        for (COUNT_T iStructure = 0; iStructure < m_structuresInOrder.GetCount(); iStructure++)
-        {
-            if (m_structuresInOrder[iStructure].dwAssociatedOrder == MAINTAIN_SAVE_ORDER)
-            {
-                ZapNode * pStructure = m_structuresInOrder[iStructure].pNode;
-                if (!pStructure->IsPlaced())
-                {
-                    ZapVirtualSection * pSection = m_pZapImage->GetSection(GetSectionForNodeType(pStructure->GetType()));
-                    pSection->Place(pStructure);
-                }
-            }
-        }
-
-        qsort(&m_structuresInOrder[0], m_structuresInOrder.GetCount(), sizeof(SavedNodeEntry), LayoutOrderCmp);
-    }
-
-    // Place the unplaced structures, which may have been re-sorted according to class-layout order
-    for (COUNT_T iStructure = 0; iStructure < m_structuresInOrder.GetCount(); iStructure++)
-    {
-        ZapNode * pStructure = m_structuresInOrder[iStructure].pNode;
-        if (!pStructure->IsPlaced())
-        {
-            ZapVirtualSection * pSection = m_pZapImage->GetSection(GetSectionForNodeType(pStructure->GetType()));
-            pSection->Place(pStructure);
-        }
-    }
-}
-
-int __cdecl DataImage::fixupEntryCmp(const void* a_, const void* b_)
-{
-    LIMITED_METHOD_CONTRACT;
-    FixupEntry *a = (FixupEntry *)a_;
-    FixupEntry *b = (FixupEntry *)b_;
-    return (a->m_pLocation->GetRVA() + a->m_offset) - (b->m_pLocation->GetRVA() + b->m_offset);
-}
-
-void DataImage::FixupRVAs()
-{
-    STANDARD_VM_CONTRACT;
-
-    FixupModuleRVAs();
-    FixupRvaStructure();
-
-
-    // Dev11 bug 181494 instrumentation
-    if (m_Fixups.GetCount() != m_iCurrentFixup) EEPOLICY_HANDLE_FATAL_ERROR(COR_E_EXECUTIONENGINE);
-
-    qsort(&m_Fixups[0], m_Fixups.GetCount(), sizeof(FixupEntry), fixupEntryCmp);
-
-    // Sentinel
-    FixupEntry entry;
-
-    entry.m_type = 0;
-    entry.m_offset = 0;
-    entry.m_pLocation = NULL;
-    entry.m_pTargetNode = NULL;
-
-    m_Fixups.Append(entry);
-
-    // Dev11 bug 181494 instrumentation
-    if (m_Fixups.GetCount() -1 != m_iCurrentFixup) EEPOLICY_HANDLE_FATAL_ERROR(COR_E_EXECUTIONENGINE);
-
-    m_iCurrentFixup = 0;
-}
-
-void DataImage::SetRVAsForFields(IMetaDataEmit * pEmit)
-{
-    for (COUNT_T i=0; i<m_rvaInfoVector.GetCount(); i++) {
-
-        RvaInfoStructure * rvaInfo = &(m_rvaInfoVector[i]);
-
-        void * pRVAData = rvaInfo->pFD->GetStaticAddressHandle(NULL);
-
-        DWORD dwOffset = GetRVA(pRVAData);
-
-        pEmit->SetRVA(rvaInfo->pFD->GetMemberDef(), dwOffset);
-    }
-}
-
-void ZapStoredStructure::Save(ZapWriter * pWriter)
-{
-    DataImage * image = ZapImage::GetImage(pWriter)->m_pDataImage;
-
-    DataImage::FixupEntry * pPrevFixupEntry = NULL;
-
-    for (;;)
-    {
-        DataImage::FixupEntry * pFixupEntry = &(image->m_Fixups[image->m_iCurrentFixup]);
-
-        if (pFixupEntry->m_pLocation != this)
-        {
-            _ASSERTE(pFixupEntry->m_pLocation == NULL ||
-                GetRVA() + GetSize() <= pFixupEntry->m_pLocation->GetRVA());
-            break;
-        }
-
-        PVOID pLocation = (BYTE *)GetData() + pFixupEntry->m_offset;
-
-        if (pPrevFixupEntry == NULL || pPrevFixupEntry->m_offset != pFixupEntry->m_offset)
-        {
-            SSIZE_T targetOffset = DecodeTargetOffset(pLocation, pFixupEntry->m_type);
-
-#ifdef _DEBUG
-            // All pointers in EE datastructures should be aligned. This is important to
-            // avoid stradling relocations that cause issues with ASLR.
-            if (pFixupEntry->m_type == IMAGE_REL_BASED_PTR)
-            {
-                _ASSERTE(IS_ALIGNED(pWriter->GetCurrentRVA() + pFixupEntry->m_offset, sizeof(TADDR)));
-            }
-#endif
-
-            ZapImage::GetImage(pWriter)->WriteReloc(
-                GetData(),
-                pFixupEntry->m_offset,
-                pFixupEntry->m_pTargetNode,
-                (int)targetOffset,
-                pFixupEntry->m_type);
-        }
-        else
-        {
-            // It's fine to have duplicate fixup entries, but they must target the same data.
-            // If this assert fires, Fixup* was called twice on the same field in an NGen'd
-            // structure with different targets, which likely indicates the current structure
-            // was illegally interned or shared.
-            _ASSERTE(pPrevFixupEntry->m_type == pFixupEntry->m_type);
-            _ASSERTE(pPrevFixupEntry->m_pTargetNode== pFixupEntry->m_pTargetNode);
-        }
-
-        pPrevFixupEntry = pFixupEntry;
-        image->m_iCurrentFixup++;
-    }
-
-    pWriter->Write(GetData(), m_dwSize);
-}
-
-void DataImage::FixupSectionRange(SIZE_T offset, ZapNode * pNode)
-{
-    STANDARD_VM_CONTRACT;
-
-    if (pNode->GetSize() != 0)
-    {
-        FixupFieldToNode(m_module->m_pNGenLayoutInfo, offset, pNode);
-
-        SIZE_T * pSize = (SIZE_T *)((BYTE *)GetImagePointer(m_module->m_pNGenLayoutInfo) + offset + sizeof(TADDR));
-        *pSize = pNode->GetSize();
-    }
-}
-
-void DataImage::FixupSectionPtr(SIZE_T offset, ZapNode * pNode)
-{
-    if (pNode->GetSize() != 0)
-        FixupFieldToNode(m_module->m_pNGenLayoutInfo, offset, pNode);
-}
-
-void DataImage::FixupJumpStubPtr(SIZE_T offset, CorInfoHelpFunc ftnNum)
-{
-    ZapNode * pNode = m_pZapImage->GetHelperThunkIfExists(ftnNum);
-    if (pNode != NULL)
-        FixupFieldToNode(m_module->m_pNGenLayoutInfo, offset, pNode);
-}
-
-void DataImage::FixupModuleRVAs()
-{
-    STANDARD_VM_CONTRACT;
-
-    FixupSectionRange(offsetof(NGenLayoutInfo, m_CodeSections[0]), m_pZapImage->m_pHotCodeSection);
-    FixupSectionRange(offsetof(NGenLayoutInfo, m_CodeSections[1]), m_pZapImage->m_pCodeSection);
-    FixupSectionRange(offsetof(NGenLayoutInfo, m_CodeSections[2]), m_pZapImage->m_pColdCodeSection);
-
-    NGenLayoutInfo * pSavedNGenLayoutInfo = (NGenLayoutInfo *)GetImagePointer(m_module->m_pNGenLayoutInfo);
-
-    COUNT_T nHotRuntimeFunctions = m_pZapImage->m_pHotRuntimeFunctionSection->GetNodeCount();
-    if (nHotRuntimeFunctions != 0)
-    {
-        pSavedNGenLayoutInfo->m_nRuntimeFunctions[0] = nHotRuntimeFunctions;
-
-        FixupFieldToNode(m_module->m_pNGenLayoutInfo, offsetof(NGenLayoutInfo, m_UnwindInfoLookupTable[0]), m_pZapImage->m_pHotRuntimeFunctionLookupSection);
-        pSavedNGenLayoutInfo->m_UnwindInfoLookupTableEntryCount[0] = m_pZapImage->m_pHotRuntimeFunctionLookupSection->GetSize() / sizeof(DWORD) - 1;
-
-        FixupFieldToNode(m_module->m_pNGenLayoutInfo, offsetof(NGenLayoutInfo, m_MethodDescs[0]), m_pZapImage->m_pHotCodeMethodDescsSection);
-
-        FixupFieldToNode(m_module->m_pNGenLayoutInfo, offsetof(NGenLayoutInfo, m_pRuntimeFunctions[0]), m_pZapImage->m_pHotRuntimeFunctionSection);
-    }
-
-    COUNT_T nRuntimeFunctions = m_pZapImage->m_pRuntimeFunctionSection->GetNodeCount();
-    if (nRuntimeFunctions != 0)
-    {
-        pSavedNGenLayoutInfo->m_nRuntimeFunctions[1] = nRuntimeFunctions;
-
-        FixupFieldToNode(m_module->m_pNGenLayoutInfo, offsetof(NGenLayoutInfo, m_UnwindInfoLookupTable[1]), m_pZapImage->m_pRuntimeFunctionLookupSection);
-        pSavedNGenLayoutInfo->m_UnwindInfoLookupTableEntryCount[1] = m_pZapImage->m_pRuntimeFunctionLookupSection->GetSize() / sizeof(DWORD) - 1;
-
-        FixupFieldToNode(m_module->m_pNGenLayoutInfo, offsetof(NGenLayoutInfo, m_MethodDescs[1]), m_pZapImage->m_pCodeMethodDescsSection);
-
-        FixupFieldToNode(m_module->m_pNGenLayoutInfo, offsetof(NGenLayoutInfo, m_pRuntimeFunctions[1]), m_pZapImage->m_pRuntimeFunctionSection);
-    }
-
-    COUNT_T nColdRuntimeFunctions = m_pZapImage->m_pColdRuntimeFunctionSection->GetNodeCount();
-    if (nColdRuntimeFunctions != 0)
-    {
-        pSavedNGenLayoutInfo->m_nRuntimeFunctions[2] = nColdRuntimeFunctions;
-
-        FixupFieldToNode(m_module->m_pNGenLayoutInfo, offsetof(NGenLayoutInfo, m_pRuntimeFunctions[2]), m_pZapImage->m_pColdRuntimeFunctionSection);
-    }
-
-    if (m_pZapImage->m_pColdCodeMapSection->GetNodeCount() != 0)
-    {
-        FixupFieldToNode(m_module->m_pNGenLayoutInfo, offsetof(NGenLayoutInfo, m_ColdCodeMap), m_pZapImage->m_pColdCodeMapSection);
-    }
-
-    FixupSectionRange(offsetof(NGenLayoutInfo, m_Precodes[0]), m_pZapImage->GetSection(CORCOMPILE_SECTION_METHOD_PRECODE_HOT));
-    FixupSectionRange(offsetof(NGenLayoutInfo, m_Precodes[1]), m_pZapImage->GetSection(CORCOMPILE_SECTION_METHOD_PRECODE_COLD));
-    FixupSectionRange(offsetof(NGenLayoutInfo, m_Precodes[2]), m_pZapImage->GetSection(CORCOMPILE_SECTION_METHOD_PRECODE_WRITE));
-    FixupSectionRange(offsetof(NGenLayoutInfo, m_Precodes[3]), m_pZapImage->GetSection(CORCOMPILE_SECTION_METHOD_PRECODE_COLD_WRITEABLE));
-
-    FixupSectionRange(offsetof(NGenLayoutInfo, m_JumpStubs), m_pZapImage->m_pHelperTableSection);
-    FixupSectionRange(offsetof(NGenLayoutInfo, m_StubLinkStubs), m_pZapImage->m_pStubsSection);
-    FixupSectionRange(offsetof(NGenLayoutInfo, m_VirtualMethodThunks), m_pZapImage->m_pVirtualImportThunkSection);
-    FixupSectionRange(offsetof(NGenLayoutInfo, m_ExternalMethodThunks), m_pZapImage->m_pExternalMethodThunkSection);
-
-    if (m_pZapImage->m_pExceptionInfoLookupTable->GetSize() != 0)
-        FixupSectionRange(offsetof(NGenLayoutInfo, m_ExceptionInfoLookupTable), m_pZapImage->m_pExceptionInfoLookupTable);
-
-    FixupJumpStubPtr(offsetof(NGenLayoutInfo, m_pPrestubJumpStub), CORINFO_HELP_EE_PRESTUB);
-#ifdef HAS_FIXUP_PRECODE
-    FixupJumpStubPtr(offsetof(NGenLayoutInfo, m_pPrecodeFixupJumpStub), CORINFO_HELP_EE_PRECODE_FIXUP);
-#endif
-    FixupJumpStubPtr(offsetof(NGenLayoutInfo, m_pVirtualImportFixupJumpStub), CORINFO_HELP_EE_VTABLE_FIXUP);
-    FixupJumpStubPtr(offsetof(NGenLayoutInfo, m_pExternalMethodFixupJumpStub), CORINFO_HELP_EE_EXTERNAL_FIXUP);
-
-    ZapNode * pFilterPersonalityRoutine = m_pZapImage->GetHelperThunkIfExists(CORINFO_HELP_EE_PERSONALITY_ROUTINE_FILTER_FUNCLET);
-    if (pFilterPersonalityRoutine != NULL)
-        FixupFieldToNode(m_module->m_pNGenLayoutInfo, offsetof(NGenLayoutInfo, m_rvaFilterPersonalityRoutine), pFilterPersonalityRoutine, 0, IMAGE_REL_BASED_ABSOLUTE);
-}
-
-void DataImage::FixupRvaStructure()
-{
-    STANDARD_VM_CONTRACT;
-
-    for (COUNT_T i=0; i<m_rvaInfoVector.GetCount(); i++) {
-
-        RvaInfoStructure * rvaInfo = &(m_rvaInfoVector[i]);
-
-        void * pRVAData = rvaInfo->pFD->GetStaticAddressHandle(NULL);
-
-        DWORD dwOffset = GetRVA(pRVAData);
-
-        FieldDesc * pNewFD = (FieldDesc *)GetImagePointer(rvaInfo->pFD);
-        pNewFD->SetOffset(dwOffset);
-    }
-}
-
-ZapNode * DataImage::GetCodeAddress(MethodDesc * method)
-{
-    ZapMethodHeader * pMethod = m_pZapImage->GetCompiledMethod((CORINFO_METHOD_HANDLE)method);
-    return (pMethod != NULL) ? pMethod->GetCode() : NULL;
-}
-
-BOOL DataImage::CanDirectCall(MethodDesc * method, CORINFO_ACCESS_FLAGS  accessFlags)
-{
-    return m_pZapImage->canIntraModuleDirectCall(NULL, (CORINFO_METHOD_HANDLE)method, NULL, accessFlags);
-}
-
-ZapNode * DataImage::GetFixupList(MethodDesc * method)
-{
-    ZapMethodHeader * pMethod = m_pZapImage->GetCompiledMethod((CORINFO_METHOD_HANDLE)method);
-    return (pMethod != NULL) ? pMethod->GetFixupList() : NULL;
-}
-
-ZapNode * DataImage::GetHelperThunk(CorInfoHelpFunc ftnNum)
-{
-    return m_pZapImage->GetHelperThunk(ftnNum);
-}
-
-ZapNode * DataImage::GetTypeHandleImport(TypeHandle th, PVOID pUniqueId)
-{
-    ZapImport * pImport = m_pZapImage->GetImportTable()->GetClassHandleImport(CORINFO_CLASS_HANDLE(th.AsPtr()), pUniqueId);
-    if (!pImport->IsPlaced())
-        m_pZapImage->GetImportTable()->PlaceImport(pImport);
-    return pImport;
-}
-
-ZapNode * DataImage::GetMethodHandleImport(MethodDesc * pMD)
-{
-    ZapImport * pImport = m_pZapImage->GetImportTable()->GetMethodHandleImport(CORINFO_METHOD_HANDLE(pMD));
-    if (!pImport->IsPlaced())
-        m_pZapImage->GetImportTable()->PlaceImport(pImport);
-    return pImport;
-}
-
-ZapNode * DataImage::GetFieldHandleImport(FieldDesc * pMD)
-{
-    ZapImport * pImport = m_pZapImage->GetImportTable()->GetFieldHandleImport(CORINFO_FIELD_HANDLE(pMD));
-    if (!pImport->IsPlaced())
-        m_pZapImage->GetImportTable()->PlaceImport(pImport);
-    return pImport;
-}
-
-ZapNode * DataImage::GetModuleHandleImport(Module * pModule)
-{
-    ZapImport * pImport = m_pZapImage->GetImportTable()->GetModuleHandleImport(CORINFO_MODULE_HANDLE(pModule));
-    if (!pImport->IsPlaced())
-        m_pZapImage->GetImportTable()->PlaceImport(pImport);
-    return pImport;
-}
-
-DWORD DataImage::GetModuleImportIndex(Module * pModule)
-{
-    return m_pZapImage->GetImportTable()->GetIndexOfModule((CORINFO_MODULE_HANDLE)pModule);
-}
-
-ZapNode * DataImage::GetExistingTypeHandleImport(TypeHandle th)
-{
-    ZapImport * pImport = m_pZapImage->GetImportTable()->GetExistingClassHandleImport(CORINFO_CLASS_HANDLE(th.AsPtr()));
-    return (pImport != NULL && pImport->IsPlaced()) ? pImport : NULL;
-}
-
-ZapNode * DataImage::GetExistingMethodHandleImport(MethodDesc * pMD)
-{
-    ZapImport * pImport = m_pZapImage->GetImportTable()->GetExistingMethodHandleImport(CORINFO_METHOD_HANDLE(pMD));
-    return (pImport != NULL && pImport->IsPlaced()) ? pImport : NULL;
-}
-
-ZapNode * DataImage::GetExistingFieldHandleImport(FieldDesc * pFD)
-{
-    ZapImport * pImport = m_pZapImage->GetImportTable()->GetExistingFieldHandleImport(CORINFO_FIELD_HANDLE(pFD));
-    return (pImport != NULL && pImport->IsPlaced()) ? pImport : NULL;
-}
-
-ZapNode * DataImage::GetVirtualImportThunk(MethodTable * pMT, MethodDesc * pMD, int slotNumber)
-{
-    _ASSERTE(pMD == pMT->GetMethodDescForSlot(slotNumber));
-    _ASSERTE(!pMD->IsGenericMethodDefinition());
-
-    ZapImport * pImport = m_pZapImage->GetImportTable()->GetVirtualImportThunk(CORINFO_METHOD_HANDLE(pMD), slotNumber);
-    if (!pImport->IsPlaced())
-        m_pZapImage->GetImportTable()->PlaceVirtualImportThunk(pImport);
-    return pImport;
-}
-
-ZapNode * DataImage::GetGenericSignature(PVOID signature, BOOL fMethod)
-{
-    ZapGenericSignature * pGenericSignature = m_pZapImage->GetImportTable()->GetGenericSignature(signature, fMethod);
-    if (!pGenericSignature->IsPlaced())
-        m_pZapImage->GetImportTable()->PlaceBlob(pGenericSignature);
-    return pGenericSignature;
-}
-
-#if defined(TARGET_X86) || defined(TARGET_AMD64)
-
-class ZapStubPrecode : public ZapNode
-{
-protected:
-    MethodDesc * m_pMD;
-    DataImage::ItemKind m_kind;
-
-public:
-    ZapStubPrecode(MethodDesc * pMethod, DataImage::ItemKind kind)
-        : m_pMD(pMethod), m_kind(kind)
-    {
-    }
-
-    virtual DWORD GetSize()
-    {
-        return sizeof(StubPrecode);
-    }
-
-    virtual UINT GetAlignment()
-    {
-        return PRECODE_ALIGNMENT;
-    }
-
-    virtual ZapNodeType GetType()
-    {
-        return NodeTypeForItemKind(m_kind);
-    }
-
-    virtual DWORD ComputeRVA(ZapWriter * pZapWriter, DWORD dwPos)
-    {
-        dwPos = AlignUp(dwPos, GetAlignment());
-
-        // Alignment for straddlers. Need a cast to help gcc choose between AlignmentTrim(UINT,UINT) and (UINT64,UINT).
-        if (AlignmentTrim(static_cast<UINT>(dwPos + offsetof(StubPrecode, m_pMethodDesc)), RELOCATION_PAGE_SIZE) > RELOCATION_PAGE_SIZE - sizeof(TADDR))
-            dwPos += GetAlignment();
-
-        SetRVA(dwPos);
-
-        dwPos += GetSize();
-
-        return dwPos;
-    }
-
-    virtual void Save(ZapWriter * pZapWriter)
-    {
-        ZapImage * pImage = ZapImage::GetImage(pZapWriter);
-
-        StubPrecode precode;
-
-        precode.Init(&precode, m_pMD);
-
-        SSIZE_T offset;
-        ZapNode * pNode = pImage->m_pDataImage->GetNodeForStructure(m_pMD, &offset);
-        pImage->WriteReloc(&precode, offsetof(StubPrecode, m_pMethodDesc),
-            pNode, (int)offset, IMAGE_REL_BASED_PTR);
-
-        pImage->WriteReloc(&precode, offsetof(StubPrecode, m_rel32),
-            pImage->GetHelperThunk(CORINFO_HELP_EE_PRESTUB), 0, IMAGE_REL_BASED_REL32);
-
-        pZapWriter->Write(&precode, sizeof(precode));
-    }
-};
-
-#ifdef HAS_NDIRECT_IMPORT_PRECODE
-class ZapNDirectImportPrecode : public ZapStubPrecode
-{
-public:
-    ZapNDirectImportPrecode(MethodDesc * pMD, DataImage::ItemKind kind)
-        : ZapStubPrecode(pMD, kind)
-    {
-    }
-
-    virtual void Save(ZapWriter * pZapWriter)
-    {
-        ZapImage * pImage = ZapImage::GetImage(pZapWriter);
-
-        StubPrecode precode;
-
-        precode.Init(&precode, m_pMD);
-
-        SSIZE_T offset;
-        ZapNode * pNode = pImage->m_pDataImage->GetNodeForStructure(m_pMD, &offset);
-        pImage->WriteReloc(&precode, offsetof(StubPrecode, m_pMethodDesc),
-            pNode, (int)offset, IMAGE_REL_BASED_PTR);
-
-        pImage->WriteReloc(&precode, offsetof(StubPrecode, m_rel32),
-            pImage->GetHelperThunk(CORINFO_HELP_EE_PINVOKE_FIXUP), 0, IMAGE_REL_BASED_REL32);
-
-        pZapWriter->Write(&precode, sizeof(precode));
-    }
-};
-#endif // HAS_NDIRECT_IMPORT_PRECODE
-
-void DataImage::SavePrecode(PVOID ptr, MethodDesc * pMD, PrecodeType t, ItemKind kind, BOOL fIsPrebound)
-{
-    ZapNode * pNode = NULL;
-
-    switch (t) {
-    case PRECODE_STUB:
-        pNode = new (GetHeap()) ZapStubPrecode(pMD, kind);
-        GetHelperThunk(CORINFO_HELP_EE_PRESTUB);
-        break;
-
-#ifdef HAS_NDIRECT_IMPORT_PRECODE
-    case PRECODE_NDIRECT_IMPORT:
-        pNode = new (GetHeap()) ZapNDirectImportPrecode(pMD, kind);
-        GetHelperThunk(CORINFO_HELP_EE_PINVOKE_FIXUP);
-        break;
-#endif // HAS_NDIRECT_IMPORT_PRECODE
-
-    default:
-        _ASSERTE(!"Unexpected precode type");
-        break;
-    }
-
-    BindPointer(ptr, pNode, 0);
-
-    AddStructureInOrder(pNode);
-}
-
-#endif // TARGET_X86 || TARGET_AMD64
-
-void DataImage::FixupModulePointer(Module * pModule, PVOID p, SSIZE_T offset, ZapRelocationType type)
-{
-    STANDARD_VM_CONTRACT;
-
-    if (pModule != NULL)
-    {
-        if (CanEagerBindToModule(pModule) && CanHardBindToZapModule(pModule))
-        {
-            FixupField(p, offset, pModule, 0, type);
-        }
-        else
-        {
-            ZapNode * pImport = GetModuleHandleImport(pModule);
-            FixupFieldToNode(p, offset, pImport, FIXUP_POINTER_INDIRECTION, type);
-        }
-    }
-}
-
-void DataImage::FixupMethodTablePointer(MethodTable * pMT, PVOID p, SSIZE_T offset, ZapRelocationType type)
-{
-    STANDARD_VM_CONTRACT;
-
-    if (pMT != NULL)
-    {
-        if (CanEagerBindToMethodTable(pMT) && CanHardBindToZapModule(pMT->GetLoaderModule()))
-        {
-            FixupField(p, offset, pMT, 0, type);
-        }
-        else
-        {
-            ZapNode * pImport = GetTypeHandleImport(pMT);
-            FixupFieldToNode(p, offset, pImport, FIXUP_POINTER_INDIRECTION, type);
-        }
-    }
-}
-
-void DataImage::FixupTypeHandlePointer(TypeHandle th, PVOID p, SSIZE_T offset, ZapRelocationType type)
-{
-    STANDARD_VM_CONTRACT;
-
-    if (!th.IsNull())
-    {
-        if (th.IsTypeDesc())
-        {
-            if (CanEagerBindToTypeHandle(th) && CanHardBindToZapModule(th.GetLoaderModule()))
-            {
-                FixupField(p, offset, th.AsTypeDesc(), 2, type);
-            }
-            else
-            {
-                ZapNode * pImport = GetTypeHandleImport(th);
-                FixupFieldToNode(p, offset, pImport, FIXUP_POINTER_INDIRECTION, type);
-            }
-        }
-        else
-        {
-            MethodTable * pMT = th.AsMethodTable();
-            FixupMethodTablePointer(pMT, p, offset, type);
-        }
-    }
-}
-
-void DataImage::FixupMethodDescPointer(MethodDesc * pMD, PVOID p, SSIZE_T offset, ZapRelocationType type /*=IMAGE_REL_BASED_PTR*/)
-{
-    STANDARD_VM_CONTRACT;
-
-    if (pMD != NULL)
-    {
-        if (CanEagerBindToMethodDesc(pMD) && CanHardBindToZapModule(pMD->GetLoaderModule()))
-        {
-            FixupField(p, offset, pMD, 0, type);
-        }
-        else
-        {
-            ZapNode * pImport = GetMethodHandleImport(pMD);
-            FixupFieldToNode(p, offset, pImport, FIXUP_POINTER_INDIRECTION, type);
-        }
-    }
-}
-
-void DataImage::FixupFieldDescPointer(FieldDesc * pFD, PVOID p, SSIZE_T offset, ZapRelocationType type /*=IMAGE_REL_BASED_PTR*/)
-{
-    STANDARD_VM_CONTRACT;
-
-    if (pFD != NULL)
-    {
-        if (CanEagerBindToFieldDesc(pFD) && CanHardBindToZapModule(pFD->GetLoaderModule()))
-        {
-            FixupField(p, offset, pFD, 0, type);
-        }
-        else
-        {
-            ZapNode * pImport = GetFieldHandleImport(pFD);
-            FixupFieldToNode(p, offset, pImport, FIXUP_POINTER_INDIRECTION, type);
-        }
-    }
-}
-
-void DataImage::FixupMethodTablePointer(PVOID p, FixupPointer<PTR_MethodTable> * ppMT)
-{
-    FixupMethodTablePointer(ppMT->GetValue(), p, (BYTE *)ppMT - (BYTE *)p, IMAGE_REL_BASED_PTR);
-}
-void DataImage::FixupTypeHandlePointer(PVOID p, FixupPointer<TypeHandle> * pth)
-{
-    FixupTypeHandlePointer(pth->GetValue(), p, (BYTE *)pth - (BYTE *)p, IMAGE_REL_BASED_PTR);
-}
-void DataImage::FixupMethodDescPointer(PVOID p, FixupPointer<PTR_MethodDesc> * ppMD)
-{
-    FixupMethodDescPointer(ppMD->GetValue(), p, (BYTE *)ppMD - (BYTE *)p, IMAGE_REL_BASED_PTR);
-}
-void DataImage::FixupFieldDescPointer(PVOID p, FixupPointer<PTR_FieldDesc> * ppFD)
-{
-    FixupFieldDescPointer(ppFD->GetValue(), p, (BYTE *)ppFD - (BYTE *)p, IMAGE_REL_BASED_PTR);
-}
-
-void DataImage::FixupModulePointer(PVOID p, RelativeFixupPointer<PTR_Module> * ppModule)
-{
-    FixupModulePointer(ppModule->GetValueMaybeNull(), p, (BYTE *)ppModule - (BYTE *)p, IMAGE_REL_BASED_RELPTR);
-}
-void DataImage::FixupMethodTablePointer(PVOID p, RelativeFixupPointer<PTR_MethodTable> * ppMT)
-{
-    FixupMethodTablePointer(ppMT->GetValueMaybeNull(), p, (BYTE *)ppMT - (BYTE *)p, IMAGE_REL_BASED_RELPTR);
-}
-void DataImage::FixupTypeHandlePointer(PVOID p, RelativeFixupPointer<TypeHandle> * pth)
-{
-    FixupTypeHandlePointer(pth->GetValueMaybeNull(), p, (BYTE *)pth - (BYTE *)p, IMAGE_REL_BASED_RELPTR);
-}
-void DataImage::FixupMethodDescPointer(PVOID p, RelativeFixupPointer<PTR_MethodDesc> * ppMD)
-{
-    FixupMethodDescPointer(ppMD->GetValueMaybeNull(), p, (BYTE *)ppMD - (BYTE *)p, IMAGE_REL_BASED_RELPTR);
-}
-void DataImage::FixupFieldDescPointer(PVOID p, RelativeFixupPointer<PTR_FieldDesc> * ppFD)
-{
-    FixupFieldDescPointer(ppFD->GetValueMaybeNull(), p, (BYTE *)ppFD - (BYTE *)p, IMAGE_REL_BASED_RELPTR);
-}
-
-BOOL DataImage::CanHardBindToZapModule(Module *targetModule)
-{
-    STANDARD_VM_CONTRACT;
-
-    _ASSERTE(targetModule == m_module || targetModule->HasNativeImage());
-    return targetModule == m_module;
-}
-
-BOOL DataImage::CanEagerBindToTypeHandle(TypeHandle th, BOOL fRequirePrerestore, TypeHandleList *pVisited)
-{
-    STANDARD_VM_CONTRACT;
-
-    Module * pLoaderModule = th.GetLoaderModule();
-
-    BOOL fCanEagerBind;
-
-    if (th.IsTypeDesc())
-    {
-        fCanEagerBind = CanEagerBindTo(pLoaderModule, Module::GetPreferredZapModuleForTypeDesc(th.AsTypeDesc()), th.AsTypeDesc());
-    }
-    else
-    {
-        fCanEagerBind = CanEagerBindTo(pLoaderModule, Module::GetPreferredZapModuleForMethodTable(th.AsMethodTable()), th.AsMethodTable());
-    }
-
-    if (GetModule() != th.GetLoaderModule())
-    {
-        if (th.IsTypeDesc())
-        {
-            return FALSE;
-        }
-
-        // As a performance optimization, don't eager bind to arrays.  They are currently very expensive to
-        // fixup so we want to do it lazily.
-
-        if (th.AsMethodTable()->IsArray())
-        {
-            return FALSE;
-        }
-
-        // For correctness in the face of targeted patching, do not eager bind to any instantiation
-        // in the target module that might go away.
-        if (!th.IsTypicalTypeDefinition() &&
-            !Module::IsAlwaysSavedInPreferredZapModule(th.GetInstantiation(),
-                                                       Instantiation()))
-        {
-            return FALSE;
-        }
-
-        // #DoNotEagerBindToTypesThatNeedRestore
-        //
-        // It is important to avoid eager binding to structures that require restore.  The code here stops
-        // this from happening for cross-module fixups.  For intra-module cases, eager fixups are allowed to
-        // (and often do) target types that require restore, even though this is generally prone to all of
-        // the same problems described below.  Correctness is preserved only because intra-module eager
-        // fixups are ignored in Module::RunEagerFixups (so their semantics are very close to normal
-        // non-eager fixups).
-        //
-        // For performance, this is the most costly type of eager fixup (and may require otherwise-unneeded
-        // assemblies to be loaded) and has the lowest benefit, since it does not avoid the need for the
-        // referencing type to require restore.
-        //
-        // More importantly, this kind of fixup can compromise correctness by causing type loads to occur
-        // during eager fixup resolution.  The system is not designed to cope with this and a variety of
-        // subtle failures can occur when it happens.  As an example, consider a scenario involving the
-        // following assemblies and types:
-        //    o A1: softbinds to A2, contains "class A1!Level2 extends A2!Level1"
-        //    o A2: hardbinds to A3, contains "class A2!Level1 extends Object", contains methods that use A3!Level3.
-        //    o A3: softbinds to A1, contains "class A3!Level3 extends A1!Level2"
-        //
-        // If eager fixups are allowed to target types that need restore, then it's possible for A2 to end
-        // up with an eager fixup targeting A3!Level3, setting up this sequence:
-        //    1 Type load starts for A1!Level2.
-        //    2 Loading base class A2!Level1 triggers assembly load for A2.
-        //    3 Loading A2 involves synchronously resolving its eager fixups, including the fixup to A3!Level3.
-        //    4 A3!Level3 needs restore, so type load starts for A3!Level3.
-        //    5 Loading A3!Level3 requires loading base class A1!Level2.
-        //    6 A1!Level2 is already being loaded on this thread (in #1 above), so type load fails.
-        //    7 Since eager fixup resolution failed, FileLoadException is thrown for A2.
-        fRequirePrerestore = TRUE;
-    }
-
-    if (fCanEagerBind && fRequirePrerestore)
-    {
-        fCanEagerBind = !th.ComputeNeedsRestore(this, pVisited);
-    }
-
-    return fCanEagerBind;
-}
-
-BOOL DataImage::CanEagerBindToMethodTable(MethodTable *pMT, BOOL fRequirePrerestore, TypeHandleList *pVisited)
-{
-    WRAPPER_NO_CONTRACT;
-
-    TypeHandle th =  TypeHandle(pMT);
-    return DataImage::CanEagerBindToTypeHandle(th, fRequirePrerestore, pVisited);
-}
-
-BOOL DataImage::CanEagerBindToMethodDesc(MethodDesc *pMD, BOOL fRequirePrerestore, TypeHandleList *pVisited)
-{
-    STANDARD_VM_CONTRACT;
-
-    BOOL fCanEagerBind = CanEagerBindTo(pMD->GetLoaderModule(), Module::GetPreferredZapModuleForMethodDesc(pMD), pMD);
-
-    // Performance optimization -- see comment in CanEagerBindToTypeHandle
-    if (GetModule() != pMD->GetLoaderModule())
-    {
-        // For correctness in the face of targeted patching, do not eager bind to any instantiation
-        // in the target module that might go away.
-        if (!pMD->IsTypicalMethodDefinition() &&
-            !Module::IsAlwaysSavedInPreferredZapModule(pMD->GetClassInstantiation(),
-                                                       pMD->GetMethodInstantiation()))
-        {
-            return FALSE;
-        }
-
-        fRequirePrerestore = TRUE;
-    }
-
-    if (fCanEagerBind && fRequirePrerestore)
-    {
-        fCanEagerBind = !pMD->ComputeNeedsRestore(this, pVisited);
-    }
-
-    return fCanEagerBind;
-}
-
-BOOL DataImage::CanEagerBindToFieldDesc(FieldDesc *pFD, BOOL fRequirePrerestore, TypeHandleList *pVisited)
-{
-    STANDARD_VM_CONTRACT;
-
-    if (!CanEagerBindTo(pFD->GetLoaderModule(), Module::GetPreferredZapModuleForFieldDesc(pFD), pFD))
-        return FALSE;
-
-    MethodTable * pMT = pFD->GetApproxEnclosingMethodTable();
-
-    return CanEagerBindToMethodTable(pMT, fRequirePrerestore, pVisited);
-}
-
-BOOL DataImage::CanEagerBindToModule(Module *pModule)
-{
-    STANDARD_VM_CONTRACT;
-
-    return GetAppDomain()->ToCompilationDomain()->CanEagerBindToZapFile(pModule);
-}
-
-// "address" is a data-structure belonging to pTargetModule.
-// This function returns whether the Module currently being ngenned can
-// hardbind "address"
-/* static */
-BOOL DataImage::CanEagerBindTo(Module *pTargetModule, Module *pPreferredZapModule, void *address)
-{
-    STANDARD_VM_CONTRACT;
-
-    if (pTargetModule != pPreferredZapModule)
-        return FALSE;
-
-    if (GetModule() == pTargetModule)
-        return TRUE;
-
-    BOOL eagerBindToZap = GetAppDomain()->ToCompilationDomain()->CanEagerBindToZapFile(pTargetModule);
-    BOOL isPersisted    = pTargetModule->IsPersistedObject(address);
-
-    return eagerBindToZap && isPersisted;
-}
-
-BOOL DataImage::CanPrerestoreEagerBindToTypeHandle(TypeHandle th, TypeHandleList *pVisited)
-{
-    WRAPPER_NO_CONTRACT;
-    return CanEagerBindToTypeHandle(th, TRUE, pVisited);
-}
-
-BOOL DataImage::CanPrerestoreEagerBindToMethodTable(MethodTable *pMT, TypeHandleList *pVisited)
-{
-    WRAPPER_NO_CONTRACT;
-    return CanEagerBindToMethodTable(pMT, TRUE, pVisited);
-}
-
-BOOL DataImage::CanPrerestoreEagerBindToMethodDesc(MethodDesc *pMD, TypeHandleList *pVisited)
-{
-    WRAPPER_NO_CONTRACT;
-    return CanEagerBindToMethodDesc(pMD, TRUE, pVisited);
-}
-
-
-void DataImage::HardBindTypeHandlePointer(PVOID p, SSIZE_T offset)
-{
-    CONTRACTL
-    {
-        STANDARD_VM_CHECK;
-        PRECONDITION(CanEagerBindToTypeHandle(*(TypeHandle UNALIGNED*)((BYTE *)p + offset)));
-    }
-    CONTRACTL_END;
-
-    TypeHandle thCopy = *(TypeHandle UNALIGNED*)((BYTE *)p + offset);
-
-    if (!thCopy.IsNull())
-    {
-        if (thCopy.IsTypeDesc())
-        {
-            FixupField(p, offset, thCopy.AsTypeDesc(), 2);
-        }
-        else
-        {
-            FixupField(p, offset, thCopy.AsMethodTable());
-        }
-    }
-}
-
-
-    // This is obsolete in-place fixup that we should get rid of. For now, it is used for:
-    // - FnPtrTypeDescs. These should not be stored in NGen images at all.
-    // - stubs-as-il signatures. These should use tokens when stored in NGen image.
-    //
-void DataImage::FixupTypeHandlePointerInPlace(PVOID p, SSIZE_T offset, BOOL fForceFixup /*=FALSE*/)
-{
-    STANDARD_VM_CONTRACT;
-
-    TypeHandle thCopy = *(TypeHandle UNALIGNED*)((BYTE *)p + offset);
-
-    if (!thCopy.IsNull())
-    {
-        if (!fForceFixup &&
-            CanEagerBindToTypeHandle(thCopy) &&
-            CanHardBindToZapModule(thCopy.GetLoaderModule()))
-        {
-            HardBindTypeHandlePointer(p, offset);
-        }
-        else
-        {
-            ZapImport * pImport = m_pZapImage->GetImportTable()->GetClassHandleImport((CORINFO_CLASS_HANDLE)thCopy.AsPtr());
-
-            ZapNode * pBlob = m_pZapImage->GetImportTable()->PlaceImportBlob(pImport);
-            FixupFieldToNode(p, offset, pBlob, 0, IMAGE_REL_BASED_ABSOLUTE_TAGGED);
-        }
-    }
-}
-
-void DataImage::BeginRegion(CorInfoRegionKind regionKind)
-{
-    STANDARD_VM_CONTRACT;
-
-    m_pZapImage->BeginRegion(regionKind);
-}
-
-void DataImage::EndRegion(CorInfoRegionKind regionKind)
-{
-    STANDARD_VM_CONTRACT;
-
-    m_pZapImage->EndRegion(regionKind);
-}
-
-void DataImage::ReportInlining(CORINFO_METHOD_HANDLE inliner, CORINFO_METHOD_HANDLE inlinee)
-{
-    STANDARD_VM_CONTRACT;
-    _ASSERTE(m_inlineTrackingMap);
-    m_inlineTrackingMap->AddInlining(GetMethod(inliner), GetMethod(inlinee));
-}
-
-InlineTrackingMap * DataImage::GetInlineTrackingMap()
-{
-    LIMITED_METHOD_DAC_CONTRACT;
-    return m_inlineTrackingMap;
-}
-
-//
-// Compressed LookupMap Support
-//
-// See the large comment near the top of ceeload.h for a much more detailed discussion of this.
-//
-// Basically we support a specialized node, ZapCompressedLookupMap, which knows how to compress the array of
-// intra-module pointers present in certain types of LookupMap.
-//
-
-// A simple class to write a sequential sequence of variable sized bit-fields into a pre-allocated buffer. I
-// was going to use the version defined by GcInfoEncoder (the reader side in ceeload.cpp uses GcInfoDecoder's
-// BitStreamReader) but unfortunately the code is not currently factored to make this easy and the resources
-// were not available to perform a non-trivial refactorization of the code. In any event the writer is fairly
-// trivial and doesn't represent a huge duplication of effort.
-// The class requires that the input buffer is DWORD-aligned and sized (it uses a DWORD cache and always
-// writes data to the buffer in DWORD-sized chunks).
-class BitStreamWriter
-{
-public:
-    // Initialize a writer and point it at the start of a pre-allocated buffer (large enough to accomodate all
-    // future writes). The buffer must be DWORD-aligned (we use this for some performance optimization).
-    BitStreamWriter(DWORD *pStart)
-    {
-        LIMITED_METHOD_CONTRACT;
-
-        // Buffer must be DWORD-aligned.
-        _ASSERTE(((TADDR)pStart & 0x3) == 0);
-
-        m_pNext = pStart;   // Point at the start of the buffer
-        m_dwCurrent = 0;    // We don't have any cached data waiting to write
-        m_cCurrentBits = 0; // Ditto
-        m_cBitsWritten = 0; // We haven't written any bits
-    }
-
-    // Write the low-order cBits of dwData to the stream.
-    void Write(DWORD dwData, DWORD cBits)
-    {
-        LIMITED_METHOD_CONTRACT;
-
-        // We can only write between 1 and 32 bits of data at a time.
-        _ASSERTE(cBits > 0 && cBits <= kBitsPerDWORD);
-
-        // Check that none of the unused high-order bits of dwData have stale data in them (we can use this to
-        // optimize paths below). Use two conditions here because << of 32-bits or more (on x86) doesn't
-        // do what you might expect (the RHS is modulo 32 so "<< 32" is a no-op rather than zero-ing the
-        // result).
-        _ASSERTE((cBits == kBitsPerDWORD) || ((dwData & ((1U << cBits) - 1)) == dwData));
-
-        // Record the input bits as written (we can't fail and we have multiple exit paths below so it's
-        // convenient to update our counter here).
-        m_cBitsWritten += cBits;
-
-        // We cache up to a DWORD of data to be written to the stream and only write back to the buffer when
-        // we have a full DWORD. Calculate how many bits of the input we're going to write first (either the
-        // rest of the input or the remaining bits of space in the current DWORD cache, whichever is smaller).
-        DWORD cInitialBits = min(cBits, kBitsPerDWORD - m_cCurrentBits);
-        if (cInitialBits == kBitsPerDWORD)
-        {
-            // Deal with this special case (we're writing all the input, an entire DWORD all at once) since it
-            // ensures that none of the << operations below have to deal with a LHS that == 32 (see the <<
-            // comment in one of the asserts above for why this matters).
-
-            // Because of the calculations above we should only come here if our DWORD cache was empty and the
-            // caller is trying to write a full DWORD (which simplifies many things).
-            _ASSERTE(m_dwCurrent == 0 && m_cCurrentBits == 0 && cBits == kBitsPerDWORD);
-
-            *m_pNext++ = dwData;    // Write a full DWORD directly from the input
-
-            // That's it, there's no more data to write and the only state update to the write was advancing
-            // the buffer pointer (cache DWORD is already in the correct state, see asserts above).
-            return;
-        }
-
-        // Calculate a mask of the low-order bits we're going to extract from the input data.
-        DWORD dwInitialMask = (1U << cInitialBits) - 1;
-
-        // OR those bits into the cache (properly shifted to fit above the data already there).
-        m_dwCurrent |= (dwData & dwInitialMask) << m_cCurrentBits;
-
-        // Update the cache bit counter for the new data.
-        m_cCurrentBits += cInitialBits;
-        if (m_cCurrentBits == kBitsPerDWORD)
-        {
-            // The cache filled up. Write the DWORD to the buffer and reset the cache state to empty.
-            *m_pNext++ = m_dwCurrent;
-            m_dwCurrent = 0;
-            m_cCurrentBits = 0;
-        }
-
-        // If the bits we just inserted comprised all the input bits we're done.
-        if (cInitialBits == cBits)
-            return;
-
-        // There's more data to write. But we can only get here if we just flushed the cache. So there is a
-        // whole DWORD free in the cache and we're guaranteed to have less than a DWORD of data left to write.
-        // As a result we can simply populate the low-order bits of the cache with our remaining data (simply
-        // shift down by the number of bits we've already written) and we're done.
-        _ASSERTE(m_dwCurrent == 0 && m_cCurrentBits == 0);
-        m_dwCurrent = dwData >>= cInitialBits;
-        m_cCurrentBits = cBits - cInitialBits;
-    }
-
-    // Because we cache a DWORD of data before writing it it's possible that there are still unwritten bits
-    // left in the cache once you've finished writing data. Call this operation after all Writes() are
-    // completed to flush any such data to memory. It's not legal to call Write() again after a Flush().
-    void Flush()
-    {
-        LIMITED_METHOD_CONTRACT;
-
-        // Nothing to do if the cache is empty.
-        if (m_cCurrentBits == 0)
-            return;
-
-        // Write what we have to memory (unused high-order bits will be zero).
-        *m_pNext = m_dwCurrent;
-
-        // Catch any attempt to make a further Write() call.
-        m_pNext = NULL;
-    }
-
-    // Get the count of bits written so far (logically, this number does not take caching into account).
-    DWORD GetBitsWritten()
-    {
-        LIMITED_METHOD_CONTRACT;
-
-        return m_cBitsWritten;
-    }
-
-private:
-    enum { kBitsPerDWORD = sizeof(DWORD) * 8 };
-
-    DWORD  *m_pNext;        // Pointer to the next DWORD that will be written in the buffer
-    DWORD   m_dwCurrent;    // We cache up to a DWORD of data before writing it to the buffer
-    DWORD   m_cCurrentBits; // Count of valid (low-order) bits in the buffer above
-    DWORD   m_cBitsWritten; // Count of bits given to Write() (ignores caching)
-};
-
-// A specialized node used to write the compressed portions of a LookupMap to an ngen image. This is
-// (optionally) allocated by a call to DataImage::StoreCompressedLayoutMap from LookupMapBase::Save() and
-// handles allocation and initialization of the compressed table and an index used to navigate the table
-// efficiently. The allocation of the map itself and any hot item list is still handled externally but this
-// node will perform any fixups in the base map required to refer to the new compressed data.
-//
-// Since the compression algorithm used depends on the precise values of the RVAs referenced by the LookupMap
-// the compression doesn't happen until ComputeRVA is called (don't call GetSize() until after ComputeRVA()
-// returns). Additionally we must ensure that this node's ComputeRVA() is not called until after that of every
-// node on those RVA it depends. Currently this is ensured by placing this node near the end of the .text
-// section (after pointers to any read-only data structures referenced by LookupMaps and after the .data
-// section containing writeable structures).
-class ZapCompressedLookupMap : public ZapNode
-{
-    DataImage      *m_pImage;                                       // Back pointer to the allocating DataImage
-    LookupMapBase  *m_pMap;                                         // Back pointer to the LookupMap we're compressing
-    BYTE           *m_pTable;                                       // ComputeRVA allocates a compressed table here
-    BYTE           *m_pIndex;                                       // ComputeRVA allocates a table index here
-    DWORD           m_cbTable;                                      // Size (in bytes) of the table above (after ComputeRVA)
-    DWORD           m_cbIndex;                                      // Size (in bytes) of the index above (after ComputeRVA)
-    DWORD           m_cBitsPerIndexEntry;                           // Number of bits in each index entry
-    DWORD           m_rgHistogram[kBitsPerRVA];                     // Table of frequencies of different delta lengths
-    BYTE            m_rgEncodingLengths[kLookupMapLengthEntries];   // Table of different bit lengths value deltas can take
-    BYTE            m_eKind;                                        // Item kind (DataImage::ITEM_COMPRESSED_MAP currently)
-
-public:
-    ZapCompressedLookupMap(DataImage *pImage, LookupMapBase *pMap, BYTE eKind)
-        : m_pImage(pImage), m_pMap(pMap), m_eKind(eKind)
-    {
-        LIMITED_METHOD_CONTRACT;
-    }
-
-    DataImage::ItemKind GetKind()
-    {
-        LIMITED_METHOD_CONTRACT;
-
-        return (DataImage::ItemKind)m_eKind;
-    }
-
-    virtual DWORD GetSize()
-    {
-        LIMITED_METHOD_CONTRACT;
-
-        if (!ShouldCompressedMapBeSaved())
-            return 0;
-
-        // This isn't legal until ComputeRVA() is called. Check this by seeing if the compressed version of
-        // the table is allocated yet.
-        _ASSERTE(m_pTable != NULL);
-        return m_cbIndex + m_cbTable;
-    }
-
-    virtual UINT GetAlignment()
-    {
-        LIMITED_METHOD_CONTRACT;
-
-        if (!ShouldCompressedMapBeSaved())
-            return 1;
-
-        // The table and index have no pointers but do require DWORD alignment.
-        return sizeof(DWORD);
-    }
-
-    virtual ZapNodeType GetType()
-    {
-        STANDARD_VM_CONTRACT;
-
-        return NodeTypeForItemKind(m_eKind);
-    }
-
-    virtual DWORD ComputeRVA(ZapWriter *pZapWriter, DWORD dwPos)
-    {
-        STANDARD_VM_CONTRACT;
-
-        if (ShouldCompressedMapBeSaved())
-        {
-
-            // This is the earliest opportunity at which all data is available in order to compress the table. In
-            // particular all values in the table (currently MethodTable* or MethodDesc*) point to structures
-            // which have been assigned final RVAs in the image. We can thus compute a compressed table value that
-            // relies on the relationship between these RVAs.
-
-            // Phase 1: Look through all the entries in the table. Look at the deltas between RVAs for adjacent
-            // items and build a histogram of how many entries require a specific number to encode their delta
-            // (using a scheme we we discard non-significant low and high-order zero bits). This call will
-            // initialize m_rgHistogram so that entry 0 contains the number of entries that require 1 bit to
-            // encode their delta, entry 1 the count of those that require 2 bits etc. up to the last entry (how
-            // many entries require the full 32 bits). Note that even on 64-bit platforms we only currently
-            // support 32-bit RVAs.
-            DWORD cRids = AnalyzeTable();
-
-            // Phase 2: Given the histogram above, calculate the set of delta lengths for the encoding table
-            // (m_rgEncodingLengths) that will result in optimal table size. We have a fixed size encoding length
-            // so we don't have to embed a large fixed-size length field for every compressed entry but we can
-            // still cope with the relatively rare but ever-present worst case entries which require many bits of
-            // delta entry.
-            OptimizeEncodingLengths();
-
-            // Phase 3: We now have enough data to allocate the final data structures (the compressed table itself
-            // and an index that bookmarks every kLookupMapIndexStride'th entry). Both structures must start
-            // DWORD-aligned and have a DWORD-aligned size (requirements of BitStreamWriter).
-
-            // PredictCompressedSize() returns its result in bits so we must convert (rounding up) to bytes before
-            // DWORD aligning.
-            m_cbTable = AlignUp((PredictCompressedSize(m_rgEncodingLengths) + 7) / 8, sizeof(DWORD));
-
-            // Each index entry contains a bit offset into the compressed stream (so we must size for the worst
-            // case of an offset at the end of the stream) plus an RVA.
-            m_cBitsPerIndexEntry = BitsRequired(m_cbTable * 8) + kBitsPerRVA;
-            _ASSERTE(m_cBitsPerIndexEntry > 0);
-
-            // Our first index entry is for entry 0 (rather than entry kLookupMapIndexStride) so we must be
-            // sure to round up the number of index entries we need in order to cover the table.
-            DWORD cIndexEntries = (cRids + (kLookupMapIndexStride - 1)) / kLookupMapIndexStride;
-
-            // Since we calculate the index size in bits we need to round up to bytes before DWORD aligning.
-            m_cbIndex = AlignUp(((m_cBitsPerIndexEntry * cIndexEntries) + 7) / 8, sizeof(DWORD));
-
-            // Allocate both table and index from a single chunk of memory.
-            BYTE *pMemory = new BYTE[m_cbIndex + m_cbTable];
-            m_pTable = pMemory;
-            m_pIndex = pMemory + m_cbTable;
-
-            // Phase 4: We've now calculated all the input data we need and allocated memory for the output so we
-            // can go ahead and fill in the compressed table and index.
-            InitializeTableAndIndex();
-
-            // Phase 5: Go back up update the saved version of the LookupMap (redirect the table pointer to the
-            // compressed table and fill in the other fields which aren't valid until the table is compressed).
-            LookupMapBase *pSaveMap = (LookupMapBase*)m_pImage->GetImagePointer(m_pMap);
-            pSaveMap->pTable = (TADDR*)m_pTable;
-            pSaveMap->pIndex = m_pIndex;
-            pSaveMap->cIndexEntryBits = m_cBitsPerIndexEntry;
-            pSaveMap->cbTable = m_cbTable;
-            pSaveMap->cbIndex = m_cbIndex;
-            memcpy(pSaveMap->rgEncodingLengths, m_rgEncodingLengths, sizeof(m_rgEncodingLengths));
-
-            // Schedule fixups for the map pointers to the compressed table and index.
-            m_pImage->FixupFieldToNode(m_pMap, offsetof(LookupMapBase, pTable), this, 0);
-            m_pImage->FixupFieldToNode(m_pMap, offsetof(LookupMapBase, pIndex), this, m_cbTable);
-        }
-
-        // We're done with generating the compressed table. Now we need to do the work ComputeRVA() is meant
-        // to do:
-        dwPos = AlignUp(dwPos, GetAlignment()); // Satisfy our alignment requirements
-        SetRVA(dwPos);                          // Set the RVA of the node (both table and index)
-        dwPos += GetSize();                     // Advance the RVA past our node
-
-        return dwPos;
-    }
-
-    virtual void Save(ZapWriter *pZapWriter)
-    {
-        STANDARD_VM_CONTRACT;
-
-        if (!ShouldCompressedMapBeSaved())
-            return;
-
-        // Save both the table and index.
-        pZapWriter->Write(m_pTable, m_cbTable);
-        pZapWriter->Write(m_pIndex, m_cbIndex);
-    }
-
-private:
-
-    // It's possible that our node has been created and only later the decision is made to store the full
-    // uncompressed table.  In this case, we want to early out of our work and make saving our node a no-op.
-    BOOL ShouldCompressedMapBeSaved()
-    {
-        LIMITED_METHOD_CONTRACT;
-
-        // To identify whether compression is desired, use the flag from LookupMapBase::Save
-        return (m_pMap->cIndexEntryBits > 0);
-    }
-
-    // Phase 1: Look through all the entries in the table. Look at the deltas between RVAs for adjacent items
-    // and build a histogram of how many entries require a specific number to encode their delta (using a
-    // scheme we we discard non-significant low and high-order zero bits). This call will initialize
-    // m_rgHistogram so that entry 0 contains the number of entries that require 1 bit to encode their delta,
-    // entry 1 the count of those that require 2 bits etc. up to the last entry (how many entries require the
-    // full 32 bits). Note that even on 64-bit platforms we only currently support 32-bit RVAs.
-    DWORD AnalyzeTable()
-    {
-        STANDARD_VM_CONTRACT;
-
-        LookupMapBase *pMap = m_pMap;
-        DWORD dwLastValue = 0;
-        DWORD cRids = 0;
-
-        // Initialize the histogram to all zeroes.
-        memset(m_rgHistogram, 0, sizeof(m_rgHistogram));
-
-        // Walk each node in the map.
-        while (pMap)
-        {
-            // Walk each entry in this node.
-            for (DWORD i = 0; i < pMap->dwCount; i++)
-            {
-                DWORD dwCurrentValue = ComputeElementRVA(pMap, i);
-
-                // Calculate the delta from the last entry. We split the delta into two-components: a bool
-                // indicating whether the RVA was higher or lower and an absolute (non-negative) size. Sort of
-                // like a ones-complement signed number.
-                bool fIncreasingDelta = dwCurrentValue > dwLastValue;
-                DWORD dwDelta = fIncreasingDelta ? (dwCurrentValue - dwLastValue) : (dwLastValue - dwCurrentValue);
-
-                // Determine the minimum number of bits required to represent the delta (by stripping
-                // non-significant leading zeros) and update the count in the histogram of the number of
-                // deltas that required this many bits. We never encode anything with zero bits (only the
-                // value zero would be eligibil and it's not a common value) so the first histogram entry
-                // records the number of deltas encodable with one bit and so on.
-                m_rgHistogram[BitsRequired(dwDelta) - 1]++;
-
-                dwLastValue = dwCurrentValue;
-                cRids++;
-            }
-
-            pMap = pMap->pNext;
-        }
-
-        return cRids;
-    }
-
-    // Phase 2: Given the histogram above, calculate the set of delta lengths for the encoding table
-    // (m_rgEncodingLengths) that will result in optimal table size. We have a fixed size encoding length so
-    // we don't have to embed a large fixed-size length field for every compressed entry but we can still cope
-    // with the relatively rare but ever-present worst case entries which require many bits of delta entry.
-    void OptimizeEncodingLengths()
-    {
-        STANDARD_VM_CONTRACT;
-
-        // Find the longest delta (search from the large end of the histogram down for the first non-zero
-        // entry).
-        BYTE bMaxBits = 0;
-#ifdef _MSC_VER
-#pragma warning(suppress:6293) // Prefast doesn't understand the unsigned modulo-8 arithmetic below.
-#endif
-        for (BYTE i = kBitsPerRVA - 1; i < 0xff; i--)
-            if (m_rgHistogram[i] > 0)
-            {
-                bMaxBits = i + 1;  // +1 because we never encode anything with zero bits.
-                break;
-            }
-        _ASSERTE(bMaxBits >= 1);
-
-        // Now find the smallest delta in a similar fashion.
-        BYTE bMinBits = bMaxBits;
-        for (BYTE i = 0; i < kBitsPerRVA; i++)
-            if (m_rgHistogram[i] > 0)
-            {
-                bMinBits = i + 1;  // +1 because we never encode anything with zero bits.
-                break;
-            }
-        _ASSERTE(bMinBits <= bMaxBits);
-
-        // The encoding lengths table is a sorted list of bit field lengths we can use to encode any
-        // entry-to-entry delta in the compressed table. We go through a table so we can use a small number of
-        // bits in the compressed stream (the table index) to express a very flexible range of deltas. The one
-        // entry we know in advance is the largest (the last). That's because we know we have to be able to
-        // encode the largest delta we found in the table or else we couldn't be functionally correct.
-        m_rgEncodingLengths[kLookupMapLengthEntries - 1] = bMaxBits;
-
-        // Now find optimal values for the other entries one by one. It doesn't really matter which order we
-        // do them in. For each entry we'll loop through all the possible encoding lengths, dwMinBits <=
-        // length < dwMaxBits, setting all the uninitialized entries to the candidate value and calculating
-        // the resulting compressed size of the table. We don't enforce that the candidate sizes get smaller
-        // for each entry so in that if the best use of an extra table entry is to add a larger length rather
-        // than a smaller one then we'll take that. The downside is that we have to sort the table before
-        // calculating the table size (the sizing algorithm is only fast for a sorted table). Luckily our
-        // table is very small (currently 4 entries) and we don't have to sort one of the entries (the last is
-        // always largest) so this isn't such a huge deal.
-        for (DWORD i = 0; i < kLookupMapLengthEntries - 1; i++)
-        {
-            DWORD dwBestSize = 0xffffffff;  // Best overall table size so far
-            BYTE bBestLength = bMaxBits; // The candidate value that lead to the above
-
-            // Iterate over all the values that could generate a good result (no point trying values smaller
-            // than the smallest delta we have or as large as the maximum table entry we've already fixed).
-            for (BYTE j = bMinBits; j < bMaxBits; j++)
-            {
-                // Build a temporary (unsorted) encoding table.
-                BYTE rgTempBuckets[kLookupMapLengthEntries];
-
-                // Entries before the current one are set to the values we've already determined in previous
-                // iterations.
-                for (DWORD k = 0; k < i; k++)
-                    rgTempBuckets[k] = m_rgEncodingLengths[k];
-
-                // The current entry and the remaining uninitialized entries are all set to the current
-                // candidate value (this is logically the equivalent of removing the non-current uninitialized
-                // entries from the table altogether).
-                for (DWORD k = i; k < kLookupMapLengthEntries - 1; k++)
-                    rgTempBuckets[k] = j;
-
-                // The last entry is always the maximum bit length.
-                rgTempBuckets[kLookupMapLengthEntries - 1] = bMaxBits;
-
-                // Sort the temporary table so that the call to PredictCompressedSize() below behaves
-                // correctly (and fast).
-                SortLengthBuckets(rgTempBuckets);
-
-                // See what size of table this would generate.
-                DWORD dwTestSize = PredictCompressedSize(rgTempBuckets);
-                if (dwTestSize < dwBestSize)
-                {
-                    // The result is better than our current best, remember it.
-                    dwBestSize = dwTestSize;
-                    bBestLength = j;
-                }
-            }
-
-            // Set the current entry to the best length we found.
-            m_rgEncodingLengths[i] = bBestLength;
-        }
-
-        // We've picked optimal values for all entries, but the result is unsorted. Fix that now.
-        SortLengthBuckets(m_rgEncodingLengths);
-    }
-
-    // Phase 4: We've now calculated all the input data we need and allocated memory for the output so we can
-    // go ahead and fill in the compressed table and index.
-    void InitializeTableAndIndex()
-    {
-        STANDARD_VM_CONTRACT;
-
-        // Initialize bit stream writers to the start of the compressed table and index.
-        BitStreamWriter sTableStream((DWORD*)m_pTable);
-        BitStreamWriter sIndexStream((DWORD*)m_pIndex);
-
-        DWORD dwRid = 0;
-        DWORD dwLastValue = 0;
-        LookupMapBase *pMap = m_pMap;
-
-        // Walk each node in the map.
-        while (pMap)
-        {
-            // Walk each entry in this node.
-            for (DWORD i = 0; i < pMap->dwCount; i++)
-            {
-                DWORD dwCurrentValue = ComputeElementRVA(pMap, i);
-
-                // Calculate the delta from the last entry. We split the delta into two-components: a bool
-                // indicating whether the RVA was higher or lower and an absolute (non-negative) size. Sort of
-                // like a ones-complement signed number.
-                bool fIncreasingDelta = dwCurrentValue > dwLastValue;
-                DWORD dwDelta = fIncreasingDelta ? (dwCurrentValue - dwLastValue) : (dwLastValue - dwCurrentValue);
-
-                // As a trade-off we can't store deltas with their most efficient length (because just
-                // encoding the length can dominate the space requirement when we have to cope with worst-case
-                // deltas). Instead we encode a relatively short index into the table of encoding lengths we
-                // calculated back in phase 2. So some deltas will encode in more bits than necessary but
-                // overall we'll win due to lowered prefix bit requirements.
-                // Look through all the table entries and choose the first that's large enough to accomodate
-                // our delta.
-                DWORD dwDeltaBitLength = BitsRequired(dwDelta);
-                DWORD j;
-                for (j = 0; j < kLookupMapLengthEntries; j++)
-                {
-                    if (m_rgEncodingLengths[j] >= dwDeltaBitLength)
-                    {
-                        dwDeltaBitLength = m_rgEncodingLengths[j];
-                        break;
-                    }
-                }
-                _ASSERTE(j < kLookupMapLengthEntries);
-
-                // Write the entry into the compressed table.
-                sTableStream.Write(j, kLookupMapLengthBits);        // The index for the delta length
-                sTableStream.Write(fIncreasingDelta ? 1 : 0, 1);    // The +/- delta indicator
-                sTableStream.Write(dwDelta, dwDeltaBitLength);      // The delta itself
-
-                // Is this entry one that requires a corresponding index entry?
-                if ((dwRid % kLookupMapIndexStride) == 0)
-                {
-                    // Write an index entry:
-                    //  * The current (map-relative) RVA.
-                    //  * The position in the table bit stream of the next entry.
-                    sIndexStream.Write(dwCurrentValue, kBitsPerRVA);
-                    sIndexStream.Write(sTableStream.GetBitsWritten(), m_cBitsPerIndexEntry - kBitsPerRVA);
-                }
-
-                dwRid++;
-
-                dwLastValue = dwCurrentValue;
-            }
-
-            pMap = pMap->pNext;
-        }
-
-        // Flush any remaining bits in the caches of the table and index stream writers.
-        sTableStream.Flush();
-        sIndexStream.Flush();
-
-        // Make sure what we wrote fitted in what we allocated.
-        _ASSERTE((sTableStream.GetBitsWritten() / 8) <= m_cbTable);
-        _ASSERTE((sIndexStream.GetBitsWritten() / 8) <= m_cbIndex);
-
-        // Also check that we didn't have more than 31 bits of excess space allocated either (we should have
-        // allocated DWORD aligned lengths).
-        _ASSERTE(((m_cbTable * 8) - sTableStream.GetBitsWritten()) < 32);
-        _ASSERTE(((m_cbIndex * 8) - sIndexStream.GetBitsWritten()) < 32);
-    }
-
-    // Determine the final, map-relative RVA of the element at a specified index
-    DWORD ComputeElementRVA(LookupMapBase *pMap, DWORD index)
-    {
-        STANDARD_VM_CONTRACT;
-
-        // We base our RVAs on the RVA of the map (rather than the module). This is purely because individual
-        // maps don't store back pointers to their owning module so it's easier to recover pointer values at
-        // runtime using the map address instead.
-        DWORD rvaBase = m_pImage->GetRVA(m_pMap);
-
-        // Retrieve the pointer value in the specified entry. This is tricky since the pointer is
-        // encoded as a RelativePointer.
-        DWORD dwFinalRVA;
-        TADDR entry = RelativePointer<TADDR>::GetValueMaybeNullAtPtr((TADDR)&pMap->pTable[index]);
-        if (entry == 0)
-        {
-            // The pointer was null. We encode this as a zero RVA (RVA pointing to the map itself,
-            // which should never happen otherwise).
-            dwFinalRVA = 0;
-        }
-        else
-        {
-            // Non-null pointer, go get the RVA it's been mapped to. Transform this RVA into our
-            // special map-relative variant by substracting the map base.
-
-            // Some of the pointer alignment bits may have been used as flags; preserve them.
-            DWORD flags = entry & ((1 << kFlagBits) - 1);
-            entry -= flags;
-
-            // We only support compressing maps of pointers to saved objects (e.g. no indirected FixupPointers)
-            // so there is guaranteed to be a valid RVA at this point.  If this does not hold, GetRVA will assert.
-            DWORD rvaEntry = m_pImage->GetRVA((void*)entry);
-
-            dwFinalRVA = rvaEntry - rvaBase + flags;
-        }
-
-        return dwFinalRVA;
-    }
-
-    // Determine the number of bits required to represent the significant portion of a value (i.e. the value
-    // without any leading 0s). Always return 1 as a minimum (we do not encode 0 in 0 bits).
-    DWORD BitsRequired(DWORD dwValue)
-    {
-        LIMITED_METHOD_CONTRACT;
-
-#if (defined(TARGET_X86) || defined(TARGET_AMD64)) && defined(_MSC_VER)
-
-        // This this operation could impact the performance of ngen (we call this a *lot*) we'll try and
-        // optimize this where we can. x86 and amd64 actually have instructions to find the least and most
-        // significant bits in a DWORD and MSVC exposes this as a builtin.
-        DWORD dwHighBit;
-        if (_BitScanReverse(&dwHighBit, dwValue))
-            return dwHighBit + 1;
-        else
-            return 1;
-
-#else // (TARGET_X86 || TARGET_AMD64) && _MSC_VER
-
-        // Otherwise we'll calculate this the slow way. Pick off the 32-bit case first due to avoid the
-        // usual << problem (x << 32 == x, not 0).
-        if (dwValue > 0x7fffffff)
-            return 32;
-
-        DWORD cBits = 1;
-        while (dwValue > ((1U << cBits) - 1))
-            cBits++;
-
-        return cBits;
-
-#endif // (TARGET_X86 || TARGET_AMD64) && _MSC_VER
-    }
-
-    // Sort the given input array (of kLookupMapLengthEntries entries, where the last entry is already sorted)
-    // from lowest to highest value.
-    void SortLengthBuckets(BYTE rgBuckets[])
-    {
-        LIMITED_METHOD_CONTRACT;
-
-        // This simplistic insertion sort algorithm is probably the fastest for small values of
-        // kLookupMapLengthEntries.
-        _ASSERTE(kLookupMapLengthEntries < 10);
-
-        // Iterate over every entry apart from the last two, moving the correct sorted value into each in
-        // turn. Don't do the last value because it's already sorted and the second last because it'll be
-        // sorted by the time we've done all the rest.
-        for (DWORD i = 0; i < (kLookupMapLengthEntries - 2); i++)
-        {
-            BYTE bLowValue = rgBuckets[i];    // The lowest value we've seen so far
-            DWORD dwLowIndex = i;               // The index which held that value
-
-            // Look through the unsorted entries for the smallest.
-            for (DWORD j = i + 1; j < (kLookupMapLengthEntries - 1); j++)
-            {
-                if (rgBuckets[j] < bLowValue)
-                {
-                    // Got a bette candidate for smallest.
-                    bLowValue = rgBuckets[j];
-                    dwLowIndex = j;
-                }
-            }
-
-            // If the original value at the current index wasn't the smallest, swap it with the one that was.
-            if (dwLowIndex != i)
-            {
-                rgBuckets[dwLowIndex] = rgBuckets[i];
-                rgBuckets[i] = bLowValue;
-            }
-        }
-
-#ifdef _DEBUG
-        // Check the table really is sorted.
-        for (DWORD i = 1; i < kLookupMapLengthEntries; i++)
-            _ASSERTE(rgBuckets[i] >= rgBuckets[i - 1]);
-#endif // _DEBUG
-    }
-
-    // Given the histogram of the delta lengths and a prospective table of the subset of those lengths that
-    // we'd utilize to encode the table, return the size (in bits) of the compressed table we'd get as a
-    // result. The algorithm requires that the encoding length table is sorted (smallest to largest length).
-    DWORD PredictCompressedSize(BYTE rgBuckets[])
-    {
-        LIMITED_METHOD_CONTRACT;
-
-        DWORD cTotalBits = 0;
-
-        // Iterate over each entry in the histogram (first entry is the number of deltas that can be encoded
-        // in 1 bit, the second is the number of entries encodable in 2 bits etc.).
-        for (DWORD i = 0; i < kBitsPerRVA; i++)
-        {
-            // Start by assuming that we can encode entries in this bucket with their exact length.
-            DWORD cBits = i + 1;
-
-            // Look through the encoding table to find the first (lowest) encoding length that can encode the
-            // values for this bucket.
-            for (DWORD j = 0; j < kLookupMapLengthEntries; j++)
-            {
-                if (cBits <= rgBuckets[j])
-                {
-                    // This is the best encoding we can do. Remember the real cost of all entries in this
-                    // histogram bucket.
-                    cBits = rgBuckets[j];
-                    break;
-                }
-            }
-
-            // Each entry for this histogram bucket costs a fixed size index into the encoding length table
-            // (kLookupMapLengthBits), a single bit of delta sign plus the number of bits of delta magnitude
-            // that we calculated above.
-            cTotalBits += (kLookupMapLengthBits + 1 + cBits) * m_rgHistogram[i];
-        }
-
-        return cTotalBits;
-    }
-};
-
-// Allocate a special zap node that will compress the cold rid map associated with the given LookupMap.
-void DataImage::StoreCompressedLayoutMap(LookupMapBase *pMap, ItemKind kind)
-{
-    STANDARD_VM_CONTRACT;
-
-    ZapNode *pNode = new (GetHeap()) ZapCompressedLookupMap(this, pMap, static_cast<BYTE>(kind));
-
-    AddStructureInOrder(pNode);
-}
-
-#endif // FEATURE_PREJIT
diff --git a/src/coreclr/vm/dataimagesection.h b/src/coreclr/vm/dataimagesection.h
deleted file mode 100644 (file)
index f78a348..0000000
+++ /dev/null
@@ -1,102 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-
-
-
-#ifndef FEATURE_PREJIT
-#error FEATURE_PREJIT is required for this file
-#endif
-
-
-#ifndef DEFINE_ITEM_KIND
-#define DEFINE_ITEM_KIND(id)
-#endif
-
-//-----------------------------------------------------------------------------
-// Items
-//-----------------------------------------------------------------------------
-
-DEFINE_ITEM_KIND(ITEM_MODULE)
-DEFINE_ITEM_KIND(ITEM_FILEREF_MAP)
-DEFINE_ITEM_KIND(ITEM_ASSEMREF_MAP)
-DEFINE_ITEM_KIND(ITEM_GC_STATIC_HANDLES_HOT)
-DEFINE_ITEM_KIND(ITEM_DYNAMIC_STATICS_INFO_TABLE)
-DEFINE_ITEM_KIND(ITEM_DYNAMIC_STATICS_INFO_ENTRY)
-DEFINE_ITEM_KIND(ITEM_RID_MAP_HOT)
-DEFINE_ITEM_KIND(ITEM_TYPEDEF_MAP)
-DEFINE_ITEM_KIND(ITEM_MODULE_CCTOR_INFO_HOT)
-DEFINE_ITEM_KIND(ITEM_MODULE_CCTOR_INFO_COLD)
-DEFINE_ITEM_KIND(ITEM_STORED_METHOD_SIG)
-DEFINE_ITEM_KIND(ITEM_STORED_METHOD_SIG_READONLY)
-DEFINE_ITEM_KIND(ITEM_STORED_METHOD_SIG_READONLY_WARM)
-DEFINE_ITEM_KIND(ITEM_STORED_METHOD_NAME)
-DEFINE_ITEM_KIND(ITEM_PROPERTY_NAME_SET)
-DEFINE_ITEM_KIND(ITEM_BINDER)
-DEFINE_ITEM_KIND(ITEM_BINDER_ITEMS)
-DEFINE_ITEM_KIND(ITEM_TYPEREF_MAP)
-DEFINE_ITEM_KIND(ITEM_METHODDEF_MAP)
-DEFINE_ITEM_KIND(ITEM_FIELDDEF_MAP)
-DEFINE_ITEM_KIND(ITEM_MEMBERREF_MAP)
-DEFINE_ITEM_KIND(ITEM_GENERICPARAM_MAP)
-DEFINE_ITEM_KIND(ITEM_GENERICTYPEDEF_MAP)
-DEFINE_ITEM_KIND(ITEM_PROPERTYINFO_MAP)
-DEFINE_ITEM_KIND(ITEM_DISPATCH_MAP)
-DEFINE_ITEM_KIND(ITEM_PARAM_TYPEDESC)
-DEFINE_ITEM_KIND(ITEM_ARRAY_TYPEDESC)
-#ifdef FEATURE_COMINTEROP
-DEFINE_ITEM_KIND(ITEM_SPARSE_VTABLE_MAP_TABLE)
-DEFINE_ITEM_KIND(ITEM_SPARSE_VTABLE_MAP_ENTRIES)
-#endif // FEATURE_COMINTEROP
-DEFINE_ITEM_KIND(ITEM_EECLASS)
-DEFINE_ITEM_KIND(ITEM_EECLASS_COLD)
-DEFINE_ITEM_KIND(ITEM_EECLASS_WARM)
-DEFINE_ITEM_KIND(ITEM_CLASS_VARIANCE_INFO)
-DEFINE_ITEM_KIND(ITEM_FIELD_DESC_LIST)
-DEFINE_ITEM_KIND(ITEM_ENUM_VALUES)
-DEFINE_ITEM_KIND(ITEM_ENUM_NAME_POINTERS)
-DEFINE_ITEM_KIND(ITEM_ENUM_NAME)
-DEFINE_ITEM_KIND(ITEM_DICTIONARY_LAYOUT)
-DEFINE_ITEM_KIND(ITEM_TYVAR_TYPEDESC)
-DEFINE_ITEM_KIND(ITEM_FPTR_TYPEDESC)
-DEFINE_ITEM_KIND(ITEM_DICTIONARY)
-DEFINE_ITEM_KIND(ITEM_DICTIONARY_WRITEABLE)
-DEFINE_ITEM_KIND(ITEM_METHOD_TABLE)
-DEFINE_ITEM_KIND(ITEM_METHOD_TABLE_SPECIAL_WRITEABLE)
-DEFINE_ITEM_KIND(ITEM_METHOD_TABLE_DATA_HOT_WRITEABLE)
-DEFINE_ITEM_KIND(ITEM_METHOD_TABLE_DATA_COLD_WRITEABLE)
-DEFINE_ITEM_KIND(ITEM_INTERFACE_MAP)
-DEFINE_ITEM_KIND(ITEM_VTABLE_CHUNK)
-DEFINE_ITEM_KIND(ITEM_GUID_INFO)
-DEFINE_ITEM_KIND(ITEM_GENERICS_STATIC_FIELDDESCS)
-DEFINE_ITEM_KIND(ITEM_RVA_STATICS)
-DEFINE_ITEM_KIND(ITEM_DEBUG)
-DEFINE_ITEM_KIND(ITEM_GC_STATIC_HANDLES_COLD)
-DEFINE_ITEM_KIND(ITEM_METHOD_PRECODE_COLD_WRITEABLE)
-DEFINE_ITEM_KIND(ITEM_METHOD_PRECODE_COLD)
-DEFINE_ITEM_KIND(ITEM_METHOD_PRECODE_HOT_WRITEABLE)
-DEFINE_ITEM_KIND(ITEM_METHOD_PRECODE_HOT)
-DEFINE_ITEM_KIND(ITEM_METHOD_DESC_COLD_WRITEABLE)
-DEFINE_ITEM_KIND(ITEM_METHOD_DESC_COLD)
-DEFINE_ITEM_KIND(ITEM_METHOD_DESC_HOT_WRITEABLE)
-DEFINE_ITEM_KIND(ITEM_METHOD_DESC_HOT)
-DEFINE_ITEM_KIND(ITEM_CROSS_DOMAIN_INFO)
-DEFINE_ITEM_KIND(ITEM_CER_ROOT_TABLE)
-DEFINE_ITEM_KIND(ITEM_CER_METHOD_LIST)
-DEFINE_ITEM_KIND(ITEM_CER_RESTORE_FLAGS)
-DEFINE_ITEM_KIND(ITEM_VTS_INFO)
-DEFINE_ITEM_KIND(ITEM_MODULE_SECDESC)
-DEFINE_ITEM_KIND(ITEM_FROZEN_OBJECTS)
-DEFINE_ITEM_KIND(ITEM_NGEN_HASH_HOT)
-DEFINE_ITEM_KIND(ITEM_NGEN_HASH_COLD)
-DEFINE_ITEM_KIND(ITEM_NGEN_HASH_BUCKETLIST_HOT)
-DEFINE_ITEM_KIND(ITEM_NGEN_HASH_BUCKETLIST_COLD)
-DEFINE_ITEM_KIND(ITEM_NGEN_HASH_ENTRIES_HOT)
-DEFINE_ITEM_KIND(ITEM_NGEN_HASH_ENTRIES_COLD)
-DEFINE_ITEM_KIND(ITEM_NGEN_HASH_ENTRIES_RO_HOT)
-DEFINE_ITEM_KIND(ITEM_NGEN_HASH_ENTRIES_RO_COLD)
-DEFINE_ITEM_KIND(ITEM_COMPRESSED_MAP)
-DEFINE_ITEM_KIND(ITEM_INLINING_DATA)
-
-#ifdef DEFINE_ITEM_KIND
-#undef DEFINE_ITEM_KIND
-#endif
index 925e1f7..7070769 100644 (file)
 #include "clrtocomcall.h"
 #endif // FEATURE_COMINTEROP
 
-#ifdef FEATURE_PREJIT
-#include "compile.h"
-#endif // FEATURE_PREJIT
-
 #include "eventtrace.h"
 
 namespace
index 963c8ef..aed2462 100644 (file)
 #include "dbginterface.h"
 #include "eventtrace.h"
 
-#ifdef FEATURE_PREJIT
-#include <corcompile.h>
-#include "compile.h"
-#endif  // FEATURE_PREJIT
-
 #include "dllimportcallback.h"
 #include "peimagelayout.inl"
 
@@ -733,33 +728,6 @@ BOOL DomainFile::IsZapRequired()
     if (pMD->GetCountWithTokenKind(mdtTypeDef) == 0 && pMD->GetCountWithTokenKind(mdtMethodDef) == 0)
         return FALSE;
 
-    DomainAssembly * pDomainAssembly = GetDomainAssembly();
-
-#ifdef FEATURE_NATIVE_IMAGE_GENERATION
-    if (IsCompilationProcess())
-    {
-        // Ignore the assembly being ngened.
-
-        bool fileIsBeingNGened = false;
-
-        if (this->GetAppDomain()->IsCompilationDomain())
-        {
-            Assembly * assemblyBeingNGened = this->GetAppDomain()->ToCompilationDomain()->GetTargetAssembly();
-            if (assemblyBeingNGened == NULL || assemblyBeingNGened == pDomainAssembly->GetCurrentAssembly())
-                fileIsBeingNGened = true;
-        }
-        else if (IsSystem())
-        {
-            // CoreLib gets loaded before the CompilationDomain gets created.
-            // However, we may be ngening CoreLib itself
-            fileIsBeingNGened = true;
-        }
-
-        if (fileIsBeingNGened)
-            return FALSE;
-    }
-#endif
-
     return TRUE;
 }
 
@@ -833,18 +801,6 @@ void DomainFile::ClearNativeImageStress()
     // Different app-domains should make different decisions
     hash ^= HashString(this->GetAppDomain()->GetFriendlyName());
 
-#ifdef FEATURE_NATIVE_IMAGE_GENERATION
-    // Since DbgRandomOnHashAndExe() is not so random under ngen.exe, also
-    // factor in the module being compiled
-    if (this->GetAppDomain()->IsCompilationDomain())
-    {
-        Module * module = this->GetAppDomain()->ToCompilationDomain()->GetTargetModule();
-        // Has the target module been set yet?
-        if (module)
-            hash ^= HashStringA(module->GetSimpleName());
-    }
-#endif
-
     if (DbgRandomOnHashAndExe(hash, float(stressPercentage)/100))
     {
         GetFile()->ClearNativeImage();
index c4c44b4..647db46 100644 (file)
 #include "eedbginterface.h"
 #include "debugdebugger.h"
 
-#ifdef FEATURE_PREJIT
-#include "corcompile.h"
-#endif // FEATURE_PREJIT
-
 #include "eeconfig.h"
 #include "pefile.h"
 
index f499668..5467b1a 100644 (file)
 
 #include "exceptmacros.h"
 #include "syncclean.hpp"
-#ifdef FEATURE_PREJIT
-class DataImage;
-#endif
 
 #include "util.hpp"
 
-#ifdef FEATURE_PREJIT
-#include "corcompile.h"
-#endif
-
 class AllocMemTracker;
 class ClassLoader;
 struct LockOwner;
index 74ff841..4fc3031 100644 (file)
@@ -700,78 +700,6 @@ VOID    FieldDesc::SetValue64(OBJECTREF o, __int64 value)
 
 #endif // !CROSSGEN_COMPILE
 
-
-#ifndef DACCESS_COMPILE
-
-#ifdef FEATURE_NATIVE_IMAGE_GENERATION
-void FieldDesc::SaveContents(DataImage *image)
-{
-    STANDARD_VM_CONTRACT;
-
-#ifdef _DEBUG
-    if (m_debugName && !image->IsStored((void*) m_debugName))
-        image->StoreStructure((void *) m_debugName,
-                                        (ULONG)(strlen(m_debugName) + 1),
-                                        DataImage::ITEM_DEBUG,
-                                        1);
-#endif
-
-    //
-    // If we are compiling an IL only image, and our RVA fits
-    // in the designated range, copy the RVA data over to the prejit
-    // image.
-    //
-
-    if (IsRVA())
-    {
-        //
-        // Move the RVA data into the prejit image.
-        //
-
-        UINT size = LoadSize();
-
-        //
-        // Compute an alignment for the data based on the alignment
-        // of the RVA.  We'll align up to 8 bytes.
-        //
-
-        UINT align = 1;
-        DWORD rva = GetOffset();
-        DWORD rvaTemp = rva;
-
-        while ((rvaTemp&1) == 0 && align < 8 && align < size)
-        {
-            align <<= 1;
-            rvaTemp >>= 1;
-        }
-
-        image->StoreRvaInfo(this,
-                            rva,
-                            size,
-                            align);
-    }
-}
-
-void FieldDesc::Fixup(DataImage *image)
-{
-    STANDARD_VM_CONTRACT;
-
-    LOG((LF_ZAP, LL_INFO10000, "FieldDesc::Fixup %s::%s\n", GetApproxEnclosingMethodTable()->GetDebugClassName(), m_debugName));
-    image->FixupRelativePointerField(this, offsetof(FieldDesc, m_pMTOfEnclosingClass));
-
-#ifdef _DEBUG
-    image->FixupPointerField(this, offsetof(FieldDesc, m_debugName));
-#endif
-
-    // if (IsRVAFieldWithLessThanBigOffset())
-    // {
-    //      offset of RVA fields is fixed up in DataImage::FixupRvaStructure
-    // }
-}
-#endif // FEATURE_NATIVE_IMAGE_GENERATION
-
-#endif // #ifndef DACCESS_COMPILE
-
 UINT FieldDesc::LoadSize()
 {
     CONTRACTL
index 8fa87ed..487f0e9 100644 (file)
@@ -356,11 +356,6 @@ public:
 
     BOOL IsObjRef();
 
-#ifdef FEATURE_PREJIT
-    void SaveContents(DataImage *image);
-    void Fixup(DataImage *image);
-#endif // FEATURE_PREJIT
-
     UINT LoadSize();
 
     // Return -1 if the type isn't loaded yet (i.e. if LookupFieldTypeHandle() would return null)
index 1fbef3a..a5c77ca 100644 (file)
 #include "eeconfig.h"
 #include "olevariant.h"
 
-#ifdef FEATURE_PREJIT
-#include "compile.h"
-#endif // FEATURE_PREJIT
-
 // Forward references
 class EEClassLayoutInfo;
 class FieldDesc;
index fd6ef6d..78dced0 100644 (file)
@@ -29,7 +29,6 @@
 #include "typectxt.h"
 #include "virtualcallstub.h"
 #include "sigbuilder.h"
-#include "compile.h"
 
 #ifndef DACCESS_COMPILE
 
@@ -494,264 +493,6 @@ DictionaryEntryLayout::GetKind()
 }
 
 #ifndef DACCESS_COMPILE
-#ifdef FEATURE_NATIVE_IMAGE_GENERATION
-
-//---------------------------------------------------------------------------------------
-//
-DWORD
-DictionaryLayout::GetObjectSize()
-{
-    LIMITED_METHOD_CONTRACT;
-    return sizeof(DictionaryLayout) + sizeof(DictionaryEntryLayout) * (m_numSlots-1);
-}
-
-//---------------------------------------------------------------------------------------
-//
-// Save the dictionary layout for prejitting
-// 
-void 
-DictionaryLayout::Save(DataImage * image)
-{
-    STANDARD_VM_CONTRACT;
-
-    image->StoreStructure(this, GetObjectSize(), DataImage::ITEM_DICTIONARY_LAYOUT);
-}
-
-//---------------------------------------------------------------------------------------
-//
-// Save the dictionary layout for prejitting
-//
-void
-DictionaryLayout::Trim()
-{
-    CONTRACTL
-    {
-        THROWS;
-        GC_NOTRIGGER;
-    }
-    CONTRACTL_END;
-
-    // Trim down the size to what's actually used
-    DWORD dwSlots = GetNumUsedSlots();
-    _ASSERTE(FitsIn<WORD>(dwSlots));
-    m_numSlots = static_cast<WORD>(dwSlots);
-
-}
-
-//---------------------------------------------------------------------------------------
-//
-// Fixup pointers in the dictionary layout for prejitting
-//
-void
-DictionaryLayout::Fixup(
-    DataImage * image,
-    BOOL        fMethod)
-{
-    STANDARD_VM_CONTRACT;
-
-    for (DWORD i = 0; i < m_numSlots; i++)
-    {
-        PVOID signature = m_slots[i].m_signature;
-        if (signature != NULL)
-        {
-            image->FixupFieldToNode(this, (BYTE *)&m_slots[i].m_signature - (BYTE *)this,
-                image->GetGenericSignature(signature, fMethod));
-        }
-    }
-}
-
-//---------------------------------------------------------------------------------------
-//
-// Fixup pointers in the actual dictionary, including the type arguments.  Delete entries
-// that are expensive or difficult to restore.
-//
-void
-Dictionary::Fixup(
-    DataImage *        image,
-    BOOL               canSaveInstantiation,
-    BOOL               canSaveSlots,
-    DWORD              numGenericArgs,
-    Module *           pModule,
-    DictionaryLayout * pDictLayout)
-{
-    STANDARD_VM_CONTRACT;
-
-    // First fixup the type handles in the instantiation itself
-    FixupPointer<TypeHandle> *pInst = GetInstantiation();
-    for (DWORD j = 0; j < numGenericArgs; j++)
-    {
-        if (canSaveInstantiation)
-        {
-            image->FixupTypeHandlePointer(pInst, &pInst[j]);
-        }
-        else
-        {
-            image->ZeroPointerField(AsPtr(), j * sizeof(DictionaryEntry));
-        }
-    }
-
-    // Now traverse the remaining slots
-    if (pDictLayout != NULL)
-    {
-        for (DWORD i = 0; i < pDictLayout->m_numSlots; i++)
-        {
-            int slotOffset = (numGenericArgs + i) * sizeof(DictionaryEntry);
-
-            // First check if we can simply hardbind to a prerestored object
-            DictionaryEntryLayout *pLayout = pDictLayout->GetEntryLayout(i);
-            switch (pLayout->GetKind())
-            {
-            case TypeHandleSlot:
-            case DeclaringTypeHandleSlot:
-                if (canSaveSlots &&
-                    !IsSlotEmpty(numGenericArgs,i) &&
-                    image->CanPrerestoreEagerBindToTypeHandle(GetTypeHandleSlot(numGenericArgs, i), NULL) &&
-                    image->CanHardBindToZapModule(GetTypeHandleSlot(numGenericArgs, i).GetLoaderModule()))
-                {
-                    image->HardBindTypeHandlePointer(AsPtr(), slotOffset);
-                }
-                else
-                {
-                    // Otherwise just zero the slot
-                    image->ZeroPointerField(AsPtr(), slotOffset);
-                }
-                break;
-            case MethodDescSlot:
-                if (canSaveSlots &&
-                    !IsSlotEmpty(numGenericArgs,i) &&
-                    image->CanPrerestoreEagerBindToMethodDesc(GetMethodDescSlot(numGenericArgs,i), NULL) &&
-                    image->CanHardBindToZapModule(GetMethodDescSlot(numGenericArgs,i)->GetLoaderModule()))
-                {
-                    image->FixupPointerField(AsPtr(), slotOffset);
-                }
-                else
-                {
-                    // Otherwise just zero the slot
-                    image->ZeroPointerField(AsPtr(), slotOffset);
-                }
-                break;
-            case FieldDescSlot:
-                if (canSaveSlots &&
-                    !IsSlotEmpty(numGenericArgs,i) &&
-                    image->CanEagerBindToFieldDesc(GetFieldDescSlot(numGenericArgs,i)) &&
-                    image->CanHardBindToZapModule(GetFieldDescSlot(numGenericArgs,i)->GetLoaderModule()))
-                {
-                    image->FixupPointerField(AsPtr(), slotOffset);
-                }
-                else
-                {
-                    // Otherwise just zero the slot
-                    image->ZeroPointerField(AsPtr(), slotOffset);
-                }
-                break;
-            default:
-                // <TODO> Method entry points are currently not saved </TODO>
-                // <TODO> Stub dispatch slots are currently not saved </TODO>
-                // Otherwise just zero the slot
-                image->ZeroPointerField(AsPtr(), slotOffset);
-            }
-        }
-    }
-} // Dictionary::Fixup
-
-//---------------------------------------------------------------------------------------
-//
-BOOL
-Dictionary::IsWriteable(
-    DataImage *         image,
-    BOOL                canSaveSlots,
-    DWORD               numGenericArgs, // Must be non-zero
-    Module *            pModule,        // module of the generic code
-    DictionaryLayout *  pDictLayout)
-{
-    STANDARD_VM_CONTRACT;
-
-    // Traverse dictionary slots
-    if (pDictLayout != NULL)
-    {
-        for (DWORD i = 0; i < pDictLayout->m_numSlots; i++)
-        {
-            // First check if we can simply hardbind to a prerestored object
-            DictionaryEntryLayout *pLayout = pDictLayout->GetEntryLayout(i);
-            switch (pLayout->GetKind())
-            {
-            case TypeHandleSlot:
-            case DeclaringTypeHandleSlot:
-                if (canSaveSlots &&
-                    !IsSlotEmpty(numGenericArgs,i) &&
-                    image->CanPrerestoreEagerBindToTypeHandle(GetTypeHandleSlot(numGenericArgs, i), NULL) &&
-                    image->CanHardBindToZapModule(GetTypeHandleSlot(numGenericArgs, i).GetLoaderModule()))
-                {
-                    // do nothing
-                }
-                else
-                {
-                    return TRUE;
-                }
-                break;
-            case MethodDescSlot:
-                if (canSaveSlots &&
-                    !IsSlotEmpty(numGenericArgs,i) &&
-                    image->CanPrerestoreEagerBindToMethodDesc(GetMethodDescSlot(numGenericArgs,i), NULL) &&
-                    image->CanHardBindToZapModule(GetMethodDescSlot(numGenericArgs,i)->GetLoaderModule()))
-                {
-                    // do nothing
-                }
-                else
-                {
-                    return TRUE;
-                }
-                break;
-            case FieldDescSlot:
-                if (canSaveSlots &&
-                    !IsSlotEmpty(numGenericArgs,i) &&
-                    image->CanEagerBindToFieldDesc(GetFieldDescSlot(numGenericArgs,i)) &&
-                    image->CanHardBindToZapModule(GetFieldDescSlot(numGenericArgs,i)->GetLoaderModule()))
-                {
-                    // do nothing
-                }
-                else
-                {
-                    return TRUE;
-                }
-                break;
-            default:
-                // <TODO> Method entry points are currently not saved </TODO>
-                // <TODO> Stub dispatch slots are currently not saved </TODO>
-                return TRUE;
-            }
-        }
-    }
-
-    return FALSE;
-} // Dictionary::IsWriteable
-
-//---------------------------------------------------------------------------------------
-//
-BOOL
-Dictionary::ComputeNeedsRestore(
-    DataImage *      image,
-    TypeHandleList * pVisited,
-    DWORD            numGenericArgs)
-{
-    STANDARD_VM_CONTRACT;
-
-    // First check the type handles in the instantiation itself
-    FixupPointer<TypeHandle> *inst = GetInstantiation();
-    for (DWORD j = 0; j < numGenericArgs; j++)
-    {
-        if (!image->CanPrerestoreEagerBindToTypeHandle(inst[j].GetValue(), pVisited))
-            return TRUE;
-    }
-
-    // Unless prepopulating we don't need to check the entries
-    // of the dictionary because if we can't
-    // hardbind to them we just zero the dictionary entry and recover
-    // it on demand.
-
-    return FALSE;
-}
-#endif //FEATURE_NATIVE_IMAGE_GENERATION
 
 #ifdef FEATURE_PREJIT
 //---------------------------------------------------------------------------------------
index 43df310..d68f5d7 100644 (file)
 #ifndef _GENERICDICT_H
 #define _GENERICDICT_H
 
-#ifdef FEATURE_PREJIT
-#include "dataimage.h"
-#endif
-
 // DICTIONARIES
 //
 // A dictionary is a cache of handles associated with particular
@@ -182,32 +178,6 @@ public:
             dac_cast<TADDR>(this) + offsetof(DictionaryLayout, m_slots) + sizeof(DictionaryEntryLayout) * i);
     }
 
-
-#ifdef FEATURE_PREJIT
-    DWORD GetObjectSize();
-
-    // Trim the canonical dictionary layout to include only those used slots actually used.
-    // WARNING!!!
-    // You should only call this if
-    //    (a) you're actually saving this shared instantiation into it's PreferredZapModule,
-    //        i.e. you must be both saving the shared instantiation and the module
-    //        you're ngen'ing MUST be that the PreferredZapModule.
-    //    (b) you're sure you've compiled all the shared code for this type
-    //        within the context of this NGEN session.
-    // This is currently the same as saying we can hardbind to the EEClass - if it's in another
-    // module then we will have already trimmed the layout, and if it's being saved into the
-    // current module then we can only hardbind to it if the current module is the PreferredZapModule.
-    //
-    // Note after calling this both GetObjectSize for this layout and the
-    // computed dictionary size for all dictionaries based on this layout may
-    // be reduced.  This may in turn affect the size of all non-canonical
-    // method tables, potentially trimming some dictionary words off the end
-    // of the method table.
-    void Trim();
-    void Save(DataImage *image);
-    void Fixup(DataImage *image, BOOL fMethod);
-#endif // FEATURE_PREJIT
-
 };
 
 
@@ -335,33 +305,6 @@ private:
 public:
 
 #ifdef FEATURE_PREJIT
-
-    // Fixup the dictionary entries, including the type arguments
-    //
-    // WARNING!!!
-    // You should only pass "canSaveSlots=TRUE" if you are certain the dictionary layout
-    // matches that which will be used at runtime.  This means you must either
-    // be able to hard-bind to the EEClass of the canonical instantiation, or else
-    // you are saving a copy of the canonical instantiation itself.
-    //
-    // If we can't save slots, then we will zero all entries in the dictionary (apart from the
-    // instantiation itself) and load at runtime.
-    void Fixup(DataImage *image,
-               BOOL canSaveInstantiation,
-               BOOL canSaveSlots,
-               DWORD numGenericArgs,            // Must be non-zero
-               Module *pModule,                 // module of the generic code
-               DictionaryLayout *pDictLayout);  // If NULL, then only type arguments are present
-
-    BOOL IsWriteable(DataImage *image,
-               BOOL canSaveSlots,
-               DWORD numGenericArgs,            // Must be non-zero
-               Module *pModule,                 // module of the generic code
-               DictionaryLayout *pDictLayout);  // If NULL, then only type arguments are present
-
-    BOOL ComputeNeedsRestore(DataImage *image,
-                             TypeHandleList *pVisited,
-                             DWORD numGenericArgs);
     void Restore(DWORD numGenericArgs, ClassLoadLevel level);
 #endif // FEATURE_PREJIT
 };
index 6af331c..7e3ef1f 100644 (file)
 #include "olevariant.h"
 #endif // FEATURE_COMINTEROP
 
-#ifdef FEATURE_PREJIT
-#include "compile.h"
-#endif
-
 #include "stublink.inl"
 
 extern "C" DWORD STDCALL GetSpecificCpuTypeAsm(void);
index 5643630..6a9f31f 100644 (file)
 #include "notifyexternals.h"
 #endif // FEATURE_COMINTEROP
 
-#ifdef FEATURE_PREJIT
-#include "compile.h"
-#endif
-
 #if defined(_DEBUG) && defined(STUBLINKER_GENERATES_UNWIND_INFO)
 #include <psapi.h>
 #endif
@@ -5398,51 +5394,6 @@ BOOL FixupPrecode::SetTargetInterlocked(TADDR target, TADDR expected)
     return FastInterlockCompareExchangeLong((INT64*)precodeWriterHolder.GetRW(), newValue, oldValue) == oldValue;
 }
 
-#ifdef FEATURE_NATIVE_IMAGE_GENERATION
-// Partial initialization. Used to save regrouped chunks.
-void FixupPrecode::InitForSave(int iPrecodeChunkIndex)
-{
-    m_op   = X86_INSTR_CALL_REL32;       // call PrecodeFixupThunk
-    m_type = FixupPrecode::TypePrestub;
-
-    _ASSERTE(FitsInU1(iPrecodeChunkIndex));
-    m_PrecodeChunkIndex = static_cast<BYTE>(iPrecodeChunkIndex);
-
-    // The rest is initialized in code:FixupPrecode::Fixup
-}
-
-void FixupPrecode::Fixup(DataImage *image, MethodDesc * pMD)
-{
-    STANDARD_VM_CONTRACT;
-
-    // Note that GetMethodDesc() does not return the correct value because of
-    // regrouping of MethodDescs into hot and cold blocks. That's why the caller
-    // has to supply the actual MethodDesc
-
-    SSIZE_T mdChunkOffset;
-    ZapNode * pMDChunkNode = image->GetNodeForStructure(pMD, &mdChunkOffset);
-    ZapNode * pHelperThunk = image->GetHelperThunk(CORINFO_HELP_EE_PRECODE_FIXUP);
-
-    image->FixupFieldToNode(this, offsetof(FixupPrecode, m_rel32),
-                            pHelperThunk, 0, IMAGE_REL_BASED_REL32);
-
-    // Set the actual chunk index
-    FixupPrecode * pNewPrecode = (FixupPrecode *)image->GetImagePointer(this);
-
-    size_t mdOffset   = mdChunkOffset - sizeof(MethodDescChunk);
-    size_t chunkIndex = mdOffset / MethodDesc::ALIGNMENT;
-    _ASSERTE(FitsInU1(chunkIndex));
-    pNewPrecode->m_MethodDescChunkIndex = (BYTE) chunkIndex;
-
-    // Fixup the base of MethodDescChunk
-    if (m_PrecodeChunkIndex == 0)
-    {
-        image->FixupFieldToNode(this, (BYTE *)GetBase() - (BYTE *)this,
-            pMDChunkNode, sizeof(MethodDescChunk));
-    }
-}
-#endif // FEATURE_NATIVE_IMAGE_GENERATION
-
 #endif // HAS_FIXUP_PRECODE
 
 #endif // !DACCESS_COMPILE
index 04c18d3..065630c 100644 (file)
@@ -14,7 +14,6 @@
 #include "jitinterface.h"
 #include "sigbuilder.h"
 #include "ngenhash.inl"
-#include "compile.h"
 
 #include "eventtrace.h"
 
@@ -722,47 +721,6 @@ void StubMethodHashTable::InsertMethodDesc(MethodDesc *pMD, MethodDesc *pStubMD)
     BaseInsertEntry(dwHash, pNewEntry);
 }
 
-#ifdef FEATURE_NATIVE_IMAGE_GENERATION
-// Save the hash table and any method descriptors referenced by it
-void StubMethodHashTable::Save(DataImage *image, CorProfileData *pProfileData)
-{
-    WRAPPER_NO_CONTRACT;
-    BaseSave(image, pProfileData);
-}
-
-void StubMethodHashTable::Fixup(DataImage *image)
-{
-    WRAPPER_NO_CONTRACT;
-    BaseFixup(image);
-}
-
-void StubMethodHashTable::FixupEntry(DataImage *pImage, StubMethodHashEntry_t *pEntry, void *pFixupBase, DWORD cbFixupOffset)
-{
-    WRAPPER_NO_CONTRACT;
-    pImage->FixupField(pFixupBase, cbFixupOffset + offsetof(StubMethodHashEntry_t, pMD), pEntry->GetMethod());
-    pImage->FixupField(pFixupBase, cbFixupOffset + offsetof(StubMethodHashEntry_t, pStubMD), pEntry->GetStubMethod());
-}
-
-bool StubMethodHashTable::ShouldSave(DataImage *pImage, StubMethodHashEntry_t *pEntry)
-{
-    STANDARD_VM_CONTRACT;
-
-    MethodDesc *pMD = pEntry->GetMethod();
-    if (pMD->GetClassification() == mcInstantiated)
-    {
-        // save entries only for "accepted" methods
-        if (!pImage->GetPreloader()->IsMethodInTransitiveClosureOfInstantiations(CORINFO_METHOD_HANDLE(pMD)))
-            return false;
-    }
-
-    // Save the entry only if the native code was successfully generated for the stub
-    if (pImage->GetCodeAddress(pEntry->GetStubMethod()) == NULL)
-        return false;
-
-    return true;
-}
-#endif // FEATURE_NATIVE_IMAGE_GENERATION
-
 #endif // !DACCESS_COMPILE
 
 #ifdef DACCESS_COMPILE
index 4506b78..4b304e8 100644 (file)
@@ -174,19 +174,6 @@ public:
 #ifndef DACCESS_COMPILE
     // Inserts a method-stub pair into the hash table
     VOID InsertMethodDesc(MethodDesc *pMD, MethodDesc *pStubMD);
-
-    void Save(DataImage *image, CorProfileData *profileData);
-    void Fixup(DataImage *image);
-
-    bool ShouldSave(DataImage *pImage, StubMethodHashEntry_t *pEntry);
-
-    bool IsHotEntry(StubMethodHashEntry_t *pEntry, CorProfileData *pProfileData)
-    { LIMITED_METHOD_CONTRACT; return true; }
-
-    bool SaveEntry(DataImage *pImage, CorProfileData *pProfileData, StubMethodHashEntry_t *pOldEntry, StubMethodHashEntry_t *pNewEntry, EntryMappingTable *pMap)
-    { LIMITED_METHOD_CONTRACT; return false; }
-
-    void FixupEntry(DataImage *pImage, StubMethodHashEntry_t *pEntry, void *pFixupBase, DWORD cbFixupOffset);
 #endif // !DACCESS_COMPILE
 
 #ifdef DACCESS_COMPILE
index e83e529..688def1 100644 (file)
@@ -306,169 +306,6 @@ Module *PersistentInlineTrackingMapNGen::GetModuleByIndex(DWORD index)
     return m_module->GetModuleFromIndexIfLoaded(index);
 }
 
-
-
-#ifndef DACCESS_COMPILE
-#ifdef FEATURE_NATIVE_IMAGE_GENERATION
-
-// This is a shared serialization routine used for both NGEN and R2R formats. If image != NULL the NGEN format is generated, otherwise the R2R format
-void SerializeInlineTrackingEntry(DataImage* image, SBuffer *inlinersBuffer, SArray<ZapInlineeRecord> *inlineeIndex, InlineTrackingEntry *entry)
-{
-    STANDARD_VM_CONTRACT;
-    // This call removes duplicates from inliners and makes sure they are sorted by module
-    entry->SortAndDeduplicate();
-    MethodInModule inlinee = entry->m_inlinee;
-    DWORD inlineeModuleZapIndex = 0;
-    if (image != NULL)
-    {
-        inlineeModuleZapIndex = image->GetModuleImportIndex(inlinee.m_module);
-    }
-    InlineSArray<MethodInModule, 3> &inliners = entry->m_inliners;
-    COUNT_T totalInlinersCount = inliners.GetCount();
-    _ASSERTE(totalInlinersCount > 0);
-
-    COUNT_T sameModuleCount;
-    // Going through all inliners and grouping them by their module, for each module we'll create
-    // an ZapInlineeRecord and encode inliners as bytes in inlinersBuffer.
-    for (COUNT_T thisModuleBegin = 0; thisModuleBegin < totalInlinersCount; thisModuleBegin += sameModuleCount)
-    {
-        Module *lastInlinerModule = inliners[thisModuleBegin].m_module;
-        DWORD lastInlinerModuleZapIndex = 0;
-        if (image != NULL)
-        {
-            lastInlinerModuleZapIndex = image->GetModuleImportIndex(lastInlinerModule);
-        }
-
-        // Counting how many inliners belong to this module
-        sameModuleCount = 1;
-        while (thisModuleBegin + sameModuleCount < totalInlinersCount &&
-            inliners[thisModuleBegin + sameModuleCount].m_module == lastInlinerModule)
-        {
-            sameModuleCount++;
-        }
-
-        // Saving module indexes and number of inliners
-        NibbleWriter inlinersStream;
-        if (image != NULL)
-        {
-            inlinersStream.WriteEncodedU32(inlineeModuleZapIndex);
-            inlinersStream.WriteEncodedU32(lastInlinerModuleZapIndex);
-        }
-        inlinersStream.WriteEncodedU32(sameModuleCount);
-
-        // Saving inliners RIDs, each new RID is represented as an adjustment (diff) to the previous one
-        RID prevMethodRid = 0;
-        for (COUNT_T i = thisModuleBegin; i < thisModuleBegin + sameModuleCount; i++)
-        {
-            RID methodRid = RidFromToken(inliners[i].m_methodDef);
-            _ASSERTE(methodRid >= prevMethodRid);
-            inlinersStream.WriteEncodedU32(methodRid - prevMethodRid);
-            prevMethodRid = methodRid;
-        }
-        inlinersStream.Flush();
-
-        // Copy output of NibbleWriter into a big buffer (inlinersBuffer) for inliners from the same module
-        // and create an InlineeRecord with correct offset
-        DWORD inlinersStreamSize;
-        const BYTE *inlinersStreamPtr = (const BYTE *)inlinersStream.GetBlob(&inlinersStreamSize);
-        ZapInlineeRecord record;
-        if (image != NULL)
-        {
-            record.InitForNGen(RidFromToken(inlinee.m_methodDef), inlinee.m_module->GetSimpleName());
-        }
-        else
-        {
-            record.InitForR2R(RidFromToken(inlinee.m_methodDef));
-        }
-        record.m_offset = inlinersBuffer->GetSize();
-        inlinersBuffer->Insert(inlinersBuffer->End(), SBuffer(SBuffer::Immutable, inlinersStreamPtr, inlinersStreamSize));
-        inlineeIndex->Append(record);
-    }
-}
-
-bool compare_entry(const InlineTrackingEntry* first, const InlineTrackingEntry* second)
-{
-    return first->m_inlinee < second->m_inlinee;
-}
-
-// This is a shared serialization routine used for both NGEN and R2R formats. If image != NULL the NGEN format is generated, otherwise the R2R format
-void SerializeTrackingMapBuffers(ZapHeap* heap, DataImage *image, SBuffer *inlinersBuffer, SArray<ZapInlineeRecord> *inlineeIndex, InlineTrackingMap* runtimeMap)
-{
-    STANDARD_VM_CONTRACT;
-    _ASSERTE(runtimeMap != NULL);
-
-    // Sort records from runtimeMap, because we need to make sure
-    // we save everything in deterministic order. Hashtable iteration is not deterministic.
-    COUNT_T runtimeMapCount = runtimeMap->GetCount();
-    InlineTrackingEntry **inlinees = new (heap) InlineTrackingEntry *[runtimeMapCount];
-    int index = 0;
-    for (auto iter = runtimeMap->Begin(), end = runtimeMap->End(); iter != end; ++iter)
-    {
-        inlinees[index++] = const_cast<InlineTrackingEntry *>(&*iter);
-    }
-    util::sort(inlinees, inlinees + runtimeMapCount, compare_entry);
-
-
-    // Iterate throught each inlinee record from the InlineTrackingMap
-    // and write corresponding records into inlineeIndex and inlinersBuffer
-    for (COUNT_T i = 0; i < runtimeMapCount; i++)
-    {
-        SerializeInlineTrackingEntry(image, inlinersBuffer, inlineeIndex, inlinees[i]);
-    }
-}
-
-
-
-void PersistentInlineTrackingMapNGen::Save(DataImage *image, InlineTrackingMap* runtimeMap)
-{
-    STANDARD_VM_CONTRACT;
-    _ASSERTE(image != NULL);
-    _ASSERTE(runtimeMap != NULL);
-
-    SArray<ZapInlineeRecord> inlineeIndex;
-    SBuffer inlinersBuffer;
-
-    SerializeTrackingMapBuffers(image->GetHeap(), image, &inlinersBuffer, &inlineeIndex, runtimeMap);
-
-    m_inlineeIndexSize = inlineeIndex.GetCount();
-    m_inlinersBufferSize = inlinersBuffer.GetSize();
-    _ASSERTE((m_inlineeIndexSize == 0) == (m_inlinersBufferSize == 0));
-
-    if (m_inlineeIndexSize != 0 && m_inlinersBufferSize != 0)
-    {
-        // Copy everything to the class fields, we didn't use the class fields for addition
-        // because we want to make sure we don't waste memory for buffer's amortized growth
-        m_inlineeIndex = new (image->GetHeap()) ZapInlineeRecord[m_inlineeIndexSize];
-        inlineeIndex.Copy(m_inlineeIndex, inlineeIndex.Begin(), m_inlineeIndexSize);
-
-        m_inlinersBuffer = new (image->GetHeap()) BYTE[m_inlinersBufferSize];
-        inlinersBuffer.Copy(m_inlinersBuffer, inlinersBuffer.Begin(), m_inlinersBufferSize);
-
-        //Sort m_inlineeIndex so we can later use binary search
-        util::sort(m_inlineeIndex, m_inlineeIndex + m_inlineeIndexSize);
-
-        //Making sure all this memory actually gets saved into NGEN image
-        image->StoreStructure(m_inlineeIndex, m_inlineeIndexSize * sizeof(m_inlineeIndex[0]), DataImage::ITEM_INLINING_DATA);
-        image->StoreStructure(m_inlinersBuffer, m_inlinersBufferSize, DataImage::ITEM_INLINING_DATA);
-    }
-
-    image->StoreStructure(this, sizeof(*this), DataImage::ITEM_INLINING_DATA);
-    LOG((LF_ZAP, LL_INFO100000,
-        "PersistentInlineTrackingMap saved. InlineeIndexSize: %d bytes, InlinersBufferSize: %d bytes\n",
-        m_inlineeIndexSize * sizeof(m_inlineeIndex[0]), m_inlinersBufferSize));
-}
-
-void PersistentInlineTrackingMapNGen::Fixup(DataImage *image)
-{
-    STANDARD_VM_CONTRACT;
-    image->FixupPointerField(this, offsetof(PersistentInlineTrackingMapNGen, m_module));
-    image->FixupPointerField(this, offsetof(PersistentInlineTrackingMapNGen, m_inlineeIndex));
-    image->FixupPointerField(this, offsetof(PersistentInlineTrackingMapNGen, m_inlinersBuffer));
-}
-
-#endif //FEATURE_NATIVE_IMAGE_GENERATION
-#endif //!DACCESS_COMPILE
-
 #ifdef FEATURE_READYTORUN
 
 struct InliningHeader
@@ -477,35 +314,6 @@ struct InliningHeader
 };
 
 #ifndef DACCESS_COMPILE
-#ifdef FEATURE_NATIVE_IMAGE_GENERATION
-
-
-
-void PersistentInlineTrackingMapR2R::Save(ZapHeap* pHeap, SBuffer* pSaveTarget, InlineTrackingMap* runtimeMap)
-{
-    STANDARD_VM_CONTRACT;
-    _ASSERTE(pSaveTarget != NULL);
-    _ASSERTE(runtimeMap != NULL);
-
-    SArray<ZapInlineeRecord> inlineeIndex;
-    SBuffer inlinersBuffer;
-
-    SerializeTrackingMapBuffers(pHeap, NULL, &inlinersBuffer, &inlineeIndex, runtimeMap);
-
-    InliningHeader header;
-    header.SizeOfInlineeIndex = inlineeIndex.GetCount() * sizeof(ZapInlineeRecord);
-
-    pSaveTarget->Insert(pSaveTarget->End(), SBuffer(SBuffer::Immutable, (const BYTE*) &header, sizeof(header)));
-    DWORD unused = 0;
-    pSaveTarget->Insert(pSaveTarget->End(), SBuffer(SBuffer::Immutable, (const BYTE*) inlineeIndex.GetElements(), header.SizeOfInlineeIndex));
-    pSaveTarget->Insert(pSaveTarget->End(), SBuffer(SBuffer::Immutable, (const BYTE*) inlinersBuffer, inlinersBuffer.GetSize()));
-
-    LOG((LF_ZAP, LL_INFO100000,
-        "PersistentInlineTrackingMap saved. InlineeIndexSize: %d bytes, InlinersBufferSize: %d bytes\n",
-        header.SizeOfInlineeIndex, inlinersBuffer.GetSize()));
-}
-
-#endif //FEATURE_NATIVE_IMAGE_GENERATION
 
 BOOL PersistentInlineTrackingMapR2R::TryLoad(Module* pModule, const BYTE* pBuffer, DWORD cbBuffer,
                                                 AllocMemTracker *pamTracker, PersistentInlineTrackingMapR2R** ppLoadedMap)
index 586b63b..80f2a25 100644 (file)
@@ -321,14 +321,7 @@ public:
     // runtime deserialization
     COUNT_T GetInliners(PTR_Module inlineeOwnerMod, mdMethodDef inlineeTkn, COUNT_T inlinersSize, MethodInModule inliners[], BOOL *incompleteData);
 
-    // compile-time serialization
-#ifndef DACCESS_COMPILE
-    void Save(DataImage *image, InlineTrackingMap* runtimeMap);
-    void Fixup(DataImage *image);
-
 private:
-#endif
-
     Module *GetModuleByIndex(DWORD index);
 
 };
@@ -357,13 +350,6 @@ public:
     static BOOL TryLoad(Module* pModule, const BYTE* pBuffer, DWORD cbBuffer, AllocMemTracker *pamTracker, PersistentInlineTrackingMapR2R** ppLoadedMap);
 #endif
     virtual COUNT_T GetInliners(PTR_Module inlineeOwnerMod, mdMethodDef inlineeTkn, COUNT_T inlinersSize, MethodInModule inliners[], BOOL *incompleteData);
-
-
-    // compile time serialization
-#ifndef DACCESS_COMPILE
-    static void Save(ZapHeap* pHeap, SBuffer *saveTarget, InlineTrackingMap* runtimeMap);
-#endif
-
 };
 
 typedef DPTR(PersistentInlineTrackingMapR2R) PTR_PersistentInlineTrackingMapR2R;
index 0e2f19b..9598655 100644 (file)
 #include "eeconfig.h"
 #include "generics.h"
 #include "typestring.h"
-#ifdef FEATURE_PREJIT
-#include "zapsig.h"
-#include "compile.h"
-#endif
 #include "ngenhash.inl"
 
 PTR_MethodDesc InstMethodHashEntry::GetMethod()
@@ -354,78 +350,6 @@ void InstMethodHashTable::InsertMethodDesc(MethodDesc *pMD)
     BaseInsertEntry(dwHash, pNewEntry);
 }
 
-#ifdef FEATURE_NATIVE_IMAGE_GENERATION
-
-#ifdef _DEBUG
-void InstMethodHashTableSeal(InstMethodHashTable * pTable) { WRAPPER_NO_CONTRACT; pTable->Seal(); }
-void InstMethodHashTableUnseal(InstMethodHashTable * pTable) { WRAPPER_NO_CONTRACT; pTable->Unseal(); }
-typedef  Wrapper<InstMethodHashTable *, InstMethodHashTableSeal, InstMethodHashTableUnseal> InstMethodHashTableSealHolder;
-#endif
-
-// Save the hash table and any method descriptors referenced by it
-void InstMethodHashTable::Save(DataImage *image, CorProfileData *pProfileData)
-{
-    CONTRACTL
-    {
-        STANDARD_VM_CHECK;
-        PRECONDITION(image->GetModule() == m_pModule);
-    }
-    CONTRACTL_END;
-
-#ifdef _DEBUG
-    // The table should not change while we are walking the buckets
-    InstMethodHashTableSealHolder h(this);
-#endif
-
-    BaseSave(image, pProfileData);
-}
-
-bool InstMethodHashTable::ShouldSave(DataImage *pImage, InstMethodHashEntry_t *pEntry)
-{
-    STANDARD_VM_CONTRACT;
-
-    return !!pImage->GetPreloader()->IsMethodInTransitiveClosureOfInstantiations(CORINFO_METHOD_HANDLE(pEntry->GetMethod()));
-}
-
-bool InstMethodHashTable::IsHotEntry(InstMethodHashEntry_t *pEntry, CorProfileData *pProfileData)
-{
-    LIMITED_METHOD_CONTRACT;
-
-    return true;
-}
-
-bool InstMethodHashTable::SaveEntry(DataImage *pImage, CorProfileData *pProfileData, InstMethodHashEntry_t *pOldEntry, InstMethodHashEntry_t *pNewEntry, EntryMappingTable *pMap)
-{
-    LIMITED_METHOD_CONTRACT;
-
-    return false;
-}
-
-void InstMethodHashTable::Fixup(DataImage *image)
-{
-    STANDARD_VM_CONTRACT;
-
-    BaseFixup(image);
-
-    image->ZeroPointerField(this, offsetof(InstMethodHashTable, m_pLoaderAllocator));
-
-#ifdef _DEBUG
-    // The persisted table should be unsealed.
-    InstMethodHashTable *pNewTable = (InstMethodHashTable*) image->GetImagePointer(this);
-    pNewTable->InitUnseal();
-#endif
-}
-
-void InstMethodHashTable::FixupEntry(DataImage *pImage, InstMethodHashEntry_t *pEntry, void *pFixupBase, DWORD cbFixupOffset)
-{
-    STANDARD_VM_CONTRACT;
-
-    pImage->FixupField(pFixupBase, cbFixupOffset + offsetof(InstMethodHashEntry_t, data), pEntry->GetMethod(), pEntry->GetFlags());
-
-    pEntry->GetMethod()->Fixup(pImage);
-}
-#endif // FEATURE_PREJIT
-
 #endif // #ifndef DACCESS_COMPILE
 
 #ifdef DACCESS_COMPILE
index 2a34012..dff9e2c 100644 (file)
@@ -120,20 +120,6 @@ public:
 
     BOOL ContainsMethodDesc(MethodDesc* pMD);
 
-#if defined(FEATURE_PREJIT) && !defined(DACCESS_COMPILE)
-    // Save the hash table and any method descriptors referenced by it
-    void Save(DataImage *image, CorProfileData *pProfileData);
-
-    // Record fixups required on the hash table
-    // Recurse into method descriptors referenced by it
-    void Fixup(DataImage *image);
-
-    bool ShouldSave(DataImage *pImage, InstMethodHashEntry_t *pEntry);
-    bool IsHotEntry(InstMethodHashEntry_t *pEntry, CorProfileData *pProfileData);
-    bool SaveEntry(DataImage *pImage, CorProfileData *pProfileData, InstMethodHashEntry_t *pOldEntry, InstMethodHashEntry_t *pNewEntry, EntryMappingTable *pMap);
-    void FixupEntry(DataImage *pImage, InstMethodHashEntry_t *pEntry, void *pFixupBase, DWORD cbFixupOffset);
-#endif // FEATURE_PREJIT && !DACCESS_COMPILE
-
     // An iterator for the table, currently used only by Module::Save
     struct Iterator
     {
index ea70bf8..e668841 100644 (file)
 #include "safemath.h"
 #include "threadstatics.h"
 
-#ifdef FEATURE_PREJIT
-#include "compile.h"
-#endif
-
 #ifdef HAVE_GCCOVER
 #include "gccover.h"
 #endif // HAVE_GCCOVER
index 692c35e..7b0cf9a 100644 (file)
 #include "gccover.h"
 #endif // HAVE_GCCOVER
 
-#ifdef FEATURE_PREJIT
-#include "compile.h"
-#include "corcompile.h"
-#endif // FEATURE_PREJIT
-
-
 #ifdef FEATURE_INTERPRETER
 #include "interpreter.h"
 #endif // FEATURE_INTERPRETER
@@ -3086,17 +3080,6 @@ void CEEInfo::ComputeRuntimeLookupForSharedGenericToken(DictionaryEntryKind entr
 
     BOOL fInstrument = FALSE;
 
-#ifdef FEATURE_NATIVE_IMAGE_GENERATION
-    // This will make sure that when IBC logging is turned on we will go through a version
-    // of JIT_GenericHandle which logs the access. Note that we still want the dictionaries
-    // to be populated to prepopulate the types at NGen time.
-    if (IsCompilingForNGen() &&
-        GetAppDomain()->ToCompilationDomain()->m_fForceInstrument)
-    {
-        fInstrument = TRUE;
-    }
-#endif // FEATURE_NATIVE_IMAGE_GENERATION
-
     if (pContextMD->RequiresInstMethodDescArg())
     {
         pResultLookup->lookupKind.runtimeLookupKind = CORINFO_LOOKUP_METHODPARAM;
@@ -4988,15 +4971,7 @@ void * CEEInfo::getArrayInitializationData(
 
     if (!pField                    ||
         !pField->IsRVA()           ||
-        (pField->LoadSize() < size)
-#ifdef FEATURE_NATIVE_IMAGE_GENERATION
-        // This will make sure that when IBC logging is on, the array initialization happens thru
-        // COMArrayInfo::InitializeArray. This gives a place to put the IBC probe that can help
-        // separate hold and cold RVA blobs.
-        || (IsCompilingForNGen() &&
-            GetAppDomain()->ToCompilationDomain()->m_fForceInstrument)
-#endif // FEATURE_NATIVE_IMAGE_GENERATION
-        )
+        (pField->LoadSize() < size))
     {
         result = NULL;
     }
@@ -6872,39 +6847,9 @@ void CEEInfo::setMethodAttribs (
 
     if (attribs & CORINFO_FLG_BAD_INLINEE)
     {
-        BOOL fCacheInliningHint = TRUE;
-
-#ifdef FEATURE_NATIVE_IMAGE_GENERATION
-        if (IsCompilationProcess())
-        {
-            // Since we are running managed code during NGen the inlining hint may be
-            // changing underneeth us as the code is JITed. We need to prevent the inlining
-            // hints from changing once we start to use them to place IL in the image.
-            if (!g_pCEECompileInfo->IsCachingOfInliningHintsEnabled())
-            {
-                fCacheInliningHint = FALSE;
-            }
-            else
-            {
-                // Don't cache inlining hints inside CoreLib during NGen of other assemblies,
-                // since CoreLib is loaded domain neutral and will survive worker process recycling,
-                // causing determinism problems.
-                Module * pModule = ftn->GetModule();
-                if (pModule->IsSystem() && pModule->HasNativeImage())
-                {
-                    fCacheInliningHint = FALSE;
-                }
-            }
-        }
-#endif
-
-        if (fCacheInliningHint)
-        {
-            ftn->SetNotInline(true);
-        }
+        ftn->SetNotInline(true);
     }
 
-#ifndef CROSSGEN_COMPILE
     if (attribs & (CORINFO_FLG_SWITCHED_TO_OPTIMIZED | CORINFO_FLG_SWITCHED_TO_MIN_OPT))
     {
         PrepareCodeConfig *config = GetThread()->GetCurrentPrepareCodeConfig();
@@ -6924,7 +6869,6 @@ void CEEInfo::setMethodAttribs (
 #endif
         }
     }
-#endif // !CROSSGEN_COMPILE
 
     EE_TO_JIT_TRANSITION();
 }
@@ -10036,22 +9980,12 @@ namespace
             _ASSERTE(pMD->IsNDirect() || pMD->HasUnmanagedCallersOnlyAttribute());
             if (pMD->IsNDirect())
             {
-#ifdef CROSSGEN_COMPILE
-                // Return CorInfoCallConvExtension::Managed to indicate that crossgen does not support handling UnmanagedCallConv
-                if (pMD->HasUnmanagedCallConvAttribute())
-                    return CorInfoCallConvExtension::Managed;
-#endif // CROSSGEN_COMPILE
-
                 CorInfoCallConvExtension unmanagedCallConv;
                 NDirect::GetCallingConvention_IgnoreErrors(pMD, &unmanagedCallConv, pSuppressGCTransition);
                 return unmanagedCallConv;
             }
             else
             {
-#ifdef CROSSGEN_COMPILE
-                _ASSERTE_MSG(false, "UnmanagedCallersOnly methods are not supported in crossgen and should be rejected before getting here.");
-                return CorInfoCallConvExtension::Managed;
-#else
                 CorInfoCallConvExtension unmanagedCallConv;
                 if (CallConv::TryGetCallingConventionFromUnmanagedCallersOnly(pMD, &unmanagedCallConv))
                 {
@@ -10062,7 +9996,6 @@ namespace
                     return unmanagedCallConv;
                 }
                 return CallConv::GetDefaultUnmanagedCallingConvention();
-#endif // CROSSGEN_COMPILE
             }
         }
         else
index c231cc8..5e86c32 100644 (file)
@@ -11,9 +11,6 @@
 #define JITINTERFACE_H
 
 #include "corjit.h"
-#ifdef FEATURE_PREJIT
-#include "corcompile.h"
-#endif // FEATURE_PREJIT
 
 #ifndef TARGET_UNIX
 #define MAX_UNCHECKED_OFFSET_FOR_NULL_OBJECT ((32*1024)-1)   // when generating JIT code
index db308ab..961d9c7 100644 (file)
 #include "versionresilienthashcode.h"
 #include "typehashingalgorithms.h"
 
-#ifdef FEATURE_PREJIT
-#include "compile.h"
-#endif
-
 #ifdef FEATURE_COMINTEROP
 #include "comcallablewrapper.h"
 #include "clrtocomcall.h"
@@ -2523,419 +2519,16 @@ BOOL MethodDesc::MayHaveNativeCode()
 
 #ifndef DACCESS_COMPILE
 
-#ifdef FEATURE_NATIVE_IMAGE_GENERATION
-//*******************************************************************************
-void MethodDesc::Save(DataImage *image)
-{
-    STANDARD_VM_CONTRACT;
-
-    // Initialize the DoesNotHaveEquivalentValuetypeParameters flag.
-    // If we fail to determine whether there is a type-equivalent struct parameter (eg. because there is a struct parameter
-    // defined in a missing dependency), then just continue. The reason we run this method is to initialize a flag that is
-    // only an optimization in any case, so it doesn't really matter if it fails.
-    EX_TRY
-    {
-        HasTypeEquivalentStructParameters();
-    }
-    EX_CATCH
-    {
-    }
-    EX_END_CATCH(RethrowTerminalExceptions);
-
-    _ASSERTE(image->GetModule()->GetAssembly() ==
-             GetAppDomain()->ToCompilationDomain()->GetTargetAssembly());
-
-#ifdef _DEBUG
-    SString s;
-    if (LoggingOn(LF_ZAP, LL_INFO10000))
-    {
-        TypeString::AppendMethodDebug(s, this);
-        LOG((LF_ZAP, LL_INFO10000, "  MethodDesc::Save %S (%p)\n", s.GetUnicode(), this));
-    }
-
-    if (m_pszDebugMethodName && !image->IsStored((void*) m_pszDebugMethodName))
-        image->StoreStructure((void *) m_pszDebugMethodName,
-                                        (ULONG)(strlen(m_pszDebugMethodName) + 1),
-                                        DataImage::ITEM_DEBUG,
-                                        1);
-    if (m_pszDebugClassName && !image->IsStored(m_pszDebugClassName))
-        image->StoreStructure((void *) m_pszDebugClassName,
-                                        (ULONG)(strlen(m_pszDebugClassName) + 1),
-                                        DataImage::ITEM_DEBUG,
-                                        1);
-    if (m_pszDebugMethodSignature && !image->IsStored(m_pszDebugMethodSignature))
-        image->StoreStructure((void *) m_pszDebugMethodSignature,
-                                        (ULONG)(strlen(m_pszDebugMethodSignature) + 1),
-                                        DataImage::ITEM_DEBUG,
-                                        1);
-#endif // _DEBUG
-
-    if (IsMethodImpl())
-    {
-        MethodImpl *pImpl = GetMethodImpl();
-
-        pImpl->Save(image);
-    }
-
-    if (IsNDirect())
-    {
-        EX_TRY
-        {
-            NDirect::PopulateNDirectMethodDesc((NDirectMethodDesc*)this);
-        }
-        EX_CATCH
-        {
-        }
-        EX_END_CATCH(RethrowTerminalExceptions);
-    }
-
-    if (HasStoredSig())
-    {
-        StoredSigMethodDesc *pNewSMD = (StoredSigMethodDesc*) this;
-
-        if (pNewSMD->HasStoredMethodSig())
-        {
-            if (!image->IsStored((void *) pNewSMD->m_pSig.GetValueMaybeNull()))
-            {
-                // Store signatures that doesn't need restore into a read only section.
-                DataImage::ItemKind sigItemKind = DataImage::ITEM_STORED_METHOD_SIG_READONLY;
-                // Place the signatures for stubs-as-il into hot/cold or writeable section
-                // here since Module::Arrange won't place them for us.
-                if (IsILStub())
-                {
-                    PTR_DynamicMethodDesc pDynamicMD = AsDynamicMethodDesc();
-                    // Forward PInvoke never touches the signature at runtime, only reverse pinvoke does.
-                    if (pDynamicMD->IsReverseStub())
-                    {
-                        sigItemKind = DataImage::ITEM_STORED_METHOD_SIG_READONLY_WARM;
-                    }
-
-                    if (FixupSignatureContainingInternalTypes(image,
-                        (PCCOR_SIGNATURE) pNewSMD->m_pSig.GetValueMaybeNull(),
-                        pNewSMD->m_cSig,
-                        true /*checkOnly if we will need to restore the signature without doing fixup*/))
-                    {
-                        sigItemKind = DataImage::ITEM_STORED_METHOD_SIG;
-                    }
-                }
-
-                image->StoreInternedStructure((void *) pNewSMD->m_pSig.GetValueMaybeNull(),
-                                         pNewSMD->m_cSig,
-                                         sigItemKind,
-                                         1);
-            }
-        }
-    }
-
-    if (GetMethodDictionary())
-    {
-        DWORD cSlotBytes;
-        DWORD cAllocBytes = DictionaryLayout::GetDictionarySizeFromLayout(GetNumGenericMethodArgs(), GetDictionaryLayout(), &cSlotBytes);
-        void* pBytes = GetMethodDictionary()->AsPtr();
-
-        LOG((LF_ZAP, LL_INFO10000, "    MethodDesc::Save dictionary size %d\n", cSlotBytes));
-        image->StoreStructure(pBytes, cSlotBytes,
-                            DataImage::ITEM_DICTIONARY_WRITEABLE);
-    }
-
-    if (HasMethodInstantiation())
-    {
-        InstantiatedMethodDesc* pIMD = AsInstantiatedMethodDesc();
-        if (pIMD->IMD_IsSharedByGenericMethodInstantiations() && !pIMD->m_pDictLayout.IsNull())
-        {
-            pIMD->m_pDictLayout.GetValue()->Save(image);
-        }
-    }
-    if (IsNDirect())
-    {
-        NDirectMethodDesc *pNMD = (NDirectMethodDesc *)this;
-
-        // Make sure that the marshaling required flag is computed
-        pNMD->MarshalingRequired();
-
-        if (!pNMD->IsQCall())
-        {
-            //Cache DefaultImportDllImportSearchPaths attribute.
-            pNMD->HasDefaultDllImportSearchPathsAttribute();
-        }
-
-        image->StoreStructure(pNMD->GetWriteableData(),
-                                sizeof(NDirectWriteableData),
-                                DataImage::ITEM_METHOD_DESC_COLD_WRITEABLE);
-
-#ifdef HAS_NDIRECT_IMPORT_PRECODE
-        if (!pNMD->MarshalingRequired())
-        {
-            // import thunk is only needed if the P/Invoke is inlinable
-#if defined(TARGET_X86) || defined(TARGET_AMD64)
-            image->SavePrecode(pNMD->GetNDirectImportThunkGlue(), pNMD, PRECODE_NDIRECT_IMPORT, DataImage::ITEM_METHOD_PRECODE_COLD);
-#else
-            image->StoreStructure(pNMD->GetNDirectImportThunkGlue(), sizeof(NDirectImportThunkGlue), DataImage::ITEM_METHOD_PRECODE_COLD);
-#endif
-        }
-#endif
-
-        if (pNMD->IsQCall())
-        {
-            // Make sure QCall id is cached
-            ECall::GetQCallImpl(this);
-            _ASSERTE(pNMD->GetECallID() != 0);
-        }
-        else
-        {
-            LPCUTF8 pszLibName = pNMD->GetLibName();
-            if (pszLibName && !image->IsStored(pszLibName))
-            {
-                image->StoreStructure(pszLibName,
-                                      (ULONG)strlen(pszLibName) + 1,
-                                      DataImage::ITEM_STORED_METHOD_NAME,
-                                      1);
-            }
-
-            LPCUTF8 pszEntrypointName = pNMD->GetEntrypointName();
-            if (pszEntrypointName != NULL && !image->IsStored(pszEntrypointName))
-            {
-                image->StoreStructure(pszEntrypointName,
-                                      (ULONG)strlen(pszEntrypointName) + 1,
-                                      DataImage::ITEM_STORED_METHOD_NAME,
-                                      1);
-            }
-        }
-    }
-
-    // ContainsGenericVariables() check is required to support generic FCalls
-    // (only instance methods on generic types constrained to "class" are allowed)
-    if(!IsUnboxingStub() && IsFCall() && !GetMethodTable()->ContainsGenericVariables())
-    {
-        // Make sure that ECall::GetFCallImpl is called for all methods. It has the
-        // side effect of adding the methoddesc to the reverse fcall hash table.
-        // MethodDesc::Save would eventually return to Module::Save which is where
-        // we would save the reverse fcall table also. Thus this call is effectively populating
-        // that reverse fcall table.
-
-        ECall::GetFCallImpl(this);
-    }
-
-    if (IsDynamicMethod())
-    {
-        DynamicMethodDesc *pDynMeth = AsDynamicMethodDesc();
-        if (!pDynMeth->m_pszMethodName.IsNull()
-            && !image->IsStored(pDynMeth->m_pszMethodName.GetValue()))
-            image->StoreStructure((void *) pDynMeth->m_pszMethodName.GetValue(),
-                                  (ULONG)(strlen(pDynMeth->m_pszMethodName.GetValue()) + 1),
-                                  DataImage::ITEM_STORED_METHOD_NAME,
-                                  1);
-    }
-
-#ifdef FEATURE_COMINTEROP
-    if (IsComPlusCall())
-    {
-        ComPlusCallMethodDesc *pCMD = (ComPlusCallMethodDesc *)this;
-        ComPlusCallInfo *pComInfo = pCMD->m_pComPlusCallInfo;
-
-        if (pComInfo != NULL && pComInfo->ShouldSave(image))
-        {
-            image->StoreStructure(pCMD->m_pComPlusCallInfo,
-                                  sizeof(ComPlusCallInfo),
-                                  DataImage::ITEM_METHOD_DESC_COLD_WRITEABLE);
-        }
-    }
-#endif // FEATURE_COMINTEROP
-
-    LOG((LF_ZAP, LL_INFO10000, "  MethodDesc::Save %S (%p) complete\n", s.GetUnicode(), this));
-
-}
-
-//*******************************************************************************
-bool MethodDesc::CanSkipDoPrestub (
-        MethodDesc *   callerMD,
-        CorInfoIndirectCallReason *pReason,
-        CORINFO_ACCESS_FLAGS    accessFlags/*=CORINFO_ACCESS_ANY*/)
-{
-    STANDARD_VM_CONTRACT;
-
-    CorInfoIndirectCallReason dummy;
-    if (pReason == NULL)
-        pReason = &dummy;
-    *pReason = CORINFO_INDIRECT_CALL_UNKNOWN;
-
-    // Only IL can be called directly
-    if (!IsIL())
-    {
-        // Pretend that IL stubs can be called directly. It allows us to not have
-        // useless precode for IL stubs
-        if (IsILStub())
-            return true;
-
-        if (IsNDirect())
-        {
-            *pReason = CORINFO_INDIRECT_CALL_PINVOKE;
-            return false;
-        }
-
-        *pReason = CORINFO_INDIRECT_CALL_EXOTIC;
-        return false;
-    }
-
-    // @todo generics: Until we fix the RVA map in zapper.cpp to be instantiation-aware, this must remain
-    CheckRestore();
-
-    // The wrapper stubs cannot be called directly (like any other stubs)
-    if (IsWrapperStub())
-    {
-        *pReason = CORINFO_INDIRECT_CALL_STUB;
-        return false;
-    }
-
-
-    // Check whether our methoddesc needs restore
-    if (NeedsRestore(GetAppDomain()->ToCompilationDomain()->GetTargetImage(), TRUE))
-    {
-        // The speculative method instantiations are restored by the time we call them via indirection.
-        if (!IsTightlyBoundToMethodTable() &&
-            GetLoaderModule() != Module::GetPreferredZapModuleForMethodDesc(this))
-        {
-            // We should only take this codepath to determine whether method needs prestub.
-            // Cross module calls should be filtered out by CanEmbedMethodHandle earlier.
-            _ASSERTE(GetLoaderModule() == GetAppDomain()->ToCompilationDomain()->GetTargetModule());
-
-            return true;
-        }
-
-        *pReason = CORINFO_INDIRECT_CALL_RESTORE_METHOD;
-        return false;
-    }
-
-    /////////////////////////////////////////////////////////////////////////////////
-    // The method looks OK. Check class restore.
-    MethodTable * calleeMT = GetMethodTable();
-
-    // If no need for restore, we can call direct.
-    if (!calleeMT->NeedsRestore(GetAppDomain()->ToCompilationDomain()->GetTargetImage()))
-        return true;
-
-    // We will override this with more specific reason if we find one
-    *pReason = CORINFO_INDIRECT_CALL_RESTORE;
-
-    /////////////////////////////////////////////////////////////////////////////////
-    // Try to prove that we have done the restore already.
-
-    // If we're calling the same class, we can assume already initialized.
-    if (callerMD != NULL)
-    {
-        MethodTable * callerMT = callerMD->GetMethodTable();
-        if (calleeMT == callerMT)
-            return true;
-    }
-
-    // If we are called on non-NULL this pointer, we can assume that class is initialized.
-    if (accessFlags & CORINFO_ACCESS_NONNULL)
-    {
-        // Static methods may be first time call on the class
-        if (IsStatic())
-        {
-            *pReason = CORINFO_INDIRECT_CALL_RESTORE_FIRST_CALL;
-        }
-        else
-        // In some cases, instance value type methods may be called before an instance initializer
-        if (calleeMT->IsValueType())
-        {
-            *pReason = CORINFO_INDIRECT_CALL_RESTORE_VALUE_TYPE;
-        }
-        else
-        {
-            // Otherwise, we conclude that there must have been at least one call on the class already.
-            return true;
-        }
-    }
-
-    // If child calls its parent class, we can assume already restored.
-    if (callerMD != NULL)
-    {
-        MethodTable * parentMT = callerMD->GetMethodTable()->GetParentMethodTable();
-        while (parentMT != NULL)
-        {
-            if (calleeMT == parentMT)
-                return true;
-            parentMT = parentMT->GetParentMethodTable();
-        }
-    }
-
-    // The speculative method table instantiations are restored by the time we call methods on them via indirection.
-    if (IsTightlyBoundToMethodTable() &&
-        calleeMT->GetLoaderModule() != Module::GetPreferredZapModuleForMethodTable(calleeMT))
-    {
-        // We should only take this codepath to determine whether method needs prestub.
-        // Cross module calls should be filtered out by CanEmbedMethodHandle earlier.
-        _ASSERTE(calleeMT->GetLoaderModule() == GetAppDomain()->ToCompilationDomain()->GetTargetModule());
-
-        return true;
-    }
-
-    // Note: Reason for restore has been initialized earlier
-    return false;
-}
-
-//*******************************************************************************
-BOOL MethodDesc::ComputeNeedsRestore(DataImage *image, TypeHandleList *pVisited, BOOL fAssumeMethodTableRestored/*=FALSE*/)
-{
-    STATIC_STANDARD_VM_CONTRACT;
-
-    _ASSERTE(GetAppDomain()->IsCompilationDomain());
-
-    MethodTable * pMT = GetMethodTable();
-
-    if (!IsTightlyBoundToMethodTable())
-    {
-        if (!image->CanEagerBindToMethodTable(pMT))
-            return TRUE;
-    }
-
-    if (!fAssumeMethodTableRestored)
-    {
-        if (pMT->ComputeNeedsRestore(image, pVisited))
-            return TRUE;
-    }
-
-    if (GetClassification() == mcInstantiated)
-    {
-        InstantiatedMethodDesc* pIMD = AsInstantiatedMethodDesc();
-
-        if (pIMD->IMD_IsWrapperStubWithInstantiations())
-        {
-            if (!image->CanPrerestoreEagerBindToMethodDesc(pIMD->m_pWrappedMethodDesc.GetValue(), pVisited))
-                return TRUE;
-
-            if (!image->CanHardBindToZapModule(pIMD->m_pWrappedMethodDesc.GetValue()->GetLoaderModule()))
-                return TRUE;
-        }
-
-        if (GetMethodDictionary())
-        {
-            if (GetMethodDictionary()->ComputeNeedsRestore(image, pVisited, GetNumGenericMethodArgs()))
-                return TRUE;
-        }
-    }
-
-    return FALSE;
-}
-
-
+#ifdef FEATURE_PREJIT
 //---------------------------------------------------------------------------------------
 //
-// Fixes up ET_INTERNAL TypeHandles in an IL stub signature. If at least one type is fixed up
-// marks the signature as "needs restore".  Also handles probing through generic instantiations
-// to find ET_INTERNAL TypeHandles used as the generic type or its parameters.
-//
+// Restores ET_INTERNAL TypeHandles in an IL stub signature.
 // This function will parse one type and expects psig to be pointing to the element type.  If
 // the type is a generic instantiation, we will recursively parse it.
 //
-bool
-FixupSignatureContainingInternalTypesParseType(
-    DataImage *     image,
-    PCCOR_SIGNATURE pOriginalSig,
-    SigPointer &    psig,
-    bool checkOnly)
+void
+RestoreSignatureContainingInternalTypesParseType(
+    SigPointer &    psig)
 {
     CONTRACTL
     {
@@ -2958,22 +2551,13 @@ FixupSignatureContainingInternalTypesParseType(
             void * ptr;
             IfFailThrow(psig.GetPointer(&ptr));
 
-            if (!checkOnly)
-            {
-                // Always force creation of fixup to avoid unaligned relocation entries. Unaligned
-                // relocations entries are perf hit for ASLR, and they even disable ASLR on ARM.
-                image->FixupTypeHandlePointerInPlace((BYTE *)pOriginalSig, (BYTE *)pTypeHandle - (BYTE *)pOriginalSig, TRUE);
-
-                // mark the signature so we know we'll need to restore it
-                BYTE *pImageSig = (BYTE *)image->GetImagePointer((PVOID)pOriginalSig);
-                *pImageSig |= IMAGE_CEE_CS_CALLCONV_NEEDSRESTORE;
-            }
+            Module::RestoreTypeHandlePointerRaw(pTypeHandle);
         }
-        return true;
+        break;
 
     case ELEMENT_TYPE_GENERICINST:
         {
-            bool needsRestore = FixupSignatureContainingInternalTypesParseType(image, pOriginalSig, psig, checkOnly);
+            RestoreSignatureContainingInternalTypesParseType(psig);
 
             // Get generic arg count
             uint32_t nArgs;
@@ -2981,44 +2565,35 @@ FixupSignatureContainingInternalTypesParseType(
 
             for (uint32_t i = 0; i < nArgs; i++)
             {
-                if (FixupSignatureContainingInternalTypesParseType(image, pOriginalSig, psig, checkOnly))
-                {
-                    needsRestore = true;
-                }
+                RestoreSignatureContainingInternalTypesParseType(psig);
             }
-
-            // Return.  We don't want to call psig.SkipExactlyOne in this case since we've manually
-            // parsed through the generic inst type.
-            return needsRestore;
         }
+        break;
 
     case ELEMENT_TYPE_BYREF:
     case ELEMENT_TYPE_PTR:
     case ELEMENT_TYPE_PINNED:
     case ELEMENT_TYPE_SZARRAY:
         // Call recursively
-        return FixupSignatureContainingInternalTypesParseType(image, pOriginalSig, psig, checkOnly);
+        RestoreSignatureContainingInternalTypesParseType(psig);
+        break;
 
     default:
         IfFailThrow(sigOrig.SkipExactlyOne());
         psig = sigOrig;
         break;
     }
-
-    return false;
 }
 
 //---------------------------------------------------------------------------------------
 //
-// Fixes up ET_INTERNAL TypeHandles in an IL stub signature. If at least one type is fixed up
-// marks the signature as "needs restore".
+// Restores ET_INTERNAL TypeHandles in an IL stub signature.
 //
-bool
-FixupSignatureContainingInternalTypes(
-    DataImage *     image,
+static
+void
+RestoreSignatureContainingInternalTypes(
     PCCOR_SIGNATURE pSig,
-    DWORD           cSig,
-    bool checkOnly)
+    DWORD           cSig)
 {
     CONTRACTL
     {
@@ -3027,154 +2602,35 @@ FixupSignatureContainingInternalTypes(
     }
     CONTRACTL_END;
 
-    uint32_t nArgs;
-    bool needsRestore = false;
-
-    SigPointer psig(pSig, cSig);
+    Volatile<BYTE> * pVolatileSig = (Volatile<BYTE> *)pSig;
+    if (*pVolatileSig & IMAGE_CEE_CS_CALLCONV_NEEDSRESTORE)
+    {
+        uint32_t nArgs;
+        SigPointer psig(pSig, cSig);
 
-    // Skip calling convention
-    BYTE uCallConv;
-    IfFailThrow(psig.GetByte(&uCallConv));
+        // Skip calling convention
+        BYTE uCallConv;
+        IfFailThrow(psig.GetByte(&uCallConv));
 
-    if ((uCallConv & IMAGE_CEE_CS_CALLCONV_MASK) == IMAGE_CEE_CS_CALLCONV_FIELD)
-    {
-        ThrowHR(META_E_BAD_SIGNATURE);
-    }
+        if ((uCallConv & IMAGE_CEE_CS_CALLCONV_MASK) == IMAGE_CEE_CS_CALLCONV_FIELD)
+        {
+            ThrowHR(META_E_BAD_SIGNATURE);
+        }
 
-    // Skip type parameter count
-    if (uCallConv & IMAGE_CEE_CS_CALLCONV_GENERIC)
-    {
-        IfFailThrow(psig.GetData(NULL));
-    }
+        // Skip type parameter count
+        if (uCallConv & IMAGE_CEE_CS_CALLCONV_GENERIC)
+        {
+            IfFailThrow(psig.GetData(NULL));
+        }
 
-    // Get arg count
-    IfFailThrow(psig.GetData(&nArgs));
+        // Get arg count
+        IfFailThrow(psig.GetData(&nArgs));
 
-    nArgs++;  // be sure to handle the return type
+        nArgs++;  // be sure to handle the return type
 
-    for (uint32_t i = 0; i < nArgs; i++)
-    {
-        if (FixupSignatureContainingInternalTypesParseType(image, pSig, psig, checkOnly))
+        for (ULONG i = 0; i < nArgs; i++)
         {
-            needsRestore = true;
-        }
-    }
-    return needsRestore;
-} // FixupSignatureContainingInternalTypes
-#endif // FEATURE_NATIVE_IMAGE_GENERATION
-
-#ifdef FEATURE_PREJIT
-//---------------------------------------------------------------------------------------
-//
-// Restores ET_INTERNAL TypeHandles in an IL stub signature.
-// This function will parse one type and expects psig to be pointing to the element type.  If
-// the type is a generic instantiation, we will recursively parse it.
-//
-void
-RestoreSignatureContainingInternalTypesParseType(
-    SigPointer &    psig)
-{
-    CONTRACTL
-    {
-        THROWS;
-        GC_TRIGGERS;
-    }
-    CONTRACTL_END;
-
-    SigPointer sigOrig = psig;
-
-    CorElementType eType;
-    IfFailThrow(psig.GetElemType(&eType));
-
-    switch (eType)
-    {
-    case ELEMENT_TYPE_INTERNAL:
-        {
-            TypeHandle * pTypeHandle = (TypeHandle *)psig.GetPtr();
-
-            void * ptr;
-            IfFailThrow(psig.GetPointer(&ptr));
-
-            Module::RestoreTypeHandlePointerRaw(pTypeHandle);
-        }
-        break;
-
-    case ELEMENT_TYPE_GENERICINST:
-        {
-            RestoreSignatureContainingInternalTypesParseType(psig);
-
-            // Get generic arg count
-            uint32_t nArgs;
-            IfFailThrow(psig.GetData(&nArgs));
-
-            for (uint32_t i = 0; i < nArgs; i++)
-            {
-                RestoreSignatureContainingInternalTypesParseType(psig);
-            }
-        }
-        break;
-
-    case ELEMENT_TYPE_BYREF:
-    case ELEMENT_TYPE_PTR:
-    case ELEMENT_TYPE_PINNED:
-    case ELEMENT_TYPE_SZARRAY:
-        // Call recursively
-        RestoreSignatureContainingInternalTypesParseType(psig);
-        break;
-
-    default:
-        IfFailThrow(sigOrig.SkipExactlyOne());
-        psig = sigOrig;
-        break;
-    }
-}
-
-//---------------------------------------------------------------------------------------
-//
-// Restores ET_INTERNAL TypeHandles in an IL stub signature.
-//
-static
-void
-RestoreSignatureContainingInternalTypes(
-    PCCOR_SIGNATURE pSig,
-    DWORD           cSig)
-{
-    CONTRACTL
-    {
-        THROWS;
-        GC_TRIGGERS;
-    }
-    CONTRACTL_END;
-
-    Volatile<BYTE> * pVolatileSig = (Volatile<BYTE> *)pSig;
-    if (*pVolatileSig & IMAGE_CEE_CS_CALLCONV_NEEDSRESTORE)
-    {
-        uint32_t nArgs;
-        SigPointer psig(pSig, cSig);
-
-        // Skip calling convention
-        BYTE uCallConv;
-        IfFailThrow(psig.GetByte(&uCallConv));
-
-        if ((uCallConv & IMAGE_CEE_CS_CALLCONV_MASK) == IMAGE_CEE_CS_CALLCONV_FIELD)
-        {
-            ThrowHR(META_E_BAD_SIGNATURE);
-        }
-
-        // Skip type parameter count
-        if (uCallConv & IMAGE_CEE_CS_CALLCONV_GENERIC)
-        {
-            IfFailThrow(psig.GetData(NULL));
-        }
-
-        // Get arg count
-        IfFailThrow(psig.GetData(&nArgs));
-
-        nArgs++;  // be sure to handle the return type
-
-        for (ULONG i = 0; i < nArgs; i++)
-        {
-            RestoreSignatureContainingInternalTypesParseType(psig);
+            RestoreSignatureContainingInternalTypesParseType(psig);
         }
 
         // clear the needs-restore bit
@@ -3207,745 +2663,6 @@ void DynamicMethodDesc::Restore()
 }
 #endif // FEATURE_PREJIT
 
-#ifdef FEATURE_NATIVE_IMAGE_GENERATION
-void DynamicMethodDesc::Fixup(DataImage* image)
-{
-    STANDARD_VM_CONTRACT;
-
-    DWORD cSigLen;
-    PCCOR_SIGNATURE pSig = GetStoredMethodSig(&cSigLen);
-
-    bool needsRestore = FixupSignatureContainingInternalTypes(image, pSig, cSigLen);
-
-    DynamicMethodDesc* pDynamicImageMD = (DynamicMethodDesc*)image->GetImagePointer(this);
-    pDynamicImageMD->SetSignatureNeedsRestore(needsRestore);
-}
-
-//---------------------------------------------------------------------------------------
-//
-void
-MethodDesc::Fixup(
-    DataImage * image)
-{
-    STANDARD_VM_CONTRACT;
-
-#ifdef _DEBUG
-    SString s;
-    if (LoggingOn(LF_ZAP, LL_INFO10000))
-    {
-        TypeString::AppendMethodDebug(s, this);
-        LOG((LF_ZAP, LL_INFO10000, "  MethodDesc::Fixup %S (%p)\n", s.GetUnicode(), this));
-    }
-#endif // _DEBUG
-
-#ifdef HAVE_GCCOVER
-    image->ZeroPointerField(this, offsetof(MethodDesc, m_GcCover));
-#endif // HAVE_GCCOVER
-
-#if _DEBUG
-    image->ZeroPointerField(this, offsetof(MethodDesc, m_pszDebugMethodName));
-    image->FixupPointerField(this, offsetof(MethodDesc, m_pszDebugMethodName));
-    image->FixupPointerField(this, offsetof(MethodDesc, m_pszDebugClassName));
-    image->FixupPointerField(this, offsetof(MethodDesc, m_pszDebugMethodSignature));
-    if (IsTightlyBoundToMethodTable())
-    {
-        image->FixupPointerField(this, offsetof(MethodDesc, m_pDebugMethodTable));
-    }
-    else
-    {
-        image->FixupMethodTablePointer(this, &m_pDebugMethodTable);
-    }
-#endif // _DEBUG
-
-    MethodDesc *pNewMD = (MethodDesc*) image->GetImagePointer(this);
-    PREFIX_ASSUME(pNewMD != NULL);
-
-    // Fixup the chunk header as part of the first MethodDesc in the chunk
-    if (pNewMD->m_chunkIndex == 0)
-    {
-        MethodDescChunk * pNewChunk = pNewMD->GetMethodDescChunk();
-
-        // For most MethodDescs we can always directly bind to the method table, because
-        // the MT is guaranteed to be in the same image.  In other words the MethodDescs and the
-        // MethodTable are guaranteed to be "tightly-bound", i.e. if one is present in
-        // an NGEN image then then other will be, and if one is used at runtime then
-        // the other will be too.  In these cases we always want to hardbind the pointer.
-        //
-        // However for generic method instantiations and other funky MDs managed by the InstMethHashTable
-        // the method table might be saved another module.  Whether these get "used" at runtime
-        // is a decision taken by the MethodDesc loading code in genmeth.cpp (FindOrCreateAssociatedMethodDesc),
-        // and is independent of the decision of whether the method table gets used.
-
-        if (IsTightlyBoundToMethodTable())
-        {
-            image->FixupRelativePointerField(pNewChunk, offsetof(MethodDescChunk, m_methodTable));
-        }
-        else
-        {
-            image->FixupMethodTablePointer(pNewChunk, &pNewChunk->m_methodTable);
-        }
-
-        if (!pNewChunk->m_next.IsNull())
-        {
-            image->FixupRelativePointerField(pNewChunk, offsetof(MethodDescChunk, m_next));
-        }
-    }
-
-    if (pNewMD->HasPrecode())
-    {
-        Precode* pPrecode = GetSavedPrecode(image);
-
-        // Fixup the precode if we have stored it
-        pPrecode->Fixup(image, this);
-    }
-
-    if (IsDynamicMethod())
-    {
-        image->ZeroPointerField(this, offsetof(DynamicMethodDesc, m_pResolver));
-        image->FixupRelativePointerField(this, offsetof(DynamicMethodDesc, m_pszMethodName));
-    }
-
-    if (GetClassification() == mcInstantiated)
-    {
-        InstantiatedMethodDesc* pIMD = AsInstantiatedMethodDesc();
-        BOOL needsRestore = NeedsRestore(image);
-
-        if (pIMD->IMD_IsWrapperStubWithInstantiations())
-        {
-            image->FixupMethodDescPointer(pIMD, &pIMD->m_pWrappedMethodDesc);
-        }
-        else
-        {
-            if (pIMD->IMD_IsSharedByGenericMethodInstantiations())
-            {
-                pIMD->m_pDictLayout.GetValue()->Fixup(image, TRUE);
-                image->FixupRelativePointerField(this, offsetof(InstantiatedMethodDesc, m_pDictLayout));
-            }
-        }
-
-        image->FixupPlainOrRelativePointerField((InstantiatedMethodDesc*) this, &InstantiatedMethodDesc::m_pPerInstInfo);
-
-        // Generic methods are dealt with specially to avoid encoding the formal method type parameters
-        if (IsTypicalMethodDefinition())
-        {
-            Instantiation inst = GetMethodInstantiation();
-            FixupPointer<TypeHandle> * pInst = inst.GetRawArgs();
-            for (DWORD j = 0; j < inst.GetNumArgs(); j++)
-            {
-                image->FixupTypeHandlePointer(pInst, &pInst[j]);
-            }
-        }
-        else if (GetMethodDictionary())
-        {
-            LOG((LF_JIT, LL_INFO10000, "GENERICS: Fixup dictionary for MD %s\n",
-                m_pszDebugMethodName ? m_pszDebugMethodName : "<no-name>"));
-            BOOL canSaveInstantiation = TRUE;
-            if (IsGenericMethodDefinition() && !IsTypicalMethodDefinition())
-            {
-                if (GetMethodDictionary()->ComputeNeedsRestore(image, NULL, GetNumGenericMethodArgs()))
-                {
-                    _ASSERTE(needsRestore);
-                    canSaveInstantiation = FALSE;
-                }
-                else
-                {
-                    Instantiation inst = GetMethodInstantiation();
-                    FixupPointer<TypeHandle> * pInst = inst.GetRawArgs();
-                    for (DWORD j = 0; j < inst.GetNumArgs(); j++)
-                    {
-                        TypeHandle th = pInst[j].GetValue();
-                        if (!th.IsNull())
-                        {
-                            if (!(image->CanEagerBindToTypeHandle(th) && image->CanHardBindToZapModule(th.GetLoaderModule())))
-                            {
-                                canSaveInstantiation = FALSE;
-                                needsRestore = TRUE;
-                                break;
-                            }
-                        }
-                    }
-                }
-            }
-            // We can only save the (non-instantiation) slots of
-            // the dictionary if we are compiling against a known and fixed
-            // dictionary layout.  That will only be the case if we can hardbind
-            // to the shared method desc (which owns the dictionary layout).
-            // If we are not a wrapper stub then
-            // there won't be any (non-instantiation) slots in the dictionary.
-            BOOL canSaveSlots =
-                pIMD->IMD_IsWrapperStubWithInstantiations() &&
-                image->CanEagerBindToMethodDesc(pIMD->IMD_GetWrappedMethodDesc());
-
-            GetMethodDictionary()->Fixup(image,
-                                         canSaveInstantiation,
-                                         canSaveSlots,
-                                         GetNumGenericMethodArgs(),
-                                         GetModule(),
-                                         GetDictionaryLayout());
-        }
-
-        if (needsRestore)
-        {
-            InstantiatedMethodDesc* pNewIMD = (InstantiatedMethodDesc *) image->GetImagePointer(this);
-            if (pNewIMD == NULL)
-                COMPlusThrowHR(E_POINTER);
-
-            pNewIMD->m_wFlags2 |= InstantiatedMethodDesc::Unrestored;
-        }
-    }
-
-    if (IsNDirect())
-    {
-        //
-        // For now, set method desc back into its pristine uninitialized state.
-        //
-
-        NDirectMethodDesc *pNMD = (NDirectMethodDesc *)this;
-
-        image->FixupPlainOrRelativePointerField(pNMD, &NDirectMethodDesc::ndirect, &decltype(NDirectMethodDesc::ndirect)::m_pWriteableData);
-
-        NDirectWriteableData *pWriteableData = pNMD->GetWriteableData();
-        NDirectImportThunkGlue *pImportThunkGlue = pNMD->GetNDirectImportThunkGlue();
-
-#ifdef HAS_NDIRECT_IMPORT_PRECODE
-        if (!pNMD->MarshalingRequired())
-        {
-            image->FixupField(pWriteableData, offsetof(NDirectWriteableData, m_pNDirectTarget),
-                pImportThunkGlue, Precode::GetEntryPointOffset());
-        }
-        else
-        {
-            image->ZeroPointerField(pWriteableData, offsetof(NDirectWriteableData, m_pNDirectTarget));
-        }
-#else // HAS_NDIRECT_IMPORT_PRECODE
-        PORTABILITY_WARNING("NDirectImportThunkGlue");
-#endif // HAS_NDIRECT_IMPORT_PRECODE
-
-        image->ZeroPointerField(this, offsetof(NDirectMethodDesc, ndirect.m_pNativeNDirectTarget));
-
-#ifdef HAS_NDIRECT_IMPORT_PRECODE
-        if (!pNMD->MarshalingRequired())
-        {
-            // import thunk is only needed if the P/Invoke is inlinable
-            image->FixupRelativePointerField(this, offsetof(NDirectMethodDesc, ndirect.m_pImportThunkGlue));
-            ((Precode*)pImportThunkGlue)->Fixup(image, this);
-        }
-        else
-        {
-            image->ZeroPointerField(this, offsetof(NDirectMethodDesc, ndirect.m_pImportThunkGlue));
-        }
-#else // HAS_NDIRECT_IMPORT_PRECODE
-        PORTABILITY_WARNING("NDirectImportThunkGlue");
-#endif // HAS_NDIRECT_IMPORT_PRECODE
-
-        if (!IsQCall())
-        {
-            image->FixupRelativePointerField(this, offsetof(NDirectMethodDesc, ndirect.m_pszLibName));
-            image->FixupRelativePointerField(this, offsetof(NDirectMethodDesc, ndirect.m_pszEntrypointName));
-        }
-
-        if (image->IsStored(pNMD->ndirect.m_pStubMD.GetValueMaybeNull()))
-            image->FixupRelativePointerField(this, offsetof(NDirectMethodDesc, ndirect.m_pStubMD));
-        else
-            image->ZeroPointerField(this, offsetof(NDirectMethodDesc, ndirect.m_pStubMD));
-    }
-
-    if (HasStoredSig())
-    {
-        image->FixupRelativePointerField(this, offsetof(StoredSigMethodDesc, m_pSig));
-
-        // The DynamicMethodDescs used for IL stubs may have a signature that refers to
-        // runtime types using ELEMENT_TYPE_INTERNAL.  We need to fixup these types here.
-        if (IsILStub())
-        {
-            PTR_DynamicMethodDesc pDynamicMD = AsDynamicMethodDesc();
-            pDynamicMD->Fixup(image);
-        }
-    }
-
-#ifdef FEATURE_COMINTEROP
-    if (IsComPlusCall())
-    {
-        ComPlusCallMethodDesc *pComPlusMD = (ComPlusCallMethodDesc*)this;
-        ComPlusCallInfo *pComInfo = pComPlusMD->m_pComPlusCallInfo;
-
-        if (image->IsStored(pComInfo))
-        {
-            image->FixupPointerField(pComPlusMD, offsetof(ComPlusCallMethodDesc, m_pComPlusCallInfo));
-            pComInfo->Fixup(image);
-        }
-        else
-        {
-            image->ZeroPointerField(pComPlusMD, offsetof(ComPlusCallMethodDesc, m_pComPlusCallInfo));
-        }
-    }
-    else if (IsGenericComPlusCall())
-    {
-        ComPlusCallInfo *pComInfo = AsInstantiatedMethodDesc()->IMD_GetComPlusCallInfo();
-        pComInfo->Fixup(image);
-    }
-#endif // FEATURE_COMINTEROP
-
-    SIZE_T currentSize = GetBaseSize();
-
-    //
-    // Save all optional members
-    //
-
-    if (HasNonVtableSlot())
-    {
-        FixupSlot(image, this, currentSize, IMAGE_REL_BASED_RelativePointer);
-
-        currentSize += sizeof(NonVtableSlot);
-    }
-
-    if (IsMethodImpl())
-    {
-        MethodImpl *pImpl = GetMethodImpl();
-
-        pImpl->Fixup(image, this, currentSize);
-
-        currentSize += sizeof(MethodImpl);
-    }
-
-    if (pNewMD->HasNativeCodeSlot())
-    {
-        ZapNode * pCodeNode = image->GetCodeAddress(this);
-        ZapNode * pFixupList = image->GetFixupList(this);
-
-        if (pCodeNode != NULL)
-            image->FixupFieldToNode(this, currentSize, pCodeNode, (pFixupList != NULL) ? 1 : 0, IMAGE_REL_BASED_RelativePointer);
-        currentSize += sizeof(NativeCodeSlot);
-
-        if (pFixupList != NULL)
-        {
-            image->FixupFieldToNode(this, currentSize, pFixupList, 0, IMAGE_REL_BASED_RelativePointer);
-            currentSize += sizeof(FixupListSlot);
-        }
-    }
-} // MethodDesc::Fixup
-
-//*******************************************************************************
-Precode* MethodDesc::GetSavedPrecode(DataImage *image)
-{
-    STANDARD_VM_CONTRACT;
-
-    Precode * pPrecode = (Precode *)image->LookupSurrogate(this);
-    _ASSERTE(pPrecode != NULL);
-    _ASSERTE(pPrecode->IsCorrectMethodDesc(this));
-
-    return pPrecode;
-}
-
-Precode* MethodDesc::GetSavedPrecodeOrNull(DataImage *image)
-{
-    STANDARD_VM_CONTRACT;
-
-    Precode * pPrecode = (Precode *)image->LookupSurrogate(this);
-    if (pPrecode == NULL)
-    {
-        return NULL;
-    }
-
-    _ASSERTE(pPrecode->IsCorrectMethodDesc(this));
-
-    return pPrecode;
-}
-
-//*******************************************************************************
-void MethodDesc::FixupSlot(DataImage *image, PVOID p, SSIZE_T offset, ZapRelocationType type)
-{
-    STANDARD_VM_CONTRACT;
-
-
-    Precode* pPrecode = GetSavedPrecodeOrNull(image);
-    if (pPrecode != NULL)
-    {
-        // Use the precode if we have decided to store it
-        image->FixupField(p, offset, pPrecode, Precode::GetEntryPointOffset(), type);
-    }
-    else
-    {
-        _ASSERTE(MayHaveNativeCode());
-        ZapNode *code = image->GetCodeAddress(this);
-        _ASSERTE(code != 0);
-        image->FixupFieldToNode(p, offset, code, Precode::GetEntryPointOffset(), type);
-    }
-}
-
-//*******************************************************************************
-SIZE_T MethodDesc::SaveChunk::GetSavedMethodDescSize(MethodInfo * pMethodInfo)
-{
-    LIMITED_METHOD_CONTRACT;
-    MethodDesc * pMD = pMethodInfo->m_pMD;
-
-    SIZE_T size = pMD->GetBaseSize();
-
-    if (pMD->HasNonVtableSlot())
-        size += sizeof(NonVtableSlot);
-
-    if (pMD->IsMethodImpl())
-        size += sizeof(MethodImpl);
-
-    if (pMethodInfo->m_fHasNativeCodeSlot)
-    {
-        size += sizeof(NativeCodeSlot);
-
-        if (pMethodInfo->m_fHasFixupList)
-            size += sizeof(FixupListSlot);
-    }
-
-#ifdef FEATURE_COMINTEROP
-    if (pMD->IsGenericComPlusCall())
-        size += sizeof(ComPlusCallInfo);
-#endif // FEATURE_COMINTEROP
-
-    _ASSERTE(size % MethodDesc::ALIGNMENT == 0);
-
-    return size;
-}
-
-//*******************************************************************************
-void MethodDesc::SaveChunk::SaveOneChunk(COUNT_T start, COUNT_T count, ULONG sizeOfMethodDescs, DWORD priority)
-{
-    STANDARD_VM_CONTRACT;
-    DataImage::ItemKind kind;
-
-    switch (priority)
-    {
-    case HotMethodDesc:
-        kind = DataImage::ITEM_METHOD_DESC_HOT;
-        break;
-    case WriteableMethodDesc:
-        kind = DataImage::ITEM_METHOD_DESC_HOT_WRITEABLE;
-        break;
-    case ColdMethodDesc:
-        kind = DataImage::ITEM_METHOD_DESC_COLD;
-        break;
-    case ColdWriteableMethodDesc:
-        kind = DataImage::ITEM_METHOD_DESC_COLD_WRITEABLE;
-        break;
-    default:
-        UNREACHABLE();
-    }
-
-    ULONG size = sizeOfMethodDescs + sizeof(MethodDescChunk);
-    ZapStoredStructure * pNode = m_pImage->StoreStructure(NULL, size, kind);
-
-    BYTE * pData = (BYTE *)m_pImage->GetImagePointer(pNode);
-
-    MethodDescChunk * pNewChunk = (MethodDescChunk *)pData;
-
-    // Bind the image space so we can use the regular fixup helpers
-    m_pImage->BindPointer(pNewChunk, pNode, 0);
-
-    pNewChunk->SetMethodTable(m_methodInfos[start].m_pMD->GetMethodTable());
-
-    pNewChunk->SetIsZapped();
-    pNewChunk->SetTokenRange(GetTokenRange(m_methodInfos[start].m_pMD->GetMemberDef()));
-
-    pNewChunk->SetSizeAndCount(sizeOfMethodDescs, count);
-
-    Precode::SaveChunk precodeSaveChunk; // Helper for saving precodes in chunks
-
-    ULONG offset = sizeof(MethodDescChunk);
-    for (COUNT_T i = 0; i < count; i++)
-    {
-        MethodInfo * pMethodInfo = &(m_methodInfos[start + i]);
-        MethodDesc * pMD = pMethodInfo->m_pMD;
-
-        m_pImage->BindPointer(pMD, pNode, offset);
-
-        pMD->Save(m_pImage);
-
-        MethodDesc * pNewMD = (MethodDesc *)(pData + offset);
-
-        CopyMemory(pNewMD, pMD, pMD->GetBaseSize());
-
-        if (pMD->IsMethodImpl())
-            CopyMemory(pNewMD->GetMethodImpl(), pMD->GetMethodImpl(), sizeof(MethodImpl));
-        else
-            pNewMD->m_wFlags &= ~mdcMethodImpl;
-
-        pNewMD->m_chunkIndex = (BYTE) ((offset - sizeof(MethodDescChunk)) / MethodDesc::ALIGNMENT);
-        _ASSERTE(pNewMD->GetMethodDescChunk() == pNewChunk);
-
-        pNewMD->m_bFlags2 |= enum_flag2_HasStableEntryPoint;
-        if (pMethodInfo->m_fHasPrecode)
-        {
-            precodeSaveChunk.Save(m_pImage, pMD);
-            pNewMD->m_bFlags2 |= enum_flag2_HasPrecode;
-        }
-        else
-        {
-            pNewMD->m_bFlags2 &= ~enum_flag2_HasPrecode;
-        }
-
-        if (pMethodInfo->m_fHasNativeCodeSlot)
-        {
-            pNewMD->m_wFlags |= mdcHasNativeCodeSlot;
-        }
-        else
-        {
-            pNewMD->m_wFlags &= ~mdcHasNativeCodeSlot;
-        }
-
-#ifdef FEATURE_COMINTEROP
-        if (pMD->IsGenericComPlusCall())
-        {
-            ComPlusCallInfo *pComInfo = pMD->AsInstantiatedMethodDesc()->IMD_GetComPlusCallInfo();
-
-            CopyMemory(pNewMD->AsInstantiatedMethodDesc()->IMD_GetComPlusCallInfo(), pComInfo, sizeof(ComPlusCallInfo));
-
-            m_pImage->BindPointer(pComInfo, pNode, offset + ((BYTE *)pComInfo - (BYTE *)pMD));
-        }
-#endif // FEATURE_COMINTEROP
-
-        pNewMD->PrecomputeNameHash();
-
-        offset += GetSavedMethodDescSize(pMethodInfo);
-    }
-    _ASSERTE(offset == sizeOfMethodDescs + sizeof(MethodDescChunk));
-
-    precodeSaveChunk.Flush(m_pImage);
-
-    if (m_methodInfos[start].m_pMD->IsTightlyBoundToMethodTable())
-    {
-        if (m_pLastChunk != NULL)
-        {
-            m_pLastChunk->m_next.SetValue(pNewChunk);
-        }
-        else
-        {
-            _ASSERTE(m_pFirstNode == NULL);
-            m_pFirstNode = pNode;
-        }
-        m_pLastChunk = pNewChunk;
-    }
-}
-
-//*******************************************************************************
-void MethodDesc::SaveChunk::Append(MethodDesc * pMD)
-{
-    STANDARD_VM_CONTRACT;
-#ifdef _DEBUG
-    if (!m_methodInfos.IsEmpty())
-    {
-        // Verify that all MethodDescs in the chunk are alike
-        MethodDesc * pFirstMD = m_methodInfos[0].m_pMD;
-
-        _ASSERTE(pFirstMD->GetMethodTable() == pMD->GetMethodTable());
-        _ASSERTE(pFirstMD->IsTightlyBoundToMethodTable() == pMD->IsTightlyBoundToMethodTable());
-    }
-    _ASSERTE(!m_pImage->IsStored(pMD));
-#endif
-
-    MethodInfo method;
-    method.m_pMD = pMD;
-
-    BYTE priority = HotMethodDesc;
-
-    // We only write into mcInstantiated methoddescs to mark them as restored
-    if (pMD->NeedsRestore(m_pImage, TRUE) && pMD->GetClassification() == mcInstantiated)
-        priority |= WriteableMethodDesc; // writeable
-
-    //
-    // Determines whether the method desc should be considered hot, based
-    // on a bitmap that contains entries for hot method descs.  At this
-    // point the only cold method descs are those not in the bitmap.
-    //
-    if ((m_pImage->GetMethodProfilingFlags(pMD) & (1 << ReadMethodDesc)) == 0)
-        priority |= ColdMethodDesc; // cold
-
-    // We can have more priorities here in the future to scale well
-    // for many IBC training scenarios.
-
-    method.m_priority = priority;
-
-    // Save the precode if we have no directly callable code
-    method.m_fHasPrecode = !m_pImage->CanDirectCall(pMD);
-
-    // Determine optional slots that are going to be saved
-    if (method.m_fHasPrecode)
-    {
-        method.m_fHasNativeCodeSlot = pMD->MayHaveNativeCode();
-
-        if (method.m_fHasNativeCodeSlot)
-        {
-            method.m_fHasFixupList = (m_pImage->GetFixupList(pMD) != NULL);
-        }
-        else
-        {
-            _ASSERTE(m_pImage->GetFixupList(pMD) == NULL);
-            method.m_fHasFixupList = FALSE;
-        }
-    }
-    else
-    {
-        method.m_fHasNativeCodeSlot = FALSE;
-
-        _ASSERTE(m_pImage->GetFixupList(pMD) == NULL);
-        method.m_fHasFixupList = FALSE;
-    }
-
-    m_methodInfos.Append(method);
-}
-
-//*******************************************************************************
-int __cdecl MethodDesc::SaveChunk::MethodInfoCmp(const void* a_, const void* b_)
-{
-    LIMITED_METHOD_CONTRACT;
-    // Sort by priority as primary key and token as secondary key
-    MethodInfo * a = (MethodInfo *)a_;
-    MethodInfo * b = (MethodInfo *)b_;
-
-    int priorityDiff = (int)(a->m_priority - b->m_priority);
-    if (priorityDiff != 0)
-        return priorityDiff;
-
-    int tokenDiff = (int)(a->m_pMD->GetMemberDef_NoLogging() - b->m_pMD->GetMemberDef_NoLogging());
-    if (tokenDiff != 0)
-        return tokenDiff;
-
-    // Place unboxing stubs first, code:MethodDesc::FindOrCreateAssociatedMethodDesc depends on this invariant
-    int unboxingDiff = (int)(b->m_pMD->IsUnboxingStub() - a->m_pMD->IsUnboxingStub());
-    return unboxingDiff;
-}
-
-//*******************************************************************************
-ZapStoredStructure * MethodDesc::SaveChunk::Save()
-{
-    // Sort by priority as primary key and token as secondary key
-    qsort (&m_methodInfos[0],           // start of array
-           m_methodInfos.GetCount(),    // array size in elements
-           sizeof(MethodInfo),          // element size in bytes
-           MethodInfoCmp);              // comparer function
-
-    DWORD currentPriority = NoFlags;
-    int currentTokenRange = -1;
-    int nextStart = 0;
-    SIZE_T sizeOfMethodDescs = 0;
-
-    //
-    // Go over all MethodDescs and create smallest number of chunks possible
-    //
-
-    for (COUNT_T i = 0; i < m_methodInfos.GetCount(); i++)
-    {
-        MethodInfo * pMethodInfo = &(m_methodInfos[i]);
-        MethodDesc * pMD = pMethodInfo->m_pMD;
-
-        DWORD priority = pMethodInfo->m_priority;
-        int tokenRange = GetTokenRange(pMD->GetMemberDef());
-
-        SIZE_T size = GetSavedMethodDescSize(pMethodInfo);
-
-        // Bundle that has to be in same chunk
-        SIZE_T bundleSize = size;
-
-        if (pMD->IsUnboxingStub() && pMD->IsTightlyBoundToMethodTable())
-        {
-            // Wrapped method desc has to immediately follow unboxing stub, and both has to be in one chunk
-            _ASSERTE(m_methodInfos[i+1].m_pMD->GetMemberDef() == m_methodInfos[i].m_pMD->GetMemberDef());
-
-            // Make sure that both wrapped method desc and unboxing stub will fit into same chunk
-            bundleSize += GetSavedMethodDescSize(&m_methodInfos[i+1]);
-        }
-
-        if (priority != currentPriority ||
-            tokenRange != currentTokenRange ||
-            sizeOfMethodDescs + bundleSize > MethodDescChunk::MaxSizeOfMethodDescs)
-        {
-            if (sizeOfMethodDescs != 0)
-            {
-                SaveOneChunk(nextStart, i - nextStart, sizeOfMethodDescs, currentPriority);
-                nextStart = i;
-            }
-
-            currentPriority = priority;
-            currentTokenRange = tokenRange;
-            sizeOfMethodDescs = 0;
-        }
-
-        sizeOfMethodDescs += size;
-    }
-
-    if (sizeOfMethodDescs != 0)
-        SaveOneChunk(nextStart, m_methodInfos.GetCount() - nextStart, sizeOfMethodDescs, currentPriority);
-
-    return m_pFirstNode;
-}
-
-#ifdef FEATURE_COMINTEROP
-BOOL ComPlusCallInfo::ShouldSave(DataImage *image)
-{
-    STANDARD_VM_CONTRACT;
-
-    MethodDesc * pStubMD = m_pStubMD.GetValueMaybeNull();
-
-    // Note that pStubMD can be regular IL methods desc for stubs implemented by IL
-    return (pStubMD != NULL) && image->CanEagerBindToMethodDesc(pStubMD) && image->CanHardBindToZapModule(pStubMD->GetLoaderModule());
-}
-
-void ComPlusCallInfo::Fixup(DataImage *image)
-{
-    STANDARD_VM_CONTRACT;
-
-    // It is not worth the complexity to do full pre-initialization for WinRT delegates
-    if (m_pInterfaceMT != NULL && m_pInterfaceMT->IsDelegate())
-    {
-        if (!m_pStubMD.IsNull())
-        {
-            image->FixupRelativePointerField(this, offsetof(ComPlusCallInfo, m_pStubMD));
-        }
-        else
-        {
-            image->ZeroPointerField(this, offsetof(ComPlusCallInfo, m_pStubMD));
-        }
-
-        image->ZeroPointerField(this, offsetof(ComPlusCallInfo, m_pInterfaceMT));
-        image->ZeroPointerField(this, offsetof(ComPlusCallInfo, m_pILStub));
-        return;
-    }
-
-    if (m_pInterfaceMT != NULL)
-    {
-        if (image->CanEagerBindToTypeHandle(m_pInterfaceMT) && image->CanHardBindToZapModule(m_pInterfaceMT->GetLoaderModule()))
-        {
-           image->FixupPointerField(this, offsetof(ComPlusCallInfo, m_pInterfaceMT));
-        }
-        else
-        {
-           image->ZeroPointerField(this, offsetof(ComPlusCallInfo, m_pInterfaceMT));
-        }
-    }
-
-    if (!m_pStubMD.IsNull())
-    {
-        image->FixupRelativePointerField(this, offsetof(ComPlusCallInfo, m_pStubMD));
-
-        MethodDesc * pStubMD = m_pStubMD.GetValue();
-        ZapNode * pCode = pStubMD->IsDynamicMethod() ? image->GetCodeAddress(pStubMD) : NULL;
-        if (pCode != NULL)
-        {
-            image->FixupFieldToNode(this, offsetof(ComPlusCallInfo, m_pILStub), pCode ARM_ARG(THUMB_CODE));
-        }
-        else
-        {
-            image->ZeroPointerField(this, offsetof(ComPlusCallInfo, m_pILStub));
-        }
-    }
-    else
-    {
-        image->ZeroPointerField(this, offsetof(ComPlusCallInfo, m_pStubMD));
-
-        image->ZeroPointerField(this, offsetof(ComPlusCallInfo, m_pILStub));
-    }
-}
-#endif // FEATURE_COMINTEROP
-
-#endif // FEATURE_NATIVE_IMAGE_GENERATION
-
 #endif // !DACCESS_COMPILE
 
 //*******************************************************************************
index c929cbe..e6ed80c 100644 (file)
@@ -314,11 +314,6 @@ public:
 
     Precode* GetOrCreatePrecode();
 
-#ifdef FEATURE_PREJIT
-    Precode *     GetSavedPrecode(DataImage *image);
-    Precode *     GetSavedPrecodeOrNull(DataImage *image);
-#endif // FEATURE_PREJIT
-
     // Given a code address return back the MethodDesc whenever possible
     //
     static MethodDesc *  GetMethodDescFromStubAddr(PCODE addr, BOOL fSpeculative = FALSE);
@@ -1670,79 +1665,6 @@ public:
     //================================================================
     // Precompilation (NGEN)
 
-    void Save(DataImage *image);
-    void Fixup(DataImage *image);
-    void FixupSlot(DataImage *image, PVOID p, SSIZE_T offset, ZapRelocationType type = IMAGE_REL_BASED_PTR);
-
-    //
-    // Helper class used to regroup MethodDesc chunks before saving them into NGen image.
-    // The regrouping takes into account IBC data and optional NGen-specific MethodDesc members.
-    //
-    class SaveChunk
-    {
-        DataImage * m_pImage;
-
-        ZapStoredStructure * m_pFirstNode;
-        MethodDescChunk * m_pLastChunk;
-
-        typedef enum _MethodPriorityEnum
-        {
-            NoFlags = -1,
-            HotMethodDesc = 0x0,
-            WriteableMethodDesc = 0x1,
-            ColdMethodDesc = 0x2,
-            ColdWriteableMethodDesc=  ColdMethodDesc | WriteableMethodDesc
-
-        } MethodPriorityEnum;
-
-        struct MethodInfo
-        {
-            MethodDesc * m_pMD;
-            //MethodPriorityEnum
-            BYTE m_priority;
-
-            BOOL m_fHasPrecode:1;
-            BOOL m_fHasNativeCodeSlot:1;
-            BOOL m_fHasFixupList:1;
-        };
-
-        InlineSArray<MethodInfo, 20> m_methodInfos;
-
-        static int __cdecl MethodInfoCmp(const void* a_, const void* b_);
-
-        SIZE_T GetSavedMethodDescSize(MethodInfo * pMethodInfo);
-
-        void SaveOneChunk(COUNT_T start, COUNT_T count, ULONG size, DWORD priority);
-
-    public:
-        SaveChunk(DataImage * image)
-            : m_pImage(image), m_pFirstNode(NULL), m_pLastChunk(NULL)
-        {
-            LIMITED_METHOD_CONTRACT;
-        }
-
-        void Append(MethodDesc * pMD);
-
-        ZapStoredStructure * Save();
-    };
-
-    bool CanSkipDoPrestub(MethodDesc * callerMD,
-                          CorInfoIndirectCallReason *pReason,
-                          CORINFO_ACCESS_FLAGS  accessFlags = CORINFO_ACCESS_ANY);
-
-    // This is different from !IsRestored() in that it checks if restoring
-    // will ever be needed for this ngened data-structure.
-    // This is to be used at ngen time of a dependent module to determine
-    // if it can be accessed directly, or if the restoring mechanism needs
-    // to be hooked in.
-    BOOL NeedsRestore(DataImage *image, BOOL fAssumeMethodTableRestored = FALSE)
-    {
-        WRAPPER_NO_CONTRACT;
-        return ComputeNeedsRestore(image, NULL, fAssumeMethodTableRestored);
-    }
-
-    BOOL ComputeNeedsRestore(DataImage *image, TypeHandleList *pVisited, BOOL fAssumeMethodTableRestored = FALSE);
-
     //
     // After the zapper compiles all code in a module it may attempt
     // to populate entries in all dictionaries
@@ -2848,7 +2770,6 @@ public:
     }
 
     void Restore();
-    void Fixup(DataImage* image);
     //
     // following implementations defined in DynamicMethod.cpp
     //
@@ -3425,11 +3346,6 @@ struct ComPlusCallInfo
 
     // This field gets set only when this MethodDesc is marked as PreImplemented
     RelativePointer<PTR_MethodDesc> m_pStubMD;
-
-#ifdef FEATURE_PREJIT
-    BOOL ShouldSave(DataImage *image);
-    void Fixup(DataImage *image);
-#endif
 };
 
 
index 4a558b7..60ad60d 100644 (file)
@@ -211,54 +211,6 @@ void MethodImpl::SetData(DWORD* slots, mdToken* tokens, RelativePointer<MethodDe
     }
 }
 
-#ifdef FEATURE_NATIVE_IMAGE_GENERATION
-void MethodImpl::Save(DataImage *image)
-{
-    STANDARD_VM_CONTRACT;
-
-    DWORD size = GetSize();
-    _ASSERTE(size > 0);
-
-    image->StoreStructure(pdwSlots.GetValue(), (size+1)*sizeof(DWORD)+size*sizeof(mdToken),
-                                    DataImage::ITEM_METHOD_DESC_COLD,
-                                    sizeof(DWORD));
-    image->StoreStructure(pImplementedMD.GetValue(), size*sizeof(RelativePointer<MethodDesc*>),
-                                    DataImage::ITEM_METHOD_DESC_COLD,
-                                    sizeof(MethodDesc*));
-}
-
-void MethodImpl::Fixup(DataImage *image, PVOID p, SSIZE_T offset)
-{
-    STANDARD_VM_CONTRACT;
-
-    DWORD size = GetSize();
-    _ASSERTE(size > 0);
-
-    for (DWORD iMD = 0; iMD < size; iMD++)
-    {
-        // <TODO> Why not use FixupMethodDescPointer? </TODO>
-        // <TODO> Does it matter if the MethodDesc needs a restore? </TODO>
-
-        RelativePointer<MethodDesc *> *pRelPtr = pImplementedMD.GetValue();
-        MethodDesc * pMD = pRelPtr[iMD].GetValueMaybeNull();
-
-        if (image->CanEagerBindToMethodDesc(pMD) &&
-            image->CanHardBindToZapModule(pMD->GetLoaderModule()))
-        {
-            image->FixupRelativePointerField(pImplementedMD.GetValue(), iMD * sizeof(RelativePointer<MethodDesc *>));
-        }
-        else
-        {
-            image->ZeroPointerField(pImplementedMD.GetValue(), iMD * sizeof(RelativePointer<MethodDesc *>));
-        }
-    }
-
-    image->FixupRelativePointerField(p, offset + offsetof(MethodImpl, pdwSlots));
-    image->FixupRelativePointerField(p, offset + offsetof(MethodImpl, pImplementedMD));
-}
-
-#endif // FEATURE_NATIVE_IMAGE_GENERATION
-
 #endif //!DACCESS_COMPILE
 
 #ifdef DACCESS_COMPILE
index 4184061..0dc557b 100644 (file)
@@ -137,12 +137,6 @@ public:
     void EnumMemoryRegions(CLRDataEnumMemoryFlags flags);
 #endif
 
-#ifdef FEATURE_PREJIT
-    void Save(DataImage *image);
-    void Fixup(DataImage *image, PVOID p, SSIZE_T offset);
-#endif // FEATURE_PREJIT
-
-
     // Returns the method desc for the replaced slot;
     PTR_MethodDesc FindMethodDesc(DWORD slot, PTR_MethodDesc defaultReturn);
 
index 1007f0b..1ba51e6 100644 (file)
@@ -1040,35 +1040,6 @@ void MethodTable::InitializeExtraInterfaceInfo(PVOID pInfo)
 #endif // _DEBUG
 }
 
-#ifdef FEATURE_NATIVE_IMAGE_GENERATION
-// Ngen support.
-void MethodTable::SaveExtraInterfaceInfo(DataImage *pImage)
-{
-    STANDARD_VM_CONTRACT;
-
-    // No extra data to save if the number of interfaces is below the threshhold -- there is either no data or
-    // it all fits into the optional members inline.
-    if (GetNumInterfaces() <= kInlinedInterfaceInfoThreshhold)
-        return;
-
-    pImage->StoreStructure((LPVOID)*GetExtraInterfaceInfoPtr(),
-                           GetExtraInterfaceInfoSize(GetNumInterfaces()),
-                           DataImage::ITEM_INTERFACE_MAP);
-}
-
-void MethodTable::FixupExtraInterfaceInfo(DataImage *pImage)
-{
-    STANDARD_VM_CONTRACT;
-
-    // No pointer to extra data to fixup if the number of interfaces is below the threshhold -- there is
-    // either no data or it all fits into the optional members inline.
-    if (GetNumInterfaces() <= kInlinedInterfaceInfoThreshhold)
-        return;
-
-    pImage->FixupPointerField(this, (BYTE*)GetExtraInterfaceInfoPtr() - (BYTE*)this);
-}
-#endif // FEATURE_NATIVE_IMAGE_GENERATION
-
 // Define a macro that generates a mask for a given bit in a TADDR correctly on either 32 or 64 bit platforms.
 #ifdef HOST_64BIT
 #define SELECT_TADDR_BIT(_index) (1ULL << (_index))
@@ -3861,1244 +3832,173 @@ void MethodTable::GetSavedExtent(TADDR *pStart, TADDR *pEnd)
     *pEnd = end;
 }
 
-#ifdef FEATURE_NATIVE_IMAGE_GENERATION
-
-#ifndef DACCESS_COMPILE
-
-BOOL MethodTable::CanInternVtableChunk(DataImage *image, VtableIndirectionSlotIterator it)
+//==========================================================================================
+void MethodTable::CheckRestore()
 {
-    STANDARD_VM_CONTRACT;
-
-    _ASSERTE(IsCompilationProcess());
-
-    BOOL canBeSharedWith = TRUE;
-
-    // We allow full sharing except that which would break MethodTable::Fixup -- when the slots are Fixup'd
-    // we need to ensure that regardless of who is doing the Fixup the same target is decided on.
-    // Note that if this requirement is not met, an assert will fire in ZapStoredStructure::Save
-
-    if (GetFlag(enum_flag_NotInPZM))
+    CONTRACTL
     {
-        canBeSharedWith = FALSE;
+        if (FORBIDGC_LOADER_USE_ENABLED()) NOTHROW; else THROWS;
+        if (FORBIDGC_LOADER_USE_ENABLED()) GC_NOTRIGGER; else GC_TRIGGERS;
     }
+    CONTRACTL_END
 
-    if (canBeSharedWith)
+    if (!IsFullyLoaded())
     {
-        for (DWORD slotNumber = it.GetStartSlot(); slotNumber < it.GetEndSlot(); slotNumber++)
-        {
-            MethodDesc *pMD = GetMethodDescForSlot(slotNumber);
-            _ASSERTE(pMD != NULL);
-            pMD->CheckRestore();
-
-            if (!image->CanEagerBindToMethodDesc(pMD))
-            {
-                canBeSharedWith = FALSE;
-                break;
-            }
-        }
+        ClassLoader::EnsureLoaded(this);
+        _ASSERTE(IsFullyLoaded());
     }
 
-    return canBeSharedWith;
+    g_IBCLogger.LogMethodTableAccess(this);
 }
 
-//==========================================================================================
-void MethodTable::PrepopulateDictionary(DataImage * image, BOOL nonExpansive)
-{
-     STANDARD_VM_CONTRACT;
-
-     if (GetDictionary())
-     {
-         // We can only save elements of the dictionary if we are sure of its
-         // layout, which means we must be either tightly-knit to the EEClass
-         // (i.e. be the owner of the EEClass) or else we can hard-bind to the EEClass.
-         // There's no point in prepopulating the dictionary if we can't save the entries.
-         //
-         // This corresponds to the canSaveSlots which we pass to the Dictionary::Fixup
+#ifndef DACCESS_COMPILE
 
-         if (!IsCanonicalMethodTable() && image->CanEagerBindToMethodTable(GetCanonicalMethodTable()))
-         {
-             LOG((LF_JIT, LL_INFO10000, "GENERICS: Prepopulating dictionary for MT %s\n",  GetDebugClassName()));
-             GetDictionary()->PrepopulateDictionary(NULL, this, nonExpansive);
-         }
-     }
-}
+BOOL SatisfiesClassConstraints(TypeHandle instanceTypeHnd, TypeHandle typicalTypeHnd,
+                               const InstantiationContext *pInstContext);
 
-//==========================================================================================
-void ModuleCtorInfo::AddElement(MethodTable *pMethodTable)
+static VOID DoAccessibilityCheck(MethodTable *pAskingMT, MethodTable *pTargetMT, UINT resIDWhy)
 {
-    STANDARD_VM_CONTRACT;
-
-    // Get the values for the new entry before we update the
-    // cache in the Module
-
-    // Expand the table if needed.  No lock is needed because this is at NGEN time
-    if (numElements >= numLastAllocated)
+    CONTRACTL
     {
-        _ASSERTE(numElements == numLastAllocated);
-
-        RelativePointer<MethodTable *> *ppOldMTEntries = ppMT;
-
-#ifdef _PREFAST_
-#pragma warning(push)
-#pragma warning(disable:22011) // Suppress PREFast warning about integer overflows or underflows
-#endif // _PREFAST_
-        DWORD numNewAllocated = max(2 * numLastAllocated, MODULE_CTOR_ELEMENTS);
-#ifdef _PREFAST_
-#pragma warning(pop)
-#endif // _PREFAST_
-
-        ppMT = new RelativePointer<MethodTable *> [numNewAllocated];
-
-        _ASSERTE(ppMT);
+        THROWS;
+        GC_TRIGGERS;
+    }
+    CONTRACTL_END;
 
-        for (unsigned index = 0; index < numLastAllocated; ++index)
-        {
-            ppMT[index].SetValueMaybeNull(ppOldMTEntries[index].GetValueMaybeNull());
-        }
+    AccessCheckContext accessContext(NULL, pAskingMT);
 
-        for (unsigned index = numLastAllocated; index < numNewAllocated; ++index)
-        {
-            ppMT[index].SetValueMaybeNull(NULL);
-        }
+    if (!ClassLoader::CanAccessClass(&accessContext,
+                                     pTargetMT,                 //the desired class
+                                     pTargetMT->GetAssembly(),  //the desired class's assembly
+                                     *AccessCheckOptions::s_pNormalAccessChecks
+                                    ))
+    {
+        SString displayName;
+        pAskingMT->GetAssembly()->GetDisplayName(displayName);
+        SString targetName;
 
-        delete[] ppOldMTEntries;
+        // Error string is either E_ACCESSDENIED which requires the type name of the target, vs
+        // a more normal TypeLoadException which displays the requesting type.
+       _ASSERTE((resIDWhy == (UINT)E_ACCESSDENIED) || (resIDWhy == (UINT)IDS_CLASSLOAD_INTERFACE_NO_ACCESS));
+        TypeString::AppendType(targetName, TypeHandle((resIDWhy == (UINT)E_ACCESSDENIED) ? pTargetMT : pAskingMT));
 
-        numLastAllocated = numNewAllocated;
+        COMPlusThrow(kTypeLoadException, resIDWhy, targetName.GetUnicode(), displayName.GetUnicode());
     }
 
-    // Assign the new entry
-    //
-    // Note the use of two "parallel" arrays.  We do this to keep the workingset smaller since we
-    // often search (in GetClassCtorInfoIfExists) for a methodtable pointer but never actually find it.
-
-    ppMT[numElements].SetValue(pMethodTable);
-    numElements++;
 }
 
-//==========================================================================================
-void MethodTable::Save(DataImage *image, DWORD profilingFlags)
+VOID DoAccessibilityCheckForConstraint(MethodTable *pAskingMT, TypeHandle thConstraint, UINT resIDWhy)
 {
-    CONTRACTL {
-        STANDARD_VM_CHECK;
-        PRECONDITION(IsRestored_NoLogging());
-        PRECONDITION(IsFullyLoaded());
-        PRECONDITION(image->GetModule()->GetAssembly() ==
-                     GetAppDomain()->ToCompilationDomain()->GetTargetAssembly());
-    } CONTRACTL_END;
-
-    LOG((LF_ZAP, LL_INFO10000, "MethodTable::Save %s (%p)\n", GetDebugClassName(), this));
-
-    // Be careful about calling DictionaryLayout::Trim - strict conditions apply.
-    // See note on that method.
-    if (GetDictionary() &&
-        GetClass()->GetDictionaryLayout() &&
-        image->CanEagerBindToMethodTable(GetCanonicalMethodTable()))
+    CONTRACTL
     {
-        GetClass()->GetDictionaryLayout()->Trim();
+        THROWS;
+        GC_TRIGGERS;
     }
+    CONTRACTL_END;
 
-    // Set the "restore" flags. They may not have been set yet.
-    // We don't need the return value of this call.
-    NeedsRestore(image);
-
-    //check if this is actually in the PZM
-    if (Module::GetPreferredZapModuleForMethodTable(this) != GetLoaderModule())
+    if (thConstraint.IsArray())
     {
-        _ASSERTE(!IsStringOrArray());
-        SetFlag(enum_flag_NotInPZM);
+        DoAccessibilityCheckForConstraint(pAskingMT, thConstraint.GetArrayElementTypeHandle(), resIDWhy);
     }
-
-    TADDR start, end;
-
-    GetSavedExtent(&start, &end);
-
-#ifdef _DEBUG
-    if (GetDebugClassName() != NULL && !image->IsStored(GetDebugClassName()))
-        image->StoreStructure(debug_m_szClassName, (ULONG)(strlen(GetDebugClassName())+1),
-                              DataImage::ITEM_DEBUG,
-                              1);
-#endif // _DEBUG
-
-    DataImage::ItemKind kindBasic    = DataImage::ITEM_METHOD_TABLE;
-    if (IsWriteable())
-        kindBasic = DataImage::ITEM_METHOD_TABLE_SPECIAL_WRITEABLE;
-
-    ZapStoredStructure * pMTNode = image->StoreStructure((void*) start, (ULONG)(end - start), kindBasic);
-
-    if ((void *)this != (void *)start)
-        image->BindPointer(this, pMTNode, (BYTE *)this - (BYTE *)start);
-
-    // Store the vtable chunks
-    VtableIndirectionSlotIterator it = IterateVtableIndirectionSlots();
-    while (it.Next())
+    else if (thConstraint.IsTypeDesc())
     {
-        if (!image->IsStored(it.GetIndirectionSlot()))
+        TypeDesc *pTypeDesc = thConstraint.AsTypeDesc();
+
+        if (pTypeDesc->IsGenericVariable())
         {
-            if (!MethodTable::VTableIndir2_t::isRelative
-                && CanInternVtableChunk(image, it))
-                image->StoreInternedStructure(it.GetIndirectionSlot(), it.GetSize(), DataImage::ITEM_VTABLE_CHUNK);
-            else
-                image->StoreStructure(it.GetIndirectionSlot(), it.GetSize(), DataImage::ITEM_VTABLE_CHUNK);
+            // since the metadata respresents a generic type param constraint as an index into
+            // the declaring type's list of generic params, it is structurally impossible
+            // to express a violation this way. So there's no check to be done here.
         }
         else
+        if (pTypeDesc->HasTypeParam())
         {
-            // Tell the interning system that we have already shared this structure without its help
-            image->NoteReusedStructure(it.GetIndirectionSlot());
-        }
-    }
-
-    if (HasNonVirtualSlotsArray())
-    {
-        image->StoreStructure(GetNonVirtualSlotsArray(), GetNonVirtualSlotsArraySize(), DataImage::ITEM_VTABLE_CHUNK);
-    }
-
-    if (HasInterfaceMap())
-    {
-#ifdef FEATURE_COMINTEROP
-        // Dynamic interface maps have an additional DWORD_PTR preceding the InterfaceInfo_t array
-        if (HasDynamicInterfaceMap())
-        {
-            ZapStoredStructure * pInterfaceMapNode;
-            if (decltype(InterfaceInfo_t::m_pMethodTable)::isRelative)
-            {
-                pInterfaceMapNode = image->StoreStructure(((DWORD_PTR *)GetInterfaceMap()) - 1,
-                                                          GetInterfaceMapSize(),
-                                                          DataImage::ITEM_INTERFACE_MAP);
-            }
-            else
-            {
-                pInterfaceMapNode = image->StoreInternedStructure(((DWORD_PTR *)GetInterfaceMap()) - 1,
-                                                                  GetInterfaceMapSize(),
-                                                                  DataImage::ITEM_INTERFACE_MAP);
-            }
-            image->BindPointer(GetInterfaceMap(), pInterfaceMapNode, sizeof(DWORD_PTR));
+            DoAccessibilityCheckForConstraint(pAskingMT, pTypeDesc->GetTypeParam(), resIDWhy);
         }
         else
-#endif // FEATURE_COMINTEROP
         {
-            if (decltype(InterfaceInfo_t::m_pMethodTable)::isRelative)
-            {
-                image->StoreStructure(GetInterfaceMap(), GetInterfaceMapSize(), DataImage::ITEM_INTERFACE_MAP);
-            }
-            else
-            {
-                image->StoreInternedStructure(GetInterfaceMap(), GetInterfaceMapSize(), DataImage::ITEM_INTERFACE_MAP);
-            }
+            COMPlusThrow(kTypeLoadException, E_ACCESSDENIED);
         }
 
-        SaveExtraInterfaceInfo(image);
     }
-
-    // If we have a dispatch map, save it.
-    if (HasDispatchMapSlot())
+    else
     {
-        GetDispatchMap()->Save(image);
+        DoAccessibilityCheck(pAskingMT, thConstraint.GetMethodTable(), resIDWhy);
     }
 
-    if (HasPerInstInfo())
-    {
-        ZapStoredStructure * pPerInstInfoNode;
-        if (CanEagerBindToParentDictionaries(image, NULL))
-        {
-            if (PerInstInfoElem_t::isRelative)
-            {
-                pPerInstInfoNode = image->StoreStructure((BYTE *)GetPerInstInfo() - sizeof(GenericsDictInfo), GetPerInstInfoSize() + sizeof(GenericsDictInfo), DataImage::ITEM_DICTIONARY);
-            }
-            else
-            {
-                pPerInstInfoNode = image->StoreInternedStructure((BYTE *)GetPerInstInfo() - sizeof(GenericsDictInfo), GetPerInstInfoSize() + sizeof(GenericsDictInfo), DataImage::ITEM_DICTIONARY);
-            }
-        }
-        else
-        {
-            pPerInstInfoNode = image->StoreStructure((BYTE *)GetPerInstInfo() - sizeof(GenericsDictInfo), GetPerInstInfoSize() + sizeof(GenericsDictInfo), DataImage::ITEM_DICTIONARY_WRITEABLE);
-        }
-        image->BindPointer(GetPerInstInfo(), pPerInstInfoNode, sizeof(GenericsDictInfo));
-    }
+}
 
-    Dictionary * pDictionary = GetDictionary();
-    if (pDictionary != NULL)
+VOID DoAccessibilityCheckForConstraints(MethodTable *pAskingMT, TypeVarTypeDesc *pTyVar, UINT resIDWhy)
+{
+    CONTRACTL
     {
-        BOOL fIsWriteable;
-
-        if (!IsCanonicalMethodTable())
-        {
-            // CanEagerBindToMethodTable would not work for targeted patching here. The dictionary
-            // layout is sensitive to compilation order that can be changed by TP compatible changes.
-            BOOL canSaveSlots = (image->GetModule() == GetCanonicalMethodTable()->GetLoaderModule());
-
-            fIsWriteable = pDictionary->IsWriteable(image, canSaveSlots,
-                                       GetNumGenericArgs(),
-                                       GetModule(),
-                                       GetClass()->GetDictionaryLayout());
-        }
-        else
-        {
-            fIsWriteable = FALSE;
-        }
-
-        DWORD slotSize;
-        DWORD allocSize = GetInstAndDictSize(&slotSize);
-        if (!fIsWriteable)
-        {
-            image->StoreInternedStructure(pDictionary, slotSize, DataImage::ITEM_DICTIONARY);
-        }
-        else
-        {
-            image->StoreStructure(pDictionary, slotSize, DataImage::ITEM_DICTIONARY_WRITEABLE);
-        }
+        THROWS;
+        GC_TRIGGERS;
     }
+    CONTRACTL_END;
 
-    WORD numStaticFields = GetClass()->GetNumStaticFields();
-
-    if (!IsCanonicalMethodTable() && HasGenericsStaticsInfo() && numStaticFields != 0)
+    DWORD numConstraints;
+    TypeHandle *pthConstraints = pTyVar->GetCachedConstraints(&numConstraints);
+    for (DWORD cidx = 0; cidx < numConstraints; cidx++)
     {
-        FieldDesc * pGenericsFieldDescs = GetGenericsStaticFieldDescs();
-
-        for (DWORD i = 0; i < numStaticFields; i++)
-        {
-            FieldDesc *pFld = pGenericsFieldDescs + i;
-            pFld->PrecomputeNameHash();
-        }
-
-        ZapStoredStructure * pFDNode = image->StoreStructure(pGenericsFieldDescs, sizeof(FieldDesc) * numStaticFields,
-                              DataImage::ITEM_GENERICS_STATIC_FIELDDESCS);
-
-        for (DWORD i = 0; i < numStaticFields; i++)
-        {
-            FieldDesc *pFld = pGenericsFieldDescs + i;
-            pFld->SaveContents(image);
-            if (pFld != pGenericsFieldDescs)
-               image->BindPointer(pFld, pFDNode, (BYTE *)pFld - (BYTE *)pGenericsFieldDescs);
-        }
-    }
+        TypeHandle thConstraint = pthConstraints[cidx];
 
-    // Allocate a ModuleCtorInfo entry in the NGEN image if necessary
-    if (HasBoxedRegularStatics())
-    {
-        image->GetModule()->GetZapModuleCtorInfo()->AddElement(this);
+        DoAccessibilityCheckForConstraint(pAskingMT, thConstraint, resIDWhy);
     }
+}
 
-    // MethodTable WriteableData
-
-
-    PTR_Const_MethodTableWriteableData pWriteableData = GetWriteableData_NoLogging();
-    _ASSERTE(pWriteableData != NULL);
-    if (pWriteableData != NULL)
-    {
-        pWriteableData->Save(image, this, profilingFlags);
-    }
 
-    LOG((LF_ZAP, LL_INFO10000, "MethodTable::Save %s (%p) complete.\n", GetDebugClassName(), this));
+// Recursive worker that pumps the transitive closure of a type's dependencies to the specified target level.
+// Dependencies include:
+//
+//   - parent
+//   - interfaces
+//   - canonical type, for non-canonical instantiations
+//   - typical type, for non-typical instantiations
+//
+// Parameters:
+//
+//   pVisited - used to prevent endless recursion in the case of cyclic dependencies
+//
+//   level    - target level to pump to - must be CLASS_DEPENDENCIES_LOADED or CLASS_LOADED
+//
+//              if CLASS_DEPENDENCIES_LOADED, all transitive dependencies are resolved to their
+//                 exact types.
+//
+//              if CLASS_LOADED, all type-safety checks are done on the type and all its transitive
+//                 dependencies. Note that for the CLASS_LOADED case, some types may be left
+//                 on the pending list rather that pushed to CLASS_LOADED in the case of cyclic
+//                 dependencies - the root caller must handle this.
+//
+//   pfBailed - if we or one of our depedencies bails early due to cyclic dependencies, we
+//              must set *pfBailed to TRUE. Otherwise, we must *leave it unchanged* (thus, the
+//              boolean acts as a cumulative OR.)
+//
+//   pPending - if one of our dependencies bailed, the type cannot yet be promoted to CLASS_LOADED
+//              as the dependencies will be checked later and may fail a security check then.
+//              Instead, DoFullyLoad() will add the type to the pending list - the root caller
+//              is responsible for promoting the type after the full transitive closure has been
+//              walked. Note that it would be just as correct to always defer to the pending list -
+//              however, that is a little less performant.
+//
 
-    // Save the EEClass at the same time as the method table if this is the canonical method table
-    if (IsCanonicalMethodTable())
-        GetClass()->Save(image, this);
-} // MethodTable::Save
 
-//==========================================================================
-// The NeedsRestore Computation.
-//
-// WARNING: The NeedsRestore predicate on MethodTable and EEClass
-// MUST be computable immediately after we have loaded a type.
-// It must NOT depend on any additions or changes made to the
-// MethodTable as a result of compiling code, or
-// later steps such as prepopulating dictionaries.
-//==========================================================================
-BOOL MethodTable::ComputeNeedsRestore(DataImage *image, TypeHandleList *pVisited)
+// Closure of locals necessary for implementing CheckForEquivalenceAndFullyLoadType.
+// Used so that we can have one valuetype walking algorithm used for type equivalence walking of the parameters of the method.
+struct DoFullyLoadLocals
 {
-    CONTRACTL
+    DoFullyLoadLocals(DFLPendingList *pPendingParam, ClassLoadLevel levelParam, MethodTable *pMT, Generics::RecursionGraph *pVisited)
+        : newVisited(pVisited, TypeHandle(pMT))
+        , pPending(pPendingParam)
+        , level(levelParam)
+        , fBailed(FALSE)
+#ifdef FEATURE_TYPEEQUIVALENCE
+        , fHasEquivalentStructParameter(FALSE)
+#endif
+        , fHasTypeForwarderDependentStructParameter(FALSE)
+        , fDependsOnEquivalentOrForwardedStructs(FALSE)
     {
-        STANDARD_VM_CHECK;
-        // See comment in ComputeNeedsRestoreWorker
-        PRECONDITION(GetLoaderModule()->HasNativeImage() || GetLoaderModule() == GetAppDomain()->ToCompilationDomain()->GetTargetModule());
-    }
-    CONTRACTL_END;
-
-    _ASSERTE(GetAppDomain()->IsCompilationDomain()); // only used at ngen time!
-
-    if (GetWriteableData()->IsNeedsRestoreCached())
-    {
-        return GetWriteableData()->GetCachedNeedsRestore();
-    }
-
-    // We may speculatively assume that any types we've visited on this run of
-    // the ComputeNeedsRestore algorithm don't need a restore.  If they
-    // do need a restore then we will check that when we first visit that method
-    // table.
-    if (TypeHandleList::Exists(pVisited, TypeHandle(this)))
-    {
-        pVisited->MarkBrokenCycle(this);
-        return FALSE;
-    }
-    TypeHandleList newVisited(this, pVisited);
-
-    BOOL needsRestore = ComputeNeedsRestoreWorker(image, &newVisited);
-
-    // Cache the results of running the algorithm.
-    // We can only cache the result if we have not speculatively assumed
-    // that any types are not NeedsRestore
-    if (!newVisited.HasBrokenCycleMark())
-    {
-        GetWriteableDataForWrite()->SetCachedNeedsRestore(needsRestore);
-    }
-    else
-    {
-        _ASSERTE(pVisited != NULL);
-    }
-    return needsRestore;
-}
-
-//==========================================================================================
-BOOL MethodTable::ComputeNeedsRestoreWorker(DataImage *image, TypeHandleList *pVisited)
-{
-    STANDARD_VM_CONTRACT;
-
-#ifdef _DEBUG
-    // You should only call ComputeNeedsRestoreWorker on things being saved into
-    // the current LoaderModule - the NeedsRestore flag should have been computed
-    // for all items from NGEN images, and we should never compute NeedsRestore
-    // on anything that is not related to an NGEN image.  If this fails then
-    // there is probably a CanEagerBindTo check missing as we trace through a
-    // pointer from one data structure to another.
-    // Trace back on the call stack and work out where this condition first fails.
-
-    Module* myModule = GetLoaderModule();
-    AppDomain* myAppDomain = GetAppDomain();
-    CompilationDomain* myCompilationDomain = myAppDomain->ToCompilationDomain();
-    Module* myCompilationModule = myCompilationDomain->GetTargetModule();
-
-    if (myModule !=  myCompilationModule)
-    {
-        _ASSERTE(!"You should only call ComputeNeedsRestoreWorker on things being saved into the current LoaderModule");
-    }
-#endif
-
-    if (g_CorCompileVerboseLevel == CORCOMPILE_VERBOSE)
-    {
-        DefineFullyQualifiedNameForClassW();
-        LPCWSTR name = GetFullyQualifiedNameForClassW(this);
-        WszOutputDebugString(W("MethodTable "));
-        WszOutputDebugString(name);
-        WszOutputDebugString(W(" needs restore? "));
-    }
-    if (g_CorCompileVerboseLevel >= CORCOMPILE_STATS && GetModule()->GetNgenStats())
-        GetModule()->GetNgenStats()->MethodTableRestoreNumReasons[TotalMethodTables]++;
-
-    #define UPDATE_RESTORE_REASON(ARG)                                                    \
-        if (g_CorCompileVerboseLevel == CORCOMPILE_VERBOSE)                               \
-            { WszOutputDebugString(W("Yes, ")); WszOutputDebugString(W(#ARG "\n")); }          \
-        if (g_CorCompileVerboseLevel >= CORCOMPILE_STATS && GetModule()->GetNgenStats())  \
-            GetModule()->GetNgenStats()->MethodTableRestoreNumReasons[ARG]++;
-
-    // The special method table for IL stubs has to be prerestored. Restore is not able to handle it
-    // because of it does not have a token. In particular, this is a problem for /profiling native images.
-    if (this == image->GetModule()->GetILStubCache()->GetStubMethodTable())
-    {
-        return FALSE;
-    }
-
-    // When profiling, we always want to perform the restore.
-    if (GetAppDomain()->ToCompilationDomain()->m_fForceProfiling)
-    {
-        UPDATE_RESTORE_REASON(ProfilingEnabled);
-        return TRUE;
-    }
-
-    if (DependsOnEquivalentOrForwardedStructs())
-    {
-        UPDATE_RESTORE_REASON(ComImportStructDependenciesNeedRestore);
-        return TRUE;
-    }
-
-    if (!IsCanonicalMethodTable() && !image->CanPrerestoreEagerBindToMethodTable(GetCanonicalMethodTable(), pVisited))
-    {
-        UPDATE_RESTORE_REASON(CanNotPreRestoreHardBindToCanonicalMethodTable);
-        return TRUE;
-    }
-
-    if (!image->CanEagerBindToModule(GetModule()))
-    {
-        UPDATE_RESTORE_REASON(CrossAssembly);
-        return TRUE;
-    }
-
-    if (GetParentMethodTable())
-    {
-        if (!image->CanPrerestoreEagerBindToMethodTable(GetParentMethodTable(), pVisited))
-        {
-            UPDATE_RESTORE_REASON(CanNotPreRestoreHardBindToParentMethodTable);
-            return TRUE;
-        }
-    }
-
-    // Check per-inst pointers-to-dictionaries.
-    if (!CanEagerBindToParentDictionaries(image, pVisited))
-    {
-        UPDATE_RESTORE_REASON(CanNotHardBindToInstanceMethodTableChain);
-        return TRUE;
-    }
-
-    // Now check if the dictionary (if any) owned by this methodtable needs a restore.
-    if (GetDictionary())
-    {
-        if (GetDictionary()->ComputeNeedsRestore(image, pVisited, GetNumGenericArgs()))
-        {
-            UPDATE_RESTORE_REASON(GenericsDictionaryNeedsRestore);
-            return TRUE;
-        }
-    }
-
-    // The interface chain is traversed without doing CheckRestore's.  Thus
-    // if any of the types in the inherited interfaces hierarchy need a restore
-    // or are cross-module pointers then this methodtable will also need a restore.
-    InterfaceMapIterator it = IterateInterfaceMap();
-    while (it.Next())
-    {
-        if (!image->CanPrerestoreEagerBindToMethodTable(it.GetInterface(this), pVisited))
-        {
-            UPDATE_RESTORE_REASON(InterfaceIsGeneric);
-            return TRUE;
-        }
-    }
-
-    if (NeedsCrossModuleGenericsStaticsInfo())
-    {
-        UPDATE_RESTORE_REASON(CrossModuleGenericsStatics);
-        return TRUE;
-    }
-
-    if (IsArray())
-    {
-        if(!image->CanPrerestoreEagerBindToTypeHandle(GetArrayElementTypeHandle(), pVisited))
-        {
-            UPDATE_RESTORE_REASON(ArrayElement);
-            return TRUE;
-        }
-    }
-
-    if (g_CorCompileVerboseLevel == CORCOMPILE_VERBOSE)
-    {
-        WszOutputDebugString(W("No\n"));
-    }
-    return FALSE;
-}
-
-//==========================================================================================
-BOOL MethodTable::CanEagerBindToParentDictionaries(DataImage *image, TypeHandleList *pVisited)
-{
-    STANDARD_VM_CONTRACT;
-
-    MethodTable *pChain = GetParentMethodTable();
-    while (pChain != NULL)
-    {
-        // This is for the case were the method table contains a pointer to
-        // an inherited dictionary, e.g. given the case D : C, C : B<int>
-        // where B<int> is in another module then D contains a pointer to the
-        // dictionary for B<int>.   Note that in this case we might still be
-        // able to hadbind to C.
-        if (pChain->HasInstantiation())
-        {
-            if (!image->CanEagerBindToMethodTable(pChain, FALSE, pVisited) ||
-                !image->CanHardBindToZapModule(pChain->GetLoaderModule()))
-            {
-                return FALSE;
-            }
-        }
-        pChain = pChain->GetParentMethodTable();
-    }
-    return TRUE;
-}
-
-//==========================================================================================
-BOOL MethodTable::NeedsCrossModuleGenericsStaticsInfo()
-{
-    STANDARD_VM_CONTRACT;
-
-    return HasGenericsStaticsInfo() && !ContainsGenericVariables() && !IsSharedByGenericInstantiations() &&
-        (Module::GetPreferredZapModuleForMethodTable(this) != GetLoaderModule());
-}
-
-//==========================================================================================
-BOOL MethodTable::IsWriteable()
-{
-    STANDARD_VM_CONTRACT;
-
-#ifdef FEATURE_COMINTEROP
-    // Dynamic expansion of interface map writes into method table
-    // (see code:MethodTable::AddDynamicInterface)
-    if (HasDynamicInterfaceMap())
-        return TRUE;
-#endif
-
-    return FALSE;
-}
-
-//==========================================================================================
-// This is used when non-canonical (i.e. duplicated) method tables
-// attempt to bind to items logically belonging to an EEClass or MethodTable.
-// i.e. the contract map in the EEClass and the generic dictionary stored in the canonical
-// method table.
-//
-// We want to check if we can hard bind to the containing structure before
-// deciding to hardbind to the inside of it.  This is because we may not be able
-// to hardbind to all EEClass and/or MethodTables even if they live in a hradbindable
-// target module.  Thus we want to call CanEagerBindToMethodTable
-// to check we can hardbind to the containing structure.
-static
-void HardBindOrClearDictionaryPointer(DataImage *image, MethodTable *pMT, void * p, SSIZE_T offset, bool isRelative)
-{
-    WRAPPER_NO_CONTRACT;
-
-    if (image->CanEagerBindToMethodTable(pMT) &&
-        image->CanHardBindToZapModule(pMT->GetLoaderModule()))
-    {
-        if (isRelative)
-        {
-            image->FixupRelativePointerField(p, offset);
-        }
-        else
-        {
-            image->FixupPointerField(p, offset);
-        }
-    }
-    else
-    {
-        image->ZeroPointerField(p, offset);
-    }
-}
-
-//==========================================================================================
-void MethodTable::Fixup(DataImage *image)
-{
-    CONTRACTL
-    {
-        STANDARD_VM_CHECK;
-        PRECONDITION(IsFullyLoaded());
-    }
-    CONTRACTL_END;
-
-    LOG((LF_ZAP, LL_INFO10000, "MethodTable::Fixup %s\n", GetDebugClassName()));
-
-    if (GetWriteableData()->IsFixedUp())
-        return;
-
-    BOOL needsRestore = NeedsRestore(image);
-    LOG((LF_ZAP, LL_INFO10000, "MethodTable::Fixup %s (%p), needsRestore=%d\n", GetDebugClassName(), this, needsRestore));
-
-    BOOL isCanonical = IsCanonicalMethodTable();
-
-    Module *pZapModule = image->GetModule();
-
-    MethodTable *pNewMT = (MethodTable *) image->GetImagePointer(this);
-
-    // For canonical method tables, the pointer to the EEClass is never encoded as a fixup
-    // even if this method table is not in its preferred zap module, i.e. the two are
-    // "tightly-bound".
-    if (IsCanonicalMethodTable())
-    {
-        // Pointer to EEClass
-        image->FixupPlainOrRelativePointerField(this, &MethodTable::m_pEEClass);
-    }
-    else
-    {
-        //
-        // Encode m_pEEClassOrCanonMT
-        //
-        MethodTable * pCanonMT = GetCanonicalMethodTable();
-
-        ZapNode * pImport = NULL;
-        if (image->CanEagerBindToMethodTable(pCanonMT))
-        {
-            if (image->CanHardBindToZapModule(pCanonMT->GetLoaderModule()))
-            {
-                // Pointer to canonical methodtable
-                image->FixupPlainOrRelativeField(this, &MethodTable::m_pCanonMT, pCanonMT, UNION_METHODTABLE);
-            }
-            else
-            {
-                // Pointer to lazy bound indirection cell to canonical methodtable
-                pImport = image->GetTypeHandleImport(pCanonMT);
-            }
-        }
-    else
-        {
-            // Pointer to eager bound indirection cell to canonical methodtable
-            _ASSERTE(pCanonMT->IsTypicalTypeDefinition() ||
-                     !pCanonMT->ContainsGenericVariables());
-            pImport = image->GetTypeHandleImport(pCanonMT);
-        }
-
-        if (pImport != NULL)
-        {
-            image->FixupPlainOrRelativeFieldToNode(this, &MethodTable::m_pCanonMT, pImport, UNION_INDIRECTION);
-        }
-    }
-
-    image->FixupField(this, offsetof(MethodTable, m_pLoaderModule), pZapModule, 0, IMAGE_REL_BASED_RELPTR);
-
-#ifdef _DEBUG
-    image->FixupPointerField(this, offsetof(MethodTable, debug_m_szClassName));
-#endif // _DEBUG
-
-    MethodTable * pParentMT = GetParentMethodTable();
-    _ASSERTE(!pNewMT->IsParentMethodTableIndirectPointerMaybeNull());
-
-    ZapRelocationType relocType;
-    if (decltype(MethodTable::m_pParentMethodTable)::isRelative)
-    {
-        relocType = IMAGE_REL_BASED_RELPTR;
-    }
-    else
-    {
-        relocType = IMAGE_REL_BASED_PTR;
-    }
-
-    if (pParentMT != NULL)
-    {
-        //
-        // Encode m_pParentMethodTable
-        //
-        ZapNode * pImport = NULL;
-        if (image->CanEagerBindToMethodTable(pParentMT))
-        {
-            if (image->CanHardBindToZapModule(pParentMT->GetLoaderModule()))
-            {
-                _ASSERTE(!IsParentMethodTableIndirectPointer());
-                image->FixupField(this, offsetof(MethodTable, m_pParentMethodTable), pParentMT, 0, relocType);
-            }
-            else
-            {
-                pImport = image->GetTypeHandleImport(pParentMT);
-            }
-        }
-        else
-        {
-            if (!pParentMT->IsCanonicalMethodTable())
-            {
-#ifdef _DEBUG
-                IMDInternalImport *pInternalImport = GetModule()->GetMDImport();
-
-                mdToken crExtends;
-                pInternalImport->GetTypeDefProps(GetCl(),
-                                                 NULL,
-                                                 &crExtends);
-
-                _ASSERTE(TypeFromToken(crExtends) == mdtTypeSpec);
-#endif
-
-                // Use unique cell for now since we are first going to set the parent method table to
-                // approx one first, and then to the exact one later. This would mess up the shared cell.
-                // It would be nice to clean it up to use the shared cell - we should set the parent method table
-                // just once at the end.
-                pImport = image->GetTypeHandleImport(pParentMT, this /* pUniqueId */);
-            }
-            else
-            {
-                pImport = image->GetTypeHandleImport(pParentMT);
-            }
-        }
-
-        if (pImport != NULL)
-        {
-            image->FixupFieldToNode(this, offsetof(MethodTable, m_pParentMethodTable), pImport, -PARENT_MT_FIXUP_OFFSET, relocType);
-            pNewMT->SetFlag(enum_flag_HasIndirectParent);
-        }
-    }
-
-    if (HasNonVirtualSlotsArray())
-    {
-        TADDR ppNonVirtualSlots = GetNonVirtualSlotsPtr();
-        PREFIX_ASSUME(ppNonVirtualSlots != NULL);
-        image->FixupRelativePointerField(this, (BYTE *)ppNonVirtualSlots - (BYTE *)this);
-    }
-
-    if (HasInterfaceMap())
-    {
-        image->FixupPlainOrRelativePointerField(this, &MethodTable::m_pInterfaceMap);
-
-        FixupExtraInterfaceInfo(image);
-    }
-
-    _ASSERTE(GetWriteableData());
-    image->FixupPlainOrRelativePointerField(this, &MethodTable::m_pWriteableData);
-    m_pWriteableData.GetValue()->Fixup(image, this, needsRestore);
-
-    //
-    // Fix flags
-    //
-
-    _ASSERTE((pNewMT->GetFlag(enum_flag_IsZapped) == 0));
-    pNewMT->SetFlag(enum_flag_IsZapped);
-
-    _ASSERTE((pNewMT->GetFlag(enum_flag_IsPreRestored) == 0));
-    if (!needsRestore)
-        pNewMT->SetFlag(enum_flag_IsPreRestored);
-
-    //
-    // Fixup vtable
-    // If the canonical method table lives in a different loader module
-    // then just zero out the entries and copy them across from the canonical
-    // vtable on restore.
-    //
-    // Note the canonical method table will be the same as the current method table
-    // if the method table is not a generic instantiation.
-
-    if (HasDispatchMapSlot())
-    {
-        TADDR pSlot = GetMultipurposeSlotPtr(enum_flag_HasDispatchMapSlot, c_DispatchMapSlotOffsets);
-        DispatchMap * pDispatchMap = RelativePointer<PTR_DispatchMap>::GetValueAtPtr(pSlot);
-        image->FixupField(this, pSlot - (TADDR)this, pDispatchMap, 0, IMAGE_REL_BASED_RelativePointer);
-        pDispatchMap->Fixup(image);
-    }
-
-    if (HasModuleOverride())
-    {
-        image->FixupModulePointer(this, GetModuleOverridePtr());
-    }
-
-    {
-        VtableIndirectionSlotIterator it = IterateVtableIndirectionSlots();
-        while (it.Next())
-        {
-            if (VTableIndir_t::isRelative)
-            {
-                image->FixupRelativePointerField(this, it.GetOffsetFromMethodTable());
-            }
-            else
-            {
-                image->FixupPointerField(this, it.GetOffsetFromMethodTable());
-            }
-        }
-    }
-
-    unsigned numVTableSlots = GetNumVtableSlots();
-    for (unsigned slotNumber = 0; slotNumber < numVTableSlots; slotNumber++)
-    {
-        //
-        // Find the method desc from the slot.
-        //
-        MethodDesc *pMD = GetMethodDescForSlot(slotNumber);
-        _ASSERTE(pMD != NULL);
-        pMD->CheckRestore();
-
-        PVOID slotBase;
-        SSIZE_T slotOffset;
-
-        if (slotNumber < GetNumVirtuals())
-        {
-            // Virtual slots live in chunks pointed to by vtable indirections
-
-            slotBase = (PVOID) GetVtableIndirections()[GetIndexOfVtableIndirection(slotNumber)].GetValueMaybeNull();
-            slotOffset = GetIndexAfterVtableIndirection(slotNumber) * sizeof(MethodTable::VTableIndir2_t);
-        }
-        else if (HasSingleNonVirtualSlot())
-        {
-            // Non-virtual slots < GetNumVtableSlots live in a single chunk pointed to by an optional member,
-            // except when there is only one in which case it lives in the optional member itself
-
-            _ASSERTE(slotNumber == GetNumVirtuals());
-            slotBase = (PVOID) this;
-            slotOffset = (BYTE *)GetSlotPtr(slotNumber) - (BYTE *)this;
-        }
-        else
-        {
-            // Non-virtual slots < GetNumVtableSlots live in a single chunk pointed to by an optional member
-
-            _ASSERTE(HasNonVirtualSlotsArray());
-            slotBase = (PVOID) GetNonVirtualSlotsArray();
-            slotOffset = (slotNumber - GetNumVirtuals()) * sizeof(PCODE);
-        }
-
-        // Attempt to make the slot point directly at the prejitted code.
-        // Note that changes to this logic may require or enable an update to CanInternVtableChunk.
-        // If a necessary update is not made, an assert will fire in ZapStoredStructure::Save.
-
-        if (pMD->GetMethodTable() == this)
-        {
-            ZapRelocationType relocType;
-            if (slotNumber >= GetNumVirtuals() || MethodTable::VTableIndir2_t::isRelative)
-                relocType = IMAGE_REL_BASED_RelativePointer;
-            else
-                relocType = IMAGE_REL_BASED_PTR;
-
-            pMD->FixupSlot(image, slotBase, slotOffset, relocType);
-        }
-        else
-        {
-
-#ifdef _DEBUG
-
-            // Static method should be in the owning methodtable only.
-            _ASSERTE(!pMD->IsStatic());
-
-            MethodTable *pSourceMT = isCanonical
-                ? GetParentMethodTable()
-                : GetCanonicalMethodTable();
-
-            // It must be inherited from the parent or copied from the canonical
-            _ASSERTE(pSourceMT->GetMethodDescForSlot(slotNumber) == pMD);
-#endif
-
-            ZapRelocationType relocType;
-            if (MethodTable::VTableIndir2_t::isRelative)
-                relocType = IMAGE_REL_BASED_RELPTR;
-            else
-                relocType = IMAGE_REL_BASED_PTR;
-
-            if (image->CanEagerBindToMethodDesc(pMD) && pMD->GetLoaderModule() == pZapModule)
-            {
-                pMD->FixupSlot(image, slotBase, slotOffset, relocType);
-            }
-            else
-            {
-                if (!pMD->IsGenericMethodDefinition())
-                {
-                    ZapNode * importThunk = image->GetVirtualImportThunk(pMD->GetMethodTable(), pMD, slotNumber);
-                    // On ARM, make sure that the address to the virtual thunk that we write into the
-                    // vtable "chunk" has the Thumb bit set.
-                    image->FixupFieldToNode(slotBase, slotOffset, importThunk ARM_ARG(THUMB_CODE) NOT_ARM_ARG(0), relocType);
-                }
-                else
-                {
-                    // Virtual generic methods don't/can't use their vtable slot
-                    image->ZeroPointerField(slotBase, slotOffset);
-                }
-            }
-        }
-    }
-
-    //
-    // Fixup Interface map
-    //
-
-    InterfaceMapIterator it = IterateInterfaceMap();
-    while (it.Next())
-    {
-        image->FixupMethodTablePointer(GetInterfaceMap(), &it.GetInterfaceInfo()->m_pMethodTable);
-    }
-
-    if (IsArray())
-    {
-        image->HardBindTypeHandlePointer(this, offsetof(MethodTable, m_ElementTypeHnd));
-    }
-
-    //
-    // Fixup per-inst pointers for this method table
-    //
-
-    if (HasPerInstInfo())
-    {
-        // Fixup the pointer to the per-inst table
-        image->FixupPlainOrRelativePointerField(this, &MethodTable::m_pPerInstInfo);
-
-        for (MethodTable *pChain = this; pChain != NULL; pChain = pChain->GetParentMethodTable())
-        {
-            if (pChain->HasInstantiation())
-            {
-                DWORD dictNum = pChain->GetNumDicts()-1;
-
-                // If we can't hardbind then the value will be copied down from
-                // the parent upon restore.
-
-                // We special-case the dictionary for this method table because we must always
-                // hard bind to it even if it's not in its preferred zap module
-                size_t sizeDict = sizeof(PerInstInfoElem_t);
-
-                if (pChain == this)
-                {
-                    if (PerInstInfoElem_t::isRelative)
-                    {
-                        image->FixupRelativePointerField(GetPerInstInfo(), dictNum * sizeDict);
-                    }
-                    else
-                    {
-                        image->FixupPointerField(GetPerInstInfo(), dictNum * sizeDict);
-                    }
-                }
-                else
-                {
-                    HardBindOrClearDictionaryPointer(image, pChain, GetPerInstInfo(), dictNum * sizeDict, PerInstInfoElem_t::isRelative);
-                }
-            }
-        }
-    }
-    //
-    // Fixup instantiation+dictionary for this method table (if any)
-    //
-    if (GetDictionary())
-    {
-        LOG((LF_JIT, LL_INFO10000, "GENERICS: Fixup dictionary for MT %s\n",  GetDebugClassName()));
-
-        // CanEagerBindToMethodTable would not work for targeted patching here. The dictionary
-        // layout is sensitive to compilation order that can be changed by TP compatible changes.
-        BOOL canSaveSlots = !IsCanonicalMethodTable() && (image->GetModule() == GetCanonicalMethodTable()->GetLoaderModule());
-
-        // See comment on Dictionary::Fixup
-        GetDictionary()->Fixup(image,
-                               TRUE,
-                               canSaveSlots,
-                               GetNumGenericArgs(),
-                               GetModule(),
-                               GetClass()->GetDictionaryLayout());
-    }
-
-    // Fixup per-inst statics info
-    if (HasGenericsStaticsInfo())
-    {
-        GenericsStaticsInfo *pInfo = GetGenericsStaticsInfo();
-
-        image->FixupRelativePointerField(this, (BYTE *)&pInfo->m_pFieldDescs - (BYTE *)this);
-        if (!isCanonical)
-        {
-            for (DWORD i = 0; i < GetClass()->GetNumStaticFields(); i++)
-            {
-                FieldDesc *pFld = GetGenericsStaticFieldDescs() + i;
-                pFld->Fixup(image);
-            }
-        }
-
-        if (NeedsCrossModuleGenericsStaticsInfo())
-        {
-            MethodTableWriteableData * pNewWriteableData = (MethodTableWriteableData *)image->GetImagePointer(m_pWriteableData.GetValue());
-            CrossModuleGenericsStaticsInfo * pNewCrossModuleGenericsStaticsInfo = pNewWriteableData->GetCrossModuleGenericsStaticsInfo();
-
-            pNewCrossModuleGenericsStaticsInfo->m_DynamicTypeID = pInfo->m_DynamicTypeID;
-
-            image->ZeroPointerField(m_pWriteableData.GetValue(), sizeof(MethodTableWriteableData) + offsetof(CrossModuleGenericsStaticsInfo, m_pModuleForStatics));
-
-            pNewMT->SetFlag(enum_flag_StaticsMask_IfGenericsThenCrossModule);
-        }
-    }
-    else
-    {
-        _ASSERTE(!NeedsCrossModuleGenericsStaticsInfo());
-    }
-
-
-    LOG((LF_ZAP, LL_INFO10000, "MethodTable::Fixup %s (%p) complete\n", GetDebugClassName(), this));
-
-    // If this method table is canonical (one-to-one with EEClass) then fix up the EEClass also
-    if (isCanonical)
-        GetClass()->Fixup(image, this);
-
-    // Mark method table as fixed-up
-    GetWriteableDataForWrite()->SetFixedUp();
-
-} // MethodTable::Fixup
-
-//==========================================================================================
-void MethodTableWriteableData::Save(DataImage *image, MethodTable *pMT, DWORD profilingFlags) const
-{
-    STANDARD_VM_CONTRACT;
-
-    SIZE_T size = sizeof(MethodTableWriteableData);
-
-    // MethodTableWriteableData is followed by optional CrossModuleGenericsStaticsInfo in NGen images
-    if (pMT->NeedsCrossModuleGenericsStaticsInfo())
-        size += sizeof(CrossModuleGenericsStaticsInfo);
-
-    DataImage::ItemKind kindWriteable = DataImage::ITEM_METHOD_TABLE_DATA_COLD_WRITEABLE;
-    if ((profilingFlags & (1 << WriteMethodTableWriteableData)) != 0)
-        kindWriteable = DataImage::ITEM_METHOD_TABLE_DATA_HOT_WRITEABLE;
-
-    ZapStoredStructure * pNode = image->StoreStructure(NULL, size, kindWriteable);
-    image->BindPointer(this, pNode, 0);
-    image->CopyData(pNode, this, sizeof(MethodTableWriteableData));
-}
-
-//==========================================================================================
-void MethodTableWriteableData::Fixup(DataImage *image, MethodTable *pMT, BOOL needsRestore)
-{
-    STANDARD_VM_CONTRACT;
-
-    image->ZeroField(this, offsetof(MethodTableWriteableData, m_hExposedClassObject), sizeof(m_hExposedClassObject));
-
-    MethodTableWriteableData *pNewNgenPrivateMT = (MethodTableWriteableData*) image->GetImagePointer(this);
-    _ASSERTE(pNewNgenPrivateMT != NULL);
-
-    if (needsRestore)
-        pNewNgenPrivateMT->m_dwFlags |= (enum_flag_UnrestoredTypeKey |
-                                         enum_flag_Unrestored |
-                                         enum_flag_HasApproxParent |
-                                         enum_flag_IsNotFullyLoaded);
-
-#ifdef _DEBUG
-    pNewNgenPrivateMT->m_dwLastVerifedGCCnt = (DWORD)-1;
-#endif
-}
-
-#endif // !DACCESS_COMPILE
-
-#endif // FEATURE_NATIVE_IMAGE_GENERATION
-
-//==========================================================================================
-void MethodTable::CheckRestore()
-{
-    CONTRACTL
-    {
-        if (FORBIDGC_LOADER_USE_ENABLED()) NOTHROW; else THROWS;
-        if (FORBIDGC_LOADER_USE_ENABLED()) GC_NOTRIGGER; else GC_TRIGGERS;
-    }
-    CONTRACTL_END
-
-    if (!IsFullyLoaded())
-    {
-        ClassLoader::EnsureLoaded(this);
-        _ASSERTE(IsFullyLoaded());
-    }
-
-    g_IBCLogger.LogMethodTableAccess(this);
-}
-
-#ifndef DACCESS_COMPILE
-
-BOOL SatisfiesClassConstraints(TypeHandle instanceTypeHnd, TypeHandle typicalTypeHnd,
-                               const InstantiationContext *pInstContext);
-
-static VOID DoAccessibilityCheck(MethodTable *pAskingMT, MethodTable *pTargetMT, UINT resIDWhy)
-{
-    CONTRACTL
-    {
-        THROWS;
-        GC_TRIGGERS;
-    }
-    CONTRACTL_END;
-
-    AccessCheckContext accessContext(NULL, pAskingMT);
-
-    if (!ClassLoader::CanAccessClass(&accessContext,
-                                     pTargetMT,                 //the desired class
-                                     pTargetMT->GetAssembly(),  //the desired class's assembly
-                                     *AccessCheckOptions::s_pNormalAccessChecks
-                                    ))
-    {
-        SString displayName;
-        pAskingMT->GetAssembly()->GetDisplayName(displayName);
-        SString targetName;
-
-        // Error string is either E_ACCESSDENIED which requires the type name of the target, vs
-        // a more normal TypeLoadException which displays the requesting type.
-       _ASSERTE((resIDWhy == (UINT)E_ACCESSDENIED) || (resIDWhy == (UINT)IDS_CLASSLOAD_INTERFACE_NO_ACCESS));
-        TypeString::AppendType(targetName, TypeHandle((resIDWhy == (UINT)E_ACCESSDENIED) ? pTargetMT : pAskingMT));
-
-        COMPlusThrow(kTypeLoadException, resIDWhy, targetName.GetUnicode(), displayName.GetUnicode());
-    }
-
-}
-
-VOID DoAccessibilityCheckForConstraint(MethodTable *pAskingMT, TypeHandle thConstraint, UINT resIDWhy)
-{
-    CONTRACTL
-    {
-        THROWS;
-        GC_TRIGGERS;
-    }
-    CONTRACTL_END;
-
-    if (thConstraint.IsArray())
-    {
-        DoAccessibilityCheckForConstraint(pAskingMT, thConstraint.GetArrayElementTypeHandle(), resIDWhy);
-    }
-    else if (thConstraint.IsTypeDesc())
-    {
-        TypeDesc *pTypeDesc = thConstraint.AsTypeDesc();
-
-        if (pTypeDesc->IsGenericVariable())
-        {
-            // since the metadata respresents a generic type param constraint as an index into
-            // the declaring type's list of generic params, it is structurally impossible
-            // to express a violation this way. So there's no check to be done here.
-        }
-        else
-        if (pTypeDesc->HasTypeParam())
-        {
-            DoAccessibilityCheckForConstraint(pAskingMT, pTypeDesc->GetTypeParam(), resIDWhy);
-        }
-        else
-        {
-            COMPlusThrow(kTypeLoadException, E_ACCESSDENIED);
-        }
-
-    }
-    else
-    {
-        DoAccessibilityCheck(pAskingMT, thConstraint.GetMethodTable(), resIDWhy);
-    }
-
-}
-
-VOID DoAccessibilityCheckForConstraints(MethodTable *pAskingMT, TypeVarTypeDesc *pTyVar, UINT resIDWhy)
-{
-    CONTRACTL
-    {
-        THROWS;
-        GC_TRIGGERS;
-    }
-    CONTRACTL_END;
-
-    DWORD numConstraints;
-    TypeHandle *pthConstraints = pTyVar->GetCachedConstraints(&numConstraints);
-    for (DWORD cidx = 0; cidx < numConstraints; cidx++)
-    {
-        TypeHandle thConstraint = pthConstraints[cidx];
-
-        DoAccessibilityCheckForConstraint(pAskingMT, thConstraint, resIDWhy);
-    }
-}
-
-
-// Recursive worker that pumps the transitive closure of a type's dependencies to the specified target level.
-// Dependencies include:
-//
-//   - parent
-//   - interfaces
-//   - canonical type, for non-canonical instantiations
-//   - typical type, for non-typical instantiations
-//
-// Parameters:
-//
-//   pVisited - used to prevent endless recursion in the case of cyclic dependencies
-//
-//   level    - target level to pump to - must be CLASS_DEPENDENCIES_LOADED or CLASS_LOADED
-//
-//              if CLASS_DEPENDENCIES_LOADED, all transitive dependencies are resolved to their
-//                 exact types.
-//
-//              if CLASS_LOADED, all type-safety checks are done on the type and all its transitive
-//                 dependencies. Note that for the CLASS_LOADED case, some types may be left
-//                 on the pending list rather that pushed to CLASS_LOADED in the case of cyclic
-//                 dependencies - the root caller must handle this.
-//
-//   pfBailed - if we or one of our depedencies bails early due to cyclic dependencies, we
-//              must set *pfBailed to TRUE. Otherwise, we must *leave it unchanged* (thus, the
-//              boolean acts as a cumulative OR.)
-//
-//   pPending - if one of our dependencies bailed, the type cannot yet be promoted to CLASS_LOADED
-//              as the dependencies will be checked later and may fail a security check then.
-//              Instead, DoFullyLoad() will add the type to the pending list - the root caller
-//              is responsible for promoting the type after the full transitive closure has been
-//              walked. Note that it would be just as correct to always defer to the pending list -
-//              however, that is a little less performant.
-//
-
-
-// Closure of locals necessary for implementing CheckForEquivalenceAndFullyLoadType.
-// Used so that we can have one valuetype walking algorithm used for type equivalence walking of the parameters of the method.
-struct DoFullyLoadLocals
-{
-    DoFullyLoadLocals(DFLPendingList *pPendingParam, ClassLoadLevel levelParam, MethodTable *pMT, Generics::RecursionGraph *pVisited)
-        : newVisited(pVisited, TypeHandle(pMT))
-        , pPending(pPendingParam)
-        , level(levelParam)
-        , fBailed(FALSE)
-#ifdef FEATURE_TYPEEQUIVALENCE
-        , fHasEquivalentStructParameter(FALSE)
-#endif
-        , fHasTypeForwarderDependentStructParameter(FALSE)
-        , fDependsOnEquivalentOrForwardedStructs(FALSE)
-    {
-        LIMITED_METHOD_CONTRACT;
+        LIMITED_METHOD_CONTRACT;
     }
 
     Generics::RecursionGraph newVisited;
@@ -5486,31 +4386,6 @@ void MethodTable::DoFullyLoad(Generics::RecursionGraph * const pVisited,  const
         }
     }
 
-#ifdef FEATURE_NATIVE_IMAGE_GENERATION
-    // Fully load the types of instance fields in types with layout when ngenning
-    if (HasLayout() && GetAppDomain()->IsCompilationDomain() && !IsZapped())
-    {
-        ApproxFieldDescIterator fieldDescs(this, ApproxFieldDescIterator::INSTANCE_FIELDS);
-
-        for (int i = 0; i < fieldDescs.Count(); i++)
-        {
-            FieldDesc* pFieldDesc = fieldDescs.Next();
-
-            // If the fielddesc pointer here is a token tagged pointer, then the field that we are
-            // working with will not need to be saved into this ngen image. And as that was the reason that we
-            // needed to load this type, thus we will not need to fully load the type associated with this field desc.
-            //
-            if (!CORCOMPILE_IS_POINTER_TAGGED(pFieldDesc))
-            {
-                TypeHandle th = pFieldDesc->GetFieldTypeHandleThrowing((ClassLoadLevel) (level-1));
-                CONSISTENCY_CHECK(!th.IsNull());
-
-                th.DoFullyLoad(&locals.newVisited, level, pPending, &locals.fBailed, pInstContext);
-            }
-        }
-    }
-#endif //FEATURE_NATIVE_IMAGE_GENERATION
-
     // Fully load exact parameter types for value type parameters opted into equivalence. This is required in case GC is
     // triggered during prestub. GC needs to know where references are on the stack and if the parameter (as read from
     // the method signature) is a structure, it relies on the loaded type to get the layout information from. For ordinary
index 816da7e..cc9a3f5 100644 (file)
@@ -391,10 +391,6 @@ public:
 #endif
 
 #ifdef FEATURE_PREJIT
-
-    void Save(DataImage *image, MethodTable *pMT, DWORD profilingFlags) const;
-    void Fixup(DataImage *image, MethodTable *pMT, BOOL needsRestore);
-
     inline BOOL IsFixedUp() const
     {
         LIMITED_METHOD_CONTRACT;
@@ -946,41 +942,6 @@ public:
     // The pending list is required for restoring types that reference themselves through
     // instantiations of the superclass or interfaces e.g. System.Int32 : IComparable<System.Int32>
 
-
-#ifdef FEATURE_PREJIT
-
-    void Save(DataImage *image, DWORD profilingFlags);
-    void Fixup(DataImage *image);
-
-    // This is different from !IsRestored() in that it checks if restoring
-    // will ever be needed for this ngened data-structure.
-    // This is to be used at ngen time of a dependent module to determine
-    // if it can be accessed directly, or if the restoring mechanism needs
-    // to be hooked in.
-    BOOL ComputeNeedsRestore(DataImage *image, TypeHandleList *pVisited);
-
-    BOOL NeedsRestore(DataImage *image)
-    {
-        WRAPPER_NO_CONTRACT;
-        return ComputeNeedsRestore(image, NULL);
-    }
-
-private:
-    BOOL ComputeNeedsRestoreWorker(DataImage *image, TypeHandleList *pVisited);
-
-public:
-    // This returns true at NGen time if we can eager bind to all dictionaries along the inheritance chain
-    BOOL CanEagerBindToParentDictionaries(DataImage *image, TypeHandleList *pVisited);
-
-    // This returns true at NGen time if we may need to attach statics to
-    // other module than current loader module at runtime
-    BOOL NeedsCrossModuleGenericsStaticsInfo();
-
-    // Returns true at NGen time if we may need to write into the MethodTable at runtime
-    BOOL IsWriteable();
-
-#endif // FEATURE_PREJIT
-
     void AllocateRegularStaticBoxes();
     static OBJECTREF AllocateStaticBox(MethodTable* pFieldMT, BOOL fPinned, OBJECTHANDLE* pHandle = 0);
 
@@ -1535,7 +1496,6 @@ public:
 
 #ifdef FEATURE_PREJIT
     static BOOL CanShareVtableChunksFrom(MethodTable *pTargetMT, Module *pCurrentLoaderModule, Module *pCurrentPreferredZapModule);
-    BOOL CanInternVtableChunk(DataImage *image, VtableIndirectionSlotIterator it);
 #else
     static BOOL CanShareVtableChunksFrom(MethodTable *pTargetMT, Module *pCurrentLoaderModule);
 #endif
@@ -2340,12 +2300,6 @@ public:
     // GetExtraInterfaceInfoSize() returned zero, this call must still be made (with a NULL argument).
     void InitializeExtraInterfaceInfo(PVOID pInfo);
 
-#ifdef FEATURE_PREJIT
-    // Ngen support.
-    void SaveExtraInterfaceInfo(DataImage *pImage);
-    void FixupExtraInterfaceInfo(DataImage *pImage);
-#endif // FEATURE_PREJIT
-
 #ifdef DACCESS_COMPILE
     void EnumMemoryRegionsForExtraInterfaceInfo();
 #endif // DACCESS_COMPILE
@@ -2974,21 +2928,6 @@ public:
     // If not instantiated, return NULL
     PTR_Dictionary GetDictionary();
 
-#ifdef FEATURE_PREJIT
-    //
-    // After the zapper compiles all code in a module it may attempt
-    // to populate entries in all dictionaries
-    // associated with generic types.  This is an optional step - nothing will
-    // go wrong at runtime except we may get more one-off calls to JIT_GenericHandle.
-    // Although these are one-off we prefer to avoid them since they touch metadata
-    // pages.
-    //
-    // Fully populating a dictionary may in theory load more types. However
-    // for the moment only those entries that refer to types that
-    // are already loaded will be filled in.
-    void PrepopulateDictionary(DataImage * image, BOOL nonExpansive);
-#endif // FEATURE_PREJIT
-
     // Return a substitution suitbale for interpreting
     // the metadata in parent class, assuming we already have a subst.
     // suitable for interpreting the current class.
index b426204..5fdba35 100644 (file)
@@ -21,7 +21,6 @@
 #include "ecmakey.h"
 #include "customattribute.h"
 #include "typestring.h"
-#include "compile.h"
 
 //*******************************************************************************
 // Helper functions to sort GCdescs by offset (decending order)
@@ -3021,7 +3020,7 @@ MethodTableBuilder::EnumerateClassMethods()
 
             // Some interface checks.
             // We only need them if default interface method support is disabled or if this is fragile crossgen
-#if !defined(FEATURE_DEFAULT_INTERFACES) || defined(FEATURE_NATIVE_IMAGE_GENERATION)
+#if !defined(FEATURE_DEFAULT_INTERFACES)
             if (fIsClassInterface
 #if defined(FEATURE_DEFAULT_INTERFACES)
                 // Only fragile crossgen wasn't upgraded to deal with default interface methods.
@@ -3045,7 +3044,7 @@ MethodTableBuilder::EnumerateClassMethods()
                     }
                 }
             }
-#endif // !defined(FEATURE_DEFAULT_INTERFACES) || defined(FEATURE_NATIVE_IMAGE_GENERATION)
+#endif // !defined(FEATURE_DEFAULT_INTERFACES)
 
             // No synchronized methods in ValueTypes
             if(fIsClassValueType && IsMiSynchronized(dwImplFlags))
index c497b12..f2fc4f1 100644 (file)
 #include "ilmarshalers.h"
 #include "interoputil.h"
 
-#ifdef FEATURE_PREJIT
-    #include "dataimage.h"
-#endif
-
 #ifdef FEATURE_COMINTEROP
 #include "comcallablewrapper.h"
 #include "runtimecallablewrapper.h"
index 2caad78..e96e29e 100644 (file)
 #ifndef __NGEN_HASH_INCLUDED
 #define __NGEN_HASH_INCLUDED
 
-#ifdef FEATURE_PREJIT
-#include "corcompile.h"
-#endif
-
 // The type used to contain an entry hash value. This is not customizable on a per-hash class basis: all
 // NgenHash derived hashes will share the same definition. Note that we only care about the data size, and the
 // fact that it is an unsigned integer value (so we can take a modulus for bucket computation and use bitwise
@@ -253,48 +249,6 @@ protected:
     DPTR(VALUE) BaseFindFirstEntryByHash(NgenHashValue iHash, LookupContext *pContext);
     DPTR(VALUE) BaseFindNextEntryByHash(LookupContext *pContext);
 
-#if defined(FEATURE_PREJIT) && !defined(DACCESS_COMPILE)
-    // Call during ngen to save hash table data structures into the ngen image. Calls derived-class
-    // implementations of ShouldSave to determine which entries should be serialized, IsHotEntry to hot/cold
-    // split the entries and SaveEntry to allow per-entry extension of the saving process.
-    void BaseSave(DataImage *pImage, CorProfileData *pProfileData);
-
-    // Call during ngen to register fixups for hash table data structure fields. Calls derived-class
-    // implementation of FixupEntry to allow per-entry extension of the fixup process.
-    void BaseFixup(DataImage *pImage);
-
-    // Opaque structure used to store state will BaseSave is re-arranging hash entries and also passed to
-    // sub-classes' SaveEntry method to facilitate mapping old entry addresses to their new locations.
-    class EntryMappingTable
-    {
-    public:
-        ~EntryMappingTable();
-
-        // Given an old entry address (pre-BaseSave) return the address of the entry relocated ready for
-        // saving to disk. Note that this address is the (ngen) runtime address, not the disk image address
-        // you can further obtain by calling DataImage::GetImagePointer().
-        VALUE *GetNewEntryAddress(VALUE *pOldEntry);
-
-    private:
-        friend class NgenHashTable<NGEN_HASH_ARGS>;
-
-        // Each Entry holds the mapping from one old-to-new hash entry.
-        struct Entry
-        {
-            VALUE          *m_pOldEntry;        // Pointer to the user part of the old entry
-            VALUE          *m_pNewEntry;        // Pointer to the user part of the new version
-            NgenHashValue   m_iHashValue;       // The hash code of the entry
-            DWORD           m_dwNewBucket;      // The new bucket index of the entry
-            DWORD           m_dwChainOrdinal;   // The 0-based position within the chain of that bucket
-            bool            m_fHot;             // If true this entry was identified as hot by the sub-class
-        };
-
-        Entry  *m_pEntries;                     // Pointer to array of Entries
-        DWORD   m_cEntries;                     // Count of valid entries in the above (may be smaller than
-                                                // allocated size)
-    };
-#endif // FEATURE_PREJIT && !DACCESS_COMPILE
-
 #ifdef DACCESS_COMPILE
     // Call during DAC enumeration of memory regions to save in mini-dump to enumerate all hash table data
     // structures. Calls derived-class implementation of EnumMemoryRegionsForEntry to allow additional
@@ -313,92 +267,6 @@ protected:
 private:
     // Internal implementation details. Nothing of interest to sub-classers for here on.
 
-#ifdef FEATURE_PREJIT
-    // This is the format of each hash entry that is persisted to disk (Hot or Cold entries).
-    struct PersistedEntry
-    {
-        VALUE           m_sValue;       // The sub-class supplied entry layout
-        NgenHashValue   m_iHashValue;   // The hash code associated with the entry (comes after m_sValue to
-                                        // minimize chance of pad bytes on a 64-bit system).
-    };
-    typedef DPTR(PersistedEntry) PTR_PersistedEntry;
-    typedef ArrayDPTR(PersistedEntry) APTR_PersistedEntry;
-
-    // This class encapsulates a bucket list identifying chains of related persisted entries. It's compressed
-    // rather than being a simple array, hence the encapsulation.
-    // A bucket list represents a non-zero sequence of buckets, each bucket identified by a zero-based index.
-    // Each bucket holds the index of the entry at the start of the bucket chain and a count of entries in
-    // that chain. (In persisted form hash entries are collated into hot and cold entries which are then
-    // allocated in contiguous blocks: this allows entries to be identified by an index into the entry block).
-    // Buckets with zero entries have an undefined start index (and a zero count obviously).
-    class PersistedBucketList
-    {
-#ifdef DACCESS_COMPILE
-        friend class NativeImageDumper;
-#endif
-
-    public:
-        // Allocate and initialize a new list with the given count of buckets and configured to hold no more
-        // than the given number of entries or have a bucket chain longer than the specified maximum. These
-        // two maximums allow the implementation to choose an optimal data format for the bucket list at
-        // runtime and are enforced by asserts in the debug build.
-        static PersistedBucketList *CreateList(DWORD cBuckets, DWORD cEntries, DWORD cMaxEntriesInBucket);
-
-        // For the given bucket set the index of the initial entry and the count of entries in the chain. If
-        // the count is zero the initial entry index is meaningless and ignored.
-        void SetBucket(DWORD dwIndex, DWORD dwFirstEntry, DWORD cEntries);
-
-        // Get the size in bytes of this entire bucket list (need to pass in the bucket count since we save
-        // space by not storing it here, but we do validate this in debug mode).
-        size_t GetSize(DWORD cBuckets);
-
-        // Get the initial entry index and entry count for the given bucket. Initial entry index value is
-        // undefined when count comes back as zero.
-        void GetBucket(DWORD dwIndex, DWORD *pdwFirstEntry, DWORD *pdwCount);
-
-        // Simplified initial entry index when you don't need the count (don't call this for buckets with zero
-        // entries).
-        DWORD GetInitialEntry(DWORD dwIndex);
-
-    private:
-        // Return the number of bits required to express a unique ID for the number of entities given.
-        static DWORD BitsRequired(DWORD cEntities);
-
-        // Return the minimum size (in bytes) of each bucket list entry that can express all buckets given the
-        // max count of entries and entries in a single bucket chain.
-        static DWORD GetBucketSize(DWORD cEntries, DWORD cMaxEntriesInBucket);
-
-        // Each bucket is represented by a variable sized bitfield (16, 32 or 64 bits) whose low-order bits
-        // contain the index of the first entry in the chain and higher-order (just above the initial entry
-        // bits) contain the count of entries in the chain.
-
-        DWORD           m_cbBucket;             // The size in bytes of each bucket descriptor (2, 4 or 8)
-        DWORD           m_dwInitialEntryMask;   // The bitmask used to extract the initial entry index from a bucket
-        DWORD           m_dwEntryCountShift;    // The bit shift used to extract the entry count from a bucket
-
-#ifdef _DEBUG
-        // In debug mode we remember more initial state to catch common errors.
-        DWORD           m_cBuckets;             // Number of buckets in the list
-        DWORD           m_cEntries;             // Total number of entries mapped by the list
-        DWORD           m_cMaxEntriesInBucket;  // Largest bucket chain in the list
-#endif
-    };
-    typedef DPTR(PersistedBucketList) PTR_PersistedBucketList;
-
-    // Pointers and counters for entries and buckets persisted to disk during ngen. Collected into a structure
-    // because this logic is replicated for Hot and Cold entries so we can factor some common code.
-    struct PersistedEntries
-    {
-        RelativePointer<APTR_PersistedEntry>     m_pEntries;  // Pointer to a contiguous block of PersistedEntry structures
-                                                              // (NULL if zero entries)
-        RelativePointer<PTR_PersistedBucketList> m_pBuckets;  // Pointer to abstracted bucket list mapping above entries
-                                                              // into a hash (NULL if zero buckets, which is iff zero
-                                                              // entries)
-        DWORD                   m_cEntries;  // Count of entries in the above block
-        DWORD                   m_cBuckets;  // Count of buckets in the above bucket list
-    };
-#endif // FEATURE_PREJIT
-
     // This is the format of a Warm entry, defined for our purposes to be a non-persisted entry (i.e. those
     // created at runtime or during the creation of the ngen image itself).
     struct VolatileEntry;
@@ -418,14 +286,6 @@ private:
         Hot     // Persisted, profiling suggests this data is probably read (or no profiling data was available)
     };
 
-#ifdef FEATURE_PREJIT
-    // Find the first persisted entry (hot or cold based on pEntries) that matches the given hash. Looks only
-    // in the persisted block given (i.e. searches only hot *or* cold entries). Returns NULL on failure.
-    // Otherwise returns pointer to the derived class portion of the entry and initializes the provided
-    // LookupContext to allow enumeration of any further matches.
-    DPTR(VALUE) FindPersistedEntryByHash(PersistedEntries *pEntries, NgenHashValue iHash, LookupContext *pContext);
-#endif // FEATURE_PREJIT
-
     // Find the first volatile (warm) entry that matches the given hash. Looks only at warm entries. Returns
     // NULL on failure. Otherwise returns pointer to the derived class portion of the entry and initializes
     // the provided LookupContext to allow enumeration of any further matches.
@@ -450,84 +310,6 @@ private:
         return ReadPointer(this, &NgenHashTable<NGEN_HASH_ARGS>::m_pWarmBuckets);
     }
 
-#ifdef FEATURE_PREJIT
-    APTR_PersistedEntry GetPersistedHotEntries()
-    {
-        SUPPORTS_DAC;
-
-        return ReadPointerMaybeNull(this,
-                                    &NgenHashTable<NGEN_HASH_ARGS>::m_sHotEntries,
-                                    &decltype(NgenHashTable<NGEN_HASH_ARGS>::m_sHotEntries)::m_pEntries);
-    }
-
-    PTR_PersistedBucketList GetPersistedHotBuckets()
-    {
-        SUPPORTS_DAC;
-
-        return ReadPointerMaybeNull(this,
-                                    &NgenHashTable<NGEN_HASH_ARGS>::m_sHotEntries,
-                                    &decltype(NgenHashTable<NGEN_HASH_ARGS>::m_sHotEntries)::m_pBuckets);
-    }
-
-    APTR_PersistedEntry GetPersistedColdEntries()
-    {
-        SUPPORTS_DAC;
-
-        return ReadPointerMaybeNull(this,
-                                    &NgenHashTable<NGEN_HASH_ARGS>::m_sColdEntries,
-                                    &decltype(NgenHashTable<NGEN_HASH_ARGS>::m_sColdEntries)::m_pEntries);
-    }
-
-    PTR_PersistedBucketList GetPersistedColdBuckets()
-    {
-        SUPPORTS_DAC;
-
-        return ReadPointerMaybeNull(this,
-                                    &NgenHashTable<NGEN_HASH_ARGS>::m_sColdEntries,
-                                    &decltype(NgenHashTable<NGEN_HASH_ARGS>::m_sColdEntries)::m_pBuckets);
-    }
-
-#ifdef DACCESS_COMPILE
-    APTR_PersistedEntry GetPersistedEntries(DPTR(PersistedEntries) pEntries)
-    {
-        SUPPORTS_DAC;
-
-        TADDR hotEntriesAddr = dac_cast<TADDR>(this) + offsetof(NgenHashTable<NGEN_HASH_ARGS>, m_sHotEntries);
-        TADDR coldEntriesAddr = dac_cast<TADDR>(this) + offsetof(NgenHashTable<NGEN_HASH_ARGS>, m_sColdEntries);
-
-        if (hotEntriesAddr == dac_cast<TADDR>(pEntries))
-        {
-            return GetPersistedHotEntries();
-        }
-        else
-        {
-            _ASSERTE(hotEntriesAddr == dac_cast<TADDR>(pEntries));
-
-            return GetPersistedColdEntries();
-        }
-    }
-
-    PTR_PersistedBucketList GetPersistedBuckets(DPTR(PersistedEntries) pEntries)
-    {
-        SUPPORTS_DAC;
-
-        TADDR hotEntriesAddr = dac_cast<TADDR>(this) + offsetof(NgenHashTable<NGEN_HASH_ARGS>, m_sHotEntries);
-        TADDR coldEntriesAddr = dac_cast<TADDR>(this) + offsetof(NgenHashTable<NGEN_HASH_ARGS>, m_sColdEntries);
-
-        if (hotEntriesAddr == dac_cast<TADDR>(pEntries))
-        {
-            return GetPersistedHotBuckets();
-        }
-        else
-        {
-            _ASSERTE(hotEntriesAddr == dac_cast<TADDR>(pEntries));
-
-            return GetPersistedColdBuckets();
-        }
-    }
-#endif // DACCESS_COMPILE
-#endif // FEATURE_PREJIT
-
     // Loader heap provided at construction time. May be NULL (in which case m_pModule must *not* be NULL).
     LoaderHeap             *m_pHeap;
 
@@ -535,14 +317,6 @@ private:
     RelativePointer<DPTR(PTR_VolatileEntry)> m_pWarmBuckets;  // Pointer to a simple bucket list (array of VolatileEntry pointers)
     DWORD                                    m_cWarmBuckets;  // Count of buckets in the above array (always non-zero)
     DWORD                                    m_cWarmEntries;  // Count of elements in the warm section of the hash
-
-#ifdef FEATURE_PREJIT
-    PersistedEntries        m_sHotEntries;      // Hot persisted hash entries (if any)
-    PersistedEntries        m_sColdEntries;     // Cold persisted hash entries (if any)
-
-    DWORD                   m_cInitialBuckets;  // Initial number of warm buckets we started with. Only used
-                                                // to reset warm bucket count in ngen-persisted table.
-#endif // FEATURE_PREJIT
 };
 
 // Abstraction around cross-hash entry references (e.g. EEClassHashTable, where entries for nested types point
@@ -560,11 +334,6 @@ public:
     // Set the reference to point to the given entry.
     void Set(VALUE *pEntry);
 
-#ifdef FEATURE_PREJIT
-    // Call this during the ngen Fixup phase to adjust the relative pointer to account for ngen image layout.
-    void Fixup(DataImage *pImage, NgenHashTable<NGEN_HASH_ARGS> *pTable);
-#endif // FEATURE_PREJIT
-
     NgenHashEntryRef<NGEN_HASH_ARGS>& operator = (const NgenHashEntryRef<NGEN_HASH_ARGS> &src)
     {
         src.m_rpEntryRef.BitwiseCopyTo(m_rpEntryRef);
index 9c608f5..952f59d 100644 (file)
@@ -58,12 +58,6 @@ NgenHashTable<NGEN_HASH_ARGS>::NgenHashTable(Module *pModule, LoaderHeap *pHeap,
 
     // Note: Memory allocated on loader heap is zero filled
     // memset(m_pWarmBuckets, 0, sizeof(VolatileEntry*) * cInitialBuckets);
-
-#ifdef FEATURE_PREJIT
-    memset(&m_sHotEntries, 0, sizeof(PersistedEntries));
-    memset(&m_sColdEntries, 0, sizeof(PersistedEntries));
-    m_cInitialBuckets = cInitialBuckets;
-#endif // FEATURE_PREJIT
 }
 
 // Allocate an uninitialized entry for the hash table (it's not inserted). The AllocMemTracker is optional and
@@ -255,11 +249,7 @@ DWORD NgenHashTable<NGEN_HASH_ARGS>::BaseGetElementCount()
 {
     LIMITED_METHOD_DAC_CONTRACT;
 
-    return m_cWarmEntries
-#ifdef FEATURE_PREJIT
-        + m_sHotEntries.m_cEntries + m_sColdEntries.m_cEntries
-#endif
-        ;
+    return m_cWarmEntries;
 }
 
 // Find first entry matching a given hash value (returns NULL on no match). Call BaseFindNextEntryByHash to
@@ -281,24 +271,12 @@ DPTR(VALUE) NgenHashTable<NGEN_HASH_ARGS>::BaseFindFirstEntryByHash(NgenHashValu
 
     DPTR(VALUE) pEntry;
 
-#ifdef FEATURE_PREJIT
-    // Look in the hot entries first.
-    pEntry = FindPersistedEntryByHash(&m_sHotEntries, iHash, pContext);
-    if (pEntry)
-        return pEntry;
-#endif // FEATURE_PREJIT
-
     // Then the warm entries.
     pEntry = FindVolatileEntryByHash(iHash, pContext);
     if (pEntry)
         return pEntry;
 
-#ifdef FEATURE_PREJIT
-    // And finally the cold entries.
-    return FindPersistedEntryByHash(&m_sColdEntries, iHash, pContext);
-#else // FEATURE_PREJIT
     return NULL;
-#endif // FEATURE_PREJIT
 }
 
 // Find first entry matching a given hash value (returns NULL on no match). Call BaseFindNextEntryByHash to
@@ -322,47 +300,6 @@ DPTR(VALUE) NgenHashTable<NGEN_HASH_ARGS>::BaseFindNextEntryByHash(LookupContext
 
     switch (pContext->m_eType)
     {
-#ifdef FEATURE_PREJIT
-    case Hot:
-    case Cold:
-    {
-        // Fetch the entry we were looking at last from the context and remember the corresponding hash code.
-        PTR_PersistedEntry pPersistedEntry = dac_cast<PTR_PersistedEntry>(pContext->m_pEntry);
-        iHash = pPersistedEntry->m_iHashValue;
-
-        // Iterate while there are still entries left in the bucket chain.
-        while (pContext->m_cRemainingEntries)
-        {
-            // Advance to next entry, reducing the number of entries left to scan.
-            pPersistedEntry++;
-            pContext->m_cRemainingEntries--;
-
-            if (pPersistedEntry->m_iHashValue == iHash)
-            {
-                // Found a match on hash code. Update our find context to indicate where we got to and return
-                // a pointer to the sub-class portion of the entry.
-                pContext->m_pEntry = dac_cast<TADDR>(pPersistedEntry);
-                return VALUE_FROM_PERSISTED_ENTRY(pPersistedEntry);
-            }
-        }
-
-        // We didn't find a match.
-        if (pContext->m_eType == Hot)
-        {
-            // If we were searching the hot entries then we should try the warm entries next.
-            DPTR(VALUE) pNext = FindVolatileEntryByHash(iHash, pContext);
-            if (pNext)
-                return pNext;
-
-            // If that didn't work try the cold entries.
-            return FindPersistedEntryByHash(&m_sColdEntries, iHash, pContext);
-        }
-
-        // We were already searching cold entries, a failure here means the entry is not in the table.
-        return NULL;
-    }
-#endif // FEATURE_PREJIT
-
     case Warm:
     {
         // Fetch the entry we were looking at last from the context and remember the corresponding hash code.
@@ -383,12 +320,7 @@ DPTR(VALUE) NgenHashTable<NGEN_HASH_ARGS>::BaseFindNextEntryByHash(LookupContext
             }
         }
 
-        // We didn't find a match, fall through to the cold entries.
-#ifdef FEATURE_PREJIT
-        return FindPersistedEntryByHash(&m_sColdEntries, iHash, pContext);
-#else
         return NULL;
-#endif
     }
 
     default:
@@ -397,667 +329,6 @@ DPTR(VALUE) NgenHashTable<NGEN_HASH_ARGS>::BaseFindNextEntryByHash(LookupContext
     }
 }
 
-#ifdef FEATURE_PREJIT
-
-// Allocate and initialize a new list with the given count of buckets and configured to hold no more than the
-// given number of entries or have a bucket chain longer than the specified maximum. These two maximums allow
-// the implementation to choose an optimal data format for the bucket list at runtime and are enforced by
-// asserts in the debug build.
-// static
-template <NGEN_HASH_PARAMS>
-typename NgenHashTable<NGEN_HASH_ARGS>::PersistedBucketList *NgenHashTable<NGEN_HASH_ARGS>::PersistedBucketList::CreateList(DWORD cBuckets, DWORD cEntries, DWORD cMaxEntriesInBucket)
-{
-    CONTRACTL
-    {
-        THROWS;
-        GC_NOTRIGGER;
-        MODE_ANY;
-    }
-    CONTRACTL_END;
-
-    // The size of each bucket depends on the number of entries we need to store and how big a bucket chain
-    // ever gets.
-    DWORD cbBucket = GetBucketSize(cEntries, cMaxEntriesInBucket);
-
-    // Allocate enough memory to store the bucket list header and bucket array.
-    S_SIZE_T cbBuckets = S_SIZE_T(sizeof(PersistedBucketList)) + (S_SIZE_T(cbBucket) * S_SIZE_T(cBuckets));
-    if (cbBuckets.IsOverflow())
-        COMPlusThrowOM();
-    PersistedBucketList *pBucketList = (PersistedBucketList*)(new BYTE[cbBuckets.Value()]);
-
-#ifdef _DEBUG
-    // In debug builds we store all the input parameters to validate subsequent requests. In retail none of
-    // this data is needed.
-    pBucketList->m_cBuckets = cBuckets;
-    pBucketList->m_cEntries = cEntries;
-    pBucketList->m_cMaxEntriesInBucket = cMaxEntriesInBucket;
-#endif // _DEBUG
-
-    pBucketList->m_cbBucket = cbBucket;
-    pBucketList->m_dwEntryCountShift = BitsRequired(cEntries);
-    pBucketList->m_dwInitialEntryMask = (1 << pBucketList->m_dwEntryCountShift) - 1;
-
-    // Zero all the buckets (empty all the bucket chains).
-    memset(pBucketList + 1, 0, cBuckets * cbBucket);
-
-    return pBucketList;
-}
-
-// Get the size in bytes of this entire bucket list (need to pass in the bucket count since we save space by
-// not storing it here, but we do validate this in debug mode).
-template <NGEN_HASH_PARAMS>
-size_t NgenHashTable<NGEN_HASH_ARGS>::PersistedBucketList::GetSize(DWORD cBuckets)
-{
-    LIMITED_METHOD_DAC_CONTRACT;
-
-    _ASSERTE(cBuckets == m_cBuckets);
-    return sizeof(PersistedBucketList) + (cBuckets * m_cbBucket);
-}
-
-// Get the initial entry index and entry count for the given bucket. Initial entry index value is undefined
-// when count comes back as zero.
-template <NGEN_HASH_PARAMS>
-void NgenHashTable<NGEN_HASH_ARGS>::PersistedBucketList::GetBucket(DWORD dwIndex, DWORD *pdwFirstEntry, DWORD *pdwCount)
-{
-    CONTRACTL
-    {
-        NOTHROW;
-        GC_NOTRIGGER;
-        MODE_ANY;
-        SUPPORTS_DAC;
-    }
-    CONTRACTL_END;
-
-    _ASSERTE(dwIndex < m_cBuckets);
-
-    // Find the start of the bucket we're interested in based on the index and size chosen for buckets in this
-    // list instance.
-    TADDR pBucket = dac_cast<TADDR>(this) + sizeof(PersistedBucketList) + (dwIndex * m_cbBucket);
-
-    // Handle each format of bucket separately. In all cases read the correct number of bytes to form one
-    // bitfield, extract the low order bits to retrieve the initial entry index and shift down the remaining
-    // bits to obtain the entry count.
-    switch (m_cbBucket)
-    {
-    case 2:
-    {
-        _ASSERTE(m_dwEntryCountShift < 16 && m_dwInitialEntryMask < 0xffff);
-
-        WORD wBucketContents = *dac_cast<PTR_WORD>(pBucket);
-
-        *pdwFirstEntry = wBucketContents & m_dwInitialEntryMask;
-        *pdwCount = wBucketContents >> m_dwEntryCountShift;
-
-        break;
-    }
-
-    case 4:
-    {
-        _ASSERTE(m_dwEntryCountShift < 32 && m_dwInitialEntryMask < 0xffffffff);
-
-        DWORD dwBucketContents = *dac_cast<PTR_DWORD>(pBucket);
-
-        *pdwFirstEntry = dwBucketContents & m_dwInitialEntryMask;
-        *pdwCount = dwBucketContents >> m_dwEntryCountShift;
-
-        break;
-    }
-
-    case 8:
-    {
-        _ASSERTE(m_dwEntryCountShift < 64);
-
-        ULONG64 qwBucketContents = *dac_cast<PTR_ULONG64>(pBucket);
-
-        *pdwFirstEntry = (DWORD)(qwBucketContents & m_dwInitialEntryMask);
-        *pdwCount = (DWORD)(qwBucketContents >> m_dwEntryCountShift);
-
-        break;
-    }
-
-    default:
-#ifdef DACCESS_COMPILE
-        // Minidumps don't guarantee this will work - memory may not have been dumped, target corrupted, etc.
-        *pdwFirstEntry = 0;
-        *pdwCount = 0;
-#else
-        _ASSERTE(!"Invalid bucket list bucket size");
-#endif
-    }
-
-    _ASSERTE((*pdwFirstEntry < m_cEntries) || (*pdwCount == 0));
-    _ASSERTE(*pdwCount <= m_cMaxEntriesInBucket);
-}
-
-// Simplified initial entry index when you don't need the count (don't call this for buckets with zero
-// entries).
-template <NGEN_HASH_PARAMS>
-DWORD NgenHashTable<NGEN_HASH_ARGS>::PersistedBucketList::GetInitialEntry(DWORD dwIndex)
-{
-    CONTRACTL
-    {
-        NOTHROW;
-        GC_NOTRIGGER;
-        MODE_ANY;
-        SUPPORTS_DAC;
-    }
-    CONTRACTL_END;
-
-    DWORD dwInitialEntry, dwEntryCount;
-    GetBucket(dwIndex, &dwInitialEntry, &dwEntryCount);
-
-    _ASSERTE(dwEntryCount > 0);
-
-    return dwInitialEntry;
-}
-
-// For the given bucket set the index of the initial entry and the count of entries in the chain. If the count
-// is zero the initial entry index is meaningless and ignored.
-template <NGEN_HASH_PARAMS>
-void NgenHashTable<NGEN_HASH_ARGS>::PersistedBucketList::SetBucket(DWORD dwIndex, DWORD dwFirstEntry, DWORD cEntries)
-{
-    CONTRACTL
-    {
-        NOTHROW;
-        GC_NOTRIGGER;
-        MODE_ANY;
-    }
-    CONTRACTL_END;
-
-    _ASSERTE(dwIndex < m_cBuckets);
-    _ASSERTE(cEntries <= m_cMaxEntriesInBucket);
-    if (cEntries > 0)
-    {
-        _ASSERTE(dwFirstEntry < m_cEntries);
-        _ASSERTE(dwFirstEntry <= m_dwInitialEntryMask);
-    }
-
-    // Find the start of the bucket we're interested in based on the index and size chosen for buckets in this
-    // list instance.
-    BYTE *pbBucket = (BYTE*)this + sizeof(PersistedBucketList) + (dwIndex * m_cbBucket);
-
-    // Handle each format of bucket separately. In all cases form a single bitfield with low-order bits
-    // specifying the initial entry index and higher bits containing the entry count. Write this into the
-    // bucket entry using the correct number of bytes.
-    ULONG64 qwBucketBits = dwFirstEntry | (cEntries << m_dwEntryCountShift);
-    switch (m_cbBucket)
-    {
-    case 2:
-    {
-        _ASSERTE(m_dwEntryCountShift < 16 && m_dwInitialEntryMask < 0xffff);
-        *(WORD*)pbBucket = (WORD)qwBucketBits;
-        break;
-    }
-
-    case 4:
-    {
-        _ASSERTE(m_dwEntryCountShift < 32 && m_dwInitialEntryMask < 0xffffffff);
-        *(DWORD*)pbBucket = (DWORD)qwBucketBits;
-        break;
-    }
-
-    case 8:
-    {
-        _ASSERTE(m_dwEntryCountShift < 64);
-        *(ULONG64*)pbBucket = qwBucketBits;
-        break;
-    }
-
-    default:
-        _ASSERTE(!"Invalid bucket list bucket size");
-    }
-}
-
-// Return the number of bits required to express a unique ID for the number of entities given.
-//static
-template <NGEN_HASH_PARAMS>
-DWORD NgenHashTable<NGEN_HASH_ARGS>::PersistedBucketList::BitsRequired(DWORD cEntities)
-{
-    LIMITED_METHOD_CONTRACT;
-
-    // Starting with a bit-mask of the most significant bit and iterating over masks for successively less
-    // significant bits, stop as soon as the mask co-incides with a set bit in the value. Simultaneously we're
-    // counting down the bits required to express the range of values implied by seeing the corresponding bit
-    // set in the value (e.g. when we're testing the high bit we know we'd need 32-bits to encode the range of
-    // values that have this bit set). Stop when we get to one bit (we never return 0 bits required, even for
-    // an input value of 0).
-    DWORD dwMask = 0x80000000;
-    DWORD cBits = 32;
-    while (cBits > 1)
-    {
-        if (cEntities & dwMask)
-            return cBits;
-
-        dwMask >>= 1;
-        cBits--;
-    }
-
-    return 1;
-}
-
-// Return the minimum size (in bytes) of each bucket list entry that can express all buckets given the max
-// count of entries and entries in a single bucket chain.
-// static
-template <NGEN_HASH_PARAMS>
-DWORD NgenHashTable<NGEN_HASH_ARGS>::PersistedBucketList::GetBucketSize(DWORD cEntries, DWORD cMaxEntriesInBucket)
-{
-    CONTRACTL
-    {
-        NOTHROW;
-        GC_NOTRIGGER;
-        MODE_ANY;
-    }
-    CONTRACTL_END;
-
-    // We need enough bits to express a start entry index (related to the total number of entries in the
-    // table) and a chain count (so take the maximum chain length into consideration).
-    DWORD cTotalBits = BitsRequired(cEntries) + BitsRequired(cMaxEntriesInBucket);
-
-    // Rather than support complete flexibility (an arbitrary number of bytes to express the combination of
-    // the two bitfields above) we'll just pull out the most useful selection (which simplifies the access
-    // code and potentially might give us a perf edge over the more generalized algorithm).
-
-    // We want naturally aligned bucket entries for access perf, 1 byte entries aren't all that interesting
-    // (most tables won't be small enough to be expressed this way and those that are won't get much benefit
-    // from the extra compression of the bucket list). We also don't believe we'll ever need more than 64
-    // bits. This leaves us with 2, 4 and 8 byte entries. The tables in the current desktop CLR for mscorlib
-    // will fit in the 2-byte category and will give us substantial space saving over the naive implementation
-    // of a bucket with two DWORDs.
-
-    if (cTotalBits <= 16)
-        return 2;
-
-    if (cTotalBits <= 32)
-        return 4;
-
-    // Invariant guaranteed by BitsRequired above.
-    _ASSERTE(cTotalBits <= 64);
-    return 8;
-}
-
-#ifndef DACCESS_COMPILE
-
-#ifdef _MSC_VER
-#pragma warning(push)
-#pragma warning(disable:4723) // Prevent "warning C4723: potential divide by 0"
-#endif // _MSC_VER
-
-// Call during ngen to save hash table data structures into the ngen image. Calls derived-class
-// implementations of ShouldSave to determine which entries should be serialized, IsHotEntry to hot/cold split
-// the entries and SaveEntry to allow per-entry extension of the saving process.
-template <NGEN_HASH_PARAMS>
-void NgenHashTable<NGEN_HASH_ARGS>::BaseSave(DataImage *pImage, CorProfileData *pProfileData)
-{
-    STANDARD_VM_CONTRACT;
-
-    // This is a fairly long and complex process but at its heart it's fairly linear. We perform multiple
-    // passes over the data in sequence which might seem slow but everything is arranged to avoid any O(N^2)
-    // algorithms.
-
-    // Persisted hashes had better have supplied an owning module at creation time (otherwise we won't know
-    // how to find a loader heap for further allocations at runtime: we don't know how to serialize a loader
-    // heap pointer).
-    _ASSERTE(!m_pModule.IsNull());
-
-    // We can only save once during ngen so the hot and cold sections of the hash cannot have been populated
-    // yet.
-    _ASSERTE(m_sHotEntries.m_cEntries == 0 && m_sColdEntries.m_cEntries == 0);
-
-    DWORD i;
-
-    // As we re-arrange volatile warm entries into hot and cold sets of persisted entries we need to keep lots
-    // of intermediate tracking information. We also need to provide a subset of this mapping information to
-    // the sub-class (so it can fix up cross entry references for example). The temporary structure allocated
-    // below performs that function (it will be destructed automatically at the end of this method).
-    EntryMappingTable sEntryMap;
-    sEntryMap.m_cEntries = m_cWarmEntries;
-#ifdef _PREFAST_
-#pragma warning(suppress:6211) // Suppress bogus prefast warning about memory leak (EntryMappingTable acts as a holder)
-#endif
-
-    // The 'typename' keyword shouldn't be necessary, but g++ gets confused without it.
-    sEntryMap.m_pEntries = new typename EntryMappingTable::Entry[m_cWarmEntries];
-
-    //
-    // PHASE 1
-    //
-    //  Iterate all the current warm entries, ask the sub-class which of them should be saved into the image
-    //  and of those which are hot and which are cold.
-    //
-
-    DWORD cHotEntries = 0;
-    DWORD cColdEntries = 0;
-
-    // Visit each warm bucket.
-    for (i = 0; i < m_cWarmBuckets; i++)
-    {
-        // Iterate through the chain of warm entries for this bucket.
-        VolatileEntry *pOldEntry = (GetWarmBuckets())[i];
-        while (pOldEntry)
-        {
-            // Is the current entry being saved into the image?
-            if (DOWNCALL(ShouldSave)(pImage, &pOldEntry->m_sValue))
-            {
-                // Yes, so save the details into the next available slot in the entry map. At this stage we
-                // know the original entry address, the hash value and whether the entry is hot or cold.
-                DWORD dwCurrentEntry = cHotEntries + cColdEntries;
-                sEntryMap.m_pEntries[dwCurrentEntry].m_pOldEntry = &pOldEntry->m_sValue;
-                sEntryMap.m_pEntries[dwCurrentEntry].m_iHashValue = pOldEntry->m_iHashValue;
-
-                // Is the entry hot? When given no profile data we assume cold.
-                if (pProfileData != NULL && DOWNCALL(IsHotEntry)(&pOldEntry->m_sValue, pProfileData))
-                {
-                    cHotEntries++;
-                    sEntryMap.m_pEntries[dwCurrentEntry].m_fHot = true;
-                }
-                else
-                {
-                    cColdEntries++;
-                    sEntryMap.m_pEntries[dwCurrentEntry].m_fHot = false;
-                }
-            }
-
-            pOldEntry = pOldEntry->m_pNextEntry;
-        }
-    }
-
-    // Set size of the entry map based on the real number of entries we're going to save.
-    _ASSERTE((cHotEntries + cColdEntries) <= m_cWarmEntries);
-    sEntryMap.m_cEntries = cHotEntries + cColdEntries;
-
-    //
-    // PHASE 2
-    //
-    //  Determine the layout of the new hot and cold tables (if applicable). We pick new bucket list sizes
-    //  based on the number of entries to go in each table and from that we can calculate the length of each
-    //  entry chain off each bucket (which is important both to derive a maximum chain length used when
-    //  picking an optimized encoding for the bucket list and allows us to layout the new entries in linear
-    //  time).
-    //
-    // We need a couple of extra arrays to track bucket chain sizes until we have enough info to allocate the
-    // new bucket lists themselves.
-    //
-
-    // We'll allocate half as many buckets as entries (with at least 1 bucket, or zero if there are no entries
-    // in this section of the hash).
-    DWORD cHotBuckets = cHotEntries ? NextLargestPrime(cHotEntries / 2) : 0;
-    DWORD cColdBuckets = cColdEntries ? NextLargestPrime(cColdEntries / 2) : 0;
-
-    // Allocate arrays to track bucket chain lengths for each hot or cold bucket list (as needed).
-    DWORD *pHotBucketSizes = cHotBuckets ? new DWORD[cHotBuckets] : NULL;
-    memset(pHotBucketSizes, 0, cHotBuckets * sizeof(DWORD));
-
-    DWORD *pColdBucketSizes = cColdBuckets ? new DWORD[cColdBuckets] : NULL;
-    memset(pColdBucketSizes, 0, cColdBuckets * sizeof(DWORD));
-
-    // We'll calculate the maximum bucket chain length separately for hot and cold sections (each has its own
-    // bucket list that might be optimized differently).
-    DWORD cMaxHotChain = 0;
-    DWORD cMaxColdChain = 0;
-
-    // Iterate through all the entries to be saved (linear scan through the entry map we built in phase 1).
-    for (i = 0; i < sEntryMap.m_cEntries; i++)
-    {
-        // The 'typename' keyword shouldn't be necessary, but g++ gets confused without it.
-        typename EntryMappingTable::Entry *pMapEntry = &sEntryMap.m_pEntries[i];
-
-        // For each entry calculate which bucket it will end up in under the revised bucket list. Also record
-        // its order in the bucket chain (first come, first served). Recording this ordinal now is what allows
-        // us to lay out entries into their final order using a linear algorithm in a later phase.
-        if (pMapEntry->m_fHot)
-        {
-            _ASSERTE(cHotBuckets != 0);
-            pMapEntry->m_dwNewBucket = pMapEntry->m_iHashValue % cHotBuckets;
-            pMapEntry->m_dwChainOrdinal = pHotBucketSizes[pMapEntry->m_dwNewBucket]++;
-            if (pHotBucketSizes[pMapEntry->m_dwNewBucket] > cMaxHotChain)
-                cMaxHotChain = pHotBucketSizes[pMapEntry->m_dwNewBucket];
-        }
-        else
-        {
-            // The C++ compiler is currently complaining that cColdBuckets could be zero in the modulo
-            // operation below. It cannot due to the logic in this method (if we have a cold entry we'll have
-            // at least one cold bucket, see the assignments above) but the flow is far too complex for the
-            // C++ compiler to follow. Unfortunately it won't be told (the warning can't be disabled and even
-            // an __assume won't work) so we take the hit of generating the useless extra if below.
-            if (cColdBuckets > 0)
-            {
-                pMapEntry->m_dwNewBucket = pMapEntry->m_iHashValue % cColdBuckets;
-                pMapEntry->m_dwChainOrdinal = pColdBucketSizes[pMapEntry->m_dwNewBucket]++;
-                if (pColdBucketSizes[pMapEntry->m_dwNewBucket] > cMaxColdChain)
-                    cMaxColdChain = pColdBucketSizes[pMapEntry->m_dwNewBucket];
-            }
-            else
-                _ASSERTE(!"Should be unreachable, see comment above");
-        }
-    }
-
-    //
-    // PHASE 3
-    //
-    //  Allocate the new hot and cold bucket lists and entry arrays (as needed). The bucket lists have
-    //  optimized layout based on knowledge of the entries they will map (total number of entries and the size
-    //  of the largest single bucket chain).
-    //
-
-    if (cHotEntries)
-    {
-        m_sHotEntries.m_cEntries = cHotEntries;
-        m_sHotEntries.m_cBuckets = cHotBuckets;
-        m_sHotEntries.m_pEntries.SetValue(new PersistedEntry[cHotEntries]);
-        m_sHotEntries.m_pBuckets.SetValue(PersistedBucketList::CreateList(cHotBuckets, cHotEntries, cMaxHotChain));
-        memset(GetPersistedHotEntries(), 0, cHotEntries * sizeof(PersistedEntry)); // NGen determinism
-    }
-
-    if (cColdEntries)
-    {
-        m_sColdEntries.m_cEntries = cColdEntries;
-        m_sColdEntries.m_cBuckets = cColdBuckets;
-        m_sColdEntries.m_pEntries.SetValue(new PersistedEntry[cColdEntries]);
-        m_sColdEntries.m_pBuckets.SetValue(PersistedBucketList::CreateList(cColdBuckets, cColdEntries, cMaxColdChain));
-        memset(GetPersistedColdEntries(), 0, cColdEntries * sizeof(PersistedEntry));    // NGen determinism
-    }
-
-    //
-    // PHASE 4
-    //
-    //  Initialize the bucket lists. We need to set an initial entry index (index into the entry array) and
-    //  entry count for each bucket. The counts we already computed in phase 2 and since we're free to order
-    //  the entry array however we like, we can compute the initial entry index for each bucket in turn
-    //  trivially by laying out all entries for bucket 0 first followed by all entries for bucket 1 etc.
-    //
-    // This also has the nice effect of placing entries in the same bucket chain contiguously (and in the
-    // order that a full hash traversal will take).
-    //
-
-    DWORD dwNextId = 0; // This represents the index of the next entry to start a bucket chain
-    for (i = 0; i < cHotBuckets; i++)
-    {
-        m_sHotEntries.m_pBuckets.GetValue()->SetBucket(i, dwNextId, pHotBucketSizes[i]);
-        dwNextId += pHotBucketSizes[i];
-    }
-    _ASSERTE(dwNextId == m_sHotEntries.m_cEntries);
-
-    dwNextId = 0; // Reset index for the cold entries (remember they have their own table of entries)
-    for (i = 0; i < cColdBuckets; i++)
-    {
-        m_sColdEntries.m_pBuckets.GetValue()->SetBucket(i, dwNextId, pColdBucketSizes[i]);
-        dwNextId += pColdBucketSizes[i];
-    }
-    _ASSERTE(dwNextId == m_sColdEntries.m_cEntries);
-
-    //
-    // PHASE 5
-    //
-    //  Determine new addresses for each entry. This is relatively simple since we know the bucket index, the
-    //  index of the first entry for that bucket and how far into that chain each entry is located.
-    //
-
-    for (i = 0; i < sEntryMap.m_cEntries; i++)
-    {
-        // The 'typename' keyword shouldn't be necessary, but g++ gets confused without it.
-        typename EntryMappingTable::Entry *pMapEntry = &sEntryMap.m_pEntries[i];
-
-        // Entry block depends on whether this entry is hot or cold.
-        APTR_PersistedEntry pPersistedEntries = pMapEntry->m_fHot ? GetPersistedHotEntries() : GetPersistedColdEntries();
-        PTR_PersistedBucketList pPersistedBucketsList = pMapEntry->m_fHot ? GetPersistedHotBuckets() : GetPersistedColdBuckets();
-
-        // We already know the new bucket this entry will go into. Retrieve the index of the first entry in
-        // that bucket chain.
-        DWORD dwBaseChainIndex = pPersistedBucketsList->GetInitialEntry(pMapEntry->m_dwNewBucket);
-
-        // This entry will be located at some offset from the index above (we calculated this ordinal in phase
-        // 2).
-        PersistedEntry *pNewEntry = &pPersistedEntries[dwBaseChainIndex + pMapEntry->m_dwChainOrdinal];
-
-        // Record the address of the embedded sub-class hash entry in the map entry (sub-classes will use this
-        // info to map old entry addresses to their new locations).
-        sEntryMap.m_pEntries[i].m_pNewEntry = &pNewEntry->m_sValue;
-
-        // Initialize the new entry. Note that a simple bit-copy is performed on the sub-classes embedded
-        // entry. If fixups are needed they can be performed in the call to SaveEntry in the next phase.
-        pNewEntry->m_sValue = *pMapEntry->m_pOldEntry;
-        pNewEntry->m_iHashValue = pMapEntry->m_iHashValue;
-    }
-
-    //
-    // PHASE 6
-    //
-    //  For each entry give the hash sub-class a chance to perform any additional saving or fixups. We pass
-    //  both the old and new address of each entry, plus the mapping table so they can map other entry
-    //  addresses (if, for example, they have cross-entry pointer fields in their data).
-    //
-    //  We ask for each entry whether the saved data will be immutable. This is an optimization: if all
-    //  entries turn out to be immutable we will save the entire entry array in a read-only (shareable)
-    //  section.
-    //
-
-    bool fAllEntriesImmutable = true;
-    for (i = 0; i < sEntryMap.m_cEntries; i++)
-        if (!DOWNCALL(SaveEntry)(pImage,
-                                 pProfileData,
-                                 sEntryMap.m_pEntries[i].m_pOldEntry,
-                                 sEntryMap.m_pEntries[i].m_pNewEntry,
-                                 &sEntryMap))
-            fAllEntriesImmutable = false;
-
-    // We're mostly done. Now just some cleanup and the actual DataImage storage operations.
-
-    // We don't need the bucket size tracking arrays any more.
-    delete [] pHotBucketSizes;
-    delete [] pColdBucketSizes;
-
-    // If there are any hot entries store the entry array and bucket list.
-    if (cHotEntries)
-    {
-        pImage->StoreStructure(GetPersistedHotEntries(),
-                               static_cast<ULONG>(sizeof(PersistedEntry) * cHotEntries),
-                               fAllEntriesImmutable ? DataImage::ITEM_NGEN_HASH_ENTRIES_RO_HOT : DataImage::ITEM_NGEN_HASH_ENTRIES_HOT);
-
-        pImage->StoreStructure(GetPersistedHotBuckets(),
-                               static_cast<ULONG>(m_sHotEntries.m_pBuckets.GetValue()->GetSize(m_sHotEntries.m_cBuckets)),
-                               DataImage::ITEM_NGEN_HASH_BUCKETLIST_HOT);
-    }
-
-    // If there are any cold entries store the entry array and bucket list.
-    if (cColdEntries)
-    {
-        pImage->StoreStructure(GetPersistedColdEntries(),
-                               static_cast<ULONG>(sizeof(PersistedEntry) * cColdEntries),
-                               fAllEntriesImmutable ? DataImage::ITEM_NGEN_HASH_ENTRIES_RO_COLD : DataImage::ITEM_NGEN_HASH_ENTRIES_COLD);
-
-        pImage->StoreStructure(GetPersistedColdBuckets(),
-                               static_cast<ULONG>(GetPersistedColdBuckets()->GetSize(m_sColdEntries.m_cBuckets)),
-                               DataImage::ITEM_NGEN_HASH_BUCKETLIST_COLD);
-    }
-
-    // Store the root data structure itself.
-    pImage->StoreStructure(this, sizeof(FINAL_CLASS), cHotEntries ?
-                           DataImage::ITEM_NGEN_HASH_HOT : DataImage::ITEM_NGEN_HASH_COLD);
-
-    // We've moved the warm entries to hot and cold sections, so reset the warm section of the table. We only
-    // do this on the copy of the table that's going to be saved into the ngen image. This is important since
-    // (especially in the case of generics) we might continue to access this table throughout the rest of the
-    // save/arrange/fixup process. Leaving two copies of saved entries in the table (hot or cold plus warm)
-    // doesn't have any real impact, but removing the warm entries could be problematic where the entry was
-    // culled from the ngen image. In those cases we'll get a miss on the lookup with the result that the
-    // caller might try to add the type back to the table, something that is prohibited in the debug build
-    // during the ngen save/arrange/fixup phases.
-
-    // Reset the warm buckets to their original size or a fairly restrictive cap. These (empty) buckets will
-    // be saved into the ngen image and form the basis for further entries added at runtime. Thus we have a
-    // trade-off between storing dead space in the ngen image and having to re-size the bucket list at
-    // runtime. Note that we can't save a zero sized bucket list: the invariant we have is that there are
-    // always a non-zero number of buckets available when we come to do an insertion (since insertions cannot
-    // fail). An alternative strategy would be to initialize these buckets at ngen image load time.
-    _ASSERTE(m_cWarmBuckets >= m_cInitialBuckets);
-    DWORD cNewWarmBuckets = min(m_cInitialBuckets, 11);
-
-    // Create the ngen version of the warm buckets.
-    pImage->StoreStructure(GetWarmBuckets(),
-                           cNewWarmBuckets * sizeof(VolatileEntry*),
-                           DataImage::ITEM_NGEN_HASH_HOT);
-
-    // Reset the ngen-version of the table to have no warm entries and the reduced warm bucket count.
-    NgenHashTable<NGEN_HASH_ARGS> *pNewTable = (NgenHashTable<NGEN_HASH_ARGS>*)pImage->GetImagePointer(this);
-    pNewTable->m_cWarmEntries = 0;
-    pNewTable->m_cWarmBuckets = cNewWarmBuckets;
-
-    // Zero-out the ngen version of the warm buckets.
-    VolatileEntry *pNewBuckets = (VolatileEntry*)pImage->GetImagePointer(GetWarmBuckets());
-    memset(pNewBuckets, 0, cNewWarmBuckets * sizeof(VolatileEntry*));
-}
-
-#ifdef _MSC_VER
-#pragma warning(pop)
-#endif // _MSC_VER:
-
-// Call during ngen to register fixups for hash table data structure fields. Calls derived-class
-// implementation of FixupEntry to allow per-entry extension of the fixup process.
-template <NGEN_HASH_PARAMS>
-void NgenHashTable<NGEN_HASH_ARGS>::BaseFixup(DataImage *pImage)
-{
-    STANDARD_VM_CONTRACT;
-
-    DWORD i;
-
-    // Fixup the module pointer.
-    pImage->FixupRelativePointerField(this, offsetof(NgenHashTable<NGEN_HASH_ARGS>, m_pModule));
-
-    // Throw away the heap pointer, we can't serialize it into the image. We'll rely on the loader heap
-    // associated with the module above at runtime.
-    pImage->ZeroPointerField(this, offsetof(NgenHashTable<NGEN_HASH_ARGS>, m_pHeap));
-
-    // Give the hash sub-class a chance to fixup any pointers in its entries. We provide the pointer to the
-    // hot or cold entry block and the offset into that block for this entry since we don't save individual
-    // zap nodes for each entry; just a single node covering the entire array. As a result all fixups have to
-    // be relative to the base of this array.
-
-    for (i = 0; i < m_sHotEntries.m_cEntries; i++)
-        DOWNCALL(FixupEntry)(pImage,
-                             &(GetPersistedHotEntries())[i].m_sValue,
-                             GetPersistedHotEntries(),
-                             i * sizeof(PersistedEntry));
-
-    for (i = 0; i < m_sColdEntries.m_cEntries; i++)
-        DOWNCALL(FixupEntry)(pImage,
-                             &(GetPersistedColdEntries())[i].m_sValue,
-                             GetPersistedColdEntries(),
-                             i * sizeof(PersistedEntry));
-
-    // Fixup the warm (empty) bucket list.
-    pImage->FixupRelativePointerField(this, offsetof(NgenHashTable<NGEN_HASH_ARGS>, m_pWarmBuckets));
-
-    // Fixup the hot entry array and bucket list.
-    pImage->FixupRelativePointerField(this, offsetof(NgenHashTable<NGEN_HASH_ARGS>, m_sHotEntries) + offsetof(PersistedEntries, m_pEntries));
-    pImage->FixupRelativePointerField(this, offsetof(NgenHashTable<NGEN_HASH_ARGS>, m_sHotEntries) + offsetof(PersistedEntries, m_pBuckets));
-
-    // Fixup the cold entry array and bucket list.
-    pImage->FixupRelativePointerField(this, offsetof(NgenHashTable<NGEN_HASH_ARGS>, m_sColdEntries) + offsetof(PersistedEntries, m_pEntries));
-    pImage->FixupRelativePointerField(this, offsetof(NgenHashTable<NGEN_HASH_ARGS>, m_sColdEntries) + offsetof(PersistedEntries, m_pBuckets));
-}
-#endif // !DACCESS_COMPILE
-#endif // FEATURE_PREJIT
-
 #ifdef DACCESS_COMPILE
 
 // Call during DAC enumeration of memory regions to save all hash table data structures. Calls derived-class
@@ -1092,149 +363,12 @@ void NgenHashTable<NGEN_HASH_ARGS>::BaseEnumMemoryRegions(CLRDataEnumMemoryFlags
         }
     }
 
-#ifdef FEATURE_PREJIT
-    // Save hot buckets and entries.
-    if (m_sHotEntries.m_cEntries > 0)
-    {
-        DacEnumMemoryRegion(dac_cast<TADDR>(GetPersistedHotEntries()),
-                            m_sHotEntries.m_cEntries * sizeof(PersistedEntry));
-        DacEnumMemoryRegion(dac_cast<TADDR>(GetPersistedHotBuckets()),
-                            GetPersistedHotBuckets()->GetSize(m_sHotEntries.m_cBuckets));
-        for (DWORD i = 0; i < m_sHotEntries.m_cEntries; i++)
-        {
-            PTR_PersistedEntry pEntry = dac_cast<PTR_PersistedEntry>(&(GetPersistedHotEntries())[i]);
-            DOWNCALL(EnumMemoryRegionsForEntry)(VALUE_FROM_PERSISTED_ENTRY(pEntry), flags);
-        }
-    }
-
-    // Save cold buckets and entries.
-    if (m_sColdEntries.m_cEntries > 0)
-    {
-        DacEnumMemoryRegion(dac_cast<TADDR>(GetPersistedColdEntries()),
-                            m_sColdEntries.m_cEntries * sizeof(PersistedEntry));
-        DacEnumMemoryRegion(dac_cast<TADDR>(GetPersistedColdBuckets()),
-                            GetPersistedColdBuckets()->GetSize(m_sColdEntries.m_cBuckets));
-        for (DWORD i = 0; i < m_sColdEntries.m_cEntries; i++)
-        {
-            PTR_PersistedEntry pEntry = dac_cast<PTR_PersistedEntry>(&(GetPersistedColdEntries())[i]);
-            DOWNCALL(EnumMemoryRegionsForEntry)(VALUE_FROM_PERSISTED_ENTRY(pEntry), flags);
-        }
-    }
-#endif // FEATURE_PREJIT
-
     // Save the module if present.
     if (GetModule().IsValid())
         GetModule()->EnumMemoryRegions(flags, true);
 }
 #endif // DACCESS_COMPILE
 
-#ifdef FEATURE_PREJIT
-
-// Find the first persisted entry (hot or cold based on pEntries) that matches the given hash. Looks only in
-// the persisted block given (i.e. searches only hot *or* cold entries). Returns NULL on failure. Otherwise
-// returns pointer to the derived class portion of the entry and initializes the provided LookupContext to
-// allow enumeration of any further matches.
-template <NGEN_HASH_PARAMS>
-DPTR(VALUE) NgenHashTable<NGEN_HASH_ARGS>::FindPersistedEntryByHash(PersistedEntries *pEntries, NgenHashValue iHash, LookupContext *pContext)
-{
-    CONTRACTL
-    {
-        NOTHROW;
-        GC_NOTRIGGER;
-        MODE_ANY;
-        SUPPORTS_DAC;
-        PRECONDITION(CheckPointer(pContext));
-    }
-    CONTRACTL_END;
-
-    // No point looking if there are no entries.
-    if (pEntries->m_cEntries == 0)
-        return NULL;
-
-    // Since there is at least one entry there must be at least one bucket.
-    _ASSERTE(pEntries->m_cBuckets > 0);
-
-    DWORD eType = (pEntries == &m_sHotEntries ? Hot : Cold);
-
-    // Get the first entry and count of entries for the bucket which contains all entries with the given hash
-    // code.
-    DWORD dwEntryIndex, cEntriesLeft;
-    if (eType == Hot)
-    {
-        GetPersistedHotBuckets()->GetBucket(iHash % pEntries->m_cBuckets, &dwEntryIndex, &cEntriesLeft);
-    }
-    else
-    {
-        GetPersistedColdBuckets()->GetBucket(iHash % pEntries->m_cBuckets, &dwEntryIndex, &cEntriesLeft);
-    }
-
-    // Determine the address of the first entry in the chain by indexing into the entry array.
-    PTR_PersistedEntry pEntry;
-
-    if (eType == Hot)
-    {
-       pEntry = dac_cast<PTR_PersistedEntry>(&(GetPersistedHotEntries())[dwEntryIndex]);
-    }
-    else
-    {
-       pEntry = dac_cast<PTR_PersistedEntry>(&(GetPersistedColdEntries())[dwEntryIndex]);
-    }
-
-    // Iterate while we've still got entries left to check in this chain.
-    while (cEntriesLeft--)
-    {
-        if (pEntry->m_iHashValue == iHash)
-        {
-            // We've found our match.
-
-            // Record our current search state into the provided context so that a subsequent call to
-            // BaseFindNextEntryByHash can pick up the search where it left off.
-            pContext->m_pEntry = dac_cast<TADDR>(pEntry);
-            pContext->m_eType = eType;
-            pContext->m_cRemainingEntries = cEntriesLeft;
-
-            // Return the address of the sub-classes' embedded entry structure.
-            return VALUE_FROM_PERSISTED_ENTRY(pEntry);
-        }
-
-        // Move to the next entry in the chain.
-        pEntry++;
-    }
-
-    // If we get here then none of the entries in the target bucket matched the hash code and we have a miss
-    // (for this section of the table at least).
-    return NULL;
-}
-
-#ifndef DACCESS_COMPILE
-template <NGEN_HASH_PARAMS>
-NgenHashTable<NGEN_HASH_ARGS>::EntryMappingTable::~EntryMappingTable()
-{
-    LIMITED_METHOD_CONTRACT;
-
-    delete [] m_pEntries;
-}
-
-// Given an old entry address (pre-BaseSave) return the address of the entry relocated ready for saving to
-// disk. Note that this address is the (ngen) runtime address, not the disk image address you can further
-// obtain by calling DataImage::GetImagePointer().
-template <NGEN_HASH_PARAMS>
-VALUE *NgenHashTable<NGEN_HASH_ARGS>::EntryMappingTable::GetNewEntryAddress(VALUE *pOldEntry)
-{
-    LIMITED_METHOD_CONTRACT;
-
-    // Perform a simple linear search. If this proves to be a bottleneck in ngen production (the only scenario
-    // in which it's called) we can replace this with something faster such as a hash lookup.
-    for (DWORD i = 0; i < m_cEntries; i++)
-        if (m_pEntries[i].m_pOldEntry == pOldEntry)
-            return m_pEntries[i].m_pNewEntry;
-
-    _ASSERTE(!"Couldn't map old hash entry to new entry");
-    return NULL;
-}
-#endif // !DACCESS_COMPILE
-#endif // FEATURE_PREJIT
-
 // Find the first volatile (warm) entry that matches the given hash. Looks only at warm entries. Returns NULL
 // on failure. Otherwise returns pointer to the derived class portion of the entry and initializes the
 // provided LookupContext to allow enumeration of any further matches.
@@ -1298,13 +432,8 @@ void NgenHashTable<NGEN_HASH_ARGS>::BaseInitIterator(BaseIterator *pIterator)
 
     pIterator->m_pTable = dac_cast<DPTR(NgenHashTable<NGEN_HASH_ARGS>)>(this);
     pIterator->m_pEntry = NULL;
-#ifdef FEATURE_PREJIT
-    pIterator->m_eType = Hot;
-    pIterator->m_cRemainingEntries = m_sHotEntries.m_cEntries;
-#else
     pIterator->m_eType = Warm;
     pIterator->m_dwBucket = 0;
-#endif
 }
 
 // Returns a pointer to the next entry in the hash table or NULL once all entries have been enumerated. Once
@@ -1328,40 +457,6 @@ DPTR(VALUE) NgenHashTable<NGEN_HASH_ARGS>::BaseIterator::Next()
         // What type of section are we walking (Hot, Warm or Cold)?
         switch (m_eType)
         {
-#ifdef FEATURE_PREJIT
-        case Hot:
-        {
-            if (m_cRemainingEntries)
-            {
-                // There's at least one more entry in the hot section to report.
-
-                if (m_pEntry == NULL)
-                {
-                    // This is our first lookup in the hot section, return the first entry in the hot array.
-                    m_pEntry = dac_cast<TADDR>(m_pTable->GetPersistedHotEntries());
-                }
-                else
-                {
-                    // This is not our first lookup, return the entry immediately after the last one we
-                    // reported.
-                    m_pEntry = (TADDR)(m_pEntry + sizeof(PersistedEntry));
-                }
-
-                // There's one less entry to report in the future.
-                m_cRemainingEntries--;
-
-                // Return the pointer to the embedded sub-class entry in the entry we found.
-                return VALUE_FROM_PERSISTED_ENTRY(dac_cast<PTR_PersistedEntry>(m_pEntry));
-            }
-
-            // We ran out of hot entries. Set up to search the warm section next and go round the loop again.
-            m_eType = Warm;
-            m_pEntry = NULL;
-            m_dwBucket = 0;
-            break;
-        }
-#endif // FEATURE_PREJIT
-
         case Warm:
         {
             if (m_pEntry == NULL)
@@ -1387,49 +482,8 @@ DPTR(VALUE) NgenHashTable<NGEN_HASH_ARGS>::BaseIterator::Next()
             if (m_dwBucket < m_pTable->m_cWarmBuckets)
                 break;
 
-            // Othwerwise we should move onto the cold section (if we have one).
-
-#ifdef FEATURE_PREJIT
-            m_eType = Cold;
-            m_pEntry = NULL;
-            m_cRemainingEntries = m_pTable->m_sColdEntries.m_cEntries;
-            break;
-#else
-            return NULL;
-#endif // FEATURE_PREJIT
-        }
-
-#ifdef FEATURE_PREJIT
-        case Cold:
-        {
-            if (m_cRemainingEntries)
-            {
-                // There's at least one more entry in the cold section to report.
-
-                if (m_pEntry == NULL)
-                {
-                    // This is our first lookup in the cold section, return the first entry in the cold array.
-                    m_pEntry = dac_cast<TADDR>(m_pTable->GetPersistedColdEntries());
-                }
-                else
-                {
-                    // This is not our first lookup, return the entry immediately after the last one we
-                    // reported.
-                    m_pEntry = (TADDR)(m_pEntry + sizeof(PersistedEntry));
-                }
-
-                // There's one less entry to report in the future.
-                m_cRemainingEntries--;
-
-                // Return the pointer to the embedded sub-class entry in the entry we found.
-                return VALUE_FROM_PERSISTED_ENTRY(dac_cast<PTR_PersistedEntry>(m_pEntry));
-            }
-
-            // If there are no more entries in the cold section that's it, the whole table has been scanned.
             return NULL;
         }
-#endif // FEATURE_PREJIT
-
         default:
             _ASSERTE(!"Invalid hash entry type");
         }
@@ -1483,79 +537,4 @@ void NgenHashEntryRef<NGEN_HASH_ARGS>::Set(VALUE *pEntry)
     m_rpEntryRef.SetValueMaybeNull(pEntry);
 }
 
-#ifdef FEATURE_PREJIT
-
-// Call this during the ngen Fixup phase to adjust the relative pointer to account for ngen image layout.
-template <NGEN_HASH_PARAMS>
-void NgenHashEntryRef<NGEN_HASH_ARGS>::Fixup(DataImage *pImage, NgenHashTable<NGEN_HASH_ARGS> *pTable)
-{
-    STANDARD_VM_CONTRACT;
-
-    // No fixup required for null pointers.
-    if (m_rpEntryRef.IsNull())
-        return;
-
-    // Location is the field containing the entry reference. We need to determine the ngen zap node that
-    // contains this field (it'll be part of either the hot or cold entry arrays). Then we can determine the
-    // offset of the field from the beginning of the node.
-    BYTE *pLocation = (BYTE*)&m_rpEntryRef;
-    BYTE *pLocationBase;
-    DWORD cbLocationOffset;
-
-    if (pLocation >= (BYTE*)pTable->GetPersistedHotEntries() &&
-        pLocation < (BYTE*)(pTable->GetPersistedHotEntries() + pTable->m_sHotEntries.m_cEntries))
-    {
-        // The field is in a hot entry.
-        pLocationBase = (BYTE*)pTable->GetPersistedHotEntries();
-    }
-    else if (pLocation >= (BYTE*)pTable->GetPersistedColdEntries() &&
-             pLocation < (BYTE*)(pTable->GetPersistedColdEntries() + pTable->m_sColdEntries.m_cEntries))
-    {
-        // The field is in a cold entry.
-        pLocationBase = (BYTE*)pTable->GetPersistedColdEntries();
-    }
-    else
-    {
-        // The field doesn't lie in one of the entry arrays. The caller has passed us an NgenHashEntryRef that
-        // wasn't embedded as a field in one of this hash's entries.
-        _ASSERTE(!"NgenHashEntryRef must be a field in an NgenHashTable entry for Fixup to work");
-        return;
-    }
-    cbLocationOffset = static_cast<DWORD>(pLocation - pLocationBase);
-
-    // Target is the address of the entry that this reference points to. Go through the same kind of logic to
-    // determine which section the target entry lives in, hot or cold.
-    BYTE *pTarget = (BYTE*)m_rpEntryRef.GetValue();
-    BYTE *pTargetBase;
-    DWORD cbTargetOffset;
-
-    if (pTarget >= (BYTE*)pTable->GetPersistedHotEntries() &&
-        pTarget < (BYTE*)(pTable->GetPersistedHotEntries() + pTable->m_sHotEntries.m_cEntries))
-    {
-        // The target is a hot entry.
-        pTargetBase = (BYTE*)pTable->GetPersistedHotEntries();
-    }
-    else if (pTarget >= (BYTE*)pTable->GetPersistedColdEntries() &&
-             pTarget < (BYTE*)(pTable->GetPersistedColdEntries() + pTable->m_sColdEntries.m_cEntries))
-    {
-        // The target is a cold entry.
-        pTargetBase = (BYTE*)pTable->GetPersistedColdEntries();
-    }
-    else
-    {
-        // The target doesn't lie in one of the entry arrays. The caller has passed us an NgenHashEntryRef that
-        // points to an entry (or other memory) not in our hash table.
-        _ASSERTE(!"NgenHashEntryRef must refer to an entry in the same hash table");
-        return;
-    }
-    cbTargetOffset = static_cast<DWORD>(pTarget - pTargetBase);
-
-    // Now we have enough data to ask for a fixup to be generated for this field. The fixup type
-    // IMAGE_REL_BASED_RELPTR means we won't actually get a base relocation fixup (an entry in the ngen image
-    // that causes a load-time fixup to be applied). Instead this record will just adjust the relative value
-    // in the field once the ngen image layout is finalized and it knows the final locations of the field and
-    // target zap nodes.
-    pImage->FixupField(pLocationBase, cbLocationOffset, pTargetBase, cbTargetOffset, IMAGE_REL_BASED_RELPTR);
-}
-#endif // FEATURE_PREJIT
 #endif // !DACCESS_COMPILE
index 91069a7..96354bf 100644 (file)
@@ -16,9 +16,6 @@
 #include "peimagelayout.inl"
 #include "dlwrap.h"
 #include "invokeutil.h"
-#ifdef FEATURE_PREJIT
-#include "compile.h"
-#endif
 #include "strongnameinternal.h"
 
 #include "../binder/inc/applicationcontext.hpp"
 #include "clrprivbinderutil.h"
 #include "../binder/inc/coreclrbindercommon.h"
 
-
-#ifdef FEATURE_PREJIT
-#include "compile.h"
-
-#ifdef DEBUGGING_SUPPORTED
-SVAL_IMPL_INIT(DWORD, PEFile, s_NGENDebugFlags, 0);
-#endif
-#endif
-
 #include "sha1.h"
 
 
index 7a38a55..915b792 100644 (file)
 #include "eventtrace.h"
 #include "peimagelayout.inl"
 
-#ifdef FEATURE_PREJIT
-#include "compile.h"
-#endif
-
 #ifndef DACCESS_COMPILE
 
 
index 0bd2bd6..3896c7e 100644 (file)
 
 #include "common.h"
 
-#ifdef FEATURE_PREJIT
-#include "compile.h"
-#endif
-
 #ifdef FEATURE_PERFMAP
 #include "perfmap.h"
 #endif
@@ -651,237 +647,8 @@ TADDR Precode::AllocateTemporaryEntryPoints(MethodDescChunk *  pChunk,
     return temporaryEntryPoints;
 }
 
-#ifdef FEATURE_NATIVE_IMAGE_GENERATION
-
-static DataImage::ItemKind GetPrecodeItemKind(DataImage * image, MethodDesc * pMD, BOOL fIsPrebound = FALSE)
-{
-    STANDARD_VM_CONTRACT;
-
-    DataImage::ItemKind kind = DataImage::ITEM_METHOD_PRECODE_COLD_WRITEABLE;
-
-    DWORD flags = image->GetMethodProfilingFlags(pMD);
-
-    if (flags & (1 << WriteMethodPrecode))
-    {
-        kind = fIsPrebound ? DataImage::ITEM_METHOD_PRECODE_HOT : DataImage::ITEM_METHOD_PRECODE_HOT_WRITEABLE;
-    }
-    else
-    if (flags & (1 << ReadMethodPrecode))
-    {
-        kind = DataImage::ITEM_METHOD_PRECODE_HOT;
-    }
-    else
-    if (
-        fIsPrebound ||
-        // The generic method definitions get precode to make GetMethodDescForSlot work.
-        // This precode should not be ever written to.
-        pMD->ContainsGenericVariables() ||
-        // Interface MDs are run only for remoting and cominterop which is pretty rare. Make them cold.
-        pMD->IsInterface()
-        )
-    {
-        kind = DataImage::ITEM_METHOD_PRECODE_COLD;
-    }
-
-    return kind;
-}
-
-void Precode::Save(DataImage *image)
-{
-    STANDARD_VM_CONTRACT;
-
-    MethodDesc * pMD = GetMethodDesc();
-    PrecodeType t = GetType();
-
-#ifdef HAS_FIXUP_PRECODE_CHUNKS
-    _ASSERTE(GetType() != PRECODE_FIXUP);
-#endif
-
-#if defined(TARGET_X86) || defined(TARGET_AMD64)
-    // StubPrecode may have straddlers (relocations crossing pages) on x86 and x64. We need
-    // to insert padding to eliminate it. To do that, we need to save these using custom ZapNode that can only
-    // be implemented in dataimage.cpp or zapper due to factoring of the header files.
-    BOOL fIsPrebound = IsPrebound(image);
-    image->SavePrecode(this,
-        pMD,
-        t,
-        GetPrecodeItemKind(image, pMD, fIsPrebound),
-        fIsPrebound);
-#else
-    _ASSERTE(FitsIn<ULONG>(SizeOf(t)));
-    image->StoreStructure((void*)GetStart(),
-        static_cast<ULONG>(SizeOf(t)),
-        GetPrecodeItemKind(image, pMD, IsPrebound(image)),
-        AlignOf(t));
-#endif // TARGET_X86 || TARGET_AMD64
-}
-
-void Precode::Fixup(DataImage *image, MethodDesc * pMD)
-{
-    STANDARD_VM_CONTRACT;
-
-    PrecodeType precodeType = GetType();
-
-#if defined(TARGET_X86) || defined(TARGET_AMD64)
-#if defined(HAS_FIXUP_PRECODE)
-    if (precodeType == PRECODE_FIXUP)
-    {
-        AsFixupPrecode()->Fixup(image, pMD);
-    }
-#endif
-#else // TARGET_X86 || TARGET_AMD64
-    ZapNode * pCodeNode = NULL;
-
-    if (IsPrebound(image))
-    {
-        pCodeNode = image->GetCodeAddress(pMD);
-    }
-
-    switch (precodeType) {
-    case PRECODE_STUB:
-        AsStubPrecode()->Fixup(image);
-        break;
-#ifdef HAS_NDIRECT_IMPORT_PRECODE
-    case PRECODE_NDIRECT_IMPORT:
-        AsNDirectImportPrecode()->Fixup(image);
-        break;
-#endif // HAS_NDIRECT_IMPORT_PRECODE
-#ifdef HAS_FIXUP_PRECODE
-    case PRECODE_FIXUP:
-        AsFixupPrecode()->Fixup(image, pMD);
-        break;
-#endif // HAS_FIXUP_PRECODE
-    default:
-        UnexpectedPrecodeType("Precode::Save", precodeType);
-        break;
-    }
-#endif // TARGET_X86 || TARGET_AMD64
-}
-
-BOOL Precode::IsPrebound(DataImage *image)
-{
-    WRAPPER_NO_CONTRACT;
-
-    return FALSE;
-}
-
-void Precode::SaveChunk::Save(DataImage* image, MethodDesc * pMD)
-{
-    STANDARD_VM_CONTRACT;
-
-    PrecodeType precodeType = pMD->GetPrecodeType();
-
-#ifdef HAS_FIXUP_PRECODE_CHUNKS
-    if (precodeType == PRECODE_FIXUP)
-    {
-        m_rgPendingChunk.Append(pMD);
-        return;
-    }
-#endif // HAS_FIXUP_PRECODE_CHUNKS
-
-    SIZE_T size = Precode::SizeOf(precodeType);
-    Precode* pPrecode = (Precode *)new (image->GetHeap()) BYTE[size];
-    pPrecode->Init(pPrecode, precodeType, pMD, NULL);
-    pPrecode->Save(image);
-
-    // Alias the temporary entrypoint
-    image->RegisterSurrogate(pMD, pPrecode);
-}
-
-#ifdef HAS_FIXUP_PRECODE_CHUNKS
-static void SaveFixupPrecodeChunk(DataImage * image, MethodDesc ** rgMD, COUNT_T count, DataImage::ItemKind kind)
-{
-    STANDARD_VM_CONTRACT;
-
-    ULONG size = sizeof(FixupPrecode) * count + sizeof(PTR_MethodDesc);
-    FixupPrecode * pBase = (FixupPrecode *)new (image->GetHeap()) BYTE[size];
-
-    ZapStoredStructure * pNode = image->StoreStructure(NULL, size, kind,
-        Precode::AlignOf(PRECODE_FIXUP));
-
-    for (COUNT_T i = 0; i < count; i++)
-    {
-        MethodDesc * pMD = rgMD[i];
-        FixupPrecode * pPrecode = pBase + i;
-
-        pPrecode->InitForSave((count - 1) - i);
-
-        image->BindPointer(pPrecode, pNode, i * sizeof(FixupPrecode));
-
-        // Alias the temporary entrypoint
-        image->RegisterSurrogate(pMD, pPrecode);
-    }
-
-    image->CopyData(pNode, pBase, size);
-}
-#endif // HAS_FIXUP_PRECODE_CHUNKS
-
-void Precode::SaveChunk::Flush(DataImage * image)
-{
-    STANDARD_VM_CONTRACT;
-
-#ifdef HAS_FIXUP_PRECODE_CHUNKS
-    if (m_rgPendingChunk.GetCount() == 0)
-        return;
-
-    // Sort MethodDescs using the item kind for hot-cold spliting
-    struct SortMethodDesc : CQuickSort< MethodDesc * >
-    {
-        DataImage * m_image;
-
-        SortMethodDesc(DataImage *image, MethodDesc **pBase, SSIZE_T iCount)
-            : CQuickSort< MethodDesc * >(pBase, iCount),
-            m_image(image)
-        {
-        }
-
-        int Compare(MethodDesc ** ppMD1, MethodDesc ** ppMD2)
-        {
-            MethodDesc * pMD1 = *ppMD1;
-            MethodDesc * pMD2 = *ppMD2;
-
-            // Compare item kind
-            DataImage::ItemKind kind1 = GetPrecodeItemKind(m_image, pMD1);
-            DataImage::ItemKind kind2 = GetPrecodeItemKind(m_image, pMD2);
-
-            return kind1 - kind2;
-        }
-    };
-
-    SortMethodDesc sort(image, &(m_rgPendingChunk[0]), m_rgPendingChunk.GetCount());
-    sort.Sort();
-
-    DataImage::ItemKind pendingKind = DataImage::ITEM_METHOD_PRECODE_COLD_WRITEABLE;
-    COUNT_T pendingCount = 0;
-
-    COUNT_T i;
-    for (i = 0; i < m_rgPendingChunk.GetCount(); i++)
-    {
-        MethodDesc * pMD = m_rgPendingChunk[i];
-
-        DataImage::ItemKind kind = GetPrecodeItemKind(image, pMD);
-        if (kind != pendingKind)
-        {
-            if (pendingCount != 0)
-                SaveFixupPrecodeChunk(image, &(m_rgPendingChunk[i-pendingCount]), pendingCount, pendingKind);
-
-            pendingKind = kind;
-            pendingCount = 0;
-        }
-
-        pendingCount++;
-    }
-
-    // Flush the remaining items
-    SaveFixupPrecodeChunk(image, &(m_rgPendingChunk[i-pendingCount]), pendingCount, pendingKind);
-#endif // HAS_FIXUP_PRECODE_CHUNKS
-}
-
-#endif // FEATURE_NATIVE_IMAGE_GENERATION
-
 #endif // !DACCESS_COMPILE
 
-
 #ifdef DACCESS_COMPILE
 void Precode::EnumMemoryRegions(CLRDataEnumMemoryFlags flags)
 {
index 6ebb02f..b386404 100644 (file)
@@ -303,30 +303,6 @@ public:
     static TADDR AllocateTemporaryEntryPoints(MethodDescChunk* pChunk,
         LoaderAllocator *pLoaderAllocator, AllocMemTracker *pamTracker);
 
-#ifdef FEATURE_PREJIT
-    //
-    // NGEN stuff
-    //
-
-    void Save(DataImage *image);
-    void Fixup(DataImage *image, MethodDesc * pMD);
-
-    BOOL IsPrebound(DataImage *image);
-
-    // Helper class for saving precodes in chunks
-    class SaveChunk
-    {
-#ifdef HAS_FIXUP_PRECODE_CHUNKS
-        // Array of methods to be saved in the method desc chunk
-        InlineSArray<MethodDesc *, 20> m_rgPendingChunk;
-#endif // HAS_FIXUP_PRECODE_CHUNKS
-
-    public:
-        void Save(DataImage * image, MethodDesc * pMD);
-        void Flush(DataImage * image);
-    };
-#endif // FEATURE_PREJIT
-
 #ifdef DACCESS_COMPILE
     void EnumMemoryRegions(CLRDataEnumMemoryFlags flags);
 #endif
index 75f78f5..c074fa0 100644 (file)
 #include "stubgen.h"
 #include "eventtrace.h"
 #include "array.h"
-#include "compile.h"
 #include "ecall.h"
 #include "virtualcallstub.h"
 
-#ifdef FEATURE_PREJIT
-#include "compile.h"
-#endif
-
 #ifdef FEATURE_INTERPRETER
 #include "interpreter.h"
 #endif
index 0253d59..5e1082b 100644 (file)
@@ -11,7 +11,6 @@
 #include "common.h"
 
 #include "dbginterface.h"
-#include "compile.h"
 #include "versionresilienthashcode.h"
 #include "typehashingalgorithms.h"
 #include "method.hpp"
@@ -555,15 +554,6 @@ PTR_ReadyToRunInfo ReadyToRunInfo::Initialize(Module * pModule, AllocMemTracker
         return NULL;
     }
 
-#ifdef FEATURE_NATIVE_IMAGE_GENERATION
-    // Ignore ReadyToRun during NGen
-    if (IsCompilationProcess() && !IsNgenPDBCompilationProcess())
-    {
-        DoLog("Ready to Run disabled - compilation process");
-        return NULL;
-    }
-#endif
-
     if (!pLayout->IsNativeMachineFormat())
     {
         // For CoreCLR, be strict about disallowing machine mismatches.
index df7315f..e655252 100644 (file)
@@ -1451,21 +1451,6 @@ TypeHandle SigPointer::GetTypeHandleThrowing(
 
             IfFailThrowBF(psig.GetToken(&typeToken), BFA_BAD_SIGNATURE, pOrigModule);
 
-#if defined(FEATURE_NATIVE_IMAGE_GENERATION) && !defined(DACCESS_COMPILE)
-            if ((pOrigModule != pModule) && (pZapSigContext->externalTokens == ZapSig::IbcTokens))
-            {
-                // ibcExternalType tokens are actually encoded as mdtTypeDef tokens in the signature
-                RID            typeRid  = RidFromToken(typeToken);
-                idExternalType ibcToken = RidToToken(typeRid, ibcExternalType);
-                typeToken = pOrigModule->LookupIbcTypeToken(pModule, ibcToken);
-
-                if (IsNilToken(typeToken))
-                {
-                    COMPlusThrow(kTypeLoadException, IDS_IBC_MISSING_EXTERNAL_TYPE);
-                }
-            }
-#endif
-
             if ((TypeFromToken(typeToken) != mdtTypeRef) && (TypeFromToken(typeToken) != mdtTypeDef))
                 THROW_BAD_FORMAT(BFA_UNEXPECTED_TOKEN_AFTER_CLASSVALTYPE, pOrigModule);
 
@@ -1746,21 +1731,6 @@ TypeHandle SigPointer::GetGenericInstType(Module *        pModule,
         mdToken typeToken = mdTypeRefNil;
         IfFailThrowBF(GetToken(&typeToken), BFA_BAD_SIGNATURE, pOrigModule);
 
-#if defined(FEATURE_NATIVE_IMAGE_GENERATION) && !defined(DACCESS_COMPILE)
-        if ((pOrigModule != pModule) && (pZapSigContext->externalTokens == ZapSig::IbcTokens))
-        {
-            // ibcExternalType tokens are actually encoded as mdtTypeDef tokens in the signature
-            RID            typeRid  = RidFromToken(typeToken);
-            idExternalType ibcToken = RidToToken(typeRid, ibcExternalType);
-            typeToken = pOrigModule->LookupIbcTypeToken(pModule, ibcToken);
-
-            if (IsNilToken(typeToken))
-            {
-                COMPlusThrow(kTypeLoadException, IDS_IBC_MISSING_EXTERNAL_TYPE);
-            }
-        }
-#endif
-
         if ((TypeFromToken(typeToken) != mdtTypeRef) && (TypeFromToken(typeToken) != mdtTypeDef))
             THROW_BAD_FORMAT(BFA_UNEXPECTED_TOKEN_AFTER_GENINST, pOrigModule);
 
index f8567e0..f880850 100644 (file)
@@ -19,9 +19,6 @@
 #include "common.h"
 #include "typedesc.h"
 #include "typestring.h"
-#if defined(FEATURE_PREJIT)
-#include "compile.h"
-#endif
 #include "array.h"
 #include "castcache.h"
 
@@ -784,203 +781,6 @@ void TypeDesc::DoRestoreTypeKey()
 
 #ifndef DACCESS_COMPILE
 
-#ifdef FEATURE_NATIVE_IMAGE_GENERATION
-// This just performs a shallow save
-void TypeDesc::Save(DataImage *image)
-{
-    STANDARD_VM_CONTRACT;
-
-    ClassLoader::EnsureLoaded(TypeHandle(this));
-
-    if (LoggingOn(LF_ZAP, LL_INFO10000))
-    {
-        StackSString name;
-        TypeString::AppendType(name, TypeHandle(this));
-        LOG((LF_ZAP, LL_INFO10000, "TypeDesc::Save %S\n", name.GetUnicode()));
-    }
-
-    if (IsGenericVariable())
-    {
-        ((TypeVarTypeDesc*)this)->Save(image);
-    }
-    else if (GetInternalCorElementType() == ELEMENT_TYPE_FNPTR)
-    {
-        ((FnPtrTypeDesc *)this)->Save(image);
-    }
-    else
-    {
-        _ASSERTE(HasTypeParam());
-        ((ParamTypeDesc*)this)->Save(image);
-    }
-
-}
-
-void TypeDesc::Fixup(DataImage *image)
-{
-    STANDARD_VM_CONTRACT;
-
-    if (IsGenericVariable())
-    {
-        TypeVarTypeDesc* tyvar = (TypeVarTypeDesc*) this;
-        tyvar->Fixup(image);
-    }
-    else if (GetInternalCorElementType() == ELEMENT_TYPE_FNPTR)
-    {
-        ((FnPtrTypeDesc*)this)->Fixup(image);
-    }
-    else
-    {
-        // Works for PTR/BYREF types, but not function pointers
-        _ASSERTE(HasTypeParam());
-
-        ((ParamTypeDesc*) this)->Fixup(image);
-    }
-
-    if (NeedsRestore(image))
-    {
-        TypeDesc *pTD = (TypeDesc*) image->GetImagePointer(this);
-        _ASSERTE(pTD != NULL);
-        pTD->m_typeAndFlags |= TypeDesc::enum_flag_Unrestored | TypeDesc::enum_flag_UnrestoredTypeKey | TypeDesc::enum_flag_IsNotFullyLoaded;
-    }
-
-}
-
-BOOL TypeDesc::ComputeNeedsRestore(DataImage *image, TypeHandleList *pVisited)
-{
-    STATIC_STANDARD_VM_CONTRACT;
-
-    _ASSERTE(GetAppDomain()->IsCompilationDomain());
-
-    if (HasTypeParam())
-    {
-        return dac_cast<PTR_ParamTypeDesc>(this)->ComputeNeedsRestore(image, pVisited);
-    }
-    else
-        return FALSE;
-}
-
-
-
-void ParamTypeDesc::Save(DataImage *image)
-{
-    STANDARD_VM_CONTRACT;
-
-    image->StoreStructure(this, sizeof(ParamTypeDesc), DataImage::ITEM_PARAM_TYPEDESC);
-
-    // This set of checks matches precisely those in ParamTypeDesc::ComputeNeedsRestore
-    //
-    // They indicate if an array TypeDesc is non-canonical (in much the same a a generic
-    // method table being non-canonical), i.e. it is not the primary
-    // owner of the m_TemplateMT 
-    //
-    if (OwnsTemplateMethodTable())
-    {
-        // This TypeDesc should be the only one saving this MT
-        _ASSERTE(!image->IsStored(GetTemplateMethodTableInternal()));
-        Module::SaveMethodTable(image, GetTemplateMethodTableInternal(), 0);
-    }
-
-}
-
-
-void ParamTypeDesc::Fixup(DataImage *image)
-{
-    STANDARD_VM_CONTRACT;
-
-    _ASSERTE(image->GetModule()->GetAssembly() ==
-             GetAppDomain()->ToCompilationDomain()->GetTargetAssembly());
-
-    if (LoggingOn(LF_ZAP, LL_INFO10000))
-    {
-        StackSString name;
-        TypeString::AppendType(name, TypeHandle(this));
-        LOG((LF_ZAP, LL_INFO10000, "ParamTypeDesc::Fixup %S\n", name.GetUnicode()));
-    }
-
-    if (!m_TemplateMT.IsNull())
-    {
-        if (OwnsTemplateMethodTable())
-        {
-            // In all other cases the type desc "owns" the m_TemplateMT
-            // and it is always stored in the same module as the TypeDesc (i.e. the
-            // TypeDesc and the MT are "tightly-knit") In other words if one is present in
-            // an NGEN image then then other will be, and if one is "used" at runtime then
-            // the other will be too.
-            image->FixupMethodTablePointer(this, &m_TemplateMT);
-            GetTemplateMethodTableInternal()->Fixup(image);
-        }
-        else
-        {
-            // Fixup the pointer to the possibly-shared m_TemplateMT. This might be in a different module.
-            image->FixupMethodTablePointer(this, &m_TemplateMT);
-        }
-    }
-
-    // Fixup the pointer to the element type.
-    image->HardBindTypeHandlePointer(this, offsetof(ParamTypeDesc, m_Arg));
-
-    // The managed object will get regenerated on demand
-    image->ZeroField(this, offsetof(ParamTypeDesc, m_hExposedClassObject), sizeof(m_hExposedClassObject));
-}
-
-BOOL ParamTypeDesc::ComputeNeedsRestore(DataImage *image, TypeHandleList *pVisited)
-{
-    STATIC_STANDARD_VM_CONTRACT;
-
-    _ASSERTE(GetAppDomain()->IsCompilationDomain());
-
-    if (m_typeAndFlags & TypeDesc::enum_flag_NeedsRestore)
-    {
-        return TRUE;
-    }
-    if (m_typeAndFlags & TypeDesc::enum_flag_PreRestored)
-    {
-        return FALSE;
-    }
-
-    BOOL res = FALSE;
-    if (!image->CanPrerestoreEagerBindToTypeHandle(m_Arg, pVisited))
-    {
-        res = TRUE;
-    }
-
-    // This set of checks matches precisely those in ParamTypeDesc::Fixup
-    //
-    if (!m_TemplateMT.IsNull())
-    {
-        if (OwnsTemplateMethodTable())
-        {
-            if (GetTemplateMethodTableInternal()->ComputeNeedsRestore(image, pVisited))
-            {
-                res = TRUE;
-            }
-        }
-        else
-        {
-            if (!image->CanPrerestoreEagerBindToMethodTable(GetTemplateMethodTableInternal(), pVisited))
-            {
-                res = TRUE;
-            }
-        }
-    }
-
-    // Cache the results of running the algorithm.
-    // We can only cache the result if we have not speculatively assumed
-    // that any types are not NeedsRestore, i.e. the visited list is empty
-    if (pVisited == NULL)
-    {
-        if (LoggingOn(LF_ZAP, LL_INFO10000))
-        {
-            StackSString name;
-            TypeString::AppendType(name, TypeHandle(this));
-            LOG((LF_ZAP, LL_INFO10000, "ParamTypeDesc::ComputeNeedsRestore=%d for %S\n", res, name.GetUnicode()));
-        }
-        m_typeAndFlags |= (res ? TypeDesc::enum_flag_NeedsRestore : TypeDesc::enum_flag_PreRestored);
-    }
-    return res;
-}
-#endif // FEATURE_NATIVE_IMAGE_GENERATION
-
 void TypeDesc::SetIsRestored()
 {
     STATIC_CONTRACT_THROWS;
@@ -1030,33 +830,6 @@ void TypeDesc::Restore()
 
 #ifndef DACCESS_COMPILE
 
-#ifdef FEATURE_NATIVE_IMAGE_GENERATION
-void TypeVarTypeDesc::Save(DataImage *image)
-{
-    STANDARD_VM_CONTRACT;
-
-    // We don't persist the constraints: instead, load them back on demand
-    m_numConstraints = (DWORD) -1;
-
-    LOG((LF_ZAP, LL_INFO10000, "  TypeVarTypeDesc::Save %x (%p)\n", GetToken(), this));
-    image->StoreStructure(this, sizeof(TypeVarTypeDesc),
-                                    DataImage::ITEM_TYVAR_TYPEDESC);
-}
-
-void TypeVarTypeDesc::Fixup(DataImage *image)
-{
-    STANDARD_VM_CONTRACT;
-
-    LOG((LF_ZAP, LL_INFO10000, "  TypeVarTypeDesc::Fixup %x (%p)\n", GetToken(), this));
-    image->FixupRelativePointerField(this, offsetof(TypeVarTypeDesc, m_pModule));
-    image->ZeroField(this, offsetof(TypeVarTypeDesc, m_hExposedClassObject), sizeof(m_hExposedClassObject));
-
-    // We don't persist the constraints: instead, load them back on demand
-    image->ZeroPointerField(this, offsetof(TypeVarTypeDesc, m_constraints));
-
-}
-#endif // FEATURE_NATIVE_IMAGE_GENERATION
-
 MethodDesc * TypeVarTypeDesc::LoadOwnerMethod()
 {
     CONTRACTL
@@ -2042,32 +1815,6 @@ FnPtrTypeDesc::IsExternallyVisible() const
 
 #endif //DACCESS_COMPILE
 
-#if defined(FEATURE_NATIVE_IMAGE_GENERATION) && !defined(DACCESS_COMPILE)
-
-void FnPtrTypeDesc::Save(DataImage * image)
-{
-    STANDARD_VM_CONTRACT;
-
-    image->StoreStructure(
-        this,
-        sizeof(FnPtrTypeDesc) + (m_NumArgs * sizeof(TypeHandle)),
-        DataImage::ITEM_FPTR_TYPEDESC);
-}
-
-void FnPtrTypeDesc::Fixup(DataImage * image)
-{
-    STANDARD_VM_CONTRACT;
-
-    for (DWORD i = 0; i <= m_NumArgs; i++)
-    {
-        image->FixupTypeHandlePointerInPlace(
-            this,
-            (BYTE *)&m_RetAndArgTypes[i] - (BYTE *)this);
-    }
-}
-
-#endif //defined(FEATURE_NATIVE_IMAGE_GENERATION) && !defined(DACCESS_COMPILE)
-
 #ifdef DACCESS_COMPILE
 
 void
index 160bfef..6d5db94 100644 (file)
@@ -118,19 +118,6 @@ public:
     // Is actually ParamTypeDesc (BYREF, PTR)
     BOOL HasTypeParam();
 
-#ifdef FEATURE_PREJIT
-    void Save(DataImage *image);
-    void Fixup(DataImage *image);
-
-    BOOL NeedsRestore(DataImage *image)
-    {
-        WRAPPER_NO_CONTRACT;
-        return ComputeNeedsRestore(image, NULL);
-    }
-
-    BOOL ComputeNeedsRestore(DataImage *image, TypeHandleList *pVisited);
-#endif
-
     void DoRestoreTypeKey();
     void Restore();
     BOOL IsRestored();
@@ -298,12 +285,6 @@ public:
 
     TypeHandle GetTypeParam();
 
-#ifdef FEATURE_PREJIT
-    void Save(DataImage *image);
-    void Fixup(DataImage *image);
-    BOOL ComputeNeedsRestore(DataImage *image, TypeHandleList *pVisited);
-#endif
-
     BOOL OwnsTemplateMethodTable();
 
 #ifdef DACCESS_COMPILE
@@ -449,11 +430,6 @@ public:
     // instantiate it with a reference type).
     BOOL ConstrainedAsValueType();
 
-#ifdef FEATURE_PREJIT
-    void Save(DataImage *image);
-    void Fixup(DataImage *image);
-#endif // FEATURE_PREJIT
-
 #ifdef DACCESS_COMPILE
     void EnumMemoryRegions(CLRDataEnumMemoryFlags flags);
 #endif
@@ -544,11 +520,6 @@ public:
     BOOL IsExternallyVisible() const;
 #endif //DACCESS_COMPILE
 
-#ifdef FEATURE_PREJIT
-    void Save(DataImage *image);
-    void Fixup(DataImage *image);
-#endif //FEATURE_PREJIT
-
 #ifdef DACCESS_COMPILE
     static ULONG32 DacSize(TADDR addr)
     {
index ed42e7b..a3543ed 100644 (file)
@@ -89,15 +89,6 @@ public:
     void EnumMemoryRegionsForEntry(TypeEquivalenceEntry *pEntry, CLRDataEnumMemoryFlags flags) { return; }
 #endif
 
-#if defined(FEATURE_PREJIT) && !defined(DACCESS_COMPILE)
-private:
-    // Override operations from NgenHashTable - see ngenhash.h
-    bool ShouldSave(DataImage *pImage, TypeEquivalenceEntry *pEntry) { return false; }
-    bool IsHotEntry(TypeEquivalenceEntry *pEntry, CorProfileData *pProfileData) { return false; }
-    bool SaveEntry(DataImage *pImage, CorProfileData *pProfileData, TypeEquivalenceEntry *pOldEntry, TypeEquivalenceEntry *pNewEntry, EntryMappingTable *pMap) { return true; }
-    void FixupEntry(DataImage *pImage, TypeEquivalenceEntry *pEntry, void *pFixupBase, DWORD cbFixupOffset) { return; }
-#endif // FEATURE_PREJIT && !DACCESS_COMPILE
-
 private:
 #ifndef DACCESS_COMPILE
     TypeEquivalenceHashTable(LoaderHeap *pHeap, DWORD cInitialBuckets, CrstExplicitInit *pCrst)
index 81550fd..e33c6db 100644 (file)
@@ -1098,20 +1098,6 @@ void TypeHandle::CheckRestore() const
 
 #ifndef DACCESS_COMPILE
 
-#ifdef FEATURE_NATIVE_IMAGE_GENERATION
-BOOL TypeHandle::ComputeNeedsRestore(DataImage *image, TypeHandleList *pVisited) const
-{
-    STATIC_STANDARD_VM_CONTRACT;
-
-    _ASSERTE(GetAppDomain()->IsCompilationDomain());
-
-    if (!IsTypeDesc())
-        return AsMethodTable()->ComputeNeedsRestore(image, pVisited);
-    else
-        return AsTypeDesc()->ComputeNeedsRestore(image, pVisited);
-}
-#endif // FEATURE_NATIVE_IMAGE_GENERATION
-
 BOOL
 TypeHandle::IsExternallyVisible() const
 {
index 339d5f3..bb448f5 100644 (file)
@@ -484,9 +484,6 @@ public:
     // True if this type handle is a zap-encoded fixup
     BOOL IsEncodedFixup() const;
 
-    // Only used at NGEN-time
-    BOOL ComputeNeedsRestore(DataImage *image, TypeHandleList *pVisited) const;
-
     void DoRestoreTypeKey();
 
     void CheckRestore() const;
index 4ef4c67..14a62fa 100644 (file)
 #include "typestring.h"
 #include "typedesc.h"
 #include "typekey.h"
-#ifdef FEATURE_PREJIT
-#include "zapsig.h"
-#include "compile.h"
-#endif
 #include "ngenhash.inl"
 
 #ifdef _MSC_VER
@@ -643,160 +639,6 @@ VOID EETypeHashTable::InsertValue(TypeHandle data)
     BaseInsertEntry(HashTypeHandle(0, data), pNewEntry);
 }
 
-#ifdef FEATURE_NATIVE_IMAGE_GENERATION
-
-#ifdef _DEBUG
-void EETypeHashTableSeal(EETypeHashTable * pTable) { WRAPPER_NO_CONTRACT; pTable->Seal(); }
-void EETypeHashTableUnseal(EETypeHashTable * pTable) { WRAPPER_NO_CONTRACT; pTable->Unseal(); }
-typedef  Wrapper<EETypeHashTable *, EETypeHashTableSeal, EETypeHashTableUnseal> EETypeHashTableSealHolder;
-#endif
-
-// Save the hash table and any type descriptors referenced by it
-// Method tables must be saved separately
-void EETypeHashTable::Save(DataImage *image, Module *module, CorProfileData *profileData)
-{
-    CONTRACTL
-    {
-        STANDARD_VM_CHECK;
-        PRECONDITION(image->GetModule() == GetModule());
-    }
-    CONTRACTL_END;
-
-#ifdef _DEBUG
-    // The table should not change while we are walking the buckets
-    EETypeHashTableSealHolder h(this);
-#endif
-
-    // The base class will call us back for every entry to see if it's considered hot. To determine this we
-    // have to walk through the profiling data. It's very inefficient for us to do this every time. Instead
-    // we'll walk the data once just now and mark each hot entry as we find it.
-    CORBBTPROF_TOKEN_INFO * pTypeProfilingData = profileData ? profileData->GetTokenFlagsData(TypeProfilingData) : NULL;
-    DWORD                   cTypeProfilingData = profileData ? profileData->GetTokenFlagsCount(TypeProfilingData) : NULL;
-
-    for (unsigned int i = 0; i < cTypeProfilingData; i++)
-    {
-        CORBBTPROF_TOKEN_INFO *entry = &pTypeProfilingData[i];
-        mdToken token = entry->token;
-        DWORD   flags = entry->flags;
-
-        if (TypeFromToken(token) != ibcTypeSpec)
-            continue;
-
-        if ((flags & (1 << ReadTypeHashTable)) == 0)
-            continue;
-
-        CORBBTPROF_BLOB_ENTRY *pBlobEntry = profileData ? profileData->GetBlobStream() : NULL;
-        if (pBlobEntry)
-        {
-            while (pBlobEntry->TypeIsValid())
-            {
-                if (TypeFromToken(pBlobEntry->token) == ibcTypeSpec)
-                {
-                    _ASSERTE(pBlobEntry->type == ParamTypeSpec);
-
-                    CORBBTPROF_BLOB_PARAM_SIG_ENTRY *pBlobSigEntry = (CORBBTPROF_BLOB_PARAM_SIG_ENTRY *) pBlobEntry;
-
-                    if (pBlobEntry->token == token)
-                    {
-                        if (flags & (1<<ReadTypeHashTable))
-                        {
-                            TypeHandle th = GetModule()->LoadIBCTypeHelper(image, pBlobSigEntry);
-#if defined(_DEBUG) && !defined(DACCESS_COMPILE)
-                            g_pConfig->DebugCheckAndForceIBCFailure(EEConfig::CallSite_8);
-#endif
-                            if (!th.IsNull())
-                            {
-                                // Found a hot type. See if we have it in our table.
-                                DWORD dwHash = HashTypeHandle(0, th);
-                                LookupContext sContext;
-                                EETypeHashEntry_t *pSearch = BaseFindFirstEntryByHash(dwHash, &sContext);
-                                while (pSearch)
-                                {
-                                    if (pSearch->GetTypeHandle() == th)
-                                    {
-                                        // Found the corresponding entry in the table. Mark it as hot.
-                                        pSearch->MarkAsHot();
-                                        break;
-                                    }
-
-                                    pSearch = BaseFindNextEntryByHash(&sContext);
-                                }
-                            }
-                        }
-                    }
-                }
-                pBlobEntry = pBlobEntry->GetNextEntry();
-            }
-        }
-    }
-
-    BaseSave(image, profileData);
-}
-
-bool EETypeHashTable::ShouldSave(DataImage *pImage, EETypeHashEntry_t *pEntry)
-{
-    STANDARD_VM_CONTRACT;
-
-    return !!pImage->GetPreloader()->IsTypeInTransitiveClosureOfInstantiations(CORINFO_CLASS_HANDLE(pEntry->GetTypeHandle().AsPtr()));
-}
-
-bool EETypeHashTable::IsHotEntry(EETypeHashEntry_t *pEntry, CorProfileData *pProfileData)
-{
-    STANDARD_VM_CONTRACT;
-
-    // EETypeHashTable::Save() will have marked the entry as hot if the profile data indicated this.
-    return pEntry->IsHot();
-}
-
-bool EETypeHashTable::SaveEntry(DataImage *pImage, CorProfileData *pProfileData, EETypeHashEntry_t *pOldEntry, EETypeHashEntry_t *pNewEntry, EntryMappingTable *pMap)
-{
-    LIMITED_METHOD_CONTRACT;
-
-    return false;
-}
-
-void EETypeHashTable::Fixup(DataImage *image)
-{
-    STANDARD_VM_CONTRACT;
-
-    BaseFixup(image);
-
-    image->ZeroPointerField(this, offsetof(EETypeHashTable, m_pAllocator));
-
-#ifdef _DEBUG
-    // The persisted table should be unsealed.
-    EETypeHashTable *pNewTable = (EETypeHashTable*) image->GetImagePointer(this);
-    pNewTable->InitUnseal();
-#endif
-}
-
-void EETypeHashTable::FixupEntry(DataImage *pImage, EETypeHashEntry_t *pEntry, void *pFixupBase, DWORD cbFixupOffset)
-{
-    STANDARD_VM_CONTRACT;
-
-    TypeHandle pType = pEntry->GetTypeHandle();
-    _ASSERTE(!pType.IsNull());
-
-    // Clear any hot entry marking in the data, it's not needed after the Save phase.
-    pEntry->SetTypeHandle(pType);
-
-    if (pType.IsTypeDesc())
-    {
-        pImage->FixupField(pFixupBase, cbFixupOffset + offsetof(EETypeHashEntry_t, m_data),
-                           pType.AsTypeDesc(), 2, IMAGE_REL_BASED_RelativePointer);
-
-        pType.AsTypeDesc()->Fixup(pImage);
-    }
-    else
-    {
-        pImage->FixupField(pFixupBase, cbFixupOffset + offsetof(EETypeHashEntry_t, m_data),
-                           pType.AsMethodTable(), 0, IMAGE_REL_BASED_RelativePointer);
-
-        pType.AsMethodTable()->Fixup(pImage);
-    }
-}
-#endif // FEATURE_NATIVE_IMAGE_GENERATION
-
 #endif // #ifndef DACCESS_COMPILE
 
 #ifdef DACCESS_COMPILE
index be19ab5..b923754 100644 (file)
@@ -141,21 +141,6 @@ public:
 
     DWORD GetCount();
 
-#if defined(FEATURE_PREJIT) && !defined(DACCESS_COMPILE)
-    // Save the hash table and any type descriptors referenced by it
-    // Template method tables (for arrays) must be saved separately
-    void Save(DataImage *image, Module *module, CorProfileData *profileData);
-
-    // Record fixups required on the hash table
-    // Recurse into type descriptors and template method tables referenced by it
-    void Fixup(DataImage *image);
-
-    bool ShouldSave(DataImage *pImage, EETypeHashEntry_t *pEntry);
-    bool IsHotEntry(EETypeHashEntry_t *pEntry, CorProfileData *pProfileData);
-    bool SaveEntry(DataImage *pImage, CorProfileData *pProfileData, EETypeHashEntry_t *pOldEntry, EETypeHashEntry_t *pNewEntry, EntryMappingTable *pMap);
-    void FixupEntry(DataImage *pImage, EETypeHashEntry_t *pEntry, void *pFixupBase, DWORD cbFixupOffset);
-#endif // FEATURE_PREJIT && !DACCESS_COMPILE
-
 #ifdef DACCESS_COMPILE
     void EnumMemoryRegions(CLRDataEnumMemoryFlags flags);
     void EnumMemoryRegionsForEntry(EETypeHashEntry_t *pEntry, CLRDataEnumMemoryFlags flags);
index 9400fd1..7746407 100644 (file)
@@ -702,9 +702,6 @@ PTR_GSCookie GetProcessGSCookiePtr() { return  PTR_GSCookie(&s_gsCookie); }
 inline
 GSCookie GetProcessGSCookie() { return *(RAW_KEYWORD(volatile) GSCookie *)(&s_gsCookie); }
 
-class CEECompileInfo;
-extern CEECompileInfo *g_pCEECompileInfo;
-
 #ifdef FEATURE_READYTORUN_COMPILER
 extern bool g_fReadyToRunCompilation;
 extern bool g_fLargeVersionBubble;
index 3af4c52..776c4b2 100644 (file)
@@ -15,9 +15,6 @@
 
 #include "common.h"
 #include "array.h"
-#ifdef FEATURE_PREJIT
-#include "compile.h"
-#endif
 
 #ifdef FEATURE_PERFMAP
 #include "perfmap.h"
index 8ef797e..3d9eeaa 100644 (file)
@@ -12,7 +12,6 @@
 #include "common.h"
 #include "zapsig.h"
 #include "typedesc.h"
-#include "compile.h"
 #include "sigbuilder.h"
 #include "nativeimage.h"
 
@@ -191,13 +190,7 @@ BOOL ZapSig::GetSignatureForTypeHandle(TypeHandle      handle,
     //
     DWORD index = 0;
     mdToken token = pMT->GetCl_NoLogging();
-#ifdef FEATURE_NATIVE_IMAGE_GENERATION
-    if (pTypeHandleModule != this->context.pInfoModule && !pTypeHandleModule->IsInCurrentVersionBubble())
-    {
-        pTypeHandleModule = GetAppDomain()->ToCompilationDomain()->GetTargetModule();
-        token = pTypeHandleModule->LookupTypeRefByMethodTable(pMT);
-    }
-#endif
+
     if (pTypeHandleModule != this->context.pInfoModule)
     {
         // During IBC profiling this calls