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