LLVM 24.0.0git
AllocToken.cpp
Go to the documentation of this file.
1//===- AllocToken.cpp - Allocation token instrumentation ------------------===//
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 implements AllocToken, an instrumentation pass that
10// replaces allocation calls with token-enabled versions.
11//
12//===----------------------------------------------------------------------===//
13
16#include "llvm/ADT/DenseMap.h"
18#include "llvm/ADT/Statistic.h"
20#include "llvm/ADT/StringRef.h"
24#include "llvm/IR/Analysis.h"
25#include "llvm/IR/Attributes.h"
26#include "llvm/IR/Constants.h"
28#include "llvm/IR/Function.h"
29#include "llvm/IR/GlobalValue.h"
30#include "llvm/IR/IRBuilder.h"
32#include "llvm/IR/InstrTypes.h"
35#include "llvm/IR/Metadata.h"
36#include "llvm/IR/Module.h"
37#include "llvm/IR/PassManager.h"
38#include "llvm/IR/Type.h"
45#include <cassert>
46#include <cstdint>
47#include <memory>
48#include <optional>
49#include <string>
50#include <utility>
51#include <variant>
52
53using namespace llvm;
55
56#define DEBUG_TYPE "alloc-token"
57
58namespace {
59
60//===--- Statistics -------------------------------------------------------===//
61
62STATISTIC(NumFunctionsModified, "Functions modified");
63STATISTIC(NumAllocationsInstrumented, "Allocations instrumented");
64
65//===----------------------------------------------------------------------===//
66
67/// Returns the !alloc_token metadata if available.
68///
69/// Expected format is: !{<type-name>, <contains-pointer>[, <function-name>]}
70MDNode *getAllocTokenMetadata(const CallBase &CB) {
71 MDNode *Ret = nullptr;
72 if (auto *II = dyn_cast<IntrinsicInst>(&CB);
73 II && II->getIntrinsicID() == Intrinsic::alloc_token_id) {
74 auto *MDV = cast<MetadataAsValue>(II->getArgOperand(0));
75 Ret = cast<MDNode>(MDV->getMetadata());
76 // If the intrinsic has an empty MDNode, type inference failed.
77 if (Ret->getNumOperands() == 0)
78 return nullptr;
79 } else {
80 Ret = CB.getMetadata(LLVMContext::MD_alloc_token);
81 if (!Ret)
82 return nullptr;
83 }
84 assert((Ret->getNumOperands() == 2 || Ret->getNumOperands() == 3) &&
85 "bad !alloc_token");
88 assert(Ret->getNumOperands() == 2 || isa<MDString>(Ret->getOperand(2)));
89 return Ret;
90}
91
92bool containsPointer(const MDNode *MD) {
94 auto *CI = cast<ConstantInt>(C->getValue());
95 return CI->getValue().getBoolValue();
96}
97
98class ModeBase {
99public:
100 explicit ModeBase(const IntegerType &TokenTy, uint64_t MaxTokens)
101 : MaxTokens(MaxTokens ? MaxTokens : TokenTy.getBitMask()) {
102 assert(MaxTokens <= TokenTy.getBitMask());
103 }
104
105protected:
106 uint64_t boundedToken(uint64_t Val) const {
107 assert(MaxTokens != 0);
108 return Val % MaxTokens;
109 }
110
111 const uint64_t MaxTokens;
112};
113
114/// Implementation for TokenMode::Increment.
115class IncrementMode : public ModeBase {
116public:
117 using ModeBase::ModeBase;
118
119 uint64_t operator()(const CallBase &CB, OptimizationRemarkEmitter &) {
120 return boundedToken(Counter++);
121 }
122
123private:
124 uint64_t Counter = 0;
125};
126
127/// Implementation for TokenMode::Random.
128class RandomMode : public ModeBase {
129public:
130 RandomMode(const IntegerType &TokenTy, uint64_t MaxTokens,
131 std::unique_ptr<RandomNumberGenerator> RNG)
132 : ModeBase(TokenTy, MaxTokens), RNG(std::move(RNG)) {}
133 uint64_t operator()(const CallBase &CB, OptimizationRemarkEmitter &) {
134 return boundedToken((*RNG)());
135 }
136
137private:
138 std::unique_ptr<RandomNumberGenerator> RNG;
139};
140
141/// Implementation for TokenMode::TypeHash. The implementation ensures
142/// hashes are stable across different compiler invocations. Uses SipHash as the
143/// hash function.
144class TypeHashMode : public ModeBase {
145public:
146 TypeHashMode(const IntegerType &TokenTy, uint64_t MaxTokens,
147 uint64_t Fallback)
148 : ModeBase(TokenTy, MaxTokens), Fallback(Fallback) {}
149
150 uint64_t operator()(const CallBase &CB, OptimizationRemarkEmitter &ORE) {
151
152 if (MDNode *N = getAllocTokenMetadata(CB)) {
153 MDString *S = cast<MDString>(N->getOperand(0));
154 AllocTokenMetadata Metadata{S->getString(), containsPointer(N)};
155 if (auto Token = getAllocToken(TokenMode::TypeHash, Metadata, MaxTokens))
156 return *Token;
157 }
158 // Fallback.
159 remarkNoMetadata(CB, ORE);
160 return Fallback;
161 }
162
163protected:
164 /// Remark that there was no precise type information.
165 static void remarkNoMetadata(const CallBase &CB,
167 ORE.emit([&] {
168 ore::NV FuncNV("Function", CB.getParent()->getParent());
169 const Function *Callee = CB.getCalledFunction();
170 ore::NV CalleeNV("Callee", Callee ? Callee->getName() : "<unknown>");
171 return OptimizationRemark(DEBUG_TYPE, "NoAllocToken", &CB)
172 << "Call to '" << CalleeNV << "' in '" << FuncNV
173 << "' without source-level type token";
174 });
175 }
176
177 const uint64_t Fallback;
178};
179
180/// Implementation for TokenMode::TypeHashPointerSplit.
181class TypeHashPointerSplitMode : public TypeHashMode {
182public:
183 using TypeHashMode::TypeHashMode;
184
185 uint64_t operator()(const CallBase &CB, OptimizationRemarkEmitter &ORE) {
186 if (MDNode *N = getAllocTokenMetadata(CB)) {
187 MDString *S = cast<MDString>(N->getOperand(0));
188 AllocTokenMetadata Metadata{S->getString(), containsPointer(N)};
190 MaxTokens))
191 return *Token;
192 }
193 // Pick the fallback token, which by default is 0, meaning it'll fall into
194 // the pointer-less bucket. Override by setting -alloc-token-fallback if
195 // that is the wrong choice.
196 remarkNoMetadata(CB, ORE);
197 return Fallback;
198 }
199};
200
201/// Implementation for TokenMode::TypeFuncHash and
202/// TokenMode::TypeFuncHashPointerSplit.
203class TypeFuncHashMode : public TypeHashMode {
204public:
205 TypeFuncHashMode(const IntegerType &TokenTy, uint64_t MaxTokens,
206 uint64_t Fallback, TokenMode Mode)
207 : TypeHashMode(TokenTy, MaxTokens, Fallback), Mode(Mode) {}
208
209 uint64_t operator()(const CallBase &CB, OptimizationRemarkEmitter &ORE) {
210 MDNode *N = getAllocTokenMetadata(CB);
211 if (!N) {
212 remarkNoMetadata(CB, ORE);
213 return Fallback;
214 }
215 // Generated for another mode, whose tokens may already be in the module.
216 if (N->getNumOperands() != 3) {
218 &CB, "!alloc_token without function name is incompatible with mode " +
220 return Fallback;
221 }
222 AllocTokenMetadata Metadata{cast<MDString>(N->getOperand(0))->getString(),
223 containsPointer(N),
224 cast<MDString>(N->getOperand(2))->getString()};
225 if (Metadata.TypeName.empty())
226 remarkNoMetadata(CB, ORE);
227 return *getAllocToken(Mode, Metadata, MaxTokens);
228 }
229
230private:
231 const TokenMode Mode;
232};
233
234// Apply opt overrides and module flags.
235static AllocTokenOptions resolveOptions(const InstrumentationOptions &CLOpts,
237 const Module &M) {
238 auto IntModuleFlagOrNull = [&](StringRef Key) {
239 return mdconst::extract_or_null<ConstantInt>(M.getModuleFlag(Key));
240 };
241
242 if (auto *S = dyn_cast_or_null<MDString>(M.getModuleFlag("alloc-token-mode")))
243 if (auto Mode = getAllocTokenModeFromString(S->getString()))
244 Opts.Mode = *Mode;
245 if (auto *Val = IntModuleFlagOrNull("alloc-token-max"))
246 Opts.MaxTokens = Val->getZExtValue();
247 if (auto *Val = IntModuleFlagOrNull("alloc-token-fast-abi"))
248 Opts.FastABI |= Val->isOne();
249 if (auto *Val = IntModuleFlagOrNull("alloc-token-extended"))
250 Opts.Extended |= Val->isOne();
251
252 // Allow overriding options from command line options.
253 Opts.MaxTokens = CLOpts.alloc_token_max.value_or(Opts.MaxTokens);
254 Opts.FastABI = valueOr(CLOpts.alloc_token_fast_abi, Opts.FastABI);
255 Opts.Extended = valueOr(CLOpts.alloc_token_extended, Opts.Extended);
256
257 return Opts;
258}
259
260class AllocToken {
261public:
262 AllocToken(const InstrumentationOptions &CLOpts, AllocTokenOptions Opts,
264 : CLOpts(CLOpts), Options(resolveOptions(CLOpts, std::move(Opts), M)),
265 Mod(M),
266 FAM(MAM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager()),
267 Mode(IncrementMode(*IntPtrTy, Options.MaxTokens)) {
268 switch (Options.Mode) {
270 break;
272 Mode.emplace<RandomMode>(*IntPtrTy, Options.MaxTokens,
273 M.createRNG(DEBUG_TYPE));
274 break;
276 Mode.emplace<TypeHashMode>(*IntPtrTy, Options.MaxTokens,
277 CLOpts.alloc_token_fallback);
278 break;
280 Mode.emplace<TypeHashPointerSplitMode>(*IntPtrTy, Options.MaxTokens,
281 CLOpts.alloc_token_fallback);
282 break;
285 Mode.emplace<TypeFuncHashMode>(*IntPtrTy, Options.MaxTokens,
286 CLOpts.alloc_token_fallback, Options.Mode);
287 break;
288 }
289 }
290
291 bool instrumentFunction(Function &F);
292
293private:
294 /// Returns the LibFunc (or NotLibFunc) if this call should be instrumented.
295 std::optional<LibFunc>
296 shouldInstrumentCall(const CallBase &CB, const TargetLibraryInfo &TLI) const;
297
298 /// Returns true for functions that are eligible for instrumentation.
299 bool isInstrumentableLibFunc(LibFunc Func, const CallBase &CB) const;
300
301 /// Returns true for isAllocationFn() functions that we should ignore.
302 static bool ignoreInstrumentableLibFunc(LibFunc Func);
303
304 /// Replace a call/invoke with a call/invoke to the allocation function
305 /// with token ID.
306 bool replaceAllocationCall(CallBase *CB, LibFunc Func,
308 const TargetLibraryInfo &TLI);
309
310 /// Return replacement function for a LibFunc that takes a token ID.
311 FunctionCallee getTokenAllocFunction(const CallBase &CB, uint64_t TokenID,
312 LibFunc OriginalFunc);
313
314 /// Lower alloc_token_* intrinsics.
315 void replaceIntrinsicInst(IntrinsicInst *II, OptimizationRemarkEmitter &ORE);
316
317 /// Return the token ID from metadata in the call.
319 return std::visit([&](auto &&Mode) { return Mode(CB, ORE); }, Mode);
320 }
321
322 const InstrumentationOptions &CLOpts;
324 Module &Mod;
325 IntegerType *IntPtrTy = Mod.getDataLayout().getIntPtrType(Mod.getContext());
327 // Cache for replacement functions.
329 // Selected mode.
330 std::variant<IncrementMode, RandomMode, TypeHashMode,
331 TypeHashPointerSplitMode, TypeFuncHashMode>
332 Mode;
333};
334
335bool AllocToken::instrumentFunction(Function &F) {
336 // Do not apply any instrumentation for naked functions.
337 if (F.hasFnAttribute(Attribute::Naked))
338 return false;
339 // Don't touch available_externally functions, their actual body is elsewhere.
340 if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage)
341 return false;
342
344 SmallVector<IntrinsicInst *, 4> IntrinsicInsts;
345
346 // Only instrument functions that have the sanitize_alloc_token attribute.
347 const bool InstrumentFunction =
348 F.hasFnAttribute(Attribute::SanitizeAllocToken) &&
349 !F.hasFnAttribute(Attribute::DisableSanitizerInstrumentation);
350
351 // Get TLI only when required.
352 const TargetLibraryInfo *TLI =
353 InstrumentFunction ? &FAM.getResult<TargetLibraryAnalysis>(F) : nullptr;
354
355 // Collect all allocation calls to avoid iterator invalidation.
356 for (Instruction &I : instructions(F)) {
357 // Collect all alloc_token_* intrinsics.
358 if (auto *II = dyn_cast<IntrinsicInst>(&I);
359 II && II->getIntrinsicID() == Intrinsic::alloc_token_id) {
360 IntrinsicInsts.emplace_back(II);
361 continue;
362 }
363
364 if (!InstrumentFunction)
365 continue;
366
367 auto *CB = dyn_cast<CallBase>(&I);
368 if (!CB)
369 continue;
370 if (std::optional<LibFunc> Func = shouldInstrumentCall(*CB, *TLI))
371 AllocCalls.emplace_back(CB, Func.value());
372 }
373
374 // Return early to avoid unnecessarily instantiating the ORE.
375 if (AllocCalls.empty() && IntrinsicInsts.empty())
376 return false;
377
378 auto &ORE = FAM.getResult<OptimizationRemarkEmitterAnalysis>(F);
379 bool Modified = false;
380
381 for (auto &[CB, Func] : AllocCalls)
382 Modified |= replaceAllocationCall(CB, Func, ORE, *TLI);
383
384 for (auto *II : IntrinsicInsts) {
385 replaceIntrinsicInst(II, ORE);
386 Modified = true;
387 }
388
389 if (Modified)
390 NumFunctionsModified++;
391
392 return Modified;
393}
394
395std::optional<LibFunc>
396AllocToken::shouldInstrumentCall(const CallBase &CB,
397 const TargetLibraryInfo &TLI) const {
398 const Function *Callee = CB.getCalledFunction();
399 if (!Callee)
400 return std::nullopt;
401
402 // Ignore nobuiltin of the CallBase, so that we can cover nobuiltin libcalls
403 // if requested via isInstrumentableLibFunc(). Note that isAllocationFn() is
404 // returning false for nobuiltin calls.
405 LibFunc Func = TLI.getLibFunc(*Callee);
406 if (Func != NotLibFunc) {
407 if (isInstrumentableLibFunc(Func, CB))
408 return Func;
409 } else if (Options.Extended && CB.getMetadata(LLVMContext::MD_alloc_token)) {
410 return NotLibFunc;
411 }
412
413 return std::nullopt;
414}
415
416bool AllocToken::isInstrumentableLibFunc(LibFunc Func,
417 const CallBase &CB) const {
418 if (ignoreInstrumentableLibFunc(Func))
419 return false;
420
421 if (isAllocationFn(&CB))
422 return true;
423
424 switch (Func) {
425 // These libfuncs don't return normal pointers, and are therefore not handled
426 // by isAllocationFn().
427 case LibFunc_posix_memalign:
428 case LibFunc_size_returning_new:
429 case LibFunc_size_returning_new_hot_cold:
430 case LibFunc_size_returning_new_aligned:
431 case LibFunc_size_returning_new_aligned_hot_cold:
432 return true;
433
434 // See the comment on -alloc-token-cover-replaceable-new.
435 case LibFunc_Znwj:
436 case LibFunc_ZnwjRKSt9nothrow_t:
437 case LibFunc_ZnwjSt11align_val_t:
438 case LibFunc_ZnwjSt11align_val_tRKSt9nothrow_t:
439 case LibFunc_Znwm:
440 case LibFunc_Znwm12__hot_cold_t:
441 case LibFunc_ZnwmRKSt9nothrow_t:
442 case LibFunc_ZnwmRKSt9nothrow_t12__hot_cold_t:
443 case LibFunc_ZnwmSt11align_val_t:
444 case LibFunc_ZnwmSt11align_val_t12__hot_cold_t:
445 case LibFunc_ZnwmSt11align_val_tRKSt9nothrow_t:
446 case LibFunc_ZnwmSt11align_val_tRKSt9nothrow_t12__hot_cold_t:
447 case LibFunc_Znaj:
448 case LibFunc_ZnajRKSt9nothrow_t:
449 case LibFunc_ZnajSt11align_val_t:
450 case LibFunc_ZnajSt11align_val_tRKSt9nothrow_t:
451 case LibFunc_Znam:
452 case LibFunc_Znam12__hot_cold_t:
453 case LibFunc_ZnamRKSt9nothrow_t:
454 case LibFunc_ZnamRKSt9nothrow_t12__hot_cold_t:
455 case LibFunc_ZnamSt11align_val_t:
456 case LibFunc_ZnamSt11align_val_t12__hot_cold_t:
457 case LibFunc_ZnamSt11align_val_tRKSt9nothrow_t:
458 case LibFunc_ZnamSt11align_val_tRKSt9nothrow_t12__hot_cold_t:
459 case LibFunc_msvc_new_int:
460 case LibFunc_msvc_new_int_nothrow:
461 case LibFunc_msvc_new_longlong:
462 case LibFunc_msvc_new_longlong_nothrow:
463 case LibFunc_msvc_new_array_int:
464 case LibFunc_msvc_new_array_int_nothrow:
465 case LibFunc_msvc_new_array_longlong:
466 case LibFunc_msvc_new_array_longlong_nothrow:
467 return CLOpts.alloc_token_cover_replaceable_new;
468
469 default:
470 return false;
471 }
472}
473
474bool AllocToken::ignoreInstrumentableLibFunc(LibFunc Func) {
475 switch (Func) {
476 case LibFunc_strdup:
477 case LibFunc_dunder_strdup:
478 case LibFunc_strndup:
479 case LibFunc_dunder_strndup:
480 return true;
481 default:
482 return false;
483 }
484}
485
486bool AllocToken::replaceAllocationCall(CallBase *CB, LibFunc Func,
488 const TargetLibraryInfo &TLI) {
489 uint64_t TokenID = getToken(*CB, ORE);
490
491 FunctionCallee TokenAlloc = getTokenAllocFunction(*CB, TokenID, Func);
492 if (!TokenAlloc)
493 return false;
494 NumAllocationsInstrumented++;
495
496 if (Options.FastABI) {
497 assert(TokenAlloc.getFunctionType()->getNumParams() == CB->arg_size());
498 CB->setCalledFunction(TokenAlloc);
499 return true;
500 }
501
502 IRBuilder<> IRB(CB);
503 // Original args.
504 SmallVector<Value *, 4> NewArgs{CB->args()};
505 // Add token ID, truncated to IntPtrTy width.
506 NewArgs.push_back(ConstantInt::get(IntPtrTy, TokenID));
507 assert(TokenAlloc.getFunctionType()->getNumParams() == NewArgs.size());
508
510 CB->getOperandBundlesAsDefs(Bundles);
511
512 // Preserve invoke vs call semantics for exception handling.
513 CallBase *NewCall;
514 if (auto *II = dyn_cast<InvokeInst>(CB)) {
515 NewCall = IRB.CreateInvoke(TokenAlloc, II->getNormalDest(),
516 II->getUnwindDest(), NewArgs, Bundles);
517 } else {
518 NewCall = IRB.CreateCall(TokenAlloc, NewArgs, Bundles);
519 cast<CallInst>(NewCall)->setTailCall(CB->isTailCall());
520 }
521 NewCall->setCallingConv(CB->getCallingConv());
522 NewCall->copyMetadata(*CB);
523 NewCall->setAttributes(CB->getAttributes());
524
525 // Replace all uses and delete the old call.
526 CB->replaceAllUsesWith(NewCall);
527 CB->eraseFromParent();
528 return true;
529}
530
531FunctionCallee AllocToken::getTokenAllocFunction(const CallBase &CB,
532 uint64_t TokenID,
533 LibFunc OriginalFunc) {
534 std::optional<std::pair<LibFunc, uint64_t>> Key;
535 if (OriginalFunc != NotLibFunc) {
536 Key = std::make_pair(OriginalFunc, Options.FastABI ? TokenID : 0);
537 auto It = TokenAllocFunctions.find(*Key);
538 if (It != TokenAllocFunctions.end())
539 return It->second;
540 }
541
542 const Function *Callee = CB.getCalledFunction();
543 if (!Callee)
544 return FunctionCallee();
545 const FunctionType *OldFTy = Callee->getFunctionType();
546 if (OldFTy->isVarArg())
547 return FunctionCallee();
548 // Copy params, and append token ID type.
549 Type *RetTy = OldFTy->getReturnType();
550 SmallVector<Type *, 4> NewParams{OldFTy->params()};
551 std::string TokenAllocName = CLOpts.alloc_token_prefix.str();
552 if (Options.FastABI)
553 TokenAllocName += utostr(TokenID) + "_";
554 else
555 NewParams.push_back(IntPtrTy); // token ID
556 TokenAllocName += Callee->getName();
557 FunctionType *NewFTy = FunctionType::get(RetTy, NewParams, false);
558 AttributeList NewAttrs = Callee->getAttributes();
559 FunctionCallee TokenAlloc =
560 Mod.getOrInsertFunction(TokenAllocName, NewFTy, NewAttrs);
561
562 if (Key.has_value())
563 TokenAllocFunctions[*Key] = TokenAlloc;
564 return TokenAlloc;
565}
566
567void AllocToken::replaceIntrinsicInst(IntrinsicInst *II,
569 assert(II->getIntrinsicID() == Intrinsic::alloc_token_id);
570
571 uint64_t TokenID = getToken(*II, ORE);
572 Value *V = ConstantInt::get(IntPtrTy, TokenID);
573 II->replaceAllUsesWith(V);
574 II->eraseFromParent();
575}
576
577} // namespace
578
581
583 const InstrumentationOptions &CLOpts = getInstrumentationOptions(M);
584 AllocToken Pass(CLOpts, Options, M, MAM);
586 MAM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
587 bool Modified = false;
588
589 for (Function &F : M) {
590 if (F.empty())
591 continue; // declaration
592 if (Pass.instrumentFunction(F)) {
593 FAM.invalidate(F, PreservedAnalyses::none().preserveSet<CFGAnalyses>());
594 Modified = true;
595 }
596 }
597
598 if (!Modified)
599 return PreservedAnalyses::all();
600
604 return PA;
605}
const TargetLowering & TLI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
Expand Atomic instructions
This file contains the simple types necessary to represent the attributes associated with functions a...
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
This file defines the DenseMap class.
#define DEBUG_TYPE
Module.h This file contains the declarations for the Module class.
This header defines various interfaces for pass management in LLVM.
static LVOptions Options
Definition LVOptions.cpp:25
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
print mir2vec MIR2Vec Vocabulary Printer Pass
Definition MIR2Vec.cpp:668
static MemorySanitizerOptions resolveOptions(const InstrumentationOptions &Opts, MemorySanitizerOptions O)
This file contains the declarations for metadata subclasses.
uint64_t IntrinsicInst * II
if(auto Err=PB.parsePassPipeline(MPM, Passes)) return wrap(std MPM run * Mod
FunctionAnalysisManager FAM
ModuleAnalysisManager MAM
static cl::opt< RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode > Mode("regalloc-enable-advisor", cl::Hidden, cl::init(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default), cl::desc("Enable regalloc advisor mode"), cl::values(clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default, "default", "Default"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Release, "release", "precompiled"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Development, "development", "for training")))
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:171
This file contains some functions that are useful when dealing with strings.
AllocTokenMode TokenMode
This templated class represents "all analyses that operate over <aparticular IR unit>" (e....
Definition Analysis.h:50
LLVM_ABI AllocTokenPass(AllocTokenOptions Opts={})
LLVM_ABI PreservedAnalyses run(Module &M, ModuleAnalysisManager &MAM)
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
void setCallingConv(CallingConv::ID CC)
LLVM_ABI void getOperandBundlesAsDefs(SmallVectorImpl< OperandBundleDef > &Defs) const
Return the list of operand bundles attached to this instruction as a vector of OperandBundleDefs.
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation or the function signa...
CallingConv::ID getCallingConv() const
void setAttributes(AttributeList A)
Set the attributes for this call.
iterator_range< User::op_iterator > args()
Iteration adapter for range-for loops.
unsigned arg_size() const
AttributeList getAttributes() const
Return the attributes for this call.
void setCalledFunction(Function *Fn)
Sets the function called, including updating the function type.
LLVM_ABI bool isTailCall() const
Tests if this call site is marked as a tail call.
void setTailCall(bool IsTc=true)
A handy container for a FunctionType+Callee-pointer pair, which can be passed around as a single enti...
FunctionType * getFunctionType()
unsigned getNumParams() const
Return the number of fixed parameters this function type requires.
static LLVM_ABI FunctionType * get(Type *Result, ArrayRef< Type * > Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
@ AvailableExternallyLinkage
Available for inspection, not emission.
Definition GlobalValue.h:54
InvokeInst * CreateInvoke(FunctionType *Ty, Value *Callee, BasicBlock *NormalDest, BasicBlock *UnwindDest, ArrayRef< Value * > Args, ArrayRef< OperandBundleDef > OpBundles, const Twine &Name="")
Create an invoke instruction.
Definition IRBuilder.h:1256
CallInst * CreateCall(FunctionType *FTy, Value *Callee, ArrayRef< Value * > Args={}, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition IRBuilder.h:2640
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2990
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
LLVM_ABI void copyMetadata(const Instruction &SrcInst, ArrayRef< unsigned > WL=ArrayRef< unsigned >())
Copy metadata from SrcInst to this instruction.
Class to represent integer types.
uint64_t getBitMask() const
Return a bitmask with ones set for all of the bits that can be set by an unsigned version of this typ...
A wrapper class for inspecting calls to intrinsic functions.
LLVM_ABI void emitError(const Instruction *I, const Twine &ErrorStr)
emitError - Emit an error message to the currently installed error handler with optional location inf...
Metadata node.
Definition Metadata.h:1087
const MDOperand & getOperand(unsigned I) const
Definition Metadata.h:1443
unsigned getNumOperands() const
Return number of MDNode operands.
Definition Metadata.h:1449
A single uniqued string.
Definition Metadata.h:734
LLVM_ABI StringRef getString() const
Definition Metadata.cpp:613
Root of the metadata hierarchy.
Definition Metadata.h:65
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
The optimization diagnostic interface.
LLVM_ABI void emit(DiagnosticInfoOptimizationBase &OptDiag)
Output the remark via the diagnostic handler and to the optimization record file.
Diagnostic information for applied optimization remarks.
Pass interface - Implemented by all 'passes'.
Definition Pass.h:97
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
Definition Analysis.h:115
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalyses & preserveSet()
Mark an analysis set as preserved.
Definition Analysis.h:151
PreservedAnalyses & preserve()
Mark an analysis as preserved.
Definition Analysis.h:132
reference emplace_back(ArgTypes &&... Args)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
Analysis pass providing the TargetLibraryInfo.
Provides information about what library functions are available for the current target.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
LLVM Value Representation.
Definition Value.h:75
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:548
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:260
const ParentTy * getParent() const
Definition ilist_node.h:34
Pass manager infrastructure for declaring and invalidating analyses.
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > extract_or_null(Y &&MD)
Extract a Value from Metadata, allowing null.
Definition Metadata.h:695
DiagnosticInfoOptimizationBase::Argument NV
This is an optimization pass for GlobalISel generic memory operations.
const InstrumentationOptions & getInstrumentationOptions(const LLVMContext &C)
LLVM_ABI std::optional< uint64_t > getAllocToken(AllocTokenMode Mode, const AllocTokenMetadata &Metadata, uint64_t MaxTokens)
Calculates stable allocation token ID.
LLVM_ABI std::pair< StringRef, StringRef > getToken(StringRef Source, StringRef Delimiters=" \t\n\v\f\r")
getToken - This function extracts one token from source, ignoring any leading characters that appear ...
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
InnerAnalysisManagerProxy< FunctionAnalysisManager, Module > FunctionAnalysisManagerModuleProxy
Provide the FunctionAnalysisManager to Module proxy.
std::string utostr(uint64_t X, bool isNeg=false)
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
@ Mod
The access may modify the value stored in memory.
Definition ModRef.h:34
LLVM_ABI bool isAllocationFn(const Value *V)
Tests if a value is a call or invoke to a library function that allocates or reallocates memory (eith...
IntPtrTy
Definition InstrProf.h:82
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1933
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
constexpr bool valueOr(BoolOrDefault X, bool Default)
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
AllocTokenMode
Modes for generating allocation token IDs.
Definition AllocToken.h:24
@ TypeFuncHashPointerSplit
Like TypeFuncHash, but for MaxTokens > 1 the most significant bit of the ID space is set for types th...
Definition AllocToken.h:46
@ TypeHash
Token ID based on allocated type hash.
Definition AllocToken.h:32
@ Random
Simple mode that returns a statically-assigned random token ID.
Definition AllocToken.h:29
@ Increment
Incrementally increasing token ID.
Definition AllocToken.h:26
@ TypeFuncHash
Token ID based on allocated type hash and containing function name hash.
Definition AllocToken.h:42
@ TypeHashPointerSplit
Token ID based on allocated type hash, where the top half ID-space is reserved for types that contain...
Definition AllocToken.h:37
LLVM_ABI std::optional< AllocTokenMode > getAllocTokenModeFromString(StringRef Name)
Returns the AllocTokenMode from its canonical string name; if an invalid name was provided returns nu...
LLVM_ABI StringRef getAllocTokenModeAsString(AllocTokenMode Mode)
Returns the canonical string name for the given AllocTokenMode.
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
Definition MIRParser.h:39
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:879
#define N
Metadata about an allocation used to generate a token ID.
Definition AllocToken.h:62
AllocTokenMode Mode
Definition AllocToken.h:27