blob: 4833b5212be0e4c963c5d765584309b4c1198d59 [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 Lopes9e72a792012-06-21 15:45:28 +000029#include "llvm/Transforms/Utils/Local.h"
Evan Chengfabcb912009-09-10 04:36:43 +000030using namespace llvm;
31
Nuno Lopes9e72a792012-06-21 15:45:28 +000032enum AllocType {
33 MallocLike = 1<<0, // allocates
34 CallocLike = 1<<1, // allocates + bzero
35 ReallocLike = 1<<2, // reallocates
36 StrDupLike = 1<<3,
37 AllocLike = MallocLike | CallocLike | StrDupLike,
38 AnyAlloc = MallocLike | CallocLike | ReallocLike | StrDupLike
39};
Evan Chengfabcb912009-09-10 04:36:43 +000040
Nuno Lopes9e72a792012-06-21 15:45:28 +000041struct AllocFnsTy {
42 const char *Name;
43 AllocType AllocTy;
44 unsigned char NumParams;
45 // First and Second size parameters (or -1 if unused)
Nuno Lopesef22f042012-06-21 18:38:26 +000046 signed char FstParam, SndParam;
Nuno Lopes9e72a792012-06-21 15:45:28 +000047};
Evan Chengfabcb912009-09-10 04:36:43 +000048
Nuno Lopes41a3f252012-06-28 16:34:03 +000049// FIXME: certain users need more information. E.g., SimplifyLibCalls needs to
50// know which functions are nounwind, noalias, nocapture parameters, etc.
Nuno Lopes9e72a792012-06-21 15:45:28 +000051static const AllocFnsTy AllocationFnData[] = {
Nuno Lopes41a3f252012-06-28 16:34:03 +000052 {"malloc", MallocLike, 1, 0, -1},
53 {"valloc", MallocLike, 1, 0, -1},
54 {"_Znwj", MallocLike, 1, 0, -1}, // new(unsigned int)
55 {"_ZnwjRKSt9nothrow_t", MallocLike, 2, 0, -1}, // new(unsigned int, nothrow)
56 {"_Znwm", MallocLike, 1, 0, -1}, // new(unsigned long)
57 {"_ZnwmRKSt9nothrow_t", MallocLike, 2, 0, -1}, // new(unsigned long, nothrow)
58 {"_Znaj", MallocLike, 1, 0, -1}, // new[](unsigned int)
59 {"_ZnajRKSt9nothrow_t", MallocLike, 2, 0, -1}, // new[](unsigned int, nothrow)
60 {"_Znam", MallocLike, 1, 0, -1}, // new[](unsigned long)
61 {"_ZnamRKSt9nothrow_t", MallocLike, 2, 0, -1}, // new[](unsigned long, nothrow)
62 {"posix_memalign", MallocLike, 3, 2, -1},
63 {"calloc", CallocLike, 2, 0, 1},
64 {"realloc", ReallocLike, 2, 1, -1},
65 {"reallocf", ReallocLike, 2, 1, -1},
66 {"strdup", StrDupLike, 1, -1, -1},
Nuno Lopes9827c8e2012-07-24 16:28:13 +000067 {"strndup", StrDupLike, 2, 1, -1}
Nuno Lopes9e72a792012-06-21 15:45:28 +000068};
69
70
71static Function *getCalledFunction(const Value *V, bool LookThroughBitCast) {
72 if (LookThroughBitCast)
73 V = V->stripPointerCasts();
Nuno Lopes2b3e9582012-06-21 21:25:05 +000074
Nuno Lopesd845c342012-06-22 15:50:53 +000075 CallSite CS(const_cast<Value*>(V));
76 if (!CS.getInstruction())
Nuno Lopes9e72a792012-06-21 15:45:28 +000077 return 0;
Evan Chengfabcb912009-09-10 04:36:43 +000078
Nuno Lopes2b3e9582012-06-21 21:25:05 +000079 Function *Callee = CS.getCalledFunction();
Nuno Lopes9e72a792012-06-21 15:45:28 +000080 if (!Callee || !Callee->isDeclaration())
81 return 0;
82 return Callee;
83}
Evan Chengfabcb912009-09-10 04:36:43 +000084
Nuno Lopes9e72a792012-06-21 15:45:28 +000085/// \brief Returns the allocation data for the given value if it is a call to a
86/// known allocation function, and NULL otherwise.
87static const AllocFnsTy *getAllocationData(const Value *V, AllocType AllocTy,
88 bool LookThroughBitCast = false) {
89 Function *Callee = getCalledFunction(V, LookThroughBitCast);
90 if (!Callee)
91 return 0;
92
93 unsigned i = 0;
94 bool found = false;
95 for ( ; i < array_lengthof(AllocationFnData); ++i) {
96 if (Callee->getName() == AllocationFnData[i].Name) {
97 found = true;
98 break;
99 }
100 }
101 if (!found)
102 return 0;
103
104 const AllocFnsTy *FnData = &AllocationFnData[i];
105 if ((FnData->AllocTy & AllocTy) == 0)
106 return 0;
107
108 // Check function prototype.
109 // FIXME: Check the nobuiltin metadata?? (PR5130)
Nuno Lopesef22f042012-06-21 18:38:26 +0000110 int FstParam = FnData->FstParam;
111 int SndParam = FnData->SndParam;
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000112 FunctionType *FTy = Callee->getFunctionType();
Nuno Lopes9e72a792012-06-21 15:45:28 +0000113
114 if (FTy->getReturnType() == Type::getInt8PtrTy(FTy->getContext()) &&
115 FTy->getNumParams() == FnData->NumParams &&
Nuno Lopesef22f042012-06-21 18:38:26 +0000116 (FstParam < 0 ||
Nuno Lopes9e72a792012-06-21 15:45:28 +0000117 (FTy->getParamType(FstParam)->isIntegerTy(32) ||
118 FTy->getParamType(FstParam)->isIntegerTy(64))) &&
Nuno Lopesef22f042012-06-21 18:38:26 +0000119 (SndParam < 0 ||
Nuno Lopes9e72a792012-06-21 15:45:28 +0000120 FTy->getParamType(SndParam)->isIntegerTy(32) ||
121 FTy->getParamType(SndParam)->isIntegerTy(64)))
122 return FnData;
123 return 0;
124}
125
126static bool hasNoAliasAttr(const Value *V, bool LookThroughBitCast) {
Nuno Lopese8742d02012-06-25 16:17:54 +0000127 ImmutableCallSite CS(LookThroughBitCast ? V->stripPointerCasts() : V);
128 return CS && CS.hasFnAttr(Attribute::NoAlias);
Nuno Lopes9e72a792012-06-21 15:45:28 +0000129}
130
131
Nuno Lopes2b3e9582012-06-21 21:25:05 +0000132/// \brief Tests if a value is a call or invoke to a library function that
133/// allocates or reallocates memory (either malloc, calloc, realloc, or strdup
134/// like).
Nuno Lopes9e72a792012-06-21 15:45:28 +0000135bool llvm::isAllocationFn(const Value *V, bool LookThroughBitCast) {
136 return getAllocationData(V, AnyAlloc, LookThroughBitCast);
137}
138
Nuno Lopes2b3e9582012-06-21 21:25:05 +0000139/// \brief Tests if a value is a call or invoke to a function that returns a
Nuno Lopes41a3f252012-06-28 16:34:03 +0000140/// NoAlias pointer (including malloc/calloc/realloc/strdup-like functions).
Nuno Lopes9e72a792012-06-21 15:45:28 +0000141bool llvm::isNoAliasFn(const Value *V, bool LookThroughBitCast) {
Nuno Lopes41a3f252012-06-28 16:34:03 +0000142 // it's safe to consider realloc as noalias since accessing the original
143 // pointer is undefined behavior
144 return isAllocationFn(V, LookThroughBitCast) ||
Nuno Lopes9e72a792012-06-21 15:45:28 +0000145 hasNoAliasAttr(V, LookThroughBitCast);
146}
147
Nuno Lopes2b3e9582012-06-21 21:25:05 +0000148/// \brief Tests if a value is a call or invoke to a library function that
149/// allocates uninitialized memory (such as malloc).
Nuno Lopes9e72a792012-06-21 15:45:28 +0000150bool llvm::isMallocLikeFn(const Value *V, bool LookThroughBitCast) {
151 return getAllocationData(V, MallocLike, LookThroughBitCast);
152}
153
Nuno Lopes2b3e9582012-06-21 21:25:05 +0000154/// \brief Tests if a value is a call or invoke to a library function that
155/// allocates zero-filled memory (such as calloc).
Nuno Lopes9e72a792012-06-21 15:45:28 +0000156bool llvm::isCallocLikeFn(const Value *V, bool LookThroughBitCast) {
157 return getAllocationData(V, CallocLike, LookThroughBitCast);
158}
159
Nuno Lopes2b3e9582012-06-21 21:25:05 +0000160/// \brief Tests if a value is a call or invoke to a library function that
161/// allocates memory (either malloc, calloc, or strdup like).
Nuno Lopes9e72a792012-06-21 15:45:28 +0000162bool llvm::isAllocLikeFn(const Value *V, bool LookThroughBitCast) {
163 return getAllocationData(V, AllocLike, LookThroughBitCast);
164}
165
Nuno Lopes2b3e9582012-06-21 21:25:05 +0000166/// \brief Tests if a value is a call or invoke to a library function that
167/// reallocates memory (such as realloc).
Nuno Lopes9e72a792012-06-21 15:45:28 +0000168bool llvm::isReallocLikeFn(const Value *V, bool LookThroughBitCast) {
169 return getAllocationData(V, ReallocLike, LookThroughBitCast);
Evan Chengfabcb912009-09-10 04:36:43 +0000170}
171
172/// extractMallocCall - Returns the corresponding CallInst if the instruction
173/// is a malloc call. Since CallInst::CreateMalloc() only creates calls, we
174/// ignore InvokeInst here.
Victor Hernandez88efeae2009-11-03 20:02:35 +0000175const CallInst *llvm::extractMallocCall(const Value *I) {
Nuno Lopeseb7c6862012-06-22 00:25:01 +0000176 return isMallocLikeFn(I) ? dyn_cast<CallInst>(I) : 0;
Evan Chengfabcb912009-09-10 04:36:43 +0000177}
178
Victor Hernandez8e345a12009-11-10 08:32:25 +0000179static Value *computeArraySize(const CallInst *CI, const TargetData *TD,
180 bool LookThroughSExt = false) {
Evan Chengfabcb912009-09-10 04:36:43 +0000181 if (!CI)
Victor Hernandez90f48e72009-10-28 20:18:55 +0000182 return NULL;
Evan Chengfabcb912009-09-10 04:36:43 +0000183
Victor Hernandez9d0b7042009-11-07 00:16:28 +0000184 // The size of the malloc's result type must be known to determine array size.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000185 Type *T = getMallocAllocatedType(CI);
Victor Hernandez9d0b7042009-11-07 00:16:28 +0000186 if (!T || !T->isSized() || !TD)
Victor Hernandez90f48e72009-10-28 20:18:55 +0000187 return NULL;
Victor Hernandez88d98392009-09-18 19:20:02 +0000188
Victor Hernandez8e345a12009-11-10 08:32:25 +0000189 unsigned ElementSize = TD->getTypeAllocSize(T);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000190 if (StructType *ST = dyn_cast<StructType>(T))
Victor Hernandez8e345a12009-11-10 08:32:25 +0000191 ElementSize = TD->getStructLayout(ST)->getSizeInBytes();
Victor Hernandez88d98392009-09-18 19:20:02 +0000192
Gabor Greife3401c42010-06-23 21:41:47 +0000193 // If malloc call's arg can be determined to be a multiple of ElementSize,
Victor Hernandez8e345a12009-11-10 08:32:25 +0000194 // return the multiple. Otherwise, return NULL.
Gabor Greife3401c42010-06-23 21:41:47 +0000195 Value *MallocArg = CI->getArgOperand(0);
Victor Hernandez8e345a12009-11-10 08:32:25 +0000196 Value *Multiple = NULL;
Victor Hernandez8e345a12009-11-10 08:32:25 +0000197 if (ComputeMultiple(MallocArg, ElementSize, Multiple,
Dan Gohman3dbb9e62009-11-18 00:58:27 +0000198 LookThroughSExt))
Victor Hernandez8e345a12009-11-10 08:32:25 +0000199 return Multiple;
Victor Hernandez88d98392009-09-18 19:20:02 +0000200
Victor Hernandez90f48e72009-10-28 20:18:55 +0000201 return NULL;
Evan Chengfabcb912009-09-10 04:36:43 +0000202}
203
204/// isArrayMalloc - Returns the corresponding CallInst if the instruction
Victor Hernandez90f48e72009-10-28 20:18:55 +0000205/// is a call to malloc whose array size can be determined and the array size
206/// is not constant 1. Otherwise, return NULL.
Chris Lattner7b550cc2009-11-06 04:27:31 +0000207const CallInst *llvm::isArrayMalloc(const Value *I, const TargetData *TD) {
Evan Chengfabcb912009-09-10 04:36:43 +0000208 const CallInst *CI = extractMallocCall(I);
Victor Hernandez8e345a12009-11-10 08:32:25 +0000209 Value *ArraySize = computeArraySize(CI, TD);
Victor Hernandez90f48e72009-10-28 20:18:55 +0000210
211 if (ArraySize &&
Gabor Greife3401c42010-06-23 21:41:47 +0000212 ArraySize != ConstantInt::get(CI->getArgOperand(0)->getType(), 1))
Victor Hernandez90f48e72009-10-28 20:18:55 +0000213 return CI;
214
215 // CI is a non-array malloc or we can't figure out that it is an array malloc.
216 return NULL;
Evan Chengfabcb912009-09-10 04:36:43 +0000217}
218
219/// getMallocType - Returns the PointerType resulting from the malloc call.
Victor Hernandez9d0b7042009-11-07 00:16:28 +0000220/// The PointerType depends on the number of bitcast uses of the malloc call:
221/// 0: PointerType is the calls' return type.
222/// 1: PointerType is the bitcast's result type.
223/// >1: Unique PointerType cannot be determined, return NULL.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000224PointerType *llvm::getMallocType(const CallInst *CI) {
Nuno Lopes9e72a792012-06-21 15:45:28 +0000225 assert(isMallocLikeFn(CI) && "getMallocType and not malloc call");
Evan Chengfabcb912009-09-10 04:36:43 +0000226
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000227 PointerType *MallocType = NULL;
Victor Hernandez9d0b7042009-11-07 00:16:28 +0000228 unsigned NumOfBitCastUses = 0;
229
Victor Hernandez88d98392009-09-18 19:20:02 +0000230 // Determine if CallInst has a bitcast use.
Gabor Greif60ad7812010-03-25 23:06:16 +0000231 for (Value::const_use_iterator UI = CI->use_begin(), E = CI->use_end();
Victor Hernandez88d98392009-09-18 19:20:02 +0000232 UI != E; )
Victor Hernandez9d0b7042009-11-07 00:16:28 +0000233 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(*UI++)) {
234 MallocType = cast<PointerType>(BCI->getDestTy());
235 NumOfBitCastUses++;
236 }
Evan Chengfabcb912009-09-10 04:36:43 +0000237
Victor Hernandez9d0b7042009-11-07 00:16:28 +0000238 // Malloc call has 1 bitcast use, so type is the bitcast's destination type.
239 if (NumOfBitCastUses == 1)
240 return MallocType;
Evan Chengfabcb912009-09-10 04:36:43 +0000241
Victor Hernandez60cfc032009-09-22 18:50:03 +0000242 // Malloc call was not bitcast, so type is the malloc function's return type.
Victor Hernandez9d0b7042009-11-07 00:16:28 +0000243 if (NumOfBitCastUses == 0)
Victor Hernandez88d98392009-09-18 19:20:02 +0000244 return cast<PointerType>(CI->getType());
245
246 // Type could not be determined.
247 return NULL;
Evan Chengfabcb912009-09-10 04:36:43 +0000248}
249
Victor Hernandez9d0b7042009-11-07 00:16:28 +0000250/// getMallocAllocatedType - Returns the Type allocated by malloc call.
251/// The Type depends on the number of bitcast uses of the malloc call:
252/// 0: PointerType is the malloc calls' return type.
253/// 1: PointerType is the bitcast's result type.
254/// >1: Unique PointerType cannot be determined, return NULL.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000255Type *llvm::getMallocAllocatedType(const CallInst *CI) {
256 PointerType *PT = getMallocType(CI);
Evan Chengfabcb912009-09-10 04:36:43 +0000257 return PT ? PT->getElementType() : NULL;
258}
259
Victor Hernandez90f48e72009-10-28 20:18:55 +0000260/// getMallocArraySize - Returns the array size of a malloc call. If the
261/// argument passed to malloc is a multiple of the size of the malloced type,
262/// then return that multiple. For non-array mallocs, the multiple is
263/// constant 1. Otherwise, return NULL for mallocs whose array size cannot be
Victor Hernandez2491ce02009-10-15 20:14:52 +0000264/// determined.
Victor Hernandez8e345a12009-11-10 08:32:25 +0000265Value *llvm::getMallocArraySize(CallInst *CI, const TargetData *TD,
266 bool LookThroughSExt) {
Nuno Lopes9e72a792012-06-21 15:45:28 +0000267 assert(isMallocLikeFn(CI) && "getMallocArraySize and not malloc call");
Victor Hernandez8e345a12009-11-10 08:32:25 +0000268 return computeArraySize(CI, TD, LookThroughSExt);
Evan Chengfabcb912009-09-10 04:36:43 +0000269}
Victor Hernandez66284e02009-10-24 04:23:03 +0000270
Nuno Lopes252ef562012-05-03 21:19:58 +0000271
Nuno Lopes252ef562012-05-03 21:19:58 +0000272/// extractCallocCall - Returns the corresponding CallInst if the instruction
273/// is a calloc call.
274const CallInst *llvm::extractCallocCall(const Value *I) {
Nuno Lopes9e72a792012-06-21 15:45:28 +0000275 return isCallocLikeFn(I) ? cast<CallInst>(I) : 0;
Nuno Lopes252ef562012-05-03 21:19:58 +0000276}
277
Victor Hernandez046e78c2009-10-26 23:43:48 +0000278
Gabor Greif02680f92010-06-23 21:51:12 +0000279/// isFreeCall - Returns non-null if the value is a call to the builtin free()
280const CallInst *llvm::isFreeCall(const Value *I) {
Victor Hernandez66284e02009-10-24 04:23:03 +0000281 const CallInst *CI = dyn_cast<CallInst>(I);
282 if (!CI)
Gabor Greif02680f92010-06-23 21:51:12 +0000283 return 0;
Victor Hernandez3ad70d52009-11-03 20:39:35 +0000284 Function *Callee = CI->getCalledFunction();
Nick Lewycky42e72ca2011-03-15 07:31:32 +0000285 if (Callee == 0 || !Callee->isDeclaration())
286 return 0;
287
288 if (Callee->getName() != "free" &&
Nick Lewycky1ace1692011-03-17 05:20:12 +0000289 Callee->getName() != "_ZdlPv" && // operator delete(void*)
290 Callee->getName() != "_ZdaPv") // operator delete[](void*)
Gabor Greif02680f92010-06-23 21:51:12 +0000291 return 0;
Victor Hernandez66284e02009-10-24 04:23:03 +0000292
293 // Check free prototype.
294 // FIXME: workaround for PR5130, this will be obsolete when a nobuiltin
295 // attribute will exist.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000296 FunctionType *FTy = Callee->getFunctionType();
Victor Hernandez3ad70d52009-11-03 20:39:35 +0000297 if (!FTy->getReturnType()->isVoidTy())
Gabor Greif02680f92010-06-23 21:51:12 +0000298 return 0;
Victor Hernandez66284e02009-10-24 04:23:03 +0000299 if (FTy->getNumParams() != 1)
Gabor Greif02680f92010-06-23 21:51:12 +0000300 return 0;
Chris Lattnerebb21892011-06-18 21:46:23 +0000301 if (FTy->getParamType(0) != Type::getInt8PtrTy(Callee->getContext()))
Gabor Greif02680f92010-06-23 21:51:12 +0000302 return 0;
Victor Hernandez66284e02009-10-24 04:23:03 +0000303
Gabor Greif02680f92010-06-23 21:51:12 +0000304 return CI;
Victor Hernandez66284e02009-10-24 04:23:03 +0000305}
Nuno Lopes9e72a792012-06-21 15:45:28 +0000306
307
308
309//===----------------------------------------------------------------------===//
310// Utility functions to compute size of objects.
311//
312
313
314/// \brief Compute the size of the object pointed by Ptr. Returns true and the
315/// object size in Size if successful, and false otherwise.
316/// If RoundToAlign is true, then Size is rounded up to the aligment of allocas,
317/// byval arguments, and global variables.
318bool llvm::getObjectSize(const Value *Ptr, uint64_t &Size, const TargetData *TD,
319 bool RoundToAlign) {
320 if (!TD)
321 return false;
322
323 ObjectSizeOffsetVisitor Visitor(TD, Ptr->getContext(), RoundToAlign);
324 SizeOffsetType Data = Visitor.compute(const_cast<Value*>(Ptr));
325 if (!Visitor.bothKnown(Data))
326 return false;
327
328 APInt ObjSize = Data.first, Offset = Data.second;
329 // check for overflow
330 if (Offset.slt(0) || ObjSize.ult(Offset))
331 Size = 0;
332 else
333 Size = (ObjSize - Offset).getZExtValue();
334 return true;
335}
336
337
338STATISTIC(ObjectVisitorArgument,
339 "Number of arguments with unsolved size and offset");
340STATISTIC(ObjectVisitorLoad,
341 "Number of load instructions with unsolved size and offset");
342
343
344APInt ObjectSizeOffsetVisitor::align(APInt Size, uint64_t Align) {
345 if (RoundToAlign && Align)
346 return APInt(IntTyBits, RoundUpToAlignment(Size.getZExtValue(), Align));
347 return Size;
348}
349
350ObjectSizeOffsetVisitor::ObjectSizeOffsetVisitor(const TargetData *TD,
351 LLVMContext &Context,
352 bool RoundToAlign)
353: TD(TD), RoundToAlign(RoundToAlign) {
354 IntegerType *IntTy = TD->getIntPtrType(Context);
355 IntTyBits = IntTy->getBitWidth();
356 Zero = APInt::getNullValue(IntTyBits);
357}
358
359SizeOffsetType ObjectSizeOffsetVisitor::compute(Value *V) {
360 V = V->stripPointerCasts();
361
362 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
363 return visitGEPOperator(*GEP);
364 if (Instruction *I = dyn_cast<Instruction>(V))
365 return visit(*I);
366 if (Argument *A = dyn_cast<Argument>(V))
367 return visitArgument(*A);
368 if (ConstantPointerNull *P = dyn_cast<ConstantPointerNull>(V))
369 return visitConstantPointerNull(*P);
370 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
371 return visitGlobalVariable(*GV);
372 if (UndefValue *UV = dyn_cast<UndefValue>(V))
373 return visitUndefValue(*UV);
374 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
375 if (CE->getOpcode() == Instruction::IntToPtr)
376 return unknown(); // clueless
377
378 DEBUG(dbgs() << "ObjectSizeOffsetVisitor::compute() unhandled value: " << *V
379 << '\n');
380 return unknown();
381}
382
383SizeOffsetType ObjectSizeOffsetVisitor::visitAllocaInst(AllocaInst &I) {
384 if (!I.getAllocatedType()->isSized())
385 return unknown();
386
387 APInt Size(IntTyBits, TD->getTypeAllocSize(I.getAllocatedType()));
388 if (!I.isArrayAllocation())
389 return std::make_pair(align(Size, I.getAlignment()), Zero);
390
391 Value *ArraySize = I.getArraySize();
392 if (const ConstantInt *C = dyn_cast<ConstantInt>(ArraySize)) {
393 Size *= C->getValue().zextOrSelf(IntTyBits);
394 return std::make_pair(align(Size, I.getAlignment()), Zero);
395 }
396 return unknown();
397}
398
399SizeOffsetType ObjectSizeOffsetVisitor::visitArgument(Argument &A) {
400 // no interprocedural analysis is done at the moment
401 if (!A.hasByValAttr()) {
402 ++ObjectVisitorArgument;
403 return unknown();
404 }
405 PointerType *PT = cast<PointerType>(A.getType());
406 APInt Size(IntTyBits, TD->getTypeAllocSize(PT->getElementType()));
407 return std::make_pair(align(Size, A.getParamAlignment()), Zero);
408}
409
410SizeOffsetType ObjectSizeOffsetVisitor::visitCallSite(CallSite CS) {
411 const AllocFnsTy *FnData = getAllocationData(CS.getInstruction(), AnyAlloc);
412 if (!FnData)
413 return unknown();
414
415 // handle strdup-like functions separately
416 if (FnData->AllocTy == StrDupLike) {
Nuno Lopes9827c8e2012-07-24 16:28:13 +0000417 APInt Size(IntTyBits, GetStringLength(CS.getArgument(0)));
418 if (!Size)
419 return unknown();
420
421 // strndup limits strlen
422 if (FnData->FstParam > 0) {
423 ConstantInt *Arg= dyn_cast<ConstantInt>(CS.getArgument(FnData->FstParam));
424 if (!Arg)
425 return unknown();
426
427 APInt MaxSize = Arg->getValue().zextOrSelf(IntTyBits);
428 if (Size.ugt(MaxSize))
429 Size = MaxSize + 1;
430 }
431 return std::make_pair(Size, Zero);
Nuno Lopes9e72a792012-06-21 15:45:28 +0000432 }
433
434 ConstantInt *Arg = dyn_cast<ConstantInt>(CS.getArgument(FnData->FstParam));
435 if (!Arg)
436 return unknown();
437
Nuno Lopes034dd6c2012-06-21 16:47:58 +0000438 APInt Size = Arg->getValue().zextOrSelf(IntTyBits);
Nuno Lopes9e72a792012-06-21 15:45:28 +0000439 // size determined by just 1 parameter
Nuno Lopesef22f042012-06-21 18:38:26 +0000440 if (FnData->SndParam < 0)
Nuno Lopes9e72a792012-06-21 15:45:28 +0000441 return std::make_pair(Size, Zero);
442
443 Arg = dyn_cast<ConstantInt>(CS.getArgument(FnData->SndParam));
444 if (!Arg)
445 return unknown();
446
Nuno Lopes034dd6c2012-06-21 16:47:58 +0000447 Size *= Arg->getValue().zextOrSelf(IntTyBits);
Nuno Lopes9e72a792012-06-21 15:45:28 +0000448 return std::make_pair(Size, Zero);
449
450 // TODO: handle more standard functions (+ wchar cousins):
451 // - strdup / strndup
452 // - strcpy / strncpy
453 // - strcat / strncat
454 // - memcpy / memmove
455 // - strcat / strncat
456 // - memset
457}
458
459SizeOffsetType
460ObjectSizeOffsetVisitor::visitConstantPointerNull(ConstantPointerNull&) {
461 return std::make_pair(Zero, Zero);
462}
463
464SizeOffsetType
Nuno Lopes41a3f252012-06-28 16:34:03 +0000465ObjectSizeOffsetVisitor::visitExtractElementInst(ExtractElementInst&) {
466 return unknown();
467}
468
469SizeOffsetType
Nuno Lopes9e72a792012-06-21 15:45:28 +0000470ObjectSizeOffsetVisitor::visitExtractValueInst(ExtractValueInst&) {
471 // Easy cases were already folded by previous passes.
472 return unknown();
473}
474
475SizeOffsetType ObjectSizeOffsetVisitor::visitGEPOperator(GEPOperator &GEP) {
476 SizeOffsetType PtrData = compute(GEP.getPointerOperand());
477 if (!bothKnown(PtrData) || !GEP.hasAllConstantIndices())
478 return unknown();
479
480 SmallVector<Value*, 8> Ops(GEP.idx_begin(), GEP.idx_end());
481 APInt Offset(IntTyBits,TD->getIndexedOffset(GEP.getPointerOperandType(),Ops));
482 return std::make_pair(PtrData.first, PtrData.second + Offset);
483}
484
485SizeOffsetType ObjectSizeOffsetVisitor::visitGlobalVariable(GlobalVariable &GV){
486 if (!GV.hasDefinitiveInitializer())
487 return unknown();
488
489 APInt Size(IntTyBits, TD->getTypeAllocSize(GV.getType()->getElementType()));
490 return std::make_pair(align(Size, GV.getAlignment()), Zero);
491}
492
493SizeOffsetType ObjectSizeOffsetVisitor::visitIntToPtrInst(IntToPtrInst&) {
494 // clueless
495 return unknown();
496}
497
498SizeOffsetType ObjectSizeOffsetVisitor::visitLoadInst(LoadInst&) {
499 ++ObjectVisitorLoad;
500 return unknown();
501}
502
503SizeOffsetType ObjectSizeOffsetVisitor::visitPHINode(PHINode&) {
504 // too complex to analyze statically.
505 return unknown();
506}
507
508SizeOffsetType ObjectSizeOffsetVisitor::visitSelectInst(SelectInst &I) {
509 SizeOffsetType TrueSide = compute(I.getTrueValue());
510 SizeOffsetType FalseSide = compute(I.getFalseValue());
511 if (bothKnown(TrueSide) && bothKnown(FalseSide) && TrueSide == FalseSide)
512 return TrueSide;
513 return unknown();
514}
515
516SizeOffsetType ObjectSizeOffsetVisitor::visitUndefValue(UndefValue&) {
517 return std::make_pair(Zero, Zero);
518}
519
520SizeOffsetType ObjectSizeOffsetVisitor::visitInstruction(Instruction &I) {
521 DEBUG(dbgs() << "ObjectSizeOffsetVisitor unknown instruction:" << I << '\n');
522 return unknown();
523}
524
525
526ObjectSizeOffsetEvaluator::ObjectSizeOffsetEvaluator(const TargetData *TD,
527 LLVMContext &Context)
528: TD(TD), Context(Context), Builder(Context, TargetFolder(TD)),
529Visitor(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) {
622 // TODO
623 return unknown();
624 }
625
Nuno Lopes034dd6c2012-06-21 16:47:58 +0000626 Value *FirstArg = CS.getArgument(FnData->FstParam);
627 FirstArg = Builder.CreateZExt(FirstArg, IntTy);
Nuno Lopesef22f042012-06-21 18:38:26 +0000628 if (FnData->SndParam < 0)
Nuno Lopes9e72a792012-06-21 15:45:28 +0000629 return std::make_pair(FirstArg, Zero);
630
631 Value *SecondArg = CS.getArgument(FnData->SndParam);
Nuno Lopes034dd6c2012-06-21 16:47:58 +0000632 SecondArg = Builder.CreateZExt(SecondArg, IntTy);
Nuno Lopes9e72a792012-06-21 15:45:28 +0000633 Value *Size = Builder.CreateMul(FirstArg, SecondArg);
634 return std::make_pair(Size, Zero);
635
636 // TODO: handle more standard functions (+ wchar cousins):
637 // - strdup / strndup
638 // - strcpy / strncpy
639 // - strcat / strncat
640 // - memcpy / memmove
641 // - strcat / strncat
642 // - memset
643}
644
645SizeOffsetEvalType
Nuno Lopes41a3f252012-06-28 16:34:03 +0000646ObjectSizeOffsetEvaluator::visitExtractElementInst(ExtractElementInst&) {
647 return unknown();
648}
649
650SizeOffsetEvalType
651ObjectSizeOffsetEvaluator::visitExtractValueInst(ExtractValueInst&) {
652 return unknown();
653}
654
655SizeOffsetEvalType
Nuno Lopes9e72a792012-06-21 15:45:28 +0000656ObjectSizeOffsetEvaluator::visitGEPOperator(GEPOperator &GEP) {
657 SizeOffsetEvalType PtrData = compute_(GEP.getPointerOperand());
658 if (!bothKnown(PtrData))
659 return unknown();
660
Nuno Lopesc606c3f2012-07-20 23:07:40 +0000661 Value *Offset = EmitGEPOffset(&Builder, *TD, &GEP, /*NoAssumptions=*/true);
Nuno Lopes9e72a792012-06-21 15:45:28 +0000662 Offset = Builder.CreateAdd(PtrData.second, Offset);
663 return std::make_pair(PtrData.first, Offset);
664}
665
666SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitIntToPtrInst(IntToPtrInst&) {
667 // clueless
668 return unknown();
669}
670
671SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitLoadInst(LoadInst&) {
672 return unknown();
673}
674
675SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitPHINode(PHINode &PHI) {
676 // create 2 PHIs: one for size and another for offset
677 PHINode *SizePHI = Builder.CreatePHI(IntTy, PHI.getNumIncomingValues());
678 PHINode *OffsetPHI = Builder.CreatePHI(IntTy, PHI.getNumIncomingValues());
679
680 // insert right away in the cache to handle recursive PHIs
681 CacheMap[&PHI] = std::make_pair(SizePHI, OffsetPHI);
682
683 // compute offset/size for each PHI incoming pointer
684 for (unsigned i = 0, e = PHI.getNumIncomingValues(); i != e; ++i) {
685 Builder.SetInsertPoint(PHI.getIncomingBlock(i)->getFirstInsertionPt());
686 SizeOffsetEvalType EdgeData = compute_(PHI.getIncomingValue(i));
687
688 if (!bothKnown(EdgeData)) {
689 OffsetPHI->replaceAllUsesWith(UndefValue::get(IntTy));
690 OffsetPHI->eraseFromParent();
691 SizePHI->replaceAllUsesWith(UndefValue::get(IntTy));
692 SizePHI->eraseFromParent();
693 return unknown();
694 }
695 SizePHI->addIncoming(EdgeData.first, PHI.getIncomingBlock(i));
696 OffsetPHI->addIncoming(EdgeData.second, PHI.getIncomingBlock(i));
697 }
Nuno Lopes0dff5322012-07-03 17:13:25 +0000698
699 Value *Size = SizePHI, *Offset = OffsetPHI, *Tmp;
700 if ((Tmp = SizePHI->hasConstantValue())) {
701 Size = Tmp;
702 SizePHI->replaceAllUsesWith(Size);
703 SizePHI->eraseFromParent();
704 }
705 if ((Tmp = OffsetPHI->hasConstantValue())) {
706 Offset = Tmp;
707 OffsetPHI->replaceAllUsesWith(Offset);
708 OffsetPHI->eraseFromParent();
709 }
710 return std::make_pair(Size, Offset);
Nuno Lopes9e72a792012-06-21 15:45:28 +0000711}
712
713SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitSelectInst(SelectInst &I) {
714 SizeOffsetEvalType TrueSide = compute_(I.getTrueValue());
715 SizeOffsetEvalType FalseSide = compute_(I.getFalseValue());
716
717 if (!bothKnown(TrueSide) || !bothKnown(FalseSide))
718 return unknown();
719 if (TrueSide == FalseSide)
720 return TrueSide;
721
722 Value *Size = Builder.CreateSelect(I.getCondition(), TrueSide.first,
723 FalseSide.first);
724 Value *Offset = Builder.CreateSelect(I.getCondition(), TrueSide.second,
725 FalseSide.second);
726 return std::make_pair(Size, Offset);
727}
728
729SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitInstruction(Instruction &I) {
730 DEBUG(dbgs() << "ObjectSizeOffsetEvaluator unknown instruction:" << I <<'\n');
731 return unknown();
732}