MemoryBuiltins.cpp revision 9e72a79ef4a9fcda482ce0b0e1f0bd6a4f16cffd
1//===------ MemoryBuiltins.cpp - Identify calls to memory builtins --------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This family of functions identifies calls to builtin functions that allocate
11// or free memory.
12//
13//===----------------------------------------------------------------------===//
14
15#define DEBUG_TYPE "memory-builtins"
16#include "llvm/ADT/Statistic.h"
17#include "llvm/ADT/STLExtras.h"
18#include "llvm/Analysis/MemoryBuiltins.h"
19#include "llvm/GlobalVariable.h"
20#include "llvm/Instructions.h"
21#include "llvm/Intrinsics.h"
22#include "llvm/Metadata.h"
23#include "llvm/Module.h"
24#include "llvm/Analysis/ValueTracking.h"
25#include "llvm/Support/Debug.h"
26#include "llvm/Support/MathExtras.h"
27#include "llvm/Support/raw_ostream.h"
28#include "llvm/Target/TargetData.h"
29#include "llvm/Transforms/Utils/Local.h"
30using namespace llvm;
31
32enum AllocType {
33  MallocLike         = 1<<0, // allocates
34  CallocLike         = 1<<1, // allocates + bzero
35  ReallocLike        = 1<<2, // reallocates
36  StrDupLike         = 1<<3,
37  AllocLike          = MallocLike | CallocLike | StrDupLike,
38  AnyAlloc           = MallocLike | CallocLike | ReallocLike | StrDupLike
39};
40
41struct AllocFnsTy {
42  const char *Name;
43  AllocType AllocTy;
44  unsigned char NumParams;
45  // First and Second size parameters (or -1 if unused)
46  unsigned char FstParam, SndParam;
47};
48
49static const AllocFnsTy AllocationFnData[] = {
50  {"malloc",         MallocLike,  1, 0,  -1},
51  {"valloc",         MallocLike,  1, 0,  -1},
52  {"_Znwj",          MallocLike,  1, 0,  -1}, // operator new(unsigned int)
53  {"_Znwm",          MallocLike,  1, 0,  -1}, // operator new(unsigned long)
54  {"_Znaj",          MallocLike,  1, 0,  -1}, // operator new[](unsigned int)
55  {"_Znam",          MallocLike,  1, 0,  -1}, // operator new[](unsigned long)
56  {"posix_memalign", MallocLike,  3, 2,  -1},
57  {"calloc",         CallocLike,  2, 0,  1},
58  {"realloc",        ReallocLike, 2, 1,  -1},
59  {"reallocf",       ReallocLike, 2, 1,  -1},
60  {"strdup",         StrDupLike,  1, -1, -1},
61  {"strndup",        StrDupLike,  2, -1, -1}
62};
63
64
65static Function *getCalledFunction(const Value *V, bool LookThroughBitCast) {
66  if (LookThroughBitCast)
67    V = V->stripPointerCasts();
68  const CallInst *CI = dyn_cast<CallInst>(V);
69  if (!CI)
70    return 0;
71
72  Function *Callee = CI->getCalledFunction();
73  if (!Callee || !Callee->isDeclaration())
74    return 0;
75  return Callee;
76}
77
78/// \brief Returns the allocation data for the given value if it is a call to a
79/// known allocation function, and NULL otherwise.
80static const AllocFnsTy *getAllocationData(const Value *V, AllocType AllocTy,
81                                           bool LookThroughBitCast = false) {
82  Function *Callee = getCalledFunction(V, LookThroughBitCast);
83  if (!Callee)
84    return 0;
85
86  unsigned i = 0;
87  bool found = false;
88  for ( ; i < array_lengthof(AllocationFnData); ++i) {
89    if (Callee->getName() == AllocationFnData[i].Name) {
90      found = true;
91      break;
92    }
93  }
94  if (!found)
95    return 0;
96
97  const AllocFnsTy *FnData = &AllocationFnData[i];
98  if ((FnData->AllocTy & AllocTy) == 0)
99    return 0;
100
101  // Check function prototype.
102  // FIXME: Check the nobuiltin metadata?? (PR5130)
103  unsigned FstParam = FnData->FstParam;
104  unsigned SndParam = FnData->SndParam;
105  FunctionType *FTy = Callee->getFunctionType();
106
107  if (FTy->getReturnType() == Type::getInt8PtrTy(FTy->getContext()) &&
108      FTy->getNumParams() == FnData->NumParams &&
109      (FstParam == (unsigned char)-1 ||
110       (FTy->getParamType(FstParam)->isIntegerTy(32) ||
111        FTy->getParamType(FstParam)->isIntegerTy(64))) &&
112      (SndParam == (unsigned char)-1 ||
113       FTy->getParamType(SndParam)->isIntegerTy(32) ||
114       FTy->getParamType(SndParam)->isIntegerTy(64)))
115    return FnData;
116  return 0;
117}
118
119static bool hasNoAliasAttr(const Value *V, bool LookThroughBitCast) {
120  Function *Callee = getCalledFunction(V, LookThroughBitCast);
121  return Callee && Callee->hasFnAttr(Attribute::NoAlias);
122}
123
124
125/// \brief Tests if a value is a call to a library function that allocates or
126/// reallocates memory (either malloc, calloc, realloc, or strdup like).
127bool llvm::isAllocationFn(const Value *V, bool LookThroughBitCast) {
128  return getAllocationData(V, AnyAlloc, LookThroughBitCast);
129}
130
131/// \brief Tests if a value is a call to a function that returns a NoAlias
132/// pointer (including malloc/calloc/strdup-like functions).
133bool llvm::isNoAliasFn(const Value *V, bool LookThroughBitCast) {
134  return isAllocLikeFn(V, LookThroughBitCast) ||
135         hasNoAliasAttr(V, LookThroughBitCast);
136}
137
138/// \brief Tests if a value is a call to a library function that allocates
139/// uninitialized memory (such as malloc).
140bool llvm::isMallocLikeFn(const Value *V, bool LookThroughBitCast) {
141  return getAllocationData(V, MallocLike, LookThroughBitCast);
142}
143
144/// \brief Tests if a value is a call to a library function that allocates
145/// zero-filled memory (such as calloc).
146bool llvm::isCallocLikeFn(const Value *V, bool LookThroughBitCast) {
147  return getAllocationData(V, CallocLike, LookThroughBitCast);
148}
149
150/// \brief Tests if a value is a call to a library function that allocates
151/// memory (either malloc, calloc, or strdup like).
152bool llvm::isAllocLikeFn(const Value *V, bool LookThroughBitCast) {
153  return getAllocationData(V, AllocLike, LookThroughBitCast);
154}
155
156/// \brief Tests if a value is a call to a library function that reallocates
157/// memory (such as realloc).
158bool llvm::isReallocLikeFn(const Value *V, bool LookThroughBitCast) {
159  return getAllocationData(V, ReallocLike, LookThroughBitCast);
160}
161
162/// extractMallocCall - Returns the corresponding CallInst if the instruction
163/// is a malloc call.  Since CallInst::CreateMalloc() only creates calls, we
164/// ignore InvokeInst here.
165const CallInst *llvm::extractMallocCall(const Value *I) {
166  return isMallocLikeFn(I) ? cast<CallInst>(I) : 0;
167}
168
169/// extractMallocCallFromBitCast - Returns the corresponding CallInst if the
170/// instruction is a bitcast of the result of a malloc call.
171const CallInst *llvm::extractMallocCallFromBitCast(const Value *I) {
172  const BitCastInst *BCI = dyn_cast<BitCastInst>(I);
173  return BCI ? extractMallocCall(BCI->getOperand(0)) : 0;
174}
175
176static Value *computeArraySize(const CallInst *CI, const TargetData *TD,
177                               bool LookThroughSExt = false) {
178  if (!CI)
179    return NULL;
180
181  // The size of the malloc's result type must be known to determine array size.
182  Type *T = getMallocAllocatedType(CI);
183  if (!T || !T->isSized() || !TD)
184    return NULL;
185
186  unsigned ElementSize = TD->getTypeAllocSize(T);
187  if (StructType *ST = dyn_cast<StructType>(T))
188    ElementSize = TD->getStructLayout(ST)->getSizeInBytes();
189
190  // If malloc call's arg can be determined to be a multiple of ElementSize,
191  // return the multiple.  Otherwise, return NULL.
192  Value *MallocArg = CI->getArgOperand(0);
193  Value *Multiple = NULL;
194  if (ComputeMultiple(MallocArg, ElementSize, Multiple,
195                      LookThroughSExt))
196    return Multiple;
197
198  return NULL;
199}
200
201/// isArrayMalloc - Returns the corresponding CallInst if the instruction
202/// is a call to malloc whose array size can be determined and the array size
203/// is not constant 1.  Otherwise, return NULL.
204const CallInst *llvm::isArrayMalloc(const Value *I, const TargetData *TD) {
205  const CallInst *CI = extractMallocCall(I);
206  Value *ArraySize = computeArraySize(CI, TD);
207
208  if (ArraySize &&
209      ArraySize != ConstantInt::get(CI->getArgOperand(0)->getType(), 1))
210    return CI;
211
212  // CI is a non-array malloc or we can't figure out that it is an array malloc.
213  return NULL;
214}
215
216/// getMallocType - Returns the PointerType resulting from the malloc call.
217/// The PointerType depends on the number of bitcast uses of the malloc call:
218///   0: PointerType is the calls' return type.
219///   1: PointerType is the bitcast's result type.
220///  >1: Unique PointerType cannot be determined, return NULL.
221PointerType *llvm::getMallocType(const CallInst *CI) {
222  assert(isMallocLikeFn(CI) && "getMallocType and not malloc call");
223
224  PointerType *MallocType = NULL;
225  unsigned NumOfBitCastUses = 0;
226
227  // Determine if CallInst has a bitcast use.
228  for (Value::const_use_iterator UI = CI->use_begin(), E = CI->use_end();
229       UI != E; )
230    if (const BitCastInst *BCI = dyn_cast<BitCastInst>(*UI++)) {
231      MallocType = cast<PointerType>(BCI->getDestTy());
232      NumOfBitCastUses++;
233    }
234
235  // Malloc call has 1 bitcast use, so type is the bitcast's destination type.
236  if (NumOfBitCastUses == 1)
237    return MallocType;
238
239  // Malloc call was not bitcast, so type is the malloc function's return type.
240  if (NumOfBitCastUses == 0)
241    return cast<PointerType>(CI->getType());
242
243  // Type could not be determined.
244  return NULL;
245}
246
247/// getMallocAllocatedType - Returns the Type allocated by malloc call.
248/// The Type depends on the number of bitcast uses of the malloc call:
249///   0: PointerType is the malloc calls' return type.
250///   1: PointerType is the bitcast's result type.
251///  >1: Unique PointerType cannot be determined, return NULL.
252Type *llvm::getMallocAllocatedType(const CallInst *CI) {
253  PointerType *PT = getMallocType(CI);
254  return PT ? PT->getElementType() : NULL;
255}
256
257/// getMallocArraySize - Returns the array size of a malloc call.  If the
258/// argument passed to malloc is a multiple of the size of the malloced type,
259/// then return that multiple.  For non-array mallocs, the multiple is
260/// constant 1.  Otherwise, return NULL for mallocs whose array size cannot be
261/// determined.
262Value *llvm::getMallocArraySize(CallInst *CI, const TargetData *TD,
263                                bool LookThroughSExt) {
264  assert(isMallocLikeFn(CI) && "getMallocArraySize and not malloc call");
265  return computeArraySize(CI, TD, LookThroughSExt);
266}
267
268
269/// extractCallocCall - Returns the corresponding CallInst if the instruction
270/// is a calloc call.
271const CallInst *llvm::extractCallocCall(const Value *I) {
272  return isCallocLikeFn(I) ? cast<CallInst>(I) : 0;
273}
274
275
276/// isFreeCall - Returns non-null if the value is a call to the builtin free()
277const CallInst *llvm::isFreeCall(const Value *I) {
278  const CallInst *CI = dyn_cast<CallInst>(I);
279  if (!CI)
280    return 0;
281  Function *Callee = CI->getCalledFunction();
282  if (Callee == 0 || !Callee->isDeclaration())
283    return 0;
284
285  if (Callee->getName() != "free" &&
286      Callee->getName() != "_ZdlPv" && // operator delete(void*)
287      Callee->getName() != "_ZdaPv")   // operator delete[](void*)
288    return 0;
289
290  // Check free prototype.
291  // FIXME: workaround for PR5130, this will be obsolete when a nobuiltin
292  // attribute will exist.
293  FunctionType *FTy = Callee->getFunctionType();
294  if (!FTy->getReturnType()->isVoidTy())
295    return 0;
296  if (FTy->getNumParams() != 1)
297    return 0;
298  if (FTy->getParamType(0) != Type::getInt8PtrTy(Callee->getContext()))
299    return 0;
300
301  return CI;
302}
303
304
305
306//===----------------------------------------------------------------------===//
307//  Utility functions to compute size of objects.
308//
309
310
311/// \brief Compute the size of the object pointed by Ptr. Returns true and the
312/// object size in Size if successful, and false otherwise.
313/// If RoundToAlign is true, then Size is rounded up to the aligment of allocas,
314/// byval arguments, and global variables.
315bool llvm::getObjectSize(const Value *Ptr, uint64_t &Size, const TargetData *TD,
316                         bool RoundToAlign) {
317  if (!TD)
318    return false;
319
320  ObjectSizeOffsetVisitor Visitor(TD, Ptr->getContext(), RoundToAlign);
321  SizeOffsetType Data = Visitor.compute(const_cast<Value*>(Ptr));
322  if (!Visitor.bothKnown(Data))
323    return false;
324
325  APInt ObjSize = Data.first, Offset = Data.second;
326  // check for overflow
327  if (Offset.slt(0) || ObjSize.ult(Offset))
328    Size = 0;
329  else
330    Size = (ObjSize - Offset).getZExtValue();
331  return true;
332}
333
334
335STATISTIC(ObjectVisitorArgument,
336          "Number of arguments with unsolved size and offset");
337STATISTIC(ObjectVisitorLoad,
338          "Number of load instructions with unsolved size and offset");
339
340
341APInt ObjectSizeOffsetVisitor::align(APInt Size, uint64_t Align) {
342  if (RoundToAlign && Align)
343    return APInt(IntTyBits, RoundUpToAlignment(Size.getZExtValue(), Align));
344  return Size;
345}
346
347ObjectSizeOffsetVisitor::ObjectSizeOffsetVisitor(const TargetData *TD,
348                                                 LLVMContext &Context,
349                                                 bool RoundToAlign)
350: TD(TD), RoundToAlign(RoundToAlign) {
351  IntegerType *IntTy = TD->getIntPtrType(Context);
352  IntTyBits = IntTy->getBitWidth();
353  Zero = APInt::getNullValue(IntTyBits);
354}
355
356SizeOffsetType ObjectSizeOffsetVisitor::compute(Value *V) {
357  V = V->stripPointerCasts();
358
359  if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
360    return visitGEPOperator(*GEP);
361  if (Instruction *I = dyn_cast<Instruction>(V))
362    return visit(*I);
363  if (Argument *A = dyn_cast<Argument>(V))
364    return visitArgument(*A);
365  if (ConstantPointerNull *P = dyn_cast<ConstantPointerNull>(V))
366    return visitConstantPointerNull(*P);
367  if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
368    return visitGlobalVariable(*GV);
369  if (UndefValue *UV = dyn_cast<UndefValue>(V))
370    return visitUndefValue(*UV);
371  if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
372    if (CE->getOpcode() == Instruction::IntToPtr)
373      return unknown(); // clueless
374
375  DEBUG(dbgs() << "ObjectSizeOffsetVisitor::compute() unhandled value: " << *V
376        << '\n');
377  return unknown();
378}
379
380SizeOffsetType ObjectSizeOffsetVisitor::visitAllocaInst(AllocaInst &I) {
381  if (!I.getAllocatedType()->isSized())
382    return unknown();
383
384  APInt Size(IntTyBits, TD->getTypeAllocSize(I.getAllocatedType()));
385  if (!I.isArrayAllocation())
386    return std::make_pair(align(Size, I.getAlignment()), Zero);
387
388  Value *ArraySize = I.getArraySize();
389  if (const ConstantInt *C = dyn_cast<ConstantInt>(ArraySize)) {
390    Size *= C->getValue().zextOrSelf(IntTyBits);
391    return std::make_pair(align(Size, I.getAlignment()), Zero);
392  }
393  return unknown();
394}
395
396SizeOffsetType ObjectSizeOffsetVisitor::visitArgument(Argument &A) {
397  // no interprocedural analysis is done at the moment
398  if (!A.hasByValAttr()) {
399    ++ObjectVisitorArgument;
400    return unknown();
401  }
402  PointerType *PT = cast<PointerType>(A.getType());
403  APInt Size(IntTyBits, TD->getTypeAllocSize(PT->getElementType()));
404  return std::make_pair(align(Size, A.getParamAlignment()), Zero);
405}
406
407SizeOffsetType ObjectSizeOffsetVisitor::visitCallSite(CallSite CS) {
408  const AllocFnsTy *FnData = getAllocationData(CS.getInstruction(), AnyAlloc);
409  if (!FnData)
410    return unknown();
411
412  // handle strdup-like functions separately
413  if (FnData->AllocTy == StrDupLike) {
414    // TODO
415    return unknown();
416  }
417
418  ConstantInt *Arg = dyn_cast<ConstantInt>(CS.getArgument(FnData->FstParam));
419  if (!Arg)
420    return unknown();
421
422  APInt Size = Arg->getValue();
423  // size determined by just 1 parameter
424  if (FnData->SndParam == (unsigned char)-1)
425    return std::make_pair(Size, Zero);
426
427  Arg = dyn_cast<ConstantInt>(CS.getArgument(FnData->SndParam));
428  if (!Arg)
429    return unknown();
430
431  Size *= Arg->getValue();
432  return std::make_pair(Size, Zero);
433
434  // TODO: handle more standard functions (+ wchar cousins):
435  // - strdup / strndup
436  // - strcpy / strncpy
437  // - strcat / strncat
438  // - memcpy / memmove
439  // - strcat / strncat
440  // - memset
441}
442
443SizeOffsetType
444ObjectSizeOffsetVisitor::visitConstantPointerNull(ConstantPointerNull&) {
445  return std::make_pair(Zero, Zero);
446}
447
448SizeOffsetType
449ObjectSizeOffsetVisitor::visitExtractValueInst(ExtractValueInst&) {
450  // Easy cases were already folded by previous passes.
451  return unknown();
452}
453
454SizeOffsetType ObjectSizeOffsetVisitor::visitGEPOperator(GEPOperator &GEP) {
455  SizeOffsetType PtrData = compute(GEP.getPointerOperand());
456  if (!bothKnown(PtrData) || !GEP.hasAllConstantIndices())
457    return unknown();
458
459  SmallVector<Value*, 8> Ops(GEP.idx_begin(), GEP.idx_end());
460  APInt Offset(IntTyBits,TD->getIndexedOffset(GEP.getPointerOperandType(),Ops));
461  return std::make_pair(PtrData.first, PtrData.second + Offset);
462}
463
464SizeOffsetType ObjectSizeOffsetVisitor::visitGlobalVariable(GlobalVariable &GV){
465  if (!GV.hasDefinitiveInitializer())
466    return unknown();
467
468  APInt Size(IntTyBits, TD->getTypeAllocSize(GV.getType()->getElementType()));
469  return std::make_pair(align(Size, GV.getAlignment()), Zero);
470}
471
472SizeOffsetType ObjectSizeOffsetVisitor::visitIntToPtrInst(IntToPtrInst&) {
473  // clueless
474  return unknown();
475}
476
477SizeOffsetType ObjectSizeOffsetVisitor::visitLoadInst(LoadInst&) {
478  ++ObjectVisitorLoad;
479  return unknown();
480}
481
482SizeOffsetType ObjectSizeOffsetVisitor::visitPHINode(PHINode&) {
483  // too complex to analyze statically.
484  return unknown();
485}
486
487SizeOffsetType ObjectSizeOffsetVisitor::visitSelectInst(SelectInst &I) {
488  SizeOffsetType TrueSide  = compute(I.getTrueValue());
489  SizeOffsetType FalseSide = compute(I.getFalseValue());
490  if (bothKnown(TrueSide) && bothKnown(FalseSide) && TrueSide == FalseSide)
491    return TrueSide;
492  return unknown();
493}
494
495SizeOffsetType ObjectSizeOffsetVisitor::visitUndefValue(UndefValue&) {
496  return std::make_pair(Zero, Zero);
497}
498
499SizeOffsetType ObjectSizeOffsetVisitor::visitInstruction(Instruction &I) {
500  DEBUG(dbgs() << "ObjectSizeOffsetVisitor unknown instruction:" << I << '\n');
501  return unknown();
502}
503
504
505ObjectSizeOffsetEvaluator::ObjectSizeOffsetEvaluator(const TargetData *TD,
506                                                     LLVMContext &Context)
507: TD(TD), Context(Context), Builder(Context, TargetFolder(TD)),
508Visitor(TD, Context) {
509  IntTy = TD->getIntPtrType(Context);
510  Zero = ConstantInt::get(IntTy, 0);
511}
512
513SizeOffsetEvalType ObjectSizeOffsetEvaluator::compute(Value *V) {
514  SizeOffsetEvalType Result = compute_(V);
515
516  if (!bothKnown(Result)) {
517    // erase everything that was computed in this iteration from the cache, so
518    // that no dangling references are left behind. We could be a bit smarter if
519    // we kept a dependency graph. It's probably not worth the complexity.
520    for (PtrSetTy::iterator I=SeenVals.begin(), E=SeenVals.end(); I != E; ++I) {
521      CacheMapTy::iterator CacheIt = CacheMap.find(*I);
522      // non-computable results can be safely cached
523      if (CacheIt != CacheMap.end() && anyKnown(CacheIt->second))
524        CacheMap.erase(CacheIt);
525    }
526  }
527
528  SeenVals.clear();
529  return Result;
530}
531
532SizeOffsetEvalType ObjectSizeOffsetEvaluator::compute_(Value *V) {
533  SizeOffsetType Const = Visitor.compute(V);
534  if (Visitor.bothKnown(Const))
535    return std::make_pair(ConstantInt::get(Context, Const.first),
536                          ConstantInt::get(Context, Const.second));
537
538  V = V->stripPointerCasts();
539
540  // check cache
541  CacheMapTy::iterator CacheIt = CacheMap.find(V);
542  if (CacheIt != CacheMap.end())
543    return CacheIt->second;
544
545  // always generate code immediately before the instruction being
546  // processed, so that the generated code dominates the same BBs
547  Instruction *PrevInsertPoint = Builder.GetInsertPoint();
548  if (Instruction *I = dyn_cast<Instruction>(V))
549    Builder.SetInsertPoint(I);
550
551  // record the pointers that were handled in this run, so that they can be
552  // cleaned later if something fails
553  SeenVals.insert(V);
554
555  // now compute the size and offset
556  SizeOffsetEvalType Result;
557  if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
558    Result = visitGEPOperator(*GEP);
559  } else if (Instruction *I = dyn_cast<Instruction>(V)) {
560    Result = visit(*I);
561  } else if (isa<Argument>(V) ||
562             (isa<ConstantExpr>(V) &&
563              cast<ConstantExpr>(V)->getOpcode() == Instruction::IntToPtr) ||
564             isa<GlobalVariable>(V)) {
565    // ignore values where we cannot do more than what ObjectSizeVisitor can
566    Result = unknown();
567  } else {
568    DEBUG(dbgs() << "ObjectSizeOffsetEvaluator::compute() unhandled value: "
569          << *V << '\n');
570    Result = unknown();
571  }
572
573  if (PrevInsertPoint)
574    Builder.SetInsertPoint(PrevInsertPoint);
575
576  // Don't reuse CacheIt since it may be invalid at this point.
577  CacheMap[V] = Result;
578  return Result;
579}
580
581SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitAllocaInst(AllocaInst &I) {
582  if (!I.getAllocatedType()->isSized())
583    return unknown();
584
585  // must be a VLA
586  assert(I.isArrayAllocation());
587  Value *ArraySize = I.getArraySize();
588  Value *Size = ConstantInt::get(ArraySize->getType(),
589                                 TD->getTypeAllocSize(I.getAllocatedType()));
590  Size = Builder.CreateMul(Size, ArraySize);
591  return std::make_pair(Size, Zero);
592}
593
594SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitCallSite(CallSite CS) {
595  const AllocFnsTy *FnData = getAllocationData(CS.getInstruction(), AnyAlloc);
596  if (!FnData)
597    return unknown();
598
599  // handle strdup-like functions separately
600  if (FnData->AllocTy == StrDupLike) {
601    // TODO
602    return unknown();
603  }
604
605  Value *FirstArg  = CS.getArgument(FnData->FstParam);
606  if (FnData->SndParam == (unsigned char)-1)
607    return std::make_pair(FirstArg, Zero);
608
609  Value *SecondArg = CS.getArgument(FnData->SndParam);
610  Value *Size = Builder.CreateMul(FirstArg, SecondArg);
611  return std::make_pair(Size, Zero);
612
613  // TODO: handle more standard functions (+ wchar cousins):
614  // - strdup / strndup
615  // - strcpy / strncpy
616  // - strcat / strncat
617  // - memcpy / memmove
618  // - strcat / strncat
619  // - memset
620}
621
622SizeOffsetEvalType
623ObjectSizeOffsetEvaluator::visitGEPOperator(GEPOperator &GEP) {
624  SizeOffsetEvalType PtrData = compute_(GEP.getPointerOperand());
625  if (!bothKnown(PtrData))
626    return unknown();
627
628  Value *Offset = EmitGEPOffset(&Builder, *TD, &GEP);
629  Offset = Builder.CreateAdd(PtrData.second, Offset);
630  return std::make_pair(PtrData.first, Offset);
631}
632
633SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitIntToPtrInst(IntToPtrInst&) {
634  // clueless
635  return unknown();
636}
637
638SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitLoadInst(LoadInst&) {
639  return unknown();
640}
641
642SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitPHINode(PHINode &PHI) {
643  // create 2 PHIs: one for size and another for offset
644  PHINode *SizePHI   = Builder.CreatePHI(IntTy, PHI.getNumIncomingValues());
645  PHINode *OffsetPHI = Builder.CreatePHI(IntTy, PHI.getNumIncomingValues());
646
647  // insert right away in the cache to handle recursive PHIs
648  CacheMap[&PHI] = std::make_pair(SizePHI, OffsetPHI);
649
650  // compute offset/size for each PHI incoming pointer
651  for (unsigned i = 0, e = PHI.getNumIncomingValues(); i != e; ++i) {
652    Builder.SetInsertPoint(PHI.getIncomingBlock(i)->getFirstInsertionPt());
653    SizeOffsetEvalType EdgeData = compute_(PHI.getIncomingValue(i));
654
655    if (!bothKnown(EdgeData)) {
656      OffsetPHI->replaceAllUsesWith(UndefValue::get(IntTy));
657      OffsetPHI->eraseFromParent();
658      SizePHI->replaceAllUsesWith(UndefValue::get(IntTy));
659      SizePHI->eraseFromParent();
660      return unknown();
661    }
662    SizePHI->addIncoming(EdgeData.first, PHI.getIncomingBlock(i));
663    OffsetPHI->addIncoming(EdgeData.second, PHI.getIncomingBlock(i));
664  }
665  return std::make_pair(SizePHI, OffsetPHI);
666}
667
668SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitSelectInst(SelectInst &I) {
669  SizeOffsetEvalType TrueSide  = compute_(I.getTrueValue());
670  SizeOffsetEvalType FalseSide = compute_(I.getFalseValue());
671
672  if (!bothKnown(TrueSide) || !bothKnown(FalseSide))
673    return unknown();
674  if (TrueSide == FalseSide)
675    return TrueSide;
676
677  Value *Size = Builder.CreateSelect(I.getCondition(), TrueSide.first,
678                                     FalseSide.first);
679  Value *Offset = Builder.CreateSelect(I.getCondition(), TrueSide.second,
680                                       FalseSide.second);
681  return std::make_pair(Size, Offset);
682}
683
684SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitInstruction(Instruction &I) {
685  DEBUG(dbgs() << "ObjectSizeOffsetEvaluator unknown instruction:" << I <<'\n');
686  return unknown();
687}
688