1 //===- GVN.cpp - Eliminate redundant values and loads ---------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This pass performs global value numbering to eliminate fully redundant 10 // instructions. It also performs simple dead load elimination. 11 // 12 // Note that this pass does the value numbering itself; it does not use the 13 // ValueNumbering analysis passes. 14 // 15 //===----------------------------------------------------------------------===// 16 17 #include "llvm/Transforms/Scalar/GVN.h" 18 #include "llvm/ADT/DenseMap.h" 19 #include "llvm/ADT/DepthFirstIterator.h" 20 #include "llvm/ADT/Hashing.h" 21 #include "llvm/ADT/MapVector.h" 22 #include "llvm/ADT/PointerIntPair.h" 23 #include "llvm/ADT/PostOrderIterator.h" 24 #include "llvm/ADT/STLExtras.h" 25 #include "llvm/ADT/SetVector.h" 26 #include "llvm/ADT/SmallPtrSet.h" 27 #include "llvm/ADT/SmallVector.h" 28 #include "llvm/ADT/Statistic.h" 29 #include "llvm/Analysis/AliasAnalysis.h" 30 #include "llvm/Analysis/AssumeBundleQueries.h" 31 #include "llvm/Analysis/AssumptionCache.h" 32 #include "llvm/Analysis/CFG.h" 33 #include "llvm/Analysis/DomTreeUpdater.h" 34 #include "llvm/Analysis/GlobalsModRef.h" 35 #include "llvm/Analysis/InstructionSimplify.h" 36 #include "llvm/Analysis/LoopInfo.h" 37 #include "llvm/Analysis/MemoryBuiltins.h" 38 #include "llvm/Analysis/MemoryDependenceAnalysis.h" 39 #include "llvm/Analysis/MemorySSA.h" 40 #include "llvm/Analysis/MemorySSAUpdater.h" 41 #include "llvm/Analysis/OptimizationRemarkEmitter.h" 42 #include "llvm/Analysis/PHITransAddr.h" 43 #include "llvm/Analysis/TargetLibraryInfo.h" 44 #include "llvm/Analysis/ValueTracking.h" 45 #include "llvm/Config/llvm-config.h" 46 #include "llvm/IR/Attributes.h" 47 #include "llvm/IR/BasicBlock.h" 48 #include "llvm/IR/Constant.h" 49 #include "llvm/IR/Constants.h" 50 #include "llvm/IR/DataLayout.h" 51 #include "llvm/IR/DebugInfoMetadata.h" 52 #include "llvm/IR/DebugLoc.h" 53 #include "llvm/IR/Dominators.h" 54 #include "llvm/IR/Function.h" 55 #include "llvm/IR/InstrTypes.h" 56 #include "llvm/IR/Instruction.h" 57 #include "llvm/IR/Instructions.h" 58 #include "llvm/IR/IntrinsicInst.h" 59 #include "llvm/IR/Intrinsics.h" 60 #include "llvm/IR/LLVMContext.h" 61 #include "llvm/IR/Metadata.h" 62 #include "llvm/IR/Module.h" 63 #include "llvm/IR/Operator.h" 64 #include "llvm/IR/PassManager.h" 65 #include "llvm/IR/PatternMatch.h" 66 #include "llvm/IR/Type.h" 67 #include "llvm/IR/Use.h" 68 #include "llvm/IR/Value.h" 69 #include "llvm/InitializePasses.h" 70 #include "llvm/Pass.h" 71 #include "llvm/Support/Casting.h" 72 #include "llvm/Support/CommandLine.h" 73 #include "llvm/Support/Compiler.h" 74 #include "llvm/Support/Debug.h" 75 #include "llvm/Support/raw_ostream.h" 76 #include "llvm/Transforms/Utils.h" 77 #include "llvm/Transforms/Utils/AssumeBundleBuilder.h" 78 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 79 #include "llvm/Transforms/Utils/Local.h" 80 #include "llvm/Transforms/Utils/SSAUpdater.h" 81 #include "llvm/Transforms/Utils/VNCoercion.h" 82 #include <algorithm> 83 #include <cassert> 84 #include <cstdint> 85 #include <utility> 86 #include <vector> 87 88 using namespace llvm; 89 using namespace llvm::gvn; 90 using namespace llvm::VNCoercion; 91 using namespace PatternMatch; 92 93 #define DEBUG_TYPE "gvn" 94 95 STATISTIC(NumGVNInstr, "Number of instructions deleted"); 96 STATISTIC(NumGVNLoad, "Number of loads deleted"); 97 STATISTIC(NumGVNPRE, "Number of instructions PRE'd"); 98 STATISTIC(NumGVNBlocks, "Number of blocks merged"); 99 STATISTIC(NumGVNSimpl, "Number of instructions simplified"); 100 STATISTIC(NumGVNEqProp, "Number of equalities propagated"); 101 STATISTIC(NumPRELoad, "Number of loads PRE'd"); 102 103 STATISTIC(IsValueFullyAvailableInBlockNumSpeculationsMax, 104 "Number of blocks speculated as available in " 105 "IsValueFullyAvailableInBlock(), max"); 106 STATISTIC(MaxBBSpeculationCutoffReachedTimes, 107 "Number of times we we reached gvn-max-block-speculations cut-off " 108 "preventing further exploration"); 109 110 static cl::opt<bool> GVNEnablePRE("enable-pre", cl::init(true), cl::Hidden); 111 static cl::opt<bool> GVNEnableLoadPRE("enable-load-pre", cl::init(true)); 112 static cl::opt<bool> GVNEnableLoadInLoopPRE("enable-load-in-loop-pre", 113 cl::init(true)); 114 static cl::opt<bool> GVNEnableMemDep("enable-gvn-memdep", cl::init(true)); 115 116 static cl::opt<uint32_t> MaxNumDeps( 117 "gvn-max-num-deps", cl::Hidden, cl::init(100), cl::ZeroOrMore, 118 cl::desc("Max number of dependences to attempt Load PRE (default = 100)")); 119 120 // This is based on IsValueFullyAvailableInBlockNumSpeculationsMax stat. 121 static cl::opt<uint32_t> MaxBBSpeculations( 122 "gvn-max-block-speculations", cl::Hidden, cl::init(600), cl::ZeroOrMore, 123 cl::desc("Max number of blocks we're willing to speculate on (and recurse " 124 "into) when deducing if a value is fully available or not in GVN " 125 "(default = 600)")); 126 127 struct llvm::GVN::Expression { 128 uint32_t opcode; 129 bool commutative = false; 130 Type *type = nullptr; 131 SmallVector<uint32_t, 4> varargs; 132 133 Expression(uint32_t o = ~2U) : opcode(o) {} 134 135 bool operator==(const Expression &other) const { 136 if (opcode != other.opcode) 137 return false; 138 if (opcode == ~0U || opcode == ~1U) 139 return true; 140 if (type != other.type) 141 return false; 142 if (varargs != other.varargs) 143 return false; 144 return true; 145 } 146 147 friend hash_code hash_value(const Expression &Value) { 148 return hash_combine( 149 Value.opcode, Value.type, 150 hash_combine_range(Value.varargs.begin(), Value.varargs.end())); 151 } 152 }; 153 154 namespace llvm { 155 156 template <> struct DenseMapInfo<GVN::Expression> { 157 static inline GVN::Expression getEmptyKey() { return ~0U; } 158 static inline GVN::Expression getTombstoneKey() { return ~1U; } 159 160 static unsigned getHashValue(const GVN::Expression &e) { 161 using llvm::hash_value; 162 163 return static_cast<unsigned>(hash_value(e)); 164 } 165 166 static bool isEqual(const GVN::Expression &LHS, const GVN::Expression &RHS) { 167 return LHS == RHS; 168 } 169 }; 170 171 } // end namespace llvm 172 173 /// Represents a particular available value that we know how to materialize. 174 /// Materialization of an AvailableValue never fails. An AvailableValue is 175 /// implicitly associated with a rematerialization point which is the 176 /// location of the instruction from which it was formed. 177 struct llvm::gvn::AvailableValue { 178 enum ValType { 179 SimpleVal, // A simple offsetted value that is accessed. 180 LoadVal, // A value produced by a load. 181 MemIntrin, // A memory intrinsic which is loaded from. 182 UndefVal // A UndefValue representing a value from dead block (which 183 // is not yet physically removed from the CFG). 184 }; 185 186 /// V - The value that is live out of the block. 187 PointerIntPair<Value *, 2, ValType> Val; 188 189 /// Offset - The byte offset in Val that is interesting for the load query. 190 unsigned Offset = 0; 191 192 static AvailableValue get(Value *V, unsigned Offset = 0) { 193 AvailableValue Res; 194 Res.Val.setPointer(V); 195 Res.Val.setInt(SimpleVal); 196 Res.Offset = Offset; 197 return Res; 198 } 199 200 static AvailableValue getMI(MemIntrinsic *MI, unsigned Offset = 0) { 201 AvailableValue Res; 202 Res.Val.setPointer(MI); 203 Res.Val.setInt(MemIntrin); 204 Res.Offset = Offset; 205 return Res; 206 } 207 208 static AvailableValue getLoad(LoadInst *LI, unsigned Offset = 0) { 209 AvailableValue Res; 210 Res.Val.setPointer(LI); 211 Res.Val.setInt(LoadVal); 212 Res.Offset = Offset; 213 return Res; 214 } 215 216 static AvailableValue getUndef() { 217 AvailableValue Res; 218 Res.Val.setPointer(nullptr); 219 Res.Val.setInt(UndefVal); 220 Res.Offset = 0; 221 return Res; 222 } 223 224 bool isSimpleValue() const { return Val.getInt() == SimpleVal; } 225 bool isCoercedLoadValue() const { return Val.getInt() == LoadVal; } 226 bool isMemIntrinValue() const { return Val.getInt() == MemIntrin; } 227 bool isUndefValue() const { return Val.getInt() == UndefVal; } 228 229 Value *getSimpleValue() const { 230 assert(isSimpleValue() && "Wrong accessor"); 231 return Val.getPointer(); 232 } 233 234 LoadInst *getCoercedLoadValue() const { 235 assert(isCoercedLoadValue() && "Wrong accessor"); 236 return cast<LoadInst>(Val.getPointer()); 237 } 238 239 MemIntrinsic *getMemIntrinValue() const { 240 assert(isMemIntrinValue() && "Wrong accessor"); 241 return cast<MemIntrinsic>(Val.getPointer()); 242 } 243 244 /// Emit code at the specified insertion point to adjust the value defined 245 /// here to the specified type. This handles various coercion cases. 246 Value *MaterializeAdjustedValue(LoadInst *LI, Instruction *InsertPt, 247 GVN &gvn) const; 248 }; 249 250 /// Represents an AvailableValue which can be rematerialized at the end of 251 /// the associated BasicBlock. 252 struct llvm::gvn::AvailableValueInBlock { 253 /// BB - The basic block in question. 254 BasicBlock *BB = nullptr; 255 256 /// AV - The actual available value 257 AvailableValue AV; 258 259 static AvailableValueInBlock get(BasicBlock *BB, AvailableValue &&AV) { 260 AvailableValueInBlock Res; 261 Res.BB = BB; 262 Res.AV = std::move(AV); 263 return Res; 264 } 265 266 static AvailableValueInBlock get(BasicBlock *BB, Value *V, 267 unsigned Offset = 0) { 268 return get(BB, AvailableValue::get(V, Offset)); 269 } 270 271 static AvailableValueInBlock getUndef(BasicBlock *BB) { 272 return get(BB, AvailableValue::getUndef()); 273 } 274 275 /// Emit code at the end of this block to adjust the value defined here to 276 /// the specified type. This handles various coercion cases. 277 Value *MaterializeAdjustedValue(LoadInst *LI, GVN &gvn) const { 278 return AV.MaterializeAdjustedValue(LI, BB->getTerminator(), gvn); 279 } 280 }; 281 282 //===----------------------------------------------------------------------===// 283 // ValueTable Internal Functions 284 //===----------------------------------------------------------------------===// 285 286 GVN::Expression GVN::ValueTable::createExpr(Instruction *I) { 287 Expression e; 288 e.type = I->getType(); 289 e.opcode = I->getOpcode(); 290 for (Instruction::op_iterator OI = I->op_begin(), OE = I->op_end(); 291 OI != OE; ++OI) 292 e.varargs.push_back(lookupOrAdd(*OI)); 293 if (I->isCommutative()) { 294 // Ensure that commutative instructions that only differ by a permutation 295 // of their operands get the same value number by sorting the operand value 296 // numbers. Since commutative operands are the 1st two operands it is more 297 // efficient to sort by hand rather than using, say, std::sort. 298 assert(I->getNumOperands() >= 2 && "Unsupported commutative instruction!"); 299 if (e.varargs[0] > e.varargs[1]) 300 std::swap(e.varargs[0], e.varargs[1]); 301 e.commutative = true; 302 } 303 304 if (auto *C = dyn_cast<CmpInst>(I)) { 305 // Sort the operand value numbers so x<y and y>x get the same value number. 306 CmpInst::Predicate Predicate = C->getPredicate(); 307 if (e.varargs[0] > e.varargs[1]) { 308 std::swap(e.varargs[0], e.varargs[1]); 309 Predicate = CmpInst::getSwappedPredicate(Predicate); 310 } 311 e.opcode = (C->getOpcode() << 8) | Predicate; 312 e.commutative = true; 313 } else if (auto *E = dyn_cast<InsertValueInst>(I)) { 314 e.varargs.append(E->idx_begin(), E->idx_end()); 315 } else if (auto *SVI = dyn_cast<ShuffleVectorInst>(I)) { 316 ArrayRef<int> ShuffleMask = SVI->getShuffleMask(); 317 e.varargs.append(ShuffleMask.begin(), ShuffleMask.end()); 318 } 319 320 return e; 321 } 322 323 GVN::Expression GVN::ValueTable::createCmpExpr(unsigned Opcode, 324 CmpInst::Predicate Predicate, 325 Value *LHS, Value *RHS) { 326 assert((Opcode == Instruction::ICmp || Opcode == Instruction::FCmp) && 327 "Not a comparison!"); 328 Expression e; 329 e.type = CmpInst::makeCmpResultType(LHS->getType()); 330 e.varargs.push_back(lookupOrAdd(LHS)); 331 e.varargs.push_back(lookupOrAdd(RHS)); 332 333 // Sort the operand value numbers so x<y and y>x get the same value number. 334 if (e.varargs[0] > e.varargs[1]) { 335 std::swap(e.varargs[0], e.varargs[1]); 336 Predicate = CmpInst::getSwappedPredicate(Predicate); 337 } 338 e.opcode = (Opcode << 8) | Predicate; 339 e.commutative = true; 340 return e; 341 } 342 343 GVN::Expression GVN::ValueTable::createExtractvalueExpr(ExtractValueInst *EI) { 344 assert(EI && "Not an ExtractValueInst?"); 345 Expression e; 346 e.type = EI->getType(); 347 e.opcode = 0; 348 349 WithOverflowInst *WO = dyn_cast<WithOverflowInst>(EI->getAggregateOperand()); 350 if (WO != nullptr && EI->getNumIndices() == 1 && *EI->idx_begin() == 0) { 351 // EI is an extract from one of our with.overflow intrinsics. Synthesize 352 // a semantically equivalent expression instead of an extract value 353 // expression. 354 e.opcode = WO->getBinaryOp(); 355 e.varargs.push_back(lookupOrAdd(WO->getLHS())); 356 e.varargs.push_back(lookupOrAdd(WO->getRHS())); 357 return e; 358 } 359 360 // Not a recognised intrinsic. Fall back to producing an extract value 361 // expression. 362 e.opcode = EI->getOpcode(); 363 for (Instruction::op_iterator OI = EI->op_begin(), OE = EI->op_end(); 364 OI != OE; ++OI) 365 e.varargs.push_back(lookupOrAdd(*OI)); 366 367 for (ExtractValueInst::idx_iterator II = EI->idx_begin(), IE = EI->idx_end(); 368 II != IE; ++II) 369 e.varargs.push_back(*II); 370 371 return e; 372 } 373 374 //===----------------------------------------------------------------------===// 375 // ValueTable External Functions 376 //===----------------------------------------------------------------------===// 377 378 GVN::ValueTable::ValueTable() = default; 379 GVN::ValueTable::ValueTable(const ValueTable &) = default; 380 GVN::ValueTable::ValueTable(ValueTable &&) = default; 381 GVN::ValueTable::~ValueTable() = default; 382 GVN::ValueTable &GVN::ValueTable::operator=(const GVN::ValueTable &Arg) = default; 383 384 /// add - Insert a value into the table with a specified value number. 385 void GVN::ValueTable::add(Value *V, uint32_t num) { 386 valueNumbering.insert(std::make_pair(V, num)); 387 if (PHINode *PN = dyn_cast<PHINode>(V)) 388 NumberingPhi[num] = PN; 389 } 390 391 uint32_t GVN::ValueTable::lookupOrAddCall(CallInst *C) { 392 if (AA->doesNotAccessMemory(C)) { 393 Expression exp = createExpr(C); 394 uint32_t e = assignExpNewValueNum(exp).first; 395 valueNumbering[C] = e; 396 return e; 397 } else if (MD && AA->onlyReadsMemory(C)) { 398 Expression exp = createExpr(C); 399 auto ValNum = assignExpNewValueNum(exp); 400 if (ValNum.second) { 401 valueNumbering[C] = ValNum.first; 402 return ValNum.first; 403 } 404 405 MemDepResult local_dep = MD->getDependency(C); 406 407 if (!local_dep.isDef() && !local_dep.isNonLocal()) { 408 valueNumbering[C] = nextValueNumber; 409 return nextValueNumber++; 410 } 411 412 if (local_dep.isDef()) { 413 // For masked load/store intrinsics, the local_dep may actully be 414 // a normal load or store instruction. 415 CallInst *local_cdep = dyn_cast<CallInst>(local_dep.getInst()); 416 417 if (!local_cdep || 418 local_cdep->getNumArgOperands() != C->getNumArgOperands()) { 419 valueNumbering[C] = nextValueNumber; 420 return nextValueNumber++; 421 } 422 423 for (unsigned i = 0, e = C->getNumArgOperands(); i < e; ++i) { 424 uint32_t c_vn = lookupOrAdd(C->getArgOperand(i)); 425 uint32_t cd_vn = lookupOrAdd(local_cdep->getArgOperand(i)); 426 if (c_vn != cd_vn) { 427 valueNumbering[C] = nextValueNumber; 428 return nextValueNumber++; 429 } 430 } 431 432 uint32_t v = lookupOrAdd(local_cdep); 433 valueNumbering[C] = v; 434 return v; 435 } 436 437 // Non-local case. 438 const MemoryDependenceResults::NonLocalDepInfo &deps = 439 MD->getNonLocalCallDependency(C); 440 // FIXME: Move the checking logic to MemDep! 441 CallInst* cdep = nullptr; 442 443 // Check to see if we have a single dominating call instruction that is 444 // identical to C. 445 for (unsigned i = 0, e = deps.size(); i != e; ++i) { 446 const NonLocalDepEntry *I = &deps[i]; 447 if (I->getResult().isNonLocal()) 448 continue; 449 450 // We don't handle non-definitions. If we already have a call, reject 451 // instruction dependencies. 452 if (!I->getResult().isDef() || cdep != nullptr) { 453 cdep = nullptr; 454 break; 455 } 456 457 CallInst *NonLocalDepCall = dyn_cast<CallInst>(I->getResult().getInst()); 458 // FIXME: All duplicated with non-local case. 459 if (NonLocalDepCall && DT->properlyDominates(I->getBB(), C->getParent())){ 460 cdep = NonLocalDepCall; 461 continue; 462 } 463 464 cdep = nullptr; 465 break; 466 } 467 468 if (!cdep) { 469 valueNumbering[C] = nextValueNumber; 470 return nextValueNumber++; 471 } 472 473 if (cdep->getNumArgOperands() != C->getNumArgOperands()) { 474 valueNumbering[C] = nextValueNumber; 475 return nextValueNumber++; 476 } 477 for (unsigned i = 0, e = C->getNumArgOperands(); i < e; ++i) { 478 uint32_t c_vn = lookupOrAdd(C->getArgOperand(i)); 479 uint32_t cd_vn = lookupOrAdd(cdep->getArgOperand(i)); 480 if (c_vn != cd_vn) { 481 valueNumbering[C] = nextValueNumber; 482 return nextValueNumber++; 483 } 484 } 485 486 uint32_t v = lookupOrAdd(cdep); 487 valueNumbering[C] = v; 488 return v; 489 } else { 490 valueNumbering[C] = nextValueNumber; 491 return nextValueNumber++; 492 } 493 } 494 495 /// Returns true if a value number exists for the specified value. 496 bool GVN::ValueTable::exists(Value *V) const { return valueNumbering.count(V) != 0; } 497 498 /// lookup_or_add - Returns the value number for the specified value, assigning 499 /// it a new number if it did not have one before. 500 uint32_t GVN::ValueTable::lookupOrAdd(Value *V) { 501 DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V); 502 if (VI != valueNumbering.end()) 503 return VI->second; 504 505 if (!isa<Instruction>(V)) { 506 valueNumbering[V] = nextValueNumber; 507 return nextValueNumber++; 508 } 509 510 Instruction* I = cast<Instruction>(V); 511 Expression exp; 512 switch (I->getOpcode()) { 513 case Instruction::Call: 514 return lookupOrAddCall(cast<CallInst>(I)); 515 case Instruction::FNeg: 516 case Instruction::Add: 517 case Instruction::FAdd: 518 case Instruction::Sub: 519 case Instruction::FSub: 520 case Instruction::Mul: 521 case Instruction::FMul: 522 case Instruction::UDiv: 523 case Instruction::SDiv: 524 case Instruction::FDiv: 525 case Instruction::URem: 526 case Instruction::SRem: 527 case Instruction::FRem: 528 case Instruction::Shl: 529 case Instruction::LShr: 530 case Instruction::AShr: 531 case Instruction::And: 532 case Instruction::Or: 533 case Instruction::Xor: 534 case Instruction::ICmp: 535 case Instruction::FCmp: 536 case Instruction::Trunc: 537 case Instruction::ZExt: 538 case Instruction::SExt: 539 case Instruction::FPToUI: 540 case Instruction::FPToSI: 541 case Instruction::UIToFP: 542 case Instruction::SIToFP: 543 case Instruction::FPTrunc: 544 case Instruction::FPExt: 545 case Instruction::PtrToInt: 546 case Instruction::IntToPtr: 547 case Instruction::AddrSpaceCast: 548 case Instruction::BitCast: 549 case Instruction::Select: 550 case Instruction::Freeze: 551 case Instruction::ExtractElement: 552 case Instruction::InsertElement: 553 case Instruction::ShuffleVector: 554 case Instruction::InsertValue: 555 case Instruction::GetElementPtr: 556 exp = createExpr(I); 557 break; 558 case Instruction::ExtractValue: 559 exp = createExtractvalueExpr(cast<ExtractValueInst>(I)); 560 break; 561 case Instruction::PHI: 562 valueNumbering[V] = nextValueNumber; 563 NumberingPhi[nextValueNumber] = cast<PHINode>(V); 564 return nextValueNumber++; 565 default: 566 valueNumbering[V] = nextValueNumber; 567 return nextValueNumber++; 568 } 569 570 uint32_t e = assignExpNewValueNum(exp).first; 571 valueNumbering[V] = e; 572 return e; 573 } 574 575 /// Returns the value number of the specified value. Fails if 576 /// the value has not yet been numbered. 577 uint32_t GVN::ValueTable::lookup(Value *V, bool Verify) const { 578 DenseMap<Value*, uint32_t>::const_iterator VI = valueNumbering.find(V); 579 if (Verify) { 580 assert(VI != valueNumbering.end() && "Value not numbered?"); 581 return VI->second; 582 } 583 return (VI != valueNumbering.end()) ? VI->second : 0; 584 } 585 586 /// Returns the value number of the given comparison, 587 /// assigning it a new number if it did not have one before. Useful when 588 /// we deduced the result of a comparison, but don't immediately have an 589 /// instruction realizing that comparison to hand. 590 uint32_t GVN::ValueTable::lookupOrAddCmp(unsigned Opcode, 591 CmpInst::Predicate Predicate, 592 Value *LHS, Value *RHS) { 593 Expression exp = createCmpExpr(Opcode, Predicate, LHS, RHS); 594 return assignExpNewValueNum(exp).first; 595 } 596 597 /// Remove all entries from the ValueTable. 598 void GVN::ValueTable::clear() { 599 valueNumbering.clear(); 600 expressionNumbering.clear(); 601 NumberingPhi.clear(); 602 PhiTranslateTable.clear(); 603 nextValueNumber = 1; 604 Expressions.clear(); 605 ExprIdx.clear(); 606 nextExprNumber = 0; 607 } 608 609 /// Remove a value from the value numbering. 610 void GVN::ValueTable::erase(Value *V) { 611 uint32_t Num = valueNumbering.lookup(V); 612 valueNumbering.erase(V); 613 // If V is PHINode, V <--> value number is an one-to-one mapping. 614 if (isa<PHINode>(V)) 615 NumberingPhi.erase(Num); 616 } 617 618 /// verifyRemoved - Verify that the value is removed from all internal data 619 /// structures. 620 void GVN::ValueTable::verifyRemoved(const Value *V) const { 621 for (DenseMap<Value*, uint32_t>::const_iterator 622 I = valueNumbering.begin(), E = valueNumbering.end(); I != E; ++I) { 623 assert(I->first != V && "Inst still occurs in value numbering map!"); 624 } 625 } 626 627 //===----------------------------------------------------------------------===// 628 // GVN Pass 629 //===----------------------------------------------------------------------===// 630 631 bool GVN::isPREEnabled() const { 632 return Options.AllowPRE.getValueOr(GVNEnablePRE); 633 } 634 635 bool GVN::isLoadPREEnabled() const { 636 return Options.AllowLoadPRE.getValueOr(GVNEnableLoadPRE); 637 } 638 639 bool GVN::isLoadInLoopPREEnabled() const { 640 return Options.AllowLoadInLoopPRE.getValueOr(GVNEnableLoadInLoopPRE); 641 } 642 643 bool GVN::isMemDepEnabled() const { 644 return Options.AllowMemDep.getValueOr(GVNEnableMemDep); 645 } 646 647 PreservedAnalyses GVN::run(Function &F, FunctionAnalysisManager &AM) { 648 // FIXME: The order of evaluation of these 'getResult' calls is very 649 // significant! Re-ordering these variables will cause GVN when run alone to 650 // be less effective! We should fix memdep and basic-aa to not exhibit this 651 // behavior, but until then don't change the order here. 652 auto &AC = AM.getResult<AssumptionAnalysis>(F); 653 auto &DT = AM.getResult<DominatorTreeAnalysis>(F); 654 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F); 655 auto &AA = AM.getResult<AAManager>(F); 656 auto *MemDep = 657 isMemDepEnabled() ? &AM.getResult<MemoryDependenceAnalysis>(F) : nullptr; 658 auto *LI = AM.getCachedResult<LoopAnalysis>(F); 659 auto *MSSA = AM.getCachedResult<MemorySSAAnalysis>(F); 660 auto &ORE = AM.getResult<OptimizationRemarkEmitterAnalysis>(F); 661 bool Changed = runImpl(F, AC, DT, TLI, AA, MemDep, LI, &ORE, 662 MSSA ? &MSSA->getMSSA() : nullptr); 663 if (!Changed) 664 return PreservedAnalyses::all(); 665 PreservedAnalyses PA; 666 PA.preserve<DominatorTreeAnalysis>(); 667 PA.preserve<GlobalsAA>(); 668 PA.preserve<TargetLibraryAnalysis>(); 669 if (MSSA) 670 PA.preserve<MemorySSAAnalysis>(); 671 if (LI) 672 PA.preserve<LoopAnalysis>(); 673 return PA; 674 } 675 676 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 677 LLVM_DUMP_METHOD void GVN::dump(DenseMap<uint32_t, Value*>& d) const { 678 errs() << "{\n"; 679 for (DenseMap<uint32_t, Value*>::iterator I = d.begin(), 680 E = d.end(); I != E; ++I) { 681 errs() << I->first << "\n"; 682 I->second->dump(); 683 } 684 errs() << "}\n"; 685 } 686 #endif 687 688 enum class AvailabilityState : char { 689 /// We know the block *is not* fully available. This is a fixpoint. 690 Unavailable = 0, 691 /// We know the block *is* fully available. This is a fixpoint. 692 Available = 1, 693 /// We do not know whether the block is fully available or not, 694 /// but we are currently speculating that it will be. 695 /// If it would have turned out that the block was, in fact, not fully 696 /// available, this would have been cleaned up into an Unavailable. 697 SpeculativelyAvailable = 2, 698 }; 699 700 /// Return true if we can prove that the value 701 /// we're analyzing is fully available in the specified block. As we go, keep 702 /// track of which blocks we know are fully alive in FullyAvailableBlocks. This 703 /// map is actually a tri-state map with the following values: 704 /// 0) we know the block *is not* fully available. 705 /// 1) we know the block *is* fully available. 706 /// 2) we do not know whether the block is fully available or not, but we are 707 /// currently speculating that it will be. 708 static bool IsValueFullyAvailableInBlock( 709 BasicBlock *BB, 710 DenseMap<BasicBlock *, AvailabilityState> &FullyAvailableBlocks) { 711 SmallVector<BasicBlock *, 32> Worklist; 712 Optional<BasicBlock *> UnavailableBB; 713 714 // The number of times we didn't find an entry for a block in a map and 715 // optimistically inserted an entry marking block as speculatively available. 716 unsigned NumNewNewSpeculativelyAvailableBBs = 0; 717 718 #ifndef NDEBUG 719 SmallSet<BasicBlock *, 32> NewSpeculativelyAvailableBBs; 720 SmallVector<BasicBlock *, 32> AvailableBBs; 721 #endif 722 723 Worklist.emplace_back(BB); 724 while (!Worklist.empty()) { 725 BasicBlock *CurrBB = Worklist.pop_back_val(); // LIFO - depth-first! 726 // Optimistically assume that the block is Speculatively Available and check 727 // to see if we already know about this block in one lookup. 728 std::pair<DenseMap<BasicBlock *, AvailabilityState>::iterator, bool> IV = 729 FullyAvailableBlocks.try_emplace( 730 CurrBB, AvailabilityState::SpeculativelyAvailable); 731 AvailabilityState &State = IV.first->second; 732 733 // Did the entry already exist for this block? 734 if (!IV.second) { 735 if (State == AvailabilityState::Unavailable) { 736 UnavailableBB = CurrBB; 737 break; // Backpropagate unavailability info. 738 } 739 740 #ifndef NDEBUG 741 AvailableBBs.emplace_back(CurrBB); 742 #endif 743 continue; // Don't recurse further, but continue processing worklist. 744 } 745 746 // No entry found for block. 747 ++NumNewNewSpeculativelyAvailableBBs; 748 bool OutOfBudget = NumNewNewSpeculativelyAvailableBBs > MaxBBSpeculations; 749 750 // If we have exhausted our budget, mark this block as unavailable. 751 // Also, if this block has no predecessors, the value isn't live-in here. 752 if (OutOfBudget || pred_empty(CurrBB)) { 753 MaxBBSpeculationCutoffReachedTimes += (int)OutOfBudget; 754 State = AvailabilityState::Unavailable; 755 UnavailableBB = CurrBB; 756 break; // Backpropagate unavailability info. 757 } 758 759 // Tentatively consider this block as speculatively available. 760 #ifndef NDEBUG 761 NewSpeculativelyAvailableBBs.insert(CurrBB); 762 #endif 763 // And further recurse into block's predecessors, in depth-first order! 764 Worklist.append(pred_begin(CurrBB), pred_end(CurrBB)); 765 } 766 767 #if LLVM_ENABLE_STATS 768 IsValueFullyAvailableInBlockNumSpeculationsMax.updateMax( 769 NumNewNewSpeculativelyAvailableBBs); 770 #endif 771 772 // If the block isn't marked as fixpoint yet 773 // (the Unavailable and Available states are fixpoints) 774 auto MarkAsFixpointAndEnqueueSuccessors = 775 [&](BasicBlock *BB, AvailabilityState FixpointState) { 776 auto It = FullyAvailableBlocks.find(BB); 777 if (It == FullyAvailableBlocks.end()) 778 return; // Never queried this block, leave as-is. 779 switch (AvailabilityState &State = It->second) { 780 case AvailabilityState::Unavailable: 781 case AvailabilityState::Available: 782 return; // Don't backpropagate further, continue processing worklist. 783 case AvailabilityState::SpeculativelyAvailable: // Fix it! 784 State = FixpointState; 785 #ifndef NDEBUG 786 assert(NewSpeculativelyAvailableBBs.erase(BB) && 787 "Found a speculatively available successor leftover?"); 788 #endif 789 // Queue successors for further processing. 790 Worklist.append(succ_begin(BB), succ_end(BB)); 791 return; 792 } 793 }; 794 795 if (UnavailableBB) { 796 // Okay, we have encountered an unavailable block. 797 // Mark speculatively available blocks reachable from UnavailableBB as 798 // unavailable as well. Paths are terminated when they reach blocks not in 799 // FullyAvailableBlocks or they are not marked as speculatively available. 800 Worklist.clear(); 801 Worklist.append(succ_begin(*UnavailableBB), succ_end(*UnavailableBB)); 802 while (!Worklist.empty()) 803 MarkAsFixpointAndEnqueueSuccessors(Worklist.pop_back_val(), 804 AvailabilityState::Unavailable); 805 } 806 807 #ifndef NDEBUG 808 Worklist.clear(); 809 for (BasicBlock *AvailableBB : AvailableBBs) 810 Worklist.append(succ_begin(AvailableBB), succ_end(AvailableBB)); 811 while (!Worklist.empty()) 812 MarkAsFixpointAndEnqueueSuccessors(Worklist.pop_back_val(), 813 AvailabilityState::Available); 814 815 assert(NewSpeculativelyAvailableBBs.empty() && 816 "Must have fixed all the new speculatively available blocks."); 817 #endif 818 819 return !UnavailableBB; 820 } 821 822 /// Given a set of loads specified by ValuesPerBlock, 823 /// construct SSA form, allowing us to eliminate LI. This returns the value 824 /// that should be used at LI's definition site. 825 static Value *ConstructSSAForLoadSet(LoadInst *LI, 826 SmallVectorImpl<AvailableValueInBlock> &ValuesPerBlock, 827 GVN &gvn) { 828 // Check for the fully redundant, dominating load case. In this case, we can 829 // just use the dominating value directly. 830 if (ValuesPerBlock.size() == 1 && 831 gvn.getDominatorTree().properlyDominates(ValuesPerBlock[0].BB, 832 LI->getParent())) { 833 assert(!ValuesPerBlock[0].AV.isUndefValue() && 834 "Dead BB dominate this block"); 835 return ValuesPerBlock[0].MaterializeAdjustedValue(LI, gvn); 836 } 837 838 // Otherwise, we have to construct SSA form. 839 SmallVector<PHINode*, 8> NewPHIs; 840 SSAUpdater SSAUpdate(&NewPHIs); 841 SSAUpdate.Initialize(LI->getType(), LI->getName()); 842 843 for (const AvailableValueInBlock &AV : ValuesPerBlock) { 844 BasicBlock *BB = AV.BB; 845 846 if (SSAUpdate.HasValueForBlock(BB)) 847 continue; 848 849 // If the value is the load that we will be eliminating, and the block it's 850 // available in is the block that the load is in, then don't add it as 851 // SSAUpdater will resolve the value to the relevant phi which may let it 852 // avoid phi construction entirely if there's actually only one value. 853 if (BB == LI->getParent() && 854 ((AV.AV.isSimpleValue() && AV.AV.getSimpleValue() == LI) || 855 (AV.AV.isCoercedLoadValue() && AV.AV.getCoercedLoadValue() == LI))) 856 continue; 857 858 SSAUpdate.AddAvailableValue(BB, AV.MaterializeAdjustedValue(LI, gvn)); 859 } 860 861 // Perform PHI construction. 862 return SSAUpdate.GetValueInMiddleOfBlock(LI->getParent()); 863 } 864 865 Value *AvailableValue::MaterializeAdjustedValue(LoadInst *LI, 866 Instruction *InsertPt, 867 GVN &gvn) const { 868 Value *Res; 869 Type *LoadTy = LI->getType(); 870 const DataLayout &DL = LI->getModule()->getDataLayout(); 871 if (isSimpleValue()) { 872 Res = getSimpleValue(); 873 if (Res->getType() != LoadTy) { 874 Res = getStoreValueForLoad(Res, Offset, LoadTy, InsertPt, DL); 875 876 LLVM_DEBUG(dbgs() << "GVN COERCED NONLOCAL VAL:\nOffset: " << Offset 877 << " " << *getSimpleValue() << '\n' 878 << *Res << '\n' 879 << "\n\n\n"); 880 } 881 } else if (isCoercedLoadValue()) { 882 LoadInst *Load = getCoercedLoadValue(); 883 if (Load->getType() == LoadTy && Offset == 0) { 884 Res = Load; 885 } else { 886 Res = getLoadValueForLoad(Load, Offset, LoadTy, InsertPt, DL); 887 // We would like to use gvn.markInstructionForDeletion here, but we can't 888 // because the load is already memoized into the leader map table that GVN 889 // tracks. It is potentially possible to remove the load from the table, 890 // but then there all of the operations based on it would need to be 891 // rehashed. Just leave the dead load around. 892 gvn.getMemDep().removeInstruction(Load); 893 LLVM_DEBUG(dbgs() << "GVN COERCED NONLOCAL LOAD:\nOffset: " << Offset 894 << " " << *getCoercedLoadValue() << '\n' 895 << *Res << '\n' 896 << "\n\n\n"); 897 } 898 } else if (isMemIntrinValue()) { 899 Res = getMemInstValueForLoad(getMemIntrinValue(), Offset, LoadTy, 900 InsertPt, DL); 901 LLVM_DEBUG(dbgs() << "GVN COERCED NONLOCAL MEM INTRIN:\nOffset: " << Offset 902 << " " << *getMemIntrinValue() << '\n' 903 << *Res << '\n' 904 << "\n\n\n"); 905 } else { 906 assert(isUndefValue() && "Should be UndefVal"); 907 LLVM_DEBUG(dbgs() << "GVN COERCED NONLOCAL Undef:\n";); 908 return UndefValue::get(LoadTy); 909 } 910 assert(Res && "failed to materialize?"); 911 return Res; 912 } 913 914 static bool isLifetimeStart(const Instruction *Inst) { 915 if (const IntrinsicInst* II = dyn_cast<IntrinsicInst>(Inst)) 916 return II->getIntrinsicID() == Intrinsic::lifetime_start; 917 return false; 918 } 919 920 /// Try to locate the three instruction involved in a missed 921 /// load-elimination case that is due to an intervening store. 922 static void reportMayClobberedLoad(LoadInst *LI, MemDepResult DepInfo, 923 DominatorTree *DT, 924 OptimizationRemarkEmitter *ORE) { 925 using namespace ore; 926 927 User *OtherAccess = nullptr; 928 929 OptimizationRemarkMissed R(DEBUG_TYPE, "LoadClobbered", LI); 930 R << "load of type " << NV("Type", LI->getType()) << " not eliminated" 931 << setExtraArgs(); 932 933 for (auto *U : LI->getPointerOperand()->users()) 934 if (U != LI && (isa<LoadInst>(U) || isa<StoreInst>(U)) && 935 DT->dominates(cast<Instruction>(U), LI)) { 936 // FIXME: for now give up if there are multiple memory accesses that 937 // dominate the load. We need further analysis to decide which one is 938 // that we're forwarding from. 939 if (OtherAccess) 940 OtherAccess = nullptr; 941 else 942 OtherAccess = U; 943 } 944 945 if (OtherAccess) 946 R << " in favor of " << NV("OtherAccess", OtherAccess); 947 948 R << " because it is clobbered by " << NV("ClobberedBy", DepInfo.getInst()); 949 950 ORE->emit(R); 951 } 952 953 bool GVN::AnalyzeLoadAvailability(LoadInst *LI, MemDepResult DepInfo, 954 Value *Address, AvailableValue &Res) { 955 assert((DepInfo.isDef() || DepInfo.isClobber()) && 956 "expected a local dependence"); 957 assert(LI->isUnordered() && "rules below are incorrect for ordered access"); 958 959 const DataLayout &DL = LI->getModule()->getDataLayout(); 960 961 Instruction *DepInst = DepInfo.getInst(); 962 if (DepInfo.isClobber()) { 963 // If the dependence is to a store that writes to a superset of the bits 964 // read by the load, we can extract the bits we need for the load from the 965 // stored value. 966 if (StoreInst *DepSI = dyn_cast<StoreInst>(DepInst)) { 967 // Can't forward from non-atomic to atomic without violating memory model. 968 if (Address && LI->isAtomic() <= DepSI->isAtomic()) { 969 int Offset = 970 analyzeLoadFromClobberingStore(LI->getType(), Address, DepSI, DL); 971 if (Offset != -1) { 972 Res = AvailableValue::get(DepSI->getValueOperand(), Offset); 973 return true; 974 } 975 } 976 } 977 978 // Check to see if we have something like this: 979 // load i32* P 980 // load i8* (P+1) 981 // if we have this, replace the later with an extraction from the former. 982 if (LoadInst *DepLI = dyn_cast<LoadInst>(DepInst)) { 983 // If this is a clobber and L is the first instruction in its block, then 984 // we have the first instruction in the entry block. 985 // Can't forward from non-atomic to atomic without violating memory model. 986 if (DepLI != LI && Address && LI->isAtomic() <= DepLI->isAtomic()) { 987 int Offset = 988 analyzeLoadFromClobberingLoad(LI->getType(), Address, DepLI, DL); 989 990 if (Offset != -1) { 991 Res = AvailableValue::getLoad(DepLI, Offset); 992 return true; 993 } 994 } 995 } 996 997 // If the clobbering value is a memset/memcpy/memmove, see if we can 998 // forward a value on from it. 999 if (MemIntrinsic *DepMI = dyn_cast<MemIntrinsic>(DepInst)) { 1000 if (Address && !LI->isAtomic()) { 1001 int Offset = analyzeLoadFromClobberingMemInst(LI->getType(), Address, 1002 DepMI, DL); 1003 if (Offset != -1) { 1004 Res = AvailableValue::getMI(DepMI, Offset); 1005 return true; 1006 } 1007 } 1008 } 1009 // Nothing known about this clobber, have to be conservative 1010 LLVM_DEBUG( 1011 // fast print dep, using operator<< on instruction is too slow. 1012 dbgs() << "GVN: load "; LI->printAsOperand(dbgs()); 1013 dbgs() << " is clobbered by " << *DepInst << '\n';); 1014 if (ORE->allowExtraAnalysis(DEBUG_TYPE)) 1015 reportMayClobberedLoad(LI, DepInfo, DT, ORE); 1016 1017 return false; 1018 } 1019 assert(DepInfo.isDef() && "follows from above"); 1020 1021 // Loading the allocation -> undef. 1022 if (isa<AllocaInst>(DepInst) || isMallocLikeFn(DepInst, TLI) || 1023 isAlignedAllocLikeFn(DepInst, TLI) || 1024 // Loading immediately after lifetime begin -> undef. 1025 isLifetimeStart(DepInst)) { 1026 Res = AvailableValue::get(UndefValue::get(LI->getType())); 1027 return true; 1028 } 1029 1030 // Loading from calloc (which zero initializes memory) -> zero 1031 if (isCallocLikeFn(DepInst, TLI)) { 1032 Res = AvailableValue::get(Constant::getNullValue(LI->getType())); 1033 return true; 1034 } 1035 1036 if (StoreInst *S = dyn_cast<StoreInst>(DepInst)) { 1037 // Reject loads and stores that are to the same address but are of 1038 // different types if we have to. If the stored value is larger or equal to 1039 // the loaded value, we can reuse it. 1040 if (!canCoerceMustAliasedValueToLoad(S->getValueOperand(), LI->getType(), 1041 DL)) 1042 return false; 1043 1044 // Can't forward from non-atomic to atomic without violating memory model. 1045 if (S->isAtomic() < LI->isAtomic()) 1046 return false; 1047 1048 Res = AvailableValue::get(S->getValueOperand()); 1049 return true; 1050 } 1051 1052 if (LoadInst *LD = dyn_cast<LoadInst>(DepInst)) { 1053 // If the types mismatch and we can't handle it, reject reuse of the load. 1054 // If the stored value is larger or equal to the loaded value, we can reuse 1055 // it. 1056 if (!canCoerceMustAliasedValueToLoad(LD, LI->getType(), DL)) 1057 return false; 1058 1059 // Can't forward from non-atomic to atomic without violating memory model. 1060 if (LD->isAtomic() < LI->isAtomic()) 1061 return false; 1062 1063 Res = AvailableValue::getLoad(LD); 1064 return true; 1065 } 1066 1067 // Unknown def - must be conservative 1068 LLVM_DEBUG( 1069 // fast print dep, using operator<< on instruction is too slow. 1070 dbgs() << "GVN: load "; LI->printAsOperand(dbgs()); 1071 dbgs() << " has unknown def " << *DepInst << '\n';); 1072 return false; 1073 } 1074 1075 void GVN::AnalyzeLoadAvailability(LoadInst *LI, LoadDepVect &Deps, 1076 AvailValInBlkVect &ValuesPerBlock, 1077 UnavailBlkVect &UnavailableBlocks) { 1078 // Filter out useless results (non-locals, etc). Keep track of the blocks 1079 // where we have a value available in repl, also keep track of whether we see 1080 // dependencies that produce an unknown value for the load (such as a call 1081 // that could potentially clobber the load). 1082 unsigned NumDeps = Deps.size(); 1083 for (unsigned i = 0, e = NumDeps; i != e; ++i) { 1084 BasicBlock *DepBB = Deps[i].getBB(); 1085 MemDepResult DepInfo = Deps[i].getResult(); 1086 1087 if (DeadBlocks.count(DepBB)) { 1088 // Dead dependent mem-op disguise as a load evaluating the same value 1089 // as the load in question. 1090 ValuesPerBlock.push_back(AvailableValueInBlock::getUndef(DepBB)); 1091 continue; 1092 } 1093 1094 if (!DepInfo.isDef() && !DepInfo.isClobber()) { 1095 UnavailableBlocks.push_back(DepBB); 1096 continue; 1097 } 1098 1099 // The address being loaded in this non-local block may not be the same as 1100 // the pointer operand of the load if PHI translation occurs. Make sure 1101 // to consider the right address. 1102 Value *Address = Deps[i].getAddress(); 1103 1104 AvailableValue AV; 1105 if (AnalyzeLoadAvailability(LI, DepInfo, Address, AV)) { 1106 // subtlety: because we know this was a non-local dependency, we know 1107 // it's safe to materialize anywhere between the instruction within 1108 // DepInfo and the end of it's block. 1109 ValuesPerBlock.push_back(AvailableValueInBlock::get(DepBB, 1110 std::move(AV))); 1111 } else { 1112 UnavailableBlocks.push_back(DepBB); 1113 } 1114 } 1115 1116 assert(NumDeps == ValuesPerBlock.size() + UnavailableBlocks.size() && 1117 "post condition violation"); 1118 } 1119 1120 bool GVN::PerformLoadPRE(LoadInst *LI, AvailValInBlkVect &ValuesPerBlock, 1121 UnavailBlkVect &UnavailableBlocks) { 1122 // Okay, we have *some* definitions of the value. This means that the value 1123 // is available in some of our (transitive) predecessors. Lets think about 1124 // doing PRE of this load. This will involve inserting a new load into the 1125 // predecessor when it's not available. We could do this in general, but 1126 // prefer to not increase code size. As such, we only do this when we know 1127 // that we only have to insert *one* load (which means we're basically moving 1128 // the load, not inserting a new one). 1129 1130 SmallPtrSet<BasicBlock *, 4> Blockers(UnavailableBlocks.begin(), 1131 UnavailableBlocks.end()); 1132 1133 // Let's find the first basic block with more than one predecessor. Walk 1134 // backwards through predecessors if needed. 1135 BasicBlock *LoadBB = LI->getParent(); 1136 BasicBlock *TmpBB = LoadBB; 1137 bool IsSafeToSpeculativelyExecute = isSafeToSpeculativelyExecute(LI); 1138 1139 // Check that there is no implicit control flow instructions above our load in 1140 // its block. If there is an instruction that doesn't always pass the 1141 // execution to the following instruction, then moving through it may become 1142 // invalid. For example: 1143 // 1144 // int arr[LEN]; 1145 // int index = ???; 1146 // ... 1147 // guard(0 <= index && index < LEN); 1148 // use(arr[index]); 1149 // 1150 // It is illegal to move the array access to any point above the guard, 1151 // because if the index is out of bounds we should deoptimize rather than 1152 // access the array. 1153 // Check that there is no guard in this block above our instruction. 1154 if (!IsSafeToSpeculativelyExecute && ICF->isDominatedByICFIFromSameBlock(LI)) 1155 return false; 1156 while (TmpBB->getSinglePredecessor()) { 1157 TmpBB = TmpBB->getSinglePredecessor(); 1158 if (TmpBB == LoadBB) // Infinite (unreachable) loop. 1159 return false; 1160 if (Blockers.count(TmpBB)) 1161 return false; 1162 1163 // If any of these blocks has more than one successor (i.e. if the edge we 1164 // just traversed was critical), then there are other paths through this 1165 // block along which the load may not be anticipated. Hoisting the load 1166 // above this block would be adding the load to execution paths along 1167 // which it was not previously executed. 1168 if (TmpBB->getTerminator()->getNumSuccessors() != 1) 1169 return false; 1170 1171 // Check that there is no implicit control flow in a block above. 1172 if (!IsSafeToSpeculativelyExecute && ICF->hasICF(TmpBB)) 1173 return false; 1174 } 1175 1176 assert(TmpBB); 1177 LoadBB = TmpBB; 1178 1179 // Check to see how many predecessors have the loaded value fully 1180 // available. 1181 MapVector<BasicBlock *, Value *> PredLoads; 1182 DenseMap<BasicBlock *, AvailabilityState> FullyAvailableBlocks; 1183 for (const AvailableValueInBlock &AV : ValuesPerBlock) 1184 FullyAvailableBlocks[AV.BB] = AvailabilityState::Available; 1185 for (BasicBlock *UnavailableBB : UnavailableBlocks) 1186 FullyAvailableBlocks[UnavailableBB] = AvailabilityState::Unavailable; 1187 1188 SmallVector<BasicBlock *, 4> CriticalEdgePred; 1189 for (BasicBlock *Pred : predecessors(LoadBB)) { 1190 // If any predecessor block is an EH pad that does not allow non-PHI 1191 // instructions before the terminator, we can't PRE the load. 1192 if (Pred->getTerminator()->isEHPad()) { 1193 LLVM_DEBUG( 1194 dbgs() << "COULD NOT PRE LOAD BECAUSE OF AN EH PAD PREDECESSOR '" 1195 << Pred->getName() << "': " << *LI << '\n'); 1196 return false; 1197 } 1198 1199 if (IsValueFullyAvailableInBlock(Pred, FullyAvailableBlocks)) { 1200 continue; 1201 } 1202 1203 if (Pred->getTerminator()->getNumSuccessors() != 1) { 1204 if (isa<IndirectBrInst>(Pred->getTerminator())) { 1205 LLVM_DEBUG( 1206 dbgs() << "COULD NOT PRE LOAD BECAUSE OF INDBR CRITICAL EDGE '" 1207 << Pred->getName() << "': " << *LI << '\n'); 1208 return false; 1209 } 1210 1211 // FIXME: Can we support the fallthrough edge? 1212 if (isa<CallBrInst>(Pred->getTerminator())) { 1213 LLVM_DEBUG( 1214 dbgs() << "COULD NOT PRE LOAD BECAUSE OF CALLBR CRITICAL EDGE '" 1215 << Pred->getName() << "': " << *LI << '\n'); 1216 return false; 1217 } 1218 1219 if (LoadBB->isEHPad()) { 1220 LLVM_DEBUG( 1221 dbgs() << "COULD NOT PRE LOAD BECAUSE OF AN EH PAD CRITICAL EDGE '" 1222 << Pred->getName() << "': " << *LI << '\n'); 1223 return false; 1224 } 1225 1226 CriticalEdgePred.push_back(Pred); 1227 } else { 1228 // Only add the predecessors that will not be split for now. 1229 PredLoads[Pred] = nullptr; 1230 } 1231 } 1232 1233 // Decide whether PRE is profitable for this load. 1234 unsigned NumUnavailablePreds = PredLoads.size() + CriticalEdgePred.size(); 1235 assert(NumUnavailablePreds != 0 && 1236 "Fully available value should already be eliminated!"); 1237 1238 // If this load is unavailable in multiple predecessors, reject it. 1239 // FIXME: If we could restructure the CFG, we could make a common pred with 1240 // all the preds that don't have an available LI and insert a new load into 1241 // that one block. 1242 if (NumUnavailablePreds != 1) 1243 return false; 1244 1245 // Split critical edges, and update the unavailable predecessors accordingly. 1246 for (BasicBlock *OrigPred : CriticalEdgePred) { 1247 BasicBlock *NewPred = splitCriticalEdges(OrigPred, LoadBB); 1248 assert(!PredLoads.count(OrigPred) && "Split edges shouldn't be in map!"); 1249 PredLoads[NewPred] = nullptr; 1250 LLVM_DEBUG(dbgs() << "Split critical edge " << OrigPred->getName() << "->" 1251 << LoadBB->getName() << '\n'); 1252 } 1253 1254 // Check if the load can safely be moved to all the unavailable predecessors. 1255 bool CanDoPRE = true; 1256 const DataLayout &DL = LI->getModule()->getDataLayout(); 1257 SmallVector<Instruction*, 8> NewInsts; 1258 for (auto &PredLoad : PredLoads) { 1259 BasicBlock *UnavailablePred = PredLoad.first; 1260 1261 // Do PHI translation to get its value in the predecessor if necessary. The 1262 // returned pointer (if non-null) is guaranteed to dominate UnavailablePred. 1263 // We do the translation for each edge we skipped by going from LI's block 1264 // to LoadBB, otherwise we might miss pieces needing translation. 1265 1266 // If all preds have a single successor, then we know it is safe to insert 1267 // the load on the pred (?!?), so we can insert code to materialize the 1268 // pointer if it is not available. 1269 Value *LoadPtr = LI->getPointerOperand(); 1270 BasicBlock *Cur = LI->getParent(); 1271 while (Cur != LoadBB) { 1272 PHITransAddr Address(LoadPtr, DL, AC); 1273 LoadPtr = Address.PHITranslateWithInsertion( 1274 Cur, Cur->getSinglePredecessor(), *DT, NewInsts); 1275 if (!LoadPtr) { 1276 CanDoPRE = false; 1277 break; 1278 } 1279 Cur = Cur->getSinglePredecessor(); 1280 } 1281 1282 if (LoadPtr) { 1283 PHITransAddr Address(LoadPtr, DL, AC); 1284 LoadPtr = Address.PHITranslateWithInsertion(LoadBB, UnavailablePred, *DT, 1285 NewInsts); 1286 } 1287 // If we couldn't find or insert a computation of this phi translated value, 1288 // we fail PRE. 1289 if (!LoadPtr) { 1290 LLVM_DEBUG(dbgs() << "COULDN'T INSERT PHI TRANSLATED VALUE OF: " 1291 << *LI->getPointerOperand() << "\n"); 1292 CanDoPRE = false; 1293 break; 1294 } 1295 1296 PredLoad.second = LoadPtr; 1297 } 1298 1299 if (!CanDoPRE) { 1300 while (!NewInsts.empty()) { 1301 // Erase instructions generated by the failed PHI translation before 1302 // trying to number them. PHI translation might insert instructions 1303 // in basic blocks other than the current one, and we delete them 1304 // directly, as markInstructionForDeletion only allows removing from the 1305 // current basic block. 1306 NewInsts.pop_back_val()->eraseFromParent(); 1307 } 1308 // HINT: Don't revert the edge-splitting as following transformation may 1309 // also need to split these critical edges. 1310 return !CriticalEdgePred.empty(); 1311 } 1312 1313 // Okay, we can eliminate this load by inserting a reload in the predecessor 1314 // and using PHI construction to get the value in the other predecessors, do 1315 // it. 1316 LLVM_DEBUG(dbgs() << "GVN REMOVING PRE LOAD: " << *LI << '\n'); 1317 LLVM_DEBUG(if (!NewInsts.empty()) dbgs() 1318 << "INSERTED " << NewInsts.size() << " INSTS: " << *NewInsts.back() 1319 << '\n'); 1320 1321 // Assign value numbers to the new instructions. 1322 for (Instruction *I : NewInsts) { 1323 // Instructions that have been inserted in predecessor(s) to materialize 1324 // the load address do not retain their original debug locations. Doing 1325 // so could lead to confusing (but correct) source attributions. 1326 if (const DebugLoc &DL = I->getDebugLoc()) 1327 I->setDebugLoc(DebugLoc::get(0, 0, DL.getScope(), DL.getInlinedAt())); 1328 1329 // FIXME: We really _ought_ to insert these value numbers into their 1330 // parent's availability map. However, in doing so, we risk getting into 1331 // ordering issues. If a block hasn't been processed yet, we would be 1332 // marking a value as AVAIL-IN, which isn't what we intend. 1333 VN.lookupOrAdd(I); 1334 } 1335 1336 for (const auto &PredLoad : PredLoads) { 1337 BasicBlock *UnavailablePred = PredLoad.first; 1338 Value *LoadPtr = PredLoad.second; 1339 1340 auto *NewLoad = new LoadInst( 1341 LI->getType(), LoadPtr, LI->getName() + ".pre", LI->isVolatile(), 1342 LI->getAlign(), LI->getOrdering(), LI->getSyncScopeID(), 1343 UnavailablePred->getTerminator()); 1344 NewLoad->setDebugLoc(LI->getDebugLoc()); 1345 if (MSSAU) { 1346 auto *MSSA = MSSAU->getMemorySSA(); 1347 // Get the defining access of the original load or use the load if it is a 1348 // MemoryDef (e.g. because it is volatile). The inserted loads are 1349 // guaranteed to load from the same definition. 1350 auto *LIAcc = MSSA->getMemoryAccess(LI); 1351 auto *DefiningAcc = 1352 isa<MemoryDef>(LIAcc) ? LIAcc : LIAcc->getDefiningAccess(); 1353 auto *NewAccess = MSSAU->createMemoryAccessInBB( 1354 NewLoad, DefiningAcc, NewLoad->getParent(), 1355 MemorySSA::BeforeTerminator); 1356 if (auto *NewDef = dyn_cast<MemoryDef>(NewAccess)) 1357 MSSAU->insertDef(NewDef, /*RenameUses=*/true); 1358 else 1359 MSSAU->insertUse(cast<MemoryUse>(NewAccess), /*RenameUses=*/true); 1360 } 1361 1362 // Transfer the old load's AA tags to the new load. 1363 AAMDNodes Tags; 1364 LI->getAAMetadata(Tags); 1365 if (Tags) 1366 NewLoad->setAAMetadata(Tags); 1367 1368 if (auto *MD = LI->getMetadata(LLVMContext::MD_invariant_load)) 1369 NewLoad->setMetadata(LLVMContext::MD_invariant_load, MD); 1370 if (auto *InvGroupMD = LI->getMetadata(LLVMContext::MD_invariant_group)) 1371 NewLoad->setMetadata(LLVMContext::MD_invariant_group, InvGroupMD); 1372 if (auto *RangeMD = LI->getMetadata(LLVMContext::MD_range)) 1373 NewLoad->setMetadata(LLVMContext::MD_range, RangeMD); 1374 1375 // We do not propagate the old load's debug location, because the new 1376 // load now lives in a different BB, and we want to avoid a jumpy line 1377 // table. 1378 // FIXME: How do we retain source locations without causing poor debugging 1379 // behavior? 1380 1381 // Add the newly created load. 1382 ValuesPerBlock.push_back(AvailableValueInBlock::get(UnavailablePred, 1383 NewLoad)); 1384 MD->invalidateCachedPointerInfo(LoadPtr); 1385 LLVM_DEBUG(dbgs() << "GVN INSERTED " << *NewLoad << '\n'); 1386 } 1387 1388 // Perform PHI construction. 1389 Value *V = ConstructSSAForLoadSet(LI, ValuesPerBlock, *this); 1390 LI->replaceAllUsesWith(V); 1391 if (isa<PHINode>(V)) 1392 V->takeName(LI); 1393 if (Instruction *I = dyn_cast<Instruction>(V)) 1394 I->setDebugLoc(LI->getDebugLoc()); 1395 if (V->getType()->isPtrOrPtrVectorTy()) 1396 MD->invalidateCachedPointerInfo(V); 1397 markInstructionForDeletion(LI); 1398 ORE->emit([&]() { 1399 return OptimizationRemark(DEBUG_TYPE, "LoadPRE", LI) 1400 << "load eliminated by PRE"; 1401 }); 1402 ++NumPRELoad; 1403 return true; 1404 } 1405 1406 static void reportLoadElim(LoadInst *LI, Value *AvailableValue, 1407 OptimizationRemarkEmitter *ORE) { 1408 using namespace ore; 1409 1410 ORE->emit([&]() { 1411 return OptimizationRemark(DEBUG_TYPE, "LoadElim", LI) 1412 << "load of type " << NV("Type", LI->getType()) << " eliminated" 1413 << setExtraArgs() << " in favor of " 1414 << NV("InfavorOfValue", AvailableValue); 1415 }); 1416 } 1417 1418 /// Attempt to eliminate a load whose dependencies are 1419 /// non-local by performing PHI construction. 1420 bool GVN::processNonLocalLoad(LoadInst *LI) { 1421 // non-local speculations are not allowed under asan. 1422 if (LI->getParent()->getParent()->hasFnAttribute( 1423 Attribute::SanitizeAddress) || 1424 LI->getParent()->getParent()->hasFnAttribute( 1425 Attribute::SanitizeHWAddress)) 1426 return false; 1427 1428 // Step 1: Find the non-local dependencies of the load. 1429 LoadDepVect Deps; 1430 MD->getNonLocalPointerDependency(LI, Deps); 1431 1432 // If we had to process more than one hundred blocks to find the 1433 // dependencies, this load isn't worth worrying about. Optimizing 1434 // it will be too expensive. 1435 unsigned NumDeps = Deps.size(); 1436 if (NumDeps > MaxNumDeps) 1437 return false; 1438 1439 // If we had a phi translation failure, we'll have a single entry which is a 1440 // clobber in the current block. Reject this early. 1441 if (NumDeps == 1 && 1442 !Deps[0].getResult().isDef() && !Deps[0].getResult().isClobber()) { 1443 LLVM_DEBUG(dbgs() << "GVN: non-local load "; LI->printAsOperand(dbgs()); 1444 dbgs() << " has unknown dependencies\n";); 1445 return false; 1446 } 1447 1448 // If this load follows a GEP, see if we can PRE the indices before analyzing. 1449 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0))) { 1450 for (GetElementPtrInst::op_iterator OI = GEP->idx_begin(), 1451 OE = GEP->idx_end(); 1452 OI != OE; ++OI) 1453 if (Instruction *I = dyn_cast<Instruction>(OI->get())) 1454 performScalarPRE(I); 1455 } 1456 1457 // Step 2: Analyze the availability of the load 1458 AvailValInBlkVect ValuesPerBlock; 1459 UnavailBlkVect UnavailableBlocks; 1460 AnalyzeLoadAvailability(LI, Deps, ValuesPerBlock, UnavailableBlocks); 1461 1462 // If we have no predecessors that produce a known value for this load, exit 1463 // early. 1464 if (ValuesPerBlock.empty()) 1465 return false; 1466 1467 // Step 3: Eliminate fully redundancy. 1468 // 1469 // If all of the instructions we depend on produce a known value for this 1470 // load, then it is fully redundant and we can use PHI insertion to compute 1471 // its value. Insert PHIs and remove the fully redundant value now. 1472 if (UnavailableBlocks.empty()) { 1473 LLVM_DEBUG(dbgs() << "GVN REMOVING NONLOCAL LOAD: " << *LI << '\n'); 1474 1475 // Perform PHI construction. 1476 Value *V = ConstructSSAForLoadSet(LI, ValuesPerBlock, *this); 1477 LI->replaceAllUsesWith(V); 1478 1479 if (isa<PHINode>(V)) 1480 V->takeName(LI); 1481 if (Instruction *I = dyn_cast<Instruction>(V)) 1482 // If instruction I has debug info, then we should not update it. 1483 // Also, if I has a null DebugLoc, then it is still potentially incorrect 1484 // to propagate LI's DebugLoc because LI may not post-dominate I. 1485 if (LI->getDebugLoc() && LI->getParent() == I->getParent()) 1486 I->setDebugLoc(LI->getDebugLoc()); 1487 if (V->getType()->isPtrOrPtrVectorTy()) 1488 MD->invalidateCachedPointerInfo(V); 1489 markInstructionForDeletion(LI); 1490 ++NumGVNLoad; 1491 reportLoadElim(LI, V, ORE); 1492 return true; 1493 } 1494 1495 // Step 4: Eliminate partial redundancy. 1496 if (!isPREEnabled() || !isLoadPREEnabled()) 1497 return false; 1498 if (!isLoadInLoopPREEnabled() && this->LI && 1499 this->LI->getLoopFor(LI->getParent())) 1500 return false; 1501 1502 return PerformLoadPRE(LI, ValuesPerBlock, UnavailableBlocks); 1503 } 1504 1505 static bool impliesEquivalanceIfTrue(CmpInst* Cmp) { 1506 if (Cmp->getPredicate() == CmpInst::Predicate::ICMP_EQ) 1507 return true; 1508 1509 // Floating point comparisons can be equal, but not equivalent. Cases: 1510 // NaNs for unordered operators 1511 // +0.0 vs 0.0 for all operators 1512 if (Cmp->getPredicate() == CmpInst::Predicate::FCMP_OEQ || 1513 (Cmp->getPredicate() == CmpInst::Predicate::FCMP_UEQ && 1514 Cmp->getFastMathFlags().noNaNs())) { 1515 Value *LHS = Cmp->getOperand(0); 1516 Value *RHS = Cmp->getOperand(1); 1517 // If we can prove either side non-zero, then equality must imply 1518 // equivalence. 1519 // FIXME: We should do this optimization if 'no signed zeros' is 1520 // applicable via an instruction-level fast-math-flag or some other 1521 // indicator that relaxed FP semantics are being used. 1522 if (isa<ConstantFP>(LHS) && !cast<ConstantFP>(LHS)->isZero()) 1523 return true; 1524 if (isa<ConstantFP>(RHS) && !cast<ConstantFP>(RHS)->isZero()) 1525 return true;; 1526 // TODO: Handle vector floating point constants 1527 } 1528 return false; 1529 } 1530 1531 static bool impliesEquivalanceIfFalse(CmpInst* Cmp) { 1532 if (Cmp->getPredicate() == CmpInst::Predicate::ICMP_NE) 1533 return true; 1534 1535 // Floating point comparisons can be equal, but not equivelent. Cases: 1536 // NaNs for unordered operators 1537 // +0.0 vs 0.0 for all operators 1538 if ((Cmp->getPredicate() == CmpInst::Predicate::FCMP_ONE && 1539 Cmp->getFastMathFlags().noNaNs()) || 1540 Cmp->getPredicate() == CmpInst::Predicate::FCMP_UNE) { 1541 Value *LHS = Cmp->getOperand(0); 1542 Value *RHS = Cmp->getOperand(1); 1543 // If we can prove either side non-zero, then equality must imply 1544 // equivalence. 1545 // FIXME: We should do this optimization if 'no signed zeros' is 1546 // applicable via an instruction-level fast-math-flag or some other 1547 // indicator that relaxed FP semantics are being used. 1548 if (isa<ConstantFP>(LHS) && !cast<ConstantFP>(LHS)->isZero()) 1549 return true; 1550 if (isa<ConstantFP>(RHS) && !cast<ConstantFP>(RHS)->isZero()) 1551 return true;; 1552 // TODO: Handle vector floating point constants 1553 } 1554 return false; 1555 } 1556 1557 1558 static bool hasUsersIn(Value *V, BasicBlock *BB) { 1559 for (User *U : V->users()) 1560 if (isa<Instruction>(U) && 1561 cast<Instruction>(U)->getParent() == BB) 1562 return true; 1563 return false; 1564 } 1565 1566 bool GVN::processAssumeIntrinsic(IntrinsicInst *IntrinsicI) { 1567 assert(IntrinsicI->getIntrinsicID() == Intrinsic::assume && 1568 "This function can only be called with llvm.assume intrinsic"); 1569 Value *V = IntrinsicI->getArgOperand(0); 1570 1571 if (ConstantInt *Cond = dyn_cast<ConstantInt>(V)) { 1572 if (Cond->isZero()) { 1573 Type *Int8Ty = Type::getInt8Ty(V->getContext()); 1574 // Insert a new store to null instruction before the load to indicate that 1575 // this code is not reachable. FIXME: We could insert unreachable 1576 // instruction directly because we can modify the CFG. 1577 auto *NewS = new StoreInst(UndefValue::get(Int8Ty), 1578 Constant::getNullValue(Int8Ty->getPointerTo()), 1579 IntrinsicI); 1580 if (MSSAU) { 1581 // This added store is to null, so it will never executed and we can 1582 // just use the LiveOnEntry def as defining access. 1583 auto *NewDef = MSSAU->createMemoryAccessInBB( 1584 NewS, MSSAU->getMemorySSA()->getLiveOnEntryDef(), NewS->getParent(), 1585 MemorySSA::BeforeTerminator); 1586 MSSAU->insertDef(cast<MemoryDef>(NewDef), /*RenameUses=*/true); 1587 } 1588 } 1589 if (isAssumeWithEmptyBundle(*IntrinsicI)) 1590 markInstructionForDeletion(IntrinsicI); 1591 return false; 1592 } else if (isa<Constant>(V)) { 1593 // If it's not false, and constant, it must evaluate to true. This means our 1594 // assume is assume(true), and thus, pointless, and we don't want to do 1595 // anything more here. 1596 return false; 1597 } 1598 1599 Constant *True = ConstantInt::getTrue(V->getContext()); 1600 bool Changed = false; 1601 1602 for (BasicBlock *Successor : successors(IntrinsicI->getParent())) { 1603 BasicBlockEdge Edge(IntrinsicI->getParent(), Successor); 1604 1605 // This property is only true in dominated successors, propagateEquality 1606 // will check dominance for us. 1607 Changed |= propagateEquality(V, True, Edge, false); 1608 } 1609 1610 // We can replace assume value with true, which covers cases like this: 1611 // call void @llvm.assume(i1 %cmp) 1612 // br i1 %cmp, label %bb1, label %bb2 ; will change %cmp to true 1613 ReplaceOperandsWithMap[V] = True; 1614 1615 // If we find an equality fact, canonicalize all dominated uses in this block 1616 // to one of the two values. We heuristically choice the "oldest" of the 1617 // two where age is determined by value number. (Note that propagateEquality 1618 // above handles the cross block case.) 1619 // 1620 // Key case to cover are: 1621 // 1) 1622 // %cmp = fcmp oeq float 3.000000e+00, %0 ; const on lhs could happen 1623 // call void @llvm.assume(i1 %cmp) 1624 // ret float %0 ; will change it to ret float 3.000000e+00 1625 // 2) 1626 // %load = load float, float* %addr 1627 // %cmp = fcmp oeq float %load, %0 1628 // call void @llvm.assume(i1 %cmp) 1629 // ret float %load ; will change it to ret float %0 1630 if (auto *CmpI = dyn_cast<CmpInst>(V)) { 1631 if (impliesEquivalanceIfTrue(CmpI)) { 1632 Value *CmpLHS = CmpI->getOperand(0); 1633 Value *CmpRHS = CmpI->getOperand(1); 1634 // Heuristically pick the better replacement -- the choice of heuristic 1635 // isn't terribly important here, but the fact we canonicalize on some 1636 // replacement is for exposing other simplifications. 1637 // TODO: pull this out as a helper function and reuse w/existing 1638 // (slightly different) logic. 1639 if (isa<Constant>(CmpLHS) && !isa<Constant>(CmpRHS)) 1640 std::swap(CmpLHS, CmpRHS); 1641 if (!isa<Instruction>(CmpLHS) && isa<Instruction>(CmpRHS)) 1642 std::swap(CmpLHS, CmpRHS); 1643 if ((isa<Argument>(CmpLHS) && isa<Argument>(CmpRHS)) || 1644 (isa<Instruction>(CmpLHS) && isa<Instruction>(CmpRHS))) { 1645 // Move the 'oldest' value to the right-hand side, using the value 1646 // number as a proxy for age. 1647 uint32_t LVN = VN.lookupOrAdd(CmpLHS); 1648 uint32_t RVN = VN.lookupOrAdd(CmpRHS); 1649 if (LVN < RVN) 1650 std::swap(CmpLHS, CmpRHS); 1651 } 1652 1653 // Handle degenerate case where we either haven't pruned a dead path or a 1654 // removed a trivial assume yet. 1655 if (isa<Constant>(CmpLHS) && isa<Constant>(CmpRHS)) 1656 return Changed; 1657 1658 LLVM_DEBUG(dbgs() << "Replacing dominated uses of " 1659 << *CmpLHS << " with " 1660 << *CmpRHS << " in block " 1661 << IntrinsicI->getParent()->getName() << "\n"); 1662 1663 1664 // Setup the replacement map - this handles uses within the same block 1665 if (hasUsersIn(CmpLHS, IntrinsicI->getParent())) 1666 ReplaceOperandsWithMap[CmpLHS] = CmpRHS; 1667 1668 // NOTE: The non-block local cases are handled by the call to 1669 // propagateEquality above; this block is just about handling the block 1670 // local cases. TODO: There's a bunch of logic in propagateEqualiy which 1671 // isn't duplicated for the block local case, can we share it somehow? 1672 } 1673 } 1674 return Changed; 1675 } 1676 1677 static void patchAndReplaceAllUsesWith(Instruction *I, Value *Repl) { 1678 patchReplacementInstruction(I, Repl); 1679 I->replaceAllUsesWith(Repl); 1680 } 1681 1682 /// Attempt to eliminate a load, first by eliminating it 1683 /// locally, and then attempting non-local elimination if that fails. 1684 bool GVN::processLoad(LoadInst *L) { 1685 if (!MD) 1686 return false; 1687 1688 // This code hasn't been audited for ordered or volatile memory access 1689 if (!L->isUnordered()) 1690 return false; 1691 1692 if (L->use_empty()) { 1693 markInstructionForDeletion(L); 1694 return true; 1695 } 1696 1697 // ... to a pointer that has been loaded from before... 1698 MemDepResult Dep = MD->getDependency(L); 1699 1700 // If it is defined in another block, try harder. 1701 if (Dep.isNonLocal()) 1702 return processNonLocalLoad(L); 1703 1704 // Only handle the local case below 1705 if (!Dep.isDef() && !Dep.isClobber()) { 1706 // This might be a NonFuncLocal or an Unknown 1707 LLVM_DEBUG( 1708 // fast print dep, using operator<< on instruction is too slow. 1709 dbgs() << "GVN: load "; L->printAsOperand(dbgs()); 1710 dbgs() << " has unknown dependence\n";); 1711 return false; 1712 } 1713 1714 AvailableValue AV; 1715 if (AnalyzeLoadAvailability(L, Dep, L->getPointerOperand(), AV)) { 1716 Value *AvailableValue = AV.MaterializeAdjustedValue(L, L, *this); 1717 1718 // Replace the load! 1719 patchAndReplaceAllUsesWith(L, AvailableValue); 1720 markInstructionForDeletion(L); 1721 if (MSSAU) 1722 MSSAU->removeMemoryAccess(L); 1723 ++NumGVNLoad; 1724 reportLoadElim(L, AvailableValue, ORE); 1725 // Tell MDA to rexamine the reused pointer since we might have more 1726 // information after forwarding it. 1727 if (MD && AvailableValue->getType()->isPtrOrPtrVectorTy()) 1728 MD->invalidateCachedPointerInfo(AvailableValue); 1729 return true; 1730 } 1731 1732 return false; 1733 } 1734 1735 /// Return a pair the first field showing the value number of \p Exp and the 1736 /// second field showing whether it is a value number newly created. 1737 std::pair<uint32_t, bool> 1738 GVN::ValueTable::assignExpNewValueNum(Expression &Exp) { 1739 uint32_t &e = expressionNumbering[Exp]; 1740 bool CreateNewValNum = !e; 1741 if (CreateNewValNum) { 1742 Expressions.push_back(Exp); 1743 if (ExprIdx.size() < nextValueNumber + 1) 1744 ExprIdx.resize(nextValueNumber * 2); 1745 e = nextValueNumber; 1746 ExprIdx[nextValueNumber++] = nextExprNumber++; 1747 } 1748 return {e, CreateNewValNum}; 1749 } 1750 1751 /// Return whether all the values related with the same \p num are 1752 /// defined in \p BB. 1753 bool GVN::ValueTable::areAllValsInBB(uint32_t Num, const BasicBlock *BB, 1754 GVN &Gvn) { 1755 LeaderTableEntry *Vals = &Gvn.LeaderTable[Num]; 1756 while (Vals && Vals->BB == BB) 1757 Vals = Vals->Next; 1758 return !Vals; 1759 } 1760 1761 /// Wrap phiTranslateImpl to provide caching functionality. 1762 uint32_t GVN::ValueTable::phiTranslate(const BasicBlock *Pred, 1763 const BasicBlock *PhiBlock, uint32_t Num, 1764 GVN &Gvn) { 1765 auto FindRes = PhiTranslateTable.find({Num, Pred}); 1766 if (FindRes != PhiTranslateTable.end()) 1767 return FindRes->second; 1768 uint32_t NewNum = phiTranslateImpl(Pred, PhiBlock, Num, Gvn); 1769 PhiTranslateTable.insert({{Num, Pred}, NewNum}); 1770 return NewNum; 1771 } 1772 1773 // Return true if the value number \p Num and NewNum have equal value. 1774 // Return false if the result is unknown. 1775 bool GVN::ValueTable::areCallValsEqual(uint32_t Num, uint32_t NewNum, 1776 const BasicBlock *Pred, 1777 const BasicBlock *PhiBlock, GVN &Gvn) { 1778 CallInst *Call = nullptr; 1779 LeaderTableEntry *Vals = &Gvn.LeaderTable[Num]; 1780 while (Vals) { 1781 Call = dyn_cast<CallInst>(Vals->Val); 1782 if (Call && Call->getParent() == PhiBlock) 1783 break; 1784 Vals = Vals->Next; 1785 } 1786 1787 if (AA->doesNotAccessMemory(Call)) 1788 return true; 1789 1790 if (!MD || !AA->onlyReadsMemory(Call)) 1791 return false; 1792 1793 MemDepResult local_dep = MD->getDependency(Call); 1794 if (!local_dep.isNonLocal()) 1795 return false; 1796 1797 const MemoryDependenceResults::NonLocalDepInfo &deps = 1798 MD->getNonLocalCallDependency(Call); 1799 1800 // Check to see if the Call has no function local clobber. 1801 for (unsigned i = 0; i < deps.size(); i++) { 1802 if (deps[i].getResult().isNonFuncLocal()) 1803 return true; 1804 } 1805 return false; 1806 } 1807 1808 /// Translate value number \p Num using phis, so that it has the values of 1809 /// the phis in BB. 1810 uint32_t GVN::ValueTable::phiTranslateImpl(const BasicBlock *Pred, 1811 const BasicBlock *PhiBlock, 1812 uint32_t Num, GVN &Gvn) { 1813 if (PHINode *PN = NumberingPhi[Num]) { 1814 for (unsigned i = 0; i != PN->getNumIncomingValues(); ++i) { 1815 if (PN->getParent() == PhiBlock && PN->getIncomingBlock(i) == Pred) 1816 if (uint32_t TransVal = lookup(PN->getIncomingValue(i), false)) 1817 return TransVal; 1818 } 1819 return Num; 1820 } 1821 1822 // If there is any value related with Num is defined in a BB other than 1823 // PhiBlock, it cannot depend on a phi in PhiBlock without going through 1824 // a backedge. We can do an early exit in that case to save compile time. 1825 if (!areAllValsInBB(Num, PhiBlock, Gvn)) 1826 return Num; 1827 1828 if (Num >= ExprIdx.size() || ExprIdx[Num] == 0) 1829 return Num; 1830 Expression Exp = Expressions[ExprIdx[Num]]; 1831 1832 for (unsigned i = 0; i < Exp.varargs.size(); i++) { 1833 // For InsertValue and ExtractValue, some varargs are index numbers 1834 // instead of value numbers. Those index numbers should not be 1835 // translated. 1836 if ((i > 1 && Exp.opcode == Instruction::InsertValue) || 1837 (i > 0 && Exp.opcode == Instruction::ExtractValue) || 1838 (i > 1 && Exp.opcode == Instruction::ShuffleVector)) 1839 continue; 1840 Exp.varargs[i] = phiTranslate(Pred, PhiBlock, Exp.varargs[i], Gvn); 1841 } 1842 1843 if (Exp.commutative) { 1844 assert(Exp.varargs.size() >= 2 && "Unsupported commutative instruction!"); 1845 if (Exp.varargs[0] > Exp.varargs[1]) { 1846 std::swap(Exp.varargs[0], Exp.varargs[1]); 1847 uint32_t Opcode = Exp.opcode >> 8; 1848 if (Opcode == Instruction::ICmp || Opcode == Instruction::FCmp) 1849 Exp.opcode = (Opcode << 8) | 1850 CmpInst::getSwappedPredicate( 1851 static_cast<CmpInst::Predicate>(Exp.opcode & 255)); 1852 } 1853 } 1854 1855 if (uint32_t NewNum = expressionNumbering[Exp]) { 1856 if (Exp.opcode == Instruction::Call && NewNum != Num) 1857 return areCallValsEqual(Num, NewNum, Pred, PhiBlock, Gvn) ? NewNum : Num; 1858 return NewNum; 1859 } 1860 return Num; 1861 } 1862 1863 /// Erase stale entry from phiTranslate cache so phiTranslate can be computed 1864 /// again. 1865 void GVN::ValueTable::eraseTranslateCacheEntry(uint32_t Num, 1866 const BasicBlock &CurrBlock) { 1867 for (const BasicBlock *Pred : predecessors(&CurrBlock)) { 1868 auto FindRes = PhiTranslateTable.find({Num, Pred}); 1869 if (FindRes != PhiTranslateTable.end()) 1870 PhiTranslateTable.erase(FindRes); 1871 } 1872 } 1873 1874 // In order to find a leader for a given value number at a 1875 // specific basic block, we first obtain the list of all Values for that number, 1876 // and then scan the list to find one whose block dominates the block in 1877 // question. This is fast because dominator tree queries consist of only 1878 // a few comparisons of DFS numbers. 1879 Value *GVN::findLeader(const BasicBlock *BB, uint32_t num) { 1880 LeaderTableEntry Vals = LeaderTable[num]; 1881 if (!Vals.Val) return nullptr; 1882 1883 Value *Val = nullptr; 1884 if (DT->dominates(Vals.BB, BB)) { 1885 Val = Vals.Val; 1886 if (isa<Constant>(Val)) return Val; 1887 } 1888 1889 LeaderTableEntry* Next = Vals.Next; 1890 while (Next) { 1891 if (DT->dominates(Next->BB, BB)) { 1892 if (isa<Constant>(Next->Val)) return Next->Val; 1893 if (!Val) Val = Next->Val; 1894 } 1895 1896 Next = Next->Next; 1897 } 1898 1899 return Val; 1900 } 1901 1902 /// There is an edge from 'Src' to 'Dst'. Return 1903 /// true if every path from the entry block to 'Dst' passes via this edge. In 1904 /// particular 'Dst' must not be reachable via another edge from 'Src'. 1905 static bool isOnlyReachableViaThisEdge(const BasicBlockEdge &E, 1906 DominatorTree *DT) { 1907 // While in theory it is interesting to consider the case in which Dst has 1908 // more than one predecessor, because Dst might be part of a loop which is 1909 // only reachable from Src, in practice it is pointless since at the time 1910 // GVN runs all such loops have preheaders, which means that Dst will have 1911 // been changed to have only one predecessor, namely Src. 1912 const BasicBlock *Pred = E.getEnd()->getSinglePredecessor(); 1913 assert((!Pred || Pred == E.getStart()) && 1914 "No edge between these basic blocks!"); 1915 return Pred != nullptr; 1916 } 1917 1918 void GVN::assignBlockRPONumber(Function &F) { 1919 BlockRPONumber.clear(); 1920 uint32_t NextBlockNumber = 1; 1921 ReversePostOrderTraversal<Function *> RPOT(&F); 1922 for (BasicBlock *BB : RPOT) 1923 BlockRPONumber[BB] = NextBlockNumber++; 1924 InvalidBlockRPONumbers = false; 1925 } 1926 1927 bool GVN::replaceOperandsForInBlockEquality(Instruction *Instr) const { 1928 bool Changed = false; 1929 for (unsigned OpNum = 0; OpNum < Instr->getNumOperands(); ++OpNum) { 1930 Value *Operand = Instr->getOperand(OpNum); 1931 auto it = ReplaceOperandsWithMap.find(Operand); 1932 if (it != ReplaceOperandsWithMap.end()) { 1933 LLVM_DEBUG(dbgs() << "GVN replacing: " << *Operand << " with " 1934 << *it->second << " in instruction " << *Instr << '\n'); 1935 Instr->setOperand(OpNum, it->second); 1936 Changed = true; 1937 } 1938 } 1939 return Changed; 1940 } 1941 1942 /// The given values are known to be equal in every block 1943 /// dominated by 'Root'. Exploit this, for example by replacing 'LHS' with 1944 /// 'RHS' everywhere in the scope. Returns whether a change was made. 1945 /// If DominatesByEdge is false, then it means that we will propagate the RHS 1946 /// value starting from the end of Root.Start. 1947 bool GVN::propagateEquality(Value *LHS, Value *RHS, const BasicBlockEdge &Root, 1948 bool DominatesByEdge) { 1949 SmallVector<std::pair<Value*, Value*>, 4> Worklist; 1950 Worklist.push_back(std::make_pair(LHS, RHS)); 1951 bool Changed = false; 1952 // For speed, compute a conservative fast approximation to 1953 // DT->dominates(Root, Root.getEnd()); 1954 const bool RootDominatesEnd = isOnlyReachableViaThisEdge(Root, DT); 1955 1956 while (!Worklist.empty()) { 1957 std::pair<Value*, Value*> Item = Worklist.pop_back_val(); 1958 LHS = Item.first; RHS = Item.second; 1959 1960 if (LHS == RHS) 1961 continue; 1962 assert(LHS->getType() == RHS->getType() && "Equality but unequal types!"); 1963 1964 // Don't try to propagate equalities between constants. 1965 if (isa<Constant>(LHS) && isa<Constant>(RHS)) 1966 continue; 1967 1968 // Prefer a constant on the right-hand side, or an Argument if no constants. 1969 if (isa<Constant>(LHS) || (isa<Argument>(LHS) && !isa<Constant>(RHS))) 1970 std::swap(LHS, RHS); 1971 assert((isa<Argument>(LHS) || isa<Instruction>(LHS)) && "Unexpected value!"); 1972 1973 // If there is no obvious reason to prefer the left-hand side over the 1974 // right-hand side, ensure the longest lived term is on the right-hand side, 1975 // so the shortest lived term will be replaced by the longest lived. 1976 // This tends to expose more simplifications. 1977 uint32_t LVN = VN.lookupOrAdd(LHS); 1978 if ((isa<Argument>(LHS) && isa<Argument>(RHS)) || 1979 (isa<Instruction>(LHS) && isa<Instruction>(RHS))) { 1980 // Move the 'oldest' value to the right-hand side, using the value number 1981 // as a proxy for age. 1982 uint32_t RVN = VN.lookupOrAdd(RHS); 1983 if (LVN < RVN) { 1984 std::swap(LHS, RHS); 1985 LVN = RVN; 1986 } 1987 } 1988 1989 // If value numbering later sees that an instruction in the scope is equal 1990 // to 'LHS' then ensure it will be turned into 'RHS'. In order to preserve 1991 // the invariant that instructions only occur in the leader table for their 1992 // own value number (this is used by removeFromLeaderTable), do not do this 1993 // if RHS is an instruction (if an instruction in the scope is morphed into 1994 // LHS then it will be turned into RHS by the next GVN iteration anyway, so 1995 // using the leader table is about compiling faster, not optimizing better). 1996 // The leader table only tracks basic blocks, not edges. Only add to if we 1997 // have the simple case where the edge dominates the end. 1998 if (RootDominatesEnd && !isa<Instruction>(RHS)) 1999 addToLeaderTable(LVN, RHS, Root.getEnd()); 2000 2001 // Replace all occurrences of 'LHS' with 'RHS' everywhere in the scope. As 2002 // LHS always has at least one use that is not dominated by Root, this will 2003 // never do anything if LHS has only one use. 2004 if (!LHS->hasOneUse()) { 2005 unsigned NumReplacements = 2006 DominatesByEdge 2007 ? replaceDominatedUsesWith(LHS, RHS, *DT, Root) 2008 : replaceDominatedUsesWith(LHS, RHS, *DT, Root.getStart()); 2009 2010 Changed |= NumReplacements > 0; 2011 NumGVNEqProp += NumReplacements; 2012 // Cached information for anything that uses LHS will be invalid. 2013 if (MD) 2014 MD->invalidateCachedPointerInfo(LHS); 2015 } 2016 2017 // Now try to deduce additional equalities from this one. For example, if 2018 // the known equality was "(A != B)" == "false" then it follows that A and B 2019 // are equal in the scope. Only boolean equalities with an explicit true or 2020 // false RHS are currently supported. 2021 if (!RHS->getType()->isIntegerTy(1)) 2022 // Not a boolean equality - bail out. 2023 continue; 2024 ConstantInt *CI = dyn_cast<ConstantInt>(RHS); 2025 if (!CI) 2026 // RHS neither 'true' nor 'false' - bail out. 2027 continue; 2028 // Whether RHS equals 'true'. Otherwise it equals 'false'. 2029 bool isKnownTrue = CI->isMinusOne(); 2030 bool isKnownFalse = !isKnownTrue; 2031 2032 // If "A && B" is known true then both A and B are known true. If "A || B" 2033 // is known false then both A and B are known false. 2034 Value *A, *B; 2035 if ((isKnownTrue && match(LHS, m_And(m_Value(A), m_Value(B)))) || 2036 (isKnownFalse && match(LHS, m_Or(m_Value(A), m_Value(B))))) { 2037 Worklist.push_back(std::make_pair(A, RHS)); 2038 Worklist.push_back(std::make_pair(B, RHS)); 2039 continue; 2040 } 2041 2042 // If we are propagating an equality like "(A == B)" == "true" then also 2043 // propagate the equality A == B. When propagating a comparison such as 2044 // "(A >= B)" == "true", replace all instances of "A < B" with "false". 2045 if (CmpInst *Cmp = dyn_cast<CmpInst>(LHS)) { 2046 Value *Op0 = Cmp->getOperand(0), *Op1 = Cmp->getOperand(1); 2047 2048 // If "A == B" is known true, or "A != B" is known false, then replace 2049 // A with B everywhere in the scope. For floating point operations, we 2050 // have to be careful since equality does not always imply equivalance. 2051 if ((isKnownTrue && impliesEquivalanceIfTrue(Cmp)) || 2052 (isKnownFalse && impliesEquivalanceIfFalse(Cmp))) 2053 Worklist.push_back(std::make_pair(Op0, Op1)); 2054 2055 // If "A >= B" is known true, replace "A < B" with false everywhere. 2056 CmpInst::Predicate NotPred = Cmp->getInversePredicate(); 2057 Constant *NotVal = ConstantInt::get(Cmp->getType(), isKnownFalse); 2058 // Since we don't have the instruction "A < B" immediately to hand, work 2059 // out the value number that it would have and use that to find an 2060 // appropriate instruction (if any). 2061 uint32_t NextNum = VN.getNextUnusedValueNumber(); 2062 uint32_t Num = VN.lookupOrAddCmp(Cmp->getOpcode(), NotPred, Op0, Op1); 2063 // If the number we were assigned was brand new then there is no point in 2064 // looking for an instruction realizing it: there cannot be one! 2065 if (Num < NextNum) { 2066 Value *NotCmp = findLeader(Root.getEnd(), Num); 2067 if (NotCmp && isa<Instruction>(NotCmp)) { 2068 unsigned NumReplacements = 2069 DominatesByEdge 2070 ? replaceDominatedUsesWith(NotCmp, NotVal, *DT, Root) 2071 : replaceDominatedUsesWith(NotCmp, NotVal, *DT, 2072 Root.getStart()); 2073 Changed |= NumReplacements > 0; 2074 NumGVNEqProp += NumReplacements; 2075 // Cached information for anything that uses NotCmp will be invalid. 2076 if (MD) 2077 MD->invalidateCachedPointerInfo(NotCmp); 2078 } 2079 } 2080 // Ensure that any instruction in scope that gets the "A < B" value number 2081 // is replaced with false. 2082 // The leader table only tracks basic blocks, not edges. Only add to if we 2083 // have the simple case where the edge dominates the end. 2084 if (RootDominatesEnd) 2085 addToLeaderTable(Num, NotVal, Root.getEnd()); 2086 2087 continue; 2088 } 2089 } 2090 2091 return Changed; 2092 } 2093 2094 /// When calculating availability, handle an instruction 2095 /// by inserting it into the appropriate sets 2096 bool GVN::processInstruction(Instruction *I) { 2097 // Ignore dbg info intrinsics. 2098 if (isa<DbgInfoIntrinsic>(I)) 2099 return false; 2100 2101 // If the instruction can be easily simplified then do so now in preference 2102 // to value numbering it. Value numbering often exposes redundancies, for 2103 // example if it determines that %y is equal to %x then the instruction 2104 // "%z = and i32 %x, %y" becomes "%z = and i32 %x, %x" which we now simplify. 2105 const DataLayout &DL = I->getModule()->getDataLayout(); 2106 if (Value *V = SimplifyInstruction(I, {DL, TLI, DT, AC})) { 2107 bool Changed = false; 2108 if (!I->use_empty()) { 2109 I->replaceAllUsesWith(V); 2110 Changed = true; 2111 } 2112 if (isInstructionTriviallyDead(I, TLI)) { 2113 markInstructionForDeletion(I); 2114 Changed = true; 2115 } 2116 if (Changed) { 2117 if (MD && V->getType()->isPtrOrPtrVectorTy()) 2118 MD->invalidateCachedPointerInfo(V); 2119 ++NumGVNSimpl; 2120 return true; 2121 } 2122 } 2123 2124 if (IntrinsicInst *IntrinsicI = dyn_cast<IntrinsicInst>(I)) 2125 if (IntrinsicI->getIntrinsicID() == Intrinsic::assume) 2126 return processAssumeIntrinsic(IntrinsicI); 2127 2128 if (LoadInst *LI = dyn_cast<LoadInst>(I)) { 2129 if (processLoad(LI)) 2130 return true; 2131 2132 unsigned Num = VN.lookupOrAdd(LI); 2133 addToLeaderTable(Num, LI, LI->getParent()); 2134 return false; 2135 } 2136 2137 // For conditional branches, we can perform simple conditional propagation on 2138 // the condition value itself. 2139 if (BranchInst *BI = dyn_cast<BranchInst>(I)) { 2140 if (!BI->isConditional()) 2141 return false; 2142 2143 if (isa<Constant>(BI->getCondition())) 2144 return processFoldableCondBr(BI); 2145 2146 Value *BranchCond = BI->getCondition(); 2147 BasicBlock *TrueSucc = BI->getSuccessor(0); 2148 BasicBlock *FalseSucc = BI->getSuccessor(1); 2149 // Avoid multiple edges early. 2150 if (TrueSucc == FalseSucc) 2151 return false; 2152 2153 BasicBlock *Parent = BI->getParent(); 2154 bool Changed = false; 2155 2156 Value *TrueVal = ConstantInt::getTrue(TrueSucc->getContext()); 2157 BasicBlockEdge TrueE(Parent, TrueSucc); 2158 Changed |= propagateEquality(BranchCond, TrueVal, TrueE, true); 2159 2160 Value *FalseVal = ConstantInt::getFalse(FalseSucc->getContext()); 2161 BasicBlockEdge FalseE(Parent, FalseSucc); 2162 Changed |= propagateEquality(BranchCond, FalseVal, FalseE, true); 2163 2164 return Changed; 2165 } 2166 2167 // For switches, propagate the case values into the case destinations. 2168 if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) { 2169 Value *SwitchCond = SI->getCondition(); 2170 BasicBlock *Parent = SI->getParent(); 2171 bool Changed = false; 2172 2173 // Remember how many outgoing edges there are to every successor. 2174 SmallDenseMap<BasicBlock *, unsigned, 16> SwitchEdges; 2175 for (unsigned i = 0, n = SI->getNumSuccessors(); i != n; ++i) 2176 ++SwitchEdges[SI->getSuccessor(i)]; 2177 2178 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end(); 2179 i != e; ++i) { 2180 BasicBlock *Dst = i->getCaseSuccessor(); 2181 // If there is only a single edge, propagate the case value into it. 2182 if (SwitchEdges.lookup(Dst) == 1) { 2183 BasicBlockEdge E(Parent, Dst); 2184 Changed |= propagateEquality(SwitchCond, i->getCaseValue(), E, true); 2185 } 2186 } 2187 return Changed; 2188 } 2189 2190 // Instructions with void type don't return a value, so there's 2191 // no point in trying to find redundancies in them. 2192 if (I->getType()->isVoidTy()) 2193 return false; 2194 2195 uint32_t NextNum = VN.getNextUnusedValueNumber(); 2196 unsigned Num = VN.lookupOrAdd(I); 2197 2198 // Allocations are always uniquely numbered, so we can save time and memory 2199 // by fast failing them. 2200 if (isa<AllocaInst>(I) || I->isTerminator() || isa<PHINode>(I)) { 2201 addToLeaderTable(Num, I, I->getParent()); 2202 return false; 2203 } 2204 2205 // If the number we were assigned was a brand new VN, then we don't 2206 // need to do a lookup to see if the number already exists 2207 // somewhere in the domtree: it can't! 2208 if (Num >= NextNum) { 2209 addToLeaderTable(Num, I, I->getParent()); 2210 return false; 2211 } 2212 2213 // Perform fast-path value-number based elimination of values inherited from 2214 // dominators. 2215 Value *Repl = findLeader(I->getParent(), Num); 2216 if (!Repl) { 2217 // Failure, just remember this instance for future use. 2218 addToLeaderTable(Num, I, I->getParent()); 2219 return false; 2220 } else if (Repl == I) { 2221 // If I was the result of a shortcut PRE, it might already be in the table 2222 // and the best replacement for itself. Nothing to do. 2223 return false; 2224 } 2225 2226 // Remove it! 2227 patchAndReplaceAllUsesWith(I, Repl); 2228 if (MD && Repl->getType()->isPtrOrPtrVectorTy()) 2229 MD->invalidateCachedPointerInfo(Repl); 2230 markInstructionForDeletion(I); 2231 return true; 2232 } 2233 2234 /// runOnFunction - This is the main transformation entry point for a function. 2235 bool GVN::runImpl(Function &F, AssumptionCache &RunAC, DominatorTree &RunDT, 2236 const TargetLibraryInfo &RunTLI, AAResults &RunAA, 2237 MemoryDependenceResults *RunMD, LoopInfo *LI, 2238 OptimizationRemarkEmitter *RunORE, MemorySSA *MSSA) { 2239 AC = &RunAC; 2240 DT = &RunDT; 2241 VN.setDomTree(DT); 2242 TLI = &RunTLI; 2243 VN.setAliasAnalysis(&RunAA); 2244 MD = RunMD; 2245 ImplicitControlFlowTracking ImplicitCFT; 2246 ICF = &ImplicitCFT; 2247 this->LI = LI; 2248 VN.setMemDep(MD); 2249 ORE = RunORE; 2250 InvalidBlockRPONumbers = true; 2251 MemorySSAUpdater Updater(MSSA); 2252 MSSAU = MSSA ? &Updater : nullptr; 2253 2254 bool Changed = false; 2255 bool ShouldContinue = true; 2256 2257 DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager); 2258 // Merge unconditional branches, allowing PRE to catch more 2259 // optimization opportunities. 2260 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ) { 2261 BasicBlock *BB = &*FI++; 2262 2263 bool removedBlock = MergeBlockIntoPredecessor(BB, &DTU, LI, MSSAU, MD); 2264 if (removedBlock) 2265 ++NumGVNBlocks; 2266 2267 Changed |= removedBlock; 2268 } 2269 2270 unsigned Iteration = 0; 2271 while (ShouldContinue) { 2272 LLVM_DEBUG(dbgs() << "GVN iteration: " << Iteration << "\n"); 2273 ShouldContinue = iterateOnFunction(F); 2274 Changed |= ShouldContinue; 2275 ++Iteration; 2276 } 2277 2278 if (isPREEnabled()) { 2279 // Fabricate val-num for dead-code in order to suppress assertion in 2280 // performPRE(). 2281 assignValNumForDeadCode(); 2282 bool PREChanged = true; 2283 while (PREChanged) { 2284 PREChanged = performPRE(F); 2285 Changed |= PREChanged; 2286 } 2287 } 2288 2289 // FIXME: Should perform GVN again after PRE does something. PRE can move 2290 // computations into blocks where they become fully redundant. Note that 2291 // we can't do this until PRE's critical edge splitting updates memdep. 2292 // Actually, when this happens, we should just fully integrate PRE into GVN. 2293 2294 cleanupGlobalSets(); 2295 // Do not cleanup DeadBlocks in cleanupGlobalSets() as it's called for each 2296 // iteration. 2297 DeadBlocks.clear(); 2298 2299 if (MSSA && VerifyMemorySSA) 2300 MSSA->verifyMemorySSA(); 2301 2302 return Changed; 2303 } 2304 2305 bool GVN::processBlock(BasicBlock *BB) { 2306 // FIXME: Kill off InstrsToErase by doing erasing eagerly in a helper function 2307 // (and incrementing BI before processing an instruction). 2308 assert(InstrsToErase.empty() && 2309 "We expect InstrsToErase to be empty across iterations"); 2310 if (DeadBlocks.count(BB)) 2311 return false; 2312 2313 // Clearing map before every BB because it can be used only for single BB. 2314 ReplaceOperandsWithMap.clear(); 2315 bool ChangedFunction = false; 2316 2317 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); 2318 BI != BE;) { 2319 if (!ReplaceOperandsWithMap.empty()) 2320 ChangedFunction |= replaceOperandsForInBlockEquality(&*BI); 2321 ChangedFunction |= processInstruction(&*BI); 2322 2323 if (InstrsToErase.empty()) { 2324 ++BI; 2325 continue; 2326 } 2327 2328 // If we need some instructions deleted, do it now. 2329 NumGVNInstr += InstrsToErase.size(); 2330 2331 // Avoid iterator invalidation. 2332 bool AtStart = BI == BB->begin(); 2333 if (!AtStart) 2334 --BI; 2335 2336 for (auto *I : InstrsToErase) { 2337 assert(I->getParent() == BB && "Removing instruction from wrong block?"); 2338 LLVM_DEBUG(dbgs() << "GVN removed: " << *I << '\n'); 2339 salvageKnowledge(I, AC); 2340 salvageDebugInfo(*I); 2341 if (MD) MD->removeInstruction(I); 2342 if (MSSAU) 2343 MSSAU->removeMemoryAccess(I); 2344 LLVM_DEBUG(verifyRemoved(I)); 2345 ICF->removeInstruction(I); 2346 I->eraseFromParent(); 2347 } 2348 InstrsToErase.clear(); 2349 2350 if (AtStart) 2351 BI = BB->begin(); 2352 else 2353 ++BI; 2354 } 2355 2356 return ChangedFunction; 2357 } 2358 2359 // Instantiate an expression in a predecessor that lacked it. 2360 bool GVN::performScalarPREInsertion(Instruction *Instr, BasicBlock *Pred, 2361 BasicBlock *Curr, unsigned int ValNo) { 2362 // Because we are going top-down through the block, all value numbers 2363 // will be available in the predecessor by the time we need them. Any 2364 // that weren't originally present will have been instantiated earlier 2365 // in this loop. 2366 bool success = true; 2367 for (unsigned i = 0, e = Instr->getNumOperands(); i != e; ++i) { 2368 Value *Op = Instr->getOperand(i); 2369 if (isa<Argument>(Op) || isa<Constant>(Op) || isa<GlobalValue>(Op)) 2370 continue; 2371 // This could be a newly inserted instruction, in which case, we won't 2372 // find a value number, and should give up before we hurt ourselves. 2373 // FIXME: Rewrite the infrastructure to let it easier to value number 2374 // and process newly inserted instructions. 2375 if (!VN.exists(Op)) { 2376 success = false; 2377 break; 2378 } 2379 uint32_t TValNo = 2380 VN.phiTranslate(Pred, Curr, VN.lookup(Op), *this); 2381 if (Value *V = findLeader(Pred, TValNo)) { 2382 Instr->setOperand(i, V); 2383 } else { 2384 success = false; 2385 break; 2386 } 2387 } 2388 2389 // Fail out if we encounter an operand that is not available in 2390 // the PRE predecessor. This is typically because of loads which 2391 // are not value numbered precisely. 2392 if (!success) 2393 return false; 2394 2395 Instr->insertBefore(Pred->getTerminator()); 2396 Instr->setName(Instr->getName() + ".pre"); 2397 Instr->setDebugLoc(Instr->getDebugLoc()); 2398 2399 unsigned Num = VN.lookupOrAdd(Instr); 2400 VN.add(Instr, Num); 2401 2402 // Update the availability map to include the new instruction. 2403 addToLeaderTable(Num, Instr, Pred); 2404 return true; 2405 } 2406 2407 bool GVN::performScalarPRE(Instruction *CurInst) { 2408 if (isa<AllocaInst>(CurInst) || CurInst->isTerminator() || 2409 isa<PHINode>(CurInst) || CurInst->getType()->isVoidTy() || 2410 CurInst->mayReadFromMemory() || CurInst->mayHaveSideEffects() || 2411 isa<DbgInfoIntrinsic>(CurInst)) 2412 return false; 2413 2414 // Don't do PRE on compares. The PHI would prevent CodeGenPrepare from 2415 // sinking the compare again, and it would force the code generator to 2416 // move the i1 from processor flags or predicate registers into a general 2417 // purpose register. 2418 if (isa<CmpInst>(CurInst)) 2419 return false; 2420 2421 // Don't do PRE on GEPs. The inserted PHI would prevent CodeGenPrepare from 2422 // sinking the addressing mode computation back to its uses. Extending the 2423 // GEP's live range increases the register pressure, and therefore it can 2424 // introduce unnecessary spills. 2425 // 2426 // This doesn't prevent Load PRE. PHI translation will make the GEP available 2427 // to the load by moving it to the predecessor block if necessary. 2428 if (isa<GetElementPtrInst>(CurInst)) 2429 return false; 2430 2431 // We don't currently value number ANY inline asm calls. 2432 if (auto *CallB = dyn_cast<CallBase>(CurInst)) 2433 if (CallB->isInlineAsm()) 2434 return false; 2435 2436 uint32_t ValNo = VN.lookup(CurInst); 2437 2438 // Look for the predecessors for PRE opportunities. We're 2439 // only trying to solve the basic diamond case, where 2440 // a value is computed in the successor and one predecessor, 2441 // but not the other. We also explicitly disallow cases 2442 // where the successor is its own predecessor, because they're 2443 // more complicated to get right. 2444 unsigned NumWith = 0; 2445 unsigned NumWithout = 0; 2446 BasicBlock *PREPred = nullptr; 2447 BasicBlock *CurrentBlock = CurInst->getParent(); 2448 2449 // Update the RPO numbers for this function. 2450 if (InvalidBlockRPONumbers) 2451 assignBlockRPONumber(*CurrentBlock->getParent()); 2452 2453 SmallVector<std::pair<Value *, BasicBlock *>, 8> predMap; 2454 for (BasicBlock *P : predecessors(CurrentBlock)) { 2455 // We're not interested in PRE where blocks with predecessors that are 2456 // not reachable. 2457 if (!DT->isReachableFromEntry(P)) { 2458 NumWithout = 2; 2459 break; 2460 } 2461 // It is not safe to do PRE when P->CurrentBlock is a loop backedge, and 2462 // when CurInst has operand defined in CurrentBlock (so it may be defined 2463 // by phi in the loop header). 2464 assert(BlockRPONumber.count(P) && BlockRPONumber.count(CurrentBlock) && 2465 "Invalid BlockRPONumber map."); 2466 if (BlockRPONumber[P] >= BlockRPONumber[CurrentBlock] && 2467 llvm::any_of(CurInst->operands(), [&](const Use &U) { 2468 if (auto *Inst = dyn_cast<Instruction>(U.get())) 2469 return Inst->getParent() == CurrentBlock; 2470 return false; 2471 })) { 2472 NumWithout = 2; 2473 break; 2474 } 2475 2476 uint32_t TValNo = VN.phiTranslate(P, CurrentBlock, ValNo, *this); 2477 Value *predV = findLeader(P, TValNo); 2478 if (!predV) { 2479 predMap.push_back(std::make_pair(static_cast<Value *>(nullptr), P)); 2480 PREPred = P; 2481 ++NumWithout; 2482 } else if (predV == CurInst) { 2483 /* CurInst dominates this predecessor. */ 2484 NumWithout = 2; 2485 break; 2486 } else { 2487 predMap.push_back(std::make_pair(predV, P)); 2488 ++NumWith; 2489 } 2490 } 2491 2492 // Don't do PRE when it might increase code size, i.e. when 2493 // we would need to insert instructions in more than one pred. 2494 if (NumWithout > 1 || NumWith == 0) 2495 return false; 2496 2497 // We may have a case where all predecessors have the instruction, 2498 // and we just need to insert a phi node. Otherwise, perform 2499 // insertion. 2500 Instruction *PREInstr = nullptr; 2501 2502 if (NumWithout != 0) { 2503 if (!isSafeToSpeculativelyExecute(CurInst)) { 2504 // It is only valid to insert a new instruction if the current instruction 2505 // is always executed. An instruction with implicit control flow could 2506 // prevent us from doing it. If we cannot speculate the execution, then 2507 // PRE should be prohibited. 2508 if (ICF->isDominatedByICFIFromSameBlock(CurInst)) 2509 return false; 2510 } 2511 2512 // Don't do PRE across indirect branch. 2513 if (isa<IndirectBrInst>(PREPred->getTerminator())) 2514 return false; 2515 2516 // Don't do PRE across callbr. 2517 // FIXME: Can we do this across the fallthrough edge? 2518 if (isa<CallBrInst>(PREPred->getTerminator())) 2519 return false; 2520 2521 // We can't do PRE safely on a critical edge, so instead we schedule 2522 // the edge to be split and perform the PRE the next time we iterate 2523 // on the function. 2524 unsigned SuccNum = GetSuccessorNumber(PREPred, CurrentBlock); 2525 if (isCriticalEdge(PREPred->getTerminator(), SuccNum)) { 2526 toSplit.push_back(std::make_pair(PREPred->getTerminator(), SuccNum)); 2527 return false; 2528 } 2529 // We need to insert somewhere, so let's give it a shot 2530 PREInstr = CurInst->clone(); 2531 if (!performScalarPREInsertion(PREInstr, PREPred, CurrentBlock, ValNo)) { 2532 // If we failed insertion, make sure we remove the instruction. 2533 LLVM_DEBUG(verifyRemoved(PREInstr)); 2534 PREInstr->deleteValue(); 2535 return false; 2536 } 2537 } 2538 2539 // Either we should have filled in the PRE instruction, or we should 2540 // not have needed insertions. 2541 assert(PREInstr != nullptr || NumWithout == 0); 2542 2543 ++NumGVNPRE; 2544 2545 // Create a PHI to make the value available in this block. 2546 PHINode *Phi = 2547 PHINode::Create(CurInst->getType(), predMap.size(), 2548 CurInst->getName() + ".pre-phi", &CurrentBlock->front()); 2549 for (unsigned i = 0, e = predMap.size(); i != e; ++i) { 2550 if (Value *V = predMap[i].first) { 2551 // If we use an existing value in this phi, we have to patch the original 2552 // value because the phi will be used to replace a later value. 2553 patchReplacementInstruction(CurInst, V); 2554 Phi->addIncoming(V, predMap[i].second); 2555 } else 2556 Phi->addIncoming(PREInstr, PREPred); 2557 } 2558 2559 VN.add(Phi, ValNo); 2560 // After creating a new PHI for ValNo, the phi translate result for ValNo will 2561 // be changed, so erase the related stale entries in phi translate cache. 2562 VN.eraseTranslateCacheEntry(ValNo, *CurrentBlock); 2563 addToLeaderTable(ValNo, Phi, CurrentBlock); 2564 Phi->setDebugLoc(CurInst->getDebugLoc()); 2565 CurInst->replaceAllUsesWith(Phi); 2566 if (MD && Phi->getType()->isPtrOrPtrVectorTy()) 2567 MD->invalidateCachedPointerInfo(Phi); 2568 VN.erase(CurInst); 2569 removeFromLeaderTable(ValNo, CurInst, CurrentBlock); 2570 2571 LLVM_DEBUG(dbgs() << "GVN PRE removed: " << *CurInst << '\n'); 2572 if (MD) 2573 MD->removeInstruction(CurInst); 2574 if (MSSAU) 2575 MSSAU->removeMemoryAccess(CurInst); 2576 LLVM_DEBUG(verifyRemoved(CurInst)); 2577 // FIXME: Intended to be markInstructionForDeletion(CurInst), but it causes 2578 // some assertion failures. 2579 ICF->removeInstruction(CurInst); 2580 CurInst->eraseFromParent(); 2581 ++NumGVNInstr; 2582 2583 return true; 2584 } 2585 2586 /// Perform a purely local form of PRE that looks for diamond 2587 /// control flow patterns and attempts to perform simple PRE at the join point. 2588 bool GVN::performPRE(Function &F) { 2589 bool Changed = false; 2590 for (BasicBlock *CurrentBlock : depth_first(&F.getEntryBlock())) { 2591 // Nothing to PRE in the entry block. 2592 if (CurrentBlock == &F.getEntryBlock()) 2593 continue; 2594 2595 // Don't perform PRE on an EH pad. 2596 if (CurrentBlock->isEHPad()) 2597 continue; 2598 2599 for (BasicBlock::iterator BI = CurrentBlock->begin(), 2600 BE = CurrentBlock->end(); 2601 BI != BE;) { 2602 Instruction *CurInst = &*BI++; 2603 Changed |= performScalarPRE(CurInst); 2604 } 2605 } 2606 2607 if (splitCriticalEdges()) 2608 Changed = true; 2609 2610 return Changed; 2611 } 2612 2613 /// Split the critical edge connecting the given two blocks, and return 2614 /// the block inserted to the critical edge. 2615 BasicBlock *GVN::splitCriticalEdges(BasicBlock *Pred, BasicBlock *Succ) { 2616 // GVN does not require loop-simplify, do not try to preserve it if it is not 2617 // possible. 2618 BasicBlock *BB = SplitCriticalEdge( 2619 Pred, Succ, 2620 CriticalEdgeSplittingOptions(DT, LI, MSSAU).unsetPreserveLoopSimplify()); 2621 if (MD) 2622 MD->invalidateCachedPredecessors(); 2623 InvalidBlockRPONumbers = true; 2624 return BB; 2625 } 2626 2627 /// Split critical edges found during the previous 2628 /// iteration that may enable further optimization. 2629 bool GVN::splitCriticalEdges() { 2630 if (toSplit.empty()) 2631 return false; 2632 do { 2633 std::pair<Instruction *, unsigned> Edge = toSplit.pop_back_val(); 2634 SplitCriticalEdge(Edge.first, Edge.second, 2635 CriticalEdgeSplittingOptions(DT, LI, MSSAU)); 2636 } while (!toSplit.empty()); 2637 if (MD) MD->invalidateCachedPredecessors(); 2638 InvalidBlockRPONumbers = true; 2639 return true; 2640 } 2641 2642 /// Executes one iteration of GVN 2643 bool GVN::iterateOnFunction(Function &F) { 2644 cleanupGlobalSets(); 2645 2646 // Top-down walk of the dominator tree 2647 bool Changed = false; 2648 // Needed for value numbering with phi construction to work. 2649 // RPOT walks the graph in its constructor and will not be invalidated during 2650 // processBlock. 2651 ReversePostOrderTraversal<Function *> RPOT(&F); 2652 2653 for (BasicBlock *BB : RPOT) 2654 Changed |= processBlock(BB); 2655 2656 return Changed; 2657 } 2658 2659 void GVN::cleanupGlobalSets() { 2660 VN.clear(); 2661 LeaderTable.clear(); 2662 BlockRPONumber.clear(); 2663 TableAllocator.Reset(); 2664 ICF->clear(); 2665 InvalidBlockRPONumbers = true; 2666 } 2667 2668 /// Verify that the specified instruction does not occur in our 2669 /// internal data structures. 2670 void GVN::verifyRemoved(const Instruction *Inst) const { 2671 VN.verifyRemoved(Inst); 2672 2673 // Walk through the value number scope to make sure the instruction isn't 2674 // ferreted away in it. 2675 for (DenseMap<uint32_t, LeaderTableEntry>::const_iterator 2676 I = LeaderTable.begin(), E = LeaderTable.end(); I != E; ++I) { 2677 const LeaderTableEntry *Node = &I->second; 2678 assert(Node->Val != Inst && "Inst still in value numbering scope!"); 2679 2680 while (Node->Next) { 2681 Node = Node->Next; 2682 assert(Node->Val != Inst && "Inst still in value numbering scope!"); 2683 } 2684 } 2685 } 2686 2687 /// BB is declared dead, which implied other blocks become dead as well. This 2688 /// function is to add all these blocks to "DeadBlocks". For the dead blocks' 2689 /// live successors, update their phi nodes by replacing the operands 2690 /// corresponding to dead blocks with UndefVal. 2691 void GVN::addDeadBlock(BasicBlock *BB) { 2692 SmallVector<BasicBlock *, 4> NewDead; 2693 SmallSetVector<BasicBlock *, 4> DF; 2694 2695 NewDead.push_back(BB); 2696 while (!NewDead.empty()) { 2697 BasicBlock *D = NewDead.pop_back_val(); 2698 if (DeadBlocks.count(D)) 2699 continue; 2700 2701 // All blocks dominated by D are dead. 2702 SmallVector<BasicBlock *, 8> Dom; 2703 DT->getDescendants(D, Dom); 2704 DeadBlocks.insert(Dom.begin(), Dom.end()); 2705 2706 // Figure out the dominance-frontier(D). 2707 for (BasicBlock *B : Dom) { 2708 for (BasicBlock *S : successors(B)) { 2709 if (DeadBlocks.count(S)) 2710 continue; 2711 2712 bool AllPredDead = true; 2713 for (BasicBlock *P : predecessors(S)) 2714 if (!DeadBlocks.count(P)) { 2715 AllPredDead = false; 2716 break; 2717 } 2718 2719 if (!AllPredDead) { 2720 // S could be proved dead later on. That is why we don't update phi 2721 // operands at this moment. 2722 DF.insert(S); 2723 } else { 2724 // While S is not dominated by D, it is dead by now. This could take 2725 // place if S already have a dead predecessor before D is declared 2726 // dead. 2727 NewDead.push_back(S); 2728 } 2729 } 2730 } 2731 } 2732 2733 // For the dead blocks' live successors, update their phi nodes by replacing 2734 // the operands corresponding to dead blocks with UndefVal. 2735 for(SmallSetVector<BasicBlock *, 4>::iterator I = DF.begin(), E = DF.end(); 2736 I != E; I++) { 2737 BasicBlock *B = *I; 2738 if (DeadBlocks.count(B)) 2739 continue; 2740 2741 // First, split the critical edges. This might also create additional blocks 2742 // to preserve LoopSimplify form and adjust edges accordingly. 2743 SmallVector<BasicBlock *, 4> Preds(pred_begin(B), pred_end(B)); 2744 for (BasicBlock *P : Preds) { 2745 if (!DeadBlocks.count(P)) 2746 continue; 2747 2748 if (llvm::any_of(successors(P), 2749 [B](BasicBlock *Succ) { return Succ == B; }) && 2750 isCriticalEdge(P->getTerminator(), B)) { 2751 if (BasicBlock *S = splitCriticalEdges(P, B)) 2752 DeadBlocks.insert(P = S); 2753 } 2754 } 2755 2756 // Now undef the incoming values from the dead predecessors. 2757 for (BasicBlock *P : predecessors(B)) { 2758 if (!DeadBlocks.count(P)) 2759 continue; 2760 for (PHINode &Phi : B->phis()) { 2761 Phi.setIncomingValueForBlock(P, UndefValue::get(Phi.getType())); 2762 if (MD) 2763 MD->invalidateCachedPointerInfo(&Phi); 2764 } 2765 } 2766 } 2767 } 2768 2769 // If the given branch is recognized as a foldable branch (i.e. conditional 2770 // branch with constant condition), it will perform following analyses and 2771 // transformation. 2772 // 1) If the dead out-coming edge is a critical-edge, split it. Let 2773 // R be the target of the dead out-coming edge. 2774 // 1) Identify the set of dead blocks implied by the branch's dead outcoming 2775 // edge. The result of this step will be {X| X is dominated by R} 2776 // 2) Identify those blocks which haves at least one dead predecessor. The 2777 // result of this step will be dominance-frontier(R). 2778 // 3) Update the PHIs in DF(R) by replacing the operands corresponding to 2779 // dead blocks with "UndefVal" in an hope these PHIs will optimized away. 2780 // 2781 // Return true iff *NEW* dead code are found. 2782 bool GVN::processFoldableCondBr(BranchInst *BI) { 2783 if (!BI || BI->isUnconditional()) 2784 return false; 2785 2786 // If a branch has two identical successors, we cannot declare either dead. 2787 if (BI->getSuccessor(0) == BI->getSuccessor(1)) 2788 return false; 2789 2790 ConstantInt *Cond = dyn_cast<ConstantInt>(BI->getCondition()); 2791 if (!Cond) 2792 return false; 2793 2794 BasicBlock *DeadRoot = 2795 Cond->getZExtValue() ? BI->getSuccessor(1) : BI->getSuccessor(0); 2796 if (DeadBlocks.count(DeadRoot)) 2797 return false; 2798 2799 if (!DeadRoot->getSinglePredecessor()) 2800 DeadRoot = splitCriticalEdges(BI->getParent(), DeadRoot); 2801 2802 addDeadBlock(DeadRoot); 2803 return true; 2804 } 2805 2806 // performPRE() will trigger assert if it comes across an instruction without 2807 // associated val-num. As it normally has far more live instructions than dead 2808 // instructions, it makes more sense just to "fabricate" a val-number for the 2809 // dead code than checking if instruction involved is dead or not. 2810 void GVN::assignValNumForDeadCode() { 2811 for (BasicBlock *BB : DeadBlocks) { 2812 for (Instruction &Inst : *BB) { 2813 unsigned ValNum = VN.lookupOrAdd(&Inst); 2814 addToLeaderTable(ValNum, &Inst, BB); 2815 } 2816 } 2817 } 2818 2819 class llvm::gvn::GVNLegacyPass : public FunctionPass { 2820 public: 2821 static char ID; // Pass identification, replacement for typeid 2822 2823 explicit GVNLegacyPass(bool NoMemDepAnalysis = !GVNEnableMemDep) 2824 : FunctionPass(ID), Impl(GVNOptions().setMemDep(!NoMemDepAnalysis)) { 2825 initializeGVNLegacyPassPass(*PassRegistry::getPassRegistry()); 2826 } 2827 2828 bool runOnFunction(Function &F) override { 2829 if (skipFunction(F)) 2830 return false; 2831 2832 auto *LIWP = getAnalysisIfAvailable<LoopInfoWrapperPass>(); 2833 2834 auto *MSSAWP = getAnalysisIfAvailable<MemorySSAWrapperPass>(); 2835 return Impl.runImpl( 2836 F, getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F), 2837 getAnalysis<DominatorTreeWrapperPass>().getDomTree(), 2838 getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F), 2839 getAnalysis<AAResultsWrapperPass>().getAAResults(), 2840 Impl.isMemDepEnabled() 2841 ? &getAnalysis<MemoryDependenceWrapperPass>().getMemDep() 2842 : nullptr, 2843 LIWP ? &LIWP->getLoopInfo() : nullptr, 2844 &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE(), 2845 MSSAWP ? &MSSAWP->getMSSA() : nullptr); 2846 } 2847 2848 void getAnalysisUsage(AnalysisUsage &AU) const override { 2849 AU.addRequired<AssumptionCacheTracker>(); 2850 AU.addRequired<DominatorTreeWrapperPass>(); 2851 AU.addRequired<TargetLibraryInfoWrapperPass>(); 2852 AU.addRequired<LoopInfoWrapperPass>(); 2853 if (Impl.isMemDepEnabled()) 2854 AU.addRequired<MemoryDependenceWrapperPass>(); 2855 AU.addRequired<AAResultsWrapperPass>(); 2856 AU.addPreserved<DominatorTreeWrapperPass>(); 2857 AU.addPreserved<GlobalsAAWrapperPass>(); 2858 AU.addPreserved<TargetLibraryInfoWrapperPass>(); 2859 AU.addPreserved<LoopInfoWrapperPass>(); 2860 AU.addRequired<OptimizationRemarkEmitterWrapperPass>(); 2861 AU.addPreserved<MemorySSAWrapperPass>(); 2862 } 2863 2864 private: 2865 GVN Impl; 2866 }; 2867 2868 char GVNLegacyPass::ID = 0; 2869 2870 INITIALIZE_PASS_BEGIN(GVNLegacyPass, "gvn", "Global Value Numbering", false, false) 2871 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 2872 INITIALIZE_PASS_DEPENDENCY(MemoryDependenceWrapperPass) 2873 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 2874 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 2875 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass) 2876 INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass) 2877 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass) 2878 INITIALIZE_PASS_END(GVNLegacyPass, "gvn", "Global Value Numbering", false, false) 2879 2880 // The public interface to this file... 2881 FunctionPass *llvm::createGVNPass(bool NoMemDepAnalysis) { 2882 return new GVNLegacyPass(NoMemDepAnalysis); 2883 } 2884