Operand.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594
  1. using ARMeilleure.CodeGen.Linking;
  2. using ARMeilleure.Common;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Diagnostics;
  6. using System.Runtime.CompilerServices;
  7. namespace ARMeilleure.IntermediateRepresentation
  8. {
  9. unsafe struct Operand : IEquatable<Operand>
  10. {
  11. internal struct Data
  12. {
  13. public byte Kind;
  14. public byte Type;
  15. public byte SymbolType;
  16. public byte Padding; // Unused space.
  17. public ushort AssignmentsCount;
  18. public ushort AssignmentsCapacity;
  19. public uint UsesCount;
  20. public uint UsesCapacity;
  21. public Operation* Assignments;
  22. public Operation* Uses;
  23. public ulong Value;
  24. public ulong SymbolValue;
  25. }
  26. private Data* _data;
  27. public OperandKind Kind
  28. {
  29. get => (OperandKind)_data->Kind;
  30. private set => _data->Kind = (byte)value;
  31. }
  32. public OperandType Type
  33. {
  34. get => (OperandType)_data->Type;
  35. private set => _data->Type = (byte)value;
  36. }
  37. public ulong Value
  38. {
  39. get => _data->Value;
  40. private set => _data->Value = value;
  41. }
  42. public Symbol Symbol
  43. {
  44. get
  45. {
  46. Debug.Assert(Kind != OperandKind.Memory);
  47. return new Symbol((SymbolType)_data->SymbolType, _data->SymbolValue);
  48. }
  49. private set
  50. {
  51. Debug.Assert(Kind != OperandKind.Memory);
  52. if (value.Type == SymbolType.None)
  53. {
  54. _data->SymbolType = (byte)SymbolType.None;
  55. }
  56. else
  57. {
  58. _data->SymbolType = (byte)value.Type;
  59. _data->SymbolValue = value.Value;
  60. }
  61. }
  62. }
  63. public ReadOnlySpan<Operation> Assignments
  64. {
  65. get
  66. {
  67. Debug.Assert(Kind != OperandKind.Memory);
  68. return new ReadOnlySpan<Operation>(_data->Assignments, _data->AssignmentsCount);
  69. }
  70. }
  71. public ReadOnlySpan<Operation> Uses
  72. {
  73. get
  74. {
  75. Debug.Assert(Kind != OperandKind.Memory);
  76. return new ReadOnlySpan<Operation>(_data->Uses, (int)_data->UsesCount);
  77. }
  78. }
  79. public int UsesCount => (int)_data->UsesCount;
  80. public int AssignmentsCount => _data->AssignmentsCount;
  81. public bool Relocatable => Symbol.Type != SymbolType.None;
  82. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  83. public Register GetRegister()
  84. {
  85. Debug.Assert(Kind == OperandKind.Register);
  86. return new Register((int)Value & 0xffffff, (RegisterType)(Value >> 24));
  87. }
  88. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  89. public MemoryOperand GetMemory()
  90. {
  91. Debug.Assert(Kind == OperandKind.Memory);
  92. return new MemoryOperand(this);
  93. }
  94. public int GetLocalNumber()
  95. {
  96. Debug.Assert(Kind == OperandKind.LocalVariable);
  97. return (int)Value;
  98. }
  99. public byte AsByte()
  100. {
  101. return (byte)Value;
  102. }
  103. public short AsInt16()
  104. {
  105. return (short)Value;
  106. }
  107. public int AsInt32()
  108. {
  109. return (int)Value;
  110. }
  111. public long AsInt64()
  112. {
  113. return (long)Value;
  114. }
  115. public float AsFloat()
  116. {
  117. return BitConverter.Int32BitsToSingle((int)Value);
  118. }
  119. public double AsDouble()
  120. {
  121. return BitConverter.Int64BitsToDouble((long)Value);
  122. }
  123. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  124. internal ref ulong GetValueUnsafe()
  125. {
  126. return ref _data->Value;
  127. }
  128. internal void NumberLocal(int number)
  129. {
  130. if (Kind != OperandKind.LocalVariable)
  131. {
  132. throw new InvalidOperationException("The operand is not a local variable.");
  133. }
  134. Value = (ulong)number;
  135. }
  136. public void AddAssignment(Operation operation)
  137. {
  138. if (Kind == OperandKind.LocalVariable)
  139. {
  140. Add(operation, ref _data->Assignments, ref _data->AssignmentsCount, ref _data->AssignmentsCapacity);
  141. }
  142. else if (Kind == OperandKind.Memory)
  143. {
  144. MemoryOperand memOp = GetMemory();
  145. Operand addr = memOp.BaseAddress;
  146. Operand index = memOp.Index;
  147. if (addr != default)
  148. {
  149. Add(operation, ref addr._data->Assignments, ref addr._data->AssignmentsCount, ref addr._data->AssignmentsCapacity);
  150. }
  151. if (index != default)
  152. {
  153. Add(operation, ref index._data->Assignments, ref index._data->AssignmentsCount, ref index._data->AssignmentsCapacity);
  154. }
  155. }
  156. }
  157. public void RemoveAssignment(Operation operation)
  158. {
  159. if (Kind == OperandKind.LocalVariable)
  160. {
  161. Remove(operation, ref _data->Assignments, ref _data->AssignmentsCount);
  162. }
  163. else if (Kind == OperandKind.Memory)
  164. {
  165. MemoryOperand memOp = GetMemory();
  166. Operand addr = memOp.BaseAddress;
  167. Operand index = memOp.Index;
  168. if (addr != default)
  169. {
  170. Remove(operation, ref addr._data->Assignments, ref addr._data->AssignmentsCount);
  171. }
  172. if (index != default)
  173. {
  174. Remove(operation, ref index._data->Assignments, ref index._data->AssignmentsCount);
  175. }
  176. }
  177. }
  178. public void AddUse(Operation operation)
  179. {
  180. if (Kind == OperandKind.LocalVariable)
  181. {
  182. Add(operation, ref _data->Uses, ref _data->UsesCount, ref _data->UsesCapacity);
  183. }
  184. else if (Kind == OperandKind.Memory)
  185. {
  186. MemoryOperand memOp = GetMemory();
  187. Operand addr = memOp.BaseAddress;
  188. Operand index = memOp.Index;
  189. if (addr != default)
  190. {
  191. Add(operation, ref addr._data->Uses, ref addr._data->UsesCount, ref addr._data->UsesCapacity);
  192. }
  193. if (index != default)
  194. {
  195. Add(operation, ref index._data->Uses, ref index._data->UsesCount, ref index._data->UsesCapacity);
  196. }
  197. }
  198. }
  199. public void RemoveUse(Operation operation)
  200. {
  201. if (Kind == OperandKind.LocalVariable)
  202. {
  203. Remove(operation, ref _data->Uses, ref _data->UsesCount);
  204. }
  205. else if (Kind == OperandKind.Memory)
  206. {
  207. MemoryOperand memOp = GetMemory();
  208. Operand addr = memOp.BaseAddress;
  209. Operand index = memOp.Index;
  210. if (addr != default)
  211. {
  212. Remove(operation, ref addr._data->Uses, ref addr._data->UsesCount);
  213. }
  214. if (index != default)
  215. {
  216. Remove(operation, ref index._data->Uses, ref index._data->UsesCount);
  217. }
  218. }
  219. }
  220. public Span<Operation> GetUses(ref Span<Operation> buffer)
  221. {
  222. ReadOnlySpan<Operation> uses = Uses;
  223. if (buffer.Length < uses.Length)
  224. {
  225. buffer = Allocators.Default.AllocateSpan<Operation>((uint)uses.Length);
  226. }
  227. uses.CopyTo(buffer);
  228. return buffer.Slice(0, uses.Length);
  229. }
  230. private static void New<T>(ref T* data, ref ushort count, ref ushort capacity, ushort initialCapacity) where T : unmanaged
  231. {
  232. count = 0;
  233. capacity = initialCapacity;
  234. data = Allocators.References.Allocate<T>(initialCapacity);
  235. }
  236. private static void New<T>(ref T* data, ref uint count, ref uint capacity, uint initialCapacity) where T : unmanaged
  237. {
  238. count = 0;
  239. capacity = initialCapacity;
  240. data = Allocators.References.Allocate<T>(initialCapacity);
  241. }
  242. private static void Add<T>(T item, ref T* data, ref ushort count, ref ushort capacity) where T : unmanaged
  243. {
  244. if (count < capacity)
  245. {
  246. data[(uint)count++] = item;
  247. return;
  248. }
  249. // Could not add item in the fast path, fallback onto the slow path.
  250. ExpandAdd(item, ref data, ref count, ref capacity);
  251. static void ExpandAdd(T item, ref T* data, ref ushort count, ref ushort capacity)
  252. {
  253. ushort newCount = checked((ushort)(count + 1));
  254. ushort newCapacity = (ushort)Math.Min(capacity * 2, ushort.MaxValue);
  255. var oldSpan = new Span<T>(data, count);
  256. capacity = newCapacity;
  257. data = Allocators.References.Allocate<T>(capacity);
  258. oldSpan.CopyTo(new Span<T>(data, count));
  259. data[count] = item;
  260. count = newCount;
  261. }
  262. }
  263. private static void Add<T>(T item, ref T* data, ref uint count, ref uint capacity) where T : unmanaged
  264. {
  265. if (count < capacity)
  266. {
  267. data[count++] = item;
  268. return;
  269. }
  270. // Could not add item in the fast path, fallback onto the slow path.
  271. ExpandAdd(item, ref data, ref count, ref capacity);
  272. static void ExpandAdd(T item, ref T* data, ref uint count, ref uint capacity)
  273. {
  274. uint newCount = checked(count + 1);
  275. uint newCapacity = (uint)Math.Min(capacity * 2, int.MaxValue);
  276. if (newCapacity <= capacity)
  277. {
  278. throw new OverflowException();
  279. }
  280. var oldSpan = new Span<T>(data, (int)count);
  281. capacity = newCapacity;
  282. data = Allocators.References.Allocate<T>(capacity);
  283. oldSpan.CopyTo(new Span<T>(data, (int)count));
  284. data[count] = item;
  285. count = newCount;
  286. }
  287. }
  288. private static void Remove<T>(in T item, ref T* data, ref ushort count) where T : unmanaged
  289. {
  290. var span = new Span<T>(data, count);
  291. for (int i = 0; i < span.Length; i++)
  292. {
  293. if (EqualityComparer<T>.Default.Equals(span[i], item))
  294. {
  295. if (i + 1 < count)
  296. {
  297. span.Slice(i + 1).CopyTo(span.Slice(i));
  298. }
  299. count--;
  300. return;
  301. }
  302. }
  303. }
  304. private static void Remove<T>(in T item, ref T* data, ref uint count) where T : unmanaged
  305. {
  306. var span = new Span<T>(data, (int)count);
  307. for (int i = 0; i < span.Length; i++)
  308. {
  309. if (EqualityComparer<T>.Default.Equals(span[i], item))
  310. {
  311. if (i + 1 < count)
  312. {
  313. span.Slice(i + 1).CopyTo(span.Slice(i));
  314. }
  315. count--;
  316. return;
  317. }
  318. }
  319. }
  320. public override int GetHashCode()
  321. {
  322. return ((ulong)_data).GetHashCode();
  323. }
  324. public bool Equals(Operand operand)
  325. {
  326. return operand._data == _data;
  327. }
  328. public override bool Equals(object obj)
  329. {
  330. return obj is Operand operand && Equals(operand);
  331. }
  332. public static bool operator ==(Operand a, Operand b)
  333. {
  334. return a.Equals(b);
  335. }
  336. public static bool operator !=(Operand a, Operand b)
  337. {
  338. return !a.Equals(b);
  339. }
  340. public static class Factory
  341. {
  342. private const int InternTableSize = 256;
  343. private const int InternTableProbeLength = 8;
  344. [ThreadStatic]
  345. private static Data* _internTable;
  346. private static Data* InternTable
  347. {
  348. get
  349. {
  350. if (_internTable == null)
  351. {
  352. _internTable = (Data*)NativeAllocator.Instance.Allocate((uint)sizeof(Data) * InternTableSize);
  353. // Make sure the table is zeroed.
  354. new Span<Data>(_internTable, InternTableSize).Clear();
  355. }
  356. return _internTable;
  357. }
  358. }
  359. private static Operand Make(OperandKind kind, OperandType type, ulong value, Symbol symbol = default)
  360. {
  361. Debug.Assert(kind != OperandKind.None);
  362. Data* data = null;
  363. // If constant or register, then try to look up in the intern table before allocating.
  364. if (kind == OperandKind.Constant || kind == OperandKind.Register)
  365. {
  366. uint hash = (uint)HashCode.Combine(kind, type, value);
  367. // Look in the next InternTableProbeLength slots for a match.
  368. for (uint i = 0; i < InternTableProbeLength; i++)
  369. {
  370. Operand interned = new();
  371. interned._data = &InternTable[(hash + i) % InternTableSize];
  372. // If slot matches the allocation request then return that slot.
  373. if (interned.Kind == kind && interned.Type == type && interned.Value == value && interned.Symbol == symbol)
  374. {
  375. return interned;
  376. }
  377. // Otherwise if the slot is not occupied, we store in that slot.
  378. else if (interned.Kind == OperandKind.None)
  379. {
  380. data = interned._data;
  381. break;
  382. }
  383. }
  384. }
  385. // If we could not get a slot from the intern table, we allocate somewhere else and store there.
  386. if (data == null)
  387. {
  388. data = Allocators.Operands.Allocate<Data>();
  389. }
  390. *data = default;
  391. Operand result = new();
  392. result._data = data;
  393. result.Value = value;
  394. result.Kind = kind;
  395. result.Type = type;
  396. if (kind != OperandKind.Memory)
  397. {
  398. result.Symbol = symbol;
  399. }
  400. // If local variable, then the use and def list is initialized with default sizes.
  401. if (kind == OperandKind.LocalVariable)
  402. {
  403. New(ref result._data->Assignments, ref result._data->AssignmentsCount, ref result._data->AssignmentsCapacity, 1);
  404. New(ref result._data->Uses, ref result._data->UsesCount, ref result._data->UsesCapacity, 4);
  405. }
  406. return result;
  407. }
  408. public static Operand Const(OperandType type, long value)
  409. {
  410. Debug.Assert(type is OperandType.I32 or OperandType.I64);
  411. return type == OperandType.I32 ? Const((int)value) : Const(value);
  412. }
  413. public static Operand Const(bool value)
  414. {
  415. return Const(value ? 1 : 0);
  416. }
  417. public static Operand Const(int value)
  418. {
  419. return Const((uint)value);
  420. }
  421. public static Operand Const(uint value)
  422. {
  423. return Make(OperandKind.Constant, OperandType.I32, value);
  424. }
  425. public static Operand Const(long value)
  426. {
  427. return Const(value, symbol: default);
  428. }
  429. public static Operand Const<T>(ref T reference, Symbol symbol = default)
  430. {
  431. return Const((long)Unsafe.AsPointer(ref reference), symbol);
  432. }
  433. public static Operand Const(long value, Symbol symbol)
  434. {
  435. return Make(OperandKind.Constant, OperandType.I64, (ulong)value, symbol);
  436. }
  437. public static Operand Const(ulong value)
  438. {
  439. return Make(OperandKind.Constant, OperandType.I64, value);
  440. }
  441. public static Operand ConstF(float value)
  442. {
  443. return Make(OperandKind.Constant, OperandType.FP32, (ulong)BitConverter.SingleToInt32Bits(value));
  444. }
  445. public static Operand ConstF(double value)
  446. {
  447. return Make(OperandKind.Constant, OperandType.FP64, (ulong)BitConverter.DoubleToInt64Bits(value));
  448. }
  449. public static Operand Label()
  450. {
  451. return Make(OperandKind.Label, OperandType.None, 0);
  452. }
  453. public static Operand Local(OperandType type)
  454. {
  455. return Make(OperandKind.LocalVariable, type, 0);
  456. }
  457. public static Operand Register(int index, RegisterType regType, OperandType type)
  458. {
  459. return Make(OperandKind.Register, type, (ulong)((int)regType << 24 | index));
  460. }
  461. public static Operand Undef()
  462. {
  463. return Make(OperandKind.Undefined, OperandType.None, 0);
  464. }
  465. public static Operand MemoryOp(
  466. OperandType type,
  467. Operand baseAddress,
  468. Operand index = default,
  469. Multiplier scale = Multiplier.x1,
  470. int displacement = 0)
  471. {
  472. Operand result = Make(OperandKind.Memory, type, 0);
  473. MemoryOperand memory = result.GetMemory();
  474. memory.BaseAddress = baseAddress;
  475. memory.Index = index;
  476. memory.Scale = scale;
  477. memory.Displacement = displacement;
  478. return result;
  479. }
  480. }
  481. }
  482. }