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