aboutsummaryrefslogtreecommitdiff
path: root/ARMeilleure/Instructions/InstEmitMemoryHelper.cs
blob: f97e395ce0c277033a6229e8662c94da8a8f457d (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
using ARMeilleure.Decoders;
using ARMeilleure.IntermediateRepresentation;
using ARMeilleure.Memory;
using ARMeilleure.Translation;
using ARMeilleure.Translation.PTC;
using System;
using System.Reflection;

using static ARMeilleure.Instructions.InstEmitHelper;
using static ARMeilleure.IntermediateRepresentation.Operand.Factory;

namespace ARMeilleure.Instructions
{
    static class InstEmitMemoryHelper
    {
        private const int PageBits = 12;
        private const int PageMask = (1 << PageBits) - 1;

        private enum Extension
        {
            Zx,
            Sx32,
            Sx64
        }

        public static void EmitLoadZx(ArmEmitterContext context, Operand address, int rt, int size)
        {
            EmitLoad(context, address, Extension.Zx, rt, size);
        }

        public static void EmitLoadSx32(ArmEmitterContext context, Operand address, int rt, int size)
        {
            EmitLoad(context, address, Extension.Sx32, rt, size);
        }

        public static void EmitLoadSx64(ArmEmitterContext context, Operand address, int rt, int size)
        {
            EmitLoad(context, address, Extension.Sx64, rt, size);
        }

        private static void EmitLoad(ArmEmitterContext context, Operand address, Extension ext, int rt, int size)
        {
            bool isSimd = IsSimd(context);

            if ((uint)size > (isSimd ? 4 : 3))
            {
                throw new ArgumentOutOfRangeException(nameof(size));
            }

            if (isSimd)
            {
                EmitReadVector(context, address, context.VectorZero(), rt, 0, size);
            }
            else
            {
                EmitReadInt(context, address, rt, size);
            }

            if (!isSimd && !(context.CurrOp is OpCode32 && rt == State.RegisterAlias.Aarch32Pc))
            {
                Operand value = GetInt(context, rt);

                if (ext == Extension.Sx32 || ext == Extension.Sx64)
                {
                    OperandType destType = ext == Extension.Sx64 ? OperandType.I64 : OperandType.I32;

                    switch (size)
                    {
                        case 0: value = context.SignExtend8 (destType, value); break;
                        case 1: value = context.SignExtend16(destType, value); break;
                        case 2: value = context.SignExtend32(destType, value); break;
                    }
                }

                SetInt(context, rt, value);
            }
        }

        public static void EmitLoadSimd(
            ArmEmitterContext context,
            Operand address,
            Operand vector,
            int rt,
            int elem,
            int size)
        {
            EmitReadVector(context, address, vector, rt, elem, size);
        }

        public static void EmitStore(ArmEmitterContext context, Operand address, int rt, int size)
        {
            bool isSimd = IsSimd(context);

            if ((uint)size > (isSimd ? 4 : 3))
            {
                throw new ArgumentOutOfRangeException(nameof(size));
            }

            if (isSimd)
            {
                EmitWriteVector(context, address, rt, 0, size);
            }
            else
            {
                EmitWriteInt(context, address, rt, size);
            }
        }

        public static void EmitStoreSimd(
            ArmEmitterContext context,
            Operand address,
            int rt,
            int elem,
            int size)
        {
            EmitWriteVector(context, address, rt, elem, size);
        }

        private static bool IsSimd(ArmEmitterContext context)
        {
            return context.CurrOp is IOpCodeSimd &&
                 !(context.CurrOp is OpCodeSimdMemMs ||
                   context.CurrOp is OpCodeSimdMemSs);
        }

        public static Operand EmitReadInt(ArmEmitterContext context, Operand address, int size)
        {
            Operand temp = context.AllocateLocal(size == 3 ? OperandType.I64 : OperandType.I32);

            Operand lblSlowPath = Label();
            Operand lblEnd      = Label();

            Operand physAddr = EmitPtPointerLoad(context, address, lblSlowPath, write: false, size);

            Operand value = default;

            switch (size)
            {
                case 0: value = context.Load8 (physAddr);                  break;
                case 1: value = context.Load16(physAddr);                  break;
                case 2: value = context.Load  (OperandType.I32, physAddr); break;
                case 3: value = context.Load  (OperandType.I64, physAddr); break;
            }

            context.Copy(temp, value);

            if (!context.Memory.Type.IsHostMapped())
            {
                context.Branch(lblEnd);

                context.MarkLabel(lblSlowPath, BasicBlockFrequency.Cold);

                context.Copy(temp, EmitReadIntFallback(context, address, size));

                context.MarkLabel(lblEnd);
            }

            return temp;
        }

        private static void EmitReadInt(ArmEmitterContext context, Operand address, int rt, int size)
        {
            Operand lblSlowPath = Label();
            Operand lblEnd      = Label();

            Operand physAddr = EmitPtPointerLoad(context, address, lblSlowPath, write: false, size);

            Operand value = default;

            switch (size)
            {
                case 0: value = context.Load8 (physAddr);                  break;
                case 1: value = context.Load16(physAddr);                  break;
                case 2: value = context.Load  (OperandType.I32, physAddr); break;
                case 3: value = context.Load  (OperandType.I64, physAddr); break;
            }

            SetInt(context, rt, value);

            if (!context.Memory.Type.IsHostMapped())
            {
                context.Branch(lblEnd);

                context.MarkLabel(lblSlowPath, BasicBlockFrequency.Cold);

                EmitReadIntFallback(context, address, rt, size);

                context.MarkLabel(lblEnd);
            }
        }

        public static Operand EmitReadIntAligned(ArmEmitterContext context, Operand address, int size)
        {
            if ((uint)size > 4)
            {
                throw new ArgumentOutOfRangeException(nameof(size));
            }

            Operand physAddr = EmitPtPointerLoad(context, address, default, write: false, size);

            return size switch
            {
                0 => context.Load8(physAddr),
                1 => context.Load16(physAddr),
                2 => context.Load(OperandType.I32, physAddr),
                3 => context.Load(OperandType.I64, physAddr),
                _ => context.Load(OperandType.V128, physAddr)
            };
        }

        private static void EmitReadVector(
            ArmEmitterContext context,
            Operand address,
            Operand vector,
            int rt,
            int elem,
            int size)
        {
            Operand lblSlowPath = Label();
            Operand lblEnd      = Label();

            Operand physAddr = EmitPtPointerLoad(context, address, lblSlowPath, write: false, size);

            Operand value = default;

            switch (size)
            {
                case 0: value = context.VectorInsert8 (vector, context.Load8(physAddr), elem);                 break;
                case 1: value = context.VectorInsert16(vector, context.Load16(physAddr), elem);                break;
                case 2: value = context.VectorInsert  (vector, context.Load(OperandType.I32, physAddr), elem); break;
                case 3: value = context.VectorInsert  (vector, context.Load(OperandType.I64, physAddr), elem); break;
                case 4: value = context.Load          (OperandType.V128, physAddr);                            break;
            }

            context.Copy(GetVec(rt), value);

            if (!context.Memory.Type.IsHostMapped())
            {
                context.Branch(lblEnd);

                context.MarkLabel(lblSlowPath, BasicBlockFrequency.Cold);

                EmitReadVectorFallback(context, address, vector, rt, elem, size);

                context.MarkLabel(lblEnd);
            }
        }

        private static Operand VectorCreate(ArmEmitterContext context, Operand value)
        {
            return context.VectorInsert(context.VectorZero(), value, 0);
        }

        private static void EmitWriteInt(ArmEmitterContext context, Operand address, int rt, int size)
        {
            Operand lblSlowPath = Label();
            Operand lblEnd      = Label();

            Operand physAddr = EmitPtPointerLoad(context, address, lblSlowPath, write: true, size);

            Operand value = GetInt(context, rt);

            if (size < 3 && value.Type == OperandType.I64)
            {
                value = context.ConvertI64ToI32(value);
            }

            switch (size)
            {
                case 0: context.Store8 (physAddr, value); break;
                case 1: context.Store16(physAddr, value); break;
                case 2: context.Store  (physAddr, value); break;
                case 3: context.Store  (physAddr, value); break;
            }

            if (!context.Memory.Type.IsHostMapped())
            {
                context.Branch(lblEnd);

                context.MarkLabel(lblSlowPath, BasicBlockFrequency.Cold);

                EmitWriteIntFallback(context, address, rt, size);

                context.MarkLabel(lblEnd);
            }
        }

        public static void EmitWriteIntAligned(ArmEmitterContext context, Operand address, Operand value, int size)
        {
            if ((uint)size > 4)
            {
                throw new ArgumentOutOfRangeException(nameof(size));
            }

            Operand physAddr = EmitPtPointerLoad(context, address, default, write: true, size);

            if (size < 3 && value.Type == OperandType.I64)
            {
                value = context.ConvertI64ToI32(value);
            }

            if (size == 0)
            {
                context.Store8(physAddr, value);
            }
            else if (size == 1)
            {
                context.Store16(physAddr, value);
            }
            else
            {
                context.Store(physAddr, value);
            }
        }

        private static void EmitWriteVector(
            ArmEmitterContext context,
            Operand address,
            int rt,
            int elem,
            int size)
        {
            Operand lblSlowPath = Label();
            Operand lblEnd      = Label();

            Operand physAddr = EmitPtPointerLoad(context, address, lblSlowPath, write: true, size);

            Operand value = GetVec(rt);

            switch (size)
            {
                case 0: context.Store8 (physAddr, context.VectorExtract8(value, elem));                 break;
                case 1: context.Store16(physAddr, context.VectorExtract16(value, elem));                break;
                case 2: context.Store  (physAddr, context.VectorExtract(OperandType.I32, value, elem)); break;
                case 3: context.Store  (physAddr, context.VectorExtract(OperandType.I64, value, elem)); break;
                case 4: context.Store  (physAddr, value);                                               break;
            }

            if (!context.Memory.Type.IsHostMapped())
            {
                context.Branch(lblEnd);

                context.MarkLabel(lblSlowPath, BasicBlockFrequency.Cold);

                EmitWriteVectorFallback(context, address, rt, elem, size);

                context.MarkLabel(lblEnd);
            }
        }

        public static Operand EmitPtPointerLoad(ArmEmitterContext context, Operand address, Operand lblSlowPath, bool write, int size)
        {
            if (context.Memory.Type.IsHostMapped())
            {
                return EmitHostMappedPointer(context, address);
            }

            int ptLevelBits = context.Memory.AddressSpaceBits - PageBits;
            int ptLevelSize = 1 << ptLevelBits;
            int ptLevelMask = ptLevelSize - 1;

            Operand addrRotated = size != 0 ? context.RotateRight(address, Const(size)) : address;
            Operand addrShifted = context.ShiftRightUI(addrRotated, Const(PageBits - size));

            Operand pte = !context.HasPtc
                ? Const(context.Memory.PageTablePointer.ToInt64())
                : Const(context.Memory.PageTablePointer.ToInt64(), Ptc.PageTableSymbol);

            Operand pteOffset = context.BitwiseAnd(addrShifted, Const(addrShifted.Type, ptLevelMask));

            if (pteOffset.Type == OperandType.I32)
            {
                pteOffset = context.ZeroExtend32(OperandType.I64, pteOffset);
            }

            pte = context.Load(OperandType.I64, context.Add(pte, context.ShiftLeft(pteOffset, Const(3))));

            if (addrShifted.Type == OperandType.I32)
            {
                addrShifted = context.ZeroExtend32(OperandType.I64, addrShifted);
            }

            // If the VA is out of range, or not aligned to the access size, force PTE to 0 by masking it.
            pte = context.BitwiseAnd(pte, context.ShiftRightSI(context.Add(addrShifted, Const(-(long)ptLevelSize)), Const(63)));

            if (lblSlowPath != default)
            {
                if (write)
                {
                    context.BranchIf(lblSlowPath, pte, Const(0L), Comparison.LessOrEqual);
                    pte = context.BitwiseAnd(pte, Const(0xffffffffffffUL)); // Ignore any software protection bits. (they are still used by C# memory access)
                }
                else
                {
                    pte = context.ShiftLeft(pte, Const(1));
                    context.BranchIf(lblSlowPath, pte, Const(0L), Comparison.LessOrEqual);
                    pte = context.ShiftRightUI(pte, Const(1));
                }
            }
            else
            {
                // When no label is provided to jump to a slow path if the address is invalid,
                // we do the validation ourselves, and throw if needed.

                Operand lblNotWatched = Label();

                // Is the page currently being tracked for read/write? If so we need to call SignalMemoryTracking.
                context.BranchIf(lblNotWatched, pte, Const(0L), Comparison.GreaterOrEqual, BasicBlockFrequency.Cold);

                // Signal memory tracking. Size here doesn't matter as address is assumed to be size aligned here.
                context.Call(typeof(NativeInterface).GetMethod(nameof(NativeInterface.SignalMemoryTracking)), address, Const(1UL), Const(write ? 1 : 0));
                context.MarkLabel(lblNotWatched);

                pte = context.BitwiseAnd(pte, Const(0xffffffffffffUL)); // Ignore any software protection bits. (they are still used by C# memory access)

                Operand lblNonNull = Label();

                // Skip exception if the PTE address is non-null (not zero).
                context.BranchIfTrue(lblNonNull, pte, BasicBlockFrequency.Cold);

                // The call is not expected to return (it should throw).
                context.Call(typeof(NativeInterface).GetMethod(nameof(NativeInterface.ThrowInvalidMemoryAccess)), address);
                context.MarkLabel(lblNonNull);
            }

            Operand pageOffset = context.BitwiseAnd(address, Const(address.Type, PageMask));

            if (pageOffset.Type == OperandType.I32)
            {
                pageOffset = context.ZeroExtend32(OperandType.I64, pageOffset);
            }

            return context.Add(pte, pageOffset);
        }

        public static Operand EmitHostMappedPointer(ArmEmitterContext context, Operand address)
        {
            if (address.Type == OperandType.I32)
            {
                address = context.ZeroExtend32(OperandType.I64, address);
            }

            if (context.Memory.Type == MemoryManagerType.HostMapped)
            {
                Operand mask = Const(ulong.MaxValue >> (64 - context.Memory.AddressSpaceBits));
                address = context.BitwiseAnd(address, mask);
            }

            Operand baseAddr = !context.HasPtc
                ? Const(context.Memory.PageTablePointer.ToInt64())
                : Const(context.Memory.PageTablePointer.ToInt64(), Ptc.PageTableSymbol);

            return context.Add(baseAddr, address);
        }

        private static void EmitReadIntFallback(ArmEmitterContext context, Operand address, int rt, int size)
        {
            SetInt(context, rt, EmitReadIntFallback(context, address, size));
        }

        private static Operand EmitReadIntFallback(ArmEmitterContext context, Operand address, int size)
        {
            MethodInfo info = null;

            switch (size)
            {
                case 0: info = typeof(NativeInterface).GetMethod(nameof(NativeInterface.ReadByte));   break;
                case 1: info = typeof(NativeInterface).GetMethod(nameof(NativeInterface.ReadUInt16)); break;
                case 2: info = typeof(NativeInterface).GetMethod(nameof(NativeInterface.ReadUInt32)); break;
                case 3: info = typeof(NativeInterface).GetMethod(nameof(NativeInterface.ReadUInt64)); break;
            }

            return context.Call(info, address);
        }

        private static void EmitReadVectorFallback(
            ArmEmitterContext context,
            Operand address,
            Operand vector,
            int rt,
            int elem,
            int size)
        {
            MethodInfo info = null;

            switch (size)
            {
                case 0: info = typeof(NativeInterface).GetMethod(nameof(NativeInterface.ReadByte));      break;
                case 1: info = typeof(NativeInterface).GetMethod(nameof(NativeInterface.ReadUInt16));    break;
                case 2: info = typeof(NativeInterface).GetMethod(nameof(NativeInterface.ReadUInt32));    break;
                case 3: info = typeof(NativeInterface).GetMethod(nameof(NativeInterface.ReadUInt64));    break;
                case 4: info = typeof(NativeInterface).GetMethod(nameof(NativeInterface.ReadVector128)); break;
            }

            Operand value = context.Call(info, address);

            switch (size)
            {
                case 0: value = context.VectorInsert8 (vector, value, elem); break;
                case 1: value = context.VectorInsert16(vector, value, elem); break;
                case 2: value = context.VectorInsert  (vector, value, elem); break;
                case 3: value = context.VectorInsert  (vector, value, elem); break;
            }

            context.Copy(GetVec(rt), value);
        }

        private static void EmitWriteIntFallback(ArmEmitterContext context, Operand address, int rt, int size)
        {
            MethodInfo info = null;

            switch (size)
            {
                case 0: info = typeof(NativeInterface).GetMethod(nameof(NativeInterface.WriteByte));   break;
                case 1: info = typeof(NativeInterface).GetMethod(nameof(NativeInterface.WriteUInt16)); break;
                case 2: info = typeof(NativeInterface).GetMethod(nameof(NativeInterface.WriteUInt32)); break;
                case 3: info = typeof(NativeInterface).GetMethod(nameof(NativeInterface.WriteUInt64)); break;
            }

            Operand value = GetInt(context, rt);

            if (size < 3 && value.Type == OperandType.I64)
            {
                value = context.ConvertI64ToI32(value);
            }

            context.Call(info, address, value);
        }

        private static void EmitWriteVectorFallback(
            ArmEmitterContext context,
            Operand address,
            int rt,
            int elem,
            int size)
        {
            MethodInfo info = null;

            switch (size)
            {
                case 0: info = typeof(NativeInterface).GetMethod(nameof(NativeInterface.WriteByte));      break;
                case 1: info = typeof(NativeInterface).GetMethod(nameof(NativeInterface.WriteUInt16));    break;
                case 2: info = typeof(NativeInterface).GetMethod(nameof(NativeInterface.WriteUInt32));    break;
                case 3: info = typeof(NativeInterface).GetMethod(nameof(NativeInterface.WriteUInt64));    break;
                case 4: info = typeof(NativeInterface).GetMethod(nameof(NativeInterface.WriteVector128)); break;
            }

            Operand value = default;

            if (size < 4)
            {
                switch (size)
                {
                    case 0: value = context.VectorExtract8 (GetVec(rt), elem);                  break;
                    case 1: value = context.VectorExtract16(GetVec(rt), elem);                  break;
                    case 2: value = context.VectorExtract  (OperandType.I32, GetVec(rt), elem); break;
                    case 3: value = context.VectorExtract  (OperandType.I64, GetVec(rt), elem); break;
                }
            }
            else
            {
                value = GetVec(rt);
            }

            context.Call(info, address, value);
        }

        private static Operand GetInt(ArmEmitterContext context, int rt)
        {
            return context.CurrOp is OpCode32 ? GetIntA32(context, rt) : GetIntOrZR(context, rt);
        }

        private static void SetInt(ArmEmitterContext context, int rt, Operand value)
        {
            if (context.CurrOp is OpCode32)
            {
                SetIntA32(context, rt, value);
            }
            else
            {
                SetIntOrZR(context, rt, value);
            }
        }

        // ARM32 helpers.
        public static Operand GetMemM(ArmEmitterContext context, bool setCarry = true)
        {
            switch (context.CurrOp)
            {
                case IOpCode32MemRsImm op: return GetMShiftedByImmediate(context, op, setCarry);

                case IOpCode32MemReg op: return GetIntA32(context, op.Rm);

                case IOpCode32Mem op: return Const(op.Immediate);

                case OpCode32SimdMemImm op: return Const(op.Immediate);

                default: throw InvalidOpCodeType(context.CurrOp);
            }
        }

        private static Exception InvalidOpCodeType(OpCode opCode)
        {
            return new InvalidOperationException($"Invalid OpCode type \"{opCode?.GetType().Name ?? "null"}\".");
        }

        public static Operand GetMShiftedByImmediate(ArmEmitterContext context, IOpCode32MemRsImm op, bool setCarry)
        {
            Operand m = GetIntA32(context, op.Rm);

            int shift = op.Immediate;

            if (shift == 0)
            {
                switch (op.ShiftType)
                {
                    case ShiftType.Lsr: shift = 32; break;
                    case ShiftType.Asr: shift = 32; break;
                    case ShiftType.Ror: shift = 1; break;
                }
            }

            if (shift != 0)
            {
                setCarry &= false;

                switch (op.ShiftType)
                {
                    case ShiftType.Lsl: m = InstEmitAluHelper.GetLslC(context, m, setCarry, shift); break;
                    case ShiftType.Lsr: m = InstEmitAluHelper.GetLsrC(context, m, setCarry, shift); break;
                    case ShiftType.Asr: m = InstEmitAluHelper.GetAsrC(context, m, setCarry, shift); break;
                    case ShiftType.Ror:
                        if (op.Immediate != 0)
                        {
                            m = InstEmitAluHelper.GetRorC(context, m, setCarry, shift);
                        }
                        else
                        {
                            m = InstEmitAluHelper.GetRrxC(context, m, setCarry);
                        }
                        break;
                }
            }

            return m;
        }
    }
}