LLVM  8.0.1
MergedLoadStoreMotion.cpp
Go to the documentation of this file.
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 //! 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 
78 #include "llvm/ADT/Statistic.h"
80 #include "llvm/Analysis/CFG.h"
82 #include "llvm/Analysis/Loads.h"
84 #include "llvm/IR/Metadata.h"
85 #include "llvm/Support/Debug.h"
87 #include "llvm/Transforms/Scalar.h"
89 
90 using namespace llvm;
91 
92 #define DEBUG_TYPE "mldst-motion"
93 
94 namespace {
95 //===----------------------------------------------------------------------===//
96 // MergedLoadStoreMotion Pass
97 //===----------------------------------------------------------------------===//
99  AliasAnalysis *AA = nullptr;
100 
101  // The mergeLoad/Store algorithms could have Size0 * Size1 complexity,
102  // where Size0 and Size1 are the #instructions on the two sides of
103  // the diamond. The constant chosen here is arbitrary. Compiler Time
104  // Control is enforced by the check Size0 * Size1 < MagicCompileTimeControl.
105  const int MagicCompileTimeControl = 250;
106 
107 public:
108  bool run(Function &F, AliasAnalysis &AA);
109 
110 private:
111  BasicBlock *getDiamondTail(BasicBlock *BB);
112  bool isDiamondHead(BasicBlock *BB);
113  // Routines for sinking stores
114  StoreInst *canSinkFromBlock(BasicBlock *BB, StoreInst *SI);
115  PHINode *getPHIOperand(BasicBlock *BB, StoreInst *S0, StoreInst *S1);
116  bool isStoreSinkBarrierInRange(const Instruction &Start,
117  const Instruction &End, MemoryLocation Loc);
118  bool sinkStore(BasicBlock *BB, StoreInst *SinkCand, StoreInst *ElseInst);
119  bool mergeStores(BasicBlock *BB);
120 };
121 } // end anonymous namespace
122 
123 ///
124 /// Return tail block of a diamond.
125 ///
126 BasicBlock *MergedLoadStoreMotion::getDiamondTail(BasicBlock *BB) {
127  assert(isDiamondHead(BB) && "Basic block is not head of a diamond");
128  return BB->getTerminator()->getSuccessor(0)->getSingleSuccessor();
129 }
130 
131 ///
132 /// True when BB is the head of a diamond (hammock)
133 ///
134 bool MergedLoadStoreMotion::isDiamondHead(BasicBlock *BB) {
135  if (!BB)
136  return false;
137  auto *BI = dyn_cast<BranchInst>(BB->getTerminator());
138  if (!BI || !BI->isConditional())
139  return false;
140 
141  BasicBlock *Succ0 = BI->getSuccessor(0);
142  BasicBlock *Succ1 = BI->getSuccessor(1);
143 
144  if (!Succ0->getSinglePredecessor())
145  return false;
146  if (!Succ1->getSinglePredecessor())
147  return false;
148 
149  BasicBlock *Succ0Succ = Succ0->getSingleSuccessor();
150  BasicBlock *Succ1Succ = Succ1->getSingleSuccessor();
151  // Ignore triangles.
152  if (!Succ0Succ || !Succ1Succ || Succ0Succ != Succ1Succ)
153  return false;
154  return true;
155 }
156 
157 
158 ///
159 /// True when instruction is a sink barrier for a store
160 /// located in Loc
161 ///
162 /// Whenever an instruction could possibly read or modify the
163 /// value being stored or protect against the store from
164 /// happening it is considered a sink barrier.
165 ///
166 bool MergedLoadStoreMotion::isStoreSinkBarrierInRange(const Instruction &Start,
167  const Instruction &End,
168  MemoryLocation Loc) {
169  for (const Instruction &Inst :
170  make_range(Start.getIterator(), End.getIterator()))
171  if (Inst.mayThrow())
172  return true;
173  return AA->canInstructionRangeModRef(Start, End, Loc, ModRefInfo::ModRef);
174 }
175 
176 ///
177 /// Check if \p BB contains a store to the same address as \p SI
178 ///
179 /// \return The store in \p when it is safe to sink. Otherwise return Null.
180 ///
181 StoreInst *MergedLoadStoreMotion::canSinkFromBlock(BasicBlock *BB1,
182  StoreInst *Store0) {
183  LLVM_DEBUG(dbgs() << "can Sink? : "; Store0->dump(); dbgs() << "\n");
184  BasicBlock *BB0 = Store0->getParent();
185  for (Instruction &Inst : reverse(*BB1)) {
186  auto *Store1 = dyn_cast<StoreInst>(&Inst);
187  if (!Store1)
188  continue;
189 
190  MemoryLocation Loc0 = MemoryLocation::get(Store0);
191  MemoryLocation Loc1 = MemoryLocation::get(Store1);
192  if (AA->isMustAlias(Loc0, Loc1) && Store0->isSameOperationAs(Store1) &&
193  !isStoreSinkBarrierInRange(*Store1->getNextNode(), BB1->back(), Loc1) &&
194  !isStoreSinkBarrierInRange(*Store0->getNextNode(), BB0->back(), Loc0)) {
195  return Store1;
196  }
197  }
198  return nullptr;
199 }
200 
201 ///
202 /// Create a PHI node in BB for the operands of S0 and S1
203 ///
204 PHINode *MergedLoadStoreMotion::getPHIOperand(BasicBlock *BB, StoreInst *S0,
205  StoreInst *S1) {
206  // Create a phi if the values mismatch.
207  Value *Opd1 = S0->getValueOperand();
208  Value *Opd2 = S1->getValueOperand();
209  if (Opd1 == Opd2)
210  return nullptr;
211 
212  auto *NewPN = PHINode::Create(Opd1->getType(), 2, Opd2->getName() + ".sink",
213  &BB->front());
214  NewPN->applyMergedLocation(S0->getDebugLoc(), S1->getDebugLoc());
215  NewPN->addIncoming(Opd1, S0->getParent());
216  NewPN->addIncoming(Opd2, S1->getParent());
217  return NewPN;
218 }
219 
220 ///
221 /// Merge two stores to same address and sink into \p BB
222 ///
223 /// Also sinks GEP instruction computing the store address
224 ///
225 bool MergedLoadStoreMotion::sinkStore(BasicBlock *BB, StoreInst *S0,
226  StoreInst *S1) {
227  // Only one definition?
228  auto *A0 = dyn_cast<Instruction>(S0->getPointerOperand());
229  auto *A1 = dyn_cast<Instruction>(S1->getPointerOperand());
230  if (A0 && A1 && A0->isIdenticalTo(A1) && A0->hasOneUse() &&
231  (A0->getParent() == S0->getParent()) && A1->hasOneUse() &&
232  (A1->getParent() == S1->getParent()) && isa<GetElementPtrInst>(A0)) {
233  LLVM_DEBUG(dbgs() << "Sink Instruction into BB \n"; BB->dump();
234  dbgs() << "Instruction Left\n"; S0->dump(); dbgs() << "\n";
235  dbgs() << "Instruction Right\n"; S1->dump(); dbgs() << "\n");
236  // Hoist the instruction.
237  BasicBlock::iterator InsertPt = BB->getFirstInsertionPt();
238  // Intersect optional metadata.
239  S0->andIRFlags(S1);
241 
242  // Create the new store to be inserted at the join point.
243  StoreInst *SNew = cast<StoreInst>(S0->clone());
244  Instruction *ANew = A0->clone();
245  SNew->insertBefore(&*InsertPt);
246  ANew->insertBefore(SNew);
247 
248  assert(S0->getParent() == A0->getParent());
249  assert(S1->getParent() == A1->getParent());
250 
251  // New PHI operand? Use it.
252  if (PHINode *NewPN = getPHIOperand(BB, S0, S1))
253  SNew->setOperand(0, NewPN);
254  S0->eraseFromParent();
255  S1->eraseFromParent();
256  A0->replaceAllUsesWith(ANew);
257  A0->eraseFromParent();
258  A1->replaceAllUsesWith(ANew);
259  A1->eraseFromParent();
260  return true;
261  }
262  return false;
263 }
264 
265 ///
266 /// True when two stores are equivalent and can sink into the footer
267 ///
268 /// Starting from a diamond tail block, iterate over the instructions in one
269 /// predecessor block and try to match a store in the second predecessor.
270 ///
271 bool MergedLoadStoreMotion::mergeStores(BasicBlock *T) {
272 
273  bool MergedStores = false;
274  assert(T && "Footer of a diamond cannot be empty");
275 
276  pred_iterator PI = pred_begin(T), E = pred_end(T);
277  assert(PI != E);
278  BasicBlock *Pred0 = *PI;
279  ++PI;
280  BasicBlock *Pred1 = *PI;
281  ++PI;
282  // tail block of a diamond/hammock?
283  if (Pred0 == Pred1)
284  return false; // No.
285  if (PI != E)
286  return false; // No. More than 2 predecessors.
287 
288  // #Instructions in Succ1 for Compile Time Control
289  auto InstsNoDbg = Pred1->instructionsWithoutDebug();
290  int Size1 = std::distance(InstsNoDbg.begin(), InstsNoDbg.end());
291  int NStores = 0;
292 
293  for (BasicBlock::reverse_iterator RBI = Pred0->rbegin(), RBE = Pred0->rend();
294  RBI != RBE;) {
295 
296  Instruction *I = &*RBI;
297  ++RBI;
298 
299  // Don't sink non-simple (atomic, volatile) stores.
300  auto *S0 = dyn_cast<StoreInst>(I);
301  if (!S0 || !S0->isSimple())
302  continue;
303 
304  ++NStores;
305  if (NStores * Size1 >= MagicCompileTimeControl)
306  break;
307  if (StoreInst *S1 = canSinkFromBlock(Pred1, S0)) {
308  bool Res = sinkStore(T, S0, S1);
309  MergedStores |= Res;
310  // Don't attempt to sink below stores that had to stick around
311  // But after removal of a store and some of its feeding
312  // instruction search again from the beginning since the iterator
313  // is likely stale at this point.
314  if (!Res)
315  break;
316  RBI = Pred0->rbegin();
317  RBE = Pred0->rend();
318  LLVM_DEBUG(dbgs() << "Search again\n"; Instruction *I = &*RBI; I->dump());
319  }
320  }
321  return MergedStores;
322 }
323 
324 bool MergedLoadStoreMotion::run(Function &F, AliasAnalysis &AA) {
325  this->AA = &AA;
326 
327  bool Changed = false;
328  LLVM_DEBUG(dbgs() << "Instruction Merger\n");
329 
330  // Merge unconditional branches, allowing PRE to catch more
331  // optimization opportunities.
332  for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE;) {
333  BasicBlock *BB = &*FI++;
334 
335  // Hoist equivalent loads and sink stores
336  // outside diamonds when possible
337  if (isDiamondHead(BB)) {
338  Changed |= mergeStores(getDiamondTail(BB));
339  }
340  }
341  return Changed;
342 }
343 
344 namespace {
345 class MergedLoadStoreMotionLegacyPass : public FunctionPass {
346 public:
347  static char ID; // Pass identification, replacement for typeid
348  MergedLoadStoreMotionLegacyPass() : FunctionPass(ID) {
351  }
352 
353  ///
354  /// Run the transformation for each function
355  ///
356  bool runOnFunction(Function &F) override {
357  if (skipFunction(F))
358  return false;
360  return Impl.run(F, getAnalysis<AAResultsWrapperPass>().getAAResults());
361  }
362 
363 private:
364  void getAnalysisUsage(AnalysisUsage &AU) const override {
365  AU.setPreservesCFG();
368  }
369 };
370 
372 } // anonymous namespace
373 
374 ///
375 /// createMergedLoadStoreMotionPass - The public interface to this file.
376 ///
378  return new MergedLoadStoreMotionLegacyPass();
379 }
380 
381 INITIALIZE_PASS_BEGIN(MergedLoadStoreMotionLegacyPass, "mldst-motion",
382  "MergedLoadStoreMotion", false, false)
384 INITIALIZE_PASS_END(MergedLoadStoreMotionLegacyPass, "mldst-motion",
386 
390  auto &AA = AM.getResult<AAManager>(F);
391  if (!Impl.run(F, AA))
392  return PreservedAnalyses::all();
393 
395  PA.preserveSet<CFGAnalyses>();
396  PA.preserve<GlobalsAA>();
397  return PA;
398 }
Legacy wrapper pass to provide the GlobalsAAResult object.
The access may reference and may modify the value stored in memory.
Value * getValueOperand()
Definition: Instructions.h:410
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks &#39;this&#39; from the containing basic block and deletes it.
Definition: Instruction.cpp:68
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
bool isSameOperationAs(const Instruction *I, unsigned flags=0) const
This function determines if the specified instruction executes the same operation as the current one...
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
Definition: ilist_node.h:289
This class represents lattice values for constants.
Definition: AllocatorList.h:24
This is the interface for a simple mod/ref and alias analysis over globals.
void dropUnknownNonDebugMetadata(ArrayRef< unsigned > KnownIDs)
Drop all unknown metadata except for debug locations.
Definition: Metadata.cpp:1199
BasicBlock * getSuccessor(unsigned Idx) const
Return the specified successor. This instruction must be a terminator.
iterator end()
Definition: Function.h:658
INITIALIZE_PASS_BEGIN(MergedLoadStoreMotionLegacyPass, "mldst-motion", "MergedLoadStoreMotion", false, false) INITIALIZE_PASS_END(MergedLoadStoreMotionLegacyPass
This file contains the declarations for metadata subclasses.
F(f)
reverse_iterator rend()
Definition: BasicBlock.h:276
reverse_iterator rbegin()
Definition: BasicBlock.h:274
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
Definition: BasicBlock.cpp:138
void dump() const
Support for debugging, callable in GDB: V->dump()
Definition: AsmWriter.cpp:4298
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition: PassSupport.h:51
mldst motion
mldst MergedLoadStoreMotion
auto reverse(ContainerTy &&C, typename std::enable_if< has_rbegin< ContainerTy >::value >::type *=nullptr) -> decltype(make_range(C.rbegin(), C.rend()))
Definition: STLExtras.h:267
Instruction * clone() const
Create a copy of &#39;this&#39; instruction that is identical in all ways except the following: ...
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:245
void andIRFlags(const Value *V)
Logical &#39;and&#39; of any supported wrapping, exact, and fast-math flags of V and this instruction...
const BasicBlock * getSingleSuccessor() const
Return the successor of this block if it has a single successor.
Definition: BasicBlock.cpp:269
An instruction for storing to memory.
Definition: Instructions.h:321
iterator begin()
Definition: Function.h:656
static bool runOnFunction(Function &F, bool PostInlining)
static MemoryLocation get(const LoadInst *LI)
Return a location with information about the memory reference by the given instruction.
A set of analyses that are preserved following a run of a transformation pass.
Definition: PassManager.h:154
const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
Definition: BasicBlock.cpp:217
const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
Definition: BasicBlock.cpp:234
void insertBefore(Instruction *InsertPos)
Insert an unlinked instruction into a basic block immediately before the specified instruction...
Definition: Instruction.cpp:74
LLVM Basic Block Representation.
Definition: BasicBlock.h:58
Conditional or Unconditional Branch instruction.
iterator_range< filter_iterator< BasicBlock::const_iterator, std::function< bool(const Instruction &)> > > instructionsWithoutDebug() const
Return a const iterator range over the instructions in the block, skipping any debug instructions...
Definition: BasicBlock.cpp:95
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
const Instruction & front() const
Definition: BasicBlock.h:281
A manager for alias analyses.
Interval::pred_iterator pred_begin(Interval *I)
pred_begin/pred_end - define methods so that Intervals may be used just like BasicBlocks can with the...
Definition: Interval.h:113
Represent the analysis usage information of a pass.
const Instruction & back() const
Definition: BasicBlock.h:283
Analysis pass providing a never-invalidated alias analysis result.
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:285
Interval::pred_iterator pred_end(Interval *I)
Definition: Interval.h:116
self_iterator getIterator()
Definition: ilist_node.h:82
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: PassManager.h:160
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
Representation for a specific memory location.
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
Iterator for intrusive lists based on ilist_node.
void applyMergedLocation(const DILocation *LocA, const DILocation *LocB)
Merge 2 debug locations and apply it to the Instruction.
Definition: DebugInfo.cpp:689
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition: Pass.cpp:286
void setOperand(unsigned i, Value *Val)
Definition: User.h:175
FunctionPass * createMergedLoadStoreMotionPass()
createMergedLoadStoreMotionPass - The public interface to this file.
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:133
Represents analyses that only rely on functions&#39; control flow.
Definition: PassManager.h:115
This pass performs merges of loads and stores on both sides of a.
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
Definition: Instruction.h:311
void preserveSet()
Mark an analysis set as preserved.
Definition: PassManager.h:190
StringRef getName() const
Return a constant reference to the value&#39;s name.
Definition: Value.cpp:214
const Function * getParent() const
Return the enclosing method, or null if none.
Definition: BasicBlock.h:107
#define I(x, y, z)
Definition: MD5.cpp:58
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Definition: Casting.h:323
void preserve()
Mark an analysis as preserved.
Definition: PassManager.h:175
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
LLVM Value Representation.
Definition: Value.h:73
A container for analyses that lazily runs them and caches their results.
A wrapper pass to provide the legacy pass manager access to a suitably prepared AAResults object...
bool isSimple() const
Definition: Instructions.h:402
#define LLVM_DEBUG(X)
Definition: Debug.h:123
void initializeMergedLoadStoreMotionLegacyPassPass(PassRegistry &)
Value * getPointerOperand()
Definition: Instructions.h:413
const BasicBlock * getParent() const
Definition: Instruction.h:67