1 //===- MergedLoadStoreMotion.cpp - merge and hoist/sink load/stores -------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
10 //! This pass performs merges of loads and stores on both sides of a
11 // diamond (hammock). It hoists the loads and sinks the stores.
13 // The algorithm iteratively hoists two loads to the same address out of a
14 // diamond (hammock) and merges them into a single load in the header. Similar
15 // it sinks and merges two stores to the tail block (footer). The algorithm
16 // iterates over the instructions of one side of the diamond and attempts to
17 // find a matching load/store on the other side. New tail/footer block may be
18 // insterted if the tail/footer block has more predecessors (not only the two
19 // predecessors that are forming the diamond). It hoists / sinks when it thinks
20 // it safe to do so. This optimization helps with eg. hiding load latencies,
21 // triggering if-conversion, and reducing static code size.
23 // NOTE: This code no longer performs load hoisting, it is subsumed by GVNHoist.
25 //===----------------------------------------------------------------------===//
29 // Diamond shaped code before merge:
32 // br %cond, label %if.then, label %if.else
37 // %lt = load %addr_l %le = load %addr_l
38 // <use %lt> <use %le>
40 // store %st, %addr_s store %se, %addr_s
41 // br label %if.end br label %if.end
48 // Diamond shaped code after merge:
52 // br %cond, label %if.then, label %if.else
59 // br label %if.end br label %if.end
64 // %s.sink = phi [%st, if.then], [%se, if.else]
66 // store %s.sink, %addr_s
70 //===----------------------- TODO -----------------------------------------===//
72 // 1) Generalize to regions other than diamonds
73 // 2) Be more aggressive merging memory operations
74 // Note that both changes require register pressure control
76 //===----------------------------------------------------------------------===//
78 #include "llvm/Transforms/Scalar/MergedLoadStoreMotion.h"
79 #include "llvm/ADT/Statistic.h"
80 #include "llvm/Analysis/AliasAnalysis.h"
81 #include "llvm/Analysis/CFG.h"
82 #include "llvm/Analysis/GlobalsModRef.h"
83 #include "llvm/Analysis/Loads.h"
84 #include "llvm/Analysis/ValueTracking.h"
85 #include "llvm/IR/Metadata.h"
86 #include "llvm/InitializePasses.h"
87 #include "llvm/Support/Debug.h"
88 #include "llvm/Support/raw_ostream.h"
89 #include "llvm/Transforms/Scalar.h"
90 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
94 #define DEBUG_TYPE "mldst-motion"
97 //===----------------------------------------------------------------------===//
98 // MergedLoadStoreMotion Pass
99 //===----------------------------------------------------------------------===//
100 class MergedLoadStoreMotion {
101 AliasAnalysis *AA = nullptr;
103 // The mergeLoad/Store algorithms could have Size0 * Size1 complexity,
104 // where Size0 and Size1 are the #instructions on the two sides of
105 // the diamond. The constant chosen here is arbitrary. Compiler Time
106 // Control is enforced by the check Size0 * Size1 < MagicCompileTimeControl.
107 const int MagicCompileTimeControl = 250;
109 const bool SplitFooterBB;
111 MergedLoadStoreMotion(bool SplitFooterBB) : SplitFooterBB(SplitFooterBB) {}
112 bool run(Function &F, AliasAnalysis &AA);
115 BasicBlock *getDiamondTail(BasicBlock *BB);
116 bool isDiamondHead(BasicBlock *BB);
117 // Routines for sinking stores
118 StoreInst *canSinkFromBlock(BasicBlock *BB, StoreInst *SI);
119 PHINode *getPHIOperand(BasicBlock *BB, StoreInst *S0, StoreInst *S1);
120 bool isStoreSinkBarrierInRange(const Instruction &Start,
121 const Instruction &End, MemoryLocation Loc);
122 bool canSinkStoresAndGEPs(StoreInst *S0, StoreInst *S1) const;
123 void sinkStoresAndGEPs(BasicBlock *BB, StoreInst *SinkCand,
124 StoreInst *ElseInst);
125 bool mergeStores(BasicBlock *BB);
127 } // end anonymous namespace
130 /// Return tail block of a diamond.
132 BasicBlock *MergedLoadStoreMotion::getDiamondTail(BasicBlock *BB) {
133 assert(isDiamondHead(BB) && "Basic block is not head of a diamond");
134 return BB->getTerminator()->getSuccessor(0)->getSingleSuccessor();
138 /// True when BB is the head of a diamond (hammock)
140 bool MergedLoadStoreMotion::isDiamondHead(BasicBlock *BB) {
143 auto *BI = dyn_cast<BranchInst>(BB->getTerminator());
144 if (!BI || !BI->isConditional())
147 BasicBlock *Succ0 = BI->getSuccessor(0);
148 BasicBlock *Succ1 = BI->getSuccessor(1);
150 if (!Succ0->getSinglePredecessor())
152 if (!Succ1->getSinglePredecessor())
155 BasicBlock *Succ0Succ = Succ0->getSingleSuccessor();
156 BasicBlock *Succ1Succ = Succ1->getSingleSuccessor();
158 if (!Succ0Succ || !Succ1Succ || Succ0Succ != Succ1Succ)
165 /// True when instruction is a sink barrier for a store
168 /// Whenever an instruction could possibly read or modify the
169 /// value being stored or protect against the store from
170 /// happening it is considered a sink barrier.
172 bool MergedLoadStoreMotion::isStoreSinkBarrierInRange(const Instruction &Start,
173 const Instruction &End,
174 MemoryLocation Loc) {
175 for (const Instruction &Inst :
176 make_range(Start.getIterator(), End.getIterator()))
179 return AA->canInstructionRangeModRef(Start, End, Loc, ModRefInfo::ModRef);
183 /// Check if \p BB contains a store to the same address as \p SI
185 /// \return The store in \p when it is safe to sink. Otherwise return Null.
187 StoreInst *MergedLoadStoreMotion::canSinkFromBlock(BasicBlock *BB1,
189 LLVM_DEBUG(dbgs() << "can Sink? : "; Store0->dump(); dbgs() << "\n");
190 BasicBlock *BB0 = Store0->getParent();
191 for (Instruction &Inst : reverse(*BB1)) {
192 auto *Store1 = dyn_cast<StoreInst>(&Inst);
196 MemoryLocation Loc0 = MemoryLocation::get(Store0);
197 MemoryLocation Loc1 = MemoryLocation::get(Store1);
198 if (AA->isMustAlias(Loc0, Loc1) && Store0->isSameOperationAs(Store1) &&
199 !isStoreSinkBarrierInRange(*Store1->getNextNode(), BB1->back(), Loc1) &&
200 !isStoreSinkBarrierInRange(*Store0->getNextNode(), BB0->back(), Loc0)) {
208 /// Create a PHI node in BB for the operands of S0 and S1
210 PHINode *MergedLoadStoreMotion::getPHIOperand(BasicBlock *BB, StoreInst *S0,
212 // Create a phi if the values mismatch.
213 Value *Opd1 = S0->getValueOperand();
214 Value *Opd2 = S1->getValueOperand();
218 auto *NewPN = PHINode::Create(Opd1->getType(), 2, Opd2->getName() + ".sink",
220 NewPN->applyMergedLocation(S0->getDebugLoc(), S1->getDebugLoc());
221 NewPN->addIncoming(Opd1, S0->getParent());
222 NewPN->addIncoming(Opd2, S1->getParent());
227 /// Check if 2 stores can be sunk together with corresponding GEPs
229 bool MergedLoadStoreMotion::canSinkStoresAndGEPs(StoreInst *S0,
230 StoreInst *S1) const {
231 auto *A0 = dyn_cast<Instruction>(S0->getPointerOperand());
232 auto *A1 = dyn_cast<Instruction>(S1->getPointerOperand());
233 return A0 && A1 && A0->isIdenticalTo(A1) && A0->hasOneUse() &&
234 (A0->getParent() == S0->getParent()) && A1->hasOneUse() &&
235 (A1->getParent() == S1->getParent()) && isa<GetElementPtrInst>(A0);
239 /// Merge two stores to same address and sink into \p BB
241 /// Also sinks GEP instruction computing the store address
243 void MergedLoadStoreMotion::sinkStoresAndGEPs(BasicBlock *BB, StoreInst *S0,
245 // Only one definition?
246 auto *A0 = dyn_cast<Instruction>(S0->getPointerOperand());
247 auto *A1 = dyn_cast<Instruction>(S1->getPointerOperand());
248 LLVM_DEBUG(dbgs() << "Sink Instruction into BB \n"; BB->dump();
249 dbgs() << "Instruction Left\n"; S0->dump(); dbgs() << "\n";
250 dbgs() << "Instruction Right\n"; S1->dump(); dbgs() << "\n");
251 // Hoist the instruction.
252 BasicBlock::iterator InsertPt = BB->getFirstInsertionPt();
253 // Intersect optional metadata.
255 S0->dropUnknownNonDebugMetadata();
257 // Create the new store to be inserted at the join point.
258 StoreInst *SNew = cast<StoreInst>(S0->clone());
259 Instruction *ANew = A0->clone();
260 SNew->insertBefore(&*InsertPt);
261 ANew->insertBefore(SNew);
263 assert(S0->getParent() == A0->getParent());
264 assert(S1->getParent() == A1->getParent());
266 // New PHI operand? Use it.
267 if (PHINode *NewPN = getPHIOperand(BB, S0, S1))
268 SNew->setOperand(0, NewPN);
269 S0->eraseFromParent();
270 S1->eraseFromParent();
271 A0->replaceAllUsesWith(ANew);
272 A0->eraseFromParent();
273 A1->replaceAllUsesWith(ANew);
274 A1->eraseFromParent();
278 /// True when two stores are equivalent and can sink into the footer
280 /// Starting from a diamond head block, iterate over the instructions in one
281 /// successor block and try to match a store in the second successor.
283 bool MergedLoadStoreMotion::mergeStores(BasicBlock *HeadBB) {
285 bool MergedStores = false;
286 BasicBlock *TailBB = getDiamondTail(HeadBB);
287 BasicBlock *SinkBB = TailBB;
288 assert(SinkBB && "Footer of a diamond cannot be empty");
290 succ_iterator SI = succ_begin(HeadBB);
291 assert(SI != succ_end(HeadBB) && "Diamond head cannot have zero successors");
292 BasicBlock *Pred0 = *SI;
294 assert(SI != succ_end(HeadBB) && "Diamond head cannot have single successor");
295 BasicBlock *Pred1 = *SI;
296 // tail block of a diamond/hammock?
299 // bail out early if we can not merge into the footer BB
300 if (!SplitFooterBB && TailBB->hasNPredecessorsOrMore(3))
302 // #Instructions in Pred1 for Compile Time Control
303 auto InstsNoDbg = Pred1->instructionsWithoutDebug();
304 int Size1 = std::distance(InstsNoDbg.begin(), InstsNoDbg.end());
307 for (BasicBlock::reverse_iterator RBI = Pred0->rbegin(), RBE = Pred0->rend();
310 Instruction *I = &*RBI;
313 // Don't sink non-simple (atomic, volatile) stores.
314 auto *S0 = dyn_cast<StoreInst>(I);
315 if (!S0 || !S0->isSimple())
319 if (NStores * Size1 >= MagicCompileTimeControl)
321 if (StoreInst *S1 = canSinkFromBlock(Pred1, S0)) {
322 if (!canSinkStoresAndGEPs(S0, S1))
323 // Don't attempt to sink below stores that had to stick around
324 // But after removal of a store and some of its feeding
325 // instruction search again from the beginning since the iterator
326 // is likely stale at this point.
329 if (SinkBB == TailBB && TailBB->hasNPredecessorsOrMore(3)) {
330 // We have more than 2 predecessors. Insert a new block
331 // postdominating 2 predecessors we're going to sink from.
332 SinkBB = SplitBlockPredecessors(TailBB, {Pred0, Pred1}, ".sink.split");
338 sinkStoresAndGEPs(SinkBB, S0, S1);
339 RBI = Pred0->rbegin();
341 LLVM_DEBUG(dbgs() << "Search again\n"; Instruction *I = &*RBI; I->dump());
347 bool MergedLoadStoreMotion::run(Function &F, AliasAnalysis &AA) {
350 bool Changed = false;
351 LLVM_DEBUG(dbgs() << "Instruction Merger\n");
353 // Merge unconditional branches, allowing PRE to catch more
354 // optimization opportunities.
355 // This loop doesn't care about newly inserted/split blocks
356 // since they never will be diamond heads.
357 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE;) {
358 BasicBlock *BB = &*FI++;
360 // Hoist equivalent loads and sink stores
361 // outside diamonds when possible
362 if (isDiamondHead(BB)) {
363 Changed |= mergeStores(BB);
370 class MergedLoadStoreMotionLegacyPass : public FunctionPass {
371 const bool SplitFooterBB;
373 static char ID; // Pass identification, replacement for typeid
374 MergedLoadStoreMotionLegacyPass(bool SplitFooterBB = false)
375 : FunctionPass(ID), SplitFooterBB(SplitFooterBB) {
376 initializeMergedLoadStoreMotionLegacyPassPass(
377 *PassRegistry::getPassRegistry());
381 /// Run the transformation for each function
383 bool runOnFunction(Function &F) override {
386 MergedLoadStoreMotion Impl(SplitFooterBB);
387 return Impl.run(F, getAnalysis<AAResultsWrapperPass>().getAAResults());
391 void getAnalysisUsage(AnalysisUsage &AU) const override {
393 AU.setPreservesCFG();
394 AU.addRequired<AAResultsWrapperPass>();
395 AU.addPreserved<GlobalsAAWrapperPass>();
399 char MergedLoadStoreMotionLegacyPass::ID = 0;
400 } // anonymous namespace
403 /// createMergedLoadStoreMotionPass - The public interface to this file.
405 FunctionPass *llvm::createMergedLoadStoreMotionPass(bool SplitFooterBB) {
406 return new MergedLoadStoreMotionLegacyPass(SplitFooterBB);
409 INITIALIZE_PASS_BEGIN(MergedLoadStoreMotionLegacyPass, "mldst-motion",
410 "MergedLoadStoreMotion", false, false)
411 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
412 INITIALIZE_PASS_END(MergedLoadStoreMotionLegacyPass, "mldst-motion",
413 "MergedLoadStoreMotion", false, false)
416 MergedLoadStoreMotionPass::run(Function &F, FunctionAnalysisManager &AM) {
417 MergedLoadStoreMotion Impl(Options.SplitFooterBB);
418 auto &AA = AM.getResult<AAManager>(F);
419 if (!Impl.run(F, AA))
420 return PreservedAnalyses::all();
422 PreservedAnalyses PA;
423 if (!Options.SplitFooterBB)
424 PA.preserveSet<CFGAnalyses>();
425 PA.preserve<GlobalsAA>();