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