LLVM 22.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"
22#include "llvm/Support/Hash.h"
23#include "llvm/Support/MD5.h"
25
26using namespace llvm;
27
28#define DEBUG_TYPE "moduleutils"
29
30static void appendToGlobalArray(StringRef ArrayName, Module &M, Function *F,
31 int Priority, Constant *Data) {
32 IRBuilder<> IRB(M.getContext());
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(
49 IRB.getInt32Ty(),
50 PointerType::get(M.getContext(), F->getAddressSpace()), 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;
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
75 appendToGlobalArray("llvm.global_ctors", M, F, Priority, Data);
76}
77
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 =
93 if (Constant *Init = GVCtor->getInitializer()) {
94 CurrentCtors.reserve(Init->getNumOperands());
95 for (Value *OP : Init->operands()) {
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
212 // Determine which hash algorithm to use
213 auto *MD = dyn_cast_or_null<MDString>(M.getModuleFlag("kcfi-hash"));
214 KCFIHashAlgorithm Algorithm =
215 parseKCFIHashAlgorithm(MD ? MD->getString() : "");
216
217 F.setMetadata(LLVMContext::MD_kcfi_type,
218 MDNode::get(Ctx, MDB.createConstant(ConstantInt::get(
219 Type::getInt32Ty(Ctx),
220 getKCFITypeID(Type, Algorithm)))));
221 // If the module was compiled with -fpatchable-function-entry, ensure
222 // we use the same patchable-function-prefix.
224 M.getModuleFlag("kcfi-offset"))) {
225 if (unsigned Offset = MD->getZExtValue())
226 F.addFnAttr("patchable-function-prefix", std::to_string(Offset));
227 }
228}
229
231 ArrayRef<Type *> InitArgTypes,
232 bool Weak) {
233 assert(!InitName.empty() && "Expected init function name");
234 auto *VoidTy = Type::getVoidTy(M.getContext());
235 auto *FnTy = FunctionType::get(VoidTy, InitArgTypes, false);
236 auto FnCallee = M.getOrInsertFunction(InitName, FnTy);
237 auto *Fn = cast<Function>(FnCallee.getCallee());
238 if (Weak && Fn->isDeclaration())
239 Fn->setLinkage(Function::ExternalWeakLinkage);
240 return FnCallee;
241}
242
245 FunctionType::get(Type::getVoidTy(M.getContext()), false),
246 GlobalValue::InternalLinkage, M.getDataLayout().getProgramAddressSpace(),
247 CtorName, &M);
248 Ctor->addFnAttr(Attribute::NoUnwind);
249 setKCFIType(M, *Ctor, "_ZTSFvvE"); // void (*)(void)
250 BasicBlock *CtorBB = BasicBlock::Create(M.getContext(), "", Ctor);
251 ReturnInst::Create(M.getContext(), CtorBB);
252 // Ensure Ctor cannot be discarded, even if in a comdat.
253 appendToUsed(M, {Ctor});
254 return Ctor;
255}
256
257std::pair<Function *, FunctionCallee> llvm::createSanitizerCtorAndInitFunctions(
258 Module &M, StringRef CtorName, StringRef InitName,
259 ArrayRef<Type *> InitArgTypes, ArrayRef<Value *> InitArgs,
260 StringRef VersionCheckName, bool Weak) {
261 assert(!InitName.empty() && "Expected init function name");
262 assert(InitArgs.size() == InitArgTypes.size() &&
263 "Sanitizer's init function expects different number of arguments");
264 FunctionCallee InitFunction =
265 declareSanitizerInitFunction(M, InitName, InitArgTypes, Weak);
266 Function *Ctor = createSanitizerCtor(M, CtorName);
267 IRBuilder<> IRB(M.getContext());
268
269 BasicBlock *RetBB = &Ctor->getEntryBlock();
270 if (Weak) {
271 RetBB->setName("ret");
272 auto *EntryBB = BasicBlock::Create(M.getContext(), "entry", Ctor, RetBB);
273 auto *CallInitBB =
274 BasicBlock::Create(M.getContext(), "callfunc", Ctor, RetBB);
275 auto *InitFn = cast<Function>(InitFunction.getCallee());
276 auto *InitFnPtr =
277 PointerType::get(M.getContext(), InitFn->getAddressSpace());
278 IRB.SetInsertPoint(EntryBB);
279 Value *InitNotNull =
280 IRB.CreateICmpNE(InitFn, ConstantPointerNull::get(InitFnPtr));
281 IRB.CreateCondBr(InitNotNull, CallInitBB, RetBB);
282 IRB.SetInsertPoint(CallInitBB);
283 } else {
284 IRB.SetInsertPoint(RetBB->getTerminator());
285 }
286
287 IRB.CreateCall(InitFunction, InitArgs);
288 if (!VersionCheckName.empty()) {
289 FunctionCallee VersionCheckFunction = M.getOrInsertFunction(
290 VersionCheckName, FunctionType::get(IRB.getVoidTy(), {}, false),
291 AttributeList());
292 IRB.CreateCall(VersionCheckFunction, {});
293 }
294
295 if (Weak)
296 IRB.CreateBr(RetBB);
297
298 return std::make_pair(Ctor, InitFunction);
299}
300
301std::pair<Function *, FunctionCallee>
303 Module &M, StringRef CtorName, StringRef InitName,
304 ArrayRef<Type *> InitArgTypes, ArrayRef<Value *> InitArgs,
305 function_ref<void(Function *, FunctionCallee)> FunctionsCreatedCallback,
306 StringRef VersionCheckName, bool Weak) {
307 assert(!CtorName.empty() && "Expected ctor function name");
308
309 if (Function *Ctor = M.getFunction(CtorName))
310 // FIXME: Sink this logic into the module, similar to the handling of
311 // globals. This will make moving to a concurrent model much easier.
312 if (Ctor->arg_empty() ||
313 Ctor->getReturnType() == Type::getVoidTy(M.getContext()))
314 return {Ctor,
315 declareSanitizerInitFunction(M, InitName, InitArgTypes, Weak)};
316
317 Function *Ctor;
318 FunctionCallee InitFunction;
319 std::tie(Ctor, InitFunction) = llvm::createSanitizerCtorAndInitFunctions(
320 M, CtorName, InitName, InitArgTypes, InitArgs, VersionCheckName, Weak);
321 FunctionsCreatedCallback(Ctor, InitFunction);
322 return std::make_pair(Ctor, InitFunction);
323}
324
326 SmallVectorImpl<Function *> &DeadComdatFunctions) {
327 SmallPtrSet<Function *, 32> MaybeDeadFunctions;
328 SmallPtrSet<Comdat *, 32> MaybeDeadComdats;
329 for (Function *F : DeadComdatFunctions) {
330 MaybeDeadFunctions.insert(F);
331 if (Comdat *C = F->getComdat())
332 MaybeDeadComdats.insert(C);
333 }
334
335 // Find comdats for which all users are dead now.
336 SmallPtrSet<Comdat *, 32> DeadComdats;
337 for (Comdat *C : MaybeDeadComdats) {
338 auto IsUserDead = [&](GlobalObject *GO) {
339 auto *F = dyn_cast<Function>(GO);
340 return F && MaybeDeadFunctions.contains(F);
341 };
342 if (all_of(C->getUsers(), IsUserDead))
343 DeadComdats.insert(C);
344 }
345
346 // Only keep functions which have no comdat or a dead comdat.
347 erase_if(DeadComdatFunctions, [&](Function *F) {
348 Comdat *C = F->getComdat();
349 return C && !DeadComdats.contains(C);
350 });
351}
352
354 MD5 Md5;
355
356 auto *UniqueSourceFileIdentifier = dyn_cast_or_null<MDNode>(
357 M->getModuleFlag("Unique Source File Identifier"));
358 if (UniqueSourceFileIdentifier) {
359 Md5.update(
360 cast<MDString>(UniqueSourceFileIdentifier->getOperand(0))->getString());
361 } else {
362 bool ExportsSymbols = false;
363 for (auto &GV : M->global_values()) {
364 if (GV.isDeclaration() || GV.getName().starts_with("llvm.") ||
365 !GV.hasExternalLinkage() || GV.hasComdat())
366 continue;
367 ExportsSymbols = true;
368 Md5.update(GV.getName());
370 }
371
372 if (!ExportsSymbols)
373 return "";
374 }
375
377 Md5.final(R);
378
379 SmallString<32> Str;
380 MD5::stringifyResult(R, Str);
381 return ("." + Str).str();
382}
383
385 StringRef SectionName, Align Alignment) {
386 // Embed the memory buffer into the module.
387 Constant *ModuleConstant = ConstantDataArray::get(
388 M.getContext(), ArrayRef(Buf.getBufferStart(), Buf.getBufferSize()));
390 M, ModuleConstant->getType(), true, GlobalValue::PrivateLinkage,
391 ModuleConstant, "llvm.embedded.object");
393 GV->setAlignment(Alignment);
394
395 LLVMContext &Ctx = M.getContext();
396 NamedMDNode *MD = M.getOrInsertNamedMetadata("llvm.embedded.objects");
397 Metadata *MDVals[] = {ConstantAsMetadata::get(GV),
399
400 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
401 GV->setMetadata(LLVMContext::MD_exclude, llvm::MDNode::get(Ctx, {}));
402
404}
405
407 Module &M, ArrayRef<GlobalIFunc *> FilteredIFuncsToLower) {
409 ArrayRef<GlobalIFunc *> IFuncsToLower = FilteredIFuncsToLower;
410 if (FilteredIFuncsToLower.empty()) { // Default to lowering all ifuncs
411 for (GlobalIFunc &GI : M.ifuncs())
412 AllIFuncs.push_back(&GI);
413 IFuncsToLower = AllIFuncs;
414 }
415
416 bool UnhandledUsers = false;
417 LLVMContext &Ctx = M.getContext();
418 const DataLayout &DL = M.getDataLayout();
419
420 PointerType *TableEntryTy =
421 PointerType::get(Ctx, DL.getProgramAddressSpace());
422
423 ArrayType *FuncPtrTableTy =
424 ArrayType::get(TableEntryTy, IFuncsToLower.size());
425
426 Align PtrAlign = DL.getABITypeAlign(TableEntryTy);
427
428 // Create a global table of function pointers we'll initialize in a global
429 // constructor.
430 auto *FuncPtrTable = new GlobalVariable(
431 M, FuncPtrTableTy, false, GlobalValue::InternalLinkage,
432 PoisonValue::get(FuncPtrTableTy), "", nullptr,
433 GlobalVariable::NotThreadLocal, DL.getDefaultGlobalsAddressSpace());
434 FuncPtrTable->setAlignment(PtrAlign);
435
436 // Create a function to initialize the function pointer table.
437 Function *NewCtor = Function::Create(
439 DL.getProgramAddressSpace(), "", &M);
440
441 BasicBlock *BB = BasicBlock::Create(Ctx, "", NewCtor);
442 IRBuilder<> InitBuilder(BB);
443
444 size_t TableIndex = 0;
445 for (GlobalIFunc *GI : IFuncsToLower) {
446 Function *ResolvedFunction = GI->getResolverFunction();
447
448 // We don't know what to pass to a resolver function taking arguments
449 //
450 // FIXME: Is this even valid? clang and gcc don't complain but this
451 // probably should be invalid IR. We could just pass through undef.
452 if (!std::empty(ResolvedFunction->getFunctionType()->params())) {
453 LLVM_DEBUG(dbgs() << "Not lowering ifunc resolver function "
454 << ResolvedFunction->getName() << " with parameters\n");
455 UnhandledUsers = true;
456 continue;
457 }
458
459 // Initialize the function pointer table.
460 CallInst *ResolvedFunc = InitBuilder.CreateCall(ResolvedFunction);
461 Value *Casted = InitBuilder.CreatePointerCast(ResolvedFunc, TableEntryTy);
463 FuncPtrTableTy, FuncPtrTable, 0, TableIndex++));
464 InitBuilder.CreateAlignedStore(Casted, GEP, PtrAlign);
465
466 // Update all users to load a pointer from the global table.
467 for (User *User : make_early_inc_range(GI->users())) {
469 if (!UserInst) {
470 // TODO: Should handle constantexpr casts in user instructions. Probably
471 // can't do much about constant initializers.
472 UnhandledUsers = true;
473 continue;
474 }
475
476 IRBuilder<> UseBuilder(UserInst);
477 LoadInst *ResolvedTarget =
478 UseBuilder.CreateAlignedLoad(TableEntryTy, GEP, PtrAlign);
479 Value *ResolvedCast =
480 UseBuilder.CreatePointerCast(ResolvedTarget, GI->getType());
481 UserInst->replaceUsesOfWith(GI, ResolvedCast);
482 }
483
484 // If we handled all users, erase the ifunc.
485 if (GI->use_empty())
486 GI->eraseFromParent();
487 }
488
489 InitBuilder.CreateRetVoid();
490
491 PointerType *ConstantDataTy = PointerType::get(Ctx, 0);
492
493 // TODO: Is this the right priority? Probably should be before any other
494 // constructors?
495 const int Priority = 10;
496 appendToGlobalCtors(M, NewCtor, Priority,
497 ConstantPointerNull::get(ConstantDataTy));
498 return UnhandledUsers;
499}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Hexagon Common GEP
Module.h This file contains the declarations for the Module class.
#define F(x, y, z)
Definition MD5.cpp:54
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)
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)
#define OP(OPC)
Definition Instruction.h:46
This file defines the SmallString class.
#define LLVM_DEBUG(...)
Definition Debug.h:114
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_t size() const
size - Get the array size.
Definition ArrayRef.h:142
bool empty() const
empty - Check if the array is empty.
Definition ArrayRef.h:137
Class to represent array types.
static LLVM_ABI ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition BasicBlock.h:206
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:233
This class represents a function call, abstracting a target machine's calling convention.
static LLVM_ABI Constant * get(ArrayType *T, ArrayRef< Constant * > V)
static ConstantAsMetadata * get(Constant *C)
Definition Metadata.h:536
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:715
static LLVM_ABI Constant * getPointerCast(Constant *C, Type *Ty)
Create a BitCast, AddrSpaceCast, or a PtrToInt cast constant expression.
static LLVM_ABI Constant * getPointerBitCastOrAddrSpaceCast(Constant *C, Type *Ty)
Create a BitCast or AddrSpaceCast for a pointer type depending on the address space.
static LLVM_ABI ConstantPointerNull * get(PointerType *T)
Static factory methods - Return objects of the specified value.
static LLVM_ABI Constant * get(StructType *T, ArrayRef< Constant * > V)
This is an important base class in LLVM.
Definition Constant.h:43
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
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...
ArrayRef< Type * > params() const
static LLVM_ABI FunctionType * get(Type *Result, ArrayRef< Type * > Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
void addFnAttr(Attribute::AttrKind Kind)
Add function attributes to this function.
Definition Function.cpp:640
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
Definition Function.h:166
const BasicBlock & getEntryBlock() const
Definition Function.h:807
FunctionType * getFunctionType() const
Returns the FunctionType for me.
Definition Function.h:209
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:380
const Function & getFunction() const
Definition Function.h:164
StringRef getSection() const
Get the custom section of this global if it has one.
LLVM_ABI void setMetadata(unsigned KindID, MDNode *Node)
Set a particular kind of metadata attachment.
LLVM_ABI void setSection(StringRef S)
Change the section for this global.
Definition Globals.cpp:275
ThreadLocalMode getThreadLocalMode() const
unsigned getAddressSpace() const
@ PrivateLinkage
Like Internal, but omit from symbol table.
Definition GlobalValue.h:61
@ InternalLinkage
Rename collisions when linking (static functions).
Definition GlobalValue.h:60
@ AppendingLinkage
Special purpose, only applies to global arrays.
Definition GlobalValue.h:59
@ ExternalWeakLinkage
ExternalWeak linkage description.
Definition GlobalValue.h:62
Type * getValueType() const
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
bool hasInitializer() const
Definitions have initializers, declarations don't.
LLVM_ABI void eraseFromParent()
eraseFromParent - This method unlinks 'this' from the containing module and deletes it.
Definition Globals.cpp:520
void setAlignment(Align Align)
Sets the alignment attribute of the GlobalVariable.
LoadInst * CreateAlignedLoad(Type *Ty, Value *Ptr, MaybeAlign Align, const char *Name)
Definition IRBuilder.h:1867
Value * CreatePointerCast(Value *V, Type *DestTy, const Twine &Name="")
Definition IRBuilder.h:2254
IntegerType * getInt32Ty()
Fetch the type representing a 32-bit integer.
Definition IRBuilder.h:562
Value * CreateICmpNE(Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:2336
ConstantInt * getInt32(uint32_t C)
Get a constant 32-bit value.
Definition IRBuilder.h:522
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:1197
ReturnInst * CreateRetVoid()
Create a 'ret void' instruction.
Definition IRBuilder.h:1167
Value * CreateConstInBoundsGEP2_32(Type *Ty, Value *Ptr, unsigned Idx0, unsigned Idx1, const Twine &Name="")
Definition IRBuilder.h:1973
CallInst * CreateCall(FunctionType *FTy, Value *Callee, ArrayRef< Value * > Args={}, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition IRBuilder.h:2511
PointerType * getPtrTy(unsigned AddrSpace=0)
Fetch the type representing a pointer.
Definition IRBuilder.h:605
BranchInst * CreateBr(BasicBlock *Dest)
Create an unconditional 'br label X' instruction.
Definition IRBuilder.h:1191
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block.
Definition IRBuilder.h:207
Type * getVoidTy()
Fetch the type representing void.
Definition IRBuilder.h:600
StoreInst * CreateAlignedStore(Value *Val, Value *Ptr, MaybeAlign Align, bool isVolatile=false)
Definition IRBuilder.h:1886
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2788
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:68
An instruction for reading from memory.
LLVM_ABI void update(ArrayRef< uint8_t > Data)
Updates the hash for the byte stream provided.
Definition MD5.cpp:188
static LLVM_ABI void stringifyResult(MD5Result &Result, SmallVectorImpl< char > &Str)
Translates the bytes in Res to a hex string that is deposited into Str.
Definition MD5.cpp:286
LLVM_ABI void final(MD5Result &Result)
Finishes off the hash and puts the result in result.
Definition MD5.cpp:233
LLVM_ABI ConstantAsMetadata * createConstant(Constant *C)
Return the given constant as metadata.
Definition MDBuilder.cpp:25
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1569
static LLVM_ABI MDString * get(LLVMContext &Context, StringRef Str)
Definition Metadata.cpp:608
size_t getBufferSize() const
const char * getBufferStart() const
Root of the metadata hierarchy.
Definition Metadata.h:64
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:67
A tuple of MDNodes.
Definition Metadata.h:1757
LLVM_ABI void addOperand(MDNode *M)
Class to represent pointers.
static PointerType * getUnqual(Type *ElementType)
This constructs a pointer to an object of the specified type in the default address space (address sp...
static LLVM_ABI PointerType * get(Type *ElementType, unsigned AddressSpace)
This constructs a pointer to an object of the specified type in a numbered address space.
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
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.
bool contains(ConstPtrType Ptr) const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
A SetVector that performs no allocations if smaller than a certain size.
Definition SetVector.h:339
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition SmallString.h:26
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void reserve(size_type N)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StringRef - Represent a constant reference to a string, i.e.
Definition StringRef.h:55
std::string str() const
str - Get the contents as an std::string.
Definition StringRef.h:225
constexpr bool empty() const
empty - Check if the string is empty.
Definition StringRef.h:143
Class to represent struct types.
static LLVM_ABI 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:413
unsigned getNumElements() const
Random access to the elements.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:45
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
Definition Type.cpp:296
Type * getArrayElementType() const
Definition Type.h:408
static LLVM_ABI Type * getVoidTy(LLVMContext &C)
Definition Type.cpp:280
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
LLVM_ABI bool replaceUsesOfWith(Value *From, Value *To)
Replace uses of one Value with another.
Definition User.cpp:24
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:256
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
Definition Value.cpp:390
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:322
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
Definition Value.cpp:396
An efficient, type-erasing, non-owning reference to a callable.
Changed
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
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:682
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:532
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:1725
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
LLVM_ABI 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:632
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
LLVM_ABI FunctionCallee declareSanitizerInitFunction(Module &M, StringRef InitName, ArrayRef< Type * > InitArgTypes, bool Weak=false)
LLVM_ABI void transformGlobalDtors(Module &M, const GlobalCtorTransformFn &Fn)
LLVM_ABI 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...
LLVM_ABI 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.
LLVM_ABI 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.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:207
LLVM_ABI void removeFromUsedLists(Module &M, function_ref< bool(Constant *)> ShouldRemove)
Removes global values from the llvm.used and llvm.compiler.used arrays.
FunctionAddr VTableAddr uintptr_t uintptr_t Data
Definition InstrProf.h:189
LLVM_ABI void appendToCompilerUsed(Module &M, ArrayRef< GlobalValue * > Values)
Adds global values to the llvm.compiler.used list.
KCFIHashAlgorithm parseKCFIHashAlgorithm(StringRef Name)
Parse a KCFI hash algorithm name.
Definition Hash.cpp:18
KCFIHashAlgorithm
Definition Hash.h:21
DWARFExpression::Operation Op
ArrayRef(const T &OneElt) -> ArrayRef< T >
LLVM_ABI 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.
LLVM_ABI void setKCFIType(Module &M, Function &F, StringRef MangledType)
Sets the KCFI type for the function.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
LLVM_ABI 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:2120
LLVM_ABI void filterDeadComdatFunctions(SmallVectorImpl< Function * > &DeadComdatFunctions)
Filter out potentially dead comdat functions where other entries keep the entire comdat group alive.
uint32_t getKCFITypeID(StringRef MangledTypeName, KCFIHashAlgorithm Algorithm)
Compute KCFI type ID from mangled type name.
Definition Hash.cpp:35
llvm::function_ref< Constant *(Constant *)> GlobalCtorTransformFn
Apply 'Fn' to the list of global ctors of module M and replace contructor record with the one returne...
Definition ModuleUtils.h:53
LLVM_ABI 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.
LLVM_ABI 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...
LLVM_ABI void appendToUsed(Module &M, ArrayRef< GlobalValue * > Values)
Adds global values to the llvm.used list.
LLVM_ABI void appendToGlobalDtors(Module &M, Function *F, int Priority, Constant *Data=nullptr)
Same as appendToGlobalCtors(), but for global dtors.
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39