[InstCombine] Signed saturation patterns
[llvm-complete.git] / lib / Transforms / Scalar / MergedLoadStoreMotion.cpp
blob9799ea7960ec51fd19b8468cf8b7d7e8804c226d
1 //===- MergedLoadStoreMotion.cpp - merge and hoist/sink load/stores -------===//
2 //
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
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 //! \file
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 //===----------------------------------------------------------------------===//
28 // Example:
29 // Diamond shaped code before merge:
31 // header:
32 // br %cond, label %if.then, label %if.else
33 // + +
34 // + +
35 // + +
36 // if.then: if.else:
37 // %lt = load %addr_l %le = load %addr_l
38 // <use %lt> <use %le>
39 // <...> <...>
40 // store %st, %addr_s store %se, %addr_s
41 // br label %if.end br label %if.end
42 // + +
43 // + +
44 // + +
45 // if.end ("footer"):
46 // <...>
48 // Diamond shaped code after merge:
50 // header:
51 // %l = load %addr_l
52 // br %cond, label %if.then, label %if.else
53 // + +
54 // + +
55 // + +
56 // if.then: if.else:
57 // <use %l> <use %l>
58 // <...> <...>
59 // br label %if.end br label %if.end
60 // + +
61 // + +
62 // + +
63 // if.end ("footer"):
64 // %s.sink = phi [%st, if.then], [%se, if.else]
65 // <...>
66 // store %s.sink, %addr_s
67 // <...>
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/Support/Debug.h"
87 #include "llvm/Support/raw_ostream.h"
88 #include "llvm/Transforms/Scalar.h"
89 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
91 using namespace llvm;
93 #define DEBUG_TYPE "mldst-motion"
95 namespace {
96 //===----------------------------------------------------------------------===//
97 // MergedLoadStoreMotion Pass
98 //===----------------------------------------------------------------------===//
99 class MergedLoadStoreMotion {
100 AliasAnalysis *AA = nullptr;
102 // The mergeLoad/Store algorithms could have Size0 * Size1 complexity,
103 // where Size0 and Size1 are the #instructions on the two sides of
104 // the diamond. The constant chosen here is arbitrary. Compiler Time
105 // Control is enforced by the check Size0 * Size1 < MagicCompileTimeControl.
106 const int MagicCompileTimeControl = 250;
108 const bool SplitFooterBB;
109 public:
110 MergedLoadStoreMotion(bool SplitFooterBB) : SplitFooterBB(SplitFooterBB) {}
111 bool run(Function &F, AliasAnalysis &AA);
113 private:
114 BasicBlock *getDiamondTail(BasicBlock *BB);
115 bool isDiamondHead(BasicBlock *BB);
116 // Routines for sinking stores
117 StoreInst *canSinkFromBlock(BasicBlock *BB, StoreInst *SI);
118 PHINode *getPHIOperand(BasicBlock *BB, StoreInst *S0, StoreInst *S1);
119 bool isStoreSinkBarrierInRange(const Instruction &Start,
120 const Instruction &End, MemoryLocation Loc);
121 bool canSinkStoresAndGEPs(StoreInst *S0, StoreInst *S1) const;
122 void sinkStoresAndGEPs(BasicBlock *BB, StoreInst *SinkCand,
123 StoreInst *ElseInst);
124 bool mergeStores(BasicBlock *BB);
126 } // end anonymous namespace
129 /// Return tail block of a diamond.
131 BasicBlock *MergedLoadStoreMotion::getDiamondTail(BasicBlock *BB) {
132 assert(isDiamondHead(BB) && "Basic block is not head of a diamond");
133 return BB->getTerminator()->getSuccessor(0)->getSingleSuccessor();
137 /// True when BB is the head of a diamond (hammock)
139 bool MergedLoadStoreMotion::isDiamondHead(BasicBlock *BB) {
140 if (!BB)
141 return false;
142 auto *BI = dyn_cast<BranchInst>(BB->getTerminator());
143 if (!BI || !BI->isConditional())
144 return false;
146 BasicBlock *Succ0 = BI->getSuccessor(0);
147 BasicBlock *Succ1 = BI->getSuccessor(1);
149 if (!Succ0->getSinglePredecessor())
150 return false;
151 if (!Succ1->getSinglePredecessor())
152 return false;
154 BasicBlock *Succ0Succ = Succ0->getSingleSuccessor();
155 BasicBlock *Succ1Succ = Succ1->getSingleSuccessor();
156 // Ignore triangles.
157 if (!Succ0Succ || !Succ1Succ || Succ0Succ != Succ1Succ)
158 return false;
159 return true;
164 /// True when instruction is a sink barrier for a store
165 /// located in Loc
167 /// Whenever an instruction could possibly read or modify the
168 /// value being stored or protect against the store from
169 /// happening it is considered a sink barrier.
171 bool MergedLoadStoreMotion::isStoreSinkBarrierInRange(const Instruction &Start,
172 const Instruction &End,
173 MemoryLocation Loc) {
174 for (const Instruction &Inst :
175 make_range(Start.getIterator(), End.getIterator()))
176 if (Inst.mayThrow())
177 return true;
178 return AA->canInstructionRangeModRef(Start, End, Loc, ModRefInfo::ModRef);
182 /// Check if \p BB contains a store to the same address as \p SI
184 /// \return The store in \p when it is safe to sink. Otherwise return Null.
186 StoreInst *MergedLoadStoreMotion::canSinkFromBlock(BasicBlock *BB1,
187 StoreInst *Store0) {
188 LLVM_DEBUG(dbgs() << "can Sink? : "; Store0->dump(); dbgs() << "\n");
189 BasicBlock *BB0 = Store0->getParent();
190 for (Instruction &Inst : reverse(*BB1)) {
191 auto *Store1 = dyn_cast<StoreInst>(&Inst);
192 if (!Store1)
193 continue;
195 MemoryLocation Loc0 = MemoryLocation::get(Store0);
196 MemoryLocation Loc1 = MemoryLocation::get(Store1);
197 if (AA->isMustAlias(Loc0, Loc1) && Store0->isSameOperationAs(Store1) &&
198 !isStoreSinkBarrierInRange(*Store1->getNextNode(), BB1->back(), Loc1) &&
199 !isStoreSinkBarrierInRange(*Store0->getNextNode(), BB0->back(), Loc0)) {
200 return Store1;
203 return nullptr;
207 /// Create a PHI node in BB for the operands of S0 and S1
209 PHINode *MergedLoadStoreMotion::getPHIOperand(BasicBlock *BB, StoreInst *S0,
210 StoreInst *S1) {
211 // Create a phi if the values mismatch.
212 Value *Opd1 = S0->getValueOperand();
213 Value *Opd2 = S1->getValueOperand();
214 if (Opd1 == Opd2)
215 return nullptr;
217 auto *NewPN = PHINode::Create(Opd1->getType(), 2, Opd2->getName() + ".sink",
218 &BB->front());
219 NewPN->applyMergedLocation(S0->getDebugLoc(), S1->getDebugLoc());
220 NewPN->addIncoming(Opd1, S0->getParent());
221 NewPN->addIncoming(Opd2, S1->getParent());
222 return NewPN;
226 /// Check if 2 stores can be sunk together with corresponding GEPs
228 bool MergedLoadStoreMotion::canSinkStoresAndGEPs(StoreInst *S0,
229 StoreInst *S1) const {
230 auto *A0 = dyn_cast<Instruction>(S0->getPointerOperand());
231 auto *A1 = dyn_cast<Instruction>(S1->getPointerOperand());
232 return A0 && A1 && A0->isIdenticalTo(A1) && A0->hasOneUse() &&
233 (A0->getParent() == S0->getParent()) && A1->hasOneUse() &&
234 (A1->getParent() == S1->getParent()) && isa<GetElementPtrInst>(A0);
238 /// Merge two stores to same address and sink into \p BB
240 /// Also sinks GEP instruction computing the store address
242 void MergedLoadStoreMotion::sinkStoresAndGEPs(BasicBlock *BB, StoreInst *S0,
243 StoreInst *S1) {
244 // Only one definition?
245 auto *A0 = dyn_cast<Instruction>(S0->getPointerOperand());
246 auto *A1 = dyn_cast<Instruction>(S1->getPointerOperand());
247 LLVM_DEBUG(dbgs() << "Sink Instruction into BB \n"; BB->dump();
248 dbgs() << "Instruction Left\n"; S0->dump(); dbgs() << "\n";
249 dbgs() << "Instruction Right\n"; S1->dump(); dbgs() << "\n");
250 // Hoist the instruction.
251 BasicBlock::iterator InsertPt = BB->getFirstInsertionPt();
252 // Intersect optional metadata.
253 S0->andIRFlags(S1);
254 S0->dropUnknownNonDebugMetadata();
256 // Create the new store to be inserted at the join point.
257 StoreInst *SNew = cast<StoreInst>(S0->clone());
258 Instruction *ANew = A0->clone();
259 SNew->insertBefore(&*InsertPt);
260 ANew->insertBefore(SNew);
262 assert(S0->getParent() == A0->getParent());
263 assert(S1->getParent() == A1->getParent());
265 // New PHI operand? Use it.
266 if (PHINode *NewPN = getPHIOperand(BB, S0, S1))
267 SNew->setOperand(0, NewPN);
268 S0->eraseFromParent();
269 S1->eraseFromParent();
270 A0->replaceAllUsesWith(ANew);
271 A0->eraseFromParent();
272 A1->replaceAllUsesWith(ANew);
273 A1->eraseFromParent();
277 /// True when two stores are equivalent and can sink into the footer
279 /// Starting from a diamond head block, iterate over the instructions in one
280 /// successor block and try to match a store in the second successor.
282 bool MergedLoadStoreMotion::mergeStores(BasicBlock *HeadBB) {
284 bool MergedStores = false;
285 BasicBlock *TailBB = getDiamondTail(HeadBB);
286 BasicBlock *SinkBB = TailBB;
287 assert(SinkBB && "Footer of a diamond cannot be empty");
289 succ_iterator SI = succ_begin(HeadBB);
290 assert(SI != succ_end(HeadBB) && "Diamond head cannot have zero successors");
291 BasicBlock *Pred0 = *SI;
292 ++SI;
293 assert(SI != succ_end(HeadBB) && "Diamond head cannot have single successor");
294 BasicBlock *Pred1 = *SI;
295 // tail block of a diamond/hammock?
296 if (Pred0 == Pred1)
297 return false; // No.
298 // bail out early if we can not merge into the footer BB
299 if (!SplitFooterBB && TailBB->hasNPredecessorsOrMore(3))
300 return false;
301 // #Instructions in Pred1 for Compile Time Control
302 auto InstsNoDbg = Pred1->instructionsWithoutDebug();
303 int Size1 = std::distance(InstsNoDbg.begin(), InstsNoDbg.end());
304 int NStores = 0;
306 for (BasicBlock::reverse_iterator RBI = Pred0->rbegin(), RBE = Pred0->rend();
307 RBI != RBE;) {
309 Instruction *I = &*RBI;
310 ++RBI;
312 // Don't sink non-simple (atomic, volatile) stores.
313 auto *S0 = dyn_cast<StoreInst>(I);
314 if (!S0 || !S0->isSimple())
315 continue;
317 ++NStores;
318 if (NStores * Size1 >= MagicCompileTimeControl)
319 break;
320 if (StoreInst *S1 = canSinkFromBlock(Pred1, S0)) {
321 if (!canSinkStoresAndGEPs(S0, S1))
322 // Don't attempt to sink below stores that had to stick around
323 // But after removal of a store and some of its feeding
324 // instruction search again from the beginning since the iterator
325 // is likely stale at this point.
326 break;
328 if (SinkBB == TailBB && TailBB->hasNPredecessorsOrMore(3)) {
329 // We have more than 2 predecessors. Insert a new block
330 // postdominating 2 predecessors we're going to sink from.
331 SinkBB = SplitBlockPredecessors(TailBB, {Pred0, Pred1}, ".sink.split");
332 if (!SinkBB)
333 break;
336 MergedStores = true;
337 sinkStoresAndGEPs(SinkBB, S0, S1);
338 RBI = Pred0->rbegin();
339 RBE = Pred0->rend();
340 LLVM_DEBUG(dbgs() << "Search again\n"; Instruction *I = &*RBI; I->dump());
343 return MergedStores;
346 bool MergedLoadStoreMotion::run(Function &F, AliasAnalysis &AA) {
347 this->AA = &AA;
349 bool Changed = false;
350 LLVM_DEBUG(dbgs() << "Instruction Merger\n");
352 // Merge unconditional branches, allowing PRE to catch more
353 // optimization opportunities.
354 // This loop doesn't care about newly inserted/split blocks
355 // since they never will be diamond heads.
356 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE;) {
357 BasicBlock *BB = &*FI++;
359 // Hoist equivalent loads and sink stores
360 // outside diamonds when possible
361 if (isDiamondHead(BB)) {
362 Changed |= mergeStores(BB);
365 return Changed;
368 namespace {
369 class MergedLoadStoreMotionLegacyPass : public FunctionPass {
370 const bool SplitFooterBB;
371 public:
372 static char ID; // Pass identification, replacement for typeid
373 MergedLoadStoreMotionLegacyPass(bool SplitFooterBB = false)
374 : FunctionPass(ID), SplitFooterBB(SplitFooterBB) {
375 initializeMergedLoadStoreMotionLegacyPassPass(
376 *PassRegistry::getPassRegistry());
380 /// Run the transformation for each function
382 bool runOnFunction(Function &F) override {
383 if (skipFunction(F))
384 return false;
385 MergedLoadStoreMotion Impl(SplitFooterBB);
386 return Impl.run(F, getAnalysis<AAResultsWrapperPass>().getAAResults());
389 private:
390 void getAnalysisUsage(AnalysisUsage &AU) const override {
391 if (!SplitFooterBB)
392 AU.setPreservesCFG();
393 AU.addRequired<AAResultsWrapperPass>();
394 AU.addPreserved<GlobalsAAWrapperPass>();
398 char MergedLoadStoreMotionLegacyPass::ID = 0;
399 } // anonymous namespace
402 /// createMergedLoadStoreMotionPass - The public interface to this file.
404 FunctionPass *llvm::createMergedLoadStoreMotionPass(bool SplitFooterBB) {
405 return new MergedLoadStoreMotionLegacyPass(SplitFooterBB);
408 INITIALIZE_PASS_BEGIN(MergedLoadStoreMotionLegacyPass, "mldst-motion",
409 "MergedLoadStoreMotion", false, false)
410 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
411 INITIALIZE_PASS_END(MergedLoadStoreMotionLegacyPass, "mldst-motion",
412 "MergedLoadStoreMotion", false, false)
414 PreservedAnalyses
415 MergedLoadStoreMotionPass::run(Function &F, FunctionAnalysisManager &AM) {
416 MergedLoadStoreMotion Impl(Options.SplitFooterBB);
417 auto &AA = AM.getResult<AAManager>(F);
418 if (!Impl.run(F, AA))
419 return PreservedAnalyses::all();
421 PreservedAnalyses PA;
422 if (!Options.SplitFooterBB)
423 PA.preserveSet<CFGAnalyses>();
424 PA.preserve<GlobalsAA>();
425 return PA;