LLVM 20.0.0git
ModuleUtils.cpp
Go to the documentation of this file.
1//===-- ModuleUtils.cpp - Functions to manipulate Modules -----------------===//
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 family of functions perform manipulations on Modules.
10//
11//===----------------------------------------------------------------------===//
12
17#include "llvm/IR/Function.h"
18#include "llvm/IR/IRBuilder.h"
19#include "llvm/IR/MDBuilder.h"
20#include "llvm/IR/Module.h"
21#include "llvm/Support/MD5.h"
23#include "llvm/Support/xxhash.h"
24
25using namespace llvm;
26
27#define DEBUG_TYPE "moduleutils"
28
29static void appendToGlobalArray(StringRef ArrayName, Module &M, Function *F,
30 int Priority, Constant *Data) {
31 IRBuilder<> IRB(M.getContext());
32 FunctionType *FnTy = FunctionType::get(IRB.getVoidTy(), false);
33
34 // Get the current set of static global constructors and add the new ctor
35 // to the list.
36 SmallVector<Constant *, 16> CurrentCtors;
37 StructType *EltTy;
38 if (GlobalVariable *GVCtor = M.getNamedGlobal(ArrayName)) {
39 EltTy = cast<StructType>(GVCtor->getValueType()->getArrayElementType());
40 if (Constant *Init = GVCtor->getInitializer()) {
41 unsigned n = Init->getNumOperands();
42 CurrentCtors.reserve(n + 1);
43 for (unsigned i = 0; i != n; ++i)
44 CurrentCtors.push_back(cast<Constant>(Init->getOperand(i)));
45 }
46 GVCtor->eraseFromParent();
47 } else {
48 EltTy = StructType::get(IRB.getInt32Ty(),
49 PointerType::get(FnTy, F->getAddressSpace()),
50 IRB.getPtrTy());
51 }
52
53 // Build a 3 field global_ctor entry. We don't take a comdat key.
54 Constant *CSVals[3];
55 CSVals[0] = IRB.getInt32(Priority);
56 CSVals[1] = F;
57 CSVals[2] = Data ? ConstantExpr::getPointerCast(Data, IRB.getPtrTy())
59 Constant *RuntimeCtorInit =
60 ConstantStruct::get(EltTy, ArrayRef(CSVals, EltTy->getNumElements()));
61
62 CurrentCtors.push_back(RuntimeCtorInit);
63
64 // Create a new initializer.
65 ArrayType *AT = ArrayType::get(EltTy, CurrentCtors.size());
66 Constant *NewInit = ConstantArray::get(AT, CurrentCtors);
67
68 // Create the new global variable and replace all uses of
69 // the old global variable with the new one.
70 (void)new GlobalVariable(M, NewInit->getType(), false,
71 GlobalValue::AppendingLinkage, NewInit, ArrayName);
72}
73
74void llvm::appendToGlobalCtors(Module &M, Function *F, int Priority, Constant *Data) {
75 appendToGlobalArray("llvm.global_ctors", M, F, Priority, Data);
76}
77
78void llvm::appendToGlobalDtors(Module &M, Function *F, int Priority, Constant *Data) {
79 appendToGlobalArray("llvm.global_dtors", M, F, Priority, Data);
80}
81
82static void transformGlobalArray(StringRef ArrayName, Module &M,
83 const GlobalCtorTransformFn &Fn) {
84 GlobalVariable *GVCtor = M.getNamedGlobal(ArrayName);
85 if (!GVCtor)
86 return;
87
88 IRBuilder<> IRB(M.getContext());
89 SmallVector<Constant *, 16> CurrentCtors;
90 bool Changed = false;
91 StructType *EltTy =
92 cast<StructType>(GVCtor->getValueType()->getArrayElementType());
93 if (Constant *Init = GVCtor->getInitializer()) {
94 CurrentCtors.reserve(Init->getNumOperands());
95 for (Value *OP : Init->operands()) {
96 Constant *C = cast<Constant>(OP);
97 Constant *NewC = Fn(C);
98 Changed |= (!NewC || NewC != C);
99 if (NewC)
100 CurrentCtors.push_back(NewC);
101 }
102 }
103 if (!Changed)
104 return;
105
106 GVCtor->eraseFromParent();
107
108 // Create a new initializer.
109 ArrayType *AT = ArrayType::get(EltTy, CurrentCtors.size());
110 Constant *NewInit = ConstantArray::get(AT, CurrentCtors);
111
112 // Create the new global variable and replace all uses of
113 // the old global variable with the new one.
114 (void)new GlobalVariable(M, NewInit->getType(), false,
115 GlobalValue::AppendingLinkage, NewInit, ArrayName);
116}
117
119 transformGlobalArray("llvm.global_ctors", M, Fn);
120}
121
123 transformGlobalArray("llvm.global_dtors", M, Fn);
124}
125
128 if (!GV || !GV->hasInitializer())
129 return;
130
131 auto *CA = cast<ConstantArray>(GV->getInitializer());
132 for (Use &Op : CA->operands())
133 Init.insert(cast<Constant>(Op));
134}
135
137 GlobalVariable *GV = M.getGlobalVariable(Name);
138
141 if (GV)
142 GV->eraseFromParent();
143
144 Type *ArrayEltTy = llvm::PointerType::getUnqual(M.getContext());
145 for (auto *V : Values)
147
148 if (Init.empty())
149 return;
150
151 ArrayType *ATy = ArrayType::get(ArrayEltTy, Init.size());
153 ConstantArray::get(ATy, Init.getArrayRef()),
154 Name);
155 GV->setSection("llvm.metadata");
156}
157
159 appendToUsedList(M, "llvm.used", Values);
160}
161
163 appendToUsedList(M, "llvm.compiler.used", Values);
164}
165
167 function_ref<bool(Constant *)> ShouldRemove) {
168 GlobalVariable *GV = M.getNamedGlobal(Name);
169 if (!GV)
170 return;
171
174
175 Type *ArrayEltTy = cast<ArrayType>(GV->getValueType())->getElementType();
176
178 for (Constant *MaybeRemoved : Init) {
179 if (!ShouldRemove(MaybeRemoved->stripPointerCasts()))
180 NewInit.push_back(MaybeRemoved);
181 }
182
183 if (!NewInit.empty()) {
184 ArrayType *ATy = ArrayType::get(ArrayEltTy, NewInit.size());
185 GlobalVariable *NewGV =
187 ConstantArray::get(ATy, NewInit), "", GV,
189 NewGV->setSection(GV->getSection());
190 NewGV->takeName(GV);
191 }
192
193 GV->eraseFromParent();
194}
195
197 function_ref<bool(Constant *)> ShouldRemove) {
198 removeFromUsedList(M, "llvm.used", ShouldRemove);
199 removeFromUsedList(M, "llvm.compiler.used", ShouldRemove);
200}
201
202void llvm::setKCFIType(Module &M, Function &F, StringRef MangledType) {
203 if (!M.getModuleFlag("kcfi"))
204 return;
205 // Matches CodeGenModule::CreateKCFITypeId in Clang.
206 LLVMContext &Ctx = M.getContext();
207 MDBuilder MDB(Ctx);
208 std::string Type = MangledType.str();
209 if (M.getModuleFlag("cfi-normalize-integers"))
210 Type += ".normalized";
211 F.setMetadata(LLVMContext::MD_kcfi_type,
212 MDNode::get(Ctx, MDB.createConstant(ConstantInt::get(
213 Type::getInt32Ty(Ctx),
214 static_cast<uint32_t>(xxHash64(Type))))));
215 // If the module was compiled with -fpatchable-function-entry, ensure
216 // we use the same patchable-function-prefix.
217 if (auto *MD = mdconst::extract_or_null<ConstantInt>(
218 M.getModuleFlag("kcfi-offset"))) {
219 if (unsigned Offset = MD->getZExtValue())
220 F.addFnAttr("patchable-function-prefix", std::to_string(Offset));
221 }
222}
223
225 ArrayRef<Type *> InitArgTypes,
226 bool Weak) {
227 assert(!InitName.empty() && "Expected init function name");
228 auto *VoidTy = Type::getVoidTy(M.getContext());
229 auto *FnTy = FunctionType::get(VoidTy, InitArgTypes, false);
230 auto FnCallee = M.getOrInsertFunction(InitName, FnTy);
231 auto *Fn = cast<Function>(FnCallee.getCallee());
232 if (Weak && Fn->isDeclaration())
233 Fn->setLinkage(Function::ExternalWeakLinkage);
234 return FnCallee;
235}
236
239 FunctionType::get(Type::getVoidTy(M.getContext()), false),
240 GlobalValue::InternalLinkage, M.getDataLayout().getProgramAddressSpace(),
241 CtorName, &M);
242 Ctor->addFnAttr(Attribute::NoUnwind);
243 setKCFIType(M, *Ctor, "_ZTSFvvE"); // void (*)(void)
244 BasicBlock *CtorBB = BasicBlock::Create(M.getContext(), "", Ctor);
245 ReturnInst::Create(M.getContext(), CtorBB);
246 // Ensure Ctor cannot be discarded, even if in a comdat.
247 appendToUsed(M, {Ctor});
248 return Ctor;
249}
250
251std::pair<Function *, FunctionCallee> llvm::createSanitizerCtorAndInitFunctions(
252 Module &M, StringRef CtorName, StringRef InitName,
253 ArrayRef<Type *> InitArgTypes, ArrayRef<Value *> InitArgs,
254 StringRef VersionCheckName, bool Weak) {
255 assert(!InitName.empty() && "Expected init function name");
256 assert(InitArgs.size() == InitArgTypes.size() &&
257 "Sanitizer's init function expects different number of arguments");
258 FunctionCallee InitFunction =
259 declareSanitizerInitFunction(M, InitName, InitArgTypes, Weak);
260 Function *Ctor = createSanitizerCtor(M, CtorName);
261 IRBuilder<> IRB(M.getContext());
262
263 BasicBlock *RetBB = &Ctor->getEntryBlock();
264 if (Weak) {
265 RetBB->setName("ret");
266 auto *EntryBB = BasicBlock::Create(M.getContext(), "entry", Ctor, RetBB);
267 auto *CallInitBB =
268 BasicBlock::Create(M.getContext(), "callfunc", Ctor, RetBB);
269 auto *InitFn = cast<Function>(InitFunction.getCallee());
270 auto *InitFnPtr =
271 PointerType::get(InitFn->getType(), InitFn->getAddressSpace());
272 IRB.SetInsertPoint(EntryBB);
273 Value *InitNotNull =
274 IRB.CreateICmpNE(InitFn, ConstantPointerNull::get(InitFnPtr));
275 IRB.CreateCondBr(InitNotNull, CallInitBB, RetBB);
276 IRB.SetInsertPoint(CallInitBB);
277 } else {
278 IRB.SetInsertPoint(RetBB->getTerminator());
279 }
280
281 IRB.CreateCall(InitFunction, InitArgs);
282 if (!VersionCheckName.empty()) {
283 FunctionCallee VersionCheckFunction = M.getOrInsertFunction(
284 VersionCheckName, FunctionType::get(IRB.getVoidTy(), {}, false),
285 AttributeList());
286 IRB.CreateCall(VersionCheckFunction, {});
287 }
288
289 if (Weak)
290 IRB.CreateBr(RetBB);
291
292 return std::make_pair(Ctor, InitFunction);
293}
294
295std::pair<Function *, FunctionCallee>
297 Module &M, StringRef CtorName, StringRef InitName,
298 ArrayRef<Type *> InitArgTypes, ArrayRef<Value *> InitArgs,
299 function_ref<void(Function *, FunctionCallee)> FunctionsCreatedCallback,
300 StringRef VersionCheckName, bool Weak) {
301 assert(!CtorName.empty() && "Expected ctor function name");
302
303 if (Function *Ctor = M.getFunction(CtorName))
304 // FIXME: Sink this logic into the module, similar to the handling of
305 // globals. This will make moving to a concurrent model much easier.
306 if (Ctor->arg_empty() ||
307 Ctor->getReturnType() == Type::getVoidTy(M.getContext()))
308 return {Ctor,
309 declareSanitizerInitFunction(M, InitName, InitArgTypes, Weak)};
310
311 Function *Ctor;
312 FunctionCallee InitFunction;
313 std::tie(Ctor, InitFunction) = llvm::createSanitizerCtorAndInitFunctions(
314 M, CtorName, InitName, InitArgTypes, InitArgs, VersionCheckName, Weak);
315 FunctionsCreatedCallback(Ctor, InitFunction);
316 return std::make_pair(Ctor, InitFunction);
317}
318
320 SmallVectorImpl<Function *> &DeadComdatFunctions) {
321 SmallPtrSet<Function *, 32> MaybeDeadFunctions;
322 SmallPtrSet<Comdat *, 32> MaybeDeadComdats;
323 for (Function *F : DeadComdatFunctions) {
324 MaybeDeadFunctions.insert(F);
325 if (Comdat *C = F->getComdat())
326 MaybeDeadComdats.insert(C);
327 }
328
329 // Find comdats for which all users are dead now.
330 SmallPtrSet<Comdat *, 32> DeadComdats;
331 for (Comdat *C : MaybeDeadComdats) {
332 auto IsUserDead = [&](GlobalObject *GO) {
333 auto *F = dyn_cast<Function>(GO);
334 return F && MaybeDeadFunctions.contains(F);
335 };
336 if (all_of(C->getUsers(), IsUserDead))
337 DeadComdats.insert(C);
338 }
339
340 // Only keep functions which have no comdat or a dead comdat.
341 erase_if(DeadComdatFunctions, [&](Function *F) {
342 Comdat *C = F->getComdat();
343 return C && !DeadComdats.contains(C);
344 });
345}
346
348 MD5 Md5;
349 bool ExportsSymbols = false;
350 auto AddGlobal = [&](GlobalValue &GV) {
351 if (GV.isDeclaration() || GV.getName().starts_with("llvm.") ||
352 !GV.hasExternalLinkage() || GV.hasComdat())
353 return;
354 ExportsSymbols = true;
355 Md5.update(GV.getName());
357 };
358
359 for (auto &F : *M)
360 AddGlobal(F);
361 for (auto &GV : M->globals())
362 AddGlobal(GV);
363 for (auto &GA : M->aliases())
364 AddGlobal(GA);
365 for (auto &IF : M->ifuncs())
366 AddGlobal(IF);
367
368 if (!ExportsSymbols)
369 return "";
370
372 Md5.final(R);
373
374 SmallString<32> Str;
375 MD5::stringifyResult(R, Str);
376 return ("." + Str).str();
377}
378
380 StringRef SectionName, Align Alignment) {
381 // Embed the memory buffer into the module.
382 Constant *ModuleConstant = ConstantDataArray::get(
383 M.getContext(), ArrayRef(Buf.getBufferStart(), Buf.getBufferSize()));
385 M, ModuleConstant->getType(), true, GlobalValue::PrivateLinkage,
386 ModuleConstant, "llvm.embedded.object");
388 GV->setAlignment(Alignment);
389
390 LLVMContext &Ctx = M.getContext();
391 NamedMDNode *MD = M.getOrInsertNamedMetadata("llvm.embedded.objects");
392 Metadata *MDVals[] = {ConstantAsMetadata::get(GV),
394
395 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
396 GV->setMetadata(LLVMContext::MD_exclude, llvm::MDNode::get(Ctx, {}));
397
399}
400
402 Module &M, ArrayRef<GlobalIFunc *> FilteredIFuncsToLower) {
404 ArrayRef<GlobalIFunc *> IFuncsToLower = FilteredIFuncsToLower;
405 if (FilteredIFuncsToLower.empty()) { // Default to lowering all ifuncs
406 for (GlobalIFunc &GI : M.ifuncs())
407 AllIFuncs.push_back(&GI);
408 IFuncsToLower = AllIFuncs;
409 }
410
411 bool UnhandledUsers = false;
412 LLVMContext &Ctx = M.getContext();
413 const DataLayout &DL = M.getDataLayout();
414
415 PointerType *TableEntryTy =
416 PointerType::get(Ctx, DL.getProgramAddressSpace());
417
418 ArrayType *FuncPtrTableTy =
419 ArrayType::get(TableEntryTy, IFuncsToLower.size());
420
421 Align PtrAlign = DL.getABITypeAlign(TableEntryTy);
422
423 // Create a global table of function pointers we'll initialize in a global
424 // constructor.
425 auto *FuncPtrTable = new GlobalVariable(
426 M, FuncPtrTableTy, false, GlobalValue::InternalLinkage,
427 PoisonValue::get(FuncPtrTableTy), "", nullptr,
428 GlobalVariable::NotThreadLocal, DL.getDefaultGlobalsAddressSpace());
429 FuncPtrTable->setAlignment(PtrAlign);
430
431 // Create a function to initialize the function pointer table.
432 Function *NewCtor = Function::Create(
433 FunctionType::get(Type::getVoidTy(Ctx), false), Function::InternalLinkage,
434 DL.getProgramAddressSpace(), "", &M);
435
436 BasicBlock *BB = BasicBlock::Create(Ctx, "", NewCtor);
437 IRBuilder<> InitBuilder(BB);
438
439 size_t TableIndex = 0;
440 for (GlobalIFunc *GI : IFuncsToLower) {
441 Function *ResolvedFunction = GI->getResolverFunction();
442
443 // We don't know what to pass to a resolver function taking arguments
444 //
445 // FIXME: Is this even valid? clang and gcc don't complain but this
446 // probably should be invalid IR. We could just pass through undef.
447 if (!std::empty(ResolvedFunction->getFunctionType()->params())) {
448 LLVM_DEBUG(dbgs() << "Not lowering ifunc resolver function "
449 << ResolvedFunction->getName() << " with parameters\n");
450 UnhandledUsers = true;
451 continue;
452 }
453
454 // Initialize the function pointer table.
455 CallInst *ResolvedFunc = InitBuilder.CreateCall(ResolvedFunction);
456 Value *Casted = InitBuilder.CreatePointerCast(ResolvedFunc, TableEntryTy);
457 Constant *GEP = cast<Constant>(InitBuilder.CreateConstInBoundsGEP2_32(
458 FuncPtrTableTy, FuncPtrTable, 0, TableIndex++));
459 InitBuilder.CreateAlignedStore(Casted, GEP, PtrAlign);
460
461 // Update all users to load a pointer from the global table.
462 for (User *User : make_early_inc_range(GI->users())) {
463 Instruction *UserInst = dyn_cast<Instruction>(User);
464 if (!UserInst) {
465 // TODO: Should handle constantexpr casts in user instructions. Probably
466 // can't do much about constant initializers.
467 UnhandledUsers = true;
468 continue;
469 }
470
471 IRBuilder<> UseBuilder(UserInst);
472 LoadInst *ResolvedTarget =
473 UseBuilder.CreateAlignedLoad(TableEntryTy, GEP, PtrAlign);
474 Value *ResolvedCast =
475 UseBuilder.CreatePointerCast(ResolvedTarget, GI->getType());
476 UserInst->replaceUsesOfWith(GI, ResolvedCast);
477 }
478
479 // If we handled all users, erase the ifunc.
480 if (GI->use_empty())
481 GI->eraseFromParent();
482 }
483
484 InitBuilder.CreateRetVoid();
485
486 PointerType *ConstantDataTy = PointerType::get(Ctx, 0);
487
488 // TODO: Is this the right priority? Probably should be before any other
489 // constructors?
490 const int Priority = 10;
491 appendToGlobalCtors(M, NewCtor, Priority,
492 ConstantPointerNull::get(ConstantDataTy));
493 return UnhandledUsers;
494}
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
#define LLVM_DEBUG(X)
Definition: Debug.h:101
std::string Name
Hexagon Common GEP
#define F(x, y, z)
Definition: MD5.cpp:55
static void appendToUsedList(Module &M, StringRef Name, ArrayRef< GlobalValue * > Values)
static void collectUsedGlobals(GlobalVariable *GV, SmallSetVector< Constant *, 16 > &Init)
static void transformGlobalArray(StringRef ArrayName, Module &M, const GlobalCtorTransformFn &Fn)
Definition: ModuleUtils.cpp:82
static void removeFromUsedList(Module &M, StringRef Name, function_ref< bool(Constant *)> ShouldRemove)
static void appendToGlobalArray(StringRef ArrayName, Module &M, Function *F, int Priority, Constant *Data)
Definition: ModuleUtils.cpp:29
Module.h This file contains the declarations for the Module class.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
#define OP(OPC)
Definition: SandboxIR.h:653
This file defines the SmallString class.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
size_t size() const
size - Get the array size.
Definition: ArrayRef.h:165
bool empty() const
empty - Check if the array is empty.
Definition: ArrayRef.h:160
Class to represent array types.
Definition: DerivedTypes.h:371
LLVM Basic Block Representation.
Definition: BasicBlock.h:61
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition: BasicBlock.h:212
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
Definition: BasicBlock.h:239
This class represents a function call, abstracting a target machine's calling convention.
static Constant * get(ArrayType *T, ArrayRef< Constant * > V)
Definition: Constants.cpp:1292
static ConstantAsMetadata * get(Constant *C)
Definition: Metadata.h:528
static Constant * get(LLVMContext &Context, ArrayRef< ElementTy > Elts)
get() constructor - Return a constant with array type with an element count and element type matching...
Definition: Constants.h:706
static Constant * getPointerCast(Constant *C, Type *Ty)
Create a BitCast, AddrSpaceCast, or a PtrToInt cast constant expression.
Definition: Constants.cpp:2227
static Constant * getPointerBitCastOrAddrSpaceCast(Constant *C, Type *Ty)
Create a BitCast or AddrSpaceCast for a pointer type depending on the address space.
Definition: Constants.cpp:2242
static ConstantPointerNull * get(PointerType *T)
Static factory methods - Return objects of the specified value.
Definition: Constants.cpp:1800
static Constant * get(StructType *T, ArrayRef< Constant * > V)
Definition: Constants.cpp:1357
This is an important base class in LLVM.
Definition: Constant.h:42
static Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
Definition: Constants.cpp:370
This class represents an Operation in the Expression.
A parsed version of the target data layout string in and methods for querying it.
Definition: DataLayout.h:63
A handy container for a FunctionType+Callee-pointer pair, which can be passed around as a single enti...
Definition: DerivedTypes.h:168
ArrayRef< Type * > params() const
Definition: DerivedTypes.h:130
void addFnAttr(Attribute::AttrKind Kind)
Add function attributes to this function.
Definition: Function.cpp:653
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
Definition: Function.h:172
const BasicBlock & getEntryBlock() const
Definition: Function.h:807
FunctionType * getFunctionType() const
Returns the FunctionType for me.
Definition: Function.h:214
static Function * createWithDefaultAttr(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
Creates a function with some attributes recorded in llvm.module.flags and the LLVMContext applied.
Definition: Function.cpp:401
StringRef getSection() const
Get the custom section of this global if it has one.
Definition: GlobalObject.h:118
void setMetadata(unsigned KindID, MDNode *Node)
Set a particular kind of metadata attachment.
Definition: Metadata.cpp:1494
void setAlignment(Align Align)
Sets the alignment attribute of the GlobalObject.
Definition: Globals.cpp:137
void setSection(StringRef S)
Change the section for this global.
Definition: Globals.cpp:267
ThreadLocalMode getThreadLocalMode() const
Definition: GlobalValue.h:271
unsigned getAddressSpace() const
Definition: GlobalValue.h:205
@ PrivateLinkage
Like Internal, but omit from symbol table.
Definition: GlobalValue.h:60
@ InternalLinkage
Rename collisions when linking (static functions).
Definition: GlobalValue.h:59
@ AppendingLinkage
Special purpose, only applies to global arrays.
Definition: GlobalValue.h:58
Type * getValueType() const
Definition: GlobalValue.h:296
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
bool hasInitializer() const
Definitions have initializers, declarations don't.
void eraseFromParent()
eraseFromParent - This method unlinks 'this' from the containing module and deletes it.
Definition: Globals.cpp:481
LoadInst * CreateAlignedLoad(Type *Ty, Value *Ptr, MaybeAlign Align, const char *Name)
Definition: IRBuilder.h:1824
Value * CreatePointerCast(Value *V, Type *DestTy, const Twine &Name="")
Definition: IRBuilder.h:2190
IntegerType * getInt32Ty()
Fetch the type representing a 32-bit integer.
Definition: IRBuilder.h:523
Value * CreateICmpNE(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:2265
ConstantInt * getInt32(uint32_t C)
Get a constant 32-bit value.
Definition: IRBuilder.h:483
BranchInst * CreateCondBr(Value *Cond, BasicBlock *True, BasicBlock *False, MDNode *BranchWeights=nullptr, MDNode *Unpredictable=nullptr)
Create a conditional 'br Cond, TrueDest, FalseDest' instruction.
Definition: IRBuilder.h:1137
ReturnInst * CreateRetVoid()
Create a 'ret void' instruction.
Definition: IRBuilder.h:1107
Value * CreateConstInBoundsGEP2_32(Type *Ty, Value *Ptr, unsigned Idx0, unsigned Idx1, const Twine &Name="")
Definition: IRBuilder.h:1930
PointerType * getPtrTy(unsigned AddrSpace=0)
Fetch the type representing a pointer.
Definition: IRBuilder.h:566
BranchInst * CreateBr(BasicBlock *Dest)
Create an unconditional 'br label X' instruction.
Definition: IRBuilder.h:1131
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block.
Definition: IRBuilder.h:177
Type * getVoidTy()
Fetch the type representing void.
Definition: IRBuilder.h:561
StoreInst * CreateAlignedStore(Value *Val, Value *Ptr, MaybeAlign Align, bool isVolatile=false)
Definition: IRBuilder.h:1843
CallInst * CreateCall(FunctionType *FTy, Value *Callee, ArrayRef< Value * > Args=std::nullopt, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition: IRBuilder.h:2432
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition: IRBuilder.h:2686
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:174
Definition: MD5.h:41
void update(ArrayRef< uint8_t > Data)
Updates the hash for the byte stream provided.
Definition: MD5.cpp:189
static void stringifyResult(MD5Result &Result, SmallVectorImpl< char > &Str)
Translates the bytes in Res to a hex string that is deposited into Str.
Definition: MD5.cpp:287
void final(MD5Result &Result)
Finishes off the hash and puts the result in result.
Definition: MD5.cpp:234
ConstantAsMetadata * createConstant(Constant *C)
Return the given constant as metadata.
Definition: MDBuilder.cpp:24
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition: Metadata.h:1542
static MDString * get(LLVMContext &Context, StringRef Str)
Definition: Metadata.cpp:606
size_t getBufferSize() const
const char * getBufferStart() const
Root of the metadata hierarchy.
Definition: Metadata.h:62
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:65
A tuple of MDNodes.
Definition: Metadata.h:1730
void addOperand(MDNode *M)
Definition: Metadata.cpp:1394
Class to represent pointers.
Definition: DerivedTypes.h:646
static PointerType * getUnqual(Type *ElementType)
This constructs a pointer to an object of the specified type in the default address space (address sp...
Definition: DerivedTypes.h:662
static PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
Definition: Constants.cpp:1852
static ReturnInst * Create(LLVMContext &C, Value *retVal=nullptr, InsertPosition InsertBefore=nullptr)
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Definition: SmallPtrSet.h:367
bool contains(ConstPtrType Ptr) const
Definition: SmallPtrSet.h:441
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
Definition: SmallPtrSet.h:502
A SetVector that performs no allocations if smaller than a certain size.
Definition: SetVector.h:370
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition: SmallString.h:26
bool empty() const
Definition: SmallVector.h:94
size_t size() const
Definition: SmallVector.h:91
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: SmallVector.h:586
void reserve(size_type N)
Definition: SmallVector.h:676
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
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
std::string str() const
str - Get the contents as an std::string.
Definition: StringRef.h:215
constexpr bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:134
Class to represent struct types.
Definition: DerivedTypes.h:216
static StructType * get(LLVMContext &Context, ArrayRef< Type * > Elements, bool isPacked=false)
This static method is the primary way to create a literal StructType.
Definition: Type.cpp:361
unsigned getNumElements() const
Random access to the elements.
Definition: DerivedTypes.h:341
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
Type * getArrayElementType() const
Definition: Type.h:399
static Type * getVoidTy(LLVMContext &C)
static IntegerType * getInt32Ty(LLVMContext &C)
A Use represents the edge between a Value definition and its users.
Definition: Use.h:43
bool replaceUsesOfWith(Value *From, Value *To)
Replace uses of one Value with another.
Definition: User.cpp:21
LLVM Value Representation.
Definition: Value.h:74
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:255
void setName(const Twine &Name)
Change the name of the value.
Definition: Value.cpp:377
StringRef getName() const
Return a constant reference to the value's name.
Definition: Value.cpp:309
void takeName(Value *V)
Transfer the name from V to this value.
Definition: Value.cpp:383
An efficient, type-erasing, non-owning reference to a callable.
@ C
The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
@ Offset
Definition: DWP.cpp:480
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1722
Function * createSanitizerCtor(Module &M, StringRef CtorName)
Creates sanitizer constructor function.
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition: STLExtras.h:656
FunctionCallee declareSanitizerInitFunction(Module &M, StringRef InitName, ArrayRef< Type * > InitArgTypes, bool Weak=false)
void transformGlobalDtors(Module &M, const GlobalCtorTransformFn &Fn)
std::string getUniqueModuleId(Module *M)
Produce a unique identifier for this module by taking the MD5 sum of the names of the module's strong...
std::pair< Function *, FunctionCallee > getOrCreateSanitizerCtorAndInitFunctions(Module &M, StringRef CtorName, StringRef InitName, ArrayRef< Type * > InitArgTypes, ArrayRef< Value * > InitArgs, function_ref< void(Function *, FunctionCallee)> FunctionsCreatedCallback, StringRef VersionCheckName=StringRef(), bool Weak=false)
Creates sanitizer constructor function lazily.
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
void removeFromUsedLists(Module &M, function_ref< bool(Constant *)> ShouldRemove)
Removes global values from the llvm.used and llvm.compiler.used arrays.
void appendToCompilerUsed(Module &M, ArrayRef< GlobalValue * > Values)
Adds global values to the llvm.compiler.used list.
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
void setKCFIType(Module &M, Function &F, StringRef MangledType)
Sets the KCFI type for the function.
void transformGlobalCtors(Module &M, const GlobalCtorTransformFn &Fn)
void erase_if(Container &C, UnaryPredicate P)
Provide a container algorithm similar to C++ Library Fundamentals v2's erase_if which is equivalent t...
Definition: STLExtras.h:2082
void filterDeadComdatFunctions(SmallVectorImpl< Function * > &DeadComdatFunctions)
Filter out potentially dead comdat functions where other entries keep the entire comdat group alive.
void embedBufferInModule(Module &M, MemoryBufferRef Buf, StringRef SectionName, Align Alignment=Align(1))
Embed the memory buffer Buf into the module M as a global using the specified section name.
bool lowerGlobalIFuncUsersAsGlobalCtor(Module &M, ArrayRef< GlobalIFunc * > IFuncsToLower={})
Lower all calls to ifuncs by replacing uses with indirect calls loaded out of a global table initiali...
void appendToUsed(Module &M, ArrayRef< GlobalValue * > Values)
Adds global values to the llvm.used list.
void appendToGlobalDtors(Module &M, Function *F, int Priority, Constant *Data=nullptr)
Same as appendToGlobalCtors(), but for global dtors.
Definition: ModuleUtils.cpp:78
uint64_t xxHash64(llvm::StringRef Data)
Definition: xxhash.cpp:103
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition: Alignment.h:39