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 static bool isMallocLikeFn(const Value *V, const TargetLibraryInfo *TLI) {
240   return getAllocationData(V, MallocOrOpNewLike, TLI).hasValue();
241 }
242 
243 /// Tests if a value is a call or invoke to a library function that
244 /// allocates uninitialized memory with alignment (such as aligned_alloc).
245 static bool isAlignedAllocLikeFn(const Value *V, const TargetLibraryInfo *TLI) {
246   return getAllocationData(V, AlignedAllocLike, TLI)
247       .hasValue();
248 }
249 
250 /// Tests if a value is a call or invoke to a library function that
251 /// allocates zero-filled memory (such as calloc).
252 static bool isCallocLikeFn(const Value *V, const TargetLibraryInfo *TLI) {
253   return getAllocationData(V, CallocLike, TLI).hasValue();
254 }
255 
256 /// Tests if a value is a call or invoke to a library function that
257 /// allocates memory similar to malloc or calloc.
258 bool llvm::isMallocOrCallocLikeFn(const Value *V, const TargetLibraryInfo *TLI) {
259   return getAllocationData(V, MallocOrCallocLike, TLI).hasValue();
260 }
261 
262 /// Tests if a value is a call or invoke to a library function that
263 /// allocates memory (either malloc, calloc, or strdup like).
264 bool llvm::isAllocLikeFn(const Value *V, const TargetLibraryInfo *TLI) {
265   return getAllocationData(V, AllocLike, TLI).hasValue();
266 }
267 
268 /// Tests if a value is a call or invoke to a library function that
269 /// reallocates memory (e.g., realloc).
270 bool llvm::isReallocLikeFn(const Value *V, const TargetLibraryInfo *TLI) {
271   return getAllocationData(V, ReallocLike, TLI).hasValue();
272 }
273 
274 /// Tests if a functions is a call or invoke to a library function that
275 /// reallocates memory (e.g., realloc).
276 bool llvm::isReallocLikeFn(const Function *F, const TargetLibraryInfo *TLI) {
277   return getAllocationDataForFunction(F, ReallocLike, TLI).hasValue();
278 }
279 
280 bool llvm::isAllocRemovable(const CallBase *CB, const TargetLibraryInfo *TLI) {
281   assert(isAllocationFn(CB, TLI));
282 
283   // Note: Removability is highly dependent on the source language.  For
284   // example, recent C++ requires direct calls to the global allocation
285   // [basic.stc.dynamic.allocation] to be observable unless part of a new
286   // expression [expr.new paragraph 13].
287 
288   // Historically we've treated the C family allocation routines as removable
289   return isAllocLikeFn(CB, TLI);
290 }
291 
292 Value *llvm::getAllocAlignment(const CallBase *V,
293                                const TargetLibraryInfo *TLI) {
294   assert(isAllocationFn(V, TLI));
295 
296   const Optional<AllocFnsTy> FnData = getAllocationData(V, AnyAlloc, TLI);
297   if (!FnData.hasValue() || FnData->AlignParam < 0) {
298     return nullptr;
299   }
300   return V->getOperand(FnData->AlignParam);
301 }
302 
303 /// When we're compiling N-bit code, and the user uses parameters that are
304 /// greater than N bits (e.g. uint64_t on a 32-bit build), we can run into
305 /// trouble with APInt size issues. This function handles resizing + overflow
306 /// checks for us. Check and zext or trunc \p I depending on IntTyBits and
307 /// I's value.
308 static bool CheckedZextOrTrunc(APInt &I, unsigned IntTyBits) {
309   // More bits than we can handle. Checking the bit width isn't necessary, but
310   // it's faster than checking active bits, and should give `false` in the
311   // vast majority of cases.
312   if (I.getBitWidth() > IntTyBits && I.getActiveBits() > IntTyBits)
313     return false;
314   if (I.getBitWidth() != IntTyBits)
315     I = I.zextOrTrunc(IntTyBits);
316   return true;
317 }
318 
319 Optional<APInt>
320 llvm::getAllocSize(const CallBase *CB,
321                    const TargetLibraryInfo *TLI,
322                    std::function<const Value*(const Value*)> Mapper) {
323   // Note: This handles both explicitly listed allocation functions and
324   // allocsize.  The code structure could stand to be cleaned up a bit.
325   Optional<AllocFnsTy> FnData = getAllocationSize(CB, TLI);
326   if (!FnData)
327     return None;
328 
329   // Get the index type for this address space, results and intermediate
330   // computations are performed at that width.
331   auto &DL = CB->getModule()->getDataLayout();
332   const unsigned IntTyBits = DL.getIndexTypeSizeInBits(CB->getType());
333 
334   // Handle strdup-like functions separately.
335   if (FnData->AllocTy == StrDupLike) {
336     APInt Size(IntTyBits, GetStringLength(Mapper(CB->getArgOperand(0))));
337     if (!Size)
338       return None;
339 
340     // Strndup limits strlen.
341     if (FnData->FstParam > 0) {
342       const ConstantInt *Arg =
343         dyn_cast<ConstantInt>(Mapper(CB->getArgOperand(FnData->FstParam)));
344       if (!Arg)
345         return None;
346 
347       APInt MaxSize = Arg->getValue().zextOrSelf(IntTyBits);
348       if (Size.ugt(MaxSize))
349         Size = MaxSize + 1;
350     }
351     return Size;
352   }
353 
354   const ConstantInt *Arg =
355     dyn_cast<ConstantInt>(Mapper(CB->getArgOperand(FnData->FstParam)));
356   if (!Arg)
357     return None;
358 
359   APInt Size = Arg->getValue();
360   if (!CheckedZextOrTrunc(Size, IntTyBits))
361     return None;
362 
363   // Size is determined by just 1 parameter.
364   if (FnData->SndParam < 0)
365     return Size;
366 
367   Arg = dyn_cast<ConstantInt>(Mapper(CB->getArgOperand(FnData->SndParam)));
368   if (!Arg)
369     return None;
370 
371   APInt NumElems = Arg->getValue();
372   if (!CheckedZextOrTrunc(NumElems, IntTyBits))
373     return None;
374 
375   bool Overflow;
376   Size = Size.umul_ov(NumElems, Overflow);
377   if (Overflow)
378     return None;
379   return Size;
380 }
381 
382 Constant *llvm::getInitialValueOfAllocation(const CallBase *Alloc,
383                                             const TargetLibraryInfo *TLI,
384                                             Type *Ty) {
385   assert(isAllocationFn(Alloc, TLI));
386 
387   // malloc and aligned_alloc are uninitialized (undef)
388   if (isMallocLikeFn(Alloc, TLI) || isAlignedAllocLikeFn(Alloc, TLI))
389     return UndefValue::get(Ty);
390 
391   // calloc zero initializes
392   if (isCallocLikeFn(Alloc, TLI))
393     return Constant::getNullValue(Ty);
394 
395   return nullptr;
396 }
397 
398 /// isLibFreeFunction - Returns true if the function is a builtin free()
399 bool llvm::isLibFreeFunction(const Function *F, const LibFunc TLIFn) {
400   unsigned ExpectedNumParams;
401   if (TLIFn == LibFunc_free ||
402       TLIFn == LibFunc_ZdlPv || // operator delete(void*)
403       TLIFn == LibFunc_ZdaPv || // operator delete[](void*)
404       TLIFn == LibFunc_msvc_delete_ptr32 || // operator delete(void*)
405       TLIFn == LibFunc_msvc_delete_ptr64 || // operator delete(void*)
406       TLIFn == LibFunc_msvc_delete_array_ptr32 || // operator delete[](void*)
407       TLIFn == LibFunc_msvc_delete_array_ptr64)   // operator delete[](void*)
408     ExpectedNumParams = 1;
409   else if (TLIFn == LibFunc_ZdlPvj ||              // delete(void*, uint)
410            TLIFn == LibFunc_ZdlPvm ||              // delete(void*, ulong)
411            TLIFn == LibFunc_ZdlPvRKSt9nothrow_t || // delete(void*, nothrow)
412            TLIFn == LibFunc_ZdlPvSt11align_val_t || // delete(void*, align_val_t)
413            TLIFn == LibFunc_ZdaPvj ||              // delete[](void*, uint)
414            TLIFn == LibFunc_ZdaPvm ||              // delete[](void*, ulong)
415            TLIFn == LibFunc_ZdaPvRKSt9nothrow_t || // delete[](void*, nothrow)
416            TLIFn == LibFunc_ZdaPvSt11align_val_t || // delete[](void*, align_val_t)
417            TLIFn == LibFunc_msvc_delete_ptr32_int ||      // delete(void*, uint)
418            TLIFn == LibFunc_msvc_delete_ptr64_longlong || // delete(void*, ulonglong)
419            TLIFn == LibFunc_msvc_delete_ptr32_nothrow || // delete(void*, nothrow)
420            TLIFn == LibFunc_msvc_delete_ptr64_nothrow || // delete(void*, nothrow)
421            TLIFn == LibFunc_msvc_delete_array_ptr32_int ||      // delete[](void*, uint)
422            TLIFn == LibFunc_msvc_delete_array_ptr64_longlong || // delete[](void*, ulonglong)
423            TLIFn == LibFunc_msvc_delete_array_ptr32_nothrow || // delete[](void*, nothrow)
424            TLIFn == LibFunc_msvc_delete_array_ptr64_nothrow || // delete[](void*, nothrow)
425            TLIFn == LibFunc___kmpc_free_shared) // OpenMP Offloading RTL free
426     ExpectedNumParams = 2;
427   else if (TLIFn == LibFunc_ZdaPvSt11align_val_tRKSt9nothrow_t || // delete(void*, align_val_t, nothrow)
428            TLIFn == LibFunc_ZdlPvSt11align_val_tRKSt9nothrow_t || // delete[](void*, align_val_t, nothrow)
429            TLIFn == LibFunc_ZdlPvjSt11align_val_t || // delete(void*, unsigned long, align_val_t)
430            TLIFn == LibFunc_ZdlPvmSt11align_val_t || // delete(void*, unsigned long, align_val_t)
431            TLIFn == LibFunc_ZdaPvjSt11align_val_t || // delete[](void*, unsigned int, align_val_t)
432            TLIFn == LibFunc_ZdaPvmSt11align_val_t) // delete[](void*, unsigned long, align_val_t)
433     ExpectedNumParams = 3;
434   else
435     return false;
436 
437   // Check free prototype.
438   // FIXME: workaround for PR5130, this will be obsolete when a nobuiltin
439   // attribute will exist.
440   FunctionType *FTy = F->getFunctionType();
441   if (!FTy->getReturnType()->isVoidTy())
442     return false;
443   if (FTy->getNumParams() != ExpectedNumParams)
444     return false;
445   if (FTy->getParamType(0) != Type::getInt8PtrTy(F->getContext()))
446     return false;
447 
448   return true;
449 }
450 
451 /// isFreeCall - Returns non-null if the value is a call to the builtin free()
452 const CallInst *llvm::isFreeCall(const Value *I, const TargetLibraryInfo *TLI) {
453   bool IsNoBuiltinCall;
454   const Function *Callee = getCalledFunction(I, IsNoBuiltinCall);
455   if (Callee == nullptr || IsNoBuiltinCall)
456     return nullptr;
457 
458   LibFunc TLIFn;
459   if (!TLI || !TLI->getLibFunc(*Callee, TLIFn) || !TLI->has(TLIFn))
460     return nullptr;
461 
462   return isLibFreeFunction(Callee, TLIFn) ? dyn_cast<CallInst>(I) : nullptr;
463 }
464 
465 
466 //===----------------------------------------------------------------------===//
467 //  Utility functions to compute size of objects.
468 //
469 static APInt getSizeWithOverflow(const SizeOffsetType &Data) {
470   if (Data.second.isNegative() || Data.first.ult(Data.second))
471     return APInt(Data.first.getBitWidth(), 0);
472   return Data.first - Data.second;
473 }
474 
475 /// Compute the size of the object pointed by Ptr. Returns true and the
476 /// object size in Size if successful, and false otherwise.
477 /// If RoundToAlign is true, then Size is rounded up to the alignment of
478 /// allocas, byval arguments, and global variables.
479 bool llvm::getObjectSize(const Value *Ptr, uint64_t &Size, const DataLayout &DL,
480                          const TargetLibraryInfo *TLI, ObjectSizeOpts Opts) {
481   ObjectSizeOffsetVisitor Visitor(DL, TLI, Ptr->getContext(), Opts);
482   SizeOffsetType Data = Visitor.compute(const_cast<Value*>(Ptr));
483   if (!Visitor.bothKnown(Data))
484     return false;
485 
486   Size = getSizeWithOverflow(Data).getZExtValue();
487   return true;
488 }
489 
490 Value *llvm::lowerObjectSizeCall(IntrinsicInst *ObjectSize,
491                                  const DataLayout &DL,
492                                  const TargetLibraryInfo *TLI,
493                                  bool MustSucceed) {
494   assert(ObjectSize->getIntrinsicID() == Intrinsic::objectsize &&
495          "ObjectSize must be a call to llvm.objectsize!");
496 
497   bool MaxVal = cast<ConstantInt>(ObjectSize->getArgOperand(1))->isZero();
498   ObjectSizeOpts EvalOptions;
499   // Unless we have to fold this to something, try to be as accurate as
500   // possible.
501   if (MustSucceed)
502     EvalOptions.EvalMode =
503         MaxVal ? ObjectSizeOpts::Mode::Max : ObjectSizeOpts::Mode::Min;
504   else
505     EvalOptions.EvalMode = ObjectSizeOpts::Mode::Exact;
506 
507   EvalOptions.NullIsUnknownSize =
508       cast<ConstantInt>(ObjectSize->getArgOperand(2))->isOne();
509 
510   auto *ResultType = cast<IntegerType>(ObjectSize->getType());
511   bool StaticOnly = cast<ConstantInt>(ObjectSize->getArgOperand(3))->isZero();
512   if (StaticOnly) {
513     // FIXME: Does it make sense to just return a failure value if the size won't
514     // fit in the output and `!MustSucceed`?
515     uint64_t Size;
516     if (getObjectSize(ObjectSize->getArgOperand(0), Size, DL, TLI, EvalOptions) &&
517         isUIntN(ResultType->getBitWidth(), Size))
518       return ConstantInt::get(ResultType, Size);
519   } else {
520     LLVMContext &Ctx = ObjectSize->getFunction()->getContext();
521     ObjectSizeOffsetEvaluator Eval(DL, TLI, Ctx, EvalOptions);
522     SizeOffsetEvalType SizeOffsetPair =
523         Eval.compute(ObjectSize->getArgOperand(0));
524 
525     if (SizeOffsetPair != ObjectSizeOffsetEvaluator::unknown()) {
526       IRBuilder<TargetFolder> Builder(Ctx, TargetFolder(DL));
527       Builder.SetInsertPoint(ObjectSize);
528 
529       // If we've outside the end of the object, then we can always access
530       // exactly 0 bytes.
531       Value *ResultSize =
532           Builder.CreateSub(SizeOffsetPair.first, SizeOffsetPair.second);
533       Value *UseZero =
534           Builder.CreateICmpULT(SizeOffsetPair.first, SizeOffsetPair.second);
535       ResultSize = Builder.CreateZExtOrTrunc(ResultSize, ResultType);
536       Value *Ret = Builder.CreateSelect(
537           UseZero, ConstantInt::get(ResultType, 0), ResultSize);
538 
539       // The non-constant size expression cannot evaluate to -1.
540       if (!isa<Constant>(SizeOffsetPair.first) ||
541           !isa<Constant>(SizeOffsetPair.second))
542         Builder.CreateAssumption(
543             Builder.CreateICmpNE(Ret, ConstantInt::get(ResultType, -1)));
544 
545       return Ret;
546     }
547   }
548 
549   if (!MustSucceed)
550     return nullptr;
551 
552   return ConstantInt::get(ResultType, MaxVal ? -1ULL : 0);
553 }
554 
555 STATISTIC(ObjectVisitorArgument,
556           "Number of arguments with unsolved size and offset");
557 STATISTIC(ObjectVisitorLoad,
558           "Number of load instructions with unsolved size and offset");
559 
560 APInt ObjectSizeOffsetVisitor::align(APInt Size, MaybeAlign Alignment) {
561   if (Options.RoundToAlign && Alignment)
562     return APInt(IntTyBits, alignTo(Size.getZExtValue(), Alignment));
563   return Size;
564 }
565 
566 ObjectSizeOffsetVisitor::ObjectSizeOffsetVisitor(const DataLayout &DL,
567                                                  const TargetLibraryInfo *TLI,
568                                                  LLVMContext &Context,
569                                                  ObjectSizeOpts Options)
570     : DL(DL), TLI(TLI), Options(Options) {
571   // Pointer size must be rechecked for each object visited since it could have
572   // a different address space.
573 }
574 
575 SizeOffsetType ObjectSizeOffsetVisitor::compute(Value *V) {
576   unsigned InitialIntTyBits = DL.getIndexTypeSizeInBits(V->getType());
577 
578   // Stripping pointer casts can strip address space casts which can change the
579   // index type size. The invariant is that we use the value type to determine
580   // the index type size and if we stripped address space casts we have to
581   // readjust the APInt as we pass it upwards in order for the APInt to match
582   // the type the caller passed in.
583   APInt Offset(InitialIntTyBits, 0);
584   V = V->stripAndAccumulateConstantOffsets(
585       DL, Offset, /* AllowNonInbounds */ true, /* AllowInvariantGroup */ true);
586 
587   // Later we use the index type size and zero but it will match the type of the
588   // value that is passed to computeImpl.
589   IntTyBits = DL.getIndexTypeSizeInBits(V->getType());
590   Zero = APInt::getZero(IntTyBits);
591 
592   bool IndexTypeSizeChanged = InitialIntTyBits != IntTyBits;
593   if (!IndexTypeSizeChanged && Offset.isZero())
594     return computeImpl(V);
595 
596   // We stripped an address space cast that changed the index type size or we
597   // accumulated some constant offset (or both). Readjust the bit width to match
598   // the argument index type size and apply the offset, as required.
599   SizeOffsetType SOT = computeImpl(V);
600   if (IndexTypeSizeChanged) {
601     if (knownSize(SOT) && !::CheckedZextOrTrunc(SOT.first, InitialIntTyBits))
602       SOT.first = APInt();
603     if (knownOffset(SOT) && !::CheckedZextOrTrunc(SOT.second, InitialIntTyBits))
604       SOT.second = APInt();
605   }
606   // If the computed offset is "unknown" we cannot add the stripped offset.
607   return {SOT.first,
608           SOT.second.getBitWidth() > 1 ? SOT.second + Offset : SOT.second};
609 }
610 
611 SizeOffsetType ObjectSizeOffsetVisitor::computeImpl(Value *V) {
612   if (Instruction *I = dyn_cast<Instruction>(V)) {
613     // If we have already seen this instruction, bail out. Cycles can happen in
614     // unreachable code after constant propagation.
615     if (!SeenInsts.insert(I).second)
616       return unknown();
617 
618     return visit(*I);
619   }
620   if (Argument *A = dyn_cast<Argument>(V))
621     return visitArgument(*A);
622   if (ConstantPointerNull *P = dyn_cast<ConstantPointerNull>(V))
623     return visitConstantPointerNull(*P);
624   if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
625     return visitGlobalAlias(*GA);
626   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
627     return visitGlobalVariable(*GV);
628   if (UndefValue *UV = dyn_cast<UndefValue>(V))
629     return visitUndefValue(*UV);
630 
631   LLVM_DEBUG(dbgs() << "ObjectSizeOffsetVisitor::compute() unhandled value: "
632                     << *V << '\n');
633   return unknown();
634 }
635 
636 bool ObjectSizeOffsetVisitor::CheckedZextOrTrunc(APInt &I) {
637   return ::CheckedZextOrTrunc(I, IntTyBits);
638 }
639 
640 SizeOffsetType ObjectSizeOffsetVisitor::visitAllocaInst(AllocaInst &I) {
641   if (!I.getAllocatedType()->isSized())
642     return unknown();
643 
644   if (isa<ScalableVectorType>(I.getAllocatedType()))
645     return unknown();
646 
647   APInt Size(IntTyBits, DL.getTypeAllocSize(I.getAllocatedType()));
648   if (!I.isArrayAllocation())
649     return std::make_pair(align(Size, I.getAlign()), Zero);
650 
651   Value *ArraySize = I.getArraySize();
652   if (const ConstantInt *C = dyn_cast<ConstantInt>(ArraySize)) {
653     APInt NumElems = C->getValue();
654     if (!CheckedZextOrTrunc(NumElems))
655       return unknown();
656 
657     bool Overflow;
658     Size = Size.umul_ov(NumElems, Overflow);
659     return Overflow ? unknown()
660                     : std::make_pair(align(Size, I.getAlign()), Zero);
661   }
662   return unknown();
663 }
664 
665 SizeOffsetType ObjectSizeOffsetVisitor::visitArgument(Argument &A) {
666   Type *MemoryTy = A.getPointeeInMemoryValueType();
667   // No interprocedural analysis is done at the moment.
668   if (!MemoryTy|| !MemoryTy->isSized()) {
669     ++ObjectVisitorArgument;
670     return unknown();
671   }
672 
673   APInt Size(IntTyBits, DL.getTypeAllocSize(MemoryTy));
674   return std::make_pair(align(Size, A.getParamAlign()), Zero);
675 }
676 
677 SizeOffsetType ObjectSizeOffsetVisitor::visitCallBase(CallBase &CB) {
678   auto Mapper = [](const Value *V) { return V; };
679   if (Optional<APInt> Size = getAllocSize(&CB, TLI, Mapper))
680     return std::make_pair(*Size, Zero);
681   return unknown();
682 }
683 
684 SizeOffsetType
685 ObjectSizeOffsetVisitor::visitConstantPointerNull(ConstantPointerNull& CPN) {
686   // If null is unknown, there's nothing we can do. Additionally, non-zero
687   // address spaces can make use of null, so we don't presume to know anything
688   // about that.
689   //
690   // TODO: How should this work with address space casts? We currently just drop
691   // them on the floor, but it's unclear what we should do when a NULL from
692   // addrspace(1) gets casted to addrspace(0) (or vice-versa).
693   if (Options.NullIsUnknownSize || CPN.getType()->getAddressSpace())
694     return unknown();
695   return std::make_pair(Zero, Zero);
696 }
697 
698 SizeOffsetType
699 ObjectSizeOffsetVisitor::visitExtractElementInst(ExtractElementInst&) {
700   return unknown();
701 }
702 
703 SizeOffsetType
704 ObjectSizeOffsetVisitor::visitExtractValueInst(ExtractValueInst&) {
705   // Easy cases were already folded by previous passes.
706   return unknown();
707 }
708 
709 SizeOffsetType ObjectSizeOffsetVisitor::visitGlobalAlias(GlobalAlias &GA) {
710   if (GA.isInterposable())
711     return unknown();
712   return compute(GA.getAliasee());
713 }
714 
715 SizeOffsetType ObjectSizeOffsetVisitor::visitGlobalVariable(GlobalVariable &GV){
716   if (!GV.hasDefinitiveInitializer())
717     return unknown();
718 
719   APInt Size(IntTyBits, DL.getTypeAllocSize(GV.getValueType()));
720   return std::make_pair(align(Size, GV.getAlign()), Zero);
721 }
722 
723 SizeOffsetType ObjectSizeOffsetVisitor::visitIntToPtrInst(IntToPtrInst&) {
724   // clueless
725   return unknown();
726 }
727 
728 SizeOffsetType ObjectSizeOffsetVisitor::visitLoadInst(LoadInst&) {
729   ++ObjectVisitorLoad;
730   return unknown();
731 }
732 
733 SizeOffsetType ObjectSizeOffsetVisitor::visitPHINode(PHINode&) {
734   // too complex to analyze statically.
735   return unknown();
736 }
737 
738 SizeOffsetType ObjectSizeOffsetVisitor::visitSelectInst(SelectInst &I) {
739   SizeOffsetType TrueSide  = compute(I.getTrueValue());
740   SizeOffsetType FalseSide = compute(I.getFalseValue());
741   if (bothKnown(TrueSide) && bothKnown(FalseSide)) {
742     if (TrueSide == FalseSide) {
743         return TrueSide;
744     }
745 
746     APInt TrueResult = getSizeWithOverflow(TrueSide);
747     APInt FalseResult = getSizeWithOverflow(FalseSide);
748 
749     if (TrueResult == FalseResult) {
750       return TrueSide;
751     }
752     if (Options.EvalMode == ObjectSizeOpts::Mode::Min) {
753       if (TrueResult.slt(FalseResult))
754         return TrueSide;
755       return FalseSide;
756     }
757     if (Options.EvalMode == ObjectSizeOpts::Mode::Max) {
758       if (TrueResult.sgt(FalseResult))
759         return TrueSide;
760       return FalseSide;
761     }
762   }
763   return unknown();
764 }
765 
766 SizeOffsetType ObjectSizeOffsetVisitor::visitUndefValue(UndefValue&) {
767   return std::make_pair(Zero, Zero);
768 }
769 
770 SizeOffsetType ObjectSizeOffsetVisitor::visitInstruction(Instruction &I) {
771   LLVM_DEBUG(dbgs() << "ObjectSizeOffsetVisitor unknown instruction:" << I
772                     << '\n');
773   return unknown();
774 }
775 
776 ObjectSizeOffsetEvaluator::ObjectSizeOffsetEvaluator(
777     const DataLayout &DL, const TargetLibraryInfo *TLI, LLVMContext &Context,
778     ObjectSizeOpts EvalOpts)
779     : DL(DL), TLI(TLI), Context(Context),
780       Builder(Context, TargetFolder(DL),
781               IRBuilderCallbackInserter(
782                   [&](Instruction *I) { InsertedInstructions.insert(I); })),
783       EvalOpts(EvalOpts) {
784   // IntTy and Zero must be set for each compute() since the address space may
785   // be different for later objects.
786 }
787 
788 SizeOffsetEvalType ObjectSizeOffsetEvaluator::compute(Value *V) {
789   // XXX - Are vectors of pointers possible here?
790   IntTy = cast<IntegerType>(DL.getIndexType(V->getType()));
791   Zero = ConstantInt::get(IntTy, 0);
792 
793   SizeOffsetEvalType Result = compute_(V);
794 
795   if (!bothKnown(Result)) {
796     // Erase everything that was computed in this iteration from the cache, so
797     // that no dangling references are left behind. We could be a bit smarter if
798     // we kept a dependency graph. It's probably not worth the complexity.
799     for (const Value *SeenVal : SeenVals) {
800       CacheMapTy::iterator CacheIt = CacheMap.find(SeenVal);
801       // non-computable results can be safely cached
802       if (CacheIt != CacheMap.end() && anyKnown(CacheIt->second))
803         CacheMap.erase(CacheIt);
804     }
805 
806     // Erase any instructions we inserted as part of the traversal.
807     for (Instruction *I : InsertedInstructions) {
808       I->replaceAllUsesWith(UndefValue::get(I->getType()));
809       I->eraseFromParent();
810     }
811   }
812 
813   SeenVals.clear();
814   InsertedInstructions.clear();
815   return Result;
816 }
817 
818 SizeOffsetEvalType ObjectSizeOffsetEvaluator::compute_(Value *V) {
819   ObjectSizeOffsetVisitor Visitor(DL, TLI, Context, EvalOpts);
820   SizeOffsetType Const = Visitor.compute(V);
821   if (Visitor.bothKnown(Const))
822     return std::make_pair(ConstantInt::get(Context, Const.first),
823                           ConstantInt::get(Context, Const.second));
824 
825   V = V->stripPointerCasts();
826 
827   // Check cache.
828   CacheMapTy::iterator CacheIt = CacheMap.find(V);
829   if (CacheIt != CacheMap.end())
830     return CacheIt->second;
831 
832   // Always generate code immediately before the instruction being
833   // processed, so that the generated code dominates the same BBs.
834   BuilderTy::InsertPointGuard Guard(Builder);
835   if (Instruction *I = dyn_cast<Instruction>(V))
836     Builder.SetInsertPoint(I);
837 
838   // Now compute the size and offset.
839   SizeOffsetEvalType Result;
840 
841   // Record the pointers that were handled in this run, so that they can be
842   // cleaned later if something fails. We also use this set to break cycles that
843   // can occur in dead code.
844   if (!SeenVals.insert(V).second) {
845     Result = unknown();
846   } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
847     Result = visitGEPOperator(*GEP);
848   } else if (Instruction *I = dyn_cast<Instruction>(V)) {
849     Result = visit(*I);
850   } else if (isa<Argument>(V) ||
851              (isa<ConstantExpr>(V) &&
852               cast<ConstantExpr>(V)->getOpcode() == Instruction::IntToPtr) ||
853              isa<GlobalAlias>(V) ||
854              isa<GlobalVariable>(V)) {
855     // Ignore values where we cannot do more than ObjectSizeVisitor.
856     Result = unknown();
857   } else {
858     LLVM_DEBUG(
859         dbgs() << "ObjectSizeOffsetEvaluator::compute() unhandled value: " << *V
860                << '\n');
861     Result = unknown();
862   }
863 
864   // Don't reuse CacheIt since it may be invalid at this point.
865   CacheMap[V] = Result;
866   return Result;
867 }
868 
869 SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitAllocaInst(AllocaInst &I) {
870   if (!I.getAllocatedType()->isSized())
871     return unknown();
872 
873   // must be a VLA
874   assert(I.isArrayAllocation());
875 
876   // If needed, adjust the alloca's operand size to match the pointer size.
877   // Subsequent math operations expect the types to match.
878   Value *ArraySize = Builder.CreateZExtOrTrunc(
879       I.getArraySize(), DL.getIntPtrType(I.getContext()));
880   assert(ArraySize->getType() == Zero->getType() &&
881          "Expected zero constant to have pointer type");
882 
883   Value *Size = ConstantInt::get(ArraySize->getType(),
884                                  DL.getTypeAllocSize(I.getAllocatedType()));
885   Size = Builder.CreateMul(Size, ArraySize);
886   return std::make_pair(Size, Zero);
887 }
888 
889 SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitCallBase(CallBase &CB) {
890   Optional<AllocFnsTy> FnData = getAllocationSize(&CB, TLI);
891   if (!FnData)
892     return unknown();
893 
894   // Handle strdup-like functions separately.
895   if (FnData->AllocTy == StrDupLike) {
896     // TODO: implement evaluation of strdup/strndup
897     return unknown();
898   }
899 
900   Value *FirstArg = CB.getArgOperand(FnData->FstParam);
901   FirstArg = Builder.CreateZExtOrTrunc(FirstArg, IntTy);
902   if (FnData->SndParam < 0)
903     return std::make_pair(FirstArg, Zero);
904 
905   Value *SecondArg = CB.getArgOperand(FnData->SndParam);
906   SecondArg = Builder.CreateZExtOrTrunc(SecondArg, IntTy);
907   Value *Size = Builder.CreateMul(FirstArg, SecondArg);
908   return std::make_pair(Size, Zero);
909 }
910 
911 SizeOffsetEvalType
912 ObjectSizeOffsetEvaluator::visitExtractElementInst(ExtractElementInst&) {
913   return unknown();
914 }
915 
916 SizeOffsetEvalType
917 ObjectSizeOffsetEvaluator::visitExtractValueInst(ExtractValueInst&) {
918   return unknown();
919 }
920 
921 SizeOffsetEvalType
922 ObjectSizeOffsetEvaluator::visitGEPOperator(GEPOperator &GEP) {
923   SizeOffsetEvalType PtrData = compute_(GEP.getPointerOperand());
924   if (!bothKnown(PtrData))
925     return unknown();
926 
927   Value *Offset = EmitGEPOffset(&Builder, DL, &GEP, /*NoAssumptions=*/true);
928   Offset = Builder.CreateAdd(PtrData.second, Offset);
929   return std::make_pair(PtrData.first, Offset);
930 }
931 
932 SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitIntToPtrInst(IntToPtrInst&) {
933   // clueless
934   return unknown();
935 }
936 
937 SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitLoadInst(LoadInst&) {
938   return unknown();
939 }
940 
941 SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitPHINode(PHINode &PHI) {
942   // Create 2 PHIs: one for size and another for offset.
943   PHINode *SizePHI   = Builder.CreatePHI(IntTy, PHI.getNumIncomingValues());
944   PHINode *OffsetPHI = Builder.CreatePHI(IntTy, PHI.getNumIncomingValues());
945 
946   // Insert right away in the cache to handle recursive PHIs.
947   CacheMap[&PHI] = std::make_pair(SizePHI, OffsetPHI);
948 
949   // Compute offset/size for each PHI incoming pointer.
950   for (unsigned i = 0, e = PHI.getNumIncomingValues(); i != e; ++i) {
951     Builder.SetInsertPoint(&*PHI.getIncomingBlock(i)->getFirstInsertionPt());
952     SizeOffsetEvalType EdgeData = compute_(PHI.getIncomingValue(i));
953 
954     if (!bothKnown(EdgeData)) {
955       OffsetPHI->replaceAllUsesWith(UndefValue::get(IntTy));
956       OffsetPHI->eraseFromParent();
957       InsertedInstructions.erase(OffsetPHI);
958       SizePHI->replaceAllUsesWith(UndefValue::get(IntTy));
959       SizePHI->eraseFromParent();
960       InsertedInstructions.erase(SizePHI);
961       return unknown();
962     }
963     SizePHI->addIncoming(EdgeData.first, PHI.getIncomingBlock(i));
964     OffsetPHI->addIncoming(EdgeData.second, PHI.getIncomingBlock(i));
965   }
966 
967   Value *Size = SizePHI, *Offset = OffsetPHI;
968   if (Value *Tmp = SizePHI->hasConstantValue()) {
969     Size = Tmp;
970     SizePHI->replaceAllUsesWith(Size);
971     SizePHI->eraseFromParent();
972     InsertedInstructions.erase(SizePHI);
973   }
974   if (Value *Tmp = OffsetPHI->hasConstantValue()) {
975     Offset = Tmp;
976     OffsetPHI->replaceAllUsesWith(Offset);
977     OffsetPHI->eraseFromParent();
978     InsertedInstructions.erase(OffsetPHI);
979   }
980   return std::make_pair(Size, Offset);
981 }
982 
983 SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitSelectInst(SelectInst &I) {
984   SizeOffsetEvalType TrueSide  = compute_(I.getTrueValue());
985   SizeOffsetEvalType FalseSide = compute_(I.getFalseValue());
986 
987   if (!bothKnown(TrueSide) || !bothKnown(FalseSide))
988     return unknown();
989   if (TrueSide == FalseSide)
990     return TrueSide;
991 
992   Value *Size = Builder.CreateSelect(I.getCondition(), TrueSide.first,
993                                      FalseSide.first);
994   Value *Offset = Builder.CreateSelect(I.getCondition(), TrueSide.second,
995                                        FalseSide.second);
996   return std::make_pair(Size, Offset);
997 }
998 
999 SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitInstruction(Instruction &I) {
1000   LLVM_DEBUG(dbgs() << "ObjectSizeOffsetEvaluator unknown instruction:" << I
1001                     << '\n');
1002   return unknown();
1003 }
1004