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