1 //===---- NewGVN.cpp - Global Value Numbering Pass --------------*- C++ -*-===//
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 /// \file
10 /// This file implements the new LLVM's Global Value Numbering pass.
11 /// GVN partitions values computed by a function into congruence classes.
12 /// Values ending up in the same congruence class are guaranteed to be the same
13 /// for every execution of the program. In that respect, congruency is a
14 /// compile-time approximation of equivalence of values at runtime.
15 /// The algorithm implemented here uses a sparse formulation and it's based
16 /// on the ideas described in the paper:
17 /// "A Sparse Algorithm for Predicated Global Value Numbering" from
18 /// Karthik Gargi.
19 ///
20 /// A brief overview of the algorithm: The algorithm is essentially the same as
21 /// the standard RPO value numbering algorithm (a good reference is the paper
22 /// "SCC based value numbering" by L. Taylor Simpson) with one major difference:
23 /// The RPO algorithm proceeds, on every iteration, to process every reachable
24 /// block and every instruction in that block.  This is because the standard RPO
25 /// algorithm does not track what things have the same value number, it only
26 /// tracks what the value number of a given operation is (the mapping is
27 /// operation -> value number).  Thus, when a value number of an operation
28 /// changes, it must reprocess everything to ensure all uses of a value number
29 /// get updated properly.  In constrast, the sparse algorithm we use *also*
30 /// tracks what operations have a given value number (IE it also tracks the
31 /// reverse mapping from value number -> operations with that value number), so
32 /// that it only needs to reprocess the instructions that are affected when
33 /// something's value number changes.  The vast majority of complexity and code
34 /// in this file is devoted to tracking what value numbers could change for what
35 /// instructions when various things happen.  The rest of the algorithm is
36 /// devoted to performing symbolic evaluation, forward propagation, and
37 /// simplification of operations based on the value numbers deduced so far
38 ///
39 /// In order to make the GVN mostly-complete, we use a technique derived from
40 /// "Detection of Redundant Expressions: A Complete and Polynomial-time
41 /// Algorithm in SSA" by R.R. Pai.  The source of incompleteness in most SSA
42 /// based GVN algorithms is related to their inability to detect equivalence
43 /// between phi of ops (IE phi(a+b, c+d)) and op of phis (phi(a,c) + phi(b, d)).
44 /// We resolve this issue by generating the equivalent "phi of ops" form for
45 /// each op of phis we see, in a way that only takes polynomial time to resolve.
46 ///
47 /// We also do not perform elimination by using any published algorithm.  All
48 /// published algorithms are O(Instructions). Instead, we use a technique that
49 /// is O(number of operations with the same value number), enabling us to skip
50 /// trying to eliminate things that have unique value numbers.
51 //===----------------------------------------------------------------------===//
52 
53 #include "llvm/Transforms/Scalar/NewGVN.h"
54 #include "llvm/ADT/BitVector.h"
55 #include "llvm/ADT/DenseMap.h"
56 #include "llvm/ADT/DenseSet.h"
57 #include "llvm/ADT/DepthFirstIterator.h"
58 #include "llvm/ADT/Hashing.h"
59 #include "llvm/ADT/MapVector.h"
60 #include "llvm/ADT/PostOrderIterator.h"
61 #include "llvm/ADT/STLExtras.h"
62 #include "llvm/ADT/SmallPtrSet.h"
63 #include "llvm/ADT/SmallSet.h"
64 #include "llvm/ADT/Statistic.h"
65 #include "llvm/ADT/TinyPtrVector.h"
66 #include "llvm/Analysis/AliasAnalysis.h"
67 #include "llvm/Analysis/AssumptionCache.h"
68 #include "llvm/Analysis/CFG.h"
69 #include "llvm/Analysis/CFGPrinter.h"
70 #include "llvm/Analysis/ConstantFolding.h"
71 #include "llvm/Analysis/GlobalsModRef.h"
72 #include "llvm/Analysis/InstructionSimplify.h"
73 #include "llvm/Analysis/MemoryBuiltins.h"
74 #include "llvm/Analysis/MemoryLocation.h"
75 #include "llvm/Analysis/MemorySSA.h"
76 #include "llvm/Analysis/TargetLibraryInfo.h"
77 #include "llvm/IR/DataLayout.h"
78 #include "llvm/IR/Dominators.h"
79 #include "llvm/IR/GlobalVariable.h"
80 #include "llvm/IR/IRBuilder.h"
81 #include "llvm/IR/IntrinsicInst.h"
82 #include "llvm/IR/LLVMContext.h"
83 #include "llvm/IR/Metadata.h"
84 #include "llvm/IR/PatternMatch.h"
85 #include "llvm/IR/Type.h"
86 #include "llvm/Support/Allocator.h"
87 #include "llvm/Support/CommandLine.h"
88 #include "llvm/Support/Debug.h"
89 #include "llvm/Support/DebugCounter.h"
90 #include "llvm/Transforms/Scalar.h"
91 #include "llvm/Transforms/Scalar/GVNExpression.h"
92 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
93 #include "llvm/Transforms/Utils/Local.h"
94 #include "llvm/Transforms/Utils/PredicateInfo.h"
95 #include "llvm/Transforms/Utils/VNCoercion.h"
96 #include <numeric>
97 #include <unordered_map>
98 #include <utility>
99 #include <vector>
100 using namespace llvm;
101 using namespace PatternMatch;
102 using namespace llvm::GVNExpression;
103 using namespace llvm::VNCoercion;
104 #define DEBUG_TYPE "newgvn"
105 
106 STATISTIC(NumGVNInstrDeleted, "Number of instructions deleted");
107 STATISTIC(NumGVNBlocksDeleted, "Number of blocks deleted");
108 STATISTIC(NumGVNOpsSimplified, "Number of Expressions simplified");
109 STATISTIC(NumGVNPhisAllSame, "Number of PHIs whos arguments are all the same");
110 STATISTIC(NumGVNMaxIterations,
111           "Maximum Number of iterations it took to converge GVN");
112 STATISTIC(NumGVNLeaderChanges, "Number of leader changes");
113 STATISTIC(NumGVNSortedLeaderChanges, "Number of sorted leader changes");
114 STATISTIC(NumGVNAvoidedSortedLeaderChanges,
115           "Number of avoided sorted leader changes");
116 STATISTIC(NumGVNDeadStores, "Number of redundant/dead stores eliminated");
117 STATISTIC(NumGVNPHIOfOpsCreated, "Number of PHI of ops created");
118 STATISTIC(NumGVNPHIOfOpsEliminations,
119           "Number of things eliminated using PHI of ops");
120 DEBUG_COUNTER(VNCounter, "newgvn-vn",
121               "Controls which instructions are value numbered");
122 DEBUG_COUNTER(PHIOfOpsCounter, "newgvn-phi",
123               "Controls which instructions we create phi of ops for");
124 // Currently store defining access refinement is too slow due to basicaa being
125 // egregiously slow.  This flag lets us keep it working while we work on this
126 // issue.
127 static cl::opt<bool> EnableStoreRefinement("enable-store-refinement",
128                                            cl::init(false), cl::Hidden);
129 
130 /// Currently, the generation "phi of ops" can result in correctness issues.
131 static cl::opt<bool> EnablePhiOfOps("enable-phi-of-ops", cl::init(false),
132                                     cl::Hidden);
133 
134 //===----------------------------------------------------------------------===//
135 //                                GVN Pass
136 //===----------------------------------------------------------------------===//
137 
138 // Anchor methods.
139 namespace llvm {
140 namespace GVNExpression {
141 Expression::~Expression() = default;
142 BasicExpression::~BasicExpression() = default;
143 CallExpression::~CallExpression() = default;
144 LoadExpression::~LoadExpression() = default;
145 StoreExpression::~StoreExpression() = default;
146 AggregateValueExpression::~AggregateValueExpression() = default;
147 PHIExpression::~PHIExpression() = default;
148 }
149 }
150 
151 namespace {
152 // Tarjan's SCC finding algorithm with Nuutila's improvements
153 // SCCIterator is actually fairly complex for the simple thing we want.
154 // It also wants to hand us SCC's that are unrelated to the phi node we ask
155 // about, and have us process them there or risk redoing work.
156 // Graph traits over a filter iterator also doesn't work that well here.
157 // This SCC finder is specialized to walk use-def chains, and only follows
158 // instructions,
159 // not generic values (arguments, etc).
160 struct TarjanSCC {
161 
162   TarjanSCC() : Components(1) {}
163 
164   void Start(const Instruction *Start) {
165     if (Root.lookup(Start) == 0)
166       FindSCC(Start);
167   }
168 
169   const SmallPtrSetImpl<const Value *> &getComponentFor(const Value *V) const {
170     unsigned ComponentID = ValueToComponent.lookup(V);
171 
172     assert(ComponentID > 0 &&
173            "Asking for a component for a value we never processed");
174     return Components[ComponentID];
175   }
176 
177 private:
178   void FindSCC(const Instruction *I) {
179     Root[I] = ++DFSNum;
180     // Store the DFS Number we had before it possibly gets incremented.
181     unsigned int OurDFS = DFSNum;
182     for (auto &Op : I->operands()) {
183       if (auto *InstOp = dyn_cast<Instruction>(Op)) {
184         if (Root.lookup(Op) == 0)
185           FindSCC(InstOp);
186         if (!InComponent.count(Op))
187           Root[I] = std::min(Root.lookup(I), Root.lookup(Op));
188       }
189     }
190     // See if we really were the root of a component, by seeing if we still have
191     // our DFSNumber.  If we do, we are the root of the component, and we have
192     // completed a component. If we do not, we are not the root of a component,
193     // and belong on the component stack.
194     if (Root.lookup(I) == OurDFS) {
195       unsigned ComponentID = Components.size();
196       Components.resize(Components.size() + 1);
197       auto &Component = Components.back();
198       Component.insert(I);
199       DEBUG(dbgs() << "Component root is " << *I << "\n");
200       InComponent.insert(I);
201       ValueToComponent[I] = ComponentID;
202       // Pop a component off the stack and label it.
203       while (!Stack.empty() && Root.lookup(Stack.back()) >= OurDFS) {
204         auto *Member = Stack.back();
205         DEBUG(dbgs() << "Component member is " << *Member << "\n");
206         Component.insert(Member);
207         InComponent.insert(Member);
208         ValueToComponent[Member] = ComponentID;
209         Stack.pop_back();
210       }
211     } else {
212       // Part of a component, push to stack
213       Stack.push_back(I);
214     }
215   }
216   unsigned int DFSNum = 1;
217   SmallPtrSet<const Value *, 8> InComponent;
218   DenseMap<const Value *, unsigned int> Root;
219   SmallVector<const Value *, 8> Stack;
220   // Store the components as vector of ptr sets, because we need the topo order
221   // of SCC's, but not individual member order
222   SmallVector<SmallPtrSet<const Value *, 8>, 8> Components;
223   DenseMap<const Value *, unsigned> ValueToComponent;
224 };
225 // Congruence classes represent the set of expressions/instructions
226 // that are all the same *during some scope in the function*.
227 // That is, because of the way we perform equality propagation, and
228 // because of memory value numbering, it is not correct to assume
229 // you can willy-nilly replace any member with any other at any
230 // point in the function.
231 //
232 // For any Value in the Member set, it is valid to replace any dominated member
233 // with that Value.
234 //
235 // Every congruence class has a leader, and the leader is used to symbolize
236 // instructions in a canonical way (IE every operand of an instruction that is a
237 // member of the same congruence class will always be replaced with leader
238 // during symbolization).  To simplify symbolization, we keep the leader as a
239 // constant if class can be proved to be a constant value.  Otherwise, the
240 // leader is the member of the value set with the smallest DFS number.  Each
241 // congruence class also has a defining expression, though the expression may be
242 // null.  If it exists, it can be used for forward propagation and reassociation
243 // of values.
244 
245 // For memory, we also track a representative MemoryAccess, and a set of memory
246 // members for MemoryPhis (which have no real instructions). Note that for
247 // memory, it seems tempting to try to split the memory members into a
248 // MemoryCongruenceClass or something.  Unfortunately, this does not work
249 // easily.  The value numbering of a given memory expression depends on the
250 // leader of the memory congruence class, and the leader of memory congruence
251 // class depends on the value numbering of a given memory expression.  This
252 // leads to wasted propagation, and in some cases, missed optimization.  For
253 // example: If we had value numbered two stores together before, but now do not,
254 // we move them to a new value congruence class.  This in turn will move at one
255 // of the memorydefs to a new memory congruence class.  Which in turn, affects
256 // the value numbering of the stores we just value numbered (because the memory
257 // congruence class is part of the value number).  So while theoretically
258 // possible to split them up, it turns out to be *incredibly* complicated to get
259 // it to work right, because of the interdependency.  While structurally
260 // slightly messier, it is algorithmically much simpler and faster to do what we
261 // do here, and track them both at once in the same class.
262 // Note: The default iterators for this class iterate over values
263 class CongruenceClass {
264 public:
265   using MemberType = Value;
266   using MemberSet = SmallPtrSet<MemberType *, 4>;
267   using MemoryMemberType = MemoryPhi;
268   using MemoryMemberSet = SmallPtrSet<const MemoryMemberType *, 2>;
269 
270   explicit CongruenceClass(unsigned ID) : ID(ID) {}
271   CongruenceClass(unsigned ID, Value *Leader, const Expression *E)
272       : ID(ID), RepLeader(Leader), DefiningExpr(E) {}
273   unsigned getID() const { return ID; }
274   // True if this class has no members left.  This is mainly used for assertion
275   // purposes, and for skipping empty classes.
276   bool isDead() const {
277     // If it's both dead from a value perspective, and dead from a memory
278     // perspective, it's really dead.
279     return empty() && memory_empty();
280   }
281   // Leader functions
282   Value *getLeader() const { return RepLeader; }
283   void setLeader(Value *Leader) { RepLeader = Leader; }
284   const std::pair<Value *, unsigned int> &getNextLeader() const {
285     return NextLeader;
286   }
287   void resetNextLeader() { NextLeader = {nullptr, ~0}; }
288 
289   void addPossibleNextLeader(std::pair<Value *, unsigned int> LeaderPair) {
290     if (LeaderPair.second < NextLeader.second)
291       NextLeader = LeaderPair;
292   }
293 
294   Value *getStoredValue() const { return RepStoredValue; }
295   void setStoredValue(Value *Leader) { RepStoredValue = Leader; }
296   const MemoryAccess *getMemoryLeader() const { return RepMemoryAccess; }
297   void setMemoryLeader(const MemoryAccess *Leader) { RepMemoryAccess = Leader; }
298 
299   // Forward propagation info
300   const Expression *getDefiningExpr() const { return DefiningExpr; }
301 
302   // Value member set
303   bool empty() const { return Members.empty(); }
304   unsigned size() const { return Members.size(); }
305   MemberSet::const_iterator begin() const { return Members.begin(); }
306   MemberSet::const_iterator end() const { return Members.end(); }
307   void insert(MemberType *M) { Members.insert(M); }
308   void erase(MemberType *M) { Members.erase(M); }
309   void swap(MemberSet &Other) { Members.swap(Other); }
310 
311   // Memory member set
312   bool memory_empty() const { return MemoryMembers.empty(); }
313   unsigned memory_size() const { return MemoryMembers.size(); }
314   MemoryMemberSet::const_iterator memory_begin() const {
315     return MemoryMembers.begin();
316   }
317   MemoryMemberSet::const_iterator memory_end() const {
318     return MemoryMembers.end();
319   }
320   iterator_range<MemoryMemberSet::const_iterator> memory() const {
321     return make_range(memory_begin(), memory_end());
322   }
323   void memory_insert(const MemoryMemberType *M) { MemoryMembers.insert(M); }
324   void memory_erase(const MemoryMemberType *M) { MemoryMembers.erase(M); }
325 
326   // Store count
327   unsigned getStoreCount() const { return StoreCount; }
328   void incStoreCount() { ++StoreCount; }
329   void decStoreCount() {
330     assert(StoreCount != 0 && "Store count went negative");
331     --StoreCount;
332   }
333 
334   // True if this class has no memory members.
335   bool definesNoMemory() const { return StoreCount == 0 && memory_empty(); }
336 
337   // Return true if two congruence classes are equivalent to each other.  This
338   // means
339   // that every field but the ID number and the dead field are equivalent.
340   bool isEquivalentTo(const CongruenceClass *Other) const {
341     if (!Other)
342       return false;
343     if (this == Other)
344       return true;
345 
346     if (std::tie(StoreCount, RepLeader, RepStoredValue, RepMemoryAccess) !=
347         std::tie(Other->StoreCount, Other->RepLeader, Other->RepStoredValue,
348                  Other->RepMemoryAccess))
349       return false;
350     if (DefiningExpr != Other->DefiningExpr)
351       if (!DefiningExpr || !Other->DefiningExpr ||
352           *DefiningExpr != *Other->DefiningExpr)
353         return false;
354     // We need some ordered set
355     std::set<Value *> AMembers(Members.begin(), Members.end());
356     std::set<Value *> BMembers(Members.begin(), Members.end());
357     return AMembers == BMembers;
358   }
359 
360 private:
361   unsigned ID;
362   // Representative leader.
363   Value *RepLeader = nullptr;
364   // The most dominating leader after our current leader, because the member set
365   // is not sorted and is expensive to keep sorted all the time.
366   std::pair<Value *, unsigned int> NextLeader = {nullptr, ~0U};
367   // If this is represented by a store, the value of the store.
368   Value *RepStoredValue = nullptr;
369   // If this class contains MemoryDefs or MemoryPhis, this is the leading memory
370   // access.
371   const MemoryAccess *RepMemoryAccess = nullptr;
372   // Defining Expression.
373   const Expression *DefiningExpr = nullptr;
374   // Actual members of this class.
375   MemberSet Members;
376   // This is the set of MemoryPhis that exist in the class. MemoryDefs and
377   // MemoryUses have real instructions representing them, so we only need to
378   // track MemoryPhis here.
379   MemoryMemberSet MemoryMembers;
380   // Number of stores in this congruence class.
381   // This is used so we can detect store equivalence changes properly.
382   int StoreCount = 0;
383 };
384 } // namespace
385 
386 namespace llvm {
387 struct ExactEqualsExpression {
388   const Expression &E;
389   explicit ExactEqualsExpression(const Expression &E) : E(E) {}
390   hash_code getComputedHash() const { return E.getComputedHash(); }
391   bool operator==(const Expression &Other) const {
392     return E.exactlyEquals(Other);
393   }
394 };
395 
396 template <> struct DenseMapInfo<const Expression *> {
397   static const Expression *getEmptyKey() {
398     auto Val = static_cast<uintptr_t>(-1);
399     Val <<= PointerLikeTypeTraits<const Expression *>::NumLowBitsAvailable;
400     return reinterpret_cast<const Expression *>(Val);
401   }
402   static const Expression *getTombstoneKey() {
403     auto Val = static_cast<uintptr_t>(~1U);
404     Val <<= PointerLikeTypeTraits<const Expression *>::NumLowBitsAvailable;
405     return reinterpret_cast<const Expression *>(Val);
406   }
407   static unsigned getHashValue(const Expression *E) {
408     return E->getComputedHash();
409   }
410   static unsigned getHashValue(const ExactEqualsExpression &E) {
411     return E.getComputedHash();
412   }
413   static bool isEqual(const ExactEqualsExpression &LHS, const Expression *RHS) {
414     if (RHS == getTombstoneKey() || RHS == getEmptyKey())
415       return false;
416     return LHS == *RHS;
417   }
418 
419   static bool isEqual(const Expression *LHS, const Expression *RHS) {
420     if (LHS == RHS)
421       return true;
422     if (LHS == getTombstoneKey() || RHS == getTombstoneKey() ||
423         LHS == getEmptyKey() || RHS == getEmptyKey())
424       return false;
425     // Compare hashes before equality.  This is *not* what the hashtable does,
426     // since it is computing it modulo the number of buckets, whereas we are
427     // using the full hash keyspace.  Since the hashes are precomputed, this
428     // check is *much* faster than equality.
429     if (LHS->getComputedHash() != RHS->getComputedHash())
430       return false;
431     return *LHS == *RHS;
432   }
433 };
434 } // end namespace llvm
435 
436 namespace {
437 class NewGVN {
438   Function &F;
439   DominatorTree *DT;
440   const TargetLibraryInfo *TLI;
441   AliasAnalysis *AA;
442   MemorySSA *MSSA;
443   MemorySSAWalker *MSSAWalker;
444   const DataLayout &DL;
445   std::unique_ptr<PredicateInfo> PredInfo;
446 
447   // These are the only two things the create* functions should have
448   // side-effects on due to allocating memory.
449   mutable BumpPtrAllocator ExpressionAllocator;
450   mutable ArrayRecycler<Value *> ArgRecycler;
451   mutable TarjanSCC SCCFinder;
452   const SimplifyQuery SQ;
453 
454   // Number of function arguments, used by ranking
455   unsigned int NumFuncArgs;
456 
457   // RPOOrdering of basic blocks
458   DenseMap<const DomTreeNode *, unsigned> RPOOrdering;
459 
460   // Congruence class info.
461 
462   // This class is called INITIAL in the paper. It is the class everything
463   // startsout in, and represents any value. Being an optimistic analysis,
464   // anything in the TOP class has the value TOP, which is indeterminate and
465   // equivalent to everything.
466   CongruenceClass *TOPClass;
467   std::vector<CongruenceClass *> CongruenceClasses;
468   unsigned NextCongruenceNum;
469 
470   // Value Mappings.
471   DenseMap<Value *, CongruenceClass *> ValueToClass;
472   DenseMap<Value *, const Expression *> ValueToExpression;
473   // Value PHI handling, used to make equivalence between phi(op, op) and
474   // op(phi, phi).
475   // These mappings just store various data that would normally be part of the
476   // IR.
477   DenseSet<const Instruction *> PHINodeUses;
478   // Map a temporary instruction we created to a parent block.
479   DenseMap<const Value *, BasicBlock *> TempToBlock;
480   // Map between the already in-program instructions and the temporary phis we
481   // created that they are known equivalent to.
482   DenseMap<const Value *, PHINode *> RealToTemp;
483   // In order to know when we should re-process instructions that have
484   // phi-of-ops, we track the set of expressions that they needed as
485   // leaders. When we discover new leaders for those expressions, we process the
486   // associated phi-of-op instructions again in case they have changed.  The
487   // other way they may change is if they had leaders, and those leaders
488   // disappear.  However, at the point they have leaders, there are uses of the
489   // relevant operands in the created phi node, and so they will get reprocessed
490   // through the normal user marking we perform.
491   mutable DenseMap<const Value *, SmallPtrSet<Value *, 2>> AdditionalUsers;
492   DenseMap<const Expression *, SmallPtrSet<Instruction *, 2>>
493       ExpressionToPhiOfOps;
494   // Map from basic block to the temporary operations we created
495   DenseMap<const BasicBlock *, SmallPtrSet<PHINode *, 2>> PHIOfOpsPHIs;
496   // Map from temporary operation to MemoryAccess.
497   DenseMap<const Instruction *, MemoryUseOrDef *> TempToMemory;
498   // Set of all temporary instructions we created.
499   // Note: This will include instructions that were just created during value
500   // numbering.  The way to test if something is using them is to check
501   // RealToTemp.
502 
503   DenseSet<Instruction *> AllTempInstructions;
504 
505   // Mapping from predicate info we used to the instructions we used it with.
506   // In order to correctly ensure propagation, we must keep track of what
507   // comparisons we used, so that when the values of the comparisons change, we
508   // propagate the information to the places we used the comparison.
509   mutable DenseMap<const Value *, SmallPtrSet<Instruction *, 2>>
510       PredicateToUsers;
511   // the same reasoning as PredicateToUsers.  When we skip MemoryAccesses for
512   // stores, we no longer can rely solely on the def-use chains of MemorySSA.
513   mutable DenseMap<const MemoryAccess *, SmallPtrSet<MemoryAccess *, 2>>
514       MemoryToUsers;
515 
516   // A table storing which memorydefs/phis represent a memory state provably
517   // equivalent to another memory state.
518   // We could use the congruence class machinery, but the MemoryAccess's are
519   // abstract memory states, so they can only ever be equivalent to each other,
520   // and not to constants, etc.
521   DenseMap<const MemoryAccess *, CongruenceClass *> MemoryAccessToClass;
522 
523   // We could, if we wanted, build MemoryPhiExpressions and
524   // MemoryVariableExpressions, etc, and value number them the same way we value
525   // number phi expressions.  For the moment, this seems like overkill.  They
526   // can only exist in one of three states: they can be TOP (equal to
527   // everything), Equivalent to something else, or unique.  Because we do not
528   // create expressions for them, we need to simulate leader change not just
529   // when they change class, but when they change state.  Note: We can do the
530   // same thing for phis, and avoid having phi expressions if we wanted, We
531   // should eventually unify in one direction or the other, so this is a little
532   // bit of an experiment in which turns out easier to maintain.
533   enum MemoryPhiState { MPS_Invalid, MPS_TOP, MPS_Equivalent, MPS_Unique };
534   DenseMap<const MemoryPhi *, MemoryPhiState> MemoryPhiState;
535 
536   enum InstCycleState { ICS_Unknown, ICS_CycleFree, ICS_Cycle };
537   mutable DenseMap<const Instruction *, InstCycleState> InstCycleState;
538   // Expression to class mapping.
539   using ExpressionClassMap = DenseMap<const Expression *, CongruenceClass *>;
540   ExpressionClassMap ExpressionToClass;
541 
542   // We have a single expression that represents currently DeadExpressions.
543   // For dead expressions we can prove will stay dead, we mark them with
544   // DFS number zero.  However, it's possible in the case of phi nodes
545   // for us to assume/prove all arguments are dead during fixpointing.
546   // We use DeadExpression for that case.
547   DeadExpression *SingletonDeadExpression = nullptr;
548 
549   // Which values have changed as a result of leader changes.
550   SmallPtrSet<Value *, 8> LeaderChanges;
551 
552   // Reachability info.
553   using BlockEdge = BasicBlockEdge;
554   DenseSet<BlockEdge> ReachableEdges;
555   SmallPtrSet<const BasicBlock *, 8> ReachableBlocks;
556 
557   // This is a bitvector because, on larger functions, we may have
558   // thousands of touched instructions at once (entire blocks,
559   // instructions with hundreds of uses, etc).  Even with optimization
560   // for when we mark whole blocks as touched, when this was a
561   // SmallPtrSet or DenseSet, for some functions, we spent >20% of all
562   // the time in GVN just managing this list.  The bitvector, on the
563   // other hand, efficiently supports test/set/clear of both
564   // individual and ranges, as well as "find next element" This
565   // enables us to use it as a worklist with essentially 0 cost.
566   BitVector TouchedInstructions;
567 
568   DenseMap<const BasicBlock *, std::pair<unsigned, unsigned>> BlockInstRange;
569 
570 #ifndef NDEBUG
571   // Debugging for how many times each block and instruction got processed.
572   DenseMap<const Value *, unsigned> ProcessedCount;
573 #endif
574 
575   // DFS info.
576   // This contains a mapping from Instructions to DFS numbers.
577   // The numbering starts at 1. An instruction with DFS number zero
578   // means that the instruction is dead.
579   DenseMap<const Value *, unsigned> InstrDFS;
580 
581   // This contains the mapping DFS numbers to instructions.
582   SmallVector<Value *, 32> DFSToInstr;
583 
584   // Deletion info.
585   SmallPtrSet<Instruction *, 8> InstructionsToErase;
586 
587 public:
588   NewGVN(Function &F, DominatorTree *DT, AssumptionCache *AC,
589          TargetLibraryInfo *TLI, AliasAnalysis *AA, MemorySSA *MSSA,
590          const DataLayout &DL)
591       : F(F), DT(DT), TLI(TLI), AA(AA), MSSA(MSSA), DL(DL),
592         PredInfo(make_unique<PredicateInfo>(F, *DT, *AC)), SQ(DL, TLI, DT, AC) {
593   }
594   bool runGVN();
595 
596 private:
597   // Expression handling.
598   const Expression *createExpression(Instruction *) const;
599   const Expression *createBinaryExpression(unsigned, Type *, Value *,
600                                            Value *) const;
601   PHIExpression *createPHIExpression(Instruction *, bool &HasBackEdge,
602                                      bool &OriginalOpsConstant) const;
603   const DeadExpression *createDeadExpression() const;
604   const VariableExpression *createVariableExpression(Value *) const;
605   const ConstantExpression *createConstantExpression(Constant *) const;
606   const Expression *createVariableOrConstant(Value *V) const;
607   const UnknownExpression *createUnknownExpression(Instruction *) const;
608   const StoreExpression *createStoreExpression(StoreInst *,
609                                                const MemoryAccess *) const;
610   LoadExpression *createLoadExpression(Type *, Value *, LoadInst *,
611                                        const MemoryAccess *) const;
612   const CallExpression *createCallExpression(CallInst *,
613                                              const MemoryAccess *) const;
614   const AggregateValueExpression *
615   createAggregateValueExpression(Instruction *) const;
616   bool setBasicExpressionInfo(Instruction *, BasicExpression *) const;
617 
618   // Congruence class handling.
619   CongruenceClass *createCongruenceClass(Value *Leader, const Expression *E) {
620     auto *result = new CongruenceClass(NextCongruenceNum++, Leader, E);
621     CongruenceClasses.emplace_back(result);
622     return result;
623   }
624 
625   CongruenceClass *createMemoryClass(MemoryAccess *MA) {
626     auto *CC = createCongruenceClass(nullptr, nullptr);
627     CC->setMemoryLeader(MA);
628     return CC;
629   }
630   CongruenceClass *ensureLeaderOfMemoryClass(MemoryAccess *MA) {
631     auto *CC = getMemoryClass(MA);
632     if (CC->getMemoryLeader() != MA)
633       CC = createMemoryClass(MA);
634     return CC;
635   }
636 
637   CongruenceClass *createSingletonCongruenceClass(Value *Member) {
638     CongruenceClass *CClass = createCongruenceClass(Member, nullptr);
639     CClass->insert(Member);
640     ValueToClass[Member] = CClass;
641     return CClass;
642   }
643   void initializeCongruenceClasses(Function &F);
644   const Expression *makePossiblePhiOfOps(Instruction *,
645                                          SmallPtrSetImpl<Value *> &);
646   void addPhiOfOps(PHINode *Op, BasicBlock *BB, Instruction *ExistingValue);
647   void removePhiOfOps(Instruction *I, PHINode *PHITemp);
648 
649   // Value number an Instruction or MemoryPhi.
650   void valueNumberMemoryPhi(MemoryPhi *);
651   void valueNumberInstruction(Instruction *);
652 
653   // Symbolic evaluation.
654   const Expression *checkSimplificationResults(Expression *, Instruction *,
655                                                Value *) const;
656   const Expression *performSymbolicEvaluation(Value *,
657                                               SmallPtrSetImpl<Value *> &) const;
658   const Expression *performSymbolicLoadCoercion(Type *, Value *, LoadInst *,
659                                                 Instruction *,
660                                                 MemoryAccess *) const;
661   const Expression *performSymbolicLoadEvaluation(Instruction *) const;
662   const Expression *performSymbolicStoreEvaluation(Instruction *) const;
663   const Expression *performSymbolicCallEvaluation(Instruction *) const;
664   const Expression *performSymbolicPHIEvaluation(Instruction *) const;
665   const Expression *performSymbolicAggrValueEvaluation(Instruction *) const;
666   const Expression *performSymbolicCmpEvaluation(Instruction *) const;
667   const Expression *performSymbolicPredicateInfoEvaluation(Instruction *) const;
668 
669   // Congruence finding.
670   bool someEquivalentDominates(const Instruction *, const Instruction *) const;
671   Value *lookupOperandLeader(Value *) const;
672   void performCongruenceFinding(Instruction *, const Expression *);
673   void moveValueToNewCongruenceClass(Instruction *, const Expression *,
674                                      CongruenceClass *, CongruenceClass *);
675   void moveMemoryToNewCongruenceClass(Instruction *, MemoryAccess *,
676                                       CongruenceClass *, CongruenceClass *);
677   Value *getNextValueLeader(CongruenceClass *) const;
678   const MemoryAccess *getNextMemoryLeader(CongruenceClass *) const;
679   bool setMemoryClass(const MemoryAccess *From, CongruenceClass *To);
680   CongruenceClass *getMemoryClass(const MemoryAccess *MA) const;
681   const MemoryAccess *lookupMemoryLeader(const MemoryAccess *) const;
682   bool isMemoryAccessTOP(const MemoryAccess *) const;
683 
684   // Ranking
685   unsigned int getRank(const Value *) const;
686   bool shouldSwapOperands(const Value *, const Value *) const;
687 
688   // Reachability handling.
689   void updateReachableEdge(BasicBlock *, BasicBlock *);
690   void processOutgoingEdges(TerminatorInst *, BasicBlock *);
691   Value *findConditionEquivalence(Value *) const;
692 
693   // Elimination.
694   struct ValueDFS;
695   void convertClassToDFSOrdered(const CongruenceClass &,
696                                 SmallVectorImpl<ValueDFS> &,
697                                 DenseMap<const Value *, unsigned int> &,
698                                 SmallPtrSetImpl<Instruction *> &) const;
699   void convertClassToLoadsAndStores(const CongruenceClass &,
700                                     SmallVectorImpl<ValueDFS> &) const;
701 
702   bool eliminateInstructions(Function &);
703   void replaceInstruction(Instruction *, Value *);
704   void markInstructionForDeletion(Instruction *);
705   void deleteInstructionsInBlock(BasicBlock *);
706   Value *findPhiOfOpsLeader(const Expression *E, const BasicBlock *BB) const;
707 
708   // New instruction creation.
709   void handleNewInstruction(Instruction *){};
710 
711   // Various instruction touch utilities
712   template <typename Map, typename KeyType, typename Func>
713   void for_each_found(Map &, const KeyType &, Func);
714   template <typename Map, typename KeyType>
715   void touchAndErase(Map &, const KeyType &);
716   void markUsersTouched(Value *);
717   void markMemoryUsersTouched(const MemoryAccess *);
718   void markMemoryDefTouched(const MemoryAccess *);
719   void markPredicateUsersTouched(Instruction *);
720   void markValueLeaderChangeTouched(CongruenceClass *CC);
721   void markMemoryLeaderChangeTouched(CongruenceClass *CC);
722   void markPhiOfOpsChanged(const Expression *E);
723   void addPredicateUsers(const PredicateBase *, Instruction *) const;
724   void addMemoryUsers(const MemoryAccess *To, MemoryAccess *U) const;
725   void addAdditionalUsers(Value *To, Value *User) const;
726 
727   // Main loop of value numbering
728   void iterateTouchedInstructions();
729 
730   // Utilities.
731   void cleanupTables();
732   std::pair<unsigned, unsigned> assignDFSNumbers(BasicBlock *, unsigned);
733   void updateProcessedCount(const Value *V);
734   void verifyMemoryCongruency() const;
735   void verifyIterationSettled(Function &F);
736   void verifyStoreExpressions() const;
737   bool singleReachablePHIPath(SmallPtrSet<const MemoryAccess *, 8> &,
738                               const MemoryAccess *, const MemoryAccess *) const;
739   BasicBlock *getBlockForValue(Value *V) const;
740   void deleteExpression(const Expression *E) const;
741   MemoryUseOrDef *getMemoryAccess(const Instruction *) const;
742   MemoryAccess *getDefiningAccess(const MemoryAccess *) const;
743   MemoryPhi *getMemoryAccess(const BasicBlock *) const;
744   template <class T, class Range> T *getMinDFSOfRange(const Range &) const;
745   unsigned InstrToDFSNum(const Value *V) const {
746     assert(isa<Instruction>(V) && "This should not be used for MemoryAccesses");
747     return InstrDFS.lookup(V);
748   }
749 
750   unsigned InstrToDFSNum(const MemoryAccess *MA) const {
751     return MemoryToDFSNum(MA);
752   }
753   Value *InstrFromDFSNum(unsigned DFSNum) { return DFSToInstr[DFSNum]; }
754   // Given a MemoryAccess, return the relevant instruction DFS number.  Note:
755   // This deliberately takes a value so it can be used with Use's, which will
756   // auto-convert to Value's but not to MemoryAccess's.
757   unsigned MemoryToDFSNum(const Value *MA) const {
758     assert(isa<MemoryAccess>(MA) &&
759            "This should not be used with instructions");
760     return isa<MemoryUseOrDef>(MA)
761                ? InstrToDFSNum(cast<MemoryUseOrDef>(MA)->getMemoryInst())
762                : InstrDFS.lookup(MA);
763   }
764   bool isCycleFree(const Instruction *) const;
765   bool isBackedge(BasicBlock *From, BasicBlock *To) const;
766   // Debug counter info.  When verifying, we have to reset the value numbering
767   // debug counter to the same state it started in to get the same results.
768   std::pair<int, int> StartingVNCounter;
769 };
770 } // end anonymous namespace
771 
772 template <typename T>
773 static bool equalsLoadStoreHelper(const T &LHS, const Expression &RHS) {
774   if (!isa<LoadExpression>(RHS) && !isa<StoreExpression>(RHS))
775     return false;
776   return LHS.MemoryExpression::equals(RHS);
777 }
778 
779 bool LoadExpression::equals(const Expression &Other) const {
780   return equalsLoadStoreHelper(*this, Other);
781 }
782 
783 bool StoreExpression::equals(const Expression &Other) const {
784   if (!equalsLoadStoreHelper(*this, Other))
785     return false;
786   // Make sure that store vs store includes the value operand.
787   if (const auto *S = dyn_cast<StoreExpression>(&Other))
788     if (getStoredValue() != S->getStoredValue())
789       return false;
790   return true;
791 }
792 
793 // Determine if the edge From->To is a backedge
794 bool NewGVN::isBackedge(BasicBlock *From, BasicBlock *To) const {
795   return From == To ||
796          RPOOrdering.lookup(DT->getNode(From)) >=
797              RPOOrdering.lookup(DT->getNode(To));
798 }
799 
800 #ifndef NDEBUG
801 static std::string getBlockName(const BasicBlock *B) {
802   return DOTGraphTraits<const Function *>::getSimpleNodeLabel(B, nullptr);
803 }
804 #endif
805 
806 // Get a MemoryAccess for an instruction, fake or real.
807 MemoryUseOrDef *NewGVN::getMemoryAccess(const Instruction *I) const {
808   auto *Result = MSSA->getMemoryAccess(I);
809   return Result ? Result : TempToMemory.lookup(I);
810 }
811 
812 // Get a MemoryPhi for a basic block. These are all real.
813 MemoryPhi *NewGVN::getMemoryAccess(const BasicBlock *BB) const {
814   return MSSA->getMemoryAccess(BB);
815 }
816 
817 // Get the basic block from an instruction/memory value.
818 BasicBlock *NewGVN::getBlockForValue(Value *V) const {
819   if (auto *I = dyn_cast<Instruction>(V)) {
820     auto *Parent = I->getParent();
821     if (Parent)
822       return Parent;
823     Parent = TempToBlock.lookup(V);
824     assert(Parent && "Every fake instruction should have a block");
825     return Parent;
826   }
827 
828   auto *MP = dyn_cast<MemoryPhi>(V);
829   assert(MP && "Should have been an instruction or a MemoryPhi");
830   return MP->getBlock();
831 }
832 
833 // Delete a definitely dead expression, so it can be reused by the expression
834 // allocator.  Some of these are not in creation functions, so we have to accept
835 // const versions.
836 void NewGVN::deleteExpression(const Expression *E) const {
837   assert(isa<BasicExpression>(E));
838   auto *BE = cast<BasicExpression>(E);
839   const_cast<BasicExpression *>(BE)->deallocateOperands(ArgRecycler);
840   ExpressionAllocator.Deallocate(E);
841 }
842 PHIExpression *NewGVN::createPHIExpression(Instruction *I, bool &HasBackedge,
843                                            bool &OriginalOpsConstant) const {
844   BasicBlock *PHIBlock = getBlockForValue(I);
845   auto *PN = cast<PHINode>(I);
846   auto *E =
847       new (ExpressionAllocator) PHIExpression(PN->getNumOperands(), PHIBlock);
848 
849   E->allocateOperands(ArgRecycler, ExpressionAllocator);
850   E->setType(I->getType());
851   E->setOpcode(I->getOpcode());
852 
853   // NewGVN assumes the operands of a PHI node are in a consistent order across
854   // PHIs. LLVM doesn't seem to always guarantee this. While we need to fix
855   // this in LLVM at some point we don't want GVN to find wrong congruences.
856   // Therefore, here we sort uses in predecessor order.
857   // We're sorting the values by pointer. In theory this might be cause of
858   // non-determinism, but here we don't rely on the ordering for anything
859   // significant, e.g. we don't create new instructions based on it so we're
860   // fine.
861   SmallVector<const Use *, 4> PHIOperands;
862   for (const Use &U : PN->operands())
863     PHIOperands.push_back(&U);
864   std::sort(PHIOperands.begin(), PHIOperands.end(),
865             [&](const Use *U1, const Use *U2) {
866               return PN->getIncomingBlock(*U1) < PN->getIncomingBlock(*U2);
867             });
868 
869   // Filter out unreachable phi operands.
870   auto Filtered = make_filter_range(PHIOperands, [&](const Use *U) {
871     if (*U == PN)
872       return false;
873     if (!ReachableEdges.count({PN->getIncomingBlock(*U), PHIBlock}))
874       return false;
875     // Things in TOPClass are equivalent to everything.
876     if (ValueToClass.lookup(*U) == TOPClass)
877       return false;
878     return lookupOperandLeader(*U) != PN;
879   });
880   std::transform(Filtered.begin(), Filtered.end(), op_inserter(E),
881                  [&](const Use *U) -> Value * {
882                    auto *BB = PN->getIncomingBlock(*U);
883                    HasBackedge = HasBackedge || isBackedge(BB, PHIBlock);
884                    OriginalOpsConstant =
885                        OriginalOpsConstant && isa<Constant>(*U);
886                    return lookupOperandLeader(*U);
887                  });
888   return E;
889 }
890 
891 // Set basic expression info (Arguments, type, opcode) for Expression
892 // E from Instruction I in block B.
893 bool NewGVN::setBasicExpressionInfo(Instruction *I, BasicExpression *E) const {
894   bool AllConstant = true;
895   if (auto *GEP = dyn_cast<GetElementPtrInst>(I))
896     E->setType(GEP->getSourceElementType());
897   else
898     E->setType(I->getType());
899   E->setOpcode(I->getOpcode());
900   E->allocateOperands(ArgRecycler, ExpressionAllocator);
901 
902   // Transform the operand array into an operand leader array, and keep track of
903   // whether all members are constant.
904   std::transform(I->op_begin(), I->op_end(), op_inserter(E), [&](Value *O) {
905     auto Operand = lookupOperandLeader(O);
906     AllConstant = AllConstant && isa<Constant>(Operand);
907     return Operand;
908   });
909 
910   return AllConstant;
911 }
912 
913 const Expression *NewGVN::createBinaryExpression(unsigned Opcode, Type *T,
914                                                  Value *Arg1,
915                                                  Value *Arg2) const {
916   auto *E = new (ExpressionAllocator) BasicExpression(2);
917 
918   E->setType(T);
919   E->setOpcode(Opcode);
920   E->allocateOperands(ArgRecycler, ExpressionAllocator);
921   if (Instruction::isCommutative(Opcode)) {
922     // Ensure that commutative instructions that only differ by a permutation
923     // of their operands get the same value number by sorting the operand value
924     // numbers.  Since all commutative instructions have two operands it is more
925     // efficient to sort by hand rather than using, say, std::sort.
926     if (shouldSwapOperands(Arg1, Arg2))
927       std::swap(Arg1, Arg2);
928   }
929   E->op_push_back(lookupOperandLeader(Arg1));
930   E->op_push_back(lookupOperandLeader(Arg2));
931 
932   Value *V = SimplifyBinOp(Opcode, E->getOperand(0), E->getOperand(1), SQ);
933   if (const Expression *SimplifiedE = checkSimplificationResults(E, nullptr, V))
934     return SimplifiedE;
935   return E;
936 }
937 
938 // Take a Value returned by simplification of Expression E/Instruction
939 // I, and see if it resulted in a simpler expression. If so, return
940 // that expression.
941 const Expression *NewGVN::checkSimplificationResults(Expression *E,
942                                                      Instruction *I,
943                                                      Value *V) const {
944   if (!V)
945     return nullptr;
946   if (auto *C = dyn_cast<Constant>(V)) {
947     if (I)
948       DEBUG(dbgs() << "Simplified " << *I << " to "
949                    << " constant " << *C << "\n");
950     NumGVNOpsSimplified++;
951     assert(isa<BasicExpression>(E) &&
952            "We should always have had a basic expression here");
953     deleteExpression(E);
954     return createConstantExpression(C);
955   } else if (isa<Argument>(V) || isa<GlobalVariable>(V)) {
956     if (I)
957       DEBUG(dbgs() << "Simplified " << *I << " to "
958                    << " variable " << *V << "\n");
959     deleteExpression(E);
960     return createVariableExpression(V);
961   }
962 
963   CongruenceClass *CC = ValueToClass.lookup(V);
964   if (CC) {
965     if (CC->getLeader() && CC->getLeader() != I) {
966       addAdditionalUsers(V, I);
967       return createVariableOrConstant(CC->getLeader());
968     }
969 
970     if (CC->getDefiningExpr()) {
971       // If we simplified to something else, we need to communicate
972       // that we're users of the value we simplified to.
973       if (I != V) {
974         // Don't add temporary instructions to the user lists.
975         if (!AllTempInstructions.count(I))
976           addAdditionalUsers(V, I);
977       }
978 
979       if (I)
980         DEBUG(dbgs() << "Simplified " << *I << " to "
981                      << " expression " << *CC->getDefiningExpr() << "\n");
982       NumGVNOpsSimplified++;
983       deleteExpression(E);
984       return CC->getDefiningExpr();
985     }
986   }
987 
988   return nullptr;
989 }
990 
991 const Expression *NewGVN::createExpression(Instruction *I) const {
992   auto *E = new (ExpressionAllocator) BasicExpression(I->getNumOperands());
993 
994   bool AllConstant = setBasicExpressionInfo(I, E);
995 
996   if (I->isCommutative()) {
997     // Ensure that commutative instructions that only differ by a permutation
998     // of their operands get the same value number by sorting the operand value
999     // numbers.  Since all commutative instructions have two operands it is more
1000     // efficient to sort by hand rather than using, say, std::sort.
1001     assert(I->getNumOperands() == 2 && "Unsupported commutative instruction!");
1002     if (shouldSwapOperands(E->getOperand(0), E->getOperand(1)))
1003       E->swapOperands(0, 1);
1004   }
1005 
1006   // Perform simplification.
1007   if (auto *CI = dyn_cast<CmpInst>(I)) {
1008     // Sort the operand value numbers so x<y and y>x get the same value
1009     // number.
1010     CmpInst::Predicate Predicate = CI->getPredicate();
1011     if (shouldSwapOperands(E->getOperand(0), E->getOperand(1))) {
1012       E->swapOperands(0, 1);
1013       Predicate = CmpInst::getSwappedPredicate(Predicate);
1014     }
1015     E->setOpcode((CI->getOpcode() << 8) | Predicate);
1016     // TODO: 25% of our time is spent in SimplifyCmpInst with pointer operands
1017     assert(I->getOperand(0)->getType() == I->getOperand(1)->getType() &&
1018            "Wrong types on cmp instruction");
1019     assert((E->getOperand(0)->getType() == I->getOperand(0)->getType() &&
1020             E->getOperand(1)->getType() == I->getOperand(1)->getType()));
1021     Value *V =
1022         SimplifyCmpInst(Predicate, E->getOperand(0), E->getOperand(1), SQ);
1023     if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
1024       return SimplifiedE;
1025   } else if (isa<SelectInst>(I)) {
1026     if (isa<Constant>(E->getOperand(0)) ||
1027         E->getOperand(1) == E->getOperand(2)) {
1028       assert(E->getOperand(1)->getType() == I->getOperand(1)->getType() &&
1029              E->getOperand(2)->getType() == I->getOperand(2)->getType());
1030       Value *V = SimplifySelectInst(E->getOperand(0), E->getOperand(1),
1031                                     E->getOperand(2), SQ);
1032       if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
1033         return SimplifiedE;
1034     }
1035   } else if (I->isBinaryOp()) {
1036     Value *V =
1037         SimplifyBinOp(E->getOpcode(), E->getOperand(0), E->getOperand(1), SQ);
1038     if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
1039       return SimplifiedE;
1040   } else if (auto *BI = dyn_cast<BitCastInst>(I)) {
1041     Value *V =
1042         SimplifyCastInst(BI->getOpcode(), BI->getOperand(0), BI->getType(), SQ);
1043     if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
1044       return SimplifiedE;
1045   } else if (isa<GetElementPtrInst>(I)) {
1046     Value *V = SimplifyGEPInst(
1047         E->getType(), ArrayRef<Value *>(E->op_begin(), E->op_end()), SQ);
1048     if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
1049       return SimplifiedE;
1050   } else if (AllConstant) {
1051     // We don't bother trying to simplify unless all of the operands
1052     // were constant.
1053     // TODO: There are a lot of Simplify*'s we could call here, if we
1054     // wanted to.  The original motivating case for this code was a
1055     // zext i1 false to i8, which we don't have an interface to
1056     // simplify (IE there is no SimplifyZExt).
1057 
1058     SmallVector<Constant *, 8> C;
1059     for (Value *Arg : E->operands())
1060       C.emplace_back(cast<Constant>(Arg));
1061 
1062     if (Value *V = ConstantFoldInstOperands(I, C, DL, TLI))
1063       if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
1064         return SimplifiedE;
1065   }
1066   return E;
1067 }
1068 
1069 const AggregateValueExpression *
1070 NewGVN::createAggregateValueExpression(Instruction *I) const {
1071   if (auto *II = dyn_cast<InsertValueInst>(I)) {
1072     auto *E = new (ExpressionAllocator)
1073         AggregateValueExpression(I->getNumOperands(), II->getNumIndices());
1074     setBasicExpressionInfo(I, E);
1075     E->allocateIntOperands(ExpressionAllocator);
1076     std::copy(II->idx_begin(), II->idx_end(), int_op_inserter(E));
1077     return E;
1078   } else if (auto *EI = dyn_cast<ExtractValueInst>(I)) {
1079     auto *E = new (ExpressionAllocator)
1080         AggregateValueExpression(I->getNumOperands(), EI->getNumIndices());
1081     setBasicExpressionInfo(EI, E);
1082     E->allocateIntOperands(ExpressionAllocator);
1083     std::copy(EI->idx_begin(), EI->idx_end(), int_op_inserter(E));
1084     return E;
1085   }
1086   llvm_unreachable("Unhandled type of aggregate value operation");
1087 }
1088 
1089 const DeadExpression *NewGVN::createDeadExpression() const {
1090   // DeadExpression has no arguments and all DeadExpression's are the same,
1091   // so we only need one of them.
1092   return SingletonDeadExpression;
1093 }
1094 
1095 const VariableExpression *NewGVN::createVariableExpression(Value *V) const {
1096   auto *E = new (ExpressionAllocator) VariableExpression(V);
1097   E->setOpcode(V->getValueID());
1098   return E;
1099 }
1100 
1101 const Expression *NewGVN::createVariableOrConstant(Value *V) const {
1102   if (auto *C = dyn_cast<Constant>(V))
1103     return createConstantExpression(C);
1104   return createVariableExpression(V);
1105 }
1106 
1107 const ConstantExpression *NewGVN::createConstantExpression(Constant *C) const {
1108   auto *E = new (ExpressionAllocator) ConstantExpression(C);
1109   E->setOpcode(C->getValueID());
1110   return E;
1111 }
1112 
1113 const UnknownExpression *NewGVN::createUnknownExpression(Instruction *I) const {
1114   auto *E = new (ExpressionAllocator) UnknownExpression(I);
1115   E->setOpcode(I->getOpcode());
1116   return E;
1117 }
1118 
1119 const CallExpression *
1120 NewGVN::createCallExpression(CallInst *CI, const MemoryAccess *MA) const {
1121   // FIXME: Add operand bundles for calls.
1122   auto *E =
1123       new (ExpressionAllocator) CallExpression(CI->getNumOperands(), CI, MA);
1124   setBasicExpressionInfo(CI, E);
1125   return E;
1126 }
1127 
1128 // Return true if some equivalent of instruction Inst dominates instruction U.
1129 bool NewGVN::someEquivalentDominates(const Instruction *Inst,
1130                                      const Instruction *U) const {
1131   auto *CC = ValueToClass.lookup(Inst);
1132   // This must be an instruction because we are only called from phi nodes
1133   // in the case that the value it needs to check against is an instruction.
1134 
1135   // The most likely candiates for dominance are the leader and the next leader.
1136   // The leader or nextleader will dominate in all cases where there is an
1137   // equivalent that is higher up in the dom tree.
1138   // We can't *only* check them, however, because the
1139   // dominator tree could have an infinite number of non-dominating siblings
1140   // with instructions that are in the right congruence class.
1141   //       A
1142   // B C D E F G
1143   // |
1144   // H
1145   // Instruction U could be in H,  with equivalents in every other sibling.
1146   // Depending on the rpo order picked, the leader could be the equivalent in
1147   // any of these siblings.
1148   if (!CC)
1149     return false;
1150   if (DT->dominates(cast<Instruction>(CC->getLeader()), U))
1151     return true;
1152   if (CC->getNextLeader().first &&
1153       DT->dominates(cast<Instruction>(CC->getNextLeader().first), U))
1154     return true;
1155   return llvm::any_of(*CC, [&](const Value *Member) {
1156     return Member != CC->getLeader() &&
1157            DT->dominates(cast<Instruction>(Member), U);
1158   });
1159 }
1160 
1161 // See if we have a congruence class and leader for this operand, and if so,
1162 // return it. Otherwise, return the operand itself.
1163 Value *NewGVN::lookupOperandLeader(Value *V) const {
1164   CongruenceClass *CC = ValueToClass.lookup(V);
1165   if (CC) {
1166     // Everything in TOP is represented by undef, as it can be any value.
1167     // We do have to make sure we get the type right though, so we can't set the
1168     // RepLeader to undef.
1169     if (CC == TOPClass)
1170       return UndefValue::get(V->getType());
1171     return CC->getStoredValue() ? CC->getStoredValue() : CC->getLeader();
1172   }
1173 
1174   return V;
1175 }
1176 
1177 const MemoryAccess *NewGVN::lookupMemoryLeader(const MemoryAccess *MA) const {
1178   auto *CC = getMemoryClass(MA);
1179   assert(CC->getMemoryLeader() &&
1180          "Every MemoryAccess should be mapped to a congruence class with a "
1181          "representative memory access");
1182   return CC->getMemoryLeader();
1183 }
1184 
1185 // Return true if the MemoryAccess is really equivalent to everything. This is
1186 // equivalent to the lattice value "TOP" in most lattices.  This is the initial
1187 // state of all MemoryAccesses.
1188 bool NewGVN::isMemoryAccessTOP(const MemoryAccess *MA) const {
1189   return getMemoryClass(MA) == TOPClass;
1190 }
1191 
1192 LoadExpression *NewGVN::createLoadExpression(Type *LoadType, Value *PointerOp,
1193                                              LoadInst *LI,
1194                                              const MemoryAccess *MA) const {
1195   auto *E =
1196       new (ExpressionAllocator) LoadExpression(1, LI, lookupMemoryLeader(MA));
1197   E->allocateOperands(ArgRecycler, ExpressionAllocator);
1198   E->setType(LoadType);
1199 
1200   // Give store and loads same opcode so they value number together.
1201   E->setOpcode(0);
1202   E->op_push_back(PointerOp);
1203   if (LI)
1204     E->setAlignment(LI->getAlignment());
1205 
1206   // TODO: Value number heap versions. We may be able to discover
1207   // things alias analysis can't on it's own (IE that a store and a
1208   // load have the same value, and thus, it isn't clobbering the load).
1209   return E;
1210 }
1211 
1212 const StoreExpression *
1213 NewGVN::createStoreExpression(StoreInst *SI, const MemoryAccess *MA) const {
1214   auto *StoredValueLeader = lookupOperandLeader(SI->getValueOperand());
1215   auto *E = new (ExpressionAllocator)
1216       StoreExpression(SI->getNumOperands(), SI, StoredValueLeader, MA);
1217   E->allocateOperands(ArgRecycler, ExpressionAllocator);
1218   E->setType(SI->getValueOperand()->getType());
1219 
1220   // Give store and loads same opcode so they value number together.
1221   E->setOpcode(0);
1222   E->op_push_back(lookupOperandLeader(SI->getPointerOperand()));
1223 
1224   // TODO: Value number heap versions. We may be able to discover
1225   // things alias analysis can't on it's own (IE that a store and a
1226   // load have the same value, and thus, it isn't clobbering the load).
1227   return E;
1228 }
1229 
1230 const Expression *NewGVN::performSymbolicStoreEvaluation(Instruction *I) const {
1231   // Unlike loads, we never try to eliminate stores, so we do not check if they
1232   // are simple and avoid value numbering them.
1233   auto *SI = cast<StoreInst>(I);
1234   auto *StoreAccess = getMemoryAccess(SI);
1235   // Get the expression, if any, for the RHS of the MemoryDef.
1236   const MemoryAccess *StoreRHS = StoreAccess->getDefiningAccess();
1237   if (EnableStoreRefinement)
1238     StoreRHS = MSSAWalker->getClobberingMemoryAccess(StoreAccess);
1239   // If we bypassed the use-def chains, make sure we add a use.
1240   StoreRHS = lookupMemoryLeader(StoreRHS);
1241   if (StoreRHS != StoreAccess->getDefiningAccess())
1242     addMemoryUsers(StoreRHS, StoreAccess);
1243   // If we are defined by ourselves, use the live on entry def.
1244   if (StoreRHS == StoreAccess)
1245     StoreRHS = MSSA->getLiveOnEntryDef();
1246 
1247   if (SI->isSimple()) {
1248     // See if we are defined by a previous store expression, it already has a
1249     // value, and it's the same value as our current store. FIXME: Right now, we
1250     // only do this for simple stores, we should expand to cover memcpys, etc.
1251     const auto *LastStore = createStoreExpression(SI, StoreRHS);
1252     const auto *LastCC = ExpressionToClass.lookup(LastStore);
1253     // We really want to check whether the expression we matched was a store. No
1254     // easy way to do that. However, we can check that the class we found has a
1255     // store, which, assuming the value numbering state is not corrupt, is
1256     // sufficient, because we must also be equivalent to that store's expression
1257     // for it to be in the same class as the load.
1258     if (LastCC && LastCC->getStoredValue() == LastStore->getStoredValue())
1259       return LastStore;
1260     // Also check if our value operand is defined by a load of the same memory
1261     // location, and the memory state is the same as it was then (otherwise, it
1262     // could have been overwritten later. See test32 in
1263     // transforms/DeadStoreElimination/simple.ll).
1264     if (auto *LI = dyn_cast<LoadInst>(LastStore->getStoredValue()))
1265       if ((lookupOperandLeader(LI->getPointerOperand()) ==
1266            LastStore->getOperand(0)) &&
1267           (lookupMemoryLeader(getMemoryAccess(LI)->getDefiningAccess()) ==
1268            StoreRHS))
1269         return LastStore;
1270     deleteExpression(LastStore);
1271   }
1272 
1273   // If the store is not equivalent to anything, value number it as a store that
1274   // produces a unique memory state (instead of using it's MemoryUse, we use
1275   // it's MemoryDef).
1276   return createStoreExpression(SI, StoreAccess);
1277 }
1278 
1279 // See if we can extract the value of a loaded pointer from a load, a store, or
1280 // a memory instruction.
1281 const Expression *
1282 NewGVN::performSymbolicLoadCoercion(Type *LoadType, Value *LoadPtr,
1283                                     LoadInst *LI, Instruction *DepInst,
1284                                     MemoryAccess *DefiningAccess) const {
1285   assert((!LI || LI->isSimple()) && "Not a simple load");
1286   if (auto *DepSI = dyn_cast<StoreInst>(DepInst)) {
1287     // Can't forward from non-atomic to atomic without violating memory model.
1288     // Also don't need to coerce if they are the same type, we will just
1289     // propagate.
1290     if (LI->isAtomic() > DepSI->isAtomic() ||
1291         LoadType == DepSI->getValueOperand()->getType())
1292       return nullptr;
1293     int Offset = analyzeLoadFromClobberingStore(LoadType, LoadPtr, DepSI, DL);
1294     if (Offset >= 0) {
1295       if (auto *C = dyn_cast<Constant>(
1296               lookupOperandLeader(DepSI->getValueOperand()))) {
1297         DEBUG(dbgs() << "Coercing load from store " << *DepSI << " to constant "
1298                      << *C << "\n");
1299         return createConstantExpression(
1300             getConstantStoreValueForLoad(C, Offset, LoadType, DL));
1301       }
1302     }
1303 
1304   } else if (auto *DepLI = dyn_cast<LoadInst>(DepInst)) {
1305     // Can't forward from non-atomic to atomic without violating memory model.
1306     if (LI->isAtomic() > DepLI->isAtomic())
1307       return nullptr;
1308     int Offset = analyzeLoadFromClobberingLoad(LoadType, LoadPtr, DepLI, DL);
1309     if (Offset >= 0) {
1310       // We can coerce a constant load into a load.
1311       if (auto *C = dyn_cast<Constant>(lookupOperandLeader(DepLI)))
1312         if (auto *PossibleConstant =
1313                 getConstantLoadValueForLoad(C, Offset, LoadType, DL)) {
1314           DEBUG(dbgs() << "Coercing load from load " << *LI << " to constant "
1315                        << *PossibleConstant << "\n");
1316           return createConstantExpression(PossibleConstant);
1317         }
1318     }
1319 
1320   } else if (auto *DepMI = dyn_cast<MemIntrinsic>(DepInst)) {
1321     int Offset = analyzeLoadFromClobberingMemInst(LoadType, LoadPtr, DepMI, DL);
1322     if (Offset >= 0) {
1323       if (auto *PossibleConstant =
1324               getConstantMemInstValueForLoad(DepMI, Offset, LoadType, DL)) {
1325         DEBUG(dbgs() << "Coercing load from meminst " << *DepMI
1326                      << " to constant " << *PossibleConstant << "\n");
1327         return createConstantExpression(PossibleConstant);
1328       }
1329     }
1330   }
1331 
1332   // All of the below are only true if the loaded pointer is produced
1333   // by the dependent instruction.
1334   if (LoadPtr != lookupOperandLeader(DepInst) &&
1335       !AA->isMustAlias(LoadPtr, DepInst))
1336     return nullptr;
1337   // If this load really doesn't depend on anything, then we must be loading an
1338   // undef value.  This can happen when loading for a fresh allocation with no
1339   // intervening stores, for example.  Note that this is only true in the case
1340   // that the result of the allocation is pointer equal to the load ptr.
1341   if (isa<AllocaInst>(DepInst) || isMallocLikeFn(DepInst, TLI)) {
1342     return createConstantExpression(UndefValue::get(LoadType));
1343   }
1344   // If this load occurs either right after a lifetime begin,
1345   // then the loaded value is undefined.
1346   else if (auto *II = dyn_cast<IntrinsicInst>(DepInst)) {
1347     if (II->getIntrinsicID() == Intrinsic::lifetime_start)
1348       return createConstantExpression(UndefValue::get(LoadType));
1349   }
1350   // If this load follows a calloc (which zero initializes memory),
1351   // then the loaded value is zero
1352   else if (isCallocLikeFn(DepInst, TLI)) {
1353     return createConstantExpression(Constant::getNullValue(LoadType));
1354   }
1355 
1356   return nullptr;
1357 }
1358 
1359 const Expression *NewGVN::performSymbolicLoadEvaluation(Instruction *I) const {
1360   auto *LI = cast<LoadInst>(I);
1361 
1362   // We can eliminate in favor of non-simple loads, but we won't be able to
1363   // eliminate the loads themselves.
1364   if (!LI->isSimple())
1365     return nullptr;
1366 
1367   Value *LoadAddressLeader = lookupOperandLeader(LI->getPointerOperand());
1368   // Load of undef is undef.
1369   if (isa<UndefValue>(LoadAddressLeader))
1370     return createConstantExpression(UndefValue::get(LI->getType()));
1371   MemoryAccess *OriginalAccess = getMemoryAccess(I);
1372   MemoryAccess *DefiningAccess =
1373       MSSAWalker->getClobberingMemoryAccess(OriginalAccess);
1374 
1375   if (!MSSA->isLiveOnEntryDef(DefiningAccess)) {
1376     if (auto *MD = dyn_cast<MemoryDef>(DefiningAccess)) {
1377       Instruction *DefiningInst = MD->getMemoryInst();
1378       // If the defining instruction is not reachable, replace with undef.
1379       if (!ReachableBlocks.count(DefiningInst->getParent()))
1380         return createConstantExpression(UndefValue::get(LI->getType()));
1381       // This will handle stores and memory insts.  We only do if it the
1382       // defining access has a different type, or it is a pointer produced by
1383       // certain memory operations that cause the memory to have a fixed value
1384       // (IE things like calloc).
1385       if (const auto *CoercionResult =
1386               performSymbolicLoadCoercion(LI->getType(), LoadAddressLeader, LI,
1387                                           DefiningInst, DefiningAccess))
1388         return CoercionResult;
1389     }
1390   }
1391 
1392   const auto *LE = createLoadExpression(LI->getType(), LoadAddressLeader,
1393                                              LI, DefiningAccess);
1394   // If our MemoryLeader is not our defining access, add a use to the
1395   // MemoryLeader, so that we get reprocessed when it changes.
1396   if (LE->getMemoryLeader() != DefiningAccess)
1397     addMemoryUsers(LE->getMemoryLeader(), OriginalAccess);
1398   return LE;
1399 }
1400 
1401 const Expression *
1402 NewGVN::performSymbolicPredicateInfoEvaluation(Instruction *I) const {
1403   auto *PI = PredInfo->getPredicateInfoFor(I);
1404   if (!PI)
1405     return nullptr;
1406 
1407   DEBUG(dbgs() << "Found predicate info from instruction !\n");
1408 
1409   auto *PWC = dyn_cast<PredicateWithCondition>(PI);
1410   if (!PWC)
1411     return nullptr;
1412 
1413   auto *CopyOf = I->getOperand(0);
1414   auto *Cond = PWC->Condition;
1415 
1416   // If this a copy of the condition, it must be either true or false depending
1417   // on the predicate info type and edge.
1418   if (CopyOf == Cond) {
1419     // We should not need to add predicate users because the predicate info is
1420     // already a use of this operand.
1421     if (isa<PredicateAssume>(PI))
1422       return createConstantExpression(ConstantInt::getTrue(Cond->getType()));
1423     if (auto *PBranch = dyn_cast<PredicateBranch>(PI)) {
1424       if (PBranch->TrueEdge)
1425         return createConstantExpression(ConstantInt::getTrue(Cond->getType()));
1426       return createConstantExpression(ConstantInt::getFalse(Cond->getType()));
1427     }
1428     if (auto *PSwitch = dyn_cast<PredicateSwitch>(PI))
1429       return createConstantExpression(cast<Constant>(PSwitch->CaseValue));
1430   }
1431 
1432   // Not a copy of the condition, so see what the predicates tell us about this
1433   // value.  First, though, we check to make sure the value is actually a copy
1434   // of one of the condition operands. It's possible, in certain cases, for it
1435   // to be a copy of a predicateinfo copy. In particular, if two branch
1436   // operations use the same condition, and one branch dominates the other, we
1437   // will end up with a copy of a copy.  This is currently a small deficiency in
1438   // predicateinfo.  What will end up happening here is that we will value
1439   // number both copies the same anyway.
1440 
1441   // Everything below relies on the condition being a comparison.
1442   auto *Cmp = dyn_cast<CmpInst>(Cond);
1443   if (!Cmp)
1444     return nullptr;
1445 
1446   if (CopyOf != Cmp->getOperand(0) && CopyOf != Cmp->getOperand(1)) {
1447     DEBUG(dbgs() << "Copy is not of any condition operands!\n");
1448     return nullptr;
1449   }
1450   Value *FirstOp = lookupOperandLeader(Cmp->getOperand(0));
1451   Value *SecondOp = lookupOperandLeader(Cmp->getOperand(1));
1452   bool SwappedOps = false;
1453   // Sort the ops.
1454   if (shouldSwapOperands(FirstOp, SecondOp)) {
1455     std::swap(FirstOp, SecondOp);
1456     SwappedOps = true;
1457   }
1458   CmpInst::Predicate Predicate =
1459       SwappedOps ? Cmp->getSwappedPredicate() : Cmp->getPredicate();
1460 
1461   if (isa<PredicateAssume>(PI)) {
1462     // If the comparison is true when the operands are equal, then we know the
1463     // operands are equal, because assumes must always be true.
1464     if (CmpInst::isTrueWhenEqual(Predicate)) {
1465       addPredicateUsers(PI, I);
1466       addAdditionalUsers(Cmp->getOperand(0), I);
1467       return createVariableOrConstant(FirstOp);
1468     }
1469   }
1470   if (const auto *PBranch = dyn_cast<PredicateBranch>(PI)) {
1471     // If we are *not* a copy of the comparison, we may equal to the other
1472     // operand when the predicate implies something about equality of
1473     // operations.  In particular, if the comparison is true/false when the
1474     // operands are equal, and we are on the right edge, we know this operation
1475     // is equal to something.
1476     if ((PBranch->TrueEdge && Predicate == CmpInst::ICMP_EQ) ||
1477         (!PBranch->TrueEdge && Predicate == CmpInst::ICMP_NE)) {
1478       addPredicateUsers(PI, I);
1479       addAdditionalUsers(SwappedOps ? Cmp->getOperand(1) : Cmp->getOperand(0),
1480                          I);
1481       return createVariableOrConstant(FirstOp);
1482     }
1483     // Handle the special case of floating point.
1484     if (((PBranch->TrueEdge && Predicate == CmpInst::FCMP_OEQ) ||
1485          (!PBranch->TrueEdge && Predicate == CmpInst::FCMP_UNE)) &&
1486         isa<ConstantFP>(FirstOp) && !cast<ConstantFP>(FirstOp)->isZero()) {
1487       addPredicateUsers(PI, I);
1488       addAdditionalUsers(SwappedOps ? Cmp->getOperand(1) : Cmp->getOperand(0),
1489                          I);
1490       return createConstantExpression(cast<Constant>(FirstOp));
1491     }
1492   }
1493   return nullptr;
1494 }
1495 
1496 // Evaluate read only and pure calls, and create an expression result.
1497 const Expression *NewGVN::performSymbolicCallEvaluation(Instruction *I) const {
1498   auto *CI = cast<CallInst>(I);
1499   if (auto *II = dyn_cast<IntrinsicInst>(I)) {
1500     // Instrinsics with the returned attribute are copies of arguments.
1501     if (auto *ReturnedValue = II->getReturnedArgOperand()) {
1502       if (II->getIntrinsicID() == Intrinsic::ssa_copy)
1503         if (const auto *Result = performSymbolicPredicateInfoEvaluation(I))
1504           return Result;
1505       return createVariableOrConstant(ReturnedValue);
1506     }
1507   }
1508   if (AA->doesNotAccessMemory(CI)) {
1509     return createCallExpression(CI, TOPClass->getMemoryLeader());
1510   } else if (AA->onlyReadsMemory(CI)) {
1511     MemoryAccess *DefiningAccess = MSSAWalker->getClobberingMemoryAccess(CI);
1512     return createCallExpression(CI, DefiningAccess);
1513   }
1514   return nullptr;
1515 }
1516 
1517 // Retrieve the memory class for a given MemoryAccess.
1518 CongruenceClass *NewGVN::getMemoryClass(const MemoryAccess *MA) const {
1519 
1520   auto *Result = MemoryAccessToClass.lookup(MA);
1521   assert(Result && "Should have found memory class");
1522   return Result;
1523 }
1524 
1525 // Update the MemoryAccess equivalence table to say that From is equal to To,
1526 // and return true if this is different from what already existed in the table.
1527 bool NewGVN::setMemoryClass(const MemoryAccess *From,
1528                             CongruenceClass *NewClass) {
1529   assert(NewClass &&
1530          "Every MemoryAccess should be getting mapped to a non-null class");
1531   DEBUG(dbgs() << "Setting " << *From);
1532   DEBUG(dbgs() << " equivalent to congruence class ");
1533   DEBUG(dbgs() << NewClass->getID() << " with current MemoryAccess leader ");
1534   DEBUG(dbgs() << *NewClass->getMemoryLeader() << "\n");
1535 
1536   auto LookupResult = MemoryAccessToClass.find(From);
1537   bool Changed = false;
1538   // If it's already in the table, see if the value changed.
1539   if (LookupResult != MemoryAccessToClass.end()) {
1540     auto *OldClass = LookupResult->second;
1541     if (OldClass != NewClass) {
1542       // If this is a phi, we have to handle memory member updates.
1543       if (auto *MP = dyn_cast<MemoryPhi>(From)) {
1544         OldClass->memory_erase(MP);
1545         NewClass->memory_insert(MP);
1546         // This may have killed the class if it had no non-memory members
1547         if (OldClass->getMemoryLeader() == From) {
1548           if (OldClass->definesNoMemory()) {
1549             OldClass->setMemoryLeader(nullptr);
1550           } else {
1551             OldClass->setMemoryLeader(getNextMemoryLeader(OldClass));
1552             DEBUG(dbgs() << "Memory class leader change for class "
1553                          << OldClass->getID() << " to "
1554                          << *OldClass->getMemoryLeader()
1555                          << " due to removal of a memory member " << *From
1556                          << "\n");
1557             markMemoryLeaderChangeTouched(OldClass);
1558           }
1559         }
1560       }
1561       // It wasn't equivalent before, and now it is.
1562       LookupResult->second = NewClass;
1563       Changed = true;
1564     }
1565   }
1566 
1567   return Changed;
1568 }
1569 
1570 // Determine if a instruction is cycle-free.  That means the values in the
1571 // instruction don't depend on any expressions that can change value as a result
1572 // of the instruction.  For example, a non-cycle free instruction would be v =
1573 // phi(0, v+1).
1574 bool NewGVN::isCycleFree(const Instruction *I) const {
1575   // In order to compute cycle-freeness, we do SCC finding on the instruction,
1576   // and see what kind of SCC it ends up in.  If it is a singleton, it is
1577   // cycle-free.  If it is not in a singleton, it is only cycle free if the
1578   // other members are all phi nodes (as they do not compute anything, they are
1579   // copies).
1580   auto ICS = InstCycleState.lookup(I);
1581   if (ICS == ICS_Unknown) {
1582     SCCFinder.Start(I);
1583     auto &SCC = SCCFinder.getComponentFor(I);
1584     // It's cycle free if it's size 1 or or the SCC is *only* phi nodes.
1585     if (SCC.size() == 1)
1586       InstCycleState.insert({I, ICS_CycleFree});
1587     else {
1588       bool AllPhis =
1589           llvm::all_of(SCC, [](const Value *V) { return isa<PHINode>(V); });
1590       ICS = AllPhis ? ICS_CycleFree : ICS_Cycle;
1591       for (auto *Member : SCC)
1592         if (auto *MemberPhi = dyn_cast<PHINode>(Member))
1593           InstCycleState.insert({MemberPhi, ICS});
1594     }
1595   }
1596   if (ICS == ICS_Cycle)
1597     return false;
1598   return true;
1599 }
1600 
1601 // Evaluate PHI nodes symbolically and create an expression result.
1602 const Expression *NewGVN::performSymbolicPHIEvaluation(Instruction *I) const {
1603   // True if one of the incoming phi edges is a backedge.
1604   bool HasBackedge = false;
1605   // All constant tracks the state of whether all the *original* phi operands
1606   // This is really shorthand for "this phi cannot cycle due to forward
1607   // change in value of the phi is guaranteed not to later change the value of
1608   // the phi. IE it can't be v = phi(undef, v+1)
1609   bool AllConstant = true;
1610   auto *E =
1611       cast<PHIExpression>(createPHIExpression(I, HasBackedge, AllConstant));
1612   // We match the semantics of SimplifyPhiNode from InstructionSimplify here.
1613   // See if all arguments are the same.
1614   // We track if any were undef because they need special handling.
1615   bool HasUndef = false;
1616   auto Filtered = make_filter_range(E->operands(), [&](Value *Arg) {
1617     if (isa<UndefValue>(Arg)) {
1618       HasUndef = true;
1619       return false;
1620     }
1621     return true;
1622   });
1623   // If we are left with no operands, it's dead.
1624   if (Filtered.begin() == Filtered.end()) {
1625     // If it has undef at this point, it means there are no-non-undef arguments,
1626     // and thus, the value of the phi node must be undef.
1627     if (HasUndef) {
1628       DEBUG(dbgs() << "PHI Node " << *I
1629                    << " has no non-undef arguments, valuing it as undef\n");
1630       return createConstantExpression(UndefValue::get(I->getType()));
1631     }
1632 
1633     DEBUG(dbgs() << "No arguments of PHI node " << *I << " are live\n");
1634     deleteExpression(E);
1635     return createDeadExpression();
1636   }
1637   unsigned NumOps = 0;
1638   Value *AllSameValue = *(Filtered.begin());
1639   ++Filtered.begin();
1640   // Can't use std::equal here, sadly, because filter.begin moves.
1641   if (llvm::all_of(Filtered, [&](Value *Arg) {
1642         ++NumOps;
1643         return Arg == AllSameValue;
1644       })) {
1645     // In LLVM's non-standard representation of phi nodes, it's possible to have
1646     // phi nodes with cycles (IE dependent on other phis that are .... dependent
1647     // on the original phi node), especially in weird CFG's where some arguments
1648     // are unreachable, or uninitialized along certain paths.  This can cause
1649     // infinite loops during evaluation. We work around this by not trying to
1650     // really evaluate them independently, but instead using a variable
1651     // expression to say if one is equivalent to the other.
1652     // We also special case undef, so that if we have an undef, we can't use the
1653     // common value unless it dominates the phi block.
1654     if (HasUndef) {
1655       // If we have undef and at least one other value, this is really a
1656       // multivalued phi, and we need to know if it's cycle free in order to
1657       // evaluate whether we can ignore the undef.  The other parts of this are
1658       // just shortcuts.  If there is no backedge, or all operands are
1659       // constants, or all operands are ignored but the undef, it also must be
1660       // cycle free.
1661       if (!AllConstant && HasBackedge && NumOps > 0 &&
1662           !isa<UndefValue>(AllSameValue) && !isCycleFree(I))
1663         return E;
1664 
1665       // Only have to check for instructions
1666       if (auto *AllSameInst = dyn_cast<Instruction>(AllSameValue))
1667         if (!someEquivalentDominates(AllSameInst, I))
1668           return E;
1669     }
1670     // Can't simplify to something that comes later in the iteration.
1671     // Otherwise, when and if it changes congruence class, we will never catch
1672     // up. We will always be a class behind it.
1673     if (isa<Instruction>(AllSameValue) &&
1674         InstrToDFSNum(AllSameValue) > InstrToDFSNum(I))
1675       return E;
1676     NumGVNPhisAllSame++;
1677     DEBUG(dbgs() << "Simplified PHI node " << *I << " to " << *AllSameValue
1678                  << "\n");
1679     deleteExpression(E);
1680     return createVariableOrConstant(AllSameValue);
1681   }
1682   return E;
1683 }
1684 
1685 const Expression *
1686 NewGVN::performSymbolicAggrValueEvaluation(Instruction *I) const {
1687   if (auto *EI = dyn_cast<ExtractValueInst>(I)) {
1688     auto *II = dyn_cast<IntrinsicInst>(EI->getAggregateOperand());
1689     if (II && EI->getNumIndices() == 1 && *EI->idx_begin() == 0) {
1690       unsigned Opcode = 0;
1691       // EI might be an extract from one of our recognised intrinsics. If it
1692       // is we'll synthesize a semantically equivalent expression instead on
1693       // an extract value expression.
1694       switch (II->getIntrinsicID()) {
1695       case Intrinsic::sadd_with_overflow:
1696       case Intrinsic::uadd_with_overflow:
1697         Opcode = Instruction::Add;
1698         break;
1699       case Intrinsic::ssub_with_overflow:
1700       case Intrinsic::usub_with_overflow:
1701         Opcode = Instruction::Sub;
1702         break;
1703       case Intrinsic::smul_with_overflow:
1704       case Intrinsic::umul_with_overflow:
1705         Opcode = Instruction::Mul;
1706         break;
1707       default:
1708         break;
1709       }
1710 
1711       if (Opcode != 0) {
1712         // Intrinsic recognized. Grab its args to finish building the
1713         // expression.
1714         assert(II->getNumArgOperands() == 2 &&
1715                "Expect two args for recognised intrinsics.");
1716         return createBinaryExpression(
1717             Opcode, EI->getType(), II->getArgOperand(0), II->getArgOperand(1));
1718       }
1719     }
1720   }
1721 
1722   return createAggregateValueExpression(I);
1723 }
1724 const Expression *NewGVN::performSymbolicCmpEvaluation(Instruction *I) const {
1725   assert(isa<CmpInst>(I) && "Expected a cmp instruction.");
1726 
1727   auto *CI = cast<CmpInst>(I);
1728   // See if our operands are equal to those of a previous predicate, and if so,
1729   // if it implies true or false.
1730   auto Op0 = lookupOperandLeader(CI->getOperand(0));
1731   auto Op1 = lookupOperandLeader(CI->getOperand(1));
1732   auto OurPredicate = CI->getPredicate();
1733   if (shouldSwapOperands(Op0, Op1)) {
1734     std::swap(Op0, Op1);
1735     OurPredicate = CI->getSwappedPredicate();
1736   }
1737 
1738   // Avoid processing the same info twice.
1739   const PredicateBase *LastPredInfo = nullptr;
1740   // See if we know something about the comparison itself, like it is the target
1741   // of an assume.
1742   auto *CmpPI = PredInfo->getPredicateInfoFor(I);
1743   if (dyn_cast_or_null<PredicateAssume>(CmpPI))
1744     return createConstantExpression(ConstantInt::getTrue(CI->getType()));
1745 
1746   if (Op0 == Op1) {
1747     // This condition does not depend on predicates, no need to add users
1748     if (CI->isTrueWhenEqual())
1749       return createConstantExpression(ConstantInt::getTrue(CI->getType()));
1750     else if (CI->isFalseWhenEqual())
1751       return createConstantExpression(ConstantInt::getFalse(CI->getType()));
1752   }
1753 
1754   // NOTE: Because we are comparing both operands here and below, and using
1755   // previous comparisons, we rely on fact that predicateinfo knows to mark
1756   // comparisons that use renamed operands as users of the earlier comparisons.
1757   // It is *not* enough to just mark predicateinfo renamed operands as users of
1758   // the earlier comparisons, because the *other* operand may have changed in a
1759   // previous iteration.
1760   // Example:
1761   // icmp slt %a, %b
1762   // %b.0 = ssa.copy(%b)
1763   // false branch:
1764   // icmp slt %c, %b.0
1765 
1766   // %c and %a may start out equal, and thus, the code below will say the second
1767   // %icmp is false.  c may become equal to something else, and in that case the
1768   // %second icmp *must* be reexamined, but would not if only the renamed
1769   // %operands are considered users of the icmp.
1770 
1771   // *Currently* we only check one level of comparisons back, and only mark one
1772   // level back as touched when changes happen.  If you modify this code to look
1773   // back farther through comparisons, you *must* mark the appropriate
1774   // comparisons as users in PredicateInfo.cpp, or you will cause bugs.  See if
1775   // we know something just from the operands themselves
1776 
1777   // See if our operands have predicate info, so that we may be able to derive
1778   // something from a previous comparison.
1779   for (const auto &Op : CI->operands()) {
1780     auto *PI = PredInfo->getPredicateInfoFor(Op);
1781     if (const auto *PBranch = dyn_cast_or_null<PredicateBranch>(PI)) {
1782       if (PI == LastPredInfo)
1783         continue;
1784       LastPredInfo = PI;
1785 
1786       // TODO: Along the false edge, we may know more things too, like icmp of
1787       // same operands is false.
1788       // TODO: We only handle actual comparison conditions below, not and/or.
1789       auto *BranchCond = dyn_cast<CmpInst>(PBranch->Condition);
1790       if (!BranchCond)
1791         continue;
1792       auto *BranchOp0 = lookupOperandLeader(BranchCond->getOperand(0));
1793       auto *BranchOp1 = lookupOperandLeader(BranchCond->getOperand(1));
1794       auto BranchPredicate = BranchCond->getPredicate();
1795       if (shouldSwapOperands(BranchOp0, BranchOp1)) {
1796         std::swap(BranchOp0, BranchOp1);
1797         BranchPredicate = BranchCond->getSwappedPredicate();
1798       }
1799       if (BranchOp0 == Op0 && BranchOp1 == Op1) {
1800         if (PBranch->TrueEdge) {
1801           // If we know the previous predicate is true and we are in the true
1802           // edge then we may be implied true or false.
1803           if (CmpInst::isImpliedTrueByMatchingCmp(BranchPredicate,
1804                                                   OurPredicate)) {
1805             addPredicateUsers(PI, I);
1806             return createConstantExpression(
1807                 ConstantInt::getTrue(CI->getType()));
1808           }
1809 
1810           if (CmpInst::isImpliedFalseByMatchingCmp(BranchPredicate,
1811                                                    OurPredicate)) {
1812             addPredicateUsers(PI, I);
1813             return createConstantExpression(
1814                 ConstantInt::getFalse(CI->getType()));
1815           }
1816 
1817         } else {
1818           // Just handle the ne and eq cases, where if we have the same
1819           // operands, we may know something.
1820           if (BranchPredicate == OurPredicate) {
1821             addPredicateUsers(PI, I);
1822             // Same predicate, same ops,we know it was false, so this is false.
1823             return createConstantExpression(
1824                 ConstantInt::getFalse(CI->getType()));
1825           } else if (BranchPredicate ==
1826                      CmpInst::getInversePredicate(OurPredicate)) {
1827             addPredicateUsers(PI, I);
1828             // Inverse predicate, we know the other was false, so this is true.
1829             return createConstantExpression(
1830                 ConstantInt::getTrue(CI->getType()));
1831           }
1832         }
1833       }
1834     }
1835   }
1836   // Create expression will take care of simplifyCmpInst
1837   return createExpression(I);
1838 }
1839 
1840 // Return true if V is a value that will always be available (IE can
1841 // be placed anywhere) in the function.  We don't do globals here
1842 // because they are often worse to put in place.
1843 static bool alwaysAvailable(Value *V) {
1844   return isa<Constant>(V) || isa<Argument>(V);
1845 }
1846 
1847 // Substitute and symbolize the value before value numbering.
1848 const Expression *
1849 NewGVN::performSymbolicEvaluation(Value *V,
1850                                   SmallPtrSetImpl<Value *> &Visited) const {
1851   const Expression *E = nullptr;
1852   if (auto *C = dyn_cast<Constant>(V))
1853     E = createConstantExpression(C);
1854   else if (isa<Argument>(V) || isa<GlobalVariable>(V)) {
1855     E = createVariableExpression(V);
1856   } else {
1857     // TODO: memory intrinsics.
1858     // TODO: Some day, we should do the forward propagation and reassociation
1859     // parts of the algorithm.
1860     auto *I = cast<Instruction>(V);
1861     switch (I->getOpcode()) {
1862     case Instruction::ExtractValue:
1863     case Instruction::InsertValue:
1864       E = performSymbolicAggrValueEvaluation(I);
1865       break;
1866     case Instruction::PHI:
1867       E = performSymbolicPHIEvaluation(I);
1868       break;
1869     case Instruction::Call:
1870       E = performSymbolicCallEvaluation(I);
1871       break;
1872     case Instruction::Store:
1873       E = performSymbolicStoreEvaluation(I);
1874       break;
1875     case Instruction::Load:
1876       E = performSymbolicLoadEvaluation(I);
1877       break;
1878     case Instruction::BitCast: {
1879       E = createExpression(I);
1880     } break;
1881     case Instruction::ICmp:
1882     case Instruction::FCmp: {
1883       E = performSymbolicCmpEvaluation(I);
1884     } break;
1885     case Instruction::Add:
1886     case Instruction::FAdd:
1887     case Instruction::Sub:
1888     case Instruction::FSub:
1889     case Instruction::Mul:
1890     case Instruction::FMul:
1891     case Instruction::UDiv:
1892     case Instruction::SDiv:
1893     case Instruction::FDiv:
1894     case Instruction::URem:
1895     case Instruction::SRem:
1896     case Instruction::FRem:
1897     case Instruction::Shl:
1898     case Instruction::LShr:
1899     case Instruction::AShr:
1900     case Instruction::And:
1901     case Instruction::Or:
1902     case Instruction::Xor:
1903     case Instruction::Trunc:
1904     case Instruction::ZExt:
1905     case Instruction::SExt:
1906     case Instruction::FPToUI:
1907     case Instruction::FPToSI:
1908     case Instruction::UIToFP:
1909     case Instruction::SIToFP:
1910     case Instruction::FPTrunc:
1911     case Instruction::FPExt:
1912     case Instruction::PtrToInt:
1913     case Instruction::IntToPtr:
1914     case Instruction::Select:
1915     case Instruction::ExtractElement:
1916     case Instruction::InsertElement:
1917     case Instruction::ShuffleVector:
1918     case Instruction::GetElementPtr:
1919       E = createExpression(I);
1920       break;
1921     default:
1922       return nullptr;
1923     }
1924   }
1925   return E;
1926 }
1927 
1928 // Look up a container in a map, and then call a function for each thing in the
1929 // found container.
1930 template <typename Map, typename KeyType, typename Func>
1931 void NewGVN::for_each_found(Map &M, const KeyType &Key, Func F) {
1932   const auto Result = M.find_as(Key);
1933   if (Result != M.end())
1934     for (typename Map::mapped_type::value_type Mapped : Result->second)
1935       F(Mapped);
1936 }
1937 
1938 // Look up a container of values/instructions in a map, and touch all the
1939 // instructions in the container.  Then erase value from the map.
1940 template <typename Map, typename KeyType>
1941 void NewGVN::touchAndErase(Map &M, const KeyType &Key) {
1942   const auto Result = M.find_as(Key);
1943   if (Result != M.end()) {
1944     for (const typename Map::mapped_type::value_type Mapped : Result->second)
1945       TouchedInstructions.set(InstrToDFSNum(Mapped));
1946     M.erase(Result);
1947   }
1948 }
1949 
1950 void NewGVN::addAdditionalUsers(Value *To, Value *User) const {
1951   if (isa<Instruction>(To))
1952     AdditionalUsers[To].insert(User);
1953 }
1954 
1955 void NewGVN::markUsersTouched(Value *V) {
1956   // Now mark the users as touched.
1957   for (auto *User : V->users()) {
1958     assert(isa<Instruction>(User) && "Use of value not within an instruction?");
1959     TouchedInstructions.set(InstrToDFSNum(User));
1960   }
1961   touchAndErase(AdditionalUsers, V);
1962 }
1963 
1964 void NewGVN::addMemoryUsers(const MemoryAccess *To, MemoryAccess *U) const {
1965   DEBUG(dbgs() << "Adding memory user " << *U << " to " << *To << "\n");
1966   MemoryToUsers[To].insert(U);
1967 }
1968 
1969 void NewGVN::markMemoryDefTouched(const MemoryAccess *MA) {
1970   TouchedInstructions.set(MemoryToDFSNum(MA));
1971 }
1972 
1973 void NewGVN::markMemoryUsersTouched(const MemoryAccess *MA) {
1974   if (isa<MemoryUse>(MA))
1975     return;
1976   for (auto U : MA->users())
1977     TouchedInstructions.set(MemoryToDFSNum(U));
1978   touchAndErase(MemoryToUsers, MA);
1979 }
1980 
1981 // Add I to the set of users of a given predicate.
1982 void NewGVN::addPredicateUsers(const PredicateBase *PB, Instruction *I) const {
1983   // Don't add temporary instructions to the user lists.
1984   if (AllTempInstructions.count(I))
1985     return;
1986 
1987   if (auto *PBranch = dyn_cast<PredicateBranch>(PB))
1988     PredicateToUsers[PBranch->Condition].insert(I);
1989   else if (auto *PAssume = dyn_cast<PredicateBranch>(PB))
1990     PredicateToUsers[PAssume->Condition].insert(I);
1991 }
1992 
1993 // Touch all the predicates that depend on this instruction.
1994 void NewGVN::markPredicateUsersTouched(Instruction *I) {
1995   touchAndErase(PredicateToUsers, I);
1996 }
1997 
1998 // Mark users affected by a memory leader change.
1999 void NewGVN::markMemoryLeaderChangeTouched(CongruenceClass *CC) {
2000   for (auto M : CC->memory())
2001     markMemoryDefTouched(M);
2002 }
2003 
2004 // Touch the instructions that need to be updated after a congruence class has a
2005 // leader change, and mark changed values.
2006 void NewGVN::markValueLeaderChangeTouched(CongruenceClass *CC) {
2007   for (auto M : *CC) {
2008     if (auto *I = dyn_cast<Instruction>(M))
2009       TouchedInstructions.set(InstrToDFSNum(I));
2010     LeaderChanges.insert(M);
2011   }
2012 }
2013 
2014 // Give a range of things that have instruction DFS numbers, this will return
2015 // the member of the range with the smallest dfs number.
2016 template <class T, class Range>
2017 T *NewGVN::getMinDFSOfRange(const Range &R) const {
2018   std::pair<T *, unsigned> MinDFS = {nullptr, ~0U};
2019   for (const auto X : R) {
2020     auto DFSNum = InstrToDFSNum(X);
2021     if (DFSNum < MinDFS.second)
2022       MinDFS = {X, DFSNum};
2023   }
2024   return MinDFS.first;
2025 }
2026 
2027 // This function returns the MemoryAccess that should be the next leader of
2028 // congruence class CC, under the assumption that the current leader is going to
2029 // disappear.
2030 const MemoryAccess *NewGVN::getNextMemoryLeader(CongruenceClass *CC) const {
2031   // TODO: If this ends up to slow, we can maintain a next memory leader like we
2032   // do for regular leaders.
2033   // Make sure there will be a leader to find.
2034   assert(!CC->definesNoMemory() && "Can't get next leader if there is none");
2035   if (CC->getStoreCount() > 0) {
2036     if (auto *NL = dyn_cast_or_null<StoreInst>(CC->getNextLeader().first))
2037       return getMemoryAccess(NL);
2038     // Find the store with the minimum DFS number.
2039     auto *V = getMinDFSOfRange<Value>(make_filter_range(
2040         *CC, [&](const Value *V) { return isa<StoreInst>(V); }));
2041     return getMemoryAccess(cast<StoreInst>(V));
2042   }
2043   assert(CC->getStoreCount() == 0);
2044 
2045   // Given our assertion, hitting this part must mean
2046   // !OldClass->memory_empty()
2047   if (CC->memory_size() == 1)
2048     return *CC->memory_begin();
2049   return getMinDFSOfRange<const MemoryPhi>(CC->memory());
2050 }
2051 
2052 // This function returns the next value leader of a congruence class, under the
2053 // assumption that the current leader is going away.  This should end up being
2054 // the next most dominating member.
2055 Value *NewGVN::getNextValueLeader(CongruenceClass *CC) const {
2056   // We don't need to sort members if there is only 1, and we don't care about
2057   // sorting the TOP class because everything either gets out of it or is
2058   // unreachable.
2059 
2060   if (CC->size() == 1 || CC == TOPClass) {
2061     return *(CC->begin());
2062   } else if (CC->getNextLeader().first) {
2063     ++NumGVNAvoidedSortedLeaderChanges;
2064     return CC->getNextLeader().first;
2065   } else {
2066     ++NumGVNSortedLeaderChanges;
2067     // NOTE: If this ends up to slow, we can maintain a dual structure for
2068     // member testing/insertion, or keep things mostly sorted, and sort only
2069     // here, or use SparseBitVector or ....
2070     return getMinDFSOfRange<Value>(*CC);
2071   }
2072 }
2073 
2074 // Move a MemoryAccess, currently in OldClass, to NewClass, including updates to
2075 // the memory members, etc for the move.
2076 //
2077 // The invariants of this function are:
2078 //
2079 // - I must be moving to NewClass from OldClass
2080 // - The StoreCount of OldClass and NewClass is expected to have been updated
2081 //   for I already if it is is a store.
2082 // - The OldClass memory leader has not been updated yet if I was the leader.
2083 void NewGVN::moveMemoryToNewCongruenceClass(Instruction *I,
2084                                             MemoryAccess *InstMA,
2085                                             CongruenceClass *OldClass,
2086                                             CongruenceClass *NewClass) {
2087   // If the leader is I, and we had a represenative MemoryAccess, it should
2088   // be the MemoryAccess of OldClass.
2089   assert((!InstMA || !OldClass->getMemoryLeader() ||
2090           OldClass->getLeader() != I ||
2091           MemoryAccessToClass.lookup(OldClass->getMemoryLeader()) ==
2092               MemoryAccessToClass.lookup(InstMA)) &&
2093          "Representative MemoryAccess mismatch");
2094   // First, see what happens to the new class
2095   if (!NewClass->getMemoryLeader()) {
2096     // Should be a new class, or a store becoming a leader of a new class.
2097     assert(NewClass->size() == 1 ||
2098            (isa<StoreInst>(I) && NewClass->getStoreCount() == 1));
2099     NewClass->setMemoryLeader(InstMA);
2100     // Mark it touched if we didn't just create a singleton
2101     DEBUG(dbgs() << "Memory class leader change for class " << NewClass->getID()
2102                  << " due to new memory instruction becoming leader\n");
2103     markMemoryLeaderChangeTouched(NewClass);
2104   }
2105   setMemoryClass(InstMA, NewClass);
2106   // Now, fixup the old class if necessary
2107   if (OldClass->getMemoryLeader() == InstMA) {
2108     if (!OldClass->definesNoMemory()) {
2109       OldClass->setMemoryLeader(getNextMemoryLeader(OldClass));
2110       DEBUG(dbgs() << "Memory class leader change for class "
2111                    << OldClass->getID() << " to "
2112                    << *OldClass->getMemoryLeader()
2113                    << " due to removal of old leader " << *InstMA << "\n");
2114       markMemoryLeaderChangeTouched(OldClass);
2115     } else
2116       OldClass->setMemoryLeader(nullptr);
2117   }
2118 }
2119 
2120 // Move a value, currently in OldClass, to be part of NewClass
2121 // Update OldClass and NewClass for the move (including changing leaders, etc).
2122 void NewGVN::moveValueToNewCongruenceClass(Instruction *I, const Expression *E,
2123                                            CongruenceClass *OldClass,
2124                                            CongruenceClass *NewClass) {
2125   if (I == OldClass->getNextLeader().first)
2126     OldClass->resetNextLeader();
2127 
2128   OldClass->erase(I);
2129   NewClass->insert(I);
2130 
2131   if (NewClass->getLeader() != I)
2132     NewClass->addPossibleNextLeader({I, InstrToDFSNum(I)});
2133   // Handle our special casing of stores.
2134   if (auto *SI = dyn_cast<StoreInst>(I)) {
2135     OldClass->decStoreCount();
2136     // Okay, so when do we want to make a store a leader of a class?
2137     // If we have a store defined by an earlier load, we want the earlier load
2138     // to lead the class.
2139     // If we have a store defined by something else, we want the store to lead
2140     // the class so everything else gets the "something else" as a value.
2141     // If we have a store as the single member of the class, we want the store
2142     // as the leader
2143     if (NewClass->getStoreCount() == 0 && !NewClass->getStoredValue()) {
2144       // If it's a store expression we are using, it means we are not equivalent
2145       // to something earlier.
2146       if (auto *SE = dyn_cast<StoreExpression>(E)) {
2147         NewClass->setStoredValue(SE->getStoredValue());
2148         markValueLeaderChangeTouched(NewClass);
2149         // Shift the new class leader to be the store
2150         DEBUG(dbgs() << "Changing leader of congruence class "
2151                      << NewClass->getID() << " from " << *NewClass->getLeader()
2152                      << " to  " << *SI << " because store joined class\n");
2153         // If we changed the leader, we have to mark it changed because we don't
2154         // know what it will do to symbolic evaluation.
2155         NewClass->setLeader(SI);
2156       }
2157       // We rely on the code below handling the MemoryAccess change.
2158     }
2159     NewClass->incStoreCount();
2160   }
2161   // True if there is no memory instructions left in a class that had memory
2162   // instructions before.
2163 
2164   // If it's not a memory use, set the MemoryAccess equivalence
2165   auto *InstMA = dyn_cast_or_null<MemoryDef>(getMemoryAccess(I));
2166   if (InstMA)
2167     moveMemoryToNewCongruenceClass(I, InstMA, OldClass, NewClass);
2168   ValueToClass[I] = NewClass;
2169   // See if we destroyed the class or need to swap leaders.
2170   if (OldClass->empty() && OldClass != TOPClass) {
2171     if (OldClass->getDefiningExpr()) {
2172       DEBUG(dbgs() << "Erasing expression " << *OldClass->getDefiningExpr()
2173                    << " from table\n");
2174       // We erase it as an exact expression to make sure we don't just erase an
2175       // equivalent one.
2176       auto Iter = ExpressionToClass.find_as(
2177           ExactEqualsExpression(*OldClass->getDefiningExpr()));
2178       if (Iter != ExpressionToClass.end())
2179         ExpressionToClass.erase(Iter);
2180 #ifdef EXPENSIVE_CHECKS
2181       assert(
2182           (*OldClass->getDefiningExpr() != *E || ExpressionToClass.lookup(E)) &&
2183           "We erased the expression we just inserted, which should not happen");
2184 #endif
2185     }
2186   } else if (OldClass->getLeader() == I) {
2187     // When the leader changes, the value numbering of
2188     // everything may change due to symbolization changes, so we need to
2189     // reprocess.
2190     DEBUG(dbgs() << "Value class leader change for class " << OldClass->getID()
2191                  << "\n");
2192     ++NumGVNLeaderChanges;
2193     // Destroy the stored value if there are no more stores to represent it.
2194     // Note that this is basically clean up for the expression removal that
2195     // happens below.  If we remove stores from a class, we may leave it as a
2196     // class of equivalent memory phis.
2197     if (OldClass->getStoreCount() == 0) {
2198       if (OldClass->getStoredValue())
2199         OldClass->setStoredValue(nullptr);
2200     }
2201     OldClass->setLeader(getNextValueLeader(OldClass));
2202     OldClass->resetNextLeader();
2203     markValueLeaderChangeTouched(OldClass);
2204   }
2205 }
2206 
2207 // For a given expression, mark the phi of ops instructions that could have
2208 // changed as a result.
2209 void NewGVN::markPhiOfOpsChanged(const Expression *E) {
2210   touchAndErase(ExpressionToPhiOfOps, ExactEqualsExpression(*E));
2211 }
2212 
2213 // Perform congruence finding on a given value numbering expression.
2214 void NewGVN::performCongruenceFinding(Instruction *I, const Expression *E) {
2215   // This is guaranteed to return something, since it will at least find
2216   // TOP.
2217 
2218   CongruenceClass *IClass = ValueToClass.lookup(I);
2219   assert(IClass && "Should have found a IClass");
2220   // Dead classes should have been eliminated from the mapping.
2221   assert(!IClass->isDead() && "Found a dead class");
2222 
2223   CongruenceClass *EClass = nullptr;
2224   if (const auto *VE = dyn_cast<VariableExpression>(E)) {
2225     EClass = ValueToClass.lookup(VE->getVariableValue());
2226   } else if (isa<DeadExpression>(E)) {
2227     EClass = TOPClass;
2228   }
2229   if (!EClass) {
2230     auto lookupResult = ExpressionToClass.insert({E, nullptr});
2231 
2232     // If it's not in the value table, create a new congruence class.
2233     if (lookupResult.second) {
2234       CongruenceClass *NewClass = createCongruenceClass(nullptr, E);
2235       auto place = lookupResult.first;
2236       place->second = NewClass;
2237 
2238       // Constants and variables should always be made the leader.
2239       if (const auto *CE = dyn_cast<ConstantExpression>(E)) {
2240         NewClass->setLeader(CE->getConstantValue());
2241       } else if (const auto *SE = dyn_cast<StoreExpression>(E)) {
2242         StoreInst *SI = SE->getStoreInst();
2243         NewClass->setLeader(SI);
2244         NewClass->setStoredValue(SE->getStoredValue());
2245         // The RepMemoryAccess field will be filled in properly by the
2246         // moveValueToNewCongruenceClass call.
2247       } else {
2248         NewClass->setLeader(I);
2249       }
2250       assert(!isa<VariableExpression>(E) &&
2251              "VariableExpression should have been handled already");
2252 
2253       EClass = NewClass;
2254       DEBUG(dbgs() << "Created new congruence class for " << *I
2255                    << " using expression " << *E << " at " << NewClass->getID()
2256                    << " and leader " << *(NewClass->getLeader()));
2257       if (NewClass->getStoredValue())
2258         DEBUG(dbgs() << " and stored value " << *(NewClass->getStoredValue()));
2259       DEBUG(dbgs() << "\n");
2260     } else {
2261       EClass = lookupResult.first->second;
2262       if (isa<ConstantExpression>(E))
2263         assert((isa<Constant>(EClass->getLeader()) ||
2264                 (EClass->getStoredValue() &&
2265                  isa<Constant>(EClass->getStoredValue()))) &&
2266                "Any class with a constant expression should have a "
2267                "constant leader");
2268 
2269       assert(EClass && "Somehow don't have an eclass");
2270 
2271       assert(!EClass->isDead() && "We accidentally looked up a dead class");
2272     }
2273   }
2274   bool ClassChanged = IClass != EClass;
2275   bool LeaderChanged = LeaderChanges.erase(I);
2276   if (ClassChanged || LeaderChanged) {
2277     DEBUG(dbgs() << "New class " << EClass->getID() << " for expression " << *E
2278                  << "\n");
2279     if (ClassChanged) {
2280       moveValueToNewCongruenceClass(I, E, IClass, EClass);
2281       markPhiOfOpsChanged(E);
2282     }
2283 
2284     markUsersTouched(I);
2285     if (MemoryAccess *MA = getMemoryAccess(I))
2286       markMemoryUsersTouched(MA);
2287     if (auto *CI = dyn_cast<CmpInst>(I))
2288       markPredicateUsersTouched(CI);
2289   }
2290   // If we changed the class of the store, we want to ensure nothing finds the
2291   // old store expression.  In particular, loads do not compare against stored
2292   // value, so they will find old store expressions (and associated class
2293   // mappings) if we leave them in the table.
2294   if (ClassChanged && isa<StoreInst>(I)) {
2295     auto *OldE = ValueToExpression.lookup(I);
2296     // It could just be that the old class died. We don't want to erase it if we
2297     // just moved classes.
2298     if (OldE && isa<StoreExpression>(OldE) && *E != *OldE) {
2299       // Erase this as an exact expression to ensure we don't erase expressions
2300       // equivalent to it.
2301       auto Iter = ExpressionToClass.find_as(ExactEqualsExpression(*OldE));
2302       if (Iter != ExpressionToClass.end())
2303         ExpressionToClass.erase(Iter);
2304     }
2305   }
2306   ValueToExpression[I] = E;
2307 }
2308 
2309 // Process the fact that Edge (from, to) is reachable, including marking
2310 // any newly reachable blocks and instructions for processing.
2311 void NewGVN::updateReachableEdge(BasicBlock *From, BasicBlock *To) {
2312   // Check if the Edge was reachable before.
2313   if (ReachableEdges.insert({From, To}).second) {
2314     // If this block wasn't reachable before, all instructions are touched.
2315     if (ReachableBlocks.insert(To).second) {
2316       DEBUG(dbgs() << "Block " << getBlockName(To) << " marked reachable\n");
2317       const auto &InstRange = BlockInstRange.lookup(To);
2318       TouchedInstructions.set(InstRange.first, InstRange.second);
2319     } else {
2320       DEBUG(dbgs() << "Block " << getBlockName(To)
2321                    << " was reachable, but new edge {" << getBlockName(From)
2322                    << "," << getBlockName(To) << "} to it found\n");
2323 
2324       // We've made an edge reachable to an existing block, which may
2325       // impact predicates. Otherwise, only mark the phi nodes as touched, as
2326       // they are the only thing that depend on new edges. Anything using their
2327       // values will get propagated to if necessary.
2328       if (MemoryAccess *MemPhi = getMemoryAccess(To))
2329         TouchedInstructions.set(InstrToDFSNum(MemPhi));
2330 
2331       auto BI = To->begin();
2332       while (isa<PHINode>(BI)) {
2333         TouchedInstructions.set(InstrToDFSNum(&*BI));
2334         ++BI;
2335       }
2336       for_each_found(PHIOfOpsPHIs, To, [&](const PHINode *I) {
2337         TouchedInstructions.set(InstrToDFSNum(I));
2338       });
2339     }
2340   }
2341 }
2342 
2343 // Given a predicate condition (from a switch, cmp, or whatever) and a block,
2344 // see if we know some constant value for it already.
2345 Value *NewGVN::findConditionEquivalence(Value *Cond) const {
2346   auto Result = lookupOperandLeader(Cond);
2347   return isa<Constant>(Result) ? Result : nullptr;
2348 }
2349 
2350 // Process the outgoing edges of a block for reachability.
2351 void NewGVN::processOutgoingEdges(TerminatorInst *TI, BasicBlock *B) {
2352   // Evaluate reachability of terminator instruction.
2353   BranchInst *BR;
2354   if ((BR = dyn_cast<BranchInst>(TI)) && BR->isConditional()) {
2355     Value *Cond = BR->getCondition();
2356     Value *CondEvaluated = findConditionEquivalence(Cond);
2357     if (!CondEvaluated) {
2358       if (auto *I = dyn_cast<Instruction>(Cond)) {
2359         const Expression *E = createExpression(I);
2360         if (const auto *CE = dyn_cast<ConstantExpression>(E)) {
2361           CondEvaluated = CE->getConstantValue();
2362         }
2363       } else if (isa<ConstantInt>(Cond)) {
2364         CondEvaluated = Cond;
2365       }
2366     }
2367     ConstantInt *CI;
2368     BasicBlock *TrueSucc = BR->getSuccessor(0);
2369     BasicBlock *FalseSucc = BR->getSuccessor(1);
2370     if (CondEvaluated && (CI = dyn_cast<ConstantInt>(CondEvaluated))) {
2371       if (CI->isOne()) {
2372         DEBUG(dbgs() << "Condition for Terminator " << *TI
2373                      << " evaluated to true\n");
2374         updateReachableEdge(B, TrueSucc);
2375       } else if (CI->isZero()) {
2376         DEBUG(dbgs() << "Condition for Terminator " << *TI
2377                      << " evaluated to false\n");
2378         updateReachableEdge(B, FalseSucc);
2379       }
2380     } else {
2381       updateReachableEdge(B, TrueSucc);
2382       updateReachableEdge(B, FalseSucc);
2383     }
2384   } else if (auto *SI = dyn_cast<SwitchInst>(TI)) {
2385     // For switches, propagate the case values into the case
2386     // destinations.
2387 
2388     // Remember how many outgoing edges there are to every successor.
2389     SmallDenseMap<BasicBlock *, unsigned, 16> SwitchEdges;
2390 
2391     Value *SwitchCond = SI->getCondition();
2392     Value *CondEvaluated = findConditionEquivalence(SwitchCond);
2393     // See if we were able to turn this switch statement into a constant.
2394     if (CondEvaluated && isa<ConstantInt>(CondEvaluated)) {
2395       auto *CondVal = cast<ConstantInt>(CondEvaluated);
2396       // We should be able to get case value for this.
2397       auto Case = *SI->findCaseValue(CondVal);
2398       if (Case.getCaseSuccessor() == SI->getDefaultDest()) {
2399         // We proved the value is outside of the range of the case.
2400         // We can't do anything other than mark the default dest as reachable,
2401         // and go home.
2402         updateReachableEdge(B, SI->getDefaultDest());
2403         return;
2404       }
2405       // Now get where it goes and mark it reachable.
2406       BasicBlock *TargetBlock = Case.getCaseSuccessor();
2407       updateReachableEdge(B, TargetBlock);
2408     } else {
2409       for (unsigned i = 0, e = SI->getNumSuccessors(); i != e; ++i) {
2410         BasicBlock *TargetBlock = SI->getSuccessor(i);
2411         ++SwitchEdges[TargetBlock];
2412         updateReachableEdge(B, TargetBlock);
2413       }
2414     }
2415   } else {
2416     // Otherwise this is either unconditional, or a type we have no
2417     // idea about. Just mark successors as reachable.
2418     for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
2419       BasicBlock *TargetBlock = TI->getSuccessor(i);
2420       updateReachableEdge(B, TargetBlock);
2421     }
2422 
2423     // This also may be a memory defining terminator, in which case, set it
2424     // equivalent only to itself.
2425     //
2426     auto *MA = getMemoryAccess(TI);
2427     if (MA && !isa<MemoryUse>(MA)) {
2428       auto *CC = ensureLeaderOfMemoryClass(MA);
2429       if (setMemoryClass(MA, CC))
2430         markMemoryUsersTouched(MA);
2431     }
2432   }
2433 }
2434 
2435 // Remove the PHI of Ops PHI for I
2436 void NewGVN::removePhiOfOps(Instruction *I, PHINode *PHITemp) {
2437   InstrDFS.erase(PHITemp);
2438   // It's still a temp instruction. We keep it in the array so it gets erased.
2439   // However, it's no longer used by I, or in the block/
2440   PHIOfOpsPHIs[getBlockForValue(PHITemp)].erase(PHITemp);
2441   TempToBlock.erase(PHITemp);
2442   RealToTemp.erase(I);
2443 }
2444 
2445 // Add PHI Op in BB as a PHI of operations version of ExistingValue.
2446 void NewGVN::addPhiOfOps(PHINode *Op, BasicBlock *BB,
2447                          Instruction *ExistingValue) {
2448   InstrDFS[Op] = InstrToDFSNum(ExistingValue);
2449   AllTempInstructions.insert(Op);
2450   PHIOfOpsPHIs[BB].insert(Op);
2451   TempToBlock[Op] = BB;
2452   RealToTemp[ExistingValue] = Op;
2453 }
2454 
2455 static bool okayForPHIOfOps(const Instruction *I) {
2456   if (!EnablePhiOfOps)
2457     return false;
2458   return isa<BinaryOperator>(I) || isa<SelectInst>(I) || isa<CmpInst>(I) ||
2459          isa<LoadInst>(I);
2460 }
2461 
2462 // When we see an instruction that is an op of phis, generate the equivalent phi
2463 // of ops form.
2464 const Expression *
2465 NewGVN::makePossiblePhiOfOps(Instruction *I,
2466                              SmallPtrSetImpl<Value *> &Visited) {
2467   if (!okayForPHIOfOps(I))
2468     return nullptr;
2469 
2470   if (!Visited.insert(I).second)
2471     return nullptr;
2472   // For now, we require the instruction be cycle free because we don't
2473   // *always* create a phi of ops for instructions that could be done as phi
2474   // of ops, we only do it if we think it is useful.  If we did do it all the
2475   // time, we could remove the cycle free check.
2476   if (!isCycleFree(I))
2477     return nullptr;
2478 
2479   unsigned IDFSNum = InstrToDFSNum(I);
2480   SmallPtrSet<const Value *, 8> ProcessedPHIs;
2481   // TODO: We don't do phi translation on memory accesses because it's
2482   // complicated. For a load, we'd need to be able to simulate a new memoryuse,
2483   // which we don't have a good way of doing ATM.
2484   auto *MemAccess = getMemoryAccess(I);
2485   // If the memory operation is defined by a memory operation this block that
2486   // isn't a MemoryPhi, transforming the pointer backwards through a scalar phi
2487   // can't help, as it would still be killed by that memory operation.
2488   if (MemAccess && !isa<MemoryPhi>(MemAccess->getDefiningAccess()) &&
2489       MemAccess->getDefiningAccess()->getBlock() == I->getParent())
2490     return nullptr;
2491 
2492   // Convert op of phis to phi of ops
2493   for (auto &Op : I->operands()) {
2494     // TODO: We can't handle expressions that must be recursively translated
2495     // IE
2496     // a = phi (b, c)
2497     // f = use a
2498     // g = f + phi of something
2499     // To properly make a phi of ops for g, we'd have to properly translate and
2500     // use the instruction for f.  We should add this by splitting out the
2501     // instruction creation we do below.
2502     if (isa<Instruction>(Op) && PHINodeUses.count(cast<Instruction>(Op)))
2503       return nullptr;
2504     if (!isa<PHINode>(Op))
2505       continue;
2506     auto *OpPHI = cast<PHINode>(Op);
2507     // No point in doing this for one-operand phis.
2508     if (OpPHI->getNumOperands() == 1)
2509       continue;
2510     if (!DebugCounter::shouldExecute(PHIOfOpsCounter))
2511       return nullptr;
2512     SmallVector<std::pair<Value *, BasicBlock *>, 4> Ops;
2513     auto *PHIBlock = getBlockForValue(OpPHI);
2514     for (auto PredBB : OpPHI->blocks()) {
2515       Value *FoundVal = nullptr;
2516       // We could just skip unreachable edges entirely but it's tricky to do
2517       // with rewriting existing phi nodes.
2518       if (ReachableEdges.count({PredBB, PHIBlock})) {
2519         // Clone the instruction, create an expression from it, and see if we
2520         // have a leader.
2521         Instruction *ValueOp = I->clone();
2522         if (MemAccess)
2523           TempToMemory.insert({ValueOp, MemAccess});
2524 
2525         for (auto &Op : ValueOp->operands()) {
2526           Op = Op->DoPHITranslation(PHIBlock, PredBB);
2527           // When this operand changes, it could change whether there is a
2528           // leader for us or not.
2529           addAdditionalUsers(Op, I);
2530         }
2531         // Make sure it's marked as a temporary instruction.
2532         AllTempInstructions.insert(ValueOp);
2533         // and make sure anything that tries to add it's DFS number is
2534         // redirected to the instruction we are making a phi of ops
2535         // for.
2536         InstrDFS.insert({ValueOp, IDFSNum});
2537         const Expression *E = performSymbolicEvaluation(ValueOp, Visited);
2538         InstrDFS.erase(ValueOp);
2539         AllTempInstructions.erase(ValueOp);
2540         ValueOp->deleteValue();
2541         if (MemAccess)
2542           TempToMemory.erase(ValueOp);
2543         if (!E)
2544           return nullptr;
2545         FoundVal = findPhiOfOpsLeader(E, PredBB);
2546         if (!FoundVal) {
2547           ExpressionToPhiOfOps[E].insert(I);
2548           return nullptr;
2549         }
2550         if (auto *SI = dyn_cast<StoreInst>(FoundVal))
2551           FoundVal = SI->getValueOperand();
2552       } else {
2553         DEBUG(dbgs() << "Skipping phi of ops operand for incoming block "
2554                      << getBlockName(PredBB)
2555                      << " because the block is unreachable\n");
2556         FoundVal = UndefValue::get(I->getType());
2557       }
2558 
2559       Ops.push_back({FoundVal, PredBB});
2560       DEBUG(dbgs() << "Found phi of ops operand " << *FoundVal << " in "
2561                    << getBlockName(PredBB) << "\n");
2562     }
2563     auto *ValuePHI = RealToTemp.lookup(I);
2564     bool NewPHI = false;
2565     if (!ValuePHI) {
2566       ValuePHI = PHINode::Create(I->getType(), OpPHI->getNumOperands());
2567       addPhiOfOps(ValuePHI, PHIBlock, I);
2568       NewPHI = true;
2569       NumGVNPHIOfOpsCreated++;
2570     }
2571     if (NewPHI) {
2572       for (auto PHIOp : Ops)
2573         ValuePHI->addIncoming(PHIOp.first, PHIOp.second);
2574     } else {
2575       unsigned int i = 0;
2576       for (auto PHIOp : Ops) {
2577         ValuePHI->setIncomingValue(i, PHIOp.first);
2578         ValuePHI->setIncomingBlock(i, PHIOp.second);
2579         ++i;
2580       }
2581     }
2582 
2583     DEBUG(dbgs() << "Created phi of ops " << *ValuePHI << " for " << *I
2584                  << "\n");
2585     return performSymbolicEvaluation(ValuePHI, Visited);
2586   }
2587   return nullptr;
2588 }
2589 
2590 // The algorithm initially places the values of the routine in the TOP
2591 // congruence class. The leader of TOP is the undetermined value `undef`.
2592 // When the algorithm has finished, values still in TOP are unreachable.
2593 void NewGVN::initializeCongruenceClasses(Function &F) {
2594   NextCongruenceNum = 0;
2595 
2596   // Note that even though we use the live on entry def as a representative
2597   // MemoryAccess, it is *not* the same as the actual live on entry def. We
2598   // have no real equivalemnt to undef for MemoryAccesses, and so we really
2599   // should be checking whether the MemoryAccess is top if we want to know if it
2600   // is equivalent to everything.  Otherwise, what this really signifies is that
2601   // the access "it reaches all the way back to the beginning of the function"
2602 
2603   // Initialize all other instructions to be in TOP class.
2604   TOPClass = createCongruenceClass(nullptr, nullptr);
2605   TOPClass->setMemoryLeader(MSSA->getLiveOnEntryDef());
2606   //  The live on entry def gets put into it's own class
2607   MemoryAccessToClass[MSSA->getLiveOnEntryDef()] =
2608       createMemoryClass(MSSA->getLiveOnEntryDef());
2609 
2610   for (auto DTN : nodes(DT)) {
2611     BasicBlock *BB = DTN->getBlock();
2612     // All MemoryAccesses are equivalent to live on entry to start. They must
2613     // be initialized to something so that initial changes are noticed. For
2614     // the maximal answer, we initialize them all to be the same as
2615     // liveOnEntry.
2616     auto *MemoryBlockDefs = MSSA->getBlockDefs(BB);
2617     if (MemoryBlockDefs)
2618       for (const auto &Def : *MemoryBlockDefs) {
2619         MemoryAccessToClass[&Def] = TOPClass;
2620         auto *MD = dyn_cast<MemoryDef>(&Def);
2621         // Insert the memory phis into the member list.
2622         if (!MD) {
2623           const MemoryPhi *MP = cast<MemoryPhi>(&Def);
2624           TOPClass->memory_insert(MP);
2625           MemoryPhiState.insert({MP, MPS_TOP});
2626         }
2627 
2628         if (MD && isa<StoreInst>(MD->getMemoryInst()))
2629           TOPClass->incStoreCount();
2630       }
2631     for (auto &I : *BB) {
2632       // TODO: Move to helper
2633       if (isa<PHINode>(&I))
2634         for (auto *U : I.users())
2635           if (auto *UInst = dyn_cast<Instruction>(U))
2636             if (InstrToDFSNum(UInst) != 0 && okayForPHIOfOps(UInst))
2637               PHINodeUses.insert(UInst);
2638       // Don't insert void terminators into the class. We don't value number
2639       // them, and they just end up sitting in TOP.
2640       if (isa<TerminatorInst>(I) && I.getType()->isVoidTy())
2641         continue;
2642       TOPClass->insert(&I);
2643       ValueToClass[&I] = TOPClass;
2644     }
2645   }
2646 
2647   // Initialize arguments to be in their own unique congruence classes
2648   for (auto &FA : F.args())
2649     createSingletonCongruenceClass(&FA);
2650 }
2651 
2652 void NewGVN::cleanupTables() {
2653   for (unsigned i = 0, e = CongruenceClasses.size(); i != e; ++i) {
2654     DEBUG(dbgs() << "Congruence class " << CongruenceClasses[i]->getID()
2655                  << " has " << CongruenceClasses[i]->size() << " members\n");
2656     // Make sure we delete the congruence class (probably worth switching to
2657     // a unique_ptr at some point.
2658     delete CongruenceClasses[i];
2659     CongruenceClasses[i] = nullptr;
2660   }
2661 
2662   // Destroy the value expressions
2663   SmallVector<Instruction *, 8> TempInst(AllTempInstructions.begin(),
2664                                          AllTempInstructions.end());
2665   AllTempInstructions.clear();
2666 
2667   // We have to drop all references for everything first, so there are no uses
2668   // left as we delete them.
2669   for (auto *I : TempInst) {
2670     I->dropAllReferences();
2671   }
2672 
2673   while (!TempInst.empty()) {
2674     auto *I = TempInst.back();
2675     TempInst.pop_back();
2676     I->deleteValue();
2677   }
2678 
2679   ValueToClass.clear();
2680   ArgRecycler.clear(ExpressionAllocator);
2681   ExpressionAllocator.Reset();
2682   CongruenceClasses.clear();
2683   ExpressionToClass.clear();
2684   ValueToExpression.clear();
2685   RealToTemp.clear();
2686   AdditionalUsers.clear();
2687   ExpressionToPhiOfOps.clear();
2688   TempToBlock.clear();
2689   TempToMemory.clear();
2690   PHIOfOpsPHIs.clear();
2691   ReachableBlocks.clear();
2692   ReachableEdges.clear();
2693 #ifndef NDEBUG
2694   ProcessedCount.clear();
2695 #endif
2696   InstrDFS.clear();
2697   InstructionsToErase.clear();
2698   DFSToInstr.clear();
2699   BlockInstRange.clear();
2700   TouchedInstructions.clear();
2701   MemoryAccessToClass.clear();
2702   PredicateToUsers.clear();
2703   MemoryToUsers.clear();
2704 }
2705 
2706 // Assign local DFS number mapping to instructions, and leave space for Value
2707 // PHI's.
2708 std::pair<unsigned, unsigned> NewGVN::assignDFSNumbers(BasicBlock *B,
2709                                                        unsigned Start) {
2710   unsigned End = Start;
2711   if (MemoryAccess *MemPhi = getMemoryAccess(B)) {
2712     InstrDFS[MemPhi] = End++;
2713     DFSToInstr.emplace_back(MemPhi);
2714   }
2715 
2716   // Then the real block goes next.
2717   for (auto &I : *B) {
2718     // There's no need to call isInstructionTriviallyDead more than once on
2719     // an instruction. Therefore, once we know that an instruction is dead
2720     // we change its DFS number so that it doesn't get value numbered.
2721     if (isInstructionTriviallyDead(&I, TLI)) {
2722       InstrDFS[&I] = 0;
2723       DEBUG(dbgs() << "Skipping trivially dead instruction " << I << "\n");
2724       markInstructionForDeletion(&I);
2725       continue;
2726     }
2727     InstrDFS[&I] = End++;
2728     DFSToInstr.emplace_back(&I);
2729   }
2730 
2731   // All of the range functions taken half-open ranges (open on the end side).
2732   // So we do not subtract one from count, because at this point it is one
2733   // greater than the last instruction.
2734   return std::make_pair(Start, End);
2735 }
2736 
2737 void NewGVN::updateProcessedCount(const Value *V) {
2738 #ifndef NDEBUG
2739   if (ProcessedCount.count(V) == 0) {
2740     ProcessedCount.insert({V, 1});
2741   } else {
2742     ++ProcessedCount[V];
2743     assert(ProcessedCount[V] < 100 &&
2744            "Seem to have processed the same Value a lot");
2745   }
2746 #endif
2747 }
2748 // Evaluate MemoryPhi nodes symbolically, just like PHI nodes
2749 void NewGVN::valueNumberMemoryPhi(MemoryPhi *MP) {
2750   // If all the arguments are the same, the MemoryPhi has the same value as the
2751   // argument.  Filter out unreachable blocks and self phis from our operands.
2752   // TODO: We could do cycle-checking on the memory phis to allow valueizing for
2753   // self-phi checking.
2754   const BasicBlock *PHIBlock = MP->getBlock();
2755   auto Filtered = make_filter_range(MP->operands(), [&](const Use &U) {
2756     return cast<MemoryAccess>(U) != MP &&
2757            !isMemoryAccessTOP(cast<MemoryAccess>(U)) &&
2758            ReachableEdges.count({MP->getIncomingBlock(U), PHIBlock});
2759   });
2760   // If all that is left is nothing, our memoryphi is undef. We keep it as
2761   // InitialClass.  Note: The only case this should happen is if we have at
2762   // least one self-argument.
2763   if (Filtered.begin() == Filtered.end()) {
2764     if (setMemoryClass(MP, TOPClass))
2765       markMemoryUsersTouched(MP);
2766     return;
2767   }
2768 
2769   // Transform the remaining operands into operand leaders.
2770   // FIXME: mapped_iterator should have a range version.
2771   auto LookupFunc = [&](const Use &U) {
2772     return lookupMemoryLeader(cast<MemoryAccess>(U));
2773   };
2774   auto MappedBegin = map_iterator(Filtered.begin(), LookupFunc);
2775   auto MappedEnd = map_iterator(Filtered.end(), LookupFunc);
2776 
2777   // and now check if all the elements are equal.
2778   // Sadly, we can't use std::equals since these are random access iterators.
2779   const auto *AllSameValue = *MappedBegin;
2780   ++MappedBegin;
2781   bool AllEqual = std::all_of(
2782       MappedBegin, MappedEnd,
2783       [&AllSameValue](const MemoryAccess *V) { return V == AllSameValue; });
2784 
2785   if (AllEqual)
2786     DEBUG(dbgs() << "Memory Phi value numbered to " << *AllSameValue << "\n");
2787   else
2788     DEBUG(dbgs() << "Memory Phi value numbered to itself\n");
2789   // If it's equal to something, it's in that class. Otherwise, it has to be in
2790   // a class where it is the leader (other things may be equivalent to it, but
2791   // it needs to start off in its own class, which means it must have been the
2792   // leader, and it can't have stopped being the leader because it was never
2793   // removed).
2794   CongruenceClass *CC =
2795       AllEqual ? getMemoryClass(AllSameValue) : ensureLeaderOfMemoryClass(MP);
2796   auto OldState = MemoryPhiState.lookup(MP);
2797   assert(OldState != MPS_Invalid && "Invalid memory phi state");
2798   auto NewState = AllEqual ? MPS_Equivalent : MPS_Unique;
2799   MemoryPhiState[MP] = NewState;
2800   if (setMemoryClass(MP, CC) || OldState != NewState)
2801     markMemoryUsersTouched(MP);
2802 }
2803 
2804 // Value number a single instruction, symbolically evaluating, performing
2805 // congruence finding, and updating mappings.
2806 void NewGVN::valueNumberInstruction(Instruction *I) {
2807   DEBUG(dbgs() << "Processing instruction " << *I << "\n");
2808   if (!I->isTerminator()) {
2809     const Expression *Symbolized = nullptr;
2810     SmallPtrSet<Value *, 2> Visited;
2811     if (DebugCounter::shouldExecute(VNCounter)) {
2812       Symbolized = performSymbolicEvaluation(I, Visited);
2813       // Make a phi of ops if necessary
2814       if (Symbolized && !isa<ConstantExpression>(Symbolized) &&
2815           !isa<VariableExpression>(Symbolized) && PHINodeUses.count(I)) {
2816         auto *PHIE = makePossiblePhiOfOps(I, Visited);
2817         // If we created a phi of ops, use it.
2818         // If we couldn't create one, make sure we don't leave one lying around
2819         if (PHIE) {
2820           Symbolized = PHIE;
2821         } else if (auto *Op = RealToTemp.lookup(I)) {
2822           removePhiOfOps(I, Op);
2823         }
2824       }
2825 
2826     } else {
2827       // Mark the instruction as unused so we don't value number it again.
2828       InstrDFS[I] = 0;
2829     }
2830     // If we couldn't come up with a symbolic expression, use the unknown
2831     // expression
2832     if (Symbolized == nullptr)
2833       Symbolized = createUnknownExpression(I);
2834     performCongruenceFinding(I, Symbolized);
2835   } else {
2836     // Handle terminators that return values. All of them produce values we
2837     // don't currently understand.  We don't place non-value producing
2838     // terminators in a class.
2839     if (!I->getType()->isVoidTy()) {
2840       auto *Symbolized = createUnknownExpression(I);
2841       performCongruenceFinding(I, Symbolized);
2842     }
2843     processOutgoingEdges(dyn_cast<TerminatorInst>(I), I->getParent());
2844   }
2845 }
2846 
2847 // Check if there is a path, using single or equal argument phi nodes, from
2848 // First to Second.
2849 bool NewGVN::singleReachablePHIPath(
2850     SmallPtrSet<const MemoryAccess *, 8> &Visited, const MemoryAccess *First,
2851     const MemoryAccess *Second) const {
2852   if (First == Second)
2853     return true;
2854   if (MSSA->isLiveOnEntryDef(First))
2855     return false;
2856 
2857   // This is not perfect, but as we're just verifying here, we can live with
2858   // the loss of precision. The real solution would be that of doing strongly
2859   // connected component finding in this routine, and it's probably not worth
2860   // the complexity for the time being. So, we just keep a set of visited
2861   // MemoryAccess and return true when we hit a cycle.
2862   if (Visited.count(First))
2863     return true;
2864   Visited.insert(First);
2865 
2866   const auto *EndDef = First;
2867   for (auto *ChainDef : optimized_def_chain(First)) {
2868     if (ChainDef == Second)
2869       return true;
2870     if (MSSA->isLiveOnEntryDef(ChainDef))
2871       return false;
2872     EndDef = ChainDef;
2873   }
2874   auto *MP = cast<MemoryPhi>(EndDef);
2875   auto ReachableOperandPred = [&](const Use &U) {
2876     return ReachableEdges.count({MP->getIncomingBlock(U), MP->getBlock()});
2877   };
2878   auto FilteredPhiArgs =
2879       make_filter_range(MP->operands(), ReachableOperandPred);
2880   SmallVector<const Value *, 32> OperandList;
2881   std::copy(FilteredPhiArgs.begin(), FilteredPhiArgs.end(),
2882             std::back_inserter(OperandList));
2883   bool Okay = OperandList.size() == 1;
2884   if (!Okay)
2885     Okay =
2886         std::equal(OperandList.begin(), OperandList.end(), OperandList.begin());
2887   if (Okay)
2888     return singleReachablePHIPath(Visited, cast<MemoryAccess>(OperandList[0]),
2889                                   Second);
2890   return false;
2891 }
2892 
2893 // Verify the that the memory equivalence table makes sense relative to the
2894 // congruence classes.  Note that this checking is not perfect, and is currently
2895 // subject to very rare false negatives. It is only useful for
2896 // testing/debugging.
2897 void NewGVN::verifyMemoryCongruency() const {
2898 #ifndef NDEBUG
2899   // Verify that the memory table equivalence and memory member set match
2900   for (const auto *CC : CongruenceClasses) {
2901     if (CC == TOPClass || CC->isDead())
2902       continue;
2903     if (CC->getStoreCount() != 0) {
2904       assert((CC->getStoredValue() || !isa<StoreInst>(CC->getLeader())) &&
2905              "Any class with a store as a leader should have a "
2906              "representative stored value");
2907       assert(CC->getMemoryLeader() &&
2908              "Any congruence class with a store should have a "
2909              "representative access");
2910     }
2911 
2912     if (CC->getMemoryLeader())
2913       assert(MemoryAccessToClass.lookup(CC->getMemoryLeader()) == CC &&
2914              "Representative MemoryAccess does not appear to be reverse "
2915              "mapped properly");
2916     for (auto M : CC->memory())
2917       assert(MemoryAccessToClass.lookup(M) == CC &&
2918              "Memory member does not appear to be reverse mapped properly");
2919   }
2920 
2921   // Anything equivalent in the MemoryAccess table should be in the same
2922   // congruence class.
2923 
2924   // Filter out the unreachable and trivially dead entries, because they may
2925   // never have been updated if the instructions were not processed.
2926   auto ReachableAccessPred =
2927       [&](const std::pair<const MemoryAccess *, CongruenceClass *> Pair) {
2928         bool Result = ReachableBlocks.count(Pair.first->getBlock());
2929         if (!Result || MSSA->isLiveOnEntryDef(Pair.first) ||
2930             MemoryToDFSNum(Pair.first) == 0)
2931           return false;
2932         if (auto *MemDef = dyn_cast<MemoryDef>(Pair.first))
2933           return !isInstructionTriviallyDead(MemDef->getMemoryInst());
2934 
2935         // We could have phi nodes which operands are all trivially dead,
2936         // so we don't process them.
2937         if (auto *MemPHI = dyn_cast<MemoryPhi>(Pair.first)) {
2938           for (auto &U : MemPHI->incoming_values()) {
2939             if (Instruction *I = dyn_cast<Instruction>(U.get())) {
2940               if (!isInstructionTriviallyDead(I))
2941                 return true;
2942             }
2943           }
2944           return false;
2945         }
2946 
2947         return true;
2948       };
2949 
2950   auto Filtered = make_filter_range(MemoryAccessToClass, ReachableAccessPred);
2951   for (auto KV : Filtered) {
2952     if (auto *FirstMUD = dyn_cast<MemoryUseOrDef>(KV.first)) {
2953       auto *SecondMUD = dyn_cast<MemoryUseOrDef>(KV.second->getMemoryLeader());
2954       if (FirstMUD && SecondMUD) {
2955         SmallPtrSet<const MemoryAccess *, 8> VisitedMAS;
2956         assert((singleReachablePHIPath(VisitedMAS, FirstMUD, SecondMUD) ||
2957                 ValueToClass.lookup(FirstMUD->getMemoryInst()) ==
2958                     ValueToClass.lookup(SecondMUD->getMemoryInst())) &&
2959                "The instructions for these memory operations should have "
2960                "been in the same congruence class or reachable through"
2961                "a single argument phi");
2962       }
2963     } else if (auto *FirstMP = dyn_cast<MemoryPhi>(KV.first)) {
2964       // We can only sanely verify that MemoryDefs in the operand list all have
2965       // the same class.
2966       auto ReachableOperandPred = [&](const Use &U) {
2967         return ReachableEdges.count(
2968                    {FirstMP->getIncomingBlock(U), FirstMP->getBlock()}) &&
2969                isa<MemoryDef>(U);
2970 
2971       };
2972       // All arguments should in the same class, ignoring unreachable arguments
2973       auto FilteredPhiArgs =
2974           make_filter_range(FirstMP->operands(), ReachableOperandPred);
2975       SmallVector<const CongruenceClass *, 16> PhiOpClasses;
2976       std::transform(FilteredPhiArgs.begin(), FilteredPhiArgs.end(),
2977                      std::back_inserter(PhiOpClasses), [&](const Use &U) {
2978                        const MemoryDef *MD = cast<MemoryDef>(U);
2979                        return ValueToClass.lookup(MD->getMemoryInst());
2980                      });
2981       assert(std::equal(PhiOpClasses.begin(), PhiOpClasses.end(),
2982                         PhiOpClasses.begin()) &&
2983              "All MemoryPhi arguments should be in the same class");
2984     }
2985   }
2986 #endif
2987 }
2988 
2989 // Verify that the sparse propagation we did actually found the maximal fixpoint
2990 // We do this by storing the value to class mapping, touching all instructions,
2991 // and redoing the iteration to see if anything changed.
2992 void NewGVN::verifyIterationSettled(Function &F) {
2993 #ifndef NDEBUG
2994   DEBUG(dbgs() << "Beginning iteration verification\n");
2995   if (DebugCounter::isCounterSet(VNCounter))
2996     DebugCounter::setCounterValue(VNCounter, StartingVNCounter);
2997 
2998   // Note that we have to store the actual classes, as we may change existing
2999   // classes during iteration.  This is because our memory iteration propagation
3000   // is not perfect, and so may waste a little work.  But it should generate
3001   // exactly the same congruence classes we have now, with different IDs.
3002   std::map<const Value *, CongruenceClass> BeforeIteration;
3003 
3004   for (auto &KV : ValueToClass) {
3005     if (auto *I = dyn_cast<Instruction>(KV.first))
3006       // Skip unused/dead instructions.
3007       if (InstrToDFSNum(I) == 0)
3008         continue;
3009     BeforeIteration.insert({KV.first, *KV.second});
3010   }
3011 
3012   TouchedInstructions.set();
3013   TouchedInstructions.reset(0);
3014   iterateTouchedInstructions();
3015   DenseSet<std::pair<const CongruenceClass *, const CongruenceClass *>>
3016       EqualClasses;
3017   for (const auto &KV : ValueToClass) {
3018     if (auto *I = dyn_cast<Instruction>(KV.first))
3019       // Skip unused/dead instructions.
3020       if (InstrToDFSNum(I) == 0)
3021         continue;
3022     // We could sink these uses, but i think this adds a bit of clarity here as
3023     // to what we are comparing.
3024     auto *BeforeCC = &BeforeIteration.find(KV.first)->second;
3025     auto *AfterCC = KV.second;
3026     // Note that the classes can't change at this point, so we memoize the set
3027     // that are equal.
3028     if (!EqualClasses.count({BeforeCC, AfterCC})) {
3029       assert(BeforeCC->isEquivalentTo(AfterCC) &&
3030              "Value number changed after main loop completed!");
3031       EqualClasses.insert({BeforeCC, AfterCC});
3032     }
3033   }
3034 #endif
3035 }
3036 
3037 // Verify that for each store expression in the expression to class mapping,
3038 // only the latest appears, and multiple ones do not appear.
3039 // Because loads do not use the stored value when doing equality with stores,
3040 // if we don't erase the old store expressions from the table, a load can find
3041 // a no-longer valid StoreExpression.
3042 void NewGVN::verifyStoreExpressions() const {
3043 #ifndef NDEBUG
3044   // This is the only use of this, and it's not worth defining a complicated
3045   // densemapinfo hash/equality function for it.
3046   std::set<
3047       std::pair<const Value *,
3048                 std::tuple<const Value *, const CongruenceClass *, Value *>>>
3049       StoreExpressionSet;
3050   for (const auto &KV : ExpressionToClass) {
3051     if (auto *SE = dyn_cast<StoreExpression>(KV.first)) {
3052       // Make sure a version that will conflict with loads is not already there
3053       auto Res = StoreExpressionSet.insert(
3054           {SE->getOperand(0), std::make_tuple(SE->getMemoryLeader(), KV.second,
3055                                               SE->getStoredValue())});
3056       bool Okay = Res.second;
3057       // It's okay to have the same expression already in there if it is
3058       // identical in nature.
3059       // This can happen when the leader of the stored value changes over time.
3060       if (!Okay)
3061         Okay = (std::get<1>(Res.first->second) == KV.second) &&
3062                (lookupOperandLeader(std::get<2>(Res.first->second)) ==
3063                 lookupOperandLeader(SE->getStoredValue()));
3064       assert(Okay && "Stored expression conflict exists in expression table");
3065       auto *ValueExpr = ValueToExpression.lookup(SE->getStoreInst());
3066       assert(ValueExpr && ValueExpr->equals(*SE) &&
3067              "StoreExpression in ExpressionToClass is not latest "
3068              "StoreExpression for value");
3069     }
3070   }
3071 #endif
3072 }
3073 
3074 // This is the main value numbering loop, it iterates over the initial touched
3075 // instruction set, propagating value numbers, marking things touched, etc,
3076 // until the set of touched instructions is completely empty.
3077 void NewGVN::iterateTouchedInstructions() {
3078   unsigned int Iterations = 0;
3079   // Figure out where touchedinstructions starts
3080   int FirstInstr = TouchedInstructions.find_first();
3081   // Nothing set, nothing to iterate, just return.
3082   if (FirstInstr == -1)
3083     return;
3084   const BasicBlock *LastBlock = getBlockForValue(InstrFromDFSNum(FirstInstr));
3085   while (TouchedInstructions.any()) {
3086     ++Iterations;
3087     // Walk through all the instructions in all the blocks in RPO.
3088     // TODO: As we hit a new block, we should push and pop equalities into a
3089     // table lookupOperandLeader can use, to catch things PredicateInfo
3090     // might miss, like edge-only equivalences.
3091     for (unsigned InstrNum : TouchedInstructions.set_bits()) {
3092 
3093       // This instruction was found to be dead. We don't bother looking
3094       // at it again.
3095       if (InstrNum == 0) {
3096         TouchedInstructions.reset(InstrNum);
3097         continue;
3098       }
3099 
3100       Value *V = InstrFromDFSNum(InstrNum);
3101       const BasicBlock *CurrBlock = getBlockForValue(V);
3102 
3103       // If we hit a new block, do reachability processing.
3104       if (CurrBlock != LastBlock) {
3105         LastBlock = CurrBlock;
3106         bool BlockReachable = ReachableBlocks.count(CurrBlock);
3107         const auto &CurrInstRange = BlockInstRange.lookup(CurrBlock);
3108 
3109         // If it's not reachable, erase any touched instructions and move on.
3110         if (!BlockReachable) {
3111           TouchedInstructions.reset(CurrInstRange.first, CurrInstRange.second);
3112           DEBUG(dbgs() << "Skipping instructions in block "
3113                        << getBlockName(CurrBlock)
3114                        << " because it is unreachable\n");
3115           continue;
3116         }
3117         updateProcessedCount(CurrBlock);
3118       }
3119       // Reset after processing (because we may mark ourselves as touched when
3120       // we propagate equalities).
3121       TouchedInstructions.reset(InstrNum);
3122 
3123       if (auto *MP = dyn_cast<MemoryPhi>(V)) {
3124         DEBUG(dbgs() << "Processing MemoryPhi " << *MP << "\n");
3125         valueNumberMemoryPhi(MP);
3126       } else if (auto *I = dyn_cast<Instruction>(V)) {
3127         valueNumberInstruction(I);
3128       } else {
3129         llvm_unreachable("Should have been a MemoryPhi or Instruction");
3130       }
3131       updateProcessedCount(V);
3132     }
3133   }
3134   NumGVNMaxIterations = std::max(NumGVNMaxIterations.getValue(), Iterations);
3135 }
3136 
3137 // This is the main transformation entry point.
3138 bool NewGVN::runGVN() {
3139   if (DebugCounter::isCounterSet(VNCounter))
3140     StartingVNCounter = DebugCounter::getCounterValue(VNCounter);
3141   bool Changed = false;
3142   NumFuncArgs = F.arg_size();
3143   MSSAWalker = MSSA->getWalker();
3144   SingletonDeadExpression = new (ExpressionAllocator) DeadExpression();
3145 
3146   // Count number of instructions for sizing of hash tables, and come
3147   // up with a global dfs numbering for instructions.
3148   unsigned ICount = 1;
3149   // Add an empty instruction to account for the fact that we start at 1
3150   DFSToInstr.emplace_back(nullptr);
3151   // Note: We want ideal RPO traversal of the blocks, which is not quite the
3152   // same as dominator tree order, particularly with regard whether backedges
3153   // get visited first or second, given a block with multiple successors.
3154   // If we visit in the wrong order, we will end up performing N times as many
3155   // iterations.
3156   // The dominator tree does guarantee that, for a given dom tree node, it's
3157   // parent must occur before it in the RPO ordering. Thus, we only need to sort
3158   // the siblings.
3159   ReversePostOrderTraversal<Function *> RPOT(&F);
3160   unsigned Counter = 0;
3161   for (auto &B : RPOT) {
3162     auto *Node = DT->getNode(B);
3163     assert(Node && "RPO and Dominator tree should have same reachability");
3164     RPOOrdering[Node] = ++Counter;
3165   }
3166   // Sort dominator tree children arrays into RPO.
3167   for (auto &B : RPOT) {
3168     auto *Node = DT->getNode(B);
3169     if (Node->getChildren().size() > 1)
3170       std::sort(Node->begin(), Node->end(),
3171                 [&](const DomTreeNode *A, const DomTreeNode *B) {
3172                   return RPOOrdering[A] < RPOOrdering[B];
3173                 });
3174   }
3175 
3176   // Now a standard depth first ordering of the domtree is equivalent to RPO.
3177   for (auto DTN : depth_first(DT->getRootNode())) {
3178     BasicBlock *B = DTN->getBlock();
3179     const auto &BlockRange = assignDFSNumbers(B, ICount);
3180     BlockInstRange.insert({B, BlockRange});
3181     ICount += BlockRange.second - BlockRange.first;
3182   }
3183   initializeCongruenceClasses(F);
3184 
3185   TouchedInstructions.resize(ICount);
3186   // Ensure we don't end up resizing the expressionToClass map, as
3187   // that can be quite expensive. At most, we have one expression per
3188   // instruction.
3189   ExpressionToClass.reserve(ICount);
3190 
3191   // Initialize the touched instructions to include the entry block.
3192   const auto &InstRange = BlockInstRange.lookup(&F.getEntryBlock());
3193   TouchedInstructions.set(InstRange.first, InstRange.second);
3194   DEBUG(dbgs() << "Block " << getBlockName(&F.getEntryBlock())
3195                << " marked reachable\n");
3196   ReachableBlocks.insert(&F.getEntryBlock());
3197 
3198   iterateTouchedInstructions();
3199   verifyMemoryCongruency();
3200   verifyIterationSettled(F);
3201   verifyStoreExpressions();
3202 
3203   Changed |= eliminateInstructions(F);
3204 
3205   // Delete all instructions marked for deletion.
3206   for (Instruction *ToErase : InstructionsToErase) {
3207     if (!ToErase->use_empty())
3208       ToErase->replaceAllUsesWith(UndefValue::get(ToErase->getType()));
3209 
3210     if (ToErase->getParent())
3211       ToErase->eraseFromParent();
3212   }
3213 
3214   // Delete all unreachable blocks.
3215   auto UnreachableBlockPred = [&](const BasicBlock &BB) {
3216     return !ReachableBlocks.count(&BB);
3217   };
3218 
3219   for (auto &BB : make_filter_range(F, UnreachableBlockPred)) {
3220     DEBUG(dbgs() << "We believe block " << getBlockName(&BB)
3221                  << " is unreachable\n");
3222     deleteInstructionsInBlock(&BB);
3223     Changed = true;
3224   }
3225 
3226   cleanupTables();
3227   return Changed;
3228 }
3229 
3230 struct NewGVN::ValueDFS {
3231   int DFSIn = 0;
3232   int DFSOut = 0;
3233   int LocalNum = 0;
3234   // Only one of Def and U will be set.
3235   // The bool in the Def tells us whether the Def is the stored value of a
3236   // store.
3237   PointerIntPair<Value *, 1, bool> Def;
3238   Use *U = nullptr;
3239   bool operator<(const ValueDFS &Other) const {
3240     // It's not enough that any given field be less than - we have sets
3241     // of fields that need to be evaluated together to give a proper ordering.
3242     // For example, if you have;
3243     // DFS (1, 3)
3244     // Val 0
3245     // DFS (1, 2)
3246     // Val 50
3247     // We want the second to be less than the first, but if we just go field
3248     // by field, we will get to Val 0 < Val 50 and say the first is less than
3249     // the second. We only want it to be less than if the DFS orders are equal.
3250     //
3251     // Each LLVM instruction only produces one value, and thus the lowest-level
3252     // differentiator that really matters for the stack (and what we use as as a
3253     // replacement) is the local dfs number.
3254     // Everything else in the structure is instruction level, and only affects
3255     // the order in which we will replace operands of a given instruction.
3256     //
3257     // For a given instruction (IE things with equal dfsin, dfsout, localnum),
3258     // the order of replacement of uses does not matter.
3259     // IE given,
3260     //  a = 5
3261     //  b = a + a
3262     // When you hit b, you will have two valuedfs with the same dfsin, out, and
3263     // localnum.
3264     // The .val will be the same as well.
3265     // The .u's will be different.
3266     // You will replace both, and it does not matter what order you replace them
3267     // in (IE whether you replace operand 2, then operand 1, or operand 1, then
3268     // operand 2).
3269     // Similarly for the case of same dfsin, dfsout, localnum, but different
3270     // .val's
3271     //  a = 5
3272     //  b  = 6
3273     //  c = a + b
3274     // in c, we will a valuedfs for a, and one for b,with everything the same
3275     // but .val  and .u.
3276     // It does not matter what order we replace these operands in.
3277     // You will always end up with the same IR, and this is guaranteed.
3278     return std::tie(DFSIn, DFSOut, LocalNum, Def, U) <
3279            std::tie(Other.DFSIn, Other.DFSOut, Other.LocalNum, Other.Def,
3280                     Other.U);
3281   }
3282 };
3283 
3284 // This function converts the set of members for a congruence class from values,
3285 // to sets of defs and uses with associated DFS info.  The total number of
3286 // reachable uses for each value is stored in UseCount, and instructions that
3287 // seem
3288 // dead (have no non-dead uses) are stored in ProbablyDead.
3289 void NewGVN::convertClassToDFSOrdered(
3290     const CongruenceClass &Dense, SmallVectorImpl<ValueDFS> &DFSOrderedSet,
3291     DenseMap<const Value *, unsigned int> &UseCounts,
3292     SmallPtrSetImpl<Instruction *> &ProbablyDead) const {
3293   for (auto D : Dense) {
3294     // First add the value.
3295     BasicBlock *BB = getBlockForValue(D);
3296     // Constants are handled prior to ever calling this function, so
3297     // we should only be left with instructions as members.
3298     assert(BB && "Should have figured out a basic block for value");
3299     ValueDFS VDDef;
3300     DomTreeNode *DomNode = DT->getNode(BB);
3301     VDDef.DFSIn = DomNode->getDFSNumIn();
3302     VDDef.DFSOut = DomNode->getDFSNumOut();
3303     // If it's a store, use the leader of the value operand, if it's always
3304     // available, or the value operand.  TODO: We could do dominance checks to
3305     // find a dominating leader, but not worth it ATM.
3306     if (auto *SI = dyn_cast<StoreInst>(D)) {
3307       auto Leader = lookupOperandLeader(SI->getValueOperand());
3308       if (alwaysAvailable(Leader)) {
3309         VDDef.Def.setPointer(Leader);
3310       } else {
3311         VDDef.Def.setPointer(SI->getValueOperand());
3312         VDDef.Def.setInt(true);
3313       }
3314     } else {
3315       VDDef.Def.setPointer(D);
3316     }
3317     assert(isa<Instruction>(D) &&
3318            "The dense set member should always be an instruction");
3319     Instruction *Def = cast<Instruction>(D);
3320     VDDef.LocalNum = InstrToDFSNum(D);
3321     DFSOrderedSet.push_back(VDDef);
3322     // If there is a phi node equivalent, add it
3323     if (auto *PN = RealToTemp.lookup(Def)) {
3324       auto *PHIE =
3325           dyn_cast_or_null<PHIExpression>(ValueToExpression.lookup(Def));
3326       if (PHIE) {
3327         VDDef.Def.setInt(false);
3328         VDDef.Def.setPointer(PN);
3329         VDDef.LocalNum = 0;
3330         DFSOrderedSet.push_back(VDDef);
3331       }
3332     }
3333 
3334     unsigned int UseCount = 0;
3335     // Now add the uses.
3336     for (auto &U : Def->uses()) {
3337       if (auto *I = dyn_cast<Instruction>(U.getUser())) {
3338         // Don't try to replace into dead uses
3339         if (InstructionsToErase.count(I))
3340           continue;
3341         ValueDFS VDUse;
3342         // Put the phi node uses in the incoming block.
3343         BasicBlock *IBlock;
3344         if (auto *P = dyn_cast<PHINode>(I)) {
3345           IBlock = P->getIncomingBlock(U);
3346           // Make phi node users appear last in the incoming block
3347           // they are from.
3348           VDUse.LocalNum = InstrDFS.size() + 1;
3349         } else {
3350           IBlock = getBlockForValue(I);
3351           VDUse.LocalNum = InstrToDFSNum(I);
3352         }
3353 
3354         // Skip uses in unreachable blocks, as we're going
3355         // to delete them.
3356         if (ReachableBlocks.count(IBlock) == 0)
3357           continue;
3358 
3359         DomTreeNode *DomNode = DT->getNode(IBlock);
3360         VDUse.DFSIn = DomNode->getDFSNumIn();
3361         VDUse.DFSOut = DomNode->getDFSNumOut();
3362         VDUse.U = &U;
3363         ++UseCount;
3364         DFSOrderedSet.emplace_back(VDUse);
3365       }
3366     }
3367 
3368     // If there are no uses, it's probably dead (but it may have side-effects,
3369     // so not definitely dead. Otherwise, store the number of uses so we can
3370     // track if it becomes dead later).
3371     if (UseCount == 0)
3372       ProbablyDead.insert(Def);
3373     else
3374       UseCounts[Def] = UseCount;
3375   }
3376 }
3377 
3378 // This function converts the set of members for a congruence class from values,
3379 // to the set of defs for loads and stores, with associated DFS info.
3380 void NewGVN::convertClassToLoadsAndStores(
3381     const CongruenceClass &Dense,
3382     SmallVectorImpl<ValueDFS> &LoadsAndStores) const {
3383   for (auto D : Dense) {
3384     if (!isa<LoadInst>(D) && !isa<StoreInst>(D))
3385       continue;
3386 
3387     BasicBlock *BB = getBlockForValue(D);
3388     ValueDFS VD;
3389     DomTreeNode *DomNode = DT->getNode(BB);
3390     VD.DFSIn = DomNode->getDFSNumIn();
3391     VD.DFSOut = DomNode->getDFSNumOut();
3392     VD.Def.setPointer(D);
3393 
3394     // If it's an instruction, use the real local dfs number.
3395     if (auto *I = dyn_cast<Instruction>(D))
3396       VD.LocalNum = InstrToDFSNum(I);
3397     else
3398       llvm_unreachable("Should have been an instruction");
3399 
3400     LoadsAndStores.emplace_back(VD);
3401   }
3402 }
3403 
3404 static void patchReplacementInstruction(Instruction *I, Value *Repl) {
3405   auto *ReplInst = dyn_cast<Instruction>(Repl);
3406   if (!ReplInst)
3407     return;
3408 
3409   // Patch the replacement so that it is not more restrictive than the value
3410   // being replaced.
3411   // Note that if 'I' is a load being replaced by some operation,
3412   // for example, by an arithmetic operation, then andIRFlags()
3413   // would just erase all math flags from the original arithmetic
3414   // operation, which is clearly not wanted and not needed.
3415   if (!isa<LoadInst>(I))
3416     ReplInst->andIRFlags(I);
3417 
3418   // FIXME: If both the original and replacement value are part of the
3419   // same control-flow region (meaning that the execution of one
3420   // guarantees the execution of the other), then we can combine the
3421   // noalias scopes here and do better than the general conservative
3422   // answer used in combineMetadata().
3423 
3424   // In general, GVN unifies expressions over different control-flow
3425   // regions, and so we need a conservative combination of the noalias
3426   // scopes.
3427   static const unsigned KnownIDs[] = {
3428       LLVMContext::MD_tbaa,           LLVMContext::MD_alias_scope,
3429       LLVMContext::MD_noalias,        LLVMContext::MD_range,
3430       LLVMContext::MD_fpmath,         LLVMContext::MD_invariant_load,
3431       LLVMContext::MD_invariant_group};
3432   combineMetadata(ReplInst, I, KnownIDs);
3433 }
3434 
3435 static void patchAndReplaceAllUsesWith(Instruction *I, Value *Repl) {
3436   patchReplacementInstruction(I, Repl);
3437   I->replaceAllUsesWith(Repl);
3438 }
3439 
3440 void NewGVN::deleteInstructionsInBlock(BasicBlock *BB) {
3441   DEBUG(dbgs() << "  BasicBlock Dead:" << *BB);
3442   ++NumGVNBlocksDeleted;
3443 
3444   // Delete the instructions backwards, as it has a reduced likelihood of having
3445   // to update as many def-use and use-def chains. Start after the terminator.
3446   auto StartPoint = BB->rbegin();
3447   ++StartPoint;
3448   // Note that we explicitly recalculate BB->rend() on each iteration,
3449   // as it may change when we remove the first instruction.
3450   for (BasicBlock::reverse_iterator I(StartPoint); I != BB->rend();) {
3451     Instruction &Inst = *I++;
3452     if (!Inst.use_empty())
3453       Inst.replaceAllUsesWith(UndefValue::get(Inst.getType()));
3454     if (isa<LandingPadInst>(Inst))
3455       continue;
3456 
3457     Inst.eraseFromParent();
3458     ++NumGVNInstrDeleted;
3459   }
3460   // Now insert something that simplifycfg will turn into an unreachable.
3461   Type *Int8Ty = Type::getInt8Ty(BB->getContext());
3462   new StoreInst(UndefValue::get(Int8Ty),
3463                 Constant::getNullValue(Int8Ty->getPointerTo()),
3464                 BB->getTerminator());
3465 }
3466 
3467 void NewGVN::markInstructionForDeletion(Instruction *I) {
3468   DEBUG(dbgs() << "Marking " << *I << " for deletion\n");
3469   InstructionsToErase.insert(I);
3470 }
3471 
3472 void NewGVN::replaceInstruction(Instruction *I, Value *V) {
3473 
3474   DEBUG(dbgs() << "Replacing " << *I << " with " << *V << "\n");
3475   patchAndReplaceAllUsesWith(I, V);
3476   // We save the actual erasing to avoid invalidating memory
3477   // dependencies until we are done with everything.
3478   markInstructionForDeletion(I);
3479 }
3480 
3481 namespace {
3482 
3483 // This is a stack that contains both the value and dfs info of where
3484 // that value is valid.
3485 class ValueDFSStack {
3486 public:
3487   Value *back() const { return ValueStack.back(); }
3488   std::pair<int, int> dfs_back() const { return DFSStack.back(); }
3489 
3490   void push_back(Value *V, int DFSIn, int DFSOut) {
3491     ValueStack.emplace_back(V);
3492     DFSStack.emplace_back(DFSIn, DFSOut);
3493   }
3494   bool empty() const { return DFSStack.empty(); }
3495   bool isInScope(int DFSIn, int DFSOut) const {
3496     if (empty())
3497       return false;
3498     return DFSIn >= DFSStack.back().first && DFSOut <= DFSStack.back().second;
3499   }
3500 
3501   void popUntilDFSScope(int DFSIn, int DFSOut) {
3502 
3503     // These two should always be in sync at this point.
3504     assert(ValueStack.size() == DFSStack.size() &&
3505            "Mismatch between ValueStack and DFSStack");
3506     while (
3507         !DFSStack.empty() &&
3508         !(DFSIn >= DFSStack.back().first && DFSOut <= DFSStack.back().second)) {
3509       DFSStack.pop_back();
3510       ValueStack.pop_back();
3511     }
3512   }
3513 
3514 private:
3515   SmallVector<Value *, 8> ValueStack;
3516   SmallVector<std::pair<int, int>, 8> DFSStack;
3517 };
3518 }
3519 
3520 // Given a value and a basic block we are trying to see if it is available in,
3521 // see if the value has a leader available in that block.
3522 Value *NewGVN::findPhiOfOpsLeader(const Expression *E,
3523                                   const BasicBlock *BB) const {
3524   // It would already be constant if we could make it constant
3525   if (auto *CE = dyn_cast<ConstantExpression>(E))
3526     return CE->getConstantValue();
3527   if (auto *VE = dyn_cast<VariableExpression>(E))
3528     return VE->getVariableValue();
3529 
3530   auto *CC = ExpressionToClass.lookup(E);
3531   if (!CC)
3532     return nullptr;
3533   if (alwaysAvailable(CC->getLeader()))
3534     return CC->getLeader();
3535 
3536   for (auto Member : *CC) {
3537     auto *MemberInst = dyn_cast<Instruction>(Member);
3538     // Anything that isn't an instruction is always available.
3539     if (!MemberInst)
3540       return Member;
3541     // If we are looking for something in the same block as the member, it must
3542     // be a leader because this function is looking for operands for a phi node.
3543     if (MemberInst->getParent() == BB ||
3544         DT->dominates(MemberInst->getParent(), BB)) {
3545       return Member;
3546     }
3547   }
3548   return nullptr;
3549 }
3550 
3551 bool NewGVN::eliminateInstructions(Function &F) {
3552   // This is a non-standard eliminator. The normal way to eliminate is
3553   // to walk the dominator tree in order, keeping track of available
3554   // values, and eliminating them.  However, this is mildly
3555   // pointless. It requires doing lookups on every instruction,
3556   // regardless of whether we will ever eliminate it.  For
3557   // instructions part of most singleton congruence classes, we know we
3558   // will never eliminate them.
3559 
3560   // Instead, this eliminator looks at the congruence classes directly, sorts
3561   // them into a DFS ordering of the dominator tree, and then we just
3562   // perform elimination straight on the sets by walking the congruence
3563   // class member uses in order, and eliminate the ones dominated by the
3564   // last member.   This is worst case O(E log E) where E = number of
3565   // instructions in a single congruence class.  In theory, this is all
3566   // instructions.   In practice, it is much faster, as most instructions are
3567   // either in singleton congruence classes or can't possibly be eliminated
3568   // anyway (if there are no overlapping DFS ranges in class).
3569   // When we find something not dominated, it becomes the new leader
3570   // for elimination purposes.
3571   // TODO: If we wanted to be faster, We could remove any members with no
3572   // overlapping ranges while sorting, as we will never eliminate anything
3573   // with those members, as they don't dominate anything else in our set.
3574 
3575   bool AnythingReplaced = false;
3576 
3577   // Since we are going to walk the domtree anyway, and we can't guarantee the
3578   // DFS numbers are updated, we compute some ourselves.
3579   DT->updateDFSNumbers();
3580 
3581   // Go through all of our phi nodes, and kill the arguments associated with
3582   // unreachable edges.
3583   auto ReplaceUnreachablePHIArgs = [&](PHINode &PHI, BasicBlock *BB) {
3584     for (auto &Operand : PHI.incoming_values())
3585       if (!ReachableEdges.count({PHI.getIncomingBlock(Operand), BB})) {
3586         DEBUG(dbgs() << "Replacing incoming value of " << PHI << " for block "
3587                      << getBlockName(PHI.getIncomingBlock(Operand))
3588                      << " with undef due to it being unreachable\n");
3589         Operand.set(UndefValue::get(PHI.getType()));
3590       }
3591   };
3592   SmallPtrSet<BasicBlock *, 8> BlocksWithPhis;
3593   for (auto &B : F)
3594     if ((!B.empty() && isa<PHINode>(*B.begin())) ||
3595         (PHIOfOpsPHIs.find(&B) != PHIOfOpsPHIs.end()))
3596       BlocksWithPhis.insert(&B);
3597   DenseMap<const BasicBlock *, unsigned> ReachablePredCount;
3598   for (auto KV : ReachableEdges)
3599     ReachablePredCount[KV.getEnd()]++;
3600   for (auto *BB : BlocksWithPhis)
3601     // TODO: It would be faster to use getNumIncomingBlocks() on a phi node in
3602     // the block and subtract the pred count, but it's more complicated.
3603     if (ReachablePredCount.lookup(BB) !=
3604         unsigned(std::distance(pred_begin(BB), pred_end(BB)))) {
3605       for (auto II = BB->begin(); isa<PHINode>(II); ++II) {
3606         auto &PHI = cast<PHINode>(*II);
3607         ReplaceUnreachablePHIArgs(PHI, BB);
3608       }
3609       for_each_found(PHIOfOpsPHIs, BB, [&](PHINode *PHI) {
3610         ReplaceUnreachablePHIArgs(*PHI, BB);
3611       });
3612     }
3613 
3614   // Map to store the use counts
3615   DenseMap<const Value *, unsigned int> UseCounts;
3616   for (auto *CC : reverse(CongruenceClasses)) {
3617     DEBUG(dbgs() << "Eliminating in congruence class " << CC->getID() << "\n");
3618     // Track the equivalent store info so we can decide whether to try
3619     // dead store elimination.
3620     SmallVector<ValueDFS, 8> PossibleDeadStores;
3621     SmallPtrSet<Instruction *, 8> ProbablyDead;
3622     if (CC->isDead() || CC->empty())
3623       continue;
3624     // Everything still in the TOP class is unreachable or dead.
3625     if (CC == TOPClass) {
3626       for (auto M : *CC) {
3627         auto *VTE = ValueToExpression.lookup(M);
3628         if (VTE && isa<DeadExpression>(VTE))
3629           markInstructionForDeletion(cast<Instruction>(M));
3630         assert((!ReachableBlocks.count(cast<Instruction>(M)->getParent()) ||
3631                 InstructionsToErase.count(cast<Instruction>(M))) &&
3632                "Everything in TOP should be unreachable or dead at this "
3633                "point");
3634       }
3635       continue;
3636     }
3637 
3638     assert(CC->getLeader() && "We should have had a leader");
3639     // If this is a leader that is always available, and it's a
3640     // constant or has no equivalences, just replace everything with
3641     // it. We then update the congruence class with whatever members
3642     // are left.
3643     Value *Leader =
3644         CC->getStoredValue() ? CC->getStoredValue() : CC->getLeader();
3645     if (alwaysAvailable(Leader)) {
3646       CongruenceClass::MemberSet MembersLeft;
3647       for (auto M : *CC) {
3648         Value *Member = M;
3649         // Void things have no uses we can replace.
3650         if (Member == Leader || !isa<Instruction>(Member) ||
3651             Member->getType()->isVoidTy()) {
3652           MembersLeft.insert(Member);
3653           continue;
3654         }
3655         DEBUG(dbgs() << "Found replacement " << *(Leader) << " for " << *Member
3656                      << "\n");
3657         auto *I = cast<Instruction>(Member);
3658         assert(Leader != I && "About to accidentally remove our leader");
3659         replaceInstruction(I, Leader);
3660         AnythingReplaced = true;
3661       }
3662       CC->swap(MembersLeft);
3663     } else {
3664       // If this is a singleton, we can skip it.
3665       if (CC->size() != 1 || RealToTemp.count(Leader)) {
3666         // This is a stack because equality replacement/etc may place
3667         // constants in the middle of the member list, and we want to use
3668         // those constant values in preference to the current leader, over
3669         // the scope of those constants.
3670         ValueDFSStack EliminationStack;
3671 
3672         // Convert the members to DFS ordered sets and then merge them.
3673         SmallVector<ValueDFS, 8> DFSOrderedSet;
3674         convertClassToDFSOrdered(*CC, DFSOrderedSet, UseCounts, ProbablyDead);
3675 
3676         // Sort the whole thing.
3677         std::sort(DFSOrderedSet.begin(), DFSOrderedSet.end());
3678         for (auto &VD : DFSOrderedSet) {
3679           int MemberDFSIn = VD.DFSIn;
3680           int MemberDFSOut = VD.DFSOut;
3681           Value *Def = VD.Def.getPointer();
3682           bool FromStore = VD.Def.getInt();
3683           Use *U = VD.U;
3684           // We ignore void things because we can't get a value from them.
3685           if (Def && Def->getType()->isVoidTy())
3686             continue;
3687           auto *DefInst = dyn_cast_or_null<Instruction>(Def);
3688           if (DefInst && AllTempInstructions.count(DefInst)) {
3689             auto *PN = cast<PHINode>(DefInst);
3690 
3691             // If this is a value phi and that's the expression we used, insert
3692             // it into the program
3693             // remove from temp instruction list.
3694             AllTempInstructions.erase(PN);
3695             auto *DefBlock = getBlockForValue(Def);
3696             DEBUG(dbgs() << "Inserting fully real phi of ops" << *Def
3697                          << " into block "
3698                          << getBlockName(getBlockForValue(Def)) << "\n");
3699             PN->insertBefore(&DefBlock->front());
3700             Def = PN;
3701             NumGVNPHIOfOpsEliminations++;
3702           }
3703 
3704           if (EliminationStack.empty()) {
3705             DEBUG(dbgs() << "Elimination Stack is empty\n");
3706           } else {
3707             DEBUG(dbgs() << "Elimination Stack Top DFS numbers are ("
3708                          << EliminationStack.dfs_back().first << ","
3709                          << EliminationStack.dfs_back().second << ")\n");
3710           }
3711 
3712           DEBUG(dbgs() << "Current DFS numbers are (" << MemberDFSIn << ","
3713                        << MemberDFSOut << ")\n");
3714           // First, we see if we are out of scope or empty.  If so,
3715           // and there equivalences, we try to replace the top of
3716           // stack with equivalences (if it's on the stack, it must
3717           // not have been eliminated yet).
3718           // Then we synchronize to our current scope, by
3719           // popping until we are back within a DFS scope that
3720           // dominates the current member.
3721           // Then, what happens depends on a few factors
3722           // If the stack is now empty, we need to push
3723           // If we have a constant or a local equivalence we want to
3724           // start using, we also push.
3725           // Otherwise, we walk along, processing members who are
3726           // dominated by this scope, and eliminate them.
3727           bool ShouldPush = Def && EliminationStack.empty();
3728           bool OutOfScope =
3729               !EliminationStack.isInScope(MemberDFSIn, MemberDFSOut);
3730 
3731           if (OutOfScope || ShouldPush) {
3732             // Sync to our current scope.
3733             EliminationStack.popUntilDFSScope(MemberDFSIn, MemberDFSOut);
3734             bool ShouldPush = Def && EliminationStack.empty();
3735             if (ShouldPush) {
3736               EliminationStack.push_back(Def, MemberDFSIn, MemberDFSOut);
3737             }
3738           }
3739 
3740           // Skip the Def's, we only want to eliminate on their uses.  But mark
3741           // dominated defs as dead.
3742           if (Def) {
3743             // For anything in this case, what and how we value number
3744             // guarantees that any side-effets that would have occurred (ie
3745             // throwing, etc) can be proven to either still occur (because it's
3746             // dominated by something that has the same side-effects), or never
3747             // occur.  Otherwise, we would not have been able to prove it value
3748             // equivalent to something else. For these things, we can just mark
3749             // it all dead.  Note that this is different from the "ProbablyDead"
3750             // set, which may not be dominated by anything, and thus, are only
3751             // easy to prove dead if they are also side-effect free. Note that
3752             // because stores are put in terms of the stored value, we skip
3753             // stored values here. If the stored value is really dead, it will
3754             // still be marked for deletion when we process it in its own class.
3755             if (!EliminationStack.empty() && Def != EliminationStack.back() &&
3756                 isa<Instruction>(Def) && !FromStore)
3757               markInstructionForDeletion(cast<Instruction>(Def));
3758             continue;
3759           }
3760           // At this point, we know it is a Use we are trying to possibly
3761           // replace.
3762 
3763           assert(isa<Instruction>(U->get()) &&
3764                  "Current def should have been an instruction");
3765           assert(isa<Instruction>(U->getUser()) &&
3766                  "Current user should have been an instruction");
3767 
3768           // If the thing we are replacing into is already marked to be dead,
3769           // this use is dead.  Note that this is true regardless of whether
3770           // we have anything dominating the use or not.  We do this here
3771           // because we are already walking all the uses anyway.
3772           Instruction *InstUse = cast<Instruction>(U->getUser());
3773           if (InstructionsToErase.count(InstUse)) {
3774             auto &UseCount = UseCounts[U->get()];
3775             if (--UseCount == 0) {
3776               ProbablyDead.insert(cast<Instruction>(U->get()));
3777             }
3778           }
3779 
3780           // If we get to this point, and the stack is empty we must have a use
3781           // with nothing we can use to eliminate this use, so just skip it.
3782           if (EliminationStack.empty())
3783             continue;
3784 
3785           Value *DominatingLeader = EliminationStack.back();
3786 
3787           auto *II = dyn_cast<IntrinsicInst>(DominatingLeader);
3788           if (II && II->getIntrinsicID() == Intrinsic::ssa_copy)
3789             DominatingLeader = II->getOperand(0);
3790 
3791           // Don't replace our existing users with ourselves.
3792           if (U->get() == DominatingLeader)
3793             continue;
3794           DEBUG(dbgs() << "Found replacement " << *DominatingLeader << " for "
3795                        << *U->get() << " in " << *(U->getUser()) << "\n");
3796 
3797           // If we replaced something in an instruction, handle the patching of
3798           // metadata.  Skip this if we are replacing predicateinfo with its
3799           // original operand, as we already know we can just drop it.
3800           auto *ReplacedInst = cast<Instruction>(U->get());
3801           auto *PI = PredInfo->getPredicateInfoFor(ReplacedInst);
3802           if (!PI || DominatingLeader != PI->OriginalOp)
3803             patchReplacementInstruction(ReplacedInst, DominatingLeader);
3804           U->set(DominatingLeader);
3805           // This is now a use of the dominating leader, which means if the
3806           // dominating leader was dead, it's now live!
3807           auto &LeaderUseCount = UseCounts[DominatingLeader];
3808           // It's about to be alive again.
3809           if (LeaderUseCount == 0 && isa<Instruction>(DominatingLeader))
3810             ProbablyDead.erase(cast<Instruction>(DominatingLeader));
3811           if (LeaderUseCount == 0 && II)
3812             ProbablyDead.insert(II);
3813           ++LeaderUseCount;
3814           AnythingReplaced = true;
3815         }
3816       }
3817     }
3818 
3819     // At this point, anything still in the ProbablyDead set is actually dead if
3820     // would be trivially dead.
3821     for (auto *I : ProbablyDead)
3822       if (wouldInstructionBeTriviallyDead(I))
3823         markInstructionForDeletion(I);
3824 
3825     // Cleanup the congruence class.
3826     CongruenceClass::MemberSet MembersLeft;
3827     for (auto *Member : *CC)
3828       if (!isa<Instruction>(Member) ||
3829           !InstructionsToErase.count(cast<Instruction>(Member)))
3830         MembersLeft.insert(Member);
3831     CC->swap(MembersLeft);
3832 
3833     // If we have possible dead stores to look at, try to eliminate them.
3834     if (CC->getStoreCount() > 0) {
3835       convertClassToLoadsAndStores(*CC, PossibleDeadStores);
3836       std::sort(PossibleDeadStores.begin(), PossibleDeadStores.end());
3837       ValueDFSStack EliminationStack;
3838       for (auto &VD : PossibleDeadStores) {
3839         int MemberDFSIn = VD.DFSIn;
3840         int MemberDFSOut = VD.DFSOut;
3841         Instruction *Member = cast<Instruction>(VD.Def.getPointer());
3842         if (EliminationStack.empty() ||
3843             !EliminationStack.isInScope(MemberDFSIn, MemberDFSOut)) {
3844           // Sync to our current scope.
3845           EliminationStack.popUntilDFSScope(MemberDFSIn, MemberDFSOut);
3846           if (EliminationStack.empty()) {
3847             EliminationStack.push_back(Member, MemberDFSIn, MemberDFSOut);
3848             continue;
3849           }
3850         }
3851         // We already did load elimination, so nothing to do here.
3852         if (isa<LoadInst>(Member))
3853           continue;
3854         assert(!EliminationStack.empty());
3855         Instruction *Leader = cast<Instruction>(EliminationStack.back());
3856         (void)Leader;
3857         assert(DT->dominates(Leader->getParent(), Member->getParent()));
3858         // Member is dominater by Leader, and thus dead
3859         DEBUG(dbgs() << "Marking dead store " << *Member
3860                      << " that is dominated by " << *Leader << "\n");
3861         markInstructionForDeletion(Member);
3862         CC->erase(Member);
3863         ++NumGVNDeadStores;
3864       }
3865     }
3866   }
3867   return AnythingReplaced;
3868 }
3869 
3870 // This function provides global ranking of operations so that we can place them
3871 // in a canonical order.  Note that rank alone is not necessarily enough for a
3872 // complete ordering, as constants all have the same rank.  However, generally,
3873 // we will simplify an operation with all constants so that it doesn't matter
3874 // what order they appear in.
3875 unsigned int NewGVN::getRank(const Value *V) const {
3876   // Prefer constants to undef to anything else
3877   // Undef is a constant, have to check it first.
3878   // Prefer smaller constants to constantexprs
3879   if (isa<ConstantExpr>(V))
3880     return 2;
3881   if (isa<UndefValue>(V))
3882     return 1;
3883   if (isa<Constant>(V))
3884     return 0;
3885   else if (auto *A = dyn_cast<Argument>(V))
3886     return 3 + A->getArgNo();
3887 
3888   // Need to shift the instruction DFS by number of arguments + 3 to account for
3889   // the constant and argument ranking above.
3890   unsigned Result = InstrToDFSNum(V);
3891   if (Result > 0)
3892     return 4 + NumFuncArgs + Result;
3893   // Unreachable or something else, just return a really large number.
3894   return ~0;
3895 }
3896 
3897 // This is a function that says whether two commutative operations should
3898 // have their order swapped when canonicalizing.
3899 bool NewGVN::shouldSwapOperands(const Value *A, const Value *B) const {
3900   // Because we only care about a total ordering, and don't rewrite expressions
3901   // in this order, we order by rank, which will give a strict weak ordering to
3902   // everything but constants, and then we order by pointer address.
3903   return std::make_pair(getRank(A), A) > std::make_pair(getRank(B), B);
3904 }
3905 
3906 namespace {
3907 class NewGVNLegacyPass : public FunctionPass {
3908 public:
3909   static char ID; // Pass identification, replacement for typeid.
3910   NewGVNLegacyPass() : FunctionPass(ID) {
3911     initializeNewGVNLegacyPassPass(*PassRegistry::getPassRegistry());
3912   }
3913   bool runOnFunction(Function &F) override;
3914 
3915 private:
3916   void getAnalysisUsage(AnalysisUsage &AU) const override {
3917     AU.addRequired<AssumptionCacheTracker>();
3918     AU.addRequired<DominatorTreeWrapperPass>();
3919     AU.addRequired<TargetLibraryInfoWrapperPass>();
3920     AU.addRequired<MemorySSAWrapperPass>();
3921     AU.addRequired<AAResultsWrapperPass>();
3922     AU.addPreserved<DominatorTreeWrapperPass>();
3923     AU.addPreserved<GlobalsAAWrapperPass>();
3924   }
3925 };
3926 } // namespace
3927 
3928 bool NewGVNLegacyPass::runOnFunction(Function &F) {
3929   if (skipFunction(F))
3930     return false;
3931   return NewGVN(F, &getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
3932                 &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
3933                 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(),
3934                 &getAnalysis<AAResultsWrapperPass>().getAAResults(),
3935                 &getAnalysis<MemorySSAWrapperPass>().getMSSA(),
3936                 F.getParent()->getDataLayout())
3937       .runGVN();
3938 }
3939 
3940 INITIALIZE_PASS_BEGIN(NewGVNLegacyPass, "newgvn", "Global Value Numbering",
3941                       false, false)
3942 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
3943 INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
3944 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
3945 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
3946 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
3947 INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
3948 INITIALIZE_PASS_END(NewGVNLegacyPass, "newgvn", "Global Value Numbering", false,
3949                     false)
3950 
3951 char NewGVNLegacyPass::ID = 0;
3952 
3953 // createGVNPass - The public interface to this file.
3954 FunctionPass *llvm::createNewGVNPass() { return new NewGVNLegacyPass(); }
3955 
3956 PreservedAnalyses NewGVNPass::run(Function &F, AnalysisManager<Function> &AM) {
3957   // Apparently the order in which we get these results matter for
3958   // the old GVN (see Chandler's comment in GVN.cpp). I'll keep
3959   // the same order here, just in case.
3960   auto &AC = AM.getResult<AssumptionAnalysis>(F);
3961   auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
3962   auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
3963   auto &AA = AM.getResult<AAManager>(F);
3964   auto &MSSA = AM.getResult<MemorySSAAnalysis>(F).getMSSA();
3965   bool Changed =
3966       NewGVN(F, &DT, &AC, &TLI, &AA, &MSSA, F.getParent()->getDataLayout())
3967           .runGVN();
3968   if (!Changed)
3969     return PreservedAnalyses::all();
3970   PreservedAnalyses PA;
3971   PA.preserve<DominatorTreeAnalysis>();
3972   PA.preserve<GlobalsAA>();
3973   return PA;
3974 }
3975