LLVM  3.7.0
ModuleUtils.cpp
Go to the documentation of this file.
1 //===-- ModuleUtils.cpp - Functions to manipulate Modules -----------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This family of functions perform manipulations on Modules.
11 //
12 //===----------------------------------------------------------------------===//
13 
15 #include "llvm/ADT/SmallPtrSet.h"
16 #include "llvm/IR/DerivedTypes.h"
17 #include "llvm/IR/Function.h"
18 #include "llvm/IR/IRBuilder.h"
19 #include "llvm/IR/Module.h"
21 
22 using namespace llvm;
23 
24 static void appendToGlobalArray(const char *Array,
25  Module &M, Function *F, int Priority) {
26  IRBuilder<> IRB(M.getContext());
27  FunctionType *FnTy = FunctionType::get(IRB.getVoidTy(), false);
28 
29  // Get the current set of static global constructors and add the new ctor
30  // to the list.
31  SmallVector<Constant *, 16> CurrentCtors;
32  StructType *EltTy;
33  if (GlobalVariable *GVCtor = M.getNamedGlobal(Array)) {
34  // If there is a global_ctors array, use the existing struct type, which can
35  // have 2 or 3 fields.
36  ArrayType *ATy = cast<ArrayType>(GVCtor->getType()->getElementType());
37  EltTy = cast<StructType>(ATy->getElementType());
38  if (Constant *Init = GVCtor->getInitializer()) {
39  unsigned n = Init->getNumOperands();
40  CurrentCtors.reserve(n + 1);
41  for (unsigned i = 0; i != n; ++i)
42  CurrentCtors.push_back(cast<Constant>(Init->getOperand(i)));
43  }
44  GVCtor->eraseFromParent();
45  } else {
46  // Use a simple two-field struct if there isn't one already.
47  EltTy = StructType::get(IRB.getInt32Ty(), PointerType::getUnqual(FnTy),
48  nullptr);
49  }
50 
51  // Build a 2 or 3 field global_ctor entry. We don't take a comdat key.
52  Constant *CSVals[3];
53  CSVals[0] = IRB.getInt32(Priority);
54  CSVals[1] = F;
55  // FIXME: Drop support for the two element form in LLVM 4.0.
56  if (EltTy->getNumElements() >= 3)
57  CSVals[2] = llvm::Constant::getNullValue(IRB.getInt8PtrTy());
58  Constant *RuntimeCtorInit =
59  ConstantStruct::get(EltTy, makeArrayRef(CSVals, EltTy->getNumElements()));
60 
61  CurrentCtors.push_back(RuntimeCtorInit);
62 
63  // Create a new initializer.
64  ArrayType *AT = ArrayType::get(EltTy, CurrentCtors.size());
65  Constant *NewInit = ConstantArray::get(AT, CurrentCtors);
66 
67  // Create the new global variable and replace all uses of
68  // the old global variable with the new one.
69  (void)new GlobalVariable(M, NewInit->getType(), false,
70  GlobalValue::AppendingLinkage, NewInit, Array);
71 }
72 
73 void llvm::appendToGlobalCtors(Module &M, Function *F, int Priority) {
74  appendToGlobalArray("llvm.global_ctors", M, F, Priority);
75 }
76 
77 void llvm::appendToGlobalDtors(Module &M, Function *F, int Priority) {
78  appendToGlobalArray("llvm.global_dtors", M, F, Priority);
79 }
80 
83  bool CompilerUsed) {
84  const char *Name = CompilerUsed ? "llvm.compiler.used" : "llvm.used";
85  GlobalVariable *GV = M.getGlobalVariable(Name);
86  if (!GV || !GV->hasInitializer())
87  return GV;
88 
89  const ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
90  for (unsigned I = 0, E = Init->getNumOperands(); I != E; ++I) {
91  Value *Op = Init->getOperand(I);
92  GlobalValue *G = cast<GlobalValue>(Op->stripPointerCastsNoFollowAliases());
93  Set.insert(G);
94  }
95  return GV;
96 }
97 
99  if (isa<Function>(FuncOrBitcast))
100  return cast<Function>(FuncOrBitcast);
101  FuncOrBitcast->dump();
102  std::string Err;
103  raw_string_ostream Stream(Err);
104  Stream << "Sanitizer interface function redefined: " << *FuncOrBitcast;
105  report_fatal_error(Err);
106 }
107 
108 std::pair<Function *, Function *> llvm::createSanitizerCtorAndInitFunctions(
109  Module &M, StringRef CtorName, StringRef InitName,
110  ArrayRef<Type *> InitArgTypes, ArrayRef<Value *> InitArgs) {
111  assert(!InitName.empty() && "Expected init function name");
112  assert(InitArgTypes.size() == InitArgTypes.size() &&
113  "Sanitizer's init function expects different number of arguments");
114  Function *Ctor = Function::Create(
116  GlobalValue::InternalLinkage, CtorName, &M);
117  BasicBlock *CtorBB = BasicBlock::Create(M.getContext(), "", Ctor);
118  IRBuilder<> IRB(ReturnInst::Create(M.getContext(), CtorBB));
119  Function *InitFunction =
121  InitName, FunctionType::get(IRB.getVoidTy(), InitArgTypes, false),
122  AttributeSet()));
123  InitFunction->setLinkage(Function::ExternalLinkage);
124  IRB.CreateCall(InitFunction, InitArgs);
125  return std::make_pair(Ctor, InitFunction);
126 }
127 
Special purpose, only applies to global arrays.
Definition: GlobalValue.h:46
Function * checkSanitizerInterfaceFunction(Constant *FuncOrBitcast)
Definition: ModuleUtils.cpp:98
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:114
unsigned getNumOperands() const
Definition: User.h:138
void appendToGlobalCtors(Module &M, Function *F, int Priority)
Append F to the list of global ctors of module M with the given Priority.
Definition: ModuleUtils.cpp:73
Externally visible function.
Definition: GlobalValue.h:40
F(f)
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
LLVM_ATTRIBUTE_NORETURN void report_fatal_error(const char *reason, bool gen_crash_diag=true)
Reports a serious error, calling any installed error handler.
static Constant * getNullValue(Type *Ty)
Definition: Constants.cpp:178
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
Definition: SmallPtrSet.h:242
static ReturnInst * Create(LLVMContext &C, Value *retVal=nullptr, Instruction *InsertBefore=nullptr)
ArrayRef< T > makeArrayRef(const T &OneElt)
Construct an ArrayRef from a single element.
Definition: ArrayRef.h:308
StructType - Class to represent struct types.
Definition: DerivedTypes.h:191
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition: IRBuilder.h:517
#define G(x, y, z)
Definition: MD5.cpp:52
FunctionType - Class to represent function types.
Definition: DerivedTypes.h:96
ArrayType - Class to represent array types.
Definition: DerivedTypes.h:336
static FunctionType * get(Type *Result, ArrayRef< Type * > Params, bool isVarArg)
FunctionType::get - This static method is the primary way of constructing a FunctionType.
Definition: Type.cpp:361
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
Definition: ArrayRef.h:31
Type * getElementType() const
Definition: DerivedTypes.h:323
size_t size() const
size - Get the array size.
Definition: ArrayRef.h:134
Value * stripPointerCastsNoFollowAliases()
Strip off pointer casts and all-zero GEPs.
Definition: Value.cpp:462
Constant * getOrInsertFunction(StringRef Name, FunctionType *T, AttributeSet AttributeList)
Look up the specified function in the module symbol table.
Definition: Module.cpp:115
LLVM Basic Block Representation.
Definition: BasicBlock.h:65
This is an important base class in LLVM.
Definition: Constant.h:41
static Constant * get(ArrayType *T, ArrayRef< Constant * > V)
Definition: Constants.cpp:873
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:264
static Type * getVoidTy(LLVMContext &C)
Definition: Type.cpp:225
Value * getOperand(unsigned i) const
Definition: User.h:118
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition: BasicBlock.h:103
static Constant * get(StructType *T, ArrayRef< Constant * > V)
Definition: Constants.cpp:1008
static void appendToGlobalArray(const char *Array, Module &M, Function *F, int Priority)
Definition: ModuleUtils.cpp:24
void appendToGlobalDtors(Module &M, Function *F, int Priority)
Same as appendToGlobalCtors(), but for global dtors.
Definition: ModuleUtils.cpp:77
void dump() const
Support for debugging, callable in GDB: V->dump()
Definition: AsmWriter.cpp:3353
static PointerType * getUnqual(Type *ElementType)
PointerType::getUnqual - This constructs a pointer to an object of the specified type in the generic ...
Definition: DerivedTypes.h:460
static StructType * get(LLVMContext &Context, ArrayRef< Type * > Elements, bool isPacked=false)
StructType::get - This static method is the primary way to create a literal StructType.
Definition: Type.cpp:404
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:861
Module.h This file contains the declarations for the Module class.
GlobalVariable * getNamedGlobal(StringRef Name)
Return the global variable in the module with the specified name, of arbitrary type.
Definition: Module.h:394
void setLinkage(LinkageTypes LT)
Definition: GlobalValue.h:284
ConstantArray - Constant Array Declarations.
Definition: Constants.h:356
bool hasInitializer() const
Definitions have initializers, declarations don't.
#define I(x, y, z)
Definition: MD5.cpp:54
static ArrayType * get(Type *ElementType, uint64_t NumElements)
ArrayType::get - This static method is the primary way to construct an ArrayType. ...
Definition: Type.cpp:686
std::pair< Function *, Function * > createSanitizerCtorAndInitFunctions(Module &M, StringRef CtorName, StringRef InitName, ArrayRef< Type * > InitArgTypes, ArrayRef< Value * > InitArgs)
Creates sanitizer constructor function, and calls sanitizer's init function from it.
Rename collisions when linking (static functions).
Definition: GlobalValue.h:47
A raw_ostream that writes to an std::string.
Definition: raw_ostream.h:465
LLVM Value Representation.
Definition: Value.h:69
GlobalVariable * collectUsedGlobalVariables(Module &M, SmallPtrSetImpl< GlobalValue * > &Set, bool CompilerUsed)
Given "llvm.used" or "llvm.compiler.used" as a global name, collect the initializer elements of that ...
Definition: ModuleUtils.cpp:82
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:40
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, const Twine &N="", Module *M=nullptr)
Definition: Function.h:121
unsigned getNumElements() const
Random access to the elements.
Definition: DerivedTypes.h:290
GlobalVariable * getGlobalVariable(StringRef Name) const
Look up the specified global variable in the module symbol table.
Definition: Module.h:381
LLVMContext & getContext() const
Get the global data context.
Definition: Module.h:265
bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:110