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