1 //===------ MemoryBuiltins.cpp - Identify calls to memory builtins --------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This family of functions identifies calls to builtin functions that allocate
13 //===----------------------------------------------------------------------===//
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/BuildLibCalls.h"
30 #include "llvm/Transforms/Utils/Local.h"
34 MallocLike = 1<<0, // allocates
35 CallocLike = 1<<1, // allocates + bzero
36 ReallocLike = 1<<2, // reallocates
38 AllocLike = MallocLike | CallocLike | StrDupLike,
39 AnyAlloc = MallocLike | CallocLike | ReallocLike | StrDupLike
45 unsigned char NumParams;
46 // First and Second size parameters (or -1 if unused)
47 signed char FstParam, SndParam;
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 {"malloc", MallocLike, 1, 0, -1},
54 {"valloc", MallocLike, 1, 0, -1},
55 {"_Znwj", MallocLike, 1, 0, -1}, // new(unsigned int)
56 {"_ZnwjRKSt9nothrow_t", MallocLike, 2, 0, -1}, // new(unsigned int, nothrow)
57 {"_Znwm", MallocLike, 1, 0, -1}, // new(unsigned long)
58 {"_ZnwmRKSt9nothrow_t", MallocLike, 2, 0, -1}, // new(unsigned long, nothrow)
59 {"_Znaj", MallocLike, 1, 0, -1}, // new[](unsigned int)
60 {"_ZnajRKSt9nothrow_t", MallocLike, 2, 0, -1}, // new[](unsigned int, nothrow)
61 {"_Znam", MallocLike, 1, 0, -1}, // new[](unsigned long)
62 {"_ZnamRKSt9nothrow_t", MallocLike, 2, 0, -1}, // new[](unsigned long, nothrow)
63 {"posix_memalign", MallocLike, 3, 2, -1},
64 {"calloc", CallocLike, 2, 0, 1},
65 {"realloc", ReallocLike, 2, 1, -1},
66 {"reallocf", ReallocLike, 2, 1, -1},
67 {"strdup", StrDupLike, 1, -1, -1},
68 {"strndup", StrDupLike, 2, 1, -1}
72 static Function *getCalledFunction(const Value *V, bool LookThroughBitCast) {
73 if (LookThroughBitCast)
74 V = V->stripPointerCasts();
76 CallSite CS(const_cast<Value*>(V));
77 if (!CS.getInstruction())
80 Function *Callee = CS.getCalledFunction();
81 if (!Callee || !Callee->isDeclaration())
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 bool LookThroughBitCast = false) {
90 Function *Callee = getCalledFunction(V, LookThroughBitCast);
96 for ( ; i < array_lengthof(AllocationFnData); ++i) {
97 if (Callee->getName() == AllocationFnData[i].Name) {
105 const AllocFnsTy *FnData = &AllocationFnData[i];
106 if ((FnData->AllocTy & AllocTy) == 0)
109 // Check function prototype.
110 // FIXME: Check the nobuiltin metadata?? (PR5130)
111 int FstParam = FnData->FstParam;
112 int SndParam = FnData->SndParam;
113 FunctionType *FTy = Callee->getFunctionType();
115 if (FTy->getReturnType() == Type::getInt8PtrTy(FTy->getContext()) &&
116 FTy->getNumParams() == FnData->NumParams &&
118 (FTy->getParamType(FstParam)->isIntegerTy(32) ||
119 FTy->getParamType(FstParam)->isIntegerTy(64))) &&
121 FTy->getParamType(SndParam)->isIntegerTy(32) ||
122 FTy->getParamType(SndParam)->isIntegerTy(64)))
127 static bool hasNoAliasAttr(const Value *V, bool LookThroughBitCast) {
128 ImmutableCallSite CS(LookThroughBitCast ? V->stripPointerCasts() : V);
129 return CS && CS.hasFnAttr(Attribute::NoAlias);
133 /// \brief Tests if a value is a call or invoke to a library function that
134 /// allocates or reallocates memory (either malloc, calloc, realloc, or strdup
136 bool llvm::isAllocationFn(const Value *V, bool LookThroughBitCast) {
137 return getAllocationData(V, AnyAlloc, LookThroughBitCast);
140 /// \brief Tests if a value is a call or invoke to a function that returns a
141 /// NoAlias pointer (including malloc/calloc/realloc/strdup-like functions).
142 bool llvm::isNoAliasFn(const Value *V, bool LookThroughBitCast) {
143 // it's safe to consider realloc as noalias since accessing the original
144 // pointer is undefined behavior
145 return isAllocationFn(V, LookThroughBitCast) ||
146 hasNoAliasAttr(V, LookThroughBitCast);
149 /// \brief Tests if a value is a call or invoke to a library function that
150 /// allocates uninitialized memory (such as malloc).
151 bool llvm::isMallocLikeFn(const Value *V, bool LookThroughBitCast) {
152 return getAllocationData(V, MallocLike, LookThroughBitCast);
155 /// \brief Tests if a value is a call or invoke to a library function that
156 /// allocates zero-filled memory (such as calloc).
157 bool llvm::isCallocLikeFn(const Value *V, bool LookThroughBitCast) {
158 return getAllocationData(V, CallocLike, LookThroughBitCast);
161 /// \brief Tests if a value is a call or invoke to a library function that
162 /// allocates memory (either malloc, calloc, or strdup like).
163 bool llvm::isAllocLikeFn(const Value *V, bool LookThroughBitCast) {
164 return getAllocationData(V, AllocLike, LookThroughBitCast);
167 /// \brief Tests if a value is a call or invoke to a library function that
168 /// reallocates memory (such as realloc).
169 bool llvm::isReallocLikeFn(const Value *V, bool LookThroughBitCast) {
170 return getAllocationData(V, ReallocLike, LookThroughBitCast);
173 /// extractMallocCall - Returns the corresponding CallInst if the instruction
174 /// is a malloc call. Since CallInst::CreateMalloc() only creates calls, we
175 /// ignore InvokeInst here.
176 const CallInst *llvm::extractMallocCall(const Value *I) {
177 return isMallocLikeFn(I) ? dyn_cast<CallInst>(I) : 0;
180 static Value *computeArraySize(const CallInst *CI, const TargetData *TD,
181 bool LookThroughSExt = false) {
185 // The size of the malloc's result type must be known to determine array size.
186 Type *T = getMallocAllocatedType(CI);
187 if (!T || !T->isSized() || !TD)
190 unsigned ElementSize = TD->getTypeAllocSize(T);
191 if (StructType *ST = dyn_cast<StructType>(T))
192 ElementSize = TD->getStructLayout(ST)->getSizeInBytes();
194 // If malloc call's arg can be determined to be a multiple of ElementSize,
195 // return the multiple. Otherwise, return NULL.
196 Value *MallocArg = CI->getArgOperand(0);
197 Value *Multiple = NULL;
198 if (ComputeMultiple(MallocArg, ElementSize, Multiple,
205 /// isArrayMalloc - Returns the corresponding CallInst if the instruction
206 /// is a call to malloc whose array size can be determined and the array size
207 /// is not constant 1. Otherwise, return NULL.
208 const CallInst *llvm::isArrayMalloc(const Value *I, const TargetData *TD) {
209 const CallInst *CI = extractMallocCall(I);
210 Value *ArraySize = computeArraySize(CI, TD);
213 ArraySize != ConstantInt::get(CI->getArgOperand(0)->getType(), 1))
216 // CI is a non-array malloc or we can't figure out that it is an array malloc.
220 /// getMallocType - Returns the PointerType resulting from the malloc call.
221 /// The PointerType depends on the number of bitcast uses of the malloc call:
222 /// 0: PointerType is the calls' return type.
223 /// 1: PointerType is the bitcast's result type.
224 /// >1: Unique PointerType cannot be determined, return NULL.
225 PointerType *llvm::getMallocType(const CallInst *CI) {
226 assert(isMallocLikeFn(CI) && "getMallocType and not malloc call");
228 PointerType *MallocType = NULL;
229 unsigned NumOfBitCastUses = 0;
231 // Determine if CallInst has a bitcast use.
232 for (Value::const_use_iterator UI = CI->use_begin(), E = CI->use_end();
234 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(*UI++)) {
235 MallocType = cast<PointerType>(BCI->getDestTy());
239 // Malloc call has 1 bitcast use, so type is the bitcast's destination type.
240 if (NumOfBitCastUses == 1)
243 // Malloc call was not bitcast, so type is the malloc function's return type.
244 if (NumOfBitCastUses == 0)
245 return cast<PointerType>(CI->getType());
247 // Type could not be determined.
251 /// getMallocAllocatedType - Returns the Type allocated by malloc call.
252 /// The Type depends on the number of bitcast uses of the malloc call:
253 /// 0: PointerType is the malloc calls' return type.
254 /// 1: PointerType is the bitcast's result type.
255 /// >1: Unique PointerType cannot be determined, return NULL.
256 Type *llvm::getMallocAllocatedType(const CallInst *CI) {
257 PointerType *PT = getMallocType(CI);
258 return PT ? PT->getElementType() : NULL;
261 /// getMallocArraySize - Returns the array size of a malloc call. If the
262 /// argument passed to malloc is a multiple of the size of the malloced type,
263 /// then return that multiple. For non-array mallocs, the multiple is
264 /// constant 1. Otherwise, return NULL for mallocs whose array size cannot be
266 Value *llvm::getMallocArraySize(CallInst *CI, const TargetData *TD,
267 bool LookThroughSExt) {
268 assert(isMallocLikeFn(CI) && "getMallocArraySize and not malloc call");
269 return computeArraySize(CI, TD, LookThroughSExt);
273 /// extractCallocCall - Returns the corresponding CallInst if the instruction
274 /// is a calloc call.
275 const CallInst *llvm::extractCallocCall(const Value *I) {
276 return isCallocLikeFn(I) ? cast<CallInst>(I) : 0;
280 /// isFreeCall - Returns non-null if the value is a call to the builtin free()
281 const CallInst *llvm::isFreeCall(const Value *I) {
282 const CallInst *CI = dyn_cast<CallInst>(I);
285 Function *Callee = CI->getCalledFunction();
286 if (Callee == 0 || !Callee->isDeclaration())
289 if (Callee->getName() != "free" &&
290 Callee->getName() != "_ZdlPv" && // operator delete(void*)
291 Callee->getName() != "_ZdaPv") // operator delete[](void*)
294 // Check free prototype.
295 // FIXME: workaround for PR5130, this will be obsolete when a nobuiltin
296 // attribute will exist.
297 FunctionType *FTy = Callee->getFunctionType();
298 if (!FTy->getReturnType()->isVoidTy())
300 if (FTy->getNumParams() != 1)
302 if (FTy->getParamType(0) != Type::getInt8PtrTy(Callee->getContext()))
310 //===----------------------------------------------------------------------===//
311 // Utility functions to compute size of objects.
315 /// \brief Compute the size of the object pointed by Ptr. Returns true and the
316 /// object size in Size if successful, and false otherwise.
317 /// If RoundToAlign is true, then Size is rounded up to the aligment of allocas,
318 /// byval arguments, and global variables.
319 bool llvm::getObjectSize(const Value *Ptr, uint64_t &Size, const TargetData *TD,
324 ObjectSizeOffsetVisitor Visitor(TD, Ptr->getContext(), RoundToAlign);
325 SizeOffsetType Data = Visitor.compute(const_cast<Value*>(Ptr));
326 if (!Visitor.bothKnown(Data))
329 APInt ObjSize = Data.first, Offset = Data.second;
330 // check for overflow
331 if (Offset.slt(0) || ObjSize.ult(Offset))
334 Size = (ObjSize - Offset).getZExtValue();
339 STATISTIC(ObjectVisitorArgument,
340 "Number of arguments with unsolved size and offset");
341 STATISTIC(ObjectVisitorLoad,
342 "Number of load instructions with unsolved size and offset");
345 APInt ObjectSizeOffsetVisitor::align(APInt Size, uint64_t Align) {
346 if (RoundToAlign && Align)
347 return APInt(IntTyBits, RoundUpToAlignment(Size.getZExtValue(), Align));
351 ObjectSizeOffsetVisitor::ObjectSizeOffsetVisitor(const TargetData *TD,
352 LLVMContext &Context,
354 : TD(TD), RoundToAlign(RoundToAlign) {
355 IntegerType *IntTy = TD->getIntPtrType(Context);
356 IntTyBits = IntTy->getBitWidth();
357 Zero = APInt::getNullValue(IntTyBits);
360 SizeOffsetType ObjectSizeOffsetVisitor::compute(Value *V) {
361 V = V->stripPointerCasts();
363 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
364 return visitGEPOperator(*GEP);
365 if (Instruction *I = dyn_cast<Instruction>(V))
367 if (Argument *A = dyn_cast<Argument>(V))
368 return visitArgument(*A);
369 if (ConstantPointerNull *P = dyn_cast<ConstantPointerNull>(V))
370 return visitConstantPointerNull(*P);
371 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
372 return visitGlobalVariable(*GV);
373 if (UndefValue *UV = dyn_cast<UndefValue>(V))
374 return visitUndefValue(*UV);
375 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
376 if (CE->getOpcode() == Instruction::IntToPtr)
377 return unknown(); // clueless
379 DEBUG(dbgs() << "ObjectSizeOffsetVisitor::compute() unhandled value: " << *V
384 SizeOffsetType ObjectSizeOffsetVisitor::visitAllocaInst(AllocaInst &I) {
385 if (!I.getAllocatedType()->isSized())
388 APInt Size(IntTyBits, TD->getTypeAllocSize(I.getAllocatedType()));
389 if (!I.isArrayAllocation())
390 return std::make_pair(align(Size, I.getAlignment()), Zero);
392 Value *ArraySize = I.getArraySize();
393 if (const ConstantInt *C = dyn_cast<ConstantInt>(ArraySize)) {
394 Size *= C->getValue().zextOrSelf(IntTyBits);
395 return std::make_pair(align(Size, I.getAlignment()), Zero);
400 SizeOffsetType ObjectSizeOffsetVisitor::visitArgument(Argument &A) {
401 // no interprocedural analysis is done at the moment
402 if (!A.hasByValAttr()) {
403 ++ObjectVisitorArgument;
406 PointerType *PT = cast<PointerType>(A.getType());
407 APInt Size(IntTyBits, TD->getTypeAllocSize(PT->getElementType()));
408 return std::make_pair(align(Size, A.getParamAlignment()), Zero);
411 SizeOffsetType ObjectSizeOffsetVisitor::visitCallSite(CallSite CS) {
412 const AllocFnsTy *FnData = getAllocationData(CS.getInstruction(), AnyAlloc);
416 // handle strdup-like functions separately
417 if (FnData->AllocTy == StrDupLike) {
418 APInt Size(IntTyBits, GetStringLength(CS.getArgument(0)));
422 // strndup limits strlen
423 if (FnData->FstParam > 0) {
424 ConstantInt *Arg= dyn_cast<ConstantInt>(CS.getArgument(FnData->FstParam));
428 APInt MaxSize = Arg->getValue().zextOrSelf(IntTyBits);
429 if (Size.ugt(MaxSize))
432 return std::make_pair(Size, Zero);
435 ConstantInt *Arg = dyn_cast<ConstantInt>(CS.getArgument(FnData->FstParam));
439 APInt Size = Arg->getValue().zextOrSelf(IntTyBits);
440 // size determined by just 1 parameter
441 if (FnData->SndParam < 0)
442 return std::make_pair(Size, Zero);
444 Arg = dyn_cast<ConstantInt>(CS.getArgument(FnData->SndParam));
448 Size *= Arg->getValue().zextOrSelf(IntTyBits);
449 return std::make_pair(Size, Zero);
451 // TODO: handle more standard functions (+ wchar cousins):
452 // - strcpy / strncpy
453 // - strcat / strncat
454 // - memcpy / memmove
459 ObjectSizeOffsetVisitor::visitConstantPointerNull(ConstantPointerNull&) {
460 return std::make_pair(Zero, Zero);
464 ObjectSizeOffsetVisitor::visitExtractElementInst(ExtractElementInst&) {
469 ObjectSizeOffsetVisitor::visitExtractValueInst(ExtractValueInst&) {
470 // Easy cases were already folded by previous passes.
474 SizeOffsetType ObjectSizeOffsetVisitor::visitGEPOperator(GEPOperator &GEP) {
475 SizeOffsetType PtrData = compute(GEP.getPointerOperand());
476 if (!bothKnown(PtrData) || !GEP.hasAllConstantIndices())
479 SmallVector<Value*, 8> Ops(GEP.idx_begin(), GEP.idx_end());
480 APInt Offset(IntTyBits,TD->getIndexedOffset(GEP.getPointerOperandType(),Ops));
481 return std::make_pair(PtrData.first, PtrData.second + Offset);
484 SizeOffsetType ObjectSizeOffsetVisitor::visitGlobalVariable(GlobalVariable &GV){
485 if (!GV.hasDefinitiveInitializer())
488 APInt Size(IntTyBits, TD->getTypeAllocSize(GV.getType()->getElementType()));
489 return std::make_pair(align(Size, GV.getAlignment()), Zero);
492 SizeOffsetType ObjectSizeOffsetVisitor::visitIntToPtrInst(IntToPtrInst&) {
497 SizeOffsetType ObjectSizeOffsetVisitor::visitLoadInst(LoadInst&) {
502 SizeOffsetType ObjectSizeOffsetVisitor::visitPHINode(PHINode&) {
503 // too complex to analyze statically.
507 SizeOffsetType ObjectSizeOffsetVisitor::visitSelectInst(SelectInst &I) {
508 SizeOffsetType TrueSide = compute(I.getTrueValue());
509 SizeOffsetType FalseSide = compute(I.getFalseValue());
510 if (bothKnown(TrueSide) && bothKnown(FalseSide) && TrueSide == FalseSide)
515 SizeOffsetType ObjectSizeOffsetVisitor::visitUndefValue(UndefValue&) {
516 return std::make_pair(Zero, Zero);
519 SizeOffsetType ObjectSizeOffsetVisitor::visitInstruction(Instruction &I) {
520 DEBUG(dbgs() << "ObjectSizeOffsetVisitor unknown instruction:" << I << '\n');
525 ObjectSizeOffsetEvaluator::ObjectSizeOffsetEvaluator(const TargetData *TD,
526 const TargetLibraryInfo *TLI,
527 LLVMContext &Context)
528 : TD(TD), TLI(TLI), Context(Context), Builder(Context, TargetFolder(TD)),
529 Visitor(TD, Context) {
530 IntTy = TD->getIntPtrType(Context);
531 Zero = ConstantInt::get(IntTy, 0);
534 SizeOffsetEvalType ObjectSizeOffsetEvaluator::compute(Value *V) {
535 SizeOffsetEvalType Result = compute_(V);
537 if (!bothKnown(Result)) {
538 // erase everything that was computed in this iteration from the cache, so
539 // that no dangling references are left behind. We could be a bit smarter if
540 // we kept a dependency graph. It's probably not worth the complexity.
541 for (PtrSetTy::iterator I=SeenVals.begin(), E=SeenVals.end(); I != E; ++I) {
542 CacheMapTy::iterator CacheIt = CacheMap.find(*I);
543 // non-computable results can be safely cached
544 if (CacheIt != CacheMap.end() && anyKnown(CacheIt->second))
545 CacheMap.erase(CacheIt);
553 SizeOffsetEvalType ObjectSizeOffsetEvaluator::compute_(Value *V) {
554 SizeOffsetType Const = Visitor.compute(V);
555 if (Visitor.bothKnown(Const))
556 return std::make_pair(ConstantInt::get(Context, Const.first),
557 ConstantInt::get(Context, Const.second));
559 V = V->stripPointerCasts();
562 CacheMapTy::iterator CacheIt = CacheMap.find(V);
563 if (CacheIt != CacheMap.end())
564 return CacheIt->second;
566 // always generate code immediately before the instruction being
567 // processed, so that the generated code dominates the same BBs
568 Instruction *PrevInsertPoint = Builder.GetInsertPoint();
569 if (Instruction *I = dyn_cast<Instruction>(V))
570 Builder.SetInsertPoint(I);
572 // record the pointers that were handled in this run, so that they can be
573 // cleaned later if something fails
576 // now compute the size and offset
577 SizeOffsetEvalType Result;
578 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
579 Result = visitGEPOperator(*GEP);
580 } else if (Instruction *I = dyn_cast<Instruction>(V)) {
582 } else if (isa<Argument>(V) ||
583 (isa<ConstantExpr>(V) &&
584 cast<ConstantExpr>(V)->getOpcode() == Instruction::IntToPtr) ||
585 isa<GlobalVariable>(V)) {
586 // ignore values where we cannot do more than what ObjectSizeVisitor can
589 DEBUG(dbgs() << "ObjectSizeOffsetEvaluator::compute() unhandled value: "
595 Builder.SetInsertPoint(PrevInsertPoint);
597 // Don't reuse CacheIt since it may be invalid at this point.
598 CacheMap[V] = Result;
602 SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitAllocaInst(AllocaInst &I) {
603 if (!I.getAllocatedType()->isSized())
607 assert(I.isArrayAllocation());
608 Value *ArraySize = I.getArraySize();
609 Value *Size = ConstantInt::get(ArraySize->getType(),
610 TD->getTypeAllocSize(I.getAllocatedType()));
611 Size = Builder.CreateMul(Size, ArraySize);
612 return std::make_pair(Size, Zero);
615 SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitCallSite(CallSite CS) {
616 const AllocFnsTy *FnData = getAllocationData(CS.getInstruction(), AnyAlloc);
620 // handle strdup-like functions separately
621 if (FnData->AllocTy == StrDupLike) {
622 IRBuilder<> StdBuilder(Builder.GetInsertPoint());
625 // strdup(str): size = strlen(str)+1
626 if (FnData->FstParam < 0)
627 Size = EmitStrLen(CS.getArgument(0), StdBuilder, TD, TLI);
629 // strndup(str, maxlen): size = strnlen(str, maxlen)+1
630 Size = EmitStrNLen(CS.getArgument(0), CS.getArgument(FnData->FstParam),
631 StdBuilder, TD, TLI);
634 Builder.SetInsertPoint(StdBuilder.GetInsertPoint());
635 Size = Builder.CreateNUWAdd(Size, ConstantInt::get(IntTy, 1));
636 return std::make_pair(Size, Zero);
639 Value *FirstArg = CS.getArgument(FnData->FstParam);
640 FirstArg = Builder.CreateZExt(FirstArg, IntTy);
641 if (FnData->SndParam < 0)
642 return std::make_pair(FirstArg, Zero);
644 Value *SecondArg = CS.getArgument(FnData->SndParam);
645 SecondArg = Builder.CreateZExt(SecondArg, IntTy);
646 Value *Size = Builder.CreateMul(FirstArg, SecondArg);
647 return std::make_pair(Size, Zero);
649 // TODO: handle more standard functions (+ wchar cousins):
650 // - strcpy / strncpy
651 // - strcat / strncat
652 // - memcpy / memmove
657 ObjectSizeOffsetEvaluator::visitExtractElementInst(ExtractElementInst&) {
662 ObjectSizeOffsetEvaluator::visitExtractValueInst(ExtractValueInst&) {
667 ObjectSizeOffsetEvaluator::visitGEPOperator(GEPOperator &GEP) {
668 SizeOffsetEvalType PtrData = compute_(GEP.getPointerOperand());
669 if (!bothKnown(PtrData))
672 Value *Offset = EmitGEPOffset(&Builder, *TD, &GEP, /*NoAssumptions=*/true);
673 Offset = Builder.CreateAdd(PtrData.second, Offset);
674 return std::make_pair(PtrData.first, Offset);
677 SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitIntToPtrInst(IntToPtrInst&) {
682 SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitLoadInst(LoadInst&) {
686 SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitPHINode(PHINode &PHI) {
687 // create 2 PHIs: one for size and another for offset
688 PHINode *SizePHI = Builder.CreatePHI(IntTy, PHI.getNumIncomingValues());
689 PHINode *OffsetPHI = Builder.CreatePHI(IntTy, PHI.getNumIncomingValues());
691 // insert right away in the cache to handle recursive PHIs
692 CacheMap[&PHI] = std::make_pair(SizePHI, OffsetPHI);
694 // compute offset/size for each PHI incoming pointer
695 for (unsigned i = 0, e = PHI.getNumIncomingValues(); i != e; ++i) {
696 Builder.SetInsertPoint(PHI.getIncomingBlock(i)->getFirstInsertionPt());
697 SizeOffsetEvalType EdgeData = compute_(PHI.getIncomingValue(i));
699 if (!bothKnown(EdgeData)) {
700 OffsetPHI->replaceAllUsesWith(UndefValue::get(IntTy));
701 OffsetPHI->eraseFromParent();
702 SizePHI->replaceAllUsesWith(UndefValue::get(IntTy));
703 SizePHI->eraseFromParent();
706 SizePHI->addIncoming(EdgeData.first, PHI.getIncomingBlock(i));
707 OffsetPHI->addIncoming(EdgeData.second, PHI.getIncomingBlock(i));
710 Value *Size = SizePHI, *Offset = OffsetPHI, *Tmp;
711 if ((Tmp = SizePHI->hasConstantValue())) {
713 SizePHI->replaceAllUsesWith(Size);
714 SizePHI->eraseFromParent();
716 if ((Tmp = OffsetPHI->hasConstantValue())) {
718 OffsetPHI->replaceAllUsesWith(Offset);
719 OffsetPHI->eraseFromParent();
721 return std::make_pair(Size, Offset);
724 SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitSelectInst(SelectInst &I) {
725 SizeOffsetEvalType TrueSide = compute_(I.getTrueValue());
726 SizeOffsetEvalType FalseSide = compute_(I.getFalseValue());
728 if (!bothKnown(TrueSide) || !bothKnown(FalseSide))
730 if (TrueSide == FalseSide)
733 Value *Size = Builder.CreateSelect(I.getCondition(), TrueSide.first,
735 Value *Offset = Builder.CreateSelect(I.getCondition(), TrueSide.second,
737 return std::make_pair(Size, Offset);
740 SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitInstruction(Instruction &I) {
741 DEBUG(dbgs() << "ObjectSizeOffsetEvaluator unknown instruction:" << I <<'\n');