xref: /llvm-project/llvm/lib/Transforms/Scalar/MergedLoadStoreMotion.cpp (revision 95d2347ae16335aa30139c0aa6c050ac3dce2ad7)
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 // NOTE: This code no longer performs load hoisting, it is subsumed by GVNHoist.
23 //
24 //===----------------------------------------------------------------------===//
25 //
26 //
27 // Example:
28 // Diamond shaped code before merge:
29 //
30 //            header:
31 //                     br %cond, label %if.then, label %if.else
32 //                        +                    +
33 //                       +                      +
34 //                      +                        +
35 //            if.then:                         if.else:
36 //               %lt = load %addr_l               %le = load %addr_l
37 //               <use %lt>                        <use %le>
38 //               <...>                            <...>
39 //               store %st, %addr_s               store %se, %addr_s
40 //               br label %if.end                 br label %if.end
41 //                     +                         +
42 //                      +                       +
43 //                       +                     +
44 //            if.end ("footer"):
45 //                     <...>
46 //
47 // Diamond shaped code after merge:
48 //
49 //            header:
50 //                     %l = load %addr_l
51 //                     br %cond, label %if.then, label %if.else
52 //                        +                    +
53 //                       +                      +
54 //                      +                        +
55 //            if.then:                         if.else:
56 //               <use %l>                         <use %l>
57 //               <...>                            <...>
58 //               br label %if.end                 br label %if.end
59 //                      +                        +
60 //                       +                      +
61 //                        +                    +
62 //            if.end ("footer"):
63 //                     %s.sink = phi [%st, if.then], [%se, if.else]
64 //                     <...>
65 //                     store %s.sink, %addr_s
66 //                     <...>
67 //
68 //
69 //===----------------------- TODO -----------------------------------------===//
70 //
71 // 1) Generalize to regions other than diamonds
72 // 2) Be more aggressive merging memory operations
73 // Note that both changes require register pressure control
74 //
75 //===----------------------------------------------------------------------===//
76 
77 #include "llvm/Transforms/Scalar/MergedLoadStoreMotion.h"
78 #include "llvm/ADT/Statistic.h"
79 #include "llvm/Analysis/AliasAnalysis.h"
80 #include "llvm/Analysis/CFG.h"
81 #include "llvm/Analysis/GlobalsModRef.h"
82 #include "llvm/Analysis/Loads.h"
83 #include "llvm/Analysis/MemoryBuiltins.h"
84 #include "llvm/Analysis/MemoryDependenceAnalysis.h"
85 #include "llvm/Analysis/ValueTracking.h"
86 #include "llvm/IR/Metadata.h"
87 #include "llvm/IR/PatternMatch.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   MemoryDependenceResults *MD = nullptr;
103   AliasAnalysis *AA = nullptr;
104 
105   // The mergeLoad/Store algorithms could have Size0 * Size1 complexity,
106   // where Size0 and Size1 are the #instructions on the two sides of
107   // the diamond. The constant chosen here is arbitrary. Compiler Time
108   // Control is enforced by the check Size0 * Size1 < MagicCompileTimeControl.
109   const int MagicCompileTimeControl = 250;
110 
111 public:
112   bool run(Function &F, MemoryDependenceResults *MD, AliasAnalysis &AA);
113 
114 private:
115   ///
116   /// \brief Remove instruction from parent and update memory dependence
117   /// analysis.
118   ///
119   void removeInstruction(Instruction *Inst);
120   BasicBlock *getDiamondTail(BasicBlock *BB);
121   bool isDiamondHead(BasicBlock *BB);
122   // Routines for sinking stores
123   StoreInst *canSinkFromBlock(BasicBlock *BB, StoreInst *SI);
124   PHINode *getPHIOperand(BasicBlock *BB, StoreInst *S0, StoreInst *S1);
125   bool isStoreSinkBarrierInRange(const Instruction &Start,
126                                  const Instruction &End, MemoryLocation Loc);
127   bool sinkStore(BasicBlock *BB, StoreInst *SinkCand, StoreInst *ElseInst);
128   bool mergeStores(BasicBlock *BB);
129 };
130 } // end anonymous namespace
131 
132 ///
133 /// \brief Remove instruction from parent and update memory dependence analysis.
134 ///
135 void MergedLoadStoreMotion::removeInstruction(Instruction *Inst) {
136   // Notify the memory dependence analysis.
137   if (MD) {
138     MD->removeInstruction(Inst);
139     if (auto *LI = dyn_cast<LoadInst>(Inst))
140       MD->invalidateCachedPointerInfo(LI->getPointerOperand());
141     if (Inst->getType()->isPtrOrPtrVectorTy()) {
142       MD->invalidateCachedPointerInfo(Inst);
143     }
144   }
145   Inst->eraseFromParent();
146 }
147 
148 ///
149 /// \brief Return tail block of a diamond.
150 ///
151 BasicBlock *MergedLoadStoreMotion::getDiamondTail(BasicBlock *BB) {
152   assert(isDiamondHead(BB) && "Basic block is not head of a diamond");
153   return BB->getTerminator()->getSuccessor(0)->getSingleSuccessor();
154 }
155 
156 ///
157 /// \brief True when BB is the head of a diamond (hammock)
158 ///
159 bool MergedLoadStoreMotion::isDiamondHead(BasicBlock *BB) {
160   if (!BB)
161     return false;
162   auto *BI = dyn_cast<BranchInst>(BB->getTerminator());
163   if (!BI || !BI->isConditional())
164     return false;
165 
166   BasicBlock *Succ0 = BI->getSuccessor(0);
167   BasicBlock *Succ1 = BI->getSuccessor(1);
168 
169   if (!Succ0->getSinglePredecessor())
170     return false;
171   if (!Succ1->getSinglePredecessor())
172     return false;
173 
174   BasicBlock *Succ0Succ = Succ0->getSingleSuccessor();
175   BasicBlock *Succ1Succ = Succ1->getSingleSuccessor();
176   // Ignore triangles.
177   if (!Succ0Succ || !Succ1Succ || Succ0Succ != Succ1Succ)
178     return false;
179   return true;
180 }
181 
182 
183 ///
184 /// \brief True when instruction is a sink barrier for a store
185 /// located in Loc
186 ///
187 /// Whenever an instruction could possibly read or modify the
188 /// value being stored or protect against the store from
189 /// happening it is considered a sink barrier.
190 ///
191 bool MergedLoadStoreMotion::isStoreSinkBarrierInRange(const Instruction &Start,
192                                                       const Instruction &End,
193                                                       MemoryLocation Loc) {
194   for (const Instruction &Inst :
195        make_range(Start.getIterator(), End.getIterator()))
196     if (Inst.mayThrow())
197       return true;
198   return AA->canInstructionRangeModRef(Start, End, Loc, MRI_ModRef);
199 }
200 
201 ///
202 /// \brief Check if \p BB contains a store to the same address as \p SI
203 ///
204 /// \return The store in \p  when it is safe to sink. Otherwise return Null.
205 ///
206 StoreInst *MergedLoadStoreMotion::canSinkFromBlock(BasicBlock *BB1,
207                                                    StoreInst *Store0) {
208   DEBUG(dbgs() << "can Sink? : "; Store0->dump(); dbgs() << "\n");
209   BasicBlock *BB0 = Store0->getParent();
210   for (Instruction &Inst : reverse(*BB1)) {
211     auto *Store1 = dyn_cast<StoreInst>(&Inst);
212     if (!Store1)
213       continue;
214 
215     MemoryLocation Loc0 = MemoryLocation::get(Store0);
216     MemoryLocation Loc1 = MemoryLocation::get(Store1);
217     if (AA->isMustAlias(Loc0, Loc1) && Store0->isSameOperationAs(Store1) &&
218         !isStoreSinkBarrierInRange(*Store1->getNextNode(), BB1->back(), Loc1) &&
219         !isStoreSinkBarrierInRange(*Store0->getNextNode(), BB0->back(), Loc0)) {
220       return Store1;
221     }
222   }
223   return nullptr;
224 }
225 
226 ///
227 /// \brief Create a PHI node in BB for the operands of S0 and S1
228 ///
229 PHINode *MergedLoadStoreMotion::getPHIOperand(BasicBlock *BB, StoreInst *S0,
230                                               StoreInst *S1) {
231   // Create a phi if the values mismatch.
232   Value *Opd1 = S0->getValueOperand();
233   Value *Opd2 = S1->getValueOperand();
234   if (Opd1 == Opd2)
235     return nullptr;
236 
237   auto *NewPN = PHINode::Create(Opd1->getType(), 2, Opd2->getName() + ".sink",
238                                 &BB->front());
239   NewPN->addIncoming(Opd1, S0->getParent());
240   NewPN->addIncoming(Opd2, S1->getParent());
241   if (MD && NewPN->getType()->isPtrOrPtrVectorTy())
242     MD->invalidateCachedPointerInfo(NewPN);
243   return NewPN;
244 }
245 
246 ///
247 /// \brief Merge two stores to same address and sink into \p BB
248 ///
249 /// Also sinks GEP instruction computing the store address
250 ///
251 bool MergedLoadStoreMotion::sinkStore(BasicBlock *BB, StoreInst *S0,
252                                       StoreInst *S1) {
253   // Only one definition?
254   auto *A0 = dyn_cast<Instruction>(S0->getPointerOperand());
255   auto *A1 = dyn_cast<Instruction>(S1->getPointerOperand());
256   if (A0 && A1 && A0->isIdenticalTo(A1) && A0->hasOneUse() &&
257       (A0->getParent() == S0->getParent()) && A1->hasOneUse() &&
258       (A1->getParent() == S1->getParent()) && isa<GetElementPtrInst>(A0)) {
259     DEBUG(dbgs() << "Sink Instruction into BB \n"; BB->dump();
260           dbgs() << "Instruction Left\n"; S0->dump(); dbgs() << "\n";
261           dbgs() << "Instruction Right\n"; S1->dump(); dbgs() << "\n");
262     // Hoist the instruction.
263     BasicBlock::iterator InsertPt = BB->getFirstInsertionPt();
264     // Intersect optional metadata.
265     S0->andIRFlags(S1);
266     S0->dropUnknownNonDebugMetadata();
267 
268     // Create the new store to be inserted at the join point.
269     StoreInst *SNew = cast<StoreInst>(S0->clone());
270     Instruction *ANew = A0->clone();
271     SNew->insertBefore(&*InsertPt);
272     ANew->insertBefore(SNew);
273 
274     assert(S0->getParent() == A0->getParent());
275     assert(S1->getParent() == A1->getParent());
276 
277     // New PHI operand? Use it.
278     if (PHINode *NewPN = getPHIOperand(BB, S0, S1))
279       SNew->setOperand(0, NewPN);
280     removeInstruction(S0);
281     removeInstruction(S1);
282     A0->replaceAllUsesWith(ANew);
283     removeInstruction(A0);
284     A1->replaceAllUsesWith(ANew);
285     removeInstruction(A1);
286     return true;
287   }
288   return false;
289 }
290 
291 ///
292 /// \brief True when two stores are equivalent and can sink into the footer
293 ///
294 /// Starting from a diamond tail block, iterate over the instructions in one
295 /// predecessor block and try to match a store in the second predecessor.
296 ///
297 bool MergedLoadStoreMotion::mergeStores(BasicBlock *T) {
298 
299   bool MergedStores = false;
300   assert(T && "Footer of a diamond cannot be empty");
301 
302   pred_iterator PI = pred_begin(T), E = pred_end(T);
303   assert(PI != E);
304   BasicBlock *Pred0 = *PI;
305   ++PI;
306   BasicBlock *Pred1 = *PI;
307   ++PI;
308   // tail block  of a diamond/hammock?
309   if (Pred0 == Pred1)
310     return false; // No.
311   if (PI != E)
312     return false; // No. More than 2 predecessors.
313 
314   // #Instructions in Succ1 for Compile Time Control
315   int Size1 = Pred1->size();
316   int NStores = 0;
317 
318   for (BasicBlock::reverse_iterator RBI = Pred0->rbegin(), RBE = Pred0->rend();
319        RBI != RBE;) {
320 
321     Instruction *I = &*RBI;
322     ++RBI;
323 
324     // Don't sink non-simple (atomic, volatile) stores.
325     auto *S0 = dyn_cast<StoreInst>(I);
326     if (!S0 || !S0->isSimple())
327       continue;
328 
329     ++NStores;
330     if (NStores * Size1 >= MagicCompileTimeControl)
331       break;
332     if (StoreInst *S1 = canSinkFromBlock(Pred1, S0)) {
333       bool Res = sinkStore(T, S0, S1);
334       MergedStores |= Res;
335       // Don't attempt to sink below stores that had to stick around
336       // But after removal of a store and some of its feeding
337       // instruction search again from the beginning since the iterator
338       // is likely stale at this point.
339       if (!Res)
340         break;
341       RBI = Pred0->rbegin();
342       RBE = Pred0->rend();
343       DEBUG(dbgs() << "Search again\n"; Instruction *I = &*RBI; I->dump());
344     }
345   }
346   return MergedStores;
347 }
348 
349 bool MergedLoadStoreMotion::run(Function &F, MemoryDependenceResults *MD,
350                                 AliasAnalysis &AA) {
351   this->MD = MD;
352   this->AA = &AA;
353 
354   bool Changed = false;
355   DEBUG(dbgs() << "Instruction Merger\n");
356 
357   // Merge unconditional branches, allowing PRE to catch more
358   // optimization opportunities.
359   for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE;) {
360     BasicBlock *BB = &*FI++;
361 
362     // Hoist equivalent loads and sink stores
363     // outside diamonds when possible
364     if (isDiamondHead(BB)) {
365       Changed |= mergeStores(getDiamondTail(BB));
366     }
367   }
368   return Changed;
369 }
370 
371 namespace {
372 class MergedLoadStoreMotionLegacyPass : public FunctionPass {
373 public:
374   static char ID; // Pass identification, replacement for typeid
375   MergedLoadStoreMotionLegacyPass() : FunctionPass(ID) {
376     initializeMergedLoadStoreMotionLegacyPassPass(
377         *PassRegistry::getPassRegistry());
378   }
379 
380   ///
381   /// \brief Run the transformation for each function
382   ///
383   bool runOnFunction(Function &F) override {
384     if (skipFunction(F))
385       return false;
386     MergedLoadStoreMotion Impl;
387     auto *MDWP = getAnalysisIfAvailable<MemoryDependenceWrapperPass>();
388     return Impl.run(F, MDWP ? &MDWP->getMemDep() : nullptr,
389                     getAnalysis<AAResultsWrapperPass>().getAAResults());
390   }
391 
392 private:
393   void getAnalysisUsage(AnalysisUsage &AU) const override {
394     AU.setPreservesCFG();
395     AU.addRequired<AAResultsWrapperPass>();
396     AU.addPreserved<GlobalsAAWrapperPass>();
397     AU.addPreserved<MemoryDependenceWrapperPass>();
398   }
399 };
400 
401 char MergedLoadStoreMotionLegacyPass::ID = 0;
402 } // anonymous namespace
403 
404 ///
405 /// \brief createMergedLoadStoreMotionPass - The public interface to this file.
406 ///
407 FunctionPass *llvm::createMergedLoadStoreMotionPass() {
408   return new MergedLoadStoreMotionLegacyPass();
409 }
410 
411 INITIALIZE_PASS_BEGIN(MergedLoadStoreMotionLegacyPass, "mldst-motion",
412                       "MergedLoadStoreMotion", false, false)
413 INITIALIZE_PASS_DEPENDENCY(MemoryDependenceWrapperPass)
414 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
415 INITIALIZE_PASS_END(MergedLoadStoreMotionLegacyPass, "mldst-motion",
416                     "MergedLoadStoreMotion", false, false)
417 
418 PreservedAnalyses
419 MergedLoadStoreMotionPass::run(Function &F, FunctionAnalysisManager &AM) {
420   MergedLoadStoreMotion Impl;
421   auto *MD = AM.getCachedResult<MemoryDependenceAnalysis>(F);
422   auto &AA = AM.getResult<AAManager>(F);
423   if (!Impl.run(F, MD, AA))
424     return PreservedAnalyses::all();
425 
426   PreservedAnalyses PA;
427   PA.preserveSet<CFGAnalyses>();
428   PA.preserve<GlobalsAA>();
429   PA.preserve<MemoryDependenceAnalysis>();
430   return PA;
431 }
432