MemoryBuiltins.h 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //==- llvm/Analysis/MemoryBuiltins.h - Calls to memory builtins --*- C++ -*-==//
  7. //
  8. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  9. // See https://llvm.org/LICENSE.txt for license information.
  10. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  11. //
  12. //===----------------------------------------------------------------------===//
  13. //
  14. // This family of functions identifies calls to builtin functions that allocate
  15. // or free memory.
  16. //
  17. //===----------------------------------------------------------------------===//
  18. #ifndef LLVM_ANALYSIS_MEMORYBUILTINS_H
  19. #define LLVM_ANALYSIS_MEMORYBUILTINS_H
  20. #include "llvm/ADT/APInt.h"
  21. #include "llvm/ADT/DenseMap.h"
  22. #include "llvm/ADT/SmallPtrSet.h"
  23. #include "llvm/Analysis/TargetFolder.h"
  24. #include "llvm/Analysis/TargetLibraryInfo.h"
  25. #include "llvm/IR/IRBuilder.h"
  26. #include "llvm/IR/InstVisitor.h"
  27. #include "llvm/IR/ValueHandle.h"
  28. #include <cstdint>
  29. #include <utility>
  30. namespace llvm {
  31. class AllocaInst;
  32. class Argument;
  33. class CallInst;
  34. class ConstantPointerNull;
  35. class DataLayout;
  36. class ExtractElementInst;
  37. class ExtractValueInst;
  38. class GEPOperator;
  39. class GlobalAlias;
  40. class GlobalVariable;
  41. class Instruction;
  42. class IntegerType;
  43. class IntrinsicInst;
  44. class IntToPtrInst;
  45. class LLVMContext;
  46. class LoadInst;
  47. class PHINode;
  48. class SelectInst;
  49. class Type;
  50. class UndefValue;
  51. class Value;
  52. /// Tests if a value is a call or invoke to a library function that
  53. /// allocates or reallocates memory (either malloc, calloc, realloc, or strdup
  54. /// like).
  55. bool isAllocationFn(const Value *V, const TargetLibraryInfo *TLI);
  56. bool isAllocationFn(const Value *V,
  57. function_ref<const TargetLibraryInfo &(Function &)> GetTLI);
  58. /// Tests if a value is a call or invoke to a library function that
  59. /// allocates memory similar to malloc or calloc.
  60. bool isMallocOrCallocLikeFn(const Value *V, const TargetLibraryInfo *TLI);
  61. /// Tests if a value is a call or invoke to a library function that
  62. /// allocates memory (either malloc, calloc, or strdup like).
  63. bool isAllocLikeFn(const Value *V, const TargetLibraryInfo *TLI);
  64. /// Tests if a value is a call or invoke to a library function that
  65. /// reallocates memory (e.g., realloc).
  66. bool isReallocLikeFn(const Value *V, const TargetLibraryInfo *TLI);
  67. /// Tests if a function is a call or invoke to a library function that
  68. /// reallocates memory (e.g., realloc).
  69. bool isReallocLikeFn(const Function *F, const TargetLibraryInfo *TLI);
  70. //===----------------------------------------------------------------------===//
  71. // free Call Utility Functions.
  72. //
  73. /// isLibFreeFunction - Returns true if the function is a builtin free()
  74. bool isLibFreeFunction(const Function *F, const LibFunc TLIFn);
  75. /// isFreeCall - Returns non-null if the value is a call to the builtin free()
  76. const CallInst *isFreeCall(const Value *I, const TargetLibraryInfo *TLI);
  77. inline CallInst *isFreeCall(Value *I, const TargetLibraryInfo *TLI) {
  78. return const_cast<CallInst*>(isFreeCall((const Value*)I, TLI));
  79. }
  80. //===----------------------------------------------------------------------===//
  81. // Properties of allocation functions
  82. //
  83. /// Return false if the allocation can have side effects on the program state
  84. /// we are required to preserve beyond the effect of allocating a new object.
  85. /// Ex: If our allocation routine has a counter for the number of objects
  86. /// allocated, and the program prints it on exit, can the value change due
  87. /// to optimization? Answer is highly language dependent.
  88. /// Note: *Removable* really does mean removable; it does not mean observable.
  89. /// A language (e.g. C++) can allow removing allocations without allowing
  90. /// insertion or speculative execution of allocation routines.
  91. bool isAllocRemovable(const CallBase *V, const TargetLibraryInfo *TLI);
  92. /// Gets the alignment argument for an aligned_alloc-like function
  93. Value *getAllocAlignment(const CallBase *V, const TargetLibraryInfo *TLI);
  94. /// Return the size of the requested allocation. With a trivial mapper, this is
  95. /// identical to calling getObjectSize(..., Exact). A mapper function can be
  96. /// used to replace one Value* (operand to the allocation) with another. This
  97. /// is useful when doing abstract interpretation.
  98. Optional<APInt> getAllocSize(const CallBase *CB,
  99. const TargetLibraryInfo *TLI,
  100. std::function<const Value*(const Value*)> Mapper);
  101. /// If this allocation function initializes memory to a fixed value, return
  102. /// said value in the requested type. Otherwise, return nullptr.
  103. Constant *getInitialValueOfAllocation(const CallBase *Alloc,
  104. const TargetLibraryInfo *TLI,
  105. Type *Ty);
  106. //===----------------------------------------------------------------------===//
  107. // Utility functions to compute size of objects.
  108. //
  109. /// Various options to control the behavior of getObjectSize.
  110. struct ObjectSizeOpts {
  111. /// Controls how we handle conditional statements with unknown conditions.
  112. enum class Mode : uint8_t {
  113. /// Fail to evaluate an unknown condition.
  114. Exact,
  115. /// Evaluate all branches of an unknown condition. If all evaluations
  116. /// succeed, pick the minimum size.
  117. Min,
  118. /// Same as Min, except we pick the maximum size of all of the branches.
  119. Max
  120. };
  121. /// How we want to evaluate this object's size.
  122. Mode EvalMode = Mode::Exact;
  123. /// Whether to round the result up to the alignment of allocas, byval
  124. /// arguments, and global variables.
  125. bool RoundToAlign = false;
  126. /// If this is true, null pointers in address space 0 will be treated as
  127. /// though they can't be evaluated. Otherwise, null is always considered to
  128. /// point to a 0 byte region of memory.
  129. bool NullIsUnknownSize = false;
  130. };
  131. /// Compute the size of the object pointed by Ptr. Returns true and the
  132. /// object size in Size if successful, and false otherwise. In this context, by
  133. /// object we mean the region of memory starting at Ptr to the end of the
  134. /// underlying object pointed to by Ptr.
  135. ///
  136. /// WARNING: The object size returned is the allocation size. This does not
  137. /// imply dereferenceability at site of use since the object may be freeed in
  138. /// between.
  139. bool getObjectSize(const Value *Ptr, uint64_t &Size, const DataLayout &DL,
  140. const TargetLibraryInfo *TLI, ObjectSizeOpts Opts = {});
  141. /// Try to turn a call to \@llvm.objectsize into an integer value of the given
  142. /// Type. Returns null on failure. If MustSucceed is true, this function will
  143. /// not return null, and may return conservative values governed by the second
  144. /// argument of the call to objectsize.
  145. Value *lowerObjectSizeCall(IntrinsicInst *ObjectSize, const DataLayout &DL,
  146. const TargetLibraryInfo *TLI, bool MustSucceed);
  147. using SizeOffsetType = std::pair<APInt, APInt>;
  148. /// Evaluate the size and offset of an object pointed to by a Value*
  149. /// statically. Fails if size or offset are not known at compile time.
  150. class ObjectSizeOffsetVisitor
  151. : public InstVisitor<ObjectSizeOffsetVisitor, SizeOffsetType> {
  152. const DataLayout &DL;
  153. const TargetLibraryInfo *TLI;
  154. ObjectSizeOpts Options;
  155. unsigned IntTyBits;
  156. APInt Zero;
  157. SmallPtrSet<Instruction *, 8> SeenInsts;
  158. APInt align(APInt Size, MaybeAlign Align);
  159. SizeOffsetType unknown() {
  160. return std::make_pair(APInt(), APInt());
  161. }
  162. public:
  163. ObjectSizeOffsetVisitor(const DataLayout &DL, const TargetLibraryInfo *TLI,
  164. LLVMContext &Context, ObjectSizeOpts Options = {});
  165. SizeOffsetType compute(Value *V);
  166. static bool knownSize(const SizeOffsetType &SizeOffset) {
  167. return SizeOffset.first.getBitWidth() > 1;
  168. }
  169. static bool knownOffset(const SizeOffsetType &SizeOffset) {
  170. return SizeOffset.second.getBitWidth() > 1;
  171. }
  172. static bool bothKnown(const SizeOffsetType &SizeOffset) {
  173. return knownSize(SizeOffset) && knownOffset(SizeOffset);
  174. }
  175. // These are "private", except they can't actually be made private. Only
  176. // compute() should be used by external users.
  177. SizeOffsetType visitAllocaInst(AllocaInst &I);
  178. SizeOffsetType visitArgument(Argument &A);
  179. SizeOffsetType visitCallBase(CallBase &CB);
  180. SizeOffsetType visitConstantPointerNull(ConstantPointerNull&);
  181. SizeOffsetType visitExtractElementInst(ExtractElementInst &I);
  182. SizeOffsetType visitExtractValueInst(ExtractValueInst &I);
  183. SizeOffsetType visitGlobalAlias(GlobalAlias &GA);
  184. SizeOffsetType visitGlobalVariable(GlobalVariable &GV);
  185. SizeOffsetType visitIntToPtrInst(IntToPtrInst&);
  186. SizeOffsetType visitLoadInst(LoadInst &I);
  187. SizeOffsetType visitPHINode(PHINode&);
  188. SizeOffsetType visitSelectInst(SelectInst &I);
  189. SizeOffsetType visitUndefValue(UndefValue&);
  190. SizeOffsetType visitInstruction(Instruction &I);
  191. private:
  192. SizeOffsetType computeImpl(Value *V);
  193. bool CheckedZextOrTrunc(APInt &I);
  194. };
  195. using SizeOffsetEvalType = std::pair<Value *, Value *>;
  196. /// Evaluate the size and offset of an object pointed to by a Value*.
  197. /// May create code to compute the result at run-time.
  198. class ObjectSizeOffsetEvaluator
  199. : public InstVisitor<ObjectSizeOffsetEvaluator, SizeOffsetEvalType> {
  200. using BuilderTy = IRBuilder<TargetFolder, IRBuilderCallbackInserter>;
  201. using WeakEvalType = std::pair<WeakTrackingVH, WeakTrackingVH>;
  202. using CacheMapTy = DenseMap<const Value *, WeakEvalType>;
  203. using PtrSetTy = SmallPtrSet<const Value *, 8>;
  204. const DataLayout &DL;
  205. const TargetLibraryInfo *TLI;
  206. LLVMContext &Context;
  207. BuilderTy Builder;
  208. IntegerType *IntTy;
  209. Value *Zero;
  210. CacheMapTy CacheMap;
  211. PtrSetTy SeenVals;
  212. ObjectSizeOpts EvalOpts;
  213. SmallPtrSet<Instruction *, 8> InsertedInstructions;
  214. SizeOffsetEvalType compute_(Value *V);
  215. public:
  216. static SizeOffsetEvalType unknown() {
  217. return std::make_pair(nullptr, nullptr);
  218. }
  219. ObjectSizeOffsetEvaluator(const DataLayout &DL, const TargetLibraryInfo *TLI,
  220. LLVMContext &Context, ObjectSizeOpts EvalOpts = {});
  221. SizeOffsetEvalType compute(Value *V);
  222. bool knownSize(SizeOffsetEvalType SizeOffset) {
  223. return SizeOffset.first;
  224. }
  225. bool knownOffset(SizeOffsetEvalType SizeOffset) {
  226. return SizeOffset.second;
  227. }
  228. bool anyKnown(SizeOffsetEvalType SizeOffset) {
  229. return knownSize(SizeOffset) || knownOffset(SizeOffset);
  230. }
  231. bool bothKnown(SizeOffsetEvalType SizeOffset) {
  232. return knownSize(SizeOffset) && knownOffset(SizeOffset);
  233. }
  234. // The individual instruction visitors should be treated as private.
  235. SizeOffsetEvalType visitAllocaInst(AllocaInst &I);
  236. SizeOffsetEvalType visitCallBase(CallBase &CB);
  237. SizeOffsetEvalType visitExtractElementInst(ExtractElementInst &I);
  238. SizeOffsetEvalType visitExtractValueInst(ExtractValueInst &I);
  239. SizeOffsetEvalType visitGEPOperator(GEPOperator &GEP);
  240. SizeOffsetEvalType visitIntToPtrInst(IntToPtrInst&);
  241. SizeOffsetEvalType visitLoadInst(LoadInst &I);
  242. SizeOffsetEvalType visitPHINode(PHINode &PHI);
  243. SizeOffsetEvalType visitSelectInst(SelectInst &I);
  244. SizeOffsetEvalType visitInstruction(Instruction &I);
  245. };
  246. } // end namespace llvm
  247. #endif // LLVM_ANALYSIS_MEMORYBUILTINS_H
  248. #ifdef __GNUC__
  249. #pragma GCC diagnostic pop
  250. #endif