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