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