blob: 53f76dfcfe95400308e54dd5bac4b76dfbb544ea [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
22#include "llvm/ADT/DenseMap.h"
23#include "llvm/ADT/SmallPtrSet.h"
24#include "llvm/ADT/Statistic.h"
25#include "llvm/Analysis/ValueTracking.h"
26#include "llvm/Transforms/Scalar.h"
27#include "llvm/Transforms/Scalar/GVN.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 Pop2aadad72016-08-03 20:54:38 +000058static cl::opt<int> MaxChainLength(
59 "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)"));
62
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 }
George Burgess IV9cf05462016-07-27 06:34:53 +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),
Sebastian Pop55c30072016-07-27 05:48:12 +0000205 HoistingGeps(OptForMinSize), HoistedCtr(0) {}
Daniel Berlin65af45d2016-07-25 17:24:22 +0000206 bool run(Function &F) {
207 VN.setDomTree(DT);
208 VN.setAliasAnalysis(AA);
209 VN.setMemDep(MD);
210 bool Res = false;
Sebastian Pop4ba7c882016-08-03 20:54:36 +0000211 // Perform DFS Numbering of instructions.
212 unsigned BBI = 0;
213 for (const BasicBlock *BB : depth_first(&F.getEntryBlock())) {
214 DFSNumber[BB] = ++BBI;
215 unsigned I = 0;
216 for (auto &Inst: *BB)
217 DFSNumber[&Inst] = ++I;
218 }
Daniel Berlin65af45d2016-07-25 17:24:22 +0000219
Sebastian Pop2aadad72016-08-03 20:54:38 +0000220 int ChainLength = 0;
221
Daniel Berlin65af45d2016-07-25 17:24:22 +0000222 // FIXME: use lazy evaluation of VN to avoid the fix-point computation.
223 while (1) {
Sebastian Pop2aadad72016-08-03 20:54:38 +0000224 if (MaxChainLength != -1 && ++ChainLength >= MaxChainLength)
225 return Res;
226
Daniel Berlin65af45d2016-07-25 17:24:22 +0000227 auto HoistStat = hoistExpressions(F);
Sebastian Pop5d3822f2016-08-03 20:54:33 +0000228 if (HoistStat.first + HoistStat.second == 0)
Daniel Berlin65af45d2016-07-25 17:24:22 +0000229 return Res;
Sebastian Pop5d3822f2016-08-03 20:54:33 +0000230
231 if (HoistStat.second > 0)
Daniel Berlin65af45d2016-07-25 17:24:22 +0000232 // To address a limitation of the current GVN, we need to rerun the
Sebastian Pop5d3822f2016-08-03 20:54:33 +0000233 // hoisting after we hoisted loads or stores in order to be able to
234 // hoist all scalars dependent on the hoisted ld/st.
Daniel Berlin65af45d2016-07-25 17:24:22 +0000235 VN.clear();
Sebastian Pop5d3822f2016-08-03 20:54:33 +0000236
Daniel Berlin65af45d2016-07-25 17:24:22 +0000237 Res = true;
238 }
239
240 return Res;
241 }
242private:
Sebastian Pop41774802016-07-15 13:45:20 +0000243 GVN::ValueTable VN;
244 DominatorTree *DT;
245 AliasAnalysis *AA;
246 MemoryDependenceResults *MD;
Daniel Berlinea02eee2016-08-23 05:42:41 +0000247 MemorySSA *MSSA;
Sebastian Pop41774802016-07-15 13:45:20 +0000248 const bool OptForMinSize;
Sebastian Pop55c30072016-07-27 05:48:12 +0000249 const bool HoistingGeps;
Sebastian Pop91d4a302016-07-26 00:15:10 +0000250 DenseMap<const Value *, unsigned> DFSNumber;
Sebastian Pop41774802016-07-15 13:45:20 +0000251 BBSideEffectsSet BBSideEffects;
David Majnemeraa241782016-07-18 00:35:01 +0000252 int HoistedCtr;
253
Sebastian Pop41774802016-07-15 13:45:20 +0000254 enum InsKind { Unknown, Scalar, Load, Store };
255
Sebastian Pop41774802016-07-15 13:45:20 +0000256 // Return true when there are exception handling in BB.
257 bool hasEH(const BasicBlock *BB) {
258 auto It = BBSideEffects.find(BB);
259 if (It != BBSideEffects.end())
260 return It->second;
261
262 if (BB->isEHPad() || BB->hasAddressTaken()) {
263 BBSideEffects[BB] = true;
264 return true;
265 }
266
267 if (BB->getTerminator()->mayThrow()) {
268 BBSideEffects[BB] = true;
269 return true;
270 }
271
272 BBSideEffects[BB] = false;
273 return false;
274 }
275
276 // Return true when all paths from A to the end of the function pass through
277 // either B or C.
278 bool hoistingFromAllPaths(const BasicBlock *A, const BasicBlock *B,
279 const BasicBlock *C) {
280 // We fully copy the WL in order to be able to remove items from it.
281 SmallPtrSet<const BasicBlock *, 2> WL;
282 WL.insert(B);
283 WL.insert(C);
284
285 for (auto It = df_begin(A), E = df_end(A); It != E;) {
286 // There exists a path from A to the exit of the function if we are still
287 // iterating in DF traversal and we removed all instructions from the work
288 // list.
289 if (WL.empty())
290 return false;
291
292 const BasicBlock *BB = *It;
293 if (WL.erase(BB)) {
294 // Stop DFS traversal when BB is in the work list.
295 It.skipChildren();
296 continue;
297 }
298
299 // Check for end of function, calls that do not return, etc.
300 if (!isGuaranteedToTransferExecutionToSuccessor(BB->getTerminator()))
301 return false;
302
303 // Increment DFS traversal when not skipping children.
304 ++It;
305 }
306
307 return true;
308 }
309
310 /* Return true when I1 appears before I2 in the instructions of BB. */
Sebastian Pop91d4a302016-07-26 00:15:10 +0000311 bool firstInBB(const Instruction *I1, const Instruction *I2) {
312 assert (I1->getParent() == I2->getParent());
313 unsigned I1DFS = DFSNumber.lookup(I1);
314 unsigned I2DFS = DFSNumber.lookup(I2);
315 assert (I1DFS && I2DFS);
316 return I1DFS < I2DFS;
Daniel Berlin40765a62016-07-25 18:19:49 +0000317 }
Sebastian Pop91d4a302016-07-26 00:15:10 +0000318
Sebastian Pop41774802016-07-15 13:45:20 +0000319 // Return true when there are users of Def in BB.
320 bool hasMemoryUseOnPath(MemoryAccess *Def, const BasicBlock *BB,
321 const Instruction *OldPt) {
Sebastian Pop41774802016-07-15 13:45:20 +0000322 const BasicBlock *DefBB = Def->getBlock();
323 const BasicBlock *OldBB = OldPt->getParent();
324
David Majnemer4c66a712016-07-18 00:34:58 +0000325 for (User *U : Def->users())
326 if (auto *MU = dyn_cast<MemoryUse>(U)) {
Sebastian Pop5d3822f2016-08-03 20:54:33 +0000327 // FIXME: MU->getBlock() does not get updated when we move the instruction.
328 BasicBlock *UBB = MU->getMemoryInst()->getParent();
Sebastian Pop41774802016-07-15 13:45:20 +0000329 // Only analyze uses in BB.
330 if (BB != UBB)
331 continue;
332
333 // A use in the same block as the Def is on the path.
334 if (UBB == DefBB) {
David Majnemer4c66a712016-07-18 00:34:58 +0000335 assert(MSSA->locallyDominates(Def, MU) && "def not dominating use");
Sebastian Pop41774802016-07-15 13:45:20 +0000336 return true;
337 }
338
339 if (UBB != OldBB)
340 return true;
341
342 // It is only harmful to hoist when the use is before OldPt.
Sebastian Pop91d4a302016-07-26 00:15:10 +0000343 if (firstInBB(MU->getMemoryInst(), OldPt))
Sebastian Pop41774802016-07-15 13:45:20 +0000344 return true;
345 }
346
347 return false;
348 }
349
350 // Return true when there are exception handling or loads of memory Def
351 // between OldPt and NewPt.
352
353 // Decrement by 1 NBBsOnAllPaths for each block between HoistPt and BB, and
354 // return true when the counter NBBsOnAllPaths reaces 0, except when it is
355 // initialized to -1 which is unlimited.
356 bool hasEHOrLoadsOnPath(const Instruction *NewPt, const Instruction *OldPt,
357 MemoryAccess *Def, int &NBBsOnAllPaths) {
358 const BasicBlock *NewBB = NewPt->getParent();
359 const BasicBlock *OldBB = OldPt->getParent();
360 assert(DT->dominates(NewBB, OldBB) && "invalid path");
361 assert(DT->dominates(Def->getBlock(), NewBB) &&
362 "def does not dominate new hoisting point");
363
364 // Walk all basic blocks reachable in depth-first iteration on the inverse
365 // CFG from OldBB to NewBB. These blocks are all the blocks that may be
366 // executed between the execution of NewBB and OldBB. Hoisting an expression
367 // from OldBB into NewBB has to be safe on all execution paths.
368 for (auto I = idf_begin(OldBB), E = idf_end(OldBB); I != E;) {
369 if (*I == NewBB) {
370 // Stop traversal when reaching HoistPt.
371 I.skipChildren();
372 continue;
373 }
374
375 // Impossible to hoist with exceptions on the path.
376 if (hasEH(*I))
377 return true;
378
379 // Check that we do not move a store past loads.
380 if (hasMemoryUseOnPath(Def, *I, OldPt))
381 return true;
382
383 // Stop walk once the limit is reached.
384 if (NBBsOnAllPaths == 0)
385 return true;
386
387 // -1 is unlimited number of blocks on all paths.
388 if (NBBsOnAllPaths != -1)
389 --NBBsOnAllPaths;
390
391 ++I;
392 }
393
394 return false;
395 }
396
397 // Return true when there are exception handling between HoistPt and BB.
398 // Decrement by 1 NBBsOnAllPaths for each block between HoistPt and BB, and
399 // return true when the counter NBBsOnAllPaths reaches 0, except when it is
400 // initialized to -1 which is unlimited.
401 bool hasEHOnPath(const BasicBlock *HoistPt, const BasicBlock *BB,
402 int &NBBsOnAllPaths) {
403 assert(DT->dominates(HoistPt, BB) && "Invalid path");
404
405 // Walk all basic blocks reachable in depth-first iteration on
406 // the inverse CFG from BBInsn to NewHoistPt. These blocks are all the
407 // blocks that may be executed between the execution of NewHoistPt and
408 // BBInsn. Hoisting an expression from BBInsn into NewHoistPt has to be safe
409 // on all execution paths.
410 for (auto I = idf_begin(BB), E = idf_end(BB); I != E;) {
411 if (*I == HoistPt) {
412 // Stop traversal when reaching NewHoistPt.
413 I.skipChildren();
414 continue;
415 }
416
417 // Impossible to hoist with exceptions on the path.
418 if (hasEH(*I))
419 return true;
420
421 // Stop walk once the limit is reached.
422 if (NBBsOnAllPaths == 0)
423 return true;
424
425 // -1 is unlimited number of blocks on all paths.
426 if (NBBsOnAllPaths != -1)
427 --NBBsOnAllPaths;
428
429 ++I;
430 }
431
432 return false;
433 }
434
435 // Return true when it is safe to hoist a memory load or store U from OldPt
436 // to NewPt.
437 bool safeToHoistLdSt(const Instruction *NewPt, const Instruction *OldPt,
438 MemoryUseOrDef *U, InsKind K, int &NBBsOnAllPaths) {
439
440 // In place hoisting is safe.
441 if (NewPt == OldPt)
442 return true;
443
444 const BasicBlock *NewBB = NewPt->getParent();
445 const BasicBlock *OldBB = OldPt->getParent();
446 const BasicBlock *UBB = U->getBlock();
447
448 // Check for dependences on the Memory SSA.
449 MemoryAccess *D = U->getDefiningAccess();
450 BasicBlock *DBB = D->getBlock();
451 if (DT->properlyDominates(NewBB, DBB))
452 // Cannot move the load or store to NewBB above its definition in DBB.
453 return false;
454
455 if (NewBB == DBB && !MSSA->isLiveOnEntryDef(D))
David Majnemer4c66a712016-07-18 00:34:58 +0000456 if (auto *UD = dyn_cast<MemoryUseOrDef>(D))
Sebastian Pop91d4a302016-07-26 00:15:10 +0000457 if (firstInBB(NewPt, UD->getMemoryInst()))
Sebastian Pop41774802016-07-15 13:45:20 +0000458 // Cannot move the load or store to NewPt above its definition in D.
459 return false;
460
461 // Check for unsafe hoistings due to side effects.
462 if (K == InsKind::Store) {
463 if (hasEHOrLoadsOnPath(NewPt, OldPt, D, NBBsOnAllPaths))
464 return false;
465 } else if (hasEHOnPath(NewBB, OldBB, NBBsOnAllPaths))
466 return false;
467
468 if (UBB == NewBB) {
469 if (DT->properlyDominates(DBB, NewBB))
470 return true;
471 assert(UBB == DBB);
472 assert(MSSA->locallyDominates(D, U));
473 }
474
475 // No side effects: it is safe to hoist.
476 return true;
477 }
478
479 // Return true when it is safe to hoist scalar instructions from BB1 and BB2
480 // to HoistBB.
481 bool safeToHoistScalar(const BasicBlock *HoistBB, const BasicBlock *BB1,
482 const BasicBlock *BB2, int &NBBsOnAllPaths) {
483 // Check that the hoisted expression is needed on all paths. When HoistBB
484 // already contains an instruction to be hoisted, the expression is needed
485 // on all paths. Enable scalar hoisting at -Oz as it is safe to hoist
486 // scalars to a place where they are partially needed.
487 if (!OptForMinSize && BB1 != HoistBB &&
488 !hoistingFromAllPaths(HoistBB, BB1, BB2))
489 return false;
490
491 if (hasEHOnPath(HoistBB, BB1, NBBsOnAllPaths) ||
492 hasEHOnPath(HoistBB, BB2, NBBsOnAllPaths))
493 return false;
494
495 // Safe to hoist scalars from BB1 and BB2 to HoistBB.
496 return true;
497 }
498
499 // Each element of a hoisting list contains the basic block where to hoist and
500 // a list of instructions to be hoisted.
501 typedef std::pair<BasicBlock *, SmallVecInsn> HoistingPointInfo;
502 typedef SmallVector<HoistingPointInfo, 4> HoistingPointList;
503
504 // Partition InstructionsToHoist into a set of candidates which can share a
505 // common hoisting point. The partitions are collected in HPL. IsScalar is
506 // true when the instructions in InstructionsToHoist are scalars. IsLoad is
507 // true when the InstructionsToHoist are loads, false when they are stores.
508 void partitionCandidates(SmallVecImplInsn &InstructionsToHoist,
509 HoistingPointList &HPL, InsKind K) {
510 // No need to sort for two instructions.
511 if (InstructionsToHoist.size() > 2) {
512 SortByDFSIn Pred(DFSNumber);
513 std::sort(InstructionsToHoist.begin(), InstructionsToHoist.end(), Pred);
514 }
515
516 int NBBsOnAllPaths = MaxNumberOfBBSInPath;
517
518 SmallVecImplInsn::iterator II = InstructionsToHoist.begin();
519 SmallVecImplInsn::iterator Start = II;
520 Instruction *HoistPt = *II;
521 BasicBlock *HoistBB = HoistPt->getParent();
522 MemoryUseOrDef *UD;
523 if (K != InsKind::Scalar)
524 UD = cast<MemoryUseOrDef>(MSSA->getMemoryAccess(HoistPt));
525
526 for (++II; II != InstructionsToHoist.end(); ++II) {
527 Instruction *Insn = *II;
528 BasicBlock *BB = Insn->getParent();
529 BasicBlock *NewHoistBB;
530 Instruction *NewHoistPt;
531
532 if (BB == HoistBB) {
533 NewHoistBB = HoistBB;
Sebastian Pop91d4a302016-07-26 00:15:10 +0000534 NewHoistPt = firstInBB(Insn, HoistPt) ? Insn : HoistPt;
Sebastian Pop41774802016-07-15 13:45:20 +0000535 } else {
536 NewHoistBB = DT->findNearestCommonDominator(HoistBB, BB);
537 if (NewHoistBB == BB)
538 NewHoistPt = Insn;
539 else if (NewHoistBB == HoistBB)
540 NewHoistPt = HoistPt;
541 else
542 NewHoistPt = NewHoistBB->getTerminator();
543 }
544
545 if (K == InsKind::Scalar) {
546 if (safeToHoistScalar(NewHoistBB, HoistBB, BB, NBBsOnAllPaths)) {
547 // Extend HoistPt to NewHoistPt.
548 HoistPt = NewHoistPt;
549 HoistBB = NewHoistBB;
550 continue;
551 }
552 } else {
553 // When NewBB already contains an instruction to be hoisted, the
554 // expression is needed on all paths.
555 // Check that the hoisted expression is needed on all paths: it is
556 // unsafe to hoist loads to a place where there may be a path not
557 // loading from the same address: for instance there may be a branch on
558 // which the address of the load may not be initialized.
559 if ((HoistBB == NewHoistBB || BB == NewHoistBB ||
560 hoistingFromAllPaths(NewHoistBB, HoistBB, BB)) &&
561 // Also check that it is safe to move the load or store from HoistPt
562 // to NewHoistPt, and from Insn to NewHoistPt.
563 safeToHoistLdSt(NewHoistPt, HoistPt, UD, K, NBBsOnAllPaths) &&
564 safeToHoistLdSt(NewHoistPt, Insn,
565 cast<MemoryUseOrDef>(MSSA->getMemoryAccess(Insn)),
566 K, NBBsOnAllPaths)) {
567 // Extend HoistPt to NewHoistPt.
568 HoistPt = NewHoistPt;
569 HoistBB = NewHoistBB;
570 continue;
571 }
572 }
573
574 // At this point it is not safe to extend the current hoisting to
575 // NewHoistPt: save the hoisting list so far.
576 if (std::distance(Start, II) > 1)
David Majnemer4c66a712016-07-18 00:34:58 +0000577 HPL.push_back({HoistBB, SmallVecInsn(Start, II)});
Sebastian Pop41774802016-07-15 13:45:20 +0000578
579 // Start over from BB.
580 Start = II;
581 if (K != InsKind::Scalar)
582 UD = cast<MemoryUseOrDef>(MSSA->getMemoryAccess(*Start));
583 HoistPt = Insn;
584 HoistBB = BB;
585 NBBsOnAllPaths = MaxNumberOfBBSInPath;
586 }
587
588 // Save the last partition.
589 if (std::distance(Start, II) > 1)
David Majnemer4c66a712016-07-18 00:34:58 +0000590 HPL.push_back({HoistBB, SmallVecInsn(Start, II)});
Sebastian Pop41774802016-07-15 13:45:20 +0000591 }
592
593 // Initialize HPL from Map.
594 void computeInsertionPoints(const VNtoInsns &Map, HoistingPointList &HPL,
595 InsKind K) {
David Majnemer4c66a712016-07-18 00:34:58 +0000596 for (const auto &Entry : Map) {
Sebastian Pop41774802016-07-15 13:45:20 +0000597 if (MaxHoistedThreshold != -1 && ++HoistedCtr > MaxHoistedThreshold)
598 return;
599
David Majnemer4c66a712016-07-18 00:34:58 +0000600 const SmallVecInsn &V = Entry.second;
Sebastian Pop41774802016-07-15 13:45:20 +0000601 if (V.size() < 2)
602 continue;
603
604 // Compute the insertion point and the list of expressions to be hoisted.
605 SmallVecInsn InstructionsToHoist;
606 for (auto I : V)
607 if (!hasEH(I->getParent()))
608 InstructionsToHoist.push_back(I);
609
David Majnemer4c66a712016-07-18 00:34:58 +0000610 if (!InstructionsToHoist.empty())
Sebastian Pop41774802016-07-15 13:45:20 +0000611 partitionCandidates(InstructionsToHoist, HPL, K);
612 }
613 }
614
615 // Return true when all operands of Instr are available at insertion point
616 // HoistPt. When limiting the number of hoisted expressions, one could hoist
617 // a load without hoisting its access function. So before hoisting any
618 // expression, make sure that all its operands are available at insert point.
619 bool allOperandsAvailable(const Instruction *I,
620 const BasicBlock *HoistPt) const {
David Majnemer4c66a712016-07-18 00:34:58 +0000621 for (const Use &Op : I->operands())
622 if (const auto *Inst = dyn_cast<Instruction>(&Op))
623 if (!DT->dominates(Inst->getParent(), HoistPt))
624 return false;
Sebastian Pop41774802016-07-15 13:45:20 +0000625
626 return true;
627 }
628
Sebastian Pop55c30072016-07-27 05:48:12 +0000629 // Same as allOperandsAvailable with recursive check for GEP operands.
630 bool allGepOperandsAvailable(const Instruction *I,
631 const BasicBlock *HoistPt) const {
632 for (const Use &Op : I->operands())
633 if (const auto *Inst = dyn_cast<Instruction>(&Op))
634 if (!DT->dominates(Inst->getParent(), HoistPt)) {
635 if (const GetElementPtrInst *GepOp = dyn_cast<GetElementPtrInst>(Inst)) {
636 if (!allGepOperandsAvailable(GepOp, HoistPt))
637 return false;
638 // Gep is available if all operands of GepOp are available.
639 } else {
640 // Gep is not available if it has operands other than GEPs that are
641 // defined in blocks not dominating HoistPt.
642 return false;
643 }
644 }
645 return true;
646 }
647
648 // Make all operands of the GEP available.
649 void makeGepsAvailable(Instruction *Repl, BasicBlock *HoistPt,
650 const SmallVecInsn &InstructionsToHoist,
651 Instruction *Gep) const {
652 assert(allGepOperandsAvailable(Gep, HoistPt) && "GEP operands not available");
653
654 Instruction *ClonedGep = Gep->clone();
655 for (unsigned i = 0, e = Gep->getNumOperands(); i != e; ++i)
656 if (Instruction *Op = dyn_cast<Instruction>(Gep->getOperand(i))) {
657
658 // Check whether the operand is already available.
659 if (DT->dominates(Op->getParent(), HoistPt))
660 continue;
661
662 // As a GEP can refer to other GEPs, recursively make all the operands
663 // of this GEP available at HoistPt.
664 if (GetElementPtrInst *GepOp = dyn_cast<GetElementPtrInst>(Op))
665 makeGepsAvailable(ClonedGep, HoistPt, InstructionsToHoist, GepOp);
666 }
667
668 // Copy Gep and replace its uses in Repl with ClonedGep.
669 ClonedGep->insertBefore(HoistPt->getTerminator());
670
671 // Conservatively discard any optimization hints, they may differ on the
672 // other paths.
673 ClonedGep->dropUnknownNonDebugMetadata();
674
675 // If we have optimization hints which agree with each other along different
676 // paths, preserve them.
677 for (const Instruction *OtherInst : InstructionsToHoist) {
678 const GetElementPtrInst *OtherGep;
679 if (auto *OtherLd = dyn_cast<LoadInst>(OtherInst))
680 OtherGep = cast<GetElementPtrInst>(OtherLd->getPointerOperand());
681 else
682 OtherGep = cast<GetElementPtrInst>(
683 cast<StoreInst>(OtherInst)->getPointerOperand());
684 ClonedGep->intersectOptionalDataWith(OtherGep);
685 }
686
687 // Replace uses of Gep with ClonedGep in Repl.
688 Repl->replaceUsesOfWith(Gep, ClonedGep);
689 }
690
691 // In the case Repl is a load or a store, we make all their GEPs
692 // available: GEPs are not hoisted by default to avoid the address
693 // computations to be hoisted without the associated load or store.
694 bool makeGepOperandsAvailable(Instruction *Repl, BasicBlock *HoistPt,
695 const SmallVecInsn &InstructionsToHoist) const {
Sebastian Pop41774802016-07-15 13:45:20 +0000696 // Check whether the GEP of a ld/st can be synthesized at HoistPt.
David Majnemerbd210122016-07-20 21:05:01 +0000697 GetElementPtrInst *Gep = nullptr;
Sebastian Pop41774802016-07-15 13:45:20 +0000698 Instruction *Val = nullptr;
Sebastian Pop55c30072016-07-27 05:48:12 +0000699 if (auto *Ld = dyn_cast<LoadInst>(Repl)) {
David Majnemerbd210122016-07-20 21:05:01 +0000700 Gep = dyn_cast<GetElementPtrInst>(Ld->getPointerOperand());
Sebastian Pop55c30072016-07-27 05:48:12 +0000701 } else if (auto *St = dyn_cast<StoreInst>(Repl)) {
David Majnemerbd210122016-07-20 21:05:01 +0000702 Gep = dyn_cast<GetElementPtrInst>(St->getPointerOperand());
Sebastian Pop41774802016-07-15 13:45:20 +0000703 Val = dyn_cast<Instruction>(St->getValueOperand());
Sebastian Pop31fd5062016-07-21 23:22:10 +0000704 // Check that the stored value is available.
Sebastian Pop0e2cec02016-07-22 00:07:01 +0000705 if (Val) {
706 if (isa<GetElementPtrInst>(Val)) {
707 // Check whether we can compute the GEP at HoistPt.
Sebastian Pop55c30072016-07-27 05:48:12 +0000708 if (!allGepOperandsAvailable(Val, HoistPt))
Sebastian Pop0e2cec02016-07-22 00:07:01 +0000709 return false;
710 } else if (!DT->dominates(Val->getParent(), HoistPt))
711 return false;
712 }
Sebastian Pop41774802016-07-15 13:45:20 +0000713 }
714
Sebastian Pop41774802016-07-15 13:45:20 +0000715 // Check whether we can compute the Gep at HoistPt.
Sebastian Pop55c30072016-07-27 05:48:12 +0000716 if (!Gep || !allGepOperandsAvailable(Gep, HoistPt))
Sebastian Pop41774802016-07-15 13:45:20 +0000717 return false;
718
Sebastian Pop55c30072016-07-27 05:48:12 +0000719 makeGepsAvailable(Repl, HoistPt, InstructionsToHoist, Gep);
Sebastian Pop41774802016-07-15 13:45:20 +0000720
Sebastian Pop55c30072016-07-27 05:48:12 +0000721 if (Val && isa<GetElementPtrInst>(Val))
722 makeGepsAvailable(Repl, HoistPt, InstructionsToHoist, Val);
Sebastian Pop41774802016-07-15 13:45:20 +0000723
724 return true;
725 }
726
727 std::pair<unsigned, unsigned> hoist(HoistingPointList &HPL) {
728 unsigned NI = 0, NL = 0, NS = 0, NC = 0, NR = 0;
729 for (const HoistingPointInfo &HP : HPL) {
730 // Find out whether we already have one of the instructions in HoistPt,
731 // in which case we do not have to move it.
732 BasicBlock *HoistPt = HP.first;
733 const SmallVecInsn &InstructionsToHoist = HP.second;
734 Instruction *Repl = nullptr;
735 for (Instruction *I : InstructionsToHoist)
Sebastian Pop586d3ea2016-07-27 05:13:52 +0000736 if (I->getParent() == HoistPt)
Sebastian Pop41774802016-07-15 13:45:20 +0000737 // If there are two instructions in HoistPt to be hoisted in place:
738 // update Repl to be the first one, such that we can rename the uses
739 // of the second based on the first.
Sebastian Pop586d3ea2016-07-27 05:13:52 +0000740 if (!Repl || firstInBB(I, Repl))
741 Repl = I;
Sebastian Pop41774802016-07-15 13:45:20 +0000742
Daniel Berlinf75fd1b2016-08-11 20:32:43 +0000743 // Keep track of whether we moved the instruction so we know whether we
744 // should move the MemoryAccess.
745 bool MoveAccess = true;
Sebastian Pop41774802016-07-15 13:45:20 +0000746 if (Repl) {
747 // Repl is already in HoistPt: it remains in place.
748 assert(allOperandsAvailable(Repl, HoistPt) &&
749 "instruction depends on operands that are not available");
Daniel Berlinf75fd1b2016-08-11 20:32:43 +0000750 MoveAccess = false;
Sebastian Pop41774802016-07-15 13:45:20 +0000751 } else {
752 // When we do not find Repl in HoistPt, select the first in the list
753 // and move it to HoistPt.
754 Repl = InstructionsToHoist.front();
755
756 // We can move Repl in HoistPt only when all operands are available.
757 // The order in which hoistings are done may influence the availability
758 // of operands.
Sebastian Pop429740a2016-08-04 23:49:05 +0000759 if (!allOperandsAvailable(Repl, HoistPt)) {
760
761 // When HoistingGeps there is nothing more we can do to make the
762 // operands available: just continue.
763 if (HoistingGeps)
764 continue;
765
766 // When not HoistingGeps we need to copy the GEPs.
767 if (!makeGepOperandsAvailable(Repl, HoistPt, InstructionsToHoist))
768 continue;
769 }
Sebastian Pop55c30072016-07-27 05:48:12 +0000770
Sebastian Pop5d3822f2016-08-03 20:54:33 +0000771 // Move the instruction at the end of HoistPt.
Sebastian Pop4ba7c882016-08-03 20:54:36 +0000772 Instruction *Last = HoistPt->getTerminator();
773 Repl->moveBefore(Last);
774
775 DFSNumber[Repl] = DFSNumber[Last]++;
Sebastian Pop41774802016-07-15 13:45:20 +0000776 }
777
Daniel Berlinf75fd1b2016-08-11 20:32:43 +0000778 MemoryAccess *NewMemAcc = MSSA->getMemoryAccess(Repl);
779
780 if (MoveAccess) {
781 if (MemoryUseOrDef *OldMemAcc =
782 dyn_cast_or_null<MemoryUseOrDef>(NewMemAcc)) {
Sebastian Pop5d3822f2016-08-03 20:54:33 +0000783 // The definition of this ld/st will not change: ld/st hoisting is
784 // legal when the ld/st is not moved past its current definition.
785 MemoryAccess *Def = OldMemAcc->getDefiningAccess();
Daniel Berlinf75fd1b2016-08-11 20:32:43 +0000786 NewMemAcc =
787 MSSA->createMemoryAccessInBB(Repl, Def, HoistPt, MemorySSA::End);
Sebastian Pop5d3822f2016-08-03 20:54:33 +0000788 OldMemAcc->replaceAllUsesWith(NewMemAcc);
789 MSSA->removeMemoryAccess(OldMemAcc);
790 }
791 }
792
Sebastian Pop41774802016-07-15 13:45:20 +0000793 if (isa<LoadInst>(Repl))
794 ++NL;
795 else if (isa<StoreInst>(Repl))
796 ++NS;
797 else if (isa<CallInst>(Repl))
798 ++NC;
799 else // Scalar
800 ++NI;
801
802 // Remove and rename all other instructions.
803 for (Instruction *I : InstructionsToHoist)
804 if (I != Repl) {
805 ++NR;
David Majnemer47285692016-07-25 02:21:23 +0000806 if (auto *ReplacementLoad = dyn_cast<LoadInst>(Repl)) {
807 ReplacementLoad->setAlignment(
808 std::min(ReplacementLoad->getAlignment(),
809 cast<LoadInst>(I)->getAlignment()));
Sebastian Pop41774802016-07-15 13:45:20 +0000810 ++NumLoadsRemoved;
David Majnemer47285692016-07-25 02:21:23 +0000811 } else if (auto *ReplacementStore = dyn_cast<StoreInst>(Repl)) {
812 ReplacementStore->setAlignment(
813 std::min(ReplacementStore->getAlignment(),
814 cast<StoreInst>(I)->getAlignment()));
Sebastian Pop41774802016-07-15 13:45:20 +0000815 ++NumStoresRemoved;
David Majnemer47285692016-07-25 02:21:23 +0000816 } else if (auto *ReplacementAlloca = dyn_cast<AllocaInst>(Repl)) {
817 ReplacementAlloca->setAlignment(
818 std::max(ReplacementAlloca->getAlignment(),
819 cast<AllocaInst>(I)->getAlignment()));
820 } else if (isa<CallInst>(Repl)) {
Sebastian Pop41774802016-07-15 13:45:20 +0000821 ++NumCallsRemoved;
David Majnemer47285692016-07-25 02:21:23 +0000822 }
Sebastian Pop5d3822f2016-08-03 20:54:33 +0000823
824 if (NewMemAcc) {
825 // Update the uses of the old MSSA access with NewMemAcc.
826 MemoryAccess *OldMA = MSSA->getMemoryAccess(I);
827 OldMA->replaceAllUsesWith(NewMemAcc);
828 MSSA->removeMemoryAccess(OldMA);
829 }
830
David Majnemer4808f262016-07-21 05:59:53 +0000831 Repl->intersectOptionalDataWith(I);
David Majnemer68623a02016-07-25 02:21:25 +0000832 combineKnownMetadata(Repl, I);
Sebastian Pop41774802016-07-15 13:45:20 +0000833 I->replaceAllUsesWith(Repl);
834 I->eraseFromParent();
835 }
Sebastian Pop5d3822f2016-08-03 20:54:33 +0000836
837 // Remove MemorySSA phi nodes with the same arguments.
838 if (NewMemAcc) {
839 SmallPtrSet<MemoryPhi *, 4> UsePhis;
840 for (User *U : NewMemAcc->users())
841 if (MemoryPhi *Phi = dyn_cast<MemoryPhi>(U))
842 UsePhis.insert(Phi);
843
844 for (auto *Phi : UsePhis) {
845 auto In = Phi->incoming_values();
David Majnemer0a16c222016-08-11 21:15:00 +0000846 if (all_of(In, [&](Use &U) { return U == NewMemAcc; })) {
Sebastian Pop5d3822f2016-08-03 20:54:33 +0000847 Phi->replaceAllUsesWith(NewMemAcc);
848 MSSA->removeMemoryAccess(Phi);
849 }
850 }
851 }
Sebastian Pop41774802016-07-15 13:45:20 +0000852 }
853
854 NumHoisted += NL + NS + NC + NI;
855 NumRemoved += NR;
856 NumLoadsHoisted += NL;
857 NumStoresHoisted += NS;
858 NumCallsHoisted += NC;
859 return {NI, NL + NC + NS};
860 }
861
862 // Hoist all expressions. Returns Number of scalars hoisted
863 // and number of non-scalars hoisted.
864 std::pair<unsigned, unsigned> hoistExpressions(Function &F) {
865 InsnInfo II;
866 LoadInfo LI;
867 StoreInfo SI;
868 CallInfo CI;
869 for (BasicBlock *BB : depth_first(&F.getEntryBlock())) {
Sebastian Pop38422b12016-07-26 00:15:08 +0000870 int InstructionNb = 0;
Sebastian Pop41774802016-07-15 13:45:20 +0000871 for (Instruction &I1 : *BB) {
Sebastian Pop38422b12016-07-26 00:15:08 +0000872 // Only hoist the first instructions in BB up to MaxDepthInBB. Hoisting
873 // deeper may increase the register pressure and compilation time.
874 if (MaxDepthInBB != -1 && InstructionNb++ >= MaxDepthInBB)
875 break;
876
David Majnemer4c66a712016-07-18 00:34:58 +0000877 if (auto *Load = dyn_cast<LoadInst>(&I1))
Sebastian Pop41774802016-07-15 13:45:20 +0000878 LI.insert(Load, VN);
David Majnemer4c66a712016-07-18 00:34:58 +0000879 else if (auto *Store = dyn_cast<StoreInst>(&I1))
Sebastian Pop41774802016-07-15 13:45:20 +0000880 SI.insert(Store, VN);
David Majnemer4c66a712016-07-18 00:34:58 +0000881 else if (auto *Call = dyn_cast<CallInst>(&I1)) {
882 if (auto *Intr = dyn_cast<IntrinsicInst>(Call)) {
Sebastian Pop41774802016-07-15 13:45:20 +0000883 if (isa<DbgInfoIntrinsic>(Intr) ||
884 Intr->getIntrinsicID() == Intrinsic::assume)
885 continue;
886 }
887 if (Call->mayHaveSideEffects()) {
888 if (!OptForMinSize)
889 break;
890 // We may continue hoisting across calls which write to memory.
891 if (Call->mayThrow())
892 break;
893 }
Matt Arsenault6ad97732016-08-04 20:52:57 +0000894
895 if (Call->isConvergent())
896 break;
897
Sebastian Pop41774802016-07-15 13:45:20 +0000898 CI.insert(Call, VN);
Sebastian Pop55c30072016-07-27 05:48:12 +0000899 } else if (HoistingGeps || !isa<GetElementPtrInst>(&I1))
Sebastian Pop41774802016-07-15 13:45:20 +0000900 // Do not hoist scalars past calls that may write to memory because
901 // that could result in spills later. geps are handled separately.
902 // TODO: We can relax this for targets like AArch64 as they have more
903 // registers than X86.
904 II.insert(&I1, VN);
905 }
906 }
907
908 HoistingPointList HPL;
909 computeInsertionPoints(II.getVNTable(), HPL, InsKind::Scalar);
910 computeInsertionPoints(LI.getVNTable(), HPL, InsKind::Load);
911 computeInsertionPoints(SI.getVNTable(), HPL, InsKind::Store);
912 computeInsertionPoints(CI.getScalarVNTable(), HPL, InsKind::Scalar);
913 computeInsertionPoints(CI.getLoadVNTable(), HPL, InsKind::Load);
914 computeInsertionPoints(CI.getStoreVNTable(), HPL, InsKind::Store);
915 return hoist(HPL);
916 }
Sebastian Pop41774802016-07-15 13:45:20 +0000917};
918
919class GVNHoistLegacyPass : public FunctionPass {
920public:
921 static char ID;
922
923 GVNHoistLegacyPass() : FunctionPass(ID) {
924 initializeGVNHoistLegacyPassPass(*PassRegistry::getPassRegistry());
925 }
926
927 bool runOnFunction(Function &F) override {
Paul Robinson2d23c022016-07-19 22:57:14 +0000928 if (skipFunction(F))
929 return false;
Sebastian Pop41774802016-07-15 13:45:20 +0000930 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
931 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
932 auto &MD = getAnalysis<MemoryDependenceWrapperPass>().getMemDep();
Daniel Berlinea02eee2016-08-23 05:42:41 +0000933 auto &MSSA = getAnalysis<MemorySSAWrapperPass>().getMSSA();
Sebastian Pop41774802016-07-15 13:45:20 +0000934
Daniel Berlinea02eee2016-08-23 05:42:41 +0000935 GVNHoist G(&DT, &AA, &MD, &MSSA, F.optForMinSize());
Sebastian Pop41774802016-07-15 13:45:20 +0000936 return G.run(F);
937 }
938
939 void getAnalysisUsage(AnalysisUsage &AU) const override {
940 AU.addRequired<DominatorTreeWrapperPass>();
941 AU.addRequired<AAResultsWrapperPass>();
942 AU.addRequired<MemoryDependenceWrapperPass>();
Daniel Berlinea02eee2016-08-23 05:42:41 +0000943 AU.addRequired<MemorySSAWrapperPass>();
Sebastian Pop41774802016-07-15 13:45:20 +0000944 AU.addPreserved<DominatorTreeWrapperPass>();
Daniel Berlinea02eee2016-08-23 05:42:41 +0000945 AU.addPreserved<MemorySSAWrapperPass>();
Sebastian Pop41774802016-07-15 13:45:20 +0000946 }
947};
948} // namespace
949
950PreservedAnalyses GVNHoistPass::run(Function &F,
Sean Silva36e0d012016-08-09 00:28:15 +0000951 FunctionAnalysisManager &AM) {
Sebastian Pop41774802016-07-15 13:45:20 +0000952 DominatorTree &DT = AM.getResult<DominatorTreeAnalysis>(F);
953 AliasAnalysis &AA = AM.getResult<AAManager>(F);
954 MemoryDependenceResults &MD = AM.getResult<MemoryDependenceAnalysis>(F);
Daniel Berlinea02eee2016-08-23 05:42:41 +0000955 MemorySSA &MSSA = AM.getResult<MemorySSAAnalysis>(F).getMSSA();
956 GVNHoist G(&DT, &AA, &MD, &MSSA, F.optForMinSize());
Sebastian Pop41774802016-07-15 13:45:20 +0000957 if (!G.run(F))
958 return PreservedAnalyses::all();
959
960 PreservedAnalyses PA;
961 PA.preserve<DominatorTreeAnalysis>();
Daniel Berlinea02eee2016-08-23 05:42:41 +0000962 PA.preserve<MemorySSAAnalysis>();
Sebastian Pop41774802016-07-15 13:45:20 +0000963 return PA;
964}
965
966char GVNHoistLegacyPass::ID = 0;
967INITIALIZE_PASS_BEGIN(GVNHoistLegacyPass, "gvn-hoist",
968 "Early GVN Hoisting of Expressions", false, false)
969INITIALIZE_PASS_DEPENDENCY(MemoryDependenceWrapperPass)
Daniel Berlinea02eee2016-08-23 05:42:41 +0000970INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
Sebastian Pop41774802016-07-15 13:45:20 +0000971INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
972INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
973INITIALIZE_PASS_END(GVNHoistLegacyPass, "gvn-hoist",
974 "Early GVN Hoisting of Expressions", false, false)
975
976FunctionPass *llvm::createGVNHoistPass() { return new GVNHoistLegacyPass(); }