blob: ba4b7f3cc2639e6e2ffc1b8ebe89102fdb118950 [file] [log] [blame]
Devang Patelf4af8c62011-10-31 23:58:51 +00001//===-- 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
14#include "llvm/Transforms/Utils/ModuleUtils.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000015#include "llvm/IR/DerivedTypes.h"
16#include "llvm/IR/Function.h"
17#include "llvm/IR/IRBuilder.h"
18#include "llvm/IR/Module.h"
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +000019#include "llvm/Support/raw_ostream.h"
Kostya Serebryanydb999c02011-11-16 01:14:38 +000020
Devang Patelf4af8c62011-10-31 23:58:51 +000021using namespace llvm;
22
Evgeniy Stepanovba6ca872016-02-12 00:37:52 +000023static void appendToGlobalArray(const char *Array, Module &M, Function *F,
24 int Priority, Constant *Data) {
Devang Patelf4af8c62011-10-31 23:58:51 +000025 IRBuilder<> IRB(M.getContext());
26 FunctionType *FnTy = FunctionType::get(IRB.getVoidTy(), false);
Devang Patelf4af8c62011-10-31 23:58:51 +000027
28 // Get the current set of static global constructors and add the new ctor
29 // to the list.
30 SmallVector<Constant *, 16> CurrentCtors;
Reid Klecknerfceb76f2014-05-16 20:39:27 +000031 StructType *EltTy;
32 if (GlobalVariable *GVCtor = M.getNamedGlobal(Array)) {
Manuel Jacob5f6eaac2016-01-16 20:30:46 +000033 ArrayType *ATy = cast<ArrayType>(GVCtor->getValueType());
Evgeniy Stepanovba6ca872016-02-12 00:37:52 +000034 StructType *OldEltTy = cast<StructType>(ATy->getElementType());
35 // Upgrade a 2-field global array type to the new 3-field format if needed.
36 if (Data && OldEltTy->getNumElements() < 3)
37 EltTy = StructType::get(IRB.getInt32Ty(), PointerType::getUnqual(FnTy),
Serge Gueltone38003f2017-05-09 19:31:13 +000038 IRB.getInt8PtrTy());
Evgeniy Stepanovba6ca872016-02-12 00:37:52 +000039 else
40 EltTy = OldEltTy;
Devang Patelf4af8c62011-10-31 23:58:51 +000041 if (Constant *Init = GVCtor->getInitializer()) {
42 unsigned n = Init->getNumOperands();
43 CurrentCtors.reserve(n + 1);
Evgeniy Stepanovba6ca872016-02-12 00:37:52 +000044 for (unsigned i = 0; i != n; ++i) {
45 auto Ctor = cast<Constant>(Init->getOperand(i));
46 if (EltTy != OldEltTy)
Serge Gueltone38003f2017-05-09 19:31:13 +000047 Ctor =
48 ConstantStruct::get(EltTy, Ctor->getAggregateElement((unsigned)0),
49 Ctor->getAggregateElement(1),
50 Constant::getNullValue(IRB.getInt8PtrTy()));
Evgeniy Stepanovba6ca872016-02-12 00:37:52 +000051 CurrentCtors.push_back(Ctor);
52 }
Devang Patelf4af8c62011-10-31 23:58:51 +000053 }
54 GVCtor->eraseFromParent();
Reid Klecknerfceb76f2014-05-16 20:39:27 +000055 } else {
Rafael Espindolab6d56a72015-12-06 16:18:25 +000056 // Use the new three-field struct if there isn't one already.
Reid Klecknerfceb76f2014-05-16 20:39:27 +000057 EltTy = StructType::get(IRB.getInt32Ty(), PointerType::getUnqual(FnTy),
Serge Gueltone38003f2017-05-09 19:31:13 +000058 IRB.getInt8PtrTy());
Devang Patelf4af8c62011-10-31 23:58:51 +000059 }
60
Reid Klecknerfceb76f2014-05-16 20:39:27 +000061 // Build a 2 or 3 field global_ctor entry. We don't take a comdat key.
62 Constant *CSVals[3];
63 CSVals[0] = IRB.getInt32(Priority);
64 CSVals[1] = F;
65 // FIXME: Drop support for the two element form in LLVM 4.0.
66 if (EltTy->getNumElements() >= 3)
Evgeniy Stepanovba6ca872016-02-12 00:37:52 +000067 CSVals[2] = Data ? ConstantExpr::getPointerCast(Data, IRB.getInt8PtrTy())
68 : Constant::getNullValue(IRB.getInt8PtrTy());
Reid Klecknerfceb76f2014-05-16 20:39:27 +000069 Constant *RuntimeCtorInit =
70 ConstantStruct::get(EltTy, makeArrayRef(CSVals, EltTy->getNumElements()));
71
Devang Patelf4af8c62011-10-31 23:58:51 +000072 CurrentCtors.push_back(RuntimeCtorInit);
73
74 // Create a new initializer.
Reid Klecknerfceb76f2014-05-16 20:39:27 +000075 ArrayType *AT = ArrayType::get(EltTy, CurrentCtors.size());
Devang Patelf4af8c62011-10-31 23:58:51 +000076 Constant *NewInit = ConstantArray::get(AT, CurrentCtors);
77
78 // Create the new global variable and replace all uses of
79 // the old global variable with the new one.
80 (void)new GlobalVariable(M, NewInit->getType(), false,
Kostya Serebryanycd1aba82011-12-15 21:59:03 +000081 GlobalValue::AppendingLinkage, NewInit, Array);
82}
83
Evgeniy Stepanovba6ca872016-02-12 00:37:52 +000084void llvm::appendToGlobalCtors(Module &M, Function *F, int Priority, Constant *Data) {
85 appendToGlobalArray("llvm.global_ctors", M, F, Priority, Data);
Kostya Serebryanycd1aba82011-12-15 21:59:03 +000086}
87
Evgeniy Stepanovba6ca872016-02-12 00:37:52 +000088void llvm::appendToGlobalDtors(Module &M, Function *F, int Priority, Constant *Data) {
89 appendToGlobalArray("llvm.global_dtors", M, F, Priority, Data);
Devang Patelf4af8c62011-10-31 23:58:51 +000090}
Rafael Espindola17600e22013-07-25 03:23:25 +000091
Evgeniy Stepanovea6d49d2016-10-25 23:53:31 +000092static void appendToUsedList(Module &M, StringRef Name, ArrayRef<GlobalValue *> Values) {
93 GlobalVariable *GV = M.getGlobalVariable(Name);
94 SmallPtrSet<Constant *, 16> InitAsSet;
95 SmallVector<Constant *, 16> Init;
96 if (GV) {
97 ConstantArray *CA = dyn_cast<ConstantArray>(GV->getInitializer());
98 for (auto &Op : CA->operands()) {
99 Constant *C = cast_or_null<Constant>(Op);
100 if (InitAsSet.insert(C).second)
101 Init.push_back(C);
102 }
103 GV->eraseFromParent();
104 }
105
106 Type *Int8PtrTy = llvm::Type::getInt8PtrTy(M.getContext());
107 for (auto *V : Values) {
108 Constant *C = ConstantExpr::getBitCast(V, Int8PtrTy);
109 if (InitAsSet.insert(C).second)
110 Init.push_back(C);
111 }
112
113 if (Init.empty())
114 return;
115
116 ArrayType *ATy = ArrayType::get(Int8PtrTy, Init.size());
117 GV = new llvm::GlobalVariable(M, ATy, false, GlobalValue::AppendingLinkage,
118 ConstantArray::get(ATy, Init), Name);
119 GV->setSection("llvm.metadata");
120}
121
122void llvm::appendToUsed(Module &M, ArrayRef<GlobalValue *> Values) {
123 appendToUsedList(M, "llvm.used", Values);
124}
125
126void llvm::appendToCompilerUsed(Module &M, ArrayRef<GlobalValue *> Values) {
127 appendToUsedList(M, "llvm.compiler.used", Values);
128}
129
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +0000130Function *llvm::checkSanitizerInterfaceFunction(Constant *FuncOrBitcast) {
131 if (isa<Function>(FuncOrBitcast))
132 return cast<Function>(FuncOrBitcast);
Matthias Braun8c209aa2017-01-28 02:02:38 +0000133 FuncOrBitcast->print(errs());
134 errs() << '\n';
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +0000135 std::string Err;
136 raw_string_ostream Stream(Err);
137 Stream << "Sanitizer interface function redefined: " << *FuncOrBitcast;
138 report_fatal_error(Err);
139}
Ismail Pazarbasi56ccf1c2015-05-06 18:48:22 +0000140
Evgeniy Stepanov039af602017-04-06 19:55:09 +0000141Function *llvm::declareSanitizerInitFunction(Module &M, StringRef InitName,
142 ArrayRef<Type *> InitArgTypes) {
143 assert(!InitName.empty() && "Expected init function name");
144 Function *F = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
145 InitName,
146 FunctionType::get(Type::getVoidTy(M.getContext()), InitArgTypes, false),
147 AttributeList()));
148 F->setLinkage(Function::ExternalLinkage);
149 return F;
150}
151
Ismail Pazarbasi56ccf1c2015-05-06 18:48:22 +0000152std::pair<Function *, Function *> llvm::createSanitizerCtorAndInitFunctions(
153 Module &M, StringRef CtorName, StringRef InitName,
Kuba Brecka45dbffd2015-07-23 10:54:06 +0000154 ArrayRef<Type *> InitArgTypes, ArrayRef<Value *> InitArgs,
155 StringRef VersionCheckName) {
Ismail Pazarbasi56ccf1c2015-05-06 18:48:22 +0000156 assert(!InitName.empty() && "Expected init function name");
Evgeniy Stepanov1bd9fc72016-10-31 22:42:39 +0000157 assert(InitArgs.size() == InitArgTypes.size() &&
Ismail Pazarbasi56ccf1c2015-05-06 18:48:22 +0000158 "Sanitizer's init function expects different number of arguments");
Evgeniy Stepanov039af602017-04-06 19:55:09 +0000159 Function *InitFunction =
160 declareSanitizerInitFunction(M, InitName, InitArgTypes);
Ismail Pazarbasi56ccf1c2015-05-06 18:48:22 +0000161 Function *Ctor = Function::Create(
162 FunctionType::get(Type::getVoidTy(M.getContext()), false),
163 GlobalValue::InternalLinkage, CtorName, &M);
164 BasicBlock *CtorBB = BasicBlock::Create(M.getContext(), "", Ctor);
165 IRBuilder<> IRB(ReturnInst::Create(M.getContext(), CtorBB));
Ismail Pazarbasi56ccf1c2015-05-06 18:48:22 +0000166 IRB.CreateCall(InitFunction, InitArgs);
Kuba Brecka45dbffd2015-07-23 10:54:06 +0000167 if (!VersionCheckName.empty()) {
168 Function *VersionCheckFunction =
169 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
170 VersionCheckName, FunctionType::get(IRB.getVoidTy(), {}, false),
Reid Klecknerb5180542017-03-21 16:57:19 +0000171 AttributeList()));
Kuba Brecka45dbffd2015-07-23 10:54:06 +0000172 IRB.CreateCall(VersionCheckFunction, {});
173 }
Ismail Pazarbasi56ccf1c2015-05-06 18:48:22 +0000174 return std::make_pair(Ctor, InitFunction);
175}
Chandler Carruth6e9bb7e2016-12-26 23:43:27 +0000176
177void llvm::filterDeadComdatFunctions(
178 Module &M, SmallVectorImpl<Function *> &DeadComdatFunctions) {
179 // Build a map from the comdat to the number of entries in that comdat we
180 // think are dead. If this fully covers the comdat group, then the entire
181 // group is dead. If we find another entry in the comdat group though, we'll
182 // have to preserve the whole group.
183 SmallDenseMap<Comdat *, int, 16> ComdatEntriesCovered;
184 for (Function *F : DeadComdatFunctions) {
185 Comdat *C = F->getComdat();
186 assert(C && "Expected all input GVs to be in a comdat!");
187 ComdatEntriesCovered[C] += 1;
188 }
189
190 auto CheckComdat = [&](Comdat &C) {
191 auto CI = ComdatEntriesCovered.find(&C);
192 if (CI == ComdatEntriesCovered.end())
193 return;
194
195 // If this could have been covered by a dead entry, just subtract one to
196 // account for it.
197 if (CI->second > 0) {
198 CI->second -= 1;
199 return;
200 }
201
202 // If we've already accounted for all the entries that were dead, the
203 // entire comdat is alive so remove it from the map.
204 ComdatEntriesCovered.erase(CI);
205 };
206
207 auto CheckAllComdats = [&] {
208 for (Function &F : M.functions())
209 if (Comdat *C = F.getComdat()) {
210 CheckComdat(*C);
211 if (ComdatEntriesCovered.empty())
212 return;
213 }
214 for (GlobalVariable &GV : M.globals())
215 if (Comdat *C = GV.getComdat()) {
216 CheckComdat(*C);
217 if (ComdatEntriesCovered.empty())
218 return;
219 }
220 for (GlobalAlias &GA : M.aliases())
221 if (Comdat *C = GA.getComdat()) {
222 CheckComdat(*C);
223 if (ComdatEntriesCovered.empty())
224 return;
225 }
226 };
227 CheckAllComdats();
228
229 if (ComdatEntriesCovered.empty()) {
230 DeadComdatFunctions.clear();
231 return;
232 }
233
234 // Remove the entries that were not covering.
235 erase_if(DeadComdatFunctions, [&](GlobalValue *GV) {
236 return ComdatEntriesCovered.find(GV->getComdat()) ==
237 ComdatEntriesCovered.end();
238 });
239}
Evgeniy Stepanov964f4662017-04-27 20:27:27 +0000240
241std::string llvm::getUniqueModuleId(Module *M) {
242 MD5 Md5;
243 bool ExportsSymbols = false;
244 auto AddGlobal = [&](GlobalValue &GV) {
245 if (GV.isDeclaration() || GV.getName().startswith("llvm.") ||
Peter Collingbourne715bcfe2017-10-05 21:54:53 +0000246 !GV.hasExternalLinkage() || GV.hasComdat())
Evgeniy Stepanov964f4662017-04-27 20:27:27 +0000247 return;
248 ExportsSymbols = true;
249 Md5.update(GV.getName());
250 Md5.update(ArrayRef<uint8_t>{0});
251 };
252
253 for (auto &F : *M)
254 AddGlobal(F);
255 for (auto &GV : M->globals())
256 AddGlobal(GV);
257 for (auto &GA : M->aliases())
258 AddGlobal(GA);
259 for (auto &IF : M->ifuncs())
260 AddGlobal(IF);
261
262 if (!ExportsSymbols)
263 return "";
264
265 MD5::MD5Result R;
266 Md5.final(R);
267
268 SmallString<32> Str;
269 MD5::stringifyResult(R, Str);
270 return ("$" + Str).str();
271}