Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
using System.IO;
using System.Diagnostics;
using System.Collections.Generic;
using System.Linq;
using System.Text;

// Managed mirror of NativeFormatWriter.h/.cpp
Expand Down Expand Up @@ -2041,13 +2042,9 @@ void ComputeLayout()
// we can use the ordering to terminate the lookup prematurely.
uint mask = ((_nBuckets - 1) << 8) | 0xFF;

// sort it by hashcode
_Entries.Sort(
(a, b) =>
{
return (int)(a.Hashcode & mask) - (int)(b.Hashcode & mask);
}
);
// Sort by hashcode. This sort must be stable since we need determinism even if two entries have
// the same hashcode. This is deterministic if entries are added in a deterministic order.
_Entries = _Entries.OrderBy(entry => entry.Hashcode & mask).ToList();
Comment thread
fadimounir marked this conversation as resolved.
Resolved

// Start with maximum size entries
_entryIndexSize = 2;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
using System.Collections.Immutable;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;

using System.Threading;
using Internal.TypeSystem;
using Internal.TypeSystem.Ecma;

Expand Down Expand Up @@ -64,8 +64,8 @@ public override byte[] GetILBytes()
if (_ilBytes != null)
return _ilBytes;

byte[] ilBytes = _methodBody.GetILBytes();
return (_ilBytes = ilBytes);
Interlocked.CompareExchange(ref _ilBytes, _methodBody.GetILBytes(), null);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this needs to be in a loop to handle race conditions

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is correct as is. No loop needed.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah, right. Sorry, my bad. I got confused by the so many other compare-exchanges we have in the runtime code base :). Thanks for catching that Jan!

return _ilBytes;
}

public override bool IsInitLocals
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,12 @@

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;

using Internal.Text;
using Internal.TypeSystem;
using Internal.TypeSystem.Ecma;

using Debug = System.Diagnostics.Debug;
Expand All @@ -36,9 +36,11 @@ public class ManifestMetadataTableNode : HeaderTableNode
private readonly Dictionary<string, int> _assemblyRefToModuleIdMap;

/// <summary>
/// Assembly references to store in the manifest metadata.
/// Map from module index to the AssemblyName for the module. This only contains modules
/// that were actually loaded and is populated by ModuleToIndex.
/// </summary>
private readonly List<AssemblyName> _manifestAssemblies;
private readonly Dictionary<int, AssemblyName> _moduleIdToAssemblyNameMap;


/// <summary>
/// Registered signature emitters.
Expand Down Expand Up @@ -69,7 +71,7 @@ public ManifestMetadataTableNode(EcmaModule inputModule, NodeFactory nodeFactory
: base(inputModule.Context.Target)
{
_assemblyRefToModuleIdMap = new Dictionary<string, int>();
_manifestAssemblies = new List<AssemblyName>();
_moduleIdToAssemblyNameMap = new Dictionary<int, AssemblyName>();
_signatureEmitters = new List<ISignatureEmitter>();
_nodeFactory = nodeFactory;

Expand All @@ -95,9 +97,22 @@ public void RegisterEmitter(ISignatureEmitter emitter)

public int ModuleToIndex(EcmaModule module)
{
if (!_nodeFactory.MarkingComplete)
{
// If we call this function before sorting is complete, we might have a determinism bug caused by
// compiling two functions in an arbitrary order and hence getting different module IDs.
throw new InvalidOperationException("Cannot get ModuleToIndex mapping until marking is complete.");
}

AssemblyName assemblyName = module.Assembly.GetName();
int assemblyRefIndex;
if (!_assemblyRefToModuleIdMap.TryGetValue(assemblyName.Name, out assemblyRefIndex))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is wrong: this will cause missing entries in the _manifestAssemblies (the bug that I fixed recently).

The right way to fix this is to get rid of _manifestAssemblies, and emit a sorted version of _assemblyRefToModuleIdMap in GetData(), sorted by module ID

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

And make _assemblyRefToModuleIdMap a Dictionary<AssemblyName, int>

{
assemblyRefIndex = _nextModuleId++;
_assemblyRefToModuleIdMap.Add(assemblyName.Name, assemblyRefIndex);
}

if (!_manifestAssemblies.Contains(assemblyName))
if (!_moduleIdToAssemblyNameMap.ContainsKey(assemblyRefIndex))
{
if (_emissionCompleted)
{
Expand All @@ -108,14 +123,9 @@ public int ModuleToIndex(EcmaModule module)
// the verification logic would be broken at runtime.
Debug.Assert(_nodeFactory.CompilationModuleGroup.VersionsWithModule(module));

_manifestAssemblies.Add(assemblyName);
if (!_assemblyRefToModuleIdMap.ContainsKey(assemblyName.Name))
_assemblyRefToModuleIdMap.Add(assemblyName.Name, _nextModuleId);

_nextModuleId++;
_moduleIdToAssemblyNameMap.Add(assemblyRefIndex, assemblyName);
}

return _assemblyRefToModuleIdMap[assemblyName.Name];
return assemblyRefIndex;
}

public override int ClassCode => 791828335;
Expand Down Expand Up @@ -166,7 +176,8 @@ public override ObjectData GetData(NodeFactory factory, bool relocsOnly = false)
fieldList: MetadataTokens.FieldDefinitionHandle(1),
methodList: MetadataTokens.MethodDefinitionHandle(1));

foreach (AssemblyName assemblyName in _manifestAssemblies)
IEnumerable<AssemblyName> manifestAssemblies = _moduleIdToAssemblyNameMap.OrderBy(x => x.Key).Select(x => x.Value);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: It might look nicer to write it without .Select(), like:

foreach (var index in _moduleIdToAssemblyNameMap.Keys.OrderBy(...))
{
    use _moduleIdToAssemblyNameMap[index]
}

foreach (AssemblyName assemblyName in manifestAssemblies)
{
AssemblyFlags assemblyFlags = 0;
byte[] publicKeyOrToken;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,11 +27,15 @@ public override ObjectData GetData(NodeFactory factory, bool relocsOnly = false)
{
ReadyToRunCodegenNodeFactory r2rFactory = (ReadyToRunCodegenNodeFactory)factory;
ObjectDataSignatureBuilder dataBuilder = new ObjectDataSignatureBuilder();
dataBuilder.AddSymbol(this);

EcmaModule targetModule = _signatureContext.GetTargetModule(_arrayType);
SignatureContext innerContext = dataBuilder.EmitFixup(r2rFactory, ReadyToRunFixupKind.READYTORUN_FIXUP_NewArray, targetModule, _signatureContext);
dataBuilder.EmitTypeSignature(_arrayType, innerContext);
if (!relocsOnly)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: would be nice to follow the same convention we have in other places:

            if (relocsOnly)
            {
                return new ObjectData(Array.Empty<byte>(), null, 1, null);
            }

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It looks like we use a mix of both, but I like the if (relocsOnly) one better because of the indentation. Can I move all of them over to that one?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I mean the ones which return trivially like that. There are some legitimate uses of it as well.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In that case, leave it the way it is.

{
dataBuilder.AddSymbol(this);

EcmaModule targetModule = _signatureContext.GetTargetModule(_arrayType);
SignatureContext innerContext = dataBuilder.EmitFixup(r2rFactory, ReadyToRunFixupKind.READYTORUN_FIXUP_NewArray, targetModule, _signatureContext);
dataBuilder.EmitTypeSignature(_arrayType, innerContext);
}

return dataBuilder.ToObjectData();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,14 @@ public override ObjectData GetData(NodeFactory factory, bool relocsOnly = false)
{
ReadyToRunCodegenNodeFactory r2rFactory = (ReadyToRunCodegenNodeFactory)factory;
ObjectDataSignatureBuilder dataBuilder = new ObjectDataSignatureBuilder();
dataBuilder.AddSymbol(this);

dataBuilder.EmitFixup(r2rFactory, ReadyToRunFixupKind.READYTORUN_FIXUP_StringHandle, _token.Module, _signatureContext);
dataBuilder.EmitUInt(_token.TokenRid);
if (!relocsOnly)
{
dataBuilder.AddSymbol(this);

dataBuilder.EmitFixup(r2rFactory, ReadyToRunFixupKind.READYTORUN_FIXUP_StringHandle, _token.Module, _signatureContext);
dataBuilder.EmitUInt(_token.TokenRid);
}

return dataBuilder.ToObjectData();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@
using System.Threading;

using Internal.IL;
using Internal.IL.Stubs;
using Internal.JitInterface;
using Internal.TypeSystem;

Expand All @@ -26,7 +25,7 @@ public abstract class Compilation : ICompilation
protected readonly NodeFactory _nodeFactory;
protected readonly Logger _logger;
private readonly DevirtualizationManager _devirtualizationManager;
private ILCache _methodILCache;
protected ILCache _methodILCache;
private readonly HashSet<ModuleDesc> _modulesBeingInstrumented;


Expand Down Expand Up @@ -79,10 +78,6 @@ public bool CanInline(MethodDesc caller, MethodDesc callee)

public virtual MethodIL GetMethodIL(MethodDesc method)
{
// Flush the cache when it grows too big
if (_methodILCache.Count > 1000)
_methodILCache = new ILCache(_methodILCache.ILProvider, NodeFactory.CompilationModuleGroup);

return _methodILCache.GetOrCreateValue(method).MethodIL;
}

Expand All @@ -106,7 +101,7 @@ public bool IsModuleInstrumented(ModuleDesc module)
return _modulesBeingInstrumented.Contains(module);
}

private sealed class ILCache : LockFreeReaderHashtable<MethodDesc, ILCache.MethodILData>
public sealed class ILCache : LockFreeReaderHashtable<MethodDesc, ILCache.MethodILData>
{
public ILProvider ILProvider { get; }
private readonly CompilationModuleGroup _compilationModuleGroup;
Expand Down Expand Up @@ -147,7 +142,7 @@ protected override MethodILData CreateValueFromKey(MethodDesc key)
return new MethodILData() { Method = key, MethodIL = methodIL };
}

internal class MethodILData
public class MethodILData
{
public MethodDesc Method;
public MethodIL MethodIL;
Expand Down Expand Up @@ -302,6 +297,11 @@ protected override void ComputeDependencyNodeDependencies(List<DependencyNodeCor
}
}
}

if (_methodILCache.Count > 1000)
{
_methodILCache = new ILCache(_methodILCache.ILProvider, NodeFactory.CompilationModuleGroup);
}
}

public ISymbolNode GetFieldRvaData(FieldDesc field) => NodeFactory.CopiedFieldRva(field);
Expand Down