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