forked from dotnet/runtime
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcodegenarm.cpp
2749 lines (2347 loc) · 98.4 KB
/
codegenarm.cpp
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
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/*XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XX XX
XX ARM Code Generator XX
XX XX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
*/
#include "jitpch.h"
#ifdef _MSC_VER
#pragma hdrstop
#endif
#ifdef TARGET_ARM
#include "codegen.h"
#include "lower.h"
#include "gcinfo.h"
#include "emit.h"
//------------------------------------------------------------------------
// genInstrWithConstant: We will typically generate one instruction
//
// ins reg1, reg2, imm
//
// However the imm might not fit as a directly encodable immediate.
// When it doesn't fit we generate extra instruction(s) that sets up
// the 'regTmp' with the proper immediate value.
//
// mov regTmp, imm
// ins reg1, reg2, regTmp
//
// Generally, codegen constants are marked non-containable if they don't fit. This function
// is used for cases that aren't mirrored in the IR, such as in the prolog.
//
// Arguments:
// ins - instruction
// attr - operation size and GC attribute
// reg1, reg2 - first and second register operands
// imm - immediate value (third operand when it fits)
// flags - whether flags are set
// tmpReg - temp register to use when the 'imm' doesn't fit. Can be REG_NA
// if caller knows for certain the constant will fit.
//
// Return Value:
// returns true if the immediate was small enough to be encoded inside instruction. If not,
// returns false meaning the immediate was too large and tmpReg was used and modified.
//
bool CodeGen::genInstrWithConstant(
instruction ins, emitAttr attr, regNumber reg1, regNumber reg2, ssize_t imm, insFlags flags, regNumber tmpReg)
{
bool immFitsInIns = false;
// reg1 is usually a dest register
// reg2 is always source register
assert(tmpReg != reg2); // regTmp cannot match any source register
switch (ins)
{
case INS_add:
case INS_sub:
immFitsInIns = validImmForInstr(ins, (target_ssize_t)imm, flags);
break;
default:
assert(!"Unexpected instruction in genInstrWithConstant");
break;
}
if (immFitsInIns)
{
// generate a single instruction that encodes the immediate directly
GetEmitter()->emitIns_R_R_I(ins, attr, reg1, reg2, (target_ssize_t)imm);
}
else
{
// caller can specify REG_NA for tmpReg, when it "knows" that the immediate will always fit
assert(tmpReg != REG_NA);
// generate two or more instructions
// first we load the immediate into tmpReg
instGen_Set_Reg_To_Imm(EA_PTRSIZE, tmpReg, imm);
// generate the instruction using a three register encoding with the immediate in tmpReg
GetEmitter()->emitIns_R_R_R(ins, attr, reg1, reg2, tmpReg);
}
return immFitsInIns;
}
//------------------------------------------------------------------------
// genStackPointerAdjustment: add a specified constant value to the stack pointer.
// An available temporary register is required to be specified, in case the constant
// is too large to encode in an "add" instruction (or "sub" instruction if we choose
// to use one), such that we need to load the constant into a register first, before using it.
//
// Arguments:
// spDelta - the value to add to SP (can be negative)
// tmpReg - an available temporary register
//
// Return Value:
// returns true if the immediate was small enough to be encoded inside instruction. If not,
// returns false meaning the immediate was too large and tmpReg was used and modified.
//
bool CodeGen::genStackPointerAdjustment(ssize_t spDelta, regNumber tmpReg)
{
// Even though INS_add is specified here, the encoder will choose either
// an INS_add or an INS_sub and encode the immediate as a positive value
//
return genInstrWithConstant(INS_add, EA_PTRSIZE, REG_SPBASE, REG_SPBASE, spDelta, INS_FLAGS_DONT_CARE, tmpReg);
}
//------------------------------------------------------------------------
// genCallFinally: Generate a call to the finally block.
//
BasicBlock* CodeGen::genCallFinally(BasicBlock* block)
{
BasicBlock* bbFinallyRet = nullptr;
// We don't have retless calls, since we use the BBJ_ALWAYS to point at a NOP pad where
// we would have otherwise created retless calls.
assert(block->isBBCallAlwaysPair());
assert(block->bbNext != NULL);
assert(block->bbNext->bbJumpKind == BBJ_ALWAYS);
assert(block->bbNext->bbJumpDest != NULL);
assert(block->bbNext->bbJumpDest->bbFlags & BBF_FINALLY_TARGET);
bbFinallyRet = block->bbNext->bbJumpDest;
// Load the address where the finally funclet should return into LR.
// The funclet prolog/epilog will do "push {lr}" / "pop {pc}" to do the return.
genMov32RelocatableDisplacement(bbFinallyRet, REG_LR);
// Jump to the finally BB
inst_JMP(EJ_jmp, block->bbJumpDest);
// The BBJ_ALWAYS is used because the BBJ_CALLFINALLY can't point to the
// jump target using bbJumpDest - that is already used to point
// to the finally block. So just skip past the BBJ_ALWAYS unless the
// block is RETLESS.
assert(!(block->bbFlags & BBF_RETLESS_CALL));
assert(block->isBBCallAlwaysPair());
return block->bbNext;
}
//------------------------------------------------------------------------
// genEHCatchRet:
void CodeGen::genEHCatchRet(BasicBlock* block)
{
genMov32RelocatableDisplacement(block->bbJumpDest, REG_INTRET);
}
//------------------------------------------------------------------------
// instGen_Set_Reg_To_Imm: Move an immediate value into an integer register.
//
void CodeGen::instGen_Set_Reg_To_Imm(emitAttr size,
regNumber reg,
ssize_t imm,
insFlags flags DEBUGARG(size_t targetHandle) DEBUGARG(GenTreeFlags gtFlags))
{
// reg cannot be a FP register
assert(!genIsValidFloatReg(reg));
if (!compiler->opts.compReloc)
{
size = EA_SIZE(size); // Strip any Reloc flags from size if we aren't doing relocs
}
if (EA_IS_RELOC(size))
{
// TODO-CrossBitness: we wouldn't need the cast below if we had CodeGen::instGen_Set_Reg_To_Reloc_Imm.
genMov32RelocatableImmediate(size, (BYTE*)imm, reg);
}
else if (imm == 0)
{
instGen_Set_Reg_To_Zero(size, reg, flags);
}
else
{
// TODO-CrossBitness: we wouldn't need the cast below if we had CodeGen::instGen_Set_Reg_To_Reloc_Imm.
const int val32 = (int)imm;
if (validImmForMov(val32))
{
GetEmitter()->emitIns_R_I(INS_mov, size, reg, val32, flags);
}
else // We have to use a movw/movt pair of instructions
{
const int imm_lo16 = val32 & 0xffff;
const int imm_hi16 = (val32 >> 16) & 0xffff;
assert(validImmForMov(imm_lo16));
assert(imm_hi16 != 0);
GetEmitter()->emitIns_R_I(INS_movw, size, reg, imm_lo16);
// If we've got a low register, the high word is all bits set,
// and the high bit of the low word is set, we can sign extend
// halfword and save two bytes of encoding. This can happen for
// small magnitude negative numbers 'n' for -32768 <= n <= -1.
if (GetEmitter()->isLowRegister(reg) && (imm_hi16 == 0xffff) && ((imm_lo16 & 0x8000) == 0x8000))
{
GetEmitter()->emitIns_Mov(INS_sxth, EA_4BYTE, reg, reg, /* canSkip */ false);
}
else
{
GetEmitter()->emitIns_R_I(INS_movt, size, reg, imm_hi16);
}
if (flags == INS_FLAGS_SET)
GetEmitter()->emitIns_Mov(INS_mov, size, reg, reg, /* canSkip */ false, INS_FLAGS_SET);
}
}
regSet.verifyRegUsed(reg);
}
//------------------------------------------------------------------------
// genSetRegToConst: Generate code to set a register 'targetReg' of type 'targetType'
// to the constant specified by the constant (GT_CNS_INT or GT_CNS_DBL) in 'tree'.
//
// Notes:
// This does not call genProduceReg() on the target register.
//
void CodeGen::genSetRegToConst(regNumber targetReg, var_types targetType, GenTree* tree)
{
switch (tree->gtOper)
{
case GT_CNS_INT:
{
// relocatable values tend to come down as a CNS_INT of native int type
// so the line between these two opcodes is kind of blurry
GenTreeIntConCommon* con = tree->AsIntConCommon();
ssize_t cnsVal = con->IconValue();
emitAttr attr = emitActualTypeSize(targetType);
// TODO-CQ: Currently we cannot do this for all handles because of
// https://github.com/dotnet/runtime/issues/60712
if (con->ImmedValNeedsReloc(compiler))
{
attr = EA_SET_FLG(attr, EA_CNS_RELOC_FLG);
}
if (targetType == TYP_BYREF)
{
attr = EA_SET_FLG(attr, EA_BYREF_FLG);
}
instGen_Set_Reg_To_Imm(attr, targetReg, cnsVal);
regSet.verifyRegUsed(targetReg);
}
break;
case GT_CNS_DBL:
{
GenTreeDblCon* dblConst = tree->AsDblCon();
double constValue = dblConst->AsDblCon()->DconValue();
// TODO-ARM-CQ: Do we have a faster/smaller way to generate 0.0 in thumb2 ISA ?
if (targetType == TYP_FLOAT)
{
// Get a temp integer register
regNumber tmpReg = tree->GetSingleTempReg();
float f = forceCastToFloat(constValue);
instGen_Set_Reg_To_Imm(EA_4BYTE, tmpReg, *((int*)(&f)));
GetEmitter()->emitIns_Mov(INS_vmov_i2f, EA_4BYTE, targetReg, tmpReg, /* canSkip */ false);
}
else
{
assert(targetType == TYP_DOUBLE);
unsigned* cv = (unsigned*)&constValue;
// Get two temp integer registers
regNumber tmpReg1 = tree->ExtractTempReg();
regNumber tmpReg2 = tree->GetSingleTempReg();
instGen_Set_Reg_To_Imm(EA_4BYTE, tmpReg1, cv[0]);
instGen_Set_Reg_To_Imm(EA_4BYTE, tmpReg2, cv[1]);
GetEmitter()->emitIns_R_R_R(INS_vmov_i2d, EA_8BYTE, targetReg, tmpReg1, tmpReg2);
}
}
break;
case GT_CNS_VEC:
{
unreached();
}
default:
unreached();
}
}
//------------------------------------------------------------------------
// genCodeForBinary: Generate code for many binary arithmetic operators
// This method is expected to have called genConsumeOperands() before calling it.
//
// Arguments:
// treeNode - The binary operation for which we are generating code.
//
// Return Value:
// None.
//
// Notes:
// Mul and div are not handled here.
// See the assert below for the operators that are handled.
void CodeGen::genCodeForBinary(GenTreeOp* treeNode)
{
const genTreeOps oper = treeNode->OperGet();
regNumber targetReg = treeNode->GetRegNum();
var_types targetType = treeNode->TypeGet();
emitter* emit = GetEmitter();
assert(treeNode->OperIs(GT_ADD, GT_SUB, GT_MUL, GT_ADD_LO, GT_ADD_HI, GT_SUB_LO, GT_SUB_HI, GT_OR, GT_XOR, GT_AND,
GT_AND_NOT));
GenTree* op1 = treeNode->gtGetOp1();
GenTree* op2 = treeNode->gtGetOp2();
instruction ins = genGetInsForOper(oper, targetType);
// The arithmetic node must be sitting in a register (since it's not contained)
noway_assert(targetReg != REG_NA);
if ((oper == GT_ADD_LO || oper == GT_SUB_LO))
{
// During decomposition, all operands become reg
assert(!op1->isContained() && !op2->isContained());
emit->emitIns_R_R_R(ins, emitTypeSize(treeNode), treeNode->GetRegNum(), op1->GetRegNum(), op2->GetRegNum(),
INS_FLAGS_SET);
}
else
{
regNumber r = emit->emitInsTernary(ins, emitTypeSize(treeNode), treeNode, op1, op2);
assert(r == targetReg);
}
genProduceReg(treeNode);
}
//--------------------------------------------------------------------------------------
// genLclHeap: Generate code for localloc
//
// Description:
// There are 2 ways depending from build version to generate code for localloc:
// 1) For debug build where memory should be initialized we generate loop
// which invoke push {tmpReg} N times.
// 2) For non-debug build, we tickle the pages to ensure that SP is always
// valid and is in sync with the "stack guard page". Amount of iteration
// is N/eeGetPageSize().
//
// Comments:
// There can be some optimization:
// 1) It's not needed to generate loop for zero size allocation
// 2) For small allocation (less than 4 store) we unroll loop
// 3) For allocation less than eeGetPageSize() and when it's not needed to initialize
// memory to zero, we can just decrement SP.
//
// Notes: Size N should be aligned to STACK_ALIGN before any allocation
//
void CodeGen::genLclHeap(GenTree* tree)
{
assert(tree->OperGet() == GT_LCLHEAP);
assert(compiler->compLocallocUsed);
GenTree* size = tree->AsOp()->gtOp1;
noway_assert((genActualType(size->gtType) == TYP_INT) || (genActualType(size->gtType) == TYP_I_IMPL));
// Result of localloc will be returned in regCnt.
// Also it used as temporary register in code generation
// for storing allocation size
regNumber regCnt = tree->GetRegNum();
var_types type = genActualType(size->gtType);
emitAttr easz = emitTypeSize(type);
BasicBlock* endLabel = nullptr;
unsigned stackAdjustment = 0;
regNumber regTmp = REG_NA;
const target_ssize_t ILLEGAL_LAST_TOUCH_DELTA = (target_ssize_t)-1;
target_ssize_t lastTouchDelta =
ILLEGAL_LAST_TOUCH_DELTA; // The number of bytes from SP to the last stack address probed.
noway_assert(isFramePointerUsed()); // localloc requires Frame Pointer to be established since SP changes
noway_assert(genStackLevel == 0); // Can't have anything on the stack
// Check to 0 size allocations
// size_t amount = 0;
if (size->IsCnsIntOrI())
{
// If size is a constant, then it must be contained.
assert(size->isContained());
// If amount is zero then return null in regCnt
size_t amount = size->AsIntCon()->gtIconVal;
if (amount == 0)
{
instGen_Set_Reg_To_Zero(EA_PTRSIZE, regCnt);
goto BAILOUT;
}
}
else
{
// If 0 bail out by returning null in regCnt
genConsumeRegAndCopy(size, regCnt);
endLabel = genCreateTempLabel();
GetEmitter()->emitIns_R_R(INS_TEST, easz, regCnt, regCnt);
inst_JMP(EJ_eq, endLabel);
}
// Setup the regTmp, if there is one.
if (tree->AvailableTempRegCount() > 0)
{
regTmp = tree->ExtractTempReg();
}
// If we have an outgoing arg area then we must adjust the SP by popping off the
// outgoing arg area. We will restore it right before we return from this method.
if (compiler->lvaOutgoingArgSpaceSize > 0)
{
// This must be true for the stack to remain aligned
assert((compiler->lvaOutgoingArgSpaceSize % STACK_ALIGN) == 0);
// We're guaranteed (by LinearScan::BuildLclHeap()) to have a legal regTmp if we need one.
genStackPointerAdjustment(compiler->lvaOutgoingArgSpaceSize, regTmp);
stackAdjustment += compiler->lvaOutgoingArgSpaceSize;
}
// Put aligned allocation size to regCnt
if (size->IsCnsIntOrI())
{
// 'amount' is the total number of bytes to localloc to properly STACK_ALIGN
target_size_t amount = (target_size_t)size->AsIntCon()->gtIconVal;
amount = AlignUp(amount, STACK_ALIGN);
// For small allocations we will generate up to four push instructions (either 2 or 4, exactly,
// since STACK_ALIGN is 8, and REGSIZE_BYTES is 4).
static_assert_no_msg(STACK_ALIGN == (REGSIZE_BYTES * 2));
assert(amount % REGSIZE_BYTES == 0);
target_size_t pushCount = amount / REGSIZE_BYTES;
if (pushCount <= 4)
{
instGen_Set_Reg_To_Zero(EA_PTRSIZE, regCnt);
while (pushCount != 0)
{
inst_IV(INS_push, (unsigned)genRegMask(regCnt));
pushCount -= 1;
}
lastTouchDelta = 0;
goto ALLOC_DONE;
}
else if (!compiler->info.compInitMem && (amount < compiler->eeGetPageSize())) // must be < not <=
{
// Since the size is less than a page, simply adjust the SP value.
// The SP might already be in the guard page, must touch it BEFORE
// the alloc, not after.
GetEmitter()->emitIns_R_R_I(INS_ldr, EA_4BYTE, regCnt, REG_SP, 0);
inst_RV_IV(INS_sub, REG_SP, amount, EA_PTRSIZE);
lastTouchDelta = amount;
goto ALLOC_DONE;
}
// regCnt will be the total number of bytes to locAlloc
instGen_Set_Reg_To_Imm(EA_4BYTE, regCnt, amount);
}
else
{
// Round up the number of bytes to allocate to a STACK_ALIGN boundary.
inst_RV_IV(INS_add, regCnt, (STACK_ALIGN - 1), emitActualTypeSize(type));
inst_RV_IV(INS_AND, regCnt, ~(STACK_ALIGN - 1), emitActualTypeSize(type));
}
// Allocation
if (compiler->info.compInitMem)
{
// At this point 'regCnt' is set to the total number of bytes to localloc.
// Since we have to zero out the allocated memory AND ensure that the stack pointer is always valid
// by tickling the pages, we will just push 0's on the stack.
instGen_Set_Reg_To_Zero(EA_PTRSIZE, regTmp);
// Loop:
BasicBlock* loop = genCreateTempLabel();
genDefineTempLabel(loop);
noway_assert(STACK_ALIGN == 8);
inst_IV(INS_push, (unsigned)genRegMask(regTmp));
inst_IV(INS_push, (unsigned)genRegMask(regTmp));
// If not done, loop
// Note that regCnt is the number of bytes to stack allocate.
assert(genIsValidIntReg(regCnt));
GetEmitter()->emitIns_R_I(INS_sub, EA_PTRSIZE, regCnt, STACK_ALIGN, INS_FLAGS_SET);
inst_JMP(EJ_ne, loop);
lastTouchDelta = 0;
}
else
{
// At this point 'regCnt' is set to the total number of bytes to locAlloc.
//
// We don't need to zero out the allocated memory. However, we do have
// to tickle the pages to ensure that SP is always valid and is
// in sync with the "stack guard page". Note that in the worst
// case SP is on the last byte of the guard page. Thus you must
// touch SP-0 first not SP-0x1000.
//
// Another subtlety is that you don't want SP to be exactly on the
// boundary of the guard page because PUSH is predecrement, thus
// call setup would not touch the guard page but just beyond it
//
// Note that we go through a few hoops so that SP never points to
// illegal pages at any time during the tickling process
//
// subs regCnt, SP, regCnt // regCnt now holds ultimate SP
// bvc Loop // result is smaller than original SP (no wrap around)
// mov regCnt, #0 // Overflow, pick lowest possible value
//
// Loop:
// ldr regTmp, [SP + 0] // tickle the page - read from the page
// sub regTmp, SP, PAGE_SIZE // decrement SP by eeGetPageSize()
// cmp regTmp, regCnt
// jb Done
// mov SP, regTmp
// j Loop
//
// Done:
// mov SP, regCnt
//
BasicBlock* loop = genCreateTempLabel();
BasicBlock* done = genCreateTempLabel();
// subs regCnt, SP, regCnt // regCnt now holds ultimate SP
GetEmitter()->emitIns_R_R_R(INS_sub, EA_PTRSIZE, regCnt, REG_SPBASE, regCnt, INS_FLAGS_SET);
inst_JMP(EJ_vc, loop); // branch if the V flag is not set
// Overflow, set regCnt to lowest possible value
instGen_Set_Reg_To_Zero(EA_PTRSIZE, regCnt);
genDefineTempLabel(loop);
// tickle the page - Read from the updated SP - this triggers a page fault when on the guard page
GetEmitter()->emitIns_R_R_I(INS_ldr, EA_4BYTE, regTmp, REG_SPBASE, 0);
// decrement SP by eeGetPageSize()
GetEmitter()->emitIns_R_R_I(INS_sub, EA_PTRSIZE, regTmp, REG_SPBASE, compiler->eeGetPageSize());
GetEmitter()->emitIns_R_R(INS_cmp, EA_PTRSIZE, regTmp, regCnt);
inst_JMP(EJ_lo, done);
// Update SP to be at the next page of stack that we will tickle
GetEmitter()->emitIns_Mov(INS_mov, EA_PTRSIZE, REG_SPBASE, regTmp, /* canSkip */ false);
// Jump to loop and tickle new stack address
inst_JMP(EJ_jmp, loop);
// Done with stack tickle loop
genDefineTempLabel(done);
// Now just move the final value to SP
GetEmitter()->emitIns_Mov(INS_mov, EA_PTRSIZE, REG_SPBASE, regCnt, /* canSkip */ false);
// lastTouchDelta is dynamic, and can be up to a page. So if we have outgoing arg space,
// we're going to assume the worst and probe.
}
ALLOC_DONE:
// Re-adjust SP to allocate outgoing arg area. We must probe this adjustment.
if (stackAdjustment != 0)
{
assert((stackAdjustment % STACK_ALIGN) == 0); // This must be true for the stack to remain aligned
assert((lastTouchDelta == ILLEGAL_LAST_TOUCH_DELTA) || (lastTouchDelta >= 0));
if ((lastTouchDelta == ILLEGAL_LAST_TOUCH_DELTA) ||
(stackAdjustment + (unsigned)lastTouchDelta + STACK_PROBE_BOUNDARY_THRESHOLD_BYTES >
compiler->eeGetPageSize()))
{
genStackPointerConstantAdjustmentLoopWithProbe(-(ssize_t)stackAdjustment, regTmp);
}
else
{
genStackPointerConstantAdjustment(-(ssize_t)stackAdjustment, regTmp);
}
// Return the stackalloc'ed address in result register.
// regCnt = SP + stackAdjustment.
genInstrWithConstant(INS_add, EA_PTRSIZE, regCnt, REG_SPBASE, (ssize_t)stackAdjustment, INS_FLAGS_DONT_CARE,
regTmp);
}
else // stackAdjustment == 0
{
// Move the final value of SP to regCnt
inst_Mov(TYP_I_IMPL, regCnt, REG_SPBASE, /* canSkip */ false);
}
BAILOUT:
if (endLabel != nullptr)
genDefineTempLabel(endLabel);
genProduceReg(tree);
}
//------------------------------------------------------------------------
// genTableBasedSwitch: generate code for a switch statement based on a table of ip-relative offsets
//
void CodeGen::genTableBasedSwitch(GenTree* treeNode)
{
genConsumeOperands(treeNode->AsOp());
regNumber idxReg = treeNode->AsOp()->gtOp1->GetRegNum();
regNumber baseReg = treeNode->AsOp()->gtOp2->GetRegNum();
GetEmitter()->emitIns_R_ARX(INS_ldr, EA_4BYTE, REG_PC, baseReg, idxReg, TARGET_POINTER_SIZE, 0);
}
//------------------------------------------------------------------------
// genJumpTable: emits the table and an instruction to get the address of the first element
//
void CodeGen::genJumpTable(GenTree* treeNode)
{
noway_assert(compiler->compCurBB->bbJumpKind == BBJ_SWITCH);
assert(treeNode->OperGet() == GT_JMPTABLE);
unsigned jumpCount = compiler->compCurBB->bbJumpSwt->bbsCount;
BasicBlock** jumpTable = compiler->compCurBB->bbJumpSwt->bbsDstTab;
unsigned jmpTabBase;
jmpTabBase = GetEmitter()->emitBBTableDataGenBeg(jumpCount, false);
JITDUMP("\n J_M%03u_DS%02u LABEL DWORD\n", compiler->compMethodID, jmpTabBase);
for (unsigned i = 0; i < jumpCount; i++)
{
BasicBlock* target = *jumpTable++;
noway_assert(target->bbFlags & BBF_HAS_LABEL);
JITDUMP(" DD L_M%03u_" FMT_BB "\n", compiler->compMethodID, target->bbNum);
GetEmitter()->emitDataGenData(i, target);
}
GetEmitter()->emitDataGenEnd();
genMov32RelocatableDataLabel(jmpTabBase, treeNode->GetRegNum());
genProduceReg(treeNode);
}
//------------------------------------------------------------------------
// genGetInsForOper: Return instruction encoding of the operation tree.
//
instruction CodeGen::genGetInsForOper(genTreeOps oper, var_types type)
{
instruction ins;
if (varTypeIsFloating(type))
return CodeGen::ins_MathOp(oper, type);
switch (oper)
{
case GT_ADD:
ins = INS_add;
break;
case GT_AND:
ins = INS_AND;
break;
case GT_AND_NOT:
ins = INS_bic;
break;
case GT_MUL:
ins = INS_MUL;
break;
#if !defined(USE_HELPERS_FOR_INT_DIV)
case GT_DIV:
ins = INS_sdiv;
break;
#endif // !USE_HELPERS_FOR_INT_DIV
case GT_LSH:
ins = INS_SHIFT_LEFT_LOGICAL;
break;
case GT_NEG:
ins = INS_rsb;
break;
case GT_NOT:
ins = INS_NOT;
break;
case GT_OR:
ins = INS_OR;
break;
case GT_RSH:
ins = INS_SHIFT_RIGHT_ARITHM;
break;
case GT_RSZ:
ins = INS_SHIFT_RIGHT_LOGICAL;
break;
case GT_SUB:
ins = INS_sub;
break;
case GT_XOR:
ins = INS_XOR;
break;
case GT_ROR:
ins = INS_ror;
break;
case GT_ADD_LO:
ins = INS_add;
break;
case GT_ADD_HI:
ins = INS_adc;
break;
case GT_SUB_LO:
ins = INS_sub;
break;
case GT_SUB_HI:
ins = INS_sbc;
break;
case GT_LSH_HI:
ins = INS_SHIFT_LEFT_LOGICAL;
break;
case GT_RSH_LO:
ins = INS_SHIFT_RIGHT_LOGICAL;
break;
default:
unreached();
break;
}
return ins;
}
//------------------------------------------------------------------------
// genCodeForNegNot: Produce code for a GT_NEG/GT_NOT node.
//
// Arguments:
// tree - the node
//
void CodeGen::genCodeForNegNot(GenTree* tree)
{
assert(tree->OperIs(GT_NEG, GT_NOT));
var_types targetType = tree->TypeGet();
assert(!tree->OperIs(GT_NOT) || !varTypeIsFloating(targetType));
regNumber targetReg = tree->GetRegNum();
instruction ins = genGetInsForOper(tree->OperGet(), targetType);
// The arithmetic node must be sitting in a register (since it's not contained)
assert(!tree->isContained());
// The dst can only be a register.
assert(targetReg != REG_NA);
GenTree* operand = tree->gtGetOp1();
assert(!operand->isContained());
// The src must be a register.
regNumber operandReg = genConsumeReg(operand);
if (ins == INS_vneg)
{
GetEmitter()->emitIns_R_R(ins, emitTypeSize(tree), targetReg, operandReg);
}
else
{
GetEmitter()->emitIns_R_R_I(ins, emitTypeSize(tree), targetReg, operandReg, 0, INS_FLAGS_SET);
}
genProduceReg(tree);
}
// Generate code for CpObj nodes which copy structs that have interleaved
// GC pointers.
// For this case we'll generate a sequence of loads/stores in the case of struct
// slots that don't contain GC pointers. The generated code will look like:
// ldr tempReg, [R13, #8]
// str tempReg, [R14, #8]
//
// In the case of a GC-Pointer we'll call the ByRef write barrier helper
// who happens to use the same registers as the previous call to maintain
// the same register requirements and register killsets:
// bl CORINFO_HELP_ASSIGN_BYREF
//
// So finally an example would look like this:
// ldr tempReg, [R13, #8]
// str tempReg, [R14, #8]
// bl CORINFO_HELP_ASSIGN_BYREF
// ldr tempReg, [R13, #8]
// str tempReg, [R14, #8]
// bl CORINFO_HELP_ASSIGN_BYREF
// ldr tempReg, [R13, #8]
// str tempReg, [R14, #8]
void CodeGen::genCodeForCpObj(GenTreeBlk* cpObjNode)
{
GenTree* dstAddr = cpObjNode->Addr();
GenTree* source = cpObjNode->Data();
var_types srcAddrType = TYP_BYREF;
bool sourceIsLocal = false;
regNumber dstReg = REG_NA;
regNumber srcReg = REG_NA;
assert(source->isContained());
if (source->gtOper == GT_IND)
{
GenTree* srcAddr = source->gtGetOp1();
assert(!srcAddr->isContained());
srcAddrType = srcAddr->TypeGet();
}
else
{
noway_assert(source->IsLocal());
sourceIsLocal = true;
}
#ifdef DEBUG
assert(!dstAddr->isContained());
// This GenTree node has data about GC pointers, this means we're dealing
// with CpObj.
assert(cpObjNode->GetLayout()->HasGCPtr());
#endif // DEBUG
// Consume the operands and get them into the right registers.
// They may now contain gc pointers (depending on their type; gcMarkRegPtrVal will "do the right thing").
genConsumeBlockOp(cpObjNode, REG_WRITE_BARRIER_DST_BYREF, REG_WRITE_BARRIER_SRC_BYREF, REG_NA);
gcInfo.gcMarkRegPtrVal(REG_WRITE_BARRIER_SRC_BYREF, srcAddrType);
gcInfo.gcMarkRegPtrVal(REG_WRITE_BARRIER_DST_BYREF, dstAddr->TypeGet());
// Temp register used to perform the sequence of loads and stores.
regNumber tmpReg = cpObjNode->ExtractTempReg();
assert(genIsValidIntReg(tmpReg));
if (cpObjNode->IsVolatile())
{
// issue a full memory barrier before & after a volatile CpObj operation
instGen_MemoryBarrier();
}
emitter* emit = GetEmitter();
ClassLayout* layout = cpObjNode->GetLayout();
unsigned slots = layout->GetSlotCount();
// If we can prove it's on the stack we don't need to use the write barrier.
if (dstAddr->gtSkipReloadOrCopy()->OperIs(GT_LCL_ADDR) || layout->HasGCByRef())
{
for (unsigned i = 0; i < slots; ++i)
{
emitAttr attr = emitTypeSize(layout->GetGCPtrType(i));
emit->emitIns_R_R_I(INS_ldr, attr, tmpReg, REG_WRITE_BARRIER_SRC_BYREF, TARGET_POINTER_SIZE,
INS_FLAGS_DONT_CARE, INS_OPTS_LDST_POST_INC);
emit->emitIns_R_R_I(INS_str, attr, tmpReg, REG_WRITE_BARRIER_DST_BYREF, TARGET_POINTER_SIZE,
INS_FLAGS_DONT_CARE, INS_OPTS_LDST_POST_INC);
}
}
else
{
unsigned i = 0;
while (i < slots)
{
if (!layout->IsGCRef(i))
{
emit->emitIns_R_R_I(INS_ldr, EA_PTRSIZE, tmpReg, REG_WRITE_BARRIER_SRC_BYREF, TARGET_POINTER_SIZE,
INS_FLAGS_DONT_CARE, INS_OPTS_LDST_POST_INC);
emit->emitIns_R_R_I(INS_str, EA_PTRSIZE, tmpReg, REG_WRITE_BARRIER_DST_BYREF, TARGET_POINTER_SIZE,
INS_FLAGS_DONT_CARE, INS_OPTS_LDST_POST_INC);
}
else
{
genEmitHelperCall(CORINFO_HELP_ASSIGN_BYREF, 0, EA_PTRSIZE);
}
++i;
}
}
if (cpObjNode->IsVolatile())
{
// issue a full memory barrier before & after a volatile CpObj operation
instGen_MemoryBarrier();
}
// Clear the gcInfo for registers of source and dest.
// While we normally update GC info prior to the last instruction that uses them,
// these actually live into the helper call.
gcInfo.gcMarkRegSetNpt(RBM_WRITE_BARRIER_SRC_BYREF | RBM_WRITE_BARRIER_DST_BYREF);
}
//------------------------------------------------------------------------
// genCodeForShiftLong: Generates the code sequence for a GenTree node that
// represents a three operand bit shift or rotate operation (<<Hi, >>Lo).
//
// Arguments:
// tree - the bit shift node (that specifies the type of bit shift to perform).
//
// Assumptions:
// a) All GenTrees are register allocated.
// b) The shift-by-amount in tree->AsOp()->gtOp2 is a contained constant
//
void CodeGen::genCodeForShiftLong(GenTree* tree)
{
// Only the non-RMW case here.
genTreeOps oper = tree->OperGet();
assert(oper == GT_LSH_HI || oper == GT_RSH_LO);
GenTree* operand = tree->AsOp()->gtOp1;
assert(operand->OperGet() == GT_LONG);
assert(operand->AsOp()->gtOp1->isUsedFromReg());
assert(operand->AsOp()->gtOp2->isUsedFromReg());
GenTree* operandLo = operand->gtGetOp1();
GenTree* operandHi = operand->gtGetOp2();
regNumber regLo = operandLo->GetRegNum();
regNumber regHi = operandHi->GetRegNum();
genConsumeOperands(tree->AsOp());
var_types targetType = tree->TypeGet();
instruction ins = genGetInsForOper(oper, targetType);
GenTree* shiftBy = tree->gtGetOp2();
assert(shiftBy->isContainedIntOrIImmed());
unsigned count = (unsigned)shiftBy->AsIntConCommon()->IconValue();
regNumber regResult = (oper == GT_LSH_HI) ? regHi : regLo;
inst_Mov(targetType, tree->GetRegNum(), regResult, /* canSkip */ true);
if (oper == GT_LSH_HI)
{
inst_RV_SH(ins, EA_4BYTE, tree->GetRegNum(), count);
GetEmitter()->emitIns_R_R_R_I(INS_OR, EA_4BYTE, tree->GetRegNum(), tree->GetRegNum(), regLo, 32 - count,
INS_FLAGS_DONT_CARE, INS_OPTS_LSR);
}
else
{
assert(oper == GT_RSH_LO);
inst_RV_SH(INS_SHIFT_RIGHT_LOGICAL, EA_4BYTE, tree->GetRegNum(), count);
GetEmitter()->emitIns_R_R_R_I(INS_OR, EA_4BYTE, tree->GetRegNum(), tree->GetRegNum(), regHi, 32 - count,
INS_FLAGS_DONT_CARE, INS_OPTS_LSL);
}
genProduceReg(tree);
}
//------------------------------------------------------------------------
// genCodeForLclVar: Produce code for a GT_LCL_VAR node.
//
// Arguments:
// tree - the GT_LCL_VAR node
//
void CodeGen::genCodeForLclVar(GenTreeLclVar* tree)
{
// lcl_vars are not defs
assert((tree->gtFlags & GTF_VAR_DEF) == 0);
bool isRegCandidate = compiler->lvaGetDesc(tree)->lvIsRegCandidate();
// If this is a register candidate that has been spilled, genConsumeReg() will
// reload it at the point of use. Otherwise, if it's not in a register, we load it here.
if (!isRegCandidate && !tree->IsMultiReg() && !(tree->gtFlags & GTF_SPILLED))
{
const LclVarDsc* varDsc = compiler->lvaGetDesc(tree);
var_types type = varDsc->GetRegisterType(tree);
GetEmitter()->emitIns_R_S(ins_Load(type), emitTypeSize(type), tree->GetRegNum(), tree->GetLclNum(), 0);
genProduceReg(tree);
}
}
//------------------------------------------------------------------------
// genCodeForStoreLclFld: Produce code for a GT_STORE_LCL_FLD node.
//
// Arguments:
// tree - the GT_STORE_LCL_FLD node
//
void CodeGen::genCodeForStoreLclFld(GenTreeLclFld* tree)
{
var_types targetType = tree->TypeGet();
regNumber targetReg = tree->GetRegNum();
emitter* emit = GetEmitter();
noway_assert(targetType != TYP_STRUCT);
// record the offset
unsigned offset = tree->GetLclOffs();