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