52#define DEBUG_TYPE "memprof"
77 "__memprof_version_mismatch_check_v";
80 "__memprof_shadow_memory_dynamic_address";
89 "memprof-guard-against-version-mismatch",
95 cl::desc(
"instrument read instructions"),
104 "memprof-instrument-atomics",
109 "memprof-use-callbacks",
110 cl::desc(
"Use callbacks instead of inline instrumentation sequences."),
115 cl::desc(
"Prefix for memory access callbacks"),
123 cl::desc(
"scale of memprof shadow mapping"),
128 cl::desc(
"granularity of memprof shadow mapping"),
132 cl::desc(
"Instrument scalar stack variables"),
153 "memprof-match-hot-cold-new",
155 "Match allocation profiles onto existing hot/cold operator new calls"),
159 cl::desc(
"Collect access count histograms"),
164 cl::desc(
"Print matching stats for each allocation "
165 "context in this module's profiles"),
171STATISTIC(NumInstrumentedReads,
"Number of instrumented reads");
172STATISTIC(NumInstrumentedWrites,
"Number of instrumented writes");
173STATISTIC(NumSkippedStackReads,
"Number of non-instrumented stack reads");
174STATISTIC(NumSkippedStackWrites,
"Number of non-instrumented stack writes");
177STATISTIC(NumOfMemProfMissing,
"Number of functions without memory profile.");
179 "Number of functions having mismatched memory profile hash.");
180STATISTIC(NumOfMemProfFunc,
"Number of functions having valid memory profile.");
182 "Number of alloc contexts in memory profile.");
184 "Number of callsites in memory profile.");
186 "Number of matched memory profile alloc contexts.");
188 "Number of matched memory profile allocs.");
190 "Number of matched memory profile callsites.");
196struct ShadowMapping {
200 Mask = ~(Granularity - 1);
213struct InterestingMemoryAccess {
217 Value *MaybeMask =
nullptr;
224 C = &(
M.getContext());
225 LongSize =
M.getDataLayout().getPointerSizeInBits();
227 PtrTy = PointerType::getUnqual(*C);
233 std::optional<InterestingMemoryAccess>
237 InterestingMemoryAccess &Access);
246 bool maybeInsertMemProfInitAtFunctionEntry(
Function &
F);
247 bool insertDynamicShadowAtFunctionEntry(
Function &
F);
250 void initializeCallbacks(
Module &M);
256 ShadowMapping Mapping;
262 Value *DynamicShadowOffset =
nullptr;
265class ModuleMemProfiler {
267 ModuleMemProfiler(
Module &M) { TargetTriple =
Triple(
M.getTargetTriple()); }
269 bool instrumentModule(
Module &);
273 ShadowMapping Mapping;
274 Function *MemProfCtorFunction =
nullptr;
284 "Memprof with histogram only supports default mapping granularity");
286 MemProfiler Profiler(M);
287 if (Profiler.instrumentFunction(
F))
297 ModuleMemProfiler Profiler(M);
298 if (Profiler.instrumentModule(M))
305 Shadow = IRB.
CreateAnd(Shadow, Mapping.Mask);
306 Shadow = IRB.
CreateLShr(Shadow, Mapping.Scale);
308 assert(DynamicShadowOffset);
309 return IRB.
CreateAdd(Shadow, DynamicShadowOffset);
315 if (isa<MemTransferInst>(
MI)) {
316 IRB.
CreateCall(isa<MemMoveInst>(
MI) ? MemProfMemmove : MemProfMemcpy,
317 {
MI->getOperand(0),
MI->getOperand(1),
319 }
else if (isa<MemSetInst>(
MI)) {
326 MI->eraseFromParent();
329std::optional<InterestingMemoryAccess>
330MemProfiler::isInterestingMemoryAccess(
Instruction *
I)
const {
332 if (DynamicShadowOffset ==
I)
335 InterestingMemoryAccess Access;
337 if (
LoadInst *LI = dyn_cast<LoadInst>(
I)) {
340 Access.IsWrite =
false;
341 Access.AccessTy = LI->getType();
342 Access.Addr = LI->getPointerOperand();
343 }
else if (
StoreInst *SI = dyn_cast<StoreInst>(
I)) {
346 Access.IsWrite =
true;
347 Access.AccessTy =
SI->getValueOperand()->getType();
348 Access.Addr =
SI->getPointerOperand();
352 Access.IsWrite =
true;
353 Access.AccessTy = RMW->getValOperand()->getType();
354 Access.Addr = RMW->getPointerOperand();
358 Access.IsWrite =
true;
359 Access.AccessTy = XCHG->getCompareOperand()->getType();
360 Access.Addr = XCHG->getPointerOperand();
361 }
else if (
auto *CI = dyn_cast<CallInst>(
I)) {
362 auto *
F = CI->getCalledFunction();
363 if (
F && (
F->getIntrinsicID() == Intrinsic::masked_load ||
364 F->getIntrinsicID() == Intrinsic::masked_store)) {
365 unsigned OpOffset = 0;
366 if (
F->getIntrinsicID() == Intrinsic::masked_store) {
371 Access.AccessTy = CI->getArgOperand(0)->getType();
372 Access.IsWrite =
true;
376 Access.AccessTy = CI->getType();
377 Access.IsWrite =
false;
380 auto *
BasePtr = CI->getOperand(0 + OpOffset);
381 Access.MaybeMask = CI->getOperand(2 + OpOffset);
391 Type *PtrTy = cast<PointerType>(Access.Addr->getType()->getScalarType());
399 if (Access.Addr->isSwiftError())
403 auto *
Addr = Access.Addr->stripInBoundsOffsets();
407 if (GV->hasSection()) {
417 if (GV->getName().starts_with(
"__llvm"))
426 Type *AccessTy,
bool IsWrite) {
427 auto *VTy = cast<FixedVectorType>(AccessTy);
428 unsigned Num = VTy->getNumElements();
429 auto *
Zero = ConstantInt::get(IntptrTy, 0);
430 for (
unsigned Idx = 0;
Idx < Num; ++
Idx) {
431 Value *InstrumentedAddress =
nullptr;
433 if (
auto *
Vector = dyn_cast<ConstantVector>(Mask)) {
446 InsertBefore = ThenTerm;
450 InstrumentedAddress =
457 InterestingMemoryAccess &Access) {
461 ++NumSkippedStackWrites;
463 ++NumSkippedStackReads;
468 NumInstrumentedWrites++;
470 NumInstrumentedReads++;
472 if (Access.MaybeMask) {
473 instrumentMaskedLoadOrStore(
DL, Access.MaybeMask,
I, Access.Addr,
474 Access.AccessTy, Access.IsWrite);
483void MemProfiler::instrumentAddress(
Instruction *OrigIns,
490 IRB.
CreateCall(MemProfMemoryAccessCallback[IsWrite], AddrLong);
497 Value *ShadowPtr = memToShadow(AddrLong, IRB);
508 Value *Inc = ConstantInt::get(ShadowTy, 1);
509 ShadowValue = IRB.
CreateAdd(ShadowValue, Inc);
516 dyn_cast_or_null<MDString>(M.getModuleFlag(
"MemProfProfileFilename"));
517 if (!MemProfFilename)
520 "Unexpected MemProfProfileFilename metadata with empty string");
522 M.getContext(), MemProfFilename->
getString(),
true);
524 M, ProfileNameConst->
getType(),
true,
526 Triple TT(M.getTargetTriple());
527 if (TT.supportsCOMDAT()) {
541 Triple TT(M.getTargetTriple());
542 if (TT.supportsCOMDAT()) {
544 MemprofHistogramFlag->setComdat(M.getOrInsertComdat(VarName));
549bool ModuleMemProfiler::instrumentModule(
Module &M) {
553 std::string VersionCheckName =
556 std::tie(MemProfCtorFunction, std::ignore) =
559 {}, VersionCheckName);
561 const uint64_t Priority = getCtorAndDtorPriority(TargetTriple);
571void MemProfiler::initializeCallbacks(
Module &M) {
574 for (
size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
575 const std::string TypeStr = AccessIsWrite ?
"store" :
"load";
576 const std::string HistPrefix =
ClHistogram ?
"hist_" :
"";
579 MemProfMemoryAccessCallback[AccessIsWrite] =
M.getOrInsertFunction(
583 MemProfMemmove =
M.getOrInsertFunction(
586 PtrTy, PtrTy, PtrTy, IntptrTy);
592bool MemProfiler::maybeInsertMemProfInitAtFunctionEntry(
Function &
F) {
600 if (
F.getName().contains(
" load]")) {
610bool MemProfiler::insertDynamicShadowAtFunctionEntry(
Function &
F) {
612 Value *GlobalDynamicAddress =
F.getParent()->getOrInsertGlobal(
615 cast<GlobalVariable>(GlobalDynamicAddress)->setDSOLocal(
true);
616 DynamicShadowOffset = IRB.
CreateLoad(IntptrTy, GlobalDynamicAddress);
620bool MemProfiler::instrumentFunction(
Function &
F) {
625 if (
F.getName().starts_with(
"__memprof_"))
628 bool FunctionModified =
false;
633 if (maybeInsertMemProfInitAtFunctionEntry(
F))
634 FunctionModified =
true;
638 initializeCallbacks(*
F.getParent());
644 for (
auto &Inst : BB) {
645 if (isInterestingMemoryAccess(&Inst) || isa<MemIntrinsic>(Inst))
650 if (ToInstrument.
empty()) {
651 LLVM_DEBUG(
dbgs() <<
"MEMPROF done instrumenting: " << FunctionModified
652 <<
" " <<
F <<
"\n");
654 return FunctionModified;
657 FunctionModified |= insertDynamicShadowAtFunctionEntry(
F);
659 int NumInstrumented = 0;
660 for (
auto *Inst : ToInstrument) {
663 std::optional<InterestingMemoryAccess> Access =
664 isInterestingMemoryAccess(Inst);
666 instrumentMop(Inst,
F.getDataLayout(), *Access);
668 instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
673 if (NumInstrumented > 0)
674 FunctionModified =
true;
676 LLVM_DEBUG(
dbgs() <<
"MEMPROF done instrumenting: " << FunctionModified <<
" "
679 return FunctionModified;
683 std::vector<uint64_t> &InlinedCallStack,
685 I.setMetadata(LLVMContext::MD_callsite,
696 std::memcpy(&Id, Hash.data(),
sizeof(Hash));
714 std::memcpy(&Id, Hash.data(),
sizeof(Hash));
721 for (
const auto &StackFrame :
AllocInfo->CallStack)
728 TotalSize =
AllocInfo->Info.getTotalSize();
742 unsigned StartIndex = 0) {
743 auto StackFrame = ProfileCallStack.
begin() + StartIndex;
744 auto InlCallStackIter = InlinedCallStack.
begin();
745 for (; StackFrame != ProfileCallStack.
end() &&
746 InlCallStackIter != InlinedCallStack.
end();
747 ++StackFrame, ++InlCallStackIter) {
749 if (StackId != *InlCallStackIter)
754 return InlCallStackIter == InlinedCallStack.
end();
766 case LibFunc_ZnwmRKSt9nothrow_t:
767 case LibFunc_ZnwmSt11align_val_t:
768 case LibFunc_ZnwmSt11align_val_tRKSt9nothrow_t:
770 case LibFunc_ZnamRKSt9nothrow_t:
771 case LibFunc_ZnamSt11align_val_t:
772 case LibFunc_ZnamSt11align_val_tRKSt9nothrow_t:
773 case LibFunc_size_returning_new:
774 case LibFunc_size_returning_new_aligned:
776 case LibFunc_Znwm12__hot_cold_t:
777 case LibFunc_ZnwmRKSt9nothrow_t12__hot_cold_t:
778 case LibFunc_ZnwmSt11align_val_t12__hot_cold_t:
779 case LibFunc_ZnwmSt11align_val_tRKSt9nothrow_t12__hot_cold_t:
780 case LibFunc_Znam12__hot_cold_t:
781 case LibFunc_ZnamRKSt9nothrow_t12__hot_cold_t:
782 case LibFunc_ZnamSt11align_val_t12__hot_cold_t:
783 case LibFunc_ZnamSt11align_val_tRKSt9nothrow_t12__hot_cold_t:
784 case LibFunc_size_returning_new_hot_cold:
785 case LibFunc_size_returning_new_aligned_hot_cold:
795 bool Matched =
false;
801 std::map<uint64_t, AllocMatchInfo> &FullStackIdToAllocMatchInfo) {
802 auto &Ctx = M.getContext();
810 auto FuncName =
F.getName();
812 std::optional<memprof::MemProfRecord> MemProfRec;
813 auto Err =
MemProfReader->getMemProfRecord(FuncGUID).moveInto(MemProfRec);
816 auto Err = IPE.
get();
817 bool SkipWarning =
false;
818 LLVM_DEBUG(
dbgs() <<
"Error in reading profile for Func " << FuncName
821 NumOfMemProfMissing++;
825 NumOfMemProfMismatch++;
831 LLVM_DEBUG(
dbgs() <<
"hash mismatch (skip=" << SkipWarning <<
")");
837 std::string Msg = (IPE.
message() +
Twine(
" ") +
F.getName().str() +
838 Twine(
" Hash = ") + std::to_string(FuncGUID))
853 bool ProfileHasColumns =
false;
857 std::map<uint64_t, std::set<const AllocationInfo *>> LocHashToAllocInfo;
860 std::map<uint64_t, std::set<std::pair<const std::vector<Frame> *,
unsigned>>>
862 for (
auto &AI : MemProfRec->AllocSites) {
863 NumOfMemProfAllocContextProfiles++;
868 LocHashToAllocInfo[StackId].insert(&AI);
869 ProfileHasColumns |= AI.CallStack[0].Column;
871 for (
auto &CS : MemProfRec->CallSites) {
872 NumOfMemProfCallSiteProfiles++;
876 for (
auto &StackFrame : CS) {
878 LocHashToCallSites[StackId].insert(std::make_pair(&CS,
Idx++));
879 ProfileHasColumns |= StackFrame.Column;
881 if (StackFrame.Function == FuncGUID)
884 assert(
Idx <= CS.size() && CS[
Idx - 1].Function == FuncGUID);
888 return (DIL->getLine() - DIL->getScope()->getSubprogram()->getLine()) &
896 if (
I.isDebugOrPseudoInst())
900 auto *CI = dyn_cast<CallBase>(&
I);
903 auto *CalledFunction = CI->getCalledFunction();
904 if (CalledFunction && CalledFunction->isIntrinsic())
908 std::vector<uint64_t> InlinedCallStack;
910 bool LeafFound =
false;
916 std::map<uint64_t, std::set<const AllocationInfo *>>::iterator
918 std::map<uint64_t, std::set<std::pair<const std::vector<Frame> *,
919 unsigned>>>::iterator CallSitesIter;
920 for (
const DILocation *DIL =
I.getDebugLoc(); DIL !=
nullptr;
921 DIL = DIL->getInlinedAt()) {
924 StringRef Name = DIL->getScope()->getSubprogram()->getLinkageName();
926 Name = DIL->getScope()->getSubprogram()->getName();
929 ProfileHasColumns ? DIL->getColumn() : 0);
935 AllocInfoIter = LocHashToAllocInfo.find(StackId);
936 CallSitesIter = LocHashToCallSites.find(StackId);
937 if (AllocInfoIter != LocHashToAllocInfo.end() ||
938 CallSitesIter != LocHashToCallSites.end())
942 InlinedCallStack.push_back(StackId);
952 if (AllocInfoIter != LocHashToAllocInfo.end()) {
960 for (
auto *
AllocInfo : AllocInfoIter->second) {
966 NumOfMemProfMatchedAllocContexts++;
972 FullStackIdToAllocMatchInfo[FullStackId] = {
980 if (!AllocTrie.
empty()) {
981 NumOfMemProfMatchedAllocs++;
985 assert(MemprofMDAttached ==
I.hasMetadata(LLVMContext::MD_memprof));
986 if (MemprofMDAttached) {
1003 assert(CallSitesIter != LocHashToCallSites.end());
1004 for (
auto CallStackIdx : CallSitesIter->second) {
1008 *CallStackIdx.first, InlinedCallStack, CallStackIdx.second)) {
1009 NumOfMemProfMatchedCallSites++;
1022 : MemoryProfileFileName(MemoryProfileFile), FS(FS) {
1029 auto &Ctx = M.getContext();
1031 if (
Error E = ReaderOrErr.takeError()) {
1040 std::move(ReaderOrErr.get());
1043 MemoryProfileFileName.data(),
StringRef(
"Cannot get MemProfReader")));
1049 "Not a memory profile"));
1058 std::map<uint64_t, AllocMatchInfo> FullStackIdToAllocMatchInfo;
1061 if (
F.isDeclaration())
1069 for (
const auto &[Id,
Info] : FullStackIdToAllocMatchInfo)
1071 <<
" context with id " << Id <<
" has total profiled size "
1072 <<
Info.TotalSize << (
Info.Matched ?
" is" :
" not")
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static cl::opt< int > ClDebugMin("asan-debug-min", cl::desc("Debug min inst"), cl::Hidden, cl::init(-1))
static cl::opt< std::string > ClMemoryAccessCallbackPrefix("asan-memory-access-callback-prefix", cl::desc("Prefix for memory access callbacks"), cl::Hidden, cl::init("__asan_"))
static cl::opt< bool > ClInsertVersionCheck("asan-guard-against-version-mismatch", cl::desc("Guard against compiler/runtime version mismatch."), cl::Hidden, cl::init(true))
static cl::opt< bool > ClInstrumentWrites("asan-instrument-writes", cl::desc("instrument write instructions"), cl::Hidden, cl::init(true))
static cl::opt< int > ClDebugMax("asan-debug-max", cl::desc("Debug max inst"), cl::Hidden, cl::init(-1))
static cl::opt< bool > ClStack("asan-stack", cl::desc("Handle stack memory"), cl::Hidden, cl::init(true))
static cl::opt< bool > ClInstrumentAtomics("asan-instrument-atomics", cl::desc("instrument atomic instructions (rmw, cmpxchg)"), cl::Hidden, cl::init(true))
static cl::opt< int > ClMappingScale("asan-mapping-scale", cl::desc("scale of asan shadow mapping"), cl::Hidden, cl::init(0))
static cl::opt< std::string > ClDebugFunc("asan-debug-func", cl::Hidden, cl::desc("Debug func"))
static cl::opt< bool > ClInstrumentReads("asan-instrument-reads", cl::desc("instrument read instructions"), cl::Hidden, cl::init(true))
Analysis containing CSE Info
Returns the sub type a function will return at a given Idx Should correspond to the result type of an ExtractValue instruction executed with just that one unsigned Idx
static cl::opt< int > ClMappingGranularity("memprof-mapping-granularity", cl::desc("granularity of memprof shadow mapping"), cl::Hidden, cl::init(DefaultMemGranularity))
constexpr char MemProfVersionCheckNamePrefix[]
static AllocationType addCallStack(CallStackTrie &AllocTrie, const AllocationInfo *AllocInfo)
static cl::opt< int > ClDebugMin("memprof-debug-min", cl::desc("Debug min inst"), cl::Hidden, cl::init(-1))
void createMemprofHistogramFlagVar(Module &M)
constexpr uint64_t MemProfEmscriptenCtorAndDtorPriority
static cl::opt< std::string > ClDebugFunc("memprof-debug-func", cl::Hidden, cl::desc("Debug func"))
constexpr char MemProfShadowMemoryDynamicAddress[]
constexpr uint64_t MemProfCtorAndDtorPriority
constexpr int LLVM_MEM_PROFILER_VERSION
static cl::opt< bool > ClUseCalls("memprof-use-callbacks", cl::desc("Use callbacks instead of inline instrumentation sequences."), cl::Hidden, cl::init(false))
static cl::opt< bool > ClInstrumentAtomics("memprof-instrument-atomics", cl::desc("instrument atomic instructions (rmw, cmpxchg)"), cl::Hidden, cl::init(true))
static cl::opt< bool > ClInsertVersionCheck("memprof-guard-against-version-mismatch", cl::desc("Guard against compiler/runtime version mismatch."), cl::Hidden, cl::init(true))
constexpr char MemProfInitName[]
constexpr char MemProfFilenameVar[]
static uint64_t computeStackId(GlobalValue::GUID Function, uint32_t LineOffset, uint32_t Column)
static cl::opt< bool > ClStack("memprof-instrument-stack", cl::desc("Instrument scalar stack variables"), cl::Hidden, cl::init(false))
static cl::opt< bool > ClHistogram("memprof-histogram", cl::desc("Collect access count histograms"), cl::Hidden, cl::init(false))
constexpr uint64_t DefaultMemGranularity
static cl::opt< bool > ClPrintMemProfMatchInfo("memprof-print-match-info", cl::desc("Print matching stats for each allocation " "context in this module's profiles"), cl::Hidden, cl::init(false))
constexpr uint64_t HistogramGranularity
constexpr uint64_t DefaultShadowScale
cl::opt< bool > MemProfReportHintedSizes
static cl::opt< std::string > ClMemoryAccessCallbackPrefix("memprof-memory-access-callback-prefix", cl::desc("Prefix for memory access callbacks"), cl::Hidden, cl::init("__memprof_"))
static bool isAllocationWithHotColdVariant(Function *Callee, const TargetLibraryInfo &TLI)
constexpr char MemProfModuleCtorName[]
static cl::opt< bool > ClInstrumentReads("memprof-instrument-reads", cl::desc("instrument read instructions"), cl::Hidden, cl::init(true))
static cl::opt< int > ClDebugMax("memprof-debug-max", cl::desc("Debug max inst"), cl::Hidden, cl::init(-1))
static cl::opt< bool > ClInstrumentWrites("memprof-instrument-writes", cl::desc("instrument write instructions"), cl::Hidden, cl::init(true))
static cl::opt< int > ClDebug("memprof-debug", cl::desc("debug"), cl::Hidden, cl::init(0))
static cl::opt< int > ClMappingScale("memprof-mapping-scale", cl::desc("scale of memprof shadow mapping"), cl::Hidden, cl::init(DefaultShadowScale))
static void addCallsiteMetadata(Instruction &I, std::vector< uint64_t > &InlinedCallStack, LLVMContext &Ctx)
static void readMemprof(Module &M, Function &F, IndexedInstrProfReader *MemProfReader, const TargetLibraryInfo &TLI, std::map< uint64_t, AllocMatchInfo > &FullStackIdToAllocMatchInfo)
static bool stackFrameIncludesInlinedCallStack(ArrayRef< Frame > ProfileCallStack, ArrayRef< uint64_t > InlinedCallStack, unsigned StartIndex=0)
static uint64_t computeFullStackId(const std::vector< memprof::Frame > &CallStack)
static cl::opt< bool > ClMemProfMatchHotColdNew("memprof-match-hot-cold-new", cl::desc("Match allocation profiles onto existing hot/cold operator new calls"), cl::Hidden, cl::init(false))
constexpr char MemProfHistogramFlagVar[]
cl::opt< bool > MemProfReportHintedSizes("memprof-report-hinted-sizes", cl::init(false), cl::Hidden, cl::desc("Report total allocation sizes of hinted allocations"))
Module.h This file contains the declarations for the Module class.
FunctionAnalysisManager FAM
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
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)
Defines the virtual file system interface vfs::FileSystem.
Class for arbitrary precision integers.
A container for analyses that lazily runs them and caches their results.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
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 Constant * getString(LLVMContext &Context, StringRef Initializer, bool AddNull=true)
This method constructs a CDS and initializes it with a text string.
This is an important base class in LLVM.
static 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.
Diagnostic information for the PGO profiler.
Base class for error info classes.
virtual std::string message() const
Return the error message as a string.
Lightweight error class with error context and mandatory checking.
A handy container for a FunctionType+Callee-pointer pair, which can be passed around as a single enti...
static FunctionType * get(Type *Result, ArrayRef< Type * > Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
void setComdat(Comdat *C)
void setLinkage(LinkageTypes LT)
GUID getGUID() const
Return a 64-bit global unique ID constructed from global value name (i.e.
@ ExternalLinkage
Externally visible function.
@ WeakAnyLinkage
Keep one copy of named function when linking (weak)
@ AvailableExternallyLinkage
Available for inspection, not emission.
HashResultTy< HasherT_ > final()
Forward to HasherT::final() if available.
Interface to help hash various types through a hasher type.
std::enable_if_t< hashbuilder_detail::IsHashableData< T >::value, HashBuilder & > add(T Value)
Implement hashing for hashable data types, e.g. integral or enum values.
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)
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.
CallInst * CreateCall(FunctionType *FTy, Value *Callee, ArrayRef< Value * > Args=std::nullopt, const Twine &Name="", MDNode *FPMathTag=nullptr)
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Reader for the indexed binary instrprof format.
static Expected< std::unique_ptr< IndexedInstrProfReader > > create(const Twine &Path, vfs::FileSystem &FS, const Twine &RemappingPath="")
Factory method to create an indexed reader.
An analysis over an "outer" IR unit that provides access to an analysis manager over an "inner" IR un...
instrprof_error get() const
std::string message() const override
Return the error message as a string.
A smart pointer to a reference-counted object that inherits from RefCountedBase or ThreadSafeRefCount...
This is an important class for using LLVM in a threaded context.
An instruction for reading from memory.
StringRef getString() const
This is the common base class for memset/memcpy/memmove.
PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
MemProfUsePass(std::string MemoryProfileFile, IntrusiveRefCntPtr< vfs::FileSystem > FS=nullptr)
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
A Module instance is used to store all the information related to an LLVM module.
static PointerType * get(Type *ElementType, unsigned AddressSpace)
This constructs a pointer to an object of the specified type 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.
StringRef - Represent a constant reference to a string, i.e.
constexpr bool empty() const
empty - Check if the string is empty.
Analysis pass providing the TargetLibraryInfo.
Provides information about what library functions are available for the current target.
bool getLibFunc(StringRef funcName, LibFunc &F) const
Searches for a particular function name.
Triple - Helper class for working with autoconf configuration names.
ObjectFormatType getObjectFormat() const
Get the object format for this triple.
bool isOSEmscripten() const
Tests whether the OS is Emscripten.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
The instances of the Type class are immutable: once they are created, they are never changed.
static IntegerType * getInt1Ty(LLVMContext &C)
unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
static IntegerType * getIntNTy(LLVMContext &C, unsigned N)
static IntegerType * getInt8Ty(LLVMContext &C)
LLVM Value Representation.
Type * getType() const
All values are typed, get the type of this value.
Class to build a trie of call stack contexts for a particular profiled allocation call,...
void addCallStack(AllocationType AllocType, ArrayRef< uint64_t > StackIds, uint64_t TotalSize=0)
Add a call stack context with the given allocation type to the Trie.
bool buildAndAttachMIBMetadata(CallBase *CI)
Build and attach the minimal necessary MIB metadata.
Helper class to iterate through stack ids in both metadata (memprof MIB and callsite) and the corresp...
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.
@ C
The default llvm calling convention, compatible with C.
initializer< Ty > init(const Ty &Val)
MDNode * buildCallstackMetadata(ArrayRef< uint64_t > CallStack, LLVMContext &Ctx)
Build callstack metadata from the provided list of call stack ids.
AllocationType getAllocType(uint64_t TotalLifetimeAccessDensity, uint64_t AllocCount, uint64_t TotalLifetime)
Return the allocation type for a given set of memory profile values.
std::string getAllocTypeAttributeString(AllocationType Type)
Returns the string to use in attributes with the given type.
IntrusiveRefCntPtr< FileSystem > getRealFileSystem()
Gets an vfs::FileSystem for the 'real' file system, as seen by the operating system.
This is an optimization pass for GlobalISel generic memory operations.
void handleAllErrors(Error E, HandlerTs &&... Handlers)
Behaves the same as handleErrors, except that by contract all errors must be handled by the given han...
const Value * getUnderlyingObject(const Value *V, unsigned MaxLookup=6)
This method strips off any GEP address adjustments, pointer casts or llvm.threadlocal....
cl::opt< bool > PGOWarnMissing
std::string getInstrProfSectionName(InstrProfSectKind IPSK, Triple::ObjectFormatType OF, bool AddSegmentInfo=true)
Return the name of the profile section corresponding to IPSK.
std::array< uint8_t, NumBytes > BLAKE3Result
The constant LLVM_BLAKE3_OUT_LEN provides the default output length, 32 bytes, which is recommended f...
FunctionCallee declareSanitizerInitFunction(Module &M, StringRef InitName, ArrayRef< Type * > InitArgTypes, bool Weak=false)
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.
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
cl::opt< bool > NoPGOWarnMismatch
raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
void appendToCompilerUsed(Module &M, ArrayRef< GlobalValue * > Values)
Adds global values to the llvm.compiler.used list.
void createProfileFileNameVar(Module &M, StringRef InstrProfileOutput)
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.
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 ...
cl::opt< bool > NoPGOWarnMismatchComdatWeak
Summary of memprof metadata on allocations.
GlobalValue::GUID Function