blob: 8e89aa98486a6f145a8b678556ac3e3ea93fa8c4 [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
Michael Ilseman9333ffb2013-03-08 21:03:09 +000011// 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"
Victor Hernandezf006b182009-10-27 20:05:49 +000016#include "llvm/Analysis/MemoryBuiltins.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000017#include "llvm/ADT/STLExtras.h"
18#include "llvm/ADT/Statistic.h"
19#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000020#include "llvm/IR/DataLayout.h"
21#include "llvm/IR/GlobalVariable.h"
22#include "llvm/IR/Instructions.h"
23#include "llvm/IR/Intrinsics.h"
24#include "llvm/IR/Metadata.h"
25#include "llvm/IR/Module.h"
Nuno Lopes9e72a792012-06-21 15:45:28 +000026#include "llvm/Support/Debug.h"
27#include "llvm/Support/MathExtras.h"
28#include "llvm/Support/raw_ostream.h"
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +000029#include "llvm/Target/TargetLibraryInfo.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 {
Benjamin Kramerd44f9f22013-09-24 17:34:29 +000034 OpNewLike = 1<<0, // allocates; never returns null
35 MallocLike = 1<<1 | OpNewLike, // allocates; may return null
36 CallocLike = 1<<2, // allocates + bzero
37 ReallocLike = 1<<3, // reallocates
38 StrDupLike = 1<<4,
39 AllocLike = MallocLike | CallocLike | StrDupLike,
Benjamin Kramer989779c2013-09-24 17:15:14 +000040 AnyAlloc = AllocLike | ReallocLike
Nuno Lopes9e72a792012-06-21 15:45:28 +000041};
Evan Chengfabcb912009-09-10 04:36:43 +000042
Nuno Lopes9e72a792012-06-21 15:45:28 +000043struct AllocFnsTy {
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +000044 LibFunc::Func Func;
Nuno Lopes9e72a792012-06-21 15:45:28 +000045 AllocType AllocTy;
46 unsigned char NumParams;
47 // First and Second size parameters (or -1 if unused)
Nuno Lopesef22f042012-06-21 18:38:26 +000048 signed char FstParam, SndParam;
Nuno Lopes9e72a792012-06-21 15:45:28 +000049};
Evan Chengfabcb912009-09-10 04:36:43 +000050
Nuno Lopes41a3f252012-06-28 16:34:03 +000051// FIXME: certain users need more information. E.g., SimplifyLibCalls needs to
52// know which functions are nounwind, noalias, nocapture parameters, etc.
Nuno Lopes9e72a792012-06-21 15:45:28 +000053static const AllocFnsTy AllocationFnData[] = {
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +000054 {LibFunc::malloc, MallocLike, 1, 0, -1},
55 {LibFunc::valloc, MallocLike, 1, 0, -1},
Benjamin Kramer66292102013-09-24 16:37:51 +000056 {LibFunc::Znwj, OpNewLike, 1, 0, -1}, // new(unsigned int)
Nadav Roteme43e2d82013-04-09 04:43:46 +000057 {LibFunc::ZnwjRKSt9nothrow_t, MallocLike, 2, 0, -1}, // new(unsigned int, nothrow)
Benjamin Kramer66292102013-09-24 16:37:51 +000058 {LibFunc::Znwm, OpNewLike, 1, 0, -1}, // new(unsigned long)
Nadav Roteme43e2d82013-04-09 04:43:46 +000059 {LibFunc::ZnwmRKSt9nothrow_t, MallocLike, 2, 0, -1}, // new(unsigned long, nothrow)
Benjamin Kramer66292102013-09-24 16:37:51 +000060 {LibFunc::Znaj, OpNewLike, 1, 0, -1}, // new[](unsigned int)
Nadav Roteme43e2d82013-04-09 04:43:46 +000061 {LibFunc::ZnajRKSt9nothrow_t, MallocLike, 2, 0, -1}, // new[](unsigned int, nothrow)
Benjamin Kramer66292102013-09-24 16:37:51 +000062 {LibFunc::Znam, OpNewLike, 1, 0, -1}, // new[](unsigned long)
Nadav Roteme43e2d82013-04-09 04:43:46 +000063 {LibFunc::ZnamRKSt9nothrow_t, MallocLike, 2, 0, -1}, // new[](unsigned long, nothrow)
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +000064 {LibFunc::calloc, CallocLike, 2, 0, 1},
65 {LibFunc::realloc, ReallocLike, 2, 1, -1},
66 {LibFunc::reallocf, ReallocLike, 2, 1, -1},
67 {LibFunc::strdup, StrDupLike, 1, -1, -1},
68 {LibFunc::strndup, StrDupLike, 2, 1, -1}
Benjamin Kramer09b16f32013-09-24 17:49:08 +000069 // TODO: Handle "int posix_memalign(void **, size_t, size_t)"
Nuno Lopes9e72a792012-06-21 15:45:28 +000070};
71
72
73static Function *getCalledFunction(const Value *V, bool LookThroughBitCast) {
74 if (LookThroughBitCast)
75 V = V->stripPointerCasts();
Nuno Lopes2b3e9582012-06-21 21:25:05 +000076
Nuno Lopesd845c342012-06-22 15:50:53 +000077 CallSite CS(const_cast<Value*>(V));
78 if (!CS.getInstruction())
Nuno Lopes9e72a792012-06-21 15:45:28 +000079 return 0;
Evan Chengfabcb912009-09-10 04:36:43 +000080
Michael Gottesman2253a2f2013-06-27 00:25:01 +000081 if (CS.isNoBuiltin())
Richard Smitheb351eb2013-05-16 04:12:04 +000082 return 0;
83
Nuno Lopes2b3e9582012-06-21 21:25:05 +000084 Function *Callee = CS.getCalledFunction();
Nuno Lopes9e72a792012-06-21 15:45:28 +000085 if (!Callee || !Callee->isDeclaration())
86 return 0;
87 return Callee;
88}
Evan Chengfabcb912009-09-10 04:36:43 +000089
Nuno Lopes9e72a792012-06-21 15:45:28 +000090/// \brief Returns the allocation data for the given value if it is a call to a
91/// known allocation function, and NULL otherwise.
92static const AllocFnsTy *getAllocationData(const Value *V, AllocType AllocTy,
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +000093 const TargetLibraryInfo *TLI,
Nuno Lopes9e72a792012-06-21 15:45:28 +000094 bool LookThroughBitCast = false) {
Michael Ilsemancacf9712013-03-08 21:15:00 +000095 // Skip intrinsics
96 if (isa<IntrinsicInst>(V))
97 return 0;
98
Nuno Lopes9e72a792012-06-21 15:45:28 +000099 Function *Callee = getCalledFunction(V, LookThroughBitCast);
100 if (!Callee)
101 return 0;
102
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000103 // Make sure that the function is available.
104 StringRef FnName = Callee->getName();
105 LibFunc::Func TLIFn;
106 if (!TLI || !TLI->getLibFunc(FnName, TLIFn) || !TLI->has(TLIFn))
107 return 0;
108
Nuno Lopes9e72a792012-06-21 15:45:28 +0000109 unsigned i = 0;
110 bool found = false;
111 for ( ; i < array_lengthof(AllocationFnData); ++i) {
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000112 if (AllocationFnData[i].Func == TLIFn) {
Nuno Lopes9e72a792012-06-21 15:45:28 +0000113 found = true;
114 break;
115 }
116 }
117 if (!found)
118 return 0;
119
120 const AllocFnsTy *FnData = &AllocationFnData[i];
Benjamin Kramerd44f9f22013-09-24 17:34:29 +0000121 if ((FnData->AllocTy & AllocTy) != FnData->AllocTy)
Nuno Lopes9e72a792012-06-21 15:45:28 +0000122 return 0;
123
124 // Check function prototype.
Nuno Lopesef22f042012-06-21 18:38:26 +0000125 int FstParam = FnData->FstParam;
126 int SndParam = FnData->SndParam;
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000127 FunctionType *FTy = Callee->getFunctionType();
Nuno Lopes9e72a792012-06-21 15:45:28 +0000128
129 if (FTy->getReturnType() == Type::getInt8PtrTy(FTy->getContext()) &&
130 FTy->getNumParams() == FnData->NumParams &&
Nuno Lopesef22f042012-06-21 18:38:26 +0000131 (FstParam < 0 ||
Nuno Lopes9e72a792012-06-21 15:45:28 +0000132 (FTy->getParamType(FstParam)->isIntegerTy(32) ||
133 FTy->getParamType(FstParam)->isIntegerTy(64))) &&
Nuno Lopesef22f042012-06-21 18:38:26 +0000134 (SndParam < 0 ||
Nuno Lopes9e72a792012-06-21 15:45:28 +0000135 FTy->getParamType(SndParam)->isIntegerTy(32) ||
136 FTy->getParamType(SndParam)->isIntegerTy(64)))
137 return FnData;
138 return 0;
139}
140
141static bool hasNoAliasAttr(const Value *V, bool LookThroughBitCast) {
Nuno Lopese8742d02012-06-25 16:17:54 +0000142 ImmutableCallSite CS(LookThroughBitCast ? V->stripPointerCasts() : V);
Bill Wendling034b94b2012-12-19 07:18:57 +0000143 return CS && CS.hasFnAttr(Attribute::NoAlias);
Nuno Lopes9e72a792012-06-21 15:45:28 +0000144}
145
146
Nuno Lopes2b3e9582012-06-21 21:25:05 +0000147/// \brief Tests if a value is a call or invoke to a library function that
148/// allocates or reallocates memory (either malloc, calloc, realloc, or strdup
149/// like).
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000150bool llvm::isAllocationFn(const Value *V, const TargetLibraryInfo *TLI,
151 bool LookThroughBitCast) {
152 return getAllocationData(V, AnyAlloc, TLI, LookThroughBitCast);
Nuno Lopes9e72a792012-06-21 15:45:28 +0000153}
154
Nuno Lopes2b3e9582012-06-21 21:25:05 +0000155/// \brief Tests if a value is a call or invoke to a function that returns a
Nuno Lopes41a3f252012-06-28 16:34:03 +0000156/// NoAlias pointer (including malloc/calloc/realloc/strdup-like functions).
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000157bool llvm::isNoAliasFn(const Value *V, const TargetLibraryInfo *TLI,
158 bool LookThroughBitCast) {
Nuno Lopes41a3f252012-06-28 16:34:03 +0000159 // it's safe to consider realloc as noalias since accessing the original
160 // pointer is undefined behavior
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000161 return isAllocationFn(V, TLI, LookThroughBitCast) ||
Nuno Lopes9e72a792012-06-21 15:45:28 +0000162 hasNoAliasAttr(V, LookThroughBitCast);
163}
164
Nuno Lopes2b3e9582012-06-21 21:25:05 +0000165/// \brief Tests if a value is a call or invoke to a library function that
166/// allocates uninitialized memory (such as malloc).
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000167bool llvm::isMallocLikeFn(const Value *V, const TargetLibraryInfo *TLI,
168 bool LookThroughBitCast) {
169 return getAllocationData(V, MallocLike, TLI, LookThroughBitCast);
Nuno Lopes9e72a792012-06-21 15:45:28 +0000170}
171
Nuno Lopes2b3e9582012-06-21 21:25:05 +0000172/// \brief Tests if a value is a call or invoke to a library function that
173/// allocates zero-filled memory (such as calloc).
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000174bool llvm::isCallocLikeFn(const Value *V, const TargetLibraryInfo *TLI,
175 bool LookThroughBitCast) {
176 return getAllocationData(V, CallocLike, TLI, LookThroughBitCast);
Nuno Lopes9e72a792012-06-21 15:45:28 +0000177}
178
Nuno Lopes2b3e9582012-06-21 21:25:05 +0000179/// \brief Tests if a value is a call or invoke to a library function that
180/// allocates memory (either malloc, calloc, or strdup like).
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000181bool llvm::isAllocLikeFn(const Value *V, const TargetLibraryInfo *TLI,
182 bool LookThroughBitCast) {
183 return getAllocationData(V, AllocLike, TLI, LookThroughBitCast);
Nuno Lopes9e72a792012-06-21 15:45:28 +0000184}
185
Nuno Lopes2b3e9582012-06-21 21:25:05 +0000186/// \brief Tests if a value is a call or invoke to a library function that
187/// reallocates memory (such as realloc).
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000188bool llvm::isReallocLikeFn(const Value *V, const TargetLibraryInfo *TLI,
189 bool LookThroughBitCast) {
190 return getAllocationData(V, ReallocLike, TLI, LookThroughBitCast);
Evan Chengfabcb912009-09-10 04:36:43 +0000191}
192
Benjamin Kramer66292102013-09-24 16:37:51 +0000193/// \brief Tests if a value is a call or invoke to a library function that
194/// allocates memory and never returns null (such as operator new).
195bool llvm::isOperatorNewLikeFn(const Value *V, const TargetLibraryInfo *TLI,
196 bool LookThroughBitCast) {
197 return getAllocationData(V, OpNewLike, TLI, LookThroughBitCast);
198}
199
Evan Chengfabcb912009-09-10 04:36:43 +0000200/// extractMallocCall - Returns the corresponding CallInst if the instruction
201/// is a malloc call. Since CallInst::CreateMalloc() only creates calls, we
202/// ignore InvokeInst here.
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000203const CallInst *llvm::extractMallocCall(const Value *I,
204 const TargetLibraryInfo *TLI) {
205 return isMallocLikeFn(I, TLI) ? dyn_cast<CallInst>(I) : 0;
Evan Chengfabcb912009-09-10 04:36:43 +0000206}
207
Micah Villmow3574eca2012-10-08 16:38:25 +0000208static Value *computeArraySize(const CallInst *CI, const DataLayout *TD,
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000209 const TargetLibraryInfo *TLI,
Victor Hernandez8e345a12009-11-10 08:32:25 +0000210 bool LookThroughSExt = false) {
Evan Chengfabcb912009-09-10 04:36:43 +0000211 if (!CI)
Jakub Staszaka9cd5162013-03-07 20:01:47 +0000212 return 0;
Evan Chengfabcb912009-09-10 04:36:43 +0000213
Victor Hernandez9d0b7042009-11-07 00:16:28 +0000214 // The size of the malloc's result type must be known to determine array size.
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000215 Type *T = getMallocAllocatedType(CI, TLI);
Victor Hernandez9d0b7042009-11-07 00:16:28 +0000216 if (!T || !T->isSized() || !TD)
Jakub Staszaka9cd5162013-03-07 20:01:47 +0000217 return 0;
Victor Hernandez88d98392009-09-18 19:20:02 +0000218
Victor Hernandez8e345a12009-11-10 08:32:25 +0000219 unsigned ElementSize = TD->getTypeAllocSize(T);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000220 if (StructType *ST = dyn_cast<StructType>(T))
Victor Hernandez8e345a12009-11-10 08:32:25 +0000221 ElementSize = TD->getStructLayout(ST)->getSizeInBytes();
Victor Hernandez88d98392009-09-18 19:20:02 +0000222
Gabor Greife3401c42010-06-23 21:41:47 +0000223 // If malloc call's arg can be determined to be a multiple of ElementSize,
Victor Hernandez8e345a12009-11-10 08:32:25 +0000224 // return the multiple. Otherwise, return NULL.
Gabor Greife3401c42010-06-23 21:41:47 +0000225 Value *MallocArg = CI->getArgOperand(0);
Jakub Staszaka9cd5162013-03-07 20:01:47 +0000226 Value *Multiple = 0;
Victor Hernandez8e345a12009-11-10 08:32:25 +0000227 if (ComputeMultiple(MallocArg, ElementSize, Multiple,
Dan Gohman3dbb9e62009-11-18 00:58:27 +0000228 LookThroughSExt))
Victor Hernandez8e345a12009-11-10 08:32:25 +0000229 return Multiple;
Victor Hernandez88d98392009-09-18 19:20:02 +0000230
Jakub Staszaka9cd5162013-03-07 20:01:47 +0000231 return 0;
Evan Chengfabcb912009-09-10 04:36:43 +0000232}
233
Michael Ilseman9333ffb2013-03-08 21:03:09 +0000234/// isArrayMalloc - Returns the corresponding CallInst if the instruction
Victor Hernandez90f48e72009-10-28 20:18:55 +0000235/// is a call to malloc whose array size can be determined and the array size
236/// is not constant 1. Otherwise, return NULL.
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000237const CallInst *llvm::isArrayMalloc(const Value *I,
Micah Villmow3574eca2012-10-08 16:38:25 +0000238 const DataLayout *TD,
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000239 const TargetLibraryInfo *TLI) {
240 const CallInst *CI = extractMallocCall(I, TLI);
241 Value *ArraySize = computeArraySize(CI, TD, TLI);
Victor Hernandez90f48e72009-10-28 20:18:55 +0000242
Jakub Staszakb1b6c172013-03-07 20:22:39 +0000243 if (ConstantInt *ConstSize = dyn_cast_or_null<ConstantInt>(ArraySize))
244 if (ConstSize->isOne())
245 return CI;
Victor Hernandez90f48e72009-10-28 20:18:55 +0000246
247 // CI is a non-array malloc or we can't figure out that it is an array malloc.
Jakub Staszaka9cd5162013-03-07 20:01:47 +0000248 return 0;
Evan Chengfabcb912009-09-10 04:36:43 +0000249}
250
251/// getMallocType - Returns the PointerType resulting from the malloc call.
Victor Hernandez9d0b7042009-11-07 00:16:28 +0000252/// The PointerType depends on the number of bitcast uses of the malloc call:
253/// 0: PointerType is the calls' return type.
254/// 1: PointerType is the bitcast's result type.
255/// >1: Unique PointerType cannot be determined, return NULL.
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000256PointerType *llvm::getMallocType(const CallInst *CI,
257 const TargetLibraryInfo *TLI) {
258 assert(isMallocLikeFn(CI, TLI) && "getMallocType and not malloc call");
Michael Ilseman9333ffb2013-03-08 21:03:09 +0000259
Jakub Staszaka9cd5162013-03-07 20:01:47 +0000260 PointerType *MallocType = 0;
Victor Hernandez9d0b7042009-11-07 00:16:28 +0000261 unsigned NumOfBitCastUses = 0;
262
Victor Hernandez88d98392009-09-18 19:20:02 +0000263 // Determine if CallInst has a bitcast use.
Gabor Greif60ad7812010-03-25 23:06:16 +0000264 for (Value::const_use_iterator UI = CI->use_begin(), E = CI->use_end();
Victor Hernandez88d98392009-09-18 19:20:02 +0000265 UI != E; )
Victor Hernandez9d0b7042009-11-07 00:16:28 +0000266 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(*UI++)) {
267 MallocType = cast<PointerType>(BCI->getDestTy());
268 NumOfBitCastUses++;
269 }
Evan Chengfabcb912009-09-10 04:36:43 +0000270
Victor Hernandez9d0b7042009-11-07 00:16:28 +0000271 // Malloc call has 1 bitcast use, so type is the bitcast's destination type.
272 if (NumOfBitCastUses == 1)
273 return MallocType;
Evan Chengfabcb912009-09-10 04:36:43 +0000274
Victor Hernandez60cfc032009-09-22 18:50:03 +0000275 // Malloc call was not bitcast, so type is the malloc function's return type.
Victor Hernandez9d0b7042009-11-07 00:16:28 +0000276 if (NumOfBitCastUses == 0)
Victor Hernandez88d98392009-09-18 19:20:02 +0000277 return cast<PointerType>(CI->getType());
278
279 // Type could not be determined.
Jakub Staszaka9cd5162013-03-07 20:01:47 +0000280 return 0;
Evan Chengfabcb912009-09-10 04:36:43 +0000281}
282
Victor Hernandez9d0b7042009-11-07 00:16:28 +0000283/// getMallocAllocatedType - Returns the Type allocated by malloc call.
284/// The Type depends on the number of bitcast uses of the malloc call:
285/// 0: PointerType is the malloc calls' return type.
286/// 1: PointerType is the bitcast's result type.
287/// >1: Unique PointerType cannot be determined, return NULL.
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000288Type *llvm::getMallocAllocatedType(const CallInst *CI,
289 const TargetLibraryInfo *TLI) {
290 PointerType *PT = getMallocType(CI, TLI);
Jakub Staszaka9cd5162013-03-07 20:01:47 +0000291 return PT ? PT->getElementType() : 0;
Evan Chengfabcb912009-09-10 04:36:43 +0000292}
293
Michael Ilseman9333ffb2013-03-08 21:03:09 +0000294/// getMallocArraySize - Returns the array size of a malloc call. If the
Victor Hernandez90f48e72009-10-28 20:18:55 +0000295/// argument passed to malloc is a multiple of the size of the malloced type,
296/// then return that multiple. For non-array mallocs, the multiple is
297/// constant 1. Otherwise, return NULL for mallocs whose array size cannot be
Victor Hernandez2491ce02009-10-15 20:14:52 +0000298/// determined.
Micah Villmow3574eca2012-10-08 16:38:25 +0000299Value *llvm::getMallocArraySize(CallInst *CI, const DataLayout *TD,
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000300 const TargetLibraryInfo *TLI,
Victor Hernandez8e345a12009-11-10 08:32:25 +0000301 bool LookThroughSExt) {
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000302 assert(isMallocLikeFn(CI, TLI) && "getMallocArraySize and not malloc call");
303 return computeArraySize(CI, TD, TLI, LookThroughSExt);
Evan Chengfabcb912009-09-10 04:36:43 +0000304}
Victor Hernandez66284e02009-10-24 04:23:03 +0000305
Nuno Lopes252ef562012-05-03 21:19:58 +0000306
Nuno Lopes252ef562012-05-03 21:19:58 +0000307/// extractCallocCall - Returns the corresponding CallInst if the instruction
308/// is a calloc call.
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000309const CallInst *llvm::extractCallocCall(const Value *I,
310 const TargetLibraryInfo *TLI) {
311 return isCallocLikeFn(I, TLI) ? cast<CallInst>(I) : 0;
Nuno Lopes252ef562012-05-03 21:19:58 +0000312}
313
Victor Hernandez046e78c2009-10-26 23:43:48 +0000314
Gabor Greif02680f92010-06-23 21:51:12 +0000315/// isFreeCall - Returns non-null if the value is a call to the builtin free()
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000316const CallInst *llvm::isFreeCall(const Value *I, const TargetLibraryInfo *TLI) {
Victor Hernandez66284e02009-10-24 04:23:03 +0000317 const CallInst *CI = dyn_cast<CallInst>(I);
Michael Ilsemancacf9712013-03-08 21:15:00 +0000318 if (!CI || isa<IntrinsicInst>(CI))
Gabor Greif02680f92010-06-23 21:51:12 +0000319 return 0;
Victor Hernandez3ad70d52009-11-03 20:39:35 +0000320 Function *Callee = CI->getCalledFunction();
Nick Lewycky42e72ca2011-03-15 07:31:32 +0000321 if (Callee == 0 || !Callee->isDeclaration())
322 return 0;
323
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000324 StringRef FnName = Callee->getName();
325 LibFunc::Func TLIFn;
326 if (!TLI || !TLI->getLibFunc(FnName, TLIFn) || !TLI->has(TLIFn))
327 return 0;
328
Richard Smith72c83312013-07-21 23:11:42 +0000329 unsigned ExpectedNumParams;
330 if (TLIFn == LibFunc::free ||
331 TLIFn == LibFunc::ZdlPv || // operator delete(void*)
332 TLIFn == LibFunc::ZdaPv) // operator delete[](void*)
333 ExpectedNumParams = 1;
334 else if (TLIFn == LibFunc::ZdlPvRKSt9nothrow_t || // delete(void*, nothrow)
335 TLIFn == LibFunc::ZdaPvRKSt9nothrow_t) // delete[](void*, nothrow)
336 ExpectedNumParams = 2;
337 else
Gabor Greif02680f92010-06-23 21:51:12 +0000338 return 0;
Victor Hernandez66284e02009-10-24 04:23:03 +0000339
340 // Check free prototype.
Michael Ilseman9333ffb2013-03-08 21:03:09 +0000341 // FIXME: workaround for PR5130, this will be obsolete when a nobuiltin
Victor Hernandez66284e02009-10-24 04:23:03 +0000342 // attribute will exist.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000343 FunctionType *FTy = Callee->getFunctionType();
Victor Hernandez3ad70d52009-11-03 20:39:35 +0000344 if (!FTy->getReturnType()->isVoidTy())
Gabor Greif02680f92010-06-23 21:51:12 +0000345 return 0;
Richard Smith72c83312013-07-21 23:11:42 +0000346 if (FTy->getNumParams() != ExpectedNumParams)
Gabor Greif02680f92010-06-23 21:51:12 +0000347 return 0;
Chris Lattnerebb21892011-06-18 21:46:23 +0000348 if (FTy->getParamType(0) != Type::getInt8PtrTy(Callee->getContext()))
Gabor Greif02680f92010-06-23 21:51:12 +0000349 return 0;
Victor Hernandez66284e02009-10-24 04:23:03 +0000350
Gabor Greif02680f92010-06-23 21:51:12 +0000351 return CI;
Victor Hernandez66284e02009-10-24 04:23:03 +0000352}
Nuno Lopes9e72a792012-06-21 15:45:28 +0000353
354
355
356//===----------------------------------------------------------------------===//
357// Utility functions to compute size of objects.
358//
359
360
361/// \brief Compute the size of the object pointed by Ptr. Returns true and the
362/// object size in Size if successful, and false otherwise.
363/// If RoundToAlign is true, then Size is rounded up to the aligment of allocas,
364/// byval arguments, and global variables.
Micah Villmow3574eca2012-10-08 16:38:25 +0000365bool llvm::getObjectSize(const Value *Ptr, uint64_t &Size, const DataLayout *TD,
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000366 const TargetLibraryInfo *TLI, bool RoundToAlign) {
Nuno Lopes9e72a792012-06-21 15:45:28 +0000367 if (!TD)
368 return false;
369
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000370 ObjectSizeOffsetVisitor Visitor(TD, TLI, Ptr->getContext(), RoundToAlign);
Nuno Lopes9e72a792012-06-21 15:45:28 +0000371 SizeOffsetType Data = Visitor.compute(const_cast<Value*>(Ptr));
372 if (!Visitor.bothKnown(Data))
373 return false;
374
375 APInt ObjSize = Data.first, Offset = Data.second;
376 // check for overflow
377 if (Offset.slt(0) || ObjSize.ult(Offset))
378 Size = 0;
379 else
380 Size = (ObjSize - Offset).getZExtValue();
381 return true;
382}
383
384
385STATISTIC(ObjectVisitorArgument,
386 "Number of arguments with unsolved size and offset");
387STATISTIC(ObjectVisitorLoad,
388 "Number of load instructions with unsolved size and offset");
389
390
391APInt ObjectSizeOffsetVisitor::align(APInt Size, uint64_t Align) {
392 if (RoundToAlign && Align)
393 return APInt(IntTyBits, RoundUpToAlignment(Size.getZExtValue(), Align));
394 return Size;
395}
396
Micah Villmow3574eca2012-10-08 16:38:25 +0000397ObjectSizeOffsetVisitor::ObjectSizeOffsetVisitor(const DataLayout *TD,
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000398 const TargetLibraryInfo *TLI,
Nuno Lopes9e72a792012-06-21 15:45:28 +0000399 LLVMContext &Context,
Chandler Carruthece6c6b2012-11-01 08:07:29 +0000400 bool RoundToAlign)
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000401: TD(TD), TLI(TLI), RoundToAlign(RoundToAlign) {
Chandler Carruthece6c6b2012-11-01 08:07:29 +0000402 IntegerType *IntTy = TD->getIntPtrType(Context);
Nuno Lopes9e72a792012-06-21 15:45:28 +0000403 IntTyBits = IntTy->getBitWidth();
404 Zero = APInt::getNullValue(IntTyBits);
405}
406
407SizeOffsetType ObjectSizeOffsetVisitor::compute(Value *V) {
408 V = V->stripPointerCasts();
Nadav Rotem8e4df482013-04-09 18:16:05 +0000409 if (Instruction *I = dyn_cast<Instruction>(V)) {
410 // If we have already seen this instruction, bail out. Cycles can happen in
411 // unreachable code after constant propagation.
412 if (!SeenInsts.insert(I))
413 return unknown();
Nuno Lopes0a9ff4c2012-12-31 20:45:10 +0000414
Benjamin Kramer168843c2012-08-17 19:26:41 +0000415 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
Nadav Rotem8e4df482013-04-09 18:16:05 +0000416 return visitGEPOperator(*GEP);
417 return visit(*I);
Benjamin Kramer168843c2012-08-17 19:26:41 +0000418 }
Nuno Lopes9e72a792012-06-21 15:45:28 +0000419 if (Argument *A = dyn_cast<Argument>(V))
420 return visitArgument(*A);
421 if (ConstantPointerNull *P = dyn_cast<ConstantPointerNull>(V))
422 return visitConstantPointerNull(*P);
Nuno Lopes41be2fb2012-12-31 16:23:48 +0000423 if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
424 return visitGlobalAlias(*GA);
Nuno Lopes9e72a792012-06-21 15:45:28 +0000425 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
426 return visitGlobalVariable(*GV);
427 if (UndefValue *UV = dyn_cast<UndefValue>(V))
428 return visitUndefValue(*UV);
Benjamin Kramer168843c2012-08-17 19:26:41 +0000429 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
Nuno Lopes9e72a792012-06-21 15:45:28 +0000430 if (CE->getOpcode() == Instruction::IntToPtr)
431 return unknown(); // clueless
Nadav Rotem8e4df482013-04-09 18:16:05 +0000432 if (CE->getOpcode() == Instruction::GetElementPtr)
433 return visitGEPOperator(cast<GEPOperator>(*CE));
Benjamin Kramer168843c2012-08-17 19:26:41 +0000434 }
Nuno Lopes9e72a792012-06-21 15:45:28 +0000435
436 DEBUG(dbgs() << "ObjectSizeOffsetVisitor::compute() unhandled value: " << *V
437 << '\n');
438 return unknown();
439}
440
441SizeOffsetType ObjectSizeOffsetVisitor::visitAllocaInst(AllocaInst &I) {
442 if (!I.getAllocatedType()->isSized())
443 return unknown();
444
445 APInt Size(IntTyBits, TD->getTypeAllocSize(I.getAllocatedType()));
446 if (!I.isArrayAllocation())
447 return std::make_pair(align(Size, I.getAlignment()), Zero);
448
449 Value *ArraySize = I.getArraySize();
450 if (const ConstantInt *C = dyn_cast<ConstantInt>(ArraySize)) {
451 Size *= C->getValue().zextOrSelf(IntTyBits);
452 return std::make_pair(align(Size, I.getAlignment()), Zero);
453 }
454 return unknown();
455}
456
457SizeOffsetType ObjectSizeOffsetVisitor::visitArgument(Argument &A) {
458 // no interprocedural analysis is done at the moment
459 if (!A.hasByValAttr()) {
460 ++ObjectVisitorArgument;
461 return unknown();
462 }
463 PointerType *PT = cast<PointerType>(A.getType());
464 APInt Size(IntTyBits, TD->getTypeAllocSize(PT->getElementType()));
465 return std::make_pair(align(Size, A.getParamAlignment()), Zero);
466}
467
468SizeOffsetType ObjectSizeOffsetVisitor::visitCallSite(CallSite CS) {
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000469 const AllocFnsTy *FnData = getAllocationData(CS.getInstruction(), AnyAlloc,
470 TLI);
Nuno Lopes9e72a792012-06-21 15:45:28 +0000471 if (!FnData)
472 return unknown();
473
474 // handle strdup-like functions separately
475 if (FnData->AllocTy == StrDupLike) {
Nuno Lopes9827c8e2012-07-24 16:28:13 +0000476 APInt Size(IntTyBits, GetStringLength(CS.getArgument(0)));
477 if (!Size)
478 return unknown();
479
480 // strndup limits strlen
481 if (FnData->FstParam > 0) {
482 ConstantInt *Arg= dyn_cast<ConstantInt>(CS.getArgument(FnData->FstParam));
483 if (!Arg)
484 return unknown();
485
486 APInt MaxSize = Arg->getValue().zextOrSelf(IntTyBits);
487 if (Size.ugt(MaxSize))
488 Size = MaxSize + 1;
489 }
490 return std::make_pair(Size, Zero);
Nuno Lopes9e72a792012-06-21 15:45:28 +0000491 }
492
493 ConstantInt *Arg = dyn_cast<ConstantInt>(CS.getArgument(FnData->FstParam));
494 if (!Arg)
495 return unknown();
496
Nuno Lopes034dd6c2012-06-21 16:47:58 +0000497 APInt Size = Arg->getValue().zextOrSelf(IntTyBits);
Nuno Lopes9e72a792012-06-21 15:45:28 +0000498 // size determined by just 1 parameter
Nuno Lopesef22f042012-06-21 18:38:26 +0000499 if (FnData->SndParam < 0)
Nuno Lopes9e72a792012-06-21 15:45:28 +0000500 return std::make_pair(Size, Zero);
501
502 Arg = dyn_cast<ConstantInt>(CS.getArgument(FnData->SndParam));
503 if (!Arg)
504 return unknown();
505
Nuno Lopes034dd6c2012-06-21 16:47:58 +0000506 Size *= Arg->getValue().zextOrSelf(IntTyBits);
Nuno Lopes9e72a792012-06-21 15:45:28 +0000507 return std::make_pair(Size, Zero);
508
509 // TODO: handle more standard functions (+ wchar cousins):
Nuno Lopes6e699bf2012-07-25 18:49:28 +0000510 // - strdup / strndup
Nuno Lopes9e72a792012-06-21 15:45:28 +0000511 // - strcpy / strncpy
512 // - strcat / strncat
513 // - memcpy / memmove
Nuno Lopes6e699bf2012-07-25 18:49:28 +0000514 // - strcat / strncat
Nuno Lopes9e72a792012-06-21 15:45:28 +0000515 // - memset
516}
517
518SizeOffsetType
519ObjectSizeOffsetVisitor::visitConstantPointerNull(ConstantPointerNull&) {
520 return std::make_pair(Zero, Zero);
521}
522
523SizeOffsetType
Nuno Lopes41a3f252012-06-28 16:34:03 +0000524ObjectSizeOffsetVisitor::visitExtractElementInst(ExtractElementInst&) {
525 return unknown();
526}
527
528SizeOffsetType
Nuno Lopes9e72a792012-06-21 15:45:28 +0000529ObjectSizeOffsetVisitor::visitExtractValueInst(ExtractValueInst&) {
530 // Easy cases were already folded by previous passes.
531 return unknown();
532}
533
534SizeOffsetType ObjectSizeOffsetVisitor::visitGEPOperator(GEPOperator &GEP) {
535 SizeOffsetType PtrData = compute(GEP.getPointerOperand());
Nuno Lopes98281a22012-12-30 16:25:48 +0000536 APInt Offset(IntTyBits, 0);
537 if (!bothKnown(PtrData) || !GEP.accumulateConstantOffset(*TD, Offset))
Nuno Lopes9e72a792012-06-21 15:45:28 +0000538 return unknown();
539
Nuno Lopes9e72a792012-06-21 15:45:28 +0000540 return std::make_pair(PtrData.first, PtrData.second + Offset);
541}
542
Nuno Lopes41be2fb2012-12-31 16:23:48 +0000543SizeOffsetType ObjectSizeOffsetVisitor::visitGlobalAlias(GlobalAlias &GA) {
544 if (GA.mayBeOverridden())
545 return unknown();
546 return compute(GA.getAliasee());
547}
548
Nuno Lopes9e72a792012-06-21 15:45:28 +0000549SizeOffsetType ObjectSizeOffsetVisitor::visitGlobalVariable(GlobalVariable &GV){
550 if (!GV.hasDefinitiveInitializer())
551 return unknown();
552
553 APInt Size(IntTyBits, TD->getTypeAllocSize(GV.getType()->getElementType()));
554 return std::make_pair(align(Size, GV.getAlignment()), Zero);
555}
556
557SizeOffsetType ObjectSizeOffsetVisitor::visitIntToPtrInst(IntToPtrInst&) {
558 // clueless
559 return unknown();
560}
561
562SizeOffsetType ObjectSizeOffsetVisitor::visitLoadInst(LoadInst&) {
563 ++ObjectVisitorLoad;
564 return unknown();
565}
566
Nadav Rotem8e4df482013-04-09 18:16:05 +0000567SizeOffsetType ObjectSizeOffsetVisitor::visitPHINode(PHINode&) {
568 // too complex to analyze statically.
569 return unknown();
Nuno Lopes9e72a792012-06-21 15:45:28 +0000570}
571
572SizeOffsetType ObjectSizeOffsetVisitor::visitSelectInst(SelectInst &I) {
573 SizeOffsetType TrueSide = compute(I.getTrueValue());
574 SizeOffsetType FalseSide = compute(I.getFalseValue());
Nuno Lopes2e594fa2012-12-31 18:01:36 +0000575 if (bothKnown(TrueSide) && bothKnown(FalseSide) && TrueSide == FalseSide)
Nuno Lopes9e72a792012-06-21 15:45:28 +0000576 return TrueSide;
577 return unknown();
578}
579
580SizeOffsetType ObjectSizeOffsetVisitor::visitUndefValue(UndefValue&) {
581 return std::make_pair(Zero, Zero);
582}
583
584SizeOffsetType ObjectSizeOffsetVisitor::visitInstruction(Instruction &I) {
585 DEBUG(dbgs() << "ObjectSizeOffsetVisitor unknown instruction:" << I << '\n');
586 return unknown();
587}
588
589
Micah Villmow3574eca2012-10-08 16:38:25 +0000590ObjectSizeOffsetEvaluator::ObjectSizeOffsetEvaluator(const DataLayout *TD,
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000591 const TargetLibraryInfo *TLI,
Chandler Carruthece6c6b2012-11-01 08:07:29 +0000592 LLVMContext &Context)
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000593: TD(TD), TLI(TLI), Context(Context), Builder(Context, TargetFolder(TD)) {
Chandler Carruthece6c6b2012-11-01 08:07:29 +0000594 IntTy = TD->getIntPtrType(Context);
Nuno Lopes9e72a792012-06-21 15:45:28 +0000595 Zero = ConstantInt::get(IntTy, 0);
596}
597
598SizeOffsetEvalType ObjectSizeOffsetEvaluator::compute(Value *V) {
599 SizeOffsetEvalType Result = compute_(V);
600
601 if (!bothKnown(Result)) {
602 // erase everything that was computed in this iteration from the cache, so
603 // that no dangling references are left behind. We could be a bit smarter if
604 // we kept a dependency graph. It's probably not worth the complexity.
605 for (PtrSetTy::iterator I=SeenVals.begin(), E=SeenVals.end(); I != E; ++I) {
606 CacheMapTy::iterator CacheIt = CacheMap.find(*I);
607 // non-computable results can be safely cached
608 if (CacheIt != CacheMap.end() && anyKnown(CacheIt->second))
609 CacheMap.erase(CacheIt);
610 }
611 }
612
613 SeenVals.clear();
614 return Result;
615}
616
617SizeOffsetEvalType ObjectSizeOffsetEvaluator::compute_(Value *V) {
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000618 ObjectSizeOffsetVisitor Visitor(TD, TLI, Context);
Nuno Lopes9e72a792012-06-21 15:45:28 +0000619 SizeOffsetType Const = Visitor.compute(V);
620 if (Visitor.bothKnown(Const))
621 return std::make_pair(ConstantInt::get(Context, Const.first),
622 ConstantInt::get(Context, Const.second));
623
624 V = V->stripPointerCasts();
625
626 // check cache
627 CacheMapTy::iterator CacheIt = CacheMap.find(V);
628 if (CacheIt != CacheMap.end())
629 return CacheIt->second;
630
631 // always generate code immediately before the instruction being
632 // processed, so that the generated code dominates the same BBs
633 Instruction *PrevInsertPoint = Builder.GetInsertPoint();
634 if (Instruction *I = dyn_cast<Instruction>(V))
635 Builder.SetInsertPoint(I);
636
Nuno Lopes9e72a792012-06-21 15:45:28 +0000637 // now compute the size and offset
638 SizeOffsetEvalType Result;
Benjamin Kramer2f084332013-09-29 19:39:13 +0000639
640 // Record the pointers that were handled in this run, so that they can be
641 // cleaned later if something fails. We also use this set to break cycles that
642 // can occur in dead code.
643 if (!SeenVals.insert(V)) {
644 Result = unknown();
645 } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
Nuno Lopes9e72a792012-06-21 15:45:28 +0000646 Result = visitGEPOperator(*GEP);
647 } else if (Instruction *I = dyn_cast<Instruction>(V)) {
648 Result = visit(*I);
649 } else if (isa<Argument>(V) ||
650 (isa<ConstantExpr>(V) &&
651 cast<ConstantExpr>(V)->getOpcode() == Instruction::IntToPtr) ||
Nuno Lopes41be2fb2012-12-31 16:23:48 +0000652 isa<GlobalAlias>(V) ||
Nuno Lopes9e72a792012-06-21 15:45:28 +0000653 isa<GlobalVariable>(V)) {
654 // ignore values where we cannot do more than what ObjectSizeVisitor can
655 Result = unknown();
656 } else {
657 DEBUG(dbgs() << "ObjectSizeOffsetEvaluator::compute() unhandled value: "
658 << *V << '\n');
659 Result = unknown();
660 }
661
662 if (PrevInsertPoint)
663 Builder.SetInsertPoint(PrevInsertPoint);
664
665 // Don't reuse CacheIt since it may be invalid at this point.
666 CacheMap[V] = Result;
667 return Result;
668}
669
670SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitAllocaInst(AllocaInst &I) {
671 if (!I.getAllocatedType()->isSized())
672 return unknown();
673
674 // must be a VLA
675 assert(I.isArrayAllocation());
676 Value *ArraySize = I.getArraySize();
677 Value *Size = ConstantInt::get(ArraySize->getType(),
678 TD->getTypeAllocSize(I.getAllocatedType()));
679 Size = Builder.CreateMul(Size, ArraySize);
680 return std::make_pair(Size, Zero);
681}
682
683SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitCallSite(CallSite CS) {
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000684 const AllocFnsTy *FnData = getAllocationData(CS.getInstruction(), AnyAlloc,
685 TLI);
Nuno Lopes9e72a792012-06-21 15:45:28 +0000686 if (!FnData)
687 return unknown();
688
689 // handle strdup-like functions separately
690 if (FnData->AllocTy == StrDupLike) {
Nuno Lopes6e699bf2012-07-25 18:49:28 +0000691 // TODO
692 return unknown();
Nuno Lopes9e72a792012-06-21 15:45:28 +0000693 }
694
Nuno Lopes034dd6c2012-06-21 16:47:58 +0000695 Value *FirstArg = CS.getArgument(FnData->FstParam);
696 FirstArg = Builder.CreateZExt(FirstArg, IntTy);
Nuno Lopesef22f042012-06-21 18:38:26 +0000697 if (FnData->SndParam < 0)
Nuno Lopes9e72a792012-06-21 15:45:28 +0000698 return std::make_pair(FirstArg, Zero);
699
700 Value *SecondArg = CS.getArgument(FnData->SndParam);
Nuno Lopes034dd6c2012-06-21 16:47:58 +0000701 SecondArg = Builder.CreateZExt(SecondArg, IntTy);
Nuno Lopes9e72a792012-06-21 15:45:28 +0000702 Value *Size = Builder.CreateMul(FirstArg, SecondArg);
703 return std::make_pair(Size, Zero);
704
705 // TODO: handle more standard functions (+ wchar cousins):
Nuno Lopes6e699bf2012-07-25 18:49:28 +0000706 // - strdup / strndup
Nuno Lopes9e72a792012-06-21 15:45:28 +0000707 // - strcpy / strncpy
708 // - strcat / strncat
709 // - memcpy / memmove
Nuno Lopes6e699bf2012-07-25 18:49:28 +0000710 // - strcat / strncat
Nuno Lopes9e72a792012-06-21 15:45:28 +0000711 // - memset
712}
713
714SizeOffsetEvalType
Nuno Lopes41a3f252012-06-28 16:34:03 +0000715ObjectSizeOffsetEvaluator::visitExtractElementInst(ExtractElementInst&) {
716 return unknown();
717}
718
719SizeOffsetEvalType
720ObjectSizeOffsetEvaluator::visitExtractValueInst(ExtractValueInst&) {
721 return unknown();
722}
723
724SizeOffsetEvalType
Nuno Lopes9e72a792012-06-21 15:45:28 +0000725ObjectSizeOffsetEvaluator::visitGEPOperator(GEPOperator &GEP) {
726 SizeOffsetEvalType PtrData = compute_(GEP.getPointerOperand());
727 if (!bothKnown(PtrData))
728 return unknown();
729
Nuno Lopesc606c3f2012-07-20 23:07:40 +0000730 Value *Offset = EmitGEPOffset(&Builder, *TD, &GEP, /*NoAssumptions=*/true);
Nuno Lopes9e72a792012-06-21 15:45:28 +0000731 Offset = Builder.CreateAdd(PtrData.second, Offset);
732 return std::make_pair(PtrData.first, Offset);
733}
734
735SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitIntToPtrInst(IntToPtrInst&) {
736 // clueless
737 return unknown();
738}
739
740SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitLoadInst(LoadInst&) {
741 return unknown();
742}
743
744SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitPHINode(PHINode &PHI) {
745 // create 2 PHIs: one for size and another for offset
746 PHINode *SizePHI = Builder.CreatePHI(IntTy, PHI.getNumIncomingValues());
747 PHINode *OffsetPHI = Builder.CreatePHI(IntTy, PHI.getNumIncomingValues());
748
749 // insert right away in the cache to handle recursive PHIs
750 CacheMap[&PHI] = std::make_pair(SizePHI, OffsetPHI);
751
752 // compute offset/size for each PHI incoming pointer
753 for (unsigned i = 0, e = PHI.getNumIncomingValues(); i != e; ++i) {
754 Builder.SetInsertPoint(PHI.getIncomingBlock(i)->getFirstInsertionPt());
755 SizeOffsetEvalType EdgeData = compute_(PHI.getIncomingValue(i));
756
757 if (!bothKnown(EdgeData)) {
758 OffsetPHI->replaceAllUsesWith(UndefValue::get(IntTy));
759 OffsetPHI->eraseFromParent();
760 SizePHI->replaceAllUsesWith(UndefValue::get(IntTy));
761 SizePHI->eraseFromParent();
762 return unknown();
763 }
764 SizePHI->addIncoming(EdgeData.first, PHI.getIncomingBlock(i));
765 OffsetPHI->addIncoming(EdgeData.second, PHI.getIncomingBlock(i));
766 }
Nuno Lopes0dff5322012-07-03 17:13:25 +0000767
768 Value *Size = SizePHI, *Offset = OffsetPHI, *Tmp;
769 if ((Tmp = SizePHI->hasConstantValue())) {
770 Size = Tmp;
771 SizePHI->replaceAllUsesWith(Size);
772 SizePHI->eraseFromParent();
773 }
774 if ((Tmp = OffsetPHI->hasConstantValue())) {
775 Offset = Tmp;
776 OffsetPHI->replaceAllUsesWith(Offset);
777 OffsetPHI->eraseFromParent();
778 }
779 return std::make_pair(Size, Offset);
Nuno Lopes9e72a792012-06-21 15:45:28 +0000780}
781
782SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitSelectInst(SelectInst &I) {
783 SizeOffsetEvalType TrueSide = compute_(I.getTrueValue());
784 SizeOffsetEvalType FalseSide = compute_(I.getFalseValue());
785
786 if (!bothKnown(TrueSide) || !bothKnown(FalseSide))
787 return unknown();
788 if (TrueSide == FalseSide)
789 return TrueSide;
790
791 Value *Size = Builder.CreateSelect(I.getCondition(), TrueSide.first,
792 FalseSide.first);
793 Value *Offset = Builder.CreateSelect(I.getCondition(), TrueSide.second,
794 FalseSide.second);
795 return std::make_pair(Size, Offset);
796}
797
798SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitInstruction(Instruction &I) {
799 DEBUG(dbgs() << "ObjectSizeOffsetEvaluator unknown instruction:" << I <<'\n');
800 return unknown();
801}