MergedLoadStoreMotion.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594
  1. //===- MergedLoadStoreMotion.cpp - merge and hoist/sink load/stores -------===//
  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. //! \file
  11. //! \brief This pass performs merges of loads and stores on both sides of a
  12. // diamond (hammock). It hoists the loads and sinks the stores.
  13. //
  14. // The algorithm iteratively hoists two loads to the same address out of a
  15. // diamond (hammock) and merges them into a single load in the header. Similar
  16. // it sinks and merges two stores to the tail block (footer). The algorithm
  17. // iterates over the instructions of one side of the diamond and attempts to
  18. // find a matching load/store on the other side. It hoists / sinks when it
  19. // thinks it safe to do so. This optimization helps with eg. hiding load
  20. // latencies, triggering if-conversion, and reducing static code size.
  21. //
  22. //===----------------------------------------------------------------------===//
  23. //
  24. //
  25. // Example:
  26. // Diamond shaped code before merge:
  27. //
  28. // header:
  29. // br %cond, label %if.then, label %if.else
  30. // + +
  31. // + +
  32. // + +
  33. // if.then: if.else:
  34. // %lt = load %addr_l %le = load %addr_l
  35. // <use %lt> <use %le>
  36. // <...> <...>
  37. // store %st, %addr_s store %se, %addr_s
  38. // br label %if.end br label %if.end
  39. // + +
  40. // + +
  41. // + +
  42. // if.end ("footer"):
  43. // <...>
  44. //
  45. // Diamond shaped code after merge:
  46. //
  47. // header:
  48. // %l = load %addr_l
  49. // br %cond, label %if.then, label %if.else
  50. // + +
  51. // + +
  52. // + +
  53. // if.then: if.else:
  54. // <use %l> <use %l>
  55. // <...> <...>
  56. // br label %if.end br label %if.end
  57. // + +
  58. // + +
  59. // + +
  60. // if.end ("footer"):
  61. // %s.sink = phi [%st, if.then], [%se, if.else]
  62. // <...>
  63. // store %s.sink, %addr_s
  64. // <...>
  65. //
  66. //
  67. //===----------------------- TODO -----------------------------------------===//
  68. //
  69. // 1) Generalize to regions other than diamonds
  70. // 2) Be more aggressive merging memory operations
  71. // Note that both changes require register pressure control
  72. //
  73. //===----------------------------------------------------------------------===//
  74. #include "llvm/Transforms/Scalar.h"
  75. #include "llvm/ADT/SetVector.h"
  76. #include "llvm/ADT/SmallPtrSet.h"
  77. #include "llvm/ADT/Statistic.h"
  78. #include "llvm/Analysis/AliasAnalysis.h"
  79. #include "llvm/Analysis/CFG.h"
  80. #include "llvm/Analysis/Loads.h"
  81. #include "llvm/Analysis/MemoryBuiltins.h"
  82. #include "llvm/Analysis/MemoryDependenceAnalysis.h"
  83. #include "llvm/Analysis/TargetLibraryInfo.h"
  84. #include "llvm/IR/Metadata.h"
  85. #include "llvm/IR/PatternMatch.h"
  86. #include "llvm/Support/Allocator.h"
  87. #include "llvm/Support/CommandLine.h"
  88. #include "llvm/Support/Debug.h"
  89. #include "llvm/Support/raw_ostream.h"
  90. #include "llvm/Transforms/Utils/BasicBlockUtils.h"
  91. #include "llvm/Transforms/Utils/SSAUpdater.h"
  92. #include <vector>
  93. using namespace llvm;
  94. #define DEBUG_TYPE "mldst-motion"
  95. //===----------------------------------------------------------------------===//
  96. // MergedLoadStoreMotion Pass
  97. //===----------------------------------------------------------------------===//
  98. namespace {
  99. class MergedLoadStoreMotion : public FunctionPass {
  100. AliasAnalysis *AA;
  101. MemoryDependenceAnalysis *MD;
  102. public:
  103. static char ID; // Pass identification, replacement for typeid
  104. explicit MergedLoadStoreMotion(void)
  105. : FunctionPass(ID), MD(nullptr), MagicCompileTimeControl(250) {
  106. initializeMergedLoadStoreMotionPass(*PassRegistry::getPassRegistry());
  107. }
  108. bool runOnFunction(Function &F) override;
  109. private:
  110. // This transformation requires dominator postdominator info
  111. void getAnalysisUsage(AnalysisUsage &AU) const override {
  112. AU.addRequired<TargetLibraryInfoWrapperPass>();
  113. AU.addRequired<AliasAnalysis>();
  114. AU.addPreserved<MemoryDependenceAnalysis>();
  115. AU.addPreserved<AliasAnalysis>();
  116. }
  117. // Helper routines
  118. ///
  119. /// \brief Remove instruction from parent and update memory dependence
  120. /// analysis.
  121. ///
  122. void removeInstruction(Instruction *Inst);
  123. BasicBlock *getDiamondTail(BasicBlock *BB);
  124. bool isDiamondHead(BasicBlock *BB);
  125. // Routines for hoisting loads
  126. bool isLoadHoistBarrierInRange(const Instruction& Start,
  127. const Instruction& End,
  128. LoadInst* LI);
  129. LoadInst *canHoistFromBlock(BasicBlock *BB, LoadInst *LI);
  130. void hoistInstruction(BasicBlock *BB, Instruction *HoistCand,
  131. Instruction *ElseInst);
  132. bool isSafeToHoist(Instruction *I) const;
  133. bool hoistLoad(BasicBlock *BB, LoadInst *HoistCand, LoadInst *ElseInst);
  134. bool mergeLoads(BasicBlock *BB);
  135. // Routines for sinking stores
  136. StoreInst *canSinkFromBlock(BasicBlock *BB, StoreInst *SI);
  137. PHINode *getPHIOperand(BasicBlock *BB, StoreInst *S0, StoreInst *S1);
  138. bool isStoreSinkBarrierInRange(const Instruction &Start,
  139. const Instruction &End, MemoryLocation Loc);
  140. bool sinkStore(BasicBlock *BB, StoreInst *SinkCand, StoreInst *ElseInst);
  141. bool mergeStores(BasicBlock *BB);
  142. // The mergeLoad/Store algorithms could have Size0 * Size1 complexity,
  143. // where Size0 and Size1 are the #instructions on the two sides of
  144. // the diamond. The constant chosen here is arbitrary. Compiler Time
  145. // Control is enforced by the check Size0 * Size1 < MagicCompileTimeControl.
  146. const int MagicCompileTimeControl;
  147. };
  148. char MergedLoadStoreMotion::ID = 0;
  149. }
  150. ///
  151. /// \brief createMergedLoadStoreMotionPass - The public interface to this file.
  152. ///
  153. FunctionPass *llvm::createMergedLoadStoreMotionPass() {
  154. return new MergedLoadStoreMotion();
  155. }
  156. INITIALIZE_PASS_BEGIN(MergedLoadStoreMotion, "mldst-motion",
  157. "MergedLoadStoreMotion", false, false)
  158. INITIALIZE_PASS_DEPENDENCY(MemoryDependenceAnalysis)
  159. INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
  160. INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
  161. INITIALIZE_PASS_END(MergedLoadStoreMotion, "mldst-motion",
  162. "MergedLoadStoreMotion", false, false)
  163. ///
  164. /// \brief Remove instruction from parent and update memory dependence analysis.
  165. ///
  166. void MergedLoadStoreMotion::removeInstruction(Instruction *Inst) {
  167. // Notify the memory dependence analysis.
  168. if (MD) {
  169. MD->removeInstruction(Inst);
  170. if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
  171. MD->invalidateCachedPointerInfo(LI->getPointerOperand());
  172. if (Inst->getType()->getScalarType()->isPointerTy()) {
  173. MD->invalidateCachedPointerInfo(Inst);
  174. }
  175. }
  176. Inst->eraseFromParent();
  177. }
  178. ///
  179. /// \brief Return tail block of a diamond.
  180. ///
  181. BasicBlock *MergedLoadStoreMotion::getDiamondTail(BasicBlock *BB) {
  182. assert(isDiamondHead(BB) && "Basic block is not head of a diamond");
  183. BranchInst *BI = (BranchInst *)(BB->getTerminator());
  184. BasicBlock *Succ0 = BI->getSuccessor(0);
  185. BasicBlock *Tail = Succ0->getTerminator()->getSuccessor(0);
  186. return Tail;
  187. }
  188. ///
  189. /// \brief True when BB is the head of a diamond (hammock)
  190. ///
  191. bool MergedLoadStoreMotion::isDiamondHead(BasicBlock *BB) {
  192. if (!BB)
  193. return false;
  194. if (!isa<BranchInst>(BB->getTerminator()))
  195. return false;
  196. if (BB->getTerminator()->getNumSuccessors() != 2)
  197. return false;
  198. BranchInst *BI = (BranchInst *)(BB->getTerminator());
  199. BasicBlock *Succ0 = BI->getSuccessor(0);
  200. BasicBlock *Succ1 = BI->getSuccessor(1);
  201. if (!Succ0->getSinglePredecessor() ||
  202. Succ0->getTerminator()->getNumSuccessors() != 1)
  203. return false;
  204. if (!Succ1->getSinglePredecessor() ||
  205. Succ1->getTerminator()->getNumSuccessors() != 1)
  206. return false;
  207. BasicBlock *Tail = Succ0->getTerminator()->getSuccessor(0);
  208. // Ignore triangles.
  209. if (Succ1->getTerminator()->getSuccessor(0) != Tail)
  210. return false;
  211. return true;
  212. }
  213. ///
  214. /// \brief True when instruction is a hoist barrier for a load
  215. ///
  216. /// Whenever an instruction could possibly modify the value
  217. /// being loaded or protect against the load from happening
  218. /// it is considered a hoist barrier.
  219. ///
  220. bool MergedLoadStoreMotion::isLoadHoistBarrierInRange(const Instruction& Start,
  221. const Instruction& End,
  222. LoadInst* LI) {
  223. MemoryLocation Loc = MemoryLocation::get(LI);
  224. return AA->canInstructionRangeModRef(Start, End, Loc, AliasAnalysis::Mod);
  225. }
  226. ///
  227. /// \brief Decide if a load can be hoisted
  228. ///
  229. /// When there is a load in \p BB to the same address as \p LI
  230. /// and it can be hoisted from \p BB, return that load.
  231. /// Otherwise return Null.
  232. ///
  233. LoadInst *MergedLoadStoreMotion::canHoistFromBlock(BasicBlock *BB1,
  234. LoadInst *Load0) {
  235. for (BasicBlock::iterator BBI = BB1->begin(), BBE = BB1->end(); BBI != BBE;
  236. ++BBI) {
  237. Instruction *Inst = BBI;
  238. // Only merge and hoist loads when their result in used only in BB
  239. if (!isa<LoadInst>(Inst) || Inst->isUsedOutsideOfBlock(BB1))
  240. continue;
  241. LoadInst *Load1 = dyn_cast<LoadInst>(Inst);
  242. BasicBlock *BB0 = Load0->getParent();
  243. MemoryLocation Loc0 = MemoryLocation::get(Load0);
  244. MemoryLocation Loc1 = MemoryLocation::get(Load1);
  245. if (AA->isMustAlias(Loc0, Loc1) && Load0->isSameOperationAs(Load1) &&
  246. !isLoadHoistBarrierInRange(BB1->front(), *Load1, Load1) &&
  247. !isLoadHoistBarrierInRange(BB0->front(), *Load0, Load0)) {
  248. return Load1;
  249. }
  250. }
  251. return nullptr;
  252. }
  253. ///
  254. /// \brief Merge two equivalent instructions \p HoistCand and \p ElseInst into
  255. /// \p BB
  256. ///
  257. /// BB is the head of a diamond
  258. ///
  259. void MergedLoadStoreMotion::hoistInstruction(BasicBlock *BB,
  260. Instruction *HoistCand,
  261. Instruction *ElseInst) {
  262. DEBUG(dbgs() << " Hoist Instruction into BB \n"; BB->dump();
  263. dbgs() << "Instruction Left\n"; HoistCand->dump(); dbgs() << "\n";
  264. dbgs() << "Instruction Right\n"; ElseInst->dump(); dbgs() << "\n");
  265. // Hoist the instruction.
  266. assert(HoistCand->getParent() != BB);
  267. // Intersect optional metadata.
  268. HoistCand->intersectOptionalDataWith(ElseInst);
  269. HoistCand->dropUnknownMetadata();
  270. // Prepend point for instruction insert
  271. Instruction *HoistPt = BB->getTerminator();
  272. // Merged instruction
  273. Instruction *HoistedInst = HoistCand->clone();
  274. // Hoist instruction.
  275. HoistedInst->insertBefore(HoistPt);
  276. HoistCand->replaceAllUsesWith(HoistedInst);
  277. removeInstruction(HoistCand);
  278. // Replace the else block instruction.
  279. ElseInst->replaceAllUsesWith(HoistedInst);
  280. removeInstruction(ElseInst);
  281. }
  282. ///
  283. /// \brief Return true if no operand of \p I is defined in I's parent block
  284. ///
  285. bool MergedLoadStoreMotion::isSafeToHoist(Instruction *I) const {
  286. BasicBlock *Parent = I->getParent();
  287. for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
  288. Instruction *Instr = dyn_cast<Instruction>(I->getOperand(i));
  289. if (Instr && Instr->getParent() == Parent)
  290. return false;
  291. }
  292. return true;
  293. }
  294. ///
  295. /// \brief Merge two equivalent loads and GEPs and hoist into diamond head
  296. ///
  297. bool MergedLoadStoreMotion::hoistLoad(BasicBlock *BB, LoadInst *L0,
  298. LoadInst *L1) {
  299. // Only one definition?
  300. Instruction *A0 = dyn_cast<Instruction>(L0->getPointerOperand());
  301. Instruction *A1 = dyn_cast<Instruction>(L1->getPointerOperand());
  302. if (A0 && A1 && A0->isIdenticalTo(A1) && isSafeToHoist(A0) &&
  303. A0->hasOneUse() && (A0->getParent() == L0->getParent()) &&
  304. A1->hasOneUse() && (A1->getParent() == L1->getParent()) &&
  305. isa<GetElementPtrInst>(A0)) {
  306. DEBUG(dbgs() << "Hoist Instruction into BB \n"; BB->dump();
  307. dbgs() << "Instruction Left\n"; L0->dump(); dbgs() << "\n";
  308. dbgs() << "Instruction Right\n"; L1->dump(); dbgs() << "\n");
  309. hoistInstruction(BB, A0, A1);
  310. hoistInstruction(BB, L0, L1);
  311. return true;
  312. } else
  313. return false;
  314. }
  315. ///
  316. /// \brief Try to hoist two loads to same address into diamond header
  317. ///
  318. /// Starting from a diamond head block, iterate over the instructions in one
  319. /// successor block and try to match a load in the second successor.
  320. ///
  321. bool MergedLoadStoreMotion::mergeLoads(BasicBlock *BB) {
  322. bool MergedLoads = false;
  323. assert(isDiamondHead(BB));
  324. BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
  325. BasicBlock *Succ0 = BI->getSuccessor(0);
  326. BasicBlock *Succ1 = BI->getSuccessor(1);
  327. // #Instructions in Succ1 for Compile Time Control
  328. // int Size1 = Succ1->size(); // HLSL Change
  329. int Size1 = Succ1->compute_size_no_dbg(); // HLSL Change
  330. int NLoads = 0;
  331. for (BasicBlock::iterator BBI = Succ0->begin(), BBE = Succ0->end();
  332. BBI != BBE;) {
  333. Instruction *I = BBI;
  334. ++BBI;
  335. // Only move non-simple (atomic, volatile) loads.
  336. LoadInst *L0 = dyn_cast<LoadInst>(I);
  337. if (!L0 || !L0->isSimple() || L0->isUsedOutsideOfBlock(Succ0))
  338. continue;
  339. ++NLoads;
  340. if (NLoads * Size1 >= MagicCompileTimeControl)
  341. break;
  342. if (LoadInst *L1 = canHoistFromBlock(Succ1, L0)) {
  343. bool Res = hoistLoad(BB, L0, L1);
  344. MergedLoads |= Res;
  345. // Don't attempt to hoist above loads that had not been hoisted.
  346. if (!Res)
  347. break;
  348. }
  349. }
  350. return MergedLoads;
  351. }
  352. ///
  353. /// \brief True when instruction is a sink barrier for a store
  354. /// located in Loc
  355. ///
  356. /// Whenever an instruction could possibly read or modify the
  357. /// value being stored or protect against the store from
  358. /// happening it is considered a sink barrier.
  359. ///
  360. bool MergedLoadStoreMotion::isStoreSinkBarrierInRange(const Instruction &Start,
  361. const Instruction &End,
  362. MemoryLocation Loc) {
  363. return AA->canInstructionRangeModRef(Start, End, Loc, AliasAnalysis::ModRef);
  364. }
  365. ///
  366. /// \brief Check if \p BB contains a store to the same address as \p SI
  367. ///
  368. /// \return The store in \p when it is safe to sink. Otherwise return Null.
  369. ///
  370. StoreInst *MergedLoadStoreMotion::canSinkFromBlock(BasicBlock *BB1,
  371. StoreInst *Store0) {
  372. DEBUG(dbgs() << "can Sink? : "; Store0->dump(); dbgs() << "\n");
  373. BasicBlock *BB0 = Store0->getParent();
  374. for (BasicBlock::reverse_iterator RBI = BB1->rbegin(), RBE = BB1->rend();
  375. RBI != RBE; ++RBI) {
  376. Instruction *Inst = &*RBI;
  377. if (!isa<StoreInst>(Inst))
  378. continue;
  379. StoreInst *Store1 = cast<StoreInst>(Inst);
  380. MemoryLocation Loc0 = MemoryLocation::get(Store0);
  381. MemoryLocation Loc1 = MemoryLocation::get(Store1);
  382. if (AA->isMustAlias(Loc0, Loc1) && Store0->isSameOperationAs(Store1) &&
  383. !isStoreSinkBarrierInRange(*(std::next(BasicBlock::iterator(Store1))),
  384. BB1->back(), Loc1) &&
  385. !isStoreSinkBarrierInRange(*(std::next(BasicBlock::iterator(Store0))),
  386. BB0->back(), Loc0)) {
  387. return Store1;
  388. }
  389. }
  390. return nullptr;
  391. }
  392. ///
  393. /// \brief Create a PHI node in BB for the operands of S0 and S1
  394. ///
  395. PHINode *MergedLoadStoreMotion::getPHIOperand(BasicBlock *BB, StoreInst *S0,
  396. StoreInst *S1) {
  397. // Create a phi if the values mismatch.
  398. PHINode *NewPN = 0;
  399. Value *Opd1 = S0->getValueOperand();
  400. Value *Opd2 = S1->getValueOperand();
  401. if (Opd1 != Opd2) {
  402. NewPN = PHINode::Create(Opd1->getType(), 2, Opd2->getName() + ".sink",
  403. BB->begin());
  404. NewPN->addIncoming(Opd1, S0->getParent());
  405. NewPN->addIncoming(Opd2, S1->getParent());
  406. if (NewPN->getType()->getScalarType()->isPointerTy()) {
  407. // AA needs to be informed when a PHI-use of the pointer value is added
  408. for (unsigned I = 0, E = NewPN->getNumIncomingValues(); I != E; ++I) {
  409. unsigned J = PHINode::getOperandNumForIncomingValue(I);
  410. AA->addEscapingUse(NewPN->getOperandUse(J));
  411. }
  412. if (MD)
  413. MD->invalidateCachedPointerInfo(NewPN);
  414. }
  415. }
  416. return NewPN;
  417. }
  418. ///
  419. /// \brief Merge two stores to same address and sink into \p BB
  420. ///
  421. /// Also sinks GEP instruction computing the store address
  422. ///
  423. bool MergedLoadStoreMotion::sinkStore(BasicBlock *BB, StoreInst *S0,
  424. StoreInst *S1) {
  425. // Only one definition?
  426. Instruction *A0 = dyn_cast<Instruction>(S0->getPointerOperand());
  427. Instruction *A1 = dyn_cast<Instruction>(S1->getPointerOperand());
  428. if (A0 && A1 && A0->isIdenticalTo(A1) && A0->hasOneUse() &&
  429. (A0->getParent() == S0->getParent()) && A1->hasOneUse() &&
  430. (A1->getParent() == S1->getParent()) && isa<GetElementPtrInst>(A0)) {
  431. DEBUG(dbgs() << "Sink Instruction into BB \n"; BB->dump();
  432. dbgs() << "Instruction Left\n"; S0->dump(); dbgs() << "\n";
  433. dbgs() << "Instruction Right\n"; S1->dump(); dbgs() << "\n");
  434. // Hoist the instruction.
  435. BasicBlock::iterator InsertPt = BB->getFirstInsertionPt();
  436. // Intersect optional metadata.
  437. S0->intersectOptionalDataWith(S1);
  438. S0->dropUnknownMetadata();
  439. // Create the new store to be inserted at the join point.
  440. StoreInst *SNew = (StoreInst *)(S0->clone());
  441. Instruction *ANew = A0->clone();
  442. SNew->insertBefore(InsertPt);
  443. ANew->insertBefore(SNew);
  444. assert(S0->getParent() == A0->getParent());
  445. assert(S1->getParent() == A1->getParent());
  446. PHINode *NewPN = getPHIOperand(BB, S0, S1);
  447. // New PHI operand? Use it.
  448. if (NewPN)
  449. SNew->setOperand(0, NewPN);
  450. removeInstruction(S0);
  451. removeInstruction(S1);
  452. A0->replaceAllUsesWith(ANew);
  453. removeInstruction(A0);
  454. A1->replaceAllUsesWith(ANew);
  455. removeInstruction(A1);
  456. return true;
  457. }
  458. return false;
  459. }
  460. ///
  461. /// \brief True when two stores are equivalent and can sink into the footer
  462. ///
  463. /// Starting from a diamond tail block, iterate over the instructions in one
  464. /// predecessor block and try to match a store in the second predecessor.
  465. ///
  466. bool MergedLoadStoreMotion::mergeStores(BasicBlock *T) {
  467. bool MergedStores = false;
  468. assert(T && "Footer of a diamond cannot be empty");
  469. pred_iterator PI = pred_begin(T), E = pred_end(T);
  470. assert(PI != E);
  471. BasicBlock *Pred0 = *PI;
  472. ++PI;
  473. BasicBlock *Pred1 = *PI;
  474. ++PI;
  475. // tail block of a diamond/hammock?
  476. if (Pred0 == Pred1)
  477. return false; // No.
  478. if (PI != E)
  479. return false; // No. More than 2 predecessors.
  480. // #Instructions in Succ1 for Compile Time Control
  481. // int Size1 = Succ1->size(); // HLSL Change
  482. int Size1 = Pred1->compute_size_no_dbg(); // HLSL Change
  483. int NStores = 0;
  484. for (BasicBlock::reverse_iterator RBI = Pred0->rbegin(), RBE = Pred0->rend();
  485. RBI != RBE;) {
  486. Instruction *I = &*RBI;
  487. ++RBI;
  488. // Sink move non-simple (atomic, volatile) stores
  489. if (!isa<StoreInst>(I))
  490. continue;
  491. StoreInst *S0 = (StoreInst *)I;
  492. if (!S0->isSimple())
  493. continue;
  494. ++NStores;
  495. if (NStores * Size1 >= MagicCompileTimeControl)
  496. break;
  497. if (StoreInst *S1 = canSinkFromBlock(Pred1, S0)) {
  498. bool Res = sinkStore(T, S0, S1);
  499. MergedStores |= Res;
  500. // Don't attempt to sink below stores that had to stick around
  501. // But after removal of a store and some of its feeding
  502. // instruction search again from the beginning since the iterator
  503. // is likely stale at this point.
  504. if (!Res)
  505. break;
  506. else {
  507. RBI = Pred0->rbegin();
  508. RBE = Pred0->rend();
  509. DEBUG(dbgs() << "Search again\n"; Instruction *I = &*RBI; I->dump());
  510. }
  511. }
  512. }
  513. return MergedStores;
  514. }
  515. ///
  516. /// \brief Run the transformation for each function
  517. ///
  518. bool MergedLoadStoreMotion::runOnFunction(Function &F) {
  519. MD = getAnalysisIfAvailable<MemoryDependenceAnalysis>();
  520. AA = &getAnalysis<AliasAnalysis>();
  521. bool Changed = false;
  522. DEBUG(dbgs() << "Instruction Merger\n");
  523. // Merge unconditional branches, allowing PRE to catch more
  524. // optimization opportunities.
  525. for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE;) {
  526. BasicBlock *BB = FI++;
  527. // Hoist equivalent loads and sink stores
  528. // outside diamonds when possible
  529. if (isDiamondHead(BB)) {
  530. Changed |= mergeLoads(BB);
  531. Changed |= mergeStores(getDiamondTail(BB));
  532. }
  533. }
  534. return Changed;
  535. }