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