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" 30 #include "llvm/ADT/STLExtras.h" 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"); 82 STATISTIC(NumGVNMaxIterations, 83 "Maximum Number of iterations it took to converge GVN"); 84 85 //===----------------------------------------------------------------------===// 86 // GVN Pass 87 //===----------------------------------------------------------------------===// 88 89 // Anchor methods. 90 namespace llvm { 91 namespace GVNExpression { 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; 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 { 125 using MemberSet = SmallPtrSet<Value *, 4>; 126 unsigned ID; 127 // Representative leader. 128 Value *RepLeader = nullptr; 129 // Defining Expression. 130 const Expression *DefiningExpr = nullptr; 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. 136 bool Dead = false; 137 138 // Number of stores in this congruence class. 139 // This is used so we can detect store equivalence changes properly. 140 int StoreCount = 0; 141 142 explicit CongruenceClass(unsigned ID) : ID(ID) {} 143 CongruenceClass(unsigned ID, Value *Leader, const Expression *E) 144 : ID(ID), RepLeader(Leader), DefiningExpr(E) {} 145 }; 146 147 namespace llvm { 148 template <> struct DenseMapInfo<const Expression *> { 149 static const Expression *getEmptyKey() { 150 auto Val = static_cast<uintptr_t>(-1); 151 Val <<= PointerLikeTypeTraits<const Expression *>::NumLowBitsAvailable; 152 return reinterpret_cast<const Expression *>(Val); 153 } 154 static const Expression *getTombstoneKey() { 155 auto Val = static_cast<uintptr_t>(~1U); 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 }; 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 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. 198 DenseMap<const MemoryAccess *, MemoryAccess *> MemoryAccessEquiv; 199 200 // Expression to class mapping. 201 using ExpressionClassMap = DenseMap<const Expression *, CongruenceClass *>; 202 ExpressionClassMap ExpressionToClass; 203 204 // Which values have changed as a result of leader changes. 205 SmallPtrSet<Value *, 8> LeaderChanges; 206 207 // Reachability info. 208 using BlockEdge = BasicBlockEdge; 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; 235 SmallVector<Value *, 32> DFSToInstr; 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, 248 TargetLibraryInfo *TLI, AliasAnalysis *AA, MemorySSA *MSSA); 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); 271 const UnknownExpression *createUnknownExpression(Instruction *); 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) { 286 auto *result = new CongruenceClass(NextCongruenceNum++, Leader, E); 287 CongruenceClasses.emplace_back(result); 288 return result; 289 } 290 291 CongruenceClass *createSingletonCongruenceClass(Value *Member) { 292 CongruenceClass *CClass = createCongruenceClass(Member, nullptr); 293 CClass->Members.insert(Member); 294 ValueToClass[Member] = CClass; 295 return CClass; 296 } 297 void initializeCongruenceClasses(Function &F); 298 299 // Value number an Instruction or MemoryPhi. 300 void valueNumberMemoryPhi(MemoryPhi *); 301 void valueNumberInstruction(Instruction *); 302 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 *); 315 bool setMemoryAccessEquivTo(MemoryAccess *From, MemoryAccess *To); 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 *); 324 void moveValueToNewCongruenceClass(Value *, CongruenceClass *, 325 CongruenceClass *); 326 // Reachability handling. 327 void updateReachableEdge(BasicBlock *, BasicBlock *); 328 void processOutgoingEdges(TerminatorInst *, BasicBlock *); 329 bool isOnlyReachableViaThisEdge(const BasicBlockEdge &) const; 330 Value *findConditionEquivalence(Value *, BasicBlock *) const; 331 MemoryAccess *lookupMemoryAccessEquiv(MemoryAccess *) const; 332 333 // Elimination. 334 struct ValueDFS; 335 void convertDenseToDFSOrdered(CongruenceClass::MemberSet &, 336 SmallVectorImpl<ValueDFS> &); 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 *){}; 345 346 // Various instruction touch utilities 347 void markUsersTouched(Value *); 348 void markMemoryUsersTouched(MemoryAccess *); 349 void markLeaderChangeTouched(CongruenceClass *CC); 350 351 // Utilities. 352 void cleanupTables(); 353 std::pair<unsigned, unsigned> assignDFSNumbers(BasicBlock *, unsigned); 354 void updateProcessedCount(Value *V); 355 void verifyMemoryCongruency() const; 356 bool singleReachablePHIPath(const MemoryAccess *, const MemoryAccess *) const; 357 }; 358 359 char NewGVN::ID = 0; 360 361 // createGVNPass - The public interface to this file. 362 FunctionPass *llvm::createNewGVNPass() { return new NewGVN(); } 363 364 template <typename T> 365 static bool equalsLoadStoreHelper(const T &LHS, const Expression &RHS) { 366 if ((!isa<LoadExpression>(RHS) && !isa<StoreExpression>(RHS)) || 367 !LHS.BasicExpression::equals(RHS)) { 368 return false; 369 } else if (const auto *L = dyn_cast<LoadExpression>(&RHS)) { 370 if (LHS.getDefiningAccess() != L->getDefiningAccess()) 371 return false; 372 } else if (const auto *S = dyn_cast<StoreExpression>(&RHS)) { 373 if (LHS.getDefiningAccess() != S->getDefiningAccess()) 374 return false; 375 } 376 return true; 377 } 378 379 bool LoadExpression::equals(const Expression &Other) const { 380 return equalsLoadStoreHelper(*this, Other); 381 } 382 383 bool StoreExpression::equals(const Expression &Other) const { 384 return equalsLoadStoreHelper(*this, Other); 385 } 386 387 #ifndef NDEBUG 388 static std::string getBlockName(const BasicBlock *B) { 389 return DOTGraphTraits<const Function *>::getSimpleNodeLabel(B, nullptr); 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) { 403 BasicBlock *PHIBlock = I->getParent(); 404 auto *PN = cast<PHINode>(I); 405 auto *E = 406 new (ExpressionAllocator) PHIExpression(PN->getNumOperands(), PHIBlock); 407 408 E->allocateOperands(ArgRecycler, ExpressionAllocator); 409 E->setType(I->getType()); 410 E->setOpcode(I->getOpcode()); 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 * { 421 // Don't try to transform self-defined phis. 422 if (U == PN) 423 return PN; 424 const BasicBlockEdge BBE(PN->getIncomingBlock(U), PHIBlock); 425 return lookupOperandLeader(U, I, BBE); 426 }); 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 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) { 445 auto Operand = lookupOperandLeader(O, I, B); 446 AllConstant &= isa<Constant>(Operand); 447 return Operand; 448 }); 449 450 return AllConstant; 451 } 452 453 const Expression *NewGVN::createBinaryExpression(unsigned Opcode, Type *T, 454 Value *Arg1, Value *Arg2, 455 const BasicBlock *B) { 456 auto *E = new (ExpressionAllocator) BasicExpression(2); 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 } 469 E->op_push_back(lookupOperandLeader(Arg1, nullptr, B)); 470 E->op_push_back(lookupOperandLeader(Arg2, nullptr, B)); 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 526 auto *E = new (ExpressionAllocator) BasicExpression(I->getNumOperands()); 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(), 592 ArrayRef<Value *>(E->op_begin(), E->op_end()), 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()) 606 C.emplace_back(cast<Constant>(Arg)); 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)) { 618 auto *E = new (ExpressionAllocator) 619 AggregateValueExpression(I->getNumOperands(), II->getNumIndices()); 620 setBasicExpressionInfo(I, E, B); 621 E->allocateIntOperands(ExpressionAllocator); 622 std::copy(II->idx_begin(), II->idx_end(), int_op_inserter(E)); 623 return E; 624 } else if (auto *EI = dyn_cast<ExtractValueInst>(I)) { 625 auto *E = new (ExpressionAllocator) 626 AggregateValueExpression(I->getNumOperands(), EI->getNumIndices()); 627 setBasicExpressionInfo(EI, E, B); 628 E->allocateIntOperands(ExpressionAllocator); 629 std::copy(EI->idx_begin(), EI->idx_end(), int_op_inserter(E)); 630 return E; 631 } 632 llvm_unreachable("Unhandled type of aggregate value operation"); 633 } 634 635 const VariableExpression *NewGVN::createVariableExpression(Value *V) { 636 auto *E = new (ExpressionAllocator) VariableExpression(V); 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 649 const ConstantExpression *NewGVN::createConstantExpression(Constant *C) { 650 auto *E = new (ExpressionAllocator) ConstantExpression(C); 651 E->setOpcode(C->getValueID()); 652 return E; 653 } 654 655 const UnknownExpression *NewGVN::createUnknownExpression(Instruction *I) { 656 auto *E = new (ExpressionAllocator) UnknownExpression(I); 657 E->setOpcode(I->getOpcode()); 658 return E; 659 } 660 661 const CallExpression *NewGVN::createCallExpression(CallInst *CI, 662 MemoryAccess *HV, 663 const BasicBlock *B) { 664 // FIXME: Add operand bundles for calls. 665 auto *E = 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> 674 Value *NewGVN::lookupOperandLeader(Value *V, const User *U, const T &B) const { 675 CongruenceClass *CC = ValueToClass.lookup(V); 676 if (CC && (CC != InitialClass)) 677 return CC->RepLeader; 678 return V; 679 } 680 681 MemoryAccess *NewGVN::lookupMemoryAccessEquiv(MemoryAccess *MA) const { 682 MemoryAccess *Result = MemoryAccessEquiv.lookup(MA); 683 return Result ? Result : MA; 684 } 685 686 LoadExpression *NewGVN::createLoadExpression(Type *LoadType, Value *PointerOp, 687 LoadInst *LI, MemoryAccess *DA, 688 const BasicBlock *B) { 689 auto *E = new (ExpressionAllocator) LoadExpression(1, LI, DA); 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); 695 E->op_push_back(lookupOperandLeader(PointerOp, LI, B)); 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) { 708 auto *E = 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); 715 E->op_push_back(lookupOperandLeader(SI->getPointerOperand(), SI, B)); 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 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) { 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 728 // right now, that member should not be us. 729 return CC->StoreCount > 1 || CC->Members.count(I) == 0; 730 } 731 732 const Expression *NewGVN::performSymbolicStoreEvaluation(Instruction *I, 733 const BasicBlock *B) { 734 // Unlike loads, we never try to eliminate stores, so we do not check if they 735 // are simple and avoid value numbering them. 736 auto *SI = cast<StoreInst>(I); 737 MemoryAccess *StoreAccess = MSSA->getMemoryAccess(SI); 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. 741 if (SI->isSimple()) { 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); 746 CongruenceClass *CC = ExpressionToClass.lookup(OldStore); 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. 750 if (CC && CC->DefiningExpr && isa<StoreExpression>(CC->DefiningExpr) && 751 CC->RepLeader == lookupOperandLeader(SI->getValueOperand(), SI, B) && 752 hasMemberOtherThanUs(CC, I)) 753 return createStoreExpression(SI, StoreRHS, B); 754 } 755 756 return createStoreExpression(SI, StoreAccess, B); 757 } 758 759 const Expression *NewGVN::performSymbolicLoadEvaluation(Instruction *I, 760 const BasicBlock *B) { 761 auto *LI = cast<LoadInst>(I); 762 763 // We can eliminate in favor of non-simple loads, but we won't be able to 764 // eliminate the loads themselves. 765 if (!LI->isSimple()) 766 return nullptr; 767 768 Value *LoadAddressLeader = lookupOperandLeader(LI->getPointerOperand(), I, B); 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 784 const Expression *E = 785 createLoadExpression(LI->getType(), LI->getPointerOperand(), LI, 786 lookupMemoryAccessEquiv(DefiningAccess), B); 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) { 793 auto *CI = cast<CallInst>(I); 794 if (AA->doesNotAccessMemory(CI)) 795 return createCallExpression(CI, nullptr, B); 796 if (AA->onlyReadsMemory(CI)) { 797 MemoryAccess *DefiningAccess = MSSAWalker->getClobberingMemoryAccess(CI); 798 return createCallExpression(CI, lookupMemoryAccessEquiv(DefiningAccess), B); 799 } 800 return nullptr; 801 } 802 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) { 806 DEBUG(dbgs() << "Setting " << *From << " equivalent to "); 807 if (!To) 808 DEBUG(dbgs() << "itself"); 809 else 810 DEBUG(dbgs() << *To); 811 DEBUG(dbgs() << "\n"); 812 auto LookupResult = MemoryAccessEquiv.find(From); 813 bool Changed = false; 814 // If it's already in the table, see if the value changed. 815 if (LookupResult != MemoryAccessEquiv.end()) { 816 if (To && LookupResult->second != To) { 817 // It wasn't equivalent before, and now it is. 818 LookupResult->second = To; 819 Changed = true; 820 } else if (!To) { 821 // It used to be equivalent to something, and now it's not. 822 MemoryAccessEquiv.erase(LookupResult); 823 Changed = true; 824 } 825 } else { 826 assert(!To && 827 "Memory equivalence should never change from nothing to something"); 828 } 829 830 return Changed; 831 } 832 // Evaluate PHI nodes symbolically, and create an expression result. 833 const Expression *NewGVN::performSymbolicPHIEvaluation(Instruction *I, 834 const BasicBlock *B) { 835 auto *E = cast<PHIExpression>(createPHIExpression(I)); 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()) { 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 } 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 875 if (auto *AllSameInst = dyn_cast<Instruction>(AllSameValue)) 876 if (!DT->dominates(AllSameInst, I)) 877 return E; 878 } 879 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) { 937 const Expression *E = nullptr; 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. 946 auto *I = cast<Instruction>(V); 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 } 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'. 1016 bool NewGVN::isOnlyReachableViaThisEdge(const BasicBlockEdge &E) const { 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. 1032 for (auto *User : V->users()) { 1033 assert(isa<Instruction>(User) && "Use of value not within an instruction?"); 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 1043 TouchedInstructions.set(InstrDFS[U]); 1044 } 1045 } 1046 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]); 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); 1087 } 1088 } 1089 1090 // Perform congruence finding on a given value numbering expression. 1091 void NewGVN::performCongruenceFinding(Value *V, const Expression *E) { 1092 ValueToExpression[V] = E; 1093 // This is guaranteed to return something, since it will at least find 1094 // INITIAL. 1095 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; 1102 if (const auto *VE = dyn_cast<VariableExpression>(E)) { 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) { 1109 CongruenceClass *NewClass = createCongruenceClass(nullptr, E); 1110 auto place = lookupResult.first; 1111 place->second = NewClass; 1112 1113 // Constants and variables should always be made the leader. 1114 if (const auto *CE = dyn_cast<ConstantExpression>(E)) { 1115 NewClass->RepLeader = CE->getConstantValue(); 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 { 1121 NewClass->RepLeader = V; 1122 } 1123 assert(!isa<VariableExpression>(E) && 1124 "VariableExpression should have been handled already"); 1125 1126 EClass = NewClass; 1127 DEBUG(dbgs() << "Created new congruence class for " << *V 1128 << " using expression " << *E << " at " << NewClass->ID 1129 << " and leader " << *(NewClass->RepLeader) << "\n"); 1130 DEBUG(dbgs() << "Hash value was " << E->getHashValue() << "\n"); 1131 } else { 1132 EClass = lookupResult.first->second; 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 1138 assert(EClass && "Somehow don't have an eclass"); 1139 1140 assert(!EClass->Dead && "We accidentally looked up a dead class"); 1141 } 1142 } 1143 bool ClassChanged = VClass != EClass; 1144 bool LeaderChanged = LeaderChanges.erase(V); 1145 if (ClassChanged || LeaderChanged) { 1146 DEBUG(dbgs() << "Found class " << EClass->ID << " for expression " << E 1147 << "\n"); 1148 1149 if (ClassChanged) 1150 1151 moveValueToNewCongruenceClass(V, VClass, EClass); 1152 1153 1154 markUsersTouched(V); 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 1158 // we determined the expression is congruent to a different memory 1159 // state, use that different memory state. If we determined it didn't, 1160 // we update that as well. Right now, we only support store 1161 // expressions. 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); 1168 } 1169 markMemoryUsersTouched(MA); 1170 } 1171 } 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 } 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. 1215 if (MemoryAccess *MemPhi = MSSA->getMemoryAccess(To)) 1216 TouchedInstructions.set(InstrDFS[MemPhi]); 1217 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 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)) { 1281 auto *CondVal = cast<ConstantInt>(CondEvaluated); 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); 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 } 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); 1313 } 1314 } 1315 1316 // The algorithm initially places the values of the routine in the INITIAL 1317 // congruence 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; 1325 InitialClass = createCongruenceClass(nullptr, nullptr); 1326 for (auto &B : F) { 1327 if (auto *MP = MSSA->getMemoryAccess(&B)) 1328 MemoryAccessEquiv.insert({MP, MSSA->getLiveOnEntryDef()}); 1329 1330 for (auto &I : B) { 1331 InitialValues.insert(&I); 1332 ValueToClass[&I] = InitialClass; 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()}); 1343 ++InitialClass->StoreCount; 1344 assert(InitialClass->StoreCount > 0); 1345 } 1346 } 1347 } 1348 InitialClass->Members.swap(InitialValues); 1349 1350 // Initialize arguments to be in their own unique congruence classes 1351 for (auto &FA : F.args()) 1352 createSingletonCongruenceClass(&FA); 1353 } 1354 1355 void NewGVN::cleanupTables() { 1356 for (unsigned i = 0, e = CongruenceClasses.size(); i != e; ++i) { 1357 DEBUG(dbgs() << "Congruence class " << CongruenceClasses[i]->ID << " has " 1358 << CongruenceClasses[i]->Members.size() << " members\n"); 1359 // Make sure we delete the congruence class (probably worth switching to 1360 // a unique_ptr at some point. 1361 delete CongruenceClasses[i]; 1362 CongruenceClasses[i] = nullptr; 1363 } 1364 1365 ValueToClass.clear(); 1366 ArgRecycler.clear(ExpressionAllocator); 1367 ExpressionAllocator.Reset(); 1368 CongruenceClasses.clear(); 1369 ExpressionToClass.clear(); 1370 ValueToExpression.clear(); 1371 ReachableBlocks.clear(); 1372 ReachableEdges.clear(); 1373 #ifndef NDEBUG 1374 ProcessedCount.clear(); 1375 #endif 1376 DFSDomMap.clear(); 1377 InstrDFS.clear(); 1378 InstructionsToErase.clear(); 1379 1380 DFSToInstr.clear(); 1381 BlockInstRange.clear(); 1382 TouchedInstructions.clear(); 1383 DominatedInstRange.clear(); 1384 MemoryAccessEquiv.clear(); 1385 } 1386 1387 std::pair<unsigned, unsigned> NewGVN::assignDFSNumbers(BasicBlock *B, 1388 unsigned Start) { 1389 unsigned End = Start; 1390 if (MemoryAccess *MemPhi = MSSA->getMemoryAccess(B)) { 1391 InstrDFS[MemPhi] = End++; 1392 DFSToInstr.emplace_back(MemPhi); 1393 } 1394 1395 for (auto &I : *B) { 1396 InstrDFS[&I] = End++; 1397 DFSToInstr.emplace_back(&I); 1398 } 1399 1400 // All of the range functions taken half-open ranges (open on the end side). 1401 // So we do not subtract one from count, because at this point it is one 1402 // greater than the last instruction. 1403 return std::make_pair(Start, End); 1404 } 1405 1406 void NewGVN::updateProcessedCount(Value *V) { 1407 #ifndef NDEBUG 1408 if (ProcessedCount.count(V) == 0) { 1409 ProcessedCount.insert({V, 1}); 1410 } else { 1411 ProcessedCount[V] += 1; 1412 assert(ProcessedCount[V] < 100 && 1413 "Seem to have processed the same Value a lot"); 1414 } 1415 #endif 1416 } 1417 // Evaluate MemoryPhi nodes symbolically, just like PHI nodes 1418 void NewGVN::valueNumberMemoryPhi(MemoryPhi *MP) { 1419 // If all the arguments are the same, the MemoryPhi has the same value as the 1420 // argument. 1421 // Filter out unreachable blocks from our operands. 1422 auto Filtered = make_filter_range(MP->operands(), [&](const Use &U) { 1423 return ReachableBlocks.count(MP->getIncomingBlock(U)); 1424 }); 1425 1426 assert(Filtered.begin() != Filtered.end() && 1427 "We should not be processing a MemoryPhi in a completely " 1428 "unreachable block"); 1429 1430 // Transform the remaining operands into operand leaders. 1431 // FIXME: mapped_iterator should have a range version. 1432 auto LookupFunc = [&](const Use &U) { 1433 return lookupMemoryAccessEquiv(cast<MemoryAccess>(U)); 1434 }; 1435 auto MappedBegin = map_iterator(Filtered.begin(), LookupFunc); 1436 auto MappedEnd = map_iterator(Filtered.end(), LookupFunc); 1437 1438 // and now check if all the elements are equal. 1439 // Sadly, we can't use std::equals since these are random access iterators. 1440 MemoryAccess *AllSameValue = *MappedBegin; 1441 ++MappedBegin; 1442 bool AllEqual = std::all_of( 1443 MappedBegin, MappedEnd, 1444 [&AllSameValue](const MemoryAccess *V) { return V == AllSameValue; }); 1445 1446 if (AllEqual) 1447 DEBUG(dbgs() << "Memory Phi value numbered to " << *AllSameValue << "\n"); 1448 else 1449 DEBUG(dbgs() << "Memory Phi value numbered to itself\n"); 1450 1451 if (setMemoryAccessEquivTo(MP, AllEqual ? AllSameValue : nullptr)) 1452 markMemoryUsersTouched(MP); 1453 } 1454 1455 // Value number a single instruction, symbolically evaluating, performing 1456 // congruence finding, and updating mappings. 1457 void NewGVN::valueNumberInstruction(Instruction *I) { 1458 DEBUG(dbgs() << "Processing instruction " << *I << "\n"); 1459 if (isInstructionTriviallyDead(I, TLI)) { 1460 DEBUG(dbgs() << "Skipping unused instruction\n"); 1461 markInstructionForDeletion(I); 1462 return; 1463 } 1464 if (!I->isTerminator()) { 1465 const auto *Symbolized = performSymbolicEvaluation(I, I->getParent()); 1466 // If we couldn't come up with a symbolic expression, use the unknown 1467 // expression 1468 if (Symbolized == nullptr) 1469 Symbolized = createUnknownExpression(I); 1470 performCongruenceFinding(I, Symbolized); 1471 } else { 1472 // Handle terminators that return values. All of them produce values we 1473 // don't currently understand. 1474 if (!I->getType()->isVoidTy()) { 1475 auto *Symbolized = createUnknownExpression(I); 1476 performCongruenceFinding(I, Symbolized); 1477 } 1478 processOutgoingEdges(dyn_cast<TerminatorInst>(I), I->getParent()); 1479 } 1480 } 1481 1482 // Check if there is a path, using single or equal argument phi nodes, from 1483 // First to Second. 1484 bool NewGVN::singleReachablePHIPath(const MemoryAccess *First, 1485 const MemoryAccess *Second) const { 1486 if (First == Second) 1487 return true; 1488 1489 if (auto *FirstDef = dyn_cast<MemoryUseOrDef>(First)) { 1490 auto *DefAccess = FirstDef->getDefiningAccess(); 1491 return singleReachablePHIPath(DefAccess, Second); 1492 } else { 1493 auto *MP = cast<MemoryPhi>(First); 1494 auto ReachableOperandPred = [&](const Use &U) { 1495 return ReachableBlocks.count(MP->getIncomingBlock(U)); 1496 }; 1497 auto FilteredPhiArgs = 1498 make_filter_range(MP->operands(), ReachableOperandPred); 1499 SmallVector<const Value *, 32> OperandList; 1500 std::copy(FilteredPhiArgs.begin(), FilteredPhiArgs.end(), 1501 std::back_inserter(OperandList)); 1502 bool Okay = OperandList.size() == 1; 1503 if (!Okay) 1504 Okay = std::equal(OperandList.begin(), OperandList.end(), 1505 OperandList.begin()); 1506 if (Okay) 1507 return singleReachablePHIPath(cast<MemoryAccess>(OperandList[0]), Second); 1508 return false; 1509 } 1510 } 1511 1512 // Verify the that the memory equivalence table makes sense relative to the 1513 // congruence classes. Note that this checking is not perfect, and is currently 1514 // subject to very rare false negatives. It is only useful for testing/debugging. 1515 void NewGVN::verifyMemoryCongruency() const { 1516 // Anything equivalent in the memory access table should be in the same 1517 // congruence class. 1518 1519 // Filter out the unreachable and trivially dead entries, because they may 1520 // never have been updated if the instructions were not processed. 1521 auto ReachableAccessPred = 1522 [&](const std::pair<const MemoryAccess *, MemoryAccess *> Pair) { 1523 bool Result = ReachableBlocks.count(Pair.first->getBlock()); 1524 if (!Result) 1525 return false; 1526 if (auto *MemDef = dyn_cast<MemoryDef>(Pair.first)) 1527 return !isInstructionTriviallyDead(MemDef->getMemoryInst()); 1528 return true; 1529 }; 1530 1531 auto Filtered = make_filter_range(MemoryAccessEquiv, ReachableAccessPred); 1532 for (auto KV : Filtered) { 1533 assert(KV.first != KV.second && 1534 "We added a useless equivalence to the memory equivalence table"); 1535 // Unreachable instructions may not have changed because we never process 1536 // them. 1537 if (!ReachableBlocks.count(KV.first->getBlock())) 1538 continue; 1539 if (auto *FirstMUD = dyn_cast<MemoryUseOrDef>(KV.first)) { 1540 auto *SecondMUD = dyn_cast<MemoryUseOrDef>(KV.second); 1541 if (FirstMUD && SecondMUD) 1542 assert((singleReachablePHIPath(FirstMUD, SecondMUD) || 1543 ValueToClass.lookup(FirstMUD->getMemoryInst()) == 1544 ValueToClass.lookup(SecondMUD->getMemoryInst())) && 1545 "The instructions for these memory operations should have " 1546 "been in the same congruence class or reachable through" 1547 "a single argument phi"); 1548 } else if (auto *FirstMP = dyn_cast<MemoryPhi>(KV.first)) { 1549 1550 // We can only sanely verify that MemoryDefs in the operand list all have 1551 // the same class. 1552 auto ReachableOperandPred = [&](const Use &U) { 1553 return ReachableBlocks.count(FirstMP->getIncomingBlock(U)) && 1554 isa<MemoryDef>(U); 1555 1556 }; 1557 // All arguments should in the same class, ignoring unreachable arguments 1558 auto FilteredPhiArgs = 1559 make_filter_range(FirstMP->operands(), ReachableOperandPred); 1560 SmallVector<const CongruenceClass *, 16> PhiOpClasses; 1561 std::transform(FilteredPhiArgs.begin(), FilteredPhiArgs.end(), 1562 std::back_inserter(PhiOpClasses), [&](const Use &U) { 1563 const MemoryDef *MD = cast<MemoryDef>(U); 1564 return ValueToClass.lookup(MD->getMemoryInst()); 1565 }); 1566 assert(std::equal(PhiOpClasses.begin(), PhiOpClasses.end(), 1567 PhiOpClasses.begin()) && 1568 "All MemoryPhi arguments should be in the same class"); 1569 } 1570 } 1571 } 1572 1573 // This is the main transformation entry point. 1574 bool NewGVN::runGVN(Function &F, DominatorTree *_DT, AssumptionCache *_AC, 1575 TargetLibraryInfo *_TLI, AliasAnalysis *_AA, 1576 MemorySSA *_MSSA) { 1577 bool Changed = false; 1578 DT = _DT; 1579 AC = _AC; 1580 TLI = _TLI; 1581 AA = _AA; 1582 MSSA = _MSSA; 1583 DL = &F.getParent()->getDataLayout(); 1584 MSSAWalker = MSSA->getWalker(); 1585 1586 // Count number of instructions for sizing of hash tables, and come 1587 // up with a global dfs numbering for instructions. 1588 unsigned ICount = 1; 1589 // Add an empty instruction to account for the fact that we start at 1 1590 DFSToInstr.emplace_back(nullptr); 1591 // Note: We want RPO traversal of the blocks, which is not quite the same as 1592 // dominator tree order, particularly with regard whether backedges get 1593 // visited first or second, given a block with multiple successors. 1594 // If we visit in the wrong order, we will end up performing N times as many 1595 // iterations. 1596 // The dominator tree does guarantee that, for a given dom tree node, it's 1597 // parent must occur before it in the RPO ordering. Thus, we only need to sort 1598 // the siblings. 1599 DenseMap<const DomTreeNode *, unsigned> RPOOrdering; 1600 ReversePostOrderTraversal<Function *> RPOT(&F); 1601 unsigned Counter = 0; 1602 for (auto &B : RPOT) { 1603 auto *Node = DT->getNode(B); 1604 assert(Node && "RPO and Dominator tree should have same reachability"); 1605 RPOOrdering[Node] = ++Counter; 1606 } 1607 // Sort dominator tree children arrays into RPO. 1608 for (auto &B : RPOT) { 1609 auto *Node = DT->getNode(B); 1610 if (Node->getChildren().size() > 1) 1611 std::sort(Node->begin(), Node->end(), 1612 [&RPOOrdering](const DomTreeNode *A, const DomTreeNode *B) { 1613 return RPOOrdering[A] < RPOOrdering[B]; 1614 }); 1615 } 1616 1617 // Now a standard depth first ordering of the domtree is equivalent to RPO. 1618 auto DFI = df_begin(DT->getRootNode()); 1619 for (auto DFE = df_end(DT->getRootNode()); DFI != DFE; ++DFI) { 1620 BasicBlock *B = DFI->getBlock(); 1621 const auto &BlockRange = assignDFSNumbers(B, ICount); 1622 BlockInstRange.insert({B, BlockRange}); 1623 ICount += BlockRange.second - BlockRange.first; 1624 } 1625 1626 // Handle forward unreachable blocks and figure out which blocks 1627 // have single preds. 1628 for (auto &B : F) { 1629 // Assign numbers to unreachable blocks. 1630 if (!DFI.nodeVisited(DT->getNode(&B))) { 1631 const auto &BlockRange = assignDFSNumbers(&B, ICount); 1632 BlockInstRange.insert({&B, BlockRange}); 1633 ICount += BlockRange.second - BlockRange.first; 1634 } 1635 } 1636 1637 TouchedInstructions.resize(ICount); 1638 DominatedInstRange.reserve(F.size()); 1639 // Ensure we don't end up resizing the expressionToClass map, as 1640 // that can be quite expensive. At most, we have one expression per 1641 // instruction. 1642 ExpressionToClass.reserve(ICount); 1643 1644 // Initialize the touched instructions to include the entry block. 1645 const auto &InstRange = BlockInstRange.lookup(&F.getEntryBlock()); 1646 TouchedInstructions.set(InstRange.first, InstRange.second); 1647 ReachableBlocks.insert(&F.getEntryBlock()); 1648 1649 initializeCongruenceClasses(F); 1650 1651 unsigned int Iterations = 0; 1652 // We start out in the entry block. 1653 BasicBlock *LastBlock = &F.getEntryBlock(); 1654 while (TouchedInstructions.any()) { 1655 ++Iterations; 1656 // Walk through all the instructions in all the blocks in RPO. 1657 for (int InstrNum = TouchedInstructions.find_first(); InstrNum != -1; 1658 InstrNum = TouchedInstructions.find_next(InstrNum)) { 1659 assert(InstrNum != 0 && "Bit 0 should never be set, something touched an " 1660 "instruction not in the lookup table"); 1661 Value *V = DFSToInstr[InstrNum]; 1662 BasicBlock *CurrBlock = nullptr; 1663 1664 if (auto *I = dyn_cast<Instruction>(V)) 1665 CurrBlock = I->getParent(); 1666 else if (auto *MP = dyn_cast<MemoryPhi>(V)) 1667 CurrBlock = MP->getBlock(); 1668 else 1669 llvm_unreachable("DFSToInstr gave us an unknown type of instruction"); 1670 1671 // If we hit a new block, do reachability processing. 1672 if (CurrBlock != LastBlock) { 1673 LastBlock = CurrBlock; 1674 bool BlockReachable = ReachableBlocks.count(CurrBlock); 1675 const auto &CurrInstRange = BlockInstRange.lookup(CurrBlock); 1676 1677 // If it's not reachable, erase any touched instructions and move on. 1678 if (!BlockReachable) { 1679 TouchedInstructions.reset(CurrInstRange.first, CurrInstRange.second); 1680 DEBUG(dbgs() << "Skipping instructions in block " 1681 << getBlockName(CurrBlock) 1682 << " because it is unreachable\n"); 1683 continue; 1684 } 1685 updateProcessedCount(CurrBlock); 1686 } 1687 1688 if (auto *MP = dyn_cast<MemoryPhi>(V)) { 1689 DEBUG(dbgs() << "Processing MemoryPhi " << *MP << "\n"); 1690 valueNumberMemoryPhi(MP); 1691 } else if (auto *I = dyn_cast<Instruction>(V)) { 1692 valueNumberInstruction(I); 1693 } else { 1694 llvm_unreachable("Should have been a MemoryPhi or Instruction"); 1695 } 1696 updateProcessedCount(V); 1697 // Reset after processing (because we may mark ourselves as touched when 1698 // we propagate equalities). 1699 TouchedInstructions.reset(InstrNum); 1700 } 1701 } 1702 NumGVNMaxIterations = std::max(NumGVNMaxIterations.getValue(), Iterations); 1703 #ifndef NDEBUG 1704 verifyMemoryCongruency(); 1705 #endif 1706 Changed |= eliminateInstructions(F); 1707 1708 // Delete all instructions marked for deletion. 1709 for (Instruction *ToErase : InstructionsToErase) { 1710 if (!ToErase->use_empty()) 1711 ToErase->replaceAllUsesWith(UndefValue::get(ToErase->getType())); 1712 1713 ToErase->eraseFromParent(); 1714 } 1715 1716 // Delete all unreachable blocks. 1717 auto UnreachableBlockPred = [&](const BasicBlock &BB) { 1718 return !ReachableBlocks.count(&BB); 1719 }; 1720 1721 for (auto &BB : make_filter_range(F, UnreachableBlockPred)) { 1722 DEBUG(dbgs() << "We believe block " << getBlockName(&BB) 1723 << " is unreachable\n"); 1724 deleteInstructionsInBlock(&BB); 1725 Changed = true; 1726 } 1727 1728 cleanupTables(); 1729 return Changed; 1730 } 1731 1732 bool NewGVN::runOnFunction(Function &F) { 1733 if (skipFunction(F)) 1734 return false; 1735 return runGVN(F, &getAnalysis<DominatorTreeWrapperPass>().getDomTree(), 1736 &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F), 1737 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(), 1738 &getAnalysis<AAResultsWrapperPass>().getAAResults(), 1739 &getAnalysis<MemorySSAWrapperPass>().getMSSA()); 1740 } 1741 1742 PreservedAnalyses NewGVNPass::run(Function &F, AnalysisManager<Function> &AM) { 1743 NewGVN Impl; 1744 1745 // Apparently the order in which we get these results matter for 1746 // the old GVN (see Chandler's comment in GVN.cpp). I'll keep 1747 // the same order here, just in case. 1748 auto &AC = AM.getResult<AssumptionAnalysis>(F); 1749 auto &DT = AM.getResult<DominatorTreeAnalysis>(F); 1750 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F); 1751 auto &AA = AM.getResult<AAManager>(F); 1752 auto &MSSA = AM.getResult<MemorySSAAnalysis>(F).getMSSA(); 1753 bool Changed = Impl.runGVN(F, &DT, &AC, &TLI, &AA, &MSSA); 1754 if (!Changed) 1755 return PreservedAnalyses::all(); 1756 PreservedAnalyses PA; 1757 PA.preserve<DominatorTreeAnalysis>(); 1758 PA.preserve<GlobalsAA>(); 1759 return PA; 1760 } 1761 1762 // Return true if V is a value that will always be available (IE can 1763 // be placed anywhere) in the function. We don't do globals here 1764 // because they are often worse to put in place. 1765 // TODO: Separate cost from availability 1766 static bool alwaysAvailable(Value *V) { 1767 return isa<Constant>(V) || isa<Argument>(V); 1768 } 1769 1770 // Get the basic block from an instruction/value. 1771 static BasicBlock *getBlockForValue(Value *V) { 1772 if (auto *I = dyn_cast<Instruction>(V)) 1773 return I->getParent(); 1774 return nullptr; 1775 } 1776 1777 struct NewGVN::ValueDFS { 1778 int DFSIn = 0; 1779 int DFSOut = 0; 1780 int LocalNum = 0; 1781 // Only one of these will be set. 1782 Value *Val = nullptr; 1783 Use *U = nullptr; 1784 1785 bool operator<(const ValueDFS &Other) const { 1786 // It's not enough that any given field be less than - we have sets 1787 // of fields that need to be evaluated together to give a proper ordering. 1788 // For example, if you have; 1789 // DFS (1, 3) 1790 // Val 0 1791 // DFS (1, 2) 1792 // Val 50 1793 // We want the second to be less than the first, but if we just go field 1794 // by field, we will get to Val 0 < Val 50 and say the first is less than 1795 // the second. We only want it to be less than if the DFS orders are equal. 1796 // 1797 // Each LLVM instruction only produces one value, and thus the lowest-level 1798 // differentiator that really matters for the stack (and what we use as as a 1799 // replacement) is the local dfs number. 1800 // Everything else in the structure is instruction level, and only affects 1801 // the order in which we will replace operands of a given instruction. 1802 // 1803 // For a given instruction (IE things with equal dfsin, dfsout, localnum), 1804 // the order of replacement of uses does not matter. 1805 // IE given, 1806 // a = 5 1807 // b = a + a 1808 // When you hit b, you will have two valuedfs with the same dfsin, out, and 1809 // localnum. 1810 // The .val will be the same as well. 1811 // The .u's will be different. 1812 // You will replace both, and it does not matter what order you replace them 1813 // in (IE whether you replace operand 2, then operand 1, or operand 1, then 1814 // operand 2). 1815 // Similarly for the case of same dfsin, dfsout, localnum, but different 1816 // .val's 1817 // a = 5 1818 // b = 6 1819 // c = a + b 1820 // in c, we will a valuedfs for a, and one for b,with everything the same 1821 // but .val and .u. 1822 // It does not matter what order we replace these operands in. 1823 // You will always end up with the same IR, and this is guaranteed. 1824 return std::tie(DFSIn, DFSOut, LocalNum, Val, U) < 1825 std::tie(Other.DFSIn, Other.DFSOut, Other.LocalNum, Other.Val, 1826 Other.U); 1827 } 1828 }; 1829 1830 void NewGVN::convertDenseToDFSOrdered( 1831 CongruenceClass::MemberSet &Dense, 1832 SmallVectorImpl<ValueDFS> &DFSOrderedSet) { 1833 for (auto D : Dense) { 1834 // First add the value. 1835 BasicBlock *BB = getBlockForValue(D); 1836 // Constants are handled prior to ever calling this function, so 1837 // we should only be left with instructions as members. 1838 assert(BB && "Should have figured out a basic block for value"); 1839 ValueDFS VD; 1840 1841 std::pair<int, int> DFSPair = DFSDomMap[BB]; 1842 assert(DFSPair.first != -1 && DFSPair.second != -1 && "Invalid DFS Pair"); 1843 VD.DFSIn = DFSPair.first; 1844 VD.DFSOut = DFSPair.second; 1845 VD.Val = D; 1846 // If it's an instruction, use the real local dfs number. 1847 if (auto *I = dyn_cast<Instruction>(D)) 1848 VD.LocalNum = InstrDFS[I]; 1849 else 1850 llvm_unreachable("Should have been an instruction"); 1851 1852 DFSOrderedSet.emplace_back(VD); 1853 1854 // Now add the users. 1855 for (auto &U : D->uses()) { 1856 if (auto *I = dyn_cast<Instruction>(U.getUser())) { 1857 ValueDFS VD; 1858 // Put the phi node uses in the incoming block. 1859 BasicBlock *IBlock; 1860 if (auto *P = dyn_cast<PHINode>(I)) { 1861 IBlock = P->getIncomingBlock(U); 1862 // Make phi node users appear last in the incoming block 1863 // they are from. 1864 VD.LocalNum = InstrDFS.size() + 1; 1865 } else { 1866 IBlock = I->getParent(); 1867 VD.LocalNum = InstrDFS[I]; 1868 } 1869 std::pair<int, int> DFSPair = DFSDomMap[IBlock]; 1870 VD.DFSIn = DFSPair.first; 1871 VD.DFSOut = DFSPair.second; 1872 VD.U = &U; 1873 DFSOrderedSet.emplace_back(VD); 1874 } 1875 } 1876 } 1877 } 1878 1879 static void patchReplacementInstruction(Instruction *I, Value *Repl) { 1880 // Patch the replacement so that it is not more restrictive than the value 1881 // being replaced. 1882 auto *Op = dyn_cast<BinaryOperator>(I); 1883 auto *ReplOp = dyn_cast<BinaryOperator>(Repl); 1884 1885 if (Op && ReplOp) 1886 ReplOp->andIRFlags(Op); 1887 1888 if (auto *ReplInst = dyn_cast<Instruction>(Repl)) { 1889 // FIXME: If both the original and replacement value are part of the 1890 // same control-flow region (meaning that the execution of one 1891 // guarentees the executation of the other), then we can combine the 1892 // noalias scopes here and do better than the general conservative 1893 // answer used in combineMetadata(). 1894 1895 // In general, GVN unifies expressions over different control-flow 1896 // regions, and so we need a conservative combination of the noalias 1897 // scopes. 1898 unsigned KnownIDs[] = { 1899 LLVMContext::MD_tbaa, LLVMContext::MD_alias_scope, 1900 LLVMContext::MD_noalias, LLVMContext::MD_range, 1901 LLVMContext::MD_fpmath, LLVMContext::MD_invariant_load, 1902 LLVMContext::MD_invariant_group}; 1903 combineMetadata(ReplInst, I, KnownIDs); 1904 } 1905 } 1906 1907 static void patchAndReplaceAllUsesWith(Instruction *I, Value *Repl) { 1908 patchReplacementInstruction(I, Repl); 1909 I->replaceAllUsesWith(Repl); 1910 } 1911 1912 void NewGVN::deleteInstructionsInBlock(BasicBlock *BB) { 1913 DEBUG(dbgs() << " BasicBlock Dead:" << *BB); 1914 ++NumGVNBlocksDeleted; 1915 1916 // Check to see if there are non-terminating instructions to delete. 1917 if (isa<TerminatorInst>(BB->begin())) 1918 return; 1919 1920 // Delete the instructions backwards, as it has a reduced likelihood of having 1921 // to update as many def-use and use-def chains. Start after the terminator. 1922 auto StartPoint = BB->rbegin(); 1923 ++StartPoint; 1924 // Note that we explicitly recalculate BB->rend() on each iteration, 1925 // as it may change when we remove the first instruction. 1926 for (BasicBlock::reverse_iterator I(StartPoint); I != BB->rend();) { 1927 Instruction &Inst = *I++; 1928 if (!Inst.use_empty()) 1929 Inst.replaceAllUsesWith(UndefValue::get(Inst.getType())); 1930 if (isa<LandingPadInst>(Inst)) 1931 continue; 1932 1933 Inst.eraseFromParent(); 1934 ++NumGVNInstrDeleted; 1935 } 1936 } 1937 1938 void NewGVN::markInstructionForDeletion(Instruction *I) { 1939 DEBUG(dbgs() << "Marking " << *I << " for deletion\n"); 1940 InstructionsToErase.insert(I); 1941 } 1942 1943 void NewGVN::replaceInstruction(Instruction *I, Value *V) { 1944 1945 DEBUG(dbgs() << "Replacing " << *I << " with " << *V << "\n"); 1946 patchAndReplaceAllUsesWith(I, V); 1947 // We save the actual erasing to avoid invalidating memory 1948 // dependencies until we are done with everything. 1949 markInstructionForDeletion(I); 1950 } 1951 1952 namespace { 1953 1954 // This is a stack that contains both the value and dfs info of where 1955 // that value is valid. 1956 class ValueDFSStack { 1957 public: 1958 Value *back() const { return ValueStack.back(); } 1959 std::pair<int, int> dfs_back() const { return DFSStack.back(); } 1960 1961 void push_back(Value *V, int DFSIn, int DFSOut) { 1962 ValueStack.emplace_back(V); 1963 DFSStack.emplace_back(DFSIn, DFSOut); 1964 } 1965 bool empty() const { return DFSStack.empty(); } 1966 bool isInScope(int DFSIn, int DFSOut) const { 1967 if (empty()) 1968 return false; 1969 return DFSIn >= DFSStack.back().first && DFSOut <= DFSStack.back().second; 1970 } 1971 1972 void popUntilDFSScope(int DFSIn, int DFSOut) { 1973 1974 // These two should always be in sync at this point. 1975 assert(ValueStack.size() == DFSStack.size() && 1976 "Mismatch between ValueStack and DFSStack"); 1977 while ( 1978 !DFSStack.empty() && 1979 !(DFSIn >= DFSStack.back().first && DFSOut <= DFSStack.back().second)) { 1980 DFSStack.pop_back(); 1981 ValueStack.pop_back(); 1982 } 1983 } 1984 1985 private: 1986 SmallVector<Value *, 8> ValueStack; 1987 SmallVector<std::pair<int, int>, 8> DFSStack; 1988 }; 1989 } 1990 1991 bool NewGVN::eliminateInstructions(Function &F) { 1992 // This is a non-standard eliminator. The normal way to eliminate is 1993 // to walk the dominator tree in order, keeping track of available 1994 // values, and eliminating them. However, this is mildly 1995 // pointless. It requires doing lookups on every instruction, 1996 // regardless of whether we will ever eliminate it. For 1997 // instructions part of most singleton congruence classes, we know we 1998 // will never eliminate them. 1999 2000 // Instead, this eliminator looks at the congruence classes directly, sorts 2001 // them into a DFS ordering of the dominator tree, and then we just 2002 // perform elimination straight on the sets by walking the congruence 2003 // class member uses in order, and eliminate the ones dominated by the 2004 // last member. This is worst case O(E log E) where E = number of 2005 // instructions in a single congruence class. In theory, this is all 2006 // instructions. In practice, it is much faster, as most instructions are 2007 // either in singleton congruence classes or can't possibly be eliminated 2008 // anyway (if there are no overlapping DFS ranges in class). 2009 // When we find something not dominated, it becomes the new leader 2010 // for elimination purposes. 2011 // TODO: If we wanted to be faster, We could remove any members with no 2012 // overlapping ranges while sorting, as we will never eliminate anything 2013 // with those members, as they don't dominate anything else in our set. 2014 2015 bool AnythingReplaced = false; 2016 2017 // Since we are going to walk the domtree anyway, and we can't guarantee the 2018 // DFS numbers are updated, we compute some ourselves. 2019 DT->updateDFSNumbers(); 2020 2021 for (auto &B : F) { 2022 if (!ReachableBlocks.count(&B)) { 2023 for (const auto S : successors(&B)) { 2024 for (auto II = S->begin(); isa<PHINode>(II); ++II) { 2025 auto &Phi = cast<PHINode>(*II); 2026 DEBUG(dbgs() << "Replacing incoming value of " << *II << " for block " 2027 << getBlockName(&B) 2028 << " with undef due to it being unreachable\n"); 2029 for (auto &Operand : Phi.incoming_values()) 2030 if (Phi.getIncomingBlock(Operand) == &B) 2031 Operand.set(UndefValue::get(Phi.getType())); 2032 } 2033 } 2034 } 2035 DomTreeNode *Node = DT->getNode(&B); 2036 if (Node) 2037 DFSDomMap[&B] = {Node->getDFSNumIn(), Node->getDFSNumOut()}; 2038 } 2039 2040 for (CongruenceClass *CC : CongruenceClasses) { 2041 // FIXME: We should eventually be able to replace everything still 2042 // in the initial class with undef, as they should be unreachable. 2043 // Right now, initial still contains some things we skip value 2044 // numbering of (UNREACHABLE's, for example). 2045 if (CC == InitialClass || CC->Dead) 2046 continue; 2047 assert(CC->RepLeader && "We should have had a leader"); 2048 2049 // If this is a leader that is always available, and it's a 2050 // constant or has no equivalences, just replace everything with 2051 // it. We then update the congruence class with whatever members 2052 // are left. 2053 if (alwaysAvailable(CC->RepLeader)) { 2054 SmallPtrSet<Value *, 4> MembersLeft; 2055 for (auto M : CC->Members) { 2056 2057 Value *Member = M; 2058 2059 // Void things have no uses we can replace. 2060 if (Member == CC->RepLeader || Member->getType()->isVoidTy()) { 2061 MembersLeft.insert(Member); 2062 continue; 2063 } 2064 2065 DEBUG(dbgs() << "Found replacement " << *(CC->RepLeader) << " for " 2066 << *Member << "\n"); 2067 // Due to equality propagation, these may not always be 2068 // instructions, they may be real values. We don't really 2069 // care about trying to replace the non-instructions. 2070 if (auto *I = dyn_cast<Instruction>(Member)) { 2071 assert(CC->RepLeader != I && 2072 "About to accidentally remove our leader"); 2073 replaceInstruction(I, CC->RepLeader); 2074 AnythingReplaced = true; 2075 2076 continue; 2077 } else { 2078 MembersLeft.insert(I); 2079 } 2080 } 2081 CC->Members.swap(MembersLeft); 2082 2083 } else { 2084 DEBUG(dbgs() << "Eliminating in congruence class " << CC->ID << "\n"); 2085 // If this is a singleton, we can skip it. 2086 if (CC->Members.size() != 1) { 2087 2088 // This is a stack because equality replacement/etc may place 2089 // constants in the middle of the member list, and we want to use 2090 // those constant values in preference to the current leader, over 2091 // the scope of those constants. 2092 ValueDFSStack EliminationStack; 2093 2094 // Convert the members to DFS ordered sets and then merge them. 2095 SmallVector<ValueDFS, 8> DFSOrderedSet; 2096 convertDenseToDFSOrdered(CC->Members, DFSOrderedSet); 2097 2098 // Sort the whole thing. 2099 std::sort(DFSOrderedSet.begin(), DFSOrderedSet.end()); 2100 2101 for (auto &VD : DFSOrderedSet) { 2102 int MemberDFSIn = VD.DFSIn; 2103 int MemberDFSOut = VD.DFSOut; 2104 Value *Member = VD.Val; 2105 Use *MemberUse = VD.U; 2106 2107 if (Member) { 2108 // We ignore void things because we can't get a value from them. 2109 // FIXME: We could actually use this to kill dead stores that are 2110 // dominated by equivalent earlier stores. 2111 if (Member->getType()->isVoidTy()) 2112 continue; 2113 } 2114 2115 if (EliminationStack.empty()) { 2116 DEBUG(dbgs() << "Elimination Stack is empty\n"); 2117 } else { 2118 DEBUG(dbgs() << "Elimination Stack Top DFS numbers are (" 2119 << EliminationStack.dfs_back().first << "," 2120 << EliminationStack.dfs_back().second << ")\n"); 2121 } 2122 2123 DEBUG(dbgs() << "Current DFS numbers are (" << MemberDFSIn << "," 2124 << MemberDFSOut << ")\n"); 2125 // First, we see if we are out of scope or empty. If so, 2126 // and there equivalences, we try to replace the top of 2127 // stack with equivalences (if it's on the stack, it must 2128 // not have been eliminated yet). 2129 // Then we synchronize to our current scope, by 2130 // popping until we are back within a DFS scope that 2131 // dominates the current member. 2132 // Then, what happens depends on a few factors 2133 // If the stack is now empty, we need to push 2134 // If we have a constant or a local equivalence we want to 2135 // start using, we also push. 2136 // Otherwise, we walk along, processing members who are 2137 // dominated by this scope, and eliminate them. 2138 bool ShouldPush = 2139 Member && (EliminationStack.empty() || isa<Constant>(Member)); 2140 bool OutOfScope = 2141 !EliminationStack.isInScope(MemberDFSIn, MemberDFSOut); 2142 2143 if (OutOfScope || ShouldPush) { 2144 // Sync to our current scope. 2145 EliminationStack.popUntilDFSScope(MemberDFSIn, MemberDFSOut); 2146 ShouldPush |= Member && EliminationStack.empty(); 2147 if (ShouldPush) { 2148 EliminationStack.push_back(Member, MemberDFSIn, MemberDFSOut); 2149 } 2150 } 2151 2152 // If we get to this point, and the stack is empty we must have a use 2153 // with nothing we can use to eliminate it, just skip it. 2154 if (EliminationStack.empty()) 2155 continue; 2156 2157 // Skip the Value's, we only want to eliminate on their uses. 2158 if (Member) 2159 continue; 2160 Value *Result = EliminationStack.back(); 2161 2162 // Don't replace our existing users with ourselves. 2163 if (MemberUse->get() == Result) 2164 continue; 2165 2166 DEBUG(dbgs() << "Found replacement " << *Result << " for " 2167 << *MemberUse->get() << " in " << *(MemberUse->getUser()) 2168 << "\n"); 2169 2170 // If we replaced something in an instruction, handle the patching of 2171 // metadata. 2172 if (auto *ReplacedInst = dyn_cast<Instruction>(MemberUse->get())) 2173 patchReplacementInstruction(ReplacedInst, Result); 2174 2175 assert(isa<Instruction>(MemberUse->getUser())); 2176 MemberUse->set(Result); 2177 AnythingReplaced = true; 2178 } 2179 } 2180 } 2181 2182 // Cleanup the congruence class. 2183 SmallPtrSet<Value *, 4> MembersLeft; 2184 for (Value *Member : CC->Members) { 2185 if (Member->getType()->isVoidTy()) { 2186 MembersLeft.insert(Member); 2187 continue; 2188 } 2189 2190 if (auto *MemberInst = dyn_cast<Instruction>(Member)) { 2191 if (isInstructionTriviallyDead(MemberInst)) { 2192 // TODO: Don't mark loads of undefs. 2193 markInstructionForDeletion(MemberInst); 2194 continue; 2195 } 2196 } 2197 MembersLeft.insert(Member); 2198 } 2199 CC->Members.swap(MembersLeft); 2200 } 2201 2202 return AnythingReplaced; 2203 } 2204