blob: 24fedfed772cbd427c9298e8ff9a8149773e04ca [file] [log] [blame]
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +00001//===- MemoryBuiltins.cpp - Identify calls to memory builtins -------------===//
Evan Cheng1d9d4bd2009-09-10 04:36:43 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Victor Hernandezf390e042009-10-27 20:05:49 +000010// This family of functions identifies calls to builtin functions that allocate
Michael Ilsemand9745242013-03-08 21:03:09 +000011// or free memory.
Evan Cheng1d9d4bd2009-09-10 04:36:43 +000012//
13//===----------------------------------------------------------------------===//
14
Victor Hernandezf390e042009-10-27 20:05:49 +000015#include "llvm/Analysis/MemoryBuiltins.h"
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +000016#include "llvm/ADT/APInt.h"
17#include "llvm/ADT/None.h"
18#include "llvm/ADT/Optional.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000019#include "llvm/ADT/STLExtras.h"
20#include "llvm/ADT/Statistic.h"
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +000021#include "llvm/ADT/StringRef.h"
22#include "llvm/Analysis/TargetFolder.h"
Chandler Carruth62d42152015-01-15 02:16:27 +000023#include "llvm/Analysis/TargetLibraryInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000024#include "llvm/Analysis/ValueTracking.h"
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +000025#include "llvm/IR/Argument.h"
26#include "llvm/IR/Attributes.h"
27#include "llvm/IR/Constants.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000028#include "llvm/IR/DataLayout.h"
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +000029#include "llvm/IR/DerivedTypes.h"
30#include "llvm/IR/Function.h"
31#include "llvm/IR/GlobalAlias.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000032#include "llvm/IR/GlobalVariable.h"
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +000033#include "llvm/IR/Instruction.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000034#include "llvm/IR/Instructions.h"
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +000035#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"
Nuno Lopes55fff832012-06-21 15:45:28 +000040#include "llvm/Support/Debug.h"
41#include "llvm/Support/MathExtras.h"
42#include "llvm/Support/raw_ostream.h"
Nuno Lopes55fff832012-06-21 15:45:28 +000043#include "llvm/Transforms/Utils/Local.h"
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +000044#include <cassert>
45#include <cstdint>
46#include <iterator>
47#include <utility>
48
Evan Cheng1d9d4bd2009-09-10 04:36:43 +000049using namespace llvm;
50
Chandler Carruthf1221bd2014-04-22 02:48:03 +000051#define DEBUG_TYPE "memory-builtins"
52
George Burgess IV2ae15e02015-11-17 19:48:06 +000053enum AllocType : uint8_t {
Benjamin Kramer2939dd32013-09-24 17:34:29 +000054 OpNewLike = 1<<0, // allocates; never returns null
55 MallocLike = 1<<1 | OpNewLike, // allocates; may return null
56 CallocLike = 1<<2, // allocates + bzero
57 ReallocLike = 1<<3, // reallocates
58 StrDupLike = 1<<4,
Craig Topper09bb7602017-04-18 21:43:46 +000059 MallocOrCallocLike = MallocLike | CallocLike,
Benjamin Kramer2939dd32013-09-24 17:34:29 +000060 AllocLike = MallocLike | CallocLike | StrDupLike,
Benjamin Kramer4d4df042013-09-24 17:15:14 +000061 AnyAlloc = AllocLike | ReallocLike
Nuno Lopes55fff832012-06-21 15:45:28 +000062};
Evan Cheng1d9d4bd2009-09-10 04:36:43 +000063
Nuno Lopes55fff832012-06-21 15:45:28 +000064struct AllocFnsTy {
Nuno Lopes55fff832012-06-21 15:45:28 +000065 AllocType AllocTy;
George Burgess IV278199f2016-04-12 01:05:35 +000066 unsigned NumParams;
Nuno Lopes55fff832012-06-21 15:45:28 +000067 // First and Second size parameters (or -1 if unused)
George Burgess IV278199f2016-04-12 01:05:35 +000068 int FstParam, SndParam;
Nuno Lopes55fff832012-06-21 15:45:28 +000069};
Evan Cheng1d9d4bd2009-09-10 04:36:43 +000070
Nuno Lopes181d67e2012-06-28 16:34:03 +000071// FIXME: certain users need more information. E.g., SimplifyLibCalls needs to
72// know which functions are nounwind, noalias, nocapture parameters, etc.
David L. Jonesd21529f2017-01-23 23:16:46 +000073static 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_Znwm, {OpNewLike, 1, 0, -1}}, // new(unsigned long)
79 {LibFunc_ZnwmRKSt9nothrow_t, {MallocLike, 2, 0, -1}}, // new(unsigned long, nothrow)
80 {LibFunc_Znaj, {OpNewLike, 1, 0, -1}}, // new[](unsigned int)
81 {LibFunc_ZnajRKSt9nothrow_t, {MallocLike, 2, 0, -1}}, // new[](unsigned int, nothrow)
82 {LibFunc_Znam, {OpNewLike, 1, 0, -1}}, // new[](unsigned long)
83 {LibFunc_ZnamRKSt9nothrow_t, {MallocLike, 2, 0, -1}}, // new[](unsigned long, nothrow)
84 {LibFunc_msvc_new_int, {OpNewLike, 1, 0, -1}}, // new(unsigned int)
85 {LibFunc_msvc_new_int_nothrow, {MallocLike, 2, 0, -1}}, // new(unsigned int, nothrow)
86 {LibFunc_msvc_new_longlong, {OpNewLike, 1, 0, -1}}, // new(unsigned long long)
87 {LibFunc_msvc_new_longlong_nothrow, {MallocLike, 2, 0, -1}}, // new(unsigned long long, nothrow)
88 {LibFunc_msvc_new_array_int, {OpNewLike, 1, 0, -1}}, // new[](unsigned int)
89 {LibFunc_msvc_new_array_int_nothrow, {MallocLike, 2, 0, -1}}, // new[](unsigned int, nothrow)
90 {LibFunc_msvc_new_array_longlong, {OpNewLike, 1, 0, -1}}, // new[](unsigned long long)
91 {LibFunc_msvc_new_array_longlong_nothrow, {MallocLike, 2, 0, -1}}, // new[](unsigned long long, nothrow)
92 {LibFunc_calloc, {CallocLike, 2, 0, 1}},
93 {LibFunc_realloc, {ReallocLike, 2, 1, -1}},
94 {LibFunc_reallocf, {ReallocLike, 2, 1, -1}},
95 {LibFunc_strdup, {StrDupLike, 1, -1, -1}},
96 {LibFunc_strndup, {StrDupLike, 2, 1, -1}}
Benjamin Kramer01df8172013-09-24 17:49:08 +000097 // TODO: Handle "int posix_memalign(void **, size_t, size_t)"
Nuno Lopes55fff832012-06-21 15:45:28 +000098};
99
Craig Toppereae6db02017-04-18 20:17:23 +0000100static const Function *getCalledFunction(const Value *V, bool LookThroughBitCast,
101 bool &IsNoBuiltin) {
George Burgess IVce044892016-12-27 06:10:50 +0000102 // Don't care about intrinsics in this case.
103 if (isa<IntrinsicInst>(V))
104 return nullptr;
105
Nuno Lopes55fff832012-06-21 15:45:28 +0000106 if (LookThroughBitCast)
107 V = V->stripPointerCasts();
Nuno Lopesdc6085e2012-06-21 21:25:05 +0000108
Craig Toppereae6db02017-04-18 20:17:23 +0000109 ImmutableCallSite CS(V);
Nuno Lopes15dbcb42012-06-22 15:50:53 +0000110 if (!CS.getInstruction())
Craig Topper9f008862014-04-15 04:59:12 +0000111 return nullptr;
Evan Cheng1d9d4bd2009-09-10 04:36:43 +0000112
George Burgess IVed160242016-12-27 06:32:14 +0000113 IsNoBuiltin = CS.isNoBuiltin();
Richard Smithe04f0d32013-05-16 04:12:04 +0000114
Craig Toppereae6db02017-04-18 20:17:23 +0000115 const Function *Callee = CS.getCalledFunction();
Nuno Lopes55fff832012-06-21 15:45:28 +0000116 if (!Callee || !Callee->isDeclaration())
Craig Topper9f008862014-04-15 04:59:12 +0000117 return nullptr;
Nuno Lopes55fff832012-06-21 15:45:28 +0000118 return Callee;
119}
Evan Cheng1d9d4bd2009-09-10 04:36:43 +0000120
George Burgess IV278199f2016-04-12 01:05:35 +0000121/// Returns the allocation data for the given value if it's either a call to a
122/// known allocation function, or a call to a function with the allocsize
123/// attribute.
George Burgess IVce044892016-12-27 06:10:50 +0000124static Optional<AllocFnsTy>
125getAllocationDataForFunction(const Function *Callee, AllocType AllocTy,
126 const TargetLibraryInfo *TLI) {
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000127 // Make sure that the function is available.
128 StringRef FnName = Callee->getName();
David L. Jonesd21529f2017-01-23 23:16:46 +0000129 LibFunc TLIFn;
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000130 if (!TLI || !TLI->getLibFunc(FnName, TLIFn) || !TLI->has(TLIFn))
George Burgess IV278199f2016-04-12 01:05:35 +0000131 return None;
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000132
George Burgess IV45a540f2016-12-20 18:46:27 +0000133 const auto *Iter = find_if(
David L. Jonesd21529f2017-01-23 23:16:46 +0000134 AllocationFnData, [TLIFn](const std::pair<LibFunc, AllocFnsTy> &P) {
George Burgess IV45a540f2016-12-20 18:46:27 +0000135 return P.first == TLIFn;
136 });
Benjamin Kramer74b6d3b2015-10-24 19:03:15 +0000137
George Burgess IV278199f2016-04-12 01:05:35 +0000138 if (Iter == std::end(AllocationFnData))
139 return None;
Nuno Lopes55fff832012-06-21 15:45:28 +0000140
George Burgess IV278199f2016-04-12 01:05:35 +0000141 const AllocFnsTy *FnData = &Iter->second;
Benjamin Kramer2939dd32013-09-24 17:34:29 +0000142 if ((FnData->AllocTy & AllocTy) != FnData->AllocTy)
George Burgess IV278199f2016-04-12 01:05:35 +0000143 return None;
Nuno Lopes55fff832012-06-21 15:45:28 +0000144
145 // Check function prototype.
Nuno Lopesf06b7312012-06-21 18:38:26 +0000146 int FstParam = FnData->FstParam;
147 int SndParam = FnData->SndParam;
Chris Lattner229907c2011-07-18 04:54:35 +0000148 FunctionType *FTy = Callee->getFunctionType();
Nuno Lopes55fff832012-06-21 15:45:28 +0000149
150 if (FTy->getReturnType() == Type::getInt8PtrTy(FTy->getContext()) &&
151 FTy->getNumParams() == FnData->NumParams &&
Nuno Lopesf06b7312012-06-21 18:38:26 +0000152 (FstParam < 0 ||
Nuno Lopes55fff832012-06-21 15:45:28 +0000153 (FTy->getParamType(FstParam)->isIntegerTy(32) ||
154 FTy->getParamType(FstParam)->isIntegerTy(64))) &&
Nuno Lopesf06b7312012-06-21 18:38:26 +0000155 (SndParam < 0 ||
Nuno Lopes55fff832012-06-21 15:45:28 +0000156 FTy->getParamType(SndParam)->isIntegerTy(32) ||
157 FTy->getParamType(SndParam)->isIntegerTy(64)))
George Burgess IV278199f2016-04-12 01:05:35 +0000158 return *FnData;
159 return None;
Nuno Lopes55fff832012-06-21 15:45:28 +0000160}
161
George Burgess IVce044892016-12-27 06:10:50 +0000162static Optional<AllocFnsTy> getAllocationData(const Value *V, AllocType AllocTy,
163 const TargetLibraryInfo *TLI,
164 bool LookThroughBitCast = false) {
George Burgess IVed160242016-12-27 06:32:14 +0000165 bool IsNoBuiltinCall;
166 if (const Function *Callee =
167 getCalledFunction(V, LookThroughBitCast, IsNoBuiltinCall))
168 if (!IsNoBuiltinCall)
169 return getAllocationDataForFunction(Callee, AllocTy, TLI);
George Burgess IVce044892016-12-27 06:10:50 +0000170 return None;
171}
172
George Burgess IVccae43a2016-12-23 01:18:09 +0000173static Optional<AllocFnsTy> getAllocationSize(const Value *V,
174 const TargetLibraryInfo *TLI) {
George Burgess IVed160242016-12-27 06:32:14 +0000175 bool IsNoBuiltinCall;
176 const Function *Callee =
177 getCalledFunction(V, /*LookThroughBitCast=*/false, IsNoBuiltinCall);
George Burgess IVce044892016-12-27 06:10:50 +0000178 if (!Callee)
179 return None;
180
George Burgess IVccae43a2016-12-23 01:18:09 +0000181 // Prefer to use existing information over allocsize. This will give us an
182 // accurate AllocTy.
George Burgess IVed160242016-12-27 06:32:14 +0000183 if (!IsNoBuiltinCall)
184 if (Optional<AllocFnsTy> Data =
185 getAllocationDataForFunction(Callee, AnyAlloc, TLI))
186 return Data;
George Burgess IVccae43a2016-12-23 01:18:09 +0000187
George Burgess IVce044892016-12-27 06:10:50 +0000188 Attribute Attr = Callee->getFnAttribute(Attribute::AllocSize);
189 if (Attr == Attribute())
George Burgess IVccae43a2016-12-23 01:18:09 +0000190 return None;
191
George Burgess IVccae43a2016-12-23 01:18:09 +0000192 std::pair<unsigned, Optional<unsigned>> Args = Attr.getAllocSizeArgs();
193
194 AllocFnsTy Result;
195 // Because allocsize only tells us how many bytes are allocated, we're not
196 // really allowed to assume anything, so we use MallocLike.
197 Result.AllocTy = MallocLike;
198 Result.NumParams = Callee->getNumOperands();
199 Result.FstParam = Args.first;
200 Result.SndParam = Args.second.getValueOr(-1);
201 return Result;
202}
203
Nuno Lopes55fff832012-06-21 15:45:28 +0000204static bool hasNoAliasAttr(const Value *V, bool LookThroughBitCast) {
Nuno Lopes9ecc8762012-06-25 16:17:54 +0000205 ImmutableCallSite CS(LookThroughBitCast ? V->stripPointerCasts() : V);
Reid Klecknerfb502d22017-04-14 20:19:02 +0000206 return CS && CS.hasRetAttr(Attribute::NoAlias);
Nuno Lopes55fff832012-06-21 15:45:28 +0000207}
208
Nuno Lopesdc6085e2012-06-21 21:25:05 +0000209/// \brief Tests if a value is a call or invoke to a library function that
210/// allocates or reallocates memory (either malloc, calloc, realloc, or strdup
211/// like).
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000212bool llvm::isAllocationFn(const Value *V, const TargetLibraryInfo *TLI,
213 bool LookThroughBitCast) {
George Burgess IV278199f2016-04-12 01:05:35 +0000214 return getAllocationData(V, AnyAlloc, TLI, LookThroughBitCast).hasValue();
Nuno Lopes55fff832012-06-21 15:45:28 +0000215}
216
Nuno Lopesdc6085e2012-06-21 21:25:05 +0000217/// \brief Tests if a value is a call or invoke to a function that returns a
Nuno Lopes181d67e2012-06-28 16:34:03 +0000218/// NoAlias pointer (including malloc/calloc/realloc/strdup-like functions).
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000219bool llvm::isNoAliasFn(const Value *V, const TargetLibraryInfo *TLI,
220 bool LookThroughBitCast) {
Nuno Lopes181d67e2012-06-28 16:34:03 +0000221 // it's safe to consider realloc as noalias since accessing the original
222 // pointer is undefined behavior
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000223 return isAllocationFn(V, TLI, LookThroughBitCast) ||
Nuno Lopes55fff832012-06-21 15:45:28 +0000224 hasNoAliasAttr(V, LookThroughBitCast);
225}
226
Nuno Lopesdc6085e2012-06-21 21:25:05 +0000227/// \brief Tests if a value is a call or invoke to a library function that
228/// allocates uninitialized memory (such as malloc).
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000229bool llvm::isMallocLikeFn(const Value *V, const TargetLibraryInfo *TLI,
230 bool LookThroughBitCast) {
George Burgess IV278199f2016-04-12 01:05:35 +0000231 return getAllocationData(V, MallocLike, TLI, LookThroughBitCast).hasValue();
Nuno Lopes55fff832012-06-21 15:45:28 +0000232}
233
Nuno Lopesdc6085e2012-06-21 21:25:05 +0000234/// \brief Tests if a value is a call or invoke to a library function that
235/// allocates zero-filled memory (such as calloc).
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000236bool llvm::isCallocLikeFn(const Value *V, const TargetLibraryInfo *TLI,
237 bool LookThroughBitCast) {
George Burgess IV278199f2016-04-12 01:05:35 +0000238 return getAllocationData(V, CallocLike, TLI, LookThroughBitCast).hasValue();
Nuno Lopes55fff832012-06-21 15:45:28 +0000239}
240
Nuno Lopesdc6085e2012-06-21 21:25:05 +0000241/// \brief Tests if a value is a call or invoke to a library function that
Craig Topper09bb7602017-04-18 21:43:46 +0000242/// allocates memory similiar to malloc or calloc.
243bool llvm::isMallocOrCallocLikeFn(const Value *V, const TargetLibraryInfo *TLI,
244 bool LookThroughBitCast) {
245 return getAllocationData(V, MallocOrCallocLike, TLI,
246 LookThroughBitCast).hasValue();
247}
248
249/// \brief Tests if a value is a call or invoke to a library function that
Nuno Lopesdc6085e2012-06-21 21:25:05 +0000250/// allocates memory (either malloc, calloc, or strdup like).
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000251bool llvm::isAllocLikeFn(const Value *V, const TargetLibraryInfo *TLI,
252 bool LookThroughBitCast) {
George Burgess IV278199f2016-04-12 01:05:35 +0000253 return getAllocationData(V, AllocLike, TLI, LookThroughBitCast).hasValue();
Nuno Lopes55fff832012-06-21 15:45:28 +0000254}
255
Evan Cheng1d9d4bd2009-09-10 04:36:43 +0000256/// extractMallocCall - Returns the corresponding CallInst if the instruction
257/// is a malloc call. Since CallInst::CreateMalloc() only creates calls, we
258/// ignore InvokeInst here.
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000259const CallInst *llvm::extractMallocCall(const Value *I,
260 const TargetLibraryInfo *TLI) {
Craig Topper9f008862014-04-15 04:59:12 +0000261 return isMallocLikeFn(I, TLI) ? dyn_cast<CallInst>(I) : nullptr;
Evan Cheng1d9d4bd2009-09-10 04:36:43 +0000262}
263
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000264static Value *computeArraySize(const CallInst *CI, const DataLayout &DL,
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000265 const TargetLibraryInfo *TLI,
Victor Hernandezfcc77b12009-11-10 08:32:25 +0000266 bool LookThroughSExt = false) {
Evan Cheng1d9d4bd2009-09-10 04:36:43 +0000267 if (!CI)
Craig Topper9f008862014-04-15 04:59:12 +0000268 return nullptr;
Evan Cheng1d9d4bd2009-09-10 04:36:43 +0000269
Victor Hernandezf3db9152009-11-07 00:16:28 +0000270 // The size of the malloc's result type must be known to determine array size.
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000271 Type *T = getMallocAllocatedType(CI, TLI);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000272 if (!T || !T->isSized())
Craig Topper9f008862014-04-15 04:59:12 +0000273 return nullptr;
Victor Hernandez788eaab2009-09-18 19:20:02 +0000274
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000275 unsigned ElementSize = DL.getTypeAllocSize(T);
Chris Lattner229907c2011-07-18 04:54:35 +0000276 if (StructType *ST = dyn_cast<StructType>(T))
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000277 ElementSize = DL.getStructLayout(ST)->getSizeInBytes();
Victor Hernandez788eaab2009-09-18 19:20:02 +0000278
Gabor Greifad7884a2010-06-23 21:41:47 +0000279 // If malloc call's arg can be determined to be a multiple of ElementSize,
Victor Hernandezfcc77b12009-11-10 08:32:25 +0000280 // return the multiple. Otherwise, return NULL.
Gabor Greifad7884a2010-06-23 21:41:47 +0000281 Value *MallocArg = CI->getArgOperand(0);
Craig Topper9f008862014-04-15 04:59:12 +0000282 Value *Multiple = nullptr;
Sanjay Patel490193d2016-07-07 16:19:09 +0000283 if (ComputeMultiple(MallocArg, ElementSize, Multiple, LookThroughSExt))
Victor Hernandezfcc77b12009-11-10 08:32:25 +0000284 return Multiple;
Victor Hernandez788eaab2009-09-18 19:20:02 +0000285
Craig Topper9f008862014-04-15 04:59:12 +0000286 return nullptr;
Evan Cheng1d9d4bd2009-09-10 04:36:43 +0000287}
288
Evan Cheng1d9d4bd2009-09-10 04:36:43 +0000289/// getMallocType - Returns the PointerType resulting from the malloc call.
Victor Hernandezf3db9152009-11-07 00:16:28 +0000290/// The PointerType depends on the number of bitcast uses of the malloc call:
291/// 0: PointerType is the calls' return type.
292/// 1: PointerType is the bitcast's result type.
293/// >1: Unique PointerType cannot be determined, return NULL.
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000294PointerType *llvm::getMallocType(const CallInst *CI,
295 const TargetLibraryInfo *TLI) {
296 assert(isMallocLikeFn(CI, TLI) && "getMallocType and not malloc call");
Michael Ilsemand9745242013-03-08 21:03:09 +0000297
Craig Topper9f008862014-04-15 04:59:12 +0000298 PointerType *MallocType = nullptr;
Victor Hernandezf3db9152009-11-07 00:16:28 +0000299 unsigned NumOfBitCastUses = 0;
300
Victor Hernandez788eaab2009-09-18 19:20:02 +0000301 // Determine if CallInst has a bitcast use.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000302 for (Value::const_user_iterator UI = CI->user_begin(), E = CI->user_end();
303 UI != E;)
Victor Hernandezf3db9152009-11-07 00:16:28 +0000304 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(*UI++)) {
305 MallocType = cast<PointerType>(BCI->getDestTy());
306 NumOfBitCastUses++;
307 }
Evan Cheng1d9d4bd2009-09-10 04:36:43 +0000308
Victor Hernandezf3db9152009-11-07 00:16:28 +0000309 // Malloc call has 1 bitcast use, so type is the bitcast's destination type.
310 if (NumOfBitCastUses == 1)
311 return MallocType;
Evan Cheng1d9d4bd2009-09-10 04:36:43 +0000312
Victor Hernandezddc2ce42009-09-22 18:50:03 +0000313 // Malloc call was not bitcast, so type is the malloc function's return type.
Victor Hernandezf3db9152009-11-07 00:16:28 +0000314 if (NumOfBitCastUses == 0)
Victor Hernandez788eaab2009-09-18 19:20:02 +0000315 return cast<PointerType>(CI->getType());
316
317 // Type could not be determined.
Craig Topper9f008862014-04-15 04:59:12 +0000318 return nullptr;
Evan Cheng1d9d4bd2009-09-10 04:36:43 +0000319}
320
Victor Hernandezf3db9152009-11-07 00:16:28 +0000321/// getMallocAllocatedType - Returns the Type allocated by malloc call.
322/// The Type depends on the number of bitcast uses of the malloc call:
323/// 0: PointerType is the malloc calls' return type.
324/// 1: PointerType is the bitcast's result type.
325/// >1: Unique PointerType cannot be determined, return NULL.
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000326Type *llvm::getMallocAllocatedType(const CallInst *CI,
327 const TargetLibraryInfo *TLI) {
328 PointerType *PT = getMallocType(CI, TLI);
Craig Topper9f008862014-04-15 04:59:12 +0000329 return PT ? PT->getElementType() : nullptr;
Evan Cheng1d9d4bd2009-09-10 04:36:43 +0000330}
331
Michael Ilsemand9745242013-03-08 21:03:09 +0000332/// getMallocArraySize - Returns the array size of a malloc call. If the
Victor Hernandez0d025422009-10-28 20:18:55 +0000333/// argument passed to malloc is a multiple of the size of the malloced type,
334/// then return that multiple. For non-array mallocs, the multiple is
335/// constant 1. Otherwise, return NULL for mallocs whose array size cannot be
Victor Hernandez13020b12009-10-15 20:14:52 +0000336/// determined.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000337Value *llvm::getMallocArraySize(CallInst *CI, const DataLayout &DL,
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000338 const TargetLibraryInfo *TLI,
Victor Hernandezfcc77b12009-11-10 08:32:25 +0000339 bool LookThroughSExt) {
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000340 assert(isMallocLikeFn(CI, TLI) && "getMallocArraySize and not malloc call");
Matt Arsenault40dddd72013-10-03 19:50:01 +0000341 return computeArraySize(CI, DL, TLI, LookThroughSExt);
Evan Cheng1d9d4bd2009-09-10 04:36:43 +0000342}
Victor Hernandeze2971492009-10-24 04:23:03 +0000343
Nuno Lopesd2b71e72012-05-03 21:19:58 +0000344/// extractCallocCall - Returns the corresponding CallInst if the instruction
345/// is a calloc call.
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000346const CallInst *llvm::extractCallocCall(const Value *I,
347 const TargetLibraryInfo *TLI) {
Craig Topper9f008862014-04-15 04:59:12 +0000348 return isCallocLikeFn(I, TLI) ? cast<CallInst>(I) : nullptr;
Nuno Lopesd2b71e72012-05-03 21:19:58 +0000349}
350
Gabor Greif5f5a8642010-06-23 21:51:12 +0000351/// isFreeCall - Returns non-null if the value is a call to the builtin free()
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000352const CallInst *llvm::isFreeCall(const Value *I, const TargetLibraryInfo *TLI) {
Victor Hernandeze2971492009-10-24 04:23:03 +0000353 const CallInst *CI = dyn_cast<CallInst>(I);
Michael Ilseman74ffc272013-03-08 21:15:00 +0000354 if (!CI || isa<IntrinsicInst>(CI))
Craig Topper9f008862014-04-15 04:59:12 +0000355 return nullptr;
Victor Hernandez33188582009-11-03 20:39:35 +0000356 Function *Callee = CI->getCalledFunction();
Richard Smithe78bb122015-01-15 01:00:33 +0000357 if (Callee == nullptr)
Craig Topper9f008862014-04-15 04:59:12 +0000358 return nullptr;
Nick Lewyckyc1f86582011-03-15 07:31:32 +0000359
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000360 StringRef FnName = Callee->getName();
David L. Jonesd21529f2017-01-23 23:16:46 +0000361 LibFunc TLIFn;
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000362 if (!TLI || !TLI->getLibFunc(FnName, TLIFn) || !TLI->has(TLIFn))
Craig Topper9f008862014-04-15 04:59:12 +0000363 return nullptr;
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000364
Richard Smith70523c72013-07-21 23:11:42 +0000365 unsigned ExpectedNumParams;
David L. Jonesd21529f2017-01-23 23:16:46 +0000366 if (TLIFn == LibFunc_free ||
367 TLIFn == LibFunc_ZdlPv || // operator delete(void*)
368 TLIFn == LibFunc_ZdaPv || // operator delete[](void*)
369 TLIFn == LibFunc_msvc_delete_ptr32 || // operator delete(void*)
370 TLIFn == LibFunc_msvc_delete_ptr64 || // operator delete(void*)
371 TLIFn == LibFunc_msvc_delete_array_ptr32 || // operator delete[](void*)
372 TLIFn == LibFunc_msvc_delete_array_ptr64) // operator delete[](void*)
Richard Smith70523c72013-07-21 23:11:42 +0000373 ExpectedNumParams = 1;
David L. Jonesd21529f2017-01-23 23:16:46 +0000374 else if (TLIFn == LibFunc_ZdlPvj || // delete(void*, uint)
375 TLIFn == LibFunc_ZdlPvm || // delete(void*, ulong)
376 TLIFn == LibFunc_ZdlPvRKSt9nothrow_t || // delete(void*, nothrow)
377 TLIFn == LibFunc_ZdaPvj || // delete[](void*, uint)
378 TLIFn == LibFunc_ZdaPvm || // delete[](void*, ulong)
379 TLIFn == LibFunc_ZdaPvRKSt9nothrow_t || // delete[](void*, nothrow)
380 TLIFn == LibFunc_msvc_delete_ptr32_int || // delete(void*, uint)
381 TLIFn == LibFunc_msvc_delete_ptr64_longlong || // delete(void*, ulonglong)
382 TLIFn == LibFunc_msvc_delete_ptr32_nothrow || // delete(void*, nothrow)
383 TLIFn == LibFunc_msvc_delete_ptr64_nothrow || // delete(void*, nothrow)
384 TLIFn == LibFunc_msvc_delete_array_ptr32_int || // delete[](void*, uint)
385 TLIFn == LibFunc_msvc_delete_array_ptr64_longlong || // delete[](void*, ulonglong)
386 TLIFn == LibFunc_msvc_delete_array_ptr32_nothrow || // delete[](void*, nothrow)
387 TLIFn == LibFunc_msvc_delete_array_ptr64_nothrow) // delete[](void*, nothrow)
Richard Smith70523c72013-07-21 23:11:42 +0000388 ExpectedNumParams = 2;
389 else
Craig Topper9f008862014-04-15 04:59:12 +0000390 return nullptr;
Victor Hernandeze2971492009-10-24 04:23:03 +0000391
392 // Check free prototype.
Michael Ilsemand9745242013-03-08 21:03:09 +0000393 // FIXME: workaround for PR5130, this will be obsolete when a nobuiltin
Victor Hernandeze2971492009-10-24 04:23:03 +0000394 // attribute will exist.
Chris Lattner229907c2011-07-18 04:54:35 +0000395 FunctionType *FTy = Callee->getFunctionType();
Victor Hernandez33188582009-11-03 20:39:35 +0000396 if (!FTy->getReturnType()->isVoidTy())
Craig Topper9f008862014-04-15 04:59:12 +0000397 return nullptr;
Richard Smith70523c72013-07-21 23:11:42 +0000398 if (FTy->getNumParams() != ExpectedNumParams)
Craig Topper9f008862014-04-15 04:59:12 +0000399 return nullptr;
Chris Lattner67733f62011-06-18 21:46:23 +0000400 if (FTy->getParamType(0) != Type::getInt8PtrTy(Callee->getContext()))
Craig Topper9f008862014-04-15 04:59:12 +0000401 return nullptr;
Victor Hernandeze2971492009-10-24 04:23:03 +0000402
Gabor Greif5f5a8642010-06-23 21:51:12 +0000403 return CI;
Victor Hernandeze2971492009-10-24 04:23:03 +0000404}
Nuno Lopes55fff832012-06-21 15:45:28 +0000405
Nuno Lopes55fff832012-06-21 15:45:28 +0000406//===----------------------------------------------------------------------===//
407// Utility functions to compute size of objects.
408//
Petar Jovanovic644b8c12016-04-13 12:25:25 +0000409static APInt getSizeWithOverflow(const SizeOffsetType &Data) {
410 if (Data.second.isNegative() || Data.first.ult(Data.second))
411 return APInt(Data.first.getBitWidth(), 0);
412 return Data.first - Data.second;
413}
Nuno Lopes55fff832012-06-21 15:45:28 +0000414
415/// \brief Compute the size of the object pointed by Ptr. Returns true and the
416/// object size in Size if successful, and false otherwise.
Hiroshi Inoueef1c2ba2017-07-01 07:12:15 +0000417/// If RoundToAlign is true, then Size is rounded up to the alignment of
418/// allocas, byval arguments, and global variables.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000419bool llvm::getObjectSize(const Value *Ptr, uint64_t &Size, const DataLayout &DL,
George Burgess IV56c7e882017-03-21 20:08:59 +0000420 const TargetLibraryInfo *TLI, ObjectSizeOpts Opts) {
421 ObjectSizeOffsetVisitor Visitor(DL, TLI, Ptr->getContext(), Opts);
Nuno Lopes55fff832012-06-21 15:45:28 +0000422 SizeOffsetType Data = Visitor.compute(const_cast<Value*>(Ptr));
423 if (!Visitor.bothKnown(Data))
424 return false;
425
Petar Jovanovic644b8c12016-04-13 12:25:25 +0000426 Size = getSizeWithOverflow(Data).getZExtValue();
Nuno Lopes55fff832012-06-21 15:45:28 +0000427 return true;
428}
429
George Burgess IV3f089142016-12-20 23:46:36 +0000430ConstantInt *llvm::lowerObjectSizeCall(IntrinsicInst *ObjectSize,
431 const DataLayout &DL,
432 const TargetLibraryInfo *TLI,
433 bool MustSucceed) {
434 assert(ObjectSize->getIntrinsicID() == Intrinsic::objectsize &&
435 "ObjectSize must be a call to llvm.objectsize!");
436
437 bool MaxVal = cast<ConstantInt>(ObjectSize->getArgOperand(1))->isZero();
George Burgess IV56c7e882017-03-21 20:08:59 +0000438 ObjectSizeOpts EvalOptions;
George Burgess IV3f089142016-12-20 23:46:36 +0000439 // Unless we have to fold this to something, try to be as accurate as
440 // possible.
441 if (MustSucceed)
George Burgess IV56c7e882017-03-21 20:08:59 +0000442 EvalOptions.EvalMode =
443 MaxVal ? ObjectSizeOpts::Mode::Max : ObjectSizeOpts::Mode::Min;
George Burgess IV3f089142016-12-20 23:46:36 +0000444 else
George Burgess IV56c7e882017-03-21 20:08:59 +0000445 EvalOptions.EvalMode = ObjectSizeOpts::Mode::Exact;
446
447 EvalOptions.NullIsUnknownSize =
448 cast<ConstantInt>(ObjectSize->getArgOperand(2))->isOne();
George Burgess IV3f089142016-12-20 23:46:36 +0000449
450 // FIXME: Does it make sense to just return a failure value if the size won't
451 // fit in the output and `!MustSucceed`?
452 uint64_t Size;
453 auto *ResultType = cast<IntegerType>(ObjectSize->getType());
George Burgess IV56c7e882017-03-21 20:08:59 +0000454 if (getObjectSize(ObjectSize->getArgOperand(0), Size, DL, TLI, EvalOptions) &&
George Burgess IV3f089142016-12-20 23:46:36 +0000455 isUIntN(ResultType->getBitWidth(), Size))
456 return ConstantInt::get(ResultType, Size);
457
458 if (!MustSucceed)
459 return nullptr;
460
461 return ConstantInt::get(ResultType, MaxVal ? -1ULL : 0);
462}
463
Nuno Lopes55fff832012-06-21 15:45:28 +0000464STATISTIC(ObjectVisitorArgument,
465 "Number of arguments with unsolved size and offset");
466STATISTIC(ObjectVisitorLoad,
467 "Number of load instructions with unsolved size and offset");
468
Nuno Lopes55fff832012-06-21 15:45:28 +0000469APInt ObjectSizeOffsetVisitor::align(APInt Size, uint64_t Align) {
George Burgess IV56c7e882017-03-21 20:08:59 +0000470 if (Options.RoundToAlign && Align)
Rui Ueyamada00f2f2016-01-14 21:06:47 +0000471 return APInt(IntTyBits, alignTo(Size.getZExtValue(), Align));
Nuno Lopes55fff832012-06-21 15:45:28 +0000472 return Size;
473}
474
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000475ObjectSizeOffsetVisitor::ObjectSizeOffsetVisitor(const DataLayout &DL,
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000476 const TargetLibraryInfo *TLI,
Nuno Lopes55fff832012-06-21 15:45:28 +0000477 LLVMContext &Context,
George Burgess IV56c7e882017-03-21 20:08:59 +0000478 ObjectSizeOpts Options)
479 : DL(DL), TLI(TLI), Options(Options) {
Matt Arsenaultd3ee7af2013-12-14 00:27:48 +0000480 // Pointer size must be rechecked for each object visited since it could have
481 // a different address space.
Nuno Lopes55fff832012-06-21 15:45:28 +0000482}
483
484SizeOffsetType ObjectSizeOffsetVisitor::compute(Value *V) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000485 IntTyBits = DL.getPointerTypeSizeInBits(V->getType());
Matt Arsenaultd3ee7af2013-12-14 00:27:48 +0000486 Zero = APInt::getNullValue(IntTyBits);
487
Nuno Lopes55fff832012-06-21 15:45:28 +0000488 V = V->stripPointerCasts();
Nadav Rotemabcc64f2013-04-09 18:16:05 +0000489 if (Instruction *I = dyn_cast<Instruction>(V)) {
490 // If we have already seen this instruction, bail out. Cycles can happen in
491 // unreachable code after constant propagation.
David Blaikie70573dc2014-11-19 07:49:26 +0000492 if (!SeenInsts.insert(I).second)
Nadav Rotemabcc64f2013-04-09 18:16:05 +0000493 return unknown();
Nuno Lopesd896a402012-12-31 20:45:10 +0000494
Benjamin Kramer34764fe2012-08-17 19:26:41 +0000495 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
Nadav Rotemabcc64f2013-04-09 18:16:05 +0000496 return visitGEPOperator(*GEP);
497 return visit(*I);
Benjamin Kramer34764fe2012-08-17 19:26:41 +0000498 }
Nuno Lopes55fff832012-06-21 15:45:28 +0000499 if (Argument *A = dyn_cast<Argument>(V))
500 return visitArgument(*A);
501 if (ConstantPointerNull *P = dyn_cast<ConstantPointerNull>(V))
502 return visitConstantPointerNull(*P);
Nuno Lopese9d6dbf2012-12-31 16:23:48 +0000503 if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
504 return visitGlobalAlias(*GA);
Nuno Lopes55fff832012-06-21 15:45:28 +0000505 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
506 return visitGlobalVariable(*GV);
507 if (UndefValue *UV = dyn_cast<UndefValue>(V))
508 return visitUndefValue(*UV);
Benjamin Kramer34764fe2012-08-17 19:26:41 +0000509 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
Nuno Lopes55fff832012-06-21 15:45:28 +0000510 if (CE->getOpcode() == Instruction::IntToPtr)
511 return unknown(); // clueless
Nadav Rotemabcc64f2013-04-09 18:16:05 +0000512 if (CE->getOpcode() == Instruction::GetElementPtr)
513 return visitGEPOperator(cast<GEPOperator>(*CE));
Benjamin Kramer34764fe2012-08-17 19:26:41 +0000514 }
Nuno Lopes55fff832012-06-21 15:45:28 +0000515
516 DEBUG(dbgs() << "ObjectSizeOffsetVisitor::compute() unhandled value: " << *V
517 << '\n');
518 return unknown();
519}
520
Mikael Holmenad7e7182017-07-12 06:19:10 +0000521/// When we're compiling N-bit code, and the user uses parameters that are
522/// greater than N bits (e.g. uint64_t on a 32-bit build), we can run into
523/// trouble with APInt size issues. This function handles resizing + overflow
524/// checks for us. Check and zext or trunc \p I depending on IntTyBits and
525/// I's value.
526bool ObjectSizeOffsetVisitor::CheckedZextOrTrunc(APInt &I) {
527 // More bits than we can handle. Checking the bit width isn't necessary, but
528 // it's faster than checking active bits, and should give `false` in the
529 // vast majority of cases.
530 if (I.getBitWidth() > IntTyBits && I.getActiveBits() > IntTyBits)
531 return false;
532 if (I.getBitWidth() != IntTyBits)
533 I = I.zextOrTrunc(IntTyBits);
534 return true;
535}
536
Nuno Lopes55fff832012-06-21 15:45:28 +0000537SizeOffsetType ObjectSizeOffsetVisitor::visitAllocaInst(AllocaInst &I) {
538 if (!I.getAllocatedType()->isSized())
539 return unknown();
540
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000541 APInt Size(IntTyBits, DL.getTypeAllocSize(I.getAllocatedType()));
Nuno Lopes55fff832012-06-21 15:45:28 +0000542 if (!I.isArrayAllocation())
543 return std::make_pair(align(Size, I.getAlignment()), Zero);
544
545 Value *ArraySize = I.getArraySize();
546 if (const ConstantInt *C = dyn_cast<ConstantInt>(ArraySize)) {
Mikael Holmenad7e7182017-07-12 06:19:10 +0000547 APInt NumElems = C->getValue();
548 if (!CheckedZextOrTrunc(NumElems))
549 return unknown();
550
551 bool Overflow;
552 Size = Size.umul_ov(NumElems, Overflow);
553 return Overflow ? unknown() : std::make_pair(align(Size, I.getAlignment()),
554 Zero);
Nuno Lopes55fff832012-06-21 15:45:28 +0000555 }
556 return unknown();
557}
558
559SizeOffsetType ObjectSizeOffsetVisitor::visitArgument(Argument &A) {
Sanjay Patel490193d2016-07-07 16:19:09 +0000560 // No interprocedural analysis is done at the moment.
Reid Kleckner26af2ca2014-01-28 02:38:36 +0000561 if (!A.hasByValOrInAllocaAttr()) {
Nuno Lopes55fff832012-06-21 15:45:28 +0000562 ++ObjectVisitorArgument;
563 return unknown();
564 }
565 PointerType *PT = cast<PointerType>(A.getType());
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000566 APInt Size(IntTyBits, DL.getTypeAllocSize(PT->getElementType()));
Nuno Lopes55fff832012-06-21 15:45:28 +0000567 return std::make_pair(align(Size, A.getParamAlignment()), Zero);
568}
569
570SizeOffsetType ObjectSizeOffsetVisitor::visitCallSite(CallSite CS) {
George Burgess IVccae43a2016-12-23 01:18:09 +0000571 Optional<AllocFnsTy> FnData = getAllocationSize(CS.getInstruction(), TLI);
Nuno Lopes55fff832012-06-21 15:45:28 +0000572 if (!FnData)
573 return unknown();
574
Sanjay Patel490193d2016-07-07 16:19:09 +0000575 // Handle strdup-like functions separately.
Nuno Lopes55fff832012-06-21 15:45:28 +0000576 if (FnData->AllocTy == StrDupLike) {
Nuno Lopes2a4b09c2012-07-24 16:28:13 +0000577 APInt Size(IntTyBits, GetStringLength(CS.getArgument(0)));
578 if (!Size)
579 return unknown();
580
Sanjay Patel490193d2016-07-07 16:19:09 +0000581 // Strndup limits strlen.
Nuno Lopes2a4b09c2012-07-24 16:28:13 +0000582 if (FnData->FstParam > 0) {
George Burgess IV278199f2016-04-12 01:05:35 +0000583 ConstantInt *Arg =
584 dyn_cast<ConstantInt>(CS.getArgument(FnData->FstParam));
Nuno Lopes2a4b09c2012-07-24 16:28:13 +0000585 if (!Arg)
586 return unknown();
587
588 APInt MaxSize = Arg->getValue().zextOrSelf(IntTyBits);
589 if (Size.ugt(MaxSize))
590 Size = MaxSize + 1;
591 }
592 return std::make_pair(Size, Zero);
Nuno Lopes55fff832012-06-21 15:45:28 +0000593 }
594
595 ConstantInt *Arg = dyn_cast<ConstantInt>(CS.getArgument(FnData->FstParam));
596 if (!Arg)
597 return unknown();
598
George Burgess IV278199f2016-04-12 01:05:35 +0000599 APInt Size = Arg->getValue();
600 if (!CheckedZextOrTrunc(Size))
601 return unknown();
602
Sanjay Patel490193d2016-07-07 16:19:09 +0000603 // Size is determined by just 1 parameter.
Nuno Lopesf06b7312012-06-21 18:38:26 +0000604 if (FnData->SndParam < 0)
Nuno Lopes55fff832012-06-21 15:45:28 +0000605 return std::make_pair(Size, Zero);
606
607 Arg = dyn_cast<ConstantInt>(CS.getArgument(FnData->SndParam));
608 if (!Arg)
609 return unknown();
610
George Burgess IV278199f2016-04-12 01:05:35 +0000611 APInt NumElems = Arg->getValue();
612 if (!CheckedZextOrTrunc(NumElems))
613 return unknown();
614
615 bool Overflow;
616 Size = Size.umul_ov(NumElems, Overflow);
617 return Overflow ? unknown() : std::make_pair(Size, Zero);
Nuno Lopes55fff832012-06-21 15:45:28 +0000618
619 // TODO: handle more standard functions (+ wchar cousins):
Nuno Lopesf0626f22012-07-25 18:49:28 +0000620 // - strdup / strndup
Nuno Lopes55fff832012-06-21 15:45:28 +0000621 // - strcpy / strncpy
622 // - strcat / strncat
623 // - memcpy / memmove
Nuno Lopesf0626f22012-07-25 18:49:28 +0000624 // - strcat / strncat
Nuno Lopes55fff832012-06-21 15:45:28 +0000625 // - memset
626}
627
628SizeOffsetType
George Burgess IV56c7e882017-03-21 20:08:59 +0000629ObjectSizeOffsetVisitor::visitConstantPointerNull(ConstantPointerNull& CPN) {
630 if (Options.NullIsUnknownSize && CPN.getType()->getAddressSpace() == 0)
631 return unknown();
Nuno Lopes55fff832012-06-21 15:45:28 +0000632 return std::make_pair(Zero, Zero);
633}
634
635SizeOffsetType
Nuno Lopes181d67e2012-06-28 16:34:03 +0000636ObjectSizeOffsetVisitor::visitExtractElementInst(ExtractElementInst&) {
637 return unknown();
638}
639
640SizeOffsetType
Nuno Lopes55fff832012-06-21 15:45:28 +0000641ObjectSizeOffsetVisitor::visitExtractValueInst(ExtractValueInst&) {
642 // Easy cases were already folded by previous passes.
643 return unknown();
644}
645
646SizeOffsetType ObjectSizeOffsetVisitor::visitGEPOperator(GEPOperator &GEP) {
647 SizeOffsetType PtrData = compute(GEP.getPointerOperand());
Nuno Lopesb6ad9822012-12-30 16:25:48 +0000648 APInt Offset(IntTyBits, 0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000649 if (!bothKnown(PtrData) || !GEP.accumulateConstantOffset(DL, Offset))
Nuno Lopes55fff832012-06-21 15:45:28 +0000650 return unknown();
651
Nuno Lopes55fff832012-06-21 15:45:28 +0000652 return std::make_pair(PtrData.first, PtrData.second + Offset);
653}
654
Nuno Lopese9d6dbf2012-12-31 16:23:48 +0000655SizeOffsetType ObjectSizeOffsetVisitor::visitGlobalAlias(GlobalAlias &GA) {
Sanjoy Das5ce32722016-04-08 00:48:30 +0000656 if (GA.isInterposable())
Nuno Lopese9d6dbf2012-12-31 16:23:48 +0000657 return unknown();
658 return compute(GA.getAliasee());
659}
660
Nuno Lopes55fff832012-06-21 15:45:28 +0000661SizeOffsetType ObjectSizeOffsetVisitor::visitGlobalVariable(GlobalVariable &GV){
662 if (!GV.hasDefinitiveInitializer())
663 return unknown();
664
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000665 APInt Size(IntTyBits, DL.getTypeAllocSize(GV.getType()->getElementType()));
Nuno Lopes55fff832012-06-21 15:45:28 +0000666 return std::make_pair(align(Size, GV.getAlignment()), Zero);
667}
668
669SizeOffsetType ObjectSizeOffsetVisitor::visitIntToPtrInst(IntToPtrInst&) {
670 // clueless
671 return unknown();
672}
673
674SizeOffsetType ObjectSizeOffsetVisitor::visitLoadInst(LoadInst&) {
675 ++ObjectVisitorLoad;
676 return unknown();
677}
678
Nadav Rotemabcc64f2013-04-09 18:16:05 +0000679SizeOffsetType ObjectSizeOffsetVisitor::visitPHINode(PHINode&) {
680 // too complex to analyze statically.
681 return unknown();
Nuno Lopes55fff832012-06-21 15:45:28 +0000682}
683
684SizeOffsetType ObjectSizeOffsetVisitor::visitSelectInst(SelectInst &I) {
685 SizeOffsetType TrueSide = compute(I.getTrueValue());
686 SizeOffsetType FalseSide = compute(I.getFalseValue());
Petar Jovanovic644b8c12016-04-13 12:25:25 +0000687 if (bothKnown(TrueSide) && bothKnown(FalseSide)) {
688 if (TrueSide == FalseSide) {
689 return TrueSide;
690 }
691
692 APInt TrueResult = getSizeWithOverflow(TrueSide);
693 APInt FalseResult = getSizeWithOverflow(FalseSide);
694
695 if (TrueResult == FalseResult) {
696 return TrueSide;
697 }
George Burgess IV56c7e882017-03-21 20:08:59 +0000698 if (Options.EvalMode == ObjectSizeOpts::Mode::Min) {
Petar Jovanovic644b8c12016-04-13 12:25:25 +0000699 if (TrueResult.slt(FalseResult))
700 return TrueSide;
701 return FalseSide;
702 }
George Burgess IV56c7e882017-03-21 20:08:59 +0000703 if (Options.EvalMode == ObjectSizeOpts::Mode::Max) {
Petar Jovanovic644b8c12016-04-13 12:25:25 +0000704 if (TrueResult.sgt(FalseResult))
705 return TrueSide;
706 return FalseSide;
707 }
708 }
Nuno Lopes55fff832012-06-21 15:45:28 +0000709 return unknown();
710}
711
712SizeOffsetType ObjectSizeOffsetVisitor::visitUndefValue(UndefValue&) {
713 return std::make_pair(Zero, Zero);
714}
715
716SizeOffsetType ObjectSizeOffsetVisitor::visitInstruction(Instruction &I) {
717 DEBUG(dbgs() << "ObjectSizeOffsetVisitor unknown instruction:" << I << '\n');
718 return unknown();
719}
720
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000721ObjectSizeOffsetEvaluator::ObjectSizeOffsetEvaluator(
722 const DataLayout &DL, const TargetLibraryInfo *TLI, LLVMContext &Context,
723 bool RoundToAlign)
724 : DL(DL), TLI(TLI), Context(Context), Builder(Context, TargetFolder(DL)),
725 RoundToAlign(RoundToAlign) {
Matt Arsenaultd3ee7af2013-12-14 00:27:48 +0000726 // IntTy and Zero must be set for each compute() since the address space may
727 // be different for later objects.
Nuno Lopes55fff832012-06-21 15:45:28 +0000728}
729
730SizeOffsetEvalType ObjectSizeOffsetEvaluator::compute(Value *V) {
Matt Arsenaultd3ee7af2013-12-14 00:27:48 +0000731 // XXX - Are vectors of pointers possible here?
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000732 IntTy = cast<IntegerType>(DL.getIntPtrType(V->getType()));
Matt Arsenaultd3ee7af2013-12-14 00:27:48 +0000733 Zero = ConstantInt::get(IntTy, 0);
734
Nuno Lopes55fff832012-06-21 15:45:28 +0000735 SizeOffsetEvalType Result = compute_(V);
736
737 if (!bothKnown(Result)) {
Sanjay Patel490193d2016-07-07 16:19:09 +0000738 // Erase everything that was computed in this iteration from the cache, so
Nuno Lopes55fff832012-06-21 15:45:28 +0000739 // that no dangling references are left behind. We could be a bit smarter if
740 // we kept a dependency graph. It's probably not worth the complexity.
Benjamin Krameraa209152016-06-26 17:27:42 +0000741 for (const Value *SeenVal : SeenVals) {
742 CacheMapTy::iterator CacheIt = CacheMap.find(SeenVal);
Nuno Lopes55fff832012-06-21 15:45:28 +0000743 // non-computable results can be safely cached
744 if (CacheIt != CacheMap.end() && anyKnown(CacheIt->second))
745 CacheMap.erase(CacheIt);
746 }
747 }
748
749 SeenVals.clear();
750 return Result;
751}
752
753SizeOffsetEvalType ObjectSizeOffsetEvaluator::compute_(Value *V) {
George Burgess IV56c7e882017-03-21 20:08:59 +0000754 ObjectSizeOpts ObjSizeOptions;
755 ObjSizeOptions.RoundToAlign = RoundToAlign;
756
757 ObjectSizeOffsetVisitor Visitor(DL, TLI, Context, ObjSizeOptions);
Nuno Lopes55fff832012-06-21 15:45:28 +0000758 SizeOffsetType Const = Visitor.compute(V);
759 if (Visitor.bothKnown(Const))
760 return std::make_pair(ConstantInt::get(Context, Const.first),
761 ConstantInt::get(Context, Const.second));
762
763 V = V->stripPointerCasts();
764
Sanjay Patel490193d2016-07-07 16:19:09 +0000765 // Check cache.
Nuno Lopes55fff832012-06-21 15:45:28 +0000766 CacheMapTy::iterator CacheIt = CacheMap.find(V);
767 if (CacheIt != CacheMap.end())
768 return CacheIt->second;
769
Sanjay Patel490193d2016-07-07 16:19:09 +0000770 // Always generate code immediately before the instruction being
771 // processed, so that the generated code dominates the same BBs.
Duncan P. N. Exon Smith5a82c912015-10-10 00:53:03 +0000772 BuilderTy::InsertPointGuard Guard(Builder);
Nuno Lopes55fff832012-06-21 15:45:28 +0000773 if (Instruction *I = dyn_cast<Instruction>(V))
774 Builder.SetInsertPoint(I);
775
Sanjay Patel490193d2016-07-07 16:19:09 +0000776 // Now compute the size and offset.
Nuno Lopes55fff832012-06-21 15:45:28 +0000777 SizeOffsetEvalType Result;
Benjamin Kramer155c9d52013-09-29 19:39:13 +0000778
779 // Record the pointers that were handled in this run, so that they can be
780 // cleaned later if something fails. We also use this set to break cycles that
781 // can occur in dead code.
David Blaikie70573dc2014-11-19 07:49:26 +0000782 if (!SeenVals.insert(V).second) {
Benjamin Kramer155c9d52013-09-29 19:39:13 +0000783 Result = unknown();
784 } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
Nuno Lopes55fff832012-06-21 15:45:28 +0000785 Result = visitGEPOperator(*GEP);
786 } else if (Instruction *I = dyn_cast<Instruction>(V)) {
787 Result = visit(*I);
788 } else if (isa<Argument>(V) ||
789 (isa<ConstantExpr>(V) &&
790 cast<ConstantExpr>(V)->getOpcode() == Instruction::IntToPtr) ||
Nuno Lopese9d6dbf2012-12-31 16:23:48 +0000791 isa<GlobalAlias>(V) ||
Nuno Lopes55fff832012-06-21 15:45:28 +0000792 isa<GlobalVariable>(V)) {
Sanjay Patel490193d2016-07-07 16:19:09 +0000793 // Ignore values where we cannot do more than ObjectSizeVisitor.
Nuno Lopes55fff832012-06-21 15:45:28 +0000794 Result = unknown();
795 } else {
796 DEBUG(dbgs() << "ObjectSizeOffsetEvaluator::compute() unhandled value: "
797 << *V << '\n');
798 Result = unknown();
799 }
800
Nuno Lopes55fff832012-06-21 15:45:28 +0000801 // Don't reuse CacheIt since it may be invalid at this point.
802 CacheMap[V] = Result;
803 return Result;
804}
805
806SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitAllocaInst(AllocaInst &I) {
807 if (!I.getAllocatedType()->isSized())
808 return unknown();
809
810 // must be a VLA
811 assert(I.isArrayAllocation());
812 Value *ArraySize = I.getArraySize();
813 Value *Size = ConstantInt::get(ArraySize->getType(),
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000814 DL.getTypeAllocSize(I.getAllocatedType()));
Nuno Lopes55fff832012-06-21 15:45:28 +0000815 Size = Builder.CreateMul(Size, ArraySize);
816 return std::make_pair(Size, Zero);
817}
818
819SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitCallSite(CallSite CS) {
George Burgess IVccae43a2016-12-23 01:18:09 +0000820 Optional<AllocFnsTy> FnData = getAllocationSize(CS.getInstruction(), TLI);
Nuno Lopes55fff832012-06-21 15:45:28 +0000821 if (!FnData)
822 return unknown();
823
Sanjay Patel490193d2016-07-07 16:19:09 +0000824 // Handle strdup-like functions separately.
Nuno Lopes55fff832012-06-21 15:45:28 +0000825 if (FnData->AllocTy == StrDupLike) {
Nuno Lopesf0626f22012-07-25 18:49:28 +0000826 // TODO
827 return unknown();
Nuno Lopes55fff832012-06-21 15:45:28 +0000828 }
829
Nuno Lopesa6aa3d32012-06-21 16:47:58 +0000830 Value *FirstArg = CS.getArgument(FnData->FstParam);
831 FirstArg = Builder.CreateZExt(FirstArg, IntTy);
Nuno Lopesf06b7312012-06-21 18:38:26 +0000832 if (FnData->SndParam < 0)
Nuno Lopes55fff832012-06-21 15:45:28 +0000833 return std::make_pair(FirstArg, Zero);
834
835 Value *SecondArg = CS.getArgument(FnData->SndParam);
Nuno Lopesa6aa3d32012-06-21 16:47:58 +0000836 SecondArg = Builder.CreateZExt(SecondArg, IntTy);
Nuno Lopes55fff832012-06-21 15:45:28 +0000837 Value *Size = Builder.CreateMul(FirstArg, SecondArg);
838 return std::make_pair(Size, Zero);
839
840 // TODO: handle more standard functions (+ wchar cousins):
Nuno Lopesf0626f22012-07-25 18:49:28 +0000841 // - strdup / strndup
Nuno Lopes55fff832012-06-21 15:45:28 +0000842 // - strcpy / strncpy
843 // - strcat / strncat
844 // - memcpy / memmove
Nuno Lopesf0626f22012-07-25 18:49:28 +0000845 // - strcat / strncat
Nuno Lopes55fff832012-06-21 15:45:28 +0000846 // - memset
847}
848
849SizeOffsetEvalType
Nuno Lopes181d67e2012-06-28 16:34:03 +0000850ObjectSizeOffsetEvaluator::visitExtractElementInst(ExtractElementInst&) {
851 return unknown();
852}
853
854SizeOffsetEvalType
855ObjectSizeOffsetEvaluator::visitExtractValueInst(ExtractValueInst&) {
856 return unknown();
857}
858
859SizeOffsetEvalType
Nuno Lopes55fff832012-06-21 15:45:28 +0000860ObjectSizeOffsetEvaluator::visitGEPOperator(GEPOperator &GEP) {
861 SizeOffsetEvalType PtrData = compute_(GEP.getPointerOperand());
862 if (!bothKnown(PtrData))
863 return unknown();
864
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000865 Value *Offset = EmitGEPOffset(&Builder, DL, &GEP, /*NoAssumptions=*/true);
Nuno Lopes55fff832012-06-21 15:45:28 +0000866 Offset = Builder.CreateAdd(PtrData.second, Offset);
867 return std::make_pair(PtrData.first, Offset);
868}
869
870SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitIntToPtrInst(IntToPtrInst&) {
871 // clueless
872 return unknown();
873}
874
875SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitLoadInst(LoadInst&) {
876 return unknown();
877}
878
879SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitPHINode(PHINode &PHI) {
Sanjay Patel490193d2016-07-07 16:19:09 +0000880 // Create 2 PHIs: one for size and another for offset.
Nuno Lopes55fff832012-06-21 15:45:28 +0000881 PHINode *SizePHI = Builder.CreatePHI(IntTy, PHI.getNumIncomingValues());
882 PHINode *OffsetPHI = Builder.CreatePHI(IntTy, PHI.getNumIncomingValues());
883
Sanjay Patel490193d2016-07-07 16:19:09 +0000884 // Insert right away in the cache to handle recursive PHIs.
Nuno Lopes55fff832012-06-21 15:45:28 +0000885 CacheMap[&PHI] = std::make_pair(SizePHI, OffsetPHI);
886
Sanjay Patel490193d2016-07-07 16:19:09 +0000887 // Compute offset/size for each PHI incoming pointer.
Nuno Lopes55fff832012-06-21 15:45:28 +0000888 for (unsigned i = 0, e = PHI.getNumIncomingValues(); i != e; ++i) {
Duncan P. N. Exon Smith5a82c912015-10-10 00:53:03 +0000889 Builder.SetInsertPoint(&*PHI.getIncomingBlock(i)->getFirstInsertionPt());
Nuno Lopes55fff832012-06-21 15:45:28 +0000890 SizeOffsetEvalType EdgeData = compute_(PHI.getIncomingValue(i));
891
892 if (!bothKnown(EdgeData)) {
893 OffsetPHI->replaceAllUsesWith(UndefValue::get(IntTy));
894 OffsetPHI->eraseFromParent();
895 SizePHI->replaceAllUsesWith(UndefValue::get(IntTy));
896 SizePHI->eraseFromParent();
897 return unknown();
898 }
899 SizePHI->addIncoming(EdgeData.first, PHI.getIncomingBlock(i));
900 OffsetPHI->addIncoming(EdgeData.second, PHI.getIncomingBlock(i));
901 }
Nuno Lopes9291ff42012-07-03 17:13:25 +0000902
903 Value *Size = SizePHI, *Offset = OffsetPHI, *Tmp;
904 if ((Tmp = SizePHI->hasConstantValue())) {
905 Size = Tmp;
906 SizePHI->replaceAllUsesWith(Size);
907 SizePHI->eraseFromParent();
908 }
909 if ((Tmp = OffsetPHI->hasConstantValue())) {
910 Offset = Tmp;
911 OffsetPHI->replaceAllUsesWith(Offset);
912 OffsetPHI->eraseFromParent();
913 }
914 return std::make_pair(Size, Offset);
Nuno Lopes55fff832012-06-21 15:45:28 +0000915}
916
917SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitSelectInst(SelectInst &I) {
918 SizeOffsetEvalType TrueSide = compute_(I.getTrueValue());
919 SizeOffsetEvalType FalseSide = compute_(I.getFalseValue());
920
921 if (!bothKnown(TrueSide) || !bothKnown(FalseSide))
922 return unknown();
923 if (TrueSide == FalseSide)
924 return TrueSide;
925
926 Value *Size = Builder.CreateSelect(I.getCondition(), TrueSide.first,
927 FalseSide.first);
928 Value *Offset = Builder.CreateSelect(I.getCondition(), TrueSide.second,
929 FalseSide.second);
930 return std::make_pair(Size, Offset);
931}
932
933SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitInstruction(Instruction &I) {
934 DEBUG(dbgs() << "ObjectSizeOffsetEvaluator unknown instruction:" << I <<'\n');
935 return unknown();
936}