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