1 //===-- ShrinkWrap.cpp - Compute safe point for prolog/epilog insertion ---===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This pass looks for safe point where the prologue and epilogue can be 11 // inserted. 12 // The safe point for the prologue (resp. epilogue) is called Save 13 // (resp. Restore). 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. 18 // 19 // For instance, the following points are safe: 20 // for (int i = 0; i < 10; ++i) { 21 // Save 22 // ... 23 // Restore 24 // } 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) { 28 // Save 29 // ... 30 // } 31 // for (int i = 0; i < 10; ++i) { 32 // ... 33 // Restore 34 // } 35 // Indeed, the execution looks like Save -> Save -> ... -> Restore -> Restore. 36 // 37 // This pass also ensures that the safe points are 3) cheaper than the regular 38 // entry and exits blocks. 39 // 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. 45 // 46 // If this pass found points matching all this properties, then 47 // MachineFrameInfo is updated this that information. 48 //===----------------------------------------------------------------------===// 49 #include "llvm/ADT/Statistic.h" 50 // To check for profitability. 51 #include "llvm/CodeGen/MachineBlockFrequencyInfo.h" 52 // For property #1 for Save. 53 #include "llvm/CodeGen/MachineDominators.h" 54 #include "llvm/CodeGen/MachineFunctionPass.h" 55 // To record the result of the analysis. 56 #include "llvm/CodeGen/MachineFrameInfo.h" 57 // For property #2. 58 #include "llvm/CodeGen/MachineLoopInfo.h" 59 // For property #1 for Restore. 60 #include "llvm/CodeGen/MachinePostDominators.h" 61 #include "llvm/CodeGen/Passes.h" 62 // To know about callee-saved. 63 #include "llvm/CodeGen/RegisterClassInfo.h" 64 #include "llvm/Support/Debug.h" 65 // To query the target about frame lowering. 66 #include "llvm/Target/TargetFrameLowering.h" 67 // To know about frame setup operation. 68 #include "llvm/Target/TargetInstrInfo.h" 69 // To access TargetInstrInfo. 70 #include "llvm/Target/TargetSubtargetInfo.h" 71 72 #define DEBUG_TYPE "shrink-wrap" 73 74 using namespace llvm; 75 76 STATISTIC(NumFunc, "Number of functions"); 77 STATISTIC(NumCandidates, "Number of shrink-wrapping candidates"); 78 STATISTIC(NumCandidatesDropped, 79 "Number of shrink-wrapping candidates dropped because of frequency"); 80 81 static cl::opt<cl::boolOrDefault> 82 EnableShrinkWrapOpt("enable-shrink-wrap", cl::Hidden, 83 cl::desc("enable the shrink-wrapping pass")); 84 85 namespace { 86 /// \brief Class to determine where the safe point to insert the 87 /// prologue and epilogue are. 88 /// Unlike the paper from Fred C. Chow, PLDI'88, that introduces the 89 /// shrink-wrapping term for prologue/epilogue placement, this pass 90 /// does not rely on expensive data-flow analysis. Instead we use the 91 /// dominance properties and loop information to decide which point 92 /// are safe for such insertion. 93 class ShrinkWrap : public MachineFunctionPass { 94 /// Hold callee-saved information. 95 RegisterClassInfo RCI; 96 MachineDominatorTree *MDT; 97 MachinePostDominatorTree *MPDT; 98 /// Current safe point found for the prologue. 99 /// The prologue will be inserted before the first instruction 100 /// in this basic block. 101 MachineBasicBlock *Save; 102 /// Current safe point found for the epilogue. 103 /// The epilogue will be inserted before the first terminator instruction 104 /// in this basic block. 105 MachineBasicBlock *Restore; 106 /// Hold the information of the basic block frequency. 107 /// Use to check the profitability of the new points. 108 MachineBlockFrequencyInfo *MBFI; 109 /// Hold the loop information. Used to determine if Save and Restore 110 /// are in the same loop. 111 MachineLoopInfo *MLI; 112 /// Frequency of the Entry block. 113 uint64_t EntryFreq; 114 /// Current opcode for frame setup. 115 unsigned FrameSetupOpcode; 116 /// Current opcode for frame destroy. 117 unsigned FrameDestroyOpcode; 118 /// Entry block. 119 const MachineBasicBlock *Entry; 120 121 /// \brief Check if \p MI uses or defines a callee-saved register or 122 /// a frame index. If this is the case, this means \p MI must happen 123 /// after Save and before Restore. 124 bool useOrDefCSROrFI(const MachineInstr &MI) const; 125 126 /// \brief Update the Save and Restore points such that \p MBB is in 127 /// the region that is dominated by Save and post-dominated by Restore 128 /// and Save and Restore still match the safe point definition. 129 /// Such point may not exist and Save and/or Restore may be null after 130 /// this call. 131 void updateSaveRestorePoints(MachineBasicBlock &MBB); 132 133 /// \brief Initialize the pass for \p MF. 134 void init(MachineFunction &MF) { 135 RCI.runOnMachineFunction(MF); 136 MDT = &getAnalysis<MachineDominatorTree>(); 137 MPDT = &getAnalysis<MachinePostDominatorTree>(); 138 Save = nullptr; 139 Restore = nullptr; 140 MBFI = &getAnalysis<MachineBlockFrequencyInfo>(); 141 MLI = &getAnalysis<MachineLoopInfo>(); 142 EntryFreq = MBFI->getEntryFreq(); 143 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 144 FrameSetupOpcode = TII.getCallFrameSetupOpcode(); 145 FrameDestroyOpcode = TII.getCallFrameDestroyOpcode(); 146 Entry = &MF.front(); 147 148 ++NumFunc; 149 } 150 151 /// Check whether or not Save and Restore points are still interesting for 152 /// shrink-wrapping. 153 bool ArePointsInteresting() const { return Save != Entry && Save && Restore; } 154 155 /// \brief Check if shrink wrapping is enabled for this target and function. 156 static bool isShrinkWrapEnabled(const MachineFunction &MF); 157 158 public: 159 static char ID; 160 161 ShrinkWrap() : MachineFunctionPass(ID) { 162 initializeShrinkWrapPass(*PassRegistry::getPassRegistry()); 163 } 164 165 void getAnalysisUsage(AnalysisUsage &AU) const override { 166 AU.setPreservesAll(); 167 AU.addRequired<MachineBlockFrequencyInfo>(); 168 AU.addRequired<MachineDominatorTree>(); 169 AU.addRequired<MachinePostDominatorTree>(); 170 AU.addRequired<MachineLoopInfo>(); 171 MachineFunctionPass::getAnalysisUsage(AU); 172 } 173 174 const char *getPassName() const override { 175 return "Shrink Wrapping analysis"; 176 } 177 178 /// \brief Perform the shrink-wrapping analysis and update 179 /// the MachineFrameInfo attached to \p MF with the results. 180 bool runOnMachineFunction(MachineFunction &MF) override; 181 }; 182 } // End anonymous namespace. 183 184 char ShrinkWrap::ID = 0; 185 char &llvm::ShrinkWrapID = ShrinkWrap::ID; 186 187 INITIALIZE_PASS_BEGIN(ShrinkWrap, "shrink-wrap", "Shrink Wrap Pass", false, 188 false) 189 INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo) 190 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree) 191 INITIALIZE_PASS_DEPENDENCY(MachinePostDominatorTree) 192 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo) 193 INITIALIZE_PASS_END(ShrinkWrap, "shrink-wrap", "Shrink Wrap Pass", false, false) 194 195 bool ShrinkWrap::useOrDefCSROrFI(const MachineInstr &MI) const { 196 if (MI.getOpcode() == FrameSetupOpcode || 197 MI.getOpcode() == FrameDestroyOpcode) { 198 DEBUG(dbgs() << "Frame instruction: " << MI << '\n'); 199 return true; 200 } 201 for (const MachineOperand &MO : MI.operands()) { 202 bool UseCSR = false; 203 if (MO.isReg()) { 204 unsigned PhysReg = MO.getReg(); 205 if (!PhysReg) 206 continue; 207 assert(TargetRegisterInfo::isPhysicalRegister(PhysReg) && 208 "Unallocated register?!"); 209 UseCSR = RCI.getLastCalleeSavedAlias(PhysReg); 210 } 211 // TODO: Handle regmask more accurately. 212 // For now, be conservative about them. 213 if (UseCSR || MO.isFI() || MO.isRegMask()) { 214 DEBUG(dbgs() << "Use or define CSR(" << UseCSR << ") or FI(" << MO.isFI() 215 << "): " << MI << '\n'); 216 return true; 217 } 218 } 219 return false; 220 } 221 222 /// \brief Helper function to find the immediate (post) dominator. 223 template <typename ListOfBBs, typename DominanceAnalysis> 224 MachineBasicBlock *FindIDom(MachineBasicBlock &Block, ListOfBBs BBs, 225 DominanceAnalysis &Dom) { 226 MachineBasicBlock *IDom = &Block; 227 for (MachineBasicBlock *BB : BBs) { 228 IDom = Dom.findNearestCommonDominator(IDom, BB); 229 if (!IDom) 230 break; 231 } 232 return IDom; 233 } 234 235 void ShrinkWrap::updateSaveRestorePoints(MachineBasicBlock &MBB) { 236 // Get rid of the easy cases first. 237 if (!Save) 238 Save = &MBB; 239 else 240 Save = MDT->findNearestCommonDominator(Save, &MBB); 241 242 if (!Save) { 243 DEBUG(dbgs() << "Found a block that is not reachable from Entry\n"); 244 return; 245 } 246 247 if (!Restore) 248 Restore = &MBB; 249 else 250 Restore = MPDT->findNearestCommonDominator(Restore, &MBB); 251 252 // Make sure we would be able to insert the restore code before the 253 // terminator. 254 if (Restore == &MBB) { 255 for (const MachineInstr &Terminator : MBB.terminators()) { 256 if (!useOrDefCSROrFI(Terminator)) 257 continue; 258 // One of the terminator needs to happen before the restore point. 259 if (MBB.succ_empty()) { 260 Restore = nullptr; 261 break; 262 } 263 // Look for a restore point that post-dominates all the successors. 264 // The immediate post-dominator is what we are looking for. 265 Restore = FindIDom<>(*Restore, Restore->successors(), *MPDT); 266 break; 267 } 268 } 269 270 if (!Restore) { 271 DEBUG(dbgs() << "Restore point needs to be spanned on several blocks\n"); 272 return; 273 } 274 275 // Make sure Save and Restore are suitable for shrink-wrapping: 276 // 1. all path from Save needs to lead to Restore before exiting. 277 // 2. all path to Restore needs to go through Save from Entry. 278 // We achieve that by making sure that: 279 // A. Save dominates Restore. 280 // B. Restore post-dominates Save. 281 // C. Save and Restore are in the same loop. 282 bool SaveDominatesRestore = false; 283 bool RestorePostDominatesSave = false; 284 while (Save && Restore && 285 (!(SaveDominatesRestore = MDT->dominates(Save, Restore)) || 286 !(RestorePostDominatesSave = MPDT->dominates(Restore, Save)) || 287 MLI->getLoopFor(Save) != MLI->getLoopFor(Restore))) { 288 // Fix (A). 289 if (!SaveDominatesRestore) { 290 Save = MDT->findNearestCommonDominator(Save, Restore); 291 continue; 292 } 293 // Fix (B). 294 if (!RestorePostDominatesSave) 295 Restore = MPDT->findNearestCommonDominator(Restore, Save); 296 297 // Fix (C). 298 if (Save && Restore && Save != Restore && 299 MLI->getLoopFor(Save) != MLI->getLoopFor(Restore)) { 300 if (MLI->getLoopDepth(Save) > MLI->getLoopDepth(Restore)) { 301 // Push Save outside of this loop if immediate dominator is different 302 // from save block. If immediate dominator is not different, bail out. 303 MachineBasicBlock *IDom = FindIDom<>(*Save, Save->predecessors(), *MDT); 304 if (IDom != Save) 305 Save = IDom; 306 else { 307 Save = nullptr; 308 break; 309 } 310 } 311 else { 312 // If the loop does not exit, there is no point in looking 313 // for a post-dominator outside the loop. 314 SmallVector<MachineBasicBlock*, 4> ExitBlocks; 315 MLI->getLoopFor(Restore)->getExitingBlocks(ExitBlocks); 316 // Push Restore outside of this loop. 317 // Look for the immediate post-dominator of the loop exits. 318 MachineBasicBlock *IPdom = Restore; 319 for (MachineBasicBlock *LoopExitBB: ExitBlocks) { 320 IPdom = FindIDom<>(*IPdom, LoopExitBB->successors(), *MPDT); 321 if (!IPdom) 322 break; 323 } 324 // If the immediate post-dominator is not in a less nested loop, 325 // then we are stuck in a program with an infinite loop. 326 // In that case, we will not find a safe point, hence, bail out. 327 if (IPdom && MLI->getLoopDepth(IPdom) < MLI->getLoopDepth(Restore)) 328 Restore = IPdom; 329 else { 330 Restore = nullptr; 331 break; 332 } 333 } 334 } 335 } 336 } 337 338 bool ShrinkWrap::runOnMachineFunction(MachineFunction &MF) { 339 if (MF.empty() || !isShrinkWrapEnabled(MF)) 340 return false; 341 342 DEBUG(dbgs() << "**** Analysing " << MF.getName() << '\n'); 343 344 init(MF); 345 346 for (MachineBasicBlock &MBB : MF) { 347 DEBUG(dbgs() << "Look into: " << MBB.getNumber() << ' ' << MBB.getName() 348 << '\n'); 349 350 for (const MachineInstr &MI : MBB) { 351 if (!useOrDefCSROrFI(MI)) 352 continue; 353 // Save (resp. restore) point must dominate (resp. post dominate) 354 // MI. Look for the proper basic block for those. 355 updateSaveRestorePoints(MBB); 356 // If we are at a point where we cannot improve the placement of 357 // save/restore instructions, just give up. 358 if (!ArePointsInteresting()) { 359 DEBUG(dbgs() << "No Shrink wrap candidate found\n"); 360 return false; 361 } 362 // No need to look for other instructions, this basic block 363 // will already be part of the handled region. 364 break; 365 } 366 } 367 if (!ArePointsInteresting()) { 368 // If the points are not interesting at this point, then they must be null 369 // because it means we did not encounter any frame/CSR related code. 370 // Otherwise, we would have returned from the previous loop. 371 assert(!Save && !Restore && "We miss a shrink-wrap opportunity?!"); 372 DEBUG(dbgs() << "Nothing to shrink-wrap\n"); 373 return false; 374 } 375 376 DEBUG(dbgs() << "\n ** Results **\nFrequency of the Entry: " << EntryFreq 377 << '\n'); 378 379 const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering(); 380 do { 381 DEBUG(dbgs() << "Shrink wrap candidates (#, Name, Freq):\nSave: " 382 << Save->getNumber() << ' ' << Save->getName() << ' ' 383 << MBFI->getBlockFreq(Save).getFrequency() << "\nRestore: " 384 << Restore->getNumber() << ' ' << Restore->getName() << ' ' 385 << MBFI->getBlockFreq(Restore).getFrequency() << '\n'); 386 387 bool IsSaveCheap, TargetCanUseSaveAsPrologue = false; 388 if (((IsSaveCheap = EntryFreq >= MBFI->getBlockFreq(Save).getFrequency()) && 389 EntryFreq >= MBFI->getBlockFreq(Restore).getFrequency()) && 390 ((TargetCanUseSaveAsPrologue = TFI->canUseAsPrologue(*Save)) && 391 TFI->canUseAsEpilogue(*Restore))) 392 break; 393 DEBUG(dbgs() << "New points are too expensive or invalid for the target\n"); 394 MachineBasicBlock *NewBB; 395 if (!IsSaveCheap || !TargetCanUseSaveAsPrologue) { 396 Save = FindIDom<>(*Save, Save->predecessors(), *MDT); 397 if (!Save) 398 break; 399 NewBB = Save; 400 } else { 401 // Restore is expensive. 402 Restore = FindIDom<>(*Restore, Restore->successors(), *MPDT); 403 if (!Restore) 404 break; 405 NewBB = Restore; 406 } 407 updateSaveRestorePoints(*NewBB); 408 } while (Save && Restore); 409 410 if (!ArePointsInteresting()) { 411 ++NumCandidatesDropped; 412 return false; 413 } 414 415 DEBUG(dbgs() << "Final shrink wrap candidates:\nSave: " << Save->getNumber() 416 << ' ' << Save->getName() << "\nRestore: " 417 << Restore->getNumber() << ' ' << Restore->getName() << '\n'); 418 419 MachineFrameInfo *MFI = MF.getFrameInfo(); 420 MFI->setSavePoint(Save); 421 MFI->setRestorePoint(Restore); 422 ++NumCandidates; 423 return false; 424 } 425 426 bool ShrinkWrap::isShrinkWrapEnabled(const MachineFunction &MF) { 427 const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering(); 428 429 switch (EnableShrinkWrapOpt) { 430 case cl::BOU_UNSET: 431 return TFI->enableShrinkWrapping(MF); 432 // If EnableShrinkWrap is set, it takes precedence on whatever the 433 // target sets. The rational is that we assume we want to test 434 // something related to shrink-wrapping. 435 case cl::BOU_TRUE: 436 return true; 437 case cl::BOU_FALSE: 438 return false; 439 } 440 llvm_unreachable("Invalid shrink-wrapping state"); 441 } 442