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
80// Command-line flags.
81
83 "memprof-guard-against-version-mismatch",
84 cl::desc("Guard against compiler/runtime version mismatch."), cl::Hidden,
85 cl::init(true));
86
87// This flag may need to be replaced with -f[no-]memprof-reads.
88static cl::opt<bool> ClInstrumentReads("memprof-instrument-reads",
89 cl::desc("instrument read instructions"),
90 cl::Hidden, cl::init(true));
91
92static cl::opt<bool>
93 ClInstrumentWrites("memprof-instrument-writes",
94 cl::desc("instrument write instructions"), cl::Hidden,
95 cl::init(true));
96
98 "memprof-instrument-atomics",
99 cl::desc("instrument atomic instructions (rmw, cmpxchg)"), cl::Hidden,
100 cl::init(true));
101
103 "memprof-use-callbacks",
104 cl::desc("Use callbacks instead of inline instrumentation sequences."),
105 cl::Hidden, cl::init(false));
106
108 ClMemoryAccessCallbackPrefix("memprof-memory-access-callback-prefix",
109 cl::desc("Prefix for memory access callbacks"),
110 cl::Hidden, cl::init("__memprof_"));
111
112// These flags allow to change the shadow mapping.
113// The shadow mapping looks like
114// Shadow = ((Mem & mask) >> scale) + offset
115
116static cl::opt<int> ClMappingScale("memprof-mapping-scale",
117 cl::desc("scale of memprof shadow mapping"),
119
120static cl::opt<int>
121 ClMappingGranularity("memprof-mapping-granularity",
122 cl::desc("granularity of memprof shadow mapping"),
124
125static cl::opt<bool> ClStack("memprof-instrument-stack",
126 cl::desc("Instrument scalar stack variables"),
127 cl::Hidden, cl::init(false));
128
129// Debug flags.
130
131static cl::opt<int> ClDebug("memprof-debug", cl::desc("debug"), cl::Hidden,
132 cl::init(0));
133
134static cl::opt<std::string> ClDebugFunc("memprof-debug-func", cl::Hidden,
135 cl::desc("Debug func"));
136
137static cl::opt<int> ClDebugMin("memprof-debug-min", cl::desc("Debug min inst"),
138 cl::Hidden, cl::init(-1));
139
140static cl::opt<int> ClDebugMax("memprof-debug-max", cl::desc("Debug max inst"),
141 cl::Hidden, cl::init(-1));
142
143// By default disable matching of allocation profiles onto operator new that
144// already explicitly pass a hot/cold hint, since we don't currently
145// override these hints anyway.
147 "memprof-match-hot-cold-new",
148 cl::desc(
149 "Match allocation profiles onto existing hot/cold operator new calls"),
150 cl::Hidden, cl::init(false));
151
152STATISTIC(NumInstrumentedReads, "Number of instrumented reads");
153STATISTIC(NumInstrumentedWrites, "Number of instrumented writes");
154STATISTIC(NumSkippedStackReads, "Number of non-instrumented stack reads");
155STATISTIC(NumSkippedStackWrites, "Number of non-instrumented stack writes");
156STATISTIC(NumOfMemProfMissing, "Number of functions without memory profile.");
157
158namespace {
159
160/// This struct defines the shadow mapping using the rule:
161/// shadow = ((mem & mask) >> Scale) ADD DynamicShadowOffset.
162struct ShadowMapping {
163 ShadowMapping() {
164 Scale = ClMappingScale;
165 Granularity = ClMappingGranularity;
166 Mask = ~(Granularity - 1);
167 }
168
169 int Scale;
170 int Granularity;
171 uint64_t Mask; // Computed as ~(Granularity-1)
172};
173
174static uint64_t getCtorAndDtorPriority(Triple &TargetTriple) {
177}
178
179struct InterestingMemoryAccess {
180 Value *Addr = nullptr;
181 bool IsWrite;
182 Type *AccessTy;
183 Value *MaybeMask = nullptr;
184};
185
186/// Instrument the code in module to profile memory accesses.
187class MemProfiler {
188public:
189 MemProfiler(Module &M) {
190 C = &(M.getContext());
191 LongSize = M.getDataLayout().getPointerSizeInBits();
192 IntptrTy = Type::getIntNTy(*C, LongSize);
193 PtrTy = PointerType::getUnqual(*C);
194 }
195
196 /// If it is an interesting memory access, populate information
197 /// about the access and return a InterestingMemoryAccess struct.
198 /// Otherwise return std::nullopt.
199 std::optional<InterestingMemoryAccess>
200 isInterestingMemoryAccess(Instruction *I) const;
201
202 void instrumentMop(Instruction *I, const DataLayout &DL,
203 InterestingMemoryAccess &Access);
204 void instrumentAddress(Instruction *OrigIns, Instruction *InsertBefore,
205 Value *Addr, bool IsWrite);
206 void instrumentMaskedLoadOrStore(const DataLayout &DL, Value *Mask,
207 Instruction *I, Value *Addr, Type *AccessTy,
208 bool IsWrite);
209 void instrumentMemIntrinsic(MemIntrinsic *MI);
210 Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
211 bool instrumentFunction(Function &F);
212 bool maybeInsertMemProfInitAtFunctionEntry(Function &F);
213 bool insertDynamicShadowAtFunctionEntry(Function &F);
214
215private:
216 void initializeCallbacks(Module &M);
217
218 LLVMContext *C;
219 int LongSize;
220 Type *IntptrTy;
221 PointerType *PtrTy;
222 ShadowMapping Mapping;
223
224 // These arrays is indexed by AccessIsWrite
225 FunctionCallee MemProfMemoryAccessCallback[2];
226
227 FunctionCallee MemProfMemmove, MemProfMemcpy, MemProfMemset;
228 Value *DynamicShadowOffset = nullptr;
229};
230
231class ModuleMemProfiler {
232public:
233 ModuleMemProfiler(Module &M) { TargetTriple = Triple(M.getTargetTriple()); }
234
235 bool instrumentModule(Module &);
236
237private:
238 Triple TargetTriple;
239 ShadowMapping Mapping;
240 Function *MemProfCtorFunction = nullptr;
241};
242
243} // end anonymous namespace
244
246
249 Module &M = *F.getParent();
250 MemProfiler Profiler(M);
251 if (Profiler.instrumentFunction(F))
253 return PreservedAnalyses::all();
254}
255
257
260 ModuleMemProfiler Profiler(M);
261 if (Profiler.instrumentModule(M))
263 return PreservedAnalyses::all();
264}
265
266Value *MemProfiler::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
267 // (Shadow & mask) >> scale
268 Shadow = IRB.CreateAnd(Shadow, Mapping.Mask);
269 Shadow = IRB.CreateLShr(Shadow, Mapping.Scale);
270 // (Shadow >> scale) | offset
271 assert(DynamicShadowOffset);
272 return IRB.CreateAdd(Shadow, DynamicShadowOffset);
273}
274
275// Instrument memset/memmove/memcpy
276void MemProfiler::instrumentMemIntrinsic(MemIntrinsic *MI) {
277 IRBuilder<> IRB(MI);
278 if (isa<MemTransferInst>(MI)) {
279 IRB.CreateCall(isa<MemMoveInst>(MI) ? MemProfMemmove : MemProfMemcpy,
280 {MI->getOperand(0), MI->getOperand(1),
281 IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false)});
282 } else if (isa<MemSetInst>(MI)) {
283 IRB.CreateCall(
284 MemProfMemset,
285 {MI->getOperand(0),
286 IRB.CreateIntCast(MI->getOperand(1), IRB.getInt32Ty(), false),
287 IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false)});
288 }
289 MI->eraseFromParent();
290}
291
292std::optional<InterestingMemoryAccess>
293MemProfiler::isInterestingMemoryAccess(Instruction *I) const {
294 // Do not instrument the load fetching the dynamic shadow address.
295 if (DynamicShadowOffset == I)
296 return std::nullopt;
297
298 InterestingMemoryAccess Access;
299
300 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
302 return std::nullopt;
303 Access.IsWrite = false;
304 Access.AccessTy = LI->getType();
305 Access.Addr = LI->getPointerOperand();
306 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
308 return std::nullopt;
309 Access.IsWrite = true;
310 Access.AccessTy = SI->getValueOperand()->getType();
311 Access.Addr = SI->getPointerOperand();
312 } else if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
314 return std::nullopt;
315 Access.IsWrite = true;
316 Access.AccessTy = RMW->getValOperand()->getType();
317 Access.Addr = RMW->getPointerOperand();
318 } else if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
320 return std::nullopt;
321 Access.IsWrite = true;
322 Access.AccessTy = XCHG->getCompareOperand()->getType();
323 Access.Addr = XCHG->getPointerOperand();
324 } else if (auto *CI = dyn_cast<CallInst>(I)) {
325 auto *F = CI->getCalledFunction();
326 if (F && (F->getIntrinsicID() == Intrinsic::masked_load ||
327 F->getIntrinsicID() == Intrinsic::masked_store)) {
328 unsigned OpOffset = 0;
329 if (F->getIntrinsicID() == Intrinsic::masked_store) {
331 return std::nullopt;
332 // Masked store has an initial operand for the value.
333 OpOffset = 1;
334 Access.AccessTy = CI->getArgOperand(0)->getType();
335 Access.IsWrite = true;
336 } else {
338 return std::nullopt;
339 Access.AccessTy = CI->getType();
340 Access.IsWrite = false;
341 }
342
343 auto *BasePtr = CI->getOperand(0 + OpOffset);
344 Access.MaybeMask = CI->getOperand(2 + OpOffset);
345 Access.Addr = BasePtr;
346 }
347 }
348
349 if (!Access.Addr)
350 return std::nullopt;
351
352 // Do not instrument accesses from different address spaces; we cannot deal
353 // with them.
354 Type *PtrTy = cast<PointerType>(Access.Addr->getType()->getScalarType());
355 if (PtrTy->getPointerAddressSpace() != 0)
356 return std::nullopt;
357
358 // Ignore swifterror addresses.
359 // swifterror memory addresses are mem2reg promoted by instruction
360 // selection. As such they cannot have regular uses like an instrumentation
361 // function and it makes no sense to track them as memory.
362 if (Access.Addr->isSwiftError())
363 return std::nullopt;
364
365 // Peel off GEPs and BitCasts.
366 auto *Addr = Access.Addr->stripInBoundsOffsets();
367
368 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Addr)) {
369 // Do not instrument PGO counter updates.
370 if (GV->hasSection()) {
371 StringRef SectionName = GV->getSection();
372 // Check if the global is in the PGO counters section.
373 auto OF = Triple(I->getModule()->getTargetTriple()).getObjectFormat();
374 if (SectionName.ends_with(
375 getInstrProfSectionName(IPSK_cnts, OF, /*AddSegmentInfo=*/false)))
376 return std::nullopt;
377 }
378
379 // Do not instrument accesses to LLVM internal variables.
380 if (GV->getName().starts_with("__llvm"))
381 return std::nullopt;
382 }
383
384 return Access;
385}
386
387void MemProfiler::instrumentMaskedLoadOrStore(const DataLayout &DL, Value *Mask,
389 Type *AccessTy, bool IsWrite) {
390 auto *VTy = cast<FixedVectorType>(AccessTy);
391 unsigned Num = VTy->getNumElements();
392 auto *Zero = ConstantInt::get(IntptrTy, 0);
393 for (unsigned Idx = 0; Idx < Num; ++Idx) {
394 Value *InstrumentedAddress = nullptr;
395 Instruction *InsertBefore = I;
396 if (auto *Vector = dyn_cast<ConstantVector>(Mask)) {
397 // dyn_cast as we might get UndefValue
398 if (auto *Masked = dyn_cast<ConstantInt>(Vector->getOperand(Idx))) {
399 if (Masked->isZero())
400 // Mask is constant false, so no instrumentation needed.
401 continue;
402 // If we have a true or undef value, fall through to instrumentAddress.
403 // with InsertBefore == I
404 }
405 } else {
406 IRBuilder<> IRB(I);
407 Value *MaskElem = IRB.CreateExtractElement(Mask, Idx);
408 Instruction *ThenTerm = SplitBlockAndInsertIfThen(MaskElem, I, false);
409 InsertBefore = ThenTerm;
410 }
411
412 IRBuilder<> IRB(InsertBefore);
413 InstrumentedAddress =
414 IRB.CreateGEP(VTy, Addr, {Zero, ConstantInt::get(IntptrTy, Idx)});
415 instrumentAddress(I, InsertBefore, InstrumentedAddress, IsWrite);
416 }
417}
418
419void MemProfiler::instrumentMop(Instruction *I, const DataLayout &DL,
420 InterestingMemoryAccess &Access) {
421 // Skip instrumentation of stack accesses unless requested.
422 if (!ClStack && isa<AllocaInst>(getUnderlyingObject(Access.Addr))) {
423 if (Access.IsWrite)
424 ++NumSkippedStackWrites;
425 else
426 ++NumSkippedStackReads;
427 return;
428 }
429
430 if (Access.IsWrite)
431 NumInstrumentedWrites++;
432 else
433 NumInstrumentedReads++;
434
435 if (Access.MaybeMask) {
436 instrumentMaskedLoadOrStore(DL, Access.MaybeMask, I, Access.Addr,
437 Access.AccessTy, Access.IsWrite);
438 } else {
439 // Since the access counts will be accumulated across the entire allocation,
440 // we only update the shadow access count for the first location and thus
441 // don't need to worry about alignment and type size.
442 instrumentAddress(I, I, Access.Addr, Access.IsWrite);
443 }
444}
445
446void MemProfiler::instrumentAddress(Instruction *OrigIns,
447 Instruction *InsertBefore, Value *Addr,
448 bool IsWrite) {
449 IRBuilder<> IRB(InsertBefore);
450 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
451
452 if (ClUseCalls) {
453 IRB.CreateCall(MemProfMemoryAccessCallback[IsWrite], AddrLong);
454 return;
455 }
456
457 // Create an inline sequence to compute shadow location, and increment the
458 // value by one.
459 Type *ShadowTy = Type::getInt64Ty(*C);
460 Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
461 Value *ShadowPtr = memToShadow(AddrLong, IRB);
462 Value *ShadowAddr = IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy);
463 Value *ShadowValue = IRB.CreateLoad(ShadowTy, ShadowAddr);
464 Value *Inc = ConstantInt::get(Type::getInt64Ty(*C), 1);
465 ShadowValue = IRB.CreateAdd(ShadowValue, Inc);
466 IRB.CreateStore(ShadowValue, ShadowAddr);
467}
468
469// Create the variable for the profile file name.
471 const MDString *MemProfFilename =
472 dyn_cast_or_null<MDString>(M.getModuleFlag("MemProfProfileFilename"));
473 if (!MemProfFilename)
474 return;
475 assert(!MemProfFilename->getString().empty() &&
476 "Unexpected MemProfProfileFilename metadata with empty string");
477 Constant *ProfileNameConst = ConstantDataArray::getString(
478 M.getContext(), MemProfFilename->getString(), true);
479 GlobalVariable *ProfileNameVar = new GlobalVariable(
480 M, ProfileNameConst->getType(), /*isConstant=*/true,
482 Triple TT(M.getTargetTriple());
483 if (TT.supportsCOMDAT()) {
485 ProfileNameVar->setComdat(M.getOrInsertComdat(MemProfFilenameVar));
486 }
487}
488
489bool ModuleMemProfiler::instrumentModule(Module &M) {
490 // Create a module constructor.
491 std::string MemProfVersion = std::to_string(LLVM_MEM_PROFILER_VERSION);
492 std::string VersionCheckName =
494 : "";
495 std::tie(MemProfCtorFunction, std::ignore) =
497 MemProfInitName, /*InitArgTypes=*/{},
498 /*InitArgs=*/{}, VersionCheckName);
499
500 const uint64_t Priority = getCtorAndDtorPriority(TargetTriple);
501 appendToGlobalCtors(M, MemProfCtorFunction, Priority);
502
504
505 return true;
506}
507
508void MemProfiler::initializeCallbacks(Module &M) {
509 IRBuilder<> IRB(*C);
510
511 for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
512 const std::string TypeStr = AccessIsWrite ? "store" : "load";
513
514 SmallVector<Type *, 2> Args1{1, IntptrTy};
515 MemProfMemoryAccessCallback[AccessIsWrite] =
516 M.getOrInsertFunction(ClMemoryAccessCallbackPrefix + TypeStr,
517 FunctionType::get(IRB.getVoidTy(), Args1, false));
518 }
519 MemProfMemmove = M.getOrInsertFunction(
520 ClMemoryAccessCallbackPrefix + "memmove", PtrTy, PtrTy, PtrTy, IntptrTy);
521 MemProfMemcpy = M.getOrInsertFunction(ClMemoryAccessCallbackPrefix + "memcpy",
522 PtrTy, PtrTy, PtrTy, IntptrTy);
523 MemProfMemset =
524 M.getOrInsertFunction(ClMemoryAccessCallbackPrefix + "memset", PtrTy,
525 PtrTy, IRB.getInt32Ty(), IntptrTy);
526}
527
528bool MemProfiler::maybeInsertMemProfInitAtFunctionEntry(Function &F) {
529 // For each NSObject descendant having a +load method, this method is invoked
530 // by the ObjC runtime before any of the static constructors is called.
531 // Therefore we need to instrument such methods with a call to __memprof_init
532 // at the beginning in order to initialize our runtime before any access to
533 // the shadow memory.
534 // We cannot just ignore these methods, because they may call other
535 // instrumented functions.
536 if (F.getName().contains(" load]")) {
537 FunctionCallee MemProfInitFunction =
539 IRBuilder<> IRB(&F.front(), F.front().begin());
540 IRB.CreateCall(MemProfInitFunction, {});
541 return true;
542 }
543 return false;
544}
545
546bool MemProfiler::insertDynamicShadowAtFunctionEntry(Function &F) {
547 IRBuilder<> IRB(&F.front().front());
548 Value *GlobalDynamicAddress = F.getParent()->getOrInsertGlobal(
550 if (F.getParent()->getPICLevel() == PICLevel::NotPIC)
551 cast<GlobalVariable>(GlobalDynamicAddress)->setDSOLocal(true);
552 DynamicShadowOffset = IRB.CreateLoad(IntptrTy, GlobalDynamicAddress);
553 return true;
554}
555
556bool MemProfiler::instrumentFunction(Function &F) {
557 if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage)
558 return false;
559 if (ClDebugFunc == F.getName())
560 return false;
561 if (F.getName().starts_with("__memprof_"))
562 return false;
563
564 bool FunctionModified = false;
565
566 // If needed, insert __memprof_init.
567 // This function needs to be called even if the function body is not
568 // instrumented.
569 if (maybeInsertMemProfInitAtFunctionEntry(F))
570 FunctionModified = true;
571
572 LLVM_DEBUG(dbgs() << "MEMPROF instrumenting:\n" << F << "\n");
573
574 initializeCallbacks(*F.getParent());
575
577
578 // Fill the set of memory operations to instrument.
579 for (auto &BB : F) {
580 for (auto &Inst : BB) {
581 if (isInterestingMemoryAccess(&Inst) || isa<MemIntrinsic>(Inst))
582 ToInstrument.push_back(&Inst);
583 }
584 }
585
586 if (ToInstrument.empty()) {
587 LLVM_DEBUG(dbgs() << "MEMPROF done instrumenting: " << FunctionModified
588 << " " << F << "\n");
589
590 return FunctionModified;
591 }
592
593 FunctionModified |= insertDynamicShadowAtFunctionEntry(F);
594
595 int NumInstrumented = 0;
596 for (auto *Inst : ToInstrument) {
597 if (ClDebugMin < 0 || ClDebugMax < 0 ||
598 (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
599 std::optional<InterestingMemoryAccess> Access =
600 isInterestingMemoryAccess(Inst);
601 if (Access)
602 instrumentMop(Inst, F.getParent()->getDataLayout(), *Access);
603 else
604 instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
605 }
606 NumInstrumented++;
607 }
608
609 if (NumInstrumented > 0)
610 FunctionModified = true;
611
612 LLVM_DEBUG(dbgs() << "MEMPROF done instrumenting: " << FunctionModified << " "
613 << F << "\n");
614
615 return FunctionModified;
616}
617
619 std::vector<uint64_t> &InlinedCallStack,
620 LLVMContext &Ctx) {
621 I.setMetadata(LLVMContext::MD_callsite,
622 buildCallstackMetadata(InlinedCallStack, Ctx));
623}
624
626 uint32_t Column) {
629 HashBuilder.add(Function, LineOffset, Column);
631 uint64_t Id;
632 std::memcpy(&Id, Hash.data(), sizeof(Hash));
633 return Id;
634}
635
638}
639
640static void addCallStack(CallStackTrie &AllocTrie,
641 const AllocationInfo *AllocInfo) {
642 SmallVector<uint64_t> StackIds;
643 for (const auto &StackFrame : AllocInfo->CallStack)
644 StackIds.push_back(computeStackId(StackFrame));
645 auto AllocType = getAllocType(AllocInfo->Info.getTotalLifetimeAccessDensity(),
646 AllocInfo->Info.getAllocCount(),
647 AllocInfo->Info.getTotalLifetime());
648 AllocTrie.addCallStack(AllocType, StackIds);
649}
650
651// Helper to compare the InlinedCallStack computed from an instruction's debug
652// info to a list of Frames from profile data (either the allocation data or a
653// callsite). For callsites, the StartIndex to use in the Frame array may be
654// non-zero.
655static bool
657 ArrayRef<uint64_t> InlinedCallStack,
658 unsigned StartIndex = 0) {
659 auto StackFrame = ProfileCallStack.begin() + StartIndex;
660 auto InlCallStackIter = InlinedCallStack.begin();
661 for (; StackFrame != ProfileCallStack.end() &&
662 InlCallStackIter != InlinedCallStack.end();
663 ++StackFrame, ++InlCallStackIter) {
664 uint64_t StackId = computeStackId(*StackFrame);
665 if (StackId != *InlCallStackIter)
666 return false;
667 }
668 // Return true if we found and matched all stack ids from the call
669 // instruction.
670 return InlCallStackIter == InlinedCallStack.end();
671}
672
674 const TargetLibraryInfo &TLI) {
675 if (!Callee)
676 return false;
677 LibFunc Func;
678 if (!TLI.getLibFunc(*Callee, Func))
679 return false;
680 switch (Func) {
681 case LibFunc_Znwm:
682 case LibFunc_ZnwmRKSt9nothrow_t:
683 case LibFunc_ZnwmSt11align_val_t:
684 case LibFunc_ZnwmSt11align_val_tRKSt9nothrow_t:
685 case LibFunc_Znam:
686 case LibFunc_ZnamRKSt9nothrow_t:
687 case LibFunc_ZnamSt11align_val_t:
688 case LibFunc_ZnamSt11align_val_tRKSt9nothrow_t:
689 return true;
690 case LibFunc_Znwm12__hot_cold_t:
691 case LibFunc_ZnwmRKSt9nothrow_t12__hot_cold_t:
692 case LibFunc_ZnwmSt11align_val_t12__hot_cold_t:
693 case LibFunc_ZnwmSt11align_val_tRKSt9nothrow_t12__hot_cold_t:
694 case LibFunc_Znam12__hot_cold_t:
695 case LibFunc_ZnamRKSt9nothrow_t12__hot_cold_t:
696 case LibFunc_ZnamSt11align_val_t12__hot_cold_t:
697 case LibFunc_ZnamSt11align_val_tRKSt9nothrow_t12__hot_cold_t:
699 default:
700 return false;
701 }
702}
703
704static void readMemprof(Module &M, Function &F,
706 const TargetLibraryInfo &TLI) {
707 auto &Ctx = M.getContext();
708 // Previously we used getIRPGOFuncName() here. If F is local linkage,
709 // getIRPGOFuncName() returns FuncName with prefix 'FileName;'. But
710 // llvm-profdata uses FuncName in dwarf to create GUID which doesn't
711 // contain FileName's prefix. It caused local linkage function can't
712 // find MemProfRecord. So we use getName() now.
713 // 'unique-internal-linkage-names' can make MemProf work better for local
714 // linkage function.
715 auto FuncName = F.getName();
716 auto FuncGUID = Function::getGUID(FuncName);
717 std::optional<memprof::MemProfRecord> MemProfRec;
718 auto Err = MemProfReader->getMemProfRecord(FuncGUID).moveInto(MemProfRec);
719 if (Err) {
720 handleAllErrors(std::move(Err), [&](const InstrProfError &IPE) {
721 auto Err = IPE.get();
722 bool SkipWarning = false;
723 LLVM_DEBUG(dbgs() << "Error in reading profile for Func " << FuncName
724 << ": ");
726 NumOfMemProfMissing++;
727 SkipWarning = !PGOWarnMissing;
728 LLVM_DEBUG(dbgs() << "unknown function");
729 } else if (Err == instrprof_error::hash_mismatch) {
730 SkipWarning =
733 (F.hasComdat() ||
735 LLVM_DEBUG(dbgs() << "hash mismatch (skip=" << SkipWarning << ")");
736 }
737
738 if (SkipWarning)
739 return;
740
741 std::string Msg = (IPE.message() + Twine(" ") + F.getName().str() +
742 Twine(" Hash = ") + std::to_string(FuncGUID))
743 .str();
744
745 Ctx.diagnose(
746 DiagnosticInfoPGOProfile(M.getName().data(), Msg, DS_Warning));
747 });
748 return;
749 }
750
751 // Detect if there are non-zero column numbers in the profile. If not,
752 // treat all column numbers as 0 when matching (i.e. ignore any non-zero
753 // columns in the IR). The profiled binary might have been built with
754 // column numbers disabled, for example.
755 bool ProfileHasColumns = false;
756
757 // Build maps of the location hash to all profile data with that leaf location
758 // (allocation info and the callsites).
759 std::map<uint64_t, std::set<const AllocationInfo *>> LocHashToAllocInfo;
760 // For the callsites we need to record the index of the associated frame in
761 // the frame array (see comments below where the map entries are added).
762 std::map<uint64_t, std::set<std::pair<const SmallVector<Frame> *, unsigned>>>
763 LocHashToCallSites;
764 for (auto &AI : MemProfRec->AllocSites) {
765 // Associate the allocation info with the leaf frame. The later matching
766 // code will match any inlined call sequences in the IR with a longer prefix
767 // of call stack frames.
768 uint64_t StackId = computeStackId(AI.CallStack[0]);
769 LocHashToAllocInfo[StackId].insert(&AI);
770 ProfileHasColumns |= AI.CallStack[0].Column;
771 }
772 for (auto &CS : MemProfRec->CallSites) {
773 // Need to record all frames from leaf up to and including this function,
774 // as any of these may or may not have been inlined at this point.
775 unsigned Idx = 0;
776 for (auto &StackFrame : CS) {
777 uint64_t StackId = computeStackId(StackFrame);
778 LocHashToCallSites[StackId].insert(std::make_pair(&CS, Idx++));
779 ProfileHasColumns |= StackFrame.Column;
780 // Once we find this function, we can stop recording.
781 if (StackFrame.Function == FuncGUID)
782 break;
783 }
784 assert(Idx <= CS.size() && CS[Idx - 1].Function == FuncGUID);
785 }
786
787 auto GetOffset = [](const DILocation *DIL) {
788 return (DIL->getLine() - DIL->getScope()->getSubprogram()->getLine()) &
789 0xffff;
790 };
791
792 // Now walk the instructions, looking up the associated profile data using
793 // dbug locations.
794 for (auto &BB : F) {
795 for (auto &I : BB) {
796 if (I.isDebugOrPseudoInst())
797 continue;
798 // We are only interested in calls (allocation or interior call stack
799 // context calls).
800 auto *CI = dyn_cast<CallBase>(&I);
801 if (!CI)
802 continue;
803 auto *CalledFunction = CI->getCalledFunction();
804 if (CalledFunction && CalledFunction->isIntrinsic())
805 continue;
806 // List of call stack ids computed from the location hashes on debug
807 // locations (leaf to inlined at root).
808 std::vector<uint64_t> InlinedCallStack;
809 // Was the leaf location found in one of the profile maps?
810 bool LeafFound = false;
811 // If leaf was found in a map, iterators pointing to its location in both
812 // of the maps. It might exist in neither, one, or both (the latter case
813 // can happen because we don't currently have discriminators to
814 // distinguish the case when a single line/col maps to both an allocation
815 // and another callsite).
816 std::map<uint64_t, std::set<const AllocationInfo *>>::iterator
817 AllocInfoIter;
818 std::map<uint64_t, std::set<std::pair<const SmallVector<Frame> *,
819 unsigned>>>::iterator CallSitesIter;
820 for (const DILocation *DIL = I.getDebugLoc(); DIL != nullptr;
821 DIL = DIL->getInlinedAt()) {
822 // Use C++ linkage name if possible. Need to compile with
823 // -fdebug-info-for-profiling to get linkage name.
824 StringRef Name = DIL->getScope()->getSubprogram()->getLinkageName();
825 if (Name.empty())
826 Name = DIL->getScope()->getSubprogram()->getName();
827 auto CalleeGUID = Function::getGUID(Name);
828 auto StackId = computeStackId(CalleeGUID, GetOffset(DIL),
829 ProfileHasColumns ? DIL->getColumn() : 0);
830 // Check if we have found the profile's leaf frame. If yes, collect
831 // the rest of the call's inlined context starting here. If not, see if
832 // we find a match further up the inlined context (in case the profile
833 // was missing debug frames at the leaf).
834 if (!LeafFound) {
835 AllocInfoIter = LocHashToAllocInfo.find(StackId);
836 CallSitesIter = LocHashToCallSites.find(StackId);
837 if (AllocInfoIter != LocHashToAllocInfo.end() ||
838 CallSitesIter != LocHashToCallSites.end())
839 LeafFound = true;
840 }
841 if (LeafFound)
842 InlinedCallStack.push_back(StackId);
843 }
844 // If leaf not in either of the maps, skip inst.
845 if (!LeafFound)
846 continue;
847
848 // First add !memprof metadata from allocation info, if we found the
849 // instruction's leaf location in that map, and if the rest of the
850 // instruction's locations match the prefix Frame locations on an
851 // allocation context with the same leaf.
852 if (AllocInfoIter != LocHashToAllocInfo.end()) {
853 // Only consider allocations via new, to reduce unnecessary metadata,
854 // since those are the only allocations that will be targeted initially.
855 if (!isNewWithHotColdVariant(CI->getCalledFunction(), TLI))
856 continue;
857 // We may match this instruction's location list to multiple MIB
858 // contexts. Add them to a Trie specialized for trimming the contexts to
859 // the minimal needed to disambiguate contexts with unique behavior.
860 CallStackTrie AllocTrie;
861 for (auto *AllocInfo : AllocInfoIter->second) {
862 // Check the full inlined call stack against this one.
863 // If we found and thus matched all frames on the call, include
864 // this MIB.
866 InlinedCallStack))
867 addCallStack(AllocTrie, AllocInfo);
868 }
869 // We might not have matched any to the full inlined call stack.
870 // But if we did, create and attach metadata, or a function attribute if
871 // all contexts have identical profiled behavior.
872 if (!AllocTrie.empty()) {
873 // MemprofMDAttached will be false if a function attribute was
874 // attached.
875 bool MemprofMDAttached = AllocTrie.buildAndAttachMIBMetadata(CI);
876 assert(MemprofMDAttached == I.hasMetadata(LLVMContext::MD_memprof));
877 if (MemprofMDAttached) {
878 // Add callsite metadata for the instruction's location list so that
879 // it simpler later on to identify which part of the MIB contexts
880 // are from this particular instruction (including during inlining,
881 // when the callsite metdata will be updated appropriately).
882 // FIXME: can this be changed to strip out the matching stack
883 // context ids from the MIB contexts and not add any callsite
884 // metadata here to save space?
885 addCallsiteMetadata(I, InlinedCallStack, Ctx);
886 }
887 }
888 continue;
889 }
890
891 // Otherwise, add callsite metadata. If we reach here then we found the
892 // instruction's leaf location in the callsites map and not the allocation
893 // map.
894 assert(CallSitesIter != LocHashToCallSites.end());
895 for (auto CallStackIdx : CallSitesIter->second) {
896 // If we found and thus matched all frames on the call, create and
897 // attach call stack metadata.
899 *CallStackIdx.first, InlinedCallStack, CallStackIdx.second)) {
900 addCallsiteMetadata(I, InlinedCallStack, Ctx);
901 // Only need to find one with a matching call stack and add a single
902 // callsite metadata.
903 break;
904 }
905 }
906 }
907 }
908}
909
910MemProfUsePass::MemProfUsePass(std::string MemoryProfileFile,
912 : MemoryProfileFileName(MemoryProfileFile), FS(FS) {
913 if (!FS)
914 this->FS = vfs::getRealFileSystem();
915}
916
918 LLVM_DEBUG(dbgs() << "Read in memory profile:");
919 auto &Ctx = M.getContext();
920 auto ReaderOrErr = IndexedInstrProfReader::create(MemoryProfileFileName, *FS);
921 if (Error E = ReaderOrErr.takeError()) {
922 handleAllErrors(std::move(E), [&](const ErrorInfoBase &EI) {
923 Ctx.diagnose(
924 DiagnosticInfoPGOProfile(MemoryProfileFileName.data(), EI.message()));
925 });
926 return PreservedAnalyses::all();
927 }
928
929 std::unique_ptr<IndexedInstrProfReader> MemProfReader =
930 std::move(ReaderOrErr.get());
931 if (!MemProfReader) {
932 Ctx.diagnose(DiagnosticInfoPGOProfile(
933 MemoryProfileFileName.data(), StringRef("Cannot get MemProfReader")));
934 return PreservedAnalyses::all();
935 }
936
937 if (!MemProfReader->hasMemoryProfile()) {
938 Ctx.diagnose(DiagnosticInfoPGOProfile(MemoryProfileFileName.data(),
939 "Not a memory profile"));
940 return PreservedAnalyses::all();
941 }
942
943 auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
944
945 for (auto &F : M) {
946 if (F.isDeclaration())
947 continue;
948
950 readMemprof(M, F, MemProfReader.get(), TLI);
951 }
952
954}
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))
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 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)
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
static void addCallStack(CallStackTrie &AllocTrie, const AllocationInfo *AllocInfo)
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))
constexpr uint64_t DefaultMemGranularity
Definition: MemProfiler.cpp:62
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 void readMemprof(Module &M, Function &F, IndexedInstrProfReader *MemProfReader, const TargetLibraryInfo &TLI)
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 bool stackFrameIncludesInlinedCallStack(ArrayRef< Frame > ProfileCallStack, ArrayRef< uint64_t > InlinedCallStack, unsigned StartIndex=0)
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))
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.
A container for analyses that lazily runs them and caches their results.
Definition: PassManager.h:321
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Definition: PassManager.h:473
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:539
an instruction that atomically reads a memory location, combines it with another value,...
Definition: Instructions.h:748
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:2881
This is an important base class in LLVM.
Definition: Constant.h:41
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:197
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:2460
Value * CreatePointerCast(Value *V, Type *DestTy, const Twine &Name="")
Definition: IRBuilder.h:2170
Value * CreateIntToPtr(Value *V, Type *DestTy, const Twine &Name="")
Definition: IRBuilder.h:2122
Value * CreateLShr(Value *LHS, Value *RHS, const Twine &Name="", bool isExact=false)
Definition: IRBuilder.h:1437
IntegerType * getInt32Ty()
Fetch the type representing a 32-bit integer.
Definition: IRBuilder.h:526
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:1790
Value * CreateAnd(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:1475
StoreInst * CreateStore(Value *Val, Value *Ptr, bool isVolatile=false)
Definition: IRBuilder.h:1803
Value * CreateAdd(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition: IRBuilder.h:1327
Value * CreateIntCast(Value *V, Type *DestTy, bool isSigned, const Twine &Name="")
Definition: IRBuilder.h:2196
Type * getVoidTy()
Fetch the type representing void.
Definition: IRBuilder.h:564
CallInst * CreateCall(FunctionType *FTy, Value *Callee, ArrayRef< Value * > Args=std::nullopt, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition: IRBuilder.h:2412
Value * CreateGEP(Type *Ty, Value *Ptr, ArrayRef< Value * > IdxList, const Twine &Name="", bool IsInBounds=false)
Definition: IRBuilder.h:1866
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition: IRBuilder.h:2666
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:631
instrprof_error get() const
Definition: InstrProf.h:410
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:184
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:109
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
Definition: Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: Analysis.h:115
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:317
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:398
bool isOSEmscripten() const
Tests whether the OS is Emscripten.
Definition: Triple.h:693
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
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.
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:450
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.
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:970
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
void createProfileFileNameVar(Module &M, StringRef InstrProfileOutput)
Definition: InstrProf.cpp:1447
@ 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:73
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:195
uint32_t LineOffset
Definition: MemProf.h:200