forked from llvm/llvm-project
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPPCFrameLowering.cpp
2700 lines (2400 loc) · 103 KB
/
PPCFrameLowering.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
//===-- PPCFrameLowering.cpp - PPC Frame Information ----------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file contains the PPC implementation of TargetFrameLowering class.
//
//===----------------------------------------------------------------------===//
#include "MCTargetDesc/PPCPredicates.h"
#include "PPCFrameLowering.h"
#include "PPCInstrBuilder.h"
#include "PPCInstrInfo.h"
#include "PPCMachineFunctionInfo.h"
#include "PPCSubtarget.h"
#include "PPCTargetMachine.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/CodeGen/MachineFrameInfo.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/MachineInstrBuilder.h"
#include "llvm/CodeGen/MachineModuleInfo.h"
#include "llvm/CodeGen/MachineRegisterInfo.h"
#include "llvm/CodeGen/RegisterScavenging.h"
#include "llvm/IR/Function.h"
#include "llvm/Target/TargetOptions.h"
using namespace llvm;
#define DEBUG_TYPE "framelowering"
STATISTIC(NumPESpillVSR, "Number of spills to vector in prologue");
STATISTIC(NumPEReloadVSR, "Number of reloads from vector in epilogue");
STATISTIC(NumPrologProbed, "Number of prologues probed");
static cl::opt<bool>
EnablePEVectorSpills("ppc-enable-pe-vector-spills",
cl::desc("Enable spills in prologue to vector registers."),
cl::init(false), cl::Hidden);
static unsigned computeReturnSaveOffset(const PPCSubtarget &STI) {
if (STI.isAIXABI())
return STI.isPPC64() ? 16 : 8;
// SVR4 ABI:
return STI.isPPC64() ? 16 : 4;
}
static unsigned computeTOCSaveOffset(const PPCSubtarget &STI) {
if (STI.isAIXABI())
return STI.isPPC64() ? 40 : 20;
return STI.isELFv2ABI() ? 24 : 40;
}
static unsigned computeFramePointerSaveOffset(const PPCSubtarget &STI) {
// First slot in the general register save area.
return STI.isPPC64() ? -8U : -4U;
}
static unsigned computeLinkageSize(const PPCSubtarget &STI) {
if (STI.isAIXABI() || STI.isPPC64())
return (STI.isELFv2ABI() ? 4 : 6) * (STI.isPPC64() ? 8 : 4);
// 32-bit SVR4 ABI:
return 8;
}
static unsigned computeBasePointerSaveOffset(const PPCSubtarget &STI) {
// Third slot in the general purpose register save area.
if (STI.is32BitELFABI() && STI.getTargetMachine().isPositionIndependent())
return -12U;
// Second slot in the general purpose register save area.
return STI.isPPC64() ? -16U : -8U;
}
static unsigned computeCRSaveOffset(const PPCSubtarget &STI) {
return (STI.isAIXABI() && !STI.isPPC64()) ? 4 : 8;
}
PPCFrameLowering::PPCFrameLowering(const PPCSubtarget &STI)
: TargetFrameLowering(TargetFrameLowering::StackGrowsDown,
STI.getPlatformStackAlignment(), 0),
Subtarget(STI), ReturnSaveOffset(computeReturnSaveOffset(Subtarget)),
TOCSaveOffset(computeTOCSaveOffset(Subtarget)),
FramePointerSaveOffset(computeFramePointerSaveOffset(Subtarget)),
LinkageSize(computeLinkageSize(Subtarget)),
BasePointerSaveOffset(computeBasePointerSaveOffset(Subtarget)),
CRSaveOffset(computeCRSaveOffset(Subtarget)) {}
// With the SVR4 ABI, callee-saved registers have fixed offsets on the stack.
const PPCFrameLowering::SpillSlot *PPCFrameLowering::getCalleeSavedSpillSlots(
unsigned &NumEntries) const {
// Floating-point register save area offsets.
#define CALLEE_SAVED_FPRS \
{PPC::F31, -8}, \
{PPC::F30, -16}, \
{PPC::F29, -24}, \
{PPC::F28, -32}, \
{PPC::F27, -40}, \
{PPC::F26, -48}, \
{PPC::F25, -56}, \
{PPC::F24, -64}, \
{PPC::F23, -72}, \
{PPC::F22, -80}, \
{PPC::F21, -88}, \
{PPC::F20, -96}, \
{PPC::F19, -104}, \
{PPC::F18, -112}, \
{PPC::F17, -120}, \
{PPC::F16, -128}, \
{PPC::F15, -136}, \
{PPC::F14, -144}
// 32-bit general purpose register save area offsets shared by ELF and
// AIX. AIX has an extra CSR with r13.
#define CALLEE_SAVED_GPRS32 \
{PPC::R31, -4}, \
{PPC::R30, -8}, \
{PPC::R29, -12}, \
{PPC::R28, -16}, \
{PPC::R27, -20}, \
{PPC::R26, -24}, \
{PPC::R25, -28}, \
{PPC::R24, -32}, \
{PPC::R23, -36}, \
{PPC::R22, -40}, \
{PPC::R21, -44}, \
{PPC::R20, -48}, \
{PPC::R19, -52}, \
{PPC::R18, -56}, \
{PPC::R17, -60}, \
{PPC::R16, -64}, \
{PPC::R15, -68}, \
{PPC::R14, -72}
// 64-bit general purpose register save area offsets.
#define CALLEE_SAVED_GPRS64 \
{PPC::X31, -8}, \
{PPC::X30, -16}, \
{PPC::X29, -24}, \
{PPC::X28, -32}, \
{PPC::X27, -40}, \
{PPC::X26, -48}, \
{PPC::X25, -56}, \
{PPC::X24, -64}, \
{PPC::X23, -72}, \
{PPC::X22, -80}, \
{PPC::X21, -88}, \
{PPC::X20, -96}, \
{PPC::X19, -104}, \
{PPC::X18, -112}, \
{PPC::X17, -120}, \
{PPC::X16, -128}, \
{PPC::X15, -136}, \
{PPC::X14, -144}
// Vector register save area offsets.
#define CALLEE_SAVED_VRS \
{PPC::V31, -16}, \
{PPC::V30, -32}, \
{PPC::V29, -48}, \
{PPC::V28, -64}, \
{PPC::V27, -80}, \
{PPC::V26, -96}, \
{PPC::V25, -112}, \
{PPC::V24, -128}, \
{PPC::V23, -144}, \
{PPC::V22, -160}, \
{PPC::V21, -176}, \
{PPC::V20, -192}
// Note that the offsets here overlap, but this is fixed up in
// processFunctionBeforeFrameFinalized.
static const SpillSlot ELFOffsets32[] = {
CALLEE_SAVED_FPRS,
CALLEE_SAVED_GPRS32,
// CR save area offset. We map each of the nonvolatile CR fields
// to the slot for CR2, which is the first of the nonvolatile CR
// fields to be assigned, so that we only allocate one save slot.
// See PPCRegisterInfo::hasReservedSpillSlot() for more information.
{PPC::CR2, -4},
// VRSAVE save area offset.
{PPC::VRSAVE, -4},
CALLEE_SAVED_VRS,
// SPE register save area (overlaps Vector save area).
{PPC::S31, -8},
{PPC::S30, -16},
{PPC::S29, -24},
{PPC::S28, -32},
{PPC::S27, -40},
{PPC::S26, -48},
{PPC::S25, -56},
{PPC::S24, -64},
{PPC::S23, -72},
{PPC::S22, -80},
{PPC::S21, -88},
{PPC::S20, -96},
{PPC::S19, -104},
{PPC::S18, -112},
{PPC::S17, -120},
{PPC::S16, -128},
{PPC::S15, -136},
{PPC::S14, -144}};
static const SpillSlot ELFOffsets64[] = {
CALLEE_SAVED_FPRS,
CALLEE_SAVED_GPRS64,
// VRSAVE save area offset.
{PPC::VRSAVE, -4},
CALLEE_SAVED_VRS
};
static const SpillSlot AIXOffsets32[] = {CALLEE_SAVED_FPRS,
CALLEE_SAVED_GPRS32,
// Add AIX's extra CSR.
{PPC::R13, -76},
CALLEE_SAVED_VRS};
static const SpillSlot AIXOffsets64[] = {
CALLEE_SAVED_FPRS, CALLEE_SAVED_GPRS64, CALLEE_SAVED_VRS};
if (Subtarget.is64BitELFABI()) {
NumEntries = array_lengthof(ELFOffsets64);
return ELFOffsets64;
}
if (Subtarget.is32BitELFABI()) {
NumEntries = array_lengthof(ELFOffsets32);
return ELFOffsets32;
}
assert(Subtarget.isAIXABI() && "Unexpected ABI.");
if (Subtarget.isPPC64()) {
NumEntries = array_lengthof(AIXOffsets64);
return AIXOffsets64;
}
NumEntries = array_lengthof(AIXOffsets32);
return AIXOffsets32;
}
static bool spillsCR(const MachineFunction &MF) {
const PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
return FuncInfo->isCRSpilled();
}
static bool hasSpills(const MachineFunction &MF) {
const PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
return FuncInfo->hasSpills();
}
static bool hasNonRISpills(const MachineFunction &MF) {
const PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
return FuncInfo->hasNonRISpills();
}
/// MustSaveLR - Return true if this function requires that we save the LR
/// register onto the stack in the prolog and restore it in the epilog of the
/// function.
static bool MustSaveLR(const MachineFunction &MF, unsigned LR) {
const PPCFunctionInfo *MFI = MF.getInfo<PPCFunctionInfo>();
// We need a save/restore of LR if there is any def of LR (which is
// defined by calls, including the PIC setup sequence), or if there is
// some use of the LR stack slot (e.g. for builtin_return_address).
// (LR comes in 32 and 64 bit versions.)
MachineRegisterInfo::def_iterator RI = MF.getRegInfo().def_begin(LR);
return RI !=MF.getRegInfo().def_end() || MFI->isLRStoreRequired();
}
/// determineFrameLayoutAndUpdate - Determine the size of the frame and maximum
/// call frame size. Update the MachineFunction object with the stack size.
uint64_t
PPCFrameLowering::determineFrameLayoutAndUpdate(MachineFunction &MF,
bool UseEstimate) const {
unsigned NewMaxCallFrameSize = 0;
uint64_t FrameSize = determineFrameLayout(MF, UseEstimate,
&NewMaxCallFrameSize);
MF.getFrameInfo().setStackSize(FrameSize);
MF.getFrameInfo().setMaxCallFrameSize(NewMaxCallFrameSize);
return FrameSize;
}
/// determineFrameLayout - Determine the size of the frame and maximum call
/// frame size.
uint64_t
PPCFrameLowering::determineFrameLayout(const MachineFunction &MF,
bool UseEstimate,
unsigned *NewMaxCallFrameSize) const {
const MachineFrameInfo &MFI = MF.getFrameInfo();
const PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
// Get the number of bytes to allocate from the FrameInfo
uint64_t FrameSize =
UseEstimate ? MFI.estimateStackSize(MF) : MFI.getStackSize();
// Get stack alignments. The frame must be aligned to the greatest of these:
Align TargetAlign = getStackAlign(); // alignment required per the ABI
Align MaxAlign = MFI.getMaxAlign(); // algmt required by data in frame
Align Alignment = std::max(TargetAlign, MaxAlign);
const PPCRegisterInfo *RegInfo = Subtarget.getRegisterInfo();
unsigned LR = RegInfo->getRARegister();
bool DisableRedZone = MF.getFunction().hasFnAttribute(Attribute::NoRedZone);
bool CanUseRedZone = !MFI.hasVarSizedObjects() && // No dynamic alloca.
!MFI.adjustsStack() && // No calls.
!MustSaveLR(MF, LR) && // No need to save LR.
!FI->mustSaveTOC() && // No need to save TOC.
!RegInfo->hasBasePointer(MF); // No special alignment.
// Note: for PPC32 SVR4ABI, we can still generate stackless
// code if all local vars are reg-allocated.
bool FitsInRedZone = FrameSize <= Subtarget.getRedZoneSize();
// Check whether we can skip adjusting the stack pointer (by using red zone)
if (!DisableRedZone && CanUseRedZone && FitsInRedZone) {
// No need for frame
return 0;
}
// Get the maximum call frame size of all the calls.
unsigned maxCallFrameSize = MFI.getMaxCallFrameSize();
// Maximum call frame needs to be at least big enough for linkage area.
unsigned minCallFrameSize = getLinkageSize();
maxCallFrameSize = std::max(maxCallFrameSize, minCallFrameSize);
// If we have dynamic alloca then maxCallFrameSize needs to be aligned so
// that allocations will be aligned.
if (MFI.hasVarSizedObjects())
maxCallFrameSize = alignTo(maxCallFrameSize, Alignment);
// Update the new max call frame size if the caller passes in a valid pointer.
if (NewMaxCallFrameSize)
*NewMaxCallFrameSize = maxCallFrameSize;
// Include call frame size in total.
FrameSize += maxCallFrameSize;
// Make sure the frame is aligned.
FrameSize = alignTo(FrameSize, Alignment);
return FrameSize;
}
// hasFP - Return true if the specified function actually has a dedicated frame
// pointer register.
bool PPCFrameLowering::hasFP(const MachineFunction &MF) const {
const MachineFrameInfo &MFI = MF.getFrameInfo();
// FIXME: This is pretty much broken by design: hasFP() might be called really
// early, before the stack layout was calculated and thus hasFP() might return
// true or false here depending on the time of call.
return (MFI.getStackSize()) && needsFP(MF);
}
// needsFP - Return true if the specified function should have a dedicated frame
// pointer register. This is true if the function has variable sized allocas or
// if frame pointer elimination is disabled.
bool PPCFrameLowering::needsFP(const MachineFunction &MF) const {
const MachineFrameInfo &MFI = MF.getFrameInfo();
// Naked functions have no stack frame pushed, so we don't have a frame
// pointer.
if (MF.getFunction().hasFnAttribute(Attribute::Naked))
return false;
return MF.getTarget().Options.DisableFramePointerElim(MF) ||
MFI.hasVarSizedObjects() || MFI.hasStackMap() || MFI.hasPatchPoint() ||
MF.exposesReturnsTwice() ||
(MF.getTarget().Options.GuaranteedTailCallOpt &&
MF.getInfo<PPCFunctionInfo>()->hasFastCall());
}
void PPCFrameLowering::replaceFPWithRealFP(MachineFunction &MF) const {
bool is31 = needsFP(MF);
unsigned FPReg = is31 ? PPC::R31 : PPC::R1;
unsigned FP8Reg = is31 ? PPC::X31 : PPC::X1;
const PPCRegisterInfo *RegInfo = Subtarget.getRegisterInfo();
bool HasBP = RegInfo->hasBasePointer(MF);
unsigned BPReg = HasBP ? (unsigned) RegInfo->getBaseRegister(MF) : FPReg;
unsigned BP8Reg = HasBP ? (unsigned) PPC::X30 : FP8Reg;
for (MachineBasicBlock &MBB : MF)
for (MachineBasicBlock::iterator MBBI = MBB.end(); MBBI != MBB.begin();) {
--MBBI;
for (unsigned I = 0, E = MBBI->getNumOperands(); I != E; ++I) {
MachineOperand &MO = MBBI->getOperand(I);
if (!MO.isReg())
continue;
switch (MO.getReg()) {
case PPC::FP:
MO.setReg(FPReg);
break;
case PPC::FP8:
MO.setReg(FP8Reg);
break;
case PPC::BP:
MO.setReg(BPReg);
break;
case PPC::BP8:
MO.setReg(BP8Reg);
break;
}
}
}
}
/* This function will do the following:
- If MBB is an entry or exit block, set SR1 and SR2 to R0 and R12
respectively (defaults recommended by the ABI) and return true
- If MBB is not an entry block, initialize the register scavenger and look
for available registers.
- If the defaults (R0/R12) are available, return true
- If TwoUniqueRegsRequired is set to true, it looks for two unique
registers. Otherwise, look for a single available register.
- If the required registers are found, set SR1 and SR2 and return true.
- If the required registers are not found, set SR2 or both SR1 and SR2 to
PPC::NoRegister and return false.
Note that if both SR1 and SR2 are valid parameters and TwoUniqueRegsRequired
is not set, this function will attempt to find two different registers, but
still return true if only one register is available (and set SR1 == SR2).
*/
bool
PPCFrameLowering::findScratchRegister(MachineBasicBlock *MBB,
bool UseAtEnd,
bool TwoUniqueRegsRequired,
Register *SR1,
Register *SR2) const {
RegScavenger RS;
Register R0 = Subtarget.isPPC64() ? PPC::X0 : PPC::R0;
Register R12 = Subtarget.isPPC64() ? PPC::X12 : PPC::R12;
// Set the defaults for the two scratch registers.
if (SR1)
*SR1 = R0;
if (SR2) {
assert (SR1 && "Asking for the second scratch register but not the first?");
*SR2 = R12;
}
// If MBB is an entry or exit block, use R0 and R12 as the scratch registers.
if ((UseAtEnd && MBB->isReturnBlock()) ||
(!UseAtEnd && (&MBB->getParent()->front() == MBB)))
return true;
RS.enterBasicBlock(*MBB);
if (UseAtEnd && !MBB->empty()) {
// The scratch register will be used at the end of the block, so must
// consider all registers used within the block
MachineBasicBlock::iterator MBBI = MBB->getFirstTerminator();
// If no terminator, back iterator up to previous instruction.
if (MBBI == MBB->end())
MBBI = std::prev(MBBI);
if (MBBI != MBB->begin())
RS.forward(MBBI);
}
// If the two registers are available, we're all good.
// Note that we only return here if both R0 and R12 are available because
// although the function may not require two unique registers, it may benefit
// from having two so we should try to provide them.
if (!RS.isRegUsed(R0) && !RS.isRegUsed(R12))
return true;
// Get the list of callee-saved registers for the target.
const PPCRegisterInfo *RegInfo = Subtarget.getRegisterInfo();
const MCPhysReg *CSRegs = RegInfo->getCalleeSavedRegs(MBB->getParent());
// Get all the available registers in the block.
BitVector BV = RS.getRegsAvailable(Subtarget.isPPC64() ? &PPC::G8RCRegClass :
&PPC::GPRCRegClass);
// We shouldn't use callee-saved registers as scratch registers as they may be
// available when looking for a candidate block for shrink wrapping but not
// available when the actual prologue/epilogue is being emitted because they
// were added as live-in to the prologue block by PrologueEpilogueInserter.
for (int i = 0; CSRegs[i]; ++i)
BV.reset(CSRegs[i]);
// Set the first scratch register to the first available one.
if (SR1) {
int FirstScratchReg = BV.find_first();
*SR1 = FirstScratchReg == -1 ? (unsigned)PPC::NoRegister : FirstScratchReg;
}
// If there is another one available, set the second scratch register to that.
// Otherwise, set it to either PPC::NoRegister if this function requires two
// or to whatever SR1 is set to if this function doesn't require two.
if (SR2) {
int SecondScratchReg = BV.find_next(*SR1);
if (SecondScratchReg != -1)
*SR2 = SecondScratchReg;
else
*SR2 = TwoUniqueRegsRequired ? Register() : *SR1;
}
// Now that we've done our best to provide both registers, double check
// whether we were unable to provide enough.
if (BV.count() < (TwoUniqueRegsRequired ? 2U : 1U))
return false;
return true;
}
// We need a scratch register for spilling LR and for spilling CR. By default,
// we use two scratch registers to hide latency. However, if only one scratch
// register is available, we can adjust for that by not overlapping the spill
// code. However, if we need to realign the stack (i.e. have a base pointer)
// and the stack frame is large, we need two scratch registers.
// Also, stack probe requires two scratch registers, one for old sp, one for
// large frame and large probe size.
bool
PPCFrameLowering::twoUniqueScratchRegsRequired(MachineBasicBlock *MBB) const {
const PPCRegisterInfo *RegInfo = Subtarget.getRegisterInfo();
MachineFunction &MF = *(MBB->getParent());
bool HasBP = RegInfo->hasBasePointer(MF);
unsigned FrameSize = determineFrameLayout(MF);
int NegFrameSize = -FrameSize;
bool IsLargeFrame = !isInt<16>(NegFrameSize);
MachineFrameInfo &MFI = MF.getFrameInfo();
Align MaxAlign = MFI.getMaxAlign();
bool HasRedZone = Subtarget.isPPC64() || !Subtarget.isSVR4ABI();
const PPCTargetLowering &TLI = *Subtarget.getTargetLowering();
return ((IsLargeFrame || !HasRedZone) && HasBP && MaxAlign > 1) ||
TLI.hasInlineStackProbe(MF);
}
bool PPCFrameLowering::canUseAsPrologue(const MachineBasicBlock &MBB) const {
MachineBasicBlock *TmpMBB = const_cast<MachineBasicBlock *>(&MBB);
return findScratchRegister(TmpMBB, false,
twoUniqueScratchRegsRequired(TmpMBB));
}
bool PPCFrameLowering::canUseAsEpilogue(const MachineBasicBlock &MBB) const {
MachineBasicBlock *TmpMBB = const_cast<MachineBasicBlock *>(&MBB);
return findScratchRegister(TmpMBB, true);
}
bool PPCFrameLowering::stackUpdateCanBeMoved(MachineFunction &MF) const {
const PPCRegisterInfo *RegInfo = Subtarget.getRegisterInfo();
PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
// Abort if there is no register info or function info.
if (!RegInfo || !FI)
return false;
// Only move the stack update on ELFv2 ABI and PPC64.
if (!Subtarget.isELFv2ABI() || !Subtarget.isPPC64())
return false;
// Check the frame size first and return false if it does not fit the
// requirements.
// We need a non-zero frame size as well as a frame that will fit in the red
// zone. This is because by moving the stack pointer update we are now storing
// to the red zone until the stack pointer is updated. If we get an interrupt
// inside the prologue but before the stack update we now have a number of
// stores to the red zone and those stores must all fit.
MachineFrameInfo &MFI = MF.getFrameInfo();
unsigned FrameSize = MFI.getStackSize();
if (!FrameSize || FrameSize > Subtarget.getRedZoneSize())
return false;
// Frame pointers and base pointers complicate matters so don't do anything
// if we have them. For example having a frame pointer will sometimes require
// a copy of r1 into r31 and that makes keeping track of updates to r1 more
// difficult. Similar situation exists with setjmp.
if (hasFP(MF) || RegInfo->hasBasePointer(MF) || MF.exposesReturnsTwice())
return false;
// Calls to fast_cc functions use different rules for passing parameters on
// the stack from the ABI and using PIC base in the function imposes
// similar restrictions to using the base pointer. It is not generally safe
// to move the stack pointer update in these situations.
if (FI->hasFastCall() || FI->usesPICBase())
return false;
// Finally we can move the stack update if we do not require register
// scavenging. Register scavenging can introduce more spills and so
// may make the frame size larger than we have computed.
return !RegInfo->requiresFrameIndexScavenging(MF);
}
void PPCFrameLowering::emitPrologue(MachineFunction &MF,
MachineBasicBlock &MBB) const {
MachineBasicBlock::iterator MBBI = MBB.begin();
MachineFrameInfo &MFI = MF.getFrameInfo();
const PPCInstrInfo &TII = *Subtarget.getInstrInfo();
const PPCRegisterInfo *RegInfo = Subtarget.getRegisterInfo();
const PPCTargetLowering &TLI = *Subtarget.getTargetLowering();
MachineModuleInfo &MMI = MF.getMMI();
const MCRegisterInfo *MRI = MMI.getContext().getRegisterInfo();
DebugLoc dl;
// AIX assembler does not support cfi directives.
const bool needsCFI = MF.needsFrameMoves() && !Subtarget.isAIXABI();
// Get processor type.
bool isPPC64 = Subtarget.isPPC64();
// Get the ABI.
bool isSVR4ABI = Subtarget.isSVR4ABI();
bool isELFv2ABI = Subtarget.isELFv2ABI();
assert((isSVR4ABI || Subtarget.isAIXABI()) && "Unsupported PPC ABI.");
// Work out frame sizes.
uint64_t FrameSize = determineFrameLayoutAndUpdate(MF);
int64_t NegFrameSize = -FrameSize;
if (!isInt<32>(FrameSize) || !isInt<32>(NegFrameSize))
llvm_unreachable("Unhandled stack size!");
if (MFI.isFrameAddressTaken())
replaceFPWithRealFP(MF);
// Check if the link register (LR) must be saved.
PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
bool MustSaveLR = FI->mustSaveLR();
bool MustSaveTOC = FI->mustSaveTOC();
const SmallVectorImpl<Register> &MustSaveCRs = FI->getMustSaveCRs();
bool MustSaveCR = !MustSaveCRs.empty();
// Do we have a frame pointer and/or base pointer for this function?
bool HasFP = hasFP(MF);
bool HasBP = RegInfo->hasBasePointer(MF);
bool HasRedZone = isPPC64 || !isSVR4ABI;
bool HasROPProtect = Subtarget.hasROPProtect();
bool HasPrivileged = Subtarget.hasPrivileged();
Register SPReg = isPPC64 ? PPC::X1 : PPC::R1;
Register BPReg = RegInfo->getBaseRegister(MF);
Register FPReg = isPPC64 ? PPC::X31 : PPC::R31;
Register LRReg = isPPC64 ? PPC::LR8 : PPC::LR;
Register TOCReg = isPPC64 ? PPC::X2 : PPC::R2;
Register ScratchReg;
Register TempReg = isPPC64 ? PPC::X12 : PPC::R12; // another scratch reg
// ...(R12/X12 is volatile in both Darwin & SVR4, & can't be a function arg.)
const MCInstrDesc& MFLRInst = TII.get(isPPC64 ? PPC::MFLR8
: PPC::MFLR );
const MCInstrDesc& StoreInst = TII.get(isPPC64 ? PPC::STD
: PPC::STW );
const MCInstrDesc& StoreUpdtInst = TII.get(isPPC64 ? PPC::STDU
: PPC::STWU );
const MCInstrDesc& StoreUpdtIdxInst = TII.get(isPPC64 ? PPC::STDUX
: PPC::STWUX);
const MCInstrDesc& LoadImmShiftedInst = TII.get(isPPC64 ? PPC::LIS8
: PPC::LIS );
const MCInstrDesc& OrImmInst = TII.get(isPPC64 ? PPC::ORI8
: PPC::ORI );
const MCInstrDesc& OrInst = TII.get(isPPC64 ? PPC::OR8
: PPC::OR );
const MCInstrDesc& SubtractCarryingInst = TII.get(isPPC64 ? PPC::SUBFC8
: PPC::SUBFC);
const MCInstrDesc& SubtractImmCarryingInst = TII.get(isPPC64 ? PPC::SUBFIC8
: PPC::SUBFIC);
const MCInstrDesc &MoveFromCondRegInst = TII.get(isPPC64 ? PPC::MFCR8
: PPC::MFCR);
const MCInstrDesc &StoreWordInst = TII.get(isPPC64 ? PPC::STW8 : PPC::STW);
const MCInstrDesc &HashST =
TII.get(isPPC64 ? (HasPrivileged ? PPC::HASHSTP8 : PPC::HASHST8)
: (HasPrivileged ? PPC::HASHSTP : PPC::HASHST));
// Regarding this assert: Even though LR is saved in the caller's frame (i.e.,
// LROffset is positive), that slot is callee-owned. Because PPC32 SVR4 has no
// Red Zone, an asynchronous event (a form of "callee") could claim a frame &
// overwrite it, so PPC32 SVR4 must claim at least a minimal frame to save LR.
assert((isPPC64 || !isSVR4ABI || !(!FrameSize && (MustSaveLR || HasFP))) &&
"FrameSize must be >0 to save/restore the FP or LR for 32-bit SVR4.");
// Using the same bool variable as below to suppress compiler warnings.
bool SingleScratchReg = findScratchRegister(
&MBB, false, twoUniqueScratchRegsRequired(&MBB), &ScratchReg, &TempReg);
assert(SingleScratchReg &&
"Required number of registers not available in this block");
SingleScratchReg = ScratchReg == TempReg;
int64_t LROffset = getReturnSaveOffset();
int64_t FPOffset = 0;
if (HasFP) {
MachineFrameInfo &MFI = MF.getFrameInfo();
int FPIndex = FI->getFramePointerSaveIndex();
assert(FPIndex && "No Frame Pointer Save Slot!");
FPOffset = MFI.getObjectOffset(FPIndex);
}
int64_t BPOffset = 0;
if (HasBP) {
MachineFrameInfo &MFI = MF.getFrameInfo();
int BPIndex = FI->getBasePointerSaveIndex();
assert(BPIndex && "No Base Pointer Save Slot!");
BPOffset = MFI.getObjectOffset(BPIndex);
}
int64_t PBPOffset = 0;
if (FI->usesPICBase()) {
MachineFrameInfo &MFI = MF.getFrameInfo();
int PBPIndex = FI->getPICBasePointerSaveIndex();
assert(PBPIndex && "No PIC Base Pointer Save Slot!");
PBPOffset = MFI.getObjectOffset(PBPIndex);
}
// Get stack alignments.
Align MaxAlign = MFI.getMaxAlign();
if (HasBP && MaxAlign > 1)
assert(Log2(MaxAlign) < 16 && "Invalid alignment!");
// Frames of 32KB & larger require special handling because they cannot be
// indexed into with a simple STDU/STWU/STD/STW immediate offset operand.
bool isLargeFrame = !isInt<16>(NegFrameSize);
// Check if we can move the stack update instruction (stdu) down the prologue
// past the callee saves. Hopefully this will avoid the situation where the
// saves are waiting for the update on the store with update to complete.
MachineBasicBlock::iterator StackUpdateLoc = MBBI;
bool MovingStackUpdateDown = false;
// Check if we can move the stack update.
if (stackUpdateCanBeMoved(MF)) {
const std::vector<CalleeSavedInfo> &Info = MFI.getCalleeSavedInfo();
for (CalleeSavedInfo CSI : Info) {
// If the callee saved register is spilled to a register instead of the
// stack then the spill no longer uses the stack pointer.
// This can lead to two consequences:
// 1) We no longer need to update the stack because the function does not
// spill any callee saved registers to stack.
// 2) We have a situation where we still have to update the stack pointer
// even though some registers are spilled to other registers. In
// this case the current code moves the stack update to an incorrect
// position.
// In either case we should abort moving the stack update operation.
if (CSI.isSpilledToReg()) {
StackUpdateLoc = MBBI;
MovingStackUpdateDown = false;
break;
}
int FrIdx = CSI.getFrameIdx();
// If the frame index is not negative the callee saved info belongs to a
// stack object that is not a fixed stack object. We ignore non-fixed
// stack objects because we won't move the stack update pointer past them.
if (FrIdx >= 0)
continue;
if (MFI.isFixedObjectIndex(FrIdx) && MFI.getObjectOffset(FrIdx) < 0) {
StackUpdateLoc++;
MovingStackUpdateDown = true;
} else {
// We need all of the Frame Indices to meet these conditions.
// If they do not, abort the whole operation.
StackUpdateLoc = MBBI;
MovingStackUpdateDown = false;
break;
}
}
// If the operation was not aborted then update the object offset.
if (MovingStackUpdateDown) {
for (CalleeSavedInfo CSI : Info) {
int FrIdx = CSI.getFrameIdx();
if (FrIdx < 0)
MFI.setObjectOffset(FrIdx, MFI.getObjectOffset(FrIdx) + NegFrameSize);
}
}
}
// Where in the prologue we move the CR fields depends on how many scratch
// registers we have, and if we need to save the link register or not. This
// lambda is to avoid duplicating the logic in 2 places.
auto BuildMoveFromCR = [&]() {
if (isELFv2ABI && MustSaveCRs.size() == 1) {
// In the ELFv2 ABI, we are not required to save all CR fields.
// If only one CR field is clobbered, it is more efficient to use
// mfocrf to selectively save just that field, because mfocrf has short
// latency compares to mfcr.
assert(isPPC64 && "V2 ABI is 64-bit only.");
MachineInstrBuilder MIB =
BuildMI(MBB, MBBI, dl, TII.get(PPC::MFOCRF8), TempReg);
MIB.addReg(MustSaveCRs[0], RegState::Kill);
} else {
MachineInstrBuilder MIB =
BuildMI(MBB, MBBI, dl, MoveFromCondRegInst, TempReg);
for (unsigned CRfield : MustSaveCRs)
MIB.addReg(CRfield, RegState::ImplicitKill);
}
};
// If we need to spill the CR and the LR but we don't have two separate
// registers available, we must spill them one at a time
if (MustSaveCR && SingleScratchReg && MustSaveLR) {
BuildMoveFromCR();
BuildMI(MBB, MBBI, dl, StoreWordInst)
.addReg(TempReg, getKillRegState(true))
.addImm(CRSaveOffset)
.addReg(SPReg);
}
if (MustSaveLR)
BuildMI(MBB, MBBI, dl, MFLRInst, ScratchReg);
if (MustSaveCR && !(SingleScratchReg && MustSaveLR))
BuildMoveFromCR();
if (HasRedZone) {
if (HasFP)
BuildMI(MBB, MBBI, dl, StoreInst)
.addReg(FPReg)
.addImm(FPOffset)
.addReg(SPReg);
if (FI->usesPICBase())
BuildMI(MBB, MBBI, dl, StoreInst)
.addReg(PPC::R30)
.addImm(PBPOffset)
.addReg(SPReg);
if (HasBP)
BuildMI(MBB, MBBI, dl, StoreInst)
.addReg(BPReg)
.addImm(BPOffset)
.addReg(SPReg);
}
// Generate the instruction to store the LR. In the case where ROP protection
// is required the register holding the LR should not be killed as it will be
// used by the hash store instruction.
if (MustSaveLR) {
BuildMI(MBB, StackUpdateLoc, dl, StoreInst)
.addReg(ScratchReg, getKillRegState(!HasROPProtect))
.addImm(LROffset)
.addReg(SPReg);
// Add the ROP protection Hash Store instruction.
// NOTE: This is technically a violation of the ABI. The hash can be saved
// up to 512 bytes into the Protected Zone. This can be outside of the
// initial 288 byte volatile program storage region in the Protected Zone.
// However, this restriction will be removed in an upcoming revision of the
// ABI.
if (HasROPProtect) {
const int SaveIndex = FI->getROPProtectionHashSaveIndex();
const int64_t ImmOffset = MFI.getObjectOffset(SaveIndex);
assert((ImmOffset <= -8 && ImmOffset >= -512) &&
"ROP hash save offset out of range.");
assert(((ImmOffset & 0x7) == 0) &&
"ROP hash save offset must be 8 byte aligned.");
BuildMI(MBB, StackUpdateLoc, dl, HashST)
.addReg(ScratchReg, getKillRegState(true))
.addImm(ImmOffset)
.addReg(SPReg);
}
}
if (MustSaveCR &&
!(SingleScratchReg && MustSaveLR)) {
assert(HasRedZone && "A red zone is always available on PPC64");
BuildMI(MBB, MBBI, dl, StoreWordInst)
.addReg(TempReg, getKillRegState(true))
.addImm(CRSaveOffset)
.addReg(SPReg);
}
// Skip the rest if this is a leaf function & all spills fit in the Red Zone.
if (!FrameSize)
return;
// Adjust stack pointer: r1 += NegFrameSize.
// If there is a preferred stack alignment, align R1 now
if (HasBP && HasRedZone) {
// Save a copy of r1 as the base pointer.
BuildMI(MBB, MBBI, dl, OrInst, BPReg)
.addReg(SPReg)
.addReg(SPReg);
}
// Have we generated a STUX instruction to claim stack frame? If so,
// the negated frame size will be placed in ScratchReg.
bool HasSTUX = false;
// If FrameSize <= TLI.getStackProbeSize(MF), as POWER ABI requires backchain
// pointer is always stored at SP, we will get a free probe due to an essential
// STU(X) instruction.
if (TLI.hasInlineStackProbe(MF) && FrameSize > TLI.getStackProbeSize(MF)) {
// To be consistent with other targets, a pseudo instruction is emitted and
// will be later expanded in `inlineStackProbe`.
BuildMI(MBB, MBBI, dl,
TII.get(isPPC64 ? PPC::PROBED_STACKALLOC_64
: PPC::PROBED_STACKALLOC_32))
.addDef(TempReg)
.addDef(ScratchReg) // ScratchReg stores the old sp.
.addImm(NegFrameSize);
// FIXME: HasSTUX is only read if HasRedZone is not set, in such case, we
// update the ScratchReg to meet the assumption that ScratchReg contains
// the NegFrameSize. This solution is rather tricky.
if (!HasRedZone) {
BuildMI(MBB, MBBI, dl, TII.get(PPC::SUBF), ScratchReg)
.addReg(ScratchReg)
.addReg(SPReg);
HasSTUX = true;
}
} else {
// This condition must be kept in sync with canUseAsPrologue.
if (HasBP && MaxAlign > 1) {
if (isPPC64)
BuildMI(MBB, MBBI, dl, TII.get(PPC::RLDICL), ScratchReg)
.addReg(SPReg)
.addImm(0)
.addImm(64 - Log2(MaxAlign));
else // PPC32...
BuildMI(MBB, MBBI, dl, TII.get(PPC::RLWINM), ScratchReg)
.addReg(SPReg)
.addImm(0)
.addImm(32 - Log2(MaxAlign))
.addImm(31);
if (!isLargeFrame) {
BuildMI(MBB, MBBI, dl, SubtractImmCarryingInst, ScratchReg)
.addReg(ScratchReg, RegState::Kill)
.addImm(NegFrameSize);
} else {
assert(!SingleScratchReg && "Only a single scratch reg available");
BuildMI(MBB, MBBI, dl, LoadImmShiftedInst, TempReg)
.addImm(NegFrameSize >> 16);
BuildMI(MBB, MBBI, dl, OrImmInst, TempReg)
.addReg(TempReg, RegState::Kill)
.addImm(NegFrameSize & 0xFFFF);
BuildMI(MBB, MBBI, dl, SubtractCarryingInst, ScratchReg)
.addReg(ScratchReg, RegState::Kill)
.addReg(TempReg, RegState::Kill);
}
BuildMI(MBB, MBBI, dl, StoreUpdtIdxInst, SPReg)
.addReg(SPReg, RegState::Kill)
.addReg(SPReg)
.addReg(ScratchReg);
HasSTUX = true;
} else if (!isLargeFrame) {
BuildMI(MBB, StackUpdateLoc, dl, StoreUpdtInst, SPReg)
.addReg(SPReg)
.addImm(NegFrameSize)
.addReg(SPReg);
} else {
BuildMI(MBB, MBBI, dl, LoadImmShiftedInst, ScratchReg)
.addImm(NegFrameSize >> 16);
BuildMI(MBB, MBBI, dl, OrImmInst, ScratchReg)
.addReg(ScratchReg, RegState::Kill)
.addImm(NegFrameSize & 0xFFFF);
BuildMI(MBB, MBBI, dl, StoreUpdtIdxInst, SPReg)
.addReg(SPReg, RegState::Kill)
.addReg(SPReg)
.addReg(ScratchReg);
HasSTUX = true;
}
}
// Save the TOC register after the stack pointer update if a prologue TOC
// save is required for the function.
if (MustSaveTOC) {
assert(isELFv2ABI && "TOC saves in the prologue only supported on ELFv2");
BuildMI(MBB, StackUpdateLoc, dl, TII.get(PPC::STD))
.addReg(TOCReg, getKillRegState(true))
.addImm(TOCSaveOffset)
.addReg(SPReg);
}
if (!HasRedZone) {
assert(!isPPC64 && "A red zone is always available on PPC64");
if (HasSTUX) {
// The negated frame size is in ScratchReg, and the SPReg has been
// decremented by the frame size: SPReg = old SPReg + ScratchReg.
// Since FPOffset, PBPOffset, etc. are relative to the beginning of
// the stack frame (i.e. the old SP), ideally, we would put the old
// SP into a register and use it as the base for the stores. The
// problem is that the only available register may be ScratchReg,
// which could be R0, and R0 cannot be used as a base address.
// First, set ScratchReg to the old SP. This may need to be modified
// later.
BuildMI(MBB, MBBI, dl, TII.get(PPC::SUBF), ScratchReg)
.addReg(ScratchReg, RegState::Kill)
.addReg(SPReg);
if (ScratchReg == PPC::R0) {