LLVM  7.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"
25 #include "llvm/IR/Argument.h"
26 #include "llvm/IR/Attributes.h"
27 #include "llvm/IR/Constants.h"
28 #include "llvm/IR/DataLayout.h"
29 #include "llvm/IR/DerivedTypes.h"
30 #include "llvm/IR/Function.h"
31 #include "llvm/IR/GlobalAlias.h"
32 #include "llvm/IR/GlobalVariable.h"
33 #include "llvm/IR/Instruction.h"
34 #include "llvm/IR/Instructions.h"
35 #include "llvm/IR/IntrinsicInst.h"
36 #include "llvm/IR/Operator.h"
37 #include "llvm/IR/Type.h"
38 #include "llvm/IR/Value.h"
39 #include "llvm/Support/Casting.h"
40 #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_Znwm, {OpNewLike, 1, 0, -1}}, // new(unsigned long)
79  {LibFunc_ZnwmRKSt9nothrow_t, {MallocLike, 2, 0, -1}}, // new(unsigned long, nothrow)
80  {LibFunc_Znaj, {OpNewLike, 1, 0, -1}}, // new[](unsigned int)
81  {LibFunc_ZnajRKSt9nothrow_t, {MallocLike, 2, 0, -1}}, // new[](unsigned int, nothrow)
82  {LibFunc_Znam, {OpNewLike, 1, 0, -1}}, // new[](unsigned long)
83  {LibFunc_ZnamRKSt9nothrow_t, {MallocLike, 2, 0, -1}}, // new[](unsigned long, nothrow)
84  {LibFunc_msvc_new_int, {OpNewLike, 1, 0, -1}}, // new(unsigned int)
85  {LibFunc_msvc_new_int_nothrow, {MallocLike, 2, 0, -1}}, // new(unsigned int, nothrow)
86  {LibFunc_msvc_new_longlong, {OpNewLike, 1, 0, -1}}, // new(unsigned long long)
87  {LibFunc_msvc_new_longlong_nothrow, {MallocLike, 2, 0, -1}}, // new(unsigned long long, nothrow)
88  {LibFunc_msvc_new_array_int, {OpNewLike, 1, 0, -1}}, // new[](unsigned int)
89  {LibFunc_msvc_new_array_int_nothrow, {MallocLike, 2, 0, -1}}, // new[](unsigned int, nothrow)
90  {LibFunc_msvc_new_array_longlong, {OpNewLike, 1, 0, -1}}, // new[](unsigned long long)
91  {LibFunc_msvc_new_array_longlong_nothrow, {MallocLike, 2, 0, -1}}, // new[](unsigned long long, nothrow)
92  {LibFunc_calloc, {CallocLike, 2, 0, 1}},
93  {LibFunc_realloc, {ReallocLike, 2, 1, -1}},
94  {LibFunc_reallocf, {ReallocLike, 2, 1, -1}},
95  {LibFunc_strdup, {StrDupLike, 1, -1, -1}},
96  {LibFunc_strndup, {StrDupLike, 2, 1, -1}}
97  // TODO: Handle "int posix_memalign(void **, size_t, size_t)"
98 };
99 
100 static const Function *getCalledFunction(const Value *V, bool LookThroughBitCast,
101  bool &IsNoBuiltin) {
102  // Don't care about intrinsics in this case.
103  if (isa<IntrinsicInst>(V))
104  return nullptr;
105 
106  if (LookThroughBitCast)
107  V = V->stripPointerCasts();
108 
109  ImmutableCallSite CS(V);
110  if (!CS.getInstruction())
111  return nullptr;
112 
113  IsNoBuiltin = CS.isNoBuiltin();
114 
115  if (const Function *Callee = CS.getCalledFunction())
116  return Callee;
117  return nullptr;
118 }
119 
120 /// Returns the allocation data for the given value if it's either a call to a
121 /// known allocation function, or a call to a function with the allocsize
122 /// attribute.
125  const TargetLibraryInfo *TLI) {
126  // Make sure that the function is available.
127  StringRef FnName = Callee->getName();
128  LibFunc TLIFn;
129  if (!TLI || !TLI->getLibFunc(FnName, TLIFn) || !TLI->has(TLIFn))
130  return None;
131 
132  const auto *Iter = find_if(
133  AllocationFnData, [TLIFn](const std::pair<LibFunc, AllocFnsTy> &P) {
134  return P.first == TLIFn;
135  });
136 
137  if (Iter == std::end(AllocationFnData))
138  return None;
139 
140  const AllocFnsTy *FnData = &Iter->second;
141  if ((FnData->AllocTy & AllocTy) != FnData->AllocTy)
142  return None;
143 
144  // Check function prototype.
145  int FstParam = FnData->FstParam;
146  int SndParam = FnData->SndParam;
147  FunctionType *FTy = Callee->getFunctionType();
148 
149  if (FTy->getReturnType() == Type::getInt8PtrTy(FTy->getContext()) &&
150  FTy->getNumParams() == FnData->NumParams &&
151  (FstParam < 0 ||
152  (FTy->getParamType(FstParam)->isIntegerTy(32) ||
153  FTy->getParamType(FstParam)->isIntegerTy(64))) &&
154  (SndParam < 0 ||
155  FTy->getParamType(SndParam)->isIntegerTy(32) ||
156  FTy->getParamType(SndParam)->isIntegerTy(64)))
157  return *FnData;
158  return None;
159 }
160 
162  const TargetLibraryInfo *TLI,
163  bool LookThroughBitCast = false) {
164  bool IsNoBuiltinCall;
165  if (const Function *Callee =
166  getCalledFunction(V, LookThroughBitCast, IsNoBuiltinCall))
167  if (!IsNoBuiltinCall)
168  return getAllocationDataForFunction(Callee, AllocTy, TLI);
169  return None;
170 }
171 
173  const TargetLibraryInfo *TLI) {
174  bool IsNoBuiltinCall;
175  const Function *Callee =
176  getCalledFunction(V, /*LookThroughBitCast=*/false, IsNoBuiltinCall);
177  if (!Callee)
178  return None;
179 
180  // Prefer to use existing information over allocsize. This will give us an
181  // accurate AllocTy.
182  if (!IsNoBuiltinCall)
185  return Data;
186 
187  Attribute Attr = Callee->getFnAttribute(Attribute::AllocSize);
188  if (Attr == Attribute())
189  return None;
190 
191  std::pair<unsigned, Optional<unsigned>> Args = Attr.getAllocSizeArgs();
192 
193  AllocFnsTy Result;
194  // Because allocsize only tells us how many bytes are allocated, we're not
195  // really allowed to assume anything, so we use MallocLike.
196  Result.AllocTy = MallocLike;
197  Result.NumParams = Callee->getNumOperands();
198  Result.FstParam = Args.first;
199  Result.SndParam = Args.second.getValueOr(-1);
200  return Result;
201 }
202 
203 static bool hasNoAliasAttr(const Value *V, bool LookThroughBitCast) {
204  ImmutableCallSite CS(LookThroughBitCast ? V->stripPointerCasts() : V);
205  return CS && CS.hasRetAttr(Attribute::NoAlias);
206 }
207 
208 /// \brief Tests if a value is a call or invoke to a library function that
209 /// allocates or reallocates memory (either malloc, calloc, realloc, or strdup
210 /// like).
211 bool llvm::isAllocationFn(const Value *V, const TargetLibraryInfo *TLI,
212  bool LookThroughBitCast) {
213  return getAllocationData(V, AnyAlloc, TLI, LookThroughBitCast).hasValue();
214 }
215 
216 /// \brief Tests if a value is a call or invoke to a function that returns a
217 /// NoAlias pointer (including malloc/calloc/realloc/strdup-like functions).
218 bool llvm::isNoAliasFn(const Value *V, const TargetLibraryInfo *TLI,
219  bool LookThroughBitCast) {
220  // it's safe to consider realloc as noalias since accessing the original
221  // pointer is undefined behavior
222  return isAllocationFn(V, TLI, LookThroughBitCast) ||
223  hasNoAliasAttr(V, LookThroughBitCast);
224 }
225 
226 /// \brief Tests if a value is a call or invoke to a library function that
227 /// allocates uninitialized memory (such as malloc).
228 bool llvm::isMallocLikeFn(const Value *V, const TargetLibraryInfo *TLI,
229  bool LookThroughBitCast) {
230  return getAllocationData(V, MallocLike, TLI, LookThroughBitCast).hasValue();
231 }
232 
233 /// \brief Tests if a value is a call or invoke to a library function that
234 /// allocates zero-filled memory (such as calloc).
235 bool llvm::isCallocLikeFn(const Value *V, const TargetLibraryInfo *TLI,
236  bool LookThroughBitCast) {
237  return getAllocationData(V, CallocLike, TLI, LookThroughBitCast).hasValue();
238 }
239 
240 /// \brief Tests if a value is a call or invoke to a library function that
241 /// allocates memory similiar to malloc or calloc.
243  bool LookThroughBitCast) {
244  return getAllocationData(V, MallocOrCallocLike, TLI,
245  LookThroughBitCast).hasValue();
246 }
247 
248 /// \brief Tests if a value is a call or invoke to a library function that
249 /// allocates memory (either malloc, calloc, or strdup like).
250 bool llvm::isAllocLikeFn(const Value *V, const TargetLibraryInfo *TLI,
251  bool LookThroughBitCast) {
252  return getAllocationData(V, AllocLike, TLI, LookThroughBitCast).hasValue();
253 }
254 
255 /// extractMallocCall - Returns the corresponding CallInst if the instruction
256 /// is a malloc call. Since CallInst::CreateMalloc() only creates calls, we
257 /// ignore InvokeInst here.
259  const TargetLibraryInfo *TLI) {
260  return isMallocLikeFn(I, TLI) ? dyn_cast<CallInst>(I) : nullptr;
261 }
262 
263 static Value *computeArraySize(const CallInst *CI, const DataLayout &DL,
264  const TargetLibraryInfo *TLI,
265  bool LookThroughSExt = false) {
266  if (!CI)
267  return nullptr;
268 
269  // The size of the malloc's result type must be known to determine array size.
270  Type *T = getMallocAllocatedType(CI, TLI);
271  if (!T || !T->isSized())
272  return nullptr;
273 
274  unsigned ElementSize = DL.getTypeAllocSize(T);
275  if (StructType *ST = dyn_cast<StructType>(T))
276  ElementSize = DL.getStructLayout(ST)->getSizeInBytes();
277 
278  // If malloc call's arg can be determined to be a multiple of ElementSize,
279  // return the multiple. Otherwise, return NULL.
280  Value *MallocArg = CI->getArgOperand(0);
281  Value *Multiple = nullptr;
282  if (ComputeMultiple(MallocArg, ElementSize, Multiple, LookThroughSExt))
283  return Multiple;
284 
285  return nullptr;
286 }
287 
288 /// getMallocType - Returns the PointerType resulting from the malloc call.
289 /// The PointerType depends on the number of bitcast uses of the malloc call:
290 /// 0: PointerType is the calls' return type.
291 /// 1: PointerType is the bitcast's result type.
292 /// >1: Unique PointerType cannot be determined, return NULL.
294  const TargetLibraryInfo *TLI) {
295  assert(isMallocLikeFn(CI, TLI) && "getMallocType and not malloc call");
296 
297  PointerType *MallocType = nullptr;
298  unsigned NumOfBitCastUses = 0;
299 
300  // Determine if CallInst has a bitcast use.
301  for (Value::const_user_iterator UI = CI->user_begin(), E = CI->user_end();
302  UI != E;)
303  if (const BitCastInst *BCI = dyn_cast<BitCastInst>(*UI++)) {
304  MallocType = cast<PointerType>(BCI->getDestTy());
305  NumOfBitCastUses++;
306  }
307 
308  // Malloc call has 1 bitcast use, so type is the bitcast's destination type.
309  if (NumOfBitCastUses == 1)
310  return MallocType;
311 
312  // Malloc call was not bitcast, so type is the malloc function's return type.
313  if (NumOfBitCastUses == 0)
314  return cast<PointerType>(CI->getType());
315 
316  // Type could not be determined.
317  return nullptr;
318 }
319 
320 /// getMallocAllocatedType - Returns the Type allocated by malloc call.
321 /// The Type depends on the number of bitcast uses of the malloc call:
322 /// 0: PointerType is the malloc calls' return type.
323 /// 1: PointerType is the bitcast's result type.
324 /// >1: Unique PointerType cannot be determined, return NULL.
326  const TargetLibraryInfo *TLI) {
327  PointerType *PT = getMallocType(CI, TLI);
328  return PT ? PT->getElementType() : nullptr;
329 }
330 
331 /// getMallocArraySize - Returns the array size of a malloc call. If the
332 /// argument passed to malloc is a multiple of the size of the malloced type,
333 /// then return that multiple. For non-array mallocs, the multiple is
334 /// constant 1. Otherwise, return NULL for mallocs whose array size cannot be
335 /// determined.
337  const TargetLibraryInfo *TLI,
338  bool LookThroughSExt) {
339  assert(isMallocLikeFn(CI, TLI) && "getMallocArraySize and not malloc call");
340  return computeArraySize(CI, DL, TLI, LookThroughSExt);
341 }
342 
343 /// extractCallocCall - Returns the corresponding CallInst if the instruction
344 /// is a calloc call.
346  const TargetLibraryInfo *TLI) {
347  return isCallocLikeFn(I, TLI) ? cast<CallInst>(I) : nullptr;
348 }
349 
350 /// isFreeCall - Returns non-null if the value is a call to the builtin free()
351 const CallInst *llvm::isFreeCall(const Value *I, const TargetLibraryInfo *TLI) {
352  bool IsNoBuiltinCall;
353  const Function *Callee =
354  getCalledFunction(I, /*LookThroughBitCast=*/false, IsNoBuiltinCall);
355  if (Callee == nullptr || IsNoBuiltinCall)
356  return nullptr;
357 
358  StringRef FnName = Callee->getName();
359  LibFunc TLIFn;
360  if (!TLI || !TLI->getLibFunc(FnName, TLIFn) || !TLI->has(TLIFn))
361  return nullptr;
362 
363  unsigned ExpectedNumParams;
364  if (TLIFn == LibFunc_free ||
365  TLIFn == LibFunc_ZdlPv || // operator delete(void*)
366  TLIFn == LibFunc_ZdaPv || // operator delete[](void*)
367  TLIFn == LibFunc_msvc_delete_ptr32 || // operator delete(void*)
368  TLIFn == LibFunc_msvc_delete_ptr64 || // operator delete(void*)
369  TLIFn == LibFunc_msvc_delete_array_ptr32 || // operator delete[](void*)
370  TLIFn == LibFunc_msvc_delete_array_ptr64) // operator delete[](void*)
371  ExpectedNumParams = 1;
372  else if (TLIFn == LibFunc_ZdlPvj || // delete(void*, uint)
373  TLIFn == LibFunc_ZdlPvm || // delete(void*, ulong)
374  TLIFn == LibFunc_ZdlPvRKSt9nothrow_t || // delete(void*, nothrow)
375  TLIFn == LibFunc_ZdaPvj || // delete[](void*, uint)
376  TLIFn == LibFunc_ZdaPvm || // delete[](void*, ulong)
377  TLIFn == LibFunc_ZdaPvRKSt9nothrow_t || // delete[](void*, nothrow)
378  TLIFn == LibFunc_msvc_delete_ptr32_int || // delete(void*, uint)
379  TLIFn == LibFunc_msvc_delete_ptr64_longlong || // delete(void*, ulonglong)
380  TLIFn == LibFunc_msvc_delete_ptr32_nothrow || // delete(void*, nothrow)
381  TLIFn == LibFunc_msvc_delete_ptr64_nothrow || // delete(void*, nothrow)
382  TLIFn == LibFunc_msvc_delete_array_ptr32_int || // delete[](void*, uint)
383  TLIFn == LibFunc_msvc_delete_array_ptr64_longlong || // delete[](void*, ulonglong)
384  TLIFn == LibFunc_msvc_delete_array_ptr32_nothrow || // delete[](void*, nothrow)
385  TLIFn == LibFunc_msvc_delete_array_ptr64_nothrow) // delete[](void*, nothrow)
386  ExpectedNumParams = 2;
387  else
388  return nullptr;
389 
390  // Check free prototype.
391  // FIXME: workaround for PR5130, this will be obsolete when a nobuiltin
392  // attribute will exist.
393  FunctionType *FTy = Callee->getFunctionType();
394  if (!FTy->getReturnType()->isVoidTy())
395  return nullptr;
396  if (FTy->getNumParams() != ExpectedNumParams)
397  return nullptr;
398  if (FTy->getParamType(0) != Type::getInt8PtrTy(Callee->getContext()))
399  return nullptr;
400 
401  return dyn_cast<CallInst>(I);
402 }
403 
404 //===----------------------------------------------------------------------===//
405 // Utility functions to compute size of objects.
406 //
408  if (Data.second.isNegative() || Data.first.ult(Data.second))
409  return APInt(Data.first.getBitWidth(), 0);
410  return Data.first - Data.second;
411 }
412 
413 /// \brief Compute the size of the object pointed by Ptr. Returns true and the
414 /// object size in Size if successful, and false otherwise.
415 /// If RoundToAlign is true, then Size is rounded up to the alignment of
416 /// allocas, byval arguments, and global variables.
417 bool llvm::getObjectSize(const Value *Ptr, uint64_t &Size, const DataLayout &DL,
418  const TargetLibraryInfo *TLI, ObjectSizeOpts Opts) {
419  ObjectSizeOffsetVisitor Visitor(DL, TLI, Ptr->getContext(), Opts);
420  SizeOffsetType Data = Visitor.compute(const_cast<Value*>(Ptr));
421  if (!Visitor.bothKnown(Data))
422  return false;
423 
424  Size = getSizeWithOverflow(Data).getZExtValue();
425  return true;
426 }
427 
429  const DataLayout &DL,
430  const TargetLibraryInfo *TLI,
431  bool MustSucceed) {
432  assert(ObjectSize->getIntrinsicID() == Intrinsic::objectsize &&
433  "ObjectSize must be a call to llvm.objectsize!");
434 
435  bool MaxVal = cast<ConstantInt>(ObjectSize->getArgOperand(1))->isZero();
436  ObjectSizeOpts EvalOptions;
437  // Unless we have to fold this to something, try to be as accurate as
438  // possible.
439  if (MustSucceed)
440  EvalOptions.EvalMode =
442  else
444 
445  EvalOptions.NullIsUnknownSize =
446  cast<ConstantInt>(ObjectSize->getArgOperand(2))->isOne();
447 
448  // FIXME: Does it make sense to just return a failure value if the size won't
449  // fit in the output and `!MustSucceed`?
450  uint64_t Size;
451  auto *ResultType = cast<IntegerType>(ObjectSize->getType());
452  if (getObjectSize(ObjectSize->getArgOperand(0), Size, DL, TLI, EvalOptions) &&
453  isUIntN(ResultType->getBitWidth(), Size))
454  return ConstantInt::get(ResultType, Size);
455 
456  if (!MustSucceed)
457  return nullptr;
458 
459  return ConstantInt::get(ResultType, MaxVal ? -1ULL : 0);
460 }
461 
462 STATISTIC(ObjectVisitorArgument,
463  "Number of arguments with unsolved size and offset");
464 STATISTIC(ObjectVisitorLoad,
465  "Number of load instructions with unsolved size and offset");
466 
467 APInt ObjectSizeOffsetVisitor::align(APInt Size, uint64_t Align) {
468  if (Options.RoundToAlign && Align)
469  return APInt(IntTyBits, alignTo(Size.getZExtValue(), Align));
470  return Size;
471 }
472 
474  const TargetLibraryInfo *TLI,
476  ObjectSizeOpts Options)
477  : DL(DL), TLI(TLI), Options(Options) {
478  // Pointer size must be rechecked for each object visited since it could have
479  // a different address space.
480 }
481 
483  IntTyBits = DL.getPointerTypeSizeInBits(V->getType());
484  Zero = APInt::getNullValue(IntTyBits);
485 
486  V = V->stripPointerCasts();
487  if (Instruction *I = dyn_cast<Instruction>(V)) {
488  // If we have already seen this instruction, bail out. Cycles can happen in
489  // unreachable code after constant propagation.
490  if (!SeenInsts.insert(I).second)
491  return unknown();
492 
493  if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
494  return visitGEPOperator(*GEP);
495  return visit(*I);
496  }
497  if (Argument *A = dyn_cast<Argument>(V))
498  return visitArgument(*A);
499  if (ConstantPointerNull *P = dyn_cast<ConstantPointerNull>(V))
500  return visitConstantPointerNull(*P);
501  if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
502  return visitGlobalAlias(*GA);
503  if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
504  return visitGlobalVariable(*GV);
505  if (UndefValue *UV = dyn_cast<UndefValue>(V))
506  return visitUndefValue(*UV);
507  if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
508  if (CE->getOpcode() == Instruction::IntToPtr)
509  return unknown(); // clueless
510  if (CE->getOpcode() == Instruction::GetElementPtr)
511  return visitGEPOperator(cast<GEPOperator>(*CE));
512  }
513 
514  DEBUG(dbgs() << "ObjectSizeOffsetVisitor::compute() unhandled value: " << *V
515  << '\n');
516  return unknown();
517 }
518 
519 /// When we're compiling N-bit code, and the user uses parameters that are
520 /// greater than N bits (e.g. uint64_t on a 32-bit build), we can run into
521 /// trouble with APInt size issues. This function handles resizing + overflow
522 /// checks for us. Check and zext or trunc \p I depending on IntTyBits and
523 /// I's value.
524 bool ObjectSizeOffsetVisitor::CheckedZextOrTrunc(APInt &I) {
525  // More bits than we can handle. Checking the bit width isn't necessary, but
526  // it's faster than checking active bits, and should give `false` in the
527  // vast majority of cases.
528  if (I.getBitWidth() > IntTyBits && I.getActiveBits() > IntTyBits)
529  return false;
530  if (I.getBitWidth() != IntTyBits)
531  I = I.zextOrTrunc(IntTyBits);
532  return true;
533 }
534 
536  if (!I.getAllocatedType()->isSized())
537  return unknown();
538 
539  APInt Size(IntTyBits, DL.getTypeAllocSize(I.getAllocatedType()));
540  if (!I.isArrayAllocation())
541  return std::make_pair(align(Size, I.getAlignment()), Zero);
542 
543  Value *ArraySize = I.getArraySize();
544  if (const ConstantInt *C = dyn_cast<ConstantInt>(ArraySize)) {
545  APInt NumElems = C->getValue();
546  if (!CheckedZextOrTrunc(NumElems))
547  return unknown();
548 
549  bool Overflow;
550  Size = Size.umul_ov(NumElems, Overflow);
551  return Overflow ? unknown() : std::make_pair(align(Size, I.getAlignment()),
552  Zero);
553  }
554  return unknown();
555 }
556 
558  // No interprocedural analysis is done at the moment.
559  if (!A.hasByValOrInAllocaAttr()) {
560  ++ObjectVisitorArgument;
561  return unknown();
562  }
563  PointerType *PT = cast<PointerType>(A.getType());
564  APInt Size(IntTyBits, DL.getTypeAllocSize(PT->getElementType()));
565  return std::make_pair(align(Size, A.getParamAlignment()), Zero);
566 }
567 
570  if (!FnData)
571  return unknown();
572 
573  // Handle strdup-like functions separately.
574  if (FnData->AllocTy == StrDupLike) {
575  APInt Size(IntTyBits, GetStringLength(CS.getArgument(0)));
576  if (!Size)
577  return unknown();
578 
579  // Strndup limits strlen.
580  if (FnData->FstParam > 0) {
581  ConstantInt *Arg =
583  if (!Arg)
584  return unknown();
585 
586  APInt MaxSize = Arg->getValue().zextOrSelf(IntTyBits);
587  if (Size.ugt(MaxSize))
588  Size = MaxSize + 1;
589  }
590  return std::make_pair(Size, Zero);
591  }
592 
594  if (!Arg)
595  return unknown();
596 
597  APInt Size = Arg->getValue();
598  if (!CheckedZextOrTrunc(Size))
599  return unknown();
600 
601  // Size is determined by just 1 parameter.
602  if (FnData->SndParam < 0)
603  return std::make_pair(Size, Zero);
604 
605  Arg = dyn_cast<ConstantInt>(CS.getArgument(FnData->SndParam));
606  if (!Arg)
607  return unknown();
608 
609  APInt NumElems = Arg->getValue();
610  if (!CheckedZextOrTrunc(NumElems))
611  return unknown();
612 
613  bool Overflow;
614  Size = Size.umul_ov(NumElems, Overflow);
615  return Overflow ? unknown() : std::make_pair(Size, Zero);
616 
617  // TODO: handle more standard functions (+ wchar cousins):
618  // - strdup / strndup
619  // - strcpy / strncpy
620  // - strcat / strncat
621  // - memcpy / memmove
622  // - strcat / strncat
623  // - memset
624 }
625 
628  if (Options.NullIsUnknownSize && CPN.getType()->getAddressSpace() == 0)
629  return unknown();
630  return std::make_pair(Zero, Zero);
631 }
632 
635  return unknown();
636 }
637 
640  // Easy cases were already folded by previous passes.
641  return unknown();
642 }
643 
645  SizeOffsetType PtrData = compute(GEP.getPointerOperand());
646  APInt Offset(IntTyBits, 0);
647  if (!bothKnown(PtrData) || !GEP.accumulateConstantOffset(DL, Offset))
648  return unknown();
649 
650  return std::make_pair(PtrData.first, PtrData.second + Offset);
651 }
652 
654  if (GA.isInterposable())
655  return unknown();
656  return compute(GA.getAliasee());
657 }
658 
660  if (!GV.hasDefinitiveInitializer())
661  return unknown();
662 
663  APInt Size(IntTyBits, DL.getTypeAllocSize(GV.getType()->getElementType()));
664  return std::make_pair(align(Size, GV.getAlignment()), Zero);
665 }
666 
668  // clueless
669  return unknown();
670 }
671 
673  ++ObjectVisitorLoad;
674  return unknown();
675 }
676 
678  // too complex to analyze statically.
679  return unknown();
680 }
681 
683  SizeOffsetType TrueSide = compute(I.getTrueValue());
684  SizeOffsetType FalseSide = compute(I.getFalseValue());
685  if (bothKnown(TrueSide) && bothKnown(FalseSide)) {
686  if (TrueSide == FalseSide) {
687  return TrueSide;
688  }
689 
690  APInt TrueResult = getSizeWithOverflow(TrueSide);
691  APInt FalseResult = getSizeWithOverflow(FalseSide);
692 
693  if (TrueResult == FalseResult) {
694  return TrueSide;
695  }
696  if (Options.EvalMode == ObjectSizeOpts::Mode::Min) {
697  if (TrueResult.slt(FalseResult))
698  return TrueSide;
699  return FalseSide;
700  }
701  if (Options.EvalMode == ObjectSizeOpts::Mode::Max) {
702  if (TrueResult.sgt(FalseResult))
703  return TrueSide;
704  return FalseSide;
705  }
706  }
707  return unknown();
708 }
709 
711  return std::make_pair(Zero, Zero);
712 }
713 
715  DEBUG(dbgs() << "ObjectSizeOffsetVisitor unknown instruction:" << I << '\n');
716  return unknown();
717 }
718 
720  const DataLayout &DL, const TargetLibraryInfo *TLI, LLVMContext &Context,
721  bool RoundToAlign)
722  : DL(DL), TLI(TLI), Context(Context), Builder(Context, TargetFolder(DL)),
723  RoundToAlign(RoundToAlign) {
724  // IntTy and Zero must be set for each compute() since the address space may
725  // be different for later objects.
726 }
727 
729  // XXX - Are vectors of pointers possible here?
730  IntTy = cast<IntegerType>(DL.getIntPtrType(V->getType()));
731  Zero = ConstantInt::get(IntTy, 0);
732 
733  SizeOffsetEvalType Result = compute_(V);
734 
735  if (!bothKnown(Result)) {
736  // Erase everything that was computed in this iteration from the cache, so
737  // that no dangling references are left behind. We could be a bit smarter if
738  // we kept a dependency graph. It's probably not worth the complexity.
739  for (const Value *SeenVal : SeenVals) {
740  CacheMapTy::iterator CacheIt = CacheMap.find(SeenVal);
741  // non-computable results can be safely cached
742  if (CacheIt != CacheMap.end() && anyKnown(CacheIt->second))
743  CacheMap.erase(CacheIt);
744  }
745  }
746 
747  SeenVals.clear();
748  return Result;
749 }
750 
751 SizeOffsetEvalType ObjectSizeOffsetEvaluator::compute_(Value *V) {
752  ObjectSizeOpts ObjSizeOptions;
753  ObjSizeOptions.RoundToAlign = RoundToAlign;
754 
755  ObjectSizeOffsetVisitor Visitor(DL, TLI, Context, ObjSizeOptions);
756  SizeOffsetType Const = Visitor.compute(V);
757  if (Visitor.bothKnown(Const))
758  return std::make_pair(ConstantInt::get(Context, Const.first),
759  ConstantInt::get(Context, Const.second));
760 
761  V = V->stripPointerCasts();
762 
763  // Check cache.
764  CacheMapTy::iterator CacheIt = CacheMap.find(V);
765  if (CacheIt != CacheMap.end())
766  return CacheIt->second;
767 
768  // Always generate code immediately before the instruction being
769  // processed, so that the generated code dominates the same BBs.
770  BuilderTy::InsertPointGuard Guard(Builder);
771  if (Instruction *I = dyn_cast<Instruction>(V))
772  Builder.SetInsertPoint(I);
773 
774  // Now compute the size and offset.
775  SizeOffsetEvalType Result;
776 
777  // Record the pointers that were handled in this run, so that they can be
778  // cleaned later if something fails. We also use this set to break cycles that
779  // can occur in dead code.
780  if (!SeenVals.insert(V).second) {
781  Result = unknown();
782  } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
783  Result = visitGEPOperator(*GEP);
784  } else if (Instruction *I = dyn_cast<Instruction>(V)) {
785  Result = visit(*I);
786  } else if (isa<Argument>(V) ||
787  (isa<ConstantExpr>(V) &&
788  cast<ConstantExpr>(V)->getOpcode() == Instruction::IntToPtr) ||
789  isa<GlobalAlias>(V) ||
790  isa<GlobalVariable>(V)) {
791  // Ignore values where we cannot do more than ObjectSizeVisitor.
792  Result = unknown();
793  } else {
794  DEBUG(dbgs() << "ObjectSizeOffsetEvaluator::compute() unhandled value: "
795  << *V << '\n');
796  Result = unknown();
797  }
798 
799  // Don't reuse CacheIt since it may be invalid at this point.
800  CacheMap[V] = Result;
801  return Result;
802 }
803 
805  if (!I.getAllocatedType()->isSized())
806  return unknown();
807 
808  // must be a VLA
810  Value *ArraySize = I.getArraySize();
811  Value *Size = ConstantInt::get(ArraySize->getType(),
813  Size = Builder.CreateMul(Size, ArraySize);
814  return std::make_pair(Size, Zero);
815 }
816 
819  if (!FnData)
820  return unknown();
821 
822  // Handle strdup-like functions separately.
823  if (FnData->AllocTy == StrDupLike) {
824  // TODO
825  return unknown();
826  }
827 
828  Value *FirstArg = CS.getArgument(FnData->FstParam);
829  FirstArg = Builder.CreateZExt(FirstArg, IntTy);
830  if (FnData->SndParam < 0)
831  return std::make_pair(FirstArg, Zero);
832 
833  Value *SecondArg = CS.getArgument(FnData->SndParam);
834  SecondArg = Builder.CreateZExt(SecondArg, IntTy);
835  Value *Size = Builder.CreateMul(FirstArg, SecondArg);
836  return std::make_pair(Size, Zero);
837 
838  // TODO: handle more standard functions (+ wchar cousins):
839  // - strdup / strndup
840  // - strcpy / strncpy
841  // - strcat / strncat
842  // - memcpy / memmove
843  // - strcat / strncat
844  // - memset
845 }
846 
849  return unknown();
850 }
851 
854  return unknown();
855 }
856 
859  SizeOffsetEvalType PtrData = compute_(GEP.getPointerOperand());
860  if (!bothKnown(PtrData))
861  return unknown();
862 
863  Value *Offset = EmitGEPOffset(&Builder, DL, &GEP, /*NoAssumptions=*/true);
864  Offset = Builder.CreateAdd(PtrData.second, Offset);
865  return std::make_pair(PtrData.first, Offset);
866 }
867 
869  // clueless
870  return unknown();
871 }
872 
874  return unknown();
875 }
876 
878  // Create 2 PHIs: one for size and another for offset.
879  PHINode *SizePHI = Builder.CreatePHI(IntTy, PHI.getNumIncomingValues());
880  PHINode *OffsetPHI = Builder.CreatePHI(IntTy, PHI.getNumIncomingValues());
881 
882  // Insert right away in the cache to handle recursive PHIs.
883  CacheMap[&PHI] = std::make_pair(SizePHI, OffsetPHI);
884 
885  // Compute offset/size for each PHI incoming pointer.
886  for (unsigned i = 0, e = PHI.getNumIncomingValues(); i != e; ++i) {
888  SizeOffsetEvalType EdgeData = compute_(PHI.getIncomingValue(i));
889 
890  if (!bothKnown(EdgeData)) {
891  OffsetPHI->replaceAllUsesWith(UndefValue::get(IntTy));
892  OffsetPHI->eraseFromParent();
893  SizePHI->replaceAllUsesWith(UndefValue::get(IntTy));
894  SizePHI->eraseFromParent();
895  return unknown();
896  }
897  SizePHI->addIncoming(EdgeData.first, PHI.getIncomingBlock(i));
898  OffsetPHI->addIncoming(EdgeData.second, PHI.getIncomingBlock(i));
899  }
900 
901  Value *Size = SizePHI, *Offset = OffsetPHI, *Tmp;
902  if ((Tmp = SizePHI->hasConstantValue())) {
903  Size = Tmp;
904  SizePHI->replaceAllUsesWith(Size);
905  SizePHI->eraseFromParent();
906  }
907  if ((Tmp = OffsetPHI->hasConstantValue())) {
908  Offset = Tmp;
909  OffsetPHI->replaceAllUsesWith(Offset);
910  OffsetPHI->eraseFromParent();
911  }
912  return std::make_pair(Size, Offset);
913 }
914 
916  SizeOffsetEvalType TrueSide = compute_(I.getTrueValue());
917  SizeOffsetEvalType FalseSide = compute_(I.getFalseValue());
918 
919  if (!bothKnown(TrueSide) || !bothKnown(FalseSide))
920  return unknown();
921  if (TrueSide == FalseSide)
922  return TrueSide;
923 
924  Value *Size = Builder.CreateSelect(I.getCondition(), TrueSide.first,
925  FalseSide.first);
926  Value *Offset = Builder.CreateSelect(I.getCondition(), TrueSide.second,
927  FalseSide.second);
928  return std::make_pair(Size, Offset);
929 }
930 
932  DEBUG(dbgs() << "ObjectSizeOffsetEvaluator unknown instruction:" << I <<'\n');
933  return unknown();
934 }
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:259
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:67
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:245
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:1542
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:262
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
Attribute
Attributes.
Definition: Dwarf.h:107
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:1183
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
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:738
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:419
bool sgt(const APInt &RHS) const
Signed greather than comparison.
Definition: APInt.h:1253
AllocType
STATISTIC(NumFunctions, "Total number of functions")
The two locations do not alias at all.
Definition: AliasAnalysis.h:85
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:677
An instruction for reading from memory.
Definition: Instructions.h:164
APInt zextOrTrunc(unsigned width) const
Zero extend or truncate to width.
Definition: APInt.cpp:884
SizeOffsetType visitArgument(Argument &A)
Hexagon Common GEP
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition: APInt.h:1488
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:109
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:640
&#39;undef&#39; values are things that do not have specified contents.
Definition: Constants.h:1252
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:900
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:932
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:1512
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:867
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:1426
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:128
Class to represent pointers.
Definition: DerivedTypes.h:467
iterator find(const_arg_type_t< KeyT > Val)
Definition: DenseMap.h:146
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:744
#define P(N)
bool erase(const KeyT &Val)
Definition: DenseMap.h:268
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:200
ConstantInt * lowerObjectSizeCall(IntrinsicInst *ObjectSize, const DataLayout &DL, const TargetLibraryInfo *TLI, bool MustSucceed)
Try to turn a call to .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:1732
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:449
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:842
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:1369
const Value * stripPointerCasts() const
Strip off pointer casts, all-zero GEPs, and aliases.
Definition: Value.cpp:567
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:976
Type * getAllocatedType() const
Return the type that is being allocated by the instruction.
Definition: Instructions.h:102
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:1697
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:176
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:523
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:598
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:132
SizeOffsetType compute(Value *V)
FunctionType * getFunctionType() const
Returns the FunctionType for me.
Definition: Function.h:145
Class for arbitrary precision integers.
Definition: APInt.h:69
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:375
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:422
bool ugt(const APInt &RHS) const
Unsigned greather than comparison.
Definition: APInt.h:1234
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...
Value * getArgOperand(unsigned i) const
getArgOperand/setArgOperand - Return/set the i-th call argument.
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:713
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:79
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.
bool anyKnown(SizeOffsetEvalType SizeOffset)
APInt umul_ov(const APInt &RHS, bool &Overflow) const
Definition: APInt.cpp:1926
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:381
static bool bothKnown(const SizeOffsetType &SizeOffset)
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)
constexpr char Size[]
Key for Kernel::Arg::Metadata::mSize.
Attribute getFnAttribute(Attribute::AttrKind Kind) const
Return the attribute for the given attribute kind.
Definition: Function.h:312
AllocType AllocTy
#define DEBUG(X)
Definition: Debug.h:118
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:562
bool isUIntN(unsigned N, uint64_t x)
Checks if an unsigned integer fits into the given (dynamic) bit width.
Definition: MathExtras.h:385
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:273
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:389
const Constant * getAliasee() const
Definition: GlobalAlias.h:78