blob: 77fd432d762f232eb768a8af6fd968366f0fe73d [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//
Aditya Kumardfa87412017-09-13 05:28:03 +000016// The algorithm factors out the reachability of values such that multiple
17// queries to find reachability of values are fast. This is based on finding the
18// ANTIC points in the CFG which do not change during hoisting. The ANTIC points
19// are basically the dominance-frontiers in the inverse graph. So we introduce a
20// data structure (CHI nodes) to keep track of values flowing out of a basic
21// block. We only do this for values with multiple occurrences in the function
22// as they are the potential hoistable candidates. This approach allows us to
23// hoist instructions to a basic block with more than two successors, as well as
24// deal with infinite loops in a trivial way.
25//
26// Limitations: This pass does not hoist fully redundant expressions because
27// they are already handled by GVN-PRE. It is advisable to run gvn-hoist before
28// and after gvn-pre because gvn-pre creates opportunities for more instructions
29// to be hoisted.
30//
Sebastian Pop41774802016-07-15 13:45:20 +000031// Hoisting may affect the performance in some cases. To mitigate that, hoisting
32// is disabled in the following cases.
33// 1. Scalars across calls.
34// 2. geps when corresponding load/store cannot be hoisted.
35//===----------------------------------------------------------------------===//
36
37#include "llvm/ADT/DenseMap.h"
38#include "llvm/ADT/SmallPtrSet.h"
39#include "llvm/ADT/Statistic.h"
Nikolai Bozhenov9e4a1c32017-04-18 13:25:49 +000040#include "llvm/Analysis/GlobalsModRef.h"
Aditya Kumardfa87412017-09-13 05:28:03 +000041#include "llvm/Analysis/IteratedDominanceFrontier.h"
Daniel Berlin554dcd82017-04-11 20:06:36 +000042#include "llvm/Analysis/MemorySSA.h"
43#include "llvm/Analysis/MemorySSAUpdater.h"
Aditya Kumardfa87412017-09-13 05:28:03 +000044#include "llvm/Analysis/PostDominators.h"
Sebastian Pop41774802016-07-15 13:45:20 +000045#include "llvm/Analysis/ValueTracking.h"
Reid Kleckner0e8c4bb2017-09-07 23:27:44 +000046#include "llvm/IR/IntrinsicInst.h"
Sebastian Pop41774802016-07-15 13:45:20 +000047#include "llvm/Transforms/Scalar.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000048#include "llvm/Transforms/Scalar/GVN.h"
David Majnemer68623a02016-07-25 02:21:25 +000049#include "llvm/Transforms/Utils/Local.h"
Sebastian Pop41774802016-07-15 13:45:20 +000050
Aditya Kumardfa87412017-09-13 05:28:03 +000051#include <stack>
52
Sebastian Pop41774802016-07-15 13:45:20 +000053using namespace llvm;
54
55#define DEBUG_TYPE "gvn-hoist"
56
57STATISTIC(NumHoisted, "Number of instructions hoisted");
58STATISTIC(NumRemoved, "Number of instructions removed");
59STATISTIC(NumLoadsHoisted, "Number of loads hoisted");
60STATISTIC(NumLoadsRemoved, "Number of loads removed");
61STATISTIC(NumStoresHoisted, "Number of stores hoisted");
62STATISTIC(NumStoresRemoved, "Number of stores removed");
63STATISTIC(NumCallsHoisted, "Number of calls hoisted");
64STATISTIC(NumCallsRemoved, "Number of calls removed");
65
66static cl::opt<int>
67 MaxHoistedThreshold("gvn-max-hoisted", cl::Hidden, cl::init(-1),
68 cl::desc("Max number of instructions to hoist "
69 "(default unlimited = -1)"));
70static cl::opt<int> MaxNumberOfBBSInPath(
71 "gvn-hoist-max-bbs", cl::Hidden, cl::init(4),
72 cl::desc("Max number of basic blocks on the path between "
73 "hoisting locations (default = 4, unlimited = -1)"));
74
Sebastian Pop38422b12016-07-26 00:15:08 +000075static cl::opt<int> MaxDepthInBB(
76 "gvn-hoist-max-depth", cl::Hidden, cl::init(100),
77 cl::desc("Hoist instructions from the beginning of the BB up to the "
78 "maximum specified depth (default = 100, unlimited = -1)"));
79
Sebastian Pop5ba9f242016-10-13 01:39:10 +000080static cl::opt<int>
81 MaxChainLength("gvn-hoist-max-chain-length", cl::Hidden, cl::init(10),
82 cl::desc("Maximum length of dependent chains to hoist "
83 "(default = 10, unlimited = -1)"));
Sebastian Pop2aadad72016-08-03 20:54:38 +000084
Daniel Berlindcb004f2017-03-02 23:06:46 +000085namespace llvm {
Sebastian Pop41774802016-07-15 13:45:20 +000086
Aditya Kumardfa87412017-09-13 05:28:03 +000087typedef DenseMap<const BasicBlock *, bool> BBSideEffectsSet;
88typedef SmallVector<Instruction *, 4> SmallVecInsn;
89typedef SmallVectorImpl<Instruction *> SmallVecImplInsn;
90// Each element of a hoisting list contains the basic block where to hoist and
91// a list of instructions to be hoisted.
92typedef std::pair<BasicBlock *, SmallVecInsn> HoistingPointInfo;
93typedef SmallVector<HoistingPointInfo, 4> HoistingPointList;
94// A map from a pair of VNs to all the instructions with those VNs.
95typedef std::pair<unsigned, unsigned> VNType;
96typedef DenseMap<VNType, SmallVector<Instruction *, 4>> VNtoInsns;
Sebastian Pop41774802016-07-15 13:45:20 +000097
Aditya Kumardfa87412017-09-13 05:28:03 +000098// CHI keeps information about values flowing out of a basic block. It is
99// similar to PHI but in the inverse graph, and used for outgoing values on each
100// edge. For conciseness, it is computed only for instructions with multiple
101// occurrences in the CFG because they are the only hoistable candidates.
102// A (CHI[{V, B, I1}, {V, C, I2}]
103// / \
104// / \
105// B(I1) C (I2)
106// The Value number for both I1 and I2 is V, the CHI node will save the
107// instruction as well as the edge where the value is flowing to.
108struct CHIArg {
109 VNType VN;
110 // Edge destination (shows the direction of flow), may not be where the I is.
111 BasicBlock *Dest;
112 // The instruction (VN) which uses the values flowing out of CHI.
113 Instruction *I;
114 bool operator==(const CHIArg &A) { return VN == A.VN; }
115 bool operator!=(const CHIArg &A) { return !(*this == A); }
Sebastian Pop41774802016-07-15 13:45:20 +0000116};
117
Aditya Kumardfa87412017-09-13 05:28:03 +0000118typedef SmallVectorImpl<CHIArg>::iterator CHIIt;
119typedef iterator_range<CHIIt> CHIArgs;
120typedef DenseMap<BasicBlock *, SmallVector<CHIArg, 2>> OutValuesType;
121typedef DenseMap<BasicBlock *, SmallVector<std::pair<VNType, Instruction *>, 2>>
122 InValuesType;
123
David Majnemer04c7c222016-07-18 06:11:37 +0000124// An invalid value number Used when inserting a single value number into
125// VNtoInsns.
Reid Kleckner3498ad12016-07-18 18:53:50 +0000126enum : unsigned { InvalidVN = ~2U };
Sebastian Pop41774802016-07-15 13:45:20 +0000127
128// Records all scalar instructions candidate for code hoisting.
129class InsnInfo {
130 VNtoInsns VNtoScalars;
131
132public:
133 // Inserts I and its value number in VNtoScalars.
134 void insert(Instruction *I, GVN::ValueTable &VN) {
135 // Scalar instruction.
136 unsigned V = VN.lookupOrAdd(I);
David Majnemer04c7c222016-07-18 06:11:37 +0000137 VNtoScalars[{V, InvalidVN}].push_back(I);
Sebastian Pop41774802016-07-15 13:45:20 +0000138 }
139
140 const VNtoInsns &getVNTable() const { return VNtoScalars; }
141};
142
143// Records all load instructions candidate for code hoisting.
144class LoadInfo {
145 VNtoInsns VNtoLoads;
146
147public:
148 // Insert Load and the value number of its memory address in VNtoLoads.
149 void insert(LoadInst *Load, GVN::ValueTable &VN) {
150 if (Load->isSimple()) {
151 unsigned V = VN.lookupOrAdd(Load->getPointerOperand());
David Majnemer04c7c222016-07-18 06:11:37 +0000152 VNtoLoads[{V, InvalidVN}].push_back(Load);
Sebastian Pop41774802016-07-15 13:45:20 +0000153 }
154 }
155
156 const VNtoInsns &getVNTable() const { return VNtoLoads; }
157};
158
159// Records all store instructions candidate for code hoisting.
160class StoreInfo {
161 VNtoInsns VNtoStores;
162
163public:
164 // Insert the Store and a hash number of the store address and the stored
165 // value in VNtoStores.
166 void insert(StoreInst *Store, GVN::ValueTable &VN) {
167 if (!Store->isSimple())
168 return;
169 // Hash the store address and the stored value.
170 Value *Ptr = Store->getPointerOperand();
171 Value *Val = Store->getValueOperand();
David Majnemer04c7c222016-07-18 06:11:37 +0000172 VNtoStores[{VN.lookupOrAdd(Ptr), VN.lookupOrAdd(Val)}].push_back(Store);
Sebastian Pop41774802016-07-15 13:45:20 +0000173 }
174
175 const VNtoInsns &getVNTable() const { return VNtoStores; }
176};
177
178// Records all call instructions candidate for code hoisting.
179class CallInfo {
180 VNtoInsns VNtoCallsScalars;
181 VNtoInsns VNtoCallsLoads;
182 VNtoInsns VNtoCallsStores;
183
184public:
185 // Insert Call and its value numbering in one of the VNtoCalls* containers.
186 void insert(CallInst *Call, GVN::ValueTable &VN) {
187 // A call that doesNotAccessMemory is handled as a Scalar,
188 // onlyReadsMemory will be handled as a Load instruction,
189 // all other calls will be handled as stores.
190 unsigned V = VN.lookupOrAdd(Call);
David Majnemer04c7c222016-07-18 06:11:37 +0000191 auto Entry = std::make_pair(V, InvalidVN);
Sebastian Pop41774802016-07-15 13:45:20 +0000192
193 if (Call->doesNotAccessMemory())
David Majnemer04c7c222016-07-18 06:11:37 +0000194 VNtoCallsScalars[Entry].push_back(Call);
Sebastian Pop41774802016-07-15 13:45:20 +0000195 else if (Call->onlyReadsMemory())
David Majnemer04c7c222016-07-18 06:11:37 +0000196 VNtoCallsLoads[Entry].push_back(Call);
Sebastian Pop41774802016-07-15 13:45:20 +0000197 else
David Majnemer04c7c222016-07-18 06:11:37 +0000198 VNtoCallsStores[Entry].push_back(Call);
Sebastian Pop41774802016-07-15 13:45:20 +0000199 }
200
201 const VNtoInsns &getScalarVNTable() const { return VNtoCallsScalars; }
202
203 const VNtoInsns &getLoadVNTable() const { return VNtoCallsLoads; }
204
205 const VNtoInsns &getStoreVNTable() const { return VNtoCallsStores; }
206};
207
David Majnemer68623a02016-07-25 02:21:25 +0000208static void combineKnownMetadata(Instruction *ReplInst, Instruction *I) {
209 static const unsigned KnownIDs[] = {
210 LLVMContext::MD_tbaa, LLVMContext::MD_alias_scope,
211 LLVMContext::MD_noalias, LLVMContext::MD_range,
212 LLVMContext::MD_fpmath, LLVMContext::MD_invariant_load,
213 LLVMContext::MD_invariant_group};
214 combineMetadata(ReplInst, I, KnownIDs);
215}
216
Sebastian Pop41774802016-07-15 13:45:20 +0000217// This pass hoists common computations across branches sharing common
218// dominator. The primary goal is to reduce the code size, and in some
219// cases reduce critical path (by exposing more ILP).
220class GVNHoist {
221public:
Aditya Kumardfa87412017-09-13 05:28:03 +0000222 GVNHoist(DominatorTree *DT, PostDominatorTree *PDT, AliasAnalysis *AA,
223 MemoryDependenceResults *MD, MemorySSA *MSSA)
224 : DT(DT), PDT(PDT), AA(AA), MD(MD), MSSA(MSSA),
Daniel Berlin17e8d0e2017-02-22 22:19:55 +0000225 MSSAUpdater(make_unique<MemorySSAUpdater>(MSSA)),
Aditya Kumardfa87412017-09-13 05:28:03 +0000226 HoistingGeps(false) {}
Aditya Kumar07cb3042016-11-29 14:34:01 +0000227
Daniel Berlin65af45d2016-07-25 17:24:22 +0000228 bool run(Function &F) {
Aditya Kumardfa87412017-09-13 05:28:03 +0000229 NumFuncArgs = F.arg_size();
Daniel Berlin65af45d2016-07-25 17:24:22 +0000230 VN.setDomTree(DT);
231 VN.setAliasAnalysis(AA);
232 VN.setMemDep(MD);
233 bool Res = false;
Sebastian Pop4ba7c882016-08-03 20:54:36 +0000234 // Perform DFS Numbering of instructions.
235 unsigned BBI = 0;
236 for (const BasicBlock *BB : depth_first(&F.getEntryBlock())) {
237 DFSNumber[BB] = ++BBI;
238 unsigned I = 0;
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000239 for (auto &Inst : *BB)
Sebastian Pop4ba7c882016-08-03 20:54:36 +0000240 DFSNumber[&Inst] = ++I;
241 }
Daniel Berlin65af45d2016-07-25 17:24:22 +0000242
Sebastian Pop2aadad72016-08-03 20:54:38 +0000243 int ChainLength = 0;
244
Daniel Berlin65af45d2016-07-25 17:24:22 +0000245 // FIXME: use lazy evaluation of VN to avoid the fix-point computation.
246 while (1) {
Sebastian Pop2aadad72016-08-03 20:54:38 +0000247 if (MaxChainLength != -1 && ++ChainLength >= MaxChainLength)
248 return Res;
249
Daniel Berlin65af45d2016-07-25 17:24:22 +0000250 auto HoistStat = hoistExpressions(F);
Sebastian Pop5d3822f2016-08-03 20:54:33 +0000251 if (HoistStat.first + HoistStat.second == 0)
Daniel Berlin65af45d2016-07-25 17:24:22 +0000252 return Res;
Sebastian Pop5d3822f2016-08-03 20:54:33 +0000253
254 if (HoistStat.second > 0)
Daniel Berlin65af45d2016-07-25 17:24:22 +0000255 // To address a limitation of the current GVN, we need to rerun the
Sebastian Pop5d3822f2016-08-03 20:54:33 +0000256 // hoisting after we hoisted loads or stores in order to be able to
257 // hoist all scalars dependent on the hoisted ld/st.
Daniel Berlin65af45d2016-07-25 17:24:22 +0000258 VN.clear();
Sebastian Pop5d3822f2016-08-03 20:54:33 +0000259
Daniel Berlin65af45d2016-07-25 17:24:22 +0000260 Res = true;
261 }
262
263 return Res;
264 }
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000265
Aditya Kumardfa87412017-09-13 05:28:03 +0000266 // Copied from NewGVN.cpp
267 // This function provides global ranking of operations so that we can place
268 // them in a canonical order. Note that rank alone is not necessarily enough
269 // for a complete ordering, as constants all have the same rank. However,
270 // generally, we will simplify an operation with all constants so that it
271 // doesn't matter what order they appear in.
272 unsigned int rank(const Value *V) const {
273 // Prefer constants to undef to anything else
274 // Undef is a constant, have to check it first.
275 // Prefer smaller constants to constantexprs
276 if (isa<ConstantExpr>(V))
277 return 2;
278 if (isa<UndefValue>(V))
279 return 1;
280 if (isa<Constant>(V))
281 return 0;
282 else if (auto *A = dyn_cast<Argument>(V))
283 return 3 + A->getArgNo();
284
285 // Need to shift the instruction DFS by number of arguments + 3 to account
286 // for the constant and argument ranking above.
287 auto Result = DFSNumber.lookup(V);
288 if (Result > 0)
289 return 4 + NumFuncArgs + Result;
290 // Unreachable or something else, just return a really large number.
291 return ~0;
292 }
293
Daniel Berlin65af45d2016-07-25 17:24:22 +0000294private:
Sebastian Pop41774802016-07-15 13:45:20 +0000295 GVN::ValueTable VN;
296 DominatorTree *DT;
Aditya Kumardfa87412017-09-13 05:28:03 +0000297 PostDominatorTree *PDT;
Sebastian Pop41774802016-07-15 13:45:20 +0000298 AliasAnalysis *AA;
299 MemoryDependenceResults *MD;
Daniel Berlinea02eee2016-08-23 05:42:41 +0000300 MemorySSA *MSSA;
Daniel Berlin17e8d0e2017-02-22 22:19:55 +0000301 std::unique_ptr<MemorySSAUpdater> MSSAUpdater;
Sebastian Pop91d4a302016-07-26 00:15:10 +0000302 DenseMap<const Value *, unsigned> DFSNumber;
Sebastian Pop41774802016-07-15 13:45:20 +0000303 BBSideEffectsSet BBSideEffects;
Aditya Kumardfa87412017-09-13 05:28:03 +0000304 DenseSet<const BasicBlock *> HoistBarrier;
305
306 SmallVector<BasicBlock *, 32> IDFBlocks;
307 unsigned NumFuncArgs;
308 const bool HoistingGeps;
David Majnemeraa241782016-07-18 00:35:01 +0000309
Sebastian Pop41774802016-07-15 13:45:20 +0000310 enum InsKind { Unknown, Scalar, Load, Store };
311
Sebastian Pop41774802016-07-15 13:45:20 +0000312 // Return true when there are exception handling in BB.
313 bool hasEH(const BasicBlock *BB) {
314 auto It = BBSideEffects.find(BB);
315 if (It != BBSideEffects.end())
316 return It->second;
317
318 if (BB->isEHPad() || BB->hasAddressTaken()) {
319 BBSideEffects[BB] = true;
320 return true;
321 }
322
323 if (BB->getTerminator()->mayThrow()) {
324 BBSideEffects[BB] = true;
325 return true;
326 }
327
328 BBSideEffects[BB] = false;
329 return false;
330 }
331
Sebastian Pop5f0d0e62016-08-25 11:55:47 +0000332 // Return true when a successor of BB dominates A.
333 bool successorDominate(const BasicBlock *BB, const BasicBlock *A) {
334 for (const BasicBlock *Succ : BB->getTerminator()->successors())
335 if (DT->dominates(Succ, A))
336 return true;
Sebastian Pop41774802016-07-15 13:45:20 +0000337
Sebastian Pop5f0d0e62016-08-25 11:55:47 +0000338 return false;
339 }
340
Sebastian Pop41774802016-07-15 13:45:20 +0000341 /* Return true when I1 appears before I2 in the instructions of BB. */
Sebastian Pop91d4a302016-07-26 00:15:10 +0000342 bool firstInBB(const Instruction *I1, const Instruction *I2) {
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000343 assert(I1->getParent() == I2->getParent());
Sebastian Pop91d4a302016-07-26 00:15:10 +0000344 unsigned I1DFS = DFSNumber.lookup(I1);
345 unsigned I2DFS = DFSNumber.lookup(I2);
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000346 assert(I1DFS && I2DFS);
Sebastian Pop91d4a302016-07-26 00:15:10 +0000347 return I1DFS < I2DFS;
Daniel Berlin40765a62016-07-25 18:19:49 +0000348 }
Sebastian Pop91d4a302016-07-26 00:15:10 +0000349
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000350 // Return true when there are memory uses of Def in BB.
351 bool hasMemoryUse(const Instruction *NewPt, MemoryDef *Def,
352 const BasicBlock *BB) {
353 const MemorySSA::AccessList *Acc = MSSA->getBlockAccesses(BB);
354 if (!Acc)
355 return false;
356
357 Instruction *OldPt = Def->getMemoryInst();
Sebastian Pop41774802016-07-15 13:45:20 +0000358 const BasicBlock *OldBB = OldPt->getParent();
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000359 const BasicBlock *NewBB = NewPt->getParent();
360 bool ReachedNewPt = false;
Sebastian Pop41774802016-07-15 13:45:20 +0000361
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000362 for (const MemoryAccess &MA : *Acc)
363 if (const MemoryUse *MU = dyn_cast<MemoryUse>(&MA)) {
364 Instruction *Insn = MU->getMemoryInst();
Sebastian Pop1531f302016-09-22 17:22:58 +0000365
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000366 // Do not check whether MU aliases Def when MU occurs after OldPt.
367 if (BB == OldBB && firstInBB(OldPt, Insn))
368 break;
369
370 // Do not check whether MU aliases Def when MU occurs before NewPt.
371 if (BB == NewBB) {
372 if (!ReachedNewPt) {
373 if (firstInBB(Insn, NewPt))
374 continue;
375 ReachedNewPt = true;
376 }
Sebastian Pop41774802016-07-15 13:45:20 +0000377 }
Daniel Berlindcb004f2017-03-02 23:06:46 +0000378 if (MemorySSAUtil::defClobbersUseOrDef(Def, MU, *AA))
Hans Wennborgc7957ef2016-09-22 21:20:53 +0000379 return true;
380 }
Sebastian Pop8e6e3312016-09-22 15:33:51 +0000381
Sebastian Pop41774802016-07-15 13:45:20 +0000382 return false;
383 }
384
Davide Italiano32504cf2017-09-05 20:49:41 +0000385 bool hasEHhelper(const BasicBlock *BB, const BasicBlock *SrcBB,
386 int &NBBsOnAllPaths) {
387 // Stop walk once the limit is reached.
388 if (NBBsOnAllPaths == 0)
389 return true;
390
391 // Impossible to hoist with exceptions on the path.
392 if (hasEH(BB))
393 return true;
394
395 // No such instruction after HoistBarrier in a basic block was
396 // selected for hoisting so instructions selected within basic block with
397 // a hoist barrier can be hoisted.
398 if ((BB != SrcBB) && HoistBarrier.count(BB))
399 return true;
400
401 return false;
402 }
403
Sebastian Pop41774802016-07-15 13:45:20 +0000404 // Return true when there are exception handling or loads of memory Def
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000405 // between Def and NewPt. This function is only called for stores: Def is
406 // the MemoryDef of the store to be hoisted.
Sebastian Pop41774802016-07-15 13:45:20 +0000407
408 // Decrement by 1 NBBsOnAllPaths for each block between HoistPt and BB, and
409 // return true when the counter NBBsOnAllPaths reaces 0, except when it is
410 // initialized to -1 which is unlimited.
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000411 bool hasEHOrLoadsOnPath(const Instruction *NewPt, MemoryDef *Def,
412 int &NBBsOnAllPaths) {
Sebastian Pop41774802016-07-15 13:45:20 +0000413 const BasicBlock *NewBB = NewPt->getParent();
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000414 const BasicBlock *OldBB = Def->getBlock();
Sebastian Pop41774802016-07-15 13:45:20 +0000415 assert(DT->dominates(NewBB, OldBB) && "invalid path");
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000416 assert(DT->dominates(Def->getDefiningAccess()->getBlock(), NewBB) &&
Sebastian Pop41774802016-07-15 13:45:20 +0000417 "def does not dominate new hoisting point");
418
419 // Walk all basic blocks reachable in depth-first iteration on the inverse
420 // CFG from OldBB to NewBB. These blocks are all the blocks that may be
421 // executed between the execution of NewBB and OldBB. Hoisting an expression
422 // from OldBB into NewBB has to be safe on all execution paths.
423 for (auto I = idf_begin(OldBB), E = idf_end(OldBB); I != E;) {
Geoff Berry635e5052017-04-10 20:45:17 +0000424 const BasicBlock *BB = *I;
425 if (BB == NewBB) {
Sebastian Pop41774802016-07-15 13:45:20 +0000426 // Stop traversal when reaching HoistPt.
427 I.skipChildren();
428 continue;
429 }
430
Davide Italiano32504cf2017-09-05 20:49:41 +0000431 if (hasEHhelper(BB, OldBB, NBBsOnAllPaths))
Sebastian Pop41774802016-07-15 13:45:20 +0000432 return true;
433
434 // Check that we do not move a store past loads.
Geoff Berry635e5052017-04-10 20:45:17 +0000435 if (hasMemoryUse(NewPt, Def, BB))
Sebastian Pop41774802016-07-15 13:45:20 +0000436 return true;
437
Sebastian Pop41774802016-07-15 13:45:20 +0000438 // -1 is unlimited number of blocks on all paths.
439 if (NBBsOnAllPaths != -1)
440 --NBBsOnAllPaths;
441
442 ++I;
443 }
444
445 return false;
446 }
447
448 // Return true when there are exception handling between HoistPt and BB.
449 // Decrement by 1 NBBsOnAllPaths for each block between HoistPt and BB, and
450 // return true when the counter NBBsOnAllPaths reaches 0, except when it is
451 // initialized to -1 which is unlimited.
Geoff Berry635e5052017-04-10 20:45:17 +0000452 bool hasEHOnPath(const BasicBlock *HoistPt, const BasicBlock *SrcBB,
Sebastian Pop41774802016-07-15 13:45:20 +0000453 int &NBBsOnAllPaths) {
Geoff Berry635e5052017-04-10 20:45:17 +0000454 assert(DT->dominates(HoistPt, SrcBB) && "Invalid path");
Sebastian Pop41774802016-07-15 13:45:20 +0000455
456 // Walk all basic blocks reachable in depth-first iteration on
457 // the inverse CFG from BBInsn to NewHoistPt. These blocks are all the
458 // blocks that may be executed between the execution of NewHoistPt and
459 // BBInsn. Hoisting an expression from BBInsn into NewHoistPt has to be safe
460 // on all execution paths.
Geoff Berry635e5052017-04-10 20:45:17 +0000461 for (auto I = idf_begin(SrcBB), E = idf_end(SrcBB); I != E;) {
462 const BasicBlock *BB = *I;
463 if (BB == HoistPt) {
Sebastian Pop41774802016-07-15 13:45:20 +0000464 // Stop traversal when reaching NewHoistPt.
465 I.skipChildren();
466 continue;
467 }
468
Davide Italiano32504cf2017-09-05 20:49:41 +0000469 if (hasEHhelper(BB, SrcBB, NBBsOnAllPaths))
Aditya Kumar314ebe02016-11-29 14:36:27 +0000470 return true;
471
Sebastian Pop41774802016-07-15 13:45:20 +0000472 // -1 is unlimited number of blocks on all paths.
473 if (NBBsOnAllPaths != -1)
474 --NBBsOnAllPaths;
475
476 ++I;
477 }
478
479 return false;
480 }
481
482 // Return true when it is safe to hoist a memory load or store U from OldPt
483 // to NewPt.
484 bool safeToHoistLdSt(const Instruction *NewPt, const Instruction *OldPt,
485 MemoryUseOrDef *U, InsKind K, int &NBBsOnAllPaths) {
486
487 // In place hoisting is safe.
488 if (NewPt == OldPt)
489 return true;
490
491 const BasicBlock *NewBB = NewPt->getParent();
492 const BasicBlock *OldBB = OldPt->getParent();
493 const BasicBlock *UBB = U->getBlock();
494
495 // Check for dependences on the Memory SSA.
496 MemoryAccess *D = U->getDefiningAccess();
497 BasicBlock *DBB = D->getBlock();
498 if (DT->properlyDominates(NewBB, DBB))
499 // Cannot move the load or store to NewBB above its definition in DBB.
500 return false;
501
502 if (NewBB == DBB && !MSSA->isLiveOnEntryDef(D))
David Majnemer4c66a712016-07-18 00:34:58 +0000503 if (auto *UD = dyn_cast<MemoryUseOrDef>(D))
Sebastian Pop91d4a302016-07-26 00:15:10 +0000504 if (firstInBB(NewPt, UD->getMemoryInst()))
Sebastian Pop41774802016-07-15 13:45:20 +0000505 // Cannot move the load or store to NewPt above its definition in D.
506 return false;
507
508 // Check for unsafe hoistings due to side effects.
509 if (K == InsKind::Store) {
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000510 if (hasEHOrLoadsOnPath(NewPt, dyn_cast<MemoryDef>(U), NBBsOnAllPaths))
Sebastian Pop41774802016-07-15 13:45:20 +0000511 return false;
512 } else if (hasEHOnPath(NewBB, OldBB, NBBsOnAllPaths))
513 return false;
514
515 if (UBB == NewBB) {
516 if (DT->properlyDominates(DBB, NewBB))
517 return true;
518 assert(UBB == DBB);
519 assert(MSSA->locallyDominates(D, U));
520 }
521
522 // No side effects: it is safe to hoist.
523 return true;
524 }
525
Sebastian Pop5f0d0e62016-08-25 11:55:47 +0000526 // Return true when it is safe to hoist scalar instructions from all blocks in
527 // WL to HoistBB.
Aditya Kumardfa87412017-09-13 05:28:03 +0000528 bool safeToHoistScalar(const BasicBlock *HoistBB, const BasicBlock *BB,
Sebastian Pop5f0d0e62016-08-25 11:55:47 +0000529 int &NBBsOnAllPaths) {
Aditya Kumardfa87412017-09-13 05:28:03 +0000530 return !hasEHOnPath(HoistBB, BB, NBBsOnAllPaths);
531 }
Sebastian Pop41774802016-07-15 13:45:20 +0000532
Aditya Kumardfa87412017-09-13 05:28:03 +0000533 // In the inverse CFG, the dominance frontier of basic block (BB) is the
534 // point where ANTIC needs to be computed for instructions which are going
535 // to be hoisted. Since this point does not change during gvn-hoist,
536 // we compute it only once (on demand).
537 // The ides is inspired from:
538 // "Partial Redundancy Elimination in SSA Form"
539 // ROBERT KENNEDY, SUN CHAN, SHIN-MING LIU, RAYMOND LO, PENG TU and FRED CHOW
540 // They use similar idea in the forward graph to to find fully redundant and
541 // partially redundant expressions, here it is used in the inverse graph to
542 // find fully anticipable instructions at merge point (post-dominator in
543 // the inverse CFG).
544 // Returns the edge via which an instruction in BB will get the values from.
545
546 // Returns true when the values are flowing out to each edge.
547 bool valueAnticipable(CHIArgs C, TerminatorInst *TI) const {
548 if (TI->getNumSuccessors() > std::distance(C.begin(), C.end()))
549 return false; // Not enough args in this CHI.
550
551 for (auto CHI : C) {
552 BasicBlock *Dest = CHI.Dest;
553 // Find if all the edges have values flowing out of BB.
554 bool Found = any_of(TI->successors(), [Dest](const BasicBlock *BB) {
555 return BB == Dest; });
556 if (!Found)
Sebastian Pop5f0d0e62016-08-25 11:55:47 +0000557 return false;
Aditya Kumardfa87412017-09-13 05:28:03 +0000558 }
Sebastian Pop41774802016-07-15 13:45:20 +0000559 return true;
560 }
561
Aditya Kumardfa87412017-09-13 05:28:03 +0000562 // Check if it is safe to hoist values tracked by CHI in the range
563 // [Begin, End) and accumulate them in Safe.
564 void checkSafety(CHIArgs C, BasicBlock *BB, InsKind K,
565 SmallVectorImpl<CHIArg> &Safe) {
Aditya Kumar314ebe02016-11-29 14:36:27 +0000566 int NumBBsOnAllPaths = MaxNumberOfBBSInPath;
Aditya Kumardfa87412017-09-13 05:28:03 +0000567 for (auto CHI : C) {
568 Instruction *Insn = CHI.I;
569 if (!Insn) // No instruction was inserted in this CHI.
570 continue;
Sebastian Pop41774802016-07-15 13:45:20 +0000571 if (K == InsKind::Scalar) {
Aditya Kumardfa87412017-09-13 05:28:03 +0000572 if (safeToHoistScalar(BB, Insn->getParent(), NumBBsOnAllPaths))
573 Safe.push_back(CHI);
Sebastian Pop41774802016-07-15 13:45:20 +0000574 } else {
Aditya Kumardfa87412017-09-13 05:28:03 +0000575 MemoryUseOrDef *UD = MSSA->getMemoryAccess(Insn);
576 if (safeToHoistLdSt(BB->getTerminator(), Insn, UD, K, NumBBsOnAllPaths))
577 Safe.push_back(CHI);
Sebastian Pop41774802016-07-15 13:45:20 +0000578 }
Sebastian Pop41774802016-07-15 13:45:20 +0000579 }
Sebastian Pop41774802016-07-15 13:45:20 +0000580 }
581
Aditya Kumardfa87412017-09-13 05:28:03 +0000582 typedef DenseMap<VNType, SmallVector<Instruction *, 2>> RenameStackType;
583 // Push all the VNs corresponding to BB into RenameStack.
584 void fillRenameStack(BasicBlock *BB, InValuesType &ValueBBs,
585 RenameStackType &RenameStack) {
586 auto it1 = ValueBBs.find(BB);
587 if (it1 != ValueBBs.end()) {
588 // Iterate in reverse order to keep lower ranked values on the top.
589 for (std::pair<VNType, Instruction *> &VI : reverse(it1->second)) {
590 // Get the value of instruction I
591 DEBUG(dbgs() << "\nPushing on stack: " << *VI.second);
592 RenameStack[VI.first].push_back(VI.second);
593 }
594 }
595 }
Sebastian Pop41774802016-07-15 13:45:20 +0000596
Aditya Kumardfa87412017-09-13 05:28:03 +0000597 void fillChiArgs(BasicBlock *BB, OutValuesType &CHIBBs,
598 RenameStackType &RenameStack) {
599 // For each *predecessor* (because Post-DOM) of BB check if it has a CHI
600 for (auto Pred : predecessors(BB)) {
601 auto P = CHIBBs.find(Pred);
602 if (P == CHIBBs.end()) {
603 continue;
604 }
605 DEBUG(dbgs() << "\nLooking at CHIs in: " << Pred->getName(););
606 // A CHI is found (BB -> Pred is an edge in the CFG)
607 // Pop the stack until Top(V) = Ve.
608 auto &VCHI = P->second;
609 for (auto It = VCHI.begin(), E = VCHI.end(); It != E;) {
610 CHIArg &C = *It;
611 if (!C.Dest) {
612 auto si = RenameStack.find(C.VN);
613 // The Basic Block where CHI is must dominate the value we want to
614 // track in a CHI. In the PDom walk, there can be values in the
615 // stack which are not control dependent e.g., nested loop.
616 if (si != RenameStack.end() && si->second.size() &&
617 DT->dominates(Pred, si->second.back()->getParent())) {
618 C.Dest = BB; // Assign the edge
619 C.I = si->second.pop_back_val(); // Assign the argument
620 DEBUG(dbgs() << "\nCHI Inserted in BB: " << C.Dest->getName()
621 << *C.I << ", VN: " << C.VN.first << ", "
622 << C.VN.second);
623 }
624 // Move to next CHI of a different value
625 It = std::find_if(It, VCHI.end(),
626 [It](CHIArg &A) { return A != *It; });
627 } else
628 ++It;
629 }
630 }
631 }
632
633 // Walk the post-dominator tree top-down and use a stack for each value to
634 // store the last value you see. When you hit a CHI from a given edge, the
635 // value to use as the argument is at the top of the stack, add the value to
636 // CHI and pop.
637 void insertCHI(InValuesType &ValueBBs, OutValuesType &CHIBBs) {
638 auto Root = PDT->getNode(nullptr);
639 if (!Root)
640 return;
641 // Depth first walk on PDom tree to fill the CHIargs at each PDF.
642 RenameStackType RenameStack;
643 for (auto Node : depth_first(Root)) {
644 BasicBlock *BB = Node->getBlock();
645 if (!BB)
Sebastian Pop41774802016-07-15 13:45:20 +0000646 continue;
647
Aditya Kumardfa87412017-09-13 05:28:03 +0000648 // Collect all values in BB and push to stack.
649 fillRenameStack(BB, ValueBBs, RenameStack);
Sebastian Pop41774802016-07-15 13:45:20 +0000650
Aditya Kumardfa87412017-09-13 05:28:03 +0000651 // Fill outgoing values in each CHI corresponding to BB.
652 fillChiArgs(BB, CHIBBs, RenameStack);
Sebastian Pop41774802016-07-15 13:45:20 +0000653 }
654 }
655
Aditya Kumardfa87412017-09-13 05:28:03 +0000656 // Walk all the CHI-nodes to find ones which have a empty-entry and remove
657 // them Then collect all the instructions which are safe to hoist and see if
658 // they form a list of anticipable values. OutValues contains CHIs
659 // corresponding to each basic block.
660 void findHoistableCandidates(OutValuesType &CHIBBs, InsKind K,
661 HoistingPointList &HPL) {
662 auto cmpVN = [](const CHIArg &A, const CHIArg &B) { return A.VN < B.VN; };
663
664 // CHIArgs now have the outgoing values, so check for anticipability and
665 // accumulate hoistable candidates in HPL.
666 for (std::pair<BasicBlock *, SmallVector<CHIArg, 2>> &A : CHIBBs) {
667 BasicBlock *BB = A.first;
668 SmallVectorImpl<CHIArg> &CHIs = A.second;
669 // Vector of PHIs contains PHIs for different instructions.
670 // Sort the args according to their VNs, such that identical
671 // instructions are together.
672 std::sort(CHIs.begin(), CHIs.end(), cmpVN);
673 auto TI = BB->getTerminator();
674 auto B = CHIs.begin();
675 // [PreIt, PHIIt) form a range of CHIs which have identical VNs.
676 auto PHIIt = std::find_if(CHIs.begin(), CHIs.end(),
677 [B](CHIArg &A) { return A != *B; });
678 auto PrevIt = CHIs.begin();
679 while (PrevIt != PHIIt) {
680 // Collect values which satisfy safety checks.
681 SmallVector<CHIArg, 2> Safe;
682 // We check for safety first because there might be multiple values in
683 // the same path, some of which are not safe to be hoisted, but overall
684 // each edge has at least one value which can be hoisted, making the
685 // value anticipable along that path.
686 checkSafety(make_range(PrevIt, PHIIt), BB, K, Safe);
687
688 // List of safe values should be anticipable at TI.
689 if (valueAnticipable(make_range(Safe.begin(), Safe.end()), TI)) {
690 HPL.push_back({BB, SmallVecInsn()});
691 SmallVecInsn &V = HPL.back().second;
692 for (auto B : Safe)
693 V.push_back(B.I);
694 }
695
696 // Check other VNs
697 PrevIt = PHIIt;
698 PHIIt = std::find_if(PrevIt, CHIs.end(),
699 [PrevIt](CHIArg &A) { return A != *PrevIt; });
700 }
701 }
702 }
703
704 // Compute insertion points for each values which can be fully anticipated at
705 // a dominator. HPL contains all such values.
706 void computeInsertionPoints(const VNtoInsns &Map, HoistingPointList &HPL,
707 InsKind K) {
708 // Sort VNs based on their rankings
709 std::vector<VNType> Ranks;
710 for (const auto &Entry : Map) {
711 Ranks.push_back(Entry.first);
712 }
713
714 // TODO: Remove fully-redundant expressions.
715 // Get instruction from the Map, assume that all the Instructions
716 // with same VNs have same rank (this is an approximation).
717 std::sort(Ranks.begin(), Ranks.end(),
718 [this, &Map](const VNType &r1, const VNType &r2) {
719 return (rank(*Map.lookup(r1).begin()) <
720 rank(*Map.lookup(r2).begin()));
721 });
722
723 // - Sort VNs according to their rank, and start with lowest ranked VN
724 // - Take a VN and for each instruction with same VN
725 // - Find the dominance frontier in the inverse graph (PDF)
726 // - Insert the chi-node at PDF
727 // - Remove the chi-nodes with missing entries
728 // - Remove values from CHI-nodes which do not truly flow out, e.g.,
729 // modified along the path.
730 // - Collect the remaining values that are still anticipable
731 SmallVector<BasicBlock *, 2> IDFBlocks;
732 ReverseIDFCalculator IDFs(*PDT);
733 OutValuesType OutValue;
734 InValuesType InValue;
735 for (const auto &R : Ranks) {
736 const SmallVecInsn &V = Map.lookup(R);
737 if (V.size() < 2)
738 continue;
739 const VNType &VN = R;
740 SmallPtrSet<BasicBlock *, 2> VNBlocks;
741 for (auto &I : V) {
742 BasicBlock *BBI = I->getParent();
743 if (!hasEH(BBI))
744 VNBlocks.insert(BBI);
745 }
746 // Compute the Post Dominance Frontiers of each basic block
747 // The dominance frontier of a live block X in the reverse
748 // control graph is the set of blocks upon which X is control
749 // dependent. The following sequence computes the set of blocks
750 // which currently have dead terminators that are control
751 // dependence sources of a block which is in NewLiveBlocks.
752 IDFs.setDefiningBlocks(VNBlocks);
753 IDFs.calculate(IDFBlocks);
754
755 // Make a map of BB vs instructions to be hoisted.
756 for (unsigned i = 0; i < V.size(); ++i) {
757 InValue[V[i]->getParent()].push_back(std::make_pair(VN, V[i]));
758 }
759 // Insert empty CHI node for this VN. This is used to factor out
760 // basic blocks where the ANTIC can potentially change.
761 for (auto IDFB : IDFBlocks) { // TODO: Prune out useless CHI insertions.
762 for (unsigned i = 0; i < V.size(); ++i) {
763 CHIArg C = {VN, nullptr, nullptr};
764 if (DT->dominates(IDFB, V[i]->getParent())) { // Ignore spurious PDFs.
765 // InValue[V[i]->getParent()].push_back(std::make_pair(VN, V[i]));
766 OutValue[IDFB].push_back(C);
767 DEBUG(dbgs() << "\nInsertion a CHI for BB: " << IDFB->getName()
768 << ", for Insn: " << *V[i]);
769 }
770 }
771 }
772 }
773
774 // Insert CHI args at each PDF to iterate on factored graph of
775 // control dependence.
776 insertCHI(InValue, OutValue);
777 // Using the CHI args inserted at each PDF, find fully anticipable values.
778 findHoistableCandidates(OutValue, K, HPL);
779 }
780
Sebastian Pop41774802016-07-15 13:45:20 +0000781 // Return true when all operands of Instr are available at insertion point
782 // HoistPt. When limiting the number of hoisted expressions, one could hoist
783 // a load without hoisting its access function. So before hoisting any
784 // expression, make sure that all its operands are available at insert point.
785 bool allOperandsAvailable(const Instruction *I,
786 const BasicBlock *HoistPt) const {
David Majnemer4c66a712016-07-18 00:34:58 +0000787 for (const Use &Op : I->operands())
788 if (const auto *Inst = dyn_cast<Instruction>(&Op))
789 if (!DT->dominates(Inst->getParent(), HoistPt))
790 return false;
Sebastian Pop41774802016-07-15 13:45:20 +0000791
792 return true;
793 }
794
Sebastian Pop55c30072016-07-27 05:48:12 +0000795 // Same as allOperandsAvailable with recursive check for GEP operands.
796 bool allGepOperandsAvailable(const Instruction *I,
797 const BasicBlock *HoistPt) const {
798 for (const Use &Op : I->operands())
799 if (const auto *Inst = dyn_cast<Instruction>(&Op))
800 if (!DT->dominates(Inst->getParent(), HoistPt)) {
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000801 if (const GetElementPtrInst *GepOp =
802 dyn_cast<GetElementPtrInst>(Inst)) {
Sebastian Pop55c30072016-07-27 05:48:12 +0000803 if (!allGepOperandsAvailable(GepOp, HoistPt))
804 return false;
805 // Gep is available if all operands of GepOp are available.
806 } else {
807 // Gep is not available if it has operands other than GEPs that are
808 // defined in blocks not dominating HoistPt.
809 return false;
810 }
811 }
812 return true;
813 }
814
815 // Make all operands of the GEP available.
816 void makeGepsAvailable(Instruction *Repl, BasicBlock *HoistPt,
817 const SmallVecInsn &InstructionsToHoist,
818 Instruction *Gep) const {
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000819 assert(allGepOperandsAvailable(Gep, HoistPt) &&
820 "GEP operands not available");
Sebastian Pop55c30072016-07-27 05:48:12 +0000821
822 Instruction *ClonedGep = Gep->clone();
823 for (unsigned i = 0, e = Gep->getNumOperands(); i != e; ++i)
824 if (Instruction *Op = dyn_cast<Instruction>(Gep->getOperand(i))) {
825
826 // Check whether the operand is already available.
827 if (DT->dominates(Op->getParent(), HoistPt))
828 continue;
829
830 // As a GEP can refer to other GEPs, recursively make all the operands
831 // of this GEP available at HoistPt.
832 if (GetElementPtrInst *GepOp = dyn_cast<GetElementPtrInst>(Op))
833 makeGepsAvailable(ClonedGep, HoistPt, InstructionsToHoist, GepOp);
834 }
835
836 // Copy Gep and replace its uses in Repl with ClonedGep.
837 ClonedGep->insertBefore(HoistPt->getTerminator());
838
839 // Conservatively discard any optimization hints, they may differ on the
840 // other paths.
841 ClonedGep->dropUnknownNonDebugMetadata();
842
843 // If we have optimization hints which agree with each other along different
844 // paths, preserve them.
845 for (const Instruction *OtherInst : InstructionsToHoist) {
846 const GetElementPtrInst *OtherGep;
847 if (auto *OtherLd = dyn_cast<LoadInst>(OtherInst))
848 OtherGep = cast<GetElementPtrInst>(OtherLd->getPointerOperand());
849 else
850 OtherGep = cast<GetElementPtrInst>(
851 cast<StoreInst>(OtherInst)->getPointerOperand());
Peter Collingbourne8f1dd5c2016-09-07 23:39:04 +0000852 ClonedGep->andIRFlags(OtherGep);
Sebastian Pop55c30072016-07-27 05:48:12 +0000853 }
854
855 // Replace uses of Gep with ClonedGep in Repl.
856 Repl->replaceUsesOfWith(Gep, ClonedGep);
857 }
858
Aditya Kumardfa87412017-09-13 05:28:03 +0000859 void updateAlignment(Instruction *I, Instruction *Repl) {
860 if (auto *ReplacementLoad = dyn_cast<LoadInst>(Repl)) {
861 ReplacementLoad->setAlignment(
862 std::min(ReplacementLoad->getAlignment(),
863 cast<LoadInst>(I)->getAlignment()));
864 ++NumLoadsRemoved;
865 } else if (auto *ReplacementStore = dyn_cast<StoreInst>(Repl)) {
866 ReplacementStore->setAlignment(
867 std::min(ReplacementStore->getAlignment(),
868 cast<StoreInst>(I)->getAlignment()));
869 ++NumStoresRemoved;
870 } else if (auto *ReplacementAlloca = dyn_cast<AllocaInst>(Repl)) {
871 ReplacementAlloca->setAlignment(
872 std::max(ReplacementAlloca->getAlignment(),
873 cast<AllocaInst>(I)->getAlignment()));
874 } else if (isa<CallInst>(Repl)) {
875 ++NumCallsRemoved;
876 }
877 }
878
879 // Remove all the instructions in Candidates and replace their usage with Repl.
880 // Returns the number of instructions removed.
881 unsigned rauw(const SmallVecInsn &Candidates, Instruction *Repl,
882 MemoryUseOrDef *NewMemAcc) {
883 unsigned NR = 0;
884 for (Instruction *I : Candidates) {
885 if (I != Repl) {
886 ++NR;
887 updateAlignment(I, Repl);
888 if (NewMemAcc) {
889 // Update the uses of the old MSSA access with NewMemAcc.
890 MemoryAccess *OldMA = MSSA->getMemoryAccess(I);
891 OldMA->replaceAllUsesWith(NewMemAcc);
892 MSSAUpdater->removeMemoryAccess(OldMA);
893 }
894
895 Repl->andIRFlags(I);
896 combineKnownMetadata(Repl, I);
897 I->replaceAllUsesWith(Repl);
898 // Also invalidate the Alias Analysis cache.
899 MD->removeInstruction(I);
900 I->eraseFromParent();
901 }
902 }
903 return NR;
904 }
905
906 // Replace all Memory PHI usage with NewMemAcc.
907 void raMPHIuw(MemoryUseOrDef *NewMemAcc) {
908 SmallPtrSet<MemoryPhi *, 4> UsePhis;
909 for (User *U : NewMemAcc->users())
910 if (MemoryPhi *Phi = dyn_cast<MemoryPhi>(U))
911 UsePhis.insert(Phi);
912
913 for (MemoryPhi *Phi : UsePhis) {
914 auto In = Phi->incoming_values();
915 if (all_of(In, [&](Use &U) { return U == NewMemAcc; })) {
916 Phi->replaceAllUsesWith(NewMemAcc);
917 MSSAUpdater->removeMemoryAccess(Phi);
918 }
919 }
920 }
921
922 // Remove all other instructions and replace them with Repl.
923 unsigned removeAndReplace(const SmallVecInsn &Candidates, Instruction *Repl,
924 BasicBlock *DestBB, bool MoveAccess) {
925 MemoryUseOrDef *NewMemAcc = MSSA->getMemoryAccess(Repl);
926 if (MoveAccess && NewMemAcc) {
927 // The definition of this ld/st will not change: ld/st hoisting is
928 // legal when the ld/st is not moved past its current definition.
929 MSSAUpdater->moveToPlace(NewMemAcc, DestBB, MemorySSA::End);
930 }
931
932 // Replace all other instructions with Repl with memory access NewMemAcc.
933 unsigned NR = rauw(Candidates, Repl, NewMemAcc);
934
935 // Remove MemorySSA phi nodes with the same arguments.
936 if (NewMemAcc)
937 raMPHIuw(NewMemAcc);
938 return NR;
939 }
940
Sebastian Pop55c30072016-07-27 05:48:12 +0000941 // In the case Repl is a load or a store, we make all their GEPs
942 // available: GEPs are not hoisted by default to avoid the address
943 // computations to be hoisted without the associated load or store.
944 bool makeGepOperandsAvailable(Instruction *Repl, BasicBlock *HoistPt,
945 const SmallVecInsn &InstructionsToHoist) const {
Sebastian Pop41774802016-07-15 13:45:20 +0000946 // Check whether the GEP of a ld/st can be synthesized at HoistPt.
David Majnemerbd210122016-07-20 21:05:01 +0000947 GetElementPtrInst *Gep = nullptr;
Sebastian Pop41774802016-07-15 13:45:20 +0000948 Instruction *Val = nullptr;
Sebastian Pop55c30072016-07-27 05:48:12 +0000949 if (auto *Ld = dyn_cast<LoadInst>(Repl)) {
David Majnemerbd210122016-07-20 21:05:01 +0000950 Gep = dyn_cast<GetElementPtrInst>(Ld->getPointerOperand());
Sebastian Pop55c30072016-07-27 05:48:12 +0000951 } else if (auto *St = dyn_cast<StoreInst>(Repl)) {
David Majnemerbd210122016-07-20 21:05:01 +0000952 Gep = dyn_cast<GetElementPtrInst>(St->getPointerOperand());
Sebastian Pop41774802016-07-15 13:45:20 +0000953 Val = dyn_cast<Instruction>(St->getValueOperand());
Sebastian Pop31fd5062016-07-21 23:22:10 +0000954 // Check that the stored value is available.
Sebastian Pop0e2cec02016-07-22 00:07:01 +0000955 if (Val) {
956 if (isa<GetElementPtrInst>(Val)) {
957 // Check whether we can compute the GEP at HoistPt.
Sebastian Pop55c30072016-07-27 05:48:12 +0000958 if (!allGepOperandsAvailable(Val, HoistPt))
Sebastian Pop0e2cec02016-07-22 00:07:01 +0000959 return false;
960 } else if (!DT->dominates(Val->getParent(), HoistPt))
961 return false;
962 }
Sebastian Pop41774802016-07-15 13:45:20 +0000963 }
964
Sebastian Pop41774802016-07-15 13:45:20 +0000965 // Check whether we can compute the Gep at HoistPt.
Sebastian Pop55c30072016-07-27 05:48:12 +0000966 if (!Gep || !allGepOperandsAvailable(Gep, HoistPt))
Sebastian Pop41774802016-07-15 13:45:20 +0000967 return false;
968
Sebastian Pop55c30072016-07-27 05:48:12 +0000969 makeGepsAvailable(Repl, HoistPt, InstructionsToHoist, Gep);
Sebastian Pop41774802016-07-15 13:45:20 +0000970
Sebastian Pop55c30072016-07-27 05:48:12 +0000971 if (Val && isa<GetElementPtrInst>(Val))
972 makeGepsAvailable(Repl, HoistPt, InstructionsToHoist, Val);
Sebastian Pop41774802016-07-15 13:45:20 +0000973
974 return true;
975 }
976
977 std::pair<unsigned, unsigned> hoist(HoistingPointList &HPL) {
978 unsigned NI = 0, NL = 0, NS = 0, NC = 0, NR = 0;
979 for (const HoistingPointInfo &HP : HPL) {
980 // Find out whether we already have one of the instructions in HoistPt,
981 // in which case we do not have to move it.
Aditya Kumardfa87412017-09-13 05:28:03 +0000982 BasicBlock *DestBB = HP.first;
Sebastian Pop41774802016-07-15 13:45:20 +0000983 const SmallVecInsn &InstructionsToHoist = HP.second;
984 Instruction *Repl = nullptr;
985 for (Instruction *I : InstructionsToHoist)
Aditya Kumardfa87412017-09-13 05:28:03 +0000986 if (I->getParent() == DestBB)
Sebastian Pop41774802016-07-15 13:45:20 +0000987 // If there are two instructions in HoistPt to be hoisted in place:
988 // update Repl to be the first one, such that we can rename the uses
989 // of the second based on the first.
Sebastian Pop586d3ea2016-07-27 05:13:52 +0000990 if (!Repl || firstInBB(I, Repl))
991 Repl = I;
Sebastian Pop41774802016-07-15 13:45:20 +0000992
Daniel Berlinf75fd1b2016-08-11 20:32:43 +0000993 // Keep track of whether we moved the instruction so we know whether we
994 // should move the MemoryAccess.
995 bool MoveAccess = true;
Sebastian Pop41774802016-07-15 13:45:20 +0000996 if (Repl) {
997 // Repl is already in HoistPt: it remains in place.
Aditya Kumardfa87412017-09-13 05:28:03 +0000998 assert(allOperandsAvailable(Repl, DestBB) &&
Sebastian Pop41774802016-07-15 13:45:20 +0000999 "instruction depends on operands that are not available");
Daniel Berlinf75fd1b2016-08-11 20:32:43 +00001000 MoveAccess = false;
Sebastian Pop41774802016-07-15 13:45:20 +00001001 } else {
1002 // When we do not find Repl in HoistPt, select the first in the list
1003 // and move it to HoistPt.
1004 Repl = InstructionsToHoist.front();
1005
1006 // We can move Repl in HoistPt only when all operands are available.
1007 // The order in which hoistings are done may influence the availability
1008 // of operands.
Aditya Kumardfa87412017-09-13 05:28:03 +00001009 if (!allOperandsAvailable(Repl, DestBB)) {
Sebastian Pop429740a2016-08-04 23:49:05 +00001010
1011 // When HoistingGeps there is nothing more we can do to make the
1012 // operands available: just continue.
1013 if (HoistingGeps)
1014 continue;
1015
1016 // When not HoistingGeps we need to copy the GEPs.
Aditya Kumardfa87412017-09-13 05:28:03 +00001017 if (!makeGepOperandsAvailable(Repl, DestBB, InstructionsToHoist))
Sebastian Pop429740a2016-08-04 23:49:05 +00001018 continue;
1019 }
Sebastian Pop55c30072016-07-27 05:48:12 +00001020
Sebastian Pop5d3822f2016-08-03 20:54:33 +00001021 // Move the instruction at the end of HoistPt.
Aditya Kumardfa87412017-09-13 05:28:03 +00001022 Instruction *Last = DestBB->getTerminator();
Eli Friedmanc6885fc2016-12-07 19:55:59 +00001023 MD->removeInstruction(Repl);
Sebastian Pop4ba7c882016-08-03 20:54:36 +00001024 Repl->moveBefore(Last);
1025
1026 DFSNumber[Repl] = DFSNumber[Last]++;
Sebastian Pop41774802016-07-15 13:45:20 +00001027 }
1028
Aditya Kumardfa87412017-09-13 05:28:03 +00001029 NR += removeAndReplace(InstructionsToHoist, Repl, DestBB, MoveAccess);
Daniel Berlinf75fd1b2016-08-11 20:32:43 +00001030
Sebastian Pop5d3822f2016-08-03 20:54:33 +00001031
Sebastian Pop41774802016-07-15 13:45:20 +00001032 if (isa<LoadInst>(Repl))
1033 ++NL;
1034 else if (isa<StoreInst>(Repl))
1035 ++NS;
1036 else if (isa<CallInst>(Repl))
1037 ++NC;
1038 else // Scalar
1039 ++NI;
Sebastian Pop41774802016-07-15 13:45:20 +00001040 }
1041
1042 NumHoisted += NL + NS + NC + NI;
1043 NumRemoved += NR;
1044 NumLoadsHoisted += NL;
1045 NumStoresHoisted += NS;
1046 NumCallsHoisted += NC;
1047 return {NI, NL + NC + NS};
1048 }
1049
1050 // Hoist all expressions. Returns Number of scalars hoisted
1051 // and number of non-scalars hoisted.
1052 std::pair<unsigned, unsigned> hoistExpressions(Function &F) {
1053 InsnInfo II;
1054 LoadInfo LI;
1055 StoreInfo SI;
1056 CallInfo CI;
1057 for (BasicBlock *BB : depth_first(&F.getEntryBlock())) {
Sebastian Pop38422b12016-07-26 00:15:08 +00001058 int InstructionNb = 0;
Sebastian Pop41774802016-07-15 13:45:20 +00001059 for (Instruction &I1 : *BB) {
Geoff Berry635e5052017-04-10 20:45:17 +00001060 // If I1 cannot guarantee progress, subsequent instructions
1061 // in BB cannot be hoisted anyways.
1062 if (!isGuaranteedToTransferExecutionToSuccessor(&I1)) {
Aditya Kumardfa87412017-09-13 05:28:03 +00001063 HoistBarrier.insert(BB);
1064 break;
Geoff Berry635e5052017-04-10 20:45:17 +00001065 }
Sebastian Pop38422b12016-07-26 00:15:08 +00001066 // Only hoist the first instructions in BB up to MaxDepthInBB. Hoisting
1067 // deeper may increase the register pressure and compilation time.
1068 if (MaxDepthInBB != -1 && InstructionNb++ >= MaxDepthInBB)
1069 break;
1070
Sebastian Pop440f15b2016-09-22 14:45:40 +00001071 // Do not value number terminator instructions.
Sebastian Pop5d68aa72016-09-22 15:08:09 +00001072 if (isa<TerminatorInst>(&I1))
Sebastian Pop440f15b2016-09-22 14:45:40 +00001073 break;
1074
David Majnemer4c66a712016-07-18 00:34:58 +00001075 if (auto *Load = dyn_cast<LoadInst>(&I1))
Sebastian Pop41774802016-07-15 13:45:20 +00001076 LI.insert(Load, VN);
David Majnemer4c66a712016-07-18 00:34:58 +00001077 else if (auto *Store = dyn_cast<StoreInst>(&I1))
Sebastian Pop41774802016-07-15 13:45:20 +00001078 SI.insert(Store, VN);
David Majnemer4c66a712016-07-18 00:34:58 +00001079 else if (auto *Call = dyn_cast<CallInst>(&I1)) {
1080 if (auto *Intr = dyn_cast<IntrinsicInst>(Call)) {
Sebastian Pop41774802016-07-15 13:45:20 +00001081 if (isa<DbgInfoIntrinsic>(Intr) ||
1082 Intr->getIntrinsicID() == Intrinsic::assume)
1083 continue;
1084 }
Hans Wennborg19c0be92017-03-01 17:15:08 +00001085 if (Call->mayHaveSideEffects())
1086 break;
Matt Arsenault6ad97732016-08-04 20:52:57 +00001087
1088 if (Call->isConvergent())
1089 break;
1090
Sebastian Pop41774802016-07-15 13:45:20 +00001091 CI.insert(Call, VN);
Sebastian Pop55c30072016-07-27 05:48:12 +00001092 } else if (HoistingGeps || !isa<GetElementPtrInst>(&I1))
Sebastian Pop41774802016-07-15 13:45:20 +00001093 // Do not hoist scalars past calls that may write to memory because
1094 // that could result in spills later. geps are handled separately.
1095 // TODO: We can relax this for targets like AArch64 as they have more
1096 // registers than X86.
1097 II.insert(&I1, VN);
1098 }
1099 }
1100
1101 HoistingPointList HPL;
1102 computeInsertionPoints(II.getVNTable(), HPL, InsKind::Scalar);
1103 computeInsertionPoints(LI.getVNTable(), HPL, InsKind::Load);
1104 computeInsertionPoints(SI.getVNTable(), HPL, InsKind::Store);
1105 computeInsertionPoints(CI.getScalarVNTable(), HPL, InsKind::Scalar);
1106 computeInsertionPoints(CI.getLoadVNTable(), HPL, InsKind::Load);
1107 computeInsertionPoints(CI.getStoreVNTable(), HPL, InsKind::Store);
1108 return hoist(HPL);
1109 }
Sebastian Pop41774802016-07-15 13:45:20 +00001110};
1111
1112class GVNHoistLegacyPass : public FunctionPass {
1113public:
1114 static char ID;
1115
1116 GVNHoistLegacyPass() : FunctionPass(ID) {
1117 initializeGVNHoistLegacyPassPass(*PassRegistry::getPassRegistry());
1118 }
1119
1120 bool runOnFunction(Function &F) override {
Paul Robinson2d23c022016-07-19 22:57:14 +00001121 if (skipFunction(F))
1122 return false;
Sebastian Pop41774802016-07-15 13:45:20 +00001123 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Aditya Kumardfa87412017-09-13 05:28:03 +00001124 auto &PDT = getAnalysis<PostDominatorTreeWrapperPass>().getPostDomTree();
Sebastian Pop41774802016-07-15 13:45:20 +00001125 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
1126 auto &MD = getAnalysis<MemoryDependenceWrapperPass>().getMemDep();
Daniel Berlinea02eee2016-08-23 05:42:41 +00001127 auto &MSSA = getAnalysis<MemorySSAWrapperPass>().getMSSA();
Sebastian Pop41774802016-07-15 13:45:20 +00001128
Aditya Kumardfa87412017-09-13 05:28:03 +00001129 GVNHoist G(&DT, &PDT, &AA, &MD, &MSSA);
Sebastian Pop41774802016-07-15 13:45:20 +00001130 return G.run(F);
1131 }
1132
1133 void getAnalysisUsage(AnalysisUsage &AU) const override {
1134 AU.addRequired<DominatorTreeWrapperPass>();
Aditya Kumardfa87412017-09-13 05:28:03 +00001135 AU.addRequired<PostDominatorTreeWrapperPass>();
Sebastian Pop41774802016-07-15 13:45:20 +00001136 AU.addRequired<AAResultsWrapperPass>();
1137 AU.addRequired<MemoryDependenceWrapperPass>();
Daniel Berlinea02eee2016-08-23 05:42:41 +00001138 AU.addRequired<MemorySSAWrapperPass>();
Sebastian Pop41774802016-07-15 13:45:20 +00001139 AU.addPreserved<DominatorTreeWrapperPass>();
Daniel Berlinea02eee2016-08-23 05:42:41 +00001140 AU.addPreserved<MemorySSAWrapperPass>();
Nikolai Bozhenov9e4a1c32017-04-18 13:25:49 +00001141 AU.addPreserved<GlobalsAAWrapperPass>();
Sebastian Pop41774802016-07-15 13:45:20 +00001142 }
1143};
Aditya Kumardfa87412017-09-13 05:28:03 +00001144} // namespace llvm
Sebastian Pop41774802016-07-15 13:45:20 +00001145
Sebastian Pop5ba9f242016-10-13 01:39:10 +00001146PreservedAnalyses GVNHoistPass::run(Function &F, FunctionAnalysisManager &AM) {
Sebastian Pop41774802016-07-15 13:45:20 +00001147 DominatorTree &DT = AM.getResult<DominatorTreeAnalysis>(F);
Aditya Kumardfa87412017-09-13 05:28:03 +00001148 PostDominatorTree &PDT = AM.getResult<PostDominatorTreeAnalysis>(F);
Sebastian Pop41774802016-07-15 13:45:20 +00001149 AliasAnalysis &AA = AM.getResult<AAManager>(F);
1150 MemoryDependenceResults &MD = AM.getResult<MemoryDependenceAnalysis>(F);
Daniel Berlinea02eee2016-08-23 05:42:41 +00001151 MemorySSA &MSSA = AM.getResult<MemorySSAAnalysis>(F).getMSSA();
Aditya Kumardfa87412017-09-13 05:28:03 +00001152 GVNHoist G(&DT, &PDT, &AA, &MD, &MSSA);
Sebastian Pop41774802016-07-15 13:45:20 +00001153 if (!G.run(F))
1154 return PreservedAnalyses::all();
1155
1156 PreservedAnalyses PA;
1157 PA.preserve<DominatorTreeAnalysis>();
Daniel Berlinea02eee2016-08-23 05:42:41 +00001158 PA.preserve<MemorySSAAnalysis>();
Nikolai Bozhenov9e4a1c32017-04-18 13:25:49 +00001159 PA.preserve<GlobalsAA>();
Sebastian Pop41774802016-07-15 13:45:20 +00001160 return PA;
1161}
1162
1163char GVNHoistLegacyPass::ID = 0;
1164INITIALIZE_PASS_BEGIN(GVNHoistLegacyPass, "gvn-hoist",
1165 "Early GVN Hoisting of Expressions", false, false)
1166INITIALIZE_PASS_DEPENDENCY(MemoryDependenceWrapperPass)
Daniel Berlinea02eee2016-08-23 05:42:41 +00001167INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
Sebastian Pop41774802016-07-15 13:45:20 +00001168INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
1169INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
1170INITIALIZE_PASS_END(GVNHoistLegacyPass, "gvn-hoist",
1171 "Early GVN Hoisting of Expressions", false, false)
1172
1173FunctionPass *llvm::createGVNHoistPass() { return new GVNHoistLegacyPass(); }