LLVM  mainline
MemoryBuiltins.cpp
Go to the documentation of this file.
00001 //===------ MemoryBuiltins.cpp - Identify calls to memory builtins --------===//
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 family of functions identifies calls to builtin functions that allocate
00011 // or free memory.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 #include "llvm/Analysis/MemoryBuiltins.h"
00016 #include "llvm/ADT/STLExtras.h"
00017 #include "llvm/ADT/Statistic.h"
00018 #include "llvm/Analysis/TargetLibraryInfo.h"
00019 #include "llvm/Analysis/ValueTracking.h"
00020 #include "llvm/IR/DataLayout.h"
00021 #include "llvm/IR/GlobalVariable.h"
00022 #include "llvm/IR/Instructions.h"
00023 #include "llvm/IR/Intrinsics.h"
00024 #include "llvm/IR/Metadata.h"
00025 #include "llvm/IR/Module.h"
00026 #include "llvm/Support/Debug.h"
00027 #include "llvm/Support/MathExtras.h"
00028 #include "llvm/Support/raw_ostream.h"
00029 #include "llvm/Transforms/Utils/Local.h"
00030 using namespace llvm;
00031 
00032 #define DEBUG_TYPE "memory-builtins"
00033 
00034 enum AllocType : uint8_t {
00035   OpNewLike          = 1<<0, // allocates; never returns null
00036   MallocLike         = 1<<1 | OpNewLike, // allocates; may return null
00037   CallocLike         = 1<<2, // allocates + bzero
00038   ReallocLike        = 1<<3, // reallocates
00039   StrDupLike         = 1<<4,
00040   AllocLike          = MallocLike | CallocLike | StrDupLike,
00041   AnyAlloc           = AllocLike | ReallocLike
00042 };
00043 
00044 struct AllocFnsTy {
00045   LibFunc::Func Func;
00046   AllocType AllocTy;
00047   unsigned char NumParams;
00048   // First and Second size parameters (or -1 if unused)
00049   signed char FstParam, SndParam;
00050 };
00051 
00052 // FIXME: certain users need more information. E.g., SimplifyLibCalls needs to
00053 // know which functions are nounwind, noalias, nocapture parameters, etc.
00054 static const AllocFnsTy AllocationFnData[] = {
00055   {LibFunc::malloc,              MallocLike,  1, 0,  -1},
00056   {LibFunc::valloc,              MallocLike,  1, 0,  -1},
00057   {LibFunc::Znwj,                OpNewLike,   1, 0,  -1}, // new(unsigned int)
00058   {LibFunc::ZnwjRKSt9nothrow_t,  MallocLike,  2, 0,  -1}, // new(unsigned int, nothrow)
00059   {LibFunc::Znwm,                OpNewLike,   1, 0,  -1}, // new(unsigned long)
00060   {LibFunc::ZnwmRKSt9nothrow_t,  MallocLike,  2, 0,  -1}, // new(unsigned long, nothrow)
00061   {LibFunc::Znaj,                OpNewLike,   1, 0,  -1}, // new[](unsigned int)
00062   {LibFunc::ZnajRKSt9nothrow_t,  MallocLike,  2, 0,  -1}, // new[](unsigned int, nothrow)
00063   {LibFunc::Znam,                OpNewLike,   1, 0,  -1}, // new[](unsigned long)
00064   {LibFunc::ZnamRKSt9nothrow_t,  MallocLike,  2, 0,  -1}, // new[](unsigned long, nothrow)
00065   {LibFunc::msvc_new_int,         OpNewLike,   1, 0,  -1}, // new(unsigned int)
00066   {LibFunc::msvc_new_int_nothrow, MallocLike,  2, 0,  -1}, // new(unsigned int, nothrow)
00067   {LibFunc::msvc_new_longlong,         OpNewLike,   1, 0,  -1}, // new(unsigned long long)
00068   {LibFunc::msvc_new_longlong_nothrow, MallocLike,  2, 0,  -1}, // new(unsigned long long, nothrow)
00069   {LibFunc::msvc_new_array_int,         OpNewLike,   1, 0,  -1}, // new[](unsigned int)
00070   {LibFunc::msvc_new_array_int_nothrow, MallocLike,  2, 0,  -1}, // new[](unsigned int, nothrow)
00071   {LibFunc::msvc_new_array_longlong,         OpNewLike,   1, 0,  -1}, // new[](unsigned long long)
00072   {LibFunc::msvc_new_array_longlong_nothrow, MallocLike,  2, 0,  -1}, // new[](unsigned long long, nothrow)
00073   {LibFunc::calloc,              CallocLike,  2, 0,   1},
00074   {LibFunc::realloc,             ReallocLike, 2, 1,  -1},
00075   {LibFunc::reallocf,            ReallocLike, 2, 1,  -1},
00076   {LibFunc::strdup,              StrDupLike,  1, -1, -1},
00077   {LibFunc::strndup,             StrDupLike,  2, 1,  -1}
00078   // TODO: Handle "int posix_memalign(void **, size_t, size_t)"
00079 };
00080 
00081 
00082 static Function *getCalledFunction(const Value *V, bool LookThroughBitCast) {
00083   if (LookThroughBitCast)
00084     V = V->stripPointerCasts();
00085 
00086   CallSite CS(const_cast<Value*>(V));
00087   if (!CS.getInstruction())
00088     return nullptr;
00089 
00090   if (CS.isNoBuiltin())
00091     return nullptr;
00092 
00093   Function *Callee = CS.getCalledFunction();
00094   if (!Callee || !Callee->isDeclaration())
00095     return nullptr;
00096   return Callee;
00097 }
00098 
00099 /// \brief Returns the allocation data for the given value if it is a call to a
00100 /// known allocation function, and NULL otherwise.
00101 static const AllocFnsTy *getAllocationData(const Value *V, AllocType AllocTy,
00102                                            const TargetLibraryInfo *TLI,
00103                                            bool LookThroughBitCast = false) {
00104   // Skip intrinsics
00105   if (isa<IntrinsicInst>(V))
00106     return nullptr;
00107 
00108   Function *Callee = getCalledFunction(V, LookThroughBitCast);
00109   if (!Callee)
00110     return nullptr;
00111 
00112   // Make sure that the function is available.
00113   StringRef FnName = Callee->getName();
00114   LibFunc::Func TLIFn;
00115   if (!TLI || !TLI->getLibFunc(FnName, TLIFn) || !TLI->has(TLIFn))
00116     return nullptr;
00117 
00118   const AllocFnsTy *FnData =
00119       std::find_if(std::begin(AllocationFnData), std::end(AllocationFnData),
00120                    [TLIFn](const AllocFnsTy &Fn) { return Fn.Func == TLIFn; });
00121 
00122   if (FnData == std::end(AllocationFnData))
00123     return nullptr;
00124 
00125   if ((FnData->AllocTy & AllocTy) != FnData->AllocTy)
00126     return nullptr;
00127 
00128   // Check function prototype.
00129   int FstParam = FnData->FstParam;
00130   int SndParam = FnData->SndParam;
00131   FunctionType *FTy = Callee->getFunctionType();
00132 
00133   if (FTy->getReturnType() == Type::getInt8PtrTy(FTy->getContext()) &&
00134       FTy->getNumParams() == FnData->NumParams &&
00135       (FstParam < 0 ||
00136        (FTy->getParamType(FstParam)->isIntegerTy(32) ||
00137         FTy->getParamType(FstParam)->isIntegerTy(64))) &&
00138       (SndParam < 0 ||
00139        FTy->getParamType(SndParam)->isIntegerTy(32) ||
00140        FTy->getParamType(SndParam)->isIntegerTy(64)))
00141     return FnData;
00142   return nullptr;
00143 }
00144 
00145 static bool hasNoAliasAttr(const Value *V, bool LookThroughBitCast) {
00146   ImmutableCallSite CS(LookThroughBitCast ? V->stripPointerCasts() : V);
00147   return CS && CS.hasFnAttr(Attribute::NoAlias);
00148 }
00149 
00150 
00151 /// \brief Tests if a value is a call or invoke to a library function that
00152 /// allocates or reallocates memory (either malloc, calloc, realloc, or strdup
00153 /// like).
00154 bool llvm::isAllocationFn(const Value *V, const TargetLibraryInfo *TLI,
00155                           bool LookThroughBitCast) {
00156   return getAllocationData(V, AnyAlloc, TLI, LookThroughBitCast);
00157 }
00158 
00159 /// \brief Tests if a value is a call or invoke to a function that returns a
00160 /// NoAlias pointer (including malloc/calloc/realloc/strdup-like functions).
00161 bool llvm::isNoAliasFn(const Value *V, const TargetLibraryInfo *TLI,
00162                        bool LookThroughBitCast) {
00163   // it's safe to consider realloc as noalias since accessing the original
00164   // pointer is undefined behavior
00165   return isAllocationFn(V, TLI, LookThroughBitCast) ||
00166          hasNoAliasAttr(V, LookThroughBitCast);
00167 }
00168 
00169 /// \brief Tests if a value is a call or invoke to a library function that
00170 /// allocates uninitialized memory (such as malloc).
00171 bool llvm::isMallocLikeFn(const Value *V, const TargetLibraryInfo *TLI,
00172                           bool LookThroughBitCast) {
00173   return getAllocationData(V, MallocLike, TLI, LookThroughBitCast);
00174 }
00175 
00176 /// \brief Tests if a value is a call or invoke to a library function that
00177 /// allocates zero-filled memory (such as calloc).
00178 bool llvm::isCallocLikeFn(const Value *V, const TargetLibraryInfo *TLI,
00179                           bool LookThroughBitCast) {
00180   return getAllocationData(V, CallocLike, TLI, LookThroughBitCast);
00181 }
00182 
00183 /// \brief Tests if a value is a call or invoke to a library function that
00184 /// allocates memory (either malloc, calloc, or strdup like).
00185 bool llvm::isAllocLikeFn(const Value *V, const TargetLibraryInfo *TLI,
00186                          bool LookThroughBitCast) {
00187   return getAllocationData(V, AllocLike, TLI, LookThroughBitCast);
00188 }
00189 
00190 /// extractMallocCall - Returns the corresponding CallInst if the instruction
00191 /// is a malloc call.  Since CallInst::CreateMalloc() only creates calls, we
00192 /// ignore InvokeInst here.
00193 const CallInst *llvm::extractMallocCall(const Value *I,
00194                                         const TargetLibraryInfo *TLI) {
00195   return isMallocLikeFn(I, TLI) ? dyn_cast<CallInst>(I) : nullptr;
00196 }
00197 
00198 static Value *computeArraySize(const CallInst *CI, const DataLayout &DL,
00199                                const TargetLibraryInfo *TLI,
00200                                bool LookThroughSExt = false) {
00201   if (!CI)
00202     return nullptr;
00203 
00204   // The size of the malloc's result type must be known to determine array size.
00205   Type *T = getMallocAllocatedType(CI, TLI);
00206   if (!T || !T->isSized())
00207     return nullptr;
00208 
00209   unsigned ElementSize = DL.getTypeAllocSize(T);
00210   if (StructType *ST = dyn_cast<StructType>(T))
00211     ElementSize = DL.getStructLayout(ST)->getSizeInBytes();
00212 
00213   // If malloc call's arg can be determined to be a multiple of ElementSize,
00214   // return the multiple.  Otherwise, return NULL.
00215   Value *MallocArg = CI->getArgOperand(0);
00216   Value *Multiple = nullptr;
00217   if (ComputeMultiple(MallocArg, ElementSize, Multiple,
00218                       LookThroughSExt))
00219     return Multiple;
00220 
00221   return nullptr;
00222 }
00223 
00224 /// getMallocType - Returns the PointerType resulting from the malloc call.
00225 /// The PointerType depends on the number of bitcast uses of the malloc call:
00226 ///   0: PointerType is the calls' return type.
00227 ///   1: PointerType is the bitcast's result type.
00228 ///  >1: Unique PointerType cannot be determined, return NULL.
00229 PointerType *llvm::getMallocType(const CallInst *CI,
00230                                  const TargetLibraryInfo *TLI) {
00231   assert(isMallocLikeFn(CI, TLI) && "getMallocType and not malloc call");
00232 
00233   PointerType *MallocType = nullptr;
00234   unsigned NumOfBitCastUses = 0;
00235 
00236   // Determine if CallInst has a bitcast use.
00237   for (Value::const_user_iterator UI = CI->user_begin(), E = CI->user_end();
00238        UI != E;)
00239     if (const BitCastInst *BCI = dyn_cast<BitCastInst>(*UI++)) {
00240       MallocType = cast<PointerType>(BCI->getDestTy());
00241       NumOfBitCastUses++;
00242     }
00243 
00244   // Malloc call has 1 bitcast use, so type is the bitcast's destination type.
00245   if (NumOfBitCastUses == 1)
00246     return MallocType;
00247 
00248   // Malloc call was not bitcast, so type is the malloc function's return type.
00249   if (NumOfBitCastUses == 0)
00250     return cast<PointerType>(CI->getType());
00251 
00252   // Type could not be determined.
00253   return nullptr;
00254 }
00255 
00256 /// getMallocAllocatedType - Returns the Type allocated by malloc call.
00257 /// The Type depends on the number of bitcast uses of the malloc call:
00258 ///   0: PointerType is the malloc calls' return type.
00259 ///   1: PointerType is the bitcast's result type.
00260 ///  >1: Unique PointerType cannot be determined, return NULL.
00261 Type *llvm::getMallocAllocatedType(const CallInst *CI,
00262                                    const TargetLibraryInfo *TLI) {
00263   PointerType *PT = getMallocType(CI, TLI);
00264   return PT ? PT->getElementType() : nullptr;
00265 }
00266 
00267 /// getMallocArraySize - Returns the array size of a malloc call.  If the
00268 /// argument passed to malloc is a multiple of the size of the malloced type,
00269 /// then return that multiple.  For non-array mallocs, the multiple is
00270 /// constant 1.  Otherwise, return NULL for mallocs whose array size cannot be
00271 /// determined.
00272 Value *llvm::getMallocArraySize(CallInst *CI, const DataLayout &DL,
00273                                 const TargetLibraryInfo *TLI,
00274                                 bool LookThroughSExt) {
00275   assert(isMallocLikeFn(CI, TLI) && "getMallocArraySize and not malloc call");
00276   return computeArraySize(CI, DL, TLI, LookThroughSExt);
00277 }
00278 
00279 
00280 /// extractCallocCall - Returns the corresponding CallInst if the instruction
00281 /// is a calloc call.
00282 const CallInst *llvm::extractCallocCall(const Value *I,
00283                                         const TargetLibraryInfo *TLI) {
00284   return isCallocLikeFn(I, TLI) ? cast<CallInst>(I) : nullptr;
00285 }
00286 
00287 
00288 /// isFreeCall - Returns non-null if the value is a call to the builtin free()
00289 const CallInst *llvm::isFreeCall(const Value *I, const TargetLibraryInfo *TLI) {
00290   const CallInst *CI = dyn_cast<CallInst>(I);
00291   if (!CI || isa<IntrinsicInst>(CI))
00292     return nullptr;
00293   Function *Callee = CI->getCalledFunction();
00294   if (Callee == nullptr)
00295     return nullptr;
00296 
00297   StringRef FnName = Callee->getName();
00298   LibFunc::Func TLIFn;
00299   if (!TLI || !TLI->getLibFunc(FnName, TLIFn) || !TLI->has(TLIFn))
00300     return nullptr;
00301 
00302   unsigned ExpectedNumParams;
00303   if (TLIFn == LibFunc::free ||
00304       TLIFn == LibFunc::ZdlPv || // operator delete(void*)
00305       TLIFn == LibFunc::ZdaPv || // operator delete[](void*)
00306       TLIFn == LibFunc::msvc_delete_ptr32 || // operator delete(void*)
00307       TLIFn == LibFunc::msvc_delete_ptr64 || // operator delete(void*)
00308       TLIFn == LibFunc::msvc_delete_array_ptr32 || // operator delete[](void*)
00309       TLIFn == LibFunc::msvc_delete_array_ptr64)   // operator delete[](void*)
00310     ExpectedNumParams = 1;
00311   else if (TLIFn == LibFunc::ZdlPvj ||              // delete(void*, uint)
00312            TLIFn == LibFunc::ZdlPvm ||              // delete(void*, ulong)
00313            TLIFn == LibFunc::ZdlPvRKSt9nothrow_t || // delete(void*, nothrow)
00314            TLIFn == LibFunc::ZdaPvj ||              // delete[](void*, uint)
00315            TLIFn == LibFunc::ZdaPvm ||              // delete[](void*, ulong)
00316            TLIFn == LibFunc::ZdaPvRKSt9nothrow_t || // delete[](void*, nothrow)
00317            TLIFn == LibFunc::msvc_delete_ptr32_int ||      // delete(void*, uint)
00318            TLIFn == LibFunc::msvc_delete_ptr64_longlong || // delete(void*, ulonglong)
00319            TLIFn == LibFunc::msvc_delete_ptr32_nothrow || // delete(void*, nothrow)
00320            TLIFn == LibFunc::msvc_delete_ptr64_nothrow || // delete(void*, nothrow)
00321            TLIFn == LibFunc::msvc_delete_array_ptr32_int ||      // delete[](void*, uint)
00322            TLIFn == LibFunc::msvc_delete_array_ptr64_longlong || // delete[](void*, ulonglong)
00323            TLIFn == LibFunc::msvc_delete_array_ptr32_nothrow || // delete[](void*, nothrow)
00324            TLIFn == LibFunc::msvc_delete_array_ptr64_nothrow)   // delete[](void*, nothrow)
00325     ExpectedNumParams = 2;
00326   else
00327     return nullptr;
00328 
00329   // Check free prototype.
00330   // FIXME: workaround for PR5130, this will be obsolete when a nobuiltin
00331   // attribute will exist.
00332   FunctionType *FTy = Callee->getFunctionType();
00333   if (!FTy->getReturnType()->isVoidTy())
00334     return nullptr;
00335   if (FTy->getNumParams() != ExpectedNumParams)
00336     return nullptr;
00337   if (FTy->getParamType(0) != Type::getInt8PtrTy(Callee->getContext()))
00338     return nullptr;
00339 
00340   return CI;
00341 }
00342 
00343 
00344 
00345 //===----------------------------------------------------------------------===//
00346 //  Utility functions to compute size of objects.
00347 //
00348 
00349 
00350 /// \brief Compute the size of the object pointed by Ptr. Returns true and the
00351 /// object size in Size if successful, and false otherwise.
00352 /// If RoundToAlign is true, then Size is rounded up to the aligment of allocas,
00353 /// byval arguments, and global variables.
00354 bool llvm::getObjectSize(const Value *Ptr, uint64_t &Size, const DataLayout &DL,
00355                          const TargetLibraryInfo *TLI, bool RoundToAlign) {
00356   ObjectSizeOffsetVisitor Visitor(DL, TLI, Ptr->getContext(), RoundToAlign);
00357   SizeOffsetType Data = Visitor.compute(const_cast<Value*>(Ptr));
00358   if (!Visitor.bothKnown(Data))
00359     return false;
00360 
00361   APInt ObjSize = Data.first, Offset = Data.second;
00362   // check for overflow
00363   if (Offset.slt(0) || ObjSize.ult(Offset))
00364     Size = 0;
00365   else
00366     Size = (ObjSize - Offset).getZExtValue();
00367   return true;
00368 }
00369 
00370 
00371 STATISTIC(ObjectVisitorArgument,
00372           "Number of arguments with unsolved size and offset");
00373 STATISTIC(ObjectVisitorLoad,
00374           "Number of load instructions with unsolved size and offset");
00375 
00376 
00377 APInt ObjectSizeOffsetVisitor::align(APInt Size, uint64_t Align) {
00378   if (RoundToAlign && Align)
00379     return APInt(IntTyBits, alignTo(Size.getZExtValue(), Align));
00380   return Size;
00381 }
00382 
00383 ObjectSizeOffsetVisitor::ObjectSizeOffsetVisitor(const DataLayout &DL,
00384                                                  const TargetLibraryInfo *TLI,
00385                                                  LLVMContext &Context,
00386                                                  bool RoundToAlign)
00387     : DL(DL), TLI(TLI), RoundToAlign(RoundToAlign) {
00388   // Pointer size must be rechecked for each object visited since it could have
00389   // a different address space.
00390 }
00391 
00392 SizeOffsetType ObjectSizeOffsetVisitor::compute(Value *V) {
00393   IntTyBits = DL.getPointerTypeSizeInBits(V->getType());
00394   Zero = APInt::getNullValue(IntTyBits);
00395 
00396   V = V->stripPointerCasts();
00397   if (Instruction *I = dyn_cast<Instruction>(V)) {
00398     // If we have already seen this instruction, bail out. Cycles can happen in
00399     // unreachable code after constant propagation.
00400     if (!SeenInsts.insert(I).second)
00401       return unknown();
00402 
00403     if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
00404       return visitGEPOperator(*GEP);
00405     return visit(*I);
00406   }
00407   if (Argument *A = dyn_cast<Argument>(V))
00408     return visitArgument(*A);
00409   if (ConstantPointerNull *P = dyn_cast<ConstantPointerNull>(V))
00410     return visitConstantPointerNull(*P);
00411   if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
00412     return visitGlobalAlias(*GA);
00413   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
00414     return visitGlobalVariable(*GV);
00415   if (UndefValue *UV = dyn_cast<UndefValue>(V))
00416     return visitUndefValue(*UV);
00417   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
00418     if (CE->getOpcode() == Instruction::IntToPtr)
00419       return unknown(); // clueless
00420     if (CE->getOpcode() == Instruction::GetElementPtr)
00421       return visitGEPOperator(cast<GEPOperator>(*CE));
00422   }
00423 
00424   DEBUG(dbgs() << "ObjectSizeOffsetVisitor::compute() unhandled value: " << *V
00425         << '\n');
00426   return unknown();
00427 }
00428 
00429 SizeOffsetType ObjectSizeOffsetVisitor::visitAllocaInst(AllocaInst &I) {
00430   if (!I.getAllocatedType()->isSized())
00431     return unknown();
00432 
00433   APInt Size(IntTyBits, DL.getTypeAllocSize(I.getAllocatedType()));
00434   if (!I.isArrayAllocation())
00435     return std::make_pair(align(Size, I.getAlignment()), Zero);
00436 
00437   Value *ArraySize = I.getArraySize();
00438   if (const ConstantInt *C = dyn_cast<ConstantInt>(ArraySize)) {
00439     Size *= C->getValue().zextOrSelf(IntTyBits);
00440     return std::make_pair(align(Size, I.getAlignment()), Zero);
00441   }
00442   return unknown();
00443 }
00444 
00445 SizeOffsetType ObjectSizeOffsetVisitor::visitArgument(Argument &A) {
00446   // no interprocedural analysis is done at the moment
00447   if (!A.hasByValOrInAllocaAttr()) {
00448     ++ObjectVisitorArgument;
00449     return unknown();
00450   }
00451   PointerType *PT = cast<PointerType>(A.getType());
00452   APInt Size(IntTyBits, DL.getTypeAllocSize(PT->getElementType()));
00453   return std::make_pair(align(Size, A.getParamAlignment()), Zero);
00454 }
00455 
00456 SizeOffsetType ObjectSizeOffsetVisitor::visitCallSite(CallSite CS) {
00457   const AllocFnsTy *FnData = getAllocationData(CS.getInstruction(), AnyAlloc,
00458                                                TLI);
00459   if (!FnData)
00460     return unknown();
00461 
00462   // handle strdup-like functions separately
00463   if (FnData->AllocTy == StrDupLike) {
00464     APInt Size(IntTyBits, GetStringLength(CS.getArgument(0)));
00465     if (!Size)
00466       return unknown();
00467 
00468     // strndup limits strlen
00469     if (FnData->FstParam > 0) {
00470       ConstantInt *Arg= dyn_cast<ConstantInt>(CS.getArgument(FnData->FstParam));
00471       if (!Arg)
00472         return unknown();
00473 
00474       APInt MaxSize = Arg->getValue().zextOrSelf(IntTyBits);
00475       if (Size.ugt(MaxSize))
00476         Size = MaxSize + 1;
00477     }
00478     return std::make_pair(Size, Zero);
00479   }
00480 
00481   ConstantInt *Arg = dyn_cast<ConstantInt>(CS.getArgument(FnData->FstParam));
00482   if (!Arg)
00483     return unknown();
00484 
00485   APInt Size = Arg->getValue().zextOrSelf(IntTyBits);
00486   // size determined by just 1 parameter
00487   if (FnData->SndParam < 0)
00488     return std::make_pair(Size, Zero);
00489 
00490   Arg = dyn_cast<ConstantInt>(CS.getArgument(FnData->SndParam));
00491   if (!Arg)
00492     return unknown();
00493 
00494   Size *= Arg->getValue().zextOrSelf(IntTyBits);
00495   return std::make_pair(Size, Zero);
00496 
00497   // TODO: handle more standard functions (+ wchar cousins):
00498   // - strdup / strndup
00499   // - strcpy / strncpy
00500   // - strcat / strncat
00501   // - memcpy / memmove
00502   // - strcat / strncat
00503   // - memset
00504 }
00505 
00506 SizeOffsetType
00507 ObjectSizeOffsetVisitor::visitConstantPointerNull(ConstantPointerNull&) {
00508   return std::make_pair(Zero, Zero);
00509 }
00510 
00511 SizeOffsetType
00512 ObjectSizeOffsetVisitor::visitExtractElementInst(ExtractElementInst&) {
00513   return unknown();
00514 }
00515 
00516 SizeOffsetType
00517 ObjectSizeOffsetVisitor::visitExtractValueInst(ExtractValueInst&) {
00518   // Easy cases were already folded by previous passes.
00519   return unknown();
00520 }
00521 
00522 SizeOffsetType ObjectSizeOffsetVisitor::visitGEPOperator(GEPOperator &GEP) {
00523   SizeOffsetType PtrData = compute(GEP.getPointerOperand());
00524   APInt Offset(IntTyBits, 0);
00525   if (!bothKnown(PtrData) || !GEP.accumulateConstantOffset(DL, Offset))
00526     return unknown();
00527 
00528   return std::make_pair(PtrData.first, PtrData.second + Offset);
00529 }
00530 
00531 SizeOffsetType ObjectSizeOffsetVisitor::visitGlobalAlias(GlobalAlias &GA) {
00532   if (GA.mayBeOverridden())
00533     return unknown();
00534   return compute(GA.getAliasee());
00535 }
00536 
00537 SizeOffsetType ObjectSizeOffsetVisitor::visitGlobalVariable(GlobalVariable &GV){
00538   if (!GV.hasDefinitiveInitializer())
00539     return unknown();
00540 
00541   APInt Size(IntTyBits, DL.getTypeAllocSize(GV.getType()->getElementType()));
00542   return std::make_pair(align(Size, GV.getAlignment()), Zero);
00543 }
00544 
00545 SizeOffsetType ObjectSizeOffsetVisitor::visitIntToPtrInst(IntToPtrInst&) {
00546   // clueless
00547   return unknown();
00548 }
00549 
00550 SizeOffsetType ObjectSizeOffsetVisitor::visitLoadInst(LoadInst&) {
00551   ++ObjectVisitorLoad;
00552   return unknown();
00553 }
00554 
00555 SizeOffsetType ObjectSizeOffsetVisitor::visitPHINode(PHINode&) {
00556   // too complex to analyze statically.
00557   return unknown();
00558 }
00559 
00560 SizeOffsetType ObjectSizeOffsetVisitor::visitSelectInst(SelectInst &I) {
00561   SizeOffsetType TrueSide  = compute(I.getTrueValue());
00562   SizeOffsetType FalseSide = compute(I.getFalseValue());
00563   if (bothKnown(TrueSide) && bothKnown(FalseSide) && TrueSide == FalseSide)
00564     return TrueSide;
00565   return unknown();
00566 }
00567 
00568 SizeOffsetType ObjectSizeOffsetVisitor::visitUndefValue(UndefValue&) {
00569   return std::make_pair(Zero, Zero);
00570 }
00571 
00572 SizeOffsetType ObjectSizeOffsetVisitor::visitInstruction(Instruction &I) {
00573   DEBUG(dbgs() << "ObjectSizeOffsetVisitor unknown instruction:" << I << '\n');
00574   return unknown();
00575 }
00576 
00577 ObjectSizeOffsetEvaluator::ObjectSizeOffsetEvaluator(
00578     const DataLayout &DL, const TargetLibraryInfo *TLI, LLVMContext &Context,
00579     bool RoundToAlign)
00580     : DL(DL), TLI(TLI), Context(Context), Builder(Context, TargetFolder(DL)),
00581       RoundToAlign(RoundToAlign) {
00582   // IntTy and Zero must be set for each compute() since the address space may
00583   // be different for later objects.
00584 }
00585 
00586 SizeOffsetEvalType ObjectSizeOffsetEvaluator::compute(Value *V) {
00587   // XXX - Are vectors of pointers possible here?
00588   IntTy = cast<IntegerType>(DL.getIntPtrType(V->getType()));
00589   Zero = ConstantInt::get(IntTy, 0);
00590 
00591   SizeOffsetEvalType Result = compute_(V);
00592 
00593   if (!bothKnown(Result)) {
00594     // erase everything that was computed in this iteration from the cache, so
00595     // that no dangling references are left behind. We could be a bit smarter if
00596     // we kept a dependency graph. It's probably not worth the complexity.
00597     for (PtrSetTy::iterator I=SeenVals.begin(), E=SeenVals.end(); I != E; ++I) {
00598       CacheMapTy::iterator CacheIt = CacheMap.find(*I);
00599       // non-computable results can be safely cached
00600       if (CacheIt != CacheMap.end() && anyKnown(CacheIt->second))
00601         CacheMap.erase(CacheIt);
00602     }
00603   }
00604 
00605   SeenVals.clear();
00606   return Result;
00607 }
00608 
00609 SizeOffsetEvalType ObjectSizeOffsetEvaluator::compute_(Value *V) {
00610   ObjectSizeOffsetVisitor Visitor(DL, TLI, Context, RoundToAlign);
00611   SizeOffsetType Const = Visitor.compute(V);
00612   if (Visitor.bothKnown(Const))
00613     return std::make_pair(ConstantInt::get(Context, Const.first),
00614                           ConstantInt::get(Context, Const.second));
00615 
00616   V = V->stripPointerCasts();
00617 
00618   // check cache
00619   CacheMapTy::iterator CacheIt = CacheMap.find(V);
00620   if (CacheIt != CacheMap.end())
00621     return CacheIt->second;
00622 
00623   // always generate code immediately before the instruction being
00624   // processed, so that the generated code dominates the same BBs
00625   BuilderTy::InsertPointGuard Guard(Builder);
00626   if (Instruction *I = dyn_cast<Instruction>(V))
00627     Builder.SetInsertPoint(I);
00628 
00629   // now compute the size and offset
00630   SizeOffsetEvalType Result;
00631 
00632   // Record the pointers that were handled in this run, so that they can be
00633   // cleaned later if something fails. We also use this set to break cycles that
00634   // can occur in dead code.
00635   if (!SeenVals.insert(V).second) {
00636     Result = unknown();
00637   } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
00638     Result = visitGEPOperator(*GEP);
00639   } else if (Instruction *I = dyn_cast<Instruction>(V)) {
00640     Result = visit(*I);
00641   } else if (isa<Argument>(V) ||
00642              (isa<ConstantExpr>(V) &&
00643               cast<ConstantExpr>(V)->getOpcode() == Instruction::IntToPtr) ||
00644              isa<GlobalAlias>(V) ||
00645              isa<GlobalVariable>(V)) {
00646     // ignore values where we cannot do more than what ObjectSizeVisitor can
00647     Result = unknown();
00648   } else {
00649     DEBUG(dbgs() << "ObjectSizeOffsetEvaluator::compute() unhandled value: "
00650           << *V << '\n');
00651     Result = unknown();
00652   }
00653 
00654   // Don't reuse CacheIt since it may be invalid at this point.
00655   CacheMap[V] = Result;
00656   return Result;
00657 }
00658 
00659 SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitAllocaInst(AllocaInst &I) {
00660   if (!I.getAllocatedType()->isSized())
00661     return unknown();
00662 
00663   // must be a VLA
00664   assert(I.isArrayAllocation());
00665   Value *ArraySize = I.getArraySize();
00666   Value *Size = ConstantInt::get(ArraySize->getType(),
00667                                  DL.getTypeAllocSize(I.getAllocatedType()));
00668   Size = Builder.CreateMul(Size, ArraySize);
00669   return std::make_pair(Size, Zero);
00670 }
00671 
00672 SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitCallSite(CallSite CS) {
00673   const AllocFnsTy *FnData = getAllocationData(CS.getInstruction(), AnyAlloc,
00674                                                TLI);
00675   if (!FnData)
00676     return unknown();
00677 
00678   // handle strdup-like functions separately
00679   if (FnData->AllocTy == StrDupLike) {
00680     // TODO
00681     return unknown();
00682   }
00683 
00684   Value *FirstArg = CS.getArgument(FnData->FstParam);
00685   FirstArg = Builder.CreateZExt(FirstArg, IntTy);
00686   if (FnData->SndParam < 0)
00687     return std::make_pair(FirstArg, Zero);
00688 
00689   Value *SecondArg = CS.getArgument(FnData->SndParam);
00690   SecondArg = Builder.CreateZExt(SecondArg, IntTy);
00691   Value *Size = Builder.CreateMul(FirstArg, SecondArg);
00692   return std::make_pair(Size, Zero);
00693 
00694   // TODO: handle more standard functions (+ wchar cousins):
00695   // - strdup / strndup
00696   // - strcpy / strncpy
00697   // - strcat / strncat
00698   // - memcpy / memmove
00699   // - strcat / strncat
00700   // - memset
00701 }
00702 
00703 SizeOffsetEvalType
00704 ObjectSizeOffsetEvaluator::visitExtractElementInst(ExtractElementInst&) {
00705   return unknown();
00706 }
00707 
00708 SizeOffsetEvalType
00709 ObjectSizeOffsetEvaluator::visitExtractValueInst(ExtractValueInst&) {
00710   return unknown();
00711 }
00712 
00713 SizeOffsetEvalType
00714 ObjectSizeOffsetEvaluator::visitGEPOperator(GEPOperator &GEP) {
00715   SizeOffsetEvalType PtrData = compute_(GEP.getPointerOperand());
00716   if (!bothKnown(PtrData))
00717     return unknown();
00718 
00719   Value *Offset = EmitGEPOffset(&Builder, DL, &GEP, /*NoAssumptions=*/true);
00720   Offset = Builder.CreateAdd(PtrData.second, Offset);
00721   return std::make_pair(PtrData.first, Offset);
00722 }
00723 
00724 SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitIntToPtrInst(IntToPtrInst&) {
00725   // clueless
00726   return unknown();
00727 }
00728 
00729 SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitLoadInst(LoadInst&) {
00730   return unknown();
00731 }
00732 
00733 SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitPHINode(PHINode &PHI) {
00734   // create 2 PHIs: one for size and another for offset
00735   PHINode *SizePHI   = Builder.CreatePHI(IntTy, PHI.getNumIncomingValues());
00736   PHINode *OffsetPHI = Builder.CreatePHI(IntTy, PHI.getNumIncomingValues());
00737 
00738   // insert right away in the cache to handle recursive PHIs
00739   CacheMap[&PHI] = std::make_pair(SizePHI, OffsetPHI);
00740 
00741   // compute offset/size for each PHI incoming pointer
00742   for (unsigned i = 0, e = PHI.getNumIncomingValues(); i != e; ++i) {
00743     Builder.SetInsertPoint(&*PHI.getIncomingBlock(i)->getFirstInsertionPt());
00744     SizeOffsetEvalType EdgeData = compute_(PHI.getIncomingValue(i));
00745 
00746     if (!bothKnown(EdgeData)) {
00747       OffsetPHI->replaceAllUsesWith(UndefValue::get(IntTy));
00748       OffsetPHI->eraseFromParent();
00749       SizePHI->replaceAllUsesWith(UndefValue::get(IntTy));
00750       SizePHI->eraseFromParent();
00751       return unknown();
00752     }
00753     SizePHI->addIncoming(EdgeData.first, PHI.getIncomingBlock(i));
00754     OffsetPHI->addIncoming(EdgeData.second, PHI.getIncomingBlock(i));
00755   }
00756 
00757   Value *Size = SizePHI, *Offset = OffsetPHI, *Tmp;
00758   if ((Tmp = SizePHI->hasConstantValue())) {
00759     Size = Tmp;
00760     SizePHI->replaceAllUsesWith(Size);
00761     SizePHI->eraseFromParent();
00762   }
00763   if ((Tmp = OffsetPHI->hasConstantValue())) {
00764     Offset = Tmp;
00765     OffsetPHI->replaceAllUsesWith(Offset);
00766     OffsetPHI->eraseFromParent();
00767   }
00768   return std::make_pair(Size, Offset);
00769 }
00770 
00771 SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitSelectInst(SelectInst &I) {
00772   SizeOffsetEvalType TrueSide  = compute_(I.getTrueValue());
00773   SizeOffsetEvalType FalseSide = compute_(I.getFalseValue());
00774 
00775   if (!bothKnown(TrueSide) || !bothKnown(FalseSide))
00776     return unknown();
00777   if (TrueSide == FalseSide)
00778     return TrueSide;
00779 
00780   Value *Size = Builder.CreateSelect(I.getCondition(), TrueSide.first,
00781                                      FalseSide.first);
00782   Value *Offset = Builder.CreateSelect(I.getCondition(), TrueSide.second,
00783                                        FalseSide.second);
00784   return std::make_pair(Size, Offset);
00785 }
00786 
00787 SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitInstruction(Instruction &I) {
00788   DEBUG(dbgs() << "ObjectSizeOffsetEvaluator unknown instruction:" << I <<'\n');
00789   return unknown();
00790 }