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