MachineSink.cpp 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176
  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/ADT/SetVector.h"
  19. #include "llvm/ADT/SmallSet.h"
  20. #include "llvm/ADT/SmallVector.h"
  21. #include "llvm/ADT/SparseBitVector.h"
  22. #include "llvm/ADT/Statistic.h"
  23. #include "llvm/Analysis/AliasAnalysis.h"
  24. #include "llvm/CodeGen/MachineBasicBlock.h"
  25. #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
  26. #include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
  27. #include "llvm/CodeGen/MachineDominators.h"
  28. #include "llvm/CodeGen/MachineFunction.h"
  29. #include "llvm/CodeGen/MachineFunctionPass.h"
  30. #include "llvm/CodeGen/MachineInstr.h"
  31. #include "llvm/CodeGen/MachineLoopInfo.h"
  32. #include "llvm/CodeGen/MachineOperand.h"
  33. #include "llvm/CodeGen/MachinePostDominators.h"
  34. #include "llvm/CodeGen/MachineRegisterInfo.h"
  35. #include "llvm/CodeGen/TargetInstrInfo.h"
  36. #include "llvm/CodeGen/TargetRegisterInfo.h"
  37. #include "llvm/CodeGen/TargetSubtargetInfo.h"
  38. #include "llvm/IR/BasicBlock.h"
  39. #include "llvm/IR/LLVMContext.h"
  40. #include "llvm/IR/DebugInfoMetadata.h"
  41. #include "llvm/Pass.h"
  42. #include "llvm/Support/BranchProbability.h"
  43. #include "llvm/Support/CommandLine.h"
  44. #include "llvm/Support/Debug.h"
  45. #include "llvm/Support/raw_ostream.h"
  46. #include <algorithm>
  47. #include <cassert>
  48. #include <cstdint>
  49. #include <map>
  50. #include <utility>
  51. #include <vector>
  52. using namespace llvm;
  53. #define DEBUG_TYPE "machine-sink"
  54. static cl::opt<bool>
  55. SplitEdges("machine-sink-split",
  56. cl::desc("Split critical edges during machine sinking"),
  57. cl::init(true), cl::Hidden);
  58. static cl::opt<bool>
  59. UseBlockFreqInfo("machine-sink-bfi",
  60. cl::desc("Use block frequency info to find successors to sink"),
  61. cl::init(true), cl::Hidden);
  62. static cl::opt<unsigned> SplitEdgeProbabilityThreshold(
  63. "machine-sink-split-probability-threshold",
  64. cl::desc(
  65. "Percentage threshold for splitting single-instruction critical edge. "
  66. "If the branch threshold is higher than this threshold, we allow "
  67. "speculative execution of up to 1 instruction to avoid branching to "
  68. "splitted critical edge"),
  69. cl::init(40), cl::Hidden);
  70. STATISTIC(NumSunk, "Number of machine instructions sunk");
  71. STATISTIC(NumSplit, "Number of critical edges split");
  72. STATISTIC(NumCoalesces, "Number of copies coalesced");
  73. STATISTIC(NumPostRACopySink, "Number of copies sunk after RA");
  74. namespace {
  75. class MachineSinking : public MachineFunctionPass {
  76. const TargetInstrInfo *TII;
  77. const TargetRegisterInfo *TRI;
  78. MachineRegisterInfo *MRI; // Machine register information
  79. MachineDominatorTree *DT; // Machine dominator tree
  80. MachinePostDominatorTree *PDT; // Machine post dominator tree
  81. MachineLoopInfo *LI;
  82. const MachineBlockFrequencyInfo *MBFI;
  83. const MachineBranchProbabilityInfo *MBPI;
  84. AliasAnalysis *AA;
  85. // Remember which edges have been considered for breaking.
  86. SmallSet<std::pair<MachineBasicBlock*, MachineBasicBlock*>, 8>
  87. CEBCandidates;
  88. // Remember which edges we are about to split.
  89. // This is different from CEBCandidates since those edges
  90. // will be split.
  91. SetVector<std::pair<MachineBasicBlock *, MachineBasicBlock *>> ToSplit;
  92. SparseBitVector<> RegsToClearKillFlags;
  93. using AllSuccsCache =
  94. std::map<MachineBasicBlock *, SmallVector<MachineBasicBlock *, 4>>;
  95. public:
  96. static char ID; // Pass identification
  97. MachineSinking() : MachineFunctionPass(ID) {
  98. initializeMachineSinkingPass(*PassRegistry::getPassRegistry());
  99. }
  100. bool runOnMachineFunction(MachineFunction &MF) override;
  101. void getAnalysisUsage(AnalysisUsage &AU) const override {
  102. AU.setPreservesCFG();
  103. MachineFunctionPass::getAnalysisUsage(AU);
  104. AU.addRequired<AAResultsWrapperPass>();
  105. AU.addRequired<MachineDominatorTree>();
  106. AU.addRequired<MachinePostDominatorTree>();
  107. AU.addRequired<MachineLoopInfo>();
  108. AU.addRequired<MachineBranchProbabilityInfo>();
  109. AU.addPreserved<MachineDominatorTree>();
  110. AU.addPreserved<MachinePostDominatorTree>();
  111. AU.addPreserved<MachineLoopInfo>();
  112. if (UseBlockFreqInfo)
  113. AU.addRequired<MachineBlockFrequencyInfo>();
  114. }
  115. void releaseMemory() override {
  116. CEBCandidates.clear();
  117. }
  118. private:
  119. bool ProcessBlock(MachineBasicBlock &MBB);
  120. bool isWorthBreakingCriticalEdge(MachineInstr &MI,
  121. MachineBasicBlock *From,
  122. MachineBasicBlock *To);
  123. /// Postpone the splitting of the given critical
  124. /// edge (\p From, \p To).
  125. ///
  126. /// We do not split the edges on the fly. Indeed, this invalidates
  127. /// the dominance information and thus triggers a lot of updates
  128. /// of that information underneath.
  129. /// Instead, we postpone all the splits after each iteration of
  130. /// the main loop. That way, the information is at least valid
  131. /// for the lifetime of an iteration.
  132. ///
  133. /// \return True if the edge is marked as toSplit, false otherwise.
  134. /// False can be returned if, for instance, this is not profitable.
  135. bool PostponeSplitCriticalEdge(MachineInstr &MI,
  136. MachineBasicBlock *From,
  137. MachineBasicBlock *To,
  138. bool BreakPHIEdge);
  139. bool SinkInstruction(MachineInstr &MI, bool &SawStore,
  140. AllSuccsCache &AllSuccessors);
  141. bool AllUsesDominatedByBlock(unsigned Reg, MachineBasicBlock *MBB,
  142. MachineBasicBlock *DefMBB,
  143. bool &BreakPHIEdge, bool &LocalUse) const;
  144. MachineBasicBlock *FindSuccToSinkTo(MachineInstr &MI, MachineBasicBlock *MBB,
  145. bool &BreakPHIEdge, AllSuccsCache &AllSuccessors);
  146. bool isProfitableToSinkTo(unsigned Reg, MachineInstr &MI,
  147. MachineBasicBlock *MBB,
  148. MachineBasicBlock *SuccToSinkTo,
  149. AllSuccsCache &AllSuccessors);
  150. bool PerformTrivialForwardCoalescing(MachineInstr &MI,
  151. MachineBasicBlock *MBB);
  152. SmallVector<MachineBasicBlock *, 4> &
  153. GetAllSortedSuccessors(MachineInstr &MI, MachineBasicBlock *MBB,
  154. AllSuccsCache &AllSuccessors) const;
  155. };
  156. } // end anonymous namespace
  157. char MachineSinking::ID = 0;
  158. char &llvm::MachineSinkingID = MachineSinking::ID;
  159. INITIALIZE_PASS_BEGIN(MachineSinking, DEBUG_TYPE,
  160. "Machine code sinking", false, false)
  161. INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
  162. INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
  163. INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
  164. INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
  165. INITIALIZE_PASS_END(MachineSinking, DEBUG_TYPE,
  166. "Machine code sinking", false, false)
  167. bool MachineSinking::PerformTrivialForwardCoalescing(MachineInstr &MI,
  168. MachineBasicBlock *MBB) {
  169. if (!MI.isCopy())
  170. return false;
  171. unsigned SrcReg = MI.getOperand(1).getReg();
  172. unsigned DstReg = MI.getOperand(0).getReg();
  173. if (!TargetRegisterInfo::isVirtualRegister(SrcReg) ||
  174. !TargetRegisterInfo::isVirtualRegister(DstReg) ||
  175. !MRI->hasOneNonDBGUse(SrcReg))
  176. return false;
  177. const TargetRegisterClass *SRC = MRI->getRegClass(SrcReg);
  178. const TargetRegisterClass *DRC = MRI->getRegClass(DstReg);
  179. if (SRC != DRC)
  180. return false;
  181. MachineInstr *DefMI = MRI->getVRegDef(SrcReg);
  182. if (DefMI->isCopyLike())
  183. return false;
  184. LLVM_DEBUG(dbgs() << "Coalescing: " << *DefMI);
  185. LLVM_DEBUG(dbgs() << "*** to: " << MI);
  186. MRI->replaceRegWith(DstReg, SrcReg);
  187. MI.eraseFromParent();
  188. // Conservatively, clear any kill flags, since it's possible that they are no
  189. // longer correct.
  190. MRI->clearKillFlags(SrcReg);
  191. ++NumCoalesces;
  192. return true;
  193. }
  194. /// AllUsesDominatedByBlock - Return true if all uses of the specified register
  195. /// occur in blocks dominated by the specified block. If any use is in the
  196. /// definition block, then return false since it is never legal to move def
  197. /// after uses.
  198. bool
  199. MachineSinking::AllUsesDominatedByBlock(unsigned Reg,
  200. MachineBasicBlock *MBB,
  201. MachineBasicBlock *DefMBB,
  202. bool &BreakPHIEdge,
  203. bool &LocalUse) const {
  204. assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
  205. "Only makes sense for vregs");
  206. // Ignore debug uses because debug info doesn't affect the code.
  207. if (MRI->use_nodbg_empty(Reg))
  208. return true;
  209. // BreakPHIEdge is true if all the uses are in the successor MBB being sunken
  210. // into and they are all PHI nodes. In this case, machine-sink must break
  211. // the critical edge first. e.g.
  212. //
  213. // %bb.1: derived from LLVM BB %bb4.preheader
  214. // Predecessors according to CFG: %bb.0
  215. // ...
  216. // %reg16385 = DEC64_32r %reg16437, implicit-def dead %eflags
  217. // ...
  218. // JE_4 <%bb.37>, implicit %eflags
  219. // Successors according to CFG: %bb.37 %bb.2
  220. //
  221. // %bb.2: derived from LLVM BB %bb.nph
  222. // Predecessors according to CFG: %bb.0 %bb.1
  223. // %reg16386 = PHI %reg16434, %bb.0, %reg16385, %bb.1
  224. BreakPHIEdge = true;
  225. for (MachineOperand &MO : MRI->use_nodbg_operands(Reg)) {
  226. MachineInstr *UseInst = MO.getParent();
  227. unsigned OpNo = &MO - &UseInst->getOperand(0);
  228. MachineBasicBlock *UseBlock = UseInst->getParent();
  229. if (!(UseBlock == MBB && UseInst->isPHI() &&
  230. UseInst->getOperand(OpNo+1).getMBB() == DefMBB)) {
  231. BreakPHIEdge = false;
  232. break;
  233. }
  234. }
  235. if (BreakPHIEdge)
  236. return true;
  237. for (MachineOperand &MO : MRI->use_nodbg_operands(Reg)) {
  238. // Determine the block of the use.
  239. MachineInstr *UseInst = MO.getParent();
  240. unsigned OpNo = &MO - &UseInst->getOperand(0);
  241. MachineBasicBlock *UseBlock = UseInst->getParent();
  242. if (UseInst->isPHI()) {
  243. // PHI nodes use the operand in the predecessor block, not the block with
  244. // the PHI.
  245. UseBlock = UseInst->getOperand(OpNo+1).getMBB();
  246. } else if (UseBlock == DefMBB) {
  247. LocalUse = true;
  248. return false;
  249. }
  250. // Check that it dominates.
  251. if (!DT->dominates(MBB, UseBlock))
  252. return false;
  253. }
  254. return true;
  255. }
  256. bool MachineSinking::runOnMachineFunction(MachineFunction &MF) {
  257. if (skipFunction(MF.getFunction()))
  258. return false;
  259. LLVM_DEBUG(dbgs() << "******** Machine Sinking ********\n");
  260. TII = MF.getSubtarget().getInstrInfo();
  261. TRI = MF.getSubtarget().getRegisterInfo();
  262. MRI = &MF.getRegInfo();
  263. DT = &getAnalysis<MachineDominatorTree>();
  264. PDT = &getAnalysis<MachinePostDominatorTree>();
  265. LI = &getAnalysis<MachineLoopInfo>();
  266. MBFI = UseBlockFreqInfo ? &getAnalysis<MachineBlockFrequencyInfo>() : nullptr;
  267. MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
  268. AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
  269. bool EverMadeChange = false;
  270. while (true) {
  271. bool MadeChange = false;
  272. // Process all basic blocks.
  273. CEBCandidates.clear();
  274. ToSplit.clear();
  275. for (auto &MBB: MF)
  276. MadeChange |= ProcessBlock(MBB);
  277. // If we have anything we marked as toSplit, split it now.
  278. for (auto &Pair : ToSplit) {
  279. auto NewSucc = Pair.first->SplitCriticalEdge(Pair.second, *this);
  280. if (NewSucc != nullptr) {
  281. LLVM_DEBUG(dbgs() << " *** Splitting critical edge: "
  282. << printMBBReference(*Pair.first) << " -- "
  283. << printMBBReference(*NewSucc) << " -- "
  284. << printMBBReference(*Pair.second) << '\n');
  285. MadeChange = true;
  286. ++NumSplit;
  287. } else
  288. LLVM_DEBUG(dbgs() << " *** Not legal to break critical edge\n");
  289. }
  290. // If this iteration over the code changed anything, keep iterating.
  291. if (!MadeChange) break;
  292. EverMadeChange = true;
  293. }
  294. // Now clear any kill flags for recorded registers.
  295. for (auto I : RegsToClearKillFlags)
  296. MRI->clearKillFlags(I);
  297. RegsToClearKillFlags.clear();
  298. return EverMadeChange;
  299. }
  300. bool MachineSinking::ProcessBlock(MachineBasicBlock &MBB) {
  301. // Can't sink anything out of a block that has less than two successors.
  302. if (MBB.succ_size() <= 1 || MBB.empty()) return false;
  303. // Don't bother sinking code out of unreachable blocks. In addition to being
  304. // unprofitable, it can also lead to infinite looping, because in an
  305. // unreachable loop there may be nowhere to stop.
  306. if (!DT->isReachableFromEntry(&MBB)) return false;
  307. bool MadeChange = false;
  308. // Cache all successors, sorted by frequency info and loop depth.
  309. AllSuccsCache AllSuccessors;
  310. // Walk the basic block bottom-up. Remember if we saw a store.
  311. MachineBasicBlock::iterator I = MBB.end();
  312. --I;
  313. bool ProcessedBegin, SawStore = false;
  314. do {
  315. MachineInstr &MI = *I; // The instruction to sink.
  316. // Predecrement I (if it's not begin) so that it isn't invalidated by
  317. // sinking.
  318. ProcessedBegin = I == MBB.begin();
  319. if (!ProcessedBegin)
  320. --I;
  321. if (MI.isDebugInstr())
  322. continue;
  323. bool Joined = PerformTrivialForwardCoalescing(MI, &MBB);
  324. if (Joined) {
  325. MadeChange = true;
  326. continue;
  327. }
  328. if (SinkInstruction(MI, SawStore, AllSuccessors)) {
  329. ++NumSunk;
  330. MadeChange = true;
  331. }
  332. // If we just processed the first instruction in the block, we're done.
  333. } while (!ProcessedBegin);
  334. return MadeChange;
  335. }
  336. bool MachineSinking::isWorthBreakingCriticalEdge(MachineInstr &MI,
  337. MachineBasicBlock *From,
  338. MachineBasicBlock *To) {
  339. // FIXME: Need much better heuristics.
  340. // If the pass has already considered breaking this edge (during this pass
  341. // through the function), then let's go ahead and break it. This means
  342. // sinking multiple "cheap" instructions into the same block.
  343. if (!CEBCandidates.insert(std::make_pair(From, To)).second)
  344. return true;
  345. if (!MI.isCopy() && !TII->isAsCheapAsAMove(MI))
  346. return true;
  347. if (From->isSuccessor(To) && MBPI->getEdgeProbability(From, To) <=
  348. BranchProbability(SplitEdgeProbabilityThreshold, 100))
  349. return true;
  350. // MI is cheap, we probably don't want to break the critical edge for it.
  351. // However, if this would allow some definitions of its source operands
  352. // to be sunk then it's probably worth it.
  353. for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
  354. const MachineOperand &MO = MI.getOperand(i);
  355. if (!MO.isReg() || !MO.isUse())
  356. continue;
  357. unsigned Reg = MO.getReg();
  358. if (Reg == 0)
  359. continue;
  360. // We don't move live definitions of physical registers,
  361. // so sinking their uses won't enable any opportunities.
  362. if (TargetRegisterInfo::isPhysicalRegister(Reg))
  363. continue;
  364. // If this instruction is the only user of a virtual register,
  365. // check if breaking the edge will enable sinking
  366. // both this instruction and the defining instruction.
  367. if (MRI->hasOneNonDBGUse(Reg)) {
  368. // If the definition resides in same MBB,
  369. // claim it's likely we can sink these together.
  370. // If definition resides elsewhere, we aren't
  371. // blocking it from being sunk so don't break the edge.
  372. MachineInstr *DefMI = MRI->getVRegDef(Reg);
  373. if (DefMI->getParent() == MI.getParent())
  374. return true;
  375. }
  376. }
  377. return false;
  378. }
  379. bool MachineSinking::PostponeSplitCriticalEdge(MachineInstr &MI,
  380. MachineBasicBlock *FromBB,
  381. MachineBasicBlock *ToBB,
  382. bool BreakPHIEdge) {
  383. if (!isWorthBreakingCriticalEdge(MI, FromBB, ToBB))
  384. return false;
  385. // Avoid breaking back edge. From == To means backedge for single BB loop.
  386. if (!SplitEdges || FromBB == ToBB)
  387. return false;
  388. // Check for backedges of more "complex" loops.
  389. if (LI->getLoopFor(FromBB) == LI->getLoopFor(ToBB) &&
  390. LI->isLoopHeader(ToBB))
  391. return false;
  392. // It's not always legal to break critical edges and sink the computation
  393. // to the edge.
  394. //
  395. // %bb.1:
  396. // v1024
  397. // Beq %bb.3
  398. // <fallthrough>
  399. // %bb.2:
  400. // ... no uses of v1024
  401. // <fallthrough>
  402. // %bb.3:
  403. // ...
  404. // = v1024
  405. //
  406. // If %bb.1 -> %bb.3 edge is broken and computation of v1024 is inserted:
  407. //
  408. // %bb.1:
  409. // ...
  410. // Bne %bb.2
  411. // %bb.4:
  412. // v1024 =
  413. // B %bb.3
  414. // %bb.2:
  415. // ... no uses of v1024
  416. // <fallthrough>
  417. // %bb.3:
  418. // ...
  419. // = v1024
  420. //
  421. // This is incorrect since v1024 is not computed along the %bb.1->%bb.2->%bb.3
  422. // flow. We need to ensure the new basic block where the computation is
  423. // sunk to dominates all the uses.
  424. // It's only legal to break critical edge and sink the computation to the
  425. // new block if all the predecessors of "To", except for "From", are
  426. // not dominated by "From". Given SSA property, this means these
  427. // predecessors are dominated by "To".
  428. //
  429. // There is no need to do this check if all the uses are PHI nodes. PHI
  430. // sources are only defined on the specific predecessor edges.
  431. if (!BreakPHIEdge) {
  432. for (MachineBasicBlock::pred_iterator PI = ToBB->pred_begin(),
  433. E = ToBB->pred_end(); PI != E; ++PI) {
  434. if (*PI == FromBB)
  435. continue;
  436. if (!DT->dominates(ToBB, *PI))
  437. return false;
  438. }
  439. }
  440. ToSplit.insert(std::make_pair(FromBB, ToBB));
  441. return true;
  442. }
  443. /// isProfitableToSinkTo - Return true if it is profitable to sink MI.
  444. bool MachineSinking::isProfitableToSinkTo(unsigned Reg, MachineInstr &MI,
  445. MachineBasicBlock *MBB,
  446. MachineBasicBlock *SuccToSinkTo,
  447. AllSuccsCache &AllSuccessors) {
  448. assert (SuccToSinkTo && "Invalid SinkTo Candidate BB");
  449. if (MBB == SuccToSinkTo)
  450. return false;
  451. // It is profitable if SuccToSinkTo does not post dominate current block.
  452. if (!PDT->dominates(SuccToSinkTo, MBB))
  453. return true;
  454. // It is profitable to sink an instruction from a deeper loop to a shallower
  455. // loop, even if the latter post-dominates the former (PR21115).
  456. if (LI->getLoopDepth(MBB) > LI->getLoopDepth(SuccToSinkTo))
  457. return true;
  458. // Check if only use in post dominated block is PHI instruction.
  459. bool NonPHIUse = false;
  460. for (MachineInstr &UseInst : MRI->use_nodbg_instructions(Reg)) {
  461. MachineBasicBlock *UseBlock = UseInst.getParent();
  462. if (UseBlock == SuccToSinkTo && !UseInst.isPHI())
  463. NonPHIUse = true;
  464. }
  465. if (!NonPHIUse)
  466. return true;
  467. // If SuccToSinkTo post dominates then also it may be profitable if MI
  468. // can further profitably sinked into another block in next round.
  469. bool BreakPHIEdge = false;
  470. // FIXME - If finding successor is compile time expensive then cache results.
  471. if (MachineBasicBlock *MBB2 =
  472. FindSuccToSinkTo(MI, SuccToSinkTo, BreakPHIEdge, AllSuccessors))
  473. return isProfitableToSinkTo(Reg, MI, SuccToSinkTo, MBB2, AllSuccessors);
  474. // If SuccToSinkTo is final destination and it is a post dominator of current
  475. // block then it is not profitable to sink MI into SuccToSinkTo block.
  476. return false;
  477. }
  478. /// Get the sorted sequence of successors for this MachineBasicBlock, possibly
  479. /// computing it if it was not already cached.
  480. SmallVector<MachineBasicBlock *, 4> &
  481. MachineSinking::GetAllSortedSuccessors(MachineInstr &MI, MachineBasicBlock *MBB,
  482. AllSuccsCache &AllSuccessors) const {
  483. // Do we have the sorted successors in cache ?
  484. auto Succs = AllSuccessors.find(MBB);
  485. if (Succs != AllSuccessors.end())
  486. return Succs->second;
  487. SmallVector<MachineBasicBlock *, 4> AllSuccs(MBB->succ_begin(),
  488. MBB->succ_end());
  489. // Handle cases where sinking can happen but where the sink point isn't a
  490. // successor. For example:
  491. //
  492. // x = computation
  493. // if () {} else {}
  494. // use x
  495. //
  496. const std::vector<MachineDomTreeNode *> &Children =
  497. DT->getNode(MBB)->getChildren();
  498. for (const auto &DTChild : Children)
  499. // DomTree children of MBB that have MBB as immediate dominator are added.
  500. if (DTChild->getIDom()->getBlock() == MI.getParent() &&
  501. // Skip MBBs already added to the AllSuccs vector above.
  502. !MBB->isSuccessor(DTChild->getBlock()))
  503. AllSuccs.push_back(DTChild->getBlock());
  504. // Sort Successors according to their loop depth or block frequency info.
  505. std::stable_sort(
  506. AllSuccs.begin(), AllSuccs.end(),
  507. [this](const MachineBasicBlock *L, const MachineBasicBlock *R) {
  508. uint64_t LHSFreq = MBFI ? MBFI->getBlockFreq(L).getFrequency() : 0;
  509. uint64_t RHSFreq = MBFI ? MBFI->getBlockFreq(R).getFrequency() : 0;
  510. bool HasBlockFreq = LHSFreq != 0 && RHSFreq != 0;
  511. return HasBlockFreq ? LHSFreq < RHSFreq
  512. : LI->getLoopDepth(L) < LI->getLoopDepth(R);
  513. });
  514. auto it = AllSuccessors.insert(std::make_pair(MBB, AllSuccs));
  515. return it.first->second;
  516. }
  517. /// FindSuccToSinkTo - Find a successor to sink this instruction to.
  518. MachineBasicBlock *
  519. MachineSinking::FindSuccToSinkTo(MachineInstr &MI, MachineBasicBlock *MBB,
  520. bool &BreakPHIEdge,
  521. AllSuccsCache &AllSuccessors) {
  522. assert (MBB && "Invalid MachineBasicBlock!");
  523. // Loop over all the operands of the specified instruction. If there is
  524. // anything we can't handle, bail out.
  525. // SuccToSinkTo - This is the successor to sink this instruction to, once we
  526. // decide.
  527. MachineBasicBlock *SuccToSinkTo = nullptr;
  528. for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
  529. const MachineOperand &MO = MI.getOperand(i);
  530. if (!MO.isReg()) continue; // Ignore non-register operands.
  531. unsigned Reg = MO.getReg();
  532. if (Reg == 0) continue;
  533. if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
  534. if (MO.isUse()) {
  535. // If the physreg has no defs anywhere, it's just an ambient register
  536. // and we can freely move its uses. Alternatively, if it's allocatable,
  537. // it could get allocated to something with a def during allocation.
  538. if (!MRI->isConstantPhysReg(Reg))
  539. return nullptr;
  540. } else if (!MO.isDead()) {
  541. // A def that isn't dead. We can't move it.
  542. return nullptr;
  543. }
  544. } else {
  545. // Virtual register uses are always safe to sink.
  546. if (MO.isUse()) continue;
  547. // If it's not safe to move defs of the register class, then abort.
  548. if (!TII->isSafeToMoveRegClassDefs(MRI->getRegClass(Reg)))
  549. return nullptr;
  550. // Virtual register defs can only be sunk if all their uses are in blocks
  551. // dominated by one of the successors.
  552. if (SuccToSinkTo) {
  553. // If a previous operand picked a block to sink to, then this operand
  554. // must be sinkable to the same block.
  555. bool LocalUse = false;
  556. if (!AllUsesDominatedByBlock(Reg, SuccToSinkTo, MBB,
  557. BreakPHIEdge, LocalUse))
  558. return nullptr;
  559. continue;
  560. }
  561. // Otherwise, we should look at all the successors and decide which one
  562. // we should sink to. If we have reliable block frequency information
  563. // (frequency != 0) available, give successors with smaller frequencies
  564. // higher priority, otherwise prioritize smaller loop depths.
  565. for (MachineBasicBlock *SuccBlock :
  566. GetAllSortedSuccessors(MI, MBB, AllSuccessors)) {
  567. bool LocalUse = false;
  568. if (AllUsesDominatedByBlock(Reg, SuccBlock, MBB,
  569. BreakPHIEdge, LocalUse)) {
  570. SuccToSinkTo = SuccBlock;
  571. break;
  572. }
  573. if (LocalUse)
  574. // Def is used locally, it's never safe to move this def.
  575. return nullptr;
  576. }
  577. // If we couldn't find a block to sink to, ignore this instruction.
  578. if (!SuccToSinkTo)
  579. return nullptr;
  580. if (!isProfitableToSinkTo(Reg, MI, MBB, SuccToSinkTo, AllSuccessors))
  581. return nullptr;
  582. }
  583. }
  584. // It is not possible to sink an instruction into its own block. This can
  585. // happen with loops.
  586. if (MBB == SuccToSinkTo)
  587. return nullptr;
  588. // It's not safe to sink instructions to EH landing pad. Control flow into
  589. // landing pad is implicitly defined.
  590. if (SuccToSinkTo && SuccToSinkTo->isEHPad())
  591. return nullptr;
  592. return SuccToSinkTo;
  593. }
  594. /// Return true if MI is likely to be usable as a memory operation by the
  595. /// implicit null check optimization.
  596. ///
  597. /// This is a "best effort" heuristic, and should not be relied upon for
  598. /// correctness. This returning true does not guarantee that the implicit null
  599. /// check optimization is legal over MI, and this returning false does not
  600. /// guarantee MI cannot possibly be used to do a null check.
  601. static bool SinkingPreventsImplicitNullCheck(MachineInstr &MI,
  602. const TargetInstrInfo *TII,
  603. const TargetRegisterInfo *TRI) {
  604. using MachineBranchPredicate = TargetInstrInfo::MachineBranchPredicate;
  605. auto *MBB = MI.getParent();
  606. if (MBB->pred_size() != 1)
  607. return false;
  608. auto *PredMBB = *MBB->pred_begin();
  609. auto *PredBB = PredMBB->getBasicBlock();
  610. // Frontends that don't use implicit null checks have no reason to emit
  611. // branches with make.implicit metadata, and this function should always
  612. // return false for them.
  613. if (!PredBB ||
  614. !PredBB->getTerminator()->getMetadata(LLVMContext::MD_make_implicit))
  615. return false;
  616. unsigned BaseReg;
  617. int64_t Offset;
  618. if (!TII->getMemOpBaseRegImmOfs(MI, BaseReg, Offset, TRI))
  619. return false;
  620. if (!(MI.mayLoad() && !MI.isPredicable()))
  621. return false;
  622. MachineBranchPredicate MBP;
  623. if (TII->analyzeBranchPredicate(*PredMBB, MBP, false))
  624. return false;
  625. return MBP.LHS.isReg() && MBP.RHS.isImm() && MBP.RHS.getImm() == 0 &&
  626. (MBP.Predicate == MachineBranchPredicate::PRED_NE ||
  627. MBP.Predicate == MachineBranchPredicate::PRED_EQ) &&
  628. MBP.LHS.getReg() == BaseReg;
  629. }
  630. /// Sink an instruction and its associated debug instructions.
  631. static void performSink(MachineInstr &MI, MachineBasicBlock &SuccToSinkTo,
  632. MachineBasicBlock::iterator InsertPos) {
  633. // Collect matching debug values.
  634. SmallVector<MachineInstr *, 2> DbgValuesToSink;
  635. MI.collectDebugValues(DbgValuesToSink);
  636. // If we cannot find a location to use (merge with), then we erase the debug
  637. // location to prevent debug-info driven tools from potentially reporting
  638. // wrong location information.
  639. if (!SuccToSinkTo.empty() && InsertPos != SuccToSinkTo.end())
  640. MI.setDebugLoc(DILocation::getMergedLocation(MI.getDebugLoc(),
  641. InsertPos->getDebugLoc()));
  642. else
  643. MI.setDebugLoc(DebugLoc());
  644. // Move the instruction.
  645. MachineBasicBlock *ParentBlock = MI.getParent();
  646. SuccToSinkTo.splice(InsertPos, ParentBlock, MI,
  647. ++MachineBasicBlock::iterator(MI));
  648. // Move previously adjacent debug value instructions to the insert position.
  649. for (SmallVectorImpl<MachineInstr *>::iterator DBI = DbgValuesToSink.begin(),
  650. DBE = DbgValuesToSink.end();
  651. DBI != DBE; ++DBI) {
  652. MachineInstr *DbgMI = *DBI;
  653. SuccToSinkTo.splice(InsertPos, ParentBlock, DbgMI,
  654. ++MachineBasicBlock::iterator(DbgMI));
  655. }
  656. }
  657. /// SinkInstruction - Determine whether it is safe to sink the specified machine
  658. /// instruction out of its current block into a successor.
  659. bool MachineSinking::SinkInstruction(MachineInstr &MI, bool &SawStore,
  660. AllSuccsCache &AllSuccessors) {
  661. // Don't sink instructions that the target prefers not to sink.
  662. if (!TII->shouldSink(MI))
  663. return false;
  664. // Check if it's safe to move the instruction.
  665. if (!MI.isSafeToMove(AA, SawStore))
  666. return false;
  667. // Convergent operations may not be made control-dependent on additional
  668. // values.
  669. if (MI.isConvergent())
  670. return false;
  671. // Don't break implicit null checks. This is a performance heuristic, and not
  672. // required for correctness.
  673. if (SinkingPreventsImplicitNullCheck(MI, TII, TRI))
  674. return false;
  675. // FIXME: This should include support for sinking instructions within the
  676. // block they are currently in to shorten the live ranges. We often get
  677. // instructions sunk into the top of a large block, but it would be better to
  678. // also sink them down before their first use in the block. This xform has to
  679. // be careful not to *increase* register pressure though, e.g. sinking
  680. // "x = y + z" down if it kills y and z would increase the live ranges of y
  681. // and z and only shrink the live range of x.
  682. bool BreakPHIEdge = false;
  683. MachineBasicBlock *ParentBlock = MI.getParent();
  684. MachineBasicBlock *SuccToSinkTo =
  685. FindSuccToSinkTo(MI, ParentBlock, BreakPHIEdge, AllSuccessors);
  686. // If there are no outputs, it must have side-effects.
  687. if (!SuccToSinkTo)
  688. return false;
  689. // If the instruction to move defines a dead physical register which is live
  690. // when leaving the basic block, don't move it because it could turn into a
  691. // "zombie" define of that preg. E.g., EFLAGS. (<rdar://problem/8030636>)
  692. for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I) {
  693. const MachineOperand &MO = MI.getOperand(I);
  694. if (!MO.isReg()) continue;
  695. unsigned Reg = MO.getReg();
  696. if (Reg == 0 || !TargetRegisterInfo::isPhysicalRegister(Reg)) continue;
  697. if (SuccToSinkTo->isLiveIn(Reg))
  698. return false;
  699. }
  700. LLVM_DEBUG(dbgs() << "Sink instr " << MI << "\tinto block " << *SuccToSinkTo);
  701. // If the block has multiple predecessors, this is a critical edge.
  702. // Decide if we can sink along it or need to break the edge.
  703. if (SuccToSinkTo->pred_size() > 1) {
  704. // We cannot sink a load across a critical edge - there may be stores in
  705. // other code paths.
  706. bool TryBreak = false;
  707. bool store = true;
  708. if (!MI.isSafeToMove(AA, store)) {
  709. LLVM_DEBUG(dbgs() << " *** NOTE: Won't sink load along critical edge.\n");
  710. TryBreak = true;
  711. }
  712. // We don't want to sink across a critical edge if we don't dominate the
  713. // successor. We could be introducing calculations to new code paths.
  714. if (!TryBreak && !DT->dominates(ParentBlock, SuccToSinkTo)) {
  715. LLVM_DEBUG(dbgs() << " *** NOTE: Critical edge found\n");
  716. TryBreak = true;
  717. }
  718. // Don't sink instructions into a loop.
  719. if (!TryBreak && LI->isLoopHeader(SuccToSinkTo)) {
  720. LLVM_DEBUG(dbgs() << " *** NOTE: Loop header found\n");
  721. TryBreak = true;
  722. }
  723. // Otherwise we are OK with sinking along a critical edge.
  724. if (!TryBreak)
  725. LLVM_DEBUG(dbgs() << "Sinking along critical edge.\n");
  726. else {
  727. // Mark this edge as to be split.
  728. // If the edge can actually be split, the next iteration of the main loop
  729. // will sink MI in the newly created block.
  730. bool Status =
  731. PostponeSplitCriticalEdge(MI, ParentBlock, SuccToSinkTo, BreakPHIEdge);
  732. if (!Status)
  733. LLVM_DEBUG(dbgs() << " *** PUNTING: Not legal or profitable to "
  734. "break critical edge\n");
  735. // The instruction will not be sunk this time.
  736. return false;
  737. }
  738. }
  739. if (BreakPHIEdge) {
  740. // BreakPHIEdge is true if all the uses are in the successor MBB being
  741. // sunken into and they are all PHI nodes. In this case, machine-sink must
  742. // break the critical edge first.
  743. bool Status = PostponeSplitCriticalEdge(MI, ParentBlock,
  744. SuccToSinkTo, BreakPHIEdge);
  745. if (!Status)
  746. LLVM_DEBUG(dbgs() << " *** PUNTING: Not legal or profitable to "
  747. "break critical edge\n");
  748. // The instruction will not be sunk this time.
  749. return false;
  750. }
  751. // Determine where to insert into. Skip phi nodes.
  752. MachineBasicBlock::iterator InsertPos = SuccToSinkTo->begin();
  753. while (InsertPos != SuccToSinkTo->end() && InsertPos->isPHI())
  754. ++InsertPos;
  755. performSink(MI, *SuccToSinkTo, InsertPos);
  756. // Conservatively, clear any kill flags, since it's possible that they are no
  757. // longer correct.
  758. // Note that we have to clear the kill flags for any register this instruction
  759. // uses as we may sink over another instruction which currently kills the
  760. // used registers.
  761. for (MachineOperand &MO : MI.operands()) {
  762. if (MO.isReg() && MO.isUse())
  763. RegsToClearKillFlags.set(MO.getReg()); // Remember to clear kill flags.
  764. }
  765. return true;
  766. }
  767. //===----------------------------------------------------------------------===//
  768. // This pass is not intended to be a replacement or a complete alternative
  769. // for the pre-ra machine sink pass. It is only designed to sink COPY
  770. // instructions which should be handled after RA.
  771. //
  772. // This pass sinks COPY instructions into a successor block, if the COPY is not
  773. // used in the current block and the COPY is live-in to a single successor
  774. // (i.e., doesn't require the COPY to be duplicated). This avoids executing the
  775. // copy on paths where their results aren't needed. This also exposes
  776. // additional opportunites for dead copy elimination and shrink wrapping.
  777. //
  778. // These copies were either not handled by or are inserted after the MachineSink
  779. // pass. As an example of the former case, the MachineSink pass cannot sink
  780. // COPY instructions with allocatable source registers; for AArch64 these type
  781. // of copy instructions are frequently used to move function parameters (PhyReg)
  782. // into virtual registers in the entry block.
  783. //
  784. // For the machine IR below, this pass will sink %w19 in the entry into its
  785. // successor (%bb.1) because %w19 is only live-in in %bb.1.
  786. // %bb.0:
  787. // %wzr = SUBSWri %w1, 1
  788. // %w19 = COPY %w0
  789. // Bcc 11, %bb.2
  790. // %bb.1:
  791. // Live Ins: %w19
  792. // BL @fun
  793. // %w0 = ADDWrr %w0, %w19
  794. // RET %w0
  795. // %bb.2:
  796. // %w0 = COPY %wzr
  797. // RET %w0
  798. // As we sink %w19 (CSR in AArch64) into %bb.1, the shrink-wrapping pass will be
  799. // able to see %bb.0 as a candidate.
  800. //===----------------------------------------------------------------------===//
  801. namespace {
  802. class PostRAMachineSinking : public MachineFunctionPass {
  803. public:
  804. bool runOnMachineFunction(MachineFunction &MF) override;
  805. static char ID;
  806. PostRAMachineSinking() : MachineFunctionPass(ID) {}
  807. StringRef getPassName() const override { return "PostRA Machine Sink"; }
  808. void getAnalysisUsage(AnalysisUsage &AU) const override {
  809. AU.setPreservesCFG();
  810. MachineFunctionPass::getAnalysisUsage(AU);
  811. }
  812. MachineFunctionProperties getRequiredProperties() const override {
  813. return MachineFunctionProperties().set(
  814. MachineFunctionProperties::Property::NoVRegs);
  815. }
  816. private:
  817. /// Track which register units have been modified and used.
  818. LiveRegUnits ModifiedRegUnits, UsedRegUnits;
  819. /// Sink Copy instructions unused in the same block close to their uses in
  820. /// successors.
  821. bool tryToSinkCopy(MachineBasicBlock &BB, MachineFunction &MF,
  822. const TargetRegisterInfo *TRI, const TargetInstrInfo *TII);
  823. };
  824. } // namespace
  825. char PostRAMachineSinking::ID = 0;
  826. char &llvm::PostRAMachineSinkingID = PostRAMachineSinking::ID;
  827. INITIALIZE_PASS(PostRAMachineSinking, "postra-machine-sink",
  828. "PostRA Machine Sink", false, false)
  829. static bool aliasWithRegsInLiveIn(MachineBasicBlock &MBB, unsigned Reg,
  830. const TargetRegisterInfo *TRI) {
  831. LiveRegUnits LiveInRegUnits(*TRI);
  832. LiveInRegUnits.addLiveIns(MBB);
  833. return !LiveInRegUnits.available(Reg);
  834. }
  835. static MachineBasicBlock *
  836. getSingleLiveInSuccBB(MachineBasicBlock &CurBB,
  837. const SmallPtrSetImpl<MachineBasicBlock *> &SinkableBBs,
  838. unsigned Reg, const TargetRegisterInfo *TRI) {
  839. // Try to find a single sinkable successor in which Reg is live-in.
  840. MachineBasicBlock *BB = nullptr;
  841. for (auto *SI : SinkableBBs) {
  842. if (aliasWithRegsInLiveIn(*SI, Reg, TRI)) {
  843. // If BB is set here, Reg is live-in to at least two sinkable successors,
  844. // so quit.
  845. if (BB)
  846. return nullptr;
  847. BB = SI;
  848. }
  849. }
  850. // Reg is not live-in to any sinkable successors.
  851. if (!BB)
  852. return nullptr;
  853. // Check if any register aliased with Reg is live-in in other successors.
  854. for (auto *SI : CurBB.successors()) {
  855. if (!SinkableBBs.count(SI) && aliasWithRegsInLiveIn(*SI, Reg, TRI))
  856. return nullptr;
  857. }
  858. return BB;
  859. }
  860. static MachineBasicBlock *
  861. getSingleLiveInSuccBB(MachineBasicBlock &CurBB,
  862. const SmallPtrSetImpl<MachineBasicBlock *> &SinkableBBs,
  863. ArrayRef<unsigned> DefedRegsInCopy,
  864. const TargetRegisterInfo *TRI) {
  865. MachineBasicBlock *SingleBB = nullptr;
  866. for (auto DefReg : DefedRegsInCopy) {
  867. MachineBasicBlock *BB =
  868. getSingleLiveInSuccBB(CurBB, SinkableBBs, DefReg, TRI);
  869. if (!BB || (SingleBB && SingleBB != BB))
  870. return nullptr;
  871. SingleBB = BB;
  872. }
  873. return SingleBB;
  874. }
  875. static void clearKillFlags(MachineInstr *MI, MachineBasicBlock &CurBB,
  876. SmallVectorImpl<unsigned> &UsedOpsInCopy,
  877. LiveRegUnits &UsedRegUnits,
  878. const TargetRegisterInfo *TRI) {
  879. for (auto U : UsedOpsInCopy) {
  880. MachineOperand &MO = MI->getOperand(U);
  881. unsigned SrcReg = MO.getReg();
  882. if (!UsedRegUnits.available(SrcReg)) {
  883. MachineBasicBlock::iterator NI = std::next(MI->getIterator());
  884. for (MachineInstr &UI : make_range(NI, CurBB.end())) {
  885. if (UI.killsRegister(SrcReg, TRI)) {
  886. UI.clearRegisterKills(SrcReg, TRI);
  887. MO.setIsKill(true);
  888. break;
  889. }
  890. }
  891. }
  892. }
  893. }
  894. static void updateLiveIn(MachineInstr *MI, MachineBasicBlock *SuccBB,
  895. SmallVectorImpl<unsigned> &UsedOpsInCopy,
  896. SmallVectorImpl<unsigned> &DefedRegsInCopy) {
  897. MachineFunction &MF = *SuccBB->getParent();
  898. const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
  899. for (unsigned DefReg : DefedRegsInCopy)
  900. for (MCSubRegIterator S(DefReg, TRI, true); S.isValid(); ++S)
  901. SuccBB->removeLiveIn(*S);
  902. for (auto U : UsedOpsInCopy) {
  903. unsigned Reg = MI->getOperand(U).getReg();
  904. if (!SuccBB->isLiveIn(Reg))
  905. SuccBB->addLiveIn(Reg);
  906. }
  907. }
  908. static bool hasRegisterDependency(MachineInstr *MI,
  909. SmallVectorImpl<unsigned> &UsedOpsInCopy,
  910. SmallVectorImpl<unsigned> &DefedRegsInCopy,
  911. LiveRegUnits &ModifiedRegUnits,
  912. LiveRegUnits &UsedRegUnits) {
  913. bool HasRegDependency = false;
  914. for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
  915. MachineOperand &MO = MI->getOperand(i);
  916. if (!MO.isReg())
  917. continue;
  918. unsigned Reg = MO.getReg();
  919. if (!Reg)
  920. continue;
  921. if (MO.isDef()) {
  922. if (!ModifiedRegUnits.available(Reg) || !UsedRegUnits.available(Reg)) {
  923. HasRegDependency = true;
  924. break;
  925. }
  926. DefedRegsInCopy.push_back(Reg);
  927. // FIXME: instead of isUse(), readsReg() would be a better fix here,
  928. // For example, we can ignore modifications in reg with undef. However,
  929. // it's not perfectly clear if skipping the internal read is safe in all
  930. // other targets.
  931. } else if (MO.isUse()) {
  932. if (!ModifiedRegUnits.available(Reg)) {
  933. HasRegDependency = true;
  934. break;
  935. }
  936. UsedOpsInCopy.push_back(i);
  937. }
  938. }
  939. return HasRegDependency;
  940. }
  941. bool PostRAMachineSinking::tryToSinkCopy(MachineBasicBlock &CurBB,
  942. MachineFunction &MF,
  943. const TargetRegisterInfo *TRI,
  944. const TargetInstrInfo *TII) {
  945. SmallPtrSet<MachineBasicBlock *, 2> SinkableBBs;
  946. // FIXME: For now, we sink only to a successor which has a single predecessor
  947. // so that we can directly sink COPY instructions to the successor without
  948. // adding any new block or branch instruction.
  949. for (MachineBasicBlock *SI : CurBB.successors())
  950. if (!SI->livein_empty() && SI->pred_size() == 1)
  951. SinkableBBs.insert(SI);
  952. if (SinkableBBs.empty())
  953. return false;
  954. bool Changed = false;
  955. // Track which registers have been modified and used between the end of the
  956. // block and the current instruction.
  957. ModifiedRegUnits.clear();
  958. UsedRegUnits.clear();
  959. for (auto I = CurBB.rbegin(), E = CurBB.rend(); I != E;) {
  960. MachineInstr *MI = &*I;
  961. ++I;
  962. if (MI->isDebugInstr())
  963. continue;
  964. // Do not move any instruction across function call.
  965. if (MI->isCall())
  966. return false;
  967. if (!MI->isCopy() || !MI->getOperand(0).isRenamable()) {
  968. LiveRegUnits::accumulateUsedDefed(*MI, ModifiedRegUnits, UsedRegUnits,
  969. TRI);
  970. continue;
  971. }
  972. // Track the operand index for use in Copy.
  973. SmallVector<unsigned, 2> UsedOpsInCopy;
  974. // Track the register number defed in Copy.
  975. SmallVector<unsigned, 2> DefedRegsInCopy;
  976. // Don't sink the COPY if it would violate a register dependency.
  977. if (hasRegisterDependency(MI, UsedOpsInCopy, DefedRegsInCopy,
  978. ModifiedRegUnits, UsedRegUnits)) {
  979. LiveRegUnits::accumulateUsedDefed(*MI, ModifiedRegUnits, UsedRegUnits,
  980. TRI);
  981. continue;
  982. }
  983. assert((!UsedOpsInCopy.empty() && !DefedRegsInCopy.empty()) &&
  984. "Unexpect SrcReg or DefReg");
  985. MachineBasicBlock *SuccBB =
  986. getSingleLiveInSuccBB(CurBB, SinkableBBs, DefedRegsInCopy, TRI);
  987. // Don't sink if we cannot find a single sinkable successor in which Reg
  988. // is live-in.
  989. if (!SuccBB) {
  990. LiveRegUnits::accumulateUsedDefed(*MI, ModifiedRegUnits, UsedRegUnits,
  991. TRI);
  992. continue;
  993. }
  994. assert((SuccBB->pred_size() == 1 && *SuccBB->pred_begin() == &CurBB) &&
  995. "Unexpected predecessor");
  996. // Clear the kill flag if SrcReg is killed between MI and the end of the
  997. // block.
  998. clearKillFlags(MI, CurBB, UsedOpsInCopy, UsedRegUnits, TRI);
  999. MachineBasicBlock::iterator InsertPos = SuccBB->getFirstNonPHI();
  1000. performSink(*MI, *SuccBB, InsertPos);
  1001. updateLiveIn(MI, SuccBB, UsedOpsInCopy, DefedRegsInCopy);
  1002. Changed = true;
  1003. ++NumPostRACopySink;
  1004. }
  1005. return Changed;
  1006. }
  1007. bool PostRAMachineSinking::runOnMachineFunction(MachineFunction &MF) {
  1008. bool Changed = false;
  1009. const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
  1010. const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
  1011. ModifiedRegUnits.init(*TRI);
  1012. UsedRegUnits.init(*TRI);
  1013. for (auto &BB : MF)
  1014. Changed |= tryToSinkCopy(BB, MF, TRI, TII);
  1015. return Changed;
  1016. }