remove extractMallocCallFromBitCast, since it was tailor maded for its sole user...
[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 #define DEBUG_TYPE "memory-builtins"
16 #include "llvm/ADT/Statistic.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/Analysis/MemoryBuiltins.h"
19 #include "llvm/GlobalVariable.h"
20 #include "llvm/Instructions.h"
21 #include "llvm/Intrinsics.h"
22 #include "llvm/Metadata.h"
23 #include "llvm/Module.h"
24 #include "llvm/Analysis/ValueTracking.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Support/MathExtras.h"
27 #include "llvm/Support/raw_ostream.h"
28 #include "llvm/Target/TargetData.h"
29 #include "llvm/Transforms/Utils/Local.h"
30 using namespace llvm;
31
32 enum 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 };
40
41 struct AllocFnsTy {
42   const char *Name;
43   AllocType AllocTy;
44   unsigned char NumParams;
45   // First and Second size parameters (or -1 if unused)
46   signed char FstParam, SndParam;
47 };
48
49 static 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
65 static Function *getCalledFunction(const Value *V, bool LookThroughBitCast) {
66   if (LookThroughBitCast)
67     V = V->stripPointerCasts();
68
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
76     return 0;
77
78   Function *Callee = CS.getCalledFunction();
79   if (!Callee || !Callee->isDeclaration())
80     return 0;
81   return Callee;
82 }
83
84 /// \brief Returns the allocation data for the given value if it is a call to a
85 /// known allocation function, and NULL otherwise.
86 static 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)
109   int FstParam = FnData->FstParam;
110   int SndParam = FnData->SndParam;
111   FunctionType *FTy = Callee->getFunctionType();
112
113   if (FTy->getReturnType() == Type::getInt8PtrTy(FTy->getContext()) &&
114       FTy->getNumParams() == FnData->NumParams &&
115       (FstParam < 0 ||
116        (FTy->getParamType(FstParam)->isIntegerTy(32) ||
117         FTy->getParamType(FstParam)->isIntegerTy(64))) &&
118       (SndParam < 0 ||
119        FTy->getParamType(SndParam)->isIntegerTy(32) ||
120        FTy->getParamType(SndParam)->isIntegerTy(64)))
121     return FnData;
122   return 0;
123 }
124
125 static bool hasNoAliasAttr(const Value *V, bool LookThroughBitCast) {
126   Function *Callee = getCalledFunction(V, LookThroughBitCast);
127   return Callee && Callee->hasFnAttr(Attribute::NoAlias);
128 }
129
130
131 /// \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).
134 bool llvm::isAllocationFn(const Value *V, bool LookThroughBitCast) {
135   return getAllocationData(V, AnyAlloc, LookThroughBitCast);
136 }
137
138 /// \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).
140 bool llvm::isNoAliasFn(const Value *V, bool LookThroughBitCast) {
141   return isAllocLikeFn(V, LookThroughBitCast) ||
142          hasNoAliasAttr(V, LookThroughBitCast);
143 }
144
145 /// \brief Tests if a value is a call or invoke to a library function that
146 /// allocates uninitialized memory (such as malloc).
147 bool llvm::isMallocLikeFn(const Value *V, bool LookThroughBitCast) {
148   return getAllocationData(V, MallocLike, LookThroughBitCast);
149 }
150
151 /// \brief Tests if a value is a call or invoke to a library function that
152 /// allocates zero-filled memory (such as calloc).
153 bool llvm::isCallocLikeFn(const Value *V, bool LookThroughBitCast) {
154   return getAllocationData(V, CallocLike, LookThroughBitCast);
155 }
156
157 /// \brief Tests if a value is a call or invoke to a library function that
158 /// allocates memory (either malloc, calloc, or strdup like).
159 bool llvm::isAllocLikeFn(const Value *V, bool LookThroughBitCast) {
160   return getAllocationData(V, AllocLike, LookThroughBitCast);
161 }
162
163 /// \brief Tests if a value is a call or invoke to a library function that
164 /// reallocates memory (such as realloc).
165 bool llvm::isReallocLikeFn(const Value *V, bool LookThroughBitCast) {
166   return getAllocationData(V, ReallocLike, LookThroughBitCast);
167 }
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.
172 const CallInst *llvm::extractMallocCall(const Value *I) {
173   return isMallocLikeFn(I) ? dyn_cast<CallInst>(I) : 0;
174 }
175
176 static Value *computeArraySize(const CallInst *CI, const TargetData *TD,
177                                bool LookThroughSExt = false) {
178   if (!CI)
179     return NULL;
180
181   // The size of the malloc's result type must be known to determine array size.
182   Type *T = getMallocAllocatedType(CI);
183   if (!T || !T->isSized() || !TD)
184     return NULL;
185
186   unsigned ElementSize = TD->getTypeAllocSize(T);
187   if (StructType *ST = dyn_cast<StructType>(T))
188     ElementSize = TD->getStructLayout(ST)->getSizeInBytes();
189
190   // If malloc call's arg can be determined to be a multiple of ElementSize,
191   // return the multiple.  Otherwise, return NULL.
192   Value *MallocArg = CI->getArgOperand(0);
193   Value *Multiple = NULL;
194   if (ComputeMultiple(MallocArg, ElementSize, Multiple,
195                       LookThroughSExt))
196     return Multiple;
197
198   return NULL;
199 }
200
201 /// isArrayMalloc - Returns the corresponding CallInst if the instruction 
202 /// is a call to malloc whose array size can be determined and the array size
203 /// is not constant 1.  Otherwise, return NULL.
204 const CallInst *llvm::isArrayMalloc(const Value *I, const TargetData *TD) {
205   const CallInst *CI = extractMallocCall(I);
206   Value *ArraySize = computeArraySize(CI, TD);
207
208   if (ArraySize &&
209       ArraySize != ConstantInt::get(CI->getArgOperand(0)->getType(), 1))
210     return CI;
211
212   // CI is a non-array malloc or we can't figure out that it is an array malloc.
213   return NULL;
214 }
215
216 /// getMallocType - Returns the PointerType resulting from the malloc call.
217 /// The PointerType depends on the number of bitcast uses of the malloc call:
218 ///   0: PointerType is the calls' return type.
219 ///   1: PointerType is the bitcast's result type.
220 ///  >1: Unique PointerType cannot be determined, return NULL.
221 PointerType *llvm::getMallocType(const CallInst *CI) {
222   assert(isMallocLikeFn(CI) && "getMallocType and not malloc call");
223   
224   PointerType *MallocType = NULL;
225   unsigned NumOfBitCastUses = 0;
226
227   // Determine if CallInst has a bitcast use.
228   for (Value::const_use_iterator UI = CI->use_begin(), E = CI->use_end();
229        UI != E; )
230     if (const BitCastInst *BCI = dyn_cast<BitCastInst>(*UI++)) {
231       MallocType = cast<PointerType>(BCI->getDestTy());
232       NumOfBitCastUses++;
233     }
234
235   // Malloc call has 1 bitcast use, so type is the bitcast's destination type.
236   if (NumOfBitCastUses == 1)
237     return MallocType;
238
239   // Malloc call was not bitcast, so type is the malloc function's return type.
240   if (NumOfBitCastUses == 0)
241     return cast<PointerType>(CI->getType());
242
243   // Type could not be determined.
244   return NULL;
245 }
246
247 /// getMallocAllocatedType - Returns the Type allocated by malloc call.
248 /// The Type depends on the number of bitcast uses of the malloc call:
249 ///   0: PointerType is the malloc calls' return type.
250 ///   1: PointerType is the bitcast's result type.
251 ///  >1: Unique PointerType cannot be determined, return NULL.
252 Type *llvm::getMallocAllocatedType(const CallInst *CI) {
253   PointerType *PT = getMallocType(CI);
254   return PT ? PT->getElementType() : NULL;
255 }
256
257 /// getMallocArraySize - Returns the array size of a malloc call.  If the 
258 /// argument passed to malloc is a multiple of the size of the malloced type,
259 /// then return that multiple.  For non-array mallocs, the multiple is
260 /// constant 1.  Otherwise, return NULL for mallocs whose array size cannot be
261 /// determined.
262 Value *llvm::getMallocArraySize(CallInst *CI, const TargetData *TD,
263                                 bool LookThroughSExt) {
264   assert(isMallocLikeFn(CI) && "getMallocArraySize and not malloc call");
265   return computeArraySize(CI, TD, LookThroughSExt);
266 }
267
268
269 /// extractCallocCall - Returns the corresponding CallInst if the instruction
270 /// is a calloc call.
271 const CallInst *llvm::extractCallocCall(const Value *I) {
272   return isCallocLikeFn(I) ? cast<CallInst>(I) : 0;
273 }
274
275
276 /// isFreeCall - Returns non-null if the value is a call to the builtin free()
277 const CallInst *llvm::isFreeCall(const Value *I) {
278   const CallInst *CI = dyn_cast<CallInst>(I);
279   if (!CI)
280     return 0;
281   Function *Callee = CI->getCalledFunction();
282   if (Callee == 0 || !Callee->isDeclaration())
283     return 0;
284
285   if (Callee->getName() != "free" &&
286       Callee->getName() != "_ZdlPv" && // operator delete(void*)
287       Callee->getName() != "_ZdaPv")   // operator delete[](void*)
288     return 0;
289
290   // Check free prototype.
291   // FIXME: workaround for PR5130, this will be obsolete when a nobuiltin 
292   // attribute will exist.
293   FunctionType *FTy = Callee->getFunctionType();
294   if (!FTy->getReturnType()->isVoidTy())
295     return 0;
296   if (FTy->getNumParams() != 1)
297     return 0;
298   if (FTy->getParamType(0) != Type::getInt8PtrTy(Callee->getContext()))
299     return 0;
300
301   return CI;
302 }
303
304
305
306 //===----------------------------------------------------------------------===//
307 //  Utility functions to compute size of objects.
308 //
309
310
311 /// \brief Compute the size of the object pointed by Ptr. Returns true and the
312 /// object size in Size if successful, and false otherwise.
313 /// If RoundToAlign is true, then Size is rounded up to the aligment of allocas,
314 /// byval arguments, and global variables.
315 bool llvm::getObjectSize(const Value *Ptr, uint64_t &Size, const TargetData *TD,
316                          bool RoundToAlign) {
317   if (!TD)
318     return false;
319
320   ObjectSizeOffsetVisitor Visitor(TD, Ptr->getContext(), RoundToAlign);
321   SizeOffsetType Data = Visitor.compute(const_cast<Value*>(Ptr));
322   if (!Visitor.bothKnown(Data))
323     return false;
324
325   APInt ObjSize = Data.first, Offset = Data.second;
326   // check for overflow
327   if (Offset.slt(0) || ObjSize.ult(Offset))
328     Size = 0;
329   else
330     Size = (ObjSize - Offset).getZExtValue();
331   return true;
332 }
333
334
335 STATISTIC(ObjectVisitorArgument,
336           "Number of arguments with unsolved size and offset");
337 STATISTIC(ObjectVisitorLoad,
338           "Number of load instructions with unsolved size and offset");
339
340
341 APInt ObjectSizeOffsetVisitor::align(APInt Size, uint64_t Align) {
342   if (RoundToAlign && Align)
343     return APInt(IntTyBits, RoundUpToAlignment(Size.getZExtValue(), Align));
344   return Size;
345 }
346
347 ObjectSizeOffsetVisitor::ObjectSizeOffsetVisitor(const TargetData *TD,
348                                                  LLVMContext &Context,
349                                                  bool RoundToAlign)
350 : TD(TD), RoundToAlign(RoundToAlign) {
351   IntegerType *IntTy = TD->getIntPtrType(Context);
352   IntTyBits = IntTy->getBitWidth();
353   Zero = APInt::getNullValue(IntTyBits);
354 }
355
356 SizeOffsetType ObjectSizeOffsetVisitor::compute(Value *V) {
357   V = V->stripPointerCasts();
358
359   if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
360     return visitGEPOperator(*GEP);
361   if (Instruction *I = dyn_cast<Instruction>(V))
362     return visit(*I);
363   if (Argument *A = dyn_cast<Argument>(V))
364     return visitArgument(*A);
365   if (ConstantPointerNull *P = dyn_cast<ConstantPointerNull>(V))
366     return visitConstantPointerNull(*P);
367   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
368     return visitGlobalVariable(*GV);
369   if (UndefValue *UV = dyn_cast<UndefValue>(V))
370     return visitUndefValue(*UV);
371   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
372     if (CE->getOpcode() == Instruction::IntToPtr)
373       return unknown(); // clueless
374
375   DEBUG(dbgs() << "ObjectSizeOffsetVisitor::compute() unhandled value: " << *V
376         << '\n');
377   return unknown();
378 }
379
380 SizeOffsetType ObjectSizeOffsetVisitor::visitAllocaInst(AllocaInst &I) {
381   if (!I.getAllocatedType()->isSized())
382     return unknown();
383
384   APInt Size(IntTyBits, TD->getTypeAllocSize(I.getAllocatedType()));
385   if (!I.isArrayAllocation())
386     return std::make_pair(align(Size, I.getAlignment()), Zero);
387
388   Value *ArraySize = I.getArraySize();
389   if (const ConstantInt *C = dyn_cast<ConstantInt>(ArraySize)) {
390     Size *= C->getValue().zextOrSelf(IntTyBits);
391     return std::make_pair(align(Size, I.getAlignment()), Zero);
392   }
393   return unknown();
394 }
395
396 SizeOffsetType ObjectSizeOffsetVisitor::visitArgument(Argument &A) {
397   // no interprocedural analysis is done at the moment
398   if (!A.hasByValAttr()) {
399     ++ObjectVisitorArgument;
400     return unknown();
401   }
402   PointerType *PT = cast<PointerType>(A.getType());
403   APInt Size(IntTyBits, TD->getTypeAllocSize(PT->getElementType()));
404   return std::make_pair(align(Size, A.getParamAlignment()), Zero);
405 }
406
407 SizeOffsetType ObjectSizeOffsetVisitor::visitCallSite(CallSite CS) {
408   const AllocFnsTy *FnData = getAllocationData(CS.getInstruction(), AnyAlloc);
409   if (!FnData)
410     return unknown();
411
412   // handle strdup-like functions separately
413   if (FnData->AllocTy == StrDupLike) {
414     // TODO
415     return unknown();
416   }
417
418   ConstantInt *Arg = dyn_cast<ConstantInt>(CS.getArgument(FnData->FstParam));
419   if (!Arg)
420     return unknown();
421
422   APInt Size = Arg->getValue().zextOrSelf(IntTyBits);
423   // size determined by just 1 parameter
424   if (FnData->SndParam < 0)
425     return std::make_pair(Size, Zero);
426
427   Arg = dyn_cast<ConstantInt>(CS.getArgument(FnData->SndParam));
428   if (!Arg)
429     return unknown();
430
431   Size *= Arg->getValue().zextOrSelf(IntTyBits);
432   return std::make_pair(Size, Zero);
433
434   // TODO: handle more standard functions (+ wchar cousins):
435   // - strdup / strndup
436   // - strcpy / strncpy
437   // - strcat / strncat
438   // - memcpy / memmove
439   // - strcat / strncat
440   // - memset
441 }
442
443 SizeOffsetType
444 ObjectSizeOffsetVisitor::visitConstantPointerNull(ConstantPointerNull&) {
445   return std::make_pair(Zero, Zero);
446 }
447
448 SizeOffsetType
449 ObjectSizeOffsetVisitor::visitExtractValueInst(ExtractValueInst&) {
450   // Easy cases were already folded by previous passes.
451   return unknown();
452 }
453
454 SizeOffsetType ObjectSizeOffsetVisitor::visitGEPOperator(GEPOperator &GEP) {
455   SizeOffsetType PtrData = compute(GEP.getPointerOperand());
456   if (!bothKnown(PtrData) || !GEP.hasAllConstantIndices())
457     return unknown();
458
459   SmallVector<Value*, 8> Ops(GEP.idx_begin(), GEP.idx_end());
460   APInt Offset(IntTyBits,TD->getIndexedOffset(GEP.getPointerOperandType(),Ops));
461   return std::make_pair(PtrData.first, PtrData.second + Offset);
462 }
463
464 SizeOffsetType ObjectSizeOffsetVisitor::visitGlobalVariable(GlobalVariable &GV){
465   if (!GV.hasDefinitiveInitializer())
466     return unknown();
467
468   APInt Size(IntTyBits, TD->getTypeAllocSize(GV.getType()->getElementType()));
469   return std::make_pair(align(Size, GV.getAlignment()), Zero);
470 }
471
472 SizeOffsetType ObjectSizeOffsetVisitor::visitIntToPtrInst(IntToPtrInst&) {
473   // clueless
474   return unknown();
475 }
476
477 SizeOffsetType ObjectSizeOffsetVisitor::visitLoadInst(LoadInst&) {
478   ++ObjectVisitorLoad;
479   return unknown();
480 }
481
482 SizeOffsetType ObjectSizeOffsetVisitor::visitPHINode(PHINode&) {
483   // too complex to analyze statically.
484   return unknown();
485 }
486
487 SizeOffsetType ObjectSizeOffsetVisitor::visitSelectInst(SelectInst &I) {
488   SizeOffsetType TrueSide  = compute(I.getTrueValue());
489   SizeOffsetType FalseSide = compute(I.getFalseValue());
490   if (bothKnown(TrueSide) && bothKnown(FalseSide) && TrueSide == FalseSide)
491     return TrueSide;
492   return unknown();
493 }
494
495 SizeOffsetType ObjectSizeOffsetVisitor::visitUndefValue(UndefValue&) {
496   return std::make_pair(Zero, Zero);
497 }
498
499 SizeOffsetType ObjectSizeOffsetVisitor::visitInstruction(Instruction &I) {
500   DEBUG(dbgs() << "ObjectSizeOffsetVisitor unknown instruction:" << I << '\n');
501   return unknown();
502 }
503
504
505 ObjectSizeOffsetEvaluator::ObjectSizeOffsetEvaluator(const TargetData *TD,
506                                                      LLVMContext &Context)
507 : TD(TD), Context(Context), Builder(Context, TargetFolder(TD)),
508 Visitor(TD, Context) {
509   IntTy = TD->getIntPtrType(Context);
510   Zero = ConstantInt::get(IntTy, 0);
511 }
512
513 SizeOffsetEvalType ObjectSizeOffsetEvaluator::compute(Value *V) {
514   SizeOffsetEvalType Result = compute_(V);
515
516   if (!bothKnown(Result)) {
517     // erase everything that was computed in this iteration from the cache, so
518     // that no dangling references are left behind. We could be a bit smarter if
519     // we kept a dependency graph. It's probably not worth the complexity.
520     for (PtrSetTy::iterator I=SeenVals.begin(), E=SeenVals.end(); I != E; ++I) {
521       CacheMapTy::iterator CacheIt = CacheMap.find(*I);
522       // non-computable results can be safely cached
523       if (CacheIt != CacheMap.end() && anyKnown(CacheIt->second))
524         CacheMap.erase(CacheIt);
525     }
526   }
527
528   SeenVals.clear();
529   return Result;
530 }
531
532 SizeOffsetEvalType ObjectSizeOffsetEvaluator::compute_(Value *V) {
533   SizeOffsetType Const = Visitor.compute(V);
534   if (Visitor.bothKnown(Const))
535     return std::make_pair(ConstantInt::get(Context, Const.first),
536                           ConstantInt::get(Context, Const.second));
537
538   V = V->stripPointerCasts();
539
540   // check cache
541   CacheMapTy::iterator CacheIt = CacheMap.find(V);
542   if (CacheIt != CacheMap.end())
543     return CacheIt->second;
544
545   // always generate code immediately before the instruction being
546   // processed, so that the generated code dominates the same BBs
547   Instruction *PrevInsertPoint = Builder.GetInsertPoint();
548   if (Instruction *I = dyn_cast<Instruction>(V))
549     Builder.SetInsertPoint(I);
550
551   // record the pointers that were handled in this run, so that they can be
552   // cleaned later if something fails
553   SeenVals.insert(V);
554
555   // now compute the size and offset
556   SizeOffsetEvalType Result;
557   if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
558     Result = visitGEPOperator(*GEP);
559   } else if (Instruction *I = dyn_cast<Instruction>(V)) {
560     Result = visit(*I);
561   } else if (isa<Argument>(V) ||
562              (isa<ConstantExpr>(V) &&
563               cast<ConstantExpr>(V)->getOpcode() == Instruction::IntToPtr) ||
564              isa<GlobalVariable>(V)) {
565     // ignore values where we cannot do more than what ObjectSizeVisitor can
566     Result = unknown();
567   } else {
568     DEBUG(dbgs() << "ObjectSizeOffsetEvaluator::compute() unhandled value: "
569           << *V << '\n');
570     Result = unknown();
571   }
572
573   if (PrevInsertPoint)
574     Builder.SetInsertPoint(PrevInsertPoint);
575
576   // Don't reuse CacheIt since it may be invalid at this point.
577   CacheMap[V] = Result;
578   return Result;
579 }
580
581 SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitAllocaInst(AllocaInst &I) {
582   if (!I.getAllocatedType()->isSized())
583     return unknown();
584
585   // must be a VLA
586   assert(I.isArrayAllocation());
587   Value *ArraySize = I.getArraySize();
588   Value *Size = ConstantInt::get(ArraySize->getType(),
589                                  TD->getTypeAllocSize(I.getAllocatedType()));
590   Size = Builder.CreateMul(Size, ArraySize);
591   return std::make_pair(Size, Zero);
592 }
593
594 SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitCallSite(CallSite CS) {
595   const AllocFnsTy *FnData = getAllocationData(CS.getInstruction(), AnyAlloc);
596   if (!FnData)
597     return unknown();
598
599   // handle strdup-like functions separately
600   if (FnData->AllocTy == StrDupLike) {
601     // TODO
602     return unknown();
603   }
604
605   Value *FirstArg = CS.getArgument(FnData->FstParam);
606   FirstArg = Builder.CreateZExt(FirstArg, IntTy);
607   if (FnData->SndParam < 0)
608     return std::make_pair(FirstArg, Zero);
609
610   Value *SecondArg = CS.getArgument(FnData->SndParam);
611   SecondArg = Builder.CreateZExt(SecondArg, IntTy);
612   Value *Size = Builder.CreateMul(FirstArg, SecondArg);
613   return std::make_pair(Size, Zero);
614
615   // TODO: handle more standard functions (+ wchar cousins):
616   // - strdup / strndup
617   // - strcpy / strncpy
618   // - strcat / strncat
619   // - memcpy / memmove
620   // - strcat / strncat
621   // - memset
622 }
623
624 SizeOffsetEvalType
625 ObjectSizeOffsetEvaluator::visitGEPOperator(GEPOperator &GEP) {
626   SizeOffsetEvalType PtrData = compute_(GEP.getPointerOperand());
627   if (!bothKnown(PtrData))
628     return unknown();
629
630   Value *Offset = EmitGEPOffset(&Builder, *TD, &GEP);
631   Offset = Builder.CreateAdd(PtrData.second, Offset);
632   return std::make_pair(PtrData.first, Offset);
633 }
634
635 SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitIntToPtrInst(IntToPtrInst&) {
636   // clueless
637   return unknown();
638 }
639
640 SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitLoadInst(LoadInst&) {
641   return unknown();
642 }
643
644 SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitPHINode(PHINode &PHI) {
645   // create 2 PHIs: one for size and another for offset
646   PHINode *SizePHI   = Builder.CreatePHI(IntTy, PHI.getNumIncomingValues());
647   PHINode *OffsetPHI = Builder.CreatePHI(IntTy, PHI.getNumIncomingValues());
648
649   // insert right away in the cache to handle recursive PHIs
650   CacheMap[&PHI] = std::make_pair(SizePHI, OffsetPHI);
651
652   // compute offset/size for each PHI incoming pointer
653   for (unsigned i = 0, e = PHI.getNumIncomingValues(); i != e; ++i) {
654     Builder.SetInsertPoint(PHI.getIncomingBlock(i)->getFirstInsertionPt());
655     SizeOffsetEvalType EdgeData = compute_(PHI.getIncomingValue(i));
656
657     if (!bothKnown(EdgeData)) {
658       OffsetPHI->replaceAllUsesWith(UndefValue::get(IntTy));
659       OffsetPHI->eraseFromParent();
660       SizePHI->replaceAllUsesWith(UndefValue::get(IntTy));
661       SizePHI->eraseFromParent();
662       return unknown();
663     }
664     SizePHI->addIncoming(EdgeData.first, PHI.getIncomingBlock(i));
665     OffsetPHI->addIncoming(EdgeData.second, PHI.getIncomingBlock(i));
666   }
667   return std::make_pair(SizePHI, OffsetPHI);
668 }
669
670 SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitSelectInst(SelectInst &I) {
671   SizeOffsetEvalType TrueSide  = compute_(I.getTrueValue());
672   SizeOffsetEvalType FalseSide = compute_(I.getFalseValue());
673
674   if (!bothKnown(TrueSide) || !bothKnown(FalseSide))
675     return unknown();
676   if (TrueSide == FalseSide)
677     return TrueSide;
678
679   Value *Size = Builder.CreateSelect(I.getCondition(), TrueSide.first,
680                                      FalseSide.first);
681   Value *Offset = Builder.CreateSelect(I.getCondition(), TrueSide.second,
682                                        FalseSide.second);
683   return std::make_pair(Size, Offset);
684 }
685
686 SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitInstruction(Instruction &I) {
687   DEBUG(dbgs() << "ObjectSizeOffsetEvaluator unknown instruction:" << I <<'\n');
688   return unknown();
689 }