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 memory uses of Def in BB. 333 bool hasMemoryUseOnPath(const Instruction *NewPt, MemoryDef *Def, const BasicBlock *BB) { 334 const Instruction *OldPt = Def->getMemoryInst(); 335 const BasicBlock *OldBB = OldPt->getParent(); 336 const BasicBlock *NewBB = NewPt->getParent(); 337 338 bool ReachedNewPt = false; 339 MemoryLocation DefLoc = MemoryLocation::get(OldPt); 340 const MemorySSA::AccessList *Acc = MSSA->getBlockAccesses(BB); 341 if (!Acc) 342 return false; 343 344 for (const MemoryAccess &MA : *Acc) { 345 auto *MU = dyn_cast<MemoryUse>(&MA); 346 if (!MU) 347 continue; 348 349 // Do not check whether MU aliases Def when MU occurs after OldPt. 350 if (BB == OldBB && firstInBB(OldPt, MU->getMemoryInst())) 351 break; 352 353 // Do not check whether MU aliases Def when MU occurs before NewPt. 354 if (BB == NewBB) { 355 if (!ReachedNewPt) { 356 if (firstInBB(MU->getMemoryInst(), NewPt)) 357 continue; 358 ReachedNewPt = true; 359 } 360 } 361 362 if (!AA->isNoAlias(DefLoc, MemoryLocation::get(MU->getMemoryInst()))) 363 return true; 364 } 365 366 return false; 367 } 368 369 // Return true when there are exception handling or loads of memory Def 370 // between Def and NewPt. This function is only called for stores: Def is 371 // the MemoryDef of the store to be hoisted. 372 373 // Decrement by 1 NBBsOnAllPaths for each block between HoistPt and BB, and 374 // return true when the counter NBBsOnAllPaths reaces 0, except when it is 375 // initialized to -1 which is unlimited. 376 bool hasEHOrLoadsOnPath(const Instruction *NewPt, MemoryDef *Def, 377 int &NBBsOnAllPaths) { 378 const BasicBlock *NewBB = NewPt->getParent(); 379 const BasicBlock *OldBB = Def->getBlock(); 380 assert(DT->dominates(NewBB, OldBB) && "invalid path"); 381 assert(DT->dominates(Def->getDefiningAccess()->getBlock(), NewBB) && 382 "def does not dominate new hoisting point"); 383 384 // Walk all basic blocks reachable in depth-first iteration on the inverse 385 // CFG from OldBB to NewBB. These blocks are all the blocks that may be 386 // executed between the execution of NewBB and OldBB. Hoisting an expression 387 // from OldBB into NewBB has to be safe on all execution paths. 388 for (auto I = idf_begin(OldBB), E = idf_end(OldBB); I != E;) { 389 if (*I == NewBB) { 390 // Stop traversal when reaching HoistPt. 391 I.skipChildren(); 392 continue; 393 } 394 395 // Impossible to hoist with exceptions on the path. 396 if (hasEH(*I)) 397 return true; 398 399 // Check that we do not move a store past loads. 400 if (hasMemoryUseOnPath(NewPt, Def, *I)) 401 return true; 402 403 // Stop walk once the limit is reached. 404 if (NBBsOnAllPaths == 0) 405 return true; 406 407 // -1 is unlimited number of blocks on all paths. 408 if (NBBsOnAllPaths != -1) 409 --NBBsOnAllPaths; 410 411 ++I; 412 } 413 414 return false; 415 } 416 417 // Return true when there are exception handling between HoistPt and BB. 418 // Decrement by 1 NBBsOnAllPaths for each block between HoistPt and BB, and 419 // return true when the counter NBBsOnAllPaths reaches 0, except when it is 420 // initialized to -1 which is unlimited. 421 bool hasEHOnPath(const BasicBlock *HoistPt, const BasicBlock *BB, 422 int &NBBsOnAllPaths) { 423 assert(DT->dominates(HoistPt, BB) && "Invalid path"); 424 425 // Walk all basic blocks reachable in depth-first iteration on 426 // the inverse CFG from BBInsn to NewHoistPt. These blocks are all the 427 // blocks that may be executed between the execution of NewHoistPt and 428 // BBInsn. Hoisting an expression from BBInsn into NewHoistPt has to be safe 429 // on all execution paths. 430 for (auto I = idf_begin(BB), E = idf_end(BB); I != E;) { 431 if (*I == HoistPt) { 432 // Stop traversal when reaching NewHoistPt. 433 I.skipChildren(); 434 continue; 435 } 436 437 // Impossible to hoist with exceptions on the path. 438 if (hasEH(*I)) 439 return true; 440 441 // Stop walk once the limit is reached. 442 if (NBBsOnAllPaths == 0) 443 return true; 444 445 // -1 is unlimited number of blocks on all paths. 446 if (NBBsOnAllPaths != -1) 447 --NBBsOnAllPaths; 448 449 ++I; 450 } 451 452 return false; 453 } 454 455 // Return true when it is safe to hoist a memory load or store U from OldPt 456 // to NewPt. 457 bool safeToHoistLdSt(const Instruction *NewPt, const Instruction *OldPt, 458 MemoryUseOrDef *U, InsKind K, int &NBBsOnAllPaths) { 459 460 // In place hoisting is safe. 461 if (NewPt == OldPt) 462 return true; 463 464 const BasicBlock *NewBB = NewPt->getParent(); 465 const BasicBlock *OldBB = OldPt->getParent(); 466 const BasicBlock *UBB = U->getBlock(); 467 468 // Check for dependences on the Memory SSA. 469 MemoryAccess *D = U->getDefiningAccess(); 470 BasicBlock *DBB = D->getBlock(); 471 if (DT->properlyDominates(NewBB, DBB)) 472 // Cannot move the load or store to NewBB above its definition in DBB. 473 return false; 474 475 if (NewBB == DBB && !MSSA->isLiveOnEntryDef(D)) 476 if (auto *UD = dyn_cast<MemoryUseOrDef>(D)) 477 if (firstInBB(NewPt, UD->getMemoryInst())) 478 // Cannot move the load or store to NewPt above its definition in D. 479 return false; 480 481 // Check for unsafe hoistings due to side effects. 482 if (K == InsKind::Store) { 483 if (hasEHOrLoadsOnPath(NewPt, dyn_cast<MemoryDef>(U), NBBsOnAllPaths)) 484 return false; 485 } else if (hasEHOnPath(NewBB, OldBB, NBBsOnAllPaths)) 486 return false; 487 488 if (UBB == NewBB) { 489 if (DT->properlyDominates(DBB, NewBB)) 490 return true; 491 assert(UBB == DBB); 492 assert(MSSA->locallyDominates(D, U)); 493 } 494 495 // No side effects: it is safe to hoist. 496 return true; 497 } 498 499 // Return true when it is safe to hoist scalar instructions from all blocks in 500 // WL to HoistBB. 501 bool safeToHoistScalar(const BasicBlock *HoistBB, 502 SmallPtrSetImpl<const BasicBlock *> &WL, 503 int &NBBsOnAllPaths) { 504 // Check that the hoisted expression is needed on all paths. Enable scalar 505 // hoisting at -Oz as it is safe to hoist scalars to a place where they are 506 // partially needed. 507 if (!OptForMinSize && !hoistingFromAllPaths(HoistBB, WL)) 508 return false; 509 510 for (const BasicBlock *BB : WL) 511 if (hasEHOnPath(HoistBB, BB, NBBsOnAllPaths)) 512 return false; 513 514 return true; 515 } 516 517 // Each element of a hoisting list contains the basic block where to hoist and 518 // a list of instructions to be hoisted. 519 typedef std::pair<BasicBlock *, SmallVecInsn> HoistingPointInfo; 520 typedef SmallVector<HoistingPointInfo, 4> HoistingPointList; 521 522 // Partition InstructionsToHoist into a set of candidates which can share a 523 // common hoisting point. The partitions are collected in HPL. IsScalar is 524 // true when the instructions in InstructionsToHoist are scalars. IsLoad is 525 // true when the InstructionsToHoist are loads, false when they are stores. 526 void partitionCandidates(SmallVecImplInsn &InstructionsToHoist, 527 HoistingPointList &HPL, InsKind K) { 528 // No need to sort for two instructions. 529 if (InstructionsToHoist.size() > 2) { 530 SortByDFSIn Pred(DFSNumber); 531 std::sort(InstructionsToHoist.begin(), InstructionsToHoist.end(), Pred); 532 } 533 534 int NBBsOnAllPaths = MaxNumberOfBBSInPath; 535 536 SmallVecImplInsn::iterator II = InstructionsToHoist.begin(); 537 SmallVecImplInsn::iterator Start = II; 538 Instruction *HoistPt = *II; 539 BasicBlock *HoistBB = HoistPt->getParent(); 540 MemoryUseOrDef *UD; 541 if (K != InsKind::Scalar) 542 UD = cast<MemoryUseOrDef>(MSSA->getMemoryAccess(HoistPt)); 543 544 for (++II; II != InstructionsToHoist.end(); ++II) { 545 Instruction *Insn = *II; 546 BasicBlock *BB = Insn->getParent(); 547 BasicBlock *NewHoistBB; 548 Instruction *NewHoistPt; 549 550 if (BB == HoistBB) { 551 NewHoistBB = HoistBB; 552 NewHoistPt = firstInBB(Insn, HoistPt) ? Insn : HoistPt; 553 } else { 554 NewHoistBB = DT->findNearestCommonDominator(HoistBB, BB); 555 if (NewHoistBB == BB) 556 NewHoistPt = Insn; 557 else if (NewHoistBB == HoistBB) 558 NewHoistPt = HoistPt; 559 else 560 NewHoistPt = NewHoistBB->getTerminator(); 561 } 562 563 SmallPtrSet<const BasicBlock *, 2> WL; 564 WL.insert(HoistBB); 565 WL.insert(BB); 566 567 if (K == InsKind::Scalar) { 568 if (safeToHoistScalar(NewHoistBB, WL, NBBsOnAllPaths)) { 569 // Extend HoistPt to NewHoistPt. 570 HoistPt = NewHoistPt; 571 HoistBB = NewHoistBB; 572 continue; 573 } 574 } else { 575 // When NewBB already contains an instruction to be hoisted, the 576 // expression is needed on all paths. 577 // Check that the hoisted expression is needed on all paths: it is 578 // unsafe to hoist loads to a place where there may be a path not 579 // loading from the same address: for instance there may be a branch on 580 // which the address of the load may not be initialized. 581 if ((HoistBB == NewHoistBB || BB == NewHoistBB || 582 hoistingFromAllPaths(NewHoistBB, WL)) && 583 // Also check that it is safe to move the load or store from HoistPt 584 // to NewHoistPt, and from Insn to NewHoistPt. 585 safeToHoistLdSt(NewHoistPt, HoistPt, UD, K, NBBsOnAllPaths) && 586 safeToHoistLdSt(NewHoistPt, Insn, 587 cast<MemoryUseOrDef>(MSSA->getMemoryAccess(Insn)), 588 K, NBBsOnAllPaths)) { 589 // Extend HoistPt to NewHoistPt. 590 HoistPt = NewHoistPt; 591 HoistBB = NewHoistBB; 592 continue; 593 } 594 } 595 596 // At this point it is not safe to extend the current hoisting to 597 // NewHoistPt: save the hoisting list so far. 598 if (std::distance(Start, II) > 1) 599 HPL.push_back({HoistBB, SmallVecInsn(Start, II)}); 600 601 // Start over from BB. 602 Start = II; 603 if (K != InsKind::Scalar) 604 UD = cast<MemoryUseOrDef>(MSSA->getMemoryAccess(*Start)); 605 HoistPt = Insn; 606 HoistBB = BB; 607 NBBsOnAllPaths = MaxNumberOfBBSInPath; 608 } 609 610 // Save the last partition. 611 if (std::distance(Start, II) > 1) 612 HPL.push_back({HoistBB, SmallVecInsn(Start, II)}); 613 } 614 615 // Initialize HPL from Map. 616 void computeInsertionPoints(const VNtoInsns &Map, HoistingPointList &HPL, 617 InsKind K) { 618 for (const auto &Entry : Map) { 619 if (MaxHoistedThreshold != -1 && ++HoistedCtr > MaxHoistedThreshold) 620 return; 621 622 const SmallVecInsn &V = Entry.second; 623 if (V.size() < 2) 624 continue; 625 626 // Compute the insertion point and the list of expressions to be hoisted. 627 SmallVecInsn InstructionsToHoist; 628 for (auto I : V) 629 if (!hasEH(I->getParent())) 630 InstructionsToHoist.push_back(I); 631 632 if (!InstructionsToHoist.empty()) 633 partitionCandidates(InstructionsToHoist, HPL, K); 634 } 635 } 636 637 // Return true when all operands of Instr are available at insertion point 638 // HoistPt. When limiting the number of hoisted expressions, one could hoist 639 // a load without hoisting its access function. So before hoisting any 640 // expression, make sure that all its operands are available at insert point. 641 bool allOperandsAvailable(const Instruction *I, 642 const BasicBlock *HoistPt) const { 643 for (const Use &Op : I->operands()) 644 if (const auto *Inst = dyn_cast<Instruction>(&Op)) 645 if (!DT->dominates(Inst->getParent(), HoistPt)) 646 return false; 647 648 return true; 649 } 650 651 // Same as allOperandsAvailable with recursive check for GEP operands. 652 bool allGepOperandsAvailable(const Instruction *I, 653 const BasicBlock *HoistPt) const { 654 for (const Use &Op : I->operands()) 655 if (const auto *Inst = dyn_cast<Instruction>(&Op)) 656 if (!DT->dominates(Inst->getParent(), HoistPt)) { 657 if (const GetElementPtrInst *GepOp = dyn_cast<GetElementPtrInst>(Inst)) { 658 if (!allGepOperandsAvailable(GepOp, HoistPt)) 659 return false; 660 // Gep is available if all operands of GepOp are available. 661 } else { 662 // Gep is not available if it has operands other than GEPs that are 663 // defined in blocks not dominating HoistPt. 664 return false; 665 } 666 } 667 return true; 668 } 669 670 // Make all operands of the GEP available. 671 void makeGepsAvailable(Instruction *Repl, BasicBlock *HoistPt, 672 const SmallVecInsn &InstructionsToHoist, 673 Instruction *Gep) const { 674 assert(allGepOperandsAvailable(Gep, HoistPt) && "GEP operands not available"); 675 676 Instruction *ClonedGep = Gep->clone(); 677 for (unsigned i = 0, e = Gep->getNumOperands(); i != e; ++i) 678 if (Instruction *Op = dyn_cast<Instruction>(Gep->getOperand(i))) { 679 680 // Check whether the operand is already available. 681 if (DT->dominates(Op->getParent(), HoistPt)) 682 continue; 683 684 // As a GEP can refer to other GEPs, recursively make all the operands 685 // of this GEP available at HoistPt. 686 if (GetElementPtrInst *GepOp = dyn_cast<GetElementPtrInst>(Op)) 687 makeGepsAvailable(ClonedGep, HoistPt, InstructionsToHoist, GepOp); 688 } 689 690 // Copy Gep and replace its uses in Repl with ClonedGep. 691 ClonedGep->insertBefore(HoistPt->getTerminator()); 692 693 // Conservatively discard any optimization hints, they may differ on the 694 // other paths. 695 ClonedGep->dropUnknownNonDebugMetadata(); 696 697 // If we have optimization hints which agree with each other along different 698 // paths, preserve them. 699 for (const Instruction *OtherInst : InstructionsToHoist) { 700 const GetElementPtrInst *OtherGep; 701 if (auto *OtherLd = dyn_cast<LoadInst>(OtherInst)) 702 OtherGep = cast<GetElementPtrInst>(OtherLd->getPointerOperand()); 703 else 704 OtherGep = cast<GetElementPtrInst>( 705 cast<StoreInst>(OtherInst)->getPointerOperand()); 706 ClonedGep->andIRFlags(OtherGep); 707 } 708 709 // Replace uses of Gep with ClonedGep in Repl. 710 Repl->replaceUsesOfWith(Gep, ClonedGep); 711 } 712 713 // In the case Repl is a load or a store, we make all their GEPs 714 // available: GEPs are not hoisted by default to avoid the address 715 // computations to be hoisted without the associated load or store. 716 bool makeGepOperandsAvailable(Instruction *Repl, BasicBlock *HoistPt, 717 const SmallVecInsn &InstructionsToHoist) const { 718 // Check whether the GEP of a ld/st can be synthesized at HoistPt. 719 GetElementPtrInst *Gep = nullptr; 720 Instruction *Val = nullptr; 721 if (auto *Ld = dyn_cast<LoadInst>(Repl)) { 722 Gep = dyn_cast<GetElementPtrInst>(Ld->getPointerOperand()); 723 } else if (auto *St = dyn_cast<StoreInst>(Repl)) { 724 Gep = dyn_cast<GetElementPtrInst>(St->getPointerOperand()); 725 Val = dyn_cast<Instruction>(St->getValueOperand()); 726 // Check that the stored value is available. 727 if (Val) { 728 if (isa<GetElementPtrInst>(Val)) { 729 // Check whether we can compute the GEP at HoistPt. 730 if (!allGepOperandsAvailable(Val, HoistPt)) 731 return false; 732 } else if (!DT->dominates(Val->getParent(), HoistPt)) 733 return false; 734 } 735 } 736 737 // Check whether we can compute the Gep at HoistPt. 738 if (!Gep || !allGepOperandsAvailable(Gep, HoistPt)) 739 return false; 740 741 makeGepsAvailable(Repl, HoistPt, InstructionsToHoist, Gep); 742 743 if (Val && isa<GetElementPtrInst>(Val)) 744 makeGepsAvailable(Repl, HoistPt, InstructionsToHoist, Val); 745 746 return true; 747 } 748 749 std::pair<unsigned, unsigned> hoist(HoistingPointList &HPL) { 750 unsigned NI = 0, NL = 0, NS = 0, NC = 0, NR = 0; 751 for (const HoistingPointInfo &HP : HPL) { 752 // Find out whether we already have one of the instructions in HoistPt, 753 // in which case we do not have to move it. 754 BasicBlock *HoistPt = HP.first; 755 const SmallVecInsn &InstructionsToHoist = HP.second; 756 Instruction *Repl = nullptr; 757 for (Instruction *I : InstructionsToHoist) 758 if (I->getParent() == HoistPt) 759 // If there are two instructions in HoistPt to be hoisted in place: 760 // update Repl to be the first one, such that we can rename the uses 761 // of the second based on the first. 762 if (!Repl || firstInBB(I, Repl)) 763 Repl = I; 764 765 // Keep track of whether we moved the instruction so we know whether we 766 // should move the MemoryAccess. 767 bool MoveAccess = true; 768 if (Repl) { 769 // Repl is already in HoistPt: it remains in place. 770 assert(allOperandsAvailable(Repl, HoistPt) && 771 "instruction depends on operands that are not available"); 772 MoveAccess = false; 773 } else { 774 // When we do not find Repl in HoistPt, select the first in the list 775 // and move it to HoistPt. 776 Repl = InstructionsToHoist.front(); 777 778 // We can move Repl in HoistPt only when all operands are available. 779 // The order in which hoistings are done may influence the availability 780 // of operands. 781 if (!allOperandsAvailable(Repl, HoistPt)) { 782 783 // When HoistingGeps there is nothing more we can do to make the 784 // operands available: just continue. 785 if (HoistingGeps) 786 continue; 787 788 // When not HoistingGeps we need to copy the GEPs. 789 if (!makeGepOperandsAvailable(Repl, HoistPt, InstructionsToHoist)) 790 continue; 791 } 792 793 // Move the instruction at the end of HoistPt. 794 Instruction *Last = HoistPt->getTerminator(); 795 Repl->moveBefore(Last); 796 797 DFSNumber[Repl] = DFSNumber[Last]++; 798 } 799 800 MemoryAccess *NewMemAcc = MSSA->getMemoryAccess(Repl); 801 802 if (MoveAccess) { 803 if (MemoryUseOrDef *OldMemAcc = 804 dyn_cast_or_null<MemoryUseOrDef>(NewMemAcc)) { 805 // The definition of this ld/st will not change: ld/st hoisting is 806 // legal when the ld/st is not moved past its current definition. 807 MemoryAccess *Def = OldMemAcc->getDefiningAccess(); 808 NewMemAcc = 809 MSSA->createMemoryAccessInBB(Repl, Def, HoistPt, MemorySSA::End); 810 OldMemAcc->replaceAllUsesWith(NewMemAcc); 811 MSSA->removeMemoryAccess(OldMemAcc); 812 } 813 } 814 815 if (isa<LoadInst>(Repl)) 816 ++NL; 817 else if (isa<StoreInst>(Repl)) 818 ++NS; 819 else if (isa<CallInst>(Repl)) 820 ++NC; 821 else // Scalar 822 ++NI; 823 824 // Remove and rename all other instructions. 825 for (Instruction *I : InstructionsToHoist) 826 if (I != Repl) { 827 ++NR; 828 if (auto *ReplacementLoad = dyn_cast<LoadInst>(Repl)) { 829 ReplacementLoad->setAlignment( 830 std::min(ReplacementLoad->getAlignment(), 831 cast<LoadInst>(I)->getAlignment())); 832 ++NumLoadsRemoved; 833 } else if (auto *ReplacementStore = dyn_cast<StoreInst>(Repl)) { 834 ReplacementStore->setAlignment( 835 std::min(ReplacementStore->getAlignment(), 836 cast<StoreInst>(I)->getAlignment())); 837 ++NumStoresRemoved; 838 } else if (auto *ReplacementAlloca = dyn_cast<AllocaInst>(Repl)) { 839 ReplacementAlloca->setAlignment( 840 std::max(ReplacementAlloca->getAlignment(), 841 cast<AllocaInst>(I)->getAlignment())); 842 } else if (isa<CallInst>(Repl)) { 843 ++NumCallsRemoved; 844 } 845 846 if (NewMemAcc) { 847 // Update the uses of the old MSSA access with NewMemAcc. 848 MemoryAccess *OldMA = MSSA->getMemoryAccess(I); 849 OldMA->replaceAllUsesWith(NewMemAcc); 850 MSSA->removeMemoryAccess(OldMA); 851 } 852 853 Repl->andIRFlags(I); 854 combineKnownMetadata(Repl, I); 855 I->replaceAllUsesWith(Repl); 856 // Also invalidate the Alias Analysis cache. 857 MD->removeInstruction(I); 858 I->eraseFromParent(); 859 } 860 861 // Remove MemorySSA phi nodes with the same arguments. 862 if (NewMemAcc) { 863 SmallPtrSet<MemoryPhi *, 4> UsePhis; 864 for (User *U : NewMemAcc->users()) 865 if (MemoryPhi *Phi = dyn_cast<MemoryPhi>(U)) 866 UsePhis.insert(Phi); 867 868 for (auto *Phi : UsePhis) { 869 auto In = Phi->incoming_values(); 870 if (all_of(In, [&](Use &U) { return U == NewMemAcc; })) { 871 Phi->replaceAllUsesWith(NewMemAcc); 872 MSSA->removeMemoryAccess(Phi); 873 } 874 } 875 } 876 } 877 878 NumHoisted += NL + NS + NC + NI; 879 NumRemoved += NR; 880 NumLoadsHoisted += NL; 881 NumStoresHoisted += NS; 882 NumCallsHoisted += NC; 883 return {NI, NL + NC + NS}; 884 } 885 886 // Hoist all expressions. Returns Number of scalars hoisted 887 // and number of non-scalars hoisted. 888 std::pair<unsigned, unsigned> hoistExpressions(Function &F) { 889 InsnInfo II; 890 LoadInfo LI; 891 StoreInfo SI; 892 CallInfo CI; 893 for (BasicBlock *BB : depth_first(&F.getEntryBlock())) { 894 int InstructionNb = 0; 895 for (Instruction &I1 : *BB) { 896 // Only hoist the first instructions in BB up to MaxDepthInBB. Hoisting 897 // deeper may increase the register pressure and compilation time. 898 if (MaxDepthInBB != -1 && InstructionNb++ >= MaxDepthInBB) 899 break; 900 901 // Do not value number terminator instructions. 902 if (isa<TerminatorInst>(&I1)) 903 break; 904 905 if (auto *Load = dyn_cast<LoadInst>(&I1)) 906 LI.insert(Load, VN); 907 else if (auto *Store = dyn_cast<StoreInst>(&I1)) 908 SI.insert(Store, VN); 909 else if (auto *Call = dyn_cast<CallInst>(&I1)) { 910 if (auto *Intr = dyn_cast<IntrinsicInst>(Call)) { 911 if (isa<DbgInfoIntrinsic>(Intr) || 912 Intr->getIntrinsicID() == Intrinsic::assume) 913 continue; 914 } 915 if (Call->mayHaveSideEffects()) { 916 if (!OptForMinSize) 917 break; 918 // We may continue hoisting across calls which write to memory. 919 if (Call->mayThrow()) 920 break; 921 } 922 923 if (Call->isConvergent()) 924 break; 925 926 CI.insert(Call, VN); 927 } else if (HoistingGeps || !isa<GetElementPtrInst>(&I1)) 928 // Do not hoist scalars past calls that may write to memory because 929 // that could result in spills later. geps are handled separately. 930 // TODO: We can relax this for targets like AArch64 as they have more 931 // registers than X86. 932 II.insert(&I1, VN); 933 } 934 } 935 936 HoistingPointList HPL; 937 computeInsertionPoints(II.getVNTable(), HPL, InsKind::Scalar); 938 computeInsertionPoints(LI.getVNTable(), HPL, InsKind::Load); 939 computeInsertionPoints(SI.getVNTable(), HPL, InsKind::Store); 940 computeInsertionPoints(CI.getScalarVNTable(), HPL, InsKind::Scalar); 941 computeInsertionPoints(CI.getLoadVNTable(), HPL, InsKind::Load); 942 computeInsertionPoints(CI.getStoreVNTable(), HPL, InsKind::Store); 943 return hoist(HPL); 944 } 945 }; 946 947 class GVNHoistLegacyPass : public FunctionPass { 948 public: 949 static char ID; 950 951 GVNHoistLegacyPass() : FunctionPass(ID) { 952 initializeGVNHoistLegacyPassPass(*PassRegistry::getPassRegistry()); 953 } 954 955 bool runOnFunction(Function &F) override { 956 if (skipFunction(F)) 957 return false; 958 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 959 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults(); 960 auto &MD = getAnalysis<MemoryDependenceWrapperPass>().getMemDep(); 961 auto &MSSA = getAnalysis<MemorySSAWrapperPass>().getMSSA(); 962 963 GVNHoist G(&DT, &AA, &MD, &MSSA, F.optForMinSize()); 964 return G.run(F); 965 } 966 967 void getAnalysisUsage(AnalysisUsage &AU) const override { 968 AU.addRequired<DominatorTreeWrapperPass>(); 969 AU.addRequired<AAResultsWrapperPass>(); 970 AU.addRequired<MemoryDependenceWrapperPass>(); 971 AU.addRequired<MemorySSAWrapperPass>(); 972 AU.addPreserved<DominatorTreeWrapperPass>(); 973 AU.addPreserved<MemorySSAWrapperPass>(); 974 } 975 }; 976 } // namespace 977 978 PreservedAnalyses GVNHoistPass::run(Function &F, 979 FunctionAnalysisManager &AM) { 980 DominatorTree &DT = AM.getResult<DominatorTreeAnalysis>(F); 981 AliasAnalysis &AA = AM.getResult<AAManager>(F); 982 MemoryDependenceResults &MD = AM.getResult<MemoryDependenceAnalysis>(F); 983 MemorySSA &MSSA = AM.getResult<MemorySSAAnalysis>(F).getMSSA(); 984 GVNHoist G(&DT, &AA, &MD, &MSSA, F.optForMinSize()); 985 if (!G.run(F)) 986 return PreservedAnalyses::all(); 987 988 PreservedAnalyses PA; 989 PA.preserve<DominatorTreeAnalysis>(); 990 PA.preserve<MemorySSAAnalysis>(); 991 return PA; 992 } 993 994 char GVNHoistLegacyPass::ID = 0; 995 INITIALIZE_PASS_BEGIN(GVNHoistLegacyPass, "gvn-hoist", 996 "Early GVN Hoisting of Expressions", false, false) 997 INITIALIZE_PASS_DEPENDENCY(MemoryDependenceWrapperPass) 998 INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass) 999 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 1000 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass) 1001 INITIALIZE_PASS_END(GVNHoistLegacyPass, "gvn-hoist", 1002 "Early GVN Hoisting of Expressions", false, false) 1003 1004 FunctionPass *llvm::createGVNHoistPass() { return new GVNHoistLegacyPass(); } 1005