1 //===- MergedLoadStoreMotion.cpp - merge and hoist/sink load/stores -------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
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.
22 //===----------------------------------------------------------------------===//
26 // Diamond shaped code before merge:
29 // br %cond, label %if.then, label %if.else
34 // %lt = load %addr_l %le = load %addr_l
35 // <use %lt> <use %le>
37 // store %st, %addr_s store %se, %addr_s
38 // br label %if.end br label %if.end
45 // Diamond shaped code after merge:
49 // br %cond, label %if.then, label %if.else
56 // br label %if.end br label %if.end
61 // %s.sink = phi [%st, if.then], [%se, if.else]
63 // store %s.sink, %addr_s
67 //===----------------------- TODO -----------------------------------------===//
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
73 //===----------------------------------------------------------------------===//
75 #include "llvm/Transforms/Scalar.h"
76 #include "llvm/ADT/SetVector.h"
77 #include "llvm/ADT/SmallPtrSet.h"
78 #include "llvm/ADT/Statistic.h"
79 #include "llvm/Analysis/AliasAnalysis.h"
80 #include "llvm/Analysis/CFG.h"
81 #include "llvm/Analysis/Loads.h"
82 #include "llvm/Analysis/MemoryBuiltins.h"
83 #include "llvm/Analysis/MemoryDependenceAnalysis.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/Target/TargetLibraryInfo.h"
90 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
91 #include "llvm/Transforms/Utils/SSAUpdater.h"
95 #define DEBUG_TYPE "mldst-motion"
97 //===----------------------------------------------------------------------===//
98 // MergedLoadStoreMotion Pass
99 //===----------------------------------------------------------------------===//
102 class MergedLoadStoreMotion : public FunctionPass {
104 MemoryDependenceAnalysis *MD;
107 static char ID; // Pass identification, replacement for typeid
108 explicit MergedLoadStoreMotion(void)
109 : FunctionPass(ID), MD(nullptr), MagicCompileTimeControl(250) {
110 initializeMergedLoadStoreMotionPass(*PassRegistry::getPassRegistry());
113 bool runOnFunction(Function &F) override;
116 // This transformation requires dominator postdominator info
117 void getAnalysisUsage(AnalysisUsage &AU) const override {
118 AU.addRequired<TargetLibraryInfo>();
119 AU.addRequired<MemoryDependenceAnalysis>();
120 AU.addRequired<AliasAnalysis>();
121 AU.addPreserved<AliasAnalysis>();
127 /// \brief Remove instruction from parent and update memory dependence
130 void removeInstruction(Instruction *Inst);
131 BasicBlock *getDiamondTail(BasicBlock *BB);
132 bool isDiamondHead(BasicBlock *BB);
133 // Routines for hoisting loads
134 bool isLoadHoistBarrier(Instruction *Inst);
135 LoadInst *canHoistFromBlock(BasicBlock *BB, LoadInst *LI);
136 void hoistInstruction(BasicBlock *BB, Instruction *HoistCand,
137 Instruction *ElseInst);
138 bool isSafeToHoist(Instruction *I) const;
139 bool hoistLoad(BasicBlock *BB, LoadInst *HoistCand, LoadInst *ElseInst);
140 bool mergeLoads(BasicBlock *BB);
141 // Routines for sinking stores
142 StoreInst *canSinkFromBlock(BasicBlock *BB, StoreInst *SI);
143 PHINode *getPHIOperand(BasicBlock *BB, StoreInst *S0, StoreInst *S1);
144 bool isStoreSinkBarrier(Instruction *Inst);
145 bool sinkStore(BasicBlock *BB, StoreInst *SinkCand, StoreInst *ElseInst);
146 bool mergeStores(BasicBlock *BB);
147 // The mergeLoad/Store algorithms could have Size0 * Size1 complexity,
148 // where Size0 and Size1 are the #instructions on the two sides of
149 // the diamond. The constant chosen here is arbitrary. Compiler Time
150 // Control is enforced by the check Size0 * Size1 < MagicCompileTimeControl.
151 const int MagicCompileTimeControl;
154 char MergedLoadStoreMotion::ID = 0;
158 /// \brief createMergedLoadStoreMotionPass - The public interface to this file.
160 FunctionPass *llvm::createMergedLoadStoreMotionPass() {
161 return new MergedLoadStoreMotion();
164 INITIALIZE_PASS_BEGIN(MergedLoadStoreMotion, "mldst-motion",
165 "MergedLoadStoreMotion", false, false)
166 INITIALIZE_PASS_DEPENDENCY(MemoryDependenceAnalysis)
167 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
168 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
169 INITIALIZE_PASS_END(MergedLoadStoreMotion, "mldst-motion",
170 "MergedLoadStoreMotion", false, false)
173 /// \brief Remove instruction from parent and update memory dependence analysis.
175 void MergedLoadStoreMotion::removeInstruction(Instruction *Inst) {
176 // Notify the memory dependence analysis.
178 MD->removeInstruction(Inst);
179 if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
180 MD->invalidateCachedPointerInfo(LI->getPointerOperand());
181 if (Inst->getType()->getScalarType()->isPointerTy()) {
182 MD->invalidateCachedPointerInfo(Inst);
185 Inst->eraseFromParent();
189 /// \brief Return tail block of a diamond.
191 BasicBlock *MergedLoadStoreMotion::getDiamondTail(BasicBlock *BB) {
192 assert(isDiamondHead(BB) && "Basic block is not head of a diamond");
193 BranchInst *BI = (BranchInst *)(BB->getTerminator());
194 BasicBlock *Succ0 = BI->getSuccessor(0);
195 BasicBlock *Tail = Succ0->getTerminator()->getSuccessor(0);
200 /// \brief True when BB is the head of a diamond (hammock)
202 bool MergedLoadStoreMotion::isDiamondHead(BasicBlock *BB) {
205 if (!isa<BranchInst>(BB->getTerminator()))
207 if (BB->getTerminator()->getNumSuccessors() != 2)
210 BranchInst *BI = (BranchInst *)(BB->getTerminator());
211 BasicBlock *Succ0 = BI->getSuccessor(0);
212 BasicBlock *Succ1 = BI->getSuccessor(1);
214 if (!Succ0->getSinglePredecessor() ||
215 Succ0->getTerminator()->getNumSuccessors() != 1)
217 if (!Succ1->getSinglePredecessor() ||
218 Succ1->getTerminator()->getNumSuccessors() != 1)
221 BasicBlock *Tail = Succ0->getTerminator()->getSuccessor(0);
223 if (Succ1->getTerminator()->getSuccessor(0) != Tail)
229 /// \brief True when instruction is a hoist barrier for a load
231 /// Whenever an instruction could possibly modify the value
232 /// being loaded or protect against the load from happening
233 /// it is considered a hoist barrier.
235 bool MergedLoadStoreMotion::isLoadHoistBarrier(Instruction *Inst) {
236 // FIXME: A call with no side effects should not be a barrier.
237 // Aren't all such calls covered by mayHaveSideEffects() below?
238 // Then this check can be removed.
239 if (isa<CallInst>(Inst))
241 if (isa<TerminatorInst>(Inst))
243 // FIXME: Conservatively let a store instruction block the load.
244 // Use alias analysis instead.
245 if (isa<StoreInst>(Inst))
247 // Note: mayHaveSideEffects covers all instructions that could
248 // trigger a change to state. Eg. in-flight stores have to be executed
249 // before ordered loads or fences, calls could invoke functions that store
250 // data to memory etc.
251 if (Inst->mayHaveSideEffects()) {
254 DEBUG(dbgs() << "No Hoist Barrier\n");
259 /// \brief Decide if a load can be hoisted
261 /// When there is a load in \p BB to the same address as \p LI
262 /// and it can be hoisted from \p BB, return that load.
263 /// Otherwise return Null.
265 LoadInst *MergedLoadStoreMotion::canHoistFromBlock(BasicBlock *BB,
267 LoadInst *I = nullptr;
268 assert(isa<LoadInst>(LI));
269 if (LI->isUsedOutsideOfBlock(LI->getParent()))
272 for (BasicBlock::iterator BBI = BB->begin(), BBE = BB->end(); BBI != BBE;
274 Instruction *Inst = BBI;
276 // Only merge and hoist loads when their result in used only in BB
277 if (isLoadHoistBarrier(Inst))
279 if (!isa<LoadInst>(Inst))
281 if (Inst->isUsedOutsideOfBlock(Inst->getParent()))
284 AliasAnalysis::Location LocLI = AA->getLocation(LI);
285 AliasAnalysis::Location LocInst = AA->getLocation((LoadInst *)Inst);
286 if (AA->isMustAlias(LocLI, LocInst) && LI->getType() == Inst->getType()) {
287 I = (LoadInst *)Inst;
295 /// \brief Merge two equivalent instructions \p HoistCand and \p ElseInst into
298 /// BB is the head of a diamond
300 void MergedLoadStoreMotion::hoistInstruction(BasicBlock *BB,
301 Instruction *HoistCand,
302 Instruction *ElseInst) {
303 DEBUG(dbgs() << " Hoist Instruction into BB \n"; BB->dump();
304 dbgs() << "Instruction Left\n"; HoistCand->dump(); dbgs() << "\n";
305 dbgs() << "Instruction Right\n"; ElseInst->dump(); dbgs() << "\n");
306 // Hoist the instruction.
307 assert(HoistCand->getParent() != BB);
309 // Intersect optional metadata.
310 HoistCand->intersectOptionalDataWith(ElseInst);
311 HoistCand->dropUnknownMetadata();
313 // Prepend point for instruction insert
314 Instruction *HoistPt = BB->getTerminator();
316 // Merged instruction
317 Instruction *HoistedInst = HoistCand->clone();
319 // Notify AA of the new value.
320 if (isa<LoadInst>(HoistCand))
321 AA->copyValue(HoistCand, HoistedInst);
323 // Hoist instruction.
324 HoistedInst->insertBefore(HoistPt);
326 HoistCand->replaceAllUsesWith(HoistedInst);
327 removeInstruction(HoistCand);
328 // Replace the else block instruction.
329 ElseInst->replaceAllUsesWith(HoistedInst);
330 removeInstruction(ElseInst);
334 /// \brief Return true if no operand of \p I is defined in I's parent block
336 bool MergedLoadStoreMotion::isSafeToHoist(Instruction *I) const {
337 BasicBlock *Parent = I->getParent();
338 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
339 Instruction *Instr = dyn_cast<Instruction>(I->getOperand(i));
340 if (Instr && Instr->getParent() == Parent)
347 /// \brief Merge two equivalent loads and GEPs and hoist into diamond head
349 bool MergedLoadStoreMotion::hoistLoad(BasicBlock *BB, LoadInst *L0,
351 // Only one definition?
352 Instruction *A0 = dyn_cast<Instruction>(L0->getPointerOperand());
353 Instruction *A1 = dyn_cast<Instruction>(L1->getPointerOperand());
354 if (A0 && A1 && A0->isIdenticalTo(A1) && isSafeToHoist(A0) &&
355 A0->hasOneUse() && (A0->getParent() == L0->getParent()) &&
356 A1->hasOneUse() && (A1->getParent() == L1->getParent()) &&
357 isa<GetElementPtrInst>(A0)) {
358 DEBUG(dbgs() << "Hoist Instruction into BB \n"; BB->dump();
359 dbgs() << "Instruction Left\n"; L0->dump(); dbgs() << "\n";
360 dbgs() << "Instruction Right\n"; L1->dump(); dbgs() << "\n");
361 hoistInstruction(BB, A0, A1);
362 hoistInstruction(BB, L0, L1);
369 /// \brief Try to hoist two loads to same address into diamond header
371 /// Starting from a diamond head block, iterate over the instructions in one
372 /// successor block and try to match a load in the second successor.
374 bool MergedLoadStoreMotion::mergeLoads(BasicBlock *BB) {
375 bool MergedLoads = false;
376 assert(isDiamondHead(BB));
377 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
378 BasicBlock *Succ0 = BI->getSuccessor(0);
379 BasicBlock *Succ1 = BI->getSuccessor(1);
380 // #Instructions in Succ1 for Compile Time Control
381 int Size1 = Succ1->size();
383 for (BasicBlock::iterator BBI = Succ0->begin(), BBE = Succ0->end();
386 Instruction *I = BBI;
388 if (isLoadHoistBarrier(I))
391 // Only move non-simple (atomic, volatile) loads.
392 if (!isa<LoadInst>(I))
395 LoadInst *L0 = (LoadInst *)I;
400 if (NLoads * Size1 >= MagicCompileTimeControl)
402 if (LoadInst *L1 = canHoistFromBlock(Succ1, L0)) {
403 bool Res = hoistLoad(BB, L0, L1);
405 // Don't attempt to hoist above loads that had not been hoisted.
414 /// \brief True when instruction is sink barrier for a store
416 bool MergedLoadStoreMotion::isStoreSinkBarrier(Instruction *Inst) {
417 // FIXME: Conservatively let a load instruction block the store.
418 // Use alias analysis instead.
419 if (isa<LoadInst>(Inst))
421 if (isa<CallInst>(Inst))
423 if (isa<TerminatorInst>(Inst) && !isa<BranchInst>(Inst))
425 // Note: mayHaveSideEffects covers all instructions that could
426 // trigger a change to state. Eg. in-flight stores have to be executed
427 // before ordered loads or fences, calls could invoke functions that store
428 // data to memory etc.
429 if (!isa<StoreInst>(Inst) && Inst->mayHaveSideEffects()) {
432 DEBUG(dbgs() << "No Sink Barrier\n");
437 /// \brief Check if \p BB contains a store to the same address as \p SI
439 /// \return The store in \p when it is safe to sink. Otherwise return Null.
441 StoreInst *MergedLoadStoreMotion::canSinkFromBlock(BasicBlock *BB,
444 DEBUG(dbgs() << "can Sink? : "; SI->dump(); dbgs() << "\n");
445 for (BasicBlock::reverse_iterator RBI = BB->rbegin(), RBE = BB->rend();
447 Instruction *Inst = &*RBI;
449 // Only move loads if they are used in the block.
450 if (isStoreSinkBarrier(Inst))
452 if (isa<StoreInst>(Inst)) {
453 AliasAnalysis::Location LocSI = AA->getLocation(SI);
454 AliasAnalysis::Location LocInst = AA->getLocation((StoreInst *)Inst);
455 if (AA->isMustAlias(LocSI, LocInst)) {
456 I = (StoreInst *)Inst;
465 /// \brief Create a PHI node in BB for the operands of S0 and S1
467 PHINode *MergedLoadStoreMotion::getPHIOperand(BasicBlock *BB, StoreInst *S0,
469 // Create a phi if the values mismatch.
471 Value *Opd1 = S0->getValueOperand();
472 Value *Opd2 = S1->getValueOperand();
474 NewPN = PHINode::Create(Opd1->getType(), 2, Opd2->getName() + ".sink",
476 NewPN->addIncoming(Opd1, S0->getParent());
477 NewPN->addIncoming(Opd2, S1->getParent());
478 if (NewPN->getType()->getScalarType()->isPointerTy()) {
479 // Notify AA of the new value.
480 AA->copyValue(Opd1, NewPN);
481 AA->copyValue(Opd2, NewPN);
482 // AA needs to be informed when a PHI-use of the pointer value is added
483 for (unsigned I = 0, E = NewPN->getNumIncomingValues(); I != E; ++I) {
484 unsigned J = PHINode::getOperandNumForIncomingValue(I);
485 AA->addEscapingUse(NewPN->getOperandUse(J));
488 MD->invalidateCachedPointerInfo(NewPN);
495 /// \brief Merge two stores to same address and sink into \p BB
497 /// Also sinks GEP instruction computing the store address
499 bool MergedLoadStoreMotion::sinkStore(BasicBlock *BB, StoreInst *S0,
501 // Only one definition?
502 Instruction *A0 = dyn_cast<Instruction>(S0->getPointerOperand());
503 Instruction *A1 = dyn_cast<Instruction>(S1->getPointerOperand());
504 if (A0 && A1 && A0->isIdenticalTo(A1) && A0->hasOneUse() &&
505 (A0->getParent() == S0->getParent()) && A1->hasOneUse() &&
506 (A1->getParent() == S1->getParent()) && isa<GetElementPtrInst>(A0)) {
507 DEBUG(dbgs() << "Sink Instruction into BB \n"; BB->dump();
508 dbgs() << "Instruction Left\n"; S0->dump(); dbgs() << "\n";
509 dbgs() << "Instruction Right\n"; S1->dump(); dbgs() << "\n");
510 // Hoist the instruction.
511 BasicBlock::iterator InsertPt = BB->getFirstInsertionPt();
512 // Intersect optional metadata.
513 S0->intersectOptionalDataWith(S1);
514 S0->dropUnknownMetadata();
516 // Create the new store to be inserted at the join point.
517 StoreInst *SNew = (StoreInst *)(S0->clone());
518 Instruction *ANew = A0->clone();
519 AA->copyValue(S0, SNew);
520 SNew->insertBefore(InsertPt);
521 ANew->insertBefore(SNew);
523 assert(S0->getParent() == A0->getParent());
524 assert(S1->getParent() == A1->getParent());
526 PHINode *NewPN = getPHIOperand(BB, S0, S1);
527 // New PHI operand? Use it.
529 SNew->setOperand(0, NewPN);
530 removeInstruction(S0);
531 removeInstruction(S1);
532 A0->replaceAllUsesWith(ANew);
533 removeInstruction(A0);
534 A1->replaceAllUsesWith(ANew);
535 removeInstruction(A1);
542 /// \brief True when two stores are equivalent and can sink into the footer
544 /// Starting from a diamond tail block, iterate over the instructions in one
545 /// predecessor block and try to match a store in the second predecessor.
547 bool MergedLoadStoreMotion::mergeStores(BasicBlock *T) {
549 bool MergedStores = false;
550 assert(T && "Footer of a diamond cannot be empty");
552 pred_iterator PI = pred_begin(T), E = pred_end(T);
554 BasicBlock *Pred0 = *PI;
556 BasicBlock *Pred1 = *PI;
558 // tail block of a diamond/hammock?
562 return false; // No. More than 2 predecessors.
564 // #Instructions in Succ1 for Compile Time Control
565 int Size1 = Pred1->size();
568 for (BasicBlock::reverse_iterator RBI = Pred0->rbegin(), RBE = Pred0->rend();
571 Instruction *I = &*RBI;
573 if (isStoreSinkBarrier(I))
575 // Sink move non-simple (atomic, volatile) stores
576 if (!isa<StoreInst>(I))
578 StoreInst *S0 = (StoreInst *)I;
583 if (NStores * Size1 >= MagicCompileTimeControl)
585 if (StoreInst *S1 = canSinkFromBlock(Pred1, S0)) {
586 bool Res = sinkStore(T, S0, S1);
588 // Don't attempt to sink below stores that had to stick around
589 // But after removal of a store and some of its feeding
590 // instruction search again from the beginning since the iterator
591 // is likely stale at this point.
595 RBI = Pred0->rbegin();
597 DEBUG(dbgs() << "Search again\n"; Instruction *I = &*RBI; I->dump());
604 /// \brief Run the transformation for each function
606 bool MergedLoadStoreMotion::runOnFunction(Function &F) {
607 MD = &getAnalysis<MemoryDependenceAnalysis>();
608 AA = &getAnalysis<AliasAnalysis>();
610 bool Changed = false;
611 DEBUG(dbgs() << "Instruction Merger\n");
613 // Merge unconditional branches, allowing PRE to catch more
614 // optimization opportunities.
615 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE;) {
616 BasicBlock *BB = FI++;
618 // Hoist equivalent loads and sink stores
619 // outside diamonds when possible
620 if (isDiamondHead(BB)) {
621 Changed |= mergeLoads(BB);
622 Changed |= mergeStores(getDiamondTail(BB));