LLVM API Documentation

MemCpyOptimizer.cpp
Go to the documentation of this file.
00001 //===- MemCpyOptimizer.cpp - Optimize use of memcpy and friends -----------===//
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 performs various transformations related to eliminating memcpy
00011 // calls, or transforming sets of stores into memset's.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 #include "llvm/Transforms/Scalar.h"
00016 #include "llvm/ADT/SmallVector.h"
00017 #include "llvm/ADT/Statistic.h"
00018 #include "llvm/Analysis/AliasAnalysis.h"
00019 #include "llvm/Analysis/AssumptionTracker.h"
00020 #include "llvm/Analysis/MemoryDependenceAnalysis.h"
00021 #include "llvm/Analysis/ValueTracking.h"
00022 #include "llvm/IR/DataLayout.h"
00023 #include "llvm/IR/Dominators.h"
00024 #include "llvm/IR/GetElementPtrTypeIterator.h"
00025 #include "llvm/IR/GlobalVariable.h"
00026 #include "llvm/IR/IRBuilder.h"
00027 #include "llvm/IR/Instructions.h"
00028 #include "llvm/IR/IntrinsicInst.h"
00029 #include "llvm/Support/Debug.h"
00030 #include "llvm/Support/raw_ostream.h"
00031 #include "llvm/Target/TargetLibraryInfo.h"
00032 #include "llvm/Transforms/Utils/Local.h"
00033 #include <list>
00034 using namespace llvm;
00035 
00036 #define DEBUG_TYPE "memcpyopt"
00037 
00038 STATISTIC(NumMemCpyInstr, "Number of memcpy instructions deleted");
00039 STATISTIC(NumMemSetInfer, "Number of memsets inferred");
00040 STATISTIC(NumMoveToCpy,   "Number of memmoves converted to memcpy");
00041 STATISTIC(NumCpyToSet,    "Number of memcpys converted to memset");
00042 
00043 static int64_t GetOffsetFromIndex(const GEPOperator *GEP, unsigned Idx,
00044                                   bool &VariableIdxFound, const DataLayout &TD){
00045   // Skip over the first indices.
00046   gep_type_iterator GTI = gep_type_begin(GEP);
00047   for (unsigned i = 1; i != Idx; ++i, ++GTI)
00048     /*skip along*/;
00049 
00050   // Compute the offset implied by the rest of the indices.
00051   int64_t Offset = 0;
00052   for (unsigned i = Idx, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
00053     ConstantInt *OpC = dyn_cast<ConstantInt>(GEP->getOperand(i));
00054     if (!OpC)
00055       return VariableIdxFound = true;
00056     if (OpC->isZero()) continue;  // No offset.
00057 
00058     // Handle struct indices, which add their field offset to the pointer.
00059     if (StructType *STy = dyn_cast<StructType>(*GTI)) {
00060       Offset += TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
00061       continue;
00062     }
00063 
00064     // Otherwise, we have a sequential type like an array or vector.  Multiply
00065     // the index by the ElementSize.
00066     uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
00067     Offset += Size*OpC->getSExtValue();
00068   }
00069 
00070   return Offset;
00071 }
00072 
00073 /// IsPointerOffset - Return true if Ptr1 is provably equal to Ptr2 plus a
00074 /// constant offset, and return that constant offset.  For example, Ptr1 might
00075 /// be &A[42], and Ptr2 might be &A[40].  In this case offset would be -8.
00076 static bool IsPointerOffset(Value *Ptr1, Value *Ptr2, int64_t &Offset,
00077                             const DataLayout &TD) {
00078   Ptr1 = Ptr1->stripPointerCasts();
00079   Ptr2 = Ptr2->stripPointerCasts();
00080 
00081   // Handle the trivial case first.
00082   if (Ptr1 == Ptr2) {
00083     Offset = 0;
00084     return true;
00085   }
00086 
00087   GEPOperator *GEP1 = dyn_cast<GEPOperator>(Ptr1);
00088   GEPOperator *GEP2 = dyn_cast<GEPOperator>(Ptr2);
00089 
00090   bool VariableIdxFound = false;
00091 
00092   // If one pointer is a GEP and the other isn't, then see if the GEP is a
00093   // constant offset from the base, as in "P" and "gep P, 1".
00094   if (GEP1 && !GEP2 && GEP1->getOperand(0)->stripPointerCasts() == Ptr2) {
00095     Offset = -GetOffsetFromIndex(GEP1, 1, VariableIdxFound, TD);
00096     return !VariableIdxFound;
00097   }
00098 
00099   if (GEP2 && !GEP1 && GEP2->getOperand(0)->stripPointerCasts() == Ptr1) {
00100     Offset = GetOffsetFromIndex(GEP2, 1, VariableIdxFound, TD);
00101     return !VariableIdxFound;
00102   }
00103 
00104   // Right now we handle the case when Ptr1/Ptr2 are both GEPs with an identical
00105   // base.  After that base, they may have some number of common (and
00106   // potentially variable) indices.  After that they handle some constant
00107   // offset, which determines their offset from each other.  At this point, we
00108   // handle no other case.
00109   if (!GEP1 || !GEP2 || GEP1->getOperand(0) != GEP2->getOperand(0))
00110     return false;
00111 
00112   // Skip any common indices and track the GEP types.
00113   unsigned Idx = 1;
00114   for (; Idx != GEP1->getNumOperands() && Idx != GEP2->getNumOperands(); ++Idx)
00115     if (GEP1->getOperand(Idx) != GEP2->getOperand(Idx))
00116       break;
00117 
00118   int64_t Offset1 = GetOffsetFromIndex(GEP1, Idx, VariableIdxFound, TD);
00119   int64_t Offset2 = GetOffsetFromIndex(GEP2, Idx, VariableIdxFound, TD);
00120   if (VariableIdxFound) return false;
00121 
00122   Offset = Offset2-Offset1;
00123   return true;
00124 }
00125 
00126 
00127 /// MemsetRange - Represents a range of memset'd bytes with the ByteVal value.
00128 /// This allows us to analyze stores like:
00129 ///   store 0 -> P+1
00130 ///   store 0 -> P+0
00131 ///   store 0 -> P+3
00132 ///   store 0 -> P+2
00133 /// which sometimes happens with stores to arrays of structs etc.  When we see
00134 /// the first store, we make a range [1, 2).  The second store extends the range
00135 /// to [0, 2).  The third makes a new range [2, 3).  The fourth store joins the
00136 /// two ranges into [0, 3) which is memset'able.
00137 namespace {
00138 struct MemsetRange {
00139   // Start/End - A semi range that describes the span that this range covers.
00140   // The range is closed at the start and open at the end: [Start, End).
00141   int64_t Start, End;
00142 
00143   /// StartPtr - The getelementptr instruction that points to the start of the
00144   /// range.
00145   Value *StartPtr;
00146 
00147   /// Alignment - The known alignment of the first store.
00148   unsigned Alignment;
00149 
00150   /// TheStores - The actual stores that make up this range.
00151   SmallVector<Instruction*, 16> TheStores;
00152 
00153   bool isProfitableToUseMemset(const DataLayout &TD) const;
00154 
00155 };
00156 } // end anon namespace
00157 
00158 bool MemsetRange::isProfitableToUseMemset(const DataLayout &TD) const {
00159   // If we found more than 4 stores to merge or 16 bytes, use memset.
00160   if (TheStores.size() >= 4 || End-Start >= 16) return true;
00161 
00162   // If there is nothing to merge, don't do anything.
00163   if (TheStores.size() < 2) return false;
00164 
00165   // If any of the stores are a memset, then it is always good to extend the
00166   // memset.
00167   for (unsigned i = 0, e = TheStores.size(); i != e; ++i)
00168     if (!isa<StoreInst>(TheStores[i]))
00169       return true;
00170 
00171   // Assume that the code generator is capable of merging pairs of stores
00172   // together if it wants to.
00173   if (TheStores.size() == 2) return false;
00174 
00175   // If we have fewer than 8 stores, it can still be worthwhile to do this.
00176   // For example, merging 4 i8 stores into an i32 store is useful almost always.
00177   // However, merging 2 32-bit stores isn't useful on a 32-bit architecture (the
00178   // memset will be split into 2 32-bit stores anyway) and doing so can
00179   // pessimize the llvm optimizer.
00180   //
00181   // Since we don't have perfect knowledge here, make some assumptions: assume
00182   // the maximum GPR width is the same size as the largest legal integer
00183   // size. If so, check to see whether we will end up actually reducing the
00184   // number of stores used.
00185   unsigned Bytes = unsigned(End-Start);
00186   unsigned MaxIntSize = TD.getLargestLegalIntTypeSize();
00187   if (MaxIntSize == 0)
00188     MaxIntSize = 1;
00189   unsigned NumPointerStores = Bytes / MaxIntSize;
00190 
00191   // Assume the remaining bytes if any are done a byte at a time.
00192   unsigned NumByteStores = Bytes - NumPointerStores * MaxIntSize;
00193 
00194   // If we will reduce the # stores (according to this heuristic), do the
00195   // transformation.  This encourages merging 4 x i8 -> i32 and 2 x i16 -> i32
00196   // etc.
00197   return TheStores.size() > NumPointerStores+NumByteStores;
00198 }
00199 
00200 
00201 namespace {
00202 class MemsetRanges {
00203   /// Ranges - A sorted list of the memset ranges.  We use std::list here
00204   /// because each element is relatively large and expensive to copy.
00205   std::list<MemsetRange> Ranges;
00206   typedef std::list<MemsetRange>::iterator range_iterator;
00207   const DataLayout &DL;
00208 public:
00209   MemsetRanges(const DataLayout &DL) : DL(DL) {}
00210 
00211   typedef std::list<MemsetRange>::const_iterator const_iterator;
00212   const_iterator begin() const { return Ranges.begin(); }
00213   const_iterator end() const { return Ranges.end(); }
00214   bool empty() const { return Ranges.empty(); }
00215 
00216   void addInst(int64_t OffsetFromFirst, Instruction *Inst) {
00217     if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
00218       addStore(OffsetFromFirst, SI);
00219     else
00220       addMemSet(OffsetFromFirst, cast<MemSetInst>(Inst));
00221   }
00222 
00223   void addStore(int64_t OffsetFromFirst, StoreInst *SI) {
00224     int64_t StoreSize = DL.getTypeStoreSize(SI->getOperand(0)->getType());
00225 
00226     addRange(OffsetFromFirst, StoreSize,
00227              SI->getPointerOperand(), SI->getAlignment(), SI);
00228   }
00229 
00230   void addMemSet(int64_t OffsetFromFirst, MemSetInst *MSI) {
00231     int64_t Size = cast<ConstantInt>(MSI->getLength())->getZExtValue();
00232     addRange(OffsetFromFirst, Size, MSI->getDest(), MSI->getAlignment(), MSI);
00233   }
00234 
00235   void addRange(int64_t Start, int64_t Size, Value *Ptr,
00236                 unsigned Alignment, Instruction *Inst);
00237 
00238 };
00239 
00240 } // end anon namespace
00241 
00242 
00243 /// addRange - Add a new store to the MemsetRanges data structure.  This adds a
00244 /// new range for the specified store at the specified offset, merging into
00245 /// existing ranges as appropriate.
00246 ///
00247 /// Do a linear search of the ranges to see if this can be joined and/or to
00248 /// find the insertion point in the list.  We keep the ranges sorted for
00249 /// simplicity here.  This is a linear search of a linked list, which is ugly,
00250 /// however the number of ranges is limited, so this won't get crazy slow.
00251 void MemsetRanges::addRange(int64_t Start, int64_t Size, Value *Ptr,
00252                             unsigned Alignment, Instruction *Inst) {
00253   int64_t End = Start+Size;
00254   range_iterator I = Ranges.begin(), E = Ranges.end();
00255 
00256   while (I != E && Start > I->End)
00257     ++I;
00258 
00259   // We now know that I == E, in which case we didn't find anything to merge
00260   // with, or that Start <= I->End.  If End < I->Start or I == E, then we need
00261   // to insert a new range.  Handle this now.
00262   if (I == E || End < I->Start) {
00263     MemsetRange &R = *Ranges.insert(I, MemsetRange());
00264     R.Start        = Start;
00265     R.End          = End;
00266     R.StartPtr     = Ptr;
00267     R.Alignment    = Alignment;
00268     R.TheStores.push_back(Inst);
00269     return;
00270   }
00271 
00272   // This store overlaps with I, add it.
00273   I->TheStores.push_back(Inst);
00274 
00275   // At this point, we may have an interval that completely contains our store.
00276   // If so, just add it to the interval and return.
00277   if (I->Start <= Start && I->End >= End)
00278     return;
00279 
00280   // Now we know that Start <= I->End and End >= I->Start so the range overlaps
00281   // but is not entirely contained within the range.
00282 
00283   // See if the range extends the start of the range.  In this case, it couldn't
00284   // possibly cause it to join the prior range, because otherwise we would have
00285   // stopped on *it*.
00286   if (Start < I->Start) {
00287     I->Start = Start;
00288     I->StartPtr = Ptr;
00289     I->Alignment = Alignment;
00290   }
00291 
00292   // Now we know that Start <= I->End and Start >= I->Start (so the startpoint
00293   // is in or right at the end of I), and that End >= I->Start.  Extend I out to
00294   // End.
00295   if (End > I->End) {
00296     I->End = End;
00297     range_iterator NextI = I;
00298     while (++NextI != E && End >= NextI->Start) {
00299       // Merge the range in.
00300       I->TheStores.append(NextI->TheStores.begin(), NextI->TheStores.end());
00301       if (NextI->End > I->End)
00302         I->End = NextI->End;
00303       Ranges.erase(NextI);
00304       NextI = I;
00305     }
00306   }
00307 }
00308 
00309 //===----------------------------------------------------------------------===//
00310 //                         MemCpyOpt Pass
00311 //===----------------------------------------------------------------------===//
00312 
00313 namespace {
00314   class MemCpyOpt : public FunctionPass {
00315     MemoryDependenceAnalysis *MD;
00316     TargetLibraryInfo *TLI;
00317     const DataLayout *DL;
00318   public:
00319     static char ID; // Pass identification, replacement for typeid
00320     MemCpyOpt() : FunctionPass(ID) {
00321       initializeMemCpyOptPass(*PassRegistry::getPassRegistry());
00322       MD = nullptr;
00323       TLI = nullptr;
00324       DL = nullptr;
00325     }
00326 
00327     bool runOnFunction(Function &F) override;
00328 
00329   private:
00330     // This transformation requires dominator postdominator info
00331     void getAnalysisUsage(AnalysisUsage &AU) const override {
00332       AU.setPreservesCFG();
00333       AU.addRequired<AssumptionTracker>();
00334       AU.addRequired<DominatorTreeWrapperPass>();
00335       AU.addRequired<MemoryDependenceAnalysis>();
00336       AU.addRequired<AliasAnalysis>();
00337       AU.addRequired<TargetLibraryInfo>();
00338       AU.addPreserved<AliasAnalysis>();
00339       AU.addPreserved<MemoryDependenceAnalysis>();
00340     }
00341 
00342     // Helper fuctions
00343     bool processStore(StoreInst *SI, BasicBlock::iterator &BBI);
00344     bool processMemSet(MemSetInst *SI, BasicBlock::iterator &BBI);
00345     bool processMemCpy(MemCpyInst *M);
00346     bool processMemMove(MemMoveInst *M);
00347     bool performCallSlotOptzn(Instruction *cpy, Value *cpyDst, Value *cpySrc,
00348                               uint64_t cpyLen, unsigned cpyAlign, CallInst *C);
00349     bool processMemCpyMemCpyDependence(MemCpyInst *M, MemCpyInst *MDep,
00350                                        uint64_t MSize);
00351     bool processByValArgument(CallSite CS, unsigned ArgNo);
00352     Instruction *tryMergingIntoMemset(Instruction *I, Value *StartPtr,
00353                                       Value *ByteVal);
00354 
00355     bool iterateOnFunction(Function &F);
00356   };
00357 
00358   char MemCpyOpt::ID = 0;
00359 }
00360 
00361 // createMemCpyOptPass - The public interface to this file...
00362 FunctionPass *llvm::createMemCpyOptPass() { return new MemCpyOpt(); }
00363 
00364 INITIALIZE_PASS_BEGIN(MemCpyOpt, "memcpyopt", "MemCpy Optimization",
00365                       false, false)
00366 INITIALIZE_PASS_DEPENDENCY(AssumptionTracker)
00367 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
00368 INITIALIZE_PASS_DEPENDENCY(MemoryDependenceAnalysis)
00369 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
00370 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
00371 INITIALIZE_PASS_END(MemCpyOpt, "memcpyopt", "MemCpy Optimization",
00372                     false, false)
00373 
00374 /// tryMergingIntoMemset - When scanning forward over instructions, we look for
00375 /// some other patterns to fold away.  In particular, this looks for stores to
00376 /// neighboring locations of memory.  If it sees enough consecutive ones, it
00377 /// attempts to merge them together into a memcpy/memset.
00378 Instruction *MemCpyOpt::tryMergingIntoMemset(Instruction *StartInst,
00379                                              Value *StartPtr, Value *ByteVal) {
00380   if (!DL) return nullptr;
00381 
00382   // Okay, so we now have a single store that can be splatable.  Scan to find
00383   // all subsequent stores of the same value to offset from the same pointer.
00384   // Join these together into ranges, so we can decide whether contiguous blocks
00385   // are stored.
00386   MemsetRanges Ranges(*DL);
00387 
00388   BasicBlock::iterator BI = StartInst;
00389   for (++BI; !isa<TerminatorInst>(BI); ++BI) {
00390     if (!isa<StoreInst>(BI) && !isa<MemSetInst>(BI)) {
00391       // If the instruction is readnone, ignore it, otherwise bail out.  We
00392       // don't even allow readonly here because we don't want something like:
00393       // A[1] = 2; strlen(A); A[2] = 2; -> memcpy(A, ...); strlen(A).
00394       if (BI->mayWriteToMemory() || BI->mayReadFromMemory())
00395         break;
00396       continue;
00397     }
00398 
00399     if (StoreInst *NextStore = dyn_cast<StoreInst>(BI)) {
00400       // If this is a store, see if we can merge it in.
00401       if (!NextStore->isSimple()) break;
00402 
00403       // Check to see if this stored value is of the same byte-splattable value.
00404       if (ByteVal != isBytewiseValue(NextStore->getOperand(0)))
00405         break;
00406 
00407       // Check to see if this store is to a constant offset from the start ptr.
00408       int64_t Offset;
00409       if (!IsPointerOffset(StartPtr, NextStore->getPointerOperand(),
00410                            Offset, *DL))
00411         break;
00412 
00413       Ranges.addStore(Offset, NextStore);
00414     } else {
00415       MemSetInst *MSI = cast<MemSetInst>(BI);
00416 
00417       if (MSI->isVolatile() || ByteVal != MSI->getValue() ||
00418           !isa<ConstantInt>(MSI->getLength()))
00419         break;
00420 
00421       // Check to see if this store is to a constant offset from the start ptr.
00422       int64_t Offset;
00423       if (!IsPointerOffset(StartPtr, MSI->getDest(), Offset, *DL))
00424         break;
00425 
00426       Ranges.addMemSet(Offset, MSI);
00427     }
00428   }
00429 
00430   // If we have no ranges, then we just had a single store with nothing that
00431   // could be merged in.  This is a very common case of course.
00432   if (Ranges.empty())
00433     return nullptr;
00434 
00435   // If we had at least one store that could be merged in, add the starting
00436   // store as well.  We try to avoid this unless there is at least something
00437   // interesting as a small compile-time optimization.
00438   Ranges.addInst(0, StartInst);
00439 
00440   // If we create any memsets, we put it right before the first instruction that
00441   // isn't part of the memset block.  This ensure that the memset is dominated
00442   // by any addressing instruction needed by the start of the block.
00443   IRBuilder<> Builder(BI);
00444 
00445   // Now that we have full information about ranges, loop over the ranges and
00446   // emit memset's for anything big enough to be worthwhile.
00447   Instruction *AMemSet = nullptr;
00448   for (MemsetRanges::const_iterator I = Ranges.begin(), E = Ranges.end();
00449        I != E; ++I) {
00450     const MemsetRange &Range = *I;
00451 
00452     if (Range.TheStores.size() == 1) continue;
00453 
00454     // If it is profitable to lower this range to memset, do so now.
00455     if (!Range.isProfitableToUseMemset(*DL))
00456       continue;
00457 
00458     // Otherwise, we do want to transform this!  Create a new memset.
00459     // Get the starting pointer of the block.
00460     StartPtr = Range.StartPtr;
00461 
00462     // Determine alignment
00463     unsigned Alignment = Range.Alignment;
00464     if (Alignment == 0) {
00465       Type *EltType =
00466         cast<PointerType>(StartPtr->getType())->getElementType();
00467       Alignment = DL->getABITypeAlignment(EltType);
00468     }
00469 
00470     AMemSet =
00471       Builder.CreateMemSet(StartPtr, ByteVal, Range.End-Range.Start, Alignment);
00472 
00473     DEBUG(dbgs() << "Replace stores:\n";
00474           for (unsigned i = 0, e = Range.TheStores.size(); i != e; ++i)
00475             dbgs() << *Range.TheStores[i] << '\n';
00476           dbgs() << "With: " << *AMemSet << '\n');
00477 
00478     if (!Range.TheStores.empty())
00479       AMemSet->setDebugLoc(Range.TheStores[0]->getDebugLoc());
00480 
00481     // Zap all the stores.
00482     for (SmallVectorImpl<Instruction *>::const_iterator
00483          SI = Range.TheStores.begin(),
00484          SE = Range.TheStores.end(); SI != SE; ++SI) {
00485       MD->removeInstruction(*SI);
00486       (*SI)->eraseFromParent();
00487     }
00488     ++NumMemSetInfer;
00489   }
00490 
00491   return AMemSet;
00492 }
00493 
00494 
00495 bool MemCpyOpt::processStore(StoreInst *SI, BasicBlock::iterator &BBI) {
00496   if (!SI->isSimple()) return false;
00497 
00498   if (!DL) return false;
00499 
00500   // Detect cases where we're performing call slot forwarding, but
00501   // happen to be using a load-store pair to implement it, rather than
00502   // a memcpy.
00503   if (LoadInst *LI = dyn_cast<LoadInst>(SI->getOperand(0))) {
00504     if (LI->isSimple() && LI->hasOneUse() &&
00505         LI->getParent() == SI->getParent()) {
00506       MemDepResult ldep = MD->getDependency(LI);
00507       CallInst *C = nullptr;
00508       if (ldep.isClobber() && !isa<MemCpyInst>(ldep.getInst()))
00509         C = dyn_cast<CallInst>(ldep.getInst());
00510 
00511       if (C) {
00512         // Check that nothing touches the dest of the "copy" between
00513         // the call and the store.
00514         AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
00515         AliasAnalysis::Location StoreLoc = AA.getLocation(SI);
00516         for (BasicBlock::iterator I = --BasicBlock::iterator(SI),
00517                                   E = C; I != E; --I) {
00518           if (AA.getModRefInfo(&*I, StoreLoc) != AliasAnalysis::NoModRef) {
00519             C = nullptr;
00520             break;
00521           }
00522         }
00523       }
00524 
00525       if (C) {
00526         unsigned storeAlign = SI->getAlignment();
00527         if (!storeAlign)
00528           storeAlign = DL->getABITypeAlignment(SI->getOperand(0)->getType());
00529         unsigned loadAlign = LI->getAlignment();
00530         if (!loadAlign)
00531           loadAlign = DL->getABITypeAlignment(LI->getType());
00532 
00533         bool changed = performCallSlotOptzn(LI,
00534                         SI->getPointerOperand()->stripPointerCasts(),
00535                         LI->getPointerOperand()->stripPointerCasts(),
00536                         DL->getTypeStoreSize(SI->getOperand(0)->getType()),
00537                         std::min(storeAlign, loadAlign), C);
00538         if (changed) {
00539           MD->removeInstruction(SI);
00540           SI->eraseFromParent();
00541           MD->removeInstruction(LI);
00542           LI->eraseFromParent();
00543           ++NumMemCpyInstr;
00544           return true;
00545         }
00546       }
00547     }
00548   }
00549 
00550   // There are two cases that are interesting for this code to handle: memcpy
00551   // and memset.  Right now we only handle memset.
00552 
00553   // Ensure that the value being stored is something that can be memset'able a
00554   // byte at a time like "0" or "-1" or any width, as well as things like
00555   // 0xA0A0A0A0 and 0.0.
00556   if (Value *ByteVal = isBytewiseValue(SI->getOperand(0)))
00557     if (Instruction *I = tryMergingIntoMemset(SI, SI->getPointerOperand(),
00558                                               ByteVal)) {
00559       BBI = I;  // Don't invalidate iterator.
00560       return true;
00561     }
00562 
00563   return false;
00564 }
00565 
00566 bool MemCpyOpt::processMemSet(MemSetInst *MSI, BasicBlock::iterator &BBI) {
00567   // See if there is another memset or store neighboring this memset which
00568   // allows us to widen out the memset to do a single larger store.
00569   if (isa<ConstantInt>(MSI->getLength()) && !MSI->isVolatile())
00570     if (Instruction *I = tryMergingIntoMemset(MSI, MSI->getDest(),
00571                                               MSI->getValue())) {
00572       BBI = I;  // Don't invalidate iterator.
00573       return true;
00574     }
00575   return false;
00576 }
00577 
00578 
00579 /// performCallSlotOptzn - takes a memcpy and a call that it depends on,
00580 /// and checks for the possibility of a call slot optimization by having
00581 /// the call write its result directly into the destination of the memcpy.
00582 bool MemCpyOpt::performCallSlotOptzn(Instruction *cpy,
00583                                      Value *cpyDest, Value *cpySrc,
00584                                      uint64_t cpyLen, unsigned cpyAlign,
00585                                      CallInst *C) {
00586   // The general transformation to keep in mind is
00587   //
00588   //   call @func(..., src, ...)
00589   //   memcpy(dest, src, ...)
00590   //
00591   // ->
00592   //
00593   //   memcpy(dest, src, ...)
00594   //   call @func(..., dest, ...)
00595   //
00596   // Since moving the memcpy is technically awkward, we additionally check that
00597   // src only holds uninitialized values at the moment of the call, meaning that
00598   // the memcpy can be discarded rather than moved.
00599 
00600   // Deliberately get the source and destination with bitcasts stripped away,
00601   // because we'll need to do type comparisons based on the underlying type.
00602   CallSite CS(C);
00603 
00604   // Require that src be an alloca.  This simplifies the reasoning considerably.
00605   AllocaInst *srcAlloca = dyn_cast<AllocaInst>(cpySrc);
00606   if (!srcAlloca)
00607     return false;
00608 
00609   // Check that all of src is copied to dest.
00610   if (!DL) return false;
00611 
00612   ConstantInt *srcArraySize = dyn_cast<ConstantInt>(srcAlloca->getArraySize());
00613   if (!srcArraySize)
00614     return false;
00615 
00616   uint64_t srcSize = DL->getTypeAllocSize(srcAlloca->getAllocatedType()) *
00617     srcArraySize->getZExtValue();
00618 
00619   if (cpyLen < srcSize)
00620     return false;
00621 
00622   // Check that accessing the first srcSize bytes of dest will not cause a
00623   // trap.  Otherwise the transform is invalid since it might cause a trap
00624   // to occur earlier than it otherwise would.
00625   if (AllocaInst *A = dyn_cast<AllocaInst>(cpyDest)) {
00626     // The destination is an alloca.  Check it is larger than srcSize.
00627     ConstantInt *destArraySize = dyn_cast<ConstantInt>(A->getArraySize());
00628     if (!destArraySize)
00629       return false;
00630 
00631     uint64_t destSize = DL->getTypeAllocSize(A->getAllocatedType()) *
00632       destArraySize->getZExtValue();
00633 
00634     if (destSize < srcSize)
00635       return false;
00636   } else if (Argument *A = dyn_cast<Argument>(cpyDest)) {
00637     if (A->getDereferenceableBytes() < srcSize) {
00638       // If the destination is an sret parameter then only accesses that are
00639       // outside of the returned struct type can trap.
00640       if (!A->hasStructRetAttr())
00641         return false;
00642 
00643       Type *StructTy = cast<PointerType>(A->getType())->getElementType();
00644       if (!StructTy->isSized()) {
00645         // The call may never return and hence the copy-instruction may never
00646         // be executed, and therefore it's not safe to say "the destination
00647         // has at least <cpyLen> bytes, as implied by the copy-instruction",
00648         return false;
00649       }
00650 
00651       uint64_t destSize = DL->getTypeAllocSize(StructTy);
00652       if (destSize < srcSize)
00653         return false;
00654     }
00655   } else {
00656     return false;
00657   }
00658 
00659   // Check that dest points to memory that is at least as aligned as src.
00660   unsigned srcAlign = srcAlloca->getAlignment();
00661   if (!srcAlign)
00662     srcAlign = DL->getABITypeAlignment(srcAlloca->getAllocatedType());
00663   bool isDestSufficientlyAligned = srcAlign <= cpyAlign;
00664   // If dest is not aligned enough and we can't increase its alignment then
00665   // bail out.
00666   if (!isDestSufficientlyAligned && !isa<AllocaInst>(cpyDest))
00667     return false;
00668 
00669   // Check that src is not accessed except via the call and the memcpy.  This
00670   // guarantees that it holds only undefined values when passed in (so the final
00671   // memcpy can be dropped), that it is not read or written between the call and
00672   // the memcpy, and that writing beyond the end of it is undefined.
00673   SmallVector<User*, 8> srcUseList(srcAlloca->user_begin(),
00674                                    srcAlloca->user_end());
00675   while (!srcUseList.empty()) {
00676     User *U = srcUseList.pop_back_val();
00677 
00678     if (isa<BitCastInst>(U) || isa<AddrSpaceCastInst>(U)) {
00679       for (User *UU : U->users())
00680         srcUseList.push_back(UU);
00681       continue;
00682     }
00683     if (GetElementPtrInst *G = dyn_cast<GetElementPtrInst>(U)) {
00684       if (!G->hasAllZeroIndices())
00685         return false;
00686 
00687       for (User *UU : U->users())
00688         srcUseList.push_back(UU);
00689       continue;
00690     }
00691     if (const IntrinsicInst *IT = dyn_cast<IntrinsicInst>(U))
00692       if (IT->getIntrinsicID() == Intrinsic::lifetime_start ||
00693           IT->getIntrinsicID() == Intrinsic::lifetime_end)
00694         continue;
00695 
00696     if (U != C && U != cpy)
00697       return false;
00698   }
00699 
00700   // Check that src isn't captured by the called function since the
00701   // transformation can cause aliasing issues in that case.
00702   for (unsigned i = 0, e = CS.arg_size(); i != e; ++i)
00703     if (CS.getArgument(i) == cpySrc && !CS.doesNotCapture(i))
00704       return false;
00705 
00706   // Since we're changing the parameter to the callsite, we need to make sure
00707   // that what would be the new parameter dominates the callsite.
00708   DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
00709   if (Instruction *cpyDestInst = dyn_cast<Instruction>(cpyDest))
00710     if (!DT.dominates(cpyDestInst, C))
00711       return false;
00712 
00713   // In addition to knowing that the call does not access src in some
00714   // unexpected manner, for example via a global, which we deduce from
00715   // the use analysis, we also need to know that it does not sneakily
00716   // access dest.  We rely on AA to figure this out for us.
00717   AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
00718   AliasAnalysis::ModRefResult MR = AA.getModRefInfo(C, cpyDest, srcSize);
00719   // If necessary, perform additional analysis.
00720   if (MR != AliasAnalysis::NoModRef)
00721     MR = AA.callCapturesBefore(C, cpyDest, srcSize, &DT);
00722   if (MR != AliasAnalysis::NoModRef)
00723     return false;
00724 
00725   // All the checks have passed, so do the transformation.
00726   bool changedArgument = false;
00727   for (unsigned i = 0; i < CS.arg_size(); ++i)
00728     if (CS.getArgument(i)->stripPointerCasts() == cpySrc) {
00729       Value *Dest = cpySrc->getType() == cpyDest->getType() ?  cpyDest
00730         : CastInst::CreatePointerCast(cpyDest, cpySrc->getType(),
00731                                       cpyDest->getName(), C);
00732       changedArgument = true;
00733       if (CS.getArgument(i)->getType() == Dest->getType())
00734         CS.setArgument(i, Dest);
00735       else
00736         CS.setArgument(i, CastInst::CreatePointerCast(Dest,
00737                           CS.getArgument(i)->getType(), Dest->getName(), C));
00738     }
00739 
00740   if (!changedArgument)
00741     return false;
00742 
00743   // If the destination wasn't sufficiently aligned then increase its alignment.
00744   if (!isDestSufficientlyAligned) {
00745     assert(isa<AllocaInst>(cpyDest) && "Can only increase alloca alignment!");
00746     cast<AllocaInst>(cpyDest)->setAlignment(srcAlign);
00747   }
00748 
00749   // Drop any cached information about the call, because we may have changed
00750   // its dependence information by changing its parameter.
00751   MD->removeInstruction(C);
00752 
00753   // Remove the memcpy.
00754   MD->removeInstruction(cpy);
00755   ++NumMemCpyInstr;
00756 
00757   return true;
00758 }
00759 
00760 /// processMemCpyMemCpyDependence - We've found that the (upward scanning)
00761 /// memory dependence of memcpy 'M' is the memcpy 'MDep'.  Try to simplify M to
00762 /// copy from MDep's input if we can.  MSize is the size of M's copy.
00763 ///
00764 bool MemCpyOpt::processMemCpyMemCpyDependence(MemCpyInst *M, MemCpyInst *MDep,
00765                                               uint64_t MSize) {
00766   // We can only transforms memcpy's where the dest of one is the source of the
00767   // other.
00768   if (M->getSource() != MDep->getDest() || MDep->isVolatile())
00769     return false;
00770 
00771   // If dep instruction is reading from our current input, then it is a noop
00772   // transfer and substituting the input won't change this instruction.  Just
00773   // ignore the input and let someone else zap MDep.  This handles cases like:
00774   //    memcpy(a <- a)
00775   //    memcpy(b <- a)
00776   if (M->getSource() == MDep->getSource())
00777     return false;
00778 
00779   // Second, the length of the memcpy's must be the same, or the preceding one
00780   // must be larger than the following one.
00781   ConstantInt *MDepLen = dyn_cast<ConstantInt>(MDep->getLength());
00782   ConstantInt *MLen = dyn_cast<ConstantInt>(M->getLength());
00783   if (!MDepLen || !MLen || MDepLen->getZExtValue() < MLen->getZExtValue())
00784     return false;
00785 
00786   AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
00787 
00788   // Verify that the copied-from memory doesn't change in between the two
00789   // transfers.  For example, in:
00790   //    memcpy(a <- b)
00791   //    *b = 42;
00792   //    memcpy(c <- a)
00793   // It would be invalid to transform the second memcpy into memcpy(c <- b).
00794   //
00795   // TODO: If the code between M and MDep is transparent to the destination "c",
00796   // then we could still perform the xform by moving M up to the first memcpy.
00797   //
00798   // NOTE: This is conservative, it will stop on any read from the source loc,
00799   // not just the defining memcpy.
00800   MemDepResult SourceDep =
00801     MD->getPointerDependencyFrom(AA.getLocationForSource(MDep),
00802                                  false, M, M->getParent());
00803   if (!SourceDep.isClobber() || SourceDep.getInst() != MDep)
00804     return false;
00805 
00806   // If the dest of the second might alias the source of the first, then the
00807   // source and dest might overlap.  We still want to eliminate the intermediate
00808   // value, but we have to generate a memmove instead of memcpy.
00809   bool UseMemMove = false;
00810   if (!AA.isNoAlias(AA.getLocationForDest(M), AA.getLocationForSource(MDep)))
00811     UseMemMove = true;
00812 
00813   // If all checks passed, then we can transform M.
00814 
00815   // Make sure to use the lesser of the alignment of the source and the dest
00816   // since we're changing where we're reading from, but don't want to increase
00817   // the alignment past what can be read from or written to.
00818   // TODO: Is this worth it if we're creating a less aligned memcpy? For
00819   // example we could be moving from movaps -> movq on x86.
00820   unsigned Align = std::min(MDep->getAlignment(), M->getAlignment());
00821 
00822   IRBuilder<> Builder(M);
00823   if (UseMemMove)
00824     Builder.CreateMemMove(M->getRawDest(), MDep->getRawSource(), M->getLength(),
00825                           Align, M->isVolatile());
00826   else
00827     Builder.CreateMemCpy(M->getRawDest(), MDep->getRawSource(), M->getLength(),
00828                          Align, M->isVolatile());
00829 
00830   // Remove the instruction we're replacing.
00831   MD->removeInstruction(M);
00832   M->eraseFromParent();
00833   ++NumMemCpyInstr;
00834   return true;
00835 }
00836 
00837 
00838 /// processMemCpy - perform simplification of memcpy's.  If we have memcpy A
00839 /// which copies X to Y, and memcpy B which copies Y to Z, then we can rewrite
00840 /// B to be a memcpy from X to Z (or potentially a memmove, depending on
00841 /// circumstances). This allows later passes to remove the first memcpy
00842 /// altogether.
00843 bool MemCpyOpt::processMemCpy(MemCpyInst *M) {
00844   // We can only optimize non-volatile memcpy's.
00845   if (M->isVolatile()) return false;
00846 
00847   // If the source and destination of the memcpy are the same, then zap it.
00848   if (M->getSource() == M->getDest()) {
00849     MD->removeInstruction(M);
00850     M->eraseFromParent();
00851     return false;
00852   }
00853 
00854   // If copying from a constant, try to turn the memcpy into a memset.
00855   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(M->getSource()))
00856     if (GV->isConstant() && GV->hasDefinitiveInitializer())
00857       if (Value *ByteVal = isBytewiseValue(GV->getInitializer())) {
00858         IRBuilder<> Builder(M);
00859         Builder.CreateMemSet(M->getRawDest(), ByteVal, M->getLength(),
00860                              M->getAlignment(), false);
00861         MD->removeInstruction(M);
00862         M->eraseFromParent();
00863         ++NumCpyToSet;
00864         return true;
00865       }
00866 
00867   // The optimizations after this point require the memcpy size.
00868   ConstantInt *CopySize = dyn_cast<ConstantInt>(M->getLength());
00869   if (!CopySize) return false;
00870 
00871   // The are three possible optimizations we can do for memcpy:
00872   //   a) memcpy-memcpy xform which exposes redundance for DSE.
00873   //   b) call-memcpy xform for return slot optimization.
00874   //   c) memcpy from freshly alloca'd space or space that has just started its
00875   //      lifetime copies undefined data, and we can therefore eliminate the
00876   //      memcpy in favor of the data that was already at the destination.
00877   MemDepResult DepInfo = MD->getDependency(M);
00878   if (DepInfo.isClobber()) {
00879     if (CallInst *C = dyn_cast<CallInst>(DepInfo.getInst())) {
00880       if (performCallSlotOptzn(M, M->getDest(), M->getSource(),
00881                                CopySize->getZExtValue(), M->getAlignment(),
00882                                C)) {
00883         MD->removeInstruction(M);
00884         M->eraseFromParent();
00885         return true;
00886       }
00887     }
00888   }
00889 
00890   AliasAnalysis::Location SrcLoc = AliasAnalysis::getLocationForSource(M);
00891   MemDepResult SrcDepInfo = MD->getPointerDependencyFrom(SrcLoc, true,
00892                                                          M, M->getParent());
00893   if (SrcDepInfo.isClobber()) {
00894     if (MemCpyInst *MDep = dyn_cast<MemCpyInst>(SrcDepInfo.getInst()))
00895       return processMemCpyMemCpyDependence(M, MDep, CopySize->getZExtValue());
00896   } else if (SrcDepInfo.isDef()) {
00897     Instruction *I = SrcDepInfo.getInst();
00898     bool hasUndefContents = false;
00899 
00900     if (isa<AllocaInst>(I)) {
00901       hasUndefContents = true;
00902     } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
00903       if (II->getIntrinsicID() == Intrinsic::lifetime_start)
00904         if (ConstantInt *LTSize = dyn_cast<ConstantInt>(II->getArgOperand(0)))
00905           if (LTSize->getZExtValue() >= CopySize->getZExtValue())
00906             hasUndefContents = true;
00907     }
00908 
00909     if (hasUndefContents) {
00910       MD->removeInstruction(M);
00911       M->eraseFromParent();
00912       ++NumMemCpyInstr;
00913       return true;
00914     }
00915   }
00916 
00917   return false;
00918 }
00919 
00920 /// processMemMove - Transforms memmove calls to memcpy calls when the src/dst
00921 /// are guaranteed not to alias.
00922 bool MemCpyOpt::processMemMove(MemMoveInst *M) {
00923   AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
00924 
00925   if (!TLI->has(LibFunc::memmove))
00926     return false;
00927 
00928   // See if the pointers alias.
00929   if (!AA.isNoAlias(AA.getLocationForDest(M), AA.getLocationForSource(M)))
00930     return false;
00931 
00932   DEBUG(dbgs() << "MemCpyOpt: Optimizing memmove -> memcpy: " << *M << "\n");
00933 
00934   // If not, then we know we can transform this.
00935   Module *Mod = M->getParent()->getParent()->getParent();
00936   Type *ArgTys[3] = { M->getRawDest()->getType(),
00937                       M->getRawSource()->getType(),
00938                       M->getLength()->getType() };
00939   M->setCalledFunction(Intrinsic::getDeclaration(Mod, Intrinsic::memcpy,
00940                                                  ArgTys));
00941 
00942   // MemDep may have over conservative information about this instruction, just
00943   // conservatively flush it from the cache.
00944   MD->removeInstruction(M);
00945 
00946   ++NumMoveToCpy;
00947   return true;
00948 }
00949 
00950 /// processByValArgument - This is called on every byval argument in call sites.
00951 bool MemCpyOpt::processByValArgument(CallSite CS, unsigned ArgNo) {
00952   if (!DL) return false;
00953 
00954   // Find out what feeds this byval argument.
00955   Value *ByValArg = CS.getArgument(ArgNo);
00956   Type *ByValTy = cast<PointerType>(ByValArg->getType())->getElementType();
00957   uint64_t ByValSize = DL->getTypeAllocSize(ByValTy);
00958   MemDepResult DepInfo =
00959     MD->getPointerDependencyFrom(AliasAnalysis::Location(ByValArg, ByValSize),
00960                                  true, CS.getInstruction(),
00961                                  CS.getInstruction()->getParent());
00962   if (!DepInfo.isClobber())
00963     return false;
00964 
00965   // If the byval argument isn't fed by a memcpy, ignore it.  If it is fed by
00966   // a memcpy, see if we can byval from the source of the memcpy instead of the
00967   // result.
00968   MemCpyInst *MDep = dyn_cast<MemCpyInst>(DepInfo.getInst());
00969   if (!MDep || MDep->isVolatile() ||
00970       ByValArg->stripPointerCasts() != MDep->getDest())
00971     return false;
00972 
00973   // The length of the memcpy must be larger or equal to the size of the byval.
00974   ConstantInt *C1 = dyn_cast<ConstantInt>(MDep->getLength());
00975   if (!C1 || C1->getValue().getZExtValue() < ByValSize)
00976     return false;
00977 
00978   // Get the alignment of the byval.  If the call doesn't specify the alignment,
00979   // then it is some target specific value that we can't know.
00980   unsigned ByValAlign = CS.getParamAlignment(ArgNo+1);
00981   if (ByValAlign == 0) return false;
00982 
00983   // If it is greater than the memcpy, then we check to see if we can force the
00984   // source of the memcpy to the alignment we need.  If we fail, we bail out.
00985   AssumptionTracker *AT = &getAnalysis<AssumptionTracker>();
00986   DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
00987   if (MDep->getAlignment() < ByValAlign &&
00988       getOrEnforceKnownAlignment(MDep->getSource(),ByValAlign,
00989                                  DL, AT, CS.getInstruction(), &DT) < ByValAlign)
00990     return false;
00991 
00992   // Verify that the copied-from memory doesn't change in between the memcpy and
00993   // the byval call.
00994   //    memcpy(a <- b)
00995   //    *b = 42;
00996   //    foo(*a)
00997   // It would be invalid to transform the second memcpy into foo(*b).
00998   //
00999   // NOTE: This is conservative, it will stop on any read from the source loc,
01000   // not just the defining memcpy.
01001   MemDepResult SourceDep =
01002     MD->getPointerDependencyFrom(AliasAnalysis::getLocationForSource(MDep),
01003                                  false, CS.getInstruction(), MDep->getParent());
01004   if (!SourceDep.isClobber() || SourceDep.getInst() != MDep)
01005     return false;
01006 
01007   Value *TmpCast = MDep->getSource();
01008   if (MDep->getSource()->getType() != ByValArg->getType())
01009     TmpCast = new BitCastInst(MDep->getSource(), ByValArg->getType(),
01010                               "tmpcast", CS.getInstruction());
01011 
01012   DEBUG(dbgs() << "MemCpyOpt: Forwarding memcpy to byval:\n"
01013                << "  " << *MDep << "\n"
01014                << "  " << *CS.getInstruction() << "\n");
01015 
01016   // Otherwise we're good!  Update the byval argument.
01017   CS.setArgument(ArgNo, TmpCast);
01018   ++NumMemCpyInstr;
01019   return true;
01020 }
01021 
01022 /// iterateOnFunction - Executes one iteration of MemCpyOpt.
01023 bool MemCpyOpt::iterateOnFunction(Function &F) {
01024   bool MadeChange = false;
01025 
01026   // Walk all instruction in the function.
01027   for (Function::iterator BB = F.begin(), BBE = F.end(); BB != BBE; ++BB) {
01028     for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE;) {
01029       // Avoid invalidating the iterator.
01030       Instruction *I = BI++;
01031 
01032       bool RepeatInstruction = false;
01033 
01034       if (StoreInst *SI = dyn_cast<StoreInst>(I))
01035         MadeChange |= processStore(SI, BI);
01036       else if (MemSetInst *M = dyn_cast<MemSetInst>(I))
01037         RepeatInstruction = processMemSet(M, BI);
01038       else if (MemCpyInst *M = dyn_cast<MemCpyInst>(I))
01039         RepeatInstruction = processMemCpy(M);
01040       else if (MemMoveInst *M = dyn_cast<MemMoveInst>(I))
01041         RepeatInstruction = processMemMove(M);
01042       else if (CallSite CS = (Value*)I) {
01043         for (unsigned i = 0, e = CS.arg_size(); i != e; ++i)
01044           if (CS.isByValArgument(i))
01045             MadeChange |= processByValArgument(CS, i);
01046       }
01047 
01048       // Reprocess the instruction if desired.
01049       if (RepeatInstruction) {
01050         if (BI != BB->begin()) --BI;
01051         MadeChange = true;
01052       }
01053     }
01054   }
01055 
01056   return MadeChange;
01057 }
01058 
01059 // MemCpyOpt::runOnFunction - This is the main transformation entry point for a
01060 // function.
01061 //
01062 bool MemCpyOpt::runOnFunction(Function &F) {
01063   if (skipOptnoneFunction(F))
01064     return false;
01065 
01066   bool MadeChange = false;
01067   MD = &getAnalysis<MemoryDependenceAnalysis>();
01068   DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
01069   DL = DLP ? &DLP->getDataLayout() : nullptr;
01070   TLI = &getAnalysis<TargetLibraryInfo>();
01071 
01072   // If we don't have at least memset and memcpy, there is little point of doing
01073   // anything here.  These are required by a freestanding implementation, so if
01074   // even they are disabled, there is no point in trying hard.
01075   if (!TLI->has(LibFunc::memset) || !TLI->has(LibFunc::memcpy))
01076     return false;
01077 
01078   while (1) {
01079     if (!iterateOnFunction(F))
01080       break;
01081     MadeChange = true;
01082   }
01083 
01084   MD = nullptr;
01085   return MadeChange;
01086 }