1 //===-- ShrinkWrap.cpp - Compute safe point for prolog/epilog insertion ---===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This pass looks for safe point where the prologue and epilogue can be
12 // The safe point for the prologue (resp. epilogue) is called Save
14 // A point is safe for prologue (resp. epilogue) if and only if
15 // it 1) dominates (resp. post-dominates) all the frame related operations and
16 // between 2) two executions of the Save (resp. Restore) point there is an
17 // execution of the Restore (resp. Save) point.
19 // For instance, the following points are safe:
20 // for (int i = 0; i < 10; ++i) {
25 // Indeed, the execution looks like Save -> Restore -> Save -> Restore ...
26 // And the following points are not:
27 // for (int i = 0; i < 10; ++i) {
31 // for (int i = 0; i < 10; ++i) {
35 // Indeed, the execution looks like Save -> Save -> ... -> Restore -> Restore.
37 // This pass also ensures that the safe points are 3) cheaper than the regular
38 // entry and exits blocks.
40 // Property #1 is ensured via the use of MachineDominatorTree and
41 // MachinePostDominatorTree.
42 // Property #2 is ensured via property #1 and MachineLoopInfo, i.e., both
43 // points must be in the same loop.
44 // Property #3 is ensured via the MachineBlockFrequencyInfo.
46 // If this pass found points matching all these properties, then
47 // MachineFrameInfo is updated with this information.
48 //===----------------------------------------------------------------------===//
49 #include "llvm/ADT/BitVector.h"
50 #include "llvm/ADT/SetVector.h"
51 #include "llvm/ADT/Statistic.h"
52 // To check for profitability.
53 #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
54 // For property #1 for Save.
55 #include "llvm/CodeGen/MachineDominators.h"
56 #include "llvm/CodeGen/MachineFunctionPass.h"
57 // To record the result of the analysis.
58 #include "llvm/CodeGen/MachineFrameInfo.h"
60 #include "llvm/CodeGen/MachineLoopInfo.h"
61 // For property #1 for Restore.
62 #include "llvm/CodeGen/MachinePostDominators.h"
63 #include "llvm/CodeGen/Passes.h"
64 // To know about callee-saved.
65 #include "llvm/CodeGen/RegisterClassInfo.h"
66 #include "llvm/CodeGen/RegisterScavenging.h"
67 #include "llvm/MC/MCAsmInfo.h"
68 #include "llvm/Support/Debug.h"
69 // To query the target about frame lowering.
70 #include "llvm/Target/TargetFrameLowering.h"
71 // To know about frame setup operation.
72 #include "llvm/Target/TargetInstrInfo.h"
73 #include "llvm/Target/TargetMachine.h"
74 // To access TargetInstrInfo.
75 #include "llvm/Target/TargetSubtargetInfo.h"
77 #define DEBUG_TYPE "shrink-wrap"
81 STATISTIC(NumFunc, "Number of functions");
82 STATISTIC(NumCandidates, "Number of shrink-wrapping candidates");
83 STATISTIC(NumCandidatesDropped,
84 "Number of shrink-wrapping candidates dropped because of frequency");
86 static cl::opt<cl::boolOrDefault>
87 EnableShrinkWrapOpt("enable-shrink-wrap", cl::Hidden,
88 cl::desc("enable the shrink-wrapping pass"));
91 /// \brief Class to determine where the safe point to insert the
92 /// prologue and epilogue are.
93 /// Unlike the paper from Fred C. Chow, PLDI'88, that introduces the
94 /// shrink-wrapping term for prologue/epilogue placement, this pass
95 /// does not rely on expensive data-flow analysis. Instead we use the
96 /// dominance properties and loop information to decide which point
97 /// are safe for such insertion.
98 class ShrinkWrap : public MachineFunctionPass {
99 /// Hold callee-saved information.
100 RegisterClassInfo RCI;
101 MachineDominatorTree *MDT;
102 MachinePostDominatorTree *MPDT;
103 /// Current safe point found for the prologue.
104 /// The prologue will be inserted before the first instruction
105 /// in this basic block.
106 MachineBasicBlock *Save;
107 /// Current safe point found for the epilogue.
108 /// The epilogue will be inserted before the first terminator instruction
109 /// in this basic block.
110 MachineBasicBlock *Restore;
111 /// Hold the information of the basic block frequency.
112 /// Use to check the profitability of the new points.
113 MachineBlockFrequencyInfo *MBFI;
114 /// Hold the loop information. Used to determine if Save and Restore
115 /// are in the same loop.
116 MachineLoopInfo *MLI;
117 /// Frequency of the Entry block.
119 /// Current opcode for frame setup.
120 unsigned FrameSetupOpcode;
121 /// Current opcode for frame destroy.
122 unsigned FrameDestroyOpcode;
124 const MachineBasicBlock *Entry;
125 typedef SmallSetVector<unsigned, 16> SetOfRegs;
126 /// Registers that need to be saved for the current function.
127 mutable SetOfRegs CurrentCSRs;
128 /// Current MachineFunction.
129 MachineFunction *MachineFunc;
131 /// \brief Check if \p MI uses or defines a callee-saved register or
132 /// a frame index. If this is the case, this means \p MI must happen
133 /// after Save and before Restore.
134 bool useOrDefCSROrFI(const MachineInstr &MI, RegScavenger *RS) const;
136 const SetOfRegs &getCurrentCSRs(RegScavenger *RS) const {
137 if (CurrentCSRs.empty()) {
139 const TargetFrameLowering *TFI =
140 MachineFunc->getSubtarget().getFrameLowering();
142 TFI->determineCalleeSaves(*MachineFunc, SavedRegs, RS);
144 for (int Reg = SavedRegs.find_first(); Reg != -1;
145 Reg = SavedRegs.find_next(Reg))
146 CurrentCSRs.insert((unsigned)Reg);
151 /// \brief Update the Save and Restore points such that \p MBB is in
152 /// the region that is dominated by Save and post-dominated by Restore
153 /// and Save and Restore still match the safe point definition.
154 /// Such point may not exist and Save and/or Restore may be null after
156 void updateSaveRestorePoints(MachineBasicBlock &MBB, RegScavenger *RS);
158 /// \brief Initialize the pass for \p MF.
159 void init(MachineFunction &MF) {
160 RCI.runOnMachineFunction(MF);
161 MDT = &getAnalysis<MachineDominatorTree>();
162 MPDT = &getAnalysis<MachinePostDominatorTree>();
165 MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
166 MLI = &getAnalysis<MachineLoopInfo>();
167 EntryFreq = MBFI->getEntryFreq();
168 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
169 FrameSetupOpcode = TII.getCallFrameSetupOpcode();
170 FrameDestroyOpcode = TII.getCallFrameDestroyOpcode();
178 /// Check whether or not Save and Restore points are still interesting for
180 bool ArePointsInteresting() const { return Save != Entry && Save && Restore; }
182 /// \brief Check if shrink wrapping is enabled for this target and function.
183 static bool isShrinkWrapEnabled(const MachineFunction &MF);
188 ShrinkWrap() : MachineFunctionPass(ID) {
189 initializeShrinkWrapPass(*PassRegistry::getPassRegistry());
192 void getAnalysisUsage(AnalysisUsage &AU) const override {
193 AU.setPreservesAll();
194 AU.addRequired<MachineBlockFrequencyInfo>();
195 AU.addRequired<MachineDominatorTree>();
196 AU.addRequired<MachinePostDominatorTree>();
197 AU.addRequired<MachineLoopInfo>();
198 MachineFunctionPass::getAnalysisUsage(AU);
201 const char *getPassName() const override {
202 return "Shrink Wrapping analysis";
205 /// \brief Perform the shrink-wrapping analysis and update
206 /// the MachineFrameInfo attached to \p MF with the results.
207 bool runOnMachineFunction(MachineFunction &MF) override;
209 } // End anonymous namespace.
211 char ShrinkWrap::ID = 0;
212 char &llvm::ShrinkWrapID = ShrinkWrap::ID;
214 INITIALIZE_PASS_BEGIN(ShrinkWrap, "shrink-wrap", "Shrink Wrap Pass", false,
216 INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
217 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
218 INITIALIZE_PASS_DEPENDENCY(MachinePostDominatorTree)
219 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
220 INITIALIZE_PASS_END(ShrinkWrap, "shrink-wrap", "Shrink Wrap Pass", false, false)
222 bool ShrinkWrap::useOrDefCSROrFI(const MachineInstr &MI,
223 RegScavenger *RS) const {
224 if (MI.getOpcode() == FrameSetupOpcode ||
225 MI.getOpcode() == FrameDestroyOpcode) {
226 DEBUG(dbgs() << "Frame instruction: " << MI << '\n');
229 for (const MachineOperand &MO : MI.operands()) {
230 bool UseOrDefCSR = false;
232 unsigned PhysReg = MO.getReg();
235 assert(TargetRegisterInfo::isPhysicalRegister(PhysReg) &&
236 "Unallocated register?!");
237 UseOrDefCSR = RCI.getLastCalleeSavedAlias(PhysReg);
238 } else if (MO.isRegMask()) {
239 // Check if this regmask clobbers any of the CSRs.
240 for (unsigned Reg : getCurrentCSRs(RS)) {
241 if (MO.clobbersPhysReg(Reg)) {
247 if (UseOrDefCSR || MO.isFI()) {
248 DEBUG(dbgs() << "Use or define CSR(" << UseOrDefCSR << ") or FI("
249 << MO.isFI() << "): " << MI << '\n');
256 /// \brief Helper function to find the immediate (post) dominator.
257 template <typename ListOfBBs, typename DominanceAnalysis>
258 MachineBasicBlock *FindIDom(MachineBasicBlock &Block, ListOfBBs BBs,
259 DominanceAnalysis &Dom) {
260 MachineBasicBlock *IDom = &Block;
261 for (MachineBasicBlock *BB : BBs) {
262 IDom = Dom.findNearestCommonDominator(IDom, BB);
271 void ShrinkWrap::updateSaveRestorePoints(MachineBasicBlock &MBB,
273 // Get rid of the easy cases first.
277 Save = MDT->findNearestCommonDominator(Save, &MBB);
280 DEBUG(dbgs() << "Found a block that is not reachable from Entry\n");
287 Restore = MPDT->findNearestCommonDominator(Restore, &MBB);
289 // Make sure we would be able to insert the restore code before the
291 if (Restore == &MBB) {
292 for (const MachineInstr &Terminator : MBB.terminators()) {
293 if (!useOrDefCSROrFI(Terminator, RS))
295 // One of the terminator needs to happen before the restore point.
296 if (MBB.succ_empty()) {
300 // Look for a restore point that post-dominates all the successors.
301 // The immediate post-dominator is what we are looking for.
302 Restore = FindIDom<>(*Restore, Restore->successors(), *MPDT);
308 DEBUG(dbgs() << "Restore point needs to be spanned on several blocks\n");
312 // Make sure Save and Restore are suitable for shrink-wrapping:
313 // 1. all path from Save needs to lead to Restore before exiting.
314 // 2. all path to Restore needs to go through Save from Entry.
315 // We achieve that by making sure that:
316 // A. Save dominates Restore.
317 // B. Restore post-dominates Save.
318 // C. Save and Restore are in the same loop.
319 bool SaveDominatesRestore = false;
320 bool RestorePostDominatesSave = false;
321 while (Save && Restore &&
322 (!(SaveDominatesRestore = MDT->dominates(Save, Restore)) ||
323 !(RestorePostDominatesSave = MPDT->dominates(Restore, Save)) ||
324 // Post-dominance is not enough in loops to ensure that all uses/defs
325 // are after the prologue and before the epilogue at runtime.
334 // All the uses/defs of CSRs are dominated by Save and post-dominated
335 // by Restore. However, the CSRs uses are still reachable after
336 // Restore and before Save are executed.
338 // For now, just push the restore/save points outside of loops.
339 // FIXME: Refine the criteria to still find interesting cases
341 MLI->getLoopFor(Save) || MLI->getLoopFor(Restore))) {
343 if (!SaveDominatesRestore) {
344 Save = MDT->findNearestCommonDominator(Save, Restore);
348 if (!RestorePostDominatesSave)
349 Restore = MPDT->findNearestCommonDominator(Restore, Save);
352 if (Save && Restore &&
353 (MLI->getLoopFor(Save) || MLI->getLoopFor(Restore))) {
354 if (MLI->getLoopDepth(Save) > MLI->getLoopDepth(Restore)) {
355 // Push Save outside of this loop if immediate dominator is different
356 // from save block. If immediate dominator is not different, bail out.
357 Save = FindIDom<>(*Save, Save->predecessors(), *MDT);
361 // If the loop does not exit, there is no point in looking
362 // for a post-dominator outside the loop.
363 SmallVector<MachineBasicBlock*, 4> ExitBlocks;
364 MLI->getLoopFor(Restore)->getExitingBlocks(ExitBlocks);
365 // Push Restore outside of this loop.
366 // Look for the immediate post-dominator of the loop exits.
367 MachineBasicBlock *IPdom = Restore;
368 for (MachineBasicBlock *LoopExitBB: ExitBlocks) {
369 IPdom = FindIDom<>(*IPdom, LoopExitBB->successors(), *MPDT);
373 // If the immediate post-dominator is not in a less nested loop,
374 // then we are stuck in a program with an infinite loop.
375 // In that case, we will not find a safe point, hence, bail out.
376 if (IPdom && MLI->getLoopDepth(IPdom) < MLI->getLoopDepth(Restore))
387 bool ShrinkWrap::runOnMachineFunction(MachineFunction &MF) {
388 if (MF.empty() || !isShrinkWrapEnabled(MF))
391 DEBUG(dbgs() << "**** Analysing " << MF.getName() << '\n');
395 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
396 std::unique_ptr<RegScavenger> RS(
397 TRI->requiresRegisterScavenging(MF) ? new RegScavenger() : nullptr);
399 for (MachineBasicBlock &MBB : MF) {
400 DEBUG(dbgs() << "Look into: " << MBB.getNumber() << ' ' << MBB.getName()
403 if (MBB.isEHFuncletEntry()) {
404 DEBUG(dbgs() << "EH Funclets are not supported yet.\n");
408 for (const MachineInstr &MI : MBB) {
409 if (!useOrDefCSROrFI(MI, RS.get()))
411 // Save (resp. restore) point must dominate (resp. post dominate)
412 // MI. Look for the proper basic block for those.
413 updateSaveRestorePoints(MBB, RS.get());
414 // If we are at a point where we cannot improve the placement of
415 // save/restore instructions, just give up.
416 if (!ArePointsInteresting()) {
417 DEBUG(dbgs() << "No Shrink wrap candidate found\n");
420 // No need to look for other instructions, this basic block
421 // will already be part of the handled region.
425 if (!ArePointsInteresting()) {
426 // If the points are not interesting at this point, then they must be null
427 // because it means we did not encounter any frame/CSR related code.
428 // Otherwise, we would have returned from the previous loop.
429 assert(!Save && !Restore && "We miss a shrink-wrap opportunity?!");
430 DEBUG(dbgs() << "Nothing to shrink-wrap\n");
434 DEBUG(dbgs() << "\n ** Results **\nFrequency of the Entry: " << EntryFreq
437 const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering();
439 DEBUG(dbgs() << "Shrink wrap candidates (#, Name, Freq):\nSave: "
440 << Save->getNumber() << ' ' << Save->getName() << ' '
441 << MBFI->getBlockFreq(Save).getFrequency() << "\nRestore: "
442 << Restore->getNumber() << ' ' << Restore->getName() << ' '
443 << MBFI->getBlockFreq(Restore).getFrequency() << '\n');
445 bool IsSaveCheap, TargetCanUseSaveAsPrologue = false;
446 if (((IsSaveCheap = EntryFreq >= MBFI->getBlockFreq(Save).getFrequency()) &&
447 EntryFreq >= MBFI->getBlockFreq(Restore).getFrequency()) &&
448 ((TargetCanUseSaveAsPrologue = TFI->canUseAsPrologue(*Save)) &&
449 TFI->canUseAsEpilogue(*Restore)))
451 DEBUG(dbgs() << "New points are too expensive or invalid for the target\n");
452 MachineBasicBlock *NewBB;
453 if (!IsSaveCheap || !TargetCanUseSaveAsPrologue) {
454 Save = FindIDom<>(*Save, Save->predecessors(), *MDT);
459 // Restore is expensive.
460 Restore = FindIDom<>(*Restore, Restore->successors(), *MPDT);
465 updateSaveRestorePoints(*NewBB, RS.get());
466 } while (Save && Restore);
468 if (!ArePointsInteresting()) {
469 ++NumCandidatesDropped;
473 DEBUG(dbgs() << "Final shrink wrap candidates:\nSave: " << Save->getNumber()
474 << ' ' << Save->getName() << "\nRestore: "
475 << Restore->getNumber() << ' ' << Restore->getName() << '\n');
477 MachineFrameInfo *MFI = MF.getFrameInfo();
478 MFI->setSavePoint(Save);
479 MFI->setRestorePoint(Restore);
484 bool ShrinkWrap::isShrinkWrapEnabled(const MachineFunction &MF) {
485 const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering();
487 switch (EnableShrinkWrapOpt) {
489 return TFI->enableShrinkWrapping(MF) &&
490 // Windows with CFI has some limitations that make it impossible
491 // to use shrink-wrapping.
492 !MF.getTarget().getMCAsmInfo()->usesWindowsCFI() &&
493 // Sanitizers look at the value of the stack at the location
494 // of the crash. Since a crash can happen anywhere, the
495 // frame must be lowered before anything else happen for the
496 // sanitizers to be able to get a correct stack frame.
497 !(MF.getFunction()->hasFnAttribute(Attribute::SanitizeAddress) ||
498 MF.getFunction()->hasFnAttribute(Attribute::SanitizeThread) ||
499 MF.getFunction()->hasFnAttribute(Attribute::SanitizeMemory));
500 // If EnableShrinkWrap is set, it takes precedence on whatever the
501 // target sets. The rational is that we assume we want to test
502 // something related to shrink-wrapping.
508 llvm_unreachable("Invalid shrink-wrapping state");