blob: 845e27c5383213ed825e6e6d9e0c2f446cca89aa [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.
Geoff Berry635e5052017-04-10 20:45:17 +000020//
21// TODO: Hoist from >2 successors. Currently GVNHoist will not hoist stores
22// in this case because it works on two instructions at a time.
23// entry:
24// switch i32 %c1, label %exit1 [
25// i32 0, label %sw0
26// i32 1, label %sw1
27// ]
28//
29// sw0:
30// store i32 1, i32* @G
31// br label %exit
32//
33// sw1:
34// store i32 1, i32* @G
35// br label %exit
36//
37// exit1:
38// store i32 1, i32* @G
39// ret void
40// exit:
41// ret void
Sebastian Pop41774802016-07-15 13:45:20 +000042//===----------------------------------------------------------------------===//
43
44#include "llvm/ADT/DenseMap.h"
45#include "llvm/ADT/SmallPtrSet.h"
46#include "llvm/ADT/Statistic.h"
Nikolai Bozhenov9e4a1c32017-04-18 13:25:49 +000047#include "llvm/Analysis/GlobalsModRef.h"
Daniel Berlin554dcd82017-04-11 20:06:36 +000048#include "llvm/Analysis/MemorySSA.h"
49#include "llvm/Analysis/MemorySSAUpdater.h"
Sebastian Pop41774802016-07-15 13:45:20 +000050#include "llvm/Analysis/ValueTracking.h"
51#include "llvm/Transforms/Scalar.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000052#include "llvm/Transforms/Scalar/GVN.h"
David Majnemer68623a02016-07-25 02:21:25 +000053#include "llvm/Transforms/Utils/Local.h"
Sebastian Pop41774802016-07-15 13:45:20 +000054
55using namespace llvm;
56
57#define DEBUG_TYPE "gvn-hoist"
58
59STATISTIC(NumHoisted, "Number of instructions hoisted");
60STATISTIC(NumRemoved, "Number of instructions removed");
61STATISTIC(NumLoadsHoisted, "Number of loads hoisted");
62STATISTIC(NumLoadsRemoved, "Number of loads removed");
63STATISTIC(NumStoresHoisted, "Number of stores hoisted");
64STATISTIC(NumStoresRemoved, "Number of stores removed");
65STATISTIC(NumCallsHoisted, "Number of calls hoisted");
66STATISTIC(NumCallsRemoved, "Number of calls removed");
67
68static cl::opt<int>
69 MaxHoistedThreshold("gvn-max-hoisted", cl::Hidden, cl::init(-1),
70 cl::desc("Max number of instructions to hoist "
71 "(default unlimited = -1)"));
72static cl::opt<int> MaxNumberOfBBSInPath(
73 "gvn-hoist-max-bbs", cl::Hidden, cl::init(4),
74 cl::desc("Max number of basic blocks on the path between "
75 "hoisting locations (default = 4, unlimited = -1)"));
76
Sebastian Pop38422b12016-07-26 00:15:08 +000077static cl::opt<int> MaxDepthInBB(
78 "gvn-hoist-max-depth", cl::Hidden, cl::init(100),
79 cl::desc("Hoist instructions from the beginning of the BB up to the "
80 "maximum specified depth (default = 100, unlimited = -1)"));
81
Sebastian Pop5ba9f242016-10-13 01:39:10 +000082static cl::opt<int>
83 MaxChainLength("gvn-hoist-max-chain-length", cl::Hidden, cl::init(10),
84 cl::desc("Maximum length of dependent chains to hoist "
85 "(default = 10, unlimited = -1)"));
Sebastian Pop2aadad72016-08-03 20:54:38 +000086
Daniel Berlindcb004f2017-03-02 23:06:46 +000087namespace llvm {
Sebastian Pop41774802016-07-15 13:45:20 +000088
89// Provides a sorting function based on the execution order of two instructions.
90struct SortByDFSIn {
91private:
Sebastian Pop91d4a302016-07-26 00:15:10 +000092 DenseMap<const Value *, unsigned> &DFSNumber;
Sebastian Pop41774802016-07-15 13:45:20 +000093
94public:
Sebastian Pop91d4a302016-07-26 00:15:10 +000095 SortByDFSIn(DenseMap<const Value *, unsigned> &D) : DFSNumber(D) {}
Sebastian Pop41774802016-07-15 13:45:20 +000096
97 // Returns true when A executes before B.
98 bool operator()(const Instruction *A, const Instruction *B) const {
Sebastian Pop4ba7c882016-08-03 20:54:36 +000099 const BasicBlock *BA = A->getParent();
100 const BasicBlock *BB = B->getParent();
101 unsigned ADFS, BDFS;
102 if (BA == BB) {
103 ADFS = DFSNumber.lookup(A);
104 BDFS = DFSNumber.lookup(B);
105 } else {
106 ADFS = DFSNumber.lookup(BA);
107 BDFS = DFSNumber.lookup(BB);
108 }
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000109 assert(ADFS && BDFS);
Sebastian Pop91d4a302016-07-26 00:15:10 +0000110 return ADFS < BDFS;
Sebastian Pop41774802016-07-15 13:45:20 +0000111 }
112};
113
David Majnemer04c7c222016-07-18 06:11:37 +0000114// A map from a pair of VNs to all the instructions with those VNs.
115typedef DenseMap<std::pair<unsigned, unsigned>, SmallVector<Instruction *, 4>>
116 VNtoInsns;
117// An invalid value number Used when inserting a single value number into
118// VNtoInsns.
Reid Kleckner3498ad12016-07-18 18:53:50 +0000119enum : unsigned { InvalidVN = ~2U };
Sebastian Pop41774802016-07-15 13:45:20 +0000120
121// Records all scalar instructions candidate for code hoisting.
122class InsnInfo {
123 VNtoInsns VNtoScalars;
124
125public:
126 // Inserts I and its value number in VNtoScalars.
127 void insert(Instruction *I, GVN::ValueTable &VN) {
128 // Scalar instruction.
129 unsigned V = VN.lookupOrAdd(I);
David Majnemer04c7c222016-07-18 06:11:37 +0000130 VNtoScalars[{V, InvalidVN}].push_back(I);
Sebastian Pop41774802016-07-15 13:45:20 +0000131 }
132
133 const VNtoInsns &getVNTable() const { return VNtoScalars; }
134};
135
136// Records all load instructions candidate for code hoisting.
137class LoadInfo {
138 VNtoInsns VNtoLoads;
139
140public:
141 // Insert Load and the value number of its memory address in VNtoLoads.
142 void insert(LoadInst *Load, GVN::ValueTable &VN) {
143 if (Load->isSimple()) {
144 unsigned V = VN.lookupOrAdd(Load->getPointerOperand());
David Majnemer04c7c222016-07-18 06:11:37 +0000145 VNtoLoads[{V, InvalidVN}].push_back(Load);
Sebastian Pop41774802016-07-15 13:45:20 +0000146 }
147 }
148
149 const VNtoInsns &getVNTable() const { return VNtoLoads; }
150};
151
152// Records all store instructions candidate for code hoisting.
153class StoreInfo {
154 VNtoInsns VNtoStores;
155
156public:
157 // Insert the Store and a hash number of the store address and the stored
158 // value in VNtoStores.
159 void insert(StoreInst *Store, GVN::ValueTable &VN) {
160 if (!Store->isSimple())
161 return;
162 // Hash the store address and the stored value.
163 Value *Ptr = Store->getPointerOperand();
164 Value *Val = Store->getValueOperand();
David Majnemer04c7c222016-07-18 06:11:37 +0000165 VNtoStores[{VN.lookupOrAdd(Ptr), VN.lookupOrAdd(Val)}].push_back(Store);
Sebastian Pop41774802016-07-15 13:45:20 +0000166 }
167
168 const VNtoInsns &getVNTable() const { return VNtoStores; }
169};
170
171// Records all call instructions candidate for code hoisting.
172class CallInfo {
173 VNtoInsns VNtoCallsScalars;
174 VNtoInsns VNtoCallsLoads;
175 VNtoInsns VNtoCallsStores;
176
177public:
178 // Insert Call and its value numbering in one of the VNtoCalls* containers.
179 void insert(CallInst *Call, GVN::ValueTable &VN) {
180 // A call that doesNotAccessMemory is handled as a Scalar,
181 // onlyReadsMemory will be handled as a Load instruction,
182 // all other calls will be handled as stores.
183 unsigned V = VN.lookupOrAdd(Call);
David Majnemer04c7c222016-07-18 06:11:37 +0000184 auto Entry = std::make_pair(V, InvalidVN);
Sebastian Pop41774802016-07-15 13:45:20 +0000185
186 if (Call->doesNotAccessMemory())
David Majnemer04c7c222016-07-18 06:11:37 +0000187 VNtoCallsScalars[Entry].push_back(Call);
Sebastian Pop41774802016-07-15 13:45:20 +0000188 else if (Call->onlyReadsMemory())
David Majnemer04c7c222016-07-18 06:11:37 +0000189 VNtoCallsLoads[Entry].push_back(Call);
Sebastian Pop41774802016-07-15 13:45:20 +0000190 else
David Majnemer04c7c222016-07-18 06:11:37 +0000191 VNtoCallsStores[Entry].push_back(Call);
Sebastian Pop41774802016-07-15 13:45:20 +0000192 }
193
194 const VNtoInsns &getScalarVNTable() const { return VNtoCallsScalars; }
195
196 const VNtoInsns &getLoadVNTable() const { return VNtoCallsLoads; }
197
198 const VNtoInsns &getStoreVNTable() const { return VNtoCallsStores; }
199};
200
201typedef DenseMap<const BasicBlock *, bool> BBSideEffectsSet;
202typedef SmallVector<Instruction *, 4> SmallVecInsn;
203typedef SmallVectorImpl<Instruction *> SmallVecImplInsn;
204
David Majnemer68623a02016-07-25 02:21:25 +0000205static void combineKnownMetadata(Instruction *ReplInst, Instruction *I) {
206 static const unsigned KnownIDs[] = {
207 LLVMContext::MD_tbaa, LLVMContext::MD_alias_scope,
208 LLVMContext::MD_noalias, LLVMContext::MD_range,
209 LLVMContext::MD_fpmath, LLVMContext::MD_invariant_load,
210 LLVMContext::MD_invariant_group};
211 combineMetadata(ReplInst, I, KnownIDs);
212}
213
Sebastian Pop41774802016-07-15 13:45:20 +0000214// This pass hoists common computations across branches sharing common
215// dominator. The primary goal is to reduce the code size, and in some
216// cases reduce critical path (by exposing more ILP).
217class GVNHoist {
218public:
Daniel Berlinea02eee2016-08-23 05:42:41 +0000219 GVNHoist(DominatorTree *DT, AliasAnalysis *AA, MemoryDependenceResults *MD,
Hans Wennborg19c0be92017-03-01 17:15:08 +0000220 MemorySSA *MSSA)
Daniel Berlin17e8d0e2017-02-22 22:19:55 +0000221 : DT(DT), AA(AA), MD(MD), MSSA(MSSA),
222 MSSAUpdater(make_unique<MemorySSAUpdater>(MSSA)),
Hans Wennborg19c0be92017-03-01 17:15:08 +0000223 HoistingGeps(false),
224 HoistedCtr(0)
225 { }
Aditya Kumar07cb3042016-11-29 14:34:01 +0000226
Daniel Berlin65af45d2016-07-25 17:24:22 +0000227 bool run(Function &F) {
228 VN.setDomTree(DT);
229 VN.setAliasAnalysis(AA);
230 VN.setMemDep(MD);
231 bool Res = false;
Sebastian Pop4ba7c882016-08-03 20:54:36 +0000232 // Perform DFS Numbering of instructions.
233 unsigned BBI = 0;
234 for (const BasicBlock *BB : depth_first(&F.getEntryBlock())) {
235 DFSNumber[BB] = ++BBI;
236 unsigned I = 0;
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000237 for (auto &Inst : *BB)
Sebastian Pop4ba7c882016-08-03 20:54:36 +0000238 DFSNumber[&Inst] = ++I;
239 }
Daniel Berlin65af45d2016-07-25 17:24:22 +0000240
Sebastian Pop2aadad72016-08-03 20:54:38 +0000241 int ChainLength = 0;
242
Daniel Berlin65af45d2016-07-25 17:24:22 +0000243 // FIXME: use lazy evaluation of VN to avoid the fix-point computation.
244 while (1) {
Sebastian Pop2aadad72016-08-03 20:54:38 +0000245 if (MaxChainLength != -1 && ++ChainLength >= MaxChainLength)
246 return Res;
247
Daniel Berlin65af45d2016-07-25 17:24:22 +0000248 auto HoistStat = hoistExpressions(F);
Sebastian Pop5d3822f2016-08-03 20:54:33 +0000249 if (HoistStat.first + HoistStat.second == 0)
Daniel Berlin65af45d2016-07-25 17:24:22 +0000250 return Res;
Sebastian Pop5d3822f2016-08-03 20:54:33 +0000251
252 if (HoistStat.second > 0)
Daniel Berlin65af45d2016-07-25 17:24:22 +0000253 // To address a limitation of the current GVN, we need to rerun the
Sebastian Pop5d3822f2016-08-03 20:54:33 +0000254 // hoisting after we hoisted loads or stores in order to be able to
255 // hoist all scalars dependent on the hoisted ld/st.
Daniel Berlin65af45d2016-07-25 17:24:22 +0000256 VN.clear();
Sebastian Pop5d3822f2016-08-03 20:54:33 +0000257
Daniel Berlin65af45d2016-07-25 17:24:22 +0000258 Res = true;
259 }
260
261 return Res;
262 }
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000263
Daniel Berlin65af45d2016-07-25 17:24:22 +0000264private:
Sebastian Pop41774802016-07-15 13:45:20 +0000265 GVN::ValueTable VN;
266 DominatorTree *DT;
267 AliasAnalysis *AA;
268 MemoryDependenceResults *MD;
Daniel Berlinea02eee2016-08-23 05:42:41 +0000269 MemorySSA *MSSA;
Daniel Berlin17e8d0e2017-02-22 22:19:55 +0000270 std::unique_ptr<MemorySSAUpdater> MSSAUpdater;
Sebastian Pop55c30072016-07-27 05:48:12 +0000271 const bool HoistingGeps;
Sebastian Pop91d4a302016-07-26 00:15:10 +0000272 DenseMap<const Value *, unsigned> DFSNumber;
Sebastian Pop41774802016-07-15 13:45:20 +0000273 BBSideEffectsSet BBSideEffects;
Geoff Berry635e5052017-04-10 20:45:17 +0000274 DenseSet<const BasicBlock*> HoistBarrier;
David Majnemeraa241782016-07-18 00:35:01 +0000275 int HoistedCtr;
276
Sebastian Pop41774802016-07-15 13:45:20 +0000277 enum InsKind { Unknown, Scalar, Load, Store };
278
Sebastian Pop41774802016-07-15 13:45:20 +0000279 // Return true when there are exception handling in BB.
280 bool hasEH(const BasicBlock *BB) {
281 auto It = BBSideEffects.find(BB);
282 if (It != BBSideEffects.end())
283 return It->second;
284
285 if (BB->isEHPad() || BB->hasAddressTaken()) {
286 BBSideEffects[BB] = true;
287 return true;
288 }
289
290 if (BB->getTerminator()->mayThrow()) {
291 BBSideEffects[BB] = true;
292 return true;
293 }
294
295 BBSideEffects[BB] = false;
296 return false;
297 }
298
Sebastian Pop5f0d0e62016-08-25 11:55:47 +0000299 // Return true when a successor of BB dominates A.
300 bool successorDominate(const BasicBlock *BB, const BasicBlock *A) {
301 for (const BasicBlock *Succ : BB->getTerminator()->successors())
302 if (DT->dominates(Succ, A))
303 return true;
Sebastian Pop41774802016-07-15 13:45:20 +0000304
Sebastian Pop5f0d0e62016-08-25 11:55:47 +0000305 return false;
306 }
307
308 // Return true when all paths from HoistBB to the end of the function pass
309 // through one of the blocks in WL.
310 bool hoistingFromAllPaths(const BasicBlock *HoistBB,
311 SmallPtrSetImpl<const BasicBlock *> &WL) {
312
313 // Copy WL as the loop will remove elements from it.
314 SmallPtrSet<const BasicBlock *, 2> WorkList(WL.begin(), WL.end());
315
316 for (auto It = df_begin(HoistBB), E = df_end(HoistBB); It != E;) {
317 // There exists a path from HoistBB to the exit of the function if we are
318 // still iterating in DF traversal and we removed all instructions from
319 // the work list.
320 if (WorkList.empty())
Sebastian Pop41774802016-07-15 13:45:20 +0000321 return false;
322
323 const BasicBlock *BB = *It;
Sebastian Pop5f0d0e62016-08-25 11:55:47 +0000324 if (WorkList.erase(BB)) {
Sebastian Pop41774802016-07-15 13:45:20 +0000325 // Stop DFS traversal when BB is in the work list.
326 It.skipChildren();
327 continue;
328 }
329
Geoff Berry635e5052017-04-10 20:45:17 +0000330 // We reached the leaf Basic Block => not all paths have this instruction.
331 if (!BB->getTerminator()->getNumSuccessors())
Sebastian Pop41774802016-07-15 13:45:20 +0000332 return false;
333
Sebastian Pop5f0d0e62016-08-25 11:55:47 +0000334 // When reaching the back-edge of a loop, there may be a path through the
335 // loop that does not pass through B or C before exiting the loop.
336 if (successorDominate(BB, HoistBB))
337 return false;
338
Sebastian Pop41774802016-07-15 13:45:20 +0000339 // Increment DFS traversal when not skipping children.
340 ++It;
341 }
342
343 return true;
344 }
345
346 /* Return true when I1 appears before I2 in the instructions of BB. */
Sebastian Pop91d4a302016-07-26 00:15:10 +0000347 bool firstInBB(const Instruction *I1, const Instruction *I2) {
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000348 assert(I1->getParent() == I2->getParent());
Sebastian Pop91d4a302016-07-26 00:15:10 +0000349 unsigned I1DFS = DFSNumber.lookup(I1);
350 unsigned I2DFS = DFSNumber.lookup(I2);
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000351 assert(I1DFS && I2DFS);
Sebastian Pop91d4a302016-07-26 00:15:10 +0000352 return I1DFS < I2DFS;
Daniel Berlin40765a62016-07-25 18:19:49 +0000353 }
Sebastian Pop91d4a302016-07-26 00:15:10 +0000354
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000355 // Return true when there are memory uses of Def in BB.
356 bool hasMemoryUse(const Instruction *NewPt, MemoryDef *Def,
357 const BasicBlock *BB) {
358 const MemorySSA::AccessList *Acc = MSSA->getBlockAccesses(BB);
359 if (!Acc)
360 return false;
361
362 Instruction *OldPt = Def->getMemoryInst();
Sebastian Pop41774802016-07-15 13:45:20 +0000363 const BasicBlock *OldBB = OldPt->getParent();
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000364 const BasicBlock *NewBB = NewPt->getParent();
365 bool ReachedNewPt = false;
Sebastian Pop41774802016-07-15 13:45:20 +0000366
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000367 for (const MemoryAccess &MA : *Acc)
368 if (const MemoryUse *MU = dyn_cast<MemoryUse>(&MA)) {
369 Instruction *Insn = MU->getMemoryInst();
Sebastian Pop1531f302016-09-22 17:22:58 +0000370
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000371 // Do not check whether MU aliases Def when MU occurs after OldPt.
372 if (BB == OldBB && firstInBB(OldPt, Insn))
373 break;
374
375 // Do not check whether MU aliases Def when MU occurs before NewPt.
376 if (BB == NewBB) {
377 if (!ReachedNewPt) {
378 if (firstInBB(Insn, NewPt))
379 continue;
380 ReachedNewPt = true;
381 }
Sebastian Pop41774802016-07-15 13:45:20 +0000382 }
Daniel Berlindcb004f2017-03-02 23:06:46 +0000383 if (MemorySSAUtil::defClobbersUseOrDef(Def, MU, *AA))
Hans Wennborgc7957ef2016-09-22 21:20:53 +0000384 return true;
385 }
Sebastian Pop8e6e3312016-09-22 15:33:51 +0000386
Sebastian Pop41774802016-07-15 13:45:20 +0000387 return false;
388 }
389
Davide Italiano32504cf2017-09-05 20:49:41 +0000390 bool hasEHhelper(const BasicBlock *BB, const BasicBlock *SrcBB,
391 int &NBBsOnAllPaths) {
392 // Stop walk once the limit is reached.
393 if (NBBsOnAllPaths == 0)
394 return true;
395
396 // Impossible to hoist with exceptions on the path.
397 if (hasEH(BB))
398 return true;
399
400 // No such instruction after HoistBarrier in a basic block was
401 // selected for hoisting so instructions selected within basic block with
402 // a hoist barrier can be hoisted.
403 if ((BB != SrcBB) && HoistBarrier.count(BB))
404 return true;
405
406 return false;
407 }
408
Sebastian Pop41774802016-07-15 13:45:20 +0000409 // Return true when there are exception handling or loads of memory Def
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000410 // between Def and NewPt. This function is only called for stores: Def is
411 // the MemoryDef of the store to be hoisted.
Sebastian Pop41774802016-07-15 13:45:20 +0000412
413 // Decrement by 1 NBBsOnAllPaths for each block between HoistPt and BB, and
414 // return true when the counter NBBsOnAllPaths reaces 0, except when it is
415 // initialized to -1 which is unlimited.
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000416 bool hasEHOrLoadsOnPath(const Instruction *NewPt, MemoryDef *Def,
417 int &NBBsOnAllPaths) {
Sebastian Pop41774802016-07-15 13:45:20 +0000418 const BasicBlock *NewBB = NewPt->getParent();
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000419 const BasicBlock *OldBB = Def->getBlock();
Sebastian Pop41774802016-07-15 13:45:20 +0000420 assert(DT->dominates(NewBB, OldBB) && "invalid path");
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000421 assert(DT->dominates(Def->getDefiningAccess()->getBlock(), NewBB) &&
Sebastian Pop41774802016-07-15 13:45:20 +0000422 "def does not dominate new hoisting point");
423
424 // Walk all basic blocks reachable in depth-first iteration on the inverse
425 // CFG from OldBB to NewBB. These blocks are all the blocks that may be
426 // executed between the execution of NewBB and OldBB. Hoisting an expression
427 // from OldBB into NewBB has to be safe on all execution paths.
428 for (auto I = idf_begin(OldBB), E = idf_end(OldBB); I != E;) {
Geoff Berry635e5052017-04-10 20:45:17 +0000429 const BasicBlock *BB = *I;
430 if (BB == NewBB) {
Sebastian Pop41774802016-07-15 13:45:20 +0000431 // Stop traversal when reaching HoistPt.
432 I.skipChildren();
433 continue;
434 }
435
Davide Italiano32504cf2017-09-05 20:49:41 +0000436 if (hasEHhelper(BB, OldBB, NBBsOnAllPaths))
Sebastian Pop41774802016-07-15 13:45:20 +0000437 return true;
438
439 // Check that we do not move a store past loads.
Geoff Berry635e5052017-04-10 20:45:17 +0000440 if (hasMemoryUse(NewPt, Def, BB))
Sebastian Pop41774802016-07-15 13:45:20 +0000441 return true;
442
Sebastian Pop41774802016-07-15 13:45:20 +0000443 // -1 is unlimited number of blocks on all paths.
444 if (NBBsOnAllPaths != -1)
445 --NBBsOnAllPaths;
446
447 ++I;
448 }
449
450 return false;
451 }
452
453 // Return true when there are exception handling between HoistPt and BB.
454 // Decrement by 1 NBBsOnAllPaths for each block between HoistPt and BB, and
455 // return true when the counter NBBsOnAllPaths reaches 0, except when it is
456 // initialized to -1 which is unlimited.
Geoff Berry635e5052017-04-10 20:45:17 +0000457 bool hasEHOnPath(const BasicBlock *HoistPt, const BasicBlock *SrcBB,
Sebastian Pop41774802016-07-15 13:45:20 +0000458 int &NBBsOnAllPaths) {
Geoff Berry635e5052017-04-10 20:45:17 +0000459 assert(DT->dominates(HoistPt, SrcBB) && "Invalid path");
Sebastian Pop41774802016-07-15 13:45:20 +0000460
461 // Walk all basic blocks reachable in depth-first iteration on
462 // the inverse CFG from BBInsn to NewHoistPt. These blocks are all the
463 // blocks that may be executed between the execution of NewHoistPt and
464 // BBInsn. Hoisting an expression from BBInsn into NewHoistPt has to be safe
465 // on all execution paths.
Geoff Berry635e5052017-04-10 20:45:17 +0000466 for (auto I = idf_begin(SrcBB), E = idf_end(SrcBB); I != E;) {
467 const BasicBlock *BB = *I;
468 if (BB == HoistPt) {
Sebastian Pop41774802016-07-15 13:45:20 +0000469 // Stop traversal when reaching NewHoistPt.
470 I.skipChildren();
471 continue;
472 }
473
Davide Italiano32504cf2017-09-05 20:49:41 +0000474 if (hasEHhelper(BB, SrcBB, NBBsOnAllPaths))
Aditya Kumar314ebe02016-11-29 14:36:27 +0000475 return true;
476
Sebastian Pop41774802016-07-15 13:45:20 +0000477 // -1 is unlimited number of blocks on all paths.
478 if (NBBsOnAllPaths != -1)
479 --NBBsOnAllPaths;
480
481 ++I;
482 }
483
484 return false;
485 }
486
487 // Return true when it is safe to hoist a memory load or store U from OldPt
488 // to NewPt.
489 bool safeToHoistLdSt(const Instruction *NewPt, const Instruction *OldPt,
490 MemoryUseOrDef *U, InsKind K, int &NBBsOnAllPaths) {
491
492 // In place hoisting is safe.
493 if (NewPt == OldPt)
494 return true;
495
496 const BasicBlock *NewBB = NewPt->getParent();
497 const BasicBlock *OldBB = OldPt->getParent();
498 const BasicBlock *UBB = U->getBlock();
499
500 // Check for dependences on the Memory SSA.
501 MemoryAccess *D = U->getDefiningAccess();
502 BasicBlock *DBB = D->getBlock();
503 if (DT->properlyDominates(NewBB, DBB))
504 // Cannot move the load or store to NewBB above its definition in DBB.
505 return false;
506
507 if (NewBB == DBB && !MSSA->isLiveOnEntryDef(D))
David Majnemer4c66a712016-07-18 00:34:58 +0000508 if (auto *UD = dyn_cast<MemoryUseOrDef>(D))
Sebastian Pop91d4a302016-07-26 00:15:10 +0000509 if (firstInBB(NewPt, UD->getMemoryInst()))
Sebastian Pop41774802016-07-15 13:45:20 +0000510 // Cannot move the load or store to NewPt above its definition in D.
511 return false;
512
513 // Check for unsafe hoistings due to side effects.
514 if (K == InsKind::Store) {
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000515 if (hasEHOrLoadsOnPath(NewPt, dyn_cast<MemoryDef>(U), NBBsOnAllPaths))
Sebastian Pop41774802016-07-15 13:45:20 +0000516 return false;
517 } else if (hasEHOnPath(NewBB, OldBB, NBBsOnAllPaths))
518 return false;
519
520 if (UBB == NewBB) {
521 if (DT->properlyDominates(DBB, NewBB))
522 return true;
523 assert(UBB == DBB);
524 assert(MSSA->locallyDominates(D, U));
525 }
526
527 // No side effects: it is safe to hoist.
528 return true;
529 }
530
Sebastian Pop5f0d0e62016-08-25 11:55:47 +0000531 // Return true when it is safe to hoist scalar instructions from all blocks in
532 // WL to HoistBB.
533 bool safeToHoistScalar(const BasicBlock *HoistBB,
534 SmallPtrSetImpl<const BasicBlock *> &WL,
535 int &NBBsOnAllPaths) {
Aditya Kumar07cb3042016-11-29 14:34:01 +0000536 // Check that the hoisted expression is needed on all paths.
537 if (!hoistingFromAllPaths(HoistBB, WL))
Sebastian Pop41774802016-07-15 13:45:20 +0000538 return false;
539
Sebastian Pop5f0d0e62016-08-25 11:55:47 +0000540 for (const BasicBlock *BB : WL)
541 if (hasEHOnPath(HoistBB, BB, NBBsOnAllPaths))
542 return false;
Sebastian Pop41774802016-07-15 13:45:20 +0000543
Sebastian Pop41774802016-07-15 13:45:20 +0000544 return true;
545 }
546
547 // Each element of a hoisting list contains the basic block where to hoist and
548 // a list of instructions to be hoisted.
549 typedef std::pair<BasicBlock *, SmallVecInsn> HoistingPointInfo;
550 typedef SmallVector<HoistingPointInfo, 4> HoistingPointList;
551
552 // Partition InstructionsToHoist into a set of candidates which can share a
553 // common hoisting point. The partitions are collected in HPL. IsScalar is
554 // true when the instructions in InstructionsToHoist are scalars. IsLoad is
555 // true when the InstructionsToHoist are loads, false when they are stores.
556 void partitionCandidates(SmallVecImplInsn &InstructionsToHoist,
557 HoistingPointList &HPL, InsKind K) {
558 // No need to sort for two instructions.
559 if (InstructionsToHoist.size() > 2) {
560 SortByDFSIn Pred(DFSNumber);
561 std::sort(InstructionsToHoist.begin(), InstructionsToHoist.end(), Pred);
562 }
563
Aditya Kumar314ebe02016-11-29 14:36:27 +0000564 int NumBBsOnAllPaths = MaxNumberOfBBSInPath;
Sebastian Pop41774802016-07-15 13:45:20 +0000565
566 SmallVecImplInsn::iterator II = InstructionsToHoist.begin();
567 SmallVecImplInsn::iterator Start = II;
568 Instruction *HoistPt = *II;
569 BasicBlock *HoistBB = HoistPt->getParent();
570 MemoryUseOrDef *UD;
571 if (K != InsKind::Scalar)
George Burgess IV66837ab2016-11-01 21:17:46 +0000572 UD = MSSA->getMemoryAccess(HoistPt);
Sebastian Pop41774802016-07-15 13:45:20 +0000573
574 for (++II; II != InstructionsToHoist.end(); ++II) {
575 Instruction *Insn = *II;
576 BasicBlock *BB = Insn->getParent();
577 BasicBlock *NewHoistBB;
578 Instruction *NewHoistPt;
579
Aditya Kumar314ebe02016-11-29 14:36:27 +0000580 if (BB == HoistBB) { // Both are in the same Basic Block.
Sebastian Pop41774802016-07-15 13:45:20 +0000581 NewHoistBB = HoistBB;
Sebastian Pop91d4a302016-07-26 00:15:10 +0000582 NewHoistPt = firstInBB(Insn, HoistPt) ? Insn : HoistPt;
Sebastian Pop41774802016-07-15 13:45:20 +0000583 } else {
Aditya Kumar314ebe02016-11-29 14:36:27 +0000584 // If the hoisting point contains one of the instructions,
585 // then hoist there, otherwise hoist before the terminator.
Sebastian Pop41774802016-07-15 13:45:20 +0000586 NewHoistBB = DT->findNearestCommonDominator(HoistBB, BB);
587 if (NewHoistBB == BB)
588 NewHoistPt = Insn;
589 else if (NewHoistBB == HoistBB)
590 NewHoistPt = HoistPt;
591 else
592 NewHoistPt = NewHoistBB->getTerminator();
593 }
594
Sebastian Pop5f0d0e62016-08-25 11:55:47 +0000595 SmallPtrSet<const BasicBlock *, 2> WL;
596 WL.insert(HoistBB);
597 WL.insert(BB);
598
Sebastian Pop41774802016-07-15 13:45:20 +0000599 if (K == InsKind::Scalar) {
Aditya Kumar314ebe02016-11-29 14:36:27 +0000600 if (safeToHoistScalar(NewHoistBB, WL, NumBBsOnAllPaths)) {
Sebastian Pop41774802016-07-15 13:45:20 +0000601 // Extend HoistPt to NewHoistPt.
602 HoistPt = NewHoistPt;
603 HoistBB = NewHoistBB;
604 continue;
605 }
606 } else {
607 // When NewBB already contains an instruction to be hoisted, the
608 // expression is needed on all paths.
609 // Check that the hoisted expression is needed on all paths: it is
610 // unsafe to hoist loads to a place where there may be a path not
611 // loading from the same address: for instance there may be a branch on
612 // which the address of the load may not be initialized.
613 if ((HoistBB == NewHoistBB || BB == NewHoistBB ||
Sebastian Pop5f0d0e62016-08-25 11:55:47 +0000614 hoistingFromAllPaths(NewHoistBB, WL)) &&
Sebastian Pop41774802016-07-15 13:45:20 +0000615 // Also check that it is safe to move the load or store from HoistPt
616 // to NewHoistPt, and from Insn to NewHoistPt.
Aditya Kumar314ebe02016-11-29 14:36:27 +0000617 safeToHoistLdSt(NewHoistPt, HoistPt, UD, K, NumBBsOnAllPaths) &&
George Burgess IV66837ab2016-11-01 21:17:46 +0000618 safeToHoistLdSt(NewHoistPt, Insn, MSSA->getMemoryAccess(Insn),
Aditya Kumar314ebe02016-11-29 14:36:27 +0000619 K, NumBBsOnAllPaths)) {
Sebastian Pop41774802016-07-15 13:45:20 +0000620 // Extend HoistPt to NewHoistPt.
621 HoistPt = NewHoistPt;
622 HoistBB = NewHoistBB;
623 continue;
624 }
625 }
626
627 // At this point it is not safe to extend the current hoisting to
628 // NewHoistPt: save the hoisting list so far.
629 if (std::distance(Start, II) > 1)
David Majnemer4c66a712016-07-18 00:34:58 +0000630 HPL.push_back({HoistBB, SmallVecInsn(Start, II)});
Sebastian Pop41774802016-07-15 13:45:20 +0000631
632 // Start over from BB.
633 Start = II;
634 if (K != InsKind::Scalar)
George Burgess IV66837ab2016-11-01 21:17:46 +0000635 UD = MSSA->getMemoryAccess(*Start);
Sebastian Pop41774802016-07-15 13:45:20 +0000636 HoistPt = Insn;
637 HoistBB = BB;
Aditya Kumar314ebe02016-11-29 14:36:27 +0000638 NumBBsOnAllPaths = MaxNumberOfBBSInPath;
Sebastian Pop41774802016-07-15 13:45:20 +0000639 }
640
641 // Save the last partition.
642 if (std::distance(Start, II) > 1)
David Majnemer4c66a712016-07-18 00:34:58 +0000643 HPL.push_back({HoistBB, SmallVecInsn(Start, II)});
Sebastian Pop41774802016-07-15 13:45:20 +0000644 }
645
646 // Initialize HPL from Map.
647 void computeInsertionPoints(const VNtoInsns &Map, HoistingPointList &HPL,
648 InsKind K) {
David Majnemer4c66a712016-07-18 00:34:58 +0000649 for (const auto &Entry : Map) {
Sebastian Pop41774802016-07-15 13:45:20 +0000650 if (MaxHoistedThreshold != -1 && ++HoistedCtr > MaxHoistedThreshold)
651 return;
652
David Majnemer4c66a712016-07-18 00:34:58 +0000653 const SmallVecInsn &V = Entry.second;
Sebastian Pop41774802016-07-15 13:45:20 +0000654 if (V.size() < 2)
655 continue;
656
657 // Compute the insertion point and the list of expressions to be hoisted.
658 SmallVecInsn InstructionsToHoist;
659 for (auto I : V)
Geoff Berry635e5052017-04-10 20:45:17 +0000660 // We don't need to check for hoist-barriers here because if
661 // I->getParent() is a barrier then I precedes the barrier.
Sebastian Pop41774802016-07-15 13:45:20 +0000662 if (!hasEH(I->getParent()))
663 InstructionsToHoist.push_back(I);
664
David Majnemer4c66a712016-07-18 00:34:58 +0000665 if (!InstructionsToHoist.empty())
Sebastian Pop41774802016-07-15 13:45:20 +0000666 partitionCandidates(InstructionsToHoist, HPL, K);
667 }
668 }
669
670 // Return true when all operands of Instr are available at insertion point
671 // HoistPt. When limiting the number of hoisted expressions, one could hoist
672 // a load without hoisting its access function. So before hoisting any
673 // expression, make sure that all its operands are available at insert point.
674 bool allOperandsAvailable(const Instruction *I,
675 const BasicBlock *HoistPt) const {
David Majnemer4c66a712016-07-18 00:34:58 +0000676 for (const Use &Op : I->operands())
677 if (const auto *Inst = dyn_cast<Instruction>(&Op))
678 if (!DT->dominates(Inst->getParent(), HoistPt))
679 return false;
Sebastian Pop41774802016-07-15 13:45:20 +0000680
681 return true;
682 }
683
Sebastian Pop55c30072016-07-27 05:48:12 +0000684 // Same as allOperandsAvailable with recursive check for GEP operands.
685 bool allGepOperandsAvailable(const Instruction *I,
686 const BasicBlock *HoistPt) const {
687 for (const Use &Op : I->operands())
688 if (const auto *Inst = dyn_cast<Instruction>(&Op))
689 if (!DT->dominates(Inst->getParent(), HoistPt)) {
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000690 if (const GetElementPtrInst *GepOp =
691 dyn_cast<GetElementPtrInst>(Inst)) {
Sebastian Pop55c30072016-07-27 05:48:12 +0000692 if (!allGepOperandsAvailable(GepOp, HoistPt))
693 return false;
694 // Gep is available if all operands of GepOp are available.
695 } else {
696 // Gep is not available if it has operands other than GEPs that are
697 // defined in blocks not dominating HoistPt.
698 return false;
699 }
700 }
701 return true;
702 }
703
704 // Make all operands of the GEP available.
705 void makeGepsAvailable(Instruction *Repl, BasicBlock *HoistPt,
706 const SmallVecInsn &InstructionsToHoist,
707 Instruction *Gep) const {
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000708 assert(allGepOperandsAvailable(Gep, HoistPt) &&
709 "GEP operands not available");
Sebastian Pop55c30072016-07-27 05:48:12 +0000710
711 Instruction *ClonedGep = Gep->clone();
712 for (unsigned i = 0, e = Gep->getNumOperands(); i != e; ++i)
713 if (Instruction *Op = dyn_cast<Instruction>(Gep->getOperand(i))) {
714
715 // Check whether the operand is already available.
716 if (DT->dominates(Op->getParent(), HoistPt))
717 continue;
718
719 // As a GEP can refer to other GEPs, recursively make all the operands
720 // of this GEP available at HoistPt.
721 if (GetElementPtrInst *GepOp = dyn_cast<GetElementPtrInst>(Op))
722 makeGepsAvailable(ClonedGep, HoistPt, InstructionsToHoist, GepOp);
723 }
724
725 // Copy Gep and replace its uses in Repl with ClonedGep.
726 ClonedGep->insertBefore(HoistPt->getTerminator());
727
728 // Conservatively discard any optimization hints, they may differ on the
729 // other paths.
730 ClonedGep->dropUnknownNonDebugMetadata();
731
732 // If we have optimization hints which agree with each other along different
733 // paths, preserve them.
734 for (const Instruction *OtherInst : InstructionsToHoist) {
735 const GetElementPtrInst *OtherGep;
736 if (auto *OtherLd = dyn_cast<LoadInst>(OtherInst))
737 OtherGep = cast<GetElementPtrInst>(OtherLd->getPointerOperand());
738 else
739 OtherGep = cast<GetElementPtrInst>(
740 cast<StoreInst>(OtherInst)->getPointerOperand());
Peter Collingbourne8f1dd5c2016-09-07 23:39:04 +0000741 ClonedGep->andIRFlags(OtherGep);
Sebastian Pop55c30072016-07-27 05:48:12 +0000742 }
743
744 // Replace uses of Gep with ClonedGep in Repl.
745 Repl->replaceUsesOfWith(Gep, ClonedGep);
746 }
747
748 // In the case Repl is a load or a store, we make all their GEPs
749 // available: GEPs are not hoisted by default to avoid the address
750 // computations to be hoisted without the associated load or store.
751 bool makeGepOperandsAvailable(Instruction *Repl, BasicBlock *HoistPt,
752 const SmallVecInsn &InstructionsToHoist) const {
Sebastian Pop41774802016-07-15 13:45:20 +0000753 // Check whether the GEP of a ld/st can be synthesized at HoistPt.
David Majnemerbd210122016-07-20 21:05:01 +0000754 GetElementPtrInst *Gep = nullptr;
Sebastian Pop41774802016-07-15 13:45:20 +0000755 Instruction *Val = nullptr;
Sebastian Pop55c30072016-07-27 05:48:12 +0000756 if (auto *Ld = dyn_cast<LoadInst>(Repl)) {
David Majnemerbd210122016-07-20 21:05:01 +0000757 Gep = dyn_cast<GetElementPtrInst>(Ld->getPointerOperand());
Sebastian Pop55c30072016-07-27 05:48:12 +0000758 } else if (auto *St = dyn_cast<StoreInst>(Repl)) {
David Majnemerbd210122016-07-20 21:05:01 +0000759 Gep = dyn_cast<GetElementPtrInst>(St->getPointerOperand());
Sebastian Pop41774802016-07-15 13:45:20 +0000760 Val = dyn_cast<Instruction>(St->getValueOperand());
Sebastian Pop31fd5062016-07-21 23:22:10 +0000761 // Check that the stored value is available.
Sebastian Pop0e2cec02016-07-22 00:07:01 +0000762 if (Val) {
763 if (isa<GetElementPtrInst>(Val)) {
764 // Check whether we can compute the GEP at HoistPt.
Sebastian Pop55c30072016-07-27 05:48:12 +0000765 if (!allGepOperandsAvailable(Val, HoistPt))
Sebastian Pop0e2cec02016-07-22 00:07:01 +0000766 return false;
767 } else if (!DT->dominates(Val->getParent(), HoistPt))
768 return false;
769 }
Sebastian Pop41774802016-07-15 13:45:20 +0000770 }
771
Sebastian Pop41774802016-07-15 13:45:20 +0000772 // Check whether we can compute the Gep at HoistPt.
Sebastian Pop55c30072016-07-27 05:48:12 +0000773 if (!Gep || !allGepOperandsAvailable(Gep, HoistPt))
Sebastian Pop41774802016-07-15 13:45:20 +0000774 return false;
775
Sebastian Pop55c30072016-07-27 05:48:12 +0000776 makeGepsAvailable(Repl, HoistPt, InstructionsToHoist, Gep);
Sebastian Pop41774802016-07-15 13:45:20 +0000777
Sebastian Pop55c30072016-07-27 05:48:12 +0000778 if (Val && isa<GetElementPtrInst>(Val))
779 makeGepsAvailable(Repl, HoistPt, InstructionsToHoist, Val);
Sebastian Pop41774802016-07-15 13:45:20 +0000780
781 return true;
782 }
783
784 std::pair<unsigned, unsigned> hoist(HoistingPointList &HPL) {
785 unsigned NI = 0, NL = 0, NS = 0, NC = 0, NR = 0;
786 for (const HoistingPointInfo &HP : HPL) {
787 // Find out whether we already have one of the instructions in HoistPt,
788 // in which case we do not have to move it.
789 BasicBlock *HoistPt = HP.first;
790 const SmallVecInsn &InstructionsToHoist = HP.second;
791 Instruction *Repl = nullptr;
792 for (Instruction *I : InstructionsToHoist)
Sebastian Pop586d3ea2016-07-27 05:13:52 +0000793 if (I->getParent() == HoistPt)
Sebastian Pop41774802016-07-15 13:45:20 +0000794 // If there are two instructions in HoistPt to be hoisted in place:
795 // update Repl to be the first one, such that we can rename the uses
796 // of the second based on the first.
Sebastian Pop586d3ea2016-07-27 05:13:52 +0000797 if (!Repl || firstInBB(I, Repl))
798 Repl = I;
Sebastian Pop41774802016-07-15 13:45:20 +0000799
Daniel Berlinf75fd1b2016-08-11 20:32:43 +0000800 // Keep track of whether we moved the instruction so we know whether we
801 // should move the MemoryAccess.
802 bool MoveAccess = true;
Sebastian Pop41774802016-07-15 13:45:20 +0000803 if (Repl) {
804 // Repl is already in HoistPt: it remains in place.
805 assert(allOperandsAvailable(Repl, HoistPt) &&
806 "instruction depends on operands that are not available");
Daniel Berlinf75fd1b2016-08-11 20:32:43 +0000807 MoveAccess = false;
Sebastian Pop41774802016-07-15 13:45:20 +0000808 } else {
809 // When we do not find Repl in HoistPt, select the first in the list
810 // and move it to HoistPt.
811 Repl = InstructionsToHoist.front();
812
813 // We can move Repl in HoistPt only when all operands are available.
814 // The order in which hoistings are done may influence the availability
815 // of operands.
Sebastian Pop429740a2016-08-04 23:49:05 +0000816 if (!allOperandsAvailable(Repl, HoistPt)) {
817
818 // When HoistingGeps there is nothing more we can do to make the
819 // operands available: just continue.
820 if (HoistingGeps)
821 continue;
822
823 // When not HoistingGeps we need to copy the GEPs.
824 if (!makeGepOperandsAvailable(Repl, HoistPt, InstructionsToHoist))
825 continue;
826 }
Sebastian Pop55c30072016-07-27 05:48:12 +0000827
Sebastian Pop5d3822f2016-08-03 20:54:33 +0000828 // Move the instruction at the end of HoistPt.
Sebastian Pop4ba7c882016-08-03 20:54:36 +0000829 Instruction *Last = HoistPt->getTerminator();
Eli Friedmanc6885fc2016-12-07 19:55:59 +0000830 MD->removeInstruction(Repl);
Sebastian Pop4ba7c882016-08-03 20:54:36 +0000831 Repl->moveBefore(Last);
832
833 DFSNumber[Repl] = DFSNumber[Last]++;
Sebastian Pop41774802016-07-15 13:45:20 +0000834 }
835
Daniel Berlinf75fd1b2016-08-11 20:32:43 +0000836 MemoryAccess *NewMemAcc = MSSA->getMemoryAccess(Repl);
837
838 if (MoveAccess) {
839 if (MemoryUseOrDef *OldMemAcc =
840 dyn_cast_or_null<MemoryUseOrDef>(NewMemAcc)) {
Sebastian Pop5d3822f2016-08-03 20:54:33 +0000841 // The definition of this ld/st will not change: ld/st hoisting is
842 // legal when the ld/st is not moved past its current definition.
843 MemoryAccess *Def = OldMemAcc->getDefiningAccess();
Daniel Berlinf75fd1b2016-08-11 20:32:43 +0000844 NewMemAcc =
Daniel Berlin17e8d0e2017-02-22 22:19:55 +0000845 MSSAUpdater->createMemoryAccessInBB(Repl, Def, HoistPt, MemorySSA::End);
Sebastian Pop5d3822f2016-08-03 20:54:33 +0000846 OldMemAcc->replaceAllUsesWith(NewMemAcc);
Daniel Berlin17e8d0e2017-02-22 22:19:55 +0000847 MSSAUpdater->removeMemoryAccess(OldMemAcc);
Sebastian Pop5d3822f2016-08-03 20:54:33 +0000848 }
849 }
850
Sebastian Pop41774802016-07-15 13:45:20 +0000851 if (isa<LoadInst>(Repl))
852 ++NL;
853 else if (isa<StoreInst>(Repl))
854 ++NS;
855 else if (isa<CallInst>(Repl))
856 ++NC;
857 else // Scalar
858 ++NI;
859
860 // Remove and rename all other instructions.
861 for (Instruction *I : InstructionsToHoist)
862 if (I != Repl) {
863 ++NR;
David Majnemer47285692016-07-25 02:21:23 +0000864 if (auto *ReplacementLoad = dyn_cast<LoadInst>(Repl)) {
865 ReplacementLoad->setAlignment(
866 std::min(ReplacementLoad->getAlignment(),
867 cast<LoadInst>(I)->getAlignment()));
Sebastian Pop41774802016-07-15 13:45:20 +0000868 ++NumLoadsRemoved;
David Majnemer47285692016-07-25 02:21:23 +0000869 } else if (auto *ReplacementStore = dyn_cast<StoreInst>(Repl)) {
870 ReplacementStore->setAlignment(
871 std::min(ReplacementStore->getAlignment(),
872 cast<StoreInst>(I)->getAlignment()));
Sebastian Pop41774802016-07-15 13:45:20 +0000873 ++NumStoresRemoved;
David Majnemer47285692016-07-25 02:21:23 +0000874 } else if (auto *ReplacementAlloca = dyn_cast<AllocaInst>(Repl)) {
875 ReplacementAlloca->setAlignment(
876 std::max(ReplacementAlloca->getAlignment(),
877 cast<AllocaInst>(I)->getAlignment()));
878 } else if (isa<CallInst>(Repl)) {
Sebastian Pop41774802016-07-15 13:45:20 +0000879 ++NumCallsRemoved;
David Majnemer47285692016-07-25 02:21:23 +0000880 }
Sebastian Pop5d3822f2016-08-03 20:54:33 +0000881
882 if (NewMemAcc) {
883 // Update the uses of the old MSSA access with NewMemAcc.
884 MemoryAccess *OldMA = MSSA->getMemoryAccess(I);
885 OldMA->replaceAllUsesWith(NewMemAcc);
Daniel Berlin17e8d0e2017-02-22 22:19:55 +0000886 MSSAUpdater->removeMemoryAccess(OldMA);
Sebastian Pop5d3822f2016-08-03 20:54:33 +0000887 }
888
Peter Collingbourne8f1dd5c2016-09-07 23:39:04 +0000889 Repl->andIRFlags(I);
David Majnemer68623a02016-07-25 02:21:25 +0000890 combineKnownMetadata(Repl, I);
Sebastian Pop41774802016-07-15 13:45:20 +0000891 I->replaceAllUsesWith(Repl);
Sebastian Pop46601992016-08-27 02:48:41 +0000892 // Also invalidate the Alias Analysis cache.
893 MD->removeInstruction(I);
Sebastian Pop41774802016-07-15 13:45:20 +0000894 I->eraseFromParent();
895 }
Sebastian Pop5d3822f2016-08-03 20:54:33 +0000896
897 // Remove MemorySSA phi nodes with the same arguments.
898 if (NewMemAcc) {
899 SmallPtrSet<MemoryPhi *, 4> UsePhis;
900 for (User *U : NewMemAcc->users())
901 if (MemoryPhi *Phi = dyn_cast<MemoryPhi>(U))
902 UsePhis.insert(Phi);
903
904 for (auto *Phi : UsePhis) {
905 auto In = Phi->incoming_values();
David Majnemer0a16c222016-08-11 21:15:00 +0000906 if (all_of(In, [&](Use &U) { return U == NewMemAcc; })) {
Sebastian Pop5d3822f2016-08-03 20:54:33 +0000907 Phi->replaceAllUsesWith(NewMemAcc);
Daniel Berlin17e8d0e2017-02-22 22:19:55 +0000908 MSSAUpdater->removeMemoryAccess(Phi);
Sebastian Pop5d3822f2016-08-03 20:54:33 +0000909 }
910 }
911 }
Sebastian Pop41774802016-07-15 13:45:20 +0000912 }
913
914 NumHoisted += NL + NS + NC + NI;
915 NumRemoved += NR;
916 NumLoadsHoisted += NL;
917 NumStoresHoisted += NS;
918 NumCallsHoisted += NC;
919 return {NI, NL + NC + NS};
920 }
921
922 // Hoist all expressions. Returns Number of scalars hoisted
923 // and number of non-scalars hoisted.
924 std::pair<unsigned, unsigned> hoistExpressions(Function &F) {
925 InsnInfo II;
926 LoadInfo LI;
927 StoreInfo SI;
928 CallInfo CI;
929 for (BasicBlock *BB : depth_first(&F.getEntryBlock())) {
Sebastian Pop38422b12016-07-26 00:15:08 +0000930 int InstructionNb = 0;
Sebastian Pop41774802016-07-15 13:45:20 +0000931 for (Instruction &I1 : *BB) {
Geoff Berry635e5052017-04-10 20:45:17 +0000932 // If I1 cannot guarantee progress, subsequent instructions
933 // in BB cannot be hoisted anyways.
934 if (!isGuaranteedToTransferExecutionToSuccessor(&I1)) {
935 HoistBarrier.insert(BB);
936 break;
937 }
Sebastian Pop38422b12016-07-26 00:15:08 +0000938 // Only hoist the first instructions in BB up to MaxDepthInBB. Hoisting
939 // deeper may increase the register pressure and compilation time.
940 if (MaxDepthInBB != -1 && InstructionNb++ >= MaxDepthInBB)
941 break;
942
Sebastian Pop440f15b2016-09-22 14:45:40 +0000943 // Do not value number terminator instructions.
Sebastian Pop5d68aa72016-09-22 15:08:09 +0000944 if (isa<TerminatorInst>(&I1))
Sebastian Pop440f15b2016-09-22 14:45:40 +0000945 break;
946
David Majnemer4c66a712016-07-18 00:34:58 +0000947 if (auto *Load = dyn_cast<LoadInst>(&I1))
Sebastian Pop41774802016-07-15 13:45:20 +0000948 LI.insert(Load, VN);
David Majnemer4c66a712016-07-18 00:34:58 +0000949 else if (auto *Store = dyn_cast<StoreInst>(&I1))
Sebastian Pop41774802016-07-15 13:45:20 +0000950 SI.insert(Store, VN);
David Majnemer4c66a712016-07-18 00:34:58 +0000951 else if (auto *Call = dyn_cast<CallInst>(&I1)) {
952 if (auto *Intr = dyn_cast<IntrinsicInst>(Call)) {
Sebastian Pop41774802016-07-15 13:45:20 +0000953 if (isa<DbgInfoIntrinsic>(Intr) ||
954 Intr->getIntrinsicID() == Intrinsic::assume)
955 continue;
956 }
Hans Wennborg19c0be92017-03-01 17:15:08 +0000957 if (Call->mayHaveSideEffects())
958 break;
Matt Arsenault6ad97732016-08-04 20:52:57 +0000959
960 if (Call->isConvergent())
961 break;
962
Sebastian Pop41774802016-07-15 13:45:20 +0000963 CI.insert(Call, VN);
Sebastian Pop55c30072016-07-27 05:48:12 +0000964 } else if (HoistingGeps || !isa<GetElementPtrInst>(&I1))
Sebastian Pop41774802016-07-15 13:45:20 +0000965 // Do not hoist scalars past calls that may write to memory because
966 // that could result in spills later. geps are handled separately.
967 // TODO: We can relax this for targets like AArch64 as they have more
968 // registers than X86.
969 II.insert(&I1, VN);
970 }
971 }
972
973 HoistingPointList HPL;
974 computeInsertionPoints(II.getVNTable(), HPL, InsKind::Scalar);
975 computeInsertionPoints(LI.getVNTable(), HPL, InsKind::Load);
976 computeInsertionPoints(SI.getVNTable(), HPL, InsKind::Store);
977 computeInsertionPoints(CI.getScalarVNTable(), HPL, InsKind::Scalar);
978 computeInsertionPoints(CI.getLoadVNTable(), HPL, InsKind::Load);
979 computeInsertionPoints(CI.getStoreVNTable(), HPL, InsKind::Store);
980 return hoist(HPL);
981 }
Sebastian Pop41774802016-07-15 13:45:20 +0000982};
983
984class GVNHoistLegacyPass : public FunctionPass {
985public:
986 static char ID;
987
988 GVNHoistLegacyPass() : FunctionPass(ID) {
989 initializeGVNHoistLegacyPassPass(*PassRegistry::getPassRegistry());
990 }
991
992 bool runOnFunction(Function &F) override {
Paul Robinson2d23c022016-07-19 22:57:14 +0000993 if (skipFunction(F))
994 return false;
Sebastian Pop41774802016-07-15 13:45:20 +0000995 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
996 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
997 auto &MD = getAnalysis<MemoryDependenceWrapperPass>().getMemDep();
Daniel Berlinea02eee2016-08-23 05:42:41 +0000998 auto &MSSA = getAnalysis<MemorySSAWrapperPass>().getMSSA();
Sebastian Pop41774802016-07-15 13:45:20 +0000999
Hans Wennborg19c0be92017-03-01 17:15:08 +00001000 GVNHoist G(&DT, &AA, &MD, &MSSA);
Sebastian Pop41774802016-07-15 13:45:20 +00001001 return G.run(F);
1002 }
1003
1004 void getAnalysisUsage(AnalysisUsage &AU) const override {
1005 AU.addRequired<DominatorTreeWrapperPass>();
1006 AU.addRequired<AAResultsWrapperPass>();
1007 AU.addRequired<MemoryDependenceWrapperPass>();
Daniel Berlinea02eee2016-08-23 05:42:41 +00001008 AU.addRequired<MemorySSAWrapperPass>();
Sebastian Pop41774802016-07-15 13:45:20 +00001009 AU.addPreserved<DominatorTreeWrapperPass>();
Daniel Berlinea02eee2016-08-23 05:42:41 +00001010 AU.addPreserved<MemorySSAWrapperPass>();
Nikolai Bozhenov9e4a1c32017-04-18 13:25:49 +00001011 AU.addPreserved<GlobalsAAWrapperPass>();
Sebastian Pop41774802016-07-15 13:45:20 +00001012 }
1013};
1014} // namespace
1015
Sebastian Pop5ba9f242016-10-13 01:39:10 +00001016PreservedAnalyses GVNHoistPass::run(Function &F, FunctionAnalysisManager &AM) {
Sebastian Pop41774802016-07-15 13:45:20 +00001017 DominatorTree &DT = AM.getResult<DominatorTreeAnalysis>(F);
1018 AliasAnalysis &AA = AM.getResult<AAManager>(F);
1019 MemoryDependenceResults &MD = AM.getResult<MemoryDependenceAnalysis>(F);
Daniel Berlinea02eee2016-08-23 05:42:41 +00001020 MemorySSA &MSSA = AM.getResult<MemorySSAAnalysis>(F).getMSSA();
Hans Wennborg19c0be92017-03-01 17:15:08 +00001021 GVNHoist G(&DT, &AA, &MD, &MSSA);
Sebastian Pop41774802016-07-15 13:45:20 +00001022 if (!G.run(F))
1023 return PreservedAnalyses::all();
1024
1025 PreservedAnalyses PA;
1026 PA.preserve<DominatorTreeAnalysis>();
Daniel Berlinea02eee2016-08-23 05:42:41 +00001027 PA.preserve<MemorySSAAnalysis>();
Nikolai Bozhenov9e4a1c32017-04-18 13:25:49 +00001028 PA.preserve<GlobalsAA>();
Sebastian Pop41774802016-07-15 13:45:20 +00001029 return PA;
1030}
1031
1032char GVNHoistLegacyPass::ID = 0;
1033INITIALIZE_PASS_BEGIN(GVNHoistLegacyPass, "gvn-hoist",
1034 "Early GVN Hoisting of Expressions", false, false)
1035INITIALIZE_PASS_DEPENDENCY(MemoryDependenceWrapperPass)
Daniel Berlinea02eee2016-08-23 05:42:41 +00001036INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
Sebastian Pop41774802016-07-15 13:45:20 +00001037INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
1038INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
1039INITIALIZE_PASS_END(GVNHoistLegacyPass, "gvn-hoist",
1040 "Early GVN Hoisting of Expressions", false, false)
1041
1042FunctionPass *llvm::createGVNHoistPass() { return new GVNHoistLegacyPass(); }