blob: e0497cbc80185cc4c9bf4512aed39aeced2c81eb [file] [log] [blame]
Victor Hernandezf390e042009-10-27 20:05:49 +00001//===------ MemoryBuiltins.cpp - Identify calls to memory builtins --------===//
Evan Cheng1d9d4bd2009-09-10 04:36:43 +00002//
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//
Victor Hernandezf390e042009-10-27 20:05:49 +000010// This family of functions identifies calls to builtin functions that allocate
Michael Ilsemand9745242013-03-08 21:03:09 +000011// or free memory.
Evan Cheng1d9d4bd2009-09-10 04:36:43 +000012//
13//===----------------------------------------------------------------------===//
14
Victor Hernandezf390e042009-10-27 20:05:49 +000015#include "llvm/Analysis/MemoryBuiltins.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000016#include "llvm/ADT/STLExtras.h"
17#include "llvm/ADT/Statistic.h"
Chandler Carruth62d42152015-01-15 02:16:27 +000018#include "llvm/Analysis/TargetLibraryInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000019#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000020#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"
Nuno Lopes55fff832012-06-21 15:45:28 +000026#include "llvm/Support/Debug.h"
27#include "llvm/Support/MathExtras.h"
28#include "llvm/Support/raw_ostream.h"
Nuno Lopes55fff832012-06-21 15:45:28 +000029#include "llvm/Transforms/Utils/Local.h"
Evan Cheng1d9d4bd2009-09-10 04:36:43 +000030using namespace llvm;
31
Chandler Carruthf1221bd2014-04-22 02:48:03 +000032#define DEBUG_TYPE "memory-builtins"
33
George Burgess IV2ae15e02015-11-17 19:48:06 +000034enum AllocType : uint8_t {
Benjamin Kramer2939dd32013-09-24 17:34:29 +000035 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,
40 AllocLike = MallocLike | CallocLike | StrDupLike,
Benjamin Kramer4d4df042013-09-24 17:15:14 +000041 AnyAlloc = AllocLike | ReallocLike
Nuno Lopes55fff832012-06-21 15:45:28 +000042};
Evan Cheng1d9d4bd2009-09-10 04:36:43 +000043
Nuno Lopes55fff832012-06-21 15:45:28 +000044struct AllocFnsTy {
Nuno Lopes55fff832012-06-21 15:45:28 +000045 AllocType AllocTy;
George Burgess IV278199f2016-04-12 01:05:35 +000046 unsigned NumParams;
Nuno Lopes55fff832012-06-21 15:45:28 +000047 // First and Second size parameters (or -1 if unused)
George Burgess IV278199f2016-04-12 01:05:35 +000048 int FstParam, SndParam;
Nuno Lopes55fff832012-06-21 15:45:28 +000049};
Evan Cheng1d9d4bd2009-09-10 04:36:43 +000050
Nuno Lopes181d67e2012-06-28 16:34:03 +000051// FIXME: certain users need more information. E.g., SimplifyLibCalls needs to
52// know which functions are nounwind, noalias, nocapture parameters, etc.
George Burgess IV278199f2016-04-12 01:05:35 +000053static 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}}
Benjamin Kramer01df8172013-09-24 17:49:08 +000077 // TODO: Handle "int posix_memalign(void **, size_t, size_t)"
Nuno Lopes55fff832012-06-21 15:45:28 +000078};
79
80
81static Function *getCalledFunction(const Value *V, bool LookThroughBitCast) {
82 if (LookThroughBitCast)
83 V = V->stripPointerCasts();
Nuno Lopesdc6085e2012-06-21 21:25:05 +000084
Nuno Lopes15dbcb42012-06-22 15:50:53 +000085 CallSite CS(const_cast<Value*>(V));
86 if (!CS.getInstruction())
Craig Topper9f008862014-04-15 04:59:12 +000087 return nullptr;
Evan Cheng1d9d4bd2009-09-10 04:36:43 +000088
Michael Gottesman41748d72013-06-27 00:25:01 +000089 if (CS.isNoBuiltin())
Craig Topper9f008862014-04-15 04:59:12 +000090 return nullptr;
Richard Smithe04f0d32013-05-16 04:12:04 +000091
Nuno Lopesdc6085e2012-06-21 21:25:05 +000092 Function *Callee = CS.getCalledFunction();
Nuno Lopes55fff832012-06-21 15:45:28 +000093 if (!Callee || !Callee->isDeclaration())
Craig Topper9f008862014-04-15 04:59:12 +000094 return nullptr;
Nuno Lopes55fff832012-06-21 15:45:28 +000095 return Callee;
96}
Evan Cheng1d9d4bd2009-09-10 04:36:43 +000097
George Burgess IV278199f2016-04-12 01:05:35 +000098/// Returns the allocation data for the given value if it's either a call to a
99/// known allocation function, or a call to a function with the allocsize
100/// attribute.
101static Optional<AllocFnsTy> getAllocationData(const Value *V, AllocType AllocTy,
102 const TargetLibraryInfo *TLI,
103 bool LookThroughBitCast = false) {
Michael Ilseman74ffc272013-03-08 21:15:00 +0000104 // Skip intrinsics
105 if (isa<IntrinsicInst>(V))
George Burgess IV278199f2016-04-12 01:05:35 +0000106 return None;
Michael Ilseman74ffc272013-03-08 21:15:00 +0000107
George Burgess IV278199f2016-04-12 01:05:35 +0000108 const Function *Callee = getCalledFunction(V, LookThroughBitCast);
Nuno Lopes55fff832012-06-21 15:45:28 +0000109 if (!Callee)
George Burgess IV278199f2016-04-12 01:05:35 +0000110 return None;
111
112 // If it has allocsize, we can skip checking if it's a known function.
113 //
114 // MallocLike is chosen here because allocsize makes no guarantees about the
115 // nullness of the result of the function, nor does it deal with strings, nor
116 // does it require that the memory returned is zeroed out.
117 LLVM_CONSTEXPR auto AllocSizeAllocTy = MallocLike;
118 if ((AllocTy & AllocSizeAllocTy) == AllocSizeAllocTy &&
119 Callee->hasFnAttribute(Attribute::AllocSize)) {
120 Attribute Attr = Callee->getFnAttribute(Attribute::AllocSize);
121 std::pair<unsigned, Optional<unsigned>> Args = Attr.getAllocSizeArgs();
122
123 AllocFnsTy Result;
124 Result.AllocTy = AllocSizeAllocTy;
125 Result.NumParams = Callee->getNumOperands();
126 Result.FstParam = Args.first;
127 Result.SndParam = Args.second.getValueOr(-1);
128 return Result;
129 }
Nuno Lopes55fff832012-06-21 15:45:28 +0000130
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000131 // Make sure that the function is available.
132 StringRef FnName = Callee->getName();
133 LibFunc::Func TLIFn;
134 if (!TLI || !TLI->getLibFunc(FnName, TLIFn) || !TLI->has(TLIFn))
George Burgess IV278199f2016-04-12 01:05:35 +0000135 return None;
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000136
George Burgess IV278199f2016-04-12 01:05:35 +0000137 const auto *Iter =
Benjamin Kramer74b6d3b2015-10-24 19:03:15 +0000138 std::find_if(std::begin(AllocationFnData), std::end(AllocationFnData),
George Burgess IV278199f2016-04-12 01:05:35 +0000139 [TLIFn](const std::pair<LibFunc::Func, AllocFnsTy> &P) {
140 return P.first == TLIFn;
141 });
Benjamin Kramer74b6d3b2015-10-24 19:03:15 +0000142
George Burgess IV278199f2016-04-12 01:05:35 +0000143 if (Iter == std::end(AllocationFnData))
144 return None;
Nuno Lopes55fff832012-06-21 15:45:28 +0000145
George Burgess IV278199f2016-04-12 01:05:35 +0000146 const AllocFnsTy *FnData = &Iter->second;
Benjamin Kramer2939dd32013-09-24 17:34:29 +0000147 if ((FnData->AllocTy & AllocTy) != FnData->AllocTy)
George Burgess IV278199f2016-04-12 01:05:35 +0000148 return None;
Nuno Lopes55fff832012-06-21 15:45:28 +0000149
150 // Check function prototype.
Nuno Lopesf06b7312012-06-21 18:38:26 +0000151 int FstParam = FnData->FstParam;
152 int SndParam = FnData->SndParam;
Chris Lattner229907c2011-07-18 04:54:35 +0000153 FunctionType *FTy = Callee->getFunctionType();
Nuno Lopes55fff832012-06-21 15:45:28 +0000154
155 if (FTy->getReturnType() == Type::getInt8PtrTy(FTy->getContext()) &&
156 FTy->getNumParams() == FnData->NumParams &&
Nuno Lopesf06b7312012-06-21 18:38:26 +0000157 (FstParam < 0 ||
Nuno Lopes55fff832012-06-21 15:45:28 +0000158 (FTy->getParamType(FstParam)->isIntegerTy(32) ||
159 FTy->getParamType(FstParam)->isIntegerTy(64))) &&
Nuno Lopesf06b7312012-06-21 18:38:26 +0000160 (SndParam < 0 ||
Nuno Lopes55fff832012-06-21 15:45:28 +0000161 FTy->getParamType(SndParam)->isIntegerTy(32) ||
162 FTy->getParamType(SndParam)->isIntegerTy(64)))
George Burgess IV278199f2016-04-12 01:05:35 +0000163 return *FnData;
164 return None;
Nuno Lopes55fff832012-06-21 15:45:28 +0000165}
166
167static bool hasNoAliasAttr(const Value *V, bool LookThroughBitCast) {
Nuno Lopes9ecc8762012-06-25 16:17:54 +0000168 ImmutableCallSite CS(LookThroughBitCast ? V->stripPointerCasts() : V);
Sanjoy Dasef8ed0c2016-02-09 21:54:18 +0000169 return CS && CS.paramHasAttr(AttributeSet::ReturnIndex, Attribute::NoAlias);
Nuno Lopes55fff832012-06-21 15:45:28 +0000170}
171
172
Nuno Lopesdc6085e2012-06-21 21:25:05 +0000173/// \brief Tests if a value is a call or invoke to a library function that
174/// allocates or reallocates memory (either malloc, calloc, realloc, or strdup
175/// like).
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000176bool llvm::isAllocationFn(const Value *V, const TargetLibraryInfo *TLI,
177 bool LookThroughBitCast) {
George Burgess IV278199f2016-04-12 01:05:35 +0000178 return getAllocationData(V, AnyAlloc, TLI, LookThroughBitCast).hasValue();
Nuno Lopes55fff832012-06-21 15:45:28 +0000179}
180
Nuno Lopesdc6085e2012-06-21 21:25:05 +0000181/// \brief Tests if a value is a call or invoke to a function that returns a
Nuno Lopes181d67e2012-06-28 16:34:03 +0000182/// NoAlias pointer (including malloc/calloc/realloc/strdup-like functions).
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000183bool llvm::isNoAliasFn(const Value *V, const TargetLibraryInfo *TLI,
184 bool LookThroughBitCast) {
Nuno Lopes181d67e2012-06-28 16:34:03 +0000185 // it's safe to consider realloc as noalias since accessing the original
186 // pointer is undefined behavior
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000187 return isAllocationFn(V, TLI, LookThroughBitCast) ||
Nuno Lopes55fff832012-06-21 15:45:28 +0000188 hasNoAliasAttr(V, LookThroughBitCast);
189}
190
Nuno Lopesdc6085e2012-06-21 21:25:05 +0000191/// \brief Tests if a value is a call or invoke to a library function that
192/// allocates uninitialized memory (such as malloc).
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000193bool llvm::isMallocLikeFn(const Value *V, const TargetLibraryInfo *TLI,
194 bool LookThroughBitCast) {
George Burgess IV278199f2016-04-12 01:05:35 +0000195 return getAllocationData(V, MallocLike, TLI, LookThroughBitCast).hasValue();
Nuno Lopes55fff832012-06-21 15:45:28 +0000196}
197
Nuno Lopesdc6085e2012-06-21 21:25:05 +0000198/// \brief Tests if a value is a call or invoke to a library function that
199/// allocates zero-filled memory (such as calloc).
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000200bool llvm::isCallocLikeFn(const Value *V, const TargetLibraryInfo *TLI,
201 bool LookThroughBitCast) {
George Burgess IV278199f2016-04-12 01:05:35 +0000202 return getAllocationData(V, CallocLike, TLI, LookThroughBitCast).hasValue();
Nuno Lopes55fff832012-06-21 15:45:28 +0000203}
204
Nuno Lopesdc6085e2012-06-21 21:25:05 +0000205/// \brief Tests if a value is a call or invoke to a library function that
206/// allocates memory (either malloc, calloc, or strdup like).
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000207bool llvm::isAllocLikeFn(const Value *V, const TargetLibraryInfo *TLI,
208 bool LookThroughBitCast) {
George Burgess IV278199f2016-04-12 01:05:35 +0000209 return getAllocationData(V, AllocLike, TLI, LookThroughBitCast).hasValue();
Nuno Lopes55fff832012-06-21 15:45:28 +0000210}
211
Evan Cheng1d9d4bd2009-09-10 04:36:43 +0000212/// extractMallocCall - Returns the corresponding CallInst if the instruction
213/// is a malloc call. Since CallInst::CreateMalloc() only creates calls, we
214/// ignore InvokeInst here.
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000215const CallInst *llvm::extractMallocCall(const Value *I,
216 const TargetLibraryInfo *TLI) {
Craig Topper9f008862014-04-15 04:59:12 +0000217 return isMallocLikeFn(I, TLI) ? dyn_cast<CallInst>(I) : nullptr;
Evan Cheng1d9d4bd2009-09-10 04:36:43 +0000218}
219
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000220static Value *computeArraySize(const CallInst *CI, const DataLayout &DL,
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000221 const TargetLibraryInfo *TLI,
Victor Hernandezfcc77b12009-11-10 08:32:25 +0000222 bool LookThroughSExt = false) {
Evan Cheng1d9d4bd2009-09-10 04:36:43 +0000223 if (!CI)
Craig Topper9f008862014-04-15 04:59:12 +0000224 return nullptr;
Evan Cheng1d9d4bd2009-09-10 04:36:43 +0000225
Victor Hernandezf3db9152009-11-07 00:16:28 +0000226 // The size of the malloc's result type must be known to determine array size.
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000227 Type *T = getMallocAllocatedType(CI, TLI);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000228 if (!T || !T->isSized())
Craig Topper9f008862014-04-15 04:59:12 +0000229 return nullptr;
Victor Hernandez788eaab2009-09-18 19:20:02 +0000230
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000231 unsigned ElementSize = DL.getTypeAllocSize(T);
Chris Lattner229907c2011-07-18 04:54:35 +0000232 if (StructType *ST = dyn_cast<StructType>(T))
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000233 ElementSize = DL.getStructLayout(ST)->getSizeInBytes();
Victor Hernandez788eaab2009-09-18 19:20:02 +0000234
Gabor Greifad7884a2010-06-23 21:41:47 +0000235 // If malloc call's arg can be determined to be a multiple of ElementSize,
Victor Hernandezfcc77b12009-11-10 08:32:25 +0000236 // return the multiple. Otherwise, return NULL.
Gabor Greifad7884a2010-06-23 21:41:47 +0000237 Value *MallocArg = CI->getArgOperand(0);
Craig Topper9f008862014-04-15 04:59:12 +0000238 Value *Multiple = nullptr;
Victor Hernandezfcc77b12009-11-10 08:32:25 +0000239 if (ComputeMultiple(MallocArg, ElementSize, Multiple,
Dan Gohman6a976bb2009-11-18 00:58:27 +0000240 LookThroughSExt))
Victor Hernandezfcc77b12009-11-10 08:32:25 +0000241 return Multiple;
Victor Hernandez788eaab2009-09-18 19:20:02 +0000242
Craig Topper9f008862014-04-15 04:59:12 +0000243 return nullptr;
Evan Cheng1d9d4bd2009-09-10 04:36:43 +0000244}
245
Evan Cheng1d9d4bd2009-09-10 04:36:43 +0000246/// getMallocType - Returns the PointerType resulting from the malloc call.
Victor Hernandezf3db9152009-11-07 00:16:28 +0000247/// The PointerType depends on the number of bitcast uses of the malloc call:
248/// 0: PointerType is the calls' return type.
249/// 1: PointerType is the bitcast's result type.
250/// >1: Unique PointerType cannot be determined, return NULL.
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000251PointerType *llvm::getMallocType(const CallInst *CI,
252 const TargetLibraryInfo *TLI) {
253 assert(isMallocLikeFn(CI, TLI) && "getMallocType and not malloc call");
Michael Ilsemand9745242013-03-08 21:03:09 +0000254
Craig Topper9f008862014-04-15 04:59:12 +0000255 PointerType *MallocType = nullptr;
Victor Hernandezf3db9152009-11-07 00:16:28 +0000256 unsigned NumOfBitCastUses = 0;
257
Victor Hernandez788eaab2009-09-18 19:20:02 +0000258 // Determine if CallInst has a bitcast use.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000259 for (Value::const_user_iterator UI = CI->user_begin(), E = CI->user_end();
260 UI != E;)
Victor Hernandezf3db9152009-11-07 00:16:28 +0000261 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(*UI++)) {
262 MallocType = cast<PointerType>(BCI->getDestTy());
263 NumOfBitCastUses++;
264 }
Evan Cheng1d9d4bd2009-09-10 04:36:43 +0000265
Victor Hernandezf3db9152009-11-07 00:16:28 +0000266 // Malloc call has 1 bitcast use, so type is the bitcast's destination type.
267 if (NumOfBitCastUses == 1)
268 return MallocType;
Evan Cheng1d9d4bd2009-09-10 04:36:43 +0000269
Victor Hernandezddc2ce42009-09-22 18:50:03 +0000270 // Malloc call was not bitcast, so type is the malloc function's return type.
Victor Hernandezf3db9152009-11-07 00:16:28 +0000271 if (NumOfBitCastUses == 0)
Victor Hernandez788eaab2009-09-18 19:20:02 +0000272 return cast<PointerType>(CI->getType());
273
274 // Type could not be determined.
Craig Topper9f008862014-04-15 04:59:12 +0000275 return nullptr;
Evan Cheng1d9d4bd2009-09-10 04:36:43 +0000276}
277
Victor Hernandezf3db9152009-11-07 00:16:28 +0000278/// getMallocAllocatedType - Returns the Type allocated by malloc call.
279/// The Type depends on the number of bitcast uses of the malloc call:
280/// 0: PointerType is the malloc calls' return type.
281/// 1: PointerType is the bitcast's result type.
282/// >1: Unique PointerType cannot be determined, return NULL.
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000283Type *llvm::getMallocAllocatedType(const CallInst *CI,
284 const TargetLibraryInfo *TLI) {
285 PointerType *PT = getMallocType(CI, TLI);
Craig Topper9f008862014-04-15 04:59:12 +0000286 return PT ? PT->getElementType() : nullptr;
Evan Cheng1d9d4bd2009-09-10 04:36:43 +0000287}
288
Michael Ilsemand9745242013-03-08 21:03:09 +0000289/// getMallocArraySize - Returns the array size of a malloc call. If the
Victor Hernandez0d025422009-10-28 20:18:55 +0000290/// argument passed to malloc is a multiple of the size of the malloced type,
291/// then return that multiple. For non-array mallocs, the multiple is
292/// constant 1. Otherwise, return NULL for mallocs whose array size cannot be
Victor Hernandez13020b12009-10-15 20:14:52 +0000293/// determined.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000294Value *llvm::getMallocArraySize(CallInst *CI, const DataLayout &DL,
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000295 const TargetLibraryInfo *TLI,
Victor Hernandezfcc77b12009-11-10 08:32:25 +0000296 bool LookThroughSExt) {
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000297 assert(isMallocLikeFn(CI, TLI) && "getMallocArraySize and not malloc call");
Matt Arsenault40dddd72013-10-03 19:50:01 +0000298 return computeArraySize(CI, DL, TLI, LookThroughSExt);
Evan Cheng1d9d4bd2009-09-10 04:36:43 +0000299}
Victor Hernandeze2971492009-10-24 04:23:03 +0000300
Nuno Lopesd2b71e72012-05-03 21:19:58 +0000301
Nuno Lopesd2b71e72012-05-03 21:19:58 +0000302/// extractCallocCall - Returns the corresponding CallInst if the instruction
303/// is a calloc call.
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000304const CallInst *llvm::extractCallocCall(const Value *I,
305 const TargetLibraryInfo *TLI) {
Craig Topper9f008862014-04-15 04:59:12 +0000306 return isCallocLikeFn(I, TLI) ? cast<CallInst>(I) : nullptr;
Nuno Lopesd2b71e72012-05-03 21:19:58 +0000307}
308
Victor Hernandezde5ad422009-10-26 23:43:48 +0000309
Gabor Greif5f5a8642010-06-23 21:51:12 +0000310/// isFreeCall - Returns non-null if the value is a call to the builtin free()
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000311const CallInst *llvm::isFreeCall(const Value *I, const TargetLibraryInfo *TLI) {
Victor Hernandeze2971492009-10-24 04:23:03 +0000312 const CallInst *CI = dyn_cast<CallInst>(I);
Michael Ilseman74ffc272013-03-08 21:15:00 +0000313 if (!CI || isa<IntrinsicInst>(CI))
Craig Topper9f008862014-04-15 04:59:12 +0000314 return nullptr;
Victor Hernandez33188582009-11-03 20:39:35 +0000315 Function *Callee = CI->getCalledFunction();
Richard Smithe78bb122015-01-15 01:00:33 +0000316 if (Callee == nullptr)
Craig Topper9f008862014-04-15 04:59:12 +0000317 return nullptr;
Nick Lewyckyc1f86582011-03-15 07:31:32 +0000318
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000319 StringRef FnName = Callee->getName();
320 LibFunc::Func TLIFn;
321 if (!TLI || !TLI->getLibFunc(FnName, TLIFn) || !TLI->has(TLIFn))
Craig Topper9f008862014-04-15 04:59:12 +0000322 return nullptr;
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000323
Richard Smith70523c72013-07-21 23:11:42 +0000324 unsigned ExpectedNumParams;
325 if (TLIFn == LibFunc::free ||
326 TLIFn == LibFunc::ZdlPv || // operator delete(void*)
David Majnemerf6665f62015-12-03 22:45:19 +0000327 TLIFn == LibFunc::ZdaPv || // operator delete[](void*)
328 TLIFn == LibFunc::msvc_delete_ptr32 || // operator delete(void*)
329 TLIFn == LibFunc::msvc_delete_ptr64 || // operator delete(void*)
330 TLIFn == LibFunc::msvc_delete_array_ptr32 || // operator delete[](void*)
331 TLIFn == LibFunc::msvc_delete_array_ptr64) // operator delete[](void*)
Richard Smith70523c72013-07-21 23:11:42 +0000332 ExpectedNumParams = 1;
Richard Smith1ed42292014-10-03 20:17:06 +0000333 else if (TLIFn == LibFunc::ZdlPvj || // delete(void*, uint)
334 TLIFn == LibFunc::ZdlPvm || // delete(void*, ulong)
335 TLIFn == LibFunc::ZdlPvRKSt9nothrow_t || // delete(void*, nothrow)
336 TLIFn == LibFunc::ZdaPvj || // delete[](void*, uint)
337 TLIFn == LibFunc::ZdaPvm || // delete[](void*, ulong)
David Majnemerf6665f62015-12-03 22:45:19 +0000338 TLIFn == LibFunc::ZdaPvRKSt9nothrow_t || // delete[](void*, nothrow)
339 TLIFn == LibFunc::msvc_delete_ptr32_int || // delete(void*, uint)
340 TLIFn == LibFunc::msvc_delete_ptr64_longlong || // delete(void*, ulonglong)
341 TLIFn == LibFunc::msvc_delete_ptr32_nothrow || // delete(void*, nothrow)
342 TLIFn == LibFunc::msvc_delete_ptr64_nothrow || // delete(void*, nothrow)
343 TLIFn == LibFunc::msvc_delete_array_ptr32_int || // delete[](void*, uint)
344 TLIFn == LibFunc::msvc_delete_array_ptr64_longlong || // delete[](void*, ulonglong)
345 TLIFn == LibFunc::msvc_delete_array_ptr32_nothrow || // delete[](void*, nothrow)
346 TLIFn == LibFunc::msvc_delete_array_ptr64_nothrow) // delete[](void*, nothrow)
Richard Smith70523c72013-07-21 23:11:42 +0000347 ExpectedNumParams = 2;
348 else
Craig Topper9f008862014-04-15 04:59:12 +0000349 return nullptr;
Victor Hernandeze2971492009-10-24 04:23:03 +0000350
351 // Check free prototype.
Michael Ilsemand9745242013-03-08 21:03:09 +0000352 // FIXME: workaround for PR5130, this will be obsolete when a nobuiltin
Victor Hernandeze2971492009-10-24 04:23:03 +0000353 // attribute will exist.
Chris Lattner229907c2011-07-18 04:54:35 +0000354 FunctionType *FTy = Callee->getFunctionType();
Victor Hernandez33188582009-11-03 20:39:35 +0000355 if (!FTy->getReturnType()->isVoidTy())
Craig Topper9f008862014-04-15 04:59:12 +0000356 return nullptr;
Richard Smith70523c72013-07-21 23:11:42 +0000357 if (FTy->getNumParams() != ExpectedNumParams)
Craig Topper9f008862014-04-15 04:59:12 +0000358 return nullptr;
Chris Lattner67733f62011-06-18 21:46:23 +0000359 if (FTy->getParamType(0) != Type::getInt8PtrTy(Callee->getContext()))
Craig Topper9f008862014-04-15 04:59:12 +0000360 return nullptr;
Victor Hernandeze2971492009-10-24 04:23:03 +0000361
Gabor Greif5f5a8642010-06-23 21:51:12 +0000362 return CI;
Victor Hernandeze2971492009-10-24 04:23:03 +0000363}
Nuno Lopes55fff832012-06-21 15:45:28 +0000364
365
366
367//===----------------------------------------------------------------------===//
368// Utility functions to compute size of objects.
369//
Petar Jovanovic644b8c12016-04-13 12:25:25 +0000370static APInt getSizeWithOverflow(const SizeOffsetType &Data) {
371 if (Data.second.isNegative() || Data.first.ult(Data.second))
372 return APInt(Data.first.getBitWidth(), 0);
373 return Data.first - Data.second;
374}
Nuno Lopes55fff832012-06-21 15:45:28 +0000375
376/// \brief Compute the size of the object pointed by Ptr. Returns true and the
377/// object size in Size if successful, and false otherwise.
378/// If RoundToAlign is true, then Size is rounded up to the aligment of allocas,
379/// byval arguments, and global variables.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000380bool llvm::getObjectSize(const Value *Ptr, uint64_t &Size, const DataLayout &DL,
Petar Jovanovic644b8c12016-04-13 12:25:25 +0000381 const TargetLibraryInfo *TLI, bool RoundToAlign,
382 llvm::ObjSizeMode Mode) {
383 ObjectSizeOffsetVisitor Visitor(DL, TLI, Ptr->getContext(),
384 RoundToAlign, Mode);
Nuno Lopes55fff832012-06-21 15:45:28 +0000385 SizeOffsetType Data = Visitor.compute(const_cast<Value*>(Ptr));
386 if (!Visitor.bothKnown(Data))
387 return false;
388
Petar Jovanovic644b8c12016-04-13 12:25:25 +0000389 Size = getSizeWithOverflow(Data).getZExtValue();
Nuno Lopes55fff832012-06-21 15:45:28 +0000390 return true;
391}
392
Nuno Lopes55fff832012-06-21 15:45:28 +0000393STATISTIC(ObjectVisitorArgument,
394 "Number of arguments with unsolved size and offset");
395STATISTIC(ObjectVisitorLoad,
396 "Number of load instructions with unsolved size and offset");
397
398
399APInt ObjectSizeOffsetVisitor::align(APInt Size, uint64_t Align) {
400 if (RoundToAlign && Align)
Rui Ueyamada00f2f2016-01-14 21:06:47 +0000401 return APInt(IntTyBits, alignTo(Size.getZExtValue(), Align));
Nuno Lopes55fff832012-06-21 15:45:28 +0000402 return Size;
403}
404
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000405ObjectSizeOffsetVisitor::ObjectSizeOffsetVisitor(const DataLayout &DL,
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000406 const TargetLibraryInfo *TLI,
Nuno Lopes55fff832012-06-21 15:45:28 +0000407 LLVMContext &Context,
Petar Jovanovic644b8c12016-04-13 12:25:25 +0000408 bool RoundToAlign,
409 ObjSizeMode Mode)
410 : DL(DL), TLI(TLI), RoundToAlign(RoundToAlign), Mode(Mode) {
Matt Arsenaultd3ee7af2013-12-14 00:27:48 +0000411 // Pointer size must be rechecked for each object visited since it could have
412 // a different address space.
Nuno Lopes55fff832012-06-21 15:45:28 +0000413}
414
415SizeOffsetType ObjectSizeOffsetVisitor::compute(Value *V) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000416 IntTyBits = DL.getPointerTypeSizeInBits(V->getType());
Matt Arsenaultd3ee7af2013-12-14 00:27:48 +0000417 Zero = APInt::getNullValue(IntTyBits);
418
Nuno Lopes55fff832012-06-21 15:45:28 +0000419 V = V->stripPointerCasts();
Nadav Rotemabcc64f2013-04-09 18:16:05 +0000420 if (Instruction *I = dyn_cast<Instruction>(V)) {
421 // If we have already seen this instruction, bail out. Cycles can happen in
422 // unreachable code after constant propagation.
David Blaikie70573dc2014-11-19 07:49:26 +0000423 if (!SeenInsts.insert(I).second)
Nadav Rotemabcc64f2013-04-09 18:16:05 +0000424 return unknown();
Nuno Lopesd896a402012-12-31 20:45:10 +0000425
Benjamin Kramer34764fe2012-08-17 19:26:41 +0000426 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
Nadav Rotemabcc64f2013-04-09 18:16:05 +0000427 return visitGEPOperator(*GEP);
428 return visit(*I);
Benjamin Kramer34764fe2012-08-17 19:26:41 +0000429 }
Nuno Lopes55fff832012-06-21 15:45:28 +0000430 if (Argument *A = dyn_cast<Argument>(V))
431 return visitArgument(*A);
432 if (ConstantPointerNull *P = dyn_cast<ConstantPointerNull>(V))
433 return visitConstantPointerNull(*P);
Nuno Lopese9d6dbf2012-12-31 16:23:48 +0000434 if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
435 return visitGlobalAlias(*GA);
Nuno Lopes55fff832012-06-21 15:45:28 +0000436 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
437 return visitGlobalVariable(*GV);
438 if (UndefValue *UV = dyn_cast<UndefValue>(V))
439 return visitUndefValue(*UV);
Benjamin Kramer34764fe2012-08-17 19:26:41 +0000440 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
Nuno Lopes55fff832012-06-21 15:45:28 +0000441 if (CE->getOpcode() == Instruction::IntToPtr)
442 return unknown(); // clueless
Nadav Rotemabcc64f2013-04-09 18:16:05 +0000443 if (CE->getOpcode() == Instruction::GetElementPtr)
444 return visitGEPOperator(cast<GEPOperator>(*CE));
Benjamin Kramer34764fe2012-08-17 19:26:41 +0000445 }
Nuno Lopes55fff832012-06-21 15:45:28 +0000446
447 DEBUG(dbgs() << "ObjectSizeOffsetVisitor::compute() unhandled value: " << *V
448 << '\n');
449 return unknown();
450}
451
452SizeOffsetType ObjectSizeOffsetVisitor::visitAllocaInst(AllocaInst &I) {
453 if (!I.getAllocatedType()->isSized())
454 return unknown();
455
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000456 APInt Size(IntTyBits, DL.getTypeAllocSize(I.getAllocatedType()));
Nuno Lopes55fff832012-06-21 15:45:28 +0000457 if (!I.isArrayAllocation())
458 return std::make_pair(align(Size, I.getAlignment()), Zero);
459
460 Value *ArraySize = I.getArraySize();
461 if (const ConstantInt *C = dyn_cast<ConstantInt>(ArraySize)) {
462 Size *= C->getValue().zextOrSelf(IntTyBits);
463 return std::make_pair(align(Size, I.getAlignment()), Zero);
464 }
465 return unknown();
466}
467
468SizeOffsetType ObjectSizeOffsetVisitor::visitArgument(Argument &A) {
469 // no interprocedural analysis is done at the moment
Reid Kleckner26af2ca2014-01-28 02:38:36 +0000470 if (!A.hasByValOrInAllocaAttr()) {
Nuno Lopes55fff832012-06-21 15:45:28 +0000471 ++ObjectVisitorArgument;
472 return unknown();
473 }
474 PointerType *PT = cast<PointerType>(A.getType());
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000475 APInt Size(IntTyBits, DL.getTypeAllocSize(PT->getElementType()));
Nuno Lopes55fff832012-06-21 15:45:28 +0000476 return std::make_pair(align(Size, A.getParamAlignment()), Zero);
477}
478
479SizeOffsetType ObjectSizeOffsetVisitor::visitCallSite(CallSite CS) {
George Burgess IV278199f2016-04-12 01:05:35 +0000480 Optional<AllocFnsTy> FnData =
481 getAllocationData(CS.getInstruction(), AnyAlloc, TLI);
Nuno Lopes55fff832012-06-21 15:45:28 +0000482 if (!FnData)
483 return unknown();
484
485 // handle strdup-like functions separately
486 if (FnData->AllocTy == StrDupLike) {
Nuno Lopes2a4b09c2012-07-24 16:28:13 +0000487 APInt Size(IntTyBits, GetStringLength(CS.getArgument(0)));
488 if (!Size)
489 return unknown();
490
491 // strndup limits strlen
492 if (FnData->FstParam > 0) {
George Burgess IV278199f2016-04-12 01:05:35 +0000493 ConstantInt *Arg =
494 dyn_cast<ConstantInt>(CS.getArgument(FnData->FstParam));
Nuno Lopes2a4b09c2012-07-24 16:28:13 +0000495 if (!Arg)
496 return unknown();
497
498 APInt MaxSize = Arg->getValue().zextOrSelf(IntTyBits);
499 if (Size.ugt(MaxSize))
500 Size = MaxSize + 1;
501 }
502 return std::make_pair(Size, Zero);
Nuno Lopes55fff832012-06-21 15:45:28 +0000503 }
504
505 ConstantInt *Arg = dyn_cast<ConstantInt>(CS.getArgument(FnData->FstParam));
506 if (!Arg)
507 return unknown();
508
George Burgess IV278199f2016-04-12 01:05:35 +0000509 // When we're compiling N-bit code, and the user uses parameters that are
510 // greater than N bits (e.g. uint64_t on a 32-bit build), we can run into
511 // trouble with APInt size issues. This function handles resizing + overflow
512 // checks for us.
513 auto CheckedZextOrTrunc = [&](APInt &I) {
514 // More bits than we can handle. Checking the bit width isn't necessary, but
515 // it's faster than checking active bits, and should give `false` in the
516 // vast majority of cases.
517 if (I.getBitWidth() > IntTyBits && I.getActiveBits() > IntTyBits)
518 return false;
519 if (I.getBitWidth() != IntTyBits)
520 I = I.zextOrTrunc(IntTyBits);
521 return true;
522 };
523
524 APInt Size = Arg->getValue();
525 if (!CheckedZextOrTrunc(Size))
526 return unknown();
527
Nuno Lopes55fff832012-06-21 15:45:28 +0000528 // size determined by just 1 parameter
Nuno Lopesf06b7312012-06-21 18:38:26 +0000529 if (FnData->SndParam < 0)
Nuno Lopes55fff832012-06-21 15:45:28 +0000530 return std::make_pair(Size, Zero);
531
532 Arg = dyn_cast<ConstantInt>(CS.getArgument(FnData->SndParam));
533 if (!Arg)
534 return unknown();
535
George Burgess IV278199f2016-04-12 01:05:35 +0000536 APInt NumElems = Arg->getValue();
537 if (!CheckedZextOrTrunc(NumElems))
538 return unknown();
539
540 bool Overflow;
541 Size = Size.umul_ov(NumElems, Overflow);
542 return Overflow ? unknown() : std::make_pair(Size, Zero);
Nuno Lopes55fff832012-06-21 15:45:28 +0000543
544 // TODO: handle more standard functions (+ wchar cousins):
Nuno Lopesf0626f22012-07-25 18:49:28 +0000545 // - strdup / strndup
Nuno Lopes55fff832012-06-21 15:45:28 +0000546 // - strcpy / strncpy
547 // - strcat / strncat
548 // - memcpy / memmove
Nuno Lopesf0626f22012-07-25 18:49:28 +0000549 // - strcat / strncat
Nuno Lopes55fff832012-06-21 15:45:28 +0000550 // - memset
551}
552
553SizeOffsetType
554ObjectSizeOffsetVisitor::visitConstantPointerNull(ConstantPointerNull&) {
555 return std::make_pair(Zero, Zero);
556}
557
558SizeOffsetType
Nuno Lopes181d67e2012-06-28 16:34:03 +0000559ObjectSizeOffsetVisitor::visitExtractElementInst(ExtractElementInst&) {
560 return unknown();
561}
562
563SizeOffsetType
Nuno Lopes55fff832012-06-21 15:45:28 +0000564ObjectSizeOffsetVisitor::visitExtractValueInst(ExtractValueInst&) {
565 // Easy cases were already folded by previous passes.
566 return unknown();
567}
568
569SizeOffsetType ObjectSizeOffsetVisitor::visitGEPOperator(GEPOperator &GEP) {
570 SizeOffsetType PtrData = compute(GEP.getPointerOperand());
Nuno Lopesb6ad9822012-12-30 16:25:48 +0000571 APInt Offset(IntTyBits, 0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000572 if (!bothKnown(PtrData) || !GEP.accumulateConstantOffset(DL, Offset))
Nuno Lopes55fff832012-06-21 15:45:28 +0000573 return unknown();
574
Nuno Lopes55fff832012-06-21 15:45:28 +0000575 return std::make_pair(PtrData.first, PtrData.second + Offset);
576}
577
Nuno Lopese9d6dbf2012-12-31 16:23:48 +0000578SizeOffsetType ObjectSizeOffsetVisitor::visitGlobalAlias(GlobalAlias &GA) {
Sanjoy Das5ce32722016-04-08 00:48:30 +0000579 if (GA.isInterposable())
Nuno Lopese9d6dbf2012-12-31 16:23:48 +0000580 return unknown();
581 return compute(GA.getAliasee());
582}
583
Nuno Lopes55fff832012-06-21 15:45:28 +0000584SizeOffsetType ObjectSizeOffsetVisitor::visitGlobalVariable(GlobalVariable &GV){
585 if (!GV.hasDefinitiveInitializer())
586 return unknown();
587
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000588 APInt Size(IntTyBits, DL.getTypeAllocSize(GV.getType()->getElementType()));
Nuno Lopes55fff832012-06-21 15:45:28 +0000589 return std::make_pair(align(Size, GV.getAlignment()), Zero);
590}
591
592SizeOffsetType ObjectSizeOffsetVisitor::visitIntToPtrInst(IntToPtrInst&) {
593 // clueless
594 return unknown();
595}
596
597SizeOffsetType ObjectSizeOffsetVisitor::visitLoadInst(LoadInst&) {
598 ++ObjectVisitorLoad;
599 return unknown();
600}
601
Nadav Rotemabcc64f2013-04-09 18:16:05 +0000602SizeOffsetType ObjectSizeOffsetVisitor::visitPHINode(PHINode&) {
603 // too complex to analyze statically.
604 return unknown();
Nuno Lopes55fff832012-06-21 15:45:28 +0000605}
606
607SizeOffsetType ObjectSizeOffsetVisitor::visitSelectInst(SelectInst &I) {
608 SizeOffsetType TrueSide = compute(I.getTrueValue());
609 SizeOffsetType FalseSide = compute(I.getFalseValue());
Petar Jovanovic644b8c12016-04-13 12:25:25 +0000610 if (bothKnown(TrueSide) && bothKnown(FalseSide)) {
611 if (TrueSide == FalseSide) {
612 return TrueSide;
613 }
614
615 APInt TrueResult = getSizeWithOverflow(TrueSide);
616 APInt FalseResult = getSizeWithOverflow(FalseSide);
617
618 if (TrueResult == FalseResult) {
619 return TrueSide;
620 }
621 if (Mode == ObjSizeMode::Min) {
622 if (TrueResult.slt(FalseResult))
623 return TrueSide;
624 return FalseSide;
625 }
626 if (Mode == ObjSizeMode::Max) {
627 if (TrueResult.sgt(FalseResult))
628 return TrueSide;
629 return FalseSide;
630 }
631 }
Nuno Lopes55fff832012-06-21 15:45:28 +0000632 return unknown();
633}
634
635SizeOffsetType ObjectSizeOffsetVisitor::visitUndefValue(UndefValue&) {
636 return std::make_pair(Zero, Zero);
637}
638
639SizeOffsetType ObjectSizeOffsetVisitor::visitInstruction(Instruction &I) {
640 DEBUG(dbgs() << "ObjectSizeOffsetVisitor unknown instruction:" << I << '\n');
641 return unknown();
642}
643
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000644ObjectSizeOffsetEvaluator::ObjectSizeOffsetEvaluator(
645 const DataLayout &DL, const TargetLibraryInfo *TLI, LLVMContext &Context,
646 bool RoundToAlign)
647 : DL(DL), TLI(TLI), Context(Context), Builder(Context, TargetFolder(DL)),
648 RoundToAlign(RoundToAlign) {
Matt Arsenaultd3ee7af2013-12-14 00:27:48 +0000649 // IntTy and Zero must be set for each compute() since the address space may
650 // be different for later objects.
Nuno Lopes55fff832012-06-21 15:45:28 +0000651}
652
653SizeOffsetEvalType ObjectSizeOffsetEvaluator::compute(Value *V) {
Matt Arsenaultd3ee7af2013-12-14 00:27:48 +0000654 // XXX - Are vectors of pointers possible here?
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000655 IntTy = cast<IntegerType>(DL.getIntPtrType(V->getType()));
Matt Arsenaultd3ee7af2013-12-14 00:27:48 +0000656 Zero = ConstantInt::get(IntTy, 0);
657
Nuno Lopes55fff832012-06-21 15:45:28 +0000658 SizeOffsetEvalType Result = compute_(V);
659
660 if (!bothKnown(Result)) {
661 // erase everything that was computed in this iteration from the cache, so
662 // that no dangling references are left behind. We could be a bit smarter if
663 // we kept a dependency graph. It's probably not worth the complexity.
664 for (PtrSetTy::iterator I=SeenVals.begin(), E=SeenVals.end(); I != E; ++I) {
665 CacheMapTy::iterator CacheIt = CacheMap.find(*I);
666 // non-computable results can be safely cached
667 if (CacheIt != CacheMap.end() && anyKnown(CacheIt->second))
668 CacheMap.erase(CacheIt);
669 }
670 }
671
672 SeenVals.clear();
673 return Result;
674}
675
676SizeOffsetEvalType ObjectSizeOffsetEvaluator::compute_(Value *V) {
Nuno Lopes340b0462013-10-24 09:17:24 +0000677 ObjectSizeOffsetVisitor Visitor(DL, TLI, Context, RoundToAlign);
Nuno Lopes55fff832012-06-21 15:45:28 +0000678 SizeOffsetType Const = Visitor.compute(V);
679 if (Visitor.bothKnown(Const))
680 return std::make_pair(ConstantInt::get(Context, Const.first),
681 ConstantInt::get(Context, Const.second));
682
683 V = V->stripPointerCasts();
684
685 // check cache
686 CacheMapTy::iterator CacheIt = CacheMap.find(V);
687 if (CacheIt != CacheMap.end())
688 return CacheIt->second;
689
690 // always generate code immediately before the instruction being
691 // processed, so that the generated code dominates the same BBs
Duncan P. N. Exon Smith5a82c912015-10-10 00:53:03 +0000692 BuilderTy::InsertPointGuard Guard(Builder);
Nuno Lopes55fff832012-06-21 15:45:28 +0000693 if (Instruction *I = dyn_cast<Instruction>(V))
694 Builder.SetInsertPoint(I);
695
Nuno Lopes55fff832012-06-21 15:45:28 +0000696 // now compute the size and offset
697 SizeOffsetEvalType Result;
Benjamin Kramer155c9d52013-09-29 19:39:13 +0000698
699 // Record the pointers that were handled in this run, so that they can be
700 // cleaned later if something fails. We also use this set to break cycles that
701 // can occur in dead code.
David Blaikie70573dc2014-11-19 07:49:26 +0000702 if (!SeenVals.insert(V).second) {
Benjamin Kramer155c9d52013-09-29 19:39:13 +0000703 Result = unknown();
704 } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
Nuno Lopes55fff832012-06-21 15:45:28 +0000705 Result = visitGEPOperator(*GEP);
706 } else if (Instruction *I = dyn_cast<Instruction>(V)) {
707 Result = visit(*I);
708 } else if (isa<Argument>(V) ||
709 (isa<ConstantExpr>(V) &&
710 cast<ConstantExpr>(V)->getOpcode() == Instruction::IntToPtr) ||
Nuno Lopese9d6dbf2012-12-31 16:23:48 +0000711 isa<GlobalAlias>(V) ||
Nuno Lopes55fff832012-06-21 15:45:28 +0000712 isa<GlobalVariable>(V)) {
713 // ignore values where we cannot do more than what ObjectSizeVisitor can
714 Result = unknown();
715 } else {
716 DEBUG(dbgs() << "ObjectSizeOffsetEvaluator::compute() unhandled value: "
717 << *V << '\n');
718 Result = unknown();
719 }
720
Nuno Lopes55fff832012-06-21 15:45:28 +0000721 // Don't reuse CacheIt since it may be invalid at this point.
722 CacheMap[V] = Result;
723 return Result;
724}
725
726SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitAllocaInst(AllocaInst &I) {
727 if (!I.getAllocatedType()->isSized())
728 return unknown();
729
730 // must be a VLA
731 assert(I.isArrayAllocation());
732 Value *ArraySize = I.getArraySize();
733 Value *Size = ConstantInt::get(ArraySize->getType(),
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000734 DL.getTypeAllocSize(I.getAllocatedType()));
Nuno Lopes55fff832012-06-21 15:45:28 +0000735 Size = Builder.CreateMul(Size, ArraySize);
736 return std::make_pair(Size, Zero);
737}
738
739SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitCallSite(CallSite CS) {
George Burgess IV278199f2016-04-12 01:05:35 +0000740 Optional<AllocFnsTy> FnData =
741 getAllocationData(CS.getInstruction(), AnyAlloc, TLI);
Nuno Lopes55fff832012-06-21 15:45:28 +0000742 if (!FnData)
743 return unknown();
744
745 // handle strdup-like functions separately
746 if (FnData->AllocTy == StrDupLike) {
Nuno Lopesf0626f22012-07-25 18:49:28 +0000747 // TODO
748 return unknown();
Nuno Lopes55fff832012-06-21 15:45:28 +0000749 }
750
Nuno Lopesa6aa3d32012-06-21 16:47:58 +0000751 Value *FirstArg = CS.getArgument(FnData->FstParam);
752 FirstArg = Builder.CreateZExt(FirstArg, IntTy);
Nuno Lopesf06b7312012-06-21 18:38:26 +0000753 if (FnData->SndParam < 0)
Nuno Lopes55fff832012-06-21 15:45:28 +0000754 return std::make_pair(FirstArg, Zero);
755
756 Value *SecondArg = CS.getArgument(FnData->SndParam);
Nuno Lopesa6aa3d32012-06-21 16:47:58 +0000757 SecondArg = Builder.CreateZExt(SecondArg, IntTy);
Nuno Lopes55fff832012-06-21 15:45:28 +0000758 Value *Size = Builder.CreateMul(FirstArg, SecondArg);
759 return std::make_pair(Size, Zero);
760
761 // TODO: handle more standard functions (+ wchar cousins):
Nuno Lopesf0626f22012-07-25 18:49:28 +0000762 // - strdup / strndup
Nuno Lopes55fff832012-06-21 15:45:28 +0000763 // - strcpy / strncpy
764 // - strcat / strncat
765 // - memcpy / memmove
Nuno Lopesf0626f22012-07-25 18:49:28 +0000766 // - strcat / strncat
Nuno Lopes55fff832012-06-21 15:45:28 +0000767 // - memset
768}
769
770SizeOffsetEvalType
Nuno Lopes181d67e2012-06-28 16:34:03 +0000771ObjectSizeOffsetEvaluator::visitExtractElementInst(ExtractElementInst&) {
772 return unknown();
773}
774
775SizeOffsetEvalType
776ObjectSizeOffsetEvaluator::visitExtractValueInst(ExtractValueInst&) {
777 return unknown();
778}
779
780SizeOffsetEvalType
Nuno Lopes55fff832012-06-21 15:45:28 +0000781ObjectSizeOffsetEvaluator::visitGEPOperator(GEPOperator &GEP) {
782 SizeOffsetEvalType PtrData = compute_(GEP.getPointerOperand());
783 if (!bothKnown(PtrData))
784 return unknown();
785
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000786 Value *Offset = EmitGEPOffset(&Builder, DL, &GEP, /*NoAssumptions=*/true);
Nuno Lopes55fff832012-06-21 15:45:28 +0000787 Offset = Builder.CreateAdd(PtrData.second, Offset);
788 return std::make_pair(PtrData.first, Offset);
789}
790
791SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitIntToPtrInst(IntToPtrInst&) {
792 // clueless
793 return unknown();
794}
795
796SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitLoadInst(LoadInst&) {
797 return unknown();
798}
799
800SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitPHINode(PHINode &PHI) {
801 // create 2 PHIs: one for size and another for offset
802 PHINode *SizePHI = Builder.CreatePHI(IntTy, PHI.getNumIncomingValues());
803 PHINode *OffsetPHI = Builder.CreatePHI(IntTy, PHI.getNumIncomingValues());
804
805 // insert right away in the cache to handle recursive PHIs
806 CacheMap[&PHI] = std::make_pair(SizePHI, OffsetPHI);
807
808 // compute offset/size for each PHI incoming pointer
809 for (unsigned i = 0, e = PHI.getNumIncomingValues(); i != e; ++i) {
Duncan P. N. Exon Smith5a82c912015-10-10 00:53:03 +0000810 Builder.SetInsertPoint(&*PHI.getIncomingBlock(i)->getFirstInsertionPt());
Nuno Lopes55fff832012-06-21 15:45:28 +0000811 SizeOffsetEvalType EdgeData = compute_(PHI.getIncomingValue(i));
812
813 if (!bothKnown(EdgeData)) {
814 OffsetPHI->replaceAllUsesWith(UndefValue::get(IntTy));
815 OffsetPHI->eraseFromParent();
816 SizePHI->replaceAllUsesWith(UndefValue::get(IntTy));
817 SizePHI->eraseFromParent();
818 return unknown();
819 }
820 SizePHI->addIncoming(EdgeData.first, PHI.getIncomingBlock(i));
821 OffsetPHI->addIncoming(EdgeData.second, PHI.getIncomingBlock(i));
822 }
Nuno Lopes9291ff42012-07-03 17:13:25 +0000823
824 Value *Size = SizePHI, *Offset = OffsetPHI, *Tmp;
825 if ((Tmp = SizePHI->hasConstantValue())) {
826 Size = Tmp;
827 SizePHI->replaceAllUsesWith(Size);
828 SizePHI->eraseFromParent();
829 }
830 if ((Tmp = OffsetPHI->hasConstantValue())) {
831 Offset = Tmp;
832 OffsetPHI->replaceAllUsesWith(Offset);
833 OffsetPHI->eraseFromParent();
834 }
835 return std::make_pair(Size, Offset);
Nuno Lopes55fff832012-06-21 15:45:28 +0000836}
837
838SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitSelectInst(SelectInst &I) {
839 SizeOffsetEvalType TrueSide = compute_(I.getTrueValue());
840 SizeOffsetEvalType FalseSide = compute_(I.getFalseValue());
841
842 if (!bothKnown(TrueSide) || !bothKnown(FalseSide))
843 return unknown();
844 if (TrueSide == FalseSide)
845 return TrueSide;
846
847 Value *Size = Builder.CreateSelect(I.getCondition(), TrueSide.first,
848 FalseSide.first);
849 Value *Offset = Builder.CreateSelect(I.getCondition(), TrueSide.second,
850 FalseSide.second);
851 return std::make_pair(Size, Offset);
852}
853
854SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitInstruction(Instruction &I) {
855 DEBUG(dbgs() << "ObjectSizeOffsetEvaluator unknown instruction:" << I <<'\n');
856 return unknown();
857}