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 | //===----------------------------------------------------------------------===// |
Chris Lattner | bdce572 | 2011-01-02 18:32:09 +0000 | [diff] [blame] | 15 | // |
| 16 | // TODO List: |
| 17 | // |
| 18 | // Future loop memory idioms to recognize: |
Chandler Carruth | a864748 | 2012-11-02 08:33:25 +0000 | [diff] [blame] | 19 | // memcmp, memmove, strlen, etc. |
Chris Lattner | bdce572 | 2011-01-02 18:32:09 +0000 | [diff] [blame] | 20 | // Future floating point idioms to recognize in -ffast-math mode: |
| 21 | // fpowi |
| 22 | // Future integer operation idioms to recognize: |
| 23 | // ctpop, ctlz, cttz |
| 24 | // |
| 25 | // Beware that isel's default lowering for ctpop is highly inefficient for |
| 26 | // i64 and larger types when i64 is legal and the value has few bits set. It |
| 27 | // would be good to enhance isel to emit a loop for ctpop in this case. |
| 28 | // |
| 29 | // We should enhance the memset/memcpy recognition to handle multiple stores in |
| 30 | // the loop. This would handle things like: |
| 31 | // void foo(_Complex float *P) |
| 32 | // for (i) { __real__(*P) = 0; __imag__(*P) = 0; } |
Chris Lattner | 91139cc | 2011-01-02 23:19:45 +0000 | [diff] [blame] | 33 | // |
Chris Lattner | 408b534 | 2011-02-21 02:08:54 +0000 | [diff] [blame] | 34 | // We should enhance this to handle negative strides through memory. |
| 35 | // Alternatively (and perhaps better) we could rely on an earlier pass to force |
| 36 | // forward iteration through memory, which is generally better for cache |
| 37 | // behavior. Negative strides *do* happen for memset/memcpy loops. |
| 38 | // |
Chris Lattner | d957c71 | 2011-01-03 01:10:08 +0000 | [diff] [blame] | 39 | // This could recognize common matrix multiplies and dot product idioms and |
Chris Lattner | 91139cc | 2011-01-02 23:19:45 +0000 | [diff] [blame] | 40 | // replace them with calls to BLAS (if linked in??). |
| 41 | // |
Chris Lattner | bdce572 | 2011-01-02 18:32:09 +0000 | [diff] [blame] | 42 | //===----------------------------------------------------------------------===// |
Chris Lattner | e6bb649 | 2010-12-26 19:39:38 +0000 | [diff] [blame] | 43 | |
| 44 | #define DEBUG_TYPE "loop-idiom" |
| 45 | #include "llvm/Transforms/Scalar.h" |
Chandler Carruth | 06cb8ed | 2012-06-29 12:38:19 +0000 | [diff] [blame] | 46 | #include "llvm/ADT/Statistic.h" |
Chris Lattner | 2e12f1a | 2010-12-27 18:39:08 +0000 | [diff] [blame] | 47 | #include "llvm/Analysis/AliasAnalysis.h" |
Chris Lattner | e6bb649 | 2010-12-26 19:39:38 +0000 | [diff] [blame] | 48 | #include "llvm/Analysis/LoopPass.h" |
Chris Lattner | a92ff91 | 2010-12-26 23:42:51 +0000 | [diff] [blame] | 49 | #include "llvm/Analysis/ScalarEvolutionExpander.h" |
Chandler Carruth | 06cb8ed | 2012-06-29 12:38:19 +0000 | [diff] [blame] | 50 | #include "llvm/Analysis/ScalarEvolutionExpressions.h" |
Chandler Carruth | be04929 | 2013-01-07 03:08:10 +0000 | [diff] [blame] | 51 | #include "llvm/Analysis/TargetTransformInfo.h" |
Chris Lattner | 22920b5 | 2010-12-26 20:45:45 +0000 | [diff] [blame] | 52 | #include "llvm/Analysis/ValueTracking.h" |
Chandler Carruth | 0b8c9a8 | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 53 | #include "llvm/IR/DataLayout.h" |
| 54 | #include "llvm/IR/IRBuilder.h" |
| 55 | #include "llvm/IR/IntrinsicInst.h" |
| 56 | #include "llvm/IR/Module.h" |
Chandler Carruth | 06cb8ed | 2012-06-29 12:38:19 +0000 | [diff] [blame] | 57 | #include "llvm/Support/Debug.h" |
| 58 | #include "llvm/Support/raw_ostream.h" |
Chris Lattner | c19175c | 2011-02-18 22:22:15 +0000 | [diff] [blame] | 59 | #include "llvm/Target/TargetLibraryInfo.h" |
Chris Lattner | 9f39188 | 2010-12-27 00:03:23 +0000 | [diff] [blame] | 60 | #include "llvm/Transforms/Utils/Local.h" |
Chris Lattner | e6bb649 | 2010-12-26 19:39:38 +0000 | [diff] [blame] | 61 | using namespace llvm; |
| 62 | |
Chandler Carruth | a864748 | 2012-11-02 08:33:25 +0000 | [diff] [blame] | 63 | STATISTIC(NumMemSet, "Number of memset's formed from loop stores"); |
| 64 | STATISTIC(NumMemCpy, "Number of memcpy's formed from loop load+stores"); |
Chris Lattner | e6bb649 | 2010-12-26 19:39:38 +0000 | [diff] [blame] | 65 | |
| 66 | namespace { |
Shuxin Yang | 5518a13 | 2012-12-09 03:12:46 +0000 | [diff] [blame] | 67 | |
| 68 | class LoopIdiomRecognize; |
| 69 | |
| 70 | /// This class defines some utility functions for loop idiom recognization. |
| 71 | class LIRUtil { |
| 72 | public: |
| 73 | /// Return true iff the block contains nothing but an uncondition branch |
| 74 | /// (aka goto instruction). |
| 75 | static bool isAlmostEmpty(BasicBlock *); |
| 76 | |
| 77 | static BranchInst *getBranch(BasicBlock *BB) { |
| 78 | return dyn_cast<BranchInst>(BB->getTerminator()); |
| 79 | } |
| 80 | |
| 81 | /// Return the condition of the branch terminating the given basic block. |
| 82 | static Value *getBrCondtion(BasicBlock *); |
| 83 | |
| 84 | /// Derive the precondition block (i.e the block that guards the loop |
| 85 | /// preheader) from the given preheader. |
| 86 | static BasicBlock *getPrecondBb(BasicBlock *PreHead); |
| 87 | }; |
| 88 | |
| 89 | /// This class is to recoginize idioms of population-count conducted in |
| 90 | /// a noncountable loop. Currently it only recognizes this pattern: |
| 91 | /// \code |
| 92 | /// while(x) {cnt++; ...; x &= x - 1; ...} |
| 93 | /// \endcode |
| 94 | class NclPopcountRecognize { |
| 95 | LoopIdiomRecognize &LIR; |
| 96 | Loop *CurLoop; |
| 97 | BasicBlock *PreCondBB; |
| 98 | |
| 99 | typedef IRBuilder<> IRBuilderTy; |
| 100 | |
| 101 | public: |
| 102 | explicit NclPopcountRecognize(LoopIdiomRecognize &TheLIR); |
| 103 | bool recognize(); |
| 104 | |
| 105 | private: |
| 106 | /// Take a glimpse of the loop to see if we need to go ahead recoginizing |
| 107 | /// the idiom. |
| 108 | bool preliminaryScreen(); |
| 109 | |
| 110 | /// Check if the given conditional branch is based on the comparison |
| 111 | /// beween a variable and zero, and if the variable is non-zero, the |
| 112 | /// control yeilds to the loop entry. If the branch matches the behavior, |
| 113 | /// the variable involved in the comparion is returned. This function will |
| 114 | /// be called to see if the precondition and postcondition of the loop |
| 115 | /// are in desirable form. |
| 116 | Value *matchCondition (BranchInst *Br, BasicBlock *NonZeroTarget) const; |
| 117 | |
| 118 | /// Return true iff the idiom is detected in the loop. and 1) \p CntInst |
| 119 | /// is set to the instruction counting the pupulation bit. 2) \p CntPhi |
| 120 | /// is set to the corresponding phi node. 3) \p Var is set to the value |
| 121 | /// whose population bits are being counted. |
| 122 | bool detectIdiom |
| 123 | (Instruction *&CntInst, PHINode *&CntPhi, Value *&Var) const; |
| 124 | |
| 125 | /// Insert ctpop intrinsic function and some obviously dead instructions. |
| 126 | void transform (Instruction *CntInst, PHINode *CntPhi, Value *Var); |
| 127 | |
| 128 | /// Create llvm.ctpop.* intrinsic function. |
| 129 | CallInst *createPopcntIntrinsic(IRBuilderTy &IRB, Value *Val, DebugLoc DL); |
| 130 | }; |
| 131 | |
Chris Lattner | e6bb649 | 2010-12-26 19:39:38 +0000 | [diff] [blame] | 132 | class LoopIdiomRecognize : public LoopPass { |
Chris Lattner | 22920b5 | 2010-12-26 20:45:45 +0000 | [diff] [blame] | 133 | Loop *CurLoop; |
Micah Villmow | 3574eca | 2012-10-08 16:38:25 +0000 | [diff] [blame] | 134 | const DataLayout *TD; |
Chris Lattner | 62c50fd | 2011-01-02 19:01:03 +0000 | [diff] [blame] | 135 | DominatorTree *DT; |
Chris Lattner | 22920b5 | 2010-12-26 20:45:45 +0000 | [diff] [blame] | 136 | ScalarEvolution *SE; |
Chris Lattner | c19175c | 2011-02-18 22:22:15 +0000 | [diff] [blame] | 137 | TargetLibraryInfo *TLI; |
Chandler Carruth | 9980b8a | 2013-01-05 10:00:09 +0000 | [diff] [blame] | 138 | const TargetTransformInfo *TTI; |
Chris Lattner | e6bb649 | 2010-12-26 19:39:38 +0000 | [diff] [blame] | 139 | public: |
| 140 | static char ID; |
| 141 | explicit LoopIdiomRecognize() : LoopPass(ID) { |
| 142 | initializeLoopIdiomRecognizePass(*PassRegistry::getPassRegistry()); |
Chandler Carruth | 9980b8a | 2013-01-05 10:00:09 +0000 | [diff] [blame] | 143 | TD = 0; DT = 0; SE = 0; TLI = 0; TTI = 0; |
Chris Lattner | e6bb649 | 2010-12-26 19:39:38 +0000 | [diff] [blame] | 144 | } |
| 145 | |
| 146 | bool runOnLoop(Loop *L, LPPassManager &LPM); |
Chris Lattner | 62c50fd | 2011-01-02 19:01:03 +0000 | [diff] [blame] | 147 | bool runOnLoopBlock(BasicBlock *BB, const SCEV *BECount, |
| 148 | SmallVectorImpl<BasicBlock*> &ExitBlocks); |
Chris Lattner | e6bb649 | 2010-12-26 19:39:38 +0000 | [diff] [blame] | 149 | |
Chris Lattner | 22920b5 | 2010-12-26 20:45:45 +0000 | [diff] [blame] | 150 | bool processLoopStore(StoreInst *SI, const SCEV *BECount); |
Chris Lattner | e41d3c0 | 2011-01-04 07:46:33 +0000 | [diff] [blame] | 151 | bool processLoopMemSet(MemSetInst *MSI, const SCEV *BECount); |
Andrew Trick | d99b39e | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 152 | |
Chris Lattner | 3a39372 | 2011-02-19 19:31:39 +0000 | [diff] [blame] | 153 | bool processLoopStridedStore(Value *DestPtr, unsigned StoreSize, |
| 154 | unsigned StoreAlignment, |
| 155 | Value *SplatValue, Instruction *TheStore, |
| 156 | const SCEVAddRecExpr *Ev, |
| 157 | const SCEV *BECount); |
Chris Lattner | e2c4392 | 2011-01-02 03:37:56 +0000 | [diff] [blame] | 158 | bool processLoopStoreOfLoopLoad(StoreInst *SI, unsigned StoreSize, |
| 159 | const SCEVAddRecExpr *StoreEv, |
| 160 | const SCEVAddRecExpr *LoadEv, |
| 161 | const SCEV *BECount); |
Andrew Trick | d99b39e | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 162 | |
Chris Lattner | e6bb649 | 2010-12-26 19:39:38 +0000 | [diff] [blame] | 163 | /// This transformation requires natural loop information & requires that |
| 164 | /// loop preheaders be inserted into the CFG. |
| 165 | /// |
| 166 | virtual void getAnalysisUsage(AnalysisUsage &AU) const { |
| 167 | AU.addRequired<LoopInfo>(); |
| 168 | AU.addPreserved<LoopInfo>(); |
| 169 | AU.addRequiredID(LoopSimplifyID); |
| 170 | AU.addPreservedID(LoopSimplifyID); |
| 171 | AU.addRequiredID(LCSSAID); |
| 172 | AU.addPreservedID(LCSSAID); |
Chris Lattner | 2e12f1a | 2010-12-27 18:39:08 +0000 | [diff] [blame] | 173 | AU.addRequired<AliasAnalysis>(); |
| 174 | AU.addPreserved<AliasAnalysis>(); |
Chris Lattner | e6bb649 | 2010-12-26 19:39:38 +0000 | [diff] [blame] | 175 | AU.addRequired<ScalarEvolution>(); |
| 176 | AU.addPreserved<ScalarEvolution>(); |
| 177 | AU.addPreserved<DominatorTree>(); |
Chris Lattner | 62c50fd | 2011-01-02 19:01:03 +0000 | [diff] [blame] | 178 | AU.addRequired<DominatorTree>(); |
Chris Lattner | c19175c | 2011-02-18 22:22:15 +0000 | [diff] [blame] | 179 | AU.addRequired<TargetLibraryInfo>(); |
Chandler Carruth | d12aae6 | 2013-01-07 09:17:41 +0000 | [diff] [blame^] | 180 | AU.addRequired<TargetTransformInfo>(); |
Chris Lattner | e6bb649 | 2010-12-26 19:39:38 +0000 | [diff] [blame] | 181 | } |
Shuxin Yang | 5518a13 | 2012-12-09 03:12:46 +0000 | [diff] [blame] | 182 | |
| 183 | const DataLayout *getDataLayout() { |
| 184 | return TD ? TD : TD=getAnalysisIfAvailable<DataLayout>(); |
| 185 | } |
| 186 | |
| 187 | DominatorTree *getDominatorTree() { |
| 188 | return DT ? DT : (DT=&getAnalysis<DominatorTree>()); |
| 189 | } |
| 190 | |
| 191 | ScalarEvolution *getScalarEvolution() { |
| 192 | return SE ? SE : (SE = &getAnalysis<ScalarEvolution>()); |
| 193 | } |
| 194 | |
| 195 | TargetLibraryInfo *getTargetLibraryInfo() { |
| 196 | return TLI ? TLI : (TLI = &getAnalysis<TargetLibraryInfo>()); |
| 197 | } |
| 198 | |
Chandler Carruth | 9980b8a | 2013-01-05 10:00:09 +0000 | [diff] [blame] | 199 | const TargetTransformInfo *getTargetTransformInfo() { |
Chandler Carruth | d12aae6 | 2013-01-07 09:17:41 +0000 | [diff] [blame^] | 200 | return TTI ? TTI : (TTI = &getAnalysis<TargetTransformInfo>()); |
Shuxin Yang | 5518a13 | 2012-12-09 03:12:46 +0000 | [diff] [blame] | 201 | } |
| 202 | |
| 203 | Loop *getLoop() const { return CurLoop; } |
| 204 | |
| 205 | private: |
| 206 | bool runOnNoncountableLoop(); |
| 207 | bool runOnCountableLoop(); |
Chris Lattner | e6bb649 | 2010-12-26 19:39:38 +0000 | [diff] [blame] | 208 | }; |
| 209 | } |
| 210 | |
| 211 | char LoopIdiomRecognize::ID = 0; |
| 212 | INITIALIZE_PASS_BEGIN(LoopIdiomRecognize, "loop-idiom", "Recognize loop idioms", |
| 213 | false, false) |
| 214 | INITIALIZE_PASS_DEPENDENCY(LoopInfo) |
Chris Lattner | 62c50fd | 2011-01-02 19:01:03 +0000 | [diff] [blame] | 215 | INITIALIZE_PASS_DEPENDENCY(DominatorTree) |
Chris Lattner | e6bb649 | 2010-12-26 19:39:38 +0000 | [diff] [blame] | 216 | INITIALIZE_PASS_DEPENDENCY(LoopSimplify) |
| 217 | INITIALIZE_PASS_DEPENDENCY(LCSSA) |
| 218 | INITIALIZE_PASS_DEPENDENCY(ScalarEvolution) |
Chris Lattner | c19175c | 2011-02-18 22:22:15 +0000 | [diff] [blame] | 219 | INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo) |
Chris Lattner | 2e12f1a | 2010-12-27 18:39:08 +0000 | [diff] [blame] | 220 | INITIALIZE_AG_DEPENDENCY(AliasAnalysis) |
Chandler Carruth | d12aae6 | 2013-01-07 09:17:41 +0000 | [diff] [blame^] | 221 | INITIALIZE_AG_DEPENDENCY(TargetTransformInfo) |
Chris Lattner | e6bb649 | 2010-12-26 19:39:38 +0000 | [diff] [blame] | 222 | INITIALIZE_PASS_END(LoopIdiomRecognize, "loop-idiom", "Recognize loop idioms", |
| 223 | false, false) |
| 224 | |
| 225 | Pass *llvm::createLoopIdiomPass() { return new LoopIdiomRecognize(); } |
| 226 | |
Chris Lattner | 4f81b54 | 2011-05-22 17:39:56 +0000 | [diff] [blame] | 227 | /// deleteDeadInstruction - Delete this instruction. Before we do, go through |
Chris Lattner | 9f39188 | 2010-12-27 00:03:23 +0000 | [diff] [blame] | 228 | /// and zero out all the operands of this instruction. If any of them become |
| 229 | /// dead, delete them and the computation tree that feeds them. |
| 230 | /// |
Benjamin Kramer | 8e0d1c0 | 2012-08-29 15:32:21 +0000 | [diff] [blame] | 231 | static void deleteDeadInstruction(Instruction *I, ScalarEvolution &SE, |
| 232 | const TargetLibraryInfo *TLI) { |
Chris Lattner | 9f39188 | 2010-12-27 00:03:23 +0000 | [diff] [blame] | 233 | SmallVector<Instruction*, 32> NowDeadInsts; |
Andrew Trick | d99b39e | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 234 | |
Chris Lattner | 9f39188 | 2010-12-27 00:03:23 +0000 | [diff] [blame] | 235 | NowDeadInsts.push_back(I); |
Andrew Trick | d99b39e | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 236 | |
Chris Lattner | 9f39188 | 2010-12-27 00:03:23 +0000 | [diff] [blame] | 237 | // Before we touch this instruction, remove it from SE! |
| 238 | do { |
| 239 | Instruction *DeadInst = NowDeadInsts.pop_back_val(); |
Andrew Trick | d99b39e | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 240 | |
Chris Lattner | 9f39188 | 2010-12-27 00:03:23 +0000 | [diff] [blame] | 241 | // This instruction is dead, zap it, in stages. Start by removing it from |
| 242 | // SCEV. |
| 243 | SE.forgetValue(DeadInst); |
Andrew Trick | d99b39e | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 244 | |
Chris Lattner | 9f39188 | 2010-12-27 00:03:23 +0000 | [diff] [blame] | 245 | for (unsigned op = 0, e = DeadInst->getNumOperands(); op != e; ++op) { |
| 246 | Value *Op = DeadInst->getOperand(op); |
| 247 | DeadInst->setOperand(op, 0); |
Andrew Trick | d99b39e | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 248 | |
Chris Lattner | 9f39188 | 2010-12-27 00:03:23 +0000 | [diff] [blame] | 249 | // If this operand just became dead, add it to the NowDeadInsts list. |
| 250 | if (!Op->use_empty()) continue; |
Andrew Trick | d99b39e | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 251 | |
Chris Lattner | 9f39188 | 2010-12-27 00:03:23 +0000 | [diff] [blame] | 252 | if (Instruction *OpI = dyn_cast<Instruction>(Op)) |
Benjamin Kramer | 8e0d1c0 | 2012-08-29 15:32:21 +0000 | [diff] [blame] | 253 | if (isInstructionTriviallyDead(OpI, TLI)) |
Chris Lattner | 9f39188 | 2010-12-27 00:03:23 +0000 | [diff] [blame] | 254 | NowDeadInsts.push_back(OpI); |
| 255 | } |
Andrew Trick | d99b39e | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 256 | |
Chris Lattner | 9f39188 | 2010-12-27 00:03:23 +0000 | [diff] [blame] | 257 | DeadInst->eraseFromParent(); |
Andrew Trick | d99b39e | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 258 | |
Chris Lattner | 9f39188 | 2010-12-27 00:03:23 +0000 | [diff] [blame] | 259 | } while (!NowDeadInsts.empty()); |
| 260 | } |
| 261 | |
Chandler Carruth | a864748 | 2012-11-02 08:33:25 +0000 | [diff] [blame] | 262 | /// deleteIfDeadInstruction - If the specified value is a dead instruction, |
| 263 | /// delete it and any recursively used instructions. |
| 264 | static void deleteIfDeadInstruction(Value *V, ScalarEvolution &SE, |
| 265 | const TargetLibraryInfo *TLI) { |
| 266 | if (Instruction *I = dyn_cast<Instruction>(V)) |
| 267 | if (isInstructionTriviallyDead(I, TLI)) |
| 268 | deleteDeadInstruction(I, SE, TLI); |
| 269 | } |
| 270 | |
Shuxin Yang | 5518a13 | 2012-12-09 03:12:46 +0000 | [diff] [blame] | 271 | //===----------------------------------------------------------------------===// |
| 272 | // |
| 273 | // Implementation of LIRUtil |
| 274 | // |
| 275 | //===----------------------------------------------------------------------===// |
| 276 | |
| 277 | // This fucntion will return true iff the given block contains nothing but goto. |
| 278 | // A typical usage of this function is to check if the preheader fucntion is |
| 279 | // "almost" empty such that generated intrinsic function can be moved across |
| 280 | // preheader and to be placed at the end of the preconditiona block without |
| 281 | // concerning of breaking data dependence. |
| 282 | bool LIRUtil::isAlmostEmpty(BasicBlock *BB) { |
| 283 | if (BranchInst *Br = getBranch(BB)) { |
| 284 | return Br->isUnconditional() && BB->size() == 1; |
| 285 | } |
| 286 | return false; |
| 287 | } |
| 288 | |
| 289 | Value *LIRUtil::getBrCondtion(BasicBlock *BB) { |
| 290 | BranchInst *Br = getBranch(BB); |
| 291 | return Br ? Br->getCondition() : 0; |
| 292 | } |
| 293 | |
| 294 | BasicBlock *LIRUtil::getPrecondBb(BasicBlock *PreHead) { |
| 295 | if (BasicBlock *BB = PreHead->getSinglePredecessor()) { |
| 296 | BranchInst *Br = getBranch(BB); |
| 297 | return Br && Br->isConditional() ? BB : 0; |
| 298 | } |
| 299 | return 0; |
| 300 | } |
| 301 | |
| 302 | //===----------------------------------------------------------------------===// |
| 303 | // |
| 304 | // Implementation of NclPopcountRecognize |
| 305 | // |
| 306 | //===----------------------------------------------------------------------===// |
| 307 | |
| 308 | NclPopcountRecognize::NclPopcountRecognize(LoopIdiomRecognize &TheLIR): |
| 309 | LIR(TheLIR), CurLoop(TheLIR.getLoop()), PreCondBB(0) { |
| 310 | } |
| 311 | |
| 312 | bool NclPopcountRecognize::preliminaryScreen() { |
Chandler Carruth | 9980b8a | 2013-01-05 10:00:09 +0000 | [diff] [blame] | 313 | const TargetTransformInfo *TTI = LIR.getTargetTransformInfo(); |
Chandler Carruth | d1b8ef9 | 2013-01-07 03:16:03 +0000 | [diff] [blame] | 314 | if (TTI->getPopcntSupport(32) != TargetTransformInfo::PSK_FastHardware) |
Shuxin Yang | 5518a13 | 2012-12-09 03:12:46 +0000 | [diff] [blame] | 315 | return false; |
| 316 | |
| 317 | // Counting population are usually conducted by few arithmetic instrutions. |
| 318 | // Such instructions can be easilly "absorbed" by vacant slots in a |
| 319 | // non-compact loop. Therefore, recognizing popcount idiom only makes sense |
| 320 | // in a compact loop. |
| 321 | |
| 322 | // Give up if the loop has multiple blocks or multiple backedges. |
| 323 | if (CurLoop->getNumBackEdges() != 1 || CurLoop->getNumBlocks() != 1) |
| 324 | return false; |
| 325 | |
| 326 | BasicBlock *LoopBody = *(CurLoop->block_begin()); |
| 327 | if (LoopBody->size() >= 20) { |
| 328 | // The loop is too big, bail out. |
| 329 | return false; |
| 330 | } |
| 331 | |
| 332 | // It should have a preheader containing nothing but a goto instruction. |
| 333 | BasicBlock *PreHead = CurLoop->getLoopPreheader(); |
| 334 | if (!PreHead || !LIRUtil::isAlmostEmpty(PreHead)) |
| 335 | return false; |
| 336 | |
| 337 | // It should have a precondition block where the generated popcount instrinsic |
| 338 | // function will be inserted. |
| 339 | PreCondBB = LIRUtil::getPrecondBb(PreHead); |
| 340 | if (!PreCondBB) |
| 341 | return false; |
| 342 | |
| 343 | return true; |
| 344 | } |
| 345 | |
| 346 | Value *NclPopcountRecognize::matchCondition (BranchInst *Br, |
| 347 | BasicBlock *LoopEntry) const { |
| 348 | if (!Br || !Br->isConditional()) |
| 349 | return 0; |
| 350 | |
| 351 | ICmpInst *Cond = dyn_cast<ICmpInst>(Br->getCondition()); |
| 352 | if (!Cond) |
| 353 | return 0; |
| 354 | |
| 355 | ConstantInt *CmpZero = dyn_cast<ConstantInt>(Cond->getOperand(1)); |
| 356 | if (!CmpZero || !CmpZero->isZero()) |
| 357 | return 0; |
| 358 | |
| 359 | ICmpInst::Predicate Pred = Cond->getPredicate(); |
| 360 | if ((Pred == ICmpInst::ICMP_NE && Br->getSuccessor(0) == LoopEntry) || |
| 361 | (Pred == ICmpInst::ICMP_EQ && Br->getSuccessor(1) == LoopEntry)) |
| 362 | return Cond->getOperand(0); |
| 363 | |
| 364 | return 0; |
| 365 | } |
| 366 | |
| 367 | bool NclPopcountRecognize::detectIdiom(Instruction *&CntInst, |
| 368 | PHINode *&CntPhi, |
| 369 | Value *&Var) const { |
| 370 | // Following code tries to detect this idiom: |
| 371 | // |
| 372 | // if (x0 != 0) |
| 373 | // goto loop-exit // the precondition of the loop |
| 374 | // cnt0 = init-val; |
| 375 | // do { |
| 376 | // x1 = phi (x0, x2); |
| 377 | // cnt1 = phi(cnt0, cnt2); |
| 378 | // |
| 379 | // cnt2 = cnt1 + 1; |
| 380 | // ... |
| 381 | // x2 = x1 & (x1 - 1); |
| 382 | // ... |
| 383 | // } while(x != 0); |
| 384 | // |
| 385 | // loop-exit: |
| 386 | // |
| 387 | |
| 388 | // step 1: Check to see if the look-back branch match this pattern: |
| 389 | // "if (a!=0) goto loop-entry". |
| 390 | BasicBlock *LoopEntry; |
| 391 | Instruction *DefX2, *CountInst; |
| 392 | Value *VarX1, *VarX0; |
| 393 | PHINode *PhiX, *CountPhi; |
| 394 | |
| 395 | DefX2 = CountInst = 0; |
| 396 | VarX1 = VarX0 = 0; |
| 397 | PhiX = CountPhi = 0; |
| 398 | LoopEntry = *(CurLoop->block_begin()); |
| 399 | |
| 400 | // step 1: Check if the loop-back branch is in desirable form. |
| 401 | { |
| 402 | if (Value *T = matchCondition (LIRUtil::getBranch(LoopEntry), LoopEntry)) |
| 403 | DefX2 = dyn_cast<Instruction>(T); |
| 404 | else |
| 405 | return false; |
| 406 | } |
| 407 | |
| 408 | // step 2: detect instructions corresponding to "x2 = x1 & (x1 - 1)" |
| 409 | { |
| 410 | if (DefX2->getOpcode() != Instruction::And) |
| 411 | return false; |
| 412 | |
| 413 | BinaryOperator *SubOneOp; |
| 414 | |
| 415 | if ((SubOneOp = dyn_cast<BinaryOperator>(DefX2->getOperand(0)))) |
| 416 | VarX1 = DefX2->getOperand(1); |
| 417 | else { |
| 418 | VarX1 = DefX2->getOperand(0); |
| 419 | SubOneOp = dyn_cast<BinaryOperator>(DefX2->getOperand(1)); |
| 420 | } |
| 421 | if (!SubOneOp) |
| 422 | return false; |
| 423 | |
| 424 | Instruction *SubInst = cast<Instruction>(SubOneOp); |
| 425 | ConstantInt *Dec = dyn_cast<ConstantInt>(SubInst->getOperand(1)); |
| 426 | if (!Dec || |
| 427 | !((SubInst->getOpcode() == Instruction::Sub && Dec->isOne()) || |
| 428 | (SubInst->getOpcode() == Instruction::Add && Dec->isAllOnesValue()))) { |
| 429 | return false; |
| 430 | } |
| 431 | } |
| 432 | |
| 433 | // step 3: Check the recurrence of variable X |
| 434 | { |
| 435 | PhiX = dyn_cast<PHINode>(VarX1); |
| 436 | if (!PhiX || |
| 437 | (PhiX->getOperand(0) != DefX2 && PhiX->getOperand(1) != DefX2)) { |
| 438 | return false; |
| 439 | } |
| 440 | } |
| 441 | |
| 442 | // step 4: Find the instruction which count the population: cnt2 = cnt1 + 1 |
| 443 | { |
| 444 | CountInst = NULL; |
| 445 | for (BasicBlock::iterator Iter = LoopEntry->getFirstNonPHI(), |
| 446 | IterE = LoopEntry->end(); Iter != IterE; Iter++) { |
| 447 | Instruction *Inst = Iter; |
| 448 | if (Inst->getOpcode() != Instruction::Add) |
| 449 | continue; |
| 450 | |
| 451 | ConstantInt *Inc = dyn_cast<ConstantInt>(Inst->getOperand(1)); |
| 452 | if (!Inc || !Inc->isOne()) |
| 453 | continue; |
| 454 | |
| 455 | PHINode *Phi = dyn_cast<PHINode>(Inst->getOperand(0)); |
| 456 | if (!Phi || Phi->getParent() != LoopEntry) |
| 457 | continue; |
| 458 | |
| 459 | // Check if the result of the instruction is live of the loop. |
| 460 | bool LiveOutLoop = false; |
| 461 | for (Value::use_iterator I = Inst->use_begin(), E = Inst->use_end(); |
| 462 | I != E; I++) { |
| 463 | if ((cast<Instruction>(*I))->getParent() != LoopEntry) { |
| 464 | LiveOutLoop = true; break; |
| 465 | } |
| 466 | } |
| 467 | |
| 468 | if (LiveOutLoop) { |
| 469 | CountInst = Inst; |
| 470 | CountPhi = Phi; |
| 471 | break; |
| 472 | } |
| 473 | } |
| 474 | |
| 475 | if (!CountInst) |
| 476 | return false; |
| 477 | } |
| 478 | |
| 479 | // step 5: check if the precondition is in this form: |
| 480 | // "if (x != 0) goto loop-head ; else goto somewhere-we-don't-care;" |
| 481 | { |
| 482 | BranchInst *PreCondBr = LIRUtil::getBranch(PreCondBB); |
| 483 | Value *T = matchCondition (PreCondBr, CurLoop->getLoopPreheader()); |
| 484 | if (T != PhiX->getOperand(0) && T != PhiX->getOperand(1)) |
| 485 | return false; |
| 486 | |
| 487 | CntInst = CountInst; |
| 488 | CntPhi = CountPhi; |
| 489 | Var = T; |
| 490 | } |
| 491 | |
| 492 | return true; |
| 493 | } |
| 494 | |
| 495 | void NclPopcountRecognize::transform(Instruction *CntInst, |
| 496 | PHINode *CntPhi, Value *Var) { |
| 497 | |
| 498 | ScalarEvolution *SE = LIR.getScalarEvolution(); |
| 499 | TargetLibraryInfo *TLI = LIR.getTargetLibraryInfo(); |
| 500 | BasicBlock *PreHead = CurLoop->getLoopPreheader(); |
| 501 | BranchInst *PreCondBr = LIRUtil::getBranch(PreCondBB); |
| 502 | const DebugLoc DL = CntInst->getDebugLoc(); |
| 503 | |
| 504 | // Assuming before transformation, the loop is following: |
| 505 | // if (x) // the precondition |
| 506 | // do { cnt++; x &= x - 1; } while(x); |
| 507 | |
| 508 | // Step 1: Insert the ctpop instruction at the end of the precondition block |
| 509 | IRBuilderTy Builder(PreCondBr); |
| 510 | Value *PopCnt, *PopCntZext, *NewCount, *TripCnt; |
| 511 | { |
| 512 | PopCnt = createPopcntIntrinsic(Builder, Var, DL); |
| 513 | NewCount = PopCntZext = |
| 514 | Builder.CreateZExtOrTrunc(PopCnt, cast<IntegerType>(CntPhi->getType())); |
| 515 | |
| 516 | if (NewCount != PopCnt) |
| 517 | (cast<Instruction>(NewCount))->setDebugLoc(DL); |
| 518 | |
| 519 | // TripCnt is exactly the number of iterations the loop has |
| 520 | TripCnt = NewCount; |
| 521 | |
| 522 | // If the popoulation counter's initial value is not zero, insert Add Inst. |
| 523 | Value *CntInitVal = CntPhi->getIncomingValueForBlock(PreHead); |
| 524 | ConstantInt *InitConst = dyn_cast<ConstantInt>(CntInitVal); |
| 525 | if (!InitConst || !InitConst->isZero()) { |
| 526 | NewCount = Builder.CreateAdd(NewCount, CntInitVal); |
| 527 | (cast<Instruction>(NewCount))->setDebugLoc(DL); |
| 528 | } |
| 529 | } |
| 530 | |
| 531 | // Step 2: Replace the precondition from "if(x == 0) goto loop-exit" to |
| 532 | // "if(NewCount == 0) loop-exit". Withtout this change, the intrinsic |
| 533 | // function would be partial dead code, and downstream passes will drag |
| 534 | // it back from the precondition block to the preheader. |
| 535 | { |
| 536 | ICmpInst *PreCond = cast<ICmpInst>(PreCondBr->getCondition()); |
| 537 | |
| 538 | Value *Opnd0 = PopCntZext; |
| 539 | Value *Opnd1 = ConstantInt::get(PopCntZext->getType(), 0); |
| 540 | if (PreCond->getOperand(0) != Var) |
| 541 | std::swap(Opnd0, Opnd1); |
| 542 | |
| 543 | ICmpInst *NewPreCond = |
| 544 | cast<ICmpInst>(Builder.CreateICmp(PreCond->getPredicate(), Opnd0, Opnd1)); |
| 545 | PreCond->replaceAllUsesWith(NewPreCond); |
| 546 | |
| 547 | deleteDeadInstruction(PreCond, *SE, TLI); |
| 548 | } |
| 549 | |
| 550 | // Step 3: Note that the population count is exactly the trip count of the |
| 551 | // loop in question, which enble us to to convert the loop from noncountable |
| 552 | // loop into a countable one. The benefit is twofold: |
| 553 | // |
| 554 | // - If the loop only counts population, the entire loop become dead after |
| 555 | // the transformation. It is lots easier to prove a countable loop dead |
| 556 | // than to prove a noncountable one. (In some C dialects, a infite loop |
| 557 | // isn't dead even if it computes nothing useful. In general, DCE needs |
| 558 | // to prove a noncountable loop finite before safely delete it.) |
| 559 | // |
| 560 | // - If the loop also performs something else, it remains alive. |
| 561 | // Since it is transformed to countable form, it can be aggressively |
| 562 | // optimized by some optimizations which are in general not applicable |
| 563 | // to a noncountable loop. |
| 564 | // |
| 565 | // After this step, this loop (conceptually) would look like following: |
| 566 | // newcnt = __builtin_ctpop(x); |
| 567 | // t = newcnt; |
| 568 | // if (x) |
| 569 | // do { cnt++; x &= x-1; t--) } while (t > 0); |
| 570 | BasicBlock *Body = *(CurLoop->block_begin()); |
| 571 | { |
| 572 | BranchInst *LbBr = LIRUtil::getBranch(Body); |
| 573 | ICmpInst *LbCond = cast<ICmpInst>(LbBr->getCondition()); |
| 574 | Type *Ty = TripCnt->getType(); |
| 575 | |
| 576 | PHINode *TcPhi = PHINode::Create(Ty, 2, "tcphi", Body->begin()); |
| 577 | |
| 578 | Builder.SetInsertPoint(LbCond); |
| 579 | Value *Opnd1 = cast<Value>(TcPhi); |
| 580 | Value *Opnd2 = cast<Value>(ConstantInt::get(Ty, 1)); |
| 581 | Instruction *TcDec = |
| 582 | cast<Instruction>(Builder.CreateSub(Opnd1, Opnd2, "tcdec", false, true)); |
| 583 | |
| 584 | TcPhi->addIncoming(TripCnt, PreHead); |
| 585 | TcPhi->addIncoming(TcDec, Body); |
| 586 | |
| 587 | CmpInst::Predicate Pred = (LbBr->getSuccessor(0) == Body) ? |
| 588 | CmpInst::ICMP_UGT : CmpInst::ICMP_SLE; |
| 589 | LbCond->setPredicate(Pred); |
| 590 | LbCond->setOperand(0, TcDec); |
| 591 | LbCond->setOperand(1, cast<Value>(ConstantInt::get(Ty, 0))); |
| 592 | } |
| 593 | |
| 594 | // Step 4: All the references to the original population counter outside |
| 595 | // the loop are replaced with the NewCount -- the value returned from |
| 596 | // __builtin_ctpop(). |
| 597 | { |
| 598 | SmallVector<Value *, 4> CntUses; |
| 599 | for (Value::use_iterator I = CntInst->use_begin(), E = CntInst->use_end(); |
| 600 | I != E; I++) { |
| 601 | if (cast<Instruction>(*I)->getParent() != Body) |
| 602 | CntUses.push_back(*I); |
| 603 | } |
| 604 | for (unsigned Idx = 0; Idx < CntUses.size(); Idx++) { |
| 605 | (cast<Instruction>(CntUses[Idx]))->replaceUsesOfWith(CntInst, NewCount); |
| 606 | } |
| 607 | } |
| 608 | |
| 609 | // step 5: Forget the "non-computable" trip-count SCEV associated with the |
| 610 | // loop. The loop would otherwise not be deleted even if it becomes empty. |
| 611 | SE->forgetLoop(CurLoop); |
| 612 | } |
| 613 | |
| 614 | CallInst *NclPopcountRecognize::createPopcntIntrinsic(IRBuilderTy &IRBuilder, |
| 615 | Value *Val, DebugLoc DL) { |
| 616 | Value *Ops[] = { Val }; |
| 617 | Type *Tys[] = { Val->getType() }; |
| 618 | |
| 619 | Module *M = (*(CurLoop->block_begin()))->getParent()->getParent(); |
| 620 | Value *Func = Intrinsic::getDeclaration(M, Intrinsic::ctpop, Tys); |
| 621 | CallInst *CI = IRBuilder.CreateCall(Func, Ops); |
| 622 | CI->setDebugLoc(DL); |
| 623 | |
| 624 | return CI; |
| 625 | } |
| 626 | |
| 627 | /// recognize - detect population count idiom in a non-countable loop. If |
| 628 | /// detected, transform the relevant code to popcount intrinsic function |
| 629 | /// call, and return true; otherwise, return false. |
| 630 | bool NclPopcountRecognize::recognize() { |
| 631 | |
Chandler Carruth | 9980b8a | 2013-01-05 10:00:09 +0000 | [diff] [blame] | 632 | if (!LIR.getTargetTransformInfo()) |
Shuxin Yang | 5518a13 | 2012-12-09 03:12:46 +0000 | [diff] [blame] | 633 | return false; |
| 634 | |
| 635 | LIR.getScalarEvolution(); |
| 636 | |
| 637 | if (!preliminaryScreen()) |
| 638 | return false; |
| 639 | |
| 640 | Instruction *CntInst; |
| 641 | PHINode *CntPhi; |
| 642 | Value *Val; |
| 643 | if (!detectIdiom(CntInst, CntPhi, Val)) |
| 644 | return false; |
| 645 | |
| 646 | transform(CntInst, CntPhi, Val); |
| 647 | return true; |
| 648 | } |
| 649 | |
| 650 | //===----------------------------------------------------------------------===// |
| 651 | // |
| 652 | // Implementation of LoopIdiomRecognize |
| 653 | // |
| 654 | //===----------------------------------------------------------------------===// |
| 655 | |
| 656 | bool LoopIdiomRecognize::runOnCountableLoop() { |
| 657 | const SCEV *BECount = SE->getBackedgeTakenCount(CurLoop); |
| 658 | if (isa<SCEVCouldNotCompute>(BECount)) return false; |
| 659 | |
| 660 | // If this loop executes exactly one time, then it should be peeled, not |
| 661 | // optimized by this pass. |
| 662 | if (const SCEVConstant *BECst = dyn_cast<SCEVConstant>(BECount)) |
| 663 | if (BECst->getValue()->getValue() == 0) |
| 664 | return false; |
| 665 | |
| 666 | // We require target data for now. |
| 667 | if (!getDataLayout()) |
| 668 | return false; |
| 669 | |
Shuxin Yang | cbf5373 | 2013-01-02 18:26:31 +0000 | [diff] [blame] | 670 | // set DT |
| 671 | (void)getDominatorTree(); |
Shuxin Yang | 5518a13 | 2012-12-09 03:12:46 +0000 | [diff] [blame] | 672 | |
| 673 | LoopInfo &LI = getAnalysis<LoopInfo>(); |
| 674 | TLI = &getAnalysis<TargetLibraryInfo>(); |
| 675 | |
Shuxin Yang | cbf5373 | 2013-01-02 18:26:31 +0000 | [diff] [blame] | 676 | // set TLI |
| 677 | (void)getTargetLibraryInfo(); |
Shuxin Yang | 5518a13 | 2012-12-09 03:12:46 +0000 | [diff] [blame] | 678 | |
| 679 | SmallVector<BasicBlock*, 8> ExitBlocks; |
| 680 | CurLoop->getUniqueExitBlocks(ExitBlocks); |
| 681 | |
| 682 | DEBUG(dbgs() << "loop-idiom Scanning: F[" |
| 683 | << CurLoop->getHeader()->getParent()->getName() |
| 684 | << "] Loop %" << CurLoop->getHeader()->getName() << "\n"); |
| 685 | |
| 686 | bool MadeChange = false; |
| 687 | // Scan all the blocks in the loop that are not in subloops. |
| 688 | for (Loop::block_iterator BI = CurLoop->block_begin(), |
| 689 | E = CurLoop->block_end(); BI != E; ++BI) { |
| 690 | // Ignore blocks in subloops. |
| 691 | if (LI.getLoopFor(*BI) != CurLoop) |
| 692 | continue; |
| 693 | |
| 694 | MadeChange |= runOnLoopBlock(*BI, BECount, ExitBlocks); |
| 695 | } |
| 696 | return MadeChange; |
| 697 | } |
| 698 | |
| 699 | bool LoopIdiomRecognize::runOnNoncountableLoop() { |
| 700 | NclPopcountRecognize Popcount(*this); |
| 701 | if (Popcount.recognize()) |
| 702 | return true; |
| 703 | |
| 704 | return false; |
| 705 | } |
| 706 | |
Chris Lattner | e6bb649 | 2010-12-26 19:39:38 +0000 | [diff] [blame] | 707 | bool LoopIdiomRecognize::runOnLoop(Loop *L, LPPassManager &LPM) { |
Chris Lattner | 22920b5 | 2010-12-26 20:45:45 +0000 | [diff] [blame] | 708 | CurLoop = L; |
Andrew Trick | d99b39e | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 709 | |
Benjamin Kramer | 28aff84 | 2012-09-21 17:27:23 +0000 | [diff] [blame] | 710 | // If the loop could not be converted to canonical form, it must have an |
| 711 | // indirectbr in it, just give up. |
| 712 | if (!L->getLoopPreheader()) |
| 713 | return false; |
| 714 | |
Nadav Rotem | a94d6e8 | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 715 | // Disable loop idiom recognition if the function's name is a common idiom. |
Chad Rosier | 71400b6 | 2011-07-15 18:25:04 +0000 | [diff] [blame] | 716 | StringRef Name = L->getHeader()->getParent()->getName(); |
Chandler Carruth | a864748 | 2012-11-02 08:33:25 +0000 | [diff] [blame] | 717 | if (Name == "memset" || Name == "memcpy") |
Chad Rosier | 71400b6 | 2011-07-15 18:25:04 +0000 | [diff] [blame] | 718 | return false; |
| 719 | |
Chris Lattner | 22920b5 | 2010-12-26 20:45:45 +0000 | [diff] [blame] | 720 | SE = &getAnalysis<ScalarEvolution>(); |
Shuxin Yang | 5518a13 | 2012-12-09 03:12:46 +0000 | [diff] [blame] | 721 | if (SE->hasLoopInvariantBackedgeTakenCount(L)) |
| 722 | return runOnCountableLoop(); |
| 723 | return runOnNoncountableLoop(); |
Chris Lattner | 62c50fd | 2011-01-02 19:01:03 +0000 | [diff] [blame] | 724 | } |
| 725 | |
| 726 | /// runOnLoopBlock - Process the specified block, which lives in a counted loop |
| 727 | /// with the specified backedge count. This block is known to be in the current |
| 728 | /// loop and not in any subloops. |
| 729 | bool LoopIdiomRecognize::runOnLoopBlock(BasicBlock *BB, const SCEV *BECount, |
| 730 | SmallVectorImpl<BasicBlock*> &ExitBlocks) { |
| 731 | // We can only promote stores in this block if they are unconditionally |
| 732 | // executed in the loop. For a block to be unconditionally executed, it has |
| 733 | // to dominate all the exit blocks of the loop. Verify this now. |
| 734 | for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) |
| 735 | if (!DT->dominates(BB, ExitBlocks[i])) |
| 736 | return false; |
Andrew Trick | d99b39e | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 737 | |
Chris Lattner | 22920b5 | 2010-12-26 20:45:45 +0000 | [diff] [blame] | 738 | bool MadeChange = false; |
| 739 | for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) { |
Chris Lattner | b7e9ef0 | 2011-01-04 07:27:30 +0000 | [diff] [blame] | 740 | Instruction *Inst = I++; |
| 741 | // Look for store instructions, which may be optimized to memset/memcpy. |
| 742 | if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) { |
Chris Lattner | b7e9ef0 | 2011-01-04 07:27:30 +0000 | [diff] [blame] | 743 | WeakVH InstPtr(I); |
| 744 | if (!processLoopStore(SI, BECount)) continue; |
| 745 | MadeChange = true; |
Andrew Trick | d99b39e | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 746 | |
Chris Lattner | b7e9ef0 | 2011-01-04 07:27:30 +0000 | [diff] [blame] | 747 | // If processing the store invalidated our iterator, start over from the |
Chris Lattner | e41d3c0 | 2011-01-04 07:46:33 +0000 | [diff] [blame] | 748 | // top of the block. |
Chris Lattner | b7e9ef0 | 2011-01-04 07:27:30 +0000 | [diff] [blame] | 749 | if (InstPtr == 0) |
| 750 | I = BB->begin(); |
| 751 | continue; |
| 752 | } |
Andrew Trick | d99b39e | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 753 | |
Chris Lattner | e41d3c0 | 2011-01-04 07:46:33 +0000 | [diff] [blame] | 754 | // Look for memset instructions, which may be optimized to a larger memset. |
| 755 | if (MemSetInst *MSI = dyn_cast<MemSetInst>(Inst)) { |
| 756 | WeakVH InstPtr(I); |
| 757 | if (!processLoopMemSet(MSI, BECount)) continue; |
| 758 | MadeChange = true; |
Andrew Trick | d99b39e | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 759 | |
Chris Lattner | e41d3c0 | 2011-01-04 07:46:33 +0000 | [diff] [blame] | 760 | // If processing the memset invalidated our iterator, start over from the |
| 761 | // top of the block. |
| 762 | if (InstPtr == 0) |
| 763 | I = BB->begin(); |
| 764 | continue; |
| 765 | } |
Chris Lattner | 22920b5 | 2010-12-26 20:45:45 +0000 | [diff] [blame] | 766 | } |
Andrew Trick | d99b39e | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 767 | |
Chris Lattner | 22920b5 | 2010-12-26 20:45:45 +0000 | [diff] [blame] | 768 | return MadeChange; |
Chris Lattner | e6bb649 | 2010-12-26 19:39:38 +0000 | [diff] [blame] | 769 | } |
| 770 | |
Chris Lattner | 62c50fd | 2011-01-02 19:01:03 +0000 | [diff] [blame] | 771 | |
Chris Lattner | e41d3c0 | 2011-01-04 07:46:33 +0000 | [diff] [blame] | 772 | /// processLoopStore - See if this store can be promoted to a memset or memcpy. |
Chris Lattner | 22920b5 | 2010-12-26 20:45:45 +0000 | [diff] [blame] | 773 | bool LoopIdiomRecognize::processLoopStore(StoreInst *SI, const SCEV *BECount) { |
Eli Friedman | 2bc3d52 | 2011-09-12 20:23:13 +0000 | [diff] [blame] | 774 | if (!SI->isSimple()) return false; |
Chris Lattner | e41d3c0 | 2011-01-04 07:46:33 +0000 | [diff] [blame] | 775 | |
Chris Lattner | 22920b5 | 2010-12-26 20:45:45 +0000 | [diff] [blame] | 776 | Value *StoredVal = SI->getValueOperand(); |
Chris Lattner | a92ff91 | 2010-12-26 23:42:51 +0000 | [diff] [blame] | 777 | Value *StorePtr = SI->getPointerOperand(); |
Andrew Trick | d99b39e | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 778 | |
Chris Lattner | 95ae676 | 2010-12-28 18:53:48 +0000 | [diff] [blame] | 779 | // Reject stores that are so large that they overflow an unsigned. |
Chris Lattner | 22920b5 | 2010-12-26 20:45:45 +0000 | [diff] [blame] | 780 | uint64_t SizeInBits = TD->getTypeSizeInBits(StoredVal->getType()); |
Chris Lattner | 95ae676 | 2010-12-28 18:53:48 +0000 | [diff] [blame] | 781 | if ((SizeInBits & 7) || (SizeInBits >> 32) != 0) |
Chris Lattner | 22920b5 | 2010-12-26 20:45:45 +0000 | [diff] [blame] | 782 | return false; |
Andrew Trick | d99b39e | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 783 | |
Chris Lattner | 22920b5 | 2010-12-26 20:45:45 +0000 | [diff] [blame] | 784 | // See if the pointer expression is an AddRec like {base,+,1} on the current |
| 785 | // loop, which indicates a strided store. If we have something else, it's a |
| 786 | // random store we can't handle. |
Chris Lattner | e2c4392 | 2011-01-02 03:37:56 +0000 | [diff] [blame] | 787 | const SCEVAddRecExpr *StoreEv = |
| 788 | dyn_cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr)); |
| 789 | if (StoreEv == 0 || StoreEv->getLoop() != CurLoop || !StoreEv->isAffine()) |
Chris Lattner | 22920b5 | 2010-12-26 20:45:45 +0000 | [diff] [blame] | 790 | return false; |
| 791 | |
| 792 | // Check to see if the stride matches the size of the store. If so, then we |
| 793 | // know that every byte is touched in the loop. |
Andrew Trick | d99b39e | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 794 | unsigned StoreSize = (unsigned)SizeInBits >> 3; |
Chris Lattner | e2c4392 | 2011-01-02 03:37:56 +0000 | [diff] [blame] | 795 | const SCEVConstant *Stride = dyn_cast<SCEVConstant>(StoreEv->getOperand(1)); |
Andrew Trick | d99b39e | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 796 | |
Chris Lattner | 408b534 | 2011-02-21 02:08:54 +0000 | [diff] [blame] | 797 | if (Stride == 0 || StoreSize != Stride->getValue()->getValue()) { |
| 798 | // TODO: Could also handle negative stride here someday, that will require |
| 799 | // the validity check in mayLoopAccessLocation to be updated though. |
| 800 | // Enable this to print exact negative strides. |
Chris Lattner | 0e68cee | 2011-02-21 17:02:55 +0000 | [diff] [blame] | 801 | if (0 && Stride && StoreSize == -Stride->getValue()->getValue()) { |
Chris Lattner | 408b534 | 2011-02-21 02:08:54 +0000 | [diff] [blame] | 802 | dbgs() << "NEGATIVE STRIDE: " << *SI << "\n"; |
| 803 | dbgs() << "BB: " << *SI->getParent(); |
| 804 | } |
Andrew Trick | d99b39e | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 805 | |
Chris Lattner | 22920b5 | 2010-12-26 20:45:45 +0000 | [diff] [blame] | 806 | return false; |
Chris Lattner | 408b534 | 2011-02-21 02:08:54 +0000 | [diff] [blame] | 807 | } |
Chris Lattner | 3a39372 | 2011-02-19 19:31:39 +0000 | [diff] [blame] | 808 | |
| 809 | // See if we can optimize just this store in isolation. |
| 810 | if (processLoopStridedStore(StorePtr, StoreSize, SI->getAlignment(), |
| 811 | StoredVal, SI, StoreEv, BECount)) |
| 812 | return true; |
Chris Lattner | a92ff91 | 2010-12-26 23:42:51 +0000 | [diff] [blame] | 813 | |
Chris Lattner | e2c4392 | 2011-01-02 03:37:56 +0000 | [diff] [blame] | 814 | // If the stored value is a strided load in the same loop with the same stride |
| 815 | // this this may be transformable into a memcpy. This kicks in for stuff like |
| 816 | // for (i) A[i] = B[i]; |
| 817 | if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) { |
| 818 | const SCEVAddRecExpr *LoadEv = |
| 819 | dyn_cast<SCEVAddRecExpr>(SE->getSCEV(LI->getOperand(0))); |
| 820 | if (LoadEv && LoadEv->getLoop() == CurLoop && LoadEv->isAffine() && |
Eli Friedman | 2bc3d52 | 2011-09-12 20:23:13 +0000 | [diff] [blame] | 821 | StoreEv->getOperand(1) == LoadEv->getOperand(1) && LI->isSimple()) |
Chris Lattner | e2c4392 | 2011-01-02 03:37:56 +0000 | [diff] [blame] | 822 | if (processLoopStoreOfLoopLoad(SI, StoreSize, StoreEv, LoadEv, BECount)) |
| 823 | return true; |
| 824 | } |
Chris Lattner | 4ce31fb | 2011-01-02 07:36:44 +0000 | [diff] [blame] | 825 | //errs() << "UNHANDLED strided store: " << *StoreEv << " - " << *SI << "\n"; |
Chris Lattner | 22920b5 | 2010-12-26 20:45:45 +0000 | [diff] [blame] | 826 | |
Chris Lattner | e6bb649 | 2010-12-26 19:39:38 +0000 | [diff] [blame] | 827 | return false; |
| 828 | } |
| 829 | |
Chris Lattner | e41d3c0 | 2011-01-04 07:46:33 +0000 | [diff] [blame] | 830 | /// processLoopMemSet - See if this memset can be promoted to a large memset. |
| 831 | bool LoopIdiomRecognize:: |
| 832 | processLoopMemSet(MemSetInst *MSI, const SCEV *BECount) { |
| 833 | // We can only handle non-volatile memsets with a constant size. |
| 834 | if (MSI->isVolatile() || !isa<ConstantInt>(MSI->getLength())) return false; |
| 835 | |
Chris Lattner | c19175c | 2011-02-18 22:22:15 +0000 | [diff] [blame] | 836 | // If we're not allowed to hack on memset, we fail. |
| 837 | if (!TLI->has(LibFunc::memset)) |
| 838 | return false; |
Andrew Trick | d99b39e | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 839 | |
Chris Lattner | e41d3c0 | 2011-01-04 07:46:33 +0000 | [diff] [blame] | 840 | Value *Pointer = MSI->getDest(); |
Andrew Trick | d99b39e | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 841 | |
Chris Lattner | e41d3c0 | 2011-01-04 07:46:33 +0000 | [diff] [blame] | 842 | // See if the pointer expression is an AddRec like {base,+,1} on the current |
| 843 | // loop, which indicates a strided store. If we have something else, it's a |
| 844 | // random store we can't handle. |
| 845 | const SCEVAddRecExpr *Ev = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Pointer)); |
| 846 | if (Ev == 0 || Ev->getLoop() != CurLoop || !Ev->isAffine()) |
| 847 | return false; |
| 848 | |
| 849 | // Reject memsets that are so large that they overflow an unsigned. |
| 850 | uint64_t SizeInBytes = cast<ConstantInt>(MSI->getLength())->getZExtValue(); |
| 851 | if ((SizeInBytes >> 32) != 0) |
| 852 | return false; |
Andrew Trick | d99b39e | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 853 | |
Chris Lattner | e41d3c0 | 2011-01-04 07:46:33 +0000 | [diff] [blame] | 854 | // Check to see if the stride matches the size of the memset. If so, then we |
| 855 | // know that every byte is touched in the loop. |
| 856 | const SCEVConstant *Stride = dyn_cast<SCEVConstant>(Ev->getOperand(1)); |
Andrew Trick | d99b39e | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 857 | |
Chris Lattner | e41d3c0 | 2011-01-04 07:46:33 +0000 | [diff] [blame] | 858 | // TODO: Could also handle negative stride here someday, that will require the |
| 859 | // validity check in mayLoopAccessLocation to be updated though. |
| 860 | if (Stride == 0 || MSI->getLength() != Stride->getValue()) |
| 861 | return false; |
Andrew Trick | d99b39e | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 862 | |
Chris Lattner | 3a39372 | 2011-02-19 19:31:39 +0000 | [diff] [blame] | 863 | return processLoopStridedStore(Pointer, (unsigned)SizeInBytes, |
| 864 | MSI->getAlignment(), MSI->getValue(), |
| 865 | MSI, Ev, BECount); |
Chris Lattner | e41d3c0 | 2011-01-04 07:46:33 +0000 | [diff] [blame] | 866 | } |
| 867 | |
Chandler Carruth | a864748 | 2012-11-02 08:33:25 +0000 | [diff] [blame] | 868 | |
| 869 | /// mayLoopAccessLocation - Return true if the specified loop might access the |
| 870 | /// specified pointer location, which is a loop-strided access. The 'Access' |
| 871 | /// argument specifies what the verboten forms of access are (read or write). |
| 872 | static bool mayLoopAccessLocation(Value *Ptr,AliasAnalysis::ModRefResult Access, |
| 873 | Loop *L, const SCEV *BECount, |
| 874 | unsigned StoreSize, AliasAnalysis &AA, |
| 875 | Instruction *IgnoredStore) { |
| 876 | // Get the location that may be stored across the loop. Since the access is |
| 877 | // strided positively through memory, we say that the modified location starts |
| 878 | // at the pointer and has infinite size. |
| 879 | uint64_t AccessSize = AliasAnalysis::UnknownSize; |
| 880 | |
| 881 | // If the loop iterates a fixed number of times, we can refine the access size |
| 882 | // to be exactly the size of the memset, which is (BECount+1)*StoreSize |
| 883 | if (const SCEVConstant *BECst = dyn_cast<SCEVConstant>(BECount)) |
| 884 | AccessSize = (BECst->getValue()->getZExtValue()+1)*StoreSize; |
| 885 | |
| 886 | // TODO: For this to be really effective, we have to dive into the pointer |
| 887 | // operand in the store. Store to &A[i] of 100 will always return may alias |
| 888 | // with store of &A[100], we need to StoreLoc to be "A" with size of 100, |
| 889 | // which will then no-alias a store to &A[100]. |
| 890 | AliasAnalysis::Location StoreLoc(Ptr, AccessSize); |
| 891 | |
| 892 | for (Loop::block_iterator BI = L->block_begin(), E = L->block_end(); BI != E; |
| 893 | ++BI) |
| 894 | for (BasicBlock::iterator I = (*BI)->begin(), E = (*BI)->end(); I != E; ++I) |
| 895 | if (&*I != IgnoredStore && |
| 896 | (AA.getModRefInfo(I, StoreLoc) & Access)) |
| 897 | return true; |
| 898 | |
| 899 | return false; |
| 900 | } |
| 901 | |
Chris Lattner | 3a39372 | 2011-02-19 19:31:39 +0000 | [diff] [blame] | 902 | /// getMemSetPatternValue - If a strided store of the specified value is safe to |
| 903 | /// turn into a memset_pattern16, return a ConstantArray of 16 bytes that should |
| 904 | /// be passed in. Otherwise, return null. |
| 905 | /// |
| 906 | /// Note that we don't ever attempt to use memset_pattern8 or 4, because these |
| 907 | /// just replicate their input array and then pass on to memset_pattern16. |
Micah Villmow | 3574eca | 2012-10-08 16:38:25 +0000 | [diff] [blame] | 908 | static Constant *getMemSetPatternValue(Value *V, const DataLayout &TD) { |
Chris Lattner | 3a39372 | 2011-02-19 19:31:39 +0000 | [diff] [blame] | 909 | // If the value isn't a constant, we can't promote it to being in a constant |
| 910 | // array. We could theoretically do a store to an alloca or something, but |
| 911 | // that doesn't seem worthwhile. |
| 912 | Constant *C = dyn_cast<Constant>(V); |
| 913 | if (C == 0) return 0; |
Andrew Trick | d99b39e | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 914 | |
Chris Lattner | 3a39372 | 2011-02-19 19:31:39 +0000 | [diff] [blame] | 915 | // Only handle simple values that are a power of two bytes in size. |
| 916 | uint64_t Size = TD.getTypeSizeInBits(V->getType()); |
| 917 | if (Size == 0 || (Size & 7) || (Size & (Size-1))) |
| 918 | return 0; |
Andrew Trick | d99b39e | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 919 | |
Chris Lattner | 80e8b50 | 2011-02-19 19:56:44 +0000 | [diff] [blame] | 920 | // Don't care enough about darwin/ppc to implement this. |
| 921 | if (TD.isBigEndian()) |
| 922 | return 0; |
Chris Lattner | 3a39372 | 2011-02-19 19:31:39 +0000 | [diff] [blame] | 923 | |
| 924 | // Convert to size in bytes. |
| 925 | Size /= 8; |
Chris Lattner | 3a39372 | 2011-02-19 19:31:39 +0000 | [diff] [blame] | 926 | |
Chris Lattner | 3a39372 | 2011-02-19 19:31:39 +0000 | [diff] [blame] | 927 | // TODO: If CI is larger than 16-bytes, we can try slicing it in half to see |
Chris Lattner | 80e8b50 | 2011-02-19 19:56:44 +0000 | [diff] [blame] | 928 | // if the top and bottom are the same (e.g. for vectors and large integers). |
Chris Lattner | 3a39372 | 2011-02-19 19:31:39 +0000 | [diff] [blame] | 929 | if (Size > 16) return 0; |
Andrew Trick | d99b39e | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 930 | |
Chris Lattner | 80e8b50 | 2011-02-19 19:56:44 +0000 | [diff] [blame] | 931 | // If the constant is exactly 16 bytes, just use it. |
| 932 | if (Size == 16) return C; |
Chris Lattner | 3a39372 | 2011-02-19 19:31:39 +0000 | [diff] [blame] | 933 | |
Chris Lattner | 80e8b50 | 2011-02-19 19:56:44 +0000 | [diff] [blame] | 934 | // Otherwise, we'll use an array of the constants. |
| 935 | unsigned ArraySize = 16/Size; |
| 936 | ArrayType *AT = ArrayType::get(V->getType(), ArraySize); |
| 937 | return ConstantArray::get(AT, std::vector<Constant*>(ArraySize, C)); |
Chris Lattner | 3a39372 | 2011-02-19 19:31:39 +0000 | [diff] [blame] | 938 | } |
| 939 | |
| 940 | |
| 941 | /// processLoopStridedStore - We see a strided store of some value. If we can |
| 942 | /// transform this into a memset or memset_pattern in the loop preheader, do so. |
| 943 | bool LoopIdiomRecognize:: |
| 944 | processLoopStridedStore(Value *DestPtr, unsigned StoreSize, |
| 945 | unsigned StoreAlignment, Value *StoredVal, |
| 946 | Instruction *TheStore, const SCEVAddRecExpr *Ev, |
| 947 | const SCEV *BECount) { |
Andrew Trick | d99b39e | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 948 | |
Chris Lattner | 3a39372 | 2011-02-19 19:31:39 +0000 | [diff] [blame] | 949 | // If the stored value is a byte-wise value (like i32 -1), then it may be |
| 950 | // turned into a memset of i8 -1, assuming that all the consecutive bytes |
| 951 | // are stored. A store of i32 0x01020304 can never be turned into a memset, |
| 952 | // but it can be turned into memset_pattern if the target supports it. |
| 953 | Value *SplatValue = isBytewiseValue(StoredVal); |
| 954 | Constant *PatternValue = 0; |
Andrew Trick | d99b39e | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 955 | |
Chris Lattner | 3a39372 | 2011-02-19 19:31:39 +0000 | [diff] [blame] | 956 | // If we're allowed to form a memset, and the stored value would be acceptable |
| 957 | // for memset, use it. |
| 958 | if (SplatValue && TLI->has(LibFunc::memset) && |
| 959 | // Verify that the stored value is loop invariant. If not, we can't |
| 960 | // promote the memset. |
| 961 | CurLoop->isLoopInvariant(SplatValue)) { |
| 962 | // Keep and use SplatValue. |
| 963 | PatternValue = 0; |
| 964 | } else if (TLI->has(LibFunc::memset_pattern16) && |
| 965 | (PatternValue = getMemSetPatternValue(StoredVal, *TD))) { |
| 966 | // It looks like we can use PatternValue! |
| 967 | SplatValue = 0; |
| 968 | } else { |
| 969 | // Otherwise, this isn't an idiom we can transform. For example, we can't |
Eli Friedman | 5ac7c7d | 2011-09-13 00:44:16 +0000 | [diff] [blame] | 970 | // do anything with a 3-byte store. |
Chris Lattner | bafa117 | 2011-01-01 20:12:04 +0000 | [diff] [blame] | 971 | return false; |
Chris Lattner | 3a39372 | 2011-02-19 19:31:39 +0000 | [diff] [blame] | 972 | } |
Andrew Trick | d99b39e | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 973 | |
Chris Lattner | 4f81b54 | 2011-05-22 17:39:56 +0000 | [diff] [blame] | 974 | // The trip count of the loop and the base pointer of the addrec SCEV is |
| 975 | // guaranteed to be loop invariant, which means that it should dominate the |
| 976 | // header. This allows us to insert code for it in the preheader. |
| 977 | BasicBlock *Preheader = CurLoop->getLoopPreheader(); |
| 978 | IRBuilder<> Builder(Preheader->getTerminator()); |
Andrew Trick | 5e7645b | 2011-06-28 05:07:32 +0000 | [diff] [blame] | 979 | SCEVExpander Expander(*SE, "loop-idiom"); |
Andrew Trick | a5d950f | 2011-06-28 05:04:16 +0000 | [diff] [blame] | 980 | |
Chris Lattner | a92ff91 | 2010-12-26 23:42:51 +0000 | [diff] [blame] | 981 | // Okay, we have a strided store "p[i]" of a splattable value. We can turn |
Benjamin Kramer | 3740e79 | 2012-10-21 19:31:16 +0000 | [diff] [blame] | 982 | // this into a memset in the loop preheader now if we want. However, this |
| 983 | // would be unsafe to do if there is anything else in the loop that may read |
Chandler Carruth | ece6c6b | 2012-11-01 08:07:29 +0000 | [diff] [blame] | 984 | // or write to the aliased location. Check for any overlap by generating the |
| 985 | // base pointer and checking the region. |
| 986 | unsigned AddrSpace = cast<PointerType>(DestPtr->getType())->getAddressSpace(); |
Andrew Trick | d99b39e | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 987 | Value *BasePtr = |
Chris Lattner | a92ff91 | 2010-12-26 23:42:51 +0000 | [diff] [blame] | 988 | Expander.expandCodeFor(Ev->getStart(), Builder.getInt8PtrTy(AddrSpace), |
| 989 | Preheader->getTerminator()); |
Andrew Trick | d99b39e | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 990 | |
Chris Lattner | 4f81b54 | 2011-05-22 17:39:56 +0000 | [diff] [blame] | 991 | |
Chandler Carruth | a864748 | 2012-11-02 08:33:25 +0000 | [diff] [blame] | 992 | if (mayLoopAccessLocation(BasePtr, AliasAnalysis::ModRef, |
| 993 | CurLoop, BECount, |
| 994 | StoreSize, getAnalysis<AliasAnalysis>(), TheStore)){ |
| 995 | Expander.clear(); |
| 996 | // If we generated new code for the base pointer, clean up. |
| 997 | deleteIfDeadInstruction(BasePtr, *SE, TLI); |
| 998 | return false; |
| 999 | } |
| 1000 | |
Chris Lattner | 4f81b54 | 2011-05-22 17:39:56 +0000 | [diff] [blame] | 1001 | // Okay, everything looks good, insert the memset. |
| 1002 | |
Chris Lattner | a92ff91 | 2010-12-26 23:42:51 +0000 | [diff] [blame] | 1003 | // The # stored bytes is (BECount+1)*Size. Expand the trip count out to |
| 1004 | // pointer size if it isn't already. |
Chandler Carruth | ece6c6b | 2012-11-01 08:07:29 +0000 | [diff] [blame] | 1005 | Type *IntPtr = TD->getIntPtrType(DestPtr->getContext()); |
Chris Lattner | 7c90b90 | 2011-01-04 00:06:55 +0000 | [diff] [blame] | 1006 | BECount = SE->getTruncateOrZeroExtend(BECount, IntPtr); |
Andrew Trick | d99b39e | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 1007 | |
Chris Lattner | a92ff91 | 2010-12-26 23:42:51 +0000 | [diff] [blame] | 1008 | const SCEV *NumBytesS = SE->getAddExpr(BECount, SE->getConstant(IntPtr, 1), |
Andrew Trick | 3228cc2 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 1009 | SCEV::FlagNUW); |
Chris Lattner | a92ff91 | 2010-12-26 23:42:51 +0000 | [diff] [blame] | 1010 | if (StoreSize != 1) |
| 1011 | NumBytesS = SE->getMulExpr(NumBytesS, SE->getConstant(IntPtr, StoreSize), |
Andrew Trick | 3228cc2 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 1012 | SCEV::FlagNUW); |
Andrew Trick | d99b39e | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 1013 | |
| 1014 | Value *NumBytes = |
Chris Lattner | a92ff91 | 2010-12-26 23:42:51 +0000 | [diff] [blame] | 1015 | Expander.expandCodeFor(NumBytesS, IntPtr, Preheader->getTerminator()); |
Andrew Trick | d99b39e | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 1016 | |
Devang Patel | cd77a50 | 2011-03-07 22:43:45 +0000 | [diff] [blame] | 1017 | CallInst *NewCall; |
Chris Lattner | 3a39372 | 2011-02-19 19:31:39 +0000 | [diff] [blame] | 1018 | if (SplatValue) |
| 1019 | NewCall = Builder.CreateMemSet(BasePtr, SplatValue,NumBytes,StoreAlignment); |
| 1020 | else { |
| 1021 | Module *M = TheStore->getParent()->getParent()->getParent(); |
| 1022 | Value *MSP = M->getOrInsertFunction("memset_pattern16", |
| 1023 | Builder.getVoidTy(), |
Andrew Trick | d99b39e | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 1024 | Builder.getInt8PtrTy(), |
Chris Lattner | 3a39372 | 2011-02-19 19:31:39 +0000 | [diff] [blame] | 1025 | Builder.getInt8PtrTy(), IntPtr, |
| 1026 | (void*)0); |
Andrew Trick | d99b39e | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 1027 | |
Chris Lattner | 3a39372 | 2011-02-19 19:31:39 +0000 | [diff] [blame] | 1028 | // Otherwise we should form a memset_pattern16. PatternValue is known to be |
| 1029 | // an constant array of 16-bytes. Plop the value into a mergable global. |
| 1030 | GlobalVariable *GV = new GlobalVariable(*M, PatternValue->getType(), true, |
| 1031 | GlobalValue::InternalLinkage, |
| 1032 | PatternValue, ".memset_pattern"); |
| 1033 | GV->setUnnamedAddr(true); // Ok to merge these. |
| 1034 | GV->setAlignment(16); |
Chris Lattner | 80e8b50 | 2011-02-19 19:56:44 +0000 | [diff] [blame] | 1035 | Value *PatternPtr = ConstantExpr::getBitCast(GV, Builder.getInt8PtrTy()); |
Chris Lattner | 3a39372 | 2011-02-19 19:31:39 +0000 | [diff] [blame] | 1036 | NewCall = Builder.CreateCall3(MSP, BasePtr, PatternPtr, NumBytes); |
| 1037 | } |
Andrew Trick | d99b39e | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 1038 | |
Chris Lattner | a92ff91 | 2010-12-26 23:42:51 +0000 | [diff] [blame] | 1039 | DEBUG(dbgs() << " Formed memset: " << *NewCall << "\n" |
Chris Lattner | e41d3c0 | 2011-01-04 07:46:33 +0000 | [diff] [blame] | 1040 | << " from store to: " << *Ev << " at: " << *TheStore << "\n"); |
Devang Patel | cd77a50 | 2011-03-07 22:43:45 +0000 | [diff] [blame] | 1041 | NewCall->setDebugLoc(TheStore->getDebugLoc()); |
Andrew Trick | d99b39e | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 1042 | |
Chris Lattner | 9f39188 | 2010-12-27 00:03:23 +0000 | [diff] [blame] | 1043 | // Okay, the memset has been formed. Zap the original store and anything that |
| 1044 | // feeds into it. |
Benjamin Kramer | 8e0d1c0 | 2012-08-29 15:32:21 +0000 | [diff] [blame] | 1045 | deleteDeadInstruction(TheStore, *SE, TLI); |
Chris Lattner | 4ce31fb | 2011-01-02 07:36:44 +0000 | [diff] [blame] | 1046 | ++NumMemSet; |
Chris Lattner | a92ff91 | 2010-12-26 23:42:51 +0000 | [diff] [blame] | 1047 | return true; |
| 1048 | } |
| 1049 | |
Chris Lattner | e2c4392 | 2011-01-02 03:37:56 +0000 | [diff] [blame] | 1050 | /// processLoopStoreOfLoopLoad - We see a strided store whose value is a |
| 1051 | /// same-strided load. |
| 1052 | bool LoopIdiomRecognize:: |
| 1053 | processLoopStoreOfLoopLoad(StoreInst *SI, unsigned StoreSize, |
| 1054 | const SCEVAddRecExpr *StoreEv, |
| 1055 | const SCEVAddRecExpr *LoadEv, |
| 1056 | const SCEV *BECount) { |
Chris Lattner | c19175c | 2011-02-18 22:22:15 +0000 | [diff] [blame] | 1057 | // If we're not allowed to form memcpy, we fail. |
Chandler Carruth | a864748 | 2012-11-02 08:33:25 +0000 | [diff] [blame] | 1058 | if (!TLI->has(LibFunc::memcpy)) |
Chris Lattner | c19175c | 2011-02-18 22:22:15 +0000 | [diff] [blame] | 1059 | return false; |
Andrew Trick | d99b39e | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 1060 | |
Chris Lattner | e2c4392 | 2011-01-02 03:37:56 +0000 | [diff] [blame] | 1061 | LoadInst *LI = cast<LoadInst>(SI->getValueOperand()); |
Andrew Trick | d99b39e | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 1062 | |
Chris Lattner | 4f81b54 | 2011-05-22 17:39:56 +0000 | [diff] [blame] | 1063 | // The trip count of the loop and the base pointer of the addrec SCEV is |
| 1064 | // guaranteed to be loop invariant, which means that it should dominate the |
| 1065 | // header. This allows us to insert code for it in the preheader. |
| 1066 | BasicBlock *Preheader = CurLoop->getLoopPreheader(); |
| 1067 | IRBuilder<> Builder(Preheader->getTerminator()); |
Andrew Trick | 5e7645b | 2011-06-28 05:07:32 +0000 | [diff] [blame] | 1068 | SCEVExpander Expander(*SE, "loop-idiom"); |
Andrew Trick | a5d950f | 2011-06-28 05:04:16 +0000 | [diff] [blame] | 1069 | |
Chris Lattner | e2c4392 | 2011-01-02 03:37:56 +0000 | [diff] [blame] | 1070 | // Okay, we have a strided store "p[i]" of a loaded value. We can turn |
Chandler Carruth | a864748 | 2012-11-02 08:33:25 +0000 | [diff] [blame] | 1071 | // this into a memcpy in the loop preheader now if we want. However, this |
| 1072 | // would be unsafe to do if there is anything else in the loop that may read |
| 1073 | // or write the memory region we're storing to. This includes the load that |
| 1074 | // feeds the stores. Check for an alias by generating the base address and |
| 1075 | // checking everything. |
Andrew Trick | d99b39e | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 1076 | Value *StoreBasePtr = |
Chris Lattner | e2c4392 | 2011-01-02 03:37:56 +0000 | [diff] [blame] | 1077 | Expander.expandCodeFor(StoreEv->getStart(), |
| 1078 | Builder.getInt8PtrTy(SI->getPointerAddressSpace()), |
| 1079 | Preheader->getTerminator()); |
Chandler Carruth | a864748 | 2012-11-02 08:33:25 +0000 | [diff] [blame] | 1080 | |
| 1081 | if (mayLoopAccessLocation(StoreBasePtr, AliasAnalysis::ModRef, |
| 1082 | CurLoop, BECount, StoreSize, |
| 1083 | getAnalysis<AliasAnalysis>(), SI)) { |
| 1084 | Expander.clear(); |
| 1085 | // If we generated new code for the base pointer, clean up. |
| 1086 | deleteIfDeadInstruction(StoreBasePtr, *SE, TLI); |
| 1087 | return false; |
| 1088 | } |
| 1089 | |
| 1090 | // For a memcpy, we have to make sure that the input array is not being |
| 1091 | // mutated by the loop. |
Chris Lattner | 4f81b54 | 2011-05-22 17:39:56 +0000 | [diff] [blame] | 1092 | Value *LoadBasePtr = |
| 1093 | Expander.expandCodeFor(LoadEv->getStart(), |
| 1094 | Builder.getInt8PtrTy(LI->getPointerAddressSpace()), |
| 1095 | Preheader->getTerminator()); |
| 1096 | |
Chandler Carruth | a864748 | 2012-11-02 08:33:25 +0000 | [diff] [blame] | 1097 | if (mayLoopAccessLocation(LoadBasePtr, AliasAnalysis::Mod, CurLoop, BECount, |
| 1098 | StoreSize, getAnalysis<AliasAnalysis>(), SI)) { |
| 1099 | Expander.clear(); |
| 1100 | // If we generated new code for the base pointer, clean up. |
| 1101 | deleteIfDeadInstruction(LoadBasePtr, *SE, TLI); |
| 1102 | deleteIfDeadInstruction(StoreBasePtr, *SE, TLI); |
| 1103 | return false; |
| 1104 | } |
| 1105 | |
Chris Lattner | 4f81b54 | 2011-05-22 17:39:56 +0000 | [diff] [blame] | 1106 | // Okay, everything is safe, we can transform this! |
Andrew Trick | a5d950f | 2011-06-28 05:04:16 +0000 | [diff] [blame] | 1107 | |
Andrew Trick | d99b39e | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 1108 | |
Chris Lattner | e2c4392 | 2011-01-02 03:37:56 +0000 | [diff] [blame] | 1109 | // The # stored bytes is (BECount+1)*Size. Expand the trip count out to |
| 1110 | // pointer size if it isn't already. |
Chandler Carruth | ece6c6b | 2012-11-01 08:07:29 +0000 | [diff] [blame] | 1111 | Type *IntPtr = TD->getIntPtrType(SI->getContext()); |
Chris Lattner | 7c90b90 | 2011-01-04 00:06:55 +0000 | [diff] [blame] | 1112 | BECount = SE->getTruncateOrZeroExtend(BECount, IntPtr); |
Andrew Trick | d99b39e | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 1113 | |
Chris Lattner | e2c4392 | 2011-01-02 03:37:56 +0000 | [diff] [blame] | 1114 | const SCEV *NumBytesS = SE->getAddExpr(BECount, SE->getConstant(IntPtr, 1), |
Andrew Trick | 3228cc2 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 1115 | SCEV::FlagNUW); |
Chris Lattner | e2c4392 | 2011-01-02 03:37:56 +0000 | [diff] [blame] | 1116 | if (StoreSize != 1) |
| 1117 | NumBytesS = SE->getMulExpr(NumBytesS, SE->getConstant(IntPtr, StoreSize), |
Andrew Trick | 3228cc2 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 1118 | SCEV::FlagNUW); |
Andrew Trick | d99b39e | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 1119 | |
Chris Lattner | e2c4392 | 2011-01-02 03:37:56 +0000 | [diff] [blame] | 1120 | Value *NumBytes = |
| 1121 | Expander.expandCodeFor(NumBytesS, IntPtr, Preheader->getTerminator()); |
Andrew Trick | d99b39e | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 1122 | |
Chandler Carruth | a864748 | 2012-11-02 08:33:25 +0000 | [diff] [blame] | 1123 | CallInst *NewCall = |
| 1124 | Builder.CreateMemCpy(StoreBasePtr, LoadBasePtr, NumBytes, |
| 1125 | std::min(SI->getAlignment(), LI->getAlignment())); |
Devang Patel | af35841 | 2011-05-04 21:37:05 +0000 | [diff] [blame] | 1126 | NewCall->setDebugLoc(SI->getDebugLoc()); |
Andrew Trick | d99b39e | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 1127 | |
Chandler Carruth | a864748 | 2012-11-02 08:33:25 +0000 | [diff] [blame] | 1128 | DEBUG(dbgs() << " Formed memcpy: " << *NewCall << "\n" |
Chris Lattner | e2c4392 | 2011-01-02 03:37:56 +0000 | [diff] [blame] | 1129 | << " from load ptr=" << *LoadEv << " at: " << *LI << "\n" |
| 1130 | << " from store ptr=" << *StoreEv << " at: " << *SI << "\n"); |
Andrew Trick | a5d950f | 2011-06-28 05:04:16 +0000 | [diff] [blame] | 1131 | |
Andrew Trick | d99b39e | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 1132 | |
Chris Lattner | e2c4392 | 2011-01-02 03:37:56 +0000 | [diff] [blame] | 1133 | // Okay, the memset has been formed. Zap the original store and anything that |
| 1134 | // feeds into it. |
Benjamin Kramer | 8e0d1c0 | 2012-08-29 15:32:21 +0000 | [diff] [blame] | 1135 | deleteDeadInstruction(SI, *SE, TLI); |
Chandler Carruth | a864748 | 2012-11-02 08:33:25 +0000 | [diff] [blame] | 1136 | ++NumMemCpy; |
Chris Lattner | e2c4392 | 2011-01-02 03:37:56 +0000 | [diff] [blame] | 1137 | return true; |
| 1138 | } |