MachineSink.cpp 28 KB

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