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