blob: eb5f3cc47cef83266f9477c8f16e663458c05008 [file] [log] [blame]
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +00001//===- LoopIdiomRecognize.cpp - Loop idiom recognition --------------------===//
Chris Lattner81ae3f22010-12-26 19:39:38 +00002//
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 Kaylor7cdf01e2016-08-11 18:28:33 +000014// 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 Lattner81ae3f22010-12-26 19:39:38 +000020//===----------------------------------------------------------------------===//
Chris Lattner0469e012011-01-02 18:32:09 +000021//
22// TODO List:
23//
24// Future loop memory idioms to recognize:
Chandler Carruth099f5cb02012-11-02 08:33:25 +000025// memcmp, memmove, strlen, etc.
Chris Lattner0469e012011-01-02 18:32:09 +000026// Future floating point idioms to recognize in -ffast-math mode:
27// fpowi
28// Future integer operation idioms to recognize:
29// ctpop, ctlz, cttz
30//
31// Beware that isel's default lowering for ctpop is highly inefficient for
32// i64 and larger types when i64 is legal and the value has few bits set. It
33// would be good to enhance isel to emit a loop for ctpop in this case.
34//
Chris Lattner02a97762011-01-03 01:10:08 +000035// This could recognize common matrix multiplies and dot product idioms and
Chris Lattner8fac5db2011-01-02 23:19:45 +000036// replace them with calls to BLAS (if linked in??).
37//
Chris Lattner0469e012011-01-02 18:32:09 +000038//===----------------------------------------------------------------------===//
Chris Lattner81ae3f22010-12-26 19:39:38 +000039
Dehao Chenb9f8e292016-07-12 18:45:51 +000040#include "llvm/Transforms/Scalar/LoopIdiomRecognize.h"
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +000041#include "llvm/ADT/APInt.h"
42#include "llvm/ADT/ArrayRef.h"
43#include "llvm/ADT/DenseMap.h"
Haicheng Wuf1c00a22016-01-26 02:27:47 +000044#include "llvm/ADT/MapVector.h"
45#include "llvm/ADT/SetVector.h"
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +000046#include "llvm/ADT/SmallPtrSet.h"
47#include "llvm/ADT/SmallVector.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000048#include "llvm/ADT/Statistic.h"
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +000049#include "llvm/ADT/StringRef.h"
Chris Lattnercb18bfa2010-12-27 18:39:08 +000050#include "llvm/Analysis/AliasAnalysis.h"
Haicheng Wuf1c00a22016-01-26 02:27:47 +000051#include "llvm/Analysis/LoopAccessAnalysis.h"
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +000052#include "llvm/Analysis/LoopInfo.h"
Dehao Chenb9f8e292016-07-12 18:45:51 +000053#include "llvm/Analysis/LoopPass.h"
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +000054#include "llvm/Analysis/MemoryLocation.h"
55#include "llvm/Analysis/ScalarEvolution.h"
Chad Rosiera15b4b62015-11-23 21:09:13 +000056#include "llvm/Analysis/ScalarEvolutionExpander.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000057#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000058#include "llvm/Analysis/TargetLibraryInfo.h"
Chandler Carruthd3e73552013-01-07 03:08:10 +000059#include "llvm/Analysis/TargetTransformInfo.h"
Chris Lattner7c5f9c32010-12-26 20:45:45 +000060#include "llvm/Analysis/ValueTracking.h"
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +000061#include "llvm/IR/Attributes.h"
62#include "llvm/IR/BasicBlock.h"
63#include "llvm/IR/Constant.h"
64#include "llvm/IR/Constants.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000065#include "llvm/IR/DataLayout.h"
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +000066#include "llvm/IR/DebugLoc.h"
67#include "llvm/IR/DerivedTypes.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000068#include "llvm/IR/Dominators.h"
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +000069#include "llvm/IR/GlobalValue.h"
70#include "llvm/IR/GlobalVariable.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000071#include "llvm/IR/IRBuilder.h"
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +000072#include "llvm/IR/InstrTypes.h"
73#include "llvm/IR/Instruction.h"
74#include "llvm/IR/Instructions.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000075#include "llvm/IR/IntrinsicInst.h"
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +000076#include "llvm/IR/Intrinsics.h"
77#include "llvm/IR/LLVMContext.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000078#include "llvm/IR/Module.h"
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +000079#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 Carruthaafe0912012-06-29 12:38:19 +000087#include "llvm/Support/Debug.h"
88#include "llvm/Support/raw_ostream.h"
Dehao Chenb9f8e292016-07-12 18:45:51 +000089#include "llvm/Transforms/Scalar.h"
Ahmed Bougachaace97c12016-04-27 19:04:50 +000090#include "llvm/Transforms/Utils/BuildLibCalls.h"
Chris Lattnerb9fe6852010-12-27 00:03:23 +000091#include "llvm/Transforms/Utils/Local.h"
Chandler Carruth31088a92016-02-19 10:45:18 +000092#include "llvm/Transforms/Utils/LoopUtils.h"
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +000093#include <algorithm>
94#include <cassert>
95#include <cstdint>
96#include <utility>
97#include <vector>
98
Chris Lattner81ae3f22010-12-26 19:39:38 +000099using namespace llvm;
100
Chandler Carruth964daaa2014-04-22 02:55:47 +0000101#define DEBUG_TYPE "loop-idiom"
102
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000103STATISTIC(NumMemSet, "Number of memset's formed from loop stores");
104STATISTIC(NumMemCpy, "Number of memcpy's formed from loop load+stores");
Chris Lattner81ae3f22010-12-26 19:39:38 +0000105
Andrew Kaylor7cdf01e2016-08-11 18:28:33 +0000106static 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 Lattner81ae3f22010-12-26 19:39:38 +0000112namespace {
Shuxin Yang95de7c32012-12-09 03:12:46 +0000113
Dehao Chenb9f8e292016-07-12 18:45:51 +0000114class LoopIdiomRecognize {
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +0000115 Loop *CurLoop = nullptr;
Chandler Carruthbf143e22015-08-14 00:21:10 +0000116 AliasAnalysis *AA;
Chandler Carruthbad690e2015-08-12 23:06:37 +0000117 DominatorTree *DT;
Chandler Carruth18c26692015-08-13 09:27:01 +0000118 LoopInfo *LI;
Chandler Carruthbad690e2015-08-12 23:06:37 +0000119 ScalarEvolution *SE;
120 TargetLibraryInfo *TLI;
121 const TargetTransformInfo *TTI;
Chad Rosier43f9b482015-11-06 16:33:57 +0000122 const DataLayout *DL;
Andrew Kaylor7cdf01e2016-08-11 18:28:33 +0000123 bool ApplyCodeSizeHeuristics;
Chris Lattner81ae3f22010-12-26 19:39:38 +0000124
Chandler Carruthbad690e2015-08-12 23:06:37 +0000125public:
Dehao Chenb9f8e292016-07-12 18:45:51 +0000126 explicit LoopIdiomRecognize(AliasAnalysis *AA, DominatorTree *DT,
127 LoopInfo *LI, ScalarEvolution *SE,
128 TargetLibraryInfo *TLI,
129 const TargetTransformInfo *TTI,
130 const DataLayout *DL)
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +0000131 : AA(AA), DT(DT), LI(LI), SE(SE), TLI(TLI), TTI(TTI), DL(DL) {}
Chris Lattner81ae3f22010-12-26 19:39:38 +0000132
Dehao Chenb9f8e292016-07-12 18:45:51 +0000133 bool runOnLoop(Loop *L);
Shuxin Yang95de7c32012-12-09 03:12:46 +0000134
Chandler Carruthbad690e2015-08-12 23:06:37 +0000135private:
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +0000136 using StoreList = SmallVector<StoreInst *, 8>;
137 using StoreListMap = MapVector<Value *, StoreList>;
138
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000139 StoreListMap StoreRefsForMemset;
140 StoreListMap StoreRefsForMemsetPattern;
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000141 StoreList StoreRefsForMemcpy;
142 bool HasMemset;
143 bool HasMemsetPattern;
144 bool HasMemcpy;
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +0000145
Anna Thomas5ecb8f72017-05-19 17:05:36 +0000146 /// Return code for isLegalStore()
147 enum LegalStoreKind {
Anna Thomasae3f752f2017-05-19 18:00:30 +0000148 None = 0,
Anna Thomas5ecb8f72017-05-19 17:05:36 +0000149 Memset,
150 MemsetPattern,
151 Memcpy,
Anna Thomasb2a212c2017-06-06 16:45:25 +0000152 UnorderedAtomicMemcpy,
Anna Thomasae3f752f2017-05-19 18:00:30 +0000153 DontUse // Dummy retval never to be used. Allows catching errors in retval
154 // handling.
Anna Thomas5ecb8f72017-05-19 17:05:36 +0000155 };
Chad Rosiercc9030b2015-11-11 23:00:59 +0000156
Chandler Carruthd9c60702015-08-13 00:10:03 +0000157 /// \name Countable Loop Idiom Handling
158 /// @{
159
Chandler Carruthbad690e2015-08-12 23:06:37 +0000160 bool runOnCountableLoop();
Chandler Carruthd9c60702015-08-13 00:10:03 +0000161 bool runOnLoopBlock(BasicBlock *BB, const SCEV *BECount,
162 SmallVectorImpl<BasicBlock *> &ExitBlocks);
163
Chad Rosiercc9030b2015-11-11 23:00:59 +0000164 void collectStores(BasicBlock *BB);
Anna Thomas5ecb8f72017-05-19 17:05:36 +0000165 LegalStoreKind isLegalStore(StoreInst *SI);
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000166 bool processLoopStores(SmallVectorImpl<StoreInst *> &SL, const SCEV *BECount,
167 bool ForMemset);
Chandler Carruthd9c60702015-08-13 00:10:03 +0000168 bool processLoopMemSet(MemSetInst *MSI, const SCEV *BECount);
169
170 bool processLoopStridedStore(Value *DestPtr, unsigned StoreSize,
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000171 unsigned StoreAlignment, Value *StoredVal,
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000172 Instruction *TheStore,
173 SmallPtrSetImpl<Instruction *> &Stores,
174 const SCEVAddRecExpr *Ev, const SCEV *BECount,
Andrew Kaylor7cdf01e2016-08-11 18:28:33 +0000175 bool NegStride, bool IsLoopMemset = false);
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000176 bool processLoopStoreOfLoopLoad(StoreInst *SI, const SCEV *BECount);
Andrew Kaylor7cdf01e2016-08-11 18:28:33 +0000177 bool avoidLIRForMultiBlockLoop(bool IsMemset = false,
178 bool IsLoopMemset = false);
Chandler Carruthd9c60702015-08-13 00:10:03 +0000179
180 /// @}
181 /// \name Noncountable Loop Idiom Handling
182 /// @{
183
184 bool runOnNoncountableLoop();
185
Chandler Carruth8219a502015-08-13 00:44:29 +0000186 bool recognizePopcount();
187 void transformLoopToPopcount(BasicBlock *PreCondBB, Instruction *CntInst,
188 PHINode *CntPhi, Value *Var);
Evgeny Stupachenko2fecd382017-05-15 19:08:56 +0000189 bool recognizeAndInsertCTLZ();
190 void transformLoopToCountable(BasicBlock *PreCondBB, Instruction *CntInst,
191 PHINode *CntPhi, Value *Var, const DebugLoc DL,
192 bool ZeroCheck, bool IsCntPhiUsedOutsideLoop);
Chandler Carruth8219a502015-08-13 00:44:29 +0000193
Chandler Carruthd9c60702015-08-13 00:10:03 +0000194 /// @}
Chandler Carruthbad690e2015-08-12 23:06:37 +0000195};
196
Dehao Chenb9f8e292016-07-12 18:45:51 +0000197class LoopIdiomRecognizeLegacyPass : public LoopPass {
198public:
199 static char ID;
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +0000200
Dehao Chenb9f8e292016-07-12 18:45:51 +0000201 explicit LoopIdiomRecognizeLegacyPass() : LoopPass(ID) {
202 initializeLoopIdiomRecognizeLegacyPassPass(
203 *PassRegistry::getPassRegistry());
204 }
205
206 bool runOnLoop(Loop *L, LPPassManager &LPM) override {
207 if (skipLoop(L))
208 return false;
209
210 AliasAnalysis *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
211 DominatorTree *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
212 LoopInfo *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
213 ScalarEvolution *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
214 TargetLibraryInfo *TLI =
215 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
216 const TargetTransformInfo *TTI =
217 &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(
218 *L->getHeader()->getParent());
219 const DataLayout *DL = &L->getHeader()->getModule()->getDataLayout();
220
221 LoopIdiomRecognize LIR(AA, DT, LI, SE, TLI, TTI, DL);
222 return LIR.runOnLoop(L);
223 }
224
225 /// This transformation requires natural loop information & requires that
226 /// loop preheaders be inserted into the CFG.
Dehao Chenb9f8e292016-07-12 18:45:51 +0000227 void getAnalysisUsage(AnalysisUsage &AU) const override {
228 AU.addRequired<TargetLibraryInfoWrapperPass>();
229 AU.addRequired<TargetTransformInfoWrapperPass>();
230 getLoopAnalysisUsage(AU);
231 }
232};
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +0000233
234} // end anonymous namespace
235
236char LoopIdiomRecognizeLegacyPass::ID = 0;
Chris Lattner81ae3f22010-12-26 19:39:38 +0000237
Chandler Carruth410eaeb2017-01-11 06:23:21 +0000238PreservedAnalyses LoopIdiomRecognizePass::run(Loop &L, LoopAnalysisManager &AM,
239 LoopStandardAnalysisResults &AR,
240 LPMUpdater &) {
Dehao Chenb9f8e292016-07-12 18:45:51 +0000241 const auto *DL = &L.getHeader()->getModule()->getDataLayout();
Dehao Chenb9f8e292016-07-12 18:45:51 +0000242
Chandler Carruth410eaeb2017-01-11 06:23:21 +0000243 LoopIdiomRecognize LIR(&AR.AA, &AR.DT, &AR.LI, &AR.SE, &AR.TLI, &AR.TTI, DL);
Dehao Chenb9f8e292016-07-12 18:45:51 +0000244 if (!LIR.runOnLoop(&L))
245 return PreservedAnalyses::all();
246
247 return getLoopPassPreservedAnalyses();
248}
249
Dehao Chenb9f8e292016-07-12 18:45:51 +0000250INITIALIZE_PASS_BEGIN(LoopIdiomRecognizeLegacyPass, "loop-idiom",
251 "Recognize loop idioms", false, false)
Chandler Carruth31088a92016-02-19 10:45:18 +0000252INITIALIZE_PASS_DEPENDENCY(LoopPass)
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000253INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
Chandler Carruth705b1852015-01-31 03:43:40 +0000254INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
Dehao Chenb9f8e292016-07-12 18:45:51 +0000255INITIALIZE_PASS_END(LoopIdiomRecognizeLegacyPass, "loop-idiom",
256 "Recognize loop idioms", false, false)
Chris Lattner81ae3f22010-12-26 19:39:38 +0000257
Dehao Chenb9f8e292016-07-12 18:45:51 +0000258Pass *llvm::createLoopIdiomPass() { return new LoopIdiomRecognizeLegacyPass(); }
Chris Lattner81ae3f22010-12-26 19:39:38 +0000259
David Majnemerc5601df2016-06-20 16:03:25 +0000260static void deleteDeadInstruction(Instruction *I) {
Benjamin Kramerf094d772015-02-07 21:37:08 +0000261 I->replaceAllUsesWith(UndefValue::get(I->getType()));
262 I->eraseFromParent();
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000263}
264
Shuxin Yang95de7c32012-12-09 03:12:46 +0000265//===----------------------------------------------------------------------===//
266//
Shuxin Yang95de7c32012-12-09 03:12:46 +0000267// Implementation of LoopIdiomRecognize
268//
269//===----------------------------------------------------------------------===//
270
Dehao Chenb9f8e292016-07-12 18:45:51 +0000271bool LoopIdiomRecognize::runOnLoop(Loop *L) {
Chandler Carruthd9c60702015-08-13 00:10:03 +0000272 CurLoop = L;
Chandler Carruthd9c60702015-08-13 00:10:03 +0000273 // If the loop could not be converted to canonical form, it must have an
274 // indirectbr in it, just give up.
275 if (!L->getLoopPreheader())
276 return false;
277
278 // Disable loop idiom recognition if the function's name is a common idiom.
279 StringRef Name = L->getHeader()->getParent()->getName();
280 if (Name == "memset" || Name == "memcpy")
281 return false;
282
Andrew Kaylor7cdf01e2016-08-11 18:28:33 +0000283 // Determine if code size heuristics need to be applied.
284 ApplyCodeSizeHeuristics =
285 L->getHeader()->getParent()->optForSize() && UseLIRCodeSizeHeurs;
286
David L. Jonesd21529f2017-01-23 23:16:46 +0000287 HasMemset = TLI->has(LibFunc_memset);
288 HasMemsetPattern = TLI->has(LibFunc_memset_pattern16);
289 HasMemcpy = TLI->has(LibFunc_memcpy);
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000290
291 if (HasMemset || HasMemsetPattern || HasMemcpy)
292 if (SE->hasLoopInvariantBackedgeTakenCount(L))
293 return runOnCountableLoop();
Chandler Carruthdc298322015-08-13 01:03:26 +0000294
Chandler Carruthd9c60702015-08-13 00:10:03 +0000295 return runOnNoncountableLoop();
296}
297
Shuxin Yang95de7c32012-12-09 03:12:46 +0000298bool LoopIdiomRecognize::runOnCountableLoop() {
299 const SCEV *BECount = SE->getBackedgeTakenCount(CurLoop);
Davide Italiano8ed04462015-05-11 21:02:34 +0000300 assert(!isa<SCEVCouldNotCompute>(BECount) &&
Chandler Carruthbad690e2015-08-12 23:06:37 +0000301 "runOnCountableLoop() called on a loop without a predictable"
302 "backedge-taken count");
Shuxin Yang95de7c32012-12-09 03:12:46 +0000303
304 // If this loop executes exactly one time, then it should be peeled, not
305 // optimized by this pass.
306 if (const SCEVConstant *BECst = dyn_cast<SCEVConstant>(BECount))
Sanjoy Das0de2fec2015-12-17 20:28:46 +0000307 if (BECst->getAPInt() == 0)
Shuxin Yang95de7c32012-12-09 03:12:46 +0000308 return false;
309
Chandler Carruthbad690e2015-08-12 23:06:37 +0000310 SmallVector<BasicBlock *, 8> ExitBlocks;
Shuxin Yang95de7c32012-12-09 03:12:46 +0000311 CurLoop->getUniqueExitBlocks(ExitBlocks);
312
313 DEBUG(dbgs() << "loop-idiom Scanning: F["
Chandler Carruthbad690e2015-08-12 23:06:37 +0000314 << CurLoop->getHeader()->getParent()->getName() << "] Loop %"
315 << CurLoop->getHeader()->getName() << "\n");
Shuxin Yang95de7c32012-12-09 03:12:46 +0000316
317 bool MadeChange = false;
Haicheng Wua95cd1262016-07-06 21:05:40 +0000318
319 // The following transforms hoist stores/memsets into the loop pre-header.
320 // Give up if the loop has instructions may throw.
321 LoopSafetyInfo SafetyInfo;
322 computeLoopSafetyInfo(&SafetyInfo, CurLoop);
Evgeniy Stepanov58ccc092017-04-24 18:25:07 +0000323 if (SafetyInfo.MayThrow)
Haicheng Wua95cd1262016-07-06 21:05:40 +0000324 return MadeChange;
325
Shuxin Yang95de7c32012-12-09 03:12:46 +0000326 // Scan all the blocks in the loop that are not in subloops.
Davide Italiano95a77e82015-05-14 21:52:12 +0000327 for (auto *BB : CurLoop->getBlocks()) {
Shuxin Yang95de7c32012-12-09 03:12:46 +0000328 // Ignore blocks in subloops.
Chandler Carruth18c26692015-08-13 09:27:01 +0000329 if (LI->getLoopFor(BB) != CurLoop)
Shuxin Yang95de7c32012-12-09 03:12:46 +0000330 continue;
331
Davide Italiano80625af2015-05-13 19:51:21 +0000332 MadeChange |= runOnLoopBlock(BB, BECount, ExitBlocks);
Shuxin Yang95de7c32012-12-09 03:12:46 +0000333 }
334 return MadeChange;
335}
336
Chad Rosiera548fe52015-11-12 19:09:16 +0000337static unsigned getStoreSizeInBytes(StoreInst *SI, const DataLayout *DL) {
338 uint64_t SizeInBits = DL->getTypeSizeInBits(SI->getValueOperand()->getType());
339 assert(((SizeInBits & 7) || (SizeInBits >> 32) == 0) &&
340 "Don't overflow unsigned.");
341 return (unsigned)SizeInBits >> 3;
342}
343
Chad Rosier4acff962016-02-12 19:05:27 +0000344static APInt getStoreStride(const SCEVAddRecExpr *StoreEv) {
Chad Rosiera548fe52015-11-12 19:09:16 +0000345 const SCEVConstant *ConstStride = cast<SCEVConstant>(StoreEv->getOperand(1));
Chad Rosier4acff962016-02-12 19:05:27 +0000346 return ConstStride->getAPInt();
Chad Rosiera548fe52015-11-12 19:09:16 +0000347}
348
Chad Rosier94274fb2015-12-21 14:49:32 +0000349/// getMemSetPatternValue - If a strided store of the specified value is safe to
350/// turn into a memset_pattern16, return a ConstantArray of 16 bytes that should
351/// be passed in. Otherwise, return null.
352///
353/// Note that we don't ever attempt to use memset_pattern8 or 4, because these
354/// just replicate their input array and then pass on to memset_pattern16.
355static Constant *getMemSetPatternValue(Value *V, const DataLayout *DL) {
356 // If the value isn't a constant, we can't promote it to being in a constant
357 // array. We could theoretically do a store to an alloca or something, but
358 // that doesn't seem worthwhile.
359 Constant *C = dyn_cast<Constant>(V);
360 if (!C)
361 return nullptr;
362
363 // Only handle simple values that are a power of two bytes in size.
364 uint64_t Size = DL->getTypeSizeInBits(V->getType());
365 if (Size == 0 || (Size & 7) || (Size & (Size - 1)))
366 return nullptr;
367
368 // Don't care enough about darwin/ppc to implement this.
369 if (DL->isBigEndian())
370 return nullptr;
371
372 // Convert to size in bytes.
373 Size /= 8;
374
375 // TODO: If CI is larger than 16-bytes, we can try slicing it in half to see
376 // if the top and bottom are the same (e.g. for vectors and large integers).
377 if (Size > 16)
378 return nullptr;
379
380 // If the constant is exactly 16 bytes, just use it.
381 if (Size == 16)
382 return C;
383
384 // Otherwise, we'll use an array of the constants.
385 unsigned ArraySize = 16 / Size;
386 ArrayType *AT = ArrayType::get(V->getType(), ArraySize);
387 return ConstantArray::get(AT, std::vector<Constant *>(ArraySize, C));
388}
389
Anna Thomasae3f752f2017-05-19 18:00:30 +0000390LoopIdiomRecognize::LegalStoreKind
391LoopIdiomRecognize::isLegalStore(StoreInst *SI) {
Chad Rosier869962f2015-12-01 14:26:35 +0000392 // Don't touch volatile stores.
Anna Thomasb2a212c2017-06-06 16:45:25 +0000393 if (SI->isVolatile())
394 return LegalStoreKind::None;
395 // We only want simple or unordered-atomic stores.
396 if (!SI->isUnordered())
Anna Thomas5ecb8f72017-05-19 17:05:36 +0000397 return LegalStoreKind::None;
Chad Rosier869962f2015-12-01 14:26:35 +0000398
Sanjoy Das206f65c2017-04-24 20:12:10 +0000399 // Don't convert stores of non-integral pointer types to memsets (which stores
400 // integers).
401 if (DL->isNonIntegralPointerType(SI->getValueOperand()->getType()))
Anna Thomas5ecb8f72017-05-19 17:05:36 +0000402 return LegalStoreKind::None;
Sanjoy Das206f65c2017-04-24 20:12:10 +0000403
Haicheng Wu57e1a3e2016-02-17 21:00:06 +0000404 // Avoid merging nontemporal stores.
405 if (SI->getMetadata(LLVMContext::MD_nontemporal))
Anna Thomas5ecb8f72017-05-19 17:05:36 +0000406 return LegalStoreKind::None;
Haicheng Wu57e1a3e2016-02-17 21:00:06 +0000407
Chad Rosiera548fe52015-11-12 19:09:16 +0000408 Value *StoredVal = SI->getValueOperand();
409 Value *StorePtr = SI->getPointerOperand();
410
411 // Reject stores that are so large that they overflow an unsigned.
412 uint64_t SizeInBits = DL->getTypeSizeInBits(StoredVal->getType());
413 if ((SizeInBits & 7) || (SizeInBits >> 32) != 0)
Anna Thomas5ecb8f72017-05-19 17:05:36 +0000414 return LegalStoreKind::None;
Chad Rosiera548fe52015-11-12 19:09:16 +0000415
416 // See if the pointer expression is an AddRec like {base,+,1} on the current
417 // loop, which indicates a strided store. If we have something else, it's a
418 // random store we can't handle.
419 const SCEVAddRecExpr *StoreEv =
420 dyn_cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr));
421 if (!StoreEv || StoreEv->getLoop() != CurLoop || !StoreEv->isAffine())
Anna Thomas5ecb8f72017-05-19 17:05:36 +0000422 return LegalStoreKind::None;
Chad Rosiera548fe52015-11-12 19:09:16 +0000423
424 // Check to see if we have a constant stride.
425 if (!isa<SCEVConstant>(StoreEv->getOperand(1)))
Anna Thomas5ecb8f72017-05-19 17:05:36 +0000426 return LegalStoreKind::None;
Chad Rosiera548fe52015-11-12 19:09:16 +0000427
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000428 // See if the store can be turned into a memset.
429
430 // If the stored value is a byte-wise value (like i32 -1), then it may be
431 // turned into a memset of i8 -1, assuming that all the consecutive bytes
432 // are stored. A store of i32 0x01020304 can never be turned into a memset,
433 // but it can be turned into memset_pattern if the target supports it.
434 Value *SplatValue = isBytewiseValue(StoredVal);
435 Constant *PatternValue = nullptr;
436
Anna Thomasb2a212c2017-06-06 16:45:25 +0000437 // Note: memset and memset_pattern on unordered-atomic is yet not supported
438 bool UnorderedAtomic = SI->isUnordered() && !SI->isSimple();
439
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000440 // If we're allowed to form a memset, and the stored value would be
441 // acceptable for memset, use it.
Anna Thomasb2a212c2017-06-06 16:45:25 +0000442 if (!UnorderedAtomic && HasMemset && SplatValue &&
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000443 // Verify that the stored value is loop invariant. If not, we can't
444 // promote the memset.
445 CurLoop->isLoopInvariant(SplatValue)) {
446 // It looks like we can use SplatValue.
Anna Thomas5ecb8f72017-05-19 17:05:36 +0000447 return LegalStoreKind::Memset;
Anna Thomasb2a212c2017-06-06 16:45:25 +0000448 } else if (!UnorderedAtomic && HasMemsetPattern &&
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000449 // Don't create memset_pattern16s with address spaces.
450 StorePtr->getType()->getPointerAddressSpace() == 0 &&
451 (PatternValue = getMemSetPatternValue(StoredVal, DL))) {
452 // It looks like we can use PatternValue!
Anna Thomas5ecb8f72017-05-19 17:05:36 +0000453 return LegalStoreKind::MemsetPattern;
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000454 }
455
456 // Otherwise, see if the store can be turned into a memcpy.
457 if (HasMemcpy) {
458 // Check to see if the stride matches the size of the store. If so, then we
459 // know that every byte is touched in the loop.
Chad Rosier4acff962016-02-12 19:05:27 +0000460 APInt Stride = getStoreStride(StoreEv);
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000461 unsigned StoreSize = getStoreSizeInBytes(SI, DL);
462 if (StoreSize != Stride && StoreSize != -Stride)
Anna Thomas5ecb8f72017-05-19 17:05:36 +0000463 return LegalStoreKind::None;
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000464
465 // The store must be feeding a non-volatile load.
466 LoadInst *LI = dyn_cast<LoadInst>(SI->getValueOperand());
Anna Thomasb2a212c2017-06-06 16:45:25 +0000467
468 // Only allow non-volatile loads
469 if (!LI || LI->isVolatile())
470 return LegalStoreKind::None;
471 // Only allow simple or unordered-atomic loads
472 if (!LI->isUnordered())
Anna Thomas5ecb8f72017-05-19 17:05:36 +0000473 return LegalStoreKind::None;
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000474
475 // See if the pointer expression is an AddRec like {base,+,1} on the current
476 // loop, which indicates a strided load. If we have something else, it's a
477 // random load we can't handle.
478 const SCEVAddRecExpr *LoadEv =
479 dyn_cast<SCEVAddRecExpr>(SE->getSCEV(LI->getPointerOperand()));
480 if (!LoadEv || LoadEv->getLoop() != CurLoop || !LoadEv->isAffine())
Anna Thomas5ecb8f72017-05-19 17:05:36 +0000481 return LegalStoreKind::None;
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000482
483 // The store and load must share the same stride.
484 if (StoreEv->getOperand(1) != LoadEv->getOperand(1))
Anna Thomas5ecb8f72017-05-19 17:05:36 +0000485 return LegalStoreKind::None;
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000486
487 // Success. This store can be converted into a memcpy.
Anna Thomasb2a212c2017-06-06 16:45:25 +0000488 UnorderedAtomic = UnorderedAtomic || LI->isAtomic();
489 return UnorderedAtomic ? LegalStoreKind::UnorderedAtomicMemcpy
490 : LegalStoreKind::Memcpy;
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000491 }
492 // This store can't be transformed into a memset/memcpy.
Anna Thomas5ecb8f72017-05-19 17:05:36 +0000493 return LegalStoreKind::None;
Chad Rosiera548fe52015-11-12 19:09:16 +0000494}
495
Chad Rosiercc9030b2015-11-11 23:00:59 +0000496void LoopIdiomRecognize::collectStores(BasicBlock *BB) {
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000497 StoreRefsForMemset.clear();
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000498 StoreRefsForMemsetPattern.clear();
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000499 StoreRefsForMemcpy.clear();
Chad Rosiercc9030b2015-11-11 23:00:59 +0000500 for (Instruction &I : *BB) {
501 StoreInst *SI = dyn_cast<StoreInst>(&I);
502 if (!SI)
503 continue;
504
Chad Rosiera548fe52015-11-12 19:09:16 +0000505 // Make sure this is a strided store with a constant stride.
Anna Thomas5ecb8f72017-05-19 17:05:36 +0000506 switch (isLegalStore(SI)) {
507 case LegalStoreKind::None:
508 // Nothing to do
509 break;
510 case LegalStoreKind::Memset: {
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000511 // Find the base pointer.
512 Value *Ptr = GetUnderlyingObject(SI->getPointerOperand(), *DL);
513 StoreRefsForMemset[Ptr].push_back(SI);
Anna Thomas5ecb8f72017-05-19 17:05:36 +0000514 } break;
515 case LegalStoreKind::MemsetPattern: {
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000516 // Find the base pointer.
517 Value *Ptr = GetUnderlyingObject(SI->getPointerOperand(), *DL);
518 StoreRefsForMemsetPattern[Ptr].push_back(SI);
Anna Thomas5ecb8f72017-05-19 17:05:36 +0000519 } break;
520 case LegalStoreKind::Memcpy:
Anna Thomasb2a212c2017-06-06 16:45:25 +0000521 case LegalStoreKind::UnorderedAtomicMemcpy:
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000522 StoreRefsForMemcpy.push_back(SI);
Anna Thomas5ecb8f72017-05-19 17:05:36 +0000523 break;
524 default:
525 assert(false && "unhandled return value");
526 break;
527 }
Chad Rosiercc9030b2015-11-11 23:00:59 +0000528 }
529}
530
Chris Lattner8455b6e2011-01-02 19:01:03 +0000531/// runOnLoopBlock - Process the specified block, which lives in a counted loop
532/// with the specified backedge count. This block is known to be in the current
533/// loop and not in any subloops.
Chandler Carruthbad690e2015-08-12 23:06:37 +0000534bool LoopIdiomRecognize::runOnLoopBlock(
535 BasicBlock *BB, const SCEV *BECount,
536 SmallVectorImpl<BasicBlock *> &ExitBlocks) {
Chris Lattner8455b6e2011-01-02 19:01:03 +0000537 // We can only promote stores in this block if they are unconditionally
538 // executed in the loop. For a block to be unconditionally executed, it has
539 // to dominate all the exit blocks of the loop. Verify this now.
540 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
541 if (!DT->dominates(BB, ExitBlocks[i]))
542 return false;
Andrew Trick328b2232011-03-14 16:48:10 +0000543
Chris Lattner7c5f9c32010-12-26 20:45:45 +0000544 bool MadeChange = false;
Chad Rosiercc9030b2015-11-11 23:00:59 +0000545 // Look for store instructions, which may be optimized to memset/memcpy.
546 collectStores(BB);
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000547
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000548 // Look for a single store or sets of stores with a common base, which can be
549 // optimized into a memset (memset_pattern). The latter most commonly happens
550 // with structs and handunrolled loops.
551 for (auto &SL : StoreRefsForMemset)
552 MadeChange |= processLoopStores(SL.second, BECount, true);
553
554 for (auto &SL : StoreRefsForMemsetPattern)
555 MadeChange |= processLoopStores(SL.second, BECount, false);
Chad Rosiercc9030b2015-11-11 23:00:59 +0000556
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000557 // Optimize the store into a memcpy, if it feeds an similarly strided load.
558 for (auto &SI : StoreRefsForMemcpy)
559 MadeChange |= processLoopStoreOfLoopLoad(SI, BECount);
560
Chandler Carruthbad690e2015-08-12 23:06:37 +0000561 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000562 Instruction *Inst = &*I++;
Chris Lattner86438102011-01-04 07:46:33 +0000563 // Look for memset instructions, which may be optimized to a larger memset.
Chandler Carruthbad690e2015-08-12 23:06:37 +0000564 if (MemSetInst *MSI = dyn_cast<MemSetInst>(Inst)) {
Sanjoy Dase6bca0e2017-05-01 17:07:49 +0000565 WeakTrackingVH InstPtr(&*I);
Chandler Carruthbad690e2015-08-12 23:06:37 +0000566 if (!processLoopMemSet(MSI, BECount))
567 continue;
Chris Lattner86438102011-01-04 07:46:33 +0000568 MadeChange = true;
Andrew Trick328b2232011-03-14 16:48:10 +0000569
Chris Lattner86438102011-01-04 07:46:33 +0000570 // If processing the memset invalidated our iterator, start over from the
571 // top of the block.
Craig Topperf40110f2014-04-25 05:29:35 +0000572 if (!InstPtr)
Chris Lattner86438102011-01-04 07:46:33 +0000573 I = BB->begin();
574 continue;
575 }
Chris Lattner7c5f9c32010-12-26 20:45:45 +0000576 }
Andrew Trick328b2232011-03-14 16:48:10 +0000577
Chris Lattner7c5f9c32010-12-26 20:45:45 +0000578 return MadeChange;
Chris Lattner81ae3f22010-12-26 19:39:38 +0000579}
580
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000581/// processLoopStores - See if this store(s) can be promoted to a memset.
582bool LoopIdiomRecognize::processLoopStores(SmallVectorImpl<StoreInst *> &SL,
583 const SCEV *BECount,
584 bool ForMemset) {
585 // Try to find consecutive stores that can be transformed into memsets.
586 SetVector<StoreInst *> Heads, Tails;
587 SmallDenseMap<StoreInst *, StoreInst *> ConsecutiveChain;
Chris Lattner86438102011-01-04 07:46:33 +0000588
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000589 // Do a quadratic search on all of the given stores and find
590 // all of the pairs of stores that follow each other.
591 SmallVector<unsigned, 16> IndexQueue;
592 for (unsigned i = 0, e = SL.size(); i < e; ++i) {
593 assert(SL[i]->isSimple() && "Expected only non-volatile stores.");
Andrew Trick328b2232011-03-14 16:48:10 +0000594
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000595 Value *FirstStoredVal = SL[i]->getValueOperand();
596 Value *FirstStorePtr = SL[i]->getPointerOperand();
597 const SCEVAddRecExpr *FirstStoreEv =
598 cast<SCEVAddRecExpr>(SE->getSCEV(FirstStorePtr));
Chad Rosier4acff962016-02-12 19:05:27 +0000599 APInt FirstStride = getStoreStride(FirstStoreEv);
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000600 unsigned FirstStoreSize = getStoreSizeInBytes(SL[i], DL);
Chad Rosier79676142015-10-28 14:38:49 +0000601
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000602 // See if we can optimize just this store in isolation.
Chad Rosier4acff962016-02-12 19:05:27 +0000603 if (FirstStride == FirstStoreSize || -FirstStride == FirstStoreSize) {
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000604 Heads.insert(SL[i]);
605 continue;
606 }
Chris Lattner0f4a6402011-02-19 19:31:39 +0000607
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000608 Value *FirstSplatValue = nullptr;
609 Constant *FirstPatternValue = nullptr;
610
611 if (ForMemset)
612 FirstSplatValue = isBytewiseValue(FirstStoredVal);
613 else
614 FirstPatternValue = getMemSetPatternValue(FirstStoredVal, DL);
615
616 assert((FirstSplatValue || FirstPatternValue) &&
617 "Expected either splat value or pattern value.");
618
619 IndexQueue.clear();
620 // If a store has multiple consecutive store candidates, search Stores
621 // array according to the sequence: from i+1 to e, then from i-1 to 0.
622 // This is because usually pairing with immediate succeeding or preceding
623 // candidate create the best chance to find memset opportunity.
624 unsigned j = 0;
625 for (j = i + 1; j < e; ++j)
626 IndexQueue.push_back(j);
627 for (j = i; j > 0; --j)
628 IndexQueue.push_back(j - 1);
629
630 for (auto &k : IndexQueue) {
631 assert(SL[k]->isSimple() && "Expected only non-volatile stores.");
632 Value *SecondStorePtr = SL[k]->getPointerOperand();
633 const SCEVAddRecExpr *SecondStoreEv =
634 cast<SCEVAddRecExpr>(SE->getSCEV(SecondStorePtr));
Chad Rosier4acff962016-02-12 19:05:27 +0000635 APInt SecondStride = getStoreStride(SecondStoreEv);
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000636
637 if (FirstStride != SecondStride)
638 continue;
639
640 Value *SecondStoredVal = SL[k]->getValueOperand();
641 Value *SecondSplatValue = nullptr;
642 Constant *SecondPatternValue = nullptr;
643
644 if (ForMemset)
645 SecondSplatValue = isBytewiseValue(SecondStoredVal);
646 else
647 SecondPatternValue = getMemSetPatternValue(SecondStoredVal, DL);
648
649 assert((SecondSplatValue || SecondPatternValue) &&
650 "Expected either splat value or pattern value.");
651
652 if (isConsecutiveAccess(SL[i], SL[k], *DL, *SE, false)) {
653 if (ForMemset) {
654 if (FirstSplatValue != SecondSplatValue)
655 continue;
656 } else {
657 if (FirstPatternValue != SecondPatternValue)
658 continue;
659 }
660 Tails.insert(SL[k]);
661 Heads.insert(SL[i]);
662 ConsecutiveChain[SL[i]] = SL[k];
663 break;
664 }
665 }
666 }
667
668 // We may run into multiple chains that merge into a single chain. We mark the
669 // stores that we transformed so that we don't visit the same store twice.
670 SmallPtrSet<Value *, 16> TransformedStores;
671 bool Changed = false;
672
673 // For stores that start but don't end a link in the chain:
674 for (SetVector<StoreInst *>::iterator it = Heads.begin(), e = Heads.end();
675 it != e; ++it) {
676 if (Tails.count(*it))
677 continue;
678
679 // We found a store instr that starts a chain. Now follow the chain and try
680 // to transform it.
681 SmallPtrSet<Instruction *, 8> AdjacentStores;
682 StoreInst *I = *it;
683
684 StoreInst *HeadStore = I;
685 unsigned StoreSize = 0;
686
687 // Collect the chain into a list.
688 while (Tails.count(I) || Heads.count(I)) {
689 if (TransformedStores.count(I))
690 break;
691 AdjacentStores.insert(I);
692
693 StoreSize += getStoreSizeInBytes(I, DL);
694 // Move to the next value in the chain.
695 I = ConsecutiveChain[I];
696 }
697
698 Value *StoredVal = HeadStore->getValueOperand();
699 Value *StorePtr = HeadStore->getPointerOperand();
700 const SCEVAddRecExpr *StoreEv = cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr));
Chad Rosier4acff962016-02-12 19:05:27 +0000701 APInt Stride = getStoreStride(StoreEv);
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000702
703 // Check to see if the stride matches the size of the stores. If so, then
704 // we know that every byte is touched in the loop.
705 if (StoreSize != Stride && StoreSize != -Stride)
706 continue;
707
708 bool NegStride = StoreSize == -Stride;
709
710 if (processLoopStridedStore(StorePtr, StoreSize, HeadStore->getAlignment(),
711 StoredVal, HeadStore, AdjacentStores, StoreEv,
712 BECount, NegStride)) {
713 TransformedStores.insert(AdjacentStores.begin(), AdjacentStores.end());
714 Changed = true;
715 }
716 }
717
718 return Changed;
Chris Lattner81ae3f22010-12-26 19:39:38 +0000719}
720
Chris Lattner86438102011-01-04 07:46:33 +0000721/// processLoopMemSet - See if this memset can be promoted to a large memset.
Chandler Carruthbad690e2015-08-12 23:06:37 +0000722bool LoopIdiomRecognize::processLoopMemSet(MemSetInst *MSI,
723 const SCEV *BECount) {
Chris Lattner86438102011-01-04 07:46:33 +0000724 // We can only handle non-volatile memsets with a constant size.
Chandler Carruthbad690e2015-08-12 23:06:37 +0000725 if (MSI->isVolatile() || !isa<ConstantInt>(MSI->getLength()))
726 return false;
Chris Lattner86438102011-01-04 07:46:33 +0000727
Chris Lattnere6b261f2011-02-18 22:22:15 +0000728 // If we're not allowed to hack on memset, we fail.
Ahmed Bougacha7f971932016-04-27 19:04:46 +0000729 if (!HasMemset)
Chris Lattnere6b261f2011-02-18 22:22:15 +0000730 return false;
Andrew Trick328b2232011-03-14 16:48:10 +0000731
Chris Lattner86438102011-01-04 07:46:33 +0000732 Value *Pointer = MSI->getDest();
Andrew Trick328b2232011-03-14 16:48:10 +0000733
Chris Lattner86438102011-01-04 07:46:33 +0000734 // See if the pointer expression is an AddRec like {base,+,1} on the current
735 // loop, which indicates a strided store. If we have something else, it's a
736 // random store we can't handle.
737 const SCEVAddRecExpr *Ev = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Pointer));
Craig Topperf40110f2014-04-25 05:29:35 +0000738 if (!Ev || Ev->getLoop() != CurLoop || !Ev->isAffine())
Chris Lattner86438102011-01-04 07:46:33 +0000739 return false;
740
741 // Reject memsets that are so large that they overflow an unsigned.
742 uint64_t SizeInBytes = cast<ConstantInt>(MSI->getLength())->getZExtValue();
743 if ((SizeInBytes >> 32) != 0)
744 return false;
Andrew Trick328b2232011-03-14 16:48:10 +0000745
Chris Lattner86438102011-01-04 07:46:33 +0000746 // Check to see if the stride matches the size of the memset. If so, then we
747 // know that every byte is touched in the loop.
Chad Rosier81362a82016-02-12 21:03:23 +0000748 const SCEVConstant *ConstStride = dyn_cast<SCEVConstant>(Ev->getOperand(1));
749 if (!ConstStride)
750 return false;
Andrew Trick328b2232011-03-14 16:48:10 +0000751
Chad Rosier81362a82016-02-12 21:03:23 +0000752 APInt Stride = ConstStride->getAPInt();
753 if (SizeInBytes != Stride && SizeInBytes != -Stride)
Chris Lattner86438102011-01-04 07:46:33 +0000754 return false;
Andrew Trick328b2232011-03-14 16:48:10 +0000755
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000756 // Verify that the memset value is loop invariant. If not, we can't promote
757 // the memset.
758 Value *SplatValue = MSI->getValue();
759 if (!SplatValue || !CurLoop->isLoopInvariant(SplatValue))
760 return false;
761
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000762 SmallPtrSet<Instruction *, 1> MSIs;
763 MSIs.insert(MSI);
Chad Rosier81362a82016-02-12 21:03:23 +0000764 bool NegStride = SizeInBytes == -Stride;
Chris Lattner0f4a6402011-02-19 19:31:39 +0000765 return processLoopStridedStore(Pointer, (unsigned)SizeInBytes,
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000766 MSI->getAlignment(), SplatValue, MSI, MSIs, Ev,
Andrew Kaylor7cdf01e2016-08-11 18:28:33 +0000767 BECount, NegStride, /*IsLoopMemset=*/true);
Chris Lattner86438102011-01-04 07:46:33 +0000768}
769
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000770/// mayLoopAccessLocation - Return true if the specified loop might access the
771/// specified pointer location, which is a loop-strided access. The 'Access'
772/// argument specifies what the verboten forms of access are (read or write).
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000773static bool
774mayLoopAccessLocation(Value *Ptr, ModRefInfo Access, Loop *L,
775 const SCEV *BECount, unsigned StoreSize,
776 AliasAnalysis &AA,
777 SmallPtrSetImpl<Instruction *> &IgnoredStores) {
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000778 // Get the location that may be stored across the loop. Since the access is
779 // strided positively through memory, we say that the modified location starts
780 // at the pointer and has infinite size.
Chandler Carruthecbd1682015-06-17 07:21:38 +0000781 uint64_t AccessSize = MemoryLocation::UnknownSize;
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000782
783 // If the loop iterates a fixed number of times, we can refine the access size
784 // to be exactly the size of the memset, which is (BECount+1)*StoreSize
785 if (const SCEVConstant *BECst = dyn_cast<SCEVConstant>(BECount))
Chandler Carruthbad690e2015-08-12 23:06:37 +0000786 AccessSize = (BECst->getValue()->getZExtValue() + 1) * StoreSize;
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000787
788 // TODO: For this to be really effective, we have to dive into the pointer
789 // operand in the store. Store to &A[i] of 100 will always return may alias
790 // with store of &A[100], we need to StoreLoc to be "A" with size of 100,
791 // which will then no-alias a store to &A[100].
Chandler Carruthac80dc72015-06-17 07:18:54 +0000792 MemoryLocation StoreLoc(Ptr, AccessSize);
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000793
794 for (Loop::block_iterator BI = L->block_begin(), E = L->block_end(); BI != E;
795 ++BI)
Benjamin Kramer135f7352016-06-26 12:28:59 +0000796 for (Instruction &I : **BI)
797 if (IgnoredStores.count(&I) == 0 &&
798 (AA.getModRefInfo(&I, StoreLoc) & Access))
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000799 return true;
800
801 return false;
802}
803
Chad Rosiered0c7d12015-11-13 19:11:07 +0000804// If we have a negative stride, Start refers to the end of the memory location
805// we're trying to memset. Therefore, we need to recompute the base pointer,
806// which is just Start - BECount*Size.
807static const SCEV *getStartForNegStride(const SCEV *Start, const SCEV *BECount,
808 Type *IntPtr, unsigned StoreSize,
809 ScalarEvolution *SE) {
810 const SCEV *Index = SE->getTruncateOrZeroExtend(BECount, IntPtr);
811 if (StoreSize != 1)
812 Index = SE->getMulExpr(Index, SE->getConstant(IntPtr, StoreSize),
813 SCEV::FlagNUW);
814 return SE->getMinusSCEV(Start, Index);
815}
816
Chandler Carruth1dc34c62017-07-25 10:48:32 +0000817/// Compute the number of bytes as a SCEV from the backedge taken count.
818///
819/// This also maps the SCEV into the provided type and tries to handle the
820/// computation in a way that will fold cleanly.
821static const SCEV *getNumBytes(const SCEV *BECount, Type *IntPtr,
822 unsigned StoreSize, Loop *CurLoop,
823 const DataLayout *DL, ScalarEvolution *SE) {
824 const SCEV *NumBytesS;
825 // The # stored bytes is (BECount+1)*Size. Expand the trip count out to
826 // pointer size if it isn't already.
827 //
828 // If we're going to need to zero extend the BE count, check if we can add
829 // one to it prior to zero extending without overflow. Provided this is safe,
830 // it allows better simplification of the +1.
831 if (DL->getTypeSizeInBits(BECount->getType()) <
832 DL->getTypeSizeInBits(IntPtr) &&
833 SE->isLoopEntryGuardedByCond(
834 CurLoop, ICmpInst::ICMP_NE, BECount,
835 SE->getNegativeSCEV(SE->getOne(BECount->getType())))) {
836 NumBytesS = SE->getZeroExtendExpr(
837 SE->getAddExpr(BECount, SE->getOne(BECount->getType()), SCEV::FlagNUW),
838 IntPtr);
839 } else {
840 NumBytesS = SE->getAddExpr(SE->getTruncateOrZeroExtend(BECount, IntPtr),
841 SE->getOne(IntPtr), SCEV::FlagNUW);
842 }
843
844 // And scale it based on the store size.
845 if (StoreSize != 1) {
846 NumBytesS = SE->getMulExpr(NumBytesS, SE->getConstant(IntPtr, StoreSize),
847 SCEV::FlagNUW);
848 }
849 return NumBytesS;
850}
851
Chris Lattner0f4a6402011-02-19 19:31:39 +0000852/// processLoopStridedStore - We see a strided store of some value. If we can
853/// transform this into a memset or memset_pattern in the loop preheader, do so.
Chandler Carruthbad690e2015-08-12 23:06:37 +0000854bool LoopIdiomRecognize::processLoopStridedStore(
855 Value *DestPtr, unsigned StoreSize, unsigned StoreAlignment,
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000856 Value *StoredVal, Instruction *TheStore,
857 SmallPtrSetImpl<Instruction *> &Stores, const SCEVAddRecExpr *Ev,
Andrew Kaylor7cdf01e2016-08-11 18:28:33 +0000858 const SCEV *BECount, bool NegStride, bool IsLoopMemset) {
Chris Lattner0f4a6402011-02-19 19:31:39 +0000859 Value *SplatValue = isBytewiseValue(StoredVal);
Craig Topperf40110f2014-04-25 05:29:35 +0000860 Constant *PatternValue = nullptr;
Matt Arsenault009faed2013-09-11 05:09:42 +0000861
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000862 if (!SplatValue)
863 PatternValue = getMemSetPatternValue(StoredVal, DL);
864
865 assert((SplatValue || PatternValue) &&
866 "Expected either splat value or pattern value.");
Andrew Trick328b2232011-03-14 16:48:10 +0000867
Chris Lattnerc4ca7ab2011-05-22 17:39:56 +0000868 // The trip count of the loop and the base pointer of the addrec SCEV is
869 // guaranteed to be loop invariant, which means that it should dominate the
870 // header. This allows us to insert code for it in the preheader.
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000871 unsigned DestAS = DestPtr->getType()->getPointerAddressSpace();
Chris Lattnerc4ca7ab2011-05-22 17:39:56 +0000872 BasicBlock *Preheader = CurLoop->getLoopPreheader();
873 IRBuilder<> Builder(Preheader->getTerminator());
Chad Rosier43f9b482015-11-06 16:33:57 +0000874 SCEVExpander Expander(*SE, *DL, "loop-idiom");
Andrew Trick60ab3ef2011-06-28 05:04:16 +0000875
Matt Arsenault009faed2013-09-11 05:09:42 +0000876 Type *DestInt8PtrTy = Builder.getInt8PtrTy(DestAS);
Chad Rosier43f9b482015-11-06 16:33:57 +0000877 Type *IntPtr = Builder.getIntPtrTy(*DL, DestAS);
Chad Rosier79676142015-10-28 14:38:49 +0000878
879 const SCEV *Start = Ev->getStart();
Chad Rosier2fa50a72015-11-13 19:13:40 +0000880 // Handle negative strided loops.
Chad Rosiered0c7d12015-11-13 19:11:07 +0000881 if (NegStride)
882 Start = getStartForNegStride(Start, BECount, IntPtr, StoreSize, SE);
Matt Arsenault009faed2013-09-11 05:09:42 +0000883
Aditya Kumar1c42d132017-05-05 14:49:45 +0000884 // TODO: ideally we should still be able to generate memset if SCEV expander
885 // is taught to generate the dependencies at the latest point.
886 if (!isSafeToExpand(Start, *SE))
887 return false;
888
Chris Lattner29e14ed2010-12-26 23:42:51 +0000889 // Okay, we have a strided store "p[i]" of a splattable value. We can turn
Benjamin Kramerf77f2242012-10-21 19:31:16 +0000890 // this into a memset in the loop preheader now if we want. However, this
891 // would be unsafe to do if there is anything else in the loop that may read
Chandler Carruth7ec50852012-11-01 08:07:29 +0000892 // or write to the aliased location. Check for any overlap by generating the
893 // base pointer and checking the region.
Chad Rosier79676142015-10-28 14:38:49 +0000894 Value *BasePtr =
895 Expander.expandCodeFor(Start, DestInt8PtrTy, Preheader->getTerminator());
Chandler Carruth194f59c2015-07-22 23:15:57 +0000896 if (mayLoopAccessLocation(BasePtr, MRI_ModRef, CurLoop, BECount, StoreSize,
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000897 *AA, Stores)) {
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000898 Expander.clear();
899 // If we generated new code for the base pointer, clean up.
Benjamin Kramerf094d772015-02-07 21:37:08 +0000900 RecursivelyDeleteTriviallyDeadInstructions(BasePtr, TLI);
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000901 return false;
902 }
903
Andrew Kaylor7cdf01e2016-08-11 18:28:33 +0000904 if (avoidLIRForMultiBlockLoop(/*IsMemset=*/true, IsLoopMemset))
905 return false;
906
Chris Lattnerc4ca7ab2011-05-22 17:39:56 +0000907 // Okay, everything looks good, insert the memset.
908
Chandler Carruthbad690e2015-08-12 23:06:37 +0000909 const SCEV *NumBytesS =
Chandler Carruth1dc34c62017-07-25 10:48:32 +0000910 getNumBytes(BECount, IntPtr, StoreSize, CurLoop, DL, SE);
Andrew Trick328b2232011-03-14 16:48:10 +0000911
Aditya Kumar1c42d132017-05-05 14:49:45 +0000912 // TODO: ideally we should still be able to generate memset if SCEV expander
913 // is taught to generate the dependencies at the latest point.
914 if (!isSafeToExpand(NumBytesS, *SE))
915 return false;
916
Andrew Trick328b2232011-03-14 16:48:10 +0000917 Value *NumBytes =
Chandler Carruthbad690e2015-08-12 23:06:37 +0000918 Expander.expandCodeFor(NumBytesS, IntPtr, Preheader->getTerminator());
Andrew Trick328b2232011-03-14 16:48:10 +0000919
Devang Pateld00c6282011-03-07 22:43:45 +0000920 CallInst *NewCall;
Matt Arsenault5df49bd2013-09-11 05:09:35 +0000921 if (SplatValue) {
Chandler Carruthbad690e2015-08-12 23:06:37 +0000922 NewCall =
923 Builder.CreateMemSet(BasePtr, SplatValue, NumBytes, StoreAlignment);
Matt Arsenault5df49bd2013-09-11 05:09:35 +0000924 } else {
Matt Arsenault009faed2013-09-11 05:09:42 +0000925 // Everything is emitted in default address space
926 Type *Int8PtrTy = DestInt8PtrTy;
927
Sanjay Patelaf674fb2015-12-14 17:24:23 +0000928 Module *M = TheStore->getModule();
Mehdi Aminidb11fdf2017-04-06 20:23:57 +0000929 Value *MSP =
930 M->getOrInsertFunction("memset_pattern16", Builder.getVoidTy(),
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000931 Int8PtrTy, Int8PtrTy, IntPtr);
Ahmed Bougachaace97c12016-04-27 19:04:50 +0000932 inferLibFuncAttributes(*M->getFunction("memset_pattern16"), *TLI);
Andrew Trick328b2232011-03-14 16:48:10 +0000933
Chris Lattner0f4a6402011-02-19 19:31:39 +0000934 // Otherwise we should form a memset_pattern16. PatternValue is known to be
935 // an constant array of 16-bytes. Plop the value into a mergable global.
936 GlobalVariable *GV = new GlobalVariable(*M, PatternValue->getType(), true,
Benjamin Kramer838752d2015-03-03 00:17:09 +0000937 GlobalValue::PrivateLinkage,
Chris Lattner0f4a6402011-02-19 19:31:39 +0000938 PatternValue, ".memset_pattern");
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000939 GV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global); // Ok to merge these.
Chris Lattner0f4a6402011-02-19 19:31:39 +0000940 GV->setAlignment(16);
Matt Arsenault009faed2013-09-11 05:09:42 +0000941 Value *PatternPtr = ConstantExpr::getBitCast(GV, Int8PtrTy);
David Blaikieff6409d2015-05-18 22:13:54 +0000942 NewCall = Builder.CreateCall(MSP, {BasePtr, PatternPtr, NumBytes});
Chris Lattner0f4a6402011-02-19 19:31:39 +0000943 }
Andrew Trick328b2232011-03-14 16:48:10 +0000944
Chris Lattner29e14ed2010-12-26 23:42:51 +0000945 DEBUG(dbgs() << " Formed memset: " << *NewCall << "\n"
Chris Lattner86438102011-01-04 07:46:33 +0000946 << " from store to: " << *Ev << " at: " << *TheStore << "\n");
Devang Pateld00c6282011-03-07 22:43:45 +0000947 NewCall->setDebugLoc(TheStore->getDebugLoc());
Andrew Trick328b2232011-03-14 16:48:10 +0000948
Chris Lattnerb9fe6852010-12-27 00:03:23 +0000949 // Okay, the memset has been formed. Zap the original store and anything that
950 // feeds into it.
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000951 for (auto *I : Stores)
David Majnemer41ff4fd2016-06-20 16:07:38 +0000952 deleteDeadInstruction(I);
Chris Lattner12f91be2011-01-02 07:36:44 +0000953 ++NumMemSet;
Chris Lattner29e14ed2010-12-26 23:42:51 +0000954 return true;
955}
956
Chad Rosier1cd3da12015-11-19 21:33:07 +0000957/// If the stored value is a strided load in the same loop with the same stride
958/// this may be transformable into a memcpy. This kicks in for stuff like
Xin Tonga41bf702017-05-01 23:08:19 +0000959/// for (i) A[i] = B[i];
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000960bool LoopIdiomRecognize::processLoopStoreOfLoopLoad(StoreInst *SI,
961 const SCEV *BECount) {
Anna Thomasb2a212c2017-06-06 16:45:25 +0000962 assert(SI->isUnordered() && "Expected only non-volatile non-ordered stores.");
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000963
964 Value *StorePtr = SI->getPointerOperand();
965 const SCEVAddRecExpr *StoreEv = cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr));
Chad Rosier4acff962016-02-12 19:05:27 +0000966 APInt Stride = getStoreStride(StoreEv);
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000967 unsigned StoreSize = getStoreSizeInBytes(SI, DL);
968 bool NegStride = StoreSize == -Stride;
Andrew Trick328b2232011-03-14 16:48:10 +0000969
Chad Rosierfddc01f2015-11-19 18:22:21 +0000970 // The store must be feeding a non-volatile load.
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000971 LoadInst *LI = cast<LoadInst>(SI->getValueOperand());
Anna Thomasb2a212c2017-06-06 16:45:25 +0000972 assert(LI->isUnordered() && "Expected only non-volatile non-ordered loads.");
Chad Rosierfddc01f2015-11-19 18:22:21 +0000973
974 // See if the pointer expression is an AddRec like {base,+,1} on the current
975 // loop, which indicates a strided load. If we have something else, it's a
976 // random load we can't handle.
Chad Rosier3ecc8d82015-11-19 18:25:11 +0000977 const SCEVAddRecExpr *LoadEv =
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000978 cast<SCEVAddRecExpr>(SE->getSCEV(LI->getPointerOperand()));
Andrew Trick328b2232011-03-14 16:48:10 +0000979
Chris Lattnerc4ca7ab2011-05-22 17:39:56 +0000980 // The trip count of the loop and the base pointer of the addrec SCEV is
981 // guaranteed to be loop invariant, which means that it should dominate the
982 // header. This allows us to insert code for it in the preheader.
983 BasicBlock *Preheader = CurLoop->getLoopPreheader();
984 IRBuilder<> Builder(Preheader->getTerminator());
Chad Rosier43f9b482015-11-06 16:33:57 +0000985 SCEVExpander Expander(*SE, *DL, "loop-idiom");
Andrew Trick60ab3ef2011-06-28 05:04:16 +0000986
Chad Rosiercc299b62015-11-13 21:51:02 +0000987 const SCEV *StrStart = StoreEv->getStart();
988 unsigned StrAS = SI->getPointerAddressSpace();
989 Type *IntPtrTy = Builder.getIntPtrTy(*DL, StrAS);
990
991 // Handle negative strided loops.
992 if (NegStride)
993 StrStart = getStartForNegStride(StrStart, BECount, IntPtrTy, StoreSize, SE);
994
Chris Lattner85b6d812011-01-02 03:37:56 +0000995 // Okay, we have a strided store "p[i]" of a loaded value. We can turn
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000996 // this into a memcpy in the loop preheader now if we want. However, this
997 // would be unsafe to do if there is anything else in the loop that may read
998 // or write the memory region we're storing to. This includes the load that
999 // feeds the stores. Check for an alias by generating the base address and
1000 // checking everything.
Chandler Carruthbad690e2015-08-12 23:06:37 +00001001 Value *StoreBasePtr = Expander.expandCodeFor(
Chad Rosiercc299b62015-11-13 21:51:02 +00001002 StrStart, Builder.getInt8PtrTy(StrAS), Preheader->getTerminator());
Chandler Carruth099f5cb02012-11-02 08:33:25 +00001003
Haicheng Wuf1c00a22016-01-26 02:27:47 +00001004 SmallPtrSet<Instruction *, 1> Stores;
1005 Stores.insert(SI);
Chandler Carruth194f59c2015-07-22 23:15:57 +00001006 if (mayLoopAccessLocation(StoreBasePtr, MRI_ModRef, CurLoop, BECount,
Haicheng Wuf1c00a22016-01-26 02:27:47 +00001007 StoreSize, *AA, Stores)) {
Chandler Carruth099f5cb02012-11-02 08:33:25 +00001008 Expander.clear();
1009 // If we generated new code for the base pointer, clean up.
Benjamin Kramerf094d772015-02-07 21:37:08 +00001010 RecursivelyDeleteTriviallyDeadInstructions(StoreBasePtr, TLI);
Chandler Carruth099f5cb02012-11-02 08:33:25 +00001011 return false;
1012 }
1013
Chad Rosiercc299b62015-11-13 21:51:02 +00001014 const SCEV *LdStart = LoadEv->getStart();
1015 unsigned LdAS = LI->getPointerAddressSpace();
1016
1017 // Handle negative strided loops.
1018 if (NegStride)
1019 LdStart = getStartForNegStride(LdStart, BECount, IntPtrTy, StoreSize, SE);
1020
Chandler Carruth099f5cb02012-11-02 08:33:25 +00001021 // For a memcpy, we have to make sure that the input array is not being
1022 // mutated by the loop.
Chandler Carruthbad690e2015-08-12 23:06:37 +00001023 Value *LoadBasePtr = Expander.expandCodeFor(
Chad Rosiercc299b62015-11-13 21:51:02 +00001024 LdStart, Builder.getInt8PtrTy(LdAS), Preheader->getTerminator());
Chris Lattnerc4ca7ab2011-05-22 17:39:56 +00001025
Chandler Carruth194f59c2015-07-22 23:15:57 +00001026 if (mayLoopAccessLocation(LoadBasePtr, MRI_Mod, CurLoop, BECount, StoreSize,
Haicheng Wuf1c00a22016-01-26 02:27:47 +00001027 *AA, Stores)) {
Chandler Carruth099f5cb02012-11-02 08:33:25 +00001028 Expander.clear();
1029 // If we generated new code for the base pointer, clean up.
Benjamin Kramerf094d772015-02-07 21:37:08 +00001030 RecursivelyDeleteTriviallyDeadInstructions(LoadBasePtr, TLI);
1031 RecursivelyDeleteTriviallyDeadInstructions(StoreBasePtr, TLI);
Chandler Carruth099f5cb02012-11-02 08:33:25 +00001032 return false;
1033 }
1034
Andrew Kaylor7cdf01e2016-08-11 18:28:33 +00001035 if (avoidLIRForMultiBlockLoop())
1036 return false;
1037
Chris Lattnerc4ca7ab2011-05-22 17:39:56 +00001038 // Okay, everything is safe, we can transform this!
Andrew Trick60ab3ef2011-06-28 05:04:16 +00001039
Chandler Carruthbad690e2015-08-12 23:06:37 +00001040 const SCEV *NumBytesS =
Chandler Carruth1dc34c62017-07-25 10:48:32 +00001041 getNumBytes(BECount, IntPtrTy, StoreSize, CurLoop, DL, SE);
Daniel Neilson3faabbb2017-06-16 14:43:59 +00001042
1043 Value *NumBytes =
1044 Expander.expandCodeFor(NumBytesS, IntPtrTy, Preheader->getTerminator());
1045
Anna Thomasb2a212c2017-06-06 16:45:25 +00001046 unsigned Align = std::min(SI->getAlignment(), LI->getAlignment());
1047 CallInst *NewCall = nullptr;
1048 // Check whether to generate an unordered atomic memcpy:
1049 // If the load or store are atomic, then they must neccessarily be unordered
1050 // by previous checks.
Daniel Neilson3faabbb2017-06-16 14:43:59 +00001051 if (!SI->isAtomic() && !LI->isAtomic())
Anna Thomasb2a212c2017-06-06 16:45:25 +00001052 NewCall = Builder.CreateMemCpy(StoreBasePtr, LoadBasePtr, NumBytes, Align);
Daniel Neilson3faabbb2017-06-16 14:43:59 +00001053 else {
Anna Thomasb2a212c2017-06-06 16:45:25 +00001054 // We cannot allow unaligned ops for unordered load/store, so reject
1055 // anything where the alignment isn't at least the element size.
1056 if (Align < StoreSize)
1057 return false;
1058
1059 // If the element.atomic memcpy is not lowered into explicit
1060 // loads/stores later, then it will be lowered into an element-size
1061 // specific lib call. If the lib call doesn't exist for our store size, then
1062 // we shouldn't generate the memcpy.
1063 if (StoreSize > TTI->getAtomicMemIntrinsicMaxElementSize())
1064 return false;
1065
Daniel Neilson3faabbb2017-06-16 14:43:59 +00001066 NewCall = Builder.CreateElementUnorderedAtomicMemCpy(
1067 StoreBasePtr, LoadBasePtr, NumBytes, StoreSize);
Anna Thomasb2a212c2017-06-06 16:45:25 +00001068
Anna Thomasb2a212c2017-06-06 16:45:25 +00001069 // Propagate alignment info onto the pointer args. Note that unordered
1070 // atomic loads/stores are *required* by the spec to have an alignment
1071 // but non-atomic loads/stores may not.
1072 NewCall->addParamAttr(0, Attribute::getWithAlignment(NewCall->getContext(),
1073 SI->getAlignment()));
1074 NewCall->addParamAttr(1, Attribute::getWithAlignment(NewCall->getContext(),
1075 LI->getAlignment()));
1076 }
Devang Patel0daa07e2011-05-04 21:37:05 +00001077 NewCall->setDebugLoc(SI->getDebugLoc());
Andrew Trick328b2232011-03-14 16:48:10 +00001078
Chandler Carruth099f5cb02012-11-02 08:33:25 +00001079 DEBUG(dbgs() << " Formed memcpy: " << *NewCall << "\n"
Chris Lattner85b6d812011-01-02 03:37:56 +00001080 << " from load ptr=" << *LoadEv << " at: " << *LI << "\n"
1081 << " from store ptr=" << *StoreEv << " at: " << *SI << "\n");
Andrew Trick60ab3ef2011-06-28 05:04:16 +00001082
Chad Rosier7f08d802015-10-13 20:59:16 +00001083 // Okay, the memcpy has been formed. Zap the original store and anything that
Chris Lattner85b6d812011-01-02 03:37:56 +00001084 // feeds into it.
David Majnemer41ff4fd2016-06-20 16:07:38 +00001085 deleteDeadInstruction(SI);
Chandler Carruth099f5cb02012-11-02 08:33:25 +00001086 ++NumMemCpy;
Chris Lattner85b6d812011-01-02 03:37:56 +00001087 return true;
1088}
Chandler Carruthd9c60702015-08-13 00:10:03 +00001089
Andrew Kaylor7cdf01e2016-08-11 18:28:33 +00001090// When compiling for codesize we avoid idiom recognition for a multi-block loop
1091// unless it is a loop_memset idiom or a memset/memcpy idiom in a nested loop.
1092//
1093bool LoopIdiomRecognize::avoidLIRForMultiBlockLoop(bool IsMemset,
1094 bool IsLoopMemset) {
1095 if (ApplyCodeSizeHeuristics && CurLoop->getNumBlocks() > 1) {
1096 if (!CurLoop->getParentLoop() && (!IsMemset || !IsLoopMemset)) {
1097 DEBUG(dbgs() << " " << CurLoop->getHeader()->getParent()->getName()
1098 << " : LIR " << (IsMemset ? "Memset" : "Memcpy")
1099 << " avoided: multi-block top-level loop\n");
1100 return true;
1101 }
1102 }
1103
1104 return false;
1105}
1106
Chandler Carruthd9c60702015-08-13 00:10:03 +00001107bool LoopIdiomRecognize::runOnNoncountableLoop() {
Evgeny Stupachenko2fecd382017-05-15 19:08:56 +00001108 return recognizePopcount() || recognizeAndInsertCTLZ();
Chandler Carruthd9c60702015-08-13 00:10:03 +00001109}
Chandler Carruth8219a502015-08-13 00:44:29 +00001110
1111/// Check if the given conditional branch is based on the comparison between
1112/// a variable and zero, and if the variable is non-zero, the control yields to
1113/// the loop entry. If the branch matches the behavior, the variable involved
Xin Tong8b8a6002017-01-05 21:40:08 +00001114/// in the comparison is returned. This function will be called to see if the
Chandler Carruth8219a502015-08-13 00:44:29 +00001115/// precondition and postcondition of the loop are in desirable form.
1116static Value *matchCondition(BranchInst *BI, BasicBlock *LoopEntry) {
1117 if (!BI || !BI->isConditional())
1118 return nullptr;
1119
1120 ICmpInst *Cond = dyn_cast<ICmpInst>(BI->getCondition());
1121 if (!Cond)
1122 return nullptr;
1123
1124 ConstantInt *CmpZero = dyn_cast<ConstantInt>(Cond->getOperand(1));
1125 if (!CmpZero || !CmpZero->isZero())
1126 return nullptr;
1127
1128 ICmpInst::Predicate Pred = Cond->getPredicate();
1129 if ((Pred == ICmpInst::ICMP_NE && BI->getSuccessor(0) == LoopEntry) ||
1130 (Pred == ICmpInst::ICMP_EQ && BI->getSuccessor(1) == LoopEntry))
1131 return Cond->getOperand(0);
1132
1133 return nullptr;
1134}
1135
Davide Italiano4bc91192017-05-23 22:32:56 +00001136// Check if the recurrence variable `VarX` is in the right form to create
1137// the idiom. Returns the value coerced to a PHINode if so.
1138static PHINode *getRecurrenceVar(Value *VarX, Instruction *DefX,
1139 BasicBlock *LoopEntry) {
1140 auto *PhiX = dyn_cast<PHINode>(VarX);
1141 if (PhiX && PhiX->getParent() == LoopEntry &&
1142 (PhiX->getOperand(0) == DefX || PhiX->getOperand(1) == DefX))
1143 return PhiX;
1144 return nullptr;
1145}
1146
Chandler Carruth8219a502015-08-13 00:44:29 +00001147/// Return true iff the idiom is detected in the loop.
1148///
1149/// Additionally:
1150/// 1) \p CntInst is set to the instruction counting the population bit.
1151/// 2) \p CntPhi is set to the corresponding phi node.
1152/// 3) \p Var is set to the value whose population bits are being counted.
1153///
1154/// The core idiom we are trying to detect is:
1155/// \code
1156/// if (x0 != 0)
1157/// goto loop-exit // the precondition of the loop
1158/// cnt0 = init-val;
1159/// do {
1160/// x1 = phi (x0, x2);
1161/// cnt1 = phi(cnt0, cnt2);
1162///
1163/// cnt2 = cnt1 + 1;
1164/// ...
1165/// x2 = x1 & (x1 - 1);
1166/// ...
1167/// } while(x != 0);
1168///
1169/// loop-exit:
1170/// \endcode
1171static bool detectPopcountIdiom(Loop *CurLoop, BasicBlock *PreCondBB,
1172 Instruction *&CntInst, PHINode *&CntPhi,
1173 Value *&Var) {
1174 // step 1: Check to see if the look-back branch match this pattern:
1175 // "if (a!=0) goto loop-entry".
1176 BasicBlock *LoopEntry;
1177 Instruction *DefX2, *CountInst;
1178 Value *VarX1, *VarX0;
1179 PHINode *PhiX, *CountPhi;
1180
1181 DefX2 = CountInst = nullptr;
1182 VarX1 = VarX0 = nullptr;
1183 PhiX = CountPhi = nullptr;
1184 LoopEntry = *(CurLoop->block_begin());
1185
1186 // step 1: Check if the loop-back branch is in desirable form.
1187 {
1188 if (Value *T = matchCondition(
1189 dyn_cast<BranchInst>(LoopEntry->getTerminator()), LoopEntry))
1190 DefX2 = dyn_cast<Instruction>(T);
1191 else
1192 return false;
1193 }
1194
1195 // step 2: detect instructions corresponding to "x2 = x1 & (x1 - 1)"
1196 {
1197 if (!DefX2 || DefX2->getOpcode() != Instruction::And)
1198 return false;
1199
1200 BinaryOperator *SubOneOp;
1201
1202 if ((SubOneOp = dyn_cast<BinaryOperator>(DefX2->getOperand(0))))
1203 VarX1 = DefX2->getOperand(1);
1204 else {
1205 VarX1 = DefX2->getOperand(0);
1206 SubOneOp = dyn_cast<BinaryOperator>(DefX2->getOperand(1));
1207 }
1208 if (!SubOneOp)
1209 return false;
1210
1211 Instruction *SubInst = cast<Instruction>(SubOneOp);
1212 ConstantInt *Dec = dyn_cast<ConstantInt>(SubInst->getOperand(1));
1213 if (!Dec ||
1214 !((SubInst->getOpcode() == Instruction::Sub && Dec->isOne()) ||
1215 (SubInst->getOpcode() == Instruction::Add &&
Craig Topper79ab6432017-07-06 18:39:47 +00001216 Dec->isMinusOne()))) {
Chandler Carruth8219a502015-08-13 00:44:29 +00001217 return false;
1218 }
1219 }
1220
1221 // step 3: Check the recurrence of variable X
Davide Italiano4bc91192017-05-23 22:32:56 +00001222 PhiX = getRecurrenceVar(VarX1, DefX2, LoopEntry);
1223 if (!PhiX)
1224 return false;
Chandler Carruth8219a502015-08-13 00:44:29 +00001225
1226 // step 4: Find the instruction which count the population: cnt2 = cnt1 + 1
1227 {
1228 CountInst = nullptr;
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001229 for (BasicBlock::iterator Iter = LoopEntry->getFirstNonPHI()->getIterator(),
Chandler Carruth8219a502015-08-13 00:44:29 +00001230 IterE = LoopEntry->end();
1231 Iter != IterE; Iter++) {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001232 Instruction *Inst = &*Iter;
Chandler Carruth8219a502015-08-13 00:44:29 +00001233 if (Inst->getOpcode() != Instruction::Add)
1234 continue;
1235
1236 ConstantInt *Inc = dyn_cast<ConstantInt>(Inst->getOperand(1));
1237 if (!Inc || !Inc->isOne())
1238 continue;
1239
Davide Italiano7bf95b92017-05-23 23:51:54 +00001240 PHINode *Phi = getRecurrenceVar(Inst->getOperand(0), Inst, LoopEntry);
1241 if (!Phi)
Chandler Carruth8219a502015-08-13 00:44:29 +00001242 continue;
1243
1244 // Check if the result of the instruction is live of the loop.
1245 bool LiveOutLoop = false;
1246 for (User *U : Inst->users()) {
1247 if ((cast<Instruction>(U))->getParent() != LoopEntry) {
1248 LiveOutLoop = true;
1249 break;
1250 }
1251 }
1252
1253 if (LiveOutLoop) {
1254 CountInst = Inst;
1255 CountPhi = Phi;
1256 break;
1257 }
1258 }
1259
1260 if (!CountInst)
1261 return false;
1262 }
1263
1264 // step 5: check if the precondition is in this form:
1265 // "if (x != 0) goto loop-head ; else goto somewhere-we-don't-care;"
1266 {
1267 auto *PreCondBr = dyn_cast<BranchInst>(PreCondBB->getTerminator());
1268 Value *T = matchCondition(PreCondBr, CurLoop->getLoopPreheader());
1269 if (T != PhiX->getOperand(0) && T != PhiX->getOperand(1))
1270 return false;
1271
1272 CntInst = CountInst;
1273 CntPhi = CountPhi;
1274 Var = T;
1275 }
1276
1277 return true;
1278}
1279
Evgeny Stupachenko2fecd382017-05-15 19:08:56 +00001280/// Return true if the idiom is detected in the loop.
1281///
1282/// Additionally:
1283/// 1) \p CntInst is set to the instruction Counting Leading Zeros (CTLZ)
1284/// or nullptr if there is no such.
1285/// 2) \p CntPhi is set to the corresponding phi node
1286/// or nullptr if there is no such.
1287/// 3) \p Var is set to the value whose CTLZ could be used.
1288/// 4) \p DefX is set to the instruction calculating Loop exit condition.
1289///
1290/// The core idiom we are trying to detect is:
1291/// \code
1292/// if (x0 == 0)
1293/// goto loop-exit // the precondition of the loop
1294/// cnt0 = init-val;
1295/// do {
1296/// x = phi (x0, x.next); //PhiX
1297/// cnt = phi(cnt0, cnt.next);
1298///
1299/// cnt.next = cnt + 1;
1300/// ...
1301/// x.next = x >> 1; // DefX
1302/// ...
1303/// } while(x.next != 0);
1304///
1305/// loop-exit:
1306/// \endcode
1307static bool detectCTLZIdiom(Loop *CurLoop, PHINode *&PhiX,
1308 Instruction *&CntInst, PHINode *&CntPhi,
1309 Instruction *&DefX) {
1310 BasicBlock *LoopEntry;
1311 Value *VarX = nullptr;
1312
1313 DefX = nullptr;
1314 PhiX = nullptr;
1315 CntInst = nullptr;
1316 CntPhi = nullptr;
1317 LoopEntry = *(CurLoop->block_begin());
1318
1319 // step 1: Check if the loop-back branch is in desirable form.
1320 if (Value *T = matchCondition(
1321 dyn_cast<BranchInst>(LoopEntry->getTerminator()), LoopEntry))
1322 DefX = dyn_cast<Instruction>(T);
1323 else
1324 return false;
1325
1326 // step 2: detect instructions corresponding to "x.next = x >> 1"
1327 if (!DefX || DefX->getOpcode() != Instruction::AShr)
1328 return false;
Evgeny Stupachenkod699de22017-11-03 18:50:03 +00001329 ConstantInt *Shft = dyn_cast<ConstantInt>(DefX->getOperand(1));
1330 if (!Shft || !Shft->isOne())
1331 return false;
Evgeny Stupachenko2fecd382017-05-15 19:08:56 +00001332 VarX = DefX->getOperand(0);
1333
1334 // step 3: Check the recurrence of variable X
Davide Italiano4bc91192017-05-23 22:32:56 +00001335 PhiX = getRecurrenceVar(VarX, DefX, LoopEntry);
1336 if (!PhiX)
Evgeny Stupachenko2fecd382017-05-15 19:08:56 +00001337 return false;
1338
1339 // step 4: Find the instruction which count the CTLZ: cnt.next = cnt + 1
1340 // TODO: We can skip the step. If loop trip count is known (CTLZ),
1341 // then all uses of "cnt.next" could be optimized to the trip count
1342 // plus "cnt0". Currently it is not optimized.
1343 // This step could be used to detect POPCNT instruction:
1344 // cnt.next = cnt + (x.next & 1)
1345 for (BasicBlock::iterator Iter = LoopEntry->getFirstNonPHI()->getIterator(),
1346 IterE = LoopEntry->end();
1347 Iter != IterE; Iter++) {
1348 Instruction *Inst = &*Iter;
1349 if (Inst->getOpcode() != Instruction::Add)
1350 continue;
1351
1352 ConstantInt *Inc = dyn_cast<ConstantInt>(Inst->getOperand(1));
1353 if (!Inc || !Inc->isOne())
1354 continue;
1355
Davide Italiano7bf95b92017-05-23 23:51:54 +00001356 PHINode *Phi = getRecurrenceVar(Inst->getOperand(0), Inst, LoopEntry);
1357 if (!Phi)
Evgeny Stupachenko2fecd382017-05-15 19:08:56 +00001358 continue;
1359
1360 CntInst = Inst;
1361 CntPhi = Phi;
1362 break;
1363 }
1364 if (!CntInst)
1365 return false;
1366
1367 return true;
1368}
1369
1370/// Recognize CTLZ idiom in a non-countable loop and convert the loop
1371/// to countable (with CTLZ trip count).
1372/// If CTLZ inserted as a new trip count returns true; otherwise, returns false.
1373bool LoopIdiomRecognize::recognizeAndInsertCTLZ() {
1374 // Give up if the loop has multiple blocks or multiple backedges.
1375 if (CurLoop->getNumBackEdges() != 1 || CurLoop->getNumBlocks() != 1)
1376 return false;
1377
1378 Instruction *CntInst, *DefX;
1379 PHINode *CntPhi, *PhiX;
1380 if (!detectCTLZIdiom(CurLoop, PhiX, CntInst, CntPhi, DefX))
1381 return false;
1382
1383 bool IsCntPhiUsedOutsideLoop = false;
1384 for (User *U : CntPhi->users())
1385 if (!CurLoop->contains(dyn_cast<Instruction>(U))) {
1386 IsCntPhiUsedOutsideLoop = true;
1387 break;
1388 }
1389 bool IsCntInstUsedOutsideLoop = false;
1390 for (User *U : CntInst->users())
1391 if (!CurLoop->contains(dyn_cast<Instruction>(U))) {
1392 IsCntInstUsedOutsideLoop = true;
1393 break;
1394 }
1395 // If both CntInst and CntPhi are used outside the loop the profitability
1396 // is questionable.
1397 if (IsCntInstUsedOutsideLoop && IsCntPhiUsedOutsideLoop)
1398 return false;
1399
1400 // For some CPUs result of CTLZ(X) intrinsic is undefined
1401 // when X is 0. If we can not guarantee X != 0, we need to check this
1402 // when expand.
1403 bool ZeroCheck = false;
1404 // It is safe to assume Preheader exist as it was checked in
1405 // parent function RunOnLoop.
1406 BasicBlock *PH = CurLoop->getLoopPreheader();
1407 Value *InitX = PhiX->getIncomingValueForBlock(PH);
1408 // If we check X != 0 before entering the loop we don't need a zero
Evgeny Stupachenkocc195602017-05-16 21:44:59 +00001409 // check in CTLZ intrinsic, but only if Cnt Phi is not used outside of the
1410 // loop (if it is used we count CTLZ(X >> 1)).
1411 if (!IsCntPhiUsedOutsideLoop)
1412 if (BasicBlock *PreCondBB = PH->getSinglePredecessor())
1413 if (BranchInst *PreCondBr =
1414 dyn_cast<BranchInst>(PreCondBB->getTerminator())) {
1415 if (matchCondition(PreCondBr, PH) == InitX)
1416 ZeroCheck = true;
1417 }
Evgeny Stupachenko2fecd382017-05-15 19:08:56 +00001418
1419 // Check if CTLZ intrinsic is profitable. Assume it is always profitable
1420 // if we delete the loop (the loop has only 6 instructions):
1421 // %n.addr.0 = phi [ %n, %entry ], [ %shr, %while.cond ]
1422 // %i.0 = phi [ %i0, %entry ], [ %inc, %while.cond ]
1423 // %shr = ashr %n.addr.0, 1
1424 // %tobool = icmp eq %shr, 0
1425 // %inc = add nsw %i.0, 1
1426 // br i1 %tobool
1427
1428 IRBuilder<> Builder(PH->getTerminator());
1429 SmallVector<const Value *, 2> Ops =
1430 {InitX, ZeroCheck ? Builder.getTrue() : Builder.getFalse()};
1431 ArrayRef<const Value *> Args(Ops);
1432 if (CurLoop->getHeader()->size() != 6 &&
1433 TTI->getIntrinsicCost(Intrinsic::ctlz, InitX->getType(), Args) >
1434 TargetTransformInfo::TCC_Basic)
1435 return false;
1436
1437 const DebugLoc DL = DefX->getDebugLoc();
1438 transformLoopToCountable(PH, CntInst, CntPhi, InitX, DL, ZeroCheck,
1439 IsCntPhiUsedOutsideLoop);
1440 return true;
1441}
1442
Chandler Carruth8219a502015-08-13 00:44:29 +00001443/// Recognizes a population count idiom in a non-countable loop.
1444///
1445/// If detected, transforms the relevant code to issue the popcount intrinsic
1446/// function call, and returns true; otherwise, returns false.
1447bool LoopIdiomRecognize::recognizePopcount() {
Chandler Carruth8219a502015-08-13 00:44:29 +00001448 if (TTI->getPopcntSupport(32) != TargetTransformInfo::PSK_FastHardware)
1449 return false;
1450
1451 // Counting population are usually conducted by few arithmetic instructions.
Nick Lewycky06b0ea22015-08-18 22:41:58 +00001452 // Such instructions can be easily "absorbed" by vacant slots in a
Chandler Carruth8219a502015-08-13 00:44:29 +00001453 // non-compact loop. Therefore, recognizing popcount idiom only makes sense
1454 // in a compact loop.
1455
Renato Golin655348f2015-08-13 11:25:38 +00001456 // Give up if the loop has multiple blocks or multiple backedges.
1457 if (CurLoop->getNumBackEdges() != 1 || CurLoop->getNumBlocks() != 1)
Chandler Carruth8219a502015-08-13 00:44:29 +00001458 return false;
1459
Renato Golin655348f2015-08-13 11:25:38 +00001460 BasicBlock *LoopBody = *(CurLoop->block_begin());
1461 if (LoopBody->size() >= 20) {
1462 // The loop is too big, bail out.
Chandler Carruth8219a502015-08-13 00:44:29 +00001463 return false;
Renato Golin655348f2015-08-13 11:25:38 +00001464 }
Chandler Carruth8219a502015-08-13 00:44:29 +00001465
1466 // It should have a preheader containing nothing but an unconditional branch.
Renato Golin655348f2015-08-13 11:25:38 +00001467 BasicBlock *PH = CurLoop->getLoopPreheader();
Davide Italianoc0169fa2016-10-07 18:39:43 +00001468 if (!PH || &PH->front() != PH->getTerminator())
Renato Golin655348f2015-08-13 11:25:38 +00001469 return false;
1470 auto *EntryBI = dyn_cast<BranchInst>(PH->getTerminator());
Chandler Carruth8219a502015-08-13 00:44:29 +00001471 if (!EntryBI || EntryBI->isConditional())
1472 return false;
1473
1474 // It should have a precondition block where the generated popcount instrinsic
1475 // function can be inserted.
Renato Golin655348f2015-08-13 11:25:38 +00001476 auto *PreCondBB = PH->getSinglePredecessor();
Chandler Carruth8219a502015-08-13 00:44:29 +00001477 if (!PreCondBB)
1478 return false;
1479 auto *PreCondBI = dyn_cast<BranchInst>(PreCondBB->getTerminator());
1480 if (!PreCondBI || PreCondBI->isUnconditional())
1481 return false;
1482
1483 Instruction *CntInst;
1484 PHINode *CntPhi;
1485 Value *Val;
1486 if (!detectPopcountIdiom(CurLoop, PreCondBB, CntInst, CntPhi, Val))
1487 return false;
1488
1489 transformLoopToPopcount(PreCondBB, CntInst, CntPhi, Val);
1490 return true;
1491}
1492
1493static CallInst *createPopcntIntrinsic(IRBuilder<> &IRBuilder, Value *Val,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00001494 const DebugLoc &DL) {
Chandler Carruth8219a502015-08-13 00:44:29 +00001495 Value *Ops[] = {Val};
1496 Type *Tys[] = {Val->getType()};
1497
1498 Module *M = IRBuilder.GetInsertBlock()->getParent()->getParent();
1499 Value *Func = Intrinsic::getDeclaration(M, Intrinsic::ctpop, Tys);
1500 CallInst *CI = IRBuilder.CreateCall(Func, Ops);
1501 CI->setDebugLoc(DL);
1502
1503 return CI;
1504}
1505
Evgeny Stupachenko2fecd382017-05-15 19:08:56 +00001506static CallInst *createCTLZIntrinsic(IRBuilder<> &IRBuilder, Value *Val,
1507 const DebugLoc &DL, bool ZeroCheck) {
1508 Value *Ops[] = {Val, ZeroCheck ? IRBuilder.getTrue() : IRBuilder.getFalse()};
1509 Type *Tys[] = {Val->getType()};
1510
1511 Module *M = IRBuilder.GetInsertBlock()->getParent()->getParent();
1512 Value *Func = Intrinsic::getDeclaration(M, Intrinsic::ctlz, Tys);
1513 CallInst *CI = IRBuilder.CreateCall(Func, Ops);
1514 CI->setDebugLoc(DL);
1515
1516 return CI;
1517}
1518
1519/// Transform the following loop:
1520/// loop:
1521/// CntPhi = PHI [Cnt0, CntInst]
1522/// PhiX = PHI [InitX, DefX]
1523/// CntInst = CntPhi + 1
1524/// DefX = PhiX >> 1
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +00001525/// LOOP_BODY
Evgeny Stupachenko2fecd382017-05-15 19:08:56 +00001526/// Br: loop if (DefX != 0)
1527/// Use(CntPhi) or Use(CntInst)
1528///
1529/// Into:
1530/// If CntPhi used outside the loop:
1531/// CountPrev = BitWidth(InitX) - CTLZ(InitX >> 1)
1532/// Count = CountPrev + 1
1533/// else
1534/// Count = BitWidth(InitX) - CTLZ(InitX)
1535/// loop:
1536/// CntPhi = PHI [Cnt0, CntInst]
1537/// PhiX = PHI [InitX, DefX]
1538/// PhiCount = PHI [Count, Dec]
1539/// CntInst = CntPhi + 1
1540/// DefX = PhiX >> 1
1541/// Dec = PhiCount - 1
1542/// LOOP_BODY
1543/// Br: loop if (Dec != 0)
1544/// Use(CountPrev + Cnt0) // Use(CntPhi)
1545/// or
1546/// Use(Count + Cnt0) // Use(CntInst)
1547///
1548/// If LOOP_BODY is empty the loop will be deleted.
1549/// If CntInst and DefX are not used in LOOP_BODY they will be removed.
1550void LoopIdiomRecognize::transformLoopToCountable(
1551 BasicBlock *Preheader, Instruction *CntInst, PHINode *CntPhi, Value *InitX,
1552 const DebugLoc DL, bool ZeroCheck, bool IsCntPhiUsedOutsideLoop) {
1553 BranchInst *PreheaderBr = dyn_cast<BranchInst>(Preheader->getTerminator());
1554
1555 // Step 1: Insert the CTLZ instruction at the end of the preheader block
1556 // Count = BitWidth - CTLZ(InitX);
1557 // If there are uses of CntPhi create:
1558 // CountPrev = BitWidth - CTLZ(InitX >> 1);
1559 IRBuilder<> Builder(PreheaderBr);
1560 Builder.SetCurrentDebugLocation(DL);
1561 Value *CTLZ, *Count, *CountPrev, *NewCount, *InitXNext;
1562
1563 if (IsCntPhiUsedOutsideLoop)
1564 InitXNext = Builder.CreateAShr(InitX,
1565 ConstantInt::get(InitX->getType(), 1));
1566 else
1567 InitXNext = InitX;
1568 CTLZ = createCTLZIntrinsic(Builder, InitXNext, DL, ZeroCheck);
1569 Count = Builder.CreateSub(
1570 ConstantInt::get(CTLZ->getType(),
1571 CTLZ->getType()->getIntegerBitWidth()),
1572 CTLZ);
1573 if (IsCntPhiUsedOutsideLoop) {
1574 CountPrev = Count;
1575 Count = Builder.CreateAdd(
1576 CountPrev,
1577 ConstantInt::get(CountPrev->getType(), 1));
1578 }
1579 if (IsCntPhiUsedOutsideLoop)
1580 NewCount = Builder.CreateZExtOrTrunc(CountPrev,
1581 cast<IntegerType>(CntInst->getType()));
1582 else
1583 NewCount = Builder.CreateZExtOrTrunc(Count,
1584 cast<IntegerType>(CntInst->getType()));
1585
1586 // If the CTLZ counter's initial value is not zero, insert Add Inst.
1587 Value *CntInitVal = CntPhi->getIncomingValueForBlock(Preheader);
1588 ConstantInt *InitConst = dyn_cast<ConstantInt>(CntInitVal);
1589 if (!InitConst || !InitConst->isZero())
1590 NewCount = Builder.CreateAdd(NewCount, CntInitVal);
1591
1592 // Step 2: Insert new IV and loop condition:
1593 // loop:
1594 // ...
1595 // PhiCount = PHI [Count, Dec]
1596 // ...
1597 // Dec = PhiCount - 1
1598 // ...
1599 // Br: loop if (Dec != 0)
1600 BasicBlock *Body = *(CurLoop->block_begin());
1601 auto *LbBr = dyn_cast<BranchInst>(Body->getTerminator());
1602 ICmpInst *LbCond = cast<ICmpInst>(LbBr->getCondition());
1603 Type *Ty = Count->getType();
1604
1605 PHINode *TcPhi = PHINode::Create(Ty, 2, "tcphi", &Body->front());
1606
1607 Builder.SetInsertPoint(LbCond);
1608 Instruction *TcDec = cast<Instruction>(
1609 Builder.CreateSub(TcPhi, ConstantInt::get(Ty, 1),
1610 "tcdec", false, true));
1611
1612 TcPhi->addIncoming(Count, Preheader);
1613 TcPhi->addIncoming(TcDec, Body);
1614
1615 CmpInst::Predicate Pred =
1616 (LbBr->getSuccessor(0) == Body) ? CmpInst::ICMP_NE : CmpInst::ICMP_EQ;
1617 LbCond->setPredicate(Pred);
1618 LbCond->setOperand(0, TcDec);
1619 LbCond->setOperand(1, ConstantInt::get(Ty, 0));
1620
1621 // Step 3: All the references to the original counter outside
1622 // the loop are replaced with the NewCount -- the value returned from
1623 // __builtin_ctlz(x).
1624 if (IsCntPhiUsedOutsideLoop)
1625 CntPhi->replaceUsesOutsideBlock(NewCount, Body);
1626 else
1627 CntInst->replaceUsesOutsideBlock(NewCount, Body);
1628
1629 // step 4: Forget the "non-computable" trip-count SCEV associated with the
1630 // loop. The loop would otherwise not be deleted even if it becomes empty.
1631 SE->forgetLoop(CurLoop);
1632}
1633
Chandler Carruth8219a502015-08-13 00:44:29 +00001634void LoopIdiomRecognize::transformLoopToPopcount(BasicBlock *PreCondBB,
1635 Instruction *CntInst,
1636 PHINode *CntPhi, Value *Var) {
1637 BasicBlock *PreHead = CurLoop->getLoopPreheader();
1638 auto *PreCondBr = dyn_cast<BranchInst>(PreCondBB->getTerminator());
1639 const DebugLoc DL = CntInst->getDebugLoc();
1640
1641 // Assuming before transformation, the loop is following:
1642 // if (x) // the precondition
1643 // do { cnt++; x &= x - 1; } while(x);
1644
1645 // Step 1: Insert the ctpop instruction at the end of the precondition block
1646 IRBuilder<> Builder(PreCondBr);
1647 Value *PopCnt, *PopCntZext, *NewCount, *TripCnt;
1648 {
1649 PopCnt = createPopcntIntrinsic(Builder, Var, DL);
1650 NewCount = PopCntZext =
1651 Builder.CreateZExtOrTrunc(PopCnt, cast<IntegerType>(CntPhi->getType()));
1652
1653 if (NewCount != PopCnt)
1654 (cast<Instruction>(NewCount))->setDebugLoc(DL);
1655
1656 // TripCnt is exactly the number of iterations the loop has
1657 TripCnt = NewCount;
1658
1659 // If the population counter's initial value is not zero, insert Add Inst.
1660 Value *CntInitVal = CntPhi->getIncomingValueForBlock(PreHead);
1661 ConstantInt *InitConst = dyn_cast<ConstantInt>(CntInitVal);
1662 if (!InitConst || !InitConst->isZero()) {
1663 NewCount = Builder.CreateAdd(NewCount, CntInitVal);
1664 (cast<Instruction>(NewCount))->setDebugLoc(DL);
1665 }
1666 }
1667
Nick Lewycky2c852542015-08-19 06:22:33 +00001668 // Step 2: Replace the precondition from "if (x == 0) goto loop-exit" to
Nick Lewycky1098e492015-08-19 06:25:30 +00001669 // "if (NewCount == 0) loop-exit". Without this change, the intrinsic
Chandler Carruth8219a502015-08-13 00:44:29 +00001670 // function would be partial dead code, and downstream passes will drag
1671 // it back from the precondition block to the preheader.
1672 {
1673 ICmpInst *PreCond = cast<ICmpInst>(PreCondBr->getCondition());
1674
1675 Value *Opnd0 = PopCntZext;
1676 Value *Opnd1 = ConstantInt::get(PopCntZext->getType(), 0);
1677 if (PreCond->getOperand(0) != Var)
1678 std::swap(Opnd0, Opnd1);
1679
1680 ICmpInst *NewPreCond = cast<ICmpInst>(
1681 Builder.CreateICmp(PreCond->getPredicate(), Opnd0, Opnd1));
1682 PreCondBr->setCondition(NewPreCond);
1683
1684 RecursivelyDeleteTriviallyDeadInstructions(PreCond, TLI);
1685 }
1686
1687 // Step 3: Note that the population count is exactly the trip count of the
Nick Lewycky1098e492015-08-19 06:25:30 +00001688 // loop in question, which enable us to to convert the loop from noncountable
Chandler Carruth8219a502015-08-13 00:44:29 +00001689 // loop into a countable one. The benefit is twofold:
1690 //
Nick Lewycky2c852542015-08-19 06:22:33 +00001691 // - If the loop only counts population, the entire loop becomes dead after
1692 // the transformation. It is a lot easier to prove a countable loop dead
1693 // than to prove a noncountable one. (In some C dialects, an infinite loop
Chandler Carruth8219a502015-08-13 00:44:29 +00001694 // isn't dead even if it computes nothing useful. In general, DCE needs
1695 // to prove a noncountable loop finite before safely delete it.)
1696 //
1697 // - If the loop also performs something else, it remains alive.
1698 // Since it is transformed to countable form, it can be aggressively
1699 // optimized by some optimizations which are in general not applicable
1700 // to a noncountable loop.
1701 //
1702 // After this step, this loop (conceptually) would look like following:
1703 // newcnt = __builtin_ctpop(x);
1704 // t = newcnt;
1705 // if (x)
1706 // do { cnt++; x &= x-1; t--) } while (t > 0);
1707 BasicBlock *Body = *(CurLoop->block_begin());
1708 {
1709 auto *LbBr = dyn_cast<BranchInst>(Body->getTerminator());
1710 ICmpInst *LbCond = cast<ICmpInst>(LbBr->getCondition());
1711 Type *Ty = TripCnt->getType();
1712
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001713 PHINode *TcPhi = PHINode::Create(Ty, 2, "tcphi", &Body->front());
Chandler Carruth8219a502015-08-13 00:44:29 +00001714
1715 Builder.SetInsertPoint(LbCond);
Chandler Carruth8219a502015-08-13 00:44:29 +00001716 Instruction *TcDec = cast<Instruction>(
Nick Lewycky1098e492015-08-19 06:25:30 +00001717 Builder.CreateSub(TcPhi, ConstantInt::get(Ty, 1),
1718 "tcdec", false, true));
Chandler Carruth8219a502015-08-13 00:44:29 +00001719
1720 TcPhi->addIncoming(TripCnt, PreHead);
1721 TcPhi->addIncoming(TcDec, Body);
1722
1723 CmpInst::Predicate Pred =
1724 (LbBr->getSuccessor(0) == Body) ? CmpInst::ICMP_UGT : CmpInst::ICMP_SLE;
1725 LbCond->setPredicate(Pred);
1726 LbCond->setOperand(0, TcDec);
Nick Lewycky2c852542015-08-19 06:22:33 +00001727 LbCond->setOperand(1, ConstantInt::get(Ty, 0));
Chandler Carruth8219a502015-08-13 00:44:29 +00001728 }
1729
1730 // Step 4: All the references to the original population counter outside
1731 // the loop are replaced with the NewCount -- the value returned from
1732 // __builtin_ctpop().
1733 CntInst->replaceUsesOutsideBlock(NewCount, Body);
1734
1735 // step 5: Forget the "non-computable" trip-count SCEV associated with the
1736 // loop. The loop would otherwise not be deleted even if it becomes empty.
1737 SE->forgetLoop(CurLoop);
1738}