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
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/ValueTracking.h"
84 #include "llvm/IR/Metadata.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
90 using namespace llvm;
91
92 #define DEBUG_TYPE "mldst-motion"
93
94 namespace {
95 //===----------------------------------------------------------------------===//
96 // MergedLoadStoreMotion Pass
97 //===----------------------------------------------------------------------===//
98 class MergedLoadStoreMotion {
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 ///
getDiamondTail(BasicBlock * BB)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 ///
isDiamondHead(BasicBlock * BB)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 ///
isStoreSinkBarrierInRange(const Instruction & Start,const Instruction & End,MemoryLocation Loc)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 ///
canSinkFromBlock(BasicBlock * BB1,StoreInst * Store0)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 ///
getPHIOperand(BasicBlock * BB,StoreInst * S0,StoreInst * S1)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 ///
sinkStore(BasicBlock * BB,StoreInst * S0,StoreInst * S1)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);
240 S0->dropUnknownNonDebugMetadata();
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 ///
mergeStores(BasicBlock * T)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
run(Function & F,AliasAnalysis & AA)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
MergedLoadStoreMotionLegacyPass()348 MergedLoadStoreMotionLegacyPass() : FunctionPass(ID) {
349 initializeMergedLoadStoreMotionLegacyPassPass(
350 *PassRegistry::getPassRegistry());
351 }
352
353 ///
354 /// Run the transformation for each function
355 ///
runOnFunction(Function & F)356 bool runOnFunction(Function &F) override {
357 if (skipFunction(F))
358 return false;
359 MergedLoadStoreMotion Impl;
360 return Impl.run(F, getAnalysis<AAResultsWrapperPass>().getAAResults());
361 }
362
363 private:
getAnalysisUsage(AnalysisUsage & AU) const364 void getAnalysisUsage(AnalysisUsage &AU) const override {
365 AU.setPreservesCFG();
366 AU.addRequired<AAResultsWrapperPass>();
367 AU.addPreserved<GlobalsAAWrapperPass>();
368 }
369 };
370
371 char MergedLoadStoreMotionLegacyPass::ID = 0;
372 } // anonymous namespace
373
374 ///
375 /// createMergedLoadStoreMotionPass - The public interface to this file.
376 ///
createMergedLoadStoreMotionPass()377 FunctionPass *llvm::createMergedLoadStoreMotionPass() {
378 return new MergedLoadStoreMotionLegacyPass();
379 }
380
381 INITIALIZE_PASS_BEGIN(MergedLoadStoreMotionLegacyPass, "mldst-motion",
382 "MergedLoadStoreMotion", false, false)
INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)383 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
384 INITIALIZE_PASS_END(MergedLoadStoreMotionLegacyPass, "mldst-motion",
385 "MergedLoadStoreMotion", false, false)
386
387 PreservedAnalyses
388 MergedLoadStoreMotionPass::run(Function &F, FunctionAnalysisManager &AM) {
389 MergedLoadStoreMotion Impl;
390 auto &AA = AM.getResult<AAManager>(F);
391 if (!Impl.run(F, AA))
392 return PreservedAnalyses::all();
393
394 PreservedAnalyses PA;
395 PA.preserveSet<CFGAnalyses>();
396 PA.preserve<GlobalsAA>();
397 return PA;
398 }
399