1 //===-------- LoopDataPrefetch.cpp - Loop Data Prefetching Pass -----------===// 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 file implements a Loop Data Prefetching Pass. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "llvm/Transforms/Scalar/LoopDataPrefetch.h" 15 16 #define DEBUG_TYPE "loop-data-prefetch" 17 #include "llvm/ADT/DepthFirstIterator.h" 18 #include "llvm/ADT/Statistic.h" 19 #include "llvm/Analysis/AssumptionCache.h" 20 #include "llvm/Analysis/CodeMetrics.h" 21 #include "llvm/Analysis/InstructionSimplify.h" 22 #include "llvm/Analysis/LoopInfo.h" 23 #include "llvm/Analysis/OptimizationRemarkEmitter.h" 24 #include "llvm/Analysis/ScalarEvolution.h" 25 #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h" 26 #include "llvm/Analysis/ScalarEvolutionExpander.h" 27 #include "llvm/Analysis/ScalarEvolutionExpressions.h" 28 #include "llvm/Analysis/TargetTransformInfo.h" 29 #include "llvm/Analysis/ValueTracking.h" 30 #include "llvm/IR/CFG.h" 31 #include "llvm/IR/Dominators.h" 32 #include "llvm/IR/Function.h" 33 #include "llvm/IR/IntrinsicInst.h" 34 #include "llvm/IR/Module.h" 35 #include "llvm/Support/CommandLine.h" 36 #include "llvm/Support/Debug.h" 37 #include "llvm/Transforms/Scalar.h" 38 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 39 #include "llvm/Transforms/Utils/Local.h" 40 #include "llvm/Transforms/Utils/ValueMapper.h" 41 using namespace llvm; 42 43 // By default, we limit this to creating 16 PHIs (which is a little over half 44 // of the allocatable register set). 45 static cl::opt<bool> 46 PrefetchWrites("loop-prefetch-writes", cl::Hidden, cl::init(false), 47 cl::desc("Prefetch write addresses")); 48 49 static cl::opt<unsigned> 50 PrefetchDistance("prefetch-distance", 51 cl::desc("Number of instructions to prefetch ahead"), 52 cl::Hidden); 53 54 static cl::opt<unsigned> 55 MinPrefetchStride("min-prefetch-stride", 56 cl::desc("Min stride to add prefetches"), cl::Hidden); 57 58 static cl::opt<unsigned> MaxPrefetchIterationsAhead( 59 "max-prefetch-iters-ahead", 60 cl::desc("Max number of iterations to prefetch ahead"), cl::Hidden); 61 62 STATISTIC(NumPrefetches, "Number of prefetches inserted"); 63 64 namespace { 65 66 /// Loop prefetch implementation class. 67 class LoopDataPrefetch { 68 public: 69 LoopDataPrefetch(AssumptionCache *AC, LoopInfo *LI, ScalarEvolution *SE, 70 const TargetTransformInfo *TTI, 71 OptimizationRemarkEmitter *ORE) 72 : AC(AC), LI(LI), SE(SE), TTI(TTI), ORE(ORE) {} 73 74 bool run(); 75 76 private: 77 bool runOnLoop(Loop *L); 78 79 /// \brief Check if the the stride of the accesses is large enough to 80 /// warrant a prefetch. 81 bool isStrideLargeEnough(const SCEVAddRecExpr *AR); 82 83 unsigned getMinPrefetchStride() { 84 if (MinPrefetchStride.getNumOccurrences() > 0) 85 return MinPrefetchStride; 86 return TTI->getMinPrefetchStride(); 87 } 88 89 unsigned getPrefetchDistance() { 90 if (PrefetchDistance.getNumOccurrences() > 0) 91 return PrefetchDistance; 92 return TTI->getPrefetchDistance(); 93 } 94 95 unsigned getMaxPrefetchIterationsAhead() { 96 if (MaxPrefetchIterationsAhead.getNumOccurrences() > 0) 97 return MaxPrefetchIterationsAhead; 98 return TTI->getMaxPrefetchIterationsAhead(); 99 } 100 101 AssumptionCache *AC; 102 LoopInfo *LI; 103 ScalarEvolution *SE; 104 const TargetTransformInfo *TTI; 105 OptimizationRemarkEmitter *ORE; 106 }; 107 108 /// Legacy class for inserting loop data prefetches. 109 class LoopDataPrefetchLegacyPass : public FunctionPass { 110 public: 111 static char ID; // Pass ID, replacement for typeid 112 LoopDataPrefetchLegacyPass() : FunctionPass(ID) { 113 initializeLoopDataPrefetchLegacyPassPass(*PassRegistry::getPassRegistry()); 114 } 115 116 void getAnalysisUsage(AnalysisUsage &AU) const override { 117 AU.addRequired<AssumptionCacheTracker>(); 118 AU.addPreserved<DominatorTreeWrapperPass>(); 119 AU.addRequired<LoopInfoWrapperPass>(); 120 AU.addPreserved<LoopInfoWrapperPass>(); 121 AU.addRequired<OptimizationRemarkEmitterWrapperPass>(); 122 AU.addRequired<ScalarEvolutionWrapperPass>(); 123 AU.addPreserved<ScalarEvolutionWrapperPass>(); 124 AU.addRequired<TargetTransformInfoWrapperPass>(); 125 } 126 127 bool runOnFunction(Function &F) override; 128 }; 129 } 130 131 char LoopDataPrefetchLegacyPass::ID = 0; 132 INITIALIZE_PASS_BEGIN(LoopDataPrefetchLegacyPass, "loop-data-prefetch", 133 "Loop Data Prefetch", false, false) 134 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 135 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass) 136 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) 137 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass) 138 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass) 139 INITIALIZE_PASS_END(LoopDataPrefetchLegacyPass, "loop-data-prefetch", 140 "Loop Data Prefetch", false, false) 141 142 FunctionPass *llvm::createLoopDataPrefetchPass() { 143 return new LoopDataPrefetchLegacyPass(); 144 } 145 146 bool LoopDataPrefetch::isStrideLargeEnough(const SCEVAddRecExpr *AR) { 147 unsigned TargetMinStride = getMinPrefetchStride(); 148 // No need to check if any stride goes. 149 if (TargetMinStride <= 1) 150 return true; 151 152 const auto *ConstStride = dyn_cast<SCEVConstant>(AR->getStepRecurrence(*SE)); 153 // If MinStride is set, don't prefetch unless we can ensure that stride is 154 // larger. 155 if (!ConstStride) 156 return false; 157 158 unsigned AbsStride = std::abs(ConstStride->getAPInt().getSExtValue()); 159 return TargetMinStride <= AbsStride; 160 } 161 162 PreservedAnalyses LoopDataPrefetchPass::run(Function &F, 163 FunctionAnalysisManager &AM) { 164 LoopInfo *LI = &AM.getResult<LoopAnalysis>(F); 165 ScalarEvolution *SE = &AM.getResult<ScalarEvolutionAnalysis>(F); 166 AssumptionCache *AC = &AM.getResult<AssumptionAnalysis>(F); 167 OptimizationRemarkEmitter *ORE = 168 &AM.getResult<OptimizationRemarkEmitterAnalysis>(F); 169 const TargetTransformInfo *TTI = &AM.getResult<TargetIRAnalysis>(F); 170 171 LoopDataPrefetch LDP(AC, LI, SE, TTI, ORE); 172 bool Changed = LDP.run(); 173 174 if (Changed) { 175 PreservedAnalyses PA; 176 PA.preserve<DominatorTreeAnalysis>(); 177 PA.preserve<LoopAnalysis>(); 178 return PA; 179 } 180 181 return PreservedAnalyses::all(); 182 } 183 184 bool LoopDataPrefetchLegacyPass::runOnFunction(Function &F) { 185 if (skipFunction(F)) 186 return false; 187 188 LoopInfo *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); 189 ScalarEvolution *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE(); 190 AssumptionCache *AC = 191 &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F); 192 OptimizationRemarkEmitter *ORE = 193 &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE(); 194 const TargetTransformInfo *TTI = 195 &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F); 196 197 LoopDataPrefetch LDP(AC, LI, SE, TTI, ORE); 198 return LDP.run(); 199 } 200 201 bool LoopDataPrefetch::run() { 202 // If PrefetchDistance is not set, don't run the pass. This gives an 203 // opportunity for targets to run this pass for selected subtargets only 204 // (whose TTI sets PrefetchDistance). 205 if (getPrefetchDistance() == 0) 206 return false; 207 assert(TTI->getCacheLineSize() && "Cache line size is not set for target"); 208 209 bool MadeChange = false; 210 211 for (Loop *I : *LI) 212 for (auto L = df_begin(I), LE = df_end(I); L != LE; ++L) 213 MadeChange |= runOnLoop(*L); 214 215 return MadeChange; 216 } 217 218 bool LoopDataPrefetch::runOnLoop(Loop *L) { 219 bool MadeChange = false; 220 221 // Only prefetch in the inner-most loop 222 if (!L->empty()) 223 return MadeChange; 224 225 SmallPtrSet<const Value *, 32> EphValues; 226 CodeMetrics::collectEphemeralValues(L, AC, EphValues); 227 228 // Calculate the number of iterations ahead to prefetch 229 CodeMetrics Metrics; 230 for (const auto BB : L->blocks()) { 231 // If the loop already has prefetches, then assume that the user knows 232 // what they are doing and don't add any more. 233 for (auto &I : *BB) 234 if (CallInst *CI = dyn_cast<CallInst>(&I)) 235 if (Function *F = CI->getCalledFunction()) 236 if (F->getIntrinsicID() == Intrinsic::prefetch) 237 return MadeChange; 238 239 Metrics.analyzeBasicBlock(BB, *TTI, EphValues); 240 } 241 unsigned LoopSize = Metrics.NumInsts; 242 if (!LoopSize) 243 LoopSize = 1; 244 245 unsigned ItersAhead = getPrefetchDistance() / LoopSize; 246 if (!ItersAhead) 247 ItersAhead = 1; 248 249 if (ItersAhead > getMaxPrefetchIterationsAhead()) 250 return MadeChange; 251 252 DEBUG(dbgs() << "Prefetching " << ItersAhead 253 << " iterations ahead (loop size: " << LoopSize << ") in " 254 << L->getHeader()->getParent()->getName() << ": " << *L); 255 256 SmallVector<std::pair<Instruction *, const SCEVAddRecExpr *>, 16> PrefLoads; 257 for (const auto BB : L->blocks()) { 258 for (auto &I : *BB) { 259 Value *PtrValue; 260 Instruction *MemI; 261 262 if (LoadInst *LMemI = dyn_cast<LoadInst>(&I)) { 263 MemI = LMemI; 264 PtrValue = LMemI->getPointerOperand(); 265 } else if (StoreInst *SMemI = dyn_cast<StoreInst>(&I)) { 266 if (!PrefetchWrites) continue; 267 MemI = SMemI; 268 PtrValue = SMemI->getPointerOperand(); 269 } else continue; 270 271 unsigned PtrAddrSpace = PtrValue->getType()->getPointerAddressSpace(); 272 if (PtrAddrSpace) 273 continue; 274 275 if (L->isLoopInvariant(PtrValue)) 276 continue; 277 278 const SCEV *LSCEV = SE->getSCEV(PtrValue); 279 const SCEVAddRecExpr *LSCEVAddRec = dyn_cast<SCEVAddRecExpr>(LSCEV); 280 if (!LSCEVAddRec) 281 continue; 282 283 // Check if the the stride of the accesses is large enough to warrant a 284 // prefetch. 285 if (!isStrideLargeEnough(LSCEVAddRec)) 286 continue; 287 288 // We don't want to double prefetch individual cache lines. If this load 289 // is known to be within one cache line of some other load that has 290 // already been prefetched, then don't prefetch this one as well. 291 bool DupPref = false; 292 for (const auto &PrefLoad : PrefLoads) { 293 const SCEV *PtrDiff = SE->getMinusSCEV(LSCEVAddRec, PrefLoad.second); 294 if (const SCEVConstant *ConstPtrDiff = 295 dyn_cast<SCEVConstant>(PtrDiff)) { 296 int64_t PD = std::abs(ConstPtrDiff->getValue()->getSExtValue()); 297 if (PD < (int64_t) TTI->getCacheLineSize()) { 298 DupPref = true; 299 break; 300 } 301 } 302 } 303 if (DupPref) 304 continue; 305 306 const SCEV *NextLSCEV = SE->getAddExpr(LSCEVAddRec, SE->getMulExpr( 307 SE->getConstant(LSCEVAddRec->getType(), ItersAhead), 308 LSCEVAddRec->getStepRecurrence(*SE))); 309 if (!isSafeToExpand(NextLSCEV, *SE)) 310 continue; 311 312 PrefLoads.push_back(std::make_pair(MemI, LSCEVAddRec)); 313 314 Type *I8Ptr = Type::getInt8PtrTy(BB->getContext(), PtrAddrSpace); 315 SCEVExpander SCEVE(*SE, I.getModule()->getDataLayout(), "prefaddr"); 316 Value *PrefPtrValue = SCEVE.expandCodeFor(NextLSCEV, I8Ptr, MemI); 317 318 IRBuilder<> Builder(MemI); 319 Module *M = BB->getParent()->getParent(); 320 Type *I32 = Type::getInt32Ty(BB->getContext()); 321 Value *PrefetchFunc = Intrinsic::getDeclaration(M, Intrinsic::prefetch); 322 Builder.CreateCall( 323 PrefetchFunc, 324 {PrefPtrValue, 325 ConstantInt::get(I32, MemI->mayReadFromMemory() ? 0 : 1), 326 ConstantInt::get(I32, 3), ConstantInt::get(I32, 1)}); 327 ++NumPrefetches; 328 DEBUG(dbgs() << " Access: " << *PtrValue << ", SCEV: " << *LSCEV 329 << "\n"); 330 ORE->emit([&]() { 331 return OptimizationRemark(DEBUG_TYPE, "Prefetched", MemI) 332 << "prefetched memory access"; 333 }); 334 335 MadeChange = true; 336 } 337 } 338 339 return MadeChange; 340 } 341 342