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