xref: /llvm-project/llvm/lib/Transforms/Scalar/MergedLoadStoreMotion.cpp (revision a494ae43bef09c8d0f6a6a98e92f3a89758247d5)
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.
12 //
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.
22 //
23 // NOTE: This code no longer performs load hoisting, it is subsumed by GVNHoist.
24 //
25 //===----------------------------------------------------------------------===//
26 //
27 //
28 // Example:
29 // Diamond shaped code before merge:
30 //
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 //                     <...>
47 //
48 // Diamond shaped code after merge:
49 //
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 //                     <...>
68 //
69 //
70 //===----------------------- TODO -----------------------------------------===//
71 //
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
75 //
76 //===----------------------------------------------------------------------===//
77 
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/Instructions.h"
86 #include "llvm/IR/Metadata.h"
87 #include "llvm/InitializePasses.h"
88 #include "llvm/Support/Debug.h"
89 #include "llvm/Support/raw_ostream.h"
90 #include "llvm/Transforms/Scalar.h"
91 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
92 
93 using namespace llvm;
94 
95 #define DEBUG_TYPE "mldst-motion"
96 
97 namespace {
98 //===----------------------------------------------------------------------===//
99 //                         MergedLoadStoreMotion Pass
100 //===----------------------------------------------------------------------===//
101 class MergedLoadStoreMotion {
102   AliasAnalysis *AA = nullptr;
103 
104   // The mergeLoad/Store algorithms could have Size0 * Size1 complexity,
105   // where Size0 and Size1 are the #instructions on the two sides of
106   // the diamond. The constant chosen here is arbitrary. Compiler Time
107   // Control is enforced by the check Size0 * Size1 < MagicCompileTimeControl.
108   const int MagicCompileTimeControl = 250;
109 
110   const bool SplitFooterBB;
111 public:
112   MergedLoadStoreMotion(bool SplitFooterBB) : SplitFooterBB(SplitFooterBB) {}
113   bool run(Function &F, AliasAnalysis &AA);
114 
115 private:
116   BasicBlock *getDiamondTail(BasicBlock *BB);
117   bool isDiamondHead(BasicBlock *BB);
118   // Routines for sinking stores
119   StoreInst *canSinkFromBlock(BasicBlock *BB, StoreInst *SI);
120   PHINode *getPHIOperand(BasicBlock *BB, StoreInst *S0, StoreInst *S1);
121   bool isStoreSinkBarrierInRange(const Instruction &Start,
122                                  const Instruction &End, MemoryLocation Loc);
123   bool canSinkStoresAndGEPs(StoreInst *S0, StoreInst *S1) const;
124   void sinkStoresAndGEPs(BasicBlock *BB, StoreInst *SinkCand,
125                          StoreInst *ElseInst);
126   bool mergeStores(BasicBlock *BB);
127 };
128 } // end anonymous namespace
129 
130 ///
131 /// Return tail block of a diamond.
132 ///
133 BasicBlock *MergedLoadStoreMotion::getDiamondTail(BasicBlock *BB) {
134   assert(isDiamondHead(BB) && "Basic block is not head of a diamond");
135   return BB->getTerminator()->getSuccessor(0)->getSingleSuccessor();
136 }
137 
138 ///
139 /// True when BB is the head of a diamond (hammock)
140 ///
141 bool MergedLoadStoreMotion::isDiamondHead(BasicBlock *BB) {
142   if (!BB)
143     return false;
144   auto *BI = dyn_cast<BranchInst>(BB->getTerminator());
145   if (!BI || !BI->isConditional())
146     return false;
147 
148   BasicBlock *Succ0 = BI->getSuccessor(0);
149   BasicBlock *Succ1 = BI->getSuccessor(1);
150 
151   if (!Succ0->getSinglePredecessor())
152     return false;
153   if (!Succ1->getSinglePredecessor())
154     return false;
155 
156   BasicBlock *Succ0Succ = Succ0->getSingleSuccessor();
157   BasicBlock *Succ1Succ = Succ1->getSingleSuccessor();
158   // Ignore triangles.
159   if (!Succ0Succ || !Succ1Succ || Succ0Succ != Succ1Succ)
160     return false;
161   return true;
162 }
163 
164 
165 ///
166 /// True when instruction is a sink barrier for a store
167 /// located in Loc
168 ///
169 /// Whenever an instruction could possibly read or modify the
170 /// value being stored or protect against the store from
171 /// happening it is considered a sink barrier.
172 ///
173 bool MergedLoadStoreMotion::isStoreSinkBarrierInRange(const Instruction &Start,
174                                                       const Instruction &End,
175                                                       MemoryLocation Loc) {
176   for (const Instruction &Inst :
177        make_range(Start.getIterator(), End.getIterator()))
178     if (Inst.mayThrow())
179       return true;
180   return AA->canInstructionRangeModRef(Start, End, Loc, ModRefInfo::ModRef);
181 }
182 
183 ///
184 /// Check if \p BB contains a store to the same address as \p SI
185 ///
186 /// \return The store in \p  when it is safe to sink. Otherwise return Null.
187 ///
188 StoreInst *MergedLoadStoreMotion::canSinkFromBlock(BasicBlock *BB1,
189                                                    StoreInst *Store0) {
190   LLVM_DEBUG(dbgs() << "can Sink? : "; Store0->dump(); dbgs() << "\n");
191   BasicBlock *BB0 = Store0->getParent();
192   for (Instruction &Inst : reverse(*BB1)) {
193     auto *Store1 = dyn_cast<StoreInst>(&Inst);
194     if (!Store1)
195       continue;
196 
197     MemoryLocation Loc0 = MemoryLocation::get(Store0);
198     MemoryLocation Loc1 = MemoryLocation::get(Store1);
199     if (AA->isMustAlias(Loc0, Loc1) && Store0->isSameOperationAs(Store1) &&
200         !isStoreSinkBarrierInRange(*Store1->getNextNode(), BB1->back(), Loc1) &&
201         !isStoreSinkBarrierInRange(*Store0->getNextNode(), BB0->back(), Loc0)) {
202       return Store1;
203     }
204   }
205   return nullptr;
206 }
207 
208 ///
209 /// Create a PHI node in BB for the operands of S0 and S1
210 ///
211 PHINode *MergedLoadStoreMotion::getPHIOperand(BasicBlock *BB, StoreInst *S0,
212                                               StoreInst *S1) {
213   // Create a phi if the values mismatch.
214   Value *Opd1 = S0->getValueOperand();
215   Value *Opd2 = S1->getValueOperand();
216   if (Opd1 == Opd2)
217     return nullptr;
218 
219   auto *NewPN = PHINode::Create(Opd1->getType(), 2, Opd2->getName() + ".sink",
220                                 &BB->front());
221   NewPN->applyMergedLocation(S0->getDebugLoc(), S1->getDebugLoc());
222   NewPN->addIncoming(Opd1, S0->getParent());
223   NewPN->addIncoming(Opd2, S1->getParent());
224   return NewPN;
225 }
226 
227 ///
228 /// Check if 2 stores can be sunk together with corresponding GEPs
229 ///
230 bool MergedLoadStoreMotion::canSinkStoresAndGEPs(StoreInst *S0,
231                                                  StoreInst *S1) const {
232   auto *A0 = dyn_cast<Instruction>(S0->getPointerOperand());
233   auto *A1 = dyn_cast<Instruction>(S1->getPointerOperand());
234   return A0 && A1 && A0->isIdenticalTo(A1) && A0->hasOneUse() &&
235          (A0->getParent() == S0->getParent()) && A1->hasOneUse() &&
236          (A1->getParent() == S1->getParent()) && isa<GetElementPtrInst>(A0);
237 }
238 
239 ///
240 /// Merge two stores to same address and sink into \p BB
241 ///
242 /// Also sinks GEP instruction computing the store address
243 ///
244 void MergedLoadStoreMotion::sinkStoresAndGEPs(BasicBlock *BB, StoreInst *S0,
245                                               StoreInst *S1) {
246   // Only one definition?
247   auto *A0 = dyn_cast<Instruction>(S0->getPointerOperand());
248   auto *A1 = dyn_cast<Instruction>(S1->getPointerOperand());
249   LLVM_DEBUG(dbgs() << "Sink Instruction into BB \n"; BB->dump();
250              dbgs() << "Instruction Left\n"; S0->dump(); dbgs() << "\n";
251              dbgs() << "Instruction Right\n"; S1->dump(); dbgs() << "\n");
252   // Hoist the instruction.
253   BasicBlock::iterator InsertPt = BB->getFirstInsertionPt();
254   // Intersect optional metadata.
255   S0->andIRFlags(S1);
256   S0->dropUnknownNonDebugMetadata();
257 
258   // Create the new store to be inserted at the join point.
259   StoreInst *SNew = cast<StoreInst>(S0->clone());
260   Instruction *ANew = A0->clone();
261   SNew->insertBefore(&*InsertPt);
262   ANew->insertBefore(SNew);
263 
264   assert(S0->getParent() == A0->getParent());
265   assert(S1->getParent() == A1->getParent());
266 
267   // New PHI operand? Use it.
268   if (PHINode *NewPN = getPHIOperand(BB, S0, S1))
269     SNew->setOperand(0, NewPN);
270   S0->eraseFromParent();
271   S1->eraseFromParent();
272   A0->replaceAllUsesWith(ANew);
273   A0->eraseFromParent();
274   A1->replaceAllUsesWith(ANew);
275   A1->eraseFromParent();
276 }
277 
278 ///
279 /// True when two stores are equivalent and can sink into the footer
280 ///
281 /// Starting from a diamond head block, iterate over the instructions in one
282 /// successor block and try to match a store in the second successor.
283 ///
284 bool MergedLoadStoreMotion::mergeStores(BasicBlock *HeadBB) {
285 
286   bool MergedStores = false;
287   BasicBlock *TailBB = getDiamondTail(HeadBB);
288   BasicBlock *SinkBB = TailBB;
289   assert(SinkBB && "Footer of a diamond cannot be empty");
290 
291   succ_iterator SI = succ_begin(HeadBB);
292   assert(SI != succ_end(HeadBB) && "Diamond head cannot have zero successors");
293   BasicBlock *Pred0 = *SI;
294   ++SI;
295   assert(SI != succ_end(HeadBB) && "Diamond head cannot have single successor");
296   BasicBlock *Pred1 = *SI;
297   // tail block  of a diamond/hammock?
298   if (Pred0 == Pred1)
299     return false; // No.
300   // bail out early if we can not merge into the footer BB
301   if (!SplitFooterBB && TailBB->hasNPredecessorsOrMore(3))
302     return false;
303   // #Instructions in Pred1 for Compile Time Control
304   auto InstsNoDbg = Pred1->instructionsWithoutDebug();
305   int Size1 = std::distance(InstsNoDbg.begin(), InstsNoDbg.end());
306   int NStores = 0;
307 
308   for (BasicBlock::reverse_iterator RBI = Pred0->rbegin(), RBE = Pred0->rend();
309        RBI != RBE;) {
310 
311     Instruction *I = &*RBI;
312     ++RBI;
313 
314     // Don't sink non-simple (atomic, volatile) stores.
315     auto *S0 = dyn_cast<StoreInst>(I);
316     if (!S0 || !S0->isSimple())
317       continue;
318 
319     ++NStores;
320     if (NStores * Size1 >= MagicCompileTimeControl)
321       break;
322     if (StoreInst *S1 = canSinkFromBlock(Pred1, S0)) {
323       if (!canSinkStoresAndGEPs(S0, S1))
324         // Don't attempt to sink below stores that had to stick around
325         // But after removal of a store and some of its feeding
326         // instruction search again from the beginning since the iterator
327         // is likely stale at this point.
328         break;
329 
330       if (SinkBB == TailBB && TailBB->hasNPredecessorsOrMore(3)) {
331         // We have more than 2 predecessors. Insert a new block
332         // postdominating 2 predecessors we're going to sink from.
333         SinkBB = SplitBlockPredecessors(TailBB, {Pred0, Pred1}, ".sink.split");
334         if (!SinkBB)
335           break;
336       }
337 
338       MergedStores = true;
339       sinkStoresAndGEPs(SinkBB, S0, S1);
340       RBI = Pred0->rbegin();
341       RBE = Pred0->rend();
342       LLVM_DEBUG(dbgs() << "Search again\n"; Instruction *I = &*RBI; I->dump());
343     }
344   }
345   return MergedStores;
346 }
347 
348 bool MergedLoadStoreMotion::run(Function &F, AliasAnalysis &AA) {
349   this->AA = &AA;
350 
351   bool Changed = false;
352   LLVM_DEBUG(dbgs() << "Instruction Merger\n");
353 
354   // Merge unconditional branches, allowing PRE to catch more
355   // optimization opportunities.
356   // This loop doesn't care about newly inserted/split blocks
357   // since they never will be diamond heads.
358   for (BasicBlock &BB : make_early_inc_range(F))
359     // Hoist equivalent loads and sink stores
360     // outside diamonds when possible
361     if (isDiamondHead(&BB))
362       Changed |= mergeStores(&BB);
363   return Changed;
364 }
365 
366 namespace {
367 class MergedLoadStoreMotionLegacyPass : public FunctionPass {
368   const bool SplitFooterBB;
369 public:
370   static char ID; // Pass identification, replacement for typeid
371   MergedLoadStoreMotionLegacyPass(bool SplitFooterBB = false)
372       : FunctionPass(ID), SplitFooterBB(SplitFooterBB) {
373     initializeMergedLoadStoreMotionLegacyPassPass(
374         *PassRegistry::getPassRegistry());
375   }
376 
377   ///
378   /// Run the transformation for each function
379   ///
380   bool runOnFunction(Function &F) override {
381     if (skipFunction(F))
382       return false;
383     MergedLoadStoreMotion Impl(SplitFooterBB);
384     return Impl.run(F, getAnalysis<AAResultsWrapperPass>().getAAResults());
385   }
386 
387 private:
388   void getAnalysisUsage(AnalysisUsage &AU) const override {
389     if (!SplitFooterBB)
390       AU.setPreservesCFG();
391     AU.addRequired<AAResultsWrapperPass>();
392     AU.addPreserved<GlobalsAAWrapperPass>();
393   }
394 };
395 
396 char MergedLoadStoreMotionLegacyPass::ID = 0;
397 } // anonymous namespace
398 
399 ///
400 /// createMergedLoadStoreMotionPass - The public interface to this file.
401 ///
402 FunctionPass *llvm::createMergedLoadStoreMotionPass(bool SplitFooterBB) {
403   return new MergedLoadStoreMotionLegacyPass(SplitFooterBB);
404 }
405 
406 INITIALIZE_PASS_BEGIN(MergedLoadStoreMotionLegacyPass, "mldst-motion",
407                       "MergedLoadStoreMotion", false, false)
408 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
409 INITIALIZE_PASS_END(MergedLoadStoreMotionLegacyPass, "mldst-motion",
410                     "MergedLoadStoreMotion", false, false)
411 
412 PreservedAnalyses
413 MergedLoadStoreMotionPass::run(Function &F, FunctionAnalysisManager &AM) {
414   MergedLoadStoreMotion Impl(Options.SplitFooterBB);
415   auto &AA = AM.getResult<AAManager>(F);
416   if (!Impl.run(F, AA))
417     return PreservedAnalyses::all();
418 
419   PreservedAnalyses PA;
420   if (!Options.SplitFooterBB)
421     PA.preserveSet<CFGAnalyses>();
422   return PA;
423 }
424 
425 void MergedLoadStoreMotionPass::printPipeline(
426     raw_ostream &OS, function_ref<StringRef(StringRef)> MapClassName2PassName) {
427   static_cast<PassInfoMixin<MergedLoadStoreMotionPass> *>(this)->printPipeline(
428       OS, MapClassName2PassName);
429   OS << "<";
430   OS << (Options.SplitFooterBB ? "" : "no-") << "split-footer-bb";
431   OS << ">";
432 }
433