LLVM  5.0.0
GVNHoist.cpp
Go to the documentation of this file.
1 //===- 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
12 // 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 //
16 // Hoisting may affect the performance in some cases. To mitigate that, hoisting
17 // is disabled in the following cases.
18 // 1. Scalars across calls.
19 // 2. geps when corresponding load/store cannot be hoisted.
20 //
21 // TODO: Hoist from >2 successors. Currently GVNHoist will not hoist stores
22 // in this case because it works on two instructions at a time.
23 // entry:
24 // switch i32 %c1, label %exit1 [
25 // i32 0, label %sw0
26 // i32 1, label %sw1
27 // ]
28 //
29 // sw0:
30 // store i32 1, i32* @G
31 // br label %exit
32 //
33 // sw1:
34 // store i32 1, i32* @G
35 // br label %exit
36 //
37 // exit1:
38 // store i32 1, i32* @G
39 // ret void
40 // exit:
41 // ret void
42 //===----------------------------------------------------------------------===//
43 
44 #include "llvm/ADT/DenseMap.h"
45 #include "llvm/ADT/SmallPtrSet.h"
46 #include "llvm/ADT/Statistic.h"
51 #include "llvm/Transforms/Scalar.h"
54 
55 using namespace llvm;
56 
57 #define DEBUG_TYPE "gvn-hoist"
58 
59 STATISTIC(NumHoisted, "Number of instructions hoisted");
60 STATISTIC(NumRemoved, "Number of instructions removed");
61 STATISTIC(NumLoadsHoisted, "Number of loads hoisted");
62 STATISTIC(NumLoadsRemoved, "Number of loads removed");
63 STATISTIC(NumStoresHoisted, "Number of stores hoisted");
64 STATISTIC(NumStoresRemoved, "Number of stores removed");
65 STATISTIC(NumCallsHoisted, "Number of calls hoisted");
66 STATISTIC(NumCallsRemoved, "Number of calls removed");
67 
68 static cl::opt<int>
69  MaxHoistedThreshold("gvn-max-hoisted", cl::Hidden, cl::init(-1),
70  cl::desc("Max number of instructions to hoist "
71  "(default unlimited = -1)"));
73  "gvn-hoist-max-bbs", cl::Hidden, cl::init(4),
74  cl::desc("Max number of basic blocks on the path between "
75  "hoisting locations (default = 4, unlimited = -1)"));
76 
78  "gvn-hoist-max-depth", cl::Hidden, cl::init(100),
79  cl::desc("Hoist instructions from the beginning of the BB up to the "
80  "maximum specified depth (default = 100, unlimited = -1)"));
81 
82 static cl::opt<int>
83  MaxChainLength("gvn-hoist-max-chain-length", cl::Hidden, cl::init(10),
84  cl::desc("Maximum length of dependent chains to hoist "
85  "(default = 10, unlimited = -1)"));
86 
87 namespace llvm {
88 
89 // Provides a sorting function based on the execution order of two instructions.
90 struct SortByDFSIn {
91 private:
93 
94 public:
96 
97  // Returns true when A executes before B.
98  bool operator()(const Instruction *A, const Instruction *B) const {
99  const BasicBlock *BA = A->getParent();
100  const BasicBlock *BB = B->getParent();
101  unsigned ADFS, BDFS;
102  if (BA == BB) {
103  ADFS = DFSNumber.lookup(A);
104  BDFS = DFSNumber.lookup(B);
105  } else {
106  ADFS = DFSNumber.lookup(BA);
107  BDFS = DFSNumber.lookup(BB);
108  }
109  assert(ADFS && BDFS);
110  return ADFS < BDFS;
111  }
112 };
113 
114 // A map from a pair of VNs to all the instructions with those VNs.
117 // An invalid value number Used when inserting a single value number into
118 // VNtoInsns.
119 enum : unsigned { InvalidVN = ~2U };
120 
121 // Records all scalar instructions candidate for code hoisting.
122 class InsnInfo {
123  VNtoInsns VNtoScalars;
124 
125 public:
126  // Inserts I and its value number in VNtoScalars.
128  // Scalar instruction.
129  unsigned V = VN.lookupOrAdd(I);
130  VNtoScalars[{V, InvalidVN}].push_back(I);
131  }
132 
133  const VNtoInsns &getVNTable() const { return VNtoScalars; }
134 };
135 
136 // Records all load instructions candidate for code hoisting.
137 class LoadInfo {
138  VNtoInsns VNtoLoads;
139 
140 public:
141  // Insert Load and the value number of its memory address in VNtoLoads.
143  if (Load->isSimple()) {
144  unsigned V = VN.lookupOrAdd(Load->getPointerOperand());
145  VNtoLoads[{V, InvalidVN}].push_back(Load);
146  }
147  }
148 
149  const VNtoInsns &getVNTable() const { return VNtoLoads; }
150 };
151 
152 // Records all store instructions candidate for code hoisting.
153 class StoreInfo {
154  VNtoInsns VNtoStores;
155 
156 public:
157  // Insert the Store and a hash number of the store address and the stored
158  // value in VNtoStores.
160  if (!Store->isSimple())
161  return;
162  // Hash the store address and the stored value.
163  Value *Ptr = Store->getPointerOperand();
164  Value *Val = Store->getValueOperand();
165  VNtoStores[{VN.lookupOrAdd(Ptr), VN.lookupOrAdd(Val)}].push_back(Store);
166  }
167 
168  const VNtoInsns &getVNTable() const { return VNtoStores; }
169 };
170 
171 // Records all call instructions candidate for code hoisting.
172 class CallInfo {
173  VNtoInsns VNtoCallsScalars;
174  VNtoInsns VNtoCallsLoads;
175  VNtoInsns VNtoCallsStores;
176 
177 public:
178  // Insert Call and its value numbering in one of the VNtoCalls* containers.
179  void insert(CallInst *Call, GVN::ValueTable &VN) {
180  // A call that doesNotAccessMemory is handled as a Scalar,
181  // onlyReadsMemory will be handled as a Load instruction,
182  // all other calls will be handled as stores.
183  unsigned V = VN.lookupOrAdd(Call);
184  auto Entry = std::make_pair(V, InvalidVN);
185 
186  if (Call->doesNotAccessMemory())
187  VNtoCallsScalars[Entry].push_back(Call);
188  else if (Call->onlyReadsMemory())
189  VNtoCallsLoads[Entry].push_back(Call);
190  else
191  VNtoCallsStores[Entry].push_back(Call);
192  }
193 
194  const VNtoInsns &getScalarVNTable() const { return VNtoCallsScalars; }
195 
196  const VNtoInsns &getLoadVNTable() const { return VNtoCallsLoads; }
197 
198  const VNtoInsns &getStoreVNTable() const { return VNtoCallsStores; }
199 };
200 
204 
205 static void combineKnownMetadata(Instruction *ReplInst, Instruction *I) {
206  static const unsigned KnownIDs[] = {
211  combineMetadata(ReplInst, I, KnownIDs);
212 }
213 
214 // This pass hoists common computations across branches sharing common
215 // dominator. The primary goal is to reduce the code size, and in some
216 // cases reduce critical path (by exposing more ILP).
217 class GVNHoist {
218 public:
220  MemorySSA *MSSA)
221  : DT(DT), AA(AA), MD(MD), MSSA(MSSA),
222  MSSAUpdater(make_unique<MemorySSAUpdater>(MSSA)),
223  HoistingGeps(false),
224  HoistedCtr(0)
225  { }
226 
227  bool run(Function &F) {
228  VN.setDomTree(DT);
229  VN.setAliasAnalysis(AA);
230  VN.setMemDep(MD);
231  bool Res = false;
232  // Perform DFS Numbering of instructions.
233  unsigned BBI = 0;
234  for (const BasicBlock *BB : depth_first(&F.getEntryBlock())) {
235  DFSNumber[BB] = ++BBI;
236  unsigned I = 0;
237  for (auto &Inst : *BB)
238  DFSNumber[&Inst] = ++I;
239  }
240 
241  int ChainLength = 0;
242 
243  // FIXME: use lazy evaluation of VN to avoid the fix-point computation.
244  while (1) {
245  if (MaxChainLength != -1 && ++ChainLength >= MaxChainLength)
246  return Res;
247 
248  auto HoistStat = hoistExpressions(F);
249  if (HoistStat.first + HoistStat.second == 0)
250  return Res;
251 
252  if (HoistStat.second > 0)
253  // To address a limitation of the current GVN, we need to rerun the
254  // hoisting after we hoisted loads or stores in order to be able to
255  // hoist all scalars dependent on the hoisted ld/st.
256  VN.clear();
257 
258  Res = true;
259  }
260 
261  return Res;
262  }
263 
264 private:
265  GVN::ValueTable VN;
266  DominatorTree *DT;
267  AliasAnalysis *AA;
269  MemorySSA *MSSA;
270  std::unique_ptr<MemorySSAUpdater> MSSAUpdater;
271  const bool HoistingGeps;
273  BBSideEffectsSet BBSideEffects;
274  DenseSet<const BasicBlock*> HoistBarrier;
275  int HoistedCtr;
276 
277  enum InsKind { Unknown, Scalar, Load, Store };
278 
279  // Return true when there are exception handling in BB.
280  bool hasEH(const BasicBlock *BB) {
281  auto It = BBSideEffects.find(BB);
282  if (It != BBSideEffects.end())
283  return It->second;
284 
285  if (BB->isEHPad() || BB->hasAddressTaken()) {
286  BBSideEffects[BB] = true;
287  return true;
288  }
289 
290  if (BB->getTerminator()->mayThrow()) {
291  BBSideEffects[BB] = true;
292  return true;
293  }
294 
295  BBSideEffects[BB] = false;
296  return false;
297  }
298 
299  // Return true when a successor of BB dominates A.
300  bool successorDominate(const BasicBlock *BB, const BasicBlock *A) {
301  for (const BasicBlock *Succ : BB->getTerminator()->successors())
302  if (DT->dominates(Succ, A))
303  return true;
304 
305  return false;
306  }
307 
308  // Return true when all paths from HoistBB to the end of the function pass
309  // through one of the blocks in WL.
310  bool hoistingFromAllPaths(const BasicBlock *HoistBB,
312 
313  // Copy WL as the loop will remove elements from it.
314  SmallPtrSet<const BasicBlock *, 2> WorkList(WL.begin(), WL.end());
315 
316  for (auto It = df_begin(HoistBB), E = df_end(HoistBB); It != E;) {
317  // There exists a path from HoistBB to the exit of the function if we are
318  // still iterating in DF traversal and we removed all instructions from
319  // the work list.
320  if (WorkList.empty())
321  return false;
322 
323  const BasicBlock *BB = *It;
324  if (WorkList.erase(BB)) {
325  // Stop DFS traversal when BB is in the work list.
326  It.skipChildren();
327  continue;
328  }
329 
330  // We reached the leaf Basic Block => not all paths have this instruction.
331  if (!BB->getTerminator()->getNumSuccessors())
332  return false;
333 
334  // When reaching the back-edge of a loop, there may be a path through the
335  // loop that does not pass through B or C before exiting the loop.
336  if (successorDominate(BB, HoistBB))
337  return false;
338 
339  // Increment DFS traversal when not skipping children.
340  ++It;
341  }
342 
343  return true;
344  }
345 
346  /* Return true when I1 appears before I2 in the instructions of BB. */
347  bool firstInBB(const Instruction *I1, const Instruction *I2) {
348  assert(I1->getParent() == I2->getParent());
349  unsigned I1DFS = DFSNumber.lookup(I1);
350  unsigned I2DFS = DFSNumber.lookup(I2);
351  assert(I1DFS && I2DFS);
352  return I1DFS < I2DFS;
353  }
354 
355  // Return true when there are memory uses of Def in BB.
356  bool hasMemoryUse(const Instruction *NewPt, MemoryDef *Def,
357  const BasicBlock *BB) {
358  const MemorySSA::AccessList *Acc = MSSA->getBlockAccesses(BB);
359  if (!Acc)
360  return false;
361 
362  Instruction *OldPt = Def->getMemoryInst();
363  const BasicBlock *OldBB = OldPt->getParent();
364  const BasicBlock *NewBB = NewPt->getParent();
365  bool ReachedNewPt = false;
366 
367  for (const MemoryAccess &MA : *Acc)
368  if (const MemoryUse *MU = dyn_cast<MemoryUse>(&MA)) {
369  Instruction *Insn = MU->getMemoryInst();
370 
371  // Do not check whether MU aliases Def when MU occurs after OldPt.
372  if (BB == OldBB && firstInBB(OldPt, Insn))
373  break;
374 
375  // Do not check whether MU aliases Def when MU occurs before NewPt.
376  if (BB == NewBB) {
377  if (!ReachedNewPt) {
378  if (firstInBB(Insn, NewPt))
379  continue;
380  ReachedNewPt = true;
381  }
382  }
383  if (MemorySSAUtil::defClobbersUseOrDef(Def, MU, *AA))
384  return true;
385  }
386 
387  return false;
388  }
389 
390  // Return true when there are exception handling or loads of memory Def
391  // between Def and NewPt. This function is only called for stores: Def is
392  // the MemoryDef of the store to be hoisted.
393 
394  // Decrement by 1 NBBsOnAllPaths for each block between HoistPt and BB, and
395  // return true when the counter NBBsOnAllPaths reaces 0, except when it is
396  // initialized to -1 which is unlimited.
397  bool hasEHOrLoadsOnPath(const Instruction *NewPt, MemoryDef *Def,
398  int &NBBsOnAllPaths) {
399  const BasicBlock *NewBB = NewPt->getParent();
400  const BasicBlock *OldBB = Def->getBlock();
401  assert(DT->dominates(NewBB, OldBB) && "invalid path");
402  assert(DT->dominates(Def->getDefiningAccess()->getBlock(), NewBB) &&
403  "def does not dominate new hoisting point");
404 
405  // Walk all basic blocks reachable in depth-first iteration on the inverse
406  // CFG from OldBB to NewBB. These blocks are all the blocks that may be
407  // executed between the execution of NewBB and OldBB. Hoisting an expression
408  // from OldBB into NewBB has to be safe on all execution paths.
409  for (auto I = idf_begin(OldBB), E = idf_end(OldBB); I != E;) {
410  const BasicBlock *BB = *I;
411  if (BB == NewBB) {
412  // Stop traversal when reaching HoistPt.
413  I.skipChildren();
414  continue;
415  }
416 
417  // Stop walk once the limit is reached.
418  if (NBBsOnAllPaths == 0)
419  return true;
420 
421  // Impossible to hoist with exceptions on the path.
422  if (hasEH(BB))
423  return true;
424 
425  // No such instruction after HoistBarrier in a basic block was
426  // selected for hoisting so instructions selected within basic block with
427  // a hoist barrier can be hoisted.
428  if ((BB != OldBB) && HoistBarrier.count(BB))
429  return true;
430 
431  // Check that we do not move a store past loads.
432  if (hasMemoryUse(NewPt, Def, BB))
433  return true;
434 
435  // -1 is unlimited number of blocks on all paths.
436  if (NBBsOnAllPaths != -1)
437  --NBBsOnAllPaths;
438 
439  ++I;
440  }
441 
442  return false;
443  }
444 
445  // Return true when there are exception handling between HoistPt and BB.
446  // Decrement by 1 NBBsOnAllPaths for each block between HoistPt and BB, and
447  // return true when the counter NBBsOnAllPaths reaches 0, except when it is
448  // initialized to -1 which is unlimited.
449  bool hasEHOnPath(const BasicBlock *HoistPt, const BasicBlock *SrcBB,
450  int &NBBsOnAllPaths) {
451  assert(DT->dominates(HoistPt, SrcBB) && "Invalid path");
452 
453  // Walk all basic blocks reachable in depth-first iteration on
454  // the inverse CFG from BBInsn to NewHoistPt. These blocks are all the
455  // blocks that may be executed between the execution of NewHoistPt and
456  // BBInsn. Hoisting an expression from BBInsn into NewHoistPt has to be safe
457  // on all execution paths.
458  for (auto I = idf_begin(SrcBB), E = idf_end(SrcBB); I != E;) {
459  const BasicBlock *BB = *I;
460  if (BB == HoistPt) {
461  // Stop traversal when reaching NewHoistPt.
462  I.skipChildren();
463  continue;
464  }
465 
466  // Stop walk once the limit is reached.
467  if (NBBsOnAllPaths == 0)
468  return true;
469 
470  // Impossible to hoist with exceptions on the path.
471  if (hasEH(BB))
472  return true;
473 
474  // No such instruction after HoistBarrier in a basic block was
475  // selected for hoisting so instructions selected within basic block with
476  // a hoist barrier can be hoisted.
477  if ((BB != SrcBB) && HoistBarrier.count(BB))
478  return true;
479 
480  // -1 is unlimited number of blocks on all paths.
481  if (NBBsOnAllPaths != -1)
482  --NBBsOnAllPaths;
483 
484  ++I;
485  }
486 
487  return false;
488  }
489 
490  // Return true when it is safe to hoist a memory load or store U from OldPt
491  // to NewPt.
492  bool safeToHoistLdSt(const Instruction *NewPt, const Instruction *OldPt,
493  MemoryUseOrDef *U, InsKind K, int &NBBsOnAllPaths) {
494 
495  // In place hoisting is safe.
496  if (NewPt == OldPt)
497  return true;
498 
499  const BasicBlock *NewBB = NewPt->getParent();
500  const BasicBlock *OldBB = OldPt->getParent();
501  const BasicBlock *UBB = U->getBlock();
502 
503  // Check for dependences on the Memory SSA.
505  BasicBlock *DBB = D->getBlock();
506  if (DT->properlyDominates(NewBB, DBB))
507  // Cannot move the load or store to NewBB above its definition in DBB.
508  return false;
509 
510  if (NewBB == DBB && !MSSA->isLiveOnEntryDef(D))
511  if (auto *UD = dyn_cast<MemoryUseOrDef>(D))
512  if (firstInBB(NewPt, UD->getMemoryInst()))
513  // Cannot move the load or store to NewPt above its definition in D.
514  return false;
515 
516  // Check for unsafe hoistings due to side effects.
517  if (K == InsKind::Store) {
518  if (hasEHOrLoadsOnPath(NewPt, dyn_cast<MemoryDef>(U), NBBsOnAllPaths))
519  return false;
520  } else if (hasEHOnPath(NewBB, OldBB, NBBsOnAllPaths))
521  return false;
522 
523  if (UBB == NewBB) {
524  if (DT->properlyDominates(DBB, NewBB))
525  return true;
526  assert(UBB == DBB);
527  assert(MSSA->locallyDominates(D, U));
528  }
529 
530  // No side effects: it is safe to hoist.
531  return true;
532  }
533 
534  // Return true when it is safe to hoist scalar instructions from all blocks in
535  // WL to HoistBB.
536  bool safeToHoistScalar(const BasicBlock *HoistBB,
538  int &NBBsOnAllPaths) {
539  // Check that the hoisted expression is needed on all paths.
540  if (!hoistingFromAllPaths(HoistBB, WL))
541  return false;
542 
543  for (const BasicBlock *BB : WL)
544  if (hasEHOnPath(HoistBB, BB, NBBsOnAllPaths))
545  return false;
546 
547  return true;
548  }
549 
550  // Each element of a hoisting list contains the basic block where to hoist and
551  // a list of instructions to be hoisted.
552  typedef std::pair<BasicBlock *, SmallVecInsn> HoistingPointInfo;
553  typedef SmallVector<HoistingPointInfo, 4> HoistingPointList;
554 
555  // Partition InstructionsToHoist into a set of candidates which can share a
556  // common hoisting point. The partitions are collected in HPL. IsScalar is
557  // true when the instructions in InstructionsToHoist are scalars. IsLoad is
558  // true when the InstructionsToHoist are loads, false when they are stores.
559  void partitionCandidates(SmallVecImplInsn &InstructionsToHoist,
560  HoistingPointList &HPL, InsKind K) {
561  // No need to sort for two instructions.
562  if (InstructionsToHoist.size() > 2) {
563  SortByDFSIn Pred(DFSNumber);
564  std::sort(InstructionsToHoist.begin(), InstructionsToHoist.end(), Pred);
565  }
566 
567  int NumBBsOnAllPaths = MaxNumberOfBBSInPath;
568 
569  SmallVecImplInsn::iterator II = InstructionsToHoist.begin();
570  SmallVecImplInsn::iterator Start = II;
571  Instruction *HoistPt = *II;
572  BasicBlock *HoistBB = HoistPt->getParent();
573  MemoryUseOrDef *UD;
574  if (K != InsKind::Scalar)
575  UD = MSSA->getMemoryAccess(HoistPt);
576 
577  for (++II; II != InstructionsToHoist.end(); ++II) {
578  Instruction *Insn = *II;
579  BasicBlock *BB = Insn->getParent();
580  BasicBlock *NewHoistBB;
581  Instruction *NewHoistPt;
582 
583  if (BB == HoistBB) { // Both are in the same Basic Block.
584  NewHoistBB = HoistBB;
585  NewHoistPt = firstInBB(Insn, HoistPt) ? Insn : HoistPt;
586  } else {
587  // If the hoisting point contains one of the instructions,
588  // then hoist there, otherwise hoist before the terminator.
589  NewHoistBB = DT->findNearestCommonDominator(HoistBB, BB);
590  if (NewHoistBB == BB)
591  NewHoistPt = Insn;
592  else if (NewHoistBB == HoistBB)
593  NewHoistPt = HoistPt;
594  else
595  NewHoistPt = NewHoistBB->getTerminator();
596  }
597 
599  WL.insert(HoistBB);
600  WL.insert(BB);
601 
602  if (K == InsKind::Scalar) {
603  if (safeToHoistScalar(NewHoistBB, WL, NumBBsOnAllPaths)) {
604  // Extend HoistPt to NewHoistPt.
605  HoistPt = NewHoistPt;
606  HoistBB = NewHoistBB;
607  continue;
608  }
609  } else {
610  // When NewBB already contains an instruction to be hoisted, the
611  // expression is needed on all paths.
612  // Check that the hoisted expression is needed on all paths: it is
613  // unsafe to hoist loads to a place where there may be a path not
614  // loading from the same address: for instance there may be a branch on
615  // which the address of the load may not be initialized.
616  if ((HoistBB == NewHoistBB || BB == NewHoistBB ||
617  hoistingFromAllPaths(NewHoistBB, WL)) &&
618  // Also check that it is safe to move the load or store from HoistPt
619  // to NewHoistPt, and from Insn to NewHoistPt.
620  safeToHoistLdSt(NewHoistPt, HoistPt, UD, K, NumBBsOnAllPaths) &&
621  safeToHoistLdSt(NewHoistPt, Insn, MSSA->getMemoryAccess(Insn),
622  K, NumBBsOnAllPaths)) {
623  // Extend HoistPt to NewHoistPt.
624  HoistPt = NewHoistPt;
625  HoistBB = NewHoistBB;
626  continue;
627  }
628  }
629 
630  // At this point it is not safe to extend the current hoisting to
631  // NewHoistPt: save the hoisting list so far.
632  if (std::distance(Start, II) > 1)
633  HPL.push_back({HoistBB, SmallVecInsn(Start, II)});
634 
635  // Start over from BB.
636  Start = II;
637  if (K != InsKind::Scalar)
638  UD = MSSA->getMemoryAccess(*Start);
639  HoistPt = Insn;
640  HoistBB = BB;
641  NumBBsOnAllPaths = MaxNumberOfBBSInPath;
642  }
643 
644  // Save the last partition.
645  if (std::distance(Start, II) > 1)
646  HPL.push_back({HoistBB, SmallVecInsn(Start, II)});
647  }
648 
649  // Initialize HPL from Map.
650  void computeInsertionPoints(const VNtoInsns &Map, HoistingPointList &HPL,
651  InsKind K) {
652  for (const auto &Entry : Map) {
653  if (MaxHoistedThreshold != -1 && ++HoistedCtr > MaxHoistedThreshold)
654  return;
655 
656  const SmallVecInsn &V = Entry.second;
657  if (V.size() < 2)
658  continue;
659 
660  // Compute the insertion point and the list of expressions to be hoisted.
661  SmallVecInsn InstructionsToHoist;
662  for (auto I : V)
663  // We don't need to check for hoist-barriers here because if
664  // I->getParent() is a barrier then I precedes the barrier.
665  if (!hasEH(I->getParent()))
666  InstructionsToHoist.push_back(I);
667 
668  if (!InstructionsToHoist.empty())
669  partitionCandidates(InstructionsToHoist, HPL, K);
670  }
671  }
672 
673  // Return true when all operands of Instr are available at insertion point
674  // HoistPt. When limiting the number of hoisted expressions, one could hoist
675  // a load without hoisting its access function. So before hoisting any
676  // expression, make sure that all its operands are available at insert point.
677  bool allOperandsAvailable(const Instruction *I,
678  const BasicBlock *HoistPt) const {
679  for (const Use &Op : I->operands())
680  if (const auto *Inst = dyn_cast<Instruction>(&Op))
681  if (!DT->dominates(Inst->getParent(), HoistPt))
682  return false;
683 
684  return true;
685  }
686 
687  // Same as allOperandsAvailable with recursive check for GEP operands.
688  bool allGepOperandsAvailable(const Instruction *I,
689  const BasicBlock *HoistPt) const {
690  for (const Use &Op : I->operands())
691  if (const auto *Inst = dyn_cast<Instruction>(&Op))
692  if (!DT->dominates(Inst->getParent(), HoistPt)) {
693  if (const GetElementPtrInst *GepOp =
694  dyn_cast<GetElementPtrInst>(Inst)) {
695  if (!allGepOperandsAvailable(GepOp, HoistPt))
696  return false;
697  // Gep is available if all operands of GepOp are available.
698  } else {
699  // Gep is not available if it has operands other than GEPs that are
700  // defined in blocks not dominating HoistPt.
701  return false;
702  }
703  }
704  return true;
705  }
706 
707  // Make all operands of the GEP available.
708  void makeGepsAvailable(Instruction *Repl, BasicBlock *HoistPt,
709  const SmallVecInsn &InstructionsToHoist,
710  Instruction *Gep) const {
711  assert(allGepOperandsAvailable(Gep, HoistPt) &&
712  "GEP operands not available");
713 
714  Instruction *ClonedGep = Gep->clone();
715  for (unsigned i = 0, e = Gep->getNumOperands(); i != e; ++i)
716  if (Instruction *Op = dyn_cast<Instruction>(Gep->getOperand(i))) {
717 
718  // Check whether the operand is already available.
719  if (DT->dominates(Op->getParent(), HoistPt))
720  continue;
721 
722  // As a GEP can refer to other GEPs, recursively make all the operands
723  // of this GEP available at HoistPt.
724  if (GetElementPtrInst *GepOp = dyn_cast<GetElementPtrInst>(Op))
725  makeGepsAvailable(ClonedGep, HoistPt, InstructionsToHoist, GepOp);
726  }
727 
728  // Copy Gep and replace its uses in Repl with ClonedGep.
729  ClonedGep->insertBefore(HoistPt->getTerminator());
730 
731  // Conservatively discard any optimization hints, they may differ on the
732  // other paths.
733  ClonedGep->dropUnknownNonDebugMetadata();
734 
735  // If we have optimization hints which agree with each other along different
736  // paths, preserve them.
737  for (const Instruction *OtherInst : InstructionsToHoist) {
738  const GetElementPtrInst *OtherGep;
739  if (auto *OtherLd = dyn_cast<LoadInst>(OtherInst))
740  OtherGep = cast<GetElementPtrInst>(OtherLd->getPointerOperand());
741  else
742  OtherGep = cast<GetElementPtrInst>(
743  cast<StoreInst>(OtherInst)->getPointerOperand());
744  ClonedGep->andIRFlags(OtherGep);
745  }
746 
747  // Replace uses of Gep with ClonedGep in Repl.
748  Repl->replaceUsesOfWith(Gep, ClonedGep);
749  }
750 
751  // In the case Repl is a load or a store, we make all their GEPs
752  // available: GEPs are not hoisted by default to avoid the address
753  // computations to be hoisted without the associated load or store.
754  bool makeGepOperandsAvailable(Instruction *Repl, BasicBlock *HoistPt,
755  const SmallVecInsn &InstructionsToHoist) const {
756  // Check whether the GEP of a ld/st can be synthesized at HoistPt.
757  GetElementPtrInst *Gep = nullptr;
758  Instruction *Val = nullptr;
759  if (auto *Ld = dyn_cast<LoadInst>(Repl)) {
760  Gep = dyn_cast<GetElementPtrInst>(Ld->getPointerOperand());
761  } else if (auto *St = dyn_cast<StoreInst>(Repl)) {
762  Gep = dyn_cast<GetElementPtrInst>(St->getPointerOperand());
763  Val = dyn_cast<Instruction>(St->getValueOperand());
764  // Check that the stored value is available.
765  if (Val) {
766  if (isa<GetElementPtrInst>(Val)) {
767  // Check whether we can compute the GEP at HoistPt.
768  if (!allGepOperandsAvailable(Val, HoistPt))
769  return false;
770  } else if (!DT->dominates(Val->getParent(), HoistPt))
771  return false;
772  }
773  }
774 
775  // Check whether we can compute the Gep at HoistPt.
776  if (!Gep || !allGepOperandsAvailable(Gep, HoistPt))
777  return false;
778 
779  makeGepsAvailable(Repl, HoistPt, InstructionsToHoist, Gep);
780 
781  if (Val && isa<GetElementPtrInst>(Val))
782  makeGepsAvailable(Repl, HoistPt, InstructionsToHoist, Val);
783 
784  return true;
785  }
786 
787  std::pair<unsigned, unsigned> hoist(HoistingPointList &HPL) {
788  unsigned NI = 0, NL = 0, NS = 0, NC = 0, NR = 0;
789  for (const HoistingPointInfo &HP : HPL) {
790  // Find out whether we already have one of the instructions in HoistPt,
791  // in which case we do not have to move it.
792  BasicBlock *HoistPt = HP.first;
793  const SmallVecInsn &InstructionsToHoist = HP.second;
794  Instruction *Repl = nullptr;
795  for (Instruction *I : InstructionsToHoist)
796  if (I->getParent() == HoistPt)
797  // If there are two instructions in HoistPt to be hoisted in place:
798  // update Repl to be the first one, such that we can rename the uses
799  // of the second based on the first.
800  if (!Repl || firstInBB(I, Repl))
801  Repl = I;
802 
803  // Keep track of whether we moved the instruction so we know whether we
804  // should move the MemoryAccess.
805  bool MoveAccess = true;
806  if (Repl) {
807  // Repl is already in HoistPt: it remains in place.
808  assert(allOperandsAvailable(Repl, HoistPt) &&
809  "instruction depends on operands that are not available");
810  MoveAccess = false;
811  } else {
812  // When we do not find Repl in HoistPt, select the first in the list
813  // and move it to HoistPt.
814  Repl = InstructionsToHoist.front();
815 
816  // We can move Repl in HoistPt only when all operands are available.
817  // The order in which hoistings are done may influence the availability
818  // of operands.
819  if (!allOperandsAvailable(Repl, HoistPt)) {
820 
821  // When HoistingGeps there is nothing more we can do to make the
822  // operands available: just continue.
823  if (HoistingGeps)
824  continue;
825 
826  // When not HoistingGeps we need to copy the GEPs.
827  if (!makeGepOperandsAvailable(Repl, HoistPt, InstructionsToHoist))
828  continue;
829  }
830 
831  // Move the instruction at the end of HoistPt.
832  Instruction *Last = HoistPt->getTerminator();
833  MD->removeInstruction(Repl);
834  Repl->moveBefore(Last);
835 
836  DFSNumber[Repl] = DFSNumber[Last]++;
837  }
838 
839  MemoryAccess *NewMemAcc = MSSA->getMemoryAccess(Repl);
840 
841  if (MoveAccess) {
842  if (MemoryUseOrDef *OldMemAcc =
843  dyn_cast_or_null<MemoryUseOrDef>(NewMemAcc)) {
844  // The definition of this ld/st will not change: ld/st hoisting is
845  // legal when the ld/st is not moved past its current definition.
846  MemoryAccess *Def = OldMemAcc->getDefiningAccess();
847  NewMemAcc =
848  MSSAUpdater->createMemoryAccessInBB(Repl, Def, HoistPt, MemorySSA::End);
849  OldMemAcc->replaceAllUsesWith(NewMemAcc);
850  MSSAUpdater->removeMemoryAccess(OldMemAcc);
851  }
852  }
853 
854  if (isa<LoadInst>(Repl))
855  ++NL;
856  else if (isa<StoreInst>(Repl))
857  ++NS;
858  else if (isa<CallInst>(Repl))
859  ++NC;
860  else // Scalar
861  ++NI;
862 
863  // Remove and rename all other instructions.
864  for (Instruction *I : InstructionsToHoist)
865  if (I != Repl) {
866  ++NR;
867  if (auto *ReplacementLoad = dyn_cast<LoadInst>(Repl)) {
868  ReplacementLoad->setAlignment(
869  std::min(ReplacementLoad->getAlignment(),
870  cast<LoadInst>(I)->getAlignment()));
871  ++NumLoadsRemoved;
872  } else if (auto *ReplacementStore = dyn_cast<StoreInst>(Repl)) {
873  ReplacementStore->setAlignment(
874  std::min(ReplacementStore->getAlignment(),
875  cast<StoreInst>(I)->getAlignment()));
876  ++NumStoresRemoved;
877  } else if (auto *ReplacementAlloca = dyn_cast<AllocaInst>(Repl)) {
878  ReplacementAlloca->setAlignment(
879  std::max(ReplacementAlloca->getAlignment(),
880  cast<AllocaInst>(I)->getAlignment()));
881  } else if (isa<CallInst>(Repl)) {
882  ++NumCallsRemoved;
883  }
884 
885  if (NewMemAcc) {
886  // Update the uses of the old MSSA access with NewMemAcc.
887  MemoryAccess *OldMA = MSSA->getMemoryAccess(I);
888  OldMA->replaceAllUsesWith(NewMemAcc);
889  MSSAUpdater->removeMemoryAccess(OldMA);
890  }
891 
892  Repl->andIRFlags(I);
893  combineKnownMetadata(Repl, I);
894  I->replaceAllUsesWith(Repl);
895  // Also invalidate the Alias Analysis cache.
896  MD->removeInstruction(I);
897  I->eraseFromParent();
898  }
899 
900  // Remove MemorySSA phi nodes with the same arguments.
901  if (NewMemAcc) {
903  for (User *U : NewMemAcc->users())
904  if (MemoryPhi *Phi = dyn_cast<MemoryPhi>(U))
905  UsePhis.insert(Phi);
906 
907  for (auto *Phi : UsePhis) {
908  auto In = Phi->incoming_values();
909  if (all_of(In, [&](Use &U) { return U == NewMemAcc; })) {
910  Phi->replaceAllUsesWith(NewMemAcc);
911  MSSAUpdater->removeMemoryAccess(Phi);
912  }
913  }
914  }
915  }
916 
917  NumHoisted += NL + NS + NC + NI;
918  NumRemoved += NR;
919  NumLoadsHoisted += NL;
920  NumStoresHoisted += NS;
921  NumCallsHoisted += NC;
922  return {NI, NL + NC + NS};
923  }
924 
925  // Hoist all expressions. Returns Number of scalars hoisted
926  // and number of non-scalars hoisted.
927  std::pair<unsigned, unsigned> hoistExpressions(Function &F) {
928  InsnInfo II;
929  LoadInfo LI;
930  StoreInfo SI;
931  CallInfo CI;
932  for (BasicBlock *BB : depth_first(&F.getEntryBlock())) {
933  int InstructionNb = 0;
934  for (Instruction &I1 : *BB) {
935  // If I1 cannot guarantee progress, subsequent instructions
936  // in BB cannot be hoisted anyways.
938  HoistBarrier.insert(BB);
939  break;
940  }
941  // Only hoist the first instructions in BB up to MaxDepthInBB. Hoisting
942  // deeper may increase the register pressure and compilation time.
943  if (MaxDepthInBB != -1 && InstructionNb++ >= MaxDepthInBB)
944  break;
945 
946  // Do not value number terminator instructions.
947  if (isa<TerminatorInst>(&I1))
948  break;
949 
950  if (auto *Load = dyn_cast<LoadInst>(&I1))
951  LI.insert(Load, VN);
952  else if (auto *Store = dyn_cast<StoreInst>(&I1))
953  SI.insert(Store, VN);
954  else if (auto *Call = dyn_cast<CallInst>(&I1)) {
955  if (auto *Intr = dyn_cast<IntrinsicInst>(Call)) {
956  if (isa<DbgInfoIntrinsic>(Intr) ||
957  Intr->getIntrinsicID() == Intrinsic::assume)
958  continue;
959  }
960  if (Call->mayHaveSideEffects())
961  break;
962 
963  if (Call->isConvergent())
964  break;
965 
966  CI.insert(Call, VN);
967  } else if (HoistingGeps || !isa<GetElementPtrInst>(&I1))
968  // Do not hoist scalars past calls that may write to memory because
969  // that could result in spills later. geps are handled separately.
970  // TODO: We can relax this for targets like AArch64 as they have more
971  // registers than X86.
972  II.insert(&I1, VN);
973  }
974  }
975 
976  HoistingPointList HPL;
977  computeInsertionPoints(II.getVNTable(), HPL, InsKind::Scalar);
978  computeInsertionPoints(LI.getVNTable(), HPL, InsKind::Load);
979  computeInsertionPoints(SI.getVNTable(), HPL, InsKind::Store);
980  computeInsertionPoints(CI.getScalarVNTable(), HPL, InsKind::Scalar);
981  computeInsertionPoints(CI.getLoadVNTable(), HPL, InsKind::Load);
982  computeInsertionPoints(CI.getStoreVNTable(), HPL, InsKind::Store);
983  return hoist(HPL);
984  }
985 };
986 
988 public:
989  static char ID;
990 
993  }
994 
995  bool runOnFunction(Function &F) override {
996  if (skipFunction(F))
997  return false;
998  auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
999  auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
1000  auto &MD = getAnalysis<MemoryDependenceWrapperPass>().getMemDep();
1001  auto &MSSA = getAnalysis<MemorySSAWrapperPass>().getMSSA();
1002 
1003  GVNHoist G(&DT, &AA, &MD, &MSSA);
1004  return G.run(F);
1005  }
1006 
1007  void getAnalysisUsage(AnalysisUsage &AU) const override {
1015  }
1016 };
1017 } // namespace
1018 
1021  AliasAnalysis &AA = AM.getResult<AAManager>(F);
1023  MemorySSA &MSSA = AM.getResult<MemorySSAAnalysis>(F).getMSSA();
1024  GVNHoist G(&DT, &AA, &MD, &MSSA);
1025  if (!G.run(F))
1026  return PreservedAnalyses::all();
1027 
1028  PreservedAnalyses PA;
1031  PA.preserve<GlobalsAA>();
1032  return PA;
1033 }
1034 
1035 char GVNHoistLegacyPass::ID = 0;
1037  "Early GVN Hoisting of Expressions", false, false)
1043  "Early GVN Hoisting of Expressions", false, false)
1044 
1045 FunctionPass *llvm::createGVNHoistPass() { return new GVNHoistLegacyPass(); }
Legacy wrapper pass to provide the GlobalsAAResult object.
const VNtoInsns & getVNTable() const
Definition: GVNHoist.cpp:133
void setDomTree(DominatorTree *D)
Definition: GVN.h:100
Value * getValueOperand()
Definition: Instructions.h:395
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
Definition: Instruction.cpp:69
void push_back(const T &Elt)
Definition: SmallVector.h:211
static cl::opt< int > MaxDepthInBB("gvn-hoist-max-depth", cl::Hidden, cl::init(100), cl::desc("Hoist instructions from the beginning of the BB up to the ""maximum specified depth (default = 100, unlimited = -1)"))
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
Provides a lazy, caching interface for making common memory aliasing information queries, backed by LLVM's alias analysis passes.
ValueT lookup(const_arg_type_t< KeyT > Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
Definition: DenseMap.h:166
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
SmallVectorImpl< Instruction * > SmallVecImplInsn
Definition: GVNHoist.cpp:203
GCNRegPressure max(const GCNRegPressure &P1, const GCNRegPressure &P2)
const VNtoInsns & getStoreVNTable() const
Definition: GVNHoist.cpp:198
gvn Early GVN Hoisting of false
Definition: GVNHoist.cpp:1042
STATISTIC(NumFunctions,"Total number of functions")
This is the interface for a simple mod/ref and alias analysis over globals.
void dropUnknownNonDebugMetadata(ArrayRef< unsigned > KnownIDs)
Drop all unknown metadata except for debug locations.
Definition: Metadata.cpp:1187
Maximum length of the test input libFuzzer tries to guess a good value based on the corpus and reports it always prefer smaller inputs during the corpus shuffle When libFuzzer itself reports a bug this exit code will be used If indicates the maximal total time in seconds to run the fuzzer minimizes the provided crash input Use with tries to cleanse the provided crash input to make it contain fewer original bytes Use with exact_artifact_path to specify the output Experimental Use value profile to guide fuzzing Number of jobs to run If min(jobs, NumberOfCpuCores()/2)\" is used.") FUZZER_FLAG_INT(reload
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
Run the pass over the function.
Definition: GVNHoist.cpp:1019
bool operator()(const Instruction *A, const Instruction *B) const
Definition: GVNHoist.cpp:98
Implements a dense probed hash-table based set.
Definition: DenseSet.h:221
unsigned getNumOperands() const
Definition: User.h:176
const VNtoInsns & getVNTable() const
Definition: GVNHoist.cpp:168
bool isSimple() const
Definition: Instructions.h:387
This class represents a function call, abstracting a target machine's calling convention.
Represents a read-write access to memory, whether it is a must-alias, or a may-alias.
Definition: MemorySSA.h:344
void setAliasAnalysis(AliasAnalysis *A)
Definition: GVN.h:97
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly...
Definition: STLExtras.h:818
bool isEHPad() const
Return true if this basic block is an exception handling block.
Definition: BasicBlock.h:383
unsigned getNumSuccessors() const
Return the number of successors that this terminator has.
Analysis pass which computes a DominatorTree.
Definition: Dominators.h:232
FunctionPass * createGVNHoistPass()
Definition: GVNHoist.cpp:1045
An instruction for reading from memory.
Definition: Instructions.h:164
bool isSimple() const
Definition: Instructions.h:262
const VNtoInsns & getScalarVNTable() const
Definition: GVNHoist.cpp:194
static void combineKnownMetadata(Instruction *ReplInst, Instruction *I)
Definition: GVNHoist.cpp:205
gvn Early GVN Hoisting of Expressions
Definition: GVNHoist.cpp:1042
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
Definition: SmallPtrSet.h:345
Represents read-only accesses to memory.
Definition: MemorySSA.h:289
bool onlyReadsMemory() const
Determine if the call does not access or only reads memory.
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition: PassSupport.h:51
static uint32_t getAlignment(const MCSectionCOFF &Sec)
Legacy analysis pass which computes MemorySSA.
Definition: MemorySSA.h:838
static Value * getPointerOperand(Instruction &Inst)
bool runOnFunction(Function &F) override
runOnFunction - Virtual method overriden by subclasses to do the per-function processing of the pass...
Definition: GVNHoist.cpp:995
void clear()
Remove all entries from the ValueTable.
Definition: GVN.cpp:558
DenseMap< const BasicBlock *, bool > BBSideEffectsSet
Definition: GVNHoist.cpp:201
Constant Hoisting
A Use represents the edge between a Value definition and its users.
Definition: Use.h:56
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: APFloat.h:42
Encapsulates MemorySSA, including all data associated with memory accesses.
Definition: MemorySSA.h:606
MemoryUseOrDef * getMemoryAccess(const Instruction *) const
Given a memory Mod/Ref'ing instruction, get the MemorySSA access associated with it.
Definition: MemorySSA.cpp:1713
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs...ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Definition: PassManager.h:687
bool hasAddressTaken() const
Returns true if there are any uses of this basic block other than direct branches, switches, etc.
Definition: BasicBlock.h:376
MemoryAccess * getDefiningAccess() const
Get the access that produces the memory state used by this Use.
Definition: MemorySSA.h:242
void insert(Instruction *I, GVN::ValueTable &VN)
Definition: GVNHoist.cpp:127
An analysis that produces MemoryDependenceResults for a function.
Instruction * clone() const
Create a copy of 'this' instruction that is identical in all ways except the following: ...
LLVM_NODISCARD bool empty() const
Definition: SmallVector.h:60
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
Definition: GVNHoist.cpp:1007
BasicBlock * getBlock() const
Definition: MemorySSA.h:152
bool run(Function &F)
Definition: GVNHoist.cpp:227
SmallVector< Instruction *, 4 > SmallVecInsn
Definition: GVNHoist.cpp:202
#define F(x, y, z)
Definition: MD5.cpp:55
void insert(LoadInst *Load, GVN::ValueTable &VN)
Definition: GVNHoist.cpp:142
The core GVN pass object.
Definition: GVN.h:46
void andIRFlags(const Value *V)
Logical 'and' of any supported wrapping, exact, and fast-math flags of V and this instruction...
const VNtoInsns & getLoadVNTable() const
Definition: GVNHoist.cpp:196
An instruction for storing to memory.
Definition: Instructions.h:306
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition: Value.cpp:428
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
Definition: Dominators.h:134
void replaceUsesOfWith(Value *From, Value *To)
Replace uses of one Value with another.
Definition: User.cpp:22
idf_iterator< T > idf_begin(const T &G)
iterator find(const_arg_type_t< KeyT > Val)
Definition: DenseMap.h:131
idf_iterator< T > idf_end(const T &G)
an instruction for type-safe pointer arithmetic to access elements of arrays and structs ...
Definition: Instructions.h:837
void insert(CallInst *Call, GVN::ValueTable &VN)
Definition: GVNHoist.cpp:179
succ_range successors()
Definition: InstrTypes.h:267
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:401
bool isGuaranteedToTransferExecutionToSuccessor(const Instruction *I)
Return true if this function can prove that the instruction I will always transfer execution to one o...
A set of analyses that are preserved following a run of a transformation pass.
Definition: PassManager.h:153
* if(!EatIfPresent(lltok::kw_thread_local)) return false
ParseOptionalThreadLocal := /*empty.
const VNtoInsns & getVNTable() const
Definition: GVNHoist.cpp:149
void insertBefore(Instruction *InsertPos)
Insert an unlinked instruction into a basic block immediately before the specified instruction...
Definition: Instruction.cpp:75
std::enable_if<!std::is_array< T >::value, std::unique_ptr< T > >::type make_unique(Args &&...args)
Constructs a new T() with the given args and returns a unique_ptr<T> which owns the object...
Definition: STLExtras.h:943
LLVM Basic Block Representation.
Definition: BasicBlock.h:59
This class holds the mapping between values and value numbers.
Definition: GVN.h:68
df_iterator< T > df_end(const T &G)
This file provides the interface for LLVM's Global Value Numbering pass which eliminates fully redund...
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator begin()
Definition: SmallVector.h:115
A manager for alias analyses.
#define A
Definition: LargeTest.cpp:12
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Definition: SmallPtrSet.h:372
Represent the analysis usage information of a pass.
bool locallyDominates(const MemoryAccess *A, const MemoryAccess *B) const
Given two memory accesses in the same basic block, determine whether MemoryAccess A dominates MemoryA...
Definition: MemorySSA.cpp:1740
Analysis pass providing a never-invalidated alias analysis result.
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE,"Assign register bank of generic virtual registers", false, false) RegBankSelect
bool doesNotAccessMemory() const
Determine if the call does not access memory.
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:298
Value * getOperand(unsigned i) const
Definition: User.h:154
op_range operands()
Definition: User.h:222
Value * getPointerOperand()
Definition: Instructions.h:270
iterator begin() const
Definition: SmallPtrSet.h:398
bool skipFunction(const Function &F) const
Optional passes call this function to check whether the pass should be skipped.
Definition: Pass.cpp:151
static cl::opt< int > MaxHoistedThreshold("gvn-max-hoisted", cl::Hidden, cl::init(-1), cl::desc("Max number of instructions to hoist ""(default unlimited = -1)"))
INITIALIZE_PASS_BEGIN(GVNHoistLegacyPass,"gvn-hoist","Early GVN Hoisting of Expressions", false, false) INITIALIZE_PASS_END(GVNHoistLegacyPass
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: PassManager.h:159
static cl::opt< int > MaxChainLength("gvn-hoist-max-chain-length", cl::Hidden, cl::init(10), cl::desc("Maximum length of dependent chains to hoist ""(default = 10, unlimited = -1)"))
A wrapper analysis pass for the legacy pass manager that exposes a MemoryDepnedenceResults instance...
An intrusive list with ownership and callbacks specified/controlled by ilist_traits, only with API safe for polymorphic types.
Definition: ilist.h:403
DenseMap< std::pair< unsigned, unsigned >, SmallVector< Instruction *, 4 > > VNtoInsns
Definition: GVNHoist.cpp:116
bool dominates(const Instruction *Def, const Use &U) const
Return true if Def dominates a use in User.
Definition: Dominators.cpp:234
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
Definition: SmallPtrSet.h:423
#define E
Definition: LargeTest.cpp:27
static bool defClobbersUseOrDef(MemoryDef *MD, const MemoryUseOrDef *MU, AliasAnalysis &AA)
Definition: MemorySSA.cpp:270
#define B
Definition: LargeTest.cpp:24
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:861
const DataFlowGraph & G
Definition: RDFGraph.cpp:206
GVNHoist(DominatorTree *DT, AliasAnalysis *AA, MemoryDependenceResults *MD, MemorySSA *MSSA)
Definition: GVNHoist.cpp:219
An analysis that produces MemorySSA for a function.
Definition: MemorySSA.h:803
static cl::opt< int > MaxNumberOfBBSInPath("gvn-hoist-max-bbs", cl::Hidden, cl::init(4), cl::desc("Max number of basic blocks on the path between ""hoisting locations (default = 4, unlimited = -1)"))
const BasicBlock & getEntryBlock() const
Definition: Function.h:564
#define NC
Definition: regutils.h:42
gvn hoist
When an instruction is found to only use loop invariant operands that is safe to hoist, this instruction is called to do the dirty work.
Definition: GVNHoist.cpp:1042
df_iterator< T > df_begin(const T &G)
Class that has the common methods + fields of memory uses/defs.
Definition: MemorySSA.h:232
typename SuperClass::iterator iterator
Definition: SmallVector.h:325
iterator_range< user_iterator > users()
Definition: Value.h:395
void insert(StoreInst *Store, GVN::ValueTable &VN)
Definition: GVNHoist.cpp:159
bool mayThrow() const
Return true if this instruction may throw an exception.
iterator end() const
Definition: SmallPtrSet.h:405
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator end()
Definition: SmallVector.h:119
void initializeGVNHoistLegacyPassPass(PassRegistry &)
#define I(x, y, z)
Definition: MD5.cpp:58
LLVM_ATTRIBUTE_ALWAYS_INLINE size_type size() const
Definition: SmallVector.h:135
iterator end()
Definition: DenseMap.h:73
void setMemDep(MemoryDependenceResults *M)
Definition: GVN.h:99
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Definition: Casting.h:323
void preserve()
Mark an analysis as preserved.
Definition: PassManager.h:174
uint32_t lookupOrAdd(Value *V)
lookup_or_add - Returns the value number for the specified value, assigning it a new number if it did...
Definition: GVN.cpp:467
iterator_range< df_iterator< T > > depth_first(const T &G)
Instruction * getMemoryInst() const
Get the instruction that this MemoryUse represents.
Definition: MemorySSA.h:239
SortByDFSIn(DenseMap< const Value *, unsigned > &D)
Definition: GVNHoist.cpp:95
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
LLVM Value Representation.
Definition: Value.h:73
void removeInstruction(Instruction *InstToRemove)
Removes an instruction from the dependence analysis, updating the dependence of instructions that pre...
void moveBefore(Instruction *MovePos)
Unlink this instruction from its current basic block and insert it into the basic block that MovePos ...
Definition: Instruction.cpp:88
This file exposes an interface to building/using memory SSA to walk memory instructions using a use/d...
A container for analyses that lazily runs them and caches their results.
Legacy analysis pass which computes a DominatorTree.
Definition: Dominators.h:261
void sort(Policy policy, RandomAccessIterator Start, RandomAccessIterator End, const Comparator &Comp=Comparator())
Definition: Parallel.h:201
int * Ptr
A wrapper pass to provide the legacy pass manager access to a suitably prepared AAResults object...
Represents phi nodes for memory accesses.
Definition: MemorySSA.h:423
const TerminatorInst * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
Definition: BasicBlock.cpp:120
NodeT * findNearestCommonDominator(NodeT *A, NodeT *B) const
findNearestCommonDominator - Find nearest common dominator basic block for basic block A and B...
const AccessList * getBlockAccesses(const BasicBlock *BB) const
Return the list of MemoryAccess's for a given basic block.
Definition: MemorySSA.h:650
Value * getPointerOperand()
Definition: Instructions.h:398
void combineMetadata(Instruction *K, const Instruction *J, ArrayRef< unsigned > KnownIDs)
Combine the metadata of two instructions so that K can replace J.
Definition: Local.cpp:1703
const BasicBlock * getParent() const
Definition: Instruction.h:66
#define D
Definition: LargeTest.cpp:26
bool isLiveOnEntryDef(const MemoryAccess *MA) const
Return true if MA represents the live on entry value.
Definition: MemorySSA.h:630
bool properlyDominates(const DomTreeNodeBase< NodeT > *A, const DomTreeNodeBase< NodeT > *B) const
properlyDominates - Returns true iff A dominates B and A != B.