LLVM 19.0.0git
MemProfiler.cpp
Go to the documentation of this file.
1//===- MemProfiler.cpp - memory allocation and access profiler ------------===//
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 file is a part of MemProfiler. Memory accesses are instrumented
10// to increment the access count held in a shadow memory location, or
11// alternatively to call into the runtime. Memory intrinsic calls (memmove,
12// memcpy, memset) are changed to call the memory profiling runtime version
13// instead.
14//
15//===----------------------------------------------------------------------===//
16
19#include "llvm/ADT/Statistic.h"
20#include "llvm/ADT/StringRef.h"
24#include "llvm/IR/Constant.h"
25#include "llvm/IR/DataLayout.h"
27#include "llvm/IR/Function.h"
28#include "llvm/IR/GlobalValue.h"
29#include "llvm/IR/IRBuilder.h"
30#include "llvm/IR/Instruction.h"
32#include "llvm/IR/Module.h"
33#include "llvm/IR/Type.h"
34#include "llvm/IR/Value.h"
37#include "llvm/Support/BLAKE3.h"
39#include "llvm/Support/Debug.h"
45#include <map>
46#include <set>
47
48using namespace llvm;
49using namespace llvm::memprof;
50
51#define DEBUG_TYPE "memprof"
52
53namespace llvm {
57} // namespace llvm
58
59constexpr int LLVM_MEM_PROFILER_VERSION = 1;
60
61// Size of memory mapped to a single shadow location.
63
64// Scale from granularity down to shadow size.
66
67constexpr char MemProfModuleCtorName[] = "memprof.module_ctor";
69// On Emscripten, the system needs more than one priorities for constructors.
71constexpr char MemProfInitName[] = "__memprof_init";
73 "__memprof_version_mismatch_check_v";
74
76 "__memprof_shadow_memory_dynamic_address";
77
78constexpr char MemProfFilenameVar[] = "__memprof_profile_filename";
79
80constexpr char MemProfHistogramFlagVar[] = "__memprof_histogram";
81
82// Command-line flags.
83
85 "memprof-guard-against-version-mismatch",
86 cl::desc("Guard against compiler/runtime version mismatch."), cl::Hidden,
87 cl::init(true));
88
89// This flag may need to be replaced with -f[no-]memprof-reads.
90static cl::opt<bool> ClInstrumentReads("memprof-instrument-reads",
91 cl::desc("instrument read instructions"),
92 cl::Hidden, cl::init(true));
93
94static cl::opt<bool>
95 ClInstrumentWrites("memprof-instrument-writes",
96 cl::desc("instrument write instructions"), cl::Hidden,
97 cl::init(true));
98
100 "memprof-instrument-atomics",
101 cl::desc("instrument atomic instructions (rmw, cmpxchg)"), cl::Hidden,
102 cl::init(true));
103
105 "memprof-use-callbacks",
106 cl::desc("Use callbacks instead of inline instrumentation sequences."),
107 cl::Hidden, cl::init(false));
108
110 ClMemoryAccessCallbackPrefix("memprof-memory-access-callback-prefix",
111 cl::desc("Prefix for memory access callbacks"),
112 cl::Hidden, cl::init("__memprof_"));
113
114// These flags allow to change the shadow mapping.
115// The shadow mapping looks like
116// Shadow = ((Mem & mask) >> scale) + offset
117
118static cl::opt<int> ClMappingScale("memprof-mapping-scale",
119 cl::desc("scale of memprof shadow mapping"),
121
122static cl::opt<int>
123 ClMappingGranularity("memprof-mapping-granularity",
124 cl::desc("granularity of memprof shadow mapping"),
126
127static cl::opt<bool> ClStack("memprof-instrument-stack",
128 cl::desc("Instrument scalar stack variables"),
129 cl::Hidden, cl::init(false));
130
131// Debug flags.
132
133static cl::opt<int> ClDebug("memprof-debug", cl::desc("debug"), cl::Hidden,
134 cl::init(0));
135
136static cl::opt<std::string> ClDebugFunc("memprof-debug-func", cl::Hidden,
137 cl::desc("Debug func"));
138
139static cl::opt<int> ClDebugMin("memprof-debug-min", cl::desc("Debug min inst"),
140 cl::Hidden, cl::init(-1));
141
142static cl::opt<int> ClDebugMax("memprof-debug-max", cl::desc("Debug max inst"),
143 cl::Hidden, cl::init(-1));
144
145// By default disable matching of allocation profiles onto operator new that
146// already explicitly pass a hot/cold hint, since we don't currently
147// override these hints anyway.
149 "memprof-match-hot-cold-new",
150 cl::desc(
151 "Match allocation profiles onto existing hot/cold operator new calls"),
152 cl::Hidden, cl::init(false));
153
154static cl::opt<bool> ClHistogram("memprof-histogram",
155 cl::desc("Collect access count histograms"),
156 cl::Hidden, cl::init(false));
157
158static cl::opt<bool>
159 ClPrintMemProfMatchInfo("memprof-print-match-info",
160 cl::desc("Print matching stats for each allocation "
161 "context in this module's profiles"),
162 cl::Hidden, cl::init(false));
163
164// Instrumentation statistics
165STATISTIC(NumInstrumentedReads, "Number of instrumented reads");
166STATISTIC(NumInstrumentedWrites, "Number of instrumented writes");
167STATISTIC(NumSkippedStackReads, "Number of non-instrumented stack reads");
168STATISTIC(NumSkippedStackWrites, "Number of non-instrumented stack writes");
169
170// Matching statistics
171STATISTIC(NumOfMemProfMissing, "Number of functions without memory profile.");
172STATISTIC(NumOfMemProfMismatch,
173 "Number of functions having mismatched memory profile hash.");
174STATISTIC(NumOfMemProfFunc, "Number of functions having valid memory profile.");
175STATISTIC(NumOfMemProfAllocContextProfiles,
176 "Number of alloc contexts in memory profile.");
177STATISTIC(NumOfMemProfCallSiteProfiles,
178 "Number of callsites in memory profile.");
179STATISTIC(NumOfMemProfMatchedAllocContexts,
180 "Number of matched memory profile alloc contexts.");
181STATISTIC(NumOfMemProfMatchedAllocs,
182 "Number of matched memory profile allocs.");
183STATISTIC(NumOfMemProfMatchedCallSites,
184 "Number of matched memory profile callsites.");
185
186namespace {
187
188/// This struct defines the shadow mapping using the rule:
189/// shadow = ((mem & mask) >> Scale) ADD DynamicShadowOffset.
190struct ShadowMapping {
191 ShadowMapping() {
192 Scale = ClMappingScale;
193 Granularity = ClMappingGranularity;
194 Mask = ~(Granularity - 1);
195 }
196
197 int Scale;
198 int Granularity;
199 uint64_t Mask; // Computed as ~(Granularity-1)
200};
201
202static uint64_t getCtorAndDtorPriority(Triple &TargetTriple) {
205}
206
207struct InterestingMemoryAccess {
208 Value *Addr = nullptr;
209 bool IsWrite;
210 Type *AccessTy;
211 Value *MaybeMask = nullptr;
212};
213
214/// Instrument the code in module to profile memory accesses.
215class MemProfiler {
216public:
217 MemProfiler(Module &M) {
218 C = &(M.getContext());
219 LongSize = M.getDataLayout().getPointerSizeInBits();
220 IntptrTy = Type::getIntNTy(*C, LongSize);
221 PtrTy = PointerType::getUnqual(*C);
222 }
223
224 /// If it is an interesting memory access, populate information
225 /// about the access and return a InterestingMemoryAccess struct.
226 /// Otherwise return std::nullopt.
227 std::optional<InterestingMemoryAccess>
228 isInterestingMemoryAccess(Instruction *I) const;
229
230 void instrumentMop(Instruction *I, const DataLayout &DL,
231 InterestingMemoryAccess &Access);
232 void instrumentAddress(Instruction *OrigIns, Instruction *InsertBefore,
233 Value *Addr, bool IsWrite);
234 void instrumentMaskedLoadOrStore(const DataLayout &DL, Value *Mask,
235 Instruction *I, Value *Addr, Type *AccessTy,
236 bool IsWrite);
237 void instrumentMemIntrinsic(MemIntrinsic *MI);
238 Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
239 bool instrumentFunction(Function &F);
240 bool maybeInsertMemProfInitAtFunctionEntry(Function &F);
241 bool insertDynamicShadowAtFunctionEntry(Function &F);
242
243private:
244 void initializeCallbacks(Module &M);
245
246 LLVMContext *C;
247 int LongSize;
248 Type *IntptrTy;
249 PointerType *PtrTy;
250 ShadowMapping Mapping;
251
252 // These arrays is indexed by AccessIsWrite
253 FunctionCallee MemProfMemoryAccessCallback[2];
254
255 FunctionCallee MemProfMemmove, MemProfMemcpy, MemProfMemset;
256 Value *DynamicShadowOffset = nullptr;
257};
258
259class ModuleMemProfiler {
260public:
261 ModuleMemProfiler(Module &M) { TargetTriple = Triple(M.getTargetTriple()); }
262
263 bool instrumentModule(Module &);
264
265private:
266 Triple TargetTriple;
267 ShadowMapping Mapping;
268 Function *MemProfCtorFunction = nullptr;
269};
270
271} // end anonymous namespace
272
274
277 Module &M = *F.getParent();
278 MemProfiler Profiler(M);
279 if (Profiler.instrumentFunction(F))
281 return PreservedAnalyses::all();
282}
283
285
288
290 "Cannot use -memprof-histogram without Callbacks. Set "
291 "memprof-use-callbacks");
292
293 ModuleMemProfiler Profiler(M);
294 if (Profiler.instrumentModule(M))
296 return PreservedAnalyses::all();
297}
298
299Value *MemProfiler::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
300 // (Shadow & mask) >> scale
301 Shadow = IRB.CreateAnd(Shadow, Mapping.Mask);
302 Shadow = IRB.CreateLShr(Shadow, Mapping.Scale);
303 // (Shadow >> scale) | offset
304 assert(DynamicShadowOffset);
305 return IRB.CreateAdd(Shadow, DynamicShadowOffset);
306}
307
308// Instrument memset/memmove/memcpy
309void MemProfiler::instrumentMemIntrinsic(MemIntrinsic *MI) {
310 IRBuilder<> IRB(MI);
311 if (isa<MemTransferInst>(MI)) {
312 IRB.CreateCall(isa<MemMoveInst>(MI) ? MemProfMemmove : MemProfMemcpy,
313 {MI->getOperand(0), MI->getOperand(1),
314 IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false)});
315 } else if (isa<MemSetInst>(MI)) {
316 IRB.CreateCall(
317 MemProfMemset,
318 {MI->getOperand(0),
319 IRB.CreateIntCast(MI->getOperand(1), IRB.getInt32Ty(), false),
320 IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false)});
321 }
322 MI->eraseFromParent();
323}
324
325std::optional<InterestingMemoryAccess>
326MemProfiler::isInterestingMemoryAccess(Instruction *I) const {
327 // Do not instrument the load fetching the dynamic shadow address.
328 if (DynamicShadowOffset == I)
329 return std::nullopt;
330
331 InterestingMemoryAccess Access;
332
333 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
335 return std::nullopt;
336 Access.IsWrite = false;
337 Access.AccessTy = LI->getType();
338 Access.Addr = LI->getPointerOperand();
339 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
341 return std::nullopt;
342 Access.IsWrite = true;
343 Access.AccessTy = SI->getValueOperand()->getType();
344 Access.Addr = SI->getPointerOperand();
345 } else if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
347 return std::nullopt;
348 Access.IsWrite = true;
349 Access.AccessTy = RMW->getValOperand()->getType();
350 Access.Addr = RMW->getPointerOperand();
351 } else if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
353 return std::nullopt;
354 Access.IsWrite = true;
355 Access.AccessTy = XCHG->getCompareOperand()->getType();
356 Access.Addr = XCHG->getPointerOperand();
357 } else if (auto *CI = dyn_cast<CallInst>(I)) {
358 auto *F = CI->getCalledFunction();
359 if (F && (F->getIntrinsicID() == Intrinsic::masked_load ||
360 F->getIntrinsicID() == Intrinsic::masked_store)) {
361 unsigned OpOffset = 0;
362 if (F->getIntrinsicID() == Intrinsic::masked_store) {
364 return std::nullopt;
365 // Masked store has an initial operand for the value.
366 OpOffset = 1;
367 Access.AccessTy = CI->getArgOperand(0)->getType();
368 Access.IsWrite = true;
369 } else {
371 return std::nullopt;
372 Access.AccessTy = CI->getType();
373 Access.IsWrite = false;
374 }
375
376 auto *BasePtr = CI->getOperand(0 + OpOffset);
377 Access.MaybeMask = CI->getOperand(2 + OpOffset);
378 Access.Addr = BasePtr;
379 }
380 }
381
382 if (!Access.Addr)
383 return std::nullopt;
384
385 // Do not instrument accesses from different address spaces; we cannot deal
386 // with them.
387 Type *PtrTy = cast<PointerType>(Access.Addr->getType()->getScalarType());
388 if (PtrTy->getPointerAddressSpace() != 0)
389 return std::nullopt;
390
391 // Ignore swifterror addresses.
392 // swifterror memory addresses are mem2reg promoted by instruction
393 // selection. As such they cannot have regular uses like an instrumentation
394 // function and it makes no sense to track them as memory.
395 if (Access.Addr->isSwiftError())
396 return std::nullopt;
397
398 // Peel off GEPs and BitCasts.
399 auto *Addr = Access.Addr->stripInBoundsOffsets();
400
401 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Addr)) {
402 // Do not instrument PGO counter updates.
403 if (GV->hasSection()) {
404 StringRef SectionName = GV->getSection();
405 // Check if the global is in the PGO counters section.
406 auto OF = Triple(I->getModule()->getTargetTriple()).getObjectFormat();
407 if (SectionName.ends_with(
408 getInstrProfSectionName(IPSK_cnts, OF, /*AddSegmentInfo=*/false)))
409 return std::nullopt;
410 }
411
412 // Do not instrument accesses to LLVM internal variables.
413 if (GV->getName().starts_with("__llvm"))
414 return std::nullopt;
415 }
416
417 return Access;
418}
419
420void MemProfiler::instrumentMaskedLoadOrStore(const DataLayout &DL, Value *Mask,
422 Type *AccessTy, bool IsWrite) {
423 auto *VTy = cast<FixedVectorType>(AccessTy);
424 unsigned Num = VTy->getNumElements();
425 auto *Zero = ConstantInt::get(IntptrTy, 0);
426 for (unsigned Idx = 0; Idx < Num; ++Idx) {
427 Value *InstrumentedAddress = nullptr;
428 Instruction *InsertBefore = I;
429 if (auto *Vector = dyn_cast<ConstantVector>(Mask)) {
430 // dyn_cast as we might get UndefValue
431 if (auto *Masked = dyn_cast<ConstantInt>(Vector->getOperand(Idx))) {
432 if (Masked->isZero())
433 // Mask is constant false, so no instrumentation needed.
434 continue;
435 // If we have a true or undef value, fall through to instrumentAddress.
436 // with InsertBefore == I
437 }
438 } else {
439 IRBuilder<> IRB(I);
440 Value *MaskElem = IRB.CreateExtractElement(Mask, Idx);
441 Instruction *ThenTerm = SplitBlockAndInsertIfThen(MaskElem, I, false);
442 InsertBefore = ThenTerm;
443 }
444
445 IRBuilder<> IRB(InsertBefore);
446 InstrumentedAddress =
447 IRB.CreateGEP(VTy, Addr, {Zero, ConstantInt::get(IntptrTy, Idx)});
448 instrumentAddress(I, InsertBefore, InstrumentedAddress, IsWrite);
449 }
450}
451
452void MemProfiler::instrumentMop(Instruction *I, const DataLayout &DL,
453 InterestingMemoryAccess &Access) {
454 // Skip instrumentation of stack accesses unless requested.
455 if (!ClStack && isa<AllocaInst>(getUnderlyingObject(Access.Addr))) {
456 if (Access.IsWrite)
457 ++NumSkippedStackWrites;
458 else
459 ++NumSkippedStackReads;
460 return;
461 }
462
463 if (Access.IsWrite)
464 NumInstrumentedWrites++;
465 else
466 NumInstrumentedReads++;
467
468 if (Access.MaybeMask) {
469 instrumentMaskedLoadOrStore(DL, Access.MaybeMask, I, Access.Addr,
470 Access.AccessTy, Access.IsWrite);
471 } else {
472 // Since the access counts will be accumulated across the entire allocation,
473 // we only update the shadow access count for the first location and thus
474 // don't need to worry about alignment and type size.
475 instrumentAddress(I, I, Access.Addr, Access.IsWrite);
476 }
477}
478
479void MemProfiler::instrumentAddress(Instruction *OrigIns,
480 Instruction *InsertBefore, Value *Addr,
481 bool IsWrite) {
482 IRBuilder<> IRB(InsertBefore);
483 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
484
485 if (ClUseCalls) {
486 IRB.CreateCall(MemProfMemoryAccessCallback[IsWrite], AddrLong);
487 return;
488 }
489
490 // Create an inline sequence to compute shadow location, and increment the
491 // value by one.
492 Type *ShadowTy = Type::getInt64Ty(*C);
493 Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
494 Value *ShadowPtr = memToShadow(AddrLong, IRB);
495 Value *ShadowAddr = IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy);
496 Value *ShadowValue = IRB.CreateLoad(ShadowTy, ShadowAddr);
497 Value *Inc = ConstantInt::get(Type::getInt64Ty(*C), 1);
498 ShadowValue = IRB.CreateAdd(ShadowValue, Inc);
499 IRB.CreateStore(ShadowValue, ShadowAddr);
500}
501
502// Create the variable for the profile file name.
504 const MDString *MemProfFilename =
505 dyn_cast_or_null<MDString>(M.getModuleFlag("MemProfProfileFilename"));
506 if (!MemProfFilename)
507 return;
508 assert(!MemProfFilename->getString().empty() &&
509 "Unexpected MemProfProfileFilename metadata with empty string");
510 Constant *ProfileNameConst = ConstantDataArray::getString(
511 M.getContext(), MemProfFilename->getString(), true);
512 GlobalVariable *ProfileNameVar = new GlobalVariable(
513 M, ProfileNameConst->getType(), /*isConstant=*/true,
515 Triple TT(M.getTargetTriple());
516 if (TT.supportsCOMDAT()) {
518 ProfileNameVar->setComdat(M.getOrInsertComdat(MemProfFilenameVar));
519 }
520}
521
522// Set MemprofHistogramFlag as a Global veriable in IR. This makes it accessible
523// to the runtime, changing shadow count behavior.
525 const StringRef VarName(MemProfHistogramFlagVar);
526 Type *IntTy1 = Type::getInt1Ty(M.getContext());
527 auto MemprofHistogramFlag = new GlobalVariable(
528 M, IntTy1, true, GlobalValue::WeakAnyLinkage,
529 Constant::getIntegerValue(IntTy1, APInt(1, ClHistogram)), VarName);
530 Triple TT(M.getTargetTriple());
531 if (TT.supportsCOMDAT()) {
532 MemprofHistogramFlag->setLinkage(GlobalValue::ExternalLinkage);
533 MemprofHistogramFlag->setComdat(M.getOrInsertComdat(VarName));
534 }
535 appendToCompilerUsed(M, MemprofHistogramFlag);
536}
537
538bool ModuleMemProfiler::instrumentModule(Module &M) {
539
540 // Create a module constructor.
541 std::string MemProfVersion = std::to_string(LLVM_MEM_PROFILER_VERSION);
542 std::string VersionCheckName =
544 : "";
545 std::tie(MemProfCtorFunction, std::ignore) =
547 MemProfInitName, /*InitArgTypes=*/{},
548 /*InitArgs=*/{}, VersionCheckName);
549
550 const uint64_t Priority = getCtorAndDtorPriority(TargetTriple);
551 appendToGlobalCtors(M, MemProfCtorFunction, Priority);
552
554
556
557 return true;
558}
559
560void MemProfiler::initializeCallbacks(Module &M) {
561 IRBuilder<> IRB(*C);
562
563 for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
564 const std::string TypeStr = AccessIsWrite ? "store" : "load";
565 const std::string HistPrefix = ClHistogram ? "hist_" : "";
566
567 SmallVector<Type *, 2> Args1{1, IntptrTy};
568 MemProfMemoryAccessCallback[AccessIsWrite] = M.getOrInsertFunction(
569 ClMemoryAccessCallbackPrefix + HistPrefix + TypeStr,
570 FunctionType::get(IRB.getVoidTy(), Args1, false));
571 }
572 MemProfMemmove = M.getOrInsertFunction(
573 ClMemoryAccessCallbackPrefix + "memmove", PtrTy, PtrTy, PtrTy, IntptrTy);
574 MemProfMemcpy = M.getOrInsertFunction(ClMemoryAccessCallbackPrefix + "memcpy",
575 PtrTy, PtrTy, PtrTy, IntptrTy);
576 MemProfMemset =
577 M.getOrInsertFunction(ClMemoryAccessCallbackPrefix + "memset", PtrTy,
578 PtrTy, IRB.getInt32Ty(), IntptrTy);
579}
580
581bool MemProfiler::maybeInsertMemProfInitAtFunctionEntry(Function &F) {
582 // For each NSObject descendant having a +load method, this method is invoked
583 // by the ObjC runtime before any of the static constructors is called.
584 // Therefore we need to instrument such methods with a call to __memprof_init
585 // at the beginning in order to initialize our runtime before any access to
586 // the shadow memory.
587 // We cannot just ignore these methods, because they may call other
588 // instrumented functions.
589 if (F.getName().contains(" load]")) {
590 FunctionCallee MemProfInitFunction =
592 IRBuilder<> IRB(&F.front(), F.front().begin());
593 IRB.CreateCall(MemProfInitFunction, {});
594 return true;
595 }
596 return false;
597}
598
599bool MemProfiler::insertDynamicShadowAtFunctionEntry(Function &F) {
600 IRBuilder<> IRB(&F.front().front());
601 Value *GlobalDynamicAddress = F.getParent()->getOrInsertGlobal(
603 if (F.getParent()->getPICLevel() == PICLevel::NotPIC)
604 cast<GlobalVariable>(GlobalDynamicAddress)->setDSOLocal(true);
605 DynamicShadowOffset = IRB.CreateLoad(IntptrTy, GlobalDynamicAddress);
606 return true;
607}
608
609bool MemProfiler::instrumentFunction(Function &F) {
610 if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage)
611 return false;
612 if (ClDebugFunc == F.getName())
613 return false;
614 if (F.getName().starts_with("__memprof_"))
615 return false;
616
617 bool FunctionModified = false;
618
619 // If needed, insert __memprof_init.
620 // This function needs to be called even if the function body is not
621 // instrumented.
622 if (maybeInsertMemProfInitAtFunctionEntry(F))
623 FunctionModified = true;
624
625 LLVM_DEBUG(dbgs() << "MEMPROF instrumenting:\n" << F << "\n");
626
627 initializeCallbacks(*F.getParent());
628
630
631 // Fill the set of memory operations to instrument.
632 for (auto &BB : F) {
633 for (auto &Inst : BB) {
634 if (isInterestingMemoryAccess(&Inst) || isa<MemIntrinsic>(Inst))
635 ToInstrument.push_back(&Inst);
636 }
637 }
638
639 if (ToInstrument.empty()) {
640 LLVM_DEBUG(dbgs() << "MEMPROF done instrumenting: " << FunctionModified
641 << " " << F << "\n");
642
643 return FunctionModified;
644 }
645
646 FunctionModified |= insertDynamicShadowAtFunctionEntry(F);
647
648 int NumInstrumented = 0;
649 for (auto *Inst : ToInstrument) {
650 if (ClDebugMin < 0 || ClDebugMax < 0 ||
651 (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
652 std::optional<InterestingMemoryAccess> Access =
653 isInterestingMemoryAccess(Inst);
654 if (Access)
655 instrumentMop(Inst, F.getDataLayout(), *Access);
656 else
657 instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
658 }
659 NumInstrumented++;
660 }
661
662 if (NumInstrumented > 0)
663 FunctionModified = true;
664
665 LLVM_DEBUG(dbgs() << "MEMPROF done instrumenting: " << FunctionModified << " "
666 << F << "\n");
667
668 return FunctionModified;
669}
670
672 std::vector<uint64_t> &InlinedCallStack,
673 LLVMContext &Ctx) {
674 I.setMetadata(LLVMContext::MD_callsite,
675 buildCallstackMetadata(InlinedCallStack, Ctx));
676}
677
679 uint32_t Column) {
682 HashBuilder.add(Function, LineOffset, Column);
684 uint64_t Id;
685 std::memcpy(&Id, Hash.data(), sizeof(Hash));
686 return Id;
687}
688
691}
692
693// Helper to generate a single hash id for a given callstack, used for emitting
694// matching statistics and useful for uniquing such statistics across modules.
695static uint64_t
696computeFullStackId(const std::vector<memprof::Frame> &CallStack) {
699 for (auto &F : CallStack)
700 HashBuilder.add(F.Function, F.LineOffset, F.Column);
702 uint64_t Id;
703 std::memcpy(&Id, Hash.data(), sizeof(Hash));
704 return Id;
705}
706
708 const AllocationInfo *AllocInfo) {
709 SmallVector<uint64_t> StackIds;
710 for (const auto &StackFrame : AllocInfo->CallStack)
711 StackIds.push_back(computeStackId(StackFrame));
712 auto AllocType = getAllocType(AllocInfo->Info.getTotalLifetimeAccessDensity(),
713 AllocInfo->Info.getAllocCount(),
714 AllocInfo->Info.getTotalLifetime());
715 AllocTrie.addCallStack(AllocType, StackIds);
716 return AllocType;
717}
718
719// Helper to compare the InlinedCallStack computed from an instruction's debug
720// info to a list of Frames from profile data (either the allocation data or a
721// callsite). For callsites, the StartIndex to use in the Frame array may be
722// non-zero.
723static bool
725 ArrayRef<uint64_t> InlinedCallStack,
726 unsigned StartIndex = 0) {
727 auto StackFrame = ProfileCallStack.begin() + StartIndex;
728 auto InlCallStackIter = InlinedCallStack.begin();
729 for (; StackFrame != ProfileCallStack.end() &&
730 InlCallStackIter != InlinedCallStack.end();
731 ++StackFrame, ++InlCallStackIter) {
732 uint64_t StackId = computeStackId(*StackFrame);
733 if (StackId != *InlCallStackIter)
734 return false;
735 }
736 // Return true if we found and matched all stack ids from the call
737 // instruction.
738 return InlCallStackIter == InlinedCallStack.end();
739}
740
742 const TargetLibraryInfo &TLI) {
743 if (!Callee)
744 return false;
745 LibFunc Func;
746 if (!TLI.getLibFunc(*Callee, Func))
747 return false;
748 switch (Func) {
749 case LibFunc_Znwm:
750 case LibFunc_ZnwmRKSt9nothrow_t:
751 case LibFunc_ZnwmSt11align_val_t:
752 case LibFunc_ZnwmSt11align_val_tRKSt9nothrow_t:
753 case LibFunc_Znam:
754 case LibFunc_ZnamRKSt9nothrow_t:
755 case LibFunc_ZnamSt11align_val_t:
756 case LibFunc_ZnamSt11align_val_tRKSt9nothrow_t:
757 return true;
758 case LibFunc_Znwm12__hot_cold_t:
759 case LibFunc_ZnwmRKSt9nothrow_t12__hot_cold_t:
760 case LibFunc_ZnwmSt11align_val_t12__hot_cold_t:
761 case LibFunc_ZnwmSt11align_val_tRKSt9nothrow_t12__hot_cold_t:
762 case LibFunc_Znam12__hot_cold_t:
763 case LibFunc_ZnamRKSt9nothrow_t12__hot_cold_t:
764 case LibFunc_ZnamSt11align_val_t12__hot_cold_t:
765 case LibFunc_ZnamSt11align_val_tRKSt9nothrow_t12__hot_cold_t:
767 default:
768 return false;
769 }
770}
771
773 uint64_t TotalSize = 0;
774 AllocationType AllocType = AllocationType::None;
775 bool Matched = false;
776};
777
778static void
780 const TargetLibraryInfo &TLI,
781 std::map<uint64_t, AllocMatchInfo> &FullStackIdToAllocMatchInfo) {
782 auto &Ctx = M.getContext();
783 // Previously we used getIRPGOFuncName() here. If F is local linkage,
784 // getIRPGOFuncName() returns FuncName with prefix 'FileName;'. But
785 // llvm-profdata uses FuncName in dwarf to create GUID which doesn't
786 // contain FileName's prefix. It caused local linkage function can't
787 // find MemProfRecord. So we use getName() now.
788 // 'unique-internal-linkage-names' can make MemProf work better for local
789 // linkage function.
790 auto FuncName = F.getName();
791 auto FuncGUID = Function::getGUID(FuncName);
792 std::optional<memprof::MemProfRecord> MemProfRec;
793 auto Err = MemProfReader->getMemProfRecord(FuncGUID).moveInto(MemProfRec);
794 if (Err) {
795 handleAllErrors(std::move(Err), [&](const InstrProfError &IPE) {
796 auto Err = IPE.get();
797 bool SkipWarning = false;
798 LLVM_DEBUG(dbgs() << "Error in reading profile for Func " << FuncName
799 << ": ");
801 NumOfMemProfMissing++;
802 SkipWarning = !PGOWarnMissing;
803 LLVM_DEBUG(dbgs() << "unknown function");
804 } else if (Err == instrprof_error::hash_mismatch) {
805 NumOfMemProfMismatch++;
806 SkipWarning =
809 (F.hasComdat() ||
811 LLVM_DEBUG(dbgs() << "hash mismatch (skip=" << SkipWarning << ")");
812 }
813
814 if (SkipWarning)
815 return;
816
817 std::string Msg = (IPE.message() + Twine(" ") + F.getName().str() +
818 Twine(" Hash = ") + std::to_string(FuncGUID))
819 .str();
820
821 Ctx.diagnose(
822 DiagnosticInfoPGOProfile(M.getName().data(), Msg, DS_Warning));
823 });
824 return;
825 }
826
827 NumOfMemProfFunc++;
828
829 // Detect if there are non-zero column numbers in the profile. If not,
830 // treat all column numbers as 0 when matching (i.e. ignore any non-zero
831 // columns in the IR). The profiled binary might have been built with
832 // column numbers disabled, for example.
833 bool ProfileHasColumns = false;
834
835 // Build maps of the location hash to all profile data with that leaf location
836 // (allocation info and the callsites).
837 std::map<uint64_t, std::set<const AllocationInfo *>> LocHashToAllocInfo;
838 // For the callsites we need to record the index of the associated frame in
839 // the frame array (see comments below where the map entries are added).
840 std::map<uint64_t, std::set<std::pair<const std::vector<Frame> *, unsigned>>>
841 LocHashToCallSites;
842 for (auto &AI : MemProfRec->AllocSites) {
843 NumOfMemProfAllocContextProfiles++;
844 // Associate the allocation info with the leaf frame. The later matching
845 // code will match any inlined call sequences in the IR with a longer prefix
846 // of call stack frames.
847 uint64_t StackId = computeStackId(AI.CallStack[0]);
848 LocHashToAllocInfo[StackId].insert(&AI);
849 ProfileHasColumns |= AI.CallStack[0].Column;
850 }
851 for (auto &CS : MemProfRec->CallSites) {
852 NumOfMemProfCallSiteProfiles++;
853 // Need to record all frames from leaf up to and including this function,
854 // as any of these may or may not have been inlined at this point.
855 unsigned Idx = 0;
856 for (auto &StackFrame : CS) {
857 uint64_t StackId = computeStackId(StackFrame);
858 LocHashToCallSites[StackId].insert(std::make_pair(&CS, Idx++));
859 ProfileHasColumns |= StackFrame.Column;
860 // Once we find this function, we can stop recording.
861 if (StackFrame.Function == FuncGUID)
862 break;
863 }
864 assert(Idx <= CS.size() && CS[Idx - 1].Function == FuncGUID);
865 }
866
867 auto GetOffset = [](const DILocation *DIL) {
868 return (DIL->getLine() - DIL->getScope()->getSubprogram()->getLine()) &
869 0xffff;
870 };
871
872 // Now walk the instructions, looking up the associated profile data using
873 // debug locations.
874 for (auto &BB : F) {
875 for (auto &I : BB) {
876 if (I.isDebugOrPseudoInst())
877 continue;
878 // We are only interested in calls (allocation or interior call stack
879 // context calls).
880 auto *CI = dyn_cast<CallBase>(&I);
881 if (!CI)
882 continue;
883 auto *CalledFunction = CI->getCalledFunction();
884 if (CalledFunction && CalledFunction->isIntrinsic())
885 continue;
886 // List of call stack ids computed from the location hashes on debug
887 // locations (leaf to inlined at root).
888 std::vector<uint64_t> InlinedCallStack;
889 // Was the leaf location found in one of the profile maps?
890 bool LeafFound = false;
891 // If leaf was found in a map, iterators pointing to its location in both
892 // of the maps. It might exist in neither, one, or both (the latter case
893 // can happen because we don't currently have discriminators to
894 // distinguish the case when a single line/col maps to both an allocation
895 // and another callsite).
896 std::map<uint64_t, std::set<const AllocationInfo *>>::iterator
897 AllocInfoIter;
898 std::map<uint64_t, std::set<std::pair<const std::vector<Frame> *,
899 unsigned>>>::iterator CallSitesIter;
900 for (const DILocation *DIL = I.getDebugLoc(); DIL != nullptr;
901 DIL = DIL->getInlinedAt()) {
902 // Use C++ linkage name if possible. Need to compile with
903 // -fdebug-info-for-profiling to get linkage name.
904 StringRef Name = DIL->getScope()->getSubprogram()->getLinkageName();
905 if (Name.empty())
906 Name = DIL->getScope()->getSubprogram()->getName();
907 auto CalleeGUID = Function::getGUID(Name);
908 auto StackId = computeStackId(CalleeGUID, GetOffset(DIL),
909 ProfileHasColumns ? DIL->getColumn() : 0);
910 // Check if we have found the profile's leaf frame. If yes, collect
911 // the rest of the call's inlined context starting here. If not, see if
912 // we find a match further up the inlined context (in case the profile
913 // was missing debug frames at the leaf).
914 if (!LeafFound) {
915 AllocInfoIter = LocHashToAllocInfo.find(StackId);
916 CallSitesIter = LocHashToCallSites.find(StackId);
917 if (AllocInfoIter != LocHashToAllocInfo.end() ||
918 CallSitesIter != LocHashToCallSites.end())
919 LeafFound = true;
920 }
921 if (LeafFound)
922 InlinedCallStack.push_back(StackId);
923 }
924 // If leaf not in either of the maps, skip inst.
925 if (!LeafFound)
926 continue;
927
928 // First add !memprof metadata from allocation info, if we found the
929 // instruction's leaf location in that map, and if the rest of the
930 // instruction's locations match the prefix Frame locations on an
931 // allocation context with the same leaf.
932 if (AllocInfoIter != LocHashToAllocInfo.end()) {
933 // Only consider allocations via new, to reduce unnecessary metadata,
934 // since those are the only allocations that will be targeted initially.
935 if (!isNewWithHotColdVariant(CI->getCalledFunction(), TLI))
936 continue;
937 // We may match this instruction's location list to multiple MIB
938 // contexts. Add them to a Trie specialized for trimming the contexts to
939 // the minimal needed to disambiguate contexts with unique behavior.
940 CallStackTrie AllocTrie;
941 for (auto *AllocInfo : AllocInfoIter->second) {
942 // Check the full inlined call stack against this one.
943 // If we found and thus matched all frames on the call, include
944 // this MIB.
946 InlinedCallStack)) {
947 NumOfMemProfMatchedAllocContexts++;
948 auto AllocType = addCallStack(AllocTrie, AllocInfo);
949 // Record information about the allocation if match info printing
950 // was requested.
952 auto FullStackId = computeFullStackId(AllocInfo->CallStack);
953 FullStackIdToAllocMatchInfo[FullStackId] = {
954 AllocInfo->Info.getTotalSize(), AllocType, /*Matched=*/true};
955 }
956 }
957 }
958 // We might not have matched any to the full inlined call stack.
959 // But if we did, create and attach metadata, or a function attribute if
960 // all contexts have identical profiled behavior.
961 if (!AllocTrie.empty()) {
962 NumOfMemProfMatchedAllocs++;
963 // MemprofMDAttached will be false if a function attribute was
964 // attached.
965 bool MemprofMDAttached = AllocTrie.buildAndAttachMIBMetadata(CI);
966 assert(MemprofMDAttached == I.hasMetadata(LLVMContext::MD_memprof));
967 if (MemprofMDAttached) {
968 // Add callsite metadata for the instruction's location list so that
969 // it simpler later on to identify which part of the MIB contexts
970 // are from this particular instruction (including during inlining,
971 // when the callsite metadata will be updated appropriately).
972 // FIXME: can this be changed to strip out the matching stack
973 // context ids from the MIB contexts and not add any callsite
974 // metadata here to save space?
975 addCallsiteMetadata(I, InlinedCallStack, Ctx);
976 }
977 }
978 continue;
979 }
980
981 // Otherwise, add callsite metadata. If we reach here then we found the
982 // instruction's leaf location in the callsites map and not the allocation
983 // map.
984 assert(CallSitesIter != LocHashToCallSites.end());
985 for (auto CallStackIdx : CallSitesIter->second) {
986 // If we found and thus matched all frames on the call, create and
987 // attach call stack metadata.
989 *CallStackIdx.first, InlinedCallStack, CallStackIdx.second)) {
990 NumOfMemProfMatchedCallSites++;
991 addCallsiteMetadata(I, InlinedCallStack, Ctx);
992 // Only need to find one with a matching call stack and add a single
993 // callsite metadata.
994 break;
995 }
996 }
997 }
998 }
999}
1000
1001MemProfUsePass::MemProfUsePass(std::string MemoryProfileFile,
1003 : MemoryProfileFileName(MemoryProfileFile), FS(FS) {
1004 if (!FS)
1005 this->FS = vfs::getRealFileSystem();
1006}
1007
1009 LLVM_DEBUG(dbgs() << "Read in memory profile:");
1010 auto &Ctx = M.getContext();
1011 auto ReaderOrErr = IndexedInstrProfReader::create(MemoryProfileFileName, *FS);
1012 if (Error E = ReaderOrErr.takeError()) {
1013 handleAllErrors(std::move(E), [&](const ErrorInfoBase &EI) {
1014 Ctx.diagnose(
1015 DiagnosticInfoPGOProfile(MemoryProfileFileName.data(), EI.message()));
1016 });
1017 return PreservedAnalyses::all();
1018 }
1019
1020 std::unique_ptr<IndexedInstrProfReader> MemProfReader =
1021 std::move(ReaderOrErr.get());
1022 if (!MemProfReader) {
1023 Ctx.diagnose(DiagnosticInfoPGOProfile(
1024 MemoryProfileFileName.data(), StringRef("Cannot get MemProfReader")));
1025 return PreservedAnalyses::all();
1026 }
1027
1028 if (!MemProfReader->hasMemoryProfile()) {
1029 Ctx.diagnose(DiagnosticInfoPGOProfile(MemoryProfileFileName.data(),
1030 "Not a memory profile"));
1031 return PreservedAnalyses::all();
1032 }
1033
1034 auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
1035
1036 // Map from the stack has of each allocation context in the function profiles
1037 // to the total profiled size (bytes), allocation type, and whether we matched
1038 // it to an allocation in the IR.
1039 std::map<uint64_t, AllocMatchInfo> FullStackIdToAllocMatchInfo;
1040
1041 for (auto &F : M) {
1042 if (F.isDeclaration())
1043 continue;
1044
1046 readMemprof(M, F, MemProfReader.get(), TLI, FullStackIdToAllocMatchInfo);
1047 }
1048
1050 for (const auto &[Id, Info] : FullStackIdToAllocMatchInfo)
1051 errs() << "MemProf " << getAllocTypeAttributeString(Info.AllocType)
1052 << " context with id " << Id << " has total profiled size "
1053 << Info.TotalSize << (Info.Matched ? " is" : " not")
1054 << " matched\n";
1055 }
1056
1057 return PreservedAnalyses::none();
1058}
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
Definition: CSEInfo.cpp:27
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
#define LLVM_DEBUG(X)
Definition: Debug.h:101
uint64_t Addr
std::string Name
IRTranslator LLVM IR MI
#define F(x, y, z)
Definition: MD5.cpp:55
#define I(x, y, z)
Definition: MD5.cpp:58
static cl::opt< int > ClMappingGranularity("memprof-mapping-granularity", cl::desc("granularity of memprof shadow mapping"), cl::Hidden, cl::init(DefaultMemGranularity))
constexpr char MemProfVersionCheckNamePrefix[]
Definition: MemProfiler.cpp:72
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))
static bool isNewWithHotColdVariant(Function *Callee, const TargetLibraryInfo &TLI)
void createMemprofHistogramFlagVar(Module &M)
constexpr uint64_t MemProfEmscriptenCtorAndDtorPriority
Definition: MemProfiler.cpp:70
static cl::opt< std::string > ClDebugFunc("memprof-debug-func", cl::Hidden, cl::desc("Debug func"))
constexpr char MemProfShadowMemoryDynamicAddress[]
Definition: MemProfiler.cpp:75
constexpr uint64_t MemProfCtorAndDtorPriority
Definition: MemProfiler.cpp:68
constexpr int LLVM_MEM_PROFILER_VERSION
Definition: MemProfiler.cpp:59
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[]
Definition: MemProfiler.cpp:71
constexpr char MemProfFilenameVar[]
Definition: MemProfiler.cpp:78
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
Definition: MemProfiler.cpp:62
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 DefaultShadowScale
Definition: MemProfiler.cpp:65
static cl::opt< std::string > ClMemoryAccessCallbackPrefix("memprof-memory-access-callback-prefix", cl::desc("Prefix for memory access callbacks"), cl::Hidden, cl::init("__memprof_"))
constexpr char MemProfModuleCtorName[]
Definition: MemProfiler.cpp:67
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[]
Definition: MemProfiler.cpp:80
AllocType
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)
Definition: Statistic.h:167
Defines the virtual file system interface vfs::FileSystem.
Class for arbitrary precision integers.
Definition: APInt.h:77
A container for analyses that lazily runs them and caches their results.
Definition: PassManager.h:253
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Definition: PassManager.h:405
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
iterator end() const
Definition: ArrayRef.h:154
iterator begin() const
Definition: ArrayRef.h:153
An instruction that atomically checks whether a specified value is in a memory location,...
Definition: Instructions.h:494
an instruction that atomically reads a memory location, combines it with another value,...
Definition: Instructions.h:695
static Constant * getString(LLVMContext &Context, StringRef Initializer, bool AddNull=true)
This method constructs a CDS and initializes it with a text string.
Definition: Constants.cpp:2900
This is an important base class in LLVM.
Definition: Constant.h:41
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...
Definition: Constants.cpp:400
Debug location.
A parsed version of the target data layout string in and methods for querying it.
Definition: DataLayout.h:110
Diagnostic information for the PGO profiler.
Base class for error info classes.
Definition: Error.h:45
virtual std::string message() const
Return the error message as a string.
Definition: Error.h:53
Lightweight error class with error context and mandatory checking.
Definition: Error.h:160
A handy container for a FunctionType+Callee-pointer pair, which can be passed around as a single enti...
Definition: DerivedTypes.h:168
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)
Definition: Globals.cpp:206
void setLinkage(LinkageTypes LT)
Definition: GlobalValue.h:537
GUID getGUID() const
Return a 64-bit global unique ID constructed from global value name (i.e.
Definition: GlobalValue.h:595
@ ExternalLinkage
Externally visible function.
Definition: GlobalValue.h:52
@ WeakAnyLinkage
Keep one copy of named function when linking (weak)
Definition: GlobalValue.h:56
@ AvailableExternallyLinkage
Available for inspection, not emission.
Definition: GlobalValue.h:53
HashResultTy< HasherT_ > final()
Forward to HasherT::final() if available.
Definition: HashBuilder.h:66
Interface to help hash various types through a hasher type.
Definition: HashBuilder.h:139
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.
Definition: HashBuilder.h:149
Value * CreateExtractElement(Value *Vec, Value *Idx, const Twine &Name="")
Definition: IRBuilder.h:2458
Value * CreatePointerCast(Value *V, Type *DestTy, const Twine &Name="")
Definition: IRBuilder.h:2168
Value * CreateIntToPtr(Value *V, Type *DestTy, const Twine &Name="")
Definition: IRBuilder.h:2120
Value * CreateLShr(Value *LHS, Value *RHS, const Twine &Name="", bool isExact=false)
Definition: IRBuilder.h:1435
IntegerType * getInt32Ty()
Fetch the type representing a 32-bit integer.
Definition: IRBuilder.h:524
Value * CreateGEP(Type *Ty, Value *Ptr, ArrayRef< Value * > IdxList, const Twine &Name="", GEPNoWrapFlags NW=GEPNoWrapFlags::none())
Definition: IRBuilder.h:1864
LoadInst * CreateLoad(Type *Ty, Value *Ptr, const char *Name)
Provided to resolve 'CreateLoad(Ty, Ptr, "...")' correctly, instead of converting the string to 'bool...
Definition: IRBuilder.h:1788
Value * CreateAnd(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:1473
StoreInst * CreateStore(Value *Val, Value *Ptr, bool isVolatile=false)
Definition: IRBuilder.h:1801
Value * CreateAdd(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition: IRBuilder.h:1325
Value * CreateIntCast(Value *V, Type *DestTy, bool isSigned, const Twine &Name="")
Definition: IRBuilder.h:2194
Type * getVoidTy()
Fetch the type representing void.
Definition: IRBuilder.h:562
CallInst * CreateCall(FunctionType *FTy, Value *Callee, ArrayRef< Value * > Args=std::nullopt, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition: IRBuilder.h:2410
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition: IRBuilder.h:2664
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...
Definition: PassManager.h:563
instrprof_error get() const
Definition: InstrProf.h:409
std::string message() const override
Return the error message as a string.
Definition: InstrProf.cpp:250
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.
Definition: LLVMContext.h:67
An instruction for reading from memory.
Definition: Instructions.h:173
A single uniqued string.
Definition: Metadata.h:720
StringRef getString() const
Definition: Metadata.cpp:610
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.
Definition: Module.h:65
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.
Definition: Analysis.h:111
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
Definition: Analysis.h:114
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: Analysis.h:117
bool empty() const
Definition: SmallVector.h:94
void push_back(const T &Elt)
Definition: SmallVector.h:426
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1209
An instruction for storing to memory.
Definition: Instructions.h:289
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
constexpr bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:134
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.
Definition: Triple.h:44
ObjectFormatType getObjectFormat() const
Get the object format for this triple.
Definition: Triple.h:399
bool isOSEmscripten() const
Tests whether the OS is Emscripten.
Definition: Triple.h:698
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
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 * getInt64Ty(LLVMContext &C)
LLVM Value Representation.
Definition: Value.h:74
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:255
Class to build a trie of call stack contexts for a particular profiled allocation call,...
void addCallStack(AllocationType AllocType, ArrayRef< uint64_t > StackIds)
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...
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.
Definition: BitmaskEnum.h:121
@ C
The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:443
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.
Definition: AddressRanges.h:18
void handleAllErrors(Error E, HandlerTs &&... Handlers)
Behaves the same as handleErrors, except that by contract all errors must be handled by the given han...
Definition: Error.h:977
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.
Definition: InstrProf.cpp:231
std::array< uint8_t, NumBytes > BLAKE3Result
The constant LLVM_BLAKE3_OUT_LEN provides the default output length, 32 bytes, which is recommended f...
Definition: BLAKE3.h:35
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.
Definition: Debug.cpp:163
cl::opt< bool > NoPGOWarnMismatch
Definition: MemProfiler.cpp:55
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)
Definition: InstrProf.cpp:1511
@ DS_Warning
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.
Definition: ModuleUtils.cpp:74
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
Definition: MemProf.h:207
uint32_t LineOffset
Definition: MemProf.h:212