forked from llvm/llvm-project
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHexagonFrameLowering.cpp
2736 lines (2435 loc) · 97.1 KB
/
HexagonFrameLowering.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
//===- HexagonFrameLowering.cpp - Define frame lowering -------------------===//
//
// 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
//
//
//===----------------------------------------------------------------------===//
#include "HexagonFrameLowering.h"
#include "HexagonBlockRanges.h"
#include "HexagonInstrInfo.h"
#include "HexagonMachineFunctionInfo.h"
#include "HexagonRegisterInfo.h"
#include "HexagonSubtarget.h"
#include "HexagonTargetMachine.h"
#include "MCTargetDesc/HexagonBaseInfo.h"
#include "llvm/ADT/BitVector.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/None.h"
#include "llvm/ADT/Optional.h"
#include "llvm/ADT/PostOrderIterator.h"
#include "llvm/ADT/SetVector.h"
#include "llvm/ADT/SmallSet.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/CodeGen/LivePhysRegs.h"
#include "llvm/CodeGen/MachineBasicBlock.h"
#include "llvm/CodeGen/MachineDominators.h"
#include "llvm/CodeGen/MachineFrameInfo.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/MachineFunctionPass.h"
#include "llvm/CodeGen/MachineInstr.h"
#include "llvm/CodeGen/MachineInstrBuilder.h"
#include "llvm/CodeGen/MachineMemOperand.h"
#include "llvm/CodeGen/MachineModuleInfo.h"
#include "llvm/CodeGen/MachineOperand.h"
#include "llvm/CodeGen/MachinePostDominators.h"
#include "llvm/CodeGen/MachineRegisterInfo.h"
#include "llvm/CodeGen/PseudoSourceValue.h"
#include "llvm/CodeGen/RegisterScavenging.h"
#include "llvm/CodeGen/TargetRegisterInfo.h"
#include "llvm/IR/Attributes.h"
#include "llvm/IR/DebugLoc.h"
#include "llvm/IR/Function.h"
#include "llvm/MC/MCDwarf.h"
#include "llvm/MC/MCRegisterInfo.h"
#include "llvm/Pass.h"
#include "llvm/Support/CodeGen.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/MathExtras.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Target/TargetOptions.h"
#include <algorithm>
#include <cassert>
#include <cstdint>
#include <iterator>
#include <limits>
#include <map>
#include <utility>
#include <vector>
#define DEBUG_TYPE "hexagon-pei"
// Hexagon stack frame layout as defined by the ABI:
//
// Incoming arguments
// passed via stack
// |
// |
// SP during function's FP during function's |
// +-- runtime (top of stack) runtime (bottom) --+ |
// | | |
// --++---------------------+------------------+-----------------++-+-------
// | parameter area for | variable-size | fixed-size |LR| arg
// | called functions | local objects | local objects |FP|
// --+----------------------+------------------+-----------------+--+-------
// <- size known -> <- size unknown -> <- size known ->
//
// Low address High address
//
// <--- stack growth
//
//
// - In any circumstances, the outgoing function arguments are always accessi-
// ble using the SP, and the incoming arguments are accessible using the FP.
// - If the local objects are not aligned, they can always be accessed using
// the FP.
// - If there are no variable-sized objects, the local objects can always be
// accessed using the SP, regardless whether they are aligned or not. (The
// alignment padding will be at the bottom of the stack (highest address),
// and so the offset with respect to the SP will be known at the compile-
// -time.)
//
// The only complication occurs if there are both, local aligned objects, and
// dynamically allocated (variable-sized) objects. The alignment pad will be
// placed between the FP and the local objects, thus preventing the use of the
// FP to access the local objects. At the same time, the variable-sized objects
// will be between the SP and the local objects, thus introducing an unknown
// distance from the SP to the locals.
//
// To avoid this problem, a new register is created that holds the aligned
// address of the bottom of the stack, referred in the sources as AP (aligned
// pointer). The AP will be equal to "FP-p", where "p" is the smallest pad
// that aligns AP to the required boundary (a maximum of the alignments of
// all stack objects, fixed- and variable-sized). All local objects[1] will
// then use AP as the base pointer.
// [1] The exception is with "fixed" stack objects. "Fixed" stack objects get
// their name from being allocated at fixed locations on the stack, relative
// to the FP. In the presence of dynamic allocation and local alignment, such
// objects can only be accessed through the FP.
//
// Illustration of the AP:
// FP --+
// |
// ---------------+---------------------+-----+-----------------------++-+--
// Rest of the | Local stack objects | Pad | Fixed stack objects |LR|
// stack frame | (aligned) | | (CSR, spills, etc.) |FP|
// ---------------+---------------------+-----+-----------------+-----+--+--
// |<-- Multiple of the -->|
// stack alignment +-- AP
//
// The AP is set up at the beginning of the function. Since it is not a dedi-
// cated (reserved) register, it needs to be kept live throughout the function
// to be available as the base register for local object accesses.
// Normally, an address of a stack objects is obtained by a pseudo-instruction
// PS_fi. To access local objects with the AP register present, a different
// pseudo-instruction needs to be used: PS_fia. The PS_fia takes one extra
// argument compared to PS_fi: the first input register is the AP register.
// This keeps the register live between its definition and its uses.
// The AP register is originally set up using pseudo-instruction PS_aligna:
// AP = PS_aligna A
// where
// A - required stack alignment
// The alignment value must be the maximum of all alignments required by
// any stack object.
// The dynamic allocation uses a pseudo-instruction PS_alloca:
// Rd = PS_alloca Rs, A
// where
// Rd - address of the allocated space
// Rs - minimum size (the actual allocated can be larger to accommodate
// alignment)
// A - required alignment
using namespace llvm;
static cl::opt<bool> DisableDeallocRet("disable-hexagon-dealloc-ret",
cl::Hidden, cl::desc("Disable Dealloc Return for Hexagon target"));
static cl::opt<unsigned> NumberScavengerSlots("number-scavenger-slots",
cl::Hidden, cl::desc("Set the number of scavenger slots"), cl::init(2),
cl::ZeroOrMore);
static cl::opt<int> SpillFuncThreshold("spill-func-threshold",
cl::Hidden, cl::desc("Specify O2(not Os) spill func threshold"),
cl::init(6), cl::ZeroOrMore);
static cl::opt<int> SpillFuncThresholdOs("spill-func-threshold-Os",
cl::Hidden, cl::desc("Specify Os spill func threshold"),
cl::init(1), cl::ZeroOrMore);
static cl::opt<bool> EnableStackOVFSanitizer("enable-stackovf-sanitizer",
cl::Hidden, cl::desc("Enable runtime checks for stack overflow."),
cl::init(false), cl::ZeroOrMore);
static cl::opt<bool> EnableShrinkWrapping("hexagon-shrink-frame",
cl::init(true), cl::Hidden, cl::ZeroOrMore,
cl::desc("Enable stack frame shrink wrapping"));
static cl::opt<unsigned> ShrinkLimit("shrink-frame-limit",
cl::init(std::numeric_limits<unsigned>::max()), cl::Hidden, cl::ZeroOrMore,
cl::desc("Max count of stack frame shrink-wraps"));
static cl::opt<bool> EnableSaveRestoreLong("enable-save-restore-long",
cl::Hidden, cl::desc("Enable long calls for save-restore stubs."),
cl::init(false), cl::ZeroOrMore);
static cl::opt<bool> EliminateFramePointer("hexagon-fp-elim", cl::init(true),
cl::Hidden, cl::desc("Refrain from using FP whenever possible"));
static cl::opt<bool> OptimizeSpillSlots("hexagon-opt-spill", cl::Hidden,
cl::init(true), cl::desc("Optimize spill slots"));
#ifndef NDEBUG
static cl::opt<unsigned> SpillOptMax("spill-opt-max", cl::Hidden,
cl::init(std::numeric_limits<unsigned>::max()));
static unsigned SpillOptCount = 0;
#endif
namespace llvm {
void initializeHexagonCallFrameInformationPass(PassRegistry&);
FunctionPass *createHexagonCallFrameInformation();
} // end namespace llvm
namespace {
class HexagonCallFrameInformation : public MachineFunctionPass {
public:
static char ID;
HexagonCallFrameInformation() : MachineFunctionPass(ID) {
PassRegistry &PR = *PassRegistry::getPassRegistry();
initializeHexagonCallFrameInformationPass(PR);
}
bool runOnMachineFunction(MachineFunction &MF) override;
MachineFunctionProperties getRequiredProperties() const override {
return MachineFunctionProperties().set(
MachineFunctionProperties::Property::NoVRegs);
}
};
char HexagonCallFrameInformation::ID = 0;
} // end anonymous namespace
bool HexagonCallFrameInformation::runOnMachineFunction(MachineFunction &MF) {
auto &HFI = *MF.getSubtarget<HexagonSubtarget>().getFrameLowering();
bool NeedCFI = MF.needsFrameMoves();
if (!NeedCFI)
return false;
HFI.insertCFIInstructions(MF);
return true;
}
INITIALIZE_PASS(HexagonCallFrameInformation, "hexagon-cfi",
"Hexagon call frame information", false, false)
FunctionPass *llvm::createHexagonCallFrameInformation() {
return new HexagonCallFrameInformation();
}
/// Map a register pair Reg to the subregister that has the greater "number",
/// i.e. D3 (aka R7:6) will be mapped to R7, etc.
static unsigned getMax32BitSubRegister(unsigned Reg,
const TargetRegisterInfo &TRI,
bool hireg = true) {
if (Reg < Hexagon::D0 || Reg > Hexagon::D15)
return Reg;
unsigned RegNo = 0;
for (MCSubRegIterator SubRegs(Reg, &TRI); SubRegs.isValid(); ++SubRegs) {
if (hireg) {
if (*SubRegs > RegNo)
RegNo = *SubRegs;
} else {
if (!RegNo || *SubRegs < RegNo)
RegNo = *SubRegs;
}
}
return RegNo;
}
/// Returns the callee saved register with the largest id in the vector.
static unsigned getMaxCalleeSavedReg(ArrayRef<CalleeSavedInfo> CSI,
const TargetRegisterInfo &TRI) {
static_assert(Hexagon::R1 > 0,
"Assume physical registers are encoded as positive integers");
if (CSI.empty())
return 0;
unsigned Max = getMax32BitSubRegister(CSI[0].getReg(), TRI);
for (unsigned I = 1, E = CSI.size(); I < E; ++I) {
unsigned Reg = getMax32BitSubRegister(CSI[I].getReg(), TRI);
if (Reg > Max)
Max = Reg;
}
return Max;
}
/// Checks if the basic block contains any instruction that needs a stack
/// frame to be already in place.
static bool needsStackFrame(const MachineBasicBlock &MBB, const BitVector &CSR,
const HexagonRegisterInfo &HRI) {
for (auto &I : MBB) {
const MachineInstr *MI = &I;
if (MI->isCall())
return true;
unsigned Opc = MI->getOpcode();
switch (Opc) {
case Hexagon::PS_alloca:
case Hexagon::PS_aligna:
return true;
default:
break;
}
// Check individual operands.
for (const MachineOperand &MO : MI->operands()) {
// While the presence of a frame index does not prove that a stack
// frame will be required, all frame indexes should be within alloc-
// frame/deallocframe. Otherwise, the code that translates a frame
// index into an offset would have to be aware of the placement of
// the frame creation/destruction instructions.
if (MO.isFI())
return true;
if (MO.isReg()) {
Register R = MO.getReg();
// Virtual registers will need scavenging, which then may require
// a stack slot.
if (R.isVirtual())
return true;
for (MCSubRegIterator S(R, &HRI, true); S.isValid(); ++S)
if (CSR[*S])
return true;
continue;
}
if (MO.isRegMask()) {
// A regmask would normally have all callee-saved registers marked
// as preserved, so this check would not be needed, but in case of
// ever having other regmasks (for other calling conventions),
// make sure they would be processed correctly.
const uint32_t *BM = MO.getRegMask();
for (int x = CSR.find_first(); x >= 0; x = CSR.find_next(x)) {
unsigned R = x;
// If this regmask does not preserve a CSR, a frame will be needed.
if (!(BM[R/32] & (1u << (R%32))))
return true;
}
}
}
}
return false;
}
/// Returns true if MBB has a machine instructions that indicates a tail call
/// in the block.
static bool hasTailCall(const MachineBasicBlock &MBB) {
MachineBasicBlock::const_iterator I = MBB.getLastNonDebugInstr();
if (I == MBB.end())
return false;
unsigned RetOpc = I->getOpcode();
return RetOpc == Hexagon::PS_tailcall_i || RetOpc == Hexagon::PS_tailcall_r;
}
/// Returns true if MBB contains an instruction that returns.
static bool hasReturn(const MachineBasicBlock &MBB) {
for (auto I = MBB.getFirstTerminator(), E = MBB.end(); I != E; ++I)
if (I->isReturn())
return true;
return false;
}
/// Returns the "return" instruction from this block, or nullptr if there
/// isn't any.
static MachineInstr *getReturn(MachineBasicBlock &MBB) {
for (auto &I : MBB)
if (I.isReturn())
return &I;
return nullptr;
}
static bool isRestoreCall(unsigned Opc) {
switch (Opc) {
case Hexagon::RESTORE_DEALLOC_RET_JMP_V4:
case Hexagon::RESTORE_DEALLOC_RET_JMP_V4_PIC:
case Hexagon::RESTORE_DEALLOC_RET_JMP_V4_EXT:
case Hexagon::RESTORE_DEALLOC_RET_JMP_V4_EXT_PIC:
case Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_EXT:
case Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_EXT_PIC:
case Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4:
case Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_PIC:
return true;
}
return false;
}
static inline bool isOptNone(const MachineFunction &MF) {
return MF.getFunction().hasOptNone() ||
MF.getTarget().getOptLevel() == CodeGenOpt::None;
}
static inline bool isOptSize(const MachineFunction &MF) {
const Function &F = MF.getFunction();
return F.hasOptSize() && !F.hasMinSize();
}
static inline bool isMinSize(const MachineFunction &MF) {
return MF.getFunction().hasMinSize();
}
/// Implements shrink-wrapping of the stack frame. By default, stack frame
/// is created in the function entry block, and is cleaned up in every block
/// that returns. This function finds alternate blocks: one for the frame
/// setup (prolog) and one for the cleanup (epilog).
void HexagonFrameLowering::findShrunkPrologEpilog(MachineFunction &MF,
MachineBasicBlock *&PrologB, MachineBasicBlock *&EpilogB) const {
static unsigned ShrinkCounter = 0;
if (MF.getSubtarget<HexagonSubtarget>().isEnvironmentMusl() &&
MF.getFunction().isVarArg())
return;
if (ShrinkLimit.getPosition()) {
if (ShrinkCounter >= ShrinkLimit)
return;
ShrinkCounter++;
}
auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
MachineDominatorTree MDT;
MDT.runOnMachineFunction(MF);
MachinePostDominatorTree MPT;
MPT.runOnMachineFunction(MF);
using UnsignedMap = DenseMap<unsigned, unsigned>;
using RPOTType = ReversePostOrderTraversal<const MachineFunction *>;
UnsignedMap RPO;
RPOTType RPOT(&MF);
unsigned RPON = 0;
for (RPOTType::rpo_iterator I = RPOT.begin(), E = RPOT.end(); I != E; ++I)
RPO[(*I)->getNumber()] = RPON++;
// Don't process functions that have loops, at least for now. Placement
// of prolog and epilog must take loop structure into account. For simpli-
// city don't do it right now.
for (auto &I : MF) {
unsigned BN = RPO[I.getNumber()];
for (auto SI = I.succ_begin(), SE = I.succ_end(); SI != SE; ++SI) {
// If found a back-edge, return.
if (RPO[(*SI)->getNumber()] <= BN)
return;
}
}
// Collect the set of blocks that need a stack frame to execute. Scan
// each block for uses/defs of callee-saved registers, calls, etc.
SmallVector<MachineBasicBlock*,16> SFBlocks;
BitVector CSR(Hexagon::NUM_TARGET_REGS);
for (const MCPhysReg *P = HRI.getCalleeSavedRegs(&MF); *P; ++P)
for (MCSubRegIterator S(*P, &HRI, true); S.isValid(); ++S)
CSR[*S] = true;
for (auto &I : MF)
if (needsStackFrame(I, CSR, HRI))
SFBlocks.push_back(&I);
LLVM_DEBUG({
dbgs() << "Blocks needing SF: {";
for (auto &B : SFBlocks)
dbgs() << " " << printMBBReference(*B);
dbgs() << " }\n";
});
// No frame needed?
if (SFBlocks.empty())
return;
// Pick a common dominator and a common post-dominator.
MachineBasicBlock *DomB = SFBlocks[0];
for (unsigned i = 1, n = SFBlocks.size(); i < n; ++i) {
DomB = MDT.findNearestCommonDominator(DomB, SFBlocks[i]);
if (!DomB)
break;
}
MachineBasicBlock *PDomB = SFBlocks[0];
for (unsigned i = 1, n = SFBlocks.size(); i < n; ++i) {
PDomB = MPT.findNearestCommonDominator(PDomB, SFBlocks[i]);
if (!PDomB)
break;
}
LLVM_DEBUG({
dbgs() << "Computed dom block: ";
if (DomB)
dbgs() << printMBBReference(*DomB);
else
dbgs() << "<null>";
dbgs() << ", computed pdom block: ";
if (PDomB)
dbgs() << printMBBReference(*PDomB);
else
dbgs() << "<null>";
dbgs() << "\n";
});
if (!DomB || !PDomB)
return;
// Make sure that DomB dominates PDomB and PDomB post-dominates DomB.
if (!MDT.dominates(DomB, PDomB)) {
LLVM_DEBUG(dbgs() << "Dom block does not dominate pdom block\n");
return;
}
if (!MPT.dominates(PDomB, DomB)) {
LLVM_DEBUG(dbgs() << "PDom block does not post-dominate dom block\n");
return;
}
// Finally, everything seems right.
PrologB = DomB;
EpilogB = PDomB;
}
/// Perform most of the PEI work here:
/// - saving/restoring of the callee-saved registers,
/// - stack frame creation and destruction.
/// Normally, this work is distributed among various functions, but doing it
/// in one place allows shrink-wrapping of the stack frame.
void HexagonFrameLowering::emitPrologue(MachineFunction &MF,
MachineBasicBlock &MBB) const {
auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
MachineFrameInfo &MFI = MF.getFrameInfo();
const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
MachineBasicBlock *PrologB = &MF.front(), *EpilogB = nullptr;
if (EnableShrinkWrapping)
findShrunkPrologEpilog(MF, PrologB, EpilogB);
bool PrologueStubs = false;
insertCSRSpillsInBlock(*PrologB, CSI, HRI, PrologueStubs);
insertPrologueInBlock(*PrologB, PrologueStubs);
updateEntryPaths(MF, *PrologB);
if (EpilogB) {
insertCSRRestoresInBlock(*EpilogB, CSI, HRI);
insertEpilogueInBlock(*EpilogB);
} else {
for (auto &B : MF)
if (B.isReturnBlock())
insertCSRRestoresInBlock(B, CSI, HRI);
for (auto &B : MF)
if (B.isReturnBlock())
insertEpilogueInBlock(B);
for (auto &B : MF) {
if (B.empty())
continue;
MachineInstr *RetI = getReturn(B);
if (!RetI || isRestoreCall(RetI->getOpcode()))
continue;
for (auto &R : CSI)
RetI->addOperand(MachineOperand::CreateReg(R.getReg(), false, true));
}
}
if (EpilogB) {
// If there is an epilog block, it may not have a return instruction.
// In such case, we need to add the callee-saved registers as live-ins
// in all blocks on all paths from the epilog to any return block.
unsigned MaxBN = MF.getNumBlockIDs();
BitVector DoneT(MaxBN+1), DoneF(MaxBN+1), Path(MaxBN+1);
updateExitPaths(*EpilogB, *EpilogB, DoneT, DoneF, Path);
}
}
/// Returns true if the target can safely skip saving callee-saved registers
/// for noreturn nounwind functions.
bool HexagonFrameLowering::enableCalleeSaveSkip(
const MachineFunction &MF) const {
const auto &F = MF.getFunction();
assert(F.hasFnAttribute(Attribute::NoReturn) &&
F.getFunction().hasFnAttribute(Attribute::NoUnwind) &&
!F.getFunction().hasFnAttribute(Attribute::UWTable));
(void)F;
// No need to save callee saved registers if the function does not return.
return MF.getSubtarget<HexagonSubtarget>().noreturnStackElim();
}
// Helper function used to determine when to eliminate the stack frame for
// functions marked as noreturn and when the noreturn-stack-elim options are
// specified. When both these conditions are true, then a FP may not be needed
// if the function makes a call. It is very similar to enableCalleeSaveSkip,
// but it used to check if the allocframe can be eliminated as well.
static bool enableAllocFrameElim(const MachineFunction &MF) {
const auto &F = MF.getFunction();
const auto &MFI = MF.getFrameInfo();
const auto &HST = MF.getSubtarget<HexagonSubtarget>();
assert(!MFI.hasVarSizedObjects() &&
!HST.getRegisterInfo()->hasStackRealignment(MF));
return F.hasFnAttribute(Attribute::NoReturn) &&
F.hasFnAttribute(Attribute::NoUnwind) &&
!F.hasFnAttribute(Attribute::UWTable) && HST.noreturnStackElim() &&
MFI.getStackSize() == 0;
}
void HexagonFrameLowering::insertPrologueInBlock(MachineBasicBlock &MBB,
bool PrologueStubs) const {
MachineFunction &MF = *MBB.getParent();
MachineFrameInfo &MFI = MF.getFrameInfo();
auto &HST = MF.getSubtarget<HexagonSubtarget>();
auto &HII = *HST.getInstrInfo();
auto &HRI = *HST.getRegisterInfo();
Align MaxAlign = std::max(MFI.getMaxAlign(), getStackAlign());
// Calculate the total stack frame size.
// Get the number of bytes to allocate from the FrameInfo.
unsigned FrameSize = MFI.getStackSize();
// Round up the max call frame size to the max alignment on the stack.
unsigned MaxCFA = alignTo(MFI.getMaxCallFrameSize(), MaxAlign);
MFI.setMaxCallFrameSize(MaxCFA);
FrameSize = MaxCFA + alignTo(FrameSize, MaxAlign);
MFI.setStackSize(FrameSize);
bool AlignStack = (MaxAlign > getStackAlign());
// Get the number of bytes to allocate from the FrameInfo.
unsigned NumBytes = MFI.getStackSize();
unsigned SP = HRI.getStackRegister();
unsigned MaxCF = MFI.getMaxCallFrameSize();
MachineBasicBlock::iterator InsertPt = MBB.begin();
SmallVector<MachineInstr *, 4> AdjustRegs;
for (auto &MBB : MF)
for (auto &MI : MBB)
if (MI.getOpcode() == Hexagon::PS_alloca)
AdjustRegs.push_back(&MI);
for (auto MI : AdjustRegs) {
assert((MI->getOpcode() == Hexagon::PS_alloca) && "Expected alloca");
expandAlloca(MI, HII, SP, MaxCF);
MI->eraseFromParent();
}
DebugLoc dl = MBB.findDebugLoc(InsertPt);
if (MF.getFunction().isVarArg() &&
MF.getSubtarget<HexagonSubtarget>().isEnvironmentMusl()) {
// Calculate the size of register saved area.
int NumVarArgRegs = 6 - FirstVarArgSavedReg;
int RegisterSavedAreaSizePlusPadding = (NumVarArgRegs % 2 == 0)
? NumVarArgRegs * 4
: NumVarArgRegs * 4 + 4;
if (RegisterSavedAreaSizePlusPadding > 0) {
// Decrement the stack pointer by size of register saved area plus
// padding if any.
BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::A2_addi), SP)
.addReg(SP)
.addImm(-RegisterSavedAreaSizePlusPadding)
.setMIFlag(MachineInstr::FrameSetup);
int NumBytes = 0;
// Copy all the named arguments below register saved area.
auto &HMFI = *MF.getInfo<HexagonMachineFunctionInfo>();
for (int i = HMFI.getFirstNamedArgFrameIndex(),
e = HMFI.getLastNamedArgFrameIndex(); i >= e; --i) {
uint64_t ObjSize = MFI.getObjectSize(i);
Align ObjAlign = MFI.getObjectAlign(i);
// Determine the kind of load/store that should be used.
unsigned LDOpc, STOpc;
uint64_t OpcodeChecker = ObjAlign.value();
// Handle cases where alignment of an object is > its size.
if (ObjAlign > ObjSize) {
if (ObjSize <= 1)
OpcodeChecker = 1;
else if (ObjSize <= 2)
OpcodeChecker = 2;
else if (ObjSize <= 4)
OpcodeChecker = 4;
else if (ObjSize > 4)
OpcodeChecker = 8;
}
switch (OpcodeChecker) {
case 1:
LDOpc = Hexagon::L2_loadrb_io;
STOpc = Hexagon::S2_storerb_io;
break;
case 2:
LDOpc = Hexagon::L2_loadrh_io;
STOpc = Hexagon::S2_storerh_io;
break;
case 4:
LDOpc = Hexagon::L2_loadri_io;
STOpc = Hexagon::S2_storeri_io;
break;
case 8:
default:
LDOpc = Hexagon::L2_loadrd_io;
STOpc = Hexagon::S2_storerd_io;
break;
}
unsigned RegUsed = LDOpc == Hexagon::L2_loadrd_io ? Hexagon::D3
: Hexagon::R6;
int LoadStoreCount = ObjSize / OpcodeChecker;
if (ObjSize % OpcodeChecker)
++LoadStoreCount;
// Get the start location of the load. NumBytes is basically the
// offset from the stack pointer of previous function, which would be
// the caller in this case, as this function has variable argument
// list.
if (NumBytes != 0)
NumBytes = alignTo(NumBytes, ObjAlign);
int Count = 0;
while (Count < LoadStoreCount) {
// Load the value of the named argument on stack.
BuildMI(MBB, InsertPt, dl, HII.get(LDOpc), RegUsed)
.addReg(SP)
.addImm(RegisterSavedAreaSizePlusPadding +
ObjAlign.value() * Count + NumBytes)
.setMIFlag(MachineInstr::FrameSetup);
// Store it below the register saved area plus padding.
BuildMI(MBB, InsertPt, dl, HII.get(STOpc))
.addReg(SP)
.addImm(ObjAlign.value() * Count + NumBytes)
.addReg(RegUsed)
.setMIFlag(MachineInstr::FrameSetup);
Count++;
}
NumBytes += MFI.getObjectSize(i);
}
// Make NumBytes 8 byte aligned
NumBytes = alignTo(NumBytes, 8);
// If the number of registers having variable arguments is odd,
// leave 4 bytes of padding to get to the location where first
// variable argument which was passed through register was copied.
NumBytes = (NumVarArgRegs % 2 == 0) ? NumBytes : NumBytes + 4;
for (int j = FirstVarArgSavedReg, i = 0; j < 6; ++j, ++i) {
BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::S2_storeri_io))
.addReg(SP)
.addImm(NumBytes + 4 * i)
.addReg(Hexagon::R0 + j)
.setMIFlag(MachineInstr::FrameSetup);
}
}
}
if (hasFP(MF)) {
insertAllocframe(MBB, InsertPt, NumBytes);
if (AlignStack) {
BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::A2_andir), SP)
.addReg(SP)
.addImm(-int64_t(MaxAlign.value()));
}
// If the stack-checking is enabled, and we spilled the callee-saved
// registers inline (i.e. did not use a spill function), then call
// the stack checker directly.
if (EnableStackOVFSanitizer && !PrologueStubs)
BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::PS_call_stk))
.addExternalSymbol("__runtime_stack_check");
} else if (NumBytes > 0) {
assert(alignTo(NumBytes, 8) == NumBytes);
BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::A2_addi), SP)
.addReg(SP)
.addImm(-int(NumBytes));
}
}
void HexagonFrameLowering::insertEpilogueInBlock(MachineBasicBlock &MBB) const {
MachineFunction &MF = *MBB.getParent();
auto &HST = MF.getSubtarget<HexagonSubtarget>();
auto &HII = *HST.getInstrInfo();
auto &HRI = *HST.getRegisterInfo();
unsigned SP = HRI.getStackRegister();
MachineBasicBlock::iterator InsertPt = MBB.getFirstTerminator();
DebugLoc dl = MBB.findDebugLoc(InsertPt);
if (!hasFP(MF)) {
MachineFrameInfo &MFI = MF.getFrameInfo();
unsigned NumBytes = MFI.getStackSize();
if (MF.getFunction().isVarArg() &&
MF.getSubtarget<HexagonSubtarget>().isEnvironmentMusl()) {
// On Hexagon Linux, deallocate the stack for the register saved area.
int NumVarArgRegs = 6 - FirstVarArgSavedReg;
int RegisterSavedAreaSizePlusPadding = (NumVarArgRegs % 2 == 0) ?
(NumVarArgRegs * 4) : (NumVarArgRegs * 4 + 4);
NumBytes += RegisterSavedAreaSizePlusPadding;
}
if (NumBytes) {
BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::A2_addi), SP)
.addReg(SP)
.addImm(NumBytes);
}
return;
}
MachineInstr *RetI = getReturn(MBB);
unsigned RetOpc = RetI ? RetI->getOpcode() : 0;
// Handle EH_RETURN.
if (RetOpc == Hexagon::EH_RETURN_JMPR) {
BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::L2_deallocframe))
.addDef(Hexagon::D15)
.addReg(Hexagon::R30);
BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::A2_add), SP)
.addReg(SP)
.addReg(Hexagon::R28);
return;
}
// Check for RESTORE_DEALLOC_RET* tail call. Don't emit an extra dealloc-
// frame instruction if we encounter it.
if (RetOpc == Hexagon::RESTORE_DEALLOC_RET_JMP_V4 ||
RetOpc == Hexagon::RESTORE_DEALLOC_RET_JMP_V4_PIC ||
RetOpc == Hexagon::RESTORE_DEALLOC_RET_JMP_V4_EXT ||
RetOpc == Hexagon::RESTORE_DEALLOC_RET_JMP_V4_EXT_PIC) {
MachineBasicBlock::iterator It = RetI;
++It;
// Delete all instructions after the RESTORE (except labels).
while (It != MBB.end()) {
if (!It->isLabel())
It = MBB.erase(It);
else
++It;
}
return;
}
// It is possible that the restoring code is a call to a library function.
// All of the restore* functions include "deallocframe", so we need to make
// sure that we don't add an extra one.
bool NeedsDeallocframe = true;
if (!MBB.empty() && InsertPt != MBB.begin()) {
MachineBasicBlock::iterator PrevIt = std::prev(InsertPt);
unsigned COpc = PrevIt->getOpcode();
if (COpc == Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4 ||
COpc == Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_PIC ||
COpc == Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_EXT ||
COpc == Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_EXT_PIC ||
COpc == Hexagon::PS_call_nr || COpc == Hexagon::PS_callr_nr)
NeedsDeallocframe = false;
}
if (!MF.getSubtarget<HexagonSubtarget>().isEnvironmentMusl() ||
!MF.getFunction().isVarArg()) {
if (!NeedsDeallocframe)
return;
// If the returning instruction is PS_jmpret, replace it with
// dealloc_return, otherwise just add deallocframe. The function
// could be returning via a tail call.
if (RetOpc != Hexagon::PS_jmpret || DisableDeallocRet) {
BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::L2_deallocframe))
.addDef(Hexagon::D15)
.addReg(Hexagon::R30);
return;
}
unsigned NewOpc = Hexagon::L4_return;
MachineInstr *NewI = BuildMI(MBB, RetI, dl, HII.get(NewOpc))
.addDef(Hexagon::D15)
.addReg(Hexagon::R30);
// Transfer the function live-out registers.
NewI->copyImplicitOps(MF, *RetI);
MBB.erase(RetI);
} else {
// L2_deallocframe instruction after it.
// Calculate the size of register saved area.
int NumVarArgRegs = 6 - FirstVarArgSavedReg;
int RegisterSavedAreaSizePlusPadding = (NumVarArgRegs % 2 == 0) ?
(NumVarArgRegs * 4) : (NumVarArgRegs * 4 + 4);
MachineBasicBlock::iterator Term = MBB.getFirstTerminator();
MachineBasicBlock::iterator I = (Term == MBB.begin()) ? MBB.end()
: std::prev(Term);
if (I == MBB.end() ||
(I->getOpcode() != Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_EXT &&
I->getOpcode() != Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_EXT_PIC &&
I->getOpcode() != Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4 &&
I->getOpcode() != Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_PIC))
BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::L2_deallocframe))
.addDef(Hexagon::D15)
.addReg(Hexagon::R30);
if (RegisterSavedAreaSizePlusPadding != 0)
BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::A2_addi), SP)
.addReg(SP)
.addImm(RegisterSavedAreaSizePlusPadding);
}
}
void HexagonFrameLowering::insertAllocframe(MachineBasicBlock &MBB,
MachineBasicBlock::iterator InsertPt, unsigned NumBytes) const {
MachineFunction &MF = *MBB.getParent();
auto &HST = MF.getSubtarget<HexagonSubtarget>();
auto &HII = *HST.getInstrInfo();
auto &HRI = *HST.getRegisterInfo();
// Check for overflow.
// Hexagon_TODO: Ugh! hardcoding. Is there an API that can be used?
const unsigned int ALLOCFRAME_MAX = 16384;
// Create a dummy memory operand to avoid allocframe from being treated as
// a volatile memory reference.
auto *MMO = MF.getMachineMemOperand(MachinePointerInfo::getStack(MF, 0),
MachineMemOperand::MOStore, 4, Align(4));
DebugLoc dl = MBB.findDebugLoc(InsertPt);
unsigned SP = HRI.getStackRegister();
if (NumBytes >= ALLOCFRAME_MAX) {
// Emit allocframe(#0).
BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::S2_allocframe))
.addDef(SP)
.addReg(SP)
.addImm(0)
.addMemOperand(MMO);
// Subtract the size from the stack pointer.
unsigned SP = HRI.getStackRegister();
BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::A2_addi), SP)
.addReg(SP)
.addImm(-int(NumBytes));
} else {
BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::S2_allocframe))
.addDef(SP)
.addReg(SP)
.addImm(NumBytes)
.addMemOperand(MMO);
}
}
void HexagonFrameLowering::updateEntryPaths(MachineFunction &MF,
MachineBasicBlock &SaveB) const {
SetVector<unsigned> Worklist;
MachineBasicBlock &EntryB = MF.front();
Worklist.insert(EntryB.getNumber());
unsigned SaveN = SaveB.getNumber();
auto &CSI = MF.getFrameInfo().getCalleeSavedInfo();
for (unsigned i = 0; i < Worklist.size(); ++i) {
unsigned BN = Worklist[i];
MachineBasicBlock &MBB = *MF.getBlockNumbered(BN);
for (auto &R : CSI)
if (!MBB.isLiveIn(R.getReg()))
MBB.addLiveIn(R.getReg());
if (BN != SaveN)
for (auto &SB : MBB.successors())
Worklist.insert(SB->getNumber());
}
}
bool HexagonFrameLowering::updateExitPaths(MachineBasicBlock &MBB,
MachineBasicBlock &RestoreB, BitVector &DoneT, BitVector &DoneF,
BitVector &Path) const {
assert(MBB.getNumber() >= 0);
unsigned BN = MBB.getNumber();
if (Path[BN] || DoneF[BN])
return false;
if (DoneT[BN])
return true;
auto &CSI = MBB.getParent()->getFrameInfo().getCalleeSavedInfo();
Path[BN] = true;
bool ReachedExit = false;
for (auto &SB : MBB.successors())
ReachedExit |= updateExitPaths(*SB, RestoreB, DoneT, DoneF, Path);
if (!MBB.empty() && MBB.back().isReturn()) {
// Add implicit uses of all callee-saved registers to the reached
// return instructions. This is to prevent the anti-dependency breaker
// from renaming these registers.
MachineInstr &RetI = MBB.back();
if (!isRestoreCall(RetI.getOpcode()))
for (auto &R : CSI)
RetI.addOperand(MachineOperand::CreateReg(R.getReg(), false, true));
ReachedExit = true;
}
// We don't want to add unnecessary live-ins to the restore block: since
// the callee-saved registers are being defined in it, the entry of the
// restore block cannot be on the path from the definitions to any exit.
if (ReachedExit && &MBB != &RestoreB) {
for (auto &R : CSI)
if (!MBB.isLiveIn(R.getReg()))
MBB.addLiveIn(R.getReg());
DoneT[BN] = true;
}
if (!ReachedExit)
DoneF[BN] = true;
Path[BN] = false;
return ReachedExit;
}
static Optional<MachineBasicBlock::iterator>
findCFILocation(MachineBasicBlock &B) {
// The CFI instructions need to be inserted right after allocframe.
// An exception to this is a situation where allocframe is bundled
// with a call: then the CFI instructions need to be inserted before
// the packet with the allocframe+call (in case the call throws an
// exception).
auto End = B.instr_end();
for (MachineInstr &I : B) {
MachineBasicBlock::iterator It = I.getIterator();
if (!I.isBundle()) {