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