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