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