blob: 26d466ed31a313f4aeada0d8a27217b5263b3b3a [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 Lopes9e72a792012-06-21 15:45:28 +000049static const AllocFnsTy AllocationFnData[] = {
50 {"malloc", MallocLike, 1, 0, -1},
51 {"valloc", MallocLike, 1, 0, -1},
52 {"_Znwj", MallocLike, 1, 0, -1}, // operator new(unsigned int)
53 {"_Znwm", MallocLike, 1, 0, -1}, // operator new(unsigned long)
54 {"_Znaj", MallocLike, 1, 0, -1}, // operator new[](unsigned int)
55 {"_Znam", MallocLike, 1, 0, -1}, // operator new[](unsigned long)
56 {"posix_memalign", MallocLike, 3, 2, -1},
57 {"calloc", CallocLike, 2, 0, 1},
58 {"realloc", ReallocLike, 2, 1, -1},
59 {"reallocf", ReallocLike, 2, 1, -1},
60 {"strdup", StrDupLike, 1, -1, -1},
61 {"strndup", StrDupLike, 2, -1, -1}
62};
63
64
65static Function *getCalledFunction(const Value *V, bool LookThroughBitCast) {
66 if (LookThroughBitCast)
67 V = V->stripPointerCasts();
Nuno Lopes2b3e9582012-06-21 21:25:05 +000068
69 Value *I = const_cast<Value*>(V);
70 CallSite CS;
71 if (CallInst *CI = dyn_cast<CallInst>(I))
72 CS = CallSite(CI);
73 else if (InvokeInst *II = dyn_cast<InvokeInst>(I))
74 CS = CallSite(II);
75 else
Nuno Lopes9e72a792012-06-21 15:45:28 +000076 return 0;
Evan Chengfabcb912009-09-10 04:36:43 +000077
Nuno Lopes2b3e9582012-06-21 21:25:05 +000078 Function *Callee = CS.getCalledFunction();
Nuno Lopes9e72a792012-06-21 15:45:28 +000079 if (!Callee || !Callee->isDeclaration())
80 return 0;
81 return Callee;
82}
Evan Chengfabcb912009-09-10 04:36:43 +000083
Nuno Lopes9e72a792012-06-21 15:45:28 +000084/// \brief Returns the allocation data for the given value if it is a call to a
85/// known allocation function, and NULL otherwise.
86static const AllocFnsTy *getAllocationData(const Value *V, AllocType AllocTy,
87 bool LookThroughBitCast = false) {
88 Function *Callee = getCalledFunction(V, LookThroughBitCast);
89 if (!Callee)
90 return 0;
91
92 unsigned i = 0;
93 bool found = false;
94 for ( ; i < array_lengthof(AllocationFnData); ++i) {
95 if (Callee->getName() == AllocationFnData[i].Name) {
96 found = true;
97 break;
98 }
99 }
100 if (!found)
101 return 0;
102
103 const AllocFnsTy *FnData = &AllocationFnData[i];
104 if ((FnData->AllocTy & AllocTy) == 0)
105 return 0;
106
107 // Check function prototype.
108 // FIXME: Check the nobuiltin metadata?? (PR5130)
Nuno Lopesef22f042012-06-21 18:38:26 +0000109 int FstParam = FnData->FstParam;
110 int SndParam = FnData->SndParam;
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000111 FunctionType *FTy = Callee->getFunctionType();
Nuno Lopes9e72a792012-06-21 15:45:28 +0000112
113 if (FTy->getReturnType() == Type::getInt8PtrTy(FTy->getContext()) &&
114 FTy->getNumParams() == FnData->NumParams &&
Nuno Lopesef22f042012-06-21 18:38:26 +0000115 (FstParam < 0 ||
Nuno Lopes9e72a792012-06-21 15:45:28 +0000116 (FTy->getParamType(FstParam)->isIntegerTy(32) ||
117 FTy->getParamType(FstParam)->isIntegerTy(64))) &&
Nuno Lopesef22f042012-06-21 18:38:26 +0000118 (SndParam < 0 ||
Nuno Lopes9e72a792012-06-21 15:45:28 +0000119 FTy->getParamType(SndParam)->isIntegerTy(32) ||
120 FTy->getParamType(SndParam)->isIntegerTy(64)))
121 return FnData;
122 return 0;
123}
124
125static bool hasNoAliasAttr(const Value *V, bool LookThroughBitCast) {
126 Function *Callee = getCalledFunction(V, LookThroughBitCast);
127 return Callee && Callee->hasFnAttr(Attribute::NoAlias);
128}
129
130
Nuno Lopes2b3e9582012-06-21 21:25:05 +0000131/// \brief Tests if a value is a call or invoke to a library function that
132/// allocates or reallocates memory (either malloc, calloc, realloc, or strdup
133/// like).
Nuno Lopes9e72a792012-06-21 15:45:28 +0000134bool llvm::isAllocationFn(const Value *V, bool LookThroughBitCast) {
135 return getAllocationData(V, AnyAlloc, LookThroughBitCast);
136}
137
Nuno Lopes2b3e9582012-06-21 21:25:05 +0000138/// \brief Tests if a value is a call or invoke to a function that returns a
139/// NoAlias pointer (including malloc/calloc/strdup-like functions).
Nuno Lopes9e72a792012-06-21 15:45:28 +0000140bool llvm::isNoAliasFn(const Value *V, bool LookThroughBitCast) {
141 return isAllocLikeFn(V, LookThroughBitCast) ||
142 hasNoAliasAttr(V, LookThroughBitCast);
143}
144
Nuno Lopes2b3e9582012-06-21 21:25:05 +0000145/// \brief Tests if a value is a call or invoke to a library function that
146/// allocates uninitialized memory (such as malloc).
Nuno Lopes9e72a792012-06-21 15:45:28 +0000147bool llvm::isMallocLikeFn(const Value *V, bool LookThroughBitCast) {
148 return getAllocationData(V, MallocLike, LookThroughBitCast);
149}
150
Nuno Lopes2b3e9582012-06-21 21:25:05 +0000151/// \brief Tests if a value is a call or invoke to a library function that
152/// allocates zero-filled memory (such as calloc).
Nuno Lopes9e72a792012-06-21 15:45:28 +0000153bool llvm::isCallocLikeFn(const Value *V, bool LookThroughBitCast) {
154 return getAllocationData(V, CallocLike, LookThroughBitCast);
155}
156
Nuno Lopes2b3e9582012-06-21 21:25:05 +0000157/// \brief Tests if a value is a call or invoke to a library function that
158/// allocates memory (either malloc, calloc, or strdup like).
Nuno Lopes9e72a792012-06-21 15:45:28 +0000159bool llvm::isAllocLikeFn(const Value *V, bool LookThroughBitCast) {
160 return getAllocationData(V, AllocLike, LookThroughBitCast);
161}
162
Nuno Lopes2b3e9582012-06-21 21:25:05 +0000163/// \brief Tests if a value is a call or invoke to a library function that
164/// reallocates memory (such as realloc).
Nuno Lopes9e72a792012-06-21 15:45:28 +0000165bool llvm::isReallocLikeFn(const Value *V, bool LookThroughBitCast) {
166 return getAllocationData(V, ReallocLike, LookThroughBitCast);
Evan Chengfabcb912009-09-10 04:36:43 +0000167}
168
169/// extractMallocCall - Returns the corresponding CallInst if the instruction
170/// is a malloc call. Since CallInst::CreateMalloc() only creates calls, we
171/// ignore InvokeInst here.
Victor Hernandez88efeae2009-11-03 20:02:35 +0000172const CallInst *llvm::extractMallocCall(const Value *I) {
Nuno Lopes9e72a792012-06-21 15:45:28 +0000173 return isMallocLikeFn(I) ? cast<CallInst>(I) : 0;
Evan Chengfabcb912009-09-10 04:36:43 +0000174}
175
176/// extractMallocCallFromBitCast - Returns the corresponding CallInst if the
177/// instruction is a bitcast of the result of a malloc call.
Victor Hernandez88efeae2009-11-03 20:02:35 +0000178const CallInst *llvm::extractMallocCallFromBitCast(const Value *I) {
Evan Chengfabcb912009-09-10 04:36:43 +0000179 const BitCastInst *BCI = dyn_cast<BitCastInst>(I);
Nuno Lopes9e72a792012-06-21 15:45:28 +0000180 return BCI ? extractMallocCall(BCI->getOperand(0)) : 0;
Evan Chengfabcb912009-09-10 04:36:43 +0000181}
182
Victor Hernandez8e345a12009-11-10 08:32:25 +0000183static Value *computeArraySize(const CallInst *CI, const TargetData *TD,
184 bool LookThroughSExt = false) {
Evan Chengfabcb912009-09-10 04:36:43 +0000185 if (!CI)
Victor Hernandez90f48e72009-10-28 20:18:55 +0000186 return NULL;
Evan Chengfabcb912009-09-10 04:36:43 +0000187
Victor Hernandez9d0b7042009-11-07 00:16:28 +0000188 // The size of the malloc's result type must be known to determine array size.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000189 Type *T = getMallocAllocatedType(CI);
Victor Hernandez9d0b7042009-11-07 00:16:28 +0000190 if (!T || !T->isSized() || !TD)
Victor Hernandez90f48e72009-10-28 20:18:55 +0000191 return NULL;
Victor Hernandez88d98392009-09-18 19:20:02 +0000192
Victor Hernandez8e345a12009-11-10 08:32:25 +0000193 unsigned ElementSize = TD->getTypeAllocSize(T);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000194 if (StructType *ST = dyn_cast<StructType>(T))
Victor Hernandez8e345a12009-11-10 08:32:25 +0000195 ElementSize = TD->getStructLayout(ST)->getSizeInBytes();
Victor Hernandez88d98392009-09-18 19:20:02 +0000196
Gabor Greife3401c42010-06-23 21:41:47 +0000197 // If malloc call's arg can be determined to be a multiple of ElementSize,
Victor Hernandez8e345a12009-11-10 08:32:25 +0000198 // return the multiple. Otherwise, return NULL.
Gabor Greife3401c42010-06-23 21:41:47 +0000199 Value *MallocArg = CI->getArgOperand(0);
Victor Hernandez8e345a12009-11-10 08:32:25 +0000200 Value *Multiple = NULL;
Victor Hernandez8e345a12009-11-10 08:32:25 +0000201 if (ComputeMultiple(MallocArg, ElementSize, Multiple,
Dan Gohman3dbb9e62009-11-18 00:58:27 +0000202 LookThroughSExt))
Victor Hernandez8e345a12009-11-10 08:32:25 +0000203 return Multiple;
Victor Hernandez88d98392009-09-18 19:20:02 +0000204
Victor Hernandez90f48e72009-10-28 20:18:55 +0000205 return NULL;
Evan Chengfabcb912009-09-10 04:36:43 +0000206}
207
208/// isArrayMalloc - Returns the corresponding CallInst if the instruction
Victor Hernandez90f48e72009-10-28 20:18:55 +0000209/// is a call to malloc whose array size can be determined and the array size
210/// is not constant 1. Otherwise, return NULL.
Chris Lattner7b550cc2009-11-06 04:27:31 +0000211const CallInst *llvm::isArrayMalloc(const Value *I, const TargetData *TD) {
Evan Chengfabcb912009-09-10 04:36:43 +0000212 const CallInst *CI = extractMallocCall(I);
Victor Hernandez8e345a12009-11-10 08:32:25 +0000213 Value *ArraySize = computeArraySize(CI, TD);
Victor Hernandez90f48e72009-10-28 20:18:55 +0000214
215 if (ArraySize &&
Gabor Greife3401c42010-06-23 21:41:47 +0000216 ArraySize != ConstantInt::get(CI->getArgOperand(0)->getType(), 1))
Victor Hernandez90f48e72009-10-28 20:18:55 +0000217 return CI;
218
219 // CI is a non-array malloc or we can't figure out that it is an array malloc.
220 return NULL;
Evan Chengfabcb912009-09-10 04:36:43 +0000221}
222
223/// getMallocType - Returns the PointerType resulting from the malloc call.
Victor Hernandez9d0b7042009-11-07 00:16:28 +0000224/// The PointerType depends on the number of bitcast uses of the malloc call:
225/// 0: PointerType is the calls' return type.
226/// 1: PointerType is the bitcast's result type.
227/// >1: Unique PointerType cannot be determined, return NULL.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000228PointerType *llvm::getMallocType(const CallInst *CI) {
Nuno Lopes9e72a792012-06-21 15:45:28 +0000229 assert(isMallocLikeFn(CI) && "getMallocType and not malloc call");
Evan Chengfabcb912009-09-10 04:36:43 +0000230
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000231 PointerType *MallocType = NULL;
Victor Hernandez9d0b7042009-11-07 00:16:28 +0000232 unsigned NumOfBitCastUses = 0;
233
Victor Hernandez88d98392009-09-18 19:20:02 +0000234 // Determine if CallInst has a bitcast use.
Gabor Greif60ad7812010-03-25 23:06:16 +0000235 for (Value::const_use_iterator UI = CI->use_begin(), E = CI->use_end();
Victor Hernandez88d98392009-09-18 19:20:02 +0000236 UI != E; )
Victor Hernandez9d0b7042009-11-07 00:16:28 +0000237 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(*UI++)) {
238 MallocType = cast<PointerType>(BCI->getDestTy());
239 NumOfBitCastUses++;
240 }
Evan Chengfabcb912009-09-10 04:36:43 +0000241
Victor Hernandez9d0b7042009-11-07 00:16:28 +0000242 // Malloc call has 1 bitcast use, so type is the bitcast's destination type.
243 if (NumOfBitCastUses == 1)
244 return MallocType;
Evan Chengfabcb912009-09-10 04:36:43 +0000245
Victor Hernandez60cfc032009-09-22 18:50:03 +0000246 // Malloc call was not bitcast, so type is the malloc function's return type.
Victor Hernandez9d0b7042009-11-07 00:16:28 +0000247 if (NumOfBitCastUses == 0)
Victor Hernandez88d98392009-09-18 19:20:02 +0000248 return cast<PointerType>(CI->getType());
249
250 // Type could not be determined.
251 return NULL;
Evan Chengfabcb912009-09-10 04:36:43 +0000252}
253
Victor Hernandez9d0b7042009-11-07 00:16:28 +0000254/// getMallocAllocatedType - Returns the Type allocated by malloc call.
255/// The Type depends on the number of bitcast uses of the malloc call:
256/// 0: PointerType is the malloc calls' return type.
257/// 1: PointerType is the bitcast's result type.
258/// >1: Unique PointerType cannot be determined, return NULL.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000259Type *llvm::getMallocAllocatedType(const CallInst *CI) {
260 PointerType *PT = getMallocType(CI);
Evan Chengfabcb912009-09-10 04:36:43 +0000261 return PT ? PT->getElementType() : NULL;
262}
263
Victor Hernandez90f48e72009-10-28 20:18:55 +0000264/// getMallocArraySize - Returns the array size of a malloc call. If the
265/// argument passed to malloc is a multiple of the size of the malloced type,
266/// then return that multiple. For non-array mallocs, the multiple is
267/// constant 1. Otherwise, return NULL for mallocs whose array size cannot be
Victor Hernandez2491ce02009-10-15 20:14:52 +0000268/// determined.
Victor Hernandez8e345a12009-11-10 08:32:25 +0000269Value *llvm::getMallocArraySize(CallInst *CI, const TargetData *TD,
270 bool LookThroughSExt) {
Nuno Lopes9e72a792012-06-21 15:45:28 +0000271 assert(isMallocLikeFn(CI) && "getMallocArraySize and not malloc call");
Victor Hernandez8e345a12009-11-10 08:32:25 +0000272 return computeArraySize(CI, TD, LookThroughSExt);
Evan Chengfabcb912009-09-10 04:36:43 +0000273}
Victor Hernandez66284e02009-10-24 04:23:03 +0000274
Nuno Lopes252ef562012-05-03 21:19:58 +0000275
Nuno Lopes252ef562012-05-03 21:19:58 +0000276/// extractCallocCall - Returns the corresponding CallInst if the instruction
277/// is a calloc call.
278const CallInst *llvm::extractCallocCall(const Value *I) {
Nuno Lopes9e72a792012-06-21 15:45:28 +0000279 return isCallocLikeFn(I) ? cast<CallInst>(I) : 0;
Nuno Lopes252ef562012-05-03 21:19:58 +0000280}
281
Victor Hernandez046e78c2009-10-26 23:43:48 +0000282
Gabor Greif02680f92010-06-23 21:51:12 +0000283/// isFreeCall - Returns non-null if the value is a call to the builtin free()
284const CallInst *llvm::isFreeCall(const Value *I) {
Victor Hernandez66284e02009-10-24 04:23:03 +0000285 const CallInst *CI = dyn_cast<CallInst>(I);
286 if (!CI)
Gabor Greif02680f92010-06-23 21:51:12 +0000287 return 0;
Victor Hernandez3ad70d52009-11-03 20:39:35 +0000288 Function *Callee = CI->getCalledFunction();
Nick Lewycky42e72ca2011-03-15 07:31:32 +0000289 if (Callee == 0 || !Callee->isDeclaration())
290 return 0;
291
292 if (Callee->getName() != "free" &&
Nick Lewycky1ace1692011-03-17 05:20:12 +0000293 Callee->getName() != "_ZdlPv" && // operator delete(void*)
294 Callee->getName() != "_ZdaPv") // operator delete[](void*)
Gabor Greif02680f92010-06-23 21:51:12 +0000295 return 0;
Victor Hernandez66284e02009-10-24 04:23:03 +0000296
297 // Check free prototype.
298 // FIXME: workaround for PR5130, this will be obsolete when a nobuiltin
299 // attribute will exist.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000300 FunctionType *FTy = Callee->getFunctionType();
Victor Hernandez3ad70d52009-11-03 20:39:35 +0000301 if (!FTy->getReturnType()->isVoidTy())
Gabor Greif02680f92010-06-23 21:51:12 +0000302 return 0;
Victor Hernandez66284e02009-10-24 04:23:03 +0000303 if (FTy->getNumParams() != 1)
Gabor Greif02680f92010-06-23 21:51:12 +0000304 return 0;
Chris Lattnerebb21892011-06-18 21:46:23 +0000305 if (FTy->getParamType(0) != Type::getInt8PtrTy(Callee->getContext()))
Gabor Greif02680f92010-06-23 21:51:12 +0000306 return 0;
Victor Hernandez66284e02009-10-24 04:23:03 +0000307
Gabor Greif02680f92010-06-23 21:51:12 +0000308 return CI;
Victor Hernandez66284e02009-10-24 04:23:03 +0000309}
Nuno Lopes9e72a792012-06-21 15:45:28 +0000310
311
312
313//===----------------------------------------------------------------------===//
314// Utility functions to compute size of objects.
315//
316
317
318/// \brief Compute the size of the object pointed by Ptr. Returns true and the
319/// object size in Size if successful, and false otherwise.
320/// If RoundToAlign is true, then Size is rounded up to the aligment of allocas,
321/// byval arguments, and global variables.
322bool llvm::getObjectSize(const Value *Ptr, uint64_t &Size, const TargetData *TD,
323 bool RoundToAlign) {
324 if (!TD)
325 return false;
326
327 ObjectSizeOffsetVisitor Visitor(TD, Ptr->getContext(), RoundToAlign);
328 SizeOffsetType Data = Visitor.compute(const_cast<Value*>(Ptr));
329 if (!Visitor.bothKnown(Data))
330 return false;
331
332 APInt ObjSize = Data.first, Offset = Data.second;
333 // check for overflow
334 if (Offset.slt(0) || ObjSize.ult(Offset))
335 Size = 0;
336 else
337 Size = (ObjSize - Offset).getZExtValue();
338 return true;
339}
340
341
342STATISTIC(ObjectVisitorArgument,
343 "Number of arguments with unsolved size and offset");
344STATISTIC(ObjectVisitorLoad,
345 "Number of load instructions with unsolved size and offset");
346
347
348APInt ObjectSizeOffsetVisitor::align(APInt Size, uint64_t Align) {
349 if (RoundToAlign && Align)
350 return APInt(IntTyBits, RoundUpToAlignment(Size.getZExtValue(), Align));
351 return Size;
352}
353
354ObjectSizeOffsetVisitor::ObjectSizeOffsetVisitor(const TargetData *TD,
355 LLVMContext &Context,
356 bool RoundToAlign)
357: TD(TD), RoundToAlign(RoundToAlign) {
358 IntegerType *IntTy = TD->getIntPtrType(Context);
359 IntTyBits = IntTy->getBitWidth();
360 Zero = APInt::getNullValue(IntTyBits);
361}
362
363SizeOffsetType ObjectSizeOffsetVisitor::compute(Value *V) {
364 V = V->stripPointerCasts();
365
366 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
367 return visitGEPOperator(*GEP);
368 if (Instruction *I = dyn_cast<Instruction>(V))
369 return visit(*I);
370 if (Argument *A = dyn_cast<Argument>(V))
371 return visitArgument(*A);
372 if (ConstantPointerNull *P = dyn_cast<ConstantPointerNull>(V))
373 return visitConstantPointerNull(*P);
374 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
375 return visitGlobalVariable(*GV);
376 if (UndefValue *UV = dyn_cast<UndefValue>(V))
377 return visitUndefValue(*UV);
378 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
379 if (CE->getOpcode() == Instruction::IntToPtr)
380 return unknown(); // clueless
381
382 DEBUG(dbgs() << "ObjectSizeOffsetVisitor::compute() unhandled value: " << *V
383 << '\n');
384 return unknown();
385}
386
387SizeOffsetType ObjectSizeOffsetVisitor::visitAllocaInst(AllocaInst &I) {
388 if (!I.getAllocatedType()->isSized())
389 return unknown();
390
391 APInt Size(IntTyBits, TD->getTypeAllocSize(I.getAllocatedType()));
392 if (!I.isArrayAllocation())
393 return std::make_pair(align(Size, I.getAlignment()), Zero);
394
395 Value *ArraySize = I.getArraySize();
396 if (const ConstantInt *C = dyn_cast<ConstantInt>(ArraySize)) {
397 Size *= C->getValue().zextOrSelf(IntTyBits);
398 return std::make_pair(align(Size, I.getAlignment()), Zero);
399 }
400 return unknown();
401}
402
403SizeOffsetType ObjectSizeOffsetVisitor::visitArgument(Argument &A) {
404 // no interprocedural analysis is done at the moment
405 if (!A.hasByValAttr()) {
406 ++ObjectVisitorArgument;
407 return unknown();
408 }
409 PointerType *PT = cast<PointerType>(A.getType());
410 APInt Size(IntTyBits, TD->getTypeAllocSize(PT->getElementType()));
411 return std::make_pair(align(Size, A.getParamAlignment()), Zero);
412}
413
414SizeOffsetType ObjectSizeOffsetVisitor::visitCallSite(CallSite CS) {
415 const AllocFnsTy *FnData = getAllocationData(CS.getInstruction(), AnyAlloc);
416 if (!FnData)
417 return unknown();
418
419 // handle strdup-like functions separately
420 if (FnData->AllocTy == StrDupLike) {
421 // TODO
422 return unknown();
423 }
424
425 ConstantInt *Arg = dyn_cast<ConstantInt>(CS.getArgument(FnData->FstParam));
426 if (!Arg)
427 return unknown();
428
Nuno Lopes034dd6c2012-06-21 16:47:58 +0000429 APInt Size = Arg->getValue().zextOrSelf(IntTyBits);
Nuno Lopes9e72a792012-06-21 15:45:28 +0000430 // size determined by just 1 parameter
Nuno Lopesef22f042012-06-21 18:38:26 +0000431 if (FnData->SndParam < 0)
Nuno Lopes9e72a792012-06-21 15:45:28 +0000432 return std::make_pair(Size, Zero);
433
434 Arg = dyn_cast<ConstantInt>(CS.getArgument(FnData->SndParam));
435 if (!Arg)
436 return unknown();
437
Nuno Lopes034dd6c2012-06-21 16:47:58 +0000438 Size *= Arg->getValue().zextOrSelf(IntTyBits);
Nuno Lopes9e72a792012-06-21 15:45:28 +0000439 return std::make_pair(Size, Zero);
440
441 // TODO: handle more standard functions (+ wchar cousins):
442 // - strdup / strndup
443 // - strcpy / strncpy
444 // - strcat / strncat
445 // - memcpy / memmove
446 // - strcat / strncat
447 // - memset
448}
449
450SizeOffsetType
451ObjectSizeOffsetVisitor::visitConstantPointerNull(ConstantPointerNull&) {
452 return std::make_pair(Zero, Zero);
453}
454
455SizeOffsetType
456ObjectSizeOffsetVisitor::visitExtractValueInst(ExtractValueInst&) {
457 // Easy cases were already folded by previous passes.
458 return unknown();
459}
460
461SizeOffsetType ObjectSizeOffsetVisitor::visitGEPOperator(GEPOperator &GEP) {
462 SizeOffsetType PtrData = compute(GEP.getPointerOperand());
463 if (!bothKnown(PtrData) || !GEP.hasAllConstantIndices())
464 return unknown();
465
466 SmallVector<Value*, 8> Ops(GEP.idx_begin(), GEP.idx_end());
467 APInt Offset(IntTyBits,TD->getIndexedOffset(GEP.getPointerOperandType(),Ops));
468 return std::make_pair(PtrData.first, PtrData.second + Offset);
469}
470
471SizeOffsetType ObjectSizeOffsetVisitor::visitGlobalVariable(GlobalVariable &GV){
472 if (!GV.hasDefinitiveInitializer())
473 return unknown();
474
475 APInt Size(IntTyBits, TD->getTypeAllocSize(GV.getType()->getElementType()));
476 return std::make_pair(align(Size, GV.getAlignment()), Zero);
477}
478
479SizeOffsetType ObjectSizeOffsetVisitor::visitIntToPtrInst(IntToPtrInst&) {
480 // clueless
481 return unknown();
482}
483
484SizeOffsetType ObjectSizeOffsetVisitor::visitLoadInst(LoadInst&) {
485 ++ObjectVisitorLoad;
486 return unknown();
487}
488
489SizeOffsetType ObjectSizeOffsetVisitor::visitPHINode(PHINode&) {
490 // too complex to analyze statically.
491 return unknown();
492}
493
494SizeOffsetType ObjectSizeOffsetVisitor::visitSelectInst(SelectInst &I) {
495 SizeOffsetType TrueSide = compute(I.getTrueValue());
496 SizeOffsetType FalseSide = compute(I.getFalseValue());
497 if (bothKnown(TrueSide) && bothKnown(FalseSide) && TrueSide == FalseSide)
498 return TrueSide;
499 return unknown();
500}
501
502SizeOffsetType ObjectSizeOffsetVisitor::visitUndefValue(UndefValue&) {
503 return std::make_pair(Zero, Zero);
504}
505
506SizeOffsetType ObjectSizeOffsetVisitor::visitInstruction(Instruction &I) {
507 DEBUG(dbgs() << "ObjectSizeOffsetVisitor unknown instruction:" << I << '\n');
508 return unknown();
509}
510
511
512ObjectSizeOffsetEvaluator::ObjectSizeOffsetEvaluator(const TargetData *TD,
513 LLVMContext &Context)
514: TD(TD), Context(Context), Builder(Context, TargetFolder(TD)),
515Visitor(TD, Context) {
516 IntTy = TD->getIntPtrType(Context);
517 Zero = ConstantInt::get(IntTy, 0);
518}
519
520SizeOffsetEvalType ObjectSizeOffsetEvaluator::compute(Value *V) {
521 SizeOffsetEvalType Result = compute_(V);
522
523 if (!bothKnown(Result)) {
524 // erase everything that was computed in this iteration from the cache, so
525 // that no dangling references are left behind. We could be a bit smarter if
526 // we kept a dependency graph. It's probably not worth the complexity.
527 for (PtrSetTy::iterator I=SeenVals.begin(), E=SeenVals.end(); I != E; ++I) {
528 CacheMapTy::iterator CacheIt = CacheMap.find(*I);
529 // non-computable results can be safely cached
530 if (CacheIt != CacheMap.end() && anyKnown(CacheIt->second))
531 CacheMap.erase(CacheIt);
532 }
533 }
534
535 SeenVals.clear();
536 return Result;
537}
538
539SizeOffsetEvalType ObjectSizeOffsetEvaluator::compute_(Value *V) {
540 SizeOffsetType Const = Visitor.compute(V);
541 if (Visitor.bothKnown(Const))
542 return std::make_pair(ConstantInt::get(Context, Const.first),
543 ConstantInt::get(Context, Const.second));
544
545 V = V->stripPointerCasts();
546
547 // check cache
548 CacheMapTy::iterator CacheIt = CacheMap.find(V);
549 if (CacheIt != CacheMap.end())
550 return CacheIt->second;
551
552 // always generate code immediately before the instruction being
553 // processed, so that the generated code dominates the same BBs
554 Instruction *PrevInsertPoint = Builder.GetInsertPoint();
555 if (Instruction *I = dyn_cast<Instruction>(V))
556 Builder.SetInsertPoint(I);
557
558 // record the pointers that were handled in this run, so that they can be
559 // cleaned later if something fails
560 SeenVals.insert(V);
561
562 // now compute the size and offset
563 SizeOffsetEvalType Result;
564 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
565 Result = visitGEPOperator(*GEP);
566 } else if (Instruction *I = dyn_cast<Instruction>(V)) {
567 Result = visit(*I);
568 } else if (isa<Argument>(V) ||
569 (isa<ConstantExpr>(V) &&
570 cast<ConstantExpr>(V)->getOpcode() == Instruction::IntToPtr) ||
571 isa<GlobalVariable>(V)) {
572 // ignore values where we cannot do more than what ObjectSizeVisitor can
573 Result = unknown();
574 } else {
575 DEBUG(dbgs() << "ObjectSizeOffsetEvaluator::compute() unhandled value: "
576 << *V << '\n');
577 Result = unknown();
578 }
579
580 if (PrevInsertPoint)
581 Builder.SetInsertPoint(PrevInsertPoint);
582
583 // Don't reuse CacheIt since it may be invalid at this point.
584 CacheMap[V] = Result;
585 return Result;
586}
587
588SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitAllocaInst(AllocaInst &I) {
589 if (!I.getAllocatedType()->isSized())
590 return unknown();
591
592 // must be a VLA
593 assert(I.isArrayAllocation());
594 Value *ArraySize = I.getArraySize();
595 Value *Size = ConstantInt::get(ArraySize->getType(),
596 TD->getTypeAllocSize(I.getAllocatedType()));
597 Size = Builder.CreateMul(Size, ArraySize);
598 return std::make_pair(Size, Zero);
599}
600
601SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitCallSite(CallSite CS) {
602 const AllocFnsTy *FnData = getAllocationData(CS.getInstruction(), AnyAlloc);
603 if (!FnData)
604 return unknown();
605
606 // handle strdup-like functions separately
607 if (FnData->AllocTy == StrDupLike) {
608 // TODO
609 return unknown();
610 }
611
Nuno Lopes034dd6c2012-06-21 16:47:58 +0000612 Value *FirstArg = CS.getArgument(FnData->FstParam);
613 FirstArg = Builder.CreateZExt(FirstArg, IntTy);
Nuno Lopesef22f042012-06-21 18:38:26 +0000614 if (FnData->SndParam < 0)
Nuno Lopes9e72a792012-06-21 15:45:28 +0000615 return std::make_pair(FirstArg, Zero);
616
617 Value *SecondArg = CS.getArgument(FnData->SndParam);
Nuno Lopes034dd6c2012-06-21 16:47:58 +0000618 SecondArg = Builder.CreateZExt(SecondArg, IntTy);
Nuno Lopes9e72a792012-06-21 15:45:28 +0000619 Value *Size = Builder.CreateMul(FirstArg, SecondArg);
620 return std::make_pair(Size, Zero);
621
622 // TODO: handle more standard functions (+ wchar cousins):
623 // - strdup / strndup
624 // - strcpy / strncpy
625 // - strcat / strncat
626 // - memcpy / memmove
627 // - strcat / strncat
628 // - memset
629}
630
631SizeOffsetEvalType
632ObjectSizeOffsetEvaluator::visitGEPOperator(GEPOperator &GEP) {
633 SizeOffsetEvalType PtrData = compute_(GEP.getPointerOperand());
634 if (!bothKnown(PtrData))
635 return unknown();
636
637 Value *Offset = EmitGEPOffset(&Builder, *TD, &GEP);
638 Offset = Builder.CreateAdd(PtrData.second, Offset);
639 return std::make_pair(PtrData.first, Offset);
640}
641
642SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitIntToPtrInst(IntToPtrInst&) {
643 // clueless
644 return unknown();
645}
646
647SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitLoadInst(LoadInst&) {
648 return unknown();
649}
650
651SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitPHINode(PHINode &PHI) {
652 // create 2 PHIs: one for size and another for offset
653 PHINode *SizePHI = Builder.CreatePHI(IntTy, PHI.getNumIncomingValues());
654 PHINode *OffsetPHI = Builder.CreatePHI(IntTy, PHI.getNumIncomingValues());
655
656 // insert right away in the cache to handle recursive PHIs
657 CacheMap[&PHI] = std::make_pair(SizePHI, OffsetPHI);
658
659 // compute offset/size for each PHI incoming pointer
660 for (unsigned i = 0, e = PHI.getNumIncomingValues(); i != e; ++i) {
661 Builder.SetInsertPoint(PHI.getIncomingBlock(i)->getFirstInsertionPt());
662 SizeOffsetEvalType EdgeData = compute_(PHI.getIncomingValue(i));
663
664 if (!bothKnown(EdgeData)) {
665 OffsetPHI->replaceAllUsesWith(UndefValue::get(IntTy));
666 OffsetPHI->eraseFromParent();
667 SizePHI->replaceAllUsesWith(UndefValue::get(IntTy));
668 SizePHI->eraseFromParent();
669 return unknown();
670 }
671 SizePHI->addIncoming(EdgeData.first, PHI.getIncomingBlock(i));
672 OffsetPHI->addIncoming(EdgeData.second, PHI.getIncomingBlock(i));
673 }
674 return std::make_pair(SizePHI, OffsetPHI);
675}
676
677SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitSelectInst(SelectInst &I) {
678 SizeOffsetEvalType TrueSide = compute_(I.getTrueValue());
679 SizeOffsetEvalType FalseSide = compute_(I.getFalseValue());
680
681 if (!bothKnown(TrueSide) || !bothKnown(FalseSide))
682 return unknown();
683 if (TrueSide == FalseSide)
684 return TrueSide;
685
686 Value *Size = Builder.CreateSelect(I.getCondition(), TrueSide.first,
687 FalseSide.first);
688 Value *Offset = Builder.CreateSelect(I.getCondition(), TrueSide.second,
689 FalseSide.second);
690 return std::make_pair(Size, Offset);
691}
692
693SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitInstruction(Instruction &I) {
694 DEBUG(dbgs() << "ObjectSizeOffsetEvaluator unknown instruction:" << I <<'\n');
695 return unknown();
696}