Home | History | Annotate | Line # | Download | only in CodeGen
      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, MinCSFrameIndex,
    403                                         MaxCSFrameIndex)) {
    404     // If target doesn't implement this, use generic code.
    405 
    406     if (CSI.empty())
    407       return; // Early exit if no callee saved registers are modified!
    408 
    409     unsigned NumFixedSpillSlots;
    410     const TargetFrameLowering::SpillSlot *FixedSpillSlots =
    411         TFI->getCalleeSavedSpillSlots(NumFixedSpillSlots);
    412 
    413     // Now that we know which registers need to be saved and restored, allocate
    414     // stack slots for them.
    415     for (auto &CS : CSI) {
    416       // If the target has spilled this register to another register, we don't
    417       // need to allocate a stack slot.
    418       if (CS.isSpilledToReg())
    419         continue;
    420 
    421       unsigned Reg = CS.getReg();
    422       const TargetRegisterClass *RC = RegInfo->getMinimalPhysRegClass(Reg);
    423 
    424       int FrameIdx;
    425       if (RegInfo->hasReservedSpillSlot(F, Reg, FrameIdx)) {
    426         CS.setFrameIdx(FrameIdx);
    427         continue;
    428       }
    429 
    430       // Check to see if this physreg must be spilled to a particular stack slot
    431       // on this target.
    432       const TargetFrameLowering::SpillSlot *FixedSlot = FixedSpillSlots;
    433       while (FixedSlot != FixedSpillSlots + NumFixedSpillSlots &&
    434              FixedSlot->Reg != Reg)
    435         ++FixedSlot;
    436 
    437       unsigned Size = RegInfo->getSpillSize(*RC);
    438       if (FixedSlot == FixedSpillSlots + NumFixedSpillSlots) {
    439         // Nope, just spill it anywhere convenient.
    440         Align Alignment = RegInfo->getSpillAlign(*RC);
    441         // We may not be able to satisfy the desired alignment specification of
    442         // the TargetRegisterClass if the stack alignment is smaller. Use the
    443         // min.
    444         Alignment = std::min(Alignment, TFI->getStackAlign());
    445         FrameIdx = MFI.CreateStackObject(Size, Alignment, true);
    446         if ((unsigned)FrameIdx < MinCSFrameIndex) MinCSFrameIndex = FrameIdx;
    447         if ((unsigned)FrameIdx > MaxCSFrameIndex) MaxCSFrameIndex = FrameIdx;
    448       } else {
    449         // Spill it to the stack where we must.
    450         FrameIdx = MFI.CreateFixedSpillStackObject(Size, FixedSlot->Offset);
    451       }
    452 
    453       CS.setFrameIdx(FrameIdx);
    454     }
    455   }
    456 
    457   MFI.setCalleeSavedInfo(CSI);
    458 }
    459 
    460 /// Helper function to update the liveness information for the callee-saved
    461 /// registers.
    462 static void updateLiveness(MachineFunction &MF) {
    463   MachineFrameInfo &MFI = MF.getFrameInfo();
    464   // Visited will contain all the basic blocks that are in the region
    465   // where the callee saved registers are alive:
    466   // - Anything that is not Save or Restore -> LiveThrough.
    467   // - Save -> LiveIn.
    468   // - Restore -> LiveOut.
    469   // The live-out is not attached to the block, so no need to keep
    470   // Restore in this set.
    471   SmallPtrSet<MachineBasicBlock *, 8> Visited;
    472   SmallVector<MachineBasicBlock *, 8> WorkList;
    473   MachineBasicBlock *Entry = &MF.front();
    474   MachineBasicBlock *Save = MFI.getSavePoint();
    475 
    476   if (!Save)
    477     Save = Entry;
    478 
    479   if (Entry != Save) {
    480     WorkList.push_back(Entry);
    481     Visited.insert(Entry);
    482   }
    483   Visited.insert(Save);
    484 
    485   MachineBasicBlock *Restore = MFI.getRestorePoint();
    486   if (Restore)
    487     // By construction Restore cannot be visited, otherwise it
    488     // means there exists a path to Restore that does not go
    489     // through Save.
    490     WorkList.push_back(Restore);
    491 
    492   while (!WorkList.empty()) {
    493     const MachineBasicBlock *CurBB = WorkList.pop_back_val();
    494     // By construction, the region that is after the save point is
    495     // dominated by the Save and post-dominated by the Restore.
    496     if (CurBB == Save && Save != Restore)
    497       continue;
    498     // Enqueue all the successors not already visited.
    499     // Those are by construction either before Save or after Restore.
    500     for (MachineBasicBlock *SuccBB : CurBB->successors())
    501       if (Visited.insert(SuccBB).second)
    502         WorkList.push_back(SuccBB);
    503   }
    504 
    505   const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
    506 
    507   MachineRegisterInfo &MRI = MF.getRegInfo();
    508   for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
    509     for (MachineBasicBlock *MBB : Visited) {
    510       MCPhysReg Reg = CSI[i].getReg();
    511       // Add the callee-saved register as live-in.
    512       // It's killed at the spill.
    513       if (!MRI.isReserved(Reg) && !MBB->isLiveIn(Reg))
    514         MBB->addLiveIn(Reg);
    515     }
    516     // If callee-saved register is spilled to another register rather than
    517     // spilling to stack, the destination register has to be marked as live for
    518     // each MBB between the prologue and epilogue so that it is not clobbered
    519     // before it is reloaded in the epilogue. The Visited set contains all
    520     // blocks outside of the region delimited by prologue/epilogue.
    521     if (CSI[i].isSpilledToReg()) {
    522       for (MachineBasicBlock &MBB : MF) {
    523         if (Visited.count(&MBB))
    524           continue;
    525         MCPhysReg DstReg = CSI[i].getDstReg();
    526         if (!MBB.isLiveIn(DstReg))
    527           MBB.addLiveIn(DstReg);
    528       }
    529     }
    530   }
    531 
    532 }
    533 
    534 /// Insert restore code for the callee-saved registers used in the function.
    535 static void insertCSRSaves(MachineBasicBlock &SaveBlock,
    536                            ArrayRef<CalleeSavedInfo> CSI) {
    537   MachineFunction &MF = *SaveBlock.getParent();
    538   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
    539   const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering();
    540   const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
    541 
    542   MachineBasicBlock::iterator I = SaveBlock.begin();
    543   if (!TFI->spillCalleeSavedRegisters(SaveBlock, I, CSI, TRI)) {
    544     for (const CalleeSavedInfo &CS : CSI) {
    545       // Insert the spill to the stack frame.
    546       unsigned Reg = CS.getReg();
    547 
    548       if (CS.isSpilledToReg()) {
    549         BuildMI(SaveBlock, I, DebugLoc(),
    550                 TII.get(TargetOpcode::COPY), CS.getDstReg())
    551           .addReg(Reg, getKillRegState(true));
    552       } else {
    553         const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
    554         TII.storeRegToStackSlot(SaveBlock, I, Reg, true, CS.getFrameIdx(), RC,
    555                                 TRI);
    556       }
    557     }
    558   }
    559 }
    560 
    561 /// Insert restore code for the callee-saved registers used in the function.
    562 static void insertCSRRestores(MachineBasicBlock &RestoreBlock,
    563                               std::vector<CalleeSavedInfo> &CSI) {
    564   MachineFunction &MF = *RestoreBlock.getParent();
    565   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
    566   const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering();
    567   const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
    568 
    569   // Restore all registers immediately before the return and any
    570   // terminators that precede it.
    571   MachineBasicBlock::iterator I = RestoreBlock.getFirstTerminator();
    572 
    573   if (!TFI->restoreCalleeSavedRegisters(RestoreBlock, I, CSI, TRI)) {
    574     for (const CalleeSavedInfo &CI : reverse(CSI)) {
    575       unsigned Reg = CI.getReg();
    576       if (CI.isSpilledToReg()) {
    577         BuildMI(RestoreBlock, I, DebugLoc(), TII.get(TargetOpcode::COPY), Reg)
    578           .addReg(CI.getDstReg(), getKillRegState(true));
    579       } else {
    580         const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
    581         TII.loadRegFromStackSlot(RestoreBlock, I, Reg, CI.getFrameIdx(), RC, TRI);
    582         assert(I != RestoreBlock.begin() &&
    583                "loadRegFromStackSlot didn't insert any code!");
    584         // Insert in reverse order.  loadRegFromStackSlot can insert
    585         // multiple instructions.
    586       }
    587     }
    588   }
    589 }
    590 
    591 void PEI::spillCalleeSavedRegs(MachineFunction &MF) {
    592   // We can't list this requirement in getRequiredProperties because some
    593   // targets (WebAssembly) use virtual registers past this point, and the pass
    594   // pipeline is set up without giving the passes a chance to look at the
    595   // TargetMachine.
    596   // FIXME: Find a way to express this in getRequiredProperties.
    597   assert(MF.getProperties().hasProperty(
    598       MachineFunctionProperties::Property::NoVRegs));
    599 
    600   const Function &F = MF.getFunction();
    601   const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering();
    602   MachineFrameInfo &MFI = MF.getFrameInfo();
    603   MinCSFrameIndex = std::numeric_limits<unsigned>::max();
    604   MaxCSFrameIndex = 0;
    605 
    606   // Determine which of the registers in the callee save list should be saved.
    607   BitVector SavedRegs;
    608   TFI->determineCalleeSaves(MF, SavedRegs, RS);
    609 
    610   // Assign stack slots for any callee-saved registers that must be spilled.
    611   assignCalleeSavedSpillSlots(MF, SavedRegs, MinCSFrameIndex, MaxCSFrameIndex);
    612 
    613   // Add the code to save and restore the callee saved registers.
    614   if (!F.hasFnAttribute(Attribute::Naked)) {
    615     MFI.setCalleeSavedInfoValid(true);
    616 
    617     std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
    618     if (!CSI.empty()) {
    619       if (!MFI.hasCalls())
    620         NumLeafFuncWithSpills++;
    621 
    622       for (MachineBasicBlock *SaveBlock : SaveBlocks)
    623         insertCSRSaves(*SaveBlock, CSI);
    624 
    625       // Update the live-in information of all the blocks up to the save point.
    626       updateLiveness(MF);
    627 
    628       for (MachineBasicBlock *RestoreBlock : RestoreBlocks)
    629         insertCSRRestores(*RestoreBlock, CSI);
    630     }
    631   }
    632 }
    633 
    634 /// AdjustStackOffset - Helper function used to adjust the stack frame offset.
    635 static inline void AdjustStackOffset(MachineFrameInfo &MFI, int FrameIdx,
    636                                      bool StackGrowsDown, int64_t &Offset,
    637                                      Align &MaxAlign, unsigned Skew) {
    638   // If the stack grows down, add the object size to find the lowest address.
    639   if (StackGrowsDown)
    640     Offset += MFI.getObjectSize(FrameIdx);
    641 
    642   Align Alignment = MFI.getObjectAlign(FrameIdx);
    643 
    644   // If the alignment of this object is greater than that of the stack, then
    645   // increase the stack alignment to match.
    646   MaxAlign = std::max(MaxAlign, Alignment);
    647 
    648   // Adjust to alignment boundary.
    649   Offset = alignTo(Offset, Alignment, Skew);
    650 
    651   if (StackGrowsDown) {
    652     LLVM_DEBUG(dbgs() << "alloc FI(" << FrameIdx << ") at SP[" << -Offset
    653                       << "]\n");
    654     MFI.setObjectOffset(FrameIdx, -Offset); // Set the computed offset
    655   } else {
    656     LLVM_DEBUG(dbgs() << "alloc FI(" << FrameIdx << ") at SP[" << Offset
    657                       << "]\n");
    658     MFI.setObjectOffset(FrameIdx, Offset);
    659     Offset += MFI.getObjectSize(FrameIdx);
    660   }
    661 }
    662 
    663 /// Compute which bytes of fixed and callee-save stack area are unused and keep
    664 /// track of them in StackBytesFree.
    665 static inline void
    666 computeFreeStackSlots(MachineFrameInfo &MFI, bool StackGrowsDown,
    667                       unsigned MinCSFrameIndex, unsigned MaxCSFrameIndex,
    668                       int64_t FixedCSEnd, BitVector &StackBytesFree) {
    669   // Avoid undefined int64_t -> int conversion below in extreme case.
    670   if (FixedCSEnd > std::numeric_limits<int>::max())
    671     return;
    672 
    673   StackBytesFree.resize(FixedCSEnd, true);
    674 
    675   SmallVector<int, 16> AllocatedFrameSlots;
    676   // Add fixed objects.
    677   for (int i = MFI.getObjectIndexBegin(); i != 0; ++i)
    678     // StackSlot scavenging is only implemented for the default stack.
    679     if (MFI.getStackID(i) == TargetStackID::Default)
    680       AllocatedFrameSlots.push_back(i);
    681   // Add callee-save objects if there are any.
    682   if (MinCSFrameIndex <= MaxCSFrameIndex) {
    683     for (int i = MinCSFrameIndex; i <= (int)MaxCSFrameIndex; ++i)
    684       if (MFI.getStackID(i) == TargetStackID::Default)
    685         AllocatedFrameSlots.push_back(i);
    686   }
    687 
    688   for (int i : AllocatedFrameSlots) {
    689     // These are converted from int64_t, but they should always fit in int
    690     // because of the FixedCSEnd check above.
    691     int ObjOffset = MFI.getObjectOffset(i);
    692     int ObjSize = MFI.getObjectSize(i);
    693     int ObjStart, ObjEnd;
    694     if (StackGrowsDown) {
    695       // ObjOffset is negative when StackGrowsDown is true.
    696       ObjStart = -ObjOffset - ObjSize;
    697       ObjEnd = -ObjOffset;
    698     } else {
    699       ObjStart = ObjOffset;
    700       ObjEnd = ObjOffset + ObjSize;
    701     }
    702     // Ignore fixed holes that are in the previous stack frame.
    703     if (ObjEnd > 0)
    704       StackBytesFree.reset(ObjStart, ObjEnd);
    705   }
    706 }
    707 
    708 /// Assign frame object to an unused portion of the stack in the fixed stack
    709 /// object range.  Return true if the allocation was successful.
    710 static inline bool scavengeStackSlot(MachineFrameInfo &MFI, int FrameIdx,
    711                                      bool StackGrowsDown, Align MaxAlign,
    712                                      BitVector &StackBytesFree) {
    713   if (MFI.isVariableSizedObjectIndex(FrameIdx))
    714     return false;
    715 
    716   if (StackBytesFree.none()) {
    717     // clear it to speed up later scavengeStackSlot calls to
    718     // StackBytesFree.none()
    719     StackBytesFree.clear();
    720     return false;
    721   }
    722 
    723   Align ObjAlign = MFI.getObjectAlign(FrameIdx);
    724   if (ObjAlign > MaxAlign)
    725     return false;
    726 
    727   int64_t ObjSize = MFI.getObjectSize(FrameIdx);
    728   int FreeStart;
    729   for (FreeStart = StackBytesFree.find_first(); FreeStart != -1;
    730        FreeStart = StackBytesFree.find_next(FreeStart)) {
    731 
    732     // Check that free space has suitable alignment.
    733     unsigned ObjStart = StackGrowsDown ? FreeStart + ObjSize : FreeStart;
    734     if (alignTo(ObjStart, ObjAlign) != ObjStart)
    735       continue;
    736 
    737     if (FreeStart + ObjSize > StackBytesFree.size())
    738       return false;
    739 
    740     bool AllBytesFree = true;
    741     for (unsigned Byte = 0; Byte < ObjSize; ++Byte)
    742       if (!StackBytesFree.test(FreeStart + Byte)) {
    743         AllBytesFree = false;
    744         break;
    745       }
    746     if (AllBytesFree)
    747       break;
    748   }
    749 
    750   if (FreeStart == -1)
    751     return false;
    752 
    753   if (StackGrowsDown) {
    754     int ObjStart = -(FreeStart + ObjSize);
    755     LLVM_DEBUG(dbgs() << "alloc FI(" << FrameIdx << ") scavenged at SP["
    756                       << ObjStart << "]\n");
    757     MFI.setObjectOffset(FrameIdx, ObjStart);
    758   } else {
    759     LLVM_DEBUG(dbgs() << "alloc FI(" << FrameIdx << ") scavenged at SP["
    760                       << FreeStart << "]\n");
    761     MFI.setObjectOffset(FrameIdx, FreeStart);
    762   }
    763 
    764   StackBytesFree.reset(FreeStart, FreeStart + ObjSize);
    765   return true;
    766 }
    767 
    768 /// AssignProtectedObjSet - Helper function to assign large stack objects (i.e.,
    769 /// those required to be close to the Stack Protector) to stack offsets.
    770 static void AssignProtectedObjSet(const StackObjSet &UnassignedObjs,
    771                                   SmallSet<int, 16> &ProtectedObjs,
    772                                   MachineFrameInfo &MFI, bool StackGrowsDown,
    773                                   int64_t &Offset, Align &MaxAlign,
    774                                   unsigned Skew) {
    775 
    776   for (int i : UnassignedObjs) {
    777     AdjustStackOffset(MFI, i, StackGrowsDown, Offset, MaxAlign, Skew);
    778     ProtectedObjs.insert(i);
    779   }
    780 }
    781 
    782 /// calculateFrameObjectOffsets - Calculate actual frame offsets for all of the
    783 /// abstract stack objects.
    784 void PEI::calculateFrameObjectOffsets(MachineFunction &MF) {
    785   const TargetFrameLowering &TFI = *MF.getSubtarget().getFrameLowering();
    786 
    787   bool StackGrowsDown =
    788     TFI.getStackGrowthDirection() == TargetFrameLowering::StackGrowsDown;
    789 
    790   // Loop over all of the stack objects, assigning sequential addresses...
    791   MachineFrameInfo &MFI = MF.getFrameInfo();
    792 
    793   // Start at the beginning of the local area.
    794   // The Offset is the distance from the stack top in the direction
    795   // of stack growth -- so it's always nonnegative.
    796   int LocalAreaOffset = TFI.getOffsetOfLocalArea();
    797   if (StackGrowsDown)
    798     LocalAreaOffset = -LocalAreaOffset;
    799   assert(LocalAreaOffset >= 0
    800          && "Local area offset should be in direction of stack growth");
    801   int64_t Offset = LocalAreaOffset;
    802 
    803   // Skew to be applied to alignment.
    804   unsigned Skew = TFI.getStackAlignmentSkew(MF);
    805 
    806 #ifdef EXPENSIVE_CHECKS
    807   for (unsigned i = 0, e = MFI.getObjectIndexEnd(); i != e; ++i)
    808     if (!MFI.isDeadObjectIndex(i) &&
    809         MFI.getStackID(i) == TargetStackID::Default)
    810       assert(MFI.getObjectAlign(i) <= MFI.getMaxAlign() &&
    811              "MaxAlignment is invalid");
    812 #endif
    813 
    814   // If there are fixed sized objects that are preallocated in the local area,
    815   // non-fixed objects can't be allocated right at the start of local area.
    816   // Adjust 'Offset' to point to the end of last fixed sized preallocated
    817   // object.
    818   for (int i = MFI.getObjectIndexBegin(); i != 0; ++i) {
    819     if (MFI.getStackID(i) !=
    820         TargetStackID::Default) // Only allocate objects on the default stack.
    821       continue;
    822 
    823     int64_t FixedOff;
    824     if (StackGrowsDown) {
    825       // The maximum distance from the stack pointer is at lower address of
    826       // the object -- which is given by offset. For down growing stack
    827       // the offset is negative, so we negate the offset to get the distance.
    828       FixedOff = -MFI.getObjectOffset(i);
    829     } else {
    830       // The maximum distance from the start pointer is at the upper
    831       // address of the object.
    832       FixedOff = MFI.getObjectOffset(i) + MFI.getObjectSize(i);
    833     }
    834     if (FixedOff > Offset) Offset = FixedOff;
    835   }
    836 
    837   // First assign frame offsets to stack objects that are used to spill
    838   // callee saved registers.
    839   if (StackGrowsDown && MaxCSFrameIndex >= MinCSFrameIndex) {
    840     for (unsigned i = MinCSFrameIndex; i <= MaxCSFrameIndex; ++i) {
    841       if (MFI.getStackID(i) !=
    842           TargetStackID::Default) // Only allocate objects on the default stack.
    843         continue;
    844 
    845       // If the stack grows down, we need to add the size to find the lowest
    846       // address of the object.
    847       Offset += MFI.getObjectSize(i);
    848 
    849       // Adjust to alignment boundary
    850       Offset = alignTo(Offset, MFI.getObjectAlign(i), Skew);
    851 
    852       LLVM_DEBUG(dbgs() << "alloc FI(" << i << ") at SP[" << -Offset << "]\n");
    853       MFI.setObjectOffset(i, -Offset);        // Set the computed offset
    854     }
    855   } else if (MaxCSFrameIndex >= MinCSFrameIndex) {
    856     // Be careful about underflow in comparisons agains MinCSFrameIndex.
    857     for (unsigned i = MaxCSFrameIndex; i != MinCSFrameIndex - 1; --i) {
    858       if (MFI.getStackID(i) !=
    859           TargetStackID::Default) // Only allocate objects on the default stack.
    860         continue;
    861 
    862       if (MFI.isDeadObjectIndex(i))
    863         continue;
    864 
    865       // Adjust to alignment boundary
    866       Offset = alignTo(Offset, MFI.getObjectAlign(i), Skew);
    867 
    868       LLVM_DEBUG(dbgs() << "alloc FI(" << i << ") at SP[" << Offset << "]\n");
    869       MFI.setObjectOffset(i, Offset);
    870       Offset += MFI.getObjectSize(i);
    871     }
    872   }
    873 
    874   // FixedCSEnd is the stack offset to the end of the fixed and callee-save
    875   // stack area.
    876   int64_t FixedCSEnd = Offset;
    877   Align MaxAlign = MFI.getMaxAlign();
    878 
    879   // Make sure the special register scavenging spill slot is closest to the
    880   // incoming stack pointer if a frame pointer is required and is closer
    881   // to the incoming rather than the final stack pointer.
    882   const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
    883   bool EarlyScavengingSlots = (TFI.hasFP(MF) && TFI.isFPCloseToIncomingSP() &&
    884                                RegInfo->useFPForScavengingIndex(MF) &&
    885                                !RegInfo->hasStackRealignment(MF));
    886   if (RS && EarlyScavengingSlots) {
    887     SmallVector<int, 2> SFIs;
    888     RS->getScavengingFrameIndices(SFIs);
    889     for (int SFI : SFIs)
    890       AdjustStackOffset(MFI, SFI, StackGrowsDown, Offset, MaxAlign, Skew);
    891   }
    892 
    893   // FIXME: Once this is working, then enable flag will change to a target
    894   // check for whether the frame is large enough to want to use virtual
    895   // frame index registers. Functions which don't want/need this optimization
    896   // will continue to use the existing code path.
    897   if (MFI.getUseLocalStackAllocationBlock()) {
    898     Align Alignment = MFI.getLocalFrameMaxAlign();
    899 
    900     // Adjust to alignment boundary.
    901     Offset = alignTo(Offset, Alignment, Skew);
    902 
    903     LLVM_DEBUG(dbgs() << "Local frame base offset: " << Offset << "\n");
    904 
    905     // Resolve offsets for objects in the local block.
    906     for (unsigned i = 0, e = MFI.getLocalFrameObjectCount(); i != e; ++i) {
    907       std::pair<int, int64_t> Entry = MFI.getLocalFrameObjectMap(i);
    908       int64_t FIOffset = (StackGrowsDown ? -Offset : Offset) + Entry.second;
    909       LLVM_DEBUG(dbgs() << "alloc FI(" << Entry.first << ") at SP[" << FIOffset
    910                         << "]\n");
    911       MFI.setObjectOffset(Entry.first, FIOffset);
    912     }
    913     // Allocate the local block
    914     Offset += MFI.getLocalFrameSize();
    915 
    916     MaxAlign = std::max(Alignment, MaxAlign);
    917   }
    918 
    919   // Retrieve the Exception Handler registration node.
    920   int EHRegNodeFrameIndex = std::numeric_limits<int>::max();
    921   if (const WinEHFuncInfo *FuncInfo = MF.getWinEHFuncInfo())
    922     EHRegNodeFrameIndex = FuncInfo->EHRegNodeFrameIndex;
    923 
    924   // Make sure that the stack protector comes before the local variables on the
    925   // stack.
    926   SmallSet<int, 16> ProtectedObjs;
    927   if (MFI.hasStackProtectorIndex()) {
    928     int StackProtectorFI = MFI.getStackProtectorIndex();
    929     StackObjSet LargeArrayObjs;
    930     StackObjSet SmallArrayObjs;
    931     StackObjSet AddrOfObjs;
    932 
    933     // If we need a stack protector, we need to make sure that
    934     // LocalStackSlotPass didn't already allocate a slot for it.
    935     // If we are told to use the LocalStackAllocationBlock, the stack protector
    936     // is expected to be already pre-allocated.
    937     if (!MFI.getUseLocalStackAllocationBlock())
    938       AdjustStackOffset(MFI, StackProtectorFI, StackGrowsDown, Offset, MaxAlign,
    939                         Skew);
    940     else if (!MFI.isObjectPreAllocated(MFI.getStackProtectorIndex()))
    941       llvm_unreachable(
    942           "Stack protector not pre-allocated by LocalStackSlotPass.");
    943 
    944     // Assign large stack objects first.
    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 (StackProtectorFI == (int)i || EHRegNodeFrameIndex == (int)i)
    955         continue;
    956       if (MFI.getStackID(i) !=
    957           TargetStackID::Default) // Only allocate objects on the default stack.
    958         continue;
    959 
    960       switch (MFI.getObjectSSPLayout(i)) {
    961       case MachineFrameInfo::SSPLK_None:
    962         continue;
    963       case MachineFrameInfo::SSPLK_SmallArray:
    964         SmallArrayObjs.insert(i);
    965         continue;
    966       case MachineFrameInfo::SSPLK_AddrOf:
    967         AddrOfObjs.insert(i);
    968         continue;
    969       case MachineFrameInfo::SSPLK_LargeArray:
    970         LargeArrayObjs.insert(i);
    971         continue;
    972       }
    973       llvm_unreachable("Unexpected SSPLayoutKind.");
    974     }
    975 
    976     // We expect **all** the protected stack objects to be pre-allocated by
    977     // LocalStackSlotPass. If it turns out that PEI still has to allocate some
    978     // of them, we may end up messing up the expected order of the objects.
    979     if (MFI.getUseLocalStackAllocationBlock() &&
    980         !(LargeArrayObjs.empty() && SmallArrayObjs.empty() &&
    981           AddrOfObjs.empty()))
    982       llvm_unreachable("Found protected stack objects not pre-allocated by "
    983                        "LocalStackSlotPass.");
    984 
    985     AssignProtectedObjSet(LargeArrayObjs, ProtectedObjs, MFI, StackGrowsDown,
    986                           Offset, MaxAlign, Skew);
    987     AssignProtectedObjSet(SmallArrayObjs, ProtectedObjs, MFI, StackGrowsDown,
    988                           Offset, MaxAlign, Skew);
    989     AssignProtectedObjSet(AddrOfObjs, ProtectedObjs, MFI, StackGrowsDown,
    990                           Offset, MaxAlign, Skew);
    991   }
    992 
    993   SmallVector<int, 8> ObjectsToAllocate;
    994 
    995   // Then prepare to assign frame offsets to stack objects that are not used to
    996   // spill callee saved registers.
    997   for (unsigned i = 0, e = MFI.getObjectIndexEnd(); i != e; ++i) {
    998     if (MFI.isObjectPreAllocated(i) && MFI.getUseLocalStackAllocationBlock())
    999       continue;
   1000     if (i >= MinCSFrameIndex && i <= MaxCSFrameIndex)
   1001       continue;
   1002     if (RS && RS->isScavengingFrameIndex((int)i))
   1003       continue;
   1004     if (MFI.isDeadObjectIndex(i))
   1005       continue;
   1006     if (MFI.getStackProtectorIndex() == (int)i || EHRegNodeFrameIndex == (int)i)
   1007       continue;
   1008     if (ProtectedObjs.count(i))
   1009       continue;
   1010     if (MFI.getStackID(i) !=
   1011         TargetStackID::Default) // Only allocate objects on the default stack.
   1012       continue;
   1013 
   1014     // Add the objects that we need to allocate to our working set.
   1015     ObjectsToAllocate.push_back(i);
   1016   }
   1017 
   1018   // Allocate the EH registration node first if one is present.
   1019   if (EHRegNodeFrameIndex != std::numeric_limits<int>::max())
   1020     AdjustStackOffset(MFI, EHRegNodeFrameIndex, StackGrowsDown, Offset,
   1021                       MaxAlign, Skew);
   1022 
   1023   // Give the targets a chance to order the objects the way they like it.
   1024   if (MF.getTarget().getOptLevel() != CodeGenOpt::None &&
   1025       MF.getTarget().Options.StackSymbolOrdering)
   1026     TFI.orderFrameObjects(MF, ObjectsToAllocate);
   1027 
   1028   // Keep track of which bytes in the fixed and callee-save range are used so we
   1029   // can use the holes when allocating later stack objects.  Only do this if
   1030   // stack protector isn't being used and the target requests it and we're
   1031   // optimizing.
   1032   BitVector StackBytesFree;
   1033   if (!ObjectsToAllocate.empty() &&
   1034       MF.getTarget().getOptLevel() != CodeGenOpt::None &&
   1035       MFI.getStackProtectorIndex() < 0 && TFI.enableStackSlotScavenging(MF))
   1036     computeFreeStackSlots(MFI, StackGrowsDown, MinCSFrameIndex, MaxCSFrameIndex,
   1037                           FixedCSEnd, StackBytesFree);
   1038 
   1039   // Now walk the objects and actually assign base offsets to them.
   1040   for (auto &Object : ObjectsToAllocate)
   1041     if (!scavengeStackSlot(MFI, Object, StackGrowsDown, MaxAlign,
   1042                            StackBytesFree))
   1043       AdjustStackOffset(MFI, Object, StackGrowsDown, Offset, MaxAlign, Skew);
   1044 
   1045   // Make sure the special register scavenging spill slot is closest to the
   1046   // stack pointer.
   1047   if (RS && !EarlyScavengingSlots) {
   1048     SmallVector<int, 2> SFIs;
   1049     RS->getScavengingFrameIndices(SFIs);
   1050     for (int SFI : SFIs)
   1051       AdjustStackOffset(MFI, SFI, StackGrowsDown, Offset, MaxAlign, Skew);
   1052   }
   1053 
   1054   if (!TFI.targetHandlesStackFrameRounding()) {
   1055     // If we have reserved argument space for call sites in the function
   1056     // immediately on entry to the current function, count it as part of the
   1057     // overall stack size.
   1058     if (MFI.adjustsStack() && TFI.hasReservedCallFrame(MF))
   1059       Offset += MFI.getMaxCallFrameSize();
   1060 
   1061     // Round up the size to a multiple of the alignment.  If the function has
   1062     // any calls or alloca's, align to the target's StackAlignment value to
   1063     // ensure that the callee's frame or the alloca data is suitably aligned;
   1064     // otherwise, for leaf functions, align to the TransientStackAlignment
   1065     // value.
   1066     Align StackAlign;
   1067     if (MFI.adjustsStack() || MFI.hasVarSizedObjects() ||
   1068         (RegInfo->hasStackRealignment(MF) && MFI.getObjectIndexEnd() != 0))
   1069       StackAlign = TFI.getStackAlign();
   1070     else
   1071       StackAlign = TFI.getTransientStackAlign();
   1072 
   1073     // If the frame pointer is eliminated, all frame offsets will be relative to
   1074     // SP not FP. Align to MaxAlign so this works.
   1075     StackAlign = std::max(StackAlign, MaxAlign);
   1076     int64_t OffsetBeforeAlignment = Offset;
   1077     Offset = alignTo(Offset, StackAlign, Skew);
   1078 
   1079     // If we have increased the offset to fulfill the alignment constrants,
   1080     // then the scavenging spill slots may become harder to reach from the
   1081     // stack pointer, float them so they stay close.
   1082     if (StackGrowsDown && OffsetBeforeAlignment != Offset && RS &&
   1083         !EarlyScavengingSlots) {
   1084       SmallVector<int, 2> SFIs;
   1085       RS->getScavengingFrameIndices(SFIs);
   1086       LLVM_DEBUG(if (!SFIs.empty()) llvm::dbgs()
   1087                      << "Adjusting emergency spill slots!\n";);
   1088       int64_t Delta = Offset - OffsetBeforeAlignment;
   1089       for (int SFI : SFIs) {
   1090         LLVM_DEBUG(llvm::dbgs()
   1091                        << "Adjusting offset of emergency spill slot #" << SFI
   1092                        << " from " << MFI.getObjectOffset(SFI););
   1093         MFI.setObjectOffset(SFI, MFI.getObjectOffset(SFI) - Delta);
   1094         LLVM_DEBUG(llvm::dbgs() << " to " << MFI.getObjectOffset(SFI) << "\n";);
   1095       }
   1096     }
   1097   }
   1098 
   1099   // Update frame info to pretend that this is part of the stack...
   1100   int64_t StackSize = Offset - LocalAreaOffset;
   1101   MFI.setStackSize(StackSize);
   1102   NumBytesStackSpace += StackSize;
   1103 }
   1104 
   1105 /// insertPrologEpilogCode - Scan the function for modified callee saved
   1106 /// registers, insert spill code for these callee saved registers, then add
   1107 /// prolog and epilog code to the function.
   1108 void PEI::insertPrologEpilogCode(MachineFunction &MF) {
   1109   const TargetFrameLowering &TFI = *MF.getSubtarget().getFrameLowering();
   1110 
   1111   // Add prologue to the function...
   1112   for (MachineBasicBlock *SaveBlock : SaveBlocks)
   1113     TFI.emitPrologue(MF, *SaveBlock);
   1114 
   1115   // Add epilogue to restore the callee-save registers in each exiting block.
   1116   for (MachineBasicBlock *RestoreBlock : RestoreBlocks)
   1117     TFI.emitEpilogue(MF, *RestoreBlock);
   1118 
   1119   for (MachineBasicBlock *SaveBlock : SaveBlocks)
   1120     TFI.inlineStackProbe(MF, *SaveBlock);
   1121 
   1122   // Emit additional code that is required to support segmented stacks, if
   1123   // we've been asked for it.  This, when linked with a runtime with support
   1124   // for segmented stacks (libgcc is one), will result in allocating stack
   1125   // space in small chunks instead of one large contiguous block.
   1126   if (MF.shouldSplitStack()) {
   1127     for (MachineBasicBlock *SaveBlock : SaveBlocks)
   1128       TFI.adjustForSegmentedStacks(MF, *SaveBlock);
   1129     // Record that there are split-stack functions, so we will emit a
   1130     // special section to tell the linker.
   1131     MF.getMMI().setHasSplitStack(true);
   1132   } else
   1133     MF.getMMI().setHasNosplitStack(true);
   1134 
   1135   // Emit additional code that is required to explicitly handle the stack in
   1136   // HiPE native code (if needed) when loaded in the Erlang/OTP runtime. The
   1137   // approach is rather similar to that of Segmented Stacks, but it uses a
   1138   // different conditional check and another BIF for allocating more stack
   1139   // space.
   1140   if (MF.getFunction().getCallingConv() == CallingConv::HiPE)
   1141     for (MachineBasicBlock *SaveBlock : SaveBlocks)
   1142       TFI.adjustForHiPEPrologue(MF, *SaveBlock);
   1143 }
   1144 
   1145 /// replaceFrameIndices - Replace all MO_FrameIndex operands with physical
   1146 /// register references and actual offsets.
   1147 void PEI::replaceFrameIndices(MachineFunction &MF) {
   1148   const auto &ST = MF.getSubtarget();
   1149   const TargetFrameLowering &TFI = *ST.getFrameLowering();
   1150   if (!TFI.needsFrameIndexResolution(MF))
   1151     return;
   1152 
   1153   const TargetRegisterInfo *TRI = ST.getRegisterInfo();
   1154 
   1155   // Allow the target to determine this after knowing the frame size.
   1156   FrameIndexEliminationScavenging = (RS && !FrameIndexVirtualScavenging) ||
   1157     TRI->requiresFrameIndexReplacementScavenging(MF);
   1158 
   1159   // Store SPAdj at exit of a basic block.
   1160   SmallVector<int, 8> SPState;
   1161   SPState.resize(MF.getNumBlockIDs());
   1162   df_iterator_default_set<MachineBasicBlock*> Reachable;
   1163 
   1164   // Iterate over the reachable blocks in DFS order.
   1165   for (auto DFI = df_ext_begin(&MF, Reachable), DFE = df_ext_end(&MF, Reachable);
   1166        DFI != DFE; ++DFI) {
   1167     int SPAdj = 0;
   1168     // Check the exit state of the DFS stack predecessor.
   1169     if (DFI.getPathLength() >= 2) {
   1170       MachineBasicBlock *StackPred = DFI.getPath(DFI.getPathLength() - 2);
   1171       assert(Reachable.count(StackPred) &&
   1172              "DFS stack predecessor is already visited.\n");
   1173       SPAdj = SPState[StackPred->getNumber()];
   1174     }
   1175     MachineBasicBlock *BB = *DFI;
   1176     replaceFrameIndices(BB, MF, SPAdj);
   1177     SPState[BB->getNumber()] = SPAdj;
   1178   }
   1179 
   1180   // Handle the unreachable blocks.
   1181   for (auto &BB : MF) {
   1182     if (Reachable.count(&BB))
   1183       // Already handled in DFS traversal.
   1184       continue;
   1185     int SPAdj = 0;
   1186     replaceFrameIndices(&BB, MF, SPAdj);
   1187   }
   1188 }
   1189 
   1190 void PEI::replaceFrameIndices(MachineBasicBlock *BB, MachineFunction &MF,
   1191                               int &SPAdj) {
   1192   assert(MF.getSubtarget().getRegisterInfo() &&
   1193          "getRegisterInfo() must be implemented!");
   1194   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
   1195   const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
   1196   const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering();
   1197 
   1198   if (RS && FrameIndexEliminationScavenging)
   1199     RS->enterBasicBlock(*BB);
   1200 
   1201   bool InsideCallSequence = false;
   1202 
   1203   for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ) {
   1204     if (TII.isFrameInstr(*I)) {
   1205       InsideCallSequence = TII.isFrameSetup(*I);
   1206       SPAdj += TII.getSPAdjust(*I);
   1207       I = TFI->eliminateCallFramePseudoInstr(MF, *BB, I);
   1208       continue;
   1209     }
   1210 
   1211     MachineInstr &MI = *I;
   1212     bool DoIncr = true;
   1213     bool DidFinishLoop = true;
   1214     for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
   1215       if (!MI.getOperand(i).isFI())
   1216         continue;
   1217 
   1218       // Frame indices in debug values are encoded in a target independent
   1219       // way with simply the frame index and offset rather than any
   1220       // target-specific addressing mode.
   1221       if (MI.isDebugValue()) {
   1222         MachineOperand &Op = MI.getOperand(i);
   1223         assert(
   1224             MI.isDebugOperand(&Op) &&
   1225             "Frame indices can only appear as a debug operand in a DBG_VALUE*"
   1226             " machine instruction");
   1227         Register Reg;
   1228         unsigned FrameIdx = Op.getIndex();
   1229         unsigned Size = MF.getFrameInfo().getObjectSize(FrameIdx);
   1230 
   1231         StackOffset Offset =
   1232             TFI->getFrameIndexReference(MF, FrameIdx, Reg);
   1233         Op.ChangeToRegister(Reg, false /*isDef*/);
   1234         Op.setIsDebug();
   1235 
   1236         const DIExpression *DIExpr = MI.getDebugExpression();
   1237 
   1238         // If we have a direct DBG_VALUE, and its location expression isn't
   1239         // currently complex, then adding an offset will morph it into a
   1240         // complex location that is interpreted as being a memory address.
   1241         // This changes a pointer-valued variable to dereference that pointer,
   1242         // which is incorrect. Fix by adding DW_OP_stack_value.
   1243 
   1244         if (MI.isNonListDebugValue()) {
   1245           unsigned PrependFlags = DIExpression::ApplyOffset;
   1246           if (!MI.isIndirectDebugValue() && !DIExpr->isComplex())
   1247             PrependFlags |= DIExpression::StackValue;
   1248 
   1249           // If we have DBG_VALUE that is indirect and has a Implicit location
   1250           // expression need to insert a deref before prepending a Memory
   1251           // location expression. Also after doing this we change the DBG_VALUE
   1252           // to be direct.
   1253           if (MI.isIndirectDebugValue() && DIExpr->isImplicit()) {
   1254             SmallVector<uint64_t, 2> Ops = {dwarf::DW_OP_deref_size, Size};
   1255             bool WithStackValue = true;
   1256             DIExpr = DIExpression::prependOpcodes(DIExpr, Ops, WithStackValue);
   1257             // Make the DBG_VALUE direct.
   1258             MI.getDebugOffset().ChangeToRegister(0, false);
   1259           }
   1260           DIExpr = TRI.prependOffsetExpression(DIExpr, PrependFlags, Offset);
   1261         } else {
   1262           // The debug operand at DebugOpIndex was a frame index at offset
   1263           // `Offset`; now the operand has been replaced with the frame
   1264           // register, we must add Offset with `register x, plus Offset`.
   1265           unsigned DebugOpIndex = MI.getDebugOperandIndex(&Op);
   1266           SmallVector<uint64_t, 3> Ops;
   1267           TRI.getOffsetOpcodes(Offset, Ops);
   1268           DIExpr = DIExpression::appendOpsToArg(DIExpr, Ops, DebugOpIndex);
   1269         }
   1270         MI.getDebugExpressionOp().setMetadata(DIExpr);
   1271         continue;
   1272       }
   1273 
   1274       // TODO: This code should be commoned with the code for
   1275       // PATCHPOINT. There's no good reason for the difference in
   1276       // implementation other than historical accident.  The only
   1277       // remaining difference is the unconditional use of the stack
   1278       // pointer as the base register.
   1279       if (MI.getOpcode() == TargetOpcode::STATEPOINT) {
   1280         assert((!MI.isDebugValue() || i == 0) &&
   1281                "Frame indicies can only appear as the first operand of a "
   1282                "DBG_VALUE machine instruction");
   1283         Register Reg;
   1284         MachineOperand &Offset = MI.getOperand(i + 1);
   1285         StackOffset refOffset = TFI->getFrameIndexReferencePreferSP(
   1286             MF, MI.getOperand(i).getIndex(), Reg, /*IgnoreSPUpdates*/ false);
   1287         assert(!refOffset.getScalable() &&
   1288                "Frame offsets with a scalable component are not supported");
   1289         Offset.setImm(Offset.getImm() + refOffset.getFixed() + SPAdj);
   1290         MI.getOperand(i).ChangeToRegister(Reg, false /*isDef*/);
   1291         continue;
   1292       }
   1293 
   1294       // Some instructions (e.g. inline asm instructions) can have
   1295       // multiple frame indices and/or cause eliminateFrameIndex
   1296       // to insert more than one instruction. We need the register
   1297       // scavenger to go through all of these instructions so that
   1298       // it can update its register information. We keep the
   1299       // iterator at the point before insertion so that we can
   1300       // revisit them in full.
   1301       bool AtBeginning = (I == BB->begin());
   1302       if (!AtBeginning) --I;
   1303 
   1304       // If this instruction has a FrameIndex operand, we need to
   1305       // use that target machine register info object to eliminate
   1306       // it.
   1307       TRI.eliminateFrameIndex(MI, SPAdj, i,
   1308                               FrameIndexEliminationScavenging ?  RS : nullptr);
   1309 
   1310       // Reset the iterator if we were at the beginning of the BB.
   1311       if (AtBeginning) {
   1312         I = BB->begin();
   1313         DoIncr = false;
   1314       }
   1315 
   1316       DidFinishLoop = false;
   1317       break;
   1318     }
   1319 
   1320     // If we are looking at a call sequence, we need to keep track of
   1321     // the SP adjustment made by each instruction in the sequence.
   1322     // This includes both the frame setup/destroy pseudos (handled above),
   1323     // as well as other instructions that have side effects w.r.t the SP.
   1324     // Note that this must come after eliminateFrameIndex, because
   1325     // if I itself referred to a frame index, we shouldn't count its own
   1326     // adjustment.
   1327     if (DidFinishLoop && InsideCallSequence)
   1328       SPAdj += TII.getSPAdjust(MI);
   1329 
   1330     if (DoIncr && I != BB->end()) ++I;
   1331 
   1332     // Update register states.
   1333     if (RS && FrameIndexEliminationScavenging && DidFinishLoop)
   1334       RS->forward(MI);
   1335   }
   1336 }
   1337