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