[PM] Separate the TargetLibraryInfo object from the immutable pass.
[oota-llvm.git] / lib / Transforms / Scalar / LoopIdiomRecognize.cpp
1 //===-- LoopIdiomRecognize.cpp - Loop idiom recognition -------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass implements an idiom recognizer that transforms simple loops into a
11 // non-loop form.  In cases that this kicks in, it can be a significant
12 // performance win.
13 //
14 //===----------------------------------------------------------------------===//
15 //
16 // TODO List:
17 //
18 // Future loop memory idioms to recognize:
19 //   memcmp, memmove, strlen, etc.
20 // 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; }
33 //
34 // 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 //
39 // This could recognize common matrix multiplies and dot product idioms and
40 // replace them with calls to BLAS (if linked in??).
41 //
42 //===----------------------------------------------------------------------===//
43
44 #include "llvm/Transforms/Scalar.h"
45 #include "llvm/ADT/Statistic.h"
46 #include "llvm/Analysis/AliasAnalysis.h"
47 #include "llvm/Analysis/LoopPass.h"
48 #include "llvm/Analysis/ScalarEvolutionExpander.h"
49 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
50 #include "llvm/Analysis/TargetTransformInfo.h"
51 #include "llvm/Analysis/ValueTracking.h"
52 #include "llvm/IR/DataLayout.h"
53 #include "llvm/IR/Dominators.h"
54 #include "llvm/IR/IRBuilder.h"
55 #include "llvm/IR/IntrinsicInst.h"
56 #include "llvm/IR/Module.h"
57 #include "llvm/Support/Debug.h"
58 #include "llvm/Support/raw_ostream.h"
59 #include "llvm/Analysis/TargetLibraryInfo.h"
60 #include "llvm/Transforms/Utils/Local.h"
61 using namespace llvm;
62
63 #define DEBUG_TYPE "loop-idiom"
64
65 STATISTIC(NumMemSet, "Number of memset's formed from loop stores");
66 STATISTIC(NumMemCpy, "Number of memcpy's formed from loop load+stores");
67
68 namespace {
69
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
83     /// Derive the precondition block (i.e the block that guards the loop
84     /// 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
110     /// 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,
112     /// the variable involved in the comparion is returned. This function will
113     /// be called to see if the precondition and postcondition of the loop
114     /// are in desirable form.
115     Value *matchCondition(BranchInst *Br, BasicBlock *NonZeroTarget) const;
116
117     /// Return true iff the idiom is detected in the loop. and 1) \p CntInst
118     /// is set to the instruction counting the population bit. 2) \p CntPhi
119     /// 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.
125     void transform(Instruction *CntInst, PHINode *CntPhi, Value *Var);
126
127     /// Create llvm.ctpop.* intrinsic function.
128     CallInst *createPopcntIntrinsic(IRBuilderTy &IRB, Value *Val, DebugLoc DL);
129   };
130
131   class LoopIdiomRecognize : public LoopPass {
132     Loop *CurLoop;
133     const DataLayout *DL;
134     DominatorTree *DT;
135     ScalarEvolution *SE;
136     TargetLibraryInfo *TLI;
137     const TargetTransformInfo *TTI;
138   public:
139     static char ID;
140     explicit LoopIdiomRecognize() : LoopPass(ID) {
141       initializeLoopIdiomRecognizePass(*PassRegistry::getPassRegistry());
142       DL = nullptr; DT = nullptr; SE = nullptr; TLI = nullptr; TTI = nullptr;
143     }
144
145     bool runOnLoop(Loop *L, LPPassManager &LPM) override;
146     bool runOnLoopBlock(BasicBlock *BB, const SCEV *BECount,
147                         SmallVectorImpl<BasicBlock*> &ExitBlocks);
148
149     bool processLoopStore(StoreInst *SI, const SCEV *BECount);
150     bool processLoopMemSet(MemSetInst *MSI, const SCEV *BECount);
151
152     bool processLoopStridedStore(Value *DestPtr, unsigned StoreSize,
153                                  unsigned StoreAlignment,
154                                  Value *SplatValue, Instruction *TheStore,
155                                  const SCEVAddRecExpr *Ev,
156                                  const SCEV *BECount);
157     bool processLoopStoreOfLoopLoad(StoreInst *SI, unsigned StoreSize,
158                                     const SCEVAddRecExpr *StoreEv,
159                                     const SCEVAddRecExpr *LoadEv,
160                                     const SCEV *BECount);
161
162     /// This transformation requires natural loop information & requires that
163     /// loop preheaders be inserted into the CFG.
164     ///
165     void getAnalysisUsage(AnalysisUsage &AU) const override {
166       AU.addRequired<LoopInfo>();
167       AU.addPreserved<LoopInfo>();
168       AU.addRequiredID(LoopSimplifyID);
169       AU.addPreservedID(LoopSimplifyID);
170       AU.addRequiredID(LCSSAID);
171       AU.addPreservedID(LCSSAID);
172       AU.addRequired<AliasAnalysis>();
173       AU.addPreserved<AliasAnalysis>();
174       AU.addRequired<ScalarEvolution>();
175       AU.addPreserved<ScalarEvolution>();
176       AU.addPreserved<DominatorTreeWrapperPass>();
177       AU.addRequired<DominatorTreeWrapperPass>();
178       AU.addRequired<TargetLibraryInfoWrapperPass>();
179       AU.addRequired<TargetTransformInfo>();
180     }
181
182     const DataLayout *getDataLayout() {
183       if (DL)
184         return DL;
185       DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
186       DL = DLP ? &DLP->getDataLayout() : nullptr;
187       return DL;
188     }
189
190     DominatorTree *getDominatorTree() {
191       return DT ? DT
192                 : (DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree());
193     }
194
195     ScalarEvolution *getScalarEvolution() {
196       return SE ? SE : (SE = &getAnalysis<ScalarEvolution>());
197     }
198
199     TargetLibraryInfo *getTargetLibraryInfo() {
200       if (!TLI)
201         TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
202
203       return TLI;
204     }
205
206     const TargetTransformInfo *getTargetTransformInfo() {
207       return TTI ? TTI : (TTI = &getAnalysis<TargetTransformInfo>());
208     }
209
210     Loop *getLoop() const { return CurLoop; }
211
212   private:
213     bool runOnNoncountableLoop();
214     bool runOnCountableLoop();
215   };
216 }
217
218 char LoopIdiomRecognize::ID = 0;
219 INITIALIZE_PASS_BEGIN(LoopIdiomRecognize, "loop-idiom", "Recognize loop idioms",
220                       false, false)
221 INITIALIZE_PASS_DEPENDENCY(LoopInfo)
222 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
223 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
224 INITIALIZE_PASS_DEPENDENCY(LCSSA)
225 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
226 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
227 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
228 INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
229 INITIALIZE_PASS_END(LoopIdiomRecognize, "loop-idiom", "Recognize loop idioms",
230                     false, false)
231
232 Pass *llvm::createLoopIdiomPass() { return new LoopIdiomRecognize(); }
233
234 /// deleteDeadInstruction - Delete this instruction.  Before we do, go through
235 /// and zero out all the operands of this instruction.  If any of them become
236 /// dead, delete them and the computation tree that feeds them.
237 ///
238 static void deleteDeadInstruction(Instruction *I, ScalarEvolution &SE,
239                                   const TargetLibraryInfo *TLI) {
240   SmallVector<Instruction*, 32> NowDeadInsts;
241
242   NowDeadInsts.push_back(I);
243
244   // Before we touch this instruction, remove it from SE!
245   do {
246     Instruction *DeadInst = NowDeadInsts.pop_back_val();
247
248     // This instruction is dead, zap it, in stages.  Start by removing it from
249     // SCEV.
250     SE.forgetValue(DeadInst);
251
252     for (unsigned op = 0, e = DeadInst->getNumOperands(); op != e; ++op) {
253       Value *Op = DeadInst->getOperand(op);
254       DeadInst->setOperand(op, nullptr);
255
256       // If this operand just became dead, add it to the NowDeadInsts list.
257       if (!Op->use_empty()) continue;
258
259       if (Instruction *OpI = dyn_cast<Instruction>(Op))
260         if (isInstructionTriviallyDead(OpI, TLI))
261           NowDeadInsts.push_back(OpI);
262     }
263
264     DeadInst->eraseFromParent();
265
266   } while (!NowDeadInsts.empty());
267 }
268
269 /// deleteIfDeadInstruction - If the specified value is a dead instruction,
270 /// delete it and any recursively used instructions.
271 static void deleteIfDeadInstruction(Value *V, ScalarEvolution &SE,
272                                     const TargetLibraryInfo *TLI) {
273   if (Instruction *I = dyn_cast<Instruction>(V))
274     if (isInstructionTriviallyDead(I, TLI))
275       deleteDeadInstruction(I, SE, TLI);
276 }
277
278 //===----------------------------------------------------------------------===//
279 //
280 //          Implementation of LIRUtil
281 //
282 //===----------------------------------------------------------------------===//
283
284 // This function will return true iff the given block contains nothing but goto.
285 // A typical usage of this function is to check if the preheader function is
286 // "almost" empty such that generated intrinsic functions can be moved across
287 // the preheader and be placed at the end of the precondition block without
288 // the concern of breaking data dependence.
289 bool LIRUtil::isAlmostEmpty(BasicBlock *BB) {
290   if (BranchInst *Br = getBranch(BB)) {
291     return Br->isUnconditional() && BB->size() == 1;
292   }
293   return false;
294 }
295
296 BasicBlock *LIRUtil::getPrecondBb(BasicBlock *PreHead) {
297   if (BasicBlock *BB = PreHead->getSinglePredecessor()) {
298     BranchInst *Br = getBranch(BB);
299     return Br && Br->isConditional() ? BB : nullptr;
300   }
301   return nullptr;
302 }
303
304 //===----------------------------------------------------------------------===//
305 //
306 //          Implementation of NclPopcountRecognize
307 //
308 //===----------------------------------------------------------------------===//
309
310 NclPopcountRecognize::NclPopcountRecognize(LoopIdiomRecognize &TheLIR):
311   LIR(TheLIR), CurLoop(TheLIR.getLoop()), PreCondBB(nullptr) {
312 }
313
314 bool NclPopcountRecognize::preliminaryScreen() {
315   const TargetTransformInfo *TTI = LIR.getTargetTransformInfo();
316   if (TTI->getPopcntSupport(32) != TargetTransformInfo::PSK_FastHardware)
317     return false;
318
319   // Counting population are usually conducted by few arithmetic instructions.
320   // Such instructions can be easilly "absorbed" by vacant slots in a
321   // non-compact loop. Therefore, recognizing popcount idiom only makes sense
322   // in a compact loop.
323
324   // Give up if the loop has multiple blocks or multiple backedges.
325   if (CurLoop->getNumBackEdges() != 1 || CurLoop->getNumBlocks() != 1)
326     return false;
327
328   BasicBlock *LoopBody = *(CurLoop->block_begin());
329   if (LoopBody->size() >= 20) {
330     // The loop is too big, bail out.
331     return false;
332   }
333
334   // It should have a preheader containing nothing but a goto instruction.
335   BasicBlock *PreHead = CurLoop->getLoopPreheader();
336   if (!PreHead || !LIRUtil::isAlmostEmpty(PreHead))
337     return false;
338
339   // It should have a precondition block where the generated popcount instrinsic
340   // function will be inserted.
341   PreCondBB = LIRUtil::getPrecondBb(PreHead);
342   if (!PreCondBB)
343     return false;
344
345   return true;
346 }
347
348 Value *NclPopcountRecognize::matchCondition(BranchInst *Br,
349                                             BasicBlock *LoopEntry) const {
350   if (!Br || !Br->isConditional())
351     return nullptr;
352
353   ICmpInst *Cond = dyn_cast<ICmpInst>(Br->getCondition());
354   if (!Cond)
355     return nullptr;
356
357   ConstantInt *CmpZero = dyn_cast<ConstantInt>(Cond->getOperand(1));
358   if (!CmpZero || !CmpZero->isZero())
359     return nullptr;
360
361   ICmpInst::Predicate Pred = Cond->getPredicate();
362   if ((Pred == ICmpInst::ICMP_NE && Br->getSuccessor(0) == LoopEntry) ||
363       (Pred == ICmpInst::ICMP_EQ && Br->getSuccessor(1) == LoopEntry))
364     return Cond->getOperand(0);
365
366   return nullptr;
367 }
368
369 bool NclPopcountRecognize::detectIdiom(Instruction *&CntInst,
370                                        PHINode *&CntPhi,
371                                        Value *&Var) const {
372   // Following code tries to detect this idiom:
373   //
374   //    if (x0 != 0)
375   //      goto loop-exit // the precondition of the loop
376   //    cnt0 = init-val;
377   //    do {
378   //       x1 = phi (x0, x2);
379   //       cnt1 = phi(cnt0, cnt2);
380   //
381   //       cnt2 = cnt1 + 1;
382   //        ...
383   //       x2 = x1 & (x1 - 1);
384   //        ...
385   //    } while(x != 0);
386   //
387   // loop-exit:
388   //
389
390   // step 1: Check to see if the look-back branch match this pattern:
391   //    "if (a!=0) goto loop-entry".
392   BasicBlock *LoopEntry;
393   Instruction *DefX2, *CountInst;
394   Value *VarX1, *VarX0;
395   PHINode *PhiX, *CountPhi;
396
397   DefX2 = CountInst = nullptr;
398   VarX1 = VarX0 = nullptr;
399   PhiX = CountPhi = nullptr;
400   LoopEntry = *(CurLoop->block_begin());
401
402   // step 1: Check if the loop-back branch is in desirable form.
403   {
404     if (Value *T = matchCondition (LIRUtil::getBranch(LoopEntry), LoopEntry))
405       DefX2 = dyn_cast<Instruction>(T);
406     else
407       return false;
408   }
409
410   // step 2: detect instructions corresponding to "x2 = x1 & (x1 - 1)"
411   {
412     if (!DefX2 || DefX2->getOpcode() != Instruction::And)
413       return false;
414
415     BinaryOperator *SubOneOp;
416
417     if ((SubOneOp = dyn_cast<BinaryOperator>(DefX2->getOperand(0))))
418       VarX1 = DefX2->getOperand(1);
419     else {
420       VarX1 = DefX2->getOperand(0);
421       SubOneOp = dyn_cast<BinaryOperator>(DefX2->getOperand(1));
422     }
423     if (!SubOneOp)
424       return false;
425
426     Instruction *SubInst = cast<Instruction>(SubOneOp);
427     ConstantInt *Dec = dyn_cast<ConstantInt>(SubInst->getOperand(1));
428     if (!Dec ||
429         !((SubInst->getOpcode() == Instruction::Sub && Dec->isOne()) ||
430           (SubInst->getOpcode() == Instruction::Add && Dec->isAllOnesValue()))) {
431       return false;
432     }
433   }
434
435   // step 3: Check the recurrence of variable X
436   {
437     PhiX = dyn_cast<PHINode>(VarX1);
438     if (!PhiX ||
439         (PhiX->getOperand(0) != DefX2 && PhiX->getOperand(1) != DefX2)) {
440       return false;
441     }
442   }
443
444   // step 4: Find the instruction which count the population: cnt2 = cnt1 + 1
445   {
446     CountInst = nullptr;
447     for (BasicBlock::iterator Iter = LoopEntry->getFirstNonPHI(),
448            IterE = LoopEntry->end(); Iter != IterE; Iter++) {
449       Instruction *Inst = Iter;
450       if (Inst->getOpcode() != Instruction::Add)
451         continue;
452
453       ConstantInt *Inc = dyn_cast<ConstantInt>(Inst->getOperand(1));
454       if (!Inc || !Inc->isOne())
455         continue;
456
457       PHINode *Phi = dyn_cast<PHINode>(Inst->getOperand(0));
458       if (!Phi || Phi->getParent() != LoopEntry)
459         continue;
460
461       // Check if the result of the instruction is live of the loop.
462       bool LiveOutLoop = false;
463       for (User *U : Inst->users()) {
464         if ((cast<Instruction>(U))->getParent() != LoopEntry) {
465           LiveOutLoop = true; break;
466         }
467       }
468
469       if (LiveOutLoop) {
470         CountInst = Inst;
471         CountPhi = Phi;
472         break;
473       }
474     }
475
476     if (!CountInst)
477       return false;
478   }
479
480   // step 5: check if the precondition is in this form:
481   //   "if (x != 0) goto loop-head ; else goto somewhere-we-don't-care;"
482   {
483     BranchInst *PreCondBr = LIRUtil::getBranch(PreCondBB);
484     Value *T = matchCondition (PreCondBr, CurLoop->getLoopPreheader());
485     if (T != PhiX->getOperand(0) && T != PhiX->getOperand(1))
486       return false;
487
488     CntInst = CountInst;
489     CntPhi = CountPhi;
490     Var = T;
491   }
492
493   return true;
494 }
495
496 void NclPopcountRecognize::transform(Instruction *CntInst,
497                                      PHINode *CntPhi, Value *Var) {
498
499   ScalarEvolution *SE = LIR.getScalarEvolution();
500   TargetLibraryInfo *TLI = LIR.getTargetLibraryInfo();
501   BasicBlock *PreHead = CurLoop->getLoopPreheader();
502   BranchInst *PreCondBr = LIRUtil::getBranch(PreCondBB);
503   const DebugLoc DL = CntInst->getDebugLoc();
504
505   // Assuming before transformation, the loop is following:
506   //  if (x) // the precondition
507   //     do { cnt++; x &= x - 1; } while(x);
508
509   // Step 1: Insert the ctpop instruction at the end of the precondition block
510   IRBuilderTy Builder(PreCondBr);
511   Value *PopCnt, *PopCntZext, *NewCount, *TripCnt;
512   {
513     PopCnt = createPopcntIntrinsic(Builder, Var, DL);
514     NewCount = PopCntZext =
515       Builder.CreateZExtOrTrunc(PopCnt, cast<IntegerType>(CntPhi->getType()));
516
517     if (NewCount != PopCnt)
518       (cast<Instruction>(NewCount))->setDebugLoc(DL);
519
520     // TripCnt is exactly the number of iterations the loop has
521     TripCnt = NewCount;
522
523     // If the population counter's initial value is not zero, insert Add Inst.
524     Value *CntInitVal = CntPhi->getIncomingValueForBlock(PreHead);
525     ConstantInt *InitConst = dyn_cast<ConstantInt>(CntInitVal);
526     if (!InitConst || !InitConst->isZero()) {
527       NewCount = Builder.CreateAdd(NewCount, CntInitVal);
528       (cast<Instruction>(NewCount))->setDebugLoc(DL);
529     }
530   }
531
532   // Step 2: Replace the precondition from "if(x == 0) goto loop-exit" to
533   //   "if(NewCount == 0) loop-exit". Withtout this change, the intrinsic
534   //   function would be partial dead code, and downstream passes will drag
535   //   it back from the precondition block to the preheader.
536   {
537     ICmpInst *PreCond = cast<ICmpInst>(PreCondBr->getCondition());
538
539     Value *Opnd0 = PopCntZext;
540     Value *Opnd1 = ConstantInt::get(PopCntZext->getType(), 0);
541     if (PreCond->getOperand(0) != Var)
542       std::swap(Opnd0, Opnd1);
543
544     ICmpInst *NewPreCond =
545       cast<ICmpInst>(Builder.CreateICmp(PreCond->getPredicate(), Opnd0, Opnd1));
546     PreCond->replaceAllUsesWith(NewPreCond);
547
548     deleteDeadInstruction(PreCond, *SE, TLI);
549   }
550
551   // Step 3: Note that the population count is exactly the trip count of the
552   // loop in question, which enble us to to convert the loop from noncountable
553   // loop into a countable one. The benefit is twofold:
554   //
555   //  - If the loop only counts population, the entire loop become dead after
556   //    the transformation. It is lots easier to prove a countable loop dead
557   //    than to prove a noncountable one. (In some C dialects, a infite loop
558   //    isn't dead even if it computes nothing useful. In general, DCE needs
559   //    to prove a noncountable loop finite before safely delete it.)
560   //
561   //  - If the loop also performs something else, it remains alive.
562   //    Since it is transformed to countable form, it can be aggressively
563   //    optimized by some optimizations which are in general not applicable
564   //    to a noncountable loop.
565   //
566   // After this step, this loop (conceptually) would look like following:
567   //   newcnt = __builtin_ctpop(x);
568   //   t = newcnt;
569   //   if (x)
570   //     do { cnt++; x &= x-1; t--) } while (t > 0);
571   BasicBlock *Body = *(CurLoop->block_begin());
572   {
573     BranchInst *LbBr = LIRUtil::getBranch(Body);
574     ICmpInst *LbCond = cast<ICmpInst>(LbBr->getCondition());
575     Type *Ty = TripCnt->getType();
576
577     PHINode *TcPhi = PHINode::Create(Ty, 2, "tcphi", Body->begin());
578
579     Builder.SetInsertPoint(LbCond);
580     Value *Opnd1 = cast<Value>(TcPhi);
581     Value *Opnd2 = cast<Value>(ConstantInt::get(Ty, 1));
582     Instruction *TcDec =
583       cast<Instruction>(Builder.CreateSub(Opnd1, Opnd2, "tcdec", false, true));
584
585     TcPhi->addIncoming(TripCnt, PreHead);
586     TcPhi->addIncoming(TcDec, Body);
587
588     CmpInst::Predicate Pred = (LbBr->getSuccessor(0) == Body) ?
589       CmpInst::ICMP_UGT : CmpInst::ICMP_SLE;
590     LbCond->setPredicate(Pred);
591     LbCond->setOperand(0, TcDec);
592     LbCond->setOperand(1, cast<Value>(ConstantInt::get(Ty, 0)));
593   }
594
595   // Step 4: All the references to the original population counter outside
596   //  the loop are replaced with the NewCount -- the value returned from
597   //  __builtin_ctpop().
598   {
599     SmallVector<Value *, 4> CntUses;
600     for (User *U : CntInst->users())
601       if (cast<Instruction>(U)->getParent() != Body)
602         CntUses.push_back(U);
603     for (unsigned Idx = 0; Idx < CntUses.size(); Idx++) {
604       (cast<Instruction>(CntUses[Idx]))->replaceUsesOfWith(CntInst, NewCount);
605     }
606   }
607
608   // step 5: Forget the "non-computable" trip-count SCEV associated with the
609   //   loop. The loop would otherwise not be deleted even if it becomes empty.
610   SE->forgetLoop(CurLoop);
611 }
612
613 CallInst *NclPopcountRecognize::createPopcntIntrinsic(IRBuilderTy &IRBuilder,
614                                                       Value *Val, DebugLoc DL) {
615   Value *Ops[] = { Val };
616   Type *Tys[] = { Val->getType() };
617
618   Module *M = (*(CurLoop->block_begin()))->getParent()->getParent();
619   Value *Func = Intrinsic::getDeclaration(M, Intrinsic::ctpop, Tys);
620   CallInst *CI = IRBuilder.CreateCall(Func, Ops);
621   CI->setDebugLoc(DL);
622
623   return CI;
624 }
625
626 /// recognize - detect population count idiom in a non-countable loop. If
627 ///   detected, transform the relevant code to popcount intrinsic function
628 ///   call, and return true; otherwise, return false.
629 bool NclPopcountRecognize::recognize() {
630
631   if (!LIR.getTargetTransformInfo())
632     return false;
633
634   LIR.getScalarEvolution();
635
636   if (!preliminaryScreen())
637     return false;
638
639   Instruction *CntInst;
640   PHINode *CntPhi;
641   Value *Val;
642   if (!detectIdiom(CntInst, CntPhi, Val))
643     return false;
644
645   transform(CntInst, CntPhi, Val);
646   return true;
647 }
648
649 //===----------------------------------------------------------------------===//
650 //
651 //          Implementation of LoopIdiomRecognize
652 //
653 //===----------------------------------------------------------------------===//
654
655 bool LoopIdiomRecognize::runOnCountableLoop() {
656   const SCEV *BECount = SE->getBackedgeTakenCount(CurLoop);
657   if (isa<SCEVCouldNotCompute>(BECount)) return false;
658
659   // If this loop executes exactly one time, then it should be peeled, not
660   // optimized by this pass.
661   if (const SCEVConstant *BECst = dyn_cast<SCEVConstant>(BECount))
662     if (BECst->getValue()->getValue() == 0)
663       return false;
664
665   // We require target data for now.
666   if (!getDataLayout())
667     return false;
668
669   // set DT
670   (void)getDominatorTree();
671
672   LoopInfo &LI = getAnalysis<LoopInfo>();
673   TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
674
675   // set TLI
676   (void)getTargetLibraryInfo();
677
678   SmallVector<BasicBlock*, 8> ExitBlocks;
679   CurLoop->getUniqueExitBlocks(ExitBlocks);
680
681   DEBUG(dbgs() << "loop-idiom Scanning: F["
682                << CurLoop->getHeader()->getParent()->getName()
683                << "] Loop %" << CurLoop->getHeader()->getName() << "\n");
684
685   bool MadeChange = false;
686   // Scan all the blocks in the loop that are not in subloops.
687   for (Loop::block_iterator BI = CurLoop->block_begin(),
688          E = CurLoop->block_end(); BI != E; ++BI) {
689     // Ignore blocks in subloops.
690     if (LI.getLoopFor(*BI) != CurLoop)
691       continue;
692
693     MadeChange |= runOnLoopBlock(*BI, BECount, ExitBlocks);
694   }
695   return MadeChange;
696 }
697
698 bool LoopIdiomRecognize::runOnNoncountableLoop() {
699   NclPopcountRecognize Popcount(*this);
700   if (Popcount.recognize())
701     return true;
702
703   return false;
704 }
705
706 bool LoopIdiomRecognize::runOnLoop(Loop *L, LPPassManager &LPM) {
707   if (skipOptnoneFunction(L))
708     return false;
709
710   CurLoop = L;
711
712   // If the loop could not be converted to canonical form, it must have an
713   // indirectbr in it, just give up.
714   if (!L->getLoopPreheader())
715     return false;
716
717   // Disable loop idiom recognition if the function's name is a common idiom.
718   StringRef Name = L->getHeader()->getParent()->getName();
719   if (Name == "memset" || Name == "memcpy")
720     return false;
721
722   SE = &getAnalysis<ScalarEvolution>();
723   if (SE->hasLoopInvariantBackedgeTakenCount(L))
724     return runOnCountableLoop();
725   return runOnNoncountableLoop();
726 }
727
728 /// runOnLoopBlock - Process the specified block, which lives in a counted loop
729 /// with the specified backedge count.  This block is known to be in the current
730 /// loop and not in any subloops.
731 bool LoopIdiomRecognize::runOnLoopBlock(BasicBlock *BB, const SCEV *BECount,
732                                      SmallVectorImpl<BasicBlock*> &ExitBlocks) {
733   // We can only promote stores in this block if they are unconditionally
734   // executed in the loop.  For a block to be unconditionally executed, it has
735   // to dominate all the exit blocks of the loop.  Verify this now.
736   for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
737     if (!DT->dominates(BB, ExitBlocks[i]))
738       return false;
739
740   bool MadeChange = false;
741   for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
742     Instruction *Inst = I++;
743     // Look for store instructions, which may be optimized to memset/memcpy.
744     if (StoreInst *SI = dyn_cast<StoreInst>(Inst))  {
745       WeakVH InstPtr(I);
746       if (!processLoopStore(SI, BECount)) continue;
747       MadeChange = true;
748
749       // If processing the store invalidated our iterator, start over from the
750       // top of the block.
751       if (!InstPtr)
752         I = BB->begin();
753       continue;
754     }
755
756     // Look for memset instructions, which may be optimized to a larger memset.
757     if (MemSetInst *MSI = dyn_cast<MemSetInst>(Inst))  {
758       WeakVH InstPtr(I);
759       if (!processLoopMemSet(MSI, BECount)) continue;
760       MadeChange = true;
761
762       // If processing the memset invalidated our iterator, start over from the
763       // top of the block.
764       if (!InstPtr)
765         I = BB->begin();
766       continue;
767     }
768   }
769
770   return MadeChange;
771 }
772
773
774 /// processLoopStore - See if this store can be promoted to a memset or memcpy.
775 bool LoopIdiomRecognize::processLoopStore(StoreInst *SI, const SCEV *BECount) {
776   if (!SI->isSimple()) return false;
777
778   Value *StoredVal = SI->getValueOperand();
779   Value *StorePtr = SI->getPointerOperand();
780
781   // Reject stores that are so large that they overflow an unsigned.
782   uint64_t SizeInBits = DL->getTypeSizeInBits(StoredVal->getType());
783   if ((SizeInBits & 7) || (SizeInBits >> 32) != 0)
784     return false;
785
786   // See if the pointer expression is an AddRec like {base,+,1} on the current
787   // loop, which indicates a strided store.  If we have something else, it's a
788   // random store we can't handle.
789   const SCEVAddRecExpr *StoreEv =
790     dyn_cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr));
791   if (!StoreEv || StoreEv->getLoop() != CurLoop || !StoreEv->isAffine())
792     return false;
793
794   // Check to see if the stride matches the size of the store.  If so, then we
795   // know that every byte is touched in the loop.
796   unsigned StoreSize = (unsigned)SizeInBits >> 3;
797   const SCEVConstant *Stride = dyn_cast<SCEVConstant>(StoreEv->getOperand(1));
798
799   if (!Stride || StoreSize != Stride->getValue()->getValue()) {
800     // TODO: Could also handle negative stride here someday, that will require
801     // the validity check in mayLoopAccessLocation to be updated though.
802     // Enable this to print exact negative strides.
803     if (0 && Stride && StoreSize == -Stride->getValue()->getValue()) {
804       dbgs() << "NEGATIVE STRIDE: " << *SI << "\n";
805       dbgs() << "BB: " << *SI->getParent();
806     }
807
808     return false;
809   }
810
811   // See if we can optimize just this store in isolation.
812   if (processLoopStridedStore(StorePtr, StoreSize, SI->getAlignment(),
813                               StoredVal, SI, StoreEv, BECount))
814     return true;
815
816   // If the stored value is a strided load in the same loop with the same stride
817   // this this may be transformable into a memcpy.  This kicks in for stuff like
818   //   for (i) A[i] = B[i];
819   if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) {
820     const SCEVAddRecExpr *LoadEv =
821       dyn_cast<SCEVAddRecExpr>(SE->getSCEV(LI->getOperand(0)));
822     if (LoadEv && LoadEv->getLoop() == CurLoop && LoadEv->isAffine() &&
823         StoreEv->getOperand(1) == LoadEv->getOperand(1) && LI->isSimple())
824       if (processLoopStoreOfLoopLoad(SI, StoreSize, StoreEv, LoadEv, BECount))
825         return true;
826   }
827   //errs() << "UNHANDLED strided store: " << *StoreEv << " - " << *SI << "\n";
828
829   return false;
830 }
831
832 /// processLoopMemSet - See if this memset can be promoted to a large memset.
833 bool LoopIdiomRecognize::
834 processLoopMemSet(MemSetInst *MSI, const SCEV *BECount) {
835   // We can only handle non-volatile memsets with a constant size.
836   if (MSI->isVolatile() || !isa<ConstantInt>(MSI->getLength())) return false;
837
838   // If we're not allowed to hack on memset, we fail.
839   if (!TLI->has(LibFunc::memset))
840     return false;
841
842   Value *Pointer = MSI->getDest();
843
844   // See if the pointer expression is an AddRec like {base,+,1} on the current
845   // loop, which indicates a strided store.  If we have something else, it's a
846   // random store we can't handle.
847   const SCEVAddRecExpr *Ev = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Pointer));
848   if (!Ev || Ev->getLoop() != CurLoop || !Ev->isAffine())
849     return false;
850
851   // Reject memsets that are so large that they overflow an unsigned.
852   uint64_t SizeInBytes = cast<ConstantInt>(MSI->getLength())->getZExtValue();
853   if ((SizeInBytes >> 32) != 0)
854     return false;
855
856   // Check to see if the stride matches the size of the memset.  If so, then we
857   // know that every byte is touched in the loop.
858   const SCEVConstant *Stride = dyn_cast<SCEVConstant>(Ev->getOperand(1));
859
860   // TODO: Could also handle negative stride here someday, that will require the
861   // validity check in mayLoopAccessLocation to be updated though.
862   if (!Stride || MSI->getLength() != Stride->getValue())
863     return false;
864
865   return processLoopStridedStore(Pointer, (unsigned)SizeInBytes,
866                                  MSI->getAlignment(), MSI->getValue(),
867                                  MSI, Ev, BECount);
868 }
869
870
871 /// mayLoopAccessLocation - Return true if the specified loop might access the
872 /// specified pointer location, which is a loop-strided access.  The 'Access'
873 /// argument specifies what the verboten forms of access are (read or write).
874 static bool mayLoopAccessLocation(Value *Ptr,AliasAnalysis::ModRefResult Access,
875                                   Loop *L, const SCEV *BECount,
876                                   unsigned StoreSize, AliasAnalysis &AA,
877                                   Instruction *IgnoredStore) {
878   // Get the location that may be stored across the loop.  Since the access is
879   // strided positively through memory, we say that the modified location starts
880   // at the pointer and has infinite size.
881   uint64_t AccessSize = AliasAnalysis::UnknownSize;
882
883   // If the loop iterates a fixed number of times, we can refine the access size
884   // to be exactly the size of the memset, which is (BECount+1)*StoreSize
885   if (const SCEVConstant *BECst = dyn_cast<SCEVConstant>(BECount))
886     AccessSize = (BECst->getValue()->getZExtValue()+1)*StoreSize;
887
888   // TODO: For this to be really effective, we have to dive into the pointer
889   // operand in the store.  Store to &A[i] of 100 will always return may alias
890   // with store of &A[100], we need to StoreLoc to be "A" with size of 100,
891   // which will then no-alias a store to &A[100].
892   AliasAnalysis::Location StoreLoc(Ptr, AccessSize);
893
894   for (Loop::block_iterator BI = L->block_begin(), E = L->block_end(); BI != E;
895        ++BI)
896     for (BasicBlock::iterator I = (*BI)->begin(), E = (*BI)->end(); I != E; ++I)
897       if (&*I != IgnoredStore &&
898           (AA.getModRefInfo(I, StoreLoc) & Access))
899         return true;
900
901   return false;
902 }
903
904 /// getMemSetPatternValue - If a strided store of the specified value is safe to
905 /// turn into a memset_pattern16, return a ConstantArray of 16 bytes that should
906 /// be passed in.  Otherwise, return null.
907 ///
908 /// Note that we don't ever attempt to use memset_pattern8 or 4, because these
909 /// just replicate their input array and then pass on to memset_pattern16.
910 static Constant *getMemSetPatternValue(Value *V, const DataLayout &DL) {
911   // If the value isn't a constant, we can't promote it to being in a constant
912   // array.  We could theoretically do a store to an alloca or something, but
913   // that doesn't seem worthwhile.
914   Constant *C = dyn_cast<Constant>(V);
915   if (!C) return nullptr;
916
917   // Only handle simple values that are a power of two bytes in size.
918   uint64_t Size = DL.getTypeSizeInBits(V->getType());
919   if (Size == 0 || (Size & 7) || (Size & (Size-1)))
920     return nullptr;
921
922   // Don't care enough about darwin/ppc to implement this.
923   if (DL.isBigEndian())
924     return nullptr;
925
926   // Convert to size in bytes.
927   Size /= 8;
928
929   // TODO: If CI is larger than 16-bytes, we can try slicing it in half to see
930   // if the top and bottom are the same (e.g. for vectors and large integers).
931   if (Size > 16) return nullptr;
932
933   // If the constant is exactly 16 bytes, just use it.
934   if (Size == 16) return C;
935
936   // Otherwise, we'll use an array of the constants.
937   unsigned ArraySize = 16/Size;
938   ArrayType *AT = ArrayType::get(V->getType(), ArraySize);
939   return ConstantArray::get(AT, std::vector<Constant*>(ArraySize, C));
940 }
941
942
943 /// processLoopStridedStore - We see a strided store of some value.  If we can
944 /// transform this into a memset or memset_pattern in the loop preheader, do so.
945 bool LoopIdiomRecognize::
946 processLoopStridedStore(Value *DestPtr, unsigned StoreSize,
947                         unsigned StoreAlignment, Value *StoredVal,
948                         Instruction *TheStore, const SCEVAddRecExpr *Ev,
949                         const SCEV *BECount) {
950
951   // If the stored value is a byte-wise value (like i32 -1), then it may be
952   // turned into a memset of i8 -1, assuming that all the consecutive bytes
953   // are stored.  A store of i32 0x01020304 can never be turned into a memset,
954   // but it can be turned into memset_pattern if the target supports it.
955   Value *SplatValue = isBytewiseValue(StoredVal);
956   Constant *PatternValue = nullptr;
957
958   unsigned DestAS = DestPtr->getType()->getPointerAddressSpace();
959
960   // If we're allowed to form a memset, and the stored value would be acceptable
961   // for memset, use it.
962   if (SplatValue && TLI->has(LibFunc::memset) &&
963       // Verify that the stored value is loop invariant.  If not, we can't
964       // promote the memset.
965       CurLoop->isLoopInvariant(SplatValue)) {
966     // Keep and use SplatValue.
967     PatternValue = nullptr;
968   } else if (DestAS == 0 &&
969              TLI->has(LibFunc::memset_pattern16) &&
970              (PatternValue = getMemSetPatternValue(StoredVal, *DL))) {
971     // Don't create memset_pattern16s with address spaces.
972     // It looks like we can use PatternValue!
973     SplatValue = nullptr;
974   } else {
975     // Otherwise, this isn't an idiom we can transform.  For example, we can't
976     // do anything with a 3-byte store.
977     return false;
978   }
979
980   // The trip count of the loop and the base pointer of the addrec SCEV is
981   // guaranteed to be loop invariant, which means that it should dominate the
982   // header.  This allows us to insert code for it in the preheader.
983   BasicBlock *Preheader = CurLoop->getLoopPreheader();
984   IRBuilder<> Builder(Preheader->getTerminator());
985   SCEVExpander Expander(*SE, "loop-idiom");
986
987   Type *DestInt8PtrTy = Builder.getInt8PtrTy(DestAS);
988
989   // Okay, we have a strided store "p[i]" of a splattable value.  We can turn
990   // this into a memset in the loop preheader now if we want.  However, this
991   // would be unsafe to do if there is anything else in the loop that may read
992   // or write to the aliased location.  Check for any overlap by generating the
993   // base pointer and checking the region.
994   Value *BasePtr =
995     Expander.expandCodeFor(Ev->getStart(), DestInt8PtrTy,
996                            Preheader->getTerminator());
997
998   if (mayLoopAccessLocation(BasePtr, AliasAnalysis::ModRef,
999                             CurLoop, BECount,
1000                             StoreSize, getAnalysis<AliasAnalysis>(), TheStore)) {
1001     Expander.clear();
1002     // If we generated new code for the base pointer, clean up.
1003     deleteIfDeadInstruction(BasePtr, *SE, TLI);
1004     return false;
1005   }
1006
1007   // Okay, everything looks good, insert the memset.
1008
1009   // The # stored bytes is (BECount+1)*Size.  Expand the trip count out to
1010   // pointer size if it isn't already.
1011   Type *IntPtr = Builder.getIntPtrTy(DL, DestAS);
1012   BECount = SE->getTruncateOrZeroExtend(BECount, IntPtr);
1013
1014   const SCEV *NumBytesS = SE->getAddExpr(BECount, SE->getConstant(IntPtr, 1),
1015                                          SCEV::FlagNUW);
1016   if (StoreSize != 1) {
1017     NumBytesS = SE->getMulExpr(NumBytesS, SE->getConstant(IntPtr, StoreSize),
1018                                SCEV::FlagNUW);
1019   }
1020
1021   Value *NumBytes =
1022     Expander.expandCodeFor(NumBytesS, IntPtr, Preheader->getTerminator());
1023
1024   CallInst *NewCall;
1025   if (SplatValue) {
1026     NewCall = Builder.CreateMemSet(BasePtr,
1027                                    SplatValue,
1028                                    NumBytes,
1029                                    StoreAlignment);
1030   } else {
1031     // Everything is emitted in default address space
1032     Type *Int8PtrTy = DestInt8PtrTy;
1033
1034     Module *M = TheStore->getParent()->getParent()->getParent();
1035     Value *MSP = M->getOrInsertFunction("memset_pattern16",
1036                                         Builder.getVoidTy(),
1037                                         Int8PtrTy,
1038                                         Int8PtrTy,
1039                                         IntPtr,
1040                                         (void*)nullptr);
1041
1042     // Otherwise we should form a memset_pattern16.  PatternValue is known to be
1043     // an constant array of 16-bytes.  Plop the value into a mergable global.
1044     GlobalVariable *GV = new GlobalVariable(*M, PatternValue->getType(), true,
1045                                             GlobalValue::InternalLinkage,
1046                                             PatternValue, ".memset_pattern");
1047     GV->setUnnamedAddr(true); // Ok to merge these.
1048     GV->setAlignment(16);
1049     Value *PatternPtr = ConstantExpr::getBitCast(GV, Int8PtrTy);
1050     NewCall = Builder.CreateCall3(MSP, BasePtr, PatternPtr, NumBytes);
1051   }
1052
1053   DEBUG(dbgs() << "  Formed memset: " << *NewCall << "\n"
1054                << "    from store to: " << *Ev << " at: " << *TheStore << "\n");
1055   NewCall->setDebugLoc(TheStore->getDebugLoc());
1056
1057   // Okay, the memset has been formed.  Zap the original store and anything that
1058   // feeds into it.
1059   deleteDeadInstruction(TheStore, *SE, TLI);
1060   ++NumMemSet;
1061   return true;
1062 }
1063
1064 /// processLoopStoreOfLoopLoad - We see a strided store whose value is a
1065 /// same-strided load.
1066 bool LoopIdiomRecognize::
1067 processLoopStoreOfLoopLoad(StoreInst *SI, unsigned StoreSize,
1068                            const SCEVAddRecExpr *StoreEv,
1069                            const SCEVAddRecExpr *LoadEv,
1070                            const SCEV *BECount) {
1071   // If we're not allowed to form memcpy, we fail.
1072   if (!TLI->has(LibFunc::memcpy))
1073     return false;
1074
1075   LoadInst *LI = cast<LoadInst>(SI->getValueOperand());
1076
1077   // The trip count of the loop and the base pointer of the addrec SCEV is
1078   // guaranteed to be loop invariant, which means that it should dominate the
1079   // header.  This allows us to insert code for it in the preheader.
1080   BasicBlock *Preheader = CurLoop->getLoopPreheader();
1081   IRBuilder<> Builder(Preheader->getTerminator());
1082   SCEVExpander Expander(*SE, "loop-idiom");
1083
1084   // Okay, we have a strided store "p[i]" of a loaded value.  We can turn
1085   // this into a memcpy in the loop preheader now if we want.  However, this
1086   // would be unsafe to do if there is anything else in the loop that may read
1087   // or write the memory region we're storing to.  This includes the load that
1088   // feeds the stores.  Check for an alias by generating the base address and
1089   // checking everything.
1090   Value *StoreBasePtr =
1091     Expander.expandCodeFor(StoreEv->getStart(),
1092                            Builder.getInt8PtrTy(SI->getPointerAddressSpace()),
1093                            Preheader->getTerminator());
1094
1095   if (mayLoopAccessLocation(StoreBasePtr, AliasAnalysis::ModRef,
1096                             CurLoop, BECount, StoreSize,
1097                             getAnalysis<AliasAnalysis>(), SI)) {
1098     Expander.clear();
1099     // If we generated new code for the base pointer, clean up.
1100     deleteIfDeadInstruction(StoreBasePtr, *SE, TLI);
1101     return false;
1102   }
1103
1104   // For a memcpy, we have to make sure that the input array is not being
1105   // mutated by the loop.
1106   Value *LoadBasePtr =
1107     Expander.expandCodeFor(LoadEv->getStart(),
1108                            Builder.getInt8PtrTy(LI->getPointerAddressSpace()),
1109                            Preheader->getTerminator());
1110
1111   if (mayLoopAccessLocation(LoadBasePtr, AliasAnalysis::Mod, CurLoop, BECount,
1112                             StoreSize, getAnalysis<AliasAnalysis>(), SI)) {
1113     Expander.clear();
1114     // If we generated new code for the base pointer, clean up.
1115     deleteIfDeadInstruction(LoadBasePtr, *SE, TLI);
1116     deleteIfDeadInstruction(StoreBasePtr, *SE, TLI);
1117     return false;
1118   }
1119
1120   // Okay, everything is safe, we can transform this!
1121
1122
1123   // The # stored bytes is (BECount+1)*Size.  Expand the trip count out to
1124   // pointer size if it isn't already.
1125   Type *IntPtrTy = Builder.getIntPtrTy(DL, SI->getPointerAddressSpace());
1126   BECount = SE->getTruncateOrZeroExtend(BECount, IntPtrTy);
1127
1128   const SCEV *NumBytesS = SE->getAddExpr(BECount, SE->getConstant(IntPtrTy, 1),
1129                                          SCEV::FlagNUW);
1130   if (StoreSize != 1)
1131     NumBytesS = SE->getMulExpr(NumBytesS, SE->getConstant(IntPtrTy, StoreSize),
1132                                SCEV::FlagNUW);
1133
1134   Value *NumBytes =
1135     Expander.expandCodeFor(NumBytesS, IntPtrTy, Preheader->getTerminator());
1136
1137   CallInst *NewCall =
1138     Builder.CreateMemCpy(StoreBasePtr, LoadBasePtr, NumBytes,
1139                          std::min(SI->getAlignment(), LI->getAlignment()));
1140   NewCall->setDebugLoc(SI->getDebugLoc());
1141
1142   DEBUG(dbgs() << "  Formed memcpy: " << *NewCall << "\n"
1143                << "    from load ptr=" << *LoadEv << " at: " << *LI << "\n"
1144                << "    from store ptr=" << *StoreEv << " at: " << *SI << "\n");
1145
1146
1147   // Okay, the memset has been formed.  Zap the original store and anything that
1148   // feeds into it.
1149   deleteDeadInstruction(SI, *SE, TLI);
1150   ++NumMemCpy;
1151   return true;
1152 }