LLVM 24.0.0git
ShrinkWrap.cpp
Go to the documentation of this file.
1//===- ShrinkWrap.cpp - Compute safe point for prolog/epilog insertion ----===//
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 looks for safe point where the prologue and epilogue can be
10// inserted.
11// The safe point for the prologue (resp. epilogue) is called Save
12// (resp. Restore).
13// A point is safe for prologue (resp. epilogue) if and only if
14// it 1) dominates (resp. post-dominates) all the frame related operations and
15// between 2) two executions of the Save (resp. Restore) point there is an
16// execution of the Restore (resp. Save) point.
17//
18// For instance, the following points are safe:
19// for (int i = 0; i < 10; ++i) {
20// Save
21// ...
22// Restore
23// }
24// Indeed, the execution looks like Save -> Restore -> Save -> Restore ...
25// And the following points are not:
26// for (int i = 0; i < 10; ++i) {
27// Save
28// ...
29// }
30// for (int i = 0; i < 10; ++i) {
31// ...
32// Restore
33// }
34// Indeed, the execution looks like Save -> Save -> ... -> Restore -> Restore.
35//
36// This pass also ensures that the safe points are 3) cheaper than the regular
37// entry and exits blocks.
38//
39// Property #1 is ensured via the use of MachineDominatorTree and
40// MachinePostDominatorTree.
41// Property #2 is ensured via property #1 and MachineLoopInfo, i.e., both
42// points must be in the same loop.
43// Property #3 is ensured via the MachineBlockFrequencyInfo.
44//
45// If this pass found points matching all these properties, then
46// MachineFrameInfo is updated with this information.
47//
48//===----------------------------------------------------------------------===//
49
51#include "llvm/ADT/BitVector.h"
53#include "llvm/ADT/SetVector.h"
55#include "llvm/ADT/Statistic.h"
56#include "llvm/Analysis/CFG.h"
76#include "llvm/IR/Attributes.h"
77#include "llvm/IR/Function.h"
79#include "llvm/MC/MCAsmInfo.h"
80#include "llvm/Pass.h"
82#include "llvm/Support/Debug.h"
86#include <cassert>
87#include <memory>
88
89using namespace llvm;
90
91#define DEBUG_TYPE "shrink-wrap"
92
93STATISTIC(NumFunc, "Number of functions");
94STATISTIC(NumCandidates, "Number of shrink-wrapping candidates");
95STATISTIC(NumCandidatesDropped,
96 "Number of shrink-wrapping candidates dropped because of frequency");
97
99EnableShrinkWrapOpt("enable-shrink-wrap", cl::Hidden,
100 cl::desc("enable the shrink-wrapping pass"));
102 "enable-shrink-wrap-region-split", cl::init(true), cl::Hidden,
103 cl::desc("enable splitting of the restore block if possible"));
104
105namespace {
106
107/// Class to determine where the safe point to insert the
108/// prologue and epilogue are.
109/// Unlike the paper from Fred C. Chow, PLDI'88, that introduces the
110/// shrink-wrapping term for prologue/epilogue placement, this pass
111/// does not rely on expensive data-flow analysis. Instead we use the
112/// dominance properties and loop information to decide which point
113/// are safe for such insertion.
114class ShrinkWrapImpl {
115 /// Hold callee-saved information.
116 const RegisterClassInfo *RCI = nullptr;
117 MachineDominatorTree *MDT = nullptr;
118 MachinePostDominatorTree *MPDT = nullptr;
119
120 /// Current safe point found for the prologue.
121 /// The prologue will be inserted before the first instruction
122 /// in this basic block.
123 MachineBasicBlock *Save = nullptr;
124
125 /// Current safe point found for the epilogue.
126 /// The epilogue will be inserted before the first terminator instruction
127 /// in this basic block.
128 MachineBasicBlock *Restore = nullptr;
129
130 /// Hold the information of the basic block frequency.
131 /// Use to check the profitability of the new points.
132 MachineBlockFrequencyInfo *MBFI = nullptr;
133
134 /// Hold the loop information. Used to determine if Save and Restore
135 /// are in the same loop.
136 MachineLoopInfo *MLI = nullptr;
137
138 // Emit remarks.
140
141 /// Frequency of the Entry block.
142 BlockFrequency EntryFreq;
143
144 /// Current opcode for frame setup.
145 unsigned FrameSetupOpcode = ~0u;
146
147 /// Current opcode for frame destroy.
148 unsigned FrameDestroyOpcode = ~0u;
149
150 /// Stack pointer register, used by llvm.{savestack,restorestack}
151 Register SP;
152
153 /// Entry block.
154 const MachineBasicBlock *Entry = nullptr;
155
156 using SetOfRegs = SmallSetVector<unsigned, 16>;
157
158 /// Registers that need to be saved for the current function.
159 mutable SetOfRegs CurrentCSRs;
160
161 /// Current MachineFunction.
162 MachineFunction *MachineFunc = nullptr;
163
164 /// Is `true` for the block numbers where we assume possible stack accesses
165 /// or computation of stack-relative addresses on any CFG path including the
166 /// block itself. Is `false` for basic blocks where we can guarantee the
167 /// opposite. False positives won't lead to incorrect analysis results,
168 /// therefore this approach is fair.
169 BitVector StackAddressUsedBlockInfo;
170
171 /// Check if \p MI uses or defines a callee-saved register or
172 /// a frame index. If this is the case, this means \p MI must happen
173 /// after Save and before Restore.
174 bool useOrDefCSROrFI(const MachineInstr &MI, RegScavenger *RS,
175 bool StackAddressUsed) const;
176
177 const SetOfRegs &getCurrentCSRs(RegScavenger *RS) const {
178 if (CurrentCSRs.empty()) {
179 BitVector SavedRegs;
180 const TargetFrameLowering *TFI =
181 MachineFunc->getSubtarget().getFrameLowering();
182
183 TFI->determineCalleeSaves(*MachineFunc, SavedRegs, RS);
184
185 for (int Reg = SavedRegs.find_first(); Reg != -1;
186 Reg = SavedRegs.find_next(Reg))
187 CurrentCSRs.insert((unsigned)Reg);
188 }
189 return CurrentCSRs;
190 }
191
192 /// Update the Save and Restore points such that \p MBB is in
193 /// the region that is dominated by Save and post-dominated by Restore
194 /// and Save and Restore still match the safe point definition.
195 /// Such point may not exist and Save and/or Restore may be null after
196 /// this call.
197 void updateSaveRestorePoints(MachineBasicBlock &MBB, RegScavenger *RS);
198
199 // Try to find safe point based on dominance and block frequency without
200 // any change in IR.
201 bool performShrinkWrapping(
202 const ReversePostOrderTraversal<MachineBasicBlock *> &RPOT,
203 RegScavenger *RS);
204
205 /// This function tries to split the restore point if doing so can shrink the
206 /// save point further. \return True if restore point is split.
207 bool postShrinkWrapping(bool HasCandidate, MachineFunction &MF,
208 RegScavenger *RS);
209
210 /// This function analyzes if the restore point can split to create a new
211 /// restore point. This function collects
212 /// 1. Any preds of current restore that are reachable by callee save/FI
213 /// blocks
214 /// - indicated by DirtyPreds
215 /// 2. Any preds of current restore that are not DirtyPreds - indicated by
216 /// CleanPreds
217 /// Both sets should be non-empty for considering restore point split.
218 bool checkIfRestoreSplittable(
219 const MachineBasicBlock *CurRestore,
220 const DenseSet<const MachineBasicBlock *> &ReachableByDirty,
221 SmallVectorImpl<MachineBasicBlock *> &DirtyPreds,
222 SmallVectorImpl<MachineBasicBlock *> &CleanPreds,
223 const TargetInstrInfo *TII, RegScavenger *RS);
224
225 /// Initialize the pass for \p MF.
226 void init(MachineFunction &MF) {
227 Save = nullptr;
228 Restore = nullptr;
229 EntryFreq = MBFI->getEntryFreq();
230 const TargetSubtargetInfo &Subtarget = MF.getSubtarget();
231 const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
232 FrameSetupOpcode = TII.getCallFrameSetupOpcode();
233 FrameDestroyOpcode = TII.getCallFrameDestroyOpcode();
235 Entry = &MF.front();
236 CurrentCSRs.clear();
237 MachineFunc = &MF;
238
239 ++NumFunc;
240 }
241
242 /// Check whether or not Save and Restore points are still interesting for
243 /// shrink-wrapping.
244 bool ArePointsInteresting() const { return Save != Entry && Save && Restore; }
245
246public:
247 ShrinkWrapImpl(const RegisterClassInfo *RCI, MachineDominatorTree *MDT,
248 MachinePostDominatorTree *MPDT,
249 MachineBlockFrequencyInfo *MBFI, MachineLoopInfo *MLI,
250 MachineOptimizationRemarkEmitter *ORE)
251 : RCI(RCI), MDT(MDT), MPDT(MPDT), MBFI(MBFI), MLI(MLI), ORE(ORE) {}
252
253 /// Check if shrink wrapping is enabled for this target and function.
254 static bool isShrinkWrapEnabled(const MachineFunction &MF);
255
256 bool run(MachineFunction &MF);
257};
258
259class ShrinkWrapLegacy : public MachineFunctionPass {
260public:
261 static char ID;
262
263 ShrinkWrapLegacy() : MachineFunctionPass(ID) {}
264
265 void getAnalysisUsage(AnalysisUsage &AU) const override {
266 AU.setPreservesAll();
267 AU.addRequired<MachineBlockFrequencyInfoWrapperPass>();
268 AU.addRequired<MachineDominatorTreeWrapperPass>();
269 AU.addRequired<MachinePostDominatorTreeWrapperPass>();
270 AU.addRequired<MachineLoopInfoWrapperPass>();
271 AU.addRequired<MachineOptimizationRemarkEmitterPass>();
272 AU.addRequired<MachineRegisterClassInfoWrapperPass>();
274 }
275
276 MachineFunctionProperties getRequiredProperties() const override {
277 return MachineFunctionProperties().setNoVRegs();
278 }
279
280 StringRef getPassName() const override { return "Shrink Wrapping analysis"; }
281
282 /// Perform the shrink-wrapping analysis and update
283 /// the MachineFrameInfo attached to \p MF with the results.
284 bool runOnMachineFunction(MachineFunction &MF) override;
285};
286
287} // end anonymous namespace
288
289char ShrinkWrapLegacy::ID = 0;
290
291char &llvm::ShrinkWrapID = ShrinkWrapLegacy::ID;
292
293INITIALIZE_PASS_BEGIN(ShrinkWrapLegacy, DEBUG_TYPE, "Shrink Wrap Pass", false,
294 false)
301INITIALIZE_PASS_END(ShrinkWrapLegacy, DEBUG_TYPE, "Shrink Wrap Pass", false,
302 false)
303
304bool ShrinkWrapImpl::useOrDefCSROrFI(const MachineInstr &MI, RegScavenger *RS,
305 bool StackAddressUsed) const {
306 /// Check if \p Op is known to access an address not on the function's stack .
307 /// At the moment, accesses where the underlying object is a global, function
308 /// argument, or jump table are considered non-stack accesses. Note that the
309 /// caller's stack may get accessed when passing an argument via the stack,
310 /// but not the stack of the current function.
311 ///
312 auto IsKnownNonStackPtr = [](MachineMemOperand *Op) {
313 if (Op->getValue()) {
314 const Value *UO = getUnderlyingObject(Op->getValue());
315 if (!UO)
316 return false;
317 if (auto *Arg = dyn_cast<Argument>(UO))
318 return !Arg->hasPassPointeeByValueCopyAttr();
319 return isa<GlobalValue>(UO);
320 }
321 if (const PseudoSourceValue *PSV = Op->getPseudoValue())
322 return PSV->isJumpTable() || PSV->isConstantPool();
323 return false;
324 };
325 // Load/store operations may access the stack indirectly when we previously
326 // computed an address to a stack location.
327 if (StackAddressUsed && MI.mayLoadOrStore() &&
328 (MI.isCall() || MI.hasUnmodeledSideEffects() || MI.memoperands_empty() ||
329 !all_of(MI.memoperands(), IsKnownNonStackPtr)))
330 return true;
331
332 if (MI.getOpcode() == FrameSetupOpcode ||
333 MI.getOpcode() == FrameDestroyOpcode) {
334 LLVM_DEBUG(dbgs() << "Frame instruction: " << MI << '\n');
335 return true;
336 }
337 const MachineFunction *MF = MI.getParent()->getParent();
339 for (const MachineOperand &MO : MI.operands()) {
340 bool UseOrDefCSR = false;
341 if (MO.isReg()) {
342 // Ignore instructions like DBG_VALUE which don't read/def the register.
343 if (!MO.isDef() && !MO.readsReg())
344 continue;
345 Register PhysReg = MO.getReg();
346 if (!PhysReg)
347 continue;
348 assert(PhysReg.isPhysical() && "Unallocated register?!");
349 // The stack pointer is not normally described as a callee-saved register
350 // in calling convention definitions, so we need to watch for it
351 // separately. An SP mentioned by a call instruction, we can ignore,
352 // though, as it's harmless and we do not want to effectively disable tail
353 // calls by forcing the restore point to post-dominate them.
354 // PPC's LR is also not normally described as a callee-saved register in
355 // calling convention definitions, so we need to watch for it, too. An LR
356 // mentioned implicitly by a return (or "branch to link register")
357 // instruction we can ignore, otherwise we may pessimize shrinkwrapping.
358 // PPC's Frame pointer (FP) is also not described as a callee-saved
359 // register. Until the FP is assigned a Physical Register PPC's FP needs
360 // to be checked separately.
361 UseOrDefCSR = (!MI.isCall() && PhysReg == SP) ||
362 RCI->getLastCalleeSavedAlias(PhysReg) ||
363 (!MI.isReturn() &&
364 TRI->isNonallocatableRegisterCalleeSave(PhysReg)) ||
365 TRI->isVirtualFrameRegister(PhysReg);
366 } else if (MO.isRegMask()) {
367 // Check if this regmask clobbers any of the CSRs.
368 for (unsigned Reg : getCurrentCSRs(RS)) {
369 if (MO.clobbersPhysReg(Reg)) {
370 UseOrDefCSR = true;
371 break;
372 }
373 }
374 }
375 // Skip FrameIndex operands in DBG_VALUE instructions.
376 if (UseOrDefCSR || (MO.isFI() && !MI.isDebugValue())) {
377 LLVM_DEBUG(dbgs() << "Use or define CSR(" << UseOrDefCSR << ") or FI("
378 << MO.isFI() << "): " << MI << '\n');
379 return true;
380 }
381 }
382 return false;
383}
384
385/// Helper function to find the immediate (post) dominator.
386template <typename ListOfBBs, typename DominanceAnalysis>
388 DominanceAnalysis &Dom, bool Strict = true) {
389 if (BBs.begin() == BBs.end())
390 return Strict ? nullptr : &Block;
391 MachineBasicBlock *IDom = Dom.findNearestCommonDominator(iterator_range(BBs));
392 if (Strict && IDom == &Block)
393 return nullptr;
394 return IDom;
395}
396
398 MachineBasicBlock &Entry) {
399 // Check if the block is analyzable.
400 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
402 return !TII.analyzeBranch(Entry, TBB, FBB, Cond);
403}
404
405/// Determines if any predecessor of MBB is on the path from block that has use
406/// or def of CSRs/FI to MBB.
407/// ReachableByDirty: All blocks reachable from block that has use or def of
408/// CSR/FI.
409static bool
411 const MachineBasicBlock &MBB) {
412 for (const MachineBasicBlock *PredBB : MBB.predecessors())
413 if (ReachableByDirty.count(PredBB))
414 return true;
415 return false;
416}
417
418/// Derives the list of all the basic blocks reachable from MBB.
420 const MachineBasicBlock &MBB) {
421 SmallVector<MachineBasicBlock *, 4> Worklist(MBB.successors());
422 Visited.insert(&MBB);
423 while (!Worklist.empty()) {
424 MachineBasicBlock *SuccMBB = Worklist.pop_back_val();
425 if (!Visited.insert(SuccMBB).second)
426 continue;
427 Worklist.append(SuccMBB->succ_begin(), SuccMBB->succ_end());
428 }
429}
430
431/// Collect blocks reachable by use or def of CSRs/FI.
434 DenseSet<const MachineBasicBlock *> &ReachableByDirty) {
435 for (const MachineBasicBlock *MBB : DirtyBBs) {
436 if (ReachableByDirty.count(MBB))
437 continue;
438 // Mark all offsprings as reachable.
439 markAllReachable(ReachableByDirty, *MBB);
440 }
441}
442
443/// \return true if there is a clean path from SavePoint to the original
444/// Restore.
445static bool
449 SmallVector<MachineBasicBlock *, 4> Worklist(CleanPreds);
450 while (!Worklist.empty()) {
451 MachineBasicBlock *CleanBB = Worklist.pop_back_val();
452 if (CleanBB == SavePoint)
453 return true;
454 if (!Visited.insert(CleanBB).second || !CleanBB->pred_size())
455 continue;
456 Worklist.append(CleanBB->pred_begin(), CleanBB->pred_end());
457 }
458 return false;
459}
460
461/// This function updates the branches post restore point split.
462///
463/// Restore point has been split.
464/// Old restore point: MBB
465/// New restore point: NMBB
466/// Any basic block(say BBToUpdate) which had a fallthrough to MBB
467/// previously should
468/// 1. Fallthrough to NMBB iff NMBB is inserted immediately above MBB in the
469/// block layout OR
470/// 2. Branch unconditionally to NMBB iff NMBB is inserted at any other place.
471static void updateTerminator(MachineBasicBlock *BBToUpdate,
472 MachineBasicBlock *NMBB,
473 const TargetInstrInfo *TII) {
474 DebugLoc DL = BBToUpdate->findBranchDebugLoc();
475 // if NMBB isn't the new layout successor for BBToUpdate, insert unconditional
476 // branch to it
477 if (!BBToUpdate->isLayoutSuccessor(NMBB))
478 TII->insertUnconditionalBranch(*BBToUpdate, NMBB, DL);
479}
480
481/// This function splits the restore point and returns new restore point/BB.
482///
483/// DirtyPreds: Predessors of \p MBB that are ReachableByDirty
484///
485/// Decision has been made to split the restore point.
486/// old restore point: \p MBB
487/// new restore point: \p NMBB
488/// This function makes the necessary block layout changes so that
489/// 1. \p NMBB points to \p MBB unconditionally
490/// 2. All dirtyPreds that previously pointed to \p MBB point to \p NMBB
491static MachineBasicBlock *
494 const TargetInstrInfo *TII) {
495 MachineFunction *MF = MBB->getParent();
496
497 // get the list of DirtyPreds who have a fallthrough to MBB
498 // before the block layout change. This is just to ensure that if the NMBB is
499 // inserted after MBB, then we create unconditional branch from
500 // DirtyPred/CleanPred to NMBB
502 for (MachineBasicBlock *BB : DirtyPreds)
503 if (BB->getFallThrough(false) == MBB)
504 MBBFallthrough.insert(BB);
505
507 // Insert this block at the end of the function. Inserting in between may
508 // interfere with control flow optimizer decisions.
509 MF->insert(MF->end(), NMBB);
510
511 for (const MachineBasicBlock::RegisterMaskPair &LI : MBB->liveins())
512 NMBB->addLiveIn(LI.PhysReg);
513
514 TII->insertUnconditionalBranch(*NMBB, MBB, DebugLoc());
515
516 // After splitting, all predecessors of the restore point should be dirty
517 // blocks.
518 for (MachineBasicBlock *SuccBB : DirtyPreds)
519 SuccBB->ReplaceUsesOfBlockWith(MBB, NMBB);
520
521 NMBB->addSuccessor(MBB);
522
523 for (MachineBasicBlock *BBToUpdate : MBBFallthrough)
524 updateTerminator(BBToUpdate, NMBB, TII);
525
526 return NMBB;
527}
528
529/// This function undoes the restore point split done earlier.
530///
531/// DirtyPreds: All predecessors of \p NMBB that are ReachableByDirty.
532///
533/// Restore point was split and the change needs to be unrolled. Make necessary
534/// changes to reset restore point from \p NMBB to \p MBB.
538 const TargetInstrInfo *TII) {
539 // For a BB, if NMBB is fallthrough in the current layout, then in the new
540 // layout a. BB should fallthrough to MBB OR b. BB should undconditionally
541 // branch to MBB
543 for (MachineBasicBlock *BB : DirtyPreds)
544 if (BB->getFallThrough(false) == NMBB)
545 NMBBFallthrough.insert(BB);
546
547 NMBB->removeSuccessor(MBB);
548 for (MachineBasicBlock *SuccBB : DirtyPreds)
549 SuccBB->ReplaceUsesOfBlockWith(NMBB, MBB);
550
551 NMBB->erase(NMBB->begin(), NMBB->end());
552 NMBB->eraseFromParent();
553
554 for (MachineBasicBlock *BBToUpdate : NMBBFallthrough)
555 updateTerminator(BBToUpdate, MBB, TII);
556}
557
558// A block is deemed fit for restore point split iff there exist
559// 1. DirtyPreds - preds of CurRestore reachable from use or def of CSR/FI
560// 2. CleanPreds - preds of CurRestore that arent DirtyPreds
561bool ShrinkWrapImpl::checkIfRestoreSplittable(
562 const MachineBasicBlock *CurRestore,
563 const DenseSet<const MachineBasicBlock *> &ReachableByDirty,
566 const TargetInstrInfo *TII, RegScavenger *RS) {
567 for (const MachineInstr &MI : *CurRestore)
568 if (useOrDefCSROrFI(MI, RS, /*StackAddressUsed=*/true))
569 return false;
570
571 for (MachineBasicBlock *PredBB : CurRestore->predecessors()) {
572 if (!isAnalyzableBB(*TII, *PredBB))
573 return false;
574
575 if (ReachableByDirty.count(PredBB))
576 DirtyPreds.push_back(PredBB);
577 else
578 CleanPreds.push_back(PredBB);
579 }
580
581 return !(CleanPreds.empty() || DirtyPreds.empty());
582}
583
584bool ShrinkWrapImpl::postShrinkWrapping(bool HasCandidate, MachineFunction &MF,
585 RegScavenger *RS) {
587 return false;
588
589 MachineBasicBlock *InitSave = nullptr;
590 MachineBasicBlock *InitRestore = nullptr;
591
592 if (HasCandidate) {
593 InitSave = Save;
594 InitRestore = Restore;
595 } else {
596 InitRestore = nullptr;
597 InitSave = &MF.front();
598 for (MachineBasicBlock &MBB : MF) {
599 if (MBB.isEHFuncletEntry())
600 return false;
601 if (MBB.isReturnBlock()) {
602 // Do not support multiple restore points.
603 if (InitRestore)
604 return false;
605 InitRestore = &MBB;
606 }
607 }
608 }
609
610 if (!InitSave || !InitRestore || InitRestore == InitSave ||
611 !MDT->dominates(InitSave, InitRestore) ||
612 !MPDT->dominates(InitRestore, InitSave))
613 return false;
614
615 // Bail out of the optimization if any of the basic block is target of
616 // INLINEASM_BR instruction
617 for (MachineBasicBlock &MBB : MF)
619 return false;
620
621 DenseSet<const MachineBasicBlock *> DirtyBBs;
622 for (MachineBasicBlock &MBB : MF) {
623 if (!MDT->isReachableFromEntry(&MBB))
624 continue;
625 if (MBB.isEHPad()) {
626 DirtyBBs.insert(&MBB);
627 continue;
628 }
629 for (const MachineInstr &MI : MBB)
630 if (useOrDefCSROrFI(MI, RS, /*StackAddressUsed=*/true)) {
631 DirtyBBs.insert(&MBB);
632 break;
633 }
634 }
635
636 // Find blocks reachable from the use or def of CSRs/FI.
637 DenseSet<const MachineBasicBlock *> ReachableByDirty;
638 collectBlocksReachableByDirty(DirtyBBs, ReachableByDirty);
639
640 const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
643 if (!checkIfRestoreSplittable(InitRestore, ReachableByDirty, DirtyPreds,
644 CleanPreds, TII, RS))
645 return false;
646
647 // Trying to reach out to the new save point which dominates all dirty blocks.
648 MachineBasicBlock *NewSave =
649 FindIDom<>(**DirtyPreds.begin(), DirtyPreds, *MDT, false);
650
651 while (NewSave && (hasDirtyPred(ReachableByDirty, *NewSave) ||
652 EntryFreq < MBFI->getBlockFreq(NewSave) ||
653 /*Entry freq has been observed more than a loop block in
654 some cases*/
655 MLI->getLoopFor(NewSave))) {
656 SmallVector<MachineBasicBlock*> ReachablePreds;
657 for (auto BB: NewSave->predecessors())
658 if (MDT->isReachableFromEntry(BB))
659 ReachablePreds.push_back(BB);
660 if (ReachablePreds.empty())
661 break;
662
663 NewSave = FindIDom<>(**ReachablePreds.begin(), ReachablePreds, *MDT,
664 false);
665 }
666
667 const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering();
668 if (!NewSave || NewSave == InitSave ||
669 isSaveReachableThroughClean(NewSave, CleanPreds) ||
670 !TFI->canUseAsPrologue(*NewSave))
671 return false;
672
673 // Now we know that splitting a restore point can isolate the restore point
674 // from clean blocks and doing so can shrink the save point.
675 MachineBasicBlock *NewRestore =
676 tryToSplitRestore(InitRestore, DirtyPreds, TII);
677
678 // Make sure if the new restore point is valid as an epilogue, depending on
679 // targets.
680 if (!TFI->canUseAsEpilogue(*NewRestore)) {
681 rollbackRestoreSplit(MF, NewRestore, InitRestore, DirtyPreds, TII);
682 return false;
683 }
684
685 Save = NewSave;
686 Restore = NewRestore;
687
688 MDT->recalculate(MF);
689 MPDT->recalculate(MF);
690
691 assert((MDT->dominates(Save, Restore) && MPDT->dominates(Restore, Save)) &&
692 "Incorrect save or restore point due to dominance relations");
693 assert((!MLI->getLoopFor(Save) && !MLI->getLoopFor(Restore)) &&
694 "Unexpected save or restore point in a loop");
695 assert((EntryFreq >= MBFI->getBlockFreq(Save) &&
696 EntryFreq >= MBFI->getBlockFreq(Restore)) &&
697 "Incorrect save or restore point based on block frequency");
698 return true;
699}
700
701void ShrinkWrapImpl::updateSaveRestorePoints(MachineBasicBlock &MBB,
702 RegScavenger *RS) {
703 // Get rid of the easy cases first.
704 if (!Save)
705 Save = &MBB;
706 else
707 Save = MDT->findNearestCommonDominator(Save, &MBB);
708 assert(Save);
709
710 if (!Restore)
711 Restore = &MBB;
712 else if (MPDT->getNode(&MBB)) // If the block is not in the post dom tree, it
713 // means the block never returns. If that's the
714 // case, we don't want to call
715 // `findNearestCommonDominator`, which will
716 // return `Restore`.
717 Restore = MPDT->findNearestCommonDominator(Restore, &MBB);
718 else
719 Restore = nullptr; // Abort, we can't find a restore point in this case.
720
721 // Make sure we would be able to insert the restore code before the
722 // terminator.
723 if (Restore == &MBB) {
724 for (const MachineInstr &Terminator : MBB.terminators()) {
725 if (!useOrDefCSROrFI(Terminator, RS, /*StackAddressUsed=*/true))
726 continue;
727 // One of the terminator needs to happen before the restore point.
728 if (MBB.succ_empty()) {
729 Restore = nullptr; // Abort, we can't find a restore point in this case.
730 break;
731 }
732 // Look for a restore point that post-dominates all the successors.
733 // The immediate post-dominator is what we are looking for.
734 Restore = FindIDom<>(*Restore, Restore->successors(), *MPDT);
735 break;
736 }
737 }
738
739 if (!Restore) {
741 dbgs() << "Restore point needs to be spanned on several blocks\n");
742 return;
743 }
744
745 // Make sure Save and Restore are suitable for shrink-wrapping:
746 // 1. all path from Save needs to lead to Restore before exiting.
747 // 2. all path to Restore needs to go through Save from Entry.
748 // We achieve that by making sure that:
749 // A. Save dominates Restore.
750 // B. Restore post-dominates Save.
751 // C. Save and Restore are in the same loop.
752 bool SaveDominatesRestore = false;
753 bool RestorePostDominatesSave = false;
754 while (Restore &&
755 (!(SaveDominatesRestore = MDT->dominates(Save, Restore)) ||
756 !(RestorePostDominatesSave = MPDT->dominates(Restore, Save)) ||
757 // Post-dominance is not enough in loops to ensure that all uses/defs
758 // are after the prologue and before the epilogue at runtime.
759 // E.g.,
760 // while(1) {
761 // Save
762 // Restore
763 // if (...)
764 // break;
765 // use/def CSRs
766 // }
767 // All the uses/defs of CSRs are dominated by Save and post-dominated
768 // by Restore. However, the CSRs uses are still reachable after
769 // Restore and before Save are executed.
770 //
771 // For now, just push the restore/save points outside of loops.
772 // FIXME: Refine the criteria to still find interesting cases
773 // for loops.
774 MLI->getLoopFor(Save) || MLI->getLoopFor(Restore))) {
775 // Fix (A).
776 if (!SaveDominatesRestore) {
777 Save = MDT->findNearestCommonDominator(Save, Restore);
778 continue;
779 }
780 // Fix (B).
781 if (!RestorePostDominatesSave)
782 Restore = MPDT->findNearestCommonDominator(Restore, Save);
783
784 // Fix (C).
785 if (Restore && (MLI->getLoopFor(Save) || MLI->getLoopFor(Restore))) {
786 if (MLI->getLoopDepth(Save) > MLI->getLoopDepth(Restore)) {
787 // Push Save outside of this loop if immediate dominator is different
788 // from save block. If immediate dominator is not different, bail out.
790 for (auto *PBB : Save->predecessors())
791 if (MDT->isReachableFromEntry(PBB))
792 Preds.push_back(PBB);
793 Save = FindIDom<>(*Save, Preds, *MDT);
794 if (!Save)
795 break;
796 } else {
797 // If the loop does not exit, there is no point in looking
798 // for a post-dominator outside the loop.
799 SmallVector<MachineBasicBlock*, 4> ExitBlocks;
800 MLI->getLoopFor(Restore)->getExitingBlocks(ExitBlocks);
801 // Push Restore outside of this loop.
802 // Look for the immediate post-dominator of the loop exits.
803 MachineBasicBlock *IPdom = Restore;
804 for (MachineBasicBlock *LoopExitBB: ExitBlocks) {
805 IPdom = FindIDom<>(*IPdom, LoopExitBB->successors(), *MPDT);
806 if (!IPdom)
807 break;
808 }
809 // If the immediate post-dominator is not in a less nested loop,
810 // then we are stuck in a program with an infinite loop.
811 // In that case, we will not find a safe point, hence, bail out.
812 if (IPdom && MLI->getLoopDepth(IPdom) < MLI->getLoopDepth(Restore))
813 Restore = IPdom;
814 else {
815 Restore = nullptr;
816 break;
817 }
818 }
819 }
820 }
821}
822
824 StringRef RemarkName, StringRef RemarkMessage,
825 const DiagnosticLocation &Loc,
826 const MachineBasicBlock *MBB) {
827 ORE->emit([&]() {
829 << RemarkMessage;
830 });
831
832 LLVM_DEBUG(dbgs() << RemarkMessage << '\n');
833 return false;
834}
835
836bool ShrinkWrapImpl::performShrinkWrapping(
837 const ReversePostOrderTraversal<MachineBasicBlock *> &RPOT,
838 RegScavenger *RS) {
839 for (MachineBasicBlock *MBB : RPOT) {
840 LLVM_DEBUG(dbgs() << "Look into: " << printMBBReference(*MBB) << '\n');
841
842 if (MBB->isEHFuncletEntry())
843 return giveUpWithRemarks(ORE, "UnsupportedEHFunclets",
844 "EH Funclets are not supported yet.",
845 MBB->front().getDebugLoc(), MBB);
846
848 // Push the prologue and epilogue outside of the region that may throw (or
849 // jump out via inlineasm_br), by making sure that all the landing pads
850 // are at least at the boundary of the save and restore points. The
851 // problem is that a basic block can jump out from the middle in these
852 // cases, which we do not handle.
853 updateSaveRestorePoints(*MBB, RS);
854 if (!ArePointsInteresting()) {
855 LLVM_DEBUG(dbgs() << "EHPad/inlineasm_br prevents shrink-wrapping\n");
856 return false;
857 }
858 continue;
859 }
860
861 bool StackAddressUsed = false;
862 // Check if we found any stack accesses in the predecessors. We are not
863 // doing a full dataflow analysis here to keep things simple but just
864 // rely on a reverse portorder traversal (RPOT) to guarantee predecessors
865 // are already processed except for loops (and accept the conservative
866 // result for loops).
867 for (const MachineBasicBlock *Pred : MBB->predecessors()) {
868 if (StackAddressUsedBlockInfo.test(Pred->getNumber())) {
869 StackAddressUsed = true;
870 break;
871 }
872 }
873
874 for (const MachineInstr &MI : *MBB) {
875 if (useOrDefCSROrFI(MI, RS, StackAddressUsed)) {
876 // Save (resp. restore) point must dominate (resp. post dominate)
877 // MI. Look for the proper basic block for those.
878 updateSaveRestorePoints(*MBB, RS);
879 // If we are at a point where we cannot improve the placement of
880 // save/restore instructions, just give up.
881 if (!ArePointsInteresting()) {
882 LLVM_DEBUG(dbgs() << "No Shrink wrap candidate found\n");
883 return false;
884 }
885 // No need to look for other instructions, this basic block
886 // will already be part of the handled region.
887 StackAddressUsed = true;
888 break;
889 }
890 }
891 StackAddressUsedBlockInfo[MBB->getNumber()] = StackAddressUsed;
892 }
893 if (!ArePointsInteresting()) {
894 // If the points are not interesting at this point, then they must be null
895 // because it means we did not encounter any frame/CSR related code.
896 // Otherwise, we would have returned from the previous loop.
897 assert(!Save && !Restore && "We miss a shrink-wrap opportunity?!");
898 LLVM_DEBUG(dbgs() << "Nothing to shrink-wrap\n");
899 return false;
900 }
901
902 LLVM_DEBUG(dbgs() << "\n ** Results **\nFrequency of the Entry: "
903 << EntryFreq.getFrequency() << '\n');
904
905 const TargetFrameLowering *TFI =
906 MachineFunc->getSubtarget().getFrameLowering();
907 do {
908 LLVM_DEBUG(dbgs() << "Shrink wrap candidates (#, Name, Freq):\nSave: "
909 << printMBBReference(*Save) << ' '
910 << printBlockFreq(*MBFI, *Save)
911 << "\nRestore: " << printMBBReference(*Restore) << ' '
912 << printBlockFreq(*MBFI, *Restore) << '\n');
913
914 bool IsSaveCheap, TargetCanUseSaveAsPrologue = false;
915 if (((IsSaveCheap = EntryFreq >= MBFI->getBlockFreq(Save)) &&
916 EntryFreq >= MBFI->getBlockFreq(Restore)) &&
917 ((TargetCanUseSaveAsPrologue = TFI->canUseAsPrologue(*Save)) &&
918 TFI->canUseAsEpilogue(*Restore)))
919 break;
921 dbgs() << "New points are too expensive or invalid for the target\n");
922 MachineBasicBlock *NewBB;
923 if (!IsSaveCheap || !TargetCanUseSaveAsPrologue) {
924 Save = FindIDom<>(*Save, Save->predecessors(), *MDT);
925 if (!Save)
926 break;
927 NewBB = Save;
928 } else {
929 // Restore is expensive.
930 Restore = FindIDom<>(*Restore, Restore->successors(), *MPDT);
931 if (!Restore)
932 break;
933 NewBB = Restore;
934 }
935 updateSaveRestorePoints(*NewBB, RS);
936 } while (Save && Restore);
937
938 if (!ArePointsInteresting()) {
939 ++NumCandidatesDropped;
940 return false;
941 }
942 return true;
943}
944
945bool ShrinkWrapImpl::run(MachineFunction &MF) {
946 LLVM_DEBUG(dbgs() << "**** Analysing " << MF.getName() << '\n');
947
948 init(MF);
949
950 ReversePostOrderTraversal<MachineBasicBlock *> RPOT(&*MF.begin());
952 // If MF is irreducible, a block may be in a loop without
953 // MachineLoopInfo reporting it. I.e., we may use the
954 // post-dominance property in loops, which lead to incorrect
955 // results. Moreover, we may miss that the prologue and
956 // epilogue are not in the same loop, leading to unbalanced
957 // construction/deconstruction of the stack frame.
958 return giveUpWithRemarks(ORE, "UnsupportedIrreducibleCFG",
959 "Irreducible CFGs are not supported yet.",
960 MF.getFunction().getSubprogram(), &MF.front());
961 }
962
963 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
964 std::unique_ptr<RegScavenger> RS(
965 TRI->requiresRegisterScavenging(MF) ? new RegScavenger() : nullptr);
966
967 bool Changed = false;
968
969 // Initially, conservatively assume that stack addresses can be used in each
970 // basic block and change the state only for those basic blocks for which we
971 // were able to prove the opposite.
972 StackAddressUsedBlockInfo.resize(MF.getNumBlockIDs(), true);
973 bool HasCandidate = performShrinkWrapping(RPOT, RS.get());
974 StackAddressUsedBlockInfo.clear();
975 Changed = postShrinkWrapping(HasCandidate, MF, RS.get());
976 if (!HasCandidate && !Changed)
977 return false;
978 if (!ArePointsInteresting())
979 return Changed;
980
981 LLVM_DEBUG(dbgs() << "Final shrink wrap candidates:\nSave: "
982 << printMBBReference(*Save) << ' '
983 << "\nRestore: " << printMBBReference(*Restore) << '\n');
984
985 MachineFrameInfo &MFI = MF.getFrameInfo();
986
987 // List of CalleeSavedInfo for registers will be added during prologepilog
988 // pass
989 SaveRestorePoints SavePoints({{Save, {}}});
990 SaveRestorePoints RestorePoints({{Restore, {}}});
991
992 MFI.setSavePoints(SavePoints);
993 MFI.setRestorePoints(RestorePoints);
994 ++NumCandidates;
995 return Changed;
996}
997
998bool ShrinkWrapLegacy::runOnMachineFunction(MachineFunction &MF) {
999 if (skipFunction(MF.getFunction()) || MF.empty() ||
1000 !ShrinkWrapImpl::isShrinkWrapEnabled(MF))
1001 return false;
1002
1003 const RegisterClassInfo *RCI =
1004 &getAnalysis<MachineRegisterClassInfoWrapperPass>().getRCI();
1005 MachineDominatorTree *MDT =
1006 &getAnalysis<MachineDominatorTreeWrapperPass>().getDomTree();
1007 MachinePostDominatorTree *MPDT =
1008 &getAnalysis<MachinePostDominatorTreeWrapperPass>().getPostDomTree();
1009 MachineBlockFrequencyInfo *MBFI =
1010 &getAnalysis<MachineBlockFrequencyInfoWrapperPass>().getMBFI();
1011 MachineLoopInfo *MLI = &getAnalysis<MachineLoopInfoWrapperPass>().getLI();
1012 MachineOptimizationRemarkEmitter *ORE =
1013 &getAnalysis<MachineOptimizationRemarkEmitterPass>().getORE();
1014
1015 return ShrinkWrapImpl(RCI, MDT, MPDT, MBFI, MLI, ORE).run(MF);
1016}
1017
1020 MFPropsModifier _(*this, MF);
1021 if (MF.empty() || !ShrinkWrapImpl::isShrinkWrapEnabled(MF))
1022 return PreservedAnalyses::all();
1023
1024 const RegisterClassInfo &RCI =
1034
1035 ShrinkWrapImpl(&RCI, &MDT, &MPDT, &MBFI, &MLI, &ORE).run(MF);
1036 return PreservedAnalyses::all();
1037}
1038
1039bool ShrinkWrapImpl::isShrinkWrapEnabled(const MachineFunction &MF) {
1041
1042 switch (EnableShrinkWrapOpt) {
1044 return TFI->enableShrinkWrapping(MF) &&
1045 // Windows with CFI has some limitations that make it impossible
1046 // to use shrink-wrapping.
1048 // Sanitizers look at the value of the stack at the location
1049 // of the crash. Since a crash can happen anywhere, the
1050 // frame must be lowered before anything else happen for the
1051 // sanitizers to be able to get a correct stack frame.
1052 !(MF.getFunction().hasFnAttribute(Attribute::SanitizeAddress) ||
1053 MF.getFunction().hasFnAttribute(Attribute::SanitizeThread) ||
1054 MF.getFunction().hasFnAttribute(Attribute::SanitizeMemory) ||
1055 MF.getFunction().hasFnAttribute(Attribute::SanitizeType) ||
1056 MF.getFunction().hasFnAttribute(Attribute::SanitizeHWAddress));
1057 // If EnableShrinkWrap is set, it takes precedence on whatever the
1058 // target sets. The rational is that we assume we want to test
1059 // something related to shrink-wrapping.
1061 return true;
1063 return false;
1064 }
1065 llvm_unreachable("Invalid shrink-wrapping state");
1066}
for(const MachineOperand &MO :llvm::drop_begin(OldMI.operands(), Desc.getNumOperands()))
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
aarch64 promote const
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
This file contains the simple types necessary to represent the attributes associated with functions a...
This file implements the BitVector class.
#define DEBUG_TYPE
const HexagonInstrInfo * TII
#define _
IRTranslator LLVM IR MI
===- MachineOptimizationRemarkEmitter.h - Opt Diagnostics -*- C++ -*-—===//
Register Reg
Register const TargetRegisterInfo * TRI
if(PassOpts->AAPipeline)
#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
This file builds on the ADT/GraphTraits.h file to build a generic graph post order iterator.
const SmallVectorImpl< MachineOperand > MachineBasicBlock * TBB
const SmallVectorImpl< MachineOperand > & Cond
This file declares the machine register scavenger class.
This file implements a set that has insertion order iteration characteristics.
static void markAllReachable(DenseSet< const MachineBasicBlock * > &Visited, const MachineBasicBlock &MBB)
Derives the list of all the basic blocks reachable from MBB.
static void updateTerminator(MachineBasicBlock *BBToUpdate, MachineBasicBlock *NMBB, const TargetInstrInfo *TII)
This function updates the branches post restore point split.
static MachineBasicBlock * tryToSplitRestore(MachineBasicBlock *MBB, ArrayRef< MachineBasicBlock * > DirtyPreds, const TargetInstrInfo *TII)
This function splits the restore point and returns new restore point/BB.
static bool hasDirtyPred(const DenseSet< const MachineBasicBlock * > &ReachableByDirty, const MachineBasicBlock &MBB)
Determines if any predecessor of MBB is on the path from block that has use or def of CSRs/FI to MBB.
static bool giveUpWithRemarks(MachineOptimizationRemarkEmitter *ORE, StringRef RemarkName, StringRef RemarkMessage, const DiagnosticLocation &Loc, const MachineBasicBlock *MBB)
static cl::opt< bool > EnablePostShrinkWrapOpt("enable-shrink-wrap-region-split", cl::init(true), cl::Hidden, cl::desc("enable splitting of the restore block if possible"))
static void rollbackRestoreSplit(MachineFunction &MF, MachineBasicBlock *NMBB, MachineBasicBlock *MBB, ArrayRef< MachineBasicBlock * > DirtyPreds, const TargetInstrInfo *TII)
This function undoes the restore point split done earlier.
static bool isAnalyzableBB(const TargetInstrInfo &TII, MachineBasicBlock &Entry)
static bool isSaveReachableThroughClean(const MachineBasicBlock *SavePoint, ArrayRef< MachineBasicBlock * > CleanPreds)
static cl::opt< cl::boolOrDefault > EnableShrinkWrapOpt("enable-shrink-wrap", cl::Hidden, cl::desc("enable the shrink-wrapping pass"))
static void collectBlocksReachableByDirty(const DenseSet< const MachineBasicBlock * > &DirtyBBs, DenseSet< const MachineBasicBlock * > &ReachableByDirty)
Collect blocks reachable by use or def of CSRs/FI.
static MachineBasicBlock * FindIDom(MachineBasicBlock &Block, ListOfBBs BBs, DominanceAnalysis &Dom, bool Strict=true)
Helper function to find the immediate (post) dominator.
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
This file describes how to lower LLVM code to machine code.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
AnalysisUsage & addRequired()
void setPreservesAll()
Set by analyses that do not transform their input at all.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
bool test(unsigned Idx) const
Returns true if bit Idx is set.
Definition BitVector.h:482
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
int find_next(unsigned Prev) const
Returns the index of the next set bit following the "Prev" bit.
Definition BitVector.h:324
uint64_t getFrequency() const
Returns the frequency as a fixpoint number scaled by the entry frequency.
A debug info location.
Definition DebugLoc.h:126
Implements a dense probed hash-table based set.
Definition DenseSet.h:281
NodeT * findNearestCommonDominator(NodeT *A, NodeT *B) const
Find nearest common dominator basic block for basic block A and B.
bool dominates(const DomTreeNodeBase< NodeT > *A, const DomTreeNodeBase< NodeT > *B) const
dominates - Returns true iff A dominates B.
void recalculate(ParentType &Func)
recalculate - compute a dominator tree for the given function
bool isReachableFromEntry(const NodeT *A) const
isReachableFromEntry - Return true if A is dominated by the entry block of the function containing it...
DomTreeNodeBase< NodeT > * getNode(const NodeT *BB) const
getNode - return the (Post)DominatorTree node for the specified basic block.
DISubprogram * getSubprogram() const
Get the attached subprogram.
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
Definition Function.cpp:723
void getExitingBlocks(SmallVectorImpl< BlockT * > &ExitingBlocks) const
Return all blocks inside the loop that have successors outside of the loop.
unsigned getLoopDepth(const BlockT *BB) const
Return the loop nesting level of the specified block.
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
bool usesWindowsCFI() const
Definition MCAsmInfo.h:675
An RAII based helper class to modify MachineFunctionProperties when running pass.
bool isInlineAsmBrIndirectTarget() const
Returns true if this is the indirect dest of an INLINEASM_BR.
bool isEHPad() const
Returns true if the block is a landing pad.
int getNumber() const
MachineBasicBlocks are uniquely numbered at the function level, unless they're not in a MachineFuncti...
bool isEHFuncletEntry() const
Returns true if this is the entry block of an EH funclet.
bool isReturnBlock() const
Convenience function that returns true if the block ends in a return instruction.
LLVM_ABI void addSuccessor(MachineBasicBlock *Succ, BranchProbability Prob=BranchProbability::getUnknown())
Add Succ as a successor of this MachineBasicBlock.
LLVM_ABI void removeSuccessor(MachineBasicBlock *Succ, bool NormalizeSuccProbs=false)
Remove successor from the successors list of this MachineBasicBlock.
LLVM_ABI bool isLayoutSuccessor(const MachineBasicBlock *MBB) const
Return true if the specified MBB will be emitted immediately after this block, such that if this bloc...
LLVM_ABI void eraseFromParent()
This method unlinks 'this' from the containing function and deletes it.
void addLiveIn(MCRegister PhysReg, LaneBitmask LaneMask=LaneBitmask::getAll())
Adds the specified register as a live in.
LLVM_ABI instr_iterator erase(instr_iterator I)
Remove an instruction from the instruction list and delete it.
iterator_range< iterator > terminators()
LLVM_ABI DebugLoc findBranchDebugLoc()
Find and return the merged DebugLoc of the branch instructions of the block.
iterator_range< succ_iterator > successors()
iterator_range< pred_iterator > predecessors()
MachineBlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate machine basic b...
LLVM_ABI BlockFrequency getBlockFreq(const MachineBasicBlock *MBB) const
getblockFreq - Return block frequency.
Analysis pass which computes a MachineDominatorTree.
Analysis pass which computes a MachineDominatorTree.
DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to compute a normal dominat...
bool dominates(const MachineInstr *A, const MachineInstr *B) const
void setSavePoints(SaveRestorePoints NewSavePoints)
void setRestorePoints(SaveRestorePoints NewRestorePoints)
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 TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
MachineFrameInfo & getFrameInfo()
getFrameInfo - Return the frame info object for the current function.
Function & getFunction()
Return the LLVM function that this machine code represents.
unsigned getNumBlockIDs() const
getNumBlockIDs - Return the number of MBB ID's allocated.
const MachineBasicBlock & front() const
MachineBasicBlock * CreateMachineBasicBlock(const BasicBlock *BB=nullptr, std::optional< UniqueBBID > BBID=std::nullopt)
CreateMachineInstr - Allocate a new MachineInstr.
void insert(iterator MBBI, MachineBasicBlock *MBB)
const TargetMachine & getTarget() const
getTarget - Return the target machine this machine code is compiled with
Representation of each machine instruction.
const DebugLoc & getDebugLoc() const
Returns the debug location id of this MachineInstr.
Analysis pass that exposes the MachineLoopInfo for a machine function.
A description of a memory reference used in the backend.
MachineOperand class - Representation of each machine instruction operand.
LLVM_ABI Result run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
LLVM_ABI void emit(DiagnosticInfoOptimizationBase &OptDiag)
Emit an optimization remark.
Diagnostic information for missed-optimization remarks.
MachinePostDominatorTree - an analysis pass wrapper for DominatorTree used to compute the post-domina...
LLVM_ABI MachineBasicBlock * findNearestCommonDominator(ArrayRef< MachineBasicBlock * > Blocks) const
Returns the nearest common dominator of the given blocks.
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
Special value supplied for machine level alias analysis.
Wrapper class representing virtual and physical registers.
Definition Register.h:20
LLVM_ABI PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
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
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
Information about stack frame layout on the target.
virtual void determineCalleeSaves(MachineFunction &MF, BitVector &SavedRegs, RegScavenger *RS=nullptr) const
This method determines which of the registers reported by TargetRegisterInfo::getCalleeSavedRegs() sh...
virtual bool enableShrinkWrapping(const MachineFunction &MF) const
Returns true if the target will correctly handle shrink wrapping.
virtual bool canUseAsEpilogue(const MachineBasicBlock &MBB) const
Check whether or not the given MBB can be used as a epilogue for the target.
virtual bool canUseAsPrologue(const MachineBasicBlock &MBB) const
Check whether or not the given MBB can be used as a prologue for the target.
TargetInstrInfo - Interface to description of machine instruction set.
Register getStackPointerRegisterToSaveRestore() const
If a physical register, this specifies the register that llvm.savestack/llvm.restorestack should save...
const MCAsmInfo & getMCAsmInfo() const
Return target specific asm information.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
virtual const TargetFrameLowering * getFrameLowering() const
virtual const TargetInstrInfo * getInstrInfo() const
virtual const TargetRegisterInfo * getRegisterInfo() const =0
Return the target's register information.
virtual const TargetLowering * getTargetLowering() const
LLVM Value Representation.
Definition Value.h:75
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:209
size_type count(const_arg_type_t< ValueT > V) const
Return 1 if the specified key is in the set, 0 otherwise.
Definition DenseSet.h:187
Changed
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
initializer< Ty > init(const Ty &Val)
DXILDebugInfoMap run(Module &M)
This is an optimization pass for GlobalISel generic memory operations.
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
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
LLVM_ABI char & ShrinkWrapID
ShrinkWrap pass. Look for the best place to insert save and restore.
bool containsIrreducibleCFG(RPOTraversalT &RPOTraversal, const LoopInfoT &LI)
Return true if the control flow in RPOTraversal is irreducible.
Definition CFG.h:154
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
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
iterator_range(Container &&) -> iterator_range< llvm::detail::IterOfRange< Container > >
DWARFExpression::Operation Op
LLVM_ABI Printable printBlockFreq(const BlockFrequencyInfo &BFI, BlockFrequency Freq)
Print the block frequency Freq relative to the current functions entry frequency.
LLVM_ABI const Value * getUnderlyingObject(const Value *V, unsigned MaxLookup=MaxLookupSearchDepth)
This method strips off any GEP address adjustments, pointer casts or llvm.threadlocal....
LLVM_ABI Printable printMBBReference(const MachineBasicBlock &MBB)
Prints a machine basic block reference.
Pair of physical register and lane mask.