1 //===-- HexagonFrameLowering.cpp - Define frame lowering ------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
9 //===----------------------------------------------------------------------===//
11 #include "HexagonFrameLowering.h"
12 #include "HexagonBlockRanges.h"
13 #include "HexagonInstrInfo.h"
14 #include "HexagonMachineFunctionInfo.h"
15 #include "HexagonRegisterInfo.h"
16 #include "HexagonSubtarget.h"
17 #include "HexagonTargetMachine.h"
18 #include "MCTargetDesc/HexagonBaseInfo.h"
19 #include "llvm/ADT/BitVector.h"
20 #include "llvm/ADT/DenseMap.h"
21 #include "llvm/ADT/None.h"
22 #include "llvm/ADT/Optional.h"
23 #include "llvm/ADT/PostOrderIterator.h"
24 #include "llvm/ADT/SetVector.h"
25 #include "llvm/ADT/SmallSet.h"
26 #include "llvm/ADT/SmallVector.h"
27 #include "llvm/CodeGen/LivePhysRegs.h"
28 #include "llvm/CodeGen/MachineBasicBlock.h"
29 #include "llvm/CodeGen/MachineDominators.h"
30 #include "llvm/CodeGen/MachineFrameInfo.h"
31 #include "llvm/CodeGen/MachineFunction.h"
32 #include "llvm/CodeGen/MachineFunctionPass.h"
33 #include "llvm/CodeGen/MachineInstr.h"
34 #include "llvm/CodeGen/MachineInstrBuilder.h"
35 #include "llvm/CodeGen/MachineMemOperand.h"
36 #include "llvm/CodeGen/MachineModuleInfo.h"
37 #include "llvm/CodeGen/MachineOperand.h"
38 #include "llvm/CodeGen/MachinePostDominators.h"
39 #include "llvm/CodeGen/MachineRegisterInfo.h"
40 #include "llvm/CodeGen/RegisterScavenging.h"
41 #include "llvm/IR/DebugLoc.h"
42 #include "llvm/IR/Function.h"
43 #include "llvm/MC/MCDwarf.h"
44 #include "llvm/MC/MCRegisterInfo.h"
45 #include "llvm/Pass.h"
46 #include "llvm/Support/CodeGen.h"
47 #include "llvm/Support/CommandLine.h"
48 #include "llvm/Support/Debug.h"
49 #include "llvm/Support/ErrorHandling.h"
50 #include "llvm/Support/MathExtras.h"
51 #include "llvm/Support/raw_ostream.h"
52 #include "llvm/Target/TargetMachine.h"
53 #include "llvm/Target/TargetRegisterInfo.h"
64 #define DEBUG_TYPE "hexagon-pei"
66 // Hexagon stack frame layout as defined by the ABI:
72 // SP during function's FP during function's |
73 // +-- runtime (top of stack) runtime (bottom) --+ |
75 // --++---------------------+------------------+-----------------++-+-------
76 // | parameter area for | variable-size | fixed-size |LR| arg
77 // | called functions | local objects | local objects |FP|
78 // --+----------------------+------------------+-----------------+--+-------
79 // <- size known -> <- size unknown -> <- size known ->
81 // Low address High address
86 // - In any circumstances, the outgoing function arguments are always accessi-
87 // ble using the SP, and the incoming arguments are accessible using the FP.
88 // - If the local objects are not aligned, they can always be accessed using
90 // - If there are no variable-sized objects, the local objects can always be
91 // accessed using the SP, regardless whether they are aligned or not. (The
92 // alignment padding will be at the bottom of the stack (highest address),
93 // and so the offset with respect to the SP will be known at the compile-
96 // The only complication occurs if there are both, local aligned objects, and
97 // dynamically allocated (variable-sized) objects. The alignment pad will be
98 // placed between the FP and the local objects, thus preventing the use of the
99 // FP to access the local objects. At the same time, the variable-sized objects
100 // will be between the SP and the local objects, thus introducing an unknown
101 // distance from the SP to the locals.
103 // To avoid this problem, a new register is created that holds the aligned
104 // address of the bottom of the stack, referred in the sources as AP (aligned
105 // pointer). The AP will be equal to "FP-p", where "p" is the smallest pad
106 // that aligns AP to the required boundary (a maximum of the alignments of
107 // all stack objects, fixed- and variable-sized). All local objects[1] will
108 // then use AP as the base pointer.
109 // [1] The exception is with "fixed" stack objects. "Fixed" stack objects get
110 // their name from being allocated at fixed locations on the stack, relative
111 // to the FP. In the presence of dynamic allocation and local alignment, such
112 // objects can only be accessed through the FP.
114 // Illustration of the AP:
117 // ---------------+---------------------+-----+-----------------------++-+--
118 // Rest of the | Local stack objects | Pad | Fixed stack objects |LR|
119 // stack frame | (aligned) | | (CSR, spills, etc.) |FP|
120 // ---------------+---------------------+-----+-----------------+-----+--+--
121 // |<-- Multiple of the -->|
122 // stack alignment +-- AP
124 // The AP is set up at the beginning of the function. Since it is not a dedi-
125 // cated (reserved) register, it needs to be kept live throughout the function
126 // to be available as the base register for local object accesses.
127 // Normally, an address of a stack objects is obtained by a pseudo-instruction
128 // PS_fi. To access local objects with the AP register present, a different
129 // pseudo-instruction needs to be used: PS_fia. The PS_fia takes one extra
130 // argument compared to PS_fi: the first input register is the AP register.
131 // This keeps the register live between its definition and its uses.
133 // The AP register is originally set up using pseudo-instruction PS_aligna:
136 // A - required stack alignment
137 // The alignment value must be the maximum of all alignments required by
140 // The dynamic allocation uses a pseudo-instruction PS_alloca:
141 // Rd = PS_alloca Rs, A
143 // Rd - address of the allocated space
144 // Rs - minimum size (the actual allocated can be larger to accommodate
146 // A - required alignment
148 using namespace llvm;
150 static cl::opt<bool> DisableDeallocRet("disable-hexagon-dealloc-ret",
151 cl::Hidden, cl::desc("Disable Dealloc Return for Hexagon target"));
153 static cl::opt<unsigned> NumberScavengerSlots("number-scavenger-slots",
154 cl::Hidden, cl::desc("Set the number of scavenger slots"), cl::init(2),
157 static cl::opt<int> SpillFuncThreshold("spill-func-threshold",
158 cl::Hidden, cl::desc("Specify O2(not Os) spill func threshold"),
159 cl::init(6), cl::ZeroOrMore);
161 static cl::opt<int> SpillFuncThresholdOs("spill-func-threshold-Os",
162 cl::Hidden, cl::desc("Specify Os spill func threshold"),
163 cl::init(1), cl::ZeroOrMore);
165 static cl::opt<bool> EnableStackOVFSanitizer("enable-stackovf-sanitizer",
166 cl::Hidden, cl::desc("Enable runtime checks for stack overflow."),
167 cl::init(false), cl::ZeroOrMore);
169 static cl::opt<bool> EnableShrinkWrapping("hexagon-shrink-frame",
170 cl::init(true), cl::Hidden, cl::ZeroOrMore,
171 cl::desc("Enable stack frame shrink wrapping"));
173 static cl::opt<unsigned> ShrinkLimit("shrink-frame-limit",
174 cl::init(std::numeric_limits<unsigned>::max()), cl::Hidden, cl::ZeroOrMore,
175 cl::desc("Max count of stack frame shrink-wraps"));
177 static cl::opt<bool> EnableSaveRestoreLong("enable-save-restore-long",
178 cl::Hidden, cl::desc("Enable long calls for save-restore stubs."),
179 cl::init(false), cl::ZeroOrMore);
181 static cl::opt<bool> EliminateFramePointer("hexagon-fp-elim", cl::init(true),
182 cl::Hidden, cl::desc("Refrain from using FP whenever possible"));
184 static cl::opt<bool> OptimizeSpillSlots("hexagon-opt-spill", cl::Hidden,
185 cl::init(true), cl::desc("Optimize spill slots"));
188 static cl::opt<unsigned> SpillOptMax("spill-opt-max", cl::Hidden,
189 cl::init(std::numeric_limits<unsigned>::max()));
190 static unsigned SpillOptCount = 0;
195 void initializeHexagonCallFrameInformationPass(PassRegistry&);
196 FunctionPass *createHexagonCallFrameInformation();
198 } // end namespace llvm
202 class HexagonCallFrameInformation : public MachineFunctionPass {
206 HexagonCallFrameInformation() : MachineFunctionPass(ID) {
207 PassRegistry &PR = *PassRegistry::getPassRegistry();
208 initializeHexagonCallFrameInformationPass(PR);
211 bool runOnMachineFunction(MachineFunction &MF) override;
213 MachineFunctionProperties getRequiredProperties() const override {
214 return MachineFunctionProperties().set(
215 MachineFunctionProperties::Property::NoVRegs);
219 char HexagonCallFrameInformation::ID = 0;
221 } // end anonymous namespace
223 bool HexagonCallFrameInformation::runOnMachineFunction(MachineFunction &MF) {
224 auto &HFI = *MF.getSubtarget<HexagonSubtarget>().getFrameLowering();
225 bool NeedCFI = MF.getMMI().hasDebugInfo() ||
226 MF.getFunction()->needsUnwindTableEntry();
230 HFI.insertCFIInstructions(MF);
234 INITIALIZE_PASS(HexagonCallFrameInformation, "hexagon-cfi",
235 "Hexagon call frame information", false, false)
237 FunctionPass *llvm::createHexagonCallFrameInformation() {
238 return new HexagonCallFrameInformation();
241 /// Map a register pair Reg to the subregister that has the greater "number",
242 /// i.e. D3 (aka R7:6) will be mapped to R7, etc.
243 static unsigned getMax32BitSubRegister(unsigned Reg,
244 const TargetRegisterInfo &TRI,
246 if (Reg < Hexagon::D0 || Reg > Hexagon::D15)
250 for (MCSubRegIterator SubRegs(Reg, &TRI); SubRegs.isValid(); ++SubRegs) {
252 if (*SubRegs > RegNo)
255 if (!RegNo || *SubRegs < RegNo)
262 /// Returns the callee saved register with the largest id in the vector.
263 static unsigned getMaxCalleeSavedReg(const std::vector<CalleeSavedInfo> &CSI,
264 const TargetRegisterInfo &TRI) {
265 static_assert(Hexagon::R1 > 0,
266 "Assume physical registers are encoded as positive integers");
270 unsigned Max = getMax32BitSubRegister(CSI[0].getReg(), TRI);
271 for (unsigned I = 1, E = CSI.size(); I < E; ++I) {
272 unsigned Reg = getMax32BitSubRegister(CSI[I].getReg(), TRI);
279 /// Checks if the basic block contains any instruction that needs a stack
280 /// frame to be already in place.
281 static bool needsStackFrame(const MachineBasicBlock &MBB, const BitVector &CSR,
282 const HexagonRegisterInfo &HRI) {
283 for (auto &I : MBB) {
284 const MachineInstr *MI = &I;
287 unsigned Opc = MI->getOpcode();
289 case Hexagon::PS_alloca:
290 case Hexagon::PS_aligna:
295 // Check individual operands.
296 for (const MachineOperand &MO : MI->operands()) {
297 // While the presence of a frame index does not prove that a stack
298 // frame will be required, all frame indexes should be within alloc-
299 // frame/deallocframe. Otherwise, the code that translates a frame
300 // index into an offset would have to be aware of the placement of
301 // the frame creation/destruction instructions.
305 unsigned R = MO.getReg();
306 // Virtual registers will need scavenging, which then may require
308 if (TargetRegisterInfo::isVirtualRegister(R))
310 for (MCSubRegIterator S(R, &HRI, true); S.isValid(); ++S)
315 if (MO.isRegMask()) {
316 // A regmask would normally have all callee-saved registers marked
317 // as preserved, so this check would not be needed, but in case of
318 // ever having other regmasks (for other calling conventions),
319 // make sure they would be processed correctly.
320 const uint32_t *BM = MO.getRegMask();
321 for (int x = CSR.find_first(); x >= 0; x = CSR.find_next(x)) {
323 // If this regmask does not preserve a CSR, a frame will be needed.
324 if (!(BM[R/32] & (1u << (R%32))))
333 /// Returns true if MBB has a machine instructions that indicates a tail call
335 static bool hasTailCall(const MachineBasicBlock &MBB) {
336 MachineBasicBlock::const_iterator I = MBB.getLastNonDebugInstr();
337 unsigned RetOpc = I->getOpcode();
338 return RetOpc == Hexagon::PS_tailcall_i || RetOpc == Hexagon::PS_tailcall_r;
341 /// Returns true if MBB contains an instruction that returns.
342 static bool hasReturn(const MachineBasicBlock &MBB) {
343 for (auto I = MBB.getFirstTerminator(), E = MBB.end(); I != E; ++I)
349 /// Returns the "return" instruction from this block, or nullptr if there
351 static MachineInstr *getReturn(MachineBasicBlock &MBB) {
358 static bool isRestoreCall(unsigned Opc) {
360 case Hexagon::RESTORE_DEALLOC_RET_JMP_V4:
361 case Hexagon::RESTORE_DEALLOC_RET_JMP_V4_PIC:
362 case Hexagon::RESTORE_DEALLOC_RET_JMP_V4_EXT:
363 case Hexagon::RESTORE_DEALLOC_RET_JMP_V4_EXT_PIC:
364 case Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_EXT:
365 case Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_EXT_PIC:
366 case Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4:
367 case Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_PIC:
373 static inline bool isOptNone(const MachineFunction &MF) {
374 return MF.getFunction()->hasFnAttribute(Attribute::OptimizeNone) ||
375 MF.getTarget().getOptLevel() == CodeGenOpt::None;
378 static inline bool isOptSize(const MachineFunction &MF) {
379 const Function &F = *MF.getFunction();
380 return F.optForSize() && !F.optForMinSize();
383 static inline bool isMinSize(const MachineFunction &MF) {
384 return MF.getFunction()->optForMinSize();
387 /// Implements shrink-wrapping of the stack frame. By default, stack frame
388 /// is created in the function entry block, and is cleaned up in every block
389 /// that returns. This function finds alternate blocks: one for the frame
390 /// setup (prolog) and one for the cleanup (epilog).
391 void HexagonFrameLowering::findShrunkPrologEpilog(MachineFunction &MF,
392 MachineBasicBlock *&PrologB, MachineBasicBlock *&EpilogB) const {
393 static unsigned ShrinkCounter = 0;
395 if (ShrinkLimit.getPosition()) {
396 if (ShrinkCounter >= ShrinkLimit)
401 auto &HST = MF.getSubtarget<HexagonSubtarget>();
402 auto &HRI = *HST.getRegisterInfo();
404 MachineDominatorTree MDT;
405 MDT.runOnMachineFunction(MF);
406 MachinePostDominatorTree MPT;
407 MPT.runOnMachineFunction(MF);
409 typedef DenseMap<unsigned,unsigned> UnsignedMap;
411 typedef ReversePostOrderTraversal<const MachineFunction*> RPOTType;
414 for (RPOTType::rpo_iterator I = RPOT.begin(), E = RPOT.end(); I != E; ++I)
415 RPO[(*I)->getNumber()] = RPON++;
417 // Don't process functions that have loops, at least for now. Placement
418 // of prolog and epilog must take loop structure into account. For simpli-
419 // city don't do it right now.
421 unsigned BN = RPO[I.getNumber()];
422 for (auto SI = I.succ_begin(), SE = I.succ_end(); SI != SE; ++SI) {
423 // If found a back-edge, return.
424 if (RPO[(*SI)->getNumber()] <= BN)
429 // Collect the set of blocks that need a stack frame to execute. Scan
430 // each block for uses/defs of callee-saved registers, calls, etc.
431 SmallVector<MachineBasicBlock*,16> SFBlocks;
432 BitVector CSR(Hexagon::NUM_TARGET_REGS);
433 for (const MCPhysReg *P = HRI.getCalleeSavedRegs(&MF); *P; ++P)
434 for (MCSubRegIterator S(*P, &HRI, true); S.isValid(); ++S)
438 if (needsStackFrame(I, CSR, HRI))
439 SFBlocks.push_back(&I);
442 dbgs() << "Blocks needing SF: {";
443 for (auto &B : SFBlocks)
444 dbgs() << " BB#" << B->getNumber();
448 if (SFBlocks.empty())
451 // Pick a common dominator and a common post-dominator.
452 MachineBasicBlock *DomB = SFBlocks[0];
453 for (unsigned i = 1, n = SFBlocks.size(); i < n; ++i) {
454 DomB = MDT.findNearestCommonDominator(DomB, SFBlocks[i]);
458 MachineBasicBlock *PDomB = SFBlocks[0];
459 for (unsigned i = 1, n = SFBlocks.size(); i < n; ++i) {
460 PDomB = MPT.findNearestCommonDominator(PDomB, SFBlocks[i]);
465 dbgs() << "Computed dom block: BB#";
466 if (DomB) dbgs() << DomB->getNumber();
467 else dbgs() << "<null>";
468 dbgs() << ", computed pdom block: BB#";
469 if (PDomB) dbgs() << PDomB->getNumber();
470 else dbgs() << "<null>";
476 // Make sure that DomB dominates PDomB and PDomB post-dominates DomB.
477 if (!MDT.dominates(DomB, PDomB)) {
478 DEBUG(dbgs() << "Dom block does not dominate pdom block\n");
481 if (!MPT.dominates(PDomB, DomB)) {
482 DEBUG(dbgs() << "PDom block does not post-dominate dom block\n");
486 // Finally, everything seems right.
491 /// Perform most of the PEI work here:
492 /// - saving/restoring of the callee-saved registers,
493 /// - stack frame creation and destruction.
494 /// Normally, this work is distributed among various functions, but doing it
495 /// in one place allows shrink-wrapping of the stack frame.
496 void HexagonFrameLowering::emitPrologue(MachineFunction &MF,
497 MachineBasicBlock &MBB) const {
498 auto &HST = MF.getSubtarget<HexagonSubtarget>();
499 auto &HRI = *HST.getRegisterInfo();
501 MachineFrameInfo &MFI = MF.getFrameInfo();
502 const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
504 MachineBasicBlock *PrologB = &MF.front(), *EpilogB = nullptr;
505 if (EnableShrinkWrapping)
506 findShrunkPrologEpilog(MF, PrologB, EpilogB);
508 bool PrologueStubs = false;
509 insertCSRSpillsInBlock(*PrologB, CSI, HRI, PrologueStubs);
510 insertPrologueInBlock(*PrologB, PrologueStubs);
511 updateEntryPaths(MF, *PrologB);
514 insertCSRRestoresInBlock(*EpilogB, CSI, HRI);
515 insertEpilogueInBlock(*EpilogB);
518 if (B.isReturnBlock())
519 insertCSRRestoresInBlock(B, CSI, HRI);
522 if (B.isReturnBlock())
523 insertEpilogueInBlock(B);
528 MachineInstr *RetI = getReturn(B);
529 if (!RetI || isRestoreCall(RetI->getOpcode()))
532 RetI->addOperand(MachineOperand::CreateReg(R.getReg(), false, true));
537 // If there is an epilog block, it may not have a return instruction.
538 // In such case, we need to add the callee-saved registers as live-ins
539 // in all blocks on all paths from the epilog to any return block.
540 unsigned MaxBN = MF.getNumBlockIDs();
541 BitVector DoneT(MaxBN+1), DoneF(MaxBN+1), Path(MaxBN+1);
542 updateExitPaths(*EpilogB, *EpilogB, DoneT, DoneF, Path);
546 void HexagonFrameLowering::insertPrologueInBlock(MachineBasicBlock &MBB,
547 bool PrologueStubs) const {
548 MachineFunction &MF = *MBB.getParent();
549 MachineFrameInfo &MFI = MF.getFrameInfo();
550 auto &HST = MF.getSubtarget<HexagonSubtarget>();
551 auto &HII = *HST.getInstrInfo();
552 auto &HRI = *HST.getRegisterInfo();
554 unsigned MaxAlign = std::max(MFI.getMaxAlignment(), getStackAlignment());
556 // Calculate the total stack frame size.
557 // Get the number of bytes to allocate from the FrameInfo.
558 unsigned FrameSize = MFI.getStackSize();
559 // Round up the max call frame size to the max alignment on the stack.
560 unsigned MaxCFA = alignTo(MFI.getMaxCallFrameSize(), MaxAlign);
561 MFI.setMaxCallFrameSize(MaxCFA);
563 FrameSize = MaxCFA + alignTo(FrameSize, MaxAlign);
564 MFI.setStackSize(FrameSize);
566 bool AlignStack = (MaxAlign > getStackAlignment());
568 // Get the number of bytes to allocate from the FrameInfo.
569 unsigned NumBytes = MFI.getStackSize();
570 unsigned SP = HRI.getStackRegister();
571 unsigned MaxCF = MFI.getMaxCallFrameSize();
572 MachineBasicBlock::iterator InsertPt = MBB.begin();
574 SmallVector<MachineInstr *, 4> AdjustRegs;
577 if (MI.getOpcode() == Hexagon::PS_alloca)
578 AdjustRegs.push_back(&MI);
580 for (auto MI : AdjustRegs) {
581 assert((MI->getOpcode() == Hexagon::PS_alloca) && "Expected alloca");
582 expandAlloca(MI, HII, SP, MaxCF);
583 MI->eraseFromParent();
586 DebugLoc dl = MBB.findDebugLoc(InsertPt);
589 insertAllocframe(MBB, InsertPt, NumBytes);
591 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::A2_andir), SP)
593 .addImm(-int64_t(MaxAlign));
595 // If the stack-checking is enabled, and we spilled the callee-saved
596 // registers inline (i.e. did not use a spill function), then call
597 // the stack checker directly.
598 if (EnableStackOVFSanitizer && !PrologueStubs)
599 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::PS_call_stk))
600 .addExternalSymbol("__runtime_stack_check");
601 } else if (NumBytes > 0) {
602 assert(alignTo(NumBytes, 8) == NumBytes);
603 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::A2_addi), SP)
605 .addImm(-int(NumBytes));
609 void HexagonFrameLowering::insertEpilogueInBlock(MachineBasicBlock &MBB) const {
610 MachineFunction &MF = *MBB.getParent();
611 auto &HST = MF.getSubtarget<HexagonSubtarget>();
612 auto &HII = *HST.getInstrInfo();
613 auto &HRI = *HST.getRegisterInfo();
614 unsigned SP = HRI.getStackRegister();
616 MachineBasicBlock::iterator InsertPt = MBB.getFirstTerminator();
617 DebugLoc dl = MBB.findDebugLoc(InsertPt);
620 MachineFrameInfo &MFI = MF.getFrameInfo();
621 if (unsigned NumBytes = MFI.getStackSize()) {
622 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::A2_addi), SP)
629 MachineInstr *RetI = getReturn(MBB);
630 unsigned RetOpc = RetI ? RetI->getOpcode() : 0;
633 if (RetOpc == Hexagon::EH_RETURN_JMPR) {
634 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::L2_deallocframe));
635 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::A2_add), SP)
637 .addReg(Hexagon::R28);
641 // Check for RESTORE_DEALLOC_RET* tail call. Don't emit an extra dealloc-
642 // frame instruction if we encounter it.
643 if (RetOpc == Hexagon::RESTORE_DEALLOC_RET_JMP_V4 ||
644 RetOpc == Hexagon::RESTORE_DEALLOC_RET_JMP_V4_PIC ||
645 RetOpc == Hexagon::RESTORE_DEALLOC_RET_JMP_V4_EXT ||
646 RetOpc == Hexagon::RESTORE_DEALLOC_RET_JMP_V4_EXT_PIC) {
647 MachineBasicBlock::iterator It = RetI;
649 // Delete all instructions after the RESTORE (except labels).
650 while (It != MBB.end()) {
659 // It is possible that the restoring code is a call to a library function.
660 // All of the restore* functions include "deallocframe", so we need to make
661 // sure that we don't add an extra one.
662 bool NeedsDeallocframe = true;
663 if (!MBB.empty() && InsertPt != MBB.begin()) {
664 MachineBasicBlock::iterator PrevIt = std::prev(InsertPt);
665 unsigned COpc = PrevIt->getOpcode();
666 if (COpc == Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4 ||
667 COpc == Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_PIC ||
668 COpc == Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_EXT ||
669 COpc == Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_EXT_PIC ||
670 COpc == Hexagon::PS_call_nr || COpc == Hexagon::PS_callr_nr)
671 NeedsDeallocframe = false;
674 if (!NeedsDeallocframe)
676 // If the returning instruction is PS_jmpret, replace it with dealloc_return,
677 // otherwise just add deallocframe. The function could be returning via a
679 if (RetOpc != Hexagon::PS_jmpret || DisableDeallocRet) {
680 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::L2_deallocframe));
683 unsigned NewOpc = Hexagon::L4_return;
684 MachineInstr *NewI = BuildMI(MBB, RetI, dl, HII.get(NewOpc));
685 // Transfer the function live-out registers.
686 NewI->copyImplicitOps(MF, *RetI);
690 void HexagonFrameLowering::insertAllocframe(MachineBasicBlock &MBB,
691 MachineBasicBlock::iterator InsertPt, unsigned NumBytes) const {
692 MachineFunction &MF = *MBB.getParent();
693 auto &HST = MF.getSubtarget<HexagonSubtarget>();
694 auto &HII = *HST.getInstrInfo();
695 auto &HRI = *HST.getRegisterInfo();
697 // Check for overflow.
698 // Hexagon_TODO: Ugh! hardcoding. Is there an API that can be used?
699 const unsigned int ALLOCFRAME_MAX = 16384;
701 // Create a dummy memory operand to avoid allocframe from being treated as
702 // a volatile memory reference.
703 auto *MMO = MF.getMachineMemOperand(MachinePointerInfo::getStack(MF, 0),
704 MachineMemOperand::MOStore, 4, 4);
706 DebugLoc dl = MBB.findDebugLoc(InsertPt);
708 if (NumBytes >= ALLOCFRAME_MAX) {
709 // Emit allocframe(#0).
710 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::S2_allocframe))
714 // Subtract the size from the stack pointer.
715 unsigned SP = HRI.getStackRegister();
716 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::A2_addi), SP)
718 .addImm(-int(NumBytes));
720 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::S2_allocframe))
726 void HexagonFrameLowering::updateEntryPaths(MachineFunction &MF,
727 MachineBasicBlock &SaveB) const {
728 SetVector<unsigned> Worklist;
730 MachineBasicBlock &EntryB = MF.front();
731 Worklist.insert(EntryB.getNumber());
733 unsigned SaveN = SaveB.getNumber();
734 auto &CSI = MF.getFrameInfo().getCalleeSavedInfo();
736 for (unsigned i = 0; i < Worklist.size(); ++i) {
737 unsigned BN = Worklist[i];
738 MachineBasicBlock &MBB = *MF.getBlockNumbered(BN);
740 if (!MBB.isLiveIn(R.getReg()))
741 MBB.addLiveIn(R.getReg());
743 for (auto &SB : MBB.successors())
744 Worklist.insert(SB->getNumber());
748 bool HexagonFrameLowering::updateExitPaths(MachineBasicBlock &MBB,
749 MachineBasicBlock &RestoreB, BitVector &DoneT, BitVector &DoneF,
750 BitVector &Path) const {
751 assert(MBB.getNumber() >= 0);
752 unsigned BN = MBB.getNumber();
753 if (Path[BN] || DoneF[BN])
758 auto &CSI = MBB.getParent()->getFrameInfo().getCalleeSavedInfo();
761 bool ReachedExit = false;
762 for (auto &SB : MBB.successors())
763 ReachedExit |= updateExitPaths(*SB, RestoreB, DoneT, DoneF, Path);
765 if (!MBB.empty() && MBB.back().isReturn()) {
766 // Add implicit uses of all callee-saved registers to the reached
767 // return instructions. This is to prevent the anti-dependency breaker
768 // from renaming these registers.
769 MachineInstr &RetI = MBB.back();
770 if (!isRestoreCall(RetI.getOpcode()))
772 RetI.addOperand(MachineOperand::CreateReg(R.getReg(), false, true));
776 // We don't want to add unnecessary live-ins to the restore block: since
777 // the callee-saved registers are being defined in it, the entry of the
778 // restore block cannot be on the path from the definitions to any exit.
779 if (ReachedExit && &MBB != &RestoreB) {
781 if (!MBB.isLiveIn(R.getReg()))
782 MBB.addLiveIn(R.getReg());
792 static Optional<MachineBasicBlock::iterator>
793 findCFILocation(MachineBasicBlock &B) {
794 // The CFI instructions need to be inserted right after allocframe.
795 // An exception to this is a situation where allocframe is bundled
796 // with a call: then the CFI instructions need to be inserted before
797 // the packet with the allocframe+call (in case the call throws an
799 auto End = B.instr_end();
801 for (MachineInstr &I : B) {
802 MachineBasicBlock::iterator It = I.getIterator();
804 if (I.getOpcode() == Hexagon::S2_allocframe)
805 return std::next(It);
809 bool HasCall = false, HasAllocFrame = false;
810 auto T = It.getInstrIterator();
811 while (++T != End && T->isBundled()) {
812 if (T->getOpcode() == Hexagon::S2_allocframe)
813 HasAllocFrame = true;
814 else if (T->isCall())
818 return HasCall ? It : std::next(It);
823 void HexagonFrameLowering::insertCFIInstructions(MachineFunction &MF) const {
825 auto At = findCFILocation(B);
827 insertCFIInstructionsAt(B, At.getValue());
831 void HexagonFrameLowering::insertCFIInstructionsAt(MachineBasicBlock &MBB,
832 MachineBasicBlock::iterator At) const {
833 MachineFunction &MF = *MBB.getParent();
834 MachineFrameInfo &MFI = MF.getFrameInfo();
835 MachineModuleInfo &MMI = MF.getMMI();
836 auto &HST = MF.getSubtarget<HexagonSubtarget>();
837 auto &HII = *HST.getInstrInfo();
838 auto &HRI = *HST.getRegisterInfo();
840 // If CFI instructions have debug information attached, something goes
841 // wrong with the final assembly generation: the prolog_end is placed
842 // in a wrong location.
844 const MCInstrDesc &CFID = HII.get(TargetOpcode::CFI_INSTRUCTION);
846 MCSymbol *FrameLabel = MMI.getContext().createTempSymbol();
847 bool HasFP = hasFP(MF);
850 unsigned DwFPReg = HRI.getDwarfRegNum(HRI.getFrameRegister(), true);
851 unsigned DwRAReg = HRI.getDwarfRegNum(HRI.getRARegister(), true);
853 // Define CFA via an offset from the value of FP.
856 // --+----+----+---------------------
857 // | FP | LR | increasing addresses -->
858 // --+----+----+---------------------
859 // | +-- Old SP (before allocframe)
860 // +-- New FP (after allocframe)
862 // MCCFIInstruction::createDefCfa subtracts the offset from the register.
863 // MCCFIInstruction::createOffset takes the offset without sign change.
864 auto DefCfa = MCCFIInstruction::createDefCfa(FrameLabel, DwFPReg, -8);
865 BuildMI(MBB, At, DL, CFID)
866 .addCFIIndex(MF.addFrameInst(DefCfa));
867 // R31 (return addr) = CFA - 4
868 auto OffR31 = MCCFIInstruction::createOffset(FrameLabel, DwRAReg, -4);
869 BuildMI(MBB, At, DL, CFID)
870 .addCFIIndex(MF.addFrameInst(OffR31));
871 // R30 (frame ptr) = CFA - 8
872 auto OffR30 = MCCFIInstruction::createOffset(FrameLabel, DwFPReg, -8);
873 BuildMI(MBB, At, DL, CFID)
874 .addCFIIndex(MF.addFrameInst(OffR30));
877 static unsigned int RegsToMove[] = {
878 Hexagon::R1, Hexagon::R0, Hexagon::R3, Hexagon::R2,
879 Hexagon::R17, Hexagon::R16, Hexagon::R19, Hexagon::R18,
880 Hexagon::R21, Hexagon::R20, Hexagon::R23, Hexagon::R22,
881 Hexagon::R25, Hexagon::R24, Hexagon::R27, Hexagon::R26,
882 Hexagon::D0, Hexagon::D1, Hexagon::D8, Hexagon::D9,
883 Hexagon::D10, Hexagon::D11, Hexagon::D12, Hexagon::D13,
887 const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
889 for (unsigned i = 0; RegsToMove[i] != Hexagon::NoRegister; ++i) {
890 unsigned Reg = RegsToMove[i];
891 auto IfR = [Reg] (const CalleeSavedInfo &C) -> bool {
892 return C.getReg() == Reg;
894 auto F = find_if(CSI, IfR);
900 // If the function has a frame pointer (i.e. has an allocframe),
901 // then the CFA has been defined in terms of FP. Any offsets in
902 // the following CFI instructions have to be defined relative
903 // to FP, which points to the bottom of the stack frame.
904 // The function getFrameIndexReference can still choose to use SP
905 // for the offset calculation, so we cannot simply call it here.
906 // Instead, get the offset (relative to the FP) directly.
907 Offset = MFI.getObjectOffset(F->getFrameIdx());
910 Offset = getFrameIndexReference(MF, F->getFrameIdx(), FrameReg);
912 // Subtract 8 to make room for R30 and R31, which are added above.
915 if (Reg < Hexagon::D0 || Reg > Hexagon::D15) {
916 unsigned DwarfReg = HRI.getDwarfRegNum(Reg, true);
917 auto OffReg = MCCFIInstruction::createOffset(FrameLabel, DwarfReg,
919 BuildMI(MBB, At, DL, CFID)
920 .addCFIIndex(MF.addFrameInst(OffReg));
922 // Split the double regs into subregs, and generate appropriate
924 // The only reason, we are split double regs is, llvm-mc does not
925 // understand paired registers for cfi_offset.
926 // Eg .cfi_offset r1:0, -64
928 unsigned HiReg = HRI.getSubReg(Reg, Hexagon::isub_hi);
929 unsigned LoReg = HRI.getSubReg(Reg, Hexagon::isub_lo);
930 unsigned HiDwarfReg = HRI.getDwarfRegNum(HiReg, true);
931 unsigned LoDwarfReg = HRI.getDwarfRegNum(LoReg, true);
932 auto OffHi = MCCFIInstruction::createOffset(FrameLabel, HiDwarfReg,
934 BuildMI(MBB, At, DL, CFID)
935 .addCFIIndex(MF.addFrameInst(OffHi));
936 auto OffLo = MCCFIInstruction::createOffset(FrameLabel, LoDwarfReg,
938 BuildMI(MBB, At, DL, CFID)
939 .addCFIIndex(MF.addFrameInst(OffLo));
944 bool HexagonFrameLowering::hasFP(const MachineFunction &MF) const {
945 if (MF.getFunction()->hasFnAttribute(Attribute::Naked))
948 auto &MFI = MF.getFrameInfo();
949 auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
950 bool HasExtraAlign = HRI.needsStackRealignment(MF);
951 bool HasAlloca = MFI.hasVarSizedObjects();
953 // Insert ALLOCFRAME if we need to or at -O0 for the debugger. Think
954 // that this shouldn't be required, but doing so now because gcc does and
955 // gdb can't break at the start of the function without it. Will remove if
956 // this turns out to be a gdb bug.
958 if (MF.getTarget().getOptLevel() == CodeGenOpt::None)
961 // By default we want to use SP (since it's always there). FP requires
962 // some setup (i.e. ALLOCFRAME).
963 // Both, alloca and stack alignment modify the stack pointer by an
964 // undetermined value, so we need to save it at the entry to the function
965 // (i.e. use allocframe).
966 if (HasAlloca || HasExtraAlign)
969 if (MFI.getStackSize() > 0) {
970 // If FP-elimination is disabled, we have to use FP at this point.
971 const TargetMachine &TM = MF.getTarget();
972 if (TM.Options.DisableFramePointerElim(MF) || !EliminateFramePointer)
974 if (EnableStackOVFSanitizer)
978 const auto &HMFI = *MF.getInfo<HexagonMachineFunctionInfo>();
979 if (MFI.hasCalls() || HMFI.hasClobberLR())
991 static const char *getSpillFunctionFor(unsigned MaxReg, SpillKind SpillType,
992 bool Stkchk = false) {
993 const char * V4SpillToMemoryFunctions[] = {
994 "__save_r16_through_r17",
995 "__save_r16_through_r19",
996 "__save_r16_through_r21",
997 "__save_r16_through_r23",
998 "__save_r16_through_r25",
999 "__save_r16_through_r27" };
1001 const char * V4SpillToMemoryStkchkFunctions[] = {
1002 "__save_r16_through_r17_stkchk",
1003 "__save_r16_through_r19_stkchk",
1004 "__save_r16_through_r21_stkchk",
1005 "__save_r16_through_r23_stkchk",
1006 "__save_r16_through_r25_stkchk",
1007 "__save_r16_through_r27_stkchk" };
1009 const char * V4SpillFromMemoryFunctions[] = {
1010 "__restore_r16_through_r17_and_deallocframe",
1011 "__restore_r16_through_r19_and_deallocframe",
1012 "__restore_r16_through_r21_and_deallocframe",
1013 "__restore_r16_through_r23_and_deallocframe",
1014 "__restore_r16_through_r25_and_deallocframe",
1015 "__restore_r16_through_r27_and_deallocframe" };
1017 const char * V4SpillFromMemoryTailcallFunctions[] = {
1018 "__restore_r16_through_r17_and_deallocframe_before_tailcall",
1019 "__restore_r16_through_r19_and_deallocframe_before_tailcall",
1020 "__restore_r16_through_r21_and_deallocframe_before_tailcall",
1021 "__restore_r16_through_r23_and_deallocframe_before_tailcall",
1022 "__restore_r16_through_r25_and_deallocframe_before_tailcall",
1023 "__restore_r16_through_r27_and_deallocframe_before_tailcall"
1026 const char **SpillFunc = nullptr;
1030 SpillFunc = Stkchk ? V4SpillToMemoryStkchkFunctions
1031 : V4SpillToMemoryFunctions;
1034 SpillFunc = V4SpillFromMemoryFunctions;
1036 case SK_FromMemTailcall:
1037 SpillFunc = V4SpillFromMemoryTailcallFunctions;
1040 assert(SpillFunc && "Unknown spill kind");
1042 // Spill all callee-saved registers up to the highest register used.
1045 return SpillFunc[0];
1047 return SpillFunc[1];
1049 return SpillFunc[2];
1051 return SpillFunc[3];
1053 return SpillFunc[4];
1055 return SpillFunc[5];
1057 llvm_unreachable("Unhandled maximum callee save register");
1062 int HexagonFrameLowering::getFrameIndexReference(const MachineFunction &MF,
1063 int FI, unsigned &FrameReg) const {
1064 auto &MFI = MF.getFrameInfo();
1065 auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
1067 int Offset = MFI.getObjectOffset(FI);
1068 bool HasAlloca = MFI.hasVarSizedObjects();
1069 bool HasExtraAlign = HRI.needsStackRealignment(MF);
1070 bool NoOpt = MF.getTarget().getOptLevel() == CodeGenOpt::None;
1072 auto &HMFI = *MF.getInfo<HexagonMachineFunctionInfo>();
1073 unsigned FrameSize = MFI.getStackSize();
1074 unsigned SP = HRI.getStackRegister();
1075 unsigned FP = HRI.getFrameRegister();
1076 unsigned AP = HMFI.getStackAlignBasePhysReg();
1077 // It may happen that AP will be absent even HasAlloca && HasExtraAlign
1078 // is true. HasExtraAlign may be set because of vector spills, without
1079 // aligned locals or aligned outgoing function arguments. Since vector
1080 // spills will ultimately be "unaligned", it is safe to use FP as the
1082 // In fact, in such a scenario the stack is actually not required to be
1083 // aligned, although it may end up being aligned anyway, since this
1084 // particular case is not easily detectable. The alignment will be
1085 // unnecessary, but not incorrect.
1086 // Unfortunately there is no quick way to verify that the above is
1087 // indeed the case (and that it's not a result of an error), so just
1088 // assume that missing AP will be replaced by FP.
1089 // (A better fix would be to rematerialize AP from FP and always align
1094 bool UseFP = false, UseAP = false; // Default: use SP (except at -O0).
1095 // Use FP at -O0, except when there are objects with extra alignment.
1096 // That additional alignment requirement may cause a pad to be inserted,
1097 // which will make it impossible to use FP to access objects located
1099 if (NoOpt && !HasExtraAlign)
1101 if (MFI.isFixedObjectIndex(FI) || MFI.isObjectPreAllocated(FI)) {
1102 // Fixed and preallocated objects will be located before any padding
1103 // so FP must be used to access them.
1104 UseFP |= (HasAlloca || HasExtraAlign);
1114 // If FP was picked, then there had better be FP.
1115 bool HasFP = hasFP(MF);
1116 assert((HasFP || !UseFP) && "This function must have frame pointer");
1118 // Having FP implies allocframe. Allocframe will store extra 8 bytes:
1119 // FP/LR. If the base register is used to access an object across these
1120 // 8 bytes, then the offset will need to be adjusted by 8.
1122 // After allocframe:
1123 // HexagonISelLowering adds 8 to ---+
1124 // the offsets of all stack-based |
1127 // getObjectOffset < 0 0 8 getObjectOffset >= 8
1128 // ------------------------+-----+------------------------> increasing
1129 // <local objects> |FP/LR| <input arguments> addresses
1130 // -----------------+------+-----+------------------------>
1132 // SP/AP point --+ +-- FP points here (**)
1134 // this side of FP/LR
1136 // (*) See LowerFormalArguments. The FP/LR is assumed to be present.
1137 // (**) *FP == old-FP. FP+0..7 are the bytes of FP/LR.
1139 // The lowering assumes that FP/LR is present, and so the offsets of
1140 // the formal arguments start at 8. If FP/LR is not there we need to
1141 // reduce the offset by 8.
1142 if (Offset > 0 && !HasFP)
1152 // Calculate the actual offset in the instruction. If there is no FP
1153 // (in other words, no allocframe), then SP will not be adjusted (i.e.
1154 // there will be no SP -= FrameSize), so the frame size should not be
1155 // added to the calculated offset.
1156 int RealOffset = Offset;
1157 if (!UseFP && !UseAP)
1158 RealOffset = FrameSize+Offset;
1162 bool HexagonFrameLowering::insertCSRSpillsInBlock(MachineBasicBlock &MBB,
1163 const CSIVect &CSI, const HexagonRegisterInfo &HRI,
1164 bool &PrologueStubs) const {
1168 MachineBasicBlock::iterator MI = MBB.begin();
1169 PrologueStubs = false;
1170 MachineFunction &MF = *MBB.getParent();
1171 auto &HST = MF.getSubtarget<HexagonSubtarget>();
1172 auto &HII = *HST.getInstrInfo();
1174 if (useSpillFunction(MF, CSI)) {
1175 PrologueStubs = true;
1176 unsigned MaxReg = getMaxCalleeSavedReg(CSI, HRI);
1177 bool StkOvrFlowEnabled = EnableStackOVFSanitizer;
1178 const char *SpillFun = getSpillFunctionFor(MaxReg, SK_ToMem,
1180 auto &HTM = static_cast<const HexagonTargetMachine&>(MF.getTarget());
1181 bool IsPIC = HTM.isPositionIndependent();
1182 bool LongCalls = HST.useLongCalls() || EnableSaveRestoreLong;
1184 // Call spill function.
1185 DebugLoc DL = MI != MBB.end() ? MI->getDebugLoc() : DebugLoc();
1187 if (StkOvrFlowEnabled) {
1189 SpillOpc = IsPIC ? Hexagon::SAVE_REGISTERS_CALL_V4STK_EXT_PIC
1190 : Hexagon::SAVE_REGISTERS_CALL_V4STK_EXT;
1192 SpillOpc = IsPIC ? Hexagon::SAVE_REGISTERS_CALL_V4STK_PIC
1193 : Hexagon::SAVE_REGISTERS_CALL_V4STK;
1196 SpillOpc = IsPIC ? Hexagon::SAVE_REGISTERS_CALL_V4_EXT_PIC
1197 : Hexagon::SAVE_REGISTERS_CALL_V4_EXT;
1199 SpillOpc = IsPIC ? Hexagon::SAVE_REGISTERS_CALL_V4_PIC
1200 : Hexagon::SAVE_REGISTERS_CALL_V4;
1203 MachineInstr *SaveRegsCall =
1204 BuildMI(MBB, MI, DL, HII.get(SpillOpc))
1205 .addExternalSymbol(SpillFun);
1207 // Add callee-saved registers as use.
1208 addCalleeSaveRegistersAsImpOperand(SaveRegsCall, CSI, false, true);
1209 // Add live in registers.
1210 for (unsigned I = 0; I < CSI.size(); ++I)
1211 MBB.addLiveIn(CSI[I].getReg());
1215 for (unsigned i = 0, n = CSI.size(); i < n; ++i) {
1216 unsigned Reg = CSI[i].getReg();
1217 // Add live in registers. We treat eh_return callee saved register r0 - r3
1218 // specially. They are not really callee saved registers as they are not
1219 // supposed to be killed.
1220 bool IsKill = !HRI.isEHReturnCalleeSaveReg(Reg);
1221 int FI = CSI[i].getFrameIdx();
1222 const TargetRegisterClass *RC = HRI.getMinimalPhysRegClass(Reg);
1223 HII.storeRegToStackSlot(MBB, MI, Reg, IsKill, FI, RC, &HRI);
1230 bool HexagonFrameLowering::insertCSRRestoresInBlock(MachineBasicBlock &MBB,
1231 const CSIVect &CSI, const HexagonRegisterInfo &HRI) const {
1235 MachineBasicBlock::iterator MI = MBB.getFirstTerminator();
1236 MachineFunction &MF = *MBB.getParent();
1237 auto &HST = MF.getSubtarget<HexagonSubtarget>();
1238 auto &HII = *HST.getInstrInfo();
1240 if (useRestoreFunction(MF, CSI)) {
1241 bool HasTC = hasTailCall(MBB) || !hasReturn(MBB);
1242 unsigned MaxR = getMaxCalleeSavedReg(CSI, HRI);
1243 SpillKind Kind = HasTC ? SK_FromMemTailcall : SK_FromMem;
1244 const char *RestoreFn = getSpillFunctionFor(MaxR, Kind);
1245 auto &HTM = static_cast<const HexagonTargetMachine&>(MF.getTarget());
1246 bool IsPIC = HTM.isPositionIndependent();
1247 bool LongCalls = HST.useLongCalls() || EnableSaveRestoreLong;
1249 // Call spill function.
1250 DebugLoc DL = MI != MBB.end() ? MI->getDebugLoc()
1251 : MBB.getLastNonDebugInstr()->getDebugLoc();
1252 MachineInstr *DeallocCall = nullptr;
1257 RetOpc = IsPIC ? Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_EXT_PIC
1258 : Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_EXT;
1260 RetOpc = IsPIC ? Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_PIC
1261 : Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4;
1262 DeallocCall = BuildMI(MBB, MI, DL, HII.get(RetOpc))
1263 .addExternalSymbol(RestoreFn);
1265 // The block has a return.
1266 MachineBasicBlock::iterator It = MBB.getFirstTerminator();
1267 assert(It->isReturn() && std::next(It) == MBB.end());
1270 RetOpc = IsPIC ? Hexagon::RESTORE_DEALLOC_RET_JMP_V4_EXT_PIC
1271 : Hexagon::RESTORE_DEALLOC_RET_JMP_V4_EXT;
1273 RetOpc = IsPIC ? Hexagon::RESTORE_DEALLOC_RET_JMP_V4_PIC
1274 : Hexagon::RESTORE_DEALLOC_RET_JMP_V4;
1275 DeallocCall = BuildMI(MBB, It, DL, HII.get(RetOpc))
1276 .addExternalSymbol(RestoreFn);
1277 // Transfer the function live-out registers.
1278 DeallocCall->copyImplicitOps(MF, *It);
1280 addCalleeSaveRegistersAsImpOperand(DeallocCall, CSI, true, false);
1284 for (unsigned i = 0; i < CSI.size(); ++i) {
1285 unsigned Reg = CSI[i].getReg();
1286 const TargetRegisterClass *RC = HRI.getMinimalPhysRegClass(Reg);
1287 int FI = CSI[i].getFrameIdx();
1288 HII.loadRegFromStackSlot(MBB, MI, Reg, FI, RC, &HRI);
1294 MachineBasicBlock::iterator HexagonFrameLowering::eliminateCallFramePseudoInstr(
1295 MachineFunction &MF, MachineBasicBlock &MBB,
1296 MachineBasicBlock::iterator I) const {
1297 MachineInstr &MI = *I;
1298 unsigned Opc = MI.getOpcode();
1299 (void)Opc; // Silence compiler warning.
1300 assert((Opc == Hexagon::ADJCALLSTACKDOWN || Opc == Hexagon::ADJCALLSTACKUP) &&
1301 "Cannot handle this call frame pseudo instruction");
1302 return MBB.erase(I);
1305 void HexagonFrameLowering::processFunctionBeforeFrameFinalized(
1306 MachineFunction &MF, RegScavenger *RS) const {
1307 // If this function has uses aligned stack and also has variable sized stack
1308 // objects, then we need to map all spill slots to fixed positions, so that
1309 // they can be accessed through FP. Otherwise they would have to be accessed
1310 // via AP, which may not be available at the particular place in the program.
1311 MachineFrameInfo &MFI = MF.getFrameInfo();
1312 bool HasAlloca = MFI.hasVarSizedObjects();
1313 bool NeedsAlign = (MFI.getMaxAlignment() > getStackAlignment());
1315 if (!HasAlloca || !NeedsAlign)
1318 unsigned LFS = MFI.getLocalFrameSize();
1319 for (int i = 0, e = MFI.getObjectIndexEnd(); i != e; ++i) {
1320 if (!MFI.isSpillSlotObjectIndex(i) || MFI.isDeadObjectIndex(i))
1322 unsigned S = MFI.getObjectSize(i);
1323 // Reduce the alignment to at most 8. This will require unaligned vector
1324 // stores if they happen here.
1325 unsigned A = std::max(MFI.getObjectAlignment(i), 8U);
1326 MFI.setObjectAlignment(i, 8);
1327 LFS = alignTo(LFS+S, A);
1328 MFI.mapLocalFrameObject(i, -LFS);
1331 MFI.setLocalFrameSize(LFS);
1332 unsigned A = MFI.getLocalFrameMaxAlign();
1333 assert(A <= 8 && "Unexpected local frame alignment");
1335 MFI.setLocalFrameMaxAlign(8);
1336 MFI.setUseLocalStackAllocationBlock(true);
1338 // Set the physical aligned-stack base address register.
1340 if (const MachineInstr *AI = getAlignaInstr(MF))
1341 AP = AI->getOperand(0).getReg();
1342 auto &HMFI = *MF.getInfo<HexagonMachineFunctionInfo>();
1343 HMFI.setStackAlignBasePhysReg(AP);
1346 /// Returns true if there are no caller-saved registers available in class RC.
1347 static bool needToReserveScavengingSpillSlots(MachineFunction &MF,
1348 const HexagonRegisterInfo &HRI, const TargetRegisterClass *RC) {
1349 MachineRegisterInfo &MRI = MF.getRegInfo();
1351 auto IsUsed = [&HRI,&MRI] (unsigned Reg) -> bool {
1352 for (MCRegAliasIterator AI(Reg, &HRI, true); AI.isValid(); ++AI)
1353 if (MRI.isPhysRegUsed(*AI))
1358 // Check for an unused caller-saved register. Callee-saved registers
1359 // have become pristine by now.
1360 for (const MCPhysReg *P = HRI.getCallerSavedRegs(&MF, RC); *P; ++P)
1364 // All caller-saved registers are used.
1369 static void dump_registers(BitVector &Regs, const TargetRegisterInfo &TRI) {
1371 for (int x = Regs.find_first(); x >= 0; x = Regs.find_next(x)) {
1373 dbgs() << ' ' << PrintReg(R, &TRI);
1379 bool HexagonFrameLowering::assignCalleeSavedSpillSlots(MachineFunction &MF,
1380 const TargetRegisterInfo *TRI, std::vector<CalleeSavedInfo> &CSI) const {
1381 DEBUG(dbgs() << __func__ << " on "
1382 << MF.getFunction()->getName() << '\n');
1383 MachineFrameInfo &MFI = MF.getFrameInfo();
1384 BitVector SRegs(Hexagon::NUM_TARGET_REGS);
1386 // Generate a set of unique, callee-saved registers (SRegs), where each
1387 // register in the set is maximal in terms of sub-/super-register relation,
1388 // i.e. for each R in SRegs, no proper super-register of R is also in SRegs.
1390 // (1) For each callee-saved register, add that register and all of its
1391 // sub-registers to SRegs.
1392 DEBUG(dbgs() << "Initial CS registers: {");
1393 for (unsigned i = 0, n = CSI.size(); i < n; ++i) {
1394 unsigned R = CSI[i].getReg();
1395 DEBUG(dbgs() << ' ' << PrintReg(R, TRI));
1396 for (MCSubRegIterator SR(R, TRI, true); SR.isValid(); ++SR)
1399 DEBUG(dbgs() << " }\n");
1400 DEBUG(dbgs() << "SRegs.1: "; dump_registers(SRegs, *TRI); dbgs() << "\n");
1402 // (2) For each reserved register, remove that register and all of its
1403 // sub- and super-registers from SRegs.
1404 BitVector Reserved = TRI->getReservedRegs(MF);
1405 for (int x = Reserved.find_first(); x >= 0; x = Reserved.find_next(x)) {
1407 for (MCSuperRegIterator SR(R, TRI, true); SR.isValid(); ++SR)
1410 DEBUG(dbgs() << "Res: "; dump_registers(Reserved, *TRI); dbgs() << "\n");
1411 DEBUG(dbgs() << "SRegs.2: "; dump_registers(SRegs, *TRI); dbgs() << "\n");
1413 // (3) Collect all registers that have at least one sub-register in SRegs,
1414 // and also have no sub-registers that are reserved. These will be the can-
1415 // didates for saving as a whole instead of their individual sub-registers.
1416 // (Saving R17:16 instead of R16 is fine, but only if R17 was not reserved.)
1417 BitVector TmpSup(Hexagon::NUM_TARGET_REGS);
1418 for (int x = SRegs.find_first(); x >= 0; x = SRegs.find_next(x)) {
1420 for (MCSuperRegIterator SR(R, TRI); SR.isValid(); ++SR)
1423 for (int x = TmpSup.find_first(); x >= 0; x = TmpSup.find_next(x)) {
1425 for (MCSubRegIterator SR(R, TRI, true); SR.isValid(); ++SR) {
1432 DEBUG(dbgs() << "TmpSup: "; dump_registers(TmpSup, *TRI); dbgs() << "\n");
1434 // (4) Include all super-registers found in (3) into SRegs.
1436 DEBUG(dbgs() << "SRegs.4: "; dump_registers(SRegs, *TRI); dbgs() << "\n");
1438 // (5) For each register R in SRegs, if any super-register of R is in SRegs,
1439 // remove R from SRegs.
1440 for (int x = SRegs.find_first(); x >= 0; x = SRegs.find_next(x)) {
1442 for (MCSuperRegIterator SR(R, TRI); SR.isValid(); ++SR) {
1449 DEBUG(dbgs() << "SRegs.5: "; dump_registers(SRegs, *TRI); dbgs() << "\n");
1451 // Now, for each register that has a fixed stack slot, create the stack
1455 typedef TargetFrameLowering::SpillSlot SpillSlot;
1457 int MinOffset = 0; // CS offsets are negative.
1458 const SpillSlot *FixedSlots = getCalleeSavedSpillSlots(NumFixed);
1459 for (const SpillSlot *S = FixedSlots; S != FixedSlots+NumFixed; ++S) {
1462 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(S->Reg);
1463 int FI = MFI.CreateFixedSpillStackObject(TRI->getSpillSize(*RC), S->Offset);
1464 MinOffset = std::min(MinOffset, S->Offset);
1465 CSI.push_back(CalleeSavedInfo(S->Reg, FI));
1466 SRegs[S->Reg] = false;
1469 // There can be some registers that don't have fixed slots. For example,
1470 // we need to store R0-R3 in functions with exception handling. For each
1471 // such register, create a non-fixed stack object.
1472 for (int x = SRegs.find_first(); x >= 0; x = SRegs.find_next(x)) {
1474 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(R);
1475 unsigned Size = TRI->getSpillSize(*RC);
1476 int Off = MinOffset - Size;
1477 unsigned Align = std::min(TRI->getSpillAlignment(*RC), getStackAlignment());
1478 assert(isPowerOf2_32(Align));
1480 int FI = MFI.CreateFixedSpillStackObject(Size, Off);
1481 MinOffset = std::min(MinOffset, Off);
1482 CSI.push_back(CalleeSavedInfo(R, FI));
1487 dbgs() << "CS information: {";
1488 for (unsigned i = 0, n = CSI.size(); i < n; ++i) {
1489 int FI = CSI[i].getFrameIdx();
1490 int Off = MFI.getObjectOffset(FI);
1491 dbgs() << ' ' << PrintReg(CSI[i].getReg(), TRI) << ":fi#" << FI << ":sp";
1500 // Verify that all registers were handled.
1501 bool MissedReg = false;
1502 for (int x = SRegs.find_first(); x >= 0; x = SRegs.find_next(x)) {
1504 dbgs() << PrintReg(R, TRI) << ' ';
1508 llvm_unreachable("...there are unhandled callee-saved registers!");
1514 bool HexagonFrameLowering::expandCopy(MachineBasicBlock &B,
1515 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1516 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1517 MachineInstr *MI = &*It;
1518 DebugLoc DL = MI->getDebugLoc();
1519 unsigned DstR = MI->getOperand(0).getReg();
1520 unsigned SrcR = MI->getOperand(1).getReg();
1521 if (!Hexagon::ModRegsRegClass.contains(DstR) ||
1522 !Hexagon::ModRegsRegClass.contains(SrcR))
1525 unsigned TmpR = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
1526 BuildMI(B, It, DL, HII.get(TargetOpcode::COPY), TmpR).add(MI->getOperand(1));
1527 BuildMI(B, It, DL, HII.get(TargetOpcode::COPY), DstR)
1528 .addReg(TmpR, RegState::Kill);
1530 NewRegs.push_back(TmpR);
1535 bool HexagonFrameLowering::expandStoreInt(MachineBasicBlock &B,
1536 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1537 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1538 MachineInstr *MI = &*It;
1539 if (!MI->getOperand(0).isFI())
1542 DebugLoc DL = MI->getDebugLoc();
1543 unsigned Opc = MI->getOpcode();
1544 unsigned SrcR = MI->getOperand(2).getReg();
1545 bool IsKill = MI->getOperand(2).isKill();
1546 int FI = MI->getOperand(0).getIndex();
1548 // TmpR = C2_tfrpr SrcR if SrcR is a predicate register
1549 // TmpR = A2_tfrcrr SrcR if SrcR is a modifier register
1550 unsigned TmpR = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
1551 unsigned TfrOpc = (Opc == Hexagon::STriw_pred) ? Hexagon::C2_tfrpr
1552 : Hexagon::A2_tfrcrr;
1553 BuildMI(B, It, DL, HII.get(TfrOpc), TmpR)
1554 .addReg(SrcR, getKillRegState(IsKill));
1556 // S2_storeri_io FI, 0, TmpR
1557 BuildMI(B, It, DL, HII.get(Hexagon::S2_storeri_io))
1560 .addReg(TmpR, RegState::Kill)
1561 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1563 NewRegs.push_back(TmpR);
1568 bool HexagonFrameLowering::expandLoadInt(MachineBasicBlock &B,
1569 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1570 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1571 MachineInstr *MI = &*It;
1572 if (!MI->getOperand(1).isFI())
1575 DebugLoc DL = MI->getDebugLoc();
1576 unsigned Opc = MI->getOpcode();
1577 unsigned DstR = MI->getOperand(0).getReg();
1578 int FI = MI->getOperand(1).getIndex();
1580 // TmpR = L2_loadri_io FI, 0
1581 unsigned TmpR = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
1582 BuildMI(B, It, DL, HII.get(Hexagon::L2_loadri_io), TmpR)
1585 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1587 // DstR = C2_tfrrp TmpR if DstR is a predicate register
1588 // DstR = A2_tfrrcr TmpR if DstR is a modifier register
1589 unsigned TfrOpc = (Opc == Hexagon::LDriw_pred) ? Hexagon::C2_tfrrp
1590 : Hexagon::A2_tfrrcr;
1591 BuildMI(B, It, DL, HII.get(TfrOpc), DstR)
1592 .addReg(TmpR, RegState::Kill);
1594 NewRegs.push_back(TmpR);
1599 bool HexagonFrameLowering::expandStoreVecPred(MachineBasicBlock &B,
1600 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1601 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1602 auto &HST = B.getParent()->getSubtarget<HexagonSubtarget>();
1603 MachineInstr *MI = &*It;
1604 if (!MI->getOperand(0).isFI())
1607 DebugLoc DL = MI->getDebugLoc();
1608 unsigned SrcR = MI->getOperand(2).getReg();
1609 bool IsKill = MI->getOperand(2).isKill();
1610 int FI = MI->getOperand(0).getIndex();
1612 bool Is128B = HST.useHVXDblOps();
1613 auto *RC = !Is128B ? &Hexagon::VectorRegsRegClass
1614 : &Hexagon::VectorRegs128BRegClass;
1616 // Insert transfer to general vector register.
1617 // TmpR0 = A2_tfrsi 0x01010101
1618 // TmpR1 = V6_vandqrt Qx, TmpR0
1619 // store FI, 0, TmpR1
1620 unsigned TmpR0 = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
1621 unsigned TmpR1 = MRI.createVirtualRegister(RC);
1623 BuildMI(B, It, DL, HII.get(Hexagon::A2_tfrsi), TmpR0)
1624 .addImm(0x01010101);
1626 unsigned VandOpc = !Is128B ? Hexagon::V6_vandqrt : Hexagon::V6_vandqrt_128B;
1627 BuildMI(B, It, DL, HII.get(VandOpc), TmpR1)
1628 .addReg(SrcR, getKillRegState(IsKill))
1629 .addReg(TmpR0, RegState::Kill);
1631 auto *HRI = B.getParent()->getSubtarget<HexagonSubtarget>().getRegisterInfo();
1632 HII.storeRegToStackSlot(B, It, TmpR1, true, FI, RC, HRI);
1633 expandStoreVec(B, std::prev(It), MRI, HII, NewRegs);
1635 NewRegs.push_back(TmpR0);
1636 NewRegs.push_back(TmpR1);
1641 bool HexagonFrameLowering::expandLoadVecPred(MachineBasicBlock &B,
1642 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1643 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1644 auto &HST = B.getParent()->getSubtarget<HexagonSubtarget>();
1645 MachineInstr *MI = &*It;
1646 if (!MI->getOperand(1).isFI())
1649 DebugLoc DL = MI->getDebugLoc();
1650 unsigned DstR = MI->getOperand(0).getReg();
1651 int FI = MI->getOperand(1).getIndex();
1653 bool Is128B = HST.useHVXDblOps();
1654 auto *RC = !Is128B ? &Hexagon::VectorRegsRegClass
1655 : &Hexagon::VectorRegs128BRegClass;
1657 // TmpR0 = A2_tfrsi 0x01010101
1658 // TmpR1 = load FI, 0
1659 // DstR = V6_vandvrt TmpR1, TmpR0
1660 unsigned TmpR0 = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
1661 unsigned TmpR1 = MRI.createVirtualRegister(RC);
1663 BuildMI(B, It, DL, HII.get(Hexagon::A2_tfrsi), TmpR0)
1664 .addImm(0x01010101);
1665 auto *HRI = B.getParent()->getSubtarget<HexagonSubtarget>().getRegisterInfo();
1666 HII.loadRegFromStackSlot(B, It, TmpR1, FI, RC, HRI);
1667 expandLoadVec(B, std::prev(It), MRI, HII, NewRegs);
1669 unsigned VandOpc = !Is128B ? Hexagon::V6_vandvrt : Hexagon::V6_vandvrt_128B;
1670 BuildMI(B, It, DL, HII.get(VandOpc), DstR)
1671 .addReg(TmpR1, RegState::Kill)
1672 .addReg(TmpR0, RegState::Kill);
1674 NewRegs.push_back(TmpR0);
1675 NewRegs.push_back(TmpR1);
1680 bool HexagonFrameLowering::expandStoreVec2(MachineBasicBlock &B,
1681 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1682 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1683 MachineFunction &MF = *B.getParent();
1684 auto &HST = MF.getSubtarget<HexagonSubtarget>();
1685 auto &MFI = MF.getFrameInfo();
1686 auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
1687 MachineInstr *MI = &*It;
1688 if (!MI->getOperand(0).isFI())
1691 // It is possible that the double vector being stored is only partially
1692 // defined. From the point of view of the liveness tracking, it is ok to
1693 // store it as a whole, but if we break it up we may end up storing a
1694 // register that is entirely undefined.
1695 LivePhysRegs LPR(HRI);
1697 SmallVector<std::pair<unsigned, const MachineOperand*>,2> Clobbers;
1698 for (auto R = B.begin(); R != It; ++R) {
1700 LPR.stepForward(*R, Clobbers);
1701 // Dead defs are recorded in Clobbers, but are not automatically removed
1702 // from the live set.
1703 for (auto &C : Clobbers)
1704 if (C.second->isReg() && C.second->isDead())
1705 LPR.removeReg(C.first);
1708 DebugLoc DL = MI->getDebugLoc();
1709 unsigned SrcR = MI->getOperand(2).getReg();
1710 unsigned SrcLo = HRI.getSubReg(SrcR, Hexagon::vsub_lo);
1711 unsigned SrcHi = HRI.getSubReg(SrcR, Hexagon::vsub_hi);
1712 bool IsKill = MI->getOperand(2).isKill();
1713 int FI = MI->getOperand(0).getIndex();
1715 bool Is128B = HST.useHVXDblOps();
1716 const auto &RC = !Is128B ? Hexagon::VectorRegsRegClass
1717 : Hexagon::VectorRegs128BRegClass;
1718 unsigned Size = HRI.getSpillSize(RC);
1719 unsigned NeedAlign = HRI.getSpillAlignment(RC);
1720 unsigned HasAlign = MFI.getObjectAlignment(FI);
1724 if (LPR.contains(SrcLo)) {
1725 if (NeedAlign <= HasAlign)
1726 StoreOpc = !Is128B ? Hexagon::V6_vS32b_ai : Hexagon::V6_vS32b_ai_128B;
1728 StoreOpc = !Is128B ? Hexagon::V6_vS32Ub_ai : Hexagon::V6_vS32Ub_ai_128B;
1730 BuildMI(B, It, DL, HII.get(StoreOpc))
1733 .addReg(SrcLo, getKillRegState(IsKill))
1734 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1738 if (LPR.contains(SrcHi)) {
1739 if (NeedAlign <= MinAlign(HasAlign, Size))
1740 StoreOpc = !Is128B ? Hexagon::V6_vS32b_ai : Hexagon::V6_vS32b_ai_128B;
1742 StoreOpc = !Is128B ? Hexagon::V6_vS32Ub_ai : Hexagon::V6_vS32Ub_ai_128B;
1744 BuildMI(B, It, DL, HII.get(StoreOpc))
1747 .addReg(SrcHi, getKillRegState(IsKill))
1748 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1755 bool HexagonFrameLowering::expandLoadVec2(MachineBasicBlock &B,
1756 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1757 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1758 MachineFunction &MF = *B.getParent();
1759 auto &HST = MF.getSubtarget<HexagonSubtarget>();
1760 auto &MFI = MF.getFrameInfo();
1761 auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
1762 MachineInstr *MI = &*It;
1763 if (!MI->getOperand(1).isFI())
1766 DebugLoc DL = MI->getDebugLoc();
1767 unsigned DstR = MI->getOperand(0).getReg();
1768 unsigned DstHi = HRI.getSubReg(DstR, Hexagon::vsub_hi);
1769 unsigned DstLo = HRI.getSubReg(DstR, Hexagon::vsub_lo);
1770 int FI = MI->getOperand(1).getIndex();
1772 bool Is128B = HST.useHVXDblOps();
1773 const auto &RC = !Is128B ? Hexagon::VectorRegsRegClass
1774 : Hexagon::VectorRegs128BRegClass;
1775 unsigned Size = HRI.getSpillSize(RC);
1776 unsigned NeedAlign = HRI.getSpillAlignment(RC);
1777 unsigned HasAlign = MFI.getObjectAlignment(FI);
1781 if (NeedAlign <= HasAlign)
1782 LoadOpc = !Is128B ? Hexagon::V6_vL32b_ai : Hexagon::V6_vL32b_ai_128B;
1784 LoadOpc = !Is128B ? Hexagon::V6_vL32Ub_ai : Hexagon::V6_vL32Ub_ai_128B;
1786 BuildMI(B, It, DL, HII.get(LoadOpc), DstLo)
1789 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1792 if (NeedAlign <= MinAlign(HasAlign, Size))
1793 LoadOpc = !Is128B ? Hexagon::V6_vL32b_ai : Hexagon::V6_vL32b_ai_128B;
1795 LoadOpc = !Is128B ? Hexagon::V6_vL32Ub_ai : Hexagon::V6_vL32Ub_ai_128B;
1797 BuildMI(B, It, DL, HII.get(LoadOpc), DstHi)
1800 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1806 bool HexagonFrameLowering::expandStoreVec(MachineBasicBlock &B,
1807 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1808 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1809 MachineFunction &MF = *B.getParent();
1810 auto &HST = MF.getSubtarget<HexagonSubtarget>();
1811 auto &MFI = MF.getFrameInfo();
1812 MachineInstr *MI = &*It;
1813 if (!MI->getOperand(0).isFI())
1816 auto &HRI = *HST.getRegisterInfo();
1817 DebugLoc DL = MI->getDebugLoc();
1818 unsigned SrcR = MI->getOperand(2).getReg();
1819 bool IsKill = MI->getOperand(2).isKill();
1820 int FI = MI->getOperand(0).getIndex();
1822 bool Is128B = HST.useHVXDblOps();
1823 const auto &RC = !Is128B ? Hexagon::VectorRegsRegClass
1824 : Hexagon::VectorRegs128BRegClass;
1825 unsigned NeedAlign = HRI.getSpillAlignment(RC);
1826 unsigned HasAlign = MFI.getObjectAlignment(FI);
1829 if (NeedAlign <= HasAlign)
1830 StoreOpc = !Is128B ? Hexagon::V6_vS32b_ai : Hexagon::V6_vS32b_ai_128B;
1832 StoreOpc = !Is128B ? Hexagon::V6_vS32Ub_ai : Hexagon::V6_vS32Ub_ai_128B;
1834 BuildMI(B, It, DL, HII.get(StoreOpc))
1837 .addReg(SrcR, getKillRegState(IsKill))
1838 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1844 bool HexagonFrameLowering::expandLoadVec(MachineBasicBlock &B,
1845 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1846 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1847 MachineFunction &MF = *B.getParent();
1848 auto &HST = MF.getSubtarget<HexagonSubtarget>();
1849 auto &MFI = MF.getFrameInfo();
1850 MachineInstr *MI = &*It;
1851 if (!MI->getOperand(1).isFI())
1854 auto &HRI = *HST.getRegisterInfo();
1855 DebugLoc DL = MI->getDebugLoc();
1856 unsigned DstR = MI->getOperand(0).getReg();
1857 int FI = MI->getOperand(1).getIndex();
1859 bool Is128B = HST.useHVXDblOps();
1860 const auto &RC = !Is128B ? Hexagon::VectorRegsRegClass
1861 : Hexagon::VectorRegs128BRegClass;
1862 unsigned NeedAlign = HRI.getSpillAlignment(RC);
1863 unsigned HasAlign = MFI.getObjectAlignment(FI);
1866 if (NeedAlign <= HasAlign)
1867 LoadOpc = !Is128B ? Hexagon::V6_vL32b_ai : Hexagon::V6_vL32b_ai_128B;
1869 LoadOpc = !Is128B ? Hexagon::V6_vL32Ub_ai : Hexagon::V6_vL32Ub_ai_128B;
1871 BuildMI(B, It, DL, HII.get(LoadOpc), DstR)
1874 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1880 bool HexagonFrameLowering::expandSpillMacros(MachineFunction &MF,
1881 SmallVectorImpl<unsigned> &NewRegs) const {
1882 auto &HST = MF.getSubtarget<HexagonSubtarget>();
1883 auto &HII = *HST.getInstrInfo();
1884 MachineRegisterInfo &MRI = MF.getRegInfo();
1885 bool Changed = false;
1887 for (auto &B : MF) {
1888 // Traverse the basic block.
1889 MachineBasicBlock::iterator NextI;
1890 for (auto I = B.begin(), E = B.end(); I != E; I = NextI) {
1891 MachineInstr *MI = &*I;
1892 NextI = std::next(I);
1893 unsigned Opc = MI->getOpcode();
1896 case TargetOpcode::COPY:
1897 Changed |= expandCopy(B, I, MRI, HII, NewRegs);
1899 case Hexagon::STriw_pred:
1900 case Hexagon::STriw_mod:
1901 Changed |= expandStoreInt(B, I, MRI, HII, NewRegs);
1903 case Hexagon::LDriw_pred:
1904 case Hexagon::LDriw_mod:
1905 Changed |= expandLoadInt(B, I, MRI, HII, NewRegs);
1907 case Hexagon::PS_vstorerq_ai:
1908 case Hexagon::PS_vstorerq_ai_128B:
1909 Changed |= expandStoreVecPred(B, I, MRI, HII, NewRegs);
1911 case Hexagon::PS_vloadrq_ai:
1912 case Hexagon::PS_vloadrq_ai_128B:
1913 Changed |= expandLoadVecPred(B, I, MRI, HII, NewRegs);
1915 case Hexagon::PS_vloadrw_ai:
1916 case Hexagon::PS_vloadrwu_ai:
1917 case Hexagon::PS_vloadrw_ai_128B:
1918 case Hexagon::PS_vloadrwu_ai_128B:
1919 Changed |= expandLoadVec2(B, I, MRI, HII, NewRegs);
1921 case Hexagon::PS_vstorerw_ai:
1922 case Hexagon::PS_vstorerwu_ai:
1923 case Hexagon::PS_vstorerw_ai_128B:
1924 case Hexagon::PS_vstorerwu_ai_128B:
1925 Changed |= expandStoreVec2(B, I, MRI, HII, NewRegs);
1934 void HexagonFrameLowering::determineCalleeSaves(MachineFunction &MF,
1935 BitVector &SavedRegs,
1936 RegScavenger *RS) const {
1937 auto &HST = MF.getSubtarget<HexagonSubtarget>();
1938 auto &HRI = *HST.getRegisterInfo();
1940 SavedRegs.resize(HRI.getNumRegs());
1942 // If we have a function containing __builtin_eh_return we want to spill and
1943 // restore all callee saved registers. Pretend that they are used.
1944 if (MF.getInfo<HexagonMachineFunctionInfo>()->hasEHReturn())
1945 for (const MCPhysReg *R = HRI.getCalleeSavedRegs(&MF); *R; ++R)
1948 // Replace predicate register pseudo spill code.
1949 SmallVector<unsigned,8> NewRegs;
1950 expandSpillMacros(MF, NewRegs);
1951 if (OptimizeSpillSlots && !isOptNone(MF))
1952 optimizeSpillSlots(MF, NewRegs);
1954 // We need to reserve a a spill slot if scavenging could potentially require
1955 // spilling a scavenged register.
1956 if (!NewRegs.empty() || mayOverflowFrameOffset(MF)) {
1957 MachineFrameInfo &MFI = MF.getFrameInfo();
1958 MachineRegisterInfo &MRI = MF.getRegInfo();
1959 SetVector<const TargetRegisterClass*> SpillRCs;
1960 // Reserve an int register in any case, because it could be used to hold
1961 // the stack offset in case it does not fit into a spill instruction.
1962 SpillRCs.insert(&Hexagon::IntRegsRegClass);
1964 for (unsigned VR : NewRegs)
1965 SpillRCs.insert(MRI.getRegClass(VR));
1967 for (auto *RC : SpillRCs) {
1968 if (!needToReserveScavengingSpillSlots(MF, HRI, RC))
1970 unsigned Num = RC == &Hexagon::IntRegsRegClass ? NumberScavengerSlots : 1;
1971 unsigned S = HRI.getSpillSize(*RC), A = HRI.getSpillAlignment(*RC);
1972 for (unsigned i = 0; i < Num; i++) {
1973 int NewFI = MFI.CreateSpillStackObject(S, A);
1974 RS->addScavengingFrameIndex(NewFI);
1979 TargetFrameLowering::determineCalleeSaves(MF, SavedRegs, RS);
1982 unsigned HexagonFrameLowering::findPhysReg(MachineFunction &MF,
1983 HexagonBlockRanges::IndexRange &FIR,
1984 HexagonBlockRanges::InstrIndexMap &IndexMap,
1985 HexagonBlockRanges::RegToRangeMap &DeadMap,
1986 const TargetRegisterClass *RC) const {
1987 auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
1988 auto &MRI = MF.getRegInfo();
1990 auto isDead = [&FIR,&DeadMap] (unsigned Reg) -> bool {
1991 auto F = DeadMap.find({Reg,0});
1992 if (F == DeadMap.end())
1994 for (auto &DR : F->second)
1995 if (DR.contains(FIR))
2000 for (unsigned Reg : RC->getRawAllocationOrder(MF)) {
2002 for (auto R : HexagonBlockRanges::expandToSubRegs({Reg,0}, MRI, HRI)) {
2014 void HexagonFrameLowering::optimizeSpillSlots(MachineFunction &MF,
2015 SmallVectorImpl<unsigned> &VRegs) const {
2016 auto &HST = MF.getSubtarget<HexagonSubtarget>();
2017 auto &HII = *HST.getInstrInfo();
2018 auto &HRI = *HST.getRegisterInfo();
2019 auto &MRI = MF.getRegInfo();
2020 HexagonBlockRanges HBR(MF);
2022 typedef std::map<MachineBasicBlock*,HexagonBlockRanges::InstrIndexMap>
2024 typedef std::map<MachineBasicBlock*,HexagonBlockRanges::RangeList>
2026 typedef HexagonBlockRanges::IndexType IndexType;
2031 const TargetRegisterClass *RC = nullptr;
2033 SlotInfo() = default;
2036 BlockIndexMap BlockIndexes;
2037 SmallSet<int,4> BadFIs;
2038 std::map<int,SlotInfo> FIRangeMap;
2040 // Accumulate register classes: get a common class for a pre-existing
2041 // class HaveRC and a new class NewRC. Return nullptr if a common class
2042 // cannot be found, otherwise return the resulting class. If HaveRC is
2043 // nullptr, assume that it is still unset.
2045 [](const TargetRegisterClass *HaveRC,
2046 const TargetRegisterClass *NewRC) -> const TargetRegisterClass * {
2047 if (HaveRC == nullptr || HaveRC == NewRC)
2049 // Different classes, both non-null. Pick the more general one.
2050 if (HaveRC->hasSubClassEq(NewRC))
2052 if (NewRC->hasSubClassEq(HaveRC))
2057 // Scan all blocks in the function. Check all occurrences of frame indexes,
2058 // and collect relevant information.
2059 for (auto &B : MF) {
2060 std::map<int,IndexType> LastStore, LastLoad;
2061 // Emplace appears not to be supported in gcc 4.7.2-4.
2062 //auto P = BlockIndexes.emplace(&B, HexagonBlockRanges::InstrIndexMap(B));
2063 auto P = BlockIndexes.insert(
2064 std::make_pair(&B, HexagonBlockRanges::InstrIndexMap(B)));
2065 auto &IndexMap = P.first->second;
2066 DEBUG(dbgs() << "Index map for BB#" << B.getNumber() << "\n"
2067 << IndexMap << '\n');
2069 for (auto &In : B) {
2071 bool Load = HII.isLoadFromStackSlot(In, LFI) && !HII.isPredicated(In);
2072 bool Store = HII.isStoreToStackSlot(In, SFI) && !HII.isPredicated(In);
2073 if (Load && Store) {
2074 // If it's both a load and a store, then we won't handle it.
2079 // Check for register classes of the register used as the source for
2080 // the store, and the register used as the destination for the load.
2081 // Also, only accept base+imm_offset addressing modes. Other addressing
2082 // modes can have side-effects (post-increments, etc.). For stack
2083 // slots they are very unlikely, so there is not much loss due to
2084 // this restriction.
2085 if (Load || Store) {
2086 int TFI = Load ? LFI : SFI;
2087 unsigned AM = HII.getAddrMode(In);
2088 SlotInfo &SI = FIRangeMap[TFI];
2089 bool Bad = (AM != HexagonII::BaseImmOffset);
2091 // If the addressing mode is ok, check the register class.
2092 unsigned OpNum = Load ? 0 : 2;
2093 auto *RC = HII.getRegClass(In.getDesc(), OpNum, &HRI, MF);
2094 RC = getCommonRC(SI.RC, RC);
2102 unsigned S = (1U << (HII.getMemAccessSize(In) - 1));
2103 if (SI.Size != 0 && SI.Size != S)
2109 for (auto *Mo : In.memoperands()) {
2110 if (!Mo->isVolatile())
2120 // Locate uses of frame indices.
2121 for (unsigned i = 0, n = In.getNumOperands(); i < n; ++i) {
2122 const MachineOperand &Op = In.getOperand(i);
2125 int FI = Op.getIndex();
2126 // Make sure that the following operand is an immediate and that
2127 // it is 0. This is the offset in the stack object.
2128 if (i+1 >= n || !In.getOperand(i+1).isImm() ||
2129 In.getOperand(i+1).getImm() != 0)
2131 if (BadFIs.count(FI))
2134 IndexType Index = IndexMap.getIndex(&In);
2136 if (LastStore[FI] == IndexType::None)
2137 LastStore[FI] = IndexType::Entry;
2138 LastLoad[FI] = Index;
2140 HexagonBlockRanges::RangeList &RL = FIRangeMap[FI].Map[&B];
2141 if (LastStore[FI] != IndexType::None)
2142 RL.add(LastStore[FI], LastLoad[FI], false, false);
2143 else if (LastLoad[FI] != IndexType::None)
2144 RL.add(IndexType::Entry, LastLoad[FI], false, false);
2145 LastLoad[FI] = IndexType::None;
2146 LastStore[FI] = Index;
2153 for (auto &I : LastLoad) {
2154 IndexType LL = I.second;
2155 if (LL == IndexType::None)
2157 auto &RL = FIRangeMap[I.first].Map[&B];
2158 IndexType &LS = LastStore[I.first];
2159 if (LS != IndexType::None)
2160 RL.add(LS, LL, false, false);
2162 RL.add(IndexType::Entry, LL, false, false);
2163 LS = IndexType::None;
2165 for (auto &I : LastStore) {
2166 IndexType LS = I.second;
2167 if (LS == IndexType::None)
2169 auto &RL = FIRangeMap[I.first].Map[&B];
2170 RL.add(LS, IndexType::None, false, false);
2175 for (auto &P : FIRangeMap) {
2176 dbgs() << "fi#" << P.first;
2177 if (BadFIs.count(P.first))
2180 if (P.second.RC != nullptr)
2181 dbgs() << HRI.getRegClassName(P.second.RC) << '\n';
2183 dbgs() << "<null>\n";
2184 for (auto &R : P.second.Map)
2185 dbgs() << " BB#" << R.first->getNumber() << " { " << R.second << "}\n";
2189 // When a slot is loaded from in a block without being stored to in the
2190 // same block, it is live-on-entry to this block. To avoid CFG analysis,
2191 // consider this slot to be live-on-exit from all blocks.
2192 SmallSet<int,4> LoxFIs;
2194 std::map<MachineBasicBlock*,std::vector<int>> BlockFIMap;
2196 for (auto &P : FIRangeMap) {
2197 // P = pair(FI, map: BB->RangeList)
2198 if (BadFIs.count(P.first))
2200 for (auto &B : MF) {
2201 auto F = P.second.Map.find(&B);
2202 // F = pair(BB, RangeList)
2203 if (F == P.second.Map.end() || F->second.empty())
2205 HexagonBlockRanges::IndexRange &IR = F->second.front();
2206 if (IR.start() == IndexType::Entry)
2207 LoxFIs.insert(P.first);
2208 BlockFIMap[&B].push_back(P.first);
2213 dbgs() << "Block-to-FI map (* -- live-on-exit):\n";
2214 for (auto &P : BlockFIMap) {
2215 auto &FIs = P.second;
2218 dbgs() << " BB#" << P.first->getNumber() << ": {";
2219 for (auto I : FIs) {
2220 dbgs() << " fi#" << I;
2221 if (LoxFIs.count(I))
2229 bool HasOptLimit = SpillOptMax.getPosition();
2232 // eliminate loads, when all loads eliminated, eliminate all stores.
2233 for (auto &B : MF) {
2234 auto F = BlockIndexes.find(&B);
2235 assert(F != BlockIndexes.end());
2236 HexagonBlockRanges::InstrIndexMap &IM = F->second;
2237 HexagonBlockRanges::RegToRangeMap LM = HBR.computeLiveMap(IM);
2238 HexagonBlockRanges::RegToRangeMap DM = HBR.computeDeadMap(IM, LM);
2239 DEBUG(dbgs() << "BB#" << B.getNumber() << " dead map\n"
2240 << HexagonBlockRanges::PrintRangeMap(DM, HRI));
2242 for (auto FI : BlockFIMap[&B]) {
2243 if (BadFIs.count(FI))
2245 DEBUG(dbgs() << "Working on fi#" << FI << '\n');
2246 HexagonBlockRanges::RangeList &RL = FIRangeMap[FI].Map[&B];
2247 for (auto &Range : RL) {
2248 DEBUG(dbgs() << "--Examining range:" << RL << '\n');
2249 if (!IndexType::isInstr(Range.start()) ||
2250 !IndexType::isInstr(Range.end()))
2252 MachineInstr &SI = *IM.getInstr(Range.start());
2253 MachineInstr &EI = *IM.getInstr(Range.end());
2254 assert(SI.mayStore() && "Unexpected start instruction");
2255 assert(EI.mayLoad() && "Unexpected end instruction");
2256 MachineOperand &SrcOp = SI.getOperand(2);
2258 HexagonBlockRanges::RegisterRef SrcRR = { SrcOp.getReg(),
2259 SrcOp.getSubReg() };
2260 auto *RC = HII.getRegClass(SI.getDesc(), 2, &HRI, MF);
2261 // The this-> is needed to unconfuse MSVC.
2262 unsigned FoundR = this->findPhysReg(MF, Range, IM, DM, RC);
2263 DEBUG(dbgs() << "Replacement reg:" << PrintReg(FoundR, &HRI) << '\n');
2268 if (SpillOptCount >= SpillOptMax)
2274 // Generate the copy-in: "FoundR = COPY SrcR" at the store location.
2275 MachineBasicBlock::iterator StartIt = SI.getIterator(), NextIt;
2276 MachineInstr *CopyIn = nullptr;
2277 if (SrcRR.Reg != FoundR || SrcRR.Sub != 0) {
2278 const DebugLoc &DL = SI.getDebugLoc();
2279 CopyIn = BuildMI(B, StartIt, DL, HII.get(TargetOpcode::COPY), FoundR)
2284 // Check if this is a last store and the FI is live-on-exit.
2285 if (LoxFIs.count(FI) && (&Range == &RL.back())) {
2286 // Update store's source register.
2287 if (unsigned SR = SrcOp.getSubReg())
2288 SrcOp.setReg(HRI.getSubReg(FoundR, SR));
2290 SrcOp.setReg(FoundR);
2292 // We are keeping this register live.
2293 SrcOp.setIsKill(false);
2296 IM.replaceInstr(&SI, CopyIn);
2299 auto EndIt = std::next(EI.getIterator());
2300 for (auto It = StartIt; It != EndIt; It = NextIt) {
2301 MachineInstr &MI = *It;
2302 NextIt = std::next(It);
2304 if (!HII.isLoadFromStackSlot(MI, TFI) || TFI != FI)
2306 unsigned DstR = MI.getOperand(0).getReg();
2307 assert(MI.getOperand(0).getSubReg() == 0);
2308 MachineInstr *CopyOut = nullptr;
2309 if (DstR != FoundR) {
2310 DebugLoc DL = MI.getDebugLoc();
2311 unsigned MemSize = (1U << (HII.getMemAccessSize(MI) - 1));
2312 assert(HII.getAddrMode(MI) == HexagonII::BaseImmOffset);
2313 unsigned CopyOpc = TargetOpcode::COPY;
2314 if (HII.isSignExtendingLoad(MI))
2315 CopyOpc = (MemSize == 1) ? Hexagon::A2_sxtb : Hexagon::A2_sxth;
2316 else if (HII.isZeroExtendingLoad(MI))
2317 CopyOpc = (MemSize == 1) ? Hexagon::A2_zxtb : Hexagon::A2_zxth;
2318 CopyOut = BuildMI(B, It, DL, HII.get(CopyOpc), DstR)
2319 .addReg(FoundR, getKillRegState(&MI == &EI));
2321 IM.replaceInstr(&MI, CopyOut);
2325 // Update the dead map.
2326 HexagonBlockRanges::RegisterRef FoundRR = { FoundR, 0 };
2327 for (auto RR : HexagonBlockRanges::expandToSubRegs(FoundRR, MRI, HRI))
2328 DM[RR].subtract(Range);
2329 } // for Range in range list
2334 void HexagonFrameLowering::expandAlloca(MachineInstr *AI,
2335 const HexagonInstrInfo &HII, unsigned SP, unsigned CF) const {
2336 MachineBasicBlock &MB = *AI->getParent();
2337 DebugLoc DL = AI->getDebugLoc();
2338 unsigned A = AI->getOperand(2).getImm();
2341 // Rd = alloca Rs, #A
2343 // If Rs and Rd are different registers, use this sequence:
2344 // Rd = sub(r29, Rs)
2345 // r29 = sub(r29, Rs)
2346 // Rd = and(Rd, #-A) ; if necessary
2347 // r29 = and(r29, #-A) ; if necessary
2348 // Rd = add(Rd, #CF) ; CF size aligned to at most A
2350 // Rd = sub(r29, Rs)
2351 // Rd = and(Rd, #-A) ; if necessary
2353 // Rd = add(Rd, #CF) ; CF size aligned to at most A
2355 MachineOperand &RdOp = AI->getOperand(0);
2356 MachineOperand &RsOp = AI->getOperand(1);
2357 unsigned Rd = RdOp.getReg(), Rs = RsOp.getReg();
2359 // Rd = sub(r29, Rs)
2360 BuildMI(MB, AI, DL, HII.get(Hexagon::A2_sub), Rd)
2364 // r29 = sub(r29, Rs)
2365 BuildMI(MB, AI, DL, HII.get(Hexagon::A2_sub), SP)
2370 // Rd = and(Rd, #-A)
2371 BuildMI(MB, AI, DL, HII.get(Hexagon::A2_andir), Rd)
2373 .addImm(-int64_t(A));
2375 BuildMI(MB, AI, DL, HII.get(Hexagon::A2_andir), SP)
2377 .addImm(-int64_t(A));
2381 BuildMI(MB, AI, DL, HII.get(TargetOpcode::COPY), SP)
2385 // Rd = add(Rd, #CF)
2386 BuildMI(MB, AI, DL, HII.get(Hexagon::A2_addi), Rd)
2392 bool HexagonFrameLowering::needsAligna(const MachineFunction &MF) const {
2393 const MachineFrameInfo &MFI = MF.getFrameInfo();
2394 if (!MFI.hasVarSizedObjects())
2396 unsigned MaxA = MFI.getMaxAlignment();
2397 if (MaxA <= getStackAlignment())
2402 const MachineInstr *HexagonFrameLowering::getAlignaInstr(
2403 const MachineFunction &MF) const {
2406 if (I.getOpcode() == Hexagon::PS_aligna)
2411 /// Adds all callee-saved registers as implicit uses or defs to the
2413 void HexagonFrameLowering::addCalleeSaveRegistersAsImpOperand(MachineInstr *MI,
2414 const CSIVect &CSI, bool IsDef, bool IsKill) const {
2415 // Add the callee-saved registers as implicit uses.
2417 MI->addOperand(MachineOperand::CreateReg(R.getReg(), IsDef, true, IsKill));
2420 /// Determine whether the callee-saved register saves and restores should
2421 /// be generated via inline code. If this function returns "true", inline
2422 /// code will be generated. If this function returns "false", additional
2423 /// checks are performed, which may still lead to the inline code.
2424 bool HexagonFrameLowering::shouldInlineCSR(const MachineFunction &MF,
2425 const CSIVect &CSI) const {
2426 if (MF.getInfo<HexagonMachineFunctionInfo>()->hasEHReturn())
2430 if (!isOptSize(MF) && !isMinSize(MF))
2431 if (MF.getTarget().getOptLevel() > CodeGenOpt::Default)
2434 // Check if CSI only has double registers, and if the registers form
2435 // a contiguous block starting from D8.
2436 BitVector Regs(Hexagon::NUM_TARGET_REGS);
2437 for (unsigned i = 0, n = CSI.size(); i < n; ++i) {
2438 unsigned R = CSI[i].getReg();
2439 if (!Hexagon::DoubleRegsRegClass.contains(R))
2443 int F = Regs.find_first();
2444 if (F != Hexagon::D8)
2447 int N = Regs.find_next(F);
2448 if (N >= 0 && N != F+1)
2456 bool HexagonFrameLowering::useSpillFunction(const MachineFunction &MF,
2457 const CSIVect &CSI) const {
2458 if (shouldInlineCSR(MF, CSI))
2460 unsigned NumCSI = CSI.size();
2464 unsigned Threshold = isOptSize(MF) ? SpillFuncThresholdOs
2465 : SpillFuncThreshold;
2466 return Threshold < NumCSI;
2469 bool HexagonFrameLowering::useRestoreFunction(const MachineFunction &MF,
2470 const CSIVect &CSI) const {
2471 if (shouldInlineCSR(MF, CSI))
2473 // The restore functions do a bit more than just restoring registers.
2474 // The non-returning versions will go back directly to the caller's
2475 // caller, others will clean up the stack frame in preparation for
2476 // a tail call. Using them can still save code size even if only one
2477 // register is getting restores. Make the decision based on -Oz:
2478 // using -Os will use inline restore for a single register.
2481 unsigned NumCSI = CSI.size();
2485 unsigned Threshold = isOptSize(MF) ? SpillFuncThresholdOs-1
2486 : SpillFuncThreshold;
2487 return Threshold < NumCSI;
2490 bool HexagonFrameLowering::mayOverflowFrameOffset(MachineFunction &MF) const {
2491 unsigned StackSize = MF.getFrameInfo().estimateStackSize(MF);
2492 auto &HST = MF.getSubtarget<HexagonSubtarget>();
2493 // A fairly simplistic guess as to whether a potential load/store to a
2494 // stack location could require an extra register.
2495 if (HST.useHVXOps() && StackSize > 256)
2498 // Check if the function has store-immediate instructions that access
2499 // the stack. Since the offset field is not extendable, if the stack
2500 // size exceeds the offset limit (6 bits, shifted), the stores will
2501 // require a new base register.
2502 bool HasImmStack = false;
2503 unsigned MinLS = ~0u; // Log_2 of the memory access size.
2505 for (const MachineBasicBlock &B : MF) {
2506 for (const MachineInstr &MI : B) {
2508 switch (MI.getOpcode()) {
2509 case Hexagon::S4_storeirit_io:
2510 case Hexagon::S4_storeirif_io:
2511 case Hexagon::S4_storeiri_io:
2514 case Hexagon::S4_storeirht_io:
2515 case Hexagon::S4_storeirhf_io:
2516 case Hexagon::S4_storeirh_io:
2519 case Hexagon::S4_storeirbt_io:
2520 case Hexagon::S4_storeirbf_io:
2521 case Hexagon::S4_storeirb_io:
2522 if (MI.getOperand(0).isFI())
2524 MinLS = std::min(MinLS, LS);
2531 return !isUInt<6>(StackSize >> MinLS);