1 //===- GVNHoist.cpp - Hoist scalar and load expressions -------------------===// 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 hoists expressions from branches to a common dominator. It uses 11 // GVN (global value numbering) to discover expressions computing the same 12 // values. The primary goals of code-hoisting are: 13 // 1. To reduce the code size. 14 // 2. In some cases reduce critical path (by exposing more ILP). 15 // 16 // Hoisting may affect the performance in some cases. To mitigate that, hoisting 17 // is disabled in the following cases. 18 // 1. Scalars across calls. 19 // 2. geps when corresponding load/store cannot be hoisted. 20 //===----------------------------------------------------------------------===// 21 22 #include "llvm/ADT/DenseMap.h" 23 #include "llvm/ADT/SmallPtrSet.h" 24 #include "llvm/ADT/Statistic.h" 25 #include "llvm/Analysis/ValueTracking.h" 26 #include "llvm/Transforms/Scalar.h" 27 #include "llvm/Transforms/Scalar/GVN.h" 28 #include "llvm/Transforms/Utils/Local.h" 29 #include "llvm/Transforms/Utils/MemorySSA.h" 30 31 using namespace llvm; 32 33 #define DEBUG_TYPE "gvn-hoist" 34 35 STATISTIC(NumHoisted, "Number of instructions hoisted"); 36 STATISTIC(NumRemoved, "Number of instructions removed"); 37 STATISTIC(NumLoadsHoisted, "Number of loads hoisted"); 38 STATISTIC(NumLoadsRemoved, "Number of loads removed"); 39 STATISTIC(NumStoresHoisted, "Number of stores hoisted"); 40 STATISTIC(NumStoresRemoved, "Number of stores removed"); 41 STATISTIC(NumCallsHoisted, "Number of calls hoisted"); 42 STATISTIC(NumCallsRemoved, "Number of calls removed"); 43 44 static cl::opt<int> 45 MaxHoistedThreshold("gvn-max-hoisted", cl::Hidden, cl::init(-1), 46 cl::desc("Max number of instructions to hoist " 47 "(default unlimited = -1)")); 48 static cl::opt<int> MaxNumberOfBBSInPath( 49 "gvn-hoist-max-bbs", cl::Hidden, cl::init(4), 50 cl::desc("Max number of basic blocks on the path between " 51 "hoisting locations (default = 4, unlimited = -1)")); 52 53 static cl::opt<int> MaxDepthInBB( 54 "gvn-hoist-max-depth", cl::Hidden, cl::init(100), 55 cl::desc("Hoist instructions from the beginning of the BB up to the " 56 "maximum specified depth (default = 100, unlimited = -1)")); 57 58 static cl::opt<int> MaxChainLength( 59 "gvn-hoist-max-chain-length", cl::Hidden, cl::init(10), 60 cl::desc("Maximum length of dependent chains to hoist " 61 "(default = 10, unlimited = -1)")); 62 63 namespace { 64 65 // Provides a sorting function based on the execution order of two instructions. 66 struct SortByDFSIn { 67 private: 68 DenseMap<const Value *, unsigned> &DFSNumber; 69 70 public: 71 SortByDFSIn(DenseMap<const Value *, unsigned> &D) : DFSNumber(D) {} 72 73 // Returns true when A executes before B. 74 bool operator()(const Instruction *A, const Instruction *B) const { 75 // FIXME: libc++ has a std::sort() algorithm that will call the compare 76 // function on the same element. Once PR20837 is fixed and some more years 77 // pass by and all the buildbots have moved to a corrected std::sort(), 78 // enable the following assert: 79 // 80 // assert(A != B); 81 82 const BasicBlock *BA = A->getParent(); 83 const BasicBlock *BB = B->getParent(); 84 unsigned ADFS, BDFS; 85 if (BA == BB) { 86 ADFS = DFSNumber.lookup(A); 87 BDFS = DFSNumber.lookup(B); 88 } else { 89 ADFS = DFSNumber.lookup(BA); 90 BDFS = DFSNumber.lookup(BB); 91 } 92 assert (ADFS && BDFS); 93 return ADFS < BDFS; 94 } 95 }; 96 97 // A map from a pair of VNs to all the instructions with those VNs. 98 typedef DenseMap<std::pair<unsigned, unsigned>, SmallVector<Instruction *, 4>> 99 VNtoInsns; 100 // An invalid value number Used when inserting a single value number into 101 // VNtoInsns. 102 enum : unsigned { InvalidVN = ~2U }; 103 104 // Records all scalar instructions candidate for code hoisting. 105 class InsnInfo { 106 VNtoInsns VNtoScalars; 107 108 public: 109 // Inserts I and its value number in VNtoScalars. 110 void insert(Instruction *I, GVN::ValueTable &VN) { 111 // Scalar instruction. 112 unsigned V = VN.lookupOrAdd(I); 113 VNtoScalars[{V, InvalidVN}].push_back(I); 114 } 115 116 const VNtoInsns &getVNTable() const { return VNtoScalars; } 117 }; 118 119 // Records all load instructions candidate for code hoisting. 120 class LoadInfo { 121 VNtoInsns VNtoLoads; 122 123 public: 124 // Insert Load and the value number of its memory address in VNtoLoads. 125 void insert(LoadInst *Load, GVN::ValueTable &VN) { 126 if (Load->isSimple()) { 127 unsigned V = VN.lookupOrAdd(Load->getPointerOperand()); 128 VNtoLoads[{V, InvalidVN}].push_back(Load); 129 } 130 } 131 132 const VNtoInsns &getVNTable() const { return VNtoLoads; } 133 }; 134 135 // Records all store instructions candidate for code hoisting. 136 class StoreInfo { 137 VNtoInsns VNtoStores; 138 139 public: 140 // Insert the Store and a hash number of the store address and the stored 141 // value in VNtoStores. 142 void insert(StoreInst *Store, GVN::ValueTable &VN) { 143 if (!Store->isSimple()) 144 return; 145 // Hash the store address and the stored value. 146 Value *Ptr = Store->getPointerOperand(); 147 Value *Val = Store->getValueOperand(); 148 VNtoStores[{VN.lookupOrAdd(Ptr), VN.lookupOrAdd(Val)}].push_back(Store); 149 } 150 151 const VNtoInsns &getVNTable() const { return VNtoStores; } 152 }; 153 154 // Records all call instructions candidate for code hoisting. 155 class CallInfo { 156 VNtoInsns VNtoCallsScalars; 157 VNtoInsns VNtoCallsLoads; 158 VNtoInsns VNtoCallsStores; 159 160 public: 161 // Insert Call and its value numbering in one of the VNtoCalls* containers. 162 void insert(CallInst *Call, GVN::ValueTable &VN) { 163 // A call that doesNotAccessMemory is handled as a Scalar, 164 // onlyReadsMemory will be handled as a Load instruction, 165 // all other calls will be handled as stores. 166 unsigned V = VN.lookupOrAdd(Call); 167 auto Entry = std::make_pair(V, InvalidVN); 168 169 if (Call->doesNotAccessMemory()) 170 VNtoCallsScalars[Entry].push_back(Call); 171 else if (Call->onlyReadsMemory()) 172 VNtoCallsLoads[Entry].push_back(Call); 173 else 174 VNtoCallsStores[Entry].push_back(Call); 175 } 176 177 const VNtoInsns &getScalarVNTable() const { return VNtoCallsScalars; } 178 179 const VNtoInsns &getLoadVNTable() const { return VNtoCallsLoads; } 180 181 const VNtoInsns &getStoreVNTable() const { return VNtoCallsStores; } 182 }; 183 184 typedef DenseMap<const BasicBlock *, bool> BBSideEffectsSet; 185 typedef SmallVector<Instruction *, 4> SmallVecInsn; 186 typedef SmallVectorImpl<Instruction *> SmallVecImplInsn; 187 188 static void combineKnownMetadata(Instruction *ReplInst, Instruction *I) { 189 static const unsigned KnownIDs[] = { 190 LLVMContext::MD_tbaa, LLVMContext::MD_alias_scope, 191 LLVMContext::MD_noalias, LLVMContext::MD_range, 192 LLVMContext::MD_fpmath, LLVMContext::MD_invariant_load, 193 LLVMContext::MD_invariant_group}; 194 combineMetadata(ReplInst, I, KnownIDs); 195 } 196 197 // This pass hoists common computations across branches sharing common 198 // dominator. The primary goal is to reduce the code size, and in some 199 // cases reduce critical path (by exposing more ILP). 200 class GVNHoist { 201 public: 202 GVNHoist(DominatorTree *DT, AliasAnalysis *AA, MemoryDependenceResults *MD, 203 MemorySSA *MSSA, bool OptForMinSize) 204 : DT(DT), AA(AA), MD(MD), MSSA(MSSA), OptForMinSize(OptForMinSize), 205 HoistingGeps(OptForMinSize), HoistedCtr(0) {} 206 bool run(Function &F) { 207 VN.setDomTree(DT); 208 VN.setAliasAnalysis(AA); 209 VN.setMemDep(MD); 210 bool Res = false; 211 // Perform DFS Numbering of instructions. 212 unsigned BBI = 0; 213 for (const BasicBlock *BB : depth_first(&F.getEntryBlock())) { 214 DFSNumber[BB] = ++BBI; 215 unsigned I = 0; 216 for (auto &Inst: *BB) 217 DFSNumber[&Inst] = ++I; 218 } 219 220 int ChainLength = 0; 221 222 // FIXME: use lazy evaluation of VN to avoid the fix-point computation. 223 while (1) { 224 if (MaxChainLength != -1 && ++ChainLength >= MaxChainLength) 225 return Res; 226 227 auto HoistStat = hoistExpressions(F); 228 if (HoistStat.first + HoistStat.second == 0) 229 return Res; 230 231 if (HoistStat.second > 0) 232 // To address a limitation of the current GVN, we need to rerun the 233 // hoisting after we hoisted loads or stores in order to be able to 234 // hoist all scalars dependent on the hoisted ld/st. 235 VN.clear(); 236 237 Res = true; 238 } 239 240 return Res; 241 } 242 private: 243 GVN::ValueTable VN; 244 DominatorTree *DT; 245 AliasAnalysis *AA; 246 MemoryDependenceResults *MD; 247 MemorySSA *MSSA; 248 const bool OptForMinSize; 249 const bool HoistingGeps; 250 DenseMap<const Value *, unsigned> DFSNumber; 251 BBSideEffectsSet BBSideEffects; 252 int HoistedCtr; 253 254 enum InsKind { Unknown, Scalar, Load, Store }; 255 256 // Return true when there are exception handling in BB. 257 bool hasEH(const BasicBlock *BB) { 258 auto It = BBSideEffects.find(BB); 259 if (It != BBSideEffects.end()) 260 return It->second; 261 262 if (BB->isEHPad() || BB->hasAddressTaken()) { 263 BBSideEffects[BB] = true; 264 return true; 265 } 266 267 if (BB->getTerminator()->mayThrow()) { 268 BBSideEffects[BB] = true; 269 return true; 270 } 271 272 BBSideEffects[BB] = false; 273 return false; 274 } 275 276 // Return true when a successor of BB dominates A. 277 bool successorDominate(const BasicBlock *BB, const BasicBlock *A) { 278 for (const BasicBlock *Succ : BB->getTerminator()->successors()) 279 if (DT->dominates(Succ, A)) 280 return true; 281 282 return false; 283 } 284 285 // Return true when all paths from HoistBB to the end of the function pass 286 // through one of the blocks in WL. 287 bool hoistingFromAllPaths(const BasicBlock *HoistBB, 288 SmallPtrSetImpl<const BasicBlock *> &WL) { 289 290 // Copy WL as the loop will remove elements from it. 291 SmallPtrSet<const BasicBlock *, 2> WorkList(WL.begin(), WL.end()); 292 293 for (auto It = df_begin(HoistBB), E = df_end(HoistBB); It != E;) { 294 // There exists a path from HoistBB to the exit of the function if we are 295 // still iterating in DF traversal and we removed all instructions from 296 // the work list. 297 if (WorkList.empty()) 298 return false; 299 300 const BasicBlock *BB = *It; 301 if (WorkList.erase(BB)) { 302 // Stop DFS traversal when BB is in the work list. 303 It.skipChildren(); 304 continue; 305 } 306 307 // Check for end of function, calls that do not return, etc. 308 if (!isGuaranteedToTransferExecutionToSuccessor(BB->getTerminator())) 309 return false; 310 311 // When reaching the back-edge of a loop, there may be a path through the 312 // loop that does not pass through B or C before exiting the loop. 313 if (successorDominate(BB, HoistBB)) 314 return false; 315 316 // Increment DFS traversal when not skipping children. 317 ++It; 318 } 319 320 return true; 321 } 322 323 /* Return true when I1 appears before I2 in the instructions of BB. */ 324 bool firstInBB(const Instruction *I1, const Instruction *I2) { 325 assert (I1->getParent() == I2->getParent()); 326 unsigned I1DFS = DFSNumber.lookup(I1); 327 unsigned I2DFS = DFSNumber.lookup(I2); 328 assert (I1DFS && I2DFS); 329 return I1DFS < I2DFS; 330 } 331 332 // Return true when there are users of Def in BB. 333 bool hasMemoryUseOnPath(MemoryAccess *Def, const BasicBlock *BB, 334 const Instruction *OldPt) { 335 const BasicBlock *DefBB = Def->getBlock(); 336 const BasicBlock *OldBB = OldPt->getParent(); 337 338 for (User *U : Def->users()) 339 if (auto *MU = dyn_cast<MemoryUse>(U)) { 340 // FIXME: MU->getBlock() does not get updated when we move the instruction. 341 BasicBlock *UBB = MU->getMemoryInst()->getParent(); 342 // Only analyze uses in BB. 343 if (BB != UBB) 344 continue; 345 346 // A use in the same block as the Def is on the path. 347 if (UBB == DefBB) { 348 assert(MSSA->locallyDominates(Def, MU) && "def not dominating use"); 349 return true; 350 } 351 352 if (UBB != OldBB) 353 return true; 354 355 // It is only harmful to hoist when the use is before OldPt. 356 if (firstInBB(MU->getMemoryInst(), OldPt)) 357 return true; 358 } 359 360 return false; 361 } 362 363 // Return true when there are exception handling or loads of memory Def 364 // between OldPt and NewPt. 365 366 // Decrement by 1 NBBsOnAllPaths for each block between HoistPt and BB, and 367 // return true when the counter NBBsOnAllPaths reaces 0, except when it is 368 // initialized to -1 which is unlimited. 369 bool hasEHOrLoadsOnPath(const Instruction *NewPt, const Instruction *OldPt, 370 MemoryAccess *Def, int &NBBsOnAllPaths) { 371 const BasicBlock *NewBB = NewPt->getParent(); 372 const BasicBlock *OldBB = OldPt->getParent(); 373 assert(DT->dominates(NewBB, OldBB) && "invalid path"); 374 assert(DT->dominates(Def->getBlock(), NewBB) && 375 "def does not dominate new hoisting point"); 376 377 // Walk all basic blocks reachable in depth-first iteration on the inverse 378 // CFG from OldBB to NewBB. These blocks are all the blocks that may be 379 // executed between the execution of NewBB and OldBB. Hoisting an expression 380 // from OldBB into NewBB has to be safe on all execution paths. 381 for (auto I = idf_begin(OldBB), E = idf_end(OldBB); I != E;) { 382 if (*I == NewBB) { 383 // Stop traversal when reaching HoistPt. 384 I.skipChildren(); 385 continue; 386 } 387 388 // Impossible to hoist with exceptions on the path. 389 if (hasEH(*I)) 390 return true; 391 392 // Check that we do not move a store past loads. 393 if (hasMemoryUseOnPath(Def, *I, OldPt)) 394 return true; 395 396 // Stop walk once the limit is reached. 397 if (NBBsOnAllPaths == 0) 398 return true; 399 400 // -1 is unlimited number of blocks on all paths. 401 if (NBBsOnAllPaths != -1) 402 --NBBsOnAllPaths; 403 404 ++I; 405 } 406 407 return false; 408 } 409 410 // Return true when there are exception handling between HoistPt and BB. 411 // Decrement by 1 NBBsOnAllPaths for each block between HoistPt and BB, and 412 // return true when the counter NBBsOnAllPaths reaches 0, except when it is 413 // initialized to -1 which is unlimited. 414 bool hasEHOnPath(const BasicBlock *HoistPt, const BasicBlock *BB, 415 int &NBBsOnAllPaths) { 416 assert(DT->dominates(HoistPt, BB) && "Invalid path"); 417 418 // Walk all basic blocks reachable in depth-first iteration on 419 // the inverse CFG from BBInsn to NewHoistPt. These blocks are all the 420 // blocks that may be executed between the execution of NewHoistPt and 421 // BBInsn. Hoisting an expression from BBInsn into NewHoistPt has to be safe 422 // on all execution paths. 423 for (auto I = idf_begin(BB), E = idf_end(BB); I != E;) { 424 if (*I == HoistPt) { 425 // Stop traversal when reaching NewHoistPt. 426 I.skipChildren(); 427 continue; 428 } 429 430 // Impossible to hoist with exceptions on the path. 431 if (hasEH(*I)) 432 return true; 433 434 // Stop walk once the limit is reached. 435 if (NBBsOnAllPaths == 0) 436 return true; 437 438 // -1 is unlimited number of blocks on all paths. 439 if (NBBsOnAllPaths != -1) 440 --NBBsOnAllPaths; 441 442 ++I; 443 } 444 445 return false; 446 } 447 448 // Return true when it is safe to hoist a memory load or store U from OldPt 449 // to NewPt. 450 bool safeToHoistLdSt(const Instruction *NewPt, const Instruction *OldPt, 451 MemoryUseOrDef *U, InsKind K, int &NBBsOnAllPaths) { 452 453 // In place hoisting is safe. 454 if (NewPt == OldPt) 455 return true; 456 457 const BasicBlock *NewBB = NewPt->getParent(); 458 const BasicBlock *OldBB = OldPt->getParent(); 459 const BasicBlock *UBB = U->getBlock(); 460 461 // Check for dependences on the Memory SSA. 462 MemoryAccess *D = U->getDefiningAccess(); 463 BasicBlock *DBB = D->getBlock(); 464 if (DT->properlyDominates(NewBB, DBB)) 465 // Cannot move the load or store to NewBB above its definition in DBB. 466 return false; 467 468 if (NewBB == DBB && !MSSA->isLiveOnEntryDef(D)) 469 if (auto *UD = dyn_cast<MemoryUseOrDef>(D)) 470 if (firstInBB(NewPt, UD->getMemoryInst())) 471 // Cannot move the load or store to NewPt above its definition in D. 472 return false; 473 474 // Check for unsafe hoistings due to side effects. 475 if (K == InsKind::Store) { 476 if (hasEHOrLoadsOnPath(NewPt, OldPt, D, NBBsOnAllPaths)) 477 return false; 478 } else if (hasEHOnPath(NewBB, OldBB, NBBsOnAllPaths)) 479 return false; 480 481 if (UBB == NewBB) { 482 if (DT->properlyDominates(DBB, NewBB)) 483 return true; 484 assert(UBB == DBB); 485 assert(MSSA->locallyDominates(D, U)); 486 } 487 488 // No side effects: it is safe to hoist. 489 return true; 490 } 491 492 // Return true when it is safe to hoist scalar instructions from all blocks in 493 // WL to HoistBB. 494 bool safeToHoistScalar(const BasicBlock *HoistBB, 495 SmallPtrSetImpl<const BasicBlock *> &WL, 496 int &NBBsOnAllPaths) { 497 // Check that the hoisted expression is needed on all paths. Enable scalar 498 // hoisting at -Oz as it is safe to hoist scalars to a place where they are 499 // partially needed. 500 if (!OptForMinSize && !hoistingFromAllPaths(HoistBB, WL)) 501 return false; 502 503 for (const BasicBlock *BB : WL) 504 if (hasEHOnPath(HoistBB, BB, NBBsOnAllPaths)) 505 return false; 506 507 return true; 508 } 509 510 // Each element of a hoisting list contains the basic block where to hoist and 511 // a list of instructions to be hoisted. 512 typedef std::pair<BasicBlock *, SmallVecInsn> HoistingPointInfo; 513 typedef SmallVector<HoistingPointInfo, 4> HoistingPointList; 514 515 // Partition InstructionsToHoist into a set of candidates which can share a 516 // common hoisting point. The partitions are collected in HPL. IsScalar is 517 // true when the instructions in InstructionsToHoist are scalars. IsLoad is 518 // true when the InstructionsToHoist are loads, false when they are stores. 519 void partitionCandidates(SmallVecImplInsn &InstructionsToHoist, 520 HoistingPointList &HPL, InsKind K) { 521 // No need to sort for two instructions. 522 if (InstructionsToHoist.size() > 2) { 523 SortByDFSIn Pred(DFSNumber); 524 std::sort(InstructionsToHoist.begin(), InstructionsToHoist.end(), Pred); 525 } 526 527 int NBBsOnAllPaths = MaxNumberOfBBSInPath; 528 529 SmallVecImplInsn::iterator II = InstructionsToHoist.begin(); 530 SmallVecImplInsn::iterator Start = II; 531 Instruction *HoistPt = *II; 532 BasicBlock *HoistBB = HoistPt->getParent(); 533 MemoryUseOrDef *UD; 534 if (K != InsKind::Scalar) 535 UD = cast<MemoryUseOrDef>(MSSA->getMemoryAccess(HoistPt)); 536 537 for (++II; II != InstructionsToHoist.end(); ++II) { 538 Instruction *Insn = *II; 539 BasicBlock *BB = Insn->getParent(); 540 BasicBlock *NewHoistBB; 541 Instruction *NewHoistPt; 542 543 if (BB == HoistBB) { 544 NewHoistBB = HoistBB; 545 NewHoistPt = firstInBB(Insn, HoistPt) ? Insn : HoistPt; 546 } else { 547 NewHoistBB = DT->findNearestCommonDominator(HoistBB, BB); 548 if (NewHoistBB == BB) 549 NewHoistPt = Insn; 550 else if (NewHoistBB == HoistBB) 551 NewHoistPt = HoistPt; 552 else 553 NewHoistPt = NewHoistBB->getTerminator(); 554 } 555 556 SmallPtrSet<const BasicBlock *, 2> WL; 557 WL.insert(HoistBB); 558 WL.insert(BB); 559 560 if (K == InsKind::Scalar) { 561 if (safeToHoistScalar(NewHoistBB, WL, NBBsOnAllPaths)) { 562 // Extend HoistPt to NewHoistPt. 563 HoistPt = NewHoistPt; 564 HoistBB = NewHoistBB; 565 continue; 566 } 567 } else { 568 // When NewBB already contains an instruction to be hoisted, the 569 // expression is needed on all paths. 570 // Check that the hoisted expression is needed on all paths: it is 571 // unsafe to hoist loads to a place where there may be a path not 572 // loading from the same address: for instance there may be a branch on 573 // which the address of the load may not be initialized. 574 if ((HoistBB == NewHoistBB || BB == NewHoistBB || 575 hoistingFromAllPaths(NewHoistBB, WL)) && 576 // Also check that it is safe to move the load or store from HoistPt 577 // to NewHoistPt, and from Insn to NewHoistPt. 578 safeToHoistLdSt(NewHoistPt, HoistPt, UD, K, NBBsOnAllPaths) && 579 safeToHoistLdSt(NewHoistPt, Insn, 580 cast<MemoryUseOrDef>(MSSA->getMemoryAccess(Insn)), 581 K, NBBsOnAllPaths)) { 582 // Extend HoistPt to NewHoistPt. 583 HoistPt = NewHoistPt; 584 HoistBB = NewHoistBB; 585 continue; 586 } 587 } 588 589 // At this point it is not safe to extend the current hoisting to 590 // NewHoistPt: save the hoisting list so far. 591 if (std::distance(Start, II) > 1) 592 HPL.push_back({HoistBB, SmallVecInsn(Start, II)}); 593 594 // Start over from BB. 595 Start = II; 596 if (K != InsKind::Scalar) 597 UD = cast<MemoryUseOrDef>(MSSA->getMemoryAccess(*Start)); 598 HoistPt = Insn; 599 HoistBB = BB; 600 NBBsOnAllPaths = MaxNumberOfBBSInPath; 601 } 602 603 // Save the last partition. 604 if (std::distance(Start, II) > 1) 605 HPL.push_back({HoistBB, SmallVecInsn(Start, II)}); 606 } 607 608 // Initialize HPL from Map. 609 void computeInsertionPoints(const VNtoInsns &Map, HoistingPointList &HPL, 610 InsKind K) { 611 for (const auto &Entry : Map) { 612 if (MaxHoistedThreshold != -1 && ++HoistedCtr > MaxHoistedThreshold) 613 return; 614 615 const SmallVecInsn &V = Entry.second; 616 if (V.size() < 2) 617 continue; 618 619 // Compute the insertion point and the list of expressions to be hoisted. 620 SmallVecInsn InstructionsToHoist; 621 for (auto I : V) 622 if (!hasEH(I->getParent())) 623 InstructionsToHoist.push_back(I); 624 625 if (!InstructionsToHoist.empty()) 626 partitionCandidates(InstructionsToHoist, HPL, K); 627 } 628 } 629 630 // Return true when all operands of Instr are available at insertion point 631 // HoistPt. When limiting the number of hoisted expressions, one could hoist 632 // a load without hoisting its access function. So before hoisting any 633 // expression, make sure that all its operands are available at insert point. 634 bool allOperandsAvailable(const Instruction *I, 635 const BasicBlock *HoistPt) const { 636 for (const Use &Op : I->operands()) 637 if (const auto *Inst = dyn_cast<Instruction>(&Op)) 638 if (!DT->dominates(Inst->getParent(), HoistPt)) 639 return false; 640 641 return true; 642 } 643 644 // Same as allOperandsAvailable with recursive check for GEP operands. 645 bool allGepOperandsAvailable(const Instruction *I, 646 const BasicBlock *HoistPt) const { 647 for (const Use &Op : I->operands()) 648 if (const auto *Inst = dyn_cast<Instruction>(&Op)) 649 if (!DT->dominates(Inst->getParent(), HoistPt)) { 650 if (const GetElementPtrInst *GepOp = dyn_cast<GetElementPtrInst>(Inst)) { 651 if (!allGepOperandsAvailable(GepOp, HoistPt)) 652 return false; 653 // Gep is available if all operands of GepOp are available. 654 } else { 655 // Gep is not available if it has operands other than GEPs that are 656 // defined in blocks not dominating HoistPt. 657 return false; 658 } 659 } 660 return true; 661 } 662 663 // Make all operands of the GEP available. 664 void makeGepsAvailable(Instruction *Repl, BasicBlock *HoistPt, 665 const SmallVecInsn &InstructionsToHoist, 666 Instruction *Gep) const { 667 assert(allGepOperandsAvailable(Gep, HoistPt) && "GEP operands not available"); 668 669 Instruction *ClonedGep = Gep->clone(); 670 for (unsigned i = 0, e = Gep->getNumOperands(); i != e; ++i) 671 if (Instruction *Op = dyn_cast<Instruction>(Gep->getOperand(i))) { 672 673 // Check whether the operand is already available. 674 if (DT->dominates(Op->getParent(), HoistPt)) 675 continue; 676 677 // As a GEP can refer to other GEPs, recursively make all the operands 678 // of this GEP available at HoistPt. 679 if (GetElementPtrInst *GepOp = dyn_cast<GetElementPtrInst>(Op)) 680 makeGepsAvailable(ClonedGep, HoistPt, InstructionsToHoist, GepOp); 681 } 682 683 // Copy Gep and replace its uses in Repl with ClonedGep. 684 ClonedGep->insertBefore(HoistPt->getTerminator()); 685 686 // Conservatively discard any optimization hints, they may differ on the 687 // other paths. 688 ClonedGep->dropUnknownNonDebugMetadata(); 689 690 // If we have optimization hints which agree with each other along different 691 // paths, preserve them. 692 for (const Instruction *OtherInst : InstructionsToHoist) { 693 const GetElementPtrInst *OtherGep; 694 if (auto *OtherLd = dyn_cast<LoadInst>(OtherInst)) 695 OtherGep = cast<GetElementPtrInst>(OtherLd->getPointerOperand()); 696 else 697 OtherGep = cast<GetElementPtrInst>( 698 cast<StoreInst>(OtherInst)->getPointerOperand()); 699 ClonedGep->andIRFlags(OtherGep); 700 } 701 702 // Replace uses of Gep with ClonedGep in Repl. 703 Repl->replaceUsesOfWith(Gep, ClonedGep); 704 } 705 706 // In the case Repl is a load or a store, we make all their GEPs 707 // available: GEPs are not hoisted by default to avoid the address 708 // computations to be hoisted without the associated load or store. 709 bool makeGepOperandsAvailable(Instruction *Repl, BasicBlock *HoistPt, 710 const SmallVecInsn &InstructionsToHoist) const { 711 // Check whether the GEP of a ld/st can be synthesized at HoistPt. 712 GetElementPtrInst *Gep = nullptr; 713 Instruction *Val = nullptr; 714 if (auto *Ld = dyn_cast<LoadInst>(Repl)) { 715 Gep = dyn_cast<GetElementPtrInst>(Ld->getPointerOperand()); 716 } else if (auto *St = dyn_cast<StoreInst>(Repl)) { 717 Gep = dyn_cast<GetElementPtrInst>(St->getPointerOperand()); 718 Val = dyn_cast<Instruction>(St->getValueOperand()); 719 // Check that the stored value is available. 720 if (Val) { 721 if (isa<GetElementPtrInst>(Val)) { 722 // Check whether we can compute the GEP at HoistPt. 723 if (!allGepOperandsAvailable(Val, HoistPt)) 724 return false; 725 } else if (!DT->dominates(Val->getParent(), HoistPt)) 726 return false; 727 } 728 } 729 730 // Check whether we can compute the Gep at HoistPt. 731 if (!Gep || !allGepOperandsAvailable(Gep, HoistPt)) 732 return false; 733 734 makeGepsAvailable(Repl, HoistPt, InstructionsToHoist, Gep); 735 736 if (Val && isa<GetElementPtrInst>(Val)) 737 makeGepsAvailable(Repl, HoistPt, InstructionsToHoist, Val); 738 739 return true; 740 } 741 742 std::pair<unsigned, unsigned> hoist(HoistingPointList &HPL) { 743 unsigned NI = 0, NL = 0, NS = 0, NC = 0, NR = 0; 744 for (const HoistingPointInfo &HP : HPL) { 745 // Find out whether we already have one of the instructions in HoistPt, 746 // in which case we do not have to move it. 747 BasicBlock *HoistPt = HP.first; 748 const SmallVecInsn &InstructionsToHoist = HP.second; 749 Instruction *Repl = nullptr; 750 for (Instruction *I : InstructionsToHoist) 751 if (I->getParent() == HoistPt) 752 // If there are two instructions in HoistPt to be hoisted in place: 753 // update Repl to be the first one, such that we can rename the uses 754 // of the second based on the first. 755 if (!Repl || firstInBB(I, Repl)) 756 Repl = I; 757 758 // Keep track of whether we moved the instruction so we know whether we 759 // should move the MemoryAccess. 760 bool MoveAccess = true; 761 if (Repl) { 762 // Repl is already in HoistPt: it remains in place. 763 assert(allOperandsAvailable(Repl, HoistPt) && 764 "instruction depends on operands that are not available"); 765 MoveAccess = false; 766 } else { 767 // When we do not find Repl in HoistPt, select the first in the list 768 // and move it to HoistPt. 769 Repl = InstructionsToHoist.front(); 770 771 // We can move Repl in HoistPt only when all operands are available. 772 // The order in which hoistings are done may influence the availability 773 // of operands. 774 if (!allOperandsAvailable(Repl, HoistPt)) { 775 776 // When HoistingGeps there is nothing more we can do to make the 777 // operands available: just continue. 778 if (HoistingGeps) 779 continue; 780 781 // When not HoistingGeps we need to copy the GEPs. 782 if (!makeGepOperandsAvailable(Repl, HoistPt, InstructionsToHoist)) 783 continue; 784 } 785 786 // Move the instruction at the end of HoistPt. 787 Instruction *Last = HoistPt->getTerminator(); 788 Repl->moveBefore(Last); 789 790 DFSNumber[Repl] = DFSNumber[Last]++; 791 } 792 793 MemoryAccess *NewMemAcc = MSSA->getMemoryAccess(Repl); 794 795 if (MoveAccess) { 796 if (MemoryUseOrDef *OldMemAcc = 797 dyn_cast_or_null<MemoryUseOrDef>(NewMemAcc)) { 798 // The definition of this ld/st will not change: ld/st hoisting is 799 // legal when the ld/st is not moved past its current definition. 800 MemoryAccess *Def = OldMemAcc->getDefiningAccess(); 801 NewMemAcc = 802 MSSA->createMemoryAccessInBB(Repl, Def, HoistPt, MemorySSA::End); 803 OldMemAcc->replaceAllUsesWith(NewMemAcc); 804 MSSA->removeMemoryAccess(OldMemAcc); 805 } 806 } 807 808 if (isa<LoadInst>(Repl)) 809 ++NL; 810 else if (isa<StoreInst>(Repl)) 811 ++NS; 812 else if (isa<CallInst>(Repl)) 813 ++NC; 814 else // Scalar 815 ++NI; 816 817 // Remove and rename all other instructions. 818 for (Instruction *I : InstructionsToHoist) 819 if (I != Repl) { 820 ++NR; 821 if (auto *ReplacementLoad = dyn_cast<LoadInst>(Repl)) { 822 ReplacementLoad->setAlignment( 823 std::min(ReplacementLoad->getAlignment(), 824 cast<LoadInst>(I)->getAlignment())); 825 ++NumLoadsRemoved; 826 } else if (auto *ReplacementStore = dyn_cast<StoreInst>(Repl)) { 827 ReplacementStore->setAlignment( 828 std::min(ReplacementStore->getAlignment(), 829 cast<StoreInst>(I)->getAlignment())); 830 ++NumStoresRemoved; 831 } else if (auto *ReplacementAlloca = dyn_cast<AllocaInst>(Repl)) { 832 ReplacementAlloca->setAlignment( 833 std::max(ReplacementAlloca->getAlignment(), 834 cast<AllocaInst>(I)->getAlignment())); 835 } else if (isa<CallInst>(Repl)) { 836 ++NumCallsRemoved; 837 } 838 839 if (NewMemAcc) { 840 // Update the uses of the old MSSA access with NewMemAcc. 841 MemoryAccess *OldMA = MSSA->getMemoryAccess(I); 842 OldMA->replaceAllUsesWith(NewMemAcc); 843 MSSA->removeMemoryAccess(OldMA); 844 } 845 846 Repl->andIRFlags(I); 847 combineKnownMetadata(Repl, I); 848 I->replaceAllUsesWith(Repl); 849 // Also invalidate the Alias Analysis cache. 850 MD->removeInstruction(I); 851 I->eraseFromParent(); 852 } 853 854 // Remove MemorySSA phi nodes with the same arguments. 855 if (NewMemAcc) { 856 SmallPtrSet<MemoryPhi *, 4> UsePhis; 857 for (User *U : NewMemAcc->users()) 858 if (MemoryPhi *Phi = dyn_cast<MemoryPhi>(U)) 859 UsePhis.insert(Phi); 860 861 for (auto *Phi : UsePhis) { 862 auto In = Phi->incoming_values(); 863 if (all_of(In, [&](Use &U) { return U == NewMemAcc; })) { 864 Phi->replaceAllUsesWith(NewMemAcc); 865 MSSA->removeMemoryAccess(Phi); 866 } 867 } 868 } 869 } 870 871 NumHoisted += NL + NS + NC + NI; 872 NumRemoved += NR; 873 NumLoadsHoisted += NL; 874 NumStoresHoisted += NS; 875 NumCallsHoisted += NC; 876 return {NI, NL + NC + NS}; 877 } 878 879 // Hoist all expressions. Returns Number of scalars hoisted 880 // and number of non-scalars hoisted. 881 std::pair<unsigned, unsigned> hoistExpressions(Function &F) { 882 InsnInfo II; 883 LoadInfo LI; 884 StoreInfo SI; 885 CallInfo CI; 886 for (BasicBlock *BB : depth_first(&F.getEntryBlock())) { 887 int InstructionNb = 0; 888 for (Instruction &I1 : *BB) { 889 // Only hoist the first instructions in BB up to MaxDepthInBB. Hoisting 890 // deeper may increase the register pressure and compilation time. 891 if (MaxDepthInBB != -1 && InstructionNb++ >= MaxDepthInBB) 892 break; 893 894 // Do not value number terminator instructions. 895 if (isa<TerminatorInst>(&I1)) 896 break; 897 898 if (auto *Load = dyn_cast<LoadInst>(&I1)) 899 LI.insert(Load, VN); 900 else if (auto *Store = dyn_cast<StoreInst>(&I1)) 901 SI.insert(Store, VN); 902 else if (auto *Call = dyn_cast<CallInst>(&I1)) { 903 if (auto *Intr = dyn_cast<IntrinsicInst>(Call)) { 904 if (isa<DbgInfoIntrinsic>(Intr) || 905 Intr->getIntrinsicID() == Intrinsic::assume) 906 continue; 907 } 908 if (Call->mayHaveSideEffects()) { 909 if (!OptForMinSize) 910 break; 911 // We may continue hoisting across calls which write to memory. 912 if (Call->mayThrow()) 913 break; 914 } 915 916 if (Call->isConvergent()) 917 break; 918 919 CI.insert(Call, VN); 920 } else if (HoistingGeps || !isa<GetElementPtrInst>(&I1)) 921 // Do not hoist scalars past calls that may write to memory because 922 // that could result in spills later. geps are handled separately. 923 // TODO: We can relax this for targets like AArch64 as they have more 924 // registers than X86. 925 II.insert(&I1, VN); 926 } 927 } 928 929 HoistingPointList HPL; 930 computeInsertionPoints(II.getVNTable(), HPL, InsKind::Scalar); 931 computeInsertionPoints(LI.getVNTable(), HPL, InsKind::Load); 932 computeInsertionPoints(SI.getVNTable(), HPL, InsKind::Store); 933 computeInsertionPoints(CI.getScalarVNTable(), HPL, InsKind::Scalar); 934 computeInsertionPoints(CI.getLoadVNTable(), HPL, InsKind::Load); 935 computeInsertionPoints(CI.getStoreVNTable(), HPL, InsKind::Store); 936 return hoist(HPL); 937 } 938 }; 939 940 class GVNHoistLegacyPass : public FunctionPass { 941 public: 942 static char ID; 943 944 GVNHoistLegacyPass() : FunctionPass(ID) { 945 initializeGVNHoistLegacyPassPass(*PassRegistry::getPassRegistry()); 946 } 947 948 bool runOnFunction(Function &F) override { 949 if (skipFunction(F)) 950 return false; 951 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 952 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults(); 953 auto &MD = getAnalysis<MemoryDependenceWrapperPass>().getMemDep(); 954 auto &MSSA = getAnalysis<MemorySSAWrapperPass>().getMSSA(); 955 956 GVNHoist G(&DT, &AA, &MD, &MSSA, F.optForMinSize()); 957 return G.run(F); 958 } 959 960 void getAnalysisUsage(AnalysisUsage &AU) const override { 961 AU.addRequired<DominatorTreeWrapperPass>(); 962 AU.addRequired<AAResultsWrapperPass>(); 963 AU.addRequired<MemoryDependenceWrapperPass>(); 964 AU.addRequired<MemorySSAWrapperPass>(); 965 AU.addPreserved<DominatorTreeWrapperPass>(); 966 AU.addPreserved<MemorySSAWrapperPass>(); 967 } 968 }; 969 } // namespace 970 971 PreservedAnalyses GVNHoistPass::run(Function &F, 972 FunctionAnalysisManager &AM) { 973 DominatorTree &DT = AM.getResult<DominatorTreeAnalysis>(F); 974 AliasAnalysis &AA = AM.getResult<AAManager>(F); 975 MemoryDependenceResults &MD = AM.getResult<MemoryDependenceAnalysis>(F); 976 MemorySSA &MSSA = AM.getResult<MemorySSAAnalysis>(F).getMSSA(); 977 GVNHoist G(&DT, &AA, &MD, &MSSA, F.optForMinSize()); 978 if (!G.run(F)) 979 return PreservedAnalyses::all(); 980 981 PreservedAnalyses PA; 982 PA.preserve<DominatorTreeAnalysis>(); 983 PA.preserve<MemorySSAAnalysis>(); 984 return PA; 985 } 986 987 char GVNHoistLegacyPass::ID = 0; 988 INITIALIZE_PASS_BEGIN(GVNHoistLegacyPass, "gvn-hoist", 989 "Early GVN Hoisting of Expressions", false, false) 990 INITIALIZE_PASS_DEPENDENCY(MemoryDependenceWrapperPass) 991 INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass) 992 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 993 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass) 994 INITIALIZE_PASS_END(GVNHoistLegacyPass, "gvn-hoist", 995 "Early GVN Hoisting of Expressions", false, false) 996 997 FunctionPass *llvm::createGVNHoistPass() { return new GVNHoistLegacyPass(); } 998