LLVM API Documentation

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