1 //===-- HexagonFrameLowering.cpp - Define frame lowering ------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //
9 //===----------------------------------------------------------------------===//
10 
11 #define DEBUG_TYPE "hexagon-pei"
12 
13 #include "HexagonFrameLowering.h"
14 #include "Hexagon.h"
15 #include "HexagonInstrInfo.h"
16 #include "HexagonMachineFunctionInfo.h"
17 #include "HexagonRegisterInfo.h"
18 #include "HexagonSubtarget.h"
19 #include "HexagonTargetMachine.h"
20 #include "llvm/ADT/BitVector.h"
21 #include "llvm/ADT/PostOrderIterator.h"
22 #include "llvm/ADT/SCCIterator.h"
23 #include "llvm/ADT/STLExtras.h"
24 #include "llvm/CodeGen/MachineDominators.h"
25 #include "llvm/CodeGen/MachineInstrBuilder.h"
26 #include "llvm/CodeGen/MachineFunction.h"
27 #include "llvm/CodeGen/MachineFunctionPass.h"
28 #include "llvm/CodeGen/MachineInstrBuilder.h"
29 #include "llvm/CodeGen/MachineModuleInfo.h"
30 #include "llvm/CodeGen/MachinePostDominators.h"
31 #include "llvm/CodeGen/MachineRegisterInfo.h"
32 #include "llvm/CodeGen/RegisterScavenging.h"
33 #include "llvm/IR/Function.h"
34 #include "llvm/IR/Type.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/raw_ostream.h"
38 #include "llvm/Target/TargetInstrInfo.h"
39 #include "llvm/Target/TargetMachine.h"
40 #include "llvm/Target/TargetOptions.h"
41 
42 // Hexagon stack frame layout as defined by the ABI:
43 //
44 //                                                       Incoming arguments
45 //                                                       passed via stack
46 //                                                                      |
47 //                                                                      |
48 //        SP during function's                 FP during function's     |
49 //    +-- runtime (top of stack)               runtime (bottom) --+     |
50 //    |                                                           |     |
51 // --++---------------------+------------------+-----------------++-+-------
52 //   |  parameter area for  |  variable-size   |   fixed-size    |LR|  arg
53 //   |   called functions   |  local objects   |  local objects  |FP|
54 // --+----------------------+------------------+-----------------+--+-------
55 //    <-    size known    -> <- size unknown -> <- size known  ->
56 //
57 // Low address                                                 High address
58 //
59 // <--- stack growth
60 //
61 //
62 // - In any circumstances, the outgoing function arguments are always accessi-
63 //   ble using the SP, and the incoming arguments are accessible using the FP.
64 // - If the local objects are not aligned, they can always be accessed using
65 //   the FP.
66 // - If there are no variable-sized objects, the local objects can always be
67 //   accessed using the SP, regardless whether they are aligned or not. (The
68 //   alignment padding will be at the bottom of the stack (highest address),
69 //   and so the offset with respect to the SP will be known at the compile-
70 //   -time.)
71 //
72 // The only complication occurs if there are both, local aligned objects, and
73 // dynamically allocated (variable-sized) objects. The alignment pad will be
74 // placed between the FP and the local objects, thus preventing the use of the
75 // FP to access the local objects. At the same time, the variable-sized objects
76 // will be between the SP and the local objects, thus introducing an unknown
77 // distance from the SP to the locals.
78 //
79 // To avoid this problem, a new register is created that holds the aligned
80 // address of the bottom of the stack, referred in the sources as AP (aligned
81 // pointer). The AP will be equal to "FP-p", where "p" is the smallest pad
82 // that aligns AP to the required boundary (a maximum of the alignments of
83 // all stack objects, fixed- and variable-sized). All local objects[1] will
84 // then use AP as the base pointer.
85 // [1] The exception is with "fixed" stack objects. "Fixed" stack objects get
86 // their name from being allocated at fixed locations on the stack, relative
87 // to the FP. In the presence of dynamic allocation and local alignment, such
88 // objects can only be accessed through the FP.
89 //
90 // Illustration of the AP:
91 //                                                                FP --+
92 //                                                                     |
93 // ---------------+---------------------+-----+-----------------------++-+--
94 //   Rest of the  | Local stack objects | Pad |  Fixed stack objects  |LR|
95 //   stack frame  | (aligned)           |     |  (CSR, spills, etc.)  |FP|
96 // ---------------+---------------------+-----+-----------------+-----+--+--
97 //                                      |<-- Multiple of the -->|
98 //                                           stack alignment    +-- AP
99 //
100 // The AP is set up at the beginning of the function. Since it is not a dedi-
101 // cated (reserved) register, it needs to be kept live throughout the function
102 // to be available as the base register for local object accesses.
103 // Normally, an address of a stack objects is obtained by a pseudo-instruction
104 // TFR_FI. To access local objects with the AP register present, a different
105 // pseudo-instruction needs to be used: TFR_FIA. The TFR_FIA takes one extra
106 // argument compared to TFR_FI: the first input register is the AP register.
107 // This keeps the register live between its definition and its uses.
108 
109 // The AP register is originally set up using pseudo-instruction ALIGNA:
110 //   AP = ALIGNA A
111 // where
112 //   A  - required stack alignment
113 // The alignment value must be the maximum of all alignments required by
114 // any stack object.
115 
116 // The dynamic allocation uses a pseudo-instruction ALLOCA:
117 //   Rd = ALLOCA Rs, A
118 // where
119 //   Rd - address of the allocated space
120 //   Rs - minimum size (the actual allocated can be larger to accommodate
121 //        alignment)
122 //   A  - required alignment
123 
124 
125 using namespace llvm;
126 
127 static cl::opt<bool> DisableDeallocRet("disable-hexagon-dealloc-ret",
128     cl::Hidden, cl::desc("Disable Dealloc Return for Hexagon target"));
129 
130 
131 static cl::opt<int> NumberScavengerSlots("number-scavenger-slots",
132     cl::Hidden, cl::desc("Set the number of scavenger slots"), cl::init(2),
133     cl::ZeroOrMore);
134 
135 static cl::opt<int> SpillFuncThreshold("spill-func-threshold",
136     cl::Hidden, cl::desc("Specify O2(not Os) spill func threshold"),
137     cl::init(6), cl::ZeroOrMore);
138 
139 static cl::opt<int> SpillFuncThresholdOs("spill-func-threshold-Os",
140     cl::Hidden, cl::desc("Specify Os spill func threshold"),
141     cl::init(1), cl::ZeroOrMore);
142 
143 static cl::opt<bool> EnableShrinkWrapping("hexagon-shrink-frame",
144     cl::init(true), cl::Hidden, cl::ZeroOrMore,
145     cl::desc("Enable stack frame shrink wrapping"));
146 
147 static cl::opt<unsigned> ShrinkLimit("shrink-frame-limit", cl::init(UINT_MAX),
148     cl::Hidden, cl::ZeroOrMore, cl::desc("Max count of stack frame "
149     "shrink-wraps"));
150 
151 static cl::opt<bool> UseAllocframe("use-allocframe", cl::init(true),
152     cl::Hidden, cl::desc("Use allocframe more conservatively"));
153 
154 
155 namespace llvm {
156   void initializeHexagonCallFrameInformationPass(PassRegistry&);
157   FunctionPass *createHexagonCallFrameInformation();
158 }
159 
160 namespace {
161   class HexagonCallFrameInformation : public MachineFunctionPass {
162   public:
163     static char ID;
164     HexagonCallFrameInformation() : MachineFunctionPass(ID) {
165       PassRegistry &PR = *PassRegistry::getPassRegistry();
166       initializeHexagonCallFrameInformationPass(PR);
167     }
168     bool runOnMachineFunction(MachineFunction &MF) override;
169   };
170 
171   char HexagonCallFrameInformation::ID = 0;
172 }
173 
174 bool HexagonCallFrameInformation::runOnMachineFunction(MachineFunction &MF) {
175   auto &HFI = *MF.getSubtarget<HexagonSubtarget>().getFrameLowering();
176   bool NeedCFI = MF.getMMI().hasDebugInfo() ||
177                  MF.getFunction()->needsUnwindTableEntry();
178 
179   if (!NeedCFI)
180     return false;
181   HFI.insertCFIInstructions(MF);
182   return true;
183 }
184 
185 INITIALIZE_PASS(HexagonCallFrameInformation, "hexagon-cfi",
186                 "Hexagon call frame information", false, false)
187 
188 FunctionPass *llvm::createHexagonCallFrameInformation() {
189   return new HexagonCallFrameInformation();
190 }
191 
192 
193 namespace {
194   /// Map a register pair Reg to the subregister that has the greater "number",
195   /// i.e. D3 (aka R7:6) will be mapped to R7, etc.
196   unsigned getMax32BitSubRegister(unsigned Reg, const TargetRegisterInfo &TRI,
197                                   bool hireg = true) {
198     if (Reg < Hexagon::D0 || Reg > Hexagon::D15)
199       return Reg;
200 
201     unsigned RegNo = 0;
202     for (MCSubRegIterator SubRegs(Reg, &TRI); SubRegs.isValid(); ++SubRegs) {
203       if (hireg) {
204         if (*SubRegs > RegNo)
205           RegNo = *SubRegs;
206       } else {
207         if (!RegNo || *SubRegs < RegNo)
208           RegNo = *SubRegs;
209       }
210     }
211     return RegNo;
212   }
213 
214   /// Returns the callee saved register with the largest id in the vector.
215   unsigned getMaxCalleeSavedReg(const std::vector<CalleeSavedInfo> &CSI,
216                                 const TargetRegisterInfo &TRI) {
217     assert(Hexagon::R1 > 0 &&
218            "Assume physical registers are encoded as positive integers");
219     if (CSI.empty())
220       return 0;
221 
222     unsigned Max = getMax32BitSubRegister(CSI[0].getReg(), TRI);
223     for (unsigned I = 1, E = CSI.size(); I < E; ++I) {
224       unsigned Reg = getMax32BitSubRegister(CSI[I].getReg(), TRI);
225       if (Reg > Max)
226         Max = Reg;
227     }
228     return Max;
229   }
230 
231   /// Checks if the basic block contains any instruction that needs a stack
232   /// frame to be already in place.
233   bool needsStackFrame(const MachineBasicBlock &MBB, const BitVector &CSR) {
234     for (auto &I : MBB) {
235       const MachineInstr *MI = &I;
236       if (MI->isCall())
237         return true;
238       unsigned Opc = MI->getOpcode();
239       switch (Opc) {
240         case Hexagon::ALLOCA:
241         case Hexagon::ALIGNA:
242           return true;
243         default:
244           break;
245       }
246       // Check individual operands.
247       for (const MachineOperand &MO : MI->operands()) {
248         // While the presence of a frame index does not prove that a stack
249         // frame will be required, all frame indexes should be within alloc-
250         // frame/deallocframe. Otherwise, the code that translates a frame
251         // index into an offset would have to be aware of the placement of
252         // the frame creation/destruction instructions.
253         if (MO.isFI())
254           return true;
255         if (!MO.isReg())
256           continue;
257         unsigned R = MO.getReg();
258         // Virtual registers will need scavenging, which then may require
259         // a stack slot.
260         if (TargetRegisterInfo::isVirtualRegister(R))
261           return true;
262         if (CSR[R])
263           return true;
264       }
265     }
266     return false;
267   }
268 
269   /// Returns true if MBB has a machine instructions that indicates a tail call
270   /// in the block.
271   bool hasTailCall(const MachineBasicBlock &MBB) {
272     MachineBasicBlock::const_iterator I = MBB.getLastNonDebugInstr();
273     unsigned RetOpc = I->getOpcode();
274     return RetOpc == Hexagon::TCRETURNi || RetOpc == Hexagon::TCRETURNr;
275   }
276 
277   /// Returns true if MBB contains an instruction that returns.
278   bool hasReturn(const MachineBasicBlock &MBB) {
279     for (auto I = MBB.getFirstTerminator(), E = MBB.end(); I != E; ++I)
280       if (I->isReturn())
281         return true;
282     return false;
283   }
284 }
285 
286 
287 /// Implements shrink-wrapping of the stack frame. By default, stack frame
288 /// is created in the function entry block, and is cleaned up in every block
289 /// that returns. This function finds alternate blocks: one for the frame
290 /// setup (prolog) and one for the cleanup (epilog).
291 void HexagonFrameLowering::findShrunkPrologEpilog(MachineFunction &MF,
292       MachineBasicBlock *&PrologB, MachineBasicBlock *&EpilogB) const {
293   static unsigned ShrinkCounter = 0;
294 
295   if (ShrinkLimit.getPosition()) {
296     if (ShrinkCounter >= ShrinkLimit)
297       return;
298     ShrinkCounter++;
299   }
300 
301   auto &HST = static_cast<const HexagonSubtarget&>(MF.getSubtarget());
302   auto &HRI = *HST.getRegisterInfo();
303 
304   MachineDominatorTree MDT;
305   MDT.runOnMachineFunction(MF);
306   MachinePostDominatorTree MPT;
307   MPT.runOnMachineFunction(MF);
308 
309   typedef DenseMap<unsigned,unsigned> UnsignedMap;
310   UnsignedMap RPO;
311   typedef ReversePostOrderTraversal<const MachineFunction*> RPOTType;
312   RPOTType RPOT(&MF);
313   unsigned RPON = 0;
314   for (RPOTType::rpo_iterator I = RPOT.begin(), E = RPOT.end(); I != E; ++I)
315     RPO[(*I)->getNumber()] = RPON++;
316 
317   // Don't process functions that have loops, at least for now. Placement
318   // of prolog and epilog must take loop structure into account. For simpli-
319   // city don't do it right now.
320   for (auto &I : MF) {
321     unsigned BN = RPO[I.getNumber()];
322     for (auto SI = I.succ_begin(), SE = I.succ_end(); SI != SE; ++SI) {
323       // If found a back-edge, return.
324       if (RPO[(*SI)->getNumber()] <= BN)
325         return;
326     }
327   }
328 
329   // Collect the set of blocks that need a stack frame to execute. Scan
330   // each block for uses/defs of callee-saved registers, calls, etc.
331   SmallVector<MachineBasicBlock*,16> SFBlocks;
332   BitVector CSR(Hexagon::NUM_TARGET_REGS);
333   for (const MCPhysReg *P = HRI.getCalleeSavedRegs(&MF); *P; ++P)
334     CSR[*P] = true;
335 
336   for (auto &I : MF)
337     if (needsStackFrame(I, CSR))
338       SFBlocks.push_back(&I);
339 
340   DEBUG({
341     dbgs() << "Blocks needing SF: {";
342     for (auto &B : SFBlocks)
343       dbgs() << " BB#" << B->getNumber();
344     dbgs() << " }\n";
345   });
346   // No frame needed?
347   if (SFBlocks.empty())
348     return;
349 
350   // Pick a common dominator and a common post-dominator.
351   MachineBasicBlock *DomB = SFBlocks[0];
352   for (unsigned i = 1, n = SFBlocks.size(); i < n; ++i) {
353     DomB = MDT.findNearestCommonDominator(DomB, SFBlocks[i]);
354     if (!DomB)
355       break;
356   }
357   MachineBasicBlock *PDomB = SFBlocks[0];
358   for (unsigned i = 1, n = SFBlocks.size(); i < n; ++i) {
359     PDomB = MPT.findNearestCommonDominator(PDomB, SFBlocks[i]);
360     if (!PDomB)
361       break;
362   }
363   DEBUG({
364     dbgs() << "Computed dom block: BB#";
365     if (DomB) dbgs() << DomB->getNumber();
366     else      dbgs() << "<null>";
367     dbgs() << ", computed pdom block: BB#";
368     if (PDomB) dbgs() << PDomB->getNumber();
369     else       dbgs() << "<null>";
370     dbgs() << "\n";
371   });
372   if (!DomB || !PDomB)
373     return;
374 
375   // Make sure that DomB dominates PDomB and PDomB post-dominates DomB.
376   if (!MDT.dominates(DomB, PDomB)) {
377     DEBUG(dbgs() << "Dom block does not dominate pdom block\n");
378     return;
379   }
380   if (!MPT.dominates(PDomB, DomB)) {
381     DEBUG(dbgs() << "PDom block does not post-dominate dom block\n");
382     return;
383   }
384 
385   // Finally, everything seems right.
386   PrologB = DomB;
387   EpilogB = PDomB;
388 }
389 
390 /// Perform most of the PEI work here:
391 /// - saving/restoring of the callee-saved registers,
392 /// - stack frame creation and destruction.
393 /// Normally, this work is distributed among various functions, but doing it
394 /// in one place allows shrink-wrapping of the stack frame.
395 void HexagonFrameLowering::emitPrologue(MachineFunction &MF,
396                                         MachineBasicBlock &MBB) const {
397   auto &HST = static_cast<const HexagonSubtarget&>(MF.getSubtarget());
398   auto &HRI = *HST.getRegisterInfo();
399 
400   assert(&MF.front() == &MBB && "Shrink-wrapping not yet supported");
401   MachineFrameInfo *MFI = MF.getFrameInfo();
402   const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
403 
404   MachineBasicBlock *PrologB = &MF.front(), *EpilogB = nullptr;
405   if (EnableShrinkWrapping)
406     findShrunkPrologEpilog(MF, PrologB, EpilogB);
407 
408   insertCSRSpillsInBlock(*PrologB, CSI, HRI);
409   insertPrologueInBlock(*PrologB);
410 
411   if (EpilogB) {
412     insertCSRRestoresInBlock(*EpilogB, CSI, HRI);
413     insertEpilogueInBlock(*EpilogB);
414   } else {
415     for (auto &B : MF)
416       if (B.isReturnBlock())
417         insertCSRRestoresInBlock(B, CSI, HRI);
418 
419     for (auto &B : MF)
420       if (B.isReturnBlock())
421         insertEpilogueInBlock(B);
422   }
423 }
424 
425 
426 void HexagonFrameLowering::insertPrologueInBlock(MachineBasicBlock &MBB) const {
427   MachineFunction &MF = *MBB.getParent();
428   MachineFrameInfo *MFI = MF.getFrameInfo();
429   auto &HST = MF.getSubtarget<HexagonSubtarget>();
430   auto &HII = *HST.getInstrInfo();
431   auto &HRI = *HST.getRegisterInfo();
432   DebugLoc dl;
433 
434   unsigned MaxAlign = std::max(MFI->getMaxAlignment(), getStackAlignment());
435 
436   // Calculate the total stack frame size.
437   // Get the number of bytes to allocate from the FrameInfo.
438   unsigned FrameSize = MFI->getStackSize();
439   // Round up the max call frame size to the max alignment on the stack.
440   unsigned MaxCFA = alignTo(MFI->getMaxCallFrameSize(), MaxAlign);
441   MFI->setMaxCallFrameSize(MaxCFA);
442 
443   FrameSize = MaxCFA + alignTo(FrameSize, MaxAlign);
444   MFI->setStackSize(FrameSize);
445 
446   bool AlignStack = (MaxAlign > getStackAlignment());
447 
448   // Get the number of bytes to allocate from the FrameInfo.
449   unsigned NumBytes = MFI->getStackSize();
450   unsigned SP = HRI.getStackRegister();
451   unsigned MaxCF = MFI->getMaxCallFrameSize();
452   MachineBasicBlock::iterator InsertPt = MBB.begin();
453 
454   auto *FuncInfo = MF.getInfo<HexagonMachineFunctionInfo>();
455   auto &AdjustRegs = FuncInfo->getAllocaAdjustInsts();
456 
457   for (auto MI : AdjustRegs) {
458     assert((MI->getOpcode() == Hexagon::ALLOCA) && "Expected alloca");
459     expandAlloca(MI, HII, SP, MaxCF);
460     MI->eraseFromParent();
461   }
462 
463   if (!hasFP(MF))
464     return;
465 
466   // Check for overflow.
467   // Hexagon_TODO: Ugh! hardcoding. Is there an API that can be used?
468   const unsigned int ALLOCFRAME_MAX = 16384;
469 
470   // Create a dummy memory operand to avoid allocframe from being treated as
471   // a volatile memory reference.
472   MachineMemOperand *MMO =
473     MF.getMachineMemOperand(MachinePointerInfo(), MachineMemOperand::MOStore,
474                             4, 4);
475 
476   if (NumBytes >= ALLOCFRAME_MAX) {
477     // Emit allocframe(#0).
478     BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::S2_allocframe))
479       .addImm(0)
480       .addMemOperand(MMO);
481 
482     // Subtract offset from frame pointer.
483     // We use a caller-saved non-parameter register for that.
484     unsigned CallerSavedReg = HRI.getFirstCallerSavedNonParamReg();
485     BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::CONST32_Int_Real),
486             CallerSavedReg).addImm(NumBytes);
487     BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::A2_sub), SP)
488       .addReg(SP)
489       .addReg(CallerSavedReg);
490   } else {
491     BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::S2_allocframe))
492       .addImm(NumBytes)
493       .addMemOperand(MMO);
494   }
495 
496   if (AlignStack) {
497     BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::A2_andir), SP)
498         .addReg(SP)
499         .addImm(-int64_t(MaxAlign));
500   }
501 }
502 
503 void HexagonFrameLowering::insertEpilogueInBlock(MachineBasicBlock &MBB) const {
504   MachineFunction &MF = *MBB.getParent();
505   if (!hasFP(MF))
506     return;
507 
508   auto &HST = static_cast<const HexagonSubtarget&>(MF.getSubtarget());
509   auto &HII = *HST.getInstrInfo();
510   auto &HRI = *HST.getRegisterInfo();
511   unsigned SP = HRI.getStackRegister();
512 
513   MachineInstr *RetI = nullptr;
514   for (auto &I : MBB) {
515     if (!I.isReturn())
516       continue;
517     RetI = &I;
518     break;
519   }
520   unsigned RetOpc = RetI ? RetI->getOpcode() : 0;
521 
522   MachineBasicBlock::iterator InsertPt = MBB.getFirstTerminator();
523   DebugLoc DL;
524   if (InsertPt != MBB.end())
525     DL = InsertPt->getDebugLoc();
526   else if (!MBB.empty())
527     DL = std::prev(MBB.end())->getDebugLoc();
528 
529   // Handle EH_RETURN.
530   if (RetOpc == Hexagon::EH_RETURN_JMPR) {
531     BuildMI(MBB, InsertPt, DL, HII.get(Hexagon::L2_deallocframe));
532     BuildMI(MBB, InsertPt, DL, HII.get(Hexagon::A2_add), SP)
533         .addReg(SP)
534         .addReg(Hexagon::R28);
535     return;
536   }
537 
538   // Check for RESTORE_DEALLOC_RET* tail call. Don't emit an extra dealloc-
539   // frame instruction if we encounter it.
540   if (RetOpc == Hexagon::RESTORE_DEALLOC_RET_JMP_V4) {
541     MachineBasicBlock::iterator It = RetI;
542     ++It;
543     // Delete all instructions after the RESTORE (except labels).
544     while (It != MBB.end()) {
545       if (!It->isLabel())
546         It = MBB.erase(It);
547       else
548         ++It;
549     }
550     return;
551   }
552 
553   // It is possible that the restoring code is a call to a library function.
554   // All of the restore* functions include "deallocframe", so we need to make
555   // sure that we don't add an extra one.
556   bool NeedsDeallocframe = true;
557   if (!MBB.empty() && InsertPt != MBB.begin()) {
558     MachineBasicBlock::iterator PrevIt = std::prev(InsertPt);
559     unsigned COpc = PrevIt->getOpcode();
560     if (COpc == Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4)
561       NeedsDeallocframe = false;
562   }
563 
564   if (!NeedsDeallocframe)
565     return;
566   // If the returning instruction is JMPret, replace it with dealloc_return,
567   // otherwise just add deallocframe. The function could be returning via a
568   // tail call.
569   if (RetOpc != Hexagon::JMPret || DisableDeallocRet) {
570     BuildMI(MBB, InsertPt, DL, HII.get(Hexagon::L2_deallocframe));
571     return;
572   }
573   unsigned NewOpc = Hexagon::L4_return;
574   MachineInstr *NewI = BuildMI(MBB, RetI, DL, HII.get(NewOpc));
575   // Transfer the function live-out registers.
576   NewI->copyImplicitOps(MF, RetI);
577   MBB.erase(RetI);
578 }
579 
580 
581 namespace {
582   bool IsAllocFrame(MachineBasicBlock::const_iterator It) {
583     if (!It->isBundle())
584       return It->getOpcode() == Hexagon::S2_allocframe;
585     auto End = It->getParent()->instr_end();
586     MachineBasicBlock::const_instr_iterator I = It.getInstrIterator();
587     while (++I != End && I->isBundled())
588       if (I->getOpcode() == Hexagon::S2_allocframe)
589         return true;
590     return false;
591   }
592 
593   MachineBasicBlock::iterator FindAllocFrame(MachineBasicBlock &B) {
594     for (auto &I : B)
595       if (IsAllocFrame(I))
596         return I;
597     return B.end();
598   }
599 }
600 
601 
602 void HexagonFrameLowering::insertCFIInstructions(MachineFunction &MF) const {
603   for (auto &B : MF) {
604     auto AF = FindAllocFrame(B);
605     if (AF == B.end())
606       continue;
607     insertCFIInstructionsAt(B, ++AF);
608   }
609 }
610 
611 
612 void HexagonFrameLowering::insertCFIInstructionsAt(MachineBasicBlock &MBB,
613       MachineBasicBlock::iterator At) const {
614   MachineFunction &MF = *MBB.getParent();
615   MachineFrameInfo *MFI = MF.getFrameInfo();
616   MachineModuleInfo &MMI = MF.getMMI();
617   auto &HST = MF.getSubtarget<HexagonSubtarget>();
618   auto &HII = *HST.getInstrInfo();
619   auto &HRI = *HST.getRegisterInfo();
620 
621   // If CFI instructions have debug information attached, something goes
622   // wrong with the final assembly generation: the prolog_end is placed
623   // in a wrong location.
624   DebugLoc DL;
625   const MCInstrDesc &CFID = HII.get(TargetOpcode::CFI_INSTRUCTION);
626 
627   MCSymbol *FrameLabel = MMI.getContext().createTempSymbol();
628 
629   if (hasFP(MF)) {
630     unsigned DwFPReg = HRI.getDwarfRegNum(HRI.getFrameRegister(), true);
631     unsigned DwRAReg = HRI.getDwarfRegNum(HRI.getRARegister(), true);
632 
633     // Define CFA via an offset from the value of FP.
634     //
635     //  -8   -4    0 (SP)
636     // --+----+----+---------------------
637     //   | FP | LR |          increasing addresses -->
638     // --+----+----+---------------------
639     //   |         +-- Old SP (before allocframe)
640     //   +-- New FP (after allocframe)
641     //
642     // MCCFIInstruction::createDefCfa subtracts the offset from the register.
643     // MCCFIInstruction::createOffset takes the offset without sign change.
644     auto DefCfa = MCCFIInstruction::createDefCfa(FrameLabel, DwFPReg, -8);
645     BuildMI(MBB, At, DL, CFID)
646         .addCFIIndex(MMI.addFrameInst(DefCfa));
647     // R31 (return addr) = CFA - 4
648     auto OffR31 = MCCFIInstruction::createOffset(FrameLabel, DwRAReg, -4);
649     BuildMI(MBB, At, DL, CFID)
650         .addCFIIndex(MMI.addFrameInst(OffR31));
651     // R30 (frame ptr) = CFA - 8
652     auto OffR30 = MCCFIInstruction::createOffset(FrameLabel, DwFPReg, -8);
653     BuildMI(MBB, At, DL, CFID)
654         .addCFIIndex(MMI.addFrameInst(OffR30));
655   }
656 
657   static unsigned int RegsToMove[] = {
658     Hexagon::R1,  Hexagon::R0,  Hexagon::R3,  Hexagon::R2,
659     Hexagon::R17, Hexagon::R16, Hexagon::R19, Hexagon::R18,
660     Hexagon::R21, Hexagon::R20, Hexagon::R23, Hexagon::R22,
661     Hexagon::R25, Hexagon::R24, Hexagon::R27, Hexagon::R26,
662     Hexagon::D0,  Hexagon::D1,  Hexagon::D8,  Hexagon::D9,
663     Hexagon::D10, Hexagon::D11, Hexagon::D12, Hexagon::D13,
664     Hexagon::NoRegister
665   };
666 
667   const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
668 
669   for (unsigned i = 0; RegsToMove[i] != Hexagon::NoRegister; ++i) {
670     unsigned Reg = RegsToMove[i];
671     auto IfR = [Reg] (const CalleeSavedInfo &C) -> bool {
672       return C.getReg() == Reg;
673     };
674     auto F = std::find_if(CSI.begin(), CSI.end(), IfR);
675     if (F == CSI.end())
676       continue;
677 
678     // Subtract 8 to make room for R30 and R31, which are added above.
679     unsigned FrameReg;
680     int64_t Offset = getFrameIndexReference(MF, F->getFrameIdx(), FrameReg) - 8;
681 
682     if (Reg < Hexagon::D0 || Reg > Hexagon::D15) {
683       unsigned DwarfReg = HRI.getDwarfRegNum(Reg, true);
684       auto OffReg = MCCFIInstruction::createOffset(FrameLabel, DwarfReg,
685                                                    Offset);
686       BuildMI(MBB, At, DL, CFID)
687           .addCFIIndex(MMI.addFrameInst(OffReg));
688     } else {
689       // Split the double regs into subregs, and generate appropriate
690       // cfi_offsets.
691       // The only reason, we are split double regs is, llvm-mc does not
692       // understand paired registers for cfi_offset.
693       // Eg .cfi_offset r1:0, -64
694 
695       unsigned HiReg = HRI.getSubReg(Reg, Hexagon::subreg_hireg);
696       unsigned LoReg = HRI.getSubReg(Reg, Hexagon::subreg_loreg);
697       unsigned HiDwarfReg = HRI.getDwarfRegNum(HiReg, true);
698       unsigned LoDwarfReg = HRI.getDwarfRegNum(LoReg, true);
699       auto OffHi = MCCFIInstruction::createOffset(FrameLabel, HiDwarfReg,
700                                                   Offset+4);
701       BuildMI(MBB, At, DL, CFID)
702           .addCFIIndex(MMI.addFrameInst(OffHi));
703       auto OffLo = MCCFIInstruction::createOffset(FrameLabel, LoDwarfReg,
704                                                   Offset);
705       BuildMI(MBB, At, DL, CFID)
706           .addCFIIndex(MMI.addFrameInst(OffLo));
707     }
708   }
709 }
710 
711 
712 bool HexagonFrameLowering::hasFP(const MachineFunction &MF) const {
713   auto &MFI = *MF.getFrameInfo();
714   auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
715 
716   bool HasFixed = MFI.getNumFixedObjects();
717   bool HasPrealloc = const_cast<MachineFrameInfo&>(MFI)
718                         .getLocalFrameObjectCount();
719   bool HasExtraAlign = HRI.needsStackRealignment(MF);
720   bool HasAlloca = MFI.hasVarSizedObjects();
721 
722   // Insert ALLOCFRAME if we need to or at -O0 for the debugger.  Think
723   // that this shouldn't be required, but doing so now because gcc does and
724   // gdb can't break at the start of the function without it.  Will remove if
725   // this turns out to be a gdb bug.
726   //
727   if (MF.getTarget().getOptLevel() == CodeGenOpt::None)
728     return true;
729 
730   // By default we want to use SP (since it's always there). FP requires
731   // some setup (i.e. ALLOCFRAME).
732   // Fixed and preallocated objects need FP if the distance from them to
733   // the SP is unknown (as is with alloca or aligna).
734   if ((HasFixed || HasPrealloc) && (HasAlloca || HasExtraAlign))
735     return true;
736 
737   if (MFI.getStackSize() > 0) {
738     if (UseAllocframe)
739       return true;
740   }
741 
742   if (MFI.hasCalls() ||
743       MF.getInfo<HexagonMachineFunctionInfo>()->hasClobberLR())
744     return true;
745 
746   return false;
747 }
748 
749 
750 enum SpillKind {
751   SK_ToMem,
752   SK_FromMem,
753   SK_FromMemTailcall
754 };
755 
756 static const char *
757 getSpillFunctionFor(unsigned MaxReg, SpillKind SpillType) {
758   const char * V4SpillToMemoryFunctions[] = {
759     "__save_r16_through_r17",
760     "__save_r16_through_r19",
761     "__save_r16_through_r21",
762     "__save_r16_through_r23",
763     "__save_r16_through_r25",
764     "__save_r16_through_r27" };
765 
766   const char * V4SpillFromMemoryFunctions[] = {
767     "__restore_r16_through_r17_and_deallocframe",
768     "__restore_r16_through_r19_and_deallocframe",
769     "__restore_r16_through_r21_and_deallocframe",
770     "__restore_r16_through_r23_and_deallocframe",
771     "__restore_r16_through_r25_and_deallocframe",
772     "__restore_r16_through_r27_and_deallocframe" };
773 
774   const char * V4SpillFromMemoryTailcallFunctions[] = {
775     "__restore_r16_through_r17_and_deallocframe_before_tailcall",
776     "__restore_r16_through_r19_and_deallocframe_before_tailcall",
777     "__restore_r16_through_r21_and_deallocframe_before_tailcall",
778     "__restore_r16_through_r23_and_deallocframe_before_tailcall",
779     "__restore_r16_through_r25_and_deallocframe_before_tailcall",
780     "__restore_r16_through_r27_and_deallocframe_before_tailcall"
781   };
782 
783   const char **SpillFunc = nullptr;
784 
785   switch(SpillType) {
786   case SK_ToMem:
787     SpillFunc = V4SpillToMemoryFunctions;
788     break;
789   case SK_FromMem:
790     SpillFunc = V4SpillFromMemoryFunctions;
791     break;
792   case SK_FromMemTailcall:
793     SpillFunc = V4SpillFromMemoryTailcallFunctions;
794     break;
795   }
796   assert(SpillFunc && "Unknown spill kind");
797 
798   // Spill all callee-saved registers up to the highest register used.
799   switch (MaxReg) {
800   case Hexagon::R17:
801     return SpillFunc[0];
802   case Hexagon::R19:
803     return SpillFunc[1];
804   case Hexagon::R21:
805     return SpillFunc[2];
806   case Hexagon::R23:
807     return SpillFunc[3];
808   case Hexagon::R25:
809     return SpillFunc[4];
810   case Hexagon::R27:
811     return SpillFunc[5];
812   default:
813     llvm_unreachable("Unhandled maximum callee save register");
814   }
815   return 0;
816 }
817 
818 /// Adds all callee-saved registers up to MaxReg to the instruction.
819 static void addCalleeSaveRegistersAsImpOperand(MachineInstr *Inst,
820                                            unsigned MaxReg, bool IsDef) {
821   // Add the callee-saved registers as implicit uses.
822   for (unsigned R = Hexagon::R16; R <= MaxReg; ++R) {
823     MachineOperand ImpUse = MachineOperand::CreateReg(R, IsDef, true);
824     Inst->addOperand(ImpUse);
825   }
826 }
827 
828 
829 int HexagonFrameLowering::getFrameIndexReference(const MachineFunction &MF,
830       int FI, unsigned &FrameReg) const {
831   auto &MFI = *MF.getFrameInfo();
832   auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
833 
834   // Large parts of this code are shared with HRI::eliminateFrameIndex.
835   int Offset = MFI.getObjectOffset(FI);
836   bool HasAlloca = MFI.hasVarSizedObjects();
837   bool HasExtraAlign = HRI.needsStackRealignment(MF);
838   bool NoOpt = MF.getTarget().getOptLevel() == CodeGenOpt::None;
839 
840   unsigned SP = HRI.getStackRegister(), FP = HRI.getFrameRegister();
841   unsigned AP = 0;
842   if (const MachineInstr *AI = getAlignaInstr(MF))
843     AP = AI->getOperand(0).getReg();
844   unsigned FrameSize = MFI.getStackSize();
845 
846   bool UseFP = false, UseAP = false;  // Default: use SP (except at -O0).
847   // Use FP at -O0, except when there are objects with extra alignment.
848   // That additional alignment requirement may cause a pad to be inserted,
849   // which will make it impossible to use FP to access objects located
850   // past the pad.
851   if (NoOpt && !HasExtraAlign)
852     UseFP = true;
853   if (MFI.isFixedObjectIndex(FI) || MFI.isObjectPreAllocated(FI)) {
854     // Fixed and preallocated objects will be located before any padding
855     // so FP must be used to access them.
856     UseFP |= (HasAlloca || HasExtraAlign);
857   } else {
858     if (HasAlloca) {
859       if (HasExtraAlign)
860         UseAP = true;
861       else
862         UseFP = true;
863     }
864   }
865 
866   // If FP was picked, then there had better be FP.
867   bool HasFP = hasFP(MF);
868   assert((HasFP || !UseFP) && "This function must have frame pointer");
869 
870   // Having FP implies allocframe. Allocframe will store extra 8 bytes:
871   // FP/LR. If the base register is used to access an object across these
872   // 8 bytes, then the offset will need to be adjusted by 8.
873   //
874   // After allocframe:
875   //                    HexagonISelLowering adds 8 to ---+
876   //                    the offsets of all stack-based   |
877   //                    arguments (*)                    |
878   //                                                     |
879   //   getObjectOffset < 0   0     8  getObjectOffset >= 8
880   // ------------------------+-----+------------------------> increasing
881   //     <local objects>     |FP/LR|    <input arguments>     addresses
882   // -----------------+------+-----+------------------------>
883   //                  |      |
884   //    SP/AP point --+      +-- FP points here (**)
885   //    somewhere on
886   //    this side of FP/LR
887   //
888   // (*) See LowerFormalArguments. The FP/LR is assumed to be present.
889   // (**) *FP == old-FP. FP+0..7 are the bytes of FP/LR.
890 
891   // The lowering assumes that FP/LR is present, and so the offsets of
892   // the formal arguments start at 8. If FP/LR is not there we need to
893   // reduce the offset by 8.
894   if (Offset > 0 && !HasFP)
895     Offset -= 8;
896 
897   if (UseFP)
898     FrameReg = FP;
899   else if (UseAP)
900     FrameReg = AP;
901   else
902     FrameReg = SP;
903 
904   // Calculate the actual offset in the instruction. If there is no FP
905   // (in other words, no allocframe), then SP will not be adjusted (i.e.
906   // there will be no SP -= FrameSize), so the frame size should not be
907   // added to the calculated offset.
908   int RealOffset = Offset;
909   if (!UseFP && !UseAP && HasFP)
910     RealOffset = FrameSize+Offset;
911   return RealOffset;
912 }
913 
914 
915 bool HexagonFrameLowering::insertCSRSpillsInBlock(MachineBasicBlock &MBB,
916       const CSIVect &CSI, const HexagonRegisterInfo &HRI) const {
917   if (CSI.empty())
918     return true;
919 
920   MachineBasicBlock::iterator MI = MBB.begin();
921   MachineFunction &MF = *MBB.getParent();
922   auto &HII = *MF.getSubtarget<HexagonSubtarget>().getInstrInfo();
923 
924   if (useSpillFunction(MF, CSI)) {
925     unsigned MaxReg = getMaxCalleeSavedReg(CSI, HRI);
926     const char *SpillFun = getSpillFunctionFor(MaxReg, SK_ToMem);
927     // Call spill function.
928     DebugLoc DL = MI != MBB.end() ? MI->getDebugLoc() : DebugLoc();
929     MachineInstr *SaveRegsCall =
930         BuildMI(MBB, MI, DL, HII.get(Hexagon::SAVE_REGISTERS_CALL_V4))
931           .addExternalSymbol(SpillFun);
932     // Add callee-saved registers as use.
933     addCalleeSaveRegistersAsImpOperand(SaveRegsCall, MaxReg, false);
934     // Add live in registers.
935     for (unsigned I = 0; I < CSI.size(); ++I)
936       MBB.addLiveIn(CSI[I].getReg());
937     return true;
938   }
939 
940   for (unsigned i = 0, n = CSI.size(); i < n; ++i) {
941     unsigned Reg = CSI[i].getReg();
942     // Add live in registers. We treat eh_return callee saved register r0 - r3
943     // specially. They are not really callee saved registers as they are not
944     // supposed to be killed.
945     bool IsKill = !HRI.isEHReturnCalleeSaveReg(Reg);
946     int FI = CSI[i].getFrameIdx();
947     const TargetRegisterClass *RC = HRI.getMinimalPhysRegClass(Reg);
948     HII.storeRegToStackSlot(MBB, MI, Reg, IsKill, FI, RC, &HRI);
949     if (IsKill)
950       MBB.addLiveIn(Reg);
951   }
952   return true;
953 }
954 
955 
956 bool HexagonFrameLowering::insertCSRRestoresInBlock(MachineBasicBlock &MBB,
957       const CSIVect &CSI, const HexagonRegisterInfo &HRI) const {
958   if (CSI.empty())
959     return false;
960 
961   MachineBasicBlock::iterator MI = MBB.getFirstTerminator();
962   MachineFunction &MF = *MBB.getParent();
963   auto &HII = *MF.getSubtarget<HexagonSubtarget>().getInstrInfo();
964 
965   if (useRestoreFunction(MF, CSI)) {
966     bool HasTC = hasTailCall(MBB) || !hasReturn(MBB);
967     unsigned MaxR = getMaxCalleeSavedReg(CSI, HRI);
968     SpillKind Kind = HasTC ? SK_FromMemTailcall : SK_FromMem;
969     const char *RestoreFn = getSpillFunctionFor(MaxR, Kind);
970 
971     // Call spill function.
972     DebugLoc DL = MI != MBB.end() ? MI->getDebugLoc()
973                                   : MBB.getLastNonDebugInstr()->getDebugLoc();
974     MachineInstr *DeallocCall = nullptr;
975 
976     if (HasTC) {
977       unsigned ROpc = Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4;
978       DeallocCall = BuildMI(MBB, MI, DL, HII.get(ROpc))
979           .addExternalSymbol(RestoreFn);
980     } else {
981       // The block has a return.
982       MachineBasicBlock::iterator It = MBB.getFirstTerminator();
983       assert(It->isReturn() && std::next(It) == MBB.end());
984       unsigned ROpc = Hexagon::RESTORE_DEALLOC_RET_JMP_V4;
985       DeallocCall = BuildMI(MBB, It, DL, HII.get(ROpc))
986           .addExternalSymbol(RestoreFn);
987       // Transfer the function live-out registers.
988       DeallocCall->copyImplicitOps(MF, It);
989     }
990     addCalleeSaveRegistersAsImpOperand(DeallocCall, MaxR, true);
991     return true;
992   }
993 
994   for (unsigned i = 0; i < CSI.size(); ++i) {
995     unsigned Reg = CSI[i].getReg();
996     const TargetRegisterClass *RC = HRI.getMinimalPhysRegClass(Reg);
997     int FI = CSI[i].getFrameIdx();
998     HII.loadRegFromStackSlot(MBB, MI, Reg, FI, RC, &HRI);
999   }
1000   return true;
1001 }
1002 
1003 
1004 void HexagonFrameLowering::eliminateCallFramePseudoInstr(MachineFunction &MF,
1005       MachineBasicBlock &MBB, MachineBasicBlock::iterator I) const {
1006   MachineInstr &MI = *I;
1007   unsigned Opc = MI.getOpcode();
1008   (void)Opc; // Silence compiler warning.
1009   assert((Opc == Hexagon::ADJCALLSTACKDOWN || Opc == Hexagon::ADJCALLSTACKUP) &&
1010          "Cannot handle this call frame pseudo instruction");
1011   MBB.erase(I);
1012 }
1013 
1014 
1015 void HexagonFrameLowering::processFunctionBeforeFrameFinalized(
1016     MachineFunction &MF, RegScavenger *RS) const {
1017   // If this function has uses aligned stack and also has variable sized stack
1018   // objects, then we need to map all spill slots to fixed positions, so that
1019   // they can be accessed through FP. Otherwise they would have to be accessed
1020   // via AP, which may not be available at the particular place in the program.
1021   MachineFrameInfo *MFI = MF.getFrameInfo();
1022   bool HasAlloca = MFI->hasVarSizedObjects();
1023   bool NeedsAlign = (MFI->getMaxAlignment() > getStackAlignment());
1024 
1025   if (!HasAlloca || !NeedsAlign)
1026     return;
1027 
1028   unsigned LFS = MFI->getLocalFrameSize();
1029   int Offset = -LFS;
1030   for (int i = 0, e = MFI->getObjectIndexEnd(); i != e; ++i) {
1031     if (!MFI->isSpillSlotObjectIndex(i) || MFI->isDeadObjectIndex(i))
1032       continue;
1033     int S = MFI->getObjectSize(i);
1034     LFS += S;
1035     Offset -= S;
1036     MFI->mapLocalFrameObject(i, Offset);
1037   }
1038 
1039   MFI->setLocalFrameSize(LFS);
1040   unsigned A = MFI->getLocalFrameMaxAlign();
1041   assert(A <= 8 && "Unexpected local frame alignment");
1042   if (A == 0)
1043     MFI->setLocalFrameMaxAlign(8);
1044   MFI->setUseLocalStackAllocationBlock(true);
1045 }
1046 
1047 /// Returns true if there is no caller saved registers available.
1048 static bool needToReserveScavengingSpillSlots(MachineFunction &MF,
1049                                               const HexagonRegisterInfo &HRI) {
1050   MachineRegisterInfo &MRI = MF.getRegInfo();
1051   const MCPhysReg *CallerSavedRegs = HRI.getCallerSavedRegs(&MF);
1052   // Check for an unused caller-saved register.
1053   for ( ; *CallerSavedRegs; ++CallerSavedRegs) {
1054     MCPhysReg FreeReg = *CallerSavedRegs;
1055     if (!MRI.reg_nodbg_empty(FreeReg))
1056       continue;
1057 
1058     // Check aliased register usage.
1059     bool IsCurrentRegUsed = false;
1060     for (MCRegAliasIterator AI(FreeReg, &HRI, false); AI.isValid(); ++AI)
1061       if (!MRI.reg_nodbg_empty(*AI)) {
1062         IsCurrentRegUsed = true;
1063         break;
1064       }
1065     if (IsCurrentRegUsed)
1066       continue;
1067 
1068     // Neither directly used nor used through an aliased register.
1069     return false;
1070   }
1071   // All caller-saved registers are used.
1072   return true;
1073 }
1074 
1075 
1076 /// Find a GPR register that's available in the range from It to any use of
1077 /// the 'spill' in FI.
1078 static bool findAvailableReg(int FI, MachineBasicBlock::iterator It,
1079                              MachineBasicBlock::iterator End,
1080                              unsigned *AvailReg,
1081                              unsigned *NumUses,
1082                              const TargetRegisterInfo *TRI,
1083                              RegScavenger *Scavenger) {
1084   assert(Scavenger->getCurrentPosition() == It &&
1085          "Unexpected scavenger position!");
1086 
1087   BitVector Avail(Scavenger->getRegsAvailable(&Hexagon::IntRegsRegClass));
1088   if (Avail.none())
1089     return false;
1090 
1091   BitVector AvailByLastLoad(Avail.size());
1092 
1093   while (++It != End) {
1094     MachineInstr *MI = It;
1095     if (MI->isDebugValue())
1096       continue;
1097 
1098     // Remove all registers modified by this inst from Avail
1099     int Reg = Avail.find_first();
1100     while (Reg != -1) {
1101       if (MI->modifiesRegister(Reg, TRI))
1102         Avail[Reg] = false;
1103       else
1104         assert(!MI->readsRegister(Reg, TRI) && "Inst reads undefined register");
1105 
1106       Reg = Avail.find_next(Reg);
1107     }
1108 
1109     int Opc = MI->getOpcode();
1110     // Stop if we find a store that overwrites the current spill in FI
1111     if ((Opc == Hexagon::STriw_pred || Opc == Hexagon::STriw_mod) &&
1112         MI->getOperand(0).getIndex() == FI)
1113       break;
1114 
1115     if ((Opc == Hexagon::LDriw_pred || Opc == Hexagon::LDriw_mod) &&
1116         MI->getOperand(1).getIndex() == FI && !MI->getOperand(0).isDead()) {
1117       AvailByLastLoad = Avail;
1118       ++(*NumUses);
1119     }
1120 
1121     // Give up early if there are no registers available
1122     if (AvailByLastLoad.none() && Avail.none())
1123       break;
1124   }
1125 
1126   if (AvailByLastLoad.none())
1127     return false;
1128 
1129   *AvailReg = (unsigned) AvailByLastLoad.find_first();
1130   return true;
1131 }
1132 
1133 
1134 
1135 void HexagonFrameLowering::determineCalleeSaves(MachineFunction &MF,
1136                                                 BitVector &SavedRegs,
1137                                                 RegScavenger *RS) const {
1138   TargetFrameLowering::determineCalleeSaves(MF, SavedRegs, RS);
1139 
1140   auto &HST = static_cast<const HexagonSubtarget&>(MF.getSubtarget());
1141   auto &HRI = *HST.getRegisterInfo();
1142 
1143   bool HasEHReturn = MF.getInfo<HexagonMachineFunctionInfo>()->hasEHReturn();
1144 
1145   // If we have a function containing __builtin_eh_return we want to spill and
1146   // restore all callee saved registers. Pretend that they are used.
1147   if (HasEHReturn) {
1148     for (const MCPhysReg *CSRegs = HRI.getCalleeSavedRegs(&MF); *CSRegs;
1149          ++CSRegs)
1150       SavedRegs.set(*CSRegs);
1151   }
1152 
1153   const TargetRegisterClass &RC = Hexagon::IntRegsRegClass;
1154 
1155   // Replace predicate register pseudo spill code.
1156   bool HasReplacedPseudoInst = replacePseudoRegTransferCode(MF);
1157 
1158   // We need to reserve a a spill slot if scavenging could potentially require
1159   // spilling a scavenged register.
1160   if (HasReplacedPseudoInst && needToReserveScavengingSpillSlots(MF, HRI)) {
1161     MachineFrameInfo *MFI = MF.getFrameInfo();
1162     for (int i = 0; i < NumberScavengerSlots; i++)
1163       RS->addScavengingFrameIndex(
1164         MFI->CreateSpillStackObject(RC.getSize(), RC.getAlignment()));
1165   }
1166 }
1167 
1168 
1169 #ifndef NDEBUG
1170 static void dump_registers(BitVector &Regs, const TargetRegisterInfo &TRI) {
1171   dbgs() << '{';
1172   for (int x = Regs.find_first(); x >= 0; x = Regs.find_next(x)) {
1173     unsigned R = x;
1174     dbgs() << ' ' << PrintReg(R, &TRI);
1175   }
1176   dbgs() << " }";
1177 }
1178 #endif
1179 
1180 
1181 bool HexagonFrameLowering::assignCalleeSavedSpillSlots(MachineFunction &MF,
1182       const TargetRegisterInfo *TRI, std::vector<CalleeSavedInfo> &CSI) const {
1183   DEBUG(dbgs() << LLVM_FUNCTION_NAME << " on "
1184                << MF.getFunction()->getName() << '\n');
1185   MachineFrameInfo *MFI = MF.getFrameInfo();
1186   BitVector SRegs(Hexagon::NUM_TARGET_REGS);
1187 
1188   // Generate a set of unique, callee-saved registers (SRegs), where each
1189   // register in the set is maximal in terms of sub-/super-register relation,
1190   // i.e. for each R in SRegs, no proper super-register of R is also in SRegs.
1191 
1192   // (1) For each callee-saved register, add that register and all of its
1193   // sub-registers to SRegs.
1194   DEBUG(dbgs() << "Initial CS registers: {");
1195   for (unsigned i = 0, n = CSI.size(); i < n; ++i) {
1196     unsigned R = CSI[i].getReg();
1197     DEBUG(dbgs() << ' ' << PrintReg(R, TRI));
1198     for (MCSubRegIterator SR(R, TRI, true); SR.isValid(); ++SR)
1199       SRegs[*SR] = true;
1200   }
1201   DEBUG(dbgs() << " }\n");
1202   DEBUG(dbgs() << "SRegs.1: "; dump_registers(SRegs, *TRI); dbgs() << "\n");
1203 
1204   // (2) For each reserved register, remove that register and all of its
1205   // sub- and super-registers from SRegs.
1206   BitVector Reserved = TRI->getReservedRegs(MF);
1207   for (int x = Reserved.find_first(); x >= 0; x = Reserved.find_next(x)) {
1208     unsigned R = x;
1209     for (MCSuperRegIterator SR(R, TRI, true); SR.isValid(); ++SR)
1210       SRegs[*SR] = false;
1211   }
1212   DEBUG(dbgs() << "Res:     "; dump_registers(Reserved, *TRI); dbgs() << "\n");
1213   DEBUG(dbgs() << "SRegs.2: "; dump_registers(SRegs, *TRI); dbgs() << "\n");
1214 
1215   // (3) Collect all registers that have at least one sub-register in SRegs,
1216   // and also have no sub-registers that are reserved. These will be the can-
1217   // didates for saving as a whole instead of their individual sub-registers.
1218   // (Saving R17:16 instead of R16 is fine, but only if R17 was not reserved.)
1219   BitVector TmpSup(Hexagon::NUM_TARGET_REGS);
1220   for (int x = SRegs.find_first(); x >= 0; x = SRegs.find_next(x)) {
1221     unsigned R = x;
1222     for (MCSuperRegIterator SR(R, TRI); SR.isValid(); ++SR)
1223       TmpSup[*SR] = true;
1224   }
1225   for (int x = TmpSup.find_first(); x >= 0; x = TmpSup.find_next(x)) {
1226     unsigned R = x;
1227     for (MCSubRegIterator SR(R, TRI, true); SR.isValid(); ++SR) {
1228       if (!Reserved[*SR])
1229         continue;
1230       TmpSup[R] = false;
1231       break;
1232     }
1233   }
1234   DEBUG(dbgs() << "TmpSup:  "; dump_registers(TmpSup, *TRI); dbgs() << "\n");
1235 
1236   // (4) Include all super-registers found in (3) into SRegs.
1237   SRegs |= TmpSup;
1238   DEBUG(dbgs() << "SRegs.4: "; dump_registers(SRegs, *TRI); dbgs() << "\n");
1239 
1240   // (5) For each register R in SRegs, if any super-register of R is in SRegs,
1241   // remove R from SRegs.
1242   for (int x = SRegs.find_first(); x >= 0; x = SRegs.find_next(x)) {
1243     unsigned R = x;
1244     for (MCSuperRegIterator SR(R, TRI); SR.isValid(); ++SR) {
1245       if (!SRegs[*SR])
1246         continue;
1247       SRegs[R] = false;
1248       break;
1249     }
1250   }
1251   DEBUG(dbgs() << "SRegs.5: "; dump_registers(SRegs, *TRI); dbgs() << "\n");
1252 
1253   // Now, for each register that has a fixed stack slot, create the stack
1254   // object for it.
1255   CSI.clear();
1256 
1257   typedef TargetFrameLowering::SpillSlot SpillSlot;
1258   unsigned NumFixed;
1259   int MinOffset = 0;  // CS offsets are negative.
1260   const SpillSlot *FixedSlots = getCalleeSavedSpillSlots(NumFixed);
1261   for (const SpillSlot *S = FixedSlots; S != FixedSlots+NumFixed; ++S) {
1262     if (!SRegs[S->Reg])
1263       continue;
1264     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(S->Reg);
1265     int FI = MFI->CreateFixedSpillStackObject(RC->getSize(), S->Offset);
1266     MinOffset = std::min(MinOffset, S->Offset);
1267     CSI.push_back(CalleeSavedInfo(S->Reg, FI));
1268     SRegs[S->Reg] = false;
1269   }
1270 
1271   // There can be some registers that don't have fixed slots. For example,
1272   // we need to store R0-R3 in functions with exception handling. For each
1273   // such register, create a non-fixed stack object.
1274   for (int x = SRegs.find_first(); x >= 0; x = SRegs.find_next(x)) {
1275     unsigned R = x;
1276     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(R);
1277     int Off = MinOffset - RC->getSize();
1278     unsigned Align = std::min(RC->getAlignment(), getStackAlignment());
1279     assert(isPowerOf2_32(Align));
1280     Off &= -Align;
1281     int FI = MFI->CreateFixedSpillStackObject(RC->getSize(), Off);
1282     MinOffset = std::min(MinOffset, Off);
1283     CSI.push_back(CalleeSavedInfo(R, FI));
1284     SRegs[R] = false;
1285   }
1286 
1287   DEBUG({
1288     dbgs() << "CS information: {";
1289     for (unsigned i = 0, n = CSI.size(); i < n; ++i) {
1290       int FI = CSI[i].getFrameIdx();
1291       int Off = MFI->getObjectOffset(FI);
1292       dbgs() << ' ' << PrintReg(CSI[i].getReg(), TRI) << ":fi#" << FI << ":sp";
1293       if (Off >= 0)
1294         dbgs() << '+';
1295       dbgs() << Off;
1296     }
1297     dbgs() << " }\n";
1298   });
1299 
1300 #ifndef NDEBUG
1301   // Verify that all registers were handled.
1302   bool MissedReg = false;
1303   for (int x = SRegs.find_first(); x >= 0; x = SRegs.find_next(x)) {
1304     unsigned R = x;
1305     dbgs() << PrintReg(R, TRI) << ' ';
1306     MissedReg = true;
1307   }
1308   if (MissedReg)
1309     llvm_unreachable("...there are unhandled callee-saved registers!");
1310 #endif
1311 
1312   return true;
1313 }
1314 
1315 
1316 /// Expands pseudo instructions that copy/spill/restore registers that cannot
1317 /// have these operations done directly. For spills/restores, it will attempt
1318 /// to spill into a general-purpose register, instead of spilling to memory.
1319 bool HexagonFrameLowering::replacePseudoRegTransferCode(MachineFunction &MF)
1320       const {
1321   auto &HST = static_cast<const HexagonSubtarget&>(MF.getSubtarget());
1322   auto &HII = *HST.getInstrInfo();
1323   auto &HRI = *HST.getRegisterInfo();
1324   MachineRegisterInfo &MRI = MF.getRegInfo();
1325   bool HasReplacedPseudoInst = false;
1326 
1327   // We use the register scavenger purely for tracking of available registers
1328   // here, but do the 'scavenging' on our own.
1329   RegScavenger Scavenger;
1330 
1331   // Map from PredReg spill FIs to GPRs and remaining number of uses
1332   DenseMap<int,std::pair<unsigned, unsigned>> FItoRegUses;
1333 
1334   // PredReg FIs that cannot be 'spilled' into GPRs because they are live
1335   // across BB boundaries.
1336   SmallSet<int, 8> AlwaysSpill;
1337 
1338   // Pred Reg FIs that have been spilled in a block due to shortage of GPRs
1339   SmallSet<int, 8> LocallySpilled;
1340 
1341   // Do an SCC traversal of the MachineFunction. This is to make sure we detect
1342   // cases where a PredReg *must* be spilled to memory because it is live across
1343   // BasicBlock boundaries: we see the reload before the spill and can mark the
1344   // PredReg's FI in AlwaysSpill.
1345   for (auto It = scc_begin(&MF); !It.isAtEnd(); ++It) {
1346     const std::vector<MachineBasicBlock *> &Scc = *It;
1347     for (MachineBasicBlock *MBB : Scc) {
1348       if (MBB->empty())
1349         continue;
1350 
1351       Scavenger.enterBasicBlock(MBB);
1352       Scavenger.forward();
1353 
1354       LocallySpilled.clear();
1355 
1356       // Traverse the basic block.
1357       MachineBasicBlock::iterator NextII;
1358       for (auto MII = MBB->begin(); MII != MBB->end(); MII = NextII) {
1359         MachineInstr *MI = MII;
1360         NextII = std::next(MII);
1361 
1362         assert(Scavenger.getCurrentPosition() == MII &&
1363             "Unexpected scavenger position");
1364 
1365         unsigned Opc = MI->getOpcode();
1366         DebugLoc DL = MI->getDebugLoc();
1367 
1368         if (Opc == TargetOpcode::COPY) {
1369           unsigned DestReg = MI->getOperand(0).getReg();
1370           unsigned SrcReg = MI->getOperand(1).getReg();
1371           MachineInstr *EraseMI = nullptr;
1372           if (Hexagon::ModRegsRegClass.contains(DestReg) &&
1373               Hexagon::ModRegsRegClass.contains(SrcReg)) {
1374             unsigned T = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
1375             BuildMI(*MBB, MII, DL, HII.get(TargetOpcode::COPY), T)
1376               .addOperand(MI->getOperand(1));
1377             BuildMI(*MBB, MII, DL, HII.get(TargetOpcode::COPY), DestReg)
1378               .addReg(T, RegState::Kill);
1379             EraseMI = &*MII;
1380             HasReplacedPseudoInst = true;
1381           }
1382           if (NextII != MBB->end())
1383             Scavenger.forward(); // Move to next instruction
1384           if (EraseMI)
1385             MBB->erase(EraseMI);
1386         } else if (Opc == Hexagon::STriw_pred || Opc == Hexagon::STriw_mod) {
1387           // STriw_pred FI, 0, SrcReg
1388           unsigned SrcReg = MI->getOperand(2).getReg();
1389           bool IsOrigSrcRegKilled = MI->getOperand(2).isKill();
1390 
1391           assert(MI->getOperand(0).isFI() && "Expect a frame index");
1392           assert((Hexagon::PredRegsRegClass.contains(SrcReg) ||
1393                   Hexagon::ModRegsRegClass.contains(SrcReg)) &&
1394               "Not a predicate or modifier register");
1395           int FI = MI->getOperand(0).getIndex();
1396 
1397           assert(!FItoRegUses.count(FI) &&
1398               "Still expecting a load of this spilled predicate register!");
1399 
1400           // Check whether we have an available GPR here and all the way to the
1401           // reload(s) of this spill
1402           unsigned AvailReg, NumUses = 0;
1403           if (!AlwaysSpill.count(FI) && findAvailableReg(FI, MII, MBB->end(),
1404                 &AvailReg, &NumUses, &HRI, &Scavenger)) {
1405             // Found a register we can move this into instead of spilling
1406             if (Opc == Hexagon::STriw_pred)
1407               BuildMI(*MBB, MII, MI->getDebugLoc(), HII.get(Hexagon::C2_tfrpr),
1408                   AvailReg).addReg(SrcReg, getKillRegState(IsOrigSrcRegKilled));
1409             else
1410               BuildMI(*MBB, MII, MI->getDebugLoc(), HII.get(Hexagon::A2_tfrcrr),
1411                   AvailReg).addReg(SrcReg, getKillRegState(IsOrigSrcRegKilled));
1412 
1413             // Mark the register as used in the function (important for callee
1414             // saved registers).
1415             BitVector UsedPhysRegsMask = MRI.getUsedPhysRegsMask();
1416             UsedPhysRegsMask.set(AvailReg);
1417             MRI.setUsedPhysRegMask(UsedPhysRegsMask);
1418 
1419             Scavenger.setRegUsed(AvailReg);
1420             if (NextII != MBB->end())
1421               Scavenger.forward();
1422 
1423             FItoRegUses[FI] = std::make_pair(AvailReg, NumUses);
1424             LocallySpilled.erase(FI);
1425 
1426             MBB->erase(MII);
1427           } else {
1428             // No register available. Insert actual spill.
1429             //   VirtReg = C2_tfrpr SrcPredReg
1430             unsigned VirtReg =
1431               MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
1432             if (Opc == Hexagon::STriw_pred)
1433               BuildMI(*MBB, MII, MI->getDebugLoc(), HII.get(Hexagon::C2_tfrpr),
1434                   VirtReg).addReg(SrcReg, getKillRegState(IsOrigSrcRegKilled));
1435             else
1436               BuildMI(*MBB, MII, MI->getDebugLoc(), HII.get(Hexagon::A2_tfrcrr),
1437                   VirtReg).addReg(SrcReg, getKillRegState(IsOrigSrcRegKilled));
1438 
1439             // Change instruction to S2_storeri_io.
1440             //   S2_storeri_io FI, 0, VirtReg
1441             MI->setDesc(HII.get(Hexagon::S2_storeri_io));
1442             MI->getOperand(2).setReg(VirtReg);
1443             MI->getOperand(2).setIsKill();
1444 
1445             HasReplacedPseudoInst = true;
1446 
1447             if (NextII != MBB->end())
1448               Scavenger.forward();
1449 
1450             if (!AlwaysSpill.count(FI))
1451               LocallySpilled.insert(FI);
1452           }
1453         } else if (Opc == Hexagon::LDriw_pred || Opc == Hexagon::LDriw_mod) {
1454           // DstReg = LDriw_pred FI, 0
1455           unsigned DestReg = MI->getOperand(0).getReg();
1456           assert(MI->getOperand(1).isFI() && "Expect a frame index");
1457           assert((Hexagon::PredRegsRegClass.contains(DestReg) ||
1458                   Hexagon::ModRegsRegClass.contains(DestReg)) &&
1459               "Not a predicate or modifier register");
1460 
1461           int FI = MI->getOperand(1).getIndex();
1462 
1463           MachineOperand &M0 = MI->getOperand(0);
1464           if (M0.isDead()) {
1465             if (NextII != MBB->end())
1466               Scavenger.forward();
1467             MBB->erase(MII);
1468             continue;
1469           }
1470 
1471           if (FItoRegUses.count(FI)) {
1472             // Reload from GPR
1473             std::pair<unsigned,unsigned> &SpillInfo = FItoRegUses[FI];
1474 
1475             --SpillInfo.second;
1476             bool IsKill = SpillInfo.second == 0;
1477             if (Opc == Hexagon::LDriw_pred)
1478               BuildMI(*MBB, std::next(MII), MI->getDebugLoc(),
1479                   HII.get(Hexagon::C2_tfrrp), DestReg).addReg(SpillInfo.first,
1480                   getKillRegState(IsKill));
1481             else
1482               BuildMI(*MBB, std::next(MII), MI->getDebugLoc(),
1483                   HII.get(Hexagon::A2_tfrrcr), DestReg).addReg(SpillInfo.first,
1484                   getKillRegState(IsKill));
1485 
1486             if (IsKill)
1487               FItoRegUses.erase(FI);
1488 
1489             Scavenger.forward(); // Process the newly inserted instruction
1490             if (NextII != MBB->end())
1491               Scavenger.forward(); // Move to next instruction
1492 
1493             MBB->erase(MII);
1494           } else {
1495             // Reload from memory
1496 
1497             // If this wasn't spilled previously in this block, the PredReg in
1498             // this FI is live across blocks. Make sure it never ends up in a
1499             // register.
1500             if (!LocallySpilled.count(FI))
1501               AlwaysSpill.insert(FI);
1502 
1503             unsigned VirtReg =
1504               MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
1505 
1506             // Change instruction to L2_loadri_io.
1507             //   VirtReg = L2_loadri_io FI, 0
1508             MI->setDesc(HII.get(Hexagon::L2_loadri_io));
1509             MI->getOperand(0).setReg(VirtReg);
1510 
1511             // Insert transfer to general purpose register.
1512             //   DestReg = C2_tfrrp VirtReg
1513             if (Opc == Hexagon::LDriw_pred)
1514               BuildMI(*MBB, std::next(MII), MI->getDebugLoc(),
1515                 HII.get(Hexagon::C2_tfrrp), DestReg).addReg(VirtReg,
1516                 getKillRegState(true));
1517             else
1518               BuildMI(*MBB, std::next(MII), MI->getDebugLoc(),
1519                 HII.get(Hexagon::A2_tfrrcr), DestReg).addReg(VirtReg,
1520                 getKillRegState(true));
1521 
1522             Scavenger.forward(); // Process newly inserted instruction
1523             if (NextII != MBB->end())
1524               Scavenger.forward(); // Move to next instruction
1525 
1526             HasReplacedPseudoInst = true;
1527           }
1528         } else if (NextII != MBB->end())
1529           Scavenger.forward();
1530       }
1531 
1532       assert(FItoRegUses.empty() && "PredRegs in GPRs outlast this block!");
1533     }
1534   }
1535 
1536   return HasReplacedPseudoInst;
1537 }
1538 
1539 
1540 
1541 void HexagonFrameLowering::expandAlloca(MachineInstr *AI,
1542       const HexagonInstrInfo &HII, unsigned SP, unsigned CF) const {
1543   MachineBasicBlock &MB = *AI->getParent();
1544   DebugLoc DL = AI->getDebugLoc();
1545   unsigned A = AI->getOperand(2).getImm();
1546 
1547   // Have
1548   //    Rd  = alloca Rs, #A
1549   //
1550   // If Rs and Rd are different registers, use this sequence:
1551   //    Rd  = sub(r29, Rs)
1552   //    r29 = sub(r29, Rs)
1553   //    Rd  = and(Rd, #-A)    ; if necessary
1554   //    r29 = and(r29, #-A)   ; if necessary
1555   //    Rd  = add(Rd, #CF)    ; CF size aligned to at most A
1556   // otherwise, do
1557   //    Rd  = sub(r29, Rs)
1558   //    Rd  = and(Rd, #-A)    ; if necessary
1559   //    r29 = Rd
1560   //    Rd  = add(Rd, #CF)    ; CF size aligned to at most A
1561 
1562   MachineOperand &RdOp = AI->getOperand(0);
1563   MachineOperand &RsOp = AI->getOperand(1);
1564   unsigned Rd = RdOp.getReg(), Rs = RsOp.getReg();
1565 
1566   // Rd = sub(r29, Rs)
1567   BuildMI(MB, AI, DL, HII.get(Hexagon::A2_sub), Rd)
1568       .addReg(SP)
1569       .addReg(Rs);
1570   if (Rs != Rd) {
1571     // r29 = sub(r29, Rs)
1572     BuildMI(MB, AI, DL, HII.get(Hexagon::A2_sub), SP)
1573         .addReg(SP)
1574         .addReg(Rs);
1575   }
1576   if (A > 8) {
1577     // Rd  = and(Rd, #-A)
1578     BuildMI(MB, AI, DL, HII.get(Hexagon::A2_andir), Rd)
1579         .addReg(Rd)
1580         .addImm(-int64_t(A));
1581     if (Rs != Rd)
1582       BuildMI(MB, AI, DL, HII.get(Hexagon::A2_andir), SP)
1583           .addReg(SP)
1584           .addImm(-int64_t(A));
1585   }
1586   if (Rs == Rd) {
1587     // r29 = Rd
1588     BuildMI(MB, AI, DL, HII.get(TargetOpcode::COPY), SP)
1589         .addReg(Rd);
1590   }
1591   if (CF > 0) {
1592     // Rd = add(Rd, #CF)
1593     BuildMI(MB, AI, DL, HII.get(Hexagon::A2_addi), Rd)
1594         .addReg(Rd)
1595         .addImm(CF);
1596   }
1597 }
1598 
1599 
1600 bool HexagonFrameLowering::needsAligna(const MachineFunction &MF) const {
1601   const MachineFrameInfo *MFI = MF.getFrameInfo();
1602   if (!MFI->hasVarSizedObjects())
1603     return false;
1604   unsigned MaxA = MFI->getMaxAlignment();
1605   if (MaxA <= getStackAlignment())
1606     return false;
1607   return true;
1608 }
1609 
1610 
1611 const MachineInstr *HexagonFrameLowering::getAlignaInstr(
1612       const MachineFunction &MF) const {
1613   for (auto &B : MF)
1614     for (auto &I : B)
1615       if (I.getOpcode() == Hexagon::ALIGNA)
1616         return &I;
1617   return nullptr;
1618 }
1619 
1620 
1621 // FIXME: Use Function::optForSize().
1622 inline static bool isOptSize(const MachineFunction &MF) {
1623   AttributeSet AF = MF.getFunction()->getAttributes();
1624   return AF.hasAttribute(AttributeSet::FunctionIndex,
1625                          Attribute::OptimizeForSize);
1626 }
1627 
1628 inline static bool isMinSize(const MachineFunction &MF) {
1629   return MF.getFunction()->optForMinSize();
1630 }
1631 
1632 
1633 /// Determine whether the callee-saved register saves and restores should
1634 /// be generated via inline code. If this function returns "true", inline
1635 /// code will be generated. If this function returns "false", additional
1636 /// checks are performed, which may still lead to the inline code.
1637 bool HexagonFrameLowering::shouldInlineCSR(MachineFunction &MF,
1638       const CSIVect &CSI) const {
1639   if (MF.getInfo<HexagonMachineFunctionInfo>()->hasEHReturn())
1640     return true;
1641   if (!isOptSize(MF) && !isMinSize(MF))
1642     if (MF.getTarget().getOptLevel() > CodeGenOpt::Default)
1643       return true;
1644 
1645   // Check if CSI only has double registers, and if the registers form
1646   // a contiguous block starting from D8.
1647   BitVector Regs(Hexagon::NUM_TARGET_REGS);
1648   for (unsigned i = 0, n = CSI.size(); i < n; ++i) {
1649     unsigned R = CSI[i].getReg();
1650     if (!Hexagon::DoubleRegsRegClass.contains(R))
1651       return true;
1652     Regs[R] = true;
1653   }
1654   int F = Regs.find_first();
1655   if (F != Hexagon::D8)
1656     return true;
1657   while (F >= 0) {
1658     int N = Regs.find_next(F);
1659     if (N >= 0 && N != F+1)
1660       return true;
1661     F = N;
1662   }
1663 
1664   return false;
1665 }
1666 
1667 
1668 bool HexagonFrameLowering::useSpillFunction(MachineFunction &MF,
1669       const CSIVect &CSI) const {
1670   if (shouldInlineCSR(MF, CSI))
1671     return false;
1672   unsigned NumCSI = CSI.size();
1673   if (NumCSI <= 1)
1674     return false;
1675 
1676   unsigned Threshold = isOptSize(MF) ? SpillFuncThresholdOs
1677                                      : SpillFuncThreshold;
1678   return Threshold < NumCSI;
1679 }
1680 
1681 
1682 bool HexagonFrameLowering::useRestoreFunction(MachineFunction &MF,
1683       const CSIVect &CSI) const {
1684   if (shouldInlineCSR(MF, CSI))
1685     return false;
1686   unsigned NumCSI = CSI.size();
1687   unsigned Threshold = isOptSize(MF) ? SpillFuncThresholdOs-1
1688                                      : SpillFuncThreshold;
1689   return Threshold < NumCSI;
1690 }
1691