LLVM  5.0.0
HexagonFrameLowering.cpp
Go to the documentation of this file.
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 #include "HexagonFrameLowering.h"
12 #include "HexagonBlockRanges.h"
13 #include "HexagonInstrInfo.h"
15 #include "HexagonRegisterInfo.h"
16 #include "HexagonSubtarget.h"
17 #include "HexagonTargetMachine.h"
19 #include "llvm/ADT/BitVector.h"
20 #include "llvm/ADT/DenseMap.h"
21 #include "llvm/ADT/None.h"
22 #include "llvm/ADT/Optional.h"
24 #include "llvm/ADT/SetVector.h"
25 #include "llvm/ADT/SmallSet.h"
26 #include "llvm/ADT/SmallVector.h"
41 #include "llvm/IR/DebugLoc.h"
42 #include "llvm/IR/Function.h"
43 #include "llvm/MC/MCDwarf.h"
44 #include "llvm/MC/MCRegisterInfo.h"
45 #include "llvm/Pass.h"
46 #include "llvm/Support/CodeGen.h"
48 #include "llvm/Support/Debug.h"
54 #include <algorithm>
55 #include <cassert>
56 #include <cstdint>
57 #include <iterator>
58 #include <limits>
59 #include <map>
60 #include <new>
61 #include <utility>
62 #include <vector>
63 
64 #define DEBUG_TYPE "hexagon-pei"
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),
156 
157 static cl::opt<int> SpillFuncThreshold("spill-func-threshold",
158  cl::Hidden, cl::desc("Specify O2(not Os) spill func threshold"),
160 
161 static cl::opt<int> SpillFuncThresholdOs("spill-func-threshold-Os",
162  cl::Hidden, cl::desc("Specify Os spill func threshold"),
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",
171  cl::desc("Enable stack frame shrink wrapping"));
172 
173 static cl::opt<unsigned> ShrinkLimit("shrink-frame-limit",
175  cl::desc("Max count of stack frame shrink-wraps"));
176 
177 static cl::opt<bool> EnableSaveRestoreLong("enable-save-restore-long",
178  cl::Hidden, cl::desc("Enable long calls for save-restore stubs."),
179  cl::init(false), cl::ZeroOrMore);
180 
181 static cl::opt<bool> EliminateFramePointer("hexagon-fp-elim", cl::init(true),
182  cl::Hidden, cl::desc("Refrain from using FP whenever possible"));
183 
184 static cl::opt<bool> OptimizeSpillSlots("hexagon-opt-spill", cl::Hidden,
185  cl::init(true), cl::desc("Optimize spill slots"));
186 
187 #ifndef NDEBUG
188 static cl::opt<unsigned> SpillOptMax("spill-opt-max", cl::Hidden,
190 static unsigned SpillOptCount = 0;
191 #endif
192 
193 namespace llvm {
194 
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) {
209  }
210 
211  bool runOnMachineFunction(MachineFunction &MF) override;
212 
213  MachineFunctionProperties getRequiredProperties() const override {
216  }
217  };
218 
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() ||
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 
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.
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) {
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.
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) ||
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 
405  MDT.runOnMachineFunction(MF);
407  MPT.runOnMachineFunction(MF);
408 
409  typedef DenseMap<unsigned,unsigned> UnsignedMap;
410  UnsignedMap RPO;
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.
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.
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;
506  findShrunkPrologEpilog(MF, PrologB, EpilogB);
507 
508  bool PrologueStubs = false;
509  insertCSRSpillsInBlock(*PrologB, CSI, HRI, PrologueStubs);
510  insertPrologueInBlock(*PrologB, PrologueStubs);
511  updateEntryPaths(MF, *PrologB);
512 
513  if (EpilogB) {
514  insertCSRRestoresInBlock(*EpilogB, CSI, HRI);
515  insertEpilogueInBlock(*EpilogB);
516  } else {
517  for (auto &B : MF)
518  if (B.isReturnBlock())
519  insertCSRRestoresInBlock(B, CSI, HRI);
520 
521  for (auto &B : MF)
522  if (B.isReturnBlock())
523  insertEpilogueInBlock(B);
524 
525  for (auto &B : MF) {
526  if (B.empty())
527  continue;
528  MachineInstr *RetI = getReturn(B);
529  if (!RetI || isRestoreCall(RetI->getOpcode()))
530  continue;
531  for (auto &R : CSI)
532  RetI->addOperand(MachineOperand::CreateReg(R.getReg(), false, true));
533  }
534  }
535 
536  if (EpilogB) {
537  // If there is an epilog block, it may not have a return instruction.
538  // In such case, we need to add the callee-saved registers as live-ins
539  // in all blocks on all paths from the epilog to any return block.
540  unsigned MaxBN = MF.getNumBlockIDs();
541  BitVector DoneT(MaxBN+1), DoneF(MaxBN+1), Path(MaxBN+1);
542  updateExitPaths(*EpilogB, *EpilogB, DoneT, DoneF, Path);
543  }
544 }
545 
546 void HexagonFrameLowering::insertPrologueInBlock(MachineBasicBlock &MBB,
547  bool PrologueStubs) const {
548  MachineFunction &MF = *MBB.getParent();
549  MachineFrameInfo &MFI = MF.getFrameInfo();
550  auto &HST = MF.getSubtarget<HexagonSubtarget>();
551  auto &HII = *HST.getInstrInfo();
552  auto &HRI = *HST.getRegisterInfo();
553 
554  unsigned MaxAlign = std::max(MFI.getMaxAlignment(), getStackAlignment());
555 
556  // Calculate the total stack frame size.
557  // Get the number of bytes to allocate from the FrameInfo.
558  unsigned FrameSize = MFI.getStackSize();
559  // Round up the max call frame size to the max alignment on the stack.
560  unsigned MaxCFA = alignTo(MFI.getMaxCallFrameSize(), MaxAlign);
561  MFI.setMaxCallFrameSize(MaxCFA);
562 
563  FrameSize = MaxCFA + alignTo(FrameSize, MaxAlign);
564  MFI.setStackSize(FrameSize);
565 
566  bool AlignStack = (MaxAlign > getStackAlignment());
567 
568  // Get the number of bytes to allocate from the FrameInfo.
569  unsigned NumBytes = MFI.getStackSize();
570  unsigned SP = HRI.getStackRegister();
571  unsigned MaxCF = MFI.getMaxCallFrameSize();
572  MachineBasicBlock::iterator InsertPt = MBB.begin();
573 
575  for (auto &MBB : MF)
576  for (auto &MI : MBB)
577  if (MI.getOpcode() == Hexagon::PS_alloca)
578  AdjustRegs.push_back(&MI);
579 
580  for (auto MI : AdjustRegs) {
581  assert((MI->getOpcode() == Hexagon::PS_alloca) && "Expected alloca");
582  expandAlloca(MI, HII, SP, MaxCF);
583  MI->eraseFromParent();
584  }
585 
586  DebugLoc dl = MBB.findDebugLoc(InsertPt);
587 
588  if (hasFP(MF)) {
589  insertAllocframe(MBB, InsertPt, NumBytes);
590  if (AlignStack) {
591  BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::A2_andir), SP)
592  .addReg(SP)
593  .addImm(-int64_t(MaxAlign));
594  }
595  // If the stack-checking is enabled, and we spilled the callee-saved
596  // registers inline (i.e. did not use a spill function), then call
597  // the stack checker directly.
598  if (EnableStackOVFSanitizer && !PrologueStubs)
599  BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::PS_call_stk))
600  .addExternalSymbol("__runtime_stack_check");
601  } else if (NumBytes > 0) {
602  assert(alignTo(NumBytes, 8) == NumBytes);
603  BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::A2_addi), SP)
604  .addReg(SP)
605  .addImm(-int(NumBytes));
606  }
607 }
608 
609 void HexagonFrameLowering::insertEpilogueInBlock(MachineBasicBlock &MBB) const {
610  MachineFunction &MF = *MBB.getParent();
611  auto &HST = MF.getSubtarget<HexagonSubtarget>();
612  auto &HII = *HST.getInstrInfo();
613  auto &HRI = *HST.getRegisterInfo();
614  unsigned SP = HRI.getStackRegister();
615 
617  DebugLoc dl = MBB.findDebugLoc(InsertPt);
618 
619  if (!hasFP(MF)) {
620  MachineFrameInfo &MFI = MF.getFrameInfo();
621  if (unsigned NumBytes = MFI.getStackSize()) {
622  BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::A2_addi), SP)
623  .addReg(SP)
624  .addImm(NumBytes);
625  }
626  return;
627  }
628 
629  MachineInstr *RetI = getReturn(MBB);
630  unsigned RetOpc = RetI ? RetI->getOpcode() : 0;
631 
632  // Handle EH_RETURN.
633  if (RetOpc == Hexagon::EH_RETURN_JMPR) {
634  BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::L2_deallocframe));
635  BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::A2_add), SP)
636  .addReg(SP)
637  .addReg(Hexagon::R28);
638  return;
639  }
640 
641  // Check for RESTORE_DEALLOC_RET* tail call. Don't emit an extra dealloc-
642  // frame instruction if we encounter it.
643  if (RetOpc == Hexagon::RESTORE_DEALLOC_RET_JMP_V4 ||
644  RetOpc == Hexagon::RESTORE_DEALLOC_RET_JMP_V4_PIC ||
645  RetOpc == Hexagon::RESTORE_DEALLOC_RET_JMP_V4_EXT ||
646  RetOpc == Hexagon::RESTORE_DEALLOC_RET_JMP_V4_EXT_PIC) {
647  MachineBasicBlock::iterator It = RetI;
648  ++It;
649  // Delete all instructions after the RESTORE (except labels).
650  while (It != MBB.end()) {
651  if (!It->isLabel())
652  It = MBB.erase(It);
653  else
654  ++It;
655  }
656  return;
657  }
658 
659  // It is possible that the restoring code is a call to a library function.
660  // All of the restore* functions include "deallocframe", so we need to make
661  // sure that we don't add an extra one.
662  bool NeedsDeallocframe = true;
663  if (!MBB.empty() && InsertPt != MBB.begin()) {
664  MachineBasicBlock::iterator PrevIt = std::prev(InsertPt);
665  unsigned COpc = PrevIt->getOpcode();
666  if (COpc == Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4 ||
667  COpc == Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_PIC ||
668  COpc == Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_EXT ||
669  COpc == Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_EXT_PIC ||
670  COpc == Hexagon::PS_call_nr || COpc == Hexagon::PS_callr_nr)
671  NeedsDeallocframe = false;
672  }
673 
674  if (!NeedsDeallocframe)
675  return;
676  // If the returning instruction is PS_jmpret, replace it with dealloc_return,
677  // otherwise just add deallocframe. The function could be returning via a
678  // tail call.
679  if (RetOpc != Hexagon::PS_jmpret || DisableDeallocRet) {
680  BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::L2_deallocframe));
681  return;
682  }
683  unsigned NewOpc = Hexagon::L4_return;
684  MachineInstr *NewI = BuildMI(MBB, RetI, dl, HII.get(NewOpc));
685  // Transfer the function live-out registers.
686  NewI->copyImplicitOps(MF, *RetI);
687  MBB.erase(RetI);
688 }
689 
690 void HexagonFrameLowering::insertAllocframe(MachineBasicBlock &MBB,
691  MachineBasicBlock::iterator InsertPt, unsigned NumBytes) const {
692  MachineFunction &MF = *MBB.getParent();
693  auto &HST = MF.getSubtarget<HexagonSubtarget>();
694  auto &HII = *HST.getInstrInfo();
695  auto &HRI = *HST.getRegisterInfo();
696 
697  // Check for overflow.
698  // Hexagon_TODO: Ugh! hardcoding. Is there an API that can be used?
699  const unsigned int ALLOCFRAME_MAX = 16384;
700 
701  // Create a dummy memory operand to avoid allocframe from being treated as
702  // a volatile memory reference.
705 
706  DebugLoc dl = MBB.findDebugLoc(InsertPt);
707 
708  if (NumBytes >= ALLOCFRAME_MAX) {
709  // Emit allocframe(#0).
710  BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::S2_allocframe))
711  .addImm(0)
712  .addMemOperand(MMO);
713 
714  // Subtract the size from the stack pointer.
715  unsigned SP = HRI.getStackRegister();
716  BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::A2_addi), SP)
717  .addReg(SP)
718  .addImm(-int(NumBytes));
719  } else {
720  BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::S2_allocframe))
721  .addImm(NumBytes)
722  .addMemOperand(MMO);
723  }
724 }
725 
726 void HexagonFrameLowering::updateEntryPaths(MachineFunction &MF,
727  MachineBasicBlock &SaveB) const {
728  SetVector<unsigned> Worklist;
729 
730  MachineBasicBlock &EntryB = MF.front();
731  Worklist.insert(EntryB.getNumber());
732 
733  unsigned SaveN = SaveB.getNumber();
734  auto &CSI = MF.getFrameInfo().getCalleeSavedInfo();
735 
736  for (unsigned i = 0; i < Worklist.size(); ++i) {
737  unsigned BN = Worklist[i];
738  MachineBasicBlock &MBB = *MF.getBlockNumbered(BN);
739  for (auto &R : CSI)
740  if (!MBB.isLiveIn(R.getReg()))
741  MBB.addLiveIn(R.getReg());
742  if (BN != SaveN)
743  for (auto &SB : MBB.successors())
744  Worklist.insert(SB->getNumber());
745  }
746 }
747 
748 bool HexagonFrameLowering::updateExitPaths(MachineBasicBlock &MBB,
749  MachineBasicBlock &RestoreB, BitVector &DoneT, BitVector &DoneF,
750  BitVector &Path) const {
751  assert(MBB.getNumber() >= 0);
752  unsigned BN = MBB.getNumber();
753  if (Path[BN] || DoneF[BN])
754  return false;
755  if (DoneT[BN])
756  return true;
757 
758  auto &CSI = MBB.getParent()->getFrameInfo().getCalleeSavedInfo();
759 
760  Path[BN] = true;
761  bool ReachedExit = false;
762  for (auto &SB : MBB.successors())
763  ReachedExit |= updateExitPaths(*SB, RestoreB, DoneT, DoneF, Path);
764 
765  if (!MBB.empty() && MBB.back().isReturn()) {
766  // Add implicit uses of all callee-saved registers to the reached
767  // return instructions. This is to prevent the anti-dependency breaker
768  // from renaming these registers.
769  MachineInstr &RetI = MBB.back();
770  if (!isRestoreCall(RetI.getOpcode()))
771  for (auto &R : CSI)
772  RetI.addOperand(MachineOperand::CreateReg(R.getReg(), false, true));
773  ReachedExit = true;
774  }
775 
776  // We don't want to add unnecessary live-ins to the restore block: since
777  // the callee-saved registers are being defined in it, the entry of the
778  // restore block cannot be on the path from the definitions to any exit.
779  if (ReachedExit && &MBB != &RestoreB) {
780  for (auto &R : CSI)
781  if (!MBB.isLiveIn(R.getReg()))
782  MBB.addLiveIn(R.getReg());
783  DoneT[BN] = true;
784  }
785  if (!ReachedExit)
786  DoneF[BN] = true;
787 
788  Path[BN] = false;
789  return ReachedExit;
790 }
791 
794  // The CFI instructions need to be inserted right after allocframe.
795  // An exception to this is a situation where allocframe is bundled
796  // with a call: then the CFI instructions need to be inserted before
797  // the packet with the allocframe+call (in case the call throws an
798  // exception).
799  auto End = B.instr_end();
800 
801  for (MachineInstr &I : B) {
802  MachineBasicBlock::iterator It = I.getIterator();
803  if (!I.isBundle()) {
804  if (I.getOpcode() == Hexagon::S2_allocframe)
805  return std::next(It);
806  continue;
807  }
808  // I is a bundle.
809  bool HasCall = false, HasAllocFrame = false;
810  auto T = It.getInstrIterator();
811  while (++T != End && T->isBundled()) {
812  if (T->getOpcode() == Hexagon::S2_allocframe)
813  HasAllocFrame = true;
814  else if (T->isCall())
815  HasCall = true;
816  }
817  if (HasAllocFrame)
818  return HasCall ? It : std::next(It);
819  }
820  return None;
821 }
822 
824  for (auto &B : MF) {
825  auto At = findCFILocation(B);
826  if (At.hasValue())
827  insertCFIInstructionsAt(B, At.getValue());
828  }
829 }
830 
831 void HexagonFrameLowering::insertCFIInstructionsAt(MachineBasicBlock &MBB,
832  MachineBasicBlock::iterator At) const {
833  MachineFunction &MF = *MBB.getParent();
834  MachineFrameInfo &MFI = MF.getFrameInfo();
835  MachineModuleInfo &MMI = MF.getMMI();
836  auto &HST = MF.getSubtarget<HexagonSubtarget>();
837  auto &HII = *HST.getInstrInfo();
838  auto &HRI = *HST.getRegisterInfo();
839 
840  // If CFI instructions have debug information attached, something goes
841  // wrong with the final assembly generation: the prolog_end is placed
842  // in a wrong location.
843  DebugLoc DL;
844  const MCInstrDesc &CFID = HII.get(TargetOpcode::CFI_INSTRUCTION);
845 
846  MCSymbol *FrameLabel = MMI.getContext().createTempSymbol();
847  bool HasFP = hasFP(MF);
848 
849  if (HasFP) {
850  unsigned DwFPReg = HRI.getDwarfRegNum(HRI.getFrameRegister(), true);
851  unsigned DwRAReg = HRI.getDwarfRegNum(HRI.getRARegister(), true);
852 
853  // Define CFA via an offset from the value of FP.
854  //
855  // -8 -4 0 (SP)
856  // --+----+----+---------------------
857  // | FP | LR | increasing addresses -->
858  // --+----+----+---------------------
859  // | +-- Old SP (before allocframe)
860  // +-- New FP (after allocframe)
861  //
862  // MCCFIInstruction::createDefCfa subtracts the offset from the register.
863  // MCCFIInstruction::createOffset takes the offset without sign change.
864  auto DefCfa = MCCFIInstruction::createDefCfa(FrameLabel, DwFPReg, -8);
865  BuildMI(MBB, At, DL, CFID)
866  .addCFIIndex(MF.addFrameInst(DefCfa));
867  // R31 (return addr) = CFA - 4
868  auto OffR31 = MCCFIInstruction::createOffset(FrameLabel, DwRAReg, -4);
869  BuildMI(MBB, At, DL, CFID)
870  .addCFIIndex(MF.addFrameInst(OffR31));
871  // R30 (frame ptr) = CFA - 8
872  auto OffR30 = MCCFIInstruction::createOffset(FrameLabel, DwFPReg, -8);
873  BuildMI(MBB, At, DL, CFID)
874  .addCFIIndex(MF.addFrameInst(OffR30));
875  }
876 
877  static unsigned int RegsToMove[] = {
878  Hexagon::R1, Hexagon::R0, Hexagon::R3, Hexagon::R2,
879  Hexagon::R17, Hexagon::R16, Hexagon::R19, Hexagon::R18,
880  Hexagon::R21, Hexagon::R20, Hexagon::R23, Hexagon::R22,
881  Hexagon::R25, Hexagon::R24, Hexagon::R27, Hexagon::R26,
882  Hexagon::D0, Hexagon::D1, Hexagon::D8, Hexagon::D9,
883  Hexagon::D10, Hexagon::D11, Hexagon::D12, Hexagon::D13,
884  Hexagon::NoRegister
885  };
886 
887  const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
888 
889  for (unsigned i = 0; RegsToMove[i] != Hexagon::NoRegister; ++i) {
890  unsigned Reg = RegsToMove[i];
891  auto IfR = [Reg] (const CalleeSavedInfo &C) -> bool {
892  return C.getReg() == Reg;
893  };
894  auto F = find_if(CSI, IfR);
895  if (F == CSI.end())
896  continue;
897 
898  int64_t Offset;
899  if (HasFP) {
900  // If the function has a frame pointer (i.e. has an allocframe),
901  // then the CFA has been defined in terms of FP. Any offsets in
902  // the following CFI instructions have to be defined relative
903  // to FP, which points to the bottom of the stack frame.
904  // The function getFrameIndexReference can still choose to use SP
905  // for the offset calculation, so we cannot simply call it here.
906  // Instead, get the offset (relative to the FP) directly.
907  Offset = MFI.getObjectOffset(F->getFrameIdx());
908  } else {
909  unsigned FrameReg;
910  Offset = getFrameIndexReference(MF, F->getFrameIdx(), FrameReg);
911  }
912  // Subtract 8 to make room for R30 and R31, which are added above.
913  Offset -= 8;
914 
915  if (Reg < Hexagon::D0 || Reg > Hexagon::D15) {
916  unsigned DwarfReg = HRI.getDwarfRegNum(Reg, true);
917  auto OffReg = MCCFIInstruction::createOffset(FrameLabel, DwarfReg,
918  Offset);
919  BuildMI(MBB, At, DL, CFID)
920  .addCFIIndex(MF.addFrameInst(OffReg));
921  } else {
922  // Split the double regs into subregs, and generate appropriate
923  // cfi_offsets.
924  // The only reason, we are split double regs is, llvm-mc does not
925  // understand paired registers for cfi_offset.
926  // Eg .cfi_offset r1:0, -64
927 
928  unsigned HiReg = HRI.getSubReg(Reg, Hexagon::isub_hi);
929  unsigned LoReg = HRI.getSubReg(Reg, Hexagon::isub_lo);
930  unsigned HiDwarfReg = HRI.getDwarfRegNum(HiReg, true);
931  unsigned LoDwarfReg = HRI.getDwarfRegNum(LoReg, true);
932  auto OffHi = MCCFIInstruction::createOffset(FrameLabel, HiDwarfReg,
933  Offset+4);
934  BuildMI(MBB, At, DL, CFID)
935  .addCFIIndex(MF.addFrameInst(OffHi));
936  auto OffLo = MCCFIInstruction::createOffset(FrameLabel, LoDwarfReg,
937  Offset);
938  BuildMI(MBB, At, DL, CFID)
939  .addCFIIndex(MF.addFrameInst(OffLo));
940  }
941  }
942 }
943 
945  if (MF.getFunction()->hasFnAttribute(Attribute::Naked))
946  return false;
947 
948  auto &MFI = MF.getFrameInfo();
949  auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
950  bool HasExtraAlign = HRI.needsStackRealignment(MF);
951  bool HasAlloca = MFI.hasVarSizedObjects();
952 
953  // Insert ALLOCFRAME if we need to or at -O0 for the debugger. Think
954  // that this shouldn't be required, but doing so now because gcc does and
955  // gdb can't break at the start of the function without it. Will remove if
956  // this turns out to be a gdb bug.
957  //
958  if (MF.getTarget().getOptLevel() == CodeGenOpt::None)
959  return true;
960 
961  // By default we want to use SP (since it's always there). FP requires
962  // some setup (i.e. ALLOCFRAME).
963  // Both, alloca and stack alignment modify the stack pointer by an
964  // undetermined value, so we need to save it at the entry to the function
965  // (i.e. use allocframe).
966  if (HasAlloca || HasExtraAlign)
967  return true;
968 
969  if (MFI.getStackSize() > 0) {
970  // If FP-elimination is disabled, we have to use FP at this point.
971  const TargetMachine &TM = MF.getTarget();
973  return true;
975  return true;
976  }
977 
978  const auto &HMFI = *MF.getInfo<HexagonMachineFunctionInfo>();
979  if (MFI.hasCalls() || HMFI.hasClobberLR())
980  return true;
981 
982  return false;
983 }
984 
985 enum SpillKind {
989 };
990 
991 static const char *getSpillFunctionFor(unsigned MaxReg, SpillKind SpillType,
992  bool Stkchk = false) {
993  const char * V4SpillToMemoryFunctions[] = {
994  "__save_r16_through_r17",
995  "__save_r16_through_r19",
996  "__save_r16_through_r21",
997  "__save_r16_through_r23",
998  "__save_r16_through_r25",
999  "__save_r16_through_r27" };
1000 
1001  const char * V4SpillToMemoryStkchkFunctions[] = {
1002  "__save_r16_through_r17_stkchk",
1003  "__save_r16_through_r19_stkchk",
1004  "__save_r16_through_r21_stkchk",
1005  "__save_r16_through_r23_stkchk",
1006  "__save_r16_through_r25_stkchk",
1007  "__save_r16_through_r27_stkchk" };
1008 
1009  const char * V4SpillFromMemoryFunctions[] = {
1010  "__restore_r16_through_r17_and_deallocframe",
1011  "__restore_r16_through_r19_and_deallocframe",
1012  "__restore_r16_through_r21_and_deallocframe",
1013  "__restore_r16_through_r23_and_deallocframe",
1014  "__restore_r16_through_r25_and_deallocframe",
1015  "__restore_r16_through_r27_and_deallocframe" };
1016 
1017  const char * V4SpillFromMemoryTailcallFunctions[] = {
1018  "__restore_r16_through_r17_and_deallocframe_before_tailcall",
1019  "__restore_r16_through_r19_and_deallocframe_before_tailcall",
1020  "__restore_r16_through_r21_and_deallocframe_before_tailcall",
1021  "__restore_r16_through_r23_and_deallocframe_before_tailcall",
1022  "__restore_r16_through_r25_and_deallocframe_before_tailcall",
1023  "__restore_r16_through_r27_and_deallocframe_before_tailcall"
1024  };
1025 
1026  const char **SpillFunc = nullptr;
1027 
1028  switch(SpillType) {
1029  case SK_ToMem:
1030  SpillFunc = Stkchk ? V4SpillToMemoryStkchkFunctions
1031  : V4SpillToMemoryFunctions;
1032  break;
1033  case SK_FromMem:
1034  SpillFunc = V4SpillFromMemoryFunctions;
1035  break;
1036  case SK_FromMemTailcall:
1037  SpillFunc = V4SpillFromMemoryTailcallFunctions;
1038  break;
1039  }
1040  assert(SpillFunc && "Unknown spill kind");
1041 
1042  // Spill all callee-saved registers up to the highest register used.
1043  switch (MaxReg) {
1044  case Hexagon::R17:
1045  return SpillFunc[0];
1046  case Hexagon::R19:
1047  return SpillFunc[1];
1048  case Hexagon::R21:
1049  return SpillFunc[2];
1050  case Hexagon::R23:
1051  return SpillFunc[3];
1052  case Hexagon::R25:
1053  return SpillFunc[4];
1054  case Hexagon::R27:
1055  return SpillFunc[5];
1056  default:
1057  llvm_unreachable("Unhandled maximum callee save register");
1058  }
1059  return nullptr;
1060 }
1061 
1063  int FI, unsigned &FrameReg) const {
1064  auto &MFI = MF.getFrameInfo();
1065  auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
1066 
1067  int Offset = MFI.getObjectOffset(FI);
1068  bool HasAlloca = MFI.hasVarSizedObjects();
1069  bool HasExtraAlign = HRI.needsStackRealignment(MF);
1070  bool NoOpt = MF.getTarget().getOptLevel() == CodeGenOpt::None;
1071 
1072  auto &HMFI = *MF.getInfo<HexagonMachineFunctionInfo>();
1073  unsigned FrameSize = MFI.getStackSize();
1074  unsigned SP = HRI.getStackRegister();
1075  unsigned FP = HRI.getFrameRegister();
1076  unsigned AP = HMFI.getStackAlignBasePhysReg();
1077  // It may happen that AP will be absent even HasAlloca && HasExtraAlign
1078  // is true. HasExtraAlign may be set because of vector spills, without
1079  // aligned locals or aligned outgoing function arguments. Since vector
1080  // spills will ultimately be "unaligned", it is safe to use FP as the
1081  // base register.
1082  // In fact, in such a scenario the stack is actually not required to be
1083  // aligned, although it may end up being aligned anyway, since this
1084  // particular case is not easily detectable. The alignment will be
1085  // unnecessary, but not incorrect.
1086  // Unfortunately there is no quick way to verify that the above is
1087  // indeed the case (and that it's not a result of an error), so just
1088  // assume that missing AP will be replaced by FP.
1089  // (A better fix would be to rematerialize AP from FP and always align
1090  // vector spills.)
1091  if (AP == 0)
1092  AP = FP;
1093 
1094  bool UseFP = false, UseAP = false; // Default: use SP (except at -O0).
1095  // Use FP at -O0, except when there are objects with extra alignment.
1096  // That additional alignment requirement may cause a pad to be inserted,
1097  // which will make it impossible to use FP to access objects located
1098  // past the pad.
1099  if (NoOpt && !HasExtraAlign)
1100  UseFP = true;
1101  if (MFI.isFixedObjectIndex(FI) || MFI.isObjectPreAllocated(FI)) {
1102  // Fixed and preallocated objects will be located before any padding
1103  // so FP must be used to access them.
1104  UseFP |= (HasAlloca || HasExtraAlign);
1105  } else {
1106  if (HasAlloca) {
1107  if (HasExtraAlign)
1108  UseAP = true;
1109  else
1110  UseFP = true;
1111  }
1112  }
1113 
1114  // If FP was picked, then there had better be FP.
1115  bool HasFP = hasFP(MF);
1116  assert((HasFP || !UseFP) && "This function must have frame pointer");
1117 
1118  // Having FP implies allocframe. Allocframe will store extra 8 bytes:
1119  // FP/LR. If the base register is used to access an object across these
1120  // 8 bytes, then the offset will need to be adjusted by 8.
1121  //
1122  // After allocframe:
1123  // HexagonISelLowering adds 8 to ---+
1124  // the offsets of all stack-based |
1125  // arguments (*) |
1126  // |
1127  // getObjectOffset < 0 0 8 getObjectOffset >= 8
1128  // ------------------------+-----+------------------------> increasing
1129  // <local objects> |FP/LR| <input arguments> addresses
1130  // -----------------+------+-----+------------------------>
1131  // | |
1132  // SP/AP point --+ +-- FP points here (**)
1133  // somewhere on
1134  // this side of FP/LR
1135  //
1136  // (*) See LowerFormalArguments. The FP/LR is assumed to be present.
1137  // (**) *FP == old-FP. FP+0..7 are the bytes of FP/LR.
1138 
1139  // The lowering assumes that FP/LR is present, and so the offsets of
1140  // the formal arguments start at 8. If FP/LR is not there we need to
1141  // reduce the offset by 8.
1142  if (Offset > 0 && !HasFP)
1143  Offset -= 8;
1144 
1145  if (UseFP)
1146  FrameReg = FP;
1147  else if (UseAP)
1148  FrameReg = AP;
1149  else
1150  FrameReg = SP;
1151 
1152  // Calculate the actual offset in the instruction. If there is no FP
1153  // (in other words, no allocframe), then SP will not be adjusted (i.e.
1154  // there will be no SP -= FrameSize), so the frame size should not be
1155  // added to the calculated offset.
1156  int RealOffset = Offset;
1157  if (!UseFP && !UseAP)
1158  RealOffset = FrameSize+Offset;
1159  return RealOffset;
1160 }
1161 
1162 bool HexagonFrameLowering::insertCSRSpillsInBlock(MachineBasicBlock &MBB,
1163  const CSIVect &CSI, const HexagonRegisterInfo &HRI,
1164  bool &PrologueStubs) const {
1165  if (CSI.empty())
1166  return true;
1167 
1169  PrologueStubs = false;
1170  MachineFunction &MF = *MBB.getParent();
1171  auto &HST = MF.getSubtarget<HexagonSubtarget>();
1172  auto &HII = *HST.getInstrInfo();
1173 
1174  if (useSpillFunction(MF, CSI)) {
1175  PrologueStubs = true;
1176  unsigned MaxReg = getMaxCalleeSavedReg(CSI, HRI);
1177  bool StkOvrFlowEnabled = EnableStackOVFSanitizer;
1178  const char *SpillFun = getSpillFunctionFor(MaxReg, SK_ToMem,
1179  StkOvrFlowEnabled);
1180  auto &HTM = static_cast<const HexagonTargetMachine&>(MF.getTarget());
1181  bool IsPIC = HTM.isPositionIndependent();
1182  bool LongCalls = HST.useLongCalls() || EnableSaveRestoreLong;
1183 
1184  // Call spill function.
1185  DebugLoc DL = MI != MBB.end() ? MI->getDebugLoc() : DebugLoc();
1186  unsigned SpillOpc;
1187  if (StkOvrFlowEnabled) {
1188  if (LongCalls)
1189  SpillOpc = IsPIC ? Hexagon::SAVE_REGISTERS_CALL_V4STK_EXT_PIC
1190  : Hexagon::SAVE_REGISTERS_CALL_V4STK_EXT;
1191  else
1192  SpillOpc = IsPIC ? Hexagon::SAVE_REGISTERS_CALL_V4STK_PIC
1193  : Hexagon::SAVE_REGISTERS_CALL_V4STK;
1194  } else {
1195  if (LongCalls)
1196  SpillOpc = IsPIC ? Hexagon::SAVE_REGISTERS_CALL_V4_EXT_PIC
1197  : Hexagon::SAVE_REGISTERS_CALL_V4_EXT;
1198  else
1199  SpillOpc = IsPIC ? Hexagon::SAVE_REGISTERS_CALL_V4_PIC
1200  : Hexagon::SAVE_REGISTERS_CALL_V4;
1201  }
1202 
1203  MachineInstr *SaveRegsCall =
1204  BuildMI(MBB, MI, DL, HII.get(SpillOpc))
1205  .addExternalSymbol(SpillFun);
1206 
1207  // Add callee-saved registers as use.
1208  addCalleeSaveRegistersAsImpOperand(SaveRegsCall, CSI, false, true);
1209  // Add live in registers.
1210  for (unsigned I = 0; I < CSI.size(); ++I)
1211  MBB.addLiveIn(CSI[I].getReg());
1212  return true;
1213  }
1214 
1215  for (unsigned i = 0, n = CSI.size(); i < n; ++i) {
1216  unsigned Reg = CSI[i].getReg();
1217  // Add live in registers. We treat eh_return callee saved register r0 - r3
1218  // specially. They are not really callee saved registers as they are not
1219  // supposed to be killed.
1220  bool IsKill = !HRI.isEHReturnCalleeSaveReg(Reg);
1221  int FI = CSI[i].getFrameIdx();
1222  const TargetRegisterClass *RC = HRI.getMinimalPhysRegClass(Reg);
1223  HII.storeRegToStackSlot(MBB, MI, Reg, IsKill, FI, RC, &HRI);
1224  if (IsKill)
1225  MBB.addLiveIn(Reg);
1226  }
1227  return true;
1228 }
1229 
1230 bool HexagonFrameLowering::insertCSRRestoresInBlock(MachineBasicBlock &MBB,
1231  const CSIVect &CSI, const HexagonRegisterInfo &HRI) const {
1232  if (CSI.empty())
1233  return false;
1234 
1236  MachineFunction &MF = *MBB.getParent();
1237  auto &HST = MF.getSubtarget<HexagonSubtarget>();
1238  auto &HII = *HST.getInstrInfo();
1239 
1240  if (useRestoreFunction(MF, CSI)) {
1241  bool HasTC = hasTailCall(MBB) || !hasReturn(MBB);
1242  unsigned MaxR = getMaxCalleeSavedReg(CSI, HRI);
1244  const char *RestoreFn = getSpillFunctionFor(MaxR, Kind);
1245  auto &HTM = static_cast<const HexagonTargetMachine&>(MF.getTarget());
1246  bool IsPIC = HTM.isPositionIndependent();
1247  bool LongCalls = HST.useLongCalls() || EnableSaveRestoreLong;
1248 
1249  // Call spill function.
1250  DebugLoc DL = MI != MBB.end() ? MI->getDebugLoc()
1251  : MBB.getLastNonDebugInstr()->getDebugLoc();
1252  MachineInstr *DeallocCall = nullptr;
1253 
1254  if (HasTC) {
1255  unsigned RetOpc;
1256  if (LongCalls)
1257  RetOpc = IsPIC ? Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_EXT_PIC
1258  : Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_EXT;
1259  else
1260  RetOpc = IsPIC ? Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_PIC
1261  : Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4;
1262  DeallocCall = BuildMI(MBB, MI, DL, HII.get(RetOpc))
1263  .addExternalSymbol(RestoreFn);
1264  } else {
1265  // The block has a return.
1267  assert(It->isReturn() && std::next(It) == MBB.end());
1268  unsigned RetOpc;
1269  if (LongCalls)
1270  RetOpc = IsPIC ? Hexagon::RESTORE_DEALLOC_RET_JMP_V4_EXT_PIC
1271  : Hexagon::RESTORE_DEALLOC_RET_JMP_V4_EXT;
1272  else
1273  RetOpc = IsPIC ? Hexagon::RESTORE_DEALLOC_RET_JMP_V4_PIC
1274  : Hexagon::RESTORE_DEALLOC_RET_JMP_V4;
1275  DeallocCall = BuildMI(MBB, It, DL, HII.get(RetOpc))
1276  .addExternalSymbol(RestoreFn);
1277  // Transfer the function live-out registers.
1278  DeallocCall->copyImplicitOps(MF, *It);
1279  }
1280  addCalleeSaveRegistersAsImpOperand(DeallocCall, CSI, true, false);
1281  return true;
1282  }
1283 
1284  for (unsigned i = 0; i < CSI.size(); ++i) {
1285  unsigned Reg = CSI[i].getReg();
1286  const TargetRegisterClass *RC = HRI.getMinimalPhysRegClass(Reg);
1287  int FI = CSI[i].getFrameIdx();
1288  HII.loadRegFromStackSlot(MBB, MI, Reg, FI, RC, &HRI);
1289  }
1290 
1291  return true;
1292 }
1293 
1297  MachineInstr &MI = *I;
1298  unsigned Opc = MI.getOpcode();
1299  (void)Opc; // Silence compiler warning.
1300  assert((Opc == Hexagon::ADJCALLSTACKDOWN || Opc == Hexagon::ADJCALLSTACKUP) &&
1301  "Cannot handle this call frame pseudo instruction");
1302  return MBB.erase(I);
1303 }
1304 
1306  MachineFunction &MF, RegScavenger *RS) const {
1307  // If this function has uses aligned stack and also has variable sized stack
1308  // objects, then we need to map all spill slots to fixed positions, so that
1309  // they can be accessed through FP. Otherwise they would have to be accessed
1310  // via AP, which may not be available at the particular place in the program.
1311  MachineFrameInfo &MFI = MF.getFrameInfo();
1312  bool HasAlloca = MFI.hasVarSizedObjects();
1313  bool NeedsAlign = (MFI.getMaxAlignment() > getStackAlignment());
1314 
1315  if (!HasAlloca || !NeedsAlign)
1316  return;
1317 
1318  unsigned LFS = MFI.getLocalFrameSize();
1319  for (int i = 0, e = MFI.getObjectIndexEnd(); i != e; ++i) {
1320  if (!MFI.isSpillSlotObjectIndex(i) || MFI.isDeadObjectIndex(i))
1321  continue;
1322  unsigned S = MFI.getObjectSize(i);
1323  // Reduce the alignment to at most 8. This will require unaligned vector
1324  // stores if they happen here.
1325  unsigned A = std::max(MFI.getObjectAlignment(i), 8U);
1326  MFI.setObjectAlignment(i, 8);
1327  LFS = alignTo(LFS+S, A);
1328  MFI.mapLocalFrameObject(i, -LFS);
1329  }
1330 
1331  MFI.setLocalFrameSize(LFS);
1332  unsigned A = MFI.getLocalFrameMaxAlign();
1333  assert(A <= 8 && "Unexpected local frame alignment");
1334  if (A == 0)
1335  MFI.setLocalFrameMaxAlign(8);
1337 
1338  // Set the physical aligned-stack base address register.
1339  unsigned AP = 0;
1340  if (const MachineInstr *AI = getAlignaInstr(MF))
1341  AP = AI->getOperand(0).getReg();
1342  auto &HMFI = *MF.getInfo<HexagonMachineFunctionInfo>();
1343  HMFI.setStackAlignBasePhysReg(AP);
1344 }
1345 
1346 /// Returns true if there are no caller-saved registers available in class RC.
1348  const HexagonRegisterInfo &HRI, const TargetRegisterClass *RC) {
1350 
1351  auto IsUsed = [&HRI,&MRI] (unsigned Reg) -> bool {
1352  for (MCRegAliasIterator AI(Reg, &HRI, true); AI.isValid(); ++AI)
1353  if (MRI.isPhysRegUsed(*AI))
1354  return true;
1355  return false;
1356  };
1357 
1358  // Check for an unused caller-saved register. Callee-saved registers
1359  // have become pristine by now.
1360  for (const MCPhysReg *P = HRI.getCallerSavedRegs(&MF, RC); *P; ++P)
1361  if (!IsUsed(*P))
1362  return false;
1363 
1364  // All caller-saved registers are used.
1365  return true;
1366 }
1367 
1368 #ifndef NDEBUG
1370  dbgs() << '{';
1371  for (int x = Regs.find_first(); x >= 0; x = Regs.find_next(x)) {
1372  unsigned R = x;
1373  dbgs() << ' ' << PrintReg(R, &TRI);
1374  }
1375  dbgs() << " }";
1376 }
1377 #endif
1378 
1380  const TargetRegisterInfo *TRI, std::vector<CalleeSavedInfo> &CSI) const {
1381  DEBUG(dbgs() << __func__ << " on "
1382  << MF.getFunction()->getName() << '\n');
1383  MachineFrameInfo &MFI = MF.getFrameInfo();
1384  BitVector SRegs(Hexagon::NUM_TARGET_REGS);
1385 
1386  // Generate a set of unique, callee-saved registers (SRegs), where each
1387  // register in the set is maximal in terms of sub-/super-register relation,
1388  // i.e. for each R in SRegs, no proper super-register of R is also in SRegs.
1389 
1390  // (1) For each callee-saved register, add that register and all of its
1391  // sub-registers to SRegs.
1392  DEBUG(dbgs() << "Initial CS registers: {");
1393  for (unsigned i = 0, n = CSI.size(); i < n; ++i) {
1394  unsigned R = CSI[i].getReg();
1395  DEBUG(dbgs() << ' ' << PrintReg(R, TRI));
1396  for (MCSubRegIterator SR(R, TRI, true); SR.isValid(); ++SR)
1397  SRegs[*SR] = true;
1398  }
1399  DEBUG(dbgs() << " }\n");
1400  DEBUG(dbgs() << "SRegs.1: "; dump_registers(SRegs, *TRI); dbgs() << "\n");
1401 
1402  // (2) For each reserved register, remove that register and all of its
1403  // sub- and super-registers from SRegs.
1404  BitVector Reserved = TRI->getReservedRegs(MF);
1405  for (int x = Reserved.find_first(); x >= 0; x = Reserved.find_next(x)) {
1406  unsigned R = x;
1407  for (MCSuperRegIterator SR(R, TRI, true); SR.isValid(); ++SR)
1408  SRegs[*SR] = false;
1409  }
1410  DEBUG(dbgs() << "Res: "; dump_registers(Reserved, *TRI); dbgs() << "\n");
1411  DEBUG(dbgs() << "SRegs.2: "; dump_registers(SRegs, *TRI); dbgs() << "\n");
1412 
1413  // (3) Collect all registers that have at least one sub-register in SRegs,
1414  // and also have no sub-registers that are reserved. These will be the can-
1415  // didates for saving as a whole instead of their individual sub-registers.
1416  // (Saving R17:16 instead of R16 is fine, but only if R17 was not reserved.)
1417  BitVector TmpSup(Hexagon::NUM_TARGET_REGS);
1418  for (int x = SRegs.find_first(); x >= 0; x = SRegs.find_next(x)) {
1419  unsigned R = x;
1420  for (MCSuperRegIterator SR(R, TRI); SR.isValid(); ++SR)
1421  TmpSup[*SR] = true;
1422  }
1423  for (int x = TmpSup.find_first(); x >= 0; x = TmpSup.find_next(x)) {
1424  unsigned R = x;
1425  for (MCSubRegIterator SR(R, TRI, true); SR.isValid(); ++SR) {
1426  if (!Reserved[*SR])
1427  continue;
1428  TmpSup[R] = false;
1429  break;
1430  }
1431  }
1432  DEBUG(dbgs() << "TmpSup: "; dump_registers(TmpSup, *TRI); dbgs() << "\n");
1433 
1434  // (4) Include all super-registers found in (3) into SRegs.
1435  SRegs |= TmpSup;
1436  DEBUG(dbgs() << "SRegs.4: "; dump_registers(SRegs, *TRI); dbgs() << "\n");
1437 
1438  // (5) For each register R in SRegs, if any super-register of R is in SRegs,
1439  // remove R from SRegs.
1440  for (int x = SRegs.find_first(); x >= 0; x = SRegs.find_next(x)) {
1441  unsigned R = x;
1442  for (MCSuperRegIterator SR(R, TRI); SR.isValid(); ++SR) {
1443  if (!SRegs[*SR])
1444  continue;
1445  SRegs[R] = false;
1446  break;
1447  }
1448  }
1449  DEBUG(dbgs() << "SRegs.5: "; dump_registers(SRegs, *TRI); dbgs() << "\n");
1450 
1451  // Now, for each register that has a fixed stack slot, create the stack
1452  // object for it.
1453  CSI.clear();
1454 
1456  unsigned NumFixed;
1457  int MinOffset = 0; // CS offsets are negative.
1458  const SpillSlot *FixedSlots = getCalleeSavedSpillSlots(NumFixed);
1459  for (const SpillSlot *S = FixedSlots; S != FixedSlots+NumFixed; ++S) {
1460  if (!SRegs[S->Reg])
1461  continue;
1462  const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(S->Reg);
1463  int FI = MFI.CreateFixedSpillStackObject(TRI->getSpillSize(*RC), S->Offset);
1464  MinOffset = std::min(MinOffset, S->Offset);
1465  CSI.push_back(CalleeSavedInfo(S->Reg, FI));
1466  SRegs[S->Reg] = false;
1467  }
1468 
1469  // There can be some registers that don't have fixed slots. For example,
1470  // we need to store R0-R3 in functions with exception handling. For each
1471  // such register, create a non-fixed stack object.
1472  for (int x = SRegs.find_first(); x >= 0; x = SRegs.find_next(x)) {
1473  unsigned R = x;
1474  const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(R);
1475  unsigned Size = TRI->getSpillSize(*RC);
1476  int Off = MinOffset - Size;
1477  unsigned Align = std::min(TRI->getSpillAlignment(*RC), getStackAlignment());
1478  assert(isPowerOf2_32(Align));
1479  Off &= -Align;
1480  int FI = MFI.CreateFixedSpillStackObject(Size, Off);
1481  MinOffset = std::min(MinOffset, Off);
1482  CSI.push_back(CalleeSavedInfo(R, FI));
1483  SRegs[R] = false;
1484  }
1485 
1486  DEBUG({
1487  dbgs() << "CS information: {";
1488  for (unsigned i = 0, n = CSI.size(); i < n; ++i) {
1489  int FI = CSI[i].getFrameIdx();
1490  int Off = MFI.getObjectOffset(FI);
1491  dbgs() << ' ' << PrintReg(CSI[i].getReg(), TRI) << ":fi#" << FI << ":sp";
1492  if (Off >= 0)
1493  dbgs() << '+';
1494  dbgs() << Off;
1495  }
1496  dbgs() << " }\n";
1497  });
1498 
1499 #ifndef NDEBUG
1500  // Verify that all registers were handled.
1501  bool MissedReg = false;
1502  for (int x = SRegs.find_first(); x >= 0; x = SRegs.find_next(x)) {
1503  unsigned R = x;
1504  dbgs() << PrintReg(R, TRI) << ' ';
1505  MissedReg = true;
1506  }
1507  if (MissedReg)
1508  llvm_unreachable("...there are unhandled callee-saved registers!");
1509 #endif
1510 
1511  return true;
1512 }
1513 
1514 bool HexagonFrameLowering::expandCopy(MachineBasicBlock &B,
1516  const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1517  MachineInstr *MI = &*It;
1518  DebugLoc DL = MI->getDebugLoc();
1519  unsigned DstR = MI->getOperand(0).getReg();
1520  unsigned SrcR = MI->getOperand(1).getReg();
1521  if (!Hexagon::ModRegsRegClass.contains(DstR) ||
1522  !Hexagon::ModRegsRegClass.contains(SrcR))
1523  return false;
1524 
1525  unsigned TmpR = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
1526  BuildMI(B, It, DL, HII.get(TargetOpcode::COPY), TmpR).add(MI->getOperand(1));
1527  BuildMI(B, It, DL, HII.get(TargetOpcode::COPY), DstR)
1528  .addReg(TmpR, RegState::Kill);
1529 
1530  NewRegs.push_back(TmpR);
1531  B.erase(It);
1532  return true;
1533 }
1534 
1535 bool HexagonFrameLowering::expandStoreInt(MachineBasicBlock &B,
1537  const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1538  MachineInstr *MI = &*It;
1539  if (!MI->getOperand(0).isFI())
1540  return false;
1541 
1542  DebugLoc DL = MI->getDebugLoc();
1543  unsigned Opc = MI->getOpcode();
1544  unsigned SrcR = MI->getOperand(2).getReg();
1545  bool IsKill = MI->getOperand(2).isKill();
1546  int FI = MI->getOperand(0).getIndex();
1547 
1548  // TmpR = C2_tfrpr SrcR if SrcR is a predicate register
1549  // TmpR = A2_tfrcrr SrcR if SrcR is a modifier register
1550  unsigned TmpR = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
1551  unsigned TfrOpc = (Opc == Hexagon::STriw_pred) ? Hexagon::C2_tfrpr
1552  : Hexagon::A2_tfrcrr;
1553  BuildMI(B, It, DL, HII.get(TfrOpc), TmpR)
1554  .addReg(SrcR, getKillRegState(IsKill));
1555 
1556  // S2_storeri_io FI, 0, TmpR
1557  BuildMI(B, It, DL, HII.get(Hexagon::S2_storeri_io))
1558  .addFrameIndex(FI)
1559  .addImm(0)
1560  .addReg(TmpR, RegState::Kill)
1562 
1563  NewRegs.push_back(TmpR);
1564  B.erase(It);
1565  return true;
1566 }
1567 
1568 bool HexagonFrameLowering::expandLoadInt(MachineBasicBlock &B,
1570  const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1571  MachineInstr *MI = &*It;
1572  if (!MI->getOperand(1).isFI())
1573  return false;
1574 
1575  DebugLoc DL = MI->getDebugLoc();
1576  unsigned Opc = MI->getOpcode();
1577  unsigned DstR = MI->getOperand(0).getReg();
1578  int FI = MI->getOperand(1).getIndex();
1579 
1580  // TmpR = L2_loadri_io FI, 0
1581  unsigned TmpR = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
1582  BuildMI(B, It, DL, HII.get(Hexagon::L2_loadri_io), TmpR)
1583  .addFrameIndex(FI)
1584  .addImm(0)
1586 
1587  // DstR = C2_tfrrp TmpR if DstR is a predicate register
1588  // DstR = A2_tfrrcr TmpR if DstR is a modifier register
1589  unsigned TfrOpc = (Opc == Hexagon::LDriw_pred) ? Hexagon::C2_tfrrp
1590  : Hexagon::A2_tfrrcr;
1591  BuildMI(B, It, DL, HII.get(TfrOpc), DstR)
1592  .addReg(TmpR, RegState::Kill);
1593 
1594  NewRegs.push_back(TmpR);
1595  B.erase(It);
1596  return true;
1597 }
1598 
1599 bool HexagonFrameLowering::expandStoreVecPred(MachineBasicBlock &B,
1601  const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1602  auto &HST = B.getParent()->getSubtarget<HexagonSubtarget>();
1603  MachineInstr *MI = &*It;
1604  if (!MI->getOperand(0).isFI())
1605  return false;
1606 
1607  DebugLoc DL = MI->getDebugLoc();
1608  unsigned SrcR = MI->getOperand(2).getReg();
1609  bool IsKill = MI->getOperand(2).isKill();
1610  int FI = MI->getOperand(0).getIndex();
1611 
1612  bool Is128B = HST.useHVXDblOps();
1613  auto *RC = !Is128B ? &Hexagon::VectorRegsRegClass
1614  : &Hexagon::VectorRegs128BRegClass;
1615 
1616  // Insert transfer to general vector register.
1617  // TmpR0 = A2_tfrsi 0x01010101
1618  // TmpR1 = V6_vandqrt Qx, TmpR0
1619  // store FI, 0, TmpR1
1620  unsigned TmpR0 = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
1621  unsigned TmpR1 = MRI.createVirtualRegister(RC);
1622 
1623  BuildMI(B, It, DL, HII.get(Hexagon::A2_tfrsi), TmpR0)
1624  .addImm(0x01010101);
1625 
1626  unsigned VandOpc = !Is128B ? Hexagon::V6_vandqrt : Hexagon::V6_vandqrt_128B;
1627  BuildMI(B, It, DL, HII.get(VandOpc), TmpR1)
1628  .addReg(SrcR, getKillRegState(IsKill))
1629  .addReg(TmpR0, RegState::Kill);
1630 
1631  auto *HRI = B.getParent()->getSubtarget<HexagonSubtarget>().getRegisterInfo();
1632  HII.storeRegToStackSlot(B, It, TmpR1, true, FI, RC, HRI);
1633  expandStoreVec(B, std::prev(It), MRI, HII, NewRegs);
1634 
1635  NewRegs.push_back(TmpR0);
1636  NewRegs.push_back(TmpR1);
1637  B.erase(It);
1638  return true;
1639 }
1640 
1641 bool HexagonFrameLowering::expandLoadVecPred(MachineBasicBlock &B,
1643  const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1644  auto &HST = B.getParent()->getSubtarget<HexagonSubtarget>();
1645  MachineInstr *MI = &*It;
1646  if (!MI->getOperand(1).isFI())
1647  return false;
1648 
1649  DebugLoc DL = MI->getDebugLoc();
1650  unsigned DstR = MI->getOperand(0).getReg();
1651  int FI = MI->getOperand(1).getIndex();
1652 
1653  bool Is128B = HST.useHVXDblOps();
1654  auto *RC = !Is128B ? &Hexagon::VectorRegsRegClass
1655  : &Hexagon::VectorRegs128BRegClass;
1656 
1657  // TmpR0 = A2_tfrsi 0x01010101
1658  // TmpR1 = load FI, 0
1659  // DstR = V6_vandvrt TmpR1, TmpR0
1660  unsigned TmpR0 = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
1661  unsigned TmpR1 = MRI.createVirtualRegister(RC);
1662 
1663  BuildMI(B, It, DL, HII.get(Hexagon::A2_tfrsi), TmpR0)
1664  .addImm(0x01010101);
1665  auto *HRI = B.getParent()->getSubtarget<HexagonSubtarget>().getRegisterInfo();
1666  HII.loadRegFromStackSlot(B, It, TmpR1, FI, RC, HRI);
1667  expandLoadVec(B, std::prev(It), MRI, HII, NewRegs);
1668 
1669  unsigned VandOpc = !Is128B ? Hexagon::V6_vandvrt : Hexagon::V6_vandvrt_128B;
1670  BuildMI(B, It, DL, HII.get(VandOpc), DstR)
1671  .addReg(TmpR1, RegState::Kill)
1672  .addReg(TmpR0, RegState::Kill);
1673 
1674  NewRegs.push_back(TmpR0);
1675  NewRegs.push_back(TmpR1);
1676  B.erase(It);
1677  return true;
1678 }
1679 
1680 bool HexagonFrameLowering::expandStoreVec2(MachineBasicBlock &B,
1682  const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1683  MachineFunction &MF = *B.getParent();
1684  auto &HST = MF.getSubtarget<HexagonSubtarget>();
1685  auto &MFI = MF.getFrameInfo();
1686  auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
1687  MachineInstr *MI = &*It;
1688  if (!MI->getOperand(0).isFI())
1689  return false;
1690 
1691  // It is possible that the double vector being stored is only partially
1692  // defined. From the point of view of the liveness tracking, it is ok to
1693  // store it as a whole, but if we break it up we may end up storing a
1694  // register that is entirely undefined.
1695  LivePhysRegs LPR(HRI);
1696  LPR.addLiveIns(B);
1698  for (auto R = B.begin(); R != It; ++R) {
1699  Clobbers.clear();
1700  LPR.stepForward(*R, Clobbers);
1701  // Dead defs are recorded in Clobbers, but are not automatically removed
1702  // from the live set.
1703  for (auto &C : Clobbers)
1704  if (C.second->isReg() && C.second->isDead())
1705  LPR.removeReg(C.first);
1706  }
1707 
1708  DebugLoc DL = MI->getDebugLoc();
1709  unsigned SrcR = MI->getOperand(2).getReg();
1710  unsigned SrcLo = HRI.getSubReg(SrcR, Hexagon::vsub_lo);
1711  unsigned SrcHi = HRI.getSubReg(SrcR, Hexagon::vsub_hi);
1712  bool IsKill = MI->getOperand(2).isKill();
1713  int FI = MI->getOperand(0).getIndex();
1714 
1715  bool Is128B = HST.useHVXDblOps();
1716  const auto &RC = !Is128B ? Hexagon::VectorRegsRegClass
1717  : Hexagon::VectorRegs128BRegClass;
1718  unsigned Size = HRI.getSpillSize(RC);
1719  unsigned NeedAlign = HRI.getSpillAlignment(RC);
1720  unsigned HasAlign = MFI.getObjectAlignment(FI);
1721  unsigned StoreOpc;
1722 
1723  // Store low part.
1724  if (LPR.contains(SrcLo)) {
1725  if (NeedAlign <= HasAlign)
1726  StoreOpc = !Is128B ? Hexagon::V6_vS32b_ai : Hexagon::V6_vS32b_ai_128B;
1727  else
1728  StoreOpc = !Is128B ? Hexagon::V6_vS32Ub_ai : Hexagon::V6_vS32Ub_ai_128B;
1729 
1730  BuildMI(B, It, DL, HII.get(StoreOpc))
1731  .addFrameIndex(FI)
1732  .addImm(0)
1733  .addReg(SrcLo, getKillRegState(IsKill))
1735  }
1736 
1737  // Store high part.
1738  if (LPR.contains(SrcHi)) {
1739  if (NeedAlign <= MinAlign(HasAlign, Size))
1740  StoreOpc = !Is128B ? Hexagon::V6_vS32b_ai : Hexagon::V6_vS32b_ai_128B;
1741  else
1742  StoreOpc = !Is128B ? Hexagon::V6_vS32Ub_ai : Hexagon::V6_vS32Ub_ai_128B;
1743 
1744  BuildMI(B, It, DL, HII.get(StoreOpc))
1745  .addFrameIndex(FI)
1746  .addImm(Size)
1747  .addReg(SrcHi, getKillRegState(IsKill))
1749  }
1750 
1751  B.erase(It);
1752  return true;
1753 }
1754 
1755 bool HexagonFrameLowering::expandLoadVec2(MachineBasicBlock &B,
1757  const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1758  MachineFunction &MF = *B.getParent();
1759  auto &HST = MF.getSubtarget<HexagonSubtarget>();
1760  auto &MFI = MF.getFrameInfo();
1761  auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
1762  MachineInstr *MI = &*It;
1763  if (!MI->getOperand(1).isFI())
1764  return false;
1765 
1766  DebugLoc DL = MI->getDebugLoc();
1767  unsigned DstR = MI->getOperand(0).getReg();
1768  unsigned DstHi = HRI.getSubReg(DstR, Hexagon::vsub_hi);
1769  unsigned DstLo = HRI.getSubReg(DstR, Hexagon::vsub_lo);
1770  int FI = MI->getOperand(1).getIndex();
1771 
1772  bool Is128B = HST.useHVXDblOps();
1773  const auto &RC = !Is128B ? Hexagon::VectorRegsRegClass
1774  : Hexagon::VectorRegs128BRegClass;
1775  unsigned Size = HRI.getSpillSize(RC);
1776  unsigned NeedAlign = HRI.getSpillAlignment(RC);
1777  unsigned HasAlign = MFI.getObjectAlignment(FI);
1778  unsigned LoadOpc;
1779 
1780  // Load low part.
1781  if (NeedAlign <= HasAlign)
1782  LoadOpc = !Is128B ? Hexagon::V6_vL32b_ai : Hexagon::V6_vL32b_ai_128B;
1783  else
1784  LoadOpc = !Is128B ? Hexagon::V6_vL32Ub_ai : Hexagon::V6_vL32Ub_ai_128B;
1785 
1786  BuildMI(B, It, DL, HII.get(LoadOpc), DstLo)
1787  .addFrameIndex(FI)
1788  .addImm(0)
1790 
1791  // Load high part.
1792  if (NeedAlign <= MinAlign(HasAlign, Size))
1793  LoadOpc = !Is128B ? Hexagon::V6_vL32b_ai : Hexagon::V6_vL32b_ai_128B;
1794  else
1795  LoadOpc = !Is128B ? Hexagon::V6_vL32Ub_ai : Hexagon::V6_vL32Ub_ai_128B;
1796 
1797  BuildMI(B, It, DL, HII.get(LoadOpc), DstHi)
1798  .addFrameIndex(FI)
1799  .addImm(Size)
1801 
1802  B.erase(It);
1803  return true;
1804 }
1805 
1806 bool HexagonFrameLowering::expandStoreVec(MachineBasicBlock &B,
1808  const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1809  MachineFunction &MF = *B.getParent();
1810  auto &HST = MF.getSubtarget<HexagonSubtarget>();
1811  auto &MFI = MF.getFrameInfo();
1812  MachineInstr *MI = &*It;
1813  if (!MI->getOperand(0).isFI())
1814  return false;
1815 
1816  auto &HRI = *HST.getRegisterInfo();
1817  DebugLoc DL = MI->getDebugLoc();
1818  unsigned SrcR = MI->getOperand(2).getReg();
1819  bool IsKill = MI->getOperand(2).isKill();
1820  int FI = MI->getOperand(0).getIndex();
1821 
1822  bool Is128B = HST.useHVXDblOps();
1823  const auto &RC = !Is128B ? Hexagon::VectorRegsRegClass
1824  : Hexagon::VectorRegs128BRegClass;
1825  unsigned NeedAlign = HRI.getSpillAlignment(RC);
1826  unsigned HasAlign = MFI.getObjectAlignment(FI);
1827  unsigned StoreOpc;
1828 
1829  if (NeedAlign <= HasAlign)
1830  StoreOpc = !Is128B ? Hexagon::V6_vS32b_ai : Hexagon::V6_vS32b_ai_128B;
1831  else
1832  StoreOpc = !Is128B ? Hexagon::V6_vS32Ub_ai : Hexagon::V6_vS32Ub_ai_128B;
1833 
1834  BuildMI(B, It, DL, HII.get(StoreOpc))
1835  .addFrameIndex(FI)
1836  .addImm(0)
1837  .addReg(SrcR, getKillRegState(IsKill))
1839 
1840  B.erase(It);
1841  return true;
1842 }
1843 
1844 bool HexagonFrameLowering::expandLoadVec(MachineBasicBlock &B,
1846  const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1847  MachineFunction &MF = *B.getParent();
1848  auto &HST = MF.getSubtarget<HexagonSubtarget>();
1849  auto &MFI = MF.getFrameInfo();
1850  MachineInstr *MI = &*It;
1851  if (!MI->getOperand(1).isFI())
1852  return false;
1853 
1854  auto &HRI = *HST.getRegisterInfo();
1855  DebugLoc DL = MI->getDebugLoc();
1856  unsigned DstR = MI->getOperand(0).getReg();
1857  int FI = MI->getOperand(1).getIndex();
1858 
1859  bool Is128B = HST.useHVXDblOps();
1860  const auto &RC = !Is128B ? Hexagon::VectorRegsRegClass
1861  : Hexagon::VectorRegs128BRegClass;
1862  unsigned NeedAlign = HRI.getSpillAlignment(RC);
1863  unsigned HasAlign = MFI.getObjectAlignment(FI);
1864  unsigned LoadOpc;
1865 
1866  if (NeedAlign <= HasAlign)
1867  LoadOpc = !Is128B ? Hexagon::V6_vL32b_ai : Hexagon::V6_vL32b_ai_128B;
1868  else
1869  LoadOpc = !Is128B ? Hexagon::V6_vL32Ub_ai : Hexagon::V6_vL32Ub_ai_128B;
1870 
1871  BuildMI(B, It, DL, HII.get(LoadOpc), DstR)
1872  .addFrameIndex(FI)
1873  .addImm(0)
1875 
1876  B.erase(It);
1877  return true;
1878 }
1879 
1880 bool HexagonFrameLowering::expandSpillMacros(MachineFunction &MF,
1881  SmallVectorImpl<unsigned> &NewRegs) const {
1882  auto &HST = MF.getSubtarget<HexagonSubtarget>();
1883  auto &HII = *HST.getInstrInfo();
1884  MachineRegisterInfo &MRI = MF.getRegInfo();
1885  bool Changed = false;
1886 
1887  for (auto &B : MF) {
1888  // Traverse the basic block.
1890  for (auto I = B.begin(), E = B.end(); I != E; I = NextI) {
1891  MachineInstr *MI = &*I;
1892  NextI = std::next(I);
1893  unsigned Opc = MI->getOpcode();
1894 
1895  switch (Opc) {
1896  case TargetOpcode::COPY:
1897  Changed |= expandCopy(B, I, MRI, HII, NewRegs);
1898  break;
1899  case Hexagon::STriw_pred:
1900  case Hexagon::STriw_mod:
1901  Changed |= expandStoreInt(B, I, MRI, HII, NewRegs);
1902  break;
1903  case Hexagon::LDriw_pred:
1904  case Hexagon::LDriw_mod:
1905  Changed |= expandLoadInt(B, I, MRI, HII, NewRegs);
1906  break;
1907  case Hexagon::PS_vstorerq_ai:
1908  case Hexagon::PS_vstorerq_ai_128B:
1909  Changed |= expandStoreVecPred(B, I, MRI, HII, NewRegs);
1910  break;
1911  case Hexagon::PS_vloadrq_ai:
1912  case Hexagon::PS_vloadrq_ai_128B:
1913  Changed |= expandLoadVecPred(B, I, MRI, HII, NewRegs);
1914  break;
1915  case Hexagon::PS_vloadrw_ai:
1916  case Hexagon::PS_vloadrwu_ai:
1917  case Hexagon::PS_vloadrw_ai_128B:
1918  case Hexagon::PS_vloadrwu_ai_128B:
1919  Changed |= expandLoadVec2(B, I, MRI, HII, NewRegs);
1920  break;
1921  case Hexagon::PS_vstorerw_ai:
1922  case Hexagon::PS_vstorerwu_ai:
1923  case Hexagon::PS_vstorerw_ai_128B:
1924  case Hexagon::PS_vstorerwu_ai_128B:
1925  Changed |= expandStoreVec2(B, I, MRI, HII, NewRegs);
1926  break;
1927  }
1928  }
1929  }
1930 
1931  return Changed;
1932 }
1933 
1935  BitVector &SavedRegs,
1936  RegScavenger *RS) const {
1937  auto &HST = MF.getSubtarget<HexagonSubtarget>();
1938  auto &HRI = *HST.getRegisterInfo();
1939 
1940  SavedRegs.resize(HRI.getNumRegs());
1941 
1942  // If we have a function containing __builtin_eh_return we want to spill and
1943  // restore all callee saved registers. Pretend that they are used.
1945  for (const MCPhysReg *R = HRI.getCalleeSavedRegs(&MF); *R; ++R)
1946  SavedRegs.set(*R);
1947 
1948  // Replace predicate register pseudo spill code.
1949  SmallVector<unsigned,8> NewRegs;
1950  expandSpillMacros(MF, NewRegs);
1951  if (OptimizeSpillSlots && !isOptNone(MF))
1952  optimizeSpillSlots(MF, NewRegs);
1953 
1954  // We need to reserve a a spill slot if scavenging could potentially require
1955  // spilling a scavenged register.
1956  if (!NewRegs.empty() || mayOverflowFrameOffset(MF)) {
1957  MachineFrameInfo &MFI = MF.getFrameInfo();
1958  MachineRegisterInfo &MRI = MF.getRegInfo();
1960  // Reserve an int register in any case, because it could be used to hold
1961  // the stack offset in case it does not fit into a spill instruction.
1962  SpillRCs.insert(&Hexagon::IntRegsRegClass);
1963 
1964  for (unsigned VR : NewRegs)
1965  SpillRCs.insert(MRI.getRegClass(VR));
1966 
1967  for (auto *RC : SpillRCs) {
1968  if (!needToReserveScavengingSpillSlots(MF, HRI, RC))
1969  continue;
1970  unsigned Num = RC == &Hexagon::IntRegsRegClass ? NumberScavengerSlots : 1;
1971  unsigned S = HRI.getSpillSize(*RC), A = HRI.getSpillAlignment(*RC);
1972  for (unsigned i = 0; i < Num; i++) {
1973  int NewFI = MFI.CreateSpillStackObject(S, A);
1974  RS->addScavengingFrameIndex(NewFI);
1975  }
1976  }
1977  }
1978 
1979  TargetFrameLowering::determineCalleeSaves(MF, SavedRegs, RS);
1980 }
1981 
1982 unsigned HexagonFrameLowering::findPhysReg(MachineFunction &MF,
1986  const TargetRegisterClass *RC) const {
1987  auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
1988  auto &MRI = MF.getRegInfo();
1989 
1990  auto isDead = [&FIR,&DeadMap] (unsigned Reg) -> bool {
1991  auto F = DeadMap.find({Reg,0});
1992  if (F == DeadMap.end())
1993  return false;
1994  for (auto &DR : F->second)
1995  if (DR.contains(FIR))
1996  return true;
1997  return false;
1998  };
1999 
2000  for (unsigned Reg : RC->getRawAllocationOrder(MF)) {
2001  bool Dead = true;
2002  for (auto R : HexagonBlockRanges::expandToSubRegs({Reg,0}, MRI, HRI)) {
2003  if (isDead(R.Reg))
2004  continue;
2005  Dead = false;
2006  break;
2007  }
2008  if (Dead)
2009  return Reg;
2010  }
2011  return 0;
2012 }
2013 
2014 void HexagonFrameLowering::optimizeSpillSlots(MachineFunction &MF,
2016  auto &HST = MF.getSubtarget<HexagonSubtarget>();
2017  auto &HII = *HST.getInstrInfo();
2018  auto &HRI = *HST.getRegisterInfo();
2019  auto &MRI = MF.getRegInfo();
2020  HexagonBlockRanges HBR(MF);
2021 
2022  typedef std::map<MachineBasicBlock*,HexagonBlockRanges::InstrIndexMap>
2023  BlockIndexMap;
2024  typedef std::map<MachineBasicBlock*,HexagonBlockRanges::RangeList>
2025  BlockRangeMap;
2026  typedef HexagonBlockRanges::IndexType IndexType;
2027 
2028  struct SlotInfo {
2029  BlockRangeMap Map;
2030  unsigned Size = 0;
2031  const TargetRegisterClass *RC = nullptr;
2032 
2033  SlotInfo() = default;
2034  };
2035 
2036  BlockIndexMap BlockIndexes;
2037  SmallSet<int,4> BadFIs;
2038  std::map<int,SlotInfo> FIRangeMap;
2039 
2040  // Accumulate register classes: get a common class for a pre-existing
2041  // class HaveRC and a new class NewRC. Return nullptr if a common class
2042  // cannot be found, otherwise return the resulting class. If HaveRC is
2043  // nullptr, assume that it is still unset.
2044  auto getCommonRC =
2045  [](const TargetRegisterClass *HaveRC,
2046  const TargetRegisterClass *NewRC) -> const TargetRegisterClass * {
2047  if (HaveRC == nullptr || HaveRC == NewRC)
2048  return NewRC;
2049  // Different classes, both non-null. Pick the more general one.
2050  if (HaveRC->hasSubClassEq(NewRC))
2051  return HaveRC;
2052  if (NewRC->hasSubClassEq(HaveRC))
2053  return NewRC;
2054  return nullptr;
2055  };
2056 
2057  // Scan all blocks in the function. Check all occurrences of frame indexes,
2058  // and collect relevant information.
2059  for (auto &B : MF) {
2060  std::map<int,IndexType> LastStore, LastLoad;
2061  // Emplace appears not to be supported in gcc 4.7.2-4.
2062  //auto P = BlockIndexes.emplace(&B, HexagonBlockRanges::InstrIndexMap(B));
2063  auto P = BlockIndexes.insert(
2064  std::make_pair(&B, HexagonBlockRanges::InstrIndexMap(B)));
2065  auto &IndexMap = P.first->second;
2066  DEBUG(dbgs() << "Index map for BB#" << B.getNumber() << "\n"
2067  << IndexMap << '\n');
2068 
2069  for (auto &In : B) {
2070  int LFI, SFI;
2071  bool Load = HII.isLoadFromStackSlot(In, LFI) && !HII.isPredicated(In);
2072  bool Store = HII.isStoreToStackSlot(In, SFI) && !HII.isPredicated(In);
2073  if (Load && Store) {
2074  // If it's both a load and a store, then we won't handle it.
2075  BadFIs.insert(LFI);
2076  BadFIs.insert(SFI);
2077  continue;
2078  }
2079  // Check for register classes of the register used as the source for
2080  // the store, and the register used as the destination for the load.
2081  // Also, only accept base+imm_offset addressing modes. Other addressing
2082  // modes can have side-effects (post-increments, etc.). For stack
2083  // slots they are very unlikely, so there is not much loss due to
2084  // this restriction.
2085  if (Load || Store) {
2086  int TFI = Load ? LFI : SFI;
2087  unsigned AM = HII.getAddrMode(In);
2088  SlotInfo &SI = FIRangeMap[TFI];
2089  bool Bad = (AM != HexagonII::BaseImmOffset);
2090  if (!Bad) {
2091  // If the addressing mode is ok, check the register class.
2092  unsigned OpNum = Load ? 0 : 2;
2093  auto *RC = HII.getRegClass(In.getDesc(), OpNum, &HRI, MF);
2094  RC = getCommonRC(SI.RC, RC);
2095  if (RC == nullptr)
2096  Bad = true;
2097  else
2098  SI.RC = RC;
2099  }
2100  if (!Bad) {
2101  // Check sizes.
2102  unsigned S = (1U << (HII.getMemAccessSize(In) - 1));
2103  if (SI.Size != 0 && SI.Size != S)
2104  Bad = true;
2105  else
2106  SI.Size = S;
2107  }
2108  if (!Bad) {
2109  for (auto *Mo : In.memoperands()) {
2110  if (!Mo->isVolatile())
2111  continue;
2112  Bad = true;
2113  break;
2114  }
2115  }
2116  if (Bad)
2117  BadFIs.insert(TFI);
2118  }
2119 
2120  // Locate uses of frame indices.
2121  for (unsigned i = 0, n = In.getNumOperands(); i < n; ++i) {
2122  const MachineOperand &Op = In.getOperand(i);
2123  if (!Op.isFI())
2124  continue;
2125  int FI = Op.getIndex();
2126  // Make sure that the following operand is an immediate and that
2127  // it is 0. This is the offset in the stack object.
2128  if (i+1 >= n || !In.getOperand(i+1).isImm() ||
2129  In.getOperand(i+1).getImm() != 0)
2130  BadFIs.insert(FI);
2131  if (BadFIs.count(FI))
2132  continue;
2133 
2134  IndexType Index = IndexMap.getIndex(&In);
2135  if (Load) {
2136  if (LastStore[FI] == IndexType::None)
2137  LastStore[FI] = IndexType::Entry;
2138  LastLoad[FI] = Index;
2139  } else if (Store) {
2140  HexagonBlockRanges::RangeList &RL = FIRangeMap[FI].Map[&B];
2141  if (LastStore[FI] != IndexType::None)
2142  RL.add(LastStore[FI], LastLoad[FI], false, false);
2143  else if (LastLoad[FI] != IndexType::None)
2144  RL.add(IndexType::Entry, LastLoad[FI], false, false);
2145  LastLoad[FI] = IndexType::None;
2146  LastStore[FI] = Index;
2147  } else {
2148  BadFIs.insert(FI);
2149  }
2150  }
2151  }
2152 
2153  for (auto &I : LastLoad) {
2154  IndexType LL = I.second;
2155  if (LL == IndexType::None)
2156  continue;
2157  auto &RL = FIRangeMap[I.first].Map[&B];
2158  IndexType &LS = LastStore[I.first];
2159  if (LS != IndexType::None)
2160  RL.add(LS, LL, false, false);
2161  else
2162  RL.add(IndexType::Entry, LL, false, false);
2163  LS = IndexType::None;
2164  }
2165  for (auto &I : LastStore) {
2166  IndexType LS = I.second;
2167  if (LS == IndexType::None)
2168  continue;
2169  auto &RL = FIRangeMap[I.first].Map[&B];
2170  RL.add(LS, IndexType::None, false, false);
2171  }
2172  }
2173 
2174  DEBUG({
2175  for (auto &P : FIRangeMap) {
2176  dbgs() << "fi#" << P.first;
2177  if (BadFIs.count(P.first))
2178  dbgs() << " (bad)";
2179  dbgs() << " RC: ";
2180  if (P.second.RC != nullptr)
2181  dbgs() << HRI.getRegClassName(P.second.RC) << '\n';
2182  else
2183  dbgs() << "<null>\n";
2184  for (auto &R : P.second.Map)
2185  dbgs() << " BB#" << R.first->getNumber() << " { " << R.second << "}\n";
2186  }
2187  });
2188 
2189  // When a slot is loaded from in a block without being stored to in the
2190  // same block, it is live-on-entry to this block. To avoid CFG analysis,
2191  // consider this slot to be live-on-exit from all blocks.
2192  SmallSet<int,4> LoxFIs;
2193 
2194  std::map<MachineBasicBlock*,std::vector<int>> BlockFIMap;
2195 
2196  for (auto &P : FIRangeMap) {
2197  // P = pair(FI, map: BB->RangeList)
2198  if (BadFIs.count(P.first))
2199  continue;
2200  for (auto &B : MF) {
2201  auto F = P.second.Map.find(&B);
2202  // F = pair(BB, RangeList)
2203  if (F == P.second.Map.end() || F->second.empty())
2204  continue;
2205  HexagonBlockRanges::IndexRange &IR = F->second.front();
2206  if (IR.start() == IndexType::Entry)
2207  LoxFIs.insert(P.first);
2208  BlockFIMap[&B].push_back(P.first);
2209  }
2210  }
2211 
2212  DEBUG({
2213  dbgs() << "Block-to-FI map (* -- live-on-exit):\n";
2214  for (auto &P : BlockFIMap) {
2215  auto &FIs = P.second;
2216  if (FIs.empty())
2217  continue;
2218  dbgs() << " BB#" << P.first->getNumber() << ": {";
2219  for (auto I : FIs) {
2220  dbgs() << " fi#" << I;
2221  if (LoxFIs.count(I))
2222  dbgs() << '*';
2223  }
2224  dbgs() << " }\n";
2225  }
2226  });
2227 
2228 #ifndef NDEBUG
2229  bool HasOptLimit = SpillOptMax.getPosition();
2230 #endif
2231 
2232  // eliminate loads, when all loads eliminated, eliminate all stores.
2233  for (auto &B : MF) {
2234  auto F = BlockIndexes.find(&B);
2235  assert(F != BlockIndexes.end());
2236  HexagonBlockRanges::InstrIndexMap &IM = F->second;
2237  HexagonBlockRanges::RegToRangeMap LM = HBR.computeLiveMap(IM);
2238  HexagonBlockRanges::RegToRangeMap DM = HBR.computeDeadMap(IM, LM);
2239  DEBUG(dbgs() << "BB#" << B.getNumber() << " dead map\n"
2240  << HexagonBlockRanges::PrintRangeMap(DM, HRI));
2241 
2242  for (auto FI : BlockFIMap[&B]) {
2243  if (BadFIs.count(FI))
2244  continue;
2245  DEBUG(dbgs() << "Working on fi#" << FI << '\n');
2246  HexagonBlockRanges::RangeList &RL = FIRangeMap[FI].Map[&B];
2247  for (auto &Range : RL) {
2248  DEBUG(dbgs() << "--Examining range:" << RL << '\n');
2249  if (!IndexType::isInstr(Range.start()) ||
2250  !IndexType::isInstr(Range.end()))
2251  continue;
2252  MachineInstr &SI = *IM.getInstr(Range.start());
2253  MachineInstr &EI = *IM.getInstr(Range.end());
2254  assert(SI.mayStore() && "Unexpected start instruction");
2255  assert(EI.mayLoad() && "Unexpected end instruction");
2256  MachineOperand &SrcOp = SI.getOperand(2);
2257 
2258  HexagonBlockRanges::RegisterRef SrcRR = { SrcOp.getReg(),
2259  SrcOp.getSubReg() };
2260  auto *RC = HII.getRegClass(SI.getDesc(), 2, &HRI, MF);
2261  // The this-> is needed to unconfuse MSVC.
2262  unsigned FoundR = this->findPhysReg(MF, Range, IM, DM, RC);
2263  DEBUG(dbgs() << "Replacement reg:" << PrintReg(FoundR, &HRI) << '\n');
2264  if (FoundR == 0)
2265  continue;
2266 #ifndef NDEBUG
2267  if (HasOptLimit) {
2268  if (SpillOptCount >= SpillOptMax)
2269  return;
2270  SpillOptCount++;
2271  }
2272 #endif
2273 
2274  // Generate the copy-in: "FoundR = COPY SrcR" at the store location.
2275  MachineBasicBlock::iterator StartIt = SI.getIterator(), NextIt;
2276  MachineInstr *CopyIn = nullptr;
2277  if (SrcRR.Reg != FoundR || SrcRR.Sub != 0) {
2278  const DebugLoc &DL = SI.getDebugLoc();
2279  CopyIn = BuildMI(B, StartIt, DL, HII.get(TargetOpcode::COPY), FoundR)
2280  .add(SrcOp);
2281  }
2282 
2283  ++StartIt;
2284  // Check if this is a last store and the FI is live-on-exit.
2285  if (LoxFIs.count(FI) && (&Range == &RL.back())) {
2286  // Update store's source register.
2287  if (unsigned SR = SrcOp.getSubReg())
2288  SrcOp.setReg(HRI.getSubReg(FoundR, SR));
2289  else
2290  SrcOp.setReg(FoundR);
2291  SrcOp.setSubReg(0);
2292  // We are keeping this register live.
2293  SrcOp.setIsKill(false);
2294  } else {
2295  B.erase(&SI);
2296  IM.replaceInstr(&SI, CopyIn);
2297  }
2298 
2299  auto EndIt = std::next(EI.getIterator());
2300  for (auto It = StartIt; It != EndIt; It = NextIt) {
2301  MachineInstr &MI = *It;
2302  NextIt = std::next(It);
2303  int TFI;
2304  if (!HII.isLoadFromStackSlot(MI, TFI) || TFI != FI)
2305  continue;
2306  unsigned DstR = MI.getOperand(0).getReg();
2307  assert(MI.getOperand(0).getSubReg() == 0);
2308  MachineInstr *CopyOut = nullptr;
2309  if (DstR != FoundR) {
2310  DebugLoc DL = MI.getDebugLoc();
2311  unsigned MemSize = (1U << (HII.getMemAccessSize(MI) - 1));
2312  assert(HII.getAddrMode(MI) == HexagonII::BaseImmOffset);
2313  unsigned CopyOpc = TargetOpcode::COPY;
2314  if (HII.isSignExtendingLoad(MI))
2315  CopyOpc = (MemSize == 1) ? Hexagon::A2_sxtb : Hexagon::A2_sxth;
2316  else if (HII.isZeroExtendingLoad(MI))
2317  CopyOpc = (MemSize == 1) ? Hexagon::A2_zxtb : Hexagon::A2_zxth;
2318  CopyOut = BuildMI(B, It, DL, HII.get(CopyOpc), DstR)
2319  .addReg(FoundR, getKillRegState(&MI == &EI));
2320  }
2321  IM.replaceInstr(&MI, CopyOut);
2322  B.erase(It);
2323  }
2324 
2325  // Update the dead map.
2326  HexagonBlockRanges::RegisterRef FoundRR = { FoundR, 0 };
2327  for (auto RR : HexagonBlockRanges::expandToSubRegs(FoundRR, MRI, HRI))
2328  DM[RR].subtract(Range);
2329  } // for Range in range list
2330  }
2331  }
2332 }
2333 
2334 void HexagonFrameLowering::expandAlloca(MachineInstr *AI,
2335  const HexagonInstrInfo &HII, unsigned SP, unsigned CF) const {
2336  MachineBasicBlock &MB = *AI->getParent();
2337  DebugLoc DL = AI->getDebugLoc();
2338  unsigned A = AI->getOperand(2).getImm();
2339 
2340  // Have
2341  // Rd = alloca Rs, #A
2342  //
2343  // If Rs and Rd are different registers, use this sequence:
2344  // Rd = sub(r29, Rs)
2345  // r29 = sub(r29, Rs)
2346  // Rd = and(Rd, #-A) ; if necessary
2347  // r29 = and(r29, #-A) ; if necessary
2348  // Rd = add(Rd, #CF) ; CF size aligned to at most A
2349  // otherwise, do
2350  // Rd = sub(r29, Rs)
2351  // Rd = and(Rd, #-A) ; if necessary
2352  // r29 = Rd
2353  // Rd = add(Rd, #CF) ; CF size aligned to at most A
2354 
2355  MachineOperand &RdOp = AI->getOperand(0);
2356  MachineOperand &RsOp = AI->getOperand(1);
2357  unsigned Rd = RdOp.getReg(), Rs = RsOp.getReg();
2358 
2359  // Rd = sub(r29, Rs)
2360  BuildMI(MB, AI, DL, HII.get(Hexagon::A2_sub), Rd)
2361  .addReg(SP)
2362  .addReg(Rs);
2363  if (Rs != Rd) {
2364  // r29 = sub(r29, Rs)
2365  BuildMI(MB, AI, DL, HII.get(Hexagon::A2_sub), SP)
2366  .addReg(SP)
2367  .addReg(Rs);
2368  }
2369  if (A > 8) {
2370  // Rd = and(Rd, #-A)
2371  BuildMI(MB, AI, DL, HII.get(Hexagon::A2_andir), Rd)
2372  .addReg(Rd)
2373  .addImm(-int64_t(A));
2374  if (Rs != Rd)
2375  BuildMI(MB, AI, DL, HII.get(Hexagon::A2_andir), SP)
2376  .addReg(SP)
2377  .addImm(-int64_t(A));
2378  }
2379  if (Rs == Rd) {
2380  // r29 = Rd
2381  BuildMI(MB, AI, DL, HII.get(TargetOpcode::COPY), SP)
2382  .addReg(Rd);
2383  }
2384  if (CF > 0) {
2385  // Rd = add(Rd, #CF)
2386  BuildMI(MB, AI, DL, HII.get(Hexagon::A2_addi), Rd)
2387  .addReg(Rd)
2388  .addImm(CF);
2389  }
2390 }
2391 
2393  const MachineFrameInfo &MFI = MF.getFrameInfo();
2394  if (!MFI.hasVarSizedObjects())
2395  return false;
2396  unsigned MaxA = MFI.getMaxAlignment();
2397  if (MaxA <= getStackAlignment())
2398  return false;
2399  return true;
2400 }
2401 
2403  const MachineFunction &MF) const {
2404  for (auto &B : MF)
2405  for (auto &I : B)
2406  if (I.getOpcode() == Hexagon::PS_aligna)
2407  return &I;
2408  return nullptr;
2409 }
2410 
2411 /// Adds all callee-saved registers as implicit uses or defs to the
2412 /// instruction.
2413 void HexagonFrameLowering::addCalleeSaveRegistersAsImpOperand(MachineInstr *MI,
2414  const CSIVect &CSI, bool IsDef, bool IsKill) const {
2415  // Add the callee-saved registers as implicit uses.
2416  for (auto &R : CSI)
2417  MI->addOperand(MachineOperand::CreateReg(R.getReg(), IsDef, true, IsKill));
2418 }
2419 
2420 /// Determine whether the callee-saved register saves and restores should
2421 /// be generated via inline code. If this function returns "true", inline
2422 /// code will be generated. If this function returns "false", additional
2423 /// checks are performed, which may still lead to the inline code.
2424 bool HexagonFrameLowering::shouldInlineCSR(const MachineFunction &MF,
2425  const CSIVect &CSI) const {
2427  return true;
2428  if (!hasFP(MF))
2429  return true;
2430  if (!isOptSize(MF) && !isMinSize(MF))
2432  return true;
2433 
2434  // Check if CSI only has double registers, and if the registers form
2435  // a contiguous block starting from D8.
2436  BitVector Regs(Hexagon::NUM_TARGET_REGS);
2437  for (unsigned i = 0, n = CSI.size(); i < n; ++i) {
2438  unsigned R = CSI[i].getReg();
2439  if (!Hexagon::DoubleRegsRegClass.contains(R))
2440  return true;
2441  Regs[R] = true;
2442  }
2443  int F = Regs.find_first();
2444  if (F != Hexagon::D8)
2445  return true;
2446  while (F >= 0) {
2447  int N = Regs.find_next(F);
2448  if (N >= 0 && N != F+1)
2449  return true;
2450  F = N;
2451  }
2452 
2453  return false;
2454 }
2455 
2456 bool HexagonFrameLowering::useSpillFunction(const MachineFunction &MF,
2457  const CSIVect &CSI) const {
2458  if (shouldInlineCSR(MF, CSI))
2459  return false;
2460  unsigned NumCSI = CSI.size();
2461  if (NumCSI <= 1)
2462  return false;
2463 
2464  unsigned Threshold = isOptSize(MF) ? SpillFuncThresholdOs
2466  return Threshold < NumCSI;
2467 }
2468 
2469 bool HexagonFrameLowering::useRestoreFunction(const MachineFunction &MF,
2470  const CSIVect &CSI) const {
2471  if (shouldInlineCSR(MF, CSI))
2472  return false;
2473  // The restore functions do a bit more than just restoring registers.
2474  // The non-returning versions will go back directly to the caller's
2475  // caller, others will clean up the stack frame in preparation for
2476  // a tail call. Using them can still save code size even if only one
2477  // register is getting restores. Make the decision based on -Oz:
2478  // using -Os will use inline restore for a single register.
2479  if (isMinSize(MF))
2480  return true;
2481  unsigned NumCSI = CSI.size();
2482  if (NumCSI <= 1)
2483  return false;
2484 
2485  unsigned Threshold = isOptSize(MF) ? SpillFuncThresholdOs-1
2487  return Threshold < NumCSI;
2488 }
2489 
2490 bool HexagonFrameLowering::mayOverflowFrameOffset(MachineFunction &MF) const {
2491  unsigned StackSize = MF.getFrameInfo().estimateStackSize(MF);
2492  auto &HST = MF.getSubtarget<HexagonSubtarget>();
2493  // A fairly simplistic guess as to whether a potential load/store to a
2494  // stack location could require an extra register.
2495  if (HST.useHVXOps() && StackSize > 256)
2496  return true;
2497 
2498  // Check if the function has store-immediate instructions that access
2499  // the stack. Since the offset field is not extendable, if the stack
2500  // size exceeds the offset limit (6 bits, shifted), the stores will
2501  // require a new base register.
2502  bool HasImmStack = false;
2503  unsigned MinLS = ~0u; // Log_2 of the memory access size.
2504 
2505  for (const MachineBasicBlock &B : MF) {
2506  for (const MachineInstr &MI : B) {
2507  unsigned LS = 0;
2508  switch (MI.getOpcode()) {
2509  case Hexagon::S4_storeirit_io:
2510  case Hexagon::S4_storeirif_io:
2511  case Hexagon::S4_storeiri_io:
2512  ++LS;
2514  case Hexagon::S4_storeirht_io:
2515  case Hexagon::S4_storeirhf_io:
2516  case Hexagon::S4_storeirh_io:
2517  ++LS;
2519  case Hexagon::S4_storeirbt_io:
2520  case Hexagon::S4_storeirbf_io:
2521  case Hexagon::S4_storeirb_io:
2522  if (MI.getOperand(0).isFI())
2523  HasImmStack = true;
2524  MinLS = std::min(MinLS, LS);
2525  break;
2526  }
2527  }
2528  }
2529 
2530  if (HasImmStack)
2531  return !isUInt<6>(StackSize >> MinLS);
2532 
2533  return false;
2534 }
void resize(unsigned N, bool t=false)
resize - Grow or shrink the bitvector.
Definition: BitVector.h:372
const NoneType None
Definition: None.h:24
unsigned getStackAlignment() const
getStackAlignment - This method returns the number of bytes to which the stack pointer must be aligne...
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
const MCPhysReg * getCallerSavedRegs(const MachineFunction *MF, const TargetRegisterClass *RC) const
BitVector & set()
Definition: BitVector.h:398
int find_first() const
find_first - Returns the index of the first set bit, -1 if none of the bits are set.
Definition: BitVector.h:332
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
GCNRegPressure max(const GCNRegPressure &P1, const GCNRegPressure &P2)
instr_iterator instr_end()
void mapLocalFrameObject(int ObjectIndex, int64_t Offset)
Map a frame index into the local object block.
static cl::opt< int > SpillFuncThresholdOs("spill-func-threshold-Os", cl::Hidden, cl::desc("Specify Os spill func threshold"), cl::init(1), cl::ZeroOrMore)
bool isValid() const
isValid - returns true if this iterator is not yet at the end.
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
Definition: MCSymbol.h:42
int getNumber() const
MachineBasicBlocks are uniquely numbered at the function level, unless they're not in a MachineFuncti...
void storeRegToStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI, unsigned SrcReg, bool isKill, int FrameIndex, const TargetRegisterClass *RC, const TargetRegisterInfo *TRI) const override
Store the specified register of the given register class to the specified stack frame index...
unsigned createVirtualRegister(const TargetRegisterClass *RegClass)
createVirtualRegister - Create and return a new virtual register in the function with the specified r...
Maximum length of the test input libFuzzer tries to guess a good value based on the corpus and reports it always prefer smaller inputs during the corpus shuffle When libFuzzer itself reports a bug this exit code will be used If indicates the maximal total time in seconds to run the fuzzer minimizes the provided crash input Use with tries to cleanse the provided crash input to make it contain fewer original bytes Use with exact_artifact_path to specify the output Experimental Use value profile to guide fuzzing Number of jobs to run If min(jobs, NumberOfCpuCores()/2)\" is used.") FUZZER_FLAG_INT(reload
MachineBasicBlock * findNearestCommonDominator(MachineBasicBlock *A, MachineBasicBlock *B)
bool hasSubClassEq(const TargetRegisterClass *RC) const
Returns true if RC is a sub-class of or equal to this class.
int find_next(unsigned Prev) const
find_next - Returns the index of the next set bit following the "Prev" bit.
Definition: BitVector.h:340
static Optional< MachineBasicBlock::iterator > findCFILocation(MachineBasicBlock &B)
unsigned getSpillAlignment(const TargetRegisterClass &RC) const
Return the minimum required alignment for a spill slot for a register of this class.
iterator getFirstTerminator()
Returns an iterator to the first terminator instruction of this basic block.
Describe properties that are true of each instruction in the target description file.
Definition: MCInstrDesc.h:163
bool mayStore(QueryType Type=AnyInBundle) const
Return true if this instruction could possibly modify memory.
Definition: MachineInstr.h:613
DataLayout DL
static MCCFIInstruction createOffset(MCSymbol *L, unsigned Register, int Offset)
.cfi_offset Previous value of Register is saved at offset Offset from CFA.
Definition: MCDwarf.h:404
static bool isVirtualRegister(unsigned Reg)
Return true if the specified register number is in the virtual register namespace.
static void dump_registers(BitVector &Regs, const TargetRegisterInfo &TRI)
static RegisterSet expandToSubRegs(RegisterRef R, const MachineRegisterInfo &MRI, const TargetRegisterInfo &TRI)
static const MCPhysReg VRegs[32]
const MCInstrDesc & getDesc() const
Returns the target instruction descriptor of this MachineInstr.
Definition: MachineInstr.h:276
Hexagon target-specific information for each MachineFunction.
const SpillSlot * getCalleeSavedSpillSlots(unsigned &NumEntries) const override
getCalleeSavedSpillSlots - This method returns a pointer to an array of pairs, that contains an entry...
A debug info location.
Definition: DebugLoc.h:34
const Function * getFunction() const
getFunction - Return the LLVM function that this machine code represents
static const char * getSpillFunctionFor(unsigned MaxReg, SpillKind SpillType, bool Stkchk=false)
uint64_t alignTo(uint64_t Value, uint64_t Align, uint64_t Skew=0)
Returns the next integer (mod 2**64) that is greater than or equal to Value and is a multiple of Alig...
Definition: MathExtras.h:677
#define R2(n)
static unsigned SpillOptCount
static cl::opt< int > SpillFuncThreshold("spill-func-threshold", cl::Hidden, cl::desc("Specify O2(not Os) spill func threshold"), cl::init(6), cl::ZeroOrMore)
iterator_range< mop_iterator > operands()
Definition: MachineInstr.h:306
static cl::opt< unsigned > SpillOptMax("spill-opt-max", cl::Hidden, cl::init(std::numeric_limits< unsigned >::max()))
size_type size() const
Determine the number of elements in the SetVector.
Definition: SetVector.h:78
const MachineInstrBuilder & addCFIIndex(unsigned CFIIndex) const
bool optForSize() const
Optimize this function for size (-Os) or minimum size (-Oz).
Definition: Function.h:522
bool isObjectPreAllocated(int ObjectIdx) const
Return true if the object was pre-allocated into the local block.
bool optForMinSize() const
Optimize this function for minimum size (-Oz).
Definition: Function.h:519
return AArch64::GPR64RegClass contains(Reg)
iterator_range< succ_iterator > successors()
StringRef getName() const
Return a constant reference to the value's name.
Definition: Value.cpp:218
INITIALIZE_PASS(HexagonCallFrameInformation,"hexagon-cfi","Hexagon call frame information", false, false) FunctionPass *llvm
unsigned getMaxAlignment() const
Return the alignment in bytes that this function must be aligned to, which is greater than the defaul...
const std::vector< CalleeSavedInfo > & getCalleeSavedInfo() const
Returns a reference to call saved info vector for the current function.
uint64_t getStackSize() const
Return the number of bytes that must be allocated to hold all of the fixed size frame objects...
int64_t getLocalFrameSize() const
Get the size of the local object blob.
void add(IndexType Start, IndexType End, bool Fixed, bool TiedEnd)
void loadRegFromStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI, unsigned DestReg, int FrameIndex, const TargetRegisterClass *RC, const TargetRegisterInfo *TRI) const override
Load the specified register of the given register class from the specified stack frame index...
void setLocalFrameSize(int64_t sz)
Set the size of the local object blob.
unsigned getNumBlockIDs() const
getNumBlockIDs - Return the number of MBB ID's allocated.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
instr_iterator erase(instr_iterator I)
Remove an instruction from the instruction list and delete it.
void setUseLocalStackAllocationBlock(bool v)
setUseLocalStackAllocationBlock - Set whether the local allocation blob should be allocated together ...
MCSuperRegIterator enumerates all super-registers of Reg.
bool isPhysRegUsed(unsigned PhysReg) const
Return true if the specified register is modified or read in this function.
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
static MachineOperand CreateReg(unsigned Reg, bool isDef, bool isImp=false, bool isKill=false, bool isDead=false, bool isUndef=false, bool isEarlyClobber=false, unsigned SubReg=0, bool isDebug=false, bool isInternalRead=false)
MachineBasicBlock::iterator eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB, MachineBasicBlock::iterator I) const override
This method is called during prolog/epilog code insertion to eliminate call frame setup and destroy p...
bool runOnMachineFunction(MachineFunction &MF) override
runOnMachineFunction - This method must be overloaded to perform the desired machine code transformat...
const HexagonRegisterInfo * getRegisterInfo() const override
bool DisableFramePointerElim(const MachineFunction &MF) const
DisableFramePointerElim - This returns true if frame pointer elimination optimization should be disab...
ArrayRef< MCPhysReg > getRawAllocationOrder(const MachineFunction &MF) const
Returns the preferred order for allocating registers from this register class in MF.
static cl::opt< bool > EnableStackOVFSanitizer("enable-stackovf-sanitizer", cl::Hidden, cl::desc("Enable runtime checks for stack overflow."), cl::init(false), cl::ZeroOrMore)
bool mayLoad(QueryType Type=AnyInBundle) const
Return true if this instruction could possibly read memory.
Definition: MachineInstr.h:600
const TargetRegisterClass * getRegClass(unsigned Reg) const
Return the register class of the specified virtual register.
Reg
All possible values of the reg field in the ModR/M byte.
static cl::opt< bool > EnableShrinkWrapping("hexagon-shrink-frame", cl::init(true), cl::Hidden, cl::ZeroOrMore, cl::desc("Enable stack frame shrink wrapping"))
The MachineFrameInfo class represents an abstract stack frame until prolog/epilog code is inserted...
bool isFixedObjectIndex(int ObjectIdx) const
Returns true if the specified index corresponds to a fixed stack object.
static unsigned getMax32BitSubRegister(unsigned Reg, const TargetRegisterInfo &TRI, bool hireg=true)
Map a register pair Reg to the subregister that has the greater "number", i.e.
bool hasDebugInfo() const
Returns true if valid debug info is present.
LLVM_NODISCARD unsigned addFrameInst(const MCCFIInstruction &Inst)
MachineMemOperand * getMachineMemOperand(MachinePointerInfo PtrInfo, MachineMemOperand::Flags f, uint64_t s, unsigned base_alignment, const AAMDNodes &AAInfo=AAMDNodes(), const MDNode *Ranges=nullptr, SyncScope::ID SSID=SyncScope::System, AtomicOrdering Ordering=AtomicOrdering::NotAtomic, AtomicOrdering FailureOrdering=AtomicOrdering::NotAtomic)
getMachineMemOperand - Allocate a new MachineMemOperand.
const MachineInstrBuilder & addImm(int64_t Val) const
Add a new immediate operand.
LLVM_NODISCARD bool empty() const
Definition: SmallVector.h:60
const MachineBasicBlock & front() const
#define F(x, y, z)
Definition: MD5.cpp:55
void copyImplicitOps(MachineFunction &MF, const MachineInstr &MI)
Copy implicit register operands from specified instruction to this instruction.
bool isKill() const
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition: SetVector.h:142
bool isFI() const
isFI - Tests if this is a MO_FrameIndex operand.
static bool isMinSize(const MachineFunction &MF)
const RegList & Regs
unsigned getLocalFrameMaxAlign() const
Return the required alignment of the local object blob.
static bool hasTailCall(const MachineBasicBlock &MBB)
Returns true if MBB has a machine instructions that indicates a tail call in the block.
void setLocalFrameMaxAlign(unsigned Align)
Required alignment of the local object blob, which is the strictest alignment of any object in it...
iterator getLastNonDebugInstr()
Returns an iterator to the last non-debug instruction in the basic block, or end().
bool needsAligna(const MachineFunction &MF) const
void determineCalleeSaves(MachineFunction &MF, BitVector &SavedRegs, RegScavenger *RS) const override
This method determines which of the registers reported by TargetRegisterInfo::getCalleeSavedRegs() sh...
MachineBasicBlock * findNearestCommonDominator(MachineBasicBlock *A, MachineBasicBlock *B)
findNearestCommonDominator - Find nearest common dominator basic block for basic block A and B...
CodeGenOpt::Level getOptLevel() const
Returns the optimization level: None, Less, Default, or Aggressive.
int64_t getImm() const
static bool needsStackFrame(const MachineBasicBlock &MBB, const BitVector &CSR, const HexagonRegisterInfo &HRI)
Checks if the basic block contains any instruction that needs a stack frame to be already in place...
void emitPrologue(MachineFunction &MF, MachineBasicBlock &MBB) const override
Perform most of the PEI work here:
Printable PrintReg(unsigned Reg, const TargetRegisterInfo *TRI=nullptr, unsigned SubRegIdx=0)
Prints virtual and physical registers with or without a TRI instance.
static MachinePointerInfo getStack(MachineFunction &MF, int64_t Offset)
Stack pointer relative access.
unsigned getKillRegState(bool B)
unsigned estimateStackSize(const MachineFunction &MF) const
Estimate and return the size of the stack frame.
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
Definition: MachineInstr.h:279
uint16_t MCPhysReg
An unsigned integer type large enough to represent all physical registers, but not necessarily virtua...
static cl::opt< bool > EliminateFramePointer("hexagon-fp-elim", cl::init(true), cl::Hidden, cl::desc("Refrain from using FP whenever possible"))
bool isSpillSlotObjectIndex(int ObjectIdx) const
Returns true if the specified index corresponds to a spill slot.
const MachineBasicBlock * getParent() const
Definition: MachineInstr.h:139
mmo_iterator memoperands_end() const
Definition: MachineInstr.h:364
INITIALIZE_PASS(HexagonEarlyIfConversion,"hexagon-eif","Hexagon early if conversion", false, false) bool HexagonEarlyIfConversion MachineBasicBlock * SB
constexpr uint64_t MinAlign(uint64_t A, uint64_t B)
A and B are either alignments or offsets.
Definition: MathExtras.h:602
MachineInstrBuilder BuildMI(MachineFunction &MF, const DebugLoc &DL, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
#define P(N)
static bool needToReserveScavengingSpillSlots(MachineFunction &MF, const HexagonRegisterInfo &HRI, const TargetRegisterClass *RC)
Returns true if there are no caller-saved registers available in class RC.
static bool isOptSize(const MachineFunction &MF)
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:401
static cl::opt< unsigned > NumberScavengerSlots("number-scavenger-slots", cl::Hidden, cl::desc("Set the number of scavenger slots"), cl::init(2), cl::ZeroOrMore)
bool isReturn(QueryType Type=AnyInBundle) const
Definition: MachineInstr.h:428
const MachineInstrBuilder & setMemRefs(MachineInstr::mmo_iterator b, MachineInstr::mmo_iterator e) const
void addLiveIn(MCPhysReg PhysReg, LaneBitmask LaneMask=LaneBitmask::getAll())
Adds the specified register as a live in.
This file declares the machine register scavenger class.
MCSymbol * createTempSymbol(bool CanBeUnnamed=true)
Create and return a new assembler temporary symbol with a unique but unspecified name.
Definition: MCContext.cpp:215
unsigned const MachineRegisterInfo * MRI
static MCCFIInstruction createDefCfa(MCSymbol *L, unsigned Register, int Offset)
.cfi_def_cfa defines a rule for computing CFA as: take address from Register and add Offset to it...
Definition: MCDwarf.h:377
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition: MathExtras.h:421
static cl::opt< bool > DisableDeallocRet("disable-hexagon-dealloc-ret", cl::Hidden, cl::desc("Disable Dealloc Return for Hexagon target"))
bool isEHReturnCalleeSaveReg(unsigned Reg) const
MachineFrameInfo & getFrameInfo()
getFrameInfo - Return the frame info object for the current function.
void setStackSize(uint64_t Size)
Set the size of the stack.
DebugLoc findDebugLoc(instr_iterator MBBI)
Find the next valid DebugLoc starting at MBBI, skipping any DBG_VALUE instructions.
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
Definition: SmallSet.h:36
const MachineOperand & getOperand(unsigned i) const
Definition: MachineInstr.h:284
#define A
Definition: LargeTest.cpp:12
void insertCFIInstructions(MachineFunction &MF) const
MCRegAliasIterator enumerates all registers aliasing Reg.
bool isPositionIndependent() const
static const unsigned End
void processFunctionBeforeFrameFinalized(MachineFunction &MF, RegScavenger *RS=nullptr) const override
processFunctionBeforeFrameFinalized - This method is called immediately before the specified function...
Ty * getInfo()
getInfo - Keep track of various per-function pieces of information for backends that would like to do...
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:298
self_iterator getIterator()
Definition: ilist_node.h:82
std::pair< NoneType, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
Definition: SmallSet.h:81
unsigned getSubReg() const
int CreateSpillStackObject(uint64_t Size, unsigned Alignment)
Create a new statically sized stack object that represents a spill slot, returning a nonnegative iden...
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
MCSubRegIterator enumerates all sub-registers of Reg.
This file implements the LivePhysRegs utility for tracking liveness of physical registers.
bool dominates(const MachineDomTreeNode *A, const MachineDomTreeNode *B) const
static MachineInstr * getReturn(MachineBasicBlock &MBB)
Returns the "return" instruction from this block, or nullptr if there isn't any.
static bool hasReturn(const MachineBasicBlock &MBB)
Returns true if MBB contains an instruction that returns.
int64_t getObjectOffset(int ObjectIdx) const
Return the assigned stack offset of the specified object from the incoming stack pointer.
bool isDeadObjectIndex(int ObjectIdx) const
Returns true if the specified index corresponds to a dead object.
virtual void determineCalleeSaves(MachineFunction &MF, BitVector &SavedRegs, RegScavenger *RS=nullptr) const
This method determines which of the registers reported by TargetRegisterInfo::getCalleeSavedRegs() sh...
The memory access writes data.
size_type count(const T &V) const
count - Return 1 if the element is in the set, 0 otherwise.
Definition: SmallSet.h:65
bool hasCalls() const
Return true if the current function has any function calls.
#define E
Definition: LargeTest.cpp:27
static cl::opt< unsigned > ShrinkLimit("shrink-frame-limit", cl::init(std::numeric_limits< unsigned >::max()), cl::Hidden, cl::ZeroOrMore, cl::desc("Max count of stack frame shrink-wraps"))
void addOperand(MachineFunction &MF, const MachineOperand &Op)
Add the specified operand to the instruction.
#define B
Definition: LargeTest.cpp:24
const MCContext & getContext() const
PostDominatorTree Class - Concrete subclass of DominatorTree that is used to compute the post-dominat...
void addScavengingFrameIndex(int FI)
Add a scavenging frame index.
MachineOperand class - Representation of each machine instruction operand.
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:861
unsigned getObjectAlignment(int ObjectIdx) const
Return the alignment of the specified stack object.
unsigned getMaxCallFrameSize() const
Return the maximum size of a call frame that must be allocated for an outgoing function call...
MachineBasicBlock * getBlockNumbered(unsigned N) const
getBlockNumbered - MachineBasicBlocks are automatically numbered when they are inserted into the mach...
const size_t N
bool needsUnwindTableEntry() const
True if this function needs an unwind table.
Definition: Function.h:497
int getFrameIndexReference(const MachineFunction &MF, int FI, unsigned &FrameReg) const override
getFrameIndexReference - This method should return the base register and offset used to reference a f...
bool assignCalleeSavedSpillSlots(MachineFunction &MF, const TargetRegisterInfo *TRI, std::vector< CalleeSavedInfo > &CSI) const override
assignCalleeSavedSpillSlots - Allows target to override spill slot assignment logic.
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:132
The CalleeSavedInfo class tracks the information need to locate where a callee saved register is in t...
static cl::opt< bool > EnableSaveRestoreLong("enable-save-restore-long", cl::Hidden, cl::desc("Enable long calls for save-restore stubs."), cl::init(false), cl::ZeroOrMore)
virtual BitVector getReservedRegs(const MachineFunction &MF) const =0
Returns a bitset indexed by physical register number indicating if a register is a special register t...
static unsigned getReg(const void *D, unsigned RC, unsigned RegNo)
const TargetRegisterClass * getMinimalPhysRegClass(unsigned Reg, MVT VT=MVT::Other) const
Returns the Register Class of a physical register of the given type, picking the most sub register cl...
FunctionPass * createHexagonCallFrameInformation()
bool runOnMachineFunction(MachineFunction &F) override
runOnMachineFunction - This method must be overloaded to perform the desired machine code transformat...
const DebugLoc & getDebugLoc() const
Returns the debug location id of this MachineInstr.
Definition: MachineInstr.h:257
constexpr char Size[]
Key for Kernel::Arg::Metadata::mSize.
llvm_unreachable("Unknown RegBank!")
MachineRegisterInfo - Keep track of information for virtual and physical registers, including vreg register classes, use/def chains for registers, etc.
MachineFunctionProperties & set(Property P)
Representation of each machine instruction.
Definition: MachineInstr.h:59
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
Definition: Function.h:254
static bool isRestoreCall(unsigned Opc)
std::map< RegisterRef, RangeList > RegToRangeMap
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
A set of physical registers with utility functions to track liveness when walking backward/forward th...
Definition: LivePhysRegs.h:49
#define C
Definition: LargeTest.cpp:25
IndexType getIndex(MachineInstr *MI) const
static cl::opt< bool > OptimizeSpillSlots("hexagon-opt-spill", cl::Hidden, cl::init(true), cl::desc("Optimize spill slots"))
TargetOptions Options
Definition: TargetMachine.h:95
const MachineInstrBuilder & addMemOperand(MachineMemOperand *MMO) const
#define I(x, y, z)
Definition: MD5.cpp:58
void setMaxCallFrameSize(unsigned S)
bool isCall(QueryType Type=AnyInBundle) const
Definition: MachineInstr.h:432
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
const TargetMachine & getTarget() const
getTarget - Return the target machine this machine code is compiled with
bool hasVarSizedObjects() const
This method may be called any time after instruction selection is complete to determine if the stack ...
bool isLiveIn(MCPhysReg Reg, LaneBitmask LaneMask=LaneBitmask::getAll()) const
Return true if the specified register is in the live in set.
static int const Threshold
TODO: Write a new FunctionPass AliasAnalysis so that it can keep a cache.
const unsigned Kind
unsigned getReg() const
getReg - Returns the register number.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
const HexagonInstrInfo * getInstrInfo() const override
rpo Deduce function attributes in RPO
A vector that has set insertion semantics.
Definition: SetVector.h:41
#define LLVM_FALLTHROUGH
LLVM_FALLTHROUGH - Mark fallthrough cases in switch statements.
Definition: Compiler.h:235
#define DEBUG(X)
Definition: Debug.h:118
static bool isOptNone(const MachineFunction &MF)
Primary interface to the complete machine description for the target machine.
Definition: TargetMachine.h:56
bool hasFP(const MachineFunction &MF) const override
hasFP - Return true if the specified function should have a dedicated frame pointer register...
IRTranslator LLVM IR MI
MachineModuleInfo & getMMI() const
PassRegistry - This class manages the registration and intitialization of the pass subsystem as appli...
Definition: PassRegistry.h:40
int getObjectIndexEnd() const
Return one past the maximum frame object index.
unsigned getSpillSize(const TargetRegisterClass &RC) const
Return the size in bytes of the stack slot allocated to hold a spilled copy of a register from class ...
void initializeHexagonCallFrameInformationPass(PassRegistry &)
auto find_if(R &&Range, UnaryPredicate P) -> decltype(std::begin(Range))
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly...
Definition: STLExtras.h:846
bool dominates(const MachineDomTreeNode *A, const MachineDomTreeNode *B) const
const MachineInstrBuilder & addReg(unsigned RegNo, unsigned flags=0, unsigned SubReg=0) const
Add a new virtual register operand.
void setObjectAlignment(int ObjectIdx, unsigned Align)
setObjectAlignment - Change the alignment of the specified stack object.
const MachineInstr * getAlignaInstr(const MachineFunction &MF) const
static unsigned getMaxCalleeSavedReg(const std::vector< CalleeSavedInfo > &CSI, const TargetRegisterInfo &TRI)
Returns the callee saved register with the largest id in the vector.
DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to compute a normal dominat...
Statically lint checks LLVM IR
Definition: Lint.cpp:193
int64_t getObjectSize(int ObjectIdx) const
Return the size of the specified object.
Properties which a MachineFunction may have at a given point in time.
This class contains meta information specific to a module.
mmo_iterator memoperands_begin() const
Access to memory operands of the instruction.
Definition: MachineInstr.h:363