LLVM: lib/Transforms/Utils/ModuleUtils.cpp Source File (original) (raw)

1

2

3

4

5

6

7

8

9

10

11

12

25

26using namespace llvm;

27

28#define DEBUG_TYPE "moduleutils"

29

33

34

35

38 if (GlobalVariable *GVCtor = M.getNamedGlobal(ArrayName)) {

39 EltTy = cast(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)

45 }

46 GVCtor->eraseFromParent();

47 } else {

51 }

52

53

55 CSVals[0] = IRB.getInt32(Priority);

56 CSVals[1] = F;

61

62 CurrentCtors.push_back(RuntimeCtorInit);

63

64

67

68

69

72}

73

77

81

85 if (!GVCtor)

86 return;

87

94 CurrentCtors.reserve(Init->getNumOperands());

98 Changed |= (!NewC || NewC != C);

99 if (NewC)

101 }

102 }

104 return;

105

107

108

111

112

113

116}

117

121

125

129 return;

130

132 for (Use &Op : CA->operands())

134}

135

138

141 if (GV)

143

145 for (auto *V : Values)

147

148 if (Init.empty())

149 return;

150

154 Name);

156}

157

161

165

169 if (!GV)

170 return;

171

174

176

179 if (!ShouldRemove(MaybeRemoved->stripPointerCasts()))

181 }

182

183 if (!NewInit.empty()) {

191 }

192

194}

195

201

203 if (!M.getModuleFlag("kcfi"))

204 return;

205

208 std::string Type = MangledType.str();

209 if (M.getModuleFlag("cfi-normalize-integers"))

210 Type += ".normalized";

211

212

216

217 F.setMetadata(LLVMContext::MD_kcfi_type,

221

222

224 M.getModuleFlag("kcfi-offset"))) {

225 if (unsigned Offset = MD->getZExtValue())

226 F.addFnAttr("patchable-function-prefix", std::to_string(Offset));

227 }

228}

229

232 bool Weak) {

233 assert(!InitName.empty() && "Expected init function name");

236 auto FnCallee = M.getOrInsertFunction(InitName, FnTy);

238 if (Weak && Fn->isDeclaration())

240 return FnCallee;

241}

242

247 CtorName, &M);

248 Ctor->addFnAttr(Attribute::NoUnwind);

249 setKCFIType(M, *Ctor, "_ZTSFvvE");

252

254 return Ctor;

255}

256

260 StringRef VersionCheckName, bool Weak) {

261 assert(!InitName.empty() && "Expected init function name");

263 "Sanitizer's init function expects different number of arguments");

268

270 if (Weak) {

272 auto *EntryBB = BasicBlock::Create(M.getContext(), "entry", Ctor, RetBB);

273 auto *CallInitBB =

276 auto *InitFnPtr =

279 Value *InitNotNull =

281 IRB.CreateCondBr(InitNotNull, CallInitBB, RetBB);

283 } else {

285 }

286

287 IRB.CreateCall(InitFunction, InitArgs);

288 if (!VersionCheckName.empty()) {

289 FunctionCallee VersionCheckFunction = M.getOrInsertFunction(

291 AttributeList());

292 IRB.CreateCall(VersionCheckFunction, {});

293 }

294

295 if (Weak)

297

298 return std::make_pair(Ctor, InitFunction);

299}

300

301std::pair<Function *, FunctionCallee>

306 StringRef VersionCheckName, bool Weak) {

307 assert(!CtorName.empty() && "Expected ctor function name");

308

310

311

312 if (Ctor->arg_empty() ||

313 Ctor->getReturnType() == Type::getVoidTy(M.getContext()))

314 return {Ctor,

316

320 M, CtorName, InitName, InitArgTypes, InitArgs, VersionCheckName, Weak);

321 FunctionsCreatedCallback(Ctor, InitFunction);

322 return std::make_pair(Ctor, InitFunction);

323}

324

329 for (Function *F : DeadComdatFunctions) {

330 MaybeDeadFunctions.insert(F);

331 if (Comdat *C = F->getComdat())

332 MaybeDeadComdats.insert(C);

333 }

334

335

337 for (Comdat *C : MaybeDeadComdats) {

340 return F && MaybeDeadFunctions.contains(F);

341 };

342 if (all_of(C->getUsers(), IsUserDead))

344 }

345

346

349 return C && !DeadComdats.contains(C);

350 });

351}

352

355

357 M->getModuleFlag("Unique Source File Identifier"));

358 if (UniqueSourceFileIdentifier) {

360 cast(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

378

381 return ("." + Str).str();

382}

383

386

391 ModuleConstant, "llvm.embedded.object");

394

396 NamedMDNode *MD = M.getOrInsertNamedMetadata("llvm.embedded.objects");

399

402

404}

405

410 if (FilteredIFuncsToLower.empty()) {

413 IFuncsToLower = AllIFuncs;

414 }

415

416 bool UnhandledUsers = false;

419

422

425

426 Align PtrAlign = DL.getABITypeAlign(TableEntryTy);

427

428

429

434 FuncPtrTable->setAlignment(PtrAlign);

435

436

439 DL.getProgramAddressSpace(), "", &M);

440

443

444 size_t TableIndex = 0;

446 Function *ResolvedFunction = GI->getResolverFunction();

447

448

449

450

451

453 LLVM_DEBUG(dbgs() << "Not lowering ifunc resolver function "

454 << ResolvedFunction->getName() << " with parameters\n");

455 UnhandledUsers = true;

456 continue;

457 }

458

459

463 FuncPtrTableTy, FuncPtrTable, 0, TableIndex++));

465

466

469 if (!UserInst) {

470

471

472 UnhandledUsers = true;

473 continue;

474 }

475

479 Value *ResolvedCast =

482 }

483

484

485 if (GI->use_empty())

487 }

488

490

492

493

494

495 const int Priority = 10;

498 return UnhandledUsers;

499}

assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")

MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL

Module.h This file contains the declarations for the Module class.

static void appendToUsedList(Module &M, StringRef Name, ArrayRef< GlobalValue * > Values)

Definition ModuleUtils.cpp:136

static void collectUsedGlobals(GlobalVariable *GV, SmallSetVector< Constant *, 16 > &Init)

Definition ModuleUtils.cpp:126

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)

Definition ModuleUtils.cpp:166

static void appendToGlobalArray(StringRef ArrayName, Module &M, Function *F, int Priority, Constant *Data)

Definition ModuleUtils.cpp:30

This file defines the SmallString class.

ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...

size_t size() const

size - Get the array size.

bool empty() const

empty - Check if the array is empty.

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.

static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)

Creates a new BasicBlock.

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...

This class represents a function call, abstracting a target machine's calling convention.

static LLVM_ABI Constant * get(ArrayType *T, ArrayRef< Constant * > V)

static Constant * get(LLVMContext &Context, ArrayRef< ElementTy > Elts)

get() constructor - Return a constant with array type with an element count and element type matching...

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.

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.

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.

static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)

const BasicBlock & getEntryBlock() const

FunctionType * getFunctionType() const

Returns the FunctionType for me.

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.

const Function & getFunction() const

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.

ThreadLocalMode getThreadLocalMode() const

unsigned getAddressSpace() const

@ PrivateLinkage

Like Internal, but omit from symbol table.

@ InternalLinkage

Rename collisions when linking (static functions).

@ AppendingLinkage

Special purpose, only applies to global arrays.

@ ExternalWeakLinkage

ExternalWeak linkage description.

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.

void setAlignment(Align Align)

Sets the alignment attribute of the GlobalVariable.

LoadInst * CreateAlignedLoad(Type *Ty, Value *Ptr, MaybeAlign Align, const char *Name)

Value * CreatePointerCast(Value *V, Type *DestTy, const Twine &Name="")

IntegerType * getInt32Ty()

Fetch the type representing a 32-bit integer.

Value * CreateICmpNE(Value *LHS, Value *RHS, const Twine &Name="")

ConstantInt * getInt32(uint32_t C)

Get a constant 32-bit value.

BranchInst * CreateCondBr(Value *Cond, BasicBlock *True, BasicBlock *False, MDNode *BranchWeights=nullptr, MDNode *Unpredictable=nullptr)

Create a conditional 'br Cond, TrueDest, FalseDest' instruction.

ReturnInst * CreateRetVoid()

Create a 'ret void' instruction.

Value * CreateConstInBoundsGEP2_32(Type *Ty, Value *Ptr, unsigned Idx0, unsigned Idx1, const Twine &Name="")

CallInst * CreateCall(FunctionType *FTy, Value *Callee, ArrayRef< Value * > Args={}, const Twine &Name="", MDNode *FPMathTag=nullptr)

PointerType * getPtrTy(unsigned AddrSpace=0)

Fetch the type representing a pointer.

BranchInst * CreateBr(BasicBlock *Dest)

Create an unconditional 'br label X' instruction.

void SetInsertPoint(BasicBlock *TheBB)

This specifies that created instructions should be appended to the end of the specified block.

Type * getVoidTy()

Fetch the type representing void.

StoreInst * CreateAlignedStore(Value *Val, Value *Ptr, MaybeAlign Align, bool isVolatile=false)

This provides a uniform API for creating instructions and inserting them into a basic block: either a...

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.

An instruction for reading from memory.

LLVM_ABI void update(ArrayRef< uint8_t > Data)

Updates the hash for the byte stream provided.

static LLVM_ABI void stringifyResult(MD5Result &Result, SmallVectorImpl< char > &Str)

Translates the bytes in Res to a hex string that is deposited into Str.

LLVM_ABI void final(MD5Result &Result)

Finishes off the hash and puts the result in result.

LLVM_ABI ConstantAsMetadata * createConstant(Constant *C)

Return the given constant as metadata.

static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)

static LLVM_ABI MDString * get(LLVMContext &Context, StringRef Str)

size_t getBufferSize() const

const char * getBufferStart() const

A Module instance is used to store all the information related to an LLVM module.

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.

SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...

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.

std::string str() const

str - Get the contents as an std::string.

constexpr bool empty() const

empty - Check if the string is empty.

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.

unsigned getNumElements() const

Random access to the elements.

The instances of the Type class are immutable: once they are created, they are never changed.

static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)

Type * getArrayElementType() const

static LLVM_ABI Type * getVoidTy(LLVMContext &C)

A Use represents the edge between a Value definition and its users.

LLVM_ABI bool replaceUsesOfWith(Value *From, Value *To)

Replace uses of one Value with another.

LLVM Value Representation.

Type * getType() const

All values are typed, get the type of this value.

LLVM_ABI void setName(const Twine &Name)

Change the name of the value.

LLVM_ABI StringRef getName() const

Return a constant reference to the value's name.

LLVM_ABI void takeName(Value *V)

Transfer the name from V to this value.

An efficient, type-erasing, non-owning reference to a callable.

@ C

The default llvm calling convention, compatible with C.

std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > extract_or_null(Y &&MD)

Extract a Value from Metadata, allowing null.

This is an optimization pass for GlobalISel generic memory operations.

bool all_of(R &&range, UnaryPredicate P)

Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.

decltype(auto) dyn_cast(const From &Val)

dyn_cast - Return the argument parameter cast to the specified type.

LLVM_ABI Function * createSanitizerCtor(Module &M, StringRef CtorName)

Creates sanitizer constructor function.

Definition ModuleUtils.cpp:243

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...

auto dyn_cast_or_null(const Y &Val)

LLVM_ABI FunctionCallee declareSanitizerInitFunction(Module &M, StringRef InitName, ArrayRef< Type * > InitArgTypes, bool Weak=false)

Definition ModuleUtils.cpp:230

LLVM_ABI void transformGlobalDtors(Module &M, const GlobalCtorTransformFn &Fn)

Definition ModuleUtils.cpp:122

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...

Definition ModuleUtils.cpp:353

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.

Definition ModuleUtils.cpp:302

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.

Definition ModuleUtils.cpp:257

LLVM_ABI raw_ostream & dbgs()

dbgs() - This returns a reference to a raw_ostream for debugging messages.

LLVM_ABI void removeFromUsedLists(Module &M, function_ref< bool(Constant *)> ShouldRemove)

Removes global values from the llvm.used and llvm.compiler.used arrays.

Definition ModuleUtils.cpp:196

FunctionAddr VTableAddr uintptr_t uintptr_t Data

LLVM_ABI void appendToCompilerUsed(Module &M, ArrayRef< GlobalValue * > Values)

Adds global values to the llvm.compiler.used list.

Definition ModuleUtils.cpp:162

KCFIHashAlgorithm parseKCFIHashAlgorithm(StringRef Name)

Parse a KCFI hash algorithm name.

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.

Definition ModuleUtils.cpp:74

LLVM_ABI void setKCFIType(Module &M, Function &F, StringRef MangledType)

Sets the KCFI type for the function.

Definition ModuleUtils.cpp:202

decltype(auto) cast(const From &Val)

cast - Return the argument parameter cast to the specified type.

LLVM_ABI void transformGlobalCtors(Module &M, const GlobalCtorTransformFn &Fn)

Definition ModuleUtils.cpp:118

void erase_if(Container &C, UnaryPredicate P)

Provide a container algorithm similar to C++ Library Fundamentals v2's erase_if which is equivalent t...

LLVM_ABI void filterDeadComdatFunctions(SmallVectorImpl< Function * > &DeadComdatFunctions)

Filter out potentially dead comdat functions where other entries keep the entire comdat group alive.

Definition ModuleUtils.cpp:325

uint32_t getKCFITypeID(StringRef MangledTypeName, KCFIHashAlgorithm Algorithm)

Compute KCFI type ID from mangled type name.

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...

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.

Definition ModuleUtils.cpp:384

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...

Definition ModuleUtils.cpp:406

LLVM_ABI void appendToUsed(Module &M, ArrayRef< GlobalValue * > Values)

Adds global values to the llvm.used list.

Definition ModuleUtils.cpp:158

LLVM_ABI void appendToGlobalDtors(Module &M, Function *F, int Priority, Constant *Data=nullptr)

Same as appendToGlobalCtors(), but for global dtors.

Definition ModuleUtils.cpp:78

This struct is a compact representation of a valid (non-zero power of two) alignment.