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 "HexagonBlockRanges.h"
14 #include "HexagonFrameLowering.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> UseAllocframe("use-allocframe", cl::init(true),
182     cl::Hidden, cl::desc("Use allocframe more conservatively"));
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   DebugLoc dl;
554 
555   unsigned MaxAlign = std::max(MFI.getMaxAlignment(), getStackAlignment());
556 
557   // Calculate the total stack frame size.
558   // Get the number of bytes to allocate from the FrameInfo.
559   unsigned FrameSize = MFI.getStackSize();
560   // Round up the max call frame size to the max alignment on the stack.
561   unsigned MaxCFA = alignTo(MFI.getMaxCallFrameSize(), MaxAlign);
562   MFI.setMaxCallFrameSize(MaxCFA);
563 
564   FrameSize = MaxCFA + alignTo(FrameSize, MaxAlign);
565   MFI.setStackSize(FrameSize);
566 
567   bool AlignStack = (MaxAlign > getStackAlignment());
568 
569   // Get the number of bytes to allocate from the FrameInfo.
570   unsigned NumBytes = MFI.getStackSize();
571   unsigned SP = HRI.getStackRegister();
572   unsigned MaxCF = MFI.getMaxCallFrameSize();
573   MachineBasicBlock::iterator InsertPt = MBB.begin();
574 
575   SmallVector<MachineInstr *, 4> AdjustRegs;
576   for (auto &MBB : MF)
577     for (auto &MI : MBB)
578       if (MI.getOpcode() == Hexagon::PS_alloca)
579         AdjustRegs.push_back(&MI);
580 
581   for (auto MI : AdjustRegs) {
582     assert((MI->getOpcode() == Hexagon::PS_alloca) && "Expected alloca");
583     expandAlloca(MI, HII, SP, MaxCF);
584     MI->eraseFromParent();
585   }
586 
587   if (!hasFP(MF))
588     return;
589 
590   // Check for overflow.
591   // Hexagon_TODO: Ugh! hardcoding. Is there an API that can be used?
592   const unsigned int ALLOCFRAME_MAX = 16384;
593 
594   // Create a dummy memory operand to avoid allocframe from being treated as
595   // a volatile memory reference.
596   MachineMemOperand *MMO =
597     MF.getMachineMemOperand(MachinePointerInfo(), MachineMemOperand::MOStore,
598                             4, 4);
599 
600   if (NumBytes >= ALLOCFRAME_MAX) {
601     // Emit allocframe(#0).
602     BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::S2_allocframe))
603       .addImm(0)
604       .addMemOperand(MMO);
605 
606     // Subtract offset from frame pointer.
607     // We use a caller-saved non-parameter register for that.
608     unsigned CallerSavedReg = HRI.getFirstCallerSavedNonParamReg();
609     BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::CONST32),
610             CallerSavedReg).addImm(NumBytes);
611     BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::A2_sub), SP)
612       .addReg(SP)
613       .addReg(CallerSavedReg);
614   } else {
615     BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::S2_allocframe))
616       .addImm(NumBytes)
617       .addMemOperand(MMO);
618   }
619 
620   if (AlignStack) {
621     BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::A2_andir), SP)
622         .addReg(SP)
623         .addImm(-int64_t(MaxAlign));
624   }
625 
626   // If the stack-checking is enabled, and we spilled the callee-saved
627   // registers inline (i.e. did not use a spill function), then call
628   // the stack checker directly.
629   if (EnableStackOVFSanitizer && !PrologueStubs)
630     BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::PS_call_stk))
631            .addExternalSymbol("__runtime_stack_check");
632 }
633 
634 void HexagonFrameLowering::insertEpilogueInBlock(MachineBasicBlock &MBB) const {
635   MachineFunction &MF = *MBB.getParent();
636   if (!hasFP(MF))
637     return;
638 
639   auto &HST = MF.getSubtarget<HexagonSubtarget>();
640   auto &HII = *HST.getInstrInfo();
641   auto &HRI = *HST.getRegisterInfo();
642   unsigned SP = HRI.getStackRegister();
643 
644   MachineInstr *RetI = getReturn(MBB);
645   unsigned RetOpc = RetI ? RetI->getOpcode() : 0;
646 
647   MachineBasicBlock::iterator InsertPt = MBB.getFirstTerminator();
648   DebugLoc DL;
649   if (InsertPt != MBB.end())
650     DL = InsertPt->getDebugLoc();
651   else if (!MBB.empty())
652     DL = std::prev(MBB.end())->getDebugLoc();
653 
654   // Handle EH_RETURN.
655   if (RetOpc == Hexagon::EH_RETURN_JMPR) {
656     BuildMI(MBB, InsertPt, DL, HII.get(Hexagon::L2_deallocframe));
657     BuildMI(MBB, InsertPt, DL, HII.get(Hexagon::A2_add), SP)
658         .addReg(SP)
659         .addReg(Hexagon::R28);
660     return;
661   }
662 
663   // Check for RESTORE_DEALLOC_RET* tail call. Don't emit an extra dealloc-
664   // frame instruction if we encounter it.
665   if (RetOpc == Hexagon::RESTORE_DEALLOC_RET_JMP_V4 ||
666       RetOpc == Hexagon::RESTORE_DEALLOC_RET_JMP_V4_PIC ||
667       RetOpc == Hexagon::RESTORE_DEALLOC_RET_JMP_V4_EXT ||
668       RetOpc == Hexagon::RESTORE_DEALLOC_RET_JMP_V4_EXT_PIC) {
669     MachineBasicBlock::iterator It = RetI;
670     ++It;
671     // Delete all instructions after the RESTORE (except labels).
672     while (It != MBB.end()) {
673       if (!It->isLabel())
674         It = MBB.erase(It);
675       else
676         ++It;
677     }
678     return;
679   }
680 
681   // It is possible that the restoring code is a call to a library function.
682   // All of the restore* functions include "deallocframe", so we need to make
683   // sure that we don't add an extra one.
684   bool NeedsDeallocframe = true;
685   if (!MBB.empty() && InsertPt != MBB.begin()) {
686     MachineBasicBlock::iterator PrevIt = std::prev(InsertPt);
687     unsigned COpc = PrevIt->getOpcode();
688     if (COpc == Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4 ||
689         COpc == Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_PIC ||
690         COpc == Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_EXT ||
691         COpc == Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_EXT_PIC ||
692         COpc == Hexagon::PS_call_nr || COpc == Hexagon::PS_callr_nr)
693       NeedsDeallocframe = false;
694   }
695 
696   if (!NeedsDeallocframe)
697     return;
698   // If the returning instruction is PS_jmpret, replace it with dealloc_return,
699   // otherwise just add deallocframe. The function could be returning via a
700   // tail call.
701   if (RetOpc != Hexagon::PS_jmpret || DisableDeallocRet) {
702     BuildMI(MBB, InsertPt, DL, HII.get(Hexagon::L2_deallocframe));
703     return;
704   }
705   unsigned NewOpc = Hexagon::L4_return;
706   MachineInstr *NewI = BuildMI(MBB, RetI, DL, HII.get(NewOpc));
707   // Transfer the function live-out registers.
708   NewI->copyImplicitOps(MF, *RetI);
709   MBB.erase(RetI);
710 }
711 
712 void HexagonFrameLowering::updateEntryPaths(MachineFunction &MF,
713       MachineBasicBlock &SaveB) const {
714   SetVector<unsigned> Worklist;
715 
716   MachineBasicBlock &EntryB = MF.front();
717   Worklist.insert(EntryB.getNumber());
718 
719   unsigned SaveN = SaveB.getNumber();
720   auto &CSI = MF.getFrameInfo().getCalleeSavedInfo();
721 
722   for (unsigned i = 0; i < Worklist.size(); ++i) {
723     unsigned BN = Worklist[i];
724     MachineBasicBlock &MBB = *MF.getBlockNumbered(BN);
725     for (auto &R : CSI)
726       if (!MBB.isLiveIn(R.getReg()))
727         MBB.addLiveIn(R.getReg());
728     if (BN != SaveN)
729       for (auto &SB : MBB.successors())
730         Worklist.insert(SB->getNumber());
731   }
732 }
733 
734 bool HexagonFrameLowering::updateExitPaths(MachineBasicBlock &MBB,
735       MachineBasicBlock &RestoreB, BitVector &DoneT, BitVector &DoneF,
736       BitVector &Path) const {
737   assert(MBB.getNumber() >= 0);
738   unsigned BN = MBB.getNumber();
739   if (Path[BN] || DoneF[BN])
740     return false;
741   if (DoneT[BN])
742     return true;
743 
744   auto &CSI = MBB.getParent()->getFrameInfo().getCalleeSavedInfo();
745 
746   Path[BN] = true;
747   bool ReachedExit = false;
748   for (auto &SB : MBB.successors())
749     ReachedExit |= updateExitPaths(*SB, RestoreB, DoneT, DoneF, Path);
750 
751   if (!MBB.empty() && MBB.back().isReturn()) {
752     // Add implicit uses of all callee-saved registers to the reached
753     // return instructions. This is to prevent the anti-dependency breaker
754     // from renaming these registers.
755     MachineInstr &RetI = MBB.back();
756     if (!isRestoreCall(RetI.getOpcode()))
757       for (auto &R : CSI)
758         RetI.addOperand(MachineOperand::CreateReg(R.getReg(), false, true));
759     ReachedExit = true;
760   }
761 
762   // We don't want to add unnecessary live-ins to the restore block: since
763   // the callee-saved registers are being defined in it, the entry of the
764   // restore block cannot be on the path from the definitions to any exit.
765   if (ReachedExit && &MBB != &RestoreB) {
766     for (auto &R : CSI)
767       if (!MBB.isLiveIn(R.getReg()))
768         MBB.addLiveIn(R.getReg());
769     DoneT[BN] = true;
770   }
771   if (!ReachedExit)
772     DoneF[BN] = true;
773 
774   Path[BN] = false;
775   return ReachedExit;
776 }
777 
778 static Optional<MachineBasicBlock::iterator>
779 findCFILocation(MachineBasicBlock &B) {
780     // The CFI instructions need to be inserted right after allocframe.
781     // An exception to this is a situation where allocframe is bundled
782     // with a call: then the CFI instructions need to be inserted before
783     // the packet with the allocframe+call (in case the call throws an
784     // exception).
785     auto End = B.instr_end();
786 
787     for (MachineInstr &I : B) {
788       MachineBasicBlock::iterator It = I.getIterator();
789       if (!I.isBundle()) {
790         if (I.getOpcode() == Hexagon::S2_allocframe)
791           return std::next(It);
792         continue;
793       }
794       // I is a bundle.
795       bool HasCall = false, HasAllocFrame = false;
796       auto T = It.getInstrIterator();
797       while (++T != End && T->isBundled()) {
798         if (T->getOpcode() == Hexagon::S2_allocframe)
799           HasAllocFrame = true;
800         else if (T->isCall())
801           HasCall = true;
802       }
803       if (HasAllocFrame)
804         return HasCall ? It : std::next(It);
805     }
806     return None;
807 }
808 
809 void HexagonFrameLowering::insertCFIInstructions(MachineFunction &MF) const {
810   for (auto &B : MF) {
811     auto At = findCFILocation(B);
812     if (At.hasValue())
813       insertCFIInstructionsAt(B, At.getValue());
814   }
815 }
816 
817 void HexagonFrameLowering::insertCFIInstructionsAt(MachineBasicBlock &MBB,
818       MachineBasicBlock::iterator At) const {
819   MachineFunction &MF = *MBB.getParent();
820   MachineFrameInfo &MFI = MF.getFrameInfo();
821   MachineModuleInfo &MMI = MF.getMMI();
822   auto &HST = MF.getSubtarget<HexagonSubtarget>();
823   auto &HII = *HST.getInstrInfo();
824   auto &HRI = *HST.getRegisterInfo();
825 
826   // If CFI instructions have debug information attached, something goes
827   // wrong with the final assembly generation: the prolog_end is placed
828   // in a wrong location.
829   DebugLoc DL;
830   const MCInstrDesc &CFID = HII.get(TargetOpcode::CFI_INSTRUCTION);
831 
832   MCSymbol *FrameLabel = MMI.getContext().createTempSymbol();
833   bool HasFP = hasFP(MF);
834 
835   if (HasFP) {
836     unsigned DwFPReg = HRI.getDwarfRegNum(HRI.getFrameRegister(), true);
837     unsigned DwRAReg = HRI.getDwarfRegNum(HRI.getRARegister(), true);
838 
839     // Define CFA via an offset from the value of FP.
840     //
841     //  -8   -4    0 (SP)
842     // --+----+----+---------------------
843     //   | FP | LR |          increasing addresses -->
844     // --+----+----+---------------------
845     //   |         +-- Old SP (before allocframe)
846     //   +-- New FP (after allocframe)
847     //
848     // MCCFIInstruction::createDefCfa subtracts the offset from the register.
849     // MCCFIInstruction::createOffset takes the offset without sign change.
850     auto DefCfa = MCCFIInstruction::createDefCfa(FrameLabel, DwFPReg, -8);
851     BuildMI(MBB, At, DL, CFID)
852         .addCFIIndex(MF.addFrameInst(DefCfa));
853     // R31 (return addr) = CFA - 4
854     auto OffR31 = MCCFIInstruction::createOffset(FrameLabel, DwRAReg, -4);
855     BuildMI(MBB, At, DL, CFID)
856         .addCFIIndex(MF.addFrameInst(OffR31));
857     // R30 (frame ptr) = CFA - 8
858     auto OffR30 = MCCFIInstruction::createOffset(FrameLabel, DwFPReg, -8);
859     BuildMI(MBB, At, DL, CFID)
860         .addCFIIndex(MF.addFrameInst(OffR30));
861   }
862 
863   static unsigned int RegsToMove[] = {
864     Hexagon::R1,  Hexagon::R0,  Hexagon::R3,  Hexagon::R2,
865     Hexagon::R17, Hexagon::R16, Hexagon::R19, Hexagon::R18,
866     Hexagon::R21, Hexagon::R20, Hexagon::R23, Hexagon::R22,
867     Hexagon::R25, Hexagon::R24, Hexagon::R27, Hexagon::R26,
868     Hexagon::D0,  Hexagon::D1,  Hexagon::D8,  Hexagon::D9,
869     Hexagon::D10, Hexagon::D11, Hexagon::D12, Hexagon::D13,
870     Hexagon::NoRegister
871   };
872 
873   const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
874 
875   for (unsigned i = 0; RegsToMove[i] != Hexagon::NoRegister; ++i) {
876     unsigned Reg = RegsToMove[i];
877     auto IfR = [Reg] (const CalleeSavedInfo &C) -> bool {
878       return C.getReg() == Reg;
879     };
880     auto F = find_if(CSI, IfR);
881     if (F == CSI.end())
882       continue;
883 
884     int64_t Offset;
885     if (HasFP) {
886       // If the function has a frame pointer (i.e. has an allocframe),
887       // then the CFA has been defined in terms of FP. Any offsets in
888       // the following CFI instructions have to be defined relative
889       // to FP, which points to the bottom of the stack frame.
890       // The function getFrameIndexReference can still choose to use SP
891       // for the offset calculation, so we cannot simply call it here.
892       // Instead, get the offset (relative to the FP) directly.
893       Offset = MFI.getObjectOffset(F->getFrameIdx());
894     } else {
895       unsigned FrameReg;
896       Offset = getFrameIndexReference(MF, F->getFrameIdx(), FrameReg);
897     }
898     // Subtract 8 to make room for R30 and R31, which are added above.
899     Offset -= 8;
900 
901     if (Reg < Hexagon::D0 || Reg > Hexagon::D15) {
902       unsigned DwarfReg = HRI.getDwarfRegNum(Reg, true);
903       auto OffReg = MCCFIInstruction::createOffset(FrameLabel, DwarfReg,
904                                                    Offset);
905       BuildMI(MBB, At, DL, CFID)
906           .addCFIIndex(MF.addFrameInst(OffReg));
907     } else {
908       // Split the double regs into subregs, and generate appropriate
909       // cfi_offsets.
910       // The only reason, we are split double regs is, llvm-mc does not
911       // understand paired registers for cfi_offset.
912       // Eg .cfi_offset r1:0, -64
913 
914       unsigned HiReg = HRI.getSubReg(Reg, Hexagon::isub_hi);
915       unsigned LoReg = HRI.getSubReg(Reg, Hexagon::isub_lo);
916       unsigned HiDwarfReg = HRI.getDwarfRegNum(HiReg, true);
917       unsigned LoDwarfReg = HRI.getDwarfRegNum(LoReg, true);
918       auto OffHi = MCCFIInstruction::createOffset(FrameLabel, HiDwarfReg,
919                                                   Offset+4);
920       BuildMI(MBB, At, DL, CFID)
921           .addCFIIndex(MF.addFrameInst(OffHi));
922       auto OffLo = MCCFIInstruction::createOffset(FrameLabel, LoDwarfReg,
923                                                   Offset);
924       BuildMI(MBB, At, DL, CFID)
925           .addCFIIndex(MF.addFrameInst(OffLo));
926     }
927   }
928 }
929 
930 bool HexagonFrameLowering::hasFP(const MachineFunction &MF) const {
931   auto &MFI = MF.getFrameInfo();
932   auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
933 
934   bool HasFixed = MFI.getNumFixedObjects();
935   bool HasPrealloc = const_cast<MachineFrameInfo&>(MFI)
936                         .getLocalFrameObjectCount();
937   bool HasExtraAlign = HRI.needsStackRealignment(MF);
938   bool HasAlloca = MFI.hasVarSizedObjects();
939 
940   // Insert ALLOCFRAME if we need to or at -O0 for the debugger.  Think
941   // that this shouldn't be required, but doing so now because gcc does and
942   // gdb can't break at the start of the function without it.  Will remove if
943   // this turns out to be a gdb bug.
944   //
945   if (MF.getTarget().getOptLevel() == CodeGenOpt::None)
946     return true;
947 
948   // By default we want to use SP (since it's always there). FP requires
949   // some setup (i.e. ALLOCFRAME).
950   // Fixed and preallocated objects need FP if the distance from them to
951   // the SP is unknown (as is with alloca or aligna).
952   if ((HasFixed || HasPrealloc) && (HasAlloca || HasExtraAlign))
953     return true;
954 
955   if (MFI.getStackSize() > 0) {
956     if (EnableStackOVFSanitizer || UseAllocframe)
957       return true;
958   }
959 
960   if (MFI.hasCalls() ||
961       MF.getInfo<HexagonMachineFunctionInfo>()->hasClobberLR())
962     return true;
963 
964   return false;
965 }
966 
967 enum SpillKind {
968   SK_ToMem,
969   SK_FromMem,
970   SK_FromMemTailcall
971 };
972 
973 static const char *getSpillFunctionFor(unsigned MaxReg, SpillKind SpillType,
974       bool Stkchk = false) {
975   const char * V4SpillToMemoryFunctions[] = {
976     "__save_r16_through_r17",
977     "__save_r16_through_r19",
978     "__save_r16_through_r21",
979     "__save_r16_through_r23",
980     "__save_r16_through_r25",
981     "__save_r16_through_r27" };
982 
983   const char * V4SpillToMemoryStkchkFunctions[] = {
984     "__save_r16_through_r17_stkchk",
985     "__save_r16_through_r19_stkchk",
986     "__save_r16_through_r21_stkchk",
987     "__save_r16_through_r23_stkchk",
988     "__save_r16_through_r25_stkchk",
989     "__save_r16_through_r27_stkchk" };
990 
991   const char * V4SpillFromMemoryFunctions[] = {
992     "__restore_r16_through_r17_and_deallocframe",
993     "__restore_r16_through_r19_and_deallocframe",
994     "__restore_r16_through_r21_and_deallocframe",
995     "__restore_r16_through_r23_and_deallocframe",
996     "__restore_r16_through_r25_and_deallocframe",
997     "__restore_r16_through_r27_and_deallocframe" };
998 
999   const char * V4SpillFromMemoryTailcallFunctions[] = {
1000     "__restore_r16_through_r17_and_deallocframe_before_tailcall",
1001     "__restore_r16_through_r19_and_deallocframe_before_tailcall",
1002     "__restore_r16_through_r21_and_deallocframe_before_tailcall",
1003     "__restore_r16_through_r23_and_deallocframe_before_tailcall",
1004     "__restore_r16_through_r25_and_deallocframe_before_tailcall",
1005     "__restore_r16_through_r27_and_deallocframe_before_tailcall"
1006   };
1007 
1008   const char **SpillFunc = nullptr;
1009 
1010   switch(SpillType) {
1011   case SK_ToMem:
1012     SpillFunc = Stkchk ? V4SpillToMemoryStkchkFunctions
1013                        : V4SpillToMemoryFunctions;
1014     break;
1015   case SK_FromMem:
1016     SpillFunc = V4SpillFromMemoryFunctions;
1017     break;
1018   case SK_FromMemTailcall:
1019     SpillFunc = V4SpillFromMemoryTailcallFunctions;
1020     break;
1021   }
1022   assert(SpillFunc && "Unknown spill kind");
1023 
1024   // Spill all callee-saved registers up to the highest register used.
1025   switch (MaxReg) {
1026   case Hexagon::R17:
1027     return SpillFunc[0];
1028   case Hexagon::R19:
1029     return SpillFunc[1];
1030   case Hexagon::R21:
1031     return SpillFunc[2];
1032   case Hexagon::R23:
1033     return SpillFunc[3];
1034   case Hexagon::R25:
1035     return SpillFunc[4];
1036   case Hexagon::R27:
1037     return SpillFunc[5];
1038   default:
1039     llvm_unreachable("Unhandled maximum callee save register");
1040   }
1041   return nullptr;
1042 }
1043 
1044 int HexagonFrameLowering::getFrameIndexReference(const MachineFunction &MF,
1045       int FI, unsigned &FrameReg) const {
1046   auto &MFI = MF.getFrameInfo();
1047   auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
1048 
1049   int Offset = MFI.getObjectOffset(FI);
1050   bool HasAlloca = MFI.hasVarSizedObjects();
1051   bool HasExtraAlign = HRI.needsStackRealignment(MF);
1052   bool NoOpt = MF.getTarget().getOptLevel() == CodeGenOpt::None;
1053 
1054   unsigned SP = HRI.getStackRegister(), FP = HRI.getFrameRegister();
1055   auto &HMFI = *MF.getInfo<HexagonMachineFunctionInfo>();
1056   unsigned AP = HMFI.getStackAlignBasePhysReg();
1057   unsigned FrameSize = MFI.getStackSize();
1058 
1059   bool UseFP = false, UseAP = false;  // Default: use SP (except at -O0).
1060   // Use FP at -O0, except when there are objects with extra alignment.
1061   // That additional alignment requirement may cause a pad to be inserted,
1062   // which will make it impossible to use FP to access objects located
1063   // past the pad.
1064   if (NoOpt && !HasExtraAlign)
1065     UseFP = true;
1066   if (MFI.isFixedObjectIndex(FI) || MFI.isObjectPreAllocated(FI)) {
1067     // Fixed and preallocated objects will be located before any padding
1068     // so FP must be used to access them.
1069     UseFP |= (HasAlloca || HasExtraAlign);
1070   } else {
1071     if (HasAlloca) {
1072       if (HasExtraAlign)
1073         UseAP = true;
1074       else
1075         UseFP = true;
1076     }
1077   }
1078 
1079   // If FP was picked, then there had better be FP.
1080   bool HasFP = hasFP(MF);
1081   assert((HasFP || !UseFP) && "This function must have frame pointer");
1082 
1083   // Having FP implies allocframe. Allocframe will store extra 8 bytes:
1084   // FP/LR. If the base register is used to access an object across these
1085   // 8 bytes, then the offset will need to be adjusted by 8.
1086   //
1087   // After allocframe:
1088   //                    HexagonISelLowering adds 8 to ---+
1089   //                    the offsets of all stack-based   |
1090   //                    arguments (*)                    |
1091   //                                                     |
1092   //   getObjectOffset < 0   0     8  getObjectOffset >= 8
1093   // ------------------------+-----+------------------------> increasing
1094   //     <local objects>     |FP/LR|    <input arguments>     addresses
1095   // -----------------+------+-----+------------------------>
1096   //                  |      |
1097   //    SP/AP point --+      +-- FP points here (**)
1098   //    somewhere on
1099   //    this side of FP/LR
1100   //
1101   // (*) See LowerFormalArguments. The FP/LR is assumed to be present.
1102   // (**) *FP == old-FP. FP+0..7 are the bytes of FP/LR.
1103 
1104   // The lowering assumes that FP/LR is present, and so the offsets of
1105   // the formal arguments start at 8. If FP/LR is not there we need to
1106   // reduce the offset by 8.
1107   if (Offset > 0 && !HasFP)
1108     Offset -= 8;
1109 
1110   if (UseFP)
1111     FrameReg = FP;
1112   else if (UseAP)
1113     FrameReg = AP;
1114   else
1115     FrameReg = SP;
1116 
1117   // Calculate the actual offset in the instruction. If there is no FP
1118   // (in other words, no allocframe), then SP will not be adjusted (i.e.
1119   // there will be no SP -= FrameSize), so the frame size should not be
1120   // added to the calculated offset.
1121   int RealOffset = Offset;
1122   if (!UseFP && !UseAP && HasFP)
1123     RealOffset = FrameSize+Offset;
1124   return RealOffset;
1125 }
1126 
1127 bool HexagonFrameLowering::insertCSRSpillsInBlock(MachineBasicBlock &MBB,
1128       const CSIVect &CSI, const HexagonRegisterInfo &HRI,
1129       bool &PrologueStubs) const {
1130   if (CSI.empty())
1131     return true;
1132 
1133   MachineBasicBlock::iterator MI = MBB.begin();
1134   PrologueStubs = false;
1135   MachineFunction &MF = *MBB.getParent();
1136   auto &HST = MF.getSubtarget<HexagonSubtarget>();
1137   auto &HII = *HST.getInstrInfo();
1138 
1139   if (useSpillFunction(MF, CSI)) {
1140     PrologueStubs = true;
1141     unsigned MaxReg = getMaxCalleeSavedReg(CSI, HRI);
1142     bool StkOvrFlowEnabled = EnableStackOVFSanitizer;
1143     const char *SpillFun = getSpillFunctionFor(MaxReg, SK_ToMem,
1144                                                StkOvrFlowEnabled);
1145     auto &HTM = static_cast<const HexagonTargetMachine&>(MF.getTarget());
1146     bool IsPIC = HTM.isPositionIndependent();
1147     bool LongCalls = HST.useLongCalls() || EnableSaveRestoreLong;
1148 
1149     // Call spill function.
1150     DebugLoc DL = MI != MBB.end() ? MI->getDebugLoc() : DebugLoc();
1151     unsigned SpillOpc;
1152     if (StkOvrFlowEnabled) {
1153       if (LongCalls)
1154         SpillOpc = IsPIC ? Hexagon::SAVE_REGISTERS_CALL_V4STK_EXT_PIC
1155                          : Hexagon::SAVE_REGISTERS_CALL_V4STK_EXT;
1156       else
1157         SpillOpc = IsPIC ? Hexagon::SAVE_REGISTERS_CALL_V4STK_PIC
1158                          : Hexagon::SAVE_REGISTERS_CALL_V4STK;
1159     } else {
1160       if (LongCalls)
1161         SpillOpc = IsPIC ? Hexagon::SAVE_REGISTERS_CALL_V4_EXT_PIC
1162                          : Hexagon::SAVE_REGISTERS_CALL_V4_EXT;
1163       else
1164         SpillOpc = IsPIC ? Hexagon::SAVE_REGISTERS_CALL_V4_PIC
1165                          : Hexagon::SAVE_REGISTERS_CALL_V4;
1166     }
1167 
1168     MachineInstr *SaveRegsCall =
1169         BuildMI(MBB, MI, DL, HII.get(SpillOpc))
1170           .addExternalSymbol(SpillFun);
1171 
1172     // Add callee-saved registers as use.
1173     addCalleeSaveRegistersAsImpOperand(SaveRegsCall, CSI, false, true);
1174     // Add live in registers.
1175     for (unsigned I = 0; I < CSI.size(); ++I)
1176       MBB.addLiveIn(CSI[I].getReg());
1177     return true;
1178   }
1179 
1180   for (unsigned i = 0, n = CSI.size(); i < n; ++i) {
1181     unsigned Reg = CSI[i].getReg();
1182     // Add live in registers. We treat eh_return callee saved register r0 - r3
1183     // specially. They are not really callee saved registers as they are not
1184     // supposed to be killed.
1185     bool IsKill = !HRI.isEHReturnCalleeSaveReg(Reg);
1186     int FI = CSI[i].getFrameIdx();
1187     const TargetRegisterClass *RC = HRI.getMinimalPhysRegClass(Reg);
1188     HII.storeRegToStackSlot(MBB, MI, Reg, IsKill, FI, RC, &HRI);
1189     if (IsKill)
1190       MBB.addLiveIn(Reg);
1191   }
1192   return true;
1193 }
1194 
1195 bool HexagonFrameLowering::insertCSRRestoresInBlock(MachineBasicBlock &MBB,
1196       const CSIVect &CSI, const HexagonRegisterInfo &HRI) const {
1197   if (CSI.empty())
1198     return false;
1199 
1200   MachineBasicBlock::iterator MI = MBB.getFirstTerminator();
1201   MachineFunction &MF = *MBB.getParent();
1202   auto &HST = MF.getSubtarget<HexagonSubtarget>();
1203   auto &HII = *HST.getInstrInfo();
1204 
1205   if (useRestoreFunction(MF, CSI)) {
1206     bool HasTC = hasTailCall(MBB) || !hasReturn(MBB);
1207     unsigned MaxR = getMaxCalleeSavedReg(CSI, HRI);
1208     SpillKind Kind = HasTC ? SK_FromMemTailcall : SK_FromMem;
1209     const char *RestoreFn = getSpillFunctionFor(MaxR, Kind);
1210     auto &HTM = static_cast<const HexagonTargetMachine&>(MF.getTarget());
1211     bool IsPIC = HTM.isPositionIndependent();
1212     bool LongCalls = HST.useLongCalls() || EnableSaveRestoreLong;
1213 
1214     // Call spill function.
1215     DebugLoc DL = MI != MBB.end() ? MI->getDebugLoc()
1216                                   : MBB.getLastNonDebugInstr()->getDebugLoc();
1217     MachineInstr *DeallocCall = nullptr;
1218 
1219     if (HasTC) {
1220       unsigned RetOpc;
1221       if (LongCalls)
1222         RetOpc = IsPIC ? Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_EXT_PIC
1223                        : Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_EXT;
1224       else
1225         RetOpc = IsPIC ? Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_PIC
1226                        : Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4;
1227       DeallocCall = BuildMI(MBB, MI, DL, HII.get(RetOpc))
1228           .addExternalSymbol(RestoreFn);
1229     } else {
1230       // The block has a return.
1231       MachineBasicBlock::iterator It = MBB.getFirstTerminator();
1232       assert(It->isReturn() && std::next(It) == MBB.end());
1233       unsigned RetOpc;
1234       if (LongCalls)
1235         RetOpc = IsPIC ? Hexagon::RESTORE_DEALLOC_RET_JMP_V4_EXT_PIC
1236                        : Hexagon::RESTORE_DEALLOC_RET_JMP_V4_EXT;
1237       else
1238         RetOpc = IsPIC ? Hexagon::RESTORE_DEALLOC_RET_JMP_V4_PIC
1239                        : Hexagon::RESTORE_DEALLOC_RET_JMP_V4;
1240       DeallocCall = BuildMI(MBB, It, DL, HII.get(RetOpc))
1241           .addExternalSymbol(RestoreFn);
1242       // Transfer the function live-out registers.
1243       DeallocCall->copyImplicitOps(MF, *It);
1244     }
1245     addCalleeSaveRegistersAsImpOperand(DeallocCall, CSI, true, false);
1246     return true;
1247   }
1248 
1249   for (unsigned i = 0; i < CSI.size(); ++i) {
1250     unsigned Reg = CSI[i].getReg();
1251     const TargetRegisterClass *RC = HRI.getMinimalPhysRegClass(Reg);
1252     int FI = CSI[i].getFrameIdx();
1253     HII.loadRegFromStackSlot(MBB, MI, Reg, FI, RC, &HRI);
1254   }
1255 
1256   return true;
1257 }
1258 
1259 MachineBasicBlock::iterator HexagonFrameLowering::eliminateCallFramePseudoInstr(
1260     MachineFunction &MF, MachineBasicBlock &MBB,
1261     MachineBasicBlock::iterator I) const {
1262   MachineInstr &MI = *I;
1263   unsigned Opc = MI.getOpcode();
1264   (void)Opc; // Silence compiler warning.
1265   assert((Opc == Hexagon::ADJCALLSTACKDOWN || Opc == Hexagon::ADJCALLSTACKUP) &&
1266          "Cannot handle this call frame pseudo instruction");
1267   return MBB.erase(I);
1268 }
1269 
1270 void HexagonFrameLowering::processFunctionBeforeFrameFinalized(
1271     MachineFunction &MF, RegScavenger *RS) const {
1272   // If this function has uses aligned stack and also has variable sized stack
1273   // objects, then we need to map all spill slots to fixed positions, so that
1274   // they can be accessed through FP. Otherwise they would have to be accessed
1275   // via AP, which may not be available at the particular place in the program.
1276   MachineFrameInfo &MFI = MF.getFrameInfo();
1277   bool HasAlloca = MFI.hasVarSizedObjects();
1278   bool NeedsAlign = (MFI.getMaxAlignment() > getStackAlignment());
1279 
1280   if (!HasAlloca || !NeedsAlign)
1281     return;
1282 
1283   unsigned LFS = MFI.getLocalFrameSize();
1284   for (int i = 0, e = MFI.getObjectIndexEnd(); i != e; ++i) {
1285     if (!MFI.isSpillSlotObjectIndex(i) || MFI.isDeadObjectIndex(i))
1286       continue;
1287     unsigned S = MFI.getObjectSize(i);
1288     // Reduce the alignment to at most 8. This will require unaligned vector
1289     // stores if they happen here.
1290     unsigned A = std::max(MFI.getObjectAlignment(i), 8U);
1291     MFI.setObjectAlignment(i, 8);
1292     LFS = alignTo(LFS+S, A);
1293     MFI.mapLocalFrameObject(i, -LFS);
1294   }
1295 
1296   MFI.setLocalFrameSize(LFS);
1297   unsigned A = MFI.getLocalFrameMaxAlign();
1298   assert(A <= 8 && "Unexpected local frame alignment");
1299   if (A == 0)
1300     MFI.setLocalFrameMaxAlign(8);
1301   MFI.setUseLocalStackAllocationBlock(true);
1302 
1303   // Set the physical aligned-stack base address register.
1304   unsigned AP = 0;
1305   if (const MachineInstr *AI = getAlignaInstr(MF))
1306     AP = AI->getOperand(0).getReg();
1307   auto &HMFI = *MF.getInfo<HexagonMachineFunctionInfo>();
1308   HMFI.setStackAlignBasePhysReg(AP);
1309 }
1310 
1311 /// Returns true if there are no caller-saved registers available in class RC.
1312 static bool needToReserveScavengingSpillSlots(MachineFunction &MF,
1313       const HexagonRegisterInfo &HRI, const TargetRegisterClass *RC) {
1314   MachineRegisterInfo &MRI = MF.getRegInfo();
1315 
1316   auto IsUsed = [&HRI,&MRI] (unsigned Reg) -> bool {
1317     for (MCRegAliasIterator AI(Reg, &HRI, true); AI.isValid(); ++AI)
1318       if (MRI.isPhysRegUsed(*AI))
1319         return true;
1320     return false;
1321   };
1322 
1323   // Check for an unused caller-saved register. Callee-saved registers
1324   // have become pristine by now.
1325   for (const MCPhysReg *P = HRI.getCallerSavedRegs(&MF, RC); *P; ++P)
1326     if (!IsUsed(*P))
1327       return false;
1328 
1329   // All caller-saved registers are used.
1330   return true;
1331 }
1332 
1333 #ifndef NDEBUG
1334 static void dump_registers(BitVector &Regs, const TargetRegisterInfo &TRI) {
1335   dbgs() << '{';
1336   for (int x = Regs.find_first(); x >= 0; x = Regs.find_next(x)) {
1337     unsigned R = x;
1338     dbgs() << ' ' << PrintReg(R, &TRI);
1339   }
1340   dbgs() << " }";
1341 }
1342 #endif
1343 
1344 bool HexagonFrameLowering::assignCalleeSavedSpillSlots(MachineFunction &MF,
1345       const TargetRegisterInfo *TRI, std::vector<CalleeSavedInfo> &CSI) const {
1346   DEBUG(dbgs() << __func__ << " on "
1347                << MF.getFunction()->getName() << '\n');
1348   MachineFrameInfo &MFI = MF.getFrameInfo();
1349   BitVector SRegs(Hexagon::NUM_TARGET_REGS);
1350 
1351   // Generate a set of unique, callee-saved registers (SRegs), where each
1352   // register in the set is maximal in terms of sub-/super-register relation,
1353   // i.e. for each R in SRegs, no proper super-register of R is also in SRegs.
1354 
1355   // (1) For each callee-saved register, add that register and all of its
1356   // sub-registers to SRegs.
1357   DEBUG(dbgs() << "Initial CS registers: {");
1358   for (unsigned i = 0, n = CSI.size(); i < n; ++i) {
1359     unsigned R = CSI[i].getReg();
1360     DEBUG(dbgs() << ' ' << PrintReg(R, TRI));
1361     for (MCSubRegIterator SR(R, TRI, true); SR.isValid(); ++SR)
1362       SRegs[*SR] = true;
1363   }
1364   DEBUG(dbgs() << " }\n");
1365   DEBUG(dbgs() << "SRegs.1: "; dump_registers(SRegs, *TRI); dbgs() << "\n");
1366 
1367   // (2) For each reserved register, remove that register and all of its
1368   // sub- and super-registers from SRegs.
1369   BitVector Reserved = TRI->getReservedRegs(MF);
1370   for (int x = Reserved.find_first(); x >= 0; x = Reserved.find_next(x)) {
1371     unsigned R = x;
1372     for (MCSuperRegIterator SR(R, TRI, true); SR.isValid(); ++SR)
1373       SRegs[*SR] = false;
1374   }
1375   DEBUG(dbgs() << "Res:     "; dump_registers(Reserved, *TRI); dbgs() << "\n");
1376   DEBUG(dbgs() << "SRegs.2: "; dump_registers(SRegs, *TRI); dbgs() << "\n");
1377 
1378   // (3) Collect all registers that have at least one sub-register in SRegs,
1379   // and also have no sub-registers that are reserved. These will be the can-
1380   // didates for saving as a whole instead of their individual sub-registers.
1381   // (Saving R17:16 instead of R16 is fine, but only if R17 was not reserved.)
1382   BitVector TmpSup(Hexagon::NUM_TARGET_REGS);
1383   for (int x = SRegs.find_first(); x >= 0; x = SRegs.find_next(x)) {
1384     unsigned R = x;
1385     for (MCSuperRegIterator SR(R, TRI); SR.isValid(); ++SR)
1386       TmpSup[*SR] = true;
1387   }
1388   for (int x = TmpSup.find_first(); x >= 0; x = TmpSup.find_next(x)) {
1389     unsigned R = x;
1390     for (MCSubRegIterator SR(R, TRI, true); SR.isValid(); ++SR) {
1391       if (!Reserved[*SR])
1392         continue;
1393       TmpSup[R] = false;
1394       break;
1395     }
1396   }
1397   DEBUG(dbgs() << "TmpSup:  "; dump_registers(TmpSup, *TRI); dbgs() << "\n");
1398 
1399   // (4) Include all super-registers found in (3) into SRegs.
1400   SRegs |= TmpSup;
1401   DEBUG(dbgs() << "SRegs.4: "; dump_registers(SRegs, *TRI); dbgs() << "\n");
1402 
1403   // (5) For each register R in SRegs, if any super-register of R is in SRegs,
1404   // remove R from SRegs.
1405   for (int x = SRegs.find_first(); x >= 0; x = SRegs.find_next(x)) {
1406     unsigned R = x;
1407     for (MCSuperRegIterator SR(R, TRI); SR.isValid(); ++SR) {
1408       if (!SRegs[*SR])
1409         continue;
1410       SRegs[R] = false;
1411       break;
1412     }
1413   }
1414   DEBUG(dbgs() << "SRegs.5: "; dump_registers(SRegs, *TRI); dbgs() << "\n");
1415 
1416   // Now, for each register that has a fixed stack slot, create the stack
1417   // object for it.
1418   CSI.clear();
1419 
1420   typedef TargetFrameLowering::SpillSlot SpillSlot;
1421   unsigned NumFixed;
1422   int MinOffset = 0;  // CS offsets are negative.
1423   const SpillSlot *FixedSlots = getCalleeSavedSpillSlots(NumFixed);
1424   for (const SpillSlot *S = FixedSlots; S != FixedSlots+NumFixed; ++S) {
1425     if (!SRegs[S->Reg])
1426       continue;
1427     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(S->Reg);
1428     int FI = MFI.CreateFixedSpillStackObject(RC->getSize(), S->Offset);
1429     MinOffset = std::min(MinOffset, S->Offset);
1430     CSI.push_back(CalleeSavedInfo(S->Reg, FI));
1431     SRegs[S->Reg] = false;
1432   }
1433 
1434   // There can be some registers that don't have fixed slots. For example,
1435   // we need to store R0-R3 in functions with exception handling. For each
1436   // such register, create a non-fixed stack object.
1437   for (int x = SRegs.find_first(); x >= 0; x = SRegs.find_next(x)) {
1438     unsigned R = x;
1439     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(R);
1440     int Off = MinOffset - RC->getSize();
1441     unsigned Align = std::min(RC->getAlignment(), getStackAlignment());
1442     assert(isPowerOf2_32(Align));
1443     Off &= -Align;
1444     int FI = MFI.CreateFixedSpillStackObject(RC->getSize(), Off);
1445     MinOffset = std::min(MinOffset, Off);
1446     CSI.push_back(CalleeSavedInfo(R, FI));
1447     SRegs[R] = false;
1448   }
1449 
1450   DEBUG({
1451     dbgs() << "CS information: {";
1452     for (unsigned i = 0, n = CSI.size(); i < n; ++i) {
1453       int FI = CSI[i].getFrameIdx();
1454       int Off = MFI.getObjectOffset(FI);
1455       dbgs() << ' ' << PrintReg(CSI[i].getReg(), TRI) << ":fi#" << FI << ":sp";
1456       if (Off >= 0)
1457         dbgs() << '+';
1458       dbgs() << Off;
1459     }
1460     dbgs() << " }\n";
1461   });
1462 
1463 #ifndef NDEBUG
1464   // Verify that all registers were handled.
1465   bool MissedReg = false;
1466   for (int x = SRegs.find_first(); x >= 0; x = SRegs.find_next(x)) {
1467     unsigned R = x;
1468     dbgs() << PrintReg(R, TRI) << ' ';
1469     MissedReg = true;
1470   }
1471   if (MissedReg)
1472     llvm_unreachable("...there are unhandled callee-saved registers!");
1473 #endif
1474 
1475   return true;
1476 }
1477 
1478 bool HexagonFrameLowering::expandCopy(MachineBasicBlock &B,
1479       MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1480       const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1481   MachineInstr *MI = &*It;
1482   DebugLoc DL = MI->getDebugLoc();
1483   unsigned DstR = MI->getOperand(0).getReg();
1484   unsigned SrcR = MI->getOperand(1).getReg();
1485   if (!Hexagon::ModRegsRegClass.contains(DstR) ||
1486       !Hexagon::ModRegsRegClass.contains(SrcR))
1487     return false;
1488 
1489   unsigned TmpR = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
1490   BuildMI(B, It, DL, HII.get(TargetOpcode::COPY), TmpR).add(MI->getOperand(1));
1491   BuildMI(B, It, DL, HII.get(TargetOpcode::COPY), DstR)
1492     .addReg(TmpR, RegState::Kill);
1493 
1494   NewRegs.push_back(TmpR);
1495   B.erase(It);
1496   return true;
1497 }
1498 
1499 bool HexagonFrameLowering::expandStoreInt(MachineBasicBlock &B,
1500       MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1501       const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1502   MachineInstr *MI = &*It;
1503   if (!MI->getOperand(0).isFI())
1504     return false;
1505 
1506   DebugLoc DL = MI->getDebugLoc();
1507   unsigned Opc = MI->getOpcode();
1508   unsigned SrcR = MI->getOperand(2).getReg();
1509   bool IsKill = MI->getOperand(2).isKill();
1510   int FI = MI->getOperand(0).getIndex();
1511 
1512   // TmpR = C2_tfrpr SrcR   if SrcR is a predicate register
1513   // TmpR = A2_tfrcrr SrcR  if SrcR is a modifier register
1514   unsigned TmpR = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
1515   unsigned TfrOpc = (Opc == Hexagon::STriw_pred) ? Hexagon::C2_tfrpr
1516                                                  : Hexagon::A2_tfrcrr;
1517   BuildMI(B, It, DL, HII.get(TfrOpc), TmpR)
1518     .addReg(SrcR, getKillRegState(IsKill));
1519 
1520   // S2_storeri_io FI, 0, TmpR
1521   BuildMI(B, It, DL, HII.get(Hexagon::S2_storeri_io))
1522     .addFrameIndex(FI)
1523     .addImm(0)
1524     .addReg(TmpR, RegState::Kill)
1525     .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1526 
1527   NewRegs.push_back(TmpR);
1528   B.erase(It);
1529   return true;
1530 }
1531 
1532 bool HexagonFrameLowering::expandLoadInt(MachineBasicBlock &B,
1533       MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1534       const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1535   MachineInstr *MI = &*It;
1536   if (!MI->getOperand(1).isFI())
1537     return false;
1538 
1539   DebugLoc DL = MI->getDebugLoc();
1540   unsigned Opc = MI->getOpcode();
1541   unsigned DstR = MI->getOperand(0).getReg();
1542   int FI = MI->getOperand(1).getIndex();
1543 
1544   // TmpR = L2_loadri_io FI, 0
1545   unsigned TmpR = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
1546   BuildMI(B, It, DL, HII.get(Hexagon::L2_loadri_io), TmpR)
1547     .addFrameIndex(FI)
1548     .addImm(0)
1549     .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1550 
1551   // DstR = C2_tfrrp TmpR   if DstR is a predicate register
1552   // DstR = A2_tfrrcr TmpR  if DstR is a modifier register
1553   unsigned TfrOpc = (Opc == Hexagon::LDriw_pred) ? Hexagon::C2_tfrrp
1554                                                  : Hexagon::A2_tfrrcr;
1555   BuildMI(B, It, DL, HII.get(TfrOpc), DstR)
1556     .addReg(TmpR, RegState::Kill);
1557 
1558   NewRegs.push_back(TmpR);
1559   B.erase(It);
1560   return true;
1561 }
1562 
1563 bool HexagonFrameLowering::expandStoreVecPred(MachineBasicBlock &B,
1564       MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1565       const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1566   auto &HST = B.getParent()->getSubtarget<HexagonSubtarget>();
1567   MachineInstr *MI = &*It;
1568   if (!MI->getOperand(0).isFI())
1569     return false;
1570 
1571   DebugLoc DL = MI->getDebugLoc();
1572   unsigned SrcR = MI->getOperand(2).getReg();
1573   bool IsKill = MI->getOperand(2).isKill();
1574   int FI = MI->getOperand(0).getIndex();
1575 
1576   bool Is128B = HST.useHVXDblOps();
1577   auto *RC = !Is128B ? &Hexagon::VectorRegsRegClass
1578                      : &Hexagon::VectorRegs128BRegClass;
1579 
1580   // Insert transfer to general vector register.
1581   //   TmpR0 = A2_tfrsi 0x01010101
1582   //   TmpR1 = V6_vandqrt Qx, TmpR0
1583   //   store FI, 0, TmpR1
1584   unsigned TmpR0 = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
1585   unsigned TmpR1 = MRI.createVirtualRegister(RC);
1586 
1587   BuildMI(B, It, DL, HII.get(Hexagon::A2_tfrsi), TmpR0)
1588     .addImm(0x01010101);
1589 
1590   unsigned VandOpc = !Is128B ? Hexagon::V6_vandqrt : Hexagon::V6_vandqrt_128B;
1591   BuildMI(B, It, DL, HII.get(VandOpc), TmpR1)
1592     .addReg(SrcR, getKillRegState(IsKill))
1593     .addReg(TmpR0, RegState::Kill);
1594 
1595   auto *HRI = B.getParent()->getSubtarget<HexagonSubtarget>().getRegisterInfo();
1596   HII.storeRegToStackSlot(B, It, TmpR1, true, FI, RC, HRI);
1597   expandStoreVec(B, std::prev(It), MRI, HII, NewRegs);
1598 
1599   NewRegs.push_back(TmpR0);
1600   NewRegs.push_back(TmpR1);
1601   B.erase(It);
1602   return true;
1603 }
1604 
1605 bool HexagonFrameLowering::expandLoadVecPred(MachineBasicBlock &B,
1606       MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1607       const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1608   auto &HST = B.getParent()->getSubtarget<HexagonSubtarget>();
1609   MachineInstr *MI = &*It;
1610   if (!MI->getOperand(1).isFI())
1611     return false;
1612 
1613   DebugLoc DL = MI->getDebugLoc();
1614   unsigned DstR = MI->getOperand(0).getReg();
1615   int FI = MI->getOperand(1).getIndex();
1616 
1617   bool Is128B = HST.useHVXDblOps();
1618   auto *RC = !Is128B ? &Hexagon::VectorRegsRegClass
1619                      : &Hexagon::VectorRegs128BRegClass;
1620 
1621   // TmpR0 = A2_tfrsi 0x01010101
1622   // TmpR1 = load FI, 0
1623   // DstR = V6_vandvrt TmpR1, TmpR0
1624   unsigned TmpR0 = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
1625   unsigned TmpR1 = MRI.createVirtualRegister(RC);
1626 
1627   BuildMI(B, It, DL, HII.get(Hexagon::A2_tfrsi), TmpR0)
1628     .addImm(0x01010101);
1629   auto *HRI = B.getParent()->getSubtarget<HexagonSubtarget>().getRegisterInfo();
1630   HII.loadRegFromStackSlot(B, It, TmpR1, FI, RC, HRI);
1631   expandLoadVec(B, std::prev(It), MRI, HII, NewRegs);
1632 
1633   unsigned VandOpc = !Is128B ? Hexagon::V6_vandvrt : Hexagon::V6_vandvrt_128B;
1634   BuildMI(B, It, DL, HII.get(VandOpc), DstR)
1635     .addReg(TmpR1, RegState::Kill)
1636     .addReg(TmpR0, RegState::Kill);
1637 
1638   NewRegs.push_back(TmpR0);
1639   NewRegs.push_back(TmpR1);
1640   B.erase(It);
1641   return true;
1642 }
1643 
1644 bool HexagonFrameLowering::expandStoreVec2(MachineBasicBlock &B,
1645       MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1646       const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1647   MachineFunction &MF = *B.getParent();
1648   auto &HST = MF.getSubtarget<HexagonSubtarget>();
1649   auto &MFI = MF.getFrameInfo();
1650   auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
1651   MachineInstr *MI = &*It;
1652   if (!MI->getOperand(0).isFI())
1653     return false;
1654 
1655   // It is possible that the double vector being stored is only partially
1656   // defined. From the point of view of the liveness tracking, it is ok to
1657   // store it as a whole, but if we break it up we may end up storing a
1658   // register that is entirely undefined.
1659   LivePhysRegs LPR(&HRI);
1660   LPR.addLiveIns(B);
1661   SmallVector<std::pair<unsigned, const MachineOperand*>,2> Clobbers;
1662   for (auto R = B.begin(); R != It; ++R) {
1663     Clobbers.clear();
1664     LPR.stepForward(*R, Clobbers);
1665     // Dead defs are recorded in Clobbers, but are not automatically removed
1666     // from the live set.
1667     for (auto &C : Clobbers)
1668       if (C.second->isReg() && C.second->isDead())
1669         LPR.removeReg(C.first);
1670   }
1671 
1672   DebugLoc DL = MI->getDebugLoc();
1673   unsigned SrcR = MI->getOperand(2).getReg();
1674   unsigned SrcLo = HRI.getSubReg(SrcR, Hexagon::vsub_lo);
1675   unsigned SrcHi = HRI.getSubReg(SrcR, Hexagon::vsub_hi);
1676   bool IsKill = MI->getOperand(2).isKill();
1677   int FI = MI->getOperand(0).getIndex();
1678 
1679   bool Is128B = HST.useHVXDblOps();
1680   auto *RC = !Is128B ? &Hexagon::VectorRegsRegClass
1681                      : &Hexagon::VectorRegs128BRegClass;
1682   unsigned Size = RC->getSize();
1683   unsigned NeedAlign = RC->getAlignment();
1684   unsigned HasAlign = MFI.getObjectAlignment(FI);
1685   unsigned StoreOpc;
1686 
1687   // Store low part.
1688   if (LPR.contains(SrcLo)) {
1689     if (NeedAlign <= HasAlign)
1690       StoreOpc = !Is128B ? Hexagon::V6_vS32b_ai  : Hexagon::V6_vS32b_ai_128B;
1691     else
1692       StoreOpc = !Is128B ? Hexagon::V6_vS32Ub_ai : Hexagon::V6_vS32Ub_ai_128B;
1693 
1694     BuildMI(B, It, DL, HII.get(StoreOpc))
1695       .addFrameIndex(FI)
1696       .addImm(0)
1697       .addReg(SrcLo, getKillRegState(IsKill))
1698       .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1699   }
1700 
1701   // Store high part.
1702   if (LPR.contains(SrcHi)) {
1703     if (NeedAlign <= MinAlign(HasAlign, Size))
1704       StoreOpc = !Is128B ? Hexagon::V6_vS32b_ai  : Hexagon::V6_vS32b_ai_128B;
1705     else
1706       StoreOpc = !Is128B ? Hexagon::V6_vS32Ub_ai : Hexagon::V6_vS32Ub_ai_128B;
1707 
1708     BuildMI(B, It, DL, HII.get(StoreOpc))
1709       .addFrameIndex(FI)
1710       .addImm(Size)
1711       .addReg(SrcHi, getKillRegState(IsKill))
1712       .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1713   }
1714 
1715   B.erase(It);
1716   return true;
1717 }
1718 
1719 bool HexagonFrameLowering::expandLoadVec2(MachineBasicBlock &B,
1720       MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1721       const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1722   MachineFunction &MF = *B.getParent();
1723   auto &HST = MF.getSubtarget<HexagonSubtarget>();
1724   auto &MFI = MF.getFrameInfo();
1725   auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
1726   MachineInstr *MI = &*It;
1727   if (!MI->getOperand(1).isFI())
1728     return false;
1729 
1730   DebugLoc DL = MI->getDebugLoc();
1731   unsigned DstR = MI->getOperand(0).getReg();
1732   unsigned DstHi = HRI.getSubReg(DstR, Hexagon::vsub_hi);
1733   unsigned DstLo = HRI.getSubReg(DstR, Hexagon::vsub_lo);
1734   int FI = MI->getOperand(1).getIndex();
1735 
1736   bool Is128B = HST.useHVXDblOps();
1737   auto *RC = !Is128B ? &Hexagon::VectorRegsRegClass
1738                      : &Hexagon::VectorRegs128BRegClass;
1739   unsigned Size = RC->getSize();
1740   unsigned NeedAlign = RC->getAlignment();
1741   unsigned HasAlign = MFI.getObjectAlignment(FI);
1742   unsigned LoadOpc;
1743 
1744   // Load low part.
1745   if (NeedAlign <= HasAlign)
1746     LoadOpc = !Is128B ? Hexagon::V6_vL32b_ai  : Hexagon::V6_vL32b_ai_128B;
1747   else
1748     LoadOpc = !Is128B ? Hexagon::V6_vL32Ub_ai : Hexagon::V6_vL32Ub_ai_128B;
1749 
1750   BuildMI(B, It, DL, HII.get(LoadOpc), DstLo)
1751     .addFrameIndex(FI)
1752     .addImm(0)
1753     .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1754 
1755   // Load high part.
1756   if (NeedAlign <= MinAlign(HasAlign, Size))
1757     LoadOpc = !Is128B ? Hexagon::V6_vL32b_ai  : Hexagon::V6_vL32b_ai_128B;
1758   else
1759     LoadOpc = !Is128B ? Hexagon::V6_vL32Ub_ai : Hexagon::V6_vL32Ub_ai_128B;
1760 
1761   BuildMI(B, It, DL, HII.get(LoadOpc), DstHi)
1762     .addFrameIndex(FI)
1763     .addImm(Size)
1764     .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1765 
1766   B.erase(It);
1767   return true;
1768 }
1769 
1770 bool HexagonFrameLowering::expandStoreVec(MachineBasicBlock &B,
1771       MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1772       const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1773   MachineFunction &MF = *B.getParent();
1774   auto &HST = MF.getSubtarget<HexagonSubtarget>();
1775   auto &MFI = MF.getFrameInfo();
1776   MachineInstr *MI = &*It;
1777   if (!MI->getOperand(0).isFI())
1778     return false;
1779 
1780   DebugLoc DL = MI->getDebugLoc();
1781   unsigned SrcR = MI->getOperand(2).getReg();
1782   bool IsKill = MI->getOperand(2).isKill();
1783   int FI = MI->getOperand(0).getIndex();
1784 
1785   bool Is128B = HST.useHVXDblOps();
1786   auto *RC = !Is128B ? &Hexagon::VectorRegsRegClass
1787                      : &Hexagon::VectorRegs128BRegClass;
1788 
1789   unsigned NeedAlign = RC->getAlignment();
1790   unsigned HasAlign = MFI.getObjectAlignment(FI);
1791   unsigned StoreOpc;
1792 
1793   if (NeedAlign <= HasAlign)
1794     StoreOpc = !Is128B ? Hexagon::V6_vS32b_ai : Hexagon::V6_vS32b_ai_128B;
1795   else
1796     StoreOpc = !Is128B ? Hexagon::V6_vS32Ub_ai : Hexagon::V6_vS32Ub_ai_128B;
1797 
1798   BuildMI(B, It, DL, HII.get(StoreOpc))
1799     .addFrameIndex(FI)
1800     .addImm(0)
1801     .addReg(SrcR, getKillRegState(IsKill))
1802     .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1803 
1804   B.erase(It);
1805   return true;
1806 }
1807 
1808 bool HexagonFrameLowering::expandLoadVec(MachineBasicBlock &B,
1809       MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1810       const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1811   MachineFunction &MF = *B.getParent();
1812   auto &HST = MF.getSubtarget<HexagonSubtarget>();
1813   auto &MFI = MF.getFrameInfo();
1814   MachineInstr *MI = &*It;
1815   if (!MI->getOperand(1).isFI())
1816     return false;
1817 
1818   DebugLoc DL = MI->getDebugLoc();
1819   unsigned DstR = MI->getOperand(0).getReg();
1820   int FI = MI->getOperand(1).getIndex();
1821 
1822   bool Is128B = HST.useHVXDblOps();
1823   auto *RC = !Is128B ? &Hexagon::VectorRegsRegClass
1824                      : &Hexagon::VectorRegs128BRegClass;
1825 
1826   unsigned NeedAlign = RC->getAlignment();
1827   unsigned HasAlign = MFI.getObjectAlignment(FI);
1828   unsigned LoadOpc;
1829 
1830   if (NeedAlign <= HasAlign)
1831     LoadOpc = !Is128B ? Hexagon::V6_vL32b_ai : Hexagon::V6_vL32b_ai_128B;
1832   else
1833     LoadOpc = !Is128B ? Hexagon::V6_vL32Ub_ai : Hexagon::V6_vL32Ub_ai_128B;
1834 
1835   BuildMI(B, It, DL, HII.get(LoadOpc), DstR)
1836     .addFrameIndex(FI)
1837     .addImm(0)
1838     .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1839 
1840   B.erase(It);
1841   return true;
1842 }
1843 
1844 bool HexagonFrameLowering::expandSpillMacros(MachineFunction &MF,
1845       SmallVectorImpl<unsigned> &NewRegs) const {
1846   auto &HST = MF.getSubtarget<HexagonSubtarget>();
1847   auto &HII = *HST.getInstrInfo();
1848   MachineRegisterInfo &MRI = MF.getRegInfo();
1849   bool Changed = false;
1850 
1851   for (auto &B : MF) {
1852     // Traverse the basic block.
1853     MachineBasicBlock::iterator NextI;
1854     for (auto I = B.begin(), E = B.end(); I != E; I = NextI) {
1855       MachineInstr *MI = &*I;
1856       NextI = std::next(I);
1857       unsigned Opc = MI->getOpcode();
1858 
1859       switch (Opc) {
1860         case TargetOpcode::COPY:
1861           Changed |= expandCopy(B, I, MRI, HII, NewRegs);
1862           break;
1863         case Hexagon::STriw_pred:
1864         case Hexagon::STriw_mod:
1865           Changed |= expandStoreInt(B, I, MRI, HII, NewRegs);
1866           break;
1867         case Hexagon::LDriw_pred:
1868         case Hexagon::LDriw_mod:
1869           Changed |= expandLoadInt(B, I, MRI, HII, NewRegs);
1870           break;
1871         case Hexagon::PS_vstorerq_ai:
1872         case Hexagon::PS_vstorerq_ai_128B:
1873           Changed |= expandStoreVecPred(B, I, MRI, HII, NewRegs);
1874           break;
1875         case Hexagon::PS_vloadrq_ai:
1876         case Hexagon::PS_vloadrq_ai_128B:
1877           Changed |= expandLoadVecPred(B, I, MRI, HII, NewRegs);
1878           break;
1879         case Hexagon::PS_vloadrw_ai:
1880         case Hexagon::PS_vloadrwu_ai:
1881         case Hexagon::PS_vloadrw_ai_128B:
1882         case Hexagon::PS_vloadrwu_ai_128B:
1883           Changed |= expandLoadVec2(B, I, MRI, HII, NewRegs);
1884           break;
1885         case Hexagon::PS_vstorerw_ai:
1886         case Hexagon::PS_vstorerwu_ai:
1887         case Hexagon::PS_vstorerw_ai_128B:
1888         case Hexagon::PS_vstorerwu_ai_128B:
1889           Changed |= expandStoreVec2(B, I, MRI, HII, NewRegs);
1890           break;
1891       }
1892     }
1893   }
1894 
1895   return Changed;
1896 }
1897 
1898 void HexagonFrameLowering::determineCalleeSaves(MachineFunction &MF,
1899                                                 BitVector &SavedRegs,
1900                                                 RegScavenger *RS) const {
1901   auto &HST = MF.getSubtarget<HexagonSubtarget>();
1902   auto &HRI = *HST.getRegisterInfo();
1903 
1904   SavedRegs.resize(HRI.getNumRegs());
1905 
1906   // If we have a function containing __builtin_eh_return we want to spill and
1907   // restore all callee saved registers. Pretend that they are used.
1908   if (MF.getInfo<HexagonMachineFunctionInfo>()->hasEHReturn())
1909     for (const MCPhysReg *R = HRI.getCalleeSavedRegs(&MF); *R; ++R)
1910       SavedRegs.set(*R);
1911 
1912   // Replace predicate register pseudo spill code.
1913   SmallVector<unsigned,8> NewRegs;
1914   expandSpillMacros(MF, NewRegs);
1915   if (OptimizeSpillSlots && !isOptNone(MF))
1916     optimizeSpillSlots(MF, NewRegs);
1917 
1918   // We need to reserve a a spill slot if scavenging could potentially require
1919   // spilling a scavenged register.
1920   if (!NewRegs.empty() || mayOverflowFrameOffset(MF)) {
1921     MachineFrameInfo &MFI = MF.getFrameInfo();
1922     MachineRegisterInfo &MRI = MF.getRegInfo();
1923     SetVector<const TargetRegisterClass*> SpillRCs;
1924     // Reserve an int register in any case, because it could be used to hold
1925     // the stack offset in case it does not fit into a spill instruction.
1926     SpillRCs.insert(&Hexagon::IntRegsRegClass);
1927 
1928     for (unsigned VR : NewRegs)
1929       SpillRCs.insert(MRI.getRegClass(VR));
1930 
1931     for (auto *RC : SpillRCs) {
1932       if (!needToReserveScavengingSpillSlots(MF, HRI, RC))
1933         continue;
1934       unsigned Num = RC == &Hexagon::IntRegsRegClass ? NumberScavengerSlots : 1;
1935       unsigned S = RC->getSize(), A = RC->getAlignment();
1936       for (unsigned i = 0; i < Num; i++) {
1937         int NewFI = MFI.CreateSpillStackObject(S, A);
1938         RS->addScavengingFrameIndex(NewFI);
1939       }
1940     }
1941   }
1942 
1943   TargetFrameLowering::determineCalleeSaves(MF, SavedRegs, RS);
1944 }
1945 
1946 unsigned HexagonFrameLowering::findPhysReg(MachineFunction &MF,
1947       HexagonBlockRanges::IndexRange &FIR,
1948       HexagonBlockRanges::InstrIndexMap &IndexMap,
1949       HexagonBlockRanges::RegToRangeMap &DeadMap,
1950       const TargetRegisterClass *RC) const {
1951   auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
1952   auto &MRI = MF.getRegInfo();
1953 
1954   auto isDead = [&FIR,&DeadMap] (unsigned Reg) -> bool {
1955     auto F = DeadMap.find({Reg,0});
1956     if (F == DeadMap.end())
1957       return false;
1958     for (auto &DR : F->second)
1959       if (DR.contains(FIR))
1960         return true;
1961     return false;
1962   };
1963 
1964   for (unsigned Reg : RC->getRawAllocationOrder(MF)) {
1965     bool Dead = true;
1966     for (auto R : HexagonBlockRanges::expandToSubRegs({Reg,0}, MRI, HRI)) {
1967       if (isDead(R.Reg))
1968         continue;
1969       Dead = false;
1970       break;
1971     }
1972     if (Dead)
1973       return Reg;
1974   }
1975   return 0;
1976 }
1977 
1978 void HexagonFrameLowering::optimizeSpillSlots(MachineFunction &MF,
1979       SmallVectorImpl<unsigned> &VRegs) const {
1980   auto &HST = MF.getSubtarget<HexagonSubtarget>();
1981   auto &HII = *HST.getInstrInfo();
1982   auto &HRI = *HST.getRegisterInfo();
1983   auto &MRI = MF.getRegInfo();
1984   HexagonBlockRanges HBR(MF);
1985 
1986   typedef std::map<MachineBasicBlock*,HexagonBlockRanges::InstrIndexMap>
1987       BlockIndexMap;
1988   typedef std::map<MachineBasicBlock*,HexagonBlockRanges::RangeList>
1989       BlockRangeMap;
1990   typedef HexagonBlockRanges::IndexType IndexType;
1991 
1992   struct SlotInfo {
1993     BlockRangeMap Map;
1994     unsigned Size = 0;
1995     const TargetRegisterClass *RC = nullptr;
1996 
1997     SlotInfo() = default;
1998   };
1999 
2000   BlockIndexMap BlockIndexes;
2001   SmallSet<int,4> BadFIs;
2002   std::map<int,SlotInfo> FIRangeMap;
2003 
2004   // Accumulate register classes: get a common class for a pre-existing
2005   // class HaveRC and a new class NewRC. Return nullptr if a common class
2006   // cannot be found, otherwise return the resulting class. If HaveRC is
2007   // nullptr, assume that it is still unset.
2008   auto getCommonRC =
2009       [](const TargetRegisterClass *HaveRC,
2010          const TargetRegisterClass *NewRC) -> const TargetRegisterClass * {
2011     if (HaveRC == nullptr || HaveRC == NewRC)
2012       return NewRC;
2013     // Different classes, both non-null. Pick the more general one.
2014     if (HaveRC->hasSubClassEq(NewRC))
2015       return HaveRC;
2016     if (NewRC->hasSubClassEq(HaveRC))
2017       return NewRC;
2018     return nullptr;
2019   };
2020 
2021   // Scan all blocks in the function. Check all occurrences of frame indexes,
2022   // and collect relevant information.
2023   for (auto &B : MF) {
2024     std::map<int,IndexType> LastStore, LastLoad;
2025     // Emplace appears not to be supported in gcc 4.7.2-4.
2026     //auto P = BlockIndexes.emplace(&B, HexagonBlockRanges::InstrIndexMap(B));
2027     auto P = BlockIndexes.insert(
2028                 std::make_pair(&B, HexagonBlockRanges::InstrIndexMap(B)));
2029     auto &IndexMap = P.first->second;
2030     DEBUG(dbgs() << "Index map for BB#" << B.getNumber() << "\n"
2031                  << IndexMap << '\n');
2032 
2033     for (auto &In : B) {
2034       int LFI, SFI;
2035       bool Load = HII.isLoadFromStackSlot(In, LFI) && !HII.isPredicated(In);
2036       bool Store = HII.isStoreToStackSlot(In, SFI) && !HII.isPredicated(In);
2037       if (Load && Store) {
2038         // If it's both a load and a store, then we won't handle it.
2039         BadFIs.insert(LFI);
2040         BadFIs.insert(SFI);
2041         continue;
2042       }
2043       // Check for register classes of the register used as the source for
2044       // the store, and the register used as the destination for the load.
2045       // Also, only accept base+imm_offset addressing modes. Other addressing
2046       // modes can have side-effects (post-increments, etc.). For stack
2047       // slots they are very unlikely, so there is not much loss due to
2048       // this restriction.
2049       if (Load || Store) {
2050         int TFI = Load ? LFI : SFI;
2051         unsigned AM = HII.getAddrMode(In);
2052         SlotInfo &SI = FIRangeMap[TFI];
2053         bool Bad = (AM != HexagonII::BaseImmOffset);
2054         if (!Bad) {
2055           // If the addressing mode is ok, check the register class.
2056           unsigned OpNum = Load ? 0 : 2;
2057           auto *RC = HII.getRegClass(In.getDesc(), OpNum, &HRI, MF);
2058           RC = getCommonRC(SI.RC, RC);
2059           if (RC == nullptr)
2060             Bad = true;
2061           else
2062             SI.RC = RC;
2063         }
2064         if (!Bad) {
2065           // Check sizes.
2066           unsigned S = (1U << (HII.getMemAccessSize(In) - 1));
2067           if (SI.Size != 0 && SI.Size != S)
2068             Bad = true;
2069           else
2070             SI.Size = S;
2071         }
2072         if (!Bad) {
2073           for (auto *Mo : In.memoperands()) {
2074             if (!Mo->isVolatile())
2075               continue;
2076             Bad = true;
2077             break;
2078           }
2079         }
2080         if (Bad)
2081           BadFIs.insert(TFI);
2082       }
2083 
2084       // Locate uses of frame indices.
2085       for (unsigned i = 0, n = In.getNumOperands(); i < n; ++i) {
2086         const MachineOperand &Op = In.getOperand(i);
2087         if (!Op.isFI())
2088           continue;
2089         int FI = Op.getIndex();
2090         // Make sure that the following operand is an immediate and that
2091         // it is 0. This is the offset in the stack object.
2092         if (i+1 >= n || !In.getOperand(i+1).isImm() ||
2093             In.getOperand(i+1).getImm() != 0)
2094           BadFIs.insert(FI);
2095         if (BadFIs.count(FI))
2096           continue;
2097 
2098         IndexType Index = IndexMap.getIndex(&In);
2099         if (Load) {
2100           if (LastStore[FI] == IndexType::None)
2101             LastStore[FI] = IndexType::Entry;
2102           LastLoad[FI] = Index;
2103         } else if (Store) {
2104           HexagonBlockRanges::RangeList &RL = FIRangeMap[FI].Map[&B];
2105           if (LastStore[FI] != IndexType::None)
2106             RL.add(LastStore[FI], LastLoad[FI], false, false);
2107           else if (LastLoad[FI] != IndexType::None)
2108             RL.add(IndexType::Entry, LastLoad[FI], false, false);
2109           LastLoad[FI] = IndexType::None;
2110           LastStore[FI] = Index;
2111         } else {
2112           BadFIs.insert(FI);
2113         }
2114       }
2115     }
2116 
2117     for (auto &I : LastLoad) {
2118       IndexType LL = I.second;
2119       if (LL == IndexType::None)
2120         continue;
2121       auto &RL = FIRangeMap[I.first].Map[&B];
2122       IndexType &LS = LastStore[I.first];
2123       if (LS != IndexType::None)
2124         RL.add(LS, LL, false, false);
2125       else
2126         RL.add(IndexType::Entry, LL, false, false);
2127       LS = IndexType::None;
2128     }
2129     for (auto &I : LastStore) {
2130       IndexType LS = I.second;
2131       if (LS == IndexType::None)
2132         continue;
2133       auto &RL = FIRangeMap[I.first].Map[&B];
2134       RL.add(LS, IndexType::None, false, false);
2135     }
2136   }
2137 
2138   DEBUG({
2139     for (auto &P : FIRangeMap) {
2140       dbgs() << "fi#" << P.first;
2141       if (BadFIs.count(P.first))
2142         dbgs() << " (bad)";
2143       dbgs() << "  RC: ";
2144       if (P.second.RC != nullptr)
2145         dbgs() << HRI.getRegClassName(P.second.RC) << '\n';
2146       else
2147         dbgs() << "<null>\n";
2148       for (auto &R : P.second.Map)
2149         dbgs() << "  BB#" << R.first->getNumber() << " { " << R.second << "}\n";
2150     }
2151   });
2152 
2153   // When a slot is loaded from in a block without being stored to in the
2154   // same block, it is live-on-entry to this block. To avoid CFG analysis,
2155   // consider this slot to be live-on-exit from all blocks.
2156   SmallSet<int,4> LoxFIs;
2157 
2158   std::map<MachineBasicBlock*,std::vector<int>> BlockFIMap;
2159 
2160   for (auto &P : FIRangeMap) {
2161     // P = pair(FI, map: BB->RangeList)
2162     if (BadFIs.count(P.first))
2163       continue;
2164     for (auto &B : MF) {
2165       auto F = P.second.Map.find(&B);
2166       // F = pair(BB, RangeList)
2167       if (F == P.second.Map.end() || F->second.empty())
2168         continue;
2169       HexagonBlockRanges::IndexRange &IR = F->second.front();
2170       if (IR.start() == IndexType::Entry)
2171         LoxFIs.insert(P.first);
2172       BlockFIMap[&B].push_back(P.first);
2173     }
2174   }
2175 
2176   DEBUG({
2177     dbgs() << "Block-to-FI map (* -- live-on-exit):\n";
2178     for (auto &P : BlockFIMap) {
2179       auto &FIs = P.second;
2180       if (FIs.empty())
2181         continue;
2182       dbgs() << "  BB#" << P.first->getNumber() << ": {";
2183       for (auto I : FIs) {
2184         dbgs() << " fi#" << I;
2185         if (LoxFIs.count(I))
2186           dbgs() << '*';
2187       }
2188       dbgs() << " }\n";
2189     }
2190   });
2191 
2192 #ifndef NDEBUG
2193   bool HasOptLimit = SpillOptMax.getPosition();
2194 #endif
2195 
2196   // eliminate loads, when all loads eliminated, eliminate all stores.
2197   for (auto &B : MF) {
2198     auto F = BlockIndexes.find(&B);
2199     assert(F != BlockIndexes.end());
2200     HexagonBlockRanges::InstrIndexMap &IM = F->second;
2201     HexagonBlockRanges::RegToRangeMap LM = HBR.computeLiveMap(IM);
2202     HexagonBlockRanges::RegToRangeMap DM = HBR.computeDeadMap(IM, LM);
2203     DEBUG(dbgs() << "BB#" << B.getNumber() << " dead map\n"
2204                  << HexagonBlockRanges::PrintRangeMap(DM, HRI));
2205 
2206     for (auto FI : BlockFIMap[&B]) {
2207       if (BadFIs.count(FI))
2208         continue;
2209       DEBUG(dbgs() << "Working on fi#" << FI << '\n');
2210       HexagonBlockRanges::RangeList &RL = FIRangeMap[FI].Map[&B];
2211       for (auto &Range : RL) {
2212         DEBUG(dbgs() << "--Examining range:" << RL << '\n');
2213         if (!IndexType::isInstr(Range.start()) ||
2214             !IndexType::isInstr(Range.end()))
2215           continue;
2216         MachineInstr &SI = *IM.getInstr(Range.start());
2217         MachineInstr &EI = *IM.getInstr(Range.end());
2218         assert(SI.mayStore() && "Unexpected start instruction");
2219         assert(EI.mayLoad() && "Unexpected end instruction");
2220         MachineOperand &SrcOp = SI.getOperand(2);
2221 
2222         HexagonBlockRanges::RegisterRef SrcRR = { SrcOp.getReg(),
2223                                                   SrcOp.getSubReg() };
2224         auto *RC = HII.getRegClass(SI.getDesc(), 2, &HRI, MF);
2225         // The this-> is needed to unconfuse MSVC.
2226         unsigned FoundR = this->findPhysReg(MF, Range, IM, DM, RC);
2227         DEBUG(dbgs() << "Replacement reg:" << PrintReg(FoundR, &HRI) << '\n');
2228         if (FoundR == 0)
2229           continue;
2230 #ifndef NDEBUG
2231         if (HasOptLimit) {
2232           if (SpillOptCount >= SpillOptMax)
2233             return;
2234           SpillOptCount++;
2235         }
2236 #endif
2237 
2238         // Generate the copy-in: "FoundR = COPY SrcR" at the store location.
2239         MachineBasicBlock::iterator StartIt = SI.getIterator(), NextIt;
2240         MachineInstr *CopyIn = nullptr;
2241         if (SrcRR.Reg != FoundR || SrcRR.Sub != 0) {
2242           const DebugLoc &DL = SI.getDebugLoc();
2243           CopyIn = BuildMI(B, StartIt, DL, HII.get(TargetOpcode::COPY), FoundR)
2244                        .add(SrcOp);
2245         }
2246 
2247         ++StartIt;
2248         // Check if this is a last store and the FI is live-on-exit.
2249         if (LoxFIs.count(FI) && (&Range == &RL.back())) {
2250           // Update store's source register.
2251           if (unsigned SR = SrcOp.getSubReg())
2252             SrcOp.setReg(HRI.getSubReg(FoundR, SR));
2253           else
2254             SrcOp.setReg(FoundR);
2255           SrcOp.setSubReg(0);
2256           // We are keeping this register live.
2257           SrcOp.setIsKill(false);
2258         } else {
2259           B.erase(&SI);
2260           IM.replaceInstr(&SI, CopyIn);
2261         }
2262 
2263         auto EndIt = std::next(EI.getIterator());
2264         for (auto It = StartIt; It != EndIt; It = NextIt) {
2265           MachineInstr &MI = *It;
2266           NextIt = std::next(It);
2267           int TFI;
2268           if (!HII.isLoadFromStackSlot(MI, TFI) || TFI != FI)
2269             continue;
2270           unsigned DstR = MI.getOperand(0).getReg();
2271           assert(MI.getOperand(0).getSubReg() == 0);
2272           MachineInstr *CopyOut = nullptr;
2273           if (DstR != FoundR) {
2274             DebugLoc DL = MI.getDebugLoc();
2275             unsigned MemSize = (1U << (HII.getMemAccessSize(MI) - 1));
2276             assert(HII.getAddrMode(MI) == HexagonII::BaseImmOffset);
2277             unsigned CopyOpc = TargetOpcode::COPY;
2278             if (HII.isSignExtendingLoad(MI))
2279               CopyOpc = (MemSize == 1) ? Hexagon::A2_sxtb : Hexagon::A2_sxth;
2280             else if (HII.isZeroExtendingLoad(MI))
2281               CopyOpc = (MemSize == 1) ? Hexagon::A2_zxtb : Hexagon::A2_zxth;
2282             CopyOut = BuildMI(B, It, DL, HII.get(CopyOpc), DstR)
2283                         .addReg(FoundR, getKillRegState(&MI == &EI));
2284           }
2285           IM.replaceInstr(&MI, CopyOut);
2286           B.erase(It);
2287         }
2288 
2289         // Update the dead map.
2290         HexagonBlockRanges::RegisterRef FoundRR = { FoundR, 0 };
2291         for (auto RR : HexagonBlockRanges::expandToSubRegs(FoundRR, MRI, HRI))
2292           DM[RR].subtract(Range);
2293       } // for Range in range list
2294     }
2295   }
2296 }
2297 
2298 void HexagonFrameLowering::expandAlloca(MachineInstr *AI,
2299       const HexagonInstrInfo &HII, unsigned SP, unsigned CF) const {
2300   MachineBasicBlock &MB = *AI->getParent();
2301   DebugLoc DL = AI->getDebugLoc();
2302   unsigned A = AI->getOperand(2).getImm();
2303 
2304   // Have
2305   //    Rd  = alloca Rs, #A
2306   //
2307   // If Rs and Rd are different registers, use this sequence:
2308   //    Rd  = sub(r29, Rs)
2309   //    r29 = sub(r29, Rs)
2310   //    Rd  = and(Rd, #-A)    ; if necessary
2311   //    r29 = and(r29, #-A)   ; if necessary
2312   //    Rd  = add(Rd, #CF)    ; CF size aligned to at most A
2313   // otherwise, do
2314   //    Rd  = sub(r29, Rs)
2315   //    Rd  = and(Rd, #-A)    ; if necessary
2316   //    r29 = Rd
2317   //    Rd  = add(Rd, #CF)    ; CF size aligned to at most A
2318 
2319   MachineOperand &RdOp = AI->getOperand(0);
2320   MachineOperand &RsOp = AI->getOperand(1);
2321   unsigned Rd = RdOp.getReg(), Rs = RsOp.getReg();
2322 
2323   // Rd = sub(r29, Rs)
2324   BuildMI(MB, AI, DL, HII.get(Hexagon::A2_sub), Rd)
2325       .addReg(SP)
2326       .addReg(Rs);
2327   if (Rs != Rd) {
2328     // r29 = sub(r29, Rs)
2329     BuildMI(MB, AI, DL, HII.get(Hexagon::A2_sub), SP)
2330         .addReg(SP)
2331         .addReg(Rs);
2332   }
2333   if (A > 8) {
2334     // Rd  = and(Rd, #-A)
2335     BuildMI(MB, AI, DL, HII.get(Hexagon::A2_andir), Rd)
2336         .addReg(Rd)
2337         .addImm(-int64_t(A));
2338     if (Rs != Rd)
2339       BuildMI(MB, AI, DL, HII.get(Hexagon::A2_andir), SP)
2340           .addReg(SP)
2341           .addImm(-int64_t(A));
2342   }
2343   if (Rs == Rd) {
2344     // r29 = Rd
2345     BuildMI(MB, AI, DL, HII.get(TargetOpcode::COPY), SP)
2346         .addReg(Rd);
2347   }
2348   if (CF > 0) {
2349     // Rd = add(Rd, #CF)
2350     BuildMI(MB, AI, DL, HII.get(Hexagon::A2_addi), Rd)
2351         .addReg(Rd)
2352         .addImm(CF);
2353   }
2354 }
2355 
2356 bool HexagonFrameLowering::needsAligna(const MachineFunction &MF) const {
2357   const MachineFrameInfo &MFI = MF.getFrameInfo();
2358   if (!MFI.hasVarSizedObjects())
2359     return false;
2360   unsigned MaxA = MFI.getMaxAlignment();
2361   if (MaxA <= getStackAlignment())
2362     return false;
2363   return true;
2364 }
2365 
2366 const MachineInstr *HexagonFrameLowering::getAlignaInstr(
2367       const MachineFunction &MF) const {
2368   for (auto &B : MF)
2369     for (auto &I : B)
2370       if (I.getOpcode() == Hexagon::PS_aligna)
2371         return &I;
2372   return nullptr;
2373 }
2374 
2375 /// Adds all callee-saved registers as implicit uses or defs to the
2376 /// instruction.
2377 void HexagonFrameLowering::addCalleeSaveRegistersAsImpOperand(MachineInstr *MI,
2378       const CSIVect &CSI, bool IsDef, bool IsKill) const {
2379   // Add the callee-saved registers as implicit uses.
2380   for (auto &R : CSI)
2381     MI->addOperand(MachineOperand::CreateReg(R.getReg(), IsDef, true, IsKill));
2382 }
2383 
2384 /// Determine whether the callee-saved register saves and restores should
2385 /// be generated via inline code. If this function returns "true", inline
2386 /// code will be generated. If this function returns "false", additional
2387 /// checks are performed, which may still lead to the inline code.
2388 bool HexagonFrameLowering::shouldInlineCSR(MachineFunction &MF,
2389       const CSIVect &CSI) const {
2390   if (MF.getInfo<HexagonMachineFunctionInfo>()->hasEHReturn())
2391     return true;
2392   if (!isOptSize(MF) && !isMinSize(MF))
2393     if (MF.getTarget().getOptLevel() > CodeGenOpt::Default)
2394       return true;
2395 
2396   // Check if CSI only has double registers, and if the registers form
2397   // a contiguous block starting from D8.
2398   BitVector Regs(Hexagon::NUM_TARGET_REGS);
2399   for (unsigned i = 0, n = CSI.size(); i < n; ++i) {
2400     unsigned R = CSI[i].getReg();
2401     if (!Hexagon::DoubleRegsRegClass.contains(R))
2402       return true;
2403     Regs[R] = true;
2404   }
2405   int F = Regs.find_first();
2406   if (F != Hexagon::D8)
2407     return true;
2408   while (F >= 0) {
2409     int N = Regs.find_next(F);
2410     if (N >= 0 && N != F+1)
2411       return true;
2412     F = N;
2413   }
2414 
2415   return false;
2416 }
2417 
2418 bool HexagonFrameLowering::useSpillFunction(MachineFunction &MF,
2419       const CSIVect &CSI) const {
2420   if (shouldInlineCSR(MF, CSI))
2421     return false;
2422   unsigned NumCSI = CSI.size();
2423   if (NumCSI <= 1)
2424     return false;
2425 
2426   unsigned Threshold = isOptSize(MF) ? SpillFuncThresholdOs
2427                                      : SpillFuncThreshold;
2428   return Threshold < NumCSI;
2429 }
2430 
2431 bool HexagonFrameLowering::useRestoreFunction(MachineFunction &MF,
2432       const CSIVect &CSI) const {
2433   if (shouldInlineCSR(MF, CSI))
2434     return false;
2435   // The restore functions do a bit more than just restoring registers.
2436   // The non-returning versions will go back directly to the caller's
2437   // caller, others will clean up the stack frame in preparation for
2438   // a tail call. Using them can still save code size even if only one
2439   // register is getting restores. Make the decision based on -Oz:
2440   // using -Os will use inline restore for a single register.
2441   if (isMinSize(MF))
2442     return true;
2443   unsigned NumCSI = CSI.size();
2444   if (NumCSI <= 1)
2445     return false;
2446 
2447   unsigned Threshold = isOptSize(MF) ? SpillFuncThresholdOs-1
2448                                      : SpillFuncThreshold;
2449   return Threshold < NumCSI;
2450 }
2451 
2452 bool HexagonFrameLowering::mayOverflowFrameOffset(MachineFunction &MF) const {
2453   unsigned StackSize = MF.getFrameInfo().estimateStackSize(MF);
2454   auto &HST = MF.getSubtarget<HexagonSubtarget>();
2455   // A fairly simplistic guess as to whether a potential load/store to a
2456   // stack location could require an extra register. It does not account
2457   // for store-immediate instructions.
2458   if (HST.useHVXOps())
2459     return StackSize > 256;
2460   return false;
2461 }
2462