1 //===- GVNHoist.cpp - Hoist scalar and load expressions -------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This pass hoists expressions from branches to a common dominator. It uses 10 // GVN (global value numbering) to discover expressions computing the same 11 // values. The primary goals of code-hoisting are: 12 // 1. To reduce the code size. 13 // 2. In some cases reduce critical path (by exposing more ILP). 14 // 15 // The algorithm factors out the reachability of values such that multiple 16 // queries to find reachability of values are fast. This is based on finding the 17 // ANTIC points in the CFG which do not change during hoisting. The ANTIC points 18 // are basically the dominance-frontiers in the inverse graph. So we introduce a 19 // data structure (CHI nodes) to keep track of values flowing out of a basic 20 // block. We only do this for values with multiple occurrences in the function 21 // as they are the potential hoistable candidates. This approach allows us to 22 // hoist instructions to a basic block with more than two successors, as well as 23 // deal with infinite loops in a trivial way. 24 // 25 // Limitations: This pass does not hoist fully redundant expressions because 26 // they are already handled by GVN-PRE. It is advisable to run gvn-hoist before 27 // and after gvn-pre because gvn-pre creates opportunities for more instructions 28 // to be hoisted. 29 // 30 // Hoisting may affect the performance in some cases. To mitigate that, hoisting 31 // is disabled in the following cases. 32 // 1. Scalars across calls. 33 // 2. geps when corresponding load/store cannot be hoisted. 34 //===----------------------------------------------------------------------===// 35 36 #include "llvm/ADT/DenseMap.h" 37 #include "llvm/ADT/DenseSet.h" 38 #include "llvm/ADT/STLExtras.h" 39 #include "llvm/ADT/SmallPtrSet.h" 40 #include "llvm/ADT/SmallVector.h" 41 #include "llvm/ADT/Statistic.h" 42 #include "llvm/ADT/iterator_range.h" 43 #include "llvm/Analysis/AliasAnalysis.h" 44 #include "llvm/Analysis/GlobalsModRef.h" 45 #include "llvm/Analysis/IteratedDominanceFrontier.h" 46 #include "llvm/Analysis/MemoryDependenceAnalysis.h" 47 #include "llvm/Analysis/MemorySSA.h" 48 #include "llvm/Analysis/MemorySSAUpdater.h" 49 #include "llvm/Analysis/PostDominators.h" 50 #include "llvm/Analysis/ValueTracking.h" 51 #include "llvm/IR/Argument.h" 52 #include "llvm/IR/BasicBlock.h" 53 #include "llvm/IR/CFG.h" 54 #include "llvm/IR/Constants.h" 55 #include "llvm/IR/Dominators.h" 56 #include "llvm/IR/Function.h" 57 #include "llvm/IR/InstrTypes.h" 58 #include "llvm/IR/Instruction.h" 59 #include "llvm/IR/Instructions.h" 60 #include "llvm/IR/IntrinsicInst.h" 61 #include "llvm/IR/Intrinsics.h" 62 #include "llvm/IR/LLVMContext.h" 63 #include "llvm/IR/PassManager.h" 64 #include "llvm/IR/Use.h" 65 #include "llvm/IR/User.h" 66 #include "llvm/IR/Value.h" 67 #include "llvm/InitializePasses.h" 68 #include "llvm/Pass.h" 69 #include "llvm/Support/Casting.h" 70 #include "llvm/Support/CommandLine.h" 71 #include "llvm/Support/Debug.h" 72 #include "llvm/Support/raw_ostream.h" 73 #include "llvm/Transforms/Scalar.h" 74 #include "llvm/Transforms/Scalar/GVN.h" 75 #include "llvm/Transforms/Utils/Local.h" 76 #include <algorithm> 77 #include <cassert> 78 #include <iterator> 79 #include <memory> 80 #include <utility> 81 #include <vector> 82 83 using namespace llvm; 84 85 #define DEBUG_TYPE "gvn-hoist" 86 87 STATISTIC(NumHoisted, "Number of instructions hoisted"); 88 STATISTIC(NumRemoved, "Number of instructions removed"); 89 STATISTIC(NumLoadsHoisted, "Number of loads hoisted"); 90 STATISTIC(NumLoadsRemoved, "Number of loads removed"); 91 STATISTIC(NumStoresHoisted, "Number of stores hoisted"); 92 STATISTIC(NumStoresRemoved, "Number of stores removed"); 93 STATISTIC(NumCallsHoisted, "Number of calls hoisted"); 94 STATISTIC(NumCallsRemoved, "Number of calls removed"); 95 96 static cl::opt<int> 97 MaxHoistedThreshold("gvn-max-hoisted", cl::Hidden, cl::init(-1), 98 cl::desc("Max number of instructions to hoist " 99 "(default unlimited = -1)")); 100 101 static cl::opt<int> MaxNumberOfBBSInPath( 102 "gvn-hoist-max-bbs", cl::Hidden, cl::init(4), 103 cl::desc("Max number of basic blocks on the path between " 104 "hoisting locations (default = 4, unlimited = -1)")); 105 106 static cl::opt<int> MaxDepthInBB( 107 "gvn-hoist-max-depth", cl::Hidden, cl::init(100), 108 cl::desc("Hoist instructions from the beginning of the BB up to the " 109 "maximum specified depth (default = 100, unlimited = -1)")); 110 111 static cl::opt<int> 112 MaxChainLength("gvn-hoist-max-chain-length", cl::Hidden, cl::init(10), 113 cl::desc("Maximum length of dependent chains to hoist " 114 "(default = 10, unlimited = -1)")); 115 116 namespace llvm { 117 118 using BBSideEffectsSet = DenseMap<const BasicBlock *, bool>; 119 using SmallVecInsn = SmallVector<Instruction *, 4>; 120 using SmallVecImplInsn = SmallVectorImpl<Instruction *>; 121 122 // Each element of a hoisting list contains the basic block where to hoist and 123 // a list of instructions to be hoisted. 124 using HoistingPointInfo = std::pair<BasicBlock *, SmallVecInsn>; 125 126 using HoistingPointList = SmallVector<HoistingPointInfo, 4>; 127 128 // A map from a pair of VNs to all the instructions with those VNs. 129 using VNType = std::pair<unsigned, unsigned>; 130 131 using VNtoInsns = DenseMap<VNType, SmallVector<Instruction *, 4>>; 132 133 // CHI keeps information about values flowing out of a basic block. It is 134 // similar to PHI but in the inverse graph, and used for outgoing values on each 135 // edge. For conciseness, it is computed only for instructions with multiple 136 // occurrences in the CFG because they are the only hoistable candidates. 137 // A (CHI[{V, B, I1}, {V, C, I2}] 138 // / \ 139 // / \ 140 // B(I1) C (I2) 141 // The Value number for both I1 and I2 is V, the CHI node will save the 142 // instruction as well as the edge where the value is flowing to. 143 struct CHIArg { 144 VNType VN; 145 146 // Edge destination (shows the direction of flow), may not be where the I is. 147 BasicBlock *Dest; 148 149 // The instruction (VN) which uses the values flowing out of CHI. 150 Instruction *I; 151 152 bool operator==(const CHIArg &A) const { return VN == A.VN; } 153 bool operator!=(const CHIArg &A) const { return !(*this == A); } 154 }; 155 156 using CHIIt = SmallVectorImpl<CHIArg>::iterator; 157 using CHIArgs = iterator_range<CHIIt>; 158 using OutValuesType = DenseMap<BasicBlock *, SmallVector<CHIArg, 2>>; 159 using InValuesType = 160 DenseMap<BasicBlock *, SmallVector<std::pair<VNType, Instruction *>, 2>>; 161 162 // An invalid value number Used when inserting a single value number into 163 // VNtoInsns. 164 enum : unsigned { InvalidVN = ~2U }; 165 166 // Records all scalar instructions candidate for code hoisting. 167 class InsnInfo { 168 VNtoInsns VNtoScalars; 169 170 public: 171 // Inserts I and its value number in VNtoScalars. 172 void insert(Instruction *I, GVN::ValueTable &VN) { 173 // Scalar instruction. 174 unsigned V = VN.lookupOrAdd(I); 175 VNtoScalars[{V, InvalidVN}].push_back(I); 176 } 177 178 const VNtoInsns &getVNTable() const { return VNtoScalars; } 179 }; 180 181 // Records all load instructions candidate for code hoisting. 182 class LoadInfo { 183 VNtoInsns VNtoLoads; 184 185 public: 186 // Insert Load and the value number of its memory address in VNtoLoads. 187 void insert(LoadInst *Load, GVN::ValueTable &VN) { 188 if (Load->isSimple()) { 189 unsigned V = VN.lookupOrAdd(Load->getPointerOperand()); 190 VNtoLoads[{V, InvalidVN}].push_back(Load); 191 } 192 } 193 194 const VNtoInsns &getVNTable() const { return VNtoLoads; } 195 }; 196 197 // Records all store instructions candidate for code hoisting. 198 class StoreInfo { 199 VNtoInsns VNtoStores; 200 201 public: 202 // Insert the Store and a hash number of the store address and the stored 203 // value in VNtoStores. 204 void insert(StoreInst *Store, GVN::ValueTable &VN) { 205 if (!Store->isSimple()) 206 return; 207 // Hash the store address and the stored value. 208 Value *Ptr = Store->getPointerOperand(); 209 Value *Val = Store->getValueOperand(); 210 VNtoStores[{VN.lookupOrAdd(Ptr), VN.lookupOrAdd(Val)}].push_back(Store); 211 } 212 213 const VNtoInsns &getVNTable() const { return VNtoStores; } 214 }; 215 216 // Records all call instructions candidate for code hoisting. 217 class CallInfo { 218 VNtoInsns VNtoCallsScalars; 219 VNtoInsns VNtoCallsLoads; 220 VNtoInsns VNtoCallsStores; 221 222 public: 223 // Insert Call and its value numbering in one of the VNtoCalls* containers. 224 void insert(CallInst *Call, GVN::ValueTable &VN) { 225 // A call that doesNotAccessMemory is handled as a Scalar, 226 // onlyReadsMemory will be handled as a Load instruction, 227 // all other calls will be handled as stores. 228 unsigned V = VN.lookupOrAdd(Call); 229 auto Entry = std::make_pair(V, InvalidVN); 230 231 if (Call->doesNotAccessMemory()) 232 VNtoCallsScalars[Entry].push_back(Call); 233 else if (Call->onlyReadsMemory()) 234 VNtoCallsLoads[Entry].push_back(Call); 235 else 236 VNtoCallsStores[Entry].push_back(Call); 237 } 238 239 const VNtoInsns &getScalarVNTable() const { return VNtoCallsScalars; } 240 const VNtoInsns &getLoadVNTable() const { return VNtoCallsLoads; } 241 const VNtoInsns &getStoreVNTable() const { return VNtoCallsStores; } 242 }; 243 244 static void combineKnownMetadata(Instruction *ReplInst, Instruction *I) { 245 static const unsigned KnownIDs[] = {LLVMContext::MD_tbaa, 246 LLVMContext::MD_alias_scope, 247 LLVMContext::MD_noalias, 248 LLVMContext::MD_range, 249 LLVMContext::MD_fpmath, 250 LLVMContext::MD_invariant_load, 251 LLVMContext::MD_invariant_group, 252 LLVMContext::MD_access_group}; 253 combineMetadata(ReplInst, I, KnownIDs, true); 254 } 255 256 // This pass hoists common computations across branches sharing common 257 // dominator. The primary goal is to reduce the code size, and in some 258 // cases reduce critical path (by exposing more ILP). 259 class GVNHoist { 260 public: 261 GVNHoist(DominatorTree *DT, PostDominatorTree *PDT, AliasAnalysis *AA, 262 MemoryDependenceResults *MD, MemorySSA *MSSA) 263 : DT(DT), PDT(PDT), AA(AA), MD(MD), MSSA(MSSA), 264 MSSAUpdater(std::make_unique<MemorySSAUpdater>(MSSA)) {} 265 266 bool run(Function &F); 267 268 // Copied from NewGVN.cpp 269 // This function provides global ranking of operations so that we can place 270 // them in a canonical order. Note that rank alone is not necessarily enough 271 // for a complete ordering, as constants all have the same rank. However, 272 // generally, we will simplify an operation with all constants so that it 273 // doesn't matter what order they appear in. 274 unsigned int rank(const Value *V) const; 275 276 private: 277 GVN::ValueTable VN; 278 DominatorTree *DT; 279 PostDominatorTree *PDT; 280 AliasAnalysis *AA; 281 MemoryDependenceResults *MD; 282 MemorySSA *MSSA; 283 std::unique_ptr<MemorySSAUpdater> MSSAUpdater; 284 DenseMap<const Value *, unsigned> DFSNumber; 285 BBSideEffectsSet BBSideEffects; 286 DenseSet<const BasicBlock *> HoistBarrier; 287 SmallVector<BasicBlock *, 32> IDFBlocks; 288 unsigned NumFuncArgs; 289 const bool HoistingGeps = false; 290 291 enum InsKind { Unknown, Scalar, Load, Store }; 292 293 // Return true when there are exception handling in BB. 294 bool hasEH(const BasicBlock *BB); 295 296 // Return true when I1 appears before I2 in the instructions of BB. 297 bool firstInBB(const Instruction *I1, const Instruction *I2) { 298 assert(I1->getParent() == I2->getParent()); 299 unsigned I1DFS = DFSNumber.lookup(I1); 300 unsigned I2DFS = DFSNumber.lookup(I2); 301 assert(I1DFS && I2DFS); 302 return I1DFS < I2DFS; 303 } 304 305 // Return true when there are memory uses of Def in BB. 306 bool hasMemoryUse(const Instruction *NewPt, MemoryDef *Def, 307 const BasicBlock *BB); 308 309 bool hasEHhelper(const BasicBlock *BB, const BasicBlock *SrcBB, 310 int &NBBsOnAllPaths); 311 312 // Return true when there are exception handling or loads of memory Def 313 // between Def and NewPt. This function is only called for stores: Def is 314 // the MemoryDef of the store to be hoisted. 315 316 // Decrement by 1 NBBsOnAllPaths for each block between HoistPt and BB, and 317 // return true when the counter NBBsOnAllPaths reaces 0, except when it is 318 // initialized to -1 which is unlimited. 319 bool hasEHOrLoadsOnPath(const Instruction *NewPt, MemoryDef *Def, 320 int &NBBsOnAllPaths); 321 322 // Return true when there are exception handling between HoistPt and BB. 323 // Decrement by 1 NBBsOnAllPaths for each block between HoistPt and BB, and 324 // return true when the counter NBBsOnAllPaths reaches 0, except when it is 325 // initialized to -1 which is unlimited. 326 bool hasEHOnPath(const BasicBlock *HoistPt, const BasicBlock *SrcBB, 327 int &NBBsOnAllPaths); 328 329 // Return true when it is safe to hoist a memory load or store U from OldPt 330 // to NewPt. 331 bool safeToHoistLdSt(const Instruction *NewPt, const Instruction *OldPt, 332 MemoryUseOrDef *U, InsKind K, int &NBBsOnAllPaths); 333 334 // Return true when it is safe to hoist scalar instructions from all blocks in 335 // WL to HoistBB. 336 bool safeToHoistScalar(const BasicBlock *HoistBB, const BasicBlock *BB, 337 int &NBBsOnAllPaths) { 338 return !hasEHOnPath(HoistBB, BB, NBBsOnAllPaths); 339 } 340 341 // In the inverse CFG, the dominance frontier of basic block (BB) is the 342 // point where ANTIC needs to be computed for instructions which are going 343 // to be hoisted. Since this point does not change during gvn-hoist, 344 // we compute it only once (on demand). 345 // The ides is inspired from: 346 // "Partial Redundancy Elimination in SSA Form" 347 // ROBERT KENNEDY, SUN CHAN, SHIN-MING LIU, RAYMOND LO, PENG TU and FRED CHOW 348 // They use similar idea in the forward graph to find fully redundant and 349 // partially redundant expressions, here it is used in the inverse graph to 350 // find fully anticipable instructions at merge point (post-dominator in 351 // the inverse CFG). 352 // Returns the edge via which an instruction in BB will get the values from. 353 354 // Returns true when the values are flowing out to each edge. 355 bool valueAnticipable(CHIArgs C, Instruction *TI) const; 356 357 // Check if it is safe to hoist values tracked by CHI in the range 358 // [Begin, End) and accumulate them in Safe. 359 void checkSafety(CHIArgs C, BasicBlock *BB, InsKind K, 360 SmallVectorImpl<CHIArg> &Safe); 361 362 using RenameStackType = DenseMap<VNType, SmallVector<Instruction *, 2>>; 363 364 // Push all the VNs corresponding to BB into RenameStack. 365 void fillRenameStack(BasicBlock *BB, InValuesType &ValueBBs, 366 RenameStackType &RenameStack); 367 368 void fillChiArgs(BasicBlock *BB, OutValuesType &CHIBBs, 369 RenameStackType &RenameStack); 370 371 // Walk the post-dominator tree top-down and use a stack for each value to 372 // store the last value you see. When you hit a CHI from a given edge, the 373 // value to use as the argument is at the top of the stack, add the value to 374 // CHI and pop. 375 void insertCHI(InValuesType &ValueBBs, OutValuesType &CHIBBs) { 376 auto Root = PDT->getNode(nullptr); 377 if (!Root) 378 return; 379 // Depth first walk on PDom tree to fill the CHIargs at each PDF. 380 RenameStackType RenameStack; 381 for (auto Node : depth_first(Root)) { 382 BasicBlock *BB = Node->getBlock(); 383 if (!BB) 384 continue; 385 386 // Collect all values in BB and push to stack. 387 fillRenameStack(BB, ValueBBs, RenameStack); 388 389 // Fill outgoing values in each CHI corresponding to BB. 390 fillChiArgs(BB, CHIBBs, RenameStack); 391 } 392 } 393 394 // Walk all the CHI-nodes to find ones which have a empty-entry and remove 395 // them Then collect all the instructions which are safe to hoist and see if 396 // they form a list of anticipable values. OutValues contains CHIs 397 // corresponding to each basic block. 398 void findHoistableCandidates(OutValuesType &CHIBBs, InsKind K, 399 HoistingPointList &HPL); 400 401 // Compute insertion points for each values which can be fully anticipated at 402 // a dominator. HPL contains all such values. 403 void computeInsertionPoints(const VNtoInsns &Map, HoistingPointList &HPL, 404 InsKind K) { 405 // Sort VNs based on their rankings 406 std::vector<VNType> Ranks; 407 for (const auto &Entry : Map) { 408 Ranks.push_back(Entry.first); 409 } 410 411 // TODO: Remove fully-redundant expressions. 412 // Get instruction from the Map, assume that all the Instructions 413 // with same VNs have same rank (this is an approximation). 414 llvm::sort(Ranks, [this, &Map](const VNType &r1, const VNType &r2) { 415 return (rank(*Map.lookup(r1).begin()) < rank(*Map.lookup(r2).begin())); 416 }); 417 418 // - Sort VNs according to their rank, and start with lowest ranked VN 419 // - Take a VN and for each instruction with same VN 420 // - Find the dominance frontier in the inverse graph (PDF) 421 // - Insert the chi-node at PDF 422 // - Remove the chi-nodes with missing entries 423 // - Remove values from CHI-nodes which do not truly flow out, e.g., 424 // modified along the path. 425 // - Collect the remaining values that are still anticipable 426 SmallVector<BasicBlock *, 2> IDFBlocks; 427 ReverseIDFCalculator IDFs(*PDT); 428 OutValuesType OutValue; 429 InValuesType InValue; 430 for (const auto &R : Ranks) { 431 const SmallVecInsn &V = Map.lookup(R); 432 if (V.size() < 2) 433 continue; 434 const VNType &VN = R; 435 SmallPtrSet<BasicBlock *, 2> VNBlocks; 436 for (auto &I : V) { 437 BasicBlock *BBI = I->getParent(); 438 if (!hasEH(BBI)) 439 VNBlocks.insert(BBI); 440 } 441 // Compute the Post Dominance Frontiers of each basic block 442 // The dominance frontier of a live block X in the reverse 443 // control graph is the set of blocks upon which X is control 444 // dependent. The following sequence computes the set of blocks 445 // which currently have dead terminators that are control 446 // dependence sources of a block which is in NewLiveBlocks. 447 IDFs.setDefiningBlocks(VNBlocks); 448 IDFBlocks.clear(); 449 IDFs.calculate(IDFBlocks); 450 451 // Make a map of BB vs instructions to be hoisted. 452 for (unsigned i = 0; i < V.size(); ++i) { 453 InValue[V[i]->getParent()].push_back(std::make_pair(VN, V[i])); 454 } 455 // Insert empty CHI node for this VN. This is used to factor out 456 // basic blocks where the ANTIC can potentially change. 457 CHIArg EmptyChi = {VN, nullptr, nullptr}; 458 for (auto *IDFBB : IDFBlocks) { 459 for (unsigned i = 0; i < V.size(); ++i) { 460 // Ignore spurious PDFs. 461 if (DT->properlyDominates(IDFBB, V[i]->getParent())) { 462 OutValue[IDFBB].push_back(EmptyChi); 463 LLVM_DEBUG(dbgs() << "\nInserting a CHI for BB: " 464 << IDFBB->getName() << ", for Insn: " << *V[i]); 465 } 466 } 467 } 468 } 469 470 // Insert CHI args at each PDF to iterate on factored graph of 471 // control dependence. 472 insertCHI(InValue, OutValue); 473 // Using the CHI args inserted at each PDF, find fully anticipable values. 474 findHoistableCandidates(OutValue, K, HPL); 475 } 476 477 // Return true when all operands of Instr are available at insertion point 478 // HoistPt. When limiting the number of hoisted expressions, one could hoist 479 // a load without hoisting its access function. So before hoisting any 480 // expression, make sure that all its operands are available at insert point. 481 bool allOperandsAvailable(const Instruction *I, 482 const BasicBlock *HoistPt) const; 483 484 // Same as allOperandsAvailable with recursive check for GEP operands. 485 bool allGepOperandsAvailable(const Instruction *I, 486 const BasicBlock *HoistPt) const; 487 488 // Make all operands of the GEP available. 489 void makeGepsAvailable(Instruction *Repl, BasicBlock *HoistPt, 490 const SmallVecInsn &InstructionsToHoist, 491 Instruction *Gep) const; 492 493 void updateAlignment(Instruction *I, Instruction *Repl); 494 495 // Remove all the instructions in Candidates and replace their usage with 496 // Repl. Returns the number of instructions removed. 497 unsigned rauw(const SmallVecInsn &Candidates, Instruction *Repl, 498 MemoryUseOrDef *NewMemAcc); 499 500 // Replace all Memory PHI usage with NewMemAcc. 501 void raMPHIuw(MemoryUseOrDef *NewMemAcc); 502 503 // Remove all other instructions and replace them with Repl. 504 unsigned removeAndReplace(const SmallVecInsn &Candidates, Instruction *Repl, 505 BasicBlock *DestBB, bool MoveAccess); 506 507 // In the case Repl is a load or a store, we make all their GEPs 508 // available: GEPs are not hoisted by default to avoid the address 509 // computations to be hoisted without the associated load or store. 510 bool makeGepOperandsAvailable(Instruction *Repl, BasicBlock *HoistPt, 511 const SmallVecInsn &InstructionsToHoist) const; 512 513 std::pair<unsigned, unsigned> hoist(HoistingPointList &HPL); 514 515 // Hoist all expressions. Returns Number of scalars hoisted 516 // and number of non-scalars hoisted. 517 std::pair<unsigned, unsigned> hoistExpressions(Function &F); 518 }; 519 520 class GVNHoistLegacyPass : public FunctionPass { 521 public: 522 static char ID; 523 524 GVNHoistLegacyPass() : FunctionPass(ID) { 525 initializeGVNHoistLegacyPassPass(*PassRegistry::getPassRegistry()); 526 } 527 528 bool runOnFunction(Function &F) override { 529 if (skipFunction(F)) 530 return false; 531 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 532 auto &PDT = getAnalysis<PostDominatorTreeWrapperPass>().getPostDomTree(); 533 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults(); 534 auto &MD = getAnalysis<MemoryDependenceWrapperPass>().getMemDep(); 535 auto &MSSA = getAnalysis<MemorySSAWrapperPass>().getMSSA(); 536 537 GVNHoist G(&DT, &PDT, &AA, &MD, &MSSA); 538 return G.run(F); 539 } 540 541 void getAnalysisUsage(AnalysisUsage &AU) const override { 542 AU.addRequired<DominatorTreeWrapperPass>(); 543 AU.addRequired<PostDominatorTreeWrapperPass>(); 544 AU.addRequired<AAResultsWrapperPass>(); 545 AU.addRequired<MemoryDependenceWrapperPass>(); 546 AU.addRequired<MemorySSAWrapperPass>(); 547 AU.addPreserved<DominatorTreeWrapperPass>(); 548 AU.addPreserved<MemorySSAWrapperPass>(); 549 AU.addPreserved<GlobalsAAWrapperPass>(); 550 AU.addPreserved<AAResultsWrapperPass>(); 551 } 552 }; 553 554 bool GVNHoist::run(Function &F) { 555 NumFuncArgs = F.arg_size(); 556 VN.setDomTree(DT); 557 VN.setAliasAnalysis(AA); 558 VN.setMemDep(MD); 559 bool Res = false; 560 // Perform DFS Numbering of instructions. 561 unsigned BBI = 0; 562 for (const BasicBlock *BB : depth_first(&F.getEntryBlock())) { 563 DFSNumber[BB] = ++BBI; 564 unsigned I = 0; 565 for (auto &Inst : *BB) 566 DFSNumber[&Inst] = ++I; 567 } 568 569 int ChainLength = 0; 570 571 // FIXME: use lazy evaluation of VN to avoid the fix-point computation. 572 while (true) { 573 if (MaxChainLength != -1 && ++ChainLength >= MaxChainLength) 574 return Res; 575 576 auto HoistStat = hoistExpressions(F); 577 if (HoistStat.first + HoistStat.second == 0) 578 return Res; 579 580 if (HoistStat.second > 0) 581 // To address a limitation of the current GVN, we need to rerun the 582 // hoisting after we hoisted loads or stores in order to be able to 583 // hoist all scalars dependent on the hoisted ld/st. 584 VN.clear(); 585 586 Res = true; 587 } 588 589 return Res; 590 } 591 592 unsigned int GVNHoist::rank(const Value *V) const { 593 // Prefer constants to undef to anything else 594 // Undef is a constant, have to check it first. 595 // Prefer smaller constants to constantexprs 596 if (isa<ConstantExpr>(V)) 597 return 2; 598 if (isa<UndefValue>(V)) 599 return 1; 600 if (isa<Constant>(V)) 601 return 0; 602 else if (auto *A = dyn_cast<Argument>(V)) 603 return 3 + A->getArgNo(); 604 605 // Need to shift the instruction DFS by number of arguments + 3 to account 606 // for the constant and argument ranking above. 607 auto Result = DFSNumber.lookup(V); 608 if (Result > 0) 609 return 4 + NumFuncArgs + Result; 610 // Unreachable or something else, just return a really large number. 611 return ~0; 612 } 613 614 bool GVNHoist::hasEH(const BasicBlock *BB) { 615 auto It = BBSideEffects.find(BB); 616 if (It != BBSideEffects.end()) 617 return It->second; 618 619 if (BB->isEHPad() || BB->hasAddressTaken()) { 620 BBSideEffects[BB] = true; 621 return true; 622 } 623 624 if (BB->getTerminator()->mayThrow()) { 625 BBSideEffects[BB] = true; 626 return true; 627 } 628 629 BBSideEffects[BB] = false; 630 return false; 631 } 632 633 bool GVNHoist::hasMemoryUse(const Instruction *NewPt, MemoryDef *Def, 634 const BasicBlock *BB) { 635 const MemorySSA::AccessList *Acc = MSSA->getBlockAccesses(BB); 636 if (!Acc) 637 return false; 638 639 Instruction *OldPt = Def->getMemoryInst(); 640 const BasicBlock *OldBB = OldPt->getParent(); 641 const BasicBlock *NewBB = NewPt->getParent(); 642 bool ReachedNewPt = false; 643 644 for (const MemoryAccess &MA : *Acc) 645 if (const MemoryUse *MU = dyn_cast<MemoryUse>(&MA)) { 646 Instruction *Insn = MU->getMemoryInst(); 647 648 // Do not check whether MU aliases Def when MU occurs after OldPt. 649 if (BB == OldBB && firstInBB(OldPt, Insn)) 650 break; 651 652 // Do not check whether MU aliases Def when MU occurs before NewPt. 653 if (BB == NewBB) { 654 if (!ReachedNewPt) { 655 if (firstInBB(Insn, NewPt)) 656 continue; 657 ReachedNewPt = true; 658 } 659 } 660 if (MemorySSAUtil::defClobbersUseOrDef(Def, MU, *AA)) 661 return true; 662 } 663 664 return false; 665 } 666 667 bool GVNHoist::hasEHhelper(const BasicBlock *BB, const BasicBlock *SrcBB, 668 int &NBBsOnAllPaths) { 669 // Stop walk once the limit is reached. 670 if (NBBsOnAllPaths == 0) 671 return true; 672 673 // Impossible to hoist with exceptions on the path. 674 if (hasEH(BB)) 675 return true; 676 677 // No such instruction after HoistBarrier in a basic block was 678 // selected for hoisting so instructions selected within basic block with 679 // a hoist barrier can be hoisted. 680 if ((BB != SrcBB) && HoistBarrier.count(BB)) 681 return true; 682 683 return false; 684 } 685 686 bool GVNHoist::hasEHOrLoadsOnPath(const Instruction *NewPt, MemoryDef *Def, 687 int &NBBsOnAllPaths) { 688 const BasicBlock *NewBB = NewPt->getParent(); 689 const BasicBlock *OldBB = Def->getBlock(); 690 assert(DT->dominates(NewBB, OldBB) && "invalid path"); 691 assert(DT->dominates(Def->getDefiningAccess()->getBlock(), NewBB) && 692 "def does not dominate new hoisting point"); 693 694 // Walk all basic blocks reachable in depth-first iteration on the inverse 695 // CFG from OldBB to NewBB. These blocks are all the blocks that may be 696 // executed between the execution of NewBB and OldBB. Hoisting an expression 697 // from OldBB into NewBB has to be safe on all execution paths. 698 for (auto I = idf_begin(OldBB), E = idf_end(OldBB); I != E;) { 699 const BasicBlock *BB = *I; 700 if (BB == NewBB) { 701 // Stop traversal when reaching HoistPt. 702 I.skipChildren(); 703 continue; 704 } 705 706 if (hasEHhelper(BB, OldBB, NBBsOnAllPaths)) 707 return true; 708 709 // Check that we do not move a store past loads. 710 if (hasMemoryUse(NewPt, Def, BB)) 711 return true; 712 713 // -1 is unlimited number of blocks on all paths. 714 if (NBBsOnAllPaths != -1) 715 --NBBsOnAllPaths; 716 717 ++I; 718 } 719 720 return false; 721 } 722 723 bool GVNHoist::hasEHOnPath(const BasicBlock *HoistPt, const BasicBlock *SrcBB, 724 int &NBBsOnAllPaths) { 725 assert(DT->dominates(HoistPt, SrcBB) && "Invalid path"); 726 727 // Walk all basic blocks reachable in depth-first iteration on 728 // the inverse CFG from BBInsn to NewHoistPt. These blocks are all the 729 // blocks that may be executed between the execution of NewHoistPt and 730 // BBInsn. Hoisting an expression from BBInsn into NewHoistPt has to be safe 731 // on all execution paths. 732 for (auto I = idf_begin(SrcBB), E = idf_end(SrcBB); I != E;) { 733 const BasicBlock *BB = *I; 734 if (BB == HoistPt) { 735 // Stop traversal when reaching NewHoistPt. 736 I.skipChildren(); 737 continue; 738 } 739 740 if (hasEHhelper(BB, SrcBB, NBBsOnAllPaths)) 741 return true; 742 743 // -1 is unlimited number of blocks on all paths. 744 if (NBBsOnAllPaths != -1) 745 --NBBsOnAllPaths; 746 747 ++I; 748 } 749 750 return false; 751 } 752 753 bool GVNHoist::safeToHoistLdSt(const Instruction *NewPt, 754 const Instruction *OldPt, MemoryUseOrDef *U, 755 GVNHoist::InsKind K, int &NBBsOnAllPaths) { 756 // In place hoisting is safe. 757 if (NewPt == OldPt) 758 return true; 759 760 const BasicBlock *NewBB = NewPt->getParent(); 761 const BasicBlock *OldBB = OldPt->getParent(); 762 const BasicBlock *UBB = U->getBlock(); 763 764 // Check for dependences on the Memory SSA. 765 MemoryAccess *D = U->getDefiningAccess(); 766 BasicBlock *DBB = D->getBlock(); 767 if (DT->properlyDominates(NewBB, DBB)) 768 // Cannot move the load or store to NewBB above its definition in DBB. 769 return false; 770 771 if (NewBB == DBB && !MSSA->isLiveOnEntryDef(D)) 772 if (auto *UD = dyn_cast<MemoryUseOrDef>(D)) 773 if (!firstInBB(UD->getMemoryInst(), NewPt)) 774 // Cannot move the load or store to NewPt above its definition in D. 775 return false; 776 777 // Check for unsafe hoistings due to side effects. 778 if (K == InsKind::Store) { 779 if (hasEHOrLoadsOnPath(NewPt, cast<MemoryDef>(U), NBBsOnAllPaths)) 780 return false; 781 } else if (hasEHOnPath(NewBB, OldBB, NBBsOnAllPaths)) 782 return false; 783 784 if (UBB == NewBB) { 785 if (DT->properlyDominates(DBB, NewBB)) 786 return true; 787 assert(UBB == DBB); 788 assert(MSSA->locallyDominates(D, U)); 789 } 790 791 // No side effects: it is safe to hoist. 792 return true; 793 } 794 795 bool GVNHoist::valueAnticipable(CHIArgs C, Instruction *TI) const { 796 if (TI->getNumSuccessors() > (unsigned)size(C)) 797 return false; // Not enough args in this CHI. 798 799 for (auto CHI : C) { 800 // Find if all the edges have values flowing out of BB. 801 if (!llvm::is_contained(successors(TI), CHI.Dest)) 802 return false; 803 } 804 return true; 805 } 806 807 void GVNHoist::checkSafety(CHIArgs C, BasicBlock *BB, GVNHoist::InsKind K, 808 SmallVectorImpl<CHIArg> &Safe) { 809 int NumBBsOnAllPaths = MaxNumberOfBBSInPath; 810 for (auto CHI : C) { 811 Instruction *Insn = CHI.I; 812 if (!Insn) // No instruction was inserted in this CHI. 813 continue; 814 if (K == InsKind::Scalar) { 815 if (safeToHoistScalar(BB, Insn->getParent(), NumBBsOnAllPaths)) 816 Safe.push_back(CHI); 817 } else { 818 auto *T = BB->getTerminator(); 819 if (MemoryUseOrDef *UD = MSSA->getMemoryAccess(Insn)) 820 if (safeToHoistLdSt(T, Insn, UD, K, NumBBsOnAllPaths)) 821 Safe.push_back(CHI); 822 } 823 } 824 } 825 826 void GVNHoist::fillRenameStack(BasicBlock *BB, InValuesType &ValueBBs, 827 GVNHoist::RenameStackType &RenameStack) { 828 auto it1 = ValueBBs.find(BB); 829 if (it1 != ValueBBs.end()) { 830 // Iterate in reverse order to keep lower ranked values on the top. 831 for (std::pair<VNType, Instruction *> &VI : reverse(it1->second)) { 832 // Get the value of instruction I 833 LLVM_DEBUG(dbgs() << "\nPushing on stack: " << *VI.second); 834 RenameStack[VI.first].push_back(VI.second); 835 } 836 } 837 } 838 839 void GVNHoist::fillChiArgs(BasicBlock *BB, OutValuesType &CHIBBs, 840 GVNHoist::RenameStackType &RenameStack) { 841 // For each *predecessor* (because Post-DOM) of BB check if it has a CHI 842 for (auto Pred : predecessors(BB)) { 843 auto P = CHIBBs.find(Pred); 844 if (P == CHIBBs.end()) { 845 continue; 846 } 847 LLVM_DEBUG(dbgs() << "\nLooking at CHIs in: " << Pred->getName();); 848 // A CHI is found (BB -> Pred is an edge in the CFG) 849 // Pop the stack until Top(V) = Ve. 850 auto &VCHI = P->second; 851 for (auto It = VCHI.begin(), E = VCHI.end(); It != E;) { 852 CHIArg &C = *It; 853 if (!C.Dest) { 854 auto si = RenameStack.find(C.VN); 855 // The Basic Block where CHI is must dominate the value we want to 856 // track in a CHI. In the PDom walk, there can be values in the 857 // stack which are not control dependent e.g., nested loop. 858 if (si != RenameStack.end() && si->second.size() && 859 DT->properlyDominates(Pred, si->second.back()->getParent())) { 860 C.Dest = BB; // Assign the edge 861 C.I = si->second.pop_back_val(); // Assign the argument 862 LLVM_DEBUG(dbgs() 863 << "\nCHI Inserted in BB: " << C.Dest->getName() << *C.I 864 << ", VN: " << C.VN.first << ", " << C.VN.second); 865 } 866 // Move to next CHI of a different value 867 It = std::find_if(It, VCHI.end(), [It](CHIArg &A) { return A != *It; }); 868 } else 869 ++It; 870 } 871 } 872 } 873 874 void GVNHoist::findHoistableCandidates(OutValuesType &CHIBBs, 875 GVNHoist::InsKind K, 876 HoistingPointList &HPL) { 877 auto cmpVN = [](const CHIArg &A, const CHIArg &B) { return A.VN < B.VN; }; 878 879 // CHIArgs now have the outgoing values, so check for anticipability and 880 // accumulate hoistable candidates in HPL. 881 for (std::pair<BasicBlock *, SmallVector<CHIArg, 2>> &A : CHIBBs) { 882 BasicBlock *BB = A.first; 883 SmallVectorImpl<CHIArg> &CHIs = A.second; 884 // Vector of PHIs contains PHIs for different instructions. 885 // Sort the args according to their VNs, such that identical 886 // instructions are together. 887 llvm::stable_sort(CHIs, cmpVN); 888 auto TI = BB->getTerminator(); 889 auto B = CHIs.begin(); 890 // [PreIt, PHIIt) form a range of CHIs which have identical VNs. 891 auto PHIIt = llvm::find_if(CHIs, [B](CHIArg &A) { return A != *B; }); 892 auto PrevIt = CHIs.begin(); 893 while (PrevIt != PHIIt) { 894 // Collect values which satisfy safety checks. 895 SmallVector<CHIArg, 2> Safe; 896 // We check for safety first because there might be multiple values in 897 // the same path, some of which are not safe to be hoisted, but overall 898 // each edge has at least one value which can be hoisted, making the 899 // value anticipable along that path. 900 checkSafety(make_range(PrevIt, PHIIt), BB, K, Safe); 901 902 // List of safe values should be anticipable at TI. 903 if (valueAnticipable(make_range(Safe.begin(), Safe.end()), TI)) { 904 HPL.push_back({BB, SmallVecInsn()}); 905 SmallVecInsn &V = HPL.back().second; 906 for (auto B : Safe) 907 V.push_back(B.I); 908 } 909 910 // Check other VNs 911 PrevIt = PHIIt; 912 PHIIt = std::find_if(PrevIt, CHIs.end(), 913 [PrevIt](CHIArg &A) { return A != *PrevIt; }); 914 } 915 } 916 } 917 918 bool GVNHoist::allOperandsAvailable(const Instruction *I, 919 const BasicBlock *HoistPt) const { 920 for (const Use &Op : I->operands()) 921 if (const auto *Inst = dyn_cast<Instruction>(&Op)) 922 if (!DT->dominates(Inst->getParent(), HoistPt)) 923 return false; 924 925 return true; 926 } 927 928 bool GVNHoist::allGepOperandsAvailable(const Instruction *I, 929 const BasicBlock *HoistPt) const { 930 for (const Use &Op : I->operands()) 931 if (const auto *Inst = dyn_cast<Instruction>(&Op)) 932 if (!DT->dominates(Inst->getParent(), HoistPt)) { 933 if (const GetElementPtrInst *GepOp = 934 dyn_cast<GetElementPtrInst>(Inst)) { 935 if (!allGepOperandsAvailable(GepOp, HoistPt)) 936 return false; 937 // Gep is available if all operands of GepOp are available. 938 } else { 939 // Gep is not available if it has operands other than GEPs that are 940 // defined in blocks not dominating HoistPt. 941 return false; 942 } 943 } 944 return true; 945 } 946 947 void GVNHoist::makeGepsAvailable(Instruction *Repl, BasicBlock *HoistPt, 948 const SmallVecInsn &InstructionsToHoist, 949 Instruction *Gep) const { 950 assert(allGepOperandsAvailable(Gep, HoistPt) && "GEP operands not available"); 951 952 Instruction *ClonedGep = Gep->clone(); 953 for (unsigned i = 0, e = Gep->getNumOperands(); i != e; ++i) 954 if (Instruction *Op = dyn_cast<Instruction>(Gep->getOperand(i))) { 955 // Check whether the operand is already available. 956 if (DT->dominates(Op->getParent(), HoistPt)) 957 continue; 958 959 // As a GEP can refer to other GEPs, recursively make all the operands 960 // of this GEP available at HoistPt. 961 if (GetElementPtrInst *GepOp = dyn_cast<GetElementPtrInst>(Op)) 962 makeGepsAvailable(ClonedGep, HoistPt, InstructionsToHoist, GepOp); 963 } 964 965 // Copy Gep and replace its uses in Repl with ClonedGep. 966 ClonedGep->insertBefore(HoistPt->getTerminator()); 967 968 // Conservatively discard any optimization hints, they may differ on the 969 // other paths. 970 ClonedGep->dropUnknownNonDebugMetadata(); 971 972 // If we have optimization hints which agree with each other along different 973 // paths, preserve them. 974 for (const Instruction *OtherInst : InstructionsToHoist) { 975 const GetElementPtrInst *OtherGep; 976 if (auto *OtherLd = dyn_cast<LoadInst>(OtherInst)) 977 OtherGep = cast<GetElementPtrInst>(OtherLd->getPointerOperand()); 978 else 979 OtherGep = cast<GetElementPtrInst>( 980 cast<StoreInst>(OtherInst)->getPointerOperand()); 981 ClonedGep->andIRFlags(OtherGep); 982 } 983 984 // Replace uses of Gep with ClonedGep in Repl. 985 Repl->replaceUsesOfWith(Gep, ClonedGep); 986 } 987 988 void GVNHoist::updateAlignment(Instruction *I, Instruction *Repl) { 989 if (auto *ReplacementLoad = dyn_cast<LoadInst>(Repl)) { 990 ReplacementLoad->setAlignment( 991 std::min(ReplacementLoad->getAlign(), cast<LoadInst>(I)->getAlign())); 992 ++NumLoadsRemoved; 993 } else if (auto *ReplacementStore = dyn_cast<StoreInst>(Repl)) { 994 ReplacementStore->setAlignment( 995 std::min(ReplacementStore->getAlign(), cast<StoreInst>(I)->getAlign())); 996 ++NumStoresRemoved; 997 } else if (auto *ReplacementAlloca = dyn_cast<AllocaInst>(Repl)) { 998 ReplacementAlloca->setAlignment(std::max(ReplacementAlloca->getAlign(), 999 cast<AllocaInst>(I)->getAlign())); 1000 } else if (isa<CallInst>(Repl)) { 1001 ++NumCallsRemoved; 1002 } 1003 } 1004 1005 unsigned GVNHoist::rauw(const SmallVecInsn &Candidates, Instruction *Repl, 1006 MemoryUseOrDef *NewMemAcc) { 1007 unsigned NR = 0; 1008 for (Instruction *I : Candidates) { 1009 if (I != Repl) { 1010 ++NR; 1011 updateAlignment(I, Repl); 1012 if (NewMemAcc) { 1013 // Update the uses of the old MSSA access with NewMemAcc. 1014 MemoryAccess *OldMA = MSSA->getMemoryAccess(I); 1015 OldMA->replaceAllUsesWith(NewMemAcc); 1016 MSSAUpdater->removeMemoryAccess(OldMA); 1017 } 1018 1019 Repl->andIRFlags(I); 1020 combineKnownMetadata(Repl, I); 1021 I->replaceAllUsesWith(Repl); 1022 // Also invalidate the Alias Analysis cache. 1023 MD->removeInstruction(I); 1024 I->eraseFromParent(); 1025 } 1026 } 1027 return NR; 1028 } 1029 1030 void GVNHoist::raMPHIuw(MemoryUseOrDef *NewMemAcc) { 1031 SmallPtrSet<MemoryPhi *, 4> UsePhis; 1032 for (User *U : NewMemAcc->users()) 1033 if (MemoryPhi *Phi = dyn_cast<MemoryPhi>(U)) 1034 UsePhis.insert(Phi); 1035 1036 for (MemoryPhi *Phi : UsePhis) { 1037 auto In = Phi->incoming_values(); 1038 if (llvm::all_of(In, [&](Use &U) { return U == NewMemAcc; })) { 1039 Phi->replaceAllUsesWith(NewMemAcc); 1040 MSSAUpdater->removeMemoryAccess(Phi); 1041 } 1042 } 1043 } 1044 1045 unsigned GVNHoist::removeAndReplace(const SmallVecInsn &Candidates, 1046 Instruction *Repl, BasicBlock *DestBB, 1047 bool MoveAccess) { 1048 MemoryUseOrDef *NewMemAcc = MSSA->getMemoryAccess(Repl); 1049 if (MoveAccess && NewMemAcc) { 1050 // The definition of this ld/st will not change: ld/st hoisting is 1051 // legal when the ld/st is not moved past its current definition. 1052 MSSAUpdater->moveToPlace(NewMemAcc, DestBB, MemorySSA::BeforeTerminator); 1053 } 1054 1055 // Replace all other instructions with Repl with memory access NewMemAcc. 1056 unsigned NR = rauw(Candidates, Repl, NewMemAcc); 1057 1058 // Remove MemorySSA phi nodes with the same arguments. 1059 if (NewMemAcc) 1060 raMPHIuw(NewMemAcc); 1061 return NR; 1062 } 1063 1064 bool GVNHoist::makeGepOperandsAvailable( 1065 Instruction *Repl, BasicBlock *HoistPt, 1066 const SmallVecInsn &InstructionsToHoist) const { 1067 // Check whether the GEP of a ld/st can be synthesized at HoistPt. 1068 GetElementPtrInst *Gep = nullptr; 1069 Instruction *Val = nullptr; 1070 if (auto *Ld = dyn_cast<LoadInst>(Repl)) { 1071 Gep = dyn_cast<GetElementPtrInst>(Ld->getPointerOperand()); 1072 } else if (auto *St = dyn_cast<StoreInst>(Repl)) { 1073 Gep = dyn_cast<GetElementPtrInst>(St->getPointerOperand()); 1074 Val = dyn_cast<Instruction>(St->getValueOperand()); 1075 // Check that the stored value is available. 1076 if (Val) { 1077 if (isa<GetElementPtrInst>(Val)) { 1078 // Check whether we can compute the GEP at HoistPt. 1079 if (!allGepOperandsAvailable(Val, HoistPt)) 1080 return false; 1081 } else if (!DT->dominates(Val->getParent(), HoistPt)) 1082 return false; 1083 } 1084 } 1085 1086 // Check whether we can compute the Gep at HoistPt. 1087 if (!Gep || !allGepOperandsAvailable(Gep, HoistPt)) 1088 return false; 1089 1090 makeGepsAvailable(Repl, HoistPt, InstructionsToHoist, Gep); 1091 1092 if (Val && isa<GetElementPtrInst>(Val)) 1093 makeGepsAvailable(Repl, HoistPt, InstructionsToHoist, Val); 1094 1095 return true; 1096 } 1097 1098 std::pair<unsigned, unsigned> GVNHoist::hoist(HoistingPointList &HPL) { 1099 unsigned NI = 0, NL = 0, NS = 0, NC = 0, NR = 0; 1100 for (const HoistingPointInfo &HP : HPL) { 1101 // Find out whether we already have one of the instructions in HoistPt, 1102 // in which case we do not have to move it. 1103 BasicBlock *DestBB = HP.first; 1104 const SmallVecInsn &InstructionsToHoist = HP.second; 1105 Instruction *Repl = nullptr; 1106 for (Instruction *I : InstructionsToHoist) 1107 if (I->getParent() == DestBB) 1108 // If there are two instructions in HoistPt to be hoisted in place: 1109 // update Repl to be the first one, such that we can rename the uses 1110 // of the second based on the first. 1111 if (!Repl || firstInBB(I, Repl)) 1112 Repl = I; 1113 1114 // Keep track of whether we moved the instruction so we know whether we 1115 // should move the MemoryAccess. 1116 bool MoveAccess = true; 1117 if (Repl) { 1118 // Repl is already in HoistPt: it remains in place. 1119 assert(allOperandsAvailable(Repl, DestBB) && 1120 "instruction depends on operands that are not available"); 1121 MoveAccess = false; 1122 } else { 1123 // When we do not find Repl in HoistPt, select the first in the list 1124 // and move it to HoistPt. 1125 Repl = InstructionsToHoist.front(); 1126 1127 // We can move Repl in HoistPt only when all operands are available. 1128 // The order in which hoistings are done may influence the availability 1129 // of operands. 1130 if (!allOperandsAvailable(Repl, DestBB)) { 1131 // When HoistingGeps there is nothing more we can do to make the 1132 // operands available: just continue. 1133 if (HoistingGeps) 1134 continue; 1135 1136 // When not HoistingGeps we need to copy the GEPs. 1137 if (!makeGepOperandsAvailable(Repl, DestBB, InstructionsToHoist)) 1138 continue; 1139 } 1140 1141 // Move the instruction at the end of HoistPt. 1142 Instruction *Last = DestBB->getTerminator(); 1143 MD->removeInstruction(Repl); 1144 Repl->moveBefore(Last); 1145 1146 DFSNumber[Repl] = DFSNumber[Last]++; 1147 } 1148 1149 NR += removeAndReplace(InstructionsToHoist, Repl, DestBB, MoveAccess); 1150 1151 if (isa<LoadInst>(Repl)) 1152 ++NL; 1153 else if (isa<StoreInst>(Repl)) 1154 ++NS; 1155 else if (isa<CallInst>(Repl)) 1156 ++NC; 1157 else // Scalar 1158 ++NI; 1159 } 1160 1161 if (MSSA && VerifyMemorySSA) 1162 MSSA->verifyMemorySSA(); 1163 1164 NumHoisted += NL + NS + NC + NI; 1165 NumRemoved += NR; 1166 NumLoadsHoisted += NL; 1167 NumStoresHoisted += NS; 1168 NumCallsHoisted += NC; 1169 return {NI, NL + NC + NS}; 1170 } 1171 1172 std::pair<unsigned, unsigned> GVNHoist::hoistExpressions(Function &F) { 1173 InsnInfo II; 1174 LoadInfo LI; 1175 StoreInfo SI; 1176 CallInfo CI; 1177 for (BasicBlock *BB : depth_first(&F.getEntryBlock())) { 1178 int InstructionNb = 0; 1179 for (Instruction &I1 : *BB) { 1180 // If I1 cannot guarantee progress, subsequent instructions 1181 // in BB cannot be hoisted anyways. 1182 if (!isGuaranteedToTransferExecutionToSuccessor(&I1)) { 1183 HoistBarrier.insert(BB); 1184 break; 1185 } 1186 // Only hoist the first instructions in BB up to MaxDepthInBB. Hoisting 1187 // deeper may increase the register pressure and compilation time. 1188 if (MaxDepthInBB != -1 && InstructionNb++ >= MaxDepthInBB) 1189 break; 1190 1191 // Do not value number terminator instructions. 1192 if (I1.isTerminator()) 1193 break; 1194 1195 if (auto *Load = dyn_cast<LoadInst>(&I1)) 1196 LI.insert(Load, VN); 1197 else if (auto *Store = dyn_cast<StoreInst>(&I1)) 1198 SI.insert(Store, VN); 1199 else if (auto *Call = dyn_cast<CallInst>(&I1)) { 1200 if (auto *Intr = dyn_cast<IntrinsicInst>(Call)) { 1201 if (isa<DbgInfoIntrinsic>(Intr) || 1202 Intr->getIntrinsicID() == Intrinsic::assume || 1203 Intr->getIntrinsicID() == Intrinsic::sideeffect) 1204 continue; 1205 } 1206 if (Call->mayHaveSideEffects()) 1207 break; 1208 1209 if (Call->isConvergent()) 1210 break; 1211 1212 CI.insert(Call, VN); 1213 } else if (HoistingGeps || !isa<GetElementPtrInst>(&I1)) 1214 // Do not hoist scalars past calls that may write to memory because 1215 // that could result in spills later. geps are handled separately. 1216 // TODO: We can relax this for targets like AArch64 as they have more 1217 // registers than X86. 1218 II.insert(&I1, VN); 1219 } 1220 } 1221 1222 HoistingPointList HPL; 1223 computeInsertionPoints(II.getVNTable(), HPL, InsKind::Scalar); 1224 computeInsertionPoints(LI.getVNTable(), HPL, InsKind::Load); 1225 computeInsertionPoints(SI.getVNTable(), HPL, InsKind::Store); 1226 computeInsertionPoints(CI.getScalarVNTable(), HPL, InsKind::Scalar); 1227 computeInsertionPoints(CI.getLoadVNTable(), HPL, InsKind::Load); 1228 computeInsertionPoints(CI.getStoreVNTable(), HPL, InsKind::Store); 1229 return hoist(HPL); 1230 } 1231 1232 } // end namespace llvm 1233 1234 PreservedAnalyses GVNHoistPass::run(Function &F, FunctionAnalysisManager &AM) { 1235 DominatorTree &DT = AM.getResult<DominatorTreeAnalysis>(F); 1236 PostDominatorTree &PDT = AM.getResult<PostDominatorTreeAnalysis>(F); 1237 AliasAnalysis &AA = AM.getResult<AAManager>(F); 1238 MemoryDependenceResults &MD = AM.getResult<MemoryDependenceAnalysis>(F); 1239 MemorySSA &MSSA = AM.getResult<MemorySSAAnalysis>(F).getMSSA(); 1240 GVNHoist G(&DT, &PDT, &AA, &MD, &MSSA); 1241 if (!G.run(F)) 1242 return PreservedAnalyses::all(); 1243 1244 PreservedAnalyses PA; 1245 PA.preserve<DominatorTreeAnalysis>(); 1246 PA.preserve<MemorySSAAnalysis>(); 1247 PA.preserve<GlobalsAA>(); 1248 return PA; 1249 } 1250 1251 char GVNHoistLegacyPass::ID = 0; 1252 1253 INITIALIZE_PASS_BEGIN(GVNHoistLegacyPass, "gvn-hoist", 1254 "Early GVN Hoisting of Expressions", false, false) 1255 INITIALIZE_PASS_DEPENDENCY(MemoryDependenceWrapperPass) 1256 INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass) 1257 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 1258 INITIALIZE_PASS_DEPENDENCY(PostDominatorTreeWrapperPass) 1259 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass) 1260 INITIALIZE_PASS_END(GVNHoistLegacyPass, "gvn-hoist", 1261 "Early GVN Hoisting of Expressions", false, false) 1262 1263 FunctionPass *llvm::createGVNHoistPass() { return new GVNHoistLegacyPass(); } 1264