MachineSink.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812
  1. //===-- MachineSink.cpp - Sinking for machine instructions ----------------===//
  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 moves instructions into successor blocks when possible, so that
  11. // they aren't executed on paths where their results aren't needed.
  12. //
  13. // This pass is not intended to be a replacement or a complete alternative
  14. // for an LLVM-IR-level sinking pass. It is only designed to sink simple
  15. // constructs that are not exposed before lowering and instruction selection.
  16. //
  17. //===----------------------------------------------------------------------===//
  18. #include "llvm/CodeGen/Passes.h"
  19. #include "llvm/ADT/SetVector.h"
  20. #include "llvm/ADT/SmallSet.h"
  21. #include "llvm/ADT/SparseBitVector.h"
  22. #include "llvm/ADT/Statistic.h"
  23. #include "llvm/Analysis/AliasAnalysis.h"
  24. #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
  25. #include "llvm/CodeGen/MachineDominators.h"
  26. #include "llvm/CodeGen/MachineLoopInfo.h"
  27. #include "llvm/CodeGen/MachinePostDominators.h"
  28. #include "llvm/CodeGen/MachineRegisterInfo.h"
  29. #include "llvm/Support/CommandLine.h"
  30. #include "llvm/Support/Debug.h"
  31. #include "llvm/Support/raw_ostream.h"
  32. #include "llvm/Target/TargetInstrInfo.h"
  33. #include "llvm/Target/TargetRegisterInfo.h"
  34. #include "llvm/Target/TargetSubtargetInfo.h"
  35. using namespace llvm;
  36. #define DEBUG_TYPE "machine-sink"
  37. static cl::opt<bool>
  38. SplitEdges("machine-sink-split",
  39. cl::desc("Split critical edges during machine sinking"),
  40. cl::init(true), cl::Hidden);
  41. static cl::opt<bool>
  42. UseBlockFreqInfo("machine-sink-bfi",
  43. cl::desc("Use block frequency info to find successors to sink"),
  44. cl::init(true), cl::Hidden);
  45. STATISTIC(NumSunk, "Number of machine instructions sunk");
  46. STATISTIC(NumSplit, "Number of critical edges split");
  47. STATISTIC(NumCoalesces, "Number of copies coalesced");
  48. namespace {
  49. class MachineSinking : public MachineFunctionPass {
  50. const TargetInstrInfo *TII;
  51. const TargetRegisterInfo *TRI;
  52. MachineRegisterInfo *MRI; // Machine register information
  53. MachineDominatorTree *DT; // Machine dominator tree
  54. MachinePostDominatorTree *PDT; // Machine post dominator tree
  55. MachineLoopInfo *LI;
  56. const MachineBlockFrequencyInfo *MBFI;
  57. AliasAnalysis *AA;
  58. // Remember which edges have been considered for breaking.
  59. SmallSet<std::pair<MachineBasicBlock*,MachineBasicBlock*>, 8>
  60. CEBCandidates;
  61. // Remember which edges we are about to split.
  62. // This is different from CEBCandidates since those edges
  63. // will be split.
  64. SetVector<std::pair<MachineBasicBlock*,MachineBasicBlock*> > ToSplit;
  65. SparseBitVector<> RegsToClearKillFlags;
  66. typedef std::map<MachineBasicBlock *, SmallVector<MachineBasicBlock *, 4>>
  67. AllSuccsCache;
  68. public:
  69. static char ID; // Pass identification
  70. MachineSinking() : MachineFunctionPass(ID) {
  71. initializeMachineSinkingPass(*PassRegistry::getPassRegistry());
  72. }
  73. bool runOnMachineFunction(MachineFunction &MF) override;
  74. void getAnalysisUsage(AnalysisUsage &AU) const override {
  75. AU.setPreservesCFG();
  76. MachineFunctionPass::getAnalysisUsage(AU);
  77. AU.addRequired<AliasAnalysis>();
  78. AU.addRequired<MachineDominatorTree>();
  79. AU.addRequired<MachinePostDominatorTree>();
  80. AU.addRequired<MachineLoopInfo>();
  81. AU.addPreserved<MachineDominatorTree>();
  82. AU.addPreserved<MachinePostDominatorTree>();
  83. AU.addPreserved<MachineLoopInfo>();
  84. if (UseBlockFreqInfo)
  85. AU.addRequired<MachineBlockFrequencyInfo>();
  86. }
  87. void releaseMemory() override {
  88. CEBCandidates.clear();
  89. }
  90. private:
  91. bool ProcessBlock(MachineBasicBlock &MBB);
  92. bool isWorthBreakingCriticalEdge(MachineInstr *MI,
  93. MachineBasicBlock *From,
  94. MachineBasicBlock *To);
  95. /// \brief Postpone the splitting of the given critical
  96. /// edge (\p From, \p To).
  97. ///
  98. /// We do not split the edges on the fly. Indeed, this invalidates
  99. /// the dominance information and thus triggers a lot of updates
  100. /// of that information underneath.
  101. /// Instead, we postpone all the splits after each iteration of
  102. /// the main loop. That way, the information is at least valid
  103. /// for the lifetime of an iteration.
  104. ///
  105. /// \return True if the edge is marked as toSplit, false otherwise.
  106. /// False can be returned if, for instance, this is not profitable.
  107. bool PostponeSplitCriticalEdge(MachineInstr *MI,
  108. MachineBasicBlock *From,
  109. MachineBasicBlock *To,
  110. bool BreakPHIEdge);
  111. bool SinkInstruction(MachineInstr *MI, bool &SawStore,
  112. AllSuccsCache &AllSuccessors);
  113. bool AllUsesDominatedByBlock(unsigned Reg, MachineBasicBlock *MBB,
  114. MachineBasicBlock *DefMBB,
  115. bool &BreakPHIEdge, bool &LocalUse) const;
  116. MachineBasicBlock *FindSuccToSinkTo(MachineInstr *MI, MachineBasicBlock *MBB,
  117. bool &BreakPHIEdge, AllSuccsCache &AllSuccessors);
  118. bool isProfitableToSinkTo(unsigned Reg, MachineInstr *MI,
  119. MachineBasicBlock *MBB,
  120. MachineBasicBlock *SuccToSinkTo,
  121. AllSuccsCache &AllSuccessors);
  122. bool PerformTrivialForwardCoalescing(MachineInstr *MI,
  123. MachineBasicBlock *MBB);
  124. SmallVector<MachineBasicBlock *, 4> &
  125. GetAllSortedSuccessors(MachineInstr *MI, MachineBasicBlock *MBB,
  126. AllSuccsCache &AllSuccessors) const;
  127. };
  128. } // end anonymous namespace
  129. char MachineSinking::ID = 0;
  130. char &llvm::MachineSinkingID = MachineSinking::ID;
  131. INITIALIZE_PASS_BEGIN(MachineSinking, "machine-sink",
  132. "Machine code sinking", false, false)
  133. INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
  134. INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
  135. INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
  136. INITIALIZE_PASS_END(MachineSinking, "machine-sink",
  137. "Machine code sinking", false, false)
  138. bool MachineSinking::PerformTrivialForwardCoalescing(MachineInstr *MI,
  139. MachineBasicBlock *MBB) {
  140. if (!MI->isCopy())
  141. return false;
  142. unsigned SrcReg = MI->getOperand(1).getReg();
  143. unsigned DstReg = MI->getOperand(0).getReg();
  144. if (!TargetRegisterInfo::isVirtualRegister(SrcReg) ||
  145. !TargetRegisterInfo::isVirtualRegister(DstReg) ||
  146. !MRI->hasOneNonDBGUse(SrcReg))
  147. return false;
  148. const TargetRegisterClass *SRC = MRI->getRegClass(SrcReg);
  149. const TargetRegisterClass *DRC = MRI->getRegClass(DstReg);
  150. if (SRC != DRC)
  151. return false;
  152. MachineInstr *DefMI = MRI->getVRegDef(SrcReg);
  153. if (DefMI->isCopyLike())
  154. return false;
  155. DEBUG(dbgs() << "Coalescing: " << *DefMI);
  156. DEBUG(dbgs() << "*** to: " << *MI);
  157. MRI->replaceRegWith(DstReg, SrcReg);
  158. MI->eraseFromParent();
  159. // Conservatively, clear any kill flags, since it's possible that they are no
  160. // longer correct.
  161. MRI->clearKillFlags(SrcReg);
  162. ++NumCoalesces;
  163. return true;
  164. }
  165. /// AllUsesDominatedByBlock - Return true if all uses of the specified register
  166. /// occur in blocks dominated by the specified block. If any use is in the
  167. /// definition block, then return false since it is never legal to move def
  168. /// after uses.
  169. bool
  170. MachineSinking::AllUsesDominatedByBlock(unsigned Reg,
  171. MachineBasicBlock *MBB,
  172. MachineBasicBlock *DefMBB,
  173. bool &BreakPHIEdge,
  174. bool &LocalUse) const {
  175. assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
  176. "Only makes sense for vregs");
  177. // Ignore debug uses because debug info doesn't affect the code.
  178. if (MRI->use_nodbg_empty(Reg))
  179. return true;
  180. // BreakPHIEdge is true if all the uses are in the successor MBB being sunken
  181. // into and they are all PHI nodes. In this case, machine-sink must break
  182. // the critical edge first. e.g.
  183. //
  184. // BB#1: derived from LLVM BB %bb4.preheader
  185. // Predecessors according to CFG: BB#0
  186. // ...
  187. // %reg16385<def> = DEC64_32r %reg16437, %EFLAGS<imp-def,dead>
  188. // ...
  189. // JE_4 <BB#37>, %EFLAGS<imp-use>
  190. // Successors according to CFG: BB#37 BB#2
  191. //
  192. // BB#2: derived from LLVM BB %bb.nph
  193. // Predecessors according to CFG: BB#0 BB#1
  194. // %reg16386<def> = PHI %reg16434, <BB#0>, %reg16385, <BB#1>
  195. BreakPHIEdge = true;
  196. for (MachineOperand &MO : MRI->use_nodbg_operands(Reg)) {
  197. MachineInstr *UseInst = MO.getParent();
  198. unsigned OpNo = &MO - &UseInst->getOperand(0);
  199. MachineBasicBlock *UseBlock = UseInst->getParent();
  200. if (!(UseBlock == MBB && UseInst->isPHI() &&
  201. UseInst->getOperand(OpNo+1).getMBB() == DefMBB)) {
  202. BreakPHIEdge = false;
  203. break;
  204. }
  205. }
  206. if (BreakPHIEdge)
  207. return true;
  208. for (MachineOperand &MO : MRI->use_nodbg_operands(Reg)) {
  209. // Determine the block of the use.
  210. MachineInstr *UseInst = MO.getParent();
  211. unsigned OpNo = &MO - &UseInst->getOperand(0);
  212. MachineBasicBlock *UseBlock = UseInst->getParent();
  213. if (UseInst->isPHI()) {
  214. // PHI nodes use the operand in the predecessor block, not the block with
  215. // the PHI.
  216. UseBlock = UseInst->getOperand(OpNo+1).getMBB();
  217. } else if (UseBlock == DefMBB) {
  218. LocalUse = true;
  219. return false;
  220. }
  221. // Check that it dominates.
  222. if (!DT->dominates(MBB, UseBlock))
  223. return false;
  224. }
  225. return true;
  226. }
  227. bool MachineSinking::runOnMachineFunction(MachineFunction &MF) {
  228. if (skipOptnoneFunction(*MF.getFunction()))
  229. return false;
  230. DEBUG(dbgs() << "******** Machine Sinking ********\n");
  231. TII = MF.getSubtarget().getInstrInfo();
  232. TRI = MF.getSubtarget().getRegisterInfo();
  233. MRI = &MF.getRegInfo();
  234. DT = &getAnalysis<MachineDominatorTree>();
  235. PDT = &getAnalysis<MachinePostDominatorTree>();
  236. LI = &getAnalysis<MachineLoopInfo>();
  237. MBFI = UseBlockFreqInfo ? &getAnalysis<MachineBlockFrequencyInfo>() : nullptr;
  238. AA = &getAnalysis<AliasAnalysis>();
  239. bool EverMadeChange = false;
  240. while (1) {
  241. bool MadeChange = false;
  242. // Process all basic blocks.
  243. CEBCandidates.clear();
  244. ToSplit.clear();
  245. for (auto &MBB: MF)
  246. MadeChange |= ProcessBlock(MBB);
  247. // If we have anything we marked as toSplit, split it now.
  248. for (auto &Pair : ToSplit) {
  249. auto NewSucc = Pair.first->SplitCriticalEdge(Pair.second, this);
  250. if (NewSucc != nullptr) {
  251. DEBUG(dbgs() << " *** Splitting critical edge:"
  252. " BB#" << Pair.first->getNumber()
  253. << " -- BB#" << NewSucc->getNumber()
  254. << " -- BB#" << Pair.second->getNumber() << '\n');
  255. MadeChange = true;
  256. ++NumSplit;
  257. } else
  258. DEBUG(dbgs() << " *** Not legal to break critical edge\n");
  259. }
  260. // If this iteration over the code changed anything, keep iterating.
  261. if (!MadeChange) break;
  262. EverMadeChange = true;
  263. }
  264. // Now clear any kill flags for recorded registers.
  265. for (auto I : RegsToClearKillFlags)
  266. MRI->clearKillFlags(I);
  267. RegsToClearKillFlags.clear();
  268. return EverMadeChange;
  269. }
  270. bool MachineSinking::ProcessBlock(MachineBasicBlock &MBB) {
  271. // Can't sink anything out of a block that has less than two successors.
  272. if (MBB.succ_size() <= 1 || MBB.empty()) return false;
  273. // Don't bother sinking code out of unreachable blocks. In addition to being
  274. // unprofitable, it can also lead to infinite looping, because in an
  275. // unreachable loop there may be nowhere to stop.
  276. if (!DT->isReachableFromEntry(&MBB)) return false;
  277. bool MadeChange = false;
  278. // Cache all successors, sorted by frequency info and loop depth.
  279. AllSuccsCache AllSuccessors;
  280. // Walk the basic block bottom-up. Remember if we saw a store.
  281. MachineBasicBlock::iterator I = MBB.end();
  282. --I;
  283. bool ProcessedBegin, SawStore = false;
  284. do {
  285. MachineInstr *MI = I; // The instruction to sink.
  286. // Predecrement I (if it's not begin) so that it isn't invalidated by
  287. // sinking.
  288. ProcessedBegin = I == MBB.begin();
  289. if (!ProcessedBegin)
  290. --I;
  291. if (MI->isDebugValue())
  292. continue;
  293. bool Joined = PerformTrivialForwardCoalescing(MI, &MBB);
  294. if (Joined) {
  295. MadeChange = true;
  296. continue;
  297. }
  298. if (SinkInstruction(MI, SawStore, AllSuccessors))
  299. ++NumSunk, MadeChange = true;
  300. // If we just processed the first instruction in the block, we're done.
  301. } while (!ProcessedBegin);
  302. return MadeChange;
  303. }
  304. bool MachineSinking::isWorthBreakingCriticalEdge(MachineInstr *MI,
  305. MachineBasicBlock *From,
  306. MachineBasicBlock *To) {
  307. // FIXME: Need much better heuristics.
  308. // If the pass has already considered breaking this edge (during this pass
  309. // through the function), then let's go ahead and break it. This means
  310. // sinking multiple "cheap" instructions into the same block.
  311. if (!CEBCandidates.insert(std::make_pair(From, To)).second)
  312. return true;
  313. if (!MI->isCopy() && !TII->isAsCheapAsAMove(MI))
  314. return true;
  315. // MI is cheap, we probably don't want to break the critical edge for it.
  316. // However, if this would allow some definitions of its source operands
  317. // to be sunk then it's probably worth it.
  318. for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
  319. const MachineOperand &MO = MI->getOperand(i);
  320. if (!MO.isReg() || !MO.isUse())
  321. continue;
  322. unsigned Reg = MO.getReg();
  323. if (Reg == 0)
  324. continue;
  325. // We don't move live definitions of physical registers,
  326. // so sinking their uses won't enable any opportunities.
  327. if (TargetRegisterInfo::isPhysicalRegister(Reg))
  328. continue;
  329. // If this instruction is the only user of a virtual register,
  330. // check if breaking the edge will enable sinking
  331. // both this instruction and the defining instruction.
  332. if (MRI->hasOneNonDBGUse(Reg)) {
  333. // If the definition resides in same MBB,
  334. // claim it's likely we can sink these together.
  335. // If definition resides elsewhere, we aren't
  336. // blocking it from being sunk so don't break the edge.
  337. MachineInstr *DefMI = MRI->getVRegDef(Reg);
  338. if (DefMI->getParent() == MI->getParent())
  339. return true;
  340. }
  341. }
  342. return false;
  343. }
  344. bool MachineSinking::PostponeSplitCriticalEdge(MachineInstr *MI,
  345. MachineBasicBlock *FromBB,
  346. MachineBasicBlock *ToBB,
  347. bool BreakPHIEdge) {
  348. if (!isWorthBreakingCriticalEdge(MI, FromBB, ToBB))
  349. return false;
  350. // Avoid breaking back edge. From == To means backedge for single BB loop.
  351. if (!SplitEdges || FromBB == ToBB)
  352. return false;
  353. // Check for backedges of more "complex" loops.
  354. if (LI->getLoopFor(FromBB) == LI->getLoopFor(ToBB) &&
  355. LI->isLoopHeader(ToBB))
  356. return false;
  357. // It's not always legal to break critical edges and sink the computation
  358. // to the edge.
  359. //
  360. // BB#1:
  361. // v1024
  362. // Beq BB#3
  363. // <fallthrough>
  364. // BB#2:
  365. // ... no uses of v1024
  366. // <fallthrough>
  367. // BB#3:
  368. // ...
  369. // = v1024
  370. //
  371. // If BB#1 -> BB#3 edge is broken and computation of v1024 is inserted:
  372. //
  373. // BB#1:
  374. // ...
  375. // Bne BB#2
  376. // BB#4:
  377. // v1024 =
  378. // B BB#3
  379. // BB#2:
  380. // ... no uses of v1024
  381. // <fallthrough>
  382. // BB#3:
  383. // ...
  384. // = v1024
  385. //
  386. // This is incorrect since v1024 is not computed along the BB#1->BB#2->BB#3
  387. // flow. We need to ensure the new basic block where the computation is
  388. // sunk to dominates all the uses.
  389. // It's only legal to break critical edge and sink the computation to the
  390. // new block if all the predecessors of "To", except for "From", are
  391. // not dominated by "From". Given SSA property, this means these
  392. // predecessors are dominated by "To".
  393. //
  394. // There is no need to do this check if all the uses are PHI nodes. PHI
  395. // sources are only defined on the specific predecessor edges.
  396. if (!BreakPHIEdge) {
  397. for (MachineBasicBlock::pred_iterator PI = ToBB->pred_begin(),
  398. E = ToBB->pred_end(); PI != E; ++PI) {
  399. if (*PI == FromBB)
  400. continue;
  401. if (!DT->dominates(ToBB, *PI))
  402. return false;
  403. }
  404. }
  405. ToSplit.insert(std::make_pair(FromBB, ToBB));
  406. return true;
  407. }
  408. static bool AvoidsSinking(MachineInstr *MI, MachineRegisterInfo *MRI) {
  409. return MI->isInsertSubreg() || MI->isSubregToReg() || MI->isRegSequence();
  410. }
  411. /// collectDebgValues - Scan instructions following MI and collect any
  412. /// matching DBG_VALUEs.
  413. static void collectDebugValues(MachineInstr *MI,
  414. SmallVectorImpl<MachineInstr *> &DbgValues) {
  415. DbgValues.clear();
  416. if (!MI->getOperand(0).isReg())
  417. return;
  418. MachineBasicBlock::iterator DI = MI; ++DI;
  419. for (MachineBasicBlock::iterator DE = MI->getParent()->end();
  420. DI != DE; ++DI) {
  421. if (!DI->isDebugValue())
  422. return;
  423. if (DI->getOperand(0).isReg() &&
  424. DI->getOperand(0).getReg() == MI->getOperand(0).getReg())
  425. DbgValues.push_back(DI);
  426. }
  427. }
  428. /// isProfitableToSinkTo - Return true if it is profitable to sink MI.
  429. bool MachineSinking::isProfitableToSinkTo(unsigned Reg, MachineInstr *MI,
  430. MachineBasicBlock *MBB,
  431. MachineBasicBlock *SuccToSinkTo,
  432. AllSuccsCache &AllSuccessors) {
  433. assert (MI && "Invalid MachineInstr!");
  434. assert (SuccToSinkTo && "Invalid SinkTo Candidate BB");
  435. if (MBB == SuccToSinkTo)
  436. return false;
  437. // It is profitable if SuccToSinkTo does not post dominate current block.
  438. if (!PDT->dominates(SuccToSinkTo, MBB))
  439. return true;
  440. // It is profitable to sink an instruction from a deeper loop to a shallower
  441. // loop, even if the latter post-dominates the former (PR21115).
  442. if (LI->getLoopDepth(MBB) > LI->getLoopDepth(SuccToSinkTo))
  443. return true;
  444. // Check if only use in post dominated block is PHI instruction.
  445. bool NonPHIUse = false;
  446. for (MachineInstr &UseInst : MRI->use_nodbg_instructions(Reg)) {
  447. MachineBasicBlock *UseBlock = UseInst.getParent();
  448. if (UseBlock == SuccToSinkTo && !UseInst.isPHI())
  449. NonPHIUse = true;
  450. }
  451. if (!NonPHIUse)
  452. return true;
  453. // If SuccToSinkTo post dominates then also it may be profitable if MI
  454. // can further profitably sinked into another block in next round.
  455. bool BreakPHIEdge = false;
  456. // FIXME - If finding successor is compile time expensive then cache results.
  457. if (MachineBasicBlock *MBB2 =
  458. FindSuccToSinkTo(MI, SuccToSinkTo, BreakPHIEdge, AllSuccessors))
  459. return isProfitableToSinkTo(Reg, MI, SuccToSinkTo, MBB2, AllSuccessors);
  460. // If SuccToSinkTo is final destination and it is a post dominator of current
  461. // block then it is not profitable to sink MI into SuccToSinkTo block.
  462. return false;
  463. }
  464. /// Get the sorted sequence of successors for this MachineBasicBlock, possibly
  465. /// computing it if it was not already cached.
  466. SmallVector<MachineBasicBlock *, 4> &
  467. MachineSinking::GetAllSortedSuccessors(MachineInstr *MI, MachineBasicBlock *MBB,
  468. AllSuccsCache &AllSuccessors) const {
  469. // Do we have the sorted successors in cache ?
  470. auto Succs = AllSuccessors.find(MBB);
  471. if (Succs != AllSuccessors.end())
  472. return Succs->second;
  473. SmallVector<MachineBasicBlock *, 4> AllSuccs(MBB->succ_begin(),
  474. MBB->succ_end());
  475. // Handle cases where sinking can happen but where the sink point isn't a
  476. // successor. For example:
  477. //
  478. // x = computation
  479. // if () {} else {}
  480. // use x
  481. //
  482. const std::vector<MachineDomTreeNode *> &Children =
  483. DT->getNode(MBB)->getChildren();
  484. for (const auto &DTChild : Children)
  485. // DomTree children of MBB that have MBB as immediate dominator are added.
  486. if (DTChild->getIDom()->getBlock() == MI->getParent() &&
  487. // Skip MBBs already added to the AllSuccs vector above.
  488. !MBB->isSuccessor(DTChild->getBlock()))
  489. AllSuccs.push_back(DTChild->getBlock());
  490. // Sort Successors according to their loop depth or block frequency info.
  491. std::stable_sort(
  492. AllSuccs.begin(), AllSuccs.end(),
  493. [this](const MachineBasicBlock *L, const MachineBasicBlock *R) {
  494. uint64_t LHSFreq = MBFI ? MBFI->getBlockFreq(L).getFrequency() : 0;
  495. uint64_t RHSFreq = MBFI ? MBFI->getBlockFreq(R).getFrequency() : 0;
  496. bool HasBlockFreq = LHSFreq != 0 && RHSFreq != 0;
  497. return HasBlockFreq ? LHSFreq < RHSFreq
  498. : LI->getLoopDepth(L) < LI->getLoopDepth(R);
  499. });
  500. auto it = AllSuccessors.insert(std::make_pair(MBB, AllSuccs));
  501. return it.first->second;
  502. }
  503. /// FindSuccToSinkTo - Find a successor to sink this instruction to.
  504. MachineBasicBlock *MachineSinking::FindSuccToSinkTo(MachineInstr *MI,
  505. MachineBasicBlock *MBB,
  506. bool &BreakPHIEdge,
  507. AllSuccsCache &AllSuccessors) {
  508. assert (MI && "Invalid MachineInstr!");
  509. assert (MBB && "Invalid MachineBasicBlock!");
  510. // Loop over all the operands of the specified instruction. If there is
  511. // anything we can't handle, bail out.
  512. // SuccToSinkTo - This is the successor to sink this instruction to, once we
  513. // decide.
  514. MachineBasicBlock *SuccToSinkTo = nullptr;
  515. for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
  516. const MachineOperand &MO = MI->getOperand(i);
  517. if (!MO.isReg()) continue; // Ignore non-register operands.
  518. unsigned Reg = MO.getReg();
  519. if (Reg == 0) continue;
  520. if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
  521. if (MO.isUse()) {
  522. // If the physreg has no defs anywhere, it's just an ambient register
  523. // and we can freely move its uses. Alternatively, if it's allocatable,
  524. // it could get allocated to something with a def during allocation.
  525. if (!MRI->isConstantPhysReg(Reg, *MBB->getParent()))
  526. return nullptr;
  527. } else if (!MO.isDead()) {
  528. // A def that isn't dead. We can't move it.
  529. return nullptr;
  530. }
  531. } else {
  532. // Virtual register uses are always safe to sink.
  533. if (MO.isUse()) continue;
  534. // If it's not safe to move defs of the register class, then abort.
  535. if (!TII->isSafeToMoveRegClassDefs(MRI->getRegClass(Reg)))
  536. return nullptr;
  537. // Virtual register defs can only be sunk if all their uses are in blocks
  538. // dominated by one of the successors.
  539. if (SuccToSinkTo) {
  540. // If a previous operand picked a block to sink to, then this operand
  541. // must be sinkable to the same block.
  542. bool LocalUse = false;
  543. if (!AllUsesDominatedByBlock(Reg, SuccToSinkTo, MBB,
  544. BreakPHIEdge, LocalUse))
  545. return nullptr;
  546. continue;
  547. }
  548. // Otherwise, we should look at all the successors and decide which one
  549. // we should sink to. If we have reliable block frequency information
  550. // (frequency != 0) available, give successors with smaller frequencies
  551. // higher priority, otherwise prioritize smaller loop depths.
  552. for (MachineBasicBlock *SuccBlock :
  553. GetAllSortedSuccessors(MI, MBB, AllSuccessors)) {
  554. bool LocalUse = false;
  555. if (AllUsesDominatedByBlock(Reg, SuccBlock, MBB,
  556. BreakPHIEdge, LocalUse)) {
  557. SuccToSinkTo = SuccBlock;
  558. break;
  559. }
  560. if (LocalUse)
  561. // Def is used locally, it's never safe to move this def.
  562. return nullptr;
  563. }
  564. // If we couldn't find a block to sink to, ignore this instruction.
  565. if (!SuccToSinkTo)
  566. return nullptr;
  567. if (!isProfitableToSinkTo(Reg, MI, MBB, SuccToSinkTo, AllSuccessors))
  568. return nullptr;
  569. }
  570. }
  571. // It is not possible to sink an instruction into its own block. This can
  572. // happen with loops.
  573. if (MBB == SuccToSinkTo)
  574. return nullptr;
  575. // It's not safe to sink instructions to EH landing pad. Control flow into
  576. // landing pad is implicitly defined.
  577. if (SuccToSinkTo && SuccToSinkTo->isLandingPad())
  578. return nullptr;
  579. return SuccToSinkTo;
  580. }
  581. /// SinkInstruction - Determine whether it is safe to sink the specified machine
  582. /// instruction out of its current block into a successor.
  583. bool MachineSinking::SinkInstruction(MachineInstr *MI, bool &SawStore,
  584. AllSuccsCache &AllSuccessors) {
  585. // Don't sink insert_subreg, subreg_to_reg, reg_sequence. These are meant to
  586. // be close to the source to make it easier to coalesce.
  587. if (AvoidsSinking(MI, MRI))
  588. return false;
  589. // Check if it's safe to move the instruction.
  590. if (!MI->isSafeToMove(AA, SawStore))
  591. return false;
  592. // Convergent operations may only be moved to control equivalent locations.
  593. if (MI->isConvergent())
  594. return false;
  595. // FIXME: This should include support for sinking instructions within the
  596. // block they are currently in to shorten the live ranges. We often get
  597. // instructions sunk into the top of a large block, but it would be better to
  598. // also sink them down before their first use in the block. This xform has to
  599. // be careful not to *increase* register pressure though, e.g. sinking
  600. // "x = y + z" down if it kills y and z would increase the live ranges of y
  601. // and z and only shrink the live range of x.
  602. bool BreakPHIEdge = false;
  603. MachineBasicBlock *ParentBlock = MI->getParent();
  604. MachineBasicBlock *SuccToSinkTo =
  605. FindSuccToSinkTo(MI, ParentBlock, BreakPHIEdge, AllSuccessors);
  606. // If there are no outputs, it must have side-effects.
  607. if (!SuccToSinkTo)
  608. return false;
  609. // If the instruction to move defines a dead physical register which is live
  610. // when leaving the basic block, don't move it because it could turn into a
  611. // "zombie" define of that preg. E.g., EFLAGS. (<rdar://problem/8030636>)
  612. for (unsigned I = 0, E = MI->getNumOperands(); I != E; ++I) {
  613. const MachineOperand &MO = MI->getOperand(I);
  614. if (!MO.isReg()) continue;
  615. unsigned Reg = MO.getReg();
  616. if (Reg == 0 || !TargetRegisterInfo::isPhysicalRegister(Reg)) continue;
  617. if (SuccToSinkTo->isLiveIn(Reg))
  618. return false;
  619. }
  620. DEBUG(dbgs() << "Sink instr " << *MI << "\tinto block " << *SuccToSinkTo);
  621. // If the block has multiple predecessors, this is a critical edge.
  622. // Decide if we can sink along it or need to break the edge.
  623. if (SuccToSinkTo->pred_size() > 1) {
  624. // We cannot sink a load across a critical edge - there may be stores in
  625. // other code paths.
  626. bool TryBreak = false;
  627. bool store = true;
  628. if (!MI->isSafeToMove(AA, store)) {
  629. DEBUG(dbgs() << " *** NOTE: Won't sink load along critical edge.\n");
  630. TryBreak = true;
  631. }
  632. // We don't want to sink across a critical edge if we don't dominate the
  633. // successor. We could be introducing calculations to new code paths.
  634. if (!TryBreak && !DT->dominates(ParentBlock, SuccToSinkTo)) {
  635. DEBUG(dbgs() << " *** NOTE: Critical edge found\n");
  636. TryBreak = true;
  637. }
  638. // Don't sink instructions into a loop.
  639. if (!TryBreak && LI->isLoopHeader(SuccToSinkTo)) {
  640. DEBUG(dbgs() << " *** NOTE: Loop header found\n");
  641. TryBreak = true;
  642. }
  643. // Otherwise we are OK with sinking along a critical edge.
  644. if (!TryBreak)
  645. DEBUG(dbgs() << "Sinking along critical edge.\n");
  646. else {
  647. // Mark this edge as to be split.
  648. // If the edge can actually be split, the next iteration of the main loop
  649. // will sink MI in the newly created block.
  650. bool Status =
  651. PostponeSplitCriticalEdge(MI, ParentBlock, SuccToSinkTo, BreakPHIEdge);
  652. if (!Status)
  653. DEBUG(dbgs() << " *** PUNTING: Not legal or profitable to "
  654. "break critical edge\n");
  655. // The instruction will not be sunk this time.
  656. return false;
  657. }
  658. }
  659. if (BreakPHIEdge) {
  660. // BreakPHIEdge is true if all the uses are in the successor MBB being
  661. // sunken into and they are all PHI nodes. In this case, machine-sink must
  662. // break the critical edge first.
  663. bool Status = PostponeSplitCriticalEdge(MI, ParentBlock,
  664. SuccToSinkTo, BreakPHIEdge);
  665. if (!Status)
  666. DEBUG(dbgs() << " *** PUNTING: Not legal or profitable to "
  667. "break critical edge\n");
  668. // The instruction will not be sunk this time.
  669. return false;
  670. }
  671. // Determine where to insert into. Skip phi nodes.
  672. MachineBasicBlock::iterator InsertPos = SuccToSinkTo->begin();
  673. while (InsertPos != SuccToSinkTo->end() && InsertPos->isPHI())
  674. ++InsertPos;
  675. // collect matching debug values.
  676. SmallVector<MachineInstr *, 2> DbgValuesToSink;
  677. collectDebugValues(MI, DbgValuesToSink);
  678. // Move the instruction.
  679. SuccToSinkTo->splice(InsertPos, ParentBlock, MI,
  680. ++MachineBasicBlock::iterator(MI));
  681. // Move debug values.
  682. for (SmallVectorImpl<MachineInstr *>::iterator DBI = DbgValuesToSink.begin(),
  683. DBE = DbgValuesToSink.end(); DBI != DBE; ++DBI) {
  684. MachineInstr *DbgMI = *DBI;
  685. SuccToSinkTo->splice(InsertPos, ParentBlock, DbgMI,
  686. ++MachineBasicBlock::iterator(DbgMI));
  687. }
  688. // Conservatively, clear any kill flags, since it's possible that they are no
  689. // longer correct.
  690. // Note that we have to clear the kill flags for any register this instruction
  691. // uses as we may sink over another instruction which currently kills the
  692. // used registers.
  693. for (MachineOperand &MO : MI->operands()) {
  694. if (MO.isReg() && MO.isUse())
  695. RegsToClearKillFlags.set(MO.getReg()); // Remember to clear kill flags.
  696. }
  697. return true;
  698. }