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