1 //===- GVNSink.cpp - sink expressions into successors -------------------===// 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 /// \file GVNSink.cpp 11 /// This pass attempts to sink instructions into successors, reducing static 12 /// instruction count and enabling if-conversion. 13 /// 14 /// We use a variant of global value numbering to decide what can be sunk. 15 /// Consider: 16 /// 17 /// [ %a1 = add i32 %b, 1 ] [ %c1 = add i32 %d, 1 ] 18 /// [ %a2 = xor i32 %a1, 1 ] [ %c2 = xor i32 %c1, 1 ] 19 /// \ / 20 /// [ %e = phi i32 %a2, %c2 ] 21 /// [ add i32 %e, 4 ] 22 /// 23 /// 24 /// GVN would number %a1 and %c1 differently because they compute different 25 /// results - the VN of an instruction is a function of its opcode and the 26 /// transitive closure of its operands. This is the key property for hoisting 27 /// and CSE. 28 /// 29 /// What we want when sinking however is for a numbering that is a function of 30 /// the *uses* of an instruction, which allows us to answer the question "if I 31 /// replace %a1 with %c1, will it contribute in an equivalent way to all 32 /// successive instructions?". The PostValueTable class in GVN provides this 33 /// mapping. 34 /// 35 //===----------------------------------------------------------------------===// 36 37 #include "llvm/ADT/DenseMap.h" 38 #include "llvm/ADT/DenseMapInfo.h" 39 #include "llvm/ADT/DenseSet.h" 40 #include "llvm/ADT/Hashing.h" 41 #include "llvm/ADT/Optional.h" 42 #include "llvm/ADT/PostOrderIterator.h" 43 #include "llvm/ADT/SCCIterator.h" 44 #include "llvm/ADT/SmallPtrSet.h" 45 #include "llvm/ADT/Statistic.h" 46 #include "llvm/ADT/StringExtras.h" 47 #include "llvm/Analysis/GlobalsModRef.h" 48 #include "llvm/Analysis/MemorySSA.h" 49 #include "llvm/Analysis/PostDominators.h" 50 #include "llvm/Analysis/TargetTransformInfo.h" 51 #include "llvm/Analysis/ValueTracking.h" 52 #include "llvm/IR/Instructions.h" 53 #include "llvm/IR/Verifier.h" 54 #include "llvm/Support/MathExtras.h" 55 #include "llvm/Transforms/Scalar.h" 56 #include "llvm/Transforms/Scalar/GVN.h" 57 #include "llvm/Transforms/Scalar/GVNExpression.h" 58 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 59 #include "llvm/Transforms/Utils/Local.h" 60 #include <unordered_set> 61 using namespace llvm; 62 63 #define DEBUG_TYPE "gvn-sink" 64 65 STATISTIC(NumRemoved, "Number of instructions removed"); 66 67 namespace llvm { 68 namespace GVNExpression { 69 70 LLVM_DUMP_METHOD void Expression::dump() const { 71 print(dbgs()); 72 dbgs() << "\n"; 73 } 74 75 } 76 } 77 78 namespace { 79 80 static bool isMemoryInst(const Instruction *I) { 81 return isa<LoadInst>(I) || isa<StoreInst>(I) || 82 (isa<InvokeInst>(I) && !cast<InvokeInst>(I)->doesNotAccessMemory()) || 83 (isa<CallInst>(I) && !cast<CallInst>(I)->doesNotAccessMemory()); 84 } 85 86 /// Iterates through instructions in a set of blocks in reverse order from the 87 /// first non-terminator. For example (assume all blocks have size n): 88 /// LockstepReverseIterator I([B1, B2, B3]); 89 /// *I-- = [B1[n], B2[n], B3[n]]; 90 /// *I-- = [B1[n-1], B2[n-1], B3[n-1]]; 91 /// *I-- = [B1[n-2], B2[n-2], B3[n-2]]; 92 /// ... 93 /// 94 /// It continues until all blocks have been exhausted. Use \c getActiveBlocks() 95 /// to 96 /// determine which blocks are still going and the order they appear in the 97 /// list returned by operator*. 98 class LockstepReverseIterator { 99 ArrayRef<BasicBlock *> Blocks; 100 SmallPtrSet<BasicBlock *, 4> ActiveBlocks; 101 SmallVector<Instruction *, 4> Insts; 102 bool Fail; 103 104 public: 105 LockstepReverseIterator(ArrayRef<BasicBlock *> Blocks) : Blocks(Blocks) { 106 reset(); 107 } 108 109 void reset() { 110 Fail = false; 111 ActiveBlocks.clear(); 112 for (BasicBlock *BB : Blocks) 113 ActiveBlocks.insert(BB); 114 Insts.clear(); 115 for (BasicBlock *BB : Blocks) { 116 if (BB->size() <= 1) { 117 // Block wasn't big enough - only contained a terminator. 118 ActiveBlocks.erase(BB); 119 continue; 120 } 121 Insts.push_back(BB->getTerminator()->getPrevNode()); 122 } 123 if (Insts.empty()) 124 Fail = true; 125 } 126 127 bool isValid() const { return !Fail; } 128 ArrayRef<Instruction *> operator*() const { return Insts; } 129 SmallPtrSet<BasicBlock *, 4> &getActiveBlocks() { return ActiveBlocks; } 130 131 void restrictToBlocks(SmallPtrSetImpl<BasicBlock *> &Blocks) { 132 for (auto II = Insts.begin(); II != Insts.end();) { 133 if (std::find(Blocks.begin(), Blocks.end(), (*II)->getParent()) == 134 Blocks.end()) { 135 ActiveBlocks.erase((*II)->getParent()); 136 II = Insts.erase(II); 137 } else { 138 ++II; 139 } 140 } 141 } 142 143 void operator--() { 144 if (Fail) 145 return; 146 SmallVector<Instruction *, 4> NewInsts; 147 for (auto *Inst : Insts) { 148 if (Inst == &Inst->getParent()->front()) 149 ActiveBlocks.erase(Inst->getParent()); 150 else 151 NewInsts.push_back(Inst->getPrevNode()); 152 } 153 if (NewInsts.empty()) { 154 Fail = true; 155 return; 156 } 157 Insts = NewInsts; 158 } 159 }; 160 161 //===----------------------------------------------------------------------===// 162 163 /// Candidate solution for sinking. There may be different ways to 164 /// sink instructions, differing in the number of instructions sunk, 165 /// the number of predecessors sunk from and the number of PHIs 166 /// required. 167 struct SinkingInstructionCandidate { 168 unsigned NumBlocks; 169 unsigned NumInstructions; 170 unsigned NumPHIs; 171 unsigned NumMemoryInsts; 172 int Cost = -1; 173 SmallVector<BasicBlock *, 4> Blocks; 174 175 void calculateCost(unsigned NumOrigPHIs, unsigned NumOrigBlocks) { 176 unsigned NumExtraPHIs = NumPHIs - NumOrigPHIs; 177 unsigned SplitEdgeCost = (NumOrigBlocks > NumBlocks) ? 2 : 0; 178 Cost = (NumInstructions * (NumBlocks - 1)) - 179 (NumExtraPHIs * 180 NumExtraPHIs) // PHIs are expensive, so make sure they're worth it. 181 - SplitEdgeCost; 182 } 183 bool operator>(const SinkingInstructionCandidate &Other) const { 184 return Cost > Other.Cost; 185 } 186 }; 187 188 #ifndef NDEBUG 189 llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, 190 const SinkingInstructionCandidate &C) { 191 OS << "<Candidate Cost=" << C.Cost << " #Blocks=" << C.NumBlocks 192 << " #Insts=" << C.NumInstructions << " #PHIs=" << C.NumPHIs << ">"; 193 return OS; 194 } 195 #endif 196 197 //===----------------------------------------------------------------------===// 198 199 /// Describes a PHI node that may or may not exist. These track the PHIs 200 /// that must be created if we sunk a sequence of instructions. It provides 201 /// a hash function for efficient equality comparisons. 202 class ModelledPHI { 203 SmallVector<Value *, 4> Values; 204 SmallVector<BasicBlock *, 4> Blocks; 205 206 public: 207 ModelledPHI() {} 208 ModelledPHI(const PHINode *PN) { 209 for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) 210 Blocks.push_back(PN->getIncomingBlock(I)); 211 std::sort(Blocks.begin(), Blocks.end()); 212 213 // This assumes the PHI is already well-formed and there aren't conflicting 214 // incoming values for the same block. 215 for (auto *B : Blocks) 216 Values.push_back(PN->getIncomingValueForBlock(B)); 217 } 218 /// Create a dummy ModelledPHI that will compare unequal to any other ModelledPHI 219 /// without the same ID. 220 /// \note This is specifically for DenseMapInfo - do not use this! 221 static ModelledPHI createDummy(size_t ID) { 222 ModelledPHI M; 223 M.Values.push_back(reinterpret_cast<Value*>(ID)); 224 return M; 225 } 226 227 /// Create a PHI from an array of incoming values and incoming blocks. 228 template <typename VArray, typename BArray> 229 ModelledPHI(const VArray &V, const BArray &B) { 230 std::copy(V.begin(), V.end(), std::back_inserter(Values)); 231 std::copy(B.begin(), B.end(), std::back_inserter(Blocks)); 232 std::sort(Blocks.begin(), Blocks.end()); 233 } 234 235 /// Create a PHI from [I[OpNum] for I in Insts]. 236 template <typename BArray> 237 ModelledPHI(ArrayRef<Instruction *> Insts, unsigned OpNum, const BArray &B) { 238 std::copy(B.begin(), B.end(), std::back_inserter(Blocks)); 239 std::sort(Blocks.begin(), Blocks.end()); 240 for (auto *I : Insts) 241 Values.push_back(I->getOperand(OpNum)); 242 } 243 244 /// Restrict the PHI's contents down to only \c NewBlocks. 245 /// \c NewBlocks must be a subset of \c this->Blocks. 246 void restrictToBlocks(const SmallPtrSetImpl<BasicBlock *> &NewBlocks) { 247 auto BI = Blocks.begin(); 248 auto VI = Values.begin(); 249 while (BI != Blocks.end()) { 250 assert(VI != Values.end()); 251 if (std::find(NewBlocks.begin(), NewBlocks.end(), *BI) == 252 NewBlocks.end()) { 253 BI = Blocks.erase(BI); 254 VI = Values.erase(VI); 255 } else { 256 ++BI; 257 ++VI; 258 } 259 } 260 assert(Blocks.size() == NewBlocks.size()); 261 } 262 263 ArrayRef<Value *> getValues() const { return Values; } 264 265 bool areAllIncomingValuesSame() const { 266 return all_of(Values, [&](Value *V) { return V == Values[0]; }); 267 } 268 bool areAllIncomingValuesSameType() const { 269 return all_of( 270 Values, [&](Value *V) { return V->getType() == Values[0]->getType(); }); 271 } 272 bool areAnyIncomingValuesConstant() const { 273 return any_of(Values, [&](Value *V) { return isa<Constant>(V); }); 274 } 275 // Hash functor 276 unsigned hash() const { 277 return (unsigned)hash_combine_range(Values.begin(), Values.end()); 278 } 279 bool operator==(const ModelledPHI &Other) const { 280 return Values == Other.Values && Blocks == Other.Blocks; 281 } 282 }; 283 284 template <typename ModelledPHI> struct DenseMapInfo { 285 static inline ModelledPHI &getEmptyKey() { 286 static ModelledPHI Dummy = ModelledPHI::createDummy(0); 287 return Dummy; 288 } 289 static inline ModelledPHI &getTombstoneKey() { 290 static ModelledPHI Dummy = ModelledPHI::createDummy(1); 291 return Dummy; 292 } 293 static unsigned getHashValue(const ModelledPHI &V) { return V.hash(); } 294 static bool isEqual(const ModelledPHI &LHS, const ModelledPHI &RHS) { 295 return LHS == RHS; 296 } 297 }; 298 299 typedef DenseSet<ModelledPHI, DenseMapInfo<ModelledPHI>> ModelledPHISet; 300 301 //===----------------------------------------------------------------------===// 302 // ValueTable 303 //===----------------------------------------------------------------------===// 304 // This is a value number table where the value number is a function of the 305 // *uses* of a value, rather than its operands. Thus, if VN(A) == VN(B) we know 306 // that the program would be equivalent if we replaced A with PHI(A, B). 307 //===----------------------------------------------------------------------===// 308 309 /// A GVN expression describing how an instruction is used. The operands 310 /// field of BasicExpression is used to store uses, not operands. 311 /// 312 /// This class also contains fields for discriminators used when determining 313 /// equivalence of instructions with sideeffects. 314 class InstructionUseExpr : public GVNExpression::BasicExpression { 315 unsigned MemoryUseOrder = -1; 316 bool Volatile = false; 317 318 public: 319 InstructionUseExpr(Instruction *I, ArrayRecycler<Value *> &R, 320 BumpPtrAllocator &A) 321 : GVNExpression::BasicExpression(I->getNumUses()) { 322 allocateOperands(R, A); 323 setOpcode(I->getOpcode()); 324 setType(I->getType()); 325 326 for (auto &U : I->uses()) 327 op_push_back(U.getUser()); 328 std::sort(op_begin(), op_end()); 329 } 330 void setMemoryUseOrder(unsigned MUO) { MemoryUseOrder = MUO; } 331 void setVolatile(bool V) { Volatile = V; } 332 333 virtual hash_code getHashValue() const { 334 return hash_combine(GVNExpression::BasicExpression::getHashValue(), 335 MemoryUseOrder, Volatile); 336 } 337 338 template <typename Function> hash_code getHashValue(Function MapFn) { 339 hash_code H = 340 hash_combine(getOpcode(), getType(), MemoryUseOrder, Volatile); 341 for (auto *V : operands()) 342 H = hash_combine(H, MapFn(V)); 343 return H; 344 } 345 }; 346 347 class ValueTable { 348 DenseMap<Value *, uint32_t> ValueNumbering; 349 DenseMap<GVNExpression::Expression *, uint32_t> ExpressionNumbering; 350 DenseMap<size_t, uint32_t> HashNumbering; 351 BumpPtrAllocator Allocator; 352 ArrayRecycler<Value *> Recycler; 353 uint32_t nextValueNumber; 354 355 /// Create an expression for I based on its opcode and its uses. If I 356 /// touches or reads memory, the expression is also based upon its memory 357 /// order - see \c getMemoryUseOrder(). 358 InstructionUseExpr *createExpr(Instruction *I) { 359 InstructionUseExpr *E = 360 new (Allocator) InstructionUseExpr(I, Recycler, Allocator); 361 if (isMemoryInst(I)) 362 E->setMemoryUseOrder(getMemoryUseOrder(I)); 363 364 if (CmpInst *C = dyn_cast<CmpInst>(I)) { 365 CmpInst::Predicate Predicate = C->getPredicate(); 366 E->setOpcode((C->getOpcode() << 8) | Predicate); 367 } 368 return E; 369 } 370 371 /// Helper to compute the value number for a memory instruction 372 /// (LoadInst/StoreInst), including checking the memory ordering and 373 /// volatility. 374 template <class Inst> InstructionUseExpr *createMemoryExpr(Inst *I) { 375 if (isStrongerThanUnordered(I->getOrdering()) || I->isAtomic()) 376 return nullptr; 377 InstructionUseExpr *E = createExpr(I); 378 E->setVolatile(I->isVolatile()); 379 return E; 380 } 381 382 public: 383 /// Returns the value number for the specified value, assigning 384 /// it a new number if it did not have one before. 385 uint32_t lookupOrAdd(Value *V) { 386 auto VI = ValueNumbering.find(V); 387 if (VI != ValueNumbering.end()) 388 return VI->second; 389 390 if (!isa<Instruction>(V)) { 391 ValueNumbering[V] = nextValueNumber; 392 return nextValueNumber++; 393 } 394 395 Instruction *I = cast<Instruction>(V); 396 InstructionUseExpr *exp = nullptr; 397 switch (I->getOpcode()) { 398 case Instruction::Load: 399 exp = createMemoryExpr(cast<LoadInst>(I)); 400 break; 401 case Instruction::Store: 402 exp = createMemoryExpr(cast<StoreInst>(I)); 403 break; 404 case Instruction::Call: 405 case Instruction::Invoke: 406 case Instruction::Add: 407 case Instruction::FAdd: 408 case Instruction::Sub: 409 case Instruction::FSub: 410 case Instruction::Mul: 411 case Instruction::FMul: 412 case Instruction::UDiv: 413 case Instruction::SDiv: 414 case Instruction::FDiv: 415 case Instruction::URem: 416 case Instruction::SRem: 417 case Instruction::FRem: 418 case Instruction::Shl: 419 case Instruction::LShr: 420 case Instruction::AShr: 421 case Instruction::And: 422 case Instruction::Or: 423 case Instruction::Xor: 424 case Instruction::ICmp: 425 case Instruction::FCmp: 426 case Instruction::Trunc: 427 case Instruction::ZExt: 428 case Instruction::SExt: 429 case Instruction::FPToUI: 430 case Instruction::FPToSI: 431 case Instruction::UIToFP: 432 case Instruction::SIToFP: 433 case Instruction::FPTrunc: 434 case Instruction::FPExt: 435 case Instruction::PtrToInt: 436 case Instruction::IntToPtr: 437 case Instruction::BitCast: 438 case Instruction::Select: 439 case Instruction::ExtractElement: 440 case Instruction::InsertElement: 441 case Instruction::ShuffleVector: 442 case Instruction::InsertValue: 443 case Instruction::GetElementPtr: 444 exp = createExpr(I); 445 break; 446 default: 447 break; 448 } 449 450 if (!exp) { 451 ValueNumbering[V] = nextValueNumber; 452 return nextValueNumber++; 453 } 454 455 uint32_t e = ExpressionNumbering[exp]; 456 if (!e) { 457 hash_code H = exp->getHashValue([=](Value *V) { return lookupOrAdd(V); }); 458 auto I = HashNumbering.find(H); 459 if (I != HashNumbering.end()) { 460 e = I->second; 461 } else { 462 e = nextValueNumber++; 463 HashNumbering[H] = e; 464 ExpressionNumbering[exp] = e; 465 } 466 } 467 ValueNumbering[V] = e; 468 return e; 469 } 470 471 /// Returns the value number of the specified value. Fails if the value has 472 /// not yet been numbered. 473 uint32_t lookup(Value *V) const { 474 auto VI = ValueNumbering.find(V); 475 assert(VI != ValueNumbering.end() && "Value not numbered?"); 476 return VI->second; 477 } 478 479 /// Removes all value numberings and resets the value table. 480 void clear() { 481 ValueNumbering.clear(); 482 ExpressionNumbering.clear(); 483 HashNumbering.clear(); 484 Recycler.clear(Allocator); 485 nextValueNumber = 1; 486 } 487 488 ValueTable() : nextValueNumber(1) {} 489 490 /// \c Inst uses or touches memory. Return an ID describing the memory state 491 /// at \c Inst such that if getMemoryUseOrder(I1) == getMemoryUseOrder(I2), 492 /// the exact same memory operations happen after I1 and I2. 493 /// 494 /// This is a very hard problem in general, so we use domain-specific 495 /// knowledge that we only ever check for equivalence between blocks sharing a 496 /// single immediate successor that is common, and when determining if I1 == 497 /// I2 we will have already determined that next(I1) == next(I2). This 498 /// inductive property allows us to simply return the value number of the next 499 /// instruction that defines memory. 500 uint32_t getMemoryUseOrder(Instruction *Inst) { 501 auto *BB = Inst->getParent(); 502 for (auto I = std::next(Inst->getIterator()), E = BB->end(); 503 I != E && !I->isTerminator(); ++I) { 504 if (!isMemoryInst(&*I)) 505 continue; 506 if (isa<LoadInst>(&*I)) 507 continue; 508 CallInst *CI = dyn_cast<CallInst>(&*I); 509 if (CI && CI->onlyReadsMemory()) 510 continue; 511 InvokeInst *II = dyn_cast<InvokeInst>(&*I); 512 if (II && II->onlyReadsMemory()) 513 continue; 514 return lookupOrAdd(&*I); 515 } 516 return 0; 517 } 518 }; 519 520 //===----------------------------------------------------------------------===// 521 522 class GVNSink { 523 public: 524 GVNSink() : VN() {} 525 bool run(Function &F) { 526 DEBUG(dbgs() << "GVNSink: running on function @" << F.getName() << "\n"); 527 528 unsigned NumSunk = 0; 529 ReversePostOrderTraversal<Function*> RPOT(&F); 530 for (auto *N : RPOT) 531 NumSunk += sinkBB(N); 532 533 return NumSunk > 0; 534 } 535 536 private: 537 ValueTable VN; 538 539 bool isInstructionBlacklisted(Instruction *I) { 540 // These instructions may change or break semantics if moved. 541 if (isa<PHINode>(I) || I->isEHPad() || isa<AllocaInst>(I) || 542 I->getType()->isTokenTy()) 543 return true; 544 return false; 545 } 546 547 /// The main heuristic function. Analyze the set of instructions pointed to by 548 /// LRI and return a candidate solution if these instructions can be sunk, or 549 /// None otherwise. 550 Optional<SinkingInstructionCandidate> analyzeInstructionForSinking( 551 LockstepReverseIterator &LRI, unsigned &InstNum, unsigned &MemoryInstNum, 552 ModelledPHISet &NeededPHIs, SmallPtrSetImpl<Value *> &PHIContents); 553 554 /// Create a ModelledPHI for each PHI in BB, adding to PHIs. 555 void analyzeInitialPHIs(BasicBlock *BB, ModelledPHISet &PHIs, 556 SmallPtrSetImpl<Value *> &PHIContents) { 557 for (auto &I : *BB) { 558 auto *PN = dyn_cast<PHINode>(&I); 559 if (!PN) 560 return; 561 562 auto MPHI = ModelledPHI(PN); 563 PHIs.insert(MPHI); 564 for (auto *V : MPHI.getValues()) 565 PHIContents.insert(V); 566 } 567 } 568 569 /// The main instruction sinking driver. Set up state and try and sink 570 /// instructions into BBEnd from its predecessors. 571 unsigned sinkBB(BasicBlock *BBEnd); 572 573 /// Perform the actual mechanics of sinking an instruction from Blocks into 574 /// BBEnd, which is their only successor. 575 void sinkLastInstruction(ArrayRef<BasicBlock *> Blocks, BasicBlock *BBEnd); 576 577 /// Remove PHIs that all have the same incoming value. 578 void foldPointlessPHINodes(BasicBlock *BB) { 579 auto I = BB->begin(); 580 while (PHINode *PN = dyn_cast<PHINode>(I++)) { 581 if (!all_of(PN->incoming_values(), 582 [&](const Value *V) { return V == PN->getIncomingValue(0); })) 583 continue; 584 if (PN->getIncomingValue(0) != PN) 585 PN->replaceAllUsesWith(PN->getIncomingValue(0)); 586 else 587 PN->replaceAllUsesWith(UndefValue::get(PN->getType())); 588 PN->eraseFromParent(); 589 } 590 } 591 }; 592 593 Optional<SinkingInstructionCandidate> GVNSink::analyzeInstructionForSinking( 594 LockstepReverseIterator &LRI, unsigned &InstNum, unsigned &MemoryInstNum, 595 ModelledPHISet &NeededPHIs, SmallPtrSetImpl<Value *> &PHIContents) { 596 auto Insts = *LRI; 597 DEBUG(dbgs() << " -- Analyzing instruction set: [\n"; for (auto *I 598 : Insts) { 599 I->dump(); 600 } dbgs() << " ]\n";); 601 602 DenseMap<uint32_t, unsigned> VNums; 603 for (auto *I : Insts) { 604 uint32_t N = VN.lookupOrAdd(I); 605 DEBUG(dbgs() << " VN=" << utohexstr(N) << " for" << *I << "\n"); 606 if (N == ~0U) 607 return None; 608 VNums[N]++; 609 } 610 unsigned VNumToSink = 611 std::max_element(VNums.begin(), VNums.end(), 612 [](const std::pair<uint32_t, unsigned> &I, 613 const std::pair<uint32_t, unsigned> &J) { 614 return I.second < J.second; 615 }) 616 ->first; 617 618 if (VNums[VNumToSink] == 1) 619 // Can't sink anything! 620 return None; 621 622 // Now restrict the number of incoming blocks down to only those with 623 // VNumToSink. 624 auto &ActivePreds = LRI.getActiveBlocks(); 625 unsigned InitialActivePredSize = ActivePreds.size(); 626 SmallVector<Instruction *, 4> NewInsts; 627 for (auto *I : Insts) { 628 if (VN.lookup(I) != VNumToSink) 629 ActivePreds.erase(I->getParent()); 630 else 631 NewInsts.push_back(I); 632 } 633 for (auto *I : NewInsts) 634 if (isInstructionBlacklisted(I)) 635 return None; 636 637 // If we've restricted the incoming blocks, restrict all needed PHIs also 638 // to that set. 639 bool RecomputePHIContents = false; 640 if (ActivePreds.size() != InitialActivePredSize) { 641 ModelledPHISet NewNeededPHIs; 642 for (auto P : NeededPHIs) { 643 P.restrictToBlocks(ActivePreds); 644 NewNeededPHIs.insert(P); 645 } 646 NeededPHIs = NewNeededPHIs; 647 LRI.restrictToBlocks(ActivePreds); 648 RecomputePHIContents = true; 649 } 650 651 // The sunk instruction's results. 652 ModelledPHI NewPHI(NewInsts, ActivePreds); 653 654 // Does sinking this instruction render previous PHIs redundant? 655 if (NeededPHIs.find(NewPHI) != NeededPHIs.end()) { 656 NeededPHIs.erase(NewPHI); 657 RecomputePHIContents = true; 658 } 659 660 if (RecomputePHIContents) { 661 // The needed PHIs have changed, so recompute the set of all needed 662 // values. 663 PHIContents.clear(); 664 for (auto &PHI : NeededPHIs) 665 PHIContents.insert(PHI.getValues().begin(), PHI.getValues().end()); 666 } 667 668 // Is this instruction required by a later PHI that doesn't match this PHI? 669 // if so, we can't sink this instruction. 670 for (auto *V : NewPHI.getValues()) 671 if (PHIContents.count(V)) 672 // V exists in this PHI, but the whole PHI is different to NewPHI 673 // (else it would have been removed earlier). We cannot continue 674 // because this isn't representable. 675 return None; 676 677 // Which operands need PHIs? 678 // FIXME: If any of these fail, we should partition up the candidates to 679 // try and continue making progress. 680 Instruction *I0 = NewInsts[0]; 681 for (unsigned OpNum = 0, E = I0->getNumOperands(); OpNum != E; ++OpNum) { 682 ModelledPHI PHI(NewInsts, OpNum, ActivePreds); 683 if (PHI.areAllIncomingValuesSame()) 684 continue; 685 if (!canReplaceOperandWithVariable(I0, OpNum)) 686 // We can 't create a PHI from this instruction! 687 return None; 688 if (NeededPHIs.count(PHI)) 689 continue; 690 if (!PHI.areAllIncomingValuesSameType()) 691 return None; 692 // Don't create indirect calls! The called value is the final operand. 693 if ((isa<CallInst>(I0) || isa<InvokeInst>(I0)) && OpNum == E - 1 && 694 PHI.areAnyIncomingValuesConstant()) 695 return None; 696 697 NeededPHIs.reserve(NeededPHIs.size()); 698 NeededPHIs.insert(PHI); 699 PHIContents.insert(PHI.getValues().begin(), PHI.getValues().end()); 700 } 701 702 if (isMemoryInst(NewInsts[0])) 703 ++MemoryInstNum; 704 705 SinkingInstructionCandidate Cand; 706 Cand.NumInstructions = ++InstNum; 707 Cand.NumMemoryInsts = MemoryInstNum; 708 Cand.NumBlocks = ActivePreds.size(); 709 Cand.NumPHIs = NeededPHIs.size(); 710 for (auto *C : ActivePreds) 711 Cand.Blocks.push_back(C); 712 713 return Cand; 714 } 715 716 unsigned GVNSink::sinkBB(BasicBlock *BBEnd) { 717 DEBUG(dbgs() << "GVNSink: running on basic block "; 718 BBEnd->printAsOperand(dbgs()); dbgs() << "\n"); 719 SmallVector<BasicBlock *, 4> Preds; 720 for (auto *B : predecessors(BBEnd)) { 721 auto *T = B->getTerminator(); 722 if (isa<BranchInst>(T) || isa<SwitchInst>(T)) 723 Preds.push_back(B); 724 else 725 return 0; 726 } 727 if (Preds.size() < 2) 728 return 0; 729 std::sort(Preds.begin(), Preds.end()); 730 731 unsigned NumOrigPreds = Preds.size(); 732 // We can only sink instructions through unconditional branches. 733 for (auto I = Preds.begin(); I != Preds.end();) { 734 if ((*I)->getTerminator()->getNumSuccessors() != 1) 735 I = Preds.erase(I); 736 else 737 ++I; 738 } 739 740 LockstepReverseIterator LRI(Preds); 741 SmallVector<SinkingInstructionCandidate, 4> Candidates; 742 unsigned InstNum = 0, MemoryInstNum = 0; 743 ModelledPHISet NeededPHIs; 744 SmallPtrSet<Value *, 4> PHIContents; 745 analyzeInitialPHIs(BBEnd, NeededPHIs, PHIContents); 746 unsigned NumOrigPHIs = NeededPHIs.size(); 747 748 while (LRI.isValid()) { 749 auto Cand = analyzeInstructionForSinking(LRI, InstNum, MemoryInstNum, 750 NeededPHIs, PHIContents); 751 if (!Cand) 752 break; 753 Cand->calculateCost(NumOrigPHIs, Preds.size()); 754 Candidates.emplace_back(*Cand); 755 --LRI; 756 } 757 758 std::stable_sort( 759 Candidates.begin(), Candidates.end(), 760 [](const SinkingInstructionCandidate &A, 761 const SinkingInstructionCandidate &B) { return A > B; }); 762 DEBUG(dbgs() << " -- Sinking candidates:\n"; for (auto &C 763 : Candidates) dbgs() 764 << " " << C << "\n";); 765 766 // Pick the top candidate, as long it is positive! 767 if (Candidates.empty() || Candidates.front().Cost <= 0) 768 return 0; 769 auto C = Candidates.front(); 770 771 DEBUG(dbgs() << " -- Sinking: " << C << "\n"); 772 BasicBlock *InsertBB = BBEnd; 773 if (C.Blocks.size() < NumOrigPreds) { 774 DEBUG(dbgs() << " -- Splitting edge to "; BBEnd->printAsOperand(dbgs()); 775 dbgs() << "\n"); 776 InsertBB = SplitBlockPredecessors(BBEnd, C.Blocks, ".gvnsink.split"); 777 if (!InsertBB) { 778 DEBUG(dbgs() << " -- FAILED to split edge!\n"); 779 // Edge couldn't be split. 780 return 0; 781 } 782 } 783 784 for (unsigned I = 0; I < C.NumInstructions; ++I) 785 sinkLastInstruction(C.Blocks, InsertBB); 786 787 return C.NumInstructions; 788 } 789 790 void GVNSink::sinkLastInstruction(ArrayRef<BasicBlock *> Blocks, 791 BasicBlock *BBEnd) { 792 SmallVector<Instruction *, 4> Insts; 793 for (BasicBlock *BB : Blocks) 794 Insts.push_back(BB->getTerminator()->getPrevNode()); 795 Instruction *I0 = Insts.front(); 796 797 SmallVector<Value *, 4> NewOperands; 798 for (unsigned O = 0, E = I0->getNumOperands(); O != E; ++O) { 799 bool NeedPHI = any_of(Insts, [&I0, O](const Instruction *I) { 800 return I->getOperand(O) != I0->getOperand(O); 801 }); 802 if (!NeedPHI) { 803 NewOperands.push_back(I0->getOperand(O)); 804 continue; 805 } 806 807 // Create a new PHI in the successor block and populate it. 808 auto *Op = I0->getOperand(O); 809 assert(!Op->getType()->isTokenTy() && "Can't PHI tokens!"); 810 auto *PN = PHINode::Create(Op->getType(), Insts.size(), 811 Op->getName() + ".sink", &BBEnd->front()); 812 for (auto *I : Insts) 813 PN->addIncoming(I->getOperand(O), I->getParent()); 814 NewOperands.push_back(PN); 815 } 816 817 // Arbitrarily use I0 as the new "common" instruction; remap its operands 818 // and move it to the start of the successor block. 819 for (unsigned O = 0, E = I0->getNumOperands(); O != E; ++O) 820 I0->getOperandUse(O).set(NewOperands[O]); 821 I0->moveBefore(&*BBEnd->getFirstInsertionPt()); 822 823 // Update metadata and IR flags. 824 for (auto *I : Insts) 825 if (I != I0) { 826 combineMetadataForCSE(I0, I); 827 I0->andIRFlags(I); 828 } 829 830 for (auto *I : Insts) 831 if (I != I0) 832 I->replaceAllUsesWith(I0); 833 foldPointlessPHINodes(BBEnd); 834 835 // Finally nuke all instructions apart from the common instruction. 836 for (auto *I : Insts) 837 if (I != I0) 838 I->eraseFromParent(); 839 840 NumRemoved += Insts.size() - 1; 841 } 842 843 //////////////////////////////////////////////////////////////////////////////// 844 // Pass machinery / boilerplate 845 846 class GVNSinkLegacyPass : public FunctionPass { 847 public: 848 static char ID; 849 850 GVNSinkLegacyPass() : FunctionPass(ID) { 851 initializeGVNSinkLegacyPassPass(*PassRegistry::getPassRegistry()); 852 } 853 854 bool runOnFunction(Function &F) override { 855 if (skipFunction(F)) 856 return false; 857 GVNSink G; 858 return G.run(F); 859 } 860 861 void getAnalysisUsage(AnalysisUsage &AU) const override { 862 AU.addPreserved<GlobalsAAWrapperPass>(); 863 } 864 }; 865 } // namespace 866 867 PreservedAnalyses GVNSinkPass::run(Function &F, FunctionAnalysisManager &AM) { 868 GVNSink G; 869 if (!G.run(F)) 870 return PreservedAnalyses::all(); 871 872 PreservedAnalyses PA; 873 PA.preserve<GlobalsAA>(); 874 return PA; 875 } 876 877 char GVNSinkLegacyPass::ID = 0; 878 INITIALIZE_PASS_BEGIN(GVNSinkLegacyPass, "gvn-sink", 879 "Early GVN sinking of Expressions", false, false) 880 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 881 INITIALIZE_PASS_DEPENDENCY(PostDominatorTreeWrapperPass) 882 INITIALIZE_PASS_END(GVNSinkLegacyPass, "gvn-sink", 883 "Early GVN sinking of Expressions", false, false) 884 885 FunctionPass *llvm::createGVNSinkPass() { return new GVNSinkLegacyPass(); } 886