blob: 9bc0153bf513738a4a3a391d2bd74d2ecc67d507 [file] [log] [blame]
Chris Lattner81ae3f22010-12-26 19:39:38 +00001//===-- LoopIdiomRecognize.cpp - Loop idiom recognition -------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This pass implements an idiom recognizer that transforms simple loops into a
11// non-loop form. In cases that this kicks in, it can be a significant
12// performance win.
13//
14//===----------------------------------------------------------------------===//
Chris Lattner0469e012011-01-02 18:32:09 +000015//
16// TODO List:
17//
18// Future loop memory idioms to recognize:
Chandler Carruth099f5cb02012-11-02 08:33:25 +000019// memcmp, memmove, strlen, etc.
Chris Lattner0469e012011-01-02 18:32:09 +000020// Future floating point idioms to recognize in -ffast-math mode:
21// fpowi
22// Future integer operation idioms to recognize:
23// ctpop, ctlz, cttz
24//
25// Beware that isel's default lowering for ctpop is highly inefficient for
26// i64 and larger types when i64 is legal and the value has few bits set. It
27// would be good to enhance isel to emit a loop for ctpop in this case.
28//
29// We should enhance the memset/memcpy recognition to handle multiple stores in
30// the loop. This would handle things like:
31// void foo(_Complex float *P)
32// for (i) { __real__(*P) = 0; __imag__(*P) = 0; }
Chris Lattner8fac5db2011-01-02 23:19:45 +000033//
Chris Lattnerbc661d62011-02-21 02:08:54 +000034// We should enhance this to handle negative strides through memory.
35// Alternatively (and perhaps better) we could rely on an earlier pass to force
36// forward iteration through memory, which is generally better for cache
37// behavior. Negative strides *do* happen for memset/memcpy loops.
38//
Chris Lattner02a97762011-01-03 01:10:08 +000039// This could recognize common matrix multiplies and dot product idioms and
Chris Lattner8fac5db2011-01-02 23:19:45 +000040// replace them with calls to BLAS (if linked in??).
41//
Chris Lattner0469e012011-01-02 18:32:09 +000042//===----------------------------------------------------------------------===//
Chris Lattner81ae3f22010-12-26 19:39:38 +000043
Chris Lattner81ae3f22010-12-26 19:39:38 +000044#include "llvm/Transforms/Scalar.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000045#include "llvm/ADT/Statistic.h"
Chris Lattnercb18bfa2010-12-27 18:39:08 +000046#include "llvm/Analysis/AliasAnalysis.h"
Chris Lattner81ae3f22010-12-26 19:39:38 +000047#include "llvm/Analysis/LoopPass.h"
Chris Lattner29e14ed2010-12-26 23:42:51 +000048#include "llvm/Analysis/ScalarEvolutionExpander.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000049#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000050#include "llvm/Analysis/TargetLibraryInfo.h"
Chandler Carruthd3e73552013-01-07 03:08:10 +000051#include "llvm/Analysis/TargetTransformInfo.h"
Chris Lattner7c5f9c32010-12-26 20:45:45 +000052#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000053#include "llvm/IR/DataLayout.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000054#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000055#include "llvm/IR/IRBuilder.h"
56#include "llvm/IR/IntrinsicInst.h"
57#include "llvm/IR/Module.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000058#include "llvm/Support/Debug.h"
59#include "llvm/Support/raw_ostream.h"
Chris Lattnerb9fe6852010-12-27 00:03:23 +000060#include "llvm/Transforms/Utils/Local.h"
Chris Lattner81ae3f22010-12-26 19:39:38 +000061using namespace llvm;
62
Chandler Carruth964daaa2014-04-22 02:55:47 +000063#define DEBUG_TYPE "loop-idiom"
64
Chandler Carruth099f5cb02012-11-02 08:33:25 +000065STATISTIC(NumMemSet, "Number of memset's formed from loop stores");
66STATISTIC(NumMemCpy, "Number of memcpy's formed from loop load+stores");
Chris Lattner81ae3f22010-12-26 19:39:38 +000067
68namespace {
Shuxin Yang95de7c32012-12-09 03:12:46 +000069
70 class LoopIdiomRecognize;
71
72 /// This class defines some utility functions for loop idiom recognization.
73 class LIRUtil {
74 public:
75 /// Return true iff the block contains nothing but an uncondition branch
76 /// (aka goto instruction).
77 static bool isAlmostEmpty(BasicBlock *);
78
79 static BranchInst *getBranch(BasicBlock *BB) {
80 return dyn_cast<BranchInst>(BB->getTerminator());
81 }
82
Matt Arsenaultfb183232013-07-22 18:59:58 +000083 /// Derive the precondition block (i.e the block that guards the loop
Shuxin Yang95de7c32012-12-09 03:12:46 +000084 /// preheader) from the given preheader.
85 static BasicBlock *getPrecondBb(BasicBlock *PreHead);
86 };
87
88 /// This class is to recoginize idioms of population-count conducted in
89 /// a noncountable loop. Currently it only recognizes this pattern:
90 /// \code
91 /// while(x) {cnt++; ...; x &= x - 1; ...}
92 /// \endcode
93 class NclPopcountRecognize {
94 LoopIdiomRecognize &LIR;
95 Loop *CurLoop;
96 BasicBlock *PreCondBB;
97
98 typedef IRBuilder<> IRBuilderTy;
99
100 public:
101 explicit NclPopcountRecognize(LoopIdiomRecognize &TheLIR);
102 bool recognize();
103
104 private:
105 /// Take a glimpse of the loop to see if we need to go ahead recoginizing
106 /// the idiom.
107 bool preliminaryScreen();
108
109 /// Check if the given conditional branch is based on the comparison
Alp Tokercb402912014-01-24 17:20:08 +0000110 /// between a variable and zero, and if the variable is non-zero, the
111 /// control yields to the loop entry. If the branch matches the behavior,
Shuxin Yang95de7c32012-12-09 03:12:46 +0000112 /// the variable involved in the comparion is returned. This function will
Matt Arsenaultfb183232013-07-22 18:59:58 +0000113 /// be called to see if the precondition and postcondition of the loop
Shuxin Yang95de7c32012-12-09 03:12:46 +0000114 /// are in desirable form.
Nick Lewyckyb06a7962014-06-14 03:48:29 +0000115 Value *matchCondition(BranchInst *Br, BasicBlock *NonZeroTarget) const;
Shuxin Yang95de7c32012-12-09 03:12:46 +0000116
117 /// Return true iff the idiom is detected in the loop. and 1) \p CntInst
Jim Grosbach4a7d4962014-04-29 22:41:55 +0000118 /// is set to the instruction counting the population bit. 2) \p CntPhi
Shuxin Yang95de7c32012-12-09 03:12:46 +0000119 /// is set to the corresponding phi node. 3) \p Var is set to the value
120 /// whose population bits are being counted.
121 bool detectIdiom
122 (Instruction *&CntInst, PHINode *&CntPhi, Value *&Var) const;
123
124 /// Insert ctpop intrinsic function and some obviously dead instructions.
Nick Lewyckyb06a7962014-06-14 03:48:29 +0000125 void transform(Instruction *CntInst, PHINode *CntPhi, Value *Var);
Shuxin Yang95de7c32012-12-09 03:12:46 +0000126
127 /// Create llvm.ctpop.* intrinsic function.
128 CallInst *createPopcntIntrinsic(IRBuilderTy &IRB, Value *Val, DebugLoc DL);
129 };
130
Chris Lattner81ae3f22010-12-26 19:39:38 +0000131 class LoopIdiomRecognize : public LoopPass {
Chris Lattner7c5f9c32010-12-26 20:45:45 +0000132 Loop *CurLoop;
Chris Lattner8455b6e2011-01-02 19:01:03 +0000133 DominatorTree *DT;
Chris Lattner7c5f9c32010-12-26 20:45:45 +0000134 ScalarEvolution *SE;
Chris Lattnere6b261f2011-02-18 22:22:15 +0000135 TargetLibraryInfo *TLI;
Chandler Carruth6fe147f2013-01-05 10:00:09 +0000136 const TargetTransformInfo *TTI;
Chris Lattner81ae3f22010-12-26 19:39:38 +0000137 public:
138 static char ID;
139 explicit LoopIdiomRecognize() : LoopPass(ID) {
140 initializeLoopIdiomRecognizePass(*PassRegistry::getPassRegistry());
Mehdi Amini46a43552015-03-04 18:43:29 +0000141 DT = nullptr;
142 SE = nullptr;
143 TLI = nullptr;
144 TTI = nullptr;
Chris Lattner81ae3f22010-12-26 19:39:38 +0000145 }
146
Craig Topper3e4c6972014-03-05 09:10:37 +0000147 bool runOnLoop(Loop *L, LPPassManager &LPM) override;
Chris Lattner8455b6e2011-01-02 19:01:03 +0000148 bool runOnLoopBlock(BasicBlock *BB, const SCEV *BECount,
149 SmallVectorImpl<BasicBlock*> &ExitBlocks);
Chris Lattner81ae3f22010-12-26 19:39:38 +0000150
Chris Lattner7c5f9c32010-12-26 20:45:45 +0000151 bool processLoopStore(StoreInst *SI, const SCEV *BECount);
Chris Lattner86438102011-01-04 07:46:33 +0000152 bool processLoopMemSet(MemSetInst *MSI, const SCEV *BECount);
Andrew Trick328b2232011-03-14 16:48:10 +0000153
Chris Lattner0f4a6402011-02-19 19:31:39 +0000154 bool processLoopStridedStore(Value *DestPtr, unsigned StoreSize,
155 unsigned StoreAlignment,
156 Value *SplatValue, Instruction *TheStore,
157 const SCEVAddRecExpr *Ev,
158 const SCEV *BECount);
Chris Lattner85b6d812011-01-02 03:37:56 +0000159 bool processLoopStoreOfLoopLoad(StoreInst *SI, unsigned StoreSize,
160 const SCEVAddRecExpr *StoreEv,
161 const SCEVAddRecExpr *LoadEv,
162 const SCEV *BECount);
Andrew Trick328b2232011-03-14 16:48:10 +0000163
Chris Lattner81ae3f22010-12-26 19:39:38 +0000164 /// This transformation requires natural loop information & requires that
165 /// loop preheaders be inserted into the CFG.
166 ///
Craig Topper3e4c6972014-03-05 09:10:37 +0000167 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000168 AU.addRequired<LoopInfoWrapperPass>();
169 AU.addPreserved<LoopInfoWrapperPass>();
Chris Lattner81ae3f22010-12-26 19:39:38 +0000170 AU.addRequiredID(LoopSimplifyID);
171 AU.addPreservedID(LoopSimplifyID);
172 AU.addRequiredID(LCSSAID);
173 AU.addPreservedID(LCSSAID);
Chris Lattnercb18bfa2010-12-27 18:39:08 +0000174 AU.addRequired<AliasAnalysis>();
175 AU.addPreserved<AliasAnalysis>();
Chris Lattner81ae3f22010-12-26 19:39:38 +0000176 AU.addRequired<ScalarEvolution>();
177 AU.addPreserved<ScalarEvolution>();
Chandler Carruth73523022014-01-13 13:07:17 +0000178 AU.addPreserved<DominatorTreeWrapperPass>();
179 AU.addRequired<DominatorTreeWrapperPass>();
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000180 AU.addRequired<TargetLibraryInfoWrapperPass>();
Chandler Carruth705b1852015-01-31 03:43:40 +0000181 AU.addRequired<TargetTransformInfoWrapperPass>();
Chris Lattner81ae3f22010-12-26 19:39:38 +0000182 }
Shuxin Yang95de7c32012-12-09 03:12:46 +0000183
Shuxin Yang95de7c32012-12-09 03:12:46 +0000184 DominatorTree *getDominatorTree() {
Chandler Carruth73523022014-01-13 13:07:17 +0000185 return DT ? DT
186 : (DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree());
Shuxin Yang95de7c32012-12-09 03:12:46 +0000187 }
188
189 ScalarEvolution *getScalarEvolution() {
190 return SE ? SE : (SE = &getAnalysis<ScalarEvolution>());
191 }
192
193 TargetLibraryInfo *getTargetLibraryInfo() {
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000194 if (!TLI)
195 TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
196
197 return TLI;
Shuxin Yang95de7c32012-12-09 03:12:46 +0000198 }
199
Chandler Carruth6fe147f2013-01-05 10:00:09 +0000200 const TargetTransformInfo *getTargetTransformInfo() {
Chandler Carruthfdb9c572015-02-01 12:01:35 +0000201 return TTI ? TTI
202 : (TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(
203 *CurLoop->getHeader()->getParent()));
Shuxin Yang95de7c32012-12-09 03:12:46 +0000204 }
205
206 Loop *getLoop() const { return CurLoop; }
207
208 private:
209 bool runOnNoncountableLoop();
210 bool runOnCountableLoop();
Chris Lattner81ae3f22010-12-26 19:39:38 +0000211 };
212}
213
214char LoopIdiomRecognize::ID = 0;
215INITIALIZE_PASS_BEGIN(LoopIdiomRecognize, "loop-idiom", "Recognize loop idioms",
216 false, false)
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000217INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
Chandler Carruth73523022014-01-13 13:07:17 +0000218INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Chris Lattner81ae3f22010-12-26 19:39:38 +0000219INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
220INITIALIZE_PASS_DEPENDENCY(LCSSA)
221INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000222INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
Chris Lattnercb18bfa2010-12-27 18:39:08 +0000223INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
Chandler Carruth705b1852015-01-31 03:43:40 +0000224INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
Chris Lattner81ae3f22010-12-26 19:39:38 +0000225INITIALIZE_PASS_END(LoopIdiomRecognize, "loop-idiom", "Recognize loop idioms",
226 false, false)
227
228Pass *llvm::createLoopIdiomPass() { return new LoopIdiomRecognize(); }
229
Chris Lattnerc4ca7ab2011-05-22 17:39:56 +0000230/// deleteDeadInstruction - Delete this instruction. Before we do, go through
Chris Lattnerb9fe6852010-12-27 00:03:23 +0000231/// and zero out all the operands of this instruction. If any of them become
232/// dead, delete them and the computation tree that feeds them.
233///
Benjamin Kramerf094d772015-02-07 21:37:08 +0000234static void deleteDeadInstruction(Instruction *I,
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000235 const TargetLibraryInfo *TLI) {
Benjamin Kramerf094d772015-02-07 21:37:08 +0000236 SmallVector<Value *, 16> Operands(I->value_op_begin(), I->value_op_end());
237 I->replaceAllUsesWith(UndefValue::get(I->getType()));
238 I->eraseFromParent();
239 for (Value *Op : Operands)
240 RecursivelyDeleteTriviallyDeadInstructions(Op, TLI);
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000241}
242
Shuxin Yang95de7c32012-12-09 03:12:46 +0000243//===----------------------------------------------------------------------===//
244//
245// Implementation of LIRUtil
246//
247//===----------------------------------------------------------------------===//
248
Matt Arsenaultfb183232013-07-22 18:59:58 +0000249// This function will return true iff the given block contains nothing but goto.
250// A typical usage of this function is to check if the preheader function is
251// "almost" empty such that generated intrinsic functions can be moved across
252// the preheader and be placed at the end of the precondition block without
253// the concern of breaking data dependence.
Shuxin Yang95de7c32012-12-09 03:12:46 +0000254bool LIRUtil::isAlmostEmpty(BasicBlock *BB) {
255 if (BranchInst *Br = getBranch(BB)) {
Benjamin Kramerf094d772015-02-07 21:37:08 +0000256 return Br->isUnconditional() && Br == BB->begin();
Shuxin Yang95de7c32012-12-09 03:12:46 +0000257 }
258 return false;
259}
260
Shuxin Yang95de7c32012-12-09 03:12:46 +0000261BasicBlock *LIRUtil::getPrecondBb(BasicBlock *PreHead) {
262 if (BasicBlock *BB = PreHead->getSinglePredecessor()) {
263 BranchInst *Br = getBranch(BB);
Craig Topperf40110f2014-04-25 05:29:35 +0000264 return Br && Br->isConditional() ? BB : nullptr;
Shuxin Yang95de7c32012-12-09 03:12:46 +0000265 }
Craig Topperf40110f2014-04-25 05:29:35 +0000266 return nullptr;
Shuxin Yang95de7c32012-12-09 03:12:46 +0000267}
268
269//===----------------------------------------------------------------------===//
270//
271// Implementation of NclPopcountRecognize
272//
273//===----------------------------------------------------------------------===//
274
275NclPopcountRecognize::NclPopcountRecognize(LoopIdiomRecognize &TheLIR):
Craig Topperf40110f2014-04-25 05:29:35 +0000276 LIR(TheLIR), CurLoop(TheLIR.getLoop()), PreCondBB(nullptr) {
Shuxin Yang95de7c32012-12-09 03:12:46 +0000277}
278
279bool NclPopcountRecognize::preliminaryScreen() {
Chandler Carruth6fe147f2013-01-05 10:00:09 +0000280 const TargetTransformInfo *TTI = LIR.getTargetTransformInfo();
Chandler Carruth50a36cd2013-01-07 03:16:03 +0000281 if (TTI->getPopcntSupport(32) != TargetTransformInfo::PSK_FastHardware)
Shuxin Yang95de7c32012-12-09 03:12:46 +0000282 return false;
283
Robert Wilhelm2788d3e2013-09-28 13:42:22 +0000284 // Counting population are usually conducted by few arithmetic instructions.
Shuxin Yang95de7c32012-12-09 03:12:46 +0000285 // Such instructions can be easilly "absorbed" by vacant slots in a
286 // non-compact loop. Therefore, recognizing popcount idiom only makes sense
287 // in a compact loop.
288
289 // Give up if the loop has multiple blocks or multiple backedges.
290 if (CurLoop->getNumBackEdges() != 1 || CurLoop->getNumBlocks() != 1)
291 return false;
292
293 BasicBlock *LoopBody = *(CurLoop->block_begin());
294 if (LoopBody->size() >= 20) {
295 // The loop is too big, bail out.
296 return false;
297 }
298
299 // It should have a preheader containing nothing but a goto instruction.
300 BasicBlock *PreHead = CurLoop->getLoopPreheader();
301 if (!PreHead || !LIRUtil::isAlmostEmpty(PreHead))
302 return false;
303
304 // It should have a precondition block where the generated popcount instrinsic
305 // function will be inserted.
306 PreCondBB = LIRUtil::getPrecondBb(PreHead);
307 if (!PreCondBB)
308 return false;
Matt Arsenaultfb183232013-07-22 18:59:58 +0000309
Shuxin Yang95de7c32012-12-09 03:12:46 +0000310 return true;
311}
312
Jim Grosbach708f80f2014-04-29 22:41:58 +0000313Value *NclPopcountRecognize::matchCondition(BranchInst *Br,
314 BasicBlock *LoopEntry) const {
Shuxin Yang95de7c32012-12-09 03:12:46 +0000315 if (!Br || !Br->isConditional())
Craig Topperf40110f2014-04-25 05:29:35 +0000316 return nullptr;
Shuxin Yang95de7c32012-12-09 03:12:46 +0000317
318 ICmpInst *Cond = dyn_cast<ICmpInst>(Br->getCondition());
319 if (!Cond)
Craig Topperf40110f2014-04-25 05:29:35 +0000320 return nullptr;
Shuxin Yang95de7c32012-12-09 03:12:46 +0000321
322 ConstantInt *CmpZero = dyn_cast<ConstantInt>(Cond->getOperand(1));
323 if (!CmpZero || !CmpZero->isZero())
Craig Topperf40110f2014-04-25 05:29:35 +0000324 return nullptr;
Shuxin Yang95de7c32012-12-09 03:12:46 +0000325
326 ICmpInst::Predicate Pred = Cond->getPredicate();
327 if ((Pred == ICmpInst::ICMP_NE && Br->getSuccessor(0) == LoopEntry) ||
328 (Pred == ICmpInst::ICMP_EQ && Br->getSuccessor(1) == LoopEntry))
329 return Cond->getOperand(0);
330
Craig Topperf40110f2014-04-25 05:29:35 +0000331 return nullptr;
Shuxin Yang95de7c32012-12-09 03:12:46 +0000332}
333
334bool NclPopcountRecognize::detectIdiom(Instruction *&CntInst,
335 PHINode *&CntPhi,
336 Value *&Var) const {
337 // Following code tries to detect this idiom:
338 //
339 // if (x0 != 0)
340 // goto loop-exit // the precondition of the loop
341 // cnt0 = init-val;
342 // do {
343 // x1 = phi (x0, x2);
344 // cnt1 = phi(cnt0, cnt2);
345 //
346 // cnt2 = cnt1 + 1;
347 // ...
348 // x2 = x1 & (x1 - 1);
349 // ...
350 // } while(x != 0);
351 //
352 // loop-exit:
353 //
354
355 // step 1: Check to see if the look-back branch match this pattern:
356 // "if (a!=0) goto loop-entry".
357 BasicBlock *LoopEntry;
358 Instruction *DefX2, *CountInst;
359 Value *VarX1, *VarX0;
360 PHINode *PhiX, *CountPhi;
361
Craig Topperf40110f2014-04-25 05:29:35 +0000362 DefX2 = CountInst = nullptr;
363 VarX1 = VarX0 = nullptr;
364 PhiX = CountPhi = nullptr;
Shuxin Yang95de7c32012-12-09 03:12:46 +0000365 LoopEntry = *(CurLoop->block_begin());
366
367 // step 1: Check if the loop-back branch is in desirable form.
368 {
369 if (Value *T = matchCondition (LIRUtil::getBranch(LoopEntry), LoopEntry))
370 DefX2 = dyn_cast<Instruction>(T);
371 else
372 return false;
373 }
374
375 // step 2: detect instructions corresponding to "x2 = x1 & (x1 - 1)"
376 {
Shuxin Yangc5c730b2013-01-10 23:32:01 +0000377 if (!DefX2 || DefX2->getOpcode() != Instruction::And)
Shuxin Yang95de7c32012-12-09 03:12:46 +0000378 return false;
379
380 BinaryOperator *SubOneOp;
381
382 if ((SubOneOp = dyn_cast<BinaryOperator>(DefX2->getOperand(0))))
383 VarX1 = DefX2->getOperand(1);
384 else {
385 VarX1 = DefX2->getOperand(0);
386 SubOneOp = dyn_cast<BinaryOperator>(DefX2->getOperand(1));
387 }
388 if (!SubOneOp)
389 return false;
390
391 Instruction *SubInst = cast<Instruction>(SubOneOp);
392 ConstantInt *Dec = dyn_cast<ConstantInt>(SubInst->getOperand(1));
393 if (!Dec ||
394 !((SubInst->getOpcode() == Instruction::Sub && Dec->isOne()) ||
395 (SubInst->getOpcode() == Instruction::Add && Dec->isAllOnesValue()))) {
396 return false;
397 }
398 }
399
400 // step 3: Check the recurrence of variable X
401 {
402 PhiX = dyn_cast<PHINode>(VarX1);
403 if (!PhiX ||
404 (PhiX->getOperand(0) != DefX2 && PhiX->getOperand(1) != DefX2)) {
405 return false;
406 }
407 }
408
409 // step 4: Find the instruction which count the population: cnt2 = cnt1 + 1
410 {
Craig Topperf40110f2014-04-25 05:29:35 +0000411 CountInst = nullptr;
Shuxin Yang95de7c32012-12-09 03:12:46 +0000412 for (BasicBlock::iterator Iter = LoopEntry->getFirstNonPHI(),
413 IterE = LoopEntry->end(); Iter != IterE; Iter++) {
414 Instruction *Inst = Iter;
415 if (Inst->getOpcode() != Instruction::Add)
416 continue;
417
418 ConstantInt *Inc = dyn_cast<ConstantInt>(Inst->getOperand(1));
419 if (!Inc || !Inc->isOne())
420 continue;
421
422 PHINode *Phi = dyn_cast<PHINode>(Inst->getOperand(0));
423 if (!Phi || Phi->getParent() != LoopEntry)
424 continue;
425
426 // Check if the result of the instruction is live of the loop.
427 bool LiveOutLoop = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000428 for (User *U : Inst->users()) {
429 if ((cast<Instruction>(U))->getParent() != LoopEntry) {
Shuxin Yang95de7c32012-12-09 03:12:46 +0000430 LiveOutLoop = true; break;
431 }
432 }
433
434 if (LiveOutLoop) {
435 CountInst = Inst;
436 CountPhi = Phi;
437 break;
438 }
439 }
440
441 if (!CountInst)
442 return false;
443 }
444
445 // step 5: check if the precondition is in this form:
446 // "if (x != 0) goto loop-head ; else goto somewhere-we-don't-care;"
447 {
448 BranchInst *PreCondBr = LIRUtil::getBranch(PreCondBB);
449 Value *T = matchCondition (PreCondBr, CurLoop->getLoopPreheader());
450 if (T != PhiX->getOperand(0) && T != PhiX->getOperand(1))
451 return false;
452
453 CntInst = CountInst;
454 CntPhi = CountPhi;
455 Var = T;
456 }
457
458 return true;
459}
460
461void NclPopcountRecognize::transform(Instruction *CntInst,
462 PHINode *CntPhi, Value *Var) {
463
464 ScalarEvolution *SE = LIR.getScalarEvolution();
465 TargetLibraryInfo *TLI = LIR.getTargetLibraryInfo();
466 BasicBlock *PreHead = CurLoop->getLoopPreheader();
467 BranchInst *PreCondBr = LIRUtil::getBranch(PreCondBB);
468 const DebugLoc DL = CntInst->getDebugLoc();
469
470 // Assuming before transformation, the loop is following:
471 // if (x) // the precondition
472 // do { cnt++; x &= x - 1; } while(x);
Matt Arsenaultfb183232013-07-22 18:59:58 +0000473
Shuxin Yang95de7c32012-12-09 03:12:46 +0000474 // Step 1: Insert the ctpop instruction at the end of the precondition block
475 IRBuilderTy Builder(PreCondBr);
476 Value *PopCnt, *PopCntZext, *NewCount, *TripCnt;
477 {
478 PopCnt = createPopcntIntrinsic(Builder, Var, DL);
479 NewCount = PopCntZext =
480 Builder.CreateZExtOrTrunc(PopCnt, cast<IntegerType>(CntPhi->getType()));
481
482 if (NewCount != PopCnt)
483 (cast<Instruction>(NewCount))->setDebugLoc(DL);
484
485 // TripCnt is exactly the number of iterations the loop has
486 TripCnt = NewCount;
487
Alp Tokercb402912014-01-24 17:20:08 +0000488 // If the population counter's initial value is not zero, insert Add Inst.
Shuxin Yang95de7c32012-12-09 03:12:46 +0000489 Value *CntInitVal = CntPhi->getIncomingValueForBlock(PreHead);
490 ConstantInt *InitConst = dyn_cast<ConstantInt>(CntInitVal);
491 if (!InitConst || !InitConst->isZero()) {
492 NewCount = Builder.CreateAdd(NewCount, CntInitVal);
493 (cast<Instruction>(NewCount))->setDebugLoc(DL);
494 }
495 }
496
497 // Step 2: Replace the precondition from "if(x == 0) goto loop-exit" to
498 // "if(NewCount == 0) loop-exit". Withtout this change, the intrinsic
499 // function would be partial dead code, and downstream passes will drag
500 // it back from the precondition block to the preheader.
501 {
502 ICmpInst *PreCond = cast<ICmpInst>(PreCondBr->getCondition());
503
504 Value *Opnd0 = PopCntZext;
505 Value *Opnd1 = ConstantInt::get(PopCntZext->getType(), 0);
506 if (PreCond->getOperand(0) != Var)
507 std::swap(Opnd0, Opnd1);
508
509 ICmpInst *NewPreCond =
510 cast<ICmpInst>(Builder.CreateICmp(PreCond->getPredicate(), Opnd0, Opnd1));
511 PreCond->replaceAllUsesWith(NewPreCond);
512
Benjamin Kramerf094d772015-02-07 21:37:08 +0000513 RecursivelyDeleteTriviallyDeadInstructions(PreCond, TLI);
Shuxin Yang95de7c32012-12-09 03:12:46 +0000514 }
515
516 // Step 3: Note that the population count is exactly the trip count of the
517 // loop in question, which enble us to to convert the loop from noncountable
518 // loop into a countable one. The benefit is twofold:
519 //
520 // - If the loop only counts population, the entire loop become dead after
521 // the transformation. It is lots easier to prove a countable loop dead
522 // than to prove a noncountable one. (In some C dialects, a infite loop
523 // isn't dead even if it computes nothing useful. In general, DCE needs
524 // to prove a noncountable loop finite before safely delete it.)
525 //
526 // - If the loop also performs something else, it remains alive.
527 // Since it is transformed to countable form, it can be aggressively
528 // optimized by some optimizations which are in general not applicable
529 // to a noncountable loop.
530 //
531 // After this step, this loop (conceptually) would look like following:
532 // newcnt = __builtin_ctpop(x);
533 // t = newcnt;
534 // if (x)
535 // do { cnt++; x &= x-1; t--) } while (t > 0);
536 BasicBlock *Body = *(CurLoop->block_begin());
537 {
538 BranchInst *LbBr = LIRUtil::getBranch(Body);
539 ICmpInst *LbCond = cast<ICmpInst>(LbBr->getCondition());
540 Type *Ty = TripCnt->getType();
541
542 PHINode *TcPhi = PHINode::Create(Ty, 2, "tcphi", Body->begin());
543
544 Builder.SetInsertPoint(LbCond);
545 Value *Opnd1 = cast<Value>(TcPhi);
546 Value *Opnd2 = cast<Value>(ConstantInt::get(Ty, 1));
547 Instruction *TcDec =
548 cast<Instruction>(Builder.CreateSub(Opnd1, Opnd2, "tcdec", false, true));
549
550 TcPhi->addIncoming(TripCnt, PreHead);
551 TcPhi->addIncoming(TcDec, Body);
552
553 CmpInst::Predicate Pred = (LbBr->getSuccessor(0) == Body) ?
554 CmpInst::ICMP_UGT : CmpInst::ICMP_SLE;
555 LbCond->setPredicate(Pred);
556 LbCond->setOperand(0, TcDec);
557 LbCond->setOperand(1, cast<Value>(ConstantInt::get(Ty, 0)));
558 }
559
560 // Step 4: All the references to the original population counter outside
561 // the loop are replaced with the NewCount -- the value returned from
562 // __builtin_ctpop().
Benjamin Kramerf094d772015-02-07 21:37:08 +0000563 CntInst->replaceUsesOutsideBlock(NewCount, Body);
Shuxin Yang95de7c32012-12-09 03:12:46 +0000564
565 // step 5: Forget the "non-computable" trip-count SCEV associated with the
566 // loop. The loop would otherwise not be deleted even if it becomes empty.
567 SE->forgetLoop(CurLoop);
568}
569
Matt Arsenaultfb183232013-07-22 18:59:58 +0000570CallInst *NclPopcountRecognize::createPopcntIntrinsic(IRBuilderTy &IRBuilder,
Shuxin Yang95de7c32012-12-09 03:12:46 +0000571 Value *Val, DebugLoc DL) {
572 Value *Ops[] = { Val };
573 Type *Tys[] = { Val->getType() };
574
575 Module *M = (*(CurLoop->block_begin()))->getParent()->getParent();
576 Value *Func = Intrinsic::getDeclaration(M, Intrinsic::ctpop, Tys);
577 CallInst *CI = IRBuilder.CreateCall(Func, Ops);
578 CI->setDebugLoc(DL);
579
580 return CI;
581}
582
583/// recognize - detect population count idiom in a non-countable loop. If
584/// detected, transform the relevant code to popcount intrinsic function
585/// call, and return true; otherwise, return false.
586bool NclPopcountRecognize::recognize() {
587
Chandler Carruth6fe147f2013-01-05 10:00:09 +0000588 if (!LIR.getTargetTransformInfo())
Shuxin Yang95de7c32012-12-09 03:12:46 +0000589 return false;
590
591 LIR.getScalarEvolution();
592
593 if (!preliminaryScreen())
594 return false;
595
596 Instruction *CntInst;
597 PHINode *CntPhi;
598 Value *Val;
599 if (!detectIdiom(CntInst, CntPhi, Val))
600 return false;
601
602 transform(CntInst, CntPhi, Val);
603 return true;
604}
605
606//===----------------------------------------------------------------------===//
607//
608// Implementation of LoopIdiomRecognize
609//
610//===----------------------------------------------------------------------===//
611
612bool LoopIdiomRecognize::runOnCountableLoop() {
613 const SCEV *BECount = SE->getBackedgeTakenCount(CurLoop);
Davide Italiano8ed04462015-05-11 21:02:34 +0000614 assert(!isa<SCEVCouldNotCompute>(BECount) &&
615 "runOnCountableLoop() called on a loop without a predictable"
616 "backedge-taken count");
Shuxin Yang95de7c32012-12-09 03:12:46 +0000617
618 // If this loop executes exactly one time, then it should be peeled, not
619 // optimized by this pass.
620 if (const SCEVConstant *BECst = dyn_cast<SCEVConstant>(BECount))
621 if (BECst->getValue()->getValue() == 0)
622 return false;
623
Matt Arsenaultfb183232013-07-22 18:59:58 +0000624 // set DT
Shuxin Yang98c844f2013-01-02 18:26:31 +0000625 (void)getDominatorTree();
Shuxin Yang95de7c32012-12-09 03:12:46 +0000626
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000627 LoopInfo &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000628 TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Shuxin Yang95de7c32012-12-09 03:12:46 +0000629
Matt Arsenaultfb183232013-07-22 18:59:58 +0000630 // set TLI
Shuxin Yang98c844f2013-01-02 18:26:31 +0000631 (void)getTargetLibraryInfo();
Shuxin Yang95de7c32012-12-09 03:12:46 +0000632
633 SmallVector<BasicBlock*, 8> ExitBlocks;
634 CurLoop->getUniqueExitBlocks(ExitBlocks);
635
636 DEBUG(dbgs() << "loop-idiom Scanning: F["
637 << CurLoop->getHeader()->getParent()->getName()
638 << "] Loop %" << CurLoop->getHeader()->getName() << "\n");
639
640 bool MadeChange = false;
641 // Scan all the blocks in the loop that are not in subloops.
Davide Italiano80625af2015-05-13 19:51:21 +0000642 for (auto BB : CurLoop->getBlocks()) {
Shuxin Yang95de7c32012-12-09 03:12:46 +0000643 // Ignore blocks in subloops.
Davide Italiano80625af2015-05-13 19:51:21 +0000644 if (LI.getLoopFor(BB) != CurLoop)
Shuxin Yang95de7c32012-12-09 03:12:46 +0000645 continue;
646
Davide Italiano80625af2015-05-13 19:51:21 +0000647 MadeChange |= runOnLoopBlock(BB, BECount, ExitBlocks);
Shuxin Yang95de7c32012-12-09 03:12:46 +0000648 }
649 return MadeChange;
650}
651
652bool LoopIdiomRecognize::runOnNoncountableLoop() {
653 NclPopcountRecognize Popcount(*this);
654 if (Popcount.recognize())
655 return true;
656
657 return false;
658}
659
Chris Lattner81ae3f22010-12-26 19:39:38 +0000660bool LoopIdiomRecognize::runOnLoop(Loop *L, LPPassManager &LPM) {
Paul Robinsonaf4e64d2014-02-06 00:07:05 +0000661 if (skipOptnoneFunction(L))
662 return false;
663
Chris Lattner7c5f9c32010-12-26 20:45:45 +0000664 CurLoop = L;
Andrew Trick328b2232011-03-14 16:48:10 +0000665
Benjamin Kramereba9aca2012-09-21 17:27:23 +0000666 // If the loop could not be converted to canonical form, it must have an
667 // indirectbr in it, just give up.
668 if (!L->getLoopPreheader())
669 return false;
670
Nadav Rotem465834c2012-07-24 10:51:42 +0000671 // Disable loop idiom recognition if the function's name is a common idiom.
Chad Rosiera7ff5432011-07-15 18:25:04 +0000672 StringRef Name = L->getHeader()->getParent()->getName();
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000673 if (Name == "memset" || Name == "memcpy")
Chad Rosiera7ff5432011-07-15 18:25:04 +0000674 return false;
675
Chris Lattner7c5f9c32010-12-26 20:45:45 +0000676 SE = &getAnalysis<ScalarEvolution>();
Shuxin Yang95de7c32012-12-09 03:12:46 +0000677 if (SE->hasLoopInvariantBackedgeTakenCount(L))
678 return runOnCountableLoop();
679 return runOnNoncountableLoop();
Chris Lattner8455b6e2011-01-02 19:01:03 +0000680}
681
682/// runOnLoopBlock - Process the specified block, which lives in a counted loop
683/// with the specified backedge count. This block is known to be in the current
684/// loop and not in any subloops.
685bool LoopIdiomRecognize::runOnLoopBlock(BasicBlock *BB, const SCEV *BECount,
686 SmallVectorImpl<BasicBlock*> &ExitBlocks) {
687 // We can only promote stores in this block if they are unconditionally
688 // executed in the loop. For a block to be unconditionally executed, it has
689 // to dominate all the exit blocks of the loop. Verify this now.
690 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
691 if (!DT->dominates(BB, ExitBlocks[i]))
692 return false;
Andrew Trick328b2232011-03-14 16:48:10 +0000693
Chris Lattner7c5f9c32010-12-26 20:45:45 +0000694 bool MadeChange = false;
695 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
Chris Lattnera62b01d2011-01-04 07:27:30 +0000696 Instruction *Inst = I++;
697 // Look for store instructions, which may be optimized to memset/memcpy.
698 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
Chris Lattnera62b01d2011-01-04 07:27:30 +0000699 WeakVH InstPtr(I);
700 if (!processLoopStore(SI, BECount)) continue;
701 MadeChange = true;
Andrew Trick328b2232011-03-14 16:48:10 +0000702
Chris Lattnera62b01d2011-01-04 07:27:30 +0000703 // If processing the store invalidated our iterator, start over from the
Chris Lattner86438102011-01-04 07:46:33 +0000704 // top of the block.
Craig Topperf40110f2014-04-25 05:29:35 +0000705 if (!InstPtr)
Chris Lattnera62b01d2011-01-04 07:27:30 +0000706 I = BB->begin();
707 continue;
708 }
Andrew Trick328b2232011-03-14 16:48:10 +0000709
Chris Lattner86438102011-01-04 07:46:33 +0000710 // Look for memset instructions, which may be optimized to a larger memset.
711 if (MemSetInst *MSI = dyn_cast<MemSetInst>(Inst)) {
712 WeakVH InstPtr(I);
713 if (!processLoopMemSet(MSI, BECount)) continue;
714 MadeChange = true;
Andrew Trick328b2232011-03-14 16:48:10 +0000715
Chris Lattner86438102011-01-04 07:46:33 +0000716 // If processing the memset invalidated our iterator, start over from the
717 // top of the block.
Craig Topperf40110f2014-04-25 05:29:35 +0000718 if (!InstPtr)
Chris Lattner86438102011-01-04 07:46:33 +0000719 I = BB->begin();
720 continue;
721 }
Chris Lattner7c5f9c32010-12-26 20:45:45 +0000722 }
Andrew Trick328b2232011-03-14 16:48:10 +0000723
Chris Lattner7c5f9c32010-12-26 20:45:45 +0000724 return MadeChange;
Chris Lattner81ae3f22010-12-26 19:39:38 +0000725}
726
Chris Lattner8455b6e2011-01-02 19:01:03 +0000727
Chris Lattner86438102011-01-04 07:46:33 +0000728/// processLoopStore - See if this store can be promoted to a memset or memcpy.
Chris Lattner7c5f9c32010-12-26 20:45:45 +0000729bool LoopIdiomRecognize::processLoopStore(StoreInst *SI, const SCEV *BECount) {
Eli Friedman7c5dc122011-09-12 20:23:13 +0000730 if (!SI->isSimple()) return false;
Chris Lattner86438102011-01-04 07:46:33 +0000731
Chris Lattner7c5f9c32010-12-26 20:45:45 +0000732 Value *StoredVal = SI->getValueOperand();
Chris Lattner29e14ed2010-12-26 23:42:51 +0000733 Value *StorePtr = SI->getPointerOperand();
Andrew Trick328b2232011-03-14 16:48:10 +0000734
Chris Lattner65a699d2010-12-28 18:53:48 +0000735 // Reject stores that are so large that they overflow an unsigned.
Mehdi Amini46a43552015-03-04 18:43:29 +0000736 auto &DL = CurLoop->getHeader()->getModule()->getDataLayout();
737 uint64_t SizeInBits = DL.getTypeSizeInBits(StoredVal->getType());
Chris Lattner65a699d2010-12-28 18:53:48 +0000738 if ((SizeInBits & 7) || (SizeInBits >> 32) != 0)
Chris Lattner7c5f9c32010-12-26 20:45:45 +0000739 return false;
Andrew Trick328b2232011-03-14 16:48:10 +0000740
Chris Lattner7c5f9c32010-12-26 20:45:45 +0000741 // See if the pointer expression is an AddRec like {base,+,1} on the current
742 // loop, which indicates a strided store. If we have something else, it's a
743 // random store we can't handle.
Chris Lattner85b6d812011-01-02 03:37:56 +0000744 const SCEVAddRecExpr *StoreEv =
745 dyn_cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr));
Craig Topperf40110f2014-04-25 05:29:35 +0000746 if (!StoreEv || StoreEv->getLoop() != CurLoop || !StoreEv->isAffine())
Chris Lattner7c5f9c32010-12-26 20:45:45 +0000747 return false;
748
749 // Check to see if the stride matches the size of the store. If so, then we
750 // know that every byte is touched in the loop.
Andrew Trick328b2232011-03-14 16:48:10 +0000751 unsigned StoreSize = (unsigned)SizeInBits >> 3;
Chris Lattner85b6d812011-01-02 03:37:56 +0000752 const SCEVConstant *Stride = dyn_cast<SCEVConstant>(StoreEv->getOperand(1));
Andrew Trick328b2232011-03-14 16:48:10 +0000753
Craig Topperf40110f2014-04-25 05:29:35 +0000754 if (!Stride || StoreSize != Stride->getValue()->getValue()) {
Chris Lattnerbc661d62011-02-21 02:08:54 +0000755 // TODO: Could also handle negative stride here someday, that will require
756 // the validity check in mayLoopAccessLocation to be updated though.
757 // Enable this to print exact negative strides.
Chris Lattner2333ac22011-02-21 17:02:55 +0000758 if (0 && Stride && StoreSize == -Stride->getValue()->getValue()) {
Chris Lattnerbc661d62011-02-21 02:08:54 +0000759 dbgs() << "NEGATIVE STRIDE: " << *SI << "\n";
760 dbgs() << "BB: " << *SI->getParent();
761 }
Andrew Trick328b2232011-03-14 16:48:10 +0000762
Chris Lattner7c5f9c32010-12-26 20:45:45 +0000763 return false;
Chris Lattnerbc661d62011-02-21 02:08:54 +0000764 }
Chris Lattner0f4a6402011-02-19 19:31:39 +0000765
766 // See if we can optimize just this store in isolation.
767 if (processLoopStridedStore(StorePtr, StoreSize, SI->getAlignment(),
768 StoredVal, SI, StoreEv, BECount))
769 return true;
Chris Lattner29e14ed2010-12-26 23:42:51 +0000770
Chris Lattner85b6d812011-01-02 03:37:56 +0000771 // If the stored value is a strided load in the same loop with the same stride
772 // this this may be transformable into a memcpy. This kicks in for stuff like
773 // for (i) A[i] = B[i];
774 if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) {
775 const SCEVAddRecExpr *LoadEv =
776 dyn_cast<SCEVAddRecExpr>(SE->getSCEV(LI->getOperand(0)));
777 if (LoadEv && LoadEv->getLoop() == CurLoop && LoadEv->isAffine() &&
Eli Friedman7c5dc122011-09-12 20:23:13 +0000778 StoreEv->getOperand(1) == LoadEv->getOperand(1) && LI->isSimple())
Chris Lattner85b6d812011-01-02 03:37:56 +0000779 if (processLoopStoreOfLoopLoad(SI, StoreSize, StoreEv, LoadEv, BECount))
780 return true;
781 }
Chris Lattner12f91be2011-01-02 07:36:44 +0000782 //errs() << "UNHANDLED strided store: " << *StoreEv << " - " << *SI << "\n";
Chris Lattner7c5f9c32010-12-26 20:45:45 +0000783
Chris Lattner81ae3f22010-12-26 19:39:38 +0000784 return false;
785}
786
Chris Lattner86438102011-01-04 07:46:33 +0000787/// processLoopMemSet - See if this memset can be promoted to a large memset.
788bool LoopIdiomRecognize::
789processLoopMemSet(MemSetInst *MSI, const SCEV *BECount) {
790 // We can only handle non-volatile memsets with a constant size.
791 if (MSI->isVolatile() || !isa<ConstantInt>(MSI->getLength())) return false;
792
Chris Lattnere6b261f2011-02-18 22:22:15 +0000793 // If we're not allowed to hack on memset, we fail.
794 if (!TLI->has(LibFunc::memset))
795 return false;
Andrew Trick328b2232011-03-14 16:48:10 +0000796
Chris Lattner86438102011-01-04 07:46:33 +0000797 Value *Pointer = MSI->getDest();
Andrew Trick328b2232011-03-14 16:48:10 +0000798
Chris Lattner86438102011-01-04 07:46:33 +0000799 // See if the pointer expression is an AddRec like {base,+,1} on the current
800 // loop, which indicates a strided store. If we have something else, it's a
801 // random store we can't handle.
802 const SCEVAddRecExpr *Ev = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Pointer));
Craig Topperf40110f2014-04-25 05:29:35 +0000803 if (!Ev || Ev->getLoop() != CurLoop || !Ev->isAffine())
Chris Lattner86438102011-01-04 07:46:33 +0000804 return false;
805
806 // Reject memsets that are so large that they overflow an unsigned.
807 uint64_t SizeInBytes = cast<ConstantInt>(MSI->getLength())->getZExtValue();
808 if ((SizeInBytes >> 32) != 0)
809 return false;
Andrew Trick328b2232011-03-14 16:48:10 +0000810
Chris Lattner86438102011-01-04 07:46:33 +0000811 // Check to see if the stride matches the size of the memset. If so, then we
812 // know that every byte is touched in the loop.
813 const SCEVConstant *Stride = dyn_cast<SCEVConstant>(Ev->getOperand(1));
Andrew Trick328b2232011-03-14 16:48:10 +0000814
Chris Lattner86438102011-01-04 07:46:33 +0000815 // TODO: Could also handle negative stride here someday, that will require the
816 // validity check in mayLoopAccessLocation to be updated though.
Craig Topperf40110f2014-04-25 05:29:35 +0000817 if (!Stride || MSI->getLength() != Stride->getValue())
Chris Lattner86438102011-01-04 07:46:33 +0000818 return false;
Andrew Trick328b2232011-03-14 16:48:10 +0000819
Chris Lattner0f4a6402011-02-19 19:31:39 +0000820 return processLoopStridedStore(Pointer, (unsigned)SizeInBytes,
821 MSI->getAlignment(), MSI->getValue(),
822 MSI, Ev, BECount);
Chris Lattner86438102011-01-04 07:46:33 +0000823}
824
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000825
826/// mayLoopAccessLocation - Return true if the specified loop might access the
827/// specified pointer location, which is a loop-strided access. The 'Access'
828/// argument specifies what the verboten forms of access are (read or write).
829static bool mayLoopAccessLocation(Value *Ptr,AliasAnalysis::ModRefResult Access,
830 Loop *L, const SCEV *BECount,
831 unsigned StoreSize, AliasAnalysis &AA,
832 Instruction *IgnoredStore) {
833 // Get the location that may be stored across the loop. Since the access is
834 // strided positively through memory, we say that the modified location starts
835 // at the pointer and has infinite size.
836 uint64_t AccessSize = AliasAnalysis::UnknownSize;
837
838 // If the loop iterates a fixed number of times, we can refine the access size
839 // to be exactly the size of the memset, which is (BECount+1)*StoreSize
840 if (const SCEVConstant *BECst = dyn_cast<SCEVConstant>(BECount))
841 AccessSize = (BECst->getValue()->getZExtValue()+1)*StoreSize;
842
843 // TODO: For this to be really effective, we have to dive into the pointer
844 // operand in the store. Store to &A[i] of 100 will always return may alias
845 // with store of &A[100], we need to StoreLoc to be "A" with size of 100,
846 // which will then no-alias a store to &A[100].
847 AliasAnalysis::Location StoreLoc(Ptr, AccessSize);
848
849 for (Loop::block_iterator BI = L->block_begin(), E = L->block_end(); BI != E;
850 ++BI)
851 for (BasicBlock::iterator I = (*BI)->begin(), E = (*BI)->end(); I != E; ++I)
852 if (&*I != IgnoredStore &&
853 (AA.getModRefInfo(I, StoreLoc) & Access))
854 return true;
855
856 return false;
857}
858
Chris Lattner0f4a6402011-02-19 19:31:39 +0000859/// getMemSetPatternValue - If a strided store of the specified value is safe to
860/// turn into a memset_pattern16, return a ConstantArray of 16 bytes that should
861/// be passed in. Otherwise, return null.
862///
863/// Note that we don't ever attempt to use memset_pattern8 or 4, because these
864/// just replicate their input array and then pass on to memset_pattern16.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000865static Constant *getMemSetPatternValue(Value *V, const DataLayout &DL) {
Chris Lattner0f4a6402011-02-19 19:31:39 +0000866 // If the value isn't a constant, we can't promote it to being in a constant
867 // array. We could theoretically do a store to an alloca or something, but
868 // that doesn't seem worthwhile.
869 Constant *C = dyn_cast<Constant>(V);
Craig Topperf40110f2014-04-25 05:29:35 +0000870 if (!C) return nullptr;
Andrew Trick328b2232011-03-14 16:48:10 +0000871
Chris Lattner0f4a6402011-02-19 19:31:39 +0000872 // Only handle simple values that are a power of two bytes in size.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000873 uint64_t Size = DL.getTypeSizeInBits(V->getType());
Chris Lattner0f4a6402011-02-19 19:31:39 +0000874 if (Size == 0 || (Size & 7) || (Size & (Size-1)))
Craig Topperf40110f2014-04-25 05:29:35 +0000875 return nullptr;
Andrew Trick328b2232011-03-14 16:48:10 +0000876
Chris Lattner72a35fb2011-02-19 19:56:44 +0000877 // Don't care enough about darwin/ppc to implement this.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000878 if (DL.isBigEndian())
Craig Topperf40110f2014-04-25 05:29:35 +0000879 return nullptr;
Chris Lattner0f4a6402011-02-19 19:31:39 +0000880
881 // Convert to size in bytes.
882 Size /= 8;
Chris Lattner0f4a6402011-02-19 19:31:39 +0000883
Chris Lattner0f4a6402011-02-19 19:31:39 +0000884 // TODO: If CI is larger than 16-bytes, we can try slicing it in half to see
Chris Lattner72a35fb2011-02-19 19:56:44 +0000885 // if the top and bottom are the same (e.g. for vectors and large integers).
Craig Topperf40110f2014-04-25 05:29:35 +0000886 if (Size > 16) return nullptr;
Andrew Trick328b2232011-03-14 16:48:10 +0000887
Chris Lattner72a35fb2011-02-19 19:56:44 +0000888 // If the constant is exactly 16 bytes, just use it.
889 if (Size == 16) return C;
Chris Lattner0f4a6402011-02-19 19:31:39 +0000890
Chris Lattner72a35fb2011-02-19 19:56:44 +0000891 // Otherwise, we'll use an array of the constants.
892 unsigned ArraySize = 16/Size;
893 ArrayType *AT = ArrayType::get(V->getType(), ArraySize);
894 return ConstantArray::get(AT, std::vector<Constant*>(ArraySize, C));
Chris Lattner0f4a6402011-02-19 19:31:39 +0000895}
896
897
898/// processLoopStridedStore - We see a strided store of some value. If we can
899/// transform this into a memset or memset_pattern in the loop preheader, do so.
900bool LoopIdiomRecognize::
901processLoopStridedStore(Value *DestPtr, unsigned StoreSize,
902 unsigned StoreAlignment, Value *StoredVal,
903 Instruction *TheStore, const SCEVAddRecExpr *Ev,
904 const SCEV *BECount) {
Andrew Trick328b2232011-03-14 16:48:10 +0000905
Chris Lattner0f4a6402011-02-19 19:31:39 +0000906 // If the stored value is a byte-wise value (like i32 -1), then it may be
907 // turned into a memset of i8 -1, assuming that all the consecutive bytes
908 // are stored. A store of i32 0x01020304 can never be turned into a memset,
909 // but it can be turned into memset_pattern if the target supports it.
910 Value *SplatValue = isBytewiseValue(StoredVal);
Craig Topperf40110f2014-04-25 05:29:35 +0000911 Constant *PatternValue = nullptr;
Mehdi Amini46a43552015-03-04 18:43:29 +0000912 auto &DL = CurLoop->getHeader()->getModule()->getDataLayout();
Matt Arsenault009faed2013-09-11 05:09:42 +0000913 unsigned DestAS = DestPtr->getType()->getPointerAddressSpace();
914
Chris Lattner0f4a6402011-02-19 19:31:39 +0000915 // If we're allowed to form a memset, and the stored value would be acceptable
916 // for memset, use it.
917 if (SplatValue && TLI->has(LibFunc::memset) &&
918 // Verify that the stored value is loop invariant. If not, we can't
919 // promote the memset.
920 CurLoop->isLoopInvariant(SplatValue)) {
921 // Keep and use SplatValue.
Craig Topperf40110f2014-04-25 05:29:35 +0000922 PatternValue = nullptr;
Mehdi Amini46a43552015-03-04 18:43:29 +0000923 } else if (DestAS == 0 && TLI->has(LibFunc::memset_pattern16) &&
924 (PatternValue = getMemSetPatternValue(StoredVal, DL))) {
Matt Arsenault009faed2013-09-11 05:09:42 +0000925 // Don't create memset_pattern16s with address spaces.
Chris Lattner0f4a6402011-02-19 19:31:39 +0000926 // It looks like we can use PatternValue!
Craig Topperf40110f2014-04-25 05:29:35 +0000927 SplatValue = nullptr;
Chris Lattner0f4a6402011-02-19 19:31:39 +0000928 } else {
929 // Otherwise, this isn't an idiom we can transform. For example, we can't
Eli Friedmana93ab132011-09-13 00:44:16 +0000930 // do anything with a 3-byte store.
Chris Lattnera3514442011-01-01 20:12:04 +0000931 return false;
Chris Lattner0f4a6402011-02-19 19:31:39 +0000932 }
Andrew Trick328b2232011-03-14 16:48:10 +0000933
Chris Lattnerc4ca7ab2011-05-22 17:39:56 +0000934 // The trip count of the loop and the base pointer of the addrec SCEV is
935 // guaranteed to be loop invariant, which means that it should dominate the
936 // header. This allows us to insert code for it in the preheader.
937 BasicBlock *Preheader = CurLoop->getLoopPreheader();
938 IRBuilder<> Builder(Preheader->getTerminator());
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000939 SCEVExpander Expander(*SE, DL, "loop-idiom");
Andrew Trick60ab3ef2011-06-28 05:04:16 +0000940
Matt Arsenault009faed2013-09-11 05:09:42 +0000941 Type *DestInt8PtrTy = Builder.getInt8PtrTy(DestAS);
942
Chris Lattner29e14ed2010-12-26 23:42:51 +0000943 // Okay, we have a strided store "p[i]" of a splattable value. We can turn
Benjamin Kramerf77f2242012-10-21 19:31:16 +0000944 // this into a memset in the loop preheader now if we want. However, this
945 // would be unsafe to do if there is anything else in the loop that may read
Chandler Carruth7ec50852012-11-01 08:07:29 +0000946 // or write to the aliased location. Check for any overlap by generating the
947 // base pointer and checking the region.
Andrew Trick328b2232011-03-14 16:48:10 +0000948 Value *BasePtr =
Matt Arsenault009faed2013-09-11 05:09:42 +0000949 Expander.expandCodeFor(Ev->getStart(), DestInt8PtrTy,
Chris Lattner29e14ed2010-12-26 23:42:51 +0000950 Preheader->getTerminator());
Andrew Trick328b2232011-03-14 16:48:10 +0000951
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000952 if (mayLoopAccessLocation(BasePtr, AliasAnalysis::ModRef,
953 CurLoop, BECount,
Matt Arsenault5df49bd2013-09-11 05:09:35 +0000954 StoreSize, getAnalysis<AliasAnalysis>(), TheStore)) {
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000955 Expander.clear();
956 // If we generated new code for the base pointer, clean up.
Benjamin Kramerf094d772015-02-07 21:37:08 +0000957 RecursivelyDeleteTriviallyDeadInstructions(BasePtr, TLI);
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000958 return false;
959 }
960
Chris Lattnerc4ca7ab2011-05-22 17:39:56 +0000961 // Okay, everything looks good, insert the memset.
962
Chris Lattner29e14ed2010-12-26 23:42:51 +0000963 // The # stored bytes is (BECount+1)*Size. Expand the trip count out to
964 // pointer size if it isn't already.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000965 Type *IntPtr = Builder.getIntPtrTy(DL, DestAS);
Chris Lattner0ba473c2011-01-04 00:06:55 +0000966 BECount = SE->getTruncateOrZeroExtend(BECount, IntPtr);
Andrew Trick328b2232011-03-14 16:48:10 +0000967
Chris Lattner29e14ed2010-12-26 23:42:51 +0000968 const SCEV *NumBytesS = SE->getAddExpr(BECount, SE->getConstant(IntPtr, 1),
Andrew Trick8b55b732011-03-14 16:50:06 +0000969 SCEV::FlagNUW);
Matt Arsenault5df49bd2013-09-11 05:09:35 +0000970 if (StoreSize != 1) {
Chris Lattner29e14ed2010-12-26 23:42:51 +0000971 NumBytesS = SE->getMulExpr(NumBytesS, SE->getConstant(IntPtr, StoreSize),
Andrew Trick8b55b732011-03-14 16:50:06 +0000972 SCEV::FlagNUW);
Matt Arsenault5df49bd2013-09-11 05:09:35 +0000973 }
Andrew Trick328b2232011-03-14 16:48:10 +0000974
975 Value *NumBytes =
Chris Lattner29e14ed2010-12-26 23:42:51 +0000976 Expander.expandCodeFor(NumBytesS, IntPtr, Preheader->getTerminator());
Andrew Trick328b2232011-03-14 16:48:10 +0000977
Devang Pateld00c6282011-03-07 22:43:45 +0000978 CallInst *NewCall;
Matt Arsenault5df49bd2013-09-11 05:09:35 +0000979 if (SplatValue) {
980 NewCall = Builder.CreateMemSet(BasePtr,
981 SplatValue,
982 NumBytes,
983 StoreAlignment);
984 } else {
Matt Arsenault009faed2013-09-11 05:09:42 +0000985 // Everything is emitted in default address space
986 Type *Int8PtrTy = DestInt8PtrTy;
987
Chris Lattner0f4a6402011-02-19 19:31:39 +0000988 Module *M = TheStore->getParent()->getParent()->getParent();
989 Value *MSP = M->getOrInsertFunction("memset_pattern16",
990 Builder.getVoidTy(),
Matt Arsenault009faed2013-09-11 05:09:42 +0000991 Int8PtrTy,
992 Int8PtrTy,
993 IntPtr,
Craig Topperf40110f2014-04-25 05:29:35 +0000994 (void*)nullptr);
Andrew Trick328b2232011-03-14 16:48:10 +0000995
Chris Lattner0f4a6402011-02-19 19:31:39 +0000996 // Otherwise we should form a memset_pattern16. PatternValue is known to be
997 // an constant array of 16-bytes. Plop the value into a mergable global.
998 GlobalVariable *GV = new GlobalVariable(*M, PatternValue->getType(), true,
Benjamin Kramer838752d2015-03-03 00:17:09 +0000999 GlobalValue::PrivateLinkage,
Chris Lattner0f4a6402011-02-19 19:31:39 +00001000 PatternValue, ".memset_pattern");
1001 GV->setUnnamedAddr(true); // Ok to merge these.
1002 GV->setAlignment(16);
Matt Arsenault009faed2013-09-11 05:09:42 +00001003 Value *PatternPtr = ConstantExpr::getBitCast(GV, Int8PtrTy);
Chris Lattner0f4a6402011-02-19 19:31:39 +00001004 NewCall = Builder.CreateCall3(MSP, BasePtr, PatternPtr, NumBytes);
1005 }
Andrew Trick328b2232011-03-14 16:48:10 +00001006
Chris Lattner29e14ed2010-12-26 23:42:51 +00001007 DEBUG(dbgs() << " Formed memset: " << *NewCall << "\n"
Chris Lattner86438102011-01-04 07:46:33 +00001008 << " from store to: " << *Ev << " at: " << *TheStore << "\n");
Devang Pateld00c6282011-03-07 22:43:45 +00001009 NewCall->setDebugLoc(TheStore->getDebugLoc());
Andrew Trick328b2232011-03-14 16:48:10 +00001010
Chris Lattnerb9fe6852010-12-27 00:03:23 +00001011 // Okay, the memset has been formed. Zap the original store and anything that
1012 // feeds into it.
Benjamin Kramerf094d772015-02-07 21:37:08 +00001013 deleteDeadInstruction(TheStore, TLI);
Chris Lattner12f91be2011-01-02 07:36:44 +00001014 ++NumMemSet;
Chris Lattner29e14ed2010-12-26 23:42:51 +00001015 return true;
1016}
1017
Chris Lattner85b6d812011-01-02 03:37:56 +00001018/// processLoopStoreOfLoopLoad - We see a strided store whose value is a
1019/// same-strided load.
1020bool LoopIdiomRecognize::
1021processLoopStoreOfLoopLoad(StoreInst *SI, unsigned StoreSize,
1022 const SCEVAddRecExpr *StoreEv,
1023 const SCEVAddRecExpr *LoadEv,
1024 const SCEV *BECount) {
Chris Lattnere6b261f2011-02-18 22:22:15 +00001025 // If we're not allowed to form memcpy, we fail.
Chandler Carruth099f5cb02012-11-02 08:33:25 +00001026 if (!TLI->has(LibFunc::memcpy))
Chris Lattnere6b261f2011-02-18 22:22:15 +00001027 return false;
Andrew Trick328b2232011-03-14 16:48:10 +00001028
Chris Lattner85b6d812011-01-02 03:37:56 +00001029 LoadInst *LI = cast<LoadInst>(SI->getValueOperand());
Andrew Trick328b2232011-03-14 16:48:10 +00001030
Chris Lattnerc4ca7ab2011-05-22 17:39:56 +00001031 // The trip count of the loop and the base pointer of the addrec SCEV is
1032 // guaranteed to be loop invariant, which means that it should dominate the
1033 // header. This allows us to insert code for it in the preheader.
1034 BasicBlock *Preheader = CurLoop->getLoopPreheader();
1035 IRBuilder<> Builder(Preheader->getTerminator());
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001036 const DataLayout &DL = Preheader->getModule()->getDataLayout();
1037 SCEVExpander Expander(*SE, DL, "loop-idiom");
Andrew Trick60ab3ef2011-06-28 05:04:16 +00001038
Chris Lattner85b6d812011-01-02 03:37:56 +00001039 // Okay, we have a strided store "p[i]" of a loaded value. We can turn
Chandler Carruth099f5cb02012-11-02 08:33:25 +00001040 // this into a memcpy in the loop preheader now if we want. However, this
1041 // would be unsafe to do if there is anything else in the loop that may read
1042 // or write the memory region we're storing to. This includes the load that
1043 // feeds the stores. Check for an alias by generating the base address and
1044 // checking everything.
Andrew Trick328b2232011-03-14 16:48:10 +00001045 Value *StoreBasePtr =
Chris Lattner85b6d812011-01-02 03:37:56 +00001046 Expander.expandCodeFor(StoreEv->getStart(),
1047 Builder.getInt8PtrTy(SI->getPointerAddressSpace()),
1048 Preheader->getTerminator());
Chandler Carruth099f5cb02012-11-02 08:33:25 +00001049
1050 if (mayLoopAccessLocation(StoreBasePtr, AliasAnalysis::ModRef,
1051 CurLoop, BECount, StoreSize,
1052 getAnalysis<AliasAnalysis>(), SI)) {
1053 Expander.clear();
1054 // If we generated new code for the base pointer, clean up.
Benjamin Kramerf094d772015-02-07 21:37:08 +00001055 RecursivelyDeleteTriviallyDeadInstructions(StoreBasePtr, TLI);
Chandler Carruth099f5cb02012-11-02 08:33:25 +00001056 return false;
1057 }
1058
1059 // For a memcpy, we have to make sure that the input array is not being
1060 // mutated by the loop.
Chris Lattnerc4ca7ab2011-05-22 17:39:56 +00001061 Value *LoadBasePtr =
1062 Expander.expandCodeFor(LoadEv->getStart(),
1063 Builder.getInt8PtrTy(LI->getPointerAddressSpace()),
1064 Preheader->getTerminator());
1065
Chandler Carruth099f5cb02012-11-02 08:33:25 +00001066 if (mayLoopAccessLocation(LoadBasePtr, AliasAnalysis::Mod, CurLoop, BECount,
1067 StoreSize, getAnalysis<AliasAnalysis>(), SI)) {
1068 Expander.clear();
1069 // If we generated new code for the base pointer, clean up.
Benjamin Kramerf094d772015-02-07 21:37:08 +00001070 RecursivelyDeleteTriviallyDeadInstructions(LoadBasePtr, TLI);
1071 RecursivelyDeleteTriviallyDeadInstructions(StoreBasePtr, TLI);
Chandler Carruth099f5cb02012-11-02 08:33:25 +00001072 return false;
1073 }
1074
Chris Lattnerc4ca7ab2011-05-22 17:39:56 +00001075 // Okay, everything is safe, we can transform this!
Andrew Trick60ab3ef2011-06-28 05:04:16 +00001076
Andrew Trick328b2232011-03-14 16:48:10 +00001077
Chris Lattner85b6d812011-01-02 03:37:56 +00001078 // The # stored bytes is (BECount+1)*Size. Expand the trip count out to
1079 // pointer size if it isn't already.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001080 Type *IntPtrTy = Builder.getIntPtrTy(DL, SI->getPointerAddressSpace());
Matt Arsenault009faed2013-09-11 05:09:42 +00001081 BECount = SE->getTruncateOrZeroExtend(BECount, IntPtrTy);
Andrew Trick328b2232011-03-14 16:48:10 +00001082
Matt Arsenault009faed2013-09-11 05:09:42 +00001083 const SCEV *NumBytesS = SE->getAddExpr(BECount, SE->getConstant(IntPtrTy, 1),
Andrew Trick8b55b732011-03-14 16:50:06 +00001084 SCEV::FlagNUW);
Chris Lattner85b6d812011-01-02 03:37:56 +00001085 if (StoreSize != 1)
Matt Arsenault009faed2013-09-11 05:09:42 +00001086 NumBytesS = SE->getMulExpr(NumBytesS, SE->getConstant(IntPtrTy, StoreSize),
Andrew Trick8b55b732011-03-14 16:50:06 +00001087 SCEV::FlagNUW);
Andrew Trick328b2232011-03-14 16:48:10 +00001088
Chris Lattner85b6d812011-01-02 03:37:56 +00001089 Value *NumBytes =
Matt Arsenault009faed2013-09-11 05:09:42 +00001090 Expander.expandCodeFor(NumBytesS, IntPtrTy, Preheader->getTerminator());
Andrew Trick328b2232011-03-14 16:48:10 +00001091
Chandler Carruth099f5cb02012-11-02 08:33:25 +00001092 CallInst *NewCall =
1093 Builder.CreateMemCpy(StoreBasePtr, LoadBasePtr, NumBytes,
1094 std::min(SI->getAlignment(), LI->getAlignment()));
Devang Patel0daa07e2011-05-04 21:37:05 +00001095 NewCall->setDebugLoc(SI->getDebugLoc());
Andrew Trick328b2232011-03-14 16:48:10 +00001096
Chandler Carruth099f5cb02012-11-02 08:33:25 +00001097 DEBUG(dbgs() << " Formed memcpy: " << *NewCall << "\n"
Chris Lattner85b6d812011-01-02 03:37:56 +00001098 << " from load ptr=" << *LoadEv << " at: " << *LI << "\n"
1099 << " from store ptr=" << *StoreEv << " at: " << *SI << "\n");
Andrew Trick60ab3ef2011-06-28 05:04:16 +00001100
Andrew Trick328b2232011-03-14 16:48:10 +00001101
Chris Lattner85b6d812011-01-02 03:37:56 +00001102 // Okay, the memset has been formed. Zap the original store and anything that
1103 // feeds into it.
Benjamin Kramerf094d772015-02-07 21:37:08 +00001104 deleteDeadInstruction(SI, TLI);
Chandler Carruth099f5cb02012-11-02 08:33:25 +00001105 ++NumMemCpy;
Chris Lattner85b6d812011-01-02 03:37:56 +00001106 return true;
1107}