Chris Lattner | e6bb649 | 2010-12-26 19:39:38 +0000 | [diff] [blame] | 1 | //===-- LoopIdiomRecognize.cpp - Loop idiom recognition -------------------===// |
| 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 implements an idiom recognizer that transforms simple loops into a |
| 11 | // non-loop form. In cases that this kicks in, it can be a significant |
| 12 | // performance win. |
| 13 | // |
| 14 | //===----------------------------------------------------------------------===// |
| 15 | |
| 16 | #define DEBUG_TYPE "loop-idiom" |
| 17 | #include "llvm/Transforms/Scalar.h" |
Chris Lattner | 2e12f1a | 2010-12-27 18:39:08 +0000 | [diff] [blame] | 18 | #include "llvm/Analysis/AliasAnalysis.h" |
Chris Lattner | e6bb649 | 2010-12-26 19:39:38 +0000 | [diff] [blame] | 19 | #include "llvm/Analysis/LoopPass.h" |
| 20 | #include "llvm/Analysis/ScalarEvolutionExpressions.h" |
Chris Lattner | a92ff91 | 2010-12-26 23:42:51 +0000 | [diff] [blame] | 21 | #include "llvm/Analysis/ScalarEvolutionExpander.h" |
Chris Lattner | 22920b5 | 2010-12-26 20:45:45 +0000 | [diff] [blame] | 22 | #include "llvm/Analysis/ValueTracking.h" |
| 23 | #include "llvm/Target/TargetData.h" |
Chris Lattner | 9f39188 | 2010-12-27 00:03:23 +0000 | [diff] [blame] | 24 | #include "llvm/Transforms/Utils/Local.h" |
Chris Lattner | e6bb649 | 2010-12-26 19:39:38 +0000 | [diff] [blame] | 25 | #include "llvm/Support/Debug.h" |
Chris Lattner | a92ff91 | 2010-12-26 23:42:51 +0000 | [diff] [blame] | 26 | #include "llvm/Support/IRBuilder.h" |
Chris Lattner | e6bb649 | 2010-12-26 19:39:38 +0000 | [diff] [blame] | 27 | #include "llvm/Support/raw_ostream.h" |
| 28 | using namespace llvm; |
| 29 | |
| 30 | // TODO: Recognize "N" size array multiplies: replace with call to blas or |
| 31 | // something. |
| 32 | |
| 33 | namespace { |
| 34 | class LoopIdiomRecognize : public LoopPass { |
Chris Lattner | 22920b5 | 2010-12-26 20:45:45 +0000 | [diff] [blame] | 35 | Loop *CurLoop; |
| 36 | const TargetData *TD; |
| 37 | ScalarEvolution *SE; |
Chris Lattner | e6bb649 | 2010-12-26 19:39:38 +0000 | [diff] [blame] | 38 | public: |
| 39 | static char ID; |
| 40 | explicit LoopIdiomRecognize() : LoopPass(ID) { |
| 41 | initializeLoopIdiomRecognizePass(*PassRegistry::getPassRegistry()); |
| 42 | } |
| 43 | |
| 44 | bool runOnLoop(Loop *L, LPPassManager &LPM); |
| 45 | |
Chris Lattner | 22920b5 | 2010-12-26 20:45:45 +0000 | [diff] [blame] | 46 | bool processLoopStore(StoreInst *SI, const SCEV *BECount); |
Chris Lattner | e6bb649 | 2010-12-26 19:39:38 +0000 | [diff] [blame] | 47 | |
Chris Lattner | a92ff91 | 2010-12-26 23:42:51 +0000 | [diff] [blame] | 48 | bool processLoopStoreOfSplatValue(StoreInst *SI, unsigned StoreSize, |
| 49 | Value *SplatValue, |
| 50 | const SCEVAddRecExpr *Ev, |
| 51 | const SCEV *BECount); |
| 52 | |
Chris Lattner | e6bb649 | 2010-12-26 19:39:38 +0000 | [diff] [blame] | 53 | /// This transformation requires natural loop information & requires that |
| 54 | /// loop preheaders be inserted into the CFG. |
| 55 | /// |
| 56 | virtual void getAnalysisUsage(AnalysisUsage &AU) const { |
| 57 | AU.addRequired<LoopInfo>(); |
| 58 | AU.addPreserved<LoopInfo>(); |
| 59 | AU.addRequiredID(LoopSimplifyID); |
| 60 | AU.addPreservedID(LoopSimplifyID); |
| 61 | AU.addRequiredID(LCSSAID); |
| 62 | AU.addPreservedID(LCSSAID); |
Chris Lattner | 2e12f1a | 2010-12-27 18:39:08 +0000 | [diff] [blame] | 63 | AU.addRequired<AliasAnalysis>(); |
| 64 | AU.addPreserved<AliasAnalysis>(); |
Chris Lattner | e6bb649 | 2010-12-26 19:39:38 +0000 | [diff] [blame] | 65 | AU.addRequired<ScalarEvolution>(); |
| 66 | AU.addPreserved<ScalarEvolution>(); |
| 67 | AU.addPreserved<DominatorTree>(); |
| 68 | } |
| 69 | }; |
| 70 | } |
| 71 | |
| 72 | char LoopIdiomRecognize::ID = 0; |
| 73 | INITIALIZE_PASS_BEGIN(LoopIdiomRecognize, "loop-idiom", "Recognize loop idioms", |
| 74 | false, false) |
| 75 | INITIALIZE_PASS_DEPENDENCY(LoopInfo) |
| 76 | INITIALIZE_PASS_DEPENDENCY(LoopSimplify) |
| 77 | INITIALIZE_PASS_DEPENDENCY(LCSSA) |
| 78 | INITIALIZE_PASS_DEPENDENCY(ScalarEvolution) |
Chris Lattner | 2e12f1a | 2010-12-27 18:39:08 +0000 | [diff] [blame] | 79 | INITIALIZE_AG_DEPENDENCY(AliasAnalysis) |
Chris Lattner | e6bb649 | 2010-12-26 19:39:38 +0000 | [diff] [blame] | 80 | INITIALIZE_PASS_END(LoopIdiomRecognize, "loop-idiom", "Recognize loop idioms", |
| 81 | false, false) |
| 82 | |
| 83 | Pass *llvm::createLoopIdiomPass() { return new LoopIdiomRecognize(); } |
| 84 | |
Chris Lattner | 9f39188 | 2010-12-27 00:03:23 +0000 | [diff] [blame] | 85 | /// DeleteDeadInstruction - Delete this instruction. Before we do, go through |
| 86 | /// and zero out all the operands of this instruction. If any of them become |
| 87 | /// dead, delete them and the computation tree that feeds them. |
| 88 | /// |
| 89 | static void DeleteDeadInstruction(Instruction *I, ScalarEvolution &SE) { |
| 90 | SmallVector<Instruction*, 32> NowDeadInsts; |
| 91 | |
| 92 | NowDeadInsts.push_back(I); |
| 93 | |
| 94 | // Before we touch this instruction, remove it from SE! |
| 95 | do { |
| 96 | Instruction *DeadInst = NowDeadInsts.pop_back_val(); |
| 97 | |
| 98 | // This instruction is dead, zap it, in stages. Start by removing it from |
| 99 | // SCEV. |
| 100 | SE.forgetValue(DeadInst); |
| 101 | |
| 102 | for (unsigned op = 0, e = DeadInst->getNumOperands(); op != e; ++op) { |
| 103 | Value *Op = DeadInst->getOperand(op); |
| 104 | DeadInst->setOperand(op, 0); |
| 105 | |
| 106 | // If this operand just became dead, add it to the NowDeadInsts list. |
| 107 | if (!Op->use_empty()) continue; |
| 108 | |
| 109 | if (Instruction *OpI = dyn_cast<Instruction>(Op)) |
| 110 | if (isInstructionTriviallyDead(OpI)) |
| 111 | NowDeadInsts.push_back(OpI); |
| 112 | } |
| 113 | |
| 114 | DeadInst->eraseFromParent(); |
| 115 | |
| 116 | } while (!NowDeadInsts.empty()); |
| 117 | } |
| 118 | |
Chris Lattner | e6bb649 | 2010-12-26 19:39:38 +0000 | [diff] [blame] | 119 | bool LoopIdiomRecognize::runOnLoop(Loop *L, LPPassManager &LPM) { |
Chris Lattner | 22920b5 | 2010-12-26 20:45:45 +0000 | [diff] [blame] | 120 | CurLoop = L; |
| 121 | |
Chris Lattner | e6bb649 | 2010-12-26 19:39:38 +0000 | [diff] [blame] | 122 | // We only look at trivial single basic block loops. |
| 123 | // TODO: eventually support more complex loops, scanning the header. |
| 124 | if (L->getBlocks().size() != 1) |
| 125 | return false; |
| 126 | |
Chris Lattner | 22920b5 | 2010-12-26 20:45:45 +0000 | [diff] [blame] | 127 | // The trip count of the loop must be analyzable. |
| 128 | SE = &getAnalysis<ScalarEvolution>(); |
| 129 | if (!SE->hasLoopInvariantBackedgeTakenCount(L)) |
| 130 | return false; |
| 131 | const SCEV *BECount = SE->getBackedgeTakenCount(L); |
| 132 | if (isa<SCEVCouldNotCompute>(BECount)) return false; |
| 133 | |
| 134 | // We require target data for now. |
| 135 | TD = getAnalysisIfAvailable<TargetData>(); |
| 136 | if (TD == 0) return false; |
| 137 | |
Chris Lattner | e6bb649 | 2010-12-26 19:39:38 +0000 | [diff] [blame] | 138 | BasicBlock *BB = L->getHeader(); |
Chris Lattner | 22920b5 | 2010-12-26 20:45:45 +0000 | [diff] [blame] | 139 | DEBUG(dbgs() << "loop-idiom Scanning: F[" << BB->getParent()->getName() |
Chris Lattner | e6bb649 | 2010-12-26 19:39:38 +0000 | [diff] [blame] | 140 | << "] Loop %" << BB->getName() << "\n"); |
| 141 | |
Chris Lattner | 22920b5 | 2010-12-26 20:45:45 +0000 | [diff] [blame] | 142 | bool MadeChange = false; |
| 143 | for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) { |
| 144 | // Look for store instructions, which may be memsets. |
Chris Lattner | a92ff91 | 2010-12-26 23:42:51 +0000 | [diff] [blame] | 145 | StoreInst *SI = dyn_cast<StoreInst>(I++); |
| 146 | if (SI == 0 || SI->isVolatile()) continue; |
| 147 | |
Chris Lattner | 2e12f1a | 2010-12-27 18:39:08 +0000 | [diff] [blame] | 148 | WeakVH InstPtr(SI); |
| 149 | if (!processLoopStore(SI, BECount)) continue; |
| 150 | |
| 151 | MadeChange = true; |
| 152 | |
| 153 | // If processing the store invalidated our iterator, start over from the |
| 154 | // head of the loop. |
| 155 | if (InstPtr == 0) |
| 156 | I = BB->begin(); |
Chris Lattner | 22920b5 | 2010-12-26 20:45:45 +0000 | [diff] [blame] | 157 | } |
| 158 | |
| 159 | return MadeChange; |
Chris Lattner | e6bb649 | 2010-12-26 19:39:38 +0000 | [diff] [blame] | 160 | } |
| 161 | |
| 162 | /// scanBlock - Look over a block to see if we can promote anything out of it. |
Chris Lattner | 22920b5 | 2010-12-26 20:45:45 +0000 | [diff] [blame] | 163 | bool LoopIdiomRecognize::processLoopStore(StoreInst *SI, const SCEV *BECount) { |
| 164 | Value *StoredVal = SI->getValueOperand(); |
Chris Lattner | a92ff91 | 2010-12-26 23:42:51 +0000 | [diff] [blame] | 165 | Value *StorePtr = SI->getPointerOperand(); |
Chris Lattner | e6bb649 | 2010-12-26 19:39:38 +0000 | [diff] [blame] | 166 | |
Chris Lattner | 95ae676 | 2010-12-28 18:53:48 +0000 | [diff] [blame] | 167 | // Reject stores that are so large that they overflow an unsigned. |
Chris Lattner | 22920b5 | 2010-12-26 20:45:45 +0000 | [diff] [blame] | 168 | uint64_t SizeInBits = TD->getTypeSizeInBits(StoredVal->getType()); |
Chris Lattner | 95ae676 | 2010-12-28 18:53:48 +0000 | [diff] [blame] | 169 | if ((SizeInBits & 7) || (SizeInBits >> 32) != 0) |
Chris Lattner | 22920b5 | 2010-12-26 20:45:45 +0000 | [diff] [blame] | 170 | return false; |
Chris Lattner | e6bb649 | 2010-12-26 19:39:38 +0000 | [diff] [blame] | 171 | |
Chris Lattner | 22920b5 | 2010-12-26 20:45:45 +0000 | [diff] [blame] | 172 | // See if the pointer expression is an AddRec like {base,+,1} on the current |
| 173 | // loop, which indicates a strided store. If we have something else, it's a |
| 174 | // random store we can't handle. |
Chris Lattner | a92ff91 | 2010-12-26 23:42:51 +0000 | [diff] [blame] | 175 | const SCEVAddRecExpr *Ev = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr)); |
Chris Lattner | 22920b5 | 2010-12-26 20:45:45 +0000 | [diff] [blame] | 176 | if (Ev == 0 || Ev->getLoop() != CurLoop || !Ev->isAffine()) |
| 177 | return false; |
| 178 | |
| 179 | // Check to see if the stride matches the size of the store. If so, then we |
| 180 | // know that every byte is touched in the loop. |
| 181 | unsigned StoreSize = (unsigned)SizeInBits >> 3; |
| 182 | const SCEVConstant *Stride = dyn_cast<SCEVConstant>(Ev->getOperand(1)); |
Chris Lattner | 30980b6 | 2011-01-01 19:39:01 +0000 | [diff] [blame] | 183 | |
| 184 | // TODO: Could also handle negative stride here someday, that will require the |
| 185 | // validity check in mayLoopModRefLocation to be updated though. |
Chris Lattner | 22920b5 | 2010-12-26 20:45:45 +0000 | [diff] [blame] | 186 | if (Stride == 0 || StoreSize != Stride->getValue()->getValue()) |
| 187 | return false; |
| 188 | |
Chris Lattner | 22920b5 | 2010-12-26 20:45:45 +0000 | [diff] [blame] | 189 | // If the stored value is a byte-wise value (like i32 -1), then it may be |
| 190 | // turned into a memset of i8 -1, assuming that all the consequtive bytes |
| 191 | // are stored. A store of i32 0x01020304 can never be turned into a memset. |
Chris Lattner | a92ff91 | 2010-12-26 23:42:51 +0000 | [diff] [blame] | 192 | if (Value *SplatValue = isBytewiseValue(StoredVal)) |
| 193 | return processLoopStoreOfSplatValue(SI, StoreSize, SplatValue, Ev, BECount); |
| 194 | |
| 195 | // Handle the memcpy case here. |
Chris Lattner | a64cbf0 | 2011-01-01 19:54:22 +0000 | [diff] [blame^] | 196 | // errs() << "Found strided store: " << *Ev << "\n"; |
Chris Lattner | 22920b5 | 2010-12-26 20:45:45 +0000 | [diff] [blame] | 197 | |
Chris Lattner | e6bb649 | 2010-12-26 19:39:38 +0000 | [diff] [blame] | 198 | return false; |
| 199 | } |
| 200 | |
Chris Lattner | 30980b6 | 2011-01-01 19:39:01 +0000 | [diff] [blame] | 201 | /// mayLoopModRefLocation - Return true if the specified loop might do a load or |
| 202 | /// store to the same location that the specified store could store to, which is |
| 203 | /// a loop-strided access. |
Chris Lattner | a64cbf0 | 2011-01-01 19:54:22 +0000 | [diff] [blame^] | 204 | static bool mayLoopModRefLocation(StoreInst *SI, Loop *L, const SCEV *BECount, |
| 205 | unsigned StoreSize, AliasAnalysis &AA) { |
Chris Lattner | 30980b6 | 2011-01-01 19:39:01 +0000 | [diff] [blame] | 206 | // Get the location that may be stored across the loop. Since the access is |
| 207 | // strided positively through memory, we say that the modified location starts |
| 208 | // at the pointer and has infinite size. |
Chris Lattner | a64cbf0 | 2011-01-01 19:54:22 +0000 | [diff] [blame^] | 209 | uint64_t AccessSize = AliasAnalysis::UnknownSize; |
| 210 | |
| 211 | // If the loop iterates a fixed number of times, we can refine the access size |
| 212 | // to be exactly the size of the memset, which is (BECount+1)*StoreSize |
| 213 | if (const SCEVConstant *BECst = dyn_cast<SCEVConstant>(BECount)) |
| 214 | AccessSize = (BECst->getValue()->getZExtValue()+1)*StoreSize; |
| 215 | |
| 216 | // TODO: For this to be really effective, we have to dive into the pointer |
| 217 | // operand in the store. Store to &A[i] of 100 will always return may alias |
| 218 | // with store of &A[100], we need to StoreLoc to be "A" with size of 100, |
| 219 | // which will then no-alias a store to &A[100]. |
| 220 | AliasAnalysis::Location StoreLoc(SI->getPointerOperand(), AccessSize); |
Chris Lattner | 30980b6 | 2011-01-01 19:39:01 +0000 | [diff] [blame] | 221 | |
| 222 | for (Loop::block_iterator BI = L->block_begin(), E = L->block_end(); BI != E; |
| 223 | ++BI) |
| 224 | for (BasicBlock::iterator I = (*BI)->begin(), E = (*BI)->end(); I != E; ++I) |
| 225 | if (AA.getModRefInfo(I, StoreLoc) != AliasAnalysis::NoModRef) |
| 226 | return true; |
| 227 | |
| 228 | return false; |
| 229 | } |
| 230 | |
Chris Lattner | a92ff91 | 2010-12-26 23:42:51 +0000 | [diff] [blame] | 231 | /// processLoopStoreOfSplatValue - We see a strided store of a memsetable value. |
| 232 | /// If we can transform this into a memset in the loop preheader, do so. |
| 233 | bool LoopIdiomRecognize:: |
| 234 | processLoopStoreOfSplatValue(StoreInst *SI, unsigned StoreSize, |
| 235 | Value *SplatValue, |
| 236 | const SCEVAddRecExpr *Ev, const SCEV *BECount) { |
Chris Lattner | 30980b6 | 2011-01-01 19:39:01 +0000 | [diff] [blame] | 237 | // Temporarily remove the store from the loop, to avoid the mod/ref query from |
| 238 | // seeing it. |
| 239 | Instruction *InstAfterStore = ++BasicBlock::iterator(SI); |
| 240 | SI->removeFromParent(); |
| 241 | |
Chris Lattner | a92ff91 | 2010-12-26 23:42:51 +0000 | [diff] [blame] | 242 | // Okay, we have a strided store "p[i]" of a splattable value. We can turn |
| 243 | // this into a memset in the loop preheader now if we want. However, this |
| 244 | // would be unsafe to do if there is anything else in the loop that may read |
| 245 | // or write to the aliased location. Check for an alias. |
Chris Lattner | a64cbf0 | 2011-01-01 19:54:22 +0000 | [diff] [blame^] | 246 | bool Unsafe = mayLoopModRefLocation(SI, CurLoop, BECount, StoreSize, |
| 247 | getAnalysis<AliasAnalysis>()); |
Chris Lattner | 30980b6 | 2011-01-01 19:39:01 +0000 | [diff] [blame] | 248 | |
| 249 | SI->insertBefore(InstAfterStore); |
Chris Lattner | a92ff91 | 2010-12-26 23:42:51 +0000 | [diff] [blame] | 250 | |
Chris Lattner | 30980b6 | 2011-01-01 19:39:01 +0000 | [diff] [blame] | 251 | if (Unsafe) return false; |
Chris Lattner | a92ff91 | 2010-12-26 23:42:51 +0000 | [diff] [blame] | 252 | |
| 253 | // Okay, everything looks good, insert the memset. |
| 254 | BasicBlock *Preheader = CurLoop->getLoopPreheader(); |
| 255 | |
| 256 | IRBuilder<> Builder(Preheader->getTerminator()); |
| 257 | |
| 258 | // The trip count of the loop and the base pointer of the addrec SCEV is |
| 259 | // guaranteed to be loop invariant, which means that it should dominate the |
| 260 | // header. Just insert code for it in the preheader. |
| 261 | SCEVExpander Expander(*SE); |
| 262 | |
| 263 | unsigned AddrSpace = SI->getPointerAddressSpace(); |
| 264 | Value *BasePtr = |
| 265 | Expander.expandCodeFor(Ev->getStart(), Builder.getInt8PtrTy(AddrSpace), |
| 266 | Preheader->getTerminator()); |
| 267 | |
| 268 | // The # stored bytes is (BECount+1)*Size. Expand the trip count out to |
| 269 | // pointer size if it isn't already. |
| 270 | const Type *IntPtr = TD->getIntPtrType(SI->getContext()); |
| 271 | unsigned BESize = SE->getTypeSizeInBits(BECount->getType()); |
| 272 | if (BESize < TD->getPointerSizeInBits()) |
| 273 | BECount = SE->getZeroExtendExpr(BECount, IntPtr); |
| 274 | else if (BESize > TD->getPointerSizeInBits()) |
| 275 | BECount = SE->getTruncateExpr(BECount, IntPtr); |
| 276 | |
| 277 | const SCEV *NumBytesS = SE->getAddExpr(BECount, SE->getConstant(IntPtr, 1), |
| 278 | true, true /*nooverflow*/); |
| 279 | if (StoreSize != 1) |
| 280 | NumBytesS = SE->getMulExpr(NumBytesS, SE->getConstant(IntPtr, StoreSize), |
| 281 | true, true /*nooverflow*/); |
| 282 | |
| 283 | Value *NumBytes = |
| 284 | Expander.expandCodeFor(NumBytesS, IntPtr, Preheader->getTerminator()); |
| 285 | |
| 286 | Value *NewCall = |
| 287 | Builder.CreateMemSet(BasePtr, SplatValue, NumBytes, SI->getAlignment()); |
| 288 | |
| 289 | DEBUG(dbgs() << " Formed memset: " << *NewCall << "\n" |
| 290 | << " from store to: " << *Ev << " at: " << *SI << "\n"); |
Duncan Sands | 7922d34 | 2010-12-28 09:41:15 +0000 | [diff] [blame] | 291 | (void)NewCall; |
Chris Lattner | a92ff91 | 2010-12-26 23:42:51 +0000 | [diff] [blame] | 292 | |
Chris Lattner | 9f39188 | 2010-12-27 00:03:23 +0000 | [diff] [blame] | 293 | // Okay, the memset has been formed. Zap the original store and anything that |
| 294 | // feeds into it. |
| 295 | DeleteDeadInstruction(SI, *SE); |
Chris Lattner | a92ff91 | 2010-12-26 23:42:51 +0000 | [diff] [blame] | 296 | return true; |
| 297 | } |
| 298 | |