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