LLVM  4.0.0
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/STLExtras.h"
17 #include "llvm/ADT/Statistic.h"
20 #include "llvm/IR/DataLayout.h"
21 #include "llvm/IR/GlobalVariable.h"
22 #include "llvm/IR/Instructions.h"
23 #include "llvm/IR/Intrinsics.h"
24 #include "llvm/IR/Metadata.h"
25 #include "llvm/IR/Module.h"
26 #include "llvm/Support/Debug.h"
30 using namespace llvm;
31 
32 #define DEBUG_TYPE "memory-builtins"
33 
34 enum AllocType : uint8_t {
35  OpNewLike = 1<<0, // allocates; never returns null
36  MallocLike = 1<<1 | OpNewLike, // allocates; may return null
37  CallocLike = 1<<2, // allocates + bzero
38  ReallocLike = 1<<3, // reallocates
39  StrDupLike = 1<<4,
42 };
43 
44 struct AllocFnsTy {
46  unsigned NumParams;
47  // First and Second size parameters (or -1 if unused)
48  int FstParam, SndParam;
49 };
50 
51 // FIXME: certain users need more information. E.g., SimplifyLibCalls needs to
52 // know which functions are nounwind, noalias, nocapture parameters, etc.
53 static const std::pair<LibFunc::Func, AllocFnsTy> AllocationFnData[] = {
54  {LibFunc::malloc, {MallocLike, 1, 0, -1}},
55  {LibFunc::valloc, {MallocLike, 1, 0, -1}},
56  {LibFunc::Znwj, {OpNewLike, 1, 0, -1}}, // new(unsigned int)
57  {LibFunc::ZnwjRKSt9nothrow_t, {MallocLike, 2, 0, -1}}, // new(unsigned int, nothrow)
58  {LibFunc::Znwm, {OpNewLike, 1, 0, -1}}, // new(unsigned long)
59  {LibFunc::ZnwmRKSt9nothrow_t, {MallocLike, 2, 0, -1}}, // new(unsigned long, nothrow)
60  {LibFunc::Znaj, {OpNewLike, 1, 0, -1}}, // new[](unsigned int)
61  {LibFunc::ZnajRKSt9nothrow_t, {MallocLike, 2, 0, -1}}, // new[](unsigned int, nothrow)
62  {LibFunc::Znam, {OpNewLike, 1, 0, -1}}, // new[](unsigned long)
63  {LibFunc::ZnamRKSt9nothrow_t, {MallocLike, 2, 0, -1}}, // new[](unsigned long, nothrow)
64  {LibFunc::msvc_new_int, {OpNewLike, 1, 0, -1}}, // new(unsigned int)
65  {LibFunc::msvc_new_int_nothrow, {MallocLike, 2, 0, -1}}, // new(unsigned int, nothrow)
66  {LibFunc::msvc_new_longlong, {OpNewLike, 1, 0, -1}}, // new(unsigned long long)
67  {LibFunc::msvc_new_longlong_nothrow, {MallocLike, 2, 0, -1}}, // new(unsigned long long, nothrow)
68  {LibFunc::msvc_new_array_int, {OpNewLike, 1, 0, -1}}, // new[](unsigned int)
69  {LibFunc::msvc_new_array_int_nothrow, {MallocLike, 2, 0, -1}}, // new[](unsigned int, nothrow)
70  {LibFunc::msvc_new_array_longlong, {OpNewLike, 1, 0, -1}}, // new[](unsigned long long)
71  {LibFunc::msvc_new_array_longlong_nothrow, {MallocLike, 2, 0, -1}}, // new[](unsigned long long, nothrow)
72  {LibFunc::calloc, {CallocLike, 2, 0, 1}},
73  {LibFunc::realloc, {ReallocLike, 2, 1, -1}},
74  {LibFunc::reallocf, {ReallocLike, 2, 1, -1}},
75  {LibFunc::strdup, {StrDupLike, 1, -1, -1}},
76  {LibFunc::strndup, {StrDupLike, 2, 1, -1}}
77  // TODO: Handle "int posix_memalign(void **, size_t, size_t)"
78 };
79 
80 static Function *getCalledFunction(const Value *V, bool LookThroughBitCast,
81  bool &IsNoBuiltin) {
82  // Don't care about intrinsics in this case.
83  if (isa<IntrinsicInst>(V))
84  return nullptr;
85 
86  if (LookThroughBitCast)
87  V = V->stripPointerCasts();
88 
89  CallSite CS(const_cast<Value*>(V));
90  if (!CS.getInstruction())
91  return nullptr;
92 
93  IsNoBuiltin = CS.isNoBuiltin();
94 
95  Function *Callee = CS.getCalledFunction();
96  if (!Callee || !Callee->isDeclaration())
97  return nullptr;
98  return Callee;
99 }
100 
101 /// Returns the allocation data for the given value if it's either a call to a
102 /// known allocation function, or a call to a function with the allocsize
103 /// attribute.
106  const TargetLibraryInfo *TLI) {
107  // Make sure that the function is available.
108  StringRef FnName = Callee->getName();
109  LibFunc::Func TLIFn;
110  if (!TLI || !TLI->getLibFunc(FnName, TLIFn) || !TLI->has(TLIFn))
111  return None;
112 
113  const auto *Iter = find_if(
114  AllocationFnData, [TLIFn](const std::pair<LibFunc::Func, AllocFnsTy> &P) {
115  return P.first == TLIFn;
116  });
117 
118  if (Iter == std::end(AllocationFnData))
119  return None;
120 
121  const AllocFnsTy *FnData = &Iter->second;
122  if ((FnData->AllocTy & AllocTy) != FnData->AllocTy)
123  return None;
124 
125  // Check function prototype.
126  int FstParam = FnData->FstParam;
127  int SndParam = FnData->SndParam;
128  FunctionType *FTy = Callee->getFunctionType();
129 
130  if (FTy->getReturnType() == Type::getInt8PtrTy(FTy->getContext()) &&
131  FTy->getNumParams() == FnData->NumParams &&
132  (FstParam < 0 ||
133  (FTy->getParamType(FstParam)->isIntegerTy(32) ||
134  FTy->getParamType(FstParam)->isIntegerTy(64))) &&
135  (SndParam < 0 ||
136  FTy->getParamType(SndParam)->isIntegerTy(32) ||
137  FTy->getParamType(SndParam)->isIntegerTy(64)))
138  return *FnData;
139  return None;
140 }
141 
143  const TargetLibraryInfo *TLI,
144  bool LookThroughBitCast = false) {
145  bool IsNoBuiltinCall;
146  if (const Function *Callee =
147  getCalledFunction(V, LookThroughBitCast, IsNoBuiltinCall))
148  if (!IsNoBuiltinCall)
149  return getAllocationDataForFunction(Callee, AllocTy, TLI);
150  return None;
151 }
152 
154  const TargetLibraryInfo *TLI) {
155  bool IsNoBuiltinCall;
156  const Function *Callee =
157  getCalledFunction(V, /*LookThroughBitCast=*/false, IsNoBuiltinCall);
158  if (!Callee)
159  return None;
160 
161  // Prefer to use existing information over allocsize. This will give us an
162  // accurate AllocTy.
163  if (!IsNoBuiltinCall)
164  if (Optional<AllocFnsTy> Data =
166  return Data;
167 
168  Attribute Attr = Callee->getFnAttribute(Attribute::AllocSize);
169  if (Attr == Attribute())
170  return None;
171 
172  std::pair<unsigned, Optional<unsigned>> Args = Attr.getAllocSizeArgs();
173 
174  AllocFnsTy Result;
175  // Because allocsize only tells us how many bytes are allocated, we're not
176  // really allowed to assume anything, so we use MallocLike.
177  Result.AllocTy = MallocLike;
178  Result.NumParams = Callee->getNumOperands();
179  Result.FstParam = Args.first;
180  Result.SndParam = Args.second.getValueOr(-1);
181  return Result;
182 }
183 
184 static bool hasNoAliasAttr(const Value *V, bool LookThroughBitCast) {
185  ImmutableCallSite CS(LookThroughBitCast ? V->stripPointerCasts() : V);
186  return CS && CS.paramHasAttr(AttributeSet::ReturnIndex, Attribute::NoAlias);
187 }
188 
189 
190 /// \brief Tests if a value is a call or invoke to a library function that
191 /// allocates or reallocates memory (either malloc, calloc, realloc, or strdup
192 /// like).
193 bool llvm::isAllocationFn(const Value *V, const TargetLibraryInfo *TLI,
194  bool LookThroughBitCast) {
195  return getAllocationData(V, AnyAlloc, TLI, LookThroughBitCast).hasValue();
196 }
197 
198 /// \brief Tests if a value is a call or invoke to a function that returns a
199 /// NoAlias pointer (including malloc/calloc/realloc/strdup-like functions).
200 bool llvm::isNoAliasFn(const Value *V, const TargetLibraryInfo *TLI,
201  bool LookThroughBitCast) {
202  // it's safe to consider realloc as noalias since accessing the original
203  // pointer is undefined behavior
204  return isAllocationFn(V, TLI, LookThroughBitCast) ||
205  hasNoAliasAttr(V, LookThroughBitCast);
206 }
207 
208 /// \brief Tests if a value is a call or invoke to a library function that
209 /// allocates uninitialized memory (such as malloc).
210 bool llvm::isMallocLikeFn(const Value *V, const TargetLibraryInfo *TLI,
211  bool LookThroughBitCast) {
212  return getAllocationData(V, MallocLike, TLI, LookThroughBitCast).hasValue();
213 }
214 
215 /// \brief Tests if a value is a call or invoke to a library function that
216 /// allocates zero-filled memory (such as calloc).
217 bool llvm::isCallocLikeFn(const Value *V, const TargetLibraryInfo *TLI,
218  bool LookThroughBitCast) {
219  return getAllocationData(V, CallocLike, TLI, LookThroughBitCast).hasValue();
220 }
221 
222 /// \brief Tests if a value is a call or invoke to a library function that
223 /// allocates memory (either malloc, calloc, or strdup like).
224 bool llvm::isAllocLikeFn(const Value *V, const TargetLibraryInfo *TLI,
225  bool LookThroughBitCast) {
226  return getAllocationData(V, AllocLike, TLI, LookThroughBitCast).hasValue();
227 }
228 
229 /// extractMallocCall - Returns the corresponding CallInst if the instruction
230 /// is a malloc call. Since CallInst::CreateMalloc() only creates calls, we
231 /// ignore InvokeInst here.
233  const TargetLibraryInfo *TLI) {
234  return isMallocLikeFn(I, TLI) ? dyn_cast<CallInst>(I) : nullptr;
235 }
236 
237 static Value *computeArraySize(const CallInst *CI, const DataLayout &DL,
238  const TargetLibraryInfo *TLI,
239  bool LookThroughSExt = false) {
240  if (!CI)
241  return nullptr;
242 
243  // The size of the malloc's result type must be known to determine array size.
244  Type *T = getMallocAllocatedType(CI, TLI);
245  if (!T || !T->isSized())
246  return nullptr;
247 
248  unsigned ElementSize = DL.getTypeAllocSize(T);
249  if (StructType *ST = dyn_cast<StructType>(T))
250  ElementSize = DL.getStructLayout(ST)->getSizeInBytes();
251 
252  // If malloc call's arg can be determined to be a multiple of ElementSize,
253  // return the multiple. Otherwise, return NULL.
254  Value *MallocArg = CI->getArgOperand(0);
255  Value *Multiple = nullptr;
256  if (ComputeMultiple(MallocArg, ElementSize, Multiple, LookThroughSExt))
257  return Multiple;
258 
259  return nullptr;
260 }
261 
262 /// getMallocType - Returns the PointerType resulting from the malloc call.
263 /// The PointerType depends on the number of bitcast uses of the malloc call:
264 /// 0: PointerType is the calls' return type.
265 /// 1: PointerType is the bitcast's result type.
266 /// >1: Unique PointerType cannot be determined, return NULL.
268  const TargetLibraryInfo *TLI) {
269  assert(isMallocLikeFn(CI, TLI) && "getMallocType and not malloc call");
270 
271  PointerType *MallocType = nullptr;
272  unsigned NumOfBitCastUses = 0;
273 
274  // Determine if CallInst has a bitcast use.
275  for (Value::const_user_iterator UI = CI->user_begin(), E = CI->user_end();
276  UI != E;)
277  if (const BitCastInst *BCI = dyn_cast<BitCastInst>(*UI++)) {
278  MallocType = cast<PointerType>(BCI->getDestTy());
279  NumOfBitCastUses++;
280  }
281 
282  // Malloc call has 1 bitcast use, so type is the bitcast's destination type.
283  if (NumOfBitCastUses == 1)
284  return MallocType;
285 
286  // Malloc call was not bitcast, so type is the malloc function's return type.
287  if (NumOfBitCastUses == 0)
288  return cast<PointerType>(CI->getType());
289 
290  // Type could not be determined.
291  return nullptr;
292 }
293 
294 /// getMallocAllocatedType - Returns the Type allocated by malloc call.
295 /// The Type depends on the number of bitcast uses of the malloc call:
296 /// 0: PointerType is the malloc calls' return type.
297 /// 1: PointerType is the bitcast's result type.
298 /// >1: Unique PointerType cannot be determined, return NULL.
300  const TargetLibraryInfo *TLI) {
301  PointerType *PT = getMallocType(CI, TLI);
302  return PT ? PT->getElementType() : nullptr;
303 }
304 
305 /// getMallocArraySize - Returns the array size of a malloc call. If the
306 /// argument passed to malloc is a multiple of the size of the malloced type,
307 /// then return that multiple. For non-array mallocs, the multiple is
308 /// constant 1. Otherwise, return NULL for mallocs whose array size cannot be
309 /// determined.
311  const TargetLibraryInfo *TLI,
312  bool LookThroughSExt) {
313  assert(isMallocLikeFn(CI, TLI) && "getMallocArraySize and not malloc call");
314  return computeArraySize(CI, DL, TLI, LookThroughSExt);
315 }
316 
317 
318 /// extractCallocCall - Returns the corresponding CallInst if the instruction
319 /// is a calloc call.
321  const TargetLibraryInfo *TLI) {
322  return isCallocLikeFn(I, TLI) ? cast<CallInst>(I) : nullptr;
323 }
324 
325 
326 /// isFreeCall - Returns non-null if the value is a call to the builtin free()
327 const CallInst *llvm::isFreeCall(const Value *I, const TargetLibraryInfo *TLI) {
328  const CallInst *CI = dyn_cast<CallInst>(I);
329  if (!CI || isa<IntrinsicInst>(CI))
330  return nullptr;
331  Function *Callee = CI->getCalledFunction();
332  if (Callee == nullptr)
333  return nullptr;
334 
335  StringRef FnName = Callee->getName();
336  LibFunc::Func TLIFn;
337  if (!TLI || !TLI->getLibFunc(FnName, TLIFn) || !TLI->has(TLIFn))
338  return nullptr;
339 
340  unsigned ExpectedNumParams;
341  if (TLIFn == LibFunc::free ||
342  TLIFn == LibFunc::ZdlPv || // operator delete(void*)
343  TLIFn == LibFunc::ZdaPv || // operator delete[](void*)
344  TLIFn == LibFunc::msvc_delete_ptr32 || // operator delete(void*)
345  TLIFn == LibFunc::msvc_delete_ptr64 || // operator delete(void*)
346  TLIFn == LibFunc::msvc_delete_array_ptr32 || // operator delete[](void*)
347  TLIFn == LibFunc::msvc_delete_array_ptr64) // operator delete[](void*)
348  ExpectedNumParams = 1;
349  else if (TLIFn == LibFunc::ZdlPvj || // delete(void*, uint)
350  TLIFn == LibFunc::ZdlPvm || // delete(void*, ulong)
351  TLIFn == LibFunc::ZdlPvRKSt9nothrow_t || // delete(void*, nothrow)
352  TLIFn == LibFunc::ZdaPvj || // delete[](void*, uint)
353  TLIFn == LibFunc::ZdaPvm || // delete[](void*, ulong)
354  TLIFn == LibFunc::ZdaPvRKSt9nothrow_t || // delete[](void*, nothrow)
355  TLIFn == LibFunc::msvc_delete_ptr32_int || // delete(void*, uint)
356  TLIFn == LibFunc::msvc_delete_ptr64_longlong || // delete(void*, ulonglong)
357  TLIFn == LibFunc::msvc_delete_ptr32_nothrow || // delete(void*, nothrow)
358  TLIFn == LibFunc::msvc_delete_ptr64_nothrow || // delete(void*, nothrow)
359  TLIFn == LibFunc::msvc_delete_array_ptr32_int || // delete[](void*, uint)
360  TLIFn == LibFunc::msvc_delete_array_ptr64_longlong || // delete[](void*, ulonglong)
361  TLIFn == LibFunc::msvc_delete_array_ptr32_nothrow || // delete[](void*, nothrow)
362  TLIFn == LibFunc::msvc_delete_array_ptr64_nothrow) // delete[](void*, nothrow)
363  ExpectedNumParams = 2;
364  else
365  return nullptr;
366 
367  // Check free prototype.
368  // FIXME: workaround for PR5130, this will be obsolete when a nobuiltin
369  // attribute will exist.
370  FunctionType *FTy = Callee->getFunctionType();
371  if (!FTy->getReturnType()->isVoidTy())
372  return nullptr;
373  if (FTy->getNumParams() != ExpectedNumParams)
374  return nullptr;
375  if (FTy->getParamType(0) != Type::getInt8PtrTy(Callee->getContext()))
376  return nullptr;
377 
378  return CI;
379 }
380 
381 
382 
383 //===----------------------------------------------------------------------===//
384 // Utility functions to compute size of objects.
385 //
387  if (Data.second.isNegative() || Data.first.ult(Data.second))
388  return APInt(Data.first.getBitWidth(), 0);
389  return Data.first - Data.second;
390 }
391 
392 /// \brief Compute the size of the object pointed by Ptr. Returns true and the
393 /// object size in Size if successful, and false otherwise.
394 /// If RoundToAlign is true, then Size is rounded up to the aligment of allocas,
395 /// byval arguments, and global variables.
396 bool llvm::getObjectSize(const Value *Ptr, uint64_t &Size, const DataLayout &DL,
397  const TargetLibraryInfo *TLI, bool RoundToAlign,
399  ObjectSizeOffsetVisitor Visitor(DL, TLI, Ptr->getContext(),
400  RoundToAlign, Mode);
401  SizeOffsetType Data = Visitor.compute(const_cast<Value*>(Ptr));
402  if (!Visitor.bothKnown(Data))
403  return false;
404 
405  Size = getSizeWithOverflow(Data).getZExtValue();
406  return true;
407 }
408 
410  const DataLayout &DL,
411  const TargetLibraryInfo *TLI,
412  bool MustSucceed) {
413  assert(ObjectSize->getIntrinsicID() == Intrinsic::objectsize &&
414  "ObjectSize must be a call to llvm.objectsize!");
415 
416  bool MaxVal = cast<ConstantInt>(ObjectSize->getArgOperand(1))->isZero();
418  // Unless we have to fold this to something, try to be as accurate as
419  // possible.
420  if (MustSucceed)
421  Mode = MaxVal ? ObjSizeMode::Max : ObjSizeMode::Min;
422  else
423  Mode = ObjSizeMode::Exact;
424 
425  // FIXME: Does it make sense to just return a failure value if the size won't
426  // fit in the output and `!MustSucceed`?
427  uint64_t Size;
428  auto *ResultType = cast<IntegerType>(ObjectSize->getType());
429  if (getObjectSize(ObjectSize->getArgOperand(0), Size, DL, TLI, false, Mode) &&
430  isUIntN(ResultType->getBitWidth(), Size))
431  return ConstantInt::get(ResultType, Size);
432 
433  if (!MustSucceed)
434  return nullptr;
435 
436  return ConstantInt::get(ResultType, MaxVal ? -1ULL : 0);
437 }
438 
439 STATISTIC(ObjectVisitorArgument,
440  "Number of arguments with unsolved size and offset");
441 STATISTIC(ObjectVisitorLoad,
442  "Number of load instructions with unsolved size and offset");
443 
444 
445 APInt ObjectSizeOffsetVisitor::align(APInt Size, uint64_t Align) {
446  if (RoundToAlign && Align)
447  return APInt(IntTyBits, alignTo(Size.getZExtValue(), Align));
448  return Size;
449 }
450 
452  const TargetLibraryInfo *TLI,
454  bool RoundToAlign,
456  : DL(DL), TLI(TLI), RoundToAlign(RoundToAlign), Mode(Mode) {
457  // Pointer size must be rechecked for each object visited since it could have
458  // a different address space.
459 }
460 
462  IntTyBits = DL.getPointerTypeSizeInBits(V->getType());
463  Zero = APInt::getNullValue(IntTyBits);
464 
465  V = V->stripPointerCasts();
466  if (Instruction *I = dyn_cast<Instruction>(V)) {
467  // If we have already seen this instruction, bail out. Cycles can happen in
468  // unreachable code after constant propagation.
469  if (!SeenInsts.insert(I).second)
470  return unknown();
471 
472  if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
473  return visitGEPOperator(*GEP);
474  return visit(*I);
475  }
476  if (Argument *A = dyn_cast<Argument>(V))
477  return visitArgument(*A);
478  if (ConstantPointerNull *P = dyn_cast<ConstantPointerNull>(V))
479  return visitConstantPointerNull(*P);
480  if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
481  return visitGlobalAlias(*GA);
482  if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
483  return visitGlobalVariable(*GV);
484  if (UndefValue *UV = dyn_cast<UndefValue>(V))
485  return visitUndefValue(*UV);
486  if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
487  if (CE->getOpcode() == Instruction::IntToPtr)
488  return unknown(); // clueless
489  if (CE->getOpcode() == Instruction::GetElementPtr)
490  return visitGEPOperator(cast<GEPOperator>(*CE));
491  }
492 
493  DEBUG(dbgs() << "ObjectSizeOffsetVisitor::compute() unhandled value: " << *V
494  << '\n');
495  return unknown();
496 }
497 
499  if (!I.getAllocatedType()->isSized())
500  return unknown();
501 
502  APInt Size(IntTyBits, DL.getTypeAllocSize(I.getAllocatedType()));
503  if (!I.isArrayAllocation())
504  return std::make_pair(align(Size, I.getAlignment()), Zero);
505 
506  Value *ArraySize = I.getArraySize();
507  if (const ConstantInt *C = dyn_cast<ConstantInt>(ArraySize)) {
508  Size *= C->getValue().zextOrSelf(IntTyBits);
509  return std::make_pair(align(Size, I.getAlignment()), Zero);
510  }
511  return unknown();
512 }
513 
515  // No interprocedural analysis is done at the moment.
516  if (!A.hasByValOrInAllocaAttr()) {
517  ++ObjectVisitorArgument;
518  return unknown();
519  }
520  PointerType *PT = cast<PointerType>(A.getType());
521  APInt Size(IntTyBits, DL.getTypeAllocSize(PT->getElementType()));
522  return std::make_pair(align(Size, A.getParamAlignment()), Zero);
523 }
524 
527  if (!FnData)
528  return unknown();
529 
530  // Handle strdup-like functions separately.
531  if (FnData->AllocTy == StrDupLike) {
532  APInt Size(IntTyBits, GetStringLength(CS.getArgument(0)));
533  if (!Size)
534  return unknown();
535 
536  // Strndup limits strlen.
537  if (FnData->FstParam > 0) {
538  ConstantInt *Arg =
540  if (!Arg)
541  return unknown();
542 
543  APInt MaxSize = Arg->getValue().zextOrSelf(IntTyBits);
544  if (Size.ugt(MaxSize))
545  Size = MaxSize + 1;
546  }
547  return std::make_pair(Size, Zero);
548  }
549 
550  ConstantInt *Arg = dyn_cast<ConstantInt>(CS.getArgument(FnData->FstParam));
551  if (!Arg)
552  return unknown();
553 
554  // When we're compiling N-bit code, and the user uses parameters that are
555  // greater than N bits (e.g. uint64_t on a 32-bit build), we can run into
556  // trouble with APInt size issues. This function handles resizing + overflow
557  // checks for us.
558  auto CheckedZextOrTrunc = [&](APInt &I) {
559  // More bits than we can handle. Checking the bit width isn't necessary, but
560  // it's faster than checking active bits, and should give `false` in the
561  // vast majority of cases.
562  if (I.getBitWidth() > IntTyBits && I.getActiveBits() > IntTyBits)
563  return false;
564  if (I.getBitWidth() != IntTyBits)
565  I = I.zextOrTrunc(IntTyBits);
566  return true;
567  };
568 
569  APInt Size = Arg->getValue();
570  if (!CheckedZextOrTrunc(Size))
571  return unknown();
572 
573  // Size is determined by just 1 parameter.
574  if (FnData->SndParam < 0)
575  return std::make_pair(Size, Zero);
576 
577  Arg = dyn_cast<ConstantInt>(CS.getArgument(FnData->SndParam));
578  if (!Arg)
579  return unknown();
580 
581  APInt NumElems = Arg->getValue();
582  if (!CheckedZextOrTrunc(NumElems))
583  return unknown();
584 
585  bool Overflow;
586  Size = Size.umul_ov(NumElems, Overflow);
587  return Overflow ? unknown() : std::make_pair(Size, Zero);
588 
589  // TODO: handle more standard functions (+ wchar cousins):
590  // - strdup / strndup
591  // - strcpy / strncpy
592  // - strcat / strncat
593  // - memcpy / memmove
594  // - strcat / strncat
595  // - memset
596 }
597 
600  return std::make_pair(Zero, Zero);
601 }
602 
605  return unknown();
606 }
607 
610  // Easy cases were already folded by previous passes.
611  return unknown();
612 }
613 
615  SizeOffsetType PtrData = compute(GEP.getPointerOperand());
616  APInt Offset(IntTyBits, 0);
617  if (!bothKnown(PtrData) || !GEP.accumulateConstantOffset(DL, Offset))
618  return unknown();
619 
620  return std::make_pair(PtrData.first, PtrData.second + Offset);
621 }
622 
624  if (GA.isInterposable())
625  return unknown();
626  return compute(GA.getAliasee());
627 }
628 
630  if (!GV.hasDefinitiveInitializer())
631  return unknown();
632 
633  APInt Size(IntTyBits, DL.getTypeAllocSize(GV.getType()->getElementType()));
634  return std::make_pair(align(Size, GV.getAlignment()), Zero);
635 }
636 
638  // clueless
639  return unknown();
640 }
641 
643  ++ObjectVisitorLoad;
644  return unknown();
645 }
646 
648  // too complex to analyze statically.
649  return unknown();
650 }
651 
653  SizeOffsetType TrueSide = compute(I.getTrueValue());
654  SizeOffsetType FalseSide = compute(I.getFalseValue());
655  if (bothKnown(TrueSide) && bothKnown(FalseSide)) {
656  if (TrueSide == FalseSide) {
657  return TrueSide;
658  }
659 
660  APInt TrueResult = getSizeWithOverflow(TrueSide);
661  APInt FalseResult = getSizeWithOverflow(FalseSide);
662 
663  if (TrueResult == FalseResult) {
664  return TrueSide;
665  }
666  if (Mode == ObjSizeMode::Min) {
667  if (TrueResult.slt(FalseResult))
668  return TrueSide;
669  return FalseSide;
670  }
671  if (Mode == ObjSizeMode::Max) {
672  if (TrueResult.sgt(FalseResult))
673  return TrueSide;
674  return FalseSide;
675  }
676  }
677  return unknown();
678 }
679 
681  return std::make_pair(Zero, Zero);
682 }
683 
685  DEBUG(dbgs() << "ObjectSizeOffsetVisitor unknown instruction:" << I << '\n');
686  return unknown();
687 }
688 
690  const DataLayout &DL, const TargetLibraryInfo *TLI, LLVMContext &Context,
691  bool RoundToAlign)
692  : DL(DL), TLI(TLI), Context(Context), Builder(Context, TargetFolder(DL)),
693  RoundToAlign(RoundToAlign) {
694  // IntTy and Zero must be set for each compute() since the address space may
695  // be different for later objects.
696 }
697 
699  // XXX - Are vectors of pointers possible here?
700  IntTy = cast<IntegerType>(DL.getIntPtrType(V->getType()));
701  Zero = ConstantInt::get(IntTy, 0);
702 
703  SizeOffsetEvalType Result = compute_(V);
704 
705  if (!bothKnown(Result)) {
706  // Erase everything that was computed in this iteration from the cache, so
707  // that no dangling references are left behind. We could be a bit smarter if
708  // we kept a dependency graph. It's probably not worth the complexity.
709  for (const Value *SeenVal : SeenVals) {
710  CacheMapTy::iterator CacheIt = CacheMap.find(SeenVal);
711  // non-computable results can be safely cached
712  if (CacheIt != CacheMap.end() && anyKnown(CacheIt->second))
713  CacheMap.erase(CacheIt);
714  }
715  }
716 
717  SeenVals.clear();
718  return Result;
719 }
720 
721 SizeOffsetEvalType ObjectSizeOffsetEvaluator::compute_(Value *V) {
722  ObjectSizeOffsetVisitor Visitor(DL, TLI, Context, RoundToAlign);
723  SizeOffsetType Const = Visitor.compute(V);
724  if (Visitor.bothKnown(Const))
725  return std::make_pair(ConstantInt::get(Context, Const.first),
726  ConstantInt::get(Context, Const.second));
727 
728  V = V->stripPointerCasts();
729 
730  // Check cache.
731  CacheMapTy::iterator CacheIt = CacheMap.find(V);
732  if (CacheIt != CacheMap.end())
733  return CacheIt->second;
734 
735  // Always generate code immediately before the instruction being
736  // processed, so that the generated code dominates the same BBs.
737  BuilderTy::InsertPointGuard Guard(Builder);
738  if (Instruction *I = dyn_cast<Instruction>(V))
739  Builder.SetInsertPoint(I);
740 
741  // Now compute the size and offset.
742  SizeOffsetEvalType Result;
743 
744  // Record the pointers that were handled in this run, so that they can be
745  // cleaned later if something fails. We also use this set to break cycles that
746  // can occur in dead code.
747  if (!SeenVals.insert(V).second) {
748  Result = unknown();
749  } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
750  Result = visitGEPOperator(*GEP);
751  } else if (Instruction *I = dyn_cast<Instruction>(V)) {
752  Result = visit(*I);
753  } else if (isa<Argument>(V) ||
754  (isa<ConstantExpr>(V) &&
755  cast<ConstantExpr>(V)->getOpcode() == Instruction::IntToPtr) ||
756  isa<GlobalAlias>(V) ||
757  isa<GlobalVariable>(V)) {
758  // Ignore values where we cannot do more than ObjectSizeVisitor.
759  Result = unknown();
760  } else {
761  DEBUG(dbgs() << "ObjectSizeOffsetEvaluator::compute() unhandled value: "
762  << *V << '\n');
763  Result = unknown();
764  }
765 
766  // Don't reuse CacheIt since it may be invalid at this point.
767  CacheMap[V] = Result;
768  return Result;
769 }
770 
772  if (!I.getAllocatedType()->isSized())
773  return unknown();
774 
775  // must be a VLA
777  Value *ArraySize = I.getArraySize();
778  Value *Size = ConstantInt::get(ArraySize->getType(),
780  Size = Builder.CreateMul(Size, ArraySize);
781  return std::make_pair(Size, Zero);
782 }
783 
786  if (!FnData)
787  return unknown();
788 
789  // Handle strdup-like functions separately.
790  if (FnData->AllocTy == StrDupLike) {
791  // TODO
792  return unknown();
793  }
794 
795  Value *FirstArg = CS.getArgument(FnData->FstParam);
796  FirstArg = Builder.CreateZExt(FirstArg, IntTy);
797  if (FnData->SndParam < 0)
798  return std::make_pair(FirstArg, Zero);
799 
800  Value *SecondArg = CS.getArgument(FnData->SndParam);
801  SecondArg = Builder.CreateZExt(SecondArg, IntTy);
802  Value *Size = Builder.CreateMul(FirstArg, SecondArg);
803  return std::make_pair(Size, Zero);
804 
805  // TODO: handle more standard functions (+ wchar cousins):
806  // - strdup / strndup
807  // - strcpy / strncpy
808  // - strcat / strncat
809  // - memcpy / memmove
810  // - strcat / strncat
811  // - memset
812 }
813 
816  return unknown();
817 }
818 
821  return unknown();
822 }
823 
826  SizeOffsetEvalType PtrData = compute_(GEP.getPointerOperand());
827  if (!bothKnown(PtrData))
828  return unknown();
829 
830  Value *Offset = EmitGEPOffset(&Builder, DL, &GEP, /*NoAssumptions=*/true);
831  Offset = Builder.CreateAdd(PtrData.second, Offset);
832  return std::make_pair(PtrData.first, Offset);
833 }
834 
836  // clueless
837  return unknown();
838 }
839 
841  return unknown();
842 }
843 
845  // Create 2 PHIs: one for size and another for offset.
846  PHINode *SizePHI = Builder.CreatePHI(IntTy, PHI.getNumIncomingValues());
847  PHINode *OffsetPHI = Builder.CreatePHI(IntTy, PHI.getNumIncomingValues());
848 
849  // Insert right away in the cache to handle recursive PHIs.
850  CacheMap[&PHI] = std::make_pair(SizePHI, OffsetPHI);
851 
852  // Compute offset/size for each PHI incoming pointer.
853  for (unsigned i = 0, e = PHI.getNumIncomingValues(); i != e; ++i) {
855  SizeOffsetEvalType EdgeData = compute_(PHI.getIncomingValue(i));
856 
857  if (!bothKnown(EdgeData)) {
858  OffsetPHI->replaceAllUsesWith(UndefValue::get(IntTy));
859  OffsetPHI->eraseFromParent();
860  SizePHI->replaceAllUsesWith(UndefValue::get(IntTy));
861  SizePHI->eraseFromParent();
862  return unknown();
863  }
864  SizePHI->addIncoming(EdgeData.first, PHI.getIncomingBlock(i));
865  OffsetPHI->addIncoming(EdgeData.second, PHI.getIncomingBlock(i));
866  }
867 
868  Value *Size = SizePHI, *Offset = OffsetPHI, *Tmp;
869  if ((Tmp = SizePHI->hasConstantValue())) {
870  Size = Tmp;
871  SizePHI->replaceAllUsesWith(Size);
872  SizePHI->eraseFromParent();
873  }
874  if ((Tmp = OffsetPHI->hasConstantValue())) {
875  Offset = Tmp;
876  OffsetPHI->replaceAllUsesWith(Offset);
877  OffsetPHI->eraseFromParent();
878  }
879  return std::make_pair(Size, Offset);
880 }
881 
883  SizeOffsetEvalType TrueSide = compute_(I.getTrueValue());
884  SizeOffsetEvalType FalseSide = compute_(I.getFalseValue());
885 
886  if (!bothKnown(TrueSide) || !bothKnown(FalseSide))
887  return unknown();
888  if (TrueSide == FalseSide)
889  return TrueSide;
890 
891  Value *Size = Builder.CreateSelect(I.getCondition(), TrueSide.first,
892  FalseSide.first);
893  Value *Offset = Builder.CreateSelect(I.getCondition(), TrueSide.second,
894  FalseSide.second);
895  return std::make_pair(Size, Offset);
896 }
897 
899  DEBUG(dbgs() << "ObjectSizeOffsetEvaluator unknown instruction:" << I <<'\n');
900  return unknown();
901 }
const NoneType None
Definition: None.h:23
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:196
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
Definition: Instruction.cpp:76
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:102
const_iterator end(StringRef path)
Get end iterator over path.
Definition: Path.cpp:241
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...
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function. ...
Definition: Function.cpp:226
LLVM Argument representation.
Definition: Argument.h:34
LLVMContext & Context
uint64_t getZExtValue() const
Get zero extended value.
Definition: APInt.h:1309
SI Whole Quad Mode
STATISTIC(NumFunctions,"Total number of functions")
size_t i
unsigned getNumParams() const
Return the number of fixed parameters this function type requires.
Definition: DerivedTypes.h:137
unsigned NumParams
Intrinsic::ID getIntrinsicID() const
Return the intrinsic ID of this intrinsic.
Definition: IntrinsicInst.h:51
const CallInst * extractCallocCall(const Value *I, const TargetLibraryInfo *TLI)
extractCallocCall - Returns the corresponding CallInst if the instruction is a calloc call...
uint64_t GetStringLength(const Value *V)
If we can compute the length of the string pointed to by the specified pointer, return 'len+1'...
bool hasByValOrInAllocaAttr() const
Return true if this argument has the byval attribute or inalloca attribute on it in its containing fu...
Definition: Function.cpp:107
unsigned getNumOperands() const
Definition: User.h:167
unsigned getPointerTypeSizeInBits(Type *) const
Layout pointer size, in bits, based on the type.
Definition: DataLayout.cpp:617
Attribute
Attributes.
Definition: Dwarf.h:94
This class represents a function call, abstracting a target machine's calling convention.
This file contains the declarations for metadata subclasses.
static Optional< AllocFnsTy > getAllocationDataForFunction(const Function *Callee, AllocType AllocTy, const TargetLibraryInfo *TLI)
Returns the allocation data for the given value if it's either a call to a known allocation function...
SizeOffsetType visitAllocaInst(AllocaInst &I)
AllocType
The two locations do not alias at all.
Definition: AliasAnalysis.h:79
Attribute getFnAttribute(Attribute::AttrKind Kind) const
Return the attribute for the given attribute kind.
Definition: Function.h:234
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:664
An instruction for reading from memory.
Definition: Instructions.h:164
SizeOffsetType visitArgument(Argument &A)
Hexagon Common GEP
Type * getElementType() const
Definition: DerivedTypes.h:462
const Constant * getAliasee() const
Definition: GlobalAlias.h:74
bool isNoBuiltin() const
Return true if the call should not be treated as a call to a builtin.
Definition: CallSite.h:408
const CallInst * isFreeCall(const Value *I, const TargetLibraryInfo *TLI)
isFreeCall - Returns non-null if the value is a call to the builtin free()
StringRef getName() const
Return a constant reference to the value's name.
Definition: Value.cpp:191
bool isArrayAllocation() const
Return true if there is an allocation size parameter to the allocation instruction that is not 1...
This class represents the LLVM 'select' instruction.
SizeOffsetEvalType visitGEPOperator(GEPOperator &GEP)
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:566
SizeOffsetType visitExtractValueInst(ExtractValueInst &I)
SizeOffsetType visitGEPOperator(GEPOperator &GEP)
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition: Constants.h:143
'undef' values are things that do not have specified contents.
Definition: Constants.h:1258
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:220
bool has(LibFunc::Func F) const
Tests whether a library function is available.
static Optional< AllocFnsTy > getAllocationSize(const Value *V, const TargetLibraryInfo *TLI)
Class to represent struct types.
Definition: DerivedTypes.h:199
SizeOffsetEvalType visitCallSite(CallSite CS)
SizeOffsetType visitIntToPtrInst(IntToPtrInst &)
Value * CreateAdd(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition: IRBuilder.h:813
ObjectSizeOffsetEvaluator(const DataLayout &DL, const TargetLibraryInfo *TLI, LLVMContext &Context, bool RoundToAlign=false)
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...
A constant value that is initialized with an expression using other constant values.
Definition: Constants.h:873
Class to represent function types.
Definition: DerivedTypes.h:102
APInt zextOrSelf(unsigned width) const
Zero extend or truncate to width.
Definition: APInt.cpp:1015
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
Definition: Type.h:128
bool accumulateConstantOffset(const DataLayout &DL, APInt &Offset) const
Accumulate the constant address offset of this GEP if possible.
Definition: Operator.cpp:21
unsigned getAlignment() const
Definition: GlobalObject.h:59
bool sgt(const APInt &RHS) const
Signed greather than comparison.
Definition: APInt.h:1101
This class represents a no-op cast from one type to another.
TargetFolder - Create constants with target dependent folding.
Definition: TargetFolder.h:32
bool getObjectSize(const Value *Ptr, uint64_t &Size, const DataLayout &DL, const TargetLibraryInfo *TLI, bool RoundToAlign=false, ObjSizeMode Mode=ObjSizeMode::Exact)
Compute the size of the object pointed by Ptr.
std::pair< APInt, APInt > SizeOffsetType
bool hasDefinitiveInitializer() const
hasDefinitiveInitializer - Whether the global variable has an initializer, and any other instances of...
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition: Value.cpp:401
APInt umul_ov(const APInt &RHS, bool &Overflow) const
Definition: APInt.cpp:2025
Value * CreateZExt(Value *V, Type *DestTy, const Twine &Name="")
Definition: IRBuilder.h:1301
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:127
Class to represent pointers.
Definition: DerivedTypes.h:443
static GCRegistry::Add< CoreCLRGC > E("coreclr","CoreCLR-compatible GC")
unsigned getNumIncomingValues() const
Return the number of incoming edges.
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 isSized(SmallPtrSetImpl< Type * > *Visited=nullptr) const
Return true if it makes sense to take the size of this type.
Definition: Type.h:254
bool getLibFunc(StringRef funcName, LibFunc::Func &F) const
Searches for a particular function name.
#define P(N)
Type * getParamType(unsigned i) const
Parameter type accessors.
Definition: DerivedTypes.h:133
bool erase(const KeyT &Val)
Definition: DenseMap.h:243
SizeOffsetEvalType visitSelectInst(SelectInst &I)
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.
Value * hasConstantValue() const
If the specified PHI node always merges together the same value, return the value, otherwise return null.
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:48
const CallInst * extractMallocCall(const Value *I, const TargetLibraryInfo *TLI)
extractMallocCall - Returns the corresponding CallInst if the instruction is a malloc call...
const Value * getCondition() const
Value * CreateSelect(Value *C, Value *True, Value *False, const Twine &Name="", Instruction *MDFrom=nullptr)
Definition: IRBuilder.h:1609
unsigned getAlignment() const
Return the alignment of the memory that is being allocated by the instruction.
Definition: Instructions.h:109
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:368
unsigned getParamAlignment() const
If this is a byval or inalloca argument, return its alignment.
Definition: Function.cpp:114
static Value * computeArraySize(const CallInst *CI, const DataLayout &DL, const TargetLibraryInfo *TLI, bool LookThroughSExt=false)
static APInt getSizeWithOverflow(const SizeOffsetType &Data)
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
uint32_t Offset
Value * getPointerOperand()
Definition: Operator.h:401
static bool hasNoAliasAttr(const Value *V, bool LookThroughBitCast)
static Optional< AllocFnsTy > getAllocationData(const Value *V, AllocType AllocTy, const TargetLibraryInfo *TLI, bool LookThroughBitCast=false)
This class represents a cast from an integer to a pointer.
static UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
Definition: Constants.cpp:1337
SizeOffsetType visitCallSite(CallSite CS)
LLVMContext & getContext() const
All values hold a context through their type.
Definition: Value.cpp:654
static PointerType * getInt8PtrTy(LLVMContext &C, unsigned AS=0)
Definition: Type.cpp:213
const Value * getTrueValue() const
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:857
SizeOffsetType visitSelectInst(SelectInst &I)
SizeOffsetType visitExtractElementInst(ExtractElementInst &I)
SizeOffsetType visitGlobalAlias(GlobalAlias &GA)
bool ugt(const APInt &RHS) const
Unsigned greather than comparison.
Definition: APInt.h:1083
PHINode * CreatePHI(Type *Ty, unsigned NumReservedValues, const Twine &Name="")
Definition: IRBuilder.h:1574
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:709
SizeOffsetEvalType visitInstruction(Instruction &I)
This is the shared class of boolean and integer constants.
Definition: Constants.h:88
InstrTy * getInstruction() const
Definition: CallSite.h:93
bool slt(const APInt &RHS) const
Signed less than comparison.
Definition: APInt.cpp:533
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
uint64_t getTypeAllocSize(Type *Ty) const
Returns the offset in bytes between successive objects of the specified type, including alignment pad...
Definition: DataLayout.h:408
Evaluate the size and offset of an object pointed to by a Value* statically.
ValTy * getArgument(unsigned ArgNo) const
Definition: CallSite.h:178
Module.h This file contains the declarations for the Module class.
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:230
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:529
uint64_t getSizeInBytes() const
Definition: DataLayout.h:503
Value * stripPointerCasts()
Strip off pointer casts, all-zero GEPs, and aliases.
Definition: Value.cpp:490
SizeOffsetType visitUndefValue(UndefValue &)
DenseMapIterator< KeyT, ValueT, KeyInfoT, BucketT > iterator
Definition: DenseMap.h:62
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:558
Function * getCalledFunction() const
Return the function called, or null if this is an indirect function invocation.
static GCRegistry::Add< ShadowStackGC > C("shadow-stack","Very portable GC for uncooperative code generators")
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:132
SizeOffsetType compute(Value *V)
Value * getArgOperand(unsigned i) const
getArgOperand/setArgOperand - Return/set the i-th call argument.
Class for arbitrary precision integers.
Definition: APInt.h:77
std::pair< Value *, Value * > SizeOffsetEvalType
SizeOffsetEvalType visitIntToPtrInst(IntToPtrInst &)
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition: Type.h:195
Type * getMallocAllocatedType(const CallInst *CI, const TargetLibraryInfo *TLI)
getMallocAllocatedType - Returns the Type allocated by malloc call.
SizeOffsetEvalType visitPHINode(PHINode &PHI)
bool isMallocLikeFn(const Value *V, const TargetLibraryInfo *TLI, bool LookThroughBitCast=false)
Tests if a value is a call or invoke to a library function that allocates uninitialized memory (such ...
SizeOffsetEvalType compute(Value *V)
static bool isZero(Value *V, const DataLayout &DL, DominatorTree *DT, AssumptionCache *AC)
Definition: Lint.cpp:528
PointerType * getType() const
Global values are always pointers.
Definition: GlobalValue.h:259
user_iterator_impl< const User > const_user_iterator
Definition: Value.h:341
bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
Definition: Globals.cpp:188
SizeOffsetEvalType visitLoadInst(LoadInst &I)
ObjectSizeOffsetVisitor(const DataLayout &DL, const TargetLibraryInfo *TLI, LLVMContext &Context, bool RoundToAlign=false, ObjSizeMode Mode=ObjSizeMode::Exact)
ImmutableCallSite - establish a view to a call site for examination.
Definition: CallSite.h:665
bool isCallocLikeFn(const Value *V, const TargetLibraryInfo *TLI, bool LookThroughBitCast=false)
Tests if a value is a call or invoke to a library function that allocates zero-filled memory (such as...
#define I(x, y, z)
Definition: MD5.cpp:54
FunctionType * getFunctionType() const
Returns the FunctionType for me.
Definition: Function.cpp:230
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:69
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.
iterator find(const KeyT &Val)
Definition: DenseMap.h:127
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:287
This instruction extracts a single (scalar) element from a VectorType value.
static const std::pair< LibFunc::Func, AllocFnsTy > AllocationFnData[]
bool isInterposable() const
Return true if this global's definition can be substituted with an arbitrary definition at link time...
Definition: GlobalValue.h:399
bool anyKnown(SizeOffsetEvalType SizeOffset)
static Function * getCalledFunction(const Value *V, bool LookThroughBitCast, bool &IsNoBuiltin)
Type * getReturnType() const
Definition: DerivedTypes.h:123
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
user_iterator user_begin()
Definition: Value.h:346
static bool bothKnown(const SizeOffsetType &SizeOffset)
FunTy * getCalledFunction() const
getCalledFunction - Return the function being called if this is a direct call, otherwise return null ...
Definition: CallSite.h:110
LLVM Value Representation.
Definition: Value.h:71
SizeOffsetEvalType visitExtractElementInst(ExtractElementInst &I)
const Value * getArraySize() const
Get the number of elements allocated.
Definition: Instructions.h:93
AllocType AllocTy
#define DEBUG(X)
Definition: Debug.h:100
const Value * getFalseValue() const
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:47
iterator getFirstInsertionPt()
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
Definition: BasicBlock.cpp:209
static APInt getNullValue(unsigned numBits)
Get the '0' value.
Definition: APInt.h:465
int * Ptr
auto find_if(R &&Range, UnaryPredicate P) -> decltype(std::begin(Range))
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly...
Definition: STLExtras.h:764
bool isUIntN(unsigned N, uint64_t x)
isUIntN - Checks if an unsigned integer fits into the given (dynamic) bit width.
Definition: MathExtras.h:360
Type * getAllocatedType() const
Return the type that is being allocated by the instruction.
Definition: Instructions.h:102
SizeOffsetType visitLoadInst(LoadInst &I)
static GCRegistry::Add< ErlangGC > A("erlang","erlang-compatible garbage collector")
SizeOffsetEvalType visitAllocaInst(AllocaInst &I)
bool bothKnown(SizeOffsetEvalType SizeOffset)
SizeOffsetType visitConstantPointerNull(ConstantPointerNull &)
SizeOffsetEvalType visitExtractValueInst(ExtractValueInst &I)
A wrapper class for inspecting calls to intrinsic functions.
Definition: IntrinsicInst.h:44
bool isVoidTy() const
Return true if this is 'void'.
Definition: Type.h:139
an instruction to allocate memory on the stack
Definition: Instructions.h:60
user_iterator user_end()
Definition: Value.h:354