blob: c9fbec2896051b7fc777648770226dbbf6b564c3 [file] [log] [blame]
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +00001//===- 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
Gerolf Hoflehnerea96a3d2014-08-07 23:19:55 +000030// + +
31// + +
32// + +
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +000033// 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
Gerolf Hoflehnerea96a3d2014-08-07 23:19:55 +000039// + +
40// + +
41// + +
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +000042// 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
Gerolf Hoflehnerea96a3d2014-08-07 23:19:55 +000050// + +
51// + +
52// + +
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +000053// if.then: if.else:
54// <use %l> <use %l>
55// <...> <...>
56// br label %if.end br label %if.end
Gerolf Hoflehnerea96a3d2014-08-07 23:19:55 +000057// + +
58// + +
59// + +
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +000060// 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
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +000075#include "llvm/ADT/Statistic.h"
76#include "llvm/Analysis/AliasAnalysis.h"
77#include "llvm/Analysis/CFG.h"
Chandler Carruth7b560d42015-09-09 17:55:00 +000078#include "llvm/Analysis/GlobalsModRef.h"
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +000079#include "llvm/Analysis/Loads.h"
80#include "llvm/Analysis/MemoryBuiltins.h"
81#include "llvm/Analysis/MemoryDependenceAnalysis.h"
Eli Friedman9f8031c2016-06-12 02:11:20 +000082#include "llvm/Analysis/ValueTracking.h"
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +000083#include "llvm/IR/Metadata.h"
84#include "llvm/IR/PatternMatch.h"
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +000085#include "llvm/Support/Debug.h"
Benjamin Kramerb85d3752015-03-23 18:45:56 +000086#include "llvm/Support/raw_ostream.h"
Mehdi Aminib550cb12016-04-18 09:17:29 +000087#include "llvm/Transforms/Scalar.h"
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +000088#include "llvm/Transforms/Utils/BasicBlockUtils.h"
89#include "llvm/Transforms/Utils/SSAUpdater.h"
Hans Wennborg083ca9b2015-10-06 23:24:35 +000090
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +000091using namespace llvm;
92
93#define DEBUG_TYPE "mldst-motion"
94
95//===----------------------------------------------------------------------===//
96// MergedLoadStoreMotion Pass
97//===----------------------------------------------------------------------===//
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +000098
99namespace {
100class MergedLoadStoreMotion : public FunctionPass {
101 AliasAnalysis *AA;
Chandler Carruth61440d22016-03-10 00:55:30 +0000102 MemoryDependenceResults *MD;
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000103
104public:
105 static char ID; // Pass identification, replacement for typeid
Davide Italiano44faf7f2016-06-13 22:27:30 +0000106 MergedLoadStoreMotion() : FunctionPass(ID), MD(nullptr) {
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000107 initializeMergedLoadStoreMotionPass(*PassRegistry::getPassRegistry());
108 }
109
110 bool runOnFunction(Function &F) override;
111
112private:
113 // This transformation requires dominator postdominator info
114 void getAnalysisUsage(AnalysisUsage &AU) const override {
Jakub Staszakf12821a2015-10-18 19:34:10 +0000115 AU.setPreservesCFG();
Chandler Carruth7b560d42015-09-09 17:55:00 +0000116 AU.addRequired<AAResultsWrapperPass>();
117 AU.addPreserved<GlobalsAAWrapperPass>();
Chandler Carruth61440d22016-03-10 00:55:30 +0000118 AU.addPreserved<MemoryDependenceWrapperPass>();
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000119 }
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000120};
121
122char MergedLoadStoreMotion::ID = 0;
Eugene Zelenkoffec81c2015-11-04 22:32:32 +0000123} // anonymous namespace
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000124
Davide Italiano44faf7f2016-06-13 22:27:30 +0000125// 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.
129const int MagicCompileTimeControl = 250;
130
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000131///
132/// \brief createMergedLoadStoreMotionPass - The public interface to this file.
133///
134FunctionPass *llvm::createMergedLoadStoreMotionPass() {
135 return new MergedLoadStoreMotion();
136}
137
138INITIALIZE_PASS_BEGIN(MergedLoadStoreMotion, "mldst-motion",
139 "MergedLoadStoreMotion", false, false)
Chandler Carruth61440d22016-03-10 00:55:30 +0000140INITIALIZE_PASS_DEPENDENCY(MemoryDependenceWrapperPass)
Chandler Carruth7b560d42015-09-09 17:55:00 +0000141INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
142INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000143INITIALIZE_PASS_END(MergedLoadStoreMotion, "mldst-motion",
144 "MergedLoadStoreMotion", false, false)
145
146///
147/// \brief Remove instruction from parent and update memory dependence analysis.
148///
Davide Italiano44faf7f2016-06-13 22:27:30 +0000149static void removeInstruction(Instruction *Inst, MemoryDependenceResults *MD) {
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000150 // Notify the memory dependence analysis.
151 if (MD) {
152 MD->removeInstruction(Inst);
David Majnemer8cce3332016-05-26 05:43:12 +0000153 if (auto *LI = dyn_cast<LoadInst>(Inst))
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000154 MD->invalidateCachedPointerInfo(LI->getPointerOperand());
David Majnemer8cce3332016-05-26 05:43:12 +0000155 if (Inst->getType()->isPtrOrPtrVectorTy()) {
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000156 MD->invalidateCachedPointerInfo(Inst);
157 }
158 }
159 Inst->eraseFromParent();
160}
161
162///
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000163/// \brief True when BB is the head of a diamond (hammock)
164///
Davide Italiano44faf7f2016-06-13 22:27:30 +0000165static bool isDiamondHead(BasicBlock *BB) {
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000166 if (!BB)
167 return false;
David Majnemer8cce3332016-05-26 05:43:12 +0000168 auto *BI = dyn_cast<BranchInst>(BB->getTerminator());
169 if (!BI || !BI->isConditional())
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000170 return false;
171
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000172 BasicBlock *Succ0 = BI->getSuccessor(0);
173 BasicBlock *Succ1 = BI->getSuccessor(1);
174
David Majnemer8cce3332016-05-26 05:43:12 +0000175 if (!Succ0->getSinglePredecessor())
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000176 return false;
David Majnemer8cce3332016-05-26 05:43:12 +0000177 if (!Succ1->getSinglePredecessor())
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000178 return false;
179
David Majnemer8cce3332016-05-26 05:43:12 +0000180 BasicBlock *Succ0Succ = Succ0->getSingleSuccessor();
181 BasicBlock *Succ1Succ = Succ1->getSingleSuccessor();
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000182 // Ignore triangles.
David Majnemer8cce3332016-05-26 05:43:12 +0000183 if (!Succ0Succ || !Succ1Succ || Succ0Succ != Succ1Succ)
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000184 return false;
185 return true;
186}
187
188///
Davide Italiano44faf7f2016-06-13 22:27:30 +0000189/// \brief Return tail block of a diamond.
190///
191static 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///
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000197/// \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///
Davide Italiano44faf7f2016-06-13 22:27:30 +0000203static bool isLoadHoistBarrierInRange(const Instruction &Start,
204 const Instruction &End, LoadInst *LI,
205 bool SafeToLoadUnconditionally,
206 AliasAnalysis *AA) {
David Majnemer47451252016-05-26 07:11:09 +0000207 if (!SafeToLoadUnconditionally)
208 for (const Instruction &Inst :
209 make_range(Start.getIterator(), End.getIterator()))
Eli Friedman9f8031c2016-06-12 02:11:20 +0000210 if (!isGuaranteedToTransferExecutionToSuccessor(&Inst))
David Majnemer47451252016-05-26 07:11:09 +0000211 return true;
Chandler Carruthac80dc72015-06-17 07:18:54 +0000212 MemoryLocation Loc = MemoryLocation::get(LI);
Chandler Carruth194f59c2015-07-22 23:15:57 +0000213 return AA->canInstructionRangeModRef(Start, End, Loc, MRI_Mod);
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000214}
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///
Davide Italiano44faf7f2016-06-13 22:27:30 +0000223static LoadInst *canHoistFromBlock(BasicBlock *BB1, LoadInst *Load0,
224 AliasAnalysis *AA) {
David Majnemer47451252016-05-26 07:11:09 +0000225 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());
Elena Demikhovsky27152ae2014-11-02 08:03:05 +0000231 for (BasicBlock::iterator BBI = BB1->begin(), BBE = BB1->end(); BBI != BBE;
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000232 ++BBI) {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000233 Instruction *Inst = &*BBI;
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000234
235 // Only merge and hoist loads when their result in used only in BB
David Majnemer47451252016-05-26 07:11:09 +0000236 auto *Load1 = dyn_cast<LoadInst>(Inst);
237 if (!Load1 || Inst->isUsedOutsideOfBlock(BB1))
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000238 continue;
239
Chandler Carruthac80dc72015-06-17 07:18:54 +0000240 MemoryLocation Loc0 = MemoryLocation::get(Load0);
241 MemoryLocation Loc1 = MemoryLocation::get(Load1);
Elena Demikhovsky27152ae2014-11-02 08:03:05 +0000242 if (AA->isMustAlias(Loc0, Loc1) && Load0->isSameOperationAs(Load1) &&
David Majnemer47451252016-05-26 07:11:09 +0000243 !isLoadHoistBarrierInRange(BB1->front(), *Load1, Load1,
Davide Italiano44faf7f2016-06-13 22:27:30 +0000244 SafeToLoadUnconditionally, AA) &&
David Majnemer47451252016-05-26 07:11:09 +0000245 !isLoadHoistBarrierInRange(BB0->front(), *Load0, Load0,
Davide Italiano44faf7f2016-06-13 22:27:30 +0000246 SafeToLoadUnconditionally, AA)) {
Elena Demikhovsky27152ae2014-11-02 08:03:05 +0000247 return Load1;
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000248 }
249 }
Elena Demikhovsky27152ae2014-11-02 08:03:05 +0000250 return nullptr;
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000251}
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///
Davide Italiano44faf7f2016-06-13 22:27:30 +0000259static void hoistInstruction(BasicBlock *BB, Instruction *HoistCand,
260 Instruction *ElseInst,
261 MemoryDependenceResults *MD) {
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000262 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);
Adrian Prantlcbdfdb72015-08-20 22:00:30 +0000270 HoistCand->dropUnknownNonDebugMetadata();
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000271
272 // Prepend point for instruction insert
273 Instruction *HoistPt = BB->getTerminator();
274
275 // Merged instruction
276 Instruction *HoistedInst = HoistCand->clone();
277
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000278 // Hoist instruction.
279 HoistedInst->insertBefore(HoistPt);
280
281 HoistCand->replaceAllUsesWith(HoistedInst);
Davide Italiano44faf7f2016-06-13 22:27:30 +0000282 removeInstruction(HoistCand, MD);
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000283 // Replace the else block instruction.
284 ElseInst->replaceAllUsesWith(HoistedInst);
Davide Italiano44faf7f2016-06-13 22:27:30 +0000285 removeInstruction(ElseInst, MD);
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000286}
287
288///
289/// \brief Return true if no operand of \p I is defined in I's parent block
290///
Davide Italiano44faf7f2016-06-13 22:27:30 +0000291static bool isSafeToHoist(Instruction *I) {
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000292 BasicBlock *Parent = I->getParent();
David Majnemer8cce3332016-05-26 05:43:12 +0000293 for (Use &U : I->operands())
294 if (auto *Instr = dyn_cast<Instruction>(&U))
295 if (Instr->getParent() == Parent)
296 return false;
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000297 return true;
298}
299
300///
301/// \brief Merge two equivalent loads and GEPs and hoist into diamond head
302///
Davide Italiano44faf7f2016-06-13 22:27:30 +0000303static bool hoistLoad(BasicBlock *BB, LoadInst *L0, LoadInst *L1,
304 MemoryDependenceResults *MD) {
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000305 // Only one definition?
David Majnemer8cce3332016-05-26 05:43:12 +0000306 auto *A0 = dyn_cast<Instruction>(L0->getPointerOperand());
307 auto *A1 = dyn_cast<Instruction>(L1->getPointerOperand());
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000308 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");
Davide Italiano44faf7f2016-06-13 22:27:30 +0000315 hoistInstruction(BB, A0, A1, MD);
316 hoistInstruction(BB, L0, L1, MD);
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000317 return true;
David Majnemer8cce3332016-05-26 05:43:12 +0000318 }
319 return false;
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000320}
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///
Davide Italiano44faf7f2016-06-13 22:27:30 +0000328static bool mergeLoads(BasicBlock *BB, AliasAnalysis *AA,
329 MemoryDependenceResults *MD) {
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000330 bool MergedLoads = false;
331 assert(isDiamondHead(BB));
David Majnemer8cce3332016-05-26 05:43:12 +0000332 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000333 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;) {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000340 Instruction *I = &*BBI;
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000341 ++BBI;
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000342
David Majnemer8cce3332016-05-26 05:43:12 +0000343 // Don't move non-simple (atomic, volatile) loads.
344 auto *L0 = dyn_cast<LoadInst>(I);
Elena Demikhovsky27152ae2014-11-02 08:03:05 +0000345 if (!L0 || !L0->isSimple() || L0->isUsedOutsideOfBlock(Succ0))
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000346 continue;
347
348 ++NLoads;
349 if (NLoads * Size1 >= MagicCompileTimeControl)
350 break;
Davide Italiano44faf7f2016-06-13 22:27:30 +0000351 if (LoadInst *L1 = canHoistFromBlock(Succ1, L0, AA)) {
352 bool Res = hoistLoad(BB, L0, L1, MD);
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000353 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///
Elena Demikhovskya5599bf2014-12-15 14:09:53 +0000363/// \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///
Davide Italiano44faf7f2016-06-13 22:27:30 +0000370static bool isStoreSinkBarrierInRange(const Instruction &Start,
371 const Instruction &End,
372 MemoryLocation Loc, AliasAnalysis *AA) {
David Majnemer47451252016-05-26 07:11:09 +0000373 for (const Instruction &Inst :
374 make_range(Start.getIterator(), End.getIterator()))
375 if (Inst.mayThrow())
376 return true;
Chandler Carruth194f59c2015-07-22 23:15:57 +0000377 return AA->canInstructionRangeModRef(Start, End, Loc, MRI_ModRef);
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000378}
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///
Davide Italiano44faf7f2016-06-13 22:27:30 +0000385static StoreInst *canSinkFromBlock(BasicBlock *BB1, StoreInst *Store0,
386 AliasAnalysis *AA) {
Elena Demikhovskya5599bf2014-12-15 14:09:53 +0000387 DEBUG(dbgs() << "can Sink? : "; Store0->dump(); dbgs() << "\n");
Elena Demikhovskyef035bb2015-02-17 13:10:05 +0000388 BasicBlock *BB0 = Store0->getParent();
Elena Demikhovskya5599bf2014-12-15 14:09:53 +0000389 for (BasicBlock::reverse_iterator RBI = BB1->rbegin(), RBE = BB1->rend();
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000390 RBI != RBE; ++RBI) {
391 Instruction *Inst = &*RBI;
392
David Majnemer47451252016-05-26 07:11:09 +0000393 auto *Store1 = dyn_cast<StoreInst>(Inst);
394 if (!Store1)
395 continue;
Elena Demikhovskya5599bf2014-12-15 14:09:53 +0000396
Chandler Carruthac80dc72015-06-17 07:18:54 +0000397 MemoryLocation Loc0 = MemoryLocation::get(Store0);
398 MemoryLocation Loc1 = MemoryLocation::get(Store1);
Elena Demikhovskya5599bf2014-12-15 14:09:53 +0000399 if (AA->isMustAlias(Loc0, Loc1) && Store0->isSameOperationAs(Store1) &&
Davide Italiano44faf7f2016-06-13 22:27:30 +0000400 !isStoreSinkBarrierInRange(*Store1->getNextNode(), BB1->back(), Loc1,
401 AA) &&
402 !isStoreSinkBarrierInRange(*Store0->getNextNode(), BB0->back(), Loc0,
403 AA)) {
Elena Demikhovskya5599bf2014-12-15 14:09:53 +0000404 return Store1;
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000405 }
406 }
Elena Demikhovskya5599bf2014-12-15 14:09:53 +0000407 return nullptr;
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000408}
409
410///
411/// \brief Create a PHI node in BB for the operands of S0 and S1
412///
Davide Italiano44faf7f2016-06-13 22:27:30 +0000413static PHINode *getPHIOperand(BasicBlock *BB, StoreInst *S0, StoreInst *S1,
414 MemoryDependenceResults *MD) {
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000415 // Create a phi if the values mismatch.
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000416 Value *Opd1 = S0->getValueOperand();
417 Value *Opd2 = S1->getValueOperand();
David Majnemer8cce3332016-05-26 05:43:12 +0000418 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);
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000427 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///
Davide Italiano44faf7f2016-06-13 22:27:30 +0000435static bool sinkStore(BasicBlock *BB, StoreInst *S0, StoreInst *S1,
436 MemoryDependenceResults *MD) {
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000437 // Only one definition?
David Majnemer8cce3332016-05-26 05:43:12 +0000438 auto *A0 = dyn_cast<Instruction>(S0->getPointerOperand());
439 auto *A1 = dyn_cast<Instruction>(S1->getPointerOperand());
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000440 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);
Adrian Prantlcbdfdb72015-08-20 22:00:30 +0000450 S0->dropUnknownNonDebugMetadata();
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000451
452 // Create the new store to be inserted at the join point.
David Majnemer8cce3332016-05-26 05:43:12 +0000453 StoreInst *SNew = cast<StoreInst>(S0->clone());
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000454 Instruction *ANew = A0->clone();
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000455 SNew->insertBefore(&*InsertPt);
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000456 ANew->insertBefore(SNew);
457
458 assert(S0->getParent() == A0->getParent());
459 assert(S1->getParent() == A1->getParent());
460
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000461 // New PHI operand? Use it.
Davide Italiano44faf7f2016-06-13 22:27:30 +0000462 if (PHINode *NewPN = getPHIOperand(BB, S0, S1, MD))
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000463 SNew->setOperand(0, NewPN);
Davide Italiano44faf7f2016-06-13 22:27:30 +0000464 removeInstruction(S0, MD);
465 removeInstruction(S1, MD);
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000466 A0->replaceAllUsesWith(ANew);
Davide Italiano44faf7f2016-06-13 22:27:30 +0000467 removeInstruction(A0, MD);
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000468 A1->replaceAllUsesWith(ANew);
Davide Italiano44faf7f2016-06-13 22:27:30 +0000469 removeInstruction(A1, MD);
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000470 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///
Davide Italiano44faf7f2016-06-13 22:27:30 +0000481static bool mergeStores(BasicBlock *T, AliasAnalysis *AA,
482 MemoryDependenceResults *MD) {
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000483
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;
Elena Demikhovskya5599bf2014-12-15 14:09:53 +0000508
David Majnemer8cce3332016-05-26 05:43:12 +0000509 // Don't sink non-simple (atomic, volatile) stores.
510 auto *S0 = dyn_cast<StoreInst>(I);
511 if (!S0 || !S0->isSimple())
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000512 continue;
513
514 ++NStores;
515 if (NStores * Size1 >= MagicCompileTimeControl)
516 break;
Davide Italiano44faf7f2016-06-13 22:27:30 +0000517 if (StoreInst *S1 = canSinkFromBlock(Pred1, S0, AA)) {
518 bool Res = sinkStore(T, S0, S1, MD);
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000519 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;
David Majnemer8cce3332016-05-26 05:43:12 +0000526 RBI = Pred0->rbegin();
527 RBE = Pred0->rend();
528 DEBUG(dbgs() << "Search again\n"; Instruction *I = &*RBI; I->dump());
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000529 }
530 }
531 return MergedStores;
532}
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000533
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000534///
535/// \brief Run the transformation for each function
536///
537bool MergedLoadStoreMotion::runOnFunction(Function &F) {
Andrew Kayloraa641a52016-04-22 22:06:11 +0000538 if (skipFunction(F))
539 return false;
540
Chandler Carruth61440d22016-03-10 00:55:30 +0000541 auto *MDWP = getAnalysisIfAvailable<MemoryDependenceWrapperPass>();
542 MD = MDWP ? &MDWP->getMemDep() : nullptr;
Chandler Carruth7b560d42015-09-09 17:55:00 +0000543 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000544
545 bool Changed = false;
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000546 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;) {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000551 BasicBlock *BB = &*FI++;
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000552
553 // Hoist equivalent loads and sink stores
554 // outside diamonds when possible
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000555 if (isDiamondHead(BB)) {
Davide Italiano44faf7f2016-06-13 22:27:30 +0000556 Changed |= mergeLoads(BB, AA, MD);
557 Changed |= mergeStores(getDiamondTail(BB), AA, MD);
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000558 }
559 }
560 return Changed;
561}