MemoryBuiltins.cpp revision 239462
1198892Srdivacky//===------ MemoryBuiltins.cpp - Identify calls to memory builtins --------===//
2198892Srdivacky//
3198892Srdivacky//                     The LLVM Compiler Infrastructure
4198892Srdivacky//
5198892Srdivacky// This file is distributed under the University of Illinois Open Source
6198892Srdivacky// License. See LICENSE.TXT for details.
7198892Srdivacky//
8198892Srdivacky//===----------------------------------------------------------------------===//
9198892Srdivacky//
10198892Srdivacky// This family of functions identifies calls to builtin functions that allocate
11198892Srdivacky// or free memory.
12198892Srdivacky//
13198892Srdivacky//===----------------------------------------------------------------------===//
14198892Srdivacky
15239462Sdim#define DEBUG_TYPE "memory-builtins"
16239462Sdim#include "llvm/ADT/Statistic.h"
17239462Sdim#include "llvm/ADT/STLExtras.h"
18198892Srdivacky#include "llvm/Analysis/MemoryBuiltins.h"
19239462Sdim#include "llvm/GlobalVariable.h"
20198892Srdivacky#include "llvm/Instructions.h"
21239462Sdim#include "llvm/Intrinsics.h"
22239462Sdim#include "llvm/Metadata.h"
23198892Srdivacky#include "llvm/Module.h"
24199481Srdivacky#include "llvm/Analysis/ValueTracking.h"
25239462Sdim#include "llvm/Support/Debug.h"
26239462Sdim#include "llvm/Support/MathExtras.h"
27239462Sdim#include "llvm/Support/raw_ostream.h"
28198953Srdivacky#include "llvm/Target/TargetData.h"
29239462Sdim#include "llvm/Transforms/Utils/Local.h"
30198892Srdivackyusing namespace llvm;
31198892Srdivacky
32239462Sdimenum AllocType {
33239462Sdim  MallocLike         = 1<<0, // allocates
34239462Sdim  CallocLike         = 1<<1, // allocates + bzero
35239462Sdim  ReallocLike        = 1<<2, // reallocates
36239462Sdim  StrDupLike         = 1<<3,
37239462Sdim  AllocLike          = MallocLike | CallocLike | StrDupLike,
38239462Sdim  AnyAlloc           = MallocLike | CallocLike | ReallocLike | StrDupLike
39239462Sdim};
40198892Srdivacky
41239462Sdimstruct AllocFnsTy {
42239462Sdim  const char *Name;
43239462Sdim  AllocType AllocTy;
44239462Sdim  unsigned char NumParams;
45239462Sdim  // First and Second size parameters (or -1 if unused)
46239462Sdim  signed char FstParam, SndParam;
47239462Sdim};
48239462Sdim
49239462Sdim// FIXME: certain users need more information. E.g., SimplifyLibCalls needs to
50239462Sdim// know which functions are nounwind, noalias, nocapture parameters, etc.
51239462Sdimstatic const AllocFnsTy AllocationFnData[] = {
52239462Sdim  {"malloc",              MallocLike,  1, 0,  -1},
53239462Sdim  {"valloc",              MallocLike,  1, 0,  -1},
54239462Sdim  {"_Znwj",               MallocLike,  1, 0,  -1}, // new(unsigned int)
55239462Sdim  {"_ZnwjRKSt9nothrow_t", MallocLike,  2, 0,  -1}, // new(unsigned int, nothrow)
56239462Sdim  {"_Znwm",               MallocLike,  1, 0,  -1}, // new(unsigned long)
57239462Sdim  {"_ZnwmRKSt9nothrow_t", MallocLike,  2, 0,  -1}, // new(unsigned long, nothrow)
58239462Sdim  {"_Znaj",               MallocLike,  1, 0,  -1}, // new[](unsigned int)
59239462Sdim  {"_ZnajRKSt9nothrow_t", MallocLike,  2, 0,  -1}, // new[](unsigned int, nothrow)
60239462Sdim  {"_Znam",               MallocLike,  1, 0,  -1}, // new[](unsigned long)
61239462Sdim  {"_ZnamRKSt9nothrow_t", MallocLike,  2, 0,  -1}, // new[](unsigned long, nothrow)
62239462Sdim  {"posix_memalign",      MallocLike,  3, 2,  -1},
63239462Sdim  {"calloc",              CallocLike,  2, 0,  1},
64239462Sdim  {"realloc",             ReallocLike, 2, 1,  -1},
65239462Sdim  {"reallocf",            ReallocLike, 2, 1,  -1},
66239462Sdim  {"strdup",              StrDupLike,  1, -1, -1},
67239462Sdim  {"strndup",             StrDupLike,  2, 1,  -1}
68239462Sdim};
69239462Sdim
70239462Sdim
71239462Sdimstatic Function *getCalledFunction(const Value *V, bool LookThroughBitCast) {
72239462Sdim  if (LookThroughBitCast)
73239462Sdim    V = V->stripPointerCasts();
74239462Sdim
75239462Sdim  CallSite CS(const_cast<Value*>(V));
76239462Sdim  if (!CS.getInstruction())
77239462Sdim    return 0;
78239462Sdim
79239462Sdim  Function *Callee = CS.getCalledFunction();
80239462Sdim  if (!Callee || !Callee->isDeclaration())
81239462Sdim    return 0;
82239462Sdim  return Callee;
83198892Srdivacky}
84198892Srdivacky
85239462Sdim/// \brief Returns the allocation data for the given value if it is a call to a
86239462Sdim/// known allocation function, and NULL otherwise.
87239462Sdimstatic const AllocFnsTy *getAllocationData(const Value *V, AllocType AllocTy,
88239462Sdim                                           bool LookThroughBitCast = false) {
89239462Sdim  Function *Callee = getCalledFunction(V, LookThroughBitCast);
90239462Sdim  if (!Callee)
91239462Sdim    return 0;
92198892Srdivacky
93239462Sdim  unsigned i = 0;
94239462Sdim  bool found = false;
95239462Sdim  for ( ; i < array_lengthof(AllocationFnData); ++i) {
96239462Sdim    if (Callee->getName() == AllocationFnData[i].Name) {
97239462Sdim      found = true;
98239462Sdim      break;
99239462Sdim    }
100239462Sdim  }
101239462Sdim  if (!found)
102239462Sdim    return 0;
103198892Srdivacky
104239462Sdim  const AllocFnsTy *FnData = &AllocationFnData[i];
105239462Sdim  if ((FnData->AllocTy & AllocTy) == 0)
106239462Sdim    return 0;
107239462Sdim
108239462Sdim  // Check function prototype.
109239462Sdim  // FIXME: Check the nobuiltin metadata?? (PR5130)
110239462Sdim  int FstParam = FnData->FstParam;
111239462Sdim  int SndParam = FnData->SndParam;
112226633Sdim  FunctionType *FTy = Callee->getFunctionType();
113239462Sdim
114239462Sdim  if (FTy->getReturnType() == Type::getInt8PtrTy(FTy->getContext()) &&
115239462Sdim      FTy->getNumParams() == FnData->NumParams &&
116239462Sdim      (FstParam < 0 ||
117239462Sdim       (FTy->getParamType(FstParam)->isIntegerTy(32) ||
118239462Sdim        FTy->getParamType(FstParam)->isIntegerTy(64))) &&
119239462Sdim      (SndParam < 0 ||
120239462Sdim       FTy->getParamType(SndParam)->isIntegerTy(32) ||
121239462Sdim       FTy->getParamType(SndParam)->isIntegerTy(64)))
122239462Sdim    return FnData;
123239462Sdim  return 0;
124198892Srdivacky}
125198892Srdivacky
126239462Sdimstatic bool hasNoAliasAttr(const Value *V, bool LookThroughBitCast) {
127239462Sdim  ImmutableCallSite CS(LookThroughBitCast ? V->stripPointerCasts() : V);
128239462Sdim  return CS && CS.hasFnAttr(Attribute::NoAlias);
129198892Srdivacky}
130198892Srdivacky
131239462Sdim
132239462Sdim/// \brief Tests if a value is a call or invoke to a library function that
133239462Sdim/// allocates or reallocates memory (either malloc, calloc, realloc, or strdup
134239462Sdim/// like).
135239462Sdimbool llvm::isAllocationFn(const Value *V, bool LookThroughBitCast) {
136239462Sdim  return getAllocationData(V, AnyAlloc, LookThroughBitCast);
137198892Srdivacky}
138198892Srdivacky
139239462Sdim/// \brief Tests if a value is a call or invoke to a function that returns a
140239462Sdim/// NoAlias pointer (including malloc/calloc/realloc/strdup-like functions).
141239462Sdimbool llvm::isNoAliasFn(const Value *V, bool LookThroughBitCast) {
142239462Sdim  // it's safe to consider realloc as noalias since accessing the original
143239462Sdim  // pointer is undefined behavior
144239462Sdim  return isAllocationFn(V, LookThroughBitCast) ||
145239462Sdim         hasNoAliasAttr(V, LookThroughBitCast);
146198892Srdivacky}
147198892Srdivacky
148239462Sdim/// \brief Tests if a value is a call or invoke to a library function that
149239462Sdim/// allocates uninitialized memory (such as malloc).
150239462Sdimbool llvm::isMallocLikeFn(const Value *V, bool LookThroughBitCast) {
151239462Sdim  return getAllocationData(V, MallocLike, LookThroughBitCast);
152198892Srdivacky}
153198892Srdivacky
154239462Sdim/// \brief Tests if a value is a call or invoke to a library function that
155239462Sdim/// allocates zero-filled memory (such as calloc).
156239462Sdimbool llvm::isCallocLikeFn(const Value *V, bool LookThroughBitCast) {
157239462Sdim  return getAllocationData(V, CallocLike, LookThroughBitCast);
158198892Srdivacky}
159198892Srdivacky
160239462Sdim/// \brief Tests if a value is a call or invoke to a library function that
161239462Sdim/// allocates memory (either malloc, calloc, or strdup like).
162239462Sdimbool llvm::isAllocLikeFn(const Value *V, bool LookThroughBitCast) {
163239462Sdim  return getAllocationData(V, AllocLike, LookThroughBitCast);
164239462Sdim}
165239462Sdim
166239462Sdim/// \brief Tests if a value is a call or invoke to a library function that
167239462Sdim/// reallocates memory (such as realloc).
168239462Sdimbool llvm::isReallocLikeFn(const Value *V, bool LookThroughBitCast) {
169239462Sdim  return getAllocationData(V, ReallocLike, LookThroughBitCast);
170239462Sdim}
171239462Sdim
172239462Sdim/// extractMallocCall - Returns the corresponding CallInst if the instruction
173239462Sdim/// is a malloc call.  Since CallInst::CreateMalloc() only creates calls, we
174239462Sdim/// ignore InvokeInst here.
175239462Sdimconst CallInst *llvm::extractMallocCall(const Value *I) {
176239462Sdim  return isMallocLikeFn(I) ? dyn_cast<CallInst>(I) : 0;
177239462Sdim}
178239462Sdim
179199481Srdivackystatic Value *computeArraySize(const CallInst *CI, const TargetData *TD,
180199481Srdivacky                               bool LookThroughSExt = false) {
181198892Srdivacky  if (!CI)
182198892Srdivacky    return NULL;
183198892Srdivacky
184198953Srdivacky  // The size of the malloc's result type must be known to determine array size.
185226633Sdim  Type *T = getMallocAllocatedType(CI);
186198953Srdivacky  if (!T || !T->isSized() || !TD)
187198892Srdivacky    return NULL;
188198892Srdivacky
189199481Srdivacky  unsigned ElementSize = TD->getTypeAllocSize(T);
190226633Sdim  if (StructType *ST = dyn_cast<StructType>(T))
191199481Srdivacky    ElementSize = TD->getStructLayout(ST)->getSizeInBytes();
192198892Srdivacky
193210299Sed  // If malloc call's arg can be determined to be a multiple of ElementSize,
194199481Srdivacky  // return the multiple.  Otherwise, return NULL.
195210299Sed  Value *MallocArg = CI->getArgOperand(0);
196199481Srdivacky  Value *Multiple = NULL;
197199481Srdivacky  if (ComputeMultiple(MallocArg, ElementSize, Multiple,
198199481Srdivacky                      LookThroughSExt))
199199481Srdivacky    return Multiple;
200198892Srdivacky
201198892Srdivacky  return NULL;
202198892Srdivacky}
203198892Srdivacky
204198892Srdivacky/// isArrayMalloc - Returns the corresponding CallInst if the instruction
205198892Srdivacky/// is a call to malloc whose array size can be determined and the array size
206198892Srdivacky/// is not constant 1.  Otherwise, return NULL.
207199481Srdivackyconst CallInst *llvm::isArrayMalloc(const Value *I, const TargetData *TD) {
208198892Srdivacky  const CallInst *CI = extractMallocCall(I);
209199481Srdivacky  Value *ArraySize = computeArraySize(CI, TD);
210198892Srdivacky
211198892Srdivacky  if (ArraySize &&
212210299Sed      ArraySize != ConstantInt::get(CI->getArgOperand(0)->getType(), 1))
213198892Srdivacky    return CI;
214198892Srdivacky
215198892Srdivacky  // CI is a non-array malloc or we can't figure out that it is an array malloc.
216198892Srdivacky  return NULL;
217198892Srdivacky}
218198892Srdivacky
219198892Srdivacky/// getMallocType - Returns the PointerType resulting from the malloc call.
220198953Srdivacky/// The PointerType depends on the number of bitcast uses of the malloc call:
221198953Srdivacky///   0: PointerType is the calls' return type.
222198953Srdivacky///   1: PointerType is the bitcast's result type.
223198953Srdivacky///  >1: Unique PointerType cannot be determined, return NULL.
224226633SdimPointerType *llvm::getMallocType(const CallInst *CI) {
225239462Sdim  assert(isMallocLikeFn(CI) && "getMallocType and not malloc call");
226198892Srdivacky
227226633Sdim  PointerType *MallocType = NULL;
228198953Srdivacky  unsigned NumOfBitCastUses = 0;
229198953Srdivacky
230198892Srdivacky  // Determine if CallInst has a bitcast use.
231206083Srdivacky  for (Value::const_use_iterator UI = CI->use_begin(), E = CI->use_end();
232198892Srdivacky       UI != E; )
233198953Srdivacky    if (const BitCastInst *BCI = dyn_cast<BitCastInst>(*UI++)) {
234198953Srdivacky      MallocType = cast<PointerType>(BCI->getDestTy());
235198953Srdivacky      NumOfBitCastUses++;
236198953Srdivacky    }
237198892Srdivacky
238198953Srdivacky  // Malloc call has 1 bitcast use, so type is the bitcast's destination type.
239198953Srdivacky  if (NumOfBitCastUses == 1)
240198953Srdivacky    return MallocType;
241198892Srdivacky
242198892Srdivacky  // Malloc call was not bitcast, so type is the malloc function's return type.
243198953Srdivacky  if (NumOfBitCastUses == 0)
244198892Srdivacky    return cast<PointerType>(CI->getType());
245198892Srdivacky
246198892Srdivacky  // Type could not be determined.
247198892Srdivacky  return NULL;
248198892Srdivacky}
249198892Srdivacky
250198953Srdivacky/// getMallocAllocatedType - Returns the Type allocated by malloc call.
251198953Srdivacky/// The Type depends on the number of bitcast uses of the malloc call:
252198953Srdivacky///   0: PointerType is the malloc calls' return type.
253198953Srdivacky///   1: PointerType is the bitcast's result type.
254198953Srdivacky///  >1: Unique PointerType cannot be determined, return NULL.
255226633SdimType *llvm::getMallocAllocatedType(const CallInst *CI) {
256226633Sdim  PointerType *PT = getMallocType(CI);
257198892Srdivacky  return PT ? PT->getElementType() : NULL;
258198892Srdivacky}
259198892Srdivacky
260198892Srdivacky/// getMallocArraySize - Returns the array size of a malloc call.  If the
261198892Srdivacky/// argument passed to malloc is a multiple of the size of the malloced type,
262198892Srdivacky/// then return that multiple.  For non-array mallocs, the multiple is
263198892Srdivacky/// constant 1.  Otherwise, return NULL for mallocs whose array size cannot be
264198892Srdivacky/// determined.
265199481SrdivackyValue *llvm::getMallocArraySize(CallInst *CI, const TargetData *TD,
266199481Srdivacky                                bool LookThroughSExt) {
267239462Sdim  assert(isMallocLikeFn(CI) && "getMallocArraySize and not malloc call");
268199481Srdivacky  return computeArraySize(CI, TD, LookThroughSExt);
269198892Srdivacky}
270198892Srdivacky
271198892Srdivacky
272239462Sdim/// extractCallocCall - Returns the corresponding CallInst if the instruction
273239462Sdim/// is a calloc call.
274239462Sdimconst CallInst *llvm::extractCallocCall(const Value *I) {
275239462Sdim  return isCallocLikeFn(I) ? cast<CallInst>(I) : 0;
276239462Sdim}
277239462Sdim
278239462Sdim
279210299Sed/// isFreeCall - Returns non-null if the value is a call to the builtin free()
280210299Sedconst CallInst *llvm::isFreeCall(const Value *I) {
281198892Srdivacky  const CallInst *CI = dyn_cast<CallInst>(I);
282198892Srdivacky  if (!CI)
283210299Sed    return 0;
284198892Srdivacky  Function *Callee = CI->getCalledFunction();
285221345Sdim  if (Callee == 0 || !Callee->isDeclaration())
286210299Sed    return 0;
287198892Srdivacky
288221345Sdim  if (Callee->getName() != "free" &&
289221345Sdim      Callee->getName() != "_ZdlPv" && // operator delete(void*)
290221345Sdim      Callee->getName() != "_ZdaPv")   // operator delete[](void*)
291221345Sdim    return 0;
292221345Sdim
293198892Srdivacky  // Check free prototype.
294198892Srdivacky  // FIXME: workaround for PR5130, this will be obsolete when a nobuiltin
295198892Srdivacky  // attribute will exist.
296226633Sdim  FunctionType *FTy = Callee->getFunctionType();
297198892Srdivacky  if (!FTy->getReturnType()->isVoidTy())
298210299Sed    return 0;
299198892Srdivacky  if (FTy->getNumParams() != 1)
300210299Sed    return 0;
301224145Sdim  if (FTy->getParamType(0) != Type::getInt8PtrTy(Callee->getContext()))
302210299Sed    return 0;
303198892Srdivacky
304210299Sed  return CI;
305198892Srdivacky}
306239462Sdim
307239462Sdim
308239462Sdim
309239462Sdim//===----------------------------------------------------------------------===//
310239462Sdim//  Utility functions to compute size of objects.
311239462Sdim//
312239462Sdim
313239462Sdim
314239462Sdim/// \brief Compute the size of the object pointed by Ptr. Returns true and the
315239462Sdim/// object size in Size if successful, and false otherwise.
316239462Sdim/// If RoundToAlign is true, then Size is rounded up to the aligment of allocas,
317239462Sdim/// byval arguments, and global variables.
318239462Sdimbool llvm::getObjectSize(const Value *Ptr, uint64_t &Size, const TargetData *TD,
319239462Sdim                         bool RoundToAlign) {
320239462Sdim  if (!TD)
321239462Sdim    return false;
322239462Sdim
323239462Sdim  ObjectSizeOffsetVisitor Visitor(TD, Ptr->getContext(), RoundToAlign);
324239462Sdim  SizeOffsetType Data = Visitor.compute(const_cast<Value*>(Ptr));
325239462Sdim  if (!Visitor.bothKnown(Data))
326239462Sdim    return false;
327239462Sdim
328239462Sdim  APInt ObjSize = Data.first, Offset = Data.second;
329239462Sdim  // check for overflow
330239462Sdim  if (Offset.slt(0) || ObjSize.ult(Offset))
331239462Sdim    Size = 0;
332239462Sdim  else
333239462Sdim    Size = (ObjSize - Offset).getZExtValue();
334239462Sdim  return true;
335239462Sdim}
336239462Sdim
337239462Sdim
338239462SdimSTATISTIC(ObjectVisitorArgument,
339239462Sdim          "Number of arguments with unsolved size and offset");
340239462SdimSTATISTIC(ObjectVisitorLoad,
341239462Sdim          "Number of load instructions with unsolved size and offset");
342239462Sdim
343239462Sdim
344239462SdimAPInt ObjectSizeOffsetVisitor::align(APInt Size, uint64_t Align) {
345239462Sdim  if (RoundToAlign && Align)
346239462Sdim    return APInt(IntTyBits, RoundUpToAlignment(Size.getZExtValue(), Align));
347239462Sdim  return Size;
348239462Sdim}
349239462Sdim
350239462SdimObjectSizeOffsetVisitor::ObjectSizeOffsetVisitor(const TargetData *TD,
351239462Sdim                                                 LLVMContext &Context,
352239462Sdim                                                 bool RoundToAlign)
353239462Sdim: TD(TD), RoundToAlign(RoundToAlign) {
354239462Sdim  IntegerType *IntTy = TD->getIntPtrType(Context);
355239462Sdim  IntTyBits = IntTy->getBitWidth();
356239462Sdim  Zero = APInt::getNullValue(IntTyBits);
357239462Sdim}
358239462Sdim
359239462SdimSizeOffsetType ObjectSizeOffsetVisitor::compute(Value *V) {
360239462Sdim  V = V->stripPointerCasts();
361239462Sdim
362239462Sdim  if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
363239462Sdim    return visitGEPOperator(*GEP);
364239462Sdim  if (Instruction *I = dyn_cast<Instruction>(V))
365239462Sdim    return visit(*I);
366239462Sdim  if (Argument *A = dyn_cast<Argument>(V))
367239462Sdim    return visitArgument(*A);
368239462Sdim  if (ConstantPointerNull *P = dyn_cast<ConstantPointerNull>(V))
369239462Sdim    return visitConstantPointerNull(*P);
370239462Sdim  if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
371239462Sdim    return visitGlobalVariable(*GV);
372239462Sdim  if (UndefValue *UV = dyn_cast<UndefValue>(V))
373239462Sdim    return visitUndefValue(*UV);
374239462Sdim  if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
375239462Sdim    if (CE->getOpcode() == Instruction::IntToPtr)
376239462Sdim      return unknown(); // clueless
377239462Sdim
378239462Sdim  DEBUG(dbgs() << "ObjectSizeOffsetVisitor::compute() unhandled value: " << *V
379239462Sdim        << '\n');
380239462Sdim  return unknown();
381239462Sdim}
382239462Sdim
383239462SdimSizeOffsetType ObjectSizeOffsetVisitor::visitAllocaInst(AllocaInst &I) {
384239462Sdim  if (!I.getAllocatedType()->isSized())
385239462Sdim    return unknown();
386239462Sdim
387239462Sdim  APInt Size(IntTyBits, TD->getTypeAllocSize(I.getAllocatedType()));
388239462Sdim  if (!I.isArrayAllocation())
389239462Sdim    return std::make_pair(align(Size, I.getAlignment()), Zero);
390239462Sdim
391239462Sdim  Value *ArraySize = I.getArraySize();
392239462Sdim  if (const ConstantInt *C = dyn_cast<ConstantInt>(ArraySize)) {
393239462Sdim    Size *= C->getValue().zextOrSelf(IntTyBits);
394239462Sdim    return std::make_pair(align(Size, I.getAlignment()), Zero);
395239462Sdim  }
396239462Sdim  return unknown();
397239462Sdim}
398239462Sdim
399239462SdimSizeOffsetType ObjectSizeOffsetVisitor::visitArgument(Argument &A) {
400239462Sdim  // no interprocedural analysis is done at the moment
401239462Sdim  if (!A.hasByValAttr()) {
402239462Sdim    ++ObjectVisitorArgument;
403239462Sdim    return unknown();
404239462Sdim  }
405239462Sdim  PointerType *PT = cast<PointerType>(A.getType());
406239462Sdim  APInt Size(IntTyBits, TD->getTypeAllocSize(PT->getElementType()));
407239462Sdim  return std::make_pair(align(Size, A.getParamAlignment()), Zero);
408239462Sdim}
409239462Sdim
410239462SdimSizeOffsetType ObjectSizeOffsetVisitor::visitCallSite(CallSite CS) {
411239462Sdim  const AllocFnsTy *FnData = getAllocationData(CS.getInstruction(), AnyAlloc);
412239462Sdim  if (!FnData)
413239462Sdim    return unknown();
414239462Sdim
415239462Sdim  // handle strdup-like functions separately
416239462Sdim  if (FnData->AllocTy == StrDupLike) {
417239462Sdim    APInt Size(IntTyBits, GetStringLength(CS.getArgument(0)));
418239462Sdim    if (!Size)
419239462Sdim      return unknown();
420239462Sdim
421239462Sdim    // strndup limits strlen
422239462Sdim    if (FnData->FstParam > 0) {
423239462Sdim      ConstantInt *Arg= dyn_cast<ConstantInt>(CS.getArgument(FnData->FstParam));
424239462Sdim      if (!Arg)
425239462Sdim        return unknown();
426239462Sdim
427239462Sdim      APInt MaxSize = Arg->getValue().zextOrSelf(IntTyBits);
428239462Sdim      if (Size.ugt(MaxSize))
429239462Sdim        Size = MaxSize + 1;
430239462Sdim    }
431239462Sdim    return std::make_pair(Size, Zero);
432239462Sdim  }
433239462Sdim
434239462Sdim  ConstantInt *Arg = dyn_cast<ConstantInt>(CS.getArgument(FnData->FstParam));
435239462Sdim  if (!Arg)
436239462Sdim    return unknown();
437239462Sdim
438239462Sdim  APInt Size = Arg->getValue().zextOrSelf(IntTyBits);
439239462Sdim  // size determined by just 1 parameter
440239462Sdim  if (FnData->SndParam < 0)
441239462Sdim    return std::make_pair(Size, Zero);
442239462Sdim
443239462Sdim  Arg = dyn_cast<ConstantInt>(CS.getArgument(FnData->SndParam));
444239462Sdim  if (!Arg)
445239462Sdim    return unknown();
446239462Sdim
447239462Sdim  Size *= Arg->getValue().zextOrSelf(IntTyBits);
448239462Sdim  return std::make_pair(Size, Zero);
449239462Sdim
450239462Sdim  // TODO: handle more standard functions (+ wchar cousins):
451239462Sdim  // - strdup / strndup
452239462Sdim  // - strcpy / strncpy
453239462Sdim  // - strcat / strncat
454239462Sdim  // - memcpy / memmove
455239462Sdim  // - strcat / strncat
456239462Sdim  // - memset
457239462Sdim}
458239462Sdim
459239462SdimSizeOffsetType
460239462SdimObjectSizeOffsetVisitor::visitConstantPointerNull(ConstantPointerNull&) {
461239462Sdim  return std::make_pair(Zero, Zero);
462239462Sdim}
463239462Sdim
464239462SdimSizeOffsetType
465239462SdimObjectSizeOffsetVisitor::visitExtractElementInst(ExtractElementInst&) {
466239462Sdim  return unknown();
467239462Sdim}
468239462Sdim
469239462SdimSizeOffsetType
470239462SdimObjectSizeOffsetVisitor::visitExtractValueInst(ExtractValueInst&) {
471239462Sdim  // Easy cases were already folded by previous passes.
472239462Sdim  return unknown();
473239462Sdim}
474239462Sdim
475239462SdimSizeOffsetType ObjectSizeOffsetVisitor::visitGEPOperator(GEPOperator &GEP) {
476239462Sdim  // Ignore self-referencing GEPs, they can occur in unreachable code.
477239462Sdim  if (&GEP == GEP.getPointerOperand())
478239462Sdim    return unknown();
479239462Sdim
480239462Sdim  SizeOffsetType PtrData = compute(GEP.getPointerOperand());
481239462Sdim  if (!bothKnown(PtrData) || !GEP.hasAllConstantIndices())
482239462Sdim    return unknown();
483239462Sdim
484239462Sdim  SmallVector<Value*, 8> Ops(GEP.idx_begin(), GEP.idx_end());
485239462Sdim  APInt Offset(IntTyBits,TD->getIndexedOffset(GEP.getPointerOperandType(),Ops));
486239462Sdim  return std::make_pair(PtrData.first, PtrData.second + Offset);
487239462Sdim}
488239462Sdim
489239462SdimSizeOffsetType ObjectSizeOffsetVisitor::visitGlobalVariable(GlobalVariable &GV){
490239462Sdim  if (!GV.hasDefinitiveInitializer())
491239462Sdim    return unknown();
492239462Sdim
493239462Sdim  APInt Size(IntTyBits, TD->getTypeAllocSize(GV.getType()->getElementType()));
494239462Sdim  return std::make_pair(align(Size, GV.getAlignment()), Zero);
495239462Sdim}
496239462Sdim
497239462SdimSizeOffsetType ObjectSizeOffsetVisitor::visitIntToPtrInst(IntToPtrInst&) {
498239462Sdim  // clueless
499239462Sdim  return unknown();
500239462Sdim}
501239462Sdim
502239462SdimSizeOffsetType ObjectSizeOffsetVisitor::visitLoadInst(LoadInst&) {
503239462Sdim  ++ObjectVisitorLoad;
504239462Sdim  return unknown();
505239462Sdim}
506239462Sdim
507239462SdimSizeOffsetType ObjectSizeOffsetVisitor::visitPHINode(PHINode&) {
508239462Sdim  // too complex to analyze statically.
509239462Sdim  return unknown();
510239462Sdim}
511239462Sdim
512239462SdimSizeOffsetType ObjectSizeOffsetVisitor::visitSelectInst(SelectInst &I) {
513239462Sdim  // ignore malformed self-looping selects
514239462Sdim  if (I.getTrueValue() == &I || I.getFalseValue() == &I)
515239462Sdim    return unknown();
516239462Sdim
517239462Sdim  SizeOffsetType TrueSide  = compute(I.getTrueValue());
518239462Sdim  SizeOffsetType FalseSide = compute(I.getFalseValue());
519239462Sdim  if (bothKnown(TrueSide) && bothKnown(FalseSide) && TrueSide == FalseSide)
520239462Sdim    return TrueSide;
521239462Sdim  return unknown();
522239462Sdim}
523239462Sdim
524239462SdimSizeOffsetType ObjectSizeOffsetVisitor::visitUndefValue(UndefValue&) {
525239462Sdim  return std::make_pair(Zero, Zero);
526239462Sdim}
527239462Sdim
528239462SdimSizeOffsetType ObjectSizeOffsetVisitor::visitInstruction(Instruction &I) {
529239462Sdim  DEBUG(dbgs() << "ObjectSizeOffsetVisitor unknown instruction:" << I << '\n');
530239462Sdim  return unknown();
531239462Sdim}
532239462Sdim
533239462Sdim
534239462SdimObjectSizeOffsetEvaluator::ObjectSizeOffsetEvaluator(const TargetData *TD,
535239462Sdim                                                     LLVMContext &Context)
536239462Sdim: TD(TD), Context(Context), Builder(Context, TargetFolder(TD)),
537239462SdimVisitor(TD, Context) {
538239462Sdim  IntTy = TD->getIntPtrType(Context);
539239462Sdim  Zero = ConstantInt::get(IntTy, 0);
540239462Sdim}
541239462Sdim
542239462SdimSizeOffsetEvalType ObjectSizeOffsetEvaluator::compute(Value *V) {
543239462Sdim  SizeOffsetEvalType Result = compute_(V);
544239462Sdim
545239462Sdim  if (!bothKnown(Result)) {
546239462Sdim    // erase everything that was computed in this iteration from the cache, so
547239462Sdim    // that no dangling references are left behind. We could be a bit smarter if
548239462Sdim    // we kept a dependency graph. It's probably not worth the complexity.
549239462Sdim    for (PtrSetTy::iterator I=SeenVals.begin(), E=SeenVals.end(); I != E; ++I) {
550239462Sdim      CacheMapTy::iterator CacheIt = CacheMap.find(*I);
551239462Sdim      // non-computable results can be safely cached
552239462Sdim      if (CacheIt != CacheMap.end() && anyKnown(CacheIt->second))
553239462Sdim        CacheMap.erase(CacheIt);
554239462Sdim    }
555239462Sdim  }
556239462Sdim
557239462Sdim  SeenVals.clear();
558239462Sdim  return Result;
559239462Sdim}
560239462Sdim
561239462SdimSizeOffsetEvalType ObjectSizeOffsetEvaluator::compute_(Value *V) {
562239462Sdim  SizeOffsetType Const = Visitor.compute(V);
563239462Sdim  if (Visitor.bothKnown(Const))
564239462Sdim    return std::make_pair(ConstantInt::get(Context, Const.first),
565239462Sdim                          ConstantInt::get(Context, Const.second));
566239462Sdim
567239462Sdim  V = V->stripPointerCasts();
568239462Sdim
569239462Sdim  // check cache
570239462Sdim  CacheMapTy::iterator CacheIt = CacheMap.find(V);
571239462Sdim  if (CacheIt != CacheMap.end())
572239462Sdim    return CacheIt->second;
573239462Sdim
574239462Sdim  // always generate code immediately before the instruction being
575239462Sdim  // processed, so that the generated code dominates the same BBs
576239462Sdim  Instruction *PrevInsertPoint = Builder.GetInsertPoint();
577239462Sdim  if (Instruction *I = dyn_cast<Instruction>(V))
578239462Sdim    Builder.SetInsertPoint(I);
579239462Sdim
580239462Sdim  // record the pointers that were handled in this run, so that they can be
581239462Sdim  // cleaned later if something fails
582239462Sdim  SeenVals.insert(V);
583239462Sdim
584239462Sdim  // now compute the size and offset
585239462Sdim  SizeOffsetEvalType Result;
586239462Sdim  if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
587239462Sdim    Result = visitGEPOperator(*GEP);
588239462Sdim  } else if (Instruction *I = dyn_cast<Instruction>(V)) {
589239462Sdim    Result = visit(*I);
590239462Sdim  } else if (isa<Argument>(V) ||
591239462Sdim             (isa<ConstantExpr>(V) &&
592239462Sdim              cast<ConstantExpr>(V)->getOpcode() == Instruction::IntToPtr) ||
593239462Sdim             isa<GlobalVariable>(V)) {
594239462Sdim    // ignore values where we cannot do more than what ObjectSizeVisitor can
595239462Sdim    Result = unknown();
596239462Sdim  } else {
597239462Sdim    DEBUG(dbgs() << "ObjectSizeOffsetEvaluator::compute() unhandled value: "
598239462Sdim          << *V << '\n');
599239462Sdim    Result = unknown();
600239462Sdim  }
601239462Sdim
602239462Sdim  if (PrevInsertPoint)
603239462Sdim    Builder.SetInsertPoint(PrevInsertPoint);
604239462Sdim
605239462Sdim  // Don't reuse CacheIt since it may be invalid at this point.
606239462Sdim  CacheMap[V] = Result;
607239462Sdim  return Result;
608239462Sdim}
609239462Sdim
610239462SdimSizeOffsetEvalType ObjectSizeOffsetEvaluator::visitAllocaInst(AllocaInst &I) {
611239462Sdim  if (!I.getAllocatedType()->isSized())
612239462Sdim    return unknown();
613239462Sdim
614239462Sdim  // must be a VLA
615239462Sdim  assert(I.isArrayAllocation());
616239462Sdim  Value *ArraySize = I.getArraySize();
617239462Sdim  Value *Size = ConstantInt::get(ArraySize->getType(),
618239462Sdim                                 TD->getTypeAllocSize(I.getAllocatedType()));
619239462Sdim  Size = Builder.CreateMul(Size, ArraySize);
620239462Sdim  return std::make_pair(Size, Zero);
621239462Sdim}
622239462Sdim
623239462SdimSizeOffsetEvalType ObjectSizeOffsetEvaluator::visitCallSite(CallSite CS) {
624239462Sdim  const AllocFnsTy *FnData = getAllocationData(CS.getInstruction(), AnyAlloc);
625239462Sdim  if (!FnData)
626239462Sdim    return unknown();
627239462Sdim
628239462Sdim  // handle strdup-like functions separately
629239462Sdim  if (FnData->AllocTy == StrDupLike) {
630239462Sdim    // TODO
631239462Sdim    return unknown();
632239462Sdim  }
633239462Sdim
634239462Sdim  Value *FirstArg = CS.getArgument(FnData->FstParam);
635239462Sdim  FirstArg = Builder.CreateZExt(FirstArg, IntTy);
636239462Sdim  if (FnData->SndParam < 0)
637239462Sdim    return std::make_pair(FirstArg, Zero);
638239462Sdim
639239462Sdim  Value *SecondArg = CS.getArgument(FnData->SndParam);
640239462Sdim  SecondArg = Builder.CreateZExt(SecondArg, IntTy);
641239462Sdim  Value *Size = Builder.CreateMul(FirstArg, SecondArg);
642239462Sdim  return std::make_pair(Size, Zero);
643239462Sdim
644239462Sdim  // TODO: handle more standard functions (+ wchar cousins):
645239462Sdim  // - strdup / strndup
646239462Sdim  // - strcpy / strncpy
647239462Sdim  // - strcat / strncat
648239462Sdim  // - memcpy / memmove
649239462Sdim  // - strcat / strncat
650239462Sdim  // - memset
651239462Sdim}
652239462Sdim
653239462SdimSizeOffsetEvalType
654239462SdimObjectSizeOffsetEvaluator::visitExtractElementInst(ExtractElementInst&) {
655239462Sdim  return unknown();
656239462Sdim}
657239462Sdim
658239462SdimSizeOffsetEvalType
659239462SdimObjectSizeOffsetEvaluator::visitExtractValueInst(ExtractValueInst&) {
660239462Sdim  return unknown();
661239462Sdim}
662239462Sdim
663239462SdimSizeOffsetEvalType
664239462SdimObjectSizeOffsetEvaluator::visitGEPOperator(GEPOperator &GEP) {
665239462Sdim  SizeOffsetEvalType PtrData = compute_(GEP.getPointerOperand());
666239462Sdim  if (!bothKnown(PtrData))
667239462Sdim    return unknown();
668239462Sdim
669239462Sdim  Value *Offset = EmitGEPOffset(&Builder, *TD, &GEP, /*NoAssumptions=*/true);
670239462Sdim  Offset = Builder.CreateAdd(PtrData.second, Offset);
671239462Sdim  return std::make_pair(PtrData.first, Offset);
672239462Sdim}
673239462Sdim
674239462SdimSizeOffsetEvalType ObjectSizeOffsetEvaluator::visitIntToPtrInst(IntToPtrInst&) {
675239462Sdim  // clueless
676239462Sdim  return unknown();
677239462Sdim}
678239462Sdim
679239462SdimSizeOffsetEvalType ObjectSizeOffsetEvaluator::visitLoadInst(LoadInst&) {
680239462Sdim  return unknown();
681239462Sdim}
682239462Sdim
683239462SdimSizeOffsetEvalType ObjectSizeOffsetEvaluator::visitPHINode(PHINode &PHI) {
684239462Sdim  // create 2 PHIs: one for size and another for offset
685239462Sdim  PHINode *SizePHI   = Builder.CreatePHI(IntTy, PHI.getNumIncomingValues());
686239462Sdim  PHINode *OffsetPHI = Builder.CreatePHI(IntTy, PHI.getNumIncomingValues());
687239462Sdim
688239462Sdim  // insert right away in the cache to handle recursive PHIs
689239462Sdim  CacheMap[&PHI] = std::make_pair(SizePHI, OffsetPHI);
690239462Sdim
691239462Sdim  // compute offset/size for each PHI incoming pointer
692239462Sdim  for (unsigned i = 0, e = PHI.getNumIncomingValues(); i != e; ++i) {
693239462Sdim    Builder.SetInsertPoint(PHI.getIncomingBlock(i)->getFirstInsertionPt());
694239462Sdim    SizeOffsetEvalType EdgeData = compute_(PHI.getIncomingValue(i));
695239462Sdim
696239462Sdim    if (!bothKnown(EdgeData)) {
697239462Sdim      OffsetPHI->replaceAllUsesWith(UndefValue::get(IntTy));
698239462Sdim      OffsetPHI->eraseFromParent();
699239462Sdim      SizePHI->replaceAllUsesWith(UndefValue::get(IntTy));
700239462Sdim      SizePHI->eraseFromParent();
701239462Sdim      return unknown();
702239462Sdim    }
703239462Sdim    SizePHI->addIncoming(EdgeData.first, PHI.getIncomingBlock(i));
704239462Sdim    OffsetPHI->addIncoming(EdgeData.second, PHI.getIncomingBlock(i));
705239462Sdim  }
706239462Sdim
707239462Sdim  Value *Size = SizePHI, *Offset = OffsetPHI, *Tmp;
708239462Sdim  if ((Tmp = SizePHI->hasConstantValue())) {
709239462Sdim    Size = Tmp;
710239462Sdim    SizePHI->replaceAllUsesWith(Size);
711239462Sdim    SizePHI->eraseFromParent();
712239462Sdim  }
713239462Sdim  if ((Tmp = OffsetPHI->hasConstantValue())) {
714239462Sdim    Offset = Tmp;
715239462Sdim    OffsetPHI->replaceAllUsesWith(Offset);
716239462Sdim    OffsetPHI->eraseFromParent();
717239462Sdim  }
718239462Sdim  return std::make_pair(Size, Offset);
719239462Sdim}
720239462Sdim
721239462SdimSizeOffsetEvalType ObjectSizeOffsetEvaluator::visitSelectInst(SelectInst &I) {
722239462Sdim  // ignore malformed self-looping selects
723239462Sdim  if (I.getTrueValue() == &I || I.getFalseValue() == &I)
724239462Sdim    return unknown();
725239462Sdim
726239462Sdim  SizeOffsetEvalType TrueSide  = compute_(I.getTrueValue());
727239462Sdim  SizeOffsetEvalType FalseSide = compute_(I.getFalseValue());
728239462Sdim
729239462Sdim  if (!bothKnown(TrueSide) || !bothKnown(FalseSide))
730239462Sdim    return unknown();
731239462Sdim  if (TrueSide == FalseSide)
732239462Sdim    return TrueSide;
733239462Sdim
734239462Sdim  Value *Size = Builder.CreateSelect(I.getCondition(), TrueSide.first,
735239462Sdim                                     FalseSide.first);
736239462Sdim  Value *Offset = Builder.CreateSelect(I.getCondition(), TrueSide.second,
737239462Sdim                                       FalseSide.second);
738239462Sdim  return std::make_pair(Size, Offset);
739239462Sdim}
740239462Sdim
741239462SdimSizeOffsetEvalType ObjectSizeOffsetEvaluator::visitInstruction(Instruction &I) {
742239462Sdim  DEBUG(dbgs() << "ObjectSizeOffsetEvaluator unknown instruction:" << I <<'\n');
743239462Sdim  return unknown();
744239462Sdim}
745