LLVM  mainline
LoopIdiomRecognize.cpp
Go to the documentation of this file.
00001 //===-- LoopIdiomRecognize.cpp - Loop idiom recognition -------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This pass implements an idiom recognizer that transforms simple loops into a
00011 // non-loop form.  In cases that this kicks in, it can be a significant
00012 // performance win.
00013 //
00014 //===----------------------------------------------------------------------===//
00015 //
00016 // TODO List:
00017 //
00018 // Future loop memory idioms to recognize:
00019 //   memcmp, memmove, strlen, etc.
00020 // Future floating point idioms to recognize in -ffast-math mode:
00021 //   fpowi
00022 // Future integer operation idioms to recognize:
00023 //   ctpop, ctlz, cttz
00024 //
00025 // Beware that isel's default lowering for ctpop is highly inefficient for
00026 // i64 and larger types when i64 is legal and the value has few bits set.  It
00027 // would be good to enhance isel to emit a loop for ctpop in this case.
00028 //
00029 // We should enhance the memset/memcpy recognition to handle multiple stores in
00030 // the loop.  This would handle things like:
00031 //   void foo(_Complex float *P)
00032 //     for (i) { __real__(*P) = 0;  __imag__(*P) = 0; }
00033 //
00034 // We should enhance this to handle negative strides through memory.
00035 // Alternatively (and perhaps better) we could rely on an earlier pass to force
00036 // forward iteration through memory, which is generally better for cache
00037 // behavior.  Negative strides *do* happen for memset/memcpy loops.
00038 //
00039 // This could recognize common matrix multiplies and dot product idioms and
00040 // replace them with calls to BLAS (if linked in??).
00041 //
00042 //===----------------------------------------------------------------------===//
00043 
00044 #include "llvm/Transforms/Scalar.h"
00045 #include "llvm/ADT/Statistic.h"
00046 #include "llvm/Analysis/AliasAnalysis.h"
00047 #include "llvm/Analysis/LoopPass.h"
00048 #include "llvm/Analysis/ScalarEvolutionExpander.h"
00049 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
00050 #include "llvm/Analysis/TargetLibraryInfo.h"
00051 #include "llvm/Analysis/TargetTransformInfo.h"
00052 #include "llvm/Analysis/ValueTracking.h"
00053 #include "llvm/IR/DataLayout.h"
00054 #include "llvm/IR/Dominators.h"
00055 #include "llvm/IR/IRBuilder.h"
00056 #include "llvm/IR/IntrinsicInst.h"
00057 #include "llvm/IR/Module.h"
00058 #include "llvm/Support/Debug.h"
00059 #include "llvm/Support/raw_ostream.h"
00060 #include "llvm/Transforms/Utils/Local.h"
00061 using namespace llvm;
00062 
00063 #define DEBUG_TYPE "loop-idiom"
00064 
00065 STATISTIC(NumMemSet, "Number of memset's formed from loop stores");
00066 STATISTIC(NumMemCpy, "Number of memcpy's formed from loop load+stores");
00067 
00068 namespace {
00069 
00070   class LoopIdiomRecognize;
00071 
00072   /// This class defines some utility functions for loop idiom recognization.
00073   class LIRUtil {
00074   public:
00075     /// Return true iff the block contains nothing but an uncondition branch
00076     /// (aka goto instruction).
00077     static bool isAlmostEmpty(BasicBlock *);
00078 
00079     static BranchInst *getBranch(BasicBlock *BB) {
00080       return dyn_cast<BranchInst>(BB->getTerminator());
00081     }
00082 
00083     /// Derive the precondition block (i.e the block that guards the loop
00084     /// preheader) from the given preheader.
00085     static BasicBlock *getPrecondBb(BasicBlock *PreHead);
00086   };
00087 
00088   /// This class is to recoginize idioms of population-count conducted in
00089   /// a noncountable loop. Currently it only recognizes this pattern:
00090   /// \code
00091   ///   while(x) {cnt++; ...; x &= x - 1; ...}
00092   /// \endcode
00093   class NclPopcountRecognize {
00094     LoopIdiomRecognize &LIR;
00095     Loop *CurLoop;
00096     BasicBlock *PreCondBB;
00097 
00098     typedef IRBuilder<> IRBuilderTy;
00099 
00100   public:
00101     explicit NclPopcountRecognize(LoopIdiomRecognize &TheLIR);
00102     bool recognize();
00103 
00104   private:
00105     /// Take a glimpse of the loop to see if we need to go ahead recoginizing
00106     /// the idiom.
00107     bool preliminaryScreen();
00108 
00109     /// Check if the given conditional branch is based on the comparison
00110     /// between a variable and zero, and if the variable is non-zero, the
00111     /// control yields to the loop entry. If the branch matches the behavior,
00112     /// the variable involved in the comparion is returned. This function will
00113     /// be called to see if the precondition and postcondition of the loop
00114     /// are in desirable form.
00115     Value *matchCondition(BranchInst *Br, BasicBlock *NonZeroTarget) const;
00116 
00117     /// Return true iff the idiom is detected in the loop. and 1) \p CntInst
00118     /// is set to the instruction counting the population bit. 2) \p CntPhi
00119     /// is set to the corresponding phi node. 3) \p Var is set to the value
00120     /// whose population bits are being counted.
00121     bool detectIdiom
00122       (Instruction *&CntInst, PHINode *&CntPhi, Value *&Var) const;
00123 
00124     /// Insert ctpop intrinsic function and some obviously dead instructions.
00125     void transform(Instruction *CntInst, PHINode *CntPhi, Value *Var);
00126 
00127     /// Create llvm.ctpop.* intrinsic function.
00128     CallInst *createPopcntIntrinsic(IRBuilderTy &IRB, Value *Val, DebugLoc DL);
00129   };
00130 
00131   class LoopIdiomRecognize : public LoopPass {
00132     Loop *CurLoop;
00133     DominatorTree *DT;
00134     ScalarEvolution *SE;
00135     TargetLibraryInfo *TLI;
00136     const TargetTransformInfo *TTI;
00137   public:
00138     static char ID;
00139     explicit LoopIdiomRecognize() : LoopPass(ID) {
00140       initializeLoopIdiomRecognizePass(*PassRegistry::getPassRegistry());
00141       DT = nullptr;
00142       SE = nullptr;
00143       TLI = nullptr;
00144       TTI = nullptr;
00145     }
00146 
00147     bool runOnLoop(Loop *L, LPPassManager &LPM) override;
00148     bool runOnLoopBlock(BasicBlock *BB, const SCEV *BECount,
00149                         SmallVectorImpl<BasicBlock*> &ExitBlocks);
00150 
00151     bool processLoopStore(StoreInst *SI, const SCEV *BECount);
00152     bool processLoopMemSet(MemSetInst *MSI, const SCEV *BECount);
00153 
00154     bool processLoopStridedStore(Value *DestPtr, unsigned StoreSize,
00155                                  unsigned StoreAlignment,
00156                                  Value *SplatValue, Instruction *TheStore,
00157                                  const SCEVAddRecExpr *Ev,
00158                                  const SCEV *BECount);
00159     bool processLoopStoreOfLoopLoad(StoreInst *SI, unsigned StoreSize,
00160                                     const SCEVAddRecExpr *StoreEv,
00161                                     const SCEVAddRecExpr *LoadEv,
00162                                     const SCEV *BECount);
00163 
00164     /// This transformation requires natural loop information & requires that
00165     /// loop preheaders be inserted into the CFG.
00166     ///
00167     void getAnalysisUsage(AnalysisUsage &AU) const override {
00168       AU.addRequired<LoopInfoWrapperPass>();
00169       AU.addPreserved<LoopInfoWrapperPass>();
00170       AU.addRequiredID(LoopSimplifyID);
00171       AU.addPreservedID(LoopSimplifyID);
00172       AU.addRequiredID(LCSSAID);
00173       AU.addPreservedID(LCSSAID);
00174       AU.addRequired<AliasAnalysis>();
00175       AU.addPreserved<AliasAnalysis>();
00176       AU.addRequired<ScalarEvolution>();
00177       AU.addPreserved<ScalarEvolution>();
00178       AU.addPreserved<DominatorTreeWrapperPass>();
00179       AU.addRequired<DominatorTreeWrapperPass>();
00180       AU.addRequired<TargetLibraryInfoWrapperPass>();
00181       AU.addRequired<TargetTransformInfoWrapperPass>();
00182     }
00183 
00184     DominatorTree *getDominatorTree() {
00185       return DT ? DT
00186                 : (DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree());
00187     }
00188 
00189     ScalarEvolution *getScalarEvolution() {
00190       return SE ? SE : (SE = &getAnalysis<ScalarEvolution>());
00191     }
00192 
00193     TargetLibraryInfo *getTargetLibraryInfo() {
00194       if (!TLI)
00195         TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
00196 
00197       return TLI;
00198     }
00199 
00200     const TargetTransformInfo *getTargetTransformInfo() {
00201       return TTI ? TTI
00202                  : (TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(
00203                         *CurLoop->getHeader()->getParent()));
00204     }
00205 
00206     Loop *getLoop() const { return CurLoop; }
00207 
00208   private:
00209     bool runOnNoncountableLoop();
00210     bool runOnCountableLoop();
00211   };
00212 }
00213 
00214 char LoopIdiomRecognize::ID = 0;
00215 INITIALIZE_PASS_BEGIN(LoopIdiomRecognize, "loop-idiom", "Recognize loop idioms",
00216                       false, false)
00217 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
00218 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
00219 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
00220 INITIALIZE_PASS_DEPENDENCY(LCSSA)
00221 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
00222 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
00223 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
00224 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
00225 INITIALIZE_PASS_END(LoopIdiomRecognize, "loop-idiom", "Recognize loop idioms",
00226                     false, false)
00227 
00228 Pass *llvm::createLoopIdiomPass() { return new LoopIdiomRecognize(); }
00229 
00230 /// deleteDeadInstruction - Delete this instruction.  Before we do, go through
00231 /// and zero out all the operands of this instruction.  If any of them become
00232 /// dead, delete them and the computation tree that feeds them.
00233 ///
00234 static void deleteDeadInstruction(Instruction *I,
00235                                   const TargetLibraryInfo *TLI) {
00236   SmallVector<Value *, 16> Operands(I->value_op_begin(), I->value_op_end());
00237   I->replaceAllUsesWith(UndefValue::get(I->getType()));
00238   I->eraseFromParent();
00239   for (Value *Op : Operands)
00240     RecursivelyDeleteTriviallyDeadInstructions(Op, TLI);
00241 }
00242 
00243 //===----------------------------------------------------------------------===//
00244 //
00245 //          Implementation of LIRUtil
00246 //
00247 //===----------------------------------------------------------------------===//
00248 
00249 // This function will return true iff the given block contains nothing but goto.
00250 // A typical usage of this function is to check if the preheader function is
00251 // "almost" empty such that generated intrinsic functions can be moved across
00252 // the preheader and be placed at the end of the precondition block without
00253 // the concern of breaking data dependence.
00254 bool LIRUtil::isAlmostEmpty(BasicBlock *BB) {
00255   if (BranchInst *Br = getBranch(BB)) {
00256     return Br->isUnconditional() && Br == BB->begin();
00257   }
00258   return false;
00259 }
00260 
00261 BasicBlock *LIRUtil::getPrecondBb(BasicBlock *PreHead) {
00262   if (BasicBlock *BB = PreHead->getSinglePredecessor()) {
00263     BranchInst *Br = getBranch(BB);
00264     return Br && Br->isConditional() ? BB : nullptr;
00265   }
00266   return nullptr;
00267 }
00268 
00269 //===----------------------------------------------------------------------===//
00270 //
00271 //          Implementation of NclPopcountRecognize
00272 //
00273 //===----------------------------------------------------------------------===//
00274 
00275 NclPopcountRecognize::NclPopcountRecognize(LoopIdiomRecognize &TheLIR):
00276   LIR(TheLIR), CurLoop(TheLIR.getLoop()), PreCondBB(nullptr) {
00277 }
00278 
00279 bool NclPopcountRecognize::preliminaryScreen() {
00280   const TargetTransformInfo *TTI = LIR.getTargetTransformInfo();
00281   if (TTI->getPopcntSupport(32) != TargetTransformInfo::PSK_FastHardware)
00282     return false;
00283 
00284   // Counting population are usually conducted by few arithmetic instructions.
00285   // Such instructions can be easilly "absorbed" by vacant slots in a
00286   // non-compact loop. Therefore, recognizing popcount idiom only makes sense
00287   // in a compact loop.
00288 
00289   // Give up if the loop has multiple blocks or multiple backedges.
00290   if (CurLoop->getNumBackEdges() != 1 || CurLoop->getNumBlocks() != 1)
00291     return false;
00292 
00293   BasicBlock *LoopBody = *(CurLoop->block_begin());
00294   if (LoopBody->size() >= 20) {
00295     // The loop is too big, bail out.
00296     return false;
00297   }
00298 
00299   // It should have a preheader containing nothing but a goto instruction.
00300   BasicBlock *PreHead = CurLoop->getLoopPreheader();
00301   if (!PreHead || !LIRUtil::isAlmostEmpty(PreHead))
00302     return false;
00303 
00304   // It should have a precondition block where the generated popcount instrinsic
00305   // function will be inserted.
00306   PreCondBB = LIRUtil::getPrecondBb(PreHead);
00307   if (!PreCondBB)
00308     return false;
00309 
00310   return true;
00311 }
00312 
00313 Value *NclPopcountRecognize::matchCondition(BranchInst *Br,
00314                                             BasicBlock *LoopEntry) const {
00315   if (!Br || !Br->isConditional())
00316     return nullptr;
00317 
00318   ICmpInst *Cond = dyn_cast<ICmpInst>(Br->getCondition());
00319   if (!Cond)
00320     return nullptr;
00321 
00322   ConstantInt *CmpZero = dyn_cast<ConstantInt>(Cond->getOperand(1));
00323   if (!CmpZero || !CmpZero->isZero())
00324     return nullptr;
00325 
00326   ICmpInst::Predicate Pred = Cond->getPredicate();
00327   if ((Pred == ICmpInst::ICMP_NE && Br->getSuccessor(0) == LoopEntry) ||
00328       (Pred == ICmpInst::ICMP_EQ && Br->getSuccessor(1) == LoopEntry))
00329     return Cond->getOperand(0);
00330 
00331   return nullptr;
00332 }
00333 
00334 bool NclPopcountRecognize::detectIdiom(Instruction *&CntInst,
00335                                        PHINode *&CntPhi,
00336                                        Value *&Var) const {
00337   // Following code tries to detect this idiom:
00338   //
00339   //    if (x0 != 0)
00340   //      goto loop-exit // the precondition of the loop
00341   //    cnt0 = init-val;
00342   //    do {
00343   //       x1 = phi (x0, x2);
00344   //       cnt1 = phi(cnt0, cnt2);
00345   //
00346   //       cnt2 = cnt1 + 1;
00347   //        ...
00348   //       x2 = x1 & (x1 - 1);
00349   //        ...
00350   //    } while(x != 0);
00351   //
00352   // loop-exit:
00353   //
00354 
00355   // step 1: Check to see if the look-back branch match this pattern:
00356   //    "if (a!=0) goto loop-entry".
00357   BasicBlock *LoopEntry;
00358   Instruction *DefX2, *CountInst;
00359   Value *VarX1, *VarX0;
00360   PHINode *PhiX, *CountPhi;
00361 
00362   DefX2 = CountInst = nullptr;
00363   VarX1 = VarX0 = nullptr;
00364   PhiX = CountPhi = nullptr;
00365   LoopEntry = *(CurLoop->block_begin());
00366 
00367   // step 1: Check if the loop-back branch is in desirable form.
00368   {
00369     if (Value *T = matchCondition (LIRUtil::getBranch(LoopEntry), LoopEntry))
00370       DefX2 = dyn_cast<Instruction>(T);
00371     else
00372       return false;
00373   }
00374 
00375   // step 2: detect instructions corresponding to "x2 = x1 & (x1 - 1)"
00376   {
00377     if (!DefX2 || DefX2->getOpcode() != Instruction::And)
00378       return false;
00379 
00380     BinaryOperator *SubOneOp;
00381 
00382     if ((SubOneOp = dyn_cast<BinaryOperator>(DefX2->getOperand(0))))
00383       VarX1 = DefX2->getOperand(1);
00384     else {
00385       VarX1 = DefX2->getOperand(0);
00386       SubOneOp = dyn_cast<BinaryOperator>(DefX2->getOperand(1));
00387     }
00388     if (!SubOneOp)
00389       return false;
00390 
00391     Instruction *SubInst = cast<Instruction>(SubOneOp);
00392     ConstantInt *Dec = dyn_cast<ConstantInt>(SubInst->getOperand(1));
00393     if (!Dec ||
00394         !((SubInst->getOpcode() == Instruction::Sub && Dec->isOne()) ||
00395           (SubInst->getOpcode() == Instruction::Add && Dec->isAllOnesValue()))) {
00396       return false;
00397     }
00398   }
00399 
00400   // step 3: Check the recurrence of variable X
00401   {
00402     PhiX = dyn_cast<PHINode>(VarX1);
00403     if (!PhiX ||
00404         (PhiX->getOperand(0) != DefX2 && PhiX->getOperand(1) != DefX2)) {
00405       return false;
00406     }
00407   }
00408 
00409   // step 4: Find the instruction which count the population: cnt2 = cnt1 + 1
00410   {
00411     CountInst = nullptr;
00412     for (BasicBlock::iterator Iter = LoopEntry->getFirstNonPHI(),
00413            IterE = LoopEntry->end(); Iter != IterE; Iter++) {
00414       Instruction *Inst = Iter;
00415       if (Inst->getOpcode() != Instruction::Add)
00416         continue;
00417 
00418       ConstantInt *Inc = dyn_cast<ConstantInt>(Inst->getOperand(1));
00419       if (!Inc || !Inc->isOne())
00420         continue;
00421 
00422       PHINode *Phi = dyn_cast<PHINode>(Inst->getOperand(0));
00423       if (!Phi || Phi->getParent() != LoopEntry)
00424         continue;
00425 
00426       // Check if the result of the instruction is live of the loop.
00427       bool LiveOutLoop = false;
00428       for (User *U : Inst->users()) {
00429         if ((cast<Instruction>(U))->getParent() != LoopEntry) {
00430           LiveOutLoop = true; break;
00431         }
00432       }
00433 
00434       if (LiveOutLoop) {
00435         CountInst = Inst;
00436         CountPhi = Phi;
00437         break;
00438       }
00439     }
00440 
00441     if (!CountInst)
00442       return false;
00443   }
00444 
00445   // step 5: check if the precondition is in this form:
00446   //   "if (x != 0) goto loop-head ; else goto somewhere-we-don't-care;"
00447   {
00448     BranchInst *PreCondBr = LIRUtil::getBranch(PreCondBB);
00449     Value *T = matchCondition (PreCondBr, CurLoop->getLoopPreheader());
00450     if (T != PhiX->getOperand(0) && T != PhiX->getOperand(1))
00451       return false;
00452 
00453     CntInst = CountInst;
00454     CntPhi = CountPhi;
00455     Var = T;
00456   }
00457 
00458   return true;
00459 }
00460 
00461 void NclPopcountRecognize::transform(Instruction *CntInst,
00462                                      PHINode *CntPhi, Value *Var) {
00463 
00464   ScalarEvolution *SE = LIR.getScalarEvolution();
00465   TargetLibraryInfo *TLI = LIR.getTargetLibraryInfo();
00466   BasicBlock *PreHead = CurLoop->getLoopPreheader();
00467   BranchInst *PreCondBr = LIRUtil::getBranch(PreCondBB);
00468   const DebugLoc DL = CntInst->getDebugLoc();
00469 
00470   // Assuming before transformation, the loop is following:
00471   //  if (x) // the precondition
00472   //     do { cnt++; x &= x - 1; } while(x);
00473 
00474   // Step 1: Insert the ctpop instruction at the end of the precondition block
00475   IRBuilderTy Builder(PreCondBr);
00476   Value *PopCnt, *PopCntZext, *NewCount, *TripCnt;
00477   {
00478     PopCnt = createPopcntIntrinsic(Builder, Var, DL);
00479     NewCount = PopCntZext =
00480       Builder.CreateZExtOrTrunc(PopCnt, cast<IntegerType>(CntPhi->getType()));
00481 
00482     if (NewCount != PopCnt)
00483       (cast<Instruction>(NewCount))->setDebugLoc(DL);
00484 
00485     // TripCnt is exactly the number of iterations the loop has
00486     TripCnt = NewCount;
00487 
00488     // If the population counter's initial value is not zero, insert Add Inst.
00489     Value *CntInitVal = CntPhi->getIncomingValueForBlock(PreHead);
00490     ConstantInt *InitConst = dyn_cast<ConstantInt>(CntInitVal);
00491     if (!InitConst || !InitConst->isZero()) {
00492       NewCount = Builder.CreateAdd(NewCount, CntInitVal);
00493       (cast<Instruction>(NewCount))->setDebugLoc(DL);
00494     }
00495   }
00496 
00497   // Step 2: Replace the precondition from "if(x == 0) goto loop-exit" to
00498   //   "if(NewCount == 0) loop-exit". Withtout this change, the intrinsic
00499   //   function would be partial dead code, and downstream passes will drag
00500   //   it back from the precondition block to the preheader.
00501   {
00502     ICmpInst *PreCond = cast<ICmpInst>(PreCondBr->getCondition());
00503 
00504     Value *Opnd0 = PopCntZext;
00505     Value *Opnd1 = ConstantInt::get(PopCntZext->getType(), 0);
00506     if (PreCond->getOperand(0) != Var)
00507       std::swap(Opnd0, Opnd1);
00508 
00509     ICmpInst *NewPreCond =
00510       cast<ICmpInst>(Builder.CreateICmp(PreCond->getPredicate(), Opnd0, Opnd1));
00511     PreCond->replaceAllUsesWith(NewPreCond);
00512 
00513     RecursivelyDeleteTriviallyDeadInstructions(PreCond, TLI);
00514   }
00515 
00516   // Step 3: Note that the population count is exactly the trip count of the
00517   // loop in question, which enble us to to convert the loop from noncountable
00518   // loop into a countable one. The benefit is twofold:
00519   //
00520   //  - If the loop only counts population, the entire loop become dead after
00521   //    the transformation. It is lots easier to prove a countable loop dead
00522   //    than to prove a noncountable one. (In some C dialects, a infite loop
00523   //    isn't dead even if it computes nothing useful. In general, DCE needs
00524   //    to prove a noncountable loop finite before safely delete it.)
00525   //
00526   //  - If the loop also performs something else, it remains alive.
00527   //    Since it is transformed to countable form, it can be aggressively
00528   //    optimized by some optimizations which are in general not applicable
00529   //    to a noncountable loop.
00530   //
00531   // After this step, this loop (conceptually) would look like following:
00532   //   newcnt = __builtin_ctpop(x);
00533   //   t = newcnt;
00534   //   if (x)
00535   //     do { cnt++; x &= x-1; t--) } while (t > 0);
00536   BasicBlock *Body = *(CurLoop->block_begin());
00537   {
00538     BranchInst *LbBr = LIRUtil::getBranch(Body);
00539     ICmpInst *LbCond = cast<ICmpInst>(LbBr->getCondition());
00540     Type *Ty = TripCnt->getType();
00541 
00542     PHINode *TcPhi = PHINode::Create(Ty, 2, "tcphi", Body->begin());
00543 
00544     Builder.SetInsertPoint(LbCond);
00545     Value *Opnd1 = cast<Value>(TcPhi);
00546     Value *Opnd2 = cast<Value>(ConstantInt::get(Ty, 1));
00547     Instruction *TcDec =
00548       cast<Instruction>(Builder.CreateSub(Opnd1, Opnd2, "tcdec", false, true));
00549 
00550     TcPhi->addIncoming(TripCnt, PreHead);
00551     TcPhi->addIncoming(TcDec, Body);
00552 
00553     CmpInst::Predicate Pred = (LbBr->getSuccessor(0) == Body) ?
00554       CmpInst::ICMP_UGT : CmpInst::ICMP_SLE;
00555     LbCond->setPredicate(Pred);
00556     LbCond->setOperand(0, TcDec);
00557     LbCond->setOperand(1, cast<Value>(ConstantInt::get(Ty, 0)));
00558   }
00559 
00560   // Step 4: All the references to the original population counter outside
00561   //  the loop are replaced with the NewCount -- the value returned from
00562   //  __builtin_ctpop().
00563   CntInst->replaceUsesOutsideBlock(NewCount, Body);
00564 
00565   // step 5: Forget the "non-computable" trip-count SCEV associated with the
00566   //   loop. The loop would otherwise not be deleted even if it becomes empty.
00567   SE->forgetLoop(CurLoop);
00568 }
00569 
00570 CallInst *NclPopcountRecognize::createPopcntIntrinsic(IRBuilderTy &IRBuilder,
00571                                                       Value *Val, DebugLoc DL) {
00572   Value *Ops[] = { Val };
00573   Type *Tys[] = { Val->getType() };
00574 
00575   Module *M = (*(CurLoop->block_begin()))->getParent()->getParent();
00576   Value *Func = Intrinsic::getDeclaration(M, Intrinsic::ctpop, Tys);
00577   CallInst *CI = IRBuilder.CreateCall(Func, Ops);
00578   CI->setDebugLoc(DL);
00579 
00580   return CI;
00581 }
00582 
00583 /// recognize - detect population count idiom in a non-countable loop. If
00584 ///   detected, transform the relevant code to popcount intrinsic function
00585 ///   call, and return true; otherwise, return false.
00586 bool NclPopcountRecognize::recognize() {
00587 
00588   if (!LIR.getTargetTransformInfo())
00589     return false;
00590 
00591   LIR.getScalarEvolution();
00592 
00593   if (!preliminaryScreen())
00594     return false;
00595 
00596   Instruction *CntInst;
00597   PHINode *CntPhi;
00598   Value *Val;
00599   if (!detectIdiom(CntInst, CntPhi, Val))
00600     return false;
00601 
00602   transform(CntInst, CntPhi, Val);
00603   return true;
00604 }
00605 
00606 //===----------------------------------------------------------------------===//
00607 //
00608 //          Implementation of LoopIdiomRecognize
00609 //
00610 //===----------------------------------------------------------------------===//
00611 
00612 bool LoopIdiomRecognize::runOnCountableLoop() {
00613   const SCEV *BECount = SE->getBackedgeTakenCount(CurLoop);
00614   assert(!isa<SCEVCouldNotCompute>(BECount) &&
00615     "runOnCountableLoop() called on a loop without a predictable"
00616     "backedge-taken count");
00617 
00618   // If this loop executes exactly one time, then it should be peeled, not
00619   // optimized by this pass.
00620   if (const SCEVConstant *BECst = dyn_cast<SCEVConstant>(BECount))
00621     if (BECst->getValue()->getValue() == 0)
00622       return false;
00623 
00624   // set DT
00625   (void)getDominatorTree();
00626 
00627   LoopInfo &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
00628   TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
00629 
00630   // set TLI
00631   (void)getTargetLibraryInfo();
00632 
00633   SmallVector<BasicBlock*, 8> ExitBlocks;
00634   CurLoop->getUniqueExitBlocks(ExitBlocks);
00635 
00636   DEBUG(dbgs() << "loop-idiom Scanning: F["
00637                << CurLoop->getHeader()->getParent()->getName()
00638                << "] Loop %" << CurLoop->getHeader()->getName() << "\n");
00639 
00640   bool MadeChange = false;
00641   // Scan all the blocks in the loop that are not in subloops.
00642   for (auto *BB : CurLoop->getBlocks()) {
00643     // Ignore blocks in subloops.
00644     if (LI.getLoopFor(BB) != CurLoop)
00645       continue;
00646 
00647     MadeChange |= runOnLoopBlock(BB, BECount, ExitBlocks);
00648   }
00649   return MadeChange;
00650 }
00651 
00652 bool LoopIdiomRecognize::runOnNoncountableLoop() {
00653   NclPopcountRecognize Popcount(*this);
00654   if (Popcount.recognize())
00655     return true;
00656 
00657   return false;
00658 }
00659 
00660 bool LoopIdiomRecognize::runOnLoop(Loop *L, LPPassManager &LPM) {
00661   if (skipOptnoneFunction(L))
00662     return false;
00663 
00664   CurLoop = L;
00665 
00666   // If the loop could not be converted to canonical form, it must have an
00667   // indirectbr in it, just give up.
00668   if (!L->getLoopPreheader())
00669     return false;
00670 
00671   // Disable loop idiom recognition if the function's name is a common idiom.
00672   StringRef Name = L->getHeader()->getParent()->getName();
00673   if (Name == "memset" || Name == "memcpy")
00674     return false;
00675 
00676   SE = &getAnalysis<ScalarEvolution>();
00677   if (SE->hasLoopInvariantBackedgeTakenCount(L))
00678     return runOnCountableLoop();
00679   return runOnNoncountableLoop();
00680 }
00681 
00682 /// runOnLoopBlock - Process the specified block, which lives in a counted loop
00683 /// with the specified backedge count.  This block is known to be in the current
00684 /// loop and not in any subloops.
00685 bool LoopIdiomRecognize::runOnLoopBlock(BasicBlock *BB, const SCEV *BECount,
00686                                      SmallVectorImpl<BasicBlock*> &ExitBlocks) {
00687   // We can only promote stores in this block if they are unconditionally
00688   // executed in the loop.  For a block to be unconditionally executed, it has
00689   // to dominate all the exit blocks of the loop.  Verify this now.
00690   for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
00691     if (!DT->dominates(BB, ExitBlocks[i]))
00692       return false;
00693 
00694   bool MadeChange = false;
00695   for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
00696     Instruction *Inst = I++;
00697     // Look for store instructions, which may be optimized to memset/memcpy.
00698     if (StoreInst *SI = dyn_cast<StoreInst>(Inst))  {
00699       WeakVH InstPtr(I);
00700       if (!processLoopStore(SI, BECount)) continue;
00701       MadeChange = true;
00702 
00703       // If processing the store invalidated our iterator, start over from the
00704       // top of the block.
00705       if (!InstPtr)
00706         I = BB->begin();
00707       continue;
00708     }
00709 
00710     // Look for memset instructions, which may be optimized to a larger memset.
00711     if (MemSetInst *MSI = dyn_cast<MemSetInst>(Inst))  {
00712       WeakVH InstPtr(I);
00713       if (!processLoopMemSet(MSI, BECount)) continue;
00714       MadeChange = true;
00715 
00716       // If processing the memset invalidated our iterator, start over from the
00717       // top of the block.
00718       if (!InstPtr)
00719         I = BB->begin();
00720       continue;
00721     }
00722   }
00723 
00724   return MadeChange;
00725 }
00726 
00727 
00728 /// processLoopStore - See if this store can be promoted to a memset or memcpy.
00729 bool LoopIdiomRecognize::processLoopStore(StoreInst *SI, const SCEV *BECount) {
00730   if (!SI->isSimple()) return false;
00731 
00732   Value *StoredVal = SI->getValueOperand();
00733   Value *StorePtr = SI->getPointerOperand();
00734 
00735   // Reject stores that are so large that they overflow an unsigned.
00736   auto &DL = CurLoop->getHeader()->getModule()->getDataLayout();
00737   uint64_t SizeInBits = DL.getTypeSizeInBits(StoredVal->getType());
00738   if ((SizeInBits & 7) || (SizeInBits >> 32) != 0)
00739     return false;
00740 
00741   // See if the pointer expression is an AddRec like {base,+,1} on the current
00742   // loop, which indicates a strided store.  If we have something else, it's a
00743   // random store we can't handle.
00744   const SCEVAddRecExpr *StoreEv =
00745     dyn_cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr));
00746   if (!StoreEv || StoreEv->getLoop() != CurLoop || !StoreEv->isAffine())
00747     return false;
00748 
00749   // Check to see if the stride matches the size of the store.  If so, then we
00750   // know that every byte is touched in the loop.
00751   unsigned StoreSize = (unsigned)SizeInBits >> 3;
00752   const SCEVConstant *Stride = dyn_cast<SCEVConstant>(StoreEv->getOperand(1));
00753 
00754   if (!Stride || StoreSize != Stride->getValue()->getValue()) {
00755     // TODO: Could also handle negative stride here someday, that will require
00756     // the validity check in mayLoopAccessLocation to be updated though.
00757     // Enable this to print exact negative strides.
00758     if (0 && Stride && StoreSize == -Stride->getValue()->getValue()) {
00759       dbgs() << "NEGATIVE STRIDE: " << *SI << "\n";
00760       dbgs() << "BB: " << *SI->getParent();
00761     }
00762 
00763     return false;
00764   }
00765 
00766   // See if we can optimize just this store in isolation.
00767   if (processLoopStridedStore(StorePtr, StoreSize, SI->getAlignment(),
00768                               StoredVal, SI, StoreEv, BECount))
00769     return true;
00770 
00771   // If the stored value is a strided load in the same loop with the same stride
00772   // this this may be transformable into a memcpy.  This kicks in for stuff like
00773   //   for (i) A[i] = B[i];
00774   if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) {
00775     const SCEVAddRecExpr *LoadEv =
00776       dyn_cast<SCEVAddRecExpr>(SE->getSCEV(LI->getOperand(0)));
00777     if (LoadEv && LoadEv->getLoop() == CurLoop && LoadEv->isAffine() &&
00778         StoreEv->getOperand(1) == LoadEv->getOperand(1) && LI->isSimple())
00779       if (processLoopStoreOfLoopLoad(SI, StoreSize, StoreEv, LoadEv, BECount))
00780         return true;
00781   }
00782   //errs() << "UNHANDLED strided store: " << *StoreEv << " - " << *SI << "\n";
00783 
00784   return false;
00785 }
00786 
00787 /// processLoopMemSet - See if this memset can be promoted to a large memset.
00788 bool LoopIdiomRecognize::
00789 processLoopMemSet(MemSetInst *MSI, const SCEV *BECount) {
00790   // We can only handle non-volatile memsets with a constant size.
00791   if (MSI->isVolatile() || !isa<ConstantInt>(MSI->getLength())) return false;
00792 
00793   // If we're not allowed to hack on memset, we fail.
00794   if (!TLI->has(LibFunc::memset))
00795     return false;
00796 
00797   Value *Pointer = MSI->getDest();
00798 
00799   // See if the pointer expression is an AddRec like {base,+,1} on the current
00800   // loop, which indicates a strided store.  If we have something else, it's a
00801   // random store we can't handle.
00802   const SCEVAddRecExpr *Ev = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Pointer));
00803   if (!Ev || Ev->getLoop() != CurLoop || !Ev->isAffine())
00804     return false;
00805 
00806   // Reject memsets that are so large that they overflow an unsigned.
00807   uint64_t SizeInBytes = cast<ConstantInt>(MSI->getLength())->getZExtValue();
00808   if ((SizeInBytes >> 32) != 0)
00809     return false;
00810 
00811   // Check to see if the stride matches the size of the memset.  If so, then we
00812   // know that every byte is touched in the loop.
00813   const SCEVConstant *Stride = dyn_cast<SCEVConstant>(Ev->getOperand(1));
00814 
00815   // TODO: Could also handle negative stride here someday, that will require the
00816   // validity check in mayLoopAccessLocation to be updated though.
00817   if (!Stride || MSI->getLength() != Stride->getValue())
00818     return false;
00819 
00820   return processLoopStridedStore(Pointer, (unsigned)SizeInBytes,
00821                                  MSI->getAlignment(), MSI->getValue(),
00822                                  MSI, Ev, BECount);
00823 }
00824 
00825 
00826 /// mayLoopAccessLocation - Return true if the specified loop might access the
00827 /// specified pointer location, which is a loop-strided access.  The 'Access'
00828 /// argument specifies what the verboten forms of access are (read or write).
00829 static bool mayLoopAccessLocation(Value *Ptr,AliasAnalysis::ModRefResult Access,
00830                                   Loop *L, const SCEV *BECount,
00831                                   unsigned StoreSize, AliasAnalysis &AA,
00832                                   Instruction *IgnoredStore) {
00833   // Get the location that may be stored across the loop.  Since the access is
00834   // strided positively through memory, we say that the modified location starts
00835   // at the pointer and has infinite size.
00836   uint64_t AccessSize = MemoryLocation::UnknownSize;
00837 
00838   // If the loop iterates a fixed number of times, we can refine the access size
00839   // to be exactly the size of the memset, which is (BECount+1)*StoreSize
00840   if (const SCEVConstant *BECst = dyn_cast<SCEVConstant>(BECount))
00841     AccessSize = (BECst->getValue()->getZExtValue()+1)*StoreSize;
00842 
00843   // TODO: For this to be really effective, we have to dive into the pointer
00844   // operand in the store.  Store to &A[i] of 100 will always return may alias
00845   // with store of &A[100], we need to StoreLoc to be "A" with size of 100,
00846   // which will then no-alias a store to &A[100].
00847   MemoryLocation StoreLoc(Ptr, AccessSize);
00848 
00849   for (Loop::block_iterator BI = L->block_begin(), E = L->block_end(); BI != E;
00850        ++BI)
00851     for (BasicBlock::iterator I = (*BI)->begin(), E = (*BI)->end(); I != E; ++I)
00852       if (&*I != IgnoredStore &&
00853           (AA.getModRefInfo(I, StoreLoc) & Access))
00854         return true;
00855 
00856   return false;
00857 }
00858 
00859 /// getMemSetPatternValue - If a strided store of the specified value is safe to
00860 /// turn into a memset_pattern16, return a ConstantArray of 16 bytes that should
00861 /// be passed in.  Otherwise, return null.
00862 ///
00863 /// Note that we don't ever attempt to use memset_pattern8 or 4, because these
00864 /// just replicate their input array and then pass on to memset_pattern16.
00865 static Constant *getMemSetPatternValue(Value *V, const DataLayout &DL) {
00866   // If the value isn't a constant, we can't promote it to being in a constant
00867   // array.  We could theoretically do a store to an alloca or something, but
00868   // that doesn't seem worthwhile.
00869   Constant *C = dyn_cast<Constant>(V);
00870   if (!C) return nullptr;
00871 
00872   // Only handle simple values that are a power of two bytes in size.
00873   uint64_t Size = DL.getTypeSizeInBits(V->getType());
00874   if (Size == 0 || (Size & 7) || (Size & (Size-1)))
00875     return nullptr;
00876 
00877   // Don't care enough about darwin/ppc to implement this.
00878   if (DL.isBigEndian())
00879     return nullptr;
00880 
00881   // Convert to size in bytes.
00882   Size /= 8;
00883 
00884   // TODO: If CI is larger than 16-bytes, we can try slicing it in half to see
00885   // if the top and bottom are the same (e.g. for vectors and large integers).
00886   if (Size > 16) return nullptr;
00887 
00888   // If the constant is exactly 16 bytes, just use it.
00889   if (Size == 16) return C;
00890 
00891   // Otherwise, we'll use an array of the constants.
00892   unsigned ArraySize = 16/Size;
00893   ArrayType *AT = ArrayType::get(V->getType(), ArraySize);
00894   return ConstantArray::get(AT, std::vector<Constant*>(ArraySize, C));
00895 }
00896 
00897 
00898 /// processLoopStridedStore - We see a strided store of some value.  If we can
00899 /// transform this into a memset or memset_pattern in the loop preheader, do so.
00900 bool LoopIdiomRecognize::
00901 processLoopStridedStore(Value *DestPtr, unsigned StoreSize,
00902                         unsigned StoreAlignment, Value *StoredVal,
00903                         Instruction *TheStore, const SCEVAddRecExpr *Ev,
00904                         const SCEV *BECount) {
00905 
00906   // If the stored value is a byte-wise value (like i32 -1), then it may be
00907   // turned into a memset of i8 -1, assuming that all the consecutive bytes
00908   // are stored.  A store of i32 0x01020304 can never be turned into a memset,
00909   // but it can be turned into memset_pattern if the target supports it.
00910   Value *SplatValue = isBytewiseValue(StoredVal);
00911   Constant *PatternValue = nullptr;
00912   auto &DL = CurLoop->getHeader()->getModule()->getDataLayout();
00913   unsigned DestAS = DestPtr->getType()->getPointerAddressSpace();
00914 
00915   // If we're allowed to form a memset, and the stored value would be acceptable
00916   // for memset, use it.
00917   if (SplatValue && TLI->has(LibFunc::memset) &&
00918       // Verify that the stored value is loop invariant.  If not, we can't
00919       // promote the memset.
00920       CurLoop->isLoopInvariant(SplatValue)) {
00921     // Keep and use SplatValue.
00922     PatternValue = nullptr;
00923   } else if (DestAS == 0 && TLI->has(LibFunc::memset_pattern16) &&
00924              (PatternValue = getMemSetPatternValue(StoredVal, DL))) {
00925     // Don't create memset_pattern16s with address spaces.
00926     // It looks like we can use PatternValue!
00927     SplatValue = nullptr;
00928   } else {
00929     // Otherwise, this isn't an idiom we can transform.  For example, we can't
00930     // do anything with a 3-byte store.
00931     return false;
00932   }
00933 
00934   // The trip count of the loop and the base pointer of the addrec SCEV is
00935   // guaranteed to be loop invariant, which means that it should dominate the
00936   // header.  This allows us to insert code for it in the preheader.
00937   BasicBlock *Preheader = CurLoop->getLoopPreheader();
00938   IRBuilder<> Builder(Preheader->getTerminator());
00939   SCEVExpander Expander(*SE, DL, "loop-idiom");
00940 
00941   Type *DestInt8PtrTy = Builder.getInt8PtrTy(DestAS);
00942 
00943   // Okay, we have a strided store "p[i]" of a splattable value.  We can turn
00944   // this into a memset in the loop preheader now if we want.  However, this
00945   // would be unsafe to do if there is anything else in the loop that may read
00946   // or write to the aliased location.  Check for any overlap by generating the
00947   // base pointer and checking the region.
00948   Value *BasePtr =
00949     Expander.expandCodeFor(Ev->getStart(), DestInt8PtrTy,
00950                            Preheader->getTerminator());
00951 
00952   if (mayLoopAccessLocation(BasePtr, AliasAnalysis::ModRef,
00953                             CurLoop, BECount,
00954                             StoreSize, getAnalysis<AliasAnalysis>(), TheStore)) {
00955     Expander.clear();
00956     // If we generated new code for the base pointer, clean up.
00957     RecursivelyDeleteTriviallyDeadInstructions(BasePtr, TLI);
00958     return false;
00959   }
00960 
00961   // Okay, everything looks good, insert the memset.
00962 
00963   // The # stored bytes is (BECount+1)*Size.  Expand the trip count out to
00964   // pointer size if it isn't already.
00965   Type *IntPtr = Builder.getIntPtrTy(DL, DestAS);
00966   BECount = SE->getTruncateOrZeroExtend(BECount, IntPtr);
00967 
00968   const SCEV *NumBytesS = SE->getAddExpr(BECount, SE->getConstant(IntPtr, 1),
00969                                          SCEV::FlagNUW);
00970   if (StoreSize != 1) {
00971     NumBytesS = SE->getMulExpr(NumBytesS, SE->getConstant(IntPtr, StoreSize),
00972                                SCEV::FlagNUW);
00973   }
00974 
00975   Value *NumBytes =
00976     Expander.expandCodeFor(NumBytesS, IntPtr, Preheader->getTerminator());
00977 
00978   CallInst *NewCall;
00979   if (SplatValue) {
00980     NewCall = Builder.CreateMemSet(BasePtr,
00981                                    SplatValue,
00982                                    NumBytes,
00983                                    StoreAlignment);
00984   } else {
00985     // Everything is emitted in default address space
00986     Type *Int8PtrTy = DestInt8PtrTy;
00987 
00988     Module *M = TheStore->getParent()->getParent()->getParent();
00989     Value *MSP = M->getOrInsertFunction("memset_pattern16",
00990                                         Builder.getVoidTy(),
00991                                         Int8PtrTy,
00992                                         Int8PtrTy,
00993                                         IntPtr,
00994                                         (void*)nullptr);
00995 
00996     // Otherwise we should form a memset_pattern16.  PatternValue is known to be
00997     // an constant array of 16-bytes.  Plop the value into a mergable global.
00998     GlobalVariable *GV = new GlobalVariable(*M, PatternValue->getType(), true,
00999                                             GlobalValue::PrivateLinkage,
01000                                             PatternValue, ".memset_pattern");
01001     GV->setUnnamedAddr(true); // Ok to merge these.
01002     GV->setAlignment(16);
01003     Value *PatternPtr = ConstantExpr::getBitCast(GV, Int8PtrTy);
01004     NewCall = Builder.CreateCall(MSP, {BasePtr, PatternPtr, NumBytes});
01005   }
01006 
01007   DEBUG(dbgs() << "  Formed memset: " << *NewCall << "\n"
01008                << "    from store to: " << *Ev << " at: " << *TheStore << "\n");
01009   NewCall->setDebugLoc(TheStore->getDebugLoc());
01010 
01011   // Okay, the memset has been formed.  Zap the original store and anything that
01012   // feeds into it.
01013   deleteDeadInstruction(TheStore, TLI);
01014   ++NumMemSet;
01015   return true;
01016 }
01017 
01018 /// processLoopStoreOfLoopLoad - We see a strided store whose value is a
01019 /// same-strided load.
01020 bool LoopIdiomRecognize::
01021 processLoopStoreOfLoopLoad(StoreInst *SI, unsigned StoreSize,
01022                            const SCEVAddRecExpr *StoreEv,
01023                            const SCEVAddRecExpr *LoadEv,
01024                            const SCEV *BECount) {
01025   // If we're not allowed to form memcpy, we fail.
01026   if (!TLI->has(LibFunc::memcpy))
01027     return false;
01028 
01029   LoadInst *LI = cast<LoadInst>(SI->getValueOperand());
01030 
01031   // The trip count of the loop and the base pointer of the addrec SCEV is
01032   // guaranteed to be loop invariant, which means that it should dominate the
01033   // header.  This allows us to insert code for it in the preheader.
01034   BasicBlock *Preheader = CurLoop->getLoopPreheader();
01035   IRBuilder<> Builder(Preheader->getTerminator());
01036   const DataLayout &DL = Preheader->getModule()->getDataLayout();
01037   SCEVExpander Expander(*SE, DL, "loop-idiom");
01038 
01039   // Okay, we have a strided store "p[i]" of a loaded value.  We can turn
01040   // this into a memcpy in the loop preheader now if we want.  However, this
01041   // would be unsafe to do if there is anything else in the loop that may read
01042   // or write the memory region we're storing to.  This includes the load that
01043   // feeds the stores.  Check for an alias by generating the base address and
01044   // checking everything.
01045   Value *StoreBasePtr =
01046     Expander.expandCodeFor(StoreEv->getStart(),
01047                            Builder.getInt8PtrTy(SI->getPointerAddressSpace()),
01048                            Preheader->getTerminator());
01049 
01050   if (mayLoopAccessLocation(StoreBasePtr, AliasAnalysis::ModRef,
01051                             CurLoop, BECount, StoreSize,
01052                             getAnalysis<AliasAnalysis>(), SI)) {
01053     Expander.clear();
01054     // If we generated new code for the base pointer, clean up.
01055     RecursivelyDeleteTriviallyDeadInstructions(StoreBasePtr, TLI);
01056     return false;
01057   }
01058 
01059   // For a memcpy, we have to make sure that the input array is not being
01060   // mutated by the loop.
01061   Value *LoadBasePtr =
01062     Expander.expandCodeFor(LoadEv->getStart(),
01063                            Builder.getInt8PtrTy(LI->getPointerAddressSpace()),
01064                            Preheader->getTerminator());
01065 
01066   if (mayLoopAccessLocation(LoadBasePtr, AliasAnalysis::Mod, CurLoop, BECount,
01067                             StoreSize, getAnalysis<AliasAnalysis>(), SI)) {
01068     Expander.clear();
01069     // If we generated new code for the base pointer, clean up.
01070     RecursivelyDeleteTriviallyDeadInstructions(LoadBasePtr, TLI);
01071     RecursivelyDeleteTriviallyDeadInstructions(StoreBasePtr, TLI);
01072     return false;
01073   }
01074 
01075   // Okay, everything is safe, we can transform this!
01076 
01077 
01078   // The # stored bytes is (BECount+1)*Size.  Expand the trip count out to
01079   // pointer size if it isn't already.
01080   Type *IntPtrTy = Builder.getIntPtrTy(DL, SI->getPointerAddressSpace());
01081   BECount = SE->getTruncateOrZeroExtend(BECount, IntPtrTy);
01082 
01083   const SCEV *NumBytesS = SE->getAddExpr(BECount, SE->getConstant(IntPtrTy, 1),
01084                                          SCEV::FlagNUW);
01085   if (StoreSize != 1)
01086     NumBytesS = SE->getMulExpr(NumBytesS, SE->getConstant(IntPtrTy, StoreSize),
01087                                SCEV::FlagNUW);
01088 
01089   Value *NumBytes =
01090     Expander.expandCodeFor(NumBytesS, IntPtrTy, Preheader->getTerminator());
01091 
01092   CallInst *NewCall =
01093     Builder.CreateMemCpy(StoreBasePtr, LoadBasePtr, NumBytes,
01094                          std::min(SI->getAlignment(), LI->getAlignment()));
01095   NewCall->setDebugLoc(SI->getDebugLoc());
01096 
01097   DEBUG(dbgs() << "  Formed memcpy: " << *NewCall << "\n"
01098                << "    from load ptr=" << *LoadEv << " at: " << *LI << "\n"
01099                << "    from store ptr=" << *StoreEv << " at: " << *SI << "\n");
01100 
01101 
01102   // Okay, the memset has been formed.  Zap the original store and anything that
01103   // feeds into it.
01104   deleteDeadInstruction(SI, TLI);
01105   ++NumMemCpy;
01106   return true;
01107 }