Chris Lattner | 81ae3f2 | 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 | 0469e01 | 2011-01-02 18:32:09 +0000 | [diff] [blame] | 15 | // |
| 16 | // TODO List: |
| 17 | // |
| 18 | // Future loop memory idioms to recognize: |
Chandler Carruth | 099f5cb0 | 2012-11-02 08:33:25 +0000 | [diff] [blame] | 19 | // memcmp, memmove, strlen, etc. |
Chris Lattner | 0469e01 | 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 | // |
Chris Lattner | 02a9776 | 2011-01-03 01:10:08 +0000 | [diff] [blame] | 29 | // This could recognize common matrix multiplies and dot product idioms and |
Chris Lattner | 8fac5db | 2011-01-02 23:19:45 +0000 | [diff] [blame] | 30 | // replace them with calls to BLAS (if linked in??). |
| 31 | // |
Chris Lattner | 0469e01 | 2011-01-02 18:32:09 +0000 | [diff] [blame] | 32 | //===----------------------------------------------------------------------===// |
Chris Lattner | 81ae3f2 | 2010-12-26 19:39:38 +0000 | [diff] [blame] | 33 | |
Chris Lattner | 81ae3f2 | 2010-12-26 19:39:38 +0000 | [diff] [blame] | 34 | #include "llvm/Transforms/Scalar.h" |
Haicheng Wu | f1c00a2 | 2016-01-26 02:27:47 +0000 | [diff] [blame] | 35 | #include "llvm/ADT/MapVector.h" |
| 36 | #include "llvm/ADT/SetVector.h" |
Chandler Carruth | aafe091 | 2012-06-29 12:38:19 +0000 | [diff] [blame] | 37 | #include "llvm/ADT/Statistic.h" |
Chris Lattner | cb18bfa | 2010-12-27 18:39:08 +0000 | [diff] [blame] | 38 | #include "llvm/Analysis/AliasAnalysis.h" |
Chandler Carruth | 7b560d4 | 2015-09-09 17:55:00 +0000 | [diff] [blame] | 39 | #include "llvm/Analysis/BasicAliasAnalysis.h" |
| 40 | #include "llvm/Analysis/GlobalsModRef.h" |
Chris Lattner | 81ae3f2 | 2010-12-26 19:39:38 +0000 | [diff] [blame] | 41 | #include "llvm/Analysis/LoopPass.h" |
Haicheng Wu | f1c00a2 | 2016-01-26 02:27:47 +0000 | [diff] [blame] | 42 | #include "llvm/Analysis/LoopAccessAnalysis.h" |
Chandler Carruth | 7b560d4 | 2015-09-09 17:55:00 +0000 | [diff] [blame] | 43 | #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h" |
Chad Rosier | a15b4b6 | 2015-11-23 21:09:13 +0000 | [diff] [blame] | 44 | #include "llvm/Analysis/ScalarEvolutionExpander.h" |
Chandler Carruth | aafe091 | 2012-06-29 12:38:19 +0000 | [diff] [blame] | 45 | #include "llvm/Analysis/ScalarEvolutionExpressions.h" |
Benjamin Kramer | 799003b | 2015-03-23 19:32:43 +0000 | [diff] [blame] | 46 | #include "llvm/Analysis/TargetLibraryInfo.h" |
Chandler Carruth | d3e7355 | 2013-01-07 03:08:10 +0000 | [diff] [blame] | 47 | #include "llvm/Analysis/TargetTransformInfo.h" |
Chris Lattner | 7c5f9c3 | 2010-12-26 20:45:45 +0000 | [diff] [blame] | 48 | #include "llvm/Analysis/ValueTracking.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 49 | #include "llvm/IR/DataLayout.h" |
Chandler Carruth | 5ad5f15 | 2014-01-13 09:26:24 +0000 | [diff] [blame] | 50 | #include "llvm/IR/Dominators.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 51 | #include "llvm/IR/IRBuilder.h" |
| 52 | #include "llvm/IR/IntrinsicInst.h" |
| 53 | #include "llvm/IR/Module.h" |
Chandler Carruth | aafe091 | 2012-06-29 12:38:19 +0000 | [diff] [blame] | 54 | #include "llvm/Support/Debug.h" |
| 55 | #include "llvm/Support/raw_ostream.h" |
Ahmed Bougacha | ace97c1 | 2016-04-27 19:04:50 +0000 | [diff] [blame] | 56 | #include "llvm/Transforms/Utils/BuildLibCalls.h" |
Chris Lattner | b9fe685 | 2010-12-27 00:03:23 +0000 | [diff] [blame] | 57 | #include "llvm/Transforms/Utils/Local.h" |
Chandler Carruth | 31088a9 | 2016-02-19 10:45:18 +0000 | [diff] [blame] | 58 | #include "llvm/Transforms/Utils/LoopUtils.h" |
Chris Lattner | 81ae3f2 | 2010-12-26 19:39:38 +0000 | [diff] [blame] | 59 | using namespace llvm; |
| 60 | |
Chandler Carruth | 964daaa | 2014-04-22 02:55:47 +0000 | [diff] [blame] | 61 | #define DEBUG_TYPE "loop-idiom" |
| 62 | |
Chandler Carruth | 099f5cb0 | 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 | 81ae3f2 | 2010-12-26 19:39:38 +0000 | [diff] [blame] | 65 | |
| 66 | namespace { |
Shuxin Yang | 95de7c3 | 2012-12-09 03:12:46 +0000 | [diff] [blame] | 67 | |
Chandler Carruth | bad690e | 2015-08-12 23:06:37 +0000 | [diff] [blame] | 68 | class LoopIdiomRecognize : public LoopPass { |
| 69 | Loop *CurLoop; |
Chandler Carruth | bf143e2 | 2015-08-14 00:21:10 +0000 | [diff] [blame] | 70 | AliasAnalysis *AA; |
Chandler Carruth | bad690e | 2015-08-12 23:06:37 +0000 | [diff] [blame] | 71 | DominatorTree *DT; |
Chandler Carruth | 18c2669 | 2015-08-13 09:27:01 +0000 | [diff] [blame] | 72 | LoopInfo *LI; |
Chandler Carruth | bad690e | 2015-08-12 23:06:37 +0000 | [diff] [blame] | 73 | ScalarEvolution *SE; |
| 74 | TargetLibraryInfo *TLI; |
| 75 | const TargetTransformInfo *TTI; |
Chad Rosier | 43f9b48 | 2015-11-06 16:33:57 +0000 | [diff] [blame] | 76 | const DataLayout *DL; |
Chris Lattner | 81ae3f2 | 2010-12-26 19:39:38 +0000 | [diff] [blame] | 77 | |
Chandler Carruth | bad690e | 2015-08-12 23:06:37 +0000 | [diff] [blame] | 78 | public: |
| 79 | static char ID; |
| 80 | explicit LoopIdiomRecognize() : LoopPass(ID) { |
| 81 | initializeLoopIdiomRecognizePass(*PassRegistry::getPassRegistry()); |
Chandler Carruth | bad690e | 2015-08-12 23:06:37 +0000 | [diff] [blame] | 82 | } |
Chris Lattner | 81ae3f2 | 2010-12-26 19:39:38 +0000 | [diff] [blame] | 83 | |
Chandler Carruth | bad690e | 2015-08-12 23:06:37 +0000 | [diff] [blame] | 84 | bool runOnLoop(Loop *L, LPPassManager &LPM) override; |
Shuxin Yang | 95de7c3 | 2012-12-09 03:12:46 +0000 | [diff] [blame] | 85 | |
Chandler Carruth | bad690e | 2015-08-12 23:06:37 +0000 | [diff] [blame] | 86 | /// This transformation requires natural loop information & requires that |
| 87 | /// loop preheaders be inserted into the CFG. |
| 88 | /// |
| 89 | void getAnalysisUsage(AnalysisUsage &AU) const override { |
Chandler Carruth | bad690e | 2015-08-12 23:06:37 +0000 | [diff] [blame] | 90 | AU.addRequired<TargetLibraryInfoWrapperPass>(); |
| 91 | AU.addRequired<TargetTransformInfoWrapperPass>(); |
Chandler Carruth | 31088a9 | 2016-02-19 10:45:18 +0000 | [diff] [blame] | 92 | getLoopAnalysisUsage(AU); |
Chandler Carruth | bad690e | 2015-08-12 23:06:37 +0000 | [diff] [blame] | 93 | } |
Shuxin Yang | 95de7c3 | 2012-12-09 03:12:46 +0000 | [diff] [blame] | 94 | |
Chandler Carruth | bad690e | 2015-08-12 23:06:37 +0000 | [diff] [blame] | 95 | private: |
Chad Rosier | cc9030b | 2015-11-11 23:00:59 +0000 | [diff] [blame] | 96 | typedef SmallVector<StoreInst *, 8> StoreList; |
Haicheng Wu | f1c00a2 | 2016-01-26 02:27:47 +0000 | [diff] [blame] | 97 | typedef MapVector<Value *, StoreList> StoreListMap; |
| 98 | StoreListMap StoreRefsForMemset; |
| 99 | StoreListMap StoreRefsForMemsetPattern; |
Haicheng Wu | 9d6c940 | 2016-01-04 21:43:14 +0000 | [diff] [blame] | 100 | StoreList StoreRefsForMemcpy; |
| 101 | bool HasMemset; |
| 102 | bool HasMemsetPattern; |
| 103 | bool HasMemcpy; |
Chad Rosier | cc9030b | 2015-11-11 23:00:59 +0000 | [diff] [blame] | 104 | |
Chandler Carruth | d9c6070 | 2015-08-13 00:10:03 +0000 | [diff] [blame] | 105 | /// \name Countable Loop Idiom Handling |
| 106 | /// @{ |
| 107 | |
Chandler Carruth | bad690e | 2015-08-12 23:06:37 +0000 | [diff] [blame] | 108 | bool runOnCountableLoop(); |
Chandler Carruth | d9c6070 | 2015-08-13 00:10:03 +0000 | [diff] [blame] | 109 | bool runOnLoopBlock(BasicBlock *BB, const SCEV *BECount, |
| 110 | SmallVectorImpl<BasicBlock *> &ExitBlocks); |
| 111 | |
Chad Rosier | cc9030b | 2015-11-11 23:00:59 +0000 | [diff] [blame] | 112 | void collectStores(BasicBlock *BB); |
Haicheng Wu | f1c00a2 | 2016-01-26 02:27:47 +0000 | [diff] [blame] | 113 | bool isLegalStore(StoreInst *SI, bool &ForMemset, bool &ForMemsetPattern, |
| 114 | bool &ForMemcpy); |
| 115 | bool processLoopStores(SmallVectorImpl<StoreInst *> &SL, const SCEV *BECount, |
| 116 | bool ForMemset); |
Chandler Carruth | d9c6070 | 2015-08-13 00:10:03 +0000 | [diff] [blame] | 117 | bool processLoopMemSet(MemSetInst *MSI, const SCEV *BECount); |
| 118 | |
| 119 | bool processLoopStridedStore(Value *DestPtr, unsigned StoreSize, |
Haicheng Wu | 9d6c940 | 2016-01-04 21:43:14 +0000 | [diff] [blame] | 120 | unsigned StoreAlignment, Value *StoredVal, |
Haicheng Wu | f1c00a2 | 2016-01-26 02:27:47 +0000 | [diff] [blame] | 121 | Instruction *TheStore, |
| 122 | SmallPtrSetImpl<Instruction *> &Stores, |
| 123 | const SCEVAddRecExpr *Ev, const SCEV *BECount, |
| 124 | bool NegStride); |
Haicheng Wu | 9d6c940 | 2016-01-04 21:43:14 +0000 | [diff] [blame] | 125 | bool processLoopStoreOfLoopLoad(StoreInst *SI, const SCEV *BECount); |
Chandler Carruth | d9c6070 | 2015-08-13 00:10:03 +0000 | [diff] [blame] | 126 | |
| 127 | /// @} |
| 128 | /// \name Noncountable Loop Idiom Handling |
| 129 | /// @{ |
| 130 | |
| 131 | bool runOnNoncountableLoop(); |
| 132 | |
Chandler Carruth | 8219a50 | 2015-08-13 00:44:29 +0000 | [diff] [blame] | 133 | bool recognizePopcount(); |
| 134 | void transformLoopToPopcount(BasicBlock *PreCondBB, Instruction *CntInst, |
| 135 | PHINode *CntPhi, Value *Var); |
| 136 | |
Chandler Carruth | d9c6070 | 2015-08-13 00:10:03 +0000 | [diff] [blame] | 137 | /// @} |
Chandler Carruth | bad690e | 2015-08-12 23:06:37 +0000 | [diff] [blame] | 138 | }; |
| 139 | |
| 140 | } // End anonymous namespace. |
Chris Lattner | 81ae3f2 | 2010-12-26 19:39:38 +0000 | [diff] [blame] | 141 | |
| 142 | char LoopIdiomRecognize::ID = 0; |
| 143 | INITIALIZE_PASS_BEGIN(LoopIdiomRecognize, "loop-idiom", "Recognize loop idioms", |
| 144 | false, false) |
Chandler Carruth | 31088a9 | 2016-02-19 10:45:18 +0000 | [diff] [blame] | 145 | INITIALIZE_PASS_DEPENDENCY(LoopPass) |
Chandler Carruth | b98f63d | 2015-01-15 10:41:28 +0000 | [diff] [blame] | 146 | INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) |
Chandler Carruth | 705b185 | 2015-01-31 03:43:40 +0000 | [diff] [blame] | 147 | INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass) |
Chris Lattner | 81ae3f2 | 2010-12-26 19:39:38 +0000 | [diff] [blame] | 148 | INITIALIZE_PASS_END(LoopIdiomRecognize, "loop-idiom", "Recognize loop idioms", |
| 149 | false, false) |
| 150 | |
| 151 | Pass *llvm::createLoopIdiomPass() { return new LoopIdiomRecognize(); } |
| 152 | |
David Majnemer | c5601df | 2016-06-20 16:03:25 +0000 | [diff] [blame] | 153 | static void deleteDeadInstruction(Instruction *I) { |
Benjamin Kramer | f094d77 | 2015-02-07 21:37:08 +0000 | [diff] [blame] | 154 | I->replaceAllUsesWith(UndefValue::get(I->getType())); |
| 155 | I->eraseFromParent(); |
Chandler Carruth | 099f5cb0 | 2012-11-02 08:33:25 +0000 | [diff] [blame] | 156 | } |
| 157 | |
Shuxin Yang | 95de7c3 | 2012-12-09 03:12:46 +0000 | [diff] [blame] | 158 | //===----------------------------------------------------------------------===// |
| 159 | // |
Shuxin Yang | 95de7c3 | 2012-12-09 03:12:46 +0000 | [diff] [blame] | 160 | // Implementation of LoopIdiomRecognize |
| 161 | // |
| 162 | //===----------------------------------------------------------------------===// |
| 163 | |
Chandler Carruth | d9c6070 | 2015-08-13 00:10:03 +0000 | [diff] [blame] | 164 | bool LoopIdiomRecognize::runOnLoop(Loop *L, LPPassManager &LPM) { |
Andrew Kaylor | aa641a5 | 2016-04-22 22:06:11 +0000 | [diff] [blame] | 165 | if (skipLoop(L)) |
Chandler Carruth | d9c6070 | 2015-08-13 00:10:03 +0000 | [diff] [blame] | 166 | return false; |
| 167 | |
| 168 | CurLoop = L; |
Chandler Carruth | d9c6070 | 2015-08-13 00:10:03 +0000 | [diff] [blame] | 169 | // If the loop could not be converted to canonical form, it must have an |
| 170 | // indirectbr in it, just give up. |
| 171 | if (!L->getLoopPreheader()) |
| 172 | return false; |
| 173 | |
| 174 | // Disable loop idiom recognition if the function's name is a common idiom. |
| 175 | StringRef Name = L->getHeader()->getParent()->getName(); |
| 176 | if (Name == "memset" || Name == "memcpy") |
| 177 | return false; |
| 178 | |
Chandler Carruth | 7b560d4 | 2015-09-09 17:55:00 +0000 | [diff] [blame] | 179 | AA = &getAnalysis<AAResultsWrapperPass>().getAAResults(); |
Chandler Carruth | dc29832 | 2015-08-13 01:03:26 +0000 | [diff] [blame] | 180 | DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree(); |
Chandler Carruth | 18c2669 | 2015-08-13 09:27:01 +0000 | [diff] [blame] | 181 | LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 182 | SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE(); |
Chandler Carruth | dc29832 | 2015-08-13 01:03:26 +0000 | [diff] [blame] | 183 | TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(); |
| 184 | TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI( |
| 185 | *CurLoop->getHeader()->getParent()); |
Chad Rosier | 43f9b48 | 2015-11-06 16:33:57 +0000 | [diff] [blame] | 186 | DL = &CurLoop->getHeader()->getModule()->getDataLayout(); |
Chandler Carruth | dc29832 | 2015-08-13 01:03:26 +0000 | [diff] [blame] | 187 | |
Haicheng Wu | 9d6c940 | 2016-01-04 21:43:14 +0000 | [diff] [blame] | 188 | HasMemset = TLI->has(LibFunc::memset); |
| 189 | HasMemsetPattern = TLI->has(LibFunc::memset_pattern16); |
| 190 | HasMemcpy = TLI->has(LibFunc::memcpy); |
| 191 | |
| 192 | if (HasMemset || HasMemsetPattern || HasMemcpy) |
| 193 | if (SE->hasLoopInvariantBackedgeTakenCount(L)) |
| 194 | return runOnCountableLoop(); |
Chandler Carruth | dc29832 | 2015-08-13 01:03:26 +0000 | [diff] [blame] | 195 | |
Chandler Carruth | d9c6070 | 2015-08-13 00:10:03 +0000 | [diff] [blame] | 196 | return runOnNoncountableLoop(); |
| 197 | } |
| 198 | |
Shuxin Yang | 95de7c3 | 2012-12-09 03:12:46 +0000 | [diff] [blame] | 199 | bool LoopIdiomRecognize::runOnCountableLoop() { |
| 200 | const SCEV *BECount = SE->getBackedgeTakenCount(CurLoop); |
Davide Italiano | 8ed0446 | 2015-05-11 21:02:34 +0000 | [diff] [blame] | 201 | assert(!isa<SCEVCouldNotCompute>(BECount) && |
Chandler Carruth | bad690e | 2015-08-12 23:06:37 +0000 | [diff] [blame] | 202 | "runOnCountableLoop() called on a loop without a predictable" |
| 203 | "backedge-taken count"); |
Shuxin Yang | 95de7c3 | 2012-12-09 03:12:46 +0000 | [diff] [blame] | 204 | |
| 205 | // If this loop executes exactly one time, then it should be peeled, not |
| 206 | // optimized by this pass. |
| 207 | if (const SCEVConstant *BECst = dyn_cast<SCEVConstant>(BECount)) |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 208 | if (BECst->getAPInt() == 0) |
Shuxin Yang | 95de7c3 | 2012-12-09 03:12:46 +0000 | [diff] [blame] | 209 | return false; |
| 210 | |
Chandler Carruth | bad690e | 2015-08-12 23:06:37 +0000 | [diff] [blame] | 211 | SmallVector<BasicBlock *, 8> ExitBlocks; |
Shuxin Yang | 95de7c3 | 2012-12-09 03:12:46 +0000 | [diff] [blame] | 212 | CurLoop->getUniqueExitBlocks(ExitBlocks); |
| 213 | |
| 214 | DEBUG(dbgs() << "loop-idiom Scanning: F[" |
Chandler Carruth | bad690e | 2015-08-12 23:06:37 +0000 | [diff] [blame] | 215 | << CurLoop->getHeader()->getParent()->getName() << "] Loop %" |
| 216 | << CurLoop->getHeader()->getName() << "\n"); |
Shuxin Yang | 95de7c3 | 2012-12-09 03:12:46 +0000 | [diff] [blame] | 217 | |
| 218 | bool MadeChange = false; |
Haicheng Wu | a95cd126 | 2016-07-06 21:05:40 +0000 | [diff] [blame^] | 219 | |
| 220 | // The following transforms hoist stores/memsets into the loop pre-header. |
| 221 | // Give up if the loop has instructions may throw. |
| 222 | LoopSafetyInfo SafetyInfo; |
| 223 | computeLoopSafetyInfo(&SafetyInfo, CurLoop); |
| 224 | if (SafetyInfo.MayThrow) |
| 225 | return MadeChange; |
| 226 | |
Shuxin Yang | 95de7c3 | 2012-12-09 03:12:46 +0000 | [diff] [blame] | 227 | // Scan all the blocks in the loop that are not in subloops. |
Davide Italiano | 95a77e8 | 2015-05-14 21:52:12 +0000 | [diff] [blame] | 228 | for (auto *BB : CurLoop->getBlocks()) { |
Shuxin Yang | 95de7c3 | 2012-12-09 03:12:46 +0000 | [diff] [blame] | 229 | // Ignore blocks in subloops. |
Chandler Carruth | 18c2669 | 2015-08-13 09:27:01 +0000 | [diff] [blame] | 230 | if (LI->getLoopFor(BB) != CurLoop) |
Shuxin Yang | 95de7c3 | 2012-12-09 03:12:46 +0000 | [diff] [blame] | 231 | continue; |
| 232 | |
Davide Italiano | 80625af | 2015-05-13 19:51:21 +0000 | [diff] [blame] | 233 | MadeChange |= runOnLoopBlock(BB, BECount, ExitBlocks); |
Shuxin Yang | 95de7c3 | 2012-12-09 03:12:46 +0000 | [diff] [blame] | 234 | } |
| 235 | return MadeChange; |
| 236 | } |
| 237 | |
Chad Rosier | a548fe5 | 2015-11-12 19:09:16 +0000 | [diff] [blame] | 238 | static unsigned getStoreSizeInBytes(StoreInst *SI, const DataLayout *DL) { |
| 239 | uint64_t SizeInBits = DL->getTypeSizeInBits(SI->getValueOperand()->getType()); |
| 240 | assert(((SizeInBits & 7) || (SizeInBits >> 32) == 0) && |
| 241 | "Don't overflow unsigned."); |
| 242 | return (unsigned)SizeInBits >> 3; |
| 243 | } |
| 244 | |
Chad Rosier | 4acff96 | 2016-02-12 19:05:27 +0000 | [diff] [blame] | 245 | static APInt getStoreStride(const SCEVAddRecExpr *StoreEv) { |
Chad Rosier | a548fe5 | 2015-11-12 19:09:16 +0000 | [diff] [blame] | 246 | const SCEVConstant *ConstStride = cast<SCEVConstant>(StoreEv->getOperand(1)); |
Chad Rosier | 4acff96 | 2016-02-12 19:05:27 +0000 | [diff] [blame] | 247 | return ConstStride->getAPInt(); |
Chad Rosier | a548fe5 | 2015-11-12 19:09:16 +0000 | [diff] [blame] | 248 | } |
| 249 | |
Chad Rosier | 94274fb | 2015-12-21 14:49:32 +0000 | [diff] [blame] | 250 | /// getMemSetPatternValue - If a strided store of the specified value is safe to |
| 251 | /// turn into a memset_pattern16, return a ConstantArray of 16 bytes that should |
| 252 | /// be passed in. Otherwise, return null. |
| 253 | /// |
| 254 | /// Note that we don't ever attempt to use memset_pattern8 or 4, because these |
| 255 | /// just replicate their input array and then pass on to memset_pattern16. |
| 256 | static Constant *getMemSetPatternValue(Value *V, const DataLayout *DL) { |
| 257 | // If the value isn't a constant, we can't promote it to being in a constant |
| 258 | // array. We could theoretically do a store to an alloca or something, but |
| 259 | // that doesn't seem worthwhile. |
| 260 | Constant *C = dyn_cast<Constant>(V); |
| 261 | if (!C) |
| 262 | return nullptr; |
| 263 | |
| 264 | // Only handle simple values that are a power of two bytes in size. |
| 265 | uint64_t Size = DL->getTypeSizeInBits(V->getType()); |
| 266 | if (Size == 0 || (Size & 7) || (Size & (Size - 1))) |
| 267 | return nullptr; |
| 268 | |
| 269 | // Don't care enough about darwin/ppc to implement this. |
| 270 | if (DL->isBigEndian()) |
| 271 | return nullptr; |
| 272 | |
| 273 | // Convert to size in bytes. |
| 274 | Size /= 8; |
| 275 | |
| 276 | // TODO: If CI is larger than 16-bytes, we can try slicing it in half to see |
| 277 | // if the top and bottom are the same (e.g. for vectors and large integers). |
| 278 | if (Size > 16) |
| 279 | return nullptr; |
| 280 | |
| 281 | // If the constant is exactly 16 bytes, just use it. |
| 282 | if (Size == 16) |
| 283 | return C; |
| 284 | |
| 285 | // Otherwise, we'll use an array of the constants. |
| 286 | unsigned ArraySize = 16 / Size; |
| 287 | ArrayType *AT = ArrayType::get(V->getType(), ArraySize); |
| 288 | return ConstantArray::get(AT, std::vector<Constant *>(ArraySize, C)); |
| 289 | } |
| 290 | |
Haicheng Wu | 9d6c940 | 2016-01-04 21:43:14 +0000 | [diff] [blame] | 291 | bool LoopIdiomRecognize::isLegalStore(StoreInst *SI, bool &ForMemset, |
Haicheng Wu | f1c00a2 | 2016-01-26 02:27:47 +0000 | [diff] [blame] | 292 | bool &ForMemsetPattern, bool &ForMemcpy) { |
Chad Rosier | 869962f | 2015-12-01 14:26:35 +0000 | [diff] [blame] | 293 | // Don't touch volatile stores. |
| 294 | if (!SI->isSimple()) |
| 295 | return false; |
| 296 | |
Haicheng Wu | 57e1a3e | 2016-02-17 21:00:06 +0000 | [diff] [blame] | 297 | // Avoid merging nontemporal stores. |
| 298 | if (SI->getMetadata(LLVMContext::MD_nontemporal)) |
| 299 | return false; |
| 300 | |
Chad Rosier | a548fe5 | 2015-11-12 19:09:16 +0000 | [diff] [blame] | 301 | Value *StoredVal = SI->getValueOperand(); |
| 302 | Value *StorePtr = SI->getPointerOperand(); |
| 303 | |
| 304 | // Reject stores that are so large that they overflow an unsigned. |
| 305 | uint64_t SizeInBits = DL->getTypeSizeInBits(StoredVal->getType()); |
| 306 | if ((SizeInBits & 7) || (SizeInBits >> 32) != 0) |
| 307 | return false; |
| 308 | |
| 309 | // See if the pointer expression is an AddRec like {base,+,1} on the current |
| 310 | // loop, which indicates a strided store. If we have something else, it's a |
| 311 | // random store we can't handle. |
| 312 | const SCEVAddRecExpr *StoreEv = |
| 313 | dyn_cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr)); |
| 314 | if (!StoreEv || StoreEv->getLoop() != CurLoop || !StoreEv->isAffine()) |
| 315 | return false; |
| 316 | |
| 317 | // Check to see if we have a constant stride. |
| 318 | if (!isa<SCEVConstant>(StoreEv->getOperand(1))) |
| 319 | return false; |
| 320 | |
Haicheng Wu | 9d6c940 | 2016-01-04 21:43:14 +0000 | [diff] [blame] | 321 | // See if the store can be turned into a memset. |
| 322 | |
| 323 | // If the stored value is a byte-wise value (like i32 -1), then it may be |
| 324 | // turned into a memset of i8 -1, assuming that all the consecutive bytes |
| 325 | // are stored. A store of i32 0x01020304 can never be turned into a memset, |
| 326 | // but it can be turned into memset_pattern if the target supports it. |
| 327 | Value *SplatValue = isBytewiseValue(StoredVal); |
| 328 | Constant *PatternValue = nullptr; |
| 329 | |
| 330 | // If we're allowed to form a memset, and the stored value would be |
| 331 | // acceptable for memset, use it. |
| 332 | if (HasMemset && SplatValue && |
| 333 | // Verify that the stored value is loop invariant. If not, we can't |
| 334 | // promote the memset. |
| 335 | CurLoop->isLoopInvariant(SplatValue)) { |
| 336 | // It looks like we can use SplatValue. |
| 337 | ForMemset = true; |
| 338 | return true; |
| 339 | } else if (HasMemsetPattern && |
| 340 | // Don't create memset_pattern16s with address spaces. |
| 341 | StorePtr->getType()->getPointerAddressSpace() == 0 && |
| 342 | (PatternValue = getMemSetPatternValue(StoredVal, DL))) { |
| 343 | // It looks like we can use PatternValue! |
Haicheng Wu | f1c00a2 | 2016-01-26 02:27:47 +0000 | [diff] [blame] | 344 | ForMemsetPattern = true; |
Haicheng Wu | 9d6c940 | 2016-01-04 21:43:14 +0000 | [diff] [blame] | 345 | return true; |
| 346 | } |
| 347 | |
| 348 | // Otherwise, see if the store can be turned into a memcpy. |
| 349 | if (HasMemcpy) { |
| 350 | // Check to see if the stride matches the size of the store. If so, then we |
| 351 | // know that every byte is touched in the loop. |
Chad Rosier | 4acff96 | 2016-02-12 19:05:27 +0000 | [diff] [blame] | 352 | APInt Stride = getStoreStride(StoreEv); |
Haicheng Wu | 9d6c940 | 2016-01-04 21:43:14 +0000 | [diff] [blame] | 353 | unsigned StoreSize = getStoreSizeInBytes(SI, DL); |
| 354 | if (StoreSize != Stride && StoreSize != -Stride) |
| 355 | return false; |
| 356 | |
| 357 | // The store must be feeding a non-volatile load. |
| 358 | LoadInst *LI = dyn_cast<LoadInst>(SI->getValueOperand()); |
| 359 | if (!LI || !LI->isSimple()) |
| 360 | return false; |
| 361 | |
| 362 | // See if the pointer expression is an AddRec like {base,+,1} on the current |
| 363 | // loop, which indicates a strided load. If we have something else, it's a |
| 364 | // random load we can't handle. |
| 365 | const SCEVAddRecExpr *LoadEv = |
| 366 | dyn_cast<SCEVAddRecExpr>(SE->getSCEV(LI->getPointerOperand())); |
| 367 | if (!LoadEv || LoadEv->getLoop() != CurLoop || !LoadEv->isAffine()) |
| 368 | return false; |
| 369 | |
| 370 | // The store and load must share the same stride. |
| 371 | if (StoreEv->getOperand(1) != LoadEv->getOperand(1)) |
| 372 | return false; |
| 373 | |
| 374 | // Success. This store can be converted into a memcpy. |
| 375 | ForMemcpy = true; |
| 376 | return true; |
| 377 | } |
| 378 | // This store can't be transformed into a memset/memcpy. |
| 379 | return false; |
Chad Rosier | a548fe5 | 2015-11-12 19:09:16 +0000 | [diff] [blame] | 380 | } |
| 381 | |
Chad Rosier | cc9030b | 2015-11-11 23:00:59 +0000 | [diff] [blame] | 382 | void LoopIdiomRecognize::collectStores(BasicBlock *BB) { |
Haicheng Wu | 9d6c940 | 2016-01-04 21:43:14 +0000 | [diff] [blame] | 383 | StoreRefsForMemset.clear(); |
Haicheng Wu | f1c00a2 | 2016-01-26 02:27:47 +0000 | [diff] [blame] | 384 | StoreRefsForMemsetPattern.clear(); |
Haicheng Wu | 9d6c940 | 2016-01-04 21:43:14 +0000 | [diff] [blame] | 385 | StoreRefsForMemcpy.clear(); |
Chad Rosier | cc9030b | 2015-11-11 23:00:59 +0000 | [diff] [blame] | 386 | for (Instruction &I : *BB) { |
| 387 | StoreInst *SI = dyn_cast<StoreInst>(&I); |
| 388 | if (!SI) |
| 389 | continue; |
| 390 | |
Haicheng Wu | 9d6c940 | 2016-01-04 21:43:14 +0000 | [diff] [blame] | 391 | bool ForMemset = false; |
Haicheng Wu | f1c00a2 | 2016-01-26 02:27:47 +0000 | [diff] [blame] | 392 | bool ForMemsetPattern = false; |
Haicheng Wu | 9d6c940 | 2016-01-04 21:43:14 +0000 | [diff] [blame] | 393 | bool ForMemcpy = false; |
Chad Rosier | a548fe5 | 2015-11-12 19:09:16 +0000 | [diff] [blame] | 394 | // Make sure this is a strided store with a constant stride. |
Haicheng Wu | f1c00a2 | 2016-01-26 02:27:47 +0000 | [diff] [blame] | 395 | if (!isLegalStore(SI, ForMemset, ForMemsetPattern, ForMemcpy)) |
Chad Rosier | a548fe5 | 2015-11-12 19:09:16 +0000 | [diff] [blame] | 396 | continue; |
| 397 | |
Chad Rosier | cc9030b | 2015-11-11 23:00:59 +0000 | [diff] [blame] | 398 | // Save the store locations. |
Haicheng Wu | f1c00a2 | 2016-01-26 02:27:47 +0000 | [diff] [blame] | 399 | if (ForMemset) { |
| 400 | // Find the base pointer. |
| 401 | Value *Ptr = GetUnderlyingObject(SI->getPointerOperand(), *DL); |
| 402 | StoreRefsForMemset[Ptr].push_back(SI); |
| 403 | } else if (ForMemsetPattern) { |
| 404 | // Find the base pointer. |
| 405 | Value *Ptr = GetUnderlyingObject(SI->getPointerOperand(), *DL); |
| 406 | StoreRefsForMemsetPattern[Ptr].push_back(SI); |
| 407 | } else if (ForMemcpy) |
Haicheng Wu | 9d6c940 | 2016-01-04 21:43:14 +0000 | [diff] [blame] | 408 | StoreRefsForMemcpy.push_back(SI); |
Chad Rosier | cc9030b | 2015-11-11 23:00:59 +0000 | [diff] [blame] | 409 | } |
| 410 | } |
| 411 | |
Chris Lattner | 8455b6e | 2011-01-02 19:01:03 +0000 | [diff] [blame] | 412 | /// runOnLoopBlock - Process the specified block, which lives in a counted loop |
| 413 | /// with the specified backedge count. This block is known to be in the current |
| 414 | /// loop and not in any subloops. |
Chandler Carruth | bad690e | 2015-08-12 23:06:37 +0000 | [diff] [blame] | 415 | bool LoopIdiomRecognize::runOnLoopBlock( |
| 416 | BasicBlock *BB, const SCEV *BECount, |
| 417 | SmallVectorImpl<BasicBlock *> &ExitBlocks) { |
Chris Lattner | 8455b6e | 2011-01-02 19:01:03 +0000 | [diff] [blame] | 418 | // We can only promote stores in this block if they are unconditionally |
| 419 | // executed in the loop. For a block to be unconditionally executed, it has |
| 420 | // to dominate all the exit blocks of the loop. Verify this now. |
| 421 | for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) |
| 422 | if (!DT->dominates(BB, ExitBlocks[i])) |
| 423 | return false; |
Andrew Trick | 328b223 | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 424 | |
Chris Lattner | 7c5f9c3 | 2010-12-26 20:45:45 +0000 | [diff] [blame] | 425 | bool MadeChange = false; |
Chad Rosier | cc9030b | 2015-11-11 23:00:59 +0000 | [diff] [blame] | 426 | // Look for store instructions, which may be optimized to memset/memcpy. |
| 427 | collectStores(BB); |
Haicheng Wu | 9d6c940 | 2016-01-04 21:43:14 +0000 | [diff] [blame] | 428 | |
Haicheng Wu | f1c00a2 | 2016-01-26 02:27:47 +0000 | [diff] [blame] | 429 | // Look for a single store or sets of stores with a common base, which can be |
| 430 | // optimized into a memset (memset_pattern). The latter most commonly happens |
| 431 | // with structs and handunrolled loops. |
| 432 | for (auto &SL : StoreRefsForMemset) |
| 433 | MadeChange |= processLoopStores(SL.second, BECount, true); |
| 434 | |
| 435 | for (auto &SL : StoreRefsForMemsetPattern) |
| 436 | MadeChange |= processLoopStores(SL.second, BECount, false); |
Chad Rosier | cc9030b | 2015-11-11 23:00:59 +0000 | [diff] [blame] | 437 | |
Haicheng Wu | 9d6c940 | 2016-01-04 21:43:14 +0000 | [diff] [blame] | 438 | // Optimize the store into a memcpy, if it feeds an similarly strided load. |
| 439 | for (auto &SI : StoreRefsForMemcpy) |
| 440 | MadeChange |= processLoopStoreOfLoopLoad(SI, BECount); |
| 441 | |
Chandler Carruth | bad690e | 2015-08-12 23:06:37 +0000 | [diff] [blame] | 442 | for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) { |
Duncan P. N. Exon Smith | be4d8cb | 2015-10-13 19:26:58 +0000 | [diff] [blame] | 443 | Instruction *Inst = &*I++; |
Chris Lattner | 8643810 | 2011-01-04 07:46:33 +0000 | [diff] [blame] | 444 | // Look for memset instructions, which may be optimized to a larger memset. |
Chandler Carruth | bad690e | 2015-08-12 23:06:37 +0000 | [diff] [blame] | 445 | if (MemSetInst *MSI = dyn_cast<MemSetInst>(Inst)) { |
Duncan P. N. Exon Smith | be4d8cb | 2015-10-13 19:26:58 +0000 | [diff] [blame] | 446 | WeakVH InstPtr(&*I); |
Chandler Carruth | bad690e | 2015-08-12 23:06:37 +0000 | [diff] [blame] | 447 | if (!processLoopMemSet(MSI, BECount)) |
| 448 | continue; |
Chris Lattner | 8643810 | 2011-01-04 07:46:33 +0000 | [diff] [blame] | 449 | MadeChange = true; |
Andrew Trick | 328b223 | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 450 | |
Chris Lattner | 8643810 | 2011-01-04 07:46:33 +0000 | [diff] [blame] | 451 | // If processing the memset invalidated our iterator, start over from the |
| 452 | // top of the block. |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 453 | if (!InstPtr) |
Chris Lattner | 8643810 | 2011-01-04 07:46:33 +0000 | [diff] [blame] | 454 | I = BB->begin(); |
| 455 | continue; |
| 456 | } |
Chris Lattner | 7c5f9c3 | 2010-12-26 20:45:45 +0000 | [diff] [blame] | 457 | } |
Andrew Trick | 328b223 | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 458 | |
Chris Lattner | 7c5f9c3 | 2010-12-26 20:45:45 +0000 | [diff] [blame] | 459 | return MadeChange; |
Chris Lattner | 81ae3f2 | 2010-12-26 19:39:38 +0000 | [diff] [blame] | 460 | } |
| 461 | |
Haicheng Wu | f1c00a2 | 2016-01-26 02:27:47 +0000 | [diff] [blame] | 462 | /// processLoopStores - See if this store(s) can be promoted to a memset. |
| 463 | bool LoopIdiomRecognize::processLoopStores(SmallVectorImpl<StoreInst *> &SL, |
| 464 | const SCEV *BECount, |
| 465 | bool ForMemset) { |
| 466 | // Try to find consecutive stores that can be transformed into memsets. |
| 467 | SetVector<StoreInst *> Heads, Tails; |
| 468 | SmallDenseMap<StoreInst *, StoreInst *> ConsecutiveChain; |
Chris Lattner | 8643810 | 2011-01-04 07:46:33 +0000 | [diff] [blame] | 469 | |
Haicheng Wu | f1c00a2 | 2016-01-26 02:27:47 +0000 | [diff] [blame] | 470 | // Do a quadratic search on all of the given stores and find |
| 471 | // all of the pairs of stores that follow each other. |
| 472 | SmallVector<unsigned, 16> IndexQueue; |
| 473 | for (unsigned i = 0, e = SL.size(); i < e; ++i) { |
| 474 | assert(SL[i]->isSimple() && "Expected only non-volatile stores."); |
Andrew Trick | 328b223 | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 475 | |
Haicheng Wu | f1c00a2 | 2016-01-26 02:27:47 +0000 | [diff] [blame] | 476 | Value *FirstStoredVal = SL[i]->getValueOperand(); |
| 477 | Value *FirstStorePtr = SL[i]->getPointerOperand(); |
| 478 | const SCEVAddRecExpr *FirstStoreEv = |
| 479 | cast<SCEVAddRecExpr>(SE->getSCEV(FirstStorePtr)); |
Chad Rosier | 4acff96 | 2016-02-12 19:05:27 +0000 | [diff] [blame] | 480 | APInt FirstStride = getStoreStride(FirstStoreEv); |
Haicheng Wu | f1c00a2 | 2016-01-26 02:27:47 +0000 | [diff] [blame] | 481 | unsigned FirstStoreSize = getStoreSizeInBytes(SL[i], DL); |
Chad Rosier | 7967614 | 2015-10-28 14:38:49 +0000 | [diff] [blame] | 482 | |
Haicheng Wu | f1c00a2 | 2016-01-26 02:27:47 +0000 | [diff] [blame] | 483 | // See if we can optimize just this store in isolation. |
Chad Rosier | 4acff96 | 2016-02-12 19:05:27 +0000 | [diff] [blame] | 484 | if (FirstStride == FirstStoreSize || -FirstStride == FirstStoreSize) { |
Haicheng Wu | f1c00a2 | 2016-01-26 02:27:47 +0000 | [diff] [blame] | 485 | Heads.insert(SL[i]); |
| 486 | continue; |
| 487 | } |
Chris Lattner | 0f4a640 | 2011-02-19 19:31:39 +0000 | [diff] [blame] | 488 | |
Haicheng Wu | f1c00a2 | 2016-01-26 02:27:47 +0000 | [diff] [blame] | 489 | Value *FirstSplatValue = nullptr; |
| 490 | Constant *FirstPatternValue = nullptr; |
| 491 | |
| 492 | if (ForMemset) |
| 493 | FirstSplatValue = isBytewiseValue(FirstStoredVal); |
| 494 | else |
| 495 | FirstPatternValue = getMemSetPatternValue(FirstStoredVal, DL); |
| 496 | |
| 497 | assert((FirstSplatValue || FirstPatternValue) && |
| 498 | "Expected either splat value or pattern value."); |
| 499 | |
| 500 | IndexQueue.clear(); |
| 501 | // If a store has multiple consecutive store candidates, search Stores |
| 502 | // array according to the sequence: from i+1 to e, then from i-1 to 0. |
| 503 | // This is because usually pairing with immediate succeeding or preceding |
| 504 | // candidate create the best chance to find memset opportunity. |
| 505 | unsigned j = 0; |
| 506 | for (j = i + 1; j < e; ++j) |
| 507 | IndexQueue.push_back(j); |
| 508 | for (j = i; j > 0; --j) |
| 509 | IndexQueue.push_back(j - 1); |
| 510 | |
| 511 | for (auto &k : IndexQueue) { |
| 512 | assert(SL[k]->isSimple() && "Expected only non-volatile stores."); |
| 513 | Value *SecondStorePtr = SL[k]->getPointerOperand(); |
| 514 | const SCEVAddRecExpr *SecondStoreEv = |
| 515 | cast<SCEVAddRecExpr>(SE->getSCEV(SecondStorePtr)); |
Chad Rosier | 4acff96 | 2016-02-12 19:05:27 +0000 | [diff] [blame] | 516 | APInt SecondStride = getStoreStride(SecondStoreEv); |
Haicheng Wu | f1c00a2 | 2016-01-26 02:27:47 +0000 | [diff] [blame] | 517 | |
| 518 | if (FirstStride != SecondStride) |
| 519 | continue; |
| 520 | |
| 521 | Value *SecondStoredVal = SL[k]->getValueOperand(); |
| 522 | Value *SecondSplatValue = nullptr; |
| 523 | Constant *SecondPatternValue = nullptr; |
| 524 | |
| 525 | if (ForMemset) |
| 526 | SecondSplatValue = isBytewiseValue(SecondStoredVal); |
| 527 | else |
| 528 | SecondPatternValue = getMemSetPatternValue(SecondStoredVal, DL); |
| 529 | |
| 530 | assert((SecondSplatValue || SecondPatternValue) && |
| 531 | "Expected either splat value or pattern value."); |
| 532 | |
| 533 | if (isConsecutiveAccess(SL[i], SL[k], *DL, *SE, false)) { |
| 534 | if (ForMemset) { |
| 535 | if (FirstSplatValue != SecondSplatValue) |
| 536 | continue; |
| 537 | } else { |
| 538 | if (FirstPatternValue != SecondPatternValue) |
| 539 | continue; |
| 540 | } |
| 541 | Tails.insert(SL[k]); |
| 542 | Heads.insert(SL[i]); |
| 543 | ConsecutiveChain[SL[i]] = SL[k]; |
| 544 | break; |
| 545 | } |
| 546 | } |
| 547 | } |
| 548 | |
| 549 | // We may run into multiple chains that merge into a single chain. We mark the |
| 550 | // stores that we transformed so that we don't visit the same store twice. |
| 551 | SmallPtrSet<Value *, 16> TransformedStores; |
| 552 | bool Changed = false; |
| 553 | |
| 554 | // For stores that start but don't end a link in the chain: |
| 555 | for (SetVector<StoreInst *>::iterator it = Heads.begin(), e = Heads.end(); |
| 556 | it != e; ++it) { |
| 557 | if (Tails.count(*it)) |
| 558 | continue; |
| 559 | |
| 560 | // We found a store instr that starts a chain. Now follow the chain and try |
| 561 | // to transform it. |
| 562 | SmallPtrSet<Instruction *, 8> AdjacentStores; |
| 563 | StoreInst *I = *it; |
| 564 | |
| 565 | StoreInst *HeadStore = I; |
| 566 | unsigned StoreSize = 0; |
| 567 | |
| 568 | // Collect the chain into a list. |
| 569 | while (Tails.count(I) || Heads.count(I)) { |
| 570 | if (TransformedStores.count(I)) |
| 571 | break; |
| 572 | AdjacentStores.insert(I); |
| 573 | |
| 574 | StoreSize += getStoreSizeInBytes(I, DL); |
| 575 | // Move to the next value in the chain. |
| 576 | I = ConsecutiveChain[I]; |
| 577 | } |
| 578 | |
| 579 | Value *StoredVal = HeadStore->getValueOperand(); |
| 580 | Value *StorePtr = HeadStore->getPointerOperand(); |
| 581 | const SCEVAddRecExpr *StoreEv = cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr)); |
Chad Rosier | 4acff96 | 2016-02-12 19:05:27 +0000 | [diff] [blame] | 582 | APInt Stride = getStoreStride(StoreEv); |
Haicheng Wu | f1c00a2 | 2016-01-26 02:27:47 +0000 | [diff] [blame] | 583 | |
| 584 | // Check to see if the stride matches the size of the stores. If so, then |
| 585 | // we know that every byte is touched in the loop. |
| 586 | if (StoreSize != Stride && StoreSize != -Stride) |
| 587 | continue; |
| 588 | |
| 589 | bool NegStride = StoreSize == -Stride; |
| 590 | |
| 591 | if (processLoopStridedStore(StorePtr, StoreSize, HeadStore->getAlignment(), |
| 592 | StoredVal, HeadStore, AdjacentStores, StoreEv, |
| 593 | BECount, NegStride)) { |
| 594 | TransformedStores.insert(AdjacentStores.begin(), AdjacentStores.end()); |
| 595 | Changed = true; |
| 596 | } |
| 597 | } |
| 598 | |
| 599 | return Changed; |
Chris Lattner | 81ae3f2 | 2010-12-26 19:39:38 +0000 | [diff] [blame] | 600 | } |
| 601 | |
Chris Lattner | 8643810 | 2011-01-04 07:46:33 +0000 | [diff] [blame] | 602 | /// processLoopMemSet - See if this memset can be promoted to a large memset. |
Chandler Carruth | bad690e | 2015-08-12 23:06:37 +0000 | [diff] [blame] | 603 | bool LoopIdiomRecognize::processLoopMemSet(MemSetInst *MSI, |
| 604 | const SCEV *BECount) { |
Chris Lattner | 8643810 | 2011-01-04 07:46:33 +0000 | [diff] [blame] | 605 | // We can only handle non-volatile memsets with a constant size. |
Chandler Carruth | bad690e | 2015-08-12 23:06:37 +0000 | [diff] [blame] | 606 | if (MSI->isVolatile() || !isa<ConstantInt>(MSI->getLength())) |
| 607 | return false; |
Chris Lattner | 8643810 | 2011-01-04 07:46:33 +0000 | [diff] [blame] | 608 | |
Chris Lattner | e6b261f | 2011-02-18 22:22:15 +0000 | [diff] [blame] | 609 | // If we're not allowed to hack on memset, we fail. |
Ahmed Bougacha | 7f97193 | 2016-04-27 19:04:46 +0000 | [diff] [blame] | 610 | if (!HasMemset) |
Chris Lattner | e6b261f | 2011-02-18 22:22:15 +0000 | [diff] [blame] | 611 | return false; |
Andrew Trick | 328b223 | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 612 | |
Chris Lattner | 8643810 | 2011-01-04 07:46:33 +0000 | [diff] [blame] | 613 | Value *Pointer = MSI->getDest(); |
Andrew Trick | 328b223 | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 614 | |
Chris Lattner | 8643810 | 2011-01-04 07:46:33 +0000 | [diff] [blame] | 615 | // See if the pointer expression is an AddRec like {base,+,1} on the current |
| 616 | // loop, which indicates a strided store. If we have something else, it's a |
| 617 | // random store we can't handle. |
| 618 | const SCEVAddRecExpr *Ev = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Pointer)); |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 619 | if (!Ev || Ev->getLoop() != CurLoop || !Ev->isAffine()) |
Chris Lattner | 8643810 | 2011-01-04 07:46:33 +0000 | [diff] [blame] | 620 | return false; |
| 621 | |
| 622 | // Reject memsets that are so large that they overflow an unsigned. |
| 623 | uint64_t SizeInBytes = cast<ConstantInt>(MSI->getLength())->getZExtValue(); |
| 624 | if ((SizeInBytes >> 32) != 0) |
| 625 | return false; |
Andrew Trick | 328b223 | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 626 | |
Chris Lattner | 8643810 | 2011-01-04 07:46:33 +0000 | [diff] [blame] | 627 | // Check to see if the stride matches the size of the memset. If so, then we |
| 628 | // know that every byte is touched in the loop. |
Chad Rosier | 81362a8 | 2016-02-12 21:03:23 +0000 | [diff] [blame] | 629 | const SCEVConstant *ConstStride = dyn_cast<SCEVConstant>(Ev->getOperand(1)); |
| 630 | if (!ConstStride) |
| 631 | return false; |
Andrew Trick | 328b223 | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 632 | |
Chad Rosier | 81362a8 | 2016-02-12 21:03:23 +0000 | [diff] [blame] | 633 | APInt Stride = ConstStride->getAPInt(); |
| 634 | if (SizeInBytes != Stride && SizeInBytes != -Stride) |
Chris Lattner | 8643810 | 2011-01-04 07:46:33 +0000 | [diff] [blame] | 635 | return false; |
Andrew Trick | 328b223 | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 636 | |
Haicheng Wu | 9d6c940 | 2016-01-04 21:43:14 +0000 | [diff] [blame] | 637 | // Verify that the memset value is loop invariant. If not, we can't promote |
| 638 | // the memset. |
| 639 | Value *SplatValue = MSI->getValue(); |
| 640 | if (!SplatValue || !CurLoop->isLoopInvariant(SplatValue)) |
| 641 | return false; |
| 642 | |
Haicheng Wu | f1c00a2 | 2016-01-26 02:27:47 +0000 | [diff] [blame] | 643 | SmallPtrSet<Instruction *, 1> MSIs; |
| 644 | MSIs.insert(MSI); |
Chad Rosier | 81362a8 | 2016-02-12 21:03:23 +0000 | [diff] [blame] | 645 | bool NegStride = SizeInBytes == -Stride; |
Chris Lattner | 0f4a640 | 2011-02-19 19:31:39 +0000 | [diff] [blame] | 646 | return processLoopStridedStore(Pointer, (unsigned)SizeInBytes, |
Haicheng Wu | f1c00a2 | 2016-01-26 02:27:47 +0000 | [diff] [blame] | 647 | MSI->getAlignment(), SplatValue, MSI, MSIs, Ev, |
Chad Rosier | 81362a8 | 2016-02-12 21:03:23 +0000 | [diff] [blame] | 648 | BECount, NegStride); |
Chris Lattner | 8643810 | 2011-01-04 07:46:33 +0000 | [diff] [blame] | 649 | } |
| 650 | |
Chandler Carruth | 099f5cb0 | 2012-11-02 08:33:25 +0000 | [diff] [blame] | 651 | /// mayLoopAccessLocation - Return true if the specified loop might access the |
| 652 | /// specified pointer location, which is a loop-strided access. The 'Access' |
| 653 | /// argument specifies what the verboten forms of access are (read or write). |
Haicheng Wu | f1c00a2 | 2016-01-26 02:27:47 +0000 | [diff] [blame] | 654 | static bool |
| 655 | mayLoopAccessLocation(Value *Ptr, ModRefInfo Access, Loop *L, |
| 656 | const SCEV *BECount, unsigned StoreSize, |
| 657 | AliasAnalysis &AA, |
| 658 | SmallPtrSetImpl<Instruction *> &IgnoredStores) { |
Chandler Carruth | 099f5cb0 | 2012-11-02 08:33:25 +0000 | [diff] [blame] | 659 | // Get the location that may be stored across the loop. Since the access is |
| 660 | // strided positively through memory, we say that the modified location starts |
| 661 | // at the pointer and has infinite size. |
Chandler Carruth | ecbd168 | 2015-06-17 07:21:38 +0000 | [diff] [blame] | 662 | uint64_t AccessSize = MemoryLocation::UnknownSize; |
Chandler Carruth | 099f5cb0 | 2012-11-02 08:33:25 +0000 | [diff] [blame] | 663 | |
| 664 | // If the loop iterates a fixed number of times, we can refine the access size |
| 665 | // to be exactly the size of the memset, which is (BECount+1)*StoreSize |
| 666 | if (const SCEVConstant *BECst = dyn_cast<SCEVConstant>(BECount)) |
Chandler Carruth | bad690e | 2015-08-12 23:06:37 +0000 | [diff] [blame] | 667 | AccessSize = (BECst->getValue()->getZExtValue() + 1) * StoreSize; |
Chandler Carruth | 099f5cb0 | 2012-11-02 08:33:25 +0000 | [diff] [blame] | 668 | |
| 669 | // TODO: For this to be really effective, we have to dive into the pointer |
| 670 | // operand in the store. Store to &A[i] of 100 will always return may alias |
| 671 | // with store of &A[100], we need to StoreLoc to be "A" with size of 100, |
| 672 | // which will then no-alias a store to &A[100]. |
Chandler Carruth | ac80dc7 | 2015-06-17 07:18:54 +0000 | [diff] [blame] | 673 | MemoryLocation StoreLoc(Ptr, AccessSize); |
Chandler Carruth | 099f5cb0 | 2012-11-02 08:33:25 +0000 | [diff] [blame] | 674 | |
| 675 | for (Loop::block_iterator BI = L->block_begin(), E = L->block_end(); BI != E; |
| 676 | ++BI) |
Benjamin Kramer | 135f735 | 2016-06-26 12:28:59 +0000 | [diff] [blame] | 677 | for (Instruction &I : **BI) |
| 678 | if (IgnoredStores.count(&I) == 0 && |
| 679 | (AA.getModRefInfo(&I, StoreLoc) & Access)) |
Chandler Carruth | 099f5cb0 | 2012-11-02 08:33:25 +0000 | [diff] [blame] | 680 | return true; |
| 681 | |
| 682 | return false; |
| 683 | } |
| 684 | |
Chad Rosier | ed0c7d1 | 2015-11-13 19:11:07 +0000 | [diff] [blame] | 685 | // If we have a negative stride, Start refers to the end of the memory location |
| 686 | // we're trying to memset. Therefore, we need to recompute the base pointer, |
| 687 | // which is just Start - BECount*Size. |
| 688 | static const SCEV *getStartForNegStride(const SCEV *Start, const SCEV *BECount, |
| 689 | Type *IntPtr, unsigned StoreSize, |
| 690 | ScalarEvolution *SE) { |
| 691 | const SCEV *Index = SE->getTruncateOrZeroExtend(BECount, IntPtr); |
| 692 | if (StoreSize != 1) |
| 693 | Index = SE->getMulExpr(Index, SE->getConstant(IntPtr, StoreSize), |
| 694 | SCEV::FlagNUW); |
| 695 | return SE->getMinusSCEV(Start, Index); |
| 696 | } |
| 697 | |
Chris Lattner | 0f4a640 | 2011-02-19 19:31:39 +0000 | [diff] [blame] | 698 | /// processLoopStridedStore - We see a strided store of some value. If we can |
| 699 | /// transform this into a memset or memset_pattern in the loop preheader, do so. |
Chandler Carruth | bad690e | 2015-08-12 23:06:37 +0000 | [diff] [blame] | 700 | bool LoopIdiomRecognize::processLoopStridedStore( |
| 701 | Value *DestPtr, unsigned StoreSize, unsigned StoreAlignment, |
Haicheng Wu | f1c00a2 | 2016-01-26 02:27:47 +0000 | [diff] [blame] | 702 | Value *StoredVal, Instruction *TheStore, |
| 703 | SmallPtrSetImpl<Instruction *> &Stores, const SCEVAddRecExpr *Ev, |
Chad Rosier | 7967614 | 2015-10-28 14:38:49 +0000 | [diff] [blame] | 704 | const SCEV *BECount, bool NegStride) { |
Chris Lattner | 0f4a640 | 2011-02-19 19:31:39 +0000 | [diff] [blame] | 705 | Value *SplatValue = isBytewiseValue(StoredVal); |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 706 | Constant *PatternValue = nullptr; |
Matt Arsenault | 009faed | 2013-09-11 05:09:42 +0000 | [diff] [blame] | 707 | |
Haicheng Wu | 9d6c940 | 2016-01-04 21:43:14 +0000 | [diff] [blame] | 708 | if (!SplatValue) |
| 709 | PatternValue = getMemSetPatternValue(StoredVal, DL); |
| 710 | |
| 711 | assert((SplatValue || PatternValue) && |
| 712 | "Expected either splat value or pattern value."); |
Andrew Trick | 328b223 | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 713 | |
Chris Lattner | c4ca7ab | 2011-05-22 17:39:56 +0000 | [diff] [blame] | 714 | // The trip count of the loop and the base pointer of the addrec SCEV is |
| 715 | // guaranteed to be loop invariant, which means that it should dominate the |
| 716 | // header. This allows us to insert code for it in the preheader. |
Haicheng Wu | 9d6c940 | 2016-01-04 21:43:14 +0000 | [diff] [blame] | 717 | unsigned DestAS = DestPtr->getType()->getPointerAddressSpace(); |
Chris Lattner | c4ca7ab | 2011-05-22 17:39:56 +0000 | [diff] [blame] | 718 | BasicBlock *Preheader = CurLoop->getLoopPreheader(); |
| 719 | IRBuilder<> Builder(Preheader->getTerminator()); |
Chad Rosier | 43f9b48 | 2015-11-06 16:33:57 +0000 | [diff] [blame] | 720 | SCEVExpander Expander(*SE, *DL, "loop-idiom"); |
Andrew Trick | 60ab3ef | 2011-06-28 05:04:16 +0000 | [diff] [blame] | 721 | |
Matt Arsenault | 009faed | 2013-09-11 05:09:42 +0000 | [diff] [blame] | 722 | Type *DestInt8PtrTy = Builder.getInt8PtrTy(DestAS); |
Chad Rosier | 43f9b48 | 2015-11-06 16:33:57 +0000 | [diff] [blame] | 723 | Type *IntPtr = Builder.getIntPtrTy(*DL, DestAS); |
Chad Rosier | 7967614 | 2015-10-28 14:38:49 +0000 | [diff] [blame] | 724 | |
| 725 | const SCEV *Start = Ev->getStart(); |
Chad Rosier | 2fa50a7 | 2015-11-13 19:13:40 +0000 | [diff] [blame] | 726 | // Handle negative strided loops. |
Chad Rosier | ed0c7d1 | 2015-11-13 19:11:07 +0000 | [diff] [blame] | 727 | if (NegStride) |
| 728 | Start = getStartForNegStride(Start, BECount, IntPtr, StoreSize, SE); |
Matt Arsenault | 009faed | 2013-09-11 05:09:42 +0000 | [diff] [blame] | 729 | |
Chris Lattner | 29e14ed | 2010-12-26 23:42:51 +0000 | [diff] [blame] | 730 | // Okay, we have a strided store "p[i]" of a splattable value. We can turn |
Benjamin Kramer | f77f224 | 2012-10-21 19:31:16 +0000 | [diff] [blame] | 731 | // this into a memset in the loop preheader now if we want. However, this |
| 732 | // would be unsafe to do if there is anything else in the loop that may read |
Chandler Carruth | 7ec5085 | 2012-11-01 08:07:29 +0000 | [diff] [blame] | 733 | // or write to the aliased location. Check for any overlap by generating the |
| 734 | // base pointer and checking the region. |
Chad Rosier | 7967614 | 2015-10-28 14:38:49 +0000 | [diff] [blame] | 735 | Value *BasePtr = |
| 736 | Expander.expandCodeFor(Start, DestInt8PtrTy, Preheader->getTerminator()); |
Chandler Carruth | 194f59c | 2015-07-22 23:15:57 +0000 | [diff] [blame] | 737 | if (mayLoopAccessLocation(BasePtr, MRI_ModRef, CurLoop, BECount, StoreSize, |
Haicheng Wu | f1c00a2 | 2016-01-26 02:27:47 +0000 | [diff] [blame] | 738 | *AA, Stores)) { |
Chandler Carruth | 099f5cb0 | 2012-11-02 08:33:25 +0000 | [diff] [blame] | 739 | Expander.clear(); |
| 740 | // If we generated new code for the base pointer, clean up. |
Benjamin Kramer | f094d77 | 2015-02-07 21:37:08 +0000 | [diff] [blame] | 741 | RecursivelyDeleteTriviallyDeadInstructions(BasePtr, TLI); |
Chandler Carruth | 099f5cb0 | 2012-11-02 08:33:25 +0000 | [diff] [blame] | 742 | return false; |
| 743 | } |
| 744 | |
Chris Lattner | c4ca7ab | 2011-05-22 17:39:56 +0000 | [diff] [blame] | 745 | // Okay, everything looks good, insert the memset. |
| 746 | |
Chris Lattner | 29e14ed | 2010-12-26 23:42:51 +0000 | [diff] [blame] | 747 | // The # stored bytes is (BECount+1)*Size. Expand the trip count out to |
| 748 | // pointer size if it isn't already. |
Chris Lattner | 0ba473c | 2011-01-04 00:06:55 +0000 | [diff] [blame] | 749 | BECount = SE->getTruncateOrZeroExtend(BECount, IntPtr); |
Andrew Trick | 328b223 | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 750 | |
Chandler Carruth | bad690e | 2015-08-12 23:06:37 +0000 | [diff] [blame] | 751 | const SCEV *NumBytesS = |
Sanjoy Das | 2aacc0e | 2015-09-23 01:59:04 +0000 | [diff] [blame] | 752 | SE->getAddExpr(BECount, SE->getOne(IntPtr), SCEV::FlagNUW); |
Matt Arsenault | 5df49bd | 2013-09-11 05:09:35 +0000 | [diff] [blame] | 753 | if (StoreSize != 1) { |
Chris Lattner | 29e14ed | 2010-12-26 23:42:51 +0000 | [diff] [blame] | 754 | NumBytesS = SE->getMulExpr(NumBytesS, SE->getConstant(IntPtr, StoreSize), |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 755 | SCEV::FlagNUW); |
Matt Arsenault | 5df49bd | 2013-09-11 05:09:35 +0000 | [diff] [blame] | 756 | } |
Andrew Trick | 328b223 | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 757 | |
| 758 | Value *NumBytes = |
Chandler Carruth | bad690e | 2015-08-12 23:06:37 +0000 | [diff] [blame] | 759 | Expander.expandCodeFor(NumBytesS, IntPtr, Preheader->getTerminator()); |
Andrew Trick | 328b223 | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 760 | |
Devang Patel | d00c628 | 2011-03-07 22:43:45 +0000 | [diff] [blame] | 761 | CallInst *NewCall; |
Matt Arsenault | 5df49bd | 2013-09-11 05:09:35 +0000 | [diff] [blame] | 762 | if (SplatValue) { |
Chandler Carruth | bad690e | 2015-08-12 23:06:37 +0000 | [diff] [blame] | 763 | NewCall = |
| 764 | Builder.CreateMemSet(BasePtr, SplatValue, NumBytes, StoreAlignment); |
Matt Arsenault | 5df49bd | 2013-09-11 05:09:35 +0000 | [diff] [blame] | 765 | } else { |
Matt Arsenault | 009faed | 2013-09-11 05:09:42 +0000 | [diff] [blame] | 766 | // Everything is emitted in default address space |
| 767 | Type *Int8PtrTy = DestInt8PtrTy; |
| 768 | |
Sanjay Patel | af674fb | 2015-12-14 17:24:23 +0000 | [diff] [blame] | 769 | Module *M = TheStore->getModule(); |
Chandler Carruth | bad690e | 2015-08-12 23:06:37 +0000 | [diff] [blame] | 770 | Value *MSP = |
| 771 | M->getOrInsertFunction("memset_pattern16", Builder.getVoidTy(), |
| 772 | Int8PtrTy, Int8PtrTy, IntPtr, (void *)nullptr); |
Ahmed Bougacha | ace97c1 | 2016-04-27 19:04:50 +0000 | [diff] [blame] | 773 | inferLibFuncAttributes(*M->getFunction("memset_pattern16"), *TLI); |
Andrew Trick | 328b223 | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 774 | |
Chris Lattner | 0f4a640 | 2011-02-19 19:31:39 +0000 | [diff] [blame] | 775 | // Otherwise we should form a memset_pattern16. PatternValue is known to be |
| 776 | // an constant array of 16-bytes. Plop the value into a mergable global. |
| 777 | GlobalVariable *GV = new GlobalVariable(*M, PatternValue->getType(), true, |
Benjamin Kramer | 838752d | 2015-03-03 00:17:09 +0000 | [diff] [blame] | 778 | GlobalValue::PrivateLinkage, |
Chris Lattner | 0f4a640 | 2011-02-19 19:31:39 +0000 | [diff] [blame] | 779 | PatternValue, ".memset_pattern"); |
Peter Collingbourne | 96efdd6 | 2016-06-14 21:01:22 +0000 | [diff] [blame] | 780 | GV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global); // Ok to merge these. |
Chris Lattner | 0f4a640 | 2011-02-19 19:31:39 +0000 | [diff] [blame] | 781 | GV->setAlignment(16); |
Matt Arsenault | 009faed | 2013-09-11 05:09:42 +0000 | [diff] [blame] | 782 | Value *PatternPtr = ConstantExpr::getBitCast(GV, Int8PtrTy); |
David Blaikie | ff6409d | 2015-05-18 22:13:54 +0000 | [diff] [blame] | 783 | NewCall = Builder.CreateCall(MSP, {BasePtr, PatternPtr, NumBytes}); |
Chris Lattner | 0f4a640 | 2011-02-19 19:31:39 +0000 | [diff] [blame] | 784 | } |
Andrew Trick | 328b223 | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 785 | |
Chris Lattner | 29e14ed | 2010-12-26 23:42:51 +0000 | [diff] [blame] | 786 | DEBUG(dbgs() << " Formed memset: " << *NewCall << "\n" |
Chris Lattner | 8643810 | 2011-01-04 07:46:33 +0000 | [diff] [blame] | 787 | << " from store to: " << *Ev << " at: " << *TheStore << "\n"); |
Devang Patel | d00c628 | 2011-03-07 22:43:45 +0000 | [diff] [blame] | 788 | NewCall->setDebugLoc(TheStore->getDebugLoc()); |
Andrew Trick | 328b223 | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 789 | |
Chris Lattner | b9fe685 | 2010-12-27 00:03:23 +0000 | [diff] [blame] | 790 | // Okay, the memset has been formed. Zap the original store and anything that |
| 791 | // feeds into it. |
Haicheng Wu | f1c00a2 | 2016-01-26 02:27:47 +0000 | [diff] [blame] | 792 | for (auto *I : Stores) |
David Majnemer | 41ff4fd | 2016-06-20 16:07:38 +0000 | [diff] [blame] | 793 | deleteDeadInstruction(I); |
Chris Lattner | 12f91be | 2011-01-02 07:36:44 +0000 | [diff] [blame] | 794 | ++NumMemSet; |
Chris Lattner | 29e14ed | 2010-12-26 23:42:51 +0000 | [diff] [blame] | 795 | return true; |
| 796 | } |
| 797 | |
Chad Rosier | 1cd3da1 | 2015-11-19 21:33:07 +0000 | [diff] [blame] | 798 | /// If the stored value is a strided load in the same loop with the same stride |
| 799 | /// this may be transformable into a memcpy. This kicks in for stuff like |
| 800 | /// for (i) A[i] = B[i]; |
Haicheng Wu | 9d6c940 | 2016-01-04 21:43:14 +0000 | [diff] [blame] | 801 | bool LoopIdiomRecognize::processLoopStoreOfLoopLoad(StoreInst *SI, |
| 802 | const SCEV *BECount) { |
| 803 | assert(SI->isSimple() && "Expected only non-volatile stores."); |
| 804 | |
| 805 | Value *StorePtr = SI->getPointerOperand(); |
| 806 | const SCEVAddRecExpr *StoreEv = cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr)); |
Chad Rosier | 4acff96 | 2016-02-12 19:05:27 +0000 | [diff] [blame] | 807 | APInt Stride = getStoreStride(StoreEv); |
Haicheng Wu | 9d6c940 | 2016-01-04 21:43:14 +0000 | [diff] [blame] | 808 | unsigned StoreSize = getStoreSizeInBytes(SI, DL); |
| 809 | bool NegStride = StoreSize == -Stride; |
Andrew Trick | 328b223 | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 810 | |
Chad Rosier | fddc01f | 2015-11-19 18:22:21 +0000 | [diff] [blame] | 811 | // The store must be feeding a non-volatile load. |
Haicheng Wu | 9d6c940 | 2016-01-04 21:43:14 +0000 | [diff] [blame] | 812 | LoadInst *LI = cast<LoadInst>(SI->getValueOperand()); |
| 813 | assert(LI->isSimple() && "Expected only non-volatile stores."); |
Chad Rosier | fddc01f | 2015-11-19 18:22:21 +0000 | [diff] [blame] | 814 | |
| 815 | // See if the pointer expression is an AddRec like {base,+,1} on the current |
| 816 | // loop, which indicates a strided load. If we have something else, it's a |
| 817 | // random load we can't handle. |
Chad Rosier | 3ecc8d8 | 2015-11-19 18:25:11 +0000 | [diff] [blame] | 818 | const SCEVAddRecExpr *LoadEv = |
Haicheng Wu | 9d6c940 | 2016-01-04 21:43:14 +0000 | [diff] [blame] | 819 | cast<SCEVAddRecExpr>(SE->getSCEV(LI->getPointerOperand())); |
Andrew Trick | 328b223 | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 820 | |
Chris Lattner | c4ca7ab | 2011-05-22 17:39:56 +0000 | [diff] [blame] | 821 | // The trip count of the loop and the base pointer of the addrec SCEV is |
| 822 | // guaranteed to be loop invariant, which means that it should dominate the |
| 823 | // header. This allows us to insert code for it in the preheader. |
| 824 | BasicBlock *Preheader = CurLoop->getLoopPreheader(); |
| 825 | IRBuilder<> Builder(Preheader->getTerminator()); |
Chad Rosier | 43f9b48 | 2015-11-06 16:33:57 +0000 | [diff] [blame] | 826 | SCEVExpander Expander(*SE, *DL, "loop-idiom"); |
Andrew Trick | 60ab3ef | 2011-06-28 05:04:16 +0000 | [diff] [blame] | 827 | |
Chad Rosier | cc299b6 | 2015-11-13 21:51:02 +0000 | [diff] [blame] | 828 | const SCEV *StrStart = StoreEv->getStart(); |
| 829 | unsigned StrAS = SI->getPointerAddressSpace(); |
| 830 | Type *IntPtrTy = Builder.getIntPtrTy(*DL, StrAS); |
| 831 | |
| 832 | // Handle negative strided loops. |
| 833 | if (NegStride) |
| 834 | StrStart = getStartForNegStride(StrStart, BECount, IntPtrTy, StoreSize, SE); |
| 835 | |
Chris Lattner | 85b6d81 | 2011-01-02 03:37:56 +0000 | [diff] [blame] | 836 | // Okay, we have a strided store "p[i]" of a loaded value. We can turn |
Chandler Carruth | 099f5cb0 | 2012-11-02 08:33:25 +0000 | [diff] [blame] | 837 | // this into a memcpy in the loop preheader now if we want. However, this |
| 838 | // would be unsafe to do if there is anything else in the loop that may read |
| 839 | // or write the memory region we're storing to. This includes the load that |
| 840 | // feeds the stores. Check for an alias by generating the base address and |
| 841 | // checking everything. |
Chandler Carruth | bad690e | 2015-08-12 23:06:37 +0000 | [diff] [blame] | 842 | Value *StoreBasePtr = Expander.expandCodeFor( |
Chad Rosier | cc299b6 | 2015-11-13 21:51:02 +0000 | [diff] [blame] | 843 | StrStart, Builder.getInt8PtrTy(StrAS), Preheader->getTerminator()); |
Chandler Carruth | 099f5cb0 | 2012-11-02 08:33:25 +0000 | [diff] [blame] | 844 | |
Haicheng Wu | f1c00a2 | 2016-01-26 02:27:47 +0000 | [diff] [blame] | 845 | SmallPtrSet<Instruction *, 1> Stores; |
| 846 | Stores.insert(SI); |
Chandler Carruth | 194f59c | 2015-07-22 23:15:57 +0000 | [diff] [blame] | 847 | if (mayLoopAccessLocation(StoreBasePtr, MRI_ModRef, CurLoop, BECount, |
Haicheng Wu | f1c00a2 | 2016-01-26 02:27:47 +0000 | [diff] [blame] | 848 | StoreSize, *AA, Stores)) { |
Chandler Carruth | 099f5cb0 | 2012-11-02 08:33:25 +0000 | [diff] [blame] | 849 | Expander.clear(); |
| 850 | // If we generated new code for the base pointer, clean up. |
Benjamin Kramer | f094d77 | 2015-02-07 21:37:08 +0000 | [diff] [blame] | 851 | RecursivelyDeleteTriviallyDeadInstructions(StoreBasePtr, TLI); |
Chandler Carruth | 099f5cb0 | 2012-11-02 08:33:25 +0000 | [diff] [blame] | 852 | return false; |
| 853 | } |
| 854 | |
Chad Rosier | cc299b6 | 2015-11-13 21:51:02 +0000 | [diff] [blame] | 855 | const SCEV *LdStart = LoadEv->getStart(); |
| 856 | unsigned LdAS = LI->getPointerAddressSpace(); |
| 857 | |
| 858 | // Handle negative strided loops. |
| 859 | if (NegStride) |
| 860 | LdStart = getStartForNegStride(LdStart, BECount, IntPtrTy, StoreSize, SE); |
| 861 | |
Chandler Carruth | 099f5cb0 | 2012-11-02 08:33:25 +0000 | [diff] [blame] | 862 | // For a memcpy, we have to make sure that the input array is not being |
| 863 | // mutated by the loop. |
Chandler Carruth | bad690e | 2015-08-12 23:06:37 +0000 | [diff] [blame] | 864 | Value *LoadBasePtr = Expander.expandCodeFor( |
Chad Rosier | cc299b6 | 2015-11-13 21:51:02 +0000 | [diff] [blame] | 865 | LdStart, Builder.getInt8PtrTy(LdAS), Preheader->getTerminator()); |
Chris Lattner | c4ca7ab | 2011-05-22 17:39:56 +0000 | [diff] [blame] | 866 | |
Chandler Carruth | 194f59c | 2015-07-22 23:15:57 +0000 | [diff] [blame] | 867 | if (mayLoopAccessLocation(LoadBasePtr, MRI_Mod, CurLoop, BECount, StoreSize, |
Haicheng Wu | f1c00a2 | 2016-01-26 02:27:47 +0000 | [diff] [blame] | 868 | *AA, Stores)) { |
Chandler Carruth | 099f5cb0 | 2012-11-02 08:33:25 +0000 | [diff] [blame] | 869 | Expander.clear(); |
| 870 | // If we generated new code for the base pointer, clean up. |
Benjamin Kramer | f094d77 | 2015-02-07 21:37:08 +0000 | [diff] [blame] | 871 | RecursivelyDeleteTriviallyDeadInstructions(LoadBasePtr, TLI); |
| 872 | RecursivelyDeleteTriviallyDeadInstructions(StoreBasePtr, TLI); |
Chandler Carruth | 099f5cb0 | 2012-11-02 08:33:25 +0000 | [diff] [blame] | 873 | return false; |
| 874 | } |
| 875 | |
Chris Lattner | c4ca7ab | 2011-05-22 17:39:56 +0000 | [diff] [blame] | 876 | // Okay, everything is safe, we can transform this! |
Andrew Trick | 60ab3ef | 2011-06-28 05:04:16 +0000 | [diff] [blame] | 877 | |
Chris Lattner | 85b6d81 | 2011-01-02 03:37:56 +0000 | [diff] [blame] | 878 | // The # stored bytes is (BECount+1)*Size. Expand the trip count out to |
| 879 | // pointer size if it isn't already. |
Matt Arsenault | 009faed | 2013-09-11 05:09:42 +0000 | [diff] [blame] | 880 | BECount = SE->getTruncateOrZeroExtend(BECount, IntPtrTy); |
Andrew Trick | 328b223 | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 881 | |
Chandler Carruth | bad690e | 2015-08-12 23:06:37 +0000 | [diff] [blame] | 882 | const SCEV *NumBytesS = |
Sanjoy Das | 2aacc0e | 2015-09-23 01:59:04 +0000 | [diff] [blame] | 883 | SE->getAddExpr(BECount, SE->getOne(IntPtrTy), SCEV::FlagNUW); |
Chris Lattner | 85b6d81 | 2011-01-02 03:37:56 +0000 | [diff] [blame] | 884 | if (StoreSize != 1) |
Matt Arsenault | 009faed | 2013-09-11 05:09:42 +0000 | [diff] [blame] | 885 | NumBytesS = SE->getMulExpr(NumBytesS, SE->getConstant(IntPtrTy, StoreSize), |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 886 | SCEV::FlagNUW); |
Andrew Trick | 328b223 | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 887 | |
Chris Lattner | 85b6d81 | 2011-01-02 03:37:56 +0000 | [diff] [blame] | 888 | Value *NumBytes = |
Chandler Carruth | bad690e | 2015-08-12 23:06:37 +0000 | [diff] [blame] | 889 | Expander.expandCodeFor(NumBytesS, IntPtrTy, Preheader->getTerminator()); |
Andrew Trick | 328b223 | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 890 | |
Chandler Carruth | 099f5cb0 | 2012-11-02 08:33:25 +0000 | [diff] [blame] | 891 | CallInst *NewCall = |
Chandler Carruth | bad690e | 2015-08-12 23:06:37 +0000 | [diff] [blame] | 892 | Builder.CreateMemCpy(StoreBasePtr, LoadBasePtr, NumBytes, |
Pete Cooper | 67cf9a7 | 2015-11-19 05:56:52 +0000 | [diff] [blame] | 893 | std::min(SI->getAlignment(), LI->getAlignment())); |
Devang Patel | 0daa07e | 2011-05-04 21:37:05 +0000 | [diff] [blame] | 894 | NewCall->setDebugLoc(SI->getDebugLoc()); |
Andrew Trick | 328b223 | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 895 | |
Chandler Carruth | 099f5cb0 | 2012-11-02 08:33:25 +0000 | [diff] [blame] | 896 | DEBUG(dbgs() << " Formed memcpy: " << *NewCall << "\n" |
Chris Lattner | 85b6d81 | 2011-01-02 03:37:56 +0000 | [diff] [blame] | 897 | << " from load ptr=" << *LoadEv << " at: " << *LI << "\n" |
| 898 | << " from store ptr=" << *StoreEv << " at: " << *SI << "\n"); |
Andrew Trick | 60ab3ef | 2011-06-28 05:04:16 +0000 | [diff] [blame] | 899 | |
Chad Rosier | 7f08d80 | 2015-10-13 20:59:16 +0000 | [diff] [blame] | 900 | // Okay, the memcpy has been formed. Zap the original store and anything that |
Chris Lattner | 85b6d81 | 2011-01-02 03:37:56 +0000 | [diff] [blame] | 901 | // feeds into it. |
David Majnemer | 41ff4fd | 2016-06-20 16:07:38 +0000 | [diff] [blame] | 902 | deleteDeadInstruction(SI); |
Chandler Carruth | 099f5cb0 | 2012-11-02 08:33:25 +0000 | [diff] [blame] | 903 | ++NumMemCpy; |
Chris Lattner | 85b6d81 | 2011-01-02 03:37:56 +0000 | [diff] [blame] | 904 | return true; |
| 905 | } |
Chandler Carruth | d9c6070 | 2015-08-13 00:10:03 +0000 | [diff] [blame] | 906 | |
| 907 | bool LoopIdiomRecognize::runOnNoncountableLoop() { |
Chad Rosier | 19dc92d | 2015-11-09 16:56:06 +0000 | [diff] [blame] | 908 | return recognizePopcount(); |
Chandler Carruth | d9c6070 | 2015-08-13 00:10:03 +0000 | [diff] [blame] | 909 | } |
Chandler Carruth | 8219a50 | 2015-08-13 00:44:29 +0000 | [diff] [blame] | 910 | |
| 911 | /// Check if the given conditional branch is based on the comparison between |
| 912 | /// a variable and zero, and if the variable is non-zero, the control yields to |
| 913 | /// the loop entry. If the branch matches the behavior, the variable involved |
| 914 | /// in the comparion is returned. This function will be called to see if the |
| 915 | /// precondition and postcondition of the loop are in desirable form. |
| 916 | static Value *matchCondition(BranchInst *BI, BasicBlock *LoopEntry) { |
| 917 | if (!BI || !BI->isConditional()) |
| 918 | return nullptr; |
| 919 | |
| 920 | ICmpInst *Cond = dyn_cast<ICmpInst>(BI->getCondition()); |
| 921 | if (!Cond) |
| 922 | return nullptr; |
| 923 | |
| 924 | ConstantInt *CmpZero = dyn_cast<ConstantInt>(Cond->getOperand(1)); |
| 925 | if (!CmpZero || !CmpZero->isZero()) |
| 926 | return nullptr; |
| 927 | |
| 928 | ICmpInst::Predicate Pred = Cond->getPredicate(); |
| 929 | if ((Pred == ICmpInst::ICMP_NE && BI->getSuccessor(0) == LoopEntry) || |
| 930 | (Pred == ICmpInst::ICMP_EQ && BI->getSuccessor(1) == LoopEntry)) |
| 931 | return Cond->getOperand(0); |
| 932 | |
| 933 | return nullptr; |
| 934 | } |
| 935 | |
| 936 | /// Return true iff the idiom is detected in the loop. |
| 937 | /// |
| 938 | /// Additionally: |
| 939 | /// 1) \p CntInst is set to the instruction counting the population bit. |
| 940 | /// 2) \p CntPhi is set to the corresponding phi node. |
| 941 | /// 3) \p Var is set to the value whose population bits are being counted. |
| 942 | /// |
| 943 | /// The core idiom we are trying to detect is: |
| 944 | /// \code |
| 945 | /// if (x0 != 0) |
| 946 | /// goto loop-exit // the precondition of the loop |
| 947 | /// cnt0 = init-val; |
| 948 | /// do { |
| 949 | /// x1 = phi (x0, x2); |
| 950 | /// cnt1 = phi(cnt0, cnt2); |
| 951 | /// |
| 952 | /// cnt2 = cnt1 + 1; |
| 953 | /// ... |
| 954 | /// x2 = x1 & (x1 - 1); |
| 955 | /// ... |
| 956 | /// } while(x != 0); |
| 957 | /// |
| 958 | /// loop-exit: |
| 959 | /// \endcode |
| 960 | static bool detectPopcountIdiom(Loop *CurLoop, BasicBlock *PreCondBB, |
| 961 | Instruction *&CntInst, PHINode *&CntPhi, |
| 962 | Value *&Var) { |
| 963 | // step 1: Check to see if the look-back branch match this pattern: |
| 964 | // "if (a!=0) goto loop-entry". |
| 965 | BasicBlock *LoopEntry; |
| 966 | Instruction *DefX2, *CountInst; |
| 967 | Value *VarX1, *VarX0; |
| 968 | PHINode *PhiX, *CountPhi; |
| 969 | |
| 970 | DefX2 = CountInst = nullptr; |
| 971 | VarX1 = VarX0 = nullptr; |
| 972 | PhiX = CountPhi = nullptr; |
| 973 | LoopEntry = *(CurLoop->block_begin()); |
| 974 | |
| 975 | // step 1: Check if the loop-back branch is in desirable form. |
| 976 | { |
| 977 | if (Value *T = matchCondition( |
| 978 | dyn_cast<BranchInst>(LoopEntry->getTerminator()), LoopEntry)) |
| 979 | DefX2 = dyn_cast<Instruction>(T); |
| 980 | else |
| 981 | return false; |
| 982 | } |
| 983 | |
| 984 | // step 2: detect instructions corresponding to "x2 = x1 & (x1 - 1)" |
| 985 | { |
| 986 | if (!DefX2 || DefX2->getOpcode() != Instruction::And) |
| 987 | return false; |
| 988 | |
| 989 | BinaryOperator *SubOneOp; |
| 990 | |
| 991 | if ((SubOneOp = dyn_cast<BinaryOperator>(DefX2->getOperand(0)))) |
| 992 | VarX1 = DefX2->getOperand(1); |
| 993 | else { |
| 994 | VarX1 = DefX2->getOperand(0); |
| 995 | SubOneOp = dyn_cast<BinaryOperator>(DefX2->getOperand(1)); |
| 996 | } |
| 997 | if (!SubOneOp) |
| 998 | return false; |
| 999 | |
| 1000 | Instruction *SubInst = cast<Instruction>(SubOneOp); |
| 1001 | ConstantInt *Dec = dyn_cast<ConstantInt>(SubInst->getOperand(1)); |
| 1002 | if (!Dec || |
| 1003 | !((SubInst->getOpcode() == Instruction::Sub && Dec->isOne()) || |
| 1004 | (SubInst->getOpcode() == Instruction::Add && |
| 1005 | Dec->isAllOnesValue()))) { |
| 1006 | return false; |
| 1007 | } |
| 1008 | } |
| 1009 | |
| 1010 | // step 3: Check the recurrence of variable X |
| 1011 | { |
| 1012 | PhiX = dyn_cast<PHINode>(VarX1); |
| 1013 | if (!PhiX || |
| 1014 | (PhiX->getOperand(0) != DefX2 && PhiX->getOperand(1) != DefX2)) { |
| 1015 | return false; |
| 1016 | } |
| 1017 | } |
| 1018 | |
| 1019 | // step 4: Find the instruction which count the population: cnt2 = cnt1 + 1 |
| 1020 | { |
| 1021 | CountInst = nullptr; |
Duncan P. N. Exon Smith | be4d8cb | 2015-10-13 19:26:58 +0000 | [diff] [blame] | 1022 | for (BasicBlock::iterator Iter = LoopEntry->getFirstNonPHI()->getIterator(), |
Chandler Carruth | 8219a50 | 2015-08-13 00:44:29 +0000 | [diff] [blame] | 1023 | IterE = LoopEntry->end(); |
| 1024 | Iter != IterE; Iter++) { |
Duncan P. N. Exon Smith | be4d8cb | 2015-10-13 19:26:58 +0000 | [diff] [blame] | 1025 | Instruction *Inst = &*Iter; |
Chandler Carruth | 8219a50 | 2015-08-13 00:44:29 +0000 | [diff] [blame] | 1026 | if (Inst->getOpcode() != Instruction::Add) |
| 1027 | continue; |
| 1028 | |
| 1029 | ConstantInt *Inc = dyn_cast<ConstantInt>(Inst->getOperand(1)); |
| 1030 | if (!Inc || !Inc->isOne()) |
| 1031 | continue; |
| 1032 | |
| 1033 | PHINode *Phi = dyn_cast<PHINode>(Inst->getOperand(0)); |
| 1034 | if (!Phi || Phi->getParent() != LoopEntry) |
| 1035 | continue; |
| 1036 | |
| 1037 | // Check if the result of the instruction is live of the loop. |
| 1038 | bool LiveOutLoop = false; |
| 1039 | for (User *U : Inst->users()) { |
| 1040 | if ((cast<Instruction>(U))->getParent() != LoopEntry) { |
| 1041 | LiveOutLoop = true; |
| 1042 | break; |
| 1043 | } |
| 1044 | } |
| 1045 | |
| 1046 | if (LiveOutLoop) { |
| 1047 | CountInst = Inst; |
| 1048 | CountPhi = Phi; |
| 1049 | break; |
| 1050 | } |
| 1051 | } |
| 1052 | |
| 1053 | if (!CountInst) |
| 1054 | return false; |
| 1055 | } |
| 1056 | |
| 1057 | // step 5: check if the precondition is in this form: |
| 1058 | // "if (x != 0) goto loop-head ; else goto somewhere-we-don't-care;" |
| 1059 | { |
| 1060 | auto *PreCondBr = dyn_cast<BranchInst>(PreCondBB->getTerminator()); |
| 1061 | Value *T = matchCondition(PreCondBr, CurLoop->getLoopPreheader()); |
| 1062 | if (T != PhiX->getOperand(0) && T != PhiX->getOperand(1)) |
| 1063 | return false; |
| 1064 | |
| 1065 | CntInst = CountInst; |
| 1066 | CntPhi = CountPhi; |
| 1067 | Var = T; |
| 1068 | } |
| 1069 | |
| 1070 | return true; |
| 1071 | } |
| 1072 | |
| 1073 | /// Recognizes a population count idiom in a non-countable loop. |
| 1074 | /// |
| 1075 | /// If detected, transforms the relevant code to issue the popcount intrinsic |
| 1076 | /// function call, and returns true; otherwise, returns false. |
| 1077 | bool LoopIdiomRecognize::recognizePopcount() { |
Chandler Carruth | 8219a50 | 2015-08-13 00:44:29 +0000 | [diff] [blame] | 1078 | if (TTI->getPopcntSupport(32) != TargetTransformInfo::PSK_FastHardware) |
| 1079 | return false; |
| 1080 | |
| 1081 | // Counting population are usually conducted by few arithmetic instructions. |
Nick Lewycky | 06b0ea2 | 2015-08-18 22:41:58 +0000 | [diff] [blame] | 1082 | // Such instructions can be easily "absorbed" by vacant slots in a |
Chandler Carruth | 8219a50 | 2015-08-13 00:44:29 +0000 | [diff] [blame] | 1083 | // non-compact loop. Therefore, recognizing popcount idiom only makes sense |
| 1084 | // in a compact loop. |
| 1085 | |
Renato Golin | 655348f | 2015-08-13 11:25:38 +0000 | [diff] [blame] | 1086 | // Give up if the loop has multiple blocks or multiple backedges. |
| 1087 | if (CurLoop->getNumBackEdges() != 1 || CurLoop->getNumBlocks() != 1) |
Chandler Carruth | 8219a50 | 2015-08-13 00:44:29 +0000 | [diff] [blame] | 1088 | return false; |
| 1089 | |
Renato Golin | 655348f | 2015-08-13 11:25:38 +0000 | [diff] [blame] | 1090 | BasicBlock *LoopBody = *(CurLoop->block_begin()); |
| 1091 | if (LoopBody->size() >= 20) { |
| 1092 | // The loop is too big, bail out. |
Chandler Carruth | 8219a50 | 2015-08-13 00:44:29 +0000 | [diff] [blame] | 1093 | return false; |
Renato Golin | 655348f | 2015-08-13 11:25:38 +0000 | [diff] [blame] | 1094 | } |
Chandler Carruth | 8219a50 | 2015-08-13 00:44:29 +0000 | [diff] [blame] | 1095 | |
| 1096 | // It should have a preheader containing nothing but an unconditional branch. |
Renato Golin | 655348f | 2015-08-13 11:25:38 +0000 | [diff] [blame] | 1097 | BasicBlock *PH = CurLoop->getLoopPreheader(); |
| 1098 | if (!PH) |
Chandler Carruth | 8219a50 | 2015-08-13 00:44:29 +0000 | [diff] [blame] | 1099 | return false; |
Renato Golin | 655348f | 2015-08-13 11:25:38 +0000 | [diff] [blame] | 1100 | if (&PH->front() != PH->getTerminator()) |
| 1101 | return false; |
| 1102 | auto *EntryBI = dyn_cast<BranchInst>(PH->getTerminator()); |
Chandler Carruth | 8219a50 | 2015-08-13 00:44:29 +0000 | [diff] [blame] | 1103 | if (!EntryBI || EntryBI->isConditional()) |
| 1104 | return false; |
| 1105 | |
| 1106 | // It should have a precondition block where the generated popcount instrinsic |
| 1107 | // function can be inserted. |
Renato Golin | 655348f | 2015-08-13 11:25:38 +0000 | [diff] [blame] | 1108 | auto *PreCondBB = PH->getSinglePredecessor(); |
Chandler Carruth | 8219a50 | 2015-08-13 00:44:29 +0000 | [diff] [blame] | 1109 | if (!PreCondBB) |
| 1110 | return false; |
| 1111 | auto *PreCondBI = dyn_cast<BranchInst>(PreCondBB->getTerminator()); |
| 1112 | if (!PreCondBI || PreCondBI->isUnconditional()) |
| 1113 | return false; |
| 1114 | |
| 1115 | Instruction *CntInst; |
| 1116 | PHINode *CntPhi; |
| 1117 | Value *Val; |
| 1118 | if (!detectPopcountIdiom(CurLoop, PreCondBB, CntInst, CntPhi, Val)) |
| 1119 | return false; |
| 1120 | |
| 1121 | transformLoopToPopcount(PreCondBB, CntInst, CntPhi, Val); |
| 1122 | return true; |
| 1123 | } |
| 1124 | |
| 1125 | static CallInst *createPopcntIntrinsic(IRBuilder<> &IRBuilder, Value *Val, |
Benjamin Kramer | bdc4956 | 2016-06-12 15:39:02 +0000 | [diff] [blame] | 1126 | const DebugLoc &DL) { |
Chandler Carruth | 8219a50 | 2015-08-13 00:44:29 +0000 | [diff] [blame] | 1127 | Value *Ops[] = {Val}; |
| 1128 | Type *Tys[] = {Val->getType()}; |
| 1129 | |
| 1130 | Module *M = IRBuilder.GetInsertBlock()->getParent()->getParent(); |
| 1131 | Value *Func = Intrinsic::getDeclaration(M, Intrinsic::ctpop, Tys); |
| 1132 | CallInst *CI = IRBuilder.CreateCall(Func, Ops); |
| 1133 | CI->setDebugLoc(DL); |
| 1134 | |
| 1135 | return CI; |
| 1136 | } |
| 1137 | |
| 1138 | void LoopIdiomRecognize::transformLoopToPopcount(BasicBlock *PreCondBB, |
| 1139 | Instruction *CntInst, |
| 1140 | PHINode *CntPhi, Value *Var) { |
| 1141 | BasicBlock *PreHead = CurLoop->getLoopPreheader(); |
| 1142 | auto *PreCondBr = dyn_cast<BranchInst>(PreCondBB->getTerminator()); |
| 1143 | const DebugLoc DL = CntInst->getDebugLoc(); |
| 1144 | |
| 1145 | // Assuming before transformation, the loop is following: |
| 1146 | // if (x) // the precondition |
| 1147 | // do { cnt++; x &= x - 1; } while(x); |
| 1148 | |
| 1149 | // Step 1: Insert the ctpop instruction at the end of the precondition block |
| 1150 | IRBuilder<> Builder(PreCondBr); |
| 1151 | Value *PopCnt, *PopCntZext, *NewCount, *TripCnt; |
| 1152 | { |
| 1153 | PopCnt = createPopcntIntrinsic(Builder, Var, DL); |
| 1154 | NewCount = PopCntZext = |
| 1155 | Builder.CreateZExtOrTrunc(PopCnt, cast<IntegerType>(CntPhi->getType())); |
| 1156 | |
| 1157 | if (NewCount != PopCnt) |
| 1158 | (cast<Instruction>(NewCount))->setDebugLoc(DL); |
| 1159 | |
| 1160 | // TripCnt is exactly the number of iterations the loop has |
| 1161 | TripCnt = NewCount; |
| 1162 | |
| 1163 | // If the population counter's initial value is not zero, insert Add Inst. |
| 1164 | Value *CntInitVal = CntPhi->getIncomingValueForBlock(PreHead); |
| 1165 | ConstantInt *InitConst = dyn_cast<ConstantInt>(CntInitVal); |
| 1166 | if (!InitConst || !InitConst->isZero()) { |
| 1167 | NewCount = Builder.CreateAdd(NewCount, CntInitVal); |
| 1168 | (cast<Instruction>(NewCount))->setDebugLoc(DL); |
| 1169 | } |
| 1170 | } |
| 1171 | |
Nick Lewycky | 2c85254 | 2015-08-19 06:22:33 +0000 | [diff] [blame] | 1172 | // Step 2: Replace the precondition from "if (x == 0) goto loop-exit" to |
Nick Lewycky | 1098e49 | 2015-08-19 06:25:30 +0000 | [diff] [blame] | 1173 | // "if (NewCount == 0) loop-exit". Without this change, the intrinsic |
Chandler Carruth | 8219a50 | 2015-08-13 00:44:29 +0000 | [diff] [blame] | 1174 | // function would be partial dead code, and downstream passes will drag |
| 1175 | // it back from the precondition block to the preheader. |
| 1176 | { |
| 1177 | ICmpInst *PreCond = cast<ICmpInst>(PreCondBr->getCondition()); |
| 1178 | |
| 1179 | Value *Opnd0 = PopCntZext; |
| 1180 | Value *Opnd1 = ConstantInt::get(PopCntZext->getType(), 0); |
| 1181 | if (PreCond->getOperand(0) != Var) |
| 1182 | std::swap(Opnd0, Opnd1); |
| 1183 | |
| 1184 | ICmpInst *NewPreCond = cast<ICmpInst>( |
| 1185 | Builder.CreateICmp(PreCond->getPredicate(), Opnd0, Opnd1)); |
| 1186 | PreCondBr->setCondition(NewPreCond); |
| 1187 | |
| 1188 | RecursivelyDeleteTriviallyDeadInstructions(PreCond, TLI); |
| 1189 | } |
| 1190 | |
| 1191 | // Step 3: Note that the population count is exactly the trip count of the |
Nick Lewycky | 1098e49 | 2015-08-19 06:25:30 +0000 | [diff] [blame] | 1192 | // loop in question, which enable us to to convert the loop from noncountable |
Chandler Carruth | 8219a50 | 2015-08-13 00:44:29 +0000 | [diff] [blame] | 1193 | // loop into a countable one. The benefit is twofold: |
| 1194 | // |
Nick Lewycky | 2c85254 | 2015-08-19 06:22:33 +0000 | [diff] [blame] | 1195 | // - If the loop only counts population, the entire loop becomes dead after |
| 1196 | // the transformation. It is a lot easier to prove a countable loop dead |
| 1197 | // than to prove a noncountable one. (In some C dialects, an infinite loop |
Chandler Carruth | 8219a50 | 2015-08-13 00:44:29 +0000 | [diff] [blame] | 1198 | // isn't dead even if it computes nothing useful. In general, DCE needs |
| 1199 | // to prove a noncountable loop finite before safely delete it.) |
| 1200 | // |
| 1201 | // - If the loop also performs something else, it remains alive. |
| 1202 | // Since it is transformed to countable form, it can be aggressively |
| 1203 | // optimized by some optimizations which are in general not applicable |
| 1204 | // to a noncountable loop. |
| 1205 | // |
| 1206 | // After this step, this loop (conceptually) would look like following: |
| 1207 | // newcnt = __builtin_ctpop(x); |
| 1208 | // t = newcnt; |
| 1209 | // if (x) |
| 1210 | // do { cnt++; x &= x-1; t--) } while (t > 0); |
| 1211 | BasicBlock *Body = *(CurLoop->block_begin()); |
| 1212 | { |
| 1213 | auto *LbBr = dyn_cast<BranchInst>(Body->getTerminator()); |
| 1214 | ICmpInst *LbCond = cast<ICmpInst>(LbBr->getCondition()); |
| 1215 | Type *Ty = TripCnt->getType(); |
| 1216 | |
Duncan P. N. Exon Smith | be4d8cb | 2015-10-13 19:26:58 +0000 | [diff] [blame] | 1217 | PHINode *TcPhi = PHINode::Create(Ty, 2, "tcphi", &Body->front()); |
Chandler Carruth | 8219a50 | 2015-08-13 00:44:29 +0000 | [diff] [blame] | 1218 | |
| 1219 | Builder.SetInsertPoint(LbCond); |
Chandler Carruth | 8219a50 | 2015-08-13 00:44:29 +0000 | [diff] [blame] | 1220 | Instruction *TcDec = cast<Instruction>( |
Nick Lewycky | 1098e49 | 2015-08-19 06:25:30 +0000 | [diff] [blame] | 1221 | Builder.CreateSub(TcPhi, ConstantInt::get(Ty, 1), |
| 1222 | "tcdec", false, true)); |
Chandler Carruth | 8219a50 | 2015-08-13 00:44:29 +0000 | [diff] [blame] | 1223 | |
| 1224 | TcPhi->addIncoming(TripCnt, PreHead); |
| 1225 | TcPhi->addIncoming(TcDec, Body); |
| 1226 | |
| 1227 | CmpInst::Predicate Pred = |
| 1228 | (LbBr->getSuccessor(0) == Body) ? CmpInst::ICMP_UGT : CmpInst::ICMP_SLE; |
| 1229 | LbCond->setPredicate(Pred); |
| 1230 | LbCond->setOperand(0, TcDec); |
Nick Lewycky | 2c85254 | 2015-08-19 06:22:33 +0000 | [diff] [blame] | 1231 | LbCond->setOperand(1, ConstantInt::get(Ty, 0)); |
Chandler Carruth | 8219a50 | 2015-08-13 00:44:29 +0000 | [diff] [blame] | 1232 | } |
| 1233 | |
| 1234 | // Step 4: All the references to the original population counter outside |
| 1235 | // the loop are replaced with the NewCount -- the value returned from |
| 1236 | // __builtin_ctpop(). |
| 1237 | CntInst->replaceUsesOutsideBlock(NewCount, Body); |
| 1238 | |
| 1239 | // step 5: Forget the "non-computable" trip-count SCEV associated with the |
| 1240 | // loop. The loop would otherwise not be deleted even if it becomes empty. |
| 1241 | SE->forgetLoop(CurLoop); |
| 1242 | } |