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 rest of the algorithm is devoted to
34 /// performing symbolic evaluation, forward propagation, and simplification of
35 /// operations based on the value numbers deduced so far.
36 ///
37 /// We also do not perform elimination by using any published algorithm.  All
38 /// published algorithms are O(Instructions). Instead, we use a technique that
39 /// is O(number of operations with the same value number), enabling us to skip
40 /// trying to eliminate things that have unique value numbers.
41 //===----------------------------------------------------------------------===//
42 
43 #include "llvm/Transforms/Scalar/NewGVN.h"
44 #include "llvm/ADT/BitVector.h"
45 #include "llvm/ADT/DenseMap.h"
46 #include "llvm/ADT/DenseSet.h"
47 #include "llvm/ADT/DepthFirstIterator.h"
48 #include "llvm/ADT/Hashing.h"
49 #include "llvm/ADT/MapVector.h"
50 #include "llvm/ADT/PostOrderIterator.h"
51 #include "llvm/ADT/STLExtras.h"
52 #include "llvm/ADT/SmallPtrSet.h"
53 #include "llvm/ADT/SmallSet.h"
54 #include "llvm/ADT/SparseBitVector.h"
55 #include "llvm/ADT/Statistic.h"
56 #include "llvm/ADT/TinyPtrVector.h"
57 #include "llvm/Analysis/AliasAnalysis.h"
58 #include "llvm/Analysis/AssumptionCache.h"
59 #include "llvm/Analysis/CFG.h"
60 #include "llvm/Analysis/CFGPrinter.h"
61 #include "llvm/Analysis/ConstantFolding.h"
62 #include "llvm/Analysis/GlobalsModRef.h"
63 #include "llvm/Analysis/InstructionSimplify.h"
64 #include "llvm/Analysis/MemoryBuiltins.h"
65 #include "llvm/Analysis/MemoryLocation.h"
66 #include "llvm/Analysis/TargetLibraryInfo.h"
67 #include "llvm/IR/DataLayout.h"
68 #include "llvm/IR/Dominators.h"
69 #include "llvm/IR/GlobalVariable.h"
70 #include "llvm/IR/IRBuilder.h"
71 #include "llvm/IR/IntrinsicInst.h"
72 #include "llvm/IR/LLVMContext.h"
73 #include "llvm/IR/Metadata.h"
74 #include "llvm/IR/PatternMatch.h"
75 #include "llvm/IR/Type.h"
76 #include "llvm/Support/Allocator.h"
77 #include "llvm/Support/CommandLine.h"
78 #include "llvm/Support/Debug.h"
79 #include "llvm/Transforms/Scalar.h"
80 #include "llvm/Transforms/Scalar/GVNExpression.h"
81 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
82 #include "llvm/Transforms/Utils/Local.h"
83 #include "llvm/Transforms/Utils/MemorySSA.h"
84 #include "llvm/Transforms/Utils/PredicateInfo.h"
85 #include <unordered_map>
86 #include <utility>
87 #include <vector>
88 using namespace llvm;
89 using namespace PatternMatch;
90 using namespace llvm::GVNExpression;
91 #define DEBUG_TYPE "newgvn"
92 
93 STATISTIC(NumGVNInstrDeleted, "Number of instructions deleted");
94 STATISTIC(NumGVNBlocksDeleted, "Number of blocks deleted");
95 STATISTIC(NumGVNOpsSimplified, "Number of Expressions simplified");
96 STATISTIC(NumGVNPhisAllSame, "Number of PHIs whos arguments are all the same");
97 STATISTIC(NumGVNMaxIterations,
98           "Maximum Number of iterations it took to converge GVN");
99 STATISTIC(NumGVNLeaderChanges, "Number of leader changes");
100 STATISTIC(NumGVNSortedLeaderChanges, "Number of sorted leader changes");
101 STATISTIC(NumGVNAvoidedSortedLeaderChanges,
102           "Number of avoided sorted leader changes");
103 STATISTIC(NumGVNNotMostDominatingLeader,
104           "Number of times a member dominated it's new classes' leader");
105 STATISTIC(NumGVNDeadStores, "Number of redundant/dead stores eliminated");
106 
107 //===----------------------------------------------------------------------===//
108 //                                GVN Pass
109 //===----------------------------------------------------------------------===//
110 
111 // Anchor methods.
112 namespace llvm {
113 namespace GVNExpression {
114 Expression::~Expression() = default;
115 BasicExpression::~BasicExpression() = default;
116 CallExpression::~CallExpression() = default;
117 LoadExpression::~LoadExpression() = default;
118 StoreExpression::~StoreExpression() = default;
119 AggregateValueExpression::~AggregateValueExpression() = default;
120 PHIExpression::~PHIExpression() = default;
121 }
122 }
123 
124 // Congruence classes represent the set of expressions/instructions
125 // that are all the same *during some scope in the function*.
126 // That is, because of the way we perform equality propagation, and
127 // because of memory value numbering, it is not correct to assume
128 // you can willy-nilly replace any member with any other at any
129 // point in the function.
130 //
131 // For any Value in the Member set, it is valid to replace any dominated member
132 // with that Value.
133 //
134 // Every congruence class has a leader, and the leader is used to
135 // symbolize instructions in a canonical way (IE every operand of an
136 // instruction that is a member of the same congruence class will
137 // always be replaced with leader during symbolization).
138 // To simplify symbolization, we keep the leader as a constant if class can be
139 // proved to be a constant value.
140 // Otherwise, the leader is a randomly chosen member of the value set, it does
141 // not matter which one is chosen.
142 // Each congruence class also has a defining expression,
143 // though the expression may be null.  If it exists, it can be used for forward
144 // propagation and reassociation of values.
145 //
146 struct CongruenceClass {
147   using MemberSet = SmallPtrSet<Value *, 4>;
148   unsigned ID;
149   // Representative leader.
150   Value *RepLeader = nullptr;
151   // If this is represented by a store, the value.
152   Value *RepStoredValue = nullptr;
153   // If this class contains MemoryDefs, what is the represented memory state.
154   MemoryAccess *RepMemoryAccess = nullptr;
155   // Defining Expression.
156   const Expression *DefiningExpr = nullptr;
157   // Actual members of this class.
158   MemberSet Members;
159 
160   // True if this class has no members left.  This is mainly used for assertion
161   // purposes, and for skipping empty classes.
162   bool Dead = false;
163 
164   // Number of stores in this congruence class.
165   // This is used so we can detect store equivalence changes properly.
166   int StoreCount = 0;
167 
168   // The most dominating leader after our current leader, because the member set
169   // is not sorted and is expensive to keep sorted all the time.
170   std::pair<Value *, unsigned int> NextLeader = {nullptr, ~0U};
171 
172   explicit CongruenceClass(unsigned ID) : ID(ID) {}
173   CongruenceClass(unsigned ID, Value *Leader, const Expression *E)
174       : ID(ID), RepLeader(Leader), DefiningExpr(E) {}
175 };
176 
177 namespace llvm {
178 template <> struct DenseMapInfo<const Expression *> {
179   static const Expression *getEmptyKey() {
180     auto Val = static_cast<uintptr_t>(-1);
181     Val <<= PointerLikeTypeTraits<const Expression *>::NumLowBitsAvailable;
182     return reinterpret_cast<const Expression *>(Val);
183   }
184   static const Expression *getTombstoneKey() {
185     auto Val = static_cast<uintptr_t>(~1U);
186     Val <<= PointerLikeTypeTraits<const Expression *>::NumLowBitsAvailable;
187     return reinterpret_cast<const Expression *>(Val);
188   }
189   static unsigned getHashValue(const Expression *V) {
190     return static_cast<unsigned>(V->getHashValue());
191   }
192   static bool isEqual(const Expression *LHS, const Expression *RHS) {
193     if (LHS == RHS)
194       return true;
195     if (LHS == getTombstoneKey() || RHS == getTombstoneKey() ||
196         LHS == getEmptyKey() || RHS == getEmptyKey())
197       return false;
198     return *LHS == *RHS;
199   }
200 };
201 } // end namespace llvm
202 
203 namespace {
204 class NewGVN : public FunctionPass {
205   DominatorTree *DT;
206   const DataLayout *DL;
207   const TargetLibraryInfo *TLI;
208   AssumptionCache *AC;
209   AliasAnalysis *AA;
210   MemorySSA *MSSA;
211   MemorySSAWalker *MSSAWalker;
212   std::unique_ptr<PredicateInfo> PredInfo;
213   BumpPtrAllocator ExpressionAllocator;
214   ArrayRecycler<Value *> ArgRecycler;
215 
216   // Number of function arguments, used by ranking
217   unsigned int NumFuncArgs;
218 
219   // Congruence class info.
220 
221   // This class is called INITIAL in the paper. It is the class everything
222   // startsout in, and represents any value. Being an optimistic analysis,
223   // anything in the INITIAL class has the value TOP, which is indeterminate and
224   // equivalent to everything.
225   CongruenceClass *InitialClass;
226   std::vector<CongruenceClass *> CongruenceClasses;
227   unsigned NextCongruenceNum;
228 
229   // Value Mappings.
230   DenseMap<Value *, CongruenceClass *> ValueToClass;
231   DenseMap<Value *, const Expression *> ValueToExpression;
232 
233   // Mapping from predicate info we used to the instructions we used it with.
234   // In order to correctly ensure propagation, we must keep track of what
235   // comparisons we used, so that when the values of the comparisons change, we
236   // propagate the information to the places we used the comparison.
237   DenseMap<const Value *, SmallPtrSet<Instruction *, 2>> PredicateToUsers;
238 
239   // A table storing which memorydefs/phis represent a memory state provably
240   // equivalent to another memory state.
241   // We could use the congruence class machinery, but the MemoryAccess's are
242   // abstract memory states, so they can only ever be equivalent to each other,
243   // and not to constants, etc.
244   DenseMap<const MemoryAccess *, CongruenceClass *> MemoryAccessToClass;
245 
246   // Expression to class mapping.
247   using ExpressionClassMap = DenseMap<const Expression *, CongruenceClass *>;
248   ExpressionClassMap ExpressionToClass;
249 
250   // Which values have changed as a result of leader changes.
251   SmallPtrSet<Value *, 8> LeaderChanges;
252 
253   // Reachability info.
254   using BlockEdge = BasicBlockEdge;
255   DenseSet<BlockEdge> ReachableEdges;
256   SmallPtrSet<const BasicBlock *, 8> ReachableBlocks;
257 
258   // This is a bitvector because, on larger functions, we may have
259   // thousands of touched instructions at once (entire blocks,
260   // instructions with hundreds of uses, etc).  Even with optimization
261   // for when we mark whole blocks as touched, when this was a
262   // SmallPtrSet or DenseSet, for some functions, we spent >20% of all
263   // the time in GVN just managing this list.  The bitvector, on the
264   // other hand, efficiently supports test/set/clear of both
265   // individual and ranges, as well as "find next element" This
266   // enables us to use it as a worklist with essentially 0 cost.
267   BitVector TouchedInstructions;
268 
269   DenseMap<const BasicBlock *, std::pair<unsigned, unsigned>> BlockInstRange;
270   DenseMap<const DomTreeNode *, std::pair<unsigned, unsigned>>
271       DominatedInstRange;
272 
273 #ifndef NDEBUG
274   // Debugging for how many times each block and instruction got processed.
275   DenseMap<const Value *, unsigned> ProcessedCount;
276 #endif
277 
278   // DFS info.
279   // This contains a mapping from Instructions to DFS numbers.
280   // The numbering starts at 1. An instruction with DFS number zero
281   // means that the instruction is dead.
282   DenseMap<const Value *, unsigned> InstrDFS;
283 
284   // This contains the mapping DFS numbers to instructions.
285   SmallVector<Value *, 32> DFSToInstr;
286 
287   // Deletion info.
288   SmallPtrSet<Instruction *, 8> InstructionsToErase;
289 
290 public:
291   static char ID; // Pass identification, replacement for typeid.
292   NewGVN() : FunctionPass(ID) {
293     initializeNewGVNPass(*PassRegistry::getPassRegistry());
294   }
295 
296   bool runOnFunction(Function &F) override;
297   bool runGVN(Function &F, DominatorTree *DT, AssumptionCache *AC,
298               TargetLibraryInfo *TLI, AliasAnalysis *AA, MemorySSA *MSSA);
299 
300 private:
301   void getAnalysisUsage(AnalysisUsage &AU) const override {
302     AU.addRequired<AssumptionCacheTracker>();
303     AU.addRequired<DominatorTreeWrapperPass>();
304     AU.addRequired<TargetLibraryInfoWrapperPass>();
305     AU.addRequired<MemorySSAWrapperPass>();
306     AU.addRequired<AAResultsWrapperPass>();
307     AU.addPreserved<DominatorTreeWrapperPass>();
308     AU.addPreserved<GlobalsAAWrapperPass>();
309   }
310 
311   // Expression handling.
312   const Expression *createExpression(Instruction *);
313   const Expression *createBinaryExpression(unsigned, Type *, Value *, Value *);
314   PHIExpression *createPHIExpression(Instruction *);
315   const VariableExpression *createVariableExpression(Value *);
316   const ConstantExpression *createConstantExpression(Constant *);
317   const Expression *createVariableOrConstant(Value *V);
318   const UnknownExpression *createUnknownExpression(Instruction *);
319   const StoreExpression *createStoreExpression(StoreInst *, MemoryAccess *);
320   LoadExpression *createLoadExpression(Type *, Value *, LoadInst *,
321                                        MemoryAccess *);
322   const CallExpression *createCallExpression(CallInst *, MemoryAccess *);
323   const AggregateValueExpression *createAggregateValueExpression(Instruction *);
324   bool setBasicExpressionInfo(Instruction *, BasicExpression *);
325 
326   // Congruence class handling.
327   CongruenceClass *createCongruenceClass(Value *Leader, const Expression *E) {
328     auto *result = new CongruenceClass(NextCongruenceNum++, Leader, E);
329     CongruenceClasses.emplace_back(result);
330     return result;
331   }
332 
333   CongruenceClass *createSingletonCongruenceClass(Value *Member) {
334     CongruenceClass *CClass = createCongruenceClass(Member, nullptr);
335     CClass->Members.insert(Member);
336     ValueToClass[Member] = CClass;
337     return CClass;
338   }
339   void initializeCongruenceClasses(Function &F);
340 
341   // Value number an Instruction or MemoryPhi.
342   void valueNumberMemoryPhi(MemoryPhi *);
343   void valueNumberInstruction(Instruction *);
344 
345   // Symbolic evaluation.
346   const Expression *checkSimplificationResults(Expression *, Instruction *,
347                                                Value *);
348   const Expression *performSymbolicEvaluation(Value *);
349   const Expression *performSymbolicLoadEvaluation(Instruction *);
350   const Expression *performSymbolicStoreEvaluation(Instruction *);
351   const Expression *performSymbolicCallEvaluation(Instruction *);
352   const Expression *performSymbolicPHIEvaluation(Instruction *);
353   const Expression *performSymbolicAggrValueEvaluation(Instruction *);
354   const Expression *performSymbolicCmpEvaluation(Instruction *);
355   const Expression *performSymbolicPredicateInfoEvaluation(Instruction *);
356 
357   // Congruence finding.
358   Value *lookupOperandLeader(Value *) const;
359   void performCongruenceFinding(Instruction *, const Expression *);
360   void moveValueToNewCongruenceClass(Instruction *, CongruenceClass *,
361                                      CongruenceClass *);
362   bool setMemoryAccessEquivTo(MemoryAccess *From, CongruenceClass *To);
363   MemoryAccess *lookupMemoryAccessEquiv(MemoryAccess *) const;
364   bool isMemoryAccessTop(const MemoryAccess *) const;
365 
366   // Ranking
367   unsigned int getRank(const Value *) const;
368   bool shouldSwapOperands(const Value *, const Value *) const;
369 
370   // Reachability handling.
371   void updateReachableEdge(BasicBlock *, BasicBlock *);
372   void processOutgoingEdges(TerminatorInst *, BasicBlock *);
373   Value *findConditionEquivalence(Value *) const;
374 
375   // Elimination.
376   struct ValueDFS;
377   void convertDenseToDFSOrdered(const CongruenceClass::MemberSet &,
378                                 SmallVectorImpl<ValueDFS> &);
379   void convertDenseToLoadsAndStores(const CongruenceClass::MemberSet &,
380                                     SmallVectorImpl<ValueDFS> &);
381 
382   bool eliminateInstructions(Function &);
383   void replaceInstruction(Instruction *, Value *);
384   void markInstructionForDeletion(Instruction *);
385   void deleteInstructionsInBlock(BasicBlock *);
386 
387   // New instruction creation.
388   void handleNewInstruction(Instruction *){};
389 
390   // Various instruction touch utilities
391   void markUsersTouched(Value *);
392   void markMemoryUsersTouched(MemoryAccess *);
393   void markPredicateUsersTouched(Instruction *);
394   void markLeaderChangeTouched(CongruenceClass *CC);
395   void addPredicateUsers(const PredicateBase *, Instruction *);
396 
397   // Utilities.
398   void cleanupTables();
399   std::pair<unsigned, unsigned> assignDFSNumbers(BasicBlock *, unsigned);
400   void updateProcessedCount(Value *V);
401   void verifyMemoryCongruency() const;
402   void verifyComparisons(Function &F);
403   bool singleReachablePHIPath(const MemoryAccess *, const MemoryAccess *) const;
404 };
405 } // end anonymous namespace
406 
407 char NewGVN::ID = 0;
408 
409 // createGVNPass - The public interface to this file.
410 FunctionPass *llvm::createNewGVNPass() { return new NewGVN(); }
411 
412 template <typename T>
413 static bool equalsLoadStoreHelper(const T &LHS, const Expression &RHS) {
414   if ((!isa<LoadExpression>(RHS) && !isa<StoreExpression>(RHS)) ||
415       !LHS.BasicExpression::equals(RHS)) {
416     return false;
417   } else if (const auto *L = dyn_cast<LoadExpression>(&RHS)) {
418     if (LHS.getDefiningAccess() != L->getDefiningAccess())
419       return false;
420   } else if (const auto *S = dyn_cast<StoreExpression>(&RHS)) {
421     if (LHS.getDefiningAccess() != S->getDefiningAccess())
422       return false;
423   }
424   return true;
425 }
426 
427 bool LoadExpression::equals(const Expression &Other) const {
428   return equalsLoadStoreHelper(*this, Other);
429 }
430 
431 bool StoreExpression::equals(const Expression &Other) const {
432   bool Result = equalsLoadStoreHelper(*this, Other);
433   // Make sure that store vs store includes the value operand.
434   if (Result)
435     if (const auto *S = dyn_cast<StoreExpression>(&Other))
436       if (getStoredValue() != S->getStoredValue())
437         return false;
438   return Result;
439 }
440 
441 #ifndef NDEBUG
442 static std::string getBlockName(const BasicBlock *B) {
443   return DOTGraphTraits<const Function *>::getSimpleNodeLabel(B, nullptr);
444 }
445 #endif
446 
447 INITIALIZE_PASS_BEGIN(NewGVN, "newgvn", "Global Value Numbering", false, false)
448 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
449 INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
450 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
451 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
452 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
453 INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
454 INITIALIZE_PASS_END(NewGVN, "newgvn", "Global Value Numbering", false, false)
455 
456 PHIExpression *NewGVN::createPHIExpression(Instruction *I) {
457   BasicBlock *PHIBlock = I->getParent();
458   auto *PN = cast<PHINode>(I);
459   auto *E =
460       new (ExpressionAllocator) PHIExpression(PN->getNumOperands(), PHIBlock);
461 
462   E->allocateOperands(ArgRecycler, ExpressionAllocator);
463   E->setType(I->getType());
464   E->setOpcode(I->getOpcode());
465 
466   // Filter out unreachable phi operands.
467   auto Filtered = make_filter_range(PN->operands(), [&](const Use &U) {
468     return ReachableBlocks.count(PN->getIncomingBlock(U));
469   });
470 
471   std::transform(Filtered.begin(), Filtered.end(), op_inserter(E),
472                  [&](const Use &U) -> Value * {
473                    // Don't try to transform self-defined phis.
474                    if (U == PN)
475                      return PN;
476                    return lookupOperandLeader(U);
477                  });
478   return E;
479 }
480 
481 // Set basic expression info (Arguments, type, opcode) for Expression
482 // E from Instruction I in block B.
483 bool NewGVN::setBasicExpressionInfo(Instruction *I, BasicExpression *E) {
484   bool AllConstant = true;
485   if (auto *GEP = dyn_cast<GetElementPtrInst>(I))
486     E->setType(GEP->getSourceElementType());
487   else
488     E->setType(I->getType());
489   E->setOpcode(I->getOpcode());
490   E->allocateOperands(ArgRecycler, ExpressionAllocator);
491 
492   // Transform the operand array into an operand leader array, and keep track of
493   // whether all members are constant.
494   std::transform(I->op_begin(), I->op_end(), op_inserter(E), [&](Value *O) {
495     auto Operand = lookupOperandLeader(O);
496     AllConstant &= isa<Constant>(Operand);
497     return Operand;
498   });
499 
500   return AllConstant;
501 }
502 
503 const Expression *NewGVN::createBinaryExpression(unsigned Opcode, Type *T,
504                                                  Value *Arg1, Value *Arg2) {
505   auto *E = new (ExpressionAllocator) BasicExpression(2);
506 
507   E->setType(T);
508   E->setOpcode(Opcode);
509   E->allocateOperands(ArgRecycler, ExpressionAllocator);
510   if (Instruction::isCommutative(Opcode)) {
511     // Ensure that commutative instructions that only differ by a permutation
512     // of their operands get the same value number by sorting the operand value
513     // numbers.  Since all commutative instructions have two operands it is more
514     // efficient to sort by hand rather than using, say, std::sort.
515     if (shouldSwapOperands(Arg1, Arg2))
516       std::swap(Arg1, Arg2);
517   }
518   E->op_push_back(lookupOperandLeader(Arg1));
519   E->op_push_back(lookupOperandLeader(Arg2));
520 
521   Value *V = SimplifyBinOp(Opcode, E->getOperand(0), E->getOperand(1), *DL, TLI,
522                            DT, AC);
523   if (const Expression *SimplifiedE = checkSimplificationResults(E, nullptr, V))
524     return SimplifiedE;
525   return E;
526 }
527 
528 // Take a Value returned by simplification of Expression E/Instruction
529 // I, and see if it resulted in a simpler expression. If so, return
530 // that expression.
531 // TODO: Once finished, this should not take an Instruction, we only
532 // use it for printing.
533 const Expression *NewGVN::checkSimplificationResults(Expression *E,
534                                                      Instruction *I, Value *V) {
535   if (!V)
536     return nullptr;
537   if (auto *C = dyn_cast<Constant>(V)) {
538     if (I)
539       DEBUG(dbgs() << "Simplified " << *I << " to "
540                    << " constant " << *C << "\n");
541     NumGVNOpsSimplified++;
542     assert(isa<BasicExpression>(E) &&
543            "We should always have had a basic expression here");
544 
545     cast<BasicExpression>(E)->deallocateOperands(ArgRecycler);
546     ExpressionAllocator.Deallocate(E);
547     return createConstantExpression(C);
548   } else if (isa<Argument>(V) || isa<GlobalVariable>(V)) {
549     if (I)
550       DEBUG(dbgs() << "Simplified " << *I << " to "
551                    << " variable " << *V << "\n");
552     cast<BasicExpression>(E)->deallocateOperands(ArgRecycler);
553     ExpressionAllocator.Deallocate(E);
554     return createVariableExpression(V);
555   }
556 
557   CongruenceClass *CC = ValueToClass.lookup(V);
558   if (CC && CC->DefiningExpr) {
559     if (I)
560       DEBUG(dbgs() << "Simplified " << *I << " to "
561                    << " expression " << *V << "\n");
562     NumGVNOpsSimplified++;
563     assert(isa<BasicExpression>(E) &&
564            "We should always have had a basic expression here");
565     cast<BasicExpression>(E)->deallocateOperands(ArgRecycler);
566     ExpressionAllocator.Deallocate(E);
567     return CC->DefiningExpr;
568   }
569   return nullptr;
570 }
571 
572 const Expression *NewGVN::createExpression(Instruction *I) {
573   auto *E = new (ExpressionAllocator) BasicExpression(I->getNumOperands());
574 
575   bool AllConstant = setBasicExpressionInfo(I, E);
576 
577   if (I->isCommutative()) {
578     // Ensure that commutative instructions that only differ by a permutation
579     // of their operands get the same value number by sorting the operand value
580     // numbers.  Since all commutative instructions have two operands it is more
581     // efficient to sort by hand rather than using, say, std::sort.
582     assert(I->getNumOperands() == 2 && "Unsupported commutative instruction!");
583     if (shouldSwapOperands(E->getOperand(0), E->getOperand(1)))
584       E->swapOperands(0, 1);
585   }
586 
587   // Perform simplificaiton
588   // TODO: Right now we only check to see if we get a constant result.
589   // We may get a less than constant, but still better, result for
590   // some operations.
591   // IE
592   //  add 0, x -> x
593   //  and x, x -> x
594   // We should handle this by simply rewriting the expression.
595   if (auto *CI = dyn_cast<CmpInst>(I)) {
596     // Sort the operand value numbers so x<y and y>x get the same value
597     // number.
598     CmpInst::Predicate Predicate = CI->getPredicate();
599     if (shouldSwapOperands(E->getOperand(0), E->getOperand(1))) {
600       E->swapOperands(0, 1);
601       Predicate = CmpInst::getSwappedPredicate(Predicate);
602     }
603     E->setOpcode((CI->getOpcode() << 8) | Predicate);
604     // TODO: 25% of our time is spent in SimplifyCmpInst with pointer operands
605     assert(I->getOperand(0)->getType() == I->getOperand(1)->getType() &&
606            "Wrong types on cmp instruction");
607     assert((E->getOperand(0)->getType() == I->getOperand(0)->getType() &&
608             E->getOperand(1)->getType() == I->getOperand(1)->getType()));
609     Value *V = SimplifyCmpInst(Predicate, E->getOperand(0), E->getOperand(1),
610                                *DL, TLI, DT, AC);
611     if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
612       return SimplifiedE;
613   } else if (isa<SelectInst>(I)) {
614     if (isa<Constant>(E->getOperand(0)) ||
615         E->getOperand(0) == E->getOperand(1)) {
616       assert(E->getOperand(1)->getType() == I->getOperand(1)->getType() &&
617              E->getOperand(2)->getType() == I->getOperand(2)->getType());
618       Value *V = SimplifySelectInst(E->getOperand(0), E->getOperand(1),
619                                     E->getOperand(2), *DL, TLI, DT, AC);
620       if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
621         return SimplifiedE;
622     }
623   } else if (I->isBinaryOp()) {
624     Value *V = SimplifyBinOp(E->getOpcode(), E->getOperand(0), E->getOperand(1),
625                              *DL, TLI, DT, AC);
626     if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
627       return SimplifiedE;
628   } else if (auto *BI = dyn_cast<BitCastInst>(I)) {
629     Value *V = SimplifyInstruction(BI, *DL, TLI, DT, AC);
630     if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
631       return SimplifiedE;
632   } else if (isa<GetElementPtrInst>(I)) {
633     Value *V = SimplifyGEPInst(E->getType(),
634                                ArrayRef<Value *>(E->op_begin(), E->op_end()),
635                                *DL, TLI, DT, AC);
636     if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
637       return SimplifiedE;
638   } else if (AllConstant) {
639     // We don't bother trying to simplify unless all of the operands
640     // were constant.
641     // TODO: There are a lot of Simplify*'s we could call here, if we
642     // wanted to.  The original motivating case for this code was a
643     // zext i1 false to i8, which we don't have an interface to
644     // simplify (IE there is no SimplifyZExt).
645 
646     SmallVector<Constant *, 8> C;
647     for (Value *Arg : E->operands())
648       C.emplace_back(cast<Constant>(Arg));
649 
650     if (Value *V = ConstantFoldInstOperands(I, C, *DL, TLI))
651       if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
652         return SimplifiedE;
653   }
654   return E;
655 }
656 
657 const AggregateValueExpression *
658 NewGVN::createAggregateValueExpression(Instruction *I) {
659   if (auto *II = dyn_cast<InsertValueInst>(I)) {
660     auto *E = new (ExpressionAllocator)
661         AggregateValueExpression(I->getNumOperands(), II->getNumIndices());
662     setBasicExpressionInfo(I, E);
663     E->allocateIntOperands(ExpressionAllocator);
664     std::copy(II->idx_begin(), II->idx_end(), int_op_inserter(E));
665     return E;
666   } else if (auto *EI = dyn_cast<ExtractValueInst>(I)) {
667     auto *E = new (ExpressionAllocator)
668         AggregateValueExpression(I->getNumOperands(), EI->getNumIndices());
669     setBasicExpressionInfo(EI, E);
670     E->allocateIntOperands(ExpressionAllocator);
671     std::copy(EI->idx_begin(), EI->idx_end(), int_op_inserter(E));
672     return E;
673   }
674   llvm_unreachable("Unhandled type of aggregate value operation");
675 }
676 
677 const VariableExpression *NewGVN::createVariableExpression(Value *V) {
678   auto *E = new (ExpressionAllocator) VariableExpression(V);
679   E->setOpcode(V->getValueID());
680   return E;
681 }
682 
683 const Expression *NewGVN::createVariableOrConstant(Value *V) {
684   if (auto *C = dyn_cast<Constant>(V))
685     return createConstantExpression(C);
686   return createVariableExpression(V);
687 }
688 
689 const ConstantExpression *NewGVN::createConstantExpression(Constant *C) {
690   auto *E = new (ExpressionAllocator) ConstantExpression(C);
691   E->setOpcode(C->getValueID());
692   return E;
693 }
694 
695 const UnknownExpression *NewGVN::createUnknownExpression(Instruction *I) {
696   auto *E = new (ExpressionAllocator) UnknownExpression(I);
697   E->setOpcode(I->getOpcode());
698   return E;
699 }
700 
701 const CallExpression *NewGVN::createCallExpression(CallInst *CI,
702                                                    MemoryAccess *HV) {
703   // FIXME: Add operand bundles for calls.
704   auto *E =
705       new (ExpressionAllocator) CallExpression(CI->getNumOperands(), CI, HV);
706   setBasicExpressionInfo(CI, E);
707   return E;
708 }
709 
710 // See if we have a congruence class and leader for this operand, and if so,
711 // return it. Otherwise, return the operand itself.
712 Value *NewGVN::lookupOperandLeader(Value *V) const {
713   CongruenceClass *CC = ValueToClass.lookup(V);
714   if (CC) {
715     // Everything in INITIAL is represneted by undef, as it can be any value.
716     // We do have to make sure we get the type right though, so we can't set the
717     // RepLeader to undef.
718     if (CC == InitialClass)
719       return UndefValue::get(V->getType());
720     return CC->RepStoredValue ? CC->RepStoredValue : CC->RepLeader;
721   }
722 
723   return V;
724 }
725 
726 MemoryAccess *NewGVN::lookupMemoryAccessEquiv(MemoryAccess *MA) const {
727   auto *CC = MemoryAccessToClass.lookup(MA);
728   if (CC && CC->RepMemoryAccess)
729     return CC->RepMemoryAccess;
730   // FIXME: We need to audit all the places that current set a nullptr To, and
731   // fix them.  There should always be *some* congruence class, even if it is
732   // singular.  Right now, we don't bother setting congruence classes for
733   // anything but stores, which means we have to return the original access
734   // here.  Otherwise, this should be unreachable.
735   return MA;
736 }
737 
738 // Return true if the MemoryAccess is really equivalent to everything. This is
739 // equivalent to the lattice value "TOP" in most lattices.  This is the initial
740 // state of all memory accesses.
741 bool NewGVN::isMemoryAccessTop(const MemoryAccess *MA) const {
742   return MemoryAccessToClass.lookup(MA) == InitialClass;
743 }
744 
745 LoadExpression *NewGVN::createLoadExpression(Type *LoadType, Value *PointerOp,
746                                              LoadInst *LI, MemoryAccess *DA) {
747   auto *E = new (ExpressionAllocator) LoadExpression(1, LI, DA);
748   E->allocateOperands(ArgRecycler, ExpressionAllocator);
749   E->setType(LoadType);
750 
751   // Give store and loads same opcode so they value number together.
752   E->setOpcode(0);
753   E->op_push_back(lookupOperandLeader(PointerOp));
754   if (LI)
755     E->setAlignment(LI->getAlignment());
756 
757   // TODO: Value number heap versions. We may be able to discover
758   // things alias analysis can't on it's own (IE that a store and a
759   // load have the same value, and thus, it isn't clobbering the load).
760   return E;
761 }
762 
763 const StoreExpression *NewGVN::createStoreExpression(StoreInst *SI,
764                                                      MemoryAccess *DA) {
765   auto *StoredValueLeader = lookupOperandLeader(SI->getValueOperand());
766   auto *E = new (ExpressionAllocator)
767       StoreExpression(SI->getNumOperands(), SI, StoredValueLeader, DA);
768   E->allocateOperands(ArgRecycler, ExpressionAllocator);
769   E->setType(SI->getValueOperand()->getType());
770 
771   // Give store and loads same opcode so they value number together.
772   E->setOpcode(0);
773   E->op_push_back(lookupOperandLeader(SI->getPointerOperand()));
774 
775   // TODO: Value number heap versions. We may be able to discover
776   // things alias analysis can't on it's own (IE that a store and a
777   // load have the same value, and thus, it isn't clobbering the load).
778   return E;
779 }
780 
781 const Expression *NewGVN::performSymbolicStoreEvaluation(Instruction *I) {
782   // Unlike loads, we never try to eliminate stores, so we do not check if they
783   // are simple and avoid value numbering them.
784   auto *SI = cast<StoreInst>(I);
785   MemoryAccess *StoreAccess = MSSA->getMemoryAccess(SI);
786   // Get the expression, if any, for the RHS of the MemoryDef.
787   MemoryAccess *StoreRHS = lookupMemoryAccessEquiv(
788       cast<MemoryDef>(StoreAccess)->getDefiningAccess());
789   // If we are defined by ourselves, use the live on entry def.
790   if (StoreRHS == StoreAccess)
791     StoreRHS = MSSA->getLiveOnEntryDef();
792 
793   if (SI->isSimple()) {
794     // See if we are defined by a previous store expression, it already has a
795     // value, and it's the same value as our current store. FIXME: Right now, we
796     // only do this for simple stores, we should expand to cover memcpys, etc.
797     const Expression *OldStore = createStoreExpression(SI, StoreRHS);
798     CongruenceClass *CC = ExpressionToClass.lookup(OldStore);
799     // Basically, check if the congruence class the store is in is defined by a
800     // store that isn't us, and has the same value.  MemorySSA takes care of
801     // ensuring the store has the same memory state as us already.
802     // The RepStoredValue gets nulled if all the stores disappear in a class, so
803     // we don't need to check if the class contains a store besides us.
804     if (CC && CC->RepStoredValue == lookupOperandLeader(SI->getValueOperand()))
805       return createStoreExpression(SI, StoreRHS);
806     // Also check if our value operand is defined by a load of the same memory
807     // location, and the memory state is the same as it was then
808     // (otherwise, it could have been overwritten later. See test32 in
809     // transforms/DeadStoreElimination/simple.ll)
810     if (LoadInst *LI = dyn_cast<LoadInst>(SI->getValueOperand())) {
811       if ((lookupOperandLeader(LI->getPointerOperand()) ==
812            lookupOperandLeader(SI->getPointerOperand())) &&
813           (lookupMemoryAccessEquiv(
814                MSSA->getMemoryAccess(LI)->getDefiningAccess()) == StoreRHS))
815         return createVariableExpression(LI);
816     }
817   }
818   return createStoreExpression(SI, StoreAccess);
819 }
820 
821 const Expression *NewGVN::performSymbolicLoadEvaluation(Instruction *I) {
822   auto *LI = cast<LoadInst>(I);
823 
824   // We can eliminate in favor of non-simple loads, but we won't be able to
825   // eliminate the loads themselves.
826   if (!LI->isSimple())
827     return nullptr;
828 
829   Value *LoadAddressLeader = lookupOperandLeader(LI->getPointerOperand());
830   // Load of undef is undef.
831   if (isa<UndefValue>(LoadAddressLeader))
832     return createConstantExpression(UndefValue::get(LI->getType()));
833 
834   MemoryAccess *DefiningAccess = MSSAWalker->getClobberingMemoryAccess(I);
835 
836   if (!MSSA->isLiveOnEntryDef(DefiningAccess)) {
837     if (auto *MD = dyn_cast<MemoryDef>(DefiningAccess)) {
838       Instruction *DefiningInst = MD->getMemoryInst();
839       // If the defining instruction is not reachable, replace with undef.
840       if (!ReachableBlocks.count(DefiningInst->getParent()))
841         return createConstantExpression(UndefValue::get(LI->getType()));
842     }
843   }
844 
845   const Expression *E =
846       createLoadExpression(LI->getType(), LI->getPointerOperand(), LI,
847                            lookupMemoryAccessEquiv(DefiningAccess));
848   return E;
849 }
850 
851 const Expression *
852 NewGVN::performSymbolicPredicateInfoEvaluation(Instruction *I) {
853   auto *PI = PredInfo->getPredicateInfoFor(I);
854   if (!PI)
855     return nullptr;
856 
857   DEBUG(dbgs() << "Found predicate info from instruction !\n");
858 
859   auto *PWC = dyn_cast<PredicateWithCondition>(PI);
860   if (!PWC)
861     return nullptr;
862 
863   auto *CopyOf = I->getOperand(0);
864   auto *Cond = PWC->Condition;
865 
866   // If this a copy of the condition, it must be either true or false depending
867   // on the predicate info type and edge
868   if (CopyOf == Cond) {
869     // We should not need to add predicate users because the predicate info is
870     // already a use of this operand.
871     if (isa<PredicateAssume>(PI))
872       return createConstantExpression(ConstantInt::getTrue(Cond->getType()));
873     if (auto *PBranch = dyn_cast<PredicateBranch>(PI)) {
874       if (PBranch->TrueEdge)
875         return createConstantExpression(ConstantInt::getTrue(Cond->getType()));
876       return createConstantExpression(ConstantInt::getFalse(Cond->getType()));
877     }
878     if (auto *PSwitch = dyn_cast<PredicateSwitch>(PI))
879       return createConstantExpression(cast<Constant>(PSwitch->CaseValue));
880   }
881 
882   // Not a copy of the condition, so see what the predicates tell us about this
883   // value.  First, though, we check to make sure the value is actually a copy
884   // of one of the condition operands. It's possible, in certain cases, for it
885   // to be a copy of a predicateinfo copy. In particular, if two branch
886   // operations use the same condition, and one branch dominates the other, we
887   // will end up with a copy of a copy.  This is currently a small deficiency in
888   // predicateinfo.  What will end up happening here is that we will value
889   // number both copies the same anyway.
890 
891   // Everything below relies on the condition being a comparison.
892   auto *Cmp = dyn_cast<CmpInst>(Cond);
893   if (!Cmp)
894     return nullptr;
895 
896   if (CopyOf != Cmp->getOperand(0) && CopyOf != Cmp->getOperand(1)) {
897     DEBUG(dbgs() << "Copy is not of any condition operands!");
898     return nullptr;
899   }
900   Value *FirstOp = lookupOperandLeader(Cmp->getOperand(0));
901   Value *SecondOp = lookupOperandLeader(Cmp->getOperand(1));
902   bool SwappedOps = false;
903   // Sort the ops
904   if (shouldSwapOperands(FirstOp, SecondOp)) {
905     std::swap(FirstOp, SecondOp);
906     SwappedOps = true;
907   }
908   CmpInst::Predicate Predicate =
909       SwappedOps ? Cmp->getSwappedPredicate() : Cmp->getPredicate();
910 
911   if (isa<PredicateAssume>(PI)) {
912     // If the comparison is true when the operands are equal, then we know the
913     // operands are equal, because assumes must always be true.
914     if (CmpInst::isTrueWhenEqual(Predicate)) {
915       addPredicateUsers(PI, I);
916       return createVariableOrConstant(FirstOp);
917     }
918   }
919   if (const auto *PBranch = dyn_cast<PredicateBranch>(PI)) {
920     // If we are *not* a copy of the comparison, we may equal to the other
921     // operand when the predicate implies something about equality of
922     // operations.  In particular, if the comparison is true/false when the
923     // operands are equal, and we are on the right edge, we know this operation
924     // is equal to something.
925     if ((PBranch->TrueEdge && Predicate == CmpInst::ICMP_EQ) ||
926         (!PBranch->TrueEdge && Predicate == CmpInst::ICMP_NE)) {
927       addPredicateUsers(PI, I);
928       return createVariableOrConstant(FirstOp);
929     }
930     // Handle the special case of floating point.
931     if (((PBranch->TrueEdge && Predicate == CmpInst::FCMP_OEQ) ||
932          (!PBranch->TrueEdge && Predicate == CmpInst::FCMP_UNE)) &&
933         isa<ConstantFP>(FirstOp) && !cast<ConstantFP>(FirstOp)->isZero()) {
934       addPredicateUsers(PI, I);
935       return createConstantExpression(cast<Constant>(FirstOp));
936     }
937   }
938   return nullptr;
939 }
940 
941 // Evaluate read only and pure calls, and create an expression result.
942 const Expression *NewGVN::performSymbolicCallEvaluation(Instruction *I) {
943   auto *CI = cast<CallInst>(I);
944   if (auto *II = dyn_cast<IntrinsicInst>(I)) {
945     // Instrinsics with the returned attribute are copies of arguments.
946     if (auto *ReturnedValue = II->getReturnedArgOperand()) {
947       if (II->getIntrinsicID() == Intrinsic::ssa_copy)
948         if (const auto *Result = performSymbolicPredicateInfoEvaluation(I))
949           return Result;
950       return createVariableOrConstant(ReturnedValue);
951     }
952   }
953   if (AA->doesNotAccessMemory(CI)) {
954     return createCallExpression(CI, nullptr);
955   } else if (AA->onlyReadsMemory(CI)) {
956     MemoryAccess *DefiningAccess = MSSAWalker->getClobberingMemoryAccess(CI);
957     return createCallExpression(CI, lookupMemoryAccessEquiv(DefiningAccess));
958   }
959   return nullptr;
960 }
961 
962 // Update the memory access equivalence table to say that From is equal to To,
963 // and return true if this is different from what already existed in the table.
964 // FIXME: We need to audit all the places that current set a nullptr To, and fix
965 // them. There should always be *some* congruence class, even if it is singular.
966 bool NewGVN::setMemoryAccessEquivTo(MemoryAccess *From, CongruenceClass *To) {
967   DEBUG(dbgs() << "Setting " << *From);
968   if (To) {
969     DEBUG(dbgs() << " equivalent to congruence class ");
970     DEBUG(dbgs() << To->ID << " with current memory access leader ");
971     DEBUG(dbgs() << *To->RepMemoryAccess);
972   } else {
973     DEBUG(dbgs() << " equivalent to itself");
974   }
975   DEBUG(dbgs() << "\n");
976 
977   auto LookupResult = MemoryAccessToClass.find(From);
978   bool Changed = false;
979   // If it's already in the table, see if the value changed.
980   if (LookupResult != MemoryAccessToClass.end()) {
981     if (To && LookupResult->second != To) {
982       // It wasn't equivalent before, and now it is.
983       LookupResult->second = To;
984       Changed = true;
985     } else if (!To) {
986       // It used to be equivalent to something, and now it's not.
987       MemoryAccessToClass.erase(LookupResult);
988       Changed = true;
989     }
990   } else {
991     assert(!To &&
992            "Memory equivalence should never change from nothing to something");
993   }
994 
995   return Changed;
996 }
997 // Evaluate PHI nodes symbolically, and create an expression result.
998 const Expression *NewGVN::performSymbolicPHIEvaluation(Instruction *I) {
999   auto *E = cast<PHIExpression>(createPHIExpression(I));
1000   // We match the semantics of SimplifyPhiNode from InstructionSimplify here.
1001 
1002   // See if all arguaments are the same.
1003   // We track if any were undef because they need special handling.
1004   bool HasUndef = false;
1005   auto Filtered = make_filter_range(E->operands(), [&](const Value *Arg) {
1006     if (Arg == I)
1007       return false;
1008     if (isa<UndefValue>(Arg)) {
1009       HasUndef = true;
1010       return false;
1011     }
1012     return true;
1013   });
1014   // If we are left with no operands, it's undef
1015   if (Filtered.begin() == Filtered.end()) {
1016     DEBUG(dbgs() << "Simplified PHI node " << *I << " to undef"
1017                  << "\n");
1018     E->deallocateOperands(ArgRecycler);
1019     ExpressionAllocator.Deallocate(E);
1020     return createConstantExpression(UndefValue::get(I->getType()));
1021   }
1022   Value *AllSameValue = *(Filtered.begin());
1023   ++Filtered.begin();
1024   // Can't use std::equal here, sadly, because filter.begin moves.
1025   if (llvm::all_of(Filtered, [AllSameValue](const Value *V) {
1026         return V == AllSameValue;
1027       })) {
1028     // In LLVM's non-standard representation of phi nodes, it's possible to have
1029     // phi nodes with cycles (IE dependent on other phis that are .... dependent
1030     // on the original phi node), especially in weird CFG's where some arguments
1031     // are unreachable, or uninitialized along certain paths.  This can cause
1032     // infinite loops during evaluation. We work around this by not trying to
1033     // really evaluate them independently, but instead using a variable
1034     // expression to say if one is equivalent to the other.
1035     // We also special case undef, so that if we have an undef, we can't use the
1036     // common value unless it dominates the phi block.
1037     if (HasUndef) {
1038       // Only have to check for instructions
1039       if (auto *AllSameInst = dyn_cast<Instruction>(AllSameValue))
1040         if (!DT->dominates(AllSameInst, I))
1041           return E;
1042     }
1043 
1044     NumGVNPhisAllSame++;
1045     DEBUG(dbgs() << "Simplified PHI node " << *I << " to " << *AllSameValue
1046                  << "\n");
1047     E->deallocateOperands(ArgRecycler);
1048     ExpressionAllocator.Deallocate(E);
1049     return createVariableOrConstant(AllSameValue);
1050   }
1051   return E;
1052 }
1053 
1054 const Expression *NewGVN::performSymbolicAggrValueEvaluation(Instruction *I) {
1055   if (auto *EI = dyn_cast<ExtractValueInst>(I)) {
1056     auto *II = dyn_cast<IntrinsicInst>(EI->getAggregateOperand());
1057     if (II && EI->getNumIndices() == 1 && *EI->idx_begin() == 0) {
1058       unsigned Opcode = 0;
1059       // EI might be an extract from one of our recognised intrinsics. If it
1060       // is we'll synthesize a semantically equivalent expression instead on
1061       // an extract value expression.
1062       switch (II->getIntrinsicID()) {
1063       case Intrinsic::sadd_with_overflow:
1064       case Intrinsic::uadd_with_overflow:
1065         Opcode = Instruction::Add;
1066         break;
1067       case Intrinsic::ssub_with_overflow:
1068       case Intrinsic::usub_with_overflow:
1069         Opcode = Instruction::Sub;
1070         break;
1071       case Intrinsic::smul_with_overflow:
1072       case Intrinsic::umul_with_overflow:
1073         Opcode = Instruction::Mul;
1074         break;
1075       default:
1076         break;
1077       }
1078 
1079       if (Opcode != 0) {
1080         // Intrinsic recognized. Grab its args to finish building the
1081         // expression.
1082         assert(II->getNumArgOperands() == 2 &&
1083                "Expect two args for recognised intrinsics.");
1084         return createBinaryExpression(
1085             Opcode, EI->getType(), II->getArgOperand(0), II->getArgOperand(1));
1086       }
1087     }
1088   }
1089 
1090   return createAggregateValueExpression(I);
1091 }
1092 const Expression *NewGVN::performSymbolicCmpEvaluation(Instruction *I) {
1093   auto *CI = dyn_cast<CmpInst>(I);
1094   // See if our operands are equal to those of a previous predicate, and if so,
1095   // if it implies true or false.
1096   auto Op0 = lookupOperandLeader(CI->getOperand(0));
1097   auto Op1 = lookupOperandLeader(CI->getOperand(1));
1098   auto OurPredicate = CI->getPredicate();
1099   if (shouldSwapOperands(Op1, Op0)) {
1100     std::swap(Op0, Op1);
1101     OurPredicate = CI->getSwappedPredicate();
1102   }
1103 
1104   // Avoid processing the same info twice
1105   const PredicateBase *LastPredInfo = nullptr;
1106   // See if we know something about the comparison itself, like it is the target
1107   // of an assume.
1108   auto *CmpPI = PredInfo->getPredicateInfoFor(I);
1109   if (dyn_cast_or_null<PredicateAssume>(CmpPI))
1110     return createConstantExpression(ConstantInt::getTrue(CI->getType()));
1111 
1112   if (Op0 == Op1) {
1113     // This condition does not depend on predicates, no need to add users
1114     if (CI->isTrueWhenEqual())
1115       return createConstantExpression(ConstantInt::getTrue(CI->getType()));
1116     else if (CI->isFalseWhenEqual())
1117       return createConstantExpression(ConstantInt::getFalse(CI->getType()));
1118   }
1119 
1120   // NOTE: Because we are comparing both operands here and below, and using
1121   // previous comparisons, we rely on fact that predicateinfo knows to mark
1122   // comparisons that use renamed operands as users of the earlier comparisons.
1123   // It is *not* enough to just mark predicateinfo renamed operands as users of
1124   // the earlier comparisons, because the *other* operand may have changed in a
1125   // previous iteration.
1126   // Example:
1127   // icmp slt %a, %b
1128   // %b.0 = ssa.copy(%b)
1129   // false branch:
1130   // icmp slt %c, %b.0
1131 
1132   // %c and %a may start out equal, and thus, the code below will say the second
1133   // %icmp is false.  c may become equal to something else, and in that case the
1134   // %second icmp *must* be reexamined, but would not if only the renamed
1135   // %operands are considered users of the icmp.
1136 
1137   // *Currently* we only check one level of comparisons back, and only mark one
1138   // level back as touched when changes appen .  If you modify this code to look
1139   // back farther through comparisons, you *must* mark the appropriate
1140   // comparisons as users in PredicateInfo.cpp, or you will cause bugs.  See if
1141   // we know something just from the operands themselves
1142 
1143   // See if our operands have predicate info, so that we may be able to derive
1144   // something from a previous comparison.
1145   for (const auto &Op : CI->operands()) {
1146     auto *PI = PredInfo->getPredicateInfoFor(Op);
1147     if (const auto *PBranch = dyn_cast_or_null<PredicateBranch>(PI)) {
1148       if (PI == LastPredInfo)
1149         continue;
1150       LastPredInfo = PI;
1151 
1152       // TODO: Along the false edge, we may know more things too, like icmp of
1153       // same operands is false.
1154       // TODO: We only handle actual comparison conditions below, not and/or.
1155       auto *BranchCond = dyn_cast<CmpInst>(PBranch->Condition);
1156       if (!BranchCond)
1157         continue;
1158       auto *BranchOp0 = lookupOperandLeader(BranchCond->getOperand(0));
1159       auto *BranchOp1 = lookupOperandLeader(BranchCond->getOperand(1));
1160       auto BranchPredicate = BranchCond->getPredicate();
1161       if (shouldSwapOperands(BranchOp1, BranchOp0)) {
1162         std::swap(BranchOp0, BranchOp1);
1163         BranchPredicate = BranchCond->getSwappedPredicate();
1164       }
1165       if (BranchOp0 == Op0 && BranchOp1 == Op1) {
1166         if (PBranch->TrueEdge) {
1167           // If we know the previous predicate is true and we are in the true
1168           // edge then we may be implied true or false.
1169           if (CmpInst::isImpliedTrueByMatchingCmp(OurPredicate,
1170                                                   BranchPredicate)) {
1171             addPredicateUsers(PI, I);
1172             return createConstantExpression(
1173                 ConstantInt::getTrue(CI->getType()));
1174           }
1175 
1176           if (CmpInst::isImpliedFalseByMatchingCmp(OurPredicate,
1177                                                    BranchPredicate)) {
1178             addPredicateUsers(PI, I);
1179             return createConstantExpression(
1180                 ConstantInt::getFalse(CI->getType()));
1181           }
1182 
1183         } else {
1184           // Just handle the ne and eq cases, where if we have the same
1185           // operands, we may know something.
1186           if (BranchPredicate == OurPredicate) {
1187             addPredicateUsers(PI, I);
1188             // Same predicate, same ops,we know it was false, so this is false.
1189             return createConstantExpression(
1190                 ConstantInt::getFalse(CI->getType()));
1191           } else if (BranchPredicate ==
1192                      CmpInst::getInversePredicate(OurPredicate)) {
1193             addPredicateUsers(PI, I);
1194             // Inverse predicate, we know the other was false, so this is true.
1195             // FIXME: Double check this
1196             return createConstantExpression(
1197                 ConstantInt::getTrue(CI->getType()));
1198           }
1199         }
1200       }
1201     }
1202   }
1203   // Create expression will take care of simplifyCmpInst
1204   return createExpression(I);
1205 }
1206 
1207 // Substitute and symbolize the value before value numbering.
1208 const Expression *NewGVN::performSymbolicEvaluation(Value *V) {
1209   const Expression *E = nullptr;
1210   if (auto *C = dyn_cast<Constant>(V))
1211     E = createConstantExpression(C);
1212   else if (isa<Argument>(V) || isa<GlobalVariable>(V)) {
1213     E = createVariableExpression(V);
1214   } else {
1215     // TODO: memory intrinsics.
1216     // TODO: Some day, we should do the forward propagation and reassociation
1217     // parts of the algorithm.
1218     auto *I = cast<Instruction>(V);
1219     switch (I->getOpcode()) {
1220     case Instruction::ExtractValue:
1221     case Instruction::InsertValue:
1222       E = performSymbolicAggrValueEvaluation(I);
1223       break;
1224     case Instruction::PHI:
1225       E = performSymbolicPHIEvaluation(I);
1226       break;
1227     case Instruction::Call:
1228       E = performSymbolicCallEvaluation(I);
1229       break;
1230     case Instruction::Store:
1231       E = performSymbolicStoreEvaluation(I);
1232       break;
1233     case Instruction::Load:
1234       E = performSymbolicLoadEvaluation(I);
1235       break;
1236     case Instruction::BitCast: {
1237       E = createExpression(I);
1238     } break;
1239     case Instruction::ICmp:
1240     case Instruction::FCmp: {
1241       E = performSymbolicCmpEvaluation(I);
1242     } break;
1243     case Instruction::Add:
1244     case Instruction::FAdd:
1245     case Instruction::Sub:
1246     case Instruction::FSub:
1247     case Instruction::Mul:
1248     case Instruction::FMul:
1249     case Instruction::UDiv:
1250     case Instruction::SDiv:
1251     case Instruction::FDiv:
1252     case Instruction::URem:
1253     case Instruction::SRem:
1254     case Instruction::FRem:
1255     case Instruction::Shl:
1256     case Instruction::LShr:
1257     case Instruction::AShr:
1258     case Instruction::And:
1259     case Instruction::Or:
1260     case Instruction::Xor:
1261     case Instruction::Trunc:
1262     case Instruction::ZExt:
1263     case Instruction::SExt:
1264     case Instruction::FPToUI:
1265     case Instruction::FPToSI:
1266     case Instruction::UIToFP:
1267     case Instruction::SIToFP:
1268     case Instruction::FPTrunc:
1269     case Instruction::FPExt:
1270     case Instruction::PtrToInt:
1271     case Instruction::IntToPtr:
1272     case Instruction::Select:
1273     case Instruction::ExtractElement:
1274     case Instruction::InsertElement:
1275     case Instruction::ShuffleVector:
1276     case Instruction::GetElementPtr:
1277       E = createExpression(I);
1278       break;
1279     default:
1280       return nullptr;
1281     }
1282   }
1283   return E;
1284 }
1285 
1286 void NewGVN::markUsersTouched(Value *V) {
1287   // Now mark the users as touched.
1288   for (auto *User : V->users()) {
1289     assert(isa<Instruction>(User) && "Use of value not within an instruction?");
1290     TouchedInstructions.set(InstrDFS.lookup(User));
1291   }
1292 }
1293 
1294 void NewGVN::markMemoryUsersTouched(MemoryAccess *MA) {
1295   for (auto U : MA->users()) {
1296     if (auto *MUD = dyn_cast<MemoryUseOrDef>(U))
1297       TouchedInstructions.set(InstrDFS.lookup(MUD->getMemoryInst()));
1298     else
1299       TouchedInstructions.set(InstrDFS.lookup(U));
1300   }
1301 }
1302 
1303 // Add I to the set of users of a given predicate.
1304 void NewGVN::addPredicateUsers(const PredicateBase *PB, Instruction *I) {
1305   if (auto *PBranch = dyn_cast<PredicateBranch>(PB))
1306     PredicateToUsers[PBranch->Condition].insert(I);
1307   else if (auto *PAssume = dyn_cast<PredicateBranch>(PB))
1308     PredicateToUsers[PAssume->Condition].insert(I);
1309 }
1310 
1311 // Touch all the predicates that depend on this instruction.
1312 void NewGVN::markPredicateUsersTouched(Instruction *I) {
1313   const auto Result = PredicateToUsers.find(I);
1314   if (Result != PredicateToUsers.end())
1315     for (auto *User : Result->second)
1316       TouchedInstructions.set(InstrDFS.lookup(User));
1317 }
1318 
1319 // Touch the instructions that need to be updated after a congruence class has a
1320 // leader change, and mark changed values.
1321 void NewGVN::markLeaderChangeTouched(CongruenceClass *CC) {
1322   for (auto M : CC->Members) {
1323     if (auto *I = dyn_cast<Instruction>(M))
1324       TouchedInstructions.set(InstrDFS.lookup(I));
1325     LeaderChanges.insert(M);
1326   }
1327 }
1328 
1329 // Move a value, currently in OldClass, to be part of NewClass
1330 // Update OldClass for the move (including changing leaders, etc)
1331 void NewGVN::moveValueToNewCongruenceClass(Instruction *I,
1332                                            CongruenceClass *OldClass,
1333                                            CongruenceClass *NewClass) {
1334   DEBUG(dbgs() << "New congruence class for " << I << " is " << NewClass->ID
1335                << "\n");
1336 
1337   if (I == OldClass->NextLeader.first)
1338     OldClass->NextLeader = {nullptr, ~0U};
1339 
1340   // It's possible, though unlikely, for us to discover equivalences such
1341   // that the current leader does not dominate the old one.
1342   // This statistic tracks how often this happens.
1343   // We assert on phi nodes when this happens, currently, for debugging, because
1344   // we want to make sure we name phi node cycles properly.
1345   if (isa<Instruction>(NewClass->RepLeader) && NewClass->RepLeader &&
1346       I != NewClass->RepLeader &&
1347       DT->properlyDominates(
1348           I->getParent(),
1349           cast<Instruction>(NewClass->RepLeader)->getParent())) {
1350     ++NumGVNNotMostDominatingLeader;
1351     assert(!isa<PHINode>(I) &&
1352            "New class for instruction should not be dominated by instruction");
1353   }
1354 
1355   if (NewClass->RepLeader != I) {
1356     auto DFSNum = InstrDFS.lookup(I);
1357     if (DFSNum < NewClass->NextLeader.second)
1358       NewClass->NextLeader = {I, DFSNum};
1359   }
1360 
1361   OldClass->Members.erase(I);
1362   NewClass->Members.insert(I);
1363   MemoryAccess *StoreAccess = nullptr;
1364   if (auto *SI = dyn_cast<StoreInst>(I)) {
1365     StoreAccess = MSSA->getMemoryAccess(SI);
1366     --OldClass->StoreCount;
1367     assert(OldClass->StoreCount >= 0);
1368     ++NewClass->StoreCount;
1369     assert(NewClass->StoreCount > 0);
1370     if (!NewClass->RepMemoryAccess) {
1371       // If we don't have a representative memory access, it better be the only
1372       // store in there.
1373       assert(NewClass->StoreCount == 1);
1374       NewClass->RepMemoryAccess = StoreAccess;
1375     }
1376     setMemoryAccessEquivTo(StoreAccess, NewClass);
1377   }
1378 
1379   ValueToClass[I] = NewClass;
1380   // See if we destroyed the class or need to swap leaders.
1381   if (OldClass->Members.empty() && OldClass != InitialClass) {
1382     if (OldClass->DefiningExpr) {
1383       OldClass->Dead = true;
1384       DEBUG(dbgs() << "Erasing expression " << OldClass->DefiningExpr
1385                    << " from table\n");
1386       ExpressionToClass.erase(OldClass->DefiningExpr);
1387     }
1388   } else if (OldClass->RepLeader == I) {
1389     // When the leader changes, the value numbering of
1390     // everything may change due to symbolization changes, so we need to
1391     // reprocess.
1392     DEBUG(dbgs() << "Leader change!\n");
1393     ++NumGVNLeaderChanges;
1394     // Destroy the stored value if there are no more stores to represent it.
1395     if (OldClass->StoreCount == 0) {
1396       if (OldClass->RepStoredValue != nullptr)
1397         OldClass->RepStoredValue = nullptr;
1398       if (OldClass->RepMemoryAccess != nullptr)
1399         OldClass->RepMemoryAccess = nullptr;
1400     }
1401 
1402     // If we destroy the old access leader, we have to effectively destroy the
1403     // congruence class.  When it comes to scalars, anything with the same value
1404     // is as good as any other.  That means that one leader is as good as
1405     // another, and as long as you have some leader for the value, you are
1406     // good.. When it comes to *memory states*, only one particular thing really
1407     // represents the definition of a given memory state.  Once it goes away, we
1408     // need to re-evaluate which pieces of memory are really still
1409     // equivalent. The best way to do this is to re-value number things.  The
1410     // only way to really make that happen is to destroy the rest of the class.
1411     // In order to effectively destroy the class, we reset ExpressionToClass for
1412     // each by using the ValueToExpression mapping.  The members later get
1413     // marked as touched due to the leader change.  We will create new
1414     // congruence classes, and the pieces that are still equivalent will end
1415     // back together in a new class.  If this becomes too expensive, it is
1416     // possible to use a versioning scheme for the congruence classes to avoid
1417     // the expressions finding this old class.
1418     if (OldClass->StoreCount > 0 && OldClass->RepMemoryAccess == StoreAccess) {
1419       DEBUG(dbgs() << "Kicking everything out of class " << OldClass->ID
1420                    << " because memory access leader changed");
1421       for (auto Member : OldClass->Members)
1422         ExpressionToClass.erase(ValueToExpression.lookup(Member));
1423     }
1424 
1425     // We don't need to sort members if there is only 1, and we don't care about
1426     // sorting the INITIAL class because everything either gets out of it or is
1427     // unreachable.
1428     if (OldClass->Members.size() == 1 || OldClass == InitialClass) {
1429       OldClass->RepLeader = *(OldClass->Members.begin());
1430     } else if (OldClass->NextLeader.first) {
1431       ++NumGVNAvoidedSortedLeaderChanges;
1432       OldClass->RepLeader = OldClass->NextLeader.first;
1433       OldClass->NextLeader = {nullptr, ~0U};
1434     } else {
1435       ++NumGVNSortedLeaderChanges;
1436       // TODO: If this ends up to slow, we can maintain a dual structure for
1437       // member testing/insertion, or keep things mostly sorted, and sort only
1438       // here, or ....
1439       std::pair<Value *, unsigned> MinDFS = {nullptr, ~0U};
1440       for (const auto X : OldClass->Members) {
1441         auto DFSNum = InstrDFS.lookup(X);
1442         if (DFSNum < MinDFS.second)
1443           MinDFS = {X, DFSNum};
1444       }
1445       OldClass->RepLeader = MinDFS.first;
1446     }
1447     markLeaderChangeTouched(OldClass);
1448   }
1449 }
1450 
1451 // Perform congruence finding on a given value numbering expression.
1452 void NewGVN::performCongruenceFinding(Instruction *I, const Expression *E) {
1453   ValueToExpression[I] = E;
1454   // This is guaranteed to return something, since it will at least find
1455   // TOP.
1456 
1457   CongruenceClass *IClass = ValueToClass[I];
1458   assert(IClass && "Should have found a IClass");
1459   // Dead classes should have been eliminated from the mapping.
1460   assert(!IClass->Dead && "Found a dead class");
1461 
1462   CongruenceClass *EClass;
1463   if (const auto *VE = dyn_cast<VariableExpression>(E)) {
1464     EClass = ValueToClass[VE->getVariableValue()];
1465   } else {
1466     auto lookupResult = ExpressionToClass.insert({E, nullptr});
1467 
1468     // If it's not in the value table, create a new congruence class.
1469     if (lookupResult.second) {
1470       CongruenceClass *NewClass = createCongruenceClass(nullptr, E);
1471       auto place = lookupResult.first;
1472       place->second = NewClass;
1473 
1474       // Constants and variables should always be made the leader.
1475       if (const auto *CE = dyn_cast<ConstantExpression>(E)) {
1476         NewClass->RepLeader = CE->getConstantValue();
1477       } else if (const auto *SE = dyn_cast<StoreExpression>(E)) {
1478         StoreInst *SI = SE->getStoreInst();
1479         NewClass->RepLeader = SI;
1480         NewClass->RepStoredValue = lookupOperandLeader(SI->getValueOperand());
1481         // The RepMemoryAccess field will be filled in properly by the
1482         // moveValueToNewCongruenceClass call.
1483       } else {
1484         NewClass->RepLeader = I;
1485       }
1486       assert(!isa<VariableExpression>(E) &&
1487              "VariableExpression should have been handled already");
1488 
1489       EClass = NewClass;
1490       DEBUG(dbgs() << "Created new congruence class for " << *I
1491                    << " using expression " << *E << " at " << NewClass->ID
1492                    << " and leader " << *(NewClass->RepLeader));
1493       if (NewClass->RepStoredValue)
1494         DEBUG(dbgs() << " and stored value " << *(NewClass->RepStoredValue));
1495       DEBUG(dbgs() << "\n");
1496       DEBUG(dbgs() << "Hash value was " << E->getHashValue() << "\n");
1497     } else {
1498       EClass = lookupResult.first->second;
1499       if (isa<ConstantExpression>(E))
1500         assert(isa<Constant>(EClass->RepLeader) &&
1501                "Any class with a constant expression should have a "
1502                "constant leader");
1503 
1504       assert(EClass && "Somehow don't have an eclass");
1505 
1506       assert(!EClass->Dead && "We accidentally looked up a dead class");
1507     }
1508   }
1509   bool ClassChanged = IClass != EClass;
1510   bool LeaderChanged = LeaderChanges.erase(I);
1511   if (ClassChanged || LeaderChanged) {
1512     DEBUG(dbgs() << "Found class " << EClass->ID << " for expression " << E
1513                  << "\n");
1514 
1515     if (ClassChanged)
1516       moveValueToNewCongruenceClass(I, IClass, EClass);
1517     markUsersTouched(I);
1518     if (MemoryAccess *MA = MSSA->getMemoryAccess(I))
1519       markMemoryUsersTouched(MA);
1520     if (auto *CI = dyn_cast<CmpInst>(I))
1521       markPredicateUsersTouched(CI);
1522   }
1523 }
1524 
1525 // Process the fact that Edge (from, to) is reachable, including marking
1526 // any newly reachable blocks and instructions for processing.
1527 void NewGVN::updateReachableEdge(BasicBlock *From, BasicBlock *To) {
1528   // Check if the Edge was reachable before.
1529   if (ReachableEdges.insert({From, To}).second) {
1530     // If this block wasn't reachable before, all instructions are touched.
1531     if (ReachableBlocks.insert(To).second) {
1532       DEBUG(dbgs() << "Block " << getBlockName(To) << " marked reachable\n");
1533       const auto &InstRange = BlockInstRange.lookup(To);
1534       TouchedInstructions.set(InstRange.first, InstRange.second);
1535     } else {
1536       DEBUG(dbgs() << "Block " << getBlockName(To)
1537                    << " was reachable, but new edge {" << getBlockName(From)
1538                    << "," << getBlockName(To) << "} to it found\n");
1539 
1540       // We've made an edge reachable to an existing block, which may
1541       // impact predicates. Otherwise, only mark the phi nodes as touched, as
1542       // they are the only thing that depend on new edges. Anything using their
1543       // values will get propagated to if necessary.
1544       if (MemoryAccess *MemPhi = MSSA->getMemoryAccess(To))
1545         TouchedInstructions.set(InstrDFS.lookup(MemPhi));
1546 
1547       auto BI = To->begin();
1548       while (isa<PHINode>(BI)) {
1549         TouchedInstructions.set(InstrDFS.lookup(&*BI));
1550         ++BI;
1551       }
1552     }
1553   }
1554 }
1555 
1556 // Given a predicate condition (from a switch, cmp, or whatever) and a block,
1557 // see if we know some constant value for it already.
1558 Value *NewGVN::findConditionEquivalence(Value *Cond) const {
1559   auto Result = lookupOperandLeader(Cond);
1560   if (isa<Constant>(Result))
1561     return Result;
1562   return nullptr;
1563 }
1564 
1565 // Process the outgoing edges of a block for reachability.
1566 void NewGVN::processOutgoingEdges(TerminatorInst *TI, BasicBlock *B) {
1567   // Evaluate reachability of terminator instruction.
1568   BranchInst *BR;
1569   if ((BR = dyn_cast<BranchInst>(TI)) && BR->isConditional()) {
1570     Value *Cond = BR->getCondition();
1571     Value *CondEvaluated = findConditionEquivalence(Cond);
1572     if (!CondEvaluated) {
1573       if (auto *I = dyn_cast<Instruction>(Cond)) {
1574         const Expression *E = createExpression(I);
1575         if (const auto *CE = dyn_cast<ConstantExpression>(E)) {
1576           CondEvaluated = CE->getConstantValue();
1577         }
1578       } else if (isa<ConstantInt>(Cond)) {
1579         CondEvaluated = Cond;
1580       }
1581     }
1582     ConstantInt *CI;
1583     BasicBlock *TrueSucc = BR->getSuccessor(0);
1584     BasicBlock *FalseSucc = BR->getSuccessor(1);
1585     if (CondEvaluated && (CI = dyn_cast<ConstantInt>(CondEvaluated))) {
1586       if (CI->isOne()) {
1587         DEBUG(dbgs() << "Condition for Terminator " << *TI
1588                      << " evaluated to true\n");
1589         updateReachableEdge(B, TrueSucc);
1590       } else if (CI->isZero()) {
1591         DEBUG(dbgs() << "Condition for Terminator " << *TI
1592                      << " evaluated to false\n");
1593         updateReachableEdge(B, FalseSucc);
1594       }
1595     } else {
1596       updateReachableEdge(B, TrueSucc);
1597       updateReachableEdge(B, FalseSucc);
1598     }
1599   } else if (auto *SI = dyn_cast<SwitchInst>(TI)) {
1600     // For switches, propagate the case values into the case
1601     // destinations.
1602 
1603     // Remember how many outgoing edges there are to every successor.
1604     SmallDenseMap<BasicBlock *, unsigned, 16> SwitchEdges;
1605 
1606     Value *SwitchCond = SI->getCondition();
1607     Value *CondEvaluated = findConditionEquivalence(SwitchCond);
1608     // See if we were able to turn this switch statement into a constant.
1609     if (CondEvaluated && isa<ConstantInt>(CondEvaluated)) {
1610       auto *CondVal = cast<ConstantInt>(CondEvaluated);
1611       // We should be able to get case value for this.
1612       auto CaseVal = SI->findCaseValue(CondVal);
1613       if (CaseVal.getCaseSuccessor() == SI->getDefaultDest()) {
1614         // We proved the value is outside of the range of the case.
1615         // We can't do anything other than mark the default dest as reachable,
1616         // and go home.
1617         updateReachableEdge(B, SI->getDefaultDest());
1618         return;
1619       }
1620       // Now get where it goes and mark it reachable.
1621       BasicBlock *TargetBlock = CaseVal.getCaseSuccessor();
1622       updateReachableEdge(B, TargetBlock);
1623     } else {
1624       for (unsigned i = 0, e = SI->getNumSuccessors(); i != e; ++i) {
1625         BasicBlock *TargetBlock = SI->getSuccessor(i);
1626         ++SwitchEdges[TargetBlock];
1627         updateReachableEdge(B, TargetBlock);
1628       }
1629     }
1630   } else {
1631     // Otherwise this is either unconditional, or a type we have no
1632     // idea about. Just mark successors as reachable.
1633     for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
1634       BasicBlock *TargetBlock = TI->getSuccessor(i);
1635       updateReachableEdge(B, TargetBlock);
1636     }
1637 
1638     // This also may be a memory defining terminator, in which case, set it
1639     // equivalent to nothing.
1640     if (MemoryAccess *MA = MSSA->getMemoryAccess(TI))
1641       setMemoryAccessEquivTo(MA, nullptr);
1642   }
1643 }
1644 
1645 // The algorithm initially places the values of the routine in the INITIAL
1646 // congruence class. The leader of INITIAL is the undetermined value `TOP`.
1647 // When the algorithm has finished, values still in INITIAL are unreachable.
1648 void NewGVN::initializeCongruenceClasses(Function &F) {
1649   // FIXME now i can't remember why this is 2
1650   NextCongruenceNum = 2;
1651   // Initialize all other instructions to be in INITIAL class.
1652   CongruenceClass::MemberSet InitialValues;
1653   InitialClass = createCongruenceClass(nullptr, nullptr);
1654   InitialClass->RepMemoryAccess = MSSA->getLiveOnEntryDef();
1655   for (auto &B : F) {
1656     if (auto *MP = MSSA->getMemoryAccess(&B))
1657       MemoryAccessToClass[MP] = InitialClass;
1658 
1659     for (auto &I : B) {
1660       // Don't insert void terminators into the class. We don't value number
1661       // them, and they just end up sitting in INITIAL.
1662       if (isa<TerminatorInst>(I) && I.getType()->isVoidTy())
1663         continue;
1664       InitialValues.insert(&I);
1665       ValueToClass[&I] = InitialClass;
1666 
1667       // All memory accesses are equivalent to live on entry to start. They must
1668       // be initialized to something so that initial changes are noticed. For
1669       // the maximal answer, we initialize them all to be the same as
1670       // liveOnEntry.  Note that to save time, we only initialize the
1671       // MemoryDef's for stores and all MemoryPhis to be equal.  Right now, no
1672       // other expression can generate a memory equivalence.  If we start
1673       // handling memcpy/etc, we can expand this.
1674       if (isa<StoreInst>(&I)) {
1675         MemoryAccessToClass[MSSA->getMemoryAccess(&I)] = InitialClass;
1676         ++InitialClass->StoreCount;
1677         assert(InitialClass->StoreCount > 0);
1678       }
1679     }
1680   }
1681   InitialClass->Members.swap(InitialValues);
1682 
1683   // Initialize arguments to be in their own unique congruence classes
1684   for (auto &FA : F.args())
1685     createSingletonCongruenceClass(&FA);
1686 }
1687 
1688 void NewGVN::cleanupTables() {
1689   for (unsigned i = 0, e = CongruenceClasses.size(); i != e; ++i) {
1690     DEBUG(dbgs() << "Congruence class " << CongruenceClasses[i]->ID << " has "
1691                  << CongruenceClasses[i]->Members.size() << " members\n");
1692     // Make sure we delete the congruence class (probably worth switching to
1693     // a unique_ptr at some point.
1694     delete CongruenceClasses[i];
1695     CongruenceClasses[i] = nullptr;
1696   }
1697 
1698   ValueToClass.clear();
1699   ArgRecycler.clear(ExpressionAllocator);
1700   ExpressionAllocator.Reset();
1701   CongruenceClasses.clear();
1702   ExpressionToClass.clear();
1703   ValueToExpression.clear();
1704   ReachableBlocks.clear();
1705   ReachableEdges.clear();
1706 #ifndef NDEBUG
1707   ProcessedCount.clear();
1708 #endif
1709   InstrDFS.clear();
1710   InstructionsToErase.clear();
1711 
1712   DFSToInstr.clear();
1713   BlockInstRange.clear();
1714   TouchedInstructions.clear();
1715   DominatedInstRange.clear();
1716   MemoryAccessToClass.clear();
1717   PredicateToUsers.clear();
1718 }
1719 
1720 std::pair<unsigned, unsigned> NewGVN::assignDFSNumbers(BasicBlock *B,
1721                                                        unsigned Start) {
1722   unsigned End = Start;
1723   if (MemoryAccess *MemPhi = MSSA->getMemoryAccess(B)) {
1724     InstrDFS[MemPhi] = End++;
1725     DFSToInstr.emplace_back(MemPhi);
1726   }
1727 
1728   for (auto &I : *B) {
1729     InstrDFS[&I] = End++;
1730     DFSToInstr.emplace_back(&I);
1731   }
1732 
1733   // All of the range functions taken half-open ranges (open on the end side).
1734   // So we do not subtract one from count, because at this point it is one
1735   // greater than the last instruction.
1736   return std::make_pair(Start, End);
1737 }
1738 
1739 void NewGVN::updateProcessedCount(Value *V) {
1740 #ifndef NDEBUG
1741   if (ProcessedCount.count(V) == 0) {
1742     ProcessedCount.insert({V, 1});
1743   } else {
1744     ++ProcessedCount[V];
1745     assert(ProcessedCount[V] < 100 &&
1746            "Seem to have processed the same Value a lot");
1747   }
1748 #endif
1749 }
1750 // Evaluate MemoryPhi nodes symbolically, just like PHI nodes
1751 void NewGVN::valueNumberMemoryPhi(MemoryPhi *MP) {
1752   // If all the arguments are the same, the MemoryPhi has the same value as the
1753   // argument.
1754   // Filter out unreachable blocks and self phis from our operands.
1755   auto Filtered = make_filter_range(MP->operands(), [&](const Use &U) {
1756     return lookupMemoryAccessEquiv(cast<MemoryAccess>(U)) != MP &&
1757            !isMemoryAccessTop(cast<MemoryAccess>(U)) &&
1758            ReachableBlocks.count(MP->getIncomingBlock(U));
1759   });
1760   // If all that is left is nothing, our memoryphi is undef. We keep it as
1761   // InitialClass.  Note: The only case this should happen is if we have at
1762   // least one self-argument.
1763   if (Filtered.begin() == Filtered.end()) {
1764     if (setMemoryAccessEquivTo(MP, InitialClass))
1765       markMemoryUsersTouched(MP);
1766     return;
1767   }
1768 
1769   // Transform the remaining operands into operand leaders.
1770   // FIXME: mapped_iterator should have a range version.
1771   auto LookupFunc = [&](const Use &U) {
1772     return lookupMemoryAccessEquiv(cast<MemoryAccess>(U));
1773   };
1774   auto MappedBegin = map_iterator(Filtered.begin(), LookupFunc);
1775   auto MappedEnd = map_iterator(Filtered.end(), LookupFunc);
1776 
1777   // and now check if all the elements are equal.
1778   // Sadly, we can't use std::equals since these are random access iterators.
1779   MemoryAccess *AllSameValue = *MappedBegin;
1780   ++MappedBegin;
1781   bool AllEqual = std::all_of(
1782       MappedBegin, MappedEnd,
1783       [&AllSameValue](const MemoryAccess *V) { return V == AllSameValue; });
1784 
1785   if (AllEqual)
1786     DEBUG(dbgs() << "Memory Phi value numbered to " << *AllSameValue << "\n");
1787   else
1788     DEBUG(dbgs() << "Memory Phi value numbered to itself\n");
1789 
1790   if (setMemoryAccessEquivTo(
1791           MP, AllEqual ? MemoryAccessToClass.lookup(AllSameValue) : nullptr))
1792     markMemoryUsersTouched(MP);
1793 }
1794 
1795 // Value number a single instruction, symbolically evaluating, performing
1796 // congruence finding, and updating mappings.
1797 void NewGVN::valueNumberInstruction(Instruction *I) {
1798   DEBUG(dbgs() << "Processing instruction " << *I << "\n");
1799 
1800   // There's no need to call isInstructionTriviallyDead more than once on
1801   // an instruction. Therefore, once we know that an instruction is dead
1802   // we change its DFS number so that it doesn't get numbered again.
1803   if (InstrDFS[I] != 0 && isInstructionTriviallyDead(I, TLI)) {
1804     InstrDFS[I] = 0;
1805     DEBUG(dbgs() << "Skipping unused instruction\n");
1806     markInstructionForDeletion(I);
1807     return;
1808   }
1809   if (!I->isTerminator()) {
1810     const auto *Symbolized = performSymbolicEvaluation(I);
1811     // If we couldn't come up with a symbolic expression, use the unknown
1812     // expression
1813     if (Symbolized == nullptr)
1814       Symbolized = createUnknownExpression(I);
1815     performCongruenceFinding(I, Symbolized);
1816   } else {
1817     // Handle terminators that return values. All of them produce values we
1818     // don't currently understand.  We don't place non-value producing
1819     // terminators in a class.
1820     if (!I->getType()->isVoidTy()) {
1821       auto *Symbolized = createUnknownExpression(I);
1822       performCongruenceFinding(I, Symbolized);
1823     }
1824     processOutgoingEdges(dyn_cast<TerminatorInst>(I), I->getParent());
1825   }
1826 }
1827 
1828 // Check if there is a path, using single or equal argument phi nodes, from
1829 // First to Second.
1830 bool NewGVN::singleReachablePHIPath(const MemoryAccess *First,
1831                                     const MemoryAccess *Second) const {
1832   if (First == Second)
1833     return true;
1834 
1835   if (auto *FirstDef = dyn_cast<MemoryUseOrDef>(First)) {
1836     auto *DefAccess = FirstDef->getDefiningAccess();
1837     return singleReachablePHIPath(DefAccess, Second);
1838   } else {
1839     auto *MP = cast<MemoryPhi>(First);
1840     auto ReachableOperandPred = [&](const Use &U) {
1841       return ReachableBlocks.count(MP->getIncomingBlock(U));
1842     };
1843     auto FilteredPhiArgs =
1844         make_filter_range(MP->operands(), ReachableOperandPred);
1845     SmallVector<const Value *, 32> OperandList;
1846     std::copy(FilteredPhiArgs.begin(), FilteredPhiArgs.end(),
1847               std::back_inserter(OperandList));
1848     bool Okay = OperandList.size() == 1;
1849     if (!Okay)
1850       Okay = std::equal(OperandList.begin(), OperandList.end(),
1851                         OperandList.begin());
1852     if (Okay)
1853       return singleReachablePHIPath(cast<MemoryAccess>(OperandList[0]), Second);
1854     return false;
1855   }
1856 }
1857 
1858 // Verify the that the memory equivalence table makes sense relative to the
1859 // congruence classes.  Note that this checking is not perfect, and is currently
1860 // subject to very rare false negatives. It is only useful for
1861 // testing/debugging.
1862 void NewGVN::verifyMemoryCongruency() const {
1863   // Anything equivalent in the memory access table should be in the same
1864   // congruence class.
1865 
1866   // Filter out the unreachable and trivially dead entries, because they may
1867   // never have been updated if the instructions were not processed.
1868   auto ReachableAccessPred =
1869       [&](const std::pair<const MemoryAccess *, CongruenceClass *> Pair) {
1870         bool Result = ReachableBlocks.count(Pair.first->getBlock());
1871         if (!Result)
1872           return false;
1873         if (auto *MemDef = dyn_cast<MemoryDef>(Pair.first))
1874           return !isInstructionTriviallyDead(MemDef->getMemoryInst());
1875         return true;
1876       };
1877 
1878   auto Filtered = make_filter_range(MemoryAccessToClass, ReachableAccessPred);
1879   for (auto KV : Filtered) {
1880     // Unreachable instructions may not have changed because we never process
1881     // them.
1882     if (!ReachableBlocks.count(KV.first->getBlock()))
1883       continue;
1884     if (auto *FirstMUD = dyn_cast<MemoryUseOrDef>(KV.first)) {
1885       auto *SecondMUD = dyn_cast<MemoryUseOrDef>(KV.second->RepMemoryAccess);
1886       if (FirstMUD && SecondMUD)
1887         assert((singleReachablePHIPath(FirstMUD, SecondMUD) ||
1888                 ValueToClass.lookup(FirstMUD->getMemoryInst()) ==
1889                     ValueToClass.lookup(SecondMUD->getMemoryInst())) &&
1890                "The instructions for these memory operations should have "
1891                "been in the same congruence class or reachable through"
1892                "a single argument phi");
1893     } else if (auto *FirstMP = dyn_cast<MemoryPhi>(KV.first)) {
1894 
1895       // We can only sanely verify that MemoryDefs in the operand list all have
1896       // the same class.
1897       auto ReachableOperandPred = [&](const Use &U) {
1898         return ReachableBlocks.count(FirstMP->getIncomingBlock(U)) &&
1899                isa<MemoryDef>(U);
1900 
1901       };
1902       // All arguments should in the same class, ignoring unreachable arguments
1903       auto FilteredPhiArgs =
1904           make_filter_range(FirstMP->operands(), ReachableOperandPred);
1905       SmallVector<const CongruenceClass *, 16> PhiOpClasses;
1906       std::transform(FilteredPhiArgs.begin(), FilteredPhiArgs.end(),
1907                      std::back_inserter(PhiOpClasses), [&](const Use &U) {
1908                        const MemoryDef *MD = cast<MemoryDef>(U);
1909                        return ValueToClass.lookup(MD->getMemoryInst());
1910                      });
1911       assert(std::equal(PhiOpClasses.begin(), PhiOpClasses.end(),
1912                         PhiOpClasses.begin()) &&
1913              "All MemoryPhi arguments should be in the same class");
1914     }
1915   }
1916 }
1917 
1918 // Re-evaluate all the comparisons after value numbering and ensure they don't
1919 // change. If they changed, we didn't mark them touched properly.
1920 void NewGVN::verifyComparisons(Function &F) {
1921 #ifndef NDEBUG
1922   for (auto &BB : F) {
1923     if (!ReachableBlocks.count(&BB))
1924       continue;
1925     for (auto &I : BB) {
1926       if (InstructionsToErase.count(&I))
1927         continue;
1928       if (isa<CmpInst>(&I)) {
1929         auto *CurrentVal = ValueToClass.lookup(&I);
1930         valueNumberInstruction(&I);
1931         assert(CurrentVal == ValueToClass.lookup(&I) &&
1932                "Re-evaluating comparison changed value");
1933       }
1934     }
1935   }
1936 #endif
1937 }
1938 
1939 // This is the main transformation entry point.
1940 bool NewGVN::runGVN(Function &F, DominatorTree *_DT, AssumptionCache *_AC,
1941                     TargetLibraryInfo *_TLI, AliasAnalysis *_AA,
1942                     MemorySSA *_MSSA) {
1943   bool Changed = false;
1944   NumFuncArgs = F.arg_size();
1945   DT = _DT;
1946   AC = _AC;
1947   TLI = _TLI;
1948   AA = _AA;
1949   MSSA = _MSSA;
1950   PredInfo = make_unique<PredicateInfo>(F, *DT, *AC);
1951   DL = &F.getParent()->getDataLayout();
1952   MSSAWalker = MSSA->getWalker();
1953 
1954   // Count number of instructions for sizing of hash tables, and come
1955   // up with a global dfs numbering for instructions.
1956   unsigned ICount = 1;
1957   // Add an empty instruction to account for the fact that we start at 1
1958   DFSToInstr.emplace_back(nullptr);
1959   // Note: We want ideal RPO traversal of the blocks, which is not quite the
1960   // same as dominator tree order, particularly with regard whether backedges
1961   // get visited first or second, given a block with multiple successors.
1962   // If we visit in the wrong order, we will end up performing N times as many
1963   // iterations.
1964   // The dominator tree does guarantee that, for a given dom tree node, it's
1965   // parent must occur before it in the RPO ordering. Thus, we only need to sort
1966   // the siblings.
1967   DenseMap<const DomTreeNode *, unsigned> RPOOrdering;
1968   ReversePostOrderTraversal<Function *> RPOT(&F);
1969   unsigned Counter = 0;
1970   for (auto &B : RPOT) {
1971     auto *Node = DT->getNode(B);
1972     assert(Node && "RPO and Dominator tree should have same reachability");
1973     RPOOrdering[Node] = ++Counter;
1974   }
1975   // Sort dominator tree children arrays into RPO.
1976   for (auto &B : RPOT) {
1977     auto *Node = DT->getNode(B);
1978     if (Node->getChildren().size() > 1)
1979       std::sort(Node->begin(), Node->end(),
1980                 [&RPOOrdering](const DomTreeNode *A, const DomTreeNode *B) {
1981                   return RPOOrdering[A] < RPOOrdering[B];
1982                 });
1983   }
1984 
1985   // Now a standard depth first ordering of the domtree is equivalent to RPO.
1986   auto DFI = df_begin(DT->getRootNode());
1987   for (auto DFE = df_end(DT->getRootNode()); DFI != DFE; ++DFI) {
1988     BasicBlock *B = DFI->getBlock();
1989     const auto &BlockRange = assignDFSNumbers(B, ICount);
1990     BlockInstRange.insert({B, BlockRange});
1991     ICount += BlockRange.second - BlockRange.first;
1992   }
1993 
1994   // Handle forward unreachable blocks and figure out which blocks
1995   // have single preds.
1996   for (auto &B : F) {
1997     // Assign numbers to unreachable blocks.
1998     if (!DFI.nodeVisited(DT->getNode(&B))) {
1999       const auto &BlockRange = assignDFSNumbers(&B, ICount);
2000       BlockInstRange.insert({&B, BlockRange});
2001       ICount += BlockRange.second - BlockRange.first;
2002     }
2003   }
2004 
2005   TouchedInstructions.resize(ICount);
2006   DominatedInstRange.reserve(F.size());
2007   // Ensure we don't end up resizing the expressionToClass map, as
2008   // that can be quite expensive. At most, we have one expression per
2009   // instruction.
2010   ExpressionToClass.reserve(ICount);
2011 
2012   // Initialize the touched instructions to include the entry block.
2013   const auto &InstRange = BlockInstRange.lookup(&F.getEntryBlock());
2014   TouchedInstructions.set(InstRange.first, InstRange.second);
2015   ReachableBlocks.insert(&F.getEntryBlock());
2016 
2017   initializeCongruenceClasses(F);
2018 
2019   unsigned int Iterations = 0;
2020   // We start out in the entry block.
2021   BasicBlock *LastBlock = &F.getEntryBlock();
2022   while (TouchedInstructions.any()) {
2023     ++Iterations;
2024     // Walk through all the instructions in all the blocks in RPO.
2025     // TODO: As we hit a new block, we should push and pop equalities into a
2026     // table lookupOperandLeader can use, to catch things PredicateInfo
2027     // might miss, like edge-only equivalences.
2028     for (int InstrNum = TouchedInstructions.find_first(); InstrNum != -1;
2029          InstrNum = TouchedInstructions.find_next(InstrNum)) {
2030 
2031       // This instruction was found to be dead. We don't bother looking
2032       // at it again.
2033       if (InstrNum == 0) {
2034         TouchedInstructions.reset(InstrNum);
2035         continue;
2036       }
2037 
2038       Value *V = DFSToInstr[InstrNum];
2039       BasicBlock *CurrBlock = nullptr;
2040 
2041       if (auto *I = dyn_cast<Instruction>(V))
2042         CurrBlock = I->getParent();
2043       else if (auto *MP = dyn_cast<MemoryPhi>(V))
2044         CurrBlock = MP->getBlock();
2045       else
2046         llvm_unreachable("DFSToInstr gave us an unknown type of instruction");
2047 
2048       // If we hit a new block, do reachability processing.
2049       if (CurrBlock != LastBlock) {
2050         LastBlock = CurrBlock;
2051         bool BlockReachable = ReachableBlocks.count(CurrBlock);
2052         const auto &CurrInstRange = BlockInstRange.lookup(CurrBlock);
2053 
2054         // If it's not reachable, erase any touched instructions and move on.
2055         if (!BlockReachable) {
2056           TouchedInstructions.reset(CurrInstRange.first, CurrInstRange.second);
2057           DEBUG(dbgs() << "Skipping instructions in block "
2058                        << getBlockName(CurrBlock)
2059                        << " because it is unreachable\n");
2060           continue;
2061         }
2062         updateProcessedCount(CurrBlock);
2063       }
2064 
2065       if (auto *MP = dyn_cast<MemoryPhi>(V)) {
2066         DEBUG(dbgs() << "Processing MemoryPhi " << *MP << "\n");
2067         valueNumberMemoryPhi(MP);
2068       } else if (auto *I = dyn_cast<Instruction>(V)) {
2069         valueNumberInstruction(I);
2070       } else {
2071         llvm_unreachable("Should have been a MemoryPhi or Instruction");
2072       }
2073       updateProcessedCount(V);
2074       // Reset after processing (because we may mark ourselves as touched when
2075       // we propagate equalities).
2076       TouchedInstructions.reset(InstrNum);
2077     }
2078   }
2079   NumGVNMaxIterations = std::max(NumGVNMaxIterations.getValue(), Iterations);
2080 #ifndef NDEBUG
2081   verifyMemoryCongruency();
2082   verifyComparisons(F);
2083 #endif
2084 
2085   Changed |= eliminateInstructions(F);
2086 
2087   // Delete all instructions marked for deletion.
2088   for (Instruction *ToErase : InstructionsToErase) {
2089     if (!ToErase->use_empty())
2090       ToErase->replaceAllUsesWith(UndefValue::get(ToErase->getType()));
2091 
2092     ToErase->eraseFromParent();
2093   }
2094 
2095   // Delete all unreachable blocks.
2096   auto UnreachableBlockPred = [&](const BasicBlock &BB) {
2097     return !ReachableBlocks.count(&BB);
2098   };
2099 
2100   for (auto &BB : make_filter_range(F, UnreachableBlockPred)) {
2101     DEBUG(dbgs() << "We believe block " << getBlockName(&BB)
2102                  << " is unreachable\n");
2103     deleteInstructionsInBlock(&BB);
2104     Changed = true;
2105   }
2106 
2107   cleanupTables();
2108   return Changed;
2109 }
2110 
2111 bool NewGVN::runOnFunction(Function &F) {
2112   if (skipFunction(F))
2113     return false;
2114   return runGVN(F, &getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
2115                 &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
2116                 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(),
2117                 &getAnalysis<AAResultsWrapperPass>().getAAResults(),
2118                 &getAnalysis<MemorySSAWrapperPass>().getMSSA());
2119 }
2120 
2121 PreservedAnalyses NewGVNPass::run(Function &F, AnalysisManager<Function> &AM) {
2122   NewGVN Impl;
2123 
2124   // Apparently the order in which we get these results matter for
2125   // the old GVN (see Chandler's comment in GVN.cpp). I'll keep
2126   // the same order here, just in case.
2127   auto &AC = AM.getResult<AssumptionAnalysis>(F);
2128   auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
2129   auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
2130   auto &AA = AM.getResult<AAManager>(F);
2131   auto &MSSA = AM.getResult<MemorySSAAnalysis>(F).getMSSA();
2132   bool Changed = Impl.runGVN(F, &DT, &AC, &TLI, &AA, &MSSA);
2133   if (!Changed)
2134     return PreservedAnalyses::all();
2135   PreservedAnalyses PA;
2136   PA.preserve<DominatorTreeAnalysis>();
2137   PA.preserve<GlobalsAA>();
2138   return PA;
2139 }
2140 
2141 // Return true if V is a value that will always be available (IE can
2142 // be placed anywhere) in the function.  We don't do globals here
2143 // because they are often worse to put in place.
2144 // TODO: Separate cost from availability
2145 static bool alwaysAvailable(Value *V) {
2146   return isa<Constant>(V) || isa<Argument>(V);
2147 }
2148 
2149 // Get the basic block from an instruction/value.
2150 static BasicBlock *getBlockForValue(Value *V) {
2151   if (auto *I = dyn_cast<Instruction>(V))
2152     return I->getParent();
2153   return nullptr;
2154 }
2155 
2156 struct NewGVN::ValueDFS {
2157   int DFSIn = 0;
2158   int DFSOut = 0;
2159   int LocalNum = 0;
2160   // Only one of these will be set.
2161   Value *Val = nullptr;
2162   Use *U = nullptr;
2163 
2164   bool operator<(const ValueDFS &Other) const {
2165     // It's not enough that any given field be less than - we have sets
2166     // of fields that need to be evaluated together to give a proper ordering.
2167     // For example, if you have;
2168     // DFS (1, 3)
2169     // Val 0
2170     // DFS (1, 2)
2171     // Val 50
2172     // We want the second to be less than the first, but if we just go field
2173     // by field, we will get to Val 0 < Val 50 and say the first is less than
2174     // the second. We only want it to be less than if the DFS orders are equal.
2175     //
2176     // Each LLVM instruction only produces one value, and thus the lowest-level
2177     // differentiator that really matters for the stack (and what we use as as a
2178     // replacement) is the local dfs number.
2179     // Everything else in the structure is instruction level, and only affects
2180     // the order in which we will replace operands of a given instruction.
2181     //
2182     // For a given instruction (IE things with equal dfsin, dfsout, localnum),
2183     // the order of replacement of uses does not matter.
2184     // IE given,
2185     //  a = 5
2186     //  b = a + a
2187     // When you hit b, you will have two valuedfs with the same dfsin, out, and
2188     // localnum.
2189     // The .val will be the same as well.
2190     // The .u's will be different.
2191     // You will replace both, and it does not matter what order you replace them
2192     // in (IE whether you replace operand 2, then operand 1, or operand 1, then
2193     // operand 2).
2194     // Similarly for the case of same dfsin, dfsout, localnum, but different
2195     // .val's
2196     //  a = 5
2197     //  b  = 6
2198     //  c = a + b
2199     // in c, we will a valuedfs for a, and one for b,with everything the same
2200     // but .val  and .u.
2201     // It does not matter what order we replace these operands in.
2202     // You will always end up with the same IR, and this is guaranteed.
2203     return std::tie(DFSIn, DFSOut, LocalNum, Val, U) <
2204            std::tie(Other.DFSIn, Other.DFSOut, Other.LocalNum, Other.Val,
2205                     Other.U);
2206   }
2207 };
2208 
2209 // This function converts the set of members for a congruence class from values,
2210 // to sets of defs and uses with associated DFS info.
2211 void NewGVN::convertDenseToDFSOrdered(
2212     const CongruenceClass::MemberSet &Dense,
2213     SmallVectorImpl<ValueDFS> &DFSOrderedSet) {
2214   for (auto D : Dense) {
2215     // First add the value.
2216     BasicBlock *BB = getBlockForValue(D);
2217     // Constants are handled prior to ever calling this function, so
2218     // we should only be left with instructions as members.
2219     assert(BB && "Should have figured out a basic block for value");
2220     ValueDFS VD;
2221     DomTreeNode *DomNode = DT->getNode(BB);
2222     VD.DFSIn = DomNode->getDFSNumIn();
2223     VD.DFSOut = DomNode->getDFSNumOut();
2224     // If it's a store, use the leader of the value operand.
2225     if (auto *SI = dyn_cast<StoreInst>(D)) {
2226       auto Leader = lookupOperandLeader(SI->getValueOperand());
2227       VD.Val = alwaysAvailable(Leader) ? Leader : SI->getValueOperand();
2228     } else {
2229       VD.Val = D;
2230     }
2231 
2232     if (auto *I = dyn_cast<Instruction>(D))
2233       VD.LocalNum = InstrDFS.lookup(I);
2234     else
2235       llvm_unreachable("Should have been an instruction");
2236 
2237     DFSOrderedSet.emplace_back(VD);
2238 
2239     // Now add the uses.
2240     for (auto &U : D->uses()) {
2241       if (auto *I = dyn_cast<Instruction>(U.getUser())) {
2242         ValueDFS VD;
2243         // Put the phi node uses in the incoming block.
2244         BasicBlock *IBlock;
2245         if (auto *P = dyn_cast<PHINode>(I)) {
2246           IBlock = P->getIncomingBlock(U);
2247           // Make phi node users appear last in the incoming block
2248           // they are from.
2249           VD.LocalNum = InstrDFS.size() + 1;
2250         } else {
2251           IBlock = I->getParent();
2252           VD.LocalNum = InstrDFS.lookup(I);
2253         }
2254 
2255         // Skip uses in unreachable blocks, as we're going
2256         // to delete them.
2257         if (ReachableBlocks.count(IBlock) == 0)
2258           continue;
2259 
2260         DomTreeNode *DomNode = DT->getNode(IBlock);
2261         VD.DFSIn = DomNode->getDFSNumIn();
2262         VD.DFSOut = DomNode->getDFSNumOut();
2263         VD.U = &U;
2264         DFSOrderedSet.emplace_back(VD);
2265       }
2266     }
2267   }
2268 }
2269 
2270 // This function converts the set of members for a congruence class from values,
2271 // to the set of defs for loads and stores, with associated DFS info.
2272 void NewGVN::convertDenseToLoadsAndStores(
2273     const CongruenceClass::MemberSet &Dense,
2274     SmallVectorImpl<ValueDFS> &LoadsAndStores) {
2275   for (auto D : Dense) {
2276     if (!isa<LoadInst>(D) && !isa<StoreInst>(D))
2277       continue;
2278 
2279     BasicBlock *BB = getBlockForValue(D);
2280     ValueDFS VD;
2281     DomTreeNode *DomNode = DT->getNode(BB);
2282     VD.DFSIn = DomNode->getDFSNumIn();
2283     VD.DFSOut = DomNode->getDFSNumOut();
2284     VD.Val = D;
2285 
2286     // If it's an instruction, use the real local dfs number.
2287     if (auto *I = dyn_cast<Instruction>(D))
2288       VD.LocalNum = InstrDFS.lookup(I);
2289     else
2290       llvm_unreachable("Should have been an instruction");
2291 
2292     LoadsAndStores.emplace_back(VD);
2293   }
2294 }
2295 
2296 static void patchReplacementInstruction(Instruction *I, Value *Repl) {
2297   auto *ReplInst = dyn_cast<Instruction>(Repl);
2298   if (!ReplInst)
2299     return;
2300 
2301   // Patch the replacement so that it is not more restrictive than the value
2302   // being replaced.
2303   // Note that if 'I' is a load being replaced by some operation,
2304   // for example, by an arithmetic operation, then andIRFlags()
2305   // would just erase all math flags from the original arithmetic
2306   // operation, which is clearly not wanted and not needed.
2307   if (!isa<LoadInst>(I))
2308     ReplInst->andIRFlags(I);
2309 
2310   // FIXME: If both the original and replacement value are part of the
2311   // same control-flow region (meaning that the execution of one
2312   // guarantees the execution of the other), then we can combine the
2313   // noalias scopes here and do better than the general conservative
2314   // answer used in combineMetadata().
2315 
2316   // In general, GVN unifies expressions over different control-flow
2317   // regions, and so we need a conservative combination of the noalias
2318   // scopes.
2319   static const unsigned KnownIDs[] = {
2320       LLVMContext::MD_tbaa,           LLVMContext::MD_alias_scope,
2321       LLVMContext::MD_noalias,        LLVMContext::MD_range,
2322       LLVMContext::MD_fpmath,         LLVMContext::MD_invariant_load,
2323       LLVMContext::MD_invariant_group};
2324   combineMetadata(ReplInst, I, KnownIDs);
2325 }
2326 
2327 static void patchAndReplaceAllUsesWith(Instruction *I, Value *Repl) {
2328   patchReplacementInstruction(I, Repl);
2329   I->replaceAllUsesWith(Repl);
2330 }
2331 
2332 void NewGVN::deleteInstructionsInBlock(BasicBlock *BB) {
2333   DEBUG(dbgs() << "  BasicBlock Dead:" << *BB);
2334   ++NumGVNBlocksDeleted;
2335 
2336   // Delete the instructions backwards, as it has a reduced likelihood of having
2337   // to update as many def-use and use-def chains. Start after the terminator.
2338   auto StartPoint = BB->rbegin();
2339   ++StartPoint;
2340   // Note that we explicitly recalculate BB->rend() on each iteration,
2341   // as it may change when we remove the first instruction.
2342   for (BasicBlock::reverse_iterator I(StartPoint); I != BB->rend();) {
2343     Instruction &Inst = *I++;
2344     if (!Inst.use_empty())
2345       Inst.replaceAllUsesWith(UndefValue::get(Inst.getType()));
2346     if (isa<LandingPadInst>(Inst))
2347       continue;
2348 
2349     Inst.eraseFromParent();
2350     ++NumGVNInstrDeleted;
2351   }
2352   // Now insert something that simplifycfg will turn into an unreachable.
2353   Type *Int8Ty = Type::getInt8Ty(BB->getContext());
2354   new StoreInst(UndefValue::get(Int8Ty),
2355                 Constant::getNullValue(Int8Ty->getPointerTo()),
2356                 BB->getTerminator());
2357 }
2358 
2359 void NewGVN::markInstructionForDeletion(Instruction *I) {
2360   DEBUG(dbgs() << "Marking " << *I << " for deletion\n");
2361   InstructionsToErase.insert(I);
2362 }
2363 
2364 void NewGVN::replaceInstruction(Instruction *I, Value *V) {
2365 
2366   DEBUG(dbgs() << "Replacing " << *I << " with " << *V << "\n");
2367   patchAndReplaceAllUsesWith(I, V);
2368   // We save the actual erasing to avoid invalidating memory
2369   // dependencies until we are done with everything.
2370   markInstructionForDeletion(I);
2371 }
2372 
2373 namespace {
2374 
2375 // This is a stack that contains both the value and dfs info of where
2376 // that value is valid.
2377 class ValueDFSStack {
2378 public:
2379   Value *back() const { return ValueStack.back(); }
2380   std::pair<int, int> dfs_back() const { return DFSStack.back(); }
2381 
2382   void push_back(Value *V, int DFSIn, int DFSOut) {
2383     ValueStack.emplace_back(V);
2384     DFSStack.emplace_back(DFSIn, DFSOut);
2385   }
2386   bool empty() const { return DFSStack.empty(); }
2387   bool isInScope(int DFSIn, int DFSOut) const {
2388     if (empty())
2389       return false;
2390     return DFSIn >= DFSStack.back().first && DFSOut <= DFSStack.back().second;
2391   }
2392 
2393   void popUntilDFSScope(int DFSIn, int DFSOut) {
2394 
2395     // These two should always be in sync at this point.
2396     assert(ValueStack.size() == DFSStack.size() &&
2397            "Mismatch between ValueStack and DFSStack");
2398     while (
2399         !DFSStack.empty() &&
2400         !(DFSIn >= DFSStack.back().first && DFSOut <= DFSStack.back().second)) {
2401       DFSStack.pop_back();
2402       ValueStack.pop_back();
2403     }
2404   }
2405 
2406 private:
2407   SmallVector<Value *, 8> ValueStack;
2408   SmallVector<std::pair<int, int>, 8> DFSStack;
2409 };
2410 }
2411 
2412 bool NewGVN::eliminateInstructions(Function &F) {
2413   // This is a non-standard eliminator. The normal way to eliminate is
2414   // to walk the dominator tree in order, keeping track of available
2415   // values, and eliminating them.  However, this is mildly
2416   // pointless. It requires doing lookups on every instruction,
2417   // regardless of whether we will ever eliminate it.  For
2418   // instructions part of most singleton congruence classes, we know we
2419   // will never eliminate them.
2420 
2421   // Instead, this eliminator looks at the congruence classes directly, sorts
2422   // them into a DFS ordering of the dominator tree, and then we just
2423   // perform elimination straight on the sets by walking the congruence
2424   // class member uses in order, and eliminate the ones dominated by the
2425   // last member.   This is worst case O(E log E) where E = number of
2426   // instructions in a single congruence class.  In theory, this is all
2427   // instructions.   In practice, it is much faster, as most instructions are
2428   // either in singleton congruence classes or can't possibly be eliminated
2429   // anyway (if there are no overlapping DFS ranges in class).
2430   // When we find something not dominated, it becomes the new leader
2431   // for elimination purposes.
2432   // TODO: If we wanted to be faster, We could remove any members with no
2433   // overlapping ranges while sorting, as we will never eliminate anything
2434   // with those members, as they don't dominate anything else in our set.
2435 
2436   bool AnythingReplaced = false;
2437 
2438   // Since we are going to walk the domtree anyway, and we can't guarantee the
2439   // DFS numbers are updated, we compute some ourselves.
2440   DT->updateDFSNumbers();
2441 
2442   for (auto &B : F) {
2443     if (!ReachableBlocks.count(&B)) {
2444       for (const auto S : successors(&B)) {
2445         for (auto II = S->begin(); isa<PHINode>(II); ++II) {
2446           auto &Phi = cast<PHINode>(*II);
2447           DEBUG(dbgs() << "Replacing incoming value of " << *II << " for block "
2448                        << getBlockName(&B)
2449                        << " with undef due to it being unreachable\n");
2450           for (auto &Operand : Phi.incoming_values())
2451             if (Phi.getIncomingBlock(Operand) == &B)
2452               Operand.set(UndefValue::get(Phi.getType()));
2453         }
2454       }
2455     }
2456   }
2457 
2458   for (CongruenceClass *CC : reverse(CongruenceClasses)) {
2459     // Track the equivalent store info so we can decide whether to try
2460     // dead store elimination.
2461     SmallVector<ValueDFS, 8> PossibleDeadStores;
2462 
2463     if (CC->Dead)
2464       continue;
2465     // Everything still in the INITIAL class is unreachable or dead.
2466     if (CC == InitialClass) {
2467 #ifndef NDEBUG
2468       for (auto M : CC->Members)
2469         assert((!ReachableBlocks.count(cast<Instruction>(M)->getParent()) ||
2470                 InstructionsToErase.count(cast<Instruction>(M))) &&
2471                "Everything in INITIAL should be unreachable or dead at this "
2472                "point");
2473 #endif
2474       continue;
2475     }
2476 
2477     assert(CC->RepLeader && "We should have had a leader");
2478 
2479     // If this is a leader that is always available, and it's a
2480     // constant or has no equivalences, just replace everything with
2481     // it. We then update the congruence class with whatever members
2482     // are left.
2483     Value *Leader = CC->RepStoredValue ? CC->RepStoredValue : CC->RepLeader;
2484     if (alwaysAvailable(Leader)) {
2485       SmallPtrSet<Value *, 4> MembersLeft;
2486       for (auto M : CC->Members) {
2487         Value *Member = M;
2488         // Void things have no uses we can replace.
2489         if (Member == CC->RepLeader || Member->getType()->isVoidTy()) {
2490           MembersLeft.insert(Member);
2491           continue;
2492         }
2493         DEBUG(dbgs() << "Found replacement " << *(Leader) << " for " << *Member
2494                      << "\n");
2495         // Due to equality propagation, these may not always be
2496         // instructions, they may be real values.  We don't really
2497         // care about trying to replace the non-instructions.
2498         if (auto *I = dyn_cast<Instruction>(Member)) {
2499           assert(Leader != I && "About to accidentally remove our leader");
2500           replaceInstruction(I, Leader);
2501           AnythingReplaced = true;
2502 
2503           continue;
2504         } else {
2505           MembersLeft.insert(I);
2506         }
2507       }
2508       CC->Members.swap(MembersLeft);
2509     } else {
2510       DEBUG(dbgs() << "Eliminating in congruence class " << CC->ID << "\n");
2511       // If this is a singleton, we can skip it.
2512       if (CC->Members.size() != 1) {
2513 
2514         // This is a stack because equality replacement/etc may place
2515         // constants in the middle of the member list, and we want to use
2516         // those constant values in preference to the current leader, over
2517         // the scope of those constants.
2518         ValueDFSStack EliminationStack;
2519 
2520         // Convert the members to DFS ordered sets and then merge them.
2521         SmallVector<ValueDFS, 8> DFSOrderedSet;
2522         convertDenseToDFSOrdered(CC->Members, DFSOrderedSet);
2523 
2524         // Sort the whole thing.
2525         std::sort(DFSOrderedSet.begin(), DFSOrderedSet.end());
2526         for (auto &VD : DFSOrderedSet) {
2527           int MemberDFSIn = VD.DFSIn;
2528           int MemberDFSOut = VD.DFSOut;
2529           Value *Member = VD.Val;
2530           Use *MemberUse = VD.U;
2531 
2532           // We ignore void things because we can't get a value from them.
2533           if (Member && Member->getType()->isVoidTy())
2534             continue;
2535 
2536           if (EliminationStack.empty()) {
2537             DEBUG(dbgs() << "Elimination Stack is empty\n");
2538           } else {
2539             DEBUG(dbgs() << "Elimination Stack Top DFS numbers are ("
2540                          << EliminationStack.dfs_back().first << ","
2541                          << EliminationStack.dfs_back().second << ")\n");
2542           }
2543 
2544           DEBUG(dbgs() << "Current DFS numbers are (" << MemberDFSIn << ","
2545                        << MemberDFSOut << ")\n");
2546           // First, we see if we are out of scope or empty.  If so,
2547           // and there equivalences, we try to replace the top of
2548           // stack with equivalences (if it's on the stack, it must
2549           // not have been eliminated yet).
2550           // Then we synchronize to our current scope, by
2551           // popping until we are back within a DFS scope that
2552           // dominates the current member.
2553           // Then, what happens depends on a few factors
2554           // If the stack is now empty, we need to push
2555           // If we have a constant or a local equivalence we want to
2556           // start using, we also push.
2557           // Otherwise, we walk along, processing members who are
2558           // dominated by this scope, and eliminate them.
2559           bool ShouldPush = Member && EliminationStack.empty();
2560           bool OutOfScope =
2561               !EliminationStack.isInScope(MemberDFSIn, MemberDFSOut);
2562 
2563           if (OutOfScope || ShouldPush) {
2564             // Sync to our current scope.
2565             EliminationStack.popUntilDFSScope(MemberDFSIn, MemberDFSOut);
2566             bool ShouldPush = Member && EliminationStack.empty();
2567             if (ShouldPush) {
2568               EliminationStack.push_back(Member, MemberDFSIn, MemberDFSOut);
2569             }
2570           }
2571 
2572           // If we get to this point, and the stack is empty we must have a use
2573           // with nothing we can use to eliminate it, just skip it.
2574           if (EliminationStack.empty())
2575             continue;
2576 
2577           // Skip the Value's, we only want to eliminate on their uses.
2578           if (Member)
2579             continue;
2580           Value *Result = EliminationStack.back();
2581 
2582           // Don't replace our existing users with ourselves.
2583           if (MemberUse->get() == Result)
2584             continue;
2585 
2586           DEBUG(dbgs() << "Found replacement " << *Result << " for "
2587                        << *MemberUse->get() << " in " << *(MemberUse->getUser())
2588                        << "\n");
2589 
2590           // If we replaced something in an instruction, handle the patching of
2591           // metadata.
2592           if (auto *ReplacedInst = dyn_cast<Instruction>(MemberUse->get())) {
2593             // Skip this if we are replacing predicateinfo with its original
2594             // operand, as we already know we can just drop it.
2595             auto *PI = PredInfo->getPredicateInfoFor(ReplacedInst);
2596             if (!PI || Result != PI->OriginalOp)
2597               patchReplacementInstruction(ReplacedInst, Result);
2598           }
2599 
2600           assert(isa<Instruction>(MemberUse->getUser()));
2601           MemberUse->set(Result);
2602           AnythingReplaced = true;
2603         }
2604       }
2605     }
2606 
2607     // Cleanup the congruence class.
2608     SmallPtrSet<Value *, 4> MembersLeft;
2609     for (Value *Member : CC->Members) {
2610       if (Member->getType()->isVoidTy()) {
2611         MembersLeft.insert(Member);
2612         continue;
2613       }
2614 
2615       if (auto *MemberInst = dyn_cast<Instruction>(Member)) {
2616         if (isInstructionTriviallyDead(MemberInst)) {
2617           // TODO: Don't mark loads of undefs.
2618           markInstructionForDeletion(MemberInst);
2619           continue;
2620         }
2621       }
2622       MembersLeft.insert(Member);
2623     }
2624     CC->Members.swap(MembersLeft);
2625 
2626     // If we have possible dead stores to look at, try to eliminate them.
2627     if (CC->StoreCount > 0) {
2628       convertDenseToLoadsAndStores(CC->Members, PossibleDeadStores);
2629       std::sort(PossibleDeadStores.begin(), PossibleDeadStores.end());
2630       ValueDFSStack EliminationStack;
2631       for (auto &VD : PossibleDeadStores) {
2632         int MemberDFSIn = VD.DFSIn;
2633         int MemberDFSOut = VD.DFSOut;
2634         Instruction *Member = cast<Instruction>(VD.Val);
2635         if (EliminationStack.empty() ||
2636             !EliminationStack.isInScope(MemberDFSIn, MemberDFSOut)) {
2637           // Sync to our current scope.
2638           EliminationStack.popUntilDFSScope(MemberDFSIn, MemberDFSOut);
2639           if (EliminationStack.empty()) {
2640             EliminationStack.push_back(Member, MemberDFSIn, MemberDFSOut);
2641             continue;
2642           }
2643         }
2644         // We already did load elimination, so nothing to do here.
2645         if (isa<LoadInst>(Member))
2646           continue;
2647         assert(!EliminationStack.empty());
2648         Instruction *Leader = cast<Instruction>(EliminationStack.back());
2649         (void)Leader;
2650         assert(DT->dominates(Leader->getParent(), Member->getParent()));
2651         // Member is dominater by Leader, and thus dead
2652         DEBUG(dbgs() << "Marking dead store " << *Member
2653                      << " that is dominated by " << *Leader << "\n");
2654         markInstructionForDeletion(Member);
2655         CC->Members.erase(Member);
2656         ++NumGVNDeadStores;
2657       }
2658     }
2659   }
2660 
2661   return AnythingReplaced;
2662 }
2663 
2664 // This function provides global ranking of operations so that we can place them
2665 // in a canonical order.  Note that rank alone is not necessarily enough for a
2666 // complete ordering, as constants all have the same rank.  However, generally,
2667 // we will simplify an operation with all constants so that it doesn't matter
2668 // what order they appear in.
2669 unsigned int NewGVN::getRank(const Value *V) const {
2670   // Prefer undef to anything else
2671   if (isa<UndefValue>(V))
2672     return 0;
2673   if (isa<Constant>(V))
2674     return 1;
2675   else if (auto *A = dyn_cast<Argument>(V))
2676     return 2 + A->getArgNo();
2677 
2678   // Need to shift the instruction DFS by number of arguments + 3 to account for
2679   // the constant and argument ranking above.
2680   unsigned Result = InstrDFS.lookup(V);
2681   if (Result > 0)
2682     return 3 + NumFuncArgs + Result;
2683   // Unreachable or something else, just return a really large number.
2684   return ~0;
2685 }
2686 
2687 // This is a function that says whether two commutative operations should
2688 // have their order swapped when canonicalizing.
2689 bool NewGVN::shouldSwapOperands(const Value *A, const Value *B) const {
2690   // Because we only care about a total ordering, and don't rewrite expressions
2691   // in this order, we order by rank, which will give a strict weak ordering to
2692   // everything but constants, and then we order by pointer address.
2693   return std::make_pair(getRank(A), A) > std::make_pair(getRank(B), B);
2694 }
2695