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