blob: 05ccf8bb00db10d7b74b2426e7ccfa31c51b4b35 [file] [log] [blame]
Sebastian Pop41774802016-07-15 13:45:20 +00001//===- GVNHoist.cpp - Hoist scalar and load expressions -------------------===//
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// This pass hoists expressions from branches to a common dominator. It uses
11// GVN (global value numbering) to discover expressions computing the same
Aditya Kumarf24939b2016-08-13 11:56:50 +000012// values. The primary goals of code-hoisting are:
13// 1. To reduce the code size.
14// 2. In some cases reduce critical path (by exposing more ILP).
15//
Sebastian Pop41774802016-07-15 13:45:20 +000016// Hoisting may affect the performance in some cases. To mitigate that, hoisting
17// is disabled in the following cases.
18// 1. Scalars across calls.
19// 2. geps when corresponding load/store cannot be hoisted.
20//===----------------------------------------------------------------------===//
21
Sebastian Pop5ba9f242016-10-13 01:39:10 +000022#include "llvm/Transforms/Scalar/GVN.h"
Sebastian Pop41774802016-07-15 13:45:20 +000023#include "llvm/ADT/DenseMap.h"
24#include "llvm/ADT/SmallPtrSet.h"
25#include "llvm/ADT/Statistic.h"
26#include "llvm/Analysis/ValueTracking.h"
27#include "llvm/Transforms/Scalar.h"
David Majnemer68623a02016-07-25 02:21:25 +000028#include "llvm/Transforms/Utils/Local.h"
Sebastian Pop41774802016-07-15 13:45:20 +000029#include "llvm/Transforms/Utils/MemorySSA.h"
Daniel Berlin17e8d0e2017-02-22 22:19:55 +000030#include "llvm/Transforms/Utils/MemorySSAUpdater.h"
Sebastian Pop41774802016-07-15 13:45:20 +000031
32using namespace llvm;
33
34#define DEBUG_TYPE "gvn-hoist"
35
36STATISTIC(NumHoisted, "Number of instructions hoisted");
37STATISTIC(NumRemoved, "Number of instructions removed");
38STATISTIC(NumLoadsHoisted, "Number of loads hoisted");
39STATISTIC(NumLoadsRemoved, "Number of loads removed");
40STATISTIC(NumStoresHoisted, "Number of stores hoisted");
41STATISTIC(NumStoresRemoved, "Number of stores removed");
42STATISTIC(NumCallsHoisted, "Number of calls hoisted");
43STATISTIC(NumCallsRemoved, "Number of calls removed");
44
45static cl::opt<int>
46 MaxHoistedThreshold("gvn-max-hoisted", cl::Hidden, cl::init(-1),
47 cl::desc("Max number of instructions to hoist "
48 "(default unlimited = -1)"));
49static cl::opt<int> MaxNumberOfBBSInPath(
50 "gvn-hoist-max-bbs", cl::Hidden, cl::init(4),
51 cl::desc("Max number of basic blocks on the path between "
52 "hoisting locations (default = 4, unlimited = -1)"));
53
Sebastian Pop38422b12016-07-26 00:15:08 +000054static cl::opt<int> MaxDepthInBB(
55 "gvn-hoist-max-depth", cl::Hidden, cl::init(100),
56 cl::desc("Hoist instructions from the beginning of the BB up to the "
57 "maximum specified depth (default = 100, unlimited = -1)"));
58
Sebastian Pop5ba9f242016-10-13 01:39:10 +000059static cl::opt<int>
60 MaxChainLength("gvn-hoist-max-chain-length", cl::Hidden, cl::init(10),
61 cl::desc("Maximum length of dependent chains to hoist "
62 "(default = 10, unlimited = -1)"));
Sebastian Pop2aadad72016-08-03 20:54:38 +000063
Daniel Berlindcb004f2017-03-02 23:06:46 +000064namespace llvm {
Sebastian Pop41774802016-07-15 13:45:20 +000065
66// Provides a sorting function based on the execution order of two instructions.
67struct SortByDFSIn {
68private:
Sebastian Pop91d4a302016-07-26 00:15:10 +000069 DenseMap<const Value *, unsigned> &DFSNumber;
Sebastian Pop41774802016-07-15 13:45:20 +000070
71public:
Sebastian Pop91d4a302016-07-26 00:15:10 +000072 SortByDFSIn(DenseMap<const Value *, unsigned> &D) : DFSNumber(D) {}
Sebastian Pop41774802016-07-15 13:45:20 +000073
74 // Returns true when A executes before B.
75 bool operator()(const Instruction *A, const Instruction *B) const {
76 // FIXME: libc++ has a std::sort() algorithm that will call the compare
77 // function on the same element. Once PR20837 is fixed and some more years
78 // pass by and all the buildbots have moved to a corrected std::sort(),
79 // enable the following assert:
80 //
81 // assert(A != B);
82
Sebastian Pop4ba7c882016-08-03 20:54:36 +000083 const BasicBlock *BA = A->getParent();
84 const BasicBlock *BB = B->getParent();
85 unsigned ADFS, BDFS;
86 if (BA == BB) {
87 ADFS = DFSNumber.lookup(A);
88 BDFS = DFSNumber.lookup(B);
89 } else {
90 ADFS = DFSNumber.lookup(BA);
91 BDFS = DFSNumber.lookup(BB);
92 }
Sebastian Pop5ba9f242016-10-13 01:39:10 +000093 assert(ADFS && BDFS);
Sebastian Pop91d4a302016-07-26 00:15:10 +000094 return ADFS < BDFS;
Sebastian Pop41774802016-07-15 13:45:20 +000095 }
96};
97
David Majnemer04c7c222016-07-18 06:11:37 +000098// A map from a pair of VNs to all the instructions with those VNs.
99typedef DenseMap<std::pair<unsigned, unsigned>, SmallVector<Instruction *, 4>>
100 VNtoInsns;
101// An invalid value number Used when inserting a single value number into
102// VNtoInsns.
Reid Kleckner3498ad12016-07-18 18:53:50 +0000103enum : unsigned { InvalidVN = ~2U };
Sebastian Pop41774802016-07-15 13:45:20 +0000104
105// Records all scalar instructions candidate for code hoisting.
106class InsnInfo {
107 VNtoInsns VNtoScalars;
108
109public:
110 // Inserts I and its value number in VNtoScalars.
111 void insert(Instruction *I, GVN::ValueTable &VN) {
112 // Scalar instruction.
113 unsigned V = VN.lookupOrAdd(I);
David Majnemer04c7c222016-07-18 06:11:37 +0000114 VNtoScalars[{V, InvalidVN}].push_back(I);
Sebastian Pop41774802016-07-15 13:45:20 +0000115 }
116
117 const VNtoInsns &getVNTable() const { return VNtoScalars; }
118};
119
120// Records all load instructions candidate for code hoisting.
121class LoadInfo {
122 VNtoInsns VNtoLoads;
123
124public:
125 // Insert Load and the value number of its memory address in VNtoLoads.
126 void insert(LoadInst *Load, GVN::ValueTable &VN) {
127 if (Load->isSimple()) {
128 unsigned V = VN.lookupOrAdd(Load->getPointerOperand());
David Majnemer04c7c222016-07-18 06:11:37 +0000129 VNtoLoads[{V, InvalidVN}].push_back(Load);
Sebastian Pop41774802016-07-15 13:45:20 +0000130 }
131 }
132
133 const VNtoInsns &getVNTable() const { return VNtoLoads; }
134};
135
136// Records all store instructions candidate for code hoisting.
137class StoreInfo {
138 VNtoInsns VNtoStores;
139
140public:
141 // Insert the Store and a hash number of the store address and the stored
142 // value in VNtoStores.
143 void insert(StoreInst *Store, GVN::ValueTable &VN) {
144 if (!Store->isSimple())
145 return;
146 // Hash the store address and the stored value.
147 Value *Ptr = Store->getPointerOperand();
148 Value *Val = Store->getValueOperand();
David Majnemer04c7c222016-07-18 06:11:37 +0000149 VNtoStores[{VN.lookupOrAdd(Ptr), VN.lookupOrAdd(Val)}].push_back(Store);
Sebastian Pop41774802016-07-15 13:45:20 +0000150 }
151
152 const VNtoInsns &getVNTable() const { return VNtoStores; }
153};
154
155// Records all call instructions candidate for code hoisting.
156class CallInfo {
157 VNtoInsns VNtoCallsScalars;
158 VNtoInsns VNtoCallsLoads;
159 VNtoInsns VNtoCallsStores;
160
161public:
162 // Insert Call and its value numbering in one of the VNtoCalls* containers.
163 void insert(CallInst *Call, GVN::ValueTable &VN) {
164 // A call that doesNotAccessMemory is handled as a Scalar,
165 // onlyReadsMemory will be handled as a Load instruction,
166 // all other calls will be handled as stores.
167 unsigned V = VN.lookupOrAdd(Call);
David Majnemer04c7c222016-07-18 06:11:37 +0000168 auto Entry = std::make_pair(V, InvalidVN);
Sebastian Pop41774802016-07-15 13:45:20 +0000169
170 if (Call->doesNotAccessMemory())
David Majnemer04c7c222016-07-18 06:11:37 +0000171 VNtoCallsScalars[Entry].push_back(Call);
Sebastian Pop41774802016-07-15 13:45:20 +0000172 else if (Call->onlyReadsMemory())
David Majnemer04c7c222016-07-18 06:11:37 +0000173 VNtoCallsLoads[Entry].push_back(Call);
Sebastian Pop41774802016-07-15 13:45:20 +0000174 else
David Majnemer04c7c222016-07-18 06:11:37 +0000175 VNtoCallsStores[Entry].push_back(Call);
Sebastian Pop41774802016-07-15 13:45:20 +0000176 }
177
178 const VNtoInsns &getScalarVNTable() const { return VNtoCallsScalars; }
179
180 const VNtoInsns &getLoadVNTable() const { return VNtoCallsLoads; }
181
182 const VNtoInsns &getStoreVNTable() const { return VNtoCallsStores; }
183};
184
185typedef DenseMap<const BasicBlock *, bool> BBSideEffectsSet;
186typedef SmallVector<Instruction *, 4> SmallVecInsn;
187typedef SmallVectorImpl<Instruction *> SmallVecImplInsn;
188
David Majnemer68623a02016-07-25 02:21:25 +0000189static void combineKnownMetadata(Instruction *ReplInst, Instruction *I) {
190 static const unsigned KnownIDs[] = {
191 LLVMContext::MD_tbaa, LLVMContext::MD_alias_scope,
192 LLVMContext::MD_noalias, LLVMContext::MD_range,
193 LLVMContext::MD_fpmath, LLVMContext::MD_invariant_load,
194 LLVMContext::MD_invariant_group};
195 combineMetadata(ReplInst, I, KnownIDs);
196}
197
Sebastian Pop41774802016-07-15 13:45:20 +0000198// This pass hoists common computations across branches sharing common
199// dominator. The primary goal is to reduce the code size, and in some
200// cases reduce critical path (by exposing more ILP).
201class GVNHoist {
202public:
Daniel Berlinea02eee2016-08-23 05:42:41 +0000203 GVNHoist(DominatorTree *DT, AliasAnalysis *AA, MemoryDependenceResults *MD,
Hans Wennborg19c0be92017-03-01 17:15:08 +0000204 MemorySSA *MSSA)
Daniel Berlin17e8d0e2017-02-22 22:19:55 +0000205 : DT(DT), AA(AA), MD(MD), MSSA(MSSA),
206 MSSAUpdater(make_unique<MemorySSAUpdater>(MSSA)),
Hans Wennborg19c0be92017-03-01 17:15:08 +0000207 HoistingGeps(false),
208 HoistedCtr(0)
209 { }
Aditya Kumar07cb3042016-11-29 14:34:01 +0000210
Daniel Berlin65af45d2016-07-25 17:24:22 +0000211 bool run(Function &F) {
212 VN.setDomTree(DT);
213 VN.setAliasAnalysis(AA);
214 VN.setMemDep(MD);
215 bool Res = false;
Sebastian Pop4ba7c882016-08-03 20:54:36 +0000216 // Perform DFS Numbering of instructions.
217 unsigned BBI = 0;
218 for (const BasicBlock *BB : depth_first(&F.getEntryBlock())) {
219 DFSNumber[BB] = ++BBI;
220 unsigned I = 0;
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000221 for (auto &Inst : *BB)
Sebastian Pop4ba7c882016-08-03 20:54:36 +0000222 DFSNumber[&Inst] = ++I;
223 }
Daniel Berlin65af45d2016-07-25 17:24:22 +0000224
Sebastian Pop2aadad72016-08-03 20:54:38 +0000225 int ChainLength = 0;
226
Daniel Berlin65af45d2016-07-25 17:24:22 +0000227 // FIXME: use lazy evaluation of VN to avoid the fix-point computation.
228 while (1) {
Sebastian Pop2aadad72016-08-03 20:54:38 +0000229 if (MaxChainLength != -1 && ++ChainLength >= MaxChainLength)
230 return Res;
231
Daniel Berlin65af45d2016-07-25 17:24:22 +0000232 auto HoistStat = hoistExpressions(F);
Sebastian Pop5d3822f2016-08-03 20:54:33 +0000233 if (HoistStat.first + HoistStat.second == 0)
Daniel Berlin65af45d2016-07-25 17:24:22 +0000234 return Res;
Sebastian Pop5d3822f2016-08-03 20:54:33 +0000235
236 if (HoistStat.second > 0)
Daniel Berlin65af45d2016-07-25 17:24:22 +0000237 // To address a limitation of the current GVN, we need to rerun the
Sebastian Pop5d3822f2016-08-03 20:54:33 +0000238 // hoisting after we hoisted loads or stores in order to be able to
239 // hoist all scalars dependent on the hoisted ld/st.
Daniel Berlin65af45d2016-07-25 17:24:22 +0000240 VN.clear();
Sebastian Pop5d3822f2016-08-03 20:54:33 +0000241
Daniel Berlin65af45d2016-07-25 17:24:22 +0000242 Res = true;
243 }
244
245 return Res;
246 }
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000247
Daniel Berlin65af45d2016-07-25 17:24:22 +0000248private:
Sebastian Pop41774802016-07-15 13:45:20 +0000249 GVN::ValueTable VN;
250 DominatorTree *DT;
251 AliasAnalysis *AA;
252 MemoryDependenceResults *MD;
Daniel Berlinea02eee2016-08-23 05:42:41 +0000253 MemorySSA *MSSA;
Daniel Berlin17e8d0e2017-02-22 22:19:55 +0000254 std::unique_ptr<MemorySSAUpdater> MSSAUpdater;
Sebastian Pop55c30072016-07-27 05:48:12 +0000255 const bool HoistingGeps;
Sebastian Pop91d4a302016-07-26 00:15:10 +0000256 DenseMap<const Value *, unsigned> DFSNumber;
Sebastian Pop41774802016-07-15 13:45:20 +0000257 BBSideEffectsSet BBSideEffects;
David Majnemeraa241782016-07-18 00:35:01 +0000258 int HoistedCtr;
259
Sebastian Pop41774802016-07-15 13:45:20 +0000260 enum InsKind { Unknown, Scalar, Load, Store };
261
Sebastian Pop41774802016-07-15 13:45:20 +0000262 // Return true when there are exception handling in BB.
263 bool hasEH(const BasicBlock *BB) {
264 auto It = BBSideEffects.find(BB);
265 if (It != BBSideEffects.end())
266 return It->second;
267
268 if (BB->isEHPad() || BB->hasAddressTaken()) {
269 BBSideEffects[BB] = true;
270 return true;
271 }
272
273 if (BB->getTerminator()->mayThrow()) {
274 BBSideEffects[BB] = true;
275 return true;
276 }
277
278 BBSideEffects[BB] = false;
279 return false;
280 }
281
Sebastian Pop5f0d0e62016-08-25 11:55:47 +0000282 // Return true when a successor of BB dominates A.
283 bool successorDominate(const BasicBlock *BB, const BasicBlock *A) {
284 for (const BasicBlock *Succ : BB->getTerminator()->successors())
285 if (DT->dominates(Succ, A))
286 return true;
Sebastian Pop41774802016-07-15 13:45:20 +0000287
Sebastian Pop5f0d0e62016-08-25 11:55:47 +0000288 return false;
289 }
290
291 // Return true when all paths from HoistBB to the end of the function pass
292 // through one of the blocks in WL.
293 bool hoistingFromAllPaths(const BasicBlock *HoistBB,
294 SmallPtrSetImpl<const BasicBlock *> &WL) {
295
296 // Copy WL as the loop will remove elements from it.
297 SmallPtrSet<const BasicBlock *, 2> WorkList(WL.begin(), WL.end());
298
299 for (auto It = df_begin(HoistBB), E = df_end(HoistBB); It != E;) {
300 // There exists a path from HoistBB to the exit of the function if we are
301 // still iterating in DF traversal and we removed all instructions from
302 // the work list.
303 if (WorkList.empty())
Sebastian Pop41774802016-07-15 13:45:20 +0000304 return false;
305
306 const BasicBlock *BB = *It;
Sebastian Pop5f0d0e62016-08-25 11:55:47 +0000307 if (WorkList.erase(BB)) {
Sebastian Pop41774802016-07-15 13:45:20 +0000308 // Stop DFS traversal when BB is in the work list.
309 It.skipChildren();
310 continue;
311 }
312
313 // Check for end of function, calls that do not return, etc.
314 if (!isGuaranteedToTransferExecutionToSuccessor(BB->getTerminator()))
315 return false;
316
Sebastian Pop5f0d0e62016-08-25 11:55:47 +0000317 // When reaching the back-edge of a loop, there may be a path through the
318 // loop that does not pass through B or C before exiting the loop.
319 if (successorDominate(BB, HoistBB))
320 return false;
321
Sebastian Pop41774802016-07-15 13:45:20 +0000322 // Increment DFS traversal when not skipping children.
323 ++It;
324 }
325
326 return true;
327 }
328
329 /* Return true when I1 appears before I2 in the instructions of BB. */
Sebastian Pop91d4a302016-07-26 00:15:10 +0000330 bool firstInBB(const Instruction *I1, const Instruction *I2) {
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000331 assert(I1->getParent() == I2->getParent());
Sebastian Pop91d4a302016-07-26 00:15:10 +0000332 unsigned I1DFS = DFSNumber.lookup(I1);
333 unsigned I2DFS = DFSNumber.lookup(I2);
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000334 assert(I1DFS && I2DFS);
Sebastian Pop91d4a302016-07-26 00:15:10 +0000335 return I1DFS < I2DFS;
Daniel Berlin40765a62016-07-25 18:19:49 +0000336 }
Sebastian Pop91d4a302016-07-26 00:15:10 +0000337
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000338 // Return true when there are memory uses of Def in BB.
339 bool hasMemoryUse(const Instruction *NewPt, MemoryDef *Def,
340 const BasicBlock *BB) {
341 const MemorySSA::AccessList *Acc = MSSA->getBlockAccesses(BB);
342 if (!Acc)
343 return false;
344
345 Instruction *OldPt = Def->getMemoryInst();
Sebastian Pop41774802016-07-15 13:45:20 +0000346 const BasicBlock *OldBB = OldPt->getParent();
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000347 const BasicBlock *NewBB = NewPt->getParent();
348 bool ReachedNewPt = false;
Sebastian Pop41774802016-07-15 13:45:20 +0000349
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000350 for (const MemoryAccess &MA : *Acc)
351 if (const MemoryUse *MU = dyn_cast<MemoryUse>(&MA)) {
352 Instruction *Insn = MU->getMemoryInst();
Sebastian Pop1531f302016-09-22 17:22:58 +0000353
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000354 // Do not check whether MU aliases Def when MU occurs after OldPt.
355 if (BB == OldBB && firstInBB(OldPt, Insn))
356 break;
357
358 // Do not check whether MU aliases Def when MU occurs before NewPt.
359 if (BB == NewBB) {
360 if (!ReachedNewPt) {
361 if (firstInBB(Insn, NewPt))
362 continue;
363 ReachedNewPt = true;
364 }
Sebastian Pop41774802016-07-15 13:45:20 +0000365 }
Daniel Berlindcb004f2017-03-02 23:06:46 +0000366 if (MemorySSAUtil::defClobbersUseOrDef(Def, MU, *AA))
Hans Wennborgc7957ef2016-09-22 21:20:53 +0000367 return true;
368 }
Sebastian Pop8e6e3312016-09-22 15:33:51 +0000369
Sebastian Pop41774802016-07-15 13:45:20 +0000370 return false;
371 }
372
373 // Return true when there are exception handling or loads of memory Def
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000374 // between Def and NewPt. This function is only called for stores: Def is
375 // the MemoryDef of the store to be hoisted.
Sebastian Pop41774802016-07-15 13:45:20 +0000376
377 // Decrement by 1 NBBsOnAllPaths for each block between HoistPt and BB, and
378 // return true when the counter NBBsOnAllPaths reaces 0, except when it is
379 // initialized to -1 which is unlimited.
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000380 bool hasEHOrLoadsOnPath(const Instruction *NewPt, MemoryDef *Def,
381 int &NBBsOnAllPaths) {
Sebastian Pop41774802016-07-15 13:45:20 +0000382 const BasicBlock *NewBB = NewPt->getParent();
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000383 const BasicBlock *OldBB = Def->getBlock();
Sebastian Pop41774802016-07-15 13:45:20 +0000384 assert(DT->dominates(NewBB, OldBB) && "invalid path");
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000385 assert(DT->dominates(Def->getDefiningAccess()->getBlock(), NewBB) &&
Sebastian Pop41774802016-07-15 13:45:20 +0000386 "def does not dominate new hoisting point");
387
388 // Walk all basic blocks reachable in depth-first iteration on the inverse
389 // CFG from OldBB to NewBB. These blocks are all the blocks that may be
390 // executed between the execution of NewBB and OldBB. Hoisting an expression
391 // from OldBB into NewBB has to be safe on all execution paths.
392 for (auto I = idf_begin(OldBB), E = idf_end(OldBB); I != E;) {
393 if (*I == NewBB) {
394 // Stop traversal when reaching HoistPt.
395 I.skipChildren();
396 continue;
397 }
398
Aditya Kumar314ebe02016-11-29 14:36:27 +0000399 // Stop walk once the limit is reached.
400 if (NBBsOnAllPaths == 0)
401 return true;
402
Sebastian Pop41774802016-07-15 13:45:20 +0000403 // Impossible to hoist with exceptions on the path.
404 if (hasEH(*I))
405 return true;
406
407 // Check that we do not move a store past loads.
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000408 if (hasMemoryUse(NewPt, Def, *I))
Sebastian Pop41774802016-07-15 13:45:20 +0000409 return true;
410
Sebastian Pop41774802016-07-15 13:45:20 +0000411 // -1 is unlimited number of blocks on all paths.
412 if (NBBsOnAllPaths != -1)
413 --NBBsOnAllPaths;
414
415 ++I;
416 }
417
418 return false;
419 }
420
421 // Return true when there are exception handling between HoistPt and BB.
422 // Decrement by 1 NBBsOnAllPaths for each block between HoistPt and BB, and
423 // return true when the counter NBBsOnAllPaths reaches 0, except when it is
424 // initialized to -1 which is unlimited.
425 bool hasEHOnPath(const BasicBlock *HoistPt, const BasicBlock *BB,
426 int &NBBsOnAllPaths) {
427 assert(DT->dominates(HoistPt, BB) && "Invalid path");
428
429 // Walk all basic blocks reachable in depth-first iteration on
430 // the inverse CFG from BBInsn to NewHoistPt. These blocks are all the
431 // blocks that may be executed between the execution of NewHoistPt and
432 // BBInsn. Hoisting an expression from BBInsn into NewHoistPt has to be safe
433 // on all execution paths.
434 for (auto I = idf_begin(BB), E = idf_end(BB); I != E;) {
435 if (*I == HoistPt) {
436 // Stop traversal when reaching NewHoistPt.
437 I.skipChildren();
438 continue;
439 }
440
Sebastian Pop41774802016-07-15 13:45:20 +0000441 // Stop walk once the limit is reached.
442 if (NBBsOnAllPaths == 0)
443 return true;
444
Aditya Kumar314ebe02016-11-29 14:36:27 +0000445 // Impossible to hoist with exceptions on the path.
446 if (hasEH(*I))
447 return true;
448
Sebastian Pop41774802016-07-15 13:45:20 +0000449 // -1 is unlimited number of blocks on all paths.
450 if (NBBsOnAllPaths != -1)
451 --NBBsOnAllPaths;
452
453 ++I;
454 }
455
456 return false;
457 }
458
459 // Return true when it is safe to hoist a memory load or store U from OldPt
460 // to NewPt.
461 bool safeToHoistLdSt(const Instruction *NewPt, const Instruction *OldPt,
462 MemoryUseOrDef *U, InsKind K, int &NBBsOnAllPaths) {
463
464 // In place hoisting is safe.
465 if (NewPt == OldPt)
466 return true;
467
468 const BasicBlock *NewBB = NewPt->getParent();
469 const BasicBlock *OldBB = OldPt->getParent();
470 const BasicBlock *UBB = U->getBlock();
471
472 // Check for dependences on the Memory SSA.
473 MemoryAccess *D = U->getDefiningAccess();
474 BasicBlock *DBB = D->getBlock();
475 if (DT->properlyDominates(NewBB, DBB))
476 // Cannot move the load or store to NewBB above its definition in DBB.
477 return false;
478
479 if (NewBB == DBB && !MSSA->isLiveOnEntryDef(D))
David Majnemer4c66a712016-07-18 00:34:58 +0000480 if (auto *UD = dyn_cast<MemoryUseOrDef>(D))
Sebastian Pop91d4a302016-07-26 00:15:10 +0000481 if (firstInBB(NewPt, UD->getMemoryInst()))
Sebastian Pop41774802016-07-15 13:45:20 +0000482 // Cannot move the load or store to NewPt above its definition in D.
483 return false;
484
485 // Check for unsafe hoistings due to side effects.
486 if (K == InsKind::Store) {
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000487 if (hasEHOrLoadsOnPath(NewPt, dyn_cast<MemoryDef>(U), NBBsOnAllPaths))
Sebastian Pop41774802016-07-15 13:45:20 +0000488 return false;
489 } else if (hasEHOnPath(NewBB, OldBB, NBBsOnAllPaths))
490 return false;
491
492 if (UBB == NewBB) {
493 if (DT->properlyDominates(DBB, NewBB))
494 return true;
495 assert(UBB == DBB);
496 assert(MSSA->locallyDominates(D, U));
497 }
498
499 // No side effects: it is safe to hoist.
500 return true;
501 }
502
Sebastian Pop5f0d0e62016-08-25 11:55:47 +0000503 // Return true when it is safe to hoist scalar instructions from all blocks in
504 // WL to HoistBB.
505 bool safeToHoistScalar(const BasicBlock *HoistBB,
506 SmallPtrSetImpl<const BasicBlock *> &WL,
507 int &NBBsOnAllPaths) {
Aditya Kumar07cb3042016-11-29 14:34:01 +0000508 // Check that the hoisted expression is needed on all paths.
509 if (!hoistingFromAllPaths(HoistBB, WL))
Sebastian Pop41774802016-07-15 13:45:20 +0000510 return false;
511
Sebastian Pop5f0d0e62016-08-25 11:55:47 +0000512 for (const BasicBlock *BB : WL)
513 if (hasEHOnPath(HoistBB, BB, NBBsOnAllPaths))
514 return false;
Sebastian Pop41774802016-07-15 13:45:20 +0000515
Sebastian Pop41774802016-07-15 13:45:20 +0000516 return true;
517 }
518
519 // Each element of a hoisting list contains the basic block where to hoist and
520 // a list of instructions to be hoisted.
521 typedef std::pair<BasicBlock *, SmallVecInsn> HoistingPointInfo;
522 typedef SmallVector<HoistingPointInfo, 4> HoistingPointList;
523
524 // Partition InstructionsToHoist into a set of candidates which can share a
525 // common hoisting point. The partitions are collected in HPL. IsScalar is
526 // true when the instructions in InstructionsToHoist are scalars. IsLoad is
527 // true when the InstructionsToHoist are loads, false when they are stores.
528 void partitionCandidates(SmallVecImplInsn &InstructionsToHoist,
529 HoistingPointList &HPL, InsKind K) {
530 // No need to sort for two instructions.
531 if (InstructionsToHoist.size() > 2) {
532 SortByDFSIn Pred(DFSNumber);
533 std::sort(InstructionsToHoist.begin(), InstructionsToHoist.end(), Pred);
534 }
535
Aditya Kumar314ebe02016-11-29 14:36:27 +0000536 int NumBBsOnAllPaths = MaxNumberOfBBSInPath;
Sebastian Pop41774802016-07-15 13:45:20 +0000537
538 SmallVecImplInsn::iterator II = InstructionsToHoist.begin();
539 SmallVecImplInsn::iterator Start = II;
540 Instruction *HoistPt = *II;
541 BasicBlock *HoistBB = HoistPt->getParent();
542 MemoryUseOrDef *UD;
543 if (K != InsKind::Scalar)
George Burgess IV66837ab2016-11-01 21:17:46 +0000544 UD = MSSA->getMemoryAccess(HoistPt);
Sebastian Pop41774802016-07-15 13:45:20 +0000545
546 for (++II; II != InstructionsToHoist.end(); ++II) {
547 Instruction *Insn = *II;
548 BasicBlock *BB = Insn->getParent();
549 BasicBlock *NewHoistBB;
550 Instruction *NewHoistPt;
551
Aditya Kumar314ebe02016-11-29 14:36:27 +0000552 if (BB == HoistBB) { // Both are in the same Basic Block.
Sebastian Pop41774802016-07-15 13:45:20 +0000553 NewHoistBB = HoistBB;
Sebastian Pop91d4a302016-07-26 00:15:10 +0000554 NewHoistPt = firstInBB(Insn, HoistPt) ? Insn : HoistPt;
Sebastian Pop41774802016-07-15 13:45:20 +0000555 } else {
Aditya Kumar314ebe02016-11-29 14:36:27 +0000556 // If the hoisting point contains one of the instructions,
557 // then hoist there, otherwise hoist before the terminator.
Sebastian Pop41774802016-07-15 13:45:20 +0000558 NewHoistBB = DT->findNearestCommonDominator(HoistBB, BB);
559 if (NewHoistBB == BB)
560 NewHoistPt = Insn;
561 else if (NewHoistBB == HoistBB)
562 NewHoistPt = HoistPt;
563 else
564 NewHoistPt = NewHoistBB->getTerminator();
565 }
566
Sebastian Pop5f0d0e62016-08-25 11:55:47 +0000567 SmallPtrSet<const BasicBlock *, 2> WL;
568 WL.insert(HoistBB);
569 WL.insert(BB);
570
Sebastian Pop41774802016-07-15 13:45:20 +0000571 if (K == InsKind::Scalar) {
Aditya Kumar314ebe02016-11-29 14:36:27 +0000572 if (safeToHoistScalar(NewHoistBB, WL, NumBBsOnAllPaths)) {
Sebastian Pop41774802016-07-15 13:45:20 +0000573 // Extend HoistPt to NewHoistPt.
574 HoistPt = NewHoistPt;
575 HoistBB = NewHoistBB;
576 continue;
577 }
578 } else {
579 // When NewBB already contains an instruction to be hoisted, the
580 // expression is needed on all paths.
581 // Check that the hoisted expression is needed on all paths: it is
582 // unsafe to hoist loads to a place where there may be a path not
583 // loading from the same address: for instance there may be a branch on
584 // which the address of the load may not be initialized.
585 if ((HoistBB == NewHoistBB || BB == NewHoistBB ||
Sebastian Pop5f0d0e62016-08-25 11:55:47 +0000586 hoistingFromAllPaths(NewHoistBB, WL)) &&
Sebastian Pop41774802016-07-15 13:45:20 +0000587 // Also check that it is safe to move the load or store from HoistPt
588 // to NewHoistPt, and from Insn to NewHoistPt.
Aditya Kumar314ebe02016-11-29 14:36:27 +0000589 safeToHoistLdSt(NewHoistPt, HoistPt, UD, K, NumBBsOnAllPaths) &&
George Burgess IV66837ab2016-11-01 21:17:46 +0000590 safeToHoistLdSt(NewHoistPt, Insn, MSSA->getMemoryAccess(Insn),
Aditya Kumar314ebe02016-11-29 14:36:27 +0000591 K, NumBBsOnAllPaths)) {
Sebastian Pop41774802016-07-15 13:45:20 +0000592 // Extend HoistPt to NewHoistPt.
593 HoistPt = NewHoistPt;
594 HoistBB = NewHoistBB;
595 continue;
596 }
597 }
598
599 // At this point it is not safe to extend the current hoisting to
600 // NewHoistPt: save the hoisting list so far.
601 if (std::distance(Start, II) > 1)
David Majnemer4c66a712016-07-18 00:34:58 +0000602 HPL.push_back({HoistBB, SmallVecInsn(Start, II)});
Sebastian Pop41774802016-07-15 13:45:20 +0000603
604 // Start over from BB.
605 Start = II;
606 if (K != InsKind::Scalar)
George Burgess IV66837ab2016-11-01 21:17:46 +0000607 UD = MSSA->getMemoryAccess(*Start);
Sebastian Pop41774802016-07-15 13:45:20 +0000608 HoistPt = Insn;
609 HoistBB = BB;
Aditya Kumar314ebe02016-11-29 14:36:27 +0000610 NumBBsOnAllPaths = MaxNumberOfBBSInPath;
Sebastian Pop41774802016-07-15 13:45:20 +0000611 }
612
613 // Save the last partition.
614 if (std::distance(Start, II) > 1)
David Majnemer4c66a712016-07-18 00:34:58 +0000615 HPL.push_back({HoistBB, SmallVecInsn(Start, II)});
Sebastian Pop41774802016-07-15 13:45:20 +0000616 }
617
618 // Initialize HPL from Map.
619 void computeInsertionPoints(const VNtoInsns &Map, HoistingPointList &HPL,
620 InsKind K) {
David Majnemer4c66a712016-07-18 00:34:58 +0000621 for (const auto &Entry : Map) {
Sebastian Pop41774802016-07-15 13:45:20 +0000622 if (MaxHoistedThreshold != -1 && ++HoistedCtr > MaxHoistedThreshold)
623 return;
624
David Majnemer4c66a712016-07-18 00:34:58 +0000625 const SmallVecInsn &V = Entry.second;
Sebastian Pop41774802016-07-15 13:45:20 +0000626 if (V.size() < 2)
627 continue;
628
629 // Compute the insertion point and the list of expressions to be hoisted.
630 SmallVecInsn InstructionsToHoist;
631 for (auto I : V)
632 if (!hasEH(I->getParent()))
633 InstructionsToHoist.push_back(I);
634
David Majnemer4c66a712016-07-18 00:34:58 +0000635 if (!InstructionsToHoist.empty())
Sebastian Pop41774802016-07-15 13:45:20 +0000636 partitionCandidates(InstructionsToHoist, HPL, K);
637 }
638 }
639
640 // Return true when all operands of Instr are available at insertion point
641 // HoistPt. When limiting the number of hoisted expressions, one could hoist
642 // a load without hoisting its access function. So before hoisting any
643 // expression, make sure that all its operands are available at insert point.
644 bool allOperandsAvailable(const Instruction *I,
645 const BasicBlock *HoistPt) const {
David Majnemer4c66a712016-07-18 00:34:58 +0000646 for (const Use &Op : I->operands())
647 if (const auto *Inst = dyn_cast<Instruction>(&Op))
648 if (!DT->dominates(Inst->getParent(), HoistPt))
649 return false;
Sebastian Pop41774802016-07-15 13:45:20 +0000650
651 return true;
652 }
653
Sebastian Pop55c30072016-07-27 05:48:12 +0000654 // Same as allOperandsAvailable with recursive check for GEP operands.
655 bool allGepOperandsAvailable(const Instruction *I,
656 const BasicBlock *HoistPt) const {
657 for (const Use &Op : I->operands())
658 if (const auto *Inst = dyn_cast<Instruction>(&Op))
659 if (!DT->dominates(Inst->getParent(), HoistPt)) {
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000660 if (const GetElementPtrInst *GepOp =
661 dyn_cast<GetElementPtrInst>(Inst)) {
Sebastian Pop55c30072016-07-27 05:48:12 +0000662 if (!allGepOperandsAvailable(GepOp, HoistPt))
663 return false;
664 // Gep is available if all operands of GepOp are available.
665 } else {
666 // Gep is not available if it has operands other than GEPs that are
667 // defined in blocks not dominating HoistPt.
668 return false;
669 }
670 }
671 return true;
672 }
673
674 // Make all operands of the GEP available.
675 void makeGepsAvailable(Instruction *Repl, BasicBlock *HoistPt,
676 const SmallVecInsn &InstructionsToHoist,
677 Instruction *Gep) const {
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000678 assert(allGepOperandsAvailable(Gep, HoistPt) &&
679 "GEP operands not available");
Sebastian Pop55c30072016-07-27 05:48:12 +0000680
681 Instruction *ClonedGep = Gep->clone();
682 for (unsigned i = 0, e = Gep->getNumOperands(); i != e; ++i)
683 if (Instruction *Op = dyn_cast<Instruction>(Gep->getOperand(i))) {
684
685 // Check whether the operand is already available.
686 if (DT->dominates(Op->getParent(), HoistPt))
687 continue;
688
689 // As a GEP can refer to other GEPs, recursively make all the operands
690 // of this GEP available at HoistPt.
691 if (GetElementPtrInst *GepOp = dyn_cast<GetElementPtrInst>(Op))
692 makeGepsAvailable(ClonedGep, HoistPt, InstructionsToHoist, GepOp);
693 }
694
695 // Copy Gep and replace its uses in Repl with ClonedGep.
696 ClonedGep->insertBefore(HoistPt->getTerminator());
697
698 // Conservatively discard any optimization hints, they may differ on the
699 // other paths.
700 ClonedGep->dropUnknownNonDebugMetadata();
701
702 // If we have optimization hints which agree with each other along different
703 // paths, preserve them.
704 for (const Instruction *OtherInst : InstructionsToHoist) {
705 const GetElementPtrInst *OtherGep;
706 if (auto *OtherLd = dyn_cast<LoadInst>(OtherInst))
707 OtherGep = cast<GetElementPtrInst>(OtherLd->getPointerOperand());
708 else
709 OtherGep = cast<GetElementPtrInst>(
710 cast<StoreInst>(OtherInst)->getPointerOperand());
Peter Collingbourne8f1dd5c2016-09-07 23:39:04 +0000711 ClonedGep->andIRFlags(OtherGep);
Sebastian Pop55c30072016-07-27 05:48:12 +0000712 }
713
714 // Replace uses of Gep with ClonedGep in Repl.
715 Repl->replaceUsesOfWith(Gep, ClonedGep);
716 }
717
718 // In the case Repl is a load or a store, we make all their GEPs
719 // available: GEPs are not hoisted by default to avoid the address
720 // computations to be hoisted without the associated load or store.
721 bool makeGepOperandsAvailable(Instruction *Repl, BasicBlock *HoistPt,
722 const SmallVecInsn &InstructionsToHoist) const {
Sebastian Pop41774802016-07-15 13:45:20 +0000723 // Check whether the GEP of a ld/st can be synthesized at HoistPt.
David Majnemerbd210122016-07-20 21:05:01 +0000724 GetElementPtrInst *Gep = nullptr;
Sebastian Pop41774802016-07-15 13:45:20 +0000725 Instruction *Val = nullptr;
Sebastian Pop55c30072016-07-27 05:48:12 +0000726 if (auto *Ld = dyn_cast<LoadInst>(Repl)) {
David Majnemerbd210122016-07-20 21:05:01 +0000727 Gep = dyn_cast<GetElementPtrInst>(Ld->getPointerOperand());
Sebastian Pop55c30072016-07-27 05:48:12 +0000728 } else if (auto *St = dyn_cast<StoreInst>(Repl)) {
David Majnemerbd210122016-07-20 21:05:01 +0000729 Gep = dyn_cast<GetElementPtrInst>(St->getPointerOperand());
Sebastian Pop41774802016-07-15 13:45:20 +0000730 Val = dyn_cast<Instruction>(St->getValueOperand());
Sebastian Pop31fd5062016-07-21 23:22:10 +0000731 // Check that the stored value is available.
Sebastian Pop0e2cec02016-07-22 00:07:01 +0000732 if (Val) {
733 if (isa<GetElementPtrInst>(Val)) {
734 // Check whether we can compute the GEP at HoistPt.
Sebastian Pop55c30072016-07-27 05:48:12 +0000735 if (!allGepOperandsAvailable(Val, HoistPt))
Sebastian Pop0e2cec02016-07-22 00:07:01 +0000736 return false;
737 } else if (!DT->dominates(Val->getParent(), HoistPt))
738 return false;
739 }
Sebastian Pop41774802016-07-15 13:45:20 +0000740 }
741
Sebastian Pop41774802016-07-15 13:45:20 +0000742 // Check whether we can compute the Gep at HoistPt.
Sebastian Pop55c30072016-07-27 05:48:12 +0000743 if (!Gep || !allGepOperandsAvailable(Gep, HoistPt))
Sebastian Pop41774802016-07-15 13:45:20 +0000744 return false;
745
Sebastian Pop55c30072016-07-27 05:48:12 +0000746 makeGepsAvailable(Repl, HoistPt, InstructionsToHoist, Gep);
Sebastian Pop41774802016-07-15 13:45:20 +0000747
Sebastian Pop55c30072016-07-27 05:48:12 +0000748 if (Val && isa<GetElementPtrInst>(Val))
749 makeGepsAvailable(Repl, HoistPt, InstructionsToHoist, Val);
Sebastian Pop41774802016-07-15 13:45:20 +0000750
751 return true;
752 }
753
754 std::pair<unsigned, unsigned> hoist(HoistingPointList &HPL) {
755 unsigned NI = 0, NL = 0, NS = 0, NC = 0, NR = 0;
756 for (const HoistingPointInfo &HP : HPL) {
757 // Find out whether we already have one of the instructions in HoistPt,
758 // in which case we do not have to move it.
759 BasicBlock *HoistPt = HP.first;
760 const SmallVecInsn &InstructionsToHoist = HP.second;
761 Instruction *Repl = nullptr;
762 for (Instruction *I : InstructionsToHoist)
Sebastian Pop586d3ea2016-07-27 05:13:52 +0000763 if (I->getParent() == HoistPt)
Sebastian Pop41774802016-07-15 13:45:20 +0000764 // If there are two instructions in HoistPt to be hoisted in place:
765 // update Repl to be the first one, such that we can rename the uses
766 // of the second based on the first.
Sebastian Pop586d3ea2016-07-27 05:13:52 +0000767 if (!Repl || firstInBB(I, Repl))
768 Repl = I;
Sebastian Pop41774802016-07-15 13:45:20 +0000769
Daniel Berlinf75fd1b2016-08-11 20:32:43 +0000770 // Keep track of whether we moved the instruction so we know whether we
771 // should move the MemoryAccess.
772 bool MoveAccess = true;
Sebastian Pop41774802016-07-15 13:45:20 +0000773 if (Repl) {
774 // Repl is already in HoistPt: it remains in place.
775 assert(allOperandsAvailable(Repl, HoistPt) &&
776 "instruction depends on operands that are not available");
Daniel Berlinf75fd1b2016-08-11 20:32:43 +0000777 MoveAccess = false;
Sebastian Pop41774802016-07-15 13:45:20 +0000778 } else {
779 // When we do not find Repl in HoistPt, select the first in the list
780 // and move it to HoistPt.
781 Repl = InstructionsToHoist.front();
782
783 // We can move Repl in HoistPt only when all operands are available.
784 // The order in which hoistings are done may influence the availability
785 // of operands.
Sebastian Pop429740a2016-08-04 23:49:05 +0000786 if (!allOperandsAvailable(Repl, HoistPt)) {
787
788 // When HoistingGeps there is nothing more we can do to make the
789 // operands available: just continue.
790 if (HoistingGeps)
791 continue;
792
793 // When not HoistingGeps we need to copy the GEPs.
794 if (!makeGepOperandsAvailable(Repl, HoistPt, InstructionsToHoist))
795 continue;
796 }
Sebastian Pop55c30072016-07-27 05:48:12 +0000797
Sebastian Pop5d3822f2016-08-03 20:54:33 +0000798 // Move the instruction at the end of HoistPt.
Sebastian Pop4ba7c882016-08-03 20:54:36 +0000799 Instruction *Last = HoistPt->getTerminator();
Eli Friedmanc6885fc2016-12-07 19:55:59 +0000800 MD->removeInstruction(Repl);
Sebastian Pop4ba7c882016-08-03 20:54:36 +0000801 Repl->moveBefore(Last);
802
803 DFSNumber[Repl] = DFSNumber[Last]++;
Sebastian Pop41774802016-07-15 13:45:20 +0000804 }
805
Daniel Berlinf75fd1b2016-08-11 20:32:43 +0000806 MemoryAccess *NewMemAcc = MSSA->getMemoryAccess(Repl);
807
808 if (MoveAccess) {
809 if (MemoryUseOrDef *OldMemAcc =
810 dyn_cast_or_null<MemoryUseOrDef>(NewMemAcc)) {
Sebastian Pop5d3822f2016-08-03 20:54:33 +0000811 // The definition of this ld/st will not change: ld/st hoisting is
812 // legal when the ld/st is not moved past its current definition.
813 MemoryAccess *Def = OldMemAcc->getDefiningAccess();
Daniel Berlinf75fd1b2016-08-11 20:32:43 +0000814 NewMemAcc =
Daniel Berlin17e8d0e2017-02-22 22:19:55 +0000815 MSSAUpdater->createMemoryAccessInBB(Repl, Def, HoistPt, MemorySSA::End);
Sebastian Pop5d3822f2016-08-03 20:54:33 +0000816 OldMemAcc->replaceAllUsesWith(NewMemAcc);
Daniel Berlin17e8d0e2017-02-22 22:19:55 +0000817 MSSAUpdater->removeMemoryAccess(OldMemAcc);
Sebastian Pop5d3822f2016-08-03 20:54:33 +0000818 }
819 }
820
Sebastian Pop41774802016-07-15 13:45:20 +0000821 if (isa<LoadInst>(Repl))
822 ++NL;
823 else if (isa<StoreInst>(Repl))
824 ++NS;
825 else if (isa<CallInst>(Repl))
826 ++NC;
827 else // Scalar
828 ++NI;
829
830 // Remove and rename all other instructions.
831 for (Instruction *I : InstructionsToHoist)
832 if (I != Repl) {
833 ++NR;
David Majnemer47285692016-07-25 02:21:23 +0000834 if (auto *ReplacementLoad = dyn_cast<LoadInst>(Repl)) {
835 ReplacementLoad->setAlignment(
836 std::min(ReplacementLoad->getAlignment(),
837 cast<LoadInst>(I)->getAlignment()));
Sebastian Pop41774802016-07-15 13:45:20 +0000838 ++NumLoadsRemoved;
David Majnemer47285692016-07-25 02:21:23 +0000839 } else if (auto *ReplacementStore = dyn_cast<StoreInst>(Repl)) {
840 ReplacementStore->setAlignment(
841 std::min(ReplacementStore->getAlignment(),
842 cast<StoreInst>(I)->getAlignment()));
Sebastian Pop41774802016-07-15 13:45:20 +0000843 ++NumStoresRemoved;
David Majnemer47285692016-07-25 02:21:23 +0000844 } else if (auto *ReplacementAlloca = dyn_cast<AllocaInst>(Repl)) {
845 ReplacementAlloca->setAlignment(
846 std::max(ReplacementAlloca->getAlignment(),
847 cast<AllocaInst>(I)->getAlignment()));
848 } else if (isa<CallInst>(Repl)) {
Sebastian Pop41774802016-07-15 13:45:20 +0000849 ++NumCallsRemoved;
David Majnemer47285692016-07-25 02:21:23 +0000850 }
Sebastian Pop5d3822f2016-08-03 20:54:33 +0000851
852 if (NewMemAcc) {
853 // Update the uses of the old MSSA access with NewMemAcc.
854 MemoryAccess *OldMA = MSSA->getMemoryAccess(I);
855 OldMA->replaceAllUsesWith(NewMemAcc);
Daniel Berlin17e8d0e2017-02-22 22:19:55 +0000856 MSSAUpdater->removeMemoryAccess(OldMA);
Sebastian Pop5d3822f2016-08-03 20:54:33 +0000857 }
858
Peter Collingbourne8f1dd5c2016-09-07 23:39:04 +0000859 Repl->andIRFlags(I);
David Majnemer68623a02016-07-25 02:21:25 +0000860 combineKnownMetadata(Repl, I);
Sebastian Pop41774802016-07-15 13:45:20 +0000861 I->replaceAllUsesWith(Repl);
Sebastian Pop46601992016-08-27 02:48:41 +0000862 // Also invalidate the Alias Analysis cache.
863 MD->removeInstruction(I);
Sebastian Pop41774802016-07-15 13:45:20 +0000864 I->eraseFromParent();
865 }
Sebastian Pop5d3822f2016-08-03 20:54:33 +0000866
867 // Remove MemorySSA phi nodes with the same arguments.
868 if (NewMemAcc) {
869 SmallPtrSet<MemoryPhi *, 4> UsePhis;
870 for (User *U : NewMemAcc->users())
871 if (MemoryPhi *Phi = dyn_cast<MemoryPhi>(U))
872 UsePhis.insert(Phi);
873
874 for (auto *Phi : UsePhis) {
875 auto In = Phi->incoming_values();
David Majnemer0a16c222016-08-11 21:15:00 +0000876 if (all_of(In, [&](Use &U) { return U == NewMemAcc; })) {
Sebastian Pop5d3822f2016-08-03 20:54:33 +0000877 Phi->replaceAllUsesWith(NewMemAcc);
Daniel Berlin17e8d0e2017-02-22 22:19:55 +0000878 MSSAUpdater->removeMemoryAccess(Phi);
Sebastian Pop5d3822f2016-08-03 20:54:33 +0000879 }
880 }
881 }
Sebastian Pop41774802016-07-15 13:45:20 +0000882 }
883
884 NumHoisted += NL + NS + NC + NI;
885 NumRemoved += NR;
886 NumLoadsHoisted += NL;
887 NumStoresHoisted += NS;
888 NumCallsHoisted += NC;
889 return {NI, NL + NC + NS};
890 }
891
892 // Hoist all expressions. Returns Number of scalars hoisted
893 // and number of non-scalars hoisted.
894 std::pair<unsigned, unsigned> hoistExpressions(Function &F) {
895 InsnInfo II;
896 LoadInfo LI;
897 StoreInfo SI;
898 CallInfo CI;
899 for (BasicBlock *BB : depth_first(&F.getEntryBlock())) {
Sebastian Pop38422b12016-07-26 00:15:08 +0000900 int InstructionNb = 0;
Sebastian Pop41774802016-07-15 13:45:20 +0000901 for (Instruction &I1 : *BB) {
Sebastian Pop38422b12016-07-26 00:15:08 +0000902 // Only hoist the first instructions in BB up to MaxDepthInBB. Hoisting
903 // deeper may increase the register pressure and compilation time.
904 if (MaxDepthInBB != -1 && InstructionNb++ >= MaxDepthInBB)
905 break;
906
Sebastian Pop440f15b2016-09-22 14:45:40 +0000907 // Do not value number terminator instructions.
Sebastian Pop5d68aa72016-09-22 15:08:09 +0000908 if (isa<TerminatorInst>(&I1))
Sebastian Pop440f15b2016-09-22 14:45:40 +0000909 break;
910
David Majnemer4c66a712016-07-18 00:34:58 +0000911 if (auto *Load = dyn_cast<LoadInst>(&I1))
Sebastian Pop41774802016-07-15 13:45:20 +0000912 LI.insert(Load, VN);
David Majnemer4c66a712016-07-18 00:34:58 +0000913 else if (auto *Store = dyn_cast<StoreInst>(&I1))
Sebastian Pop41774802016-07-15 13:45:20 +0000914 SI.insert(Store, VN);
David Majnemer4c66a712016-07-18 00:34:58 +0000915 else if (auto *Call = dyn_cast<CallInst>(&I1)) {
916 if (auto *Intr = dyn_cast<IntrinsicInst>(Call)) {
Sebastian Pop41774802016-07-15 13:45:20 +0000917 if (isa<DbgInfoIntrinsic>(Intr) ||
918 Intr->getIntrinsicID() == Intrinsic::assume)
919 continue;
920 }
Hans Wennborg19c0be92017-03-01 17:15:08 +0000921 if (Call->mayHaveSideEffects())
922 break;
Matt Arsenault6ad97732016-08-04 20:52:57 +0000923
924 if (Call->isConvergent())
925 break;
926
Sebastian Pop41774802016-07-15 13:45:20 +0000927 CI.insert(Call, VN);
Sebastian Pop55c30072016-07-27 05:48:12 +0000928 } else if (HoistingGeps || !isa<GetElementPtrInst>(&I1))
Sebastian Pop41774802016-07-15 13:45:20 +0000929 // Do not hoist scalars past calls that may write to memory because
930 // that could result in spills later. geps are handled separately.
931 // TODO: We can relax this for targets like AArch64 as they have more
932 // registers than X86.
933 II.insert(&I1, VN);
934 }
935 }
936
937 HoistingPointList HPL;
938 computeInsertionPoints(II.getVNTable(), HPL, InsKind::Scalar);
939 computeInsertionPoints(LI.getVNTable(), HPL, InsKind::Load);
940 computeInsertionPoints(SI.getVNTable(), HPL, InsKind::Store);
941 computeInsertionPoints(CI.getScalarVNTable(), HPL, InsKind::Scalar);
942 computeInsertionPoints(CI.getLoadVNTable(), HPL, InsKind::Load);
943 computeInsertionPoints(CI.getStoreVNTable(), HPL, InsKind::Store);
944 return hoist(HPL);
945 }
Sebastian Pop41774802016-07-15 13:45:20 +0000946};
947
948class GVNHoistLegacyPass : public FunctionPass {
949public:
950 static char ID;
951
952 GVNHoistLegacyPass() : FunctionPass(ID) {
953 initializeGVNHoistLegacyPassPass(*PassRegistry::getPassRegistry());
954 }
955
956 bool runOnFunction(Function &F) override {
Paul Robinson2d23c022016-07-19 22:57:14 +0000957 if (skipFunction(F))
958 return false;
Sebastian Pop41774802016-07-15 13:45:20 +0000959 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
960 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
961 auto &MD = getAnalysis<MemoryDependenceWrapperPass>().getMemDep();
Daniel Berlinea02eee2016-08-23 05:42:41 +0000962 auto &MSSA = getAnalysis<MemorySSAWrapperPass>().getMSSA();
Sebastian Pop41774802016-07-15 13:45:20 +0000963
Hans Wennborg19c0be92017-03-01 17:15:08 +0000964 GVNHoist G(&DT, &AA, &MD, &MSSA);
Sebastian Pop41774802016-07-15 13:45:20 +0000965 return G.run(F);
966 }
967
968 void getAnalysisUsage(AnalysisUsage &AU) const override {
969 AU.addRequired<DominatorTreeWrapperPass>();
970 AU.addRequired<AAResultsWrapperPass>();
971 AU.addRequired<MemoryDependenceWrapperPass>();
Daniel Berlinea02eee2016-08-23 05:42:41 +0000972 AU.addRequired<MemorySSAWrapperPass>();
Sebastian Pop41774802016-07-15 13:45:20 +0000973 AU.addPreserved<DominatorTreeWrapperPass>();
Daniel Berlinea02eee2016-08-23 05:42:41 +0000974 AU.addPreserved<MemorySSAWrapperPass>();
Sebastian Pop41774802016-07-15 13:45:20 +0000975 }
976};
977} // namespace
978
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000979PreservedAnalyses GVNHoistPass::run(Function &F, FunctionAnalysisManager &AM) {
Sebastian Pop41774802016-07-15 13:45:20 +0000980 DominatorTree &DT = AM.getResult<DominatorTreeAnalysis>(F);
981 AliasAnalysis &AA = AM.getResult<AAManager>(F);
982 MemoryDependenceResults &MD = AM.getResult<MemoryDependenceAnalysis>(F);
Daniel Berlinea02eee2016-08-23 05:42:41 +0000983 MemorySSA &MSSA = AM.getResult<MemorySSAAnalysis>(F).getMSSA();
Hans Wennborg19c0be92017-03-01 17:15:08 +0000984 GVNHoist G(&DT, &AA, &MD, &MSSA);
Sebastian Pop41774802016-07-15 13:45:20 +0000985 if (!G.run(F))
986 return PreservedAnalyses::all();
987
988 PreservedAnalyses PA;
989 PA.preserve<DominatorTreeAnalysis>();
Daniel Berlinea02eee2016-08-23 05:42:41 +0000990 PA.preserve<MemorySSAAnalysis>();
Sebastian Pop41774802016-07-15 13:45:20 +0000991 return PA;
992}
993
994char GVNHoistLegacyPass::ID = 0;
995INITIALIZE_PASS_BEGIN(GVNHoistLegacyPass, "gvn-hoist",
996 "Early GVN Hoisting of Expressions", false, false)
997INITIALIZE_PASS_DEPENDENCY(MemoryDependenceWrapperPass)
Daniel Berlinea02eee2016-08-23 05:42:41 +0000998INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
Sebastian Pop41774802016-07-15 13:45:20 +0000999INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
1000INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
1001INITIALIZE_PASS_END(GVNHoistLegacyPass, "gvn-hoist",
1002 "Early GVN Hoisting of Expressions", false, false)
1003
1004FunctionPass *llvm::createGVNHoistPass() { return new GVNHoistLegacyPass(); }