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