LLVM  10.0.0svn
MemoryBuiltins.cpp
Go to the documentation of this file.
1 //===- MemoryBuiltins.cpp - Identify calls to memory builtins -------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This family of functions identifies calls to builtin functions that allocate
10 // or free memory.
11 //
12 //===----------------------------------------------------------------------===//
13 
15 #include "llvm/ADT/APInt.h"
16 #include "llvm/ADT/None.h"
17 #include "llvm/ADT/Optional.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/ADT/Statistic.h"
20 #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"
43 #include <cassert>
44 #include <cstdint>
45 #include <iterator>
46 #include <utility>
47 
48 using namespace llvm;
49 
50 #define DEBUG_TYPE "memory-builtins"
51 
52 enum AllocType : uint8_t {
53  OpNewLike = 1<<0, // allocates; never returns null
54  MallocLike = 1<<1 | OpNewLike, // allocates; may return null
55  CallocLike = 1<<2, // allocates + bzero
56  ReallocLike = 1<<3, // reallocates
57  StrDupLike = 1<<4,
61 };
62 
63 struct AllocFnsTy {
65  unsigned NumParams;
66  // First and Second size parameters (or -1 if unused)
67  int FstParam, SndParam;
68 };
69 
70 // FIXME: certain users need more information. E.g., SimplifyLibCalls needs to
71 // know which functions are nounwind, noalias, nocapture parameters, etc.
72 static const std::pair<LibFunc, AllocFnsTy> AllocationFnData[] = {
73  {LibFunc_malloc, {MallocLike, 1, 0, -1}},
74  {LibFunc_valloc, {MallocLike, 1, 0, -1}},
75  {LibFunc_Znwj, {OpNewLike, 1, 0, -1}}, // new(unsigned int)
76  {LibFunc_ZnwjRKSt9nothrow_t, {MallocLike, 2, 0, -1}}, // new(unsigned int, nothrow)
77  {LibFunc_ZnwjSt11align_val_t, {OpNewLike, 2, 0, -1}}, // new(unsigned int, align_val_t)
78  {LibFunc_ZnwjSt11align_val_tRKSt9nothrow_t, // new(unsigned int, align_val_t, nothrow)
79  {MallocLike, 3, 0, -1}},
80  {LibFunc_Znwm, {OpNewLike, 1, 0, -1}}, // new(unsigned long)
81  {LibFunc_ZnwmRKSt9nothrow_t, {MallocLike, 2, 0, -1}}, // new(unsigned long, nothrow)
82  {LibFunc_ZnwmSt11align_val_t, {OpNewLike, 2, 0, -1}}, // new(unsigned long, align_val_t)
83  {LibFunc_ZnwmSt11align_val_tRKSt9nothrow_t, // new(unsigned long, align_val_t, nothrow)
84  {MallocLike, 3, 0, -1}},
85  {LibFunc_Znaj, {OpNewLike, 1, 0, -1}}, // new[](unsigned int)
86  {LibFunc_ZnajRKSt9nothrow_t, {MallocLike, 2, 0, -1}}, // new[](unsigned int, nothrow)
87  {LibFunc_ZnajSt11align_val_t, {OpNewLike, 2, 0, -1}}, // new[](unsigned int, align_val_t)
88  {LibFunc_ZnajSt11align_val_tRKSt9nothrow_t, // new[](unsigned int, align_val_t, nothrow)
89  {MallocLike, 3, 0, -1}},
90  {LibFunc_Znam, {OpNewLike, 1, 0, -1}}, // new[](unsigned long)
91  {LibFunc_ZnamRKSt9nothrow_t, {MallocLike, 2, 0, -1}}, // new[](unsigned long, nothrow)
92  {LibFunc_ZnamSt11align_val_t, {OpNewLike, 2, 0, -1}}, // new[](unsigned long, align_val_t)
93  {LibFunc_ZnamSt11align_val_tRKSt9nothrow_t, // new[](unsigned long, align_val_t, nothrow)
94  {MallocLike, 3, 0, -1}},
95  {LibFunc_msvc_new_int, {OpNewLike, 1, 0, -1}}, // new(unsigned int)
96  {LibFunc_msvc_new_int_nothrow, {MallocLike, 2, 0, -1}}, // new(unsigned int, nothrow)
97  {LibFunc_msvc_new_longlong, {OpNewLike, 1, 0, -1}}, // new(unsigned long long)
98  {LibFunc_msvc_new_longlong_nothrow, {MallocLike, 2, 0, -1}}, // new(unsigned long long, nothrow)
99  {LibFunc_msvc_new_array_int, {OpNewLike, 1, 0, -1}}, // new[](unsigned int)
100  {LibFunc_msvc_new_array_int_nothrow, {MallocLike, 2, 0, -1}}, // new[](unsigned int, nothrow)
101  {LibFunc_msvc_new_array_longlong, {OpNewLike, 1, 0, -1}}, // new[](unsigned long long)
102  {LibFunc_msvc_new_array_longlong_nothrow, {MallocLike, 2, 0, -1}}, // new[](unsigned long long, nothrow)
103  {LibFunc_calloc, {CallocLike, 2, 0, 1}},
104  {LibFunc_realloc, {ReallocLike, 2, 1, -1}},
105  {LibFunc_reallocf, {ReallocLike, 2, 1, -1}},
106  {LibFunc_strdup, {StrDupLike, 1, -1, -1}},
107  {LibFunc_strndup, {StrDupLike, 2, 1, -1}}
108  // TODO: Handle "int posix_memalign(void **, size_t, size_t)"
109 };
110 
111 static const Function *getCalledFunction(const Value *V, bool LookThroughBitCast,
112  bool &IsNoBuiltin) {
113  // Don't care about intrinsics in this case.
114  if (isa<IntrinsicInst>(V))
115  return nullptr;
116 
117  if (LookThroughBitCast)
118  V = V->stripPointerCasts();
119 
120  ImmutableCallSite CS(V);
121  if (!CS.getInstruction())
122  return nullptr;
123 
124  IsNoBuiltin = CS.isNoBuiltin();
125 
126  if (const Function *Callee = CS.getCalledFunction())
127  return Callee;
128  return nullptr;
129 }
130 
131 /// Returns the allocation data for the given value if it's either a call to a
132 /// known allocation function, or a call to a function with the allocsize
133 /// attribute.
136  const TargetLibraryInfo *TLI) {
137  // Make sure that the function is available.
138  StringRef FnName = Callee->getName();
139  LibFunc TLIFn;
140  if (!TLI || !TLI->getLibFunc(FnName, TLIFn) || !TLI->has(TLIFn))
141  return None;
142 
143  const auto *Iter = find_if(
144  AllocationFnData, [TLIFn](const std::pair<LibFunc, AllocFnsTy> &P) {
145  return P.first == TLIFn;
146  });
147 
148  if (Iter == std::end(AllocationFnData))
149  return None;
150 
151  const AllocFnsTy *FnData = &Iter->second;
152  if ((FnData->AllocTy & AllocTy) != FnData->AllocTy)
153  return None;
154 
155  // Check function prototype.
156  int FstParam = FnData->FstParam;
157  int SndParam = FnData->SndParam;
158  FunctionType *FTy = Callee->getFunctionType();
159 
160  if (FTy->getReturnType() == Type::getInt8PtrTy(FTy->getContext()) &&
161  FTy->getNumParams() == FnData->NumParams &&
162  (FstParam < 0 ||
163  (FTy->getParamType(FstParam)->isIntegerTy(32) ||
164  FTy->getParamType(FstParam)->isIntegerTy(64))) &&
165  (SndParam < 0 ||
166  FTy->getParamType(SndParam)->isIntegerTy(32) ||
167  FTy->getParamType(SndParam)->isIntegerTy(64)))
168  return *FnData;
169  return None;
170 }
171 
173  const TargetLibraryInfo *TLI,
174  bool LookThroughBitCast = false) {
175  bool IsNoBuiltinCall;
176  if (const Function *Callee =
177  getCalledFunction(V, LookThroughBitCast, IsNoBuiltinCall))
178  if (!IsNoBuiltinCall)
179  return getAllocationDataForFunction(Callee, AllocTy, TLI);
180  return None;
181 }
182 
185  function_ref<const TargetLibraryInfo &(Function &)> GetTLI,
186  bool LookThroughBitCast = false) {
187  bool IsNoBuiltinCall;
188  if (const Function *Callee =
189  getCalledFunction(V, LookThroughBitCast, IsNoBuiltinCall))
190  if (!IsNoBuiltinCall)
192  Callee, AllocTy, &GetTLI(const_cast<Function &>(*Callee)));
193  return None;
194 }
195 
197  const TargetLibraryInfo *TLI) {
198  bool IsNoBuiltinCall;
199  const Function *Callee =
200  getCalledFunction(V, /*LookThroughBitCast=*/false, IsNoBuiltinCall);
201  if (!Callee)
202  return None;
203 
204  // Prefer to use existing information over allocsize. This will give us an
205  // accurate AllocTy.
206  if (!IsNoBuiltinCall)
209  return Data;
210 
211  Attribute Attr = Callee->getFnAttribute(Attribute::AllocSize);
212  if (Attr == Attribute())
213  return None;
214 
215  std::pair<unsigned, Optional<unsigned>> Args = Attr.getAllocSizeArgs();
216 
217  AllocFnsTy Result;
218  // Because allocsize only tells us how many bytes are allocated, we're not
219  // really allowed to assume anything, so we use MallocLike.
220  Result.AllocTy = MallocLike;
221  Result.NumParams = Callee->getNumOperands();
222  Result.FstParam = Args.first;
223  Result.SndParam = Args.second.getValueOr(-1);
224  return Result;
225 }
226 
227 static bool hasNoAliasAttr(const Value *V, bool LookThroughBitCast) {
228  ImmutableCallSite CS(LookThroughBitCast ? V->stripPointerCasts() : V);
229  return CS && CS.hasRetAttr(Attribute::NoAlias);
230 }
231 
232 /// Tests if a value is a call or invoke to a library function that
233 /// allocates or reallocates memory (either malloc, calloc, realloc, or strdup
234 /// like).
235 bool llvm::isAllocationFn(const Value *V, const TargetLibraryInfo *TLI,
236  bool LookThroughBitCast) {
237  return getAllocationData(V, AnyAlloc, TLI, LookThroughBitCast).hasValue();
238 }
240  const Value *V, function_ref<const TargetLibraryInfo &(Function &)> GetTLI,
241  bool LookThroughBitCast) {
242  return getAllocationData(V, AnyAlloc, GetTLI, LookThroughBitCast).hasValue();
243 }
244 
245 /// Tests if a value is a call or invoke to a function that returns a
246 /// NoAlias pointer (including malloc/calloc/realloc/strdup-like functions).
247 bool llvm::isNoAliasFn(const Value *V, const TargetLibraryInfo *TLI,
248  bool LookThroughBitCast) {
249  // it's safe to consider realloc as noalias since accessing the original
250  // pointer is undefined behavior
251  return isAllocationFn(V, TLI, LookThroughBitCast) ||
252  hasNoAliasAttr(V, LookThroughBitCast);
253 }
254 
255 /// Tests if a value is a call or invoke to a library function that
256 /// allocates uninitialized memory (such as malloc).
257 bool llvm::isMallocLikeFn(const Value *V, const TargetLibraryInfo *TLI,
258  bool LookThroughBitCast) {
259  return getAllocationData(V, MallocLike, TLI, LookThroughBitCast).hasValue();
260 }
262  const Value *V, function_ref<const TargetLibraryInfo &(Function &)> GetTLI,
263  bool LookThroughBitCast) {
264  return getAllocationData(V, MallocLike, GetTLI, LookThroughBitCast)
265  .hasValue();
266 }
267 
268 /// Tests if a value is a call or invoke to a library function that
269 /// allocates zero-filled memory (such as calloc).
270 bool llvm::isCallocLikeFn(const Value *V, const TargetLibraryInfo *TLI,
271  bool LookThroughBitCast) {
272  return getAllocationData(V, CallocLike, TLI, LookThroughBitCast).hasValue();
273 }
274 
275 /// Tests if a value is a call or invoke to a library function that
276 /// allocates memory similar to malloc or calloc.
278  bool LookThroughBitCast) {
279  return getAllocationData(V, MallocOrCallocLike, TLI,
280  LookThroughBitCast).hasValue();
281 }
282 
283 /// Tests if a value is a call or invoke to a library function that
284 /// allocates memory (either malloc, calloc, or strdup like).
285 bool llvm::isAllocLikeFn(const Value *V, const TargetLibraryInfo *TLI,
286  bool LookThroughBitCast) {
287  return getAllocationData(V, AllocLike, TLI, LookThroughBitCast).hasValue();
288 }
289 
290 /// Tests if a value is a call or invoke to a library function that
291 /// reallocates memory (e.g., realloc).
293  bool LookThroughBitCast) {
294  return getAllocationData(V, ReallocLike, TLI, LookThroughBitCast).hasValue();
295 }
296 
297 /// Tests if a functions is a call or invoke to a library function that
298 /// reallocates memory (e.g., realloc).
300  return getAllocationDataForFunction(F, ReallocLike, TLI).hasValue();
301 }
302 
303 /// Tests if a value is a call or invoke to a library function that
304 /// allocates memory and throws if an allocation failed (e.g., new).
305 bool llvm::isOpNewLikeFn(const Value *V, const TargetLibraryInfo *TLI,
306  bool LookThroughBitCast) {
307  return getAllocationData(V, OpNewLike, TLI, LookThroughBitCast).hasValue();
308 }
309 
310 /// Tests if a value is a call or invoke to a library function that
311 /// allocates memory (strdup, strndup).
312 bool llvm::isStrdupLikeFn(const Value *V, const TargetLibraryInfo *TLI,
313  bool LookThroughBitCast) {
314  return getAllocationData(V, StrDupLike, TLI, LookThroughBitCast).hasValue();
315 }
316 
317 /// extractMallocCall - Returns the corresponding CallInst if the instruction
318 /// is a malloc call. Since CallInst::CreateMalloc() only creates calls, we
319 /// ignore InvokeInst here.
321  const Value *I,
322  function_ref<const TargetLibraryInfo &(Function &)> GetTLI) {
323  return isMallocLikeFn(I, GetTLI) ? dyn_cast<CallInst>(I) : nullptr;
324 }
325 
326 static Value *computeArraySize(const CallInst *CI, const DataLayout &DL,
327  const TargetLibraryInfo *TLI,
328  bool LookThroughSExt = false) {
329  if (!CI)
330  return nullptr;
331 
332  // The size of the malloc's result type must be known to determine array size.
333  Type *T = getMallocAllocatedType(CI, TLI);
334  if (!T || !T->isSized())
335  return nullptr;
336 
337  unsigned ElementSize = DL.getTypeAllocSize(T);
338  if (StructType *ST = dyn_cast<StructType>(T))
339  ElementSize = DL.getStructLayout(ST)->getSizeInBytes();
340 
341  // If malloc call's arg can be determined to be a multiple of ElementSize,
342  // return the multiple. Otherwise, return NULL.
343  Value *MallocArg = CI->getArgOperand(0);
344  Value *Multiple = nullptr;
345  if (ComputeMultiple(MallocArg, ElementSize, Multiple, LookThroughSExt))
346  return Multiple;
347 
348  return nullptr;
349 }
350 
351 /// getMallocType - Returns the PointerType resulting from the malloc call.
352 /// The PointerType depends on the number of bitcast uses of the malloc call:
353 /// 0: PointerType is the calls' return type.
354 /// 1: PointerType is the bitcast's result type.
355 /// >1: Unique PointerType cannot be determined, return NULL.
357  const TargetLibraryInfo *TLI) {
358  assert(isMallocLikeFn(CI, TLI) && "getMallocType and not malloc call");
359 
360  PointerType *MallocType = nullptr;
361  unsigned NumOfBitCastUses = 0;
362 
363  // Determine if CallInst has a bitcast use.
364  for (Value::const_user_iterator UI = CI->user_begin(), E = CI->user_end();
365  UI != E;)
366  if (const BitCastInst *BCI = dyn_cast<BitCastInst>(*UI++)) {
367  MallocType = cast<PointerType>(BCI->getDestTy());
368  NumOfBitCastUses++;
369  }
370 
371  // Malloc call has 1 bitcast use, so type is the bitcast's destination type.
372  if (NumOfBitCastUses == 1)
373  return MallocType;
374 
375  // Malloc call was not bitcast, so type is the malloc function's return type.
376  if (NumOfBitCastUses == 0)
377  return cast<PointerType>(CI->getType());
378 
379  // Type could not be determined.
380  return nullptr;
381 }
382 
383 /// getMallocAllocatedType - Returns the Type allocated by malloc call.
384 /// The Type depends on the number of bitcast uses of the malloc call:
385 /// 0: PointerType is the malloc calls' return type.
386 /// 1: PointerType is the bitcast's result type.
387 /// >1: Unique PointerType cannot be determined, return NULL.
389  const TargetLibraryInfo *TLI) {
390  PointerType *PT = getMallocType(CI, TLI);
391  return PT ? PT->getElementType() : nullptr;
392 }
393 
394 /// getMallocArraySize - Returns the array size of a malloc call. If the
395 /// argument passed to malloc is a multiple of the size of the malloced type,
396 /// then return that multiple. For non-array mallocs, the multiple is
397 /// constant 1. Otherwise, return NULL for mallocs whose array size cannot be
398 /// determined.
400  const TargetLibraryInfo *TLI,
401  bool LookThroughSExt) {
402  assert(isMallocLikeFn(CI, TLI) && "getMallocArraySize and not malloc call");
403  return computeArraySize(CI, DL, TLI, LookThroughSExt);
404 }
405 
406 /// extractCallocCall - Returns the corresponding CallInst if the instruction
407 /// is a calloc call.
409  const TargetLibraryInfo *TLI) {
410  return isCallocLikeFn(I, TLI) ? cast<CallInst>(I) : nullptr;
411 }
412 
413 /// isLibFreeFunction - Returns true if the function is a builtin free()
414 bool llvm::isLibFreeFunction(const Function *F, const LibFunc TLIFn) {
415  unsigned ExpectedNumParams;
416  if (TLIFn == LibFunc_free ||
417  TLIFn == LibFunc_ZdlPv || // operator delete(void*)
418  TLIFn == LibFunc_ZdaPv || // operator delete[](void*)
419  TLIFn == LibFunc_msvc_delete_ptr32 || // operator delete(void*)
420  TLIFn == LibFunc_msvc_delete_ptr64 || // operator delete(void*)
421  TLIFn == LibFunc_msvc_delete_array_ptr32 || // operator delete[](void*)
422  TLIFn == LibFunc_msvc_delete_array_ptr64) // operator delete[](void*)
423  ExpectedNumParams = 1;
424  else if (TLIFn == LibFunc_ZdlPvj || // delete(void*, uint)
425  TLIFn == LibFunc_ZdlPvm || // delete(void*, ulong)
426  TLIFn == LibFunc_ZdlPvRKSt9nothrow_t || // delete(void*, nothrow)
427  TLIFn == LibFunc_ZdlPvSt11align_val_t || // delete(void*, align_val_t)
428  TLIFn == LibFunc_ZdaPvj || // delete[](void*, uint)
429  TLIFn == LibFunc_ZdaPvm || // delete[](void*, ulong)
430  TLIFn == LibFunc_ZdaPvRKSt9nothrow_t || // delete[](void*, nothrow)
431  TLIFn == LibFunc_ZdaPvSt11align_val_t || // delete[](void*, align_val_t)
432  TLIFn == LibFunc_msvc_delete_ptr32_int || // delete(void*, uint)
433  TLIFn == LibFunc_msvc_delete_ptr64_longlong || // delete(void*, ulonglong)
434  TLIFn == LibFunc_msvc_delete_ptr32_nothrow || // delete(void*, nothrow)
435  TLIFn == LibFunc_msvc_delete_ptr64_nothrow || // delete(void*, nothrow)
436  TLIFn == LibFunc_msvc_delete_array_ptr32_int || // delete[](void*, uint)
437  TLIFn == LibFunc_msvc_delete_array_ptr64_longlong || // delete[](void*, ulonglong)
438  TLIFn == LibFunc_msvc_delete_array_ptr32_nothrow || // delete[](void*, nothrow)
439  TLIFn == LibFunc_msvc_delete_array_ptr64_nothrow) // delete[](void*, nothrow)
440  ExpectedNumParams = 2;
441  else if (TLIFn == LibFunc_ZdaPvSt11align_val_tRKSt9nothrow_t || // delete(void*, align_val_t, nothrow)
442  TLIFn == LibFunc_ZdlPvSt11align_val_tRKSt9nothrow_t) // delete[](void*, align_val_t, nothrow)
443  ExpectedNumParams = 3;
444  else
445  return false;
446 
447  // Check free prototype.
448  // FIXME: workaround for PR5130, this will be obsolete when a nobuiltin
449  // attribute will exist.
450  FunctionType *FTy = F->getFunctionType();
451  if (!FTy->getReturnType()->isVoidTy())
452  return false;
453  if (FTy->getNumParams() != ExpectedNumParams)
454  return false;
455  if (FTy->getParamType(0) != Type::getInt8PtrTy(F->getContext()))
456  return false;
457 
458  return true;
459 }
460 
461 /// isFreeCall - Returns non-null if the value is a call to the builtin free()
462 const CallInst *llvm::isFreeCall(const Value *I, const TargetLibraryInfo *TLI) {
463  bool IsNoBuiltinCall;
464  const Function *Callee =
465  getCalledFunction(I, /*LookThroughBitCast=*/false, IsNoBuiltinCall);
466  if (Callee == nullptr || IsNoBuiltinCall)
467  return nullptr;
468 
469  StringRef FnName = Callee->getName();
470  LibFunc TLIFn;
471  if (!TLI || !TLI->getLibFunc(FnName, TLIFn) || !TLI->has(TLIFn))
472  return nullptr;
473 
474  return isLibFreeFunction(Callee, TLIFn) ? dyn_cast<CallInst>(I) : nullptr;
475 }
476 
477 
478 //===----------------------------------------------------------------------===//
479 // Utility functions to compute size of objects.
480 //
482  if (Data.second.isNegative() || Data.first.ult(Data.second))
483  return APInt(Data.first.getBitWidth(), 0);
484  return Data.first - Data.second;
485 }
486 
487 /// Compute the size of the object pointed by Ptr. Returns true and the
488 /// object size in Size if successful, and false otherwise.
489 /// If RoundToAlign is true, then Size is rounded up to the alignment of
490 /// allocas, byval arguments, and global variables.
491 bool llvm::getObjectSize(const Value *Ptr, uint64_t &Size, const DataLayout &DL,
492  const TargetLibraryInfo *TLI, ObjectSizeOpts Opts) {
493  ObjectSizeOffsetVisitor Visitor(DL, TLI, Ptr->getContext(), Opts);
494  SizeOffsetType Data = Visitor.compute(const_cast<Value*>(Ptr));
495  if (!Visitor.bothKnown(Data))
496  return false;
497 
498  Size = getSizeWithOverflow(Data).getZExtValue();
499  return true;
500 }
501 
503  const DataLayout &DL,
504  const TargetLibraryInfo *TLI,
505  bool MustSucceed) {
506  assert(ObjectSize->getIntrinsicID() == Intrinsic::objectsize &&
507  "ObjectSize must be a call to llvm.objectsize!");
508 
509  bool MaxVal = cast<ConstantInt>(ObjectSize->getArgOperand(1))->isZero();
510  ObjectSizeOpts EvalOptions;
511  // Unless we have to fold this to something, try to be as accurate as
512  // possible.
513  if (MustSucceed)
514  EvalOptions.EvalMode =
516  else
518 
519  EvalOptions.NullIsUnknownSize =
520  cast<ConstantInt>(ObjectSize->getArgOperand(2))->isOne();
521 
522  auto *ResultType = cast<IntegerType>(ObjectSize->getType());
523  bool StaticOnly = cast<ConstantInt>(ObjectSize->getArgOperand(3))->isZero();
524  if (StaticOnly) {
525  // FIXME: Does it make sense to just return a failure value if the size won't
526  // fit in the output and `!MustSucceed`?
527  uint64_t Size;
528  if (getObjectSize(ObjectSize->getArgOperand(0), Size, DL, TLI, EvalOptions) &&
529  isUIntN(ResultType->getBitWidth(), Size))
530  return ConstantInt::get(ResultType, Size);
531  } else {
532  LLVMContext &Ctx = ObjectSize->getFunction()->getContext();
533  ObjectSizeOffsetEvaluator Eval(DL, TLI, Ctx, EvalOptions);
534  SizeOffsetEvalType SizeOffsetPair =
535  Eval.compute(ObjectSize->getArgOperand(0));
536 
537  if (SizeOffsetPair != ObjectSizeOffsetEvaluator::unknown()) {
538  IRBuilder<TargetFolder> Builder(Ctx, TargetFolder(DL));
539  Builder.SetInsertPoint(ObjectSize);
540 
541  // If we've outside the end of the object, then we can always access
542  // exactly 0 bytes.
543  Value *ResultSize =
544  Builder.CreateSub(SizeOffsetPair.first, SizeOffsetPair.second);
545  Value *UseZero =
546  Builder.CreateICmpULT(SizeOffsetPair.first, SizeOffsetPair.second);
547  return Builder.CreateSelect(UseZero, ConstantInt::get(ResultType, 0),
548  ResultSize);
549  }
550  }
551 
552  if (!MustSucceed)
553  return nullptr;
554 
555  return ConstantInt::get(ResultType, MaxVal ? -1ULL : 0);
556 }
557 
558 STATISTIC(ObjectVisitorArgument,
559  "Number of arguments with unsolved size and offset");
560 STATISTIC(ObjectVisitorLoad,
561  "Number of load instructions with unsolved size and offset");
562 
563 APInt ObjectSizeOffsetVisitor::align(APInt Size, uint64_t Align) {
564  if (Options.RoundToAlign && Align)
565  return APInt(IntTyBits, alignTo(Size.getZExtValue(), llvm::Align(Align)));
566  return Size;
567 }
568 
570  const TargetLibraryInfo *TLI,
572  ObjectSizeOpts Options)
573  : DL(DL), TLI(TLI), Options(Options) {
574  // Pointer size must be rechecked for each object visited since it could have
575  // a different address space.
576 }
577 
579  IntTyBits = DL.getPointerTypeSizeInBits(V->getType());
580  Zero = APInt::getNullValue(IntTyBits);
581 
582  V = V->stripPointerCasts();
583  if (Instruction *I = dyn_cast<Instruction>(V)) {
584  // If we have already seen this instruction, bail out. Cycles can happen in
585  // unreachable code after constant propagation.
586  if (!SeenInsts.insert(I).second)
587  return unknown();
588 
589  if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
590  return visitGEPOperator(*GEP);
591  return visit(*I);
592  }
593  if (Argument *A = dyn_cast<Argument>(V))
594  return visitArgument(*A);
595  if (ConstantPointerNull *P = dyn_cast<ConstantPointerNull>(V))
596  return visitConstantPointerNull(*P);
597  if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
598  return visitGlobalAlias(*GA);
599  if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
600  return visitGlobalVariable(*GV);
601  if (UndefValue *UV = dyn_cast<UndefValue>(V))
602  return visitUndefValue(*UV);
603  if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
604  if (CE->getOpcode() == Instruction::IntToPtr)
605  return unknown(); // clueless
606  if (CE->getOpcode() == Instruction::GetElementPtr)
607  return visitGEPOperator(cast<GEPOperator>(*CE));
608  }
609 
610  LLVM_DEBUG(dbgs() << "ObjectSizeOffsetVisitor::compute() unhandled value: "
611  << *V << '\n');
612  return unknown();
613 }
614 
615 /// When we're compiling N-bit code, and the user uses parameters that are
616 /// greater than N bits (e.g. uint64_t on a 32-bit build), we can run into
617 /// trouble with APInt size issues. This function handles resizing + overflow
618 /// checks for us. Check and zext or trunc \p I depending on IntTyBits and
619 /// I's value.
620 bool ObjectSizeOffsetVisitor::CheckedZextOrTrunc(APInt &I) {
621  // More bits than we can handle. Checking the bit width isn't necessary, but
622  // it's faster than checking active bits, and should give `false` in the
623  // vast majority of cases.
624  if (I.getBitWidth() > IntTyBits && I.getActiveBits() > IntTyBits)
625  return false;
626  if (I.getBitWidth() != IntTyBits)
627  I = I.zextOrTrunc(IntTyBits);
628  return true;
629 }
630 
632  if (!I.getAllocatedType()->isSized())
633  return unknown();
634 
635  APInt Size(IntTyBits, DL.getTypeAllocSize(I.getAllocatedType()));
636  if (!I.isArrayAllocation())
637  return std::make_pair(align(Size, I.getAlignment()), Zero);
638 
639  Value *ArraySize = I.getArraySize();
640  if (const ConstantInt *C = dyn_cast<ConstantInt>(ArraySize)) {
641  APInt NumElems = C->getValue();
642  if (!CheckedZextOrTrunc(NumElems))
643  return unknown();
644 
645  bool Overflow;
646  Size = Size.umul_ov(NumElems, Overflow);
647  return Overflow ? unknown() : std::make_pair(align(Size, I.getAlignment()),
648  Zero);
649  }
650  return unknown();
651 }
652 
654  // No interprocedural analysis is done at the moment.
655  if (!A.hasByValOrInAllocaAttr()) {
656  ++ObjectVisitorArgument;
657  return unknown();
658  }
659  PointerType *PT = cast<PointerType>(A.getType());
660  APInt Size(IntTyBits, DL.getTypeAllocSize(PT->getElementType()));
661  return std::make_pair(align(Size, A.getParamAlignment()), Zero);
662 }
663 
666  if (!FnData)
667  return unknown();
668 
669  // Handle strdup-like functions separately.
670  if (FnData->AllocTy == StrDupLike) {
671  APInt Size(IntTyBits, GetStringLength(CS.getArgument(0)));
672  if (!Size)
673  return unknown();
674 
675  // Strndup limits strlen.
676  if (FnData->FstParam > 0) {
677  ConstantInt *Arg =
679  if (!Arg)
680  return unknown();
681 
682  APInt MaxSize = Arg->getValue().zextOrSelf(IntTyBits);
683  if (Size.ugt(MaxSize))
684  Size = MaxSize + 1;
685  }
686  return std::make_pair(Size, Zero);
687  }
688 
690  if (!Arg)
691  return unknown();
692 
693  APInt Size = Arg->getValue();
694  if (!CheckedZextOrTrunc(Size))
695  return unknown();
696 
697  // Size is determined by just 1 parameter.
698  if (FnData->SndParam < 0)
699  return std::make_pair(Size, Zero);
700 
701  Arg = dyn_cast<ConstantInt>(CS.getArgument(FnData->SndParam));
702  if (!Arg)
703  return unknown();
704 
705  APInt NumElems = Arg->getValue();
706  if (!CheckedZextOrTrunc(NumElems))
707  return unknown();
708 
709  bool Overflow;
710  Size = Size.umul_ov(NumElems, Overflow);
711  return Overflow ? unknown() : std::make_pair(Size, Zero);
712 
713  // TODO: handle more standard functions (+ wchar cousins):
714  // - strdup / strndup
715  // - strcpy / strncpy
716  // - strcat / strncat
717  // - memcpy / memmove
718  // - strcat / strncat
719  // - memset
720 }
721 
724  // If null is unknown, there's nothing we can do. Additionally, non-zero
725  // address spaces can make use of null, so we don't presume to know anything
726  // about that.
727  //
728  // TODO: How should this work with address space casts? We currently just drop
729  // them on the floor, but it's unclear what we should do when a NULL from
730  // addrspace(1) gets casted to addrspace(0) (or vice-versa).
731  if (Options.NullIsUnknownSize || CPN.getType()->getAddressSpace())
732  return unknown();
733  return std::make_pair(Zero, Zero);
734 }
735 
738  return unknown();
739 }
740 
743  // Easy cases were already folded by previous passes.
744  return unknown();
745 }
746 
748  SizeOffsetType PtrData = compute(GEP.getPointerOperand());
749  APInt Offset(IntTyBits, 0);
750  if (!bothKnown(PtrData) || !GEP.accumulateConstantOffset(DL, Offset))
751  return unknown();
752 
753  return std::make_pair(PtrData.first, PtrData.second + Offset);
754 }
755 
757  if (GA.isInterposable())
758  return unknown();
759  return compute(GA.getAliasee());
760 }
761 
763  if (!GV.hasDefinitiveInitializer())
764  return unknown();
765 
766  APInt Size(IntTyBits, DL.getTypeAllocSize(GV.getValueType()));
767  return std::make_pair(align(Size, GV.getAlignment()), Zero);
768 }
769 
771  // clueless
772  return unknown();
773 }
774 
776  ++ObjectVisitorLoad;
777  return unknown();
778 }
779 
781  // too complex to analyze statically.
782  return unknown();
783 }
784 
786  SizeOffsetType TrueSide = compute(I.getTrueValue());
787  SizeOffsetType FalseSide = compute(I.getFalseValue());
788  if (bothKnown(TrueSide) && bothKnown(FalseSide)) {
789  if (TrueSide == FalseSide) {
790  return TrueSide;
791  }
792 
793  APInt TrueResult = getSizeWithOverflow(TrueSide);
794  APInt FalseResult = getSizeWithOverflow(FalseSide);
795 
796  if (TrueResult == FalseResult) {
797  return TrueSide;
798  }
799  if (Options.EvalMode == ObjectSizeOpts::Mode::Min) {
800  if (TrueResult.slt(FalseResult))
801  return TrueSide;
802  return FalseSide;
803  }
804  if (Options.EvalMode == ObjectSizeOpts::Mode::Max) {
805  if (TrueResult.sgt(FalseResult))
806  return TrueSide;
807  return FalseSide;
808  }
809  }
810  return unknown();
811 }
812 
814  return std::make_pair(Zero, Zero);
815 }
816 
818  LLVM_DEBUG(dbgs() << "ObjectSizeOffsetVisitor unknown instruction:" << I
819  << '\n');
820  return unknown();
821 }
822 
824  const DataLayout &DL, const TargetLibraryInfo *TLI, LLVMContext &Context,
825  ObjectSizeOpts EvalOpts)
826  : DL(DL), TLI(TLI), Context(Context),
827  Builder(Context, TargetFolder(DL),
829  [&](Instruction *I) { InsertedInstructions.insert(I); })),
830  EvalOpts(EvalOpts) {
831  // IntTy and Zero must be set for each compute() since the address space may
832  // be different for later objects.
833 }
834 
836  // XXX - Are vectors of pointers possible here?
837  IntTy = cast<IntegerType>(DL.getIntPtrType(V->getType()));
838  Zero = ConstantInt::get(IntTy, 0);
839 
840  SizeOffsetEvalType Result = compute_(V);
841 
842  if (!bothKnown(Result)) {
843  // Erase everything that was computed in this iteration from the cache, so
844  // that no dangling references are left behind. We could be a bit smarter if
845  // we kept a dependency graph. It's probably not worth the complexity.
846  for (const Value *SeenVal : SeenVals) {
847  CacheMapTy::iterator CacheIt = CacheMap.find(SeenVal);
848  // non-computable results can be safely cached
849  if (CacheIt != CacheMap.end() && anyKnown(CacheIt->second))
850  CacheMap.erase(CacheIt);
851  }
852 
853  // Erase any instructions we inserted as part of the traversal.
854  for (Instruction *I : InsertedInstructions) {
855  I->replaceAllUsesWith(UndefValue::get(I->getType()));
856  I->eraseFromParent();
857  }
858  }
859 
860  SeenVals.clear();
861  InsertedInstructions.clear();
862  return Result;
863 }
864 
865 SizeOffsetEvalType ObjectSizeOffsetEvaluator::compute_(Value *V) {
866  ObjectSizeOffsetVisitor Visitor(DL, TLI, Context, EvalOpts);
867  SizeOffsetType Const = Visitor.compute(V);
868  if (Visitor.bothKnown(Const))
869  return std::make_pair(ConstantInt::get(Context, Const.first),
870  ConstantInt::get(Context, Const.second));
871 
872  V = V->stripPointerCasts();
873 
874  // Check cache.
875  CacheMapTy::iterator CacheIt = CacheMap.find(V);
876  if (CacheIt != CacheMap.end())
877  return CacheIt->second;
878 
879  // Always generate code immediately before the instruction being
880  // processed, so that the generated code dominates the same BBs.
881  BuilderTy::InsertPointGuard Guard(Builder);
882  if (Instruction *I = dyn_cast<Instruction>(V))
883  Builder.SetInsertPoint(I);
884 
885  // Now compute the size and offset.
886  SizeOffsetEvalType Result;
887 
888  // Record the pointers that were handled in this run, so that they can be
889  // cleaned later if something fails. We also use this set to break cycles that
890  // can occur in dead code.
891  if (!SeenVals.insert(V).second) {
892  Result = unknown();
893  } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
894  Result = visitGEPOperator(*GEP);
895  } else if (Instruction *I = dyn_cast<Instruction>(V)) {
896  Result = visit(*I);
897  } else if (isa<Argument>(V) ||
898  (isa<ConstantExpr>(V) &&
899  cast<ConstantExpr>(V)->getOpcode() == Instruction::IntToPtr) ||
900  isa<GlobalAlias>(V) ||
901  isa<GlobalVariable>(V)) {
902  // Ignore values where we cannot do more than ObjectSizeVisitor.
903  Result = unknown();
904  } else {
905  LLVM_DEBUG(
906  dbgs() << "ObjectSizeOffsetEvaluator::compute() unhandled value: " << *V
907  << '\n');
908  Result = unknown();
909  }
910 
911  // Don't reuse CacheIt since it may be invalid at this point.
912  CacheMap[V] = Result;
913  return Result;
914 }
915 
917  if (!I.getAllocatedType()->isSized())
918  return unknown();
919 
920  // must be a VLA
922  Value *ArraySize = I.getArraySize();
923  Value *Size = ConstantInt::get(ArraySize->getType(),
925  Size = Builder.CreateMul(Size, ArraySize);
926  return std::make_pair(Size, Zero);
927 }
928 
931  if (!FnData)
932  return unknown();
933 
934  // Handle strdup-like functions separately.
935  if (FnData->AllocTy == StrDupLike) {
936  // TODO
937  return unknown();
938  }
939 
940  Value *FirstArg = CS.getArgument(FnData->FstParam);
941  FirstArg = Builder.CreateZExt(FirstArg, IntTy);
942  if (FnData->SndParam < 0)
943  return std::make_pair(FirstArg, Zero);
944 
945  Value *SecondArg = CS.getArgument(FnData->SndParam);
946  SecondArg = Builder.CreateZExt(SecondArg, IntTy);
947  Value *Size = Builder.CreateMul(FirstArg, SecondArg);
948  return std::make_pair(Size, Zero);
949 
950  // TODO: handle more standard functions (+ wchar cousins):
951  // - strdup / strndup
952  // - strcpy / strncpy
953  // - strcat / strncat
954  // - memcpy / memmove
955  // - strcat / strncat
956  // - memset
957 }
958 
961  return unknown();
962 }
963 
966  return unknown();
967 }
968 
971  SizeOffsetEvalType PtrData = compute_(GEP.getPointerOperand());
972  if (!bothKnown(PtrData))
973  return unknown();
974 
975  Value *Offset = EmitGEPOffset(&Builder, DL, &GEP, /*NoAssumptions=*/true);
976  Offset = Builder.CreateAdd(PtrData.second, Offset);
977  return std::make_pair(PtrData.first, Offset);
978 }
979 
981  // clueless
982  return unknown();
983 }
984 
986  return unknown();
987 }
988 
990  // Create 2 PHIs: one for size and another for offset.
991  PHINode *SizePHI = Builder.CreatePHI(IntTy, PHI.getNumIncomingValues());
992  PHINode *OffsetPHI = Builder.CreatePHI(IntTy, PHI.getNumIncomingValues());
993 
994  // Insert right away in the cache to handle recursive PHIs.
995  CacheMap[&PHI] = std::make_pair(SizePHI, OffsetPHI);
996 
997  // Compute offset/size for each PHI incoming pointer.
998  for (unsigned i = 0, e = PHI.getNumIncomingValues(); i != e; ++i) {
1000  SizeOffsetEvalType EdgeData = compute_(PHI.getIncomingValue(i));
1001 
1002  if (!bothKnown(EdgeData)) {
1003  OffsetPHI->replaceAllUsesWith(UndefValue::get(IntTy));
1004  OffsetPHI->eraseFromParent();
1005  InsertedInstructions.erase(OffsetPHI);
1006  SizePHI->replaceAllUsesWith(UndefValue::get(IntTy));
1007  SizePHI->eraseFromParent();
1008  InsertedInstructions.erase(SizePHI);
1009  return unknown();
1010  }
1011  SizePHI->addIncoming(EdgeData.first, PHI.getIncomingBlock(i));
1012  OffsetPHI->addIncoming(EdgeData.second, PHI.getIncomingBlock(i));
1013  }
1014 
1015  Value *Size = SizePHI, *Offset = OffsetPHI;
1016  if (Value *Tmp = SizePHI->hasConstantValue()) {
1017  Size = Tmp;
1018  SizePHI->replaceAllUsesWith(Size);
1019  SizePHI->eraseFromParent();
1020  InsertedInstructions.erase(SizePHI);
1021  }
1022  if (Value *Tmp = OffsetPHI->hasConstantValue()) {
1023  Offset = Tmp;
1024  OffsetPHI->replaceAllUsesWith(Offset);
1025  OffsetPHI->eraseFromParent();
1026  InsertedInstructions.erase(OffsetPHI);
1027  }
1028  return std::make_pair(Size, Offset);
1029 }
1030 
1032  SizeOffsetEvalType TrueSide = compute_(I.getTrueValue());
1033  SizeOffsetEvalType FalseSide = compute_(I.getFalseValue());
1034 
1035  if (!bothKnown(TrueSide) || !bothKnown(FalseSide))
1036  return unknown();
1037  if (TrueSide == FalseSide)
1038  return TrueSide;
1039 
1040  Value *Size = Builder.CreateSelect(I.getCondition(), TrueSide.first,
1041  FalseSide.first);
1042  Value *Offset = Builder.CreateSelect(I.getCondition(), TrueSide.second,
1043  FalseSide.second);
1044  return std::make_pair(Size, Offset);
1045 }
1046 
1048  LLVM_DEBUG(dbgs() << "ObjectSizeOffsetEvaluator unknown instruction:" << I
1049  << '\n');
1050  return unknown();
1051 }
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:28
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:233
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:1571
This class represents an incoming formal argument to a Function.
Definition: Argument.h:29
LLVMContext & Context
This class represents lattice values for constants.
Definition: AllocatorList.h:23
Type * getParamType(unsigned i) const
Parameter type accessors.
Definition: DerivedTypes.h:135
Value * CreateICmpULT(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:2118
static SizeOffsetEvalType unknown()
bool isSized(SmallPtrSetImpl< Type *> *Visited=nullptr) const
Return true if it makes sense to take the size of this type.
Definition: Type.h:264
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:610
bool hasByValOrInAllocaAttr() const
Return true if this argument has the byval attribute or inalloca attribute.
Definition: Function.cpp:104
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:1203
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:84
An efficient, type-erasing, non-owning reference to a callable.
Definition: STLExtras.h:104
LLVMContext & getContext() const
All values hold a context through their type.
Definition: Value.cpp:733
bool hasRetAttr(Attribute::AttrKind Kind) const
Return true if this return value has the given attribute.
Definition: CallSite.h:380
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:429
bool sgt(const APInt &RHS) const
Signed greather than comparison.
Definition: APInt.h:1273
AllocType
STATISTIC(NumFunctions, "Total number of functions")
F(f)
bool isLibFreeFunction(const Function *F, const LibFunc TLIFn)
isLibFreeFunction - Returns true if the function is a builtin free()
An instruction for reading from memory.
Definition: Instructions.h:167
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:111
bool isReallocLikeFn(const Value *V, const TargetLibraryInfo *TLI, bool LookThroughBitCast=false)
Tests if a value is a call or invoke to a library function that reallocates memory (e...
APInt zextOrTrunc(unsigned width) const
Zero extend or truncate to width.
Definition: APInt.cpp:930
SizeOffsetType visitArgument(Argument &A)
Hexagon Common GEP
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition: APInt.h:1517
bool accumulateConstantOffset(const DataLayout &DL, APInt &Offset) const
Accumulate the constant address offset of this GEP if possible.
Definition: Operator.cpp:34
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
Definition: Type.h:129
const CallInst * isFreeCall(const Value *I, const TargetLibraryInfo *TLI)
isFreeCall - Returns non-null if the value is a call to the builtin free()
Value * getArgOperand(unsigned i) const
Definition: InstrTypes.h:1241
This class represents the LLVM &#39;select&#39; instruction.
const CallInst * extractMallocCall(const Value *I, function_ref< const TargetLibraryInfo &(Function &)> GetTLI)
extractMallocCall - Returns the corresponding CallInst if the instruction is a malloc call...
unsigned getAlignment() const
Return the alignment of the memory that is being allocated by the instruction.
Definition: Instructions.h:112
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:668
&#39;undef&#39; values are things that do not have specified contents.
Definition: Constants.h:1285
static Optional< AllocFnsTy > getAllocationSize(const Value *V, const TargetLibraryInfo *TLI)
Class to represent struct types.
Definition: DerivedTypes.h:233
APInt zextOrSelf(unsigned width) const
Zero extend or truncate to width.
Definition: APInt.cpp:946
static Optional< unsigned > getOpcode(ArrayRef< VPValue *> Values)
Returns the opcode of Values or ~0 if they do not all agree.
Definition: VPlanSLP.cpp:196
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition: Type.h:196
SizeOffsetEvalType visitCallSite(CallSite CS)
SizeOffsetType visitIntToPtrInst(IntToPtrInst &)
This file contains the simple types necessary to represent the attributes associated with functions a...
Value * CreateAdd(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition: IRBuilder.h:1118
This file implements a class to represent arbitrary precision integral constant values and operations...
Value * 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.
InstrTy * getInstruction() const
Definition: CallSite.h:96
unsigned getActiveBits() const
Compute the number of active bits in the value.
Definition: APInt.h:1541
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:888
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.
Evaluate the size and offset of an object pointed to by a Value*.
bool has(LibFunc F) const
Tests whether a library function is available.
This class represents a no-op cast from one type to another.
bool isOpNewLikeFn(const Value *V, const TargetLibraryInfo *TLI, bool LookThroughBitCast=false)
Tests if a value is a call or invoke to a library function that allocates memory and throws if an all...
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition: Constants.h:137
TargetFolder - Create constants with target dependent folding.
Definition: TargetFolder.h:31
Value * CreateSub(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition: IRBuilder.h:1135
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition: Value.cpp:429
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:273
Value * CreateZExt(Value *V, Type *DestTy, const Twine &Name="")
Definition: IRBuilder.h:1878
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)
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block...
Definition: IRBuilder.h:132
Class to represent pointers.
Definition: DerivedTypes.h:544
iterator find(const_arg_type_t< KeyT > Val)
Definition: DenseMap.h:150
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:140
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:766
#define P(N)
bool erase(const KeyT &Val)
Definition: DenseMap.h:272
bool isNoBuiltin() const
Return true if the call should not be treated as a call to a builtin.
Definition: CallSite.h:441
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:216
ObjectSizeOffsetEvaluator(const DataLayout &DL, const TargetLibraryInfo *TLI, LLVMContext &Context, ObjectSizeOpts EvalOpts={})
The instances of the Type class are immutable: once they are created, they are never changed...
Definition: Type.h:45
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:64
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:2285
ValTy * getArgument(unsigned ArgNo) const
Definition: CallSite.h:193
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:370
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:473
amdgpu Simplify well known AMD library false FunctionCallee Value * Arg
static bool hasNoAliasAttr(const Value *V, bool LookThroughBitCast)
unsigned getAddressSpace() const
Return the address space of the Pointer type.
Definition: DerivedTypes.h:572
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:1193
const Function * getFunction() const
Return the function this instruction belongs to.
Definition: Instruction.cpp:59
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:205
static UndefValue * get(Type *T)
Static factory methods - Return an &#39;undef&#39; object of the specified type.
Definition: Constants.cpp:1446
const Value * stripPointerCasts() const
Strip off pointer casts, all-zero GEPs and address space casts.
Definition: Value.cpp:525
SizeOffsetType visitCallSite(CallSite CS)
const Value * getArraySize() const
Get the number of elements allocated.
Definition: Instructions.h:92
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:219
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:1152
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition: Alignment.h:40
Type * getAllocatedType() const
Return the type that is being allocated by the instruction.
Definition: Instructions.h:105
SizeOffsetType visitSelectInst(SelectInst &I)
Intrinsic::ID getIntrinsicID() const
Return the intrinsic ID of this intrinsic.
Definition: IntrinsicInst.h:50
SizeOffsetType visitExtractElementInst(ExtractElementInst &I)
SizeOffsetType visitGlobalAlias(GlobalAlias &GA)
PHINode * CreatePHI(Type *Ty, unsigned NumReservedValues, const Twine &Name="")
Definition: IRBuilder.h:2232
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:191
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:83
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:111
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:538
Type * getReturnType() const
Definition: DerivedTypes.h:124
uint64_t getSizeInBytes() const
Definition: DataLayout.h:567
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:653
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:163
Class for arbitrary precision integers.
Definition: APInt.h:69
amdgpu Simplify well known AMD library false FunctionCallee Callee
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:389
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:470
bool ugt(const APInt &RHS) const
Unsigned greather than comparison.
Definition: APInt.h:1254
static bool isZero(Value *V, const DataLayout &DL, DominatorTree *DT, AssumptionCache *AC)
Definition: Lint.cpp:549
Provides an &#39;InsertHelper&#39; that calls a user-provided callback after performing the default insertion...
Definition: IRBuilder.h:72
uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition: Alignment.h:133
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:214
Establish a view to a call site for examination.
Definition: CallSite.h:897
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:554
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:82
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:332
Type * getValueType() const
Definition: GlobalValue.h:279
This instruction extracts a single (scalar) element from a VectorType value.
uint32_t Size
Definition: Profile.cpp:46
bool anyKnown(SizeOffsetEvalType SizeOffset)
APInt umul_ov(const APInt &RHS, bool &Overflow) const
Definition: APInt.cpp:1973
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:395
static bool bothKnown(const SizeOffsetType &SizeOffset)
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:333
AllocType AllocTy
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:48
Various options to control the behavior of getObjectSize.
static APInt getNullValue(unsigned numBits)
Get the &#39;0&#39; value.
Definition: APInt.h:568
bool isUIntN(unsigned N, uint64_t x)
Checks if an unsigned integer fits into the given (dynamic) bit width.
Definition: MathExtras.h:392
#define LLVM_DEBUG(X)
Definition: Debug.h:122
SizeOffsetType visitLoadInst(LoadInst &I)
SizeOffsetEvalType visitAllocaInst(AllocaInst &I)
bool isStrdupLikeFn(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 (strdup, strndup).
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:563
A wrapper class for inspecting calls to intrinsic functions.
Definition: IntrinsicInst.h:43
an instruction to allocate memory on the stack
Definition: Instructions.h:59
user_iterator user_end()
Definition: Value.h:403
const Constant * getAliasee() const
Definition: GlobalAlias.h:73