xref: /freebsd/contrib/llvm-project/llvm/lib/Transforms/Scalar/GVNHoist.cpp (revision 0fca6ea1d4eea4c934cfff25ac9ee8ad6fe95583)
1 //===- GVNHoist.cpp - Hoist scalar and load expressions -------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This pass hoists expressions from branches to a common dominator. It uses
10 // GVN (global value numbering) to discover expressions computing the same
11 // values. The primary goals of code-hoisting are:
12 // 1. To reduce the code size.
13 // 2. In some cases reduce critical path (by exposing more ILP).
14 //
15 // The algorithm factors out the reachability of values such that multiple
16 // queries to find reachability of values are fast. This is based on finding the
17 // ANTIC points in the CFG which do not change during hoisting. The ANTIC points
18 // are basically the dominance-frontiers in the inverse graph. So we introduce a
19 // data structure (CHI nodes) to keep track of values flowing out of a basic
20 // block. We only do this for values with multiple occurrences in the function
21 // as they are the potential hoistable candidates. This approach allows us to
22 // hoist instructions to a basic block with more than two successors, as well as
23 // deal with infinite loops in a trivial way.
24 //
25 // Limitations: This pass does not hoist fully redundant expressions because
26 // they are already handled by GVN-PRE. It is advisable to run gvn-hoist before
27 // and after gvn-pre because gvn-pre creates opportunities for more instructions
28 // to be hoisted.
29 //
30 // Hoisting may affect the performance in some cases. To mitigate that, hoisting
31 // is disabled in the following cases.
32 // 1. Scalars across calls.
33 // 2. geps when corresponding load/store cannot be hoisted.
34 //===----------------------------------------------------------------------===//
35 
36 #include "llvm/ADT/DenseMap.h"
37 #include "llvm/ADT/DenseSet.h"
38 #include "llvm/ADT/STLExtras.h"
39 #include "llvm/ADT/SmallPtrSet.h"
40 #include "llvm/ADT/SmallVector.h"
41 #include "llvm/ADT/Statistic.h"
42 #include "llvm/ADT/iterator_range.h"
43 #include "llvm/Analysis/AliasAnalysis.h"
44 #include "llvm/Analysis/GlobalsModRef.h"
45 #include "llvm/Analysis/IteratedDominanceFrontier.h"
46 #include "llvm/Analysis/MemoryDependenceAnalysis.h"
47 #include "llvm/Analysis/MemorySSA.h"
48 #include "llvm/Analysis/MemorySSAUpdater.h"
49 #include "llvm/Analysis/PostDominators.h"
50 #include "llvm/Analysis/ValueTracking.h"
51 #include "llvm/IR/Argument.h"
52 #include "llvm/IR/BasicBlock.h"
53 #include "llvm/IR/CFG.h"
54 #include "llvm/IR/Constants.h"
55 #include "llvm/IR/Dominators.h"
56 #include "llvm/IR/Function.h"
57 #include "llvm/IR/Instruction.h"
58 #include "llvm/IR/Instructions.h"
59 #include "llvm/IR/IntrinsicInst.h"
60 #include "llvm/IR/LLVMContext.h"
61 #include "llvm/IR/PassManager.h"
62 #include "llvm/IR/Use.h"
63 #include "llvm/IR/User.h"
64 #include "llvm/IR/Value.h"
65 #include "llvm/Support/Casting.h"
66 #include "llvm/Support/CommandLine.h"
67 #include "llvm/Support/Debug.h"
68 #include "llvm/Support/raw_ostream.h"
69 #include "llvm/Transforms/Scalar/GVN.h"
70 #include "llvm/Transforms/Utils/Local.h"
71 #include <algorithm>
72 #include <cassert>
73 #include <iterator>
74 #include <memory>
75 #include <utility>
76 #include <vector>
77 
78 using namespace llvm;
79 
80 #define DEBUG_TYPE "gvn-hoist"
81 
82 STATISTIC(NumHoisted, "Number of instructions hoisted");
83 STATISTIC(NumRemoved, "Number of instructions removed");
84 STATISTIC(NumLoadsHoisted, "Number of loads hoisted");
85 STATISTIC(NumLoadsRemoved, "Number of loads removed");
86 STATISTIC(NumStoresHoisted, "Number of stores hoisted");
87 STATISTIC(NumStoresRemoved, "Number of stores removed");
88 STATISTIC(NumCallsHoisted, "Number of calls hoisted");
89 STATISTIC(NumCallsRemoved, "Number of calls removed");
90 
91 static cl::opt<int>
92     MaxHoistedThreshold("gvn-max-hoisted", cl::Hidden, cl::init(-1),
93                         cl::desc("Max number of instructions to hoist "
94                                  "(default unlimited = -1)"));
95 
96 static cl::opt<int> MaxNumberOfBBSInPath(
97     "gvn-hoist-max-bbs", cl::Hidden, cl::init(4),
98     cl::desc("Max number of basic blocks on the path between "
99              "hoisting locations (default = 4, unlimited = -1)"));
100 
101 static cl::opt<int> MaxDepthInBB(
102     "gvn-hoist-max-depth", cl::Hidden, cl::init(100),
103     cl::desc("Hoist instructions from the beginning of the BB up to the "
104              "maximum specified depth (default = 100, unlimited = -1)"));
105 
106 static cl::opt<int>
107     MaxChainLength("gvn-hoist-max-chain-length", cl::Hidden, cl::init(10),
108                    cl::desc("Maximum length of dependent chains to hoist "
109                             "(default = 10, unlimited = -1)"));
110 
111 namespace llvm {
112 
113 using BBSideEffectsSet = DenseMap<const BasicBlock *, bool>;
114 using SmallVecInsn = SmallVector<Instruction *, 4>;
115 using SmallVecImplInsn = SmallVectorImpl<Instruction *>;
116 
117 // Each element of a hoisting list contains the basic block where to hoist and
118 // a list of instructions to be hoisted.
119 using HoistingPointInfo = std::pair<BasicBlock *, SmallVecInsn>;
120 
121 using HoistingPointList = SmallVector<HoistingPointInfo, 4>;
122 
123 // A map from a pair of VNs to all the instructions with those VNs.
124 using VNType = std::pair<unsigned, uintptr_t>;
125 
126 using VNtoInsns = DenseMap<VNType, SmallVector<Instruction *, 4>>;
127 
128 // CHI keeps information about values flowing out of a basic block.  It is
129 // similar to PHI but in the inverse graph, and used for outgoing values on each
130 // edge. For conciseness, it is computed only for instructions with multiple
131 // occurrences in the CFG because they are the only hoistable candidates.
132 //     A (CHI[{V, B, I1}, {V, C, I2}]
133 //  /     \
134 // /       \
135 // B(I1)  C (I2)
136 // The Value number for both I1 and I2 is V, the CHI node will save the
137 // instruction as well as the edge where the value is flowing to.
138 struct CHIArg {
139   VNType VN;
140 
141   // Edge destination (shows the direction of flow), may not be where the I is.
142   BasicBlock *Dest;
143 
144   // The instruction (VN) which uses the values flowing out of CHI.
145   Instruction *I;
146 
operator ==llvm::CHIArg147   bool operator==(const CHIArg &A) const { return VN == A.VN; }
operator !=llvm::CHIArg148   bool operator!=(const CHIArg &A) const { return !(*this == A); }
149 };
150 
151 using CHIIt = SmallVectorImpl<CHIArg>::iterator;
152 using CHIArgs = iterator_range<CHIIt>;
153 using OutValuesType = DenseMap<BasicBlock *, SmallVector<CHIArg, 2>>;
154 using InValuesType =
155     DenseMap<BasicBlock *, SmallVector<std::pair<VNType, Instruction *>, 2>>;
156 
157 // An invalid value number Used when inserting a single value number into
158 // VNtoInsns.
159 enum : uintptr_t { InvalidVN = ~(uintptr_t)2 };
160 
161 // Records all scalar instructions candidate for code hoisting.
162 class InsnInfo {
163   VNtoInsns VNtoScalars;
164 
165 public:
166   // Inserts I and its value number in VNtoScalars.
insert(Instruction * I,GVNPass::ValueTable & VN)167   void insert(Instruction *I, GVNPass::ValueTable &VN) {
168     // Scalar instruction.
169     unsigned V = VN.lookupOrAdd(I);
170     VNtoScalars[{V, InvalidVN}].push_back(I);
171   }
172 
getVNTable() const173   const VNtoInsns &getVNTable() const { return VNtoScalars; }
174 };
175 
176 // Records all load instructions candidate for code hoisting.
177 class LoadInfo {
178   VNtoInsns VNtoLoads;
179 
180 public:
181   // Insert Load and the value number of its memory address in VNtoLoads.
insert(LoadInst * Load,GVNPass::ValueTable & VN)182   void insert(LoadInst *Load, GVNPass::ValueTable &VN) {
183     if (Load->isSimple()) {
184       unsigned V = VN.lookupOrAdd(Load->getPointerOperand());
185       // With opaque pointers we may have loads from the same pointer with
186       // different result types, which should be disambiguated.
187       VNtoLoads[{V, (uintptr_t)Load->getType()}].push_back(Load);
188     }
189   }
190 
getVNTable() const191   const VNtoInsns &getVNTable() const { return VNtoLoads; }
192 };
193 
194 // Records all store instructions candidate for code hoisting.
195 class StoreInfo {
196   VNtoInsns VNtoStores;
197 
198 public:
199   // Insert the Store and a hash number of the store address and the stored
200   // value in VNtoStores.
insert(StoreInst * Store,GVNPass::ValueTable & VN)201   void insert(StoreInst *Store, GVNPass::ValueTable &VN) {
202     if (!Store->isSimple())
203       return;
204     // Hash the store address and the stored value.
205     Value *Ptr = Store->getPointerOperand();
206     Value *Val = Store->getValueOperand();
207     VNtoStores[{VN.lookupOrAdd(Ptr), VN.lookupOrAdd(Val)}].push_back(Store);
208   }
209 
getVNTable() const210   const VNtoInsns &getVNTable() const { return VNtoStores; }
211 };
212 
213 // Records all call instructions candidate for code hoisting.
214 class CallInfo {
215   VNtoInsns VNtoCallsScalars;
216   VNtoInsns VNtoCallsLoads;
217   VNtoInsns VNtoCallsStores;
218 
219 public:
220   // Insert Call and its value numbering in one of the VNtoCalls* containers.
insert(CallInst * Call,GVNPass::ValueTable & VN)221   void insert(CallInst *Call, GVNPass::ValueTable &VN) {
222     // A call that doesNotAccessMemory is handled as a Scalar,
223     // onlyReadsMemory will be handled as a Load instruction,
224     // all other calls will be handled as stores.
225     unsigned V = VN.lookupOrAdd(Call);
226     auto Entry = std::make_pair(V, InvalidVN);
227 
228     if (Call->doesNotAccessMemory())
229       VNtoCallsScalars[Entry].push_back(Call);
230     else if (Call->onlyReadsMemory())
231       VNtoCallsLoads[Entry].push_back(Call);
232     else
233       VNtoCallsStores[Entry].push_back(Call);
234   }
235 
getScalarVNTable() const236   const VNtoInsns &getScalarVNTable() const { return VNtoCallsScalars; }
getLoadVNTable() const237   const VNtoInsns &getLoadVNTable() const { return VNtoCallsLoads; }
getStoreVNTable() const238   const VNtoInsns &getStoreVNTable() const { return VNtoCallsStores; }
239 };
240 
241 // This pass hoists common computations across branches sharing common
242 // dominator. The primary goal is to reduce the code size, and in some
243 // cases reduce critical path (by exposing more ILP).
244 class GVNHoist {
245 public:
GVNHoist(DominatorTree * DT,PostDominatorTree * PDT,AliasAnalysis * AA,MemoryDependenceResults * MD,MemorySSA * MSSA)246   GVNHoist(DominatorTree *DT, PostDominatorTree *PDT, AliasAnalysis *AA,
247            MemoryDependenceResults *MD, MemorySSA *MSSA)
248       : DT(DT), PDT(PDT), AA(AA), MD(MD), MSSA(MSSA),
249         MSSAUpdater(std::make_unique<MemorySSAUpdater>(MSSA)) {
250     MSSA->ensureOptimizedUses();
251   }
252 
253   bool run(Function &F);
254 
255   // Copied from NewGVN.cpp
256   // This function provides global ranking of operations so that we can place
257   // them in a canonical order.  Note that rank alone is not necessarily enough
258   // for a complete ordering, as constants all have the same rank.  However,
259   // generally, we will simplify an operation with all constants so that it
260   // doesn't matter what order they appear in.
261   unsigned int rank(const Value *V) const;
262 
263 private:
264   GVNPass::ValueTable VN;
265   DominatorTree *DT;
266   PostDominatorTree *PDT;
267   AliasAnalysis *AA;
268   MemoryDependenceResults *MD;
269   MemorySSA *MSSA;
270   std::unique_ptr<MemorySSAUpdater> MSSAUpdater;
271   DenseMap<const Value *, unsigned> DFSNumber;
272   BBSideEffectsSet BBSideEffects;
273   DenseSet<const BasicBlock *> HoistBarrier;
274   SmallVector<BasicBlock *, 32> IDFBlocks;
275   unsigned NumFuncArgs;
276   const bool HoistingGeps = false;
277 
278   enum InsKind { Unknown, Scalar, Load, Store };
279 
280   // Return true when there are exception handling in BB.
281   bool hasEH(const BasicBlock *BB);
282 
283   // Return true when I1 appears before I2 in the instructions of BB.
firstInBB(const Instruction * I1,const Instruction * I2)284   bool firstInBB(const Instruction *I1, const Instruction *I2) {
285     assert(I1->getParent() == I2->getParent());
286     unsigned I1DFS = DFSNumber.lookup(I1);
287     unsigned I2DFS = DFSNumber.lookup(I2);
288     assert(I1DFS && I2DFS);
289     return I1DFS < I2DFS;
290   }
291 
292   // Return true when there are memory uses of Def in BB.
293   bool hasMemoryUse(const Instruction *NewPt, MemoryDef *Def,
294                     const BasicBlock *BB);
295 
296   bool hasEHhelper(const BasicBlock *BB, const BasicBlock *SrcBB,
297                    int &NBBsOnAllPaths);
298 
299   // Return true when there are exception handling or loads of memory Def
300   // between Def and NewPt.  This function is only called for stores: Def is
301   // the MemoryDef of the store to be hoisted.
302 
303   // Decrement by 1 NBBsOnAllPaths for each block between HoistPt and BB, and
304   // return true when the counter NBBsOnAllPaths reaces 0, except when it is
305   // initialized to -1 which is unlimited.
306   bool hasEHOrLoadsOnPath(const Instruction *NewPt, MemoryDef *Def,
307                           int &NBBsOnAllPaths);
308 
309   // Return true when there are exception handling between HoistPt and BB.
310   // Decrement by 1 NBBsOnAllPaths for each block between HoistPt and BB, and
311   // return true when the counter NBBsOnAllPaths reaches 0, except when it is
312   // initialized to -1 which is unlimited.
313   bool hasEHOnPath(const BasicBlock *HoistPt, const BasicBlock *SrcBB,
314                    int &NBBsOnAllPaths);
315 
316   // Return true when it is safe to hoist a memory load or store U from OldPt
317   // to NewPt.
318   bool safeToHoistLdSt(const Instruction *NewPt, const Instruction *OldPt,
319                        MemoryUseOrDef *U, InsKind K, int &NBBsOnAllPaths);
320 
321   // Return true when it is safe to hoist scalar instructions from all blocks in
322   // WL to HoistBB.
safeToHoistScalar(const BasicBlock * HoistBB,const BasicBlock * BB,int & NBBsOnAllPaths)323   bool safeToHoistScalar(const BasicBlock *HoistBB, const BasicBlock *BB,
324                          int &NBBsOnAllPaths) {
325     return !hasEHOnPath(HoistBB, BB, NBBsOnAllPaths);
326   }
327 
328   // In the inverse CFG, the dominance frontier of basic block (BB) is the
329   // point where ANTIC needs to be computed for instructions which are going
330   // to be hoisted. Since this point does not change during gvn-hoist,
331   // we compute it only once (on demand).
332   // The ides is inspired from:
333   // "Partial Redundancy Elimination in SSA Form"
334   // ROBERT KENNEDY, SUN CHAN, SHIN-MING LIU, RAYMOND LO, PENG TU and FRED CHOW
335   // They use similar idea in the forward graph to find fully redundant and
336   // partially redundant expressions, here it is used in the inverse graph to
337   // find fully anticipable instructions at merge point (post-dominator in
338   // the inverse CFG).
339   // Returns the edge via which an instruction in BB will get the values from.
340 
341   // Returns true when the values are flowing out to each edge.
342   bool valueAnticipable(CHIArgs C, Instruction *TI) const;
343 
344   // Check if it is safe to hoist values tracked by CHI in the range
345   // [Begin, End) and accumulate them in Safe.
346   void checkSafety(CHIArgs C, BasicBlock *BB, InsKind K,
347                    SmallVectorImpl<CHIArg> &Safe);
348 
349   using RenameStackType = DenseMap<VNType, SmallVector<Instruction *, 2>>;
350 
351   // Push all the VNs corresponding to BB into RenameStack.
352   void fillRenameStack(BasicBlock *BB, InValuesType &ValueBBs,
353                        RenameStackType &RenameStack);
354 
355   void fillChiArgs(BasicBlock *BB, OutValuesType &CHIBBs,
356                    RenameStackType &RenameStack);
357 
358   // Walk the post-dominator tree top-down and use a stack for each value to
359   // store the last value you see. When you hit a CHI from a given edge, the
360   // value to use as the argument is at the top of the stack, add the value to
361   // CHI and pop.
insertCHI(InValuesType & ValueBBs,OutValuesType & CHIBBs)362   void insertCHI(InValuesType &ValueBBs, OutValuesType &CHIBBs) {
363     auto Root = PDT->getNode(nullptr);
364     if (!Root)
365       return;
366     // Depth first walk on PDom tree to fill the CHIargs at each PDF.
367     for (auto *Node : depth_first(Root)) {
368       BasicBlock *BB = Node->getBlock();
369       if (!BB)
370         continue;
371 
372       RenameStackType RenameStack;
373       // Collect all values in BB and push to stack.
374       fillRenameStack(BB, ValueBBs, RenameStack);
375 
376       // Fill outgoing values in each CHI corresponding to BB.
377       fillChiArgs(BB, CHIBBs, RenameStack);
378     }
379   }
380 
381   // Walk all the CHI-nodes to find ones which have a empty-entry and remove
382   // them Then collect all the instructions which are safe to hoist and see if
383   // they form a list of anticipable values. OutValues contains CHIs
384   // corresponding to each basic block.
385   void findHoistableCandidates(OutValuesType &CHIBBs, InsKind K,
386                                HoistingPointList &HPL);
387 
388   // Compute insertion points for each values which can be fully anticipated at
389   // a dominator. HPL contains all such values.
computeInsertionPoints(const VNtoInsns & Map,HoistingPointList & HPL,InsKind K)390   void computeInsertionPoints(const VNtoInsns &Map, HoistingPointList &HPL,
391                               InsKind K) {
392     // Sort VNs based on their rankings
393     std::vector<VNType> Ranks;
394     for (const auto &Entry : Map) {
395       Ranks.push_back(Entry.first);
396     }
397 
398     // TODO: Remove fully-redundant expressions.
399     // Get instruction from the Map, assume that all the Instructions
400     // with same VNs have same rank (this is an approximation).
401     llvm::sort(Ranks, [this, &Map](const VNType &r1, const VNType &r2) {
402       return (rank(*Map.lookup(r1).begin()) < rank(*Map.lookup(r2).begin()));
403     });
404 
405     // - Sort VNs according to their rank, and start with lowest ranked VN
406     // - Take a VN and for each instruction with same VN
407     //   - Find the dominance frontier in the inverse graph (PDF)
408     //   - Insert the chi-node at PDF
409     // - Remove the chi-nodes with missing entries
410     // - Remove values from CHI-nodes which do not truly flow out, e.g.,
411     //   modified along the path.
412     // - Collect the remaining values that are still anticipable
413     SmallVector<BasicBlock *, 2> IDFBlocks;
414     ReverseIDFCalculator IDFs(*PDT);
415     OutValuesType OutValue;
416     InValuesType InValue;
417     for (const auto &R : Ranks) {
418       const SmallVecInsn &V = Map.lookup(R);
419       if (V.size() < 2)
420         continue;
421       const VNType &VN = R;
422       SmallPtrSet<BasicBlock *, 2> VNBlocks;
423       for (const auto &I : V) {
424         BasicBlock *BBI = I->getParent();
425         if (!hasEH(BBI))
426           VNBlocks.insert(BBI);
427       }
428       // Compute the Post Dominance Frontiers of each basic block
429       // The dominance frontier of a live block X in the reverse
430       // control graph is the set of blocks upon which X is control
431       // dependent. The following sequence computes the set of blocks
432       // which currently have dead terminators that are control
433       // dependence sources of a block which is in NewLiveBlocks.
434       IDFs.setDefiningBlocks(VNBlocks);
435       IDFBlocks.clear();
436       IDFs.calculate(IDFBlocks);
437 
438       // Make a map of BB vs instructions to be hoisted.
439       for (unsigned i = 0; i < V.size(); ++i) {
440         InValue[V[i]->getParent()].push_back(std::make_pair(VN, V[i]));
441       }
442       // Insert empty CHI node for this VN. This is used to factor out
443       // basic blocks where the ANTIC can potentially change.
444       CHIArg EmptyChi = {VN, nullptr, nullptr};
445       for (auto *IDFBB : IDFBlocks) {
446         for (unsigned i = 0; i < V.size(); ++i) {
447           // Ignore spurious PDFs.
448           if (DT->properlyDominates(IDFBB, V[i]->getParent())) {
449             OutValue[IDFBB].push_back(EmptyChi);
450             LLVM_DEBUG(dbgs() << "\nInserting a CHI for BB: "
451                               << IDFBB->getName() << ", for Insn: " << *V[i]);
452           }
453         }
454       }
455     }
456 
457     // Insert CHI args at each PDF to iterate on factored graph of
458     // control dependence.
459     insertCHI(InValue, OutValue);
460     // Using the CHI args inserted at each PDF, find fully anticipable values.
461     findHoistableCandidates(OutValue, K, HPL);
462   }
463 
464   // Return true when all operands of Instr are available at insertion point
465   // HoistPt. When limiting the number of hoisted expressions, one could hoist
466   // a load without hoisting its access function. So before hoisting any
467   // expression, make sure that all its operands are available at insert point.
468   bool allOperandsAvailable(const Instruction *I,
469                             const BasicBlock *HoistPt) const;
470 
471   // Same as allOperandsAvailable with recursive check for GEP operands.
472   bool allGepOperandsAvailable(const Instruction *I,
473                                const BasicBlock *HoistPt) const;
474 
475   // Make all operands of the GEP available.
476   void makeGepsAvailable(Instruction *Repl, BasicBlock *HoistPt,
477                          const SmallVecInsn &InstructionsToHoist,
478                          Instruction *Gep) const;
479 
480   void updateAlignment(Instruction *I, Instruction *Repl);
481 
482   // Remove all the instructions in Candidates and replace their usage with
483   // Repl. Returns the number of instructions removed.
484   unsigned rauw(const SmallVecInsn &Candidates, Instruction *Repl,
485                 MemoryUseOrDef *NewMemAcc);
486 
487   // Replace all Memory PHI usage with NewMemAcc.
488   void raMPHIuw(MemoryUseOrDef *NewMemAcc);
489 
490   // Remove all other instructions and replace them with Repl.
491   unsigned removeAndReplace(const SmallVecInsn &Candidates, Instruction *Repl,
492                             BasicBlock *DestBB, bool MoveAccess);
493 
494   // In the case Repl is a load or a store, we make all their GEPs
495   // available: GEPs are not hoisted by default to avoid the address
496   // computations to be hoisted without the associated load or store.
497   bool makeGepOperandsAvailable(Instruction *Repl, BasicBlock *HoistPt,
498                                 const SmallVecInsn &InstructionsToHoist) const;
499 
500   std::pair<unsigned, unsigned> hoist(HoistingPointList &HPL);
501 
502   // Hoist all expressions. Returns Number of scalars hoisted
503   // and number of non-scalars hoisted.
504   std::pair<unsigned, unsigned> hoistExpressions(Function &F);
505 };
506 
run(Function & F)507 bool GVNHoist::run(Function &F) {
508   NumFuncArgs = F.arg_size();
509   VN.setDomTree(DT);
510   VN.setAliasAnalysis(AA);
511   VN.setMemDep(MD);
512   bool Res = false;
513   // Perform DFS Numbering of instructions.
514   unsigned BBI = 0;
515   for (const BasicBlock *BB : depth_first(&F.getEntryBlock())) {
516     DFSNumber[BB] = ++BBI;
517     unsigned I = 0;
518     for (const auto &Inst : *BB)
519       DFSNumber[&Inst] = ++I;
520   }
521 
522   int ChainLength = 0;
523 
524   // FIXME: use lazy evaluation of VN to avoid the fix-point computation.
525   while (true) {
526     if (MaxChainLength != -1 && ++ChainLength >= MaxChainLength)
527       return Res;
528 
529     auto HoistStat = hoistExpressions(F);
530     if (HoistStat.first + HoistStat.second == 0)
531       return Res;
532 
533     if (HoistStat.second > 0)
534       // To address a limitation of the current GVN, we need to rerun the
535       // hoisting after we hoisted loads or stores in order to be able to
536       // hoist all scalars dependent on the hoisted ld/st.
537       VN.clear();
538 
539     Res = true;
540   }
541 
542   return Res;
543 }
544 
rank(const Value * V) const545 unsigned int GVNHoist::rank(const Value *V) const {
546   // Prefer constants to undef to anything else
547   // Undef is a constant, have to check it first.
548   // Prefer smaller constants to constantexprs
549   if (isa<ConstantExpr>(V))
550     return 2;
551   if (isa<UndefValue>(V))
552     return 1;
553   if (isa<Constant>(V))
554     return 0;
555   else if (auto *A = dyn_cast<Argument>(V))
556     return 3 + A->getArgNo();
557 
558   // Need to shift the instruction DFS by number of arguments + 3 to account
559   // for the constant and argument ranking above.
560   auto Result = DFSNumber.lookup(V);
561   if (Result > 0)
562     return 4 + NumFuncArgs + Result;
563   // Unreachable or something else, just return a really large number.
564   return ~0;
565 }
566 
hasEH(const BasicBlock * BB)567 bool GVNHoist::hasEH(const BasicBlock *BB) {
568   auto It = BBSideEffects.find(BB);
569   if (It != BBSideEffects.end())
570     return It->second;
571 
572   if (BB->isEHPad() || BB->hasAddressTaken()) {
573     BBSideEffects[BB] = true;
574     return true;
575   }
576 
577   if (BB->getTerminator()->mayThrow()) {
578     BBSideEffects[BB] = true;
579     return true;
580   }
581 
582   BBSideEffects[BB] = false;
583   return false;
584 }
585 
hasMemoryUse(const Instruction * NewPt,MemoryDef * Def,const BasicBlock * BB)586 bool GVNHoist::hasMemoryUse(const Instruction *NewPt, MemoryDef *Def,
587                             const BasicBlock *BB) {
588   const MemorySSA::AccessList *Acc = MSSA->getBlockAccesses(BB);
589   if (!Acc)
590     return false;
591 
592   Instruction *OldPt = Def->getMemoryInst();
593   const BasicBlock *OldBB = OldPt->getParent();
594   const BasicBlock *NewBB = NewPt->getParent();
595   bool ReachedNewPt = false;
596 
597   for (const MemoryAccess &MA : *Acc)
598     if (const MemoryUse *MU = dyn_cast<MemoryUse>(&MA)) {
599       Instruction *Insn = MU->getMemoryInst();
600 
601       // Do not check whether MU aliases Def when MU occurs after OldPt.
602       if (BB == OldBB && firstInBB(OldPt, Insn))
603         break;
604 
605       // Do not check whether MU aliases Def when MU occurs before NewPt.
606       if (BB == NewBB) {
607         if (!ReachedNewPt) {
608           if (firstInBB(Insn, NewPt))
609             continue;
610           ReachedNewPt = true;
611         }
612       }
613       if (MemorySSAUtil::defClobbersUseOrDef(Def, MU, *AA))
614         return true;
615     }
616 
617   return false;
618 }
619 
hasEHhelper(const BasicBlock * BB,const BasicBlock * SrcBB,int & NBBsOnAllPaths)620 bool GVNHoist::hasEHhelper(const BasicBlock *BB, const BasicBlock *SrcBB,
621                            int &NBBsOnAllPaths) {
622   // Stop walk once the limit is reached.
623   if (NBBsOnAllPaths == 0)
624     return true;
625 
626   // Impossible to hoist with exceptions on the path.
627   if (hasEH(BB))
628     return true;
629 
630   // No such instruction after HoistBarrier in a basic block was
631   // selected for hoisting so instructions selected within basic block with
632   // a hoist barrier can be hoisted.
633   if ((BB != SrcBB) && HoistBarrier.count(BB))
634     return true;
635 
636   return false;
637 }
638 
hasEHOrLoadsOnPath(const Instruction * NewPt,MemoryDef * Def,int & NBBsOnAllPaths)639 bool GVNHoist::hasEHOrLoadsOnPath(const Instruction *NewPt, MemoryDef *Def,
640                                   int &NBBsOnAllPaths) {
641   const BasicBlock *NewBB = NewPt->getParent();
642   const BasicBlock *OldBB = Def->getBlock();
643   assert(DT->dominates(NewBB, OldBB) && "invalid path");
644   assert(DT->dominates(Def->getDefiningAccess()->getBlock(), NewBB) &&
645          "def does not dominate new hoisting point");
646 
647   // Walk all basic blocks reachable in depth-first iteration on the inverse
648   // CFG from OldBB to NewBB. These blocks are all the blocks that may be
649   // executed between the execution of NewBB and OldBB. Hoisting an expression
650   // from OldBB into NewBB has to be safe on all execution paths.
651   for (auto I = idf_begin(OldBB), E = idf_end(OldBB); I != E;) {
652     const BasicBlock *BB = *I;
653     if (BB == NewBB) {
654       // Stop traversal when reaching HoistPt.
655       I.skipChildren();
656       continue;
657     }
658 
659     if (hasEHhelper(BB, OldBB, NBBsOnAllPaths))
660       return true;
661 
662     // Check that we do not move a store past loads.
663     if (hasMemoryUse(NewPt, Def, BB))
664       return true;
665 
666     // -1 is unlimited number of blocks on all paths.
667     if (NBBsOnAllPaths != -1)
668       --NBBsOnAllPaths;
669 
670     ++I;
671   }
672 
673   return false;
674 }
675 
hasEHOnPath(const BasicBlock * HoistPt,const BasicBlock * SrcBB,int & NBBsOnAllPaths)676 bool GVNHoist::hasEHOnPath(const BasicBlock *HoistPt, const BasicBlock *SrcBB,
677                            int &NBBsOnAllPaths) {
678   assert(DT->dominates(HoistPt, SrcBB) && "Invalid path");
679 
680   // Walk all basic blocks reachable in depth-first iteration on
681   // the inverse CFG from BBInsn to NewHoistPt. These blocks are all the
682   // blocks that may be executed between the execution of NewHoistPt and
683   // BBInsn. Hoisting an expression from BBInsn into NewHoistPt has to be safe
684   // on all execution paths.
685   for (auto I = idf_begin(SrcBB), E = idf_end(SrcBB); I != E;) {
686     const BasicBlock *BB = *I;
687     if (BB == HoistPt) {
688       // Stop traversal when reaching NewHoistPt.
689       I.skipChildren();
690       continue;
691     }
692 
693     if (hasEHhelper(BB, SrcBB, NBBsOnAllPaths))
694       return true;
695 
696     // -1 is unlimited number of blocks on all paths.
697     if (NBBsOnAllPaths != -1)
698       --NBBsOnAllPaths;
699 
700     ++I;
701   }
702 
703   return false;
704 }
705 
safeToHoistLdSt(const Instruction * NewPt,const Instruction * OldPt,MemoryUseOrDef * U,GVNHoist::InsKind K,int & NBBsOnAllPaths)706 bool GVNHoist::safeToHoistLdSt(const Instruction *NewPt,
707                                const Instruction *OldPt, MemoryUseOrDef *U,
708                                GVNHoist::InsKind K, int &NBBsOnAllPaths) {
709   // In place hoisting is safe.
710   if (NewPt == OldPt)
711     return true;
712 
713   const BasicBlock *NewBB = NewPt->getParent();
714   const BasicBlock *OldBB = OldPt->getParent();
715   const BasicBlock *UBB = U->getBlock();
716 
717   // Check for dependences on the Memory SSA.
718   MemoryAccess *D = U->getDefiningAccess();
719   BasicBlock *DBB = D->getBlock();
720   if (DT->properlyDominates(NewBB, DBB))
721     // Cannot move the load or store to NewBB above its definition in DBB.
722     return false;
723 
724   if (NewBB == DBB && !MSSA->isLiveOnEntryDef(D))
725     if (auto *UD = dyn_cast<MemoryUseOrDef>(D))
726       if (!firstInBB(UD->getMemoryInst(), NewPt))
727         // Cannot move the load or store to NewPt above its definition in D.
728         return false;
729 
730   // Check for unsafe hoistings due to side effects.
731   if (K == InsKind::Store) {
732     if (hasEHOrLoadsOnPath(NewPt, cast<MemoryDef>(U), NBBsOnAllPaths))
733       return false;
734   } else if (hasEHOnPath(NewBB, OldBB, NBBsOnAllPaths))
735     return false;
736 
737   if (UBB == NewBB) {
738     if (DT->properlyDominates(DBB, NewBB))
739       return true;
740     assert(UBB == DBB);
741     assert(MSSA->locallyDominates(D, U));
742   }
743 
744   // No side effects: it is safe to hoist.
745   return true;
746 }
747 
valueAnticipable(CHIArgs C,Instruction * TI) const748 bool GVNHoist::valueAnticipable(CHIArgs C, Instruction *TI) const {
749   if (TI->getNumSuccessors() > (unsigned)size(C))
750     return false; // Not enough args in this CHI.
751 
752   for (auto CHI : C) {
753     // Find if all the edges have values flowing out of BB.
754     if (!llvm::is_contained(successors(TI), CHI.Dest))
755       return false;
756   }
757   return true;
758 }
759 
checkSafety(CHIArgs C,BasicBlock * BB,GVNHoist::InsKind K,SmallVectorImpl<CHIArg> & Safe)760 void GVNHoist::checkSafety(CHIArgs C, BasicBlock *BB, GVNHoist::InsKind K,
761                            SmallVectorImpl<CHIArg> &Safe) {
762   int NumBBsOnAllPaths = MaxNumberOfBBSInPath;
763   const Instruction *T = BB->getTerminator();
764   for (auto CHI : C) {
765     Instruction *Insn = CHI.I;
766     if (!Insn) // No instruction was inserted in this CHI.
767       continue;
768     // If the Terminator is some kind of "exotic terminator" that produces a
769     // value (such as InvokeInst, CallBrInst, or CatchSwitchInst) which the CHI
770     // uses, it is not safe to hoist the use above the def.
771     if (!T->use_empty() && is_contained(Insn->operands(), cast<const Value>(T)))
772       continue;
773     if (K == InsKind::Scalar) {
774       if (safeToHoistScalar(BB, Insn->getParent(), NumBBsOnAllPaths))
775         Safe.push_back(CHI);
776     } else {
777       if (MemoryUseOrDef *UD = MSSA->getMemoryAccess(Insn))
778         if (safeToHoistLdSt(T, Insn, UD, K, NumBBsOnAllPaths))
779           Safe.push_back(CHI);
780     }
781   }
782 }
783 
fillRenameStack(BasicBlock * BB,InValuesType & ValueBBs,GVNHoist::RenameStackType & RenameStack)784 void GVNHoist::fillRenameStack(BasicBlock *BB, InValuesType &ValueBBs,
785                                GVNHoist::RenameStackType &RenameStack) {
786   auto it1 = ValueBBs.find(BB);
787   if (it1 != ValueBBs.end()) {
788     // Iterate in reverse order to keep lower ranked values on the top.
789     LLVM_DEBUG(dbgs() << "\nVisiting: " << BB->getName()
790                       << " for pushing instructions on stack";);
791     for (std::pair<VNType, Instruction *> &VI : reverse(it1->second)) {
792       // Get the value of instruction I
793       LLVM_DEBUG(dbgs() << "\nPushing on stack: " << *VI.second);
794       RenameStack[VI.first].push_back(VI.second);
795     }
796   }
797 }
798 
fillChiArgs(BasicBlock * BB,OutValuesType & CHIBBs,GVNHoist::RenameStackType & RenameStack)799 void GVNHoist::fillChiArgs(BasicBlock *BB, OutValuesType &CHIBBs,
800                            GVNHoist::RenameStackType &RenameStack) {
801   // For each *predecessor* (because Post-DOM) of BB check if it has a CHI
802   for (auto *Pred : predecessors(BB)) {
803     auto P = CHIBBs.find(Pred);
804     if (P == CHIBBs.end()) {
805       continue;
806     }
807     LLVM_DEBUG(dbgs() << "\nLooking at CHIs in: " << Pred->getName(););
808     // A CHI is found (BB -> Pred is an edge in the CFG)
809     // Pop the stack until Top(V) = Ve.
810     auto &VCHI = P->second;
811     for (auto It = VCHI.begin(), E = VCHI.end(); It != E;) {
812       CHIArg &C = *It;
813       if (!C.Dest) {
814         auto si = RenameStack.find(C.VN);
815         // The Basic Block where CHI is must dominate the value we want to
816         // track in a CHI. In the PDom walk, there can be values in the
817         // stack which are not control dependent e.g., nested loop.
818         if (si != RenameStack.end() && si->second.size() &&
819             DT->properlyDominates(Pred, si->second.back()->getParent())) {
820           C.Dest = BB;                     // Assign the edge
821           C.I = si->second.pop_back_val(); // Assign the argument
822           LLVM_DEBUG(dbgs()
823                      << "\nCHI Inserted in BB: " << C.Dest->getName() << *C.I
824                      << ", VN: " << C.VN.first << ", " << C.VN.second);
825         }
826         // Move to next CHI of a different value
827         It = std::find_if(It, VCHI.end(), [It](CHIArg &A) { return A != *It; });
828       } else
829         ++It;
830     }
831   }
832 }
833 
findHoistableCandidates(OutValuesType & CHIBBs,GVNHoist::InsKind K,HoistingPointList & HPL)834 void GVNHoist::findHoistableCandidates(OutValuesType &CHIBBs,
835                                        GVNHoist::InsKind K,
836                                        HoistingPointList &HPL) {
837   auto cmpVN = [](const CHIArg &A, const CHIArg &B) { return A.VN < B.VN; };
838 
839   // CHIArgs now have the outgoing values, so check for anticipability and
840   // accumulate hoistable candidates in HPL.
841   for (std::pair<BasicBlock *, SmallVector<CHIArg, 2>> &A : CHIBBs) {
842     BasicBlock *BB = A.first;
843     SmallVectorImpl<CHIArg> &CHIs = A.second;
844     // Vector of PHIs contains PHIs for different instructions.
845     // Sort the args according to their VNs, such that identical
846     // instructions are together.
847     llvm::stable_sort(CHIs, cmpVN);
848     auto TI = BB->getTerminator();
849     auto B = CHIs.begin();
850     // [PreIt, PHIIt) form a range of CHIs which have identical VNs.
851     auto PHIIt = llvm::find_if(CHIs, [B](CHIArg &A) { return A != *B; });
852     auto PrevIt = CHIs.begin();
853     while (PrevIt != PHIIt) {
854       // Collect values which satisfy safety checks.
855       SmallVector<CHIArg, 2> Safe;
856       // We check for safety first because there might be multiple values in
857       // the same path, some of which are not safe to be hoisted, but overall
858       // each edge has at least one value which can be hoisted, making the
859       // value anticipable along that path.
860       checkSafety(make_range(PrevIt, PHIIt), BB, K, Safe);
861 
862       // List of safe values should be anticipable at TI.
863       if (valueAnticipable(make_range(Safe.begin(), Safe.end()), TI)) {
864         HPL.push_back({BB, SmallVecInsn()});
865         SmallVecInsn &V = HPL.back().second;
866         for (auto B : Safe)
867           V.push_back(B.I);
868       }
869 
870       // Check other VNs
871       PrevIt = PHIIt;
872       PHIIt = std::find_if(PrevIt, CHIs.end(),
873                            [PrevIt](CHIArg &A) { return A != *PrevIt; });
874     }
875   }
876 }
877 
allOperandsAvailable(const Instruction * I,const BasicBlock * HoistPt) const878 bool GVNHoist::allOperandsAvailable(const Instruction *I,
879                                     const BasicBlock *HoistPt) const {
880   for (const Use &Op : I->operands())
881     if (const auto *Inst = dyn_cast<Instruction>(&Op))
882       if (!DT->dominates(Inst->getParent(), HoistPt))
883         return false;
884 
885   return true;
886 }
887 
allGepOperandsAvailable(const Instruction * I,const BasicBlock * HoistPt) const888 bool GVNHoist::allGepOperandsAvailable(const Instruction *I,
889                                        const BasicBlock *HoistPt) const {
890   for (const Use &Op : I->operands())
891     if (const auto *Inst = dyn_cast<Instruction>(&Op))
892       if (!DT->dominates(Inst->getParent(), HoistPt)) {
893         if (const GetElementPtrInst *GepOp =
894                 dyn_cast<GetElementPtrInst>(Inst)) {
895           if (!allGepOperandsAvailable(GepOp, HoistPt))
896             return false;
897           // Gep is available if all operands of GepOp are available.
898         } else {
899           // Gep is not available if it has operands other than GEPs that are
900           // defined in blocks not dominating HoistPt.
901           return false;
902         }
903       }
904   return true;
905 }
906 
makeGepsAvailable(Instruction * Repl,BasicBlock * HoistPt,const SmallVecInsn & InstructionsToHoist,Instruction * Gep) const907 void GVNHoist::makeGepsAvailable(Instruction *Repl, BasicBlock *HoistPt,
908                                  const SmallVecInsn &InstructionsToHoist,
909                                  Instruction *Gep) const {
910   assert(allGepOperandsAvailable(Gep, HoistPt) && "GEP operands not available");
911 
912   Instruction *ClonedGep = Gep->clone();
913   for (unsigned i = 0, e = Gep->getNumOperands(); i != e; ++i)
914     if (Instruction *Op = dyn_cast<Instruction>(Gep->getOperand(i))) {
915       // Check whether the operand is already available.
916       if (DT->dominates(Op->getParent(), HoistPt))
917         continue;
918 
919       // As a GEP can refer to other GEPs, recursively make all the operands
920       // of this GEP available at HoistPt.
921       if (GetElementPtrInst *GepOp = dyn_cast<GetElementPtrInst>(Op))
922         makeGepsAvailable(ClonedGep, HoistPt, InstructionsToHoist, GepOp);
923     }
924 
925   // Copy Gep and replace its uses in Repl with ClonedGep.
926   ClonedGep->insertBefore(HoistPt->getTerminator());
927 
928   // Conservatively discard any optimization hints, they may differ on the
929   // other paths.
930   ClonedGep->dropUnknownNonDebugMetadata();
931 
932   // If we have optimization hints which agree with each other along different
933   // paths, preserve them.
934   for (const Instruction *OtherInst : InstructionsToHoist) {
935     const GetElementPtrInst *OtherGep;
936     if (auto *OtherLd = dyn_cast<LoadInst>(OtherInst))
937       OtherGep = cast<GetElementPtrInst>(OtherLd->getPointerOperand());
938     else
939       OtherGep = cast<GetElementPtrInst>(
940           cast<StoreInst>(OtherInst)->getPointerOperand());
941     ClonedGep->andIRFlags(OtherGep);
942 
943     // Merge debug locations of GEPs, because the hoisted GEP replaces those
944     // in branches. When cloning, ClonedGep preserves the debug location of
945     // Gepd, so Gep is skipped to avoid merging it twice.
946     if (OtherGep != Gep) {
947       ClonedGep->applyMergedLocation(ClonedGep->getDebugLoc(),
948                                      OtherGep->getDebugLoc());
949     }
950   }
951 
952   // Replace uses of Gep with ClonedGep in Repl.
953   Repl->replaceUsesOfWith(Gep, ClonedGep);
954 }
955 
updateAlignment(Instruction * I,Instruction * Repl)956 void GVNHoist::updateAlignment(Instruction *I, Instruction *Repl) {
957   if (auto *ReplacementLoad = dyn_cast<LoadInst>(Repl)) {
958     ReplacementLoad->setAlignment(
959         std::min(ReplacementLoad->getAlign(), cast<LoadInst>(I)->getAlign()));
960     ++NumLoadsRemoved;
961   } else if (auto *ReplacementStore = dyn_cast<StoreInst>(Repl)) {
962     ReplacementStore->setAlignment(
963         std::min(ReplacementStore->getAlign(), cast<StoreInst>(I)->getAlign()));
964     ++NumStoresRemoved;
965   } else if (auto *ReplacementAlloca = dyn_cast<AllocaInst>(Repl)) {
966     ReplacementAlloca->setAlignment(std::max(ReplacementAlloca->getAlign(),
967                                              cast<AllocaInst>(I)->getAlign()));
968   } else if (isa<CallInst>(Repl)) {
969     ++NumCallsRemoved;
970   }
971 }
972 
rauw(const SmallVecInsn & Candidates,Instruction * Repl,MemoryUseOrDef * NewMemAcc)973 unsigned GVNHoist::rauw(const SmallVecInsn &Candidates, Instruction *Repl,
974                         MemoryUseOrDef *NewMemAcc) {
975   unsigned NR = 0;
976   for (Instruction *I : Candidates) {
977     if (I != Repl) {
978       ++NR;
979       updateAlignment(I, Repl);
980       if (NewMemAcc) {
981         // Update the uses of the old MSSA access with NewMemAcc.
982         MemoryAccess *OldMA = MSSA->getMemoryAccess(I);
983         OldMA->replaceAllUsesWith(NewMemAcc);
984         MSSAUpdater->removeMemoryAccess(OldMA);
985       }
986 
987       combineMetadataForCSE(Repl, I, true);
988       Repl->andIRFlags(I);
989       I->replaceAllUsesWith(Repl);
990       // Also invalidate the Alias Analysis cache.
991       MD->removeInstruction(I);
992       I->eraseFromParent();
993     }
994   }
995   return NR;
996 }
997 
raMPHIuw(MemoryUseOrDef * NewMemAcc)998 void GVNHoist::raMPHIuw(MemoryUseOrDef *NewMemAcc) {
999   SmallPtrSet<MemoryPhi *, 4> UsePhis;
1000   for (User *U : NewMemAcc->users())
1001     if (MemoryPhi *Phi = dyn_cast<MemoryPhi>(U))
1002       UsePhis.insert(Phi);
1003 
1004   for (MemoryPhi *Phi : UsePhis) {
1005     auto In = Phi->incoming_values();
1006     if (llvm::all_of(In, [&](Use &U) { return U == NewMemAcc; })) {
1007       Phi->replaceAllUsesWith(NewMemAcc);
1008       MSSAUpdater->removeMemoryAccess(Phi);
1009     }
1010   }
1011 }
1012 
removeAndReplace(const SmallVecInsn & Candidates,Instruction * Repl,BasicBlock * DestBB,bool MoveAccess)1013 unsigned GVNHoist::removeAndReplace(const SmallVecInsn &Candidates,
1014                                     Instruction *Repl, BasicBlock *DestBB,
1015                                     bool MoveAccess) {
1016   MemoryUseOrDef *NewMemAcc = MSSA->getMemoryAccess(Repl);
1017   if (MoveAccess && NewMemAcc) {
1018     // The definition of this ld/st will not change: ld/st hoisting is
1019     // legal when the ld/st is not moved past its current definition.
1020     MSSAUpdater->moveToPlace(NewMemAcc, DestBB, MemorySSA::BeforeTerminator);
1021   }
1022 
1023   // Replace all other instructions with Repl with memory access NewMemAcc.
1024   unsigned NR = rauw(Candidates, Repl, NewMemAcc);
1025 
1026   // Remove MemorySSA phi nodes with the same arguments.
1027   if (NewMemAcc)
1028     raMPHIuw(NewMemAcc);
1029   return NR;
1030 }
1031 
makeGepOperandsAvailable(Instruction * Repl,BasicBlock * HoistPt,const SmallVecInsn & InstructionsToHoist) const1032 bool GVNHoist::makeGepOperandsAvailable(
1033     Instruction *Repl, BasicBlock *HoistPt,
1034     const SmallVecInsn &InstructionsToHoist) const {
1035   // Check whether the GEP of a ld/st can be synthesized at HoistPt.
1036   GetElementPtrInst *Gep = nullptr;
1037   Instruction *Val = nullptr;
1038   if (auto *Ld = dyn_cast<LoadInst>(Repl)) {
1039     Gep = dyn_cast<GetElementPtrInst>(Ld->getPointerOperand());
1040   } else if (auto *St = dyn_cast<StoreInst>(Repl)) {
1041     Gep = dyn_cast<GetElementPtrInst>(St->getPointerOperand());
1042     Val = dyn_cast<Instruction>(St->getValueOperand());
1043     // Check that the stored value is available.
1044     if (Val) {
1045       if (isa<GetElementPtrInst>(Val)) {
1046         // Check whether we can compute the GEP at HoistPt.
1047         if (!allGepOperandsAvailable(Val, HoistPt))
1048           return false;
1049       } else if (!DT->dominates(Val->getParent(), HoistPt))
1050         return false;
1051     }
1052   }
1053 
1054   // Check whether we can compute the Gep at HoistPt.
1055   if (!Gep || !allGepOperandsAvailable(Gep, HoistPt))
1056     return false;
1057 
1058   makeGepsAvailable(Repl, HoistPt, InstructionsToHoist, Gep);
1059 
1060   if (Val && isa<GetElementPtrInst>(Val))
1061     makeGepsAvailable(Repl, HoistPt, InstructionsToHoist, Val);
1062 
1063   return true;
1064 }
1065 
hoist(HoistingPointList & HPL)1066 std::pair<unsigned, unsigned> GVNHoist::hoist(HoistingPointList &HPL) {
1067   unsigned NI = 0, NL = 0, NS = 0, NC = 0, NR = 0;
1068   for (const HoistingPointInfo &HP : HPL) {
1069     // Find out whether we already have one of the instructions in HoistPt,
1070     // in which case we do not have to move it.
1071     BasicBlock *DestBB = HP.first;
1072     const SmallVecInsn &InstructionsToHoist = HP.second;
1073     Instruction *Repl = nullptr;
1074     for (Instruction *I : InstructionsToHoist)
1075       if (I->getParent() == DestBB)
1076         // If there are two instructions in HoistPt to be hoisted in place:
1077         // update Repl to be the first one, such that we can rename the uses
1078         // of the second based on the first.
1079         if (!Repl || firstInBB(I, Repl))
1080           Repl = I;
1081 
1082     // Keep track of whether we moved the instruction so we know whether we
1083     // should move the MemoryAccess.
1084     bool MoveAccess = true;
1085     if (Repl) {
1086       // Repl is already in HoistPt: it remains in place.
1087       assert(allOperandsAvailable(Repl, DestBB) &&
1088              "instruction depends on operands that are not available");
1089       MoveAccess = false;
1090     } else {
1091       // When we do not find Repl in HoistPt, select the first in the list
1092       // and move it to HoistPt.
1093       Repl = InstructionsToHoist.front();
1094 
1095       // We can move Repl in HoistPt only when all operands are available.
1096       // The order in which hoistings are done may influence the availability
1097       // of operands.
1098       if (!allOperandsAvailable(Repl, DestBB)) {
1099         // When HoistingGeps there is nothing more we can do to make the
1100         // operands available: just continue.
1101         if (HoistingGeps)
1102           continue;
1103 
1104         // When not HoistingGeps we need to copy the GEPs.
1105         if (!makeGepOperandsAvailable(Repl, DestBB, InstructionsToHoist))
1106           continue;
1107       }
1108 
1109       // Move the instruction at the end of HoistPt.
1110       Instruction *Last = DestBB->getTerminator();
1111       MD->removeInstruction(Repl);
1112       Repl->moveBefore(Last);
1113 
1114       DFSNumber[Repl] = DFSNumber[Last]++;
1115     }
1116 
1117     // Drop debug location as per debug info update guide.
1118     Repl->dropLocation();
1119     NR += removeAndReplace(InstructionsToHoist, Repl, DestBB, MoveAccess);
1120 
1121     if (isa<LoadInst>(Repl))
1122       ++NL;
1123     else if (isa<StoreInst>(Repl))
1124       ++NS;
1125     else if (isa<CallInst>(Repl))
1126       ++NC;
1127     else // Scalar
1128       ++NI;
1129   }
1130 
1131   if (MSSA && VerifyMemorySSA)
1132     MSSA->verifyMemorySSA();
1133 
1134   NumHoisted += NL + NS + NC + NI;
1135   NumRemoved += NR;
1136   NumLoadsHoisted += NL;
1137   NumStoresHoisted += NS;
1138   NumCallsHoisted += NC;
1139   return {NI, NL + NC + NS};
1140 }
1141 
hoistExpressions(Function & F)1142 std::pair<unsigned, unsigned> GVNHoist::hoistExpressions(Function &F) {
1143   InsnInfo II;
1144   LoadInfo LI;
1145   StoreInfo SI;
1146   CallInfo CI;
1147   for (BasicBlock *BB : depth_first(&F.getEntryBlock())) {
1148     int InstructionNb = 0;
1149     for (Instruction &I1 : *BB) {
1150       // If I1 cannot guarantee progress, subsequent instructions
1151       // in BB cannot be hoisted anyways.
1152       if (!isGuaranteedToTransferExecutionToSuccessor(&I1)) {
1153         HoistBarrier.insert(BB);
1154         break;
1155       }
1156       // Only hoist the first instructions in BB up to MaxDepthInBB. Hoisting
1157       // deeper may increase the register pressure and compilation time.
1158       if (MaxDepthInBB != -1 && InstructionNb++ >= MaxDepthInBB)
1159         break;
1160 
1161       // Do not value number terminator instructions.
1162       if (I1.isTerminator())
1163         break;
1164 
1165       if (auto *Load = dyn_cast<LoadInst>(&I1))
1166         LI.insert(Load, VN);
1167       else if (auto *Store = dyn_cast<StoreInst>(&I1))
1168         SI.insert(Store, VN);
1169       else if (auto *Call = dyn_cast<CallInst>(&I1)) {
1170         if (auto *Intr = dyn_cast<IntrinsicInst>(Call)) {
1171           if (isa<DbgInfoIntrinsic>(Intr) ||
1172               Intr->getIntrinsicID() == Intrinsic::assume ||
1173               Intr->getIntrinsicID() == Intrinsic::sideeffect)
1174             continue;
1175         }
1176         if (Call->mayHaveSideEffects())
1177           break;
1178 
1179         if (Call->isConvergent())
1180           break;
1181 
1182         CI.insert(Call, VN);
1183       } else if (HoistingGeps || !isa<GetElementPtrInst>(&I1))
1184         // Do not hoist scalars past calls that may write to memory because
1185         // that could result in spills later. geps are handled separately.
1186         // TODO: We can relax this for targets like AArch64 as they have more
1187         // registers than X86.
1188         II.insert(&I1, VN);
1189     }
1190   }
1191 
1192   HoistingPointList HPL;
1193   computeInsertionPoints(II.getVNTable(), HPL, InsKind::Scalar);
1194   computeInsertionPoints(LI.getVNTable(), HPL, InsKind::Load);
1195   computeInsertionPoints(SI.getVNTable(), HPL, InsKind::Store);
1196   computeInsertionPoints(CI.getScalarVNTable(), HPL, InsKind::Scalar);
1197   computeInsertionPoints(CI.getLoadVNTable(), HPL, InsKind::Load);
1198   computeInsertionPoints(CI.getStoreVNTable(), HPL, InsKind::Store);
1199   return hoist(HPL);
1200 }
1201 
1202 } // end namespace llvm
1203 
run(Function & F,FunctionAnalysisManager & AM)1204 PreservedAnalyses GVNHoistPass::run(Function &F, FunctionAnalysisManager &AM) {
1205   DominatorTree &DT = AM.getResult<DominatorTreeAnalysis>(F);
1206   PostDominatorTree &PDT = AM.getResult<PostDominatorTreeAnalysis>(F);
1207   AliasAnalysis &AA = AM.getResult<AAManager>(F);
1208   MemoryDependenceResults &MD = AM.getResult<MemoryDependenceAnalysis>(F);
1209   MemorySSA &MSSA = AM.getResult<MemorySSAAnalysis>(F).getMSSA();
1210   GVNHoist G(&DT, &PDT, &AA, &MD, &MSSA);
1211   if (!G.run(F))
1212     return PreservedAnalyses::all();
1213 
1214   PreservedAnalyses PA;
1215   PA.preserve<DominatorTreeAnalysis>();
1216   PA.preserve<MemorySSAAnalysis>();
1217   return PA;
1218 }
1219