1 //===- MemoryBuiltins.cpp - Identify calls to memory builtins -------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This family of functions identifies calls to builtin functions that allocate
10 // or free memory.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/Analysis/MemoryBuiltins.h"
15 #include "llvm/ADT/APInt.h"
16 #include "llvm/ADT/None.h"
17 #include "llvm/ADT/Optional.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/ADT/Statistic.h"
20 #include "llvm/ADT/StringRef.h"
21 #include "llvm/Analysis/TargetFolder.h"
22 #include "llvm/Analysis/TargetLibraryInfo.h"
23 #include "llvm/Analysis/Utils/Local.h"
24 #include "llvm/Analysis/ValueTracking.h"
25 #include "llvm/IR/Argument.h"
26 #include "llvm/IR/Attributes.h"
27 #include "llvm/IR/Constants.h"
28 #include "llvm/IR/DataLayout.h"
29 #include "llvm/IR/DerivedTypes.h"
30 #include "llvm/IR/Function.h"
31 #include "llvm/IR/GlobalAlias.h"
32 #include "llvm/IR/GlobalVariable.h"
33 #include "llvm/IR/Instruction.h"
34 #include "llvm/IR/Instructions.h"
35 #include "llvm/IR/IntrinsicInst.h"
36 #include "llvm/IR/Operator.h"
37 #include "llvm/IR/Type.h"
38 #include "llvm/IR/Value.h"
39 #include "llvm/Support/Casting.h"
40 #include "llvm/Support/Debug.h"
41 #include "llvm/Support/MathExtras.h"
42 #include "llvm/Support/raw_ostream.h"
43 #include <cassert>
44 #include <cstdint>
45 #include <iterator>
46 #include <utility>
47 
48 using namespace llvm;
49 
50 #define DEBUG_TYPE "memory-builtins"
51 
52 enum AllocType : uint8_t {
53   OpNewLike          = 1<<0, // allocates; never returns null
54   MallocLike         = 1<<1 | OpNewLike, // allocates; may return null
55   AlignedAllocLike   = 1<<2, // allocates with alignment; may return null
56   CallocLike         = 1<<3, // allocates + bzero
57   ReallocLike        = 1<<4, // reallocates
58   StrDupLike         = 1<<5,
59   MallocOrCallocLike = MallocLike | CallocLike | AlignedAllocLike,
60   AllocLike          = MallocOrCallocLike | StrDupLike,
61   AnyAlloc           = AllocLike | ReallocLike
62 };
63 
64 struct AllocFnsTy {
65   AllocType AllocTy;
66   unsigned NumParams;
67   // First and Second size parameters (or -1 if unused)
68   int FstParam, SndParam;
69 };
70 
71 // FIXME: certain users need more information. E.g., SimplifyLibCalls needs to
72 // know which functions are nounwind, noalias, nocapture parameters, etc.
73 static const std::pair<LibFunc, AllocFnsTy> AllocationFnData[] = {
74   {LibFunc_malloc,              {MallocLike,  1, 0,  -1}},
75   {LibFunc_valloc,              {MallocLike,  1, 0,  -1}},
76   {LibFunc_Znwj,                {OpNewLike,   1, 0,  -1}}, // new(unsigned int)
77   {LibFunc_ZnwjRKSt9nothrow_t,  {MallocLike,  2, 0,  -1}}, // new(unsigned int, nothrow)
78   {LibFunc_ZnwjSt11align_val_t, {OpNewLike,   2, 0,  -1}}, // new(unsigned int, align_val_t)
79   {LibFunc_ZnwjSt11align_val_tRKSt9nothrow_t, // new(unsigned int, align_val_t, nothrow)
80                                 {MallocLike,  3, 0,  -1}},
81   {LibFunc_Znwm,                {OpNewLike,   1, 0,  -1}}, // new(unsigned long)
82   {LibFunc_ZnwmRKSt9nothrow_t,  {MallocLike,  2, 0,  -1}}, // new(unsigned long, nothrow)
83   {LibFunc_ZnwmSt11align_val_t, {OpNewLike,   2, 0,  -1}}, // new(unsigned long, align_val_t)
84   {LibFunc_ZnwmSt11align_val_tRKSt9nothrow_t, // new(unsigned long, align_val_t, nothrow)
85                                 {MallocLike,  3, 0,  -1}},
86   {LibFunc_Znaj,                {OpNewLike,   1, 0,  -1}}, // new[](unsigned int)
87   {LibFunc_ZnajRKSt9nothrow_t,  {MallocLike,  2, 0,  -1}}, // new[](unsigned int, nothrow)
88   {LibFunc_ZnajSt11align_val_t, {OpNewLike,   2, 0,  -1}}, // new[](unsigned int, align_val_t)
89   {LibFunc_ZnajSt11align_val_tRKSt9nothrow_t, // new[](unsigned int, align_val_t, nothrow)
90                                 {MallocLike,  3, 0,  -1}},
91   {LibFunc_Znam,                {OpNewLike,   1, 0,  -1}}, // new[](unsigned long)
92   {LibFunc_ZnamRKSt9nothrow_t,  {MallocLike,  2, 0,  -1}}, // new[](unsigned long, nothrow)
93   {LibFunc_ZnamSt11align_val_t, {OpNewLike,   2, 0,  -1}}, // new[](unsigned long, align_val_t)
94   {LibFunc_ZnamSt11align_val_tRKSt9nothrow_t, // new[](unsigned long, align_val_t, nothrow)
95                                  {MallocLike,  3, 0,  -1}},
96   {LibFunc_msvc_new_int,         {OpNewLike,   1, 0,  -1}}, // new(unsigned int)
97   {LibFunc_msvc_new_int_nothrow, {MallocLike,  2, 0,  -1}}, // new(unsigned int, nothrow)
98   {LibFunc_msvc_new_longlong,         {OpNewLike,   1, 0,  -1}}, // new(unsigned long long)
99   {LibFunc_msvc_new_longlong_nothrow, {MallocLike,  2, 0,  -1}}, // new(unsigned long long, nothrow)
100   {LibFunc_msvc_new_array_int,         {OpNewLike,   1, 0,  -1}}, // new[](unsigned int)
101   {LibFunc_msvc_new_array_int_nothrow, {MallocLike,  2, 0,  -1}}, // new[](unsigned int, nothrow)
102   {LibFunc_msvc_new_array_longlong,         {OpNewLike,   1, 0,  -1}}, // new[](unsigned long long)
103   {LibFunc_msvc_new_array_longlong_nothrow, {MallocLike,  2, 0,  -1}}, // new[](unsigned long long, nothrow)
104   {LibFunc_aligned_alloc,       {AlignedAllocLike, 2, 1,  -1}},
105   {LibFunc_calloc,              {CallocLike,  2, 0,   1}},
106   {LibFunc_realloc,             {ReallocLike, 2, 1,  -1}},
107   {LibFunc_reallocf,            {ReallocLike, 2, 1,  -1}},
108   {LibFunc_strdup,              {StrDupLike,  1, -1, -1}},
109   {LibFunc_strndup,             {StrDupLike,  2, 1,  -1}}
110   // TODO: Handle "int posix_memalign(void **, size_t, size_t)"
111 };
112 
113 static const Function *getCalledFunction(const Value *V, bool LookThroughBitCast,
114                                          bool &IsNoBuiltin) {
115   // Don't care about intrinsics in this case.
116   if (isa<IntrinsicInst>(V))
117     return nullptr;
118 
119   if (LookThroughBitCast)
120     V = V->stripPointerCasts();
121 
122   ImmutableCallSite CS(V);
123   if (!CS.getInstruction())
124     return nullptr;
125 
126   IsNoBuiltin = CS.isNoBuiltin();
127 
128   if (const Function *Callee = CS.getCalledFunction())
129     return Callee;
130   return nullptr;
131 }
132 
133 /// Returns the allocation data for the given value if it's either a call to a
134 /// known allocation function, or a call to a function with the allocsize
135 /// attribute.
136 static Optional<AllocFnsTy>
137 getAllocationDataForFunction(const Function *Callee, AllocType AllocTy,
138                              const TargetLibraryInfo *TLI) {
139   // Make sure that the function is available.
140   StringRef FnName = Callee->getName();
141   LibFunc TLIFn;
142   if (!TLI || !TLI->getLibFunc(FnName, TLIFn) || !TLI->has(TLIFn))
143     return None;
144 
145   const auto *Iter = find_if(
146       AllocationFnData, [TLIFn](const std::pair<LibFunc, AllocFnsTy> &P) {
147         return P.first == TLIFn;
148       });
149 
150   if (Iter == std::end(AllocationFnData))
151     return None;
152 
153   const AllocFnsTy *FnData = &Iter->second;
154   if ((FnData->AllocTy & AllocTy) != FnData->AllocTy)
155     return None;
156 
157   // Check function prototype.
158   int FstParam = FnData->FstParam;
159   int SndParam = FnData->SndParam;
160   FunctionType *FTy = Callee->getFunctionType();
161 
162   if (FTy->getReturnType() == Type::getInt8PtrTy(FTy->getContext()) &&
163       FTy->getNumParams() == FnData->NumParams &&
164       (FstParam < 0 ||
165        (FTy->getParamType(FstParam)->isIntegerTy(32) ||
166         FTy->getParamType(FstParam)->isIntegerTy(64))) &&
167       (SndParam < 0 ||
168        FTy->getParamType(SndParam)->isIntegerTy(32) ||
169        FTy->getParamType(SndParam)->isIntegerTy(64)))
170     return *FnData;
171   return None;
172 }
173 
174 static Optional<AllocFnsTy> getAllocationData(const Value *V, AllocType AllocTy,
175                                               const TargetLibraryInfo *TLI,
176                                               bool LookThroughBitCast = false) {
177   bool IsNoBuiltinCall;
178   if (const Function *Callee =
179           getCalledFunction(V, LookThroughBitCast, IsNoBuiltinCall))
180     if (!IsNoBuiltinCall)
181       return getAllocationDataForFunction(Callee, AllocTy, TLI);
182   return None;
183 }
184 
185 static Optional<AllocFnsTy>
186 getAllocationData(const Value *V, AllocType AllocTy,
187                   function_ref<const TargetLibraryInfo &(Function &)> GetTLI,
188                   bool LookThroughBitCast = false) {
189   bool IsNoBuiltinCall;
190   if (const Function *Callee =
191           getCalledFunction(V, LookThroughBitCast, IsNoBuiltinCall))
192     if (!IsNoBuiltinCall)
193       return getAllocationDataForFunction(
194           Callee, AllocTy, &GetTLI(const_cast<Function &>(*Callee)));
195   return None;
196 }
197 
198 static Optional<AllocFnsTy> getAllocationSize(const Value *V,
199                                               const TargetLibraryInfo *TLI) {
200   bool IsNoBuiltinCall;
201   const Function *Callee =
202       getCalledFunction(V, /*LookThroughBitCast=*/false, IsNoBuiltinCall);
203   if (!Callee)
204     return None;
205 
206   // Prefer to use existing information over allocsize. This will give us an
207   // accurate AllocTy.
208   if (!IsNoBuiltinCall)
209     if (Optional<AllocFnsTy> Data =
210             getAllocationDataForFunction(Callee, AnyAlloc, TLI))
211       return Data;
212 
213   Attribute Attr = Callee->getFnAttribute(Attribute::AllocSize);
214   if (Attr == Attribute())
215     return None;
216 
217   std::pair<unsigned, Optional<unsigned>> Args = Attr.getAllocSizeArgs();
218 
219   AllocFnsTy Result;
220   // Because allocsize only tells us how many bytes are allocated, we're not
221   // really allowed to assume anything, so we use MallocLike.
222   Result.AllocTy = MallocLike;
223   Result.NumParams = Callee->getNumOperands();
224   Result.FstParam = Args.first;
225   Result.SndParam = Args.second.getValueOr(-1);
226   return Result;
227 }
228 
229 static bool hasNoAliasAttr(const Value *V, bool LookThroughBitCast) {
230   ImmutableCallSite CS(LookThroughBitCast ? V->stripPointerCasts() : V);
231   return CS && CS.hasRetAttr(Attribute::NoAlias);
232 }
233 
234 /// Tests if a value is a call or invoke to a library function that
235 /// allocates or reallocates memory (either malloc, calloc, realloc, or strdup
236 /// like).
237 bool llvm::isAllocationFn(const Value *V, const TargetLibraryInfo *TLI,
238                           bool LookThroughBitCast) {
239   return getAllocationData(V, AnyAlloc, TLI, LookThroughBitCast).hasValue();
240 }
241 bool llvm::isAllocationFn(
242     const Value *V, function_ref<const TargetLibraryInfo &(Function &)> GetTLI,
243     bool LookThroughBitCast) {
244   return getAllocationData(V, AnyAlloc, GetTLI, LookThroughBitCast).hasValue();
245 }
246 
247 /// Tests if a value is a call or invoke to a function that returns a
248 /// NoAlias pointer (including malloc/calloc/realloc/strdup-like functions).
249 bool llvm::isNoAliasFn(const Value *V, const TargetLibraryInfo *TLI,
250                        bool LookThroughBitCast) {
251   // it's safe to consider realloc as noalias since accessing the original
252   // pointer is undefined behavior
253   return isAllocationFn(V, TLI, LookThroughBitCast) ||
254          hasNoAliasAttr(V, LookThroughBitCast);
255 }
256 
257 /// Tests if a value is a call or invoke to a library function that
258 /// allocates uninitialized memory (such as malloc).
259 bool llvm::isMallocLikeFn(const Value *V, const TargetLibraryInfo *TLI,
260                           bool LookThroughBitCast) {
261   return getAllocationData(V, MallocLike, TLI, LookThroughBitCast).hasValue();
262 }
263 bool llvm::isMallocLikeFn(
264     const Value *V, function_ref<const TargetLibraryInfo &(Function &)> GetTLI,
265     bool LookThroughBitCast) {
266   return getAllocationData(V, MallocLike, GetTLI, LookThroughBitCast)
267       .hasValue();
268 }
269 
270 /// Tests if a value is a call or invoke to a library function that
271 /// allocates uninitialized memory with alignment (such as aligned_alloc).
272 bool llvm::isAlignedAllocLikeFn(const Value *V, const TargetLibraryInfo *TLI,
273                                 bool LookThroughBitCast) {
274   return getAllocationData(V, AlignedAllocLike, TLI, LookThroughBitCast)
275       .hasValue();
276 }
277 bool llvm::isAlignedAllocLikeFn(
278     const Value *V, function_ref<const TargetLibraryInfo &(Function &)> GetTLI,
279     bool LookThroughBitCast) {
280   return getAllocationData(V, AlignedAllocLike, GetTLI, LookThroughBitCast)
281       .hasValue();
282 }
283 
284 /// Tests if a value is a call or invoke to a library function that
285 /// allocates zero-filled memory (such as calloc).
286 bool llvm::isCallocLikeFn(const Value *V, const TargetLibraryInfo *TLI,
287                           bool LookThroughBitCast) {
288   return getAllocationData(V, CallocLike, TLI, LookThroughBitCast).hasValue();
289 }
290 
291 /// Tests if a value is a call or invoke to a library function that
292 /// allocates memory similar to malloc or calloc.
293 bool llvm::isMallocOrCallocLikeFn(const Value *V, const TargetLibraryInfo *TLI,
294                                   bool LookThroughBitCast) {
295   return getAllocationData(V, MallocOrCallocLike, TLI,
296                            LookThroughBitCast).hasValue();
297 }
298 
299 /// Tests if a value is a call or invoke to a library function that
300 /// allocates memory (either malloc, calloc, or strdup like).
301 bool llvm::isAllocLikeFn(const Value *V, const TargetLibraryInfo *TLI,
302                          bool LookThroughBitCast) {
303   return getAllocationData(V, AllocLike, TLI, LookThroughBitCast).hasValue();
304 }
305 
306 /// Tests if a value is a call or invoke to a library function that
307 /// reallocates memory (e.g., realloc).
308 bool llvm::isReallocLikeFn(const Value *V, const TargetLibraryInfo *TLI,
309                      bool LookThroughBitCast) {
310   return getAllocationData(V, ReallocLike, TLI, LookThroughBitCast).hasValue();
311 }
312 
313 /// Tests if a functions is a call or invoke to a library function that
314 /// reallocates memory (e.g., realloc).
315 bool llvm::isReallocLikeFn(const Function *F, const TargetLibraryInfo *TLI) {
316   return getAllocationDataForFunction(F, ReallocLike, TLI).hasValue();
317 }
318 
319 /// Tests if a value is a call or invoke to a library function that
320 /// allocates memory and throws if an allocation failed (e.g., new).
321 bool llvm::isOpNewLikeFn(const Value *V, const TargetLibraryInfo *TLI,
322                      bool LookThroughBitCast) {
323   return getAllocationData(V, OpNewLike, TLI, LookThroughBitCast).hasValue();
324 }
325 
326 /// Tests if a value is a call or invoke to a library function that
327 /// allocates memory (strdup, strndup).
328 bool llvm::isStrdupLikeFn(const Value *V, const TargetLibraryInfo *TLI,
329                           bool LookThroughBitCast) {
330   return getAllocationData(V, StrDupLike, TLI, LookThroughBitCast).hasValue();
331 }
332 
333 /// extractMallocCall - Returns the corresponding CallInst if the instruction
334 /// is a malloc call.  Since CallInst::CreateMalloc() only creates calls, we
335 /// ignore InvokeInst here.
336 const CallInst *llvm::extractMallocCall(
337     const Value *I,
338     function_ref<const TargetLibraryInfo &(Function &)> GetTLI) {
339   return isMallocLikeFn(I, GetTLI) ? dyn_cast<CallInst>(I) : nullptr;
340 }
341 
342 static Value *computeArraySize(const CallInst *CI, const DataLayout &DL,
343                                const TargetLibraryInfo *TLI,
344                                bool LookThroughSExt = false) {
345   if (!CI)
346     return nullptr;
347 
348   // The size of the malloc's result type must be known to determine array size.
349   Type *T = getMallocAllocatedType(CI, TLI);
350   if (!T || !T->isSized())
351     return nullptr;
352 
353   unsigned ElementSize = DL.getTypeAllocSize(T);
354   if (StructType *ST = dyn_cast<StructType>(T))
355     ElementSize = DL.getStructLayout(ST)->getSizeInBytes();
356 
357   // If malloc call's arg can be determined to be a multiple of ElementSize,
358   // return the multiple.  Otherwise, return NULL.
359   Value *MallocArg = CI->getArgOperand(0);
360   Value *Multiple = nullptr;
361   if (ComputeMultiple(MallocArg, ElementSize, Multiple, LookThroughSExt))
362     return Multiple;
363 
364   return nullptr;
365 }
366 
367 /// getMallocType - Returns the PointerType resulting from the malloc call.
368 /// The PointerType depends on the number of bitcast uses of the malloc call:
369 ///   0: PointerType is the calls' return type.
370 ///   1: PointerType is the bitcast's result type.
371 ///  >1: Unique PointerType cannot be determined, return NULL.
372 PointerType *llvm::getMallocType(const CallInst *CI,
373                                  const TargetLibraryInfo *TLI) {
374   assert(isMallocLikeFn(CI, TLI) && "getMallocType and not malloc call");
375 
376   PointerType *MallocType = nullptr;
377   unsigned NumOfBitCastUses = 0;
378 
379   // Determine if CallInst has a bitcast use.
380   for (Value::const_user_iterator UI = CI->user_begin(), E = CI->user_end();
381        UI != E;)
382     if (const BitCastInst *BCI = dyn_cast<BitCastInst>(*UI++)) {
383       MallocType = cast<PointerType>(BCI->getDestTy());
384       NumOfBitCastUses++;
385     }
386 
387   // Malloc call has 1 bitcast use, so type is the bitcast's destination type.
388   if (NumOfBitCastUses == 1)
389     return MallocType;
390 
391   // Malloc call was not bitcast, so type is the malloc function's return type.
392   if (NumOfBitCastUses == 0)
393     return cast<PointerType>(CI->getType());
394 
395   // Type could not be determined.
396   return nullptr;
397 }
398 
399 /// getMallocAllocatedType - Returns the Type allocated by malloc call.
400 /// The Type depends on the number of bitcast uses of the malloc call:
401 ///   0: PointerType is the malloc calls' return type.
402 ///   1: PointerType is the bitcast's result type.
403 ///  >1: Unique PointerType cannot be determined, return NULL.
404 Type *llvm::getMallocAllocatedType(const CallInst *CI,
405                                    const TargetLibraryInfo *TLI) {
406   PointerType *PT = getMallocType(CI, TLI);
407   return PT ? PT->getElementType() : nullptr;
408 }
409 
410 /// getMallocArraySize - Returns the array size of a malloc call.  If the
411 /// argument passed to malloc is a multiple of the size of the malloced type,
412 /// then return that multiple.  For non-array mallocs, the multiple is
413 /// constant 1.  Otherwise, return NULL for mallocs whose array size cannot be
414 /// determined.
415 Value *llvm::getMallocArraySize(CallInst *CI, const DataLayout &DL,
416                                 const TargetLibraryInfo *TLI,
417                                 bool LookThroughSExt) {
418   assert(isMallocLikeFn(CI, TLI) && "getMallocArraySize and not malloc call");
419   return computeArraySize(CI, DL, TLI, LookThroughSExt);
420 }
421 
422 /// extractCallocCall - Returns the corresponding CallInst if the instruction
423 /// is a calloc call.
424 const CallInst *llvm::extractCallocCall(const Value *I,
425                                         const TargetLibraryInfo *TLI) {
426   return isCallocLikeFn(I, TLI) ? cast<CallInst>(I) : nullptr;
427 }
428 
429 /// isLibFreeFunction - Returns true if the function is a builtin free()
430 bool llvm::isLibFreeFunction(const Function *F, const LibFunc TLIFn) {
431   unsigned ExpectedNumParams;
432   if (TLIFn == LibFunc_free ||
433       TLIFn == LibFunc_ZdlPv || // operator delete(void*)
434       TLIFn == LibFunc_ZdaPv || // operator delete[](void*)
435       TLIFn == LibFunc_msvc_delete_ptr32 || // operator delete(void*)
436       TLIFn == LibFunc_msvc_delete_ptr64 || // operator delete(void*)
437       TLIFn == LibFunc_msvc_delete_array_ptr32 || // operator delete[](void*)
438       TLIFn == LibFunc_msvc_delete_array_ptr64)   // operator delete[](void*)
439     ExpectedNumParams = 1;
440   else if (TLIFn == LibFunc_ZdlPvj ||              // delete(void*, uint)
441            TLIFn == LibFunc_ZdlPvm ||              // delete(void*, ulong)
442            TLIFn == LibFunc_ZdlPvRKSt9nothrow_t || // delete(void*, nothrow)
443            TLIFn == LibFunc_ZdlPvSt11align_val_t || // delete(void*, align_val_t)
444            TLIFn == LibFunc_ZdaPvj ||              // delete[](void*, uint)
445            TLIFn == LibFunc_ZdaPvm ||              // delete[](void*, ulong)
446            TLIFn == LibFunc_ZdaPvRKSt9nothrow_t || // delete[](void*, nothrow)
447            TLIFn == LibFunc_ZdaPvSt11align_val_t || // delete[](void*, align_val_t)
448            TLIFn == LibFunc_msvc_delete_ptr32_int ||      // delete(void*, uint)
449            TLIFn == LibFunc_msvc_delete_ptr64_longlong || // delete(void*, ulonglong)
450            TLIFn == LibFunc_msvc_delete_ptr32_nothrow || // delete(void*, nothrow)
451            TLIFn == LibFunc_msvc_delete_ptr64_nothrow || // delete(void*, nothrow)
452            TLIFn == LibFunc_msvc_delete_array_ptr32_int ||      // delete[](void*, uint)
453            TLIFn == LibFunc_msvc_delete_array_ptr64_longlong || // delete[](void*, ulonglong)
454            TLIFn == LibFunc_msvc_delete_array_ptr32_nothrow || // delete[](void*, nothrow)
455            TLIFn == LibFunc_msvc_delete_array_ptr64_nothrow)   // delete[](void*, nothrow)
456     ExpectedNumParams = 2;
457   else if (TLIFn == LibFunc_ZdaPvSt11align_val_tRKSt9nothrow_t || // delete(void*, align_val_t, nothrow)
458            TLIFn == LibFunc_ZdlPvSt11align_val_tRKSt9nothrow_t) // delete[](void*, align_val_t, nothrow)
459     ExpectedNumParams = 3;
460   else
461     return false;
462 
463   // Check free prototype.
464   // FIXME: workaround for PR5130, this will be obsolete when a nobuiltin
465   // attribute will exist.
466   FunctionType *FTy = F->getFunctionType();
467   if (!FTy->getReturnType()->isVoidTy())
468     return false;
469   if (FTy->getNumParams() != ExpectedNumParams)
470     return false;
471   if (FTy->getParamType(0) != Type::getInt8PtrTy(F->getContext()))
472     return false;
473 
474   return true;
475 }
476 
477 /// isFreeCall - Returns non-null if the value is a call to the builtin free()
478 const CallInst *llvm::isFreeCall(const Value *I, const TargetLibraryInfo *TLI) {
479   bool IsNoBuiltinCall;
480   const Function *Callee =
481       getCalledFunction(I, /*LookThroughBitCast=*/false, IsNoBuiltinCall);
482   if (Callee == nullptr || IsNoBuiltinCall)
483     return nullptr;
484 
485   StringRef FnName = Callee->getName();
486   LibFunc TLIFn;
487   if (!TLI || !TLI->getLibFunc(FnName, TLIFn) || !TLI->has(TLIFn))
488     return nullptr;
489 
490   return isLibFreeFunction(Callee, TLIFn) ? dyn_cast<CallInst>(I) : nullptr;
491 }
492 
493 
494 //===----------------------------------------------------------------------===//
495 //  Utility functions to compute size of objects.
496 //
497 static APInt getSizeWithOverflow(const SizeOffsetType &Data) {
498   if (Data.second.isNegative() || Data.first.ult(Data.second))
499     return APInt(Data.first.getBitWidth(), 0);
500   return Data.first - Data.second;
501 }
502 
503 /// Compute the size of the object pointed by Ptr. Returns true and the
504 /// object size in Size if successful, and false otherwise.
505 /// If RoundToAlign is true, then Size is rounded up to the alignment of
506 /// allocas, byval arguments, and global variables.
507 bool llvm::getObjectSize(const Value *Ptr, uint64_t &Size, const DataLayout &DL,
508                          const TargetLibraryInfo *TLI, ObjectSizeOpts Opts) {
509   ObjectSizeOffsetVisitor Visitor(DL, TLI, Ptr->getContext(), Opts);
510   SizeOffsetType Data = Visitor.compute(const_cast<Value*>(Ptr));
511   if (!Visitor.bothKnown(Data))
512     return false;
513 
514   Size = getSizeWithOverflow(Data).getZExtValue();
515   return true;
516 }
517 
518 Value *llvm::lowerObjectSizeCall(IntrinsicInst *ObjectSize,
519                                  const DataLayout &DL,
520                                  const TargetLibraryInfo *TLI,
521                                  bool MustSucceed) {
522   assert(ObjectSize->getIntrinsicID() == Intrinsic::objectsize &&
523          "ObjectSize must be a call to llvm.objectsize!");
524 
525   bool MaxVal = cast<ConstantInt>(ObjectSize->getArgOperand(1))->isZero();
526   ObjectSizeOpts EvalOptions;
527   // Unless we have to fold this to something, try to be as accurate as
528   // possible.
529   if (MustSucceed)
530     EvalOptions.EvalMode =
531         MaxVal ? ObjectSizeOpts::Mode::Max : ObjectSizeOpts::Mode::Min;
532   else
533     EvalOptions.EvalMode = ObjectSizeOpts::Mode::Exact;
534 
535   EvalOptions.NullIsUnknownSize =
536       cast<ConstantInt>(ObjectSize->getArgOperand(2))->isOne();
537 
538   auto *ResultType = cast<IntegerType>(ObjectSize->getType());
539   bool StaticOnly = cast<ConstantInt>(ObjectSize->getArgOperand(3))->isZero();
540   if (StaticOnly) {
541     // FIXME: Does it make sense to just return a failure value if the size won't
542     // fit in the output and `!MustSucceed`?
543     uint64_t Size;
544     if (getObjectSize(ObjectSize->getArgOperand(0), Size, DL, TLI, EvalOptions) &&
545         isUIntN(ResultType->getBitWidth(), Size))
546       return ConstantInt::get(ResultType, Size);
547   } else {
548     LLVMContext &Ctx = ObjectSize->getFunction()->getContext();
549     ObjectSizeOffsetEvaluator Eval(DL, TLI, Ctx, EvalOptions);
550     SizeOffsetEvalType SizeOffsetPair =
551         Eval.compute(ObjectSize->getArgOperand(0));
552 
553     if (SizeOffsetPair != ObjectSizeOffsetEvaluator::unknown()) {
554       IRBuilder<TargetFolder> Builder(Ctx, TargetFolder(DL));
555       Builder.SetInsertPoint(ObjectSize);
556 
557       // If we've outside the end of the object, then we can always access
558       // exactly 0 bytes.
559       Value *ResultSize =
560           Builder.CreateSub(SizeOffsetPair.first, SizeOffsetPair.second);
561       Value *UseZero =
562           Builder.CreateICmpULT(SizeOffsetPair.first, SizeOffsetPair.second);
563       ResultSize = Builder.CreateZExtOrTrunc(ResultSize, ResultType);
564       return Builder.CreateSelect(UseZero, ConstantInt::get(ResultType, 0),
565                                   ResultSize);
566     }
567   }
568 
569   if (!MustSucceed)
570     return nullptr;
571 
572   return ConstantInt::get(ResultType, MaxVal ? -1ULL : 0);
573 }
574 
575 STATISTIC(ObjectVisitorArgument,
576           "Number of arguments with unsolved size and offset");
577 STATISTIC(ObjectVisitorLoad,
578           "Number of load instructions with unsolved size and offset");
579 
580 APInt ObjectSizeOffsetVisitor::align(APInt Size, uint64_t Alignment) {
581   if (Options.RoundToAlign && Alignment)
582     return APInt(IntTyBits, alignTo(Size.getZExtValue(), Align(Alignment)));
583   return Size;
584 }
585 
586 ObjectSizeOffsetVisitor::ObjectSizeOffsetVisitor(const DataLayout &DL,
587                                                  const TargetLibraryInfo *TLI,
588                                                  LLVMContext &Context,
589                                                  ObjectSizeOpts Options)
590     : DL(DL), TLI(TLI), Options(Options) {
591   // Pointer size must be rechecked for each object visited since it could have
592   // a different address space.
593 }
594 
595 SizeOffsetType ObjectSizeOffsetVisitor::compute(Value *V) {
596   IntTyBits = DL.getIndexTypeSizeInBits(V->getType());
597   Zero = APInt::getNullValue(IntTyBits);
598 
599   V = V->stripPointerCasts();
600   if (Instruction *I = dyn_cast<Instruction>(V)) {
601     // If we have already seen this instruction, bail out. Cycles can happen in
602     // unreachable code after constant propagation.
603     if (!SeenInsts.insert(I).second)
604       return unknown();
605 
606     if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
607       return visitGEPOperator(*GEP);
608     return visit(*I);
609   }
610   if (Argument *A = dyn_cast<Argument>(V))
611     return visitArgument(*A);
612   if (ConstantPointerNull *P = dyn_cast<ConstantPointerNull>(V))
613     return visitConstantPointerNull(*P);
614   if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
615     return visitGlobalAlias(*GA);
616   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
617     return visitGlobalVariable(*GV);
618   if (UndefValue *UV = dyn_cast<UndefValue>(V))
619     return visitUndefValue(*UV);
620   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
621     if (CE->getOpcode() == Instruction::IntToPtr)
622       return unknown(); // clueless
623     if (CE->getOpcode() == Instruction::GetElementPtr)
624       return visitGEPOperator(cast<GEPOperator>(*CE));
625   }
626 
627   LLVM_DEBUG(dbgs() << "ObjectSizeOffsetVisitor::compute() unhandled value: "
628                     << *V << '\n');
629   return unknown();
630 }
631 
632 /// When we're compiling N-bit code, and the user uses parameters that are
633 /// greater than N bits (e.g. uint64_t on a 32-bit build), we can run into
634 /// trouble with APInt size issues. This function handles resizing + overflow
635 /// checks for us. Check and zext or trunc \p I depending on IntTyBits and
636 /// I's value.
637 bool ObjectSizeOffsetVisitor::CheckedZextOrTrunc(APInt &I) {
638   // More bits than we can handle. Checking the bit width isn't necessary, but
639   // it's faster than checking active bits, and should give `false` in the
640   // vast majority of cases.
641   if (I.getBitWidth() > IntTyBits && I.getActiveBits() > IntTyBits)
642     return false;
643   if (I.getBitWidth() != IntTyBits)
644     I = I.zextOrTrunc(IntTyBits);
645   return true;
646 }
647 
648 SizeOffsetType ObjectSizeOffsetVisitor::visitAllocaInst(AllocaInst &I) {
649   if (!I.getAllocatedType()->isSized())
650     return unknown();
651 
652   if (I.getAllocatedType()->isVectorTy() &&
653       cast<VectorType>(I.getAllocatedType())->isScalable())
654     return unknown();
655 
656   APInt Size(IntTyBits, DL.getTypeAllocSize(I.getAllocatedType()));
657   if (!I.isArrayAllocation())
658     return std::make_pair(align(Size, I.getAlignment()), Zero);
659 
660   Value *ArraySize = I.getArraySize();
661   if (const ConstantInt *C = dyn_cast<ConstantInt>(ArraySize)) {
662     APInt NumElems = C->getValue();
663     if (!CheckedZextOrTrunc(NumElems))
664       return unknown();
665 
666     bool Overflow;
667     Size = Size.umul_ov(NumElems, Overflow);
668     return Overflow ? unknown() : std::make_pair(align(Size, I.getAlignment()),
669                                                  Zero);
670   }
671   return unknown();
672 }
673 
674 SizeOffsetType ObjectSizeOffsetVisitor::visitArgument(Argument &A) {
675   // No interprocedural analysis is done at the moment.
676   if (!A.hasByValOrInAllocaAttr()) {
677     ++ObjectVisitorArgument;
678     return unknown();
679   }
680   PointerType *PT = cast<PointerType>(A.getType());
681   APInt Size(IntTyBits, DL.getTypeAllocSize(PT->getElementType()));
682   return std::make_pair(align(Size, A.getParamAlignment()), Zero);
683 }
684 
685 SizeOffsetType ObjectSizeOffsetVisitor::visitCallSite(CallSite CS) {
686   Optional<AllocFnsTy> FnData = getAllocationSize(CS.getInstruction(), TLI);
687   if (!FnData)
688     return unknown();
689 
690   // Handle strdup-like functions separately.
691   if (FnData->AllocTy == StrDupLike) {
692     APInt Size(IntTyBits, GetStringLength(CS.getArgument(0)));
693     if (!Size)
694       return unknown();
695 
696     // Strndup limits strlen.
697     if (FnData->FstParam > 0) {
698       ConstantInt *Arg =
699           dyn_cast<ConstantInt>(CS.getArgument(FnData->FstParam));
700       if (!Arg)
701         return unknown();
702 
703       APInt MaxSize = Arg->getValue().zextOrSelf(IntTyBits);
704       if (Size.ugt(MaxSize))
705         Size = MaxSize + 1;
706     }
707     return std::make_pair(Size, Zero);
708   }
709 
710   ConstantInt *Arg = dyn_cast<ConstantInt>(CS.getArgument(FnData->FstParam));
711   if (!Arg)
712     return unknown();
713 
714   APInt Size = Arg->getValue();
715   if (!CheckedZextOrTrunc(Size))
716     return unknown();
717 
718   // Size is determined by just 1 parameter.
719   if (FnData->SndParam < 0)
720     return std::make_pair(Size, Zero);
721 
722   Arg = dyn_cast<ConstantInt>(CS.getArgument(FnData->SndParam));
723   if (!Arg)
724     return unknown();
725 
726   APInt NumElems = Arg->getValue();
727   if (!CheckedZextOrTrunc(NumElems))
728     return unknown();
729 
730   bool Overflow;
731   Size = Size.umul_ov(NumElems, Overflow);
732   return Overflow ? unknown() : std::make_pair(Size, Zero);
733 
734   // TODO: handle more standard functions (+ wchar cousins):
735   // - strdup / strndup
736   // - strcpy / strncpy
737   // - strcat / strncat
738   // - memcpy / memmove
739   // - strcat / strncat
740   // - memset
741 }
742 
743 SizeOffsetType
744 ObjectSizeOffsetVisitor::visitConstantPointerNull(ConstantPointerNull& CPN) {
745   // If null is unknown, there's nothing we can do. Additionally, non-zero
746   // address spaces can make use of null, so we don't presume to know anything
747   // about that.
748   //
749   // TODO: How should this work with address space casts? We currently just drop
750   // them on the floor, but it's unclear what we should do when a NULL from
751   // addrspace(1) gets casted to addrspace(0) (or vice-versa).
752   if (Options.NullIsUnknownSize || CPN.getType()->getAddressSpace())
753     return unknown();
754   return std::make_pair(Zero, Zero);
755 }
756 
757 SizeOffsetType
758 ObjectSizeOffsetVisitor::visitExtractElementInst(ExtractElementInst&) {
759   return unknown();
760 }
761 
762 SizeOffsetType
763 ObjectSizeOffsetVisitor::visitExtractValueInst(ExtractValueInst&) {
764   // Easy cases were already folded by previous passes.
765   return unknown();
766 }
767 
768 SizeOffsetType ObjectSizeOffsetVisitor::visitGEPOperator(GEPOperator &GEP) {
769   SizeOffsetType PtrData = compute(GEP.getPointerOperand());
770   APInt Offset(DL.getIndexTypeSizeInBits(GEP.getPointerOperand()->getType()), 0);
771   if (!bothKnown(PtrData) || !GEP.accumulateConstantOffset(DL, Offset))
772     return unknown();
773 
774   return std::make_pair(PtrData.first, PtrData.second + Offset);
775 }
776 
777 SizeOffsetType ObjectSizeOffsetVisitor::visitGlobalAlias(GlobalAlias &GA) {
778   if (GA.isInterposable())
779     return unknown();
780   return compute(GA.getAliasee());
781 }
782 
783 SizeOffsetType ObjectSizeOffsetVisitor::visitGlobalVariable(GlobalVariable &GV){
784   if (!GV.hasDefinitiveInitializer())
785     return unknown();
786 
787   APInt Size(IntTyBits, DL.getTypeAllocSize(GV.getValueType()));
788   return std::make_pair(align(Size, GV.getAlignment()), Zero);
789 }
790 
791 SizeOffsetType ObjectSizeOffsetVisitor::visitIntToPtrInst(IntToPtrInst&) {
792   // clueless
793   return unknown();
794 }
795 
796 SizeOffsetType ObjectSizeOffsetVisitor::visitLoadInst(LoadInst&) {
797   ++ObjectVisitorLoad;
798   return unknown();
799 }
800 
801 SizeOffsetType ObjectSizeOffsetVisitor::visitPHINode(PHINode&) {
802   // too complex to analyze statically.
803   return unknown();
804 }
805 
806 SizeOffsetType ObjectSizeOffsetVisitor::visitSelectInst(SelectInst &I) {
807   SizeOffsetType TrueSide  = compute(I.getTrueValue());
808   SizeOffsetType FalseSide = compute(I.getFalseValue());
809   if (bothKnown(TrueSide) && bothKnown(FalseSide)) {
810     if (TrueSide == FalseSide) {
811         return TrueSide;
812     }
813 
814     APInt TrueResult = getSizeWithOverflow(TrueSide);
815     APInt FalseResult = getSizeWithOverflow(FalseSide);
816 
817     if (TrueResult == FalseResult) {
818       return TrueSide;
819     }
820     if (Options.EvalMode == ObjectSizeOpts::Mode::Min) {
821       if (TrueResult.slt(FalseResult))
822         return TrueSide;
823       return FalseSide;
824     }
825     if (Options.EvalMode == ObjectSizeOpts::Mode::Max) {
826       if (TrueResult.sgt(FalseResult))
827         return TrueSide;
828       return FalseSide;
829     }
830   }
831   return unknown();
832 }
833 
834 SizeOffsetType ObjectSizeOffsetVisitor::visitUndefValue(UndefValue&) {
835   return std::make_pair(Zero, Zero);
836 }
837 
838 SizeOffsetType ObjectSizeOffsetVisitor::visitInstruction(Instruction &I) {
839   LLVM_DEBUG(dbgs() << "ObjectSizeOffsetVisitor unknown instruction:" << I
840                     << '\n');
841   return unknown();
842 }
843 
844 ObjectSizeOffsetEvaluator::ObjectSizeOffsetEvaluator(
845     const DataLayout &DL, const TargetLibraryInfo *TLI, LLVMContext &Context,
846     ObjectSizeOpts EvalOpts)
847     : DL(DL), TLI(TLI), Context(Context),
848       Builder(Context, TargetFolder(DL),
849               IRBuilderCallbackInserter(
850                   [&](Instruction *I) { InsertedInstructions.insert(I); })),
851       EvalOpts(EvalOpts) {
852   // IntTy and Zero must be set for each compute() since the address space may
853   // be different for later objects.
854 }
855 
856 SizeOffsetEvalType ObjectSizeOffsetEvaluator::compute(Value *V) {
857   // XXX - Are vectors of pointers possible here?
858   IntTy = cast<IntegerType>(DL.getIndexType(V->getType()));
859   Zero = ConstantInt::get(IntTy, 0);
860 
861   SizeOffsetEvalType Result = compute_(V);
862 
863   if (!bothKnown(Result)) {
864     // Erase everything that was computed in this iteration from the cache, so
865     // that no dangling references are left behind. We could be a bit smarter if
866     // we kept a dependency graph. It's probably not worth the complexity.
867     for (const Value *SeenVal : SeenVals) {
868       CacheMapTy::iterator CacheIt = CacheMap.find(SeenVal);
869       // non-computable results can be safely cached
870       if (CacheIt != CacheMap.end() && anyKnown(CacheIt->second))
871         CacheMap.erase(CacheIt);
872     }
873 
874     // Erase any instructions we inserted as part of the traversal.
875     for (Instruction *I : InsertedInstructions) {
876       I->replaceAllUsesWith(UndefValue::get(I->getType()));
877       I->eraseFromParent();
878     }
879   }
880 
881   SeenVals.clear();
882   InsertedInstructions.clear();
883   return Result;
884 }
885 
886 SizeOffsetEvalType ObjectSizeOffsetEvaluator::compute_(Value *V) {
887   ObjectSizeOffsetVisitor Visitor(DL, TLI, Context, EvalOpts);
888   SizeOffsetType Const = Visitor.compute(V);
889   if (Visitor.bothKnown(Const))
890     return std::make_pair(ConstantInt::get(Context, Const.first),
891                           ConstantInt::get(Context, Const.second));
892 
893   V = V->stripPointerCasts();
894 
895   // Check cache.
896   CacheMapTy::iterator CacheIt = CacheMap.find(V);
897   if (CacheIt != CacheMap.end())
898     return CacheIt->second;
899 
900   // Always generate code immediately before the instruction being
901   // processed, so that the generated code dominates the same BBs.
902   BuilderTy::InsertPointGuard Guard(Builder);
903   if (Instruction *I = dyn_cast<Instruction>(V))
904     Builder.SetInsertPoint(I);
905 
906   // Now compute the size and offset.
907   SizeOffsetEvalType Result;
908 
909   // Record the pointers that were handled in this run, so that they can be
910   // cleaned later if something fails. We also use this set to break cycles that
911   // can occur in dead code.
912   if (!SeenVals.insert(V).second) {
913     Result = unknown();
914   } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
915     Result = visitGEPOperator(*GEP);
916   } else if (Instruction *I = dyn_cast<Instruction>(V)) {
917     Result = visit(*I);
918   } else if (isa<Argument>(V) ||
919              (isa<ConstantExpr>(V) &&
920               cast<ConstantExpr>(V)->getOpcode() == Instruction::IntToPtr) ||
921              isa<GlobalAlias>(V) ||
922              isa<GlobalVariable>(V)) {
923     // Ignore values where we cannot do more than ObjectSizeVisitor.
924     Result = unknown();
925   } else {
926     LLVM_DEBUG(
927         dbgs() << "ObjectSizeOffsetEvaluator::compute() unhandled value: " << *V
928                << '\n');
929     Result = unknown();
930   }
931 
932   // Don't reuse CacheIt since it may be invalid at this point.
933   CacheMap[V] = Result;
934   return Result;
935 }
936 
937 SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitAllocaInst(AllocaInst &I) {
938   if (!I.getAllocatedType()->isSized())
939     return unknown();
940 
941   // must be a VLA
942   assert(I.isArrayAllocation());
943   Value *ArraySize = I.getArraySize();
944   Value *Size = ConstantInt::get(ArraySize->getType(),
945                                  DL.getTypeAllocSize(I.getAllocatedType()));
946   Size = Builder.CreateMul(Size, ArraySize);
947   return std::make_pair(Size, Zero);
948 }
949 
950 SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitCallSite(CallSite CS) {
951   Optional<AllocFnsTy> FnData = getAllocationSize(CS.getInstruction(), TLI);
952   if (!FnData)
953     return unknown();
954 
955   // Handle strdup-like functions separately.
956   if (FnData->AllocTy == StrDupLike) {
957     // TODO
958     return unknown();
959   }
960 
961   Value *FirstArg = CS.getArgument(FnData->FstParam);
962   FirstArg = Builder.CreateZExtOrTrunc(FirstArg, IntTy);
963   if (FnData->SndParam < 0)
964     return std::make_pair(FirstArg, Zero);
965 
966   Value *SecondArg = CS.getArgument(FnData->SndParam);
967   SecondArg = Builder.CreateZExtOrTrunc(SecondArg, IntTy);
968   Value *Size = Builder.CreateMul(FirstArg, SecondArg);
969   return std::make_pair(Size, Zero);
970 
971   // TODO: handle more standard functions (+ wchar cousins):
972   // - strdup / strndup
973   // - strcpy / strncpy
974   // - strcat / strncat
975   // - memcpy / memmove
976   // - strcat / strncat
977   // - memset
978 }
979 
980 SizeOffsetEvalType
981 ObjectSizeOffsetEvaluator::visitExtractElementInst(ExtractElementInst&) {
982   return unknown();
983 }
984 
985 SizeOffsetEvalType
986 ObjectSizeOffsetEvaluator::visitExtractValueInst(ExtractValueInst&) {
987   return unknown();
988 }
989 
990 SizeOffsetEvalType
991 ObjectSizeOffsetEvaluator::visitGEPOperator(GEPOperator &GEP) {
992   SizeOffsetEvalType PtrData = compute_(GEP.getPointerOperand());
993   if (!bothKnown(PtrData))
994     return unknown();
995 
996   Value *Offset = EmitGEPOffset(&Builder, DL, &GEP, /*NoAssumptions=*/true);
997   Offset = Builder.CreateAdd(PtrData.second, Offset);
998   return std::make_pair(PtrData.first, Offset);
999 }
1000 
1001 SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitIntToPtrInst(IntToPtrInst&) {
1002   // clueless
1003   return unknown();
1004 }
1005 
1006 SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitLoadInst(LoadInst&) {
1007   return unknown();
1008 }
1009 
1010 SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitPHINode(PHINode &PHI) {
1011   // Create 2 PHIs: one for size and another for offset.
1012   PHINode *SizePHI   = Builder.CreatePHI(IntTy, PHI.getNumIncomingValues());
1013   PHINode *OffsetPHI = Builder.CreatePHI(IntTy, PHI.getNumIncomingValues());
1014 
1015   // Insert right away in the cache to handle recursive PHIs.
1016   CacheMap[&PHI] = std::make_pair(SizePHI, OffsetPHI);
1017 
1018   // Compute offset/size for each PHI incoming pointer.
1019   for (unsigned i = 0, e = PHI.getNumIncomingValues(); i != e; ++i) {
1020     Builder.SetInsertPoint(&*PHI.getIncomingBlock(i)->getFirstInsertionPt());
1021     SizeOffsetEvalType EdgeData = compute_(PHI.getIncomingValue(i));
1022 
1023     if (!bothKnown(EdgeData)) {
1024       OffsetPHI->replaceAllUsesWith(UndefValue::get(IntTy));
1025       OffsetPHI->eraseFromParent();
1026       InsertedInstructions.erase(OffsetPHI);
1027       SizePHI->replaceAllUsesWith(UndefValue::get(IntTy));
1028       SizePHI->eraseFromParent();
1029       InsertedInstructions.erase(SizePHI);
1030       return unknown();
1031     }
1032     SizePHI->addIncoming(EdgeData.first, PHI.getIncomingBlock(i));
1033     OffsetPHI->addIncoming(EdgeData.second, PHI.getIncomingBlock(i));
1034   }
1035 
1036   Value *Size = SizePHI, *Offset = OffsetPHI;
1037   if (Value *Tmp = SizePHI->hasConstantValue()) {
1038     Size = Tmp;
1039     SizePHI->replaceAllUsesWith(Size);
1040     SizePHI->eraseFromParent();
1041     InsertedInstructions.erase(SizePHI);
1042   }
1043   if (Value *Tmp = OffsetPHI->hasConstantValue()) {
1044     Offset = Tmp;
1045     OffsetPHI->replaceAllUsesWith(Offset);
1046     OffsetPHI->eraseFromParent();
1047     InsertedInstructions.erase(OffsetPHI);
1048   }
1049   return std::make_pair(Size, Offset);
1050 }
1051 
1052 SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitSelectInst(SelectInst &I) {
1053   SizeOffsetEvalType TrueSide  = compute_(I.getTrueValue());
1054   SizeOffsetEvalType FalseSide = compute_(I.getFalseValue());
1055 
1056   if (!bothKnown(TrueSide) || !bothKnown(FalseSide))
1057     return unknown();
1058   if (TrueSide == FalseSide)
1059     return TrueSide;
1060 
1061   Value *Size = Builder.CreateSelect(I.getCondition(), TrueSide.first,
1062                                      FalseSide.first);
1063   Value *Offset = Builder.CreateSelect(I.getCondition(), TrueSide.second,
1064                                        FalseSide.second);
1065   return std::make_pair(Size, Offset);
1066 }
1067 
1068 SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitInstruction(Instruction &I) {
1069   LLVM_DEBUG(dbgs() << "ObjectSizeOffsetEvaluator unknown instruction:" << I
1070                     << '\n');
1071   return unknown();
1072 }
1073