ShrinkWrap.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617
  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. #include "llvm/ADT/BitVector.h"
  50. #include "llvm/ADT/PostOrderIterator.h"
  51. #include "llvm/ADT/SetVector.h"
  52. #include "llvm/ADT/SmallVector.h"
  53. #include "llvm/ADT/Statistic.h"
  54. #include "llvm/Analysis/CFG.h"
  55. #include "llvm/CodeGen/MachineBasicBlock.h"
  56. #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
  57. #include "llvm/CodeGen/MachineDominators.h"
  58. #include "llvm/CodeGen/MachineFrameInfo.h"
  59. #include "llvm/CodeGen/MachineFunction.h"
  60. #include "llvm/CodeGen/MachineFunctionPass.h"
  61. #include "llvm/CodeGen/MachineInstr.h"
  62. #include "llvm/CodeGen/MachineLoopInfo.h"
  63. #include "llvm/CodeGen/MachineOperand.h"
  64. #include "llvm/CodeGen/MachineOptimizationRemarkEmitter.h"
  65. #include "llvm/CodeGen/MachinePostDominators.h"
  66. #include "llvm/CodeGen/RegisterClassInfo.h"
  67. #include "llvm/CodeGen/RegisterScavenging.h"
  68. #include "llvm/CodeGen/TargetFrameLowering.h"
  69. #include "llvm/CodeGen/TargetInstrInfo.h"
  70. #include "llvm/CodeGen/TargetLowering.h"
  71. #include "llvm/CodeGen/TargetRegisterInfo.h"
  72. #include "llvm/CodeGen/TargetSubtargetInfo.h"
  73. #include "llvm/IR/Attributes.h"
  74. #include "llvm/IR/Function.h"
  75. #include "llvm/MC/MCAsmInfo.h"
  76. #include "llvm/Pass.h"
  77. #include "llvm/Support/CommandLine.h"
  78. #include "llvm/Support/Debug.h"
  79. #include "llvm/Support/ErrorHandling.h"
  80. #include "llvm/Support/raw_ostream.h"
  81. #include "llvm/Target/TargetMachine.h"
  82. #include <cassert>
  83. #include <cstdint>
  84. #include <memory>
  85. using namespace llvm;
  86. #define DEBUG_TYPE "shrink-wrap"
  87. STATISTIC(NumFunc, "Number of functions");
  88. STATISTIC(NumCandidates, "Number of shrink-wrapping candidates");
  89. STATISTIC(NumCandidatesDropped,
  90. "Number of shrink-wrapping candidates dropped because of frequency");
  91. static cl::opt<cl::boolOrDefault>
  92. EnableShrinkWrapOpt("enable-shrink-wrap", cl::Hidden,
  93. cl::desc("enable the shrink-wrapping pass"));
  94. namespace {
  95. /// Class to determine where the safe point to insert the
  96. /// prologue and epilogue are.
  97. /// Unlike the paper from Fred C. Chow, PLDI'88, that introduces the
  98. /// shrink-wrapping term for prologue/epilogue placement, this pass
  99. /// does not rely on expensive data-flow analysis. Instead we use the
  100. /// dominance properties and loop information to decide which point
  101. /// are safe for such insertion.
  102. class ShrinkWrap : public MachineFunctionPass {
  103. /// Hold callee-saved information.
  104. RegisterClassInfo RCI;
  105. MachineDominatorTree *MDT;
  106. MachinePostDominatorTree *MPDT;
  107. /// Current safe point found for the prologue.
  108. /// The prologue will be inserted before the first instruction
  109. /// in this basic block.
  110. MachineBasicBlock *Save;
  111. /// Current safe point found for the epilogue.
  112. /// The epilogue will be inserted before the first terminator instruction
  113. /// in this basic block.
  114. MachineBasicBlock *Restore;
  115. /// Hold the information of the basic block frequency.
  116. /// Use to check the profitability of the new points.
  117. MachineBlockFrequencyInfo *MBFI;
  118. /// Hold the loop information. Used to determine if Save and Restore
  119. /// are in the same loop.
  120. MachineLoopInfo *MLI;
  121. // Emit remarks.
  122. MachineOptimizationRemarkEmitter *ORE = nullptr;
  123. /// Frequency of the Entry block.
  124. uint64_t EntryFreq;
  125. /// Current opcode for frame setup.
  126. unsigned FrameSetupOpcode;
  127. /// Current opcode for frame destroy.
  128. unsigned FrameDestroyOpcode;
  129. /// Stack pointer register, used by llvm.{savestack,restorestack}
  130. unsigned SP;
  131. /// Entry block.
  132. const MachineBasicBlock *Entry;
  133. using SetOfRegs = SmallSetVector<unsigned, 16>;
  134. /// Registers that need to be saved for the current function.
  135. mutable SetOfRegs CurrentCSRs;
  136. /// Current MachineFunction.
  137. MachineFunction *MachineFunc;
  138. /// Check if \p MI uses or defines a callee-saved register or
  139. /// a frame index. If this is the case, this means \p MI must happen
  140. /// after Save and before Restore.
  141. bool useOrDefCSROrFI(const MachineInstr &MI, RegScavenger *RS) const;
  142. const SetOfRegs &getCurrentCSRs(RegScavenger *RS) const {
  143. if (CurrentCSRs.empty()) {
  144. BitVector SavedRegs;
  145. const TargetFrameLowering *TFI =
  146. MachineFunc->getSubtarget().getFrameLowering();
  147. TFI->determineCalleeSaves(*MachineFunc, SavedRegs, RS);
  148. for (int Reg = SavedRegs.find_first(); Reg != -1;
  149. Reg = SavedRegs.find_next(Reg))
  150. CurrentCSRs.insert((unsigned)Reg);
  151. }
  152. return CurrentCSRs;
  153. }
  154. /// Update the Save and Restore points such that \p MBB is in
  155. /// the region that is dominated by Save and post-dominated by Restore
  156. /// and Save and Restore still match the safe point definition.
  157. /// Such point may not exist and Save and/or Restore may be null after
  158. /// this call.
  159. void updateSaveRestorePoints(MachineBasicBlock &MBB, RegScavenger *RS);
  160. /// Initialize the pass for \p MF.
  161. void init(MachineFunction &MF) {
  162. RCI.runOnMachineFunction(MF);
  163. MDT = &getAnalysis<MachineDominatorTree>();
  164. MPDT = &getAnalysis<MachinePostDominatorTree>();
  165. Save = nullptr;
  166. Restore = nullptr;
  167. MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
  168. MLI = &getAnalysis<MachineLoopInfo>();
  169. ORE = &getAnalysis<MachineOptimizationRemarkEmitterPass>().getORE();
  170. EntryFreq = MBFI->getEntryFreq();
  171. const TargetSubtargetInfo &Subtarget = MF.getSubtarget();
  172. const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
  173. FrameSetupOpcode = TII.getCallFrameSetupOpcode();
  174. FrameDestroyOpcode = TII.getCallFrameDestroyOpcode();
  175. SP = Subtarget.getTargetLowering()->getStackPointerRegisterToSaveRestore();
  176. Entry = &MF.front();
  177. CurrentCSRs.clear();
  178. MachineFunc = &MF;
  179. ++NumFunc;
  180. }
  181. /// Check whether or not Save and Restore points are still interesting for
  182. /// shrink-wrapping.
  183. bool ArePointsInteresting() const { return Save != Entry && Save && Restore; }
  184. /// Check if shrink wrapping is enabled for this target and function.
  185. static bool isShrinkWrapEnabled(const MachineFunction &MF);
  186. public:
  187. static char ID;
  188. ShrinkWrap() : MachineFunctionPass(ID) {
  189. initializeShrinkWrapPass(*PassRegistry::getPassRegistry());
  190. }
  191. void getAnalysisUsage(AnalysisUsage &AU) const override {
  192. AU.setPreservesAll();
  193. AU.addRequired<MachineBlockFrequencyInfo>();
  194. AU.addRequired<MachineDominatorTree>();
  195. AU.addRequired<MachinePostDominatorTree>();
  196. AU.addRequired<MachineLoopInfo>();
  197. AU.addRequired<MachineOptimizationRemarkEmitterPass>();
  198. MachineFunctionPass::getAnalysisUsage(AU);
  199. }
  200. MachineFunctionProperties getRequiredProperties() const override {
  201. return MachineFunctionProperties().set(
  202. MachineFunctionProperties::Property::NoVRegs);
  203. }
  204. StringRef getPassName() const override { return "Shrink Wrapping analysis"; }
  205. /// Perform the shrink-wrapping analysis and update
  206. /// the MachineFrameInfo attached to \p MF with the results.
  207. bool runOnMachineFunction(MachineFunction &MF) override;
  208. };
  209. } // end anonymous namespace
  210. char ShrinkWrap::ID = 0;
  211. char &llvm::ShrinkWrapID = ShrinkWrap::ID;
  212. INITIALIZE_PASS_BEGIN(ShrinkWrap, DEBUG_TYPE, "Shrink Wrap Pass", false, false)
  213. INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
  214. INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
  215. INITIALIZE_PASS_DEPENDENCY(MachinePostDominatorTree)
  216. INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
  217. INITIALIZE_PASS_DEPENDENCY(MachineOptimizationRemarkEmitterPass)
  218. INITIALIZE_PASS_END(ShrinkWrap, DEBUG_TYPE, "Shrink Wrap Pass", false, false)
  219. bool ShrinkWrap::useOrDefCSROrFI(const MachineInstr &MI,
  220. RegScavenger *RS) const {
  221. // This prevents premature stack popping when occurs a indirect stack
  222. // access. It is overly aggressive for the moment.
  223. // TODO: - Obvious non-stack loads and store, such as global values,
  224. // are known to not access the stack.
  225. // - Further, data dependency and alias analysis can validate
  226. // that load and stores never derive from the stack pointer.
  227. if (MI.mayLoadOrStore())
  228. return true;
  229. if (MI.getOpcode() == FrameSetupOpcode ||
  230. MI.getOpcode() == FrameDestroyOpcode) {
  231. LLVM_DEBUG(dbgs() << "Frame instruction: " << MI << '\n');
  232. return true;
  233. }
  234. for (const MachineOperand &MO : MI.operands()) {
  235. bool UseOrDefCSR = false;
  236. if (MO.isReg()) {
  237. // Ignore instructions like DBG_VALUE which don't read/def the register.
  238. if (!MO.isDef() && !MO.readsReg())
  239. continue;
  240. Register PhysReg = MO.getReg();
  241. if (!PhysReg)
  242. continue;
  243. assert(Register::isPhysicalRegister(PhysReg) && "Unallocated register?!");
  244. // The stack pointer is not normally described as a callee-saved register
  245. // in calling convention definitions, so we need to watch for it
  246. // separately. An SP mentioned by a call instruction, we can ignore,
  247. // though, as it's harmless and we do not want to effectively disable tail
  248. // calls by forcing the restore point to post-dominate them.
  249. UseOrDefCSR = (!MI.isCall() && PhysReg == SP) ||
  250. RCI.getLastCalleeSavedAlias(PhysReg);
  251. } else if (MO.isRegMask()) {
  252. // Check if this regmask clobbers any of the CSRs.
  253. for (unsigned Reg : getCurrentCSRs(RS)) {
  254. if (MO.clobbersPhysReg(Reg)) {
  255. UseOrDefCSR = true;
  256. break;
  257. }
  258. }
  259. }
  260. // Skip FrameIndex operands in DBG_VALUE instructions.
  261. if (UseOrDefCSR || (MO.isFI() && !MI.isDebugValue())) {
  262. LLVM_DEBUG(dbgs() << "Use or define CSR(" << UseOrDefCSR << ") or FI("
  263. << MO.isFI() << "): " << MI << '\n');
  264. return true;
  265. }
  266. }
  267. return false;
  268. }
  269. /// Helper function to find the immediate (post) dominator.
  270. template <typename ListOfBBs, typename DominanceAnalysis>
  271. static MachineBasicBlock *FindIDom(MachineBasicBlock &Block, ListOfBBs BBs,
  272. DominanceAnalysis &Dom) {
  273. MachineBasicBlock *IDom = &Block;
  274. for (MachineBasicBlock *BB : BBs) {
  275. IDom = Dom.findNearestCommonDominator(IDom, BB);
  276. if (!IDom)
  277. break;
  278. }
  279. if (IDom == &Block)
  280. return nullptr;
  281. return IDom;
  282. }
  283. void ShrinkWrap::updateSaveRestorePoints(MachineBasicBlock &MBB,
  284. RegScavenger *RS) {
  285. // Get rid of the easy cases first.
  286. if (!Save)
  287. Save = &MBB;
  288. else
  289. Save = MDT->findNearestCommonDominator(Save, &MBB);
  290. if (!Save) {
  291. LLVM_DEBUG(dbgs() << "Found a block that is not reachable from Entry\n");
  292. return;
  293. }
  294. if (!Restore)
  295. Restore = &MBB;
  296. else if (MPDT->getNode(&MBB)) // If the block is not in the post dom tree, it
  297. // means the block never returns. If that's the
  298. // case, we don't want to call
  299. // `findNearestCommonDominator`, which will
  300. // return `Restore`.
  301. Restore = MPDT->findNearestCommonDominator(Restore, &MBB);
  302. else
  303. Restore = nullptr; // Abort, we can't find a restore point in this case.
  304. // Make sure we would be able to insert the restore code before the
  305. // terminator.
  306. if (Restore == &MBB) {
  307. for (const MachineInstr &Terminator : MBB.terminators()) {
  308. if (!useOrDefCSROrFI(Terminator, RS))
  309. continue;
  310. // One of the terminator needs to happen before the restore point.
  311. if (MBB.succ_empty()) {
  312. Restore = nullptr; // Abort, we can't find a restore point in this case.
  313. break;
  314. }
  315. // Look for a restore point that post-dominates all the successors.
  316. // The immediate post-dominator is what we are looking for.
  317. Restore = FindIDom<>(*Restore, Restore->successors(), *MPDT);
  318. break;
  319. }
  320. }
  321. if (!Restore) {
  322. LLVM_DEBUG(
  323. dbgs() << "Restore point needs to be spanned on several blocks\n");
  324. return;
  325. }
  326. // Make sure Save and Restore are suitable for shrink-wrapping:
  327. // 1. all path from Save needs to lead to Restore before exiting.
  328. // 2. all path to Restore needs to go through Save from Entry.
  329. // We achieve that by making sure that:
  330. // A. Save dominates Restore.
  331. // B. Restore post-dominates Save.
  332. // C. Save and Restore are in the same loop.
  333. bool SaveDominatesRestore = false;
  334. bool RestorePostDominatesSave = false;
  335. while (Save && Restore &&
  336. (!(SaveDominatesRestore = MDT->dominates(Save, Restore)) ||
  337. !(RestorePostDominatesSave = MPDT->dominates(Restore, Save)) ||
  338. // Post-dominance is not enough in loops to ensure that all uses/defs
  339. // are after the prologue and before the epilogue at runtime.
  340. // E.g.,
  341. // while(1) {
  342. // Save
  343. // Restore
  344. // if (...)
  345. // break;
  346. // use/def CSRs
  347. // }
  348. // All the uses/defs of CSRs are dominated by Save and post-dominated
  349. // by Restore. However, the CSRs uses are still reachable after
  350. // Restore and before Save are executed.
  351. //
  352. // For now, just push the restore/save points outside of loops.
  353. // FIXME: Refine the criteria to still find interesting cases
  354. // for loops.
  355. MLI->getLoopFor(Save) || MLI->getLoopFor(Restore))) {
  356. // Fix (A).
  357. if (!SaveDominatesRestore) {
  358. Save = MDT->findNearestCommonDominator(Save, Restore);
  359. continue;
  360. }
  361. // Fix (B).
  362. if (!RestorePostDominatesSave)
  363. Restore = MPDT->findNearestCommonDominator(Restore, Save);
  364. // Fix (C).
  365. if (Save && Restore &&
  366. (MLI->getLoopFor(Save) || MLI->getLoopFor(Restore))) {
  367. if (MLI->getLoopDepth(Save) > MLI->getLoopDepth(Restore)) {
  368. // Push Save outside of this loop if immediate dominator is different
  369. // from save block. If immediate dominator is not different, bail out.
  370. Save = FindIDom<>(*Save, Save->predecessors(), *MDT);
  371. if (!Save)
  372. break;
  373. } else {
  374. // If the loop does not exit, there is no point in looking
  375. // for a post-dominator outside the loop.
  376. SmallVector<MachineBasicBlock*, 4> ExitBlocks;
  377. MLI->getLoopFor(Restore)->getExitingBlocks(ExitBlocks);
  378. // Push Restore outside of this loop.
  379. // Look for the immediate post-dominator of the loop exits.
  380. MachineBasicBlock *IPdom = Restore;
  381. for (MachineBasicBlock *LoopExitBB: ExitBlocks) {
  382. IPdom = FindIDom<>(*IPdom, LoopExitBB->successors(), *MPDT);
  383. if (!IPdom)
  384. break;
  385. }
  386. // If the immediate post-dominator is not in a less nested loop,
  387. // then we are stuck in a program with an infinite loop.
  388. // In that case, we will not find a safe point, hence, bail out.
  389. if (IPdom && MLI->getLoopDepth(IPdom) < MLI->getLoopDepth(Restore))
  390. Restore = IPdom;
  391. else {
  392. Restore = nullptr;
  393. break;
  394. }
  395. }
  396. }
  397. }
  398. }
  399. static bool giveUpWithRemarks(MachineOptimizationRemarkEmitter *ORE,
  400. StringRef RemarkName, StringRef RemarkMessage,
  401. const DiagnosticLocation &Loc,
  402. const MachineBasicBlock *MBB) {
  403. ORE->emit([&]() {
  404. return MachineOptimizationRemarkMissed(DEBUG_TYPE, RemarkName, Loc, MBB)
  405. << RemarkMessage;
  406. });
  407. LLVM_DEBUG(dbgs() << RemarkMessage << '\n');
  408. return false;
  409. }
  410. bool ShrinkWrap::runOnMachineFunction(MachineFunction &MF) {
  411. if (skipFunction(MF.getFunction()) || MF.empty() || !isShrinkWrapEnabled(MF))
  412. return false;
  413. LLVM_DEBUG(dbgs() << "**** Analysing " << MF.getName() << '\n');
  414. init(MF);
  415. ReversePostOrderTraversal<MachineBasicBlock *> RPOT(&*MF.begin());
  416. if (containsIrreducibleCFG<MachineBasicBlock *>(RPOT, *MLI)) {
  417. // If MF is irreducible, a block may be in a loop without
  418. // MachineLoopInfo reporting it. I.e., we may use the
  419. // post-dominance property in loops, which lead to incorrect
  420. // results. Moreover, we may miss that the prologue and
  421. // epilogue are not in the same loop, leading to unbalanced
  422. // construction/deconstruction of the stack frame.
  423. return giveUpWithRemarks(ORE, "UnsupportedIrreducibleCFG",
  424. "Irreducible CFGs are not supported yet.",
  425. MF.getFunction().getSubprogram(), &MF.front());
  426. }
  427. const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
  428. std::unique_ptr<RegScavenger> RS(
  429. TRI->requiresRegisterScavenging(MF) ? new RegScavenger() : nullptr);
  430. for (MachineBasicBlock &MBB : MF) {
  431. LLVM_DEBUG(dbgs() << "Look into: " << MBB.getNumber() << ' '
  432. << MBB.getName() << '\n');
  433. if (MBB.isEHFuncletEntry())
  434. return giveUpWithRemarks(ORE, "UnsupportedEHFunclets",
  435. "EH Funclets are not supported yet.",
  436. MBB.front().getDebugLoc(), &MBB);
  437. if (MBB.isEHPad()) {
  438. // Push the prologue and epilogue outside of
  439. // the region that may throw by making sure
  440. // that all the landing pads are at least at the
  441. // boundary of the save and restore points.
  442. // The problem with exceptions is that the throw
  443. // is not properly modeled and in particular, a
  444. // basic block can jump out from the middle.
  445. updateSaveRestorePoints(MBB, RS.get());
  446. if (!ArePointsInteresting()) {
  447. LLVM_DEBUG(dbgs() << "EHPad prevents shrink-wrapping\n");
  448. return false;
  449. }
  450. continue;
  451. }
  452. for (const MachineInstr &MI : MBB) {
  453. if (!useOrDefCSROrFI(MI, RS.get()))
  454. continue;
  455. // Save (resp. restore) point must dominate (resp. post dominate)
  456. // MI. Look for the proper basic block for those.
  457. updateSaveRestorePoints(MBB, RS.get());
  458. // If we are at a point where we cannot improve the placement of
  459. // save/restore instructions, just give up.
  460. if (!ArePointsInteresting()) {
  461. LLVM_DEBUG(dbgs() << "No Shrink wrap candidate found\n");
  462. return false;
  463. }
  464. // No need to look for other instructions, this basic block
  465. // will already be part of the handled region.
  466. break;
  467. }
  468. }
  469. if (!ArePointsInteresting()) {
  470. // If the points are not interesting at this point, then they must be null
  471. // because it means we did not encounter any frame/CSR related code.
  472. // Otherwise, we would have returned from the previous loop.
  473. assert(!Save && !Restore && "We miss a shrink-wrap opportunity?!");
  474. LLVM_DEBUG(dbgs() << "Nothing to shrink-wrap\n");
  475. return false;
  476. }
  477. LLVM_DEBUG(dbgs() << "\n ** Results **\nFrequency of the Entry: " << EntryFreq
  478. << '\n');
  479. const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering();
  480. do {
  481. LLVM_DEBUG(dbgs() << "Shrink wrap candidates (#, Name, Freq):\nSave: "
  482. << Save->getNumber() << ' ' << Save->getName() << ' '
  483. << MBFI->getBlockFreq(Save).getFrequency()
  484. << "\nRestore: " << Restore->getNumber() << ' '
  485. << Restore->getName() << ' '
  486. << MBFI->getBlockFreq(Restore).getFrequency() << '\n');
  487. bool IsSaveCheap, TargetCanUseSaveAsPrologue = false;
  488. if (((IsSaveCheap = EntryFreq >= MBFI->getBlockFreq(Save).getFrequency()) &&
  489. EntryFreq >= MBFI->getBlockFreq(Restore).getFrequency()) &&
  490. ((TargetCanUseSaveAsPrologue = TFI->canUseAsPrologue(*Save)) &&
  491. TFI->canUseAsEpilogue(*Restore)))
  492. break;
  493. LLVM_DEBUG(
  494. dbgs() << "New points are too expensive or invalid for the target\n");
  495. MachineBasicBlock *NewBB;
  496. if (!IsSaveCheap || !TargetCanUseSaveAsPrologue) {
  497. Save = FindIDom<>(*Save, Save->predecessors(), *MDT);
  498. if (!Save)
  499. break;
  500. NewBB = Save;
  501. } else {
  502. // Restore is expensive.
  503. Restore = FindIDom<>(*Restore, Restore->successors(), *MPDT);
  504. if (!Restore)
  505. break;
  506. NewBB = Restore;
  507. }
  508. updateSaveRestorePoints(*NewBB, RS.get());
  509. } while (Save && Restore);
  510. if (!ArePointsInteresting()) {
  511. ++NumCandidatesDropped;
  512. return false;
  513. }
  514. LLVM_DEBUG(dbgs() << "Final shrink wrap candidates:\nSave: "
  515. << Save->getNumber() << ' ' << Save->getName()
  516. << "\nRestore: " << Restore->getNumber() << ' '
  517. << Restore->getName() << '\n');
  518. MachineFrameInfo &MFI = MF.getFrameInfo();
  519. MFI.setSavePoint(Save);
  520. MFI.setRestorePoint(Restore);
  521. ++NumCandidates;
  522. return false;
  523. }
  524. bool ShrinkWrap::isShrinkWrapEnabled(const MachineFunction &MF) {
  525. const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering();
  526. switch (EnableShrinkWrapOpt) {
  527. case cl::BOU_UNSET:
  528. return TFI->enableShrinkWrapping(MF) &&
  529. // Windows with CFI has some limitations that make it impossible
  530. // to use shrink-wrapping.
  531. !MF.getTarget().getMCAsmInfo()->usesWindowsCFI() &&
  532. // Sanitizers look at the value of the stack at the location
  533. // of the crash. Since a crash can happen anywhere, the
  534. // frame must be lowered before anything else happen for the
  535. // sanitizers to be able to get a correct stack frame.
  536. !(MF.getFunction().hasFnAttribute(Attribute::SanitizeAddress) ||
  537. MF.getFunction().hasFnAttribute(Attribute::SanitizeThread) ||
  538. MF.getFunction().hasFnAttribute(Attribute::SanitizeMemory) ||
  539. MF.getFunction().hasFnAttribute(Attribute::SanitizeHWAddress));
  540. // If EnableShrinkWrap is set, it takes precedence on whatever the
  541. // target sets. The rational is that we assume we want to test
  542. // something related to shrink-wrapping.
  543. case cl::BOU_TRUE:
  544. return true;
  545. case cl::BOU_FALSE:
  546. return false;
  547. }
  548. llvm_unreachable("Invalid shrink-wrapping state");
  549. }