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