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