b19ecadd31619ed627e5f7f7d11a998c9a9f11f4
[oota-llvm.git] / lib / Analysis / MemoryBuiltins.cpp
1 //===------ MemoryBuiltins.cpp - Identify calls to memory builtins --------===//
2 //
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 //
10 // This family of functions identifies calls to builtin functions that allocate
11 // or free memory.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "llvm/Analysis/MemoryBuiltins.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/ADT/Statistic.h"
18 #include "llvm/Analysis/TargetLibraryInfo.h"
19 #include "llvm/Analysis/ValueTracking.h"
20 #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"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/Support/MathExtras.h"
28 #include "llvm/Support/raw_ostream.h"
29 #include "llvm/Transforms/Utils/Local.h"
30 using namespace llvm;
31
32 #define DEBUG_TYPE "memory-builtins"
33
34 enum AllocType : uint8_t {
35   OpNewLike          = 1<<0, // allocates; never returns null
36   MallocLike         = 1<<1 | OpNewLike, // allocates; may return null
37   CallocLike         = 1<<2, // allocates + bzero
38   ReallocLike        = 1<<3, // reallocates
39   StrDupLike         = 1<<4,
40   AllocLike          = MallocLike | CallocLike | StrDupLike,
41   AnyAlloc           = AllocLike | ReallocLike
42 };
43
44 struct AllocFnsTy {
45   LibFunc::Func Func;
46   AllocType AllocTy;
47   unsigned char NumParams;
48   // First and Second size parameters (or -1 if unused)
49   signed char FstParam, SndParam;
50 };
51
52 // FIXME: certain users need more information. E.g., SimplifyLibCalls needs to
53 // know which functions are nounwind, noalias, nocapture parameters, etc.
54 static const AllocFnsTy AllocationFnData[] = {
55   {LibFunc::malloc,              MallocLike,  1, 0,  -1},
56   {LibFunc::valloc,              MallocLike,  1, 0,  -1},
57   {LibFunc::Znwj,                OpNewLike,   1, 0,  -1}, // new(unsigned int)
58   {LibFunc::ZnwjRKSt9nothrow_t,  MallocLike,  2, 0,  -1}, // new(unsigned int, nothrow)
59   {LibFunc::Znwm,                OpNewLike,   1, 0,  -1}, // new(unsigned long)
60   {LibFunc::ZnwmRKSt9nothrow_t,  MallocLike,  2, 0,  -1}, // new(unsigned long, nothrow)
61   {LibFunc::Znaj,                OpNewLike,   1, 0,  -1}, // new[](unsigned int)
62   {LibFunc::ZnajRKSt9nothrow_t,  MallocLike,  2, 0,  -1}, // new[](unsigned int, nothrow)
63   {LibFunc::Znam,                OpNewLike,   1, 0,  -1}, // new[](unsigned long)
64   {LibFunc::ZnamRKSt9nothrow_t,  MallocLike,  2, 0,  -1}, // new[](unsigned long, nothrow)
65   {LibFunc::msvc_new_int,         OpNewLike,   1, 0,  -1}, // new(unsigned int)
66   {LibFunc::msvc_new_int_nothrow, MallocLike,  2, 0,  -1}, // new(unsigned int, nothrow)
67   {LibFunc::msvc_new_longlong,         OpNewLike,   1, 0,  -1}, // new(unsigned long long)
68   {LibFunc::msvc_new_longlong_nothrow, MallocLike,  2, 0,  -1}, // new(unsigned long long, nothrow)
69   {LibFunc::msvc_new_array_int,         OpNewLike,   1, 0,  -1}, // new[](unsigned int)
70   {LibFunc::msvc_new_array_int_nothrow, MallocLike,  2, 0,  -1}, // new[](unsigned int, nothrow)
71   {LibFunc::msvc_new_array_longlong,         OpNewLike,   1, 0,  -1}, // new[](unsigned long long)
72   {LibFunc::msvc_new_array_longlong_nothrow, MallocLike,  2, 0,  -1}, // new[](unsigned long long, nothrow)
73   {LibFunc::calloc,              CallocLike,  2, 0,   1},
74   {LibFunc::realloc,             ReallocLike, 2, 1,  -1},
75   {LibFunc::reallocf,            ReallocLike, 2, 1,  -1},
76   {LibFunc::strdup,              StrDupLike,  1, -1, -1},
77   {LibFunc::strndup,             StrDupLike,  2, 1,  -1}
78   // TODO: Handle "int posix_memalign(void **, size_t, size_t)"
79 };
80
81
82 static Function *getCalledFunction(const Value *V, bool LookThroughBitCast) {
83   if (LookThroughBitCast)
84     V = V->stripPointerCasts();
85
86   CallSite CS(const_cast<Value*>(V));
87   if (!CS.getInstruction())
88     return nullptr;
89
90   if (CS.isNoBuiltin())
91     return nullptr;
92
93   Function *Callee = CS.getCalledFunction();
94   if (!Callee || !Callee->isDeclaration())
95     return nullptr;
96   return Callee;
97 }
98
99 /// \brief Returns the allocation data for the given value if it is a call to a
100 /// known allocation function, and NULL otherwise.
101 static const AllocFnsTy *getAllocationData(const Value *V, AllocType AllocTy,
102                                            const TargetLibraryInfo *TLI,
103                                            bool LookThroughBitCast = false) {
104   // Skip intrinsics
105   if (isa<IntrinsicInst>(V))
106     return nullptr;
107
108   Function *Callee = getCalledFunction(V, LookThroughBitCast);
109   if (!Callee)
110     return nullptr;
111
112   // Make sure that the function is available.
113   StringRef FnName = Callee->getName();
114   LibFunc::Func TLIFn;
115   if (!TLI || !TLI->getLibFunc(FnName, TLIFn) || !TLI->has(TLIFn))
116     return nullptr;
117
118   const AllocFnsTy *FnData =
119       std::find_if(std::begin(AllocationFnData), std::end(AllocationFnData),
120                    [TLIFn](const AllocFnsTy &Fn) { return Fn.Func == TLIFn; });
121
122   if (FnData == std::end(AllocationFnData))
123     return nullptr;
124
125   if ((FnData->AllocTy & AllocTy) != FnData->AllocTy)
126     return nullptr;
127
128   // Check function prototype.
129   int FstParam = FnData->FstParam;
130   int SndParam = FnData->SndParam;
131   FunctionType *FTy = Callee->getFunctionType();
132
133   if (FTy->getReturnType() == Type::getInt8PtrTy(FTy->getContext()) &&
134       FTy->getNumParams() == FnData->NumParams &&
135       (FstParam < 0 ||
136        (FTy->getParamType(FstParam)->isIntegerTy(32) ||
137         FTy->getParamType(FstParam)->isIntegerTy(64))) &&
138       (SndParam < 0 ||
139        FTy->getParamType(SndParam)->isIntegerTy(32) ||
140        FTy->getParamType(SndParam)->isIntegerTy(64)))
141     return FnData;
142   return nullptr;
143 }
144
145 static bool hasNoAliasAttr(const Value *V, bool LookThroughBitCast) {
146   ImmutableCallSite CS(LookThroughBitCast ? V->stripPointerCasts() : V);
147   return CS && CS.hasFnAttr(Attribute::NoAlias);
148 }
149
150
151 /// \brief Tests if a value is a call or invoke to a library function that
152 /// allocates or reallocates memory (either malloc, calloc, realloc, or strdup
153 /// like).
154 bool llvm::isAllocationFn(const Value *V, const TargetLibraryInfo *TLI,
155                           bool LookThroughBitCast) {
156   return getAllocationData(V, AnyAlloc, TLI, LookThroughBitCast);
157 }
158
159 /// \brief Tests if a value is a call or invoke to a function that returns a
160 /// NoAlias pointer (including malloc/calloc/realloc/strdup-like functions).
161 bool llvm::isNoAliasFn(const Value *V, const TargetLibraryInfo *TLI,
162                        bool LookThroughBitCast) {
163   // it's safe to consider realloc as noalias since accessing the original
164   // pointer is undefined behavior
165   return isAllocationFn(V, TLI, LookThroughBitCast) ||
166          hasNoAliasAttr(V, LookThroughBitCast);
167 }
168
169 /// \brief Tests if a value is a call or invoke to a library function that
170 /// allocates uninitialized memory (such as malloc).
171 bool llvm::isMallocLikeFn(const Value *V, const TargetLibraryInfo *TLI,
172                           bool LookThroughBitCast) {
173   return getAllocationData(V, MallocLike, TLI, LookThroughBitCast);
174 }
175
176 /// \brief Tests if a value is a call or invoke to a library function that
177 /// allocates zero-filled memory (such as calloc).
178 bool llvm::isCallocLikeFn(const Value *V, const TargetLibraryInfo *TLI,
179                           bool LookThroughBitCast) {
180   return getAllocationData(V, CallocLike, TLI, LookThroughBitCast);
181 }
182
183 /// \brief Tests if a value is a call or invoke to a library function that
184 /// allocates memory (either malloc, calloc, or strdup like).
185 bool llvm::isAllocLikeFn(const Value *V, const TargetLibraryInfo *TLI,
186                          bool LookThroughBitCast) {
187   return getAllocationData(V, AllocLike, TLI, LookThroughBitCast);
188 }
189
190 /// \brief Tests if a value is a call or invoke to a library function that
191 /// allocates memory and never returns null (such as operator new).
192 bool llvm::isOperatorNewLikeFn(const Value *V, const TargetLibraryInfo *TLI,
193                                bool LookThroughBitCast) {
194   return getAllocationData(V, OpNewLike, TLI, LookThroughBitCast);
195 }
196
197 /// extractMallocCall - Returns the corresponding CallInst if the instruction
198 /// is a malloc call.  Since CallInst::CreateMalloc() only creates calls, we
199 /// ignore InvokeInst here.
200 const CallInst *llvm::extractMallocCall(const Value *I,
201                                         const TargetLibraryInfo *TLI) {
202   return isMallocLikeFn(I, TLI) ? dyn_cast<CallInst>(I) : nullptr;
203 }
204
205 static Value *computeArraySize(const CallInst *CI, const DataLayout &DL,
206                                const TargetLibraryInfo *TLI,
207                                bool LookThroughSExt = false) {
208   if (!CI)
209     return nullptr;
210
211   // The size of the malloc's result type must be known to determine array size.
212   Type *T = getMallocAllocatedType(CI, TLI);
213   if (!T || !T->isSized())
214     return nullptr;
215
216   unsigned ElementSize = DL.getTypeAllocSize(T);
217   if (StructType *ST = dyn_cast<StructType>(T))
218     ElementSize = DL.getStructLayout(ST)->getSizeInBytes();
219
220   // If malloc call's arg can be determined to be a multiple of ElementSize,
221   // return the multiple.  Otherwise, return NULL.
222   Value *MallocArg = CI->getArgOperand(0);
223   Value *Multiple = nullptr;
224   if (ComputeMultiple(MallocArg, ElementSize, Multiple,
225                       LookThroughSExt))
226     return Multiple;
227
228   return nullptr;
229 }
230
231 /// getMallocType - Returns the PointerType resulting from the malloc call.
232 /// The PointerType depends on the number of bitcast uses of the malloc call:
233 ///   0: PointerType is the calls' return type.
234 ///   1: PointerType is the bitcast's result type.
235 ///  >1: Unique PointerType cannot be determined, return NULL.
236 PointerType *llvm::getMallocType(const CallInst *CI,
237                                  const TargetLibraryInfo *TLI) {
238   assert(isMallocLikeFn(CI, TLI) && "getMallocType and not malloc call");
239
240   PointerType *MallocType = nullptr;
241   unsigned NumOfBitCastUses = 0;
242
243   // Determine if CallInst has a bitcast use.
244   for (Value::const_user_iterator UI = CI->user_begin(), E = CI->user_end();
245        UI != E;)
246     if (const BitCastInst *BCI = dyn_cast<BitCastInst>(*UI++)) {
247       MallocType = cast<PointerType>(BCI->getDestTy());
248       NumOfBitCastUses++;
249     }
250
251   // Malloc call has 1 bitcast use, so type is the bitcast's destination type.
252   if (NumOfBitCastUses == 1)
253     return MallocType;
254
255   // Malloc call was not bitcast, so type is the malloc function's return type.
256   if (NumOfBitCastUses == 0)
257     return cast<PointerType>(CI->getType());
258
259   // Type could not be determined.
260   return nullptr;
261 }
262
263 /// getMallocAllocatedType - Returns the Type allocated by malloc call.
264 /// The Type depends on the number of bitcast uses of the malloc call:
265 ///   0: PointerType is the malloc calls' return type.
266 ///   1: PointerType is the bitcast's result type.
267 ///  >1: Unique PointerType cannot be determined, return NULL.
268 Type *llvm::getMallocAllocatedType(const CallInst *CI,
269                                    const TargetLibraryInfo *TLI) {
270   PointerType *PT = getMallocType(CI, TLI);
271   return PT ? PT->getElementType() : nullptr;
272 }
273
274 /// getMallocArraySize - Returns the array size of a malloc call.  If the
275 /// argument passed to malloc is a multiple of the size of the malloced type,
276 /// then return that multiple.  For non-array mallocs, the multiple is
277 /// constant 1.  Otherwise, return NULL for mallocs whose array size cannot be
278 /// determined.
279 Value *llvm::getMallocArraySize(CallInst *CI, const DataLayout &DL,
280                                 const TargetLibraryInfo *TLI,
281                                 bool LookThroughSExt) {
282   assert(isMallocLikeFn(CI, TLI) && "getMallocArraySize and not malloc call");
283   return computeArraySize(CI, DL, TLI, LookThroughSExt);
284 }
285
286
287 /// extractCallocCall - Returns the corresponding CallInst if the instruction
288 /// is a calloc call.
289 const CallInst *llvm::extractCallocCall(const Value *I,
290                                         const TargetLibraryInfo *TLI) {
291   return isCallocLikeFn(I, TLI) ? cast<CallInst>(I) : nullptr;
292 }
293
294
295 /// isFreeCall - Returns non-null if the value is a call to the builtin free()
296 const CallInst *llvm::isFreeCall(const Value *I, const TargetLibraryInfo *TLI) {
297   const CallInst *CI = dyn_cast<CallInst>(I);
298   if (!CI || isa<IntrinsicInst>(CI))
299     return nullptr;
300   Function *Callee = CI->getCalledFunction();
301   if (Callee == nullptr)
302     return nullptr;
303
304   StringRef FnName = Callee->getName();
305   LibFunc::Func TLIFn;
306   if (!TLI || !TLI->getLibFunc(FnName, TLIFn) || !TLI->has(TLIFn))
307     return nullptr;
308
309   unsigned ExpectedNumParams;
310   if (TLIFn == LibFunc::free ||
311       TLIFn == LibFunc::ZdlPv || // operator delete(void*)
312       TLIFn == LibFunc::ZdaPv || // operator delete[](void*)
313       TLIFn == LibFunc::msvc_delete_ptr32 || // operator delete(void*)
314       TLIFn == LibFunc::msvc_delete_ptr64 || // operator delete(void*)
315       TLIFn == LibFunc::msvc_delete_array_ptr32 || // operator delete[](void*)
316       TLIFn == LibFunc::msvc_delete_array_ptr64)   // operator delete[](void*)
317     ExpectedNumParams = 1;
318   else if (TLIFn == LibFunc::ZdlPvj ||              // delete(void*, uint)
319            TLIFn == LibFunc::ZdlPvm ||              // delete(void*, ulong)
320            TLIFn == LibFunc::ZdlPvRKSt9nothrow_t || // delete(void*, nothrow)
321            TLIFn == LibFunc::ZdaPvj ||              // delete[](void*, uint)
322            TLIFn == LibFunc::ZdaPvm ||              // delete[](void*, ulong)
323            TLIFn == LibFunc::ZdaPvRKSt9nothrow_t || // delete[](void*, nothrow)
324            TLIFn == LibFunc::msvc_delete_ptr32_int ||      // delete(void*, uint)
325            TLIFn == LibFunc::msvc_delete_ptr64_longlong || // delete(void*, ulonglong)
326            TLIFn == LibFunc::msvc_delete_ptr32_nothrow || // delete(void*, nothrow)
327            TLIFn == LibFunc::msvc_delete_ptr64_nothrow || // delete(void*, nothrow)
328            TLIFn == LibFunc::msvc_delete_array_ptr32_int ||      // delete[](void*, uint)
329            TLIFn == LibFunc::msvc_delete_array_ptr64_longlong || // delete[](void*, ulonglong)
330            TLIFn == LibFunc::msvc_delete_array_ptr32_nothrow || // delete[](void*, nothrow)
331            TLIFn == LibFunc::msvc_delete_array_ptr64_nothrow)   // delete[](void*, nothrow)
332     ExpectedNumParams = 2;
333   else
334     return nullptr;
335
336   // Check free prototype.
337   // FIXME: workaround for PR5130, this will be obsolete when a nobuiltin
338   // attribute will exist.
339   FunctionType *FTy = Callee->getFunctionType();
340   if (!FTy->getReturnType()->isVoidTy())
341     return nullptr;
342   if (FTy->getNumParams() != ExpectedNumParams)
343     return nullptr;
344   if (FTy->getParamType(0) != Type::getInt8PtrTy(Callee->getContext()))
345     return nullptr;
346
347   return CI;
348 }
349
350
351
352 //===----------------------------------------------------------------------===//
353 //  Utility functions to compute size of objects.
354 //
355
356
357 /// \brief Compute the size of the object pointed by Ptr. Returns true and the
358 /// object size in Size if successful, and false otherwise.
359 /// If RoundToAlign is true, then Size is rounded up to the aligment of allocas,
360 /// byval arguments, and global variables.
361 bool llvm::getObjectSize(const Value *Ptr, uint64_t &Size, const DataLayout &DL,
362                          const TargetLibraryInfo *TLI, bool RoundToAlign) {
363   ObjectSizeOffsetVisitor Visitor(DL, TLI, Ptr->getContext(), RoundToAlign);
364   SizeOffsetType Data = Visitor.compute(const_cast<Value*>(Ptr));
365   if (!Visitor.bothKnown(Data))
366     return false;
367
368   APInt ObjSize = Data.first, Offset = Data.second;
369   // check for overflow
370   if (Offset.slt(0) || ObjSize.ult(Offset))
371     Size = 0;
372   else
373     Size = (ObjSize - Offset).getZExtValue();
374   return true;
375 }
376
377
378 STATISTIC(ObjectVisitorArgument,
379           "Number of arguments with unsolved size and offset");
380 STATISTIC(ObjectVisitorLoad,
381           "Number of load instructions with unsolved size and offset");
382
383
384 APInt ObjectSizeOffsetVisitor::align(APInt Size, uint64_t Align) {
385   if (RoundToAlign && Align)
386     return APInt(IntTyBits, RoundUpToAlignment(Size.getZExtValue(), Align));
387   return Size;
388 }
389
390 ObjectSizeOffsetVisitor::ObjectSizeOffsetVisitor(const DataLayout &DL,
391                                                  const TargetLibraryInfo *TLI,
392                                                  LLVMContext &Context,
393                                                  bool RoundToAlign)
394     : DL(DL), TLI(TLI), RoundToAlign(RoundToAlign) {
395   // Pointer size must be rechecked for each object visited since it could have
396   // a different address space.
397 }
398
399 SizeOffsetType ObjectSizeOffsetVisitor::compute(Value *V) {
400   IntTyBits = DL.getPointerTypeSizeInBits(V->getType());
401   Zero = APInt::getNullValue(IntTyBits);
402
403   V = V->stripPointerCasts();
404   if (Instruction *I = dyn_cast<Instruction>(V)) {
405     // If we have already seen this instruction, bail out. Cycles can happen in
406     // unreachable code after constant propagation.
407     if (!SeenInsts.insert(I).second)
408       return unknown();
409
410     if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
411       return visitGEPOperator(*GEP);
412     return visit(*I);
413   }
414   if (Argument *A = dyn_cast<Argument>(V))
415     return visitArgument(*A);
416   if (ConstantPointerNull *P = dyn_cast<ConstantPointerNull>(V))
417     return visitConstantPointerNull(*P);
418   if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
419     return visitGlobalAlias(*GA);
420   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
421     return visitGlobalVariable(*GV);
422   if (UndefValue *UV = dyn_cast<UndefValue>(V))
423     return visitUndefValue(*UV);
424   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
425     if (CE->getOpcode() == Instruction::IntToPtr)
426       return unknown(); // clueless
427     if (CE->getOpcode() == Instruction::GetElementPtr)
428       return visitGEPOperator(cast<GEPOperator>(*CE));
429   }
430
431   DEBUG(dbgs() << "ObjectSizeOffsetVisitor::compute() unhandled value: " << *V
432         << '\n');
433   return unknown();
434 }
435
436 SizeOffsetType ObjectSizeOffsetVisitor::visitAllocaInst(AllocaInst &I) {
437   if (!I.getAllocatedType()->isSized())
438     return unknown();
439
440   APInt Size(IntTyBits, DL.getTypeAllocSize(I.getAllocatedType()));
441   if (!I.isArrayAllocation())
442     return std::make_pair(align(Size, I.getAlignment()), Zero);
443
444   Value *ArraySize = I.getArraySize();
445   if (const ConstantInt *C = dyn_cast<ConstantInt>(ArraySize)) {
446     Size *= C->getValue().zextOrSelf(IntTyBits);
447     return std::make_pair(align(Size, I.getAlignment()), Zero);
448   }
449   return unknown();
450 }
451
452 SizeOffsetType ObjectSizeOffsetVisitor::visitArgument(Argument &A) {
453   // no interprocedural analysis is done at the moment
454   if (!A.hasByValOrInAllocaAttr()) {
455     ++ObjectVisitorArgument;
456     return unknown();
457   }
458   PointerType *PT = cast<PointerType>(A.getType());
459   APInt Size(IntTyBits, DL.getTypeAllocSize(PT->getElementType()));
460   return std::make_pair(align(Size, A.getParamAlignment()), Zero);
461 }
462
463 SizeOffsetType ObjectSizeOffsetVisitor::visitCallSite(CallSite CS) {
464   const AllocFnsTy *FnData = getAllocationData(CS.getInstruction(), AnyAlloc,
465                                                TLI);
466   if (!FnData)
467     return unknown();
468
469   // handle strdup-like functions separately
470   if (FnData->AllocTy == StrDupLike) {
471     APInt Size(IntTyBits, GetStringLength(CS.getArgument(0)));
472     if (!Size)
473       return unknown();
474
475     // strndup limits strlen
476     if (FnData->FstParam > 0) {
477       ConstantInt *Arg= dyn_cast<ConstantInt>(CS.getArgument(FnData->FstParam));
478       if (!Arg)
479         return unknown();
480
481       APInt MaxSize = Arg->getValue().zextOrSelf(IntTyBits);
482       if (Size.ugt(MaxSize))
483         Size = MaxSize + 1;
484     }
485     return std::make_pair(Size, Zero);
486   }
487
488   ConstantInt *Arg = dyn_cast<ConstantInt>(CS.getArgument(FnData->FstParam));
489   if (!Arg)
490     return unknown();
491
492   APInt Size = Arg->getValue().zextOrSelf(IntTyBits);
493   // size determined by just 1 parameter
494   if (FnData->SndParam < 0)
495     return std::make_pair(Size, Zero);
496
497   Arg = dyn_cast<ConstantInt>(CS.getArgument(FnData->SndParam));
498   if (!Arg)
499     return unknown();
500
501   Size *= Arg->getValue().zextOrSelf(IntTyBits);
502   return std::make_pair(Size, Zero);
503
504   // TODO: handle more standard functions (+ wchar cousins):
505   // - strdup / strndup
506   // - strcpy / strncpy
507   // - strcat / strncat
508   // - memcpy / memmove
509   // - strcat / strncat
510   // - memset
511 }
512
513 SizeOffsetType
514 ObjectSizeOffsetVisitor::visitConstantPointerNull(ConstantPointerNull&) {
515   return std::make_pair(Zero, Zero);
516 }
517
518 SizeOffsetType
519 ObjectSizeOffsetVisitor::visitExtractElementInst(ExtractElementInst&) {
520   return unknown();
521 }
522
523 SizeOffsetType
524 ObjectSizeOffsetVisitor::visitExtractValueInst(ExtractValueInst&) {
525   // Easy cases were already folded by previous passes.
526   return unknown();
527 }
528
529 SizeOffsetType ObjectSizeOffsetVisitor::visitGEPOperator(GEPOperator &GEP) {
530   SizeOffsetType PtrData = compute(GEP.getPointerOperand());
531   APInt Offset(IntTyBits, 0);
532   if (!bothKnown(PtrData) || !GEP.accumulateConstantOffset(DL, Offset))
533     return unknown();
534
535   return std::make_pair(PtrData.first, PtrData.second + Offset);
536 }
537
538 SizeOffsetType ObjectSizeOffsetVisitor::visitGlobalAlias(GlobalAlias &GA) {
539   if (GA.mayBeOverridden())
540     return unknown();
541   return compute(GA.getAliasee());
542 }
543
544 SizeOffsetType ObjectSizeOffsetVisitor::visitGlobalVariable(GlobalVariable &GV){
545   if (!GV.hasDefinitiveInitializer())
546     return unknown();
547
548   APInt Size(IntTyBits, DL.getTypeAllocSize(GV.getType()->getElementType()));
549   return std::make_pair(align(Size, GV.getAlignment()), Zero);
550 }
551
552 SizeOffsetType ObjectSizeOffsetVisitor::visitIntToPtrInst(IntToPtrInst&) {
553   // clueless
554   return unknown();
555 }
556
557 SizeOffsetType ObjectSizeOffsetVisitor::visitLoadInst(LoadInst&) {
558   ++ObjectVisitorLoad;
559   return unknown();
560 }
561
562 SizeOffsetType ObjectSizeOffsetVisitor::visitPHINode(PHINode&) {
563   // too complex to analyze statically.
564   return unknown();
565 }
566
567 SizeOffsetType ObjectSizeOffsetVisitor::visitSelectInst(SelectInst &I) {
568   SizeOffsetType TrueSide  = compute(I.getTrueValue());
569   SizeOffsetType FalseSide = compute(I.getFalseValue());
570   if (bothKnown(TrueSide) && bothKnown(FalseSide) && TrueSide == FalseSide)
571     return TrueSide;
572   return unknown();
573 }
574
575 SizeOffsetType ObjectSizeOffsetVisitor::visitUndefValue(UndefValue&) {
576   return std::make_pair(Zero, Zero);
577 }
578
579 SizeOffsetType ObjectSizeOffsetVisitor::visitInstruction(Instruction &I) {
580   DEBUG(dbgs() << "ObjectSizeOffsetVisitor unknown instruction:" << I << '\n');
581   return unknown();
582 }
583
584 ObjectSizeOffsetEvaluator::ObjectSizeOffsetEvaluator(
585     const DataLayout &DL, const TargetLibraryInfo *TLI, LLVMContext &Context,
586     bool RoundToAlign)
587     : DL(DL), TLI(TLI), Context(Context), Builder(Context, TargetFolder(DL)),
588       RoundToAlign(RoundToAlign) {
589   // IntTy and Zero must be set for each compute() since the address space may
590   // be different for later objects.
591 }
592
593 SizeOffsetEvalType ObjectSizeOffsetEvaluator::compute(Value *V) {
594   // XXX - Are vectors of pointers possible here?
595   IntTy = cast<IntegerType>(DL.getIntPtrType(V->getType()));
596   Zero = ConstantInt::get(IntTy, 0);
597
598   SizeOffsetEvalType Result = compute_(V);
599
600   if (!bothKnown(Result)) {
601     // erase everything that was computed in this iteration from the cache, so
602     // that no dangling references are left behind. We could be a bit smarter if
603     // we kept a dependency graph. It's probably not worth the complexity.
604     for (PtrSetTy::iterator I=SeenVals.begin(), E=SeenVals.end(); I != E; ++I) {
605       CacheMapTy::iterator CacheIt = CacheMap.find(*I);
606       // non-computable results can be safely cached
607       if (CacheIt != CacheMap.end() && anyKnown(CacheIt->second))
608         CacheMap.erase(CacheIt);
609     }
610   }
611
612   SeenVals.clear();
613   return Result;
614 }
615
616 SizeOffsetEvalType ObjectSizeOffsetEvaluator::compute_(Value *V) {
617   ObjectSizeOffsetVisitor Visitor(DL, TLI, Context, RoundToAlign);
618   SizeOffsetType Const = Visitor.compute(V);
619   if (Visitor.bothKnown(Const))
620     return std::make_pair(ConstantInt::get(Context, Const.first),
621                           ConstantInt::get(Context, Const.second));
622
623   V = V->stripPointerCasts();
624
625   // check cache
626   CacheMapTy::iterator CacheIt = CacheMap.find(V);
627   if (CacheIt != CacheMap.end())
628     return CacheIt->second;
629
630   // always generate code immediately before the instruction being
631   // processed, so that the generated code dominates the same BBs
632   BuilderTy::InsertPointGuard Guard(Builder);
633   if (Instruction *I = dyn_cast<Instruction>(V))
634     Builder.SetInsertPoint(I);
635
636   // now compute the size and offset
637   SizeOffsetEvalType Result;
638
639   // Record the pointers that were handled in this run, so that they can be
640   // cleaned later if something fails. We also use this set to break cycles that
641   // can occur in dead code.
642   if (!SeenVals.insert(V).second) {
643     Result = unknown();
644   } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
645     Result = visitGEPOperator(*GEP);
646   } else if (Instruction *I = dyn_cast<Instruction>(V)) {
647     Result = visit(*I);
648   } else if (isa<Argument>(V) ||
649              (isa<ConstantExpr>(V) &&
650               cast<ConstantExpr>(V)->getOpcode() == Instruction::IntToPtr) ||
651              isa<GlobalAlias>(V) ||
652              isa<GlobalVariable>(V)) {
653     // ignore values where we cannot do more than what ObjectSizeVisitor can
654     Result = unknown();
655   } else {
656     DEBUG(dbgs() << "ObjectSizeOffsetEvaluator::compute() unhandled value: "
657           << *V << '\n');
658     Result = unknown();
659   }
660
661   // Don't reuse CacheIt since it may be invalid at this point.
662   CacheMap[V] = Result;
663   return Result;
664 }
665
666 SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitAllocaInst(AllocaInst &I) {
667   if (!I.getAllocatedType()->isSized())
668     return unknown();
669
670   // must be a VLA
671   assert(I.isArrayAllocation());
672   Value *ArraySize = I.getArraySize();
673   Value *Size = ConstantInt::get(ArraySize->getType(),
674                                  DL.getTypeAllocSize(I.getAllocatedType()));
675   Size = Builder.CreateMul(Size, ArraySize);
676   return std::make_pair(Size, Zero);
677 }
678
679 SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitCallSite(CallSite CS) {
680   const AllocFnsTy *FnData = getAllocationData(CS.getInstruction(), AnyAlloc,
681                                                TLI);
682   if (!FnData)
683     return unknown();
684
685   // handle strdup-like functions separately
686   if (FnData->AllocTy == StrDupLike) {
687     // TODO
688     return unknown();
689   }
690
691   Value *FirstArg = CS.getArgument(FnData->FstParam);
692   FirstArg = Builder.CreateZExt(FirstArg, IntTy);
693   if (FnData->SndParam < 0)
694     return std::make_pair(FirstArg, Zero);
695
696   Value *SecondArg = CS.getArgument(FnData->SndParam);
697   SecondArg = Builder.CreateZExt(SecondArg, IntTy);
698   Value *Size = Builder.CreateMul(FirstArg, SecondArg);
699   return std::make_pair(Size, Zero);
700
701   // TODO: handle more standard functions (+ wchar cousins):
702   // - strdup / strndup
703   // - strcpy / strncpy
704   // - strcat / strncat
705   // - memcpy / memmove
706   // - strcat / strncat
707   // - memset
708 }
709
710 SizeOffsetEvalType
711 ObjectSizeOffsetEvaluator::visitExtractElementInst(ExtractElementInst&) {
712   return unknown();
713 }
714
715 SizeOffsetEvalType
716 ObjectSizeOffsetEvaluator::visitExtractValueInst(ExtractValueInst&) {
717   return unknown();
718 }
719
720 SizeOffsetEvalType
721 ObjectSizeOffsetEvaluator::visitGEPOperator(GEPOperator &GEP) {
722   SizeOffsetEvalType PtrData = compute_(GEP.getPointerOperand());
723   if (!bothKnown(PtrData))
724     return unknown();
725
726   Value *Offset = EmitGEPOffset(&Builder, DL, &GEP, /*NoAssumptions=*/true);
727   Offset = Builder.CreateAdd(PtrData.second, Offset);
728   return std::make_pair(PtrData.first, Offset);
729 }
730
731 SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitIntToPtrInst(IntToPtrInst&) {
732   // clueless
733   return unknown();
734 }
735
736 SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitLoadInst(LoadInst&) {
737   return unknown();
738 }
739
740 SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitPHINode(PHINode &PHI) {
741   // create 2 PHIs: one for size and another for offset
742   PHINode *SizePHI   = Builder.CreatePHI(IntTy, PHI.getNumIncomingValues());
743   PHINode *OffsetPHI = Builder.CreatePHI(IntTy, PHI.getNumIncomingValues());
744
745   // insert right away in the cache to handle recursive PHIs
746   CacheMap[&PHI] = std::make_pair(SizePHI, OffsetPHI);
747
748   // compute offset/size for each PHI incoming pointer
749   for (unsigned i = 0, e = PHI.getNumIncomingValues(); i != e; ++i) {
750     Builder.SetInsertPoint(&*PHI.getIncomingBlock(i)->getFirstInsertionPt());
751     SizeOffsetEvalType EdgeData = compute_(PHI.getIncomingValue(i));
752
753     if (!bothKnown(EdgeData)) {
754       OffsetPHI->replaceAllUsesWith(UndefValue::get(IntTy));
755       OffsetPHI->eraseFromParent();
756       SizePHI->replaceAllUsesWith(UndefValue::get(IntTy));
757       SizePHI->eraseFromParent();
758       return unknown();
759     }
760     SizePHI->addIncoming(EdgeData.first, PHI.getIncomingBlock(i));
761     OffsetPHI->addIncoming(EdgeData.second, PHI.getIncomingBlock(i));
762   }
763
764   Value *Size = SizePHI, *Offset = OffsetPHI, *Tmp;
765   if ((Tmp = SizePHI->hasConstantValue())) {
766     Size = Tmp;
767     SizePHI->replaceAllUsesWith(Size);
768     SizePHI->eraseFromParent();
769   }
770   if ((Tmp = OffsetPHI->hasConstantValue())) {
771     Offset = Tmp;
772     OffsetPHI->replaceAllUsesWith(Offset);
773     OffsetPHI->eraseFromParent();
774   }
775   return std::make_pair(Size, Offset);
776 }
777
778 SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitSelectInst(SelectInst &I) {
779   SizeOffsetEvalType TrueSide  = compute_(I.getTrueValue());
780   SizeOffsetEvalType FalseSide = compute_(I.getFalseValue());
781
782   if (!bothKnown(TrueSide) || !bothKnown(FalseSide))
783     return unknown();
784   if (TrueSide == FalseSide)
785     return TrueSide;
786
787   Value *Size = Builder.CreateSelect(I.getCondition(), TrueSide.first,
788                                      FalseSide.first);
789   Value *Offset = Builder.CreateSelect(I.getCondition(), TrueSide.second,
790                                        FalseSide.second);
791   return std::make_pair(Size, Offset);
792 }
793
794 SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitInstruction(Instruction &I) {
795   DEBUG(dbgs() << "ObjectSizeOffsetEvaluator unknown instruction:" << I <<'\n');
796   return unknown();
797 }