1 //===- HexagonFrameLowering.cpp - Define frame lowering -------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "HexagonFrameLowering.h"
11 #include "HexagonBlockRanges.h"
12 #include "HexagonInstrInfo.h"
13 #include "HexagonMachineFunctionInfo.h"
14 #include "HexagonRegisterInfo.h"
15 #include "HexagonSubtarget.h"
16 #include "HexagonTargetMachine.h"
17 #include "MCTargetDesc/HexagonBaseInfo.h"
18 #include "llvm/ADT/BitVector.h"
19 #include "llvm/ADT/DenseMap.h"
20 #include "llvm/ADT/None.h"
21 #include "llvm/ADT/Optional.h"
22 #include "llvm/ADT/PostOrderIterator.h"
23 #include "llvm/ADT/SetVector.h"
24 #include "llvm/ADT/SmallSet.h"
25 #include "llvm/ADT/SmallVector.h"
26 #include "llvm/CodeGen/LivePhysRegs.h"
27 #include "llvm/CodeGen/MachineBasicBlock.h"
28 #include "llvm/CodeGen/MachineDominators.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineFunction.h"
31 #include "llvm/CodeGen/MachineFunctionPass.h"
32 #include "llvm/CodeGen/MachineInstr.h"
33 #include "llvm/CodeGen/MachineInstrBuilder.h"
34 #include "llvm/CodeGen/MachineMemOperand.h"
35 #include "llvm/CodeGen/MachineModuleInfo.h"
36 #include "llvm/CodeGen/MachineOperand.h"
37 #include "llvm/CodeGen/MachinePostDominators.h"
38 #include "llvm/CodeGen/MachineRegisterInfo.h"
39 #include "llvm/CodeGen/PseudoSourceValue.h"
40 #include "llvm/CodeGen/RegisterScavenging.h"
41 #include "llvm/CodeGen/TargetRegisterInfo.h"
42 #include "llvm/IR/Attributes.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/Compiler.h"
51 #include "llvm/Support/Debug.h"
52 #include "llvm/Support/ErrorHandling.h"
53 #include "llvm/Support/MathExtras.h"
54 #include "llvm/Support/raw_ostream.h"
55 #include "llvm/Target/TargetMachine.h"
56 #include "llvm/Target/TargetOptions.h"
57 #include <algorithm>
58 #include <cassert>
59 #include <cstdint>
60 #include <iterator>
61 #include <limits>
62 #include <map>
63 #include <utility>
64 #include <vector>
65 
66 #define DEBUG_TYPE "hexagon-pei"
67 
68 // Hexagon stack frame layout as defined by the ABI:
69 //
70 //                                                       Incoming arguments
71 //                                                       passed via stack
72 //                                                                      |
73 //                                                                      |
74 //        SP during function's                 FP during function's     |
75 //    +-- runtime (top of stack)               runtime (bottom) --+     |
76 //    |                                                           |     |
77 // --++---------------------+------------------+-----------------++-+-------
78 //   |  parameter area for  |  variable-size   |   fixed-size    |LR|  arg
79 //   |   called functions   |  local objects   |  local objects  |FP|
80 // --+----------------------+------------------+-----------------+--+-------
81 //    <-    size known    -> <- size unknown -> <- size known  ->
82 //
83 // Low address                                                 High address
84 //
85 // <--- stack growth
86 //
87 //
88 // - In any circumstances, the outgoing function arguments are always accessi-
89 //   ble using the SP, and the incoming arguments are accessible using the FP.
90 // - If the local objects are not aligned, they can always be accessed using
91 //   the FP.
92 // - If there are no variable-sized objects, the local objects can always be
93 //   accessed using the SP, regardless whether they are aligned or not. (The
94 //   alignment padding will be at the bottom of the stack (highest address),
95 //   and so the offset with respect to the SP will be known at the compile-
96 //   -time.)
97 //
98 // The only complication occurs if there are both, local aligned objects, and
99 // dynamically allocated (variable-sized) objects. The alignment pad will be
100 // placed between the FP and the local objects, thus preventing the use of the
101 // FP to access the local objects. At the same time, the variable-sized objects
102 // will be between the SP and the local objects, thus introducing an unknown
103 // distance from the SP to the locals.
104 //
105 // To avoid this problem, a new register is created that holds the aligned
106 // address of the bottom of the stack, referred in the sources as AP (aligned
107 // pointer). The AP will be equal to "FP-p", where "p" is the smallest pad
108 // that aligns AP to the required boundary (a maximum of the alignments of
109 // all stack objects, fixed- and variable-sized). All local objects[1] will
110 // then use AP as the base pointer.
111 // [1] The exception is with "fixed" stack objects. "Fixed" stack objects get
112 // their name from being allocated at fixed locations on the stack, relative
113 // to the FP. In the presence of dynamic allocation and local alignment, such
114 // objects can only be accessed through the FP.
115 //
116 // Illustration of the AP:
117 //                                                                FP --+
118 //                                                                     |
119 // ---------------+---------------------+-----+-----------------------++-+--
120 //   Rest of the  | Local stack objects | Pad |  Fixed stack objects  |LR|
121 //   stack frame  | (aligned)           |     |  (CSR, spills, etc.)  |FP|
122 // ---------------+---------------------+-----+-----------------+-----+--+--
123 //                                      |<-- Multiple of the -->|
124 //                                           stack alignment    +-- AP
125 //
126 // The AP is set up at the beginning of the function. Since it is not a dedi-
127 // cated (reserved) register, it needs to be kept live throughout the function
128 // to be available as the base register for local object accesses.
129 // Normally, an address of a stack objects is obtained by a pseudo-instruction
130 // PS_fi. To access local objects with the AP register present, a different
131 // pseudo-instruction needs to be used: PS_fia. The PS_fia takes one extra
132 // argument compared to PS_fi: the first input register is the AP register.
133 // This keeps the register live between its definition and its uses.
134 
135 // The AP register is originally set up using pseudo-instruction PS_aligna:
136 //   AP = PS_aligna A
137 // where
138 //   A  - required stack alignment
139 // The alignment value must be the maximum of all alignments required by
140 // any stack object.
141 
142 // The dynamic allocation uses a pseudo-instruction PS_alloca:
143 //   Rd = PS_alloca Rs, A
144 // where
145 //   Rd - address of the allocated space
146 //   Rs - minimum size (the actual allocated can be larger to accommodate
147 //        alignment)
148 //   A  - required alignment
149 
150 using namespace llvm;
151 
152 static cl::opt<bool> DisableDeallocRet("disable-hexagon-dealloc-ret",
153     cl::Hidden, cl::desc("Disable Dealloc Return for Hexagon target"));
154 
155 static cl::opt<unsigned> NumberScavengerSlots("number-scavenger-slots",
156     cl::Hidden, cl::desc("Set the number of scavenger slots"), cl::init(2),
157     cl::ZeroOrMore);
158 
159 static cl::opt<int>
160     SpillFuncThreshold("spill-func-threshold", cl::Hidden,
161                        cl::desc("Specify O2(not Os) spill func threshold"),
162                        cl::init(6));
163 
164 static cl::opt<int>
165     SpillFuncThresholdOs("spill-func-threshold-Os", cl::Hidden,
166                          cl::desc("Specify Os spill func threshold"),
167                          cl::init(1));
168 
169 static cl::opt<bool> EnableStackOVFSanitizer(
170     "enable-stackovf-sanitizer", cl::Hidden,
171     cl::desc("Enable runtime checks for stack overflow."), cl::init(false));
172 
173 static cl::opt<bool>
174     EnableShrinkWrapping("hexagon-shrink-frame", cl::init(true), cl::Hidden,
175                          cl::desc("Enable stack frame shrink wrapping"));
176 
177 static cl::opt<unsigned>
178     ShrinkLimit("shrink-frame-limit",
179                 cl::init(std::numeric_limits<unsigned>::max()), cl::Hidden,
180                 cl::desc("Max count of stack frame shrink-wraps"));
181 
182 static cl::opt<bool>
183     EnableSaveRestoreLong("enable-save-restore-long", cl::Hidden,
184                           cl::desc("Enable long calls for save-restore stubs."),
185                           cl::init(false));
186 
187 static cl::opt<bool> EliminateFramePointer("hexagon-fp-elim", cl::init(true),
188     cl::Hidden, cl::desc("Refrain from using FP whenever possible"));
189 
190 static cl::opt<bool> OptimizeSpillSlots("hexagon-opt-spill", cl::Hidden,
191     cl::init(true), cl::desc("Optimize spill slots"));
192 
193 #ifndef NDEBUG
194 static cl::opt<unsigned> SpillOptMax("spill-opt-max", cl::Hidden,
195     cl::init(std::numeric_limits<unsigned>::max()));
196 static unsigned SpillOptCount = 0;
197 #endif
198 
199 namespace llvm {
200 
201   void initializeHexagonCallFrameInformationPass(PassRegistry&);
202   FunctionPass *createHexagonCallFrameInformation();
203 
204 } // end namespace llvm
205 
206 namespace {
207 
208   class HexagonCallFrameInformation : public MachineFunctionPass {
209   public:
210     static char ID;
211 
212     HexagonCallFrameInformation() : MachineFunctionPass(ID) {
213       PassRegistry &PR = *PassRegistry::getPassRegistry();
214       initializeHexagonCallFrameInformationPass(PR);
215     }
216 
217     bool runOnMachineFunction(MachineFunction &MF) override;
218 
219     MachineFunctionProperties getRequiredProperties() const override {
220       return MachineFunctionProperties().set(
221           MachineFunctionProperties::Property::NoVRegs);
222     }
223   };
224 
225   char HexagonCallFrameInformation::ID = 0;
226 
227 } // end anonymous namespace
228 
229 bool HexagonCallFrameInformation::runOnMachineFunction(MachineFunction &MF) {
230   auto &HFI = *MF.getSubtarget<HexagonSubtarget>().getFrameLowering();
231   bool NeedCFI = MF.needsFrameMoves();
232 
233   if (!NeedCFI)
234     return false;
235   HFI.insertCFIInstructions(MF);
236   return true;
237 }
238 
239 INITIALIZE_PASS(HexagonCallFrameInformation, "hexagon-cfi",
240                 "Hexagon call frame information", false, false)
241 
242 FunctionPass *llvm::createHexagonCallFrameInformation() {
243   return new HexagonCallFrameInformation();
244 }
245 
246 /// Map a register pair Reg to the subregister that has the greater "number",
247 /// i.e. D3 (aka R7:6) will be mapped to R7, etc.
248 static unsigned getMax32BitSubRegister(unsigned Reg,
249                                        const TargetRegisterInfo &TRI,
250                                        bool hireg = true) {
251     if (Reg < Hexagon::D0 || Reg > Hexagon::D15)
252       return Reg;
253 
254     unsigned RegNo = 0;
255     for (MCSubRegIterator SubRegs(Reg, &TRI); SubRegs.isValid(); ++SubRegs) {
256       if (hireg) {
257         if (*SubRegs > RegNo)
258           RegNo = *SubRegs;
259       } else {
260         if (!RegNo || *SubRegs < RegNo)
261           RegNo = *SubRegs;
262       }
263     }
264     return RegNo;
265 }
266 
267 /// Returns the callee saved register with the largest id in the vector.
268 static unsigned getMaxCalleeSavedReg(ArrayRef<CalleeSavedInfo> CSI,
269                                      const TargetRegisterInfo &TRI) {
270   static_assert(Hexagon::R1 > 0,
271                 "Assume physical registers are encoded as positive integers");
272   if (CSI.empty())
273     return 0;
274 
275   unsigned Max = getMax32BitSubRegister(CSI[0].getReg(), TRI);
276   for (unsigned I = 1, E = CSI.size(); I < E; ++I) {
277     unsigned Reg = getMax32BitSubRegister(CSI[I].getReg(), TRI);
278     if (Reg > Max)
279       Max = Reg;
280   }
281   return Max;
282 }
283 
284 /// Checks if the basic block contains any instruction that needs a stack
285 /// frame to be already in place.
286 static bool needsStackFrame(const MachineBasicBlock &MBB, const BitVector &CSR,
287                             const HexagonRegisterInfo &HRI) {
288     for (const MachineInstr &MI : MBB) {
289       if (MI.isCall())
290         return true;
291       unsigned Opc = MI.getOpcode();
292       switch (Opc) {
293         case Hexagon::PS_alloca:
294         case Hexagon::PS_aligna:
295           return true;
296         default:
297           break;
298       }
299       // Check individual operands.
300       for (const MachineOperand &MO : MI.operands()) {
301         // While the presence of a frame index does not prove that a stack
302         // frame will be required, all frame indexes should be within alloc-
303         // frame/deallocframe. Otherwise, the code that translates a frame
304         // index into an offset would have to be aware of the placement of
305         // the frame creation/destruction instructions.
306         if (MO.isFI())
307           return true;
308         if (MO.isReg()) {
309           Register R = MO.getReg();
310           // Virtual registers will need scavenging, which then may require
311           // a stack slot.
312           if (R.isVirtual())
313             return true;
314           for (MCSubRegIterator S(R, &HRI, true); S.isValid(); ++S)
315             if (CSR[*S])
316               return true;
317           continue;
318         }
319         if (MO.isRegMask()) {
320           // A regmask would normally have all callee-saved registers marked
321           // as preserved, so this check would not be needed, but in case of
322           // ever having other regmasks (for other calling conventions),
323           // make sure they would be processed correctly.
324           const uint32_t *BM = MO.getRegMask();
325           for (int x = CSR.find_first(); x >= 0; x = CSR.find_next(x)) {
326             unsigned R = x;
327             // If this regmask does not preserve a CSR, a frame will be needed.
328             if (!(BM[R/32] & (1u << (R%32))))
329               return true;
330           }
331         }
332       }
333     }
334     return false;
335 }
336 
337   /// Returns true if MBB has a machine instructions that indicates a tail call
338   /// in the block.
339 static bool hasTailCall(const MachineBasicBlock &MBB) {
340     MachineBasicBlock::const_iterator I = MBB.getLastNonDebugInstr();
341     if (I == MBB.end())
342       return false;
343     unsigned RetOpc = I->getOpcode();
344     return RetOpc == Hexagon::PS_tailcall_i || RetOpc == Hexagon::PS_tailcall_r;
345 }
346 
347 /// Returns true if MBB contains an instruction that returns.
348 static bool hasReturn(const MachineBasicBlock &MBB) {
349     for (const MachineInstr &MI : MBB.terminators())
350       if (MI.isReturn())
351         return true;
352     return false;
353 }
354 
355 /// Returns the "return" instruction from this block, or nullptr if there
356 /// isn't any.
357 static MachineInstr *getReturn(MachineBasicBlock &MBB) {
358     for (auto &I : MBB)
359       if (I.isReturn())
360         return &I;
361     return nullptr;
362 }
363 
364 static bool isRestoreCall(unsigned Opc) {
365     switch (Opc) {
366       case Hexagon::RESTORE_DEALLOC_RET_JMP_V4:
367       case Hexagon::RESTORE_DEALLOC_RET_JMP_V4_PIC:
368       case Hexagon::RESTORE_DEALLOC_RET_JMP_V4_EXT:
369       case Hexagon::RESTORE_DEALLOC_RET_JMP_V4_EXT_PIC:
370       case Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_EXT:
371       case Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_EXT_PIC:
372       case Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4:
373       case Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_PIC:
374         return true;
375     }
376     return false;
377 }
378 
379 static inline bool isOptNone(const MachineFunction &MF) {
380     return MF.getFunction().hasOptNone() ||
381            MF.getTarget().getOptLevel() == CodeGenOpt::None;
382 }
383 
384 static inline bool isOptSize(const MachineFunction &MF) {
385     const Function &F = MF.getFunction();
386     return F.hasOptSize() && !F.hasMinSize();
387 }
388 
389 static inline bool isMinSize(const MachineFunction &MF) {
390     return MF.getFunction().hasMinSize();
391 }
392 
393 /// Implements shrink-wrapping of the stack frame. By default, stack frame
394 /// is created in the function entry block, and is cleaned up in every block
395 /// that returns. This function finds alternate blocks: one for the frame
396 /// setup (prolog) and one for the cleanup (epilog).
397 void HexagonFrameLowering::findShrunkPrologEpilog(MachineFunction &MF,
398       MachineBasicBlock *&PrologB, MachineBasicBlock *&EpilogB) const {
399   static unsigned ShrinkCounter = 0;
400 
401   if (MF.getSubtarget<HexagonSubtarget>().isEnvironmentMusl() &&
402       MF.getFunction().isVarArg())
403     return;
404   if (ShrinkLimit.getPosition()) {
405     if (ShrinkCounter >= ShrinkLimit)
406       return;
407     ShrinkCounter++;
408   }
409 
410   auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
411 
412   MachineDominatorTree MDT;
413   MDT.runOnMachineFunction(MF);
414   MachinePostDominatorTree MPT;
415   MPT.runOnMachineFunction(MF);
416 
417   using UnsignedMap = DenseMap<unsigned, unsigned>;
418   using RPOTType = ReversePostOrderTraversal<const MachineFunction *>;
419 
420   UnsignedMap RPO;
421   RPOTType RPOT(&MF);
422   unsigned RPON = 0;
423   for (auto &I : RPOT)
424     RPO[I->getNumber()] = RPON++;
425 
426   // Don't process functions that have loops, at least for now. Placement
427   // of prolog and epilog must take loop structure into account. For simpli-
428   // city don't do it right now.
429   for (auto &I : MF) {
430     unsigned BN = RPO[I.getNumber()];
431     for (MachineBasicBlock *Succ : I.successors())
432       // If found a back-edge, return.
433       if (RPO[Succ->getNumber()] <= BN)
434         return;
435   }
436 
437   // Collect the set of blocks that need a stack frame to execute. Scan
438   // each block for uses/defs of callee-saved registers, calls, etc.
439   SmallVector<MachineBasicBlock*,16> SFBlocks;
440   BitVector CSR(Hexagon::NUM_TARGET_REGS);
441   for (const MCPhysReg *P = HRI.getCalleeSavedRegs(&MF); *P; ++P)
442     for (MCSubRegIterator S(*P, &HRI, true); S.isValid(); ++S)
443       CSR[*S] = true;
444 
445   for (auto &I : MF)
446     if (needsStackFrame(I, CSR, HRI))
447       SFBlocks.push_back(&I);
448 
449   LLVM_DEBUG({
450     dbgs() << "Blocks needing SF: {";
451     for (auto &B : SFBlocks)
452       dbgs() << " " << printMBBReference(*B);
453     dbgs() << " }\n";
454   });
455   // No frame needed?
456   if (SFBlocks.empty())
457     return;
458 
459   // Pick a common dominator and a common post-dominator.
460   MachineBasicBlock *DomB = SFBlocks[0];
461   for (unsigned i = 1, n = SFBlocks.size(); i < n; ++i) {
462     DomB = MDT.findNearestCommonDominator(DomB, SFBlocks[i]);
463     if (!DomB)
464       break;
465   }
466   MachineBasicBlock *PDomB = SFBlocks[0];
467   for (unsigned i = 1, n = SFBlocks.size(); i < n; ++i) {
468     PDomB = MPT.findNearestCommonDominator(PDomB, SFBlocks[i]);
469     if (!PDomB)
470       break;
471   }
472   LLVM_DEBUG({
473     dbgs() << "Computed dom block: ";
474     if (DomB)
475       dbgs() << printMBBReference(*DomB);
476     else
477       dbgs() << "<null>";
478     dbgs() << ", computed pdom block: ";
479     if (PDomB)
480       dbgs() << printMBBReference(*PDomB);
481     else
482       dbgs() << "<null>";
483     dbgs() << "\n";
484   });
485   if (!DomB || !PDomB)
486     return;
487 
488   // Make sure that DomB dominates PDomB and PDomB post-dominates DomB.
489   if (!MDT.dominates(DomB, PDomB)) {
490     LLVM_DEBUG(dbgs() << "Dom block does not dominate pdom block\n");
491     return;
492   }
493   if (!MPT.dominates(PDomB, DomB)) {
494     LLVM_DEBUG(dbgs() << "PDom block does not post-dominate dom block\n");
495     return;
496   }
497 
498   // Finally, everything seems right.
499   PrologB = DomB;
500   EpilogB = PDomB;
501 }
502 
503 /// Perform most of the PEI work here:
504 /// - saving/restoring of the callee-saved registers,
505 /// - stack frame creation and destruction.
506 /// Normally, this work is distributed among various functions, but doing it
507 /// in one place allows shrink-wrapping of the stack frame.
508 void HexagonFrameLowering::emitPrologue(MachineFunction &MF,
509                                         MachineBasicBlock &MBB) const {
510   auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
511 
512   MachineFrameInfo &MFI = MF.getFrameInfo();
513   const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
514 
515   MachineBasicBlock *PrologB = &MF.front(), *EpilogB = nullptr;
516   if (EnableShrinkWrapping)
517     findShrunkPrologEpilog(MF, PrologB, EpilogB);
518 
519   bool PrologueStubs = false;
520   insertCSRSpillsInBlock(*PrologB, CSI, HRI, PrologueStubs);
521   insertPrologueInBlock(*PrologB, PrologueStubs);
522   updateEntryPaths(MF, *PrologB);
523 
524   if (EpilogB) {
525     insertCSRRestoresInBlock(*EpilogB, CSI, HRI);
526     insertEpilogueInBlock(*EpilogB);
527   } else {
528     for (auto &B : MF)
529       if (B.isReturnBlock())
530         insertCSRRestoresInBlock(B, CSI, HRI);
531 
532     for (auto &B : MF)
533       if (B.isReturnBlock())
534         insertEpilogueInBlock(B);
535 
536     for (auto &B : MF) {
537       if (B.empty())
538         continue;
539       MachineInstr *RetI = getReturn(B);
540       if (!RetI || isRestoreCall(RetI->getOpcode()))
541         continue;
542       for (auto &R : CSI)
543         RetI->addOperand(MachineOperand::CreateReg(R.getReg(), false, true));
544     }
545   }
546 
547   if (EpilogB) {
548     // If there is an epilog block, it may not have a return instruction.
549     // In such case, we need to add the callee-saved registers as live-ins
550     // in all blocks on all paths from the epilog to any return block.
551     unsigned MaxBN = MF.getNumBlockIDs();
552     BitVector DoneT(MaxBN+1), DoneF(MaxBN+1), Path(MaxBN+1);
553     updateExitPaths(*EpilogB, *EpilogB, DoneT, DoneF, Path);
554   }
555 }
556 
557 /// Returns true if the target can safely skip saving callee-saved registers
558 /// for noreturn nounwind functions.
559 bool HexagonFrameLowering::enableCalleeSaveSkip(
560     const MachineFunction &MF) const {
561   const auto &F = MF.getFunction();
562   assert(F.hasFnAttribute(Attribute::NoReturn) &&
563          F.getFunction().hasFnAttribute(Attribute::NoUnwind) &&
564          !F.getFunction().hasFnAttribute(Attribute::UWTable));
565   (void)F;
566 
567   // No need to save callee saved registers if the function does not return.
568   return MF.getSubtarget<HexagonSubtarget>().noreturnStackElim();
569 }
570 
571 // Helper function used to determine when to eliminate the stack frame for
572 // functions marked as noreturn and when the noreturn-stack-elim options are
573 // specified. When both these conditions are true, then a FP may not be needed
574 // if the function makes a call. It is very similar to enableCalleeSaveSkip,
575 // but it used to check if the allocframe can be eliminated as well.
576 static bool enableAllocFrameElim(const MachineFunction &MF) {
577   const auto &F = MF.getFunction();
578   const auto &MFI = MF.getFrameInfo();
579   const auto &HST = MF.getSubtarget<HexagonSubtarget>();
580   assert(!MFI.hasVarSizedObjects() &&
581          !HST.getRegisterInfo()->hasStackRealignment(MF));
582   return F.hasFnAttribute(Attribute::NoReturn) &&
583     F.hasFnAttribute(Attribute::NoUnwind) &&
584     !F.hasFnAttribute(Attribute::UWTable) && HST.noreturnStackElim() &&
585     MFI.getStackSize() == 0;
586 }
587 
588 void HexagonFrameLowering::insertPrologueInBlock(MachineBasicBlock &MBB,
589       bool PrologueStubs) const {
590   MachineFunction &MF = *MBB.getParent();
591   MachineFrameInfo &MFI = MF.getFrameInfo();
592   auto &HST = MF.getSubtarget<HexagonSubtarget>();
593   auto &HII = *HST.getInstrInfo();
594   auto &HRI = *HST.getRegisterInfo();
595 
596   Align MaxAlign = std::max(MFI.getMaxAlign(), getStackAlign());
597 
598   // Calculate the total stack frame size.
599   // Get the number of bytes to allocate from the FrameInfo.
600   unsigned FrameSize = MFI.getStackSize();
601   // Round up the max call frame size to the max alignment on the stack.
602   unsigned MaxCFA = alignTo(MFI.getMaxCallFrameSize(), MaxAlign);
603   MFI.setMaxCallFrameSize(MaxCFA);
604 
605   FrameSize = MaxCFA + alignTo(FrameSize, MaxAlign);
606   MFI.setStackSize(FrameSize);
607 
608   bool AlignStack = (MaxAlign > getStackAlign());
609 
610   // Get the number of bytes to allocate from the FrameInfo.
611   unsigned NumBytes = MFI.getStackSize();
612   unsigned SP = HRI.getStackRegister();
613   unsigned MaxCF = MFI.getMaxCallFrameSize();
614   MachineBasicBlock::iterator InsertPt = MBB.begin();
615 
616   SmallVector<MachineInstr *, 4> AdjustRegs;
617   for (auto &MBB : MF)
618     for (auto &MI : MBB)
619       if (MI.getOpcode() == Hexagon::PS_alloca)
620         AdjustRegs.push_back(&MI);
621 
622   for (auto MI : AdjustRegs) {
623     assert((MI->getOpcode() == Hexagon::PS_alloca) && "Expected alloca");
624     expandAlloca(MI, HII, SP, MaxCF);
625     MI->eraseFromParent();
626   }
627 
628   DebugLoc dl = MBB.findDebugLoc(InsertPt);
629 
630   if (MF.getFunction().isVarArg() &&
631       MF.getSubtarget<HexagonSubtarget>().isEnvironmentMusl()) {
632     // Calculate the size of register saved area.
633     int NumVarArgRegs = 6 - FirstVarArgSavedReg;
634     int RegisterSavedAreaSizePlusPadding = (NumVarArgRegs % 2 == 0)
635                                               ? NumVarArgRegs * 4
636                                               : NumVarArgRegs * 4 + 4;
637     if (RegisterSavedAreaSizePlusPadding > 0) {
638       // Decrement the stack pointer by size of register saved area plus
639       // padding if any.
640       BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::A2_addi), SP)
641         .addReg(SP)
642         .addImm(-RegisterSavedAreaSizePlusPadding)
643         .setMIFlag(MachineInstr::FrameSetup);
644 
645       int NumBytes = 0;
646       // Copy all the named arguments below register saved area.
647       auto &HMFI = *MF.getInfo<HexagonMachineFunctionInfo>();
648       for (int i = HMFI.getFirstNamedArgFrameIndex(),
649                e = HMFI.getLastNamedArgFrameIndex(); i >= e; --i) {
650         uint64_t ObjSize = MFI.getObjectSize(i);
651         Align ObjAlign = MFI.getObjectAlign(i);
652 
653         // Determine the kind of load/store that should be used.
654         unsigned LDOpc, STOpc;
655         uint64_t OpcodeChecker = ObjAlign.value();
656 
657         // Handle cases where alignment of an object is > its size.
658         if (ObjAlign > ObjSize) {
659           if (ObjSize <= 1)
660             OpcodeChecker = 1;
661           else if (ObjSize <= 2)
662             OpcodeChecker = 2;
663           else if (ObjSize <= 4)
664             OpcodeChecker = 4;
665           else if (ObjSize > 4)
666             OpcodeChecker = 8;
667         }
668 
669         switch (OpcodeChecker) {
670           case 1:
671             LDOpc = Hexagon::L2_loadrb_io;
672             STOpc = Hexagon::S2_storerb_io;
673             break;
674           case 2:
675             LDOpc = Hexagon::L2_loadrh_io;
676             STOpc = Hexagon::S2_storerh_io;
677             break;
678           case 4:
679             LDOpc = Hexagon::L2_loadri_io;
680             STOpc = Hexagon::S2_storeri_io;
681             break;
682           case 8:
683           default:
684             LDOpc = Hexagon::L2_loadrd_io;
685             STOpc = Hexagon::S2_storerd_io;
686             break;
687         }
688 
689         unsigned RegUsed = LDOpc == Hexagon::L2_loadrd_io ? Hexagon::D3
690                                                           : Hexagon::R6;
691         int LoadStoreCount = ObjSize / OpcodeChecker;
692 
693         if (ObjSize % OpcodeChecker)
694           ++LoadStoreCount;
695 
696         // Get the start location of the load. NumBytes is basically the
697         // offset from the stack pointer of previous function, which would be
698         // the caller in this case, as this function has variable argument
699         // list.
700         if (NumBytes != 0)
701           NumBytes = alignTo(NumBytes, ObjAlign);
702 
703         int Count = 0;
704         while (Count < LoadStoreCount) {
705           // Load the value of the named argument on stack.
706           BuildMI(MBB, InsertPt, dl, HII.get(LDOpc), RegUsed)
707               .addReg(SP)
708               .addImm(RegisterSavedAreaSizePlusPadding +
709                       ObjAlign.value() * Count + NumBytes)
710               .setMIFlag(MachineInstr::FrameSetup);
711 
712           // Store it below the register saved area plus padding.
713           BuildMI(MBB, InsertPt, dl, HII.get(STOpc))
714               .addReg(SP)
715               .addImm(ObjAlign.value() * Count + NumBytes)
716               .addReg(RegUsed)
717               .setMIFlag(MachineInstr::FrameSetup);
718 
719           Count++;
720         }
721         NumBytes += MFI.getObjectSize(i);
722       }
723 
724       // Make NumBytes 8 byte aligned
725       NumBytes = alignTo(NumBytes, 8);
726 
727       // If the number of registers having variable arguments is odd,
728       // leave 4 bytes of padding to get to the location where first
729       // variable argument which was passed through register was copied.
730       NumBytes = (NumVarArgRegs % 2 == 0) ? NumBytes : NumBytes + 4;
731 
732       for (int j = FirstVarArgSavedReg, i = 0; j < 6; ++j, ++i) {
733         BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::S2_storeri_io))
734           .addReg(SP)
735           .addImm(NumBytes + 4 * i)
736           .addReg(Hexagon::R0 + j)
737           .setMIFlag(MachineInstr::FrameSetup);
738       }
739     }
740   }
741 
742   if (hasFP(MF)) {
743     insertAllocframe(MBB, InsertPt, NumBytes);
744     if (AlignStack) {
745       BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::A2_andir), SP)
746           .addReg(SP)
747           .addImm(-int64_t(MaxAlign.value()));
748     }
749     // If the stack-checking is enabled, and we spilled the callee-saved
750     // registers inline (i.e. did not use a spill function), then call
751     // the stack checker directly.
752     if (EnableStackOVFSanitizer && !PrologueStubs)
753       BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::PS_call_stk))
754              .addExternalSymbol("__runtime_stack_check");
755   } else if (NumBytes > 0) {
756     assert(alignTo(NumBytes, 8) == NumBytes);
757     BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::A2_addi), SP)
758       .addReg(SP)
759       .addImm(-int(NumBytes));
760   }
761 }
762 
763 void HexagonFrameLowering::insertEpilogueInBlock(MachineBasicBlock &MBB) const {
764   MachineFunction &MF = *MBB.getParent();
765   auto &HST = MF.getSubtarget<HexagonSubtarget>();
766   auto &HII = *HST.getInstrInfo();
767   auto &HRI = *HST.getRegisterInfo();
768   unsigned SP = HRI.getStackRegister();
769 
770   MachineBasicBlock::iterator InsertPt = MBB.getFirstTerminator();
771   DebugLoc dl = MBB.findDebugLoc(InsertPt);
772 
773   if (!hasFP(MF)) {
774     MachineFrameInfo &MFI = MF.getFrameInfo();
775     unsigned NumBytes = MFI.getStackSize();
776     if (MF.getFunction().isVarArg() &&
777         MF.getSubtarget<HexagonSubtarget>().isEnvironmentMusl()) {
778       // On Hexagon Linux, deallocate the stack for the register saved area.
779       int NumVarArgRegs = 6 - FirstVarArgSavedReg;
780       int RegisterSavedAreaSizePlusPadding = (NumVarArgRegs % 2 == 0) ?
781         (NumVarArgRegs * 4) : (NumVarArgRegs * 4 + 4);
782       NumBytes += RegisterSavedAreaSizePlusPadding;
783     }
784     if (NumBytes) {
785       BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::A2_addi), SP)
786         .addReg(SP)
787         .addImm(NumBytes);
788     }
789     return;
790   }
791 
792   MachineInstr *RetI = getReturn(MBB);
793   unsigned RetOpc = RetI ? RetI->getOpcode() : 0;
794 
795   // Handle EH_RETURN.
796   if (RetOpc == Hexagon::EH_RETURN_JMPR) {
797     BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::L2_deallocframe))
798         .addDef(Hexagon::D15)
799         .addReg(Hexagon::R30);
800     BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::A2_add), SP)
801         .addReg(SP)
802         .addReg(Hexagon::R28);
803     return;
804   }
805 
806   // Check for RESTORE_DEALLOC_RET* tail call. Don't emit an extra dealloc-
807   // frame instruction if we encounter it.
808   if (RetOpc == Hexagon::RESTORE_DEALLOC_RET_JMP_V4 ||
809       RetOpc == Hexagon::RESTORE_DEALLOC_RET_JMP_V4_PIC ||
810       RetOpc == Hexagon::RESTORE_DEALLOC_RET_JMP_V4_EXT ||
811       RetOpc == Hexagon::RESTORE_DEALLOC_RET_JMP_V4_EXT_PIC) {
812     MachineBasicBlock::iterator It = RetI;
813     ++It;
814     // Delete all instructions after the RESTORE (except labels).
815     while (It != MBB.end()) {
816       if (!It->isLabel())
817         It = MBB.erase(It);
818       else
819         ++It;
820     }
821     return;
822   }
823 
824   // It is possible that the restoring code is a call to a library function.
825   // All of the restore* functions include "deallocframe", so we need to make
826   // sure that we don't add an extra one.
827   bool NeedsDeallocframe = true;
828   if (!MBB.empty() && InsertPt != MBB.begin()) {
829     MachineBasicBlock::iterator PrevIt = std::prev(InsertPt);
830     unsigned COpc = PrevIt->getOpcode();
831     if (COpc == Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4 ||
832         COpc == Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_PIC ||
833         COpc == Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_EXT ||
834         COpc == Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_EXT_PIC ||
835         COpc == Hexagon::PS_call_nr || COpc == Hexagon::PS_callr_nr)
836       NeedsDeallocframe = false;
837   }
838 
839   if (!MF.getSubtarget<HexagonSubtarget>().isEnvironmentMusl() ||
840       !MF.getFunction().isVarArg()) {
841     if (!NeedsDeallocframe)
842       return;
843     // If the returning instruction is PS_jmpret, replace it with
844     // dealloc_return, otherwise just add deallocframe. The function
845     // could be returning via a tail call.
846     if (RetOpc != Hexagon::PS_jmpret || DisableDeallocRet) {
847       BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::L2_deallocframe))
848       .addDef(Hexagon::D15)
849       .addReg(Hexagon::R30);
850       return;
851     }
852     unsigned NewOpc = Hexagon::L4_return;
853     MachineInstr *NewI = BuildMI(MBB, RetI, dl, HII.get(NewOpc))
854       .addDef(Hexagon::D15)
855       .addReg(Hexagon::R30);
856     // Transfer the function live-out registers.
857     NewI->copyImplicitOps(MF, *RetI);
858     MBB.erase(RetI);
859   } else {
860     // L2_deallocframe instruction after it.
861     // Calculate the size of register saved area.
862     int NumVarArgRegs = 6 - FirstVarArgSavedReg;
863     int RegisterSavedAreaSizePlusPadding = (NumVarArgRegs % 2 == 0) ?
864       (NumVarArgRegs * 4) : (NumVarArgRegs * 4 + 4);
865 
866     MachineBasicBlock::iterator Term = MBB.getFirstTerminator();
867     MachineBasicBlock::iterator I = (Term == MBB.begin()) ? MBB.end()
868                                                           : std::prev(Term);
869     if (I == MBB.end() ||
870        (I->getOpcode() != Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_EXT &&
871         I->getOpcode() != Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_EXT_PIC &&
872         I->getOpcode() != Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4 &&
873         I->getOpcode() != Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_PIC))
874       BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::L2_deallocframe))
875         .addDef(Hexagon::D15)
876         .addReg(Hexagon::R30);
877     if (RegisterSavedAreaSizePlusPadding != 0)
878       BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::A2_addi), SP)
879         .addReg(SP)
880         .addImm(RegisterSavedAreaSizePlusPadding);
881   }
882 }
883 
884 void HexagonFrameLowering::insertAllocframe(MachineBasicBlock &MBB,
885       MachineBasicBlock::iterator InsertPt, unsigned NumBytes) const {
886   MachineFunction &MF = *MBB.getParent();
887   auto &HST = MF.getSubtarget<HexagonSubtarget>();
888   auto &HII = *HST.getInstrInfo();
889   auto &HRI = *HST.getRegisterInfo();
890 
891   // Check for overflow.
892   // Hexagon_TODO: Ugh! hardcoding. Is there an API that can be used?
893   const unsigned int ALLOCFRAME_MAX = 16384;
894 
895   // Create a dummy memory operand to avoid allocframe from being treated as
896   // a volatile memory reference.
897   auto *MMO = MF.getMachineMemOperand(MachinePointerInfo::getStack(MF, 0),
898                                       MachineMemOperand::MOStore, 4, Align(4));
899 
900   DebugLoc dl = MBB.findDebugLoc(InsertPt);
901   unsigned SP = HRI.getStackRegister();
902 
903   if (NumBytes >= ALLOCFRAME_MAX) {
904     // Emit allocframe(#0).
905     BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::S2_allocframe))
906       .addDef(SP)
907       .addReg(SP)
908       .addImm(0)
909       .addMemOperand(MMO);
910 
911     // Subtract the size from the stack pointer.
912     unsigned SP = HRI.getStackRegister();
913     BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::A2_addi), SP)
914       .addReg(SP)
915       .addImm(-int(NumBytes));
916   } else {
917     BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::S2_allocframe))
918       .addDef(SP)
919       .addReg(SP)
920       .addImm(NumBytes)
921       .addMemOperand(MMO);
922   }
923 }
924 
925 void HexagonFrameLowering::updateEntryPaths(MachineFunction &MF,
926       MachineBasicBlock &SaveB) const {
927   SetVector<unsigned> Worklist;
928 
929   MachineBasicBlock &EntryB = MF.front();
930   Worklist.insert(EntryB.getNumber());
931 
932   unsigned SaveN = SaveB.getNumber();
933   auto &CSI = MF.getFrameInfo().getCalleeSavedInfo();
934 
935   for (unsigned i = 0; i < Worklist.size(); ++i) {
936     unsigned BN = Worklist[i];
937     MachineBasicBlock &MBB = *MF.getBlockNumbered(BN);
938     for (auto &R : CSI)
939       if (!MBB.isLiveIn(R.getReg()))
940         MBB.addLiveIn(R.getReg());
941     if (BN != SaveN)
942       for (auto &SB : MBB.successors())
943         Worklist.insert(SB->getNumber());
944   }
945 }
946 
947 bool HexagonFrameLowering::updateExitPaths(MachineBasicBlock &MBB,
948       MachineBasicBlock &RestoreB, BitVector &DoneT, BitVector &DoneF,
949       BitVector &Path) const {
950   assert(MBB.getNumber() >= 0);
951   unsigned BN = MBB.getNumber();
952   if (Path[BN] || DoneF[BN])
953     return false;
954   if (DoneT[BN])
955     return true;
956 
957   auto &CSI = MBB.getParent()->getFrameInfo().getCalleeSavedInfo();
958 
959   Path[BN] = true;
960   bool ReachedExit = false;
961   for (auto &SB : MBB.successors())
962     ReachedExit |= updateExitPaths(*SB, RestoreB, DoneT, DoneF, Path);
963 
964   if (!MBB.empty() && MBB.back().isReturn()) {
965     // Add implicit uses of all callee-saved registers to the reached
966     // return instructions. This is to prevent the anti-dependency breaker
967     // from renaming these registers.
968     MachineInstr &RetI = MBB.back();
969     if (!isRestoreCall(RetI.getOpcode()))
970       for (auto &R : CSI)
971         RetI.addOperand(MachineOperand::CreateReg(R.getReg(), false, true));
972     ReachedExit = true;
973   }
974 
975   // We don't want to add unnecessary live-ins to the restore block: since
976   // the callee-saved registers are being defined in it, the entry of the
977   // restore block cannot be on the path from the definitions to any exit.
978   if (ReachedExit && &MBB != &RestoreB) {
979     for (auto &R : CSI)
980       if (!MBB.isLiveIn(R.getReg()))
981         MBB.addLiveIn(R.getReg());
982     DoneT[BN] = true;
983   }
984   if (!ReachedExit)
985     DoneF[BN] = true;
986 
987   Path[BN] = false;
988   return ReachedExit;
989 }
990 
991 static Optional<MachineBasicBlock::iterator>
992 findCFILocation(MachineBasicBlock &B) {
993     // The CFI instructions need to be inserted right after allocframe.
994     // An exception to this is a situation where allocframe is bundled
995     // with a call: then the CFI instructions need to be inserted before
996     // the packet with the allocframe+call (in case the call throws an
997     // exception).
998     auto End = B.instr_end();
999 
1000     for (MachineInstr &I : B) {
1001       MachineBasicBlock::iterator It = I.getIterator();
1002       if (!I.isBundle()) {
1003         if (I.getOpcode() == Hexagon::S2_allocframe)
1004           return std::next(It);
1005         continue;
1006       }
1007       // I is a bundle.
1008       bool HasCall = false, HasAllocFrame = false;
1009       auto T = It.getInstrIterator();
1010       while (++T != End && T->isBundled()) {
1011         if (T->getOpcode() == Hexagon::S2_allocframe)
1012           HasAllocFrame = true;
1013         else if (T->isCall())
1014           HasCall = true;
1015       }
1016       if (HasAllocFrame)
1017         return HasCall ? It : std::next(It);
1018     }
1019     return None;
1020 }
1021 
1022 void HexagonFrameLowering::insertCFIInstructions(MachineFunction &MF) const {
1023   for (auto &B : MF) {
1024     auto At = findCFILocation(B);
1025     if (At.hasValue())
1026       insertCFIInstructionsAt(B, At.getValue());
1027   }
1028 }
1029 
1030 void HexagonFrameLowering::insertCFIInstructionsAt(MachineBasicBlock &MBB,
1031       MachineBasicBlock::iterator At) const {
1032   MachineFunction &MF = *MBB.getParent();
1033   MachineFrameInfo &MFI = MF.getFrameInfo();
1034   MachineModuleInfo &MMI = MF.getMMI();
1035   auto &HST = MF.getSubtarget<HexagonSubtarget>();
1036   auto &HII = *HST.getInstrInfo();
1037   auto &HRI = *HST.getRegisterInfo();
1038 
1039   // If CFI instructions have debug information attached, something goes
1040   // wrong with the final assembly generation: the prolog_end is placed
1041   // in a wrong location.
1042   DebugLoc DL;
1043   const MCInstrDesc &CFID = HII.get(TargetOpcode::CFI_INSTRUCTION);
1044 
1045   MCSymbol *FrameLabel = MMI.getContext().createTempSymbol();
1046   bool HasFP = hasFP(MF);
1047 
1048   if (HasFP) {
1049     unsigned DwFPReg = HRI.getDwarfRegNum(HRI.getFrameRegister(), true);
1050     unsigned DwRAReg = HRI.getDwarfRegNum(HRI.getRARegister(), true);
1051 
1052     // Define CFA via an offset from the value of FP.
1053     //
1054     //  -8   -4    0 (SP)
1055     // --+----+----+---------------------
1056     //   | FP | LR |          increasing addresses -->
1057     // --+----+----+---------------------
1058     //   |         +-- Old SP (before allocframe)
1059     //   +-- New FP (after allocframe)
1060     //
1061     // MCCFIInstruction::cfiDefCfa adds the offset from the register.
1062     // MCCFIInstruction::createOffset takes the offset without sign change.
1063     auto DefCfa = MCCFIInstruction::cfiDefCfa(FrameLabel, DwFPReg, 8);
1064     BuildMI(MBB, At, DL, CFID)
1065         .addCFIIndex(MF.addFrameInst(DefCfa));
1066     // R31 (return addr) = CFA - 4
1067     auto OffR31 = MCCFIInstruction::createOffset(FrameLabel, DwRAReg, -4);
1068     BuildMI(MBB, At, DL, CFID)
1069         .addCFIIndex(MF.addFrameInst(OffR31));
1070     // R30 (frame ptr) = CFA - 8
1071     auto OffR30 = MCCFIInstruction::createOffset(FrameLabel, DwFPReg, -8);
1072     BuildMI(MBB, At, DL, CFID)
1073         .addCFIIndex(MF.addFrameInst(OffR30));
1074   }
1075 
1076   static unsigned int RegsToMove[] = {
1077     Hexagon::R1,  Hexagon::R0,  Hexagon::R3,  Hexagon::R2,
1078     Hexagon::R17, Hexagon::R16, Hexagon::R19, Hexagon::R18,
1079     Hexagon::R21, Hexagon::R20, Hexagon::R23, Hexagon::R22,
1080     Hexagon::R25, Hexagon::R24, Hexagon::R27, Hexagon::R26,
1081     Hexagon::D0,  Hexagon::D1,  Hexagon::D8,  Hexagon::D9,
1082     Hexagon::D10, Hexagon::D11, Hexagon::D12, Hexagon::D13,
1083     Hexagon::NoRegister
1084   };
1085 
1086   const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
1087 
1088   for (unsigned i = 0; RegsToMove[i] != Hexagon::NoRegister; ++i) {
1089     unsigned Reg = RegsToMove[i];
1090     auto IfR = [Reg] (const CalleeSavedInfo &C) -> bool {
1091       return C.getReg() == Reg;
1092     };
1093     auto F = find_if(CSI, IfR);
1094     if (F == CSI.end())
1095       continue;
1096 
1097     int64_t Offset;
1098     if (HasFP) {
1099       // If the function has a frame pointer (i.e. has an allocframe),
1100       // then the CFA has been defined in terms of FP. Any offsets in
1101       // the following CFI instructions have to be defined relative
1102       // to FP, which points to the bottom of the stack frame.
1103       // The function getFrameIndexReference can still choose to use SP
1104       // for the offset calculation, so we cannot simply call it here.
1105       // Instead, get the offset (relative to the FP) directly.
1106       Offset = MFI.getObjectOffset(F->getFrameIdx());
1107     } else {
1108       Register FrameReg;
1109       Offset =
1110           getFrameIndexReference(MF, F->getFrameIdx(), FrameReg).getFixed();
1111     }
1112     // Subtract 8 to make room for R30 and R31, which are added above.
1113     Offset -= 8;
1114 
1115     if (Reg < Hexagon::D0 || Reg > Hexagon::D15) {
1116       unsigned DwarfReg = HRI.getDwarfRegNum(Reg, true);
1117       auto OffReg = MCCFIInstruction::createOffset(FrameLabel, DwarfReg,
1118                                                    Offset);
1119       BuildMI(MBB, At, DL, CFID)
1120           .addCFIIndex(MF.addFrameInst(OffReg));
1121     } else {
1122       // Split the double regs into subregs, and generate appropriate
1123       // cfi_offsets.
1124       // The only reason, we are split double regs is, llvm-mc does not
1125       // understand paired registers for cfi_offset.
1126       // Eg .cfi_offset r1:0, -64
1127 
1128       Register HiReg = HRI.getSubReg(Reg, Hexagon::isub_hi);
1129       Register LoReg = HRI.getSubReg(Reg, Hexagon::isub_lo);
1130       unsigned HiDwarfReg = HRI.getDwarfRegNum(HiReg, true);
1131       unsigned LoDwarfReg = HRI.getDwarfRegNum(LoReg, true);
1132       auto OffHi = MCCFIInstruction::createOffset(FrameLabel, HiDwarfReg,
1133                                                   Offset+4);
1134       BuildMI(MBB, At, DL, CFID)
1135           .addCFIIndex(MF.addFrameInst(OffHi));
1136       auto OffLo = MCCFIInstruction::createOffset(FrameLabel, LoDwarfReg,
1137                                                   Offset);
1138       BuildMI(MBB, At, DL, CFID)
1139           .addCFIIndex(MF.addFrameInst(OffLo));
1140     }
1141   }
1142 }
1143 
1144 bool HexagonFrameLowering::hasFP(const MachineFunction &MF) const {
1145   if (MF.getFunction().hasFnAttribute(Attribute::Naked))
1146     return false;
1147 
1148   auto &MFI = MF.getFrameInfo();
1149   auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
1150   bool HasExtraAlign = HRI.hasStackRealignment(MF);
1151   bool HasAlloca = MFI.hasVarSizedObjects();
1152 
1153   // Insert ALLOCFRAME if we need to or at -O0 for the debugger.  Think
1154   // that this shouldn't be required, but doing so now because gcc does and
1155   // gdb can't break at the start of the function without it.  Will remove if
1156   // this turns out to be a gdb bug.
1157   //
1158   if (MF.getTarget().getOptLevel() == CodeGenOpt::None)
1159     return true;
1160 
1161   // By default we want to use SP (since it's always there). FP requires
1162   // some setup (i.e. ALLOCFRAME).
1163   // Both, alloca and stack alignment modify the stack pointer by an
1164   // undetermined value, so we need to save it at the entry to the function
1165   // (i.e. use allocframe).
1166   if (HasAlloca || HasExtraAlign)
1167     return true;
1168 
1169   if (MFI.getStackSize() > 0) {
1170     // If FP-elimination is disabled, we have to use FP at this point.
1171     const TargetMachine &TM = MF.getTarget();
1172     if (TM.Options.DisableFramePointerElim(MF) || !EliminateFramePointer)
1173       return true;
1174     if (EnableStackOVFSanitizer)
1175       return true;
1176   }
1177 
1178   const auto &HMFI = *MF.getInfo<HexagonMachineFunctionInfo>();
1179   if ((MFI.hasCalls() && !enableAllocFrameElim(MF)) || HMFI.hasClobberLR())
1180     return true;
1181 
1182   return false;
1183 }
1184 
1185 enum SpillKind {
1186   SK_ToMem,
1187   SK_FromMem,
1188   SK_FromMemTailcall
1189 };
1190 
1191 static const char *getSpillFunctionFor(unsigned MaxReg, SpillKind SpillType,
1192       bool Stkchk = false) {
1193   const char * V4SpillToMemoryFunctions[] = {
1194     "__save_r16_through_r17",
1195     "__save_r16_through_r19",
1196     "__save_r16_through_r21",
1197     "__save_r16_through_r23",
1198     "__save_r16_through_r25",
1199     "__save_r16_through_r27" };
1200 
1201   const char * V4SpillToMemoryStkchkFunctions[] = {
1202     "__save_r16_through_r17_stkchk",
1203     "__save_r16_through_r19_stkchk",
1204     "__save_r16_through_r21_stkchk",
1205     "__save_r16_through_r23_stkchk",
1206     "__save_r16_through_r25_stkchk",
1207     "__save_r16_through_r27_stkchk" };
1208 
1209   const char * V4SpillFromMemoryFunctions[] = {
1210     "__restore_r16_through_r17_and_deallocframe",
1211     "__restore_r16_through_r19_and_deallocframe",
1212     "__restore_r16_through_r21_and_deallocframe",
1213     "__restore_r16_through_r23_and_deallocframe",
1214     "__restore_r16_through_r25_and_deallocframe",
1215     "__restore_r16_through_r27_and_deallocframe" };
1216 
1217   const char * V4SpillFromMemoryTailcallFunctions[] = {
1218     "__restore_r16_through_r17_and_deallocframe_before_tailcall",
1219     "__restore_r16_through_r19_and_deallocframe_before_tailcall",
1220     "__restore_r16_through_r21_and_deallocframe_before_tailcall",
1221     "__restore_r16_through_r23_and_deallocframe_before_tailcall",
1222     "__restore_r16_through_r25_and_deallocframe_before_tailcall",
1223     "__restore_r16_through_r27_and_deallocframe_before_tailcall"
1224   };
1225 
1226   const char **SpillFunc = nullptr;
1227 
1228   switch(SpillType) {
1229   case SK_ToMem:
1230     SpillFunc = Stkchk ? V4SpillToMemoryStkchkFunctions
1231                        : V4SpillToMemoryFunctions;
1232     break;
1233   case SK_FromMem:
1234     SpillFunc = V4SpillFromMemoryFunctions;
1235     break;
1236   case SK_FromMemTailcall:
1237     SpillFunc = V4SpillFromMemoryTailcallFunctions;
1238     break;
1239   }
1240   assert(SpillFunc && "Unknown spill kind");
1241 
1242   // Spill all callee-saved registers up to the highest register used.
1243   switch (MaxReg) {
1244   case Hexagon::R17:
1245     return SpillFunc[0];
1246   case Hexagon::R19:
1247     return SpillFunc[1];
1248   case Hexagon::R21:
1249     return SpillFunc[2];
1250   case Hexagon::R23:
1251     return SpillFunc[3];
1252   case Hexagon::R25:
1253     return SpillFunc[4];
1254   case Hexagon::R27:
1255     return SpillFunc[5];
1256   default:
1257     llvm_unreachable("Unhandled maximum callee save register");
1258   }
1259   return nullptr;
1260 }
1261 
1262 StackOffset
1263 HexagonFrameLowering::getFrameIndexReference(const MachineFunction &MF, int FI,
1264                                              Register &FrameReg) const {
1265   auto &MFI = MF.getFrameInfo();
1266   auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
1267 
1268   int Offset = MFI.getObjectOffset(FI);
1269   bool HasAlloca = MFI.hasVarSizedObjects();
1270   bool HasExtraAlign = HRI.hasStackRealignment(MF);
1271   bool NoOpt = MF.getTarget().getOptLevel() == CodeGenOpt::None;
1272 
1273   auto &HMFI = *MF.getInfo<HexagonMachineFunctionInfo>();
1274   unsigned FrameSize = MFI.getStackSize();
1275   Register SP = HRI.getStackRegister();
1276   Register FP = HRI.getFrameRegister();
1277   Register AP = HMFI.getStackAlignBasePhysReg();
1278   // It may happen that AP will be absent even HasAlloca && HasExtraAlign
1279   // is true. HasExtraAlign may be set because of vector spills, without
1280   // aligned locals or aligned outgoing function arguments. Since vector
1281   // spills will ultimately be "unaligned", it is safe to use FP as the
1282   // base register.
1283   // In fact, in such a scenario the stack is actually not required to be
1284   // aligned, although it may end up being aligned anyway, since this
1285   // particular case is not easily detectable. The alignment will be
1286   // unnecessary, but not incorrect.
1287   // Unfortunately there is no quick way to verify that the above is
1288   // indeed the case (and that it's not a result of an error), so just
1289   // assume that missing AP will be replaced by FP.
1290   // (A better fix would be to rematerialize AP from FP and always align
1291   // vector spills.)
1292   if (AP == 0)
1293     AP = FP;
1294 
1295   bool UseFP = false, UseAP = false;  // Default: use SP (except at -O0).
1296   // Use FP at -O0, except when there are objects with extra alignment.
1297   // That additional alignment requirement may cause a pad to be inserted,
1298   // which will make it impossible to use FP to access objects located
1299   // past the pad.
1300   if (NoOpt && !HasExtraAlign)
1301     UseFP = true;
1302   if (MFI.isFixedObjectIndex(FI) || MFI.isObjectPreAllocated(FI)) {
1303     // Fixed and preallocated objects will be located before any padding
1304     // so FP must be used to access them.
1305     UseFP |= (HasAlloca || HasExtraAlign);
1306   } else {
1307     if (HasAlloca) {
1308       if (HasExtraAlign)
1309         UseAP = true;
1310       else
1311         UseFP = true;
1312     }
1313   }
1314 
1315   // If FP was picked, then there had better be FP.
1316   bool HasFP = hasFP(MF);
1317   assert((HasFP || !UseFP) && "This function must have frame pointer");
1318 
1319   // Having FP implies allocframe. Allocframe will store extra 8 bytes:
1320   // FP/LR. If the base register is used to access an object across these
1321   // 8 bytes, then the offset will need to be adjusted by 8.
1322   //
1323   // After allocframe:
1324   //                    HexagonISelLowering adds 8 to ---+
1325   //                    the offsets of all stack-based   |
1326   //                    arguments (*)                    |
1327   //                                                     |
1328   //   getObjectOffset < 0   0     8  getObjectOffset >= 8
1329   // ------------------------+-----+------------------------> increasing
1330   //     <local objects>     |FP/LR|    <input arguments>     addresses
1331   // -----------------+------+-----+------------------------>
1332   //                  |      |
1333   //    SP/AP point --+      +-- FP points here (**)
1334   //    somewhere on
1335   //    this side of FP/LR
1336   //
1337   // (*) See LowerFormalArguments. The FP/LR is assumed to be present.
1338   // (**) *FP == old-FP. FP+0..7 are the bytes of FP/LR.
1339 
1340   // The lowering assumes that FP/LR is present, and so the offsets of
1341   // the formal arguments start at 8. If FP/LR is not there we need to
1342   // reduce the offset by 8.
1343   if (Offset > 0 && !HasFP)
1344     Offset -= 8;
1345 
1346   if (UseFP)
1347     FrameReg = FP;
1348   else if (UseAP)
1349     FrameReg = AP;
1350   else
1351     FrameReg = SP;
1352 
1353   // Calculate the actual offset in the instruction. If there is no FP
1354   // (in other words, no allocframe), then SP will not be adjusted (i.e.
1355   // there will be no SP -= FrameSize), so the frame size should not be
1356   // added to the calculated offset.
1357   int RealOffset = Offset;
1358   if (!UseFP && !UseAP)
1359     RealOffset = FrameSize+Offset;
1360   return StackOffset::getFixed(RealOffset);
1361 }
1362 
1363 bool HexagonFrameLowering::insertCSRSpillsInBlock(MachineBasicBlock &MBB,
1364       const CSIVect &CSI, const HexagonRegisterInfo &HRI,
1365       bool &PrologueStubs) const {
1366   if (CSI.empty())
1367     return true;
1368 
1369   MachineBasicBlock::iterator MI = MBB.begin();
1370   PrologueStubs = false;
1371   MachineFunction &MF = *MBB.getParent();
1372   auto &HST = MF.getSubtarget<HexagonSubtarget>();
1373   auto &HII = *HST.getInstrInfo();
1374 
1375   if (useSpillFunction(MF, CSI)) {
1376     PrologueStubs = true;
1377     unsigned MaxReg = getMaxCalleeSavedReg(CSI, HRI);
1378     bool StkOvrFlowEnabled = EnableStackOVFSanitizer;
1379     const char *SpillFun = getSpillFunctionFor(MaxReg, SK_ToMem,
1380                                                StkOvrFlowEnabled);
1381     auto &HTM = static_cast<const HexagonTargetMachine&>(MF.getTarget());
1382     bool IsPIC = HTM.isPositionIndependent();
1383     bool LongCalls = HST.useLongCalls() || EnableSaveRestoreLong;
1384 
1385     // Call spill function.
1386     DebugLoc DL = MI != MBB.end() ? MI->getDebugLoc() : DebugLoc();
1387     unsigned SpillOpc;
1388     if (StkOvrFlowEnabled) {
1389       if (LongCalls)
1390         SpillOpc = IsPIC ? Hexagon::SAVE_REGISTERS_CALL_V4STK_EXT_PIC
1391                          : Hexagon::SAVE_REGISTERS_CALL_V4STK_EXT;
1392       else
1393         SpillOpc = IsPIC ? Hexagon::SAVE_REGISTERS_CALL_V4STK_PIC
1394                          : Hexagon::SAVE_REGISTERS_CALL_V4STK;
1395     } else {
1396       if (LongCalls)
1397         SpillOpc = IsPIC ? Hexagon::SAVE_REGISTERS_CALL_V4_EXT_PIC
1398                          : Hexagon::SAVE_REGISTERS_CALL_V4_EXT;
1399       else
1400         SpillOpc = IsPIC ? Hexagon::SAVE_REGISTERS_CALL_V4_PIC
1401                          : Hexagon::SAVE_REGISTERS_CALL_V4;
1402     }
1403 
1404     MachineInstr *SaveRegsCall =
1405         BuildMI(MBB, MI, DL, HII.get(SpillOpc))
1406           .addExternalSymbol(SpillFun);
1407 
1408     // Add callee-saved registers as use.
1409     addCalleeSaveRegistersAsImpOperand(SaveRegsCall, CSI, false, true);
1410     // Add live in registers.
1411     for (const CalleeSavedInfo &I : CSI)
1412       MBB.addLiveIn(I.getReg());
1413     return true;
1414   }
1415 
1416   for (const CalleeSavedInfo &I : CSI) {
1417     Register Reg = I.getReg();
1418     // Add live in registers. We treat eh_return callee saved register r0 - r3
1419     // specially. They are not really callee saved registers as they are not
1420     // supposed to be killed.
1421     bool IsKill = !HRI.isEHReturnCalleeSaveReg(Reg);
1422     int FI = I.getFrameIdx();
1423     const TargetRegisterClass *RC = HRI.getMinimalPhysRegClass(Reg);
1424     HII.storeRegToStackSlot(MBB, MI, Reg, IsKill, FI, RC, &HRI);
1425     if (IsKill)
1426       MBB.addLiveIn(Reg);
1427   }
1428   return true;
1429 }
1430 
1431 bool HexagonFrameLowering::insertCSRRestoresInBlock(MachineBasicBlock &MBB,
1432       const CSIVect &CSI, const HexagonRegisterInfo &HRI) const {
1433   if (CSI.empty())
1434     return false;
1435 
1436   MachineBasicBlock::iterator MI = MBB.getFirstTerminator();
1437   MachineFunction &MF = *MBB.getParent();
1438   auto &HST = MF.getSubtarget<HexagonSubtarget>();
1439   auto &HII = *HST.getInstrInfo();
1440 
1441   if (useRestoreFunction(MF, CSI)) {
1442     bool HasTC = hasTailCall(MBB) || !hasReturn(MBB);
1443     unsigned MaxR = getMaxCalleeSavedReg(CSI, HRI);
1444     SpillKind Kind = HasTC ? SK_FromMemTailcall : SK_FromMem;
1445     const char *RestoreFn = getSpillFunctionFor(MaxR, Kind);
1446     auto &HTM = static_cast<const HexagonTargetMachine&>(MF.getTarget());
1447     bool IsPIC = HTM.isPositionIndependent();
1448     bool LongCalls = HST.useLongCalls() || EnableSaveRestoreLong;
1449 
1450     // Call spill function.
1451     DebugLoc DL = MI != MBB.end() ? MI->getDebugLoc()
1452                                   : MBB.findDebugLoc(MBB.end());
1453     MachineInstr *DeallocCall = nullptr;
1454 
1455     if (HasTC) {
1456       unsigned RetOpc;
1457       if (LongCalls)
1458         RetOpc = IsPIC ? Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_EXT_PIC
1459                        : Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_EXT;
1460       else
1461         RetOpc = IsPIC ? Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_PIC
1462                        : Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4;
1463       DeallocCall = BuildMI(MBB, MI, DL, HII.get(RetOpc))
1464           .addExternalSymbol(RestoreFn);
1465     } else {
1466       // The block has a return.
1467       MachineBasicBlock::iterator It = MBB.getFirstTerminator();
1468       assert(It->isReturn() && std::next(It) == MBB.end());
1469       unsigned RetOpc;
1470       if (LongCalls)
1471         RetOpc = IsPIC ? Hexagon::RESTORE_DEALLOC_RET_JMP_V4_EXT_PIC
1472                        : Hexagon::RESTORE_DEALLOC_RET_JMP_V4_EXT;
1473       else
1474         RetOpc = IsPIC ? Hexagon::RESTORE_DEALLOC_RET_JMP_V4_PIC
1475                        : Hexagon::RESTORE_DEALLOC_RET_JMP_V4;
1476       DeallocCall = BuildMI(MBB, It, DL, HII.get(RetOpc))
1477           .addExternalSymbol(RestoreFn);
1478       // Transfer the function live-out registers.
1479       DeallocCall->copyImplicitOps(MF, *It);
1480     }
1481     addCalleeSaveRegistersAsImpOperand(DeallocCall, CSI, true, false);
1482     return true;
1483   }
1484 
1485   for (const CalleeSavedInfo &I : CSI) {
1486     Register Reg = I.getReg();
1487     const TargetRegisterClass *RC = HRI.getMinimalPhysRegClass(Reg);
1488     int FI = I.getFrameIdx();
1489     HII.loadRegFromStackSlot(MBB, MI, Reg, FI, RC, &HRI);
1490   }
1491 
1492   return true;
1493 }
1494 
1495 MachineBasicBlock::iterator HexagonFrameLowering::eliminateCallFramePseudoInstr(
1496     MachineFunction &MF, MachineBasicBlock &MBB,
1497     MachineBasicBlock::iterator I) const {
1498   MachineInstr &MI = *I;
1499   unsigned Opc = MI.getOpcode();
1500   (void)Opc; // Silence compiler warning.
1501   assert((Opc == Hexagon::ADJCALLSTACKDOWN || Opc == Hexagon::ADJCALLSTACKUP) &&
1502          "Cannot handle this call frame pseudo instruction");
1503   return MBB.erase(I);
1504 }
1505 
1506 void HexagonFrameLowering::processFunctionBeforeFrameFinalized(
1507     MachineFunction &MF, RegScavenger *RS) const {
1508   // If this function has uses aligned stack and also has variable sized stack
1509   // objects, then we need to map all spill slots to fixed positions, so that
1510   // they can be accessed through FP. Otherwise they would have to be accessed
1511   // via AP, which may not be available at the particular place in the program.
1512   MachineFrameInfo &MFI = MF.getFrameInfo();
1513   bool HasAlloca = MFI.hasVarSizedObjects();
1514   bool NeedsAlign = (MFI.getMaxAlign() > getStackAlign());
1515 
1516   if (!HasAlloca || !NeedsAlign)
1517     return;
1518 
1519   SmallSet<int, 4> DealignSlots;
1520   unsigned LFS = MFI.getLocalFrameSize();
1521   for (int i = 0, e = MFI.getObjectIndexEnd(); i != e; ++i) {
1522     if (!MFI.isSpillSlotObjectIndex(i) || MFI.isDeadObjectIndex(i))
1523       continue;
1524     unsigned S = MFI.getObjectSize(i);
1525     // Reduce the alignment to at most 8. This will require unaligned vector
1526     // stores if they happen here.
1527     Align A = std::max(MFI.getObjectAlign(i), Align(8));
1528     MFI.setObjectAlignment(i, Align(8));
1529     LFS = alignTo(LFS+S, A);
1530     MFI.mapLocalFrameObject(i, -static_cast<int64_t>(LFS));
1531     DealignSlots.insert(i);
1532   }
1533 
1534   MFI.setLocalFrameSize(LFS);
1535   Align A = MFI.getLocalFrameMaxAlign();
1536   assert(A <= 8 && "Unexpected local frame alignment");
1537   if (A == 1)
1538     MFI.setLocalFrameMaxAlign(Align(8));
1539   MFI.setUseLocalStackAllocationBlock(true);
1540 
1541   // Go over all MachineMemOperands in the code, and change the ones that
1542   // refer to the dealigned stack slots to reflect the new alignment.
1543   if (!DealignSlots.empty()) {
1544     for (MachineBasicBlock &BB : MF) {
1545       for (MachineInstr &MI : BB) {
1546         bool KeepOld = true;
1547         ArrayRef<MachineMemOperand*> memops = MI.memoperands();
1548         SmallVector<MachineMemOperand*,1> new_memops;
1549         for (MachineMemOperand *MMO : memops) {
1550           auto *PV = MMO->getPseudoValue();
1551           if (auto *FS = dyn_cast_or_null<FixedStackPseudoSourceValue>(PV)) {
1552             int FI = FS->getFrameIndex();
1553             if (DealignSlots.count(FI)) {
1554               auto *NewMMO = MF.getMachineMemOperand(
1555                   MMO->getPointerInfo(), MMO->getFlags(), MMO->getSize(),
1556                   MFI.getObjectAlign(FI), MMO->getAAInfo(), MMO->getRanges(),
1557                   MMO->getSyncScopeID(), MMO->getSuccessOrdering(),
1558                   MMO->getFailureOrdering());
1559               new_memops.push_back(NewMMO);
1560               KeepOld = false;
1561               continue;
1562             }
1563           }
1564           new_memops.push_back(MMO);
1565         }
1566         if (!KeepOld)
1567           MI.setMemRefs(MF, new_memops);
1568       }
1569     }
1570   }
1571 
1572   // Set the physical aligned-stack base address register.
1573   unsigned AP = 0;
1574   if (const MachineInstr *AI = getAlignaInstr(MF))
1575     AP = AI->getOperand(0).getReg();
1576   auto &HMFI = *MF.getInfo<HexagonMachineFunctionInfo>();
1577   HMFI.setStackAlignBasePhysReg(AP);
1578 }
1579 
1580 /// Returns true if there are no caller-saved registers available in class RC.
1581 static bool needToReserveScavengingSpillSlots(MachineFunction &MF,
1582       const HexagonRegisterInfo &HRI, const TargetRegisterClass *RC) {
1583   MachineRegisterInfo &MRI = MF.getRegInfo();
1584 
1585   auto IsUsed = [&HRI,&MRI] (unsigned Reg) -> bool {
1586     for (MCRegAliasIterator AI(Reg, &HRI, true); AI.isValid(); ++AI)
1587       if (MRI.isPhysRegUsed(*AI))
1588         return true;
1589     return false;
1590   };
1591 
1592   // Check for an unused caller-saved register. Callee-saved registers
1593   // have become pristine by now.
1594   for (const MCPhysReg *P = HRI.getCallerSavedRegs(&MF, RC); *P; ++P)
1595     if (!IsUsed(*P))
1596       return false;
1597 
1598   // All caller-saved registers are used.
1599   return true;
1600 }
1601 
1602 #ifndef NDEBUG
1603 static void dump_registers(BitVector &Regs, const TargetRegisterInfo &TRI) {
1604   dbgs() << '{';
1605   for (int x = Regs.find_first(); x >= 0; x = Regs.find_next(x)) {
1606     unsigned R = x;
1607     dbgs() << ' ' << printReg(R, &TRI);
1608   }
1609   dbgs() << " }";
1610 }
1611 #endif
1612 
1613 bool HexagonFrameLowering::assignCalleeSavedSpillSlots(MachineFunction &MF,
1614       const TargetRegisterInfo *TRI, std::vector<CalleeSavedInfo> &CSI) const {
1615   LLVM_DEBUG(dbgs() << __func__ << " on " << MF.getName() << '\n');
1616   MachineFrameInfo &MFI = MF.getFrameInfo();
1617   BitVector SRegs(Hexagon::NUM_TARGET_REGS);
1618 
1619   // Generate a set of unique, callee-saved registers (SRegs), where each
1620   // register in the set is maximal in terms of sub-/super-register relation,
1621   // i.e. for each R in SRegs, no proper super-register of R is also in SRegs.
1622 
1623   // (1) For each callee-saved register, add that register and all of its
1624   // sub-registers to SRegs.
1625   LLVM_DEBUG(dbgs() << "Initial CS registers: {");
1626   for (const CalleeSavedInfo &I : CSI) {
1627     Register R = I.getReg();
1628     LLVM_DEBUG(dbgs() << ' ' << printReg(R, TRI));
1629     for (MCSubRegIterator SR(R, TRI, true); SR.isValid(); ++SR)
1630       SRegs[*SR] = true;
1631   }
1632   LLVM_DEBUG(dbgs() << " }\n");
1633   LLVM_DEBUG(dbgs() << "SRegs.1: "; dump_registers(SRegs, *TRI);
1634              dbgs() << "\n");
1635 
1636   // (2) For each reserved register, remove that register and all of its
1637   // sub- and super-registers from SRegs.
1638   BitVector Reserved = TRI->getReservedRegs(MF);
1639   for (int x = Reserved.find_first(); x >= 0; x = Reserved.find_next(x)) {
1640     unsigned R = x;
1641     for (MCSuperRegIterator SR(R, TRI, true); SR.isValid(); ++SR)
1642       SRegs[*SR] = false;
1643   }
1644   LLVM_DEBUG(dbgs() << "Res:     "; dump_registers(Reserved, *TRI);
1645              dbgs() << "\n");
1646   LLVM_DEBUG(dbgs() << "SRegs.2: "; dump_registers(SRegs, *TRI);
1647              dbgs() << "\n");
1648 
1649   // (3) Collect all registers that have at least one sub-register in SRegs,
1650   // and also have no sub-registers that are reserved. These will be the can-
1651   // didates for saving as a whole instead of their individual sub-registers.
1652   // (Saving R17:16 instead of R16 is fine, but only if R17 was not reserved.)
1653   BitVector TmpSup(Hexagon::NUM_TARGET_REGS);
1654   for (int x = SRegs.find_first(); x >= 0; x = SRegs.find_next(x)) {
1655     unsigned R = x;
1656     for (MCSuperRegIterator SR(R, TRI); SR.isValid(); ++SR)
1657       TmpSup[*SR] = true;
1658   }
1659   for (int x = TmpSup.find_first(); x >= 0; x = TmpSup.find_next(x)) {
1660     unsigned R = x;
1661     for (MCSubRegIterator SR(R, TRI, true); SR.isValid(); ++SR) {
1662       if (!Reserved[*SR])
1663         continue;
1664       TmpSup[R] = false;
1665       break;
1666     }
1667   }
1668   LLVM_DEBUG(dbgs() << "TmpSup:  "; dump_registers(TmpSup, *TRI);
1669              dbgs() << "\n");
1670 
1671   // (4) Include all super-registers found in (3) into SRegs.
1672   SRegs |= TmpSup;
1673   LLVM_DEBUG(dbgs() << "SRegs.4: "; dump_registers(SRegs, *TRI);
1674              dbgs() << "\n");
1675 
1676   // (5) For each register R in SRegs, if any super-register of R is in SRegs,
1677   // remove R from SRegs.
1678   for (int x = SRegs.find_first(); x >= 0; x = SRegs.find_next(x)) {
1679     unsigned R = x;
1680     for (MCSuperRegIterator SR(R, TRI); SR.isValid(); ++SR) {
1681       if (!SRegs[*SR])
1682         continue;
1683       SRegs[R] = false;
1684       break;
1685     }
1686   }
1687   LLVM_DEBUG(dbgs() << "SRegs.5: "; dump_registers(SRegs, *TRI);
1688              dbgs() << "\n");
1689 
1690   // Now, for each register that has a fixed stack slot, create the stack
1691   // object for it.
1692   CSI.clear();
1693 
1694   using SpillSlot = TargetFrameLowering::SpillSlot;
1695 
1696   unsigned NumFixed;
1697   int MinOffset = 0;  // CS offsets are negative.
1698   const SpillSlot *FixedSlots = getCalleeSavedSpillSlots(NumFixed);
1699   for (const SpillSlot *S = FixedSlots; S != FixedSlots+NumFixed; ++S) {
1700     if (!SRegs[S->Reg])
1701       continue;
1702     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(S->Reg);
1703     int FI = MFI.CreateFixedSpillStackObject(TRI->getSpillSize(*RC), S->Offset);
1704     MinOffset = std::min(MinOffset, S->Offset);
1705     CSI.push_back(CalleeSavedInfo(S->Reg, FI));
1706     SRegs[S->Reg] = false;
1707   }
1708 
1709   // There can be some registers that don't have fixed slots. For example,
1710   // we need to store R0-R3 in functions with exception handling. For each
1711   // such register, create a non-fixed stack object.
1712   for (int x = SRegs.find_first(); x >= 0; x = SRegs.find_next(x)) {
1713     unsigned R = x;
1714     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(R);
1715     unsigned Size = TRI->getSpillSize(*RC);
1716     int Off = MinOffset - Size;
1717     Align Alignment = std::min(TRI->getSpillAlign(*RC), getStackAlign());
1718     Off &= -Alignment.value();
1719     int FI = MFI.CreateFixedSpillStackObject(Size, Off);
1720     MinOffset = std::min(MinOffset, Off);
1721     CSI.push_back(CalleeSavedInfo(R, FI));
1722     SRegs[R] = false;
1723   }
1724 
1725   LLVM_DEBUG({
1726     dbgs() << "CS information: {";
1727     for (const CalleeSavedInfo &I : CSI) {
1728       int FI = I.getFrameIdx();
1729       int Off = MFI.getObjectOffset(FI);
1730       dbgs() << ' ' << printReg(I.getReg(), TRI) << ":fi#" << FI << ":sp";
1731       if (Off >= 0)
1732         dbgs() << '+';
1733       dbgs() << Off;
1734     }
1735     dbgs() << " }\n";
1736   });
1737 
1738 #ifndef NDEBUG
1739   // Verify that all registers were handled.
1740   bool MissedReg = false;
1741   for (int x = SRegs.find_first(); x >= 0; x = SRegs.find_next(x)) {
1742     unsigned R = x;
1743     dbgs() << printReg(R, TRI) << ' ';
1744     MissedReg = true;
1745   }
1746   if (MissedReg)
1747     llvm_unreachable("...there are unhandled callee-saved registers!");
1748 #endif
1749 
1750   return true;
1751 }
1752 
1753 bool HexagonFrameLowering::expandCopy(MachineBasicBlock &B,
1754       MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1755       const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1756   MachineInstr *MI = &*It;
1757   DebugLoc DL = MI->getDebugLoc();
1758   Register DstR = MI->getOperand(0).getReg();
1759   Register SrcR = MI->getOperand(1).getReg();
1760   if (!Hexagon::ModRegsRegClass.contains(DstR) ||
1761       !Hexagon::ModRegsRegClass.contains(SrcR))
1762     return false;
1763 
1764   Register TmpR = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
1765   BuildMI(B, It, DL, HII.get(TargetOpcode::COPY), TmpR).add(MI->getOperand(1));
1766   BuildMI(B, It, DL, HII.get(TargetOpcode::COPY), DstR)
1767     .addReg(TmpR, RegState::Kill);
1768 
1769   NewRegs.push_back(TmpR);
1770   B.erase(It);
1771   return true;
1772 }
1773 
1774 bool HexagonFrameLowering::expandStoreInt(MachineBasicBlock &B,
1775       MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1776       const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1777   MachineInstr *MI = &*It;
1778   if (!MI->getOperand(0).isFI())
1779     return false;
1780 
1781   DebugLoc DL = MI->getDebugLoc();
1782   unsigned Opc = MI->getOpcode();
1783   Register SrcR = MI->getOperand(2).getReg();
1784   bool IsKill = MI->getOperand(2).isKill();
1785   int FI = MI->getOperand(0).getIndex();
1786 
1787   // TmpR = C2_tfrpr SrcR   if SrcR is a predicate register
1788   // TmpR = A2_tfrcrr SrcR  if SrcR is a modifier register
1789   Register TmpR = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
1790   unsigned TfrOpc = (Opc == Hexagon::STriw_pred) ? Hexagon::C2_tfrpr
1791                                                  : Hexagon::A2_tfrcrr;
1792   BuildMI(B, It, DL, HII.get(TfrOpc), TmpR)
1793     .addReg(SrcR, getKillRegState(IsKill));
1794 
1795   // S2_storeri_io FI, 0, TmpR
1796   BuildMI(B, It, DL, HII.get(Hexagon::S2_storeri_io))
1797       .addFrameIndex(FI)
1798       .addImm(0)
1799       .addReg(TmpR, RegState::Kill)
1800       .cloneMemRefs(*MI);
1801 
1802   NewRegs.push_back(TmpR);
1803   B.erase(It);
1804   return true;
1805 }
1806 
1807 bool HexagonFrameLowering::expandLoadInt(MachineBasicBlock &B,
1808       MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1809       const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1810   MachineInstr *MI = &*It;
1811   if (!MI->getOperand(1).isFI())
1812     return false;
1813 
1814   DebugLoc DL = MI->getDebugLoc();
1815   unsigned Opc = MI->getOpcode();
1816   Register DstR = MI->getOperand(0).getReg();
1817   int FI = MI->getOperand(1).getIndex();
1818 
1819   // TmpR = L2_loadri_io FI, 0
1820   Register TmpR = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
1821   BuildMI(B, It, DL, HII.get(Hexagon::L2_loadri_io), TmpR)
1822       .addFrameIndex(FI)
1823       .addImm(0)
1824       .cloneMemRefs(*MI);
1825 
1826   // DstR = C2_tfrrp TmpR   if DstR is a predicate register
1827   // DstR = A2_tfrrcr TmpR  if DstR is a modifier register
1828   unsigned TfrOpc = (Opc == Hexagon::LDriw_pred) ? Hexagon::C2_tfrrp
1829                                                  : Hexagon::A2_tfrrcr;
1830   BuildMI(B, It, DL, HII.get(TfrOpc), DstR)
1831     .addReg(TmpR, RegState::Kill);
1832 
1833   NewRegs.push_back(TmpR);
1834   B.erase(It);
1835   return true;
1836 }
1837 
1838 bool HexagonFrameLowering::expandStoreVecPred(MachineBasicBlock &B,
1839       MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1840       const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1841   MachineInstr *MI = &*It;
1842   if (!MI->getOperand(0).isFI())
1843     return false;
1844 
1845   DebugLoc DL = MI->getDebugLoc();
1846   Register SrcR = MI->getOperand(2).getReg();
1847   bool IsKill = MI->getOperand(2).isKill();
1848   int FI = MI->getOperand(0).getIndex();
1849   auto *RC = &Hexagon::HvxVRRegClass;
1850 
1851   // Insert transfer to general vector register.
1852   //   TmpR0 = A2_tfrsi 0x01010101
1853   //   TmpR1 = V6_vandqrt Qx, TmpR0
1854   //   store FI, 0, TmpR1
1855   Register TmpR0 = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
1856   Register TmpR1 = MRI.createVirtualRegister(RC);
1857 
1858   BuildMI(B, It, DL, HII.get(Hexagon::A2_tfrsi), TmpR0)
1859     .addImm(0x01010101);
1860 
1861   BuildMI(B, It, DL, HII.get(Hexagon::V6_vandqrt), TmpR1)
1862     .addReg(SrcR, getKillRegState(IsKill))
1863     .addReg(TmpR0, RegState::Kill);
1864 
1865   auto *HRI = B.getParent()->getSubtarget<HexagonSubtarget>().getRegisterInfo();
1866   HII.storeRegToStackSlot(B, It, TmpR1, true, FI, RC, HRI);
1867   expandStoreVec(B, std::prev(It), MRI, HII, NewRegs);
1868 
1869   NewRegs.push_back(TmpR0);
1870   NewRegs.push_back(TmpR1);
1871   B.erase(It);
1872   return true;
1873 }
1874 
1875 bool HexagonFrameLowering::expandLoadVecPred(MachineBasicBlock &B,
1876       MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1877       const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1878   MachineInstr *MI = &*It;
1879   if (!MI->getOperand(1).isFI())
1880     return false;
1881 
1882   DebugLoc DL = MI->getDebugLoc();
1883   Register DstR = MI->getOperand(0).getReg();
1884   int FI = MI->getOperand(1).getIndex();
1885   auto *RC = &Hexagon::HvxVRRegClass;
1886 
1887   // TmpR0 = A2_tfrsi 0x01010101
1888   // TmpR1 = load FI, 0
1889   // DstR = V6_vandvrt TmpR1, TmpR0
1890   Register TmpR0 = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
1891   Register TmpR1 = MRI.createVirtualRegister(RC);
1892 
1893   BuildMI(B, It, DL, HII.get(Hexagon::A2_tfrsi), TmpR0)
1894     .addImm(0x01010101);
1895   MachineFunction &MF = *B.getParent();
1896   auto *HRI = MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
1897   HII.loadRegFromStackSlot(B, It, TmpR1, FI, RC, HRI);
1898   expandLoadVec(B, std::prev(It), MRI, HII, NewRegs);
1899 
1900   BuildMI(B, It, DL, HII.get(Hexagon::V6_vandvrt), DstR)
1901     .addReg(TmpR1, RegState::Kill)
1902     .addReg(TmpR0, RegState::Kill);
1903 
1904   NewRegs.push_back(TmpR0);
1905   NewRegs.push_back(TmpR1);
1906   B.erase(It);
1907   return true;
1908 }
1909 
1910 bool HexagonFrameLowering::expandStoreVec2(MachineBasicBlock &B,
1911       MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1912       const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1913   MachineFunction &MF = *B.getParent();
1914   auto &MFI = MF.getFrameInfo();
1915   auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
1916   MachineInstr *MI = &*It;
1917   if (!MI->getOperand(0).isFI())
1918     return false;
1919 
1920   // It is possible that the double vector being stored is only partially
1921   // defined. From the point of view of the liveness tracking, it is ok to
1922   // store it as a whole, but if we break it up we may end up storing a
1923   // register that is entirely undefined.
1924   LivePhysRegs LPR(HRI);
1925   LPR.addLiveIns(B);
1926   SmallVector<std::pair<MCPhysReg, const MachineOperand*>,2> Clobbers;
1927   for (auto R = B.begin(); R != It; ++R) {
1928     Clobbers.clear();
1929     LPR.stepForward(*R, Clobbers);
1930   }
1931 
1932   DebugLoc DL = MI->getDebugLoc();
1933   Register SrcR = MI->getOperand(2).getReg();
1934   Register SrcLo = HRI.getSubReg(SrcR, Hexagon::vsub_lo);
1935   Register SrcHi = HRI.getSubReg(SrcR, Hexagon::vsub_hi);
1936   bool IsKill = MI->getOperand(2).isKill();
1937   int FI = MI->getOperand(0).getIndex();
1938   bool NeedsAligna = needsAligna(MF);
1939 
1940   unsigned Size = HRI.getSpillSize(Hexagon::HvxVRRegClass);
1941   Align NeedAlign = HRI.getSpillAlign(Hexagon::HvxVRRegClass);
1942   Align HasAlign = MFI.getObjectAlign(FI);
1943   unsigned StoreOpc;
1944 
1945   auto UseAligned = [&](Align NeedAlign, Align HasAlign) {
1946     return !NeedsAligna && (NeedAlign <= HasAlign);
1947   };
1948 
1949   // Store low part.
1950   if (LPR.contains(SrcLo)) {
1951     StoreOpc = UseAligned(NeedAlign, HasAlign) ? Hexagon::V6_vS32b_ai
1952                                                : Hexagon::V6_vS32Ub_ai;
1953     BuildMI(B, It, DL, HII.get(StoreOpc))
1954         .addFrameIndex(FI)
1955         .addImm(0)
1956         .addReg(SrcLo, getKillRegState(IsKill))
1957         .cloneMemRefs(*MI);
1958   }
1959 
1960   // Store high part.
1961   if (LPR.contains(SrcHi)) {
1962     StoreOpc = UseAligned(NeedAlign, HasAlign) ? Hexagon::V6_vS32b_ai
1963                                                : Hexagon::V6_vS32Ub_ai;
1964     BuildMI(B, It, DL, HII.get(StoreOpc))
1965         .addFrameIndex(FI)
1966         .addImm(Size)
1967         .addReg(SrcHi, getKillRegState(IsKill))
1968         .cloneMemRefs(*MI);
1969   }
1970 
1971   B.erase(It);
1972   return true;
1973 }
1974 
1975 bool HexagonFrameLowering::expandLoadVec2(MachineBasicBlock &B,
1976       MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1977       const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1978   MachineFunction &MF = *B.getParent();
1979   auto &MFI = MF.getFrameInfo();
1980   auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
1981   MachineInstr *MI = &*It;
1982   if (!MI->getOperand(1).isFI())
1983     return false;
1984 
1985   DebugLoc DL = MI->getDebugLoc();
1986   Register DstR = MI->getOperand(0).getReg();
1987   Register DstHi = HRI.getSubReg(DstR, Hexagon::vsub_hi);
1988   Register DstLo = HRI.getSubReg(DstR, Hexagon::vsub_lo);
1989   int FI = MI->getOperand(1).getIndex();
1990   bool NeedsAligna = needsAligna(MF);
1991 
1992   unsigned Size = HRI.getSpillSize(Hexagon::HvxVRRegClass);
1993   Align NeedAlign = HRI.getSpillAlign(Hexagon::HvxVRRegClass);
1994   Align HasAlign = MFI.getObjectAlign(FI);
1995   unsigned LoadOpc;
1996 
1997   auto UseAligned = [&](Align NeedAlign, Align HasAlign) {
1998     return !NeedsAligna && (NeedAlign <= HasAlign);
1999   };
2000 
2001   // Load low part.
2002   LoadOpc = UseAligned(NeedAlign, HasAlign) ? Hexagon::V6_vL32b_ai
2003                                             : Hexagon::V6_vL32Ub_ai;
2004   BuildMI(B, It, DL, HII.get(LoadOpc), DstLo)
2005       .addFrameIndex(FI)
2006       .addImm(0)
2007       .cloneMemRefs(*MI);
2008 
2009   // Load high part.
2010   LoadOpc = UseAligned(NeedAlign, HasAlign) ? Hexagon::V6_vL32b_ai
2011                                             : Hexagon::V6_vL32Ub_ai;
2012   BuildMI(B, It, DL, HII.get(LoadOpc), DstHi)
2013       .addFrameIndex(FI)
2014       .addImm(Size)
2015       .cloneMemRefs(*MI);
2016 
2017   B.erase(It);
2018   return true;
2019 }
2020 
2021 bool HexagonFrameLowering::expandStoreVec(MachineBasicBlock &B,
2022       MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
2023       const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
2024   MachineFunction &MF = *B.getParent();
2025   auto &MFI = MF.getFrameInfo();
2026   MachineInstr *MI = &*It;
2027   if (!MI->getOperand(0).isFI())
2028     return false;
2029 
2030   bool NeedsAligna = needsAligna(MF);
2031   auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
2032   DebugLoc DL = MI->getDebugLoc();
2033   Register SrcR = MI->getOperand(2).getReg();
2034   bool IsKill = MI->getOperand(2).isKill();
2035   int FI = MI->getOperand(0).getIndex();
2036 
2037   Align NeedAlign = HRI.getSpillAlign(Hexagon::HvxVRRegClass);
2038   Align HasAlign = MFI.getObjectAlign(FI);
2039   bool UseAligned = !NeedsAligna && (NeedAlign <= HasAlign);
2040   unsigned StoreOpc = UseAligned ? Hexagon::V6_vS32b_ai
2041                                  : Hexagon::V6_vS32Ub_ai;
2042   BuildMI(B, It, DL, HII.get(StoreOpc))
2043       .addFrameIndex(FI)
2044       .addImm(0)
2045       .addReg(SrcR, getKillRegState(IsKill))
2046       .cloneMemRefs(*MI);
2047 
2048   B.erase(It);
2049   return true;
2050 }
2051 
2052 bool HexagonFrameLowering::expandLoadVec(MachineBasicBlock &B,
2053       MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
2054       const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
2055   MachineFunction &MF = *B.getParent();
2056   auto &MFI = MF.getFrameInfo();
2057   MachineInstr *MI = &*It;
2058   if (!MI->getOperand(1).isFI())
2059     return false;
2060 
2061   bool NeedsAligna = needsAligna(MF);
2062   auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
2063   DebugLoc DL = MI->getDebugLoc();
2064   Register DstR = MI->getOperand(0).getReg();
2065   int FI = MI->getOperand(1).getIndex();
2066 
2067   Align NeedAlign = HRI.getSpillAlign(Hexagon::HvxVRRegClass);
2068   Align HasAlign = MFI.getObjectAlign(FI);
2069   bool UseAligned = !NeedsAligna && (NeedAlign <= HasAlign);
2070   unsigned LoadOpc = UseAligned ? Hexagon::V6_vL32b_ai
2071                                 : Hexagon::V6_vL32Ub_ai;
2072   BuildMI(B, It, DL, HII.get(LoadOpc), DstR)
2073       .addFrameIndex(FI)
2074       .addImm(0)
2075       .cloneMemRefs(*MI);
2076 
2077   B.erase(It);
2078   return true;
2079 }
2080 
2081 bool HexagonFrameLowering::expandSpillMacros(MachineFunction &MF,
2082       SmallVectorImpl<unsigned> &NewRegs) const {
2083   auto &HII = *MF.getSubtarget<HexagonSubtarget>().getInstrInfo();
2084   MachineRegisterInfo &MRI = MF.getRegInfo();
2085   bool Changed = false;
2086 
2087   for (auto &B : MF) {
2088     // Traverse the basic block.
2089     MachineBasicBlock::iterator NextI;
2090     for (auto I = B.begin(), E = B.end(); I != E; I = NextI) {
2091       MachineInstr *MI = &*I;
2092       NextI = std::next(I);
2093       unsigned Opc = MI->getOpcode();
2094 
2095       switch (Opc) {
2096         case TargetOpcode::COPY:
2097           Changed |= expandCopy(B, I, MRI, HII, NewRegs);
2098           break;
2099         case Hexagon::STriw_pred:
2100         case Hexagon::STriw_ctr:
2101           Changed |= expandStoreInt(B, I, MRI, HII, NewRegs);
2102           break;
2103         case Hexagon::LDriw_pred:
2104         case Hexagon::LDriw_ctr:
2105           Changed |= expandLoadInt(B, I, MRI, HII, NewRegs);
2106           break;
2107         case Hexagon::PS_vstorerq_ai:
2108           Changed |= expandStoreVecPred(B, I, MRI, HII, NewRegs);
2109           break;
2110         case Hexagon::PS_vloadrq_ai:
2111           Changed |= expandLoadVecPred(B, I, MRI, HII, NewRegs);
2112           break;
2113         case Hexagon::PS_vloadrw_ai:
2114           Changed |= expandLoadVec2(B, I, MRI, HII, NewRegs);
2115           break;
2116         case Hexagon::PS_vstorerw_ai:
2117           Changed |= expandStoreVec2(B, I, MRI, HII, NewRegs);
2118           break;
2119       }
2120     }
2121   }
2122 
2123   return Changed;
2124 }
2125 
2126 void HexagonFrameLowering::determineCalleeSaves(MachineFunction &MF,
2127                                                 BitVector &SavedRegs,
2128                                                 RegScavenger *RS) const {
2129   auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
2130 
2131   SavedRegs.resize(HRI.getNumRegs());
2132 
2133   // If we have a function containing __builtin_eh_return we want to spill and
2134   // restore all callee saved registers. Pretend that they are used.
2135   if (MF.getInfo<HexagonMachineFunctionInfo>()->hasEHReturn())
2136     for (const MCPhysReg *R = HRI.getCalleeSavedRegs(&MF); *R; ++R)
2137       SavedRegs.set(*R);
2138 
2139   // Replace predicate register pseudo spill code.
2140   SmallVector<unsigned,8> NewRegs;
2141   expandSpillMacros(MF, NewRegs);
2142   if (OptimizeSpillSlots && !isOptNone(MF))
2143     optimizeSpillSlots(MF, NewRegs);
2144 
2145   // We need to reserve a spill slot if scavenging could potentially require
2146   // spilling a scavenged register.
2147   if (!NewRegs.empty() || mayOverflowFrameOffset(MF)) {
2148     MachineFrameInfo &MFI = MF.getFrameInfo();
2149     MachineRegisterInfo &MRI = MF.getRegInfo();
2150     SetVector<const TargetRegisterClass*> SpillRCs;
2151     // Reserve an int register in any case, because it could be used to hold
2152     // the stack offset in case it does not fit into a spill instruction.
2153     SpillRCs.insert(&Hexagon::IntRegsRegClass);
2154 
2155     for (unsigned VR : NewRegs)
2156       SpillRCs.insert(MRI.getRegClass(VR));
2157 
2158     for (auto *RC : SpillRCs) {
2159       if (!needToReserveScavengingSpillSlots(MF, HRI, RC))
2160         continue;
2161       unsigned Num = 1;
2162       switch (RC->getID()) {
2163         case Hexagon::IntRegsRegClassID:
2164           Num = NumberScavengerSlots;
2165           break;
2166         case Hexagon::HvxQRRegClassID:
2167           Num = 2; // Vector predicate spills also need a vector register.
2168           break;
2169       }
2170       unsigned S = HRI.getSpillSize(*RC);
2171       Align A = HRI.getSpillAlign(*RC);
2172       for (unsigned i = 0; i < Num; i++) {
2173         int NewFI = MFI.CreateSpillStackObject(S, A);
2174         RS->addScavengingFrameIndex(NewFI);
2175       }
2176     }
2177   }
2178 
2179   TargetFrameLowering::determineCalleeSaves(MF, SavedRegs, RS);
2180 }
2181 
2182 unsigned HexagonFrameLowering::findPhysReg(MachineFunction &MF,
2183       HexagonBlockRanges::IndexRange &FIR,
2184       HexagonBlockRanges::InstrIndexMap &IndexMap,
2185       HexagonBlockRanges::RegToRangeMap &DeadMap,
2186       const TargetRegisterClass *RC) const {
2187   auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
2188   auto &MRI = MF.getRegInfo();
2189 
2190   auto isDead = [&FIR,&DeadMap] (unsigned Reg) -> bool {
2191     auto F = DeadMap.find({Reg,0});
2192     if (F == DeadMap.end())
2193       return false;
2194     for (auto &DR : F->second)
2195       if (DR.contains(FIR))
2196         return true;
2197     return false;
2198   };
2199 
2200   for (unsigned Reg : RC->getRawAllocationOrder(MF)) {
2201     bool Dead = true;
2202     for (auto R : HexagonBlockRanges::expandToSubRegs({Reg,0}, MRI, HRI)) {
2203       if (isDead(R.Reg))
2204         continue;
2205       Dead = false;
2206       break;
2207     }
2208     if (Dead)
2209       return Reg;
2210   }
2211   return 0;
2212 }
2213 
2214 void HexagonFrameLowering::optimizeSpillSlots(MachineFunction &MF,
2215       SmallVectorImpl<unsigned> &VRegs) const {
2216   auto &HST = MF.getSubtarget<HexagonSubtarget>();
2217   auto &HII = *HST.getInstrInfo();
2218   auto &HRI = *HST.getRegisterInfo();
2219   auto &MRI = MF.getRegInfo();
2220   HexagonBlockRanges HBR(MF);
2221 
2222   using BlockIndexMap =
2223       std::map<MachineBasicBlock *, HexagonBlockRanges::InstrIndexMap>;
2224   using BlockRangeMap =
2225       std::map<MachineBasicBlock *, HexagonBlockRanges::RangeList>;
2226   using IndexType = HexagonBlockRanges::IndexType;
2227 
2228   struct SlotInfo {
2229     BlockRangeMap Map;
2230     unsigned Size = 0;
2231     const TargetRegisterClass *RC = nullptr;
2232 
2233     SlotInfo() = default;
2234   };
2235 
2236   BlockIndexMap BlockIndexes;
2237   SmallSet<int,4> BadFIs;
2238   std::map<int,SlotInfo> FIRangeMap;
2239 
2240   // Accumulate register classes: get a common class for a pre-existing
2241   // class HaveRC and a new class NewRC. Return nullptr if a common class
2242   // cannot be found, otherwise return the resulting class. If HaveRC is
2243   // nullptr, assume that it is still unset.
2244   auto getCommonRC =
2245       [](const TargetRegisterClass *HaveRC,
2246          const TargetRegisterClass *NewRC) -> const TargetRegisterClass * {
2247     if (HaveRC == nullptr || HaveRC == NewRC)
2248       return NewRC;
2249     // Different classes, both non-null. Pick the more general one.
2250     if (HaveRC->hasSubClassEq(NewRC))
2251       return HaveRC;
2252     if (NewRC->hasSubClassEq(HaveRC))
2253       return NewRC;
2254     return nullptr;
2255   };
2256 
2257   // Scan all blocks in the function. Check all occurrences of frame indexes,
2258   // and collect relevant information.
2259   for (auto &B : MF) {
2260     std::map<int,IndexType> LastStore, LastLoad;
2261     // Emplace appears not to be supported in gcc 4.7.2-4.
2262     //auto P = BlockIndexes.emplace(&B, HexagonBlockRanges::InstrIndexMap(B));
2263     auto P = BlockIndexes.insert(
2264                 std::make_pair(&B, HexagonBlockRanges::InstrIndexMap(B)));
2265     auto &IndexMap = P.first->second;
2266     LLVM_DEBUG(dbgs() << "Index map for " << printMBBReference(B) << "\n"
2267                       << IndexMap << '\n');
2268 
2269     for (auto &In : B) {
2270       int LFI, SFI;
2271       bool Load = HII.isLoadFromStackSlot(In, LFI) && !HII.isPredicated(In);
2272       bool Store = HII.isStoreToStackSlot(In, SFI) && !HII.isPredicated(In);
2273       if (Load && Store) {
2274         // If it's both a load and a store, then we won't handle it.
2275         BadFIs.insert(LFI);
2276         BadFIs.insert(SFI);
2277         continue;
2278       }
2279       // Check for register classes of the register used as the source for
2280       // the store, and the register used as the destination for the load.
2281       // Also, only accept base+imm_offset addressing modes. Other addressing
2282       // modes can have side-effects (post-increments, etc.). For stack
2283       // slots they are very unlikely, so there is not much loss due to
2284       // this restriction.
2285       if (Load || Store) {
2286         int TFI = Load ? LFI : SFI;
2287         unsigned AM = HII.getAddrMode(In);
2288         SlotInfo &SI = FIRangeMap[TFI];
2289         bool Bad = (AM != HexagonII::BaseImmOffset);
2290         if (!Bad) {
2291           // If the addressing mode is ok, check the register class.
2292           unsigned OpNum = Load ? 0 : 2;
2293           auto *RC = HII.getRegClass(In.getDesc(), OpNum, &HRI, MF);
2294           RC = getCommonRC(SI.RC, RC);
2295           if (RC == nullptr)
2296             Bad = true;
2297           else
2298             SI.RC = RC;
2299         }
2300         if (!Bad) {
2301           // Check sizes.
2302           unsigned S = HII.getMemAccessSize(In);
2303           if (SI.Size != 0 && SI.Size != S)
2304             Bad = true;
2305           else
2306             SI.Size = S;
2307         }
2308         if (!Bad) {
2309           for (auto *Mo : In.memoperands()) {
2310             if (!Mo->isVolatile() && !Mo->isAtomic())
2311               continue;
2312             Bad = true;
2313             break;
2314           }
2315         }
2316         if (Bad)
2317           BadFIs.insert(TFI);
2318       }
2319 
2320       // Locate uses of frame indices.
2321       for (unsigned i = 0, n = In.getNumOperands(); i < n; ++i) {
2322         const MachineOperand &Op = In.getOperand(i);
2323         if (!Op.isFI())
2324           continue;
2325         int FI = Op.getIndex();
2326         // Make sure that the following operand is an immediate and that
2327         // it is 0. This is the offset in the stack object.
2328         if (i+1 >= n || !In.getOperand(i+1).isImm() ||
2329             In.getOperand(i+1).getImm() != 0)
2330           BadFIs.insert(FI);
2331         if (BadFIs.count(FI))
2332           continue;
2333 
2334         IndexType Index = IndexMap.getIndex(&In);
2335         if (Load) {
2336           if (LastStore[FI] == IndexType::None)
2337             LastStore[FI] = IndexType::Entry;
2338           LastLoad[FI] = Index;
2339         } else if (Store) {
2340           HexagonBlockRanges::RangeList &RL = FIRangeMap[FI].Map[&B];
2341           if (LastStore[FI] != IndexType::None)
2342             RL.add(LastStore[FI], LastLoad[FI], false, false);
2343           else if (LastLoad[FI] != IndexType::None)
2344             RL.add(IndexType::Entry, LastLoad[FI], false, false);
2345           LastLoad[FI] = IndexType::None;
2346           LastStore[FI] = Index;
2347         } else {
2348           BadFIs.insert(FI);
2349         }
2350       }
2351     }
2352 
2353     for (auto &I : LastLoad) {
2354       IndexType LL = I.second;
2355       if (LL == IndexType::None)
2356         continue;
2357       auto &RL = FIRangeMap[I.first].Map[&B];
2358       IndexType &LS = LastStore[I.first];
2359       if (LS != IndexType::None)
2360         RL.add(LS, LL, false, false);
2361       else
2362         RL.add(IndexType::Entry, LL, false, false);
2363       LS = IndexType::None;
2364     }
2365     for (auto &I : LastStore) {
2366       IndexType LS = I.second;
2367       if (LS == IndexType::None)
2368         continue;
2369       auto &RL = FIRangeMap[I.first].Map[&B];
2370       RL.add(LS, IndexType::None, false, false);
2371     }
2372   }
2373 
2374   LLVM_DEBUG({
2375     for (auto &P : FIRangeMap) {
2376       dbgs() << "fi#" << P.first;
2377       if (BadFIs.count(P.first))
2378         dbgs() << " (bad)";
2379       dbgs() << "  RC: ";
2380       if (P.second.RC != nullptr)
2381         dbgs() << HRI.getRegClassName(P.second.RC) << '\n';
2382       else
2383         dbgs() << "<null>\n";
2384       for (auto &R : P.second.Map)
2385         dbgs() << "  " << printMBBReference(*R.first) << " { " << R.second
2386                << "}\n";
2387     }
2388   });
2389 
2390   // When a slot is loaded from in a block without being stored to in the
2391   // same block, it is live-on-entry to this block. To avoid CFG analysis,
2392   // consider this slot to be live-on-exit from all blocks.
2393   SmallSet<int,4> LoxFIs;
2394 
2395   std::map<MachineBasicBlock*,std::vector<int>> BlockFIMap;
2396 
2397   for (auto &P : FIRangeMap) {
2398     // P = pair(FI, map: BB->RangeList)
2399     if (BadFIs.count(P.first))
2400       continue;
2401     for (auto &B : MF) {
2402       auto F = P.second.Map.find(&B);
2403       // F = pair(BB, RangeList)
2404       if (F == P.second.Map.end() || F->second.empty())
2405         continue;
2406       HexagonBlockRanges::IndexRange &IR = F->second.front();
2407       if (IR.start() == IndexType::Entry)
2408         LoxFIs.insert(P.first);
2409       BlockFIMap[&B].push_back(P.first);
2410     }
2411   }
2412 
2413   LLVM_DEBUG({
2414     dbgs() << "Block-to-FI map (* -- live-on-exit):\n";
2415     for (auto &P : BlockFIMap) {
2416       auto &FIs = P.second;
2417       if (FIs.empty())
2418         continue;
2419       dbgs() << "  " << printMBBReference(*P.first) << ": {";
2420       for (auto I : FIs) {
2421         dbgs() << " fi#" << I;
2422         if (LoxFIs.count(I))
2423           dbgs() << '*';
2424       }
2425       dbgs() << " }\n";
2426     }
2427   });
2428 
2429 #ifndef NDEBUG
2430   bool HasOptLimit = SpillOptMax.getPosition();
2431 #endif
2432 
2433   // eliminate loads, when all loads eliminated, eliminate all stores.
2434   for (auto &B : MF) {
2435     auto F = BlockIndexes.find(&B);
2436     assert(F != BlockIndexes.end());
2437     HexagonBlockRanges::InstrIndexMap &IM = F->second;
2438     HexagonBlockRanges::RegToRangeMap LM = HBR.computeLiveMap(IM);
2439     HexagonBlockRanges::RegToRangeMap DM = HBR.computeDeadMap(IM, LM);
2440     LLVM_DEBUG(dbgs() << printMBBReference(B) << " dead map\n"
2441                       << HexagonBlockRanges::PrintRangeMap(DM, HRI));
2442 
2443     for (auto FI : BlockFIMap[&B]) {
2444       if (BadFIs.count(FI))
2445         continue;
2446       LLVM_DEBUG(dbgs() << "Working on fi#" << FI << '\n');
2447       HexagonBlockRanges::RangeList &RL = FIRangeMap[FI].Map[&B];
2448       for (auto &Range : RL) {
2449         LLVM_DEBUG(dbgs() << "--Examining range:" << RL << '\n');
2450         if (!IndexType::isInstr(Range.start()) ||
2451             !IndexType::isInstr(Range.end()))
2452           continue;
2453         MachineInstr &SI = *IM.getInstr(Range.start());
2454         MachineInstr &EI = *IM.getInstr(Range.end());
2455         assert(SI.mayStore() && "Unexpected start instruction");
2456         assert(EI.mayLoad() && "Unexpected end instruction");
2457         MachineOperand &SrcOp = SI.getOperand(2);
2458 
2459         HexagonBlockRanges::RegisterRef SrcRR = { SrcOp.getReg(),
2460                                                   SrcOp.getSubReg() };
2461         auto *RC = HII.getRegClass(SI.getDesc(), 2, &HRI, MF);
2462         // The this-> is needed to unconfuse MSVC.
2463         unsigned FoundR = this->findPhysReg(MF, Range, IM, DM, RC);
2464         LLVM_DEBUG(dbgs() << "Replacement reg:" << printReg(FoundR, &HRI)
2465                           << '\n');
2466         if (FoundR == 0)
2467           continue;
2468 #ifndef NDEBUG
2469         if (HasOptLimit) {
2470           if (SpillOptCount >= SpillOptMax)
2471             return;
2472           SpillOptCount++;
2473         }
2474 #endif
2475 
2476         // Generate the copy-in: "FoundR = COPY SrcR" at the store location.
2477         MachineBasicBlock::iterator StartIt = SI.getIterator(), NextIt;
2478         MachineInstr *CopyIn = nullptr;
2479         if (SrcRR.Reg != FoundR || SrcRR.Sub != 0) {
2480           const DebugLoc &DL = SI.getDebugLoc();
2481           CopyIn = BuildMI(B, StartIt, DL, HII.get(TargetOpcode::COPY), FoundR)
2482                        .add(SrcOp);
2483         }
2484 
2485         ++StartIt;
2486         // Check if this is a last store and the FI is live-on-exit.
2487         if (LoxFIs.count(FI) && (&Range == &RL.back())) {
2488           // Update store's source register.
2489           if (unsigned SR = SrcOp.getSubReg())
2490             SrcOp.setReg(HRI.getSubReg(FoundR, SR));
2491           else
2492             SrcOp.setReg(FoundR);
2493           SrcOp.setSubReg(0);
2494           // We are keeping this register live.
2495           SrcOp.setIsKill(false);
2496         } else {
2497           B.erase(&SI);
2498           IM.replaceInstr(&SI, CopyIn);
2499         }
2500 
2501         auto EndIt = std::next(EI.getIterator());
2502         for (auto It = StartIt; It != EndIt; It = NextIt) {
2503           MachineInstr &MI = *It;
2504           NextIt = std::next(It);
2505           int TFI;
2506           if (!HII.isLoadFromStackSlot(MI, TFI) || TFI != FI)
2507             continue;
2508           Register DstR = MI.getOperand(0).getReg();
2509           assert(MI.getOperand(0).getSubReg() == 0);
2510           MachineInstr *CopyOut = nullptr;
2511           if (DstR != FoundR) {
2512             DebugLoc DL = MI.getDebugLoc();
2513             unsigned MemSize = HII.getMemAccessSize(MI);
2514             assert(HII.getAddrMode(MI) == HexagonII::BaseImmOffset);
2515             unsigned CopyOpc = TargetOpcode::COPY;
2516             if (HII.isSignExtendingLoad(MI))
2517               CopyOpc = (MemSize == 1) ? Hexagon::A2_sxtb : Hexagon::A2_sxth;
2518             else if (HII.isZeroExtendingLoad(MI))
2519               CopyOpc = (MemSize == 1) ? Hexagon::A2_zxtb : Hexagon::A2_zxth;
2520             CopyOut = BuildMI(B, It, DL, HII.get(CopyOpc), DstR)
2521                         .addReg(FoundR, getKillRegState(&MI == &EI));
2522           }
2523           IM.replaceInstr(&MI, CopyOut);
2524           B.erase(It);
2525         }
2526 
2527         // Update the dead map.
2528         HexagonBlockRanges::RegisterRef FoundRR = { FoundR, 0 };
2529         for (auto RR : HexagonBlockRanges::expandToSubRegs(FoundRR, MRI, HRI))
2530           DM[RR].subtract(Range);
2531       } // for Range in range list
2532     }
2533   }
2534 }
2535 
2536 void HexagonFrameLowering::expandAlloca(MachineInstr *AI,
2537       const HexagonInstrInfo &HII, unsigned SP, unsigned CF) const {
2538   MachineBasicBlock &MB = *AI->getParent();
2539   DebugLoc DL = AI->getDebugLoc();
2540   unsigned A = AI->getOperand(2).getImm();
2541 
2542   // Have
2543   //    Rd  = alloca Rs, #A
2544   //
2545   // If Rs and Rd are different registers, use this sequence:
2546   //    Rd  = sub(r29, Rs)
2547   //    r29 = sub(r29, Rs)
2548   //    Rd  = and(Rd, #-A)    ; if necessary
2549   //    r29 = and(r29, #-A)   ; if necessary
2550   //    Rd  = add(Rd, #CF)    ; CF size aligned to at most A
2551   // otherwise, do
2552   //    Rd  = sub(r29, Rs)
2553   //    Rd  = and(Rd, #-A)    ; if necessary
2554   //    r29 = Rd
2555   //    Rd  = add(Rd, #CF)    ; CF size aligned to at most A
2556 
2557   MachineOperand &RdOp = AI->getOperand(0);
2558   MachineOperand &RsOp = AI->getOperand(1);
2559   unsigned Rd = RdOp.getReg(), Rs = RsOp.getReg();
2560 
2561   // Rd = sub(r29, Rs)
2562   BuildMI(MB, AI, DL, HII.get(Hexagon::A2_sub), Rd)
2563       .addReg(SP)
2564       .addReg(Rs);
2565   if (Rs != Rd) {
2566     // r29 = sub(r29, Rs)
2567     BuildMI(MB, AI, DL, HII.get(Hexagon::A2_sub), SP)
2568         .addReg(SP)
2569         .addReg(Rs);
2570   }
2571   if (A > 8) {
2572     // Rd  = and(Rd, #-A)
2573     BuildMI(MB, AI, DL, HII.get(Hexagon::A2_andir), Rd)
2574         .addReg(Rd)
2575         .addImm(-int64_t(A));
2576     if (Rs != Rd)
2577       BuildMI(MB, AI, DL, HII.get(Hexagon::A2_andir), SP)
2578           .addReg(SP)
2579           .addImm(-int64_t(A));
2580   }
2581   if (Rs == Rd) {
2582     // r29 = Rd
2583     BuildMI(MB, AI, DL, HII.get(TargetOpcode::COPY), SP)
2584         .addReg(Rd);
2585   }
2586   if (CF > 0) {
2587     // Rd = add(Rd, #CF)
2588     BuildMI(MB, AI, DL, HII.get(Hexagon::A2_addi), Rd)
2589         .addReg(Rd)
2590         .addImm(CF);
2591   }
2592 }
2593 
2594 bool HexagonFrameLowering::needsAligna(const MachineFunction &MF) const {
2595   const MachineFrameInfo &MFI = MF.getFrameInfo();
2596   if (!MFI.hasVarSizedObjects())
2597     return false;
2598   // Do not check for max stack object alignment here, because the stack
2599   // may not be complete yet. Assume that we will need PS_aligna if there
2600   // are variable-sized objects.
2601   return true;
2602 }
2603 
2604 const MachineInstr *HexagonFrameLowering::getAlignaInstr(
2605       const MachineFunction &MF) const {
2606   for (auto &B : MF)
2607     for (auto &I : B)
2608       if (I.getOpcode() == Hexagon::PS_aligna)
2609         return &I;
2610   return nullptr;
2611 }
2612 
2613 /// Adds all callee-saved registers as implicit uses or defs to the
2614 /// instruction.
2615 void HexagonFrameLowering::addCalleeSaveRegistersAsImpOperand(MachineInstr *MI,
2616       const CSIVect &CSI, bool IsDef, bool IsKill) const {
2617   // Add the callee-saved registers as implicit uses.
2618   for (auto &R : CSI)
2619     MI->addOperand(MachineOperand::CreateReg(R.getReg(), IsDef, true, IsKill));
2620 }
2621 
2622 /// Determine whether the callee-saved register saves and restores should
2623 /// be generated via inline code. If this function returns "true", inline
2624 /// code will be generated. If this function returns "false", additional
2625 /// checks are performed, which may still lead to the inline code.
2626 bool HexagonFrameLowering::shouldInlineCSR(const MachineFunction &MF,
2627       const CSIVect &CSI) const {
2628   if (MF.getSubtarget<HexagonSubtarget>().isEnvironmentMusl())
2629     return true;
2630   if (MF.getInfo<HexagonMachineFunctionInfo>()->hasEHReturn())
2631     return true;
2632   if (!hasFP(MF))
2633     return true;
2634   if (!isOptSize(MF) && !isMinSize(MF))
2635     if (MF.getTarget().getOptLevel() > CodeGenOpt::Default)
2636       return true;
2637 
2638   // Check if CSI only has double registers, and if the registers form
2639   // a contiguous block starting from D8.
2640   BitVector Regs(Hexagon::NUM_TARGET_REGS);
2641   for (const CalleeSavedInfo &I : CSI) {
2642     Register R = I.getReg();
2643     if (!Hexagon::DoubleRegsRegClass.contains(R))
2644       return true;
2645     Regs[R] = true;
2646   }
2647   int F = Regs.find_first();
2648   if (F != Hexagon::D8)
2649     return true;
2650   while (F >= 0) {
2651     int N = Regs.find_next(F);
2652     if (N >= 0 && N != F+1)
2653       return true;
2654     F = N;
2655   }
2656 
2657   return false;
2658 }
2659 
2660 bool HexagonFrameLowering::useSpillFunction(const MachineFunction &MF,
2661       const CSIVect &CSI) const {
2662   if (shouldInlineCSR(MF, CSI))
2663     return false;
2664   unsigned NumCSI = CSI.size();
2665   if (NumCSI <= 1)
2666     return false;
2667 
2668   unsigned Threshold = isOptSize(MF) ? SpillFuncThresholdOs
2669                                      : SpillFuncThreshold;
2670   return Threshold < NumCSI;
2671 }
2672 
2673 bool HexagonFrameLowering::useRestoreFunction(const MachineFunction &MF,
2674       const CSIVect &CSI) const {
2675   if (shouldInlineCSR(MF, CSI))
2676     return false;
2677   // The restore functions do a bit more than just restoring registers.
2678   // The non-returning versions will go back directly to the caller's
2679   // caller, others will clean up the stack frame in preparation for
2680   // a tail call. Using them can still save code size even if only one
2681   // register is getting restores. Make the decision based on -Oz:
2682   // using -Os will use inline restore for a single register.
2683   if (isMinSize(MF))
2684     return true;
2685   unsigned NumCSI = CSI.size();
2686   if (NumCSI <= 1)
2687     return false;
2688 
2689   unsigned Threshold = isOptSize(MF) ? SpillFuncThresholdOs-1
2690                                      : SpillFuncThreshold;
2691   return Threshold < NumCSI;
2692 }
2693 
2694 bool HexagonFrameLowering::mayOverflowFrameOffset(MachineFunction &MF) const {
2695   unsigned StackSize = MF.getFrameInfo().estimateStackSize(MF);
2696   auto &HST = MF.getSubtarget<HexagonSubtarget>();
2697   // A fairly simplistic guess as to whether a potential load/store to a
2698   // stack location could require an extra register.
2699   if (HST.useHVXOps() && StackSize > 256)
2700     return true;
2701 
2702   // Check if the function has store-immediate instructions that access
2703   // the stack. Since the offset field is not extendable, if the stack
2704   // size exceeds the offset limit (6 bits, shifted), the stores will
2705   // require a new base register.
2706   bool HasImmStack = false;
2707   unsigned MinLS = ~0u;   // Log_2 of the memory access size.
2708 
2709   for (const MachineBasicBlock &B : MF) {
2710     for (const MachineInstr &MI : B) {
2711       unsigned LS = 0;
2712       switch (MI.getOpcode()) {
2713         case Hexagon::S4_storeirit_io:
2714         case Hexagon::S4_storeirif_io:
2715         case Hexagon::S4_storeiri_io:
2716           ++LS;
2717           LLVM_FALLTHROUGH;
2718         case Hexagon::S4_storeirht_io:
2719         case Hexagon::S4_storeirhf_io:
2720         case Hexagon::S4_storeirh_io:
2721           ++LS;
2722           LLVM_FALLTHROUGH;
2723         case Hexagon::S4_storeirbt_io:
2724         case Hexagon::S4_storeirbf_io:
2725         case Hexagon::S4_storeirb_io:
2726           if (MI.getOperand(0).isFI())
2727             HasImmStack = true;
2728           MinLS = std::min(MinLS, LS);
2729           break;
2730       }
2731     }
2732   }
2733 
2734   if (HasImmStack)
2735     return !isUInt<6>(StackSize >> MinLS);
2736 
2737   return false;
2738 }
2739