blob: 33633ae073f959bcdec203cff4492c15d291f26a [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
Chandler Carruthbad690e2015-08-12 23:06:37 +000070class LoopIdiomRecognize;
Shuxin Yang95de7c32012-12-09 03:12:46 +000071
Chandler Carruthbad690e2015-08-12 23:06:37 +000072/// This class is to recoginize idioms of population-count conducted in
73/// a noncountable loop. Currently it only recognizes this pattern:
74/// \code
75/// while(x) {cnt++; ...; x &= x - 1; ...}
76/// \endcode
77class NclPopcountRecognize {
78 LoopIdiomRecognize &LIR;
79 Loop *CurLoop;
80 BasicBlock *PreCondBB;
Shuxin Yang95de7c32012-12-09 03:12:46 +000081
Chandler Carruthbad690e2015-08-12 23:06:37 +000082 typedef IRBuilder<> IRBuilderTy;
Shuxin Yang95de7c32012-12-09 03:12:46 +000083
Chandler Carruthbad690e2015-08-12 23:06:37 +000084public:
85 explicit NclPopcountRecognize(LoopIdiomRecognize &TheLIR);
86 bool recognize();
Shuxin Yang95de7c32012-12-09 03:12:46 +000087
Chandler Carruthbad690e2015-08-12 23:06:37 +000088private:
89 /// Take a glimpse of the loop to see if we need to go ahead recoginizing
90 /// the idiom.
91 bool preliminaryScreen();
Shuxin Yang95de7c32012-12-09 03:12:46 +000092
Chandler Carruthbad690e2015-08-12 23:06:37 +000093 /// Check if the given conditional branch is based on the comparison
94 /// between a variable and zero, and if the variable is non-zero, the
95 /// control yields to the loop entry. If the branch matches the behavior,
96 /// the variable involved in the comparion is returned. This function will
97 /// be called to see if the precondition and postcondition of the loop
98 /// are in desirable form.
99 Value *matchCondition(BranchInst *Br, BasicBlock *NonZeroTarget) const;
Shuxin Yang95de7c32012-12-09 03:12:46 +0000100
Chandler Carruthbad690e2015-08-12 23:06:37 +0000101 /// Return true iff the idiom is detected in the loop. and 1) \p CntInst
102 /// is set to the instruction counting the population bit. 2) \p CntPhi
103 /// is set to the corresponding phi node. 3) \p Var is set to the value
104 /// whose population bits are being counted.
105 bool detectIdiom(Instruction *&CntInst, PHINode *&CntPhi, Value *&Var) const;
Shuxin Yang95de7c32012-12-09 03:12:46 +0000106
Chandler Carruthbad690e2015-08-12 23:06:37 +0000107 /// Insert ctpop intrinsic function and some obviously dead instructions.
108 void transform(Instruction *CntInst, PHINode *CntPhi, Value *Var);
Shuxin Yang95de7c32012-12-09 03:12:46 +0000109
Chandler Carruthbad690e2015-08-12 23:06:37 +0000110 /// Create llvm.ctpop.* intrinsic function.
111 CallInst *createPopcntIntrinsic(IRBuilderTy &IRB, Value *Val, DebugLoc DL);
112};
Shuxin Yang95de7c32012-12-09 03:12:46 +0000113
Chandler Carruthbad690e2015-08-12 23:06:37 +0000114class LoopIdiomRecognize : public LoopPass {
115 Loop *CurLoop;
116 DominatorTree *DT;
117 ScalarEvolution *SE;
118 TargetLibraryInfo *TLI;
119 const TargetTransformInfo *TTI;
Chris Lattner81ae3f22010-12-26 19:39:38 +0000120
Chandler Carruthbad690e2015-08-12 23:06:37 +0000121public:
122 static char ID;
123 explicit LoopIdiomRecognize() : LoopPass(ID) {
124 initializeLoopIdiomRecognizePass(*PassRegistry::getPassRegistry());
125 DT = nullptr;
126 SE = nullptr;
127 TLI = nullptr;
128 TTI = nullptr;
129 }
Chris Lattner81ae3f22010-12-26 19:39:38 +0000130
Chandler Carruthbad690e2015-08-12 23:06:37 +0000131 bool runOnLoop(Loop *L, LPPassManager &LPM) override;
132 bool runOnLoopBlock(BasicBlock *BB, const SCEV *BECount,
133 SmallVectorImpl<BasicBlock *> &ExitBlocks);
Andrew Trick328b2232011-03-14 16:48:10 +0000134
Chandler Carruthbad690e2015-08-12 23:06:37 +0000135 bool processLoopStore(StoreInst *SI, const SCEV *BECount);
136 bool processLoopMemSet(MemSetInst *MSI, const SCEV *BECount);
Andrew Trick328b2232011-03-14 16:48:10 +0000137
Chandler Carruthbad690e2015-08-12 23:06:37 +0000138 bool processLoopStridedStore(Value *DestPtr, unsigned StoreSize,
139 unsigned StoreAlignment, Value *SplatValue,
140 Instruction *TheStore, const SCEVAddRecExpr *Ev,
141 const SCEV *BECount);
142 bool processLoopStoreOfLoopLoad(StoreInst *SI, unsigned StoreSize,
143 const SCEVAddRecExpr *StoreEv,
144 const SCEVAddRecExpr *LoadEv,
145 const SCEV *BECount);
Shuxin Yang95de7c32012-12-09 03:12:46 +0000146
Chandler Carruthbad690e2015-08-12 23:06:37 +0000147 /// This transformation requires natural loop information & requires that
148 /// loop preheaders be inserted into the CFG.
149 ///
150 void getAnalysisUsage(AnalysisUsage &AU) const override {
151 AU.addRequired<LoopInfoWrapperPass>();
152 AU.addPreserved<LoopInfoWrapperPass>();
153 AU.addRequiredID(LoopSimplifyID);
154 AU.addPreservedID(LoopSimplifyID);
155 AU.addRequiredID(LCSSAID);
156 AU.addPreservedID(LCSSAID);
157 AU.addRequired<AliasAnalysis>();
158 AU.addPreserved<AliasAnalysis>();
159 AU.addRequired<ScalarEvolution>();
160 AU.addPreserved<ScalarEvolution>();
161 AU.addPreserved<DominatorTreeWrapperPass>();
162 AU.addRequired<DominatorTreeWrapperPass>();
163 AU.addRequired<TargetLibraryInfoWrapperPass>();
164 AU.addRequired<TargetTransformInfoWrapperPass>();
165 }
Shuxin Yang95de7c32012-12-09 03:12:46 +0000166
Chandler Carruthbad690e2015-08-12 23:06:37 +0000167 DominatorTree *getDominatorTree() {
168 return DT ? DT
169 : (DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree());
170 }
Shuxin Yang95de7c32012-12-09 03:12:46 +0000171
Chandler Carruthbad690e2015-08-12 23:06:37 +0000172 ScalarEvolution *getScalarEvolution() {
173 return SE ? SE : (SE = &getAnalysis<ScalarEvolution>());
174 }
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000175
Chandler Carruthbad690e2015-08-12 23:06:37 +0000176 TargetLibraryInfo *getTargetLibraryInfo() {
177 if (!TLI)
178 TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Shuxin Yang95de7c32012-12-09 03:12:46 +0000179
Chandler Carruthbad690e2015-08-12 23:06:37 +0000180 return TLI;
181 }
Shuxin Yang95de7c32012-12-09 03:12:46 +0000182
Chandler Carruthbad690e2015-08-12 23:06:37 +0000183 const TargetTransformInfo *getTargetTransformInfo() {
184 return TTI ? TTI
185 : (TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(
186 *CurLoop->getHeader()->getParent()));
187 }
Shuxin Yang95de7c32012-12-09 03:12:46 +0000188
Chandler Carruthbad690e2015-08-12 23:06:37 +0000189 Loop *getLoop() const { return CurLoop; }
190
191private:
192 bool runOnNoncountableLoop();
193 bool runOnCountableLoop();
194};
195
196} // End anonymous namespace.
Chris Lattner81ae3f22010-12-26 19:39:38 +0000197
198char LoopIdiomRecognize::ID = 0;
199INITIALIZE_PASS_BEGIN(LoopIdiomRecognize, "loop-idiom", "Recognize loop idioms",
200 false, false)
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000201INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
Chandler Carruth73523022014-01-13 13:07:17 +0000202INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Chris Lattner81ae3f22010-12-26 19:39:38 +0000203INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
204INITIALIZE_PASS_DEPENDENCY(LCSSA)
205INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000206INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
Chris Lattnercb18bfa2010-12-27 18:39:08 +0000207INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
Chandler Carruth705b1852015-01-31 03:43:40 +0000208INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
Chris Lattner81ae3f22010-12-26 19:39:38 +0000209INITIALIZE_PASS_END(LoopIdiomRecognize, "loop-idiom", "Recognize loop idioms",
210 false, false)
211
212Pass *llvm::createLoopIdiomPass() { return new LoopIdiomRecognize(); }
213
Chris Lattnerc4ca7ab2011-05-22 17:39:56 +0000214/// deleteDeadInstruction - Delete this instruction. Before we do, go through
Chris Lattnerb9fe6852010-12-27 00:03:23 +0000215/// and zero out all the operands of this instruction. If any of them become
216/// dead, delete them and the computation tree that feeds them.
217///
Benjamin Kramerf094d772015-02-07 21:37:08 +0000218static void deleteDeadInstruction(Instruction *I,
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000219 const TargetLibraryInfo *TLI) {
Benjamin Kramerf094d772015-02-07 21:37:08 +0000220 SmallVector<Value *, 16> Operands(I->value_op_begin(), I->value_op_end());
221 I->replaceAllUsesWith(UndefValue::get(I->getType()));
222 I->eraseFromParent();
223 for (Value *Op : Operands)
224 RecursivelyDeleteTriviallyDeadInstructions(Op, TLI);
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000225}
226
Shuxin Yang95de7c32012-12-09 03:12:46 +0000227//===----------------------------------------------------------------------===//
228//
Shuxin Yang95de7c32012-12-09 03:12:46 +0000229// Implementation of NclPopcountRecognize
230//
231//===----------------------------------------------------------------------===//
232
Chandler Carruthbad690e2015-08-12 23:06:37 +0000233NclPopcountRecognize::NclPopcountRecognize(LoopIdiomRecognize &TheLIR)
234 : LIR(TheLIR), CurLoop(TheLIR.getLoop()), PreCondBB(nullptr) {}
Shuxin Yang95de7c32012-12-09 03:12:46 +0000235
236bool NclPopcountRecognize::preliminaryScreen() {
Chandler Carruth6fe147f2013-01-05 10:00:09 +0000237 const TargetTransformInfo *TTI = LIR.getTargetTransformInfo();
Chandler Carruth50a36cd2013-01-07 03:16:03 +0000238 if (TTI->getPopcntSupport(32) != TargetTransformInfo::PSK_FastHardware)
Shuxin Yang95de7c32012-12-09 03:12:46 +0000239 return false;
240
Robert Wilhelm2788d3e2013-09-28 13:42:22 +0000241 // Counting population are usually conducted by few arithmetic instructions.
Shuxin Yang95de7c32012-12-09 03:12:46 +0000242 // Such instructions can be easilly "absorbed" by vacant slots in a
243 // non-compact loop. Therefore, recognizing popcount idiom only makes sense
244 // in a compact loop.
245
246 // Give up if the loop has multiple blocks or multiple backedges.
247 if (CurLoop->getNumBackEdges() != 1 || CurLoop->getNumBlocks() != 1)
248 return false;
249
250 BasicBlock *LoopBody = *(CurLoop->block_begin());
251 if (LoopBody->size() >= 20) {
252 // The loop is too big, bail out.
253 return false;
254 }
255
Chandler Carruthbe158b12015-08-12 23:55:56 +0000256 // It should have a preheader containing nothing but an unconditional branch.
257 BasicBlock *PH = CurLoop->getLoopPreheader();
258 if (!PH)
259 return false;
260 if (&PH->front() != PH->getTerminator())
261 return false;
262 auto *EntryBI = dyn_cast<BranchInst>(PH->getTerminator());
263 if (!EntryBI || EntryBI->isConditional())
Shuxin Yang95de7c32012-12-09 03:12:46 +0000264 return false;
265
266 // It should have a precondition block where the generated popcount instrinsic
Chandler Carruthbe158b12015-08-12 23:55:56 +0000267 // function can be inserted.
268 PreCondBB = PH->getSinglePredecessor();
Shuxin Yang95de7c32012-12-09 03:12:46 +0000269 if (!PreCondBB)
270 return false;
Chandler Carruthbe158b12015-08-12 23:55:56 +0000271 auto *PreCondBI = dyn_cast<BranchInst>(PreCondBB->getTerminator());
272 if (!PreCondBI || PreCondBI->isUnconditional())
273 return false;
Matt Arsenaultfb183232013-07-22 18:59:58 +0000274
Shuxin Yang95de7c32012-12-09 03:12:46 +0000275 return true;
276}
277
Jim Grosbach708f80f2014-04-29 22:41:58 +0000278Value *NclPopcountRecognize::matchCondition(BranchInst *Br,
279 BasicBlock *LoopEntry) const {
Shuxin Yang95de7c32012-12-09 03:12:46 +0000280 if (!Br || !Br->isConditional())
Craig Topperf40110f2014-04-25 05:29:35 +0000281 return nullptr;
Shuxin Yang95de7c32012-12-09 03:12:46 +0000282
283 ICmpInst *Cond = dyn_cast<ICmpInst>(Br->getCondition());
284 if (!Cond)
Craig Topperf40110f2014-04-25 05:29:35 +0000285 return nullptr;
Shuxin Yang95de7c32012-12-09 03:12:46 +0000286
287 ConstantInt *CmpZero = dyn_cast<ConstantInt>(Cond->getOperand(1));
288 if (!CmpZero || !CmpZero->isZero())
Craig Topperf40110f2014-04-25 05:29:35 +0000289 return nullptr;
Shuxin Yang95de7c32012-12-09 03:12:46 +0000290
291 ICmpInst::Predicate Pred = Cond->getPredicate();
292 if ((Pred == ICmpInst::ICMP_NE && Br->getSuccessor(0) == LoopEntry) ||
293 (Pred == ICmpInst::ICMP_EQ && Br->getSuccessor(1) == LoopEntry))
294 return Cond->getOperand(0);
295
Craig Topperf40110f2014-04-25 05:29:35 +0000296 return nullptr;
Shuxin Yang95de7c32012-12-09 03:12:46 +0000297}
298
Chandler Carruthbad690e2015-08-12 23:06:37 +0000299bool NclPopcountRecognize::detectIdiom(Instruction *&CntInst, PHINode *&CntPhi,
Shuxin Yang95de7c32012-12-09 03:12:46 +0000300 Value *&Var) const {
301 // Following code tries to detect this idiom:
302 //
303 // if (x0 != 0)
304 // goto loop-exit // the precondition of the loop
305 // cnt0 = init-val;
306 // do {
307 // x1 = phi (x0, x2);
308 // cnt1 = phi(cnt0, cnt2);
309 //
310 // cnt2 = cnt1 + 1;
311 // ...
312 // x2 = x1 & (x1 - 1);
313 // ...
314 // } while(x != 0);
315 //
316 // loop-exit:
317 //
318
319 // step 1: Check to see if the look-back branch match this pattern:
320 // "if (a!=0) goto loop-entry".
321 BasicBlock *LoopEntry;
322 Instruction *DefX2, *CountInst;
323 Value *VarX1, *VarX0;
324 PHINode *PhiX, *CountPhi;
325
Craig Topperf40110f2014-04-25 05:29:35 +0000326 DefX2 = CountInst = nullptr;
327 VarX1 = VarX0 = nullptr;
328 PhiX = CountPhi = nullptr;
Shuxin Yang95de7c32012-12-09 03:12:46 +0000329 LoopEntry = *(CurLoop->block_begin());
330
331 // step 1: Check if the loop-back branch is in desirable form.
332 {
Chandler Carruthbe158b12015-08-12 23:55:56 +0000333 if (Value *T = matchCondition(
334 dyn_cast<BranchInst>(LoopEntry->getTerminator()), LoopEntry))
Shuxin Yang95de7c32012-12-09 03:12:46 +0000335 DefX2 = dyn_cast<Instruction>(T);
336 else
337 return false;
338 }
339
340 // step 2: detect instructions corresponding to "x2 = x1 & (x1 - 1)"
341 {
Shuxin Yangc5c730b2013-01-10 23:32:01 +0000342 if (!DefX2 || DefX2->getOpcode() != Instruction::And)
Shuxin Yang95de7c32012-12-09 03:12:46 +0000343 return false;
344
345 BinaryOperator *SubOneOp;
346
347 if ((SubOneOp = dyn_cast<BinaryOperator>(DefX2->getOperand(0))))
348 VarX1 = DefX2->getOperand(1);
349 else {
350 VarX1 = DefX2->getOperand(0);
351 SubOneOp = dyn_cast<BinaryOperator>(DefX2->getOperand(1));
352 }
353 if (!SubOneOp)
354 return false;
355
356 Instruction *SubInst = cast<Instruction>(SubOneOp);
357 ConstantInt *Dec = dyn_cast<ConstantInt>(SubInst->getOperand(1));
358 if (!Dec ||
359 !((SubInst->getOpcode() == Instruction::Sub && Dec->isOne()) ||
Chandler Carruthbad690e2015-08-12 23:06:37 +0000360 (SubInst->getOpcode() == Instruction::Add &&
361 Dec->isAllOnesValue()))) {
Shuxin Yang95de7c32012-12-09 03:12:46 +0000362 return false;
363 }
364 }
365
366 // step 3: Check the recurrence of variable X
367 {
368 PhiX = dyn_cast<PHINode>(VarX1);
369 if (!PhiX ||
370 (PhiX->getOperand(0) != DefX2 && PhiX->getOperand(1) != DefX2)) {
371 return false;
372 }
373 }
374
375 // step 4: Find the instruction which count the population: cnt2 = cnt1 + 1
376 {
Craig Topperf40110f2014-04-25 05:29:35 +0000377 CountInst = nullptr;
Shuxin Yang95de7c32012-12-09 03:12:46 +0000378 for (BasicBlock::iterator Iter = LoopEntry->getFirstNonPHI(),
Chandler Carruthbad690e2015-08-12 23:06:37 +0000379 IterE = LoopEntry->end();
380 Iter != IterE; Iter++) {
Shuxin Yang95de7c32012-12-09 03:12:46 +0000381 Instruction *Inst = Iter;
382 if (Inst->getOpcode() != Instruction::Add)
383 continue;
384
385 ConstantInt *Inc = dyn_cast<ConstantInt>(Inst->getOperand(1));
386 if (!Inc || !Inc->isOne())
387 continue;
388
389 PHINode *Phi = dyn_cast<PHINode>(Inst->getOperand(0));
390 if (!Phi || Phi->getParent() != LoopEntry)
391 continue;
392
393 // Check if the result of the instruction is live of the loop.
394 bool LiveOutLoop = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000395 for (User *U : Inst->users()) {
396 if ((cast<Instruction>(U))->getParent() != LoopEntry) {
Chandler Carruthbad690e2015-08-12 23:06:37 +0000397 LiveOutLoop = true;
398 break;
Shuxin Yang95de7c32012-12-09 03:12:46 +0000399 }
400 }
401
402 if (LiveOutLoop) {
403 CountInst = Inst;
404 CountPhi = Phi;
405 break;
406 }
407 }
408
409 if (!CountInst)
410 return false;
411 }
412
413 // step 5: check if the precondition is in this form:
414 // "if (x != 0) goto loop-head ; else goto somewhere-we-don't-care;"
415 {
Chandler Carruthbe158b12015-08-12 23:55:56 +0000416 auto *PreCondBr = dyn_cast<BranchInst>(PreCondBB->getTerminator());
Chandler Carruthbad690e2015-08-12 23:06:37 +0000417 Value *T = matchCondition(PreCondBr, CurLoop->getLoopPreheader());
Shuxin Yang95de7c32012-12-09 03:12:46 +0000418 if (T != PhiX->getOperand(0) && T != PhiX->getOperand(1))
419 return false;
420
421 CntInst = CountInst;
422 CntPhi = CountPhi;
423 Var = T;
424 }
425
426 return true;
427}
428
Chandler Carruthbad690e2015-08-12 23:06:37 +0000429void NclPopcountRecognize::transform(Instruction *CntInst, PHINode *CntPhi,
430 Value *Var) {
Shuxin Yang95de7c32012-12-09 03:12:46 +0000431
432 ScalarEvolution *SE = LIR.getScalarEvolution();
433 TargetLibraryInfo *TLI = LIR.getTargetLibraryInfo();
434 BasicBlock *PreHead = CurLoop->getLoopPreheader();
Chandler Carruthbe158b12015-08-12 23:55:56 +0000435 auto *PreCondBr = dyn_cast<BranchInst>(PreCondBB->getTerminator());
Shuxin Yang95de7c32012-12-09 03:12:46 +0000436 const DebugLoc DL = CntInst->getDebugLoc();
437
438 // Assuming before transformation, the loop is following:
439 // if (x) // the precondition
440 // do { cnt++; x &= x - 1; } while(x);
Matt Arsenaultfb183232013-07-22 18:59:58 +0000441
Shuxin Yang95de7c32012-12-09 03:12:46 +0000442 // Step 1: Insert the ctpop instruction at the end of the precondition block
443 IRBuilderTy Builder(PreCondBr);
444 Value *PopCnt, *PopCntZext, *NewCount, *TripCnt;
445 {
446 PopCnt = createPopcntIntrinsic(Builder, Var, DL);
447 NewCount = PopCntZext =
Chandler Carruthbad690e2015-08-12 23:06:37 +0000448 Builder.CreateZExtOrTrunc(PopCnt, cast<IntegerType>(CntPhi->getType()));
Shuxin Yang95de7c32012-12-09 03:12:46 +0000449
450 if (NewCount != PopCnt)
451 (cast<Instruction>(NewCount))->setDebugLoc(DL);
452
453 // TripCnt is exactly the number of iterations the loop has
454 TripCnt = NewCount;
455
Alp Tokercb402912014-01-24 17:20:08 +0000456 // If the population counter's initial value is not zero, insert Add Inst.
Shuxin Yang95de7c32012-12-09 03:12:46 +0000457 Value *CntInitVal = CntPhi->getIncomingValueForBlock(PreHead);
458 ConstantInt *InitConst = dyn_cast<ConstantInt>(CntInitVal);
459 if (!InitConst || !InitConst->isZero()) {
460 NewCount = Builder.CreateAdd(NewCount, CntInitVal);
461 (cast<Instruction>(NewCount))->setDebugLoc(DL);
462 }
463 }
464
465 // Step 2: Replace the precondition from "if(x == 0) goto loop-exit" to
466 // "if(NewCount == 0) loop-exit". Withtout this change, the intrinsic
467 // function would be partial dead code, and downstream passes will drag
468 // it back from the precondition block to the preheader.
469 {
470 ICmpInst *PreCond = cast<ICmpInst>(PreCondBr->getCondition());
471
472 Value *Opnd0 = PopCntZext;
473 Value *Opnd1 = ConstantInt::get(PopCntZext->getType(), 0);
474 if (PreCond->getOperand(0) != Var)
475 std::swap(Opnd0, Opnd1);
476
Chandler Carruthbad690e2015-08-12 23:06:37 +0000477 ICmpInst *NewPreCond = cast<ICmpInst>(
478 Builder.CreateICmp(PreCond->getPredicate(), Opnd0, Opnd1));
Pete Cooper90d95ed2015-07-13 21:25:33 +0000479 PreCondBr->setCondition(NewPreCond);
Shuxin Yang95de7c32012-12-09 03:12:46 +0000480
Benjamin Kramerf094d772015-02-07 21:37:08 +0000481 RecursivelyDeleteTriviallyDeadInstructions(PreCond, TLI);
Shuxin Yang95de7c32012-12-09 03:12:46 +0000482 }
483
484 // Step 3: Note that the population count is exactly the trip count of the
485 // loop in question, which enble us to to convert the loop from noncountable
486 // loop into a countable one. The benefit is twofold:
487 //
488 // - If the loop only counts population, the entire loop become dead after
489 // the transformation. It is lots easier to prove a countable loop dead
490 // than to prove a noncountable one. (In some C dialects, a infite loop
491 // isn't dead even if it computes nothing useful. In general, DCE needs
492 // to prove a noncountable loop finite before safely delete it.)
493 //
494 // - If the loop also performs something else, it remains alive.
495 // Since it is transformed to countable form, it can be aggressively
496 // optimized by some optimizations which are in general not applicable
497 // to a noncountable loop.
498 //
499 // After this step, this loop (conceptually) would look like following:
500 // newcnt = __builtin_ctpop(x);
501 // t = newcnt;
502 // if (x)
503 // do { cnt++; x &= x-1; t--) } while (t > 0);
504 BasicBlock *Body = *(CurLoop->block_begin());
505 {
Chandler Carruthbe158b12015-08-12 23:55:56 +0000506 auto *LbBr = dyn_cast<BranchInst>(Body->getTerminator());
Shuxin Yang95de7c32012-12-09 03:12:46 +0000507 ICmpInst *LbCond = cast<ICmpInst>(LbBr->getCondition());
508 Type *Ty = TripCnt->getType();
509
510 PHINode *TcPhi = PHINode::Create(Ty, 2, "tcphi", Body->begin());
511
512 Builder.SetInsertPoint(LbCond);
513 Value *Opnd1 = cast<Value>(TcPhi);
514 Value *Opnd2 = cast<Value>(ConstantInt::get(Ty, 1));
Chandler Carruthbad690e2015-08-12 23:06:37 +0000515 Instruction *TcDec = cast<Instruction>(
516 Builder.CreateSub(Opnd1, Opnd2, "tcdec", false, true));
Shuxin Yang95de7c32012-12-09 03:12:46 +0000517
518 TcPhi->addIncoming(TripCnt, PreHead);
519 TcPhi->addIncoming(TcDec, Body);
520
Chandler Carruthbad690e2015-08-12 23:06:37 +0000521 CmpInst::Predicate Pred =
522 (LbBr->getSuccessor(0) == Body) ? CmpInst::ICMP_UGT : CmpInst::ICMP_SLE;
Shuxin Yang95de7c32012-12-09 03:12:46 +0000523 LbCond->setPredicate(Pred);
524 LbCond->setOperand(0, TcDec);
525 LbCond->setOperand(1, cast<Value>(ConstantInt::get(Ty, 0)));
526 }
527
528 // Step 4: All the references to the original population counter outside
529 // the loop are replaced with the NewCount -- the value returned from
530 // __builtin_ctpop().
Benjamin Kramerf094d772015-02-07 21:37:08 +0000531 CntInst->replaceUsesOutsideBlock(NewCount, Body);
Shuxin Yang95de7c32012-12-09 03:12:46 +0000532
533 // step 5: Forget the "non-computable" trip-count SCEV associated with the
534 // loop. The loop would otherwise not be deleted even if it becomes empty.
535 SE->forgetLoop(CurLoop);
536}
537
Matt Arsenaultfb183232013-07-22 18:59:58 +0000538CallInst *NclPopcountRecognize::createPopcntIntrinsic(IRBuilderTy &IRBuilder,
Shuxin Yang95de7c32012-12-09 03:12:46 +0000539 Value *Val, DebugLoc DL) {
Chandler Carruthbad690e2015-08-12 23:06:37 +0000540 Value *Ops[] = {Val};
541 Type *Tys[] = {Val->getType()};
Shuxin Yang95de7c32012-12-09 03:12:46 +0000542
543 Module *M = (*(CurLoop->block_begin()))->getParent()->getParent();
544 Value *Func = Intrinsic::getDeclaration(M, Intrinsic::ctpop, Tys);
545 CallInst *CI = IRBuilder.CreateCall(Func, Ops);
546 CI->setDebugLoc(DL);
547
548 return CI;
549}
550
551/// recognize - detect population count idiom in a non-countable loop. If
552/// detected, transform the relevant code to popcount intrinsic function
553/// call, and return true; otherwise, return false.
554bool NclPopcountRecognize::recognize() {
555
Chandler Carruth6fe147f2013-01-05 10:00:09 +0000556 if (!LIR.getTargetTransformInfo())
Shuxin Yang95de7c32012-12-09 03:12:46 +0000557 return false;
558
559 LIR.getScalarEvolution();
560
561 if (!preliminaryScreen())
562 return false;
563
564 Instruction *CntInst;
565 PHINode *CntPhi;
566 Value *Val;
567 if (!detectIdiom(CntInst, CntPhi, Val))
568 return false;
569
570 transform(CntInst, CntPhi, Val);
571 return true;
572}
573
574//===----------------------------------------------------------------------===//
575//
576// Implementation of LoopIdiomRecognize
577//
578//===----------------------------------------------------------------------===//
579
580bool LoopIdiomRecognize::runOnCountableLoop() {
581 const SCEV *BECount = SE->getBackedgeTakenCount(CurLoop);
Davide Italiano8ed04462015-05-11 21:02:34 +0000582 assert(!isa<SCEVCouldNotCompute>(BECount) &&
Chandler Carruthbad690e2015-08-12 23:06:37 +0000583 "runOnCountableLoop() called on a loop without a predictable"
584 "backedge-taken count");
Shuxin Yang95de7c32012-12-09 03:12:46 +0000585
586 // If this loop executes exactly one time, then it should be peeled, not
587 // optimized by this pass.
588 if (const SCEVConstant *BECst = dyn_cast<SCEVConstant>(BECount))
589 if (BECst->getValue()->getValue() == 0)
590 return false;
591
Matt Arsenaultfb183232013-07-22 18:59:58 +0000592 // set DT
Shuxin Yang98c844f2013-01-02 18:26:31 +0000593 (void)getDominatorTree();
Shuxin Yang95de7c32012-12-09 03:12:46 +0000594
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000595 LoopInfo &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000596 TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Shuxin Yang95de7c32012-12-09 03:12:46 +0000597
Matt Arsenaultfb183232013-07-22 18:59:58 +0000598 // set TLI
Shuxin Yang98c844f2013-01-02 18:26:31 +0000599 (void)getTargetLibraryInfo();
Shuxin Yang95de7c32012-12-09 03:12:46 +0000600
Chandler Carruthbad690e2015-08-12 23:06:37 +0000601 SmallVector<BasicBlock *, 8> ExitBlocks;
Shuxin Yang95de7c32012-12-09 03:12:46 +0000602 CurLoop->getUniqueExitBlocks(ExitBlocks);
603
604 DEBUG(dbgs() << "loop-idiom Scanning: F["
Chandler Carruthbad690e2015-08-12 23:06:37 +0000605 << CurLoop->getHeader()->getParent()->getName() << "] Loop %"
606 << CurLoop->getHeader()->getName() << "\n");
Shuxin Yang95de7c32012-12-09 03:12:46 +0000607
608 bool MadeChange = false;
609 // Scan all the blocks in the loop that are not in subloops.
Davide Italiano95a77e82015-05-14 21:52:12 +0000610 for (auto *BB : CurLoop->getBlocks()) {
Shuxin Yang95de7c32012-12-09 03:12:46 +0000611 // Ignore blocks in subloops.
Davide Italiano80625af2015-05-13 19:51:21 +0000612 if (LI.getLoopFor(BB) != CurLoop)
Shuxin Yang95de7c32012-12-09 03:12:46 +0000613 continue;
614
Davide Italiano80625af2015-05-13 19:51:21 +0000615 MadeChange |= runOnLoopBlock(BB, BECount, ExitBlocks);
Shuxin Yang95de7c32012-12-09 03:12:46 +0000616 }
617 return MadeChange;
618}
619
620bool LoopIdiomRecognize::runOnNoncountableLoop() {
621 NclPopcountRecognize Popcount(*this);
622 if (Popcount.recognize())
623 return true;
624
625 return false;
626}
627
Chris Lattner81ae3f22010-12-26 19:39:38 +0000628bool LoopIdiomRecognize::runOnLoop(Loop *L, LPPassManager &LPM) {
Paul Robinsonaf4e64d2014-02-06 00:07:05 +0000629 if (skipOptnoneFunction(L))
630 return false;
631
Chris Lattner7c5f9c32010-12-26 20:45:45 +0000632 CurLoop = L;
Andrew Trick328b2232011-03-14 16:48:10 +0000633
Benjamin Kramereba9aca2012-09-21 17:27:23 +0000634 // If the loop could not be converted to canonical form, it must have an
635 // indirectbr in it, just give up.
636 if (!L->getLoopPreheader())
637 return false;
638
Nadav Rotem465834c2012-07-24 10:51:42 +0000639 // Disable loop idiom recognition if the function's name is a common idiom.
Chad Rosiera7ff5432011-07-15 18:25:04 +0000640 StringRef Name = L->getHeader()->getParent()->getName();
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000641 if (Name == "memset" || Name == "memcpy")
Chad Rosiera7ff5432011-07-15 18:25:04 +0000642 return false;
643
Chris Lattner7c5f9c32010-12-26 20:45:45 +0000644 SE = &getAnalysis<ScalarEvolution>();
Shuxin Yang95de7c32012-12-09 03:12:46 +0000645 if (SE->hasLoopInvariantBackedgeTakenCount(L))
646 return runOnCountableLoop();
647 return runOnNoncountableLoop();
Chris Lattner8455b6e2011-01-02 19:01:03 +0000648}
649
650/// runOnLoopBlock - Process the specified block, which lives in a counted loop
651/// with the specified backedge count. This block is known to be in the current
652/// loop and not in any subloops.
Chandler Carruthbad690e2015-08-12 23:06:37 +0000653bool LoopIdiomRecognize::runOnLoopBlock(
654 BasicBlock *BB, const SCEV *BECount,
655 SmallVectorImpl<BasicBlock *> &ExitBlocks) {
Chris Lattner8455b6e2011-01-02 19:01:03 +0000656 // We can only promote stores in this block if they are unconditionally
657 // executed in the loop. For a block to be unconditionally executed, it has
658 // to dominate all the exit blocks of the loop. Verify this now.
659 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
660 if (!DT->dominates(BB, ExitBlocks[i]))
661 return false;
Andrew Trick328b2232011-03-14 16:48:10 +0000662
Chris Lattner7c5f9c32010-12-26 20:45:45 +0000663 bool MadeChange = false;
Chandler Carruthbad690e2015-08-12 23:06:37 +0000664 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
Chris Lattnera62b01d2011-01-04 07:27:30 +0000665 Instruction *Inst = I++;
666 // Look for store instructions, which may be optimized to memset/memcpy.
Chandler Carruthbad690e2015-08-12 23:06:37 +0000667 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
Chris Lattnera62b01d2011-01-04 07:27:30 +0000668 WeakVH InstPtr(I);
Chandler Carruthbad690e2015-08-12 23:06:37 +0000669 if (!processLoopStore(SI, BECount))
670 continue;
Chris Lattnera62b01d2011-01-04 07:27:30 +0000671 MadeChange = true;
Andrew Trick328b2232011-03-14 16:48:10 +0000672
Chris Lattnera62b01d2011-01-04 07:27:30 +0000673 // If processing the store invalidated our iterator, start over from the
Chris Lattner86438102011-01-04 07:46:33 +0000674 // top of the block.
Craig Topperf40110f2014-04-25 05:29:35 +0000675 if (!InstPtr)
Chris Lattnera62b01d2011-01-04 07:27:30 +0000676 I = BB->begin();
677 continue;
678 }
Andrew Trick328b2232011-03-14 16:48:10 +0000679
Chris Lattner86438102011-01-04 07:46:33 +0000680 // Look for memset instructions, which may be optimized to a larger memset.
Chandler Carruthbad690e2015-08-12 23:06:37 +0000681 if (MemSetInst *MSI = dyn_cast<MemSetInst>(Inst)) {
Chris Lattner86438102011-01-04 07:46:33 +0000682 WeakVH InstPtr(I);
Chandler Carruthbad690e2015-08-12 23:06:37 +0000683 if (!processLoopMemSet(MSI, BECount))
684 continue;
Chris Lattner86438102011-01-04 07:46:33 +0000685 MadeChange = true;
Andrew Trick328b2232011-03-14 16:48:10 +0000686
Chris Lattner86438102011-01-04 07:46:33 +0000687 // If processing the memset invalidated our iterator, start over from the
688 // top of the block.
Craig Topperf40110f2014-04-25 05:29:35 +0000689 if (!InstPtr)
Chris Lattner86438102011-01-04 07:46:33 +0000690 I = BB->begin();
691 continue;
692 }
Chris Lattner7c5f9c32010-12-26 20:45:45 +0000693 }
Andrew Trick328b2232011-03-14 16:48:10 +0000694
Chris Lattner7c5f9c32010-12-26 20:45:45 +0000695 return MadeChange;
Chris Lattner81ae3f22010-12-26 19:39:38 +0000696}
697
Chris Lattner86438102011-01-04 07:46:33 +0000698/// processLoopStore - See if this store can be promoted to a memset or memcpy.
Chris Lattner7c5f9c32010-12-26 20:45:45 +0000699bool LoopIdiomRecognize::processLoopStore(StoreInst *SI, const SCEV *BECount) {
Chandler Carruthbad690e2015-08-12 23:06:37 +0000700 if (!SI->isSimple())
701 return false;
Chris Lattner86438102011-01-04 07:46:33 +0000702
Chris Lattner7c5f9c32010-12-26 20:45:45 +0000703 Value *StoredVal = SI->getValueOperand();
Chris Lattner29e14ed2010-12-26 23:42:51 +0000704 Value *StorePtr = SI->getPointerOperand();
Andrew Trick328b2232011-03-14 16:48:10 +0000705
Chris Lattner65a699d2010-12-28 18:53:48 +0000706 // Reject stores that are so large that they overflow an unsigned.
Mehdi Amini46a43552015-03-04 18:43:29 +0000707 auto &DL = CurLoop->getHeader()->getModule()->getDataLayout();
708 uint64_t SizeInBits = DL.getTypeSizeInBits(StoredVal->getType());
Chris Lattner65a699d2010-12-28 18:53:48 +0000709 if ((SizeInBits & 7) || (SizeInBits >> 32) != 0)
Chris Lattner7c5f9c32010-12-26 20:45:45 +0000710 return false;
Andrew Trick328b2232011-03-14 16:48:10 +0000711
Chris Lattner7c5f9c32010-12-26 20:45:45 +0000712 // See if the pointer expression is an AddRec like {base,+,1} on the current
713 // loop, which indicates a strided store. If we have something else, it's a
714 // random store we can't handle.
Chris Lattner85b6d812011-01-02 03:37:56 +0000715 const SCEVAddRecExpr *StoreEv =
Chandler Carruthbad690e2015-08-12 23:06:37 +0000716 dyn_cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr));
Craig Topperf40110f2014-04-25 05:29:35 +0000717 if (!StoreEv || StoreEv->getLoop() != CurLoop || !StoreEv->isAffine())
Chris Lattner7c5f9c32010-12-26 20:45:45 +0000718 return false;
719
720 // Check to see if the stride matches the size of the store. If so, then we
721 // know that every byte is touched in the loop.
Andrew Trick328b2232011-03-14 16:48:10 +0000722 unsigned StoreSize = (unsigned)SizeInBits >> 3;
Chris Lattner85b6d812011-01-02 03:37:56 +0000723 const SCEVConstant *Stride = dyn_cast<SCEVConstant>(StoreEv->getOperand(1));
Andrew Trick328b2232011-03-14 16:48:10 +0000724
Craig Topperf40110f2014-04-25 05:29:35 +0000725 if (!Stride || StoreSize != Stride->getValue()->getValue()) {
Chris Lattnerbc661d62011-02-21 02:08:54 +0000726 // TODO: Could also handle negative stride here someday, that will require
727 // the validity check in mayLoopAccessLocation to be updated though.
728 // Enable this to print exact negative strides.
Chris Lattner2333ac22011-02-21 17:02:55 +0000729 if (0 && Stride && StoreSize == -Stride->getValue()->getValue()) {
Chris Lattnerbc661d62011-02-21 02:08:54 +0000730 dbgs() << "NEGATIVE STRIDE: " << *SI << "\n";
731 dbgs() << "BB: " << *SI->getParent();
732 }
Andrew Trick328b2232011-03-14 16:48:10 +0000733
Chris Lattner7c5f9c32010-12-26 20:45:45 +0000734 return false;
Chris Lattnerbc661d62011-02-21 02:08:54 +0000735 }
Chris Lattner0f4a6402011-02-19 19:31:39 +0000736
737 // See if we can optimize just this store in isolation.
738 if (processLoopStridedStore(StorePtr, StoreSize, SI->getAlignment(),
739 StoredVal, SI, StoreEv, BECount))
740 return true;
Chris Lattner29e14ed2010-12-26 23:42:51 +0000741
Chris Lattner85b6d812011-01-02 03:37:56 +0000742 // If the stored value is a strided load in the same loop with the same stride
743 // this this may be transformable into a memcpy. This kicks in for stuff like
744 // for (i) A[i] = B[i];
745 if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) {
746 const SCEVAddRecExpr *LoadEv =
Chandler Carruthbad690e2015-08-12 23:06:37 +0000747 dyn_cast<SCEVAddRecExpr>(SE->getSCEV(LI->getOperand(0)));
Chris Lattner85b6d812011-01-02 03:37:56 +0000748 if (LoadEv && LoadEv->getLoop() == CurLoop && LoadEv->isAffine() &&
Eli Friedman7c5dc122011-09-12 20:23:13 +0000749 StoreEv->getOperand(1) == LoadEv->getOperand(1) && LI->isSimple())
Chris Lattner85b6d812011-01-02 03:37:56 +0000750 if (processLoopStoreOfLoopLoad(SI, StoreSize, StoreEv, LoadEv, BECount))
751 return true;
752 }
Chandler Carruthbad690e2015-08-12 23:06:37 +0000753 // errs() << "UNHANDLED strided store: " << *StoreEv << " - " << *SI << "\n";
Chris Lattner7c5f9c32010-12-26 20:45:45 +0000754
Chris Lattner81ae3f22010-12-26 19:39:38 +0000755 return false;
756}
757
Chris Lattner86438102011-01-04 07:46:33 +0000758/// processLoopMemSet - See if this memset can be promoted to a large memset.
Chandler Carruthbad690e2015-08-12 23:06:37 +0000759bool LoopIdiomRecognize::processLoopMemSet(MemSetInst *MSI,
760 const SCEV *BECount) {
Chris Lattner86438102011-01-04 07:46:33 +0000761 // We can only handle non-volatile memsets with a constant size.
Chandler Carruthbad690e2015-08-12 23:06:37 +0000762 if (MSI->isVolatile() || !isa<ConstantInt>(MSI->getLength()))
763 return false;
Chris Lattner86438102011-01-04 07:46:33 +0000764
Chris Lattnere6b261f2011-02-18 22:22:15 +0000765 // If we're not allowed to hack on memset, we fail.
766 if (!TLI->has(LibFunc::memset))
767 return false;
Andrew Trick328b2232011-03-14 16:48:10 +0000768
Chris Lattner86438102011-01-04 07:46:33 +0000769 Value *Pointer = MSI->getDest();
Andrew Trick328b2232011-03-14 16:48:10 +0000770
Chris Lattner86438102011-01-04 07:46:33 +0000771 // See if the pointer expression is an AddRec like {base,+,1} on the current
772 // loop, which indicates a strided store. If we have something else, it's a
773 // random store we can't handle.
774 const SCEVAddRecExpr *Ev = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Pointer));
Craig Topperf40110f2014-04-25 05:29:35 +0000775 if (!Ev || Ev->getLoop() != CurLoop || !Ev->isAffine())
Chris Lattner86438102011-01-04 07:46:33 +0000776 return false;
777
778 // Reject memsets that are so large that they overflow an unsigned.
779 uint64_t SizeInBytes = cast<ConstantInt>(MSI->getLength())->getZExtValue();
780 if ((SizeInBytes >> 32) != 0)
781 return false;
Andrew Trick328b2232011-03-14 16:48:10 +0000782
Chris Lattner86438102011-01-04 07:46:33 +0000783 // Check to see if the stride matches the size of the memset. If so, then we
784 // know that every byte is touched in the loop.
785 const SCEVConstant *Stride = dyn_cast<SCEVConstant>(Ev->getOperand(1));
Andrew Trick328b2232011-03-14 16:48:10 +0000786
Chris Lattner86438102011-01-04 07:46:33 +0000787 // TODO: Could also handle negative stride here someday, that will require the
788 // validity check in mayLoopAccessLocation to be updated though.
Craig Topperf40110f2014-04-25 05:29:35 +0000789 if (!Stride || MSI->getLength() != Stride->getValue())
Chris Lattner86438102011-01-04 07:46:33 +0000790 return false;
Andrew Trick328b2232011-03-14 16:48:10 +0000791
Chris Lattner0f4a6402011-02-19 19:31:39 +0000792 return processLoopStridedStore(Pointer, (unsigned)SizeInBytes,
Chandler Carruthbad690e2015-08-12 23:06:37 +0000793 MSI->getAlignment(), MSI->getValue(), MSI, Ev,
794 BECount);
Chris Lattner86438102011-01-04 07:46:33 +0000795}
796
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000797/// mayLoopAccessLocation - Return true if the specified loop might access the
798/// specified pointer location, which is a loop-strided access. The 'Access'
799/// argument specifies what the verboten forms of access are (read or write).
Chandler Carruth194f59c2015-07-22 23:15:57 +0000800static bool mayLoopAccessLocation(Value *Ptr, ModRefInfo Access, Loop *L,
801 const SCEV *BECount, unsigned StoreSize,
802 AliasAnalysis &AA,
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000803 Instruction *IgnoredStore) {
804 // Get the location that may be stored across the loop. Since the access is
805 // strided positively through memory, we say that the modified location starts
806 // at the pointer and has infinite size.
Chandler Carruthecbd1682015-06-17 07:21:38 +0000807 uint64_t AccessSize = MemoryLocation::UnknownSize;
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000808
809 // If the loop iterates a fixed number of times, we can refine the access size
810 // to be exactly the size of the memset, which is (BECount+1)*StoreSize
811 if (const SCEVConstant *BECst = dyn_cast<SCEVConstant>(BECount))
Chandler Carruthbad690e2015-08-12 23:06:37 +0000812 AccessSize = (BECst->getValue()->getZExtValue() + 1) * StoreSize;
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000813
814 // TODO: For this to be really effective, we have to dive into the pointer
815 // operand in the store. Store to &A[i] of 100 will always return may alias
816 // with store of &A[100], we need to StoreLoc to be "A" with size of 100,
817 // which will then no-alias a store to &A[100].
Chandler Carruthac80dc72015-06-17 07:18:54 +0000818 MemoryLocation StoreLoc(Ptr, AccessSize);
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000819
820 for (Loop::block_iterator BI = L->block_begin(), E = L->block_end(); BI != E;
821 ++BI)
822 for (BasicBlock::iterator I = (*BI)->begin(), E = (*BI)->end(); I != E; ++I)
Chandler Carruthbad690e2015-08-12 23:06:37 +0000823 if (&*I != IgnoredStore && (AA.getModRefInfo(I, StoreLoc) & Access))
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000824 return true;
825
826 return false;
827}
828
Chris Lattner0f4a6402011-02-19 19:31:39 +0000829/// getMemSetPatternValue - If a strided store of the specified value is safe to
830/// turn into a memset_pattern16, return a ConstantArray of 16 bytes that should
831/// be passed in. Otherwise, return null.
832///
833/// Note that we don't ever attempt to use memset_pattern8 or 4, because these
834/// just replicate their input array and then pass on to memset_pattern16.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000835static Constant *getMemSetPatternValue(Value *V, const DataLayout &DL) {
Chris Lattner0f4a6402011-02-19 19:31:39 +0000836 // If the value isn't a constant, we can't promote it to being in a constant
837 // array. We could theoretically do a store to an alloca or something, but
838 // that doesn't seem worthwhile.
839 Constant *C = dyn_cast<Constant>(V);
Chandler Carruthbad690e2015-08-12 23:06:37 +0000840 if (!C)
841 return nullptr;
Andrew Trick328b2232011-03-14 16:48:10 +0000842
Chris Lattner0f4a6402011-02-19 19:31:39 +0000843 // Only handle simple values that are a power of two bytes in size.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000844 uint64_t Size = DL.getTypeSizeInBits(V->getType());
Chandler Carruthbad690e2015-08-12 23:06:37 +0000845 if (Size == 0 || (Size & 7) || (Size & (Size - 1)))
Craig Topperf40110f2014-04-25 05:29:35 +0000846 return nullptr;
Andrew Trick328b2232011-03-14 16:48:10 +0000847
Chris Lattner72a35fb2011-02-19 19:56:44 +0000848 // Don't care enough about darwin/ppc to implement this.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000849 if (DL.isBigEndian())
Craig Topperf40110f2014-04-25 05:29:35 +0000850 return nullptr;
Chris Lattner0f4a6402011-02-19 19:31:39 +0000851
852 // Convert to size in bytes.
853 Size /= 8;
Chris Lattner0f4a6402011-02-19 19:31:39 +0000854
Chris Lattner0f4a6402011-02-19 19:31:39 +0000855 // TODO: If CI is larger than 16-bytes, we can try slicing it in half to see
Chris Lattner72a35fb2011-02-19 19:56:44 +0000856 // if the top and bottom are the same (e.g. for vectors and large integers).
Chandler Carruthbad690e2015-08-12 23:06:37 +0000857 if (Size > 16)
858 return nullptr;
Andrew Trick328b2232011-03-14 16:48:10 +0000859
Chris Lattner72a35fb2011-02-19 19:56:44 +0000860 // If the constant is exactly 16 bytes, just use it.
Chandler Carruthbad690e2015-08-12 23:06:37 +0000861 if (Size == 16)
862 return C;
Chris Lattner0f4a6402011-02-19 19:31:39 +0000863
Chris Lattner72a35fb2011-02-19 19:56:44 +0000864 // Otherwise, we'll use an array of the constants.
Chandler Carruthbad690e2015-08-12 23:06:37 +0000865 unsigned ArraySize = 16 / Size;
Chris Lattner72a35fb2011-02-19 19:56:44 +0000866 ArrayType *AT = ArrayType::get(V->getType(), ArraySize);
Chandler Carruthbad690e2015-08-12 23:06:37 +0000867 return ConstantArray::get(AT, std::vector<Constant *>(ArraySize, C));
Chris Lattner0f4a6402011-02-19 19:31:39 +0000868}
869
Chris Lattner0f4a6402011-02-19 19:31:39 +0000870/// processLoopStridedStore - We see a strided store of some value. If we can
871/// transform this into a memset or memset_pattern in the loop preheader, do so.
Chandler Carruthbad690e2015-08-12 23:06:37 +0000872bool LoopIdiomRecognize::processLoopStridedStore(
873 Value *DestPtr, unsigned StoreSize, unsigned StoreAlignment,
874 Value *StoredVal, Instruction *TheStore, const SCEVAddRecExpr *Ev,
875 const SCEV *BECount) {
Andrew Trick328b2232011-03-14 16:48:10 +0000876
Chris Lattner0f4a6402011-02-19 19:31:39 +0000877 // If the stored value is a byte-wise value (like i32 -1), then it may be
878 // turned into a memset of i8 -1, assuming that all the consecutive bytes
879 // are stored. A store of i32 0x01020304 can never be turned into a memset,
880 // but it can be turned into memset_pattern if the target supports it.
881 Value *SplatValue = isBytewiseValue(StoredVal);
Craig Topperf40110f2014-04-25 05:29:35 +0000882 Constant *PatternValue = nullptr;
Mehdi Amini46a43552015-03-04 18:43:29 +0000883 auto &DL = CurLoop->getHeader()->getModule()->getDataLayout();
Matt Arsenault009faed2013-09-11 05:09:42 +0000884 unsigned DestAS = DestPtr->getType()->getPointerAddressSpace();
885
Chris Lattner0f4a6402011-02-19 19:31:39 +0000886 // If we're allowed to form a memset, and the stored value would be acceptable
887 // for memset, use it.
888 if (SplatValue && TLI->has(LibFunc::memset) &&
889 // Verify that the stored value is loop invariant. If not, we can't
890 // promote the memset.
891 CurLoop->isLoopInvariant(SplatValue)) {
892 // Keep and use SplatValue.
Craig Topperf40110f2014-04-25 05:29:35 +0000893 PatternValue = nullptr;
Mehdi Amini46a43552015-03-04 18:43:29 +0000894 } else if (DestAS == 0 && TLI->has(LibFunc::memset_pattern16) &&
895 (PatternValue = getMemSetPatternValue(StoredVal, DL))) {
Matt Arsenault009faed2013-09-11 05:09:42 +0000896 // Don't create memset_pattern16s with address spaces.
Chris Lattner0f4a6402011-02-19 19:31:39 +0000897 // It looks like we can use PatternValue!
Craig Topperf40110f2014-04-25 05:29:35 +0000898 SplatValue = nullptr;
Chris Lattner0f4a6402011-02-19 19:31:39 +0000899 } else {
900 // Otherwise, this isn't an idiom we can transform. For example, we can't
Eli Friedmana93ab132011-09-13 00:44:16 +0000901 // do anything with a 3-byte store.
Chris Lattnera3514442011-01-01 20:12:04 +0000902 return false;
Chris Lattner0f4a6402011-02-19 19:31:39 +0000903 }
Andrew Trick328b2232011-03-14 16:48:10 +0000904
Chris Lattnerc4ca7ab2011-05-22 17:39:56 +0000905 // The trip count of the loop and the base pointer of the addrec SCEV is
906 // guaranteed to be loop invariant, which means that it should dominate the
907 // header. This allows us to insert code for it in the preheader.
908 BasicBlock *Preheader = CurLoop->getLoopPreheader();
909 IRBuilder<> Builder(Preheader->getTerminator());
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000910 SCEVExpander Expander(*SE, DL, "loop-idiom");
Andrew Trick60ab3ef2011-06-28 05:04:16 +0000911
Matt Arsenault009faed2013-09-11 05:09:42 +0000912 Type *DestInt8PtrTy = Builder.getInt8PtrTy(DestAS);
913
Chris Lattner29e14ed2010-12-26 23:42:51 +0000914 // Okay, we have a strided store "p[i]" of a splattable value. We can turn
Benjamin Kramerf77f2242012-10-21 19:31:16 +0000915 // this into a memset in the loop preheader now if we want. However, this
916 // would be unsafe to do if there is anything else in the loop that may read
Chandler Carruth7ec50852012-11-01 08:07:29 +0000917 // or write to the aliased location. Check for any overlap by generating the
918 // base pointer and checking the region.
Chandler Carruthbad690e2015-08-12 23:06:37 +0000919 Value *BasePtr = Expander.expandCodeFor(Ev->getStart(), DestInt8PtrTy,
920 Preheader->getTerminator());
Andrew Trick328b2232011-03-14 16:48:10 +0000921
Chandler Carruth194f59c2015-07-22 23:15:57 +0000922 if (mayLoopAccessLocation(BasePtr, MRI_ModRef, CurLoop, BECount, StoreSize,
923 getAnalysis<AliasAnalysis>(), TheStore)) {
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000924 Expander.clear();
925 // If we generated new code for the base pointer, clean up.
Benjamin Kramerf094d772015-02-07 21:37:08 +0000926 RecursivelyDeleteTriviallyDeadInstructions(BasePtr, TLI);
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000927 return false;
928 }
929
Chris Lattnerc4ca7ab2011-05-22 17:39:56 +0000930 // Okay, everything looks good, insert the memset.
931
Chris Lattner29e14ed2010-12-26 23:42:51 +0000932 // The # stored bytes is (BECount+1)*Size. Expand the trip count out to
933 // pointer size if it isn't already.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000934 Type *IntPtr = Builder.getIntPtrTy(DL, DestAS);
Chris Lattner0ba473c2011-01-04 00:06:55 +0000935 BECount = SE->getTruncateOrZeroExtend(BECount, IntPtr);
Andrew Trick328b2232011-03-14 16:48:10 +0000936
Chandler Carruthbad690e2015-08-12 23:06:37 +0000937 const SCEV *NumBytesS =
938 SE->getAddExpr(BECount, SE->getConstant(IntPtr, 1), SCEV::FlagNUW);
Matt Arsenault5df49bd2013-09-11 05:09:35 +0000939 if (StoreSize != 1) {
Chris Lattner29e14ed2010-12-26 23:42:51 +0000940 NumBytesS = SE->getMulExpr(NumBytesS, SE->getConstant(IntPtr, StoreSize),
Andrew Trick8b55b732011-03-14 16:50:06 +0000941 SCEV::FlagNUW);
Matt Arsenault5df49bd2013-09-11 05:09:35 +0000942 }
Andrew Trick328b2232011-03-14 16:48:10 +0000943
944 Value *NumBytes =
Chandler Carruthbad690e2015-08-12 23:06:37 +0000945 Expander.expandCodeFor(NumBytesS, IntPtr, Preheader->getTerminator());
Andrew Trick328b2232011-03-14 16:48:10 +0000946
Devang Pateld00c6282011-03-07 22:43:45 +0000947 CallInst *NewCall;
Matt Arsenault5df49bd2013-09-11 05:09:35 +0000948 if (SplatValue) {
Chandler Carruthbad690e2015-08-12 23:06:37 +0000949 NewCall =
950 Builder.CreateMemSet(BasePtr, SplatValue, NumBytes, StoreAlignment);
Matt Arsenault5df49bd2013-09-11 05:09:35 +0000951 } else {
Matt Arsenault009faed2013-09-11 05:09:42 +0000952 // Everything is emitted in default address space
953 Type *Int8PtrTy = DestInt8PtrTy;
954
Chris Lattner0f4a6402011-02-19 19:31:39 +0000955 Module *M = TheStore->getParent()->getParent()->getParent();
Chandler Carruthbad690e2015-08-12 23:06:37 +0000956 Value *MSP =
957 M->getOrInsertFunction("memset_pattern16", Builder.getVoidTy(),
958 Int8PtrTy, Int8PtrTy, IntPtr, (void *)nullptr);
Andrew Trick328b2232011-03-14 16:48:10 +0000959
Chris Lattner0f4a6402011-02-19 19:31:39 +0000960 // Otherwise we should form a memset_pattern16. PatternValue is known to be
961 // an constant array of 16-bytes. Plop the value into a mergable global.
962 GlobalVariable *GV = new GlobalVariable(*M, PatternValue->getType(), true,
Benjamin Kramer838752d2015-03-03 00:17:09 +0000963 GlobalValue::PrivateLinkage,
Chris Lattner0f4a6402011-02-19 19:31:39 +0000964 PatternValue, ".memset_pattern");
965 GV->setUnnamedAddr(true); // Ok to merge these.
966 GV->setAlignment(16);
Matt Arsenault009faed2013-09-11 05:09:42 +0000967 Value *PatternPtr = ConstantExpr::getBitCast(GV, Int8PtrTy);
David Blaikieff6409d2015-05-18 22:13:54 +0000968 NewCall = Builder.CreateCall(MSP, {BasePtr, PatternPtr, NumBytes});
Chris Lattner0f4a6402011-02-19 19:31:39 +0000969 }
Andrew Trick328b2232011-03-14 16:48:10 +0000970
Chris Lattner29e14ed2010-12-26 23:42:51 +0000971 DEBUG(dbgs() << " Formed memset: " << *NewCall << "\n"
Chris Lattner86438102011-01-04 07:46:33 +0000972 << " from store to: " << *Ev << " at: " << *TheStore << "\n");
Devang Pateld00c6282011-03-07 22:43:45 +0000973 NewCall->setDebugLoc(TheStore->getDebugLoc());
Andrew Trick328b2232011-03-14 16:48:10 +0000974
Chris Lattnerb9fe6852010-12-27 00:03:23 +0000975 // Okay, the memset has been formed. Zap the original store and anything that
976 // feeds into it.
Benjamin Kramerf094d772015-02-07 21:37:08 +0000977 deleteDeadInstruction(TheStore, TLI);
Chris Lattner12f91be2011-01-02 07:36:44 +0000978 ++NumMemSet;
Chris Lattner29e14ed2010-12-26 23:42:51 +0000979 return true;
980}
981
Chris Lattner85b6d812011-01-02 03:37:56 +0000982/// processLoopStoreOfLoopLoad - We see a strided store whose value is a
983/// same-strided load.
Chandler Carruthbad690e2015-08-12 23:06:37 +0000984bool LoopIdiomRecognize::processLoopStoreOfLoopLoad(
985 StoreInst *SI, unsigned StoreSize, const SCEVAddRecExpr *StoreEv,
986 const SCEVAddRecExpr *LoadEv, const SCEV *BECount) {
Chris Lattnere6b261f2011-02-18 22:22:15 +0000987 // If we're not allowed to form memcpy, we fail.
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000988 if (!TLI->has(LibFunc::memcpy))
Chris Lattnere6b261f2011-02-18 22:22:15 +0000989 return false;
Andrew Trick328b2232011-03-14 16:48:10 +0000990
Chris Lattner85b6d812011-01-02 03:37:56 +0000991 LoadInst *LI = cast<LoadInst>(SI->getValueOperand());
Andrew Trick328b2232011-03-14 16:48:10 +0000992
Chris Lattnerc4ca7ab2011-05-22 17:39:56 +0000993 // The trip count of the loop and the base pointer of the addrec SCEV is
994 // guaranteed to be loop invariant, which means that it should dominate the
995 // header. This allows us to insert code for it in the preheader.
996 BasicBlock *Preheader = CurLoop->getLoopPreheader();
997 IRBuilder<> Builder(Preheader->getTerminator());
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000998 const DataLayout &DL = Preheader->getModule()->getDataLayout();
999 SCEVExpander Expander(*SE, DL, "loop-idiom");
Andrew Trick60ab3ef2011-06-28 05:04:16 +00001000
Chris Lattner85b6d812011-01-02 03:37:56 +00001001 // Okay, we have a strided store "p[i]" of a loaded value. We can turn
Chandler Carruth099f5cb02012-11-02 08:33:25 +00001002 // this into a memcpy in the loop preheader now if we want. However, this
1003 // would be unsafe to do if there is anything else in the loop that may read
1004 // or write the memory region we're storing to. This includes the load that
1005 // feeds the stores. Check for an alias by generating the base address and
1006 // checking everything.
Chandler Carruthbad690e2015-08-12 23:06:37 +00001007 Value *StoreBasePtr = Expander.expandCodeFor(
1008 StoreEv->getStart(), Builder.getInt8PtrTy(SI->getPointerAddressSpace()),
1009 Preheader->getTerminator());
Chandler Carruth099f5cb02012-11-02 08:33:25 +00001010
Chandler Carruth194f59c2015-07-22 23:15:57 +00001011 if (mayLoopAccessLocation(StoreBasePtr, MRI_ModRef, CurLoop, BECount,
1012 StoreSize, getAnalysis<AliasAnalysis>(), SI)) {
Chandler Carruth099f5cb02012-11-02 08:33:25 +00001013 Expander.clear();
1014 // If we generated new code for the base pointer, clean up.
Benjamin Kramerf094d772015-02-07 21:37:08 +00001015 RecursivelyDeleteTriviallyDeadInstructions(StoreBasePtr, TLI);
Chandler Carruth099f5cb02012-11-02 08:33:25 +00001016 return false;
1017 }
1018
1019 // For a memcpy, we have to make sure that the input array is not being
1020 // mutated by the loop.
Chandler Carruthbad690e2015-08-12 23:06:37 +00001021 Value *LoadBasePtr = Expander.expandCodeFor(
1022 LoadEv->getStart(), Builder.getInt8PtrTy(LI->getPointerAddressSpace()),
1023 Preheader->getTerminator());
Chris Lattnerc4ca7ab2011-05-22 17:39:56 +00001024
Chandler Carruth194f59c2015-07-22 23:15:57 +00001025 if (mayLoopAccessLocation(LoadBasePtr, MRI_Mod, CurLoop, BECount, StoreSize,
1026 getAnalysis<AliasAnalysis>(), SI)) {
Chandler Carruth099f5cb02012-11-02 08:33:25 +00001027 Expander.clear();
1028 // If we generated new code for the base pointer, clean up.
Benjamin Kramerf094d772015-02-07 21:37:08 +00001029 RecursivelyDeleteTriviallyDeadInstructions(LoadBasePtr, TLI);
1030 RecursivelyDeleteTriviallyDeadInstructions(StoreBasePtr, TLI);
Chandler Carruth099f5cb02012-11-02 08:33:25 +00001031 return false;
1032 }
1033
Chris Lattnerc4ca7ab2011-05-22 17:39:56 +00001034 // Okay, everything is safe, we can transform this!
Andrew Trick60ab3ef2011-06-28 05:04:16 +00001035
Chris Lattner85b6d812011-01-02 03:37:56 +00001036 // The # stored bytes is (BECount+1)*Size. Expand the trip count out to
1037 // pointer size if it isn't already.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001038 Type *IntPtrTy = Builder.getIntPtrTy(DL, SI->getPointerAddressSpace());
Matt Arsenault009faed2013-09-11 05:09:42 +00001039 BECount = SE->getTruncateOrZeroExtend(BECount, IntPtrTy);
Andrew Trick328b2232011-03-14 16:48:10 +00001040
Chandler Carruthbad690e2015-08-12 23:06:37 +00001041 const SCEV *NumBytesS =
1042 SE->getAddExpr(BECount, SE->getConstant(IntPtrTy, 1), SCEV::FlagNUW);
Chris Lattner85b6d812011-01-02 03:37:56 +00001043 if (StoreSize != 1)
Matt Arsenault009faed2013-09-11 05:09:42 +00001044 NumBytesS = SE->getMulExpr(NumBytesS, SE->getConstant(IntPtrTy, StoreSize),
Andrew Trick8b55b732011-03-14 16:50:06 +00001045 SCEV::FlagNUW);
Andrew Trick328b2232011-03-14 16:48:10 +00001046
Chris Lattner85b6d812011-01-02 03:37:56 +00001047 Value *NumBytes =
Chandler Carruthbad690e2015-08-12 23:06:37 +00001048 Expander.expandCodeFor(NumBytesS, IntPtrTy, Preheader->getTerminator());
Andrew Trick328b2232011-03-14 16:48:10 +00001049
Chandler Carruth099f5cb02012-11-02 08:33:25 +00001050 CallInst *NewCall =
Chandler Carruthbad690e2015-08-12 23:06:37 +00001051 Builder.CreateMemCpy(StoreBasePtr, LoadBasePtr, NumBytes,
1052 std::min(SI->getAlignment(), LI->getAlignment()));
Devang Patel0daa07e2011-05-04 21:37:05 +00001053 NewCall->setDebugLoc(SI->getDebugLoc());
Andrew Trick328b2232011-03-14 16:48:10 +00001054
Chandler Carruth099f5cb02012-11-02 08:33:25 +00001055 DEBUG(dbgs() << " Formed memcpy: " << *NewCall << "\n"
Chris Lattner85b6d812011-01-02 03:37:56 +00001056 << " from load ptr=" << *LoadEv << " at: " << *LI << "\n"
1057 << " from store ptr=" << *StoreEv << " at: " << *SI << "\n");
Andrew Trick60ab3ef2011-06-28 05:04:16 +00001058
Chris Lattner85b6d812011-01-02 03:37:56 +00001059 // Okay, the memset has been formed. Zap the original store and anything that
1060 // feeds into it.
Benjamin Kramerf094d772015-02-07 21:37:08 +00001061 deleteDeadInstruction(SI, TLI);
Chandler Carruth099f5cb02012-11-02 08:33:25 +00001062 ++NumMemCpy;
Chris Lattner85b6d812011-01-02 03:37:56 +00001063 return true;
1064}