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