]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/lib/CodeGen/PrologEpilogInserter.cpp
Merge llvm, clang, lld, lldb, compiler-rt and libc++ r301441, and update
[FreeBSD/FreeBSD.git] / contrib / llvm / lib / CodeGen / PrologEpilogInserter.cpp
1 //===-- PrologEpilogInserter.cpp - Insert Prolog/Epilog code in function --===//
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 // This pass is responsible for finalizing the functions frame layout, saving
11 // callee saved registers, and for emitting prolog & epilog code for the
12 // function.
13 //
14 // This pass must be run after register allocation.  After this pass is
15 // executed, it is illegal to construct MO_FrameIndex operands.
16 //
17 //===----------------------------------------------------------------------===//
18
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/SetVector.h"
21 #include "llvm/ADT/SmallSet.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/CodeGen/MachineDominators.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineInstr.h"
26 #include "llvm/CodeGen/MachineLoopInfo.h"
27 #include "llvm/CodeGen/MachineModuleInfo.h"
28 #include "llvm/CodeGen/MachineRegisterInfo.h"
29 #include "llvm/CodeGen/Passes.h"
30 #include "llvm/CodeGen/RegisterScavenging.h"
31 #include "llvm/CodeGen/StackProtector.h"
32 #include "llvm/CodeGen/WinEHFuncInfo.h"
33 #include "llvm/IR/DiagnosticInfo.h"
34 #include "llvm/IR/InlineAsm.h"
35 #include "llvm/IR/LLVMContext.h"
36 #include "llvm/Support/CommandLine.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Support/raw_ostream.h"
39 #include "llvm/Target/TargetFrameLowering.h"
40 #include "llvm/Target/TargetInstrInfo.h"
41 #include "llvm/Target/TargetMachine.h"
42 #include "llvm/Target/TargetRegisterInfo.h"
43 #include "llvm/Target/TargetSubtargetInfo.h"
44 #include <climits>
45
46 using namespace llvm;
47
48 #define DEBUG_TYPE "pei"
49
50 typedef SmallVector<MachineBasicBlock *, 4> MBBVector;
51 static void doSpillCalleeSavedRegs(MachineFunction &MF, RegScavenger *RS,
52                                    unsigned &MinCSFrameIndex,
53                                    unsigned &MaxCXFrameIndex,
54                                    const MBBVector &SaveBlocks,
55                                    const MBBVector &RestoreBlocks);
56
57 static void doScavengeFrameVirtualRegs(MachineFunction &MF, RegScavenger *RS);
58
59 namespace {
60 class PEI : public MachineFunctionPass {
61 public:
62   static char ID;
63   explicit PEI(const TargetMachine *TM = nullptr) : MachineFunctionPass(ID) {
64     initializePEIPass(*PassRegistry::getPassRegistry());
65
66     if (TM && (!TM->usesPhysRegsForPEI())) {
67       SpillCalleeSavedRegisters = [](MachineFunction &, RegScavenger *,
68                                      unsigned &, unsigned &, const MBBVector &,
69                                      const MBBVector &) {};
70       ScavengeFrameVirtualRegs = [](MachineFunction &, RegScavenger *) {};
71     } else {
72       SpillCalleeSavedRegisters = doSpillCalleeSavedRegs;
73       ScavengeFrameVirtualRegs = doScavengeFrameVirtualRegs;
74       UsesCalleeSaves = true;
75     }
76   }
77
78   void getAnalysisUsage(AnalysisUsage &AU) const override;
79
80   MachineFunctionProperties getRequiredProperties() const override {
81     MachineFunctionProperties MFP;
82     if (UsesCalleeSaves)
83       MFP.set(MachineFunctionProperties::Property::NoVRegs);
84     return MFP;
85   }
86
87   /// runOnMachineFunction - Insert prolog/epilog code and replace abstract
88   /// frame indexes with appropriate references.
89   ///
90   bool runOnMachineFunction(MachineFunction &Fn) override;
91
92 private:
93   std::function<void(MachineFunction &MF, RegScavenger *RS,
94                      unsigned &MinCSFrameIndex, unsigned &MaxCSFrameIndex,
95                      const MBBVector &SaveBlocks,
96                      const MBBVector &RestoreBlocks)>
97       SpillCalleeSavedRegisters;
98   std::function<void(MachineFunction &MF, RegScavenger *RS)>
99       ScavengeFrameVirtualRegs;
100
101   bool UsesCalleeSaves = false;
102
103   RegScavenger *RS;
104
105   // MinCSFrameIndex, MaxCSFrameIndex - Keeps the range of callee saved
106   // stack frame indexes.
107   unsigned MinCSFrameIndex = std::numeric_limits<unsigned>::max();
108   unsigned MaxCSFrameIndex = 0;
109
110   // Save and Restore blocks of the current function. Typically there is a
111   // single save block, unless Windows EH funclets are involved.
112   MBBVector SaveBlocks;
113   MBBVector RestoreBlocks;
114
115   // Flag to control whether to use the register scavenger to resolve
116   // frame index materialization registers. Set according to
117   // TRI->requiresFrameIndexScavenging() for the current function.
118   bool FrameIndexVirtualScavenging;
119
120   // Flag to control whether the scavenger should be passed even though
121   // FrameIndexVirtualScavenging is used.
122   bool FrameIndexEliminationScavenging;
123
124   void calculateCallFrameInfo(MachineFunction &Fn);
125   void calculateSaveRestoreBlocks(MachineFunction &Fn);
126
127   void calculateFrameObjectOffsets(MachineFunction &Fn);
128   void replaceFrameIndices(MachineFunction &Fn);
129   void replaceFrameIndices(MachineBasicBlock *BB, MachineFunction &Fn,
130                            int &SPAdj);
131   void insertPrologEpilogCode(MachineFunction &Fn);
132 };
133 } // namespace
134
135 char PEI::ID = 0;
136 char &llvm::PrologEpilogCodeInserterID = PEI::ID;
137
138 static cl::opt<unsigned>
139 WarnStackSize("warn-stack-size", cl::Hidden, cl::init((unsigned)-1),
140               cl::desc("Warn for stack size bigger than the given"
141                        " number"));
142
143 INITIALIZE_TM_PASS_BEGIN(PEI, "prologepilog", "Prologue/Epilogue Insertion",
144                          false, false)
145 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
146 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
147 INITIALIZE_PASS_DEPENDENCY(StackProtector)
148 INITIALIZE_TM_PASS_END(PEI, "prologepilog",
149                        "Prologue/Epilogue Insertion & Frame Finalization",
150                        false, false)
151
152 MachineFunctionPass *
153 llvm::createPrologEpilogInserterPass(const TargetMachine *TM) {
154   return new PEI(TM);
155 }
156
157 STATISTIC(NumScavengedRegs, "Number of frame index regs scavenged");
158 STATISTIC(NumBytesStackSpace,
159           "Number of bytes used for stack in all functions");
160
161 void PEI::getAnalysisUsage(AnalysisUsage &AU) const {
162   AU.setPreservesCFG();
163   AU.addPreserved<MachineLoopInfo>();
164   AU.addPreserved<MachineDominatorTree>();
165   AU.addRequired<StackProtector>();
166   MachineFunctionPass::getAnalysisUsage(AU);
167 }
168
169
170 /// StackObjSet - A set of stack object indexes
171 typedef SmallSetVector<int, 8> StackObjSet;
172
173 /// runOnMachineFunction - Insert prolog/epilog code and replace abstract
174 /// frame indexes with appropriate references.
175 ///
176 bool PEI::runOnMachineFunction(MachineFunction &Fn) {
177   const Function* F = Fn.getFunction();
178   const TargetRegisterInfo *TRI = Fn.getSubtarget().getRegisterInfo();
179   const TargetFrameLowering *TFI = Fn.getSubtarget().getFrameLowering();
180
181   RS = TRI->requiresRegisterScavenging(Fn) ? new RegScavenger() : nullptr;
182   FrameIndexVirtualScavenging = TRI->requiresFrameIndexScavenging(Fn);
183   FrameIndexEliminationScavenging = (RS && !FrameIndexVirtualScavenging) ||
184     TRI->requiresFrameIndexReplacementScavenging(Fn);
185
186   // Calculate the MaxCallFrameSize and AdjustsStack variables for the
187   // function's frame information. Also eliminates call frame pseudo
188   // instructions.
189   calculateCallFrameInfo(Fn);
190
191   // Determine placement of CSR spill/restore code and prolog/epilog code:
192   // place all spills in the entry block, all restores in return blocks.
193   calculateSaveRestoreBlocks(Fn);
194
195   // Handle CSR spilling and restoring, for targets that need it.
196   SpillCalleeSavedRegisters(Fn, RS, MinCSFrameIndex, MaxCSFrameIndex,
197                             SaveBlocks, RestoreBlocks);
198
199   // Allow the target machine to make final modifications to the function
200   // before the frame layout is finalized.
201   TFI->processFunctionBeforeFrameFinalized(Fn, RS);
202
203   // Calculate actual frame offsets for all abstract stack objects...
204   calculateFrameObjectOffsets(Fn);
205
206   // Add prolog and epilog code to the function.  This function is required
207   // to align the stack frame as necessary for any stack variables or
208   // called functions.  Because of this, calculateCalleeSavedRegisters()
209   // must be called before this function in order to set the AdjustsStack
210   // and MaxCallFrameSize variables.
211   if (!F->hasFnAttribute(Attribute::Naked))
212     insertPrologEpilogCode(Fn);
213
214   // Replace all MO_FrameIndex operands with physical register references
215   // and actual offsets.
216   //
217   replaceFrameIndices(Fn);
218
219   // If register scavenging is needed, as we've enabled doing it as a
220   // post-pass, scavenge the virtual registers that frame index elimination
221   // inserted.
222   if (TRI->requiresRegisterScavenging(Fn) && FrameIndexVirtualScavenging) {
223       ScavengeFrameVirtualRegs(Fn, RS);
224
225       // Clear any vregs created by virtual scavenging.
226       Fn.getRegInfo().clearVirtRegs();
227   }
228
229   // Warn on stack size when we exceeds the given limit.
230   MachineFrameInfo &MFI = Fn.getFrameInfo();
231   uint64_t StackSize = MFI.getStackSize();
232   if (WarnStackSize.getNumOccurrences() > 0 && WarnStackSize < StackSize) {
233     DiagnosticInfoStackSize DiagStackSize(*F, StackSize);
234     F->getContext().diagnose(DiagStackSize);
235   }
236
237   delete RS;
238   SaveBlocks.clear();
239   RestoreBlocks.clear();
240   MFI.setSavePoint(nullptr);
241   MFI.setRestorePoint(nullptr);
242   return true;
243 }
244
245 /// Calculate the MaxCallFrameSize and AdjustsStack
246 /// variables for the function's frame information and eliminate call frame
247 /// pseudo instructions.
248 void PEI::calculateCallFrameInfo(MachineFunction &Fn) {
249   const TargetInstrInfo &TII = *Fn.getSubtarget().getInstrInfo();
250   const TargetFrameLowering *TFI = Fn.getSubtarget().getFrameLowering();
251   MachineFrameInfo &MFI = Fn.getFrameInfo();
252
253   unsigned MaxCallFrameSize = 0;
254   bool AdjustsStack = MFI.adjustsStack();
255
256   // Get the function call frame set-up and tear-down instruction opcode
257   unsigned FrameSetupOpcode = TII.getCallFrameSetupOpcode();
258   unsigned FrameDestroyOpcode = TII.getCallFrameDestroyOpcode();
259
260   // Early exit for targets which have no call frame setup/destroy pseudo
261   // instructions.
262   if (FrameSetupOpcode == ~0u && FrameDestroyOpcode == ~0u)
263     return;
264
265   std::vector<MachineBasicBlock::iterator> FrameSDOps;
266   for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB)
267     for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ++I)
268       if (TII.isFrameInstr(*I)) {
269         unsigned Size = TII.getFrameSize(*I);
270         if (Size > MaxCallFrameSize) MaxCallFrameSize = Size;
271         AdjustsStack = true;
272         FrameSDOps.push_back(I);
273       } else if (I->isInlineAsm()) {
274         // Some inline asm's need a stack frame, as indicated by operand 1.
275         unsigned ExtraInfo = I->getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
276         if (ExtraInfo & InlineAsm::Extra_IsAlignStack)
277           AdjustsStack = true;
278       }
279
280   MFI.setAdjustsStack(AdjustsStack);
281   MFI.setMaxCallFrameSize(MaxCallFrameSize);
282
283   for (std::vector<MachineBasicBlock::iterator>::iterator
284          i = FrameSDOps.begin(), e = FrameSDOps.end(); i != e; ++i) {
285     MachineBasicBlock::iterator I = *i;
286
287     // If call frames are not being included as part of the stack frame, and
288     // the target doesn't indicate otherwise, remove the call frame pseudos
289     // here. The sub/add sp instruction pairs are still inserted, but we don't
290     // need to track the SP adjustment for frame index elimination.
291     if (TFI->canSimplifyCallFramePseudos(Fn))
292       TFI->eliminateCallFramePseudoInstr(Fn, *I->getParent(), I);
293   }
294 }
295
296 /// Compute the sets of entry and return blocks for saving and restoring
297 /// callee-saved registers, and placing prolog and epilog code.
298 void PEI::calculateSaveRestoreBlocks(MachineFunction &Fn) {
299   const MachineFrameInfo &MFI = Fn.getFrameInfo();
300
301   // Even when we do not change any CSR, we still want to insert the
302   // prologue and epilogue of the function.
303   // So set the save points for those.
304
305   // Use the points found by shrink-wrapping, if any.
306   if (MFI.getSavePoint()) {
307     SaveBlocks.push_back(MFI.getSavePoint());
308     assert(MFI.getRestorePoint() && "Both restore and save must be set");
309     MachineBasicBlock *RestoreBlock = MFI.getRestorePoint();
310     // If RestoreBlock does not have any successor and is not a return block
311     // then the end point is unreachable and we do not need to insert any
312     // epilogue.
313     if (!RestoreBlock->succ_empty() || RestoreBlock->isReturnBlock())
314       RestoreBlocks.push_back(RestoreBlock);
315     return;
316   }
317
318   // Save refs to entry and return blocks.
319   SaveBlocks.push_back(&Fn.front());
320   for (MachineBasicBlock &MBB : Fn) {
321     if (MBB.isEHFuncletEntry())
322       SaveBlocks.push_back(&MBB);
323     if (MBB.isReturnBlock())
324       RestoreBlocks.push_back(&MBB);
325   }
326 }
327
328 static void assignCalleeSavedSpillSlots(MachineFunction &F,
329                                         const BitVector &SavedRegs,
330                                         unsigned &MinCSFrameIndex,
331                                         unsigned &MaxCSFrameIndex) {
332   if (SavedRegs.empty())
333     return;
334
335   const TargetRegisterInfo *RegInfo = F.getSubtarget().getRegisterInfo();
336   const MCPhysReg *CSRegs = F.getRegInfo().getCalleeSavedRegs();
337
338   std::vector<CalleeSavedInfo> CSI;
339   for (unsigned i = 0; CSRegs[i]; ++i) {
340     unsigned Reg = CSRegs[i];
341     if (SavedRegs.test(Reg))
342       CSI.push_back(CalleeSavedInfo(Reg));
343   }
344
345   const TargetFrameLowering *TFI = F.getSubtarget().getFrameLowering();
346   MachineFrameInfo &MFI = F.getFrameInfo();
347   if (!TFI->assignCalleeSavedSpillSlots(F, RegInfo, CSI)) {
348     // If target doesn't implement this, use generic code.
349
350     if (CSI.empty())
351       return; // Early exit if no callee saved registers are modified!
352
353     unsigned NumFixedSpillSlots;
354     const TargetFrameLowering::SpillSlot *FixedSpillSlots =
355         TFI->getCalleeSavedSpillSlots(NumFixedSpillSlots);
356
357     // Now that we know which registers need to be saved and restored, allocate
358     // stack slots for them.
359     for (auto &CS : CSI) {
360       unsigned Reg = CS.getReg();
361       const TargetRegisterClass *RC = RegInfo->getMinimalPhysRegClass(Reg);
362
363       int FrameIdx;
364       if (RegInfo->hasReservedSpillSlot(F, Reg, FrameIdx)) {
365         CS.setFrameIdx(FrameIdx);
366         continue;
367       }
368
369       // Check to see if this physreg must be spilled to a particular stack slot
370       // on this target.
371       const TargetFrameLowering::SpillSlot *FixedSlot = FixedSpillSlots;
372       while (FixedSlot != FixedSpillSlots + NumFixedSpillSlots &&
373              FixedSlot->Reg != Reg)
374         ++FixedSlot;
375
376       unsigned Size = RegInfo->getSpillSize(*RC);
377       if (FixedSlot == FixedSpillSlots + NumFixedSpillSlots) {
378         // Nope, just spill it anywhere convenient.
379         unsigned Align = RegInfo->getSpillAlignment(*RC);
380         unsigned StackAlign = TFI->getStackAlignment();
381
382         // We may not be able to satisfy the desired alignment specification of
383         // the TargetRegisterClass if the stack alignment is smaller. Use the
384         // min.
385         Align = std::min(Align, StackAlign);
386         FrameIdx = MFI.CreateStackObject(Size, Align, true);
387         if ((unsigned)FrameIdx < MinCSFrameIndex) MinCSFrameIndex = FrameIdx;
388         if ((unsigned)FrameIdx > MaxCSFrameIndex) MaxCSFrameIndex = FrameIdx;
389       } else {
390         // Spill it to the stack where we must.
391         FrameIdx = MFI.CreateFixedSpillStackObject(Size, FixedSlot->Offset);
392       }
393
394       CS.setFrameIdx(FrameIdx);
395     }
396   }
397
398   MFI.setCalleeSavedInfo(CSI);
399 }
400
401 /// Helper function to update the liveness information for the callee-saved
402 /// registers.
403 static void updateLiveness(MachineFunction &MF) {
404   MachineFrameInfo &MFI = MF.getFrameInfo();
405   // Visited will contain all the basic blocks that are in the region
406   // where the callee saved registers are alive:
407   // - Anything that is not Save or Restore -> LiveThrough.
408   // - Save -> LiveIn.
409   // - Restore -> LiveOut.
410   // The live-out is not attached to the block, so no need to keep
411   // Restore in this set.
412   SmallPtrSet<MachineBasicBlock *, 8> Visited;
413   SmallVector<MachineBasicBlock *, 8> WorkList;
414   MachineBasicBlock *Entry = &MF.front();
415   MachineBasicBlock *Save = MFI.getSavePoint();
416
417   if (!Save)
418     Save = Entry;
419
420   if (Entry != Save) {
421     WorkList.push_back(Entry);
422     Visited.insert(Entry);
423   }
424   Visited.insert(Save);
425
426   MachineBasicBlock *Restore = MFI.getRestorePoint();
427   if (Restore)
428     // By construction Restore cannot be visited, otherwise it
429     // means there exists a path to Restore that does not go
430     // through Save.
431     WorkList.push_back(Restore);
432
433   while (!WorkList.empty()) {
434     const MachineBasicBlock *CurBB = WorkList.pop_back_val();
435     // By construction, the region that is after the save point is
436     // dominated by the Save and post-dominated by the Restore.
437     if (CurBB == Save && Save != Restore)
438       continue;
439     // Enqueue all the successors not already visited.
440     // Those are by construction either before Save or after Restore.
441     for (MachineBasicBlock *SuccBB : CurBB->successors())
442       if (Visited.insert(SuccBB).second)
443         WorkList.push_back(SuccBB);
444   }
445
446   const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
447
448   for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
449     for (MachineBasicBlock *MBB : Visited) {
450       MCPhysReg Reg = CSI[i].getReg();
451       // Add the callee-saved register as live-in.
452       // It's killed at the spill.
453       if (!MBB->isLiveIn(Reg))
454         MBB->addLiveIn(Reg);
455     }
456   }
457 }
458
459 /// insertCSRSpillsAndRestores - Insert spill and restore code for
460 /// callee saved registers used in the function.
461 ///
462 static void insertCSRSpillsAndRestores(MachineFunction &Fn,
463                                        const MBBVector &SaveBlocks,
464                                        const MBBVector &RestoreBlocks) {
465   // Get callee saved register information.
466   MachineFrameInfo &MFI = Fn.getFrameInfo();
467   const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
468
469   MFI.setCalleeSavedInfoValid(true);
470
471   // Early exit if no callee saved registers are modified!
472   if (CSI.empty())
473     return;
474
475   const TargetInstrInfo &TII = *Fn.getSubtarget().getInstrInfo();
476   const TargetFrameLowering *TFI = Fn.getSubtarget().getFrameLowering();
477   const TargetRegisterInfo *TRI = Fn.getSubtarget().getRegisterInfo();
478   MachineBasicBlock::iterator I;
479
480   // Spill using target interface.
481   for (MachineBasicBlock *SaveBlock : SaveBlocks) {
482     I = SaveBlock->begin();
483     if (!TFI->spillCalleeSavedRegisters(*SaveBlock, I, CSI, TRI)) {
484       for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
485         // Insert the spill to the stack frame.
486         unsigned Reg = CSI[i].getReg();
487         const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
488         TII.storeRegToStackSlot(*SaveBlock, I, Reg, true, CSI[i].getFrameIdx(),
489                                 RC, TRI);
490       }
491     }
492     // Update the live-in information of all the blocks up to the save point.
493     updateLiveness(Fn);
494   }
495
496   // Restore using target interface.
497   for (MachineBasicBlock *MBB : RestoreBlocks) {
498     I = MBB->end();
499
500     // Skip over all terminator instructions, which are part of the return
501     // sequence.
502     MachineBasicBlock::iterator I2 = I;
503     while (I2 != MBB->begin() && (--I2)->isTerminator())
504       I = I2;
505
506     bool AtStart = I == MBB->begin();
507     MachineBasicBlock::iterator BeforeI = I;
508     if (!AtStart)
509       --BeforeI;
510
511     // Restore all registers immediately before the return and any
512     // terminators that precede it.
513     if (!TFI->restoreCalleeSavedRegisters(*MBB, I, CSI, TRI)) {
514       for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
515         unsigned Reg = CSI[i].getReg();
516         const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
517         TII.loadRegFromStackSlot(*MBB, I, Reg, CSI[i].getFrameIdx(), RC, TRI);
518         assert(I != MBB->begin() &&
519                "loadRegFromStackSlot didn't insert any code!");
520         // Insert in reverse order.  loadRegFromStackSlot can insert
521         // multiple instructions.
522         if (AtStart)
523           I = MBB->begin();
524         else {
525           I = BeforeI;
526           ++I;
527         }
528       }
529     }
530   }
531 }
532
533 static void doSpillCalleeSavedRegs(MachineFunction &Fn, RegScavenger *RS,
534                                    unsigned &MinCSFrameIndex,
535                                    unsigned &MaxCSFrameIndex,
536                                    const MBBVector &SaveBlocks,
537                                    const MBBVector &RestoreBlocks) {
538   const Function *F = Fn.getFunction();
539   const TargetFrameLowering *TFI = Fn.getSubtarget().getFrameLowering();
540   MinCSFrameIndex = std::numeric_limits<unsigned>::max();
541   MaxCSFrameIndex = 0;
542
543   // Determine which of the registers in the callee save list should be saved.
544   BitVector SavedRegs;
545   TFI->determineCalleeSaves(Fn, SavedRegs, RS);
546
547   // Assign stack slots for any callee-saved registers that must be spilled.
548   assignCalleeSavedSpillSlots(Fn, SavedRegs, MinCSFrameIndex, MaxCSFrameIndex);
549
550   // Add the code to save and restore the callee saved registers.
551   if (!F->hasFnAttribute(Attribute::Naked))
552     insertCSRSpillsAndRestores(Fn, SaveBlocks, RestoreBlocks);
553 }
554
555 /// AdjustStackOffset - Helper function used to adjust the stack frame offset.
556 static inline void
557 AdjustStackOffset(MachineFrameInfo &MFI, int FrameIdx,
558                   bool StackGrowsDown, int64_t &Offset,
559                   unsigned &MaxAlign, unsigned Skew) {
560   // If the stack grows down, add the object size to find the lowest address.
561   if (StackGrowsDown)
562     Offset += MFI.getObjectSize(FrameIdx);
563
564   unsigned Align = MFI.getObjectAlignment(FrameIdx);
565
566   // If the alignment of this object is greater than that of the stack, then
567   // increase the stack alignment to match.
568   MaxAlign = std::max(MaxAlign, Align);
569
570   // Adjust to alignment boundary.
571   Offset = alignTo(Offset, Align, Skew);
572
573   if (StackGrowsDown) {
574     DEBUG(dbgs() << "alloc FI(" << FrameIdx << ") at SP[" << -Offset << "]\n");
575     MFI.setObjectOffset(FrameIdx, -Offset); // Set the computed offset
576   } else {
577     DEBUG(dbgs() << "alloc FI(" << FrameIdx << ") at SP[" << Offset << "]\n");
578     MFI.setObjectOffset(FrameIdx, Offset);
579     Offset += MFI.getObjectSize(FrameIdx);
580   }
581 }
582
583 /// Compute which bytes of fixed and callee-save stack area are unused and keep
584 /// track of them in StackBytesFree.
585 ///
586 static inline void
587 computeFreeStackSlots(MachineFrameInfo &MFI, bool StackGrowsDown,
588                       unsigned MinCSFrameIndex, unsigned MaxCSFrameIndex,
589                       int64_t FixedCSEnd, BitVector &StackBytesFree) {
590   // Avoid undefined int64_t -> int conversion below in extreme case.
591   if (FixedCSEnd > std::numeric_limits<int>::max())
592     return;
593
594   StackBytesFree.resize(FixedCSEnd, true);
595
596   SmallVector<int, 16> AllocatedFrameSlots;
597   // Add fixed objects.
598   for (int i = MFI.getObjectIndexBegin(); i != 0; ++i)
599     AllocatedFrameSlots.push_back(i);
600   // Add callee-save objects.
601   for (int i = MinCSFrameIndex; i <= (int)MaxCSFrameIndex; ++i)
602     AllocatedFrameSlots.push_back(i);
603
604   for (int i : AllocatedFrameSlots) {
605     // These are converted from int64_t, but they should always fit in int
606     // because of the FixedCSEnd check above.
607     int ObjOffset = MFI.getObjectOffset(i);
608     int ObjSize = MFI.getObjectSize(i);
609     int ObjStart, ObjEnd;
610     if (StackGrowsDown) {
611       // ObjOffset is negative when StackGrowsDown is true.
612       ObjStart = -ObjOffset - ObjSize;
613       ObjEnd = -ObjOffset;
614     } else {
615       ObjStart = ObjOffset;
616       ObjEnd = ObjOffset + ObjSize;
617     }
618     // Ignore fixed holes that are in the previous stack frame.
619     if (ObjEnd > 0)
620       StackBytesFree.reset(ObjStart, ObjEnd);
621   }
622 }
623
624 /// Assign frame object to an unused portion of the stack in the fixed stack
625 /// object range.  Return true if the allocation was successful.
626 ///
627 static inline bool scavengeStackSlot(MachineFrameInfo &MFI, int FrameIdx,
628                                      bool StackGrowsDown, unsigned MaxAlign,
629                                      BitVector &StackBytesFree) {
630   if (MFI.isVariableSizedObjectIndex(FrameIdx))
631     return false;
632
633   if (StackBytesFree.none()) {
634     // clear it to speed up later scavengeStackSlot calls to
635     // StackBytesFree.none()
636     StackBytesFree.clear();
637     return false;
638   }
639
640   unsigned ObjAlign = MFI.getObjectAlignment(FrameIdx);
641   if (ObjAlign > MaxAlign)
642     return false;
643
644   int64_t ObjSize = MFI.getObjectSize(FrameIdx);
645   int FreeStart;
646   for (FreeStart = StackBytesFree.find_first(); FreeStart != -1;
647        FreeStart = StackBytesFree.find_next(FreeStart)) {
648
649     // Check that free space has suitable alignment.
650     unsigned ObjStart = StackGrowsDown ? FreeStart + ObjSize : FreeStart;
651     if (alignTo(ObjStart, ObjAlign) != ObjStart)
652       continue;
653
654     if (FreeStart + ObjSize > StackBytesFree.size())
655       return false;
656
657     bool AllBytesFree = true;
658     for (unsigned Byte = 0; Byte < ObjSize; ++Byte)
659       if (!StackBytesFree.test(FreeStart + Byte)) {
660         AllBytesFree = false;
661         break;
662       }
663     if (AllBytesFree)
664       break;
665   }
666
667   if (FreeStart == -1)
668     return false;
669
670   if (StackGrowsDown) {
671     int ObjStart = -(FreeStart + ObjSize);
672     DEBUG(dbgs() << "alloc FI(" << FrameIdx << ") scavenged at SP[" << ObjStart
673                  << "]\n");
674     MFI.setObjectOffset(FrameIdx, ObjStart);
675   } else {
676     DEBUG(dbgs() << "alloc FI(" << FrameIdx << ") scavenged at SP[" << FreeStart
677                  << "]\n");
678     MFI.setObjectOffset(FrameIdx, FreeStart);
679   }
680
681   StackBytesFree.reset(FreeStart, FreeStart + ObjSize);
682   return true;
683 }
684
685 /// AssignProtectedObjSet - Helper function to assign large stack objects (i.e.,
686 /// those required to be close to the Stack Protector) to stack offsets.
687 static void
688 AssignProtectedObjSet(const StackObjSet &UnassignedObjs,
689                       SmallSet<int, 16> &ProtectedObjs,
690                       MachineFrameInfo &MFI, bool StackGrowsDown,
691                       int64_t &Offset, unsigned &MaxAlign, unsigned Skew) {
692
693   for (StackObjSet::const_iterator I = UnassignedObjs.begin(),
694         E = UnassignedObjs.end(); I != E; ++I) {
695     int i = *I;
696     AdjustStackOffset(MFI, i, StackGrowsDown, Offset, MaxAlign, Skew);
697     ProtectedObjs.insert(i);
698   }
699 }
700
701 /// calculateFrameObjectOffsets - Calculate actual frame offsets for all of the
702 /// abstract stack objects.
703 ///
704 void PEI::calculateFrameObjectOffsets(MachineFunction &Fn) {
705   const TargetFrameLowering &TFI = *Fn.getSubtarget().getFrameLowering();
706   StackProtector *SP = &getAnalysis<StackProtector>();
707
708   bool StackGrowsDown =
709     TFI.getStackGrowthDirection() == TargetFrameLowering::StackGrowsDown;
710
711   // Loop over all of the stack objects, assigning sequential addresses...
712   MachineFrameInfo &MFI = Fn.getFrameInfo();
713
714   // Start at the beginning of the local area.
715   // The Offset is the distance from the stack top in the direction
716   // of stack growth -- so it's always nonnegative.
717   int LocalAreaOffset = TFI.getOffsetOfLocalArea();
718   if (StackGrowsDown)
719     LocalAreaOffset = -LocalAreaOffset;
720   assert(LocalAreaOffset >= 0
721          && "Local area offset should be in direction of stack growth");
722   int64_t Offset = LocalAreaOffset;
723
724   // Skew to be applied to alignment.
725   unsigned Skew = TFI.getStackAlignmentSkew(Fn);
726
727   // If there are fixed sized objects that are preallocated in the local area,
728   // non-fixed objects can't be allocated right at the start of local area.
729   // Adjust 'Offset' to point to the end of last fixed sized preallocated
730   // object.
731   for (int i = MFI.getObjectIndexBegin(); i != 0; ++i) {
732     int64_t FixedOff;
733     if (StackGrowsDown) {
734       // The maximum distance from the stack pointer is at lower address of
735       // the object -- which is given by offset. For down growing stack
736       // the offset is negative, so we negate the offset to get the distance.
737       FixedOff = -MFI.getObjectOffset(i);
738     } else {
739       // The maximum distance from the start pointer is at the upper
740       // address of the object.
741       FixedOff = MFI.getObjectOffset(i) + MFI.getObjectSize(i);
742     }
743     if (FixedOff > Offset) Offset = FixedOff;
744   }
745
746   // First assign frame offsets to stack objects that are used to spill
747   // callee saved registers.
748   if (StackGrowsDown) {
749     for (unsigned i = MinCSFrameIndex; i <= MaxCSFrameIndex; ++i) {
750       // If the stack grows down, we need to add the size to find the lowest
751       // address of the object.
752       Offset += MFI.getObjectSize(i);
753
754       unsigned Align = MFI.getObjectAlignment(i);
755       // Adjust to alignment boundary
756       Offset = alignTo(Offset, Align, Skew);
757
758       DEBUG(dbgs() << "alloc FI(" << i << ") at SP[" << -Offset << "]\n");
759       MFI.setObjectOffset(i, -Offset);        // Set the computed offset
760     }
761   } else if (MaxCSFrameIndex >= MinCSFrameIndex) {
762     // Be careful about underflow in comparisons agains MinCSFrameIndex.
763     for (unsigned i = MaxCSFrameIndex; i != MinCSFrameIndex - 1; --i) {
764       unsigned Align = MFI.getObjectAlignment(i);
765       // Adjust to alignment boundary
766       Offset = alignTo(Offset, Align, Skew);
767
768       DEBUG(dbgs() << "alloc FI(" << i << ") at SP[" << Offset << "]\n");
769       MFI.setObjectOffset(i, Offset);
770       Offset += MFI.getObjectSize(i);
771     }
772   }
773
774   // FixedCSEnd is the stack offset to the end of the fixed and callee-save
775   // stack area.
776   int64_t FixedCSEnd = Offset;
777   unsigned MaxAlign = MFI.getMaxAlignment();
778
779   // Make sure the special register scavenging spill slot is closest to the
780   // incoming stack pointer if a frame pointer is required and is closer
781   // to the incoming rather than the final stack pointer.
782   const TargetRegisterInfo *RegInfo = Fn.getSubtarget().getRegisterInfo();
783   bool EarlyScavengingSlots = (TFI.hasFP(Fn) &&
784                                TFI.isFPCloseToIncomingSP() &&
785                                RegInfo->useFPForScavengingIndex(Fn) &&
786                                !RegInfo->needsStackRealignment(Fn));
787   if (RS && EarlyScavengingSlots) {
788     SmallVector<int, 2> SFIs;
789     RS->getScavengingFrameIndices(SFIs);
790     for (SmallVectorImpl<int>::iterator I = SFIs.begin(),
791            IE = SFIs.end(); I != IE; ++I)
792       AdjustStackOffset(MFI, *I, StackGrowsDown, Offset, MaxAlign, Skew);
793   }
794
795   // FIXME: Once this is working, then enable flag will change to a target
796   // check for whether the frame is large enough to want to use virtual
797   // frame index registers. Functions which don't want/need this optimization
798   // will continue to use the existing code path.
799   if (MFI.getUseLocalStackAllocationBlock()) {
800     unsigned Align = MFI.getLocalFrameMaxAlign();
801
802     // Adjust to alignment boundary.
803     Offset = alignTo(Offset, Align, Skew);
804
805     DEBUG(dbgs() << "Local frame base offset: " << Offset << "\n");
806
807     // Resolve offsets for objects in the local block.
808     for (unsigned i = 0, e = MFI.getLocalFrameObjectCount(); i != e; ++i) {
809       std::pair<int, int64_t> Entry = MFI.getLocalFrameObjectMap(i);
810       int64_t FIOffset = (StackGrowsDown ? -Offset : Offset) + Entry.second;
811       DEBUG(dbgs() << "alloc FI(" << Entry.first << ") at SP[" <<
812             FIOffset << "]\n");
813       MFI.setObjectOffset(Entry.first, FIOffset);
814     }
815     // Allocate the local block
816     Offset += MFI.getLocalFrameSize();
817
818     MaxAlign = std::max(Align, MaxAlign);
819   }
820
821   // Retrieve the Exception Handler registration node.
822   int EHRegNodeFrameIndex = INT_MAX;
823   if (const WinEHFuncInfo *FuncInfo = Fn.getWinEHFuncInfo())
824     EHRegNodeFrameIndex = FuncInfo->EHRegNodeFrameIndex;
825
826   // Make sure that the stack protector comes before the local variables on the
827   // stack.
828   SmallSet<int, 16> ProtectedObjs;
829   if (MFI.getStackProtectorIndex() >= 0) {
830     StackObjSet LargeArrayObjs;
831     StackObjSet SmallArrayObjs;
832     StackObjSet AddrOfObjs;
833
834     AdjustStackOffset(MFI, MFI.getStackProtectorIndex(), StackGrowsDown,
835                       Offset, MaxAlign, Skew);
836
837     // Assign large stack objects first.
838     for (unsigned i = 0, e = MFI.getObjectIndexEnd(); i != e; ++i) {
839       if (MFI.isObjectPreAllocated(i) &&
840           MFI.getUseLocalStackAllocationBlock())
841         continue;
842       if (i >= MinCSFrameIndex && i <= MaxCSFrameIndex)
843         continue;
844       if (RS && RS->isScavengingFrameIndex((int)i))
845         continue;
846       if (MFI.isDeadObjectIndex(i))
847         continue;
848       if (MFI.getStackProtectorIndex() == (int)i ||
849           EHRegNodeFrameIndex == (int)i)
850         continue;
851
852       switch (SP->getSSPLayout(MFI.getObjectAllocation(i))) {
853       case StackProtector::SSPLK_None:
854         continue;
855       case StackProtector::SSPLK_SmallArray:
856         SmallArrayObjs.insert(i);
857         continue;
858       case StackProtector::SSPLK_AddrOf:
859         AddrOfObjs.insert(i);
860         continue;
861       case StackProtector::SSPLK_LargeArray:
862         LargeArrayObjs.insert(i);
863         continue;
864       }
865       llvm_unreachable("Unexpected SSPLayoutKind.");
866     }
867
868     AssignProtectedObjSet(LargeArrayObjs, ProtectedObjs, MFI, StackGrowsDown,
869                           Offset, MaxAlign, Skew);
870     AssignProtectedObjSet(SmallArrayObjs, ProtectedObjs, MFI, StackGrowsDown,
871                           Offset, MaxAlign, Skew);
872     AssignProtectedObjSet(AddrOfObjs, ProtectedObjs, MFI, StackGrowsDown,
873                           Offset, MaxAlign, Skew);
874   }
875
876   SmallVector<int, 8> ObjectsToAllocate;
877
878   // Then prepare to assign frame offsets to stack objects that are not used to
879   // spill callee saved registers.
880   for (unsigned i = 0, e = MFI.getObjectIndexEnd(); i != e; ++i) {
881     if (MFI.isObjectPreAllocated(i) && MFI.getUseLocalStackAllocationBlock())
882       continue;
883     if (i >= MinCSFrameIndex && i <= MaxCSFrameIndex)
884       continue;
885     if (RS && RS->isScavengingFrameIndex((int)i))
886       continue;
887     if (MFI.isDeadObjectIndex(i))
888       continue;
889     if (MFI.getStackProtectorIndex() == (int)i ||
890         EHRegNodeFrameIndex == (int)i)
891       continue;
892     if (ProtectedObjs.count(i))
893       continue;
894
895     // Add the objects that we need to allocate to our working set.
896     ObjectsToAllocate.push_back(i);
897   }
898
899   // Allocate the EH registration node first if one is present.
900   if (EHRegNodeFrameIndex != INT_MAX)
901     AdjustStackOffset(MFI, EHRegNodeFrameIndex, StackGrowsDown, Offset,
902                       MaxAlign, Skew);
903
904   // Give the targets a chance to order the objects the way they like it.
905   if (Fn.getTarget().getOptLevel() != CodeGenOpt::None &&
906       Fn.getTarget().Options.StackSymbolOrdering)
907     TFI.orderFrameObjects(Fn, ObjectsToAllocate);
908
909   // Keep track of which bytes in the fixed and callee-save range are used so we
910   // can use the holes when allocating later stack objects.  Only do this if
911   // stack protector isn't being used and the target requests it and we're
912   // optimizing.
913   BitVector StackBytesFree;
914   if (!ObjectsToAllocate.empty() &&
915       Fn.getTarget().getOptLevel() != CodeGenOpt::None &&
916       MFI.getStackProtectorIndex() < 0 && TFI.enableStackSlotScavenging(Fn))
917     computeFreeStackSlots(MFI, StackGrowsDown, MinCSFrameIndex, MaxCSFrameIndex,
918                           FixedCSEnd, StackBytesFree);
919
920   // Now walk the objects and actually assign base offsets to them.
921   for (auto &Object : ObjectsToAllocate)
922     if (!scavengeStackSlot(MFI, Object, StackGrowsDown, MaxAlign,
923                            StackBytesFree))
924       AdjustStackOffset(MFI, Object, StackGrowsDown, Offset, MaxAlign, Skew);
925
926   // Make sure the special register scavenging spill slot is closest to the
927   // stack pointer.
928   if (RS && !EarlyScavengingSlots) {
929     SmallVector<int, 2> SFIs;
930     RS->getScavengingFrameIndices(SFIs);
931     for (SmallVectorImpl<int>::iterator I = SFIs.begin(),
932            IE = SFIs.end(); I != IE; ++I)
933       AdjustStackOffset(MFI, *I, StackGrowsDown, Offset, MaxAlign, Skew);
934   }
935
936   if (!TFI.targetHandlesStackFrameRounding()) {
937     // If we have reserved argument space for call sites in the function
938     // immediately on entry to the current function, count it as part of the
939     // overall stack size.
940     if (MFI.adjustsStack() && TFI.hasReservedCallFrame(Fn))
941       Offset += MFI.getMaxCallFrameSize();
942
943     // Round up the size to a multiple of the alignment.  If the function has
944     // any calls or alloca's, align to the target's StackAlignment value to
945     // ensure that the callee's frame or the alloca data is suitably aligned;
946     // otherwise, for leaf functions, align to the TransientStackAlignment
947     // value.
948     unsigned StackAlign;
949     if (MFI.adjustsStack() || MFI.hasVarSizedObjects() ||
950         (RegInfo->needsStackRealignment(Fn) && MFI.getObjectIndexEnd() != 0))
951       StackAlign = TFI.getStackAlignment();
952     else
953       StackAlign = TFI.getTransientStackAlignment();
954
955     // If the frame pointer is eliminated, all frame offsets will be relative to
956     // SP not FP. Align to MaxAlign so this works.
957     StackAlign = std::max(StackAlign, MaxAlign);
958     Offset = alignTo(Offset, StackAlign, Skew);
959   }
960
961   // Update frame info to pretend that this is part of the stack...
962   int64_t StackSize = Offset - LocalAreaOffset;
963   MFI.setStackSize(StackSize);
964   NumBytesStackSpace += StackSize;
965 }
966
967 /// insertPrologEpilogCode - Scan the function for modified callee saved
968 /// registers, insert spill code for these callee saved registers, then add
969 /// prolog and epilog code to the function.
970 ///
971 void PEI::insertPrologEpilogCode(MachineFunction &Fn) {
972   const TargetFrameLowering &TFI = *Fn.getSubtarget().getFrameLowering();
973
974   // Add prologue to the function...
975   for (MachineBasicBlock *SaveBlock : SaveBlocks)
976     TFI.emitPrologue(Fn, *SaveBlock);
977
978   // Add epilogue to restore the callee-save registers in each exiting block.
979   for (MachineBasicBlock *RestoreBlock : RestoreBlocks)
980     TFI.emitEpilogue(Fn, *RestoreBlock);
981
982   for (MachineBasicBlock *SaveBlock : SaveBlocks)
983     TFI.inlineStackProbe(Fn, *SaveBlock);
984
985   // Emit additional code that is required to support segmented stacks, if
986   // we've been asked for it.  This, when linked with a runtime with support
987   // for segmented stacks (libgcc is one), will result in allocating stack
988   // space in small chunks instead of one large contiguous block.
989   if (Fn.shouldSplitStack()) {
990     for (MachineBasicBlock *SaveBlock : SaveBlocks)
991       TFI.adjustForSegmentedStacks(Fn, *SaveBlock);
992   }
993
994   // Emit additional code that is required to explicitly handle the stack in
995   // HiPE native code (if needed) when loaded in the Erlang/OTP runtime. The
996   // approach is rather similar to that of Segmented Stacks, but it uses a
997   // different conditional check and another BIF for allocating more stack
998   // space.
999   if (Fn.getFunction()->getCallingConv() == CallingConv::HiPE)
1000     for (MachineBasicBlock *SaveBlock : SaveBlocks)
1001       TFI.adjustForHiPEPrologue(Fn, *SaveBlock);
1002 }
1003
1004 /// replaceFrameIndices - Replace all MO_FrameIndex operands with physical
1005 /// register references and actual offsets.
1006 ///
1007 void PEI::replaceFrameIndices(MachineFunction &Fn) {
1008   const TargetFrameLowering &TFI = *Fn.getSubtarget().getFrameLowering();
1009   if (!TFI.needsFrameIndexResolution(Fn)) return;
1010
1011   // Store SPAdj at exit of a basic block.
1012   SmallVector<int, 8> SPState;
1013   SPState.resize(Fn.getNumBlockIDs());
1014   df_iterator_default_set<MachineBasicBlock*> Reachable;
1015
1016   // Iterate over the reachable blocks in DFS order.
1017   for (auto DFI = df_ext_begin(&Fn, Reachable), DFE = df_ext_end(&Fn, Reachable);
1018        DFI != DFE; ++DFI) {
1019     int SPAdj = 0;
1020     // Check the exit state of the DFS stack predecessor.
1021     if (DFI.getPathLength() >= 2) {
1022       MachineBasicBlock *StackPred = DFI.getPath(DFI.getPathLength() - 2);
1023       assert(Reachable.count(StackPred) &&
1024              "DFS stack predecessor is already visited.\n");
1025       SPAdj = SPState[StackPred->getNumber()];
1026     }
1027     MachineBasicBlock *BB = *DFI;
1028     replaceFrameIndices(BB, Fn, SPAdj);
1029     SPState[BB->getNumber()] = SPAdj;
1030   }
1031
1032   // Handle the unreachable blocks.
1033   for (auto &BB : Fn) {
1034     if (Reachable.count(&BB))
1035       // Already handled in DFS traversal.
1036       continue;
1037     int SPAdj = 0;
1038     replaceFrameIndices(&BB, Fn, SPAdj);
1039   }
1040 }
1041
1042 void PEI::replaceFrameIndices(MachineBasicBlock *BB, MachineFunction &Fn,
1043                               int &SPAdj) {
1044   assert(Fn.getSubtarget().getRegisterInfo() &&
1045          "getRegisterInfo() must be implemented!");
1046   const TargetInstrInfo &TII = *Fn.getSubtarget().getInstrInfo();
1047   const TargetRegisterInfo &TRI = *Fn.getSubtarget().getRegisterInfo();
1048   const TargetFrameLowering *TFI = Fn.getSubtarget().getFrameLowering();
1049
1050   if (RS && FrameIndexEliminationScavenging)
1051     RS->enterBasicBlock(*BB);
1052
1053   bool InsideCallSequence = false;
1054
1055   for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ) {
1056
1057     if (TII.isFrameInstr(*I)) {
1058       InsideCallSequence = TII.isFrameSetup(*I);
1059       SPAdj += TII.getSPAdjust(*I);
1060       I = TFI->eliminateCallFramePseudoInstr(Fn, *BB, I);
1061       continue;
1062     }
1063
1064     MachineInstr &MI = *I;
1065     bool DoIncr = true;
1066     bool DidFinishLoop = true;
1067     for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1068       if (!MI.getOperand(i).isFI())
1069         continue;
1070
1071       // Frame indices in debug values are encoded in a target independent
1072       // way with simply the frame index and offset rather than any
1073       // target-specific addressing mode.
1074       if (MI.isDebugValue()) {
1075         assert(i == 0 && "Frame indices can only appear as the first "
1076                          "operand of a DBG_VALUE machine instruction");
1077         unsigned Reg;
1078         MachineOperand &Offset = MI.getOperand(1);
1079         Offset.setImm(
1080             Offset.getImm() +
1081             TFI->getFrameIndexReference(Fn, MI.getOperand(0).getIndex(), Reg));
1082         MI.getOperand(0).ChangeToRegister(Reg, false /*isDef*/);
1083         continue;
1084       }
1085
1086       // TODO: This code should be commoned with the code for
1087       // PATCHPOINT. There's no good reason for the difference in
1088       // implementation other than historical accident.  The only
1089       // remaining difference is the unconditional use of the stack
1090       // pointer as the base register.
1091       if (MI.getOpcode() == TargetOpcode::STATEPOINT) {
1092         assert((!MI.isDebugValue() || i == 0) &&
1093                "Frame indicies can only appear as the first operand of a "
1094                "DBG_VALUE machine instruction");
1095         unsigned Reg;
1096         MachineOperand &Offset = MI.getOperand(i + 1);
1097         int refOffset = TFI->getFrameIndexReferencePreferSP(
1098             Fn, MI.getOperand(i).getIndex(), Reg, /*IgnoreSPUpdates*/ false);
1099         Offset.setImm(Offset.getImm() + refOffset);
1100         MI.getOperand(i).ChangeToRegister(Reg, false /*isDef*/);
1101         continue;
1102       }
1103
1104       // Some instructions (e.g. inline asm instructions) can have
1105       // multiple frame indices and/or cause eliminateFrameIndex
1106       // to insert more than one instruction. We need the register
1107       // scavenger to go through all of these instructions so that
1108       // it can update its register information. We keep the
1109       // iterator at the point before insertion so that we can
1110       // revisit them in full.
1111       bool AtBeginning = (I == BB->begin());
1112       if (!AtBeginning) --I;
1113
1114       // If this instruction has a FrameIndex operand, we need to
1115       // use that target machine register info object to eliminate
1116       // it.
1117       TRI.eliminateFrameIndex(MI, SPAdj, i,
1118                               FrameIndexEliminationScavenging ?  RS : nullptr);
1119
1120       // Reset the iterator if we were at the beginning of the BB.
1121       if (AtBeginning) {
1122         I = BB->begin();
1123         DoIncr = false;
1124       }
1125
1126       DidFinishLoop = false;
1127       break;
1128     }
1129
1130     // If we are looking at a call sequence, we need to keep track of
1131     // the SP adjustment made by each instruction in the sequence.
1132     // This includes both the frame setup/destroy pseudos (handled above),
1133     // as well as other instructions that have side effects w.r.t the SP.
1134     // Note that this must come after eliminateFrameIndex, because
1135     // if I itself referred to a frame index, we shouldn't count its own
1136     // adjustment.
1137     if (DidFinishLoop && InsideCallSequence)
1138       SPAdj += TII.getSPAdjust(MI);
1139
1140     if (DoIncr && I != BB->end()) ++I;
1141
1142     // Update register states.
1143     if (RS && FrameIndexEliminationScavenging && DidFinishLoop)
1144       RS->forward(MI);
1145   }
1146 }
1147
1148 /// doScavengeFrameVirtualRegs - Replace all frame index virtual registers
1149 /// with physical registers. Use the register scavenger to find an
1150 /// appropriate register to use.
1151 ///
1152 /// FIXME: Iterating over the instruction stream is unnecessary. We can simply
1153 /// iterate over the vreg use list, which at this point only contains machine
1154 /// operands for which eliminateFrameIndex need a new scratch reg.
1155 static void
1156 doScavengeFrameVirtualRegs(MachineFunction &MF, RegScavenger *RS) {
1157   // Run through the instructions and find any virtual registers.
1158   MachineRegisterInfo &MRI = MF.getRegInfo();
1159   for (MachineBasicBlock &MBB : MF) {
1160     RS->enterBasicBlock(MBB);
1161
1162     int SPAdj = 0;
1163
1164     // The instruction stream may change in the loop, so check MBB.end()
1165     // directly.
1166     for (MachineBasicBlock::iterator I = MBB.begin(); I != MBB.end(); ) {
1167       // We might end up here again with a NULL iterator if we scavenged a
1168       // register for which we inserted spill code for definition by what was
1169       // originally the first instruction in MBB.
1170       if (I == MachineBasicBlock::iterator(nullptr))
1171         I = MBB.begin();
1172
1173       const MachineInstr &MI = *I;
1174       MachineBasicBlock::iterator J = std::next(I);
1175       MachineBasicBlock::iterator P =
1176                          I == MBB.begin() ? MachineBasicBlock::iterator(nullptr)
1177                                           : std::prev(I);
1178
1179       // RS should process this instruction before we might scavenge at this
1180       // location. This is because we might be replacing a virtual register
1181       // defined by this instruction, and if so, registers killed by this
1182       // instruction are available, and defined registers are not.
1183       RS->forward(I);
1184
1185       for (const MachineOperand &MO : MI.operands()) {
1186         if (!MO.isReg())
1187           continue;
1188         unsigned Reg = MO.getReg();
1189         if (!TargetRegisterInfo::isVirtualRegister(Reg))
1190           continue;
1191
1192         // When we first encounter a new virtual register, it
1193         // must be a definition.
1194         assert(MO.isDef() && "frame index virtual missing def!");
1195         // Scavenge a new scratch register
1196         const TargetRegisterClass *RC = MRI.getRegClass(Reg);
1197         unsigned ScratchReg = RS->scavengeRegister(RC, J, SPAdj);
1198
1199         ++NumScavengedRegs;
1200
1201         // Replace this reference to the virtual register with the
1202         // scratch register.
1203         assert(ScratchReg && "Missing scratch register!");
1204         MRI.replaceRegWith(Reg, ScratchReg);
1205
1206         // Because this instruction was processed by the RS before this
1207         // register was allocated, make sure that the RS now records the
1208         // register as being used.
1209         RS->setRegUsed(ScratchReg);
1210       }
1211
1212       // If the scavenger needed to use one of its spill slots, the
1213       // spill code will have been inserted in between I and J. This is a
1214       // problem because we need the spill code before I: Move I to just
1215       // prior to J.
1216       if (I != std::prev(J)) {
1217         MBB.splice(J, &MBB, I);
1218
1219         // Before we move I, we need to prepare the RS to visit I again.
1220         // Specifically, RS will assert if it sees uses of registers that
1221         // it believes are undefined. Because we have already processed
1222         // register kills in I, when it visits I again, it will believe that
1223         // those registers are undefined. To avoid this situation, unprocess
1224         // the instruction I.
1225         assert(RS->getCurrentPosition() == I &&
1226           "The register scavenger has an unexpected position");
1227         I = P;
1228         RS->unprocess(P);
1229       } else
1230         ++I;
1231     }
1232   }
1233
1234   MF.getProperties().set(MachineFunctionProperties::Property::NoVRegs);
1235 }