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