46#define DEBUG_TYPE "memprof"
62 "__memprof_version_mismatch_check_v";
65 "__memprof_shadow_memory_dynamic_address";
72STATISTIC(NumInstrumentedReads,
"Number of instrumented reads");
73STATISTIC(NumInstrumentedWrites,
"Number of instrumented writes");
74STATISTIC(NumSkippedStackReads,
"Number of non-instrumented stack reads");
75STATISTIC(NumSkippedStackWrites,
"Number of non-instrumented stack writes");
82 ShadowMapping(
const InstrumentationOptions &Opts) {
83 Scale = Opts.memprof_mapping_scale;
85 : Opts.memprof_mapping_granularity;
86 Mask = ~(Granularity - 1);
99struct InterestingMemoryAccess {
100 Value *Addr =
nullptr;
103 Value *MaybeMask =
nullptr;
109 MemProfiler(
const InstrumentationOptions &Opts,
Module &M)
110 : Opts(Opts), Mapping(Opts) {
111 C = &(
M.getContext());
112 LongSize =
M.getDataLayout().getPointerSizeInBits();
113 IntptrTy = Type::getIntNTy(*C, LongSize);
114 PtrTy = PointerType::getUnqual(*C);
120 std::optional<InterestingMemoryAccess>
121 isInterestingMemoryAccess(Instruction *
I)
const;
123 void instrumentMop(Instruction *
I,
const DataLayout &
DL,
124 InterestingMemoryAccess &
Access);
126 Value *Addr,
bool IsWrite);
127 void instrumentMaskedLoadOrStore(
const DataLayout &
DL,
Value *Mask,
130 void instrumentMemIntrinsic(MemIntrinsic *
MI);
133 bool maybeInsertMemProfInitAtFunctionEntry(
Function &
F);
134 bool insertDynamicShadowAtFunctionEntry(
Function &
F);
137 void initializeCallbacks(
Module &M);
139 const InstrumentationOptions &Opts;
144 ShadowMapping Mapping;
147 FunctionCallee MemProfMemoryAccessCallback[2];
149 FunctionCallee MemProfMemmove, MemProfMemcpy, MemProfMemset;
150 Value *DynamicShadowOffset =
nullptr;
153class ModuleMemProfiler {
155 ModuleMemProfiler(
const InstrumentationOptions &Opts,
Module &M)
156 : Opts(Opts), Mapping(Opts) {
157 TargetTriple =
M.getTargetTriple();
160 bool instrumentModule(
Module &);
163 const InstrumentationOptions &Opts;
165 ShadowMapping Mapping;
166 Function *MemProfCtorFunction =
nullptr;
176 assert((!Opts.memprof_histogram ||
178 "Memprof with histogram only supports default mapping granularity");
180 MemProfiler Profiler(Opts, M);
181 if (Profiler.instrumentFunction(
F))
192 ModuleMemProfiler Profiler(Opts, M);
193 if (Profiler.instrumentModule(M))
200 Shadow = IRB.
CreateAnd(Shadow, Mapping.Mask);
201 Shadow = IRB.
CreateLShr(Shadow, Mapping.Scale);
203 assert(DynamicShadowOffset);
204 return IRB.
CreateAdd(Shadow, DynamicShadowOffset);
212 {
MI->getOperand(0),
MI->getOperand(1),
221 MI->eraseFromParent();
224std::optional<InterestingMemoryAccess>
225MemProfiler::isInterestingMemoryAccess(
Instruction *
I)
const {
227 if (DynamicShadowOffset ==
I)
230 InterestingMemoryAccess
Access;
233 if (!Opts.memprof_instrument_reads)
236 Access.AccessTy = LI->getType();
237 Access.Addr = LI->getPointerOperand();
239 if (!Opts.memprof_instrument_writes)
242 Access.AccessTy =
SI->getValueOperand()->getType();
243 Access.Addr =
SI->getPointerOperand();
245 if (!Opts.memprof_instrument_atomics)
248 Access.AccessTy = RMW->getValOperand()->getType();
249 Access.Addr = RMW->getPointerOperand();
251 if (!Opts.memprof_instrument_atomics)
254 Access.AccessTy = XCHG->getCompareOperand()->getType();
255 Access.Addr = XCHG->getPointerOperand();
257 auto *
F = CI->getCalledFunction();
258 if (
F && (
F->getIntrinsicID() == Intrinsic::masked_load ||
259 F->getIntrinsicID() == Intrinsic::masked_store)) {
260 unsigned OpOffset = 0;
261 if (
F->getIntrinsicID() == Intrinsic::masked_store) {
262 if (!Opts.memprof_instrument_writes)
266 Access.AccessTy = CI->getArgOperand(0)->getType();
269 if (!Opts.memprof_instrument_reads)
271 Access.AccessTy = CI->getType();
275 auto *
BasePtr = CI->getOperand(0 + OpOffset);
276 Access.MaybeMask = CI->getOperand(1 + OpOffset);
294 if (
Access.Addr->isSwiftError())
298 auto *Addr =
Access.Addr->stripInBoundsOffsets();
302 if (GV->hasSection()) {
305 auto OF =
I->getModule()->getTargetTriple().getObjectFormat();
312 if (GV->getName().starts_with(
"__llvm") ||
322 Type *AccessTy,
bool IsWrite) {
324 unsigned Num = VTy->getNumElements();
325 auto *
Zero = ConstantInt::get(IntptrTy, 0);
326 for (
unsigned Idx = 0;
Idx < Num; ++
Idx) {
327 Value *InstrumentedAddress =
nullptr;
342 InsertBefore = ThenTerm;
346 InstrumentedAddress =
347 IRB.
CreateGEP(VTy, Addr, {
Zero, ConstantInt::get(IntptrTy, Idx)});
353 InterestingMemoryAccess &
Access) {
355 if (!Opts.memprof_instrument_stack &&
358 ++NumSkippedStackWrites;
360 ++NumSkippedStackReads;
365 NumInstrumentedWrites++;
367 NumInstrumentedReads++;
380void MemProfiler::instrumentAddress(
Instruction *OrigIns,
386 if (Opts.memprof_use_callbacks) {
387 IRB.
CreateCall(MemProfMemoryAccessCallback[IsWrite], AddrLong);
395 Value *ShadowPtr = memToShadow(AddrLong, IRB);
399 if (Opts.memprof_histogram) {
406 Value *Inc = ConstantInt::get(ShadowTy, 1);
407 ShadowValue = IRB.
CreateAdd(ShadowValue, Inc);
415 if (!MemProfFilename)
418 "Unexpected MemProfProfileFilename metadata with empty string");
420 M.getContext(), MemProfFilename->
getString(),
true);
422 M, ProfileNameConst->
getType(),
true,
424 const Triple &TT = M.getTargetTriple();
425 if (TT.supportsCOMDAT()) {
441 const Triple &TT = M.getTargetTriple();
442 if (TT.supportsCOMDAT()) {
444 MemprofHistogramFlag->setComdat(M.getOrInsertComdat(VarName));
452 M.getContext(), Opts.memprof_runtime_default_options,
true);
457 const Triple &TT = M.getTargetTriple();
458 if (TT.supportsCOMDAT()) {
464bool ModuleMemProfiler::instrumentModule(
Module &M) {
468 std::string VersionCheckName =
469 Opts.memprof_guard_against_version_mismatch
472 std::tie(MemProfCtorFunction, std::ignore) =
475 {}, VersionCheckName);
477 const uint64_t Priority = getCtorAndDtorPriority(TargetTriple);
489void MemProfiler::initializeCallbacks(
Module &M) {
492 for (
size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
493 const std::string TypeStr = AccessIsWrite ?
"store" :
"load";
494 const std::string HistPrefix = Opts.memprof_histogram ?
"hist_" :
"";
497 MemProfMemoryAccessCallback[AccessIsWrite] =
M.getOrInsertFunction(
498 (Opts.memprof_memory_access_callback_prefix + HistPrefix + TypeStr)
502 MemProfMemmove =
M.getOrInsertFunction(
503 (Opts.memprof_memory_access_callback_prefix +
"memmove").str(), PtrTy,
504 PtrTy, PtrTy, IntptrTy);
505 MemProfMemcpy =
M.getOrInsertFunction(
506 (Opts.memprof_memory_access_callback_prefix +
"memcpy").str(), PtrTy,
507 PtrTy, PtrTy, IntptrTy);
508 MemProfMemset =
M.getOrInsertFunction(
509 (Opts.memprof_memory_access_callback_prefix +
"memset").str(), PtrTy,
513bool MemProfiler::maybeInsertMemProfInitAtFunctionEntry(
Function &
F) {
521 if (
F.getName().contains(
" load]")) {
531bool MemProfiler::insertDynamicShadowAtFunctionEntry(
Function &
F) {
533 Value *GlobalDynamicAddress =
F.getParent()->getOrInsertGlobal(
537 DynamicShadowOffset = IRB.
CreateLoad(IntptrTy, GlobalDynamicAddress);
541bool MemProfiler::instrumentFunction(
Function &
F) {
544 if (Opts.memprof_debug_func ==
F.getName())
546 if (
F.getName().starts_with(
"__memprof_"))
549 bool FunctionModified =
false;
554 if (maybeInsertMemProfInitAtFunctionEntry(
F))
555 FunctionModified =
true;
559 initializeCallbacks(*
F.getParent());
565 for (
auto &Inst : BB) {
571 if (ToInstrument.
empty()) {
572 LLVM_DEBUG(
dbgs() <<
"MEMPROF done instrumenting: " << FunctionModified
573 <<
" " <<
F <<
"\n");
575 return FunctionModified;
578 FunctionModified |= insertDynamicShadowAtFunctionEntry(
F);
580 int NumInstrumented = 0;
581 for (
auto *Inst : ToInstrument) {
582 if (Opts.memprof_debug_min < 0 || Opts.memprof_debug_max < 0 ||
583 (NumInstrumented >= Opts.memprof_debug_min &&
584 NumInstrumented <= Opts.memprof_debug_max)) {
585 std::optional<InterestingMemoryAccess>
Access =
586 isInterestingMemoryAccess(Inst);
588 instrumentMop(Inst,
F.getDataLayout(), *
Access);
595 if (NumInstrumented > 0)
596 FunctionModified =
true;
598 LLVM_DEBUG(
dbgs() <<
"MEMPROF done instrumenting: " << FunctionModified <<
" "
601 return FunctionModified;
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
Module.h This file contains the declarations for the Module class.
constexpr char MemProfVersionCheckNamePrefix[]
constexpr uint64_t MemProfEmscriptenCtorAndDtorPriority
constexpr char MemProfShadowMemoryDynamicAddress[]
constexpr uint64_t MemProfCtorAndDtorPriority
constexpr int LLVM_MEM_PROFILER_VERSION
constexpr char MemProfInitName[]
constexpr char MemProfFilenameVar[]
constexpr uint64_t DefaultMemGranularity
constexpr uint64_t HistogramGranularity
constexpr char MemProfModuleCtorName[]
void createMemprofDefaultOptionsVar(const InstrumentationOptions &Opts, Module &M)
constexpr char MemProfHistogramFlagVar[]
void createMemprofHistogramFlagVar(const InstrumentationOptions &Opts, Module &M)
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Class for arbitrary precision integers.
A container for analyses that lazily runs them and caches their results.
An instruction that atomically checks whether a specified value is in a memory location,...
an instruction that atomically reads a memory location, combines it with another value,...
static LLVM_ABI Constant * getString(LLVMContext &Context, StringRef Initializer, bool AddNull=true, bool ByteString=false)
This method constructs a CDS and initializes it with a text string.
This is an important base class in LLVM.
static LLVM_ABI Constant * getIntegerValue(Type *Ty, const APInt &V)
Return the value for an integer or pointer constant, or a vector thereof, with the given scalar value...
A parsed version of the target data layout string in and methods for querying it.
A handy container for a FunctionType+Callee-pointer pair, which can be passed around as a single enti...
static LLVM_ABI FunctionType * get(Type *Result, ArrayRef< Type * > Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
LLVM_ABI void setComdat(Comdat *C)
void setLinkage(LinkageTypes LT)
@ ExternalLinkage
Externally visible function.
@ WeakAnyLinkage
Keep one copy of named function when linking (weak)
@ AvailableExternallyLinkage
Available for inspection, not emission.
Value * CreateICmpULT(Value *LHS, Value *RHS, const Twine &Name="")
Value * CreateExtractElement(Value *Vec, Value *Idx, const Twine &Name="")
Value * CreatePointerCast(Value *V, Type *DestTy, const Twine &Name="")
Value * CreateIntToPtr(Value *V, Type *DestTy, const Twine &Name="")
Value * CreateLShr(Value *LHS, Value *RHS, const Twine &Name="", bool isExact=false)
IntegerType * getInt32Ty()
Fetch the type representing a 32-bit integer.
Value * CreateGEP(Type *Ty, Value *Ptr, ArrayRef< Value * > IdxList, const Twine &Name="", GEPNoWrapFlags NW=GEPNoWrapFlags::none())
LoadInst * CreateLoad(Type *Ty, Value *Ptr, const char *Name)
Provided to resolve 'CreateLoad(Ty, Ptr, "...")' correctly, instead of converting the string to 'bool...
Value * CreateAnd(Value *LHS, Value *RHS, const Twine &Name="")
StoreInst * CreateStore(Value *Val, Value *Ptr, bool isVolatile=false)
Value * CreateAdd(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
CallInst * CreateCall(FunctionType *FTy, Value *Callee, ArrayRef< Value * > Args={}, const Twine &Name="", MDNode *FPMathTag=nullptr)
Value * CreateIntCast(Value *V, Type *DestTy, bool isSigned, const Twine &Name="")
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block.
Type * getVoidTy()
Fetch the type representing void.
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
An instruction for reading from memory.
LLVM_ABI StringRef getString() const
This is the common base class for memset/memcpy/memmove.
LLVM_ABI MemProfilerPass()
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
LLVM_ABI PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
LLVM_ABI ModuleMemProfilerPass()
A Module instance is used to store all the information related to an LLVM module.
static LLVM_ABI PointerType * get(LLVMContext &C, unsigned AddressSpace)
This constructs an opaque pointer to an object in a numbered address space.
A set of analyses that are preserved following a run of a transformation pass.
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
An instruction for storing to memory.
Represent a constant reference to a string, i.e.
constexpr bool empty() const
Check if the string is empty.
Triple - Helper class for working with autoconf configuration names.
bool isOSEmscripten() const
Tests whether the OS is Emscripten.
The instances of the Type class are immutable: once they are created, they are never changed.
LLVM_ABI unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
static LLVM_ABI IntegerType * getInt8Ty(LLVMContext &C)
static LLVM_ABI IntegerType * getInt1Ty(LLVMContext &C)
LLVM Value Representation.
Type * getType() const
All values are typed, get the type of this value.
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
void instrumentAddress(Module &M, IRBuilder<> &IRB, Instruction *OrigIns, Instruction *InsertBefore, Value *Addr, Align Alignment, TypeSize TypeStoreSize, bool IsWrite, Value *SizeArgument, bool UseCalls, bool Recover, int AsanScale, int AsanOffset)
Instrument the memory operand Addr.
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
llvm::StringRef getMemprofOptionsSymbolName()
This is an optimization pass for GlobalISel generic memory operations.
const InstrumentationOptions & getInstrumentationOptions(const LLVMContext &C)
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
LLVM_ABI std::string getInstrProfSectionName(InstrProfSectKind IPSK, Triple::ObjectFormatType OF, bool AddSegmentInfo=true)
Return the name of the profile section corresponding to IPSK.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
auto dyn_cast_or_null(const Y &Val)
LLVM_ABI FunctionCallee declareSanitizerInitFunction(Module &M, StringRef InitName, ArrayRef< Type * > InitArgTypes, bool Weak=false)
LLVM_ABI std::pair< Function *, FunctionCallee > createSanitizerCtorAndInitFunctions(Module &M, StringRef CtorName, StringRef InitName, ArrayRef< Type * > InitArgTypes, ArrayRef< Value * > InitArgs, StringRef VersionCheckName=StringRef(), bool Weak=false)
Creates sanitizer constructor function, and calls sanitizer's init function from it.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
IRBuilder(LLVMContext &, FolderTy, InserterTy) -> IRBuilder< FolderTy, InserterTy >
LLVM_ABI const Value * getUnderlyingObject(const Value *V, unsigned MaxLookup=MaxLookupSearchDepth, bool MustPreserveProvenance=false)
This method strips off any GEP address adjustments, pointer casts or llvm.threadlocal....
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
LLVM_ABI void appendToCompilerUsed(Module &M, ArrayRef< GlobalValue * > Values)
Adds global values to the llvm.compiler.used list.
StringRef getInstrProfVarPrefix()
Return the prefix of the name of the variables to function as a filter.
LLVM_ABI void createProfileFileNameVar(Module &M, StringRef InstrProfileOutput)
LLVM_ABI void appendToGlobalCtors(Module &M, Function *F, int Priority, Constant *Data=nullptr)
Append F to the list of global ctors of module M with the given Priority.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
LLVM_ABI Instruction * SplitBlockAndInsertIfThen(Value *Cond, BasicBlock::iterator SplitBefore, bool Unreachable, MDNode *BranchWeights=nullptr, DomTreeUpdater *DTU=nullptr, LoopInfo *LI=nullptr, BasicBlock *ThenBlock=nullptr)
Split the containing block at the specified instruction - everything before SplitBefore stays in the ...