Eugene Zelenko | dd40f5e | 2017-10-16 21:34:24 +0000 | [diff] [blame] | 1 | //===- LoopIdiomRecognize.cpp - Loop idiom recognition --------------------===// |
Chris Lattner | 81ae3f2 | 2010-12-26 19:39:38 +0000 | [diff] [blame] | 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: |
Craig Topper | c9a6000 | 2018-12-26 21:59:48 +0000 | [diff] [blame^] | 29 | // ctpop |
Chris Lattner | 0469e01 | 2011-01-02 18:32:09 +0000 | [diff] [blame] | 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 | |
Eugene Zelenko | dd40f5e | 2017-10-16 21:34:24 +0000 | [diff] [blame] | 40 | #include "llvm/ADT/APInt.h" |
| 41 | #include "llvm/ADT/ArrayRef.h" |
| 42 | #include "llvm/ADT/DenseMap.h" |
Haicheng Wu | f1c00a2 | 2016-01-26 02:27:47 +0000 | [diff] [blame] | 43 | #include "llvm/ADT/MapVector.h" |
| 44 | #include "llvm/ADT/SetVector.h" |
Eugene Zelenko | dd40f5e | 2017-10-16 21:34:24 +0000 | [diff] [blame] | 45 | #include "llvm/ADT/SmallPtrSet.h" |
| 46 | #include "llvm/ADT/SmallVector.h" |
Chandler Carruth | aafe091 | 2012-06-29 12:38:19 +0000 | [diff] [blame] | 47 | #include "llvm/ADT/Statistic.h" |
Eugene Zelenko | dd40f5e | 2017-10-16 21:34:24 +0000 | [diff] [blame] | 48 | #include "llvm/ADT/StringRef.h" |
Chris Lattner | cb18bfa | 2010-12-27 18:39:08 +0000 | [diff] [blame] | 49 | #include "llvm/Analysis/AliasAnalysis.h" |
Haicheng Wu | f1c00a2 | 2016-01-26 02:27:47 +0000 | [diff] [blame] | 50 | #include "llvm/Analysis/LoopAccessAnalysis.h" |
Eugene Zelenko | dd40f5e | 2017-10-16 21:34:24 +0000 | [diff] [blame] | 51 | #include "llvm/Analysis/LoopInfo.h" |
Dehao Chen | b9f8e29 | 2016-07-12 18:45:51 +0000 | [diff] [blame] | 52 | #include "llvm/Analysis/LoopPass.h" |
Eugene Zelenko | dd40f5e | 2017-10-16 21:34:24 +0000 | [diff] [blame] | 53 | #include "llvm/Analysis/MemoryLocation.h" |
| 54 | #include "llvm/Analysis/ScalarEvolution.h" |
Chad Rosier | a15b4b6 | 2015-11-23 21:09:13 +0000 | [diff] [blame] | 55 | #include "llvm/Analysis/ScalarEvolutionExpander.h" |
Chandler Carruth | aafe091 | 2012-06-29 12:38:19 +0000 | [diff] [blame] | 56 | #include "llvm/Analysis/ScalarEvolutionExpressions.h" |
Benjamin Kramer | 799003b | 2015-03-23 19:32:43 +0000 | [diff] [blame] | 57 | #include "llvm/Analysis/TargetLibraryInfo.h" |
Chandler Carruth | d3e7355 | 2013-01-07 03:08:10 +0000 | [diff] [blame] | 58 | #include "llvm/Analysis/TargetTransformInfo.h" |
David Blaikie | 31b98d2 | 2018-06-04 21:23:21 +0000 | [diff] [blame] | 59 | #include "llvm/Transforms/Utils/Local.h" |
Chris Lattner | 7c5f9c3 | 2010-12-26 20:45:45 +0000 | [diff] [blame] | 60 | #include "llvm/Analysis/ValueTracking.h" |
Eugene Zelenko | dd40f5e | 2017-10-16 21:34:24 +0000 | [diff] [blame] | 61 | #include "llvm/IR/Attributes.h" |
| 62 | #include "llvm/IR/BasicBlock.h" |
| 63 | #include "llvm/IR/Constant.h" |
| 64 | #include "llvm/IR/Constants.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 65 | #include "llvm/IR/DataLayout.h" |
Eugene Zelenko | dd40f5e | 2017-10-16 21:34:24 +0000 | [diff] [blame] | 66 | #include "llvm/IR/DebugLoc.h" |
| 67 | #include "llvm/IR/DerivedTypes.h" |
Chandler Carruth | 5ad5f15 | 2014-01-13 09:26:24 +0000 | [diff] [blame] | 68 | #include "llvm/IR/Dominators.h" |
Eugene Zelenko | dd40f5e | 2017-10-16 21:34:24 +0000 | [diff] [blame] | 69 | #include "llvm/IR/GlobalValue.h" |
| 70 | #include "llvm/IR/GlobalVariable.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 71 | #include "llvm/IR/IRBuilder.h" |
Eugene Zelenko | dd40f5e | 2017-10-16 21:34:24 +0000 | [diff] [blame] | 72 | #include "llvm/IR/InstrTypes.h" |
| 73 | #include "llvm/IR/Instruction.h" |
| 74 | #include "llvm/IR/Instructions.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 75 | #include "llvm/IR/IntrinsicInst.h" |
Eugene Zelenko | dd40f5e | 2017-10-16 21:34:24 +0000 | [diff] [blame] | 76 | #include "llvm/IR/Intrinsics.h" |
| 77 | #include "llvm/IR/LLVMContext.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 78 | #include "llvm/IR/Module.h" |
Eugene Zelenko | dd40f5e | 2017-10-16 21:34:24 +0000 | [diff] [blame] | 79 | #include "llvm/IR/PassManager.h" |
| 80 | #include "llvm/IR/Type.h" |
| 81 | #include "llvm/IR/User.h" |
| 82 | #include "llvm/IR/Value.h" |
| 83 | #include "llvm/IR/ValueHandle.h" |
| 84 | #include "llvm/Pass.h" |
| 85 | #include "llvm/Support/Casting.h" |
| 86 | #include "llvm/Support/CommandLine.h" |
Chandler Carruth | aafe091 | 2012-06-29 12:38:19 +0000 | [diff] [blame] | 87 | #include "llvm/Support/Debug.h" |
| 88 | #include "llvm/Support/raw_ostream.h" |
Dehao Chen | b9f8e29 | 2016-07-12 18:45:51 +0000 | [diff] [blame] | 89 | #include "llvm/Transforms/Scalar.h" |
Xin Tong | 99c4e2f | 2018-04-08 13:19:53 +0000 | [diff] [blame] | 90 | #include "llvm/Transforms/Scalar/LoopIdiomRecognize.h" |
Ahmed Bougacha | ace97c1 | 2016-04-27 19:04:50 +0000 | [diff] [blame] | 91 | #include "llvm/Transforms/Utils/BuildLibCalls.h" |
Chandler Carruth | 31088a9 | 2016-02-19 10:45:18 +0000 | [diff] [blame] | 92 | #include "llvm/Transforms/Utils/LoopUtils.h" |
Eugene Zelenko | dd40f5e | 2017-10-16 21:34:24 +0000 | [diff] [blame] | 93 | #include <algorithm> |
| 94 | #include <cassert> |
| 95 | #include <cstdint> |
| 96 | #include <utility> |
| 97 | #include <vector> |
| 98 | |
Chris Lattner | 81ae3f2 | 2010-12-26 19:39:38 +0000 | [diff] [blame] | 99 | using namespace llvm; |
| 100 | |
Chandler Carruth | 964daaa | 2014-04-22 02:55:47 +0000 | [diff] [blame] | 101 | #define DEBUG_TYPE "loop-idiom" |
| 102 | |
Chandler Carruth | 099f5cb0 | 2012-11-02 08:33:25 +0000 | [diff] [blame] | 103 | STATISTIC(NumMemSet, "Number of memset's formed from loop stores"); |
| 104 | STATISTIC(NumMemCpy, "Number of memcpy's formed from loop load+stores"); |
Chris Lattner | 81ae3f2 | 2010-12-26 19:39:38 +0000 | [diff] [blame] | 105 | |
Andrew Kaylor | 7cdf01e | 2016-08-11 18:28:33 +0000 | [diff] [blame] | 106 | static cl::opt<bool> UseLIRCodeSizeHeurs( |
| 107 | "use-lir-code-size-heurs", |
| 108 | cl::desc("Use loop idiom recognition code size heuristics when compiling" |
| 109 | "with -Os/-Oz"), |
| 110 | cl::init(true), cl::Hidden); |
| 111 | |
Chris Lattner | 81ae3f2 | 2010-12-26 19:39:38 +0000 | [diff] [blame] | 112 | namespace { |
Shuxin Yang | 95de7c3 | 2012-12-09 03:12:46 +0000 | [diff] [blame] | 113 | |
Dehao Chen | b9f8e29 | 2016-07-12 18:45:51 +0000 | [diff] [blame] | 114 | class LoopIdiomRecognize { |
Eugene Zelenko | dd40f5e | 2017-10-16 21:34:24 +0000 | [diff] [blame] | 115 | Loop *CurLoop = nullptr; |
Chandler Carruth | bf143e2 | 2015-08-14 00:21:10 +0000 | [diff] [blame] | 116 | AliasAnalysis *AA; |
Chandler Carruth | bad690e | 2015-08-12 23:06:37 +0000 | [diff] [blame] | 117 | DominatorTree *DT; |
Chandler Carruth | 18c2669 | 2015-08-13 09:27:01 +0000 | [diff] [blame] | 118 | LoopInfo *LI; |
Chandler Carruth | bad690e | 2015-08-12 23:06:37 +0000 | [diff] [blame] | 119 | ScalarEvolution *SE; |
| 120 | TargetLibraryInfo *TLI; |
| 121 | const TargetTransformInfo *TTI; |
Chad Rosier | 43f9b48 | 2015-11-06 16:33:57 +0000 | [diff] [blame] | 122 | const DataLayout *DL; |
Andrew Kaylor | 7cdf01e | 2016-08-11 18:28:33 +0000 | [diff] [blame] | 123 | bool ApplyCodeSizeHeuristics; |
Chris Lattner | 81ae3f2 | 2010-12-26 19:39:38 +0000 | [diff] [blame] | 124 | |
Chandler Carruth | bad690e | 2015-08-12 23:06:37 +0000 | [diff] [blame] | 125 | public: |
Dehao Chen | b9f8e29 | 2016-07-12 18:45:51 +0000 | [diff] [blame] | 126 | explicit LoopIdiomRecognize(AliasAnalysis *AA, DominatorTree *DT, |
| 127 | LoopInfo *LI, ScalarEvolution *SE, |
| 128 | TargetLibraryInfo *TLI, |
| 129 | const TargetTransformInfo *TTI, |
| 130 | const DataLayout *DL) |
Eugene Zelenko | dd40f5e | 2017-10-16 21:34:24 +0000 | [diff] [blame] | 131 | : AA(AA), DT(DT), LI(LI), SE(SE), TLI(TLI), TTI(TTI), DL(DL) {} |
Chris Lattner | 81ae3f2 | 2010-12-26 19:39:38 +0000 | [diff] [blame] | 132 | |
Dehao Chen | b9f8e29 | 2016-07-12 18:45:51 +0000 | [diff] [blame] | 133 | bool runOnLoop(Loop *L); |
Shuxin Yang | 95de7c3 | 2012-12-09 03:12:46 +0000 | [diff] [blame] | 134 | |
Chandler Carruth | bad690e | 2015-08-12 23:06:37 +0000 | [diff] [blame] | 135 | private: |
Eugene Zelenko | dd40f5e | 2017-10-16 21:34:24 +0000 | [diff] [blame] | 136 | using StoreList = SmallVector<StoreInst *, 8>; |
| 137 | using StoreListMap = MapVector<Value *, StoreList>; |
| 138 | |
Haicheng Wu | f1c00a2 | 2016-01-26 02:27:47 +0000 | [diff] [blame] | 139 | StoreListMap StoreRefsForMemset; |
| 140 | StoreListMap StoreRefsForMemsetPattern; |
Haicheng Wu | 9d6c940 | 2016-01-04 21:43:14 +0000 | [diff] [blame] | 141 | StoreList StoreRefsForMemcpy; |
| 142 | bool HasMemset; |
| 143 | bool HasMemsetPattern; |
| 144 | bool HasMemcpy; |
Eugene Zelenko | dd40f5e | 2017-10-16 21:34:24 +0000 | [diff] [blame] | 145 | |
Anna Thomas | 5ecb8f7 | 2017-05-19 17:05:36 +0000 | [diff] [blame] | 146 | /// Return code for isLegalStore() |
| 147 | enum LegalStoreKind { |
Anna Thomas | ae3f752f | 2017-05-19 18:00:30 +0000 | [diff] [blame] | 148 | None = 0, |
Anna Thomas | 5ecb8f7 | 2017-05-19 17:05:36 +0000 | [diff] [blame] | 149 | Memset, |
| 150 | MemsetPattern, |
| 151 | Memcpy, |
Anna Thomas | b2a212c | 2017-06-06 16:45:25 +0000 | [diff] [blame] | 152 | UnorderedAtomicMemcpy, |
Anna Thomas | ae3f752f | 2017-05-19 18:00:30 +0000 | [diff] [blame] | 153 | DontUse // Dummy retval never to be used. Allows catching errors in retval |
| 154 | // handling. |
Anna Thomas | 5ecb8f7 | 2017-05-19 17:05:36 +0000 | [diff] [blame] | 155 | }; |
Chad Rosier | cc9030b | 2015-11-11 23:00:59 +0000 | [diff] [blame] | 156 | |
Chandler Carruth | d9c6070 | 2015-08-13 00:10:03 +0000 | [diff] [blame] | 157 | /// \name Countable Loop Idiom Handling |
| 158 | /// @{ |
| 159 | |
Chandler Carruth | bad690e | 2015-08-12 23:06:37 +0000 | [diff] [blame] | 160 | bool runOnCountableLoop(); |
Chandler Carruth | d9c6070 | 2015-08-13 00:10:03 +0000 | [diff] [blame] | 161 | bool runOnLoopBlock(BasicBlock *BB, const SCEV *BECount, |
| 162 | SmallVectorImpl<BasicBlock *> &ExitBlocks); |
| 163 | |
Chad Rosier | cc9030b | 2015-11-11 23:00:59 +0000 | [diff] [blame] | 164 | void collectStores(BasicBlock *BB); |
Anna Thomas | 5ecb8f7 | 2017-05-19 17:05:36 +0000 | [diff] [blame] | 165 | LegalStoreKind isLegalStore(StoreInst *SI); |
JF Bastien | 7e2dd2d | 2018-09-07 18:17:59 +0000 | [diff] [blame] | 166 | enum class ForMemset { No, Yes }; |
Haicheng Wu | f1c00a2 | 2016-01-26 02:27:47 +0000 | [diff] [blame] | 167 | bool processLoopStores(SmallVectorImpl<StoreInst *> &SL, const SCEV *BECount, |
JF Bastien | 7e2dd2d | 2018-09-07 18:17:59 +0000 | [diff] [blame] | 168 | ForMemset For); |
Chandler Carruth | d9c6070 | 2015-08-13 00:10:03 +0000 | [diff] [blame] | 169 | bool processLoopMemSet(MemSetInst *MSI, const SCEV *BECount); |
| 170 | |
| 171 | bool processLoopStridedStore(Value *DestPtr, unsigned StoreSize, |
Haicheng Wu | 9d6c940 | 2016-01-04 21:43:14 +0000 | [diff] [blame] | 172 | unsigned StoreAlignment, Value *StoredVal, |
Haicheng Wu | f1c00a2 | 2016-01-26 02:27:47 +0000 | [diff] [blame] | 173 | Instruction *TheStore, |
| 174 | SmallPtrSetImpl<Instruction *> &Stores, |
| 175 | const SCEVAddRecExpr *Ev, const SCEV *BECount, |
Andrew Kaylor | 7cdf01e | 2016-08-11 18:28:33 +0000 | [diff] [blame] | 176 | bool NegStride, bool IsLoopMemset = false); |
Haicheng Wu | 9d6c940 | 2016-01-04 21:43:14 +0000 | [diff] [blame] | 177 | bool processLoopStoreOfLoopLoad(StoreInst *SI, const SCEV *BECount); |
Andrew Kaylor | 7cdf01e | 2016-08-11 18:28:33 +0000 | [diff] [blame] | 178 | bool avoidLIRForMultiBlockLoop(bool IsMemset = false, |
| 179 | bool IsLoopMemset = false); |
Chandler Carruth | d9c6070 | 2015-08-13 00:10:03 +0000 | [diff] [blame] | 180 | |
| 181 | /// @} |
| 182 | /// \name Noncountable Loop Idiom Handling |
| 183 | /// @{ |
| 184 | |
| 185 | bool runOnNoncountableLoop(); |
| 186 | |
Chandler Carruth | 8219a50 | 2015-08-13 00:44:29 +0000 | [diff] [blame] | 187 | bool recognizePopcount(); |
| 188 | void transformLoopToPopcount(BasicBlock *PreCondBB, Instruction *CntInst, |
| 189 | PHINode *CntPhi, Value *Var); |
Craig Topper | c9a6000 | 2018-12-26 21:59:48 +0000 | [diff] [blame^] | 190 | bool recognizeAndInsertFFS(); /// Find First Set: ctlz or cttz |
| 191 | void transformLoopToCountable(Intrinsic::ID IntrinID, BasicBlock *PreCondBB, |
| 192 | Instruction *CntInst, PHINode *CntPhi, |
| 193 | Value *Var, Instruction *DefX, |
Craig Topper | 2835278 | 2018-07-08 01:45:47 +0000 | [diff] [blame] | 194 | const DebugLoc &DL, bool ZeroCheck, |
| 195 | bool IsCntPhiUsedOutsideLoop); |
Chandler Carruth | 8219a50 | 2015-08-13 00:44:29 +0000 | [diff] [blame] | 196 | |
Chandler Carruth | d9c6070 | 2015-08-13 00:10:03 +0000 | [diff] [blame] | 197 | /// @} |
Chandler Carruth | bad690e | 2015-08-12 23:06:37 +0000 | [diff] [blame] | 198 | }; |
| 199 | |
Dehao Chen | b9f8e29 | 2016-07-12 18:45:51 +0000 | [diff] [blame] | 200 | class LoopIdiomRecognizeLegacyPass : public LoopPass { |
| 201 | public: |
| 202 | static char ID; |
Eugene Zelenko | dd40f5e | 2017-10-16 21:34:24 +0000 | [diff] [blame] | 203 | |
Dehao Chen | b9f8e29 | 2016-07-12 18:45:51 +0000 | [diff] [blame] | 204 | explicit LoopIdiomRecognizeLegacyPass() : LoopPass(ID) { |
| 205 | initializeLoopIdiomRecognizeLegacyPassPass( |
| 206 | *PassRegistry::getPassRegistry()); |
| 207 | } |
| 208 | |
| 209 | bool runOnLoop(Loop *L, LPPassManager &LPM) override { |
| 210 | if (skipLoop(L)) |
| 211 | return false; |
| 212 | |
| 213 | AliasAnalysis *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults(); |
| 214 | DominatorTree *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree(); |
| 215 | LoopInfo *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); |
| 216 | ScalarEvolution *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE(); |
| 217 | TargetLibraryInfo *TLI = |
| 218 | &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(); |
| 219 | const TargetTransformInfo *TTI = |
| 220 | &getAnalysis<TargetTransformInfoWrapperPass>().getTTI( |
| 221 | *L->getHeader()->getParent()); |
| 222 | const DataLayout *DL = &L->getHeader()->getModule()->getDataLayout(); |
| 223 | |
| 224 | LoopIdiomRecognize LIR(AA, DT, LI, SE, TLI, TTI, DL); |
| 225 | return LIR.runOnLoop(L); |
| 226 | } |
| 227 | |
| 228 | /// This transformation requires natural loop information & requires that |
| 229 | /// loop preheaders be inserted into the CFG. |
Dehao Chen | b9f8e29 | 2016-07-12 18:45:51 +0000 | [diff] [blame] | 230 | void getAnalysisUsage(AnalysisUsage &AU) const override { |
| 231 | AU.addRequired<TargetLibraryInfoWrapperPass>(); |
| 232 | AU.addRequired<TargetTransformInfoWrapperPass>(); |
| 233 | getLoopAnalysisUsage(AU); |
| 234 | } |
| 235 | }; |
Eugene Zelenko | dd40f5e | 2017-10-16 21:34:24 +0000 | [diff] [blame] | 236 | |
| 237 | } // end anonymous namespace |
| 238 | |
| 239 | char LoopIdiomRecognizeLegacyPass::ID = 0; |
Chris Lattner | 81ae3f2 | 2010-12-26 19:39:38 +0000 | [diff] [blame] | 240 | |
Chandler Carruth | 410eaeb | 2017-01-11 06:23:21 +0000 | [diff] [blame] | 241 | PreservedAnalyses LoopIdiomRecognizePass::run(Loop &L, LoopAnalysisManager &AM, |
| 242 | LoopStandardAnalysisResults &AR, |
| 243 | LPMUpdater &) { |
Dehao Chen | b9f8e29 | 2016-07-12 18:45:51 +0000 | [diff] [blame] | 244 | const auto *DL = &L.getHeader()->getModule()->getDataLayout(); |
Dehao Chen | b9f8e29 | 2016-07-12 18:45:51 +0000 | [diff] [blame] | 245 | |
Chandler Carruth | 410eaeb | 2017-01-11 06:23:21 +0000 | [diff] [blame] | 246 | 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] | 247 | if (!LIR.runOnLoop(&L)) |
| 248 | return PreservedAnalyses::all(); |
| 249 | |
| 250 | return getLoopPassPreservedAnalyses(); |
| 251 | } |
| 252 | |
Dehao Chen | b9f8e29 | 2016-07-12 18:45:51 +0000 | [diff] [blame] | 253 | INITIALIZE_PASS_BEGIN(LoopIdiomRecognizeLegacyPass, "loop-idiom", |
| 254 | "Recognize loop idioms", false, false) |
Chandler Carruth | 31088a9 | 2016-02-19 10:45:18 +0000 | [diff] [blame] | 255 | INITIALIZE_PASS_DEPENDENCY(LoopPass) |
Chandler Carruth | b98f63d | 2015-01-15 10:41:28 +0000 | [diff] [blame] | 256 | INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) |
Chandler Carruth | 705b185 | 2015-01-31 03:43:40 +0000 | [diff] [blame] | 257 | INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass) |
Dehao Chen | b9f8e29 | 2016-07-12 18:45:51 +0000 | [diff] [blame] | 258 | INITIALIZE_PASS_END(LoopIdiomRecognizeLegacyPass, "loop-idiom", |
| 259 | "Recognize loop idioms", false, false) |
Chris Lattner | 81ae3f2 | 2010-12-26 19:39:38 +0000 | [diff] [blame] | 260 | |
Dehao Chen | b9f8e29 | 2016-07-12 18:45:51 +0000 | [diff] [blame] | 261 | Pass *llvm::createLoopIdiomPass() { return new LoopIdiomRecognizeLegacyPass(); } |
Chris Lattner | 81ae3f2 | 2010-12-26 19:39:38 +0000 | [diff] [blame] | 262 | |
David Majnemer | c5601df | 2016-06-20 16:03:25 +0000 | [diff] [blame] | 263 | static void deleteDeadInstruction(Instruction *I) { |
Benjamin Kramer | f094d77 | 2015-02-07 21:37:08 +0000 | [diff] [blame] | 264 | I->replaceAllUsesWith(UndefValue::get(I->getType())); |
| 265 | I->eraseFromParent(); |
Chandler Carruth | 099f5cb0 | 2012-11-02 08:33:25 +0000 | [diff] [blame] | 266 | } |
| 267 | |
Shuxin Yang | 95de7c3 | 2012-12-09 03:12:46 +0000 | [diff] [blame] | 268 | //===----------------------------------------------------------------------===// |
| 269 | // |
Shuxin Yang | 95de7c3 | 2012-12-09 03:12:46 +0000 | [diff] [blame] | 270 | // Implementation of LoopIdiomRecognize |
| 271 | // |
| 272 | //===----------------------------------------------------------------------===// |
| 273 | |
Dehao Chen | b9f8e29 | 2016-07-12 18:45:51 +0000 | [diff] [blame] | 274 | bool LoopIdiomRecognize::runOnLoop(Loop *L) { |
Chandler Carruth | d9c6070 | 2015-08-13 00:10:03 +0000 | [diff] [blame] | 275 | CurLoop = L; |
Chandler Carruth | d9c6070 | 2015-08-13 00:10:03 +0000 | [diff] [blame] | 276 | // If the loop could not be converted to canonical form, it must have an |
| 277 | // indirectbr in it, just give up. |
| 278 | if (!L->getLoopPreheader()) |
| 279 | return false; |
| 280 | |
| 281 | // Disable loop idiom recognition if the function's name is a common idiom. |
| 282 | StringRef Name = L->getHeader()->getParent()->getName(); |
| 283 | if (Name == "memset" || Name == "memcpy") |
| 284 | return false; |
| 285 | |
Andrew Kaylor | 7cdf01e | 2016-08-11 18:28:33 +0000 | [diff] [blame] | 286 | // Determine if code size heuristics need to be applied. |
| 287 | ApplyCodeSizeHeuristics = |
| 288 | L->getHeader()->getParent()->optForSize() && UseLIRCodeSizeHeurs; |
| 289 | |
David L. Jones | d21529f | 2017-01-23 23:16:46 +0000 | [diff] [blame] | 290 | HasMemset = TLI->has(LibFunc_memset); |
| 291 | HasMemsetPattern = TLI->has(LibFunc_memset_pattern16); |
| 292 | HasMemcpy = TLI->has(LibFunc_memcpy); |
Haicheng Wu | 9d6c940 | 2016-01-04 21:43:14 +0000 | [diff] [blame] | 293 | |
| 294 | if (HasMemset || HasMemsetPattern || HasMemcpy) |
| 295 | if (SE->hasLoopInvariantBackedgeTakenCount(L)) |
| 296 | return runOnCountableLoop(); |
Chandler Carruth | dc29832 | 2015-08-13 01:03:26 +0000 | [diff] [blame] | 297 | |
Chandler Carruth | d9c6070 | 2015-08-13 00:10:03 +0000 | [diff] [blame] | 298 | return runOnNoncountableLoop(); |
| 299 | } |
| 300 | |
Shuxin Yang | 95de7c3 | 2012-12-09 03:12:46 +0000 | [diff] [blame] | 301 | bool LoopIdiomRecognize::runOnCountableLoop() { |
| 302 | const SCEV *BECount = SE->getBackedgeTakenCount(CurLoop); |
Davide Italiano | 8ed0446 | 2015-05-11 21:02:34 +0000 | [diff] [blame] | 303 | assert(!isa<SCEVCouldNotCompute>(BECount) && |
Chandler Carruth | bad690e | 2015-08-12 23:06:37 +0000 | [diff] [blame] | 304 | "runOnCountableLoop() called on a loop without a predictable" |
| 305 | "backedge-taken count"); |
Shuxin Yang | 95de7c3 | 2012-12-09 03:12:46 +0000 | [diff] [blame] | 306 | |
| 307 | // If this loop executes exactly one time, then it should be peeled, not |
| 308 | // optimized by this pass. |
| 309 | if (const SCEVConstant *BECst = dyn_cast<SCEVConstant>(BECount)) |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 310 | if (BECst->getAPInt() == 0) |
Shuxin Yang | 95de7c3 | 2012-12-09 03:12:46 +0000 | [diff] [blame] | 311 | return false; |
| 312 | |
Chandler Carruth | bad690e | 2015-08-12 23:06:37 +0000 | [diff] [blame] | 313 | SmallVector<BasicBlock *, 8> ExitBlocks; |
Shuxin Yang | 95de7c3 | 2012-12-09 03:12:46 +0000 | [diff] [blame] | 314 | CurLoop->getUniqueExitBlocks(ExitBlocks); |
| 315 | |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 316 | LLVM_DEBUG(dbgs() << "loop-idiom Scanning: F[" |
| 317 | << CurLoop->getHeader()->getParent()->getName() |
| 318 | << "] Loop %" << CurLoop->getHeader()->getName() << "\n"); |
Shuxin Yang | 95de7c3 | 2012-12-09 03:12:46 +0000 | [diff] [blame] | 319 | |
| 320 | bool MadeChange = false; |
Haicheng Wu | a95cd126 | 2016-07-06 21:05:40 +0000 | [diff] [blame] | 321 | |
| 322 | // The following transforms hoist stores/memsets into the loop pre-header. |
| 323 | // Give up if the loop has instructions may throw. |
Max Kazantsev | 9c90ec2 | 2018-10-16 08:31:05 +0000 | [diff] [blame] | 324 | SimpleLoopSafetyInfo SafetyInfo; |
Max Kazantsev | 530b8d1 | 2018-08-15 05:55:43 +0000 | [diff] [blame] | 325 | SafetyInfo.computeLoopSafetyInfo(CurLoop); |
| 326 | if (SafetyInfo.anyBlockMayThrow()) |
Haicheng Wu | a95cd126 | 2016-07-06 21:05:40 +0000 | [diff] [blame] | 327 | return MadeChange; |
| 328 | |
Shuxin Yang | 95de7c3 | 2012-12-09 03:12:46 +0000 | [diff] [blame] | 329 | // Scan all the blocks in the loop that are not in subloops. |
Davide Italiano | 95a77e8 | 2015-05-14 21:52:12 +0000 | [diff] [blame] | 330 | for (auto *BB : CurLoop->getBlocks()) { |
Shuxin Yang | 95de7c3 | 2012-12-09 03:12:46 +0000 | [diff] [blame] | 331 | // Ignore blocks in subloops. |
Chandler Carruth | 18c2669 | 2015-08-13 09:27:01 +0000 | [diff] [blame] | 332 | if (LI->getLoopFor(BB) != CurLoop) |
Shuxin Yang | 95de7c3 | 2012-12-09 03:12:46 +0000 | [diff] [blame] | 333 | continue; |
| 334 | |
Davide Italiano | 80625af | 2015-05-13 19:51:21 +0000 | [diff] [blame] | 335 | MadeChange |= runOnLoopBlock(BB, BECount, ExitBlocks); |
Shuxin Yang | 95de7c3 | 2012-12-09 03:12:46 +0000 | [diff] [blame] | 336 | } |
| 337 | return MadeChange; |
| 338 | } |
| 339 | |
Chad Rosier | 4acff96 | 2016-02-12 19:05:27 +0000 | [diff] [blame] | 340 | static APInt getStoreStride(const SCEVAddRecExpr *StoreEv) { |
Chad Rosier | a548fe5 | 2015-11-12 19:09:16 +0000 | [diff] [blame] | 341 | const SCEVConstant *ConstStride = cast<SCEVConstant>(StoreEv->getOperand(1)); |
Chad Rosier | 4acff96 | 2016-02-12 19:05:27 +0000 | [diff] [blame] | 342 | return ConstStride->getAPInt(); |
Chad Rosier | a548fe5 | 2015-11-12 19:09:16 +0000 | [diff] [blame] | 343 | } |
| 344 | |
Chad Rosier | 94274fb | 2015-12-21 14:49:32 +0000 | [diff] [blame] | 345 | /// getMemSetPatternValue - If a strided store of the specified value is safe to |
| 346 | /// turn into a memset_pattern16, return a ConstantArray of 16 bytes that should |
| 347 | /// be passed in. Otherwise, return null. |
| 348 | /// |
| 349 | /// Note that we don't ever attempt to use memset_pattern8 or 4, because these |
| 350 | /// just replicate their input array and then pass on to memset_pattern16. |
| 351 | static Constant *getMemSetPatternValue(Value *V, const DataLayout *DL) { |
JF Bastien | 73d8e4e | 2018-09-21 05:17:42 +0000 | [diff] [blame] | 352 | // FIXME: This could check for UndefValue because it can be merged into any |
| 353 | // other valid pattern. |
| 354 | |
Chad Rosier | 94274fb | 2015-12-21 14:49:32 +0000 | [diff] [blame] | 355 | // If the value isn't a constant, we can't promote it to being in a constant |
| 356 | // array. We could theoretically do a store to an alloca or something, but |
| 357 | // that doesn't seem worthwhile. |
| 358 | Constant *C = dyn_cast<Constant>(V); |
| 359 | if (!C) |
| 360 | return nullptr; |
| 361 | |
| 362 | // Only handle simple values that are a power of two bytes in size. |
| 363 | uint64_t Size = DL->getTypeSizeInBits(V->getType()); |
| 364 | if (Size == 0 || (Size & 7) || (Size & (Size - 1))) |
| 365 | return nullptr; |
| 366 | |
| 367 | // Don't care enough about darwin/ppc to implement this. |
| 368 | if (DL->isBigEndian()) |
| 369 | return nullptr; |
| 370 | |
| 371 | // Convert to size in bytes. |
| 372 | Size /= 8; |
| 373 | |
| 374 | // TODO: If CI is larger than 16-bytes, we can try slicing it in half to see |
| 375 | // if the top and bottom are the same (e.g. for vectors and large integers). |
| 376 | if (Size > 16) |
| 377 | return nullptr; |
| 378 | |
| 379 | // If the constant is exactly 16 bytes, just use it. |
| 380 | if (Size == 16) |
| 381 | return C; |
| 382 | |
| 383 | // Otherwise, we'll use an array of the constants. |
| 384 | unsigned ArraySize = 16 / Size; |
| 385 | ArrayType *AT = ArrayType::get(V->getType(), ArraySize); |
| 386 | return ConstantArray::get(AT, std::vector<Constant *>(ArraySize, C)); |
| 387 | } |
| 388 | |
Anna Thomas | ae3f752f | 2017-05-19 18:00:30 +0000 | [diff] [blame] | 389 | LoopIdiomRecognize::LegalStoreKind |
| 390 | LoopIdiomRecognize::isLegalStore(StoreInst *SI) { |
Chad Rosier | 869962f | 2015-12-01 14:26:35 +0000 | [diff] [blame] | 391 | // Don't touch volatile stores. |
Anna Thomas | b2a212c | 2017-06-06 16:45:25 +0000 | [diff] [blame] | 392 | if (SI->isVolatile()) |
| 393 | return LegalStoreKind::None; |
| 394 | // We only want simple or unordered-atomic stores. |
| 395 | if (!SI->isUnordered()) |
Anna Thomas | 5ecb8f7 | 2017-05-19 17:05:36 +0000 | [diff] [blame] | 396 | return LegalStoreKind::None; |
Chad Rosier | 869962f | 2015-12-01 14:26:35 +0000 | [diff] [blame] | 397 | |
Sanjoy Das | 206f65c | 2017-04-24 20:12:10 +0000 | [diff] [blame] | 398 | // Don't convert stores of non-integral pointer types to memsets (which stores |
| 399 | // integers). |
| 400 | if (DL->isNonIntegralPointerType(SI->getValueOperand()->getType())) |
Anna Thomas | 5ecb8f7 | 2017-05-19 17:05:36 +0000 | [diff] [blame] | 401 | return LegalStoreKind::None; |
Sanjoy Das | 206f65c | 2017-04-24 20:12:10 +0000 | [diff] [blame] | 402 | |
Haicheng Wu | 57e1a3e | 2016-02-17 21:00:06 +0000 | [diff] [blame] | 403 | // Avoid merging nontemporal stores. |
| 404 | if (SI->getMetadata(LLVMContext::MD_nontemporal)) |
Anna Thomas | 5ecb8f7 | 2017-05-19 17:05:36 +0000 | [diff] [blame] | 405 | return LegalStoreKind::None; |
Haicheng Wu | 57e1a3e | 2016-02-17 21:00:06 +0000 | [diff] [blame] | 406 | |
Chad Rosier | a548fe5 | 2015-11-12 19:09:16 +0000 | [diff] [blame] | 407 | Value *StoredVal = SI->getValueOperand(); |
| 408 | Value *StorePtr = SI->getPointerOperand(); |
| 409 | |
| 410 | // Reject stores that are so large that they overflow an unsigned. |
| 411 | uint64_t SizeInBits = DL->getTypeSizeInBits(StoredVal->getType()); |
| 412 | if ((SizeInBits & 7) || (SizeInBits >> 32) != 0) |
Anna Thomas | 5ecb8f7 | 2017-05-19 17:05:36 +0000 | [diff] [blame] | 413 | return LegalStoreKind::None; |
Chad Rosier | a548fe5 | 2015-11-12 19:09:16 +0000 | [diff] [blame] | 414 | |
| 415 | // See if the pointer expression is an AddRec like {base,+,1} on the current |
| 416 | // loop, which indicates a strided store. If we have something else, it's a |
| 417 | // random store we can't handle. |
| 418 | const SCEVAddRecExpr *StoreEv = |
| 419 | dyn_cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr)); |
| 420 | if (!StoreEv || StoreEv->getLoop() != CurLoop || !StoreEv->isAffine()) |
Anna Thomas | 5ecb8f7 | 2017-05-19 17:05:36 +0000 | [diff] [blame] | 421 | return LegalStoreKind::None; |
Chad Rosier | a548fe5 | 2015-11-12 19:09:16 +0000 | [diff] [blame] | 422 | |
| 423 | // Check to see if we have a constant stride. |
| 424 | if (!isa<SCEVConstant>(StoreEv->getOperand(1))) |
Anna Thomas | 5ecb8f7 | 2017-05-19 17:05:36 +0000 | [diff] [blame] | 425 | return LegalStoreKind::None; |
Chad Rosier | a548fe5 | 2015-11-12 19:09:16 +0000 | [diff] [blame] | 426 | |
Haicheng Wu | 9d6c940 | 2016-01-04 21:43:14 +0000 | [diff] [blame] | 427 | // See if the store can be turned into a memset. |
| 428 | |
| 429 | // If the stored value is a byte-wise value (like i32 -1), then it may be |
| 430 | // turned into a memset of i8 -1, assuming that all the consecutive bytes |
| 431 | // are stored. A store of i32 0x01020304 can never be turned into a memset, |
| 432 | // but it can be turned into memset_pattern if the target supports it. |
| 433 | Value *SplatValue = isBytewiseValue(StoredVal); |
| 434 | Constant *PatternValue = nullptr; |
| 435 | |
Anna Thomas | b2a212c | 2017-06-06 16:45:25 +0000 | [diff] [blame] | 436 | // Note: memset and memset_pattern on unordered-atomic is yet not supported |
| 437 | bool UnorderedAtomic = SI->isUnordered() && !SI->isSimple(); |
| 438 | |
Haicheng Wu | 9d6c940 | 2016-01-04 21:43:14 +0000 | [diff] [blame] | 439 | // If we're allowed to form a memset, and the stored value would be |
| 440 | // acceptable for memset, use it. |
Anna Thomas | b2a212c | 2017-06-06 16:45:25 +0000 | [diff] [blame] | 441 | if (!UnorderedAtomic && HasMemset && SplatValue && |
Haicheng Wu | 9d6c940 | 2016-01-04 21:43:14 +0000 | [diff] [blame] | 442 | // Verify that the stored value is loop invariant. If not, we can't |
| 443 | // promote the memset. |
| 444 | CurLoop->isLoopInvariant(SplatValue)) { |
| 445 | // It looks like we can use SplatValue. |
Anna Thomas | 5ecb8f7 | 2017-05-19 17:05:36 +0000 | [diff] [blame] | 446 | return LegalStoreKind::Memset; |
Anna Thomas | b2a212c | 2017-06-06 16:45:25 +0000 | [diff] [blame] | 447 | } else if (!UnorderedAtomic && HasMemsetPattern && |
Haicheng Wu | 9d6c940 | 2016-01-04 21:43:14 +0000 | [diff] [blame] | 448 | // Don't create memset_pattern16s with address spaces. |
| 449 | StorePtr->getType()->getPointerAddressSpace() == 0 && |
| 450 | (PatternValue = getMemSetPatternValue(StoredVal, DL))) { |
| 451 | // It looks like we can use PatternValue! |
Anna Thomas | 5ecb8f7 | 2017-05-19 17:05:36 +0000 | [diff] [blame] | 452 | return LegalStoreKind::MemsetPattern; |
Haicheng Wu | 9d6c940 | 2016-01-04 21:43:14 +0000 | [diff] [blame] | 453 | } |
| 454 | |
| 455 | // Otherwise, see if the store can be turned into a memcpy. |
| 456 | if (HasMemcpy) { |
| 457 | // Check to see if the stride matches the size of the store. If so, then we |
| 458 | // know that every byte is touched in the loop. |
Chad Rosier | 4acff96 | 2016-02-12 19:05:27 +0000 | [diff] [blame] | 459 | APInt Stride = getStoreStride(StoreEv); |
Jonas Paulsson | f0ff20f | 2017-11-28 14:44:32 +0000 | [diff] [blame] | 460 | unsigned StoreSize = DL->getTypeStoreSize(SI->getValueOperand()->getType()); |
Haicheng Wu | 9d6c940 | 2016-01-04 21:43:14 +0000 | [diff] [blame] | 461 | if (StoreSize != Stride && StoreSize != -Stride) |
Anna Thomas | 5ecb8f7 | 2017-05-19 17:05:36 +0000 | [diff] [blame] | 462 | return LegalStoreKind::None; |
Haicheng Wu | 9d6c940 | 2016-01-04 21:43:14 +0000 | [diff] [blame] | 463 | |
| 464 | // The store must be feeding a non-volatile load. |
| 465 | LoadInst *LI = dyn_cast<LoadInst>(SI->getValueOperand()); |
Anna Thomas | b2a212c | 2017-06-06 16:45:25 +0000 | [diff] [blame] | 466 | |
| 467 | // Only allow non-volatile loads |
| 468 | if (!LI || LI->isVolatile()) |
| 469 | return LegalStoreKind::None; |
| 470 | // Only allow simple or unordered-atomic loads |
| 471 | if (!LI->isUnordered()) |
Anna Thomas | 5ecb8f7 | 2017-05-19 17:05:36 +0000 | [diff] [blame] | 472 | return LegalStoreKind::None; |
Haicheng Wu | 9d6c940 | 2016-01-04 21:43:14 +0000 | [diff] [blame] | 473 | |
| 474 | // See if the pointer expression is an AddRec like {base,+,1} on the current |
| 475 | // loop, which indicates a strided load. If we have something else, it's a |
| 476 | // random load we can't handle. |
| 477 | const SCEVAddRecExpr *LoadEv = |
| 478 | dyn_cast<SCEVAddRecExpr>(SE->getSCEV(LI->getPointerOperand())); |
| 479 | if (!LoadEv || LoadEv->getLoop() != CurLoop || !LoadEv->isAffine()) |
Anna Thomas | 5ecb8f7 | 2017-05-19 17:05:36 +0000 | [diff] [blame] | 480 | return LegalStoreKind::None; |
Haicheng Wu | 9d6c940 | 2016-01-04 21:43:14 +0000 | [diff] [blame] | 481 | |
| 482 | // The store and load must share the same stride. |
| 483 | if (StoreEv->getOperand(1) != LoadEv->getOperand(1)) |
Anna Thomas | 5ecb8f7 | 2017-05-19 17:05:36 +0000 | [diff] [blame] | 484 | return LegalStoreKind::None; |
Haicheng Wu | 9d6c940 | 2016-01-04 21:43:14 +0000 | [diff] [blame] | 485 | |
| 486 | // Success. This store can be converted into a memcpy. |
Anna Thomas | b2a212c | 2017-06-06 16:45:25 +0000 | [diff] [blame] | 487 | UnorderedAtomic = UnorderedAtomic || LI->isAtomic(); |
| 488 | return UnorderedAtomic ? LegalStoreKind::UnorderedAtomicMemcpy |
| 489 | : LegalStoreKind::Memcpy; |
Haicheng Wu | 9d6c940 | 2016-01-04 21:43:14 +0000 | [diff] [blame] | 490 | } |
| 491 | // This store can't be transformed into a memset/memcpy. |
Anna Thomas | 5ecb8f7 | 2017-05-19 17:05:36 +0000 | [diff] [blame] | 492 | return LegalStoreKind::None; |
Chad Rosier | a548fe5 | 2015-11-12 19:09:16 +0000 | [diff] [blame] | 493 | } |
| 494 | |
Chad Rosier | cc9030b | 2015-11-11 23:00:59 +0000 | [diff] [blame] | 495 | void LoopIdiomRecognize::collectStores(BasicBlock *BB) { |
Haicheng Wu | 9d6c940 | 2016-01-04 21:43:14 +0000 | [diff] [blame] | 496 | StoreRefsForMemset.clear(); |
Haicheng Wu | f1c00a2 | 2016-01-26 02:27:47 +0000 | [diff] [blame] | 497 | StoreRefsForMemsetPattern.clear(); |
Haicheng Wu | 9d6c940 | 2016-01-04 21:43:14 +0000 | [diff] [blame] | 498 | StoreRefsForMemcpy.clear(); |
Chad Rosier | cc9030b | 2015-11-11 23:00:59 +0000 | [diff] [blame] | 499 | for (Instruction &I : *BB) { |
| 500 | StoreInst *SI = dyn_cast<StoreInst>(&I); |
| 501 | if (!SI) |
| 502 | continue; |
| 503 | |
Chad Rosier | a548fe5 | 2015-11-12 19:09:16 +0000 | [diff] [blame] | 504 | // Make sure this is a strided store with a constant stride. |
Anna Thomas | 5ecb8f7 | 2017-05-19 17:05:36 +0000 | [diff] [blame] | 505 | switch (isLegalStore(SI)) { |
| 506 | case LegalStoreKind::None: |
| 507 | // Nothing to do |
| 508 | break; |
| 509 | case LegalStoreKind::Memset: { |
Haicheng Wu | f1c00a2 | 2016-01-26 02:27:47 +0000 | [diff] [blame] | 510 | // Find the base pointer. |
| 511 | Value *Ptr = GetUnderlyingObject(SI->getPointerOperand(), *DL); |
| 512 | StoreRefsForMemset[Ptr].push_back(SI); |
Anna Thomas | 5ecb8f7 | 2017-05-19 17:05:36 +0000 | [diff] [blame] | 513 | } break; |
| 514 | case LegalStoreKind::MemsetPattern: { |
Haicheng Wu | f1c00a2 | 2016-01-26 02:27:47 +0000 | [diff] [blame] | 515 | // Find the base pointer. |
| 516 | Value *Ptr = GetUnderlyingObject(SI->getPointerOperand(), *DL); |
| 517 | StoreRefsForMemsetPattern[Ptr].push_back(SI); |
Anna Thomas | 5ecb8f7 | 2017-05-19 17:05:36 +0000 | [diff] [blame] | 518 | } break; |
| 519 | case LegalStoreKind::Memcpy: |
Anna Thomas | b2a212c | 2017-06-06 16:45:25 +0000 | [diff] [blame] | 520 | case LegalStoreKind::UnorderedAtomicMemcpy: |
Haicheng Wu | 9d6c940 | 2016-01-04 21:43:14 +0000 | [diff] [blame] | 521 | StoreRefsForMemcpy.push_back(SI); |
Anna Thomas | 5ecb8f7 | 2017-05-19 17:05:36 +0000 | [diff] [blame] | 522 | break; |
| 523 | default: |
| 524 | assert(false && "unhandled return value"); |
| 525 | break; |
| 526 | } |
Chad Rosier | cc9030b | 2015-11-11 23:00:59 +0000 | [diff] [blame] | 527 | } |
| 528 | } |
| 529 | |
Chris Lattner | 8455b6e | 2011-01-02 19:01:03 +0000 | [diff] [blame] | 530 | /// runOnLoopBlock - Process the specified block, which lives in a counted loop |
| 531 | /// with the specified backedge count. This block is known to be in the current |
| 532 | /// loop and not in any subloops. |
Chandler Carruth | bad690e | 2015-08-12 23:06:37 +0000 | [diff] [blame] | 533 | bool LoopIdiomRecognize::runOnLoopBlock( |
| 534 | BasicBlock *BB, const SCEV *BECount, |
| 535 | SmallVectorImpl<BasicBlock *> &ExitBlocks) { |
Chris Lattner | 8455b6e | 2011-01-02 19:01:03 +0000 | [diff] [blame] | 536 | // We can only promote stores in this block if they are unconditionally |
| 537 | // executed in the loop. For a block to be unconditionally executed, it has |
| 538 | // to dominate all the exit blocks of the loop. Verify this now. |
| 539 | for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) |
| 540 | if (!DT->dominates(BB, ExitBlocks[i])) |
| 541 | return false; |
Andrew Trick | 328b223 | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 542 | |
Chris Lattner | 7c5f9c3 | 2010-12-26 20:45:45 +0000 | [diff] [blame] | 543 | bool MadeChange = false; |
Chad Rosier | cc9030b | 2015-11-11 23:00:59 +0000 | [diff] [blame] | 544 | // Look for store instructions, which may be optimized to memset/memcpy. |
| 545 | collectStores(BB); |
Haicheng Wu | 9d6c940 | 2016-01-04 21:43:14 +0000 | [diff] [blame] | 546 | |
Haicheng Wu | f1c00a2 | 2016-01-26 02:27:47 +0000 | [diff] [blame] | 547 | // Look for a single store or sets of stores with a common base, which can be |
| 548 | // optimized into a memset (memset_pattern). The latter most commonly happens |
| 549 | // with structs and handunrolled loops. |
| 550 | for (auto &SL : StoreRefsForMemset) |
JF Bastien | 7e2dd2d | 2018-09-07 18:17:59 +0000 | [diff] [blame] | 551 | MadeChange |= processLoopStores(SL.second, BECount, ForMemset::Yes); |
Haicheng Wu | f1c00a2 | 2016-01-26 02:27:47 +0000 | [diff] [blame] | 552 | |
| 553 | for (auto &SL : StoreRefsForMemsetPattern) |
JF Bastien | 7e2dd2d | 2018-09-07 18:17:59 +0000 | [diff] [blame] | 554 | MadeChange |= processLoopStores(SL.second, BECount, ForMemset::No); |
Chad Rosier | cc9030b | 2015-11-11 23:00:59 +0000 | [diff] [blame] | 555 | |
Haicheng Wu | 9d6c940 | 2016-01-04 21:43:14 +0000 | [diff] [blame] | 556 | // Optimize the store into a memcpy, if it feeds an similarly strided load. |
| 557 | for (auto &SI : StoreRefsForMemcpy) |
| 558 | MadeChange |= processLoopStoreOfLoopLoad(SI, BECount); |
| 559 | |
Chandler Carruth | bad690e | 2015-08-12 23:06:37 +0000 | [diff] [blame] | 560 | 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] | 561 | Instruction *Inst = &*I++; |
Chris Lattner | 8643810 | 2011-01-04 07:46:33 +0000 | [diff] [blame] | 562 | // Look for memset instructions, which may be optimized to a larger memset. |
Chandler Carruth | bad690e | 2015-08-12 23:06:37 +0000 | [diff] [blame] | 563 | if (MemSetInst *MSI = dyn_cast<MemSetInst>(Inst)) { |
Sanjoy Das | e6bca0e | 2017-05-01 17:07:49 +0000 | [diff] [blame] | 564 | WeakTrackingVH InstPtr(&*I); |
Chandler Carruth | bad690e | 2015-08-12 23:06:37 +0000 | [diff] [blame] | 565 | if (!processLoopMemSet(MSI, BECount)) |
| 566 | continue; |
Chris Lattner | 8643810 | 2011-01-04 07:46:33 +0000 | [diff] [blame] | 567 | MadeChange = true; |
Andrew Trick | 328b223 | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 568 | |
Chris Lattner | 8643810 | 2011-01-04 07:46:33 +0000 | [diff] [blame] | 569 | // If processing the memset invalidated our iterator, start over from the |
| 570 | // top of the block. |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 571 | if (!InstPtr) |
Chris Lattner | 8643810 | 2011-01-04 07:46:33 +0000 | [diff] [blame] | 572 | I = BB->begin(); |
| 573 | continue; |
| 574 | } |
Chris Lattner | 7c5f9c3 | 2010-12-26 20:45:45 +0000 | [diff] [blame] | 575 | } |
Andrew Trick | 328b223 | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 576 | |
Chris Lattner | 7c5f9c3 | 2010-12-26 20:45:45 +0000 | [diff] [blame] | 577 | return MadeChange; |
Chris Lattner | 81ae3f2 | 2010-12-26 19:39:38 +0000 | [diff] [blame] | 578 | } |
| 579 | |
JF Bastien | 7e2dd2d | 2018-09-07 18:17:59 +0000 | [diff] [blame] | 580 | /// See if this store(s) can be promoted to a memset. |
Haicheng Wu | f1c00a2 | 2016-01-26 02:27:47 +0000 | [diff] [blame] | 581 | bool LoopIdiomRecognize::processLoopStores(SmallVectorImpl<StoreInst *> &SL, |
JF Bastien | 7e2dd2d | 2018-09-07 18:17:59 +0000 | [diff] [blame] | 582 | const SCEV *BECount, ForMemset For) { |
Haicheng Wu | f1c00a2 | 2016-01-26 02:27:47 +0000 | [diff] [blame] | 583 | // Try to find consecutive stores that can be transformed into memsets. |
| 584 | SetVector<StoreInst *> Heads, Tails; |
| 585 | SmallDenseMap<StoreInst *, StoreInst *> ConsecutiveChain; |
Chris Lattner | 8643810 | 2011-01-04 07:46:33 +0000 | [diff] [blame] | 586 | |
Haicheng Wu | f1c00a2 | 2016-01-26 02:27:47 +0000 | [diff] [blame] | 587 | // Do a quadratic search on all of the given stores and find |
| 588 | // all of the pairs of stores that follow each other. |
| 589 | SmallVector<unsigned, 16> IndexQueue; |
| 590 | for (unsigned i = 0, e = SL.size(); i < e; ++i) { |
| 591 | assert(SL[i]->isSimple() && "Expected only non-volatile stores."); |
Andrew Trick | 328b223 | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 592 | |
Haicheng Wu | f1c00a2 | 2016-01-26 02:27:47 +0000 | [diff] [blame] | 593 | Value *FirstStoredVal = SL[i]->getValueOperand(); |
| 594 | Value *FirstStorePtr = SL[i]->getPointerOperand(); |
| 595 | const SCEVAddRecExpr *FirstStoreEv = |
| 596 | cast<SCEVAddRecExpr>(SE->getSCEV(FirstStorePtr)); |
Chad Rosier | 4acff96 | 2016-02-12 19:05:27 +0000 | [diff] [blame] | 597 | APInt FirstStride = getStoreStride(FirstStoreEv); |
Jonas Paulsson | f0ff20f | 2017-11-28 14:44:32 +0000 | [diff] [blame] | 598 | unsigned FirstStoreSize = DL->getTypeStoreSize(SL[i]->getValueOperand()->getType()); |
Chad Rosier | 7967614 | 2015-10-28 14:38:49 +0000 | [diff] [blame] | 599 | |
Haicheng Wu | f1c00a2 | 2016-01-26 02:27:47 +0000 | [diff] [blame] | 600 | // See if we can optimize just this store in isolation. |
Chad Rosier | 4acff96 | 2016-02-12 19:05:27 +0000 | [diff] [blame] | 601 | if (FirstStride == FirstStoreSize || -FirstStride == FirstStoreSize) { |
Haicheng Wu | f1c00a2 | 2016-01-26 02:27:47 +0000 | [diff] [blame] | 602 | Heads.insert(SL[i]); |
| 603 | continue; |
| 604 | } |
Chris Lattner | 0f4a640 | 2011-02-19 19:31:39 +0000 | [diff] [blame] | 605 | |
Haicheng Wu | f1c00a2 | 2016-01-26 02:27:47 +0000 | [diff] [blame] | 606 | Value *FirstSplatValue = nullptr; |
| 607 | Constant *FirstPatternValue = nullptr; |
| 608 | |
JF Bastien | 7e2dd2d | 2018-09-07 18:17:59 +0000 | [diff] [blame] | 609 | if (For == ForMemset::Yes) |
Haicheng Wu | f1c00a2 | 2016-01-26 02:27:47 +0000 | [diff] [blame] | 610 | FirstSplatValue = isBytewiseValue(FirstStoredVal); |
| 611 | else |
| 612 | FirstPatternValue = getMemSetPatternValue(FirstStoredVal, DL); |
| 613 | |
| 614 | assert((FirstSplatValue || FirstPatternValue) && |
| 615 | "Expected either splat value or pattern value."); |
| 616 | |
| 617 | IndexQueue.clear(); |
| 618 | // If a store has multiple consecutive store candidates, search Stores |
| 619 | // array according to the sequence: from i+1 to e, then from i-1 to 0. |
| 620 | // This is because usually pairing with immediate succeeding or preceding |
| 621 | // candidate create the best chance to find memset opportunity. |
| 622 | unsigned j = 0; |
| 623 | for (j = i + 1; j < e; ++j) |
| 624 | IndexQueue.push_back(j); |
| 625 | for (j = i; j > 0; --j) |
| 626 | IndexQueue.push_back(j - 1); |
| 627 | |
| 628 | for (auto &k : IndexQueue) { |
| 629 | assert(SL[k]->isSimple() && "Expected only non-volatile stores."); |
| 630 | Value *SecondStorePtr = SL[k]->getPointerOperand(); |
| 631 | const SCEVAddRecExpr *SecondStoreEv = |
| 632 | cast<SCEVAddRecExpr>(SE->getSCEV(SecondStorePtr)); |
Chad Rosier | 4acff96 | 2016-02-12 19:05:27 +0000 | [diff] [blame] | 633 | APInt SecondStride = getStoreStride(SecondStoreEv); |
Haicheng Wu | f1c00a2 | 2016-01-26 02:27:47 +0000 | [diff] [blame] | 634 | |
| 635 | if (FirstStride != SecondStride) |
| 636 | continue; |
| 637 | |
| 638 | Value *SecondStoredVal = SL[k]->getValueOperand(); |
| 639 | Value *SecondSplatValue = nullptr; |
| 640 | Constant *SecondPatternValue = nullptr; |
| 641 | |
JF Bastien | 7e2dd2d | 2018-09-07 18:17:59 +0000 | [diff] [blame] | 642 | if (For == ForMemset::Yes) |
Haicheng Wu | f1c00a2 | 2016-01-26 02:27:47 +0000 | [diff] [blame] | 643 | SecondSplatValue = isBytewiseValue(SecondStoredVal); |
| 644 | else |
| 645 | SecondPatternValue = getMemSetPatternValue(SecondStoredVal, DL); |
| 646 | |
| 647 | assert((SecondSplatValue || SecondPatternValue) && |
| 648 | "Expected either splat value or pattern value."); |
| 649 | |
| 650 | if (isConsecutiveAccess(SL[i], SL[k], *DL, *SE, false)) { |
JF Bastien | 7e2dd2d | 2018-09-07 18:17:59 +0000 | [diff] [blame] | 651 | if (For == ForMemset::Yes) { |
JF Bastien | 73d8e4e | 2018-09-21 05:17:42 +0000 | [diff] [blame] | 652 | if (isa<UndefValue>(FirstSplatValue)) |
| 653 | FirstSplatValue = SecondSplatValue; |
Haicheng Wu | f1c00a2 | 2016-01-26 02:27:47 +0000 | [diff] [blame] | 654 | if (FirstSplatValue != SecondSplatValue) |
| 655 | continue; |
| 656 | } else { |
JF Bastien | 73d8e4e | 2018-09-21 05:17:42 +0000 | [diff] [blame] | 657 | if (isa<UndefValue>(FirstPatternValue)) |
| 658 | FirstPatternValue = SecondPatternValue; |
Haicheng Wu | f1c00a2 | 2016-01-26 02:27:47 +0000 | [diff] [blame] | 659 | if (FirstPatternValue != SecondPatternValue) |
| 660 | continue; |
| 661 | } |
| 662 | Tails.insert(SL[k]); |
| 663 | Heads.insert(SL[i]); |
| 664 | ConsecutiveChain[SL[i]] = SL[k]; |
| 665 | break; |
| 666 | } |
| 667 | } |
| 668 | } |
| 669 | |
| 670 | // We may run into multiple chains that merge into a single chain. We mark the |
| 671 | // stores that we transformed so that we don't visit the same store twice. |
| 672 | SmallPtrSet<Value *, 16> TransformedStores; |
| 673 | bool Changed = false; |
| 674 | |
| 675 | // For stores that start but don't end a link in the chain: |
| 676 | for (SetVector<StoreInst *>::iterator it = Heads.begin(), e = Heads.end(); |
| 677 | it != e; ++it) { |
| 678 | if (Tails.count(*it)) |
| 679 | continue; |
| 680 | |
| 681 | // We found a store instr that starts a chain. Now follow the chain and try |
| 682 | // to transform it. |
| 683 | SmallPtrSet<Instruction *, 8> AdjacentStores; |
| 684 | StoreInst *I = *it; |
| 685 | |
| 686 | StoreInst *HeadStore = I; |
| 687 | unsigned StoreSize = 0; |
| 688 | |
| 689 | // Collect the chain into a list. |
| 690 | while (Tails.count(I) || Heads.count(I)) { |
| 691 | if (TransformedStores.count(I)) |
| 692 | break; |
| 693 | AdjacentStores.insert(I); |
| 694 | |
Jonas Paulsson | f0ff20f | 2017-11-28 14:44:32 +0000 | [diff] [blame] | 695 | StoreSize += DL->getTypeStoreSize(I->getValueOperand()->getType()); |
Haicheng Wu | f1c00a2 | 2016-01-26 02:27:47 +0000 | [diff] [blame] | 696 | // Move to the next value in the chain. |
| 697 | I = ConsecutiveChain[I]; |
| 698 | } |
| 699 | |
| 700 | Value *StoredVal = HeadStore->getValueOperand(); |
| 701 | Value *StorePtr = HeadStore->getPointerOperand(); |
| 702 | const SCEVAddRecExpr *StoreEv = cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr)); |
Chad Rosier | 4acff96 | 2016-02-12 19:05:27 +0000 | [diff] [blame] | 703 | APInt Stride = getStoreStride(StoreEv); |
Haicheng Wu | f1c00a2 | 2016-01-26 02:27:47 +0000 | [diff] [blame] | 704 | |
| 705 | // Check to see if the stride matches the size of the stores. If so, then |
| 706 | // we know that every byte is touched in the loop. |
| 707 | if (StoreSize != Stride && StoreSize != -Stride) |
| 708 | continue; |
| 709 | |
| 710 | bool NegStride = StoreSize == -Stride; |
| 711 | |
| 712 | if (processLoopStridedStore(StorePtr, StoreSize, HeadStore->getAlignment(), |
| 713 | StoredVal, HeadStore, AdjacentStores, StoreEv, |
| 714 | BECount, NegStride)) { |
| 715 | TransformedStores.insert(AdjacentStores.begin(), AdjacentStores.end()); |
| 716 | Changed = true; |
| 717 | } |
| 718 | } |
| 719 | |
| 720 | return Changed; |
Chris Lattner | 81ae3f2 | 2010-12-26 19:39:38 +0000 | [diff] [blame] | 721 | } |
| 722 | |
Chris Lattner | 8643810 | 2011-01-04 07:46:33 +0000 | [diff] [blame] | 723 | /// processLoopMemSet - See if this memset can be promoted to a large memset. |
Chandler Carruth | bad690e | 2015-08-12 23:06:37 +0000 | [diff] [blame] | 724 | bool LoopIdiomRecognize::processLoopMemSet(MemSetInst *MSI, |
| 725 | const SCEV *BECount) { |
Chris Lattner | 8643810 | 2011-01-04 07:46:33 +0000 | [diff] [blame] | 726 | // We can only handle non-volatile memsets with a constant size. |
Chandler Carruth | bad690e | 2015-08-12 23:06:37 +0000 | [diff] [blame] | 727 | if (MSI->isVolatile() || !isa<ConstantInt>(MSI->getLength())) |
| 728 | return false; |
Chris Lattner | 8643810 | 2011-01-04 07:46:33 +0000 | [diff] [blame] | 729 | |
Chris Lattner | e6b261f | 2011-02-18 22:22:15 +0000 | [diff] [blame] | 730 | // If we're not allowed to hack on memset, we fail. |
Ahmed Bougacha | 7f97193 | 2016-04-27 19:04:46 +0000 | [diff] [blame] | 731 | if (!HasMemset) |
Chris Lattner | e6b261f | 2011-02-18 22:22:15 +0000 | [diff] [blame] | 732 | return false; |
Andrew Trick | 328b223 | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 733 | |
Chris Lattner | 8643810 | 2011-01-04 07:46:33 +0000 | [diff] [blame] | 734 | Value *Pointer = MSI->getDest(); |
Andrew Trick | 328b223 | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 735 | |
Chris Lattner | 8643810 | 2011-01-04 07:46:33 +0000 | [diff] [blame] | 736 | // See if the pointer expression is an AddRec like {base,+,1} on the current |
| 737 | // loop, which indicates a strided store. If we have something else, it's a |
| 738 | // random store we can't handle. |
| 739 | const SCEVAddRecExpr *Ev = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Pointer)); |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 740 | if (!Ev || Ev->getLoop() != CurLoop || !Ev->isAffine()) |
Chris Lattner | 8643810 | 2011-01-04 07:46:33 +0000 | [diff] [blame] | 741 | return false; |
| 742 | |
| 743 | // Reject memsets that are so large that they overflow an unsigned. |
| 744 | uint64_t SizeInBytes = cast<ConstantInt>(MSI->getLength())->getZExtValue(); |
| 745 | if ((SizeInBytes >> 32) != 0) |
| 746 | return false; |
Andrew Trick | 328b223 | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 747 | |
Chris Lattner | 8643810 | 2011-01-04 07:46:33 +0000 | [diff] [blame] | 748 | // Check to see if the stride matches the size of the memset. If so, then we |
| 749 | // know that every byte is touched in the loop. |
Chad Rosier | 81362a8 | 2016-02-12 21:03:23 +0000 | [diff] [blame] | 750 | const SCEVConstant *ConstStride = dyn_cast<SCEVConstant>(Ev->getOperand(1)); |
| 751 | if (!ConstStride) |
| 752 | return false; |
Andrew Trick | 328b223 | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 753 | |
Chad Rosier | 81362a8 | 2016-02-12 21:03:23 +0000 | [diff] [blame] | 754 | APInt Stride = ConstStride->getAPInt(); |
| 755 | if (SizeInBytes != Stride && SizeInBytes != -Stride) |
Chris Lattner | 8643810 | 2011-01-04 07:46:33 +0000 | [diff] [blame] | 756 | return false; |
Andrew Trick | 328b223 | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 757 | |
Haicheng Wu | 9d6c940 | 2016-01-04 21:43:14 +0000 | [diff] [blame] | 758 | // Verify that the memset value is loop invariant. If not, we can't promote |
| 759 | // the memset. |
| 760 | Value *SplatValue = MSI->getValue(); |
| 761 | if (!SplatValue || !CurLoop->isLoopInvariant(SplatValue)) |
| 762 | return false; |
| 763 | |
Haicheng Wu | f1c00a2 | 2016-01-26 02:27:47 +0000 | [diff] [blame] | 764 | SmallPtrSet<Instruction *, 1> MSIs; |
| 765 | MSIs.insert(MSI); |
Chad Rosier | 81362a8 | 2016-02-12 21:03:23 +0000 | [diff] [blame] | 766 | bool NegStride = SizeInBytes == -Stride; |
Chris Lattner | 0f4a640 | 2011-02-19 19:31:39 +0000 | [diff] [blame] | 767 | return processLoopStridedStore(Pointer, (unsigned)SizeInBytes, |
Daniel Neilson | fb99a49 | 2018-02-08 17:33:08 +0000 | [diff] [blame] | 768 | MSI->getDestAlignment(), SplatValue, MSI, MSIs, |
| 769 | Ev, BECount, NegStride, /*IsLoopMemset=*/true); |
Chris Lattner | 8643810 | 2011-01-04 07:46:33 +0000 | [diff] [blame] | 770 | } |
| 771 | |
Chandler Carruth | 099f5cb0 | 2012-11-02 08:33:25 +0000 | [diff] [blame] | 772 | /// mayLoopAccessLocation - Return true if the specified loop might access the |
| 773 | /// specified pointer location, which is a loop-strided access. The 'Access' |
| 774 | /// argument specifies what the verboten forms of access are (read or write). |
Haicheng Wu | f1c00a2 | 2016-01-26 02:27:47 +0000 | [diff] [blame] | 775 | static bool |
| 776 | mayLoopAccessLocation(Value *Ptr, ModRefInfo Access, Loop *L, |
| 777 | const SCEV *BECount, unsigned StoreSize, |
| 778 | AliasAnalysis &AA, |
| 779 | SmallPtrSetImpl<Instruction *> &IgnoredStores) { |
Chandler Carruth | 099f5cb0 | 2012-11-02 08:33:25 +0000 | [diff] [blame] | 780 | // Get the location that may be stored across the loop. Since the access is |
| 781 | // strided positively through memory, we say that the modified location starts |
| 782 | // at the pointer and has infinite size. |
George Burgess IV | 7e12875 | 2018-12-24 05:55:50 +0000 | [diff] [blame] | 783 | LocationSize AccessSize = LocationSize::unknown(); |
Chandler Carruth | 099f5cb0 | 2012-11-02 08:33:25 +0000 | [diff] [blame] | 784 | |
| 785 | // If the loop iterates a fixed number of times, we can refine the access size |
| 786 | // to be exactly the size of the memset, which is (BECount+1)*StoreSize |
| 787 | if (const SCEVConstant *BECst = dyn_cast<SCEVConstant>(BECount)) |
George Burgess IV | 7e12875 | 2018-12-24 05:55:50 +0000 | [diff] [blame] | 788 | AccessSize = LocationSize::precise((BECst->getValue()->getZExtValue() + 1) * |
| 789 | StoreSize); |
Chandler Carruth | 099f5cb0 | 2012-11-02 08:33:25 +0000 | [diff] [blame] | 790 | |
| 791 | // TODO: For this to be really effective, we have to dive into the pointer |
| 792 | // operand in the store. Store to &A[i] of 100 will always return may alias |
| 793 | // with store of &A[100], we need to StoreLoc to be "A" with size of 100, |
| 794 | // which will then no-alias a store to &A[100]. |
Chandler Carruth | ac80dc7 | 2015-06-17 07:18:54 +0000 | [diff] [blame] | 795 | MemoryLocation StoreLoc(Ptr, AccessSize); |
Chandler Carruth | 099f5cb0 | 2012-11-02 08:33:25 +0000 | [diff] [blame] | 796 | |
| 797 | for (Loop::block_iterator BI = L->block_begin(), E = L->block_end(); BI != E; |
| 798 | ++BI) |
Benjamin Kramer | 135f735 | 2016-06-26 12:28:59 +0000 | [diff] [blame] | 799 | for (Instruction &I : **BI) |
| 800 | if (IgnoredStores.count(&I) == 0 && |
Alina Sbirlea | 18fea01 | 2017-12-06 19:56:37 +0000 | [diff] [blame] | 801 | isModOrRefSet( |
| 802 | intersectModRef(AA.getModRefInfo(&I, StoreLoc), Access))) |
Chandler Carruth | 099f5cb0 | 2012-11-02 08:33:25 +0000 | [diff] [blame] | 803 | return true; |
| 804 | |
| 805 | return false; |
| 806 | } |
| 807 | |
Chad Rosier | ed0c7d1 | 2015-11-13 19:11:07 +0000 | [diff] [blame] | 808 | // If we have a negative stride, Start refers to the end of the memory location |
| 809 | // we're trying to memset. Therefore, we need to recompute the base pointer, |
| 810 | // which is just Start - BECount*Size. |
| 811 | static const SCEV *getStartForNegStride(const SCEV *Start, const SCEV *BECount, |
| 812 | Type *IntPtr, unsigned StoreSize, |
| 813 | ScalarEvolution *SE) { |
| 814 | const SCEV *Index = SE->getTruncateOrZeroExtend(BECount, IntPtr); |
| 815 | if (StoreSize != 1) |
| 816 | Index = SE->getMulExpr(Index, SE->getConstant(IntPtr, StoreSize), |
| 817 | SCEV::FlagNUW); |
| 818 | return SE->getMinusSCEV(Start, Index); |
| 819 | } |
| 820 | |
Chandler Carruth | 1dc34c6 | 2017-07-25 10:48:32 +0000 | [diff] [blame] | 821 | /// Compute the number of bytes as a SCEV from the backedge taken count. |
| 822 | /// |
| 823 | /// This also maps the SCEV into the provided type and tries to handle the |
| 824 | /// computation in a way that will fold cleanly. |
| 825 | static const SCEV *getNumBytes(const SCEV *BECount, Type *IntPtr, |
| 826 | unsigned StoreSize, Loop *CurLoop, |
| 827 | const DataLayout *DL, ScalarEvolution *SE) { |
| 828 | const SCEV *NumBytesS; |
| 829 | // The # stored bytes is (BECount+1)*Size. Expand the trip count out to |
| 830 | // pointer size if it isn't already. |
| 831 | // |
| 832 | // If we're going to need to zero extend the BE count, check if we can add |
| 833 | // one to it prior to zero extending without overflow. Provided this is safe, |
| 834 | // it allows better simplification of the +1. |
| 835 | if (DL->getTypeSizeInBits(BECount->getType()) < |
| 836 | DL->getTypeSizeInBits(IntPtr) && |
| 837 | SE->isLoopEntryGuardedByCond( |
| 838 | CurLoop, ICmpInst::ICMP_NE, BECount, |
| 839 | SE->getNegativeSCEV(SE->getOne(BECount->getType())))) { |
| 840 | NumBytesS = SE->getZeroExtendExpr( |
| 841 | SE->getAddExpr(BECount, SE->getOne(BECount->getType()), SCEV::FlagNUW), |
| 842 | IntPtr); |
| 843 | } else { |
| 844 | NumBytesS = SE->getAddExpr(SE->getTruncateOrZeroExtend(BECount, IntPtr), |
| 845 | SE->getOne(IntPtr), SCEV::FlagNUW); |
| 846 | } |
| 847 | |
| 848 | // And scale it based on the store size. |
| 849 | if (StoreSize != 1) { |
| 850 | NumBytesS = SE->getMulExpr(NumBytesS, SE->getConstant(IntPtr, StoreSize), |
| 851 | SCEV::FlagNUW); |
| 852 | } |
| 853 | return NumBytesS; |
| 854 | } |
| 855 | |
Chris Lattner | 0f4a640 | 2011-02-19 19:31:39 +0000 | [diff] [blame] | 856 | /// processLoopStridedStore - We see a strided store of some value. If we can |
| 857 | /// 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] | 858 | bool LoopIdiomRecognize::processLoopStridedStore( |
| 859 | Value *DestPtr, unsigned StoreSize, unsigned StoreAlignment, |
Haicheng Wu | f1c00a2 | 2016-01-26 02:27:47 +0000 | [diff] [blame] | 860 | Value *StoredVal, Instruction *TheStore, |
| 861 | SmallPtrSetImpl<Instruction *> &Stores, const SCEVAddRecExpr *Ev, |
Andrew Kaylor | 7cdf01e | 2016-08-11 18:28:33 +0000 | [diff] [blame] | 862 | const SCEV *BECount, bool NegStride, bool IsLoopMemset) { |
Chris Lattner | 0f4a640 | 2011-02-19 19:31:39 +0000 | [diff] [blame] | 863 | Value *SplatValue = isBytewiseValue(StoredVal); |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 864 | Constant *PatternValue = nullptr; |
Matt Arsenault | 009faed | 2013-09-11 05:09:42 +0000 | [diff] [blame] | 865 | |
Haicheng Wu | 9d6c940 | 2016-01-04 21:43:14 +0000 | [diff] [blame] | 866 | if (!SplatValue) |
| 867 | PatternValue = getMemSetPatternValue(StoredVal, DL); |
| 868 | |
| 869 | assert((SplatValue || PatternValue) && |
| 870 | "Expected either splat value or pattern value."); |
Andrew Trick | 328b223 | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 871 | |
Chris Lattner | c4ca7ab | 2011-05-22 17:39:56 +0000 | [diff] [blame] | 872 | // The trip count of the loop and the base pointer of the addrec SCEV is |
| 873 | // guaranteed to be loop invariant, which means that it should dominate the |
| 874 | // header. This allows us to insert code for it in the preheader. |
Haicheng Wu | 9d6c940 | 2016-01-04 21:43:14 +0000 | [diff] [blame] | 875 | unsigned DestAS = DestPtr->getType()->getPointerAddressSpace(); |
Chris Lattner | c4ca7ab | 2011-05-22 17:39:56 +0000 | [diff] [blame] | 876 | BasicBlock *Preheader = CurLoop->getLoopPreheader(); |
| 877 | IRBuilder<> Builder(Preheader->getTerminator()); |
Chad Rosier | 43f9b48 | 2015-11-06 16:33:57 +0000 | [diff] [blame] | 878 | SCEVExpander Expander(*SE, *DL, "loop-idiom"); |
Andrew Trick | 60ab3ef | 2011-06-28 05:04:16 +0000 | [diff] [blame] | 879 | |
Matt Arsenault | 009faed | 2013-09-11 05:09:42 +0000 | [diff] [blame] | 880 | Type *DestInt8PtrTy = Builder.getInt8PtrTy(DestAS); |
Chad Rosier | 43f9b48 | 2015-11-06 16:33:57 +0000 | [diff] [blame] | 881 | Type *IntPtr = Builder.getIntPtrTy(*DL, DestAS); |
Chad Rosier | 7967614 | 2015-10-28 14:38:49 +0000 | [diff] [blame] | 882 | |
| 883 | const SCEV *Start = Ev->getStart(); |
Chad Rosier | 2fa50a7 | 2015-11-13 19:13:40 +0000 | [diff] [blame] | 884 | // Handle negative strided loops. |
Chad Rosier | ed0c7d1 | 2015-11-13 19:11:07 +0000 | [diff] [blame] | 885 | if (NegStride) |
| 886 | Start = getStartForNegStride(Start, BECount, IntPtr, StoreSize, SE); |
Matt Arsenault | 009faed | 2013-09-11 05:09:42 +0000 | [diff] [blame] | 887 | |
Aditya Kumar | 1c42d13 | 2017-05-05 14:49:45 +0000 | [diff] [blame] | 888 | // TODO: ideally we should still be able to generate memset if SCEV expander |
| 889 | // is taught to generate the dependencies at the latest point. |
| 890 | if (!isSafeToExpand(Start, *SE)) |
| 891 | return false; |
| 892 | |
Chris Lattner | 29e14ed | 2010-12-26 23:42:51 +0000 | [diff] [blame] | 893 | // 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] | 894 | // this into a memset in the loop preheader now if we want. However, this |
| 895 | // 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] | 896 | // or write to the aliased location. Check for any overlap by generating the |
| 897 | // base pointer and checking the region. |
Chad Rosier | 7967614 | 2015-10-28 14:38:49 +0000 | [diff] [blame] | 898 | Value *BasePtr = |
| 899 | Expander.expandCodeFor(Start, DestInt8PtrTy, Preheader->getTerminator()); |
Alina Sbirlea | 193429f | 2017-12-07 22:41:34 +0000 | [diff] [blame] | 900 | if (mayLoopAccessLocation(BasePtr, ModRefInfo::ModRef, CurLoop, BECount, |
| 901 | StoreSize, *AA, Stores)) { |
Chandler Carruth | 099f5cb0 | 2012-11-02 08:33:25 +0000 | [diff] [blame] | 902 | Expander.clear(); |
| 903 | // If we generated new code for the base pointer, clean up. |
Benjamin Kramer | f094d77 | 2015-02-07 21:37:08 +0000 | [diff] [blame] | 904 | RecursivelyDeleteTriviallyDeadInstructions(BasePtr, TLI); |
Chandler Carruth | 099f5cb0 | 2012-11-02 08:33:25 +0000 | [diff] [blame] | 905 | return false; |
| 906 | } |
| 907 | |
Andrew Kaylor | 7cdf01e | 2016-08-11 18:28:33 +0000 | [diff] [blame] | 908 | if (avoidLIRForMultiBlockLoop(/*IsMemset=*/true, IsLoopMemset)) |
| 909 | return false; |
| 910 | |
Chris Lattner | c4ca7ab | 2011-05-22 17:39:56 +0000 | [diff] [blame] | 911 | // Okay, everything looks good, insert the memset. |
| 912 | |
Chandler Carruth | bad690e | 2015-08-12 23:06:37 +0000 | [diff] [blame] | 913 | const SCEV *NumBytesS = |
Chandler Carruth | 1dc34c6 | 2017-07-25 10:48:32 +0000 | [diff] [blame] | 914 | getNumBytes(BECount, IntPtr, StoreSize, CurLoop, DL, SE); |
Andrew Trick | 328b223 | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 915 | |
Aditya Kumar | 1c42d13 | 2017-05-05 14:49:45 +0000 | [diff] [blame] | 916 | // TODO: ideally we should still be able to generate memset if SCEV expander |
| 917 | // is taught to generate the dependencies at the latest point. |
| 918 | if (!isSafeToExpand(NumBytesS, *SE)) |
| 919 | return false; |
| 920 | |
Andrew Trick | 328b223 | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 921 | Value *NumBytes = |
Chandler Carruth | bad690e | 2015-08-12 23:06:37 +0000 | [diff] [blame] | 922 | Expander.expandCodeFor(NumBytesS, IntPtr, Preheader->getTerminator()); |
Andrew Trick | 328b223 | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 923 | |
Devang Patel | d00c628 | 2011-03-07 22:43:45 +0000 | [diff] [blame] | 924 | CallInst *NewCall; |
Matt Arsenault | 5df49bd | 2013-09-11 05:09:35 +0000 | [diff] [blame] | 925 | if (SplatValue) { |
Chandler Carruth | bad690e | 2015-08-12 23:06:37 +0000 | [diff] [blame] | 926 | NewCall = |
| 927 | Builder.CreateMemSet(BasePtr, SplatValue, NumBytes, StoreAlignment); |
Matt Arsenault | 5df49bd | 2013-09-11 05:09:35 +0000 | [diff] [blame] | 928 | } else { |
Matt Arsenault | 009faed | 2013-09-11 05:09:42 +0000 | [diff] [blame] | 929 | // Everything is emitted in default address space |
| 930 | Type *Int8PtrTy = DestInt8PtrTy; |
| 931 | |
Sanjay Patel | af674fb | 2015-12-14 17:24:23 +0000 | [diff] [blame] | 932 | Module *M = TheStore->getModule(); |
David Bolvansky | 7c7760d | 2018-10-16 21:18:31 +0000 | [diff] [blame] | 933 | StringRef FuncName = "memset_pattern16"; |
Mehdi Amini | db11fdf | 2017-04-06 20:23:57 +0000 | [diff] [blame] | 934 | Value *MSP = |
David Bolvansky | 7c7760d | 2018-10-16 21:18:31 +0000 | [diff] [blame] | 935 | M->getOrInsertFunction(FuncName, Builder.getVoidTy(), |
Serge Guelton | 59a2d7b | 2017-04-11 15:01:18 +0000 | [diff] [blame] | 936 | Int8PtrTy, Int8PtrTy, IntPtr); |
David Bolvansky | 7c7760d | 2018-10-16 21:18:31 +0000 | [diff] [blame] | 937 | inferLibFuncAttributes(M, FuncName, *TLI); |
Andrew Trick | 328b223 | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 938 | |
Chris Lattner | 0f4a640 | 2011-02-19 19:31:39 +0000 | [diff] [blame] | 939 | // Otherwise we should form a memset_pattern16. PatternValue is known to be |
| 940 | // an constant array of 16-bytes. Plop the value into a mergable global. |
| 941 | GlobalVariable *GV = new GlobalVariable(*M, PatternValue->getType(), true, |
Benjamin Kramer | 838752d | 2015-03-03 00:17:09 +0000 | [diff] [blame] | 942 | GlobalValue::PrivateLinkage, |
Chris Lattner | 0f4a640 | 2011-02-19 19:31:39 +0000 | [diff] [blame] | 943 | PatternValue, ".memset_pattern"); |
Peter Collingbourne | 96efdd6 | 2016-06-14 21:01:22 +0000 | [diff] [blame] | 944 | GV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global); // Ok to merge these. |
Chris Lattner | 0f4a640 | 2011-02-19 19:31:39 +0000 | [diff] [blame] | 945 | GV->setAlignment(16); |
Matt Arsenault | 009faed | 2013-09-11 05:09:42 +0000 | [diff] [blame] | 946 | Value *PatternPtr = ConstantExpr::getBitCast(GV, Int8PtrTy); |
David Blaikie | ff6409d | 2015-05-18 22:13:54 +0000 | [diff] [blame] | 947 | NewCall = Builder.CreateCall(MSP, {BasePtr, PatternPtr, NumBytes}); |
Chris Lattner | 0f4a640 | 2011-02-19 19:31:39 +0000 | [diff] [blame] | 948 | } |
Andrew Trick | 328b223 | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 949 | |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 950 | LLVM_DEBUG(dbgs() << " Formed memset: " << *NewCall << "\n" |
| 951 | << " from store to: " << *Ev << " at: " << *TheStore |
| 952 | << "\n"); |
Devang Patel | d00c628 | 2011-03-07 22:43:45 +0000 | [diff] [blame] | 953 | NewCall->setDebugLoc(TheStore->getDebugLoc()); |
Andrew Trick | 328b223 | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 954 | |
Chris Lattner | b9fe685 | 2010-12-27 00:03:23 +0000 | [diff] [blame] | 955 | // Okay, the memset has been formed. Zap the original store and anything that |
| 956 | // feeds into it. |
Haicheng Wu | f1c00a2 | 2016-01-26 02:27:47 +0000 | [diff] [blame] | 957 | for (auto *I : Stores) |
David Majnemer | 41ff4fd | 2016-06-20 16:07:38 +0000 | [diff] [blame] | 958 | deleteDeadInstruction(I); |
Chris Lattner | 12f91be | 2011-01-02 07:36:44 +0000 | [diff] [blame] | 959 | ++NumMemSet; |
Chris Lattner | 29e14ed | 2010-12-26 23:42:51 +0000 | [diff] [blame] | 960 | return true; |
| 961 | } |
| 962 | |
Chad Rosier | 1cd3da1 | 2015-11-19 21:33:07 +0000 | [diff] [blame] | 963 | /// If the stored value is a strided load in the same loop with the same stride |
| 964 | /// this may be transformable into a memcpy. This kicks in for stuff like |
Xin Tong | a41bf70 | 2017-05-01 23:08:19 +0000 | [diff] [blame] | 965 | /// for (i) A[i] = B[i]; |
Haicheng Wu | 9d6c940 | 2016-01-04 21:43:14 +0000 | [diff] [blame] | 966 | bool LoopIdiomRecognize::processLoopStoreOfLoopLoad(StoreInst *SI, |
| 967 | const SCEV *BECount) { |
Anna Thomas | b2a212c | 2017-06-06 16:45:25 +0000 | [diff] [blame] | 968 | assert(SI->isUnordered() && "Expected only non-volatile non-ordered stores."); |
Haicheng Wu | 9d6c940 | 2016-01-04 21:43:14 +0000 | [diff] [blame] | 969 | |
| 970 | Value *StorePtr = SI->getPointerOperand(); |
| 971 | const SCEVAddRecExpr *StoreEv = cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr)); |
Chad Rosier | 4acff96 | 2016-02-12 19:05:27 +0000 | [diff] [blame] | 972 | APInt Stride = getStoreStride(StoreEv); |
Jonas Paulsson | f0ff20f | 2017-11-28 14:44:32 +0000 | [diff] [blame] | 973 | unsigned StoreSize = DL->getTypeStoreSize(SI->getValueOperand()->getType()); |
Haicheng Wu | 9d6c940 | 2016-01-04 21:43:14 +0000 | [diff] [blame] | 974 | bool NegStride = StoreSize == -Stride; |
Andrew Trick | 328b223 | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 975 | |
Chad Rosier | fddc01f | 2015-11-19 18:22:21 +0000 | [diff] [blame] | 976 | // The store must be feeding a non-volatile load. |
Haicheng Wu | 9d6c940 | 2016-01-04 21:43:14 +0000 | [diff] [blame] | 977 | LoadInst *LI = cast<LoadInst>(SI->getValueOperand()); |
Anna Thomas | b2a212c | 2017-06-06 16:45:25 +0000 | [diff] [blame] | 978 | assert(LI->isUnordered() && "Expected only non-volatile non-ordered loads."); |
Chad Rosier | fddc01f | 2015-11-19 18:22:21 +0000 | [diff] [blame] | 979 | |
| 980 | // See if the pointer expression is an AddRec like {base,+,1} on the current |
| 981 | // loop, which indicates a strided load. If we have something else, it's a |
| 982 | // random load we can't handle. |
Chad Rosier | 3ecc8d8 | 2015-11-19 18:25:11 +0000 | [diff] [blame] | 983 | const SCEVAddRecExpr *LoadEv = |
Haicheng Wu | 9d6c940 | 2016-01-04 21:43:14 +0000 | [diff] [blame] | 984 | cast<SCEVAddRecExpr>(SE->getSCEV(LI->getPointerOperand())); |
Andrew Trick | 328b223 | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 985 | |
Chris Lattner | c4ca7ab | 2011-05-22 17:39:56 +0000 | [diff] [blame] | 986 | // The trip count of the loop and the base pointer of the addrec SCEV is |
| 987 | // guaranteed to be loop invariant, which means that it should dominate the |
| 988 | // header. This allows us to insert code for it in the preheader. |
| 989 | BasicBlock *Preheader = CurLoop->getLoopPreheader(); |
| 990 | IRBuilder<> Builder(Preheader->getTerminator()); |
Chad Rosier | 43f9b48 | 2015-11-06 16:33:57 +0000 | [diff] [blame] | 991 | SCEVExpander Expander(*SE, *DL, "loop-idiom"); |
Andrew Trick | 60ab3ef | 2011-06-28 05:04:16 +0000 | [diff] [blame] | 992 | |
Chad Rosier | cc299b6 | 2015-11-13 21:51:02 +0000 | [diff] [blame] | 993 | const SCEV *StrStart = StoreEv->getStart(); |
| 994 | unsigned StrAS = SI->getPointerAddressSpace(); |
| 995 | Type *IntPtrTy = Builder.getIntPtrTy(*DL, StrAS); |
| 996 | |
| 997 | // Handle negative strided loops. |
| 998 | if (NegStride) |
| 999 | StrStart = getStartForNegStride(StrStart, BECount, IntPtrTy, StoreSize, SE); |
| 1000 | |
Chris Lattner | 85b6d81 | 2011-01-02 03:37:56 +0000 | [diff] [blame] | 1001 | // 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] | 1002 | // this into a memcpy in the loop preheader now if we want. However, this |
| 1003 | // would be unsafe to do if there is anything else in the loop that may read |
| 1004 | // or write the memory region we're storing to. This includes the load that |
| 1005 | // feeds the stores. Check for an alias by generating the base address and |
| 1006 | // checking everything. |
Chandler Carruth | bad690e | 2015-08-12 23:06:37 +0000 | [diff] [blame] | 1007 | Value *StoreBasePtr = Expander.expandCodeFor( |
Chad Rosier | cc299b6 | 2015-11-13 21:51:02 +0000 | [diff] [blame] | 1008 | StrStart, Builder.getInt8PtrTy(StrAS), Preheader->getTerminator()); |
Chandler Carruth | 099f5cb0 | 2012-11-02 08:33:25 +0000 | [diff] [blame] | 1009 | |
Haicheng Wu | f1c00a2 | 2016-01-26 02:27:47 +0000 | [diff] [blame] | 1010 | SmallPtrSet<Instruction *, 1> Stores; |
| 1011 | Stores.insert(SI); |
Alina Sbirlea | 193429f | 2017-12-07 22:41:34 +0000 | [diff] [blame] | 1012 | if (mayLoopAccessLocation(StoreBasePtr, ModRefInfo::ModRef, CurLoop, BECount, |
Haicheng Wu | f1c00a2 | 2016-01-26 02:27:47 +0000 | [diff] [blame] | 1013 | StoreSize, *AA, Stores)) { |
Chandler Carruth | 099f5cb0 | 2012-11-02 08:33:25 +0000 | [diff] [blame] | 1014 | Expander.clear(); |
| 1015 | // If we generated new code for the base pointer, clean up. |
Benjamin Kramer | f094d77 | 2015-02-07 21:37:08 +0000 | [diff] [blame] | 1016 | RecursivelyDeleteTriviallyDeadInstructions(StoreBasePtr, TLI); |
Chandler Carruth | 099f5cb0 | 2012-11-02 08:33:25 +0000 | [diff] [blame] | 1017 | return false; |
| 1018 | } |
| 1019 | |
Chad Rosier | cc299b6 | 2015-11-13 21:51:02 +0000 | [diff] [blame] | 1020 | const SCEV *LdStart = LoadEv->getStart(); |
| 1021 | unsigned LdAS = LI->getPointerAddressSpace(); |
| 1022 | |
| 1023 | // Handle negative strided loops. |
| 1024 | if (NegStride) |
| 1025 | LdStart = getStartForNegStride(LdStart, BECount, IntPtrTy, StoreSize, SE); |
| 1026 | |
Chandler Carruth | 099f5cb0 | 2012-11-02 08:33:25 +0000 | [diff] [blame] | 1027 | // For a memcpy, we have to make sure that the input array is not being |
| 1028 | // mutated by the loop. |
Chandler Carruth | bad690e | 2015-08-12 23:06:37 +0000 | [diff] [blame] | 1029 | Value *LoadBasePtr = Expander.expandCodeFor( |
Chad Rosier | cc299b6 | 2015-11-13 21:51:02 +0000 | [diff] [blame] | 1030 | LdStart, Builder.getInt8PtrTy(LdAS), Preheader->getTerminator()); |
Chris Lattner | c4ca7ab | 2011-05-22 17:39:56 +0000 | [diff] [blame] | 1031 | |
Alina Sbirlea | 193429f | 2017-12-07 22:41:34 +0000 | [diff] [blame] | 1032 | if (mayLoopAccessLocation(LoadBasePtr, ModRefInfo::Mod, CurLoop, BECount, |
| 1033 | StoreSize, *AA, Stores)) { |
Chandler Carruth | 099f5cb0 | 2012-11-02 08:33:25 +0000 | [diff] [blame] | 1034 | Expander.clear(); |
| 1035 | // If we generated new code for the base pointer, clean up. |
Benjamin Kramer | f094d77 | 2015-02-07 21:37:08 +0000 | [diff] [blame] | 1036 | RecursivelyDeleteTriviallyDeadInstructions(LoadBasePtr, TLI); |
| 1037 | RecursivelyDeleteTriviallyDeadInstructions(StoreBasePtr, TLI); |
Chandler Carruth | 099f5cb0 | 2012-11-02 08:33:25 +0000 | [diff] [blame] | 1038 | return false; |
| 1039 | } |
| 1040 | |
Andrew Kaylor | 7cdf01e | 2016-08-11 18:28:33 +0000 | [diff] [blame] | 1041 | if (avoidLIRForMultiBlockLoop()) |
| 1042 | return false; |
| 1043 | |
Chris Lattner | c4ca7ab | 2011-05-22 17:39:56 +0000 | [diff] [blame] | 1044 | // Okay, everything is safe, we can transform this! |
Andrew Trick | 60ab3ef | 2011-06-28 05:04:16 +0000 | [diff] [blame] | 1045 | |
Chandler Carruth | bad690e | 2015-08-12 23:06:37 +0000 | [diff] [blame] | 1046 | const SCEV *NumBytesS = |
Chandler Carruth | 1dc34c6 | 2017-07-25 10:48:32 +0000 | [diff] [blame] | 1047 | getNumBytes(BECount, IntPtrTy, StoreSize, CurLoop, DL, SE); |
Daniel Neilson | 3faabbb | 2017-06-16 14:43:59 +0000 | [diff] [blame] | 1048 | |
| 1049 | Value *NumBytes = |
| 1050 | Expander.expandCodeFor(NumBytesS, IntPtrTy, Preheader->getTerminator()); |
| 1051 | |
Anna Thomas | b2a212c | 2017-06-06 16:45:25 +0000 | [diff] [blame] | 1052 | CallInst *NewCall = nullptr; |
| 1053 | // Check whether to generate an unordered atomic memcpy: |
Hiroshi Inoue | f209649 | 2018-06-14 05:41:49 +0000 | [diff] [blame] | 1054 | // If the load or store are atomic, then they must necessarily be unordered |
Anna Thomas | b2a212c | 2017-06-06 16:45:25 +0000 | [diff] [blame] | 1055 | // by previous checks. |
Daniel Neilson | 3faabbb | 2017-06-16 14:43:59 +0000 | [diff] [blame] | 1056 | if (!SI->isAtomic() && !LI->isAtomic()) |
Daniel Neilson | fb99a49 | 2018-02-08 17:33:08 +0000 | [diff] [blame] | 1057 | NewCall = Builder.CreateMemCpy(StoreBasePtr, SI->getAlignment(), |
| 1058 | LoadBasePtr, LI->getAlignment(), NumBytes); |
Daniel Neilson | 3faabbb | 2017-06-16 14:43:59 +0000 | [diff] [blame] | 1059 | else { |
Anna Thomas | b2a212c | 2017-06-06 16:45:25 +0000 | [diff] [blame] | 1060 | // We cannot allow unaligned ops for unordered load/store, so reject |
| 1061 | // anything where the alignment isn't at least the element size. |
Daniel Neilson | fb99a49 | 2018-02-08 17:33:08 +0000 | [diff] [blame] | 1062 | unsigned Align = std::min(SI->getAlignment(), LI->getAlignment()); |
Anna Thomas | b2a212c | 2017-06-06 16:45:25 +0000 | [diff] [blame] | 1063 | if (Align < StoreSize) |
| 1064 | return false; |
| 1065 | |
| 1066 | // If the element.atomic memcpy is not lowered into explicit |
| 1067 | // loads/stores later, then it will be lowered into an element-size |
| 1068 | // specific lib call. If the lib call doesn't exist for our store size, then |
| 1069 | // we shouldn't generate the memcpy. |
| 1070 | if (StoreSize > TTI->getAtomicMemIntrinsicMaxElementSize()) |
| 1071 | return false; |
| 1072 | |
Daniel Neilson | 6e4aa1e | 2017-11-10 19:38:12 +0000 | [diff] [blame] | 1073 | // Create the call. |
| 1074 | // Note that unordered atomic loads/stores are *required* by the spec to |
| 1075 | // have an alignment but non-atomic loads/stores may not. |
Daniel Neilson | 3faabbb | 2017-06-16 14:43:59 +0000 | [diff] [blame] | 1076 | NewCall = Builder.CreateElementUnorderedAtomicMemCpy( |
Daniel Neilson | 6e4aa1e | 2017-11-10 19:38:12 +0000 | [diff] [blame] | 1077 | StoreBasePtr, SI->getAlignment(), LoadBasePtr, LI->getAlignment(), |
| 1078 | NumBytes, StoreSize); |
Anna Thomas | b2a212c | 2017-06-06 16:45:25 +0000 | [diff] [blame] | 1079 | } |
Devang Patel | 0daa07e | 2011-05-04 21:37:05 +0000 | [diff] [blame] | 1080 | NewCall->setDebugLoc(SI->getDebugLoc()); |
Andrew Trick | 328b223 | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 1081 | |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 1082 | LLVM_DEBUG(dbgs() << " Formed memcpy: " << *NewCall << "\n" |
| 1083 | << " from load ptr=" << *LoadEv << " at: " << *LI << "\n" |
| 1084 | << " from store ptr=" << *StoreEv << " at: " << *SI |
| 1085 | << "\n"); |
Andrew Trick | 60ab3ef | 2011-06-28 05:04:16 +0000 | [diff] [blame] | 1086 | |
Chad Rosier | 7f08d80 | 2015-10-13 20:59:16 +0000 | [diff] [blame] | 1087 | // 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] | 1088 | // feeds into it. |
David Majnemer | 41ff4fd | 2016-06-20 16:07:38 +0000 | [diff] [blame] | 1089 | deleteDeadInstruction(SI); |
Chandler Carruth | 099f5cb0 | 2012-11-02 08:33:25 +0000 | [diff] [blame] | 1090 | ++NumMemCpy; |
Chris Lattner | 85b6d81 | 2011-01-02 03:37:56 +0000 | [diff] [blame] | 1091 | return true; |
| 1092 | } |
Chandler Carruth | d9c6070 | 2015-08-13 00:10:03 +0000 | [diff] [blame] | 1093 | |
Andrew Kaylor | 7cdf01e | 2016-08-11 18:28:33 +0000 | [diff] [blame] | 1094 | // When compiling for codesize we avoid idiom recognition for a multi-block loop |
| 1095 | // unless it is a loop_memset idiom or a memset/memcpy idiom in a nested loop. |
| 1096 | // |
| 1097 | bool LoopIdiomRecognize::avoidLIRForMultiBlockLoop(bool IsMemset, |
| 1098 | bool IsLoopMemset) { |
| 1099 | if (ApplyCodeSizeHeuristics && CurLoop->getNumBlocks() > 1) { |
| 1100 | if (!CurLoop->getParentLoop() && (!IsMemset || !IsLoopMemset)) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 1101 | LLVM_DEBUG(dbgs() << " " << CurLoop->getHeader()->getParent()->getName() |
| 1102 | << " : LIR " << (IsMemset ? "Memset" : "Memcpy") |
| 1103 | << " avoided: multi-block top-level loop\n"); |
Andrew Kaylor | 7cdf01e | 2016-08-11 18:28:33 +0000 | [diff] [blame] | 1104 | return true; |
| 1105 | } |
| 1106 | } |
| 1107 | |
| 1108 | return false; |
| 1109 | } |
| 1110 | |
Chandler Carruth | d9c6070 | 2015-08-13 00:10:03 +0000 | [diff] [blame] | 1111 | bool LoopIdiomRecognize::runOnNoncountableLoop() { |
Craig Topper | c9a6000 | 2018-12-26 21:59:48 +0000 | [diff] [blame^] | 1112 | return recognizePopcount() || recognizeAndInsertFFS(); |
Chandler Carruth | d9c6070 | 2015-08-13 00:10:03 +0000 | [diff] [blame] | 1113 | } |
Chandler Carruth | 8219a50 | 2015-08-13 00:44:29 +0000 | [diff] [blame] | 1114 | |
| 1115 | /// Check if the given conditional branch is based on the comparison between |
Craig Topper | c9a6000 | 2018-12-26 21:59:48 +0000 | [diff] [blame^] | 1116 | /// a variable and zero, and if the variable is non-zero or zero (JmpOnZero is |
| 1117 | /// true), the control yields to the loop entry. If the branch matches the |
| 1118 | /// behavior, the variable involved in the comparison is returned. This function |
| 1119 | /// will be called to see if the precondition and postcondition of the loop are |
| 1120 | /// in desirable form. |
| 1121 | static Value *matchCondition(BranchInst *BI, BasicBlock *LoopEntry, |
| 1122 | bool JmpOnZero = false) { |
Chandler Carruth | 8219a50 | 2015-08-13 00:44:29 +0000 | [diff] [blame] | 1123 | if (!BI || !BI->isConditional()) |
| 1124 | return nullptr; |
| 1125 | |
| 1126 | ICmpInst *Cond = dyn_cast<ICmpInst>(BI->getCondition()); |
| 1127 | if (!Cond) |
| 1128 | return nullptr; |
| 1129 | |
| 1130 | ConstantInt *CmpZero = dyn_cast<ConstantInt>(Cond->getOperand(1)); |
| 1131 | if (!CmpZero || !CmpZero->isZero()) |
| 1132 | return nullptr; |
| 1133 | |
Craig Topper | c9a6000 | 2018-12-26 21:59:48 +0000 | [diff] [blame^] | 1134 | BasicBlock *TrueSucc = BI->getSuccessor(0); |
| 1135 | BasicBlock *FalseSucc = BI->getSuccessor(1); |
| 1136 | if (JmpOnZero) |
| 1137 | std::swap(TrueSucc, FalseSucc); |
| 1138 | |
Chandler Carruth | 8219a50 | 2015-08-13 00:44:29 +0000 | [diff] [blame] | 1139 | ICmpInst::Predicate Pred = Cond->getPredicate(); |
Craig Topper | c9a6000 | 2018-12-26 21:59:48 +0000 | [diff] [blame^] | 1140 | if ((Pred == ICmpInst::ICMP_NE && TrueSucc == LoopEntry) || |
| 1141 | (Pred == ICmpInst::ICMP_EQ && FalseSucc == LoopEntry)) |
Chandler Carruth | 8219a50 | 2015-08-13 00:44:29 +0000 | [diff] [blame] | 1142 | return Cond->getOperand(0); |
| 1143 | |
| 1144 | return nullptr; |
| 1145 | } |
| 1146 | |
Davide Italiano | 4bc9119 | 2017-05-23 22:32:56 +0000 | [diff] [blame] | 1147 | // Check if the recurrence variable `VarX` is in the right form to create |
| 1148 | // the idiom. Returns the value coerced to a PHINode if so. |
| 1149 | static PHINode *getRecurrenceVar(Value *VarX, Instruction *DefX, |
| 1150 | BasicBlock *LoopEntry) { |
| 1151 | auto *PhiX = dyn_cast<PHINode>(VarX); |
| 1152 | if (PhiX && PhiX->getParent() == LoopEntry && |
| 1153 | (PhiX->getOperand(0) == DefX || PhiX->getOperand(1) == DefX)) |
| 1154 | return PhiX; |
| 1155 | return nullptr; |
| 1156 | } |
| 1157 | |
Chandler Carruth | 8219a50 | 2015-08-13 00:44:29 +0000 | [diff] [blame] | 1158 | /// Return true iff the idiom is detected in the loop. |
| 1159 | /// |
| 1160 | /// Additionally: |
| 1161 | /// 1) \p CntInst is set to the instruction counting the population bit. |
| 1162 | /// 2) \p CntPhi is set to the corresponding phi node. |
| 1163 | /// 3) \p Var is set to the value whose population bits are being counted. |
| 1164 | /// |
| 1165 | /// The core idiom we are trying to detect is: |
| 1166 | /// \code |
| 1167 | /// if (x0 != 0) |
| 1168 | /// goto loop-exit // the precondition of the loop |
| 1169 | /// cnt0 = init-val; |
| 1170 | /// do { |
| 1171 | /// x1 = phi (x0, x2); |
| 1172 | /// cnt1 = phi(cnt0, cnt2); |
| 1173 | /// |
| 1174 | /// cnt2 = cnt1 + 1; |
| 1175 | /// ... |
| 1176 | /// x2 = x1 & (x1 - 1); |
| 1177 | /// ... |
| 1178 | /// } while(x != 0); |
| 1179 | /// |
| 1180 | /// loop-exit: |
| 1181 | /// \endcode |
| 1182 | static bool detectPopcountIdiom(Loop *CurLoop, BasicBlock *PreCondBB, |
| 1183 | Instruction *&CntInst, PHINode *&CntPhi, |
| 1184 | Value *&Var) { |
| 1185 | // step 1: Check to see if the look-back branch match this pattern: |
| 1186 | // "if (a!=0) goto loop-entry". |
| 1187 | BasicBlock *LoopEntry; |
| 1188 | Instruction *DefX2, *CountInst; |
| 1189 | Value *VarX1, *VarX0; |
| 1190 | PHINode *PhiX, *CountPhi; |
| 1191 | |
| 1192 | DefX2 = CountInst = nullptr; |
| 1193 | VarX1 = VarX0 = nullptr; |
| 1194 | PhiX = CountPhi = nullptr; |
| 1195 | LoopEntry = *(CurLoop->block_begin()); |
| 1196 | |
| 1197 | // step 1: Check if the loop-back branch is in desirable form. |
| 1198 | { |
| 1199 | if (Value *T = matchCondition( |
| 1200 | dyn_cast<BranchInst>(LoopEntry->getTerminator()), LoopEntry)) |
| 1201 | DefX2 = dyn_cast<Instruction>(T); |
| 1202 | else |
| 1203 | return false; |
| 1204 | } |
| 1205 | |
| 1206 | // step 2: detect instructions corresponding to "x2 = x1 & (x1 - 1)" |
| 1207 | { |
| 1208 | if (!DefX2 || DefX2->getOpcode() != Instruction::And) |
| 1209 | return false; |
| 1210 | |
| 1211 | BinaryOperator *SubOneOp; |
| 1212 | |
| 1213 | if ((SubOneOp = dyn_cast<BinaryOperator>(DefX2->getOperand(0)))) |
| 1214 | VarX1 = DefX2->getOperand(1); |
| 1215 | else { |
| 1216 | VarX1 = DefX2->getOperand(0); |
| 1217 | SubOneOp = dyn_cast<BinaryOperator>(DefX2->getOperand(1)); |
| 1218 | } |
Craig Topper | 856fd68 | 2018-05-03 05:48:49 +0000 | [diff] [blame] | 1219 | if (!SubOneOp || SubOneOp->getOperand(0) != VarX1) |
Chandler Carruth | 8219a50 | 2015-08-13 00:44:29 +0000 | [diff] [blame] | 1220 | return false; |
| 1221 | |
Craig Topper | 8ef2abd | 2018-05-03 05:00:18 +0000 | [diff] [blame] | 1222 | ConstantInt *Dec = dyn_cast<ConstantInt>(SubOneOp->getOperand(1)); |
Chandler Carruth | 8219a50 | 2015-08-13 00:44:29 +0000 | [diff] [blame] | 1223 | if (!Dec || |
Craig Topper | 8ef2abd | 2018-05-03 05:00:18 +0000 | [diff] [blame] | 1224 | !((SubOneOp->getOpcode() == Instruction::Sub && Dec->isOne()) || |
| 1225 | (SubOneOp->getOpcode() == Instruction::Add && |
Craig Topper | 79ab643 | 2017-07-06 18:39:47 +0000 | [diff] [blame] | 1226 | Dec->isMinusOne()))) { |
Chandler Carruth | 8219a50 | 2015-08-13 00:44:29 +0000 | [diff] [blame] | 1227 | return false; |
| 1228 | } |
| 1229 | } |
| 1230 | |
| 1231 | // step 3: Check the recurrence of variable X |
Davide Italiano | 4bc9119 | 2017-05-23 22:32:56 +0000 | [diff] [blame] | 1232 | PhiX = getRecurrenceVar(VarX1, DefX2, LoopEntry); |
| 1233 | if (!PhiX) |
| 1234 | return false; |
Chandler Carruth | 8219a50 | 2015-08-13 00:44:29 +0000 | [diff] [blame] | 1235 | |
| 1236 | // step 4: Find the instruction which count the population: cnt2 = cnt1 + 1 |
| 1237 | { |
| 1238 | CountInst = nullptr; |
Duncan P. N. Exon Smith | be4d8cb | 2015-10-13 19:26:58 +0000 | [diff] [blame] | 1239 | for (BasicBlock::iterator Iter = LoopEntry->getFirstNonPHI()->getIterator(), |
Chandler Carruth | 8219a50 | 2015-08-13 00:44:29 +0000 | [diff] [blame] | 1240 | IterE = LoopEntry->end(); |
| 1241 | Iter != IterE; Iter++) { |
Duncan P. N. Exon Smith | be4d8cb | 2015-10-13 19:26:58 +0000 | [diff] [blame] | 1242 | Instruction *Inst = &*Iter; |
Chandler Carruth | 8219a50 | 2015-08-13 00:44:29 +0000 | [diff] [blame] | 1243 | if (Inst->getOpcode() != Instruction::Add) |
| 1244 | continue; |
| 1245 | |
| 1246 | ConstantInt *Inc = dyn_cast<ConstantInt>(Inst->getOperand(1)); |
| 1247 | if (!Inc || !Inc->isOne()) |
| 1248 | continue; |
| 1249 | |
Davide Italiano | 7bf95b9 | 2017-05-23 23:51:54 +0000 | [diff] [blame] | 1250 | PHINode *Phi = getRecurrenceVar(Inst->getOperand(0), Inst, LoopEntry); |
| 1251 | if (!Phi) |
Chandler Carruth | 8219a50 | 2015-08-13 00:44:29 +0000 | [diff] [blame] | 1252 | continue; |
| 1253 | |
| 1254 | // Check if the result of the instruction is live of the loop. |
| 1255 | bool LiveOutLoop = false; |
| 1256 | for (User *U : Inst->users()) { |
| 1257 | if ((cast<Instruction>(U))->getParent() != LoopEntry) { |
| 1258 | LiveOutLoop = true; |
| 1259 | break; |
| 1260 | } |
| 1261 | } |
| 1262 | |
| 1263 | if (LiveOutLoop) { |
| 1264 | CountInst = Inst; |
| 1265 | CountPhi = Phi; |
| 1266 | break; |
| 1267 | } |
| 1268 | } |
| 1269 | |
| 1270 | if (!CountInst) |
| 1271 | return false; |
| 1272 | } |
| 1273 | |
| 1274 | // step 5: check if the precondition is in this form: |
| 1275 | // "if (x != 0) goto loop-head ; else goto somewhere-we-don't-care;" |
| 1276 | { |
| 1277 | auto *PreCondBr = dyn_cast<BranchInst>(PreCondBB->getTerminator()); |
| 1278 | Value *T = matchCondition(PreCondBr, CurLoop->getLoopPreheader()); |
| 1279 | if (T != PhiX->getOperand(0) && T != PhiX->getOperand(1)) |
| 1280 | return false; |
| 1281 | |
| 1282 | CntInst = CountInst; |
| 1283 | CntPhi = CountPhi; |
| 1284 | Var = T; |
| 1285 | } |
| 1286 | |
| 1287 | return true; |
| 1288 | } |
| 1289 | |
Evgeny Stupachenko | 2fecd38 | 2017-05-15 19:08:56 +0000 | [diff] [blame] | 1290 | /// Return true if the idiom is detected in the loop. |
| 1291 | /// |
| 1292 | /// Additionally: |
| 1293 | /// 1) \p CntInst is set to the instruction Counting Leading Zeros (CTLZ) |
| 1294 | /// or nullptr if there is no such. |
| 1295 | /// 2) \p CntPhi is set to the corresponding phi node |
| 1296 | /// or nullptr if there is no such. |
| 1297 | /// 3) \p Var is set to the value whose CTLZ could be used. |
| 1298 | /// 4) \p DefX is set to the instruction calculating Loop exit condition. |
| 1299 | /// |
| 1300 | /// The core idiom we are trying to detect is: |
| 1301 | /// \code |
| 1302 | /// if (x0 == 0) |
| 1303 | /// goto loop-exit // the precondition of the loop |
| 1304 | /// cnt0 = init-val; |
| 1305 | /// do { |
| 1306 | /// x = phi (x0, x.next); //PhiX |
| 1307 | /// cnt = phi(cnt0, cnt.next); |
| 1308 | /// |
| 1309 | /// cnt.next = cnt + 1; |
| 1310 | /// ... |
| 1311 | /// x.next = x >> 1; // DefX |
| 1312 | /// ... |
| 1313 | /// } while(x.next != 0); |
| 1314 | /// |
| 1315 | /// loop-exit: |
| 1316 | /// \endcode |
Craig Topper | c9a6000 | 2018-12-26 21:59:48 +0000 | [diff] [blame^] | 1317 | static bool detectShiftUntilZeroIdiom(Loop *CurLoop, const DataLayout &DL, |
| 1318 | Intrinsic::ID &IntrinID, Value *&InitX, |
| 1319 | Instruction *&CntInst, PHINode *&CntPhi, |
| 1320 | Instruction *&DefX) { |
Evgeny Stupachenko | 2fecd38 | 2017-05-15 19:08:56 +0000 | [diff] [blame] | 1321 | BasicBlock *LoopEntry; |
| 1322 | Value *VarX = nullptr; |
| 1323 | |
| 1324 | DefX = nullptr; |
Evgeny Stupachenko | 2fecd38 | 2017-05-15 19:08:56 +0000 | [diff] [blame] | 1325 | CntInst = nullptr; |
| 1326 | CntPhi = nullptr; |
| 1327 | LoopEntry = *(CurLoop->block_begin()); |
| 1328 | |
| 1329 | // step 1: Check if the loop-back branch is in desirable form. |
| 1330 | if (Value *T = matchCondition( |
| 1331 | dyn_cast<BranchInst>(LoopEntry->getTerminator()), LoopEntry)) |
| 1332 | DefX = dyn_cast<Instruction>(T); |
| 1333 | else |
| 1334 | return false; |
| 1335 | |
Craig Topper | c9a6000 | 2018-12-26 21:59:48 +0000 | [diff] [blame^] | 1336 | // step 2: detect instructions corresponding to "x.next = x >> 1 or x << 1" |
| 1337 | if (!DefX || !DefX->isShift()) |
Evgeny Stupachenko | 2fecd38 | 2017-05-15 19:08:56 +0000 | [diff] [blame] | 1338 | return false; |
Craig Topper | c9a6000 | 2018-12-26 21:59:48 +0000 | [diff] [blame^] | 1339 | IntrinID = DefX->getOpcode() == Instruction::Shl ? Intrinsic::cttz : |
| 1340 | Intrinsic::ctlz; |
Evgeny Stupachenko | d699de2 | 2017-11-03 18:50:03 +0000 | [diff] [blame] | 1341 | ConstantInt *Shft = dyn_cast<ConstantInt>(DefX->getOperand(1)); |
| 1342 | if (!Shft || !Shft->isOne()) |
| 1343 | return false; |
Evgeny Stupachenko | 2fecd38 | 2017-05-15 19:08:56 +0000 | [diff] [blame] | 1344 | VarX = DefX->getOperand(0); |
| 1345 | |
| 1346 | // step 3: Check the recurrence of variable X |
Craig Topper | c9a6000 | 2018-12-26 21:59:48 +0000 | [diff] [blame^] | 1347 | PHINode *PhiX = getRecurrenceVar(VarX, DefX, LoopEntry); |
Davide Italiano | 4bc9119 | 2017-05-23 22:32:56 +0000 | [diff] [blame] | 1348 | if (!PhiX) |
Evgeny Stupachenko | 2fecd38 | 2017-05-15 19:08:56 +0000 | [diff] [blame] | 1349 | return false; |
| 1350 | |
Craig Topper | c9a6000 | 2018-12-26 21:59:48 +0000 | [diff] [blame^] | 1351 | InitX = PhiX->getIncomingValueForBlock(CurLoop->getLoopPreheader()); |
| 1352 | |
| 1353 | // Make sure the initial value can't be negative otherwise the ashr in the |
| 1354 | // loop might never reach zero which would make the loop infinite. |
| 1355 | if (DefX->getOpcode() == Instruction::AShr && !isKnownNonNegative(InitX, DL)) |
| 1356 | return false; |
| 1357 | |
Evgeny Stupachenko | 2fecd38 | 2017-05-15 19:08:56 +0000 | [diff] [blame] | 1358 | // step 4: Find the instruction which count the CTLZ: cnt.next = cnt + 1 |
| 1359 | // TODO: We can skip the step. If loop trip count is known (CTLZ), |
| 1360 | // then all uses of "cnt.next" could be optimized to the trip count |
| 1361 | // plus "cnt0". Currently it is not optimized. |
| 1362 | // This step could be used to detect POPCNT instruction: |
| 1363 | // cnt.next = cnt + (x.next & 1) |
| 1364 | for (BasicBlock::iterator Iter = LoopEntry->getFirstNonPHI()->getIterator(), |
| 1365 | IterE = LoopEntry->end(); |
| 1366 | Iter != IterE; Iter++) { |
| 1367 | Instruction *Inst = &*Iter; |
| 1368 | if (Inst->getOpcode() != Instruction::Add) |
| 1369 | continue; |
| 1370 | |
| 1371 | ConstantInt *Inc = dyn_cast<ConstantInt>(Inst->getOperand(1)); |
| 1372 | if (!Inc || !Inc->isOne()) |
| 1373 | continue; |
| 1374 | |
Davide Italiano | 7bf95b9 | 2017-05-23 23:51:54 +0000 | [diff] [blame] | 1375 | PHINode *Phi = getRecurrenceVar(Inst->getOperand(0), Inst, LoopEntry); |
| 1376 | if (!Phi) |
Evgeny Stupachenko | 2fecd38 | 2017-05-15 19:08:56 +0000 | [diff] [blame] | 1377 | continue; |
| 1378 | |
| 1379 | CntInst = Inst; |
| 1380 | CntPhi = Phi; |
| 1381 | break; |
| 1382 | } |
| 1383 | if (!CntInst) |
| 1384 | return false; |
| 1385 | |
| 1386 | return true; |
| 1387 | } |
| 1388 | |
Craig Topper | c9a6000 | 2018-12-26 21:59:48 +0000 | [diff] [blame^] | 1389 | /// Recognize CTLZ or CTTZ idiom in a non-countable loop and convert the loop |
| 1390 | /// to countable (with CTLZ / CTTZ trip count). If CTLZ / CTTZ inserted as a new |
| 1391 | /// trip count returns true; otherwise, returns false. |
| 1392 | bool LoopIdiomRecognize::recognizeAndInsertFFS() { |
Evgeny Stupachenko | 2fecd38 | 2017-05-15 19:08:56 +0000 | [diff] [blame] | 1393 | // Give up if the loop has multiple blocks or multiple backedges. |
| 1394 | if (CurLoop->getNumBackEdges() != 1 || CurLoop->getNumBlocks() != 1) |
| 1395 | return false; |
| 1396 | |
Craig Topper | c9a6000 | 2018-12-26 21:59:48 +0000 | [diff] [blame^] | 1397 | Intrinsic::ID IntrinID; |
| 1398 | Value *InitX; |
| 1399 | Instruction *DefX = nullptr; |
| 1400 | PHINode *CntPhi = nullptr; |
| 1401 | Instruction *CntInst = nullptr; |
| 1402 | // Help decide if transformation is profitable. For ShiftUntilZero idiom, |
| 1403 | // this is always 6. |
| 1404 | size_t IdiomCanonicalSize = 6; |
| 1405 | |
| 1406 | if (!detectShiftUntilZeroIdiom(CurLoop, *DL, IntrinID, InitX, |
| 1407 | CntInst, CntPhi, DefX)) |
Evgeny Stupachenko | 2fecd38 | 2017-05-15 19:08:56 +0000 | [diff] [blame] | 1408 | return false; |
| 1409 | |
| 1410 | bool IsCntPhiUsedOutsideLoop = false; |
| 1411 | for (User *U : CntPhi->users()) |
Craig Topper | 8304231 | 2018-05-04 01:04:24 +0000 | [diff] [blame] | 1412 | if (!CurLoop->contains(cast<Instruction>(U))) { |
Evgeny Stupachenko | 2fecd38 | 2017-05-15 19:08:56 +0000 | [diff] [blame] | 1413 | IsCntPhiUsedOutsideLoop = true; |
| 1414 | break; |
| 1415 | } |
| 1416 | bool IsCntInstUsedOutsideLoop = false; |
| 1417 | for (User *U : CntInst->users()) |
Craig Topper | 8304231 | 2018-05-04 01:04:24 +0000 | [diff] [blame] | 1418 | if (!CurLoop->contains(cast<Instruction>(U))) { |
Evgeny Stupachenko | 2fecd38 | 2017-05-15 19:08:56 +0000 | [diff] [blame] | 1419 | IsCntInstUsedOutsideLoop = true; |
| 1420 | break; |
| 1421 | } |
| 1422 | // If both CntInst and CntPhi are used outside the loop the profitability |
| 1423 | // is questionable. |
| 1424 | if (IsCntInstUsedOutsideLoop && IsCntPhiUsedOutsideLoop) |
| 1425 | return false; |
| 1426 | |
| 1427 | // For some CPUs result of CTLZ(X) intrinsic is undefined |
| 1428 | // when X is 0. If we can not guarantee X != 0, we need to check this |
| 1429 | // when expand. |
| 1430 | bool ZeroCheck = false; |
| 1431 | // It is safe to assume Preheader exist as it was checked in |
| 1432 | // parent function RunOnLoop. |
| 1433 | BasicBlock *PH = CurLoop->getLoopPreheader(); |
Craig Topper | 9a6c0bd | 2018-05-31 22:16:55 +0000 | [diff] [blame] | 1434 | |
Craig Topper | ed6acde | 2018-07-11 22:35:28 +0000 | [diff] [blame] | 1435 | // If we are using the count instruction outside the loop, make sure we |
| 1436 | // have a zero check as a precondition. Without the check the loop would run |
| 1437 | // one iteration for before any check of the input value. This means 0 and 1 |
| 1438 | // would have identical behavior in the original loop and thus |
| 1439 | if (!IsCntPhiUsedOutsideLoop) { |
| 1440 | auto *PreCondBB = PH->getSinglePredecessor(); |
| 1441 | if (!PreCondBB) |
| 1442 | return false; |
| 1443 | auto *PreCondBI = dyn_cast<BranchInst>(PreCondBB->getTerminator()); |
| 1444 | if (!PreCondBI) |
| 1445 | return false; |
| 1446 | if (matchCondition(PreCondBI, PH) != InitX) |
| 1447 | return false; |
| 1448 | ZeroCheck = true; |
| 1449 | } |
Evgeny Stupachenko | 2fecd38 | 2017-05-15 19:08:56 +0000 | [diff] [blame] | 1450 | |
Craig Topper | c9a6000 | 2018-12-26 21:59:48 +0000 | [diff] [blame^] | 1451 | // Check if CTLZ / CTTZ intrinsic is profitable. Assume it is always |
| 1452 | // profitable if we delete the loop. |
| 1453 | |
| 1454 | // the loop has only 6 instructions: |
Evgeny Stupachenko | 2fecd38 | 2017-05-15 19:08:56 +0000 | [diff] [blame] | 1455 | // %n.addr.0 = phi [ %n, %entry ], [ %shr, %while.cond ] |
| 1456 | // %i.0 = phi [ %i0, %entry ], [ %inc, %while.cond ] |
| 1457 | // %shr = ashr %n.addr.0, 1 |
| 1458 | // %tobool = icmp eq %shr, 0 |
| 1459 | // %inc = add nsw %i.0, 1 |
| 1460 | // br i1 %tobool |
| 1461 | |
Craig Topper | cafae62 | 2018-05-04 01:04:26 +0000 | [diff] [blame] | 1462 | const Value *Args[] = |
Craig Topper | ded8ee0 | 2018-05-04 17:39:08 +0000 | [diff] [blame] | 1463 | {InitX, ZeroCheck ? ConstantInt::getTrue(InitX->getContext()) |
| 1464 | : ConstantInt::getFalse(InitX->getContext())}; |
Craig Topper | c9a6000 | 2018-12-26 21:59:48 +0000 | [diff] [blame^] | 1465 | if (CurLoop->getHeader()->size() != IdiomCanonicalSize && |
| 1466 | TTI->getIntrinsicCost(IntrinID, InitX->getType(), Args) > |
| 1467 | TargetTransformInfo::TCC_Basic) |
Evgeny Stupachenko | 2fecd38 | 2017-05-15 19:08:56 +0000 | [diff] [blame] | 1468 | return false; |
| 1469 | |
Craig Topper | c9a6000 | 2018-12-26 21:59:48 +0000 | [diff] [blame^] | 1470 | transformLoopToCountable(IntrinID, PH, CntInst, CntPhi, InitX, DefX, |
Craig Topper | 2835278 | 2018-07-08 01:45:47 +0000 | [diff] [blame] | 1471 | DefX->getDebugLoc(), ZeroCheck, |
| 1472 | IsCntPhiUsedOutsideLoop); |
Evgeny Stupachenko | 2fecd38 | 2017-05-15 19:08:56 +0000 | [diff] [blame] | 1473 | return true; |
| 1474 | } |
| 1475 | |
Chandler Carruth | 8219a50 | 2015-08-13 00:44:29 +0000 | [diff] [blame] | 1476 | /// Recognizes a population count idiom in a non-countable loop. |
| 1477 | /// |
| 1478 | /// If detected, transforms the relevant code to issue the popcount intrinsic |
| 1479 | /// function call, and returns true; otherwise, returns false. |
| 1480 | bool LoopIdiomRecognize::recognizePopcount() { |
Chandler Carruth | 8219a50 | 2015-08-13 00:44:29 +0000 | [diff] [blame] | 1481 | if (TTI->getPopcntSupport(32) != TargetTransformInfo::PSK_FastHardware) |
| 1482 | return false; |
| 1483 | |
| 1484 | // Counting population are usually conducted by few arithmetic instructions. |
Nick Lewycky | 06b0ea2 | 2015-08-18 22:41:58 +0000 | [diff] [blame] | 1485 | // Such instructions can be easily "absorbed" by vacant slots in a |
Chandler Carruth | 8219a50 | 2015-08-13 00:44:29 +0000 | [diff] [blame] | 1486 | // non-compact loop. Therefore, recognizing popcount idiom only makes sense |
| 1487 | // in a compact loop. |
| 1488 | |
Renato Golin | 655348f | 2015-08-13 11:25:38 +0000 | [diff] [blame] | 1489 | // Give up if the loop has multiple blocks or multiple backedges. |
| 1490 | if (CurLoop->getNumBackEdges() != 1 || CurLoop->getNumBlocks() != 1) |
Chandler Carruth | 8219a50 | 2015-08-13 00:44:29 +0000 | [diff] [blame] | 1491 | return false; |
| 1492 | |
Renato Golin | 655348f | 2015-08-13 11:25:38 +0000 | [diff] [blame] | 1493 | BasicBlock *LoopBody = *(CurLoop->block_begin()); |
| 1494 | if (LoopBody->size() >= 20) { |
| 1495 | // The loop is too big, bail out. |
Chandler Carruth | 8219a50 | 2015-08-13 00:44:29 +0000 | [diff] [blame] | 1496 | return false; |
Renato Golin | 655348f | 2015-08-13 11:25:38 +0000 | [diff] [blame] | 1497 | } |
Chandler Carruth | 8219a50 | 2015-08-13 00:44:29 +0000 | [diff] [blame] | 1498 | |
| 1499 | // It should have a preheader containing nothing but an unconditional branch. |
Renato Golin | 655348f | 2015-08-13 11:25:38 +0000 | [diff] [blame] | 1500 | BasicBlock *PH = CurLoop->getLoopPreheader(); |
Davide Italiano | c0169fa | 2016-10-07 18:39:43 +0000 | [diff] [blame] | 1501 | if (!PH || &PH->front() != PH->getTerminator()) |
Renato Golin | 655348f | 2015-08-13 11:25:38 +0000 | [diff] [blame] | 1502 | return false; |
| 1503 | auto *EntryBI = dyn_cast<BranchInst>(PH->getTerminator()); |
Chandler Carruth | 8219a50 | 2015-08-13 00:44:29 +0000 | [diff] [blame] | 1504 | if (!EntryBI || EntryBI->isConditional()) |
| 1505 | return false; |
| 1506 | |
Hiroshi Inoue | f209649 | 2018-06-14 05:41:49 +0000 | [diff] [blame] | 1507 | // It should have a precondition block where the generated popcount intrinsic |
Chandler Carruth | 8219a50 | 2015-08-13 00:44:29 +0000 | [diff] [blame] | 1508 | // function can be inserted. |
Renato Golin | 655348f | 2015-08-13 11:25:38 +0000 | [diff] [blame] | 1509 | auto *PreCondBB = PH->getSinglePredecessor(); |
Chandler Carruth | 8219a50 | 2015-08-13 00:44:29 +0000 | [diff] [blame] | 1510 | if (!PreCondBB) |
| 1511 | return false; |
| 1512 | auto *PreCondBI = dyn_cast<BranchInst>(PreCondBB->getTerminator()); |
| 1513 | if (!PreCondBI || PreCondBI->isUnconditional()) |
| 1514 | return false; |
| 1515 | |
| 1516 | Instruction *CntInst; |
| 1517 | PHINode *CntPhi; |
| 1518 | Value *Val; |
| 1519 | if (!detectPopcountIdiom(CurLoop, PreCondBB, CntInst, CntPhi, Val)) |
| 1520 | return false; |
| 1521 | |
| 1522 | transformLoopToPopcount(PreCondBB, CntInst, CntPhi, Val); |
| 1523 | return true; |
| 1524 | } |
| 1525 | |
| 1526 | static CallInst *createPopcntIntrinsic(IRBuilder<> &IRBuilder, Value *Val, |
Benjamin Kramer | bdc4956 | 2016-06-12 15:39:02 +0000 | [diff] [blame] | 1527 | const DebugLoc &DL) { |
Chandler Carruth | 8219a50 | 2015-08-13 00:44:29 +0000 | [diff] [blame] | 1528 | Value *Ops[] = {Val}; |
| 1529 | Type *Tys[] = {Val->getType()}; |
| 1530 | |
| 1531 | Module *M = IRBuilder.GetInsertBlock()->getParent()->getParent(); |
| 1532 | Value *Func = Intrinsic::getDeclaration(M, Intrinsic::ctpop, Tys); |
| 1533 | CallInst *CI = IRBuilder.CreateCall(Func, Ops); |
| 1534 | CI->setDebugLoc(DL); |
| 1535 | |
| 1536 | return CI; |
| 1537 | } |
| 1538 | |
Craig Topper | c9a6000 | 2018-12-26 21:59:48 +0000 | [diff] [blame^] | 1539 | static CallInst *createFFSIntrinsic(IRBuilder<> &IRBuilder, Value *Val, |
| 1540 | const DebugLoc &DL, bool ZeroCheck, |
| 1541 | Intrinsic::ID IID) { |
Evgeny Stupachenko | 2fecd38 | 2017-05-15 19:08:56 +0000 | [diff] [blame] | 1542 | Value *Ops[] = {Val, ZeroCheck ? IRBuilder.getTrue() : IRBuilder.getFalse()}; |
| 1543 | Type *Tys[] = {Val->getType()}; |
| 1544 | |
| 1545 | Module *M = IRBuilder.GetInsertBlock()->getParent()->getParent(); |
Craig Topper | c9a6000 | 2018-12-26 21:59:48 +0000 | [diff] [blame^] | 1546 | Value *Func = Intrinsic::getDeclaration(M, IID, Tys); |
Evgeny Stupachenko | 2fecd38 | 2017-05-15 19:08:56 +0000 | [diff] [blame] | 1547 | CallInst *CI = IRBuilder.CreateCall(Func, Ops); |
| 1548 | CI->setDebugLoc(DL); |
| 1549 | |
| 1550 | return CI; |
| 1551 | } |
| 1552 | |
Craig Topper | c9a6000 | 2018-12-26 21:59:48 +0000 | [diff] [blame^] | 1553 | /// Transform the following loop (Using CTLZ, CTTZ is similar): |
Evgeny Stupachenko | 2fecd38 | 2017-05-15 19:08:56 +0000 | [diff] [blame] | 1554 | /// loop: |
| 1555 | /// CntPhi = PHI [Cnt0, CntInst] |
| 1556 | /// PhiX = PHI [InitX, DefX] |
| 1557 | /// CntInst = CntPhi + 1 |
| 1558 | /// DefX = PhiX >> 1 |
Eugene Zelenko | dd40f5e | 2017-10-16 21:34:24 +0000 | [diff] [blame] | 1559 | /// LOOP_BODY |
Evgeny Stupachenko | 2fecd38 | 2017-05-15 19:08:56 +0000 | [diff] [blame] | 1560 | /// Br: loop if (DefX != 0) |
| 1561 | /// Use(CntPhi) or Use(CntInst) |
| 1562 | /// |
| 1563 | /// Into: |
| 1564 | /// If CntPhi used outside the loop: |
| 1565 | /// CountPrev = BitWidth(InitX) - CTLZ(InitX >> 1) |
| 1566 | /// Count = CountPrev + 1 |
| 1567 | /// else |
| 1568 | /// Count = BitWidth(InitX) - CTLZ(InitX) |
| 1569 | /// loop: |
| 1570 | /// CntPhi = PHI [Cnt0, CntInst] |
| 1571 | /// PhiX = PHI [InitX, DefX] |
| 1572 | /// PhiCount = PHI [Count, Dec] |
| 1573 | /// CntInst = CntPhi + 1 |
| 1574 | /// DefX = PhiX >> 1 |
| 1575 | /// Dec = PhiCount - 1 |
| 1576 | /// LOOP_BODY |
| 1577 | /// Br: loop if (Dec != 0) |
| 1578 | /// Use(CountPrev + Cnt0) // Use(CntPhi) |
| 1579 | /// or |
| 1580 | /// Use(Count + Cnt0) // Use(CntInst) |
| 1581 | /// |
| 1582 | /// If LOOP_BODY is empty the loop will be deleted. |
| 1583 | /// If CntInst and DefX are not used in LOOP_BODY they will be removed. |
| 1584 | void LoopIdiomRecognize::transformLoopToCountable( |
Craig Topper | c9a6000 | 2018-12-26 21:59:48 +0000 | [diff] [blame^] | 1585 | Intrinsic::ID IntrinID, BasicBlock *Preheader, Instruction *CntInst, |
| 1586 | PHINode *CntPhi, Value *InitX, Instruction *DefX, const DebugLoc &DL, |
| 1587 | bool ZeroCheck, bool IsCntPhiUsedOutsideLoop) { |
Craig Topper | 9510f70 | 2018-05-04 01:04:28 +0000 | [diff] [blame] | 1588 | BranchInst *PreheaderBr = cast<BranchInst>(Preheader->getTerminator()); |
Evgeny Stupachenko | 2fecd38 | 2017-05-15 19:08:56 +0000 | [diff] [blame] | 1589 | |
Craig Topper | c9a6000 | 2018-12-26 21:59:48 +0000 | [diff] [blame^] | 1590 | // Step 1: Insert the CTLZ/CTTZ instruction at the end of the preheader block |
| 1591 | IRBuilder<> Builder(PreheaderBr); |
| 1592 | Builder.SetCurrentDebugLocation(DL); |
| 1593 | Value *FFS, *Count, *CountPrev, *NewCount, *InitXNext; |
| 1594 | |
Evgeny Stupachenko | 2fecd38 | 2017-05-15 19:08:56 +0000 | [diff] [blame] | 1595 | // Count = BitWidth - CTLZ(InitX); |
| 1596 | // If there are uses of CntPhi create: |
| 1597 | // CountPrev = BitWidth - CTLZ(InitX >> 1); |
Craig Topper | 2835278 | 2018-07-08 01:45:47 +0000 | [diff] [blame] | 1598 | if (IsCntPhiUsedOutsideLoop) { |
| 1599 | if (DefX->getOpcode() == Instruction::AShr) |
| 1600 | InitXNext = |
| 1601 | Builder.CreateAShr(InitX, ConstantInt::get(InitX->getType(), 1)); |
| 1602 | else if (DefX->getOpcode() == Instruction::LShr) |
| 1603 | InitXNext = |
| 1604 | Builder.CreateLShr(InitX, ConstantInt::get(InitX->getType(), 1)); |
Craig Topper | c9a6000 | 2018-12-26 21:59:48 +0000 | [diff] [blame^] | 1605 | else if (DefX->getOpcode() == Instruction::Shl) // cttz |
| 1606 | InitXNext = |
| 1607 | Builder.CreateShl(InitX, ConstantInt::get(InitX->getType(), 1)); |
Craig Topper | 2835278 | 2018-07-08 01:45:47 +0000 | [diff] [blame] | 1608 | else |
Fangrui Song | f78650a | 2018-07-30 19:41:25 +0000 | [diff] [blame] | 1609 | llvm_unreachable("Unexpected opcode!"); |
Craig Topper | 2835278 | 2018-07-08 01:45:47 +0000 | [diff] [blame] | 1610 | } else |
Evgeny Stupachenko | 2fecd38 | 2017-05-15 19:08:56 +0000 | [diff] [blame] | 1611 | InitXNext = InitX; |
Craig Topper | c9a6000 | 2018-12-26 21:59:48 +0000 | [diff] [blame^] | 1612 | FFS = createFFSIntrinsic(Builder, InitXNext, DL, ZeroCheck, IntrinID); |
Evgeny Stupachenko | 2fecd38 | 2017-05-15 19:08:56 +0000 | [diff] [blame] | 1613 | Count = Builder.CreateSub( |
Craig Topper | c9a6000 | 2018-12-26 21:59:48 +0000 | [diff] [blame^] | 1614 | ConstantInt::get(FFS->getType(), |
| 1615 | FFS->getType()->getIntegerBitWidth()), |
| 1616 | FFS); |
Evgeny Stupachenko | 2fecd38 | 2017-05-15 19:08:56 +0000 | [diff] [blame] | 1617 | if (IsCntPhiUsedOutsideLoop) { |
| 1618 | CountPrev = Count; |
| 1619 | Count = Builder.CreateAdd( |
| 1620 | CountPrev, |
| 1621 | ConstantInt::get(CountPrev->getType(), 1)); |
| 1622 | } |
Evgeny Stupachenko | 2fecd38 | 2017-05-15 19:08:56 +0000 | [diff] [blame] | 1623 | |
Craig Topper | c9a6000 | 2018-12-26 21:59:48 +0000 | [diff] [blame^] | 1624 | NewCount = Builder.CreateZExtOrTrunc( |
| 1625 | IsCntPhiUsedOutsideLoop ? CountPrev : Count, |
| 1626 | cast<IntegerType>(CntInst->getType())); |
| 1627 | |
| 1628 | // If the counter's initial value is not zero, insert Add Inst. |
Evgeny Stupachenko | 2fecd38 | 2017-05-15 19:08:56 +0000 | [diff] [blame] | 1629 | Value *CntInitVal = CntPhi->getIncomingValueForBlock(Preheader); |
| 1630 | ConstantInt *InitConst = dyn_cast<ConstantInt>(CntInitVal); |
| 1631 | if (!InitConst || !InitConst->isZero()) |
| 1632 | NewCount = Builder.CreateAdd(NewCount, CntInitVal); |
| 1633 | |
| 1634 | // Step 2: Insert new IV and loop condition: |
| 1635 | // loop: |
| 1636 | // ... |
| 1637 | // PhiCount = PHI [Count, Dec] |
| 1638 | // ... |
| 1639 | // Dec = PhiCount - 1 |
| 1640 | // ... |
| 1641 | // Br: loop if (Dec != 0) |
| 1642 | BasicBlock *Body = *(CurLoop->block_begin()); |
Craig Topper | 9510f70 | 2018-05-04 01:04:28 +0000 | [diff] [blame] | 1643 | auto *LbBr = cast<BranchInst>(Body->getTerminator()); |
Evgeny Stupachenko | 2fecd38 | 2017-05-15 19:08:56 +0000 | [diff] [blame] | 1644 | ICmpInst *LbCond = cast<ICmpInst>(LbBr->getCondition()); |
| 1645 | Type *Ty = Count->getType(); |
| 1646 | |
| 1647 | PHINode *TcPhi = PHINode::Create(Ty, 2, "tcphi", &Body->front()); |
| 1648 | |
| 1649 | Builder.SetInsertPoint(LbCond); |
| 1650 | Instruction *TcDec = cast<Instruction>( |
| 1651 | Builder.CreateSub(TcPhi, ConstantInt::get(Ty, 1), |
| 1652 | "tcdec", false, true)); |
| 1653 | |
| 1654 | TcPhi->addIncoming(Count, Preheader); |
| 1655 | TcPhi->addIncoming(TcDec, Body); |
| 1656 | |
| 1657 | CmpInst::Predicate Pred = |
| 1658 | (LbBr->getSuccessor(0) == Body) ? CmpInst::ICMP_NE : CmpInst::ICMP_EQ; |
| 1659 | LbCond->setPredicate(Pred); |
| 1660 | LbCond->setOperand(0, TcDec); |
| 1661 | LbCond->setOperand(1, ConstantInt::get(Ty, 0)); |
| 1662 | |
| 1663 | // Step 3: All the references to the original counter outside |
Craig Topper | c9a6000 | 2018-12-26 21:59:48 +0000 | [diff] [blame^] | 1664 | // the loop are replaced with the NewCount |
Evgeny Stupachenko | 2fecd38 | 2017-05-15 19:08:56 +0000 | [diff] [blame] | 1665 | if (IsCntPhiUsedOutsideLoop) |
| 1666 | CntPhi->replaceUsesOutsideBlock(NewCount, Body); |
| 1667 | else |
| 1668 | CntInst->replaceUsesOutsideBlock(NewCount, Body); |
| 1669 | |
| 1670 | // step 4: Forget the "non-computable" trip-count SCEV associated with the |
| 1671 | // loop. The loop would otherwise not be deleted even if it becomes empty. |
| 1672 | SE->forgetLoop(CurLoop); |
| 1673 | } |
| 1674 | |
Chandler Carruth | 8219a50 | 2015-08-13 00:44:29 +0000 | [diff] [blame] | 1675 | void LoopIdiomRecognize::transformLoopToPopcount(BasicBlock *PreCondBB, |
| 1676 | Instruction *CntInst, |
| 1677 | PHINode *CntPhi, Value *Var) { |
| 1678 | BasicBlock *PreHead = CurLoop->getLoopPreheader(); |
Craig Topper | 9510f70 | 2018-05-04 01:04:28 +0000 | [diff] [blame] | 1679 | auto *PreCondBr = cast<BranchInst>(PreCondBB->getTerminator()); |
Craig Topper | 2784786 | 2018-06-25 20:45:45 +0000 | [diff] [blame] | 1680 | const DebugLoc &DL = CntInst->getDebugLoc(); |
Chandler Carruth | 8219a50 | 2015-08-13 00:44:29 +0000 | [diff] [blame] | 1681 | |
| 1682 | // Assuming before transformation, the loop is following: |
| 1683 | // if (x) // the precondition |
| 1684 | // do { cnt++; x &= x - 1; } while(x); |
| 1685 | |
| 1686 | // Step 1: Insert the ctpop instruction at the end of the precondition block |
| 1687 | IRBuilder<> Builder(PreCondBr); |
| 1688 | Value *PopCnt, *PopCntZext, *NewCount, *TripCnt; |
| 1689 | { |
| 1690 | PopCnt = createPopcntIntrinsic(Builder, Var, DL); |
| 1691 | NewCount = PopCntZext = |
| 1692 | Builder.CreateZExtOrTrunc(PopCnt, cast<IntegerType>(CntPhi->getType())); |
| 1693 | |
| 1694 | if (NewCount != PopCnt) |
| 1695 | (cast<Instruction>(NewCount))->setDebugLoc(DL); |
| 1696 | |
| 1697 | // TripCnt is exactly the number of iterations the loop has |
| 1698 | TripCnt = NewCount; |
| 1699 | |
| 1700 | // If the population counter's initial value is not zero, insert Add Inst. |
| 1701 | Value *CntInitVal = CntPhi->getIncomingValueForBlock(PreHead); |
| 1702 | ConstantInt *InitConst = dyn_cast<ConstantInt>(CntInitVal); |
| 1703 | if (!InitConst || !InitConst->isZero()) { |
| 1704 | NewCount = Builder.CreateAdd(NewCount, CntInitVal); |
| 1705 | (cast<Instruction>(NewCount))->setDebugLoc(DL); |
| 1706 | } |
| 1707 | } |
| 1708 | |
Nick Lewycky | 2c85254 | 2015-08-19 06:22:33 +0000 | [diff] [blame] | 1709 | // 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] | 1710 | // "if (NewCount == 0) loop-exit". Without this change, the intrinsic |
Chandler Carruth | 8219a50 | 2015-08-13 00:44:29 +0000 | [diff] [blame] | 1711 | // function would be partial dead code, and downstream passes will drag |
| 1712 | // it back from the precondition block to the preheader. |
| 1713 | { |
| 1714 | ICmpInst *PreCond = cast<ICmpInst>(PreCondBr->getCondition()); |
| 1715 | |
| 1716 | Value *Opnd0 = PopCntZext; |
| 1717 | Value *Opnd1 = ConstantInt::get(PopCntZext->getType(), 0); |
| 1718 | if (PreCond->getOperand(0) != Var) |
| 1719 | std::swap(Opnd0, Opnd1); |
| 1720 | |
| 1721 | ICmpInst *NewPreCond = cast<ICmpInst>( |
| 1722 | Builder.CreateICmp(PreCond->getPredicate(), Opnd0, Opnd1)); |
| 1723 | PreCondBr->setCondition(NewPreCond); |
| 1724 | |
| 1725 | RecursivelyDeleteTriviallyDeadInstructions(PreCond, TLI); |
| 1726 | } |
| 1727 | |
| 1728 | // Step 3: Note that the population count is exactly the trip count of the |
Hiroshi Inoue | c8e9245 | 2018-01-29 05:17:03 +0000 | [diff] [blame] | 1729 | // loop in question, which enable us to convert the loop from noncountable |
Chandler Carruth | 8219a50 | 2015-08-13 00:44:29 +0000 | [diff] [blame] | 1730 | // loop into a countable one. The benefit is twofold: |
| 1731 | // |
Nick Lewycky | 2c85254 | 2015-08-19 06:22:33 +0000 | [diff] [blame] | 1732 | // - If the loop only counts population, the entire loop becomes dead after |
| 1733 | // the transformation. It is a lot easier to prove a countable loop dead |
| 1734 | // 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] | 1735 | // isn't dead even if it computes nothing useful. In general, DCE needs |
| 1736 | // to prove a noncountable loop finite before safely delete it.) |
| 1737 | // |
| 1738 | // - If the loop also performs something else, it remains alive. |
| 1739 | // Since it is transformed to countable form, it can be aggressively |
| 1740 | // optimized by some optimizations which are in general not applicable |
| 1741 | // to a noncountable loop. |
| 1742 | // |
| 1743 | // After this step, this loop (conceptually) would look like following: |
| 1744 | // newcnt = __builtin_ctpop(x); |
| 1745 | // t = newcnt; |
| 1746 | // if (x) |
| 1747 | // do { cnt++; x &= x-1; t--) } while (t > 0); |
| 1748 | BasicBlock *Body = *(CurLoop->block_begin()); |
| 1749 | { |
Craig Topper | 9510f70 | 2018-05-04 01:04:28 +0000 | [diff] [blame] | 1750 | auto *LbBr = cast<BranchInst>(Body->getTerminator()); |
Chandler Carruth | 8219a50 | 2015-08-13 00:44:29 +0000 | [diff] [blame] | 1751 | ICmpInst *LbCond = cast<ICmpInst>(LbBr->getCondition()); |
| 1752 | Type *Ty = TripCnt->getType(); |
| 1753 | |
Duncan P. N. Exon Smith | be4d8cb | 2015-10-13 19:26:58 +0000 | [diff] [blame] | 1754 | PHINode *TcPhi = PHINode::Create(Ty, 2, "tcphi", &Body->front()); |
Chandler Carruth | 8219a50 | 2015-08-13 00:44:29 +0000 | [diff] [blame] | 1755 | |
| 1756 | Builder.SetInsertPoint(LbCond); |
Chandler Carruth | 8219a50 | 2015-08-13 00:44:29 +0000 | [diff] [blame] | 1757 | Instruction *TcDec = cast<Instruction>( |
Nick Lewycky | 1098e49 | 2015-08-19 06:25:30 +0000 | [diff] [blame] | 1758 | Builder.CreateSub(TcPhi, ConstantInt::get(Ty, 1), |
| 1759 | "tcdec", false, true)); |
Chandler Carruth | 8219a50 | 2015-08-13 00:44:29 +0000 | [diff] [blame] | 1760 | |
| 1761 | TcPhi->addIncoming(TripCnt, PreHead); |
| 1762 | TcPhi->addIncoming(TcDec, Body); |
| 1763 | |
| 1764 | CmpInst::Predicate Pred = |
| 1765 | (LbBr->getSuccessor(0) == Body) ? CmpInst::ICMP_UGT : CmpInst::ICMP_SLE; |
| 1766 | LbCond->setPredicate(Pred); |
| 1767 | LbCond->setOperand(0, TcDec); |
Nick Lewycky | 2c85254 | 2015-08-19 06:22:33 +0000 | [diff] [blame] | 1768 | LbCond->setOperand(1, ConstantInt::get(Ty, 0)); |
Chandler Carruth | 8219a50 | 2015-08-13 00:44:29 +0000 | [diff] [blame] | 1769 | } |
| 1770 | |
| 1771 | // Step 4: All the references to the original population counter outside |
| 1772 | // the loop are replaced with the NewCount -- the value returned from |
| 1773 | // __builtin_ctpop(). |
| 1774 | CntInst->replaceUsesOutsideBlock(NewCount, Body); |
| 1775 | |
| 1776 | // step 5: Forget the "non-computable" trip-count SCEV associated with the |
| 1777 | // loop. The loop would otherwise not be deleted even if it becomes empty. |
| 1778 | SE->forgetLoop(CurLoop); |
| 1779 | } |