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