Thanks to visit codestin.com
Credit goes to github.com

Skip to content
Merged
Changes from 1 commit
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
Prev Previous commit
Next Next commit
Use BinaryPrimitives in ILEmitter
  • Loading branch information
PaulusParssinen committed Jul 24, 2024
commit a3b5da2835080e4503badb301441e139025d690f
41 changes: 23 additions & 18 deletions src/coreclr/tools/Common/TypeSystem/IL/Stubs/ILEmitter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,9 @@
// The .NET Foundation licenses this file to you under the MIT license.

using System;
using System.Buffers.Binary;
using System.Collections.Generic;

using System.Runtime.CompilerServices;
using Internal.TypeSystem;

using Debug = System.Diagnostics.Debug;
Expand Down Expand Up @@ -49,23 +50,33 @@ internal int RelativeToAbsoluteOffset(int relativeOffset)

private void EmitByte(byte b)
{
if (_instructions.Length == _length)
Array.Resize<byte>(ref _instructions, 2 * _instructions.Length + 10);
if (_length == _instructions.Length)
Grow();
_instructions[_length++] = b;
}

private void EmitUInt16(ushort value)
{
EmitByte((byte)value);
EmitByte((byte)(value >> 8));
if (_length + sizeof(ushort) > _instructions.Length)
Grow();

BinaryPrimitives.WriteUInt16LittleEndian(_instructions.AsSpan(_length, sizeof(ushort)), value);
_length += sizeof(ushort);
}

private void EmitUInt32(int value)
{
EmitByte((byte)value);
EmitByte((byte)(value >> 8));
EmitByte((byte)(value >> 16));
EmitByte((byte)(value >> 24));
if (_length + sizeof(int) > _instructions.Length)
Grow();

BinaryPrimitives.WriteInt32LittleEndian(_instructions.AsSpan(_length, sizeof(int)), value);
_length += sizeof(int);
}

[MethodImpl(MethodImplOptions.NoInlining)]
private void Grow()
{
Array.Resize(ref _instructions, 2 * _instructions.Length + 10);
}

public void Emit(ILOpcode opcode)
Expand Down Expand Up @@ -468,19 +479,13 @@ internal void PatchLabels()
Debug.Assert(patch.Label.IsPlaced);
Debug.Assert(_startOffsetForLinking != StartOffsetNotSet);

int offset = patch.Offset;
Span<byte> offsetSpan = _instructions.AsSpan(patch.Offset, sizeof(int));

int delta = _instructions[offset + 3] << 24 |
_instructions[offset + 2] << 16 |
_instructions[offset + 1] << 8 |
_instructions[offset];
int delta = BinaryPrimitives.ReadInt32LittleEndian(offsetSpan);

int value = patch.Label.AbsoluteOffset - _startOffsetForLinking - patch.Offset - delta;

_instructions[offset] = (byte)value;
_instructions[offset + 1] = (byte)(value >> 8);
_instructions[offset + 2] = (byte)(value >> 16);
_instructions[offset + 3] = (byte)(value >> 24);
BinaryPrimitives.WriteInt32LittleEndian(offsetSpan, value);
}
}

Expand Down