blob: 21417781bd6ddff3c5d27f2b0bae3add16d0aaae [file] [log] [blame]
Victor Hernandezf006b182009-10-27 20:05:49 +00001//===------ MemoryBuiltins.cpp - Identify calls to memory builtins --------===//
Evan Chengfabcb912009-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 Hernandezf006b182009-10-27 20:05:49 +000010// This family of functions identifies calls to builtin functions that allocate
11// or free memory.
Evan Chengfabcb912009-09-10 04:36:43 +000012//
13//===----------------------------------------------------------------------===//
14
Nuno Lopes9e72a792012-06-21 15:45:28 +000015#define DEBUG_TYPE "memory-builtins"
16#include "llvm/ADT/Statistic.h"
17#include "llvm/ADT/STLExtras.h"
Victor Hernandezf006b182009-10-27 20:05:49 +000018#include "llvm/Analysis/MemoryBuiltins.h"
Nuno Lopes9e72a792012-06-21 15:45:28 +000019#include "llvm/GlobalVariable.h"
Evan Chengfabcb912009-09-10 04:36:43 +000020#include "llvm/Instructions.h"
Nuno Lopes9e72a792012-06-21 15:45:28 +000021#include "llvm/Intrinsics.h"
22#include "llvm/Metadata.h"
Evan Chengfabcb912009-09-10 04:36:43 +000023#include "llvm/Module.h"
Victor Hernandez8e345a12009-11-10 08:32:25 +000024#include "llvm/Analysis/ValueTracking.h"
Nuno Lopes9e72a792012-06-21 15:45:28 +000025#include "llvm/Support/Debug.h"
26#include "llvm/Support/MathExtras.h"
27#include "llvm/Support/raw_ostream.h"
Victor Hernandez9d0b7042009-11-07 00:16:28 +000028#include "llvm/Target/TargetData.h"
Nuno Lopese3094282012-07-25 17:29:22 +000029#include "llvm/Transforms/Utils/BuildLibCalls.h"
Nuno Lopes9e72a792012-06-21 15:45:28 +000030#include "llvm/Transforms/Utils/Local.h"
Evan Chengfabcb912009-09-10 04:36:43 +000031using namespace llvm;
32
Nuno Lopes9e72a792012-06-21 15:45:28 +000033enum AllocType {
34 MallocLike = 1<<0, // allocates
35 CallocLike = 1<<1, // allocates + bzero
36 ReallocLike = 1<<2, // reallocates
37 StrDupLike = 1<<3,
38 AllocLike = MallocLike | CallocLike | StrDupLike,
39 AnyAlloc = MallocLike | CallocLike | ReallocLike | StrDupLike
40};
Evan Chengfabcb912009-09-10 04:36:43 +000041
Nuno Lopes9e72a792012-06-21 15:45:28 +000042struct AllocFnsTy {
43 const char *Name;
44 AllocType AllocTy;
45 unsigned char NumParams;
46 // First and Second size parameters (or -1 if unused)
Nuno Lopesef22f042012-06-21 18:38:26 +000047 signed char FstParam, SndParam;
Nuno Lopes9e72a792012-06-21 15:45:28 +000048};
Evan Chengfabcb912009-09-10 04:36:43 +000049
Nuno Lopes41a3f252012-06-28 16:34:03 +000050// FIXME: certain users need more information. E.g., SimplifyLibCalls needs to
51// know which functions are nounwind, noalias, nocapture parameters, etc.
Nuno Lopes9e72a792012-06-21 15:45:28 +000052static const AllocFnsTy AllocationFnData[] = {
Nuno Lopes41a3f252012-06-28 16:34:03 +000053 {"malloc", MallocLike, 1, 0, -1},
54 {"valloc", MallocLike, 1, 0, -1},
55 {"_Znwj", MallocLike, 1, 0, -1}, // new(unsigned int)
56 {"_ZnwjRKSt9nothrow_t", MallocLike, 2, 0, -1}, // new(unsigned int, nothrow)
57 {"_Znwm", MallocLike, 1, 0, -1}, // new(unsigned long)
58 {"_ZnwmRKSt9nothrow_t", MallocLike, 2, 0, -1}, // new(unsigned long, nothrow)
59 {"_Znaj", MallocLike, 1, 0, -1}, // new[](unsigned int)
60 {"_ZnajRKSt9nothrow_t", MallocLike, 2, 0, -1}, // new[](unsigned int, nothrow)
61 {"_Znam", MallocLike, 1, 0, -1}, // new[](unsigned long)
62 {"_ZnamRKSt9nothrow_t", MallocLike, 2, 0, -1}, // new[](unsigned long, nothrow)
63 {"posix_memalign", MallocLike, 3, 2, -1},
64 {"calloc", CallocLike, 2, 0, 1},
65 {"realloc", ReallocLike, 2, 1, -1},
66 {"reallocf", ReallocLike, 2, 1, -1},
67 {"strdup", StrDupLike, 1, -1, -1},
Nuno Lopes9827c8e2012-07-24 16:28:13 +000068 {"strndup", StrDupLike, 2, 1, -1}
Nuno Lopes9e72a792012-06-21 15:45:28 +000069};
70
71
72static Function *getCalledFunction(const Value *V, bool LookThroughBitCast) {
73 if (LookThroughBitCast)
74 V = V->stripPointerCasts();
Nuno Lopes2b3e9582012-06-21 21:25:05 +000075
Nuno Lopesd845c342012-06-22 15:50:53 +000076 CallSite CS(const_cast<Value*>(V));
77 if (!CS.getInstruction())
Nuno Lopes9e72a792012-06-21 15:45:28 +000078 return 0;
Evan Chengfabcb912009-09-10 04:36:43 +000079
Nuno Lopes2b3e9582012-06-21 21:25:05 +000080 Function *Callee = CS.getCalledFunction();
Nuno Lopes9e72a792012-06-21 15:45:28 +000081 if (!Callee || !Callee->isDeclaration())
82 return 0;
83 return Callee;
84}
Evan Chengfabcb912009-09-10 04:36:43 +000085
Nuno Lopes9e72a792012-06-21 15:45:28 +000086/// \brief Returns the allocation data for the given value if it is a call to a
87/// known allocation function, and NULL otherwise.
88static const AllocFnsTy *getAllocationData(const Value *V, AllocType AllocTy,
89 bool LookThroughBitCast = false) {
90 Function *Callee = getCalledFunction(V, LookThroughBitCast);
91 if (!Callee)
92 return 0;
93
94 unsigned i = 0;
95 bool found = false;
96 for ( ; i < array_lengthof(AllocationFnData); ++i) {
97 if (Callee->getName() == AllocationFnData[i].Name) {
98 found = true;
99 break;
100 }
101 }
102 if (!found)
103 return 0;
104
105 const AllocFnsTy *FnData = &AllocationFnData[i];
106 if ((FnData->AllocTy & AllocTy) == 0)
107 return 0;
108
109 // Check function prototype.
110 // FIXME: Check the nobuiltin metadata?? (PR5130)
Nuno Lopesef22f042012-06-21 18:38:26 +0000111 int FstParam = FnData->FstParam;
112 int SndParam = FnData->SndParam;
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000113 FunctionType *FTy = Callee->getFunctionType();
Nuno Lopes9e72a792012-06-21 15:45:28 +0000114
115 if (FTy->getReturnType() == Type::getInt8PtrTy(FTy->getContext()) &&
116 FTy->getNumParams() == FnData->NumParams &&
Nuno Lopesef22f042012-06-21 18:38:26 +0000117 (FstParam < 0 ||
Nuno Lopes9e72a792012-06-21 15:45:28 +0000118 (FTy->getParamType(FstParam)->isIntegerTy(32) ||
119 FTy->getParamType(FstParam)->isIntegerTy(64))) &&
Nuno Lopesef22f042012-06-21 18:38:26 +0000120 (SndParam < 0 ||
Nuno Lopes9e72a792012-06-21 15:45:28 +0000121 FTy->getParamType(SndParam)->isIntegerTy(32) ||
122 FTy->getParamType(SndParam)->isIntegerTy(64)))
123 return FnData;
124 return 0;
125}
126
127static bool hasNoAliasAttr(const Value *V, bool LookThroughBitCast) {
Nuno Lopese8742d02012-06-25 16:17:54 +0000128 ImmutableCallSite CS(LookThroughBitCast ? V->stripPointerCasts() : V);
129 return CS && CS.hasFnAttr(Attribute::NoAlias);
Nuno Lopes9e72a792012-06-21 15:45:28 +0000130}
131
132
Nuno Lopes2b3e9582012-06-21 21:25:05 +0000133/// \brief Tests if a value is a call or invoke to a library function that
134/// allocates or reallocates memory (either malloc, calloc, realloc, or strdup
135/// like).
Nuno Lopes9e72a792012-06-21 15:45:28 +0000136bool llvm::isAllocationFn(const Value *V, bool LookThroughBitCast) {
137 return getAllocationData(V, AnyAlloc, LookThroughBitCast);
138}
139
Nuno Lopes2b3e9582012-06-21 21:25:05 +0000140/// \brief Tests if a value is a call or invoke to a function that returns a
Nuno Lopes41a3f252012-06-28 16:34:03 +0000141/// NoAlias pointer (including malloc/calloc/realloc/strdup-like functions).
Nuno Lopes9e72a792012-06-21 15:45:28 +0000142bool llvm::isNoAliasFn(const Value *V, bool LookThroughBitCast) {
Nuno Lopes41a3f252012-06-28 16:34:03 +0000143 // it's safe to consider realloc as noalias since accessing the original
144 // pointer is undefined behavior
145 return isAllocationFn(V, LookThroughBitCast) ||
Nuno Lopes9e72a792012-06-21 15:45:28 +0000146 hasNoAliasAttr(V, LookThroughBitCast);
147}
148
Nuno Lopes2b3e9582012-06-21 21:25:05 +0000149/// \brief Tests if a value is a call or invoke to a library function that
150/// allocates uninitialized memory (such as malloc).
Nuno Lopes9e72a792012-06-21 15:45:28 +0000151bool llvm::isMallocLikeFn(const Value *V, bool LookThroughBitCast) {
152 return getAllocationData(V, MallocLike, LookThroughBitCast);
153}
154
Nuno Lopes2b3e9582012-06-21 21:25:05 +0000155/// \brief Tests if a value is a call or invoke to a library function that
156/// allocates zero-filled memory (such as calloc).
Nuno Lopes9e72a792012-06-21 15:45:28 +0000157bool llvm::isCallocLikeFn(const Value *V, bool LookThroughBitCast) {
158 return getAllocationData(V, CallocLike, LookThroughBitCast);
159}
160
Nuno Lopes2b3e9582012-06-21 21:25:05 +0000161/// \brief Tests if a value is a call or invoke to a library function that
162/// allocates memory (either malloc, calloc, or strdup like).
Nuno Lopes9e72a792012-06-21 15:45:28 +0000163bool llvm::isAllocLikeFn(const Value *V, bool LookThroughBitCast) {
164 return getAllocationData(V, AllocLike, LookThroughBitCast);
165}
166
Nuno Lopes2b3e9582012-06-21 21:25:05 +0000167/// \brief Tests if a value is a call or invoke to a library function that
168/// reallocates memory (such as realloc).
Nuno Lopes9e72a792012-06-21 15:45:28 +0000169bool llvm::isReallocLikeFn(const Value *V, bool LookThroughBitCast) {
170 return getAllocationData(V, ReallocLike, LookThroughBitCast);
Evan Chengfabcb912009-09-10 04:36:43 +0000171}
172
173/// extractMallocCall - Returns the corresponding CallInst if the instruction
174/// is a malloc call. Since CallInst::CreateMalloc() only creates calls, we
175/// ignore InvokeInst here.
Victor Hernandez88efeae2009-11-03 20:02:35 +0000176const CallInst *llvm::extractMallocCall(const Value *I) {
Nuno Lopeseb7c6862012-06-22 00:25:01 +0000177 return isMallocLikeFn(I) ? dyn_cast<CallInst>(I) : 0;
Evan Chengfabcb912009-09-10 04:36:43 +0000178}
179
Victor Hernandez8e345a12009-11-10 08:32:25 +0000180static Value *computeArraySize(const CallInst *CI, const TargetData *TD,
181 bool LookThroughSExt = false) {
Evan Chengfabcb912009-09-10 04:36:43 +0000182 if (!CI)
Victor Hernandez90f48e72009-10-28 20:18:55 +0000183 return NULL;
Evan Chengfabcb912009-09-10 04:36:43 +0000184
Victor Hernandez9d0b7042009-11-07 00:16:28 +0000185 // The size of the malloc's result type must be known to determine array size.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000186 Type *T = getMallocAllocatedType(CI);
Victor Hernandez9d0b7042009-11-07 00:16:28 +0000187 if (!T || !T->isSized() || !TD)
Victor Hernandez90f48e72009-10-28 20:18:55 +0000188 return NULL;
Victor Hernandez88d98392009-09-18 19:20:02 +0000189
Victor Hernandez8e345a12009-11-10 08:32:25 +0000190 unsigned ElementSize = TD->getTypeAllocSize(T);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000191 if (StructType *ST = dyn_cast<StructType>(T))
Victor Hernandez8e345a12009-11-10 08:32:25 +0000192 ElementSize = TD->getStructLayout(ST)->getSizeInBytes();
Victor Hernandez88d98392009-09-18 19:20:02 +0000193
Gabor Greife3401c42010-06-23 21:41:47 +0000194 // If malloc call's arg can be determined to be a multiple of ElementSize,
Victor Hernandez8e345a12009-11-10 08:32:25 +0000195 // return the multiple. Otherwise, return NULL.
Gabor Greife3401c42010-06-23 21:41:47 +0000196 Value *MallocArg = CI->getArgOperand(0);
Victor Hernandez8e345a12009-11-10 08:32:25 +0000197 Value *Multiple = NULL;
Victor Hernandez8e345a12009-11-10 08:32:25 +0000198 if (ComputeMultiple(MallocArg, ElementSize, Multiple,
Dan Gohman3dbb9e62009-11-18 00:58:27 +0000199 LookThroughSExt))
Victor Hernandez8e345a12009-11-10 08:32:25 +0000200 return Multiple;
Victor Hernandez88d98392009-09-18 19:20:02 +0000201
Victor Hernandez90f48e72009-10-28 20:18:55 +0000202 return NULL;
Evan Chengfabcb912009-09-10 04:36:43 +0000203}
204
205/// isArrayMalloc - Returns the corresponding CallInst if the instruction
Victor Hernandez90f48e72009-10-28 20:18:55 +0000206/// is a call to malloc whose array size can be determined and the array size
207/// is not constant 1. Otherwise, return NULL.
Chris Lattner7b550cc2009-11-06 04:27:31 +0000208const CallInst *llvm::isArrayMalloc(const Value *I, const TargetData *TD) {
Evan Chengfabcb912009-09-10 04:36:43 +0000209 const CallInst *CI = extractMallocCall(I);
Victor Hernandez8e345a12009-11-10 08:32:25 +0000210 Value *ArraySize = computeArraySize(CI, TD);
Victor Hernandez90f48e72009-10-28 20:18:55 +0000211
212 if (ArraySize &&
Gabor Greife3401c42010-06-23 21:41:47 +0000213 ArraySize != ConstantInt::get(CI->getArgOperand(0)->getType(), 1))
Victor Hernandez90f48e72009-10-28 20:18:55 +0000214 return CI;
215
216 // CI is a non-array malloc or we can't figure out that it is an array malloc.
217 return NULL;
Evan Chengfabcb912009-09-10 04:36:43 +0000218}
219
220/// getMallocType - Returns the PointerType resulting from the malloc call.
Victor Hernandez9d0b7042009-11-07 00:16:28 +0000221/// The PointerType depends on the number of bitcast uses of the malloc call:
222/// 0: PointerType is the calls' return type.
223/// 1: PointerType is the bitcast's result type.
224/// >1: Unique PointerType cannot be determined, return NULL.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000225PointerType *llvm::getMallocType(const CallInst *CI) {
Nuno Lopes9e72a792012-06-21 15:45:28 +0000226 assert(isMallocLikeFn(CI) && "getMallocType and not malloc call");
Evan Chengfabcb912009-09-10 04:36:43 +0000227
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000228 PointerType *MallocType = NULL;
Victor Hernandez9d0b7042009-11-07 00:16:28 +0000229 unsigned NumOfBitCastUses = 0;
230
Victor Hernandez88d98392009-09-18 19:20:02 +0000231 // Determine if CallInst has a bitcast use.
Gabor Greif60ad7812010-03-25 23:06:16 +0000232 for (Value::const_use_iterator UI = CI->use_begin(), E = CI->use_end();
Victor Hernandez88d98392009-09-18 19:20:02 +0000233 UI != E; )
Victor Hernandez9d0b7042009-11-07 00:16:28 +0000234 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(*UI++)) {
235 MallocType = cast<PointerType>(BCI->getDestTy());
236 NumOfBitCastUses++;
237 }
Evan Chengfabcb912009-09-10 04:36:43 +0000238
Victor Hernandez9d0b7042009-11-07 00:16:28 +0000239 // Malloc call has 1 bitcast use, so type is the bitcast's destination type.
240 if (NumOfBitCastUses == 1)
241 return MallocType;
Evan Chengfabcb912009-09-10 04:36:43 +0000242
Victor Hernandez60cfc032009-09-22 18:50:03 +0000243 // Malloc call was not bitcast, so type is the malloc function's return type.
Victor Hernandez9d0b7042009-11-07 00:16:28 +0000244 if (NumOfBitCastUses == 0)
Victor Hernandez88d98392009-09-18 19:20:02 +0000245 return cast<PointerType>(CI->getType());
246
247 // Type could not be determined.
248 return NULL;
Evan Chengfabcb912009-09-10 04:36:43 +0000249}
250
Victor Hernandez9d0b7042009-11-07 00:16:28 +0000251/// getMallocAllocatedType - Returns the Type allocated by malloc call.
252/// The Type depends on the number of bitcast uses of the malloc call:
253/// 0: PointerType is the malloc calls' return type.
254/// 1: PointerType is the bitcast's result type.
255/// >1: Unique PointerType cannot be determined, return NULL.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000256Type *llvm::getMallocAllocatedType(const CallInst *CI) {
257 PointerType *PT = getMallocType(CI);
Evan Chengfabcb912009-09-10 04:36:43 +0000258 return PT ? PT->getElementType() : NULL;
259}
260
Victor Hernandez90f48e72009-10-28 20:18:55 +0000261/// getMallocArraySize - Returns the array size of a malloc call. If the
262/// argument passed to malloc is a multiple of the size of the malloced type,
263/// then return that multiple. For non-array mallocs, the multiple is
264/// constant 1. Otherwise, return NULL for mallocs whose array size cannot be
Victor Hernandez2491ce02009-10-15 20:14:52 +0000265/// determined.
Victor Hernandez8e345a12009-11-10 08:32:25 +0000266Value *llvm::getMallocArraySize(CallInst *CI, const TargetData *TD,
267 bool LookThroughSExt) {
Nuno Lopes9e72a792012-06-21 15:45:28 +0000268 assert(isMallocLikeFn(CI) && "getMallocArraySize and not malloc call");
Victor Hernandez8e345a12009-11-10 08:32:25 +0000269 return computeArraySize(CI, TD, LookThroughSExt);
Evan Chengfabcb912009-09-10 04:36:43 +0000270}
Victor Hernandez66284e02009-10-24 04:23:03 +0000271
Nuno Lopes252ef562012-05-03 21:19:58 +0000272
Nuno Lopes252ef562012-05-03 21:19:58 +0000273/// extractCallocCall - Returns the corresponding CallInst if the instruction
274/// is a calloc call.
275const CallInst *llvm::extractCallocCall(const Value *I) {
Nuno Lopes9e72a792012-06-21 15:45:28 +0000276 return isCallocLikeFn(I) ? cast<CallInst>(I) : 0;
Nuno Lopes252ef562012-05-03 21:19:58 +0000277}
278
Victor Hernandez046e78c2009-10-26 23:43:48 +0000279
Gabor Greif02680f92010-06-23 21:51:12 +0000280/// isFreeCall - Returns non-null if the value is a call to the builtin free()
281const CallInst *llvm::isFreeCall(const Value *I) {
Victor Hernandez66284e02009-10-24 04:23:03 +0000282 const CallInst *CI = dyn_cast<CallInst>(I);
283 if (!CI)
Gabor Greif02680f92010-06-23 21:51:12 +0000284 return 0;
Victor Hernandez3ad70d52009-11-03 20:39:35 +0000285 Function *Callee = CI->getCalledFunction();
Nick Lewycky42e72ca2011-03-15 07:31:32 +0000286 if (Callee == 0 || !Callee->isDeclaration())
287 return 0;
288
289 if (Callee->getName() != "free" &&
Nick Lewycky1ace1692011-03-17 05:20:12 +0000290 Callee->getName() != "_ZdlPv" && // operator delete(void*)
291 Callee->getName() != "_ZdaPv") // operator delete[](void*)
Gabor Greif02680f92010-06-23 21:51:12 +0000292 return 0;
Victor Hernandez66284e02009-10-24 04:23:03 +0000293
294 // Check free prototype.
295 // FIXME: workaround for PR5130, this will be obsolete when a nobuiltin
296 // attribute will exist.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000297 FunctionType *FTy = Callee->getFunctionType();
Victor Hernandez3ad70d52009-11-03 20:39:35 +0000298 if (!FTy->getReturnType()->isVoidTy())
Gabor Greif02680f92010-06-23 21:51:12 +0000299 return 0;
Victor Hernandez66284e02009-10-24 04:23:03 +0000300 if (FTy->getNumParams() != 1)
Gabor Greif02680f92010-06-23 21:51:12 +0000301 return 0;
Chris Lattnerebb21892011-06-18 21:46:23 +0000302 if (FTy->getParamType(0) != Type::getInt8PtrTy(Callee->getContext()))
Gabor Greif02680f92010-06-23 21:51:12 +0000303 return 0;
Victor Hernandez66284e02009-10-24 04:23:03 +0000304
Gabor Greif02680f92010-06-23 21:51:12 +0000305 return CI;
Victor Hernandez66284e02009-10-24 04:23:03 +0000306}
Nuno Lopes9e72a792012-06-21 15:45:28 +0000307
308
309
310//===----------------------------------------------------------------------===//
311// Utility functions to compute size of objects.
312//
313
314
315/// \brief Compute the size of the object pointed by Ptr. Returns true and the
316/// object size in Size if successful, and false otherwise.
317/// If RoundToAlign is true, then Size is rounded up to the aligment of allocas,
318/// byval arguments, and global variables.
319bool llvm::getObjectSize(const Value *Ptr, uint64_t &Size, const TargetData *TD,
320 bool RoundToAlign) {
321 if (!TD)
322 return false;
323
324 ObjectSizeOffsetVisitor Visitor(TD, Ptr->getContext(), RoundToAlign);
325 SizeOffsetType Data = Visitor.compute(const_cast<Value*>(Ptr));
326 if (!Visitor.bothKnown(Data))
327 return false;
328
329 APInt ObjSize = Data.first, Offset = Data.second;
330 // check for overflow
331 if (Offset.slt(0) || ObjSize.ult(Offset))
332 Size = 0;
333 else
334 Size = (ObjSize - Offset).getZExtValue();
335 return true;
336}
337
338
339STATISTIC(ObjectVisitorArgument,
340 "Number of arguments with unsolved size and offset");
341STATISTIC(ObjectVisitorLoad,
342 "Number of load instructions with unsolved size and offset");
343
344
345APInt ObjectSizeOffsetVisitor::align(APInt Size, uint64_t Align) {
346 if (RoundToAlign && Align)
347 return APInt(IntTyBits, RoundUpToAlignment(Size.getZExtValue(), Align));
348 return Size;
349}
350
351ObjectSizeOffsetVisitor::ObjectSizeOffsetVisitor(const TargetData *TD,
352 LLVMContext &Context,
353 bool RoundToAlign)
354: TD(TD), RoundToAlign(RoundToAlign) {
355 IntegerType *IntTy = TD->getIntPtrType(Context);
356 IntTyBits = IntTy->getBitWidth();
357 Zero = APInt::getNullValue(IntTyBits);
358}
359
360SizeOffsetType ObjectSizeOffsetVisitor::compute(Value *V) {
361 V = V->stripPointerCasts();
362
363 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
364 return visitGEPOperator(*GEP);
365 if (Instruction *I = dyn_cast<Instruction>(V))
366 return visit(*I);
367 if (Argument *A = dyn_cast<Argument>(V))
368 return visitArgument(*A);
369 if (ConstantPointerNull *P = dyn_cast<ConstantPointerNull>(V))
370 return visitConstantPointerNull(*P);
371 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
372 return visitGlobalVariable(*GV);
373 if (UndefValue *UV = dyn_cast<UndefValue>(V))
374 return visitUndefValue(*UV);
375 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
376 if (CE->getOpcode() == Instruction::IntToPtr)
377 return unknown(); // clueless
378
379 DEBUG(dbgs() << "ObjectSizeOffsetVisitor::compute() unhandled value: " << *V
380 << '\n');
381 return unknown();
382}
383
384SizeOffsetType ObjectSizeOffsetVisitor::visitAllocaInst(AllocaInst &I) {
385 if (!I.getAllocatedType()->isSized())
386 return unknown();
387
388 APInt Size(IntTyBits, TD->getTypeAllocSize(I.getAllocatedType()));
389 if (!I.isArrayAllocation())
390 return std::make_pair(align(Size, I.getAlignment()), Zero);
391
392 Value *ArraySize = I.getArraySize();
393 if (const ConstantInt *C = dyn_cast<ConstantInt>(ArraySize)) {
394 Size *= C->getValue().zextOrSelf(IntTyBits);
395 return std::make_pair(align(Size, I.getAlignment()), Zero);
396 }
397 return unknown();
398}
399
400SizeOffsetType ObjectSizeOffsetVisitor::visitArgument(Argument &A) {
401 // no interprocedural analysis is done at the moment
402 if (!A.hasByValAttr()) {
403 ++ObjectVisitorArgument;
404 return unknown();
405 }
406 PointerType *PT = cast<PointerType>(A.getType());
407 APInt Size(IntTyBits, TD->getTypeAllocSize(PT->getElementType()));
408 return std::make_pair(align(Size, A.getParamAlignment()), Zero);
409}
410
411SizeOffsetType ObjectSizeOffsetVisitor::visitCallSite(CallSite CS) {
412 const AllocFnsTy *FnData = getAllocationData(CS.getInstruction(), AnyAlloc);
413 if (!FnData)
414 return unknown();
415
416 // handle strdup-like functions separately
417 if (FnData->AllocTy == StrDupLike) {
Nuno Lopes9827c8e2012-07-24 16:28:13 +0000418 APInt Size(IntTyBits, GetStringLength(CS.getArgument(0)));
419 if (!Size)
420 return unknown();
421
422 // strndup limits strlen
423 if (FnData->FstParam > 0) {
424 ConstantInt *Arg= dyn_cast<ConstantInt>(CS.getArgument(FnData->FstParam));
425 if (!Arg)
426 return unknown();
427
428 APInt MaxSize = Arg->getValue().zextOrSelf(IntTyBits);
429 if (Size.ugt(MaxSize))
430 Size = MaxSize + 1;
431 }
432 return std::make_pair(Size, Zero);
Nuno Lopes9e72a792012-06-21 15:45:28 +0000433 }
434
435 ConstantInt *Arg = dyn_cast<ConstantInt>(CS.getArgument(FnData->FstParam));
436 if (!Arg)
437 return unknown();
438
Nuno Lopes034dd6c2012-06-21 16:47:58 +0000439 APInt Size = Arg->getValue().zextOrSelf(IntTyBits);
Nuno Lopes9e72a792012-06-21 15:45:28 +0000440 // size determined by just 1 parameter
Nuno Lopesef22f042012-06-21 18:38:26 +0000441 if (FnData->SndParam < 0)
Nuno Lopes9e72a792012-06-21 15:45:28 +0000442 return std::make_pair(Size, Zero);
443
444 Arg = dyn_cast<ConstantInt>(CS.getArgument(FnData->SndParam));
445 if (!Arg)
446 return unknown();
447
Nuno Lopes034dd6c2012-06-21 16:47:58 +0000448 Size *= Arg->getValue().zextOrSelf(IntTyBits);
Nuno Lopes9e72a792012-06-21 15:45:28 +0000449 return std::make_pair(Size, Zero);
450
451 // TODO: handle more standard functions (+ wchar cousins):
Nuno Lopes9e72a792012-06-21 15:45:28 +0000452 // - strcpy / strncpy
453 // - strcat / strncat
454 // - memcpy / memmove
Nuno Lopes9e72a792012-06-21 15:45:28 +0000455 // - memset
456}
457
458SizeOffsetType
459ObjectSizeOffsetVisitor::visitConstantPointerNull(ConstantPointerNull&) {
460 return std::make_pair(Zero, Zero);
461}
462
463SizeOffsetType
Nuno Lopes41a3f252012-06-28 16:34:03 +0000464ObjectSizeOffsetVisitor::visitExtractElementInst(ExtractElementInst&) {
465 return unknown();
466}
467
468SizeOffsetType
Nuno Lopes9e72a792012-06-21 15:45:28 +0000469ObjectSizeOffsetVisitor::visitExtractValueInst(ExtractValueInst&) {
470 // Easy cases were already folded by previous passes.
471 return unknown();
472}
473
474SizeOffsetType ObjectSizeOffsetVisitor::visitGEPOperator(GEPOperator &GEP) {
475 SizeOffsetType PtrData = compute(GEP.getPointerOperand());
476 if (!bothKnown(PtrData) || !GEP.hasAllConstantIndices())
477 return unknown();
478
479 SmallVector<Value*, 8> Ops(GEP.idx_begin(), GEP.idx_end());
480 APInt Offset(IntTyBits,TD->getIndexedOffset(GEP.getPointerOperandType(),Ops));
481 return std::make_pair(PtrData.first, PtrData.second + Offset);
482}
483
484SizeOffsetType ObjectSizeOffsetVisitor::visitGlobalVariable(GlobalVariable &GV){
485 if (!GV.hasDefinitiveInitializer())
486 return unknown();
487
488 APInt Size(IntTyBits, TD->getTypeAllocSize(GV.getType()->getElementType()));
489 return std::make_pair(align(Size, GV.getAlignment()), Zero);
490}
491
492SizeOffsetType ObjectSizeOffsetVisitor::visitIntToPtrInst(IntToPtrInst&) {
493 // clueless
494 return unknown();
495}
496
497SizeOffsetType ObjectSizeOffsetVisitor::visitLoadInst(LoadInst&) {
498 ++ObjectVisitorLoad;
499 return unknown();
500}
501
502SizeOffsetType ObjectSizeOffsetVisitor::visitPHINode(PHINode&) {
503 // too complex to analyze statically.
504 return unknown();
505}
506
507SizeOffsetType ObjectSizeOffsetVisitor::visitSelectInst(SelectInst &I) {
508 SizeOffsetType TrueSide = compute(I.getTrueValue());
509 SizeOffsetType FalseSide = compute(I.getFalseValue());
510 if (bothKnown(TrueSide) && bothKnown(FalseSide) && TrueSide == FalseSide)
511 return TrueSide;
512 return unknown();
513}
514
515SizeOffsetType ObjectSizeOffsetVisitor::visitUndefValue(UndefValue&) {
516 return std::make_pair(Zero, Zero);
517}
518
519SizeOffsetType ObjectSizeOffsetVisitor::visitInstruction(Instruction &I) {
520 DEBUG(dbgs() << "ObjectSizeOffsetVisitor unknown instruction:" << I << '\n');
521 return unknown();
522}
523
524
525ObjectSizeOffsetEvaluator::ObjectSizeOffsetEvaluator(const TargetData *TD,
Nuno Lopese3094282012-07-25 17:29:22 +0000526 const TargetLibraryInfo *TLI,
Nuno Lopes9e72a792012-06-21 15:45:28 +0000527 LLVMContext &Context)
Nuno Lopese3094282012-07-25 17:29:22 +0000528: TD(TD), TLI(TLI), Context(Context), Builder(Context, TargetFolder(TD)),
Nuno Lopes9e72a792012-06-21 15:45:28 +0000529Visitor(TD, Context) {
530 IntTy = TD->getIntPtrType(Context);
531 Zero = ConstantInt::get(IntTy, 0);
532}
533
534SizeOffsetEvalType ObjectSizeOffsetEvaluator::compute(Value *V) {
535 SizeOffsetEvalType Result = compute_(V);
536
537 if (!bothKnown(Result)) {
538 // erase everything that was computed in this iteration from the cache, so
539 // that no dangling references are left behind. We could be a bit smarter if
540 // we kept a dependency graph. It's probably not worth the complexity.
541 for (PtrSetTy::iterator I=SeenVals.begin(), E=SeenVals.end(); I != E; ++I) {
542 CacheMapTy::iterator CacheIt = CacheMap.find(*I);
543 // non-computable results can be safely cached
544 if (CacheIt != CacheMap.end() && anyKnown(CacheIt->second))
545 CacheMap.erase(CacheIt);
546 }
547 }
548
549 SeenVals.clear();
550 return Result;
551}
552
553SizeOffsetEvalType ObjectSizeOffsetEvaluator::compute_(Value *V) {
554 SizeOffsetType Const = Visitor.compute(V);
555 if (Visitor.bothKnown(Const))
556 return std::make_pair(ConstantInt::get(Context, Const.first),
557 ConstantInt::get(Context, Const.second));
558
559 V = V->stripPointerCasts();
560
561 // check cache
562 CacheMapTy::iterator CacheIt = CacheMap.find(V);
563 if (CacheIt != CacheMap.end())
564 return CacheIt->second;
565
566 // always generate code immediately before the instruction being
567 // processed, so that the generated code dominates the same BBs
568 Instruction *PrevInsertPoint = Builder.GetInsertPoint();
569 if (Instruction *I = dyn_cast<Instruction>(V))
570 Builder.SetInsertPoint(I);
571
572 // record the pointers that were handled in this run, so that they can be
573 // cleaned later if something fails
574 SeenVals.insert(V);
575
576 // now compute the size and offset
577 SizeOffsetEvalType Result;
578 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
579 Result = visitGEPOperator(*GEP);
580 } else if (Instruction *I = dyn_cast<Instruction>(V)) {
581 Result = visit(*I);
582 } else if (isa<Argument>(V) ||
583 (isa<ConstantExpr>(V) &&
584 cast<ConstantExpr>(V)->getOpcode() == Instruction::IntToPtr) ||
585 isa<GlobalVariable>(V)) {
586 // ignore values where we cannot do more than what ObjectSizeVisitor can
587 Result = unknown();
588 } else {
589 DEBUG(dbgs() << "ObjectSizeOffsetEvaluator::compute() unhandled value: "
590 << *V << '\n');
591 Result = unknown();
592 }
593
594 if (PrevInsertPoint)
595 Builder.SetInsertPoint(PrevInsertPoint);
596
597 // Don't reuse CacheIt since it may be invalid at this point.
598 CacheMap[V] = Result;
599 return Result;
600}
601
602SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitAllocaInst(AllocaInst &I) {
603 if (!I.getAllocatedType()->isSized())
604 return unknown();
605
606 // must be a VLA
607 assert(I.isArrayAllocation());
608 Value *ArraySize = I.getArraySize();
609 Value *Size = ConstantInt::get(ArraySize->getType(),
610 TD->getTypeAllocSize(I.getAllocatedType()));
611 Size = Builder.CreateMul(Size, ArraySize);
612 return std::make_pair(Size, Zero);
613}
614
615SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitCallSite(CallSite CS) {
616 const AllocFnsTy *FnData = getAllocationData(CS.getInstruction(), AnyAlloc);
617 if (!FnData)
618 return unknown();
619
620 // handle strdup-like functions separately
621 if (FnData->AllocTy == StrDupLike) {
Nuno Lopese3094282012-07-25 17:29:22 +0000622 IRBuilder<> StdBuilder(Builder.GetInsertPoint());
623 Value *Size;
624
625 // strdup(str): size = strlen(str)+1
626 if (FnData->FstParam < 0)
627 Size = EmitStrLen(CS.getArgument(0), StdBuilder, TD, TLI);
628 else
629 // strndup(str, maxlen): size = strnlen(str, maxlen)+1
630 Size = EmitStrNLen(CS.getArgument(0), CS.getArgument(FnData->FstParam),
631 StdBuilder, TD, TLI);
632 if (!Size)
633 return unknown();
634 Builder.SetInsertPoint(StdBuilder.GetInsertPoint());
635 Size = Builder.CreateNUWAdd(Size, ConstantInt::get(IntTy, 1));
636 return std::make_pair(Size, Zero);
Nuno Lopes9e72a792012-06-21 15:45:28 +0000637 }
638
Nuno Lopes034dd6c2012-06-21 16:47:58 +0000639 Value *FirstArg = CS.getArgument(FnData->FstParam);
640 FirstArg = Builder.CreateZExt(FirstArg, IntTy);
Nuno Lopesef22f042012-06-21 18:38:26 +0000641 if (FnData->SndParam < 0)
Nuno Lopes9e72a792012-06-21 15:45:28 +0000642 return std::make_pair(FirstArg, Zero);
643
644 Value *SecondArg = CS.getArgument(FnData->SndParam);
Nuno Lopes034dd6c2012-06-21 16:47:58 +0000645 SecondArg = Builder.CreateZExt(SecondArg, IntTy);
Nuno Lopes9e72a792012-06-21 15:45:28 +0000646 Value *Size = Builder.CreateMul(FirstArg, SecondArg);
647 return std::make_pair(Size, Zero);
648
649 // TODO: handle more standard functions (+ wchar cousins):
Nuno Lopes9e72a792012-06-21 15:45:28 +0000650 // - strcpy / strncpy
651 // - strcat / strncat
652 // - memcpy / memmove
Nuno Lopes9e72a792012-06-21 15:45:28 +0000653 // - memset
654}
655
656SizeOffsetEvalType
Nuno Lopes41a3f252012-06-28 16:34:03 +0000657ObjectSizeOffsetEvaluator::visitExtractElementInst(ExtractElementInst&) {
658 return unknown();
659}
660
661SizeOffsetEvalType
662ObjectSizeOffsetEvaluator::visitExtractValueInst(ExtractValueInst&) {
663 return unknown();
664}
665
666SizeOffsetEvalType
Nuno Lopes9e72a792012-06-21 15:45:28 +0000667ObjectSizeOffsetEvaluator::visitGEPOperator(GEPOperator &GEP) {
668 SizeOffsetEvalType PtrData = compute_(GEP.getPointerOperand());
669 if (!bothKnown(PtrData))
670 return unknown();
671
Nuno Lopesc606c3f2012-07-20 23:07:40 +0000672 Value *Offset = EmitGEPOffset(&Builder, *TD, &GEP, /*NoAssumptions=*/true);
Nuno Lopes9e72a792012-06-21 15:45:28 +0000673 Offset = Builder.CreateAdd(PtrData.second, Offset);
674 return std::make_pair(PtrData.first, Offset);
675}
676
677SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitIntToPtrInst(IntToPtrInst&) {
678 // clueless
679 return unknown();
680}
681
682SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitLoadInst(LoadInst&) {
683 return unknown();
684}
685
686SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitPHINode(PHINode &PHI) {
687 // create 2 PHIs: one for size and another for offset
688 PHINode *SizePHI = Builder.CreatePHI(IntTy, PHI.getNumIncomingValues());
689 PHINode *OffsetPHI = Builder.CreatePHI(IntTy, PHI.getNumIncomingValues());
690
691 // insert right away in the cache to handle recursive PHIs
692 CacheMap[&PHI] = std::make_pair(SizePHI, OffsetPHI);
693
694 // compute offset/size for each PHI incoming pointer
695 for (unsigned i = 0, e = PHI.getNumIncomingValues(); i != e; ++i) {
696 Builder.SetInsertPoint(PHI.getIncomingBlock(i)->getFirstInsertionPt());
697 SizeOffsetEvalType EdgeData = compute_(PHI.getIncomingValue(i));
698
699 if (!bothKnown(EdgeData)) {
700 OffsetPHI->replaceAllUsesWith(UndefValue::get(IntTy));
701 OffsetPHI->eraseFromParent();
702 SizePHI->replaceAllUsesWith(UndefValue::get(IntTy));
703 SizePHI->eraseFromParent();
704 return unknown();
705 }
706 SizePHI->addIncoming(EdgeData.first, PHI.getIncomingBlock(i));
707 OffsetPHI->addIncoming(EdgeData.second, PHI.getIncomingBlock(i));
708 }
Nuno Lopes0dff5322012-07-03 17:13:25 +0000709
710 Value *Size = SizePHI, *Offset = OffsetPHI, *Tmp;
711 if ((Tmp = SizePHI->hasConstantValue())) {
712 Size = Tmp;
713 SizePHI->replaceAllUsesWith(Size);
714 SizePHI->eraseFromParent();
715 }
716 if ((Tmp = OffsetPHI->hasConstantValue())) {
717 Offset = Tmp;
718 OffsetPHI->replaceAllUsesWith(Offset);
719 OffsetPHI->eraseFromParent();
720 }
721 return std::make_pair(Size, Offset);
Nuno Lopes9e72a792012-06-21 15:45:28 +0000722}
723
724SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitSelectInst(SelectInst &I) {
725 SizeOffsetEvalType TrueSide = compute_(I.getTrueValue());
726 SizeOffsetEvalType FalseSide = compute_(I.getFalseValue());
727
728 if (!bothKnown(TrueSide) || !bothKnown(FalseSide))
729 return unknown();
730 if (TrueSide == FalseSide)
731 return TrueSide;
732
733 Value *Size = Builder.CreateSelect(I.getCondition(), TrueSide.first,
734 FalseSide.first);
735 Value *Offset = Builder.CreateSelect(I.getCondition(), TrueSide.second,
736 FalseSide.second);
737 return std::make_pair(Size, Offset);
738}
739
740SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitInstruction(Instruction &I) {
741 DEBUG(dbgs() << "ObjectSizeOffsetEvaluator unknown instruction:" << I <<'\n');
742 return unknown();
743}