xref: /llvm-project/llvm/lib/Transforms/Scalar/MergedLoadStoreMotion.cpp (revision 44faf7f407072d245fd98bcb92644b77469dbfb2)
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 //===----------------------------------------------------------------------===//
23 //
24 //
25 // Example:
26 // Diamond shaped code before merge:
27 //
28 //            header:
29 //                     br %cond, label %if.then, label %if.else
30 //                        +                    +
31 //                       +                      +
32 //                      +                        +
33 //            if.then:                         if.else:
34 //               %lt = load %addr_l               %le = load %addr_l
35 //               <use %lt>                        <use %le>
36 //               <...>                            <...>
37 //               store %st, %addr_s               store %se, %addr_s
38 //               br label %if.end                 br label %if.end
39 //                     +                         +
40 //                      +                       +
41 //                       +                     +
42 //            if.end ("footer"):
43 //                     <...>
44 //
45 // Diamond shaped code after merge:
46 //
47 //            header:
48 //                     %l = load %addr_l
49 //                     br %cond, label %if.then, label %if.else
50 //                        +                    +
51 //                       +                      +
52 //                      +                        +
53 //            if.then:                         if.else:
54 //               <use %l>                         <use %l>
55 //               <...>                            <...>
56 //               br label %if.end                 br label %if.end
57 //                      +                        +
58 //                       +                      +
59 //                        +                    +
60 //            if.end ("footer"):
61 //                     %s.sink = phi [%st, if.then], [%se, if.else]
62 //                     <...>
63 //                     store %s.sink, %addr_s
64 //                     <...>
65 //
66 //
67 //===----------------------- TODO -----------------------------------------===//
68 //
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
72 //
73 //===----------------------------------------------------------------------===//
74 
75 #include "llvm/ADT/Statistic.h"
76 #include "llvm/Analysis/AliasAnalysis.h"
77 #include "llvm/Analysis/CFG.h"
78 #include "llvm/Analysis/GlobalsModRef.h"
79 #include "llvm/Analysis/Loads.h"
80 #include "llvm/Analysis/MemoryBuiltins.h"
81 #include "llvm/Analysis/MemoryDependenceAnalysis.h"
82 #include "llvm/Analysis/ValueTracking.h"
83 #include "llvm/IR/Metadata.h"
84 #include "llvm/IR/PatternMatch.h"
85 #include "llvm/Support/Debug.h"
86 #include "llvm/Support/raw_ostream.h"
87 #include "llvm/Transforms/Scalar.h"
88 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
89 #include "llvm/Transforms/Utils/SSAUpdater.h"
90 
91 using namespace llvm;
92 
93 #define DEBUG_TYPE "mldst-motion"
94 
95 //===----------------------------------------------------------------------===//
96 //                         MergedLoadStoreMotion Pass
97 //===----------------------------------------------------------------------===//
98 
99 namespace {
100 class MergedLoadStoreMotion : public FunctionPass {
101   AliasAnalysis *AA;
102   MemoryDependenceResults *MD;
103 
104 public:
105   static char ID; // Pass identification, replacement for typeid
106   MergedLoadStoreMotion() : FunctionPass(ID), MD(nullptr) {
107     initializeMergedLoadStoreMotionPass(*PassRegistry::getPassRegistry());
108   }
109 
110   bool runOnFunction(Function &F) override;
111 
112 private:
113   // This transformation requires dominator postdominator info
114   void getAnalysisUsage(AnalysisUsage &AU) const override {
115     AU.setPreservesCFG();
116     AU.addRequired<AAResultsWrapperPass>();
117     AU.addPreserved<GlobalsAAWrapperPass>();
118     AU.addPreserved<MemoryDependenceWrapperPass>();
119   }
120 };
121 
122 char MergedLoadStoreMotion::ID = 0;
123 } // anonymous namespace
124 
125 // The mergeLoad/Store algorithms could have Size0 * Size1 complexity,
126 // where Size0 and Size1 are the #instructions on the two sides of
127 // the diamond. The constant chosen here is arbitrary. Compiler Time
128 // Control is enforced by the check Size0 * Size1 < MagicCompileTimeControl.
129 const int MagicCompileTimeControl = 250;
130 
131 ///
132 /// \brief createMergedLoadStoreMotionPass - The public interface to this file.
133 ///
134 FunctionPass *llvm::createMergedLoadStoreMotionPass() {
135   return new MergedLoadStoreMotion();
136 }
137 
138 INITIALIZE_PASS_BEGIN(MergedLoadStoreMotion, "mldst-motion",
139                       "MergedLoadStoreMotion", false, false)
140 INITIALIZE_PASS_DEPENDENCY(MemoryDependenceWrapperPass)
141 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
142 INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
143 INITIALIZE_PASS_END(MergedLoadStoreMotion, "mldst-motion",
144                     "MergedLoadStoreMotion", false, false)
145 
146 ///
147 /// \brief Remove instruction from parent and update memory dependence analysis.
148 ///
149 static void removeInstruction(Instruction *Inst, MemoryDependenceResults *MD) {
150   // Notify the memory dependence analysis.
151   if (MD) {
152     MD->removeInstruction(Inst);
153     if (auto *LI = dyn_cast<LoadInst>(Inst))
154       MD->invalidateCachedPointerInfo(LI->getPointerOperand());
155     if (Inst->getType()->isPtrOrPtrVectorTy()) {
156       MD->invalidateCachedPointerInfo(Inst);
157     }
158   }
159   Inst->eraseFromParent();
160 }
161 
162 ///
163 /// \brief True when BB is the head of a diamond (hammock)
164 ///
165 static bool isDiamondHead(BasicBlock *BB) {
166   if (!BB)
167     return false;
168   auto *BI = dyn_cast<BranchInst>(BB->getTerminator());
169   if (!BI || !BI->isConditional())
170     return false;
171 
172   BasicBlock *Succ0 = BI->getSuccessor(0);
173   BasicBlock *Succ1 = BI->getSuccessor(1);
174 
175   if (!Succ0->getSinglePredecessor())
176     return false;
177   if (!Succ1->getSinglePredecessor())
178     return false;
179 
180   BasicBlock *Succ0Succ = Succ0->getSingleSuccessor();
181   BasicBlock *Succ1Succ = Succ1->getSingleSuccessor();
182   // Ignore triangles.
183   if (!Succ0Succ || !Succ1Succ || Succ0Succ != Succ1Succ)
184     return false;
185   return true;
186 }
187 
188 ///
189 /// \brief Return tail block of a diamond.
190 ///
191 static BasicBlock *getDiamondTail(BasicBlock *BB) {
192   assert(isDiamondHead(BB) && "Basic block is not head of a diamond");
193   return BB->getTerminator()->getSuccessor(0)->getSingleSuccessor();
194 }
195 
196 ///
197 /// \brief True when instruction is a hoist barrier for a load
198 ///
199 /// Whenever an instruction could possibly modify the value
200 /// being loaded or protect against the load from happening
201 /// it is considered a hoist barrier.
202 ///
203 static bool isLoadHoistBarrierInRange(const Instruction &Start,
204                                       const Instruction &End, LoadInst *LI,
205                                       bool SafeToLoadUnconditionally,
206                                       AliasAnalysis *AA) {
207   if (!SafeToLoadUnconditionally)
208     for (const Instruction &Inst :
209          make_range(Start.getIterator(), End.getIterator()))
210       if (!isGuaranteedToTransferExecutionToSuccessor(&Inst))
211         return true;
212   MemoryLocation Loc = MemoryLocation::get(LI);
213   return AA->canInstructionRangeModRef(Start, End, Loc, MRI_Mod);
214 }
215 
216 ///
217 /// \brief Decide if a load can be hoisted
218 ///
219 /// When there is a load in \p BB to the same address as \p LI
220 /// and it can be hoisted from \p BB, return that load.
221 /// Otherwise return Null.
222 ///
223 static LoadInst *canHoistFromBlock(BasicBlock *BB1, LoadInst *Load0,
224                                    AliasAnalysis *AA) {
225   BasicBlock *BB0 = Load0->getParent();
226   BasicBlock *Head = BB0->getSinglePredecessor();
227   bool SafeToLoadUnconditionally = isSafeToLoadUnconditionally(
228       Load0->getPointerOperand(), Load0->getAlignment(),
229       Load0->getModule()->getDataLayout(),
230       /*ScanFrom=*/Head->getTerminator());
231   for (BasicBlock::iterator BBI = BB1->begin(), BBE = BB1->end(); BBI != BBE;
232        ++BBI) {
233     Instruction *Inst = &*BBI;
234 
235     // Only merge and hoist loads when their result in used only in BB
236     auto *Load1 = dyn_cast<LoadInst>(Inst);
237     if (!Load1 || Inst->isUsedOutsideOfBlock(BB1))
238       continue;
239 
240     MemoryLocation Loc0 = MemoryLocation::get(Load0);
241     MemoryLocation Loc1 = MemoryLocation::get(Load1);
242     if (AA->isMustAlias(Loc0, Loc1) && Load0->isSameOperationAs(Load1) &&
243         !isLoadHoistBarrierInRange(BB1->front(), *Load1, Load1,
244                                    SafeToLoadUnconditionally, AA) &&
245         !isLoadHoistBarrierInRange(BB0->front(), *Load0, Load0,
246                                    SafeToLoadUnconditionally, AA)) {
247       return Load1;
248     }
249   }
250   return nullptr;
251 }
252 
253 ///
254 /// \brief Merge two equivalent instructions \p HoistCand and \p ElseInst into
255 /// \p BB
256 ///
257 /// BB is the head of a diamond
258 ///
259 static void hoistInstruction(BasicBlock *BB, Instruction *HoistCand,
260                              Instruction *ElseInst,
261                              MemoryDependenceResults *MD) {
262   DEBUG(dbgs() << " Hoist Instruction into BB \n"; BB->dump();
263         dbgs() << "Instruction Left\n"; HoistCand->dump(); dbgs() << "\n";
264         dbgs() << "Instruction Right\n"; ElseInst->dump(); dbgs() << "\n");
265   // Hoist the instruction.
266   assert(HoistCand->getParent() != BB);
267 
268   // Intersect optional metadata.
269   HoistCand->intersectOptionalDataWith(ElseInst);
270   HoistCand->dropUnknownNonDebugMetadata();
271 
272   // Prepend point for instruction insert
273   Instruction *HoistPt = BB->getTerminator();
274 
275   // Merged instruction
276   Instruction *HoistedInst = HoistCand->clone();
277 
278   // Hoist instruction.
279   HoistedInst->insertBefore(HoistPt);
280 
281   HoistCand->replaceAllUsesWith(HoistedInst);
282   removeInstruction(HoistCand, MD);
283   // Replace the else block instruction.
284   ElseInst->replaceAllUsesWith(HoistedInst);
285   removeInstruction(ElseInst, MD);
286 }
287 
288 ///
289 /// \brief Return true if no operand of \p I is defined in I's parent block
290 ///
291 static bool isSafeToHoist(Instruction *I) {
292   BasicBlock *Parent = I->getParent();
293   for (Use &U : I->operands())
294     if (auto *Instr = dyn_cast<Instruction>(&U))
295       if (Instr->getParent() == Parent)
296         return false;
297   return true;
298 }
299 
300 ///
301 /// \brief Merge two equivalent loads and GEPs and hoist into diamond head
302 ///
303 static bool hoistLoad(BasicBlock *BB, LoadInst *L0, LoadInst *L1,
304                       MemoryDependenceResults *MD) {
305   // Only one definition?
306   auto *A0 = dyn_cast<Instruction>(L0->getPointerOperand());
307   auto *A1 = dyn_cast<Instruction>(L1->getPointerOperand());
308   if (A0 && A1 && A0->isIdenticalTo(A1) && isSafeToHoist(A0) &&
309       A0->hasOneUse() && (A0->getParent() == L0->getParent()) &&
310       A1->hasOneUse() && (A1->getParent() == L1->getParent()) &&
311       isa<GetElementPtrInst>(A0)) {
312     DEBUG(dbgs() << "Hoist Instruction into BB \n"; BB->dump();
313           dbgs() << "Instruction Left\n"; L0->dump(); dbgs() << "\n";
314           dbgs() << "Instruction Right\n"; L1->dump(); dbgs() << "\n");
315     hoistInstruction(BB, A0, A1, MD);
316     hoistInstruction(BB, L0, L1, MD);
317     return true;
318   }
319   return false;
320 }
321 
322 ///
323 /// \brief Try to hoist two loads to same address into diamond header
324 ///
325 /// Starting from a diamond head block, iterate over the instructions in one
326 /// successor block and try to match a load in the second successor.
327 ///
328 static bool mergeLoads(BasicBlock *BB, AliasAnalysis *AA,
329                        MemoryDependenceResults *MD) {
330   bool MergedLoads = false;
331   assert(isDiamondHead(BB));
332   BranchInst *BI = cast<BranchInst>(BB->getTerminator());
333   BasicBlock *Succ0 = BI->getSuccessor(0);
334   BasicBlock *Succ1 = BI->getSuccessor(1);
335   // #Instructions in Succ1 for Compile Time Control
336   int Size1 = Succ1->size();
337   int NLoads = 0;
338   for (BasicBlock::iterator BBI = Succ0->begin(), BBE = Succ0->end();
339        BBI != BBE;) {
340     Instruction *I = &*BBI;
341     ++BBI;
342 
343     // Don't move non-simple (atomic, volatile) loads.
344     auto *L0 = dyn_cast<LoadInst>(I);
345     if (!L0 || !L0->isSimple() || L0->isUsedOutsideOfBlock(Succ0))
346       continue;
347 
348     ++NLoads;
349     if (NLoads * Size1 >= MagicCompileTimeControl)
350       break;
351     if (LoadInst *L1 = canHoistFromBlock(Succ1, L0, AA)) {
352       bool Res = hoistLoad(BB, L0, L1, MD);
353       MergedLoads |= Res;
354       // Don't attempt to hoist above loads that had not been hoisted.
355       if (!Res)
356         break;
357     }
358   }
359   return MergedLoads;
360 }
361 
362 ///
363 /// \brief True when instruction is a sink barrier for a store
364 /// located in Loc
365 ///
366 /// Whenever an instruction could possibly read or modify the
367 /// value being stored or protect against the store from
368 /// happening it is considered a sink barrier.
369 ///
370 static bool isStoreSinkBarrierInRange(const Instruction &Start,
371                                       const Instruction &End,
372                                       MemoryLocation Loc, AliasAnalysis *AA) {
373   for (const Instruction &Inst :
374        make_range(Start.getIterator(), End.getIterator()))
375     if (Inst.mayThrow())
376       return true;
377   return AA->canInstructionRangeModRef(Start, End, Loc, MRI_ModRef);
378 }
379 
380 ///
381 /// \brief Check if \p BB contains a store to the same address as \p SI
382 ///
383 /// \return The store in \p  when it is safe to sink. Otherwise return Null.
384 ///
385 static StoreInst *canSinkFromBlock(BasicBlock *BB1, StoreInst *Store0,
386                                    AliasAnalysis *AA) {
387   DEBUG(dbgs() << "can Sink? : "; Store0->dump(); dbgs() << "\n");
388   BasicBlock *BB0 = Store0->getParent();
389   for (BasicBlock::reverse_iterator RBI = BB1->rbegin(), RBE = BB1->rend();
390        RBI != RBE; ++RBI) {
391     Instruction *Inst = &*RBI;
392 
393     auto *Store1 = dyn_cast<StoreInst>(Inst);
394     if (!Store1)
395       continue;
396 
397     MemoryLocation Loc0 = MemoryLocation::get(Store0);
398     MemoryLocation Loc1 = MemoryLocation::get(Store1);
399     if (AA->isMustAlias(Loc0, Loc1) && Store0->isSameOperationAs(Store1) &&
400         !isStoreSinkBarrierInRange(*Store1->getNextNode(), BB1->back(), Loc1,
401                                    AA) &&
402         !isStoreSinkBarrierInRange(*Store0->getNextNode(), BB0->back(), Loc0,
403                                    AA)) {
404       return Store1;
405     }
406   }
407   return nullptr;
408 }
409 
410 ///
411 /// \brief Create a PHI node in BB for the operands of S0 and S1
412 ///
413 static PHINode *getPHIOperand(BasicBlock *BB, StoreInst *S0, StoreInst *S1,
414                               MemoryDependenceResults *MD) {
415   // Create a phi if the values mismatch.
416   Value *Opd1 = S0->getValueOperand();
417   Value *Opd2 = S1->getValueOperand();
418   if (Opd1 == Opd2)
419     return nullptr;
420 
421   auto *NewPN = PHINode::Create(Opd1->getType(), 2, Opd2->getName() + ".sink",
422                                 &BB->front());
423   NewPN->addIncoming(Opd1, S0->getParent());
424   NewPN->addIncoming(Opd2, S1->getParent());
425   if (MD && NewPN->getType()->getScalarType()->isPointerTy())
426     MD->invalidateCachedPointerInfo(NewPN);
427   return NewPN;
428 }
429 
430 ///
431 /// \brief Merge two stores to same address and sink into \p BB
432 ///
433 /// Also sinks GEP instruction computing the store address
434 ///
435 static bool sinkStore(BasicBlock *BB, StoreInst *S0, StoreInst *S1,
436                       MemoryDependenceResults *MD) {
437   // Only one definition?
438   auto *A0 = dyn_cast<Instruction>(S0->getPointerOperand());
439   auto *A1 = dyn_cast<Instruction>(S1->getPointerOperand());
440   if (A0 && A1 && A0->isIdenticalTo(A1) && A0->hasOneUse() &&
441       (A0->getParent() == S0->getParent()) && A1->hasOneUse() &&
442       (A1->getParent() == S1->getParent()) && isa<GetElementPtrInst>(A0)) {
443     DEBUG(dbgs() << "Sink Instruction into BB \n"; BB->dump();
444           dbgs() << "Instruction Left\n"; S0->dump(); dbgs() << "\n";
445           dbgs() << "Instruction Right\n"; S1->dump(); dbgs() << "\n");
446     // Hoist the instruction.
447     BasicBlock::iterator InsertPt = BB->getFirstInsertionPt();
448     // Intersect optional metadata.
449     S0->intersectOptionalDataWith(S1);
450     S0->dropUnknownNonDebugMetadata();
451 
452     // Create the new store to be inserted at the join point.
453     StoreInst *SNew = cast<StoreInst>(S0->clone());
454     Instruction *ANew = A0->clone();
455     SNew->insertBefore(&*InsertPt);
456     ANew->insertBefore(SNew);
457 
458     assert(S0->getParent() == A0->getParent());
459     assert(S1->getParent() == A1->getParent());
460 
461     // New PHI operand? Use it.
462     if (PHINode *NewPN = getPHIOperand(BB, S0, S1, MD))
463       SNew->setOperand(0, NewPN);
464     removeInstruction(S0, MD);
465     removeInstruction(S1, MD);
466     A0->replaceAllUsesWith(ANew);
467     removeInstruction(A0, MD);
468     A1->replaceAllUsesWith(ANew);
469     removeInstruction(A1, MD);
470     return true;
471   }
472   return false;
473 }
474 
475 ///
476 /// \brief True when two stores are equivalent and can sink into the footer
477 ///
478 /// Starting from a diamond tail block, iterate over the instructions in one
479 /// predecessor block and try to match a store in the second predecessor.
480 ///
481 static bool mergeStores(BasicBlock *T, AliasAnalysis *AA,
482                         MemoryDependenceResults *MD) {
483 
484   bool MergedStores = false;
485   assert(T && "Footer of a diamond cannot be empty");
486 
487   pred_iterator PI = pred_begin(T), E = pred_end(T);
488   assert(PI != E);
489   BasicBlock *Pred0 = *PI;
490   ++PI;
491   BasicBlock *Pred1 = *PI;
492   ++PI;
493   // tail block  of a diamond/hammock?
494   if (Pred0 == Pred1)
495     return false; // No.
496   if (PI != E)
497     return false; // No. More than 2 predecessors.
498 
499   // #Instructions in Succ1 for Compile Time Control
500   int Size1 = Pred1->size();
501   int NStores = 0;
502 
503   for (BasicBlock::reverse_iterator RBI = Pred0->rbegin(), RBE = Pred0->rend();
504        RBI != RBE;) {
505 
506     Instruction *I = &*RBI;
507     ++RBI;
508 
509     // Don't sink non-simple (atomic, volatile) stores.
510     auto *S0 = dyn_cast<StoreInst>(I);
511     if (!S0 || !S0->isSimple())
512       continue;
513 
514     ++NStores;
515     if (NStores * Size1 >= MagicCompileTimeControl)
516       break;
517     if (StoreInst *S1 = canSinkFromBlock(Pred1, S0, AA)) {
518       bool Res = sinkStore(T, S0, S1, MD);
519       MergedStores |= Res;
520       // Don't attempt to sink below stores that had to stick around
521       // But after removal of a store and some of its feeding
522       // instruction search again from the beginning since the iterator
523       // is likely stale at this point.
524       if (!Res)
525         break;
526       RBI = Pred0->rbegin();
527       RBE = Pred0->rend();
528       DEBUG(dbgs() << "Search again\n"; Instruction *I = &*RBI; I->dump());
529     }
530   }
531   return MergedStores;
532 }
533 
534 ///
535 /// \brief Run the transformation for each function
536 ///
537 bool MergedLoadStoreMotion::runOnFunction(Function &F) {
538   if (skipFunction(F))
539     return false;
540 
541   auto *MDWP = getAnalysisIfAvailable<MemoryDependenceWrapperPass>();
542   MD = MDWP ? &MDWP->getMemDep() : nullptr;
543   AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
544 
545   bool Changed = false;
546   DEBUG(dbgs() << "Instruction Merger\n");
547 
548   // Merge unconditional branches, allowing PRE to catch more
549   // optimization opportunities.
550   for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE;) {
551     BasicBlock *BB = &*FI++;
552 
553     // Hoist equivalent loads and sink stores
554     // outside diamonds when possible
555     if (isDiamondHead(BB)) {
556       Changed |= mergeLoads(BB, AA, MD);
557       Changed |= mergeStores(getDiamondTail(BB), AA, MD);
558     }
559   }
560   return Changed;
561 }
562