1 //===- MergedLoadStoreMotion.cpp - merge and hoist/sink load/stores -------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 //! \file 11 //! \brief This pass performs merges of loads and stores on both sides of a 12 // diamond (hammock). It hoists the loads and sinks the stores. 13 // 14 // The algorithm iteratively hoists two loads to the same address out of a 15 // diamond (hammock) and merges them into a single load in the header. Similar 16 // it sinks and merges two stores to the tail block (footer). The algorithm 17 // iterates over the instructions of one side of the diamond and attempts to 18 // find a matching load/store on the other side. It hoists / sinks when it 19 // thinks it safe to do so. This optimization helps with eg. hiding load 20 // latencies, triggering if-conversion, and reducing static code size. 21 // 22 //===----------------------------------------------------------------------===// 23 // 24 // 25 // Example: 26 // Diamond shaped code before merge: 27 // 28 // header: 29 // br %cond, label %if.then, label %if.else 30 // + + 31 // + + 32 // + + 33 // if.then: if.else: 34 // %lt = load %addr_l %le = load %addr_l 35 // <use %lt> <use %le> 36 // <...> <...> 37 // store %st, %addr_s store %se, %addr_s 38 // br label %if.end br label %if.end 39 // + + 40 // + + 41 // + + 42 // if.end ("footer"): 43 // <...> 44 // 45 // Diamond shaped code after merge: 46 // 47 // header: 48 // %l = load %addr_l 49 // br %cond, label %if.then, label %if.else 50 // + + 51 // + + 52 // + + 53 // if.then: if.else: 54 // <use %l> <use %l> 55 // <...> <...> 56 // br label %if.end br label %if.end 57 // + + 58 // + + 59 // + + 60 // if.end ("footer"): 61 // %s.sink = phi [%st, if.then], [%se, if.else] 62 // <...> 63 // store %s.sink, %addr_s 64 // <...> 65 // 66 // 67 //===----------------------- TODO -----------------------------------------===// 68 // 69 // 1) Generalize to regions other than diamonds 70 // 2) Be more aggressive merging memory operations 71 // Note that both changes require register pressure control 72 // 73 //===----------------------------------------------------------------------===// 74 75 #include "llvm/Transforms/Scalar/MergedLoadStoreMotion.h" 76 #include "llvm/ADT/Statistic.h" 77 #include "llvm/Analysis/AliasAnalysis.h" 78 #include "llvm/Analysis/CFG.h" 79 #include "llvm/Analysis/GlobalsModRef.h" 80 #include "llvm/Analysis/Loads.h" 81 #include "llvm/Analysis/MemoryBuiltins.h" 82 #include "llvm/Analysis/MemoryDependenceAnalysis.h" 83 #include "llvm/Analysis/ValueTracking.h" 84 #include "llvm/IR/Metadata.h" 85 #include "llvm/IR/PatternMatch.h" 86 #include "llvm/Support/Debug.h" 87 #include "llvm/Support/raw_ostream.h" 88 #include "llvm/Transforms/Scalar.h" 89 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 90 #include "llvm/Transforms/Utils/SSAUpdater.h" 91 92 using namespace llvm; 93 94 #define DEBUG_TYPE "mldst-motion" 95 96 //===----------------------------------------------------------------------===// 97 // MergedLoadStoreMotion Pass 98 //===----------------------------------------------------------------------===// 99 100 // The mergeLoad/Store algorithms could have Size0 * Size1 complexity, 101 // where Size0 and Size1 are the #instructions on the two sides of 102 // the diamond. The constant chosen here is arbitrary. Compiler Time 103 // Control is enforced by the check Size0 * Size1 < MagicCompileTimeControl. 104 const int MagicCompileTimeControl = 250; 105 106 /// 107 /// \brief Remove instruction from parent and update memory dependence analysis. 108 /// 109 static void removeInstruction(Instruction *Inst, MemoryDependenceResults *MD) { 110 // Notify the memory dependence analysis. 111 if (MD) { 112 MD->removeInstruction(Inst); 113 if (auto *LI = dyn_cast<LoadInst>(Inst)) 114 MD->invalidateCachedPointerInfo(LI->getPointerOperand()); 115 if (Inst->getType()->isPtrOrPtrVectorTy()) { 116 MD->invalidateCachedPointerInfo(Inst); 117 } 118 } 119 Inst->eraseFromParent(); 120 } 121 122 /// 123 /// \brief True when BB is the head of a diamond (hammock) 124 /// 125 static bool isDiamondHead(BasicBlock *BB) { 126 if (!BB) 127 return false; 128 auto *BI = dyn_cast<BranchInst>(BB->getTerminator()); 129 if (!BI || !BI->isConditional()) 130 return false; 131 132 BasicBlock *Succ0 = BI->getSuccessor(0); 133 BasicBlock *Succ1 = BI->getSuccessor(1); 134 135 if (!Succ0->getSinglePredecessor()) 136 return false; 137 if (!Succ1->getSinglePredecessor()) 138 return false; 139 140 BasicBlock *Succ0Succ = Succ0->getSingleSuccessor(); 141 BasicBlock *Succ1Succ = Succ1->getSingleSuccessor(); 142 // Ignore triangles. 143 if (!Succ0Succ || !Succ1Succ || Succ0Succ != Succ1Succ) 144 return false; 145 return true; 146 } 147 148 /// 149 /// \brief Return tail block of a diamond. 150 /// 151 static BasicBlock *getDiamondTail(BasicBlock *BB) { 152 assert(isDiamondHead(BB) && "Basic block is not head of a diamond"); 153 return BB->getTerminator()->getSuccessor(0)->getSingleSuccessor(); 154 } 155 156 /// 157 /// \brief True when instruction is a hoist barrier for a load 158 /// 159 /// Whenever an instruction could possibly modify the value 160 /// being loaded or protect against the load from happening 161 /// it is considered a hoist barrier. 162 /// 163 static bool isLoadHoistBarrierInRange(const Instruction &Start, 164 const Instruction &End, LoadInst *LI, 165 bool SafeToLoadUnconditionally, 166 AliasAnalysis *AA) { 167 if (!SafeToLoadUnconditionally) 168 for (const Instruction &Inst : 169 make_range(Start.getIterator(), End.getIterator())) 170 if (!isGuaranteedToTransferExecutionToSuccessor(&Inst)) 171 return true; 172 MemoryLocation Loc = MemoryLocation::get(LI); 173 return AA->canInstructionRangeModRef(Start, End, Loc, MRI_Mod); 174 } 175 176 /// 177 /// \brief Decide if a load can be hoisted 178 /// 179 /// When there is a load in \p BB to the same address as \p LI 180 /// and it can be hoisted from \p BB, return that load. 181 /// Otherwise return Null. 182 /// 183 static LoadInst *canHoistFromBlock(BasicBlock *BB1, LoadInst *Load0, 184 AliasAnalysis *AA) { 185 BasicBlock *BB0 = Load0->getParent(); 186 BasicBlock *Head = BB0->getSinglePredecessor(); 187 bool SafeToLoadUnconditionally = isSafeToLoadUnconditionally( 188 Load0->getPointerOperand(), Load0->getAlignment(), 189 Load0->getModule()->getDataLayout(), 190 /*ScanFrom=*/Head->getTerminator()); 191 for (BasicBlock::iterator BBI = BB1->begin(), BBE = BB1->end(); BBI != BBE; 192 ++BBI) { 193 Instruction *Inst = &*BBI; 194 195 // Only merge and hoist loads when their result in used only in BB 196 auto *Load1 = dyn_cast<LoadInst>(Inst); 197 if (!Load1 || Inst->isUsedOutsideOfBlock(BB1)) 198 continue; 199 200 MemoryLocation Loc0 = MemoryLocation::get(Load0); 201 MemoryLocation Loc1 = MemoryLocation::get(Load1); 202 if (AA->isMustAlias(Loc0, Loc1) && Load0->isSameOperationAs(Load1) && 203 !isLoadHoistBarrierInRange(BB1->front(), *Load1, Load1, 204 SafeToLoadUnconditionally, AA) && 205 !isLoadHoistBarrierInRange(BB0->front(), *Load0, Load0, 206 SafeToLoadUnconditionally, AA)) { 207 return Load1; 208 } 209 } 210 return nullptr; 211 } 212 213 /// 214 /// \brief Merge two equivalent instructions \p HoistCand and \p ElseInst into 215 /// \p BB 216 /// 217 /// BB is the head of a diamond 218 /// 219 static void hoistInstruction(BasicBlock *BB, Instruction *HoistCand, 220 Instruction *ElseInst, 221 MemoryDependenceResults *MD) { 222 DEBUG(dbgs() << " Hoist Instruction into BB \n"; BB->dump(); 223 dbgs() << "Instruction Left\n"; HoistCand->dump(); dbgs() << "\n"; 224 dbgs() << "Instruction Right\n"; ElseInst->dump(); dbgs() << "\n"); 225 // Hoist the instruction. 226 assert(HoistCand->getParent() != BB); 227 228 // Intersect optional metadata. 229 HoistCand->intersectOptionalDataWith(ElseInst); 230 HoistCand->dropUnknownNonDebugMetadata(); 231 232 // Prepend point for instruction insert 233 Instruction *HoistPt = BB->getTerminator(); 234 235 // Merged instruction 236 Instruction *HoistedInst = HoistCand->clone(); 237 238 // Hoist instruction. 239 HoistedInst->insertBefore(HoistPt); 240 241 HoistCand->replaceAllUsesWith(HoistedInst); 242 removeInstruction(HoistCand, MD); 243 // Replace the else block instruction. 244 ElseInst->replaceAllUsesWith(HoistedInst); 245 removeInstruction(ElseInst, MD); 246 } 247 248 /// 249 /// \brief Return true if no operand of \p I is defined in I's parent block 250 /// 251 static bool isSafeToHoist(Instruction *I) { 252 BasicBlock *Parent = I->getParent(); 253 for (Use &U : I->operands()) 254 if (auto *Instr = dyn_cast<Instruction>(&U)) 255 if (Instr->getParent() == Parent) 256 return false; 257 return true; 258 } 259 260 /// 261 /// \brief Merge two equivalent loads and GEPs and hoist into diamond head 262 /// 263 static bool hoistLoad(BasicBlock *BB, LoadInst *L0, LoadInst *L1, 264 MemoryDependenceResults *MD) { 265 // Only one definition? 266 auto *A0 = dyn_cast<Instruction>(L0->getPointerOperand()); 267 auto *A1 = dyn_cast<Instruction>(L1->getPointerOperand()); 268 if (A0 && A1 && A0->isIdenticalTo(A1) && isSafeToHoist(A0) && 269 A0->hasOneUse() && (A0->getParent() == L0->getParent()) && 270 A1->hasOneUse() && (A1->getParent() == L1->getParent()) && 271 isa<GetElementPtrInst>(A0)) { 272 DEBUG(dbgs() << "Hoist Instruction into BB \n"; BB->dump(); 273 dbgs() << "Instruction Left\n"; L0->dump(); dbgs() << "\n"; 274 dbgs() << "Instruction Right\n"; L1->dump(); dbgs() << "\n"); 275 hoistInstruction(BB, A0, A1, MD); 276 hoistInstruction(BB, L0, L1, MD); 277 return true; 278 } 279 return false; 280 } 281 282 /// 283 /// \brief Try to hoist two loads to same address into diamond header 284 /// 285 /// Starting from a diamond head block, iterate over the instructions in one 286 /// successor block and try to match a load in the second successor. 287 /// 288 static bool mergeLoads(BasicBlock *BB, AliasAnalysis *AA, 289 MemoryDependenceResults *MD) { 290 bool MergedLoads = false; 291 assert(isDiamondHead(BB)); 292 BranchInst *BI = cast<BranchInst>(BB->getTerminator()); 293 BasicBlock *Succ0 = BI->getSuccessor(0); 294 BasicBlock *Succ1 = BI->getSuccessor(1); 295 // #Instructions in Succ1 for Compile Time Control 296 int Size1 = Succ1->size(); 297 int NLoads = 0; 298 for (BasicBlock::iterator BBI = Succ0->begin(), BBE = Succ0->end(); 299 BBI != BBE;) { 300 Instruction *I = &*BBI; 301 ++BBI; 302 303 // Don't move non-simple (atomic, volatile) loads. 304 auto *L0 = dyn_cast<LoadInst>(I); 305 if (!L0 || !L0->isSimple() || L0->isUsedOutsideOfBlock(Succ0)) 306 continue; 307 308 ++NLoads; 309 if (NLoads * Size1 >= MagicCompileTimeControl) 310 break; 311 if (LoadInst *L1 = canHoistFromBlock(Succ1, L0, AA)) { 312 bool Res = hoistLoad(BB, L0, L1, MD); 313 MergedLoads |= Res; 314 // Don't attempt to hoist above loads that had not been hoisted. 315 if (!Res) 316 break; 317 } 318 } 319 return MergedLoads; 320 } 321 322 /// 323 /// \brief True when instruction is a sink barrier for a store 324 /// located in Loc 325 /// 326 /// Whenever an instruction could possibly read or modify the 327 /// value being stored or protect against the store from 328 /// happening it is considered a sink barrier. 329 /// 330 static bool isStoreSinkBarrierInRange(const Instruction &Start, 331 const Instruction &End, 332 MemoryLocation Loc, AliasAnalysis *AA) { 333 for (const Instruction &Inst : 334 make_range(Start.getIterator(), End.getIterator())) 335 if (Inst.mayThrow()) 336 return true; 337 return AA->canInstructionRangeModRef(Start, End, Loc, MRI_ModRef); 338 } 339 340 /// 341 /// \brief Check if \p BB contains a store to the same address as \p SI 342 /// 343 /// \return The store in \p when it is safe to sink. Otherwise return Null. 344 /// 345 static StoreInst *canSinkFromBlock(BasicBlock *BB1, StoreInst *Store0, 346 AliasAnalysis *AA) { 347 DEBUG(dbgs() << "can Sink? : "; Store0->dump(); dbgs() << "\n"); 348 BasicBlock *BB0 = Store0->getParent(); 349 for (BasicBlock::reverse_iterator RBI = BB1->rbegin(), RBE = BB1->rend(); 350 RBI != RBE; ++RBI) { 351 Instruction *Inst = &*RBI; 352 353 auto *Store1 = dyn_cast<StoreInst>(Inst); 354 if (!Store1) 355 continue; 356 357 MemoryLocation Loc0 = MemoryLocation::get(Store0); 358 MemoryLocation Loc1 = MemoryLocation::get(Store1); 359 if (AA->isMustAlias(Loc0, Loc1) && Store0->isSameOperationAs(Store1) && 360 !isStoreSinkBarrierInRange(*Store1->getNextNode(), BB1->back(), Loc1, 361 AA) && 362 !isStoreSinkBarrierInRange(*Store0->getNextNode(), BB0->back(), Loc0, 363 AA)) { 364 return Store1; 365 } 366 } 367 return nullptr; 368 } 369 370 /// 371 /// \brief Create a PHI node in BB for the operands of S0 and S1 372 /// 373 static PHINode *getPHIOperand(BasicBlock *BB, StoreInst *S0, StoreInst *S1, 374 MemoryDependenceResults *MD) { 375 // Create a phi if the values mismatch. 376 Value *Opd1 = S0->getValueOperand(); 377 Value *Opd2 = S1->getValueOperand(); 378 if (Opd1 == Opd2) 379 return nullptr; 380 381 auto *NewPN = PHINode::Create(Opd1->getType(), 2, Opd2->getName() + ".sink", 382 &BB->front()); 383 NewPN->addIncoming(Opd1, S0->getParent()); 384 NewPN->addIncoming(Opd2, S1->getParent()); 385 if (MD && NewPN->getType()->getScalarType()->isPointerTy()) 386 MD->invalidateCachedPointerInfo(NewPN); 387 return NewPN; 388 } 389 390 /// 391 /// \brief Merge two stores to same address and sink into \p BB 392 /// 393 /// Also sinks GEP instruction computing the store address 394 /// 395 static bool sinkStore(BasicBlock *BB, StoreInst *S0, StoreInst *S1, 396 MemoryDependenceResults *MD) { 397 // Only one definition? 398 auto *A0 = dyn_cast<Instruction>(S0->getPointerOperand()); 399 auto *A1 = dyn_cast<Instruction>(S1->getPointerOperand()); 400 if (A0 && A1 && A0->isIdenticalTo(A1) && A0->hasOneUse() && 401 (A0->getParent() == S0->getParent()) && A1->hasOneUse() && 402 (A1->getParent() == S1->getParent()) && isa<GetElementPtrInst>(A0)) { 403 DEBUG(dbgs() << "Sink Instruction into BB \n"; BB->dump(); 404 dbgs() << "Instruction Left\n"; S0->dump(); dbgs() << "\n"; 405 dbgs() << "Instruction Right\n"; S1->dump(); dbgs() << "\n"); 406 // Hoist the instruction. 407 BasicBlock::iterator InsertPt = BB->getFirstInsertionPt(); 408 // Intersect optional metadata. 409 S0->intersectOptionalDataWith(S1); 410 S0->dropUnknownNonDebugMetadata(); 411 412 // Create the new store to be inserted at the join point. 413 StoreInst *SNew = cast<StoreInst>(S0->clone()); 414 Instruction *ANew = A0->clone(); 415 SNew->insertBefore(&*InsertPt); 416 ANew->insertBefore(SNew); 417 418 assert(S0->getParent() == A0->getParent()); 419 assert(S1->getParent() == A1->getParent()); 420 421 // New PHI operand? Use it. 422 if (PHINode *NewPN = getPHIOperand(BB, S0, S1, MD)) 423 SNew->setOperand(0, NewPN); 424 removeInstruction(S0, MD); 425 removeInstruction(S1, MD); 426 A0->replaceAllUsesWith(ANew); 427 removeInstruction(A0, MD); 428 A1->replaceAllUsesWith(ANew); 429 removeInstruction(A1, MD); 430 return true; 431 } 432 return false; 433 } 434 435 /// 436 /// \brief True when two stores are equivalent and can sink into the footer 437 /// 438 /// Starting from a diamond tail block, iterate over the instructions in one 439 /// predecessor block and try to match a store in the second predecessor. 440 /// 441 static bool mergeStores(BasicBlock *T, AliasAnalysis *AA, 442 MemoryDependenceResults *MD) { 443 444 bool MergedStores = false; 445 assert(T && "Footer of a diamond cannot be empty"); 446 447 pred_iterator PI = pred_begin(T), E = pred_end(T); 448 assert(PI != E); 449 BasicBlock *Pred0 = *PI; 450 ++PI; 451 BasicBlock *Pred1 = *PI; 452 ++PI; 453 // tail block of a diamond/hammock? 454 if (Pred0 == Pred1) 455 return false; // No. 456 if (PI != E) 457 return false; // No. More than 2 predecessors. 458 459 // #Instructions in Succ1 for Compile Time Control 460 int Size1 = Pred1->size(); 461 int NStores = 0; 462 463 for (BasicBlock::reverse_iterator RBI = Pred0->rbegin(), RBE = Pred0->rend(); 464 RBI != RBE;) { 465 466 Instruction *I = &*RBI; 467 ++RBI; 468 469 // Don't sink non-simple (atomic, volatile) stores. 470 auto *S0 = dyn_cast<StoreInst>(I); 471 if (!S0 || !S0->isSimple()) 472 continue; 473 474 ++NStores; 475 if (NStores * Size1 >= MagicCompileTimeControl) 476 break; 477 if (StoreInst *S1 = canSinkFromBlock(Pred1, S0, AA)) { 478 bool Res = sinkStore(T, S0, S1, MD); 479 MergedStores |= Res; 480 // Don't attempt to sink below stores that had to stick around 481 // But after removal of a store and some of its feeding 482 // instruction search again from the beginning since the iterator 483 // is likely stale at this point. 484 if (!Res) 485 break; 486 RBI = Pred0->rbegin(); 487 RBE = Pred0->rend(); 488 DEBUG(dbgs() << "Search again\n"; Instruction *I = &*RBI; I->dump()); 489 } 490 } 491 return MergedStores; 492 } 493 494 /// 495 /// \brief Run the transformation for each function 496 /// 497 static bool runMergedLoadStoreMotion(Function &F, AliasAnalysis *AA, 498 MemoryDependenceResults *MD) { 499 bool Changed = false; 500 DEBUG(dbgs() << "Instruction Merger\n"); 501 502 // Merge unconditional branches, allowing PRE to catch more 503 // optimization opportunities. 504 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE;) { 505 BasicBlock *BB = &*FI++; 506 507 // Hoist equivalent loads and sink stores 508 // outside diamonds when possible 509 if (isDiamondHead(BB)) { 510 Changed |= mergeLoads(BB, AA, MD); 511 Changed |= mergeStores(getDiamondTail(BB), AA, MD); 512 } 513 } 514 return Changed; 515 } 516 517 PreservedAnalyses 518 MergedLoadStoreMotionPass::run(Function &F, AnalysisManager<Function> &AM) { 519 auto &AA = AM.getResult<AAManager>(F); 520 auto *MD = AM.getCachedResult<MemoryDependenceAnalysis>(F); 521 if (!runMergedLoadStoreMotion(F, &AA, MD)) 522 return PreservedAnalyses::all(); 523 return PreservedAnalyses::none(); 524 } 525 526 namespace { 527 class MergedLoadStoreMotionLegacyPass : public FunctionPass { 528 AliasAnalysis *AA; 529 MemoryDependenceResults *MD; 530 531 public: 532 static char ID; // Pass identification, replacement for typeid 533 MergedLoadStoreMotionLegacyPass() : FunctionPass(ID), MD(nullptr) { 534 initializeMergedLoadStoreMotionLegacyPassPass( 535 *PassRegistry::getPassRegistry()); 536 } 537 538 bool runOnFunction(Function &F) override { 539 if (skipFunction(F)) 540 return false; 541 542 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults(); 543 auto *MDWP = getAnalysisIfAvailable<MemoryDependenceWrapperPass>(); 544 MD = MDWP ? &MDWP->getMemDep() : nullptr; 545 return runMergedLoadStoreMotion(F, AA, MD); 546 } 547 548 private: 549 // This transformation requires dominator postdominator info 550 void getAnalysisUsage(AnalysisUsage &AU) const override { 551 AU.setPreservesCFG(); 552 AU.addRequired<AAResultsWrapperPass>(); 553 AU.addPreserved<GlobalsAAWrapperPass>(); 554 AU.addPreserved<MemoryDependenceWrapperPass>(); 555 } 556 }; 557 558 char MergedLoadStoreMotionLegacyPass::ID = 0; 559 } // anonymous namespace 560 561 /// 562 /// \brief createMergedLoadStoreMotionPass - The public interface to this file. 563 /// 564 FunctionPass *llvm::createMergedLoadStoreMotionPass() { 565 return new MergedLoadStoreMotionLegacyPass(); 566 } 567 568 INITIALIZE_PASS_BEGIN(MergedLoadStoreMotionLegacyPass, "mldst-motion", 569 "MergedLoadStoreMotion", false, false) 570 INITIALIZE_PASS_DEPENDENCY(MemoryDependenceWrapperPass) 571 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass) 572 INITIALIZE_PASS_END(MergedLoadStoreMotionLegacyPass, "mldst-motion", 573 "MergedLoadStoreMotion", false, false) 574