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 //! 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 // NOTE: This code no longer performs load hoisting, it is subsumed by GVNHoist. 23 // 24 //===----------------------------------------------------------------------===// 25 // 26 // 27 // Example: 28 // Diamond shaped code before merge: 29 // 30 // header: 31 // br %cond, label %if.then, label %if.else 32 // + + 33 // + + 34 // + + 35 // if.then: if.else: 36 // %lt = load %addr_l %le = load %addr_l 37 // <use %lt> <use %le> 38 // <...> <...> 39 // store %st, %addr_s store %se, %addr_s 40 // br label %if.end br label %if.end 41 // + + 42 // + + 43 // + + 44 // if.end ("footer"): 45 // <...> 46 // 47 // Diamond shaped code after merge: 48 // 49 // header: 50 // %l = load %addr_l 51 // br %cond, label %if.then, label %if.else 52 // + + 53 // + + 54 // + + 55 // if.then: if.else: 56 // <use %l> <use %l> 57 // <...> <...> 58 // br label %if.end br label %if.end 59 // + + 60 // + + 61 // + + 62 // if.end ("footer"): 63 // %s.sink = phi [%st, if.then], [%se, if.else] 64 // <...> 65 // store %s.sink, %addr_s 66 // <...> 67 // 68 // 69 //===----------------------- TODO -----------------------------------------===// 70 // 71 // 1) Generalize to regions other than diamonds 72 // 2) Be more aggressive merging memory operations 73 // Note that both changes require register pressure control 74 // 75 //===----------------------------------------------------------------------===// 76 77 #include "llvm/Transforms/Scalar/MergedLoadStoreMotion.h" 78 #include "llvm/ADT/Statistic.h" 79 #include "llvm/Analysis/AliasAnalysis.h" 80 #include "llvm/Analysis/CFG.h" 81 #include "llvm/Analysis/GlobalsModRef.h" 82 #include "llvm/Analysis/Loads.h" 83 #include "llvm/Analysis/ValueTracking.h" 84 #include "llvm/IR/Metadata.h" 85 #include "llvm/Support/Debug.h" 86 #include "llvm/Support/raw_ostream.h" 87 #include "llvm/Transforms/Scalar.h" 88 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 89 90 using namespace llvm; 91 92 #define DEBUG_TYPE "mldst-motion" 93 94 namespace { 95 //===----------------------------------------------------------------------===// 96 // MergedLoadStoreMotion Pass 97 //===----------------------------------------------------------------------===// 98 class MergedLoadStoreMotion { 99 AliasAnalysis *AA = nullptr; 100 101 // The mergeLoad/Store algorithms could have Size0 * Size1 complexity, 102 // where Size0 and Size1 are the #instructions on the two sides of 103 // the diamond. The constant chosen here is arbitrary. Compiler Time 104 // Control is enforced by the check Size0 * Size1 < MagicCompileTimeControl. 105 const int MagicCompileTimeControl = 250; 106 107 public: 108 bool run(Function &F, AliasAnalysis &AA); 109 110 private: 111 BasicBlock *getDiamondTail(BasicBlock *BB); 112 bool isDiamondHead(BasicBlock *BB); 113 // Routines for sinking stores 114 StoreInst *canSinkFromBlock(BasicBlock *BB, StoreInst *SI); 115 PHINode *getPHIOperand(BasicBlock *BB, StoreInst *S0, StoreInst *S1); 116 bool isStoreSinkBarrierInRange(const Instruction &Start, 117 const Instruction &End, MemoryLocation Loc); 118 bool sinkStore(BasicBlock *BB, StoreInst *SinkCand, StoreInst *ElseInst); 119 bool mergeStores(BasicBlock *BB); 120 }; 121 } // end anonymous namespace 122 123 /// 124 /// Return tail block of a diamond. 125 /// 126 BasicBlock *MergedLoadStoreMotion::getDiamondTail(BasicBlock *BB) { 127 assert(isDiamondHead(BB) && "Basic block is not head of a diamond"); 128 return BB->getTerminator()->getSuccessor(0)->getSingleSuccessor(); 129 } 130 131 /// 132 /// True when BB is the head of a diamond (hammock) 133 /// 134 bool MergedLoadStoreMotion::isDiamondHead(BasicBlock *BB) { 135 if (!BB) 136 return false; 137 auto *BI = dyn_cast<BranchInst>(BB->getTerminator()); 138 if (!BI || !BI->isConditional()) 139 return false; 140 141 BasicBlock *Succ0 = BI->getSuccessor(0); 142 BasicBlock *Succ1 = BI->getSuccessor(1); 143 144 if (!Succ0->getSinglePredecessor()) 145 return false; 146 if (!Succ1->getSinglePredecessor()) 147 return false; 148 149 BasicBlock *Succ0Succ = Succ0->getSingleSuccessor(); 150 BasicBlock *Succ1Succ = Succ1->getSingleSuccessor(); 151 // Ignore triangles. 152 if (!Succ0Succ || !Succ1Succ || Succ0Succ != Succ1Succ) 153 return false; 154 return true; 155 } 156 157 158 /// 159 /// True when instruction is a sink barrier for a store 160 /// located in Loc 161 /// 162 /// Whenever an instruction could possibly read or modify the 163 /// value being stored or protect against the store from 164 /// happening it is considered a sink barrier. 165 /// 166 bool MergedLoadStoreMotion::isStoreSinkBarrierInRange(const Instruction &Start, 167 const Instruction &End, 168 MemoryLocation Loc) { 169 for (const Instruction &Inst : 170 make_range(Start.getIterator(), End.getIterator())) 171 if (Inst.mayThrow()) 172 return true; 173 return AA->canInstructionRangeModRef(Start, End, Loc, ModRefInfo::ModRef); 174 } 175 176 /// 177 /// Check if \p BB contains a store to the same address as \p SI 178 /// 179 /// \return The store in \p when it is safe to sink. Otherwise return Null. 180 /// 181 StoreInst *MergedLoadStoreMotion::canSinkFromBlock(BasicBlock *BB1, 182 StoreInst *Store0) { 183 LLVM_DEBUG(dbgs() << "can Sink? : "; Store0->dump(); dbgs() << "\n"); 184 BasicBlock *BB0 = Store0->getParent(); 185 for (Instruction &Inst : reverse(*BB1)) { 186 auto *Store1 = dyn_cast<StoreInst>(&Inst); 187 if (!Store1) 188 continue; 189 190 MemoryLocation Loc0 = MemoryLocation::get(Store0); 191 MemoryLocation Loc1 = MemoryLocation::get(Store1); 192 if (AA->isMustAlias(Loc0, Loc1) && Store0->isSameOperationAs(Store1) && 193 !isStoreSinkBarrierInRange(*Store1->getNextNode(), BB1->back(), Loc1) && 194 !isStoreSinkBarrierInRange(*Store0->getNextNode(), BB0->back(), Loc0)) { 195 return Store1; 196 } 197 } 198 return nullptr; 199 } 200 201 /// 202 /// Create a PHI node in BB for the operands of S0 and S1 203 /// 204 PHINode *MergedLoadStoreMotion::getPHIOperand(BasicBlock *BB, StoreInst *S0, 205 StoreInst *S1) { 206 // Create a phi if the values mismatch. 207 Value *Opd1 = S0->getValueOperand(); 208 Value *Opd2 = S1->getValueOperand(); 209 if (Opd1 == Opd2) 210 return nullptr; 211 212 auto *NewPN = PHINode::Create(Opd1->getType(), 2, Opd2->getName() + ".sink", 213 &BB->front()); 214 NewPN->addIncoming(Opd1, S0->getParent()); 215 NewPN->addIncoming(Opd2, S1->getParent()); 216 return NewPN; 217 } 218 219 /// 220 /// Merge two stores to same address and sink into \p BB 221 /// 222 /// Also sinks GEP instruction computing the store address 223 /// 224 bool MergedLoadStoreMotion::sinkStore(BasicBlock *BB, StoreInst *S0, 225 StoreInst *S1) { 226 // Only one definition? 227 auto *A0 = dyn_cast<Instruction>(S0->getPointerOperand()); 228 auto *A1 = dyn_cast<Instruction>(S1->getPointerOperand()); 229 if (A0 && A1 && A0->isIdenticalTo(A1) && A0->hasOneUse() && 230 (A0->getParent() == S0->getParent()) && A1->hasOneUse() && 231 (A1->getParent() == S1->getParent()) && isa<GetElementPtrInst>(A0)) { 232 LLVM_DEBUG(dbgs() << "Sink Instruction into BB \n"; BB->dump(); 233 dbgs() << "Instruction Left\n"; S0->dump(); dbgs() << "\n"; 234 dbgs() << "Instruction Right\n"; S1->dump(); dbgs() << "\n"); 235 // Hoist the instruction. 236 BasicBlock::iterator InsertPt = BB->getFirstInsertionPt(); 237 // Intersect optional metadata. 238 S0->andIRFlags(S1); 239 S0->dropUnknownNonDebugMetadata(); 240 241 // Create the new store to be inserted at the join point. 242 StoreInst *SNew = cast<StoreInst>(S0->clone()); 243 Instruction *ANew = A0->clone(); 244 SNew->insertBefore(&*InsertPt); 245 ANew->insertBefore(SNew); 246 247 assert(S0->getParent() == A0->getParent()); 248 assert(S1->getParent() == A1->getParent()); 249 250 // New PHI operand? Use it. 251 if (PHINode *NewPN = getPHIOperand(BB, S0, S1)) 252 SNew->setOperand(0, NewPN); 253 S0->eraseFromParent(); 254 S1->eraseFromParent(); 255 A0->replaceAllUsesWith(ANew); 256 A0->eraseFromParent(); 257 A1->replaceAllUsesWith(ANew); 258 A1->eraseFromParent(); 259 return true; 260 } 261 return false; 262 } 263 264 /// 265 /// True when two stores are equivalent and can sink into the footer 266 /// 267 /// Starting from a diamond tail block, iterate over the instructions in one 268 /// predecessor block and try to match a store in the second predecessor. 269 /// 270 bool MergedLoadStoreMotion::mergeStores(BasicBlock *T) { 271 272 bool MergedStores = false; 273 assert(T && "Footer of a diamond cannot be empty"); 274 275 pred_iterator PI = pred_begin(T), E = pred_end(T); 276 assert(PI != E); 277 BasicBlock *Pred0 = *PI; 278 ++PI; 279 BasicBlock *Pred1 = *PI; 280 ++PI; 281 // tail block of a diamond/hammock? 282 if (Pred0 == Pred1) 283 return false; // No. 284 if (PI != E) 285 return false; // No. More than 2 predecessors. 286 287 // #Instructions in Succ1 for Compile Time Control 288 int Size1 = distance(Pred1->instructionsWithoutDebug()); 289 int NStores = 0; 290 291 for (BasicBlock::reverse_iterator RBI = Pred0->rbegin(), RBE = Pred0->rend(); 292 RBI != RBE;) { 293 294 Instruction *I = &*RBI; 295 ++RBI; 296 297 // Don't sink non-simple (atomic, volatile) stores. 298 auto *S0 = dyn_cast<StoreInst>(I); 299 if (!S0 || !S0->isSimple()) 300 continue; 301 302 ++NStores; 303 if (NStores * Size1 >= MagicCompileTimeControl) 304 break; 305 if (StoreInst *S1 = canSinkFromBlock(Pred1, S0)) { 306 bool Res = sinkStore(T, S0, S1); 307 MergedStores |= Res; 308 // Don't attempt to sink below stores that had to stick around 309 // But after removal of a store and some of its feeding 310 // instruction search again from the beginning since the iterator 311 // is likely stale at this point. 312 if (!Res) 313 break; 314 RBI = Pred0->rbegin(); 315 RBE = Pred0->rend(); 316 LLVM_DEBUG(dbgs() << "Search again\n"; Instruction *I = &*RBI; I->dump()); 317 } 318 } 319 return MergedStores; 320 } 321 322 bool MergedLoadStoreMotion::run(Function &F, AliasAnalysis &AA) { 323 this->AA = &AA; 324 325 bool Changed = false; 326 LLVM_DEBUG(dbgs() << "Instruction Merger\n"); 327 328 // Merge unconditional branches, allowing PRE to catch more 329 // optimization opportunities. 330 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE;) { 331 BasicBlock *BB = &*FI++; 332 333 // Hoist equivalent loads and sink stores 334 // outside diamonds when possible 335 if (isDiamondHead(BB)) { 336 Changed |= mergeStores(getDiamondTail(BB)); 337 } 338 } 339 return Changed; 340 } 341 342 namespace { 343 class MergedLoadStoreMotionLegacyPass : public FunctionPass { 344 public: 345 static char ID; // Pass identification, replacement for typeid 346 MergedLoadStoreMotionLegacyPass() : FunctionPass(ID) { 347 initializeMergedLoadStoreMotionLegacyPassPass( 348 *PassRegistry::getPassRegistry()); 349 } 350 351 /// 352 /// Run the transformation for each function 353 /// 354 bool runOnFunction(Function &F) override { 355 if (skipFunction(F)) 356 return false; 357 MergedLoadStoreMotion Impl; 358 return Impl.run(F, getAnalysis<AAResultsWrapperPass>().getAAResults()); 359 } 360 361 private: 362 void getAnalysisUsage(AnalysisUsage &AU) const override { 363 AU.setPreservesCFG(); 364 AU.addRequired<AAResultsWrapperPass>(); 365 AU.addPreserved<GlobalsAAWrapperPass>(); 366 } 367 }; 368 369 char MergedLoadStoreMotionLegacyPass::ID = 0; 370 } // anonymous namespace 371 372 /// 373 /// createMergedLoadStoreMotionPass - The public interface to this file. 374 /// 375 FunctionPass *llvm::createMergedLoadStoreMotionPass() { 376 return new MergedLoadStoreMotionLegacyPass(); 377 } 378 379 INITIALIZE_PASS_BEGIN(MergedLoadStoreMotionLegacyPass, "mldst-motion", 380 "MergedLoadStoreMotion", false, false) 381 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass) 382 INITIALIZE_PASS_END(MergedLoadStoreMotionLegacyPass, "mldst-motion", 383 "MergedLoadStoreMotion", false, false) 384 385 PreservedAnalyses 386 MergedLoadStoreMotionPass::run(Function &F, FunctionAnalysisManager &AM) { 387 MergedLoadStoreMotion Impl; 388 auto &AA = AM.getResult<AAManager>(F); 389 if (!Impl.run(F, AA)) 390 return PreservedAnalyses::all(); 391 392 PreservedAnalyses PA; 393 PA.preserveSet<CFGAnalyses>(); 394 PA.preserve<GlobalsAA>(); 395 return PA; 396 } 397