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