Operand.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587
  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. private static void New<T>(ref T* data, ref ushort count, ref ushort capacity, ushort initialCapacity) where T : unmanaged
  221. {
  222. count = 0;
  223. capacity = initialCapacity;
  224. data = Allocators.References.Allocate<T>(initialCapacity);
  225. }
  226. private static void New<T>(ref T* data, ref uint count, ref uint capacity, uint initialCapacity) where T : unmanaged
  227. {
  228. count = 0;
  229. capacity = initialCapacity;
  230. data = Allocators.References.Allocate<T>(initialCapacity);
  231. }
  232. private static void Add<T>(T item, ref T* data, ref ushort count, ref ushort capacity) where T : unmanaged
  233. {
  234. if (count < capacity)
  235. {
  236. data[(uint)count++] = item;
  237. return;
  238. }
  239. // Could not add item in the fast path, fallback onto the slow path.
  240. ExpandAdd(item, ref data, ref count, ref capacity);
  241. static void ExpandAdd(T item, ref T* data, ref ushort count, ref ushort capacity)
  242. {
  243. ushort newCount = checked((ushort)(count + 1));
  244. ushort newCapacity = (ushort)Math.Min(capacity * 2, ushort.MaxValue);
  245. var oldSpan = new Span<T>(data, count);
  246. capacity = newCapacity;
  247. data = Allocators.References.Allocate<T>(capacity);
  248. oldSpan.CopyTo(new Span<T>(data, count));
  249. data[count] = item;
  250. count = newCount;
  251. }
  252. }
  253. private static void Add<T>(T item, ref T* data, ref uint count, ref uint capacity) where T : unmanaged
  254. {
  255. if (count < capacity)
  256. {
  257. data[count++] = item;
  258. return;
  259. }
  260. // Could not add item in the fast path, fallback onto the slow path.
  261. ExpandAdd(item, ref data, ref count, ref capacity);
  262. static void ExpandAdd(T item, ref T* data, ref uint count, ref uint capacity)
  263. {
  264. uint newCount = checked(count + 1);
  265. uint newCapacity = (uint)Math.Min(capacity * 2, int.MaxValue);
  266. if (newCapacity <= capacity)
  267. {
  268. throw new OverflowException();
  269. }
  270. var oldSpan = new Span<T>(data, (int)count);
  271. capacity = newCapacity;
  272. data = Allocators.References.Allocate<T>(capacity);
  273. oldSpan.CopyTo(new Span<T>(data, (int)count));
  274. data[count] = item;
  275. count = newCount;
  276. }
  277. }
  278. private static void Remove<T>(in T item, ref T* data, ref ushort count) where T : unmanaged
  279. {
  280. var span = new Span<T>(data, count);
  281. for (int i = 0; i < span.Length; i++)
  282. {
  283. if (EqualityComparer<T>.Default.Equals(span[i], item))
  284. {
  285. if (i + 1 < count)
  286. {
  287. span.Slice(i + 1).CopyTo(span.Slice(i));
  288. }
  289. count--;
  290. return;
  291. }
  292. }
  293. }
  294. private static void Remove<T>(in T item, ref T* data, ref uint count) where T : unmanaged
  295. {
  296. var span = new Span<T>(data, (int)count);
  297. for (int i = 0; i < span.Length; i++)
  298. {
  299. if (EqualityComparer<T>.Default.Equals(span[i], item))
  300. {
  301. if (i + 1 < count)
  302. {
  303. span.Slice(i + 1).CopyTo(span.Slice(i));
  304. }
  305. count--;
  306. return;
  307. }
  308. }
  309. }
  310. public override int GetHashCode()
  311. {
  312. if (Kind == OperandKind.LocalVariable)
  313. {
  314. return base.GetHashCode();
  315. }
  316. else
  317. {
  318. return (int)Value ^ ((int)Kind << 16) ^ ((int)Type << 20);
  319. }
  320. }
  321. public bool Equals(Operand operand)
  322. {
  323. return operand._data == _data;
  324. }
  325. public override bool Equals(object obj)
  326. {
  327. return obj is Operand operand && Equals(operand);
  328. }
  329. public static bool operator ==(Operand a, Operand b)
  330. {
  331. return a.Equals(b);
  332. }
  333. public static bool operator !=(Operand a, Operand b)
  334. {
  335. return !a.Equals(b);
  336. }
  337. public static class Factory
  338. {
  339. private const int InternTableSize = 256;
  340. private const int InternTableProbeLength = 8;
  341. [ThreadStatic]
  342. private static Data* _internTable;
  343. private static Data* InternTable
  344. {
  345. get
  346. {
  347. if (_internTable == null)
  348. {
  349. _internTable = (Data*)NativeAllocator.Instance.Allocate((uint)sizeof(Data) * InternTableSize);
  350. // Make sure the table is zeroed.
  351. new Span<Data>(_internTable, InternTableSize).Clear();
  352. }
  353. return _internTable;
  354. }
  355. }
  356. private static Operand Make(OperandKind kind, OperandType type, ulong value, Symbol symbol = default)
  357. {
  358. Debug.Assert(kind != OperandKind.None);
  359. Data* data = null;
  360. // If constant or register, then try to look up in the intern table before allocating.
  361. if (kind == OperandKind.Constant || kind == OperandKind.Register)
  362. {
  363. uint hash = (uint)HashCode.Combine(kind, type, value);
  364. // Look in the next InternTableProbeLength slots for a match.
  365. for (uint i = 0; i < InternTableProbeLength; i++)
  366. {
  367. Operand interned = new();
  368. interned._data = &InternTable[(hash + i) % InternTableSize];
  369. // If slot matches the allocation request then return that slot.
  370. if (interned.Kind == kind && interned.Type == type && interned.Value == value && interned.Symbol == symbol)
  371. {
  372. return interned;
  373. }
  374. // Otherwise if the slot is not occupied, we store in that slot.
  375. else if (interned.Kind == OperandKind.None)
  376. {
  377. data = interned._data;
  378. break;
  379. }
  380. }
  381. }
  382. // If we could not get a slot from the intern table, we allocate somewhere else and store there.
  383. if (data == null)
  384. {
  385. data = Allocators.Operands.Allocate<Data>();
  386. }
  387. *data = default;
  388. Operand result = new();
  389. result._data = data;
  390. result.Value = value;
  391. result.Kind = kind;
  392. result.Type = type;
  393. if (kind != OperandKind.Memory)
  394. {
  395. result.Symbol = symbol;
  396. }
  397. // If local variable, then the use and def list is initialized with default sizes.
  398. if (kind == OperandKind.LocalVariable)
  399. {
  400. New(ref result._data->Assignments, ref result._data->AssignmentsCount, ref result._data->AssignmentsCapacity, 1);
  401. New(ref result._data->Uses, ref result._data->UsesCount, ref result._data->UsesCapacity, 4);
  402. }
  403. return result;
  404. }
  405. public static Operand Const(OperandType type, long value)
  406. {
  407. Debug.Assert(type is OperandType.I32 or OperandType.I64);
  408. return type == OperandType.I32 ? Const((int)value) : Const(value);
  409. }
  410. public static Operand Const(bool value)
  411. {
  412. return Const(value ? 1 : 0);
  413. }
  414. public static Operand Const(int value)
  415. {
  416. return Const((uint)value);
  417. }
  418. public static Operand Const(uint value)
  419. {
  420. return Make(OperandKind.Constant, OperandType.I32, value);
  421. }
  422. public static Operand Const(long value)
  423. {
  424. return Const(value, symbol: default);
  425. }
  426. public static Operand Const<T>(ref T reference, Symbol symbol = default)
  427. {
  428. return Const((long)Unsafe.AsPointer(ref reference), symbol);
  429. }
  430. public static Operand Const(long value, Symbol symbol)
  431. {
  432. return Make(OperandKind.Constant, OperandType.I64, (ulong)value, symbol);
  433. }
  434. public static Operand Const(ulong value)
  435. {
  436. return Make(OperandKind.Constant, OperandType.I64, value);
  437. }
  438. public static Operand ConstF(float value)
  439. {
  440. return Make(OperandKind.Constant, OperandType.FP32, (ulong)BitConverter.SingleToInt32Bits(value));
  441. }
  442. public static Operand ConstF(double value)
  443. {
  444. return Make(OperandKind.Constant, OperandType.FP64, (ulong)BitConverter.DoubleToInt64Bits(value));
  445. }
  446. public static Operand Label()
  447. {
  448. return Make(OperandKind.Label, OperandType.None, 0);
  449. }
  450. public static Operand Local(OperandType type)
  451. {
  452. return Make(OperandKind.LocalVariable, type, 0);
  453. }
  454. public static Operand Register(int index, RegisterType regType, OperandType type)
  455. {
  456. return Make(OperandKind.Register, type, (ulong)((int)regType << 24 | index));
  457. }
  458. public static Operand Undef()
  459. {
  460. return Make(OperandKind.Undefined, OperandType.None, 0);
  461. }
  462. public static Operand MemoryOp(
  463. OperandType type,
  464. Operand baseAddress,
  465. Operand index = default,
  466. Multiplier scale = Multiplier.x1,
  467. int displacement = 0)
  468. {
  469. Operand result = Make(OperandKind.Memory, type, 0);
  470. MemoryOperand memory = result.GetMemory();
  471. memory.BaseAddress = baseAddress;
  472. memory.Index = index;
  473. memory.Scale = scale;
  474. memory.Displacement = displacement;
  475. return result;
  476. }
  477. }
  478. }
  479. }