Ryujinx/ARMeilleure/Translation/SsaConstruction.cs
FICTURE7 22b2cb39af
Reduce JIT GC allocations (#2515)
* Turn `MemoryOperand` into a struct

* Remove `IntrinsicOperation`

* Remove `PhiNode`

* Remove `Node`

* Turn `Operand` into a struct

* Turn `Operation` into a struct

* Clean up pool management methods

* Add `Arena` allocator

* Move `OperationHelper` to `Operation.Factory`

* Move `OperandHelper` to `Operand.Factory`

* Optimize `Operation` a bit

* Fix `Arena` initialization

* Rename `NativeList<T>` to `ArenaList<T>`

* Reduce `Operand` size from 88 to 56 bytes

* Reduce `Operation` size from 56 to 40 bytes

* Add optimistic interning of Register & Constant operands

* Optimize `RegisterUsage` pass a bit

* Optimize `RemoveUnusedNodes` pass a bit

Iterating in reverse-order allows killing dependency chains in a single
pass.

* Fix PPTC symbols

* Optimize `BasicBlock` a bit

Reduce allocations from `_successor` & `DominanceFrontiers`

* Fix `Operation` resize

* Make `Arena` expandable

Change the arena allocator to be expandable by allocating in pages, with
some of them being pooled. Currently 32 pages are pooled. An LRU removal
mechanism should probably be added to it.

Apparently MHR can allocate bitmaps large enough to exceed the 16MB
limit for the type.

* Move `Arena` & `ArenaList` to `Common`

* Remove `ThreadStaticPool` & co

* Add `PhiOperation`

* Reduce `Operand` size from 56 from 48 bytes

* Add linear-probing to `Operand` intern table

* Optimize `HybridAllocator` a bit

* Add `Allocators` class

* Tune `ArenaAllocator` sizes

* Add page removal mechanism to `ArenaAllocator`

Remove pages which have not been used for more than 5s after each reset.

I am on fence if this would be better using a Gen2 callback object like
the one in System.Buffers.ArrayPool<T>, to trim the pool. Because right
now if a large translation happens, the pages will be freed only after a
reset. This reset may not happen for a while because no new translation
is hit, but the arena base sizes are rather small.

* Fix `OOM` when allocating larger than page size in `ArenaAllocator`

Tweak resizing mechanism for Operand.Uses and Assignemnts.

* Optimize `Optimizer` a bit

* Optimize `Operand.Add<T>/Remove<T>` a bit

* Clean up `PreAllocator`

* Fix phi insertion order

Reduce codegen diffs.

* Fix code alignment

* Use new heuristics for degree of parallelism

* Suppress warnings

* Address gdkchan's feedback

Renamed `GetValue()` to `GetValueUnsafe()` to make it more clear that
`Operand.Value` should usually not be modified directly.

* Add fast path to `ArenaAllocator`

* Assembly for `ArenaAllocator.Allocate(ulong)`:

  .L0:
    mov rax, [rcx+0x18]
    lea r8, [rax+rdx]
    cmp r8, [rcx+0x10]
    ja short .L2
  .L1:
    mov rdx, [rcx+8]
    add rax, [rdx+8]
    mov [rcx+0x18], r8
    ret
  .L2:
    jmp ArenaAllocator.AllocateSlow(UInt64)

  A few variable/field had to be changed to ulong so that RyuJIT avoids
  emitting zero-extends.

* Implement a new heuristic to free pooled pages.

  If an arena is used often, it is more likely that its pages will be
  needed, so the pages are kept for longer (e.g: during PPTC rebuild or
  burst sof compilations). If is not used often, then it is more likely
  that its pages will not be needed (e.g: after PPTC rebuild or bursts
  of compilations).

* Address riperiperi's feedback

* Use `EqualityComparer<T>` in `IntrusiveList<T>`

Avoids a potential GC hole in `Equals(T, T)`.
2021-08-17 15:08:34 -03:00

289 lines
9.2 KiB
C#

using ARMeilleure.Common;
using ARMeilleure.IntermediateRepresentation;
using ARMeilleure.State;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using static ARMeilleure.IntermediateRepresentation.Operand.Factory;
namespace ARMeilleure.Translation
{
static partial class Ssa
{
private class DefMap
{
private readonly Dictionary<int, Operand> _map;
private readonly BitMap _phiMasks;
public DefMap()
{
_map = new Dictionary<int, Operand>();
_phiMasks = new BitMap(Allocators.Default, RegisterConsts.TotalCount);
}
public bool TryAddOperand(int key, Operand operand)
{
return _map.TryAdd(key, operand);
}
public bool TryGetOperand(int key, out Operand operand)
{
return _map.TryGetValue(key, out operand);
}
public bool AddPhi(int key)
{
return _phiMasks.Set(key);
}
public bool HasPhi(int key)
{
return _phiMasks.IsSet(key);
}
}
public static void Construct(ControlFlowGraph cfg)
{
var globalDefs = new DefMap[cfg.Blocks.Count];
var localDefs = new Operand[cfg.LocalsCount + RegisterConsts.TotalCount];
var dfPhiBlocks = new Queue<BasicBlock>();
for (BasicBlock block = cfg.Blocks.First; block != null; block = block.ListNext)
{
globalDefs[block.Index] = new DefMap();
}
// First pass, get all defs and locals uses.
for (BasicBlock block = cfg.Blocks.First; block != null; block = block.ListNext)
{
for (Operation node = block.Operations.First; node != default; node = node.ListNext)
{
for (int index = 0; index < node.SourcesCount; index++)
{
Operand src = node.GetSource(index);
if (TryGetId(src, out int srcKey))
{
Operand local = localDefs[srcKey];
if (local == default)
{
local = src;
}
node.SetSource(index, local);
}
}
Operand dest = node.Destination;
if (TryGetId(dest, out int destKey))
{
Operand local = Local(dest.Type);
localDefs[destKey] = local;
node.Destination = local;
}
}
for (int key = 0; key < localDefs.Length; key++)
{
Operand local = localDefs[key];
if (local == default)
{
continue;
}
globalDefs[block.Index].TryAddOperand(key, local);
dfPhiBlocks.Enqueue(block);
while (dfPhiBlocks.TryDequeue(out BasicBlock dfPhiBlock))
{
foreach (BasicBlock domFrontier in dfPhiBlock.DominanceFrontiers)
{
if (globalDefs[domFrontier.Index].AddPhi(key))
{
dfPhiBlocks.Enqueue(domFrontier);
}
}
}
}
Array.Clear(localDefs, 0, localDefs.Length);
}
// Second pass, rename variables with definitions on different blocks.
for (BasicBlock block = cfg.Blocks.First; block != null; block = block.ListNext)
{
for (Operation node = block.Operations.First; node != default; node = node.ListNext)
{
for (int index = 0; index < node.SourcesCount; index++)
{
Operand src = node.GetSource(index);
if (TryGetId(src, out int key))
{
Operand local = localDefs[key];
if (local == default)
{
local = FindDef(globalDefs, block, src);
localDefs[key] = local;
}
node.SetSource(index, local);
}
}
}
Array.Clear(localDefs, 0, localDefs.Length);
}
}
private static Operand FindDef(DefMap[] globalDefs, BasicBlock current, Operand operand)
{
if (globalDefs[current.Index].HasPhi(GetId(operand)))
{
return InsertPhi(globalDefs, current, operand);
}
if (current != current.ImmediateDominator)
{
return FindDefOnPred(globalDefs, current.ImmediateDominator, operand);
}
return Undef();
}
private static Operand FindDefOnPred(DefMap[] globalDefs, BasicBlock current, Operand operand)
{
BasicBlock previous;
do
{
DefMap defMap = globalDefs[current.Index];
int key = GetId(operand);
if (defMap.TryGetOperand(key, out Operand lastDef))
{
return lastDef;
}
if (defMap.HasPhi(key))
{
return InsertPhi(globalDefs, current, operand);
}
previous = current;
current = current.ImmediateDominator;
}
while (previous != current);
return Undef();
}
private static Operand InsertPhi(DefMap[] globalDefs, BasicBlock block, Operand operand)
{
// This block has a Phi that has not been materialized yet, but that
// would define a new version of the variable we're looking for. We need
// to materialize the Phi, add all the block/operand pairs into the Phi, and
// then use the definition from that Phi.
Operand local = Local(operand.Type);
Operation operation = Operation.Factory.PhiOperation(local, block.Predecessors.Count);
AddPhi(block, operation);
globalDefs[block.Index].TryAddOperand(GetId(operand), local);
PhiOperation phi = operation.AsPhi();
for (int index = 0; index < block.Predecessors.Count; index++)
{
BasicBlock predecessor = block.Predecessors[index];
phi.SetBlock(index, predecessor);
phi.SetSource(index, FindDefOnPred(globalDefs, predecessor, operand));
}
return local;
}
private static void AddPhi(BasicBlock block, Operation phi)
{
Operation node = block.Operations.First;
if (node != default)
{
while (node.ListNext != default && node.ListNext.Instruction == Instruction.Phi)
{
node = node.ListNext;
}
}
if (node != default && node.Instruction == Instruction.Phi)
{
block.Operations.AddAfter(node, phi);
}
else
{
block.Operations.AddFirst(phi);
}
}
private static bool TryGetId(Operand operand, out int result)
{
if (operand != default)
{
if (operand.Kind == OperandKind.Register)
{
Register reg = operand.GetRegister();
if (reg.Type == RegisterType.Integer)
{
result = reg.Index;
}
else if (reg.Type == RegisterType.Vector)
{
result = RegisterConsts.IntRegsCount + reg.Index;
}
else if (reg.Type == RegisterType.Flag)
{
result = RegisterConsts.IntAndVecRegsCount + reg.Index;
}
else /* if (reg.Type == RegisterType.FpFlag) */
{
result = RegisterConsts.FpFlagsOffset + reg.Index;
}
return true;
}
else if (operand.Kind == OperandKind.LocalVariable && operand.GetLocalNumber() > 0)
{
result = RegisterConsts.TotalCount + operand.GetLocalNumber() - 1;
return true;
}
}
result = -1;
return false;
}
private static int GetId(Operand operand)
{
if (!TryGetId(operand, out int key))
{
Debug.Fail("OperandKind must be Register or a numbered LocalVariable.");
}
return key;
}
}
}