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