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/STLExtras.h"
21#include "llvm/ADT/SetVector.h"
22#include "llvm/ADT/SmallPtrSet.h"
23#include "llvm/ADT/SmallSet.h"
24#include "llvm/ADT/SmallVector.h"
25#include "llvm/ADT/Statistic.h"
26#include "llvm/Analysis/OptimizationRemarkEmitter.h"
27#include "llvm/CodeGen/MachineBasicBlock.h"
28#include "llvm/CodeGen/MachineDominators.h"
29#include "llvm/CodeGen/MachineFrameInfo.h"
30#include "llvm/CodeGen/MachineFunction.h"
31#include "llvm/CodeGen/MachineFunctionPass.h"
32#include "llvm/CodeGen/MachineInstr.h"
33#include "llvm/CodeGen/MachineModuleInfo.h"
34#include "llvm/CodeGen/MachineOperand.h"
35#include "llvm/CodeGen/MachineOptimizationRemarkEmitter.h"
36#include "llvm/CodeGen/MachineRegisterInfo.h"
37#include "llvm/CodeGen/PEI.h"
38#include "llvm/CodeGen/RegisterScavenging.h"
39#include "llvm/CodeGen/TargetFrameLowering.h"
40#include "llvm/CodeGen/TargetInstrInfo.h"
41#include "llvm/CodeGen/TargetOpcodes.h"
42#include "llvm/CodeGen/TargetRegisterInfo.h"
43#include "llvm/CodeGen/TargetSubtargetInfo.h"
44#include "llvm/CodeGen/WinEHFuncInfo.h"
45#include "llvm/IR/Attributes.h"
46#include "llvm/IR/CallingConv.h"
47#include "llvm/IR/DebugInfoMetadata.h"
48#include "llvm/IR/DiagnosticInfo.h"
49#include "llvm/IR/Function.h"
50#include "llvm/IR/LLVMContext.h"
51#include "llvm/InitializePasses.h"
52#include "llvm/Pass.h"
53#include "llvm/Support/CodeGen.h"
54#include "llvm/Support/Debug.h"
55#include "llvm/Support/ErrorHandling.h"
56#include "llvm/Support/FormatVariadic.h"
57#include "llvm/Support/raw_ostream.h"
58#include "llvm/Target/TargetMachine.h"
59#include "llvm/Target/TargetOptions.h"
60#include <algorithm>
61#include <cassert>
62#include <cstdint>
63#include <limits>
64#include <utility>
65#include <vector>
66
67using namespace llvm;
68
69#define DEBUG_TYPE "prolog-epilog"
70
71using MBBVector = SmallVector<MachineBasicBlock *, 4>;
72
73STATISTIC(NumLeafFuncWithSpills, "Number of leaf functions with CSRs");
74STATISTIC(NumFuncSeen, "Number of functions seen in PEI");
75
76
77namespace {
78
79class PEIImpl {
80 RegScavenger *RS = nullptr;
81
82 // Save and Restore blocks of the current function. Typically there is a
83 // single save block, unless Windows EH funclets are involved.
84 MBBVector SaveBlocks;
85 MBBVector RestoreBlocks;
86
87 // Flag to control whether to use the register scavenger to resolve
88 // frame index materialization registers. Set according to
89 // TRI->requiresFrameIndexScavenging() for the current function.
90 bool FrameIndexVirtualScavenging = false;
91
92 // Flag to control whether the scavenger should be passed even though
93 // FrameIndexVirtualScavenging is used.
94 bool FrameIndexEliminationScavenging = false;
95
96 // Emit remarks.
97 MachineOptimizationRemarkEmitter *ORE = nullptr;
98
99 void calculateCallFrameInfo(MachineFunction &MF);
100 void calculateSaveRestoreBlocks(MachineFunction &MF);
101 void spillCalleeSavedRegs(MachineFunction &MF);
102
103 void calculateFrameObjectOffsets(MachineFunction &MF);
104 void replaceFrameIndices(MachineFunction &MF);
105 void replaceFrameIndices(MachineBasicBlock *BB, MachineFunction &MF,
106 int &SPAdj);
107 // Frame indices in debug values are encoded in a target independent
108 // way with simply the frame index and offset rather than any
109 // target-specific addressing mode.
110 bool replaceFrameIndexDebugInstr(MachineFunction &MF, MachineInstr &MI,
111 unsigned OpIdx, int SPAdj = 0);
112 // Does same as replaceFrameIndices but using the backward MIR walk and
113 // backward register scavenger walk.
114 void replaceFrameIndicesBackward(MachineFunction &MF);
115 void replaceFrameIndicesBackward(MachineBasicBlock *BB, MachineFunction &MF,
116 int &SPAdj);
117
118 void insertPrologEpilogCode(MachineFunction &MF);
119 void insertZeroCallUsedRegs(MachineFunction &MF);
120
121public:
122 PEIImpl(MachineOptimizationRemarkEmitter *ORE) : ORE(ORE) {}
123 bool run(MachineFunction &MF);
124};
125
126class PEILegacy : public MachineFunctionPass {
127public:
128 static char ID;
129
130 PEILegacy() : MachineFunctionPass(ID) {}
131
132 void getAnalysisUsage(AnalysisUsage &AU) const override;
133
134 /// runOnMachineFunction - Insert prolog/epilog code and replace abstract
135 /// frame indexes with appropriate references.
136 bool runOnMachineFunction(MachineFunction &MF) override;
137};
138
139} // end anonymous namespace
140
141char PEILegacy::ID = 0;
142
143char &llvm::PrologEpilogCodeInserterID = PEILegacy::ID;
144
145INITIALIZE_PASS_BEGIN(PEILegacy, DEBUG_TYPE, "Prologue/Epilogue Insertion",
146 false, false)
147INITIALIZE_PASS_DEPENDENCY(MachineLoopInfoWrapperPass)
148INITIALIZE_PASS_DEPENDENCY(MachineDominatorTreeWrapperPass)
149INITIALIZE_PASS_DEPENDENCY(MachineOptimizationRemarkEmitterPass)
150INITIALIZE_PASS_END(PEILegacy, DEBUG_TYPE,
151 "Prologue/Epilogue Insertion & Frame Finalization", false,
152 false)
153
154MachineFunctionPass *llvm::createPrologEpilogInserterPass() {
155 return new PEILegacy();
156}
157
158STATISTIC(NumBytesStackSpace,
159 "Number of bytes used for stack in all functions");
160
161void PEILegacy::getAnalysisUsage(AnalysisUsage &AU) const {
162 AU.setPreservesCFG();
163 AU.addRequired<MachineOptimizationRemarkEmitterPass>();
164 MachineFunctionPass::getAnalysisUsage(AU);
165}
166
167/// StackObjSet - A set of stack object indexes
168using StackObjSet = SmallSetVector<int, 8>;
169
170using SavedDbgValuesMap =
171 SmallDenseMap<MachineBasicBlock *, SmallVector<MachineInstr *, 4>, 4>;
172
173/// Stash DBG_VALUEs that describe parameters and which are placed at the start
174/// of the block. Later on, after the prologue code has been emitted, the
175/// stashed DBG_VALUEs will be reinserted at the start of the block.
176static void stashEntryDbgValues(MachineBasicBlock &MBB,
177 SavedDbgValuesMap &EntryDbgValues) {
178 SmallVector<const MachineInstr *, 4> FrameIndexValues;
179
180 for (auto &MI : MBB) {
181 if (!MI.isDebugInstr())
182 break;
183 if (!MI.isDebugValue() || !MI.getDebugVariable()->isParameter())
184 continue;
185 if (any_of(Range: MI.debug_operands(),
186 P: [](const MachineOperand &MO) { return MO.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(Elt: &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(Other: 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(Range&: FrameIndexValues, P: Overlaps))
202 EntryDbgValues[&MBB].push_back(Elt: &MI);
203 }
204
205 // Remove stashed debug values from the block.
206 if (auto It = EntryDbgValues.find(Val: &MBB); It != EntryDbgValues.end())
207 for (auto *MI : It->second)
208 MI->removeFromParent();
209}
210
211bool PEIImpl::run(MachineFunction &MF) {
212 NumFuncSeen++;
213 const Function &F = MF.getFunction();
214 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
215 const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering();
216
217 RS = TRI->requiresRegisterScavenging(MF) ? new RegScavenger() : nullptr;
218 FrameIndexVirtualScavenging = TRI->requiresFrameIndexScavenging(MF);
219
220 // Spill frame pointer and/or base pointer registers if they are clobbered.
221 // It is placed before call frame instruction elimination so it will not mess
222 // with stack arguments.
223 TFI->spillFPBP(MF);
224
225 // Calculate the MaxCallFrameSize value for the function's frame
226 // information. Also eliminates call frame pseudo instructions.
227 calculateCallFrameInfo(MF);
228
229 // Determine placement of CSR spill/restore code and prolog/epilog code:
230 // place all spills in the entry block, all restores in return blocks.
231 calculateSaveRestoreBlocks(MF);
232
233 // Stash away DBG_VALUEs that should not be moved by insertion of prolog code.
234 SavedDbgValuesMap EntryDbgValues;
235 for (MachineBasicBlock *SaveBlock : SaveBlocks)
236 stashEntryDbgValues(MBB&: *SaveBlock, EntryDbgValues);
237
238 // Handle CSR spilling and restoring, for targets that need it.
239 if (MF.getTarget().usesPhysRegsForValues())
240 spillCalleeSavedRegs(MF);
241
242 // Allow the target machine to make final modifications to the function
243 // before the frame layout is finalized.
244 TFI->processFunctionBeforeFrameFinalized(MF, RS);
245
246 // Calculate actual frame offsets for all abstract stack objects...
247 calculateFrameObjectOffsets(MF);
248
249 // Add prolog and epilog code to the function. This function is required
250 // to align the stack frame as necessary for any stack variables or
251 // called functions. Because of this, calculateCalleeSavedRegisters()
252 // must be called before this function in order to set the AdjustsStack
253 // and MaxCallFrameSize variables.
254 if (!F.hasFnAttribute(Kind: Attribute::Naked))
255 insertPrologEpilogCode(MF);
256
257 // Reinsert stashed debug values at the start of the entry blocks.
258 for (auto &I : EntryDbgValues)
259 I.first->insert(I: I.first->begin(), S: I.second.begin(), E: I.second.end());
260
261 // Allow the target machine to make final modifications to the function
262 // before the frame layout is finalized.
263 TFI->processFunctionBeforeFrameIndicesReplaced(MF, RS);
264
265 // Replace all MO_FrameIndex operands with physical register references
266 // and actual offsets.
267 if (TFI->needsFrameIndexResolution(MF)) {
268 // Allow the target to determine this after knowing the frame size.
269 FrameIndexEliminationScavenging =
270 (RS && !FrameIndexVirtualScavenging) ||
271 TRI->requiresFrameIndexReplacementScavenging(MF);
272
273 if (TRI->eliminateFrameIndicesBackwards())
274 replaceFrameIndicesBackward(MF);
275 else
276 replaceFrameIndices(MF);
277 }
278
279 // If register scavenging is needed, as we've enabled doing it as a
280 // post-pass, scavenge the virtual registers that frame index elimination
281 // inserted.
282 if (TRI->requiresRegisterScavenging(MF) && FrameIndexVirtualScavenging)
283 scavengeFrameVirtualRegs(MF, RS&: *RS);
284
285 insertZeroCallUsedRegs(MF);
286
287 // Warn on stack size when we exceeds the given limit.
288 MachineFrameInfo &MFI = MF.getFrameInfo();
289 uint64_t StackSize = MFI.getStackSize();
290
291 uint64_t Threshold = TFI->getStackThreshold();
292 if (MF.getFunction().hasFnAttribute(Kind: "warn-stack-size")) {
293 bool Failed = MF.getFunction()
294 .getFnAttribute(Kind: "warn-stack-size")
295 .getValueAsString()
296 .getAsInteger(Radix: 10, Result&: Threshold);
297 // Verifier should have caught this.
298 assert(!Failed && "Invalid warn-stack-size fn attr value");
299 (void)Failed;
300 }
301 uint64_t UnsafeStackSize = MFI.getUnsafeStackSize();
302 if (MF.getFunction().hasFnAttribute(Kind: Attribute::SafeStack))
303 StackSize += UnsafeStackSize;
304
305 if (StackSize > Threshold) {
306 DiagnosticInfoStackSize DiagStackSize(F, StackSize, Threshold, DS_Warning);
307 F.getContext().diagnose(DI: DiagStackSize);
308 int64_t SpillSize = 0;
309 for (int Idx = MFI.getObjectIndexBegin(), End = MFI.getObjectIndexEnd();
310 Idx != End; ++Idx) {
311 if (MFI.isSpillSlotObjectIndex(ObjectIdx: Idx))
312 SpillSize += MFI.getObjectSize(ObjectIdx: Idx);
313 }
314
315 [[maybe_unused]] float SpillPct =
316 static_cast<float>(SpillSize) / static_cast<float>(StackSize);
317 LLVM_DEBUG(
318 dbgs() << formatv("{0}/{1} ({3:P}) spills, {2}/{1} ({4:P}) variables",
319 SpillSize, StackSize, StackSize - SpillSize, SpillPct,
320 1.0f - SpillPct));
321 if (UnsafeStackSize != 0) {
322 LLVM_DEBUG(dbgs() << formatv(", {0}/{2} ({1:P}) unsafe stack",
323 UnsafeStackSize,
324 static_cast<float>(UnsafeStackSize) /
325 static_cast<float>(StackSize),
326 StackSize));
327 }
328 LLVM_DEBUG(dbgs() << "\n");
329 }
330
331 ORE->emit(RemarkBuilder: [&]() {
332 return MachineOptimizationRemarkAnalysis(DEBUG_TYPE, "StackSize",
333 MF.getFunction().getSubprogram(),
334 &MF.front())
335 << ore::NV("NumStackBytes", StackSize)
336 << " stack bytes in function '"
337 << ore::NV("Function", MF.getFunction().getName()) << "'";
338 });
339
340 // Emit any remarks implemented for the target, based on final frame layout.
341 TFI->emitRemarks(MF, ORE);
342
343 delete RS;
344 SaveBlocks.clear();
345 RestoreBlocks.clear();
346 MFI.clearSavePoints();
347 MFI.clearRestorePoints();
348 return true;
349}
350
351/// runOnMachineFunction - Insert prolog/epilog code and replace abstract
352/// frame indexes with appropriate references.
353bool PEILegacy::runOnMachineFunction(MachineFunction &MF) {
354 MachineOptimizationRemarkEmitter *ORE =
355 &getAnalysis<MachineOptimizationRemarkEmitterPass>().getORE();
356 return PEIImpl(ORE).run(MF);
357}
358
359PreservedAnalyses
360PrologEpilogInserterPass::run(MachineFunction &MF,
361 MachineFunctionAnalysisManager &MFAM) {
362 MachineOptimizationRemarkEmitter &ORE =
363 MFAM.getResult<MachineOptimizationRemarkEmitterAnalysis>(IR&: MF);
364 if (!PEIImpl(&ORE).run(MF))
365 return PreservedAnalyses::all();
366
367 return getMachineFunctionPassPreservedAnalyses().preserveSet<CFGAnalyses>();
368}
369
370/// Calculate the MaxCallFrameSize variable for the function's frame
371/// information and eliminate call frame pseudo instructions.
372void PEIImpl::calculateCallFrameInfo(MachineFunction &MF) {
373 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
374 const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering();
375 MachineFrameInfo &MFI = MF.getFrameInfo();
376
377 // Get the function call frame set-up and tear-down instruction opcode
378 unsigned FrameSetupOpcode = TII.getCallFrameSetupOpcode();
379 unsigned FrameDestroyOpcode = TII.getCallFrameDestroyOpcode();
380
381 // Early exit for targets which have no call frame setup/destroy pseudo
382 // instructions.
383 if (FrameSetupOpcode == ~0u && FrameDestroyOpcode == ~0u)
384 return;
385
386 // (Re-)Compute the MaxCallFrameSize.
387 [[maybe_unused]] uint64_t MaxCFSIn =
388 MFI.isMaxCallFrameSizeComputed() ? MFI.getMaxCallFrameSize() : UINT64_MAX;
389 std::vector<MachineBasicBlock::iterator> FrameSDOps;
390 MFI.computeMaxCallFrameSize(MF, FrameSDOps: &FrameSDOps);
391 assert(MFI.getMaxCallFrameSize() <= MaxCFSIn &&
392 "Recomputing MaxCFS gave a larger value.");
393 assert((FrameSDOps.empty() || MF.getFrameInfo().adjustsStack()) &&
394 "AdjustsStack not set in presence of a frame pseudo instruction.");
395
396 if (TFI->canSimplifyCallFramePseudos(MF)) {
397 // If call frames are not being included as part of the stack frame, and
398 // the target doesn't indicate otherwise, remove the call frame pseudos
399 // here. The sub/add sp instruction pairs are still inserted, but we don't
400 // need to track the SP adjustment for frame index elimination.
401 for (MachineBasicBlock::iterator I : FrameSDOps)
402 TFI->eliminateCallFramePseudoInstr(MF, MBB&: *I->getParent(), MI: I);
403
404 // We can't track the call frame size after call frame pseudos have been
405 // eliminated. Set it to zero everywhere to keep MachineVerifier happy.
406 for (MachineBasicBlock &MBB : MF)
407 MBB.setCallFrameSize(0);
408 }
409}
410
411/// Compute the sets of entry and return blocks for saving and restoring
412/// callee-saved registers, and placing prolog and epilog code.
413void PEIImpl::calculateSaveRestoreBlocks(MachineFunction &MF) {
414 const MachineFrameInfo &MFI = MF.getFrameInfo();
415 // Even when we do not change any CSR, we still want to insert the
416 // prologue and epilogue of the function.
417 // So set the save points for those.
418
419 // Use the points found by shrink-wrapping, if any.
420 if (!MFI.getSavePoints().empty()) {
421 assert(MFI.getSavePoints().size() == 1 &&
422 "Multiple save points are not yet supported!");
423 const auto &SavePoint = *MFI.getSavePoints().begin();
424 SaveBlocks.push_back(Elt: SavePoint.first);
425 assert(MFI.getRestorePoints().size() == 1 &&
426 "Multiple restore points are not yet supported!");
427 const auto &RestorePoint = *MFI.getRestorePoints().begin();
428 MachineBasicBlock *RestoreBlock = RestorePoint.first;
429 // If RestoreBlock does not have any successor and is not a return block
430 // then the end point is unreachable and we do not need to insert any
431 // epilogue.
432 if (!RestoreBlock->succ_empty() || RestoreBlock->isReturnBlock())
433 RestoreBlocks.push_back(Elt: RestoreBlock);
434 return;
435 }
436
437 // Save refs to entry and return blocks.
438 SaveBlocks.push_back(Elt: &MF.front());
439 for (MachineBasicBlock &MBB : MF) {
440 if (MBB.isEHFuncletEntry())
441 SaveBlocks.push_back(Elt: &MBB);
442 if (MBB.isReturnBlock())
443 RestoreBlocks.push_back(Elt: &MBB);
444 }
445}
446
447static void assignCalleeSavedSpillSlots(MachineFunction &F,
448 const BitVector &SavedRegs) {
449 if (SavedRegs.empty())
450 return;
451
452 const TargetRegisterInfo *RegInfo = F.getSubtarget().getRegisterInfo();
453 const MCPhysReg *CSRegs = F.getRegInfo().getCalleeSavedRegs();
454 BitVector CSMask(SavedRegs.size());
455
456 for (unsigned i = 0; CSRegs[i]; ++i)
457 CSMask.set(CSRegs[i]);
458
459 std::vector<CalleeSavedInfo> CSI;
460 for (unsigned i = 0; CSRegs[i]; ++i) {
461 unsigned Reg = CSRegs[i];
462 if (SavedRegs.test(Idx: Reg)) {
463 bool SavedSuper = false;
464 for (const MCPhysReg &SuperReg : RegInfo->superregs(Reg)) {
465 // Some backends set all aliases for some registers as saved, such as
466 // Mips's $fp, so they appear in SavedRegs but not CSRegs.
467 if (SavedRegs.test(Idx: SuperReg) && CSMask.test(Idx: SuperReg)) {
468 SavedSuper = true;
469 break;
470 }
471 }
472
473 if (!SavedSuper)
474 CSI.push_back(x: CalleeSavedInfo(Reg));
475 }
476 }
477
478 const TargetFrameLowering *TFI = F.getSubtarget().getFrameLowering();
479 MachineFrameInfo &MFI = F.getFrameInfo();
480 if (!TFI->assignCalleeSavedSpillSlots(MF&: F, TRI: RegInfo, CSI)) {
481 // If target doesn't implement this, use generic code.
482
483 if (CSI.empty())
484 return; // Early exit if no callee saved registers are modified!
485
486 unsigned NumFixedSpillSlots;
487 const TargetFrameLowering::SpillSlot *FixedSpillSlots =
488 TFI->getCalleeSavedSpillSlots(NumEntries&: NumFixedSpillSlots);
489
490 // Now that we know which registers need to be saved and restored, allocate
491 // stack slots for them.
492 for (auto &CS : CSI) {
493 // If the target has spilled this register to another register or already
494 // handled it , we don't need to allocate a stack slot.
495 if (CS.isSpilledToReg())
496 continue;
497
498 MCRegister Reg = CS.getReg();
499 const TargetRegisterClass *RC = RegInfo->getMinimalPhysRegClass(Reg);
500
501 int FrameIdx;
502 if (RegInfo->hasReservedSpillSlot(MF: F, Reg, FrameIdx)) {
503 CS.setFrameIdx(FrameIdx);
504 continue;
505 }
506
507 // Check to see if this physreg must be spilled to a particular stack slot
508 // on this target.
509 const TargetFrameLowering::SpillSlot *FixedSlot = FixedSpillSlots;
510 while (FixedSlot != FixedSpillSlots + NumFixedSpillSlots &&
511 FixedSlot->Reg != Reg)
512 ++FixedSlot;
513
514 unsigned Size = RegInfo->getSpillSize(RC: *RC);
515 if (FixedSlot == FixedSpillSlots + NumFixedSpillSlots) {
516 // Nope, just spill it anywhere convenient.
517 Align Alignment = RegInfo->getSpillAlign(RC: *RC);
518 // We may not be able to satisfy the desired alignment specification of
519 // the TargetRegisterClass if the stack alignment is smaller. Use the
520 // min.
521 Alignment = std::min(a: Alignment, b: TFI->getStackAlign());
522 FrameIdx = MFI.CreateStackObject(Size, Alignment, isSpillSlot: true, Alloca: nullptr,
523 ID: RegInfo->getSpillStackID(RC: *RC));
524 MFI.setIsCalleeSavedObjectIndex(ObjectIdx: FrameIdx, IsCalleeSaved: true);
525 } else {
526 // Spill it to the stack where we must.
527 FrameIdx = MFI.CreateFixedSpillStackObject(Size, SPOffset: FixedSlot->Offset);
528 }
529
530 CS.setFrameIdx(FrameIdx);
531 }
532 }
533
534 MFI.setCalleeSavedInfo(CSI);
535}
536
537/// Helper function to update the liveness information for the callee-saved
538/// registers.
539static void updateLiveness(MachineFunction &MF) {
540 MachineFrameInfo &MFI = MF.getFrameInfo();
541 // Visited will contain all the basic blocks that are in the region
542 // where the callee saved registers are alive:
543 // - Anything that is not Save or Restore -> LiveThrough.
544 // - Save -> LiveIn.
545 // - Restore -> LiveOut.
546 // The live-out is not attached to the block, so no need to keep
547 // Restore in this set.
548 SmallPtrSet<MachineBasicBlock *, 8> Visited;
549 SmallVector<MachineBasicBlock *, 8> WorkList;
550 MachineBasicBlock *Entry = &MF.front();
551
552 assert(MFI.getSavePoints().size() < 2 &&
553 "Multiple save points not yet supported!");
554 MachineBasicBlock *Save = MFI.getSavePoints().empty()
555 ? nullptr
556 : (*MFI.getSavePoints().begin()).first;
557
558 if (!Save)
559 Save = Entry;
560
561 if (Entry != Save) {
562 WorkList.push_back(Elt: Entry);
563 Visited.insert(Ptr: Entry);
564 }
565 Visited.insert(Ptr: Save);
566
567 assert(MFI.getRestorePoints().size() < 2 &&
568 "Multiple restore points not yet supported!");
569 MachineBasicBlock *Restore = MFI.getRestorePoints().empty()
570 ? nullptr
571 : (*MFI.getRestorePoints().begin()).first;
572 if (Restore)
573 // By construction Restore cannot be visited, otherwise it
574 // means there exists a path to Restore that does not go
575 // through Save.
576 WorkList.push_back(Elt: Restore);
577
578 while (!WorkList.empty()) {
579 const MachineBasicBlock *CurBB = WorkList.pop_back_val();
580 // By construction, the region that is after the save point is
581 // dominated by the Save and post-dominated by the Restore.
582 if (CurBB == Save && Save != Restore)
583 continue;
584 // Enqueue all the successors not already visited.
585 // Those are by construction either before Save or after Restore.
586 for (MachineBasicBlock *SuccBB : CurBB->successors())
587 if (Visited.insert(Ptr: SuccBB).second)
588 WorkList.push_back(Elt: SuccBB);
589 }
590
591 const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
592
593 MachineRegisterInfo &MRI = MF.getRegInfo();
594 for (const CalleeSavedInfo &I : CSI) {
595 for (MachineBasicBlock *MBB : Visited) {
596 MCRegister Reg = I.getReg();
597 // Add the callee-saved register as live-in.
598 // It's killed at the spill.
599 if (!MRI.isReserved(PhysReg: Reg) && !MBB->isLiveIn(Reg))
600 MBB->addLiveIn(PhysReg: Reg);
601 }
602 // If callee-saved register is spilled to another register rather than
603 // spilling to stack, the destination register has to be marked as live for
604 // each MBB between the prologue and epilogue so that it is not clobbered
605 // before it is reloaded in the epilogue. The Visited set contains all
606 // blocks outside of the region delimited by prologue/epilogue.
607 if (I.isSpilledToReg()) {
608 for (MachineBasicBlock &MBB : MF) {
609 if (Visited.count(Ptr: &MBB))
610 continue;
611 MCRegister DstReg = I.getDstReg();
612 if (!MBB.isLiveIn(Reg: DstReg))
613 MBB.addLiveIn(PhysReg: DstReg);
614 }
615 }
616 }
617}
618
619/// Insert spill code for the callee-saved registers used in the function.
620static void insertCSRSaves(MachineBasicBlock &SaveBlock,
621 ArrayRef<CalleeSavedInfo> CSI) {
622 MachineFunction &MF = *SaveBlock.getParent();
623 const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
624 const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering();
625 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
626
627 MachineBasicBlock::iterator I = SaveBlock.begin();
628 if (!TFI->spillCalleeSavedRegisters(MBB&: SaveBlock, MI: I, CSI, TRI)) {
629 for (const CalleeSavedInfo &CS : CSI) {
630 TFI->spillCalleeSavedRegister(SaveBlock, MI: I, CS, TII, TRI);
631 }
632 }
633}
634
635/// Insert restore code for the callee-saved registers used in the function.
636static void insertCSRRestores(MachineBasicBlock &RestoreBlock,
637 std::vector<CalleeSavedInfo> &CSI) {
638 MachineFunction &MF = *RestoreBlock.getParent();
639 const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
640 const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering();
641 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
642
643 // Restore all registers immediately before the return and any
644 // terminators that precede it.
645 MachineBasicBlock::iterator I = RestoreBlock.getFirstTerminator();
646
647 if (!TFI->restoreCalleeSavedRegisters(MBB&: RestoreBlock, MI: I, CSI, TRI)) {
648 for (const CalleeSavedInfo &CI : reverse(C&: CSI)) {
649 TFI->restoreCalleeSavedRegister(MBB&: RestoreBlock, MI: I, CS: CI, TII, TRI);
650 }
651 }
652}
653
654void PEIImpl::spillCalleeSavedRegs(MachineFunction &MF) {
655 // We can't list this requirement in getRequiredProperties because some
656 // targets (WebAssembly) use virtual registers past this point, and the pass
657 // pipeline is set up without giving the passes a chance to look at the
658 // TargetMachine.
659 // FIXME: Find a way to express this in getRequiredProperties.
660 assert(MF.getProperties().hasNoVRegs());
661
662 const Function &F = MF.getFunction();
663 const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering();
664 MachineFrameInfo &MFI = MF.getFrameInfo();
665
666 // Determine which of the registers in the callee save list should be saved.
667 BitVector SavedRegs;
668 TFI->determineCalleeSaves(MF, SavedRegs, RS);
669
670 // Assign stack slots for any callee-saved registers that must be spilled.
671 assignCalleeSavedSpillSlots(F&: MF, SavedRegs);
672
673 // Add the code to save and restore the callee saved registers.
674 if (!F.hasFnAttribute(Kind: Attribute::Naked)) {
675 MFI.setCalleeSavedInfoValid(true);
676
677 std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
678
679 // Fill SavePoints and RestorePoints with CalleeSavedRegisters
680 if (!MFI.getSavePoints().empty()) {
681 SaveRestorePoints SaveRestorePts;
682 for (const auto &SavePoint : MFI.getSavePoints())
683 SaveRestorePts.insert(KV: {SavePoint.first, CSI});
684 MFI.setSavePoints(std::move(SaveRestorePts));
685
686 SaveRestorePts.clear();
687 for (const auto &RestorePoint : MFI.getRestorePoints())
688 SaveRestorePts.insert(KV: {RestorePoint.first, CSI});
689 MFI.setRestorePoints(std::move(SaveRestorePts));
690 }
691
692 if (!CSI.empty()) {
693 if (!MFI.hasCalls())
694 NumLeafFuncWithSpills++;
695
696 for (MachineBasicBlock *SaveBlock : SaveBlocks)
697 insertCSRSaves(SaveBlock&: *SaveBlock, CSI);
698
699 // Update the live-in information of all the blocks up to the save point.
700 updateLiveness(MF);
701
702 for (MachineBasicBlock *RestoreBlock : RestoreBlocks)
703 insertCSRRestores(RestoreBlock&: *RestoreBlock, CSI);
704 }
705 }
706}
707
708/// AdjustStackOffset - Helper function used to adjust the stack frame offset.
709static inline void AdjustStackOffset(MachineFrameInfo &MFI, int FrameIdx,
710 bool StackGrowsDown, int64_t &Offset,
711 Align &MaxAlign) {
712 // If the stack grows down, add the object size to find the lowest address.
713 if (StackGrowsDown)
714 Offset += MFI.getObjectSize(ObjectIdx: FrameIdx);
715
716 Align Alignment = MFI.getObjectAlign(ObjectIdx: FrameIdx);
717
718 // If the alignment of this object is greater than that of the stack, then
719 // increase the stack alignment to match.
720 MaxAlign = std::max(a: MaxAlign, b: Alignment);
721
722 // Adjust to alignment boundary.
723 Offset = alignTo(Size: Offset, A: Alignment);
724
725 if (StackGrowsDown) {
726 LLVM_DEBUG(dbgs() << "alloc FI(" << FrameIdx << ") at SP[" << -Offset
727 << "]\n");
728 MFI.setObjectOffset(ObjectIdx: FrameIdx, SPOffset: -Offset); // Set the computed offset
729 } else {
730 LLVM_DEBUG(dbgs() << "alloc FI(" << FrameIdx << ") at SP[" << Offset
731 << "]\n");
732 MFI.setObjectOffset(ObjectIdx: FrameIdx, SPOffset: Offset);
733 Offset += MFI.getObjectSize(ObjectIdx: FrameIdx);
734 }
735}
736
737/// Compute which bytes of fixed and callee-save stack area are unused and keep
738/// track of them in StackBytesFree.
739static inline void computeFreeStackSlots(MachineFrameInfo &MFI,
740 bool StackGrowsDown,
741 int64_t FixedCSEnd,
742 BitVector &StackBytesFree) {
743 // Avoid undefined int64_t -> int conversion below in extreme case.
744 if (FixedCSEnd > std::numeric_limits<int>::max())
745 return;
746
747 StackBytesFree.resize(N: FixedCSEnd, t: true);
748
749 SmallVector<int, 16> AllocatedFrameSlots;
750 // Add fixed objects.
751 for (int i = MFI.getObjectIndexBegin(); i != 0; ++i)
752 // StackSlot scavenging is only implemented for the default stack.
753 if (MFI.getStackID(ObjectIdx: i) == TargetStackID::Default)
754 AllocatedFrameSlots.push_back(Elt: i);
755 // Add callee-save objects if there are any.
756 for (int i = MFI.getObjectIndexBegin(); i < MFI.getObjectIndexEnd(); i++)
757 if (MFI.isCalleeSavedObjectIndex(ObjectIdx: i) &&
758 MFI.getStackID(ObjectIdx: i) == TargetStackID::Default)
759 AllocatedFrameSlots.push_back(Elt: i);
760
761 for (int i : AllocatedFrameSlots) {
762 // These are converted from int64_t, but they should always fit in int
763 // because of the FixedCSEnd check above.
764 int ObjOffset = MFI.getObjectOffset(ObjectIdx: i);
765 int ObjSize = MFI.getObjectSize(ObjectIdx: i);
766 int ObjStart, ObjEnd;
767 if (StackGrowsDown) {
768 // ObjOffset is negative when StackGrowsDown is true.
769 ObjStart = -ObjOffset - ObjSize;
770 ObjEnd = -ObjOffset;
771 } else {
772 ObjStart = ObjOffset;
773 ObjEnd = ObjOffset + ObjSize;
774 }
775 // Ignore fixed holes that are in the previous stack frame.
776 if (ObjEnd > 0)
777 StackBytesFree.reset(I: ObjStart, E: ObjEnd);
778 }
779}
780
781/// Assign frame object to an unused portion of the stack in the fixed stack
782/// object range. Return true if the allocation was successful.
783static inline bool scavengeStackSlot(MachineFrameInfo &MFI, int FrameIdx,
784 bool StackGrowsDown, Align MaxAlign,
785 BitVector &StackBytesFree) {
786 if (MFI.isVariableSizedObjectIndex(ObjectIdx: FrameIdx))
787 return false;
788
789 if (StackBytesFree.none()) {
790 // clear it to speed up later scavengeStackSlot calls to
791 // StackBytesFree.none()
792 StackBytesFree.clear();
793 return false;
794 }
795
796 Align ObjAlign = MFI.getObjectAlign(ObjectIdx: FrameIdx);
797 if (ObjAlign > MaxAlign)
798 return false;
799
800 int64_t ObjSize = MFI.getObjectSize(ObjectIdx: FrameIdx);
801 int FreeStart;
802 for (FreeStart = StackBytesFree.find_first(); FreeStart != -1;
803 FreeStart = StackBytesFree.find_next(Prev: FreeStart)) {
804
805 // Check that free space has suitable alignment.
806 unsigned ObjStart = StackGrowsDown ? FreeStart + ObjSize : FreeStart;
807 if (alignTo(Size: ObjStart, A: ObjAlign) != ObjStart)
808 continue;
809
810 if (FreeStart + ObjSize > StackBytesFree.size())
811 return false;
812
813 bool AllBytesFree = true;
814 for (unsigned Byte = 0; Byte < ObjSize; ++Byte)
815 if (!StackBytesFree.test(Idx: FreeStart + Byte)) {
816 AllBytesFree = false;
817 break;
818 }
819 if (AllBytesFree)
820 break;
821 }
822
823 if (FreeStart == -1)
824 return false;
825
826 if (StackGrowsDown) {
827 int ObjStart = -(FreeStart + ObjSize);
828 LLVM_DEBUG(dbgs() << "alloc FI(" << FrameIdx << ") scavenged at SP["
829 << ObjStart << "]\n");
830 MFI.setObjectOffset(ObjectIdx: FrameIdx, SPOffset: ObjStart);
831 } else {
832 LLVM_DEBUG(dbgs() << "alloc FI(" << FrameIdx << ") scavenged at SP["
833 << FreeStart << "]\n");
834 MFI.setObjectOffset(ObjectIdx: FrameIdx, SPOffset: FreeStart);
835 }
836
837 StackBytesFree.reset(I: FreeStart, E: FreeStart + ObjSize);
838 return true;
839}
840
841/// AssignProtectedObjSet - Helper function to assign large stack objects (i.e.,
842/// those required to be close to the Stack Protector) to stack offsets.
843static void AssignProtectedObjSet(const StackObjSet &UnassignedObjs,
844 SmallSet<int, 16> &ProtectedObjs,
845 MachineFrameInfo &MFI, bool StackGrowsDown,
846 int64_t &Offset, Align &MaxAlign) {
847
848 for (int i : UnassignedObjs) {
849 AdjustStackOffset(MFI, FrameIdx: i, StackGrowsDown, Offset, MaxAlign);
850 ProtectedObjs.insert(V: i);
851 }
852}
853
854/// calculateFrameObjectOffsets - Calculate actual frame offsets for all of the
855/// abstract stack objects.
856void PEIImpl::calculateFrameObjectOffsets(MachineFunction &MF) {
857 const TargetFrameLowering &TFI = *MF.getSubtarget().getFrameLowering();
858
859 bool StackGrowsDown =
860 TFI.getStackGrowthDirection() == TargetFrameLowering::StackGrowsDown;
861
862 // Loop over all of the stack objects, assigning sequential addresses...
863 MachineFrameInfo &MFI = MF.getFrameInfo();
864
865 // Start at the beginning of the local area.
866 // The Offset is the distance from the stack top in the direction
867 // of stack growth -- so it's always nonnegative.
868 int LocalAreaOffset = TFI.getOffsetOfLocalArea();
869 if (StackGrowsDown)
870 LocalAreaOffset = -LocalAreaOffset;
871 assert(LocalAreaOffset >= 0
872 && "Local area offset should be in direction of stack growth");
873 int64_t Offset = LocalAreaOffset;
874
875#ifdef EXPENSIVE_CHECKS
876 for (unsigned i = 0, e = MFI.getObjectIndexEnd(); i != e; ++i)
877 if (!MFI.isDeadObjectIndex(i) &&
878 MFI.getStackID(i) == TargetStackID::Default)
879 assert(MFI.getObjectAlign(i) <= MFI.getMaxAlign() &&
880 "MaxAlignment is invalid");
881#endif
882
883 // If there are fixed sized objects that are preallocated in the local area,
884 // non-fixed objects can't be allocated right at the start of local area.
885 // Adjust 'Offset' to point to the end of last fixed sized preallocated
886 // object.
887 for (int i = MFI.getObjectIndexBegin(); i != 0; ++i) {
888 // Only allocate objects on the default stack.
889 if (MFI.getStackID(ObjectIdx: i) != TargetStackID::Default)
890 continue;
891
892 int64_t FixedOff;
893 if (StackGrowsDown) {
894 // The maximum distance from the stack pointer is at lower address of
895 // the object -- which is given by offset. For down growing stack
896 // the offset is negative, so we negate the offset to get the distance.
897 FixedOff = -MFI.getObjectOffset(ObjectIdx: i);
898 } else {
899 // The maximum distance from the start pointer is at the upper
900 // address of the object.
901 FixedOff = MFI.getObjectOffset(ObjectIdx: i) + MFI.getObjectSize(ObjectIdx: i);
902 }
903 if (FixedOff > Offset) Offset = FixedOff;
904 }
905
906 Align MaxAlign = MFI.getMaxAlign();
907 // First assign frame offsets to stack objects that are used to spill
908 // callee saved registers.
909 auto AllFIs = seq(Begin: MFI.getObjectIndexBegin(), End: MFI.getObjectIndexEnd());
910 for (int FI : reverse_conditionally(C&: AllFIs, /*Reverse=*/ShouldReverse: !StackGrowsDown)) {
911 // Only allocate objects on the default stack.
912 if (!MFI.isCalleeSavedObjectIndex(ObjectIdx: FI) ||
913 MFI.getStackID(ObjectIdx: FI) != TargetStackID::Default)
914 continue;
915
916 // TODO: should this just be if (MFI.isDeadObjectIndex(FI))
917 if (!StackGrowsDown && MFI.isDeadObjectIndex(ObjectIdx: FI))
918 continue;
919
920 AdjustStackOffset(MFI, FrameIdx: FI, StackGrowsDown, Offset, MaxAlign);
921 }
922
923 assert(MaxAlign == MFI.getMaxAlign() &&
924 "MFI.getMaxAlign should already account for all callee-saved "
925 "registers without a fixed stack slot");
926
927 // FixedCSEnd is the stack offset to the end of the fixed and callee-save
928 // stack area.
929 int64_t FixedCSEnd = Offset;
930
931 // Make sure the special register scavenging spill slot is closest to the
932 // incoming stack pointer if a frame pointer is required and is closer
933 // to the incoming rather than the final stack pointer.
934 const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
935 bool EarlyScavengingSlots = TFI.allocateScavengingFrameIndexesNearIncomingSP(MF);
936 if (RS && EarlyScavengingSlots) {
937 SmallVector<int, 2> SFIs;
938 RS->getScavengingFrameIndices(A&: SFIs);
939 for (int SFI : SFIs)
940 AdjustStackOffset(MFI, FrameIdx: SFI, StackGrowsDown, Offset, MaxAlign);
941 }
942
943 // FIXME: Once this is working, then enable flag will change to a target
944 // check for whether the frame is large enough to want to use virtual
945 // frame index registers. Functions which don't want/need this optimization
946 // will continue to use the existing code path.
947 if (MFI.getUseLocalStackAllocationBlock()) {
948 Align Alignment = MFI.getLocalFrameMaxAlign();
949
950 // Adjust to alignment boundary.
951 Offset = alignTo(Size: Offset, A: Alignment);
952
953 LLVM_DEBUG(dbgs() << "Local frame base offset: " << Offset << "\n");
954
955 // Resolve offsets for objects in the local block.
956 for (unsigned i = 0, e = MFI.getLocalFrameObjectCount(); i != e; ++i) {
957 std::pair<int, int64_t> Entry = MFI.getLocalFrameObjectMap(i);
958 int64_t FIOffset = (StackGrowsDown ? -Offset : Offset) + Entry.second;
959 LLVM_DEBUG(dbgs() << "alloc FI(" << Entry.first << ") at SP[" << FIOffset
960 << "]\n");
961 MFI.setObjectOffset(ObjectIdx: Entry.first, SPOffset: FIOffset);
962 }
963 // Allocate the local block
964 Offset += MFI.getLocalFrameSize();
965
966 MaxAlign = std::max(a: Alignment, b: MaxAlign);
967 }
968
969 // Retrieve the Exception Handler registration node.
970 int EHRegNodeFrameIndex = std::numeric_limits<int>::max();
971 if (const WinEHFuncInfo *FuncInfo = MF.getWinEHFuncInfo())
972 EHRegNodeFrameIndex = FuncInfo->EHRegNodeFrameIndex;
973
974 // Make sure that the stack protector comes before the local variables on the
975 // stack.
976 SmallSet<int, 16> ProtectedObjs;
977 if (MFI.hasStackProtectorIndex()) {
978 int StackProtectorFI = MFI.getStackProtectorIndex();
979 StackObjSet LargeArrayObjs;
980 StackObjSet SmallArrayObjs;
981 StackObjSet AddrOfObjs;
982
983 // If we need a stack protector, we need to make sure that
984 // LocalStackSlotPass didn't already allocate a slot for it.
985 // If we are told to use the LocalStackAllocationBlock, the stack protector
986 // is expected to be already pre-allocated.
987 if (MFI.getStackID(ObjectIdx: StackProtectorFI) != TargetStackID::Default) {
988 // If the stack protector isn't on the default stack then it's up to the
989 // target to set the stack offset.
990 assert(MFI.getObjectOffset(StackProtectorFI) != 0 &&
991 "Offset of stack protector on non-default stack expected to be "
992 "already set.");
993 assert(!MFI.isObjectPreAllocated(MFI.getStackProtectorIndex()) &&
994 "Stack protector on non-default stack expected to not be "
995 "pre-allocated by LocalStackSlotPass.");
996 } else if (!MFI.getUseLocalStackAllocationBlock()) {
997 AdjustStackOffset(MFI, FrameIdx: StackProtectorFI, StackGrowsDown, Offset,
998 MaxAlign);
999 } else if (!MFI.isObjectPreAllocated(ObjectIdx: MFI.getStackProtectorIndex())) {
1000 llvm_unreachable(
1001 "Stack protector not pre-allocated by LocalStackSlotPass.");
1002 }
1003
1004 // Assign large stack objects first.
1005 for (unsigned i = 0, e = MFI.getObjectIndexEnd(); i != e; ++i) {
1006 if (MFI.isObjectPreAllocated(ObjectIdx: i) && MFI.getUseLocalStackAllocationBlock())
1007 continue;
1008 if (MFI.isCalleeSavedObjectIndex(ObjectIdx: i))
1009 continue;
1010 if (RS && RS->isScavengingFrameIndex(FI: (int)i))
1011 continue;
1012 if (MFI.isDeadObjectIndex(ObjectIdx: i))
1013 continue;
1014 if (StackProtectorFI == (int)i || EHRegNodeFrameIndex == (int)i)
1015 continue;
1016 // Only allocate objects on the default stack.
1017 if (MFI.getStackID(ObjectIdx: i) != TargetStackID::Default)
1018 continue;
1019
1020 switch (MFI.getObjectSSPLayout(ObjectIdx: i)) {
1021 case MachineFrameInfo::SSPLK_None:
1022 continue;
1023 case MachineFrameInfo::SSPLK_SmallArray:
1024 SmallArrayObjs.insert(X: i);
1025 continue;
1026 case MachineFrameInfo::SSPLK_AddrOf:
1027 AddrOfObjs.insert(X: i);
1028 continue;
1029 case MachineFrameInfo::SSPLK_LargeArray:
1030 LargeArrayObjs.insert(X: i);
1031 continue;
1032 }
1033 llvm_unreachable("Unexpected SSPLayoutKind.");
1034 }
1035
1036 // We expect **all** the protected stack objects to be pre-allocated by
1037 // LocalStackSlotPass. If it turns out that PEI still has to allocate some
1038 // of them, we may end up messing up the expected order of the objects.
1039 if (MFI.getUseLocalStackAllocationBlock() &&
1040 !(LargeArrayObjs.empty() && SmallArrayObjs.empty() &&
1041 AddrOfObjs.empty()))
1042 llvm_unreachable("Found protected stack objects not pre-allocated by "
1043 "LocalStackSlotPass.");
1044
1045 AssignProtectedObjSet(UnassignedObjs: LargeArrayObjs, ProtectedObjs, MFI, StackGrowsDown,
1046 Offset, MaxAlign);
1047 AssignProtectedObjSet(UnassignedObjs: SmallArrayObjs, ProtectedObjs, MFI, StackGrowsDown,
1048 Offset, MaxAlign);
1049 AssignProtectedObjSet(UnassignedObjs: AddrOfObjs, ProtectedObjs, MFI, StackGrowsDown,
1050 Offset, MaxAlign);
1051 }
1052
1053 SmallVector<int, 8> ObjectsToAllocate;
1054
1055 // Then prepare to assign frame offsets to stack objects that are not used to
1056 // spill callee saved registers.
1057 for (unsigned i = 0, e = MFI.getObjectIndexEnd(); i != e; ++i) {
1058 if (MFI.isObjectPreAllocated(ObjectIdx: i) && MFI.getUseLocalStackAllocationBlock())
1059 continue;
1060 if (MFI.isCalleeSavedObjectIndex(ObjectIdx: i))
1061 continue;
1062 if (RS && RS->isScavengingFrameIndex(FI: (int)i))
1063 continue;
1064 if (MFI.isDeadObjectIndex(ObjectIdx: i))
1065 continue;
1066 if (MFI.getStackProtectorIndex() == (int)i || EHRegNodeFrameIndex == (int)i)
1067 continue;
1068 if (ProtectedObjs.count(V: i))
1069 continue;
1070 // Only allocate objects on the default stack.
1071 if (MFI.getStackID(ObjectIdx: i) != TargetStackID::Default)
1072 continue;
1073
1074 // Add the objects that we need to allocate to our working set.
1075 ObjectsToAllocate.push_back(Elt: i);
1076 }
1077
1078 // Allocate the EH registration node first if one is present.
1079 if (EHRegNodeFrameIndex != std::numeric_limits<int>::max())
1080 AdjustStackOffset(MFI, FrameIdx: EHRegNodeFrameIndex, StackGrowsDown, Offset,
1081 MaxAlign);
1082
1083 // Give the targets a chance to order the objects the way they like it.
1084 if (MF.getTarget().getOptLevel() != CodeGenOptLevel::None &&
1085 MF.getTarget().Options.StackSymbolOrdering)
1086 TFI.orderFrameObjects(MF, objectsToAllocate&: ObjectsToAllocate);
1087
1088 // Keep track of which bytes in the fixed and callee-save range are used so we
1089 // can use the holes when allocating later stack objects. Only do this if
1090 // stack protector isn't being used and the target requests it and we're
1091 // optimizing.
1092 BitVector StackBytesFree;
1093 if (!ObjectsToAllocate.empty() &&
1094 MF.getTarget().getOptLevel() != CodeGenOptLevel::None &&
1095 MFI.getStackProtectorIndex() < 0 && TFI.enableStackSlotScavenging(MF))
1096 computeFreeStackSlots(MFI, StackGrowsDown, FixedCSEnd, StackBytesFree);
1097
1098 // Now walk the objects and actually assign base offsets to them.
1099 for (auto &Object : ObjectsToAllocate)
1100 if (!scavengeStackSlot(MFI, FrameIdx: Object, StackGrowsDown, MaxAlign,
1101 StackBytesFree))
1102 AdjustStackOffset(MFI, FrameIdx: Object, StackGrowsDown, Offset, MaxAlign);
1103
1104 // Make sure the special register scavenging spill slot is closest to the
1105 // stack pointer.
1106 if (RS && !EarlyScavengingSlots) {
1107 SmallVector<int, 2> SFIs;
1108 RS->getScavengingFrameIndices(A&: SFIs);
1109 for (int SFI : SFIs)
1110 AdjustStackOffset(MFI, FrameIdx: SFI, StackGrowsDown, Offset, MaxAlign);
1111 }
1112
1113 if (!TFI.targetHandlesStackFrameRounding()) {
1114 // If we have reserved argument space for call sites in the function
1115 // immediately on entry to the current function, count it as part of the
1116 // overall stack size.
1117 if (MFI.adjustsStack() && TFI.hasReservedCallFrame(MF))
1118 Offset += MFI.getMaxCallFrameSize();
1119
1120 // Round up the size to a multiple of the alignment. If the function has
1121 // any calls or alloca's, align to the target's StackAlignment value to
1122 // ensure that the callee's frame or the alloca data is suitably aligned;
1123 // otherwise, for leaf functions, align to the TransientStackAlignment
1124 // value.
1125 Align StackAlign;
1126 if (MFI.adjustsStack() || MFI.hasVarSizedObjects() ||
1127 (RegInfo->hasStackRealignment(MF) && MFI.getObjectIndexEnd() != 0))
1128 StackAlign = TFI.getStackAlign();
1129 else
1130 StackAlign = TFI.getTransientStackAlign();
1131
1132 // If the frame pointer is eliminated, all frame offsets will be relative to
1133 // SP not FP. Align to MaxAlign so this works.
1134 StackAlign = std::max(a: StackAlign, b: MaxAlign);
1135 int64_t OffsetBeforeAlignment = Offset;
1136 Offset = alignTo(Size: Offset, A: StackAlign);
1137
1138 // If we have increased the offset to fulfill the alignment constrants,
1139 // then the scavenging spill slots may become harder to reach from the
1140 // stack pointer, float them so they stay close.
1141 if (StackGrowsDown && OffsetBeforeAlignment != Offset && RS &&
1142 !EarlyScavengingSlots) {
1143 SmallVector<int, 2> SFIs;
1144 RS->getScavengingFrameIndices(A&: SFIs);
1145 LLVM_DEBUG(if (!SFIs.empty()) llvm::dbgs()
1146 << "Adjusting emergency spill slots!\n";);
1147 int64_t Delta = Offset - OffsetBeforeAlignment;
1148 for (int SFI : SFIs) {
1149 LLVM_DEBUG(llvm::dbgs()
1150 << "Adjusting offset of emergency spill slot #" << SFI
1151 << " from " << MFI.getObjectOffset(SFI););
1152 MFI.setObjectOffset(ObjectIdx: SFI, SPOffset: MFI.getObjectOffset(ObjectIdx: SFI) - Delta);
1153 LLVM_DEBUG(llvm::dbgs() << " to " << MFI.getObjectOffset(SFI) << "\n";);
1154 }
1155 }
1156 }
1157
1158 // Update frame info to pretend that this is part of the stack...
1159 int64_t StackSize = Offset - LocalAreaOffset;
1160 MFI.setStackSize(StackSize);
1161 NumBytesStackSpace += StackSize;
1162}
1163
1164/// insertPrologEpilogCode - Scan the function for modified callee saved
1165/// registers, insert spill code for these callee saved registers, then add
1166/// prolog and epilog code to the function.
1167void PEIImpl::insertPrologEpilogCode(MachineFunction &MF) {
1168 const TargetFrameLowering &TFI = *MF.getSubtarget().getFrameLowering();
1169
1170 // Add prologue to the function...
1171 for (MachineBasicBlock *SaveBlock : SaveBlocks)
1172 TFI.emitPrologue(MF, MBB&: *SaveBlock);
1173
1174 // Add epilogue to restore the callee-save registers in each exiting block.
1175 for (MachineBasicBlock *RestoreBlock : RestoreBlocks)
1176 TFI.emitEpilogue(MF, MBB&: *RestoreBlock);
1177
1178 for (MachineBasicBlock *SaveBlock : SaveBlocks)
1179 TFI.inlineStackProbe(MF, PrologueMBB&: *SaveBlock);
1180
1181 // Emit additional code that is required to support segmented stacks, if
1182 // we've been asked for it. This, when linked with a runtime with support
1183 // for segmented stacks (libgcc is one), will result in allocating stack
1184 // space in small chunks instead of one large contiguous block.
1185 if (MF.shouldSplitStack()) {
1186 for (MachineBasicBlock *SaveBlock : SaveBlocks)
1187 TFI.adjustForSegmentedStacks(MF, PrologueMBB&: *SaveBlock);
1188 }
1189
1190 // Emit additional code that is required to explicitly handle the stack in
1191 // HiPE native code (if needed) when loaded in the Erlang/OTP runtime. The
1192 // approach is rather similar to that of Segmented Stacks, but it uses a
1193 // different conditional check and another BIF for allocating more stack
1194 // space.
1195 if (MF.getFunction().getCallingConv() == CallingConv::HiPE)
1196 for (MachineBasicBlock *SaveBlock : SaveBlocks)
1197 TFI.adjustForHiPEPrologue(MF, PrologueMBB&: *SaveBlock);
1198}
1199
1200/// insertZeroCallUsedRegs - Zero out call used registers.
1201void PEIImpl::insertZeroCallUsedRegs(MachineFunction &MF) {
1202 const Function &F = MF.getFunction();
1203
1204 if (!F.hasFnAttribute(Kind: "zero-call-used-regs"))
1205 return;
1206
1207 using namespace ZeroCallUsedRegs;
1208
1209 ZeroCallUsedRegsKind ZeroRegsKind =
1210 StringSwitch<ZeroCallUsedRegsKind>(
1211 F.getFnAttribute(Kind: "zero-call-used-regs").getValueAsString())
1212 .Case(S: "skip", Value: ZeroCallUsedRegsKind::Skip)
1213 .Case(S: "used-gpr-arg", Value: ZeroCallUsedRegsKind::UsedGPRArg)
1214 .Case(S: "used-gpr", Value: ZeroCallUsedRegsKind::UsedGPR)
1215 .Case(S: "used-arg", Value: ZeroCallUsedRegsKind::UsedArg)
1216 .Case(S: "used", Value: ZeroCallUsedRegsKind::Used)
1217 .Case(S: "all-gpr-arg", Value: ZeroCallUsedRegsKind::AllGPRArg)
1218 .Case(S: "all-gpr", Value: ZeroCallUsedRegsKind::AllGPR)
1219 .Case(S: "all-arg", Value: ZeroCallUsedRegsKind::AllArg)
1220 .Case(S: "all", Value: ZeroCallUsedRegsKind::All);
1221
1222 if (ZeroRegsKind == ZeroCallUsedRegsKind::Skip)
1223 return;
1224
1225 const bool OnlyGPR = static_cast<unsigned>(ZeroRegsKind) & ONLY_GPR;
1226 const bool OnlyUsed = static_cast<unsigned>(ZeroRegsKind) & ONLY_USED;
1227 const bool OnlyArg = static_cast<unsigned>(ZeroRegsKind) & ONLY_ARG;
1228
1229 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
1230 const BitVector AllocatableSet(TRI.getAllocatableSet(MF));
1231
1232 // Mark all used registers.
1233 BitVector UsedRegs(TRI.getNumRegs());
1234 if (OnlyUsed)
1235 for (const MachineBasicBlock &MBB : MF)
1236 for (const MachineInstr &MI : MBB) {
1237 // skip debug instructions
1238 if (MI.isDebugInstr())
1239 continue;
1240
1241 for (const MachineOperand &MO : MI.operands()) {
1242 if (!MO.isReg())
1243 continue;
1244
1245 MCRegister Reg = MO.getReg();
1246 if (AllocatableSet[Reg.id()] && !MO.isImplicit() &&
1247 (MO.isDef() || MO.isUse()))
1248 UsedRegs.set(Reg.id());
1249 }
1250 }
1251
1252 // Get a list of registers that are used.
1253 BitVector LiveIns(TRI.getNumRegs());
1254 for (const MachineBasicBlock::RegisterMaskPair &LI : MF.front().liveins())
1255 LiveIns.set(LI.PhysReg);
1256
1257 BitVector RegsToZero(TRI.getNumRegs());
1258 for (MCRegister Reg : AllocatableSet.set_bits()) {
1259 // Skip over fixed registers.
1260 if (TRI.isFixedRegister(MF, PhysReg: Reg))
1261 continue;
1262
1263 // Want only general purpose registers.
1264 if (OnlyGPR && !TRI.isGeneralPurposeRegister(MF, PhysReg: Reg))
1265 continue;
1266
1267 // Want only used registers.
1268 if (OnlyUsed && !UsedRegs[Reg.id()])
1269 continue;
1270
1271 // Want only registers used for arguments.
1272 if (OnlyArg) {
1273 if (OnlyUsed) {
1274 for (MCRegister LiveReg : LiveIns.set_bits()) {
1275 if (TRI.regsOverlap(RegA: Reg, RegB: LiveReg))
1276 RegsToZero.set(LiveReg);
1277 }
1278 continue;
1279 } else if (!TRI.isArgumentRegister(MF, PhysReg: Reg)) {
1280 continue;
1281 }
1282 }
1283
1284 RegsToZero.set(Reg.id());
1285 }
1286
1287 // Don't clear registers that are live when leaving the function.
1288 for (const MachineBasicBlock &MBB : MF)
1289 for (const MachineInstr &MI : MBB.terminators()) {
1290 if (!MI.isReturn())
1291 continue;
1292
1293 for (const auto &MO : MI.operands()) {
1294 if (!MO.isReg())
1295 continue;
1296
1297 MCRegister Reg = MO.getReg();
1298 if (!Reg)
1299 continue;
1300
1301 // This picks up sibling registers (e.q. %al -> %ah).
1302 // FIXME: Mixing physical registers and register units is likely a bug.
1303 for (MCRegUnit Unit : TRI.regunits(Reg))
1304 RegsToZero.reset(Idx: static_cast<unsigned>(Unit));
1305
1306 for (MCPhysReg SReg : TRI.sub_and_superregs_inclusive(Reg))
1307 RegsToZero.reset(Idx: SReg);
1308 }
1309 }
1310
1311 // Don't need to clear registers that are used/clobbered by terminating
1312 // instructions.
1313 for (const MachineBasicBlock &MBB : MF) {
1314 if (!MBB.isReturnBlock())
1315 continue;
1316
1317 MachineBasicBlock::const_iterator MBBI = MBB.getFirstTerminator();
1318 for (MachineBasicBlock::const_iterator I = MBBI, E = MBB.end(); I != E;
1319 ++I) {
1320 for (const MachineOperand &MO : I->operands()) {
1321 if (!MO.isReg())
1322 continue;
1323
1324 MCRegister Reg = MO.getReg();
1325 if (!Reg)
1326 continue;
1327
1328 for (const MCPhysReg Reg : TRI.sub_and_superregs_inclusive(Reg))
1329 RegsToZero.reset(Idx: Reg);
1330 }
1331 }
1332 }
1333
1334 // Don't clear registers that must be preserved.
1335 for (const MCPhysReg *CSRegs = TRI.getCalleeSavedRegs(MF: &MF);
1336 MCPhysReg CSReg = *CSRegs; ++CSRegs)
1337 for (MCRegister Reg : TRI.sub_and_superregs_inclusive(Reg: CSReg))
1338 RegsToZero.reset(Idx: Reg.id());
1339
1340 const TargetFrameLowering &TFI = *MF.getSubtarget().getFrameLowering();
1341 for (MachineBasicBlock &MBB : MF)
1342 if (MBB.isReturnBlock())
1343 TFI.emitZeroCallUsedRegs(RegsToZero, MBB, RS);
1344}
1345
1346/// Replace all FrameIndex operands with physical register references and actual
1347/// offsets.
1348void PEIImpl::replaceFrameIndicesBackward(MachineFunction &MF) {
1349 const TargetFrameLowering &TFI = *MF.getSubtarget().getFrameLowering();
1350
1351 for (auto &MBB : MF) {
1352 int SPAdj = 0;
1353 if (!MBB.succ_empty()) {
1354 // Get the SP adjustment for the end of MBB from the start of any of its
1355 // successors. They should all be the same.
1356 assert(all_of(MBB.successors(), [&MBB](const MachineBasicBlock *Succ) {
1357 return Succ->getCallFrameSize() ==
1358 (*MBB.succ_begin())->getCallFrameSize();
1359 }));
1360 const MachineBasicBlock &FirstSucc = **MBB.succ_begin();
1361 SPAdj = TFI.alignSPAdjust(SPAdj: FirstSucc.getCallFrameSize());
1362 if (TFI.getStackGrowthDirection() == TargetFrameLowering::StackGrowsUp)
1363 SPAdj = -SPAdj;
1364 }
1365
1366 replaceFrameIndicesBackward(BB: &MBB, MF, SPAdj);
1367
1368 // We can't track the call frame size after call frame pseudos have been
1369 // eliminated. Set it to zero everywhere to keep MachineVerifier happy.
1370 MBB.setCallFrameSize(0);
1371 }
1372}
1373
1374/// replaceFrameIndices - Replace all MO_FrameIndex operands with physical
1375/// register references and actual offsets.
1376void PEIImpl::replaceFrameIndices(MachineFunction &MF) {
1377 const TargetFrameLowering &TFI = *MF.getSubtarget().getFrameLowering();
1378
1379 for (auto &MBB : MF) {
1380 int SPAdj = TFI.alignSPAdjust(SPAdj: MBB.getCallFrameSize());
1381 if (TFI.getStackGrowthDirection() == TargetFrameLowering::StackGrowsUp)
1382 SPAdj = -SPAdj;
1383
1384 replaceFrameIndices(BB: &MBB, MF, SPAdj);
1385
1386 // We can't track the call frame size after call frame pseudos have been
1387 // eliminated. Set it to zero everywhere to keep MachineVerifier happy.
1388 MBB.setCallFrameSize(0);
1389 }
1390}
1391
1392bool PEIImpl::replaceFrameIndexDebugInstr(MachineFunction &MF, MachineInstr &MI,
1393 unsigned OpIdx, int SPAdj) {
1394 const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering();
1395 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
1396 if (MI.isDebugValue()) {
1397
1398 MachineOperand &Op = MI.getOperand(i: OpIdx);
1399 assert(MI.isDebugOperand(&Op) &&
1400 "Frame indices can only appear as a debug operand in a DBG_VALUE*"
1401 " machine instruction");
1402 Register Reg;
1403 unsigned FrameIdx = Op.getIndex();
1404 unsigned Size = MF.getFrameInfo().getObjectSize(ObjectIdx: FrameIdx);
1405
1406 StackOffset Offset = TFI->getFrameIndexReference(MF, FI: FrameIdx, FrameReg&: Reg);
1407 Op.ChangeToRegister(Reg, isDef: false /*isDef*/);
1408
1409 const DIExpression *DIExpr = MI.getDebugExpression();
1410
1411 // If we have a direct DBG_VALUE, and its location expression isn't
1412 // currently complex, then adding an offset will morph it into a
1413 // complex location that is interpreted as being a memory address.
1414 // This changes a pointer-valued variable to dereference that pointer,
1415 // which is incorrect. Fix by adding DW_OP_stack_value.
1416
1417 if (MI.isNonListDebugValue()) {
1418 unsigned PrependFlags = DIExpression::ApplyOffset;
1419 if (!MI.isIndirectDebugValue() && !DIExpr->isComplex())
1420 PrependFlags |= DIExpression::StackValue;
1421
1422 // If we have DBG_VALUE that is indirect and has a Implicit location
1423 // expression need to insert a deref before prepending a Memory
1424 // location expression. Also after doing this we change the DBG_VALUE
1425 // to be direct.
1426 if (MI.isIndirectDebugValue() && DIExpr->isImplicit()) {
1427 SmallVector<uint64_t, 2> Ops = {dwarf::DW_OP_deref_size, Size};
1428 bool WithStackValue = true;
1429 DIExpr = DIExpression::prependOpcodes(Expr: DIExpr, Ops, StackValue: WithStackValue);
1430 // Make the DBG_VALUE direct.
1431 MI.getDebugOffset().ChangeToRegister(Reg: 0, isDef: false);
1432 }
1433 DIExpr = TRI.prependOffsetExpression(Expr: DIExpr, PrependFlags, Offset);
1434 } else {
1435 // The debug operand at DebugOpIndex was a frame index at offset
1436 // `Offset`; now the operand has been replaced with the frame
1437 // register, we must add Offset with `register x, plus Offset`.
1438 unsigned DebugOpIndex = MI.getDebugOperandIndex(Op: &Op);
1439 SmallVector<uint64_t, 3> Ops;
1440 TRI.getOffsetOpcodes(Offset, Ops);
1441 DIExpr = DIExpression::appendOpsToArg(Expr: DIExpr, Ops, ArgNo: DebugOpIndex);
1442 }
1443 MI.getDebugExpressionOp().setMetadata(DIExpr);
1444 return true;
1445 }
1446
1447 if (MI.isDebugPHI()) {
1448 // Allow stack ref to continue onwards.
1449 return true;
1450 }
1451
1452 // TODO: This code should be commoned with the code for
1453 // PATCHPOINT. There's no good reason for the difference in
1454 // implementation other than historical accident. The only
1455 // remaining difference is the unconditional use of the stack
1456 // pointer as the base register.
1457 if (MI.getOpcode() == TargetOpcode::STATEPOINT) {
1458 assert((!MI.isDebugValue() || OpIdx == 0) &&
1459 "Frame indices can only appear as the first operand of a "
1460 "DBG_VALUE machine instruction");
1461 Register Reg;
1462 MachineOperand &Offset = MI.getOperand(i: OpIdx + 1);
1463 StackOffset refOffset = TFI->getFrameIndexReferencePreferSP(
1464 MF, FI: MI.getOperand(i: OpIdx).getIndex(), FrameReg&: Reg, /*IgnoreSPUpdates*/ false);
1465 assert(!refOffset.getScalable() &&
1466 "Frame offsets with a scalable component are not supported");
1467 Offset.setImm(Offset.getImm() + refOffset.getFixed() + SPAdj);
1468 MI.getOperand(i: OpIdx).ChangeToRegister(Reg, isDef: false /*isDef*/);
1469 return true;
1470 }
1471 return false;
1472}
1473
1474void PEIImpl::replaceFrameIndicesBackward(MachineBasicBlock *BB,
1475 MachineFunction &MF, int &SPAdj) {
1476 assert(MF.getSubtarget().getRegisterInfo() &&
1477 "getRegisterInfo() must be implemented!");
1478
1479 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
1480 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
1481 const TargetFrameLowering &TFI = *MF.getSubtarget().getFrameLowering();
1482
1483 RegScavenger *LocalRS = FrameIndexEliminationScavenging ? RS : nullptr;
1484 if (LocalRS)
1485 LocalRS->enterBasicBlockEnd(MBB&: *BB);
1486
1487 for (MachineBasicBlock::iterator I = BB->end(); I != BB->begin();) {
1488 MachineInstr &MI = *std::prev(x: I);
1489
1490 if (TII.isFrameInstr(I: MI)) {
1491 SPAdj -= TII.getSPAdjust(MI);
1492 TFI.eliminateCallFramePseudoInstr(MF, MBB&: *BB, MI: &MI);
1493 continue;
1494 }
1495
1496 // Step backwards to get the liveness state at (immedately after) MI.
1497 if (LocalRS)
1498 LocalRS->backward(I);
1499
1500 bool RemovedMI = false;
1501 for (const auto &[Idx, Op] : enumerate(First: MI.operands())) {
1502 if (!Op.isFI())
1503 continue;
1504
1505 if (replaceFrameIndexDebugInstr(MF, MI, OpIdx: Idx, SPAdj))
1506 continue;
1507
1508 // Eliminate this FrameIndex operand.
1509 RemovedMI = TRI.eliminateFrameIndex(MI, SPAdj, FIOperandNum: Idx, RS: LocalRS);
1510 if (RemovedMI)
1511 break;
1512 }
1513
1514 if (!RemovedMI)
1515 --I;
1516 }
1517}
1518
1519void PEIImpl::replaceFrameIndices(MachineBasicBlock *BB, MachineFunction &MF,
1520 int &SPAdj) {
1521 assert(MF.getSubtarget().getRegisterInfo() &&
1522 "getRegisterInfo() must be implemented!");
1523 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
1524 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
1525 const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering();
1526
1527 bool InsideCallSequence = false;
1528
1529 for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ) {
1530 if (TII.isFrameInstr(I: *I)) {
1531 InsideCallSequence = TII.isFrameSetup(I: *I);
1532 SPAdj += TII.getSPAdjust(MI: *I);
1533 I = TFI->eliminateCallFramePseudoInstr(MF, MBB&: *BB, MI: I);
1534 continue;
1535 }
1536
1537 MachineInstr &MI = *I;
1538 bool DoIncr = true;
1539 bool DidFinishLoop = true;
1540 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1541 if (!MI.getOperand(i).isFI())
1542 continue;
1543
1544 if (replaceFrameIndexDebugInstr(MF, MI, OpIdx: i, SPAdj))
1545 continue;
1546
1547 // Some instructions (e.g. inline asm instructions) can have
1548 // multiple frame indices and/or cause eliminateFrameIndex
1549 // to insert more than one instruction. We need the register
1550 // scavenger to go through all of these instructions so that
1551 // it can update its register information. We keep the
1552 // iterator at the point before insertion so that we can
1553 // revisit them in full.
1554 bool AtBeginning = (I == BB->begin());
1555 if (!AtBeginning) --I;
1556
1557 // If this instruction has a FrameIndex operand, we need to
1558 // use that target machine register info object to eliminate
1559 // it.
1560 TRI.eliminateFrameIndex(MI, SPAdj, FIOperandNum: i, RS);
1561
1562 // Reset the iterator if we were at the beginning of the BB.
1563 if (AtBeginning) {
1564 I = BB->begin();
1565 DoIncr = false;
1566 }
1567
1568 DidFinishLoop = false;
1569 break;
1570 }
1571
1572 // If we are looking at a call sequence, we need to keep track of
1573 // the SP adjustment made by each instruction in the sequence.
1574 // This includes both the frame setup/destroy pseudos (handled above),
1575 // as well as other instructions that have side effects w.r.t the SP.
1576 // Note that this must come after eliminateFrameIndex, because
1577 // if I itself referred to a frame index, we shouldn't count its own
1578 // adjustment.
1579 if (DidFinishLoop && InsideCallSequence)
1580 SPAdj += TII.getSPAdjust(MI);
1581
1582 if (DoIncr && I != BB->end())
1583 ++I;
1584 }
1585}
1586