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