]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/lib/Target/Hexagon/HexagonFrameLowering.cpp
Merge llvm, clang, lld, lldb, compiler-rt and libc++ r306325, and update
[FreeBSD/FreeBSD.git] / contrib / llvm / lib / Target / Hexagon / HexagonFrameLowering.cpp
1 //===-- HexagonFrameLowering.cpp - Define frame lowering ------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //
9 //===----------------------------------------------------------------------===//
10
11 #define DEBUG_TYPE "hexagon-pei"
12
13 #include "HexagonFrameLowering.h"
14 #include "HexagonBlockRanges.h"
15 #include "HexagonInstrInfo.h"
16 #include "HexagonMachineFunctionInfo.h"
17 #include "HexagonRegisterInfo.h"
18 #include "HexagonSubtarget.h"
19 #include "HexagonTargetMachine.h"
20 #include "MCTargetDesc/HexagonBaseInfo.h"
21 #include "llvm/ADT/BitVector.h"
22 #include "llvm/ADT/DenseMap.h"
23 #include "llvm/ADT/None.h"
24 #include "llvm/ADT/Optional.h"
25 #include "llvm/ADT/PostOrderIterator.h"
26 #include "llvm/ADT/SetVector.h"
27 #include "llvm/ADT/SmallSet.h"
28 #include "llvm/ADT/SmallVector.h"
29 #include "llvm/CodeGen/LivePhysRegs.h"
30 #include "llvm/CodeGen/MachineBasicBlock.h"
31 #include "llvm/CodeGen/MachineDominators.h"
32 #include "llvm/CodeGen/MachineFrameInfo.h"
33 #include "llvm/CodeGen/MachineFunction.h"
34 #include "llvm/CodeGen/MachineFunctionPass.h"
35 #include "llvm/CodeGen/MachineInstr.h"
36 #include "llvm/CodeGen/MachineInstrBuilder.h"
37 #include "llvm/CodeGen/MachineMemOperand.h"
38 #include "llvm/CodeGen/MachineModuleInfo.h"
39 #include "llvm/CodeGen/MachineOperand.h"
40 #include "llvm/CodeGen/MachinePostDominators.h"
41 #include "llvm/CodeGen/MachineRegisterInfo.h"
42 #include "llvm/CodeGen/RegisterScavenging.h"
43 #include "llvm/IR/DebugLoc.h"
44 #include "llvm/IR/Function.h"
45 #include "llvm/MC/MCDwarf.h"
46 #include "llvm/MC/MCRegisterInfo.h"
47 #include "llvm/Pass.h"
48 #include "llvm/Support/CodeGen.h"
49 #include "llvm/Support/CommandLine.h"
50 #include "llvm/Support/Debug.h"
51 #include "llvm/Support/ErrorHandling.h"
52 #include "llvm/Support/MathExtras.h"
53 #include "llvm/Support/raw_ostream.h"
54 #include "llvm/Target/TargetMachine.h"
55 #include "llvm/Target/TargetRegisterInfo.h"
56 #include <algorithm>
57 #include <cassert>
58 #include <cstdint>
59 #include <iterator>
60 #include <limits>
61 #include <map>
62 #include <new>
63 #include <utility>
64 #include <vector>
65
66 // Hexagon stack frame layout as defined by the ABI:
67 //
68 //                                                       Incoming arguments
69 //                                                       passed via stack
70 //                                                                      |
71 //                                                                      |
72 //        SP during function's                 FP during function's     |
73 //    +-- runtime (top of stack)               runtime (bottom) --+     |
74 //    |                                                           |     |
75 // --++---------------------+------------------+-----------------++-+-------
76 //   |  parameter area for  |  variable-size   |   fixed-size    |LR|  arg
77 //   |   called functions   |  local objects   |  local objects  |FP|
78 // --+----------------------+------------------+-----------------+--+-------
79 //    <-    size known    -> <- size unknown -> <- size known  ->
80 //
81 // Low address                                                 High address
82 //
83 // <--- stack growth
84 //
85 //
86 // - In any circumstances, the outgoing function arguments are always accessi-
87 //   ble using the SP, and the incoming arguments are accessible using the FP.
88 // - If the local objects are not aligned, they can always be accessed using
89 //   the FP.
90 // - If there are no variable-sized objects, the local objects can always be
91 //   accessed using the SP, regardless whether they are aligned or not. (The
92 //   alignment padding will be at the bottom of the stack (highest address),
93 //   and so the offset with respect to the SP will be known at the compile-
94 //   -time.)
95 //
96 // The only complication occurs if there are both, local aligned objects, and
97 // dynamically allocated (variable-sized) objects. The alignment pad will be
98 // placed between the FP and the local objects, thus preventing the use of the
99 // FP to access the local objects. At the same time, the variable-sized objects
100 // will be between the SP and the local objects, thus introducing an unknown
101 // distance from the SP to the locals.
102 //
103 // To avoid this problem, a new register is created that holds the aligned
104 // address of the bottom of the stack, referred in the sources as AP (aligned
105 // pointer). The AP will be equal to "FP-p", where "p" is the smallest pad
106 // that aligns AP to the required boundary (a maximum of the alignments of
107 // all stack objects, fixed- and variable-sized). All local objects[1] will
108 // then use AP as the base pointer.
109 // [1] The exception is with "fixed" stack objects. "Fixed" stack objects get
110 // their name from being allocated at fixed locations on the stack, relative
111 // to the FP. In the presence of dynamic allocation and local alignment, such
112 // objects can only be accessed through the FP.
113 //
114 // Illustration of the AP:
115 //                                                                FP --+
116 //                                                                     |
117 // ---------------+---------------------+-----+-----------------------++-+--
118 //   Rest of the  | Local stack objects | Pad |  Fixed stack objects  |LR|
119 //   stack frame  | (aligned)           |     |  (CSR, spills, etc.)  |FP|
120 // ---------------+---------------------+-----+-----------------+-----+--+--
121 //                                      |<-- Multiple of the -->|
122 //                                           stack alignment    +-- AP
123 //
124 // The AP is set up at the beginning of the function. Since it is not a dedi-
125 // cated (reserved) register, it needs to be kept live throughout the function
126 // to be available as the base register for local object accesses.
127 // Normally, an address of a stack objects is obtained by a pseudo-instruction
128 // PS_fi. To access local objects with the AP register present, a different
129 // pseudo-instruction needs to be used: PS_fia. The PS_fia takes one extra
130 // argument compared to PS_fi: the first input register is the AP register.
131 // This keeps the register live between its definition and its uses.
132
133 // The AP register is originally set up using pseudo-instruction PS_aligna:
134 //   AP = PS_aligna A
135 // where
136 //   A  - required stack alignment
137 // The alignment value must be the maximum of all alignments required by
138 // any stack object.
139
140 // The dynamic allocation uses a pseudo-instruction PS_alloca:
141 //   Rd = PS_alloca Rs, A
142 // where
143 //   Rd - address of the allocated space
144 //   Rs - minimum size (the actual allocated can be larger to accommodate
145 //        alignment)
146 //   A  - required alignment
147
148 using namespace llvm;
149
150 static cl::opt<bool> DisableDeallocRet("disable-hexagon-dealloc-ret",
151     cl::Hidden, cl::desc("Disable Dealloc Return for Hexagon target"));
152
153 static cl::opt<unsigned> NumberScavengerSlots("number-scavenger-slots",
154     cl::Hidden, cl::desc("Set the number of scavenger slots"), cl::init(2),
155     cl::ZeroOrMore);
156
157 static cl::opt<int> SpillFuncThreshold("spill-func-threshold",
158     cl::Hidden, cl::desc("Specify O2(not Os) spill func threshold"),
159     cl::init(6), cl::ZeroOrMore);
160
161 static cl::opt<int> SpillFuncThresholdOs("spill-func-threshold-Os",
162     cl::Hidden, cl::desc("Specify Os spill func threshold"),
163     cl::init(1), cl::ZeroOrMore);
164
165 static cl::opt<bool> EnableStackOVFSanitizer("enable-stackovf-sanitizer",
166     cl::Hidden, cl::desc("Enable runtime checks for stack overflow."),
167     cl::init(false), cl::ZeroOrMore);
168
169 static cl::opt<bool> EnableShrinkWrapping("hexagon-shrink-frame",
170     cl::init(true), cl::Hidden, cl::ZeroOrMore,
171     cl::desc("Enable stack frame shrink wrapping"));
172
173 static cl::opt<unsigned> ShrinkLimit("shrink-frame-limit",
174     cl::init(std::numeric_limits<unsigned>::max()), cl::Hidden, cl::ZeroOrMore,
175     cl::desc("Max count of stack frame shrink-wraps"));
176
177 static cl::opt<bool> EnableSaveRestoreLong("enable-save-restore-long",
178     cl::Hidden, cl::desc("Enable long calls for save-restore stubs."),
179     cl::init(false), cl::ZeroOrMore);
180
181 static cl::opt<bool> 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 FrameSize = MFI.getStackSize();
1055   unsigned SP = HRI.getStackRegister(), FP = HRI.getFrameRegister();
1056   auto &HMFI = *MF.getInfo<HexagonMachineFunctionInfo>();
1057   unsigned AP = HMFI.getStackAlignBasePhysReg();
1058   // It may happen that AP will be absent even HasAlloca && HasExtraAlign
1059   // is true. HasExtraAlign may be set because of vector spills, without
1060   // aligned locals or aligned outgoing function arguments. Since vector
1061   // spills will ultimately be "unaligned", it is safe to use FP as the
1062   // base register.
1063   // In fact, in such a scenario the stack is actually not required to be
1064   // aligned, although it may end up being aligned anyway, since this
1065   // particular case is not easily detectable. The alignment will be
1066   // unnecessary, but not incorrect.
1067   // Unfortunately there is no quick way to verify that the above is
1068   // indeed the case (and that it's not a result of an error), so just
1069   // assume that missing AP will be replaced by FP.
1070   // (A better fix would be to rematerialize AP from FP and always align
1071   // vector spills.)
1072   if (AP == 0)
1073     AP = FP;
1074
1075   bool UseFP = false, UseAP = false;  // Default: use SP (except at -O0).
1076   // Use FP at -O0, except when there are objects with extra alignment.
1077   // That additional alignment requirement may cause a pad to be inserted,
1078   // which will make it impossible to use FP to access objects located
1079   // past the pad.
1080   if (NoOpt && !HasExtraAlign)
1081     UseFP = true;
1082   if (MFI.isFixedObjectIndex(FI) || MFI.isObjectPreAllocated(FI)) {
1083     // Fixed and preallocated objects will be located before any padding
1084     // so FP must be used to access them.
1085     UseFP |= (HasAlloca || HasExtraAlign);
1086   } else {
1087     if (HasAlloca) {
1088       if (HasExtraAlign)
1089         UseAP = true;
1090       else
1091         UseFP = true;
1092     }
1093   }
1094
1095   // If FP was picked, then there had better be FP.
1096   bool HasFP = hasFP(MF);
1097   assert((HasFP || !UseFP) && "This function must have frame pointer");
1098
1099   // Having FP implies allocframe. Allocframe will store extra 8 bytes:
1100   // FP/LR. If the base register is used to access an object across these
1101   // 8 bytes, then the offset will need to be adjusted by 8.
1102   //
1103   // After allocframe:
1104   //                    HexagonISelLowering adds 8 to ---+
1105   //                    the offsets of all stack-based   |
1106   //                    arguments (*)                    |
1107   //                                                     |
1108   //   getObjectOffset < 0   0     8  getObjectOffset >= 8
1109   // ------------------------+-----+------------------------> increasing
1110   //     <local objects>     |FP/LR|    <input arguments>     addresses
1111   // -----------------+------+-----+------------------------>
1112   //                  |      |
1113   //    SP/AP point --+      +-- FP points here (**)
1114   //    somewhere on
1115   //    this side of FP/LR
1116   //
1117   // (*) See LowerFormalArguments. The FP/LR is assumed to be present.
1118   // (**) *FP == old-FP. FP+0..7 are the bytes of FP/LR.
1119
1120   // The lowering assumes that FP/LR is present, and so the offsets of
1121   // the formal arguments start at 8. If FP/LR is not there we need to
1122   // reduce the offset by 8.
1123   if (Offset > 0 && !HasFP)
1124     Offset -= 8;
1125
1126   if (UseFP)
1127     FrameReg = FP;
1128   else if (UseAP)
1129     FrameReg = AP;
1130   else
1131     FrameReg = SP;
1132
1133   // Calculate the actual offset in the instruction. If there is no FP
1134   // (in other words, no allocframe), then SP will not be adjusted (i.e.
1135   // there will be no SP -= FrameSize), so the frame size should not be
1136   // added to the calculated offset.
1137   int RealOffset = Offset;
1138   if (!UseFP && !UseAP && HasFP)
1139     RealOffset = FrameSize+Offset;
1140   return RealOffset;
1141 }
1142
1143 bool HexagonFrameLowering::insertCSRSpillsInBlock(MachineBasicBlock &MBB,
1144       const CSIVect &CSI, const HexagonRegisterInfo &HRI,
1145       bool &PrologueStubs) const {
1146   if (CSI.empty())
1147     return true;
1148
1149   MachineBasicBlock::iterator MI = MBB.begin();
1150   PrologueStubs = false;
1151   MachineFunction &MF = *MBB.getParent();
1152   auto &HST = MF.getSubtarget<HexagonSubtarget>();
1153   auto &HII = *HST.getInstrInfo();
1154
1155   if (useSpillFunction(MF, CSI)) {
1156     PrologueStubs = true;
1157     unsigned MaxReg = getMaxCalleeSavedReg(CSI, HRI);
1158     bool StkOvrFlowEnabled = EnableStackOVFSanitizer;
1159     const char *SpillFun = getSpillFunctionFor(MaxReg, SK_ToMem,
1160                                                StkOvrFlowEnabled);
1161     auto &HTM = static_cast<const HexagonTargetMachine&>(MF.getTarget());
1162     bool IsPIC = HTM.isPositionIndependent();
1163     bool LongCalls = HST.useLongCalls() || EnableSaveRestoreLong;
1164
1165     // Call spill function.
1166     DebugLoc DL = MI != MBB.end() ? MI->getDebugLoc() : DebugLoc();
1167     unsigned SpillOpc;
1168     if (StkOvrFlowEnabled) {
1169       if (LongCalls)
1170         SpillOpc = IsPIC ? Hexagon::SAVE_REGISTERS_CALL_V4STK_EXT_PIC
1171                          : Hexagon::SAVE_REGISTERS_CALL_V4STK_EXT;
1172       else
1173         SpillOpc = IsPIC ? Hexagon::SAVE_REGISTERS_CALL_V4STK_PIC
1174                          : Hexagon::SAVE_REGISTERS_CALL_V4STK;
1175     } else {
1176       if (LongCalls)
1177         SpillOpc = IsPIC ? Hexagon::SAVE_REGISTERS_CALL_V4_EXT_PIC
1178                          : Hexagon::SAVE_REGISTERS_CALL_V4_EXT;
1179       else
1180         SpillOpc = IsPIC ? Hexagon::SAVE_REGISTERS_CALL_V4_PIC
1181                          : Hexagon::SAVE_REGISTERS_CALL_V4;
1182     }
1183
1184     MachineInstr *SaveRegsCall =
1185         BuildMI(MBB, MI, DL, HII.get(SpillOpc))
1186           .addExternalSymbol(SpillFun);
1187
1188     // Add callee-saved registers as use.
1189     addCalleeSaveRegistersAsImpOperand(SaveRegsCall, CSI, false, true);
1190     // Add live in registers.
1191     for (unsigned I = 0; I < CSI.size(); ++I)
1192       MBB.addLiveIn(CSI[I].getReg());
1193     return true;
1194   }
1195
1196   for (unsigned i = 0, n = CSI.size(); i < n; ++i) {
1197     unsigned Reg = CSI[i].getReg();
1198     // Add live in registers. We treat eh_return callee saved register r0 - r3
1199     // specially. They are not really callee saved registers as they are not
1200     // supposed to be killed.
1201     bool IsKill = !HRI.isEHReturnCalleeSaveReg(Reg);
1202     int FI = CSI[i].getFrameIdx();
1203     const TargetRegisterClass *RC = HRI.getMinimalPhysRegClass(Reg);
1204     HII.storeRegToStackSlot(MBB, MI, Reg, IsKill, FI, RC, &HRI);
1205     if (IsKill)
1206       MBB.addLiveIn(Reg);
1207   }
1208   return true;
1209 }
1210
1211 bool HexagonFrameLowering::insertCSRRestoresInBlock(MachineBasicBlock &MBB,
1212       const CSIVect &CSI, const HexagonRegisterInfo &HRI) const {
1213   if (CSI.empty())
1214     return false;
1215
1216   MachineBasicBlock::iterator MI = MBB.getFirstTerminator();
1217   MachineFunction &MF = *MBB.getParent();
1218   auto &HST = MF.getSubtarget<HexagonSubtarget>();
1219   auto &HII = *HST.getInstrInfo();
1220
1221   if (useRestoreFunction(MF, CSI)) {
1222     bool HasTC = hasTailCall(MBB) || !hasReturn(MBB);
1223     unsigned MaxR = getMaxCalleeSavedReg(CSI, HRI);
1224     SpillKind Kind = HasTC ? SK_FromMemTailcall : SK_FromMem;
1225     const char *RestoreFn = getSpillFunctionFor(MaxR, Kind);
1226     auto &HTM = static_cast<const HexagonTargetMachine&>(MF.getTarget());
1227     bool IsPIC = HTM.isPositionIndependent();
1228     bool LongCalls = HST.useLongCalls() || EnableSaveRestoreLong;
1229
1230     // Call spill function.
1231     DebugLoc DL = MI != MBB.end() ? MI->getDebugLoc()
1232                                   : MBB.getLastNonDebugInstr()->getDebugLoc();
1233     MachineInstr *DeallocCall = nullptr;
1234
1235     if (HasTC) {
1236       unsigned RetOpc;
1237       if (LongCalls)
1238         RetOpc = IsPIC ? Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_EXT_PIC
1239                        : Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_EXT;
1240       else
1241         RetOpc = IsPIC ? Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_PIC
1242                        : Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4;
1243       DeallocCall = BuildMI(MBB, MI, DL, HII.get(RetOpc))
1244           .addExternalSymbol(RestoreFn);
1245     } else {
1246       // The block has a return.
1247       MachineBasicBlock::iterator It = MBB.getFirstTerminator();
1248       assert(It->isReturn() && std::next(It) == MBB.end());
1249       unsigned RetOpc;
1250       if (LongCalls)
1251         RetOpc = IsPIC ? Hexagon::RESTORE_DEALLOC_RET_JMP_V4_EXT_PIC
1252                        : Hexagon::RESTORE_DEALLOC_RET_JMP_V4_EXT;
1253       else
1254         RetOpc = IsPIC ? Hexagon::RESTORE_DEALLOC_RET_JMP_V4_PIC
1255                        : Hexagon::RESTORE_DEALLOC_RET_JMP_V4;
1256       DeallocCall = BuildMI(MBB, It, DL, HII.get(RetOpc))
1257           .addExternalSymbol(RestoreFn);
1258       // Transfer the function live-out registers.
1259       DeallocCall->copyImplicitOps(MF, *It);
1260     }
1261     addCalleeSaveRegistersAsImpOperand(DeallocCall, CSI, true, false);
1262     return true;
1263   }
1264
1265   for (unsigned i = 0; i < CSI.size(); ++i) {
1266     unsigned Reg = CSI[i].getReg();
1267     const TargetRegisterClass *RC = HRI.getMinimalPhysRegClass(Reg);
1268     int FI = CSI[i].getFrameIdx();
1269     HII.loadRegFromStackSlot(MBB, MI, Reg, FI, RC, &HRI);
1270   }
1271
1272   return true;
1273 }
1274
1275 MachineBasicBlock::iterator HexagonFrameLowering::eliminateCallFramePseudoInstr(
1276     MachineFunction &MF, MachineBasicBlock &MBB,
1277     MachineBasicBlock::iterator I) const {
1278   MachineInstr &MI = *I;
1279   unsigned Opc = MI.getOpcode();
1280   (void)Opc; // Silence compiler warning.
1281   assert((Opc == Hexagon::ADJCALLSTACKDOWN || Opc == Hexagon::ADJCALLSTACKUP) &&
1282          "Cannot handle this call frame pseudo instruction");
1283   return MBB.erase(I);
1284 }
1285
1286 void HexagonFrameLowering::processFunctionBeforeFrameFinalized(
1287     MachineFunction &MF, RegScavenger *RS) const {
1288   // If this function has uses aligned stack and also has variable sized stack
1289   // objects, then we need to map all spill slots to fixed positions, so that
1290   // they can be accessed through FP. Otherwise they would have to be accessed
1291   // via AP, which may not be available at the particular place in the program.
1292   MachineFrameInfo &MFI = MF.getFrameInfo();
1293   bool HasAlloca = MFI.hasVarSizedObjects();
1294   bool NeedsAlign = (MFI.getMaxAlignment() > getStackAlignment());
1295
1296   if (!HasAlloca || !NeedsAlign)
1297     return;
1298
1299   unsigned LFS = MFI.getLocalFrameSize();
1300   for (int i = 0, e = MFI.getObjectIndexEnd(); i != e; ++i) {
1301     if (!MFI.isSpillSlotObjectIndex(i) || MFI.isDeadObjectIndex(i))
1302       continue;
1303     unsigned S = MFI.getObjectSize(i);
1304     // Reduce the alignment to at most 8. This will require unaligned vector
1305     // stores if they happen here.
1306     unsigned A = std::max(MFI.getObjectAlignment(i), 8U);
1307     MFI.setObjectAlignment(i, 8);
1308     LFS = alignTo(LFS+S, A);
1309     MFI.mapLocalFrameObject(i, -LFS);
1310   }
1311
1312   MFI.setLocalFrameSize(LFS);
1313   unsigned A = MFI.getLocalFrameMaxAlign();
1314   assert(A <= 8 && "Unexpected local frame alignment");
1315   if (A == 0)
1316     MFI.setLocalFrameMaxAlign(8);
1317   MFI.setUseLocalStackAllocationBlock(true);
1318
1319   // Set the physical aligned-stack base address register.
1320   unsigned AP = 0;
1321   if (const MachineInstr *AI = getAlignaInstr(MF))
1322     AP = AI->getOperand(0).getReg();
1323   auto &HMFI = *MF.getInfo<HexagonMachineFunctionInfo>();
1324   HMFI.setStackAlignBasePhysReg(AP);
1325 }
1326
1327 /// Returns true if there are no caller-saved registers available in class RC.
1328 static bool needToReserveScavengingSpillSlots(MachineFunction &MF,
1329       const HexagonRegisterInfo &HRI, const TargetRegisterClass *RC) {
1330   MachineRegisterInfo &MRI = MF.getRegInfo();
1331
1332   auto IsUsed = [&HRI,&MRI] (unsigned Reg) -> bool {
1333     for (MCRegAliasIterator AI(Reg, &HRI, true); AI.isValid(); ++AI)
1334       if (MRI.isPhysRegUsed(*AI))
1335         return true;
1336     return false;
1337   };
1338
1339   // Check for an unused caller-saved register. Callee-saved registers
1340   // have become pristine by now.
1341   for (const MCPhysReg *P = HRI.getCallerSavedRegs(&MF, RC); *P; ++P)
1342     if (!IsUsed(*P))
1343       return false;
1344
1345   // All caller-saved registers are used.
1346   return true;
1347 }
1348
1349 #ifndef NDEBUG
1350 static void dump_registers(BitVector &Regs, const TargetRegisterInfo &TRI) {
1351   dbgs() << '{';
1352   for (int x = Regs.find_first(); x >= 0; x = Regs.find_next(x)) {
1353     unsigned R = x;
1354     dbgs() << ' ' << PrintReg(R, &TRI);
1355   }
1356   dbgs() << " }";
1357 }
1358 #endif
1359
1360 bool HexagonFrameLowering::assignCalleeSavedSpillSlots(MachineFunction &MF,
1361       const TargetRegisterInfo *TRI, std::vector<CalleeSavedInfo> &CSI) const {
1362   DEBUG(dbgs() << __func__ << " on "
1363                << MF.getFunction()->getName() << '\n');
1364   MachineFrameInfo &MFI = MF.getFrameInfo();
1365   BitVector SRegs(Hexagon::NUM_TARGET_REGS);
1366
1367   // Generate a set of unique, callee-saved registers (SRegs), where each
1368   // register in the set is maximal in terms of sub-/super-register relation,
1369   // i.e. for each R in SRegs, no proper super-register of R is also in SRegs.
1370
1371   // (1) For each callee-saved register, add that register and all of its
1372   // sub-registers to SRegs.
1373   DEBUG(dbgs() << "Initial CS registers: {");
1374   for (unsigned i = 0, n = CSI.size(); i < n; ++i) {
1375     unsigned R = CSI[i].getReg();
1376     DEBUG(dbgs() << ' ' << PrintReg(R, TRI));
1377     for (MCSubRegIterator SR(R, TRI, true); SR.isValid(); ++SR)
1378       SRegs[*SR] = true;
1379   }
1380   DEBUG(dbgs() << " }\n");
1381   DEBUG(dbgs() << "SRegs.1: "; dump_registers(SRegs, *TRI); dbgs() << "\n");
1382
1383   // (2) For each reserved register, remove that register and all of its
1384   // sub- and super-registers from SRegs.
1385   BitVector Reserved = TRI->getReservedRegs(MF);
1386   for (int x = Reserved.find_first(); x >= 0; x = Reserved.find_next(x)) {
1387     unsigned R = x;
1388     for (MCSuperRegIterator SR(R, TRI, true); SR.isValid(); ++SR)
1389       SRegs[*SR] = false;
1390   }
1391   DEBUG(dbgs() << "Res:     "; dump_registers(Reserved, *TRI); dbgs() << "\n");
1392   DEBUG(dbgs() << "SRegs.2: "; dump_registers(SRegs, *TRI); dbgs() << "\n");
1393
1394   // (3) Collect all registers that have at least one sub-register in SRegs,
1395   // and also have no sub-registers that are reserved. These will be the can-
1396   // didates for saving as a whole instead of their individual sub-registers.
1397   // (Saving R17:16 instead of R16 is fine, but only if R17 was not reserved.)
1398   BitVector TmpSup(Hexagon::NUM_TARGET_REGS);
1399   for (int x = SRegs.find_first(); x >= 0; x = SRegs.find_next(x)) {
1400     unsigned R = x;
1401     for (MCSuperRegIterator SR(R, TRI); SR.isValid(); ++SR)
1402       TmpSup[*SR] = true;
1403   }
1404   for (int x = TmpSup.find_first(); x >= 0; x = TmpSup.find_next(x)) {
1405     unsigned R = x;
1406     for (MCSubRegIterator SR(R, TRI, true); SR.isValid(); ++SR) {
1407       if (!Reserved[*SR])
1408         continue;
1409       TmpSup[R] = false;
1410       break;
1411     }
1412   }
1413   DEBUG(dbgs() << "TmpSup:  "; dump_registers(TmpSup, *TRI); dbgs() << "\n");
1414
1415   // (4) Include all super-registers found in (3) into SRegs.
1416   SRegs |= TmpSup;
1417   DEBUG(dbgs() << "SRegs.4: "; dump_registers(SRegs, *TRI); dbgs() << "\n");
1418
1419   // (5) For each register R in SRegs, if any super-register of R is in SRegs,
1420   // remove R from SRegs.
1421   for (int x = SRegs.find_first(); x >= 0; x = SRegs.find_next(x)) {
1422     unsigned R = x;
1423     for (MCSuperRegIterator SR(R, TRI); SR.isValid(); ++SR) {
1424       if (!SRegs[*SR])
1425         continue;
1426       SRegs[R] = false;
1427       break;
1428     }
1429   }
1430   DEBUG(dbgs() << "SRegs.5: "; dump_registers(SRegs, *TRI); dbgs() << "\n");
1431
1432   // Now, for each register that has a fixed stack slot, create the stack
1433   // object for it.
1434   CSI.clear();
1435
1436   typedef TargetFrameLowering::SpillSlot SpillSlot;
1437   unsigned NumFixed;
1438   int MinOffset = 0;  // CS offsets are negative.
1439   const SpillSlot *FixedSlots = getCalleeSavedSpillSlots(NumFixed);
1440   for (const SpillSlot *S = FixedSlots; S != FixedSlots+NumFixed; ++S) {
1441     if (!SRegs[S->Reg])
1442       continue;
1443     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(S->Reg);
1444     int FI = MFI.CreateFixedSpillStackObject(TRI->getSpillSize(*RC), S->Offset);
1445     MinOffset = std::min(MinOffset, S->Offset);
1446     CSI.push_back(CalleeSavedInfo(S->Reg, FI));
1447     SRegs[S->Reg] = false;
1448   }
1449
1450   // There can be some registers that don't have fixed slots. For example,
1451   // we need to store R0-R3 in functions with exception handling. For each
1452   // such register, create a non-fixed stack object.
1453   for (int x = SRegs.find_first(); x >= 0; x = SRegs.find_next(x)) {
1454     unsigned R = x;
1455     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(R);
1456     unsigned Size = TRI->getSpillSize(*RC);
1457     int Off = MinOffset - Size;
1458     unsigned Align = std::min(TRI->getSpillAlignment(*RC), getStackAlignment());
1459     assert(isPowerOf2_32(Align));
1460     Off &= -Align;
1461     int FI = MFI.CreateFixedSpillStackObject(Size, Off);
1462     MinOffset = std::min(MinOffset, Off);
1463     CSI.push_back(CalleeSavedInfo(R, FI));
1464     SRegs[R] = false;
1465   }
1466
1467   DEBUG({
1468     dbgs() << "CS information: {";
1469     for (unsigned i = 0, n = CSI.size(); i < n; ++i) {
1470       int FI = CSI[i].getFrameIdx();
1471       int Off = MFI.getObjectOffset(FI);
1472       dbgs() << ' ' << PrintReg(CSI[i].getReg(), TRI) << ":fi#" << FI << ":sp";
1473       if (Off >= 0)
1474         dbgs() << '+';
1475       dbgs() << Off;
1476     }
1477     dbgs() << " }\n";
1478   });
1479
1480 #ifndef NDEBUG
1481   // Verify that all registers were handled.
1482   bool MissedReg = false;
1483   for (int x = SRegs.find_first(); x >= 0; x = SRegs.find_next(x)) {
1484     unsigned R = x;
1485     dbgs() << PrintReg(R, TRI) << ' ';
1486     MissedReg = true;
1487   }
1488   if (MissedReg)
1489     llvm_unreachable("...there are unhandled callee-saved registers!");
1490 #endif
1491
1492   return true;
1493 }
1494
1495 bool HexagonFrameLowering::expandCopy(MachineBasicBlock &B,
1496       MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1497       const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1498   MachineInstr *MI = &*It;
1499   DebugLoc DL = MI->getDebugLoc();
1500   unsigned DstR = MI->getOperand(0).getReg();
1501   unsigned SrcR = MI->getOperand(1).getReg();
1502   if (!Hexagon::ModRegsRegClass.contains(DstR) ||
1503       !Hexagon::ModRegsRegClass.contains(SrcR))
1504     return false;
1505
1506   unsigned TmpR = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
1507   BuildMI(B, It, DL, HII.get(TargetOpcode::COPY), TmpR).add(MI->getOperand(1));
1508   BuildMI(B, It, DL, HII.get(TargetOpcode::COPY), DstR)
1509     .addReg(TmpR, RegState::Kill);
1510
1511   NewRegs.push_back(TmpR);
1512   B.erase(It);
1513   return true;
1514 }
1515
1516 bool HexagonFrameLowering::expandStoreInt(MachineBasicBlock &B,
1517       MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1518       const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1519   MachineInstr *MI = &*It;
1520   if (!MI->getOperand(0).isFI())
1521     return false;
1522
1523   DebugLoc DL = MI->getDebugLoc();
1524   unsigned Opc = MI->getOpcode();
1525   unsigned SrcR = MI->getOperand(2).getReg();
1526   bool IsKill = MI->getOperand(2).isKill();
1527   int FI = MI->getOperand(0).getIndex();
1528
1529   // TmpR = C2_tfrpr SrcR   if SrcR is a predicate register
1530   // TmpR = A2_tfrcrr SrcR  if SrcR is a modifier register
1531   unsigned TmpR = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
1532   unsigned TfrOpc = (Opc == Hexagon::STriw_pred) ? Hexagon::C2_tfrpr
1533                                                  : Hexagon::A2_tfrcrr;
1534   BuildMI(B, It, DL, HII.get(TfrOpc), TmpR)
1535     .addReg(SrcR, getKillRegState(IsKill));
1536
1537   // S2_storeri_io FI, 0, TmpR
1538   BuildMI(B, It, DL, HII.get(Hexagon::S2_storeri_io))
1539     .addFrameIndex(FI)
1540     .addImm(0)
1541     .addReg(TmpR, RegState::Kill)
1542     .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1543
1544   NewRegs.push_back(TmpR);
1545   B.erase(It);
1546   return true;
1547 }
1548
1549 bool HexagonFrameLowering::expandLoadInt(MachineBasicBlock &B,
1550       MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1551       const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1552   MachineInstr *MI = &*It;
1553   if (!MI->getOperand(1).isFI())
1554     return false;
1555
1556   DebugLoc DL = MI->getDebugLoc();
1557   unsigned Opc = MI->getOpcode();
1558   unsigned DstR = MI->getOperand(0).getReg();
1559   int FI = MI->getOperand(1).getIndex();
1560
1561   // TmpR = L2_loadri_io FI, 0
1562   unsigned TmpR = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
1563   BuildMI(B, It, DL, HII.get(Hexagon::L2_loadri_io), TmpR)
1564     .addFrameIndex(FI)
1565     .addImm(0)
1566     .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1567
1568   // DstR = C2_tfrrp TmpR   if DstR is a predicate register
1569   // DstR = A2_tfrrcr TmpR  if DstR is a modifier register
1570   unsigned TfrOpc = (Opc == Hexagon::LDriw_pred) ? Hexagon::C2_tfrrp
1571                                                  : Hexagon::A2_tfrrcr;
1572   BuildMI(B, It, DL, HII.get(TfrOpc), DstR)
1573     .addReg(TmpR, RegState::Kill);
1574
1575   NewRegs.push_back(TmpR);
1576   B.erase(It);
1577   return true;
1578 }
1579
1580 bool HexagonFrameLowering::expandStoreVecPred(MachineBasicBlock &B,
1581       MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1582       const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1583   auto &HST = B.getParent()->getSubtarget<HexagonSubtarget>();
1584   MachineInstr *MI = &*It;
1585   if (!MI->getOperand(0).isFI())
1586     return false;
1587
1588   DebugLoc DL = MI->getDebugLoc();
1589   unsigned SrcR = MI->getOperand(2).getReg();
1590   bool IsKill = MI->getOperand(2).isKill();
1591   int FI = MI->getOperand(0).getIndex();
1592
1593   bool Is128B = HST.useHVXDblOps();
1594   auto *RC = !Is128B ? &Hexagon::VectorRegsRegClass
1595                      : &Hexagon::VectorRegs128BRegClass;
1596
1597   // Insert transfer to general vector register.
1598   //   TmpR0 = A2_tfrsi 0x01010101
1599   //   TmpR1 = V6_vandqrt Qx, TmpR0
1600   //   store FI, 0, TmpR1
1601   unsigned TmpR0 = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
1602   unsigned TmpR1 = MRI.createVirtualRegister(RC);
1603
1604   BuildMI(B, It, DL, HII.get(Hexagon::A2_tfrsi), TmpR0)
1605     .addImm(0x01010101);
1606
1607   unsigned VandOpc = !Is128B ? Hexagon::V6_vandqrt : Hexagon::V6_vandqrt_128B;
1608   BuildMI(B, It, DL, HII.get(VandOpc), TmpR1)
1609     .addReg(SrcR, getKillRegState(IsKill))
1610     .addReg(TmpR0, RegState::Kill);
1611
1612   auto *HRI = B.getParent()->getSubtarget<HexagonSubtarget>().getRegisterInfo();
1613   HII.storeRegToStackSlot(B, It, TmpR1, true, FI, RC, HRI);
1614   expandStoreVec(B, std::prev(It), MRI, HII, NewRegs);
1615
1616   NewRegs.push_back(TmpR0);
1617   NewRegs.push_back(TmpR1);
1618   B.erase(It);
1619   return true;
1620 }
1621
1622 bool HexagonFrameLowering::expandLoadVecPred(MachineBasicBlock &B,
1623       MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1624       const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1625   auto &HST = B.getParent()->getSubtarget<HexagonSubtarget>();
1626   MachineInstr *MI = &*It;
1627   if (!MI->getOperand(1).isFI())
1628     return false;
1629
1630   DebugLoc DL = MI->getDebugLoc();
1631   unsigned DstR = MI->getOperand(0).getReg();
1632   int FI = MI->getOperand(1).getIndex();
1633
1634   bool Is128B = HST.useHVXDblOps();
1635   auto *RC = !Is128B ? &Hexagon::VectorRegsRegClass
1636                      : &Hexagon::VectorRegs128BRegClass;
1637
1638   // TmpR0 = A2_tfrsi 0x01010101
1639   // TmpR1 = load FI, 0
1640   // DstR = V6_vandvrt TmpR1, TmpR0
1641   unsigned TmpR0 = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
1642   unsigned TmpR1 = MRI.createVirtualRegister(RC);
1643
1644   BuildMI(B, It, DL, HII.get(Hexagon::A2_tfrsi), TmpR0)
1645     .addImm(0x01010101);
1646   auto *HRI = B.getParent()->getSubtarget<HexagonSubtarget>().getRegisterInfo();
1647   HII.loadRegFromStackSlot(B, It, TmpR1, FI, RC, HRI);
1648   expandLoadVec(B, std::prev(It), MRI, HII, NewRegs);
1649
1650   unsigned VandOpc = !Is128B ? Hexagon::V6_vandvrt : Hexagon::V6_vandvrt_128B;
1651   BuildMI(B, It, DL, HII.get(VandOpc), DstR)
1652     .addReg(TmpR1, RegState::Kill)
1653     .addReg(TmpR0, RegState::Kill);
1654
1655   NewRegs.push_back(TmpR0);
1656   NewRegs.push_back(TmpR1);
1657   B.erase(It);
1658   return true;
1659 }
1660
1661 bool HexagonFrameLowering::expandStoreVec2(MachineBasicBlock &B,
1662       MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1663       const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1664   MachineFunction &MF = *B.getParent();
1665   auto &HST = MF.getSubtarget<HexagonSubtarget>();
1666   auto &MFI = MF.getFrameInfo();
1667   auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
1668   MachineInstr *MI = &*It;
1669   if (!MI->getOperand(0).isFI())
1670     return false;
1671
1672   // It is possible that the double vector being stored is only partially
1673   // defined. From the point of view of the liveness tracking, it is ok to
1674   // store it as a whole, but if we break it up we may end up storing a
1675   // register that is entirely undefined.
1676   LivePhysRegs LPR(HRI);
1677   LPR.addLiveIns(B);
1678   SmallVector<std::pair<unsigned, const MachineOperand*>,2> Clobbers;
1679   for (auto R = B.begin(); R != It; ++R) {
1680     Clobbers.clear();
1681     LPR.stepForward(*R, Clobbers);
1682     // Dead defs are recorded in Clobbers, but are not automatically removed
1683     // from the live set.
1684     for (auto &C : Clobbers)
1685       if (C.second->isReg() && C.second->isDead())
1686         LPR.removeReg(C.first);
1687   }
1688
1689   DebugLoc DL = MI->getDebugLoc();
1690   unsigned SrcR = MI->getOperand(2).getReg();
1691   unsigned SrcLo = HRI.getSubReg(SrcR, Hexagon::vsub_lo);
1692   unsigned SrcHi = HRI.getSubReg(SrcR, Hexagon::vsub_hi);
1693   bool IsKill = MI->getOperand(2).isKill();
1694   int FI = MI->getOperand(0).getIndex();
1695
1696   bool Is128B = HST.useHVXDblOps();
1697   const auto &RC = !Is128B ? Hexagon::VectorRegsRegClass
1698                            : Hexagon::VectorRegs128BRegClass;
1699   unsigned Size = HRI.getSpillSize(RC);
1700   unsigned NeedAlign = HRI.getSpillAlignment(RC);
1701   unsigned HasAlign = MFI.getObjectAlignment(FI);
1702   unsigned StoreOpc;
1703
1704   // Store low part.
1705   if (LPR.contains(SrcLo)) {
1706     if (NeedAlign <= HasAlign)
1707       StoreOpc = !Is128B ? Hexagon::V6_vS32b_ai  : Hexagon::V6_vS32b_ai_128B;
1708     else
1709       StoreOpc = !Is128B ? Hexagon::V6_vS32Ub_ai : Hexagon::V6_vS32Ub_ai_128B;
1710
1711     BuildMI(B, It, DL, HII.get(StoreOpc))
1712       .addFrameIndex(FI)
1713       .addImm(0)
1714       .addReg(SrcLo, getKillRegState(IsKill))
1715       .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1716   }
1717
1718   // Store high part.
1719   if (LPR.contains(SrcHi)) {
1720     if (NeedAlign <= MinAlign(HasAlign, Size))
1721       StoreOpc = !Is128B ? Hexagon::V6_vS32b_ai  : Hexagon::V6_vS32b_ai_128B;
1722     else
1723       StoreOpc = !Is128B ? Hexagon::V6_vS32Ub_ai : Hexagon::V6_vS32Ub_ai_128B;
1724
1725     BuildMI(B, It, DL, HII.get(StoreOpc))
1726       .addFrameIndex(FI)
1727       .addImm(Size)
1728       .addReg(SrcHi, getKillRegState(IsKill))
1729       .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1730   }
1731
1732   B.erase(It);
1733   return true;
1734 }
1735
1736 bool HexagonFrameLowering::expandLoadVec2(MachineBasicBlock &B,
1737       MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1738       const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1739   MachineFunction &MF = *B.getParent();
1740   auto &HST = MF.getSubtarget<HexagonSubtarget>();
1741   auto &MFI = MF.getFrameInfo();
1742   auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
1743   MachineInstr *MI = &*It;
1744   if (!MI->getOperand(1).isFI())
1745     return false;
1746
1747   DebugLoc DL = MI->getDebugLoc();
1748   unsigned DstR = MI->getOperand(0).getReg();
1749   unsigned DstHi = HRI.getSubReg(DstR, Hexagon::vsub_hi);
1750   unsigned DstLo = HRI.getSubReg(DstR, Hexagon::vsub_lo);
1751   int FI = MI->getOperand(1).getIndex();
1752
1753   bool Is128B = HST.useHVXDblOps();
1754   const auto &RC = !Is128B ? Hexagon::VectorRegsRegClass
1755                            : Hexagon::VectorRegs128BRegClass;
1756   unsigned Size = HRI.getSpillSize(RC);
1757   unsigned NeedAlign = HRI.getSpillAlignment(RC);
1758   unsigned HasAlign = MFI.getObjectAlignment(FI);
1759   unsigned LoadOpc;
1760
1761   // Load low part.
1762   if (NeedAlign <= HasAlign)
1763     LoadOpc = !Is128B ? Hexagon::V6_vL32b_ai  : Hexagon::V6_vL32b_ai_128B;
1764   else
1765     LoadOpc = !Is128B ? Hexagon::V6_vL32Ub_ai : Hexagon::V6_vL32Ub_ai_128B;
1766
1767   BuildMI(B, It, DL, HII.get(LoadOpc), DstLo)
1768     .addFrameIndex(FI)
1769     .addImm(0)
1770     .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1771
1772   // Load high part.
1773   if (NeedAlign <= MinAlign(HasAlign, Size))
1774     LoadOpc = !Is128B ? Hexagon::V6_vL32b_ai  : Hexagon::V6_vL32b_ai_128B;
1775   else
1776     LoadOpc = !Is128B ? Hexagon::V6_vL32Ub_ai : Hexagon::V6_vL32Ub_ai_128B;
1777
1778   BuildMI(B, It, DL, HII.get(LoadOpc), DstHi)
1779     .addFrameIndex(FI)
1780     .addImm(Size)
1781     .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1782
1783   B.erase(It);
1784   return true;
1785 }
1786
1787 bool HexagonFrameLowering::expandStoreVec(MachineBasicBlock &B,
1788       MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1789       const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1790   MachineFunction &MF = *B.getParent();
1791   auto &HST = MF.getSubtarget<HexagonSubtarget>();
1792   auto &MFI = MF.getFrameInfo();
1793   MachineInstr *MI = &*It;
1794   if (!MI->getOperand(0).isFI())
1795     return false;
1796
1797   auto &HRI = *HST.getRegisterInfo();
1798   DebugLoc DL = MI->getDebugLoc();
1799   unsigned SrcR = MI->getOperand(2).getReg();
1800   bool IsKill = MI->getOperand(2).isKill();
1801   int FI = MI->getOperand(0).getIndex();
1802
1803   bool Is128B = HST.useHVXDblOps();
1804   const auto &RC = !Is128B ? Hexagon::VectorRegsRegClass
1805                            : Hexagon::VectorRegs128BRegClass;
1806   unsigned NeedAlign = HRI.getSpillAlignment(RC);
1807   unsigned HasAlign = MFI.getObjectAlignment(FI);
1808   unsigned StoreOpc;
1809
1810   if (NeedAlign <= HasAlign)
1811     StoreOpc = !Is128B ? Hexagon::V6_vS32b_ai : Hexagon::V6_vS32b_ai_128B;
1812   else
1813     StoreOpc = !Is128B ? Hexagon::V6_vS32Ub_ai : Hexagon::V6_vS32Ub_ai_128B;
1814
1815   BuildMI(B, It, DL, HII.get(StoreOpc))
1816     .addFrameIndex(FI)
1817     .addImm(0)
1818     .addReg(SrcR, getKillRegState(IsKill))
1819     .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1820
1821   B.erase(It);
1822   return true;
1823 }
1824
1825 bool HexagonFrameLowering::expandLoadVec(MachineBasicBlock &B,
1826       MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1827       const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1828   MachineFunction &MF = *B.getParent();
1829   auto &HST = MF.getSubtarget<HexagonSubtarget>();
1830   auto &MFI = MF.getFrameInfo();
1831   MachineInstr *MI = &*It;
1832   if (!MI->getOperand(1).isFI())
1833     return false;
1834
1835   auto &HRI = *HST.getRegisterInfo();
1836   DebugLoc DL = MI->getDebugLoc();
1837   unsigned DstR = MI->getOperand(0).getReg();
1838   int FI = MI->getOperand(1).getIndex();
1839
1840   bool Is128B = HST.useHVXDblOps();
1841   const auto &RC = !Is128B ? Hexagon::VectorRegsRegClass
1842                            : Hexagon::VectorRegs128BRegClass;
1843   unsigned NeedAlign = HRI.getSpillAlignment(RC);
1844   unsigned HasAlign = MFI.getObjectAlignment(FI);
1845   unsigned LoadOpc;
1846
1847   if (NeedAlign <= HasAlign)
1848     LoadOpc = !Is128B ? Hexagon::V6_vL32b_ai : Hexagon::V6_vL32b_ai_128B;
1849   else
1850     LoadOpc = !Is128B ? Hexagon::V6_vL32Ub_ai : Hexagon::V6_vL32Ub_ai_128B;
1851
1852   BuildMI(B, It, DL, HII.get(LoadOpc), DstR)
1853     .addFrameIndex(FI)
1854     .addImm(0)
1855     .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1856
1857   B.erase(It);
1858   return true;
1859 }
1860
1861 bool HexagonFrameLowering::expandSpillMacros(MachineFunction &MF,
1862       SmallVectorImpl<unsigned> &NewRegs) const {
1863   auto &HST = MF.getSubtarget<HexagonSubtarget>();
1864   auto &HII = *HST.getInstrInfo();
1865   MachineRegisterInfo &MRI = MF.getRegInfo();
1866   bool Changed = false;
1867
1868   for (auto &B : MF) {
1869     // Traverse the basic block.
1870     MachineBasicBlock::iterator NextI;
1871     for (auto I = B.begin(), E = B.end(); I != E; I = NextI) {
1872       MachineInstr *MI = &*I;
1873       NextI = std::next(I);
1874       unsigned Opc = MI->getOpcode();
1875
1876       switch (Opc) {
1877         case TargetOpcode::COPY:
1878           Changed |= expandCopy(B, I, MRI, HII, NewRegs);
1879           break;
1880         case Hexagon::STriw_pred:
1881         case Hexagon::STriw_mod:
1882           Changed |= expandStoreInt(B, I, MRI, HII, NewRegs);
1883           break;
1884         case Hexagon::LDriw_pred:
1885         case Hexagon::LDriw_mod:
1886           Changed |= expandLoadInt(B, I, MRI, HII, NewRegs);
1887           break;
1888         case Hexagon::PS_vstorerq_ai:
1889         case Hexagon::PS_vstorerq_ai_128B:
1890           Changed |= expandStoreVecPred(B, I, MRI, HII, NewRegs);
1891           break;
1892         case Hexagon::PS_vloadrq_ai:
1893         case Hexagon::PS_vloadrq_ai_128B:
1894           Changed |= expandLoadVecPred(B, I, MRI, HII, NewRegs);
1895           break;
1896         case Hexagon::PS_vloadrw_ai:
1897         case Hexagon::PS_vloadrwu_ai:
1898         case Hexagon::PS_vloadrw_ai_128B:
1899         case Hexagon::PS_vloadrwu_ai_128B:
1900           Changed |= expandLoadVec2(B, I, MRI, HII, NewRegs);
1901           break;
1902         case Hexagon::PS_vstorerw_ai:
1903         case Hexagon::PS_vstorerwu_ai:
1904         case Hexagon::PS_vstorerw_ai_128B:
1905         case Hexagon::PS_vstorerwu_ai_128B:
1906           Changed |= expandStoreVec2(B, I, MRI, HII, NewRegs);
1907           break;
1908       }
1909     }
1910   }
1911
1912   return Changed;
1913 }
1914
1915 void HexagonFrameLowering::determineCalleeSaves(MachineFunction &MF,
1916                                                 BitVector &SavedRegs,
1917                                                 RegScavenger *RS) const {
1918   auto &HST = MF.getSubtarget<HexagonSubtarget>();
1919   auto &HRI = *HST.getRegisterInfo();
1920
1921   SavedRegs.resize(HRI.getNumRegs());
1922
1923   // If we have a function containing __builtin_eh_return we want to spill and
1924   // restore all callee saved registers. Pretend that they are used.
1925   if (MF.getInfo<HexagonMachineFunctionInfo>()->hasEHReturn())
1926     for (const MCPhysReg *R = HRI.getCalleeSavedRegs(&MF); *R; ++R)
1927       SavedRegs.set(*R);
1928
1929   // Replace predicate register pseudo spill code.
1930   SmallVector<unsigned,8> NewRegs;
1931   expandSpillMacros(MF, NewRegs);
1932   if (OptimizeSpillSlots && !isOptNone(MF))
1933     optimizeSpillSlots(MF, NewRegs);
1934
1935   // We need to reserve a a spill slot if scavenging could potentially require
1936   // spilling a scavenged register.
1937   if (!NewRegs.empty() || mayOverflowFrameOffset(MF)) {
1938     MachineFrameInfo &MFI = MF.getFrameInfo();
1939     MachineRegisterInfo &MRI = MF.getRegInfo();
1940     SetVector<const TargetRegisterClass*> SpillRCs;
1941     // Reserve an int register in any case, because it could be used to hold
1942     // the stack offset in case it does not fit into a spill instruction.
1943     SpillRCs.insert(&Hexagon::IntRegsRegClass);
1944
1945     for (unsigned VR : NewRegs)
1946       SpillRCs.insert(MRI.getRegClass(VR));
1947
1948     for (auto *RC : SpillRCs) {
1949       if (!needToReserveScavengingSpillSlots(MF, HRI, RC))
1950         continue;
1951       unsigned Num = RC == &Hexagon::IntRegsRegClass ? NumberScavengerSlots : 1;
1952       unsigned S = HRI.getSpillSize(*RC), A = HRI.getSpillAlignment(*RC);
1953       for (unsigned i = 0; i < Num; i++) {
1954         int NewFI = MFI.CreateSpillStackObject(S, A);
1955         RS->addScavengingFrameIndex(NewFI);
1956       }
1957     }
1958   }
1959
1960   TargetFrameLowering::determineCalleeSaves(MF, SavedRegs, RS);
1961 }
1962
1963 unsigned HexagonFrameLowering::findPhysReg(MachineFunction &MF,
1964       HexagonBlockRanges::IndexRange &FIR,
1965       HexagonBlockRanges::InstrIndexMap &IndexMap,
1966       HexagonBlockRanges::RegToRangeMap &DeadMap,
1967       const TargetRegisterClass *RC) const {
1968   auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
1969   auto &MRI = MF.getRegInfo();
1970
1971   auto isDead = [&FIR,&DeadMap] (unsigned Reg) -> bool {
1972     auto F = DeadMap.find({Reg,0});
1973     if (F == DeadMap.end())
1974       return false;
1975     for (auto &DR : F->second)
1976       if (DR.contains(FIR))
1977         return true;
1978     return false;
1979   };
1980
1981   for (unsigned Reg : RC->getRawAllocationOrder(MF)) {
1982     bool Dead = true;
1983     for (auto R : HexagonBlockRanges::expandToSubRegs({Reg,0}, MRI, HRI)) {
1984       if (isDead(R.Reg))
1985         continue;
1986       Dead = false;
1987       break;
1988     }
1989     if (Dead)
1990       return Reg;
1991   }
1992   return 0;
1993 }
1994
1995 void HexagonFrameLowering::optimizeSpillSlots(MachineFunction &MF,
1996       SmallVectorImpl<unsigned> &VRegs) const {
1997   auto &HST = MF.getSubtarget<HexagonSubtarget>();
1998   auto &HII = *HST.getInstrInfo();
1999   auto &HRI = *HST.getRegisterInfo();
2000   auto &MRI = MF.getRegInfo();
2001   HexagonBlockRanges HBR(MF);
2002
2003   typedef std::map<MachineBasicBlock*,HexagonBlockRanges::InstrIndexMap>
2004       BlockIndexMap;
2005   typedef std::map<MachineBasicBlock*,HexagonBlockRanges::RangeList>
2006       BlockRangeMap;
2007   typedef HexagonBlockRanges::IndexType IndexType;
2008
2009   struct SlotInfo {
2010     BlockRangeMap Map;
2011     unsigned Size = 0;
2012     const TargetRegisterClass *RC = nullptr;
2013
2014     SlotInfo() = default;
2015   };
2016
2017   BlockIndexMap BlockIndexes;
2018   SmallSet<int,4> BadFIs;
2019   std::map<int,SlotInfo> FIRangeMap;
2020
2021   // Accumulate register classes: get a common class for a pre-existing
2022   // class HaveRC and a new class NewRC. Return nullptr if a common class
2023   // cannot be found, otherwise return the resulting class. If HaveRC is
2024   // nullptr, assume that it is still unset.
2025   auto getCommonRC =
2026       [](const TargetRegisterClass *HaveRC,
2027          const TargetRegisterClass *NewRC) -> const TargetRegisterClass * {
2028     if (HaveRC == nullptr || HaveRC == NewRC)
2029       return NewRC;
2030     // Different classes, both non-null. Pick the more general one.
2031     if (HaveRC->hasSubClassEq(NewRC))
2032       return HaveRC;
2033     if (NewRC->hasSubClassEq(HaveRC))
2034       return NewRC;
2035     return nullptr;
2036   };
2037
2038   // Scan all blocks in the function. Check all occurrences of frame indexes,
2039   // and collect relevant information.
2040   for (auto &B : MF) {
2041     std::map<int,IndexType> LastStore, LastLoad;
2042     // Emplace appears not to be supported in gcc 4.7.2-4.
2043     //auto P = BlockIndexes.emplace(&B, HexagonBlockRanges::InstrIndexMap(B));
2044     auto P = BlockIndexes.insert(
2045                 std::make_pair(&B, HexagonBlockRanges::InstrIndexMap(B)));
2046     auto &IndexMap = P.first->second;
2047     DEBUG(dbgs() << "Index map for BB#" << B.getNumber() << "\n"
2048                  << IndexMap << '\n');
2049
2050     for (auto &In : B) {
2051       int LFI, SFI;
2052       bool Load = HII.isLoadFromStackSlot(In, LFI) && !HII.isPredicated(In);
2053       bool Store = HII.isStoreToStackSlot(In, SFI) && !HII.isPredicated(In);
2054       if (Load && Store) {
2055         // If it's both a load and a store, then we won't handle it.
2056         BadFIs.insert(LFI);
2057         BadFIs.insert(SFI);
2058         continue;
2059       }
2060       // Check for register classes of the register used as the source for
2061       // the store, and the register used as the destination for the load.
2062       // Also, only accept base+imm_offset addressing modes. Other addressing
2063       // modes can have side-effects (post-increments, etc.). For stack
2064       // slots they are very unlikely, so there is not much loss due to
2065       // this restriction.
2066       if (Load || Store) {
2067         int TFI = Load ? LFI : SFI;
2068         unsigned AM = HII.getAddrMode(In);
2069         SlotInfo &SI = FIRangeMap[TFI];
2070         bool Bad = (AM != HexagonII::BaseImmOffset);
2071         if (!Bad) {
2072           // If the addressing mode is ok, check the register class.
2073           unsigned OpNum = Load ? 0 : 2;
2074           auto *RC = HII.getRegClass(In.getDesc(), OpNum, &HRI, MF);
2075           RC = getCommonRC(SI.RC, RC);
2076           if (RC == nullptr)
2077             Bad = true;
2078           else
2079             SI.RC = RC;
2080         }
2081         if (!Bad) {
2082           // Check sizes.
2083           unsigned S = (1U << (HII.getMemAccessSize(In) - 1));
2084           if (SI.Size != 0 && SI.Size != S)
2085             Bad = true;
2086           else
2087             SI.Size = S;
2088         }
2089         if (!Bad) {
2090           for (auto *Mo : In.memoperands()) {
2091             if (!Mo->isVolatile())
2092               continue;
2093             Bad = true;
2094             break;
2095           }
2096         }
2097         if (Bad)
2098           BadFIs.insert(TFI);
2099       }
2100
2101       // Locate uses of frame indices.
2102       for (unsigned i = 0, n = In.getNumOperands(); i < n; ++i) {
2103         const MachineOperand &Op = In.getOperand(i);
2104         if (!Op.isFI())
2105           continue;
2106         int FI = Op.getIndex();
2107         // Make sure that the following operand is an immediate and that
2108         // it is 0. This is the offset in the stack object.
2109         if (i+1 >= n || !In.getOperand(i+1).isImm() ||
2110             In.getOperand(i+1).getImm() != 0)
2111           BadFIs.insert(FI);
2112         if (BadFIs.count(FI))
2113           continue;
2114
2115         IndexType Index = IndexMap.getIndex(&In);
2116         if (Load) {
2117           if (LastStore[FI] == IndexType::None)
2118             LastStore[FI] = IndexType::Entry;
2119           LastLoad[FI] = Index;
2120         } else if (Store) {
2121           HexagonBlockRanges::RangeList &RL = FIRangeMap[FI].Map[&B];
2122           if (LastStore[FI] != IndexType::None)
2123             RL.add(LastStore[FI], LastLoad[FI], false, false);
2124           else if (LastLoad[FI] != IndexType::None)
2125             RL.add(IndexType::Entry, LastLoad[FI], false, false);
2126           LastLoad[FI] = IndexType::None;
2127           LastStore[FI] = Index;
2128         } else {
2129           BadFIs.insert(FI);
2130         }
2131       }
2132     }
2133
2134     for (auto &I : LastLoad) {
2135       IndexType LL = I.second;
2136       if (LL == IndexType::None)
2137         continue;
2138       auto &RL = FIRangeMap[I.first].Map[&B];
2139       IndexType &LS = LastStore[I.first];
2140       if (LS != IndexType::None)
2141         RL.add(LS, LL, false, false);
2142       else
2143         RL.add(IndexType::Entry, LL, false, false);
2144       LS = IndexType::None;
2145     }
2146     for (auto &I : LastStore) {
2147       IndexType LS = I.second;
2148       if (LS == IndexType::None)
2149         continue;
2150       auto &RL = FIRangeMap[I.first].Map[&B];
2151       RL.add(LS, IndexType::None, false, false);
2152     }
2153   }
2154
2155   DEBUG({
2156     for (auto &P : FIRangeMap) {
2157       dbgs() << "fi#" << P.first;
2158       if (BadFIs.count(P.first))
2159         dbgs() << " (bad)";
2160       dbgs() << "  RC: ";
2161       if (P.second.RC != nullptr)
2162         dbgs() << HRI.getRegClassName(P.second.RC) << '\n';
2163       else
2164         dbgs() << "<null>\n";
2165       for (auto &R : P.second.Map)
2166         dbgs() << "  BB#" << R.first->getNumber() << " { " << R.second << "}\n";
2167     }
2168   });
2169
2170   // When a slot is loaded from in a block without being stored to in the
2171   // same block, it is live-on-entry to this block. To avoid CFG analysis,
2172   // consider this slot to be live-on-exit from all blocks.
2173   SmallSet<int,4> LoxFIs;
2174
2175   std::map<MachineBasicBlock*,std::vector<int>> BlockFIMap;
2176
2177   for (auto &P : FIRangeMap) {
2178     // P = pair(FI, map: BB->RangeList)
2179     if (BadFIs.count(P.first))
2180       continue;
2181     for (auto &B : MF) {
2182       auto F = P.second.Map.find(&B);
2183       // F = pair(BB, RangeList)
2184       if (F == P.second.Map.end() || F->second.empty())
2185         continue;
2186       HexagonBlockRanges::IndexRange &IR = F->second.front();
2187       if (IR.start() == IndexType::Entry)
2188         LoxFIs.insert(P.first);
2189       BlockFIMap[&B].push_back(P.first);
2190     }
2191   }
2192
2193   DEBUG({
2194     dbgs() << "Block-to-FI map (* -- live-on-exit):\n";
2195     for (auto &P : BlockFIMap) {
2196       auto &FIs = P.second;
2197       if (FIs.empty())
2198         continue;
2199       dbgs() << "  BB#" << P.first->getNumber() << ": {";
2200       for (auto I : FIs) {
2201         dbgs() << " fi#" << I;
2202         if (LoxFIs.count(I))
2203           dbgs() << '*';
2204       }
2205       dbgs() << " }\n";
2206     }
2207   });
2208
2209 #ifndef NDEBUG
2210   bool HasOptLimit = SpillOptMax.getPosition();
2211 #endif
2212
2213   // eliminate loads, when all loads eliminated, eliminate all stores.
2214   for (auto &B : MF) {
2215     auto F = BlockIndexes.find(&B);
2216     assert(F != BlockIndexes.end());
2217     HexagonBlockRanges::InstrIndexMap &IM = F->second;
2218     HexagonBlockRanges::RegToRangeMap LM = HBR.computeLiveMap(IM);
2219     HexagonBlockRanges::RegToRangeMap DM = HBR.computeDeadMap(IM, LM);
2220     DEBUG(dbgs() << "BB#" << B.getNumber() << " dead map\n"
2221                  << HexagonBlockRanges::PrintRangeMap(DM, HRI));
2222
2223     for (auto FI : BlockFIMap[&B]) {
2224       if (BadFIs.count(FI))
2225         continue;
2226       DEBUG(dbgs() << "Working on fi#" << FI << '\n');
2227       HexagonBlockRanges::RangeList &RL = FIRangeMap[FI].Map[&B];
2228       for (auto &Range : RL) {
2229         DEBUG(dbgs() << "--Examining range:" << RL << '\n');
2230         if (!IndexType::isInstr(Range.start()) ||
2231             !IndexType::isInstr(Range.end()))
2232           continue;
2233         MachineInstr &SI = *IM.getInstr(Range.start());
2234         MachineInstr &EI = *IM.getInstr(Range.end());
2235         assert(SI.mayStore() && "Unexpected start instruction");
2236         assert(EI.mayLoad() && "Unexpected end instruction");
2237         MachineOperand &SrcOp = SI.getOperand(2);
2238
2239         HexagonBlockRanges::RegisterRef SrcRR = { SrcOp.getReg(),
2240                                                   SrcOp.getSubReg() };
2241         auto *RC = HII.getRegClass(SI.getDesc(), 2, &HRI, MF);
2242         // The this-> is needed to unconfuse MSVC.
2243         unsigned FoundR = this->findPhysReg(MF, Range, IM, DM, RC);
2244         DEBUG(dbgs() << "Replacement reg:" << PrintReg(FoundR, &HRI) << '\n');
2245         if (FoundR == 0)
2246           continue;
2247 #ifndef NDEBUG
2248         if (HasOptLimit) {
2249           if (SpillOptCount >= SpillOptMax)
2250             return;
2251           SpillOptCount++;
2252         }
2253 #endif
2254
2255         // Generate the copy-in: "FoundR = COPY SrcR" at the store location.
2256         MachineBasicBlock::iterator StartIt = SI.getIterator(), NextIt;
2257         MachineInstr *CopyIn = nullptr;
2258         if (SrcRR.Reg != FoundR || SrcRR.Sub != 0) {
2259           const DebugLoc &DL = SI.getDebugLoc();
2260           CopyIn = BuildMI(B, StartIt, DL, HII.get(TargetOpcode::COPY), FoundR)
2261                        .add(SrcOp);
2262         }
2263
2264         ++StartIt;
2265         // Check if this is a last store and the FI is live-on-exit.
2266         if (LoxFIs.count(FI) && (&Range == &RL.back())) {
2267           // Update store's source register.
2268           if (unsigned SR = SrcOp.getSubReg())
2269             SrcOp.setReg(HRI.getSubReg(FoundR, SR));
2270           else
2271             SrcOp.setReg(FoundR);
2272           SrcOp.setSubReg(0);
2273           // We are keeping this register live.
2274           SrcOp.setIsKill(false);
2275         } else {
2276           B.erase(&SI);
2277           IM.replaceInstr(&SI, CopyIn);
2278         }
2279
2280         auto EndIt = std::next(EI.getIterator());
2281         for (auto It = StartIt; It != EndIt; It = NextIt) {
2282           MachineInstr &MI = *It;
2283           NextIt = std::next(It);
2284           int TFI;
2285           if (!HII.isLoadFromStackSlot(MI, TFI) || TFI != FI)
2286             continue;
2287           unsigned DstR = MI.getOperand(0).getReg();
2288           assert(MI.getOperand(0).getSubReg() == 0);
2289           MachineInstr *CopyOut = nullptr;
2290           if (DstR != FoundR) {
2291             DebugLoc DL = MI.getDebugLoc();
2292             unsigned MemSize = (1U << (HII.getMemAccessSize(MI) - 1));
2293             assert(HII.getAddrMode(MI) == HexagonII::BaseImmOffset);
2294             unsigned CopyOpc = TargetOpcode::COPY;
2295             if (HII.isSignExtendingLoad(MI))
2296               CopyOpc = (MemSize == 1) ? Hexagon::A2_sxtb : Hexagon::A2_sxth;
2297             else if (HII.isZeroExtendingLoad(MI))
2298               CopyOpc = (MemSize == 1) ? Hexagon::A2_zxtb : Hexagon::A2_zxth;
2299             CopyOut = BuildMI(B, It, DL, HII.get(CopyOpc), DstR)
2300                         .addReg(FoundR, getKillRegState(&MI == &EI));
2301           }
2302           IM.replaceInstr(&MI, CopyOut);
2303           B.erase(It);
2304         }
2305
2306         // Update the dead map.
2307         HexagonBlockRanges::RegisterRef FoundRR = { FoundR, 0 };
2308         for (auto RR : HexagonBlockRanges::expandToSubRegs(FoundRR, MRI, HRI))
2309           DM[RR].subtract(Range);
2310       } // for Range in range list
2311     }
2312   }
2313 }
2314
2315 void HexagonFrameLowering::expandAlloca(MachineInstr *AI,
2316       const HexagonInstrInfo &HII, unsigned SP, unsigned CF) const {
2317   MachineBasicBlock &MB = *AI->getParent();
2318   DebugLoc DL = AI->getDebugLoc();
2319   unsigned A = AI->getOperand(2).getImm();
2320
2321   // Have
2322   //    Rd  = alloca Rs, #A
2323   //
2324   // If Rs and Rd are different registers, use this sequence:
2325   //    Rd  = sub(r29, Rs)
2326   //    r29 = sub(r29, Rs)
2327   //    Rd  = and(Rd, #-A)    ; if necessary
2328   //    r29 = and(r29, #-A)   ; if necessary
2329   //    Rd  = add(Rd, #CF)    ; CF size aligned to at most A
2330   // otherwise, do
2331   //    Rd  = sub(r29, Rs)
2332   //    Rd  = and(Rd, #-A)    ; if necessary
2333   //    r29 = Rd
2334   //    Rd  = add(Rd, #CF)    ; CF size aligned to at most A
2335
2336   MachineOperand &RdOp = AI->getOperand(0);
2337   MachineOperand &RsOp = AI->getOperand(1);
2338   unsigned Rd = RdOp.getReg(), Rs = RsOp.getReg();
2339
2340   // Rd = sub(r29, Rs)
2341   BuildMI(MB, AI, DL, HII.get(Hexagon::A2_sub), Rd)
2342       .addReg(SP)
2343       .addReg(Rs);
2344   if (Rs != Rd) {
2345     // r29 = sub(r29, Rs)
2346     BuildMI(MB, AI, DL, HII.get(Hexagon::A2_sub), SP)
2347         .addReg(SP)
2348         .addReg(Rs);
2349   }
2350   if (A > 8) {
2351     // Rd  = and(Rd, #-A)
2352     BuildMI(MB, AI, DL, HII.get(Hexagon::A2_andir), Rd)
2353         .addReg(Rd)
2354         .addImm(-int64_t(A));
2355     if (Rs != Rd)
2356       BuildMI(MB, AI, DL, HII.get(Hexagon::A2_andir), SP)
2357           .addReg(SP)
2358           .addImm(-int64_t(A));
2359   }
2360   if (Rs == Rd) {
2361     // r29 = Rd
2362     BuildMI(MB, AI, DL, HII.get(TargetOpcode::COPY), SP)
2363         .addReg(Rd);
2364   }
2365   if (CF > 0) {
2366     // Rd = add(Rd, #CF)
2367     BuildMI(MB, AI, DL, HII.get(Hexagon::A2_addi), Rd)
2368         .addReg(Rd)
2369         .addImm(CF);
2370   }
2371 }
2372
2373 bool HexagonFrameLowering::needsAligna(const MachineFunction &MF) const {
2374   const MachineFrameInfo &MFI = MF.getFrameInfo();
2375   if (!MFI.hasVarSizedObjects())
2376     return false;
2377   unsigned MaxA = MFI.getMaxAlignment();
2378   if (MaxA <= getStackAlignment())
2379     return false;
2380   return true;
2381 }
2382
2383 const MachineInstr *HexagonFrameLowering::getAlignaInstr(
2384       const MachineFunction &MF) const {
2385   for (auto &B : MF)
2386     for (auto &I : B)
2387       if (I.getOpcode() == Hexagon::PS_aligna)
2388         return &I;
2389   return nullptr;
2390 }
2391
2392 /// Adds all callee-saved registers as implicit uses or defs to the
2393 /// instruction.
2394 void HexagonFrameLowering::addCalleeSaveRegistersAsImpOperand(MachineInstr *MI,
2395       const CSIVect &CSI, bool IsDef, bool IsKill) const {
2396   // Add the callee-saved registers as implicit uses.
2397   for (auto &R : CSI)
2398     MI->addOperand(MachineOperand::CreateReg(R.getReg(), IsDef, true, IsKill));
2399 }
2400
2401 /// Determine whether the callee-saved register saves and restores should
2402 /// be generated via inline code. If this function returns "true", inline
2403 /// code will be generated. If this function returns "false", additional
2404 /// checks are performed, which may still lead to the inline code.
2405 bool HexagonFrameLowering::shouldInlineCSR(MachineFunction &MF,
2406       const CSIVect &CSI) const {
2407   if (MF.getInfo<HexagonMachineFunctionInfo>()->hasEHReturn())
2408     return true;
2409   if (!isOptSize(MF) && !isMinSize(MF))
2410     if (MF.getTarget().getOptLevel() > CodeGenOpt::Default)
2411       return true;
2412
2413   // Check if CSI only has double registers, and if the registers form
2414   // a contiguous block starting from D8.
2415   BitVector Regs(Hexagon::NUM_TARGET_REGS);
2416   for (unsigned i = 0, n = CSI.size(); i < n; ++i) {
2417     unsigned R = CSI[i].getReg();
2418     if (!Hexagon::DoubleRegsRegClass.contains(R))
2419       return true;
2420     Regs[R] = true;
2421   }
2422   int F = Regs.find_first();
2423   if (F != Hexagon::D8)
2424     return true;
2425   while (F >= 0) {
2426     int N = Regs.find_next(F);
2427     if (N >= 0 && N != F+1)
2428       return true;
2429     F = N;
2430   }
2431
2432   return false;
2433 }
2434
2435 bool HexagonFrameLowering::useSpillFunction(MachineFunction &MF,
2436       const CSIVect &CSI) const {
2437   if (shouldInlineCSR(MF, CSI))
2438     return false;
2439   unsigned NumCSI = CSI.size();
2440   if (NumCSI <= 1)
2441     return false;
2442
2443   unsigned Threshold = isOptSize(MF) ? SpillFuncThresholdOs
2444                                      : SpillFuncThreshold;
2445   return Threshold < NumCSI;
2446 }
2447
2448 bool HexagonFrameLowering::useRestoreFunction(MachineFunction &MF,
2449       const CSIVect &CSI) const {
2450   if (shouldInlineCSR(MF, CSI))
2451     return false;
2452   // The restore functions do a bit more than just restoring registers.
2453   // The non-returning versions will go back directly to the caller's
2454   // caller, others will clean up the stack frame in preparation for
2455   // a tail call. Using them can still save code size even if only one
2456   // register is getting restores. Make the decision based on -Oz:
2457   // using -Os will use inline restore for a single register.
2458   if (isMinSize(MF))
2459     return true;
2460   unsigned NumCSI = CSI.size();
2461   if (NumCSI <= 1)
2462     return false;
2463
2464   unsigned Threshold = isOptSize(MF) ? SpillFuncThresholdOs-1
2465                                      : SpillFuncThreshold;
2466   return Threshold < NumCSI;
2467 }
2468
2469 bool HexagonFrameLowering::mayOverflowFrameOffset(MachineFunction &MF) const {
2470   unsigned StackSize = MF.getFrameInfo().estimateStackSize(MF);
2471   auto &HST = MF.getSubtarget<HexagonSubtarget>();
2472   // A fairly simplistic guess as to whether a potential load/store to a
2473   // stack location could require an extra register.
2474   if (HST.useHVXOps() && StackSize > 256)
2475     return true;
2476
2477   // Check if the function has store-immediate instructions that access
2478   // the stack. Since the offset field is not extendable, if the stack
2479   // size exceeds the offset limit (6 bits, shifted), the stores will
2480   // require a new base register.
2481   bool HasImmStack = false;
2482   unsigned MinLS = ~0u;   // Log_2 of the memory access size.
2483
2484   for (const MachineBasicBlock &B : MF) {
2485     for (const MachineInstr &MI : B) {
2486       unsigned LS = 0;
2487       switch (MI.getOpcode()) {
2488         case Hexagon::S4_storeirit_io:
2489         case Hexagon::S4_storeirif_io:
2490         case Hexagon::S4_storeiri_io:
2491           ++LS;
2492           LLVM_FALLTHROUGH;
2493         case Hexagon::S4_storeirht_io:
2494         case Hexagon::S4_storeirhf_io:
2495         case Hexagon::S4_storeirh_io:
2496           ++LS;
2497           LLVM_FALLTHROUGH;
2498         case Hexagon::S4_storeirbt_io:
2499         case Hexagon::S4_storeirbf_io:
2500         case Hexagon::S4_storeirb_io:
2501           if (MI.getOperand(0).isFI())
2502             HasImmStack = true;
2503           MinLS = std::min(MinLS, LS);
2504           break;
2505       }
2506     }
2507   }
2508
2509   if (HasImmStack)
2510     return !isUInt<6>(StackSize >> MinLS);
2511
2512   return false;
2513 }