LLVM API Documentation

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