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