LLVM  8.0.0svn
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 
16 #include "llvm/ADT/APInt.h"
17 #include "llvm/ADT/None.h"
18 #include "llvm/ADT/Optional.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/Statistic.h"
21 #include "llvm/ADT/StringRef.h"
26 #include "llvm/IR/Argument.h"
27 #include "llvm/IR/Attributes.h"
28 #include "llvm/IR/Constants.h"
29 #include "llvm/IR/DataLayout.h"
30 #include "llvm/IR/DerivedTypes.h"
31 #include "llvm/IR/Function.h"
32 #include "llvm/IR/GlobalAlias.h"
33 #include "llvm/IR/GlobalVariable.h"
34 #include "llvm/IR/Instruction.h"
35 #include "llvm/IR/Instructions.h"
36 #include "llvm/IR/IntrinsicInst.h"
37 #include "llvm/IR/Operator.h"
38 #include "llvm/IR/Type.h"
39 #include "llvm/IR/Value.h"
40 #include "llvm/Support/Casting.h"
41 #include "llvm/Support/Debug.h"
44 #include <cassert>
45 #include <cstdint>
46 #include <iterator>
47 #include <utility>
48 
49 using namespace llvm;
50 
51 #define DEBUG_TYPE "memory-builtins"
52 
53 enum AllocType : uint8_t {
54  OpNewLike = 1<<0, // allocates; never returns null
55  MallocLike = 1<<1 | OpNewLike, // allocates; may return null
56  CallocLike = 1<<2, // allocates + bzero
57  ReallocLike = 1<<3, // reallocates
58  StrDupLike = 1<<4,
62 };
63 
64 struct AllocFnsTy {
66  unsigned NumParams;
67  // First and Second size parameters (or -1 if unused)
68  int FstParam, SndParam;
69 };
70 
71 // FIXME: certain users need more information. E.g., SimplifyLibCalls needs to
72 // know which functions are nounwind, noalias, nocapture parameters, etc.
73 static const std::pair<LibFunc, AllocFnsTy> AllocationFnData[] = {
74  {LibFunc_malloc, {MallocLike, 1, 0, -1}},
75  {LibFunc_valloc, {MallocLike, 1, 0, -1}},
76  {LibFunc_Znwj, {OpNewLike, 1, 0, -1}}, // new(unsigned int)
77  {LibFunc_ZnwjRKSt9nothrow_t, {MallocLike, 2, 0, -1}}, // new(unsigned int, nothrow)
78  {LibFunc_ZnwjSt11align_val_t, {OpNewLike, 2, 0, -1}}, // new(unsigned int, align_val_t)
79  {LibFunc_ZnwjSt11align_val_tRKSt9nothrow_t, // new(unsigned int, align_val_t, nothrow)
80  {MallocLike, 3, 0, -1}},
81  {LibFunc_Znwm, {OpNewLike, 1, 0, -1}}, // new(unsigned long)
82  {LibFunc_ZnwmRKSt9nothrow_t, {MallocLike, 2, 0, -1}}, // new(unsigned long, nothrow)
83  {LibFunc_ZnwmSt11align_val_t, {OpNewLike, 2, 0, -1}}, // new(unsigned long, align_val_t)
84  {LibFunc_ZnwmSt11align_val_tRKSt9nothrow_t, // new(unsigned long, align_val_t, nothrow)
85  {MallocLike, 3, 0, -1}},
86  {LibFunc_Znaj, {OpNewLike, 1, 0, -1}}, // new[](unsigned int)
87  {LibFunc_ZnajRKSt9nothrow_t, {MallocLike, 2, 0, -1}}, // new[](unsigned int, nothrow)
88  {LibFunc_ZnajSt11align_val_t, {OpNewLike, 2, 0, -1}}, // new[](unsigned int, align_val_t)
89  {LibFunc_ZnajSt11align_val_tRKSt9nothrow_t, // new[](unsigned int, align_val_t, nothrow)
90  {MallocLike, 3, 0, -1}},
91  {LibFunc_Znam, {OpNewLike, 1, 0, -1}}, // new[](unsigned long)
92  {LibFunc_ZnamRKSt9nothrow_t, {MallocLike, 2, 0, -1}}, // new[](unsigned long, nothrow)
93  {LibFunc_ZnamSt11align_val_t, {OpNewLike, 2, 0, -1}}, // new[](unsigned long, align_val_t)
94  {LibFunc_ZnamSt11align_val_tRKSt9nothrow_t, // new[](unsigned long, align_val_t, nothrow)
95  {MallocLike, 3, 0, -1}},
96  {LibFunc_msvc_new_int, {OpNewLike, 1, 0, -1}}, // new(unsigned int)
97  {LibFunc_msvc_new_int_nothrow, {MallocLike, 2, 0, -1}}, // new(unsigned int, nothrow)
98  {LibFunc_msvc_new_longlong, {OpNewLike, 1, 0, -1}}, // new(unsigned long long)
99  {LibFunc_msvc_new_longlong_nothrow, {MallocLike, 2, 0, -1}}, // new(unsigned long long, nothrow)
100  {LibFunc_msvc_new_array_int, {OpNewLike, 1, 0, -1}}, // new[](unsigned int)
101  {LibFunc_msvc_new_array_int_nothrow, {MallocLike, 2, 0, -1}}, // new[](unsigned int, nothrow)
102  {LibFunc_msvc_new_array_longlong, {OpNewLike, 1, 0, -1}}, // new[](unsigned long long)
103  {LibFunc_msvc_new_array_longlong_nothrow, {MallocLike, 2, 0, -1}}, // new[](unsigned long long, nothrow)
104  {LibFunc_calloc, {CallocLike, 2, 0, 1}},
105  {LibFunc_realloc, {ReallocLike, 2, 1, -1}},
106  {LibFunc_reallocf, {ReallocLike, 2, 1, -1}},
107  {LibFunc_strdup, {StrDupLike, 1, -1, -1}},
108  {LibFunc_strndup, {StrDupLike, 2, 1, -1}}
109  // TODO: Handle "int posix_memalign(void **, size_t, size_t)"
110 };
111 
112 static const Function *getCalledFunction(const Value *V, bool LookThroughBitCast,
113  bool &IsNoBuiltin) {
114  // Don't care about intrinsics in this case.
115  if (isa<IntrinsicInst>(V))
116  return nullptr;
117 
118  if (LookThroughBitCast)
119  V = V->stripPointerCasts();
120 
121  ImmutableCallSite CS(V);
122  if (!CS.getInstruction())
123  return nullptr;
124 
125  IsNoBuiltin = CS.isNoBuiltin();
126 
127  if (const Function *Callee = CS.getCalledFunction())
128  return Callee;
129  return nullptr;
130 }
131 
132 /// Returns the allocation data for the given value if it's either a call to a
133 /// known allocation function, or a call to a function with the allocsize
134 /// attribute.
137  const TargetLibraryInfo *TLI) {
138  // Make sure that the function is available.
139  StringRef FnName = Callee->getName();
140  LibFunc TLIFn;
141  if (!TLI || !TLI->getLibFunc(FnName, TLIFn) || !TLI->has(TLIFn))
142  return None;
143 
144  const auto *Iter = find_if(
145  AllocationFnData, [TLIFn](const std::pair<LibFunc, AllocFnsTy> &P) {
146  return P.first == TLIFn;
147  });
148 
149  if (Iter == std::end(AllocationFnData))
150  return None;
151 
152  const AllocFnsTy *FnData = &Iter->second;
153  if ((FnData->AllocTy & AllocTy) != FnData->AllocTy)
154  return None;
155 
156  // Check function prototype.
157  int FstParam = FnData->FstParam;
158  int SndParam = FnData->SndParam;
159  FunctionType *FTy = Callee->getFunctionType();
160 
161  if (FTy->getReturnType() == Type::getInt8PtrTy(FTy->getContext()) &&
162  FTy->getNumParams() == FnData->NumParams &&
163  (FstParam < 0 ||
164  (FTy->getParamType(FstParam)->isIntegerTy(32) ||
165  FTy->getParamType(FstParam)->isIntegerTy(64))) &&
166  (SndParam < 0 ||
167  FTy->getParamType(SndParam)->isIntegerTy(32) ||
168  FTy->getParamType(SndParam)->isIntegerTy(64)))
169  return *FnData;
170  return None;
171 }
172 
174  const TargetLibraryInfo *TLI,
175  bool LookThroughBitCast = false) {
176  bool IsNoBuiltinCall;
177  if (const Function *Callee =
178  getCalledFunction(V, LookThroughBitCast, IsNoBuiltinCall))
179  if (!IsNoBuiltinCall)
180  return getAllocationDataForFunction(Callee, AllocTy, TLI);
181  return None;
182 }
183 
185  const TargetLibraryInfo *TLI) {
186  bool IsNoBuiltinCall;
187  const Function *Callee =
188  getCalledFunction(V, /*LookThroughBitCast=*/false, IsNoBuiltinCall);
189  if (!Callee)
190  return None;
191 
192  // Prefer to use existing information over allocsize. This will give us an
193  // accurate AllocTy.
194  if (!IsNoBuiltinCall)
197  return Data;
198 
199  Attribute Attr = Callee->getFnAttribute(Attribute::AllocSize);
200  if (Attr == Attribute())
201  return None;
202 
203  std::pair<unsigned, Optional<unsigned>> Args = Attr.getAllocSizeArgs();
204 
205  AllocFnsTy Result;
206  // Because allocsize only tells us how many bytes are allocated, we're not
207  // really allowed to assume anything, so we use MallocLike.
208  Result.AllocTy = MallocLike;
209  Result.NumParams = Callee->getNumOperands();
210  Result.FstParam = Args.first;
211  Result.SndParam = Args.second.getValueOr(-1);
212  return Result;
213 }
214 
215 static bool hasNoAliasAttr(const Value *V, bool LookThroughBitCast) {
216  ImmutableCallSite CS(LookThroughBitCast ? V->stripPointerCasts() : V);
217  return CS && CS.hasRetAttr(Attribute::NoAlias);
218 }
219 
220 /// Tests if a value is a call or invoke to a library function that
221 /// allocates or reallocates memory (either malloc, calloc, realloc, or strdup
222 /// like).
223 bool llvm::isAllocationFn(const Value *V, const TargetLibraryInfo *TLI,
224  bool LookThroughBitCast) {
225  return getAllocationData(V, AnyAlloc, TLI, LookThroughBitCast).hasValue();
226 }
227 
228 /// Tests if a value is a call or invoke to a function that returns a
229 /// NoAlias pointer (including malloc/calloc/realloc/strdup-like functions).
230 bool llvm::isNoAliasFn(const Value *V, const TargetLibraryInfo *TLI,
231  bool LookThroughBitCast) {
232  // it's safe to consider realloc as noalias since accessing the original
233  // pointer is undefined behavior
234  return isAllocationFn(V, TLI, LookThroughBitCast) ||
235  hasNoAliasAttr(V, LookThroughBitCast);
236 }
237 
238 /// Tests if a value is a call or invoke to a library function that
239 /// allocates uninitialized memory (such as malloc).
240 bool llvm::isMallocLikeFn(const Value *V, const TargetLibraryInfo *TLI,
241  bool LookThroughBitCast) {
242  return getAllocationData(V, MallocLike, TLI, LookThroughBitCast).hasValue();
243 }
244 
245 /// Tests if a value is a call or invoke to a library function that
246 /// allocates zero-filled memory (such as calloc).
247 bool llvm::isCallocLikeFn(const Value *V, const TargetLibraryInfo *TLI,
248  bool LookThroughBitCast) {
249  return getAllocationData(V, CallocLike, TLI, LookThroughBitCast).hasValue();
250 }
251 
252 /// Tests if a value is a call or invoke to a library function that
253 /// allocates memory similar to malloc or calloc.
255  bool LookThroughBitCast) {
256  return getAllocationData(V, MallocOrCallocLike, TLI,
257  LookThroughBitCast).hasValue();
258 }
259 
260 /// Tests if a value is a call or invoke to a library function that
261 /// allocates memory (either malloc, calloc, or strdup like).
262 bool llvm::isAllocLikeFn(const Value *V, const TargetLibraryInfo *TLI,
263  bool LookThroughBitCast) {
264  return getAllocationData(V, AllocLike, TLI, LookThroughBitCast).hasValue();
265 }
266 
267 /// extractMallocCall - Returns the corresponding CallInst if the instruction
268 /// is a malloc call. Since CallInst::CreateMalloc() only creates calls, we
269 /// ignore InvokeInst here.
271  const TargetLibraryInfo *TLI) {
272  return isMallocLikeFn(I, TLI) ? dyn_cast<CallInst>(I) : nullptr;
273 }
274 
275 static Value *computeArraySize(const CallInst *CI, const DataLayout &DL,
276  const TargetLibraryInfo *TLI,
277  bool LookThroughSExt = false) {
278  if (!CI)
279  return nullptr;
280 
281  // The size of the malloc's result type must be known to determine array size.
282  Type *T = getMallocAllocatedType(CI, TLI);
283  if (!T || !T->isSized())
284  return nullptr;
285 
286  unsigned ElementSize = DL.getTypeAllocSize(T);
287  if (StructType *ST = dyn_cast<StructType>(T))
288  ElementSize = DL.getStructLayout(ST)->getSizeInBytes();
289 
290  // If malloc call's arg can be determined to be a multiple of ElementSize,
291  // return the multiple. Otherwise, return NULL.
292  Value *MallocArg = CI->getArgOperand(0);
293  Value *Multiple = nullptr;
294  if (ComputeMultiple(MallocArg, ElementSize, Multiple, LookThroughSExt))
295  return Multiple;
296 
297  return nullptr;
298 }
299 
300 /// getMallocType - Returns the PointerType resulting from the malloc call.
301 /// The PointerType depends on the number of bitcast uses of the malloc call:
302 /// 0: PointerType is the calls' return type.
303 /// 1: PointerType is the bitcast's result type.
304 /// >1: Unique PointerType cannot be determined, return NULL.
306  const TargetLibraryInfo *TLI) {
307  assert(isMallocLikeFn(CI, TLI) && "getMallocType and not malloc call");
308 
309  PointerType *MallocType = nullptr;
310  unsigned NumOfBitCastUses = 0;
311 
312  // Determine if CallInst has a bitcast use.
313  for (Value::const_user_iterator UI = CI->user_begin(), E = CI->user_end();
314  UI != E;)
315  if (const BitCastInst *BCI = dyn_cast<BitCastInst>(*UI++)) {
316  MallocType = cast<PointerType>(BCI->getDestTy());
317  NumOfBitCastUses++;
318  }
319 
320  // Malloc call has 1 bitcast use, so type is the bitcast's destination type.
321  if (NumOfBitCastUses == 1)
322  return MallocType;
323 
324  // Malloc call was not bitcast, so type is the malloc function's return type.
325  if (NumOfBitCastUses == 0)
326  return cast<PointerType>(CI->getType());
327 
328  // Type could not be determined.
329  return nullptr;
330 }
331 
332 /// getMallocAllocatedType - Returns the Type allocated by malloc call.
333 /// The Type depends on the number of bitcast uses of the malloc call:
334 /// 0: PointerType is the malloc calls' return type.
335 /// 1: PointerType is the bitcast's result type.
336 /// >1: Unique PointerType cannot be determined, return NULL.
338  const TargetLibraryInfo *TLI) {
339  PointerType *PT = getMallocType(CI, TLI);
340  return PT ? PT->getElementType() : nullptr;
341 }
342 
343 /// getMallocArraySize - Returns the array size of a malloc call. If the
344 /// argument passed to malloc is a multiple of the size of the malloced type,
345 /// then return that multiple. For non-array mallocs, the multiple is
346 /// constant 1. Otherwise, return NULL for mallocs whose array size cannot be
347 /// determined.
349  const TargetLibraryInfo *TLI,
350  bool LookThroughSExt) {
351  assert(isMallocLikeFn(CI, TLI) && "getMallocArraySize and not malloc call");
352  return computeArraySize(CI, DL, TLI, LookThroughSExt);
353 }
354 
355 /// extractCallocCall - Returns the corresponding CallInst if the instruction
356 /// is a calloc call.
358  const TargetLibraryInfo *TLI) {
359  return isCallocLikeFn(I, TLI) ? cast<CallInst>(I) : nullptr;
360 }
361 
362 /// isFreeCall - Returns non-null if the value is a call to the builtin free()
363 const CallInst *llvm::isFreeCall(const Value *I, const TargetLibraryInfo *TLI) {
364  bool IsNoBuiltinCall;
365  const Function *Callee =
366  getCalledFunction(I, /*LookThroughBitCast=*/false, IsNoBuiltinCall);
367  if (Callee == nullptr || IsNoBuiltinCall)
368  return nullptr;
369 
370  StringRef FnName = Callee->getName();
371  LibFunc TLIFn;
372  if (!TLI || !TLI->getLibFunc(FnName, TLIFn) || !TLI->has(TLIFn))
373  return nullptr;
374 
375  unsigned ExpectedNumParams;
376  if (TLIFn == LibFunc_free ||
377  TLIFn == LibFunc_ZdlPv || // operator delete(void*)
378  TLIFn == LibFunc_ZdaPv || // operator delete[](void*)
379  TLIFn == LibFunc_msvc_delete_ptr32 || // operator delete(void*)
380  TLIFn == LibFunc_msvc_delete_ptr64 || // operator delete(void*)
381  TLIFn == LibFunc_msvc_delete_array_ptr32 || // operator delete[](void*)
382  TLIFn == LibFunc_msvc_delete_array_ptr64) // operator delete[](void*)
383  ExpectedNumParams = 1;
384  else if (TLIFn == LibFunc_ZdlPvj || // delete(void*, uint)
385  TLIFn == LibFunc_ZdlPvm || // delete(void*, ulong)
386  TLIFn == LibFunc_ZdlPvRKSt9nothrow_t || // delete(void*, nothrow)
387  TLIFn == LibFunc_ZdlPvSt11align_val_t || // delete(void*, align_val_t)
388  TLIFn == LibFunc_ZdaPvj || // delete[](void*, uint)
389  TLIFn == LibFunc_ZdaPvm || // delete[](void*, ulong)
390  TLIFn == LibFunc_ZdaPvRKSt9nothrow_t || // delete[](void*, nothrow)
391  TLIFn == LibFunc_ZdaPvSt11align_val_t || // delete[](void*, align_val_t)
392  TLIFn == LibFunc_msvc_delete_ptr32_int || // delete(void*, uint)
393  TLIFn == LibFunc_msvc_delete_ptr64_longlong || // delete(void*, ulonglong)
394  TLIFn == LibFunc_msvc_delete_ptr32_nothrow || // delete(void*, nothrow)
395  TLIFn == LibFunc_msvc_delete_ptr64_nothrow || // delete(void*, nothrow)
396  TLIFn == LibFunc_msvc_delete_array_ptr32_int || // delete[](void*, uint)
397  TLIFn == LibFunc_msvc_delete_array_ptr64_longlong || // delete[](void*, ulonglong)
398  TLIFn == LibFunc_msvc_delete_array_ptr32_nothrow || // delete[](void*, nothrow)
399  TLIFn == LibFunc_msvc_delete_array_ptr64_nothrow) // delete[](void*, nothrow)
400  ExpectedNumParams = 2;
401  else if (TLIFn == LibFunc_ZdaPvSt11align_val_tRKSt9nothrow_t || // delete(void*, align_val_t, nothrow)
402  TLIFn == LibFunc_ZdlPvSt11align_val_tRKSt9nothrow_t) // delete[](void*, align_val_t, nothrow)
403  ExpectedNumParams = 3;
404  else
405  return nullptr;
406 
407  // Check free prototype.
408  // FIXME: workaround for PR5130, this will be obsolete when a nobuiltin
409  // attribute will exist.
410  FunctionType *FTy = Callee->getFunctionType();
411  if (!FTy->getReturnType()->isVoidTy())
412  return nullptr;
413  if (FTy->getNumParams() != ExpectedNumParams)
414  return nullptr;
415  if (FTy->getParamType(0) != Type::getInt8PtrTy(Callee->getContext()))
416  return nullptr;
417 
418  return dyn_cast<CallInst>(I);
419 }
420 
421 //===----------------------------------------------------------------------===//
422 // Utility functions to compute size of objects.
423 //
425  if (Data.second.isNegative() || Data.first.ult(Data.second))
426  return APInt(Data.first.getBitWidth(), 0);
427  return Data.first - Data.second;
428 }
429 
430 /// Compute the size of the object pointed by Ptr. Returns true and the
431 /// object size in Size if successful, and false otherwise.
432 /// If RoundToAlign is true, then Size is rounded up to the alignment of
433 /// allocas, byval arguments, and global variables.
434 bool llvm::getObjectSize(const Value *Ptr, uint64_t &Size, const DataLayout &DL,
435  const TargetLibraryInfo *TLI, ObjectSizeOpts Opts) {
436  ObjectSizeOffsetVisitor Visitor(DL, TLI, Ptr->getContext(), Opts);
437  SizeOffsetType Data = Visitor.compute(const_cast<Value*>(Ptr));
438  if (!Visitor.bothKnown(Data))
439  return false;
440 
441  Size = getSizeWithOverflow(Data).getZExtValue();
442  return true;
443 }
444 
446  const DataLayout &DL,
447  const TargetLibraryInfo *TLI,
448  bool MustSucceed) {
449  assert(ObjectSize->getIntrinsicID() == Intrinsic::objectsize &&
450  "ObjectSize must be a call to llvm.objectsize!");
451 
452  bool MaxVal = cast<ConstantInt>(ObjectSize->getArgOperand(1))->isZero();
453  ObjectSizeOpts EvalOptions;
454  // Unless we have to fold this to something, try to be as accurate as
455  // possible.
456  if (MustSucceed)
457  EvalOptions.EvalMode =
459  else
461 
462  EvalOptions.NullIsUnknownSize =
463  cast<ConstantInt>(ObjectSize->getArgOperand(2))->isOne();
464 
465  // FIXME: Does it make sense to just return a failure value if the size won't
466  // fit in the output and `!MustSucceed`?
467  uint64_t Size;
468  auto *ResultType = cast<IntegerType>(ObjectSize->getType());
469  if (getObjectSize(ObjectSize->getArgOperand(0), Size, DL, TLI, EvalOptions) &&
470  isUIntN(ResultType->getBitWidth(), Size))
471  return ConstantInt::get(ResultType, Size);
472 
473  if (!MustSucceed)
474  return nullptr;
475 
476  return ConstantInt::get(ResultType, MaxVal ? -1ULL : 0);
477 }
478 
479 STATISTIC(ObjectVisitorArgument,
480  "Number of arguments with unsolved size and offset");
481 STATISTIC(ObjectVisitorLoad,
482  "Number of load instructions with unsolved size and offset");
483 
484 APInt ObjectSizeOffsetVisitor::align(APInt Size, uint64_t Align) {
485  if (Options.RoundToAlign && Align)
486  return APInt(IntTyBits, alignTo(Size.getZExtValue(), Align));
487  return Size;
488 }
489 
491  const TargetLibraryInfo *TLI,
493  ObjectSizeOpts Options)
494  : DL(DL), TLI(TLI), Options(Options) {
495  // Pointer size must be rechecked for each object visited since it could have
496  // a different address space.
497 }
498 
500  IntTyBits = DL.getPointerTypeSizeInBits(V->getType());
501  Zero = APInt::getNullValue(IntTyBits);
502 
503  V = V->stripPointerCasts();
504  if (Instruction *I = dyn_cast<Instruction>(V)) {
505  // If we have already seen this instruction, bail out. Cycles can happen in
506  // unreachable code after constant propagation.
507  if (!SeenInsts.insert(I).second)
508  return unknown();
509 
510  if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
511  return visitGEPOperator(*GEP);
512  return visit(*I);
513  }
514  if (Argument *A = dyn_cast<Argument>(V))
515  return visitArgument(*A);
516  if (ConstantPointerNull *P = dyn_cast<ConstantPointerNull>(V))
517  return visitConstantPointerNull(*P);
518  if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
519  return visitGlobalAlias(*GA);
520  if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
521  return visitGlobalVariable(*GV);
522  if (UndefValue *UV = dyn_cast<UndefValue>(V))
523  return visitUndefValue(*UV);
524  if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
525  if (CE->getOpcode() == Instruction::IntToPtr)
526  return unknown(); // clueless
527  if (CE->getOpcode() == Instruction::GetElementPtr)
528  return visitGEPOperator(cast<GEPOperator>(*CE));
529  }
530 
531  LLVM_DEBUG(dbgs() << "ObjectSizeOffsetVisitor::compute() unhandled value: "
532  << *V << '\n');
533  return unknown();
534 }
535 
536 /// When we're compiling N-bit code, and the user uses parameters that are
537 /// greater than N bits (e.g. uint64_t on a 32-bit build), we can run into
538 /// trouble with APInt size issues. This function handles resizing + overflow
539 /// checks for us. Check and zext or trunc \p I depending on IntTyBits and
540 /// I's value.
541 bool ObjectSizeOffsetVisitor::CheckedZextOrTrunc(APInt &I) {
542  // More bits than we can handle. Checking the bit width isn't necessary, but
543  // it's faster than checking active bits, and should give `false` in the
544  // vast majority of cases.
545  if (I.getBitWidth() > IntTyBits && I.getActiveBits() > IntTyBits)
546  return false;
547  if (I.getBitWidth() != IntTyBits)
548  I = I.zextOrTrunc(IntTyBits);
549  return true;
550 }
551 
553  if (!I.getAllocatedType()->isSized())
554  return unknown();
555 
556  APInt Size(IntTyBits, DL.getTypeAllocSize(I.getAllocatedType()));
557  if (!I.isArrayAllocation())
558  return std::make_pair(align(Size, I.getAlignment()), Zero);
559 
560  Value *ArraySize = I.getArraySize();
561  if (const ConstantInt *C = dyn_cast<ConstantInt>(ArraySize)) {
562  APInt NumElems = C->getValue();
563  if (!CheckedZextOrTrunc(NumElems))
564  return unknown();
565 
566  bool Overflow;
567  Size = Size.umul_ov(NumElems, Overflow);
568  return Overflow ? unknown() : std::make_pair(align(Size, I.getAlignment()),
569  Zero);
570  }
571  return unknown();
572 }
573 
575  // No interprocedural analysis is done at the moment.
576  if (!A.hasByValOrInAllocaAttr()) {
577  ++ObjectVisitorArgument;
578  return unknown();
579  }
580  PointerType *PT = cast<PointerType>(A.getType());
581  APInt Size(IntTyBits, DL.getTypeAllocSize(PT->getElementType()));
582  return std::make_pair(align(Size, A.getParamAlignment()), Zero);
583 }
584 
587  if (!FnData)
588  return unknown();
589 
590  // Handle strdup-like functions separately.
591  if (FnData->AllocTy == StrDupLike) {
592  APInt Size(IntTyBits, GetStringLength(CS.getArgument(0)));
593  if (!Size)
594  return unknown();
595 
596  // Strndup limits strlen.
597  if (FnData->FstParam > 0) {
598  ConstantInt *Arg =
600  if (!Arg)
601  return unknown();
602 
603  APInt MaxSize = Arg->getValue().zextOrSelf(IntTyBits);
604  if (Size.ugt(MaxSize))
605  Size = MaxSize + 1;
606  }
607  return std::make_pair(Size, Zero);
608  }
609 
611  if (!Arg)
612  return unknown();
613 
614  APInt Size = Arg->getValue();
615  if (!CheckedZextOrTrunc(Size))
616  return unknown();
617 
618  // Size is determined by just 1 parameter.
619  if (FnData->SndParam < 0)
620  return std::make_pair(Size, Zero);
621 
622  Arg = dyn_cast<ConstantInt>(CS.getArgument(FnData->SndParam));
623  if (!Arg)
624  return unknown();
625 
626  APInt NumElems = Arg->getValue();
627  if (!CheckedZextOrTrunc(NumElems))
628  return unknown();
629 
630  bool Overflow;
631  Size = Size.umul_ov(NumElems, Overflow);
632  return Overflow ? unknown() : std::make_pair(Size, Zero);
633 
634  // TODO: handle more standard functions (+ wchar cousins):
635  // - strdup / strndup
636  // - strcpy / strncpy
637  // - strcat / strncat
638  // - memcpy / memmove
639  // - strcat / strncat
640  // - memset
641 }
642 
645  // If null is unknown, there's nothing we can do. Additionally, non-zero
646  // address spaces can make use of null, so we don't presume to know anything
647  // about that.
648  //
649  // TODO: How should this work with address space casts? We currently just drop
650  // them on the floor, but it's unclear what we should do when a NULL from
651  // addrspace(1) gets casted to addrspace(0) (or vice-versa).
652  if (Options.NullIsUnknownSize || CPN.getType()->getAddressSpace())
653  return unknown();
654  return std::make_pair(Zero, Zero);
655 }
656 
659  return unknown();
660 }
661 
664  // Easy cases were already folded by previous passes.
665  return unknown();
666 }
667 
669  SizeOffsetType PtrData = compute(GEP.getPointerOperand());
670  APInt Offset(IntTyBits, 0);
671  if (!bothKnown(PtrData) || !GEP.accumulateConstantOffset(DL, Offset))
672  return unknown();
673 
674  return std::make_pair(PtrData.first, PtrData.second + Offset);
675 }
676 
678  if (GA.isInterposable())
679  return unknown();
680  return compute(GA.getAliasee());
681 }
682 
684  if (!GV.hasDefinitiveInitializer())
685  return unknown();
686 
687  APInt Size(IntTyBits, DL.getTypeAllocSize(GV.getType()->getElementType()));
688  return std::make_pair(align(Size, GV.getAlignment()), Zero);
689 }
690 
692  // clueless
693  return unknown();
694 }
695 
697  ++ObjectVisitorLoad;
698  return unknown();
699 }
700 
702  // too complex to analyze statically.
703  return unknown();
704 }
705 
707  SizeOffsetType TrueSide = compute(I.getTrueValue());
708  SizeOffsetType FalseSide = compute(I.getFalseValue());
709  if (bothKnown(TrueSide) && bothKnown(FalseSide)) {
710  if (TrueSide == FalseSide) {
711  return TrueSide;
712  }
713 
714  APInt TrueResult = getSizeWithOverflow(TrueSide);
715  APInt FalseResult = getSizeWithOverflow(FalseSide);
716 
717  if (TrueResult == FalseResult) {
718  return TrueSide;
719  }
720  if (Options.EvalMode == ObjectSizeOpts::Mode::Min) {
721  if (TrueResult.slt(FalseResult))
722  return TrueSide;
723  return FalseSide;
724  }
725  if (Options.EvalMode == ObjectSizeOpts::Mode::Max) {
726  if (TrueResult.sgt(FalseResult))
727  return TrueSide;
728  return FalseSide;
729  }
730  }
731  return unknown();
732 }
733 
735  return std::make_pair(Zero, Zero);
736 }
737 
739  LLVM_DEBUG(dbgs() << "ObjectSizeOffsetVisitor unknown instruction:" << I
740  << '\n');
741  return unknown();
742 }
743 
745  const DataLayout &DL, const TargetLibraryInfo *TLI, LLVMContext &Context,
746  bool RoundToAlign)
747  : DL(DL), TLI(TLI), Context(Context), Builder(Context, TargetFolder(DL)),
748  RoundToAlign(RoundToAlign) {
749  // IntTy and Zero must be set for each compute() since the address space may
750  // be different for later objects.
751 }
752 
754  // XXX - Are vectors of pointers possible here?
755  IntTy = cast<IntegerType>(DL.getIntPtrType(V->getType()));
756  Zero = ConstantInt::get(IntTy, 0);
757 
758  SizeOffsetEvalType Result = compute_(V);
759 
760  if (!bothKnown(Result)) {
761  // Erase everything that was computed in this iteration from the cache, so
762  // that no dangling references are left behind. We could be a bit smarter if
763  // we kept a dependency graph. It's probably not worth the complexity.
764  for (const Value *SeenVal : SeenVals) {
765  CacheMapTy::iterator CacheIt = CacheMap.find(SeenVal);
766  // non-computable results can be safely cached
767  if (CacheIt != CacheMap.end() && anyKnown(CacheIt->second))
768  CacheMap.erase(CacheIt);
769  }
770  }
771 
772  SeenVals.clear();
773  return Result;
774 }
775 
776 SizeOffsetEvalType ObjectSizeOffsetEvaluator::compute_(Value *V) {
777  ObjectSizeOpts ObjSizeOptions;
778  ObjSizeOptions.RoundToAlign = RoundToAlign;
779 
780  ObjectSizeOffsetVisitor Visitor(DL, TLI, Context, ObjSizeOptions);
781  SizeOffsetType Const = Visitor.compute(V);
782  if (Visitor.bothKnown(Const))
783  return std::make_pair(ConstantInt::get(Context, Const.first),
784  ConstantInt::get(Context, Const.second));
785 
786  V = V->stripPointerCasts();
787 
788  // Check cache.
789  CacheMapTy::iterator CacheIt = CacheMap.find(V);
790  if (CacheIt != CacheMap.end())
791  return CacheIt->second;
792 
793  // Always generate code immediately before the instruction being
794  // processed, so that the generated code dominates the same BBs.
795  BuilderTy::InsertPointGuard Guard(Builder);
796  if (Instruction *I = dyn_cast<Instruction>(V))
797  Builder.SetInsertPoint(I);
798 
799  // Now compute the size and offset.
800  SizeOffsetEvalType Result;
801 
802  // Record the pointers that were handled in this run, so that they can be
803  // cleaned later if something fails. We also use this set to break cycles that
804  // can occur in dead code.
805  if (!SeenVals.insert(V).second) {
806  Result = unknown();
807  } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
808  Result = visitGEPOperator(*GEP);
809  } else if (Instruction *I = dyn_cast<Instruction>(V)) {
810  Result = visit(*I);
811  } else if (isa<Argument>(V) ||
812  (isa<ConstantExpr>(V) &&
813  cast<ConstantExpr>(V)->getOpcode() == Instruction::IntToPtr) ||
814  isa<GlobalAlias>(V) ||
815  isa<GlobalVariable>(V)) {
816  // Ignore values where we cannot do more than ObjectSizeVisitor.
817  Result = unknown();
818  } else {
819  LLVM_DEBUG(
820  dbgs() << "ObjectSizeOffsetEvaluator::compute() unhandled value: " << *V
821  << '\n');
822  Result = unknown();
823  }
824 
825  // Don't reuse CacheIt since it may be invalid at this point.
826  CacheMap[V] = Result;
827  return Result;
828 }
829 
831  if (!I.getAllocatedType()->isSized())
832  return unknown();
833 
834  // must be a VLA
836  Value *ArraySize = I.getArraySize();
837  Value *Size = ConstantInt::get(ArraySize->getType(),
839  Size = Builder.CreateMul(Size, ArraySize);
840  return std::make_pair(Size, Zero);
841 }
842 
845  if (!FnData)
846  return unknown();
847 
848  // Handle strdup-like functions separately.
849  if (FnData->AllocTy == StrDupLike) {
850  // TODO
851  return unknown();
852  }
853 
854  Value *FirstArg = CS.getArgument(FnData->FstParam);
855  FirstArg = Builder.CreateZExt(FirstArg, IntTy);
856  if (FnData->SndParam < 0)
857  return std::make_pair(FirstArg, Zero);
858 
859  Value *SecondArg = CS.getArgument(FnData->SndParam);
860  SecondArg = Builder.CreateZExt(SecondArg, IntTy);
861  Value *Size = Builder.CreateMul(FirstArg, SecondArg);
862  return std::make_pair(Size, Zero);
863 
864  // TODO: handle more standard functions (+ wchar cousins):
865  // - strdup / strndup
866  // - strcpy / strncpy
867  // - strcat / strncat
868  // - memcpy / memmove
869  // - strcat / strncat
870  // - memset
871 }
872 
875  return unknown();
876 }
877 
880  return unknown();
881 }
882 
885  SizeOffsetEvalType PtrData = compute_(GEP.getPointerOperand());
886  if (!bothKnown(PtrData))
887  return unknown();
888 
889  Value *Offset = EmitGEPOffset(&Builder, DL, &GEP, /*NoAssumptions=*/true);
890  Offset = Builder.CreateAdd(PtrData.second, Offset);
891  return std::make_pair(PtrData.first, Offset);
892 }
893 
895  // clueless
896  return unknown();
897 }
898 
900  return unknown();
901 }
902 
904  // Create 2 PHIs: one for size and another for offset.
905  PHINode *SizePHI = Builder.CreatePHI(IntTy, PHI.getNumIncomingValues());
906  PHINode *OffsetPHI = Builder.CreatePHI(IntTy, PHI.getNumIncomingValues());
907 
908  // Insert right away in the cache to handle recursive PHIs.
909  CacheMap[&PHI] = std::make_pair(SizePHI, OffsetPHI);
910 
911  // Compute offset/size for each PHI incoming pointer.
912  for (unsigned i = 0, e = PHI.getNumIncomingValues(); i != e; ++i) {
914  SizeOffsetEvalType EdgeData = compute_(PHI.getIncomingValue(i));
915 
916  if (!bothKnown(EdgeData)) {
917  OffsetPHI->replaceAllUsesWith(UndefValue::get(IntTy));
918  OffsetPHI->eraseFromParent();
919  SizePHI->replaceAllUsesWith(UndefValue::get(IntTy));
920  SizePHI->eraseFromParent();
921  return unknown();
922  }
923  SizePHI->addIncoming(EdgeData.first, PHI.getIncomingBlock(i));
924  OffsetPHI->addIncoming(EdgeData.second, PHI.getIncomingBlock(i));
925  }
926 
927  Value *Size = SizePHI, *Offset = OffsetPHI, *Tmp;
928  if ((Tmp = SizePHI->hasConstantValue())) {
929  Size = Tmp;
930  SizePHI->replaceAllUsesWith(Size);
931  SizePHI->eraseFromParent();
932  }
933  if ((Tmp = OffsetPHI->hasConstantValue())) {
934  Offset = Tmp;
935  OffsetPHI->replaceAllUsesWith(Offset);
936  OffsetPHI->eraseFromParent();
937  }
938  return std::make_pair(Size, Offset);
939 }
940 
942  SizeOffsetEvalType TrueSide = compute_(I.getTrueValue());
943  SizeOffsetEvalType FalseSide = compute_(I.getFalseValue());
944 
945  if (!bothKnown(TrueSide) || !bothKnown(FalseSide))
946  return unknown();
947  if (TrueSide == FalseSide)
948  return TrueSide;
949 
950  Value *Size = Builder.CreateSelect(I.getCondition(), TrueSide.first,
951  FalseSide.first);
952  Value *Offset = Builder.CreateSelect(I.getCondition(), TrueSide.second,
953  FalseSide.second);
954  return std::make_pair(Size, Offset);
955 }
956 
958  LLVM_DEBUG(dbgs() << "ObjectSizeOffsetEvaluator unknown instruction:" << I
959  << '\n');
960  return unknown();
961 }
bool getObjectSize(const Value *Ptr, uint64_t &Size, const DataLayout &DL, const TargetLibraryInfo *TLI, ObjectSizeOpts Opts={})
Compute the size of the object pointed by Ptr.
Value * EmitGEPOffset(IRBuilderTy *Builder, const DataLayout &DL, User *GEP, bool NoAssumptions=false)
Given a getelementptr instruction/constantexpr, emit the code necessary to compute the offset from th...
Definition: Local.h:29
uint64_t CallInst * C
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks &#39;this&#39; from the containing basic block and deletes it.
Definition: Instruction.cpp:68
unsigned getAlignment() const
Definition: GlobalObject.h:59
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...
A parsed version of the target data layout string in and methods for querying it. ...
Definition: DataLayout.h:111
const_iterator end(StringRef path)
Get end iterator over path.
Definition: Path.cpp:259
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
bool hasDefinitiveInitializer() const
hasDefinitiveInitializer - Whether the global variable has an initializer, and any other instances of...
static const std::pair< LibFunc, AllocFnsTy > AllocationFnData[]
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
This instruction extracts a struct member or array element value from an aggregate value...
uint64_t getZExtValue() const
Get zero extended value.
Definition: APInt.h:1557
This class represents an incoming formal argument to a Function.
Definition: Argument.h:30
LLVMContext & Context
Compute iterated dominance frontiers using a linear time algorithm.
Definition: AllocatorList.h:24
Type * getParamType(unsigned i) const
Parameter type accessors.
Definition: DerivedTypes.h:135
bool isSized(SmallPtrSetImpl< Type *> *Visited=nullptr) const
Return true if it makes sense to take the size of this type.
Definition: Type.h:265
unsigned NumParams
const CallInst * extractCallocCall(const Value *I, const TargetLibraryInfo *TLI)
extractCallocCall - Returns the corresponding CallInst if the instruction is a calloc call...
const StructLayout * getStructLayout(StructType *Ty) const
Returns a StructLayout object, indicating the alignment of the struct, its size, and the offsets of i...
Definition: DataLayout.cpp:588
bool hasByValOrInAllocaAttr() const
Return true if this argument has the byval attribute or inalloca attribute.
Definition: Function.cpp:106
std::pair< Value *, Value * > SizeOffsetEvalType
bool NullIsUnknownSize
If this is true, null pointers in address space 0 will be treated as though they can&#39;t be evaluated...
bool slt(const APInt &RHS) const
Signed less than comparison.
Definition: APInt.h:1198
This class represents a function call, abstracting a target machine&#39;s calling convention.
static Optional< AllocFnsTy > getAllocationDataForFunction(const Function *Callee, AllocType AllocTy, const TargetLibraryInfo *TLI)
Returns the allocation data for the given value if it&#39;s either a call to a known allocation function...
const Value * getTrueValue() const
The two locations do not alias at all.
Definition: AliasAnalysis.h:85
bool RoundToAlign
Whether to round the result up to the alignment of allocas, byval arguments, and global variables...
LLVMContext & getContext() const
All values hold a context through their type.
Definition: Value.cpp:714
SizeOffsetType visitAllocaInst(AllocaInst &I)
bool isInterposable() const
Return true if this global&#39;s definition can be substituted with an arbitrary definition at link time...
Definition: GlobalValue.h:420
bool sgt(const APInt &RHS) const
Signed greather than comparison.
Definition: APInt.h:1268
AllocType
STATISTIC(NumFunctions, "Total number of functions")
uint64_t alignTo(uint64_t Value, uint64_t Align, uint64_t Skew=0)
Returns the next integer (mod 2**64) that is greater than or equal to Value and is a multiple of Alig...
Definition: MathExtras.h:685
An instruction for reading from memory.
Definition: Instructions.h:168
APInt zextOrTrunc(unsigned width) const
Zero extend or truncate to width.
Definition: APInt.cpp:876
SizeOffsetType visitArgument(Argument &A)
Hexagon Common GEP
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition: APInt.h:1503
bool accumulateConstantOffset(const DataLayout &DL, APInt &Offset) const
Accumulate the constant address offset of this GEP if possible.
Definition: Operator.cpp:35
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
Definition: Type.h:130
const CallInst * isFreeCall(const Value *I, const TargetLibraryInfo *TLI)
isFreeCall - Returns non-null if the value is a call to the builtin free()
This class represents the LLVM &#39;select&#39; instruction.
unsigned getAlignment() const
Return the alignment of the memory that is being allocated by the instruction.
Definition: Instructions.h:113
SizeOffsetEvalType visitGEPOperator(GEPOperator &GEP)
SizeOffsetType visitExtractValueInst(ExtractValueInst &I)
SizeOffsetType visitGEPOperator(GEPOperator &GEP)
unsigned getPointerTypeSizeInBits(Type *) const
Layout pointer size, in bits, based on the type.
Definition: DataLayout.cpp:638
&#39;undef&#39; values are things that do not have specified contents.
Definition: Constants.h:1282
static Optional< AllocFnsTy > getAllocationSize(const Value *V, const TargetLibraryInfo *TLI)
Class to represent struct types.
Definition: DerivedTypes.h:201
APInt zextOrSelf(unsigned width) const
Zero extend or truncate to width.
Definition: APInt.cpp:892
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition: Type.h:197
SizeOffsetEvalType visitCallSite(CallSite CS)
SizeOffsetType visitIntToPtrInst(IntToPtrInst &)
This file contains the simple types necessary to represent the attributes associated with functions a...
InstrTy * getInstruction() const
Definition: CallSite.h:92
Value * CreateAdd(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition: IRBuilder.h:974
This file implements a class to represent arbitrary precision integral constant values and operations...
ObjectSizeOffsetEvaluator(const DataLayout &DL, const TargetLibraryInfo *TLI, LLVMContext &Context, bool RoundToAlign=false)
unsigned getActiveBits() const
Compute the number of active bits in the value.
Definition: APInt.h:1527
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...
Same as Min, except we pick the maximum size of all of the branches.
A constant value that is initialized with an expression using other constant values.
Definition: Constants.h:885
Class to represent function types.
Definition: DerivedTypes.h:103
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:245
Evaluate all branches of an unknown condition.
bool isNoBuiltin() const
Return true if the call should not be treated as a call to a builtin.
Definition: CallSite.h:428
bool has(LibFunc F) const
Tests whether a library function is available.
This class represents a no-op cast from one type to another.
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition: Constants.h:138
TargetFolder - Create constants with target dependent folding.
Definition: TargetFolder.h:32
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition: Value.cpp:439
std::pair< unsigned, Optional< unsigned > > getAllocSizeArgs() const
Returns the argument numbers for the allocsize attribute (or pair(0, 0) if not known).
Definition: Attributes.cpp:237
Value * CreateZExt(Value *V, Type *DestTy, const Twine &Name="")
Definition: IRBuilder.h:1568
uint64_t GetStringLength(const Value *V, unsigned CharSize=8)
If we can compute the length of the string pointed to by the specified pointer, return &#39;len+1&#39;...
SizeOffsetType visitInstruction(Instruction &I)
amdgpu Simplify well known AMD library false Value * Callee
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block...
Definition: IRBuilder.h:127
Class to represent pointers.
Definition: DerivedTypes.h:467
iterator find(const_arg_type_t< KeyT > Val)
Definition: DenseMap.h:176
Value * getMallocArraySize(CallInst *CI, const DataLayout &DL, const TargetLibraryInfo *TLI, bool LookThroughSExt=false)
getMallocArraySize - Returns the array size of a malloc call.
SizeOffsetType visitGlobalVariable(GlobalVariable &GV)
bool isVoidTy() const
Return true if this is &#39;void&#39;.
Definition: Type.h:141
IntegerType * getIntPtrType(LLVMContext &C, unsigned AddressSpace=0) const
Returns an integer type with size at least as big as that of a pointer in the given address space...
Definition: DataLayout.cpp:742
#define P(N)
bool erase(const KeyT &Val)
Definition: DenseMap.h:298
SizeOffsetEvalType visitSelectInst(SelectInst &I)
const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
Definition: BasicBlock.cpp:219
ConstantInt * lowerObjectSizeCall(IntrinsicInst *ObjectSize, const DataLayout &DL, const TargetLibraryInfo *TLI, bool MustSucceed)
Try to turn a call to @llvm.objectsize into an integer value of the given Type.
The instances of the Type class are immutable: once they are created, they are never changed...
Definition: Type.h:46
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:69
const CallInst * extractMallocCall(const Value *I, const TargetLibraryInfo *TLI)
extractMallocCall - Returns the corresponding CallInst if the instruction is a malloc call...
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
Value * CreateSelect(Value *C, Value *True, Value *False, const Twine &Name="", Instruction *MDFrom=nullptr)
Definition: IRBuilder.h:1913
unsigned getNumParams() const
Return the number of fixed parameters this function type requires.
Definition: DerivedTypes.h:139
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Definition: SmallPtrSet.h:371
static Value * computeArraySize(const CallInst *CI, const DataLayout &DL, const TargetLibraryInfo *TLI, bool LookThroughSExt=false)
static APInt getSizeWithOverflow(const SizeOffsetType &Data)
Value * getPointerOperand()
Definition: Operator.h:467
static bool hasNoAliasAttr(const Value *V, bool LookThroughBitCast)
unsigned getAddressSpace() const
Return the address space of the Pointer type.
Definition: DerivedTypes.h:495
static Optional< AllocFnsTy > getAllocationData(const Value *V, AllocType AllocTy, const TargetLibraryInfo *TLI, bool LookThroughBitCast=false)
auto find_if(R &&Range, UnaryPredicate P) -> decltype(adl_begin(Range))
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly...
Definition: STLExtras.h:1076
This class represents a cast from an integer to a pointer.
const Value * getCondition() const
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function. ...
Definition: Function.cpp:194
static UndefValue * get(Type *T)
Static factory methods - Return an &#39;undef&#39; object of the specified type.
Definition: Constants.cpp:1392
const Value * stripPointerCasts() const
Strip off pointer casts, all-zero GEPs, and aliases.
Definition: Value.cpp:539
SizeOffsetType visitCallSite(CallSite CS)
const Value * getArraySize() const
Get the number of elements allocated.
Definition: Instructions.h:93
std::pair< APInt, APInt > SizeOffsetType
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
static PointerType * getInt8PtrTy(LLVMContext &C, unsigned AS=0)
Definition: Type.cpp:220
PointerType * getMallocType(const CallInst *CI, const TargetLibraryInfo *TLI)
getMallocType - Returns the PointerType resulting from the malloc call.
Value * CreateMul(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition: IRBuilder.h:1008
Type * getAllocatedType() const
Return the type that is being allocated by the instruction.
Definition: Instructions.h:106
SizeOffsetType visitSelectInst(SelectInst &I)
Intrinsic::ID getIntrinsicID() const
Return the intrinsic ID of this intrinsic.
Definition: IntrinsicInst.h:51
SizeOffsetType visitExtractElementInst(ExtractElementInst &I)
SizeOffsetType visitGlobalAlias(GlobalAlias &GA)
PHINode * CreatePHI(Type *Ty, unsigned NumReservedValues, const Twine &Name="")
Definition: IRBuilder.h:1878
SizeOffsetEvalType visitInstruction(Instruction &I)
Value * hasConstantValue() const
If the specified PHI node always merges together the same value, return the value, otherwise return null.
unsigned getNumOperands() const
Definition: User.h:192
Mode EvalMode
How we want to evaluate this object&#39;s size.
This is the shared class of boolean and integer constants.
Definition: Constants.h:84
ValTy * getArgument(unsigned ArgNo) const
Definition: CallSite.h:186
Evaluate the size and offset of an object pointed to by a Value* statically.
unsigned getParamAlignment() const
If this is a byval or inalloca argument, return its alignment.
Definition: Function.cpp:113
Provides information about what library functions are available for the current target.
SizeOffsetType visitPHINode(PHINode &)
A constant pointer value that points to null.
Definition: Constants.h:535
Type * getReturnType() const
Definition: DerivedTypes.h:124
uint64_t getSizeInBytes() const
Definition: DataLayout.h:529
SizeOffsetType visitUndefValue(UndefValue &)
static Constant * get(Type *Ty, uint64_t V, bool isSigned=false)
If Ty is a vector type, return a Constant with a splat of the given value.
Definition: Constants.cpp:621
unsigned getNumIncomingValues() const
Return the number of incoming edges.
static const Function * getCalledFunction(const Value *V, bool LookThroughBitCast, bool &IsNoBuiltin)
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:133
SizeOffsetType compute(Value *V)
FunctionType * getFunctionType() const
Returns the FunctionType for me.
Definition: Function.h:164
Class for arbitrary precision integers.
Definition: APInt.h:70
SizeOffsetEvalType visitIntToPtrInst(IntToPtrInst &)
Type * getMallocAllocatedType(const CallInst *CI, const TargetLibraryInfo *TLI)
getMallocAllocatedType - Returns the Type allocated by malloc call.
SizeOffsetEvalType visitPHINode(PHINode &PHI)
bool getLibFunc(StringRef funcName, LibFunc &F) const
Searches for a particular function name.
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 ...
const Value * getFalseValue() const
user_iterator_impl< const User > const_user_iterator
Definition: Value.h:370
amdgpu Simplify well known AMD library false Value Value * Arg
Fail to evaluate an unknown condition.
SizeOffsetEvalType compute(Value *V)
uint64_t getTypeAllocSize(Type *Ty) const
Returns the offset in bytes between successive objects of the specified type, including alignment pad...
Definition: DataLayout.h:428
bool ugt(const APInt &RHS) const
Unsigned greather than comparison.
Definition: APInt.h:1249
static bool isZero(Value *V, const DataLayout &DL, DominatorTree *DT, AssumptionCache *AC)
Definition: Lint.cpp:546
ObjectSizeOffsetVisitor(const DataLayout &DL, const TargetLibraryInfo *TLI, LLVMContext &Context, ObjectSizeOpts Options={})
SizeOffsetEvalType visitLoadInst(LoadInst &I)
bool isMallocOrCallocLikeFn(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 similar to malloc or...
StringRef getName() const
Return a constant reference to the value&#39;s name.
Definition: Value.cpp:224
Establish a view to a call site for examination.
Definition: CallSite.h:714
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
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:58
PointerType * getType() const
Specialize the getType() method to always return an PointerType, which reduces the amount of casting ...
Definition: Constants.h:551
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()
Definition: DenseMap.h:109
bool ComputeMultiple(Value *V, unsigned Base, Value *&Multiple, bool LookThroughSExt=false, unsigned Depth=0)
This function computes the integer multiple of Base that equals V.
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Definition: Casting.h:323
This instruction extracts a single (scalar) element from a VectorType value.
uint32_t Size
Definition: Profile.cpp:47
bool anyKnown(SizeOffsetEvalType SizeOffset)
APInt umul_ov(const APInt &RHS, bool &Overflow) const
Definition: APInt.cpp:1917
FunTy * getCalledFunction() const
Return the function being called if this is a direct call, otherwise return null (if it&#39;s an indirect...
Definition: CallSite.h:107
bool isArrayAllocation() const
Return true if there is an allocation size parameter to the allocation instruction that is not 1...
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
user_iterator user_begin()
Definition: Value.h:376
static bool bothKnown(const SizeOffsetType &SizeOffset)
Value * getArgOperand(unsigned i) const
getArgOperand/setArgOperand - Return/set the i-th call argument.
bool hasRetAttr(Attribute::AttrKind Kind) const
Return true if this return value has the given attribute.
Definition: CallSite.h:372
LLVM Value Representation.
Definition: Value.h:73
SizeOffsetEvalType visitExtractElementInst(ExtractElementInst &I)
Attribute getFnAttribute(Attribute::AttrKind Kind) const
Return the attribute for the given attribute kind.
Definition: Function.h:331
AllocType AllocTy
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:49
Various options to control the behavior of getObjectSize.
static APInt getNullValue(unsigned numBits)
Get the &#39;0&#39; value.
Definition: APInt.h:569
bool isUIntN(unsigned N, uint64_t x)
Checks if an unsigned integer fits into the given (dynamic) bit width.
Definition: MathExtras.h:393
#define LLVM_DEBUG(X)
Definition: Debug.h:123
SizeOffsetType visitLoadInst(LoadInst &I)
SizeOffsetEvalType visitAllocaInst(AllocaInst &I)
bool bothKnown(SizeOffsetEvalType SizeOffset)
SizeOffsetType visitConstantPointerNull(ConstantPointerNull &)
SizeOffsetEvalType visitExtractValueInst(ExtractValueInst &I)
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
Type * getElementType() const
Definition: DerivedTypes.h:486
PointerType * getType() const
Global values are always pointers.
Definition: GlobalValue.h:274
A wrapper class for inspecting calls to intrinsic functions.
Definition: IntrinsicInst.h:44
an instruction to allocate memory on the stack
Definition: Instructions.h:60
user_iterator user_end()
Definition: Value.h:384
const Constant * getAliasee() const
Definition: GlobalAlias.h:78