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