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 #define DEBUG_TYPE "hexagon-pei"
13 #include "HexagonFrameLowering.h"
14 #include "HexagonBlockRanges.h"
15 #include "HexagonInstrInfo.h"
16 #include "HexagonMachineFunctionInfo.h"
17 #include "HexagonRegisterInfo.h"
18 #include "HexagonSubtarget.h"
19 #include "HexagonTargetMachine.h"
20 #include "MCTargetDesc/HexagonBaseInfo.h"
21 #include "llvm/ADT/BitVector.h"
22 #include "llvm/ADT/DenseMap.h"
23 #include "llvm/ADT/None.h"
24 #include "llvm/ADT/Optional.h"
25 #include "llvm/ADT/PostOrderIterator.h"
26 #include "llvm/ADT/SetVector.h"
27 #include "llvm/ADT/SmallSet.h"
28 #include "llvm/ADT/SmallVector.h"
29 #include "llvm/CodeGen/LivePhysRegs.h"
30 #include "llvm/CodeGen/MachineBasicBlock.h"
31 #include "llvm/CodeGen/MachineDominators.h"
32 #include "llvm/CodeGen/MachineFrameInfo.h"
33 #include "llvm/CodeGen/MachineFunction.h"
34 #include "llvm/CodeGen/MachineFunctionPass.h"
35 #include "llvm/CodeGen/MachineInstr.h"
36 #include "llvm/CodeGen/MachineInstrBuilder.h"
37 #include "llvm/CodeGen/MachineMemOperand.h"
38 #include "llvm/CodeGen/MachineModuleInfo.h"
39 #include "llvm/CodeGen/MachineOperand.h"
40 #include "llvm/CodeGen/MachinePostDominators.h"
41 #include "llvm/CodeGen/MachineRegisterInfo.h"
42 #include "llvm/CodeGen/RegisterScavenging.h"
43 #include "llvm/IR/DebugLoc.h"
44 #include "llvm/IR/Function.h"
45 #include "llvm/MC/MCDwarf.h"
46 #include "llvm/MC/MCRegisterInfo.h"
47 #include "llvm/Pass.h"
48 #include "llvm/Support/CodeGen.h"
49 #include "llvm/Support/CommandLine.h"
50 #include "llvm/Support/Debug.h"
51 #include "llvm/Support/ErrorHandling.h"
52 #include "llvm/Support/MathExtras.h"
53 #include "llvm/Support/raw_ostream.h"
54 #include "llvm/Target/TargetMachine.h"
55 #include "llvm/Target/TargetRegisterInfo.h"
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> UseAllocframe("use-allocframe", cl::init(true),
182 cl::Hidden, cl::desc("Use allocframe more conservatively"));
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();
555 unsigned MaxAlign = std::max(MFI.getMaxAlignment(), getStackAlignment());
557 // Calculate the total stack frame size.
558 // Get the number of bytes to allocate from the FrameInfo.
559 unsigned FrameSize = MFI.getStackSize();
560 // Round up the max call frame size to the max alignment on the stack.
561 unsigned MaxCFA = alignTo(MFI.getMaxCallFrameSize(), MaxAlign);
562 MFI.setMaxCallFrameSize(MaxCFA);
564 FrameSize = MaxCFA + alignTo(FrameSize, MaxAlign);
565 MFI.setStackSize(FrameSize);
567 bool AlignStack = (MaxAlign > getStackAlignment());
569 // Get the number of bytes to allocate from the FrameInfo.
570 unsigned NumBytes = MFI.getStackSize();
571 unsigned SP = HRI.getStackRegister();
572 unsigned MaxCF = MFI.getMaxCallFrameSize();
573 MachineBasicBlock::iterator InsertPt = MBB.begin();
575 SmallVector<MachineInstr *, 4> AdjustRegs;
578 if (MI.getOpcode() == Hexagon::PS_alloca)
579 AdjustRegs.push_back(&MI);
581 for (auto MI : AdjustRegs) {
582 assert((MI->getOpcode() == Hexagon::PS_alloca) && "Expected alloca");
583 expandAlloca(MI, HII, SP, MaxCF);
584 MI->eraseFromParent();
590 // Check for overflow.
591 // Hexagon_TODO: Ugh! hardcoding. Is there an API that can be used?
592 const unsigned int ALLOCFRAME_MAX = 16384;
594 // Create a dummy memory operand to avoid allocframe from being treated as
595 // a volatile memory reference.
596 MachineMemOperand *MMO =
597 MF.getMachineMemOperand(MachinePointerInfo(), MachineMemOperand::MOStore,
600 if (NumBytes >= ALLOCFRAME_MAX) {
601 // Emit allocframe(#0).
602 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::S2_allocframe))
606 // Subtract offset from frame pointer.
607 // We use a caller-saved non-parameter register for that.
608 unsigned CallerSavedReg = HRI.getFirstCallerSavedNonParamReg();
609 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::CONST32),
610 CallerSavedReg).addImm(NumBytes);
611 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::A2_sub), SP)
613 .addReg(CallerSavedReg);
615 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::S2_allocframe))
621 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::A2_andir), SP)
623 .addImm(-int64_t(MaxAlign));
626 // If the stack-checking is enabled, and we spilled the callee-saved
627 // registers inline (i.e. did not use a spill function), then call
628 // the stack checker directly.
629 if (EnableStackOVFSanitizer && !PrologueStubs)
630 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::PS_call_stk))
631 .addExternalSymbol("__runtime_stack_check");
634 void HexagonFrameLowering::insertEpilogueInBlock(MachineBasicBlock &MBB) const {
635 MachineFunction &MF = *MBB.getParent();
639 auto &HST = MF.getSubtarget<HexagonSubtarget>();
640 auto &HII = *HST.getInstrInfo();
641 auto &HRI = *HST.getRegisterInfo();
642 unsigned SP = HRI.getStackRegister();
644 MachineInstr *RetI = getReturn(MBB);
645 unsigned RetOpc = RetI ? RetI->getOpcode() : 0;
647 MachineBasicBlock::iterator InsertPt = MBB.getFirstTerminator();
649 if (InsertPt != MBB.end())
650 DL = InsertPt->getDebugLoc();
651 else if (!MBB.empty())
652 DL = std::prev(MBB.end())->getDebugLoc();
655 if (RetOpc == Hexagon::EH_RETURN_JMPR) {
656 BuildMI(MBB, InsertPt, DL, HII.get(Hexagon::L2_deallocframe));
657 BuildMI(MBB, InsertPt, DL, HII.get(Hexagon::A2_add), SP)
659 .addReg(Hexagon::R28);
663 // Check for RESTORE_DEALLOC_RET* tail call. Don't emit an extra dealloc-
664 // frame instruction if we encounter it.
665 if (RetOpc == Hexagon::RESTORE_DEALLOC_RET_JMP_V4 ||
666 RetOpc == Hexagon::RESTORE_DEALLOC_RET_JMP_V4_PIC ||
667 RetOpc == Hexagon::RESTORE_DEALLOC_RET_JMP_V4_EXT ||
668 RetOpc == Hexagon::RESTORE_DEALLOC_RET_JMP_V4_EXT_PIC) {
669 MachineBasicBlock::iterator It = RetI;
671 // Delete all instructions after the RESTORE (except labels).
672 while (It != MBB.end()) {
681 // It is possible that the restoring code is a call to a library function.
682 // All of the restore* functions include "deallocframe", so we need to make
683 // sure that we don't add an extra one.
684 bool NeedsDeallocframe = true;
685 if (!MBB.empty() && InsertPt != MBB.begin()) {
686 MachineBasicBlock::iterator PrevIt = std::prev(InsertPt);
687 unsigned COpc = PrevIt->getOpcode();
688 if (COpc == Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4 ||
689 COpc == Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_PIC ||
690 COpc == Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_EXT ||
691 COpc == Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_EXT_PIC ||
692 COpc == Hexagon::PS_call_nr || COpc == Hexagon::PS_callr_nr)
693 NeedsDeallocframe = false;
696 if (!NeedsDeallocframe)
698 // If the returning instruction is PS_jmpret, replace it with dealloc_return,
699 // otherwise just add deallocframe. The function could be returning via a
701 if (RetOpc != Hexagon::PS_jmpret || DisableDeallocRet) {
702 BuildMI(MBB, InsertPt, DL, HII.get(Hexagon::L2_deallocframe));
705 unsigned NewOpc = Hexagon::L4_return;
706 MachineInstr *NewI = BuildMI(MBB, RetI, DL, HII.get(NewOpc));
707 // Transfer the function live-out registers.
708 NewI->copyImplicitOps(MF, *RetI);
712 void HexagonFrameLowering::updateEntryPaths(MachineFunction &MF,
713 MachineBasicBlock &SaveB) const {
714 SetVector<unsigned> Worklist;
716 MachineBasicBlock &EntryB = MF.front();
717 Worklist.insert(EntryB.getNumber());
719 unsigned SaveN = SaveB.getNumber();
720 auto &CSI = MF.getFrameInfo().getCalleeSavedInfo();
722 for (unsigned i = 0; i < Worklist.size(); ++i) {
723 unsigned BN = Worklist[i];
724 MachineBasicBlock &MBB = *MF.getBlockNumbered(BN);
726 if (!MBB.isLiveIn(R.getReg()))
727 MBB.addLiveIn(R.getReg());
729 for (auto &SB : MBB.successors())
730 Worklist.insert(SB->getNumber());
734 bool HexagonFrameLowering::updateExitPaths(MachineBasicBlock &MBB,
735 MachineBasicBlock &RestoreB, BitVector &DoneT, BitVector &DoneF,
736 BitVector &Path) const {
737 assert(MBB.getNumber() >= 0);
738 unsigned BN = MBB.getNumber();
739 if (Path[BN] || DoneF[BN])
744 auto &CSI = MBB.getParent()->getFrameInfo().getCalleeSavedInfo();
747 bool ReachedExit = false;
748 for (auto &SB : MBB.successors())
749 ReachedExit |= updateExitPaths(*SB, RestoreB, DoneT, DoneF, Path);
751 if (!MBB.empty() && MBB.back().isReturn()) {
752 // Add implicit uses of all callee-saved registers to the reached
753 // return instructions. This is to prevent the anti-dependency breaker
754 // from renaming these registers.
755 MachineInstr &RetI = MBB.back();
756 if (!isRestoreCall(RetI.getOpcode()))
758 RetI.addOperand(MachineOperand::CreateReg(R.getReg(), false, true));
762 // We don't want to add unnecessary live-ins to the restore block: since
763 // the callee-saved registers are being defined in it, the entry of the
764 // restore block cannot be on the path from the definitions to any exit.
765 if (ReachedExit && &MBB != &RestoreB) {
767 if (!MBB.isLiveIn(R.getReg()))
768 MBB.addLiveIn(R.getReg());
778 static Optional<MachineBasicBlock::iterator>
779 findCFILocation(MachineBasicBlock &B) {
780 // The CFI instructions need to be inserted right after allocframe.
781 // An exception to this is a situation where allocframe is bundled
782 // with a call: then the CFI instructions need to be inserted before
783 // the packet with the allocframe+call (in case the call throws an
785 auto End = B.instr_end();
787 for (MachineInstr &I : B) {
788 MachineBasicBlock::iterator It = I.getIterator();
790 if (I.getOpcode() == Hexagon::S2_allocframe)
791 return std::next(It);
795 bool HasCall = false, HasAllocFrame = false;
796 auto T = It.getInstrIterator();
797 while (++T != End && T->isBundled()) {
798 if (T->getOpcode() == Hexagon::S2_allocframe)
799 HasAllocFrame = true;
800 else if (T->isCall())
804 return HasCall ? It : std::next(It);
809 void HexagonFrameLowering::insertCFIInstructions(MachineFunction &MF) const {
811 auto At = findCFILocation(B);
813 insertCFIInstructionsAt(B, At.getValue());
817 void HexagonFrameLowering::insertCFIInstructionsAt(MachineBasicBlock &MBB,
818 MachineBasicBlock::iterator At) const {
819 MachineFunction &MF = *MBB.getParent();
820 MachineFrameInfo &MFI = MF.getFrameInfo();
821 MachineModuleInfo &MMI = MF.getMMI();
822 auto &HST = MF.getSubtarget<HexagonSubtarget>();
823 auto &HII = *HST.getInstrInfo();
824 auto &HRI = *HST.getRegisterInfo();
826 // If CFI instructions have debug information attached, something goes
827 // wrong with the final assembly generation: the prolog_end is placed
828 // in a wrong location.
830 const MCInstrDesc &CFID = HII.get(TargetOpcode::CFI_INSTRUCTION);
832 MCSymbol *FrameLabel = MMI.getContext().createTempSymbol();
833 bool HasFP = hasFP(MF);
836 unsigned DwFPReg = HRI.getDwarfRegNum(HRI.getFrameRegister(), true);
837 unsigned DwRAReg = HRI.getDwarfRegNum(HRI.getRARegister(), true);
839 // Define CFA via an offset from the value of FP.
842 // --+----+----+---------------------
843 // | FP | LR | increasing addresses -->
844 // --+----+----+---------------------
845 // | +-- Old SP (before allocframe)
846 // +-- New FP (after allocframe)
848 // MCCFIInstruction::createDefCfa subtracts the offset from the register.
849 // MCCFIInstruction::createOffset takes the offset without sign change.
850 auto DefCfa = MCCFIInstruction::createDefCfa(FrameLabel, DwFPReg, -8);
851 BuildMI(MBB, At, DL, CFID)
852 .addCFIIndex(MF.addFrameInst(DefCfa));
853 // R31 (return addr) = CFA - 4
854 auto OffR31 = MCCFIInstruction::createOffset(FrameLabel, DwRAReg, -4);
855 BuildMI(MBB, At, DL, CFID)
856 .addCFIIndex(MF.addFrameInst(OffR31));
857 // R30 (frame ptr) = CFA - 8
858 auto OffR30 = MCCFIInstruction::createOffset(FrameLabel, DwFPReg, -8);
859 BuildMI(MBB, At, DL, CFID)
860 .addCFIIndex(MF.addFrameInst(OffR30));
863 static unsigned int RegsToMove[] = {
864 Hexagon::R1, Hexagon::R0, Hexagon::R3, Hexagon::R2,
865 Hexagon::R17, Hexagon::R16, Hexagon::R19, Hexagon::R18,
866 Hexagon::R21, Hexagon::R20, Hexagon::R23, Hexagon::R22,
867 Hexagon::R25, Hexagon::R24, Hexagon::R27, Hexagon::R26,
868 Hexagon::D0, Hexagon::D1, Hexagon::D8, Hexagon::D9,
869 Hexagon::D10, Hexagon::D11, Hexagon::D12, Hexagon::D13,
873 const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
875 for (unsigned i = 0; RegsToMove[i] != Hexagon::NoRegister; ++i) {
876 unsigned Reg = RegsToMove[i];
877 auto IfR = [Reg] (const CalleeSavedInfo &C) -> bool {
878 return C.getReg() == Reg;
880 auto F = find_if(CSI, IfR);
886 // If the function has a frame pointer (i.e. has an allocframe),
887 // then the CFA has been defined in terms of FP. Any offsets in
888 // the following CFI instructions have to be defined relative
889 // to FP, which points to the bottom of the stack frame.
890 // The function getFrameIndexReference can still choose to use SP
891 // for the offset calculation, so we cannot simply call it here.
892 // Instead, get the offset (relative to the FP) directly.
893 Offset = MFI.getObjectOffset(F->getFrameIdx());
896 Offset = getFrameIndexReference(MF, F->getFrameIdx(), FrameReg);
898 // Subtract 8 to make room for R30 and R31, which are added above.
901 if (Reg < Hexagon::D0 || Reg > Hexagon::D15) {
902 unsigned DwarfReg = HRI.getDwarfRegNum(Reg, true);
903 auto OffReg = MCCFIInstruction::createOffset(FrameLabel, DwarfReg,
905 BuildMI(MBB, At, DL, CFID)
906 .addCFIIndex(MF.addFrameInst(OffReg));
908 // Split the double regs into subregs, and generate appropriate
910 // The only reason, we are split double regs is, llvm-mc does not
911 // understand paired registers for cfi_offset.
912 // Eg .cfi_offset r1:0, -64
914 unsigned HiReg = HRI.getSubReg(Reg, Hexagon::isub_hi);
915 unsigned LoReg = HRI.getSubReg(Reg, Hexagon::isub_lo);
916 unsigned HiDwarfReg = HRI.getDwarfRegNum(HiReg, true);
917 unsigned LoDwarfReg = HRI.getDwarfRegNum(LoReg, true);
918 auto OffHi = MCCFIInstruction::createOffset(FrameLabel, HiDwarfReg,
920 BuildMI(MBB, At, DL, CFID)
921 .addCFIIndex(MF.addFrameInst(OffHi));
922 auto OffLo = MCCFIInstruction::createOffset(FrameLabel, LoDwarfReg,
924 BuildMI(MBB, At, DL, CFID)
925 .addCFIIndex(MF.addFrameInst(OffLo));
930 bool HexagonFrameLowering::hasFP(const MachineFunction &MF) const {
931 auto &MFI = MF.getFrameInfo();
932 auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
934 bool HasFixed = MFI.getNumFixedObjects();
935 bool HasPrealloc = const_cast<MachineFrameInfo&>(MFI)
936 .getLocalFrameObjectCount();
937 bool HasExtraAlign = HRI.needsStackRealignment(MF);
938 bool HasAlloca = MFI.hasVarSizedObjects();
940 // Insert ALLOCFRAME if we need to or at -O0 for the debugger. Think
941 // that this shouldn't be required, but doing so now because gcc does and
942 // gdb can't break at the start of the function without it. Will remove if
943 // this turns out to be a gdb bug.
945 if (MF.getTarget().getOptLevel() == CodeGenOpt::None)
948 // By default we want to use SP (since it's always there). FP requires
949 // some setup (i.e. ALLOCFRAME).
950 // Fixed and preallocated objects need FP if the distance from them to
951 // the SP is unknown (as is with alloca or aligna).
952 if ((HasFixed || HasPrealloc) && (HasAlloca || HasExtraAlign))
955 if (MFI.getStackSize() > 0) {
956 if (EnableStackOVFSanitizer || UseAllocframe)
960 if (MFI.hasCalls() ||
961 MF.getInfo<HexagonMachineFunctionInfo>()->hasClobberLR())
973 static const char *getSpillFunctionFor(unsigned MaxReg, SpillKind SpillType,
974 bool Stkchk = false) {
975 const char * V4SpillToMemoryFunctions[] = {
976 "__save_r16_through_r17",
977 "__save_r16_through_r19",
978 "__save_r16_through_r21",
979 "__save_r16_through_r23",
980 "__save_r16_through_r25",
981 "__save_r16_through_r27" };
983 const char * V4SpillToMemoryStkchkFunctions[] = {
984 "__save_r16_through_r17_stkchk",
985 "__save_r16_through_r19_stkchk",
986 "__save_r16_through_r21_stkchk",
987 "__save_r16_through_r23_stkchk",
988 "__save_r16_through_r25_stkchk",
989 "__save_r16_through_r27_stkchk" };
991 const char * V4SpillFromMemoryFunctions[] = {
992 "__restore_r16_through_r17_and_deallocframe",
993 "__restore_r16_through_r19_and_deallocframe",
994 "__restore_r16_through_r21_and_deallocframe",
995 "__restore_r16_through_r23_and_deallocframe",
996 "__restore_r16_through_r25_and_deallocframe",
997 "__restore_r16_through_r27_and_deallocframe" };
999 const char * V4SpillFromMemoryTailcallFunctions[] = {
1000 "__restore_r16_through_r17_and_deallocframe_before_tailcall",
1001 "__restore_r16_through_r19_and_deallocframe_before_tailcall",
1002 "__restore_r16_through_r21_and_deallocframe_before_tailcall",
1003 "__restore_r16_through_r23_and_deallocframe_before_tailcall",
1004 "__restore_r16_through_r25_and_deallocframe_before_tailcall",
1005 "__restore_r16_through_r27_and_deallocframe_before_tailcall"
1008 const char **SpillFunc = nullptr;
1012 SpillFunc = Stkchk ? V4SpillToMemoryStkchkFunctions
1013 : V4SpillToMemoryFunctions;
1016 SpillFunc = V4SpillFromMemoryFunctions;
1018 case SK_FromMemTailcall:
1019 SpillFunc = V4SpillFromMemoryTailcallFunctions;
1022 assert(SpillFunc && "Unknown spill kind");
1024 // Spill all callee-saved registers up to the highest register used.
1027 return SpillFunc[0];
1029 return SpillFunc[1];
1031 return SpillFunc[2];
1033 return SpillFunc[3];
1035 return SpillFunc[4];
1037 return SpillFunc[5];
1039 llvm_unreachable("Unhandled maximum callee save register");
1044 int HexagonFrameLowering::getFrameIndexReference(const MachineFunction &MF,
1045 int FI, unsigned &FrameReg) const {
1046 auto &MFI = MF.getFrameInfo();
1047 auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
1049 int Offset = MFI.getObjectOffset(FI);
1050 bool HasAlloca = MFI.hasVarSizedObjects();
1051 bool HasExtraAlign = HRI.needsStackRealignment(MF);
1052 bool NoOpt = MF.getTarget().getOptLevel() == CodeGenOpt::None;
1054 unsigned FrameSize = MFI.getStackSize();
1055 unsigned SP = HRI.getStackRegister(), FP = HRI.getFrameRegister();
1056 auto &HMFI = *MF.getInfo<HexagonMachineFunctionInfo>();
1057 unsigned AP = HMFI.getStackAlignBasePhysReg();
1058 // It may happen that AP will be absent even HasAlloca && HasExtraAlign
1059 // is true. HasExtraAlign may be set because of vector spills, without
1060 // aligned locals or aligned outgoing function arguments. Since vector
1061 // spills will ultimately be "unaligned", it is safe to use FP as the
1063 // In fact, in such a scenario the stack is actually not required to be
1064 // aligned, although it may end up being aligned anyway, since this
1065 // particular case is not easily detectable. The alignment will be
1066 // unnecessary, but not incorrect.
1067 // Unfortunately there is no quick way to verify that the above is
1068 // indeed the case (and that it's not a result of an error), so just
1069 // assume that missing AP will be replaced by FP.
1070 // (A better fix would be to rematerialize AP from FP and always align
1075 bool UseFP = false, UseAP = false; // Default: use SP (except at -O0).
1076 // Use FP at -O0, except when there are objects with extra alignment.
1077 // That additional alignment requirement may cause a pad to be inserted,
1078 // which will make it impossible to use FP to access objects located
1080 if (NoOpt && !HasExtraAlign)
1082 if (MFI.isFixedObjectIndex(FI) || MFI.isObjectPreAllocated(FI)) {
1083 // Fixed and preallocated objects will be located before any padding
1084 // so FP must be used to access them.
1085 UseFP |= (HasAlloca || HasExtraAlign);
1095 // If FP was picked, then there had better be FP.
1096 bool HasFP = hasFP(MF);
1097 assert((HasFP || !UseFP) && "This function must have frame pointer");
1099 // Having FP implies allocframe. Allocframe will store extra 8 bytes:
1100 // FP/LR. If the base register is used to access an object across these
1101 // 8 bytes, then the offset will need to be adjusted by 8.
1103 // After allocframe:
1104 // HexagonISelLowering adds 8 to ---+
1105 // the offsets of all stack-based |
1108 // getObjectOffset < 0 0 8 getObjectOffset >= 8
1109 // ------------------------+-----+------------------------> increasing
1110 // <local objects> |FP/LR| <input arguments> addresses
1111 // -----------------+------+-----+------------------------>
1113 // SP/AP point --+ +-- FP points here (**)
1115 // this side of FP/LR
1117 // (*) See LowerFormalArguments. The FP/LR is assumed to be present.
1118 // (**) *FP == old-FP. FP+0..7 are the bytes of FP/LR.
1120 // The lowering assumes that FP/LR is present, and so the offsets of
1121 // the formal arguments start at 8. If FP/LR is not there we need to
1122 // reduce the offset by 8.
1123 if (Offset > 0 && !HasFP)
1133 // Calculate the actual offset in the instruction. If there is no FP
1134 // (in other words, no allocframe), then SP will not be adjusted (i.e.
1135 // there will be no SP -= FrameSize), so the frame size should not be
1136 // added to the calculated offset.
1137 int RealOffset = Offset;
1138 if (!UseFP && !UseAP && HasFP)
1139 RealOffset = FrameSize+Offset;
1143 bool HexagonFrameLowering::insertCSRSpillsInBlock(MachineBasicBlock &MBB,
1144 const CSIVect &CSI, const HexagonRegisterInfo &HRI,
1145 bool &PrologueStubs) const {
1149 MachineBasicBlock::iterator MI = MBB.begin();
1150 PrologueStubs = false;
1151 MachineFunction &MF = *MBB.getParent();
1152 auto &HST = MF.getSubtarget<HexagonSubtarget>();
1153 auto &HII = *HST.getInstrInfo();
1155 if (useSpillFunction(MF, CSI)) {
1156 PrologueStubs = true;
1157 unsigned MaxReg = getMaxCalleeSavedReg(CSI, HRI);
1158 bool StkOvrFlowEnabled = EnableStackOVFSanitizer;
1159 const char *SpillFun = getSpillFunctionFor(MaxReg, SK_ToMem,
1161 auto &HTM = static_cast<const HexagonTargetMachine&>(MF.getTarget());
1162 bool IsPIC = HTM.isPositionIndependent();
1163 bool LongCalls = HST.useLongCalls() || EnableSaveRestoreLong;
1165 // Call spill function.
1166 DebugLoc DL = MI != MBB.end() ? MI->getDebugLoc() : DebugLoc();
1168 if (StkOvrFlowEnabled) {
1170 SpillOpc = IsPIC ? Hexagon::SAVE_REGISTERS_CALL_V4STK_EXT_PIC
1171 : Hexagon::SAVE_REGISTERS_CALL_V4STK_EXT;
1173 SpillOpc = IsPIC ? Hexagon::SAVE_REGISTERS_CALL_V4STK_PIC
1174 : Hexagon::SAVE_REGISTERS_CALL_V4STK;
1177 SpillOpc = IsPIC ? Hexagon::SAVE_REGISTERS_CALL_V4_EXT_PIC
1178 : Hexagon::SAVE_REGISTERS_CALL_V4_EXT;
1180 SpillOpc = IsPIC ? Hexagon::SAVE_REGISTERS_CALL_V4_PIC
1181 : Hexagon::SAVE_REGISTERS_CALL_V4;
1184 MachineInstr *SaveRegsCall =
1185 BuildMI(MBB, MI, DL, HII.get(SpillOpc))
1186 .addExternalSymbol(SpillFun);
1188 // Add callee-saved registers as use.
1189 addCalleeSaveRegistersAsImpOperand(SaveRegsCall, CSI, false, true);
1190 // Add live in registers.
1191 for (unsigned I = 0; I < CSI.size(); ++I)
1192 MBB.addLiveIn(CSI[I].getReg());
1196 for (unsigned i = 0, n = CSI.size(); i < n; ++i) {
1197 unsigned Reg = CSI[i].getReg();
1198 // Add live in registers. We treat eh_return callee saved register r0 - r3
1199 // specially. They are not really callee saved registers as they are not
1200 // supposed to be killed.
1201 bool IsKill = !HRI.isEHReturnCalleeSaveReg(Reg);
1202 int FI = CSI[i].getFrameIdx();
1203 const TargetRegisterClass *RC = HRI.getMinimalPhysRegClass(Reg);
1204 HII.storeRegToStackSlot(MBB, MI, Reg, IsKill, FI, RC, &HRI);
1211 bool HexagonFrameLowering::insertCSRRestoresInBlock(MachineBasicBlock &MBB,
1212 const CSIVect &CSI, const HexagonRegisterInfo &HRI) const {
1216 MachineBasicBlock::iterator MI = MBB.getFirstTerminator();
1217 MachineFunction &MF = *MBB.getParent();
1218 auto &HST = MF.getSubtarget<HexagonSubtarget>();
1219 auto &HII = *HST.getInstrInfo();
1221 if (useRestoreFunction(MF, CSI)) {
1222 bool HasTC = hasTailCall(MBB) || !hasReturn(MBB);
1223 unsigned MaxR = getMaxCalleeSavedReg(CSI, HRI);
1224 SpillKind Kind = HasTC ? SK_FromMemTailcall : SK_FromMem;
1225 const char *RestoreFn = getSpillFunctionFor(MaxR, Kind);
1226 auto &HTM = static_cast<const HexagonTargetMachine&>(MF.getTarget());
1227 bool IsPIC = HTM.isPositionIndependent();
1228 bool LongCalls = HST.useLongCalls() || EnableSaveRestoreLong;
1230 // Call spill function.
1231 DebugLoc DL = MI != MBB.end() ? MI->getDebugLoc()
1232 : MBB.getLastNonDebugInstr()->getDebugLoc();
1233 MachineInstr *DeallocCall = nullptr;
1238 RetOpc = IsPIC ? Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_EXT_PIC
1239 : Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_EXT;
1241 RetOpc = IsPIC ? Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_PIC
1242 : Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4;
1243 DeallocCall = BuildMI(MBB, MI, DL, HII.get(RetOpc))
1244 .addExternalSymbol(RestoreFn);
1246 // The block has a return.
1247 MachineBasicBlock::iterator It = MBB.getFirstTerminator();
1248 assert(It->isReturn() && std::next(It) == MBB.end());
1251 RetOpc = IsPIC ? Hexagon::RESTORE_DEALLOC_RET_JMP_V4_EXT_PIC
1252 : Hexagon::RESTORE_DEALLOC_RET_JMP_V4_EXT;
1254 RetOpc = IsPIC ? Hexagon::RESTORE_DEALLOC_RET_JMP_V4_PIC
1255 : Hexagon::RESTORE_DEALLOC_RET_JMP_V4;
1256 DeallocCall = BuildMI(MBB, It, DL, HII.get(RetOpc))
1257 .addExternalSymbol(RestoreFn);
1258 // Transfer the function live-out registers.
1259 DeallocCall->copyImplicitOps(MF, *It);
1261 addCalleeSaveRegistersAsImpOperand(DeallocCall, CSI, true, false);
1265 for (unsigned i = 0; i < CSI.size(); ++i) {
1266 unsigned Reg = CSI[i].getReg();
1267 const TargetRegisterClass *RC = HRI.getMinimalPhysRegClass(Reg);
1268 int FI = CSI[i].getFrameIdx();
1269 HII.loadRegFromStackSlot(MBB, MI, Reg, FI, RC, &HRI);
1275 MachineBasicBlock::iterator HexagonFrameLowering::eliminateCallFramePseudoInstr(
1276 MachineFunction &MF, MachineBasicBlock &MBB,
1277 MachineBasicBlock::iterator I) const {
1278 MachineInstr &MI = *I;
1279 unsigned Opc = MI.getOpcode();
1280 (void)Opc; // Silence compiler warning.
1281 assert((Opc == Hexagon::ADJCALLSTACKDOWN || Opc == Hexagon::ADJCALLSTACKUP) &&
1282 "Cannot handle this call frame pseudo instruction");
1283 return MBB.erase(I);
1286 void HexagonFrameLowering::processFunctionBeforeFrameFinalized(
1287 MachineFunction &MF, RegScavenger *RS) const {
1288 // If this function has uses aligned stack and also has variable sized stack
1289 // objects, then we need to map all spill slots to fixed positions, so that
1290 // they can be accessed through FP. Otherwise they would have to be accessed
1291 // via AP, which may not be available at the particular place in the program.
1292 MachineFrameInfo &MFI = MF.getFrameInfo();
1293 bool HasAlloca = MFI.hasVarSizedObjects();
1294 bool NeedsAlign = (MFI.getMaxAlignment() > getStackAlignment());
1296 if (!HasAlloca || !NeedsAlign)
1299 unsigned LFS = MFI.getLocalFrameSize();
1300 for (int i = 0, e = MFI.getObjectIndexEnd(); i != e; ++i) {
1301 if (!MFI.isSpillSlotObjectIndex(i) || MFI.isDeadObjectIndex(i))
1303 unsigned S = MFI.getObjectSize(i);
1304 // Reduce the alignment to at most 8. This will require unaligned vector
1305 // stores if they happen here.
1306 unsigned A = std::max(MFI.getObjectAlignment(i), 8U);
1307 MFI.setObjectAlignment(i, 8);
1308 LFS = alignTo(LFS+S, A);
1309 MFI.mapLocalFrameObject(i, -LFS);
1312 MFI.setLocalFrameSize(LFS);
1313 unsigned A = MFI.getLocalFrameMaxAlign();
1314 assert(A <= 8 && "Unexpected local frame alignment");
1316 MFI.setLocalFrameMaxAlign(8);
1317 MFI.setUseLocalStackAllocationBlock(true);
1319 // Set the physical aligned-stack base address register.
1321 if (const MachineInstr *AI = getAlignaInstr(MF))
1322 AP = AI->getOperand(0).getReg();
1323 auto &HMFI = *MF.getInfo<HexagonMachineFunctionInfo>();
1324 HMFI.setStackAlignBasePhysReg(AP);
1327 /// Returns true if there are no caller-saved registers available in class RC.
1328 static bool needToReserveScavengingSpillSlots(MachineFunction &MF,
1329 const HexagonRegisterInfo &HRI, const TargetRegisterClass *RC) {
1330 MachineRegisterInfo &MRI = MF.getRegInfo();
1332 auto IsUsed = [&HRI,&MRI] (unsigned Reg) -> bool {
1333 for (MCRegAliasIterator AI(Reg, &HRI, true); AI.isValid(); ++AI)
1334 if (MRI.isPhysRegUsed(*AI))
1339 // Check for an unused caller-saved register. Callee-saved registers
1340 // have become pristine by now.
1341 for (const MCPhysReg *P = HRI.getCallerSavedRegs(&MF, RC); *P; ++P)
1345 // All caller-saved registers are used.
1350 static void dump_registers(BitVector &Regs, const TargetRegisterInfo &TRI) {
1352 for (int x = Regs.find_first(); x >= 0; x = Regs.find_next(x)) {
1354 dbgs() << ' ' << PrintReg(R, &TRI);
1360 bool HexagonFrameLowering::assignCalleeSavedSpillSlots(MachineFunction &MF,
1361 const TargetRegisterInfo *TRI, std::vector<CalleeSavedInfo> &CSI) const {
1362 DEBUG(dbgs() << __func__ << " on "
1363 << MF.getFunction()->getName() << '\n');
1364 MachineFrameInfo &MFI = MF.getFrameInfo();
1365 BitVector SRegs(Hexagon::NUM_TARGET_REGS);
1367 // Generate a set of unique, callee-saved registers (SRegs), where each
1368 // register in the set is maximal in terms of sub-/super-register relation,
1369 // i.e. for each R in SRegs, no proper super-register of R is also in SRegs.
1371 // (1) For each callee-saved register, add that register and all of its
1372 // sub-registers to SRegs.
1373 DEBUG(dbgs() << "Initial CS registers: {");
1374 for (unsigned i = 0, n = CSI.size(); i < n; ++i) {
1375 unsigned R = CSI[i].getReg();
1376 DEBUG(dbgs() << ' ' << PrintReg(R, TRI));
1377 for (MCSubRegIterator SR(R, TRI, true); SR.isValid(); ++SR)
1380 DEBUG(dbgs() << " }\n");
1381 DEBUG(dbgs() << "SRegs.1: "; dump_registers(SRegs, *TRI); dbgs() << "\n");
1383 // (2) For each reserved register, remove that register and all of its
1384 // sub- and super-registers from SRegs.
1385 BitVector Reserved = TRI->getReservedRegs(MF);
1386 for (int x = Reserved.find_first(); x >= 0; x = Reserved.find_next(x)) {
1388 for (MCSuperRegIterator SR(R, TRI, true); SR.isValid(); ++SR)
1391 DEBUG(dbgs() << "Res: "; dump_registers(Reserved, *TRI); dbgs() << "\n");
1392 DEBUG(dbgs() << "SRegs.2: "; dump_registers(SRegs, *TRI); dbgs() << "\n");
1394 // (3) Collect all registers that have at least one sub-register in SRegs,
1395 // and also have no sub-registers that are reserved. These will be the can-
1396 // didates for saving as a whole instead of their individual sub-registers.
1397 // (Saving R17:16 instead of R16 is fine, but only if R17 was not reserved.)
1398 BitVector TmpSup(Hexagon::NUM_TARGET_REGS);
1399 for (int x = SRegs.find_first(); x >= 0; x = SRegs.find_next(x)) {
1401 for (MCSuperRegIterator SR(R, TRI); SR.isValid(); ++SR)
1404 for (int x = TmpSup.find_first(); x >= 0; x = TmpSup.find_next(x)) {
1406 for (MCSubRegIterator SR(R, TRI, true); SR.isValid(); ++SR) {
1413 DEBUG(dbgs() << "TmpSup: "; dump_registers(TmpSup, *TRI); dbgs() << "\n");
1415 // (4) Include all super-registers found in (3) into SRegs.
1417 DEBUG(dbgs() << "SRegs.4: "; dump_registers(SRegs, *TRI); dbgs() << "\n");
1419 // (5) For each register R in SRegs, if any super-register of R is in SRegs,
1420 // remove R from SRegs.
1421 for (int x = SRegs.find_first(); x >= 0; x = SRegs.find_next(x)) {
1423 for (MCSuperRegIterator SR(R, TRI); SR.isValid(); ++SR) {
1430 DEBUG(dbgs() << "SRegs.5: "; dump_registers(SRegs, *TRI); dbgs() << "\n");
1432 // Now, for each register that has a fixed stack slot, create the stack
1436 typedef TargetFrameLowering::SpillSlot SpillSlot;
1438 int MinOffset = 0; // CS offsets are negative.
1439 const SpillSlot *FixedSlots = getCalleeSavedSpillSlots(NumFixed);
1440 for (const SpillSlot *S = FixedSlots; S != FixedSlots+NumFixed; ++S) {
1443 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(S->Reg);
1444 int FI = MFI.CreateFixedSpillStackObject(TRI->getSpillSize(*RC), S->Offset);
1445 MinOffset = std::min(MinOffset, S->Offset);
1446 CSI.push_back(CalleeSavedInfo(S->Reg, FI));
1447 SRegs[S->Reg] = false;
1450 // There can be some registers that don't have fixed slots. For example,
1451 // we need to store R0-R3 in functions with exception handling. For each
1452 // such register, create a non-fixed stack object.
1453 for (int x = SRegs.find_first(); x >= 0; x = SRegs.find_next(x)) {
1455 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(R);
1456 unsigned Size = TRI->getSpillSize(*RC);
1457 int Off = MinOffset - Size;
1458 unsigned Align = std::min(TRI->getSpillAlignment(*RC), getStackAlignment());
1459 assert(isPowerOf2_32(Align));
1461 int FI = MFI.CreateFixedSpillStackObject(Size, Off);
1462 MinOffset = std::min(MinOffset, Off);
1463 CSI.push_back(CalleeSavedInfo(R, FI));
1468 dbgs() << "CS information: {";
1469 for (unsigned i = 0, n = CSI.size(); i < n; ++i) {
1470 int FI = CSI[i].getFrameIdx();
1471 int Off = MFI.getObjectOffset(FI);
1472 dbgs() << ' ' << PrintReg(CSI[i].getReg(), TRI) << ":fi#" << FI << ":sp";
1481 // Verify that all registers were handled.
1482 bool MissedReg = false;
1483 for (int x = SRegs.find_first(); x >= 0; x = SRegs.find_next(x)) {
1485 dbgs() << PrintReg(R, TRI) << ' ';
1489 llvm_unreachable("...there are unhandled callee-saved registers!");
1495 bool HexagonFrameLowering::expandCopy(MachineBasicBlock &B,
1496 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1497 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1498 MachineInstr *MI = &*It;
1499 DebugLoc DL = MI->getDebugLoc();
1500 unsigned DstR = MI->getOperand(0).getReg();
1501 unsigned SrcR = MI->getOperand(1).getReg();
1502 if (!Hexagon::ModRegsRegClass.contains(DstR) ||
1503 !Hexagon::ModRegsRegClass.contains(SrcR))
1506 unsigned TmpR = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
1507 BuildMI(B, It, DL, HII.get(TargetOpcode::COPY), TmpR).add(MI->getOperand(1));
1508 BuildMI(B, It, DL, HII.get(TargetOpcode::COPY), DstR)
1509 .addReg(TmpR, RegState::Kill);
1511 NewRegs.push_back(TmpR);
1516 bool HexagonFrameLowering::expandStoreInt(MachineBasicBlock &B,
1517 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1518 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1519 MachineInstr *MI = &*It;
1520 if (!MI->getOperand(0).isFI())
1523 DebugLoc DL = MI->getDebugLoc();
1524 unsigned Opc = MI->getOpcode();
1525 unsigned SrcR = MI->getOperand(2).getReg();
1526 bool IsKill = MI->getOperand(2).isKill();
1527 int FI = MI->getOperand(0).getIndex();
1529 // TmpR = C2_tfrpr SrcR if SrcR is a predicate register
1530 // TmpR = A2_tfrcrr SrcR if SrcR is a modifier register
1531 unsigned TmpR = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
1532 unsigned TfrOpc = (Opc == Hexagon::STriw_pred) ? Hexagon::C2_tfrpr
1533 : Hexagon::A2_tfrcrr;
1534 BuildMI(B, It, DL, HII.get(TfrOpc), TmpR)
1535 .addReg(SrcR, getKillRegState(IsKill));
1537 // S2_storeri_io FI, 0, TmpR
1538 BuildMI(B, It, DL, HII.get(Hexagon::S2_storeri_io))
1541 .addReg(TmpR, RegState::Kill)
1542 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1544 NewRegs.push_back(TmpR);
1549 bool HexagonFrameLowering::expandLoadInt(MachineBasicBlock &B,
1550 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1551 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1552 MachineInstr *MI = &*It;
1553 if (!MI->getOperand(1).isFI())
1556 DebugLoc DL = MI->getDebugLoc();
1557 unsigned Opc = MI->getOpcode();
1558 unsigned DstR = MI->getOperand(0).getReg();
1559 int FI = MI->getOperand(1).getIndex();
1561 // TmpR = L2_loadri_io FI, 0
1562 unsigned TmpR = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
1563 BuildMI(B, It, DL, HII.get(Hexagon::L2_loadri_io), TmpR)
1566 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1568 // DstR = C2_tfrrp TmpR if DstR is a predicate register
1569 // DstR = A2_tfrrcr TmpR if DstR is a modifier register
1570 unsigned TfrOpc = (Opc == Hexagon::LDriw_pred) ? Hexagon::C2_tfrrp
1571 : Hexagon::A2_tfrrcr;
1572 BuildMI(B, It, DL, HII.get(TfrOpc), DstR)
1573 .addReg(TmpR, RegState::Kill);
1575 NewRegs.push_back(TmpR);
1580 bool HexagonFrameLowering::expandStoreVecPred(MachineBasicBlock &B,
1581 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1582 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1583 auto &HST = B.getParent()->getSubtarget<HexagonSubtarget>();
1584 MachineInstr *MI = &*It;
1585 if (!MI->getOperand(0).isFI())
1588 DebugLoc DL = MI->getDebugLoc();
1589 unsigned SrcR = MI->getOperand(2).getReg();
1590 bool IsKill = MI->getOperand(2).isKill();
1591 int FI = MI->getOperand(0).getIndex();
1593 bool Is128B = HST.useHVXDblOps();
1594 auto *RC = !Is128B ? &Hexagon::VectorRegsRegClass
1595 : &Hexagon::VectorRegs128BRegClass;
1597 // Insert transfer to general vector register.
1598 // TmpR0 = A2_tfrsi 0x01010101
1599 // TmpR1 = V6_vandqrt Qx, TmpR0
1600 // store FI, 0, TmpR1
1601 unsigned TmpR0 = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
1602 unsigned TmpR1 = MRI.createVirtualRegister(RC);
1604 BuildMI(B, It, DL, HII.get(Hexagon::A2_tfrsi), TmpR0)
1605 .addImm(0x01010101);
1607 unsigned VandOpc = !Is128B ? Hexagon::V6_vandqrt : Hexagon::V6_vandqrt_128B;
1608 BuildMI(B, It, DL, HII.get(VandOpc), TmpR1)
1609 .addReg(SrcR, getKillRegState(IsKill))
1610 .addReg(TmpR0, RegState::Kill);
1612 auto *HRI = B.getParent()->getSubtarget<HexagonSubtarget>().getRegisterInfo();
1613 HII.storeRegToStackSlot(B, It, TmpR1, true, FI, RC, HRI);
1614 expandStoreVec(B, std::prev(It), MRI, HII, NewRegs);
1616 NewRegs.push_back(TmpR0);
1617 NewRegs.push_back(TmpR1);
1622 bool HexagonFrameLowering::expandLoadVecPred(MachineBasicBlock &B,
1623 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1624 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1625 auto &HST = B.getParent()->getSubtarget<HexagonSubtarget>();
1626 MachineInstr *MI = &*It;
1627 if (!MI->getOperand(1).isFI())
1630 DebugLoc DL = MI->getDebugLoc();
1631 unsigned DstR = MI->getOperand(0).getReg();
1632 int FI = MI->getOperand(1).getIndex();
1634 bool Is128B = HST.useHVXDblOps();
1635 auto *RC = !Is128B ? &Hexagon::VectorRegsRegClass
1636 : &Hexagon::VectorRegs128BRegClass;
1638 // TmpR0 = A2_tfrsi 0x01010101
1639 // TmpR1 = load FI, 0
1640 // DstR = V6_vandvrt TmpR1, TmpR0
1641 unsigned TmpR0 = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
1642 unsigned TmpR1 = MRI.createVirtualRegister(RC);
1644 BuildMI(B, It, DL, HII.get(Hexagon::A2_tfrsi), TmpR0)
1645 .addImm(0x01010101);
1646 auto *HRI = B.getParent()->getSubtarget<HexagonSubtarget>().getRegisterInfo();
1647 HII.loadRegFromStackSlot(B, It, TmpR1, FI, RC, HRI);
1648 expandLoadVec(B, std::prev(It), MRI, HII, NewRegs);
1650 unsigned VandOpc = !Is128B ? Hexagon::V6_vandvrt : Hexagon::V6_vandvrt_128B;
1651 BuildMI(B, It, DL, HII.get(VandOpc), DstR)
1652 .addReg(TmpR1, RegState::Kill)
1653 .addReg(TmpR0, RegState::Kill);
1655 NewRegs.push_back(TmpR0);
1656 NewRegs.push_back(TmpR1);
1661 bool HexagonFrameLowering::expandStoreVec2(MachineBasicBlock &B,
1662 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1663 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1664 MachineFunction &MF = *B.getParent();
1665 auto &HST = MF.getSubtarget<HexagonSubtarget>();
1666 auto &MFI = MF.getFrameInfo();
1667 auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
1668 MachineInstr *MI = &*It;
1669 if (!MI->getOperand(0).isFI())
1672 // It is possible that the double vector being stored is only partially
1673 // defined. From the point of view of the liveness tracking, it is ok to
1674 // store it as a whole, but if we break it up we may end up storing a
1675 // register that is entirely undefined.
1676 LivePhysRegs LPR(HRI);
1678 SmallVector<std::pair<unsigned, const MachineOperand*>,2> Clobbers;
1679 for (auto R = B.begin(); R != It; ++R) {
1681 LPR.stepForward(*R, Clobbers);
1682 // Dead defs are recorded in Clobbers, but are not automatically removed
1683 // from the live set.
1684 for (auto &C : Clobbers)
1685 if (C.second->isReg() && C.second->isDead())
1686 LPR.removeReg(C.first);
1689 DebugLoc DL = MI->getDebugLoc();
1690 unsigned SrcR = MI->getOperand(2).getReg();
1691 unsigned SrcLo = HRI.getSubReg(SrcR, Hexagon::vsub_lo);
1692 unsigned SrcHi = HRI.getSubReg(SrcR, Hexagon::vsub_hi);
1693 bool IsKill = MI->getOperand(2).isKill();
1694 int FI = MI->getOperand(0).getIndex();
1696 bool Is128B = HST.useHVXDblOps();
1697 const auto &RC = !Is128B ? Hexagon::VectorRegsRegClass
1698 : Hexagon::VectorRegs128BRegClass;
1699 unsigned Size = HRI.getSpillSize(RC);
1700 unsigned NeedAlign = HRI.getSpillAlignment(RC);
1701 unsigned HasAlign = MFI.getObjectAlignment(FI);
1705 if (LPR.contains(SrcLo)) {
1706 if (NeedAlign <= HasAlign)
1707 StoreOpc = !Is128B ? Hexagon::V6_vS32b_ai : Hexagon::V6_vS32b_ai_128B;
1709 StoreOpc = !Is128B ? Hexagon::V6_vS32Ub_ai : Hexagon::V6_vS32Ub_ai_128B;
1711 BuildMI(B, It, DL, HII.get(StoreOpc))
1714 .addReg(SrcLo, getKillRegState(IsKill))
1715 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1719 if (LPR.contains(SrcHi)) {
1720 if (NeedAlign <= MinAlign(HasAlign, Size))
1721 StoreOpc = !Is128B ? Hexagon::V6_vS32b_ai : Hexagon::V6_vS32b_ai_128B;
1723 StoreOpc = !Is128B ? Hexagon::V6_vS32Ub_ai : Hexagon::V6_vS32Ub_ai_128B;
1725 BuildMI(B, It, DL, HII.get(StoreOpc))
1728 .addReg(SrcHi, getKillRegState(IsKill))
1729 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1736 bool HexagonFrameLowering::expandLoadVec2(MachineBasicBlock &B,
1737 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1738 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1739 MachineFunction &MF = *B.getParent();
1740 auto &HST = MF.getSubtarget<HexagonSubtarget>();
1741 auto &MFI = MF.getFrameInfo();
1742 auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
1743 MachineInstr *MI = &*It;
1744 if (!MI->getOperand(1).isFI())
1747 DebugLoc DL = MI->getDebugLoc();
1748 unsigned DstR = MI->getOperand(0).getReg();
1749 unsigned DstHi = HRI.getSubReg(DstR, Hexagon::vsub_hi);
1750 unsigned DstLo = HRI.getSubReg(DstR, Hexagon::vsub_lo);
1751 int FI = MI->getOperand(1).getIndex();
1753 bool Is128B = HST.useHVXDblOps();
1754 const auto &RC = !Is128B ? Hexagon::VectorRegsRegClass
1755 : Hexagon::VectorRegs128BRegClass;
1756 unsigned Size = HRI.getSpillSize(RC);
1757 unsigned NeedAlign = HRI.getSpillAlignment(RC);
1758 unsigned HasAlign = MFI.getObjectAlignment(FI);
1762 if (NeedAlign <= HasAlign)
1763 LoadOpc = !Is128B ? Hexagon::V6_vL32b_ai : Hexagon::V6_vL32b_ai_128B;
1765 LoadOpc = !Is128B ? Hexagon::V6_vL32Ub_ai : Hexagon::V6_vL32Ub_ai_128B;
1767 BuildMI(B, It, DL, HII.get(LoadOpc), DstLo)
1770 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1773 if (NeedAlign <= MinAlign(HasAlign, Size))
1774 LoadOpc = !Is128B ? Hexagon::V6_vL32b_ai : Hexagon::V6_vL32b_ai_128B;
1776 LoadOpc = !Is128B ? Hexagon::V6_vL32Ub_ai : Hexagon::V6_vL32Ub_ai_128B;
1778 BuildMI(B, It, DL, HII.get(LoadOpc), DstHi)
1781 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1787 bool HexagonFrameLowering::expandStoreVec(MachineBasicBlock &B,
1788 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1789 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1790 MachineFunction &MF = *B.getParent();
1791 auto &HST = MF.getSubtarget<HexagonSubtarget>();
1792 auto &MFI = MF.getFrameInfo();
1793 MachineInstr *MI = &*It;
1794 if (!MI->getOperand(0).isFI())
1797 auto &HRI = *HST.getRegisterInfo();
1798 DebugLoc DL = MI->getDebugLoc();
1799 unsigned SrcR = MI->getOperand(2).getReg();
1800 bool IsKill = MI->getOperand(2).isKill();
1801 int FI = MI->getOperand(0).getIndex();
1803 bool Is128B = HST.useHVXDblOps();
1804 const auto &RC = !Is128B ? Hexagon::VectorRegsRegClass
1805 : Hexagon::VectorRegs128BRegClass;
1806 unsigned NeedAlign = HRI.getSpillAlignment(RC);
1807 unsigned HasAlign = MFI.getObjectAlignment(FI);
1810 if (NeedAlign <= HasAlign)
1811 StoreOpc = !Is128B ? Hexagon::V6_vS32b_ai : Hexagon::V6_vS32b_ai_128B;
1813 StoreOpc = !Is128B ? Hexagon::V6_vS32Ub_ai : Hexagon::V6_vS32Ub_ai_128B;
1815 BuildMI(B, It, DL, HII.get(StoreOpc))
1818 .addReg(SrcR, getKillRegState(IsKill))
1819 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1825 bool HexagonFrameLowering::expandLoadVec(MachineBasicBlock &B,
1826 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1827 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1828 MachineFunction &MF = *B.getParent();
1829 auto &HST = MF.getSubtarget<HexagonSubtarget>();
1830 auto &MFI = MF.getFrameInfo();
1831 MachineInstr *MI = &*It;
1832 if (!MI->getOperand(1).isFI())
1835 auto &HRI = *HST.getRegisterInfo();
1836 DebugLoc DL = MI->getDebugLoc();
1837 unsigned DstR = MI->getOperand(0).getReg();
1838 int FI = MI->getOperand(1).getIndex();
1840 bool Is128B = HST.useHVXDblOps();
1841 const auto &RC = !Is128B ? Hexagon::VectorRegsRegClass
1842 : Hexagon::VectorRegs128BRegClass;
1843 unsigned NeedAlign = HRI.getSpillAlignment(RC);
1844 unsigned HasAlign = MFI.getObjectAlignment(FI);
1847 if (NeedAlign <= HasAlign)
1848 LoadOpc = !Is128B ? Hexagon::V6_vL32b_ai : Hexagon::V6_vL32b_ai_128B;
1850 LoadOpc = !Is128B ? Hexagon::V6_vL32Ub_ai : Hexagon::V6_vL32Ub_ai_128B;
1852 BuildMI(B, It, DL, HII.get(LoadOpc), DstR)
1855 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1861 bool HexagonFrameLowering::expandSpillMacros(MachineFunction &MF,
1862 SmallVectorImpl<unsigned> &NewRegs) const {
1863 auto &HST = MF.getSubtarget<HexagonSubtarget>();
1864 auto &HII = *HST.getInstrInfo();
1865 MachineRegisterInfo &MRI = MF.getRegInfo();
1866 bool Changed = false;
1868 for (auto &B : MF) {
1869 // Traverse the basic block.
1870 MachineBasicBlock::iterator NextI;
1871 for (auto I = B.begin(), E = B.end(); I != E; I = NextI) {
1872 MachineInstr *MI = &*I;
1873 NextI = std::next(I);
1874 unsigned Opc = MI->getOpcode();
1877 case TargetOpcode::COPY:
1878 Changed |= expandCopy(B, I, MRI, HII, NewRegs);
1880 case Hexagon::STriw_pred:
1881 case Hexagon::STriw_mod:
1882 Changed |= expandStoreInt(B, I, MRI, HII, NewRegs);
1884 case Hexagon::LDriw_pred:
1885 case Hexagon::LDriw_mod:
1886 Changed |= expandLoadInt(B, I, MRI, HII, NewRegs);
1888 case Hexagon::PS_vstorerq_ai:
1889 case Hexagon::PS_vstorerq_ai_128B:
1890 Changed |= expandStoreVecPred(B, I, MRI, HII, NewRegs);
1892 case Hexagon::PS_vloadrq_ai:
1893 case Hexagon::PS_vloadrq_ai_128B:
1894 Changed |= expandLoadVecPred(B, I, MRI, HII, NewRegs);
1896 case Hexagon::PS_vloadrw_ai:
1897 case Hexagon::PS_vloadrwu_ai:
1898 case Hexagon::PS_vloadrw_ai_128B:
1899 case Hexagon::PS_vloadrwu_ai_128B:
1900 Changed |= expandLoadVec2(B, I, MRI, HII, NewRegs);
1902 case Hexagon::PS_vstorerw_ai:
1903 case Hexagon::PS_vstorerwu_ai:
1904 case Hexagon::PS_vstorerw_ai_128B:
1905 case Hexagon::PS_vstorerwu_ai_128B:
1906 Changed |= expandStoreVec2(B, I, MRI, HII, NewRegs);
1915 void HexagonFrameLowering::determineCalleeSaves(MachineFunction &MF,
1916 BitVector &SavedRegs,
1917 RegScavenger *RS) const {
1918 auto &HST = MF.getSubtarget<HexagonSubtarget>();
1919 auto &HRI = *HST.getRegisterInfo();
1921 SavedRegs.resize(HRI.getNumRegs());
1923 // If we have a function containing __builtin_eh_return we want to spill and
1924 // restore all callee saved registers. Pretend that they are used.
1925 if (MF.getInfo<HexagonMachineFunctionInfo>()->hasEHReturn())
1926 for (const MCPhysReg *R = HRI.getCalleeSavedRegs(&MF); *R; ++R)
1929 // Replace predicate register pseudo spill code.
1930 SmallVector<unsigned,8> NewRegs;
1931 expandSpillMacros(MF, NewRegs);
1932 if (OptimizeSpillSlots && !isOptNone(MF))
1933 optimizeSpillSlots(MF, NewRegs);
1935 // We need to reserve a a spill slot if scavenging could potentially require
1936 // spilling a scavenged register.
1937 if (!NewRegs.empty() || mayOverflowFrameOffset(MF)) {
1938 MachineFrameInfo &MFI = MF.getFrameInfo();
1939 MachineRegisterInfo &MRI = MF.getRegInfo();
1940 SetVector<const TargetRegisterClass*> SpillRCs;
1941 // Reserve an int register in any case, because it could be used to hold
1942 // the stack offset in case it does not fit into a spill instruction.
1943 SpillRCs.insert(&Hexagon::IntRegsRegClass);
1945 for (unsigned VR : NewRegs)
1946 SpillRCs.insert(MRI.getRegClass(VR));
1948 for (auto *RC : SpillRCs) {
1949 if (!needToReserveScavengingSpillSlots(MF, HRI, RC))
1951 unsigned Num = RC == &Hexagon::IntRegsRegClass ? NumberScavengerSlots : 1;
1952 unsigned S = HRI.getSpillSize(*RC), A = HRI.getSpillAlignment(*RC);
1953 for (unsigned i = 0; i < Num; i++) {
1954 int NewFI = MFI.CreateSpillStackObject(S, A);
1955 RS->addScavengingFrameIndex(NewFI);
1960 TargetFrameLowering::determineCalleeSaves(MF, SavedRegs, RS);
1963 unsigned HexagonFrameLowering::findPhysReg(MachineFunction &MF,
1964 HexagonBlockRanges::IndexRange &FIR,
1965 HexagonBlockRanges::InstrIndexMap &IndexMap,
1966 HexagonBlockRanges::RegToRangeMap &DeadMap,
1967 const TargetRegisterClass *RC) const {
1968 auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
1969 auto &MRI = MF.getRegInfo();
1971 auto isDead = [&FIR,&DeadMap] (unsigned Reg) -> bool {
1972 auto F = DeadMap.find({Reg,0});
1973 if (F == DeadMap.end())
1975 for (auto &DR : F->second)
1976 if (DR.contains(FIR))
1981 for (unsigned Reg : RC->getRawAllocationOrder(MF)) {
1983 for (auto R : HexagonBlockRanges::expandToSubRegs({Reg,0}, MRI, HRI)) {
1995 void HexagonFrameLowering::optimizeSpillSlots(MachineFunction &MF,
1996 SmallVectorImpl<unsigned> &VRegs) const {
1997 auto &HST = MF.getSubtarget<HexagonSubtarget>();
1998 auto &HII = *HST.getInstrInfo();
1999 auto &HRI = *HST.getRegisterInfo();
2000 auto &MRI = MF.getRegInfo();
2001 HexagonBlockRanges HBR(MF);
2003 typedef std::map<MachineBasicBlock*,HexagonBlockRanges::InstrIndexMap>
2005 typedef std::map<MachineBasicBlock*,HexagonBlockRanges::RangeList>
2007 typedef HexagonBlockRanges::IndexType IndexType;
2012 const TargetRegisterClass *RC = nullptr;
2014 SlotInfo() = default;
2017 BlockIndexMap BlockIndexes;
2018 SmallSet<int,4> BadFIs;
2019 std::map<int,SlotInfo> FIRangeMap;
2021 // Accumulate register classes: get a common class for a pre-existing
2022 // class HaveRC and a new class NewRC. Return nullptr if a common class
2023 // cannot be found, otherwise return the resulting class. If HaveRC is
2024 // nullptr, assume that it is still unset.
2026 [](const TargetRegisterClass *HaveRC,
2027 const TargetRegisterClass *NewRC) -> const TargetRegisterClass * {
2028 if (HaveRC == nullptr || HaveRC == NewRC)
2030 // Different classes, both non-null. Pick the more general one.
2031 if (HaveRC->hasSubClassEq(NewRC))
2033 if (NewRC->hasSubClassEq(HaveRC))
2038 // Scan all blocks in the function. Check all occurrences of frame indexes,
2039 // and collect relevant information.
2040 for (auto &B : MF) {
2041 std::map<int,IndexType> LastStore, LastLoad;
2042 // Emplace appears not to be supported in gcc 4.7.2-4.
2043 //auto P = BlockIndexes.emplace(&B, HexagonBlockRanges::InstrIndexMap(B));
2044 auto P = BlockIndexes.insert(
2045 std::make_pair(&B, HexagonBlockRanges::InstrIndexMap(B)));
2046 auto &IndexMap = P.first->second;
2047 DEBUG(dbgs() << "Index map for BB#" << B.getNumber() << "\n"
2048 << IndexMap << '\n');
2050 for (auto &In : B) {
2052 bool Load = HII.isLoadFromStackSlot(In, LFI) && !HII.isPredicated(In);
2053 bool Store = HII.isStoreToStackSlot(In, SFI) && !HII.isPredicated(In);
2054 if (Load && Store) {
2055 // If it's both a load and a store, then we won't handle it.
2060 // Check for register classes of the register used as the source for
2061 // the store, and the register used as the destination for the load.
2062 // Also, only accept base+imm_offset addressing modes. Other addressing
2063 // modes can have side-effects (post-increments, etc.). For stack
2064 // slots they are very unlikely, so there is not much loss due to
2065 // this restriction.
2066 if (Load || Store) {
2067 int TFI = Load ? LFI : SFI;
2068 unsigned AM = HII.getAddrMode(In);
2069 SlotInfo &SI = FIRangeMap[TFI];
2070 bool Bad = (AM != HexagonII::BaseImmOffset);
2072 // If the addressing mode is ok, check the register class.
2073 unsigned OpNum = Load ? 0 : 2;
2074 auto *RC = HII.getRegClass(In.getDesc(), OpNum, &HRI, MF);
2075 RC = getCommonRC(SI.RC, RC);
2083 unsigned S = (1U << (HII.getMemAccessSize(In) - 1));
2084 if (SI.Size != 0 && SI.Size != S)
2090 for (auto *Mo : In.memoperands()) {
2091 if (!Mo->isVolatile())
2101 // Locate uses of frame indices.
2102 for (unsigned i = 0, n = In.getNumOperands(); i < n; ++i) {
2103 const MachineOperand &Op = In.getOperand(i);
2106 int FI = Op.getIndex();
2107 // Make sure that the following operand is an immediate and that
2108 // it is 0. This is the offset in the stack object.
2109 if (i+1 >= n || !In.getOperand(i+1).isImm() ||
2110 In.getOperand(i+1).getImm() != 0)
2112 if (BadFIs.count(FI))
2115 IndexType Index = IndexMap.getIndex(&In);
2117 if (LastStore[FI] == IndexType::None)
2118 LastStore[FI] = IndexType::Entry;
2119 LastLoad[FI] = Index;
2121 HexagonBlockRanges::RangeList &RL = FIRangeMap[FI].Map[&B];
2122 if (LastStore[FI] != IndexType::None)
2123 RL.add(LastStore[FI], LastLoad[FI], false, false);
2124 else if (LastLoad[FI] != IndexType::None)
2125 RL.add(IndexType::Entry, LastLoad[FI], false, false);
2126 LastLoad[FI] = IndexType::None;
2127 LastStore[FI] = Index;
2134 for (auto &I : LastLoad) {
2135 IndexType LL = I.second;
2136 if (LL == IndexType::None)
2138 auto &RL = FIRangeMap[I.first].Map[&B];
2139 IndexType &LS = LastStore[I.first];
2140 if (LS != IndexType::None)
2141 RL.add(LS, LL, false, false);
2143 RL.add(IndexType::Entry, LL, false, false);
2144 LS = IndexType::None;
2146 for (auto &I : LastStore) {
2147 IndexType LS = I.second;
2148 if (LS == IndexType::None)
2150 auto &RL = FIRangeMap[I.first].Map[&B];
2151 RL.add(LS, IndexType::None, false, false);
2156 for (auto &P : FIRangeMap) {
2157 dbgs() << "fi#" << P.first;
2158 if (BadFIs.count(P.first))
2161 if (P.second.RC != nullptr)
2162 dbgs() << HRI.getRegClassName(P.second.RC) << '\n';
2164 dbgs() << "<null>\n";
2165 for (auto &R : P.second.Map)
2166 dbgs() << " BB#" << R.first->getNumber() << " { " << R.second << "}\n";
2170 // When a slot is loaded from in a block without being stored to in the
2171 // same block, it is live-on-entry to this block. To avoid CFG analysis,
2172 // consider this slot to be live-on-exit from all blocks.
2173 SmallSet<int,4> LoxFIs;
2175 std::map<MachineBasicBlock*,std::vector<int>> BlockFIMap;
2177 for (auto &P : FIRangeMap) {
2178 // P = pair(FI, map: BB->RangeList)
2179 if (BadFIs.count(P.first))
2181 for (auto &B : MF) {
2182 auto F = P.second.Map.find(&B);
2183 // F = pair(BB, RangeList)
2184 if (F == P.second.Map.end() || F->second.empty())
2186 HexagonBlockRanges::IndexRange &IR = F->second.front();
2187 if (IR.start() == IndexType::Entry)
2188 LoxFIs.insert(P.first);
2189 BlockFIMap[&B].push_back(P.first);
2194 dbgs() << "Block-to-FI map (* -- live-on-exit):\n";
2195 for (auto &P : BlockFIMap) {
2196 auto &FIs = P.second;
2199 dbgs() << " BB#" << P.first->getNumber() << ": {";
2200 for (auto I : FIs) {
2201 dbgs() << " fi#" << I;
2202 if (LoxFIs.count(I))
2210 bool HasOptLimit = SpillOptMax.getPosition();
2213 // eliminate loads, when all loads eliminated, eliminate all stores.
2214 for (auto &B : MF) {
2215 auto F = BlockIndexes.find(&B);
2216 assert(F != BlockIndexes.end());
2217 HexagonBlockRanges::InstrIndexMap &IM = F->second;
2218 HexagonBlockRanges::RegToRangeMap LM = HBR.computeLiveMap(IM);
2219 HexagonBlockRanges::RegToRangeMap DM = HBR.computeDeadMap(IM, LM);
2220 DEBUG(dbgs() << "BB#" << B.getNumber() << " dead map\n"
2221 << HexagonBlockRanges::PrintRangeMap(DM, HRI));
2223 for (auto FI : BlockFIMap[&B]) {
2224 if (BadFIs.count(FI))
2226 DEBUG(dbgs() << "Working on fi#" << FI << '\n');
2227 HexagonBlockRanges::RangeList &RL = FIRangeMap[FI].Map[&B];
2228 for (auto &Range : RL) {
2229 DEBUG(dbgs() << "--Examining range:" << RL << '\n');
2230 if (!IndexType::isInstr(Range.start()) ||
2231 !IndexType::isInstr(Range.end()))
2233 MachineInstr &SI = *IM.getInstr(Range.start());
2234 MachineInstr &EI = *IM.getInstr(Range.end());
2235 assert(SI.mayStore() && "Unexpected start instruction");
2236 assert(EI.mayLoad() && "Unexpected end instruction");
2237 MachineOperand &SrcOp = SI.getOperand(2);
2239 HexagonBlockRanges::RegisterRef SrcRR = { SrcOp.getReg(),
2240 SrcOp.getSubReg() };
2241 auto *RC = HII.getRegClass(SI.getDesc(), 2, &HRI, MF);
2242 // The this-> is needed to unconfuse MSVC.
2243 unsigned FoundR = this->findPhysReg(MF, Range, IM, DM, RC);
2244 DEBUG(dbgs() << "Replacement reg:" << PrintReg(FoundR, &HRI) << '\n');
2249 if (SpillOptCount >= SpillOptMax)
2255 // Generate the copy-in: "FoundR = COPY SrcR" at the store location.
2256 MachineBasicBlock::iterator StartIt = SI.getIterator(), NextIt;
2257 MachineInstr *CopyIn = nullptr;
2258 if (SrcRR.Reg != FoundR || SrcRR.Sub != 0) {
2259 const DebugLoc &DL = SI.getDebugLoc();
2260 CopyIn = BuildMI(B, StartIt, DL, HII.get(TargetOpcode::COPY), FoundR)
2265 // Check if this is a last store and the FI is live-on-exit.
2266 if (LoxFIs.count(FI) && (&Range == &RL.back())) {
2267 // Update store's source register.
2268 if (unsigned SR = SrcOp.getSubReg())
2269 SrcOp.setReg(HRI.getSubReg(FoundR, SR));
2271 SrcOp.setReg(FoundR);
2273 // We are keeping this register live.
2274 SrcOp.setIsKill(false);
2277 IM.replaceInstr(&SI, CopyIn);
2280 auto EndIt = std::next(EI.getIterator());
2281 for (auto It = StartIt; It != EndIt; It = NextIt) {
2282 MachineInstr &MI = *It;
2283 NextIt = std::next(It);
2285 if (!HII.isLoadFromStackSlot(MI, TFI) || TFI != FI)
2287 unsigned DstR = MI.getOperand(0).getReg();
2288 assert(MI.getOperand(0).getSubReg() == 0);
2289 MachineInstr *CopyOut = nullptr;
2290 if (DstR != FoundR) {
2291 DebugLoc DL = MI.getDebugLoc();
2292 unsigned MemSize = (1U << (HII.getMemAccessSize(MI) - 1));
2293 assert(HII.getAddrMode(MI) == HexagonII::BaseImmOffset);
2294 unsigned CopyOpc = TargetOpcode::COPY;
2295 if (HII.isSignExtendingLoad(MI))
2296 CopyOpc = (MemSize == 1) ? Hexagon::A2_sxtb : Hexagon::A2_sxth;
2297 else if (HII.isZeroExtendingLoad(MI))
2298 CopyOpc = (MemSize == 1) ? Hexagon::A2_zxtb : Hexagon::A2_zxth;
2299 CopyOut = BuildMI(B, It, DL, HII.get(CopyOpc), DstR)
2300 .addReg(FoundR, getKillRegState(&MI == &EI));
2302 IM.replaceInstr(&MI, CopyOut);
2306 // Update the dead map.
2307 HexagonBlockRanges::RegisterRef FoundRR = { FoundR, 0 };
2308 for (auto RR : HexagonBlockRanges::expandToSubRegs(FoundRR, MRI, HRI))
2309 DM[RR].subtract(Range);
2310 } // for Range in range list
2315 void HexagonFrameLowering::expandAlloca(MachineInstr *AI,
2316 const HexagonInstrInfo &HII, unsigned SP, unsigned CF) const {
2317 MachineBasicBlock &MB = *AI->getParent();
2318 DebugLoc DL = AI->getDebugLoc();
2319 unsigned A = AI->getOperand(2).getImm();
2322 // Rd = alloca Rs, #A
2324 // If Rs and Rd are different registers, use this sequence:
2325 // Rd = sub(r29, Rs)
2326 // r29 = sub(r29, Rs)
2327 // Rd = and(Rd, #-A) ; if necessary
2328 // r29 = and(r29, #-A) ; if necessary
2329 // Rd = add(Rd, #CF) ; CF size aligned to at most A
2331 // Rd = sub(r29, Rs)
2332 // Rd = and(Rd, #-A) ; if necessary
2334 // Rd = add(Rd, #CF) ; CF size aligned to at most A
2336 MachineOperand &RdOp = AI->getOperand(0);
2337 MachineOperand &RsOp = AI->getOperand(1);
2338 unsigned Rd = RdOp.getReg(), Rs = RsOp.getReg();
2340 // Rd = sub(r29, Rs)
2341 BuildMI(MB, AI, DL, HII.get(Hexagon::A2_sub), Rd)
2345 // r29 = sub(r29, Rs)
2346 BuildMI(MB, AI, DL, HII.get(Hexagon::A2_sub), SP)
2351 // Rd = and(Rd, #-A)
2352 BuildMI(MB, AI, DL, HII.get(Hexagon::A2_andir), Rd)
2354 .addImm(-int64_t(A));
2356 BuildMI(MB, AI, DL, HII.get(Hexagon::A2_andir), SP)
2358 .addImm(-int64_t(A));
2362 BuildMI(MB, AI, DL, HII.get(TargetOpcode::COPY), SP)
2366 // Rd = add(Rd, #CF)
2367 BuildMI(MB, AI, DL, HII.get(Hexagon::A2_addi), Rd)
2373 bool HexagonFrameLowering::needsAligna(const MachineFunction &MF) const {
2374 const MachineFrameInfo &MFI = MF.getFrameInfo();
2375 if (!MFI.hasVarSizedObjects())
2377 unsigned MaxA = MFI.getMaxAlignment();
2378 if (MaxA <= getStackAlignment())
2383 const MachineInstr *HexagonFrameLowering::getAlignaInstr(
2384 const MachineFunction &MF) const {
2387 if (I.getOpcode() == Hexagon::PS_aligna)
2392 /// Adds all callee-saved registers as implicit uses or defs to the
2394 void HexagonFrameLowering::addCalleeSaveRegistersAsImpOperand(MachineInstr *MI,
2395 const CSIVect &CSI, bool IsDef, bool IsKill) const {
2396 // Add the callee-saved registers as implicit uses.
2398 MI->addOperand(MachineOperand::CreateReg(R.getReg(), IsDef, true, IsKill));
2401 /// Determine whether the callee-saved register saves and restores should
2402 /// be generated via inline code. If this function returns "true", inline
2403 /// code will be generated. If this function returns "false", additional
2404 /// checks are performed, which may still lead to the inline code.
2405 bool HexagonFrameLowering::shouldInlineCSR(MachineFunction &MF,
2406 const CSIVect &CSI) const {
2407 if (MF.getInfo<HexagonMachineFunctionInfo>()->hasEHReturn())
2409 if (!isOptSize(MF) && !isMinSize(MF))
2410 if (MF.getTarget().getOptLevel() > CodeGenOpt::Default)
2413 // Check if CSI only has double registers, and if the registers form
2414 // a contiguous block starting from D8.
2415 BitVector Regs(Hexagon::NUM_TARGET_REGS);
2416 for (unsigned i = 0, n = CSI.size(); i < n; ++i) {
2417 unsigned R = CSI[i].getReg();
2418 if (!Hexagon::DoubleRegsRegClass.contains(R))
2422 int F = Regs.find_first();
2423 if (F != Hexagon::D8)
2426 int N = Regs.find_next(F);
2427 if (N >= 0 && N != F+1)
2435 bool HexagonFrameLowering::useSpillFunction(MachineFunction &MF,
2436 const CSIVect &CSI) const {
2437 if (shouldInlineCSR(MF, CSI))
2439 unsigned NumCSI = CSI.size();
2443 unsigned Threshold = isOptSize(MF) ? SpillFuncThresholdOs
2444 : SpillFuncThreshold;
2445 return Threshold < NumCSI;
2448 bool HexagonFrameLowering::useRestoreFunction(MachineFunction &MF,
2449 const CSIVect &CSI) const {
2450 if (shouldInlineCSR(MF, CSI))
2452 // The restore functions do a bit more than just restoring registers.
2453 // The non-returning versions will go back directly to the caller's
2454 // caller, others will clean up the stack frame in preparation for
2455 // a tail call. Using them can still save code size even if only one
2456 // register is getting restores. Make the decision based on -Oz:
2457 // using -Os will use inline restore for a single register.
2460 unsigned NumCSI = CSI.size();
2464 unsigned Threshold = isOptSize(MF) ? SpillFuncThresholdOs-1
2465 : SpillFuncThreshold;
2466 return Threshold < NumCSI;
2469 bool HexagonFrameLowering::mayOverflowFrameOffset(MachineFunction &MF) const {
2470 unsigned StackSize = MF.getFrameInfo().estimateStackSize(MF);
2471 auto &HST = MF.getSubtarget<HexagonSubtarget>();
2472 // A fairly simplistic guess as to whether a potential load/store to a
2473 // stack location could require an extra register.
2474 if (HST.useHVXOps() && StackSize > 256)
2477 // Check if the function has store-immediate instructions that access
2478 // the stack. Since the offset field is not extendable, if the stack
2479 // size exceeds the offset limit (6 bits, shifted), the stores will
2480 // require a new base register.
2481 bool HasImmStack = false;
2482 unsigned MinLS = ~0u; // Log_2 of the memory access size.
2484 for (const MachineBasicBlock &B : MF) {
2485 for (const MachineInstr &MI : B) {
2487 switch (MI.getOpcode()) {
2488 case Hexagon::S4_storeirit_io:
2489 case Hexagon::S4_storeirif_io:
2490 case Hexagon::S4_storeiri_io:
2493 case Hexagon::S4_storeirht_io:
2494 case Hexagon::S4_storeirhf_io:
2495 case Hexagon::S4_storeirh_io:
2498 case Hexagon::S4_storeirbt_io:
2499 case Hexagon::S4_storeirbf_io:
2500 case Hexagon::S4_storeirb_io:
2501 if (MI.getOperand(0).isFI())
2503 MinLS = std::min(MinLS, LS);
2510 return !isUInt<6>(StackSize >> MinLS);