blob: 5b2f1b6277f40b7f200413f0edfbd2911990e932 [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"
30
31using namespace llvm;
32
33#define DEBUG_TYPE "gvn-hoist"
34
35STATISTIC(NumHoisted, "Number of instructions hoisted");
36STATISTIC(NumRemoved, "Number of instructions removed");
37STATISTIC(NumLoadsHoisted, "Number of loads hoisted");
38STATISTIC(NumLoadsRemoved, "Number of loads removed");
39STATISTIC(NumStoresHoisted, "Number of stores hoisted");
40STATISTIC(NumStoresRemoved, "Number of stores removed");
41STATISTIC(NumCallsHoisted, "Number of calls hoisted");
42STATISTIC(NumCallsRemoved, "Number of calls removed");
43
44static cl::opt<int>
45 MaxHoistedThreshold("gvn-max-hoisted", cl::Hidden, cl::init(-1),
46 cl::desc("Max number of instructions to hoist "
47 "(default unlimited = -1)"));
48static cl::opt<int> MaxNumberOfBBSInPath(
49 "gvn-hoist-max-bbs", cl::Hidden, cl::init(4),
50 cl::desc("Max number of basic blocks on the path between "
51 "hoisting locations (default = 4, unlimited = -1)"));
52
Sebastian Pop38422b12016-07-26 00:15:08 +000053static cl::opt<int> MaxDepthInBB(
54 "gvn-hoist-max-depth", cl::Hidden, cl::init(100),
55 cl::desc("Hoist instructions from the beginning of the BB up to the "
56 "maximum specified depth (default = 100, unlimited = -1)"));
57
Sebastian Pop5ba9f242016-10-13 01:39:10 +000058static cl::opt<int>
59 MaxChainLength("gvn-hoist-max-chain-length", cl::Hidden, cl::init(10),
60 cl::desc("Maximum length of dependent chains to hoist "
61 "(default = 10, unlimited = -1)"));
Sebastian Pop2aadad72016-08-03 20:54:38 +000062
Sebastian Pop41774802016-07-15 13:45:20 +000063namespace {
64
65// Provides a sorting function based on the execution order of two instructions.
66struct SortByDFSIn {
67private:
Sebastian Pop91d4a302016-07-26 00:15:10 +000068 DenseMap<const Value *, unsigned> &DFSNumber;
Sebastian Pop41774802016-07-15 13:45:20 +000069
70public:
Sebastian Pop91d4a302016-07-26 00:15:10 +000071 SortByDFSIn(DenseMap<const Value *, unsigned> &D) : DFSNumber(D) {}
Sebastian Pop41774802016-07-15 13:45:20 +000072
73 // Returns true when A executes before B.
74 bool operator()(const Instruction *A, const Instruction *B) const {
75 // FIXME: libc++ has a std::sort() algorithm that will call the compare
76 // function on the same element. Once PR20837 is fixed and some more years
77 // pass by and all the buildbots have moved to a corrected std::sort(),
78 // enable the following assert:
79 //
80 // assert(A != B);
81
Sebastian Pop4ba7c882016-08-03 20:54:36 +000082 const BasicBlock *BA = A->getParent();
83 const BasicBlock *BB = B->getParent();
84 unsigned ADFS, BDFS;
85 if (BA == BB) {
86 ADFS = DFSNumber.lookup(A);
87 BDFS = DFSNumber.lookup(B);
88 } else {
89 ADFS = DFSNumber.lookup(BA);
90 BDFS = DFSNumber.lookup(BB);
91 }
Sebastian Pop5ba9f242016-10-13 01:39:10 +000092 assert(ADFS && BDFS);
Sebastian Pop91d4a302016-07-26 00:15:10 +000093 return ADFS < BDFS;
Sebastian Pop41774802016-07-15 13:45:20 +000094 }
95};
96
David Majnemer04c7c222016-07-18 06:11:37 +000097// A map from a pair of VNs to all the instructions with those VNs.
98typedef DenseMap<std::pair<unsigned, unsigned>, SmallVector<Instruction *, 4>>
99 VNtoInsns;
100// An invalid value number Used when inserting a single value number into
101// VNtoInsns.
Reid Kleckner3498ad12016-07-18 18:53:50 +0000102enum : unsigned { InvalidVN = ~2U };
Sebastian Pop41774802016-07-15 13:45:20 +0000103
104// Records all scalar instructions candidate for code hoisting.
105class InsnInfo {
106 VNtoInsns VNtoScalars;
107
108public:
109 // Inserts I and its value number in VNtoScalars.
110 void insert(Instruction *I, GVN::ValueTable &VN) {
111 // Scalar instruction.
112 unsigned V = VN.lookupOrAdd(I);
David Majnemer04c7c222016-07-18 06:11:37 +0000113 VNtoScalars[{V, InvalidVN}].push_back(I);
Sebastian Pop41774802016-07-15 13:45:20 +0000114 }
115
116 const VNtoInsns &getVNTable() const { return VNtoScalars; }
117};
118
119// Records all load instructions candidate for code hoisting.
120class LoadInfo {
121 VNtoInsns VNtoLoads;
122
123public:
124 // Insert Load and the value number of its memory address in VNtoLoads.
125 void insert(LoadInst *Load, GVN::ValueTable &VN) {
126 if (Load->isSimple()) {
127 unsigned V = VN.lookupOrAdd(Load->getPointerOperand());
David Majnemer04c7c222016-07-18 06:11:37 +0000128 VNtoLoads[{V, InvalidVN}].push_back(Load);
Sebastian Pop41774802016-07-15 13:45:20 +0000129 }
130 }
131
132 const VNtoInsns &getVNTable() const { return VNtoLoads; }
133};
134
135// Records all store instructions candidate for code hoisting.
136class StoreInfo {
137 VNtoInsns VNtoStores;
138
139public:
140 // Insert the Store and a hash number of the store address and the stored
141 // value in VNtoStores.
142 void insert(StoreInst *Store, GVN::ValueTable &VN) {
143 if (!Store->isSimple())
144 return;
145 // Hash the store address and the stored value.
146 Value *Ptr = Store->getPointerOperand();
147 Value *Val = Store->getValueOperand();
David Majnemer04c7c222016-07-18 06:11:37 +0000148 VNtoStores[{VN.lookupOrAdd(Ptr), VN.lookupOrAdd(Val)}].push_back(Store);
Sebastian Pop41774802016-07-15 13:45:20 +0000149 }
150
151 const VNtoInsns &getVNTable() const { return VNtoStores; }
152};
153
154// Records all call instructions candidate for code hoisting.
155class CallInfo {
156 VNtoInsns VNtoCallsScalars;
157 VNtoInsns VNtoCallsLoads;
158 VNtoInsns VNtoCallsStores;
159
160public:
161 // Insert Call and its value numbering in one of the VNtoCalls* containers.
162 void insert(CallInst *Call, GVN::ValueTable &VN) {
163 // A call that doesNotAccessMemory is handled as a Scalar,
164 // onlyReadsMemory will be handled as a Load instruction,
165 // all other calls will be handled as stores.
166 unsigned V = VN.lookupOrAdd(Call);
David Majnemer04c7c222016-07-18 06:11:37 +0000167 auto Entry = std::make_pair(V, InvalidVN);
Sebastian Pop41774802016-07-15 13:45:20 +0000168
169 if (Call->doesNotAccessMemory())
David Majnemer04c7c222016-07-18 06:11:37 +0000170 VNtoCallsScalars[Entry].push_back(Call);
Sebastian Pop41774802016-07-15 13:45:20 +0000171 else if (Call->onlyReadsMemory())
David Majnemer04c7c222016-07-18 06:11:37 +0000172 VNtoCallsLoads[Entry].push_back(Call);
Sebastian Pop41774802016-07-15 13:45:20 +0000173 else
David Majnemer04c7c222016-07-18 06:11:37 +0000174 VNtoCallsStores[Entry].push_back(Call);
Sebastian Pop41774802016-07-15 13:45:20 +0000175 }
176
177 const VNtoInsns &getScalarVNTable() const { return VNtoCallsScalars; }
178
179 const VNtoInsns &getLoadVNTable() const { return VNtoCallsLoads; }
180
181 const VNtoInsns &getStoreVNTable() const { return VNtoCallsStores; }
182};
183
184typedef DenseMap<const BasicBlock *, bool> BBSideEffectsSet;
185typedef SmallVector<Instruction *, 4> SmallVecInsn;
186typedef SmallVectorImpl<Instruction *> SmallVecImplInsn;
187
David Majnemer68623a02016-07-25 02:21:25 +0000188static void combineKnownMetadata(Instruction *ReplInst, Instruction *I) {
189 static const unsigned KnownIDs[] = {
190 LLVMContext::MD_tbaa, LLVMContext::MD_alias_scope,
191 LLVMContext::MD_noalias, LLVMContext::MD_range,
192 LLVMContext::MD_fpmath, LLVMContext::MD_invariant_load,
193 LLVMContext::MD_invariant_group};
194 combineMetadata(ReplInst, I, KnownIDs);
195}
196
Sebastian Pop41774802016-07-15 13:45:20 +0000197// This pass hoists common computations across branches sharing common
198// dominator. The primary goal is to reduce the code size, and in some
199// cases reduce critical path (by exposing more ILP).
200class GVNHoist {
201public:
Daniel Berlinea02eee2016-08-23 05:42:41 +0000202 GVNHoist(DominatorTree *DT, AliasAnalysis *AA, MemoryDependenceResults *MD,
203 MemorySSA *MSSA, bool OptForMinSize)
204 : DT(DT), AA(AA), MD(MD), MSSA(MSSA), OptForMinSize(OptForMinSize),
Aditya Kumar07cb3042016-11-29 14:34:01 +0000205 HoistingGeps(OptForMinSize), HoistedCtr(0) {
206 // Hoist as far as possible when optimizing for code-size.
207 if (OptForMinSize)
208 MaxNumberOfBBSInPath = -1;
209 }
210
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;
Sebastian Pop41774802016-07-15 13:45:20 +0000254 const bool OptForMinSize;
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 }
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000366 if (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
399 // Impossible to hoist with exceptions on the path.
400 if (hasEH(*I))
401 return true;
402
403 // Check that we do not move a store past loads.
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000404 if (hasMemoryUse(NewPt, Def, *I))
Sebastian Pop41774802016-07-15 13:45:20 +0000405 return true;
406
407 // Stop walk once the limit is reached.
408 if (NBBsOnAllPaths == 0)
409 return true;
410
411 // -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
441 // Impossible to hoist with exceptions on the path.
442 if (hasEH(*I))
443 return true;
444
445 // Stop walk once the limit is reached.
446 if (NBBsOnAllPaths == 0)
447 return true;
448
449 // -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 // Enable scalar hoisting at -Oz as it is safe to hoist scalars to a place
509 // where they are partially needed.
510 if (OptForMinSize)
511 return true;
512
513 // Check that the hoisted expression is needed on all paths.
514 if (!hoistingFromAllPaths(HoistBB, WL))
Sebastian Pop41774802016-07-15 13:45:20 +0000515 return false;
516
Sebastian Pop5f0d0e62016-08-25 11:55:47 +0000517 for (const BasicBlock *BB : WL)
518 if (hasEHOnPath(HoistBB, BB, NBBsOnAllPaths))
519 return false;
Sebastian Pop41774802016-07-15 13:45:20 +0000520
Sebastian Pop41774802016-07-15 13:45:20 +0000521 return true;
522 }
523
524 // Each element of a hoisting list contains the basic block where to hoist and
525 // a list of instructions to be hoisted.
526 typedef std::pair<BasicBlock *, SmallVecInsn> HoistingPointInfo;
527 typedef SmallVector<HoistingPointInfo, 4> HoistingPointList;
528
529 // Partition InstructionsToHoist into a set of candidates which can share a
530 // common hoisting point. The partitions are collected in HPL. IsScalar is
531 // true when the instructions in InstructionsToHoist are scalars. IsLoad is
532 // true when the InstructionsToHoist are loads, false when they are stores.
533 void partitionCandidates(SmallVecImplInsn &InstructionsToHoist,
534 HoistingPointList &HPL, InsKind K) {
535 // No need to sort for two instructions.
536 if (InstructionsToHoist.size() > 2) {
537 SortByDFSIn Pred(DFSNumber);
538 std::sort(InstructionsToHoist.begin(), InstructionsToHoist.end(), Pred);
539 }
540
541 int NBBsOnAllPaths = MaxNumberOfBBSInPath;
542
543 SmallVecImplInsn::iterator II = InstructionsToHoist.begin();
544 SmallVecImplInsn::iterator Start = II;
545 Instruction *HoistPt = *II;
546 BasicBlock *HoistBB = HoistPt->getParent();
547 MemoryUseOrDef *UD;
548 if (K != InsKind::Scalar)
George Burgess IV66837ab2016-11-01 21:17:46 +0000549 UD = MSSA->getMemoryAccess(HoistPt);
Sebastian Pop41774802016-07-15 13:45:20 +0000550
551 for (++II; II != InstructionsToHoist.end(); ++II) {
552 Instruction *Insn = *II;
553 BasicBlock *BB = Insn->getParent();
554 BasicBlock *NewHoistBB;
555 Instruction *NewHoistPt;
556
557 if (BB == HoistBB) {
558 NewHoistBB = HoistBB;
Sebastian Pop91d4a302016-07-26 00:15:10 +0000559 NewHoistPt = firstInBB(Insn, HoistPt) ? Insn : HoistPt;
Sebastian Pop41774802016-07-15 13:45:20 +0000560 } else {
561 NewHoistBB = DT->findNearestCommonDominator(HoistBB, BB);
562 if (NewHoistBB == BB)
563 NewHoistPt = Insn;
564 else if (NewHoistBB == HoistBB)
565 NewHoistPt = HoistPt;
566 else
567 NewHoistPt = NewHoistBB->getTerminator();
568 }
569
Sebastian Pop5f0d0e62016-08-25 11:55:47 +0000570 SmallPtrSet<const BasicBlock *, 2> WL;
571 WL.insert(HoistBB);
572 WL.insert(BB);
573
Sebastian Pop41774802016-07-15 13:45:20 +0000574 if (K == InsKind::Scalar) {
Sebastian Pop5f0d0e62016-08-25 11:55:47 +0000575 if (safeToHoistScalar(NewHoistBB, WL, NBBsOnAllPaths)) {
Sebastian Pop41774802016-07-15 13:45:20 +0000576 // Extend HoistPt to NewHoistPt.
577 HoistPt = NewHoistPt;
578 HoistBB = NewHoistBB;
579 continue;
580 }
581 } else {
582 // When NewBB already contains an instruction to be hoisted, the
583 // expression is needed on all paths.
584 // Check that the hoisted expression is needed on all paths: it is
585 // unsafe to hoist loads to a place where there may be a path not
586 // loading from the same address: for instance there may be a branch on
587 // which the address of the load may not be initialized.
588 if ((HoistBB == NewHoistBB || BB == NewHoistBB ||
Sebastian Pop5f0d0e62016-08-25 11:55:47 +0000589 hoistingFromAllPaths(NewHoistBB, WL)) &&
Sebastian Pop41774802016-07-15 13:45:20 +0000590 // Also check that it is safe to move the load or store from HoistPt
591 // to NewHoistPt, and from Insn to NewHoistPt.
592 safeToHoistLdSt(NewHoistPt, HoistPt, UD, K, NBBsOnAllPaths) &&
George Burgess IV66837ab2016-11-01 21:17:46 +0000593 safeToHoistLdSt(NewHoistPt, Insn, MSSA->getMemoryAccess(Insn),
Sebastian Pop41774802016-07-15 13:45:20 +0000594 K, NBBsOnAllPaths)) {
595 // Extend HoistPt to NewHoistPt.
596 HoistPt = NewHoistPt;
597 HoistBB = NewHoistBB;
598 continue;
599 }
600 }
601
602 // At this point it is not safe to extend the current hoisting to
603 // NewHoistPt: save the hoisting list so far.
604 if (std::distance(Start, II) > 1)
David Majnemer4c66a712016-07-18 00:34:58 +0000605 HPL.push_back({HoistBB, SmallVecInsn(Start, II)});
Sebastian Pop41774802016-07-15 13:45:20 +0000606
607 // Start over from BB.
608 Start = II;
609 if (K != InsKind::Scalar)
George Burgess IV66837ab2016-11-01 21:17:46 +0000610 UD = MSSA->getMemoryAccess(*Start);
Sebastian Pop41774802016-07-15 13:45:20 +0000611 HoistPt = Insn;
612 HoistBB = BB;
613 NBBsOnAllPaths = MaxNumberOfBBSInPath;
614 }
615
616 // Save the last partition.
617 if (std::distance(Start, II) > 1)
David Majnemer4c66a712016-07-18 00:34:58 +0000618 HPL.push_back({HoistBB, SmallVecInsn(Start, II)});
Sebastian Pop41774802016-07-15 13:45:20 +0000619 }
620
621 // Initialize HPL from Map.
622 void computeInsertionPoints(const VNtoInsns &Map, HoistingPointList &HPL,
623 InsKind K) {
David Majnemer4c66a712016-07-18 00:34:58 +0000624 for (const auto &Entry : Map) {
Sebastian Pop41774802016-07-15 13:45:20 +0000625 if (MaxHoistedThreshold != -1 && ++HoistedCtr > MaxHoistedThreshold)
626 return;
627
David Majnemer4c66a712016-07-18 00:34:58 +0000628 const SmallVecInsn &V = Entry.second;
Sebastian Pop41774802016-07-15 13:45:20 +0000629 if (V.size() < 2)
630 continue;
631
632 // Compute the insertion point and the list of expressions to be hoisted.
633 SmallVecInsn InstructionsToHoist;
634 for (auto I : V)
635 if (!hasEH(I->getParent()))
636 InstructionsToHoist.push_back(I);
637
David Majnemer4c66a712016-07-18 00:34:58 +0000638 if (!InstructionsToHoist.empty())
Sebastian Pop41774802016-07-15 13:45:20 +0000639 partitionCandidates(InstructionsToHoist, HPL, K);
640 }
641 }
642
643 // Return true when all operands of Instr are available at insertion point
644 // HoistPt. When limiting the number of hoisted expressions, one could hoist
645 // a load without hoisting its access function. So before hoisting any
646 // expression, make sure that all its operands are available at insert point.
647 bool allOperandsAvailable(const Instruction *I,
648 const BasicBlock *HoistPt) const {
David Majnemer4c66a712016-07-18 00:34:58 +0000649 for (const Use &Op : I->operands())
650 if (const auto *Inst = dyn_cast<Instruction>(&Op))
651 if (!DT->dominates(Inst->getParent(), HoistPt))
652 return false;
Sebastian Pop41774802016-07-15 13:45:20 +0000653
654 return true;
655 }
656
Sebastian Pop55c30072016-07-27 05:48:12 +0000657 // Same as allOperandsAvailable with recursive check for GEP operands.
658 bool allGepOperandsAvailable(const Instruction *I,
659 const BasicBlock *HoistPt) const {
660 for (const Use &Op : I->operands())
661 if (const auto *Inst = dyn_cast<Instruction>(&Op))
662 if (!DT->dominates(Inst->getParent(), HoistPt)) {
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000663 if (const GetElementPtrInst *GepOp =
664 dyn_cast<GetElementPtrInst>(Inst)) {
Sebastian Pop55c30072016-07-27 05:48:12 +0000665 if (!allGepOperandsAvailable(GepOp, HoistPt))
666 return false;
667 // Gep is available if all operands of GepOp are available.
668 } else {
669 // Gep is not available if it has operands other than GEPs that are
670 // defined in blocks not dominating HoistPt.
671 return false;
672 }
673 }
674 return true;
675 }
676
677 // Make all operands of the GEP available.
678 void makeGepsAvailable(Instruction *Repl, BasicBlock *HoistPt,
679 const SmallVecInsn &InstructionsToHoist,
680 Instruction *Gep) const {
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000681 assert(allGepOperandsAvailable(Gep, HoistPt) &&
682 "GEP operands not available");
Sebastian Pop55c30072016-07-27 05:48:12 +0000683
684 Instruction *ClonedGep = Gep->clone();
685 for (unsigned i = 0, e = Gep->getNumOperands(); i != e; ++i)
686 if (Instruction *Op = dyn_cast<Instruction>(Gep->getOperand(i))) {
687
688 // Check whether the operand is already available.
689 if (DT->dominates(Op->getParent(), HoistPt))
690 continue;
691
692 // As a GEP can refer to other GEPs, recursively make all the operands
693 // of this GEP available at HoistPt.
694 if (GetElementPtrInst *GepOp = dyn_cast<GetElementPtrInst>(Op))
695 makeGepsAvailable(ClonedGep, HoistPt, InstructionsToHoist, GepOp);
696 }
697
698 // Copy Gep and replace its uses in Repl with ClonedGep.
699 ClonedGep->insertBefore(HoistPt->getTerminator());
700
701 // Conservatively discard any optimization hints, they may differ on the
702 // other paths.
703 ClonedGep->dropUnknownNonDebugMetadata();
704
705 // If we have optimization hints which agree with each other along different
706 // paths, preserve them.
707 for (const Instruction *OtherInst : InstructionsToHoist) {
708 const GetElementPtrInst *OtherGep;
709 if (auto *OtherLd = dyn_cast<LoadInst>(OtherInst))
710 OtherGep = cast<GetElementPtrInst>(OtherLd->getPointerOperand());
711 else
712 OtherGep = cast<GetElementPtrInst>(
713 cast<StoreInst>(OtherInst)->getPointerOperand());
Peter Collingbourne8f1dd5c2016-09-07 23:39:04 +0000714 ClonedGep->andIRFlags(OtherGep);
Sebastian Pop55c30072016-07-27 05:48:12 +0000715 }
716
717 // Replace uses of Gep with ClonedGep in Repl.
718 Repl->replaceUsesOfWith(Gep, ClonedGep);
719 }
720
721 // In the case Repl is a load or a store, we make all their GEPs
722 // available: GEPs are not hoisted by default to avoid the address
723 // computations to be hoisted without the associated load or store.
724 bool makeGepOperandsAvailable(Instruction *Repl, BasicBlock *HoistPt,
725 const SmallVecInsn &InstructionsToHoist) const {
Sebastian Pop41774802016-07-15 13:45:20 +0000726 // Check whether the GEP of a ld/st can be synthesized at HoistPt.
David Majnemerbd210122016-07-20 21:05:01 +0000727 GetElementPtrInst *Gep = nullptr;
Sebastian Pop41774802016-07-15 13:45:20 +0000728 Instruction *Val = nullptr;
Sebastian Pop55c30072016-07-27 05:48:12 +0000729 if (auto *Ld = dyn_cast<LoadInst>(Repl)) {
David Majnemerbd210122016-07-20 21:05:01 +0000730 Gep = dyn_cast<GetElementPtrInst>(Ld->getPointerOperand());
Sebastian Pop55c30072016-07-27 05:48:12 +0000731 } else if (auto *St = dyn_cast<StoreInst>(Repl)) {
David Majnemerbd210122016-07-20 21:05:01 +0000732 Gep = dyn_cast<GetElementPtrInst>(St->getPointerOperand());
Sebastian Pop41774802016-07-15 13:45:20 +0000733 Val = dyn_cast<Instruction>(St->getValueOperand());
Sebastian Pop31fd5062016-07-21 23:22:10 +0000734 // Check that the stored value is available.
Sebastian Pop0e2cec02016-07-22 00:07:01 +0000735 if (Val) {
736 if (isa<GetElementPtrInst>(Val)) {
737 // Check whether we can compute the GEP at HoistPt.
Sebastian Pop55c30072016-07-27 05:48:12 +0000738 if (!allGepOperandsAvailable(Val, HoistPt))
Sebastian Pop0e2cec02016-07-22 00:07:01 +0000739 return false;
740 } else if (!DT->dominates(Val->getParent(), HoistPt))
741 return false;
742 }
Sebastian Pop41774802016-07-15 13:45:20 +0000743 }
744
Sebastian Pop41774802016-07-15 13:45:20 +0000745 // Check whether we can compute the Gep at HoistPt.
Sebastian Pop55c30072016-07-27 05:48:12 +0000746 if (!Gep || !allGepOperandsAvailable(Gep, HoistPt))
Sebastian Pop41774802016-07-15 13:45:20 +0000747 return false;
748
Sebastian Pop55c30072016-07-27 05:48:12 +0000749 makeGepsAvailable(Repl, HoistPt, InstructionsToHoist, Gep);
Sebastian Pop41774802016-07-15 13:45:20 +0000750
Sebastian Pop55c30072016-07-27 05:48:12 +0000751 if (Val && isa<GetElementPtrInst>(Val))
752 makeGepsAvailable(Repl, HoistPt, InstructionsToHoist, Val);
Sebastian Pop41774802016-07-15 13:45:20 +0000753
754 return true;
755 }
756
757 std::pair<unsigned, unsigned> hoist(HoistingPointList &HPL) {
758 unsigned NI = 0, NL = 0, NS = 0, NC = 0, NR = 0;
759 for (const HoistingPointInfo &HP : HPL) {
760 // Find out whether we already have one of the instructions in HoistPt,
761 // in which case we do not have to move it.
762 BasicBlock *HoistPt = HP.first;
763 const SmallVecInsn &InstructionsToHoist = HP.second;
764 Instruction *Repl = nullptr;
765 for (Instruction *I : InstructionsToHoist)
Sebastian Pop586d3ea2016-07-27 05:13:52 +0000766 if (I->getParent() == HoistPt)
Sebastian Pop41774802016-07-15 13:45:20 +0000767 // If there are two instructions in HoistPt to be hoisted in place:
768 // update Repl to be the first one, such that we can rename the uses
769 // of the second based on the first.
Sebastian Pop586d3ea2016-07-27 05:13:52 +0000770 if (!Repl || firstInBB(I, Repl))
771 Repl = I;
Sebastian Pop41774802016-07-15 13:45:20 +0000772
Daniel Berlinf75fd1b2016-08-11 20:32:43 +0000773 // Keep track of whether we moved the instruction so we know whether we
774 // should move the MemoryAccess.
775 bool MoveAccess = true;
Sebastian Pop41774802016-07-15 13:45:20 +0000776 if (Repl) {
777 // Repl is already in HoistPt: it remains in place.
778 assert(allOperandsAvailable(Repl, HoistPt) &&
779 "instruction depends on operands that are not available");
Daniel Berlinf75fd1b2016-08-11 20:32:43 +0000780 MoveAccess = false;
Sebastian Pop41774802016-07-15 13:45:20 +0000781 } else {
782 // When we do not find Repl in HoistPt, select the first in the list
783 // and move it to HoistPt.
784 Repl = InstructionsToHoist.front();
785
786 // We can move Repl in HoistPt only when all operands are available.
787 // The order in which hoistings are done may influence the availability
788 // of operands.
Sebastian Pop429740a2016-08-04 23:49:05 +0000789 if (!allOperandsAvailable(Repl, HoistPt)) {
790
791 // When HoistingGeps there is nothing more we can do to make the
792 // operands available: just continue.
793 if (HoistingGeps)
794 continue;
795
796 // When not HoistingGeps we need to copy the GEPs.
797 if (!makeGepOperandsAvailable(Repl, HoistPt, InstructionsToHoist))
798 continue;
799 }
Sebastian Pop55c30072016-07-27 05:48:12 +0000800
Sebastian Pop5d3822f2016-08-03 20:54:33 +0000801 // Move the instruction at the end of HoistPt.
Sebastian Pop4ba7c882016-08-03 20:54:36 +0000802 Instruction *Last = HoistPt->getTerminator();
803 Repl->moveBefore(Last);
804
805 DFSNumber[Repl] = DFSNumber[Last]++;
Sebastian Pop41774802016-07-15 13:45:20 +0000806 }
807
Daniel Berlinf75fd1b2016-08-11 20:32:43 +0000808 MemoryAccess *NewMemAcc = MSSA->getMemoryAccess(Repl);
809
810 if (MoveAccess) {
811 if (MemoryUseOrDef *OldMemAcc =
812 dyn_cast_or_null<MemoryUseOrDef>(NewMemAcc)) {
Sebastian Pop5d3822f2016-08-03 20:54:33 +0000813 // The definition of this ld/st will not change: ld/st hoisting is
814 // legal when the ld/st is not moved past its current definition.
815 MemoryAccess *Def = OldMemAcc->getDefiningAccess();
Daniel Berlinf75fd1b2016-08-11 20:32:43 +0000816 NewMemAcc =
817 MSSA->createMemoryAccessInBB(Repl, Def, HoistPt, MemorySSA::End);
Sebastian Pop5d3822f2016-08-03 20:54:33 +0000818 OldMemAcc->replaceAllUsesWith(NewMemAcc);
819 MSSA->removeMemoryAccess(OldMemAcc);
820 }
821 }
822
Sebastian Pop41774802016-07-15 13:45:20 +0000823 if (isa<LoadInst>(Repl))
824 ++NL;
825 else if (isa<StoreInst>(Repl))
826 ++NS;
827 else if (isa<CallInst>(Repl))
828 ++NC;
829 else // Scalar
830 ++NI;
831
832 // Remove and rename all other instructions.
833 for (Instruction *I : InstructionsToHoist)
834 if (I != Repl) {
835 ++NR;
David Majnemer47285692016-07-25 02:21:23 +0000836 if (auto *ReplacementLoad = dyn_cast<LoadInst>(Repl)) {
837 ReplacementLoad->setAlignment(
838 std::min(ReplacementLoad->getAlignment(),
839 cast<LoadInst>(I)->getAlignment()));
Sebastian Pop41774802016-07-15 13:45:20 +0000840 ++NumLoadsRemoved;
David Majnemer47285692016-07-25 02:21:23 +0000841 } else if (auto *ReplacementStore = dyn_cast<StoreInst>(Repl)) {
842 ReplacementStore->setAlignment(
843 std::min(ReplacementStore->getAlignment(),
844 cast<StoreInst>(I)->getAlignment()));
Sebastian Pop41774802016-07-15 13:45:20 +0000845 ++NumStoresRemoved;
David Majnemer47285692016-07-25 02:21:23 +0000846 } else if (auto *ReplacementAlloca = dyn_cast<AllocaInst>(Repl)) {
847 ReplacementAlloca->setAlignment(
848 std::max(ReplacementAlloca->getAlignment(),
849 cast<AllocaInst>(I)->getAlignment()));
850 } else if (isa<CallInst>(Repl)) {
Sebastian Pop41774802016-07-15 13:45:20 +0000851 ++NumCallsRemoved;
David Majnemer47285692016-07-25 02:21:23 +0000852 }
Sebastian Pop5d3822f2016-08-03 20:54:33 +0000853
854 if (NewMemAcc) {
855 // Update the uses of the old MSSA access with NewMemAcc.
856 MemoryAccess *OldMA = MSSA->getMemoryAccess(I);
857 OldMA->replaceAllUsesWith(NewMemAcc);
858 MSSA->removeMemoryAccess(OldMA);
859 }
860
Peter Collingbourne8f1dd5c2016-09-07 23:39:04 +0000861 Repl->andIRFlags(I);
David Majnemer68623a02016-07-25 02:21:25 +0000862 combineKnownMetadata(Repl, I);
Sebastian Pop41774802016-07-15 13:45:20 +0000863 I->replaceAllUsesWith(Repl);
Sebastian Pop46601992016-08-27 02:48:41 +0000864 // Also invalidate the Alias Analysis cache.
865 MD->removeInstruction(I);
Sebastian Pop41774802016-07-15 13:45:20 +0000866 I->eraseFromParent();
867 }
Sebastian Pop5d3822f2016-08-03 20:54:33 +0000868
869 // Remove MemorySSA phi nodes with the same arguments.
870 if (NewMemAcc) {
871 SmallPtrSet<MemoryPhi *, 4> UsePhis;
872 for (User *U : NewMemAcc->users())
873 if (MemoryPhi *Phi = dyn_cast<MemoryPhi>(U))
874 UsePhis.insert(Phi);
875
876 for (auto *Phi : UsePhis) {
877 auto In = Phi->incoming_values();
David Majnemer0a16c222016-08-11 21:15:00 +0000878 if (all_of(In, [&](Use &U) { return U == NewMemAcc; })) {
Sebastian Pop5d3822f2016-08-03 20:54:33 +0000879 Phi->replaceAllUsesWith(NewMemAcc);
880 MSSA->removeMemoryAccess(Phi);
881 }
882 }
883 }
Sebastian Pop41774802016-07-15 13:45:20 +0000884 }
885
886 NumHoisted += NL + NS + NC + NI;
887 NumRemoved += NR;
888 NumLoadsHoisted += NL;
889 NumStoresHoisted += NS;
890 NumCallsHoisted += NC;
891 return {NI, NL + NC + NS};
892 }
893
894 // Hoist all expressions. Returns Number of scalars hoisted
895 // and number of non-scalars hoisted.
896 std::pair<unsigned, unsigned> hoistExpressions(Function &F) {
897 InsnInfo II;
898 LoadInfo LI;
899 StoreInfo SI;
900 CallInfo CI;
901 for (BasicBlock *BB : depth_first(&F.getEntryBlock())) {
Sebastian Pop38422b12016-07-26 00:15:08 +0000902 int InstructionNb = 0;
Sebastian Pop41774802016-07-15 13:45:20 +0000903 for (Instruction &I1 : *BB) {
Sebastian Pop38422b12016-07-26 00:15:08 +0000904 // Only hoist the first instructions in BB up to MaxDepthInBB. Hoisting
905 // deeper may increase the register pressure and compilation time.
906 if (MaxDepthInBB != -1 && InstructionNb++ >= MaxDepthInBB)
907 break;
908
Sebastian Pop440f15b2016-09-22 14:45:40 +0000909 // Do not value number terminator instructions.
Sebastian Pop5d68aa72016-09-22 15:08:09 +0000910 if (isa<TerminatorInst>(&I1))
Sebastian Pop440f15b2016-09-22 14:45:40 +0000911 break;
912
David Majnemer4c66a712016-07-18 00:34:58 +0000913 if (auto *Load = dyn_cast<LoadInst>(&I1))
Sebastian Pop41774802016-07-15 13:45:20 +0000914 LI.insert(Load, VN);
David Majnemer4c66a712016-07-18 00:34:58 +0000915 else if (auto *Store = dyn_cast<StoreInst>(&I1))
Sebastian Pop41774802016-07-15 13:45:20 +0000916 SI.insert(Store, VN);
David Majnemer4c66a712016-07-18 00:34:58 +0000917 else if (auto *Call = dyn_cast<CallInst>(&I1)) {
918 if (auto *Intr = dyn_cast<IntrinsicInst>(Call)) {
Sebastian Pop41774802016-07-15 13:45:20 +0000919 if (isa<DbgInfoIntrinsic>(Intr) ||
920 Intr->getIntrinsicID() == Intrinsic::assume)
921 continue;
922 }
923 if (Call->mayHaveSideEffects()) {
924 if (!OptForMinSize)
925 break;
926 // We may continue hoisting across calls which write to memory.
927 if (Call->mayThrow())
928 break;
929 }
Matt Arsenault6ad97732016-08-04 20:52:57 +0000930
931 if (Call->isConvergent())
932 break;
933
Sebastian Pop41774802016-07-15 13:45:20 +0000934 CI.insert(Call, VN);
Sebastian Pop55c30072016-07-27 05:48:12 +0000935 } else if (HoistingGeps || !isa<GetElementPtrInst>(&I1))
Sebastian Pop41774802016-07-15 13:45:20 +0000936 // Do not hoist scalars past calls that may write to memory because
937 // that could result in spills later. geps are handled separately.
938 // TODO: We can relax this for targets like AArch64 as they have more
939 // registers than X86.
940 II.insert(&I1, VN);
941 }
942 }
943
944 HoistingPointList HPL;
945 computeInsertionPoints(II.getVNTable(), HPL, InsKind::Scalar);
946 computeInsertionPoints(LI.getVNTable(), HPL, InsKind::Load);
947 computeInsertionPoints(SI.getVNTable(), HPL, InsKind::Store);
948 computeInsertionPoints(CI.getScalarVNTable(), HPL, InsKind::Scalar);
949 computeInsertionPoints(CI.getLoadVNTable(), HPL, InsKind::Load);
950 computeInsertionPoints(CI.getStoreVNTable(), HPL, InsKind::Store);
951 return hoist(HPL);
952 }
Sebastian Pop41774802016-07-15 13:45:20 +0000953};
954
955class GVNHoistLegacyPass : public FunctionPass {
956public:
957 static char ID;
958
959 GVNHoistLegacyPass() : FunctionPass(ID) {
960 initializeGVNHoistLegacyPassPass(*PassRegistry::getPassRegistry());
961 }
962
963 bool runOnFunction(Function &F) override {
Paul Robinson2d23c022016-07-19 22:57:14 +0000964 if (skipFunction(F))
965 return false;
Sebastian Pop41774802016-07-15 13:45:20 +0000966 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
967 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
968 auto &MD = getAnalysis<MemoryDependenceWrapperPass>().getMemDep();
Daniel Berlinea02eee2016-08-23 05:42:41 +0000969 auto &MSSA = getAnalysis<MemorySSAWrapperPass>().getMSSA();
Sebastian Pop41774802016-07-15 13:45:20 +0000970
Daniel Berlinea02eee2016-08-23 05:42:41 +0000971 GVNHoist G(&DT, &AA, &MD, &MSSA, F.optForMinSize());
Sebastian Pop41774802016-07-15 13:45:20 +0000972 return G.run(F);
973 }
974
975 void getAnalysisUsage(AnalysisUsage &AU) const override {
976 AU.addRequired<DominatorTreeWrapperPass>();
977 AU.addRequired<AAResultsWrapperPass>();
978 AU.addRequired<MemoryDependenceWrapperPass>();
Daniel Berlinea02eee2016-08-23 05:42:41 +0000979 AU.addRequired<MemorySSAWrapperPass>();
Sebastian Pop41774802016-07-15 13:45:20 +0000980 AU.addPreserved<DominatorTreeWrapperPass>();
Daniel Berlinea02eee2016-08-23 05:42:41 +0000981 AU.addPreserved<MemorySSAWrapperPass>();
Sebastian Pop41774802016-07-15 13:45:20 +0000982 }
983};
984} // namespace
985
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000986PreservedAnalyses GVNHoistPass::run(Function &F, FunctionAnalysisManager &AM) {
Sebastian Pop41774802016-07-15 13:45:20 +0000987 DominatorTree &DT = AM.getResult<DominatorTreeAnalysis>(F);
988 AliasAnalysis &AA = AM.getResult<AAManager>(F);
989 MemoryDependenceResults &MD = AM.getResult<MemoryDependenceAnalysis>(F);
Daniel Berlinea02eee2016-08-23 05:42:41 +0000990 MemorySSA &MSSA = AM.getResult<MemorySSAAnalysis>(F).getMSSA();
991 GVNHoist G(&DT, &AA, &MD, &MSSA, F.optForMinSize());
Sebastian Pop41774802016-07-15 13:45:20 +0000992 if (!G.run(F))
993 return PreservedAnalyses::all();
994
995 PreservedAnalyses PA;
996 PA.preserve<DominatorTreeAnalysis>();
Daniel Berlinea02eee2016-08-23 05:42:41 +0000997 PA.preserve<MemorySSAAnalysis>();
Sebastian Pop41774802016-07-15 13:45:20 +0000998 return PA;
999}
1000
1001char GVNHoistLegacyPass::ID = 0;
1002INITIALIZE_PASS_BEGIN(GVNHoistLegacyPass, "gvn-hoist",
1003 "Early GVN Hoisting of Expressions", false, false)
1004INITIALIZE_PASS_DEPENDENCY(MemoryDependenceWrapperPass)
Daniel Berlinea02eee2016-08-23 05:42:41 +00001005INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
Sebastian Pop41774802016-07-15 13:45:20 +00001006INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
1007INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
1008INITIALIZE_PASS_END(GVNHoistLegacyPass, "gvn-hoist",
1009 "Early GVN Hoisting of Expressions", false, false)
1010
1011FunctionPass *llvm::createGVNHoistPass() { return new GVNHoistLegacyPass(); }