MemoryBuiltins.cpp 48 KB

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