LLVM API Documentation

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